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:
1 parent
8bf76f18ff
commit
36196526bb
25 files changed
+6411
-14
No files matched your search
@@ -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);
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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 << 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
@@ -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 << 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user