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

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

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

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

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

No files matched your search

+596
View File
@@ -0,0 +1,596 @@
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The boolean entropy encoder of RFC 6386 §7.3 (write_bool, add_one_to_output, flush_bool_encoder), for the tests.
/// </summary>
internal sealed class Vp8BoolEncoder
{
private readonly List<byte> _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);
}
}
/// <summary>A flag, then (when the value is not 0) magnitude and sign, as the frame header writes deltas.</summary>
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<sbyte> tree, ReadOnlySpan<byte> probs, int offset, int leaf)
{
Span<int> 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<sbyte> tree, int node, int leaf, Span<int> 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]++;
}
}
/// <summary>What a test macroblock holds.</summary>
internal sealed class Vp8TestMacroblock
{
public int Segment { get; set; }
public bool Skip { get; set; }
/// <summary>DC_PRED, V_PRED, H_PRED, TM_PRED or B_PRED (Vp8Tables).</summary>
public int YMode { get; set; }
/// <summary>The sixteen subblock modes for B_PRED.</summary>
public int[] BModes { get; } = new int[16];
public int UvMode { get; set; }
/// <summary>Quantized levels of the 25 blocks (16 Y, 4 U, 4 V, Y2), in zigzag order.</summary>
public int[][] Levels { get; } = [.. Enumerable.Range(0, 25).Select(_ => new int[16])];
}
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>The VP8 frame (the payload of a «VP8 » chunk).</summary>
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();
}
/// <summary>A frame of empty macroblocks with the given modes (skip set, so no tokens).</summary>
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;
}
/// <summary>Random modes, segments and levels from a fixed seed; about a third of the blocks empty.</summary>
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<int> 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<int> 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<byte> 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;
}