Lettore e scrittore JPEG di casa (C1, passo 3)

Febe deve leggere e scrivere JPEG senza SkiaSharp né altri componenti
esterni (decisione del 18 novembre 2026), quindi il codec è scritto dalla
specifica ITU-T T.81.

Lettore (JpegDecoder): sequenziale di base ed esteso, progressivo (selezione
spettrale e approssimazioni successive), senza perdita (predittori 1-7),
ognuno con Huffman e con codifica aritmetica; 8 e 12 bit (senza perdita da 2
a 16); qualunque campionamento, ripristino, DNL; grigio, YCbCr, RGB, CMYK e
YCCK con il segmento Adobe. IDCT esatta e crominanza con il filtro
triangolare. EXIF, ICC a pezzi, XMP e commenti; l'orientamento EXIF va in
ImageMetadata.Orientation (anche per PNG) e non si applica ai pixel. I file
gerarchici e quelli a 2 componenti si rifiutano come formato non letto; i
dati troncati dentro una scansione sono un file danneggiato.

Scrittore (JpegEncoder): sequenziale di base, qualità 1-100 sulle tabelle
dell'allegato K, 4:2:0, 4:4:4 e grigio, intervallo di ripristino, EXIF, ICC,
XMP e commenti.

Prove: contro le letture di SkiaSharp i JPEG dell'insieme di riferimento
stanno fra 59 e 67 dB di PSNR per canale, scarto massimo 3 (soglia 40 dB e
0,1% di pixel oltre 16). Un codificatore di prova scrive gli stessi
coefficienti in progressivo, aritmetico, 12 bit, con ripristino, scansioni
separate e DNL, e il lettore deve ridarli identici; senza perdita si
confronta campione per campione. Più andata e ritorno dello scrittore, file
danneggiati e mutazioni casuali con seme fisso. La facciata ImageDecoder
ora legge i JPEG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:14:20 +01:00
1 parent 8bf76f18ff
commit 36196526bb
25 files changed
+6411 -14

No files matched your search

+1
View File
@@ -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 |
@@ -0,0 +1,79 @@
using System.Buffers.Binary;
namespace Febe.Core.Codecs.Images;
/// <summary>Reads the Orientation tag (0x0112) of the first IFD of an EXIF block (a TIFF structure).</summary>
internal static class ExifOrientation
{
private const ushort OrientationTag = 0x0112;
/// <summary>
/// The orientation 1-8 of <paramref name="tiff"/> (starting with «II*\0» or «MM\0*»), or 1 when the block has no
/// such tag, an invalid value or is damaged.
/// </summary>
public static int Read(ReadOnlySpan<byte> 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<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
private static uint U32(ReadOnlySpan<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b);
}
+3 -1
View File
@@ -7,7 +7,7 @@ namespace Febe.Core.Codecs.Images;
public static class ImageDecoder
{
/// <summary>Whether Febe has a decoder for <paramref name="format"/>.</summary>
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;
/// <summary>Size, frames and metadata of an image, without decoding the pixels.</summary>
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
@@ -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),
+9 -3
View File
@@ -1,7 +1,7 @@
namespace Febe.Core.Codecs.Images;
/// <summary>A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment).</summary>
/// <param name="Keyword">The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF comment.</param>
/// <summary>A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment; JPEG COM).</summary>
/// <param name="Keyword">The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF or JPEG comment.</param>
/// <param name="Text">The text.</param>
/// <param name="Language">The language tag of an iTXt chunk, empty otherwise.</param>
/// <param name="TranslatedKeyword">The translated keyword of an iTXt chunk, empty otherwise.</param>
@@ -16,13 +16,19 @@ public sealed class ImageMetadata
/// <summary>The EXIF block as a TIFF structure (starts with «II*\0» or «MM\0*»), or null.</summary>
public byte[]? Exif { get; init; }
/// <summary>
/// The EXIF orientation, 1-8 (T.81 has none of its own: it is the Orientation tag of <see cref="Exif"/>); 1 when the
/// image has no EXIF block, no such tag or an invalid value. The decoders never apply it to the pixels.
/// </summary>
public int Orientation { get; init; } = 1;
/// <summary>The ICC colour profile, decompressed, or null.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>The name of the ICC profile as the file gives it, or null.</summary>
public string? IccProfileName { get; init; }
/// <summary>The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG), or null.</summary>
/// <summary>The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG, the APP1 segment of a JPEG), or null.</summary>
public string? Xmp { get; init; }
/// <summary>The texts, in file order (the XMP packet is in <see cref="Xmp"/>, not here).</summary>
@@ -0,0 +1,202 @@
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
internal static class JpegArithmeticTable
{
/// <summary>Index of the fixed estimate (Qe = 0x5A1D, never adapted) used for the signs of AC coefficients.</summary>
public const byte FixedState = 113;
/// <summary>Qe of each index; entry 113 is the fixed estimate.</summary>
public static ReadOnlySpan<ushort> 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,
];
/// <summary>Next_Index_LPS of each index.</summary>
public static ReadOnlySpan<byte> 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,
];
/// <summary>Next_Index_MPS of each index.</summary>
public static ReadOnlySpan<byte> 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,
];
/// <summary>Switch_MPS of each index: 1 where an LPS inverts the sense of the MPS.</summary>
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;
/// <summary>The state of a context after coding its LPS with renormalization (T.81 D.1.5.4).</summary>
[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]);
}
/// <summary>The state of a context after coding its MPS with renormalization (T.81 D.1.5.3).</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte AfterMps(byte state) => (byte)((state & 0x80) | NextMps[state & 0x7F]);
}
/// <summary>
/// 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.
/// </summary>
internal ref struct JpegArithmeticDecoder
{
private readonly ReadOnlySpan<byte> _data;
private int _position;
private uint _c;
private int _a;
private int _ct;
public JpegArithmeticDecoder(ReadOnlySpan<byte> data, int position)
{
_data = data;
_position = position;
Initialize();
}
/// <summary>Position of the next byte not yet read.</summary>
public readonly int Position => _position;
/// <summary>Initdec (Figure D.22) at <paramref name="position"/>, for a restart interval.</summary>
public void Restart(int position)
{
_position = position;
Initialize();
}
/// <summary>Decode(S) of Figure D.16: one binary decision of context <paramref name="state"/>, updated in place.</summary>
[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;
}
/// <summary>A decision with the fixed estimate of probability one half (signs of AC coefficients).</summary>
[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;
}
/// <summary>Byte_in of Figure D.20: a stuffed 0xFF 0x00 is one 0xFF; at a marker nothing is consumed.</summary>
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;
}
}
+150
View File
@@ -0,0 +1,150 @@
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
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)
/// <summary>
/// Dequantizes a block (natural order) and writes its 8×8 samples to <paramref name="output"/>, row after row
/// <paramref name="stride"/> bytes apart. With <paramref name="precision"/> 12 the samples are 12-bit and are
/// reduced to 8 bits through <paramref name="to8Bit"/> (4096 entries); with 8 they are written as they are.
/// </summary>
public static void Inverse(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> to8Bit)
{
Span<float> 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<float> 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;
}
}
}
/// <summary>
/// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order,
/// not yet quantized.
/// </summary>
public static void Forward(ReadOnlySpan<float> samples, Span<float> coefficients)
{
Span<float> 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;
}
}
/// <summary>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.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Inverse1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span<float> 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;
}
/// <summary>Eight points of X[k] = C(k) Σ x[n] cos((2n+1)kπ/16): twice the T.81 forward transform.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Forward1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span<float> 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);
}
}
@@ -0,0 +1,95 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged
/// (<see cref="ImageDecodeException"/>), 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 <see cref="ImageFormatNotSupportedException"/>.
/// </remarks>
public static class JpegDecoder
{
/// <summary>Whether the bytes start like a JPEG file (SOI and the start of a marker).</summary>
public static bool IsJpeg(ReadOnlySpan<byte> data) => data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF;
/// <summary>Size and metadata of a JPEG, without decoding the pixels.</summary>
/// <exception cref="ImageDecodeException">The file is damaged or not a JPEG.</exception>
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Identify, readMetadata: true);
file.Run();
return file.ToInfo();
}
/// <summary>Decodes a JPEG to straight RGBA8.</summary>
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a JPEG.</exception>
/// <exception cref="ImageFormatNotSupportedException">The file uses the hierarchical process.</exception>
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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);
}
/// <summary>Decodes a JPEG to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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;
}
/// <summary>
/// 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).
/// </summary>
internal static JpegCoefficients DecodeCoefficients(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Coefficients, readMetadata: false);
file.Run();
return file.ToCoefficients();
}
}
/// <summary>The coefficients of one component, natural order inside each block, blocks row after row.</summary>
/// <param name="Id">Component identifier.</param>
/// <param name="H">Horizontal sampling factor.</param>
/// <param name="V">Vertical sampling factor.</param>
/// <param name="BlocksWide">Blocks that cover the component's samples horizontally.</param>
/// <param name="BlocksHigh">Blocks that cover the component's samples vertically.</param>
/// <param name="Stride">Blocks per row in <paramref name="Coefficients"/> (the MCU grid, at least <paramref name="BlocksWide"/>).</param>
/// <param name="Quantization">The quantization table the component used, natural order.</param>
/// <param name="Coefficients">64 coefficients per block.</param>
internal sealed record JpegComponentCoefficients(int Id, int H, int V, int BlocksWide, int BlocksHigh, int Stride, ushort[] Quantization, short[] Coefficients)
{
/// <summary>The DQT table the component refers to.</summary>
public int QuantizationTable { get; init; }
/// <summary>Rows of blocks in <see cref="Coefficients"/>.</summary>
public int StoredRows => Coefficients.Length / 64 / Stride;
/// <summary>The 64 coefficients of block (<paramref name="x"/>, <paramref name="y"/>).</summary>
public ReadOnlySpan<short> Block(int x, int y) => Coefficients.AsSpan(((y * Stride) + x) * 64, 64);
}
/// <summary>What <see cref="JpegDecoder.DecodeCoefficients"/> returns.</summary>
internal sealed record JpegCoefficients(
int FrameMarker,
int Precision,
int Width,
int Height,
int RestartInterval,
int AdobeTransform,
bool Jfif,
int ScanCount,
IReadOnlyList<JpegComponentCoefficients> Components);
+796
View File
@@ -0,0 +1,796 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>Chroma sampling of a colour JPEG.</summary>
public enum JpegSubsampling
{
/// <summary>Chroma at half width and half height (H = V = 2 for luma): the usual choice for photos.</summary>
Ratio420,
/// <summary>Chroma at full resolution.</summary>
Ratio444,
}
/// <summary>How <see cref="JpegEncoder"/> writes a file.</summary>
public sealed record JpegEncoderOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static JpegEncoderOptions Default { get; } = new();
/// <summary>Quality 1-100: the Annex K tables scaled (50 keeps them as they are).</summary>
public int Quality { get; init; } = 85;
/// <summary>Chroma sampling of a colour image.</summary>
public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Ratio420;
/// <summary>One component (luma) instead of three.</summary>
public bool Grayscale { get; init; }
/// <summary>MCUs per restart interval (DRI and RSTn markers), 0 for none.</summary>
public int RestartInterval { get; init; }
/// <summary>
/// EXIF to write in an APP1 segment: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by «Exif\0\0».
/// </summary>
public byte[]? Exif { get; init; }
/// <summary>ICC profile to write in APP2 «ICC_PROFILE» chunks.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>XMP packet to write in an APP1 segment (at most one segment: no extended XMP).</summary>
public string? Xmp { get; init; }
/// <summary>Comments to write in COM segments, UTF-8.</summary>
public IReadOnlyList<string> Comments { get; init; } = [];
}
/// <summary>
/// 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.
/// </summary>
public static class JpegEncoder
{
/// <summary>Encodes an image to a JPEG file.</summary>
public static byte[] Encode(RgbaImage image, JpegEncoderOptions? options = null)
{
var output = new JpegOutput();
Write(image, options ?? JpegEncoderOptions.Default, output);
return output.ToArray();
}
/// <summary>Encodes an image to a JPEG file written to <paramref name="output"/>.</summary>
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);
}
/// <summary>
/// The quantized coefficients the encoder would write for <paramref name="image"/>, with its frame layout: what tests
/// compare with the decoder and with other entropy codings of the same image.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
internal static JpegCoefficients TransformPlanes(
int width,
int height,
int precision,
IReadOnlyList<(int Id, int H, int V, int Table, int[] Samples)> planes,
IReadOnlyList<ushort[]> 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<float> samples = stackalloc float[64];
Span<float> 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<short> 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);
}
/// <summary>One block, baseline: DC difference (F.1.2.1) and run-length coded AC (F.1.2.2).</summary>
internal static void EncodeBlock(JpegBitWriter writer, ReadOnlySpan<short> 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);
}
}
/// <summary>The Annex K Huffman tables, built once.</summary>
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);
}
/// <summary>Components, sampling factors and quantization of the frame the encoder writes.</summary>
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; }
/// <summary>Blocks per row of the MCU grid.</summary>
public int Stride { get; }
/// <summary>Rows of blocks of the MCU grid.</summary>
public int Rows { get; }
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
}
/// <summary>Block (<paramref name="bx"/>, row <paramref name="v"/> of the strip) of component <paramref name="i"/>, quantized.</summary>
public void Quantize(int i, int bx, int v, Span<short> block)
{
Span<float> samples = stackalloc float[64];
Span<float> 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);
}
}
}
}
/// <summary>A growing byte buffer for the encoders.</summary>
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<byte> 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);
}
/// <summary>Drops bytes from the end (the trailing zeros an arithmetic coder may leave out).</summary>
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);
}
/// <summary>Writes Huffman codes and extra bits of an entropy-coded segment, stuffing a zero after each 0xFF.</summary>
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);
}
/// <summary>Symbol (run &lt;&lt; 4 | category) and the low bits of <paramref name="value"/> (F.1.2.1, F.1.2.2).</summary>
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);
}
}
/// <summary>Pads the last byte with one bits (F.1.2.3).</summary>
public void Flush()
{
if (_count > 0)
{
WriteBits((1 << (8 - _count)) - 1, 8 - _count);
}
}
}
/// <summary>Marker segments of T.81 Annex B and of JFIF, EXIF, XMP and ICC, for the encoders.</summary>
internal static class JpegSegments
{
private const int MaxPayload = 65533;
private const int IccChunk = 65519;
public static void WriteSegment(JpegOutput output, int marker, ReadOnlySpan<byte> 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<string>? comments)
{
if (exif is not null)
{
ReadOnlySpan<byte> 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));
}
}
}
/// <summary>One DQT segment with every table (8-bit entries when all fit, 16-bit otherwise), zig-zag order.</summary>
public static void WriteQuantization(JpegOutput output, IReadOnlyList<ushort[]> tables)
{
var payload = new List<byte>();
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<byte> counts, ReadOnlySpan<byte> 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);
}
}
@@ -0,0 +1,338 @@
namespace Febe.Core.Codecs.Images;
/// <summary>Arithmetic-coded scans: sequential (T.81 F.2.4), progressive (G.1.3, G.2) and lossless (H.1.2.3).</summary>
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<byte> 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<short> 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);
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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 <paramref name="context"/>, magnitude bins from <paramref name="x1"/>. The context of the next
/// difference is set from this one.
/// </summary>
private static int DecodeDifference(ref JpegArithmeticDecoder decoder, Span<byte> 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<byte> 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;
}
/// <summary>Decode the bits below the leading one of Sz (Figure F.9 reversed), all with bin <paramref name="s"/>.</summary>
private static int DecodeMagnitudeBits(ref JpegArithmeticDecoder decoder, Span<byte> 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;
}
/// <summary>AC coefficients of a sequential block or of the first scan of a band (Figure F.5, Table F.5).</summary>
private static void DecodeAcArithmetic(ref JpegArithmeticDecoder decoder, Span<byte> statistics, int kx, int ss, int se, int al, Span<short> block, ReadOnlySpan<byte> 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));
}
}
/// <summary>A later scan of successive approximation of a band (Figures G.10, G.11; Table G.2).</summary>
private static void DecodeAcRefineArithmetic(ref JpegArithmeticDecoder decoder, Span<byte> statistics, in Scan scan, Span<short> block, ReadOnlySpan<byte> 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);
}
}
@@ -0,0 +1,459 @@
namespace Febe.Core.Codecs.Images;
/// <summary>Huffman-coded scans: sequential (T.81 F.2), progressive (G.2) and lossless (H.2).</summary>
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<byte> 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<short> 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<short> block, ReadOnlySpan<byte> 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<short> block, ReadOnlySpan<byte> 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<short> block, ReadOnlySpan<byte> 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);
}
/// <summary>The predictors of T.81 H.1.2.1 and the samples they reconstruct.</summary>
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;
}
/// <summary>A restart interval starts at MCU row <paramref name="mcuRow"/>: its first line predicts like the first line of the scan.</summary>
public void Restart(int mcuRow)
{
for (var i = 0; i < _scan.Components.Length; i++)
{
_firstRow[i] = _single ? mcuRow : mcuRow * _scan.Components[i].V;
}
}
/// <summary>Whether (x, y) of component <paramref name="c"/> is on the first line of the scan or restart interval.</summary>
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);
}
/// <summary>Undoes the point transform and writes the 8-bit planes.</summary>
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);
}
}
}
}
}
@@ -0,0 +1,311 @@
using System.Buffers;
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>From the component planes to RGBA: upsampling of the chroma and colour conversion.</summary>
internal sealed partial class JpegFile
{
/// <summary>The colour space of the components, as decoders choose it (JFIF, Adobe APP14, component identifiers).</summary>
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<byte>.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<byte>.Shared.Return(buffer);
}
}
}
return image;
}
/// <summary>
/// Row <paramref name="y"/> of the image for component <paramref name="c"/>, <see cref="Width"/> 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.
/// </summary>
private ReadOnlySpan<byte> 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<byte> grey, Span<byte> 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<byte> r, ReadOnlySpan<byte> g, ReadOnlySpan<byte> b, Span<byte> 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<byte> luma, ReadOnlySpan<byte> cb, ReadOnlySpan<byte> cr, Span<byte> 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;
}
}
/// <summary>
/// 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).
/// </summary>
private static void WriteCmyk(ReadOnlySpan<byte> c0, ReadOnlySpan<byte> c1, ReadOnlySpan<byte> c2, ReadOnlySpan<byte> k, Span<byte> 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;
/// <summary>
/// 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.
/// </summary>
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];
}
}
File diff suppressed because it is too large. Load diff
+275
View File
@@ -0,0 +1,275 @@
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// A Huffman table of T.81 (Annex C): the canonical codes built from the counts per length, with a lookup of the
/// first <see cref="LookupBits"/> bits for decoding and the code of every symbol for encoding.
/// </summary>
internal sealed class JpegHuffmanTable
{
/// <summary>Bits looked up at once; longer codes take the slow path of T.81 F.2.2.3.</summary>
public const int LookupBits = 9;
private JpegHuffmanTable(byte[] counts, byte[] values)
{
Counts = counts;
Values = values;
}
/// <summary>Codes of each length 1-16.</summary>
public byte[] Counts { get; }
/// <summary>The symbols, in code order.</summary>
public byte[] Values { get; }
/// <summary>For each value of the next <see cref="LookupBits"/> bits: (length &lt;&lt; 8) | symbol, or 0.</summary>
public ushort[] Lookup { get; } = new ushort[1 << LookupBits];
/// <summary>Largest code of each length (index 1-16), -1 when there is none.</summary>
public int[] MaxCode { get; } = new int[17];
/// <summary>For each length, the index in <see cref="Values"/> of its first code minus that code.</summary>
public int[] ValueOffset { get; } = new int[17];
/// <summary>The code of each symbol (encoding).</summary>
public ushort[] Codes { get; } = new ushort[256];
/// <summary>The length of the code of each symbol, 0 when the table has no code for it (encoding).</summary>
public byte[] Sizes { get; } = new byte[256];
/// <summary>Builds a table from the 16 counts and the symbols of a DHT segment.</summary>
/// <exception cref="ImageDecodeException">The counts describe more codes than fit, or do not match the symbols.</exception>
public static JpegHuffmanTable Build(ReadOnlySpan<byte> counts, ReadOnlySpan<byte> 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;
}
}
/// <summary>
/// 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.
/// </summary>
internal ref struct JpegBitReader
{
private readonly ReadOnlySpan<byte> _data;
private int _position;
private ulong _bits;
private int _count;
private int _padBits;
public JpegBitReader(ReadOnlySpan<byte> data, int position)
{
_data = data;
_position = position;
}
/// <summary>Position of the next byte not yet read.</summary>
public readonly int Position => _position;
/// <summary>Whether the reader ran out of data (not at a marker).</summary>
public bool ReachedEnd { get; private set; }
/// <summary>Whether a decoded symbol used bits past the end of the segment.</summary>
public readonly bool UsedPadding => _padBits > _count;
/// <summary>Drops the bits of the current byte and those buffered, for a restart marker or the end of a scan.</summary>
public void Reset()
{
_bits = 0;
_count = 0;
_padBits = 0;
ReachedEnd = false;
}
/// <summary>Moves to <paramref name="position"/>, with no buffered bits.</summary>
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;
}
/// <summary>The next <paramref name="n"/> bits (0-16) as an unsigned number.</summary>
[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;
}
/// <summary>RECEIVE and EXTEND of T.81 F.2.2.1: <paramref name="s"/> bits as a signed value of category s.</summary>
[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;
}
/// <summary>Decodes one symbol with <paramref name="table"/>.</summary>
/// <exception cref="ImageDecodeException">The bits are no code of the table.</exception>
[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;
}
}
}
+136
View File
@@ -0,0 +1,136 @@
namespace Febe.Core.Codecs.Images;
/// <summary>Fixed tables of ITU-T T.81: the zig-zag order and the example tables of Annex K.</summary>
internal static class JpegTables
{
/// <summary>Coefficients in a block.</summary>
public const int BlockSize = 64;
/// <summary>
/// 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.
/// </summary>
public static readonly byte[] ZigZag = BuildZigZag();
/// <summary>T.81 Table K.1, luminance quantization, natural order.</summary>
public static ReadOnlySpan<byte> 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,
];
/// <summary>T.81 Table K.2, chrominance quantization, natural order.</summary>
public static ReadOnlySpan<byte> 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,
];
/// <summary>T.81 Table K.3 as code counts per length 1-16.</summary>
public static ReadOnlySpan<byte> LuminanceDcCounts => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
/// <summary>T.81 Table K.3 symbols.</summary>
public static ReadOnlySpan<byte> LuminanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
/// <summary>T.81 Table K.4 as code counts per length 1-16.</summary>
public static ReadOnlySpan<byte> ChrominanceDcCounts => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
/// <summary>T.81 Table K.4 symbols.</summary>
public static ReadOnlySpan<byte> ChrominanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
/// <summary>T.81 Table K.5 as code counts per length 1-16.</summary>
public static ReadOnlySpan<byte> LuminanceAcCounts => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D];
/// <summary>T.81 Table K.5 symbols (run/size), in code order.</summary>
public static ReadOnlySpan<byte> 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,
];
/// <summary>T.81 Table K.6 as code counts per length 1-16.</summary>
public static ReadOnlySpan<byte> ChrominanceAcCounts => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
/// <summary>T.81 Table K.6 symbols (run/size), in code order.</summary>
public static ReadOnlySpan<byte> 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,
];
/// <summary>
/// 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.
/// </summary>
public static ushort[] ScaledQuantization(ReadOnlySpan<byte> 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;
}
}
+1 -1
View File
@@ -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<byte> memory, ImageLimits limits, bool readMetadata)
@@ -18,6 +18,7 @@ public sealed class ImageFuzzTests
[ReferenceFormat.Png],
[ReferenceFormat.Gif],
[ReferenceFormat.Bmp],
[ReferenceFormat.Jpeg],
];
[TestMethod]
+106
View File
@@ -0,0 +1,106 @@
using System.Globalization;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>How close a lossy decode is to its reference: PSNR per channel and the share of pixels far off.</summary>
/// <param name="PsnrRed">PSNR of the red channel, dB (infinity when identical).</param>
/// <param name="PsnrGreen">PSNR of the green channel, dB.</param>
/// <param name="PsnrBlue">PSNR of the blue channel, dB.</param>
/// <param name="PsnrAlpha">PSNR of the alpha channel, dB.</param>
/// <param name="FarOff">Share (0-1) of pixels with some channel off by more than <see cref="ImageQuality.FarThreshold"/>.</param>
/// <param name="MaxDifference">Largest difference of any channel.</param>
internal sealed record ImageQualityResult(double PsnrRed, double PsnrGreen, double PsnrBlue, double PsnrAlpha, double FarOff, int MaxDifference)
{
/// <summary>The smallest PSNR of the colour channels.</summary>
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}");
}
/// <summary>Measures and orientation helpers for comparing decoded images.</summary>
internal static class ImageQuality
{
/// <summary>A pixel counts as far off when one of its channels differs by more than this.</summary>
public const int FarThreshold = 16;
/// <summary>Lossy decodes must reach this PSNR on every colour channel (SPECIFICA §14.1, proposal of C1).</summary>
public const double MinimumPsnr = 40;
/// <summary>Lossy decodes may have at most this share of pixels far off.</summary>
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<double> 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);
}
/// <summary>Asserts the thresholds of a lossy decode.</summary>
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));
/// <summary>
/// The image as it should be shown for EXIF orientation <paramref name="orientation"/> (1-8): mirrored, rotated
/// or transposed from the stored pixels.
/// </summary>
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;
}
}
+5 -5
View File
@@ -85,11 +85,11 @@ public sealed class ImagingBaseTests
[TestMethod]
public void TheFacadeSaysWhichFormatsItCannotReadYet()
{
var jpeg = ReferenceImages.Of(ReferenceFormat.Jpeg).First().ReadInput();
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(jpeg));
Assert.Contains("JPEG", error.Message);
var webp = ReferenceImages.Of(ReferenceFormat.WebP).First().ReadInput();
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(webp));
Assert.Contains("WEBP", error.Message);
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => 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));
}
}
+549
View File
@@ -0,0 +1,549 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// 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.
/// </summary>
[TestClass]
public sealed class JpegCodingTests
{
public TestContext TestContext { get; set; } = null!;
/// <summary>Images and encoder settings the cross-checks run on.</summary>
public static IEnumerable<object[]> Sources =>
[
["gradiente-420", 61, 37, JpegSubsampling.Ratio420, false],
["gradiente-444", 45, 29, JpegSubsampling.Ratio444, false],
["grigio", 33, 50, JpegSubsampling.Ratio420, true],
["riferimento-420", 0, 0, JpegSubsampling.Ratio420, false],
];
private static RgbaImage SourceImage(int width, int height)
{
if (width == 0)
{
// A real-looking picture with edges: the PNG of the reference set.
return PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput());
}
return TestImages.Gradient(width, height, width * height);
}
private static JpegEncoderOptions Settings(JpegSubsampling subsampling, bool grey, int quality = 90) =>
new() { Quality = quality, Subsampling = subsampling, Grayscale = grey };
[TestMethod]
[DynamicData(nameof(Sources))]
public void TheBaselineFileHoldsExactlyTheEncodersCoefficients(string name, int width, int height, JpegSubsampling subsampling, bool grey)
{
using var image = SourceImage(width, height);
var settings = Settings(subsampling, grey);
var expected = JpegEncoder.Transform(image, settings);
var file = JpegEncoder.Encode(image, settings);
var actual = JpegDecoder.DecodeCoefficients(file);
Assert.AreEqual(0xC0, actual.FrameMarker, name);
AssertSameCoefficients(expected, actual, name);
}
[TestMethod]
[DynamicData(nameof(Sources))]
public void EveryOtherCodingOfTheSameCoefficientsDecodesToThem(string name, int width, int height, JpegSubsampling subsampling, bool grey)
{
using var image = SourceImage(width, height);
var settings = Settings(subsampling, grey);
var coefficients = JpegEncoder.Transform(image, settings);
using var baseline = JpegDecoder.Decode(JpegEncoder.Encode(image, settings));
var count = coefficients.Components.Count;
var variants = new (string What, JpegTestOptions Options, int Marker)[]
{
("sequenziale esteso", new JpegTestOptions(), 0xC1),
("scansioni separate", new JpegTestOptions { SeparateScans = true }, 0xC1),
("ripristino ogni 3", new JpegTestOptions { RestartInterval = 3 }, 0xC1),
("altezza in DNL", new JpegTestOptions { HeightInDnl = true }, 0xC1),
("progressivo", new JpegTestOptions { Progressive = true }, 0xC2),
("progressivo con ripristino", new JpegTestOptions { Progressive = true, RestartInterval = 2 }, 0xC2),
("solo selezione spettrale", new JpegTestOptions { Progressive = true, Script = SpectralOnly(count) }, 0xC2),
("approssimazioni fini", new JpegTestOptions { Progressive = true, Script = ManyApproximations(count) }, 0xC2),
("aritmetico", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic }, 0xC9),
("aritmetico con ripristino", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 5 }, 0xC9),
("aritmetico condizionato", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, DcConditioning = (2, 4), AcConditioning = 12 }, 0xC9),
("aritmetico progressivo", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true }, 0xCA),
("aritmetico progressivo fine", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true, Script = ManyApproximations(count), RestartInterval = 4 }, 0xCA),
};
foreach (var (what, options, marker) in variants)
{
var file = JpegTestEncoder.Write(coefficients, options);
var decoded = JpegDecoder.DecodeCoefficients(file);
Assert.AreEqual(marker, decoded.FrameMarker, $"{name}, {what}");
AssertSameCoefficients(coefficients, decoded, $"{name}, {what}");
// The same coefficients make the same pixels, whatever the coding.
using var pixels = JpegDecoder.Decode(file);
ImageAssert.AreEqual(baseline, pixels, $"{name}, {what}");
TestContext.WriteLine($"{name}, {what}: {file.Length} byte");
}
}
[TestMethod]
public void TheProductionEncodersRestartIntervalsChangeNoCoefficient()
{
using var image = TestImages.Gradient(83, 51, 5);
foreach (var interval in new[] { 1, 2, 7, 100 })
{
var settings = new JpegEncoderOptions { Quality = 80, RestartInterval = interval };
var file = JpegEncoder.Encode(image, settings);
var decoded = JpegDecoder.DecodeCoefficients(file);
Assert.AreEqual(interval, decoded.RestartInterval);
AssertSameCoefficients(JpegEncoder.Transform(image, settings), decoded, $"intervallo {interval}");
var markers = CountRestartMarkers(file);
var mcus = ((83 + 15) / 16) * ((51 + 15) / 16);
Assert.AreEqual((mcus - 1) / interval, markers, $"intervallo {interval}");
}
}
public static IEnumerable<object[]> TwelveBitCases =>
[
[JpegTestCoding.Huffman, false],
[JpegTestCoding.Huffman, true],
[JpegTestCoding.Arithmetic, false],
[JpegTestCoding.Arithmetic, true],
];
[TestMethod]
[DynamicData(nameof(TwelveBitCases))]
public void TwelveBitFilesDecodeToTheirCoefficientsAndCloseToTheirSamples(JpegTestCoding coding, bool progressive)
{
const int width = 43;
const int height = 27;
var random = new Random(12);
var grey = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
grey[(y * width) + x] = Math.Clamp((x * 4095 / (width - 1)) + random.Next(-20, 21), 0, 4095);
}
}
// Fine 16-bit quantization: 12-bit coefficients need categories up to 15 (DC) and 14 (AC).
var table = Enumerable.Repeat((ushort)2, 64).ToArray();
table[0] = 1;
var coefficients = JpegEncoder.TransformPlanes(width, height, 12, [(1, 1, 1, 0, grey)], [table], 0xC1);
var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = coding, Progressive = progressive, RestartInterval = 4 });
var decoded = JpegDecoder.DecodeCoefficients(file);
Assert.AreEqual(12, decoded.Precision);
AssertSameCoefficients(coefficients, decoded, $"{coding}, progressivo {progressive}");
using var image = JpegDecoder.Decode(file);
var worst = 0;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var expected = ((grey[(y * width) + x] * 255) + 2047) / 4095;
worst = Math.Max(worst, Math.Abs(image.GetPixel(x, y).R - expected));
}
}
Assert.IsLessThanOrEqualTo(1, worst, "a 12 bit con quantizzazione fine l'errore resta sotto un livello di 8 bit");
}
public static IEnumerable<object[]> SamplingCases =>
[
["4:2:2", 2, 1],
["4:4:0", 1, 2],
["4:1:1", 4, 1],
["4:1:0", 4, 2],
["3×1 (rapporto non intero con 2×1)", 3, 1],
];
[TestMethod]
[DynamicData(nameof(SamplingCases))]
public void AnySamplingFactorsDecode(string name, int lumaH, int lumaV)
{
using var image = TestImages.Gradient(57, 41, 9);
var (yPlane, cbPlane, crPlane) = YCbCrPlanes(image);
const int width = 57;
const int height = 41;
var chromaH = name.StartsWith('3') ? 2 : 1;
var planes = new List<(int Id, int H, int V, int Table, int[] Samples)>
{
(1, lumaH, lumaV, 0, yPlane),
(2, chromaH, 1, 1, Downsample(cbPlane, width, height, lumaH, lumaV, chromaH, 1)),
(3, chromaH, 1, 1, Downsample(crPlane, width, height, lumaH, lumaV, chromaH, 1)),
};
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
var coefficients = JpegEncoder.TransformPlanes(width, height, 8, planes, [fine, fine], 0xC1);
foreach (var options in new[] { new JpegTestOptions(), new JpegTestOptions { Progressive = true, RestartInterval = 3 }, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic } })
{
var file = JpegTestEncoder.Write(coefficients, options);
AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), name);
using var decoded = JpegDecoder.Decode(file);
var quality = ImageQuality.Compare(Opaque(image), decoded);
TestContext.WriteLine($"{name}: {quality}");
// The chroma of a smooth gradient survives subsampling well; the luma is lossless but for rounding.
Assert.IsGreaterThanOrEqualTo(30, quality.MinPsnr, $"{name}: {quality}");
}
}
[TestMethod]
public void AdobeCmykAndYcckBecomeRgb()
{
using var image = TestImages.Gradient(40, 24, 3);
const int width = 40;
const int height = 24;
var c = new int[width * height];
var m = new int[width * height];
var yellow = new int[width * height];
var k = new int[width * height];
for (var i = 0; i < c.Length; i++)
{
var p = image.Pixels.Slice(i * 4, 4);
// Adobe's inverted CMYK: stored values are 255 minus the ink, so R = C × K / 255 with K = the brightest.
var key = Math.Max(p[0], Math.Max(p[1], Math.Max(p[2], (byte)1)));
k[i] = key;
c[i] = Math.Min(255, ((p[0] * 255) + (key / 2)) / key);
m[i] = Math.Min(255, ((p[1] * 255) + (key / 2)) / key);
yellow[i] = Math.Min(255, ((p[2] * 255) + (key / 2)) / key);
}
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, c), (2, 1, 1, 0, m), (3, 1, 1, 0, yellow), (4, 1, 1, 0, k)], [fine], 0xC1);
var cmykFile = JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 });
using var fromCmyk = JpegDecoder.Decode(cmykFile);
var cmykQuality = ImageQuality.Compare(Opaque(image), fromCmyk);
TestContext.WriteLine($"CMYK: {cmykQuality}");
Assert.IsGreaterThanOrEqualTo(40, cmykQuality.MinPsnr, cmykQuality.ToString());
// YCCK: the inverted C, M, Y as RGB (255 − stored), to YCbCr; K as it is.
var yy = new int[c.Length];
var cb = new int[c.Length];
var cr = new int[c.Length];
for (var i = 0; i < c.Length; i++)
{
(yy[i], cb[i], cr[i]) = ToYCbCr(255 - c[i], 255 - m[i], 255 - yellow[i]);
}
var ycck = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, yy), (2, 1, 1, 0, cb), (3, 1, 1, 0, cr), (4, 1, 1, 0, k)], [fine], 0xC1);
var ycckFile = JpegTestEncoder.Write(ycck, new JpegTestOptions { Jfif = false, AdobeTransform = 2, Progressive = true });
using var fromYcck = JpegDecoder.Decode(ycckFile);
var ycckQuality = ImageQuality.Compare(Opaque(image), fromYcck);
TestContext.WriteLine($"YCCK: {ycckQuality}");
Assert.IsGreaterThanOrEqualTo(38, ycckQuality.MinPsnr, ycckQuality.ToString());
}
[TestMethod]
public void ThreeComponentsAreRgbWithAdobeTransformZeroOrRgbIdentifiers()
{
using var image = TestImages.Gradient(24, 16, 4);
var (r, g, b) = Channels(image);
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
foreach (var (ids, adobe) in new[] { ((1, 2, 3), 0), (('R', 'G', 'B'), -1) })
{
var coefficients = JpegEncoder.TransformPlanes(24, 16, 8, [(ids.Item1, 1, 1, 0, r), (ids.Item2, 1, 1, 0, g), (ids.Item3, 1, 1, 0, b)], [fine], 0xC1);
using var decoded = JpegDecoder.Decode(JpegTestEncoder.Write(coefficients, new JpegTestOptions { Jfif = false, AdobeTransform = adobe }));
var quality = ImageQuality.Compare(Opaque(image), decoded);
Assert.IsGreaterThanOrEqualTo(45, quality.MinPsnr, quality.ToString());
}
}
public static IEnumerable<object[]> LosslessCases()
{
foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic })
{
for (var predictor = 1; predictor <= 7; predictor++)
{
yield return [coding, 8, predictor, 0, 1, 0];
}
yield return [coding, 8, 4, 2, 3, 0];
yield return [coding, 12, 7, 0, 1, 5];
yield return [coding, 16, 4, 0, 3, 0];
yield return [coding, 16, 6, 3, 1, 9];
yield return [coding, 2, 1, 0, 1, 0];
yield return [coding, 8, 5, 0, 3, 4];
}
}
[TestMethod]
[DynamicData(nameof(LosslessCases))]
public void LosslessFilesGiveBackTheirSamples(JpegTestCoding coding, int precision, int predictor, int pointTransform, int components, int restart)
{
const int width = 23;
const int height = 14;
var random = new Random((precision * 100) + predictor);
var max = (1 << precision) - 1;
var planes = new List<(int Id, int H, int V, int[] Samples)>();
for (var c = 0; c < components; c++)
{
var samples = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
// A ramp with noise, plus a hard step: large and small differences both occur.
var value = ((x + (2 * y) + (c * 7)) * max / (width + (2 * height) + 14)) + random.Next(-3, 4) + (x > 15 ? max / 3 : 0);
samples[(y * width) + x] = Math.Clamp(value, 0, max);
}
}
planes.Add(((byte)"RGB"[c % 3] + (c / 3), 1, 1, samples));
}
var options = new JpegTestOptions { Coding = coding, Jfif = false, RestartInterval = restart, DcConditioning = restart == 9 ? (1, 3) : (0, 1) };
var file = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options);
using var image = JpegDecoder.Decode(file);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var pixel = image.GetPixel(x, y);
for (var c = 0; c < 3; c++)
{
var sample = planes[components == 1 ? 0 : c].Samples[(y * width) + x];
var restored = (sample >> pointTransform) << pointTransform;
var expected = precision == 8 ? restored : (int)(((restored * 255L) + (max >> 1)) / max);
var actual = c == 0 ? pixel.R : c == 1 ? pixel.G : pixel.B;
Assert.AreEqual(expected, actual, $"({x}, {y}) canale {c}");
}
}
}
if (components == 3)
{
// The same samples as three separate scans.
var separate = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options with { SeparateScans = true });
using var again = JpegDecoder.Decode(separate);
ImageAssert.AreEqual(image, again, "scansioni separate");
}
}
[TestMethod]
public void LosslessWithSamplingFactorsAndInterleavedMcus()
{
// Grey with factors 2×2 (one component: MCU of one sample) and two components... no: three, with a 2×1 luma.
const int width = 19;
const int height = 11;
var random = new Random(4);
var luma = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray();
var chroma = Enumerable.Range(0, 10 * height).Select(_ => 128).ToArray();
var planes = new List<(int Id, int H, int V, int[] Samples)> { (1, 2, 1, luma), (2, 1, 1, chroma), (3, 1, 1, chroma) };
foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic })
{
var file = JpegTestEncoder.WriteLossless(width, height, 8, planes, 1, 0, new JpegTestOptions { Coding = coding, RestartInterval = 10 });
using var image = JpegDecoder.Decode(file);
// Neutral chroma: every pixel is grey with the luma sample.
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var expected = luma[(y * width) + x];
Assert.AreEqual(((byte)expected, (byte)expected, (byte)expected), (image.GetPixel(x, y).R, image.GetPixel(x, y).G, image.GetPixel(x, y).B), $"{coding} ({x}, {y})");
}
}
}
}
[TestMethod]
public void TheArithmeticCoderRoundTripsLongRandomDecisions()
{
// Many blocks of random coefficients exercise carries, stacked 0xFF bytes and every state of Table D.2.
var random = new Random(31);
const int width = 64;
const int height = 64;
var samples = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray();
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
var coefficients = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, samples)], [fine], 0xC9);
foreach (var progressive in new[] { false, true })
{
var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = progressive });
AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), $"progressivo {progressive}");
}
}
[TestMethod]
public void TheArithmeticTablesHaveOneEntryPerState()
{
Assert.AreEqual(114, JpegArithmeticTable.Qe.Length);
Assert.AreEqual(114, JpegArithmeticTable.NextLps.Length);
Assert.AreEqual(114, JpegArithmeticTable.NextMps.Length);
for (var i = 0; i < 113; i++)
{
Assert.IsLessThan(113, (int)JpegArithmeticTable.NextLps[i], $"stato {i}");
Assert.IsLessThan(113, (int)JpegArithmeticTable.NextMps[i], $"stato {i}");
}
// A few rows of T.81 Table D.2, checked by hand against the Recommendation.
Assert.AreEqual((0x5A1D, 1, 1, true), (JpegArithmeticTable.Qe[0], (int)JpegArithmeticTable.NextLps[0], (int)JpegArithmeticTable.NextMps[0], JpegArithmeticTable.Switches(0)));
Assert.AreEqual((0x0001, 12, 13, false), (JpegArithmeticTable.Qe[13], (int)JpegArithmeticTable.NextLps[13], (int)JpegArithmeticTable.NextMps[13], JpegArithmeticTable.Switches(13)));
Assert.AreEqual((0x002C, 33, 9, false), (JpegArithmeticTable.Qe[35], (int)JpegArithmeticTable.NextLps[35], (int)JpegArithmeticTable.NextMps[35], JpegArithmeticTable.Switches(35)));
Assert.AreEqual((0x2516, 86, 71, false), (JpegArithmeticTable.Qe[87], (int)JpegArithmeticTable.NextLps[87], (int)JpegArithmeticTable.NextMps[87], JpegArithmeticTable.Switches(87)));
Assert.AreEqual((0x59EB, 112, 111, true), (JpegArithmeticTable.Qe[112], (int)JpegArithmeticTable.NextLps[112], (int)JpegArithmeticTable.NextMps[112], JpegArithmeticTable.Switches(112)));
}
internal static void AssertSameCoefficients(JpegCoefficients expected, JpegCoefficients actual, string what)
{
Assert.AreEqual((expected.Width, expected.Height, expected.Precision), (actual.Width, actual.Height, actual.Precision), what);
Assert.HasCount(expected.Components.Count, actual.Components, what);
for (var i = 0; i < expected.Components.Count; i++)
{
var e = expected.Components[i];
var a = actual.Components[i];
Assert.AreEqual((e.Id, e.H, e.V, e.BlocksWide, e.BlocksHigh), (a.Id, a.H, a.V, a.BlocksWide, a.BlocksHigh), $"{what}, componente {i}");
CollectionAssert.AreEqual(e.Quantization, a.Quantization, $"{what}, quantizzazione {i}");
for (var by = 0; by < e.BlocksHigh; by++)
{
for (var bx = 0; bx < e.BlocksWide; bx++)
{
var eb = e.Block(bx, by);
var ab = a.Block(bx, by);
if (!eb.SequenceEqual(ab))
{
var k = 0;
while (eb[k] == ab[k])
{
k++;
}
Assert.Fail($"{what}: componente {i}, blocco ({bx}, {by}), coefficiente {k}: atteso {eb[k]}, letto {ab[k]}.");
}
}
}
}
}
private static int CountRestartMarkers(byte[] file)
{
var count = 0;
for (var i = 0; i + 1 < file.Length; i++)
{
if (file[i] == 0xFF && file[i + 1] is >= 0xD0 and <= 0xD7)
{
count++;
}
}
return count;
}
private static IReadOnlyList<JpegTestScan> SpectralOnly(int count)
{
var all = Enumerable.Range(0, count).ToArray();
var scans = new List<JpegTestScan> { new(all, 0, 0, 0, 0) };
foreach (var c in all)
{
scans.Add(new([c], 1, 1, 0, 0));
scans.Add(new([c], 2, 9, 0, 0));
scans.Add(new([c], 10, 63, 0, 0));
}
return scans;
}
private static IReadOnlyList<JpegTestScan> ManyApproximations(int count)
{
var all = Enumerable.Range(0, count).ToArray();
var scans = new List<JpegTestScan> { new(all, 0, 0, 0, 4) };
for (var al = 3; al >= 0; al--)
{
scans.Add(new(all, 0, 0, al + 1, al));
}
foreach (var c in all)
{
scans.Add(new([c], 1, 63, 0, 5));
for (var al = 4; al >= 0; al--)
{
scans.Add(new([c], 1, 63, al + 1, al));
}
}
return scans;
}
private static RgbaImage Opaque(RgbaImage image)
{
var copy = new RgbaImage(image.Width, image.Height, image.ToArray());
var pixels = copy.Pixels;
for (var i = 3; i < pixels.Length; i += 4)
{
pixels[i] = 255;
}
return copy;
}
private static (int[] R, int[] G, int[] B) Channels(RgbaImage image)
{
var n = image.Width * image.Height;
var r = new int[n];
var g = new int[n];
var b = new int[n];
for (var i = 0; i < n; i++)
{
r[i] = image.Pixels[i * 4];
g[i] = image.Pixels[(i * 4) + 1];
b[i] = image.Pixels[(i * 4) + 2];
}
return (r, g, b);
}
private static (int Y, int Cb, int Cr) ToYCbCr(int r, int g, int b) =>
(
Math.Clamp((int)Math.Round((0.299 * r) + (0.587 * g) + (0.114 * b)), 0, 255),
Math.Clamp((int)Math.Round((-0.168736 * r) - (0.331264 * g) + (0.5 * b) + 128), 0, 255),
Math.Clamp((int)Math.Round((0.5 * r) - (0.418688 * g) - (0.081312 * b) + 128), 0, 255));
private static (int[] Y, int[] Cb, int[] Cr) YCbCrPlanes(RgbaImage image)
{
var (r, g, b) = Channels(image);
var y = new int[r.Length];
var cb = new int[r.Length];
var cr = new int[r.Length];
for (var i = 0; i < r.Length; i++)
{
(y[i], cb[i], cr[i]) = ToYCbCr(r[i], g[i], b[i]);
}
return (y, cb, cr);
}
/// <summary>A full-resolution plane averaged down to a component with factors (h, v) of a frame with maxima (maxH, maxV).</summary>
private static int[] Downsample(int[] plane, int width, int height, int maxH, int maxV, int h, int v)
{
var cw = ((width * h) + maxH - 1) / maxH;
var ch = ((height * v) + maxV - 1) / maxV;
var result = new int[cw * ch];
for (var y = 0; y < ch; y++)
{
for (var x = 0; x < cw; x++)
{
var sum = 0;
var count = 0;
for (var sy = y * maxV / v; sy < Math.Min(height, (y + 1) * maxV / v); sy++)
{
for (var sx = x * maxH / h; sx < Math.Min(width, (x + 1) * maxH / h); sx++)
{
sum += plane[(sy * width) + sx];
count++;
}
}
result[(y * cw) + x] = count == 0 ? 128 : (sum + (count / 2)) / count;
}
}
return result;
}
}
@@ -0,0 +1,275 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The in-house baseline JPEG encoder: the files it writes read back close to the source with our decoder, quality
/// moves size and fidelity the right way, metadata (EXIF, ICC in chunks, XMP, comments) survives the round trip, and
/// what cannot be written is refused.
/// </summary>
[TestClass]
public sealed class JpegEncoderTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheAnnexKTablesAreComplete()
{
Assert.AreEqual(12, Sum(JpegTables.LuminanceDcCounts));
Assert.AreEqual(12, Sum(JpegTables.ChrominanceDcCounts));
Assert.AreEqual(162, Sum(JpegTables.LuminanceAcCounts));
Assert.AreEqual(162, Sum(JpegTables.ChrominanceAcCounts));
Assert.HasCount(162, JpegTables.LuminanceAcValues);
Assert.HasCount(162, JpegTables.ChrominanceAcValues);
// Every (run, size) pair with size 1..10, plus EOB and ZRL: the full AC alphabet.
var expected = new HashSet<byte> { 0x00, 0xF0 };
for (var run = 0; run < 16; run++)
{
for (var size = 1; size <= 10; size++)
{
expected.Add((byte)((run << 4) | size));
}
}
Assert.IsTrue(expected.SetEquals(JpegTables.LuminanceAcValues.ToArray()));
Assert.IsTrue(expected.SetEquals(JpegTables.ChrominanceAcValues.ToArray()));
// Zig-zag is a permutation that starts 0, 1, 8, 16, 9, 2 and ends at 63.
var zigzag = JpegTables.ZigZag.ToArray();
CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), zigzag.Select(v => (int)v).ToArray());
CollectionAssert.AreEqual(new[] { 0, 1, 8, 16, 9, 2 }, zigzag.Take(6).Select(v => (int)v).ToArray());
Assert.AreEqual(63, (int)zigzag[63]);
}
[TestMethod]
public void QualityScalesTheStandardTables()
{
var at50 = JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 50);
CollectionAssert.AreEqual(JpegTables.LuminanceQuantization.ToArray().Select(v => (int)v).ToArray(), at50.Select(v => (int)v).ToArray());
Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 100).All(v => v == 1));
Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.ChrominanceQuantization, 1).All(v => v == 255));
// 16 at q50 becomes (16 × 20 + 50) / 100 = 3 at q90.
Assert.AreEqual(3, (int)JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 90)[0]);
}
public static IEnumerable<object[]> RoundTrips =>
[
[JpegSubsampling.Ratio420, false, 90, 38.0],
[JpegSubsampling.Ratio444, false, 90, 40.0],
[JpegSubsampling.Ratio444, false, 100, 48.0],
[JpegSubsampling.Ratio420, true, 85, 40.0],
];
[TestMethod]
[DynamicData(nameof(RoundTrips))]
public void EncodedImagesReadBackCloseToTheSource(JpegSubsampling subsampling, bool grey, int quality, double minimum)
{
using var source = Opaque(TestImages.Gradient(97, 61, 21), grey);
var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = subsampling, Grayscale = grey });
Assert.IsTrue(JpegDecoder.IsJpeg(file));
using var decoded = JpegDecoder.Decode(file, out var info);
Assert.AreEqual((97, 61, false, ImageFormat.Jpeg), (info.Width, info.Height, info.HasAlpha, info.Format));
var result = ImageQuality.Compare(source, decoded);
TestContext.WriteLine($"{subsampling}, grigio {grey}, q{quality}: {file.Length} byte, {result}");
Assert.IsGreaterThanOrEqualTo(minimum, result.MinPsnr, result.ToString());
Assert.AreEqual(0.0, result.FarOff, result.ToString());
}
[TestMethod]
public void HigherQualityMeansLargerFilesAndCloserPixels()
{
using var source = Opaque(PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput()), false);
var lastSize = 0;
var lastPsnr = 0.0;
foreach (var quality in new[] { 10, 30, 50, 75, 90, 100 })
{
// 4:4:4: the image is pixel-level noise in blue, which 4:2:0 cannot keep at any quality.
var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = JpegSubsampling.Ratio444 });
using var decoded = JpegDecoder.Decode(file);
var result = ImageQuality.Compare(source, decoded);
TestContext.WriteLine($"q{quality}: {file.Length} byte, {result}");
Assert.IsGreaterThan(lastSize, file.Length, $"q{quality}");
Assert.IsGreaterThan(lastPsnr, result.MinPsnr, $"q{quality}");
lastSize = file.Length;
lastPsnr = result.MinPsnr;
}
}
[TestMethod]
public void TheReferenceImagesSurviveReEncoding()
{
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
{
using var original = JpegDecoder.Decode(reference.ReadInput());
var file = JpegEncoder.Encode(original, new JpegEncoderOptions { Quality = 100, Subsampling = JpegSubsampling.Ratio444 });
using var again = JpegDecoder.Decode(file);
var result = ImageQuality.Compare(original, again);
TestContext.WriteLine($"{reference.Name}: {result}");
ImageQuality.AssertClose(result, reference.Name);
}
}
[TestMethod]
public void TinyAndOddSizesWork()
{
foreach (var (width, height) in new[] { (1, 1), (1, 17), (17, 1), (8, 8), (9, 9), (15, 16), (16, 15), (33, 7) })
{
using var source = Opaque(TestImages.Gradient(width, height, width + height), false);
foreach (var subsampling in new[] { JpegSubsampling.Ratio420, JpegSubsampling.Ratio444 })
{
var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = 100, Subsampling = subsampling });
using var decoded = JpegDecoder.Decode(file);
Assert.AreEqual((width, height), (decoded.Width, decoded.Height));
var result = ImageQuality.Compare(source, decoded);
if (subsampling == JpegSubsampling.Ratio444)
{
Assert.IsLessThanOrEqualTo(8, result.MaxDifference, $"{width}×{height} {subsampling}: {result}");
}
else
{
// The source has per-pixel noise: averaged chroma loses some of it.
Assert.IsGreaterThanOrEqualTo(25, result.MinPsnr, $"{width}×{height} {subsampling}: {result}");
}
}
}
}
[TestMethod]
public void RestartIntervalsDoNotChangeThePixels()
{
using var source = Opaque(TestImages.Gradient(70, 45, 8), false);
using var plain = JpegDecoder.Decode(JpegEncoder.Encode(source));
foreach (var interval in new[] { 1, 3, 65535 })
{
using var restarted = JpegDecoder.Decode(JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = interval }));
ImageAssert.AreEqual(plain, restarted, $"intervallo {interval}");
}
}
[TestMethod]
public void TheStreamOverloadWritesTheSameBytes()
{
using var source = TestImages.Gradient(20, 20, 1);
using var stream = new MemoryStream();
JpegEncoder.Encode(source, stream);
CollectionAssert.AreEqual(JpegEncoder.Encode(source), stream.ToArray());
}
[TestMethod]
public void MetadataSurvivesTheRoundTrip()
{
using var source = TestImages.Gradient(30, 20, 2);
var exif = Tiff(orientation: 6);
var random = new Random(66);
var icc = new byte[150_000];
random.NextBytes(icc);
"acsp"u8.CopyTo(icc.AsSpan(36));
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF/></x:xmpmeta>";
var options = new JpegEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp, Comments = ["primo commento", "secondo, con àccenti"] };
var file = JpegEncoder.Encode(source, options);
// 150 000 bytes need three APP2 chunks of at most 65 519.
Assert.AreEqual(3, CountSegments(file, 0xE2));
var info = JpegDecoder.Identify(file);
CollectionAssert.AreEqual(exif, info.Metadata.Exif);
Assert.AreEqual(6, info.Metadata.Orientation);
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
Assert.AreEqual(xmp, info.Metadata.Xmp);
CollectionAssert.AreEqual(new[] { "primo commento", "secondo, con àccenti" }, info.Metadata.Texts.Select(t => t.Text).ToArray());
// The orientation is reported, not applied: the pixels keep their stored layout.
using var decoded = JpegDecoder.Decode(file);
Assert.AreEqual((30, 20), (decoded.Width, decoded.Height));
Assert.IsGreaterThan(30, ImageQuality.Compare(Opaque(source, false), decoded).MinPsnr);
// Without metadata only JFIF is written.
var bare = JpegDecoder.Identify(JpegEncoder.Encode(source));
Assert.IsNull(bare.Metadata.Exif);
Assert.IsNull(bare.Metadata.IccProfile);
Assert.IsNull(bare.Metadata.Xmp);
Assert.IsEmpty(bare.Metadata.Texts);
Assert.AreEqual(1, bare.Metadata.Orientation);
}
[TestMethod]
public void WhatCannotBeWrittenIsRefused()
{
using var source = TestImages.Gradient(8, 8, 1);
foreach (var quality in new[] { 0, -5, 101 })
{
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality }), $"qualità {quality}");
}
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = -1 }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = 65536 }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = "non TIFF"u8.ToArray() }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = Tiff(1, padding: 70_000) }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Xmp = new string('x', 70_000) }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { IccProfile = new byte[256 * 65519] }));
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Comments = [new string('c', 70_000)] }));
}
private static byte[] Tiff(int orientation, int padding = 0)
{
// Little-endian TIFF header, IFD0 at 8 with one entry: Orientation (0x0112), SHORT, count 1.
var tiff = new byte[8 + 2 + 12 + 4 + padding];
"II*\0"u8.CopyTo(tiff);
tiff[4] = 8;
tiff[8] = 1;
tiff[10] = 0x12;
tiff[11] = 0x01;
tiff[12] = 3;
tiff[14] = 1;
tiff[18] = (byte)orientation;
return tiff;
}
private static int CountSegments(byte[] file, int marker)
{
var count = 0;
var pos = 2;
while (pos + 4 <= file.Length && file[pos] == 0xFF && file[pos + 1] != 0xDA)
{
if (file[pos + 1] == marker)
{
count++;
}
pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]);
}
return count;
}
private static int Sum(ReadOnlySpan<byte> counts)
{
var sum = 0;
foreach (var c in counts)
{
sum += c;
}
return sum;
}
/// <summary>The image with alpha 255 (JPEG has none) and, for grey, R = G = B.</summary>
private static RgbaImage Opaque(RgbaImage image, bool grey)
{
var pixels = image.ToArray();
for (var i = 0; i < pixels.Length; i += 4)
{
if (grey)
{
var y = (byte)(((pixels[i] * 299) + (pixels[i + 1] * 587) + (pixels[i + 2] * 114) + 500) / 1000);
pixels[i] = pixels[i + 1] = pixels[i + 2] = y;
}
pixels[i + 3] = 255;
}
return new RgbaImage(image.Width, image.Height, pixels);
}
}
@@ -0,0 +1,353 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI,
/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way.
/// </summary>
[TestClass]
public sealed class JpegMalformedTests
{
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
private static byte[] Baseline(int width = 37, int height = 21, int restart = 0) =>
JpegEncoder.Encode(TestImages.Gradient(width, height, 3), new JpegEncoderOptions { Quality = 80, RestartInterval = restart });
[TestMethod]
public void ABaselineFileCutInsideItsScanIsDamaged()
{
foreach (var restart in new[] { 0, 2 })
{
var file = Baseline(restart: restart);
// Identify needs the headers up to the frame, not the scan.
var sof = SegmentOffset(file, 0xC0);
var frameEnd = sof + 2 + ((file[sof + 2] << 8) | file[sof + 3]);
using var whole = JpegDecoder.Decode(file);
for (var length = 0; length < file.Length - 2; length++)
{
var cut = file[..length];
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte");
if (length < frameEnd)
{
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Identify(cut), $"Identify, {length} byte");
}
}
// Only the EOI missing: complete scans are accepted.
using var withoutEoi = JpegDecoder.Decode(file[..^2]);
ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}");
}
}
[TestMethod]
public void BytesAfterTheEndAreIgnored()
{
var file = Baseline();
using var whole = JpegDecoder.Decode(file);
var random = new Random(5);
var tail = new byte[300];
random.NextBytes(tail);
byte[] longer = [.. file, .. tail];
using var withTail = JpegDecoder.Decode(longer);
ImageAssert.AreEqual(whole, withTail, "byte dopo EOI");
}
[TestMethod]
public void FillBytesAndGarbageBetweenSegmentsAreSkipped()
{
var file = Baseline();
using var whole = JpegDecoder.Decode(file);
var dqt = SegmentOffset(file, 0xDB);
// T.81 B.1.1.2: any marker may be preceded by fill bytes 0xFF.
byte[] padded = [.. file[..dqt], 0xFF, 0xFF, 0xFF, .. file[dqt..]];
using var filled = JpegDecoder.Decode(padded);
ImageAssert.AreEqual(whole, filled, "byte di riempimento");
}
[TestMethod]
public void WithoutDhtTheAnnexKTablesAreUsed()
{
// Motion JPEG frames omit DHT and rely on the tables of Annex K, which are the ones our encoder writes.
var file = Baseline();
using var whole = JpegDecoder.Decode(file);
var stripped = RemoveSegments(file, 0xC4);
Assert.IsLessThan(file.Length, stripped.Length);
using var decoded = JpegDecoder.Decode(stripped);
ImageAssert.AreEqual(whole, decoded, "senza DHT");
}
[TestMethod]
public void HierarchicalAndTwoComponentFilesAreNotSupported()
{
var file = Baseline();
foreach (var marker in new byte[] { 0xC5, 0xC6, 0xC7, 0xCD, 0xCE, 0xCF })
{
var changed = file.ToArray();
changed[SegmentOffset(file, 0xC0) + 1] = marker;
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(changed), $"SOF 0x{marker:X2}");
}
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
var samples = new int[16 * 16];
var two = JpegEncoder.TransformPlanes(16, 16, 8, [(1, 1, 1, 0, samples), (2, 1, 1, 0, samples)], [fine], 0xC1);
var twoFile = JpegTestEncoder.Write(two, new JpegTestOptions());
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(twoFile));
}
[TestMethod]
public void DamagedHeadersAreRefused()
{
var file = Baseline();
var sof = SegmentOffset(file, 0xC0);
var sos = SegmentOffset(file, 0xDA);
// Width 0.
var zeroWidth = file.ToArray();
zeroWidth[sof + 7] = 0;
zeroWidth[sof + 8] = 0;
AssertDamaged(zeroWidth, "larghezza 0");
// Height 0 and no DNL segment after the first scan.
var zeroHeight = file.ToArray();
zeroHeight[sof + 5] = 0;
zeroHeight[sof + 6] = 0;
AssertDamaged(zeroHeight, "altezza 0 senza DNL");
// Precision 7.
var precision = file.ToArray();
precision[sof + 4] = 7;
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(precision), "precisione 7");
// Sampling factor 0 and 5.
foreach (var factor in new byte[] { 0x01, 0x10, 0x51, 0x15 })
{
var sampling = file.ToArray();
sampling[sof + 11] = factor;
AssertDamaged(sampling, $"campionamento 0x{factor:X2}");
}
// A scan naming a component the frame does not have.
var unknown = file.ToArray();
unknown[sos + 5] = 99;
AssertDamaged(unknown, "componente sconosciuto");
// A scan referring to a Huffman table that was never defined (slot 3).
var table = file.ToArray();
table[sos + 6] = 0x33;
AssertDamaged(table, "tabella di Huffman assente");
// No quantization table.
AssertDamaged(RemoveSegments(file, 0xDB), "senza DQT");
// A Huffman table with more codes than its lengths allow (two codes of length 1, then more).
var dht = SegmentOffset(file, 0xC4);
var badTable = file.ToArray();
badTable[dht + 5] = 3;
AssertDamaged(badTable, "tabella di Huffman impossibile");
// A segment length that runs past the end.
var longSegment = file.ToArray();
longSegment[sof + 2] = 0xFF;
AssertDamaged(longSegment, "segmento oltre la fine");
// No SOI, no frame, no scan.
AssertDamaged(file[2..], "senza SOI");
AssertDamaged([0xFF, 0xD8, 0xFF, 0xD9], "solo SOI ed EOI");
AssertDamaged(file[..sos], "senza scansioni");
}
[TestMethod]
public void TheLimitsAreEnforcedBeforeDecoding()
{
var file = Baseline(200, 150);
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 }));
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 }));
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWorkingBytes = 40_000 }));
// A header claiming 65535 × 65535 is refused at once, not after allocating.
var huge = file.ToArray();
var sof = SegmentOffset(file, 0xC0);
huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF;
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(huge, Small));
}
[TestMethod]
public void AnIccProfileWithAMissingChunkIsDropped()
{
var icc = new byte[140_000];
new Random(8).NextBytes(icc);
var file = JpegEncoder.Encode(TestImages.Gradient(10, 10, 1), new JpegEncoderOptions { IccProfile = icc });
CollectionAssert.AreEqual(icc, JpegDecoder.Identify(file).Metadata.IccProfile);
// Remove the second of three APP2 chunks.
var second = SegmentOffsets(file, 0xE2)[1];
var length = (file[second + 2] << 8) | file[second + 3];
byte[] missing = [.. file[..second], .. file[(second + 2 + length)..]];
Assert.IsNull(JpegDecoder.Identify(missing).Metadata.IccProfile);
using var image = JpegDecoder.Decode(missing);
Assert.AreEqual(10, image.Width);
}
[TestMethod]
public void OtherFormatsAreNotJpeg()
{
var png = ReferenceImages.Of(ReferenceFormat.Png).First().ReadInput();
Assert.IsFalse(JpegDecoder.IsJpeg(png));
Assert.IsFalse(JpegDecoder.IsJpeg([0xFF, 0xD8]));
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(png));
}
[TestMethod]
public void ChangedBytesInEveryCodingNeverBreakTheDecoder()
{
using var image = TestImages.Gradient(45, 30, 6);
var coefficients = JpegEncoder.Transform(image, new JpegEncoderOptions { Quality = 75 });
var lossless = new List<(int Id, int H, int V, int[] Samples)>
{
(1, 2, 2, Enumerable.Range(0, 45 * 30).Select(i => i % 251).ToArray()),
(2, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 13).ToArray()),
(3, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 7).ToArray()),
};
var files = new (string Name, byte[] File)[]
{
("progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Progressive = true, RestartInterval = 3 })),
("aritmetico", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 4 })),
("aritmetico progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true })),
("DNL", JpegTestEncoder.Write(coefficients, new JpegTestOptions { HeightInDnl = true })),
("senza perdita", JpegTestEncoder.WriteLossless(45, 30, 8, lossless, 4, 0, new JpegTestOptions { RestartInterval = 7 })),
("senza perdita aritmetico", JpegTestEncoder.WriteLossless(45, 30, 12, lossless, 7, 1, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic })),
};
var random = new Random(2026);
foreach (var (name, file) in files)
{
using (JpegDecoder.Decode(file, Small))
{
}
for (var i = 0; i < 150; i++)
{
var mutated = Mutate(file, random);
TryDecode(mutated, $"{name}, modifica {i}");
}
// Every cut of the file, as the network would leave it.
for (var length = 0; length < file.Length; length += 1 + (file.Length / 200))
{
TryDecode(file[..length], $"{name}, {length} byte");
}
}
}
private static void TryDecode(byte[] bytes, string what)
{
try
{
using var decoded = JpegDecoder.Decode(bytes, Small);
Assert.IsGreaterThan(0, decoded.Width, what);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
try
{
JpegDecoder.Identify(bytes, Small);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
private static byte[] Mutate(byte[] original, Random random)
{
var bytes = original.ToArray();
switch (random.Next(3))
{
case 0:
for (var k = random.Next(1, 9); k > 0; k--)
{
bytes[random.Next(2, bytes.Length)] = (byte)random.Next(256);
}
return bytes;
case 1:
// Headers: the first segments hold the tables and the frame.
bytes[random.Next(2, Math.Min(bytes.Length, 700))] = (byte)(random.Next(3) switch { 0 => 0, 1 => 0xFF, _ => random.Next(256) });
return bytes;
default:
var start = random.Next(2, bytes.Length);
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
for (var k = 0; k < length; k++)
{
bytes[start + k] ^= 0x5A;
}
return bytes;
}
}
private static void AssertDamaged(byte[] file, string what)
{
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(file), what);
Assert.IsNotInstanceOfType<ImageLimitException>(error, what);
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what);
}
/// <summary>Offset of the first marker segment of type <paramref name="marker"/> (the 0xFF byte).</summary>
private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0];
private static List<int> SegmentOffsets(byte[] file, int marker)
{
var found = new List<int>();
var pos = 2;
while (pos + 4 <= file.Length && file[pos] == 0xFF)
{
if (file[pos + 1] == marker)
{
found.Add(pos);
}
if (file[pos + 1] == 0xDA)
{
break;
}
pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]);
}
return found;
}
private static byte[] RemoveSegments(byte[] file, int marker)
{
var result = new List<byte>(file.Length);
result.AddRange(file.AsSpan(0, 2));
var pos = 2;
while (file[pos + 1] != 0xDA)
{
var length = 2 + ((file[pos + 2] << 8) | file[pos + 3]);
if (file[pos + 1] != marker)
{
result.AddRange(file.AsSpan(pos, length));
}
pos += length;
}
result.AddRange(file.AsSpan(pos));
return [.. result];
}
}
@@ -0,0 +1,56 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The in-house JPEG decoder against the SkiaSharp (libjpeg-turbo) reads of the reference set. JPEG is lossy and two
/// correct decoders differ by the rounding of their IDCT and upsampling, so the comparison has thresholds instead of
/// equality: every colour channel at least <see cref="ImageQuality.MinimumPsnr"/> dB and at most
/// <see cref="ImageQuality.MaximumFarOff"/> of the pixels off by more than <see cref="ImageQuality.FarThreshold"/>.
/// </summary>
[TestClass]
public sealed class JpegReferenceTests
{
public TestContext TestContext { get; set; } = null!;
public static IEnumerable<object[]> JpegCases => ReferenceImages.NamesOf(ReferenceFormat.Jpeg);
[TestMethod]
[DynamicData(nameof(JpegCases))]
public void TheJpegDecoderIsCloseToTheReference(string name)
{
var reference = ReferenceImages.Get(name);
var input = reference.ReadInput();
using var stored = JpegDecoder.Decode(input, out var info);
Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (stored.Width, stored.Height), name);
Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, name);
Assert.IsTrue(stored.IsOpaque(), name);
using var shown = ImageQuality.Orient(stored, info.Metadata.Orientation);
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
var result = ImageQuality.Compare(expected, shown);
TestContext.WriteLine($"{name}: {result}");
ImageQuality.AssertClose(result, name);
}
[TestMethod]
public void TheFacadeReadsJpegAndIdentifyAgreesWithDecode()
{
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
{
var input = reference.ReadInput();
using var viaFacade = ImageDecoder.Decode(input);
using var direct = JpegDecoder.Decode(input, pooled: true);
ImageAssert.AreEqual(direct, viaFacade, reference.Name);
var info = ImageDecoder.Identify(input);
Assert.AreEqual((ImageFormat.Jpeg, reference.StoredWidth, reference.StoredHeight, 1, false), (info.Format, info.Width, info.Height, info.FrameCount, info.HasAlpha), reference.Name);
Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, reference.Name);
if (reference.Orientation != 1)
{
Assert.IsNotNull(info.Metadata.Exif, reference.Name);
Assert.IsTrue(info.Metadata.Exif.AsSpan().StartsWith("II*\0"u8) || info.Metadata.Exif.AsSpan().StartsWith("MM\0*"u8), reference.Name);
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -64,6 +64,12 @@ public sealed class ReferenceDecodeTests
continue;
}
if (reference.Format == ReferenceFormat.Jpeg)
{
// Lossy: JpegReferenceTests compares it with thresholds, and with the EXIF orientation applied.
continue;
}
using var image = ImageDecoder.Decode(input);
using var expectedImage = PngDecoder.Decode(reference.ReadExpectedPng());
ImageAssert.AreEqual(expectedImage, image, reference.Name);
@@ -66,8 +66,10 @@ Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up,
fotogramma l'immagine attesa è trasparente (0, 0, 0, 0).
- Alfa non premoltiplicata: per i PNG il colore sotto un'alfa 0 resta quello del file.
- JPEG e WebP con perdita: l'immagine attesa è la lettura di libjpeg-turbo e libwebp dentro SkiaSharp (IDCT,
ricampionamento della crominanza, conversione dei colori). Il nostro lettore potrà differire di poco: la tolleranza
la fissano le prove di quei lettori. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte.
ricampionamento della crominanza, conversione dei colori). Il nostro lettore può differire di poco: per JPEG la
tolleranza è almeno 40 dB di PSNR per canale e al più lo 0,1% dei pixel con uno scarto oltre 16 (il lettore di casa
sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). PNG, GIF, BMP e WebP senza perdita devono coincidere
byte per byte.
## Che cosa qui non c'è
@@ -91,7 +93,12 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
- `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG
di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato,
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per JPEG e
WebP dice che non li legge ancora.
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per WebP
dice che non lo legge ancora; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal
passo 3), che applica anche l'orientamento EXIF riportato dal lettore.
- `Imaging/JpegCodingTests.cs`, `JpegEncoderTests.cs`, `JpegMalformedTests.cs` (dal passo 3): i casi qui assenti
(progressivo, ripristino, codifica aritmetica, 12 bit, senza perdita, CMYK e YCCK, campionamenti insoliti) scritti
dal codificatore di prova `JpegTestEncoder.cs` e confrontati coefficiente per coefficiente con la codifica di base
delle stesse immagini; il codificatore di casa; i file danneggiati.
- `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini
come binarie e tiene `elenco.txt` con le righe Unix.