diff --git a/docs/decisioni.md b/docs/decisioni.md index bb4eff6..a88a50d 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -423,3 +423,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Insieme fisso di immagini di riferimento per i codec di casa in `tests/Febe.Tests/Imaging/Riferimenti` (57 casi, circa 2,2 MB, descritti in `LEGGIMI.md`): per ogni caso un file d'ingresso (PNG, GIF e BMP costruiti a mano dalle specifiche; PNG, JPEG base e WebP codificati da SkiaSharp; JPEG con un `APP1` EXIF di orientamento inserito a mano) e `.atteso.png`, la lettura di SkiaSharp 4.153.1 in RGBA a 8 bit non premoltiplicata, raddrizzata. Generato una volta sola, con il permesso di Alberto, da un programma usa e getta fuori dal repository; contenuto solo sintetico. Le immagini attese sono PNG RGBA a 8 bit senza interlacciamento, filtro 0, un solo `IDAT`, scritti a mano e non dal codificatore di SkiaSharp, così le legge il lettore PNG di casa (passo 2 di C1); fino ad allora `ReferenceSetTests` controlla solo la struttura (firme, misure, CRC dei blocchi, nessun file in più o in meno). JPEG progressivo, intervalli di ripristino e CMYK/Adobe non hanno riferimento: li proveranno codificatori di prova nostri dalla T.81 (allegati F e G) con controlli sui coefficienti. Estensioni delle immagini `binary` in `.gitattributes`, `elenco.txt` con `eol=lf` | SkiaSharp esce da Febe (C1): serve un termine di confronto prima di toglierlo, e dopo non si potrà più generarlo. Un riferimento che solo SkiaSharp sapesse leggere sarebbe inutile proprio quando serve | | 2026-11-18 | Base dei codec d'immagine di casa in `src/Febe.Core/Codecs/Images` (spazio dei nomi `Febe.Core.Codecs.Images`, accanto a `Codecs/Containers` del ramo `funzione/decoder-h264`): `RgbaImage` (RGBA a 8 bit non premoltiplicata, array suo o preso dal pool e reso con `Dispose`), `ImageLimits` (predefiniti 65535 pixel per lato, 100 milioni di pixel come `ImageDecoding.MaxDecodedPixels`, 512 MiB di memoria di lavoro, 16 MiB di metadati decompressi), `ImageDecodeException` con `ImageLimitException` e `ImageFormatNotSupportedException`, `ImageFormatSniffer`, la facciata `ImageDecoder`; lettore e scrittore PNG, lettori GIF e BMP dalle specifiche, CRC-32 e LZW scritti in casa, zlib di `System.IO.Compression`. Scelte di lettura: i campioni a 16 bit tengono il byte alto e le maschere BMP sotto gli 8 bit si scalano con arrotondamento (così i 37 riferimenti PNG, GIF e BMP coincidono byte per byte); nessuna gestione del colore (profilo ICC, gamma); un blocco PNG ausiliario con il CRC sbagliato si salta, uno critico ferma la lettura; un PNG senza `IEND` dopo dati completi si accetta, uno tagliato prima no; un GIF tagliato o con dati LZW rotti dà ciò che si è letto, il resto trasparente; del GIF solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo, più il numero dei fotogrammi; nel BMP l'alfa viene solo da una maschera alfa di `BI_BITFIELDS`/`BI_ALPHABITFIELDS`, i pixel saltati da RLE restano trasparenti, `BI_PNG` passa al lettore PNG, `BI_JPEG` e 64 bit non si leggono. `Identify` legge misura, fotogrammi e metadati senza applicare i limiti di misura; `Decode` li applica prima di allocare. Lo scrittore PNG scrive RGB o RGBA a 8 bit (RGB in automatico se tutto è opaco), per ogni riga il filtro con la minima somma dei valori assoluti (specifica PNG §12.8), `IDAT` da 64 KiB e, a richiesta, `eXIf`, `iCCP` e l'XMP in un `iTXt` | C1: SkiaSharp esce da Febe e niente componenti esterni (decisione di Alberto del 18 novembre 2026). Lettori tolleranti dove lo sono i browser (GIF, metadati), severi dove un'immagine letta a metà passerebbe per buona (PNG, BMP); limiti controllati prima di ogni allocazione, perché pochi byte di un file possono chiedere gigabyte | | 2026-11-18 | Lettore e scrittore JPEG di casa (`JpegDecoder`, `JpegEncoder`), scritti dalla T.81: il lettore fa sequenziale di base ed esteso, progressivo, senza perdita, con Huffman e con codifica aritmetica, a 8 e 12 bit (senza perdita da 2 a 16), qualunque campionamento, ripristino, DNL; IDCT esatta in virgola mobile e crominanza con il filtro triangolare dove il rapporto è 2; colori secondo JFIF, Adobe APP14 (CMYK e YCCK invertiti come li scrive Adobe) e identificatori `R`, `G`, `B`; tabelle dell'allegato K quando manca `DHT` (Motion JPEG); dati troncati dentro una scansione = file danneggiato, EOI mancante e byte dopo EOI accettati; gerarchici e JPEG a 2 componenti rifiutati come formato non letto. L'orientamento EXIF va in `ImageMetadata.Orientation` e non si applica ai pixel. Lo scrittore fa solo il sequenziale di base (qualità 1–100 sulle tabelle dell'allegato K, 4:2:0 e 4:4:4, grigio, ripristino) con EXIF, ICC a pezzi, XMP e commenti. Progressivo, aritmetico, 12 bit e senza perdita si provano con un codificatore di prova (`tests/Febe.Tests/Imaging/JpegTestEncoder.cs`) confrontando i coefficienti con la codifica di base; contro SkiaSharp la tolleranza è PSNR ≥ 40 dB per canale e ≤ 0,1% di pixel con scarto oltre 16 | Tappa C1, passo 3: niente componenti esterni (decisione del 18 novembre 2026). Due lettori JPEG corretti differiscono per gli arrotondamenti, quindi contro il riferimento serve una soglia; il nostro sta fra 59 e 67 dB. La codifica aritmetica è verificata solo con il nostro codificatore e le tabelle della specifica: nessun file di riferimento esterno | +| 2026-11-18 | Lettore e scrittore WebP di casa (`WebPDecoder`, `WebPEncoder`), scritti dalla RFC 9649 e, per VP8, dalla RFC 6386: il lettore fa VP8 con perdita (decodificatore booleano, segmenti, modi intra, DCT e WHT, filtro semplice e normale, più partizioni), VP8L senza perdita (codici prefissi, cache dei colori, le quattro trasformate), `ALPH` grezzo e compresso con ogni filtro, VP8X con ICCP, EXIF (tolto il prefisso «Exif» se c'è) e XMP; di un'animazione solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo di `ANIM`, con lo scostamento di `ANMF` e la fusione della specifica, più il numero dei fotogrammi. Scelte di lettura: YUV→RGB BT.601 a intervallo ridotto in virgola fissa a 16 bit e crominanza ricampionata con i pesi 9/3/3/1 (così i quattro riferimenti con perdita stanno fra 68,7 e 74,4 dB, scarto massimo 1, alfa esatta; i quattro senza perdita coincidono); severo dove un'immagine letta a metà passerebbe per buona: dimensione RIFF oltre il file, blocco oltre la fine, tela diversa dall'immagine, trasformata ripetuta, codice prefisso incompleto, distanza prima dell'inizio, dati VP8 finiti prima dell'ultimo macroblocco (si tollera un solo byte di riempimento a zero, perché il codificatore booleano chiude con byte che il lettore può non usare), `ALPH` corto o con bit riservati; i modi 14 e 15 del predittore VP8L, non definiti, valgono come 0. Lo scrittore fa solo VP8L senza perdita (tavolozza fino a 256 colori, sottrazione del verde, predittore per blocchi, trasformata del colore, LZ77 con catene di hash, cache dei colori scelta stimando l'entropia, codici di Huffman limitati a 15 bit) e il formato esteso VP8X solo se ci sono metadati, nell'ordine VP8X, ICCP, VP8L, EXIF, XMP | Tappa C1, passo 4: niente componenti esterni (decisione del 18 novembre 2026). Uno scrittore con perdita servirebbe solo a file più piccoli, e la libreria conserva gli originali: senza perdita i 57 riferimenti stanno all'88% del PNG di casa, e sul riferimento grande 70952 byte contro i 64406 di libwebp | diff --git a/src/Febe.Core/Codecs/Images/ImageDecoder.cs b/src/Febe.Core/Codecs/Images/ImageDecoder.cs index 302d9f8..d653068 100644 --- a/src/Febe.Core/Codecs/Images/ImageDecoder.cs +++ b/src/Febe.Core/Codecs/Images/ImageDecoder.cs @@ -7,7 +7,7 @@ namespace Febe.Core.Codecs.Images; public static class ImageDecoder { /// Whether Febe has a decoder for . - public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.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; /// Size, frames and metadata of an image, without decoding the pixels. /// The format is not known or has no decoder yet. @@ -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), }; diff --git a/src/Febe.Core/Codecs/Images/Vp8BoolDecoder.cs b/src/Febe.Core/Codecs/Images/Vp8BoolDecoder.cs new file mode 100644 index 0000000..4f13a4f --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8BoolDecoder.cs @@ -0,0 +1,131 @@ +using System.Numerics; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// The boolean entropy decoder of VP8 (RFC 6386 §7): each call decodes one bit whose probability of being 0 is +/// prob/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. +/// +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(); + } + + /// + /// 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. + /// + 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; + } + + /// An unsigned value of bits, most significant first, each with probability ½ (L(n)). + public int GetLiteral(int bits) + { + var v = 0; + while (bits-- > 0) + { + v = (v << 1) | GetBit(128); + } + + return v; + } + + /// A magnitude of bits followed by a sign bit, as the frame header writes deltas. + public int GetSignedLiteral(int bits) + { + var v = GetLiteral(bits); + return GetBit(128) == 1 ? -v : v; + } + + /// An optional signed delta: a flag, then ; 0 when the flag is clear. + public int GetOptionalSigned(int bits) => GetBit(128) == 1 ? GetSignedLiteral(bits) : 0; + + /// + /// 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 probs[offset + i/2]. + /// + public int ReadTree(ReadOnlySpan tree, ReadOnlySpan 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; + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8Decoder.cs b/src/Febe.Core/Codecs/Images/Vp8Decoder.cs new file mode 100644 index 0000000..34f764b --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8Decoder.cs @@ -0,0 +1,862 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +/// +/// 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. +/// +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; + } + + /// The size of a VP8 key frame, after checking its frame tag and start code. + /// The bytes are not a VP8 key frame that can be shown. + public static (int Width, int Height) ReadSize(ReadOnlySpan 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); + } + + /// + /// Decodes the VP8 frame in [..+] into + /// , which must have the frame's size; every alpha byte is set to 255. + /// + 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(); + } + } + + /// + /// 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). + /// + 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.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.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 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 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.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; + + /// Edge limit, interior limit and threshold for a macroblock, and whether its inner edges are filtered. + 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); + } +} + +/// BT.601 YUV (studio range) to RGB in 16-bit fixed point. +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 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 f) + { + var table = new int[256]; + for (var i = 0; i < 256; i++) + { + table[i] = f(i); + } + + return table; + } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs b/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs new file mode 100644 index 0000000..ded00d7 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs @@ -0,0 +1,692 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +internal sealed class Vp8LDecoder +{ + /// The byte every VP8L bitstream starts with. + 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 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 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; + } + + /// Size and alpha hint of a VP8L bitstream, from its five-byte header. + /// The bytes are not a VP8L header. + public static (int Width, int Height, bool AlphaUsed) ReadHeader(ReadOnlySpan 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); + } + + /// Decodes a whole VP8L bitstream into , which must have its size. + 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.Shared.Return(argb); + } + } + + /// + /// 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. + /// + public static void DecodeAlpha(byte[] data, int start, int length, int width, int height, ImageLimits limits, Span 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.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(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.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.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 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 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)); + } + + /// The (dx, dy) of short distance code 1-120. + 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 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."); +} diff --git a/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs b/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs new file mode 100644 index 0000000..0e7d501 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs @@ -0,0 +1,275 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +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(); + } + + /// Whether bits past the end of the data were consumed. + public bool EndOfStream { get; private set; } + + /// Reads bits (0-24), least significant first. + 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; + } + + /// At least 32 bits ready for when the data has them; zeros past the end. + 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; + } + } +} + +/// +/// 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. +/// +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; + } + + /// The symbol of a code that has only one (read with zero bits), or −1. + public int SingleSymbol { get; } + + /// Entries of the decoding tables, for the memory budget. + public int TableSize => _table.Length; + + /// + /// 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. + /// + public static Vp8LHuffman? Build(ReadOnlySpan lengths) + { + Span 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 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 longest = stackalloc byte[1 << RootBits]; + longest.Clear(); + var codes = new int[lengths.Length]; + { + Span 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 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); + } + + /// Reads one symbol. + 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs new file mode 100644 index 0000000..cf04c23 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs @@ -0,0 +1,1075 @@ +using System.Buffers; + +namespace Febe.Core.Codecs.Images; + +/// Writes bits least significant first, as WebP lossless reads them. +internal sealed class Vp8LBitWriter +{ + private byte[] _buffer; + private int _length; + private ulong _accumulator; + private int _bits; + + public Vp8LBitWriter(int capacity = 4096) + { + _buffer = new byte[Math.Max(16, capacity)]; + } + + /// Bits written so far. + public long BitLength => ((long)_length * 8) + _bits; + + /// Writes the low bits (0-32) of . + public void WriteBits(uint value, int n) + { + if (n == 0) + { + return; + } + + _accumulator |= (ulong)(value & (uint)((1UL << n) - 1)) << _bits; + _bits += n; + while (_bits >= 8) + { + if (_length == _buffer.Length) + { + Array.Resize(ref _buffer, _buffer.Length * 2); + } + + _buffer[_length++] = (byte)_accumulator; + _accumulator >>= 8; + _bits -= 8; + } + } + + /// The bytes written, the last one padded with zero bits. + public byte[] ToArray() + { + var result = new byte[_length + (_bits > 0 ? 1 : 0)]; + _buffer.AsSpan(0, _length).CopyTo(result); + if (_bits > 0) + { + result[_length] = (byte)_accumulator; + } + + return result; + } +} + +/// A prefix code for writing: the length and the bit-reversed canonical code of every symbol. +internal sealed class Vp8LPrefixCode +{ + private Vp8LPrefixCode(byte[] lengths, ushort[] codes, bool single) + { + Lengths = lengths; + Codes = codes; + IsSingle = single; + } + + /// The code length of each symbol (0 when unused). + public byte[] Lengths { get; } + + /// The code of each symbol, reversed so that it is written least significant bit first. + public ushort[] Codes { get; } + + /// Whether at most one symbol is used: it is then written with zero bits. + public bool IsSingle { get; } + + public void Write(Vp8LBitWriter writer, int symbol) + { + if (!IsSingle) + { + writer.WriteBits(Codes[symbol], Lengths[symbol]); + } + } + + /// The length-limited code for the given symbol counts. + public static Vp8LPrefixCode FromCounts(ReadOnlySpan counts, int maxLength) + { + var lengths = new byte[counts.Length]; + var used = 0; + var last = 0; + for (var i = 0; i < counts.Length; i++) + { + if (counts[i] > 0) + { + used++; + last = i; + } + } + + if (used <= 1) + { + lengths[last] = 1; + return new Vp8LPrefixCode(lengths, new ushort[counts.Length], single: true); + } + + HuffmanLengths(counts, maxLength, lengths); + return new Vp8LPrefixCode(lengths, CanonicalCodes(lengths), single: false); + } + + private static ushort[] CanonicalCodes(byte[] lengths) + { + Span count = stackalloc int[Vp8LHuffman.MaxCodeLength + 1]; + foreach (var len in lengths) + { + count[len]++; + } + + count[0] = 0; + Span next = stackalloc int[Vp8LHuffman.MaxCodeLength + 2]; + var code = 0; + for (var len = 1; len <= Vp8LHuffman.MaxCodeLength; len++) + { + code = (code + count[len - 1]) << 1; + next[len] = code; + } + + var codes = new ushort[lengths.Length]; + for (var s = 0; s < lengths.Length; s++) + { + if (lengths[s] > 0) + { + codes[s] = (ushort)Vp8LHuffman.Reverse(next[lengths[s]]++, lengths[s]); + } + } + + return codes; + } + + // Huffman code lengths of the used symbols, at most maxLength: if the tree is too deep, the counts are flattened + // (divided, keeping every used symbol at least 1) and the tree is built again. + private static void HuffmanLengths(ReadOnlySpan counts, int maxLength, byte[] lengths) + { + var n = counts.Length; + var weights = new long[2 * n]; + var parent = new int[2 * n]; + var depth = new int[2 * n]; + for (var shift = 0; ; shift++) + { + var queue = new PriorityQueue(); + var nodes = 0; + var leaves = new List(); + for (var s = 0; s < n; s++) + { + if (counts[s] > 0) + { + var w = Math.Max(1L, (long)counts[s] >> shift); + weights[nodes] = w; + leaves.Add(s); + queue.Enqueue(nodes, (w << 20) | (uint)nodes); + nodes++; + } + } + + var leafCount = nodes; + while (queue.Count > 1) + { + var a = queue.Dequeue(); + var b = queue.Dequeue(); + weights[nodes] = weights[a] + weights[b]; + parent[a] = nodes; + parent[b] = nodes; + queue.Enqueue(nodes, (weights[nodes] << 20) | (uint)nodes); + nodes++; + } + + var root = nodes - 1; + depth[root] = 0; + var max = 0; + for (var i = root - 1; i >= 0; i--) + { + depth[i] = depth[parent[i]] + 1; + if (i < leafCount) + { + max = Math.Max(max, depth[i]); + } + } + + if (max <= maxLength) + { + Array.Clear(lengths); + for (var i = 0; i < leafCount; i++) + { + lengths[leaves[i]] = (byte)depth[i]; + } + + return; + } + } + } +} + +/// +/// The encoder of WebP lossless (RFC 9649 §3) behind : colour indexing for images of at most +/// 256 colours, otherwise subtract green, the predictor transform (the mode of each block chosen by the smallest sum +/// of residuals) and the colour transform (factors from a least-squares estimate refined by search), then LZ77 with +/// hash chains, a colour cache whose size is chosen by estimated entropy, and length-limited Huffman codes. +/// +internal static class Vp8LEncoder +{ + private const uint HashMultiplier = 0x1E35A7BD; + private const int MaxLength = 4096; + private const int MaxDistance = (1 << 20) - 120; + private const int HashBits = 18; + private const int NumLengthCodes = 24; + + private static ReadOnlySpan CodeLengthOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + + /// The image stream for (transforms, colour cache, codes, data), without header. + public static void WriteImageStream(Vp8LBitWriter writer, uint[] argb, int width, int height, Vp8LEncoderSettings settings) + { + var pixels = argb.AsSpan(0, width * height).ToArray(); + var xsize = width; + if (settings.Palette && TryPalette(pixels, out var palette)) + { + writer.WriteBits(1, 1); + writer.WriteBits(3, 2); + writer.WriteBits((uint)(palette.Length - 1), 8); + var deltas = new uint[palette.Length]; + deltas[0] = palette[0]; + for (var i = 1; i < palette.Length; i++) + { + deltas[i] = Vp8LDecoder.SubtractPixels(palette[i], palette[i - 1]); + } + + WriteEntropyImage(writer, deltas, palette.Length, 1, settings); + pixels = Bundle(pixels, width, height, palette, out xsize); + } + else + { + if (settings.SubtractGreen) + { + writer.WriteBits(1, 1); + writer.WriteBits(2, 2); + SubtractGreen(pixels); + } + + if (settings.Predictor) + { + writer.WriteBits(1, 1); + writer.WriteBits(0, 2); + writer.WriteBits((uint)(settings.PredictorBits - 2), 3); + var modes = ApplyPredictor(pixels, width, height, settings.PredictorBits); + WriteEntropyImage(writer, modes, Vp8LDecoder.DivRoundUp(width, settings.PredictorBits), Vp8LDecoder.DivRoundUp(height, settings.PredictorBits), settings); + } + + if (settings.ColorTransform) + { + writer.WriteBits(1, 1); + writer.WriteBits(1, 2); + writer.WriteBits((uint)(settings.ColorTransformBits - 2), 3); + var elements = ApplyColorTransform(pixels, width, height, settings.ColorTransformBits); + WriteEntropyImage(writer, elements, Vp8LDecoder.DivRoundUp(width, settings.ColorTransformBits), Vp8LDecoder.DivRoundUp(height, settings.ColorTransformBits), settings); + } + } + + writer.WriteBits(0, 1); // no more transforms + WriteCoded(writer, pixels, xsize, height, settings, mainImage: true); + } + + private static void WriteEntropyImage(Vp8LBitWriter writer, uint[] pixels, int width, int height, Vp8LEncoderSettings settings) => + WriteCoded(writer, pixels, width, height, settings with { ColorCacheBits = 0 }, mainImage: false); + + // Colour cache info, (for the main image) no meta prefix codes, the five codes and the data. + private static void WriteCoded(Vp8LBitWriter writer, uint[] pixels, int width, int height, Vp8LEncoderSettings settings, bool mainImage) + { + var count = width * height; + var pool = ArrayPool.Shared; + var lengths = pool.Rent(count); + var distances = pool.Rent(count); + try + { + var tokens = settings.Lz77 ? FindMatches(pixels, width, count, settings.ChainLength, lengths, distances) : Literals(count, lengths); + var cacheBits = settings.ColorCacheBits ?? ChooseCacheBits(pixels, lengths.AsSpan(0, tokens)); + writer.WriteBits(cacheBits > 0 ? 1u : 0u, 1); + if (cacheBits > 0) + { + writer.WriteBits((uint)cacheBits, 4); + } + + if (mainImage) + { + writer.WriteBits(0, 1); // one group of prefix codes for the whole image + } + + var cacheSize = cacheBits > 0 ? 1 << cacheBits : 0; + var green = new int[256 + NumLengthCodes + cacheSize]; + var red = new int[256]; + var blue = new int[256]; + var alpha = new int[256]; + var distance = new int[40]; + var cache = cacheBits > 0 ? new uint[cacheSize] : null; + var shift = 32 - cacheBits; + + // First pass: the symbols, to count them; second pass: write them with the codes. + for (var pass = 0; pass < 2; pass++) + { + Vp8LPrefixCode? gc = null, rc = null, bc = null, ac = null, dc = null; + if (pass == 1) + { + gc = Vp8LPrefixCode.FromCounts(green, Vp8LHuffman.MaxCodeLength); + rc = Vp8LPrefixCode.FromCounts(red, Vp8LHuffman.MaxCodeLength); + bc = Vp8LPrefixCode.FromCounts(blue, Vp8LHuffman.MaxCodeLength); + ac = Vp8LPrefixCode.FromCounts(alpha, Vp8LHuffman.MaxCodeLength); + dc = Vp8LPrefixCode.FromCounts(distance, Vp8LHuffman.MaxCodeLength); + WriteCode(writer, gc); + WriteCode(writer, rc); + WriteCode(writer, bc); + WriteCode(writer, ac); + WriteCode(writer, dc); + if (cache is not null) + { + Array.Clear(cache); + } + } + + var pos = 0; + for (var t = 0; t < tokens; t++) + { + var length = lengths[t]; + if (length == 0) + { + var p = pixels[pos++]; + var key = cache is null ? 0 : (int)((HashMultiplier * p) >> shift); + if (cache is not null && cache[key] == p) + { + if (pass == 0) + { + green[256 + NumLengthCodes + key]++; + } + else + { + gc!.Write(writer, 256 + NumLengthCodes + key); + } + } + else + { + int g = (byte)(p >> 8), r = (byte)(p >> 16), b = (byte)p, a = (byte)(p >> 24); + if (pass == 0) + { + green[g]++; + red[r]++; + blue[b]++; + alpha[a]++; + } + else + { + gc!.Write(writer, g); + rc!.Write(writer, r); + bc!.Write(writer, b); + ac!.Write(writer, a); + } + + if (cache is not null) + { + cache[key] = p; + } + } + + continue; + } + + var (lengthSymbol, lengthBits, lengthExtra) = Prefix(length); + var (distanceSymbol, distanceBits, distanceExtra) = Prefix(DistanceCode(distances[t], width)); + if (pass == 0) + { + green[256 + lengthSymbol]++; + distance[distanceSymbol]++; + } + else + { + gc!.Write(writer, 256 + lengthSymbol); + writer.WriteBits((uint)lengthExtra, lengthBits); + dc!.Write(writer, distanceSymbol); + writer.WriteBits((uint)distanceExtra, distanceBits); + } + + if (cache is not null) + { + for (var k = 0; k < length; k++) + { + var p = pixels[pos + k]; + cache[(HashMultiplier * p) >> shift] = p; + } + } + + pos += length; + } + } + } + finally + { + pool.Return(lengths); + pool.Return(distances); + } + } + + private static int Literals(int count, int[] lengths) + { + lengths.AsSpan(0, count).Clear(); + return count; + } + + // Greedy LZ77 over hash chains of pixel pairs; the distances 1 (left) and width (above) are always tried. Fills + // one entry per token: length 0 for a literal pixel, else the length and the distance of a backward reference. + private static int FindMatches(uint[] pixels, int width, int count, int chainLength, int[] lengths, int[] distances) + { + var head = ArrayPool.Shared.Rent(1 << HashBits); + var previous = ArrayPool.Shared.Rent(count); + try + { + head.AsSpan(0, 1 << HashBits).Fill(-1); + var tokens = 0; + var i = 0; + while (i < count) + { + var bestLength = 0; + var bestDistance = 0; + var limit = Math.Min(MaxLength, count - i); + if (limit >= 2) + { + TryMatch(pixels, i, 1, limit, ref bestLength, ref bestDistance); + if (width > 1) + { + TryMatch(pixels, i, width, limit, ref bestLength, ref bestDistance); + } + + var candidate = head[Hash(pixels, i)]; + for (var c = 0; c < chainLength && candidate >= 0 && bestLength < limit; c++) + { + var d = i - candidate; + if (d > MaxDistance) + { + break; + } + + TryMatch(pixels, i, d, limit, ref bestLength, ref bestDistance); + candidate = previous[candidate]; + } + } + + var cheap = bestDistance == 1 || bestDistance == width; + if (bestLength >= 3 || (bestLength == 2 && cheap)) + { + lengths[tokens] = bestLength; + distances[tokens] = bestDistance; + tokens++; + for (var k = 0; k < bestLength; k++) + { + Insert(pixels, i + k, count, head, previous); + } + + i += bestLength; + } + else + { + lengths[tokens] = 0; + tokens++; + Insert(pixels, i, count, head, previous); + i++; + } + } + + return tokens; + } + finally + { + ArrayPool.Shared.Return(head); + ArrayPool.Shared.Return(previous); + } + } + + private static void TryMatch(uint[] pixels, int i, int distance, int limit, ref int bestLength, ref int bestDistance) + { + if (distance > i || distance <= 0) + { + return; + } + + var from = i - distance; + if (bestLength >= limit || (bestLength > 0 && pixels[from + bestLength] != pixels[i + bestLength])) + { + return; + } + + var length = 0; + while (length < limit && pixels[from + length] == pixels[i + length]) + { + length++; + } + + if (length > bestLength) + { + bestLength = length; + bestDistance = distance; + } + } + + private static void Insert(uint[] pixels, int i, int count, int[] head, int[] previous) + { + if (i + 1 >= count) + { + return; + } + + var h = Hash(pixels, i); + previous[i] = head[h]; + head[h] = i; + } + + private static int Hash(uint[] pixels, int i) + { + var next = i + 1 < pixels.Length ? pixels[i + 1] : 0; + var key = (pixels[i] * HashMultiplier) ^ (next * 0x9E3779B1); + return (int)(key >> (32 - HashBits)); + } + + // RFC 9649 §3.6: a distance as a distance code, using the 120 short codes for neighbours when one matches. + internal static int DistanceCode(int distance, int width) + { + for (var dy = 0; dy <= 7; dy++) + { + var dx = distance - (dy * width); + if (dx is >= -7 and <= 8) + { + var index = ShortCodes[(dy * 16) + (dx + 7)]; + if (index > 0) + { + return index; + } + } + } + + return distance + 120; + } + + // ShortCodes[dy * 16 + dx + 7] = 1-based short distance code of (dx, dy), 0 when there is none. + private static readonly int[] ShortCodes = BuildShortCodes(); + + private static int[] BuildShortCodes() + { + var table = new int[8 * 16]; + for (var code = 1; code <= 120; code++) + { + var (dx, dy) = Vp8LDecoder.ShortDistance(code); + table[(dy * 16) + dx + 7] = code; + } + + return table; + } + + /// The prefix symbol, the number of extra bits and their value for a length or distance code ≥ 1. + internal static (int Symbol, int Bits, int Extra) Prefix(int value) + { + var d = value - 1; + if (d < 4) + { + return (d, 0, 0); + } + + var high = 31 - System.Numerics.BitOperations.LeadingZeroCount((uint)d); + var second = (d >> (high - 1)) & 1; + var bits = high - 1; + return ((2 * high) + second, bits, d & ((1 << bits) - 1)); + } + + // Estimates, for cache sizes 0-10, the entropy of the symbols the cache would produce; returns the cheapest. + private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan lengths) + { + var bestBits = 0; + var bestCost = double.MaxValue; + var green = new int[256 + NumLengthCodes + (1 << 10)]; + var red = new int[256]; + var blue = new int[256]; + var alpha = new int[256]; + foreach (var bits in (ReadOnlySpan)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + { + Array.Clear(green); + Array.Clear(red); + Array.Clear(blue); + Array.Clear(alpha); + var cache = bits > 0 ? new uint[1 << bits] : null; + var shift = 32 - bits; + var pos = 0; + foreach (var length in lengths) + { + if (length > 0) + { + if (cache is not null) + { + for (var k = 0; k < length; k++) + { + var q = pixels[pos + k]; + cache[(HashMultiplier * q) >> shift] = q; + } + } + + pos += length; + continue; + } + + var p = pixels[pos++]; + if (cache is not null) + { + var key = (int)((HashMultiplier * p) >> shift); + if (cache[key] == p) + { + green[256 + NumLengthCodes + key]++; + continue; + } + + cache[key] = p; + } + + green[(byte)(p >> 8)]++; + red[(byte)(p >> 16)]++; + blue[(byte)p]++; + alpha[(byte)(p >> 24)]++; + } + + var cost = Entropy(green) + Entropy(red) + Entropy(blue) + Entropy(alpha); + if (cost < bestCost) + { + bestCost = cost; + bestBits = bits; + } + } + + return bestBits; + } + + // Bits to code the counts with an ideal code, plus a rough price for describing the code. + private static double Entropy(ReadOnlySpan counts) + { + long total = 0; + var used = 0; + foreach (var c in counts) + { + total += c; + used += c > 0 ? 1 : 0; + } + + if (used <= 1) + { + return 8; + } + + var bits = 0.0; + foreach (var c in counts) + { + if (c > 0) + { + bits -= c * Math.Log2((double)c / total); + } + } + + return bits + (used * 4.0); + } + + // Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length + // coded with 16/17/18 and themselves Huffman coded. + private static void WriteCode(Vp8LBitWriter writer, Vp8LPrefixCode code) + { + var lengths = code.Lengths; + Span symbols = stackalloc int[2]; + var used = 0; + for (var s = 0; s < lengths.Length && used <= 2; s++) + { + if (lengths[s] > 0) + { + if (used < 2) + { + symbols[used] = s; + } + + used++; + } + } + + if (used <= 2 && symbols[0] < 256 && (used < 2 || symbols[1] < 256)) + { + writer.WriteBits(1, 1); + writer.WriteBits((uint)(used - 1), 1); + if (symbols[0] <= 1) + { + writer.WriteBits(0, 1); + writer.WriteBits((uint)symbols[0], 1); + } + else + { + writer.WriteBits(1, 1); + writer.WriteBits((uint)symbols[0], 8); + } + + if (used == 2) + { + writer.WriteBits((uint)symbols[1], 8); + } + + return; + } + + // Run-length tokens of the code lengths: (symbol, extra bits value). + var tokens = new List<(int Symbol, int Extra)>(lengths.Length); + var previous = 8; + for (var i = 0; i < lengths.Length;) + { + var value = lengths[i]; + var run = 1; + while (i + run < lengths.Length && lengths[i + run] == value) + { + run++; + } + + i += run; + if (value == 0) + { + while (run >= 11) + { + var n = Math.Min(run, 138); + tokens.Add((18, n - 11)); + run -= n; + } + + if (run >= 3) + { + tokens.Add((17, run - 3)); + run = 0; + } + + for (; run > 0; run--) + { + tokens.Add((0, 0)); + } + + continue; + } + + if (value != previous) + { + tokens.Add((value, 0)); + previous = value; + run--; + } + + while (run >= 3) + { + var n = Math.Min(run, 6); + tokens.Add((16, n - 3)); + run -= n; + } + + for (; run > 0; run--) + { + tokens.Add((value, 0)); + } + } + + Span counts = stackalloc int[19]; + counts.Clear(); + foreach (var (symbol, _) in tokens) + { + counts[symbol]++; + } + + var lengthCode = Vp8LPrefixCode.FromCounts(counts, 7); + var written = 4; + for (var i = 0; i < 19; i++) + { + if (lengthCode.Lengths[CodeLengthOrder[i]] > 0) + { + written = Math.Max(written, i + 1); + } + } + + writer.WriteBits(0, 1); + writer.WriteBits((uint)(written - 4), 4); + for (var i = 0; i < written; i++) + { + writer.WriteBits(lengthCode.Lengths[CodeLengthOrder[i]], 3); + } + + writer.WriteBits(0, 1); // the lengths of the whole alphabet follow + foreach (var (symbol, extra) in tokens) + { + lengthCode.Write(writer, symbol); + switch (symbol) + { + case 16: + writer.WriteBits((uint)extra, 2); + break; + case 17: + writer.WriteBits((uint)extra, 3); + break; + case 18: + writer.WriteBits((uint)extra, 7); + break; + } + } + } + + private static bool TryPalette(uint[] pixels, out uint[] palette) + { + var colors = new HashSet(); + foreach (var p in pixels) + { + if (colors.Add(p) && colors.Count > 256) + { + palette = []; + return false; + } + } + + palette = [.. colors]; + Array.Sort(palette); + return true; + } + + // Indices into the palette, bundled 2, 4 or 8 to a pixel for palettes of at most 16, 4 or 2 colours. + private static uint[] Bundle(uint[] pixels, int width, int height, uint[] palette, out int packedWidth) + { + var index = new Dictionary(palette.Length); + for (var i = 0; i < palette.Length; i++) + { + index[palette[i]] = i; + } + + var bits = palette.Length > 16 ? 0 : palette.Length > 4 ? 1 : palette.Length > 2 ? 2 : 3; + packedWidth = Vp8LDecoder.DivRoundUp(width, bits); + var packed = new uint[packedWidth * height]; + var bitsPerPixel = 8 >> bits; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var i = index[pixels[(y * width) + x]]; + var at = (y * packedWidth) + (x >> bits); + packed[at] |= (uint)i << (8 + ((x & ((1 << bits) - 1)) * bitsPerPixel)); + } + } + + for (var i = 0; i < packed.Length; i++) + { + packed[i] |= 0xFF000000; + } + + return packed; + } + + private static void SubtractGreen(uint[] pixels) + { + for (var i = 0; i < pixels.Length; i++) + { + var p = pixels[i]; + var green = (p >> 8) & 0xFF; + var redBlue = (p | 0xFF00FF00) - ((green << 16) | green); + pixels[i] = (p & 0xFF00FF00) | (redBlue & 0x00FF00FF); + } + } + + // Replaces the pixels with their residuals; returns the image of modes (in the green channel). + private static uint[] ApplyPredictor(uint[] pixels, int width, int height, int bits) + { + var blocksWide = Vp8LDecoder.DivRoundUp(width, bits); + var blocksHigh = Vp8LDecoder.DivRoundUp(height, bits); + var modes = new uint[blocksWide * blocksHigh]; + var size = 1 << bits; + Span costs = stackalloc long[14]; + for (var by = 0; by < blocksHigh; by++) + { + for (var bx = 0; bx < blocksWide; bx++) + { + costs.Clear(); + var y0 = by * size; + var x0 = bx * size; + var y1 = Math.Min(height, y0 + size); + var x1 = Math.Min(width, x0 + size); + for (var y = Math.Max(1, y0); y < y1; y++) + { + for (var x = Math.Max(1, x0); x < x1; x++) + { + var i = (y * width) + x; + var p = pixels[i]; + uint left = pixels[i - 1], top = pixels[i - width], topRight = pixels[i - width + 1], topLeft = pixels[i - width - 1]; + for (var mode = 0; mode < 14; mode++) + { + costs[mode] += ResidualCost(Vp8LDecoder.SubtractPixels(p, Vp8LDecoder.Predict(mode, left, top, topRight, topLeft))); + } + } + } + + var best = 0; + for (var mode = 1; mode < 14; mode++) + { + if (costs[mode] < costs[best]) + { + best = mode; + } + } + + modes[(by * blocksWide) + bx] = 0xFF000000 | ((uint)best << 8); + } + } + + // Residuals from the original neighbours, last pixel first so that every neighbour is still original. + for (var y = height - 1; y >= 0; y--) + { + for (var x = width - 1; x >= 0; x--) + { + var i = (y * width) + x; + uint prediction; + if (y == 0) + { + prediction = x == 0 ? 0xFF000000 : pixels[i - 1]; + } + else if (x == 0) + { + prediction = pixels[i - width]; + } + else + { + var mode = (int)(modes[((y >> bits) * blocksWide) + (x >> bits)] >> 8) & 0xF; + prediction = Vp8LDecoder.Predict(mode, pixels[i - 1], pixels[i - width], pixels[i - width + 1], pixels[i - width - 1]); + } + + pixels[i] = Vp8LDecoder.SubtractPixels(pixels[i], prediction); + } + } + + return modes; + } + + private static int ResidualCost(uint residual) + { + var cost = 0; + for (var shift = 0; shift < 32; shift += 8) + { + var v = (sbyte)(residual >> shift); + cost += v < 0 ? -v : v; + } + + return cost; + } + + // Chooses green-to-red, green-to-blue and red-to-blue per block and applies the forward transform. + private static uint[] ApplyColorTransform(uint[] pixels, int width, int height, int bits) + { + var blocksWide = Vp8LDecoder.DivRoundUp(width, bits); + var blocksHigh = Vp8LDecoder.DivRoundUp(height, bits); + var elements = new uint[blocksWide * blocksHigh]; + var size = 1 << bits; + for (var by = 0; by < blocksHigh; by++) + { + for (var bx = 0; bx < blocksWide; bx++) + { + var y0 = by * size; + var x0 = bx * size; + var y1 = Math.Min(height, y0 + size); + var x1 = Math.Min(width, x0 + size); + var greenToRed = BestFactor(pixels, width, x0, x1, y0, y1, 8, 16, 0, 0, 0); + var greenToBlue = BestFactor(pixels, width, x0, x1, y0, y1, 8, 0, 0, 0, 0); + var redToBlue = BestFactor(pixels, width, x0, x1, y0, y1, 16, 0, 8, greenToBlue, 1); + elements[(by * blocksWide) + bx] = 0xFF000000 | ((uint)(byte)redToBlue << 16) | ((uint)(byte)greenToBlue << 8) | (byte)greenToRed; + for (var y = y0; y < y1; y++) + { + for (var x = x0; x < x1; x++) + { + var i = (y * width) + x; + var p = pixels[i]; + var green = (sbyte)(p >> 8); + var red = (sbyte)(p >> 16); + var newRed = (int)((p >> 16) & 0xFF) - ((greenToRed * green) >> 5); + var newBlue = (int)(p & 0xFF) - ((greenToBlue * green) >> 5) - ((redToBlue * red) >> 5); + pixels[i] = (p & 0xFF00FF00) | ((uint)(newRed & 0xFF) << 16) | (uint)(newBlue & 0xFF); + } + } + } + } + + return elements; + } + + // The factor t in [-128, 127] that minimises Σ|target − (t·source >> 5) − (prior·other >> 5)| over a block, from + // the least-squares estimate and a search around it (and 0). + private static int BestFactor(uint[] pixels, int width, int x0, int x1, int y0, int y1, int sourceShift, int targetShift, int otherShift, int prior, int usePrior) + { + long sumProduct = 0; + long sumSquares = 0; + for (var y = y0; y < y1; y++) + { + for (var x = x0; x < x1; x++) + { + var p = pixels[(y * width) + x]; + int s = (sbyte)(p >> sourceShift); + var t = Target(p, targetShift, otherShift, prior, usePrior); + sumProduct += s * t; + sumSquares += s * s; + } + } + + var estimate = sumSquares == 0 ? 0 : (int)Math.Clamp(Math.Round(32.0 * sumProduct / sumSquares), -128, 127); + var best = 0; + var bestCost = long.MaxValue; + for (var candidate = estimate - 4; candidate <= estimate + 4 + 1; candidate++) + { + var factor = candidate == estimate + 5 ? 0 : Math.Clamp(candidate, -128, 127); + long cost = 0; + for (var y = y0; y < y1 && cost < bestCost; y++) + { + for (var x = x0; x < x1; x++) + { + var p = pixels[(y * width) + x]; + int s = (sbyte)(p >> sourceShift); + var v = (sbyte)(Target(p, targetShift, otherShift, prior, usePrior) - ((factor * s) >> 5)); + cost += v < 0 ? -v : v; + } + } + + if (cost < bestCost) + { + bestCost = cost; + best = factor; + } + } + + return best; + } + + // The target channel as a signed value, less the contribution already removed by the prior factor. + private static int Target(uint p, int targetShift, int otherShift, int prior, int usePrior) + { + int t = (sbyte)(p >> targetShift); + if (usePrior == 1) + { + // Blue after green-to-blue: the source here is red, the prior factor applies to green. + t = (sbyte)(t - ((prior * (sbyte)(p >> otherShift)) >> 5)); + } + + return t; + } +} + +/// Settings of , internal so that tests can exercise each tool alone. +internal sealed record Vp8LEncoderSettings +{ + public static Vp8LEncoderSettings Default { get; } = new(); + + public bool Palette { get; init; } = true; + + public bool SubtractGreen { get; init; } = true; + + public bool Predictor { get; init; } = true; + + public int PredictorBits { get; init; } = 4; + + public bool ColorTransform { get; init; } = true; + + public int ColorTransformBits { get; init; } = 5; + + public bool Lz77 { get; init; } = true; + + public int ChainLength { get; init; } = 32; + + /// Bits of the colour cache (0 = none), or null to choose by estimated entropy. + public int? ColorCacheBits { get; init; } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8Reconstruction.cs b/src/Febe.Core/Codecs/Images/Vp8Reconstruction.cs new file mode 100644 index 0000000..3e7331b --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8Reconstruction.cs @@ -0,0 +1,565 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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 at. +/// +internal static class Vp8Predict +{ + /// A 16×16 luma or 8×8 chroma prediction (DC_PRED, V_PRED, H_PRED, TM_PRED). + public static void Block(Span 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; + } + } + } + + /// A 4×4 luma subblock prediction (the ten intra_bmode of RFC 6386 §12.3). + public static void Sub4x4(Span 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 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)[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 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 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; + } +} + +/// The inverse transforms of VP8 (RFC 6386 §14.3 and §14.4), exact integer arithmetic. +internal static class Vp8Transforms +{ + private const int C1 = 20091; // cos(π/8)·√2 − 1, ×65536 + private const int S1 = 35468; // sin(π/8)·√2, ×65536 + + /// + /// 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 ). + /// + public static void InverseWht(ReadOnlySpan input, Span blocks) + { + Span 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); + } + } + + /// + /// Adds the inverse DCT of (raster order) to the 4×4 pixels at : + /// 0 means an empty block, 1 only a DC coefficient, 2 any coefficients. + /// + public static void AddBlock(ReadOnlySpan coeffs, int kind, Span 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 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); +} + +/// The loop filters of VP8 (RFC 6386 §15), applied to the whole reconstructed frame in raster order. +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); + } + } + } + } + + /// + /// The simple filter over 16 pixels of an edge: crosses the edge (1 for a vertical edge), + /// moves along it; is twice the edge limit plus one. + /// + 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); +} diff --git a/src/Febe.Core/Codecs/Images/Vp8Tables.cs b/src/Febe.Core/Codecs/Images/Vp8Tables.cs new file mode 100644 index 0000000..3f6a46b --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8Tables.cs @@ -0,0 +1,426 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +internal static class Vp8Tables +{ + /// Intra modes of a 16×16 luma block or an 8×8 chroma block (RFC 6386 §8.1). + public const int DcPred = 0, VPred = 1, HPred = 2, TmPred = 3, BPred = 4; + + /// Modes of a 4×4 luma subblock, in the order of RFC 6386 §8.1 (intra_bmode). + 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; + + /// §11.2: kf_ymode_prob. + public static ReadOnlySpan KeyFrameYModeProbs => [145, 156, 163, 128]; + + /// §11.2: kf_uv_mode_prob. + public static ReadOnlySpan KeyFrameUvModeProbs => [142, 114, 183]; + + /// + /// §11.2: bmode_tree, as pairs of children; a child ≤ 0 is the leaf −mode, a positive child the index of the next + /// pair. + /// + public static ReadOnlySpan BModeTree => + [ + -BDc, 2, + -BTm, 4, + -BVe, 6, + 8, 12, + -BHe, 10, + -BRd, -BVr, + -BLd, 14, + -BVl, 16, + -BHd, -BHu, + ]; + + /// + /// §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. + /// + public static ReadOnlySpan 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, + ]; + + /// §14.1: dc_qlookup. + public static ReadOnlySpan 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, + ]; + + /// §14.1: ac_qlookup. + public static ReadOnlySpan 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, + ]; + + /// §13: the zigzag scan, from position in the token stream to raster index in the 4×4 block. + public static ReadOnlySpan Zigzag => [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + + /// §13.3: the band of each coefficient position (a 17th entry, never a real position, keeps lookups simple). + public static ReadOnlySpan Bands => [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]; + + /// §13.2: the probabilities of the extra bits of DCT_CAT3 to DCT_CAT6 (cat1 and cat2 are read inline). + public static ReadOnlySpan Cat3 => [173, 148, 140]; + + public static ReadOnlySpan Cat4 => [176, 155, 140, 135]; + + public static ReadOnlySpan Cat5 => [180, 157, 141, 134, 130]; + + public static ReadOnlySpan Cat6 => [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129]; + + /// Number of token probabilities: 4 block types × 8 bands × 3 contexts × 11 tree nodes. + public const int CoefficientProbCount = 4 * 8 * 3 * 11; + + /// §13.5: default_coeff_probs, flattened [type][band][context][node]. + public static ReadOnlySpan 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, + ]; + + /// §13.4: coeff_update_probs, flattened like . + public static ReadOnlySpan 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, + ]; +} diff --git a/src/Febe.Core/Codecs/Images/WebPDecoder.cs b/src/Febe.Core/Codecs/Images/WebPDecoder.cs new file mode 100644 index 0000000..74eb291 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/WebPDecoder.cs @@ -0,0 +1,511 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +/// +/// Strictness, as for PNG: data that ends before the last pixel of a picture is damaged (), +/// 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 are skipped. +/// +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 " + + /// Whether the bytes start like a WebP file (a RIFF of form WEBP). + public static bool IsWebP(ReadOnlySpan data) => + data.Length >= 12 && data[..4].SequenceEqual("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8); + + /// Size, frames and metadata of a WebP, without decoding the pixels. + /// The file is damaged or not a WebP. + public static ImageInfo Identify(ReadOnlyMemory 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(); + } + + /// Decodes a WebP to straight RGBA8 (the first frame of an animation, on its canvas). + /// The file is damaged, truncated or not a WebP. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) => + Decode(data, out _, limits, pooled, readMetadata: false); + + /// Decodes a WebP to straight RGBA8 and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false) => + Decode(data, out info, limits, pooled, readMetadata: true); + + private static RgbaImage Decode(ReadOnlyMemory 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); + + /// A picture: its bitstream chunk (VP8 or VP8L) and, for VP8, its optional ALPH chunk. + 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 ReadChunks(byte[] data, int start, int length) + { + var chunks = new List(); + 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)); + } + } + } + + /// + /// 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. + /// + internal static void Blend(ReadOnlySpan source, Span 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 b) => (uint)(b[0] | (b[1] << 8) | (b[2] << 16)); + + private static byte[] AsArray(ReadOnlyMemory 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(); + } +} + +/// The ALPH chunk of RFC 9649 §2.7.1.2: raw or VP8L-compressed alpha, then the inverse of its filter. +internal static class WebPAlpha +{ + /// Decodes the alpha plane of the chunk payload and writes it into the alpha bytes of . + 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.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.Shared.Return(alpha); + } + } + + /// + /// 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. + /// + internal static void Unfilter(Span 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; + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/WebPEncoder.cs b/src/Febe.Core/Codecs/Images/WebPEncoder.cs new file mode 100644 index 0000000..a94c12f --- /dev/null +++ b/src/Febe.Core/Codecs/Images/WebPEncoder.cs @@ -0,0 +1,183 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// Options of . +public sealed record WebPEncoderOptions +{ + /// The options used when a caller passes none. + public static WebPEncoderOptions Default { get; } = new(); + + /// + /// 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. + /// + public byte[]? Exif { get; init; } + + /// ICC profile to write in an ICCP chunk. + public byte[]? IccProfile { get; init; } + + /// XMP packet to write in an XMP chunk (UTF-8). + public string? Xmp { get; init; } + + /// The tools of the lossless encoder (tests turn them on and off one by one). + internal Vp8LEncoderSettings Lossless { get; init; } = Vp8LEncoderSettings.Default; +} + +/// +/// 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. +/// +public static class WebPEncoder +{ + /// Largest width or height a WebP picture can have. + public const int MaxDimension = 16384; + + /// The WebP file of . + /// The image is wider or taller than . + /// The EXIF block is not a TIFF structure. + public static byte[] Encode(RgbaImage image, WebPEncoderOptions? options = null) + { + using var output = new MemoryStream(); + Encode(image, output, options); + return output.ToArray(); + } + + /// Writes the WebP file of to . + 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 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 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); + } + } + + /// The VP8L bitstream (signature, header, image stream) of . + 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(); + } + + /// + /// The headerless image stream of an ALPH chunk compressed with VP8L: the alpha values in the green channel. + /// + internal static byte[] EncodeAlphaStream(ReadOnlySpan 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 type, ReadOnlySpan payload) + { + Span 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 destination, int value) + { + destination[0] = (byte)value; + destination[1] = (byte)(value >> 8); + destination[2] = (byte)(value >> 16); + } + + private static byte[] ExifPayload(byte[] exif) + { + ReadOnlySpan 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(); + } +} diff --git a/tests/Febe.Tests/Imaging/ImageFuzzTests.cs b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs index 9f6cd5e..3e732ea 100644 --- a/tests/Febe.Tests/Imaging/ImageFuzzTests.cs +++ b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs @@ -19,6 +19,7 @@ public sealed class ImageFuzzTests [ReferenceFormat.Gif], [ReferenceFormat.Bmp], [ReferenceFormat.Jpeg], + [ReferenceFormat.WebP], ]; [TestMethod] diff --git a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs index 565b0a3..dc93dac 100644 --- a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs +++ b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs @@ -85,11 +85,11 @@ public sealed class ImagingBaseTests [TestMethod] public void TheFacadeSaysWhichFormatsItCannotReadYet() { - var webp = ReferenceImages.Of(ReferenceFormat.WebP).First().ReadInput(); - var error = Assert.ThrowsExactly(() => ImageDecoder.Decode(webp)); - Assert.Contains("WEBP", error.Message); + var tiff = "II*\0\u0008\0\0\0\0\0"u8.ToArray(); + var error = Assert.ThrowsExactly(() => ImageDecoder.Decode(tiff)); + Assert.Contains("TIFF", error.Message); Assert.ThrowsExactly(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi"))); - Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg)); - Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown)); + Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg) && ImageDecoder.CanDecode(ImageFormat.WebP)); + Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Tiff) || ImageDecoder.CanDecode(ImageFormat.Heif) || ImageDecoder.CanDecode(ImageFormat.Unknown)); } } diff --git a/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs b/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs index 6ec9156..e889f00 100644 --- a/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs +++ b/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs @@ -64,9 +64,10 @@ public sealed class ReferenceDecodeTests continue; } - if (reference.Format == ReferenceFormat.Jpeg) + if (reference.Format == ReferenceFormat.Jpeg || (reference.Format == ReferenceFormat.WebP && !reference.Name.Contains("senza-perdita", StringComparison.Ordinal))) { - // Lossy: JpegReferenceTests compares it with thresholds, and with the EXIF orientation applied. + // Lossy: JpegReferenceTests and WebPReferenceTests compare it with thresholds (JPEG with the EXIF + // orientation applied). continue; } diff --git a/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md b/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md index 66d4702..75df413 100644 --- a/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md +++ b/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md @@ -68,8 +68,9 @@ Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up, - JPEG e WebP con perdita: l'immagine attesa è la lettura di libjpeg-turbo e libwebp dentro SkiaSharp (IDCT, ricampionamento della crominanza, conversione dei colori). Il nostro lettore può differire di poco: per JPEG la tolleranza è almeno 40 dB di PSNR per canale e al più lo 0,1% dei pixel con uno scarto oltre 16 (il lettore di casa - sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). PNG, GIF, BMP e WebP senza perdita devono coincidere - byte per byte. + sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). Per WebP con perdita la tolleranza è la stessa e l'alfa + deve coincidere: il lettore di casa (passo 4) sta fra 68,7 e 74,4 dB, scarto massimo 1, nessun pixel oltre 16, alfa + esatta. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte. ## Che cosa qui non c'è @@ -93,12 +94,19 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo. - `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato, - esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per WebP - dice che non lo legge ancora; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal - passo 3), che applica anche l'orientamento EXIF riportato dal lettore. + esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e i WebP + senza perdita devono coincidere; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal + passo 3), che applica anche l'orientamento EXIF riportato dal lettore, e i WebP con perdita + `Imaging/WebPReferenceTests.cs` (dal passo 4). - `Imaging/JpegCodingTests.cs`, `JpegEncoderTests.cs`, `JpegMalformedTests.cs` (dal passo 3): i casi qui assenti (progressivo, ripristino, codifica aritmetica, 12 bit, senza perdita, CMYK e YCCK, campionamenti insoliti) scritti dal codificatore di prova `JpegTestEncoder.cs` e confrontati coefficiente per coefficiente con la codifica di base delle stesse immagini; il codificatore di casa; i file danneggiati. +- `Imaging/WebPReferenceTests.cs`, `WebPEncoderTests.cs`, `WebPContainerTests.cs`, `Vp8BitstreamTests.cs` (dal passo + 4): i WebP dell'insieme contro l'immagine attesa (senza perdita esatti, con perdita con la tolleranza sopra); lo + scrittore senza perdita di casa, che rilegge esatti tutti i 57 riferimenti; le varianti che qui mancano, costruite + dalle prove a partire dai file dell'insieme (`ALPH` grezzo e compresso con ogni filtro, VP8X con ICCP, EXIF e XMP, + animazioni con scostamento e fusione) o scritte bit per bit (`Vp8TestWriter.cs`: segmenti, delta del filtro, più + partizioni, filtro semplice); i file danneggiati o tagliati. - `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini come binarie e tiene `elenco.txt` con le righe Unix. diff --git a/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs b/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs new file mode 100644 index 0000000..ca7eb6a --- /dev/null +++ b/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs @@ -0,0 +1,338 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The VP8 decoder on frames written by , for what the libwebp references do not reach: +/// the border rules of intra prediction, the token categories, several partitions, the skip flag, segment maps, +/// filter deltas and the simple loop filter (checked against a separate implementation of RFC 6386 §15.2). +/// +[TestClass] +public sealed class Vp8BitstreamTests +{ + [TestMethod] + public void TheBooleanCoderRoundTrips() + { + var random = new Random(21); + for (var round = 0; round < 20; round++) + { + var count = random.Next(1, 4000); + var probs = new int[count]; + var bits = new bool[count]; + var encoder = new Vp8BoolEncoder(); + for (var i = 0; i < count; i++) + { + probs[i] = random.Next(1, 256); + bits[i] = random.Next(256) >= probs[i]; + encoder.Write(probs[i], bits[i]); + } + + var data = encoder.Finish(); + var decoder = new Vp8BoolDecoder(data, 0, data.Length); + for (var i = 0; i < count; i++) + { + Assert.AreEqual(bits[i] ? 1 : 0, decoder.GetBit(probs[i]), $"giro {round}, bit {i}"); + } + + Assert.IsFalse(decoder.Overrun); + } + + // Reading on past the end is noticed. + var empty = new Vp8BoolDecoder([], 0, 0); + for (var i = 0; i < 40; i++) + { + empty.GetBit(128); + } + + Assert.IsTrue(empty.Overrun); + } + + [TestMethod] + public void PredictionFollowsTheBorderRules() + { + // 3×2 macroblocks, no residual, no loop filter: the pixels are the prediction alone. + Assert.AreEqual(128, Uniform(Vp8Tables.DcPred, Vp8Tables.DcPred).Y.Distinct().Single(), "DC senza vicini"); + Assert.AreEqual(127, Uniform(Vp8Tables.VPred, Vp8Tables.VPred).Y.Distinct().Single(), "sopra il fotogramma 127"); + Assert.AreEqual(129, Uniform(Vp8Tables.HPred, Vp8Tables.HPred).Y.Distinct().Single(), "a sinistra del fotogramma 129"); + Assert.AreEqual(129, Uniform(Vp8Tables.TmPred, Vp8Tables.TmPred).Y.Distinct().Single(), "TM: 129 + 127 − 127"); + var vertical = Uniform(Vp8Tables.VPred, Vp8Tables.VPred); + Assert.AreEqual(127, vertical.U.Distinct().Single()); + + // B_VE smooths the row above with the pixel above-left, which is 127 above the frame and 129 left of it: + // column 0 is avg3(127, 127, 127) in the first four rows and avg3(129, 127, 127) = 128 below. + var subVertical = Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BVe); + for (var y = 0; y < 32; y++) + { + Assert.AreEqual(y < 4 ? 127 : 128, subVertical.Y[y * 48], $"riga {y}"); + Assert.AreEqual(127, subVertical.Y[(y * 48) + 1], $"riga {y}"); + } + + // B_DC of the first subblock: (4·127 + 4·129 + 4) >> 3; B_HE and B_TM next to the left border: 129. + Assert.AreEqual(128, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BDc).Y[0]); + Assert.AreEqual(129, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BHe).Y[0]); + Assert.AreEqual(129, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BTm).Y[0]); + } + + [TestMethod] + public void TokenCategoriesCarryTheirValues() + { + // Base quantizer 0: Y DC step 4, Y2 DC step 8. A DC-only block adds (level·4 + 4) >> 3 to the prediction 128. + foreach (var level in (int[])[1, -1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 18, 19, 34, 35, 66, 67, 300, -2114, 2114]) + { + var mbs = Vp8TestWriter.Uniform(1, Vp8Tables.BPred, Vp8Tables.DcPred); + mbs[0].Skip = false; + mbs[0].Levels[0][0] = level; + var planes = Planes(new Vp8TestWriter { Width = 16, Height = 16, BaseQ = 0 }.Write(mbs)); + var expected = Math.Clamp(128 + (((level * 4) + 4) >> 3), 0, 255); + Assert.AreEqual(expected, planes.Y[0], $"livello {level}"); + Assert.AreEqual(expected, planes.Y[(3 * 16) + 3], $"livello {level}"); + } + + // Y2: the inverse WHT of a DC of 8·16 gives 16 to every luma block, which adds (16 + 4) >> 3 = 2. + var whole = Vp8TestWriter.Uniform(1, Vp8Tables.DcPred, Vp8Tables.DcPred); + whole[0].Skip = false; + whole[0].Levels[24][0] = 16; + Assert.AreEqual(130, Planes(new Vp8TestWriter { Width = 16, Height = 16, BaseQ = 0 }.Write(whole)).Y.Distinct().Single()); + } + + [TestMethod] + public void PartitionsDoNotChangeThePicture() + { + var mbs = Vp8TestWriter.Random(7 * 5, seed: 31); + var expected = Planes(new Vp8TestWriter { Width = 100, Height = 70, FilterLevel = 20, Sharpness = 2 }.Write(mbs)); + for (var log2 = 1; log2 <= 3; log2++) + { + var actual = Planes(new Vp8TestWriter { Width = 100, Height = 70, FilterLevel = 20, Sharpness = 2, Log2Partitions = log2 }.Write(mbs)); + AssertSamePlanes(expected, actual, $"{1 << log2} partizioni"); + } + } + + [TestMethod] + public void TheSkipFlagAndEmptyBlocksAgree() + { + var mbs = Vp8TestWriter.Random(6 * 4, seed: 32, skips: false); + for (var i = 0; i < mbs.Length; i += 3) + { + foreach (var block in mbs[i].Levels) + { + Array.Clear(block); + } + + mbs[i].Skip = true; + } + + var skipped = Planes(new Vp8TestWriter { Width = 90, Height = 60, FilterLevel = 30 }.Write(mbs)); + var explicitEmpty = Planes(new Vp8TestWriter { Width = 90, Height = 60, FilterLevel = 30, UseSkipProb = false }.Write(mbs)); + AssertSamePlanes(skipped, explicitEmpty, "salto contro blocchi vuoti"); + } + + [TestMethod] + public void SegmentsWithTheBaseValuesChangeNothing() + { + var mbs = Vp8TestWriter.Random(5 * 5, seed: 33); + var plain = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50 }.Write(mbs)); + var deltas = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50, Segmentation = true, UpdateMap = true, SegmentProbs = [90, 140, 200] }.Write(mbs)); + AssertSamePlanes(plain, deltas, "segmenti con differenze nulle"); + var absolute = Planes(new Vp8TestWriter + { + Width = 80, + Height = 80, + FilterLevel = 25, + BaseQ = 50, + Segmentation = true, + UpdateMap = true, + AbsoluteDeltas = true, + SegmentQuant = [50, 50, 50, 50], + SegmentFilter = [25, 25, 25, 25], + }.Write(mbs)); + AssertSamePlanes(plain, absolute, "segmenti con valori assoluti uguali"); + + // Different quantizers per segment do change the picture. + var different = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50, Segmentation = true, UpdateMap = true, SegmentQuant = [0, 10, -20, 30] }.Write(mbs)); + Assert.IsFalse(plain.Y.AsSpan().SequenceEqual(different.Y)); + } + + [TestMethod] + public void FilterDeltasMoveTheLevel() + { + var unfiltered = Vp8TestWriter.Random(4 * 3, seed: 34); + var none = Planes(new Vp8TestWriter { Width = 64, Height = 48 }.Write(unfiltered)); + var cancelled = Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, RefLfDelta = [-30, 5, 5, 5] }.Write(unfiltered)); + AssertSamePlanes(none, cancelled, "livello annullato dalla differenza del riferimento intra"); + + // The mode delta of B_PRED: on a frame of B_PRED macroblocks it cancels the level, on 16×16 ones it does not. + var subblocks = Vp8TestWriter.Random(4 * 3, seed: 35); + var sixteen = Vp8TestWriter.Random(4 * 3, seed: 35); + foreach (var mb in subblocks) + { + mb.YMode = Vp8Tables.BPred; + } + + foreach (var mb in sixteen) + { + mb.YMode = Vp8Tables.TmPred; + } + + AssertSamePlanes( + Planes(new Vp8TestWriter { Width = 64, Height = 48 }.Write(subblocks)), + Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, ModeLfDelta = [-30, 0, 0, 0] }.Write(subblocks)), + "B_PRED"); + AssertSamePlanes( + Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30 }.Write(sixteen)), + Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, ModeLfDelta = [-30, 0, 0, 0] }.Write(sixteen)), + "16×16"); + } + + [TestMethod] + public void TheSimpleFilterMatchesASeparateImplementation() + { + foreach (var (level, sharpness, seed) in new[] { (10, 0, 40), (32, 3, 41), (63, 7, 42), (45, 5, 43) }) + { + var mbs = Vp8TestWriter.Random(6 * 4, seed); + var raw = Planes(new Vp8TestWriter { Width = 96, Height = 64 }.Write(mbs)); + var filtered = Planes(new Vp8TestWriter { Width = 96, Height = 64, SimpleFilter = true, FilterLevel = level, Sharpness = sharpness }.Write(mbs)); + var expected = raw.Y.ToArray(); + SimpleFilter(expected, raw.YStride, 6, 4, mbs, level, sharpness); + CollectionAssert.AreEqual(expected, filtered.Y, $"livello {level}, nitidezza {sharpness}"); + CollectionAssert.AreEqual(raw.U, filtered.U, "il filtro semplice non tocca la crominanza"); + CollectionAssert.AreEqual(raw.V, filtered.V); + Assert.IsFalse(raw.Y.AsSpan().SequenceEqual(filtered.Y), "il filtro deve aver cambiato qualcosa"); + } + } + + [TestMethod] + public void RandomFramesDecodeThroughTheContainer() + { + for (var seed = 50; seed < 60; seed++) + { + var random = new Random(seed); + var width = random.Next(1, 120); + var height = random.Next(1, 90); + var writer = new Vp8TestWriter + { + Width = width, + Height = height, + FilterLevel = random.Next(64), + Sharpness = random.Next(8), + SimpleFilter = random.Next(2) == 0, + Log2Partitions = random.Next(4), + BaseQ = random.Next(128), + QDeltas = [random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16)], + Segmentation = random.Next(2) == 0, + UpdateMap = true, + SegmentQuant = [random.Next(-30, 30), random.Next(-30, 30), random.Next(-30, 30), random.Next(-30, 30)], + SegmentFilter = [random.Next(-20, 20), random.Next(-20, 20), random.Next(-20, 20), random.Next(-20, 20)], + }; + var frame = writer.Write(Vp8TestWriter.Random(writer.MbWidth * writer.MbHeight, seed, maxLevel: 2114)); + var file = WebPTestFiles.Riff(("VP8 ", frame)); + using var image = WebPDecoder.Decode(file); + Assert.AreEqual((width, height), (image.Width, image.Height)); + Assert.IsTrue(image.IsOpaque()); + } + } + + // RFC 6386 §15.2 and §15.1, written apart from the decoder: the simple filter over the luma plane, macroblock + // after macroblock, left edge, inner vertical edges, top edge, inner horizontal edges. + private static void SimpleFilter(byte[] y, int stride, int mbWidth, int mbHeight, Vp8TestMacroblock[] mbs, int level, int sharpness) + { + var interior = level; + if (sharpness > 0) + { + interior >>= sharpness > 4 ? 2 : 1; + interior = Math.Min(interior, 9 - sharpness); + } + + interior = Math.Max(interior, 1); + var mbLimit = ((level + 2) * 2) + interior; + var subLimit = (level * 2) + interior; + for (var mbY = 0; mbY < mbHeight; mbY++) + { + for (var mbX = 0; mbX < mbWidth; mbX++) + { + var mb = mbs[(mbY * mbWidth) + mbX]; + var inner = mb.YMode == Vp8Tables.BPred || HasCoefficients(mb); + var x0 = mbX * 16; + var y0 = mbY * 16; + for (var edge = 0; edge < 16; edge += 4) + { + if ((edge == 0 && mbX > 0) || (edge > 0 && inner)) + { + for (var r = 0; r < 16; r++) + { + Segment(y, ((y0 + r) * stride) + x0 + edge, 1, edge == 0 ? mbLimit : subLimit); + } + } + } + + for (var edge = 0; edge < 16; edge += 4) + { + if ((edge == 0 && mbY > 0) || (edge > 0 && inner)) + { + for (var c = 0; c < 16; c++) + { + Segment(y, ((y0 + edge) * stride) + x0 + c, stride, edge == 0 ? mbLimit : subLimit); + } + } + } + } + } + } + + private static void Segment(byte[] y, int q0At, int step, int edgeLimit) + { + int p1 = y[q0At - (2 * step)] - 128, p0 = y[q0At - step] - 128, q0 = y[q0At] - 128, q1 = y[q0At + step] - 128; + if ((Math.Abs(p0 - q0) * 2) + (Math.Abs(p1 - q1) >> 1) > edgeLimit) + { + return; + } + + static int C(int v) => Math.Clamp(v, -128, 127); + var a = C(C(p1 - q1) + (3 * (q0 - p0))); + var b = C(a + 3) >> 3; + a = C(a + 4) >> 3; + y[q0At] = (byte)(C(q0 - a) + 128); + y[q0At - step] = (byte)(C(p0 + b) + 128); + } + + private static bool HasCoefficients(Vp8TestMacroblock mb) + { + if (mb.Skip) + { + return false; + } + + var i16 = mb.YMode != Vp8Tables.BPred; + for (var b = 0; b < 25; b++) + { + var levels = mb.Levels[b]; + var first = i16 && b < 16 ? 1 : 0; + if (b == 24 && !i16) + { + continue; + } + + for (var n = first; n < 16; n++) + { + if (levels[n] != 0) + { + return true; + } + } + } + + return false; + } + + private static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) Uniform(int yMode, int uvMode, int bMode = Vp8Tables.BDc) => + Planes(new Vp8TestWriter { Width = 48, Height = 32 }.Write(Vp8TestWriter.Uniform(6, yMode, uvMode, bMode))); + + private static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) Planes(byte[] frame) => + Vp8Decoder.DecodePlanes(frame, 0, frame.Length, ImageLimits.Default); + + private static void AssertSamePlanes((byte[] Y, byte[] U, byte[] V, int, int) expected, (byte[] Y, byte[] U, byte[] V, int, int) actual, string what) + { + CollectionAssert.AreEqual(expected.Y, actual.Y, $"{what}: Y"); + CollectionAssert.AreEqual(expected.U, actual.U, $"{what}: U"); + CollectionAssert.AreEqual(expected.V, actual.V, $"{what}: V"); + } +} diff --git a/tests/Febe.Tests/Imaging/Vp8TestWriter.cs b/tests/Febe.Tests/Imaging/Vp8TestWriter.cs new file mode 100644 index 0000000..c25edd8 --- /dev/null +++ b/tests/Febe.Tests/Imaging/Vp8TestWriter.cs @@ -0,0 +1,596 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The boolean entropy encoder of RFC 6386 §7.3 (write_bool, add_one_to_output, flush_bool_encoder), for the tests. +/// +internal sealed class Vp8BoolEncoder +{ + private readonly List _output = []; + private uint _range = 255; + private uint _bottom; + private int _bitCount = 24; + + public void Write(int prob, bool value) + { + var split = 1 + (((_range - 1) * (uint)prob) >> 8); + if (value) + { + _bottom += split; + _range -= split; + } + else + { + _range = split; + } + + while (_range < 128) + { + _range <<= 1; + if ((_bottom & (1u << 31)) != 0) + { + AddOne(); + } + + _bottom <<= 1; + if (--_bitCount == 0) + { + _output.Add((byte)(_bottom >> 24)); + _bottom &= (1 << 24) - 1; + _bitCount = 8; + } + } + } + + public void Write(int prob, int value) => Write(prob, value != 0); + + public void Literal(int value, int bits) + { + for (var b = bits - 1; b >= 0; b--) + { + Write(128, (value >> b) & 1); + } + } + + /// A flag, then (when the value is not 0) magnitude and sign, as the frame header writes deltas. + public void OptionalSigned(int value, int bits) + { + Write(128, value != 0); + if (value != 0) + { + Literal(Math.Abs(value), bits); + Write(128, value < 0); + } + } + + public void Tree(ReadOnlySpan tree, ReadOnlySpan probs, int offset, int leaf) + { + Span path = stackalloc int[16]; + var depth = FindPath(tree, 0, leaf, path, 0); + Assert.IsGreaterThan(0, depth, $"foglia {leaf} assente"); + var node = 0; + for (var i = 0; i < depth; i++) + { + Write(probs[offset + (node >> 1)], path[i]); + node = tree[node + path[i]]; + } + } + + public byte[] Finish() + { + var c = _bitCount; + var v = _bottom; + if ((v & (1u << (32 - c))) != 0) + { + AddOne(); + } + + v <<= c & 7; + c >>= 3; + while (--c >= 0) + { + v <<= 8; + } + + for (c = 0; c < 4; c++) + { + _output.Add((byte)(v >> 24)); + v <<= 8; + } + + return [.. _output]; + } + + private static int FindPath(ReadOnlySpan tree, int node, int leaf, Span path, int depth) + { + for (var bit = 0; bit < 2; bit++) + { + var child = tree[node + bit]; + path[depth] = bit; + if (child <= 0) + { + if (-child == leaf) + { + return depth + 1; + } + } + else + { + var found = FindPath(tree, child, leaf, path, depth + 1); + if (found > 0) + { + return found; + } + } + } + + return 0; + } + + private void AddOne() + { + var i = _output.Count - 1; + while (_output[i] == 255) + { + _output[i] = 0; + i--; + } + + _output[i]++; + } +} + +/// What a test macroblock holds. +internal sealed class Vp8TestMacroblock +{ + public int Segment { get; set; } + + public bool Skip { get; set; } + + /// DC_PRED, V_PRED, H_PRED, TM_PRED or B_PRED (Vp8Tables). + public int YMode { get; set; } + + /// The sixteen subblock modes for B_PRED. + public int[] BModes { get; } = new int[16]; + + public int UvMode { get; set; } + + /// Quantized levels of the 25 blocks (16 Y, 4 U, 4 V, Y2), in zigzag order. + public int[][] Levels { get; } = [.. Enumerable.Range(0, 25).Select(_ => new int[16])]; +} + +/// +/// A VP8 key frame writer for the tests (RFC 6386 §9, §19): any header the decoder reads, given modes and quantized +/// levels of every macroblock, tokens with the same contexts and default probabilities as the decoder. +/// +internal sealed class Vp8TestWriter +{ + public int Width { get; init; } + + public int Height { get; init; } + + public bool Segmentation { get; init; } + + public bool UpdateMap { get; init; } + + public bool AbsoluteDeltas { get; init; } + + public int[] SegmentQuant { get; init; } = new int[4]; + + public int[] SegmentFilter { get; init; } = new int[4]; + + public byte[] SegmentProbs { get; init; } = [128, 128, 128]; + + public bool SimpleFilter { get; init; } + + public int FilterLevel { get; init; } + + public int Sharpness { get; init; } + + public int[]? RefLfDelta { get; init; } + + public int[]? ModeLfDelta { get; init; } + + public int Log2Partitions { get; init; } + + public int BaseQ { get; init; } = 40; + + public int[] QDeltas { get; init; } = new int[5]; + + public bool UseSkipProb { get; init; } = true; + + public int SkipProb { get; init; } = 100; + + public int MbWidth => (Width + 15) / 16; + + public int MbHeight => (Height + 15) / 16; + + /// The VP8 frame (the payload of a «VP8 » chunk). + public byte[] Write(Vp8TestMacroblock[] macroblocks) + { + Assert.HasCount(MbWidth * MbHeight, macroblocks); + var first = new Vp8BoolEncoder(); + WriteHeader(first); + var partitions = Enumerable.Range(0, 1 << Log2Partitions).Select(_ => new Vp8BoolEncoder()).ToArray(); + var intraTop = Enumerable.Repeat(Vp8Tables.BDc, MbWidth * 4).ToArray(); + var nzTop = new int[MbWidth * 9]; + for (var mbY = 0; mbY < MbHeight; mbY++) + { + var intraLeft = new int[] { Vp8Tables.BDc, Vp8Tables.BDc, Vp8Tables.BDc, Vp8Tables.BDc }; + var nzLeft = new int[9]; + var tokens = partitions[mbY % partitions.Length]; + for (var mbX = 0; mbX < MbWidth; mbX++) + { + var mb = macroblocks[(mbY * MbWidth) + mbX]; + WriteModes(first, mb, intraTop.AsSpan(mbX * 4, 4), intraLeft); + var top = nzTop.AsSpan(mbX * 9, 9); + if (UseSkipProb && mb.Skip) + { + top[..8].Clear(); + nzLeft.AsSpan(0, 8).Clear(); + if (mb.YMode != Vp8Tables.BPred) + { + top[8] = nzLeft[8] = 0; + } + + continue; + } + + WriteResiduals(tokens, mb, top, nzLeft); + } + } + + var firstBytes = first.Finish(); + var partitionBytes = partitions.Select(p => p.Finish()).ToArray(); + using var frame = new MemoryStream(); + var tag = (firstBytes.Length << 5) | (1 << 4); // key frame, version 0, shown + frame.Write([(byte)tag, (byte)(tag >> 8), (byte)(tag >> 16), 0x9D, 0x01, 0x2A, (byte)Width, (byte)(Width >> 8), (byte)Height, (byte)(Height >> 8)]); + frame.Write(firstBytes); + for (var i = 0; i < partitionBytes.Length - 1; i++) + { + var size = partitionBytes[i].Length; + frame.Write([(byte)size, (byte)(size >> 8), (byte)(size >> 16)]); + } + + foreach (var p in partitionBytes) + { + frame.Write(p); + } + + return frame.ToArray(); + } + + /// A frame of empty macroblocks with the given modes (skip set, so no tokens). + public static Vp8TestMacroblock[] Uniform(int count, int yMode, int uvMode, int bMode = Vp8Tables.BDc) + { + var mbs = new Vp8TestMacroblock[count]; + for (var i = 0; i < count; i++) + { + mbs[i] = new Vp8TestMacroblock { YMode = yMode, UvMode = uvMode, Skip = true }; + Array.Fill(mbs[i].BModes, bMode); + } + + return mbs; + } + + /// Random modes, segments and levels from a fixed seed; about a third of the blocks empty. + public static Vp8TestMacroblock[] Random(int count, int seed, int maxLevel = 40, bool skips = true) + { + var random = new Random(seed); + var mbs = new Vp8TestMacroblock[count]; + for (var i = 0; i < count; i++) + { + var mb = new Vp8TestMacroblock + { + Segment = random.Next(4), + YMode = random.Next(5), + UvMode = random.Next(4), + Skip = skips && random.Next(6) == 0, + }; + for (var b = 0; b < 16; b++) + { + mb.BModes[b] = random.Next(Vp8Tables.NumBModes); + } + + foreach (var block in mb.Levels) + { + if (random.Next(3) == 0) + { + continue; + } + + var count2 = random.Next(1, 17); + for (var k = 0; k < count2; k++) + { + var position = random.Next(k < 3 ? 4 : 16); + var magnitude = random.Next(8) == 0 ? random.Next(1, maxLevel + 1) : random.Next(1, 4); + block[position] = random.Next(2) == 0 ? magnitude : -magnitude; + } + } + + mbs[i] = mb; + } + + return mbs; + } + + private void WriteHeader(Vp8BoolEncoder e) + { + e.Literal(0, 1); // colour space + e.Literal(0, 1); // clamping type + e.Write(128, Segmentation); + if (Segmentation) + { + e.Write(128, UpdateMap); + e.Write(128, true); // update segment feature data + e.Write(128, AbsoluteDeltas); + foreach (var q in SegmentQuant) + { + e.OptionalSigned(q, 7); + } + + foreach (var f in SegmentFilter) + { + e.OptionalSigned(f, 6); + } + + if (UpdateMap) + { + foreach (var p in SegmentProbs) + { + e.Write(128, true); + e.Literal(p, 8); + } + } + } + + e.Write(128, SimpleFilter); + e.Literal(FilterLevel, 6); + e.Literal(Sharpness, 3); + var deltas = RefLfDelta is not null || ModeLfDelta is not null; + e.Write(128, deltas); + if (deltas) + { + e.Write(128, true); + foreach (var d in RefLfDelta ?? new int[4]) + { + e.OptionalSigned(d, 6); + } + + foreach (var d in ModeLfDelta ?? new int[4]) + { + e.OptionalSigned(d, 6); + } + } + + e.Literal(Log2Partitions, 2); + e.Literal(BaseQ, 7); + foreach (var d in QDeltas) + { + e.OptionalSigned(d, 4); + } + + e.Write(128, false); // refresh entropy probs + foreach (var p in Vp8Tables.CoefficientUpdateProbs) + { + e.Write(p, false); // no probability updated + } + + e.Write(128, UseSkipProb); + if (UseSkipProb) + { + e.Literal(SkipProb, 8); + } + } + + private void WriteModes(Vp8BoolEncoder e, Vp8TestMacroblock mb, Span top, int[] left) + { + if (UpdateMap) + { + var s = mb.Segment; + e.Write(SegmentProbs[0], s >= 2); + e.Write(SegmentProbs[s >= 2 ? 2 : 1], s & 1); + } + + if (UseSkipProb) + { + e.Write(SkipProb, mb.Skip); + } + + if (mb.YMode == Vp8Tables.BPred) + { + e.Write(145, false); + for (var row = 0; row < 4; row++) + { + for (var col = 0; col < 4; col++) + { + var mode = mb.BModes[(row * 4) + col]; + e.Tree(Vp8Tables.BModeTree, Vp8Tables.KeyFrameBModeProbs, ((top[col] * Vp8Tables.NumBModes) + left[row]) * 9, mode); + top[col] = left[row] = mode; + } + } + } + else + { + e.Write(145, true); + var y = mb.YMode; + e.Write(156, y is Vp8Tables.HPred or Vp8Tables.TmPred); + if (y is Vp8Tables.HPred or Vp8Tables.TmPred) + { + e.Write(128, y == Vp8Tables.TmPred); + } + else + { + e.Write(163, y == Vp8Tables.VPred); + } + + var implied = y switch { Vp8Tables.VPred => Vp8Tables.BVe, Vp8Tables.HPred => Vp8Tables.BHe, Vp8Tables.TmPred => Vp8Tables.BTm, _ => Vp8Tables.BDc }; + top.Fill(implied); + Array.Fill(left, implied); + } + + var uv = mb.UvMode; + e.Write(142, uv != Vp8Tables.DcPred); + if (uv != Vp8Tables.DcPred) + { + e.Write(114, uv != Vp8Tables.VPred); + if (uv != Vp8Tables.VPred) + { + e.Write(183, uv == Vp8Tables.TmPred); + } + } + } + + private static void WriteResiduals(Vp8BoolEncoder e, Vp8TestMacroblock mb, Span top, int[] left) + { + int first; + int yType; + if (mb.YMode != Vp8Tables.BPred) + { + var flag = WriteBlock(e, 1, top[8] + left[8], 0, mb.Levels[24]); + top[8] = left[8] = flag; + first = 1; + yType = 0; + } + else + { + first = 0; + yType = 3; + } + + for (var row = 0; row < 4; row++) + { + for (var col = 0; col < 4; col++) + { + var flag = WriteBlock(e, yType, top[col] + left[row], first, mb.Levels[(row * 4) + col]); + top[col] = left[row] = flag; + } + } + + for (var plane = 0; plane < 2; plane++) + { + for (var row = 0; row < 2; row++) + { + for (var col = 0; col < 2; col++) + { + var t = 4 + (plane * 2) + col; + var l = 4 + (plane * 2) + row; + var flag = WriteBlock(e, 2, top[t] + left[l], 0, mb.Levels[16 + (plane * 4) + (row * 2) + col]); + top[t] = left[l] = flag; + } + } + } + } + + // RFC 6386 §13: the tokens of one block from position `first`; returns the context flag (any token not EOB). + private static int WriteBlock(Vp8BoolEncoder e, int type, int context, int first, int[] levels) + { + var probs = Vp8Tables.DefaultCoefficientProbs; + var bands = Vp8Tables.Bands; + var last = -1; + for (var n = first; n < 16; n++) + { + if (levels[n] != 0) + { + last = n; + } + } + + var p = Index(type, bands[first], context); + if (last < 0) + { + e.Write(probs[p], false); + return 0; + } + + var afterZero = false; + for (var n = first; n <= last; n++) + { + if (!afterZero) + { + e.Write(probs[p], true); // not the end of the block + } + + var v = Math.Abs(levels[n]); + if (v == 0) + { + e.Write(probs[p + 1], false); + p = Index(type, bands[n + 1], 0); + afterZero = true; + continue; + } + + e.Write(probs[p + 1], true); + int context2; + if (v == 1) + { + e.Write(probs[p + 2], false); + context2 = 1; + } + else + { + e.Write(probs[p + 2], true); + WriteLarge(e, probs.Slice(p, 11), v); + context2 = 2; + } + + e.Write(128, levels[n] < 0); + p = Index(type, bands[n + 1], context2); + afterZero = false; + } + + if (last < 15) + { + e.Write(probs[p], false); // end of block + } + + return 1; + } + + private static void WriteLarge(Vp8BoolEncoder e, ReadOnlySpan p, int v) + { + if (v <= 4) + { + e.Write(p[3], false); + e.Write(p[4], v != 2); + if (v != 2) + { + e.Write(p[5], v == 4); + } + + return; + } + + e.Write(p[3], true); + if (v <= 10) + { + e.Write(p[6], false); + e.Write(p[7], v > 6); + if (v <= 6) + { + e.Write(159, v - 5); + } + else + { + e.Write(165, (v - 7) >> 1); + e.Write(145, (v - 7) & 1); + } + + return; + } + + e.Write(p[6], true); + var category = v <= 18 ? 0 : v <= 34 ? 1 : v <= 66 ? 2 : 3; + e.Write(p[8], category >> 1); + e.Write(p[9 + (category >> 1)], category & 1); + var extra = category switch { 0 => Vp8Tables.Cat3, 1 => Vp8Tables.Cat4, 2 => Vp8Tables.Cat5, _ => Vp8Tables.Cat6 }; + var value = v - 3 - (8 << category); + for (var i = 0; i < extra.Length; i++) + { + e.Write(extra[i], (value >> (extra.Length - 1 - i)) & 1); + } + } + + private static int Index(int type, int band, int context) => (((type * 8) + band) * 3 + context) * 11; +} diff --git a/tests/Febe.Tests/Imaging/WebPContainerTests.cs b/tests/Febe.Tests/Imaging/WebPContainerTests.cs new file mode 100644 index 0000000..57fc1fc --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPContainerTests.cs @@ -0,0 +1,471 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The WebP container (RFC 9649 §2): the extended format with ALPH in every variant, ICCP, EXIF and XMP; the first +/// frame of an animation on its canvas; limits; and files that are damaged or cut short. +/// +[TestClass] +public sealed class WebPContainerTests +{ + private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 }; + + [TestMethod] + public void EveryAlphaVariantGivesTheSamePicture() + { + var reference = ReferenceImages.Get("webp-perdita-alfa-q80"); + var original = reference.ReadInput(); + using var expected = WebPDecoder.Decode(original); + var vp8 = WebPTestFiles.Payload(original, "VP8 "); + var alpha = WebPTestFiles.AlphaOf(expected); + var (w, h) = (expected.Width, expected.Height); + Assert.IsTrue(alpha.Distinct().Count() > 2, "il riferimento ha un'alfa vera"); + + for (var filter = 0; filter < 4; filter++) + { + var filtered = WebPTestFiles.FilterAlpha(alpha, w, h, filter); + foreach (var preprocessed in (bool[])[false, true]) + { + var flags = (filter << 2) | (preprocessed ? 0x10 : 0); + var raw = File((byte)flags, filtered); + var compressed = File((byte)(flags | 1), WebPEncoder.EncodeAlphaStream(filtered, w, h, Vp8LEncoderSettings.Default)); + using var fromRaw = WebPDecoder.Decode(raw); + using var fromCompressed = WebPDecoder.Decode(compressed); + ImageAssert.AreEqual(expected, fromRaw, $"grezza, filtro {filter}"); + ImageAssert.AreEqual(expected, fromCompressed, $"compressa, filtro {filter}"); + } + } + + // A raw plane with bytes to spare is fine; a short one, an unknown method or reserved bits are not. + using (var longer = WebPDecoder.Decode(File(0, [.. alpha, 1, 2, 3]))) + { + ImageAssert.AreEqual(expected, longer, "byte in più"); + } + + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0, alpha[..^1]))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(2, alpha))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0x40, alpha))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0x20, alpha))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(1, [1, 2, 3]))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, w, h)), ("ALPH", []), ("VP8 ", vp8)))); + + byte[] File(byte header, byte[] plane) => + WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, w, h)), ("ALPH", [header, .. plane]), ("VP8 ", vp8)); + } + + [TestMethod] + public void TheAlphaFilterIsUndoneForEveryMethod() + { + var random = new Random(61); + foreach (var (w, h) in new[] { (1, 1), (1, 7), (9, 1), (13, 11) }) + { + var alpha = new byte[w * h]; + random.NextBytes(alpha); + for (var filter = 0; filter < 4; filter++) + { + var plane = WebPTestFiles.FilterAlpha(alpha, w, h, filter); + WebPAlpha.Unfilter(plane, w, h, filter); + CollectionAssert.AreEqual(alpha, plane, $"{w}×{h}, filtro {filter}"); + } + } + } + + [TestMethod] + public void TheExtendedFormatCarriesMetadataAroundAStillPicture() + { + var lossy = ReferenceImages.Get("webp-perdita-q80").ReadInput(); + using var expected = WebPDecoder.Decode(lossy); + var vp8 = WebPTestFiles.Payload(lossy, "VP8 "); + var tiff = WebPTestFiles.Tiff(8); + var icc = new byte[77]; + new Random(62).NextBytes(icc); + var file = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x20 | 0x08 | 0x04, 101, 67)), + ("ICCP", icc), + ("VP8 ", vp8), + ("ABCD", [1, 2, 3]), + ("EXIF", [.. "Exif\0\0"u8, .. tiff]), + ("XMP ", ""u8.ToArray())); + using var image = WebPDecoder.Decode(file, out var info); + ImageAssert.AreEqual(expected, image, "VP8 dentro VP8X"); + Assert.AreEqual((101, 67, 1, false), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); + CollectionAssert.AreEqual(tiff, info.Metadata.Exif, "il prefisso «Exif» si toglie"); + Assert.AreEqual(8, info.Metadata.Orientation); + CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); + Assert.AreEqual("", info.Metadata.Xmp); + Assert.AreEqual(8, WebPDecoder.Identify(file).Metadata.Orientation); + + // Metadata beyond the budget is skipped, the picture is still read. + var tight = WebPDecoder.Identify(file, ImageLimits.Default with { MaxMetadataBytes = 50 }); + Assert.IsNull(tight.Metadata.IccProfile); + CollectionAssert.AreEqual(tiff, tight.Metadata.Exif); + + // VP8L inside VP8X; a canvas of another size is refused. + var lossless = ReferenceImages.Get("webp-senza-perdita").ReadInput(); + var vp8l = WebPTestFiles.Payload(lossless, "VP8L"); + using var simple = WebPDecoder.Decode(lossless); + using var extended = WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 101, 67)), ("VP8L", vp8l))); + ImageAssert.AreEqual(simple, extended, "VP8L dentro VP8X"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 102, 67)), ("VP8L", vp8l)))); + Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0, 101, 67))))); + Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", new byte[9]), ("VP8L", vp8l)))); + Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("ABCD", vp8l)))); + } + + [TestMethod] + public void TheFirstFrameOfAnAnimationIsPlacedAndBlendedOnTheCanvas() + { + using var frame = TestImages.Random(20, 10, 63); // random alpha, some 0 and some 255 + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(frame), "VP8L"); + using var second = TestImages.Random(8, 8, 64, opaque: true); + var secondFrame = WebPTestFiles.Anmf(0, 0, 8, 8, 0, ("VP8L", WebPTestFiles.Payload(WebPEncoder.Encode(second), "VP8L"))); + + foreach (var blend in (bool[])[true, false]) + { + var file = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 40, 30)), + ("ANIM", WebPTestFiles.Anim(0xFF0000FF, 0)), + ("ANMF", WebPTestFiles.Anmf(4, 6, 20, 10, blend ? 0 : 2, ("VP8L", vp8l))), + ("ANMF", secondFrame)); + using var canvas = WebPDecoder.Decode(file, out var info); + Assert.AreEqual((40, 30, 2, true), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); + for (var y = 0; y < 30; y++) + { + for (var x = 0; x < 40; x++) + { + var inside = x >= 4 && x < 24 && y >= 6 && y < 16; + var actual = canvas.GetPixel(x, y); + if (!inside) + { + Assert.AreEqual(((byte)0, (byte)0, (byte)0, (byte)0), actual, $"fuori dal fotogramma ({x}, {y})"); + continue; + } + + var source = frame.GetPixel(x - 4, y - 6); + + // On a transparent canvas blending gives the source, and transparent black where it is transparent. + var expected = blend && source.A == 0 ? ((byte)0, (byte)0, (byte)0, (byte)0) : source; + Assert.AreEqual(expected, actual, $"fondere {blend}, ({x}, {y})"); + } + } + + Assert.AreEqual(2, ImageDecoder.Identify(file).FrameCount); + } + + // A lossy frame with alpha that covers the canvas reads as the still picture. + var lossy = ReferenceImages.Get("webp-perdita-alfa-q80").ReadInput(); + using var still = WebPDecoder.Decode(lossy); + var animated = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 101, 67)), + ("ANIM", WebPTestFiles.Anim()), + ("ANMF", WebPTestFiles.Anmf(0, 0, 101, 67, 2, ("ALPH", WebPTestFiles.Payload(lossy, "ALPH")), ("VP8 ", WebPTestFiles.Payload(lossy, "VP8 "))))); + using var first = WebPDecoder.Decode(animated); + ImageAssert.AreEqual(still, first, "fotogramma VP8 con ALPH"); + } + + [TestMethod] + public void BrokenAnimationsAreRefused() + { + using var frame = TestImages.Random(20, 10, 65); + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(frame), "VP8L"); + byte[] Animation(params (string, byte[])[] chunks) => WebPTestFiles.Riff([("VP8X", WebPTestFiles.Vp8X(0x02, 40, 30)), ("ANIM", WebPTestFiles.Anim()), .. chunks]); + + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(22, 0, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 22, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela in basso"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 21, 10, 0, ("VP8L", vp8l))))), "misura diversa dall'immagine"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 20, 10, 0)))), "senza immagine"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", new byte[15]))), "ANMF corto"); + Assert.ThrowsExactly(() => WebPDecoder.Identify(Animation()), "nessun fotogramma"); + } + + [TestMethod] + public void BlendingFollowsTheFormulaOfTheSpecification() + { + // A = As + Ad·(1 − As), RGB = (RGBs·As + RGBd·Ad·(1 − As)) / A. + var destination = new byte[] { 200, 100, 0, 128 }; + WebPDecoder.Blend([0, 50, 250, 64], destination); + var sa = 64 / 255.0; + var da = 128 / 255.0 * (1 - sa); + var a = sa + da; + Assert.AreEqual((int)Math.Round(a * 255), destination[3]); + Assert.AreEqual((int)Math.Round(((0 * sa) + (200 * da)) / a), destination[0]); + Assert.AreEqual((int)Math.Round(((50 * sa) + (100 * da)) / a), destination[1]); + Assert.AreEqual((int)Math.Round(((250 * sa) + (0 * da)) / a), destination[2]); + + var opaque = new byte[] { 1, 2, 3, 4 }; + WebPDecoder.Blend([9, 8, 7, 255], opaque); + CollectionAssert.AreEqual(new byte[] { 9, 8, 7, 255 }, opaque); + var keep = new byte[] { 1, 2, 3, 40 }; + WebPDecoder.Blend([9, 8, 7, 0], keep); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 40 }, keep); + } + + [TestMethod] + public void LimitsAreCheckedBeforeDecoding() + { + using var image = TestImages.Random(4, 4, 66); + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(image), "VP8L"); + + // A canvas of 16384×16384 announced by VP8X for an animation: Identify tells its size, Decode refuses it. + var big = WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x02, 16384, 16384)), ("ANIM", WebPTestFiles.Anim()), ("ANMF", WebPTestFiles.Anmf(0, 0, 4, 4, 0, ("VP8L", vp8l)))); + var info = WebPDecoder.Identify(big, Small); + Assert.AreEqual((16384, 16384), (info.Width, info.Height)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(big, Small)); + + // A VP8L header claiming 4000×4000 with nothing behind it: over the small limits it is refused for its + // size, within the default ones for the missing data. + var writer = new Vp8LBitWriter(); + writer.WriteBits(0x2F, 8); + writer.WriteBits(3999, 14); + writer.WriteBits(3999, 14); + writer.WriteBits(0, 4); + writer.WriteBits(0, 16); + var empty = WebPTestFiles.Riff(("VP8L", writer.ToArray())); + Assert.AreEqual((4000, 4000), (WebPDecoder.Identify(empty, Small).Width, WebPDecoder.Identify(empty, Small).Height)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(empty, Small)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(empty)); + } + + [TestMethod] + public void DamagedHeadersAreRefused() + { + var lossy = ReferenceImages.Get("webp-perdita-q30").ReadInput(); + var vp8 = WebPTestFiles.Payload(lossy, "VP8 "); + Assert.ThrowsExactly(() => WebPDecoder.Decode("RIFF\0\0\0\0WEBQ"u8.ToArray())); + Assert.ThrowsExactly(() => WebPDecoder.Decode((byte[])[.. "RIFF"u8, 3, 0, 0, 0, .. "WEBP"u8])); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff())); + + // RIFF size beyond the file; a chunk beyond the RIFF size. + var longer = lossy.ToArray(); + BinaryPrimitives.WriteUInt32LittleEndian(longer.AsSpan(4), (uint)(lossy.Length - 8 + 2)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(longer)); + var chunk = lossy.ToArray(); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(16), (uint)(vp8.Length + 3)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(chunk)); + + // Trailing bytes after the RIFF size are ignored. + using (var trailing = WebPDecoder.Decode((byte[])[.. lossy, 1, 2, 3, 4, 5])) + using (var plain = WebPDecoder.Decode(lossy)) + { + ImageAssert.AreEqual(plain, trailing, "byte dopo il RIFF"); + } + + // VP8 frame header: inter frame, unknown version, not shown, start code, zero size, first partition too long. + foreach (var (at, value, what) in new[] { (0, vp8[0] | 1, "interfotogramma"), (0, (vp8[0] & 0xF1) | 0x08, "versione 4"), (0, vp8[0] & 0xEF, "da non mostrare"), (3, 0x9C, "codice d'inizio"), (6, 0, "larghezza nulla") }) + { + var bad = vp8.ToArray(); + bad[at] = (byte)value; + if (what == "larghezza nulla") + { + bad[7] &= 0xC0; + } + + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", bad))), what); + } + + var huge = vp8.ToArray(); + huge[2] = 0xFF; + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", huge))), "prima partizione troppo lunga"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", vp8[..9])))); + + // VP8L header: signature, version. + var vp8l = WebPTestFiles.Payload(ReferenceImages.Get("webp-senza-perdita").ReadInput(), "VP8L"); + var signature = vp8l.ToArray(); + signature[0] = 0x2E; + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", signature)))); + var version = vp8l.ToArray(); + version[4] |= 0x20; + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", version)))); + } + + [TestMethod] + public void DamagedLosslessStreamsAreRefused() + { + // Built bit by bit: header of a 4×4 image, then what follows. + byte[] Stream(Action body) + { + var writer = new Vp8LBitWriter(); + writer.WriteBits(0x2F, 8); + writer.WriteBits(3, 14); + writer.WriteBits(3, 14); + writer.WriteBits(0, 4); + body(writer); + writer.WriteBits(0, 32); + return WebPTestFiles.Riff(("VP8L", writer.ToArray())); + } + + void SimpleCode(Vp8LBitWriter w, int symbol) + { + w.WriteBits(1, 1); // simple + w.WriteBits(0, 1); // one symbol + w.WriteBits(1, 1); // eight bits + w.WriteBits((uint)symbol, 8); + } + + void NoTransformNoCache(Vp8LBitWriter w) + { + w.WriteBits(0, 1); // no transform + w.WriteBits(0, 1); // no colour cache + w.WriteBits(0, 1); // no meta codes + } + + // A valid stream: every pixel the literal (green 7, red 1, blue 2, alpha 3). + var valid = Stream(w => + { + NoTransformNoCache(w); + SimpleCode(w, 7); + SimpleCode(w, 1); + SimpleCode(w, 2); + SimpleCode(w, 3); + SimpleCode(w, 0); + }); + using (var image = WebPDecoder.Decode(valid)) + { + Assert.AreEqual(((byte)1, (byte)7, (byte)2, (byte)3), image.GetPixel(3, 3)); + } + + // The same transform twice. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + w.WriteBits(1, 1); + w.WriteBits(2, 2); + w.WriteBits(1, 1); + w.WriteBits(2, 2); + }))); + + // Colour cache of 0 and 12 bits. + foreach (var bits in (uint[])[0, 12]) + { + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + w.WriteBits(0, 1); + w.WriteBits(1, 1); + w.WriteBits(bits, 4); + })), $"cache {bits}"); + } + + // An incomplete normal code: code length code with two lengths of 2 (half the space unused). + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + NoTransformNoCache(w); + w.WriteBits(0, 1); + w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 + w.WriteBits(0, 3); + w.WriteBits(0, 3); + w.WriteBits(2, 3); + w.WriteBits(2, 3); + }))); + + // A simple code naming a symbol outside a distance alphabet of 40. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + NoTransformNoCache(w); + SimpleCode(w, 7); + SimpleCode(w, 1); + SimpleCode(w, 2); + SimpleCode(w, 3); + SimpleCode(w, 45); + }))); + + // A backward reference before the first pixel: the green code has only symbol 256 + 0 (length 1)... which + // needs a normal code since it is above 255; here a two-symbol simple code cannot reach it, so use the cache + // index instead: a cache symbol with no cache is damage. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + w.WriteBits(0, 1); + w.WriteBits(1, 1); + w.WriteBits(1, 4); // cache of 2 entries: green alphabet 282 + w.WriteBits(0, 1); + Normal(w, 282, 256); + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 0); + }))); + + // A distance past the start of the image. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + NoTransformNoCache(w); + Normal(w, 280, 256 + 3); // only length symbol 3: length 4 + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 39); // the largest distance + w.WriteBits(0, 18); + }))); + } + + [TestMethod] + public void StreamsCutShortAreRefusedOrReadWhole() + { + foreach (var name in (string[])["webp-senza-perdita", "webp-senza-perdita-rapido", "webp-perdita-q30", "webp-perdita-alfa-q80"]) + { + var input = ReferenceImages.Get(name).ReadInput(); + using var whole = WebPDecoder.Decode(input); + var chunks = WebPTestFiles.Chunks(input); + var last = chunks[^1]; + var lossless = last.Type == "VP8L"; + for (var cut = 1; cut < last.Payload.Length - 1; cut++) + { + // Cut the image chunk, and keep the RIFF consistent so only the bitstream is short. + var shorter = last.Payload[..^cut]; + var file = WebPTestFiles.Riff([.. chunks.Take(chunks.Count - 1), (last.Type, shorter)]); + RgbaImage? image = null; + try + { + image = WebPDecoder.Decode(file); + } + catch (ImageDecodeException) + { + } + + using (image) + { + if (image is null) + { + continue; + } + + // What is read is read whole. The boolean coder ends with flush bytes the decoder may never + // need (measured: up to 3 on these files), so a lossy stream can lose only those. + ImageAssert.AreEqual(whole, image, $"{name} senza gli ultimi {cut} byte"); + if (!lossless) + { + Assert.IsLessThanOrEqualTo(4, cut, $"{name}: senza gli ultimi {cut} byte la lettura doveva fermarsi"); + } + } + } + + // Plainly cut files (RIFF size beyond the end) are refused at every length. + for (var length = 0; length < input.Length; length += Math.Max(1, input.Length / 200)) + { + Assert.ThrowsExactly(() => WebPDecoder.Decode(input[..length]), $"{name} tagliato a {length}"); + } + } + } + + // A normal code over `alphabet` symbols in which only `symbol` has a length (a code of zero bits): code length + // code with the single symbol 1 (zero bits too), then max_symbol so only the lengths up to `symbol` are read. + private static void Normal(Vp8LBitWriter w, int alphabet, int symbol) + { + w.WriteBits(0, 1); + w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 + w.WriteBits(0, 3); + w.WriteBits(0, 3); + w.WriteBits(1, 3); // length code 0 has length 1 + w.WriteBits(1, 3); // length code 1 has length 1 + w.WriteBits(1, 1); // max_symbol present + w.WriteBits(4, 3); // length_nbits = 2 + 2·4 = 10 + w.WriteBits((uint)(symbol + 1 - 2), 10); + for (var s = 0; s < symbol; s++) + { + w.WriteBits(0, 1); // length 0 (code 0) + } + + w.WriteBits(1, 1); // length 1 (code 1) + Assert.IsGreaterThan(symbol, alphabet); + } +} diff --git a/tests/Febe.Tests/Imaging/WebPEncoderTests.cs b/tests/Febe.Tests/Imaging/WebPEncoderTests.cs new file mode 100644 index 0000000..9286f7d --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPEncoderTests.cs @@ -0,0 +1,227 @@ +using System.Globalization; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The in-house lossless WebP encoder: every image comes back exactly with each tool alone and with all of them, +/// metadata goes into a VP8X file in the order of RFC 9649, and what cannot be written is refused. +/// +[TestClass] +public sealed class WebPEncoderTests +{ + private static readonly Vp8LEncoderSettings Nothing = new() + { + Palette = false, + SubtractGreen = false, + Predictor = false, + ColorTransform = false, + Lz77 = false, + ColorCacheBits = 0, + }; + + public TestContext TestContext { get; set; } = null!; + + public static IEnumerable Tools => + [ + ["nessuno"], + ["tavolozza"], + ["verde"], + ["predittore"], + ["colore"], + ["lz77"], + ["cache"], + ["tutti"], + ["predittore-piccolo"], + ["predittore-grande"], + ]; + + [TestMethod] + [DynamicData(nameof(Tools))] + public void EveryImageComesBackExactly(string tool) + { + var settings = Settings(tool); + var sizes = new (int Width, int Height)[] { (1, 1), (2, 1), (1, 3), (5, 4), (17, 13), (64, 1), (1, 40), (101, 67) }; + var seed = 10; + foreach (var (width, height) in sizes) + { + foreach (var image in Images(width, height, seed++)) + { + using (image) + { + var file = WebPEncoder.Encode(image, new WebPEncoderOptions { Lossless = settings }); + using var back = WebPDecoder.Decode(file); + ImageAssert.AreEqual(image, back, $"{tool}, {width}×{height}"); + } + } + } + } + + [TestMethod] + public void TheReferencesComeBackExactly() + { + long ours = 0; + long png = 0; + foreach (var reference in ReferenceImages.All) + { + using var image = PngDecoder.Decode(reference.ReadExpectedPng()); + var file = WebPEncoder.Encode(image); + using var back = WebPDecoder.Decode(file); + ImageAssert.AreEqual(image, back, reference.Name); + ours += file.Length; + png += PngEncoder.Encode(image).Length; + } + + TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"57 riferimenti: WebP senza perdita {ours} byte, PNG di casa {png} byte ({100.0 * ours / png:F1}%).")); + Assert.IsLessThan(png, ours, "il WebP senza perdita deve stare sotto il PNG di casa"); + } + + [TestMethod] + public void TheToolsMakeTheFilesSmaller() + { + // On the large lossless reference the default tools beat plain Huffman coding by a wide margin, and stay + // within reach of libwebp's own file. + var reference = ReferenceImages.Get("webp-grande-senza-perdita"); + using var image = PngDecoder.Decode(reference.ReadExpectedPng()); + var plain = WebPEncoder.Encode(image, new WebPEncoderOptions { Lossless = Nothing }).Length; + var full = WebPEncoder.Encode(image).Length; + var skia = reference.ReadInput().Length; + TestContext.WriteLine($"{reference.Name}: solo Huffman {plain} byte, tutti gli strumenti {full} byte, libwebp {skia} byte."); + Assert.IsLessThan(plain * 3 / 4, full); + Assert.IsLessThan(skia * 2, full); + + using var flat = new RgbaImage(300, 200); + flat.Pixels.Fill(0x80); + Assert.IsLessThan(100, WebPEncoder.Encode(flat).Length); + } + + [TestMethod] + public void WithoutMetadataTheFileIsTheSimpleFormat() + { + using var opaque = TestImages.Random(9, 7, 3, opaque: true); + var file = WebPEncoder.Encode(opaque); + var chunks = WebPTestFiles.Chunks(file); + Assert.AreEqual("VP8L", chunks.Single().Type); + var info = WebPDecoder.Identify(file); + Assert.AreEqual((9, 7, 1, false), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); + + using var transparent = TestImages.Random(9, 7, 3); + Assert.IsTrue(WebPDecoder.Identify(WebPEncoder.Encode(transparent)).HasAlpha); + } + + [TestMethod] + public void MetadataGoesIntoAnExtendedFileInOrder() + { + using var image = TestImages.Random(11, 5, 4); + var tiff = WebPTestFiles.Tiff(6); + var icc = new byte[301]; + new Random(5).NextBytes(icc); + const string Xmp = "città"; + var file = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = [.. "Exif\0\0"u8, .. tiff], IccProfile = icc, Xmp = Xmp }); + + var chunks = WebPTestFiles.Chunks(file); + CollectionAssert.AreEqual(new[] { "VP8X", "ICCP", "VP8L", "EXIF", "XMP " }, chunks.Select(c => c.Type).ToArray()); + var vp8x = chunks[0].Payload; + Assert.AreEqual(0x20 | 0x10 | 0x08 | 0x04, vp8x[0]); + Assert.AreEqual((10, 4), (vp8x[4] | (vp8x[5] << 8) | (vp8x[6] << 16), vp8x[7] | (vp8x[8] << 8) | (vp8x[9] << 16))); + CollectionAssert.AreEqual(tiff, chunks[3].Payload, "il prefisso «Exif» di JPEG si toglie"); + Assert.AreEqual(file.Length, 8 + (int)System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4))); + Assert.AreEqual(0, file.Length % 2); + + using var back = WebPDecoder.Decode(file, out var info); + ImageAssert.AreEqual(image, back, "con i metadati"); + CollectionAssert.AreEqual(tiff, info.Metadata.Exif); + Assert.AreEqual(6, info.Metadata.Orientation); + CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); + Assert.AreEqual(Xmp, info.Metadata.Xmp); + Assert.IsTrue(info.HasAlpha); + + // Only one kind of metadata: only its flag; an opaque image has no alpha flag. + using var opaque = TestImages.Random(4, 4, 6, opaque: true); + var onlyXmp = WebPEncoder.Encode(opaque, new WebPEncoderOptions { Xmp = "x" }); + Assert.AreEqual(0x04, WebPTestFiles.Payload(onlyXmp, "VP8X")[0]); + Assert.AreEqual("x", WebPDecoder.Identify(onlyXmp).Metadata.Xmp); + } + + [TestMethod] + public void WhatCannotBeWrittenIsRefused() + { + using var image = TestImages.Random(3, 3, 7); + Assert.Throws(() => WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = "non TIFF"u8.ToArray() })); + Assert.Throws(() => WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = [.. "Exif\0\0"u8, 1, 2] })); + Assert.Throws(() => WebPEncoder.Encode(null!)); + using var wide = new RgbaImage(WebPEncoder.MaxDimension + 1, 1); + Assert.Throws(() => WebPEncoder.Encode(wide)); + using var tall = new RgbaImage(1, WebPEncoder.MaxDimension + 1); + Assert.Throws(() => WebPEncoder.Encode(tall)); + } + + [TestMethod] + public void TheLargestSideIsWritten() + { + using var image = TestImages.Random(WebPEncoder.MaxDimension, 2, 8); + var file = WebPEncoder.Encode(image); + using var back = WebPDecoder.Decode(file); + ImageAssert.AreEqual(image, back, "16384×2"); + } + + [TestMethod] + public void ThePrefixCodesOfLengthsAndDistancesInvertTheDecoder() + { + for (var value = 1; value <= (1 << 20); value += value < 5000 ? 1 : 997) + { + var (symbol, bits, extra) = Vp8LEncoder.Prefix(value); + Assert.IsLessThan(40, symbol); + var decoded = symbol < 4 ? symbol + 1 : ((2 + (symbol & 1)) << ((symbol - 2) >> 1)) + extra + 1; + Assert.AreEqual(value, decoded, $"valore {value}"); + Assert.AreEqual(symbol < 4 ? 0 : (symbol - 2) >> 1, bits); + } + + // The 120 short codes cover the neighbours exactly once. + for (var code = 1; code <= 120; code++) + { + var (dx, dy) = Vp8LDecoder.ShortDistance(code); + Assert.AreEqual(code, Vp8LEncoder.DistanceCode(dx + (dy * 1000), 1000), $"codice {code}"); + } + + Assert.AreEqual(9000 + 120, Vp8LEncoder.DistanceCode(9000, 1000)); // eight rows up: no short code + } + + private static Vp8LEncoderSettings Settings(string tool) => tool switch + { + "nessuno" => Nothing, + "tavolozza" => Nothing with { Palette = true }, + "verde" => Nothing with { SubtractGreen = true }, + "predittore" => Nothing with { Predictor = true }, + "colore" => Nothing with { ColorTransform = true }, + "lz77" => Nothing with { Lz77 = true }, + "cache" => Nothing with { ColorCacheBits = 6 }, + "predittore-piccolo" => Vp8LEncoderSettings.Default with { Palette = false, PredictorBits = 2, ColorTransformBits = 2 }, + "predittore-grande" => Vp8LEncoderSettings.Default with { Palette = false, PredictorBits = 9, ColorTransformBits = 9 }, + _ => Vp8LEncoderSettings.Default, + }; + + private static IEnumerable Images(int width, int height, int seed) + { + yield return TestImages.Random(width, height, seed); + yield return TestImages.Random(width, height, seed, opaque: true); + yield return TestImages.Gradient(width, height, seed); + foreach (var colors in (int[])[1, 2, 3, 4, 5, 16, 17, 256]) + { + yield return WebPTestFiles.FewColors(width, height, colors, seed + colors); + } + + // Transparent pixels that keep their colour, and long runs. + var runs = new RgbaImage(width, height); + var pixels = runs.Pixels; + for (var i = 0; i < width * height; i++) + { + pixels[i * 4] = (byte)(i / 7); + pixels[(i * 4) + 1] = 200; + pixels[(i * 4) + 2] = (byte)(i % 3); + pixels[(i * 4) + 3] = (byte)((i / 5) % 2 == 0 ? 0 : 255); + } + + yield return runs; + } +} diff --git a/tests/Febe.Tests/Imaging/WebPReferenceTests.cs b/tests/Febe.Tests/Imaging/WebPReferenceTests.cs new file mode 100644 index 0000000..cddd617 --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPReferenceTests.cs @@ -0,0 +1,74 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The in-house WebP decoder against the SkiaSharp (libwebp) reads of the reference set: lossless files must match +/// byte for byte, alpha included; lossy files are compared with the thresholds of , and their +/// alpha (stored losslessly in ALPH) must match exactly. +/// +[TestClass] +public sealed class WebPReferenceTests +{ + public TestContext TestContext { get; set; } = null!; + + public static IEnumerable LosslessCases => ReferenceImages.Of(ReferenceFormat.WebP).Where(c => !IsLossy(c)).Select(c => new object[] { c.Name }); + + public static IEnumerable LossyCases => ReferenceImages.Of(ReferenceFormat.WebP).Where(IsLossy).Select(c => new object[] { c.Name }); + + [TestMethod] + [DynamicData(nameof(LosslessCases))] + public void TheLosslessDecoderReadsTheReferenceExactly(string name) + { + var reference = ReferenceImages.Get(name); + using var expected = PngDecoder.Decode(reference.ReadExpectedPng()); + using var actual = WebPDecoder.Decode(reference.ReadInput()); + ImageAssert.AreEqual(expected, actual, name); + } + + [TestMethod] + [DynamicData(nameof(LossyCases))] + public void TheLossyDecoderIsCloseToTheReference(string name) + { + var reference = ReferenceImages.Get(name); + using var expected = PngDecoder.Decode(reference.ReadExpectedPng()); + using var actual = WebPDecoder.Decode(reference.ReadInput(), out var info); + var result = ImageQuality.Compare(expected, actual); + TestContext.WriteLine($"{name}: {result}"); + ImageQuality.AssertClose(result, name); + + // Alpha is lossless even in a lossy file. + var e = expected.Pixels; + var a = actual.Pixels; + for (var i = 3; i < e.Length; i += 4) + { + Assert.AreEqual(e[i], a[i], $"{name}: alfa del pixel {i / 4}"); + } + + Assert.AreEqual(name.Contains("alfa", StringComparison.Ordinal), info.HasAlpha, name); + } + + [TestMethod] + public void TheFacadeReadsWebPAndIdentifyAgreesWithDecode() + { + foreach (var reference in ReferenceImages.Of(ReferenceFormat.WebP)) + { + var input = reference.ReadInput(); + Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.WebP)); + using var viaFacade = ImageDecoder.Decode(input); + using var direct = WebPDecoder.Decode(input, pooled: true); + Assert.IsTrue(direct.IsPooled); + ImageAssert.AreEqual(direct, viaFacade, reference.Name); + + var info = ImageDecoder.Identify(input); + Assert.AreEqual((ImageFormat.WebP, reference.Width, reference.Height, 1), (info.Format, info.Width, info.Height, info.FrameCount), reference.Name); + Assert.AreSame(ImageMetadata.Empty, info.Metadata, reference.Name); + if (!info.HasAlpha) + { + Assert.IsTrue(direct.IsOpaque(), reference.Name); + } + } + } + + private static bool IsLossy(ReferenceCase c) => !c.Name.Contains("senza-perdita", StringComparison.Ordinal); +} diff --git a/tests/Febe.Tests/Imaging/WebPTestFiles.cs b/tests/Febe.Tests/Imaging/WebPTestFiles.cs new file mode 100644 index 0000000..37ed02d --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPTestFiles.cs @@ -0,0 +1,185 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// WebP files put together by the tests from RIFF chunks (RFC 9649 §2), to reach what the reference set lacks. +internal static class WebPTestFiles +{ + /// The chunks of a WebP file: FourCC and payload, in order. + public static List<(string Type, byte[] Payload)> Chunks(byte[] file) + { + var chunks = new List<(string, byte[])>(); + var end = 8 + (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4)); + var pos = 12; + while (pos + 8 <= end) + { + var size = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos + 4)); + chunks.Add((System.Text.Encoding.ASCII.GetString(file, pos, 4), file.AsSpan(pos + 8, size).ToArray())); + pos += 8 + size + (size & 1); + } + + return chunks; + } + + /// The payload of the first chunk of that type. + public static byte[] Payload(byte[] file, string type) => Chunks(file).First(c => c.Type == type).Payload; + + /// A RIFF/WEBP file of the given chunks (padded to even sizes). + public static byte[] Riff(params (string Type, byte[] Payload)[] chunks) + { + using var body = new MemoryStream(); + body.Write("WEBP"u8); + foreach (var (type, payload) in chunks) + { + body.Write(Chunk(type, payload)); + } + + var file = new byte[8 + body.Length]; + "RIFF"u8.CopyTo(file); + BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(4), (uint)body.Length); + body.ToArray().CopyTo(file, 8); + return file; + } + + public static byte[] Chunk(string type, byte[] payload) + { + var chunk = new byte[8 + payload.Length + (payload.Length & 1)]; + System.Text.Encoding.ASCII.GetBytes(type).CopyTo(chunk, 0); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(4), (uint)payload.Length); + payload.CopyTo(chunk, 8); + return chunk; + } + + /// A VP8X payload: the flags byte and the canvas size. + public static byte[] Vp8X(int flags, int width, int height) + { + var payload = new byte[10]; + payload[0] = (byte)flags; + Uint24(payload.AsSpan(4), width - 1); + Uint24(payload.AsSpan(7), height - 1); + return payload; + } + + /// An ANIM payload: background colour (B, G, R, A) and loop count. + public static byte[] Anim(uint backgroundBgra = 0, int loops = 0) + { + var payload = new byte[6]; + BinaryPrimitives.WriteUInt32LittleEndian(payload, backgroundBgra); + BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(4), (ushort)loops); + return payload; + } + + /// An ANMF payload: offset (even), size, duration, flags (2 = do not blend, 1 = dispose) and frame chunks. + public static byte[] Anmf(int x, int y, int width, int height, int flags, params (string Type, byte[] Payload)[] chunks) + { + using var payload = new MemoryStream(); + var header = new byte[16]; + Uint24(header, x / 2); + Uint24(header.AsSpan(3), y / 2); + Uint24(header.AsSpan(6), width - 1); + Uint24(header.AsSpan(9), height - 1); + Uint24(header.AsSpan(12), 100); + header[15] = (byte)flags; + payload.Write(header); + foreach (var (type, data) in chunks) + { + payload.Write(Chunk(type, data)); + } + + return payload.ToArray(); + } + + /// + /// The forward alpha filter of RFC 9649 §2.7.1.2 (1 horizontal, 2 vertical, 3 gradient), written from the + /// predictor definitions, independent of the decoder's inverse. + /// + public static byte[] FilterAlpha(ReadOnlySpan alpha, int width, int height, int filter) + { + var output = new byte[alpha.Length]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + int predictor; + if (filter == 0 || (x == 0 && y == 0)) + { + predictor = 0; + } + else if (y == 0) + { + predictor = alpha[x - 1]; + } + else if (x == 0) + { + predictor = alpha[(y - 1) * width]; + } + else + { + int left = alpha[(y * width) + x - 1], top = alpha[((y - 1) * width) + x], topLeft = alpha[((y - 1) * width) + x - 1]; + predictor = filter switch + { + 1 => left, + 2 => top, + _ => Math.Clamp(left + top - topLeft, 0, 255), + }; + } + + output[(y * width) + x] = (byte)(alpha[(y * width) + x] - predictor); + } + } + + return output; + } + + /// The alpha bytes of an image. + public static byte[] AlphaOf(RgbaImage image) + { + var alpha = new byte[image.Width * image.Height]; + for (var i = 0; i < alpha.Length; i++) + { + alpha[i] = image.Pixels[(i * 4) + 3]; + } + + return alpha; + } + + /// A little-endian TIFF with an IFD0 holding only the Orientation tag. + public static byte[] Tiff(int orientation) + { + var tiff = new byte[8 + 2 + 12 + 4]; + "II*\0"u8.CopyTo(tiff); + tiff[4] = 8; + tiff[8] = 1; + tiff[10] = 0x12; + tiff[11] = 0x01; + tiff[12] = 3; + tiff[14] = 1; + tiff[18] = (byte)orientation; + return tiff; + } + + /// An image with only distinct colours (some transparent), from a fixed seed. + public static RgbaImage FewColors(int width, int height, int colors, int seed) + { + var random = new Random(seed); + var palette = new byte[colors * 4]; + random.NextBytes(palette); + var image = new RgbaImage(width, height); + var pixels = image.Pixels; + for (var i = 0; i < width * height; i++) + { + var c = (((i % width) / 3) + ((i / width) / 2) + random.Next(2)) % colors; + palette.AsSpan(c * 4, 4).CopyTo(pixels[(i * 4)..]); + } + + return image; + } + + private static void Uint24(Span destination, int value) + { + destination[0] = (byte)value; + destination[1] = (byte)(value >> 8); + destination[2] = (byte)(value >> 16); + } +}