Lettore e scrittore WebP di casa (C1, passo 4)

Il lettore WebP, scritto dalla RFC 9649 e dalla RFC 6386, prende il posto di
SkiaSharp per i WebP: VP8 con perdita, VP8L senza perdita, ALPH grezzo e
compresso con ogni filtro, VP8X con ICCP, EXIF e XMP, e di un'animazione il
primo fotogramma fuso sulla tela, con il numero dei fotogrammi. La facciata
ImageDecoder ora legge i WebP.

Contro i riferimenti di SkiaSharp i quattro WebP senza perdita coincidono byte
per byte; i quattro con perdita stanno fra 68,7 e 74,4 dB per canale, scarto
massimo 1, alfa esatta. File danneggiati, tagliati o fuori dai limiti si
rifiutano; i limiti si controllano prima di allocare.

Lo scrittore fa WebP senza perdita (tavolozza, sottrazione del verde,
predittore, trasformata del colore, LZ77, cache dei colori, Huffman) e il
formato esteso solo quando ci sono metadati: i 57 riferimenti tornano esatti e
pesano l'88% del PNG di casa. Niente componenti esterni.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 15:01:47 +01:00
1 parent 36196526bb
commit b4383a6110
21 files changed
+6637 -13

No files matched your search

+3 -1
View File
@@ -7,7 +7,7 @@ namespace Febe.Core.Codecs.Images;
public static class ImageDecoder
{
/// <summary>Whether Febe has a decoder for <paramref name="format"/>.</summary>
public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Jpeg 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 or ImageFormat.WebP;
/// <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>
@@ -19,6 +19,7 @@ public static class ImageDecoder
ImageFormat.Jpeg => JpegDecoder.Identify(data, limits),
ImageFormat.Gif => GifDecoder.Identify(data, limits),
ImageFormat.Bmp => BmpDecoder.Identify(data, limits),
ImageFormat.WebP => WebPDecoder.Identify(data, limits),
var other => throw NotSupported(other),
};
@@ -33,6 +34,7 @@ public static class ImageDecoder
ImageFormat.Jpeg => JpegDecoder.Decode(data, limits, pooled),
ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled),
ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled),
ImageFormat.WebP => WebPDecoder.Decode(data, limits, pooled),
var other => throw NotSupported(other),
};
@@ -0,0 +1,131 @@
using System.Numerics;
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// The boolean entropy decoder of VP8 (RFC 6386 §7): each call decodes one bit whose probability of being 0 is
/// <c>prob</c>/256. The bytes are loaded several at a time into a 64-bit window; past the end of the data the decoder
/// reads zeros and counts them, so a caller can tell a stream that was cut short.
/// </summary>
internal struct Vp8BoolDecoder
{
private readonly byte[] _data;
private readonly int _end;
private int _pos;
// The bits loaded and not yet consumed: the low 8 + _bits bits of _value; the top 8 of them are the window that
// is compared with the split.
private ulong _value;
private int _bits;
private uint _range;
private int _padding;
public Vp8BoolDecoder(byte[] data, int start, int length)
{
_data = data;
_pos = start;
_end = start + length;
_value = 0;
_bits = -8;
_range = 255;
_padding = 0;
Fill();
}
/// <summary>
/// Whether the decoder needed bytes past the end of its data. A stream that ends cleanly never does; one byte of
/// tolerance is given to writers that flush a little short.
/// </summary>
public readonly bool Overrun => _padding > 1;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetBit(int prob)
{
if (_bits < 0)
{
Fill();
}
var split = 1 + (((_range - 1) * (uint)prob) >> 8);
var window = (uint)(_value >> _bits);
int bit;
if (window >= split)
{
_range -= split;
_value -= (ulong)split << _bits;
bit = 1;
}
else
{
_range = split;
bit = 0;
}
var shift = BitOperations.LeadingZeroCount(_range) - 24;
_range <<= shift;
_bits -= shift;
return bit;
}
/// <summary>An unsigned value of <paramref name="bits"/> bits, most significant first, each with probability ½ (L(n)).</summary>
public int GetLiteral(int bits)
{
var v = 0;
while (bits-- > 0)
{
v = (v << 1) | GetBit(128);
}
return v;
}
/// <summary>A magnitude of <paramref name="bits"/> bits followed by a sign bit, as the frame header writes deltas.</summary>
public int GetSignedLiteral(int bits)
{
var v = GetLiteral(bits);
return GetBit(128) == 1 ? -v : v;
}
/// <summary>An optional signed delta: a flag, then <see cref="GetSignedLiteral"/>; 0 when the flag is clear.</summary>
public int GetOptionalSigned(int bits) => GetBit(128) == 1 ? GetSignedLiteral(bits) : 0;
/// <summary>
/// A value read with a tree of RFC 6386 §8.1: pairs of children, a child ≤ 0 being the leaf −value; the
/// probability of node pair i is <c>probs[offset + i/2]</c>.
/// </summary>
public int ReadTree(ReadOnlySpan<sbyte> tree, ReadOnlySpan<byte> probs, int offset = 0)
{
var i = 0;
do
{
i = tree[i + GetBit(probs[offset + (i >> 1)])];
}
while (i > 0);
return -i;
}
private void Fill()
{
while (_bits <= 40)
{
if (_pos < _end)
{
_value = (_value << 8) | _data[_pos++];
_bits += 8;
}
else
{
if (_bits < 0)
{
_value <<= 8;
_bits += 8;
_padding++;
}
return;
}
}
}
}
+862
View File
@@ -0,0 +1,862 @@
using System.Buffers;
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// Decodes a VP8 key frame (RFC 6386), the lossy picture of a WebP file: frame header, segmentation, the intra modes of
/// every macroblock, the DCT tokens of the partitions, dequantization, the inverse WHT and DCT, intra prediction, the
/// simple or normal loop filter, then YUV 4:2:0 to RGB (BT.601) with the chroma upsampled by the triangular filter
/// ("fancy upsampling"). Alpha is not part of VP8: the pixels come out opaque.
/// </summary>
/// <remarks>
/// Intra prediction reads the reconstructed pixels before the loop filter (as RFC 6386 §15 prescribes), so the whole
/// frame is reconstructed first and filtered afterwards, macroblock after macroblock in raster order.
/// </remarks>
internal sealed class Vp8Decoder
{
private const int WorkStride = 32;
private const int ChromaWorkStride = 16;
private readonly byte[] _data;
private readonly int _start;
private readonly int _length;
private readonly ImageLimits _limits;
private int _width;
private int _height;
private int _mbWidth;
private int _mbHeight;
// Header.
private bool _segmentation;
private bool _updateMap;
private bool _absoluteDeltas;
private readonly int[] _segmentQuant = new int[4];
private readonly int[] _segmentFilter = new int[4];
private readonly byte[] _segmentProbs = [255, 255, 255];
private bool _simpleFilter;
private int _filterLevel;
private int _sharpness;
private bool _useLfDelta;
private readonly int[] _refLfDelta = new int[4];
private readonly int[] _modeLfDelta = new int[4];
private bool _useSkipProb;
private int _skipProb;
private readonly byte[] _probs = new byte[Vp8Tables.CoefficientProbCount];
// Dequantization factors per segment: Y1 DC, Y1 AC, Y2 DC, Y2 AC, UV DC, UV AC.
private readonly int[] _dequant = new int[4 * 6];
// Loop filter parameters per segment and per "is B_PRED": edge limit, interior limit, high edge variance threshold.
private readonly int[] _filterParams = new int[4 * 2 * 3];
private Vp8BoolDecoder[] _partitions = [];
// Planes, macroblock aligned.
private byte[] _y = [];
private byte[] _u = [];
private byte[] _v = [];
private int _yStride;
private int _uvStride;
// Per macroblock state for the loop filter: segment, B_PRED, inner edges.
private byte[] _mbSegment = [];
private byte[] _mbFlags = [];
// Contexts.
private byte[] _intraTop = [];
private readonly byte[] _intraLeft = new byte[4];
private byte[] _nzTop = [];
private readonly byte[] _nzLeft = new byte[9];
// Current macroblock.
private int _segment;
private bool _isI4x4;
private int _yMode;
private int _uvMode;
private readonly byte[] _bModes = new byte[16];
private readonly short[] _coeffs = new short[25 * 16];
private readonly byte[] _blockData = new byte[24];
private readonly byte[] _yWork = new byte[WorkStride * 17];
private readonly byte[] _uWork = new byte[ChromaWorkStride * 9];
private readonly byte[] _vWork = new byte[ChromaWorkStride * 9];
private Vp8Decoder(byte[] data, int start, int length, ImageLimits limits)
{
_data = data;
_start = start;
_length = length;
_limits = limits;
}
/// <summary>The size of a VP8 key frame, after checking its frame tag and start code.</summary>
/// <exception cref="ImageDecodeException">The bytes are not a VP8 key frame that can be shown.</exception>
public static (int Width, int Height) ReadSize(ReadOnlySpan<byte> frame)
{
if (frame.Length < 10)
{
throw new ImageDecodeException("WebP troncato: l'intestazione del fotogramma VP8 è incompleta.");
}
var tag = frame[0] | (frame[1] << 8) | (frame[2] << 16);
if ((tag & 1) != 0)
{
throw new ImageDecodeException("WebP danneggiato: il fotogramma VP8 non è un fotogramma chiave.");
}
if (((tag >> 1) & 7) > 3)
{
throw new ImageDecodeException("WebP danneggiato: versione VP8 sconosciuta.");
}
if (((tag >> 4) & 1) == 0)
{
throw new ImageDecodeException("WebP danneggiato: il fotogramma VP8 è segnato come da non mostrare.");
}
if (frame[3] != 0x9D || frame[4] != 0x01 || frame[5] != 0x2A)
{
throw new ImageDecodeException("WebP danneggiato: manca il codice d'inizio del fotogramma VP8.");
}
var width = (frame[6] | (frame[7] << 8)) & 0x3FFF;
var height = (frame[8] | (frame[9] << 8)) & 0x3FFF;
if (width == 0 || height == 0)
{
throw new ImageDecodeException("WebP danneggiato: il fotogramma VP8 ha misura nulla.");
}
if ((tag >> 5) > frame.Length - 10)
{
throw new ImageDecodeException("WebP troncato: la prima partizione VP8 finisce oltre i dati.");
}
return (width, height);
}
/// <summary>
/// Decodes the VP8 frame in <paramref name="data"/>[<paramref name="start"/>..+<paramref name="length"/>] into
/// <paramref name="target"/>, which must have the frame's size; every alpha byte is set to 255.
/// </summary>
public static void Decode(byte[] data, int start, int length, ImageLimits limits, RgbaImage target)
{
var (width, height) = ReadSize(data.AsSpan(start, length));
if (target.Width != width || target.Height != height)
{
throw new ArgumentException("The target does not have the size of the frame.", nameof(target));
}
var decoder = new Vp8Decoder(data, start, length, limits) { _width = width, _height = height };
try
{
decoder.Run(target);
}
finally
{
decoder.Release();
}
}
/// <summary>
/// The Y, U and V planes of a frame after the loop filter, macroblock aligned (for tests of prediction and
/// filtering, which the RGB conversion would blur).
/// </summary>
internal static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) DecodePlanes(byte[] data, int start, int length, ImageLimits limits)
{
var (width, height) = ReadSize(data.AsSpan(start, length));
var decoder = new Vp8Decoder(data, start, length, limits) { _width = width, _height = height };
try
{
decoder.DecodeFrame();
var luma = decoder._yStride * decoder._mbHeight * 16;
var chroma = decoder._uvStride * decoder._mbHeight * 8;
return (decoder._y.AsSpan(0, luma).ToArray(), decoder._u.AsSpan(0, chroma).ToArray(), decoder._v.AsSpan(0, chroma).ToArray(), decoder._yStride, decoder._uvStride);
}
finally
{
decoder.Release();
}
}
private void Run(RgbaImage target)
{
DecodeFrame();
WriteRgba(target);
}
private void DecodeFrame()
{
_mbWidth = (_width + 15) >> 4;
_mbHeight = (_height + 15) >> 4;
_yStride = _mbWidth * 16;
_uvStride = _mbWidth * 8;
var lumaBytes = (long)_yStride * _mbHeight * 16;
_limits.CheckWorkingBytes((lumaBytes * 3 / 2) + ((long)_mbWidth * _mbHeight * 2) + (_mbWidth * 13L));
var tag = _data[_start] | (_data[_start + 1] << 8) | (_data[_start + 2] << 16);
var firstSize = tag >> 5;
var header = new Vp8BoolDecoder(_data, _start + 10, firstSize);
ParseHeader(ref header);
SetUpPartitions(_start + 10 + firstSize, _length - 10 - firstSize);
var pool = ArrayPool<byte>.Shared;
_y = pool.Rent((int)lumaBytes);
_u = pool.Rent((int)(lumaBytes / 4));
_v = pool.Rent((int)(lumaBytes / 4));
_mbSegment = pool.Rent(_mbWidth * _mbHeight);
_mbFlags = pool.Rent(_mbWidth * _mbHeight);
_intraTop = pool.Rent(_mbWidth * 4);
_nzTop = pool.Rent(_mbWidth * 9);
_intraTop.AsSpan(0, _mbWidth * 4).Fill(Vp8Tables.BDc);
_nzTop.AsSpan(0, _mbWidth * 9).Clear();
for (var mbY = 0; mbY < _mbHeight; mbY++)
{
ref var tokens = ref _partitions[mbY & (_partitions.Length - 1)];
_intraLeft.AsSpan().Fill(Vp8Tables.BDc);
_nzLeft.AsSpan().Clear();
for (var mbX = 0; mbX < _mbWidth; mbX++)
{
var skip = ParseModes(ref header, mbX);
var nonZero = !skip && ParseResiduals(ref tokens, mbX);
if (skip)
{
SkipResiduals(mbX);
}
var index = (mbY * _mbWidth) + mbX;
_mbSegment[index] = (byte)_segment;
_mbFlags[index] = (byte)((_isI4x4 ? 1 : 0) | (_isI4x4 || nonZero ? 2 : 0));
Reconstruct(mbX, mbY, nonZero);
}
if (header.Overrun || tokens.Overrun)
{
throw new ImageDecodeException("WebP troncato: i dati VP8 finiscono prima dell'ultimo macroblocco.");
}
}
Vp8LoopFilter.Apply(this);
}
private void Release()
{
var pool = ArrayPool<byte>.Shared;
foreach (var array in new[] { _y, _u, _v, _mbSegment, _mbFlags, _intraTop, _nzTop })
{
if (array.Length > 0)
{
pool.Return(array);
}
}
_y = _u = _v = _mbSegment = _mbFlags = _intraTop = _nzTop = [];
}
private void ParseHeader(ref Vp8BoolDecoder br)
{
br.GetBit(128); // colour space: only 0 (YUV) is defined, and decoders ignore it
br.GetBit(128); // clamping type: clamping is always done
_segmentation = br.GetBit(128) == 1;
if (_segmentation)
{
_updateMap = br.GetBit(128) == 1;
var updateData = br.GetBit(128) == 1;
if (updateData)
{
_absoluteDeltas = br.GetBit(128) == 1;
for (var s = 0; s < 4; s++)
{
_segmentQuant[s] = br.GetOptionalSigned(7);
}
for (var s = 0; s < 4; s++)
{
_segmentFilter[s] = br.GetOptionalSigned(6);
}
}
if (_updateMap)
{
for (var i = 0; i < 3; i++)
{
_segmentProbs[i] = br.GetBit(128) == 1 ? (byte)br.GetLiteral(8) : (byte)255;
}
}
}
_simpleFilter = br.GetBit(128) == 1;
_filterLevel = br.GetLiteral(6);
_sharpness = br.GetLiteral(3);
_useLfDelta = br.GetBit(128) == 1;
if (_useLfDelta && br.GetBit(128) == 1)
{
for (var i = 0; i < 4; i++)
{
if (br.GetBit(128) == 1)
{
_refLfDelta[i] = br.GetSignedLiteral(6);
}
}
for (var i = 0; i < 4; i++)
{
if (br.GetBit(128) == 1)
{
_modeLfDelta[i] = br.GetSignedLiteral(6);
}
}
}
var partitionCount = 1 << br.GetLiteral(2);
_partitions = new Vp8BoolDecoder[partitionCount];
var baseQ = br.GetLiteral(7);
var yDc = br.GetOptionalSigned(4);
var y2Dc = br.GetOptionalSigned(4);
var y2Ac = br.GetOptionalSigned(4);
var uvDc = br.GetOptionalSigned(4);
var uvAc = br.GetOptionalSigned(4);
for (var s = 0; s < 4; s++)
{
var q = !_segmentation ? baseQ : _absoluteDeltas ? _segmentQuant[s] : baseQ + _segmentQuant[s];
var d = _dequant.AsSpan(s * 6, 6);
d[0] = Vp8Tables.DcQuant[QIndex(q + yDc)];
d[1] = Vp8Tables.AcQuant[QIndex(q)];
d[2] = Vp8Tables.DcQuant[QIndex(q + y2Dc)] * 2;
d[3] = Math.Max(8, Vp8Tables.AcQuant[QIndex(q + y2Ac)] * 155 / 100);
d[4] = Math.Min(132, (int)Vp8Tables.DcQuant[QIndex(q + uvDc)]);
d[5] = Vp8Tables.AcQuant[QIndex(q + uvAc)];
}
br.GetBit(128); // refresh_entropy_probs: there is no later frame to keep them for
Vp8Tables.DefaultCoefficientProbs.CopyTo(_probs);
var update = Vp8Tables.CoefficientUpdateProbs;
for (var i = 0; i < _probs.Length; i++)
{
if (br.GetBit(update[i]) == 1)
{
_probs[i] = (byte)br.GetLiteral(8);
}
}
_useSkipProb = br.GetBit(128) == 1;
_skipProb = _useSkipProb ? br.GetLiteral(8) : 0;
if (br.Overrun)
{
throw new ImageDecodeException("WebP troncato: l'intestazione VP8 finisce prima del tempo.");
}
ComputeFilterParams();
}
private static int QIndex(int q) => Math.Clamp(q, 0, 127);
private void ComputeFilterParams()
{
for (var s = 0; s < 4; s++)
{
var baseLevel = !_segmentation ? _filterLevel : _absoluteDeltas ? _segmentFilter[s] : _filterLevel + _segmentFilter[s];
for (var i4x4 = 0; i4x4 < 2; i4x4++)
{
var level = baseLevel;
if (_useLfDelta)
{
level += _refLfDelta[0];
if (i4x4 == 1)
{
level += _modeLfDelta[0];
}
}
level = Math.Clamp(level, 0, 63);
var p = _filterParams.AsSpan(((s * 2) + i4x4) * 3, 3);
if (level == 0)
{
p.Clear();
continue;
}
var interior = level;
if (_sharpness > 0)
{
interior >>= _sharpness > 4 ? 2 : 1;
interior = Math.Min(interior, 9 - _sharpness);
}
interior = Math.Max(interior, 1);
p[0] = (2 * level) + interior;
p[1] = interior;
p[2] = level >= 40 ? 2 : level >= 15 ? 1 : 0;
}
}
}
private void SetUpPartitions(int start, int length)
{
var count = _partitions.Length;
var sizesLength = 3 * (count - 1);
if (length < sizesLength)
{
throw new ImageDecodeException("WebP troncato: mancano le misure delle partizioni VP8.");
}
var pos = start + sizesLength;
var left = length - sizesLength;
for (var i = 0; i < count; i++)
{
int size;
if (i < count - 1)
{
var at = start + (3 * i);
size = _data[at] | (_data[at + 1] << 8) | (_data[at + 2] << 16);
if (size > left)
{
throw new ImageDecodeException("WebP troncato: una partizione VP8 finisce oltre i dati.");
}
}
else
{
size = left;
}
_partitions[i] = new Vp8BoolDecoder(_data, pos, size);
pos += size;
left -= size;
}
}
// Reads the segment, skip flag and modes of a macroblock from the first partition; returns the skip flag.
private bool ParseModes(ref Vp8BoolDecoder br, int mbX)
{
if (_updateMap)
{
_segment = br.GetBit(_segmentProbs[0]) == 0 ? br.GetBit(_segmentProbs[1]) : 2 + br.GetBit(_segmentProbs[2]);
}
else
{
_segment = 0;
}
var skip = _useSkipProb && br.GetBit(_skipProb) == 1;
var top = _intraTop.AsSpan(mbX * 4, 4);
_isI4x4 = br.GetBit(145) == 0;
if (!_isI4x4)
{
_yMode = br.GetBit(156) == 1
? (br.GetBit(128) == 1 ? Vp8Tables.TmPred : Vp8Tables.HPred)
: (br.GetBit(163) == 1 ? Vp8Tables.VPred : Vp8Tables.DcPred);
var implied = (byte)(_yMode switch
{
Vp8Tables.VPred => Vp8Tables.BVe,
Vp8Tables.HPred => Vp8Tables.BHe,
Vp8Tables.TmPred => Vp8Tables.BTm,
_ => Vp8Tables.BDc,
});
top.Fill(implied);
_intraLeft.AsSpan().Fill(implied);
}
else
{
_yMode = Vp8Tables.BPred;
var probs = Vp8Tables.KeyFrameBModeProbs;
for (var row = 0; row < 4; row++)
{
for (var col = 0; col < 4; col++)
{
var mode = br.ReadTree(Vp8Tables.BModeTree, probs, ((top[col] * Vp8Tables.NumBModes) + _intraLeft[row]) * 9);
top[col] = (byte)mode;
_intraLeft[row] = (byte)mode;
_bModes[(row * 4) + col] = (byte)mode;
}
}
}
_uvMode = br.GetBit(142) == 0 ? Vp8Tables.DcPred
: br.GetBit(114) == 0 ? Vp8Tables.VPred
: br.GetBit(183) == 1 ? Vp8Tables.TmPred : Vp8Tables.HPred;
return skip;
}
private void SkipResiduals(int mbX)
{
var top = _nzTop.AsSpan(mbX * 9, 9);
top[..8].Clear();
_nzLeft.AsSpan(0, 8).Clear();
if (!_isI4x4)
{
top[8] = 0;
_nzLeft[8] = 0;
}
_blockData.AsSpan().Clear();
}
// Reads the DCT tokens of a macroblock, dequantized, into _coeffs; returns whether any block has data.
private bool ParseResiduals(ref Vp8BoolDecoder br, int mbX)
{
var coeffs = _coeffs.AsSpan();
coeffs.Clear();
var top = _nzTop.AsSpan(mbX * 9, 9);
var left = _nzLeft.AsSpan();
var q = _dequant.AsSpan(_segment * 6, 6);
var any = false;
int first;
int yType;
if (!_isI4x4)
{
var dc = coeffs.Slice(24 * 16, 16);
var nz = GetCoefficients(ref br, 1, top[8] + left[8], 0, q[2], q[3], dc);
top[8] = left[8] = (byte)(nz > 0 ? 1 : 0);
Vp8Transforms.InverseWht(dc, coeffs);
first = 1;
yType = 0;
}
else
{
first = 0;
yType = 3;
}
for (var row = 0; row < 4; row++)
{
for (var col = 0; col < 4; col++)
{
var block = coeffs.Slice(((row * 4) + col) * 16, 16);
var nz = GetCoefficients(ref br, yType, top[col] + left[row], first, q[0], q[1], block);
var flag = nz > first;
top[col] = left[row] = (byte)(flag ? 1 : 0);
var data = nz > 1 ? 2 : block[0] != 0 ? 1 : 0;
_blockData[(row * 4) + col] = (byte)data;
any |= data != 0;
}
}
for (var plane = 0; plane < 2; plane++)
{
for (var row = 0; row < 2; row++)
{
for (var col = 0; col < 2; col++)
{
var index = 16 + (plane * 4) + (row * 2) + col;
var block = coeffs.Slice(index * 16, 16);
var t = 4 + (plane * 2) + col;
var l = 4 + (plane * 2) + row;
var nz = GetCoefficients(ref br, 2, top[t] + left[l], 0, q[4], q[5], block);
top[t] = left[l] = (byte)(nz > 0 ? 1 : 0);
var data = nz > 1 ? 2 : nz == 1 ? 1 : 0;
_blockData[index] = (byte)data;
any |= data != 0;
}
}
}
return any;
}
// RFC 6386 §13: the tokens of one block, from position `first`; returns the position after the last token read
// that was not an end of block (`first` when the block is empty).
private int GetCoefficients(ref Vp8BoolDecoder br, int type, int context, int first, int dcQuant, int acQuant, Span<short> block)
{
var probs = _probs;
var typeBase = type * 8 * 3 * 11;
var bands = Vp8Tables.Bands;
var zigzag = Vp8Tables.Zigzag;
var n = first;
var p = typeBase + (((bands[n] * 3) + context) * 11);
while (n < 16)
{
if (br.GetBit(probs[p]) == 0)
{
return n; // end of block
}
while (br.GetBit(probs[p + 1]) == 0)
{
// DCT_0: the next token cannot be an end of block.
if (++n == 16)
{
return 16;
}
p = typeBase + (bands[n] * 3 * 11);
}
int value;
int next;
if (br.GetBit(probs[p + 2]) == 0)
{
value = 1;
next = 1;
}
else
{
value = LargeValue(ref br, probs.AsSpan(p, 11));
next = 2;
}
if (br.GetBit(128) == 1)
{
value = -value;
}
block[zigzag[n]] = (short)Math.Clamp(value * (n > 0 ? acQuant : dcQuant), short.MinValue, short.MaxValue);
n++;
p = typeBase + (((bands[n] * 3) + next) * 11);
}
return 16;
}
// The tokens above DCT_1 (RFC 6386 §13.2): DCT_2 to DCT_4 and the categories with their extra bits.
private static int LargeValue(ref Vp8BoolDecoder br, ReadOnlySpan<byte> p)
{
if (br.GetBit(p[3]) == 0)
{
return br.GetBit(p[4]) == 0 ? 2 : 3 + br.GetBit(p[5]);
}
if (br.GetBit(p[6]) == 0)
{
if (br.GetBit(p[7]) == 0)
{
return 5 + br.GetBit(159); // DCT_CAT1
}
var v = 7 + (2 * br.GetBit(165)); // DCT_CAT2
return v + br.GetBit(145);
}
var high = br.GetBit(p[8]);
var low = br.GetBit(p[9 + high]);
var category = (2 * high) + low;
var extra = category switch
{
0 => Vp8Tables.Cat3,
1 => Vp8Tables.Cat4,
2 => Vp8Tables.Cat5,
_ => Vp8Tables.Cat6,
};
var value = 0;
foreach (var prob in extra)
{
value = (value << 1) | br.GetBit(prob);
}
return value + 3 + (8 << category);
}
private void Reconstruct(int mbX, int mbY, bool hasCoefficients)
{
LoadEdges(mbX, mbY);
var y = _yWork.AsSpan();
var coeffs = _coeffs.AsSpan();
if (_isI4x4)
{
// Subblocks of the right column use the pixels above-right of the macroblock in every row.
var topRight = y.Slice(17, 4);
topRight.CopyTo(y.Slice((4 * WorkStride) + 17, 4));
topRight.CopyTo(y.Slice((8 * WorkStride) + 17, 4));
topRight.CopyTo(y.Slice((12 * WorkStride) + 17, 4));
for (var b = 0; b < 16; b++)
{
var at = ((1 + ((b >> 2) * 4)) * WorkStride) + 1 + ((b & 3) * 4);
Vp8Predict.Sub4x4(y, at, WorkStride, _bModes[b]);
if (hasCoefficients)
{
Vp8Transforms.AddBlock(coeffs.Slice(b * 16, 16), _blockData[b], y, at, WorkStride);
}
}
}
else
{
Vp8Predict.Block(y, WorkStride + 1, WorkStride, 16, _yMode, mbX > 0, mbY > 0);
if (hasCoefficients)
{
for (var b = 0; b < 16; b++)
{
var at = ((1 + ((b >> 2) * 4)) * WorkStride) + 1 + ((b & 3) * 4);
Vp8Transforms.AddBlock(coeffs.Slice(b * 16, 16), _blockData[b], y, at, WorkStride);
}
}
}
Vp8Predict.Block(_uWork, ChromaWorkStride + 1, ChromaWorkStride, 8, _uvMode, mbX > 0, mbY > 0);
Vp8Predict.Block(_vWork, ChromaWorkStride + 1, ChromaWorkStride, 8, _uvMode, mbX > 0, mbY > 0);
if (hasCoefficients)
{
for (var b = 0; b < 4; b++)
{
var at = ((1 + ((b >> 1) * 4)) * ChromaWorkStride) + 1 + ((b & 1) * 4);
Vp8Transforms.AddBlock(coeffs.Slice((16 + b) * 16, 16), _blockData[16 + b], _uWork, at, ChromaWorkStride);
Vp8Transforms.AddBlock(coeffs.Slice((20 + b) * 16, 16), _blockData[20 + b], _vWork, at, ChromaWorkStride);
}
}
StoreBlock(_yWork, WorkStride, 16, _y, _yStride, mbX * 16, mbY * 16);
StoreBlock(_uWork, ChromaWorkStride, 8, _u, _uvStride, mbX * 8, mbY * 8);
StoreBlock(_vWork, ChromaWorkStride, 8, _v, _uvStride, mbX * 8, mbY * 8);
}
// Fills the row above (with the above-left pixel and, for luma, four above-right pixels) and the column to the
// left of the work buffers: neighbouring pixels where they exist, 127 above the frame and 129 left of it.
private void LoadEdges(int mbX, int mbY)
{
LoadEdges(_yWork, WorkStride, 16, _y, _yStride, mbX, mbY, topRight: true);
LoadEdges(_uWork, ChromaWorkStride, 8, _u, _uvStride, mbX, mbY, topRight: false);
LoadEdges(_vWork, ChromaWorkStride, 8, _v, _uvStride, mbX, mbY, topRight: false);
}
private void LoadEdges(byte[] work, int workStride, int size, byte[] plane, int stride, int mbX, int mbY, bool topRight)
{
var x = mbX * size;
var y = mbY * size;
var extra = topRight ? 4 : 0;
if (mbY == 0)
{
work.AsSpan(0, 1 + size + extra).Fill(127);
}
else
{
var above = (y - 1) * stride;
work[0] = mbX > 0 ? plane[above + x - 1] : (byte)129;
plane.AsSpan(above + x, size).CopyTo(work.AsSpan(1, size));
if (topRight)
{
if (mbX < _mbWidth - 1)
{
plane.AsSpan(above + x + size, 4).CopyTo(work.AsSpan(1 + size, 4));
}
else
{
work.AsSpan(1 + size, 4).Fill(plane[above + x + size - 1]);
}
}
}
for (var r = 0; r < size; r++)
{
work[((r + 1) * workStride)] = mbX > 0 ? plane[((y + r) * stride) + x - 1] : (byte)129;
}
}
private static void StoreBlock(byte[] work, int workStride, int size, byte[] plane, int stride, int x, int y)
{
for (var r = 0; r < size; r++)
{
work.AsSpan(((r + 1) * workStride) + 1, size).CopyTo(plane.AsSpan(((y + r) * stride) + x, size));
}
}
// YUV 4:2:0 to RGBA, BT.601 with the studio range of VP8; each chroma sample is interpolated from the four
// nearest with weights 9, 3, 3, 1 (chroma sited between the luma samples, edges replicated).
private void WriteRgba(RgbaImage target)
{
var width = _width;
var height = _height;
var chromaWidth = (width + 1) >> 1;
var chromaHeight = (height + 1) >> 1;
var pool = ArrayPool<int>.Shared;
var rowU = pool.Rent(chromaWidth);
var rowV = pool.Rent(chromaWidth);
try
{
for (var y = 0; y < height; y++)
{
var cy = y >> 1;
var cy2 = (y & 1) == 1 ? Math.Min(cy + 1, chromaHeight - 1) : Math.Max(cy - 1, 0);
var u0 = _u.AsSpan(cy * _uvStride, chromaWidth);
var u1 = _u.AsSpan(cy2 * _uvStride, chromaWidth);
var v0 = _v.AsSpan(cy * _uvStride, chromaWidth);
var v1 = _v.AsSpan(cy2 * _uvStride, chromaWidth);
var ru = rowU.AsSpan(0, chromaWidth);
var rv = rowV.AsSpan(0, chromaWidth);
for (var i = 0; i < chromaWidth; i++)
{
ru[i] = (3 * u0[i]) + u1[i];
rv[i] = (3 * v0[i]) + v1[i];
}
var luma = _y.AsSpan(y * _yStride, width);
var output = target.GetRow(y);
for (var x = 0; x < width; x++)
{
var cx = x >> 1;
var cx2 = (x & 1) == 1 ? Math.Min(cx + 1, chromaWidth - 1) : Math.Max(cx - 1, 0);
var u = ((3 * ru[cx]) + ru[cx2] + 8) >> 4;
var v = ((3 * rv[cx]) + rv[cx2] + 8) >> 4;
YuvToRgb.Write(luma[x], u, v, output.Slice(x * 4, 4));
}
}
}
finally
{
pool.Return(rowU);
pool.Return(rowV);
}
}
// Accessors for the loop filter.
internal int MbWidth => _mbWidth;
internal int MbHeight => _mbHeight;
internal bool SimpleFilter => _simpleFilter;
internal byte[] YPlane => _y;
internal byte[] UPlane => _u;
internal byte[] VPlane => _v;
internal int YStride => _yStride;
internal int UvStride => _uvStride;
/// <summary>Edge limit, interior limit and threshold for a macroblock, and whether its inner edges are filtered.</summary>
internal (int Limit, int Interior, int HevThreshold, bool Inner) FilterOf(int mbIndex)
{
var flags = _mbFlags[mbIndex];
var p = _filterParams.AsSpan(((_mbSegment[mbIndex] * 2) + (flags & 1)) * 3, 3);
return (p[0], p[1], p[2], (flags & 2) != 0);
}
}
/// <summary>BT.601 YUV (studio range) to RGB in 16-bit fixed point.</summary>
internal static class YuvToRgb
{
private static readonly int[] YTerm = Table(i => (76309 * (i - 16)) + 32768);
private static readonly int[] RFromV = Table(i => 104597 * (i - 128));
private static readonly int[] GFromU = Table(i => -25675 * (i - 128));
private static readonly int[] GFromV = Table(i => -53279 * (i - 128));
private static readonly int[] BFromU = Table(i => 132201 * (i - 128));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(int y, int u, int v, Span<byte> rgba)
{
var yy = YTerm[y];
rgba[0] = Clamp((yy + RFromV[v]) >> 16);
rgba[1] = Clamp((yy + GFromU[u] + GFromV[v]) >> 16);
rgba[2] = Clamp((yy + BFromU[u]) >> 16);
rgba[3] = 255;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte Clamp(int v) => (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
private static int[] Table(Func<int, int> f)
{
var table = new int[256];
for (var i = 0; i < 256; i++)
{
table[i] = f(i);
}
return table;
}
}
+692
View File
@@ -0,0 +1,692 @@
using System.Buffers;
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// Decodes WebP lossless (VP8L, RFC 9649 §3): transforms (predictor, colour, subtract green, colour indexing with
/// pixel bundling), the colour cache, meta prefix codes and the LZ77 backward references of the entropy-coded
/// image. Also decodes the headerless image stream that carries compressed alpha in an ALPH chunk.
/// </summary>
internal sealed class Vp8LDecoder
{
/// <summary>The byte every VP8L bitstream starts with.</summary>
public const byte Signature = 0x2F;
private const int NumLengthCodes = 24;
private const int NumDistanceCodes = 40;
private const int MaxCacheBits = 11;
private const uint HashMultiplier = 0x1E35A7BD;
private static ReadOnlySpan<byte> CodeLengthOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
// RFC 9649 §3.6: the 120 short distance codes as (dx, dy), dx first: distance = dx + dy * width.
private static ReadOnlySpan<sbyte> DistanceMap =>
[
0, 1, 1, 0, 1, 1, -1, 1, 0, 2, 2, 0, 1, 2,
-1, 2, 2, 1, -2, 1, 2, 2, -2, 2, 0, 3, 3, 0,
1, 3, -1, 3, 3, 1, -3, 1, 2, 3, -2, 3, 3, 2,
-3, 2, 0, 4, 4, 0, 1, 4, -1, 4, 4, 1, -4, 1,
3, 3, -3, 3, 2, 4, -2, 4, 4, 2, -4, 2, 0, 5,
3, 4, -3, 4, 4, 3, -4, 3, 5, 0, 1, 5, -1, 5,
5, 1, -5, 1, 2, 5, -2, 5, 5, 2, -5, 2, 4, 4,
-4, 4, 3, 5, -3, 5, 5, 3, -5, 3, 0, 6, 6, 0,
1, 6, -1, 6, 6, 1, -6, 1, 2, 6, -2, 6, 6, 2,
-6, 2, 4, 5, -4, 5, 5, 4, -5, 4, 3, 6, -3, 6,
6, 3, -6, 3, 0, 7, 7, 0, 1, 7, -1, 7, 5, 5,
-5, 5, 7, 1, -7, 1, 4, 6, -4, 6, 6, 4, -6, 4,
2, 7, -2, 7, 7, 2, -7, 2, 3, 7, -3, 7, 7, 3,
-7, 3, 5, 6, -5, 6, 6, 5, -6, 5, 8, 0, 4, 7,
-4, 7, 7, 4, -7, 4, 8, 1, 8, 2, 6, 6, -6, 6,
8, 3, 5, 7, -5, 7, 7, 5, -7, 5, 8, 4, 6, 7,
-6, 7, 7, 6, -7, 6, 8, 5, 7, 7, -7, 7, 8, 6,
8, 7,
];
private readonly Vp8LBitReader _br;
private readonly ImageLimits _limits;
private long _budget;
private Vp8LDecoder(byte[] data, int start, int length, ImageLimits limits)
{
_br = new Vp8LBitReader(data, start, length);
_limits = limits;
}
/// <summary>Size and alpha hint of a VP8L bitstream, from its five-byte header.</summary>
/// <exception cref="ImageDecodeException">The bytes are not a VP8L header.</exception>
public static (int Width, int Height, bool AlphaUsed) ReadHeader(ReadOnlySpan<byte> data)
{
if (data.Length < 5)
{
throw new ImageDecodeException("WebP troncato: l'intestazione VP8L è incompleta.");
}
if (data[0] != Signature)
{
throw new ImageDecodeException("WebP danneggiato: manca la firma del flusso VP8L.");
}
var bits = (uint)(data[1] | (data[2] << 8) | (data[3] << 16) | (data[4] << 24));
if (bits >> 29 != 0)
{
throw new ImageDecodeException("WebP danneggiato: versione VP8L sconosciuta.");
}
return ((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1, ((bits >> 28) & 1) == 1);
}
/// <summary>Decodes a whole VP8L bitstream into <paramref name="target"/>, which must have its size.</summary>
public static void Decode(byte[] data, int start, int length, ImageLimits limits, RgbaImage target)
{
var (width, height, _) = ReadHeader(data.AsSpan(start, length));
if (target.Width != width || target.Height != height)
{
throw new ArgumentException("The target does not have the size of the image.", nameof(target));
}
var decoder = new Vp8LDecoder(data, start + 5, length - 5, limits);
var argb = decoder.DecodeImage(width, height);
try
{
var pixels = argb.AsSpan(0, width * height);
var output = target.Pixels;
for (var i = 0; i < pixels.Length; i++)
{
var p = pixels[i];
var o = i * 4;
output[o] = (byte)(p >> 16);
output[o + 1] = (byte)(p >> 8);
output[o + 2] = (byte)p;
output[o + 3] = (byte)(p >> 24);
}
}
finally
{
ArrayPool<uint>.Shared.Return(argb);
}
}
/// <summary>
/// Decodes the image stream of an ALPH chunk compressed with VP8L (no signature, no size: the size is the
/// frame's); the alpha values are the green channel.
/// </summary>
public static void DecodeAlpha(byte[] data, int start, int length, int width, int height, ImageLimits limits, Span<byte> alpha)
{
var decoder = new Vp8LDecoder(data, start, length, limits);
var argb = decoder.DecodeImage(width, height);
try
{
var pixels = argb.AsSpan(0, width * height);
for (var i = 0; i < pixels.Length; i++)
{
alpha[i] = (byte)(pixels[i] >> 8);
}
}
finally
{
ArrayPool<uint>.Shared.Return(argb);
}
}
private enum TransformType
{
Predictor = 0,
Color = 1,
SubtractGreen = 2,
ColorIndexing = 3,
}
private sealed record Transform(TransformType Type, int Bits, int Width, int PackedWidth, uint[] Data);
// The image of RFC 9649 §3.5 "spatially-coded image" with its transforms; a pooled array of width × height.
private uint[] DecodeImage(int width, int height)
{
_limits.CheckSize(width, height);
var pixelCount = (long)width * height;
Charge(pixelCount * 4);
var transforms = new List<Transform>(4);
var seen = 0;
var xsize = width;
while (_br.ReadBits(1) == 1)
{
var type = (TransformType)_br.ReadBits(2);
if ((seen & (1 << (int)type)) != 0)
{
throw new ImageDecodeException("WebP danneggiato: una trasformata VP8L compare due volte.");
}
seen |= 1 << (int)type;
switch (type)
{
case TransformType.Predictor:
case TransformType.Color:
{
var bits = _br.ReadBits(3) + 2;
var sub = DecodeEntropyImage(DivRoundUp(xsize, bits), DivRoundUp(height, bits));
transforms.Add(new Transform(type, bits, xsize, xsize, sub));
break;
}
case TransformType.SubtractGreen:
transforms.Add(new Transform(type, 0, xsize, xsize, []));
break;
default:
{
var colors = _br.ReadBits(8) + 1;
var bits = colors > 16 ? 0 : colors > 4 ? 1 : colors > 2 ? 2 : 3;
var raw = DecodeEntropyImage(colors, 1);
var palette = new uint[256];
palette[0] = raw[0];
for (var i = 1; i < colors; i++)
{
palette[i] = AddPixels(raw[i], palette[i - 1]);
}
var packed = DivRoundUp(xsize, bits);
transforms.Add(new Transform(type, bits, xsize, packed, palette));
xsize = packed;
break;
}
}
CheckStream();
}
var argb = ArrayPool<uint>.Shared.Rent((int)pixelCount);
try
{
DecodeSpatial(xsize, height, argb, allowMeta: true);
for (var i = transforms.Count - 1; i >= 0; i--)
{
var t = transforms[i];
switch (t.Type)
{
case TransformType.Predictor:
InversePredictor(argb, t.Width, height, t.Bits, t.Data);
break;
case TransformType.Color:
InverseColor(argb, t.Width, height, t.Bits, t.Data);
break;
case TransformType.SubtractGreen:
AddGreen(argb.AsSpan(0, t.Width * height));
break;
default:
InverseColorIndexing(argb, t.Width, t.PackedWidth, height, t.Bits, t.Data);
break;
}
}
return argb;
}
catch
{
ArrayPool<uint>.Shared.Return(argb);
throw;
}
}
// A sub-image (transform data, entropy image, palette): colour cache allowed, no meta prefix codes.
private uint[] DecodeEntropyImage(int width, int height)
{
var count = (long)width * height;
Charge(count * 4);
var pixels = new uint[count];
DecodeSpatial(width, height, pixels, allowMeta: false);
return pixels;
}
private void DecodeSpatial(int width, int height, uint[] output, bool allowMeta)
{
var cacheBits = 0;
if (_br.ReadBits(1) == 1)
{
cacheBits = _br.ReadBits(4);
if (cacheBits is < 1 or > MaxCacheBits)
{
throw new ImageDecodeException("WebP danneggiato: misura della cache dei colori VP8L non valida.");
}
}
var metaBits = 0;
uint[]? meta = null;
var metaWidth = 0;
var groupCount = 1;
if (allowMeta && _br.ReadBits(1) == 1)
{
metaBits = _br.ReadBits(3) + 2;
metaWidth = DivRoundUp(width, metaBits);
meta = DecodeEntropyImage(metaWidth, DivRoundUp(height, metaBits));
var max = 0;
for (var i = 0; i < meta.Length; i++)
{
var g = (int)((meta[i] >> 8) & 0xFFFF);
meta[i] = (uint)g;
max = Math.Max(max, g);
}
groupCount = max + 1;
}
CheckStream();
var cacheSize = cacheBits > 0 ? 1 << cacheBits : 0;
var groups = new Vp8LHuffman[groupCount * 5];
Span<int> alphabets = [256 + NumLengthCodes + cacheSize, 256, 256, 256, NumDistanceCodes];
var lengths = new byte[alphabets[0]];
for (var g = 0; g < groupCount; g++)
{
for (var k = 0; k < 5; k++)
{
var code = ReadCode(alphabets[k], lengths);
Charge(code.TableSize * 4L);
groups[(g * 5) + k] = code;
}
CheckStream();
}
DecodePixels(width, height, output, groups, meta, metaBits, metaWidth, cacheBits);
}
private Vp8LHuffman ReadCode(int alphabet, byte[] buffer)
{
var lengths = buffer.AsSpan(0, alphabet);
lengths.Clear();
if (_br.ReadBits(1) == 1)
{
// Simple code: one or two symbols, each of length 1 (a single symbol is read with zero bits).
var symbols = _br.ReadBits(1) + 1;
var first = _br.ReadBits(_br.ReadBits(1) == 1 ? 8 : 1);
if (first >= alphabet)
{
throw Damaged();
}
lengths[first] = 1;
if (symbols == 2)
{
var second = _br.ReadBits(8);
if (second >= alphabet)
{
throw Damaged();
}
lengths[second] = 1;
}
}
else
{
Span<byte> codeLengthLengths = stackalloc byte[19];
codeLengthLengths.Clear();
var count = 4 + _br.ReadBits(4);
for (var i = 0; i < count; i++)
{
codeLengthLengths[CodeLengthOrder[i]] = (byte)_br.ReadBits(3);
}
var codeLengthCode = Vp8LHuffman.Build(codeLengthLengths) ?? throw Damaged();
var maxSymbol = alphabet;
if (_br.ReadBits(1) == 1)
{
var lengthBits = 2 + (2 * _br.ReadBits(3));
maxSymbol = 2 + _br.ReadBits(lengthBits);
if (maxSymbol > alphabet)
{
throw Damaged();
}
}
var previous = 8;
var symbol = 0;
while (symbol < alphabet)
{
if (maxSymbol-- == 0)
{
break;
}
var len = codeLengthCode.Read(_br);
if (len < 16)
{
lengths[symbol++] = (byte)len;
if (len != 0)
{
previous = len;
}
continue;
}
var repeat = len switch
{
16 => 3 + _br.ReadBits(2),
17 => 3 + _br.ReadBits(3),
_ => 11 + _br.ReadBits(7),
};
if (symbol + repeat > alphabet)
{
throw Damaged();
}
lengths.Slice(symbol, repeat).Fill(len == 16 ? (byte)previous : (byte)0);
symbol += repeat;
}
}
if (_br.EndOfStream)
{
throw Truncated();
}
return Vp8LHuffman.Build(lengths) ?? throw Damaged();
}
private void DecodePixels(int width, int height, uint[] output, Vp8LHuffman[] groups, uint[]? meta, int metaBits, int metaWidth, int cacheBits)
{
var total = width * height;
uint[]? cache = cacheBits > 0 ? new uint[1 << cacheBits] : null;
var cacheShift = 32 - cacheBits;
var metaMask = meta is null ? -1 : (1 << metaBits) - 1;
var br = _br;
var pos = 0;
var x = 0;
var y = 0;
var g = 0;
var nextCheck = width;
while (pos < total)
{
if ((x & metaMask) == 0)
{
g = GroupAt(meta, metaBits, metaWidth, x, y) * 5;
}
var code = groups[g].Read(br);
if (code < 256)
{
var red = groups[g + 1].Read(br);
var blue = groups[g + 2].Read(br);
var alpha = groups[g + 3].Read(br);
var pixel = ((uint)alpha << 24) | ((uint)red << 16) | ((uint)code << 8) | (uint)blue;
output[pos++] = pixel;
if (cache is not null)
{
cache[(HashMultiplier * pixel) >> cacheShift] = pixel;
}
if (++x == width)
{
x = 0;
y++;
}
}
else if (code < 256 + NumLengthCodes)
{
var length = PrefixValue(code - 256);
var distanceCode = PrefixValue(groups[g + 4].Read(br));
var distance = PlaneDistance(distanceCode, width);
if (distance > pos || length > total - pos)
{
throw Damaged();
}
var target = output.AsSpan(pos, length);
var from = pos - distance;
if (distance >= length)
{
output.AsSpan(from, length).CopyTo(target);
}
else
{
for (var k = 0; k < length; k++)
{
output[pos + k] = output[from + k];
}
}
if (cache is not null)
{
foreach (var pixel in target)
{
cache[(HashMultiplier * pixel) >> cacheShift] = pixel;
}
}
pos += length;
x += length;
while (x >= width)
{
x -= width;
y++;
}
if (meta is not null && pos < total)
{
g = GroupAt(meta, metaBits, metaWidth, x, y) * 5;
}
}
else
{
var index = code - 256 - NumLengthCodes;
if (cache is null || index >= cache.Length)
{
throw Damaged();
}
var pixel = cache[index];
output[pos++] = pixel;
cache[(HashMultiplier * pixel) >> cacheShift] = pixel;
if (++x == width)
{
x = 0;
y++;
}
}
if (pos >= nextCheck)
{
CheckStream();
nextCheck = pos + width;
}
}
CheckStream();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GroupAt(uint[]? meta, int metaBits, int metaWidth, int x, int y) =>
meta is null ? 0 : (int)meta[((y >> metaBits) * metaWidth) + (x >> metaBits)];
// RFC 9649 §3.6: the value of an LZ77 prefix code with its extra bits.
private int PrefixValue(int code)
{
if (code < 4)
{
return code + 1;
}
var extraBits = (code - 2) >> 1;
var offset = (2 + (code & 1)) << extraBits;
return offset + _br.ReadBits(extraBits) + 1;
}
private static int PlaneDistance(int code, int width)
{
if (code > 120)
{
return code - 120;
}
var (dx, dy) = ShortDistance(code);
return Math.Max(1, dx + (dy * width));
}
/// <summary>The (dx, dy) of short distance code 1-120.</summary>
internal static (int Dx, int Dy) ShortDistance(int code) => (DistanceMap[(code - 1) * 2], DistanceMap[((code - 1) * 2) + 1]);
private static void InversePredictor(uint[] data, int width, int height, int bits, uint[] modes)
{
var blocksWide = DivRoundUp(width, bits);
data[0] = AddPixels(data[0], 0xFF000000);
for (var x = 1; x < width; x++)
{
data[x] = AddPixels(data[x], data[x - 1]);
}
for (var y = 1; y < height; y++)
{
var row = y * width;
data[row] = AddPixels(data[row], data[row - width]);
var modeRow = (y >> bits) * blocksWide;
for (var x = 1; x < width; x++)
{
var i = row + x;
var mode = (int)(modes[modeRow + (x >> bits)] >> 8) & 0xF;
data[i] = AddPixels(data[i], Predict(mode, data[i - 1], data[i - width], data[i - width + 1], data[i - width - 1]));
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static uint Predict(int mode, uint left, uint top, uint topRight, uint topLeft) => mode switch
{
1 => left,
2 => top,
3 => topRight,
4 => topLeft,
5 => Average2(Average2(left, topRight), top),
6 => Average2(left, topLeft),
7 => Average2(left, top),
8 => Average2(topLeft, top),
9 => Average2(top, topRight),
10 => Average2(Average2(left, topLeft), Average2(top, topRight)),
11 => Select(left, top, topLeft),
12 => ClampAddSubtractFull(left, top, topLeft),
13 => ClampAddSubtractHalf(Average2(left, top), topLeft),
_ => 0xFF000000, // mode 0, and 14 and 15 which the format does not define
};
private static void InverseColor(uint[] data, int width, int height, int bits, uint[] elements)
{
var blocksWide = DivRoundUp(width, bits);
for (var y = 0; y < height; y++)
{
var row = y * width;
var elementRow = (y >> bits) * blocksWide;
for (var x = 0; x < width; x++)
{
var e = elements[elementRow + (x >> bits)];
var p = data[row + x];
var green = (sbyte)(p >> 8);
var red = (int)((p >> 16) & 0xFF) + (((sbyte)e * green) >> 5);
var blue = (int)(p & 0xFF) + (((sbyte)(e >> 8) * green) >> 5);
blue += ((sbyte)(e >> 16) * (sbyte)red) >> 5;
data[row + x] = (p & 0xFF00FF00) | ((uint)(red & 0xFF) << 16) | (uint)(blue & 0xFF);
}
}
}
private static void AddGreen(Span<uint> data)
{
for (var i = 0; i < data.Length; i++)
{
var p = data[i];
var green = (p >> 8) & 0xFF;
var redBlue = (p & 0x00FF00FF) + ((green << 16) | green);
data[i] = (p & 0xFF00FF00) | (redBlue & 0x00FF00FF);
}
}
private static void InverseColorIndexing(uint[] data, int width, int packedWidth, int height, int bits, uint[] palette)
{
if (bits == 0)
{
var pixels = data.AsSpan(0, width * height);
for (var i = 0; i < pixels.Length; i++)
{
pixels[i] = palette[(pixels[i] >> 8) & 0xFF];
}
return;
}
var perByte = 1 << bits;
var bitsPerPixel = 8 >> bits;
var mask = (1 << bitsPerPixel) - 1;
// Backwards, so the packed row is read before the wider row overwrites it.
for (var y = height - 1; y >= 0; y--)
{
var packedRow = y * packedWidth;
var row = y * width;
for (var x = width - 1; x >= 0; x--)
{
var packed = (int)(data[packedRow + (x >> bits)] >> 8) & 0xFF;
var index = (packed >> ((x & (perByte - 1)) * bitsPerPixel)) & mask;
data[row + x] = palette[index];
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static uint AddPixels(uint a, uint b) =>
(((a & 0xFF00FF00) + (b & 0xFF00FF00)) & 0xFF00FF00) | (((a & 0x00FF00FF) + (b & 0x00FF00FF)) & 0x00FF00FF);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static uint SubtractPixels(uint a, uint b) =>
(((a | 0x00FF00FF) - (b & 0xFF00FF00)) & 0xFF00FF00) | (((a | 0xFF00FF00) - (b & 0x00FF00FF)) & 0x00FF00FF);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint Average2(uint a, uint b) => (((a ^ b) & 0xFEFEFEFE) >> 1) + (a & b);
private static uint Select(uint left, uint top, uint topLeft)
{
// Manhattan distances of the estimate L + T − TL to L and to T.
var toLeft = Math.Abs(Channel(top, 24) - Channel(topLeft, 24)) + Math.Abs(Channel(top, 16) - Channel(topLeft, 16))
+ Math.Abs(Channel(top, 8) - Channel(topLeft, 8)) + Math.Abs(Channel(top, 0) - Channel(topLeft, 0));
var toTop = Math.Abs(Channel(left, 24) - Channel(topLeft, 24)) + Math.Abs(Channel(left, 16) - Channel(topLeft, 16))
+ Math.Abs(Channel(left, 8) - Channel(topLeft, 8)) + Math.Abs(Channel(left, 0) - Channel(topLeft, 0));
return toLeft < toTop ? left : top;
}
private static uint ClampAddSubtractFull(uint a, uint b, uint c) =>
((uint)Clip255(Channel(a, 24) + Channel(b, 24) - Channel(c, 24)) << 24)
| ((uint)Clip255(Channel(a, 16) + Channel(b, 16) - Channel(c, 16)) << 16)
| ((uint)Clip255(Channel(a, 8) + Channel(b, 8) - Channel(c, 8)) << 8)
| (uint)Clip255(Channel(a, 0) + Channel(b, 0) - Channel(c, 0));
private static uint ClampAddSubtractHalf(uint a, uint b) =>
((uint)Half(Channel(a, 24), Channel(b, 24)) << 24)
| ((uint)Half(Channel(a, 16), Channel(b, 16)) << 16)
| ((uint)Half(Channel(a, 8), Channel(b, 8)) << 8)
| (uint)Half(Channel(a, 0), Channel(b, 0));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Half(int a, int b) => Clip255(a + ((a - b) / 2));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Channel(uint p, int shift) => (int)((p >> shift) & 0xFF);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Clip255(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
internal static int DivRoundUp(int value, int bits) => (value + (1 << bits) - 1) >> bits;
private void Charge(long bytes)
{
_budget += bytes;
_limits.CheckWorkingBytes(_budget);
}
private void CheckStream()
{
if (_br.EndOfStream)
{
throw Truncated();
}
}
private static ImageDecodeException Truncated() => new("WebP troncato: il flusso VP8L finisce prima dell'ultimo pixel.");
private static ImageDecodeException Damaged() => new("WebP danneggiato: codici del flusso VP8L non validi.");
}
+275
View File
@@ -0,0 +1,275 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// The bit reader of WebP lossless (RFC 9649 §3): bits are read from the least significant bit of each byte, and
/// past the end of the data it reads zeros and remembers it.
/// </summary>
internal sealed class Vp8LBitReader
{
private readonly byte[] _data;
private readonly int _end;
private int _pos;
private ulong _buffer;
private int _count;
public Vp8LBitReader(byte[] data, int start, int length)
{
_data = data;
_pos = start;
_end = start + length;
Fill();
}
/// <summary>Whether bits past the end of the data were consumed.</summary>
public bool EndOfStream { get; private set; }
/// <summary>Reads <paramref name="n"/> bits (0-24), least significant first.</summary>
public int ReadBits(int n)
{
if (_count < n)
{
Fill();
if (_count < n)
{
EndOfStream = true;
_count = n; // the missing bits are zeros
}
}
var value = (int)(_buffer & ((1UL << n) - 1));
_buffer >>= n;
_count -= n;
return value;
}
/// <summary>At least 32 bits ready for <see cref="Peek"/> when the data has them; zeros past the end.</summary>
public ulong Peek()
{
if (_count < 32)
{
Fill();
}
return _buffer;
}
public void Skip(int n)
{
if (_count < n)
{
EndOfStream = true;
_buffer = 0;
_count = 0;
return;
}
_buffer >>= n;
_count -= n;
}
private void Fill()
{
while (_count <= 56 && _pos < _end)
{
_buffer |= (ulong)_data[_pos++] << _count;
_count += 8;
}
}
}
/// <summary>
/// A canonical prefix code of WebP lossless (the codes of DEFLATE: shorter codes first, then by symbol; read from the
/// first bit of the code), decoded with a table of 8 bits and second-level tables for longer codes.
/// </summary>
internal sealed class Vp8LHuffman
{
public const int MaxCodeLength = 15;
private const int RootBits = 8;
// Entry: symbol (or offset of the second-level table) | bits << 16 | second-level bits << 24.
private readonly uint[] _table;
private Vp8LHuffman(uint[] table, int singleSymbol)
{
_table = table;
SingleSymbol = singleSymbol;
}
/// <summary>The symbol of a code that has only one (read with zero bits), or −1.</summary>
public int SingleSymbol { get; }
/// <summary>Entries of the decoding tables, for the memory budget.</summary>
public int TableSize => _table.Length;
/// <summary>
/// The code given by the code lengths of each symbol (0 = not used), or null when the lengths are not a complete
/// prefix code (or use no symbol at all). A single used symbol is a code of zero bits.
/// </summary>
public static Vp8LHuffman? Build(ReadOnlySpan<byte> lengths)
{
Span<int> counts = stackalloc int[MaxCodeLength + 1];
var used = 0;
var last = -1;
for (var s = 0; s < lengths.Length; s++)
{
var len = lengths[s];
if (len > MaxCodeLength)
{
return null;
}
if (len > 0)
{
counts[len]++;
used++;
last = s;
}
}
if (used == 0)
{
return null;
}
if (used == 1)
{
var single = new uint[1 << RootBits];
single.AsSpan().Fill((uint)last);
return new Vp8LHuffman(single, last);
}
// Kraft: the code must be complete, neither over- nor under-subscribed.
var space = 1 << MaxCodeLength;
for (var len = 1; len <= MaxCodeLength; len++)
{
space -= counts[len] << (MaxCodeLength - len);
if (space < 0)
{
return null;
}
}
if (space != 0)
{
return null;
}
Span<int> next = stackalloc int[MaxCodeLength + 2];
var code = 0;
for (var len = 1; len <= MaxCodeLength; len++)
{
code = (code + counts[len - 1]) << 1;
next[len] = code;
}
// Longest code under each root prefix, to size the second-level tables.
Span<byte> longest = stackalloc byte[1 << RootBits];
longest.Clear();
var codes = new int[lengths.Length];
{
Span<int> assign = stackalloc int[MaxCodeLength + 2];
next.CopyTo(assign);
for (var s = 0; s < lengths.Length; s++)
{
var len = lengths[s];
if (len == 0)
{
continue;
}
var reversed = Reverse(assign[len]++, len);
codes[s] = reversed;
if (len > RootBits)
{
var prefix = reversed & ((1 << RootBits) - 1);
longest[prefix] = Math.Max(longest[prefix], len);
}
}
}
Span<int> offsets = stackalloc int[1 << RootBits];
var size = 1 << RootBits;
for (var prefix = 0; prefix < longest.Length; prefix++)
{
if (longest[prefix] > 0)
{
offsets[prefix] = size;
size += 1 << (longest[prefix] - RootBits);
}
}
var table = new uint[size];
for (var prefix = 0; prefix < longest.Length; prefix++)
{
if (longest[prefix] > 0)
{
table[prefix] = (uint)offsets[prefix] | (uint)(longest[prefix] - RootBits) << 24;
}
}
for (var s = 0; s < lengths.Length; s++)
{
var len = lengths[s];
if (len == 0)
{
continue;
}
var reversed = codes[s];
if (len <= RootBits)
{
var entry = (uint)s | (uint)len << 16;
for (var i = reversed; i < (1 << RootBits); i += 1 << len)
{
table[i] = entry;
}
}
else
{
var prefix = reversed & ((1 << RootBits) - 1);
var subBits = longest[prefix] - RootBits;
var entry = (uint)s | (uint)(len - RootBits) << 16;
for (var i = reversed >> RootBits; i < (1 << subBits); i += 1 << (len - RootBits))
{
table[offsets[prefix] + i] = entry;
}
}
}
return new Vp8LHuffman(table, -1);
}
/// <summary>Reads one symbol.</summary>
public int Read(Vp8LBitReader reader)
{
if (SingleSymbol >= 0)
{
return SingleSymbol;
}
var bits = reader.Peek();
var entry = _table[(int)(bits & ((1 << RootBits) - 1))];
var sub = (int)(entry >> 24);
if (sub == 0)
{
reader.Skip((int)(entry >> 16) & 0xFF);
return (int)(entry & 0xFFFF);
}
var second = _table[(int)(entry & 0xFFFF) + (int)((bits >> RootBits) & ((1UL << sub) - 1))];
reader.Skip(RootBits + ((int)(second >> 16) & 0xFF));
return (int)(second & 0xFFFF);
}
internal static int Reverse(int code, int length)
{
var r = 0;
for (var i = 0; i < length; i++)
{
r = (r << 1) | (code & 1);
code >>= 1;
}
return r;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,565 @@
using System.Runtime.CompilerServices;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// Intra prediction of VP8 (RFC 6386 §12). The buffers hold the block with its row above (from one pixel to the
/// left; for subblocks eight pixels wide) and its column to the left at the usual offsets of <c>at</c>.
/// </summary>
internal static class Vp8Predict
{
/// <summary>A 16×16 luma or 8×8 chroma prediction (DC_PRED, V_PRED, H_PRED, TM_PRED).</summary>
public static void Block(Span<byte> buf, int at, int stride, int size, int mode, bool hasLeft, bool hasTop)
{
switch (mode)
{
case Vp8Tables.VPred:
{
var above = buf.Slice(at - stride, size);
for (var r = 0; r < size; r++)
{
above.CopyTo(buf.Slice(at + (r * stride), size));
}
break;
}
case Vp8Tables.HPred:
for (var r = 0; r < size; r++)
{
var row = at + (r * stride);
buf.Slice(row, size).Fill(buf[row - 1]);
}
break;
case Vp8Tables.TmPred:
{
var corner = buf[at - stride - 1];
for (var r = 0; r < size; r++)
{
var row = at + (r * stride);
var delta = buf[row - 1] - corner;
for (var c = 0; c < size; c++)
{
buf[row + c] = Clip(buf[at - stride + c] + delta);
}
}
break;
}
default:
{
var shift = size == 16 ? 4 : 3;
int value;
if (hasTop && hasLeft)
{
value = (SumAbove(buf, at, stride, size) + SumLeft(buf, at, stride, size) + size) >> (shift + 1);
}
else if (hasTop)
{
value = (SumAbove(buf, at, stride, size) + (size >> 1)) >> shift;
}
else if (hasLeft)
{
value = (SumLeft(buf, at, stride, size) + (size >> 1)) >> shift;
}
else
{
value = 128;
}
for (var r = 0; r < size; r++)
{
buf.Slice(at + (r * stride), size).Fill((byte)value);
}
break;
}
}
}
/// <summary>A 4×4 luma subblock prediction (the ten intra_bmode of RFC 6386 §12.3).</summary>
public static void Sub4x4(Span<byte> buf, int at, int stride, int mode)
{
var up = at - stride;
int a0 = buf[up], a1 = buf[up + 1], a2 = buf[up + 2], a3 = buf[up + 3];
int a4 = buf[up + 4], a5 = buf[up + 5], a6 = buf[up + 6], a7 = buf[up + 7];
int p = buf[up - 1];
int l0 = buf[at - 1], l1 = buf[at + stride - 1], l2 = buf[at + (2 * stride) - 1], l3 = buf[at + (3 * stride) - 1];
var r0 = at;
var r1 = at + stride;
var r2 = at + (2 * stride);
var r3 = at + (3 * stride);
switch (mode)
{
case Vp8Tables.BDc:
{
var v = (byte)((a0 + a1 + a2 + a3 + l0 + l1 + l2 + l3 + 4) >> 3);
buf.Slice(r0, 4).Fill(v);
buf.Slice(r1, 4).Fill(v);
buf.Slice(r2, 4).Fill(v);
buf.Slice(r3, 4).Fill(v);
break;
}
case Vp8Tables.BTm:
{
Span<int> left = [l0, l1, l2, l3];
for (var r = 0; r < 4; r++)
{
var row = at + (r * stride);
var delta = left[r] - p;
buf[row] = Clip(a0 + delta);
buf[row + 1] = Clip(a1 + delta);
buf[row + 2] = Clip(a2 + delta);
buf[row + 3] = Clip(a3 + delta);
}
break;
}
case Vp8Tables.BVe:
{
var c0 = Avg3(p, a0, a1);
var c1 = Avg3(a0, a1, a2);
var c2 = Avg3(a1, a2, a3);
var c3 = Avg3(a2, a3, a4);
foreach (var row in (ReadOnlySpan<int>)[r0, r1, r2, r3])
{
buf[row] = c0;
buf[row + 1] = c1;
buf[row + 2] = c2;
buf[row + 3] = c3;
}
break;
}
case Vp8Tables.BHe:
buf.Slice(r0, 4).Fill(Avg3(p, l0, l1));
buf.Slice(r1, 4).Fill(Avg3(l0, l1, l2));
buf.Slice(r2, 4).Fill(Avg3(l1, l2, l3));
buf.Slice(r3, 4).Fill(Avg3(l2, l3, l3));
break;
case Vp8Tables.BLd:
buf[r0] = Avg3(a0, a1, a2);
buf[r0 + 1] = buf[r1] = Avg3(a1, a2, a3);
buf[r0 + 2] = buf[r1 + 1] = buf[r2] = Avg3(a2, a3, a4);
buf[r0 + 3] = buf[r1 + 2] = buf[r2 + 1] = buf[r3] = Avg3(a3, a4, a5);
buf[r1 + 3] = buf[r2 + 2] = buf[r3 + 1] = Avg3(a4, a5, a6);
buf[r2 + 3] = buf[r3 + 2] = Avg3(a5, a6, a7);
buf[r3 + 3] = Avg3(a6, a7, a7);
break;
case Vp8Tables.BRd:
{
// Edge from bottom-left to top-right: L3, L2, L1, L0, P, A0, A1, A2, A3.
buf[r3] = Avg3(l3, l2, l1);
buf[r3 + 1] = buf[r2] = Avg3(l2, l1, l0);
buf[r3 + 2] = buf[r2 + 1] = buf[r1] = Avg3(l1, l0, p);
buf[r3 + 3] = buf[r2 + 2] = buf[r1 + 1] = buf[r0] = Avg3(l0, p, a0);
buf[r2 + 3] = buf[r1 + 2] = buf[r0 + 1] = Avg3(p, a0, a1);
buf[r1 + 3] = buf[r0 + 2] = Avg3(a0, a1, a2);
buf[r0 + 3] = Avg3(a1, a2, a3);
break;
}
case Vp8Tables.BVr:
buf[r3] = Avg3(l2, l1, l0);
buf[r2] = Avg3(l1, l0, p);
buf[r3 + 1] = buf[r1] = Avg3(l0, p, a0);
buf[r2 + 1] = buf[r0] = Avg2(p, a0);
buf[r3 + 2] = buf[r1 + 1] = Avg3(p, a0, a1);
buf[r2 + 2] = buf[r0 + 1] = Avg2(a0, a1);
buf[r3 + 3] = buf[r1 + 2] = Avg3(a0, a1, a2);
buf[r2 + 3] = buf[r0 + 2] = Avg2(a1, a2);
buf[r1 + 3] = Avg3(a1, a2, a3);
buf[r0 + 3] = Avg2(a2, a3);
break;
case Vp8Tables.BVl:
buf[r0] = Avg2(a0, a1);
buf[r1] = Avg3(a0, a1, a2);
buf[r2] = buf[r0 + 1] = Avg2(a1, a2);
buf[r1 + 1] = buf[r3] = Avg3(a1, a2, a3);
buf[r2 + 1] = buf[r0 + 2] = Avg2(a2, a3);
buf[r3 + 1] = buf[r1 + 2] = Avg3(a2, a3, a4);
buf[r2 + 2] = buf[r0 + 3] = Avg2(a3, a4);
buf[r3 + 2] = buf[r1 + 3] = Avg3(a3, a4, a5);
buf[r2 + 3] = Avg3(a4, a5, a6);
buf[r3 + 3] = Avg3(a5, a6, a7);
break;
case Vp8Tables.BHd:
buf[r3] = Avg2(l3, l2);
buf[r3 + 1] = Avg3(l3, l2, l1);
buf[r2] = buf[r3 + 2] = Avg2(l2, l1);
buf[r2 + 1] = buf[r3 + 3] = Avg3(l2, l1, l0);
buf[r2 + 2] = buf[r1] = Avg2(l1, l0);
buf[r2 + 3] = buf[r1 + 1] = Avg3(l1, l0, p);
buf[r1 + 2] = buf[r0] = Avg2(l0, p);
buf[r1 + 3] = buf[r0 + 1] = Avg3(l0, p, a0);
buf[r0 + 2] = Avg3(p, a0, a1);
buf[r0 + 3] = Avg3(a0, a1, a2);
break;
default: // B_HU_PRED
buf[r0] = Avg2(l0, l1);
buf[r0 + 1] = Avg3(l0, l1, l2);
buf[r0 + 2] = buf[r1] = Avg2(l1, l2);
buf[r0 + 3] = buf[r1 + 1] = Avg3(l1, l2, l3);
buf[r1 + 2] = buf[r2] = Avg2(l2, l3);
buf[r1 + 3] = buf[r2 + 1] = Avg3(l2, l3, l3);
buf[r2 + 2] = buf[r2 + 3] = (byte)l3;
buf.Slice(r3, 4).Fill((byte)l3);
break;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte Avg2(int a, int b) => (byte)((a + b + 1) >> 1);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte Avg3(int a, int b, int c) => (byte)((a + (2 * b) + c + 2) >> 2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static byte Clip(int v) => (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
private static int SumAbove(Span<byte> buf, int at, int stride, int size)
{
var sum = 0;
foreach (var b in buf.Slice(at - stride, size))
{
sum += b;
}
return sum;
}
private static int SumLeft(Span<byte> buf, int at, int stride, int size)
{
var sum = 0;
for (var r = 0; r < size; r++)
{
sum += buf[at + (r * stride) - 1];
}
return sum;
}
}
/// <summary>The inverse transforms of VP8 (RFC 6386 §14.3 and §14.4), exact integer arithmetic.</summary>
internal static class Vp8Transforms
{
private const int C1 = 20091; // cos(π/8)·√2 − 1, ×65536
private const int S1 = 35468; // sin(π/8)·√2, ×65536
/// <summary>
/// The inverse Walsh-Hadamard transform of the Y2 block: its outputs are the DC coefficients of the sixteen luma
/// blocks (coefficient 0 of each block of 16 in <paramref name="blocks"/>).
/// </summary>
public static void InverseWht(ReadOnlySpan<short> input, Span<short> blocks)
{
Span<int> tmp = stackalloc int[16];
for (var i = 0; i < 4; i++)
{
var a1 = input[i] + input[12 + i];
var b1 = input[4 + i] + input[8 + i];
var c1 = input[4 + i] - input[8 + i];
var d1 = input[i] - input[12 + i];
tmp[i] = a1 + b1;
tmp[4 + i] = c1 + d1;
tmp[8 + i] = a1 - b1;
tmp[12 + i] = d1 - c1;
}
for (var i = 0; i < 4; i++)
{
var row = tmp.Slice(i * 4, 4);
var a1 = row[0] + row[3];
var b1 = row[1] + row[2];
var c1 = row[1] - row[2];
var d1 = row[0] - row[3];
blocks[((i * 4) + 0) * 16] = Short((a1 + b1 + 3) >> 3);
blocks[((i * 4) + 1) * 16] = Short((c1 + d1 + 3) >> 3);
blocks[((i * 4) + 2) * 16] = Short((a1 - b1 + 3) >> 3);
blocks[((i * 4) + 3) * 16] = Short((d1 - c1 + 3) >> 3);
}
}
/// <summary>
/// Adds the inverse DCT of <paramref name="coeffs"/> (raster order) to the 4×4 pixels at <paramref name="at"/>:
/// <paramref name="kind"/> 0 means an empty block, 1 only a DC coefficient, 2 any coefficients.
/// </summary>
public static void AddBlock(ReadOnlySpan<short> coeffs, int kind, Span<byte> buf, int at, int stride)
{
if (kind == 0)
{
return;
}
if (kind == 1)
{
var dc = (coeffs[0] + 4) >> 3;
for (var r = 0; r < 4; r++)
{
var row = buf.Slice(at + (r * stride), 4);
row[0] = Vp8Predict.Clip(row[0] + dc);
row[1] = Vp8Predict.Clip(row[1] + dc);
row[2] = Vp8Predict.Clip(row[2] + dc);
row[3] = Vp8Predict.Clip(row[3] + dc);
}
return;
}
Span<int> tmp = stackalloc int[16];
for (var i = 0; i < 4; i++)
{
// Vertical pass over column i.
int i0 = coeffs[i], i4 = coeffs[4 + i], i8 = coeffs[8 + i], i12 = coeffs[12 + i];
var a = i0 + i8;
var b = i0 - i8;
var c = Mul2(i4) - Mul1(i12);
var d = Mul1(i4) + Mul2(i12);
tmp[i] = a + d;
tmp[4 + i] = b + c;
tmp[8 + i] = b - c;
tmp[12 + i] = a - d;
}
for (var r = 0; r < 4; r++)
{
// Horizontal pass over row r.
var t = tmp.Slice(r * 4, 4);
var a = t[0] + t[2];
var b = t[0] - t[2];
var c = Mul2(t[1]) - Mul1(t[3]);
var d = Mul1(t[1]) + Mul2(t[3]);
var row = buf.Slice(at + (r * stride), 4);
row[0] = Vp8Predict.Clip(row[0] + ((a + d + 4) >> 3));
row[1] = Vp8Predict.Clip(row[1] + ((b + c + 4) >> 3));
row[2] = Vp8Predict.Clip(row[2] + ((b - c + 4) >> 3));
row[3] = Vp8Predict.Clip(row[3] + ((a - d + 4) >> 3));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Mul1(int a) => ((a * C1) >> 16) + a;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Mul2(int a) => (a * S1) >> 16;
private static short Short(int v) => (short)Math.Clamp(v, short.MinValue, short.MaxValue);
}
/// <summary>The loop filters of VP8 (RFC 6386 §15), applied to the whole reconstructed frame in raster order.</summary>
internal static class Vp8LoopFilter
{
public static void Apply(Vp8Decoder frame)
{
var y = frame.YPlane;
var u = frame.UPlane;
var v = frame.VPlane;
var ys = frame.YStride;
var uvs = frame.UvStride;
var simple = frame.SimpleFilter;
for (var mbY = 0; mbY < frame.MbHeight; mbY++)
{
for (var mbX = 0; mbX < frame.MbWidth; mbX++)
{
var (limit, interior, hev, inner) = frame.FilterOf((mbY * frame.MbWidth) + mbX);
if (limit == 0)
{
continue;
}
var yAt = (mbY * 16 * ys) + (mbX * 16);
var uvAt = (mbY * 8 * uvs) + (mbX * 8);
if (simple)
{
// Edge strength 2·limit + 1 compares with 4·|p0 − q0| + |p1 − q1| (RFC 6386 §15.2).
if (mbX > 0)
{
SimpleEdge(y, yAt, 1, ys, (2 * (limit + 4)) + 1);
}
if (inner)
{
for (var k = 4; k < 16; k += 4)
{
SimpleEdge(y, yAt + k, 1, ys, (2 * limit) + 1);
}
}
if (mbY > 0)
{
SimpleEdge(y, yAt, ys, 1, (2 * (limit + 4)) + 1);
}
if (inner)
{
for (var k = 4; k < 16; k += 4)
{
SimpleEdge(y, yAt + (k * ys), ys, 1, (2 * limit) + 1);
}
}
continue;
}
var mbEdge = (2 * (limit + 4)) + 1;
var subEdge = (2 * limit) + 1;
if (mbX > 0)
{
MacroblockEdge(y, yAt, 1, ys, 16, mbEdge, interior, hev);
MacroblockEdge(u, uvAt, 1, uvs, 8, mbEdge, interior, hev);
MacroblockEdge(v, uvAt, 1, uvs, 8, mbEdge, interior, hev);
}
if (inner)
{
for (var k = 4; k < 16; k += 4)
{
SubblockEdge(y, yAt + k, 1, ys, 16, subEdge, interior, hev);
}
SubblockEdge(u, uvAt + 4, 1, uvs, 8, subEdge, interior, hev);
SubblockEdge(v, uvAt + 4, 1, uvs, 8, subEdge, interior, hev);
}
if (mbY > 0)
{
MacroblockEdge(y, yAt, ys, 1, 16, mbEdge, interior, hev);
MacroblockEdge(u, uvAt, uvs, 1, 8, mbEdge, interior, hev);
MacroblockEdge(v, uvAt, uvs, 1, 8, mbEdge, interior, hev);
}
if (inner)
{
for (var k = 4; k < 16; k += 4)
{
SubblockEdge(y, yAt + (k * ys), ys, 1, 16, subEdge, interior, hev);
}
SubblockEdge(u, uvAt + (4 * uvs), uvs, 1, 8, subEdge, interior, hev);
SubblockEdge(v, uvAt + (4 * uvs), uvs, 1, 8, subEdge, interior, hev);
}
}
}
}
/// <summary>
/// The simple filter over 16 pixels of an edge: <paramref name="step"/> crosses the edge (1 for a vertical edge),
/// <paramref name="along"/> moves along it; <paramref name="edge2"/> is twice the edge limit plus one.
/// </summary>
internal static void SimpleEdge(byte[] buf, int at, int step, int along, int edge2)
{
for (var i = 0; i < 16; i++)
{
var q = at + (i * along);
int p1 = buf[q - (2 * step)], p0 = buf[q - step], q0 = buf[q], q1 = buf[q + step];
if ((4 * Math.Abs(p0 - q0)) + Math.Abs(p1 - q1) <= edge2)
{
CommonAdjust(buf, q, step, useOuterTaps: true);
}
}
}
internal static void SubblockEdge(byte[] buf, int at, int step, int along, int count, int edge2, int interior, int hevThreshold)
{
for (var i = 0; i < count; i++)
{
var q = at + (i * along);
if (!NeedsFilter(buf, q, step, edge2, interior))
{
continue;
}
var hev = HighEdgeVariance(buf, q, step, hevThreshold);
var a = (CommonAdjust(buf, q, step, hev) + 1) >> 1;
if (!hev)
{
buf[q + step] = S2U(U2S(buf[q + step]) - a);
buf[q - (2 * step)] = S2U(U2S(buf[q - (2 * step)]) + a);
}
}
}
internal static void MacroblockEdge(byte[] buf, int at, int step, int along, int count, int edge2, int interior, int hevThreshold)
{
for (var i = 0; i < count; i++)
{
var q = at + (i * along);
if (!NeedsFilter(buf, q, step, edge2, interior))
{
continue;
}
if (HighEdgeVariance(buf, q, step, hevThreshold))
{
CommonAdjust(buf, q, step, useOuterTaps: true);
continue;
}
var p2 = U2S(buf[q - (3 * step)]);
var p1 = U2S(buf[q - (2 * step)]);
var p0 = U2S(buf[q - step]);
var q0 = U2S(buf[q]);
var q1 = U2S(buf[q + step]);
var q2 = U2S(buf[q + (2 * step)]);
var w = C(C(p1 - q1) + (3 * (q0 - p0)));
var a = C(((27 * w) + 63) >> 7);
buf[q] = S2U(q0 - a);
buf[q - step] = S2U(p0 + a);
a = C(((18 * w) + 63) >> 7);
buf[q + step] = S2U(q1 - a);
buf[q - (2 * step)] = S2U(p1 + a);
a = C(((9 * w) + 63) >> 7);
buf[q + (2 * step)] = S2U(q2 - a);
buf[q - (3 * step)] = S2U(p2 + a);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool NeedsFilter(byte[] buf, int q, int step, int edge2, int interior)
{
int p3 = buf[q - (4 * step)], p2 = buf[q - (3 * step)], p1 = buf[q - (2 * step)], p0 = buf[q - step];
int q0 = buf[q], q1 = buf[q + step], q2 = buf[q + (2 * step)], q3 = buf[q + (3 * step)];
return (4 * Math.Abs(p0 - q0)) + Math.Abs(p1 - q1) <= edge2
&& Math.Abs(p3 - p2) <= interior && Math.Abs(p2 - p1) <= interior && Math.Abs(p1 - p0) <= interior
&& Math.Abs(q3 - q2) <= interior && Math.Abs(q2 - q1) <= interior && Math.Abs(q1 - q0) <= interior;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool HighEdgeVariance(byte[] buf, int q, int step, int threshold) =>
Math.Abs(buf[q - (2 * step)] - buf[q - step]) > threshold || Math.Abs(buf[q + step] - buf[q]) > threshold;
// RFC 6386 §15.2, common_adjust: moves p0 and q0 towards each other; returns the adjustment of q0.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CommonAdjust(byte[] buf, int q, int step, bool useOuterTaps)
{
var p1 = U2S(buf[q - (2 * step)]);
var p0 = U2S(buf[q - step]);
var q0 = U2S(buf[q]);
var q1 = U2S(buf[q + step]);
var a = C((useOuterTaps ? C(p1 - q1) : 0) + (3 * (q0 - p0)));
var b = C(a + 3) >> 3;
a = C(a + 4) >> 3;
buf[q] = S2U(q0 - a);
buf[q - step] = S2U(p0 + b);
return a;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int U2S(byte v) => v - 128;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte S2U(int v) => (byte)(C(v) + 128);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int C(int v) => Math.Clamp(v, -128, 127);
}
+426
View File
@@ -0,0 +1,426 @@
namespace Febe.Core.Codecs.Images;
/// <summary>
/// The constant tables of the VP8 key frame format (RFC 6386): quantizer steps (§14.1), the probabilities of the intra
/// modes (§11) and of the DCT tokens (§13), the trees they are read with, the scan order and the coefficient bands.
/// </summary>
internal static class Vp8Tables
{
/// <summary>Intra modes of a 16×16 luma block or an 8×8 chroma block (RFC 6386 §8.1).</summary>
public const int DcPred = 0, VPred = 1, HPred = 2, TmPred = 3, BPred = 4;
/// <summary>Modes of a 4×4 luma subblock, in the order of RFC 6386 §8.1 (intra_bmode).</summary>
public const int BDc = 0, BTm = 1, BVe = 2, BHe = 3, BLd = 4, BRd = 5, BVr = 6, BVl = 7, BHd = 8, BHu = 9;
public const int NumBModes = 10;
/// <summary>§11.2: kf_ymode_prob.</summary>
public static ReadOnlySpan<byte> KeyFrameYModeProbs => [145, 156, 163, 128];
/// <summary>§11.2: kf_uv_mode_prob.</summary>
public static ReadOnlySpan<byte> KeyFrameUvModeProbs => [142, 114, 183];
/// <summary>
/// §11.2: bmode_tree, as pairs of children; a child ≤ 0 is the leaf −mode, a positive child the index of the next
/// pair.
/// </summary>
public static ReadOnlySpan<sbyte> BModeTree =>
[
-BDc, 2,
-BTm, 4,
-BVe, 6,
8, 12,
-BHe, 10,
-BRd, -BVr,
-BLd, 14,
-BVl, 16,
-BHd, -BHu,
];
/// <summary>
/// §11.5: kf_bmode_probs[above][left][9], flattened: the probabilities of the tree of a subblock mode given the
/// modes of the subblocks above and to the left.
/// </summary>
public static ReadOnlySpan<byte> KeyFrameBModeProbs =>
[
231, 120, 48, 89, 115, 113, 120, 152, 112,
152, 179, 64, 126, 170, 118, 46, 70, 95,
175, 69, 143, 80, 85, 82, 72, 155, 103,
56, 58, 10, 171, 218, 189, 17, 13, 152,
144, 71, 10, 38, 171, 213, 144, 34, 26,
114, 26, 17, 163, 44, 195, 21, 10, 173,
121, 24, 80, 195, 26, 62, 44, 64, 85,
170, 46, 55, 19, 136, 160, 33, 206, 71,
63, 20, 8, 114, 114, 208, 12, 9, 226,
81, 40, 11, 96, 182, 84, 29, 16, 36,
134, 183, 89, 137, 98, 101, 106, 165, 148,
72, 187, 100, 130, 157, 111, 32, 75, 80,
66, 102, 167, 99, 74, 62, 40, 234, 128,
41, 53, 9, 178, 241, 141, 26, 8, 107,
104, 79, 12, 27, 217, 255, 87, 17, 7,
74, 43, 26, 146, 73, 166, 49, 23, 157,
65, 38, 105, 160, 51, 52, 31, 115, 128,
87, 68, 71, 44, 114, 51, 15, 186, 23,
47, 41, 14, 110, 182, 183, 21, 17, 194,
66, 45, 25, 102, 197, 189, 23, 18, 22,
88, 88, 147, 150, 42, 46, 45, 196, 205,
43, 97, 183, 117, 85, 38, 35, 179, 61,
39, 53, 200, 87, 26, 21, 43, 232, 171,
56, 34, 51, 104, 114, 102, 29, 93, 77,
107, 54, 32, 26, 51, 1, 81, 43, 31,
39, 28, 85, 171, 58, 165, 90, 98, 64,
34, 22, 116, 206, 23, 34, 43, 166, 73,
68, 25, 106, 22, 64, 171, 36, 225, 114,
34, 19, 21, 102, 132, 188, 16, 76, 124,
62, 18, 78, 95, 85, 57, 50, 48, 51,
193, 101, 35, 159, 215, 111, 89, 46, 111,
60, 148, 31, 172, 219, 228, 21, 18, 111,
112, 113, 77, 85, 179, 255, 38, 120, 114,
40, 42, 1, 196, 245, 209, 10, 25, 109,
100, 80, 8, 43, 154, 1, 51, 26, 71,
88, 43, 29, 140, 166, 213, 37, 43, 154,
61, 63, 30, 155, 67, 45, 68, 1, 209,
142, 78, 78, 16, 255, 128, 34, 197, 171,
41, 40, 5, 102, 211, 183, 4, 1, 221,
51, 50, 17, 168, 209, 192, 23, 25, 82,
125, 98, 42, 88, 104, 85, 117, 175, 82,
95, 84, 53, 89, 128, 100, 113, 101, 45,
75, 79, 123, 47, 51, 128, 81, 171, 1,
57, 17, 5, 71, 102, 57, 53, 41, 49,
115, 21, 2, 10, 102, 255, 166, 23, 6,
38, 33, 13, 121, 57, 73, 26, 1, 85,
41, 10, 67, 138, 77, 110, 90, 47, 114,
101, 29, 16, 10, 85, 128, 101, 196, 26,
57, 18, 10, 102, 102, 213, 34, 20, 43,
117, 20, 15, 36, 163, 128, 68, 1, 26,
138, 31, 36, 171, 27, 166, 38, 44, 229,
67, 87, 58, 169, 82, 115, 26, 59, 179,
63, 59, 90, 180, 59, 166, 93, 73, 154,
40, 40, 21, 116, 143, 209, 34, 39, 175,
57, 46, 22, 24, 128, 1, 54, 17, 37,
47, 15, 16, 183, 34, 223, 49, 45, 183,
46, 17, 33, 183, 6, 98, 15, 32, 183,
65, 32, 73, 115, 28, 128, 23, 128, 205,
40, 3, 9, 115, 51, 192, 18, 6, 223,
87, 37, 9, 115, 59, 77, 64, 21, 47,
104, 55, 44, 218, 9, 54, 53, 130, 226,
64, 90, 70, 205, 40, 41, 23, 26, 57,
54, 57, 112, 184, 5, 41, 38, 166, 213,
30, 34, 26, 133, 152, 116, 10, 32, 134,
75, 32, 12, 51, 192, 255, 160, 43, 51,
39, 19, 53, 221, 26, 114, 32, 73, 255,
31, 9, 65, 234, 2, 15, 1, 118, 73,
88, 31, 35, 67, 102, 85, 55, 186, 85,
56, 21, 23, 111, 59, 205, 45, 37, 192,
55, 38, 70, 124, 73, 102, 1, 34, 98,
102, 61, 71, 37, 34, 53, 31, 243, 192,
69, 60, 71, 38, 73, 119, 28, 222, 37,
68, 45, 128, 34, 1, 47, 11, 245, 171,
62, 17, 19, 70, 146, 85, 55, 62, 70,
75, 15, 9, 9, 64, 255, 184, 119, 16,
37, 43, 37, 154, 100, 163, 85, 160, 1,
63, 9, 92, 136, 28, 64, 32, 201, 85,
86, 6, 28, 5, 64, 255, 25, 248, 1,
56, 8, 17, 132, 137, 255, 55, 116, 128,
58, 15, 20, 82, 135, 57, 26, 121, 40,
164, 50, 31, 137, 154, 133, 25, 35, 218,
51, 103, 44, 131, 131, 123, 31, 6, 158,
86, 40, 64, 135, 148, 224, 45, 183, 128,
22, 26, 17, 131, 240, 154, 14, 1, 209,
83, 12, 13, 54, 192, 255, 68, 47, 28,
45, 16, 21, 91, 64, 222, 7, 1, 197,
56, 21, 39, 155, 60, 138, 23, 102, 213,
85, 26, 85, 85, 128, 128, 32, 146, 171,
18, 11, 7, 63, 144, 171, 4, 4, 246,
35, 27, 10, 146, 174, 171, 12, 26, 128,
190, 80, 35, 99, 180, 80, 126, 54, 45,
85, 126, 47, 87, 176, 51, 41, 20, 32,
101, 75, 128, 139, 118, 146, 116, 128, 85,
56, 41, 15, 176, 236, 85, 37, 9, 62,
146, 36, 19, 30, 171, 255, 97, 27, 20,
71, 30, 17, 119, 118, 255, 17, 18, 138,
101, 38, 60, 138, 55, 70, 43, 26, 142,
138, 45, 61, 62, 219, 1, 81, 188, 64,
32, 41, 20, 117, 151, 142, 20, 21, 163,
112, 19, 12, 61, 195, 128, 48, 4, 24,
];
/// <summary>§14.1: dc_qlookup.</summary>
public static ReadOnlySpan<byte> DcQuant =>
[
4, 5, 6, 7, 8, 9, 10, 10, 11, 12,
13, 14, 15, 16, 17, 17, 18, 19, 20, 20,
21, 21, 22, 22, 23, 23, 24, 25, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 91, 93, 95, 96,
98, 100, 101, 102, 104, 106, 108, 110, 112, 114,
116, 118, 122, 124, 126, 128, 130, 132, 134, 136,
138, 140, 143, 145, 148, 151, 154, 157,
];
/// <summary>§14.1: ac_qlookup.</summary>
public static ReadOnlySpan<short> AcQuant =>
[
4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 60, 62, 64, 66, 68,
70, 72, 74, 76, 78, 80, 82, 84, 86, 88,
90, 92, 94, 96, 98, 100, 102, 104, 106, 108,
110, 112, 114, 116, 119, 122, 125, 128, 131, 134,
137, 140, 143, 146, 149, 152, 155, 158, 161, 164,
167, 170, 173, 177, 181, 185, 189, 193, 197, 201,
205, 209, 213, 217, 221, 225, 229, 234, 239, 245,
249, 254, 259, 264, 269, 274, 279, 284,
];
/// <summary>§13: the zigzag scan, from position in the token stream to raster index in the 4×4 block.</summary>
public static ReadOnlySpan<byte> Zigzag => [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
/// <summary>§13.3: the band of each coefficient position (a 17th entry, never a real position, keeps lookups simple).</summary>
public static ReadOnlySpan<byte> Bands => [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0];
/// <summary>§13.2: the probabilities of the extra bits of DCT_CAT3 to DCT_CAT6 (cat1 and cat2 are read inline).</summary>
public static ReadOnlySpan<byte> Cat3 => [173, 148, 140];
public static ReadOnlySpan<byte> Cat4 => [176, 155, 140, 135];
public static ReadOnlySpan<byte> Cat5 => [180, 157, 141, 134, 130];
public static ReadOnlySpan<byte> Cat6 => [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
/// <summary>Number of token probabilities: 4 block types × 8 bands × 3 contexts × 11 tree nodes.</summary>
public const int CoefficientProbCount = 4 * 8 * 3 * 11;
/// <summary>§13.5: default_coeff_probs, flattened [type][band][context][node].</summary>
public static ReadOnlySpan<byte> DefaultCoefficientProbs =>
[
// Block type 0
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128,
189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128,
106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128,
1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128,
181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128,
78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128,
1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128,
184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128,
77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128,
1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128,
170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128,
37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128,
1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128,
207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128,
102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128,
1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128,
177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128,
80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128,
1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
// Block type 1
198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62,
131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1,
68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128,
1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128,
184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128,
81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128,
1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128,
99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128,
23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128,
1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128,
109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128,
44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128,
1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128,
94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128,
22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128,
1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128,
124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128,
35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128,
1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128,
121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128,
45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128,
1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128,
203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128,
137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128,
// Block type 2
253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128,
175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128,
73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128,
1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128,
239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128,
155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128,
1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128,
201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128,
69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128,
1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128,
223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128,
141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128,
1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128,
190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128,
149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128,
247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128,
240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128,
1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128,
213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128,
55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
// Block type 3
202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255,
126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128,
61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128,
1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128,
166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128,
39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128,
1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128,
124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128,
24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128,
1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128,
149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128,
28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128,
1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128,
123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128,
20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128,
1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128,
168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128,
47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128,
1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128,
141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128,
42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128,
1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
];
/// <summary>§13.4: coeff_update_probs, flattened like <see cref="DefaultCoefficientProbs"/>.</summary>
public static ReadOnlySpan<byte> CoefficientUpdateProbs =>
[
// Block type 0
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255,
223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255,
249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255,
234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255,
239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255,
251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255,
250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
// Block type 1
217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255,
234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255,
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255,
255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255,
249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255,
247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255,
250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
// Block type 2
186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255,
234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255,
251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255,
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255,
255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
// Block type 3
248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255,
248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255,
255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255,
255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255,
248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255,
253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255,
255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255,
245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255,
253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255,
252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255,
249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255,
250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
}
+511
View File
@@ -0,0 +1,511 @@
using System.Buffers;
using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// Reads WebP files (RFC 9649): the simple formats (one VP8 or VP8L chunk) and the extended format (VP8X) with alpha
/// (ALPH, raw or compressed with VP8L, with its filtering), the colour profile (ICCP), EXIF and XMP. Of an animation
/// it decodes the first frame, placed and blended on a transparent canvas as its ANMF chunk says, and counts the
/// frames. The pixels come out as straight RGBA8; the EXIF orientation is reported, not applied.
/// </summary>
/// <remarks>
/// Strictness, as for PNG: data that ends before the last pixel of a picture is damaged (<see cref="ImageDecodeException"/>),
/// as is a RIFF size larger than the file or an ALPH chunk that cannot be decoded; unknown chunks and bytes after the
/// RIFF size are ignored, metadata chunks beyond <see cref="ImageLimits.MaxMetadataBytes"/> are skipped.
/// </remarks>
public static class WebPDecoder
{
private const uint Vp8 = 0x20385056; // "VP8 "
private const uint Vp8L = 0x4C385056; // "VP8L"
private const uint Vp8X = 0x58385056; // "VP8X"
private const uint Alph = 0x48504C41; // "ALPH"
private const uint Anim = 0x4D494E41; // "ANIM"
private const uint Anmf = 0x464D4E41; // "ANMF"
private const uint Iccp = 0x50434349; // "ICCP"
private const uint Exif = 0x46495845; // "EXIF"
private const uint Xmp = 0x20504D58; // "XMP "
/// <summary>Whether the bytes start like a WebP file (a RIFF of form WEBP).</summary>
public static bool IsWebP(ReadOnlySpan<byte> data) =>
data.Length >= 12 && data[..4].SequenceEqual("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8);
/// <summary>Size, frames and metadata of a WebP, without decoding the pixels.</summary>
/// <exception cref="ImageDecodeException">The file is damaged or not a WebP.</exception>
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
{
var bytes = AsArray(data, out var offset);
var file = Parse(bytes, offset, data.Length, limits ?? ImageLimits.Default, readMetadata: true);
return file.ToInfo();
}
/// <summary>Decodes a WebP to straight RGBA8 (the first frame of an animation, on its canvas).</summary>
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a WebP.</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) =>
Decode(data, out _, limits, pooled, readMetadata: false);
/// <summary>Decodes a WebP 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) =>
Decode(data, out info, limits, pooled, readMetadata: true);
private static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits, bool pooled, bool readMetadata)
{
limits ??= ImageLimits.Default;
var bytes = AsArray(data, out var offset);
var file = Parse(bytes, offset, data.Length, limits, readMetadata);
var image = RgbaImage.Create(file.Width, file.Height, limits, pooled);
try
{
if (file.FirstFrame is { } frame)
{
DrawFrame(bytes, frame, image, limits, pooled);
}
else
{
DecodePicture(bytes, file.Picture, image, limits);
}
}
catch
{
image.Dispose();
throw;
}
info = file.ToInfo();
return image;
}
private readonly record struct Chunk(uint Type, int Start, int Length);
/// <summary>A picture: its bitstream chunk (VP8 or VP8L) and, for VP8, its optional ALPH chunk.</summary>
private readonly record struct Picture(Chunk Bitstream, Chunk? Alpha, int Width, int Height, bool HasAlpha);
private sealed record Frame(int X, int Y, bool Blend, Picture Picture);
private sealed class WebPFile
{
public int Width;
public int Height;
public int FrameCount = 1;
public bool HasAlpha;
public Picture Picture;
public Frame? FirstFrame;
public byte[]? Exif;
public byte[]? Icc;
public string? Xmp;
public ImageInfo ToInfo() => new(
ImageFormat.WebP,
Width,
Height,
FrameCount,
HasAlpha,
Exif is null && Icc is null && Xmp is null
? ImageMetadata.Empty
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp });
}
private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata)
{
var span = data.AsSpan(offset, length);
if (!IsWebP(span))
{
throw new ImageDecodeException("Non è un file WebP.");
}
var riffSize = BinaryPrimitives.ReadUInt32LittleEndian(span[4..]);
if (riffSize < 4)
{
throw new ImageDecodeException("WebP danneggiato: misura RIFF non valida.");
}
if (riffSize > length - 8)
{
throw new ImageDecodeException("WebP troncato: il file è più corto della misura RIFF.");
}
var chunks = ReadChunks(data, offset + 12, (int)riffSize - 4);
if (chunks.Count == 0)
{
throw new ImageDecodeException("WebP danneggiato: nessun blocco dopo l'intestazione RIFF.");
}
var file = new WebPFile();
var first = chunks[0];
if (first.Type == Vp8 || first.Type == Vp8L)
{
file.Picture = ReadPicture(data, first, null);
file.Width = file.Picture.Width;
file.Height = file.Picture.Height;
file.HasAlpha = file.Picture.HasAlpha;
return file;
}
if (first.Type != Vp8X)
{
throw new ImageDecodeException("WebP danneggiato: il primo blocco non è VP8, VP8L né VP8X.");
}
if (first.Length < 10)
{
throw new ImageDecodeException("WebP danneggiato: blocco VP8X troppo corto.");
}
var header = data.AsSpan(first.Start, 10);
var flags = header[0];
file.Width = (int)ReadUInt24(header[4..]) + 1;
file.Height = (int)ReadUInt24(header[7..]) + 1;
if ((long)file.Width * file.Height > uint.MaxValue)
{
throw new ImageDecodeException("WebP danneggiato: la tela VP8X è più grande di quanto il formato ammetta.");
}
var animated = (flags & 0x02) != 0;
file.HasAlpha = (flags & 0x10) != 0;
var budget = limits.MaxMetadataBytes;
Chunk? alpha = null;
Chunk? bitstream = null;
var frames = 0;
for (var i = 1; i < chunks.Count; i++)
{
var chunk = chunks[i];
switch (chunk.Type)
{
case Anmf:
if (frames++ == 0)
{
file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height);
}
break;
case Alph:
alpha ??= chunk;
break;
case Vp8:
case Vp8L:
bitstream ??= chunk;
break;
case Iccp when readMetadata && file.Icc is null && chunk.Length <= budget:
file.Icc = data.AsSpan(chunk.Start, chunk.Length).ToArray();
budget -= chunk.Length;
break;
case Exif when readMetadata && file.Exif is null && chunk.Length <= budget:
var exif = data.AsSpan(chunk.Start, chunk.Length);
file.Exif = (exif.StartsWith("Exif\0\0"u8) ? exif[6..] : exif).ToArray();
budget -= chunk.Length;
break;
case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget:
file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length);
budget -= chunk.Length;
break;
}
}
if (frames > 0)
{
file.FrameCount = frames;
file.HasAlpha |= file.FirstFrame!.Picture.HasAlpha;
return file;
}
if (animated && bitstream is null)
{
throw new ImageDecodeException("WebP danneggiato: animazione senza fotogrammi.");
}
if (bitstream is not { } still)
{
throw new ImageDecodeException("WebP danneggiato: manca il blocco con l'immagine.");
}
file.Picture = ReadPicture(data, still, alpha);
if (file.Picture.Width != file.Width || file.Picture.Height != file.Height)
{
throw new ImageDecodeException("WebP danneggiato: l'immagine non ha la misura della tela VP8X.");
}
file.HasAlpha |= file.Picture.HasAlpha;
return file;
}
private static List<Chunk> ReadChunks(byte[] data, int start, int length)
{
var chunks = new List<Chunk>();
var pos = start;
var end = start + length;
while (end - pos >= 8)
{
var type = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(pos));
var size = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(pos + 4));
if (size > (uint)(end - pos - 8))
{
throw new ImageDecodeException("WebP troncato: un blocco dichiara più byte di quelli che il file contiene.");
}
chunks.Add(new Chunk(type, pos + 8, (int)size));
pos += 8 + (int)size;
if ((size & 1) == 1 && pos < end)
{
pos++; // padding to an even size
}
}
return chunks;
}
private static Picture ReadPicture(byte[] data, Chunk bitstream, Chunk? alpha)
{
var payload = data.AsSpan(bitstream.Start, bitstream.Length);
if (bitstream.Type == Vp8L)
{
var (width, height, alphaUsed) = Vp8LDecoder.ReadHeader(payload);
return new Picture(bitstream, null, width, height, alphaUsed);
}
var (w, h) = Vp8Decoder.ReadSize(payload);
if (alpha is { } a && a.Length == 0)
{
throw new ImageDecodeException("WebP danneggiato: blocco ALPH vuoto.");
}
return new Picture(bitstream, alpha, w, h, alpha is not null);
}
private static Frame ReadFrame(byte[] data, Chunk anmf, int canvasWidth, int canvasHeight)
{
if (anmf.Length < 16)
{
throw new ImageDecodeException("WebP danneggiato: blocco ANMF troppo corto.");
}
var header = data.AsSpan(anmf.Start, 16);
var x = 2 * (int)ReadUInt24(header);
var y = 2 * (int)ReadUInt24(header[3..]);
var width = (int)ReadUInt24(header[6..]) + 1;
var height = (int)ReadUInt24(header[9..]) + 1;
var blend = (header[15] & 0x02) == 0;
if ((long)x + width > canvasWidth || (long)y + height > canvasHeight)
{
throw new ImageDecodeException("WebP danneggiato: un fotogramma esce dalla tela.");
}
Chunk? alpha = null;
Chunk? bitstream = null;
foreach (var chunk in ReadChunks(data, anmf.Start + 16, anmf.Length - 16))
{
if (chunk.Type == Alph)
{
alpha ??= chunk;
}
else if (chunk.Type is Vp8 or Vp8L && bitstream is null)
{
bitstream = chunk;
}
}
if (bitstream is not { } frameBitstream)
{
throw new ImageDecodeException("WebP danneggiato: un fotogramma non ha l'immagine.");
}
var picture = ReadPicture(data, frameBitstream, frameBitstream.Type == Vp8 ? alpha : null);
if (picture.Width != width || picture.Height != height)
{
throw new ImageDecodeException("WebP danneggiato: l'immagine di un fotogramma non ha la misura del suo blocco ANMF.");
}
return new Frame(x, y, blend, picture);
}
private static void DecodePicture(byte[] data, Picture picture, RgbaImage target, ImageLimits limits)
{
var chunk = picture.Bitstream;
if (chunk.Type == Vp8L)
{
Vp8LDecoder.Decode(data, chunk.Start, chunk.Length, limits, target);
return;
}
Vp8Decoder.Decode(data, chunk.Start, chunk.Length, limits, target);
if (picture.Alpha is { } alpha)
{
WebPAlpha.Decode(data, alpha.Start, alpha.Length, limits, target);
}
}
// The first frame of an animation on a transparent canvas: copied, or blended over the canvas (RFC 9649 §2.7.1.1).
private static void DrawFrame(byte[] data, Frame frame, RgbaImage canvas, ImageLimits limits, bool pooled)
{
var picture = frame.Picture;
if (frame.X == 0 && frame.Y == 0 && picture.Width == canvas.Width && picture.Height == canvas.Height && !frame.Blend)
{
DecodePicture(data, picture, canvas, limits);
return;
}
limits.CheckWorkingBytes((long)picture.Width * picture.Height * RgbaImage.BytesPerPixel);
using var image = pooled ? RgbaImage.Rent(picture.Width, picture.Height) : new RgbaImage(picture.Width, picture.Height);
DecodePicture(data, picture, image, limits);
for (var y = 0; y < picture.Height; y++)
{
var source = image.GetRow(y);
var destination = canvas.GetRow(frame.Y + y).Slice(frame.X * 4, picture.Width * 4);
if (!frame.Blend)
{
source.CopyTo(destination);
continue;
}
for (var i = 0; i < source.Length; i += 4)
{
Blend(source.Slice(i, 4), destination.Slice(i, 4));
}
}
}
/// <summary>
/// Alpha blending of RFC 9649 on straight alpha: A = As + Ad·(1 − As); RGB = (RGBs·As + RGBd·Ad·(1 − As)) / A, and
/// 0 when A is 0.
/// </summary>
internal static void Blend(ReadOnlySpan<byte> source, Span<byte> destination)
{
int sa = source[3];
if (sa == 255)
{
source.CopyTo(destination);
return;
}
var da = destination[3] * (255 - sa); // ×255
var a = (sa * 255) + da; // ×255
if (a == 0)
{
destination.Clear();
return;
}
for (var c = 0; c < 3; c++)
{
destination[c] = (byte)((((source[c] * sa * 255) + (destination[c] * da)) + (a / 2)) / a);
}
destination[3] = (byte)((a + 127) / 255);
}
private static uint ReadUInt24(ReadOnlySpan<byte> b) => (uint)(b[0] | (b[1] << 8) | (b[2] << 16));
private static byte[] AsArray(ReadOnlyMemory<byte> data, out int offset)
{
if (MemoryMarshal.TryGetArray(data, out var segment) && segment.Array is not null)
{
offset = segment.Offset;
return segment.Array;
}
offset = 0;
return data.ToArray();
}
}
/// <summary>The ALPH chunk of RFC 9649 §2.7.1.2: raw or VP8L-compressed alpha, then the inverse of its filter.</summary>
internal static class WebPAlpha
{
/// <summary>Decodes the alpha plane of the chunk payload and writes it into the alpha bytes of <paramref name="target"/>.</summary>
public static void Decode(byte[] data, int start, int length, ImageLimits limits, RgbaImage target)
{
var width = target.Width;
var height = target.Height;
var header = data[start];
var compression = header & 3;
var filter = (header >> 2) & 3;
var preprocessing = (header >> 4) & 3;
if (compression > 1 || preprocessing > 1 || (header >> 6) != 0)
{
throw new ImageDecodeException("WebP danneggiato: intestazione ALPH non valida.");
}
var count = width * height;
limits.CheckWorkingBytes(count);
var alpha = ArrayPool<byte>.Shared.Rent(count);
try
{
var plane = alpha.AsSpan(0, count);
if (compression == 0)
{
if (length - 1 < count)
{
throw new ImageDecodeException("WebP troncato: l'alfa del blocco ALPH è incompleta.");
}
data.AsSpan(start + 1, count).CopyTo(plane);
}
else
{
Vp8LDecoder.DecodeAlpha(data, start + 1, length - 1, width, height, limits, plane);
}
Unfilter(plane, width, height, filter);
var pixels = target.Pixels;
for (var i = 0; i < count; i++)
{
pixels[(i * 4) + 3] = plane[i];
}
}
finally
{
ArrayPool<byte>.Shared.Return(alpha);
}
}
/// <summary>
/// Undoes the prediction filter of the alpha plane: 1 horizontal (from the left), 2 vertical (from above), 3
/// gradient (left + above − above-left, clamped). The first pixel is predicted from 0, the rest of the first row
/// from the left and the first column from above.
/// </summary>
internal static void Unfilter(Span<byte> plane, int width, int height, int filter)
{
if (filter == 0)
{
return;
}
for (var x = 1; x < width; x++)
{
plane[x] += plane[x - 1];
}
for (var y = 1; y < height; y++)
{
var row = plane.Slice(y * width, width);
var above = plane.Slice((y - 1) * width, width);
row[0] += above[0];
switch (filter)
{
case 1:
for (var x = 1; x < width; x++)
{
row[x] += row[x - 1];
}
break;
case 2:
for (var x = 1; x < width; x++)
{
row[x] += above[x];
}
break;
default:
for (var x = 1; x < width; x++)
{
row[x] += (byte)Math.Clamp(row[x - 1] + above[x] - above[x - 1], 0, 255);
}
break;
}
}
}
}
+183
View File
@@ -0,0 +1,183 @@
using System.Buffers.Binary;
using System.Text;
namespace Febe.Core.Codecs.Images;
/// <summary>Options of <see cref="WebPEncoder"/>.</summary>
public sealed record WebPEncoderOptions
{
/// <summary>The options used when a caller passes none.</summary>
public static WebPEncoderOptions Default { get; } = new();
/// <summary>
/// EXIF to write in an EXIF chunk: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by the «Exif\0\0»
/// of a JPEG APP1 segment, which is removed.
/// </summary>
public byte[]? Exif { get; init; }
/// <summary>ICC profile to write in an ICCP chunk.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>XMP packet to write in an XMP chunk (UTF-8).</summary>
public string? Xmp { get; init; }
/// <summary>The tools of the lossless encoder (tests turn them on and off one by one).</summary>
internal Vp8LEncoderSettings Lossless { get; init; } = Vp8LEncoderSettings.Default;
}
/// <summary>
/// Writes lossless WebP files (RFC 9649): one VP8L chunk, inside the extended format (VP8X, then ICCP, VP8L, EXIF,
/// XMP) when there is metadata. Every pixel comes back exactly, the colour under a transparent pixel included.
/// </summary>
public static class WebPEncoder
{
/// <summary>Largest width or height a WebP picture can have.</summary>
public const int MaxDimension = 16384;
/// <summary>The WebP file of <paramref name="image"/>.</summary>
/// <exception cref="ArgumentOutOfRangeException">The image is wider or taller than <see cref="MaxDimension"/>.</exception>
/// <exception cref="ArgumentException">The EXIF block is not a TIFF structure.</exception>
public static byte[] Encode(RgbaImage image, WebPEncoderOptions? options = null)
{
using var output = new MemoryStream();
Encode(image, output, options);
return output.ToArray();
}
/// <summary>Writes the WebP file of <paramref name="image"/> to <paramref name="output"/>.</summary>
public static void Encode(RgbaImage image, Stream output, WebPEncoderOptions? options = null)
{
ArgumentNullException.ThrowIfNull(image);
ArgumentNullException.ThrowIfNull(output);
options ??= WebPEncoderOptions.Default;
var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
var xmp = options.Xmp is { } givenXmp ? Encoding.UTF8.GetBytes(givenXmp) : null;
var bitstream = EncodeBitstream(image, options.Lossless);
var alpha = !image.IsOpaque();
var extended = exif is not null || options.IccProfile is not null || xmp is not null;
var size = 4L + ChunkSize(bitstream.Length);
if (extended)
{
size += ChunkSize(10) + ChunkSize(options.IccProfile?.Length) + ChunkSize(exif?.Length) + ChunkSize(xmp?.Length);
}
if (size > uint.MaxValue - 8)
{
throw new ArgumentException("The WebP file would be larger than RIFF allows.", nameof(image));
}
Span<byte> header = stackalloc byte[12];
"RIFF"u8.CopyTo(header);
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)size);
"WEBP"u8.CopyTo(header[8..]);
output.Write(header);
if (extended)
{
Span<byte> vp8x = stackalloc byte[10];
vp8x.Clear();
vp8x[0] = (byte)((options.IccProfile is not null ? 0x20 : 0) | (alpha ? 0x10 : 0) | (exif is not null ? 0x08 : 0) | (xmp is not null ? 0x04 : 0));
WriteUInt24(vp8x[4..], image.Width - 1);
WriteUInt24(vp8x[7..], image.Height - 1);
WriteChunk(output, "VP8X"u8, vp8x);
if (options.IccProfile is { } icc)
{
WriteChunk(output, "ICCP"u8, icc);
}
}
WriteChunk(output, "VP8L"u8, bitstream);
if (exif is not null)
{
WriteChunk(output, "EXIF"u8, exif);
}
if (xmp is not null)
{
WriteChunk(output, "XMP "u8, xmp);
}
}
/// <summary>The VP8L bitstream (signature, header, image stream) of <paramref name="image"/>.</summary>
internal static byte[] EncodeBitstream(RgbaImage image, Vp8LEncoderSettings settings)
{
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Width, MaxDimension, nameof(image));
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Height, MaxDimension, nameof(image));
var argb = ToArgb(image);
var writer = new Vp8LBitWriter(image.Length / 4);
writer.WriteBits(Vp8LDecoder.Signature, 8);
writer.WriteBits((uint)(image.Width - 1), 14);
writer.WriteBits((uint)(image.Height - 1), 14);
writer.WriteBits(image.IsOpaque() ? 0u : 1u, 1);
writer.WriteBits(0, 3);
Vp8LEncoder.WriteImageStream(writer, argb, image.Width, image.Height, settings);
return writer.ToArray();
}
/// <summary>
/// The headerless image stream of an ALPH chunk compressed with VP8L: the alpha values in the green channel.
/// </summary>
internal static byte[] EncodeAlphaStream(ReadOnlySpan<byte> alpha, int width, int height, Vp8LEncoderSettings settings)
{
var argb = new uint[width * height];
for (var i = 0; i < argb.Length; i++)
{
argb[i] = 0xFF000000 | ((uint)alpha[i] << 8);
}
var writer = new Vp8LBitWriter(argb.Length / 4);
Vp8LEncoder.WriteImageStream(writer, argb, width, height, settings);
return writer.ToArray();
}
internal static uint[] ToArgb(RgbaImage image)
{
var pixels = image.Pixels;
var argb = new uint[image.Width * image.Height];
for (var i = 0; i < argb.Length; i++)
{
var o = i * 4;
argb[i] = ((uint)pixels[o + 3] << 24) | ((uint)pixels[o] << 16) | ((uint)pixels[o + 1] << 8) | pixels[o + 2];
}
return argb;
}
private static long ChunkSize(int? length) => length is { } n ? 8L + n + (n & 1) : 0;
private static void WriteChunk(Stream output, ReadOnlySpan<byte> type, ReadOnlySpan<byte> payload)
{
Span<byte> header = stackalloc byte[8];
type.CopyTo(header);
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)payload.Length);
output.Write(header);
output.Write(payload);
if ((payload.Length & 1) == 1)
{
output.WriteByte(0);
}
}
private static void WriteUInt24(Span<byte> destination, int value)
{
destination[0] = (byte)value;
destination[1] = (byte)(value >> 8);
destination[2] = (byte)(value >> 16);
}
private static byte[] ExifPayload(byte[] exif)
{
ReadOnlySpan<byte> span = exif;
if (span.StartsWith("Exif\0\0"u8))
{
span = span[6..];
}
if (span.Length < 8 || !(span.StartsWith("II*\0"u8) || span.StartsWith("MM\0*"u8)))
{
throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif));
}
return span.ToArray();
}
}