feat(video): managed encoder provider for MJPEG-AVI, image sequences, GIF and APNG

Sessions write to a temporary file or folder that Complete renames into
place and Dispose deletes; constant-rate outputs repeat held frames.
Adds AVI/GIF/APNG readers used to verify rendered outputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:42:05 +00:00
1 parent 33d7284c25
commit b3801961aa
4 files changed
+934

No files matched your search

@@ -0,0 +1,410 @@
using System.Buffers.Binary;
using System.Text;
using Titano.Core.Codecs.Png;
using Titano.Core.Hashing;
using Titano.Core.Imaging;
using Titano.Core.Video;
namespace Titano.Core.Render.Diagnostics;
/// <summary>A composed animation frame (8-bit sRGB RGBA canvas) and how long it is shown.</summary>
internal sealed record AnimationFrame(byte[] Rgba, long Duration90k);
/// <summary>A decoded GIF or APNG used to verify rendered outputs.</summary>
internal sealed record AnimationInfo(int Width, int Height, IReadOnlyList<AnimationFrame> Frames, int? LoopCount)
{
public long Duration90k => Frames.Sum(f => f.Duration90k);
/// <summary>Frame <paramref name="index"/> as a linear-light RGB buffer (alpha dropped).</summary>
public ImageBuffer ToLinear(int index) => PixelConvert.FromInterleaved8(Frames[index].Rgba, Width, Height, 4, TransferFunction.Srgb, 3);
}
/// <summary>The structure of an MJPEG AVI: headers, the JPEG of every frame and the legacy index size.</summary>
internal sealed record AviInfo(int Width, int Height, Rational FrameRate, int HeaderFrames, int StreamFrames, IReadOnlyList<byte[]> Frames, int IndexEntries);
/// <summary>Bounds-checked big/little-endian reads; every violation is an <see cref="InvalidDataException"/>.</summary>
internal ref struct ByteCursor(ReadOnlySpan<byte> data)
{
private readonly ReadOnlySpan<byte> _data = data;
public int Position { get; set; }
public readonly int Remaining => _data.Length - Position;
public ReadOnlySpan<byte> Take(int count)
{
if (count < 0 || count > Remaining) throw new InvalidDataException($"Truncated data at offset {Position}");
var span = _data.Slice(Position, count);
Position += count;
return span;
}
public byte U8() => Take(1)[0];
public ushort U16Le() => BinaryPrimitives.ReadUInt16LittleEndian(Take(2));
public uint U32Le() => BinaryPrimitives.ReadUInt32LittleEndian(Take(4));
public uint U32Be() => BinaryPrimitives.ReadUInt32BigEndian(Take(4));
public string FourCc() => Encoding.ASCII.GetString(Take(4));
}
/// <summary>Reads AVI files written by <see cref="Video.Avi.AviMjpegWriter"/> (RIFF 'AVI ' plus 'AVIX' continuations).</summary>
internal static class AviReader
{
public static AviInfo Read(ReadOnlySpan<byte> data)
{
var cursor = new ByteCursor(data);
var frames = new List<byte[]>();
int width = 0, height = 0, headerFrames = 0, streamFrames = 0, index = 0;
var rate = default(Rational);
var first = true;
while (cursor.Remaining >= 12)
{
if (cursor.FourCc() != "RIFF") throw new InvalidDataException("RIFF expected");
var size = (int)cursor.U32Le();
var end = cursor.Position + size;
var type = cursor.FourCc();
if (type != (first ? "AVI " : "AVIX")) throw new InvalidDataException($"Unexpected RIFF type '{type}'");
Walk(ref cursor, end, frames, ref width, ref height, ref headerFrames, ref streamFrames, ref rate, ref index);
cursor.Position = end + (size & 1);
first = false;
}
if (first) throw new InvalidDataException("No RIFF list");
if (width == 0 || rate.Numerator == 0) throw new InvalidDataException("Missing avih/strh headers");
return new AviInfo(width, height, rate, headerFrames, streamFrames, frames, index);
}
private static void Walk(ref ByteCursor cursor, int end, List<byte[]> frames, ref int width, ref int height, ref int headerFrames,
ref int streamFrames, ref Rational rate, ref int index)
{
while (cursor.Position + 8 <= end)
{
var id = cursor.FourCc();
var size = (int)cursor.U32Le();
if (size < 0 || cursor.Position + size > end) throw new InvalidDataException($"Chunk '{id}' overruns its list");
if (id == "LIST")
{
var listEnd = cursor.Position + size;
cursor.FourCc();
Walk(ref cursor, listEnd, frames, ref width, ref height, ref headerFrames, ref streamFrames, ref rate, ref index);
cursor.Position = listEnd + (size & 1);
continue;
}
var body = cursor.Take(size);
switch (id)
{
case "avih":
headerFrames = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[16..]);
width = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[32..]);
height = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[36..]);
break;
case "strh":
var scale = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[20..]);
var rateValue = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[24..]);
if (scale <= 0 || rateValue <= 0) throw new InvalidDataException("Invalid stream rate");
rate = new Rational(rateValue, scale);
streamFrames = (int)BinaryPrimitives.ReadUInt32LittleEndian(body[32..]);
break;
case "00dc":
if (size < 4 || body[0] != 0xFF || body[1] != 0xD8) throw new InvalidDataException("Video chunk is not a JPEG");
frames.Add(body.ToArray());
break;
case "idx1":
index = size / 16;
break;
}
cursor.Position += size & 1;
}
}
}
/// <summary>GIF89a decoder with frame composition (disposal 0–3, transparency) for output verification.</summary>
internal static class GifReader
{
public static AnimationInfo Decode(ReadOnlySpan<byte> data)
{
var cursor = new ByteCursor(data);
var signature = Encoding.ASCII.GetString(cursor.Take(6));
if (signature is not ("GIF89a" or "GIF87a")) throw new InvalidDataException("Not a GIF");
int width = cursor.U16Le(), height = cursor.U16Le();
var packed = cursor.U8();
cursor.Take(2);
if (width == 0 || height == 0) throw new InvalidDataException("Empty logical screen");
var global = (packed & 0x80) != 0 ? cursor.Take(3 << ((packed & 7) + 1)).ToArray() : null;
var canvas = new byte[width * height * 4];
var frames = new List<AnimationFrame>();
int? loop = null;
int delay = 0, disposal = 0, transparent = -1;
while (true)
{
var block = cursor.U8();
if (block == 0x3B) break;
if (block == 0x21)
{
var label = cursor.U8();
if (label == 0xF9)
{
if (cursor.U8() != 4) throw new InvalidDataException("Bad graphic control extension");
var flags = cursor.U8();
delay = cursor.U16Le();
var index = cursor.U8();
disposal = (flags >> 2) & 7;
transparent = (flags & 1) != 0 ? index : -1;
if (cursor.U8() != 0) throw new InvalidDataException("Unterminated graphic control extension");
continue;
}
var payload = SubBlocks(ref cursor);
if (label == 0xFF && payload.Length >= 14 && Encoding.ASCII.GetString(payload, 0, 11) == "NETSCAPE2.0") loop = payload[12] | payload[13] << 8;
continue;
}
if (block != 0x2C) throw new InvalidDataException($"Unexpected block 0x{block:X2}");
int left = cursor.U16Le(), top = cursor.U16Le(), w = cursor.U16Le(), h = cursor.U16Le();
var imagePacked = cursor.U8();
if (left + w > width || top + h > height || w == 0 || h == 0) throw new InvalidDataException("Frame outside the logical screen");
if ((imagePacked & 0x40) != 0) throw new InvalidDataException("Interlaced frames are not verified");
var table = (imagePacked & 0x80) != 0 ? cursor.Take(3 << ((imagePacked & 7) + 1)).ToArray() : global
?? throw new InvalidDataException("No colour table");
var minCode = cursor.U8();
if (minCode is < 2 or > 8) throw new InvalidDataException("Bad LZW code size");
var indices = Lzw(SubBlocks(ref cursor), minCode, w * h);
var saved = disposal == 3 ? (byte[])canvas.Clone() : null;
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
var i = indices[y * w + x];
if (i == transparent) continue;
if (i * 3 + 2 >= table.Length) throw new InvalidDataException("Index outside the colour table");
var o = ((top + y) * width + left + x) * 4;
canvas[o] = table[i * 3];
canvas[o + 1] = table[i * 3 + 1];
canvas[o + 2] = table[i * 3 + 2];
canvas[o + 3] = 255;
}
}
frames.Add(new AnimationFrame((byte[])canvas.Clone(), delay * 900L));
if (disposal == 2)
{
for (var y = 0; y < h; y++) canvas.AsSpan(((top + y) * width + left) * 4, w * 4).Clear();
}
else if (saved is not null)
{
canvas = saved;
}
delay = 0;
disposal = 0;
transparent = -1;
}
return new AnimationInfo(width, height, frames, loop);
}
private static byte[] SubBlocks(ref ByteCursor cursor)
{
using var buffer = new MemoryStream();
while (true)
{
var length = cursor.U8();
if (length == 0) return buffer.ToArray();
buffer.Write(cursor.Take(length));
}
}
/// <summary>Variable-length LZW (GIF flavour: clear/end codes, codes up to 12 bits, deferred clear allowed).</summary>
private static byte[] Lzw(byte[] data, int minCode, int count)
{
var output = new byte[count];
var prefix = new short[4096];
var suffix = new byte[4096];
var stack = new byte[4097];
int clear = 1 << minCode, end = clear + 1;
int size = minCode + 1, next = end + 1, previous = -1, written = 0;
byte first = 0;
long bits = 0;
var bitCount = 0;
var pos = 0;
while (written < count)
{
while (bitCount < size && pos < data.Length)
{
bits |= (long)data[pos++] << bitCount;
bitCount += 8;
}
if (bitCount < size) throw new InvalidDataException("Image data ends early");
var code = (int)(bits & ((1 << size) - 1));
bits >>= size;
bitCount -= size;
if (code == clear)
{
size = minCode + 1;
next = end + 1;
previous = -1;
continue;
}
if (code == end) break;
int top = 0, current = code;
if (previous < 0)
{
if (code >= clear) throw new InvalidDataException("First code is not a literal");
first = (byte)code;
output[written++] = first;
previous = code;
continue;
}
if (code > next || (code == next && next >= 4096)) throw new InvalidDataException("Invalid LZW code");
if (code == next)
{
stack[top++] = first;
current = previous;
}
while (current >= clear)
{
stack[top++] = suffix[current];
current = prefix[current];
}
first = (byte)current;
stack[top++] = first;
while (top > 0 && written < count) output[written++] = stack[--top];
if (next < 4096)
{
prefix[next] = (short)previous;
suffix[next] = first;
next++;
if (next == 1 << size && size < 12) size++;
}
previous = code;
}
if (written < count) throw new InvalidDataException("Image data ends early");
return output;
}
}
/// <summary>APNG decoder for output verification: chunk CRCs, the shared sequence counter, fcTL/fdAT layout, and
/// composition with every dispose and blend operation (each frame is decoded through <see cref="PngDecoder"/>).</summary>
internal static class ApngReader
{
private static readonly byte[] Signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
private sealed record Control(int Width, int Height, int X, int Y, long Duration90k, byte Dispose, byte Blend)
{
public List<byte[]> Data { get; } = [];
}
public static AnimationInfo Decode(ReadOnlySpan<byte> data)
{
var cursor = new ByteCursor(data);
if (!cursor.Take(8).SequenceEqual(Signature)) throw new InvalidDataException("Not a PNG");
byte[]? ihdr = null;
int? declaredFrames = null, plays = null;
var controls = new List<Control>();
var sequence = 0u;
while (true)
{
var length = (int)cursor.U32Be();
if (length < 0) throw new InvalidDataException("Chunk too long");
var typeAndBody = cursor.Take(4 + length);
if (Crc32.Compute(typeAndBody) != cursor.U32Be()) throw new InvalidDataException("Chunk CRC mismatch");
var type = Encoding.ASCII.GetString(typeAndBody[..4]);
var body = typeAndBody[4..];
switch (type)
{
case "IHDR":
ihdr = body.ToArray();
break;
case "acTL":
declaredFrames = (int)BinaryPrimitives.ReadUInt32BigEndian(body);
plays = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
break;
case "fcTL":
Expect(ref sequence, body);
var num = BinaryPrimitives.ReadUInt16BigEndian(body[20..]);
var den = BinaryPrimitives.ReadUInt16BigEndian(body[22..]);
controls.Add(new Control(
(int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]), (int)BinaryPrimitives.ReadUInt32BigEndian(body[8..]),
(int)BinaryPrimitives.ReadUInt32BigEndian(body[12..]), (int)BinaryPrimitives.ReadUInt32BigEndian(body[16..]),
num * 90000L / (den == 0 ? 100 : den), body[24], body[25]));
break;
case "IDAT":
if (controls.Count != 1) throw new InvalidDataException("The default image must be the first frame");
controls[0].Data.Add(body.ToArray());
break;
case "fdAT":
Expect(ref sequence, body);
if (controls.Count == 0) throw new InvalidDataException("fdAT before fcTL");
controls[^1].Data.Add(body[4..].ToArray());
break;
}
if (type == "IEND") break;
}
if (ihdr is null || declaredFrames is null) throw new InvalidDataException("Missing IHDR or acTL");
if (declaredFrames != controls.Count) throw new InvalidDataException($"acTL declares {declaredFrames} frames, {controls.Count} found");
var width = (int)BinaryPrimitives.ReadUInt32BigEndian(ihdr);
var height = (int)BinaryPrimitives.ReadUInt32BigEndian(ihdr.AsSpan(4));
var canvas = new byte[width * height * 4];
var frames = new List<AnimationFrame>(controls.Count);
foreach (var c in controls)
{
if (c.X + c.Width > width || c.Y + c.Height > height || c.Data.Count == 0) throw new InvalidDataException("Frame outside the canvas or without data");
var saved = c.Dispose == 2 ? (byte[])canvas.Clone() : null;
Compose(canvas, width, Region(ihdr, c), c);
frames.Add(new AnimationFrame((byte[])canvas.Clone(), c.Duration90k));
if (c.Dispose == 1)
{
for (var y = 0; y < c.Height; y++) canvas.AsSpan(((c.Y + y) * width + c.X) * 4, c.Width * 4).Clear();
}
else if (saved is not null)
{
canvas = saved;
}
}
return new AnimationInfo(width, height, frames, plays);
}
private static void Expect(ref uint sequence, ReadOnlySpan<byte> body)
{
if (BinaryPrimitives.ReadUInt32BigEndian(body) != sequence) throw new InvalidDataException($"Sequence number {sequence} expected");
sequence++;
}
/// <summary>Decodes one frame's data as a stand-alone PNG with the frame's size.</summary>
private static PngImage Region(byte[] ihdr, Control c)
{
using var png = new MemoryStream();
png.Write(Signature);
var header = (byte[])ihdr.Clone();
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)c.Width);
BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(4), (uint)c.Height);
PngEncoder.WriteChunk(png, "IHDR", header);
foreach (var part in c.Data) PngEncoder.WriteChunk(png, "IDAT", part);
PngEncoder.WriteChunk(png, "IEND", []);
var image = PngDecoder.Decode(png.ToArray());
if (image.Warnings.Count > 0) throw new InvalidDataException("Frame data: " + image.Warnings[0]);
if (image.Pixels8 is null || image.Channels is not (3 or 4)) throw new InvalidDataException("Only 8-bit RGB/RGBA frames are verified");
return image;
}
private static void Compose(byte[] canvas, int width, PngImage frame, Control c)
{
var pixels = frame.Pixels8!;
var channels = frame.Channels;
for (var y = 0; y < c.Height; y++)
{
for (var x = 0; x < c.Width; x++)
{
var s = (y * c.Width + x) * channels;
var o = ((c.Y + y) * width + c.X + x) * 4;
var alpha = channels == 4 ? pixels[s + 3] : 255;
if (c.Blend == 1)
{
if (alpha == 0) continue;
if (alpha < 255) throw new InvalidDataException("Partial alpha blending is not verified");
}
canvas[o] = pixels[s];
canvas[o + 1] = pixels[s + 1];
canvas[o + 2] = pixels[s + 2];
canvas[o + 3] = (byte)alpha;
}
}
}
}