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();
}
}