refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,221 @@
using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
using Chronos.Core.Codecs.Apng;
using Chronos.Core.Hashing;
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class ApngEncoderTests
{
private const int W = 40, H = 30;
[Test]
public void ChunkOrderSequenceNumbersAndCrcsAreValid()
{
var frames = Enumerable.Range(0, 5).Select(i => Pattern(i, 3)).ToList();
var bytes = Encode(frames, new ApngEncoderOptions(), 3000);
var chunks = Chunks(bytes);
Assert.SequenceEqual(
["IHDR", "acTL", "fcTL", "IDAT", "fcTL", "fdAT", "fcTL", "fdAT", "fcTL", "fdAT", "fcTL", "fdAT", "IEND"],
chunks.Select(c => c.Type));
var actl = chunks[1].Data;
Assert.Equal(5, BinaryPrimitives.ReadInt32BigEndian(actl));
Assert.Equal(0, BinaryPrimitives.ReadInt32BigEndian(actl.AsSpan(4)));
var sequence = chunks.Where(c => c.Type is "fcTL" or "fdAT").Select(c => BinaryPrimitives.ReadUInt32BigEndian(c.Data)).ToList();
Assert.SequenceEqual(Enumerable.Range(0, sequence.Count).Select(i => (uint)i), sequence);
var first = chunks[2].Data;
Assert.Equal((W, H, 0, 0), (BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(4)), BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(8)),
BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(12)), BinaryPrimitives.ReadInt32BigEndian(first.AsSpan(16))));
Assert.Equal((1, 30), Delay(first));
}
[Test]
public void FirstFrameIsTheDefaultImageAndAllFramesComposeExactly()
{
var frames = new List<byte[]> { Pattern(0, 3), Pattern(0, 3), Pattern(1, 3) };
// Frame 3 changes only a small block of frame 2.
var last = (byte[])frames[2].Clone();
for (var y = 5; y < 9; y++)
{
for (var x = 20; x < 26; x++) last[(y * W + x) * 3] ^= 0xFF;
}
frames.Add(last);
var bytes = Encode(frames, new ApngEncoderOptions(), 1500);
var decoded = Decode(bytes, 3);
Assert.Equal(3, decoded.Count); // the duplicate merged into the first frame
Assert.BytesEqual(frames[0], decoded[0].Canvas);
Assert.BytesEqual(frames[2], decoded[1].Canvas);
Assert.BytesEqual(frames[3], decoded[2].Canvas);
Assert.Equal((1, 30), decoded[0].Delay);
Assert.Equal((20, 5, 6, 4), decoded[2].Rect);
Assert.Equal(0, decoded[2].Blend); // RGB output always uses SOURCE
}
[Test]
public void RgbaDifferencingUsesOverWithTransparentUnchangedPixels()
{
var a = Pattern(2, 4);
var b = (byte[])a.Clone();
b[(10 * W + 10) * 4] ^= 0x80;
b[(12 * W + 14) * 4 + 1] ^= 0x80;
var bytes = Encode([a, b], new ApngEncoderOptions { Alpha = true }, 3000);
var decoded = Decode(bytes, 4);
Assert.Equal(2, decoded.Count);
Assert.Equal(1, decoded[1].Blend);
Assert.Equal((10, 10, 5, 3), decoded[1].Rect);
Assert.BytesEqual(b, decoded[1].Canvas);
}
[Theory]
[Case(3003L, 1001, 30000)]
[Case(90000L * 30, 30, 1)]
[Case(3001L, 33, 1000)]
public void DelaysAreExactFractionsOrCumulativelyRounded(long duration, int num, int den)
{
var bytes = Encode([Pattern(0, 3), Pattern(1, 3)], new ApngEncoderOptions(), duration);
var fctl = Chunks(bytes).Where(c => c.Type == "fcTL").ToList();
Assert.Equal((num, den), Delay(fctl[0].Data));
}
[Test]
public void LinearBuffersAreEncodedAsSrgb()
{
using var image = new ImageBuffer(W, H, 4);
image.Plane(0).Fill(ColorSpace.Linear8(200));
image.Plane(1).Fill(ColorSpace.Linear8(100));
image.Plane(3).Fill(0.5f);
using var ms = new MemoryStream();
var encoder = new ApngEncoder(ms, W, H, new ApngEncoderOptions { Alpha = true, LoopCount = 2 });
encoder.AddFrame(image, 9000);
encoder.Complete();
var decoded = Decode(ms.ToArray(), 4);
Assert.SequenceEqual(new byte[] { 200, 100, 0, 128 }, decoded[0].Canvas.Take(4));
Assert.Equal(2, BinaryPrimitives.ReadInt32BigEndian(Chunks(ms.ToArray())[1].Data.AsSpan(4)));
}
private static byte[] Encode(List<byte[]> frames, ApngEncoderOptions options, long duration)
{
using var ms = new MemoryStream();
var encoder = new ApngEncoder(ms, W, H, options);
foreach (var f in frames) encoder.AddFrame(f, duration);
encoder.Complete();
return ms.ToArray();
}
private static (int, int) Delay(byte[] fctl) =>
(BinaryPrimitives.ReadUInt16BigEndian(fctl.AsSpan(20)), BinaryPrimitives.ReadUInt16BigEndian(fctl.AsSpan(22)));
private sealed record Chunk(string Type, byte[] Data);
/// <summary>Splits the PNG into chunks, checking the signature, lengths and every CRC.</summary>
private static List<Chunk> Chunks(byte[] png)
{
Assert.BytesEqual([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], png.AsSpan(0, 8));
var list = new List<Chunk>();
var pos = 8;
while (pos < png.Length)
{
var length = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(pos));
var type = Encoding.ASCII.GetString(png, pos + 4, 4);
Assert.Equal(BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos + 8 + length)), Crc32.Compute(png.AsSpan(pos + 4, length + 4)), $"CRC of {type}");
list.Add(new Chunk(type, png.AsSpan(pos + 8, length).ToArray()));
pos += 12 + length;
}
Assert.Equal(png.Length, pos);
return list;
}
private sealed record Frame(byte[] Canvas, (int, int) Delay, (int X, int Y, int W, int H) Rect, int Blend);
/// <summary>Inflates, unfilters and composites every frame (dispose NONE, blend SOURCE/OVER with binary alpha).</summary>
private static List<Frame> Decode(byte[] png, int bpp)
{
var chunks = Chunks(png);
var canvas = new byte[W * H * bpp];
var frames = new List<Frame>();
for (var i = 0; i < chunks.Count; i++)
{
if (chunks[i].Type != "fcTL") continue;
var f = chunks[i].Data;
int w = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(4)), h = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(8));
int x = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(12)), y = BinaryPrimitives.ReadInt32BigEndian(f.AsSpan(16));
Assert.Equal((byte)0, f[24]);
var data = chunks[i + 1].Type == "IDAT" ? chunks[i + 1].Data : chunks[i + 1].Data[4..];
var pixels = Unfilter(Inflate(data), w, h, bpp);
for (var row = 0; row < h; row++)
{
for (var col = 0; col < w; col++)
{
var s = (row * w + col) * bpp;
var d = ((y + row) * W + x + col) * bpp;
if (f[25] == 1 && bpp == 4 && pixels[s + 3] == 0) continue;
pixels.AsSpan(s, bpp).CopyTo(canvas.AsSpan(d));
}
}
frames.Add(new Frame((byte[])canvas.Clone(), Delay(f), (x, y, w, h), f[25]));
}
return frames;
}
private static byte[] Inflate(byte[] zlib)
{
using var z = new ZLibStream(new MemoryStream(zlib), CompressionMode.Decompress);
using var ms = new MemoryStream();
z.CopyTo(ms);
return ms.ToArray();
}
private static byte[] Unfilter(byte[] filtered, int w, int h, int bpp)
{
var stride = w * bpp;
Assert.Equal((stride + 1) * h, filtered.Length);
var output = new byte[stride * h];
for (var y = 0; y < h; y++)
{
var filter = filtered[y * (stride + 1)];
for (var i = 0; i < stride; i++)
{
int raw = filtered[y * (stride + 1) + 1 + i];
int a = i >= bpp ? output[y * stride + i - bpp] : 0;
int b = y > 0 ? output[(y - 1) * stride + i] : 0;
int c = i >= bpp && y > 0 ? output[(y - 1) * stride + i - bpp] : 0;
output[y * stride + i] = (byte)(filter switch
{
0 => raw,
1 => raw + a,
2 => raw + b,
3 => raw + ((a + b) >> 1),
_ => raw + Paeth(a, b, c),
});
}
}
return output;
}
private static int Paeth(int a, int b, int c)
{
var p = a + b - c;
int pa = Math.Abs(p - a), pb = Math.Abs(p - b), pc = Math.Abs(p - c);
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
}
private static byte[] Pattern(int variant, int bpp)
{
var pixels = new byte[W * H * bpp];
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
var o = (y * W + x) * bpp;
pixels[o] = (byte)(x * 6 + variant * 40);
pixels[o + 1] = (byte)(y * 8);
pixels[o + 2] = (byte)((x ^ y) * 4 + variant);
if (bpp == 4) pixels[o + 3] = 255;
}
}
return pixels;
}
}
@@ -0,0 +1,205 @@
using System.Buffers.Binary;
using System.Text;
using Chronos.Core.Video;
using Chronos.Core.Video.Avi;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class AviMjpegWriterTests
{
[Test]
public void SingleRiffHasHeadersIdx1AndStandardIndex()
{
var frames = Frames(10, 1);
var bytes = Write(frames, Rational.Fps2997, AviMjpegWriter.DefaultRiffSizeLimit);
var file = Riff.Parse(bytes);
Assert.Equal(bytes.Length, file.Sum(r => r.Size + 8));
Assert.Count(1, file);
var riff = file[0];
Assert.Equal("RIFF", riff.Id);
Assert.Equal("AVI ", riff.Type);
var hdrl = riff.List("hdrl");
var avih = hdrl.Chunk("avih").Data;
Assert.Equal(33367u, U32(avih, 0));
Assert.Equal(10u, U32(avih, 16));
Assert.Equal(1u, U32(avih, 24));
Assert.Equal(64u, U32(avih, 32));
Assert.Equal(48u, U32(avih, 36));
var strl = hdrl.List("strl");
var strh = strl.Chunk("strh").Data;
Assert.Equal("vids", Encoding.ASCII.GetString(strh, 0, 4));
Assert.Equal("MJPG", Encoding.ASCII.GetString(strh, 4, 4));
Assert.Equal(1001u, U32(strh, 20));
Assert.Equal(30000u, U32(strh, 24));
Assert.Equal(10u, U32(strh, 32));
Assert.Equal("MJPG", Encoding.ASCII.GetString(strl.Chunk("strf").Data, 16, 4));
Assert.Equal(10u, U32(hdrl.List("odml").Chunk("dmlh").Data, 0));
var movi = riff.List("movi");
var chunks = movi.Children.Where(c => c.Id == "00dc").ToList();
Assert.Equal(10, chunks.Count);
for (var i = 0; i < 10; i++)
{
Assert.BytesEqual(frames[i], chunks[i].Data);
Assert.Equal(0L, chunks[i].Offset % 2, "chunks stay word aligned after odd frames");
}
var idx1 = riff.Chunk("idx1").Data;
Assert.Equal(160, idx1.Length);
for (var i = 0; i < 10; i++)
{
Assert.Equal("00dc", Encoding.ASCII.GetString(idx1, i * 16, 4));
Assert.Equal(0x10u, U32(idx1, i * 16 + 4));
Assert.Equal(chunks[i].Offset, movi.TypeOffset + U32(idx1, i * 16 + 8));
Assert.Equal((uint)frames[i].Length, U32(idx1, i * 16 + 12));
}
AssertOpenDmlIndex(bytes, file, frames);
}
[Test]
public void LargeOutputsContinueInAvixLists()
{
var frames = Frames(40, 2);
const long limit = 16 * 1024;
var bytes = Write(frames, new Rational(25, 1), limit);
var file = Riff.Parse(bytes);
Assert.Equal(bytes.Length, file.Sum(r => r.Size + 8));
Assert.Greater(file.Count, 3);
Assert.Equal("AVI ", file[0].Type);
Assert.True(file.Skip(1).All(r => r.Type == "AVIX" && r.Children.All(c => c.Id != "idx1")));
Assert.True(file.All(r => r.Size + 8 <= limit), "every RIFF respects the limit");
var first = file[0].List("movi").Children.Count(c => c.Id == "00dc");
Assert.Equal((uint)first, U32(file[0].List("hdrl").Chunk("avih").Data, 16));
Assert.Equal(first * 16, file[0].Chunk("idx1").Data.Length);
Assert.Equal(40u, U32(file[0].List("hdrl").List("strl").Chunk("strh").Data, 32));
Assert.Equal(40u, U32(file[0].List("hdrl").List("odml").Chunk("dmlh").Data, 0));
AssertOpenDmlIndex(bytes, file, frames);
}
[Theory]
[Case(24, 1, 41667u)]
[Case(25, 1, 40000u)]
[Case(60000, 1001, 16683u)]
[Case(48, 2, 41667u)]
public void FrameRateFieldsAreExact(int numerator, int denominator, uint microseconds)
{
var bytes = Write(Frames(2, 3), new Rational(numerator, denominator), AviMjpegWriter.DefaultRiffSizeLimit);
var hdrl = Riff.Parse(bytes)[0].List("hdrl");
Assert.Equal(microseconds, U32(hdrl.Chunk("avih").Data, 0));
var strh = hdrl.List("strl").Chunk("strh").Data;
var g = (uint)System.Numerics.BigInteger.GreatestCommonDivisor(numerator, denominator);
Assert.Equal((uint)denominator / g, U32(strh, 20));
Assert.Equal((uint)numerator / g, U32(strh, 24));
}
[Test]
public void RejectsNonJpegFrames()
{
using var ms = new MemoryStream();
var writer = new AviMjpegWriter(ms, 64, 48, new Rational(30, 1));
Assert.Throws<ArgumentException>(() => writer.WriteFrame([0x89, 0x50, 0x4E, 0x47]));
}
private static void AssertOpenDmlIndex(byte[] bytes, List<Riff.Node> file, List<byte[]> frames)
{
var indx = file[0].List("hdrl").List("strl").Chunk("indx").Data;
Assert.Equal(4, BinaryPrimitives.ReadUInt16LittleEndian(indx));
Assert.Equal((byte)0, indx[3]); // AVI_INDEX_OF_INDEXES
var entries = U32(indx, 4);
Assert.Equal((uint)file.Count, entries);
var frame = 0;
for (var e = 0; e < entries; e++)
{
var offset = BinaryPrimitives.ReadInt64LittleEndian(indx.AsSpan(24 + e * 16));
var size = U32(indx, 32 + e * 16);
var duration = U32(indx, 36 + e * 16);
Assert.Equal("ix00", Encoding.ASCII.GetString(bytes, (int)offset, 4));
Assert.Equal(size, U32(bytes, (int)offset + 4) + 8);
var ix = bytes.AsSpan((int)offset + 8);
Assert.Equal((byte)1, ix[3]); // AVI_INDEX_OF_CHUNKS
Assert.Equal(duration, U32(bytes, (int)offset + 12));
var baseOffset = BinaryPrimitives.ReadInt64LittleEndian(ix[12..]);
for (var i = 0; i < duration; i++, frame++)
{
var dataOffset = baseOffset + U32(bytes, (int)offset + 32 + i * 8);
var length = U32(bytes, (int)offset + 36 + i * 8);
Assert.Equal(0u, length & 0x8000_0000u, "every MJPEG frame is a key frame");
Assert.BytesEqual(frames[frame], bytes.AsSpan((int)dataOffset, (int)length));
}
}
Assert.Equal(frames.Count, frame);
}
private static byte[] Write(List<byte[]> frames, Rational rate, long limit)
{
using var ms = new MemoryStream();
var writer = new AviMjpegWriter(ms, 64, 48, rate, limit);
foreach (var f in frames) writer.WriteFrame(f);
writer.Complete();
Assert.Equal(frames.Count, writer.FrameCount);
return ms.ToArray();
}
/// <summary>JPEG-shaped payloads (SOI … EOI) of odd and even lengths.</summary>
private static List<byte[]> Frames(int count, int seed)
{
var rng = new Random(seed);
var list = new List<byte[]>();
for (var i = 0; i < count; i++)
{
var f = new byte[1500 + rng.Next(2000)];
rng.NextBytes(f);
f[0] = 0xFF;
f[1] = 0xD8;
f[^2] = 0xFF;
f[^1] = 0xD9;
list.Add(f);
}
return list;
}
private static uint U32(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset));
/// <summary>Minimal RIFF tree reader for verification.</summary>
private static class Riff
{
public sealed record Node(string Id, string? Type, long Offset, uint Size, byte[] Data, List<Node> Children)
{
/// <summary>File offset of the list type four-cc (the base of idx1 offsets).</summary>
public long TypeOffset => Offset + 8;
public Node List(string type) => Children.Single(c => c.Type == type);
public Node Chunk(string id) => Children.Single(c => c.Id == id);
}
public static List<Node> Parse(byte[] bytes) => ParseRange(bytes, 0, bytes.Length);
private static List<Node> ParseRange(byte[] bytes, long start, long end)
{
var nodes = new List<Node>();
var pos = start;
while (pos + 8 <= end)
{
var id = Encoding.ASCII.GetString(bytes, (int)pos, 4);
var size = U32(bytes, (int)pos + 4);
Assert.True(pos + 8 + size <= end, $"chunk {id} at {pos} overruns its parent");
if (id is "RIFF" or "LIST")
{
var type = Encoding.ASCII.GetString(bytes, (int)pos + 8, 4);
nodes.Add(new Node(id, type, pos, size, [], ParseRange(bytes, pos + 12, pos + 8 + size)));
}
else
{
nodes.Add(new Node(id, null, pos, size, bytes.AsSpan((int)pos + 8, (int)size).ToArray(), []));
}
pos += 8 + size + (size & 1);
}
Assert.Equal(end, pos);
return nodes;
}
}
}
@@ -0,0 +1,229 @@
using Chronos.Core.Video.Bitstream;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class BitstreamTests
{
[Test]
public void ExpGolombRoundTrip()
{
uint[] unsigned = [0, 1, 2, 3, 7, 8, 254, 255, 256, 65535, 1_000_000, uint.MaxValue - 1];
int[] signed = [0, 1, -1, 2, -2, 100, -100, int.MaxValue, -int.MaxValue];
var w = new BitWriter();
foreach (var v in unsigned) w.WriteUe(v);
foreach (var v in signed) w.WriteSe(v);
w.WriteBits(0b101, 3);
var r = new BitReader(w.ToArray());
foreach (var v in unsigned) Assert.Equal(v, r.ReadUe());
foreach (var v in signed) Assert.Equal(v, r.ReadSe());
Assert.Equal(0b101u, r.ReadBits(3));
Assert.False(r.IsOverrun);
}
[Test]
public void ReadingPastTheEndSetsOverrunWithoutThrowing()
{
var r = new BitReader([0xFF]);
Assert.Equal(0xFFu, r.ReadBits(8));
Assert.Equal(0u, r.ReadBits(16));
Assert.True(r.IsOverrun);
var zeros = new BitReader(new byte[8]);
Assert.Equal(0u, zeros.ReadUe());
Assert.True(zeros.IsOverrun);
}
[Test]
public void Leb128RoundTrip()
{
Span<byte> buffer = stackalloc byte[8];
foreach (var v in new ulong[] { 0, 1, 127, 128, 16383, 16384, uint.MaxValue })
{
var n = Av1ObuParser.WriteLeb128(buffer, v);
Assert.Equal(Av1ObuParser.Leb128Size(v), n);
Assert.True(Av1ObuParser.TryReadLeb128(buffer[..n], out var back, out var length));
Assert.Equal(v, back);
Assert.Equal(n, length);
}
}
[Test]
public void SplitsThreeAndFourByteStartCodes()
{
byte[] stream = [0xAA, 0, 0, 0, 1, 0x67, 1, 2, 0, 0, 1, 0x68, 3, 0, 0, 0, 0, 1, 0x65, 4, 5, 6, 0, 0];
var units = AnnexBParser.Split(stream);
Assert.Count(3, units);
Assert.BytesEqual([0x67, 1, 2], units[0].Slice(stream));
Assert.BytesEqual([0x68, 3], units[1].Slice(stream));
Assert.BytesEqual([0x65, 4, 5, 6], units[2].Slice(stream));
Assert.Equal(H264NalUnitType.Sps, AnnexBParser.H264Type(stream[units[0].Offset]));
Assert.Equal(H264NalUnitType.IdrSlice, AnnexBParser.H264Type(stream[units[2].Offset]));
}
[Test]
public void ConvertsAnnexBToLengthPrefixedAndDetectsBoth()
{
var annexB = AnnexBParser.ToAnnexB([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps(), SyntheticStreams.H264Slice(true, 300, 1)]);
var prefixed = AnnexBParser.ToLengthPrefixed(annexB);
var fromAnnexB = AnnexBParser.SplitAccessUnit(annexB, out var wasAnnexB);
var fromPrefixed = AnnexBParser.SplitAccessUnit(prefixed, out var wasAnnexB2);
Assert.True(wasAnnexB);
Assert.False(wasAnnexB2);
Assert.Equal(3, fromAnnexB.Count);
Assert.Equal(3, fromPrefixed.Count);
for (var i = 0; i < 3; i++)
Assert.BytesEqual(fromAnnexB[i].Slice(annexB), fromPrefixed[i].Slice(prefixed));
}
[Test]
public void LengthPrefixedSplitRejectsInconsistentLengths()
{
Assert.False(AnnexBParser.TrySplitLengthPrefixed([0, 0, 0, 9, 1, 2], 4, out _));
Assert.False(AnnexBParser.TrySplitLengthPrefixed([0, 0, 0, 0], 4, out _));
Assert.True(AnnexBParser.TrySplitLengthPrefixed([0, 2, 0x41, 9, 0, 1, 0x41], 2, out var units));
Assert.Count(2, units);
}
[Test]
public void EmulationPreventionRoundTrip()
{
var rng = new Random(7);
for (var trial = 0; trial < 200; trial++)
{
var data = new byte[rng.Next(1, 200)];
for (var i = 0; i < data.Length; i++) data[i] = rng.Next(4) == 0 ? (byte)rng.Next(4) : (byte)0;
var escaped = AnnexBParser.AddEmulationPrevention(data);
for (var i = 2; i < escaped.Length; i++)
Assert.False(escaped[i - 2] == 0 && escaped[i - 1] == 0 && escaped[i] <= 2, "start code prefix survived escaping");
var back = AnnexBParser.RemoveEmulationPrevention(escaped);
// After a lone trailing 0x00 the appended 0x03 is not preceded by two zeros, so it stays.
if (back.Length == data.Length + 1) back = back[..^1];
Assert.BytesEqual(data, back);
}
Assert.BytesEqual([0, 0, 3, 1, 0, 0, 3, 0], AnnexBParser.AddEmulationPrevention([0, 0, 1, 0, 0, 0]).AsSpan(0, 8));
}
[Test]
public void ParsesH264HighProfileSps()
{
var nal = SyntheticStreams.H264Sps(1920, 1080, 100, 41);
Assert.True(H264SpsParser.TryParse(nal, out var sps));
Assert.Equal(100, sps.ProfileIdc);
Assert.Equal(41, sps.LevelIdc);
Assert.Equal(1, sps.ChromaFormatIdc);
Assert.Equal(8, sps.BitDepthLuma);
Assert.Equal(1920, sps.Width);
Assert.Equal(1080, sps.Height);
Assert.Equal(1088, sps.CodedHeight);
Assert.Equal(1, sps.ColourPrimaries);
Assert.Equal(false, sps.FullRange);
Assert.Approximately(29.97, sps.FrameRate!.Value, 0.01);
}
[Theory]
[Case(1280, 720, 77, 31)]
[Case(3840, 2160, 100, 51)]
[Case(642, 482, 66, 30)]
public void ParsesH264SizesWithCropping(int width, int height, int profile, int level)
{
Assert.True(H264SpsParser.TryParse(SyntheticStreams.H264Sps(width, height, profile, level), out var sps));
Assert.Equal(width, sps.Width);
Assert.Equal(height, sps.Height);
Assert.Equal(profile, sps.ProfileIdc);
}
[Test]
public void ParsesHevcMain10Sps()
{
Assert.True(HevcSpsParser.TryParse(SyntheticStreams.HevcSps(1920, 1080, 10, 153), out var sps));
Assert.Equal(1920, sps.Width);
Assert.Equal(1080, sps.Height);
Assert.Equal(1080, sps.CodedHeight);
Assert.Equal(10, sps.BitDepthLuma);
Assert.Equal(10, sps.BitDepthChroma);
Assert.Equal(1, sps.ChromaFormatIdc);
Assert.Equal(2, sps.ProfileTierLevel.ProfileIdc);
Assert.Equal(153, sps.ProfileTierLevel.LevelIdc);
Assert.Equal(0x2000_0000u, sps.ProfileTierLevel.ProfileCompatibilityFlags);
Assert.Equal(0x9000_0000_0000UL, sps.ProfileTierLevel.ConstraintIndicatorFlags);
Assert.False(sps.ProfileTierLevel.HighTier);
Assert.True(sps.TemporalIdNesting);
}
[Test]
public void AppliesHevcConformanceWindow()
{
Assert.True(HevcSpsParser.TryParse(SyntheticStreams.HevcSps(1916, 1076, 8, 120), out var sps));
Assert.Equal(1920, sps.CodedWidth);
Assert.Equal(1080, sps.CodedHeight);
Assert.Equal(1916, sps.Width);
Assert.Equal(1076, sps.Height);
Assert.Equal(1, sps.ProfileTierLevel.ProfileIdc);
}
[Test]
public void ParsesAv1SequenceHeader()
{
var obuBytes = SyntheticStreams.Av1SequenceHeaderObu(3840, 2160, 12, tenBit: true);
Assert.True(Av1ObuParser.TryReadObu(obuBytes, 0, out var obu));
Assert.Equal(Av1ObuType.SequenceHeader, obu.Type);
Assert.True(obu.HasSizeField);
Assert.Equal(obuBytes.Length, obu.TotalLength);
Assert.True(Av1ObuParser.TryParseSequenceHeader(obu.Payload(obuBytes), out var header));
Assert.Equal(3840, header.MaxFrameWidth);
Assert.Equal(2160, header.MaxFrameHeight);
Assert.Equal(12, header.SeqLevelIdx);
Assert.Equal(10, header.BitDepth);
Assert.True(header.ChromaSubsamplingX && header.ChromaSubsamplingY);
Assert.Equal(1, header.ColorPrimaries);
Assert.False(header.FullRange);
}
[Test]
public void ReadsObuWithoutSizeFieldAndSplitsTemporalUnits()
{
byte[] lastWithoutSize = [(byte)Av1ObuType.Frame << 3, 9, 8, 7];
Assert.True(Av1ObuParser.TryReadObu(lastWithoutSize, 0, out var obu));
Assert.False(obu.HasSizeField);
Assert.Equal(3, obu.PayloadLength);
var stream = SyntheticStreams.Concat(
SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1SequenceHeaderObu(), SyntheticStreams.Av1Frame(50, 1),
SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1Frame(40, 2),
SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1Frame(30, 3));
var units = Av1ObuParser.SplitTemporalUnits(stream);
Assert.Count(3, units);
Assert.Equal(0, units[0].Offset);
Assert.Equal(stream.Length, units[2].Offset + units[2].Length);
Assert.Equal(units[0].Length, units[1].Offset);
}
[Test]
public void ParsersSurviveTruncationAndGarbage()
{
byte[][] inputs = [SyntheticStreams.H264Sps(), SyntheticStreams.HevcSps(), SyntheticStreams.Av1SequenceHeaderObu()];
var rng = new Random(3);
foreach (var input in inputs)
{
for (var length = 0; length < input.Length; length++)
{
var slice = input.AsSpan(0, length);
H264SpsParser.TryParse(slice, out _);
HevcSpsParser.TryParse(slice, out _);
Av1ObuParser.Split(slice);
if (length > 2) Av1ObuParser.TryParseSequenceHeader(slice[2..], out _);
}
for (var trial = 0; trial < 300; trial++)
{
var corrupt = (byte[])input.Clone();
corrupt[rng.Next(corrupt.Length)] ^= (byte)(1 << rng.Next(8));
H264SpsParser.TryParse(corrupt, out _);
HevcSpsParser.TryParse(corrupt, out _);
Av1ObuParser.SplitTemporalUnits(corrupt);
Av1ObuParser.TryParseSequenceHeader(corrupt, out _);
AnnexBParser.SplitAccessUnit(corrupt, out _);
}
}
Assert.False(H264SpsParser.TryParse(SyntheticStreams.H264Sps().AsSpan(0, 5), out _));
}
}
@@ -0,0 +1,70 @@
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class CodecLimitsTests
{
[Theory]
[Case(VideoCodec.H264, 1920, 1080, 30.0, 6_220_800L, "4.0", Name = "1080p30 H.264 (0.10 bpp)")]
[Case(VideoCodec.H264, 1920, 1080, 60.0, 12_441_600L, "4.2")]
[Case(VideoCodec.H264, 1280, 720, 30.0, 0L, "3.1")]
[Case(VideoCodec.H264, 3840, 2160, 30.0, 24_883_200L, "5.1")]
[Case(VideoCodec.H264, 1920, 1080, 30.0, 40_000_000L, "4.1", Name = "1080p30 H.264 at 40 Mbit/s")]
[Case(VideoCodec.Hevc, 3840, 2160, 60.0, 34_836_480L, "5.1", Name = "4K60 HEVC (0.07 bpp)")]
[Case(VideoCodec.Hevc, 7680, 4320, 30.0, 69_672_960L, "6.1", Name = "8K30 HEVC (0.07 bpp)")]
[Case(VideoCodec.Hevc, 7680, 4320, 30.0, 50_000_000L, "6.0")]
[Case(VideoCodec.Hevc, 1920, 1080, 30.0, 0L, "4.0")]
[Case(VideoCodec.Av1, 1920, 1080, 30.0, 0L, "4.0")]
[Case(VideoCodec.Av1, 3840, 2160, 60.0, 29_859_840L, "5.1")]
[Case(VideoCodec.Av1, 640, 360, 24.0, 0L, "2.1")]
public void ChoosesLowestFittingLevel(VideoCodec codec, int width, int height, double fps, long bitRate, string level)
{
var check = CodecLimits.Check(codec, width, height, fps, bitRate);
Assert.True(check.Fits);
Assert.Equal(level, check.Level!.Value.Name);
Assert.Equal(LevelLimit.None, check.Exceeded);
Assert.Equal(width, check.SuggestedWidth);
}
[Test]
public void LevelIdentifiersMatchTheBitstreamCodes()
{
Assert.Equal(41, new CodecLevel(VideoCodec.H264, 4, 1).H264LevelIdc);
Assert.Equal(153, new CodecLevel(VideoCodec.Hevc, 5, 1).HevcLevelIdc);
Assert.Equal(186, new CodecLevel(VideoCodec.Hevc, 6, 2).HevcLevelIdc);
Assert.Equal(13, new CodecLevel(VideoCodec.Av1, 5, 1).Av1SeqLevelIdx);
Assert.Equal(19, CodecLimits.Levels(VideoCodec.H264).Count);
Assert.Equal("6.3", CodecLimits.Levels(VideoCodec.Av1)[^1].Name);
}
[Theory]
[Case(VideoCodec.H264, 16384, 8640, 30.0)]
[Case(VideoCodec.Hevc, 15360, 8640, 60.0)]
[Case(VideoCodec.Av1, 20000, 10000, 30.0)]
public void OversizedConfigurationsGetACappedSuggestion(VideoCodec codec, int width, int height, double fps)
{
var check = CodecLimits.Check(codec, width, height, fps, 0);
Assert.False(check.Fits);
Assert.True((check.Exceeded & (LevelLimit.PictureSize | LevelLimit.SampleRate | LevelLimit.Dimension)) != 0);
Assert.True(check.SuggestedWidth % 2 == 0 && check.SuggestedHeight % 2 == 0);
Assert.Approximately(width / (double)height, check.SuggestedWidth / (double)check.SuggestedHeight, 0.01);
Assert.True(CodecLimits.Check(codec, check.SuggestedWidth, check.SuggestedHeight, fps, 0).Fits);
// The suggestion is tight: a slightly larger size no longer fits.
var w = check.SuggestedWidth + 64;
var h = (int)Math.Round(w * (double)height / width);
Assert.False(CodecLimits.Check(codec, w, h, fps, 0).Fits);
}
[Test]
public void ExcessiveBitRateIsReportedWithoutResizing()
{
var check = CodecLimits.Check(VideoCodec.H264, 1920, 1080, 30, 2_000_000_000, CodecProfile.H264High);
Assert.False(check.Fits);
Assert.Equal(LevelLimit.BitRate, check.Exceeded);
Assert.Equal(1920, check.SuggestedWidth);
Assert.Equal(1080, check.SuggestedHeight);
Assert.Equal(1_000_000_000L, check.MaxBitRate);
Assert.Equal(800_000_000L, CodecLimits.Check(VideoCodec.H264, 64, 64, 30, 0, CodecProfile.H264Main).MaxBitRate);
}
}
@@ -0,0 +1,255 @@
using Chronos.Core.Codecs.Gif;
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class GifEncoderTests(TestContext context)
{
private const int W = 64, H = 48;
private const long Frame30 = 3000; // 1/30 s in 90 kHz ticks
[Test]
public void SmoothFramesRoundTripWithinPaletteError()
{
var frames = Enumerable.Range(0, 4).Select(i => Smooth(i * 3)).ToList();
var plain = Encode(frames, new GifEncoderOptions { Dither = false });
var dithered = Encode(frames, new GifEncoderOptions());
Assert.Equal(4, plain.Frames.Count);
Assert.True(plain.GlobalTable);
for (var f = 0; f < frames.Count; f++)
{
var (mean, max) = Error(frames[f], plain.Frames[f].Canvas);
Assert.Less(mean, 6.0, $"frame {f} mean error");
Assert.Less(max, 40, $"frame {f} max error");
context.Log($"frame {f}: plain {mean:0.00}/{max}, dithered tiles {TileError(frames[f], dithered.Frames[f].Canvas):0.00}");
// Dithering trades per-pixel error for accurate local averages.
Assert.Less(TileError(frames[f], dithered.Frames[f].Canvas), 2.0, $"frame {f} 4×4 average error");
}
}
/// <summary>Mean absolute difference of 4×4 tile averages.</summary>
private static double TileError(byte[] rgb, byte[] rgba)
{
double sum = 0;
var tiles = 0;
for (var ty = 0; ty < H / 4; ty++)
{
for (var tx = 0; tx < W / 4; tx++)
{
for (var c = 0; c < 3; c++)
{
double a = 0, b = 0;
for (var y = 0; y < 4; y++)
{
for (var x = 0; x < 4; x++)
{
var i = (ty * 4 + y) * W + tx * 4 + x;
a += rgb[i * 3 + c];
b += rgba[i * 4 + c];
}
}
sum += Math.Abs(a - b) / 16;
tiles++;
}
}
}
return sum / tiles;
}
[Test]
public void ExactColoursReproduceExactly()
{
var palette = RandomColours(120, 5);
var frames = Enumerable.Range(0, 3).Select(i => Blocks(palette, i)).ToList();
var gif = Encode(frames, new GifEncoderOptions { Dither = false, DifferenceThreshold = 0 });
for (var f = 0; f < frames.Count; f++) Assert.Equal((0.0, 0), Error(frames[f], gif.Frames[f].Canvas));
}
[Test]
public void DelaysFollowTheCumulativeTimelineAndLoopIsWritten()
{
var frames = Enumerable.Range(0, 10).Select(i => Blocks(RandomColours(8, i), i)).ToList();
var gif = Encode(frames, new GifEncoderOptions());
Assert.Equal(0, gif.LoopCount);
Assert.SequenceEqual([3, 4, 3, 3, 4, 3, 3, 4, 3, 3], gif.Frames.Select(f => f.DelayCs));
Assert.Equal(33, gif.Frames.Sum(f => f.DelayCs));
Assert.Equal(5, Encode(frames, new GifEncoderOptions { LoopCount = 5 }).LoopCount);
Assert.Null(Encode(frames, new GifEncoderOptions { LoopCount = null }).LoopCount);
}
[Test]
public void DifferencingCropsToTheChangedAreaAndKeepsTheRest()
{
var palette = RandomColours(64, 9);
var a = Blocks(palette, 0);
var b = (byte[])a.Clone();
for (var y = 7; y < 11; y++)
{
for (var x = 10; x < 15; x++)
{
var i = (y * W + x) * 3;
b[i] = (byte)(255 - b[i]);
b[i + 1] = (byte)(255 - b[i + 1]);
}
}
var gif = Encode([a, b], new GifEncoderOptions { Dither = false, DifferenceThreshold = 0 });
Assert.Equal(2, gif.Frames.Count);
var second = gif.Frames[1];
Assert.Equal((10, 7, 5, 4), (second.Left, second.Top, second.Width, second.Height));
Assert.True(second.Transparent);
Assert.Equal(1, second.Disposal);
Assert.Equal(1, gif.Frames[0].Disposal);
Assert.False(gif.Frames[0].Transparent);
Assert.Equal((0.0, 0), Error(b, second.Canvas));
}
[Test]
public void IdenticalFramesMergeIntoOneLongerFrame()
{
var palette = RandomColours(16, 2);
var a = Blocks(palette, 0);
var b = Blocks(palette, 1);
var gif = Encode([a, a, a, b], new GifEncoderOptions { Dither = false });
Assert.Equal(2, gif.Frames.Count);
Assert.Equal(10, gif.Frames[0].DelayCs);
Assert.Equal(3, gif.Frames[1].DelayCs);
}
[Test]
public void LocalPalettesFollowEachFrame()
{
var reds = Enumerable.Range(0, 200).SelectMany(i => new[] { (byte)(55 + i), (byte)(i / 4), (byte)0 }).ToArray();
var blues = Enumerable.Range(0, 200).SelectMany(i => new[] { (byte)0, (byte)(i / 4), (byte)(55 + i) }).ToArray();
var frames = new List<byte[]> { Blocks(reds, 0), Blocks(blues, 0) };
var gif = Encode(frames, new GifEncoderOptions { PaletteMode = GifPaletteMode.Local, Dither = false, DifferenceThreshold = 0 });
Assert.False(gif.GlobalTable);
Assert.True(gif.Frames.All(f => f.LocalTable));
for (var f = 0; f < 2; f++) Assert.Equal((0.0, 0), Error(frames[f], gif.Frames[f].Canvas));
}
[Test]
public void LzwSurvivesDictionaryResets()
{
// 200×200 pixels of random indices fill the 4096-entry dictionary many times over.
const int size = 200;
var palette = RandomColours(200, 4);
var rng = new Random(8);
var rgb = new byte[size * size * 3];
for (var i = 0; i < size * size; i++)
{
var c = rng.Next(200);
rgb[i * 3] = palette[c * 3];
rgb[i * 3 + 1] = palette[c * 3 + 1];
rgb[i * 3 + 2] = palette[c * 3 + 2];
}
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, size, size, new GifEncoderOptions { Dither = false, FrameDifferencing = false });
encoder.AddFrame(rgb, Frame30);
encoder.Complete();
var gif = GifTestDecoder.Decode(ms.ToArray());
Assert.Equal((0.0, 0), Error(rgb, gif.Frames[0].Canvas));
}
[Test]
public void LinearImageBuffersAreEncodedAsSrgb()
{
var palette = RandomColours(30, 6);
var rgb = Blocks(palette, 3);
using var image = new ImageBuffer(W, H);
for (var i = 0; i < W * H; i++)
{
for (var c = 0; c < 3; c++) image.Plane(c)[i] = ColorSpace.Linear8(rgb[i * 3 + c]);
}
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, W, H, new GifEncoderOptions { Dither = false });
encoder.AddFrame(image, Frame30);
encoder.Complete();
Assert.Equal(1, encoder.FrameCount);
Assert.Equal((0.0, 0), Error(rgb, GifTestDecoder.Decode(ms.ToArray()).Frames[0].Canvas));
}
[Test]
public void SuppliedPaletteIsUsedAsGlobalTable()
{
using var image = new ImageBuffer(W, H);
image.Plane(0).Fill(0.5f);
var palette = GifEncoder.BuildPalette([image], 4);
Assert.Equal(3, palette.Length);
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, W, H, new GifEncoderOptions { Palette = palette });
encoder.AddFrame(image, Frame30);
encoder.Complete();
var gif = GifTestDecoder.Decode(ms.ToArray());
Assert.True(gif.GlobalTable);
Assert.Equal(ColorSpace.Encode8(0.5f), gif.Frames[0].Canvas[0]);
}
private static GifTestDecoder Encode(List<byte[]> frames, GifEncoderOptions options)
{
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, W, H, options);
foreach (var f in frames) encoder.AddFrame(f, Frame30);
encoder.Complete();
return GifTestDecoder.Decode(ms.ToArray());
}
private static (double Mean, int Max) Error(byte[] rgb, byte[] rgba)
{
long sum = 0;
var max = 0;
for (var i = 0; i < rgb.Length / 3; i++)
{
for (var c = 0; c < 3; c++)
{
var d = Math.Abs(rgb[i * 3 + c] - rgba[i * 4 + c]);
sum += d;
max = Math.Max(max, d);
}
}
return (sum / (double)rgb.Length, max);
}
private static byte[] Smooth(int shift)
{
var rgb = new byte[W * H * 3];
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
var i = (y * W + x) * 3;
rgb[i] = (byte)((x + shift) * 255 / (W + 12));
rgb[i + 1] = (byte)(y * 255 / H);
rgb[i + 2] = (byte)(128 + 100 * Math.Sin((x + y + shift) * 0.1));
}
}
return rgb;
}
private static byte[] RandomColours(int count, int seed)
{
var bytes = new byte[count * 3];
new Random(seed).NextBytes(bytes);
return bytes;
}
/// <summary>4×4 blocks coloured from <paramref name="palette"/>, pattern varying with <paramref name="variant"/>.</summary>
private static byte[] Blocks(byte[] palette, int variant)
{
var colours = palette.Length / 3;
var rgb = new byte[W * H * 3];
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
var c = ((x / 4) * 7 + (y / 4) * 13 + variant * 5) % colours;
var i = (y * W + x) * 3;
rgb[i] = palette[c * 3];
rgb[i + 1] = palette[c * 3 + 1];
rgb[i + 2] = palette[c * 3 + 2];
}
}
return rgb;
}
}
@@ -0,0 +1,197 @@
using System.Text;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
/// <summary>Minimal GIF89a decoder used to verify <c>GifEncoder</c> output (composition with disposal 0–3).</summary>
internal sealed class GifTestDecoder
{
public sealed record Frame(byte[] Canvas, int DelayCs, int Left, int Top, int Width, int Height, int Disposal, bool Transparent, bool LocalTable);
public int Width { get; private set; }
public int Height { get; private set; }
public bool GlobalTable { get; private set; }
public int? LoopCount { get; private set; }
public List<Frame> Frames { get; } = [];
public static GifTestDecoder Decode(byte[] data)
{
var gif = new GifTestDecoder();
Assert.Equal("GIF89a", Encoding.ASCII.GetString(data, 0, 6));
gif.Width = data[6] | data[7] << 8;
gif.Height = data[8] | data[9] << 8;
var pos = 13;
byte[]? global = null;
if ((data[10] & 0x80) != 0)
{
gif.GlobalTable = true;
var size = 3 << ((data[10] & 7) + 1);
global = data.AsSpan(pos, size).ToArray();
pos += size;
}
var canvas = new byte[gif.Width * gif.Height * 4];
int delay = 0, disposal = 0, transparentIndex = -1;
while (true)
{
var block = data[pos++];
if (block == 0x3B) break;
if (block == 0x21)
{
var label = data[pos++];
if (label == 0xF9)
{
Assert.Equal((byte)4, data[pos]);
disposal = (data[pos + 1] >> 2) & 7;
transparentIndex = (data[pos + 1] & 1) != 0 ? data[pos + 4] : -1;
delay = data[pos + 2] | data[pos + 3] << 8;
pos += 6;
}
else if (label == 0xFF && Encoding.ASCII.GetString(data, pos + 1, 11) == "NETSCAPE2.0")
{
gif.LoopCount = data[pos + 14] | data[pos + 15] << 8;
pos += 12;
pos = SkipSubBlocks(data, pos);
}
else
{
pos = SkipSubBlocks(data, pos);
}
continue;
}
Assert.Equal((byte)0x2C, block);
var left = data[pos] | data[pos + 1] << 8;
var top = data[pos + 2] | data[pos + 3] << 8;
var w = data[pos + 4] | data[pos + 5] << 8;
var h = data[pos + 6] | data[pos + 7] << 8;
var packed = data[pos + 8];
pos += 9;
var table = global;
var local = (packed & 0x80) != 0;
if (local)
{
var size = 3 << ((packed & 7) + 1);
table = data.AsSpan(pos, size).ToArray();
pos += size;
}
Assert.False((packed & 0x40) != 0, "interlaced frames are not produced");
Assert.True(left + w <= gif.Width && top + h <= gif.Height, "frame inside the logical screen");
var minCode = data[pos++];
using var lzw = new MemoryStream();
while (data[pos] != 0)
{
lzw.Write(data, pos + 1, data[pos]);
pos += data[pos] + 1;
}
pos++;
var indices = DecodeLzw(lzw.ToArray(), 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 index = indices[y * w + x];
if (index == transparentIndex) continue;
var o = ((top + y) * gif.Width + left + x) * 4;
canvas[o] = table![index * 3];
canvas[o + 1] = table[index * 3 + 1];
canvas[o + 2] = table[index * 3 + 2];
canvas[o + 3] = 255;
}
}
gif.Frames.Add(new Frame((byte[])canvas.Clone(), delay, left, top, w, h, disposal, transparentIndex >= 0, local));
if (disposal == 2)
{
for (var y = 0; y < h; y++) canvas.AsSpan(((top + y) * gif.Width + left) * 4, w * 4).Clear();
}
else if (disposal == 3)
{
canvas = saved!;
}
delay = 0;
disposal = 0;
transparentIndex = -1;
}
return gif;
}
private static int SkipSubBlocks(byte[] data, int pos)
{
while (data[pos] != 0) pos += data[pos] + 1;
return pos + 1;
}
private static byte[] DecodeLzw(byte[] data, int minCode, int pixels)
{
var output = new List<byte>(pixels);
var prefix = new short[4096];
var suffix = new byte[4096];
var stack = new byte[4097];
var clear = 1 << minCode;
var end = clear + 1;
var codeSize = minCode + 1;
var next = end + 1;
var old = -1;
long bits = 0;
var count = 0;
var pos = 0;
while (true)
{
while (count < codeSize && pos < data.Length)
{
bits |= (long)data[pos++] << count;
count += 8;
}
Assert.True(count >= codeSize, "LZW data ended before the end code");
var code = (int)(bits & ((1 << codeSize) - 1));
bits >>= codeSize;
count -= codeSize;
if (code == clear)
{
codeSize = minCode + 1;
next = end + 1;
old = -1;
continue;
}
if (code == end) break;
if (old == -1)
{
Assert.True(code < clear, "first code after clear is a literal");
output.Add((byte)code);
old = code;
continue;
}
Assert.True(code <= next, $"LZW code {code} beyond the table ({next})");
var depth = 0;
var c = code;
if (code == next)
{
stack[depth++] = First(old, prefix, suffix, clear);
c = old;
}
while (c >= clear)
{
stack[depth++] = suffix[c];
c = prefix[c];
}
stack[depth++] = (byte)c;
var firstByte = (byte)c;
for (var i = depth - 1; i >= 0; i--) output.Add(stack[i]);
if (next < 4096)
{
prefix[next] = (short)old;
suffix[next] = firstByte;
next++;
if (next == 1 << codeSize && codeSize < 12) codeSize++;
}
old = code;
}
Assert.Equal(pixels, output.Count);
return [.. output];
}
private static byte First(int code, short[] prefix, byte[] suffix, int clear)
{
while (code >= clear) code = prefix[code];
return (byte)code;
}
}
@@ -0,0 +1,256 @@
using System.Buffers.Binary;
using Chronos.Core.Video;
using Chronos.Core.Video.Bitstream;
using Chronos.Core.Video.Mp4;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class Mp4MuxerTests(TestContext context)
{
private static long Duration(int i) => 3000 + i % 3 * 1500;
[Test]
public void H264WithVariableDurationsInspectsClean()
{
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 });
var expected = new List<byte[]>();
long total = 0;
for (var i = 0; i < 30; i++)
{
var idr = i % 10 == 0;
var slice = SyntheticStreams.H264Slice(idr, 200 + i * 7, i);
List<byte[]> nals = [SyntheticStreams.H264AccessUnitDelimiter()];
if (idr) nals.AddRange([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()]);
nals.Add(slice);
var annexB = AnnexBParser.ToAnnexB(nals);
// Alternate input formats: the muxer accepts both.
muxer.WriteSample(i % 2 == 0 ? annexB : AnnexBParser.ToLengthPrefixed(annexB), Duration(i), idr);
expected.Add(AnnexBParser.ToLengthPrefixed(AnnexBParser.ToAnnexB([slice])));
total += Duration(i);
}
muxer.Complete();
var report = Mp4Inspector.Inspect(ms);
AssertClean(report);
Assert.Equal("avc1", report.SampleEntry);
Assert.Equal("avc1.640029", report.CodecString);
Assert.Equal(1920, report.Width);
Assert.Equal(1080, report.Height);
Assert.Equal(30, report.FrameCount);
Assert.Equal(3, report.SyncSampleCount);
Assert.Equal(90000u, report.TimeScale);
Assert.Equal(total, report.DurationTicks);
Assert.False(report.FastStart);
Assert.False(report.HasEditList);
for (var i = 0; i < 30; i++)
{
Assert.Equal(Duration(i), (long)report.Samples[i].Duration);
Assert.BytesEqual(expected[i], ReadSample(ms, report.Samples[i]));
}
}
[Test]
public void HevcMain10InspectsClean()
{
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.Hevc, Width = 3840, Height = 2160 });
for (var i = 0; i < 12; i++)
{
var idr = i % 6 == 0;
List<byte[]> nals = idr ? [SyntheticStreams.HevcVps(), SyntheticStreams.HevcSps(3840, 2160), SyntheticStreams.HevcPps()] : [];
nals.Add(SyntheticStreams.HevcSlice(idr, 500, i));
muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 1500, idr);
}
muxer.Complete();
var report = Mp4Inspector.Inspect(ms);
AssertClean(report);
Assert.Equal("hvc1", report.SampleEntry);
Assert.Equal(VideoCodec.Hevc, report.Codec);
Assert.Equal("hvc1.2.4.L153.90", report.CodecString);
Assert.Equal(3840, report.Width);
Assert.Equal(2160, report.Height);
Assert.Equal(10, report.BitDepth);
Assert.Equal(12, report.FrameCount);
Assert.Equal(18000L, report.DurationTicks);
Assert.Approximately(0.2, report.Duration.TotalSeconds, 1e-9);
}
[Test]
public void Av1InspectsCleanAndGetsSizeFields()
{
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.Av1, Width = 1280, Height = 720 });
for (var i = 0; i < 10; i++)
{
var key = i == 0;
var frame = SyntheticStreams.Random(300, i);
// Last OBU of the temporal unit without obu_size, as encoders may emit it.
byte[] lastWithoutSize = [(byte)Av1ObuType.Frame << 3, .. frame];
var tu = key
? SyntheticStreams.Concat(SyntheticStreams.Av1TemporalDelimiter(), SyntheticStreams.Av1SequenceHeaderObu(1280, 720, 5), lastWithoutSize)
: SyntheticStreams.Concat(SyntheticStreams.Av1TemporalDelimiter(), lastWithoutSize);
muxer.WriteSample(tu, 3003, key);
}
muxer.Complete();
var report = Mp4Inspector.Inspect(ms);
AssertClean(report);
Assert.Equal("av01", report.SampleEntry);
Assert.Equal("av01.0.05M.08", report.CodecString);
Assert.Equal(1280, report.Width);
Assert.Equal(720, report.Height);
Assert.Equal(10, report.FrameCount);
Assert.Equal(1, report.SyncSampleCount);
var second = ReadSample(ms, report.Samples[1]);
Assert.True(Av1ObuParser.TryReadObu(second, 0, out var obu));
Assert.True(obu.HasSizeField);
Assert.Equal(Av1ObuType.Frame, obu.Type);
Assert.Equal(second.Length, obu.TotalLength);
}
[Test]
public void FastStartMovesMoovAndKeepsOffsetsValid()
{
var path = Path.Combine(context.CreateTempDirectory(), "fast.mp4");
var expected = new List<byte[]>();
using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite))
{
var muxer = new Mp4Muxer(fs, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1280, Height = 720, FastStart = true });
for (var i = 0; i < 90; i++)
{
var idr = i % 30 == 0;
var slice = SyntheticStreams.H264Slice(idr, 4000 + i, i);
List<byte[]> nals = idr ? [SyntheticStreams.H264Sps(1280, 720, 77, 31), SyntheticStreams.H264Pps(), slice] : [slice];
muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 3000, idr);
expected.Add(AnnexBParser.ToLengthPrefixed(AnnexBParser.ToAnnexB([slice])));
}
muxer.Complete();
}
var report = Mp4Inspector.Inspect(path);
AssertClean(report);
Assert.True(report.FastStart);
Assert.SequenceEqual(["ftyp", "moov", "free", "mdat"], report.Boxes.Select(b => b.Type));
Assert.Equal(new FileInfo(path).Length, report.Boxes.Sum(b => b.Size));
using var read = File.OpenRead(path);
for (var i = 0; i < expected.Count; i++) Assert.BytesEqual(expected[i], ReadSample(read, report.Samples[i]));
}
[Test]
public void CompositionOffsetsProduceCttsAndEditList()
{
// Decode order I0 P3 B1 B2 P6 B4 B5 with unit durations of 3000 ticks; encoder gives PTS − DTS.
int[] pts = [0, 3, 1, 2, 6, 4, 5];
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 });
for (var i = 0; i < pts.Length; i++)
{
List<byte[]> nals = i == 0 ? [SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()] : [];
nals.Add(SyntheticStreams.H264Slice(i == 0, 100, i));
muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 3000, i == 0, (pts[i] - i) * 3000L);
}
muxer.Complete();
var report = Mp4Inspector.Inspect(ms);
AssertClean(report);
Assert.True(report.HasCompositionOffsets);
Assert.True(report.HasEditList);
Assert.Equal(7 * 3000L, report.DurationTicks);
// After the shift every composition time is non-negative and I0 presents first.
var cts = report.Samples.Select(s => s.DecodeTime + s.CompositionOffset).ToArray();
Assert.Equal(cts.Min(), cts[0]);
Assert.True(report.Samples.All(s => s.CompositionOffset >= 0));
}
[Test]
public void LargeFilesUseCo64AndLargeMdat()
{
const int sampleSize = 1 << 20;
const int samples = 4200; // ≈ 4.4 GB of payload, dropped by the sparse stream
var slice = new byte[sampleSize];
BinaryPrimitives.WriteInt32BigEndian(slice, sampleSize - 4);
slice[4] = 0x41; // non-IDR slice header
var first = SyntheticStreams.Concat(
AnnexBParser.ToLengthPrefixed(AnnexBParser.ToAnnexB([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()])), slice);
first[first.Length - sampleSize + 4] = 0x65;
using var sparse = new SparseStream();
var muxer = new Mp4Muxer(sparse, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 });
muxer.WriteSample(first, 3000, true);
for (var i = 1; i < samples; i++) muxer.WriteSample(slice, 3000, i % 60 == 0);
muxer.Complete();
var report = Mp4Inspector.Inspect(sparse);
AssertClean(report);
Assert.True(report.UsesCo64);
Assert.True(report.UsesLargeMdat);
Assert.Equal(samples, report.FrameCount);
Assert.Greater(report.Samples[^1].Offset, uint.MaxValue);
Assert.Equal((long)sampleSize * samples, report.MediaBytes);
}
[Test]
public void CompleteWithoutParameterSetsThrows()
{
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 64, Height = 64 });
muxer.WriteSample(AnnexBParser.ToAnnexB([SyntheticStreams.H264Slice(true, 10, 1)]), 3000, true);
Assert.Throws<InvalidOperationException>(muxer.Complete);
Assert.Throws<ArgumentOutOfRangeException>(() => muxer.WriteSample([0, 0, 1, 0x65, 1], 0, true));
}
[Test]
public void ParameterSetOnlyUnitsAddNoSampleAndSeiOnlyUnitsAreRejected()
{
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 });
muxer.WriteSample(AnnexBParser.ToAnnexB([SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()]), 3000, true);
Assert.Equal(0, muxer.SampleCount);
Assert.Throws<ArgumentException>(() => muxer.WriteSample(AnnexBParser.ToAnnexB([[0x06, 0x05, 0x01, 0x00, 0x80]]), 3000, false));
muxer.WriteSample(AnnexBParser.ToAnnexB([SyntheticStreams.H264Slice(true, 64, 1)]), 3000, true);
muxer.Complete();
var report = Mp4Inspector.Inspect(ms);
AssertClean(report);
Assert.Equal(1, report.FrameCount);
Assert.Equal(0, report.Warnings.Count);
}
[Test]
public void InspectorSurvivesTruncationAndCorruption()
{
using var ms = new MemoryStream();
var muxer = new Mp4Muxer(ms, new VideoTrackConfig { Codec = VideoCodec.H264, Width = 1920, Height = 1080 });
for (var i = 0; i < 5; i++)
{
List<byte[]> nals = i == 0 ? [SyntheticStreams.H264Sps(), SyntheticStreams.H264Pps()] : [];
nals.Add(SyntheticStreams.H264Slice(i == 0, 50, i));
muxer.WriteSample(AnnexBParser.ToAnnexB(nals), 3000, i == 0);
}
muxer.Complete();
var valid = ms.ToArray();
for (var cut = 0; cut < valid.Length; cut += 7)
{
var report = Mp4Inspector.Inspect(new MemoryStream(valid, 0, cut));
Assert.False(report.IsValid, $"truncated at {cut} should not validate");
}
var rng = new Random(11);
for (var trial = 0; trial < 500; trial++)
{
var corrupt = (byte[])valid.Clone();
for (var k = 0; k < 3; k++) corrupt[rng.Next(corrupt.Length)] = (byte)rng.Next(256);
Mp4Inspector.Inspect(new MemoryStream(corrupt)).ToString();
}
}
private static void AssertClean(Mp4Report report)
{
if (!report.IsValid) Assert.Fail("Inspector errors: " + string.Join("; ", report.Errors));
}
private static byte[] ReadSample(Stream stream, Mp4SampleInfo sample)
{
var data = new byte[sample.Size];
stream.Position = sample.Offset;
stream.ReadExactly(data);
return data;
}
}
@@ -0,0 +1,181 @@
using Chronos.Core.Imaging;
using Chronos.Core.Video.Yuv;
using Chronos.Testing;
namespace Chronos.Core.Tests.Video;
public sealed class Nv12ConverterTests
{
[Theory]
[Case(1f, 1f, 1f, 235, 128, 128)]
[Case(0f, 0f, 0f, 16, 128, 128)]
[Case(1f, 0f, 0f, 63, 102, 240)]
[Case(0f, 1f, 0f, 173, 42, 26)]
[Case(0f, 0f, 1f, 32, 240, 118)]
public void FlatColoursHitBt709LimitedRangeCodes(float r, float g, float b, int y, int u, int v)
{
using var image = Flat(8, 4, r, g, b);
var nv12 = new byte[Nv12Converter.FrameLength(8, 4)];
Nv12Converter.ToNv12(image, nv12);
Assert.True(nv12.AsSpan(0, 32).ToArray().All(c => c == y), $"luma {nv12[0]} expected {y}");
Assert.Equal((byte)u, nv12[32]);
Assert.Equal((byte)v, nv12[33]);
var p010 = new ushort[Nv12Converter.FrameLength(8, 4)];
Nv12Converter.ToP010(image, p010);
Assert.InRange(p010[0] >> 6, y * 4 - 2, y * 4 + 2);
Assert.Equal(0, p010[0] & 0x3F);
Assert.InRange(p010[32] >> 6, u * 4 - 2, u * 4 + 2);
}
[Test]
public void TenBitWhiteAndBlackAreExact()
{
using var white = Flat(4, 2, 1, 1, 1);
var p010 = new ushort[Nv12Converter.FrameLength(4, 2)];
Nv12Converter.ToP010(white, p010);
Assert.Equal((ushort)(940 << 6), p010[0]);
Assert.Equal((ushort)(512 << 6), p010[8]);
using var black = Flat(4, 2, 0, 0, 0);
Nv12Converter.ToP010(black, p010);
Assert.Equal((ushort)(64 << 6), p010[3]);
}
[Theory]
[Case(70, 34)]
[Case(512, 256)]
public void LumaMatchesScalarReferenceIncludingRemainders(int width, int height)
{
using var image = Gradient(width, height);
var nv12 = new byte[Nv12Converter.FrameLength(width, height)];
var p010 = new ushort[Nv12Converter.FrameLength(width, height)];
Nv12Converter.ToNv12(image, nv12);
Nv12Converter.ToP010(image, p010);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var luma = 0.2126f * ColorSpace.EncodeFast(image[0, x, y]) + 0.7152f * ColorSpace.EncodeFast(image[1, x, y]) + 0.0722f * ColorSpace.EncodeFast(image[2, x, y]);
Assert.InRange(nv12[y * width + x], luma * 219 + 16 - 1, luma * 219 + 17);
Assert.InRange(p010[y * width + x] >> 6, luma * 876 + 64 - 1, luma * 876 + 65);
}
}
}
[Theory]
[Case(ChromaSiting.Left)]
[Case(ChromaSiting.Center)]
public void RoundTripStaysWithinQuantisationError(ChromaSiting siting)
{
const int w = 256, h = 128;
using var image = Gradient(w, h);
using var back = new ImageBuffer(w, h);
var nv12 = new byte[Nv12Converter.FrameLength(w, h)];
Nv12Converter.ToNv12(image, nv12, siting);
Nv12Converter.FromNv12(nv12, back, siting);
var maxNv12 = MaxEncodedError(image, back);
var p010 = new ushort[Nv12Converter.FrameLength(w, h)];
Nv12Converter.ToP010(image, p010, siting);
Nv12Converter.FromP010(p010, back, siting);
var maxP010 = MaxEncodedError(image, back);
Assert.LessOrEqual(maxNv12, 3.5 / 255);
Assert.LessOrEqual(maxP010, 2.0 / 255);
Assert.Less(maxP010, maxNv12);
}
[Test]
public void GreyRampRoundTripOnlyCarriesLumaQuantisation()
{
const int w = 256, h = 4;
using var image = new ImageBuffer(w, h, 1);
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++) image[0, x, y] = ColorSpace.Linear8((byte)x);
}
using var back = new ImageBuffer(w, h, 1);
var nv12 = new byte[Nv12Converter.FrameLength(w, h)];
Nv12Converter.ToNv12(image, nv12);
Assert.True(nv12.AsSpan(w * h).ToArray().All(c => c == 128), "grey has neutral chroma");
Nv12Converter.FromNv12(nv12, back);
double max = 0;
for (var i = 0; i < w * h; i++) max = Math.Max(max, Math.Abs(ColorSpace.LinearToSrgb(image.Plane(0)[i]) - ColorSpace.LinearToSrgb(back.Plane(0)[i])));
// One limited-range step is 255/219 full-range levels; rounding keeps half of it.
Assert.LessOrEqual(max, 0.6 / 219);
}
[Test]
public void SitingChangesTheChromaFilterFootprint()
{
// Columns: red, red | blue, blue. Centre siting keeps the second chroma pure blue,
// left siting (co-sited with column 2, taps 1:2:1) mixes in a quarter of red.
using var image = new ImageBuffer(4, 2);
for (var y = 0; y < 2; y++)
{
image[0, 0, y] = image[0, 1, y] = 1;
image[2, 2, y] = image[2, 3, y] = 1;
}
var centre = new byte[Nv12Converter.FrameLength(4, 2)];
var left = new byte[Nv12Converter.FrameLength(4, 2)];
Nv12Converter.ToNv12(image, centre, ChromaSiting.Center);
Nv12Converter.ToNv12(image, left, ChromaSiting.Left);
Assert.Equal((byte)240, centre[8 + 2]); // Cb of pure blue
Assert.Equal((byte)118, centre[8 + 3]); // Cr of pure blue
Assert.Equal((byte)240, left[8 + 1]); // Cr of pure red at column 0
// R'G'B' = (0.25, 0, 0.75): Cb = (0.75 − 0.1073) / 1.8556 → 206, Cr = (0.25 − 0.1073) / 1.5748 → 148.
Assert.Equal((byte)206, left[8 + 2]);
Assert.Equal((byte)148, left[8 + 3]);
}
[Test]
public void RespectsStrideAndRejectsOddSizes()
{
using var image = Flat(6, 2, 1, 1, 1);
var nv12 = new byte[Nv12Converter.FrameLength(16, 2)];
nv12.AsSpan().Fill(7);
Nv12Converter.ToNv12(image, nv12, stride: 16);
Assert.Equal((byte)235, nv12[5]);
Assert.Equal((byte)7, nv12[6]); // padding untouched
Assert.Equal((byte)128, nv12[32]);
using var odd = new ImageBuffer(5, 2);
Assert.Throws<ArgumentException>(() => Nv12Converter.ToNv12(odd, new byte[64]));
}
private static double MaxEncodedError(ImageBuffer a, ImageBuffer b)
{
double max = 0;
for (var c = 0; c < 3; c++)
{
var pa = a.Plane(c);
var pb = b.Plane(c);
for (var i = 0; i < pa.Length; i++) max = Math.Max(max, Math.Abs(ColorSpace.LinearToSrgb(pa[i]) - ColorSpace.LinearToSrgb(pb[i])));
}
return max;
}
private static ImageBuffer Flat(int w, int h, float r, float g, float b)
{
var image = new ImageBuffer(w, h);
image.Plane(0).Fill(r);
image.Plane(1).Fill(g);
image.Plane(2).Fill(b);
return image;
}
/// <summary>Smooth colour ramps in encoded space (linearised), so 4:2:0 loss stays small.</summary>
private static ImageBuffer Gradient(int w, int h)
{
var image = new ImageBuffer(w, h);
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
image[0, x, y] = (float)ColorSpace.SrgbToLinear(0.1 + 0.8 * x / w);
image[1, x, y] = (float)ColorSpace.SrgbToLinear(0.2 + 0.6 * y / h);
image[2, x, y] = (float)ColorSpace.SrgbToLinear(0.5 + 0.2 * Math.Sin((x + y) * 0.02));
}
}
return image;
}
}
@@ -0,0 +1,76 @@
namespace Chronos.Core.Tests.Video;
/// <summary>
/// A seekable stream that keeps small writes (headers, length prefixes, moov) and drops large payload writes,
/// which read back as zeros. Lets tests produce multi-gigabyte container layouts without the bytes.
/// </summary>
internal sealed class SparseStream : Stream
{
private const int PageSize = 1024;
private const int LargeWrite = 64 * 1024;
private readonly Dictionary<long, byte[]> _pages = [];
private long _length;
private long _position;
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => true;
public override long Length => _length;
public override long Position
{
get => _position;
set => _position = value;
}
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => _position = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => _position + offset,
_ => _length + offset,
};
public override void SetLength(long value) => _length = value;
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
public override int Read(Span<byte> buffer)
{
var n = (int)Math.Clamp(_length - _position, 0, buffer.Length);
for (var i = 0; i < n;)
{
var at = _position + i;
var inPage = (int)(at % PageSize);
var chunk = Math.Min(n - i, PageSize - inPage);
if (_pages.TryGetValue(at / PageSize, out var page)) page.AsSpan(inPage, chunk).CopyTo(buffer.Slice(i, chunk));
else buffer.Slice(i, chunk).Clear();
i += chunk;
}
_position += n;
return n;
}
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
if (buffer.Length < LargeWrite)
{
for (var i = 0; i < buffer.Length;)
{
var at = _position + i;
var inPage = (int)(at % PageSize);
var chunk = Math.Min(buffer.Length - i, PageSize - inPage);
if (!_pages.TryGetValue(at / PageSize, out var page)) _pages[at / PageSize] = page = new byte[PageSize];
buffer.Slice(i, chunk).CopyTo(page.AsSpan(inPage, chunk));
i += chunk;
}
}
_position += buffer.Length;
_length = Math.Max(_length, _position);
}
}
@@ -0,0 +1,323 @@
using Chronos.Core.Video.Bitstream;
namespace Chronos.Core.Tests.Video;
/// <summary>Builds syntactically valid H.264/HEVC parameter sets, AV1 sequence headers and slice stubs.</summary>
internal static class SyntheticStreams
{
/// <summary>H.264 SPS NAL (header included) for 4:2:0 8-bit with cropping to the requested size and VUI timing.</summary>
public static byte[] H264Sps(int width = 1920, int height = 1080, int profileIdc = 100, int levelIdc = 41, uint timeScale = 60000, uint unitsInTick = 1001)
{
var w = new BitWriter();
w.WriteBits((ulong)profileIdc, 8);
w.WriteBits(0, 8); // constraint flags
w.WriteBits((ulong)levelIdc, 8);
w.WriteUe(0); // seq_parameter_set_id
if (profileIdc == 100)
{
w.WriteUe(1); // chroma_format_idc
w.WriteUe(0); // bit_depth_luma_minus8
w.WriteUe(0); // bit_depth_chroma_minus8
w.WriteBit(false); // qpprime_y_zero_transform_bypass_flag
w.WriteBit(false); // seq_scaling_matrix_present_flag
}
w.WriteUe(0); // log2_max_frame_num_minus4
w.WriteUe(0); // pic_order_cnt_type
w.WriteUe(2); // log2_max_pic_order_cnt_lsb_minus4
w.WriteUe(4); // max_num_ref_frames
w.WriteBit(false); // gaps_in_frame_num_value_allowed_flag
var mbW = (width + 15) / 16;
var mbH = (height + 15) / 16;
w.WriteUe((uint)mbW - 1);
w.WriteUe((uint)mbH - 1);
w.WriteBit(true); // frame_mbs_only_flag
w.WriteBit(true); // direct_8x8_inference_flag
var cropRight = (mbW * 16 - width) / 2;
var cropBottom = (mbH * 16 - height) / 2;
var crop = cropRight > 0 || cropBottom > 0;
w.WriteBit(crop);
if (crop)
{
w.WriteUe(0);
w.WriteUe((uint)cropRight);
w.WriteUe(0);
w.WriteUe((uint)cropBottom);
}
w.WriteBit(true); // vui_parameters_present_flag
w.WriteBit(true); // aspect_ratio_info_present_flag
w.WriteBits(1, 8); // aspect_ratio_idc 1:1
w.WriteBit(false); // overscan_info_present_flag
w.WriteBit(true); // video_signal_type_present_flag
w.WriteBits(5, 3); // video_format
w.WriteBit(false); // video_full_range_flag
w.WriteBit(true); // colour_description_present_flag
w.WriteBits(1, 8);
w.WriteBits(1, 8);
w.WriteBits(1, 8);
w.WriteBit(false); // chroma_loc_info_present_flag
w.WriteBit(true); // timing_info_present_flag
w.WriteBits(unitsInTick, 32);
w.WriteBits(timeScale, 32);
w.WriteBit(true); // fixed_frame_rate_flag
w.WriteBit(false); // nal_hrd_parameters_present_flag
w.WriteBit(false); // vcl_hrd_parameters_present_flag
w.WriteBit(false); // pic_struct_present_flag
w.WriteBit(false); // bitstream_restriction_flag
w.WriteTrailingBits();
return Nal([0x67], w.ToArray());
}
public static byte[] H264Pps()
{
var w = new BitWriter();
w.WriteUe(0); // pic_parameter_set_id
w.WriteUe(0); // seq_parameter_set_id
w.WriteBit(true); // entropy_coding_mode_flag
w.WriteBit(false); // bottom_field_pic_order_in_frame_present_flag
w.WriteUe(0); // num_slice_groups_minus1
w.WriteUe(0); // num_ref_idx_l0_default_active_minus1
w.WriteUe(0); // num_ref_idx_l1_default_active_minus1
w.WriteBit(false); // weighted_pred_flag
w.WriteBits(0, 2); // weighted_bipred_idc
w.WriteSe(0); // pic_init_qp_minus26
w.WriteSe(0); // pic_init_qs_minus26
w.WriteSe(0); // chroma_qp_index_offset
w.WriteBit(true); // deblocking_filter_control_present_flag
w.WriteBit(false); // constrained_intra_pred_flag
w.WriteBit(false); // redundant_pic_cnt_present_flag
w.WriteBit(true); // transform_8x8_mode_flag
w.WriteBit(false); // pic_scaling_matrix_present_flag
w.WriteSe(0); // second_chroma_qp_index_offset
w.WriteTrailingBits();
return Nal([0x68], w.ToArray());
}
/// <summary>A slice NAL with a plausible header and pseudo-random payload.</summary>
public static byte[] H264Slice(bool idr, int payloadBytes, int seed)
{
var w = new BitWriter();
w.WriteUe(0); // first_mb_in_slice
w.WriteUe(idr ? 7u : 5u); // slice_type I / P
w.WriteUe(0); // pic_parameter_set_id
w.WriteBytes(Random(payloadBytes, seed));
w.WriteTrailingBits();
return Nal([idr ? (byte)0x65 : (byte)0x41], w.ToArray());
}
public static byte[] H264AccessUnitDelimiter() => [0x09, 0xF0];
public static byte[] HevcVps()
{
var w = new BitWriter();
w.WriteBits(0, 4); // vps_video_parameter_set_id
w.WriteBit(true); // vps_base_layer_internal_flag
w.WriteBit(true); // vps_base_layer_available_flag
w.WriteBits(0, 6); // vps_max_layers_minus1
w.WriteBits(0, 3); // vps_max_sub_layers_minus1
w.WriteBit(true); // vps_temporal_id_nesting_flag
w.WriteBits(0xFFFF, 16);
WriteHevcProfileTierLevel(w, 2, 153);
w.WriteBit(true); // vps_sub_layer_ordering_info_present_flag
w.WriteUe(4);
w.WriteUe(0);
w.WriteUe(0);
w.WriteBits(0, 6); // vps_max_layer_id
w.WriteUe(0); // vps_num_layer_sets_minus1
w.WriteBit(false); // vps_timing_info_present_flag
w.WriteBit(false); // vps_extension_flag
w.WriteTrailingBits();
return Nal([0x40, 0x01], w.ToArray());
}
/// <summary>HEVC SPS for 4:2:0 with the given bit depth, coded in 8×8 units with a conformance window.</summary>
public static byte[] HevcSps(int width = 1920, int height = 1080, int bitDepth = 10, int levelIdc = 153)
{
var w = new BitWriter();
w.WriteBits(0, 4); // sps_video_parameter_set_id
w.WriteBits(0, 3); // sps_max_sub_layers_minus1
w.WriteBit(true); // sps_temporal_id_nesting_flag
WriteHevcProfileTierLevel(w, bitDepth == 10 ? 2 : 1, levelIdc);
w.WriteUe(0); // sps_seq_parameter_set_id
w.WriteUe(1); // chroma_format_idc
var codedW = (width + 7) / 8 * 8;
var codedH = (height + 7) / 8 * 8;
w.WriteUe((uint)codedW);
w.WriteUe((uint)codedH);
var window = codedW != width || codedH != height;
w.WriteBit(window);
if (window)
{
w.WriteUe(0);
w.WriteUe((uint)(codedW - width) / 2);
w.WriteUe(0);
w.WriteUe((uint)(codedH - height) / 2);
}
w.WriteUe((uint)bitDepth - 8);
w.WriteUe((uint)bitDepth - 8);
w.WriteUe(4); // log2_max_pic_order_cnt_lsb_minus4
w.WriteBit(true); // sps_sub_layer_ordering_info_present_flag
w.WriteUe(4);
w.WriteUe(0);
w.WriteUe(0);
w.WriteUe(0); // log2_min_luma_coding_block_size_minus3
w.WriteUe(3); // log2_diff_max_min_luma_coding_block_size
w.WriteUe(0); // log2_min_luma_transform_block_size_minus2
w.WriteUe(3); // log2_diff_max_min_luma_transform_block_size
w.WriteUe(1); // max_transform_hierarchy_depth_inter
w.WriteUe(1); // max_transform_hierarchy_depth_intra
w.WriteBit(false); // scaling_list_enabled_flag
w.WriteBit(true); // amp_enabled_flag
w.WriteBit(true); // sample_adaptive_offset_enabled_flag
w.WriteBit(false); // pcm_enabled_flag
w.WriteUe(0); // num_short_term_ref_pic_sets
w.WriteBit(false); // long_term_ref_pics_present_flag
w.WriteBit(true); // sps_temporal_mvp_enabled_flag
w.WriteBit(true); // strong_intra_smoothing_enabled_flag
w.WriteBit(false); // vui_parameters_present_flag
w.WriteBit(false); // sps_extension_present_flag
w.WriteTrailingBits();
return Nal([0x42, 0x01], w.ToArray());
}
public static byte[] HevcPps()
{
var w = new BitWriter();
w.WriteUe(0); // pps_pic_parameter_set_id
w.WriteUe(0); // pps_seq_parameter_set_id
w.WriteBit(false); // dependent_slice_segments_enabled_flag
w.WriteBit(false); // output_flag_present_flag
w.WriteBits(0, 3); // num_extra_slice_header_bits
w.WriteBit(false); // sign_data_hiding_enabled_flag
w.WriteBit(true); // cabac_init_present_flag
w.WriteUe(0);
w.WriteUe(0);
w.WriteSe(0); // init_qp_minus26
w.WriteBit(false); // constrained_intra_pred_flag
w.WriteBit(false); // transform_skip_enabled_flag
w.WriteBit(false); // cu_qp_delta_enabled_flag
w.WriteSe(0);
w.WriteSe(0);
w.WriteBit(false); // pps_slice_chroma_qp_offsets_present_flag
w.WriteBit(false); // weighted_pred_flag
w.WriteBit(false); // weighted_bipred_flag
w.WriteBit(false); // transquant_bypass_enabled_flag
w.WriteBit(false); // tiles_enabled_flag
w.WriteBit(false); // entropy_coding_sync_enabled_flag
w.WriteBit(true); // pps_loop_filter_across_slices_enabled_flag
w.WriteBit(false); // deblocking_filter_control_present_flag
w.WriteBit(false); // pps_scaling_list_data_present_flag
w.WriteBit(false); // lists_modification_present_flag
w.WriteUe(0); // log2_parallel_merge_level_minus2
w.WriteBit(false); // slice_segment_header_extension_present_flag
w.WriteBit(false); // pps_extension_present_flag
w.WriteTrailingBits();
return Nal([0x44, 0x01], w.ToArray());
}
public static byte[] HevcSlice(bool idr, int payloadBytes, int seed)
{
var type = idr ? HevcNalUnitType.IdrWRadl : HevcNalUnitType.TrailR;
var w = new BitWriter();
w.WriteBit(true); // first_slice_segment_in_pic_flag
w.WriteBytes(Random(payloadBytes, seed));
w.WriteTrailingBits();
return Nal([(byte)((byte)type << 1), 0x01], w.ToArray());
}
/// <summary>AV1 sequence header OBU (with size field) for profile 0 4:2:0.</summary>
public static byte[] Av1SequenceHeaderObu(int width = 1920, int height = 1080, int levelIdx = 8, bool tenBit = false)
{
var w = new BitWriter();
w.WriteBits(0, 3); // seq_profile
w.WriteBit(false); // still_picture
w.WriteBit(false); // reduced_still_picture_header
w.WriteBit(false); // timing_info_present_flag
w.WriteBit(false); // initial_display_delay_present_flag
w.WriteBits(0, 5); // operating_points_cnt_minus_1
w.WriteBits(0, 12); // operating_point_idc[0]
w.WriteBits((ulong)levelIdx, 5);
if (levelIdx > 7) w.WriteBit(false); // seq_tier[0]
const int bits = 16;
w.WriteBits(bits - 1, 4);
w.WriteBits(bits - 1, 4);
w.WriteBits((ulong)width - 1, bits);
w.WriteBits((ulong)height - 1, bits);
w.WriteBit(false); // frame_id_numbers_present_flag
w.WriteBit(false); // use_128x128_superblock
w.WriteBit(true); // enable_filter_intra
w.WriteBit(true); // enable_intra_edge_filter
w.WriteBits(0, 4); // interintra, masked, warped, dual filter
w.WriteBit(true); // enable_order_hint
w.WriteBits(0, 2); // enable_jnt_comp, enable_ref_frame_mvs
w.WriteBit(true); // seq_choose_screen_content_tools
w.WriteBit(true); // seq_choose_integer_mv
w.WriteBits(6, 3); // order_hint_bits_minus_1
w.WriteBits(0, 3); // superres, cdef, restoration
w.WriteBit(tenBit); // high_bitdepth
w.WriteBit(false); // mono_chrome
w.WriteBit(true); // color_description_present_flag
w.WriteBits(1, 8);
w.WriteBits(1, 8);
w.WriteBits(1, 8);
w.WriteBit(false); // color_range
w.WriteBits(0, 2); // chroma_sample_position
w.WriteBit(false); // separate_uv_delta_q
w.WriteBit(false); // film_grain_params_present
w.WriteTrailingBits();
return Obu(Av1ObuType.SequenceHeader, w.ToArray());
}
public static byte[] Av1TemporalDelimiter() => Obu(Av1ObuType.TemporalDelimiter, []);
public static byte[] Av1Frame(int payloadBytes, int seed) => Obu(Av1ObuType.Frame, Random(payloadBytes, seed));
/// <summary>An OBU with obu_has_size_field set.</summary>
public static byte[] Obu(Av1ObuType type, ReadOnlySpan<byte> payload)
{
var w = new BitWriter();
w.WriteBits((ulong)((byte)type << 3 | 0x02), 8);
w.WriteLeb128((ulong)payload.Length);
w.WriteBytes(payload);
return w.ToArray();
}
public static byte[] Concat(params byte[][] parts)
{
var total = 0;
foreach (var p in parts) total += p.Length;
var result = new byte[total];
var pos = 0;
foreach (var p in parts)
{
p.CopyTo(result, pos);
pos += p.Length;
}
return result;
}
public static byte[] Random(int length, int seed)
{
var bytes = new byte[length];
new Random(seed).NextBytes(bytes);
return bytes;
}
private static void WriteHevcProfileTierLevel(BitWriter w, int profileIdc, int levelIdc)
{
w.WriteBits(0, 2); // general_profile_space
w.WriteBit(false); // general_tier_flag
w.WriteBits((ulong)profileIdc, 5);
w.WriteBits(1UL << (31 - profileIdc), 32); // general_profile_compatibility_flag[profileIdc]
w.WriteBits(0x9000_0000_0000UL, 48); // progressive_source + frame_only_constraint
w.WriteBits((ulong)levelIdc, 8);
}
private static byte[] Nal(ReadOnlySpan<byte> header, byte[] rbsp)
{
var escaped = AnnexBParser.AddEmulationPrevention(rbsp);
var nal = new byte[header.Length + escaped.Length];
header.CopyTo(nal);
escaped.CopyTo(nal, header.Length);
return nal;
}
}