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>
184 lines
7.0 KiB
C#
184 lines
7.0 KiB
C#
using System.Buffers.Binary;
|
|
using System.Text;
|
|
|
|
namespace Febe.Core.Codecs.Images;
|
|
|
|
/// <summary>Options of <see cref="WebPEncoder"/>.</summary>
|
|
public sealed record WebPEncoderOptions
|
|
{
|
|
/// <summary>The options used when a caller passes none.</summary>
|
|
public static WebPEncoderOptions Default { get; } = new();
|
|
|
|
/// <summary>
|
|
/// EXIF to write in an EXIF chunk: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by the «Exif\0\0»
|
|
/// of a JPEG APP1 segment, which is removed.
|
|
/// </summary>
|
|
public byte[]? Exif { get; init; }
|
|
|
|
/// <summary>ICC profile to write in an ICCP chunk.</summary>
|
|
public byte[]? IccProfile { get; init; }
|
|
|
|
/// <summary>XMP packet to write in an XMP chunk (UTF-8).</summary>
|
|
public string? Xmp { get; init; }
|
|
|
|
/// <summary>The tools of the lossless encoder (tests turn them on and off one by one).</summary>
|
|
internal Vp8LEncoderSettings Lossless { get; init; } = Vp8LEncoderSettings.Default;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes lossless WebP files (RFC 9649): one VP8L chunk, inside the extended format (VP8X, then ICCP, VP8L, EXIF,
|
|
/// XMP) when there is metadata. Every pixel comes back exactly, the colour under a transparent pixel included.
|
|
/// </summary>
|
|
public static class WebPEncoder
|
|
{
|
|
/// <summary>Largest width or height a WebP picture can have.</summary>
|
|
public const int MaxDimension = 16384;
|
|
|
|
/// <summary>The WebP file of <paramref name="image"/>.</summary>
|
|
/// <exception cref="ArgumentOutOfRangeException">The image is wider or taller than <see cref="MaxDimension"/>.</exception>
|
|
/// <exception cref="ArgumentException">The EXIF block is not a TIFF structure.</exception>
|
|
public static byte[] Encode(RgbaImage image, WebPEncoderOptions? options = null)
|
|
{
|
|
using var output = new MemoryStream();
|
|
Encode(image, output, options);
|
|
return output.ToArray();
|
|
}
|
|
|
|
/// <summary>Writes the WebP file of <paramref name="image"/> to <paramref name="output"/>.</summary>
|
|
public static void Encode(RgbaImage image, Stream output, WebPEncoderOptions? options = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(image);
|
|
ArgumentNullException.ThrowIfNull(output);
|
|
options ??= WebPEncoderOptions.Default;
|
|
var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
|
|
var xmp = options.Xmp is { } givenXmp ? Encoding.UTF8.GetBytes(givenXmp) : null;
|
|
var bitstream = EncodeBitstream(image, options.Lossless);
|
|
var alpha = !image.IsOpaque();
|
|
var extended = exif is not null || options.IccProfile is not null || xmp is not null;
|
|
|
|
var size = 4L + ChunkSize(bitstream.Length);
|
|
if (extended)
|
|
{
|
|
size += ChunkSize(10) + ChunkSize(options.IccProfile?.Length) + ChunkSize(exif?.Length) + ChunkSize(xmp?.Length);
|
|
}
|
|
|
|
if (size > uint.MaxValue - 8)
|
|
{
|
|
throw new ArgumentException("The WebP file would be larger than RIFF allows.", nameof(image));
|
|
}
|
|
|
|
Span<byte> header = stackalloc byte[12];
|
|
"RIFF"u8.CopyTo(header);
|
|
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)size);
|
|
"WEBP"u8.CopyTo(header[8..]);
|
|
output.Write(header);
|
|
if (extended)
|
|
{
|
|
Span<byte> vp8x = stackalloc byte[10];
|
|
vp8x.Clear();
|
|
vp8x[0] = (byte)((options.IccProfile is not null ? 0x20 : 0) | (alpha ? 0x10 : 0) | (exif is not null ? 0x08 : 0) | (xmp is not null ? 0x04 : 0));
|
|
WriteUInt24(vp8x[4..], image.Width - 1);
|
|
WriteUInt24(vp8x[7..], image.Height - 1);
|
|
WriteChunk(output, "VP8X"u8, vp8x);
|
|
if (options.IccProfile is { } icc)
|
|
{
|
|
WriteChunk(output, "ICCP"u8, icc);
|
|
}
|
|
}
|
|
|
|
WriteChunk(output, "VP8L"u8, bitstream);
|
|
if (exif is not null)
|
|
{
|
|
WriteChunk(output, "EXIF"u8, exif);
|
|
}
|
|
|
|
if (xmp is not null)
|
|
{
|
|
WriteChunk(output, "XMP "u8, xmp);
|
|
}
|
|
}
|
|
|
|
/// <summary>The VP8L bitstream (signature, header, image stream) of <paramref name="image"/>.</summary>
|
|
internal static byte[] EncodeBitstream(RgbaImage image, Vp8LEncoderSettings settings)
|
|
{
|
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Width, MaxDimension, nameof(image));
|
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Height, MaxDimension, nameof(image));
|
|
var argb = ToArgb(image);
|
|
var writer = new Vp8LBitWriter(image.Length / 4);
|
|
writer.WriteBits(Vp8LDecoder.Signature, 8);
|
|
writer.WriteBits((uint)(image.Width - 1), 14);
|
|
writer.WriteBits((uint)(image.Height - 1), 14);
|
|
writer.WriteBits(image.IsOpaque() ? 0u : 1u, 1);
|
|
writer.WriteBits(0, 3);
|
|
Vp8LEncoder.WriteImageStream(writer, argb, image.Width, image.Height, settings);
|
|
return writer.ToArray();
|
|
}
|
|
|
|
/// <summary>
|
|
/// The headerless image stream of an ALPH chunk compressed with VP8L: the alpha values in the green channel.
|
|
/// </summary>
|
|
internal static byte[] EncodeAlphaStream(ReadOnlySpan<byte> alpha, int width, int height, Vp8LEncoderSettings settings)
|
|
{
|
|
var argb = new uint[width * height];
|
|
for (var i = 0; i < argb.Length; i++)
|
|
{
|
|
argb[i] = 0xFF000000 | ((uint)alpha[i] << 8);
|
|
}
|
|
|
|
var writer = new Vp8LBitWriter(argb.Length / 4);
|
|
Vp8LEncoder.WriteImageStream(writer, argb, width, height, settings);
|
|
return writer.ToArray();
|
|
}
|
|
|
|
internal static uint[] ToArgb(RgbaImage image)
|
|
{
|
|
var pixels = image.Pixels;
|
|
var argb = new uint[image.Width * image.Height];
|
|
for (var i = 0; i < argb.Length; i++)
|
|
{
|
|
var o = i * 4;
|
|
argb[i] = ((uint)pixels[o + 3] << 24) | ((uint)pixels[o] << 16) | ((uint)pixels[o + 1] << 8) | pixels[o + 2];
|
|
}
|
|
|
|
return argb;
|
|
}
|
|
|
|
private static long ChunkSize(int? length) => length is { } n ? 8L + n + (n & 1) : 0;
|
|
|
|
private static void WriteChunk(Stream output, ReadOnlySpan<byte> type, ReadOnlySpan<byte> payload)
|
|
{
|
|
Span<byte> header = stackalloc byte[8];
|
|
type.CopyTo(header);
|
|
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)payload.Length);
|
|
output.Write(header);
|
|
output.Write(payload);
|
|
if ((payload.Length & 1) == 1)
|
|
{
|
|
output.WriteByte(0);
|
|
}
|
|
}
|
|
|
|
private static void WriteUInt24(Span<byte> destination, int value)
|
|
{
|
|
destination[0] = (byte)value;
|
|
destination[1] = (byte)(value >> 8);
|
|
destination[2] = (byte)(value >> 16);
|
|
}
|
|
|
|
private static byte[] ExifPayload(byte[] exif)
|
|
{
|
|
ReadOnlySpan<byte> span = exif;
|
|
if (span.StartsWith("Exif\0\0"u8))
|
|
{
|
|
span = span[6..];
|
|
}
|
|
|
|
if (span.Length < 8 || !(span.StartsWith("II*\0"u8) || span.StartsWith("MM\0*"u8)))
|
|
{
|
|
throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif));
|
|
}
|
|
|
|
return span.ToArray();
|
|
}
|
|
}
|