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
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:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,410 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
using Chronos.Core.Hashing;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using Chronos.Core.Imaging;
|
||||
|
||||
namespace Chronos.Core.Render.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// A continuous fractal value-noise texture (four octaves, periods 4–32 px, amplitude proportional to the period like
|
||||
/// natural scenes) moved by a per-frame camera offset: exact sub-pixel motion and broadband texture for stabilisation,
|
||||
/// flow and interpolation checks. Unlike per-pixel noise it passes the stabiliser's texture gate, and unlike sinusoids
|
||||
/// it has no periodic ambiguity.
|
||||
/// </summary>
|
||||
public sealed class PatternFrameSource(int width, int height, int frameCount, Func<int, (double X, double Y)>? cameraMotion = null, double intervalSeconds = 10)
|
||||
: IRenderFrameSource
|
||||
{
|
||||
private static readonly DateTime Start = new(2024, 6, 21, 21, 0, 0);
|
||||
|
||||
public int FrameCount { get; } = frameCount > 0 ? frameCount : throw new ArgumentOutOfRangeException(nameof(frameCount));
|
||||
|
||||
public int Width { get; } = width > 0 ? width : throw new ArgumentOutOfRangeException(nameof(width));
|
||||
|
||||
public int Height { get; } = height > 0 ? height : throw new ArgumentOutOfRangeException(nameof(height));
|
||||
|
||||
/// <summary>Content displacement of frame <paramref name="index"/> in full-resolution pixels.</summary>
|
||||
public (double X, double Y) Offset(int index) => cameraMotion?.Invoke(index) ?? (0, 0);
|
||||
|
||||
/// <summary>Regular capture times, 1/250 s exposures.</summary>
|
||||
public SourceFrameInfo[] Metadata()
|
||||
{
|
||||
var result = new SourceFrameInfo[FrameCount];
|
||||
for (var i = 0; i < FrameCount; i++) result[i] = new SourceFrameInfo(Start.AddSeconds(i * intervalSeconds), 1.0 / 250, 10);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The texture at full resolution displaced by (<paramref name="dx"/>, <paramref name="dy"/>).</summary>
|
||||
public ImageBuffer Render(double dx, double dy)
|
||||
{
|
||||
var image = new ImageBuffer(Width, Height, 3, clear: false);
|
||||
var r = image.Plane(0);
|
||||
var g = image.Plane(1);
|
||||
var b = image.Plane(2);
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++)
|
||||
{
|
||||
double u = x - dx, v = y - dy;
|
||||
var value = 0.06 + 0.4 * Texture(u, v);
|
||||
var i = y * Width + x;
|
||||
r[i] = (float)(value * (0.9 + 0.2 * ValueNoise(u / 48, v / 48, 101)));
|
||||
g[i] = (float)value;
|
||||
b[i] = (float)(value * (0.8 + 0.2 * ValueNoise(u / 48, v / 48, 102)));
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
/// <summary>Fractal value noise in [0, 1): octaves of period 4, 8, 16, 32 px weighted by their period.</summary>
|
||||
private static double Texture(double x, double y)
|
||||
{
|
||||
double sum = 0, weights = 0;
|
||||
for (var octave = 0; octave < 4; octave++)
|
||||
{
|
||||
double period = 4 << octave;
|
||||
sum += period * ValueNoise(x / period, y / period, octave);
|
||||
weights += period;
|
||||
}
|
||||
return sum / weights;
|
||||
}
|
||||
|
||||
/// <summary>Hashed lattice values blended with a C1 smoothstep: continuous in x and y.</summary>
|
||||
private static double ValueNoise(double x, double y, int seed)
|
||||
{
|
||||
var xi = (long)double.Floor(x);
|
||||
var yi = (long)double.Floor(y);
|
||||
var fx = x - xi;
|
||||
var fy = y - yi;
|
||||
fx = fx * fx * (3 - 2 * fx);
|
||||
fy = fy * fy * (3 - 2 * fy);
|
||||
var a = Hash(xi, yi, seed);
|
||||
var b = Hash(xi + 1, yi, seed);
|
||||
var c = Hash(xi, yi + 1, seed);
|
||||
var d = Hash(xi + 1, yi + 1, seed);
|
||||
var top = a + (b - a) * fx;
|
||||
return top + (c + (d - c) * fx - top) * fy;
|
||||
}
|
||||
|
||||
/// <summary>Uniform [0, 1) from a SplitMix64 mix of the lattice point (stable across processes).</summary>
|
||||
private static double Hash(long x, long y, int seed)
|
||||
{
|
||||
var z = unchecked((ulong)x * 0x9E3779B97F4A7C15UL ^ (ulong)y * 0xC2B2AE3D27D4EB4FUL ^ (ulong)(uint)seed * 0x165667B19E3779F9UL);
|
||||
z = unchecked((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL);
|
||||
z = unchecked((z ^ (z >> 27)) * 0x94D049BB133111EBUL);
|
||||
z ^= z >> 31;
|
||||
return (z >> 11) * (1.0 / (1UL << 53));
|
||||
}
|
||||
|
||||
public ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, FrameCount);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var (dx, dy) = Offset(index);
|
||||
var frame = Render(dx, dy);
|
||||
if (maxLongEdge <= 0 || int.Max(Width, Height) <= maxLongEdge) return ValueTask.FromResult(frame);
|
||||
using (frame) return ValueTask.FromResult(Resampler.Thumbnail(frame, maxLongEdge));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
using Chronos.Core.Diagnostics.Synthetic;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Core.Video.Managed;
|
||||
|
||||
namespace Chronos.Core.Render.Diagnostics;
|
||||
|
||||
public enum SelfTestOutcome
|
||||
{
|
||||
Passed,
|
||||
Failed,
|
||||
|
||||
/// <summary>The check needs something this machine does not have (e.g. an MP4 encoder).</summary>
|
||||
Skipped,
|
||||
}
|
||||
|
||||
/// <summary>Outcome of one self-test check; <see cref="Detail"/> carries the measured figures or the failure.</summary>
|
||||
public sealed record SelfTestResult(string Id, string Group, string Description, SelfTestOutcome Outcome, string Detail, TimeSpan Elapsed);
|
||||
|
||||
/// <summary>What a check may use: its own empty folder, the encoders, and the run's cancellation.</summary>
|
||||
public sealed record SelfTestContext(string WorkDirectory, IReadOnlyList<IVideoEncoderProvider> Encoders, IReadOnlyList<IVideoEncoderProvider> PlatformEncoders,
|
||||
CancellationToken Cancellation);
|
||||
|
||||
/// <summary>One end-to-end check; it returns a short detail on success and throws on failure.</summary>
|
||||
public sealed record SelfTestCheck(string Id, string Group, string Description, Func<SelfTestContext, Task<string>> Run);
|
||||
|
||||
public sealed record SelfTestOptions
|
||||
{
|
||||
/// <summary>Platform encoders tested in addition to the managed ones (the desktop passes Media Foundation).</summary>
|
||||
public IReadOnlyList<IVideoEncoderProvider> PlatformEncoders { get; init; } = [];
|
||||
|
||||
/// <summary>Parent folder of the run's scratch folder (deleted afterwards); default the system temp folder.</summary>
|
||||
public string? WorkDirectory { get; init; }
|
||||
|
||||
/// <summary>Run only checks whose id starts with one of these prefixes (all when empty).</summary>
|
||||
public IReadOnlyList<string> Filters { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The engine's end-to-end self-test (BRIEF §20.2, §20.4), shared by <c>Chronos.Tools selftest</c> and the desktop
|
||||
/// Settings page: render plans, export resolution and naming, encoder selection, managed codec round trips, renders of
|
||||
/// small synthetic sequences into every managed format (and MP4 when a platform encoder is supplied) with their outputs
|
||||
/// decoded back and compared, the processing modules measured on rendered frames, and cancellation, failure,
|
||||
/// determinism and memory behaviour.
|
||||
/// </summary>
|
||||
public static partial class SelfTest
|
||||
{
|
||||
public static IReadOnlyList<SelfTestCheck> Checks { get; } = [.. PlanChecks(), .. ExportChecks(), .. CodecChecks(), .. RenderChecks(), .. ProcessingChecks(), .. RobustnessChecks()];
|
||||
|
||||
public static async Task<IReadOnlyList<SelfTestResult>> RunAsync(SelfTestOptions? options = null, IProgress<SelfTestResult>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
options ??= new SelfTestOptions();
|
||||
var root = Path.Combine(options.WorkDirectory ?? Path.GetTempPath(), "chronos-selftest-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(root);
|
||||
IVideoEncoderProvider[] encoders = [.. options.PlatformEncoders, new ManagedEncoderProvider()];
|
||||
var results = new List<SelfTestResult>();
|
||||
try
|
||||
{
|
||||
foreach (var check in Checks)
|
||||
{
|
||||
if (options.Filters.Count > 0 && !options.Filters.Any(f => check.Id.StartsWith(f, StringComparison.OrdinalIgnoreCase))) continue;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var directory = Path.Combine(root, check.Id);
|
||||
Directory.CreateDirectory(directory);
|
||||
var context = new SelfTestContext(directory, encoders, options.PlatformEncoders, cancellationToken);
|
||||
var clock = Stopwatch.StartNew();
|
||||
SelfTestOutcome outcome;
|
||||
string detail;
|
||||
try
|
||||
{
|
||||
detail = await check.Run(context).ConfigureAwait(false);
|
||||
outcome = SelfTestOutcome.Passed;
|
||||
}
|
||||
catch (SkipException skip)
|
||||
{
|
||||
(outcome, detail) = (SelfTestOutcome.Skipped, skip.Message);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
(outcome, detail) = (SelfTestOutcome.Failed, ex is FailureException ? ex.Message : $"{ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
var result = new SelfTestResult(check.Id, check.Group, check.Description, outcome, detail, clock.Elapsed);
|
||||
results.Add(result);
|
||||
progress?.Report(result);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Chronos.Core.Diagnostics.Log.Warning("SelfTest", "Could not delete " + root, ex);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private sealed class FailureException(string message) : Exception(message);
|
||||
|
||||
private sealed class SkipException(string message) : Exception(message);
|
||||
|
||||
private static void Require(bool condition, string failure)
|
||||
{
|
||||
if (!condition) throw new FailureException(failure);
|
||||
}
|
||||
|
||||
private static SelfTestCheck Check(string id, string description, Func<SelfTestContext, Task<string>> run) =>
|
||||
new(id, id[..id.IndexOf('.', StringComparison.Ordinal)], description, run);
|
||||
|
||||
private static SelfTestCheck Check(string id, string description, Func<string> run) => Check(id, description, _ => Task.FromResult(run()));
|
||||
|
||||
private static string Invariant(FormattableString text) => text.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>No module and no knee: renders reproduce the source.</summary>
|
||||
private static ProjectSettings Plain { get; } = new() { Exposure = new ExposureSettings { HighlightKnee = null } };
|
||||
|
||||
private static Auto<T> Manual<T>(T value) => new Auto<T>().WithManual(value);
|
||||
|
||||
private static SyntheticFrameSource Synthetic(int frames, Func<SyntheticSequenceOptions, SyntheticSequenceOptions>? configure = null,
|
||||
Func<int, (double X, double Y)>? motion = null)
|
||||
{
|
||||
var options = new SyntheticSequenceOptions { FrameCount = frames, StartEv = 0, EndEv = 1, Seed = 5 };
|
||||
return new SyntheticFrameSource(SyntheticSequence.Create(configure is null ? options : configure(options)), motion);
|
||||
}
|
||||
|
||||
private static RenderInput Input(SyntheticFrameSource source, ProjectSettings? project = null) =>
|
||||
new() { Source = source, Frames = source.Metadata(), Project = project ?? Plain };
|
||||
|
||||
/// <summary>A built-in preset's values at the synthetic frame size (or another size; 0×0 = source).</summary>
|
||||
private static ResolvedExport Preset(string id, int width = 96, int height = 64) =>
|
||||
ExportResolver.FromPreset(ExportPresets.Find(id)!) with { Width = width, Height = height };
|
||||
|
||||
private static RenderTarget Target(SelfTestContext context, ResolvedExport export, string name = "out") =>
|
||||
new(export, Path.Combine(context.WorkDirectory, name + (export.Container == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(export.Codec))));
|
||||
|
||||
private static RenderPipeline Pipeline(SelfTestContext context) => new(context.Encoders);
|
||||
|
||||
/// <summary>Renders to a 16-bit PNG sequence and decodes every picture back (linear light).</summary>
|
||||
private static async Task<List<ImageBuffer>> RenderDecodedAsync(SelfTestContext context, RenderInput input, ResolvedExport? export = null, string name = "decoded")
|
||||
{
|
||||
var target = Target(context, (export ?? Preset("png-sequence")) with { Codec = VideoCodec.PngSequence, BitDepth = 16 }, name);
|
||||
await Pipeline(context).RenderAsync(input, target, cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
var frames = new List<ImageBuffer>();
|
||||
foreach (var file in Directory.GetFiles(target.OutputPath).Order(StringComparer.Ordinal))
|
||||
frames.Add(PngDecoder.DecodeToLinear(await File.ReadAllBytesAsync(file, context.Cancellation).ConfigureAwait(false)));
|
||||
return frames;
|
||||
}
|
||||
|
||||
private static void DisposeAll(IEnumerable<ImageBuffer> frames)
|
||||
{
|
||||
foreach (var f in frames) f.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Peak signal-to-noise ratio of the 8-bit sRGB encodings, optionally inside a margin.</summary>
|
||||
private static double Psnr(ImageBuffer expected, ImageBuffer actual, int margin = 0)
|
||||
{
|
||||
var a = PixelConvert.ToInterleaved8(expected, 3);
|
||||
var b = PixelConvert.ToInterleaved8(actual, 3);
|
||||
double sum = 0;
|
||||
long count = 0;
|
||||
for (var y = margin; y < expected.Height - margin; y++)
|
||||
{
|
||||
for (var i = (y * expected.Width + margin) * 3; i < (y * expected.Width + expected.Width - margin) * 3; i++)
|
||||
{
|
||||
sum += (a[i] - b[i]) * (a[i] - b[i]);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return sum == 0 ? double.PositiveInfinity : 10 * double.Log10(255.0 * 255 / (sum / count));
|
||||
}
|
||||
|
||||
private static double Rms(IReadOnlyList<double> values)
|
||||
{
|
||||
var mean = values.Average();
|
||||
return double.Sqrt(values.Sum(v => (v - mean) * (v - mean)) / values.Count);
|
||||
}
|
||||
|
||||
/// <summary>RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve.</summary>
|
||||
private static double FrameToFrameResidual(IReadOnlyList<double> series, IReadOnlyList<double> truth)
|
||||
{
|
||||
double sum = 0;
|
||||
for (var i = 1; i < series.Count; i++)
|
||||
{
|
||||
var d = series[i] - series[i - 1] - (truth[i] - truth[i - 1]);
|
||||
sum += d * d;
|
||||
}
|
||||
return double.Sqrt(sum / (series.Count - 1));
|
||||
}
|
||||
|
||||
/// <summary>Largest |series − truth − c| with c the mean offset (the measurement constant).</summary>
|
||||
private static double MaxDeviation(IReadOnlyList<double> series, IReadOnlyList<double> truth)
|
||||
{
|
||||
var offset = 0.0;
|
||||
for (var i = 0; i < series.Count; i++) offset += series[i] - truth[i];
|
||||
offset /= series.Count;
|
||||
var max = 0.0;
|
||||
for (var i = 0; i < series.Count; i++) max = double.Max(max, double.Abs(series[i] - truth[i] - offset));
|
||||
return max;
|
||||
}
|
||||
|
||||
/// <summary>Synchronous progress sink (Progress<T> would post to the thread pool).</summary>
|
||||
private sealed class Sink<T>(Action<T> report) : IProgress<T>
|
||||
{
|
||||
public void Report(T value) => report(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
using Chronos.Core.Codecs.Apng;
|
||||
using Chronos.Core.Codecs.Dng;
|
||||
using Chronos.Core.Codecs.Gif;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
using Chronos.Core.Codecs.Tiff;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata.Tiff;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Core.Video.Avi;
|
||||
|
||||
namespace Chronos.Core.Render.Diagnostics;
|
||||
|
||||
/// <summary>Plan, export, encoder-selection and codec checks.</summary>
|
||||
public static partial class SelfTest
|
||||
{
|
||||
private static readonly DateTime Origin = new(2024, 6, 21, 19, 0, 0);
|
||||
|
||||
private static DateTime?[] Regular(int count) => [.. Enumerable.Range(0, count).Select(i => (DateTime?)Origin.AddSeconds(10 * i))];
|
||||
|
||||
private static ProjectSettings Timing(TimingMode mode, double? fit = null, IReadOnlyList<CurvePoint>? curve = null, IReadOnlyList<int>? excluded = null) => new()
|
||||
{
|
||||
Timing = new TimingSettings { Mode = Manual(mode), FitToSeconds = fit, RemapCurve = curve ?? [new(0, 0), new(1, 1)] },
|
||||
ExcludedFrames = excluded ?? [],
|
||||
};
|
||||
|
||||
private static void RequireExact(RenderPlan plan)
|
||||
{
|
||||
Require(plan.Frames.Sum(f => f.Duration90k) == plan.Duration90k, "durations do not add up to the total");
|
||||
Require(plan.Duration90k == RenderPlan.TicksAt(plan.FrameRate, plan.SlotCount), "total differs from the period grid");
|
||||
for (var k = 1; k < plan.Frames.Count; k++)
|
||||
{
|
||||
Require(plan.Frames[k].Start90k == plan.Frames[k - 1].Start90k + plan.Frames[k - 1].Duration90k, "frames are not contiguous");
|
||||
Require(plan.Frames[k].SourcePosition >= plan.Frames[k - 1].SourcePosition, "source positions go backwards");
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<SelfTestCheck> PlanChecks()
|
||||
{
|
||||
yield return Check("plan.constant", "Constant timing: one frame per period, exact durations", () =>
|
||||
{
|
||||
var plan = RenderPlan.Build(Regular(120), Timing(TimingMode.Constant), new Rational(24, 1));
|
||||
RequireExact(plan);
|
||||
Require(plan.Frames.Count == 120 && plan.Frames.All(f => f.Duration90k == 3750 && f.Slots == 1), "not one 1/24 s frame per source frame");
|
||||
return Invariant($"120 frames, {plan.DurationSeconds} s");
|
||||
});
|
||||
yield return Check("plan.ntsc", "29.97 fps durations accumulate without drift", () =>
|
||||
{
|
||||
var plan = RenderPlan.Build(Regular(1001), Timing(TimingMode.Constant), Rational.Fps2997);
|
||||
RequireExact(plan);
|
||||
Require(plan.Duration90k == 1001 * 3003L, Invariant($"total {plan.Duration90k} ticks, expected {1001 * 3003L}"));
|
||||
return Invariant($"1001 frames = {plan.Duration90k} ticks");
|
||||
});
|
||||
yield return Check("plan.excluded", "Excluded frames are skipped", () =>
|
||||
{
|
||||
var plan = RenderPlan.Build(Regular(30), Timing(TimingMode.Constant, excluded: [3, 4, 17]), new Rational(30, 1));
|
||||
RequireExact(plan);
|
||||
Require(plan.Frames.Count == 27 && !plan.Frames.Any(f => f.From is 3 or 4 or 17 || f.To is 3 or 4 or 17), "an excluded frame is used");
|
||||
return "27 of 30 frames";
|
||||
});
|
||||
yield return Check("plan.adaptive.gap", "Adaptive: a doubled interval holds the frame for two periods", () =>
|
||||
{
|
||||
var times = Regular(20);
|
||||
for (var i = 10; i < 20; i++) times[i] = times[i]!.Value.AddSeconds(10);
|
||||
var plan = RenderPlan.Build(times, Timing(TimingMode.Adaptive), new Rational(24, 1));
|
||||
RequireExact(plan);
|
||||
Require(plan.Frames[9].Slots == 2 && plan.Frames[9].IsHeld, Invariant($"frame 9 lasts {plan.Frames[9].Slots} periods"));
|
||||
return "held 2 periods";
|
||||
});
|
||||
yield return Check("plan.adaptive.pause", "Adaptive: a deliberate pause becomes a short cut", () =>
|
||||
{
|
||||
var times = Regular(20);
|
||||
for (var i = 10; i < 20; i++) times[i] = times[i]!.Value.AddHours(2);
|
||||
var plan = RenderPlan.Build(times, Timing(TimingMode.Adaptive), new Rational(24, 1));
|
||||
RequireExact(plan);
|
||||
var seconds = plan.Frames[9].Duration90k / 90000.0;
|
||||
Require(seconds <= 0.25 && plan.IsCutBefore(10), Invariant($"pause shown for {seconds:0.###} s"));
|
||||
return Invariant($"2 h pause shown for {seconds:0.###} s");
|
||||
});
|
||||
yield return Check("plan.interpolated", "Interpolated: a missing capture is synthesised half-way", () =>
|
||||
{
|
||||
var times = Regular(20);
|
||||
for (var i = 10; i < 20; i++) times[i] = times[i]!.Value.AddSeconds(10);
|
||||
var plan = RenderPlan.Build(times, Timing(TimingMode.Interpolated), new Rational(24, 1));
|
||||
RequireExact(plan);
|
||||
Require(plan.Frames.Count == 21 && plan.Frames.Count(f => f.IsInterpolated) == 1 && plan.Frames[10].SourcePosition == 9.5, "no synthesised frame at 9.5");
|
||||
return "21 frames, 9.5 synthesised";
|
||||
});
|
||||
yield return Check("plan.remap.monotonic", "Remapped: positions are monotone even for a non-monotone curve", () =>
|
||||
{
|
||||
var plan = RenderPlan.Build(Regular(90), Timing(TimingMode.Remapped, curve: [new(0, 0), new(0.3, 0.6), new(0.5, 0.4), new(1, 1)]), new Rational(24, 1));
|
||||
RequireExact(plan);
|
||||
Require(plan.Warnings.Contains("Export.Plan.RemapNotMonotonic"), "the curve repair is not reported");
|
||||
return Invariant($"{plan.Frames.Count} frames, {plan.Statistics.InterpolatedFrames} synthesised");
|
||||
});
|
||||
yield return Check("plan.fit", "Fit to duration rescales the plan exactly", () =>
|
||||
{
|
||||
var plan = RenderPlan.Build(Regular(300), Timing(TimingMode.Constant, fit: 5), new Rational(25, 1));
|
||||
RequireExact(plan);
|
||||
Require(plan.SlotCount == 125 && plan.Duration90k == 450_000, Invariant($"{plan.SlotCount} periods, {plan.DurationSeconds} s"));
|
||||
return Invariant($"300 frames in {plan.DurationSeconds} s, speed {plan.Statistics.MaximumSpeed:0.##}×");
|
||||
});
|
||||
}
|
||||
|
||||
private static IEnumerable<SelfTestCheck> ExportChecks()
|
||||
{
|
||||
yield return Check("export.presets", "Every built-in preset resolves to itself and to valid encode settings", () =>
|
||||
{
|
||||
foreach (var preset in ExportPresets.BuiltIn)
|
||||
{
|
||||
var resolved = ExportResolver.Resolve(new ExportSettings { Preset = Manual(preset.Id) });
|
||||
Require(resolved.PresetId == preset.Id && resolved.Warnings.Count == 0, preset.Id + " does not resolve to itself");
|
||||
var settings = resolved.ToEncodeSettings("out", int.Max(2, preset.Width), int.Max(2, preset.Height));
|
||||
Require(settings.GopLength >= 1 && (VideoCodecInfo.IsManaged(preset.Codec) || settings.BitRate > 0), preset.Id + " has invalid encode settings");
|
||||
}
|
||||
return Invariant($"{ExportPresets.BuiltIn.Count} presets");
|
||||
});
|
||||
yield return Check("export.custom", "Editing a value gives Custom; equal values restore the preset", () =>
|
||||
{
|
||||
var edited = ExportResolver.Resolve(new ExportSettings { Preset = Manual("1080p-h264"), Overrides = new ExportOverrides { Height = 1000 } });
|
||||
var restored = ExportResolver.Resolve(new ExportSettings { Preset = Manual("1080p-h264"), Overrides = new ExportOverrides { Height = 1080, Codec = "H.264" } });
|
||||
var other = ExportResolver.Resolve(new ExportSettings { Preset = Manual("1080p-h264"), Overrides = new ExportOverrides { FrameRate = "60" } });
|
||||
Require(edited.IsCustom && restored.PresetId == "1080p-h264" && other.PresetId == "1080p60", "the Custom rule is broken");
|
||||
return "custom ↔ preset";
|
||||
});
|
||||
yield return Check("export.naming", "Name tokens expand and are sanitised", () =>
|
||||
{
|
||||
var name = ExportNaming.Expand("{date} {title} - {preset} {width}x{height} {fps} {codec}", new ExportNameContext
|
||||
{
|
||||
Date = Origin,
|
||||
Title = "Harbour: sunset",
|
||||
PresetName = "4K",
|
||||
Width = 3840,
|
||||
Height = 2160,
|
||||
FrameRate = Rational.Fps2997,
|
||||
Codec = VideoCodec.Hevc,
|
||||
});
|
||||
Require(name.IsValid && name.Name == "2024-06-21 Harbour_ sunset - 4K 3840x2160 29.97 HEVC", "expanded to \"" + name.Name + "\"");
|
||||
return name.Name;
|
||||
});
|
||||
yield return Check("export.collision", "Existing outputs get a numbered suffix", context =>
|
||||
{
|
||||
var nameContext = new ExportNameContext { Date = Origin, PresetName = "GIF", Codec = VideoCodec.Gif, Title = "Clip" };
|
||||
var first = ExportNaming.OutputPath(context.WorkDirectory, "{title}", nameContext);
|
||||
File.WriteAllBytes(first, [0]);
|
||||
var second = ExportNaming.OutputPath(context.WorkDirectory, "{title}", nameContext);
|
||||
Require(Path.GetFileName(first) == "Clip.gif" && Path.GetFileName(second) == "Clip (2).gif", "got " + Path.GetFileName(second));
|
||||
return Task.FromResult(Path.GetFileName(second));
|
||||
});
|
||||
yield return Check("export.estimate", "Size and time estimates are consistent", () =>
|
||||
{
|
||||
var export = ExportResolver.FromPreset(ExportPresets.Find("4k-hevc")!);
|
||||
var workload = new ExportWorkload(720, 720, 24, 3840, 2160, 3840L * 2160, 0, 0, true);
|
||||
var bytes = ExportEstimator.EstimateBytes(export, workload);
|
||||
var expected = export.EffectiveBitRate(3840, 2160) * 24 / 8.0 * 1.01;
|
||||
Require(double.Abs(bytes - expected) <= 1, "video size is not bit rate × duration");
|
||||
var time = ExportEstimator.EstimateTime(export.Codec, workload, ThroughputModel.Default);
|
||||
var calibrated = ThroughputModel.Default.Calibrate(time, time / 2, 1);
|
||||
Require(double.Abs(ExportEstimator.EstimateTime(export.Codec, workload, calibrated).TotalSeconds * 2 - time.TotalSeconds) < 1e-6, "calibration does not rescale");
|
||||
return Invariant($"{bytes / 1e6:0.#} MB, {time.TotalSeconds:0} s");
|
||||
});
|
||||
yield return Check("select.managed", "Managed codecs select the managed encoder on clients and servers", context =>
|
||||
{
|
||||
foreach (var host in new[] { EncoderHost.Client, EncoderHost.Server })
|
||||
{
|
||||
var selection = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("png-sequence")!).ToEncodeSettings("x", 640, 360), context.Encoders, host);
|
||||
Require(selection.IsReady && selection.Provider is Video.Managed.ManagedEncoderProvider, "PNG is not served by the managed encoder");
|
||||
}
|
||||
return Task.FromResult("managed");
|
||||
});
|
||||
yield return Check("select.server", "MP4 on the server needs a render node", context =>
|
||||
{
|
||||
var selection = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("1080p-h264")!).ToEncodeSettings("x.mp4", 1920, 1080), context.Encoders, EncoderHost.Server);
|
||||
Require(selection.Status == EncoderSelectionStatus.NeedsRenderNode && selection.Notices.Any(n => n.Key == EncoderNotices.NeedsRenderNode), "no render-node notice");
|
||||
return Task.FromResult(selection.Notices[0].Key);
|
||||
});
|
||||
yield return Check("select.client", "MP4 on this client: hardware preferred, HEVC falls back to H.264 with a reason", context =>
|
||||
{
|
||||
var hevc = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("4k-hevc")!).ToEncodeSettings("x.mp4", 3840, 2160), context.Encoders, EncoderHost.Client);
|
||||
var hasHevc = context.Encoders.Any(p => p.Capabilities.Any(c => c.Codec == VideoCodec.Hevc));
|
||||
var hasH264 = context.Encoders.Any(p => p.Capabilities.Any(c => c.Codec == VideoCodec.H264));
|
||||
if (!hasHevc) Require(hevc.Notices.Count > 0 && hevc.Notices[0].Key == EncoderNotices.FallbackToH264, "no H.264 fallback notice");
|
||||
if (!hasHevc && !hasH264) Require(hevc.Status == EncoderSelectionStatus.Unavailable, "an MP4 encoder was selected without any");
|
||||
if (hasH264)
|
||||
{
|
||||
var h264 = EncoderSelector.Select(ExportResolver.FromPreset(ExportPresets.Find("1080p-h264")!).ToEncodeSettings("x.mp4", 1920, 1080), context.Encoders, EncoderHost.Client);
|
||||
var hardware = context.Encoders.SelectMany(p => p.Capabilities).Any(c => c.Codec == VideoCodec.H264 && c.Hardware);
|
||||
Require(h264.IsReady && h264.Capability!.Hardware == hardware, "hardware H.264 is not preferred");
|
||||
return Task.FromResult($"{hevc.Status} via {hevc.Capability?.Name ?? "none"}; H.264 via {h264.Capability!.Name}");
|
||||
}
|
||||
return Task.FromResult(string.Join(", ", hevc.Notices.Select(n => n.Key)));
|
||||
});
|
||||
yield return Check("export.setup", "A render setup reports size, encoder, plan and estimates before rendering", context =>
|
||||
{
|
||||
var source = Synthetic(48, o => o with { Width = 480, Height = 320 });
|
||||
var input = Input(source, Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true) } });
|
||||
var setup = Pipeline(context).Setup(input, Target(context, Preset("gif-preview", 480, 270)));
|
||||
var estimate = setup.Estimate();
|
||||
Require(setup.Encoder.IsReady && (setup.Geometry.OutputWidth, setup.Geometry.OutputHeight) == (480, 270) && setup.Plan.Frames.Count == 48
|
||||
&& setup.NeedsPreparation && setup.Geometry.WorkingLongEdge == 480 && estimate.Bytes > 0 && estimate.Time > TimeSpan.Zero, "the setup is inconsistent");
|
||||
return Task.FromResult(Invariant($"{estimate.Bytes / 1024} KiB, {estimate.Time.TotalSeconds:0.#} s estimated"));
|
||||
});
|
||||
yield return Check("select.limits", "Sizes beyond the codec levels are capped with a reason", () =>
|
||||
{
|
||||
var check = CodecLimits.Check(VideoCodec.Hevc, 7680, 4320, 240, 0);
|
||||
Require(!check.Fits && check.SuggestedWidth > 0, "8K at 240 fps should exceed HEVC level 6.2");
|
||||
Require(CodecLimits.Check(VideoCodec.Hevc, check.SuggestedWidth, check.SuggestedHeight, 240, 0).Fits, "the suggested size does not fit");
|
||||
return Invariant($"8K240 → {check.SuggestedWidth}×{check.SuggestedHeight}");
|
||||
});
|
||||
}
|
||||
|
||||
private static ImageBuffer CodecFrame(int seed)
|
||||
{
|
||||
var image = new ImageBuffer(64, 48);
|
||||
for (var y = 0; y < 48; y++)
|
||||
{
|
||||
for (var x = 0; x < 64; x++)
|
||||
{
|
||||
image[0, x, y] = (x + seed * 5) % 64 / 64f;
|
||||
image[1, x, y] = y / 48f * 0.8f;
|
||||
image[2, x, y] = (x * y + seed) % 29 / 28f * 0.6f;
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private static IEnumerable<SelfTestCheck> CodecChecks()
|
||||
{
|
||||
yield return Check("codec.jpeg", "JPEG round trip", () =>
|
||||
{
|
||||
using var frame = CodecFrame(1);
|
||||
using var back = JpegDecoder.DecodeToLinear(JpegEncoder.Encode(frame, new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444 }));
|
||||
var psnr = Psnr(frame, back);
|
||||
Require(psnr > 33, Invariant($"PSNR {psnr:0.#} dB"));
|
||||
return Invariant($"PSNR {psnr:0.#} dB");
|
||||
});
|
||||
yield return Check("codec.png8", "PNG 8-bit round trip is exact", () =>
|
||||
{
|
||||
using var frame = CodecFrame(2);
|
||||
Require(PngDecoder.Decode(PngEncoder.Encode(frame)).Pixels8!.AsSpan().SequenceEqual(PixelConvert.ToInterleaved8(frame, 3)), "pixels differ");
|
||||
return "exact";
|
||||
});
|
||||
yield return Check("codec.png16", "PNG 16-bit round trip is exact", () =>
|
||||
{
|
||||
using var frame = CodecFrame(3);
|
||||
Require(PngDecoder.Decode(PngEncoder.Encode(frame, 16)).Pixels16!.AsSpan().SequenceEqual(PixelConvert.ToInterleaved16(frame, 3)), "pixels differ");
|
||||
return "exact";
|
||||
});
|
||||
yield return Check("codec.tiff16", "TIFF 16-bit round trip is exact", () =>
|
||||
{
|
||||
using var frame = CodecFrame(4);
|
||||
var reader = TiffReader.Open(new MemoryStream(TiffWriter.Write(frame))) ?? throw new InvalidDataException("Not a TIFF");
|
||||
var raster = TiffImageReader.ReadRaster(reader, reader.ReadChain()[0]);
|
||||
Require(raster.Samples is not null && raster.Samples.AsSpan().SequenceEqual(PixelConvert.ToInterleaved16(frame, 3)), "samples differ");
|
||||
return "exact";
|
||||
});
|
||||
yield return Check("codec.dng", "Linear DNG round trip within one 16-bit step", () =>
|
||||
{
|
||||
using var frame = CodecFrame(5);
|
||||
using var back = TiffImageReader.Decode(LinearDngWriter.Write(frame, new LinearDngOptions { TileSize = 64 }));
|
||||
var error = 0.0;
|
||||
for (var i = 0; i < frame.Data.Length; i++) error = double.Max(error, double.Abs(frame.Data[i] - back.Data[i]));
|
||||
Require(error <= 1.0 / 65535 + 1e-7, Invariant($"error {error:E2}"));
|
||||
return Invariant($"max error {error * 65535:0.##} LSB");
|
||||
});
|
||||
yield return Check("codec.gif", "GIF frames and delays round trip", () =>
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
var gif = new GifEncoder(stream, 64, 48);
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
using var f = CodecFrame(i);
|
||||
gif.AddFrame(f, 9000 * (i + 1));
|
||||
}
|
||||
gif.Complete();
|
||||
var animation = GifReader.Decode(stream.ToArray());
|
||||
Require(animation.Frames.Count == 3 && animation.Duration90k == 54000 && animation.LoopCount == 0, "frames or delays differ");
|
||||
using var expected = CodecFrame(2);
|
||||
using var decoded = animation.ToLinear(2);
|
||||
var psnr = Psnr(expected, decoded);
|
||||
Require(psnr > 25, Invariant($"PSNR {psnr:0.#} dB"));
|
||||
return Invariant($"3 frames, 0.6 s, PSNR {psnr:0.#} dB");
|
||||
});
|
||||
yield return Check("codec.apng", "APNG frames and delays round trip exactly", () =>
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
var apng = new ApngEncoder(stream, 64, 48);
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
using var f = CodecFrame(i);
|
||||
apng.AddFrame(f, 6000);
|
||||
}
|
||||
apng.Complete();
|
||||
var animation = ApngReader.Decode(stream.ToArray());
|
||||
using var expected = CodecFrame(1);
|
||||
using var decoded = animation.ToLinear(1);
|
||||
var psnr = Psnr(expected, decoded);
|
||||
Require(animation.Frames.Count == 3 && animation.Duration90k == 18000 && psnr > 60, Invariant($"{animation.Frames.Count} frames, {animation.Duration90k} ticks, PSNR {psnr:0.#} dB"));
|
||||
return "3 frames, exact delays";
|
||||
});
|
||||
yield return Check("codec.avi", "MJPEG AVI headers and indexes", () =>
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
var writer = new AviMjpegWriter(stream, 64, 48, Rational.Fps2997);
|
||||
using var frame = CodecFrame(0);
|
||||
var jpeg = JpegEncoder.Encode(frame);
|
||||
for (var i = 0; i < 5; i++) writer.WriteFrame(jpeg);
|
||||
writer.Complete();
|
||||
var avi = AviReader.Read(stream.ToArray());
|
||||
Require(avi.Frames.Count == 5 && avi.HeaderFrames == 5 && avi.StreamFrames == 5 && avi.IndexEntries == 5 && avi.FrameRate == Rational.Fps2997
|
||||
&& (avi.Width, avi.Height) == (64, 48), "AVI structure differs");
|
||||
return "5 frames, 30000/1001";
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Codecs.Png;
|
||||
using Chronos.Core.Codecs.Tiff;
|
||||
using Chronos.Core.Diagnostics.Synthetic;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Core.Video.Managed;
|
||||
|
||||
namespace Chronos.Core.Render.Diagnostics;
|
||||
|
||||
/// <summary>Renders through the whole pipeline: output formats, processing modules and robustness.</summary>
|
||||
public static partial class SelfTest
|
||||
{
|
||||
private static IEnumerable<SelfTestCheck> RenderChecks()
|
||||
{
|
||||
(string Id, string Preset, int Depth, double MinPsnr)[] formats =
|
||||
[
|
||||
("render.mjpeg", "mjpeg-avi", 8, 35), ("render.jpeg", "jpeg-sequence", 8, 35), ("render.png8", "png-sequence", 8, 60),
|
||||
("render.png16", "png-sequence", 16, 60), ("render.tiff16", "tiff16-sequence", 16, 60), ("render.dng", "dng-sequence", 16, 60),
|
||||
("render.gif", "gif-preview", 8, 25), ("render.apng", "apng", 8, 60),
|
||||
];
|
||||
foreach (var (id, preset, depth, minPsnr) in formats)
|
||||
yield return Check(id, $"Render a synthetic sequence to {preset} ({depth}-bit) and decode it back", context => RenderFormatAsync(context, preset, depth, minPsnr));
|
||||
yield return Check("render.mp4", "Render MP4 with this machine's platform encoders and inspect the file", RenderMp4Async);
|
||||
yield return Check("render.held", "Held frames repeat on constant-rate outputs", async context =>
|
||||
{
|
||||
var source = Synthetic(10, o => o with { TimeShifts = [new SyntheticTimeShift(5, 20)] });
|
||||
var project = Plain with { Timing = new TimingSettings { Mode = Manual(TimingMode.Adaptive) } };
|
||||
var result = await Pipeline(context).RenderAsync(Input(source, project), Target(context, Preset("mjpeg-avi")), cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
var avi = AviReader.Read(await File.ReadAllBytesAsync(result.OutputPath, context.Cancellation).ConfigureAwait(false));
|
||||
Require(result.FrameCount == 10 && avi.Frames.Count == 12, Invariant($"{result.FrameCount} pictures in {avi.Frames.Count} AVI frames"));
|
||||
return "10 pictures, 12 frames";
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<string> RenderFormatAsync(SelfTestContext context, string presetId, int bitDepth, double minPsnr)
|
||||
{
|
||||
var source = Synthetic(12);
|
||||
var export = Preset(presetId) with { BitDepth = bitDepth };
|
||||
var target = Target(context, export);
|
||||
var result = await Pipeline(context).RenderAsync(Input(source), target, cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
var entries = Directory.GetFileSystemEntries(context.WorkDirectory);
|
||||
Require(entries.Length == 1 && entries[0] == target.OutputPath, "the folder holds more than the output");
|
||||
Require(result.Bytes > 0 && result.FrameCount == 12, Invariant($"{result.FrameCount} frames, {result.Bytes} bytes"));
|
||||
|
||||
int count;
|
||||
ImageBuffer decoded;
|
||||
switch (export.Codec)
|
||||
{
|
||||
case VideoCodec.Mjpeg:
|
||||
var avi = AviReader.Read(await File.ReadAllBytesAsync(target.OutputPath, context.Cancellation).ConfigureAwait(false));
|
||||
Require(avi.FrameRate == export.FrameRate && (avi.Width, avi.Height) == (96, 64), "AVI headers differ");
|
||||
count = avi.Frames.Count;
|
||||
decoded = JpegDecoder.DecodeToLinear(avi.Frames[5]);
|
||||
break;
|
||||
case VideoCodec.Gif or VideoCodec.Apng:
|
||||
var bytes = await File.ReadAllBytesAsync(target.OutputPath, context.Cancellation).ConfigureAwait(false);
|
||||
var animation = export.Codec == VideoCodec.Gif ? GifReader.Decode(bytes) : ApngReader.Decode(bytes);
|
||||
var expectedTicks = RenderPlan.TicksAt(export.FrameRate, 12);
|
||||
Require(double.Abs(animation.Duration90k - expectedTicks) <= 900, Invariant($"duration {animation.Duration90k} ticks, expected {expectedTicks}"));
|
||||
count = animation.Frames.Count;
|
||||
decoded = animation.ToLinear(5);
|
||||
break;
|
||||
default:
|
||||
var files = Directory.GetFiles(target.OutputPath).Order(StringComparer.Ordinal).ToArray();
|
||||
var stem = Path.GetFileName(target.OutputPath);
|
||||
Require(files.Select(Path.GetFileName).SequenceEqual(Enumerable.Range(1, files.Length).Select(i => ImageSequenceSession.FrameName(stem, i, VideoCodecInfo.FileExtension(export.Codec)))),
|
||||
"frame files are not numbered 1…n");
|
||||
count = files.Length;
|
||||
var data = await File.ReadAllBytesAsync(files[5], context.Cancellation).ConfigureAwait(false);
|
||||
decoded = export.Codec switch
|
||||
{
|
||||
VideoCodec.JpegSequence => JpegDecoder.DecodeToLinear(data),
|
||||
VideoCodec.PngSequence => PngDecoder.DecodeToLinear(data),
|
||||
_ => TiffImageReader.Decode(data),
|
||||
};
|
||||
break;
|
||||
}
|
||||
using (decoded)
|
||||
using (var expected = source.Sequence.Render(5))
|
||||
{
|
||||
Require(count == 12, Invariant($"{count} pictures in the output"));
|
||||
var psnr = Psnr(expected, decoded);
|
||||
Require(psnr >= minPsnr, Invariant($"PSNR {psnr:0.#} dB < {minPsnr} dB"));
|
||||
return Invariant($"{result.Bytes} bytes, PSNR {(double.IsPositiveInfinity(psnr) ? "∞" : psnr.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture))} dB, {result.EncoderName}");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> RenderMp4Async(SelfTestContext context)
|
||||
{
|
||||
var codecs = context.PlatformEncoders.SelectMany(p => p.Capabilities).Select(c => c.Codec).Where(c => !VideoCodecInfo.IsManaged(c)).Distinct().ToList();
|
||||
if (codecs.Count == 0) throw new SkipException("no MP4 encoder on this machine");
|
||||
var pipeline = new RenderPipeline(context.Encoders);
|
||||
var details = new List<string>();
|
||||
foreach (var codec in codecs)
|
||||
{
|
||||
var export = Preset("1080p-h264", 320, 180) with { Codec = codec, Profile = CodecProfile.Auto, BitRate = 0, BitsPerPixel = 0 };
|
||||
var result = await pipeline.RenderAsync(Input(Synthetic(24)), Target(context, export, codec.ToString()), cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
var report = Mp4Inspector.Inspect(result.OutputPath);
|
||||
Require(report.IsValid, codec + ": " + string.Join("; ", report.Errors));
|
||||
Require(report.Codec == codec && report.FrameCount == 24 && (report.Width, report.Height) == (320, 180), Invariant($"{codec}: {report.Codec} {report.Width}×{report.Height}, {report.FrameCount} frames"));
|
||||
Require(double.Abs(report.Duration.TotalSeconds - result.DurationSeconds) < 0.05, Invariant($"{codec}: duration {report.Duration.TotalSeconds:0.###} s"));
|
||||
details.Add($"{codec} via {result.EncoderName}{(result.Hardware ? " (hardware)" : string.Empty)}");
|
||||
}
|
||||
return string.Join(", ", details);
|
||||
}
|
||||
|
||||
private static IEnumerable<SelfTestCheck> ProcessingChecks()
|
||||
{
|
||||
yield return Check("proc.deflicker", "Deflicker on rendered frames: flicker −60 % or better, ramp kept within 0.05 EV (§20.4)", async context =>
|
||||
{
|
||||
var source = Synthetic(200, o => o with { Seed = 3, StartEv = -2, EndEv = 1, FlickerEv = 0.1 });
|
||||
var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true), DeflickerWindow = Manual(21), HighlightKnee = null } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false);
|
||||
var output = frames.Select(f => FrameStatistics.MeasureLogLuminance(f)).ToArray();
|
||||
DisposeAll(frames);
|
||||
var input = Enumerable.Range(0, 200).Select(i =>
|
||||
{
|
||||
using var f = source.Sequence.Render(i);
|
||||
return FrameStatistics.MeasureLogLuminance(f);
|
||||
}).ToArray();
|
||||
var before = FrameToFrameResidual(input, source.Sequence.SceneEv);
|
||||
var after = FrameToFrameResidual(output, source.Sequence.SceneEv);
|
||||
var ramp = MaxDeviation(output, source.Sequence.SceneEv);
|
||||
Require(1 - after / before >= 0.6, Invariant($"flicker reduced by {1 - after / before:P0} only"));
|
||||
Require(ramp <= 0.05, Invariant($"ramp deviates by {ramp:0.###} EV"));
|
||||
return Invariant($"flicker −{1 - after / before:P0}, ramp within {ramp:0.###} EV");
|
||||
});
|
||||
yield return Check("proc.holygrail", "Holy grail: no output step above 0.3 EV (§20.4)", async context =>
|
||||
{
|
||||
var source = Synthetic(80, o => o with { ExposureSteps = [new SyntheticExposureStep(40, 1.0)], StartEv = 0, EndEv = 0 });
|
||||
var project = Plain with { Exposure = new ExposureSettings { HolyGrail = Manual(true), Deflicker = Manual(true), HighlightKnee = null } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false);
|
||||
var output = frames.Select(f => FrameStatistics.MeasureLogLuminance(f)).ToArray();
|
||||
DisposeAll(frames);
|
||||
var step = output.Zip(output.Skip(1), (a, b) => double.Abs(b - a)).Max();
|
||||
Require(step <= 0.32, Invariant($"largest step {step:0.###} EV"));
|
||||
Require(double.Abs(output[^1] - output[0] + 1) <= 0.1, "the exposure step was not kept");
|
||||
return Invariant($"largest step {step:0.###} EV");
|
||||
});
|
||||
yield return Check("proc.regions", "Region deflicker: land residual at most half of the global correction's", async context =>
|
||||
{
|
||||
var source = Synthetic(48, o => o with { SkyFlickerEv = 0.3, LandFlickerEv = 0.3, StartEv = 0, EndEv = 0 });
|
||||
var land = new float[96 * 64];
|
||||
for (var y = 0; y < 64; y++)
|
||||
{
|
||||
for (var x = 0; x < 96; x++) land[y * 96 + x] = source.Sequence.IsSky(x, y) || y + 0.5 < source.Sequence.HorizonRow(x + 0.5) + 2 ? 0 : 1;
|
||||
}
|
||||
async Task<double> LandResidualAsync(RegionMode mode, string name)
|
||||
{
|
||||
var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true), Regions = Manual(mode), HighlightKnee = null } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project), name: name).ConfigureAwait(false);
|
||||
var series = frames.Select(f => FrameStatistics.MeasureLogLuminance(f, land)).ToArray();
|
||||
DisposeAll(frames);
|
||||
return Rms(series);
|
||||
}
|
||||
var global = await LandResidualAsync(RegionMode.Off, "global").ConfigureAwait(false);
|
||||
var regions = await LandResidualAsync(RegionMode.Horizon, "regions").ConfigureAwait(false);
|
||||
Require(regions <= 0.5 * global, Invariant($"land residual {regions:0.###} EV vs global {global:0.###} EV"));
|
||||
return Invariant($"land residual {regions:0.###} vs {global:0.###} EV");
|
||||
});
|
||||
yield return Check("proc.whitebalance", "White-balance smoothing removes colour jitter", async context =>
|
||||
{
|
||||
var source = Synthetic(48, o => o with { WhiteBalanceJitter = 0.1 });
|
||||
var project = Plain with { Exposure = new ExposureSettings { WhiteBalanceSmoothing = Manual(true), HighlightKnee = null } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false);
|
||||
static double Ratio(ImageBuffer f)
|
||||
{
|
||||
var stats = FrameStatistics.Measure(f);
|
||||
return double.Log2(stats.MeanRed / stats.MeanGreen);
|
||||
}
|
||||
var after = frames.Select(Ratio).ToArray();
|
||||
DisposeAll(frames);
|
||||
var before = Enumerable.Range(0, 48).Select(i =>
|
||||
{
|
||||
using var f = source.Sequence.Render(i);
|
||||
return Ratio(f);
|
||||
}).ToArray();
|
||||
static double Jitter(double[] r) => double.Sqrt(r.Zip(r.Skip(1), (a, b) => (b - a) * (b - a)).Average());
|
||||
Require(Jitter(after) < 0.3 * Jitter(before), Invariant($"R/G jitter {Jitter(before):0.####} → {Jitter(after):0.####}"));
|
||||
return Invariant($"R/G jitter {Jitter(before):0.###} → {Jitter(after):0.####}");
|
||||
});
|
||||
yield return Check("proc.offset", "Exposure offset +1 EV doubles linear values", async context =>
|
||||
{
|
||||
var source = Synthetic(2);
|
||||
var plain = await RenderDecodedAsync(context, Input(source), name: "plain").ConfigureAwait(false);
|
||||
var brighter = await RenderDecodedAsync(context, Input(source, Plain with { Exposure = new ExposureSettings { ExposureOffsetEv = 1, HighlightKnee = null } }), name: "bright")
|
||||
.ConfigureAwait(false);
|
||||
var error = 0.0;
|
||||
for (var i = 0; i < plain[0].Data.Length; i++) error = double.Max(error, double.Abs(2 * plain[0].Data[i] - brighter[0].Data[i]) / (1e-3 + brighter[0].Data[i]));
|
||||
DisposeAll(plain);
|
||||
DisposeAll(brighter);
|
||||
Require(error < 0.01, Invariant($"relative error {error:P2}"));
|
||||
return Invariant($"relative error {error:P3}");
|
||||
});
|
||||
yield return Check("proc.knee", "The highlight knee keeps values below 1 and leaves shadows alone", async context =>
|
||||
{
|
||||
var source = Synthetic(2, o => o with { StartEv = 2, EndEv = 2 });
|
||||
var hard = await RenderDecodedAsync(context, Input(source), name: "hard").ConfigureAwait(false);
|
||||
var knee = await RenderDecodedAsync(context, Input(source, Plain with { Exposure = new ExposureSettings { HighlightKnee = 0.8 } }), name: "knee").ConfigureAwait(false);
|
||||
var clipped = hard[0].Data.ToArray().Count(v => v >= 0.9999f);
|
||||
var top = knee[0].Data.ToArray().Max();
|
||||
var shadows = true;
|
||||
for (var i = 0; i < hard[0].Data.Length; i++)
|
||||
{
|
||||
if (hard[0].Data[i] < 0.5f) shadows &= double.Abs(hard[0].Data[i] - knee[0].Data[i]) < 1e-4;
|
||||
}
|
||||
DisposeAll(hard);
|
||||
DisposeAll(knee);
|
||||
Require(clipped > 0 && top < 0.9999f && shadows, Invariant($"{clipped} clipped samples without knee, max {top:0.####} with it"));
|
||||
return Invariant($"{clipped} clipped samples → max {top:0.###}");
|
||||
});
|
||||
yield return Check("proc.aspect", "A square export crops the centre of a 3:2 frame", async context =>
|
||||
{
|
||||
var source = Synthetic(3);
|
||||
var frames = await RenderDecodedAsync(context, Input(source), Preset("png-sequence", 64, 64)).ConfigureAwait(false);
|
||||
using var reference = source.Sequence.Render(1);
|
||||
using var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(16, 0, 64, 64), OutputWidth = 64, OutputHeight = 64 });
|
||||
var psnr = Psnr(expected, frames[1]);
|
||||
DisposeAll(frames);
|
||||
Require(psnr > 60, Invariant($"PSNR {psnr:0.#} dB"));
|
||||
return "centre 64×64";
|
||||
});
|
||||
yield return Check("proc.crop", "The camera crop selects its region at source size", async context =>
|
||||
{
|
||||
var source = Synthetic(3);
|
||||
var project = Plain with { Camera = new CameraSettings { Crop = [0.5, 0.5, 0.5, 0.5] } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 0, 0)).ConfigureAwait(false);
|
||||
using var reference = source.Sequence.Render(1);
|
||||
using var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = new RectD(48, 32, 48, 32) });
|
||||
var size = (frames[1].Width, frames[1].Height);
|
||||
var psnr = Psnr(expected, frames[1]);
|
||||
DisposeAll(frames);
|
||||
Require(size == (48, 32) && psnr > 60, Invariant($"{size}, PSNR {psnr:0.#} dB"));
|
||||
return "quarter 48×32";
|
||||
});
|
||||
yield return Check("proc.zoom", "Virtual-camera zoom matches a direct crop and doubles the decode size", async context =>
|
||||
{
|
||||
var source = Synthetic(3, o => o with { Width = 480, Height = 320 });
|
||||
var project = Plain with { Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 2, 0), new CameraKey(2, 0.5, 0.5, 2, 0)] } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 96, 64)).ConfigureAwait(false);
|
||||
using var full = source.Sequence.Render(1);
|
||||
using var expected = GeometryStage.Apply(full, new GeometrySettings { Crop = new RectD(120, 80, 240, 160), OutputWidth = 96, OutputHeight = 64 });
|
||||
var psnr = Psnr(expected, frames[1]);
|
||||
DisposeAll(frames);
|
||||
Require(psnr > 28 && source.LargestRenderRequest == 192, Invariant($"PSNR {psnr:0.#} dB, decoded at {source.LargestRenderRequest} px"));
|
||||
return Invariant($"PSNR {psnr:0.#} dB, decode {source.LargestRenderRequest} px");
|
||||
});
|
||||
yield return Check("proc.stabilize", "Stabilisation removes 90 % of the camera shake", async context =>
|
||||
{
|
||||
var random = new Random(11);
|
||||
var shake = Enumerable.Range(0, 24).Select(_ => (X: random.NextDouble() * 6 - 3, Y: random.NextDouble() * 6 - 3)).ToArray();
|
||||
var source = new PatternFrameSource(320, 192, 24, i => shake[i]);
|
||||
var project = Plain with { Motion = new MotionSettings { Stabilize = Manual(true), StabilizeSmoothing = Manual(12.0) } };
|
||||
var input = new RenderInput { Source = source, Frames = source.Metadata(), Project = project };
|
||||
var frames = await RenderDecodedAsync(context, input, Preset("png-sequence", 0, 0)).ConfigureAwait(false);
|
||||
using var stabilizer = new Stabilizer(320, 192);
|
||||
var motions = frames.Select(f => stabilizer.AddFrame(f).Transform).Skip(1).ToArray();
|
||||
DisposeAll(frames);
|
||||
var after = double.Sqrt(motions.Average(m => m.Tx * m.Tx + m.Ty * m.Ty));
|
||||
var before = double.Sqrt(Enumerable.Range(1, 23).Average(k => double.Pow(shake[k].X - shake[k - 1].X, 2) + double.Pow(shake[k].Y - shake[k - 1].Y, 2)));
|
||||
Require(after <= 0.1 * before * 1.2, Invariant($"frame-to-frame shake {before:0.##} → {after:0.###} px"));
|
||||
return Invariant($"shake {before:0.##} → {after:0.###} px");
|
||||
});
|
||||
yield return Check("proc.interpolate", "Synthesised in-betweens follow the motion", async context =>
|
||||
{
|
||||
var source = Synthetic(6, o => o with { StartEv = 0, EndEv = 0 }, i => (2.0 * i, 0));
|
||||
var project = Plain with { Timing = new TimingSettings { Mode = Manual(TimingMode.Interpolated), FrameRate = Manual("15") } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false);
|
||||
var truth = Synthetic(6, o => o with { StartEv = 0, EndEv = 0 }, i => (2.0 * i + 1, 0));
|
||||
using var halfway = await truth.GetFrameAsync(2, 0, DecodePurpose.Render, context.Cancellation).ConfigureAwait(false);
|
||||
var synthesised = Psnr(halfway, frames[5], 8);
|
||||
var nearest = Psnr(halfway, frames[4], 8);
|
||||
var count = frames.Count;
|
||||
DisposeAll(frames);
|
||||
Require(count == 12 && synthesised > 30 && synthesised > nearest + 5, Invariant($"{count} frames, {synthesised:0.#} dB vs nearest {nearest:0.#} dB"));
|
||||
return Invariant($"{synthesised:0.#} dB (nearest whole frame {nearest:0.#} dB)");
|
||||
});
|
||||
yield return Check("proc.motionblur", "Motion blur smears along the motion and leaves still scenes alone", async context =>
|
||||
{
|
||||
var blur = new MotionSettings { MotionBlur = Manual(true), TargetShutterAngle = Manual(360.0) };
|
||||
var moving = Synthetic(6, o => o with { StartEv = 0, EndEv = 0 }, i => (3.0 * i, 0));
|
||||
var sharp = await RenderDecodedAsync(context, Input(moving), name: "sharp").ConfigureAwait(false);
|
||||
var blurred = await RenderDecodedAsync(context, Input(moving, Plain with { Motion = blur }), name: "blurred").ConfigureAwait(false);
|
||||
static double Gradient(ImageBuffer f, int dx, int dy)
|
||||
{
|
||||
double sum = 0;
|
||||
var g = f.Plane(1);
|
||||
for (var y = 8; y < f.Height - 8; y++)
|
||||
{
|
||||
for (var x = 8; x < f.Width - 8; x++) sum += double.Abs(g[y * f.Width + x] - g[(y + dy) * f.Width + x + dx]);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
var horizontal = Gradient(blurred[3], 1, 0) / Gradient(sharp[3], 1, 0);
|
||||
var vertical = Gradient(blurred[3], 0, 1) / Gradient(sharp[3], 0, 1);
|
||||
DisposeAll(sharp);
|
||||
DisposeAll(blurred);
|
||||
var still = Synthetic(4, o => o with { StartEv = 0, EndEv = 0 });
|
||||
var a = await RenderDecodedAsync(context, Input(still), name: "still").ConfigureAwait(false);
|
||||
var b = await RenderDecodedAsync(context, Input(still, Plain with { Motion = blur }), name: "still-blur").ConfigureAwait(false);
|
||||
var stillPsnr = Psnr(a[2], b[2]);
|
||||
DisposeAll(a);
|
||||
DisposeAll(b);
|
||||
Require(horizontal < 0.75 && vertical > horizontal + 0.1 && stillPsnr > 40, Invariant($"gradients ×{horizontal:0.##} along, ×{vertical:0.##} across; still {stillPsnr:0.#} dB"));
|
||||
return Invariant($"gradient ×{horizontal:0.##} along, ×{vertical:0.##} across");
|
||||
});
|
||||
yield return Check("proc.median", "A median stack removes a one-frame transient", async context =>
|
||||
{
|
||||
var source = Synthetic(9, o => o with { StartEv = 0, EndEv = 0 });
|
||||
var project = Plain with { Stack = new StackSettings { Mode = StackSetting.Median, Length = 5 } };
|
||||
var input = Input(source, project) with { Source = new TransientSource(source, 4) };
|
||||
var frames = await RenderDecodedAsync(context, input).ConfigureAwait(false);
|
||||
using var clean = source.Sequence.Render(4);
|
||||
var psnr = Psnr(clean, frames[4]);
|
||||
DisposeAll(frames);
|
||||
Require(psnr > 45, Invariant($"PSNR {psnr:0.#} dB"));
|
||||
return "transient removed";
|
||||
});
|
||||
yield return Check("proc.startrails", "Star-trail luminance never decreases on 99 % of steps (§20.4)", async context =>
|
||||
{
|
||||
var source = Synthetic(16, o => o with { StarField = true, StarCount = 60, StartEv = 0, EndEv = 0 }, i => (1.0 * i, 0.5 * i));
|
||||
var project = Plain with { Stack = new StackSettings { Mode = StackSetting.StarTrails, Length = 0 } };
|
||||
var frames = await RenderDecodedAsync(context, Input(source, project)).ConfigureAwait(false);
|
||||
var luminance = frames.Select(f => FrameStatistics.MeasureLogLuminance(f, default, 0, 0)).ToArray();
|
||||
DisposeAll(frames);
|
||||
var rising = luminance.Zip(luminance.Skip(1), (a, b) => b >= a - 1e-9).Count(r => r);
|
||||
Require(rising >= 0.99 * (luminance.Length - 1), Invariant($"{rising} of {luminance.Length - 1} steps non-decreasing"));
|
||||
return Invariant($"{rising}/{luminance.Length - 1} steps non-decreasing");
|
||||
});
|
||||
yield return Check("proc.cached", "Cached analysis skips the measuring pass and gives the same corrections", async context =>
|
||||
{
|
||||
var source = Synthetic(30, o => o with { FlickerEv = 0.2 });
|
||||
var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true) } };
|
||||
var measured = await RenderPreparation.PrepareAsync(Input(source, project), cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
var decodes = source.Decodes;
|
||||
var cached = await RenderPreparation.PrepareAsync(Input(source, project) with { Analysis = new PrecomputedAnalysis { LogLuminance = measured.MeasuredLogLuminance } },
|
||||
cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
Require(cached.Report.MeasuredFrames == 0 && source.Decodes == decodes && cached.ExposureEv.AsSpan().SequenceEqual(measured.ExposureEv), "the cache was not used as is");
|
||||
return Invariant($"{measured.Report.MeasuredFrames} frames measured once");
|
||||
});
|
||||
}
|
||||
|
||||
private static IEnumerable<SelfTestCheck> RobustnessChecks()
|
||||
{
|
||||
yield return Check("robust.deterministic", "Identical inputs give byte-identical lossless outputs", async context =>
|
||||
{
|
||||
var project = Plain with
|
||||
{
|
||||
Exposure = new ExposureSettings { Deflicker = Manual(true) },
|
||||
Timing = new TimingSettings { Mode = Manual(TimingMode.Interpolated), FrameRate = Manual("15") },
|
||||
};
|
||||
var a = await Pipeline(context).RenderAsync(Input(Synthetic(12, o => o with { FlickerEv = 0.2 }), project), Target(context, Preset("png-sequence"), "a"), cancellationToken: context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
var b = await Pipeline(context).RenderAsync(Input(Synthetic(12, o => o with { FlickerEv = 0.2 }), project), Target(context, Preset("png-sequence"), "b"), cancellationToken: context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
var filesA = Directory.GetFiles(a.OutputPath).Order(StringComparer.Ordinal).ToArray();
|
||||
var filesB = Directory.GetFiles(b.OutputPath).Order(StringComparer.Ordinal).ToArray();
|
||||
Require(filesA.Length == filesB.Length && filesA.Length > 12, "different frame counts");
|
||||
for (var i = 0; i < filesA.Length; i++) Require(File.ReadAllBytes(filesA[i]).AsSpan().SequenceEqual(File.ReadAllBytes(filesB[i])), $"frame {i + 1} differs");
|
||||
return Invariant($"{filesA.Length} frames identical");
|
||||
});
|
||||
foreach (var preset in new[] { "mjpeg-avi", "png-sequence", "gif-preview", "apng" })
|
||||
{
|
||||
yield return Check("robust.cancel." + preset.Split('-')[0], $"Cancelling a {preset} render leaves no file behind (§20.4)", async context =>
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
|
||||
var progress = new Sink<RenderProgress>(p =>
|
||||
{
|
||||
if (p.Stage == RenderStage.Rendering && p.Done == 5) cts.Cancel();
|
||||
});
|
||||
try
|
||||
{
|
||||
await Pipeline(context).RenderAsync(Input(Synthetic(24)), Target(context, Preset(preset)), progress: progress, cancellationToken: cts.Token).ConfigureAwait(false);
|
||||
Require(false, "the render was not cancelled");
|
||||
}
|
||||
catch (OperationCanceledException) when (!context.Cancellation.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
Require(Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "partial output or temporary files remain");
|
||||
return "nothing left";
|
||||
});
|
||||
}
|
||||
yield return Check("robust.source-failure", "A failing frame stops the render once, without output", async context =>
|
||||
{
|
||||
var input = Input(Synthetic(12)) with { Source = new FailingSource(Synthetic(12), 7) };
|
||||
var error = await CaptureAsync(() => Pipeline(context).RenderAsync(input, Target(context, Preset("mjpeg-avi")), cancellationToken: context.Cancellation)).ConfigureAwait(false);
|
||||
Require(error is IOException { Message: "frame 7 is unreadable" }, "unexpected error " + error?.GetType().Name);
|
||||
Require(Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "partial output remains");
|
||||
return "IOException, no output";
|
||||
});
|
||||
yield return Check("robust.encoder-failure", "An encoder failure stops the render once, without output", async context =>
|
||||
{
|
||||
var pipeline = new RenderPipeline([new FaultInjectingProvider(new ManagedEncoderProvider(), 4)]);
|
||||
var error = await CaptureAsync(() => pipeline.RenderAsync(Input(Synthetic(12)), Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation)).ConfigureAwait(false);
|
||||
Require(error is InvalidDataException { Message: FaultInjectingProvider.Message }, "unexpected error " + error?.GetType().Name);
|
||||
Require(Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "partial output remains");
|
||||
return "InvalidDataException, no output";
|
||||
});
|
||||
yield return Check("robust.unobserved", "Failed renders leave no unobserved task exceptions (§20.4)", async context =>
|
||||
{
|
||||
var unobserved = 0;
|
||||
void Handler(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
|
||||
TaskScheduler.UnobservedTaskException += Handler;
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var pipeline = new RenderPipeline([new FaultInjectingProvider(new ManagedEncoderProvider(), 2 + i)]);
|
||||
await CaptureAsync(() => pipeline.RenderAsync(Input(Synthetic(12)), Target(context, Preset("gif-preview")), cancellationToken: context.Cancellation)).ConfigureAwait(false);
|
||||
var input = Input(Synthetic(12)) with { Source = new FailingSource(Synthetic(12), 3 + i) };
|
||||
await CaptureAsync(() => Pipeline(context).RenderAsync(input, Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation)).ConfigureAwait(false);
|
||||
}
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
}
|
||||
finally
|
||||
{
|
||||
TaskScheduler.UnobservedTaskException -= Handler;
|
||||
}
|
||||
Require(unobserved == 0, Invariant($"{unobserved} unobserved exceptions"));
|
||||
return "none";
|
||||
});
|
||||
yield return Check("robust.memory", "Peak memory does not depend on the sequence length (§20.4)", async context =>
|
||||
{
|
||||
async Task<long> PeakAsync(int frames, string name)
|
||||
{
|
||||
long peak = 0;
|
||||
var progress = new Sink<RenderProgress>(p =>
|
||||
{
|
||||
if (p.Stage == RenderStage.Rendering && p.Done % 8 == 0) peak = long.Max(peak, GC.GetTotalMemory(forceFullCollection: true));
|
||||
});
|
||||
var project = Plain with { Exposure = new ExposureSettings { Deflicker = Manual(true) } };
|
||||
await Pipeline(context).RenderAsync(Input(Synthetic(frames), project), Target(context, Preset("mjpeg-avi"), name), progress: progress,
|
||||
cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
return peak;
|
||||
}
|
||||
await PeakAsync(16, "warm-up").ConfigureAwait(false);
|
||||
var small = await PeakAsync(48, "short").ConfigureAwait(false);
|
||||
var large = await PeakAsync(192, "long").ConfigureAwait(false);
|
||||
Require(large - small < 2 << 20, Invariant($"live heap grew by {(large - small) / 1024} KiB from 48 to 192 frames"));
|
||||
return Invariant($"48 frames {small / 1024} KiB, 192 frames {large / 1024} KiB");
|
||||
});
|
||||
yield return Check("robust.batch", "A batch renders every target and reports the ones that cannot run", async context =>
|
||||
{
|
||||
var server = new RenderPipeline([new ManagedEncoderProvider()], EncoderHost.Server);
|
||||
var results = await server.RenderBatchAsync(Input(Synthetic(12)),
|
||||
[Target(context, Preset("png-sequence"), "png"), Target(context, Preset("1080p-h264"), "h264"), Target(context, Preset("apng"), "apng")],
|
||||
cancellationToken: context.Cancellation).ConfigureAwait(false);
|
||||
Require(results.Count == 3 && results[0].Succeeded && results[2].Succeeded, "a renderable target failed");
|
||||
Require(results[1].Error is RenderException { ReasonKey: EncoderNotices.NeedsRenderNode }, "the MP4 target was not reported as needing a render node");
|
||||
return "2 rendered, 1 needs a render node";
|
||||
});
|
||||
yield return Check("robust.progress", "Progress counts frames, estimates the end and delivers previews", async context =>
|
||||
{
|
||||
var reports = new List<RenderProgress>();
|
||||
var options = new RenderOptions { PreviewInterval = 4, PreviewLongEdge = 48 };
|
||||
await Pipeline(context).RenderAsync(Input(Synthetic(12)), Target(context, Preset("jpeg-sequence")), options, new Sink<RenderProgress>(reports.Add), context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
var rendering = reports.Where(r => r.Stage == RenderStage.Rendering).ToList();
|
||||
var previews = rendering.Where(r => r.Preview is not null).ToList();
|
||||
var ok = rendering.Select(r => r.Done).SequenceEqual(Enumerable.Range(1, 12)) && rendering.All(r => r.Remaining >= TimeSpan.Zero)
|
||||
&& previews.Count == 3 && previews.All(r => r.Preview!.Width == 48) && reports[^1].Stage == RenderStage.Finishing;
|
||||
foreach (var r in previews) r.Preview!.Dispose();
|
||||
Require(ok, Invariant($"{rendering.Count} reports, {previews.Count} previews"));
|
||||
return Invariant($"{rendering.Count} reports, {previews.Count} previews");
|
||||
});
|
||||
yield return Check("robust.excluded", "Excluding every frame is reported, not rendered", async context =>
|
||||
{
|
||||
var project = Plain with { ExcludedFrames = [.. Enumerable.Range(0, 6)] };
|
||||
var error = await CaptureAsync(() => Pipeline(context).RenderAsync(Input(Synthetic(6), project), Target(context, Preset("png-sequence")), cancellationToken: context.Cancellation))
|
||||
.ConfigureAwait(false);
|
||||
Require(error is RenderException { ReasonKey: "Export.Render.NoFrames" } && Directory.GetFileSystemEntries(context.WorkDirectory).Length == 0, "no NoFrames error");
|
||||
return "Export.Render.NoFrames";
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The exception <paramref name="render"/> throws, or null.</summary>
|
||||
private static async Task<Exception?> CaptureAsync(Func<Task> render)
|
||||
{
|
||||
try
|
||||
{
|
||||
await render().ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
return ex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Throws an <see cref="IOException"/> for one frame, as an unreadable file would.</summary>
|
||||
private sealed class FailingSource(IRenderFrameSource inner, int failAt) : IRenderFrameSource
|
||||
{
|
||||
public int FrameCount => inner.FrameCount;
|
||||
public int Width => inner.Width;
|
||||
public int Height => inner.Height;
|
||||
|
||||
public ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) =>
|
||||
index == failAt ? throw new IOException($"frame {index} is unreadable") : inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Adds a bright square to one frame (a passing aircraft light).</summary>
|
||||
private sealed class TransientSource(IRenderFrameSource inner, int frame) : IRenderFrameSource
|
||||
{
|
||||
public int FrameCount => inner.FrameCount;
|
||||
public int Width => inner.Width;
|
||||
public int Height => inner.Height;
|
||||
|
||||
public async ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await inner.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken).ConfigureAwait(false);
|
||||
if (index != frame) return image;
|
||||
for (var c = 0; c < image.Channels; c++)
|
||||
{
|
||||
for (var y = image.Height / 3; y < image.Height / 3 + 10; y++)
|
||||
{
|
||||
for (var x = image.Width / 2; x < image.Width / 2 + 10; x++) image[c, x, y] = 1;
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wraps a real provider and fails its sessions at a given frame (fault injection).</summary>
|
||||
private sealed class FaultInjectingProvider(IVideoEncoderProvider inner, int failAt) : IVideoEncoderProvider
|
||||
{
|
||||
public const string Message = "injected encoder fault";
|
||||
|
||||
public string Name => inner.Name;
|
||||
public IReadOnlyList<EncoderCapability> Capabilities => inner.Capabilities;
|
||||
public bool CanEncode(EncodeSettings settings) => inner.CanEncode(settings);
|
||||
public IVideoEncoderSession Open(EncodeSettings settings) => new Session(inner.Open(settings), failAt);
|
||||
|
||||
private sealed class Session(IVideoEncoderSession inner, int failAt) : IVideoEncoderSession
|
||||
{
|
||||
private int _frames;
|
||||
|
||||
public string EncoderName => inner.EncoderName;
|
||||
public bool IsHardware => inner.IsHardware;
|
||||
|
||||
public void WriteFrame(ImageBuffer frame, long duration90k)
|
||||
{
|
||||
if (_frames++ == failAt) throw new InvalidDataException(Message);
|
||||
inner.WriteFrame(frame, duration90k);
|
||||
}
|
||||
|
||||
public void Complete() => inner.Complete();
|
||||
public void Dispose() => inner.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using Chronos.Core.Diagnostics.Synthetic;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
|
||||
namespace Chronos.Core.Render.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IRenderFrameSource"/> over a <see cref="SyntheticSequence"/> (self-test and tests). An optional camera
|
||||
/// motion translates each frame's content by a per-frame offset in pixels (pans, shake). Frames are rendered on demand,
|
||||
/// so memory does not depend on the sequence length.
|
||||
/// </summary>
|
||||
public sealed class SyntheticFrameSource(SyntheticSequence sequence, Func<int, (double X, double Y)>? cameraMotion = null) : IRenderFrameSource
|
||||
{
|
||||
private int _decodes;
|
||||
private int _largestRequest;
|
||||
|
||||
public SyntheticSequence Sequence { get; } = sequence ?? throw new ArgumentNullException(nameof(sequence));
|
||||
|
||||
public int FrameCount => Sequence.Count;
|
||||
|
||||
public int Width => Sequence.Options.Width;
|
||||
|
||||
public int Height => Sequence.Options.Height;
|
||||
|
||||
/// <summary>Frames produced so far.</summary>
|
||||
public int Decodes => Volatile.Read(ref _decodes);
|
||||
|
||||
/// <summary>Largest long edge requested for rendering (0 = full size).</summary>
|
||||
public int LargestRenderRequest => Volatile.Read(ref _largestRequest);
|
||||
|
||||
/// <summary>Capture metadata of the sequence's frames.</summary>
|
||||
public SourceFrameInfo[] Metadata() => SourceFrameInfo.From(Sequence.Frames);
|
||||
|
||||
public ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Interlocked.Increment(ref _decodes);
|
||||
if (purpose == DecodePurpose.Render) InterlockedMax(ref _largestRequest, maxLongEdge);
|
||||
var frame = Sequence.Render(index);
|
||||
try
|
||||
{
|
||||
if (cameraMotion is not null)
|
||||
{
|
||||
var (dx, dy) = cameraMotion(index);
|
||||
var moved = new ImageBuffer(frame.Width, frame.Height, frame.Channels, clear: false);
|
||||
try
|
||||
{
|
||||
GeometryStage.Warp(frame, moved, Affine2D.Translation(-dx, -dy), BorderMode.Clamp, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
moved.Dispose();
|
||||
throw;
|
||||
}
|
||||
frame.Dispose();
|
||||
frame = moved;
|
||||
}
|
||||
if (maxLongEdge > 0 && int.Max(frame.Width, frame.Height) > maxLongEdge)
|
||||
{
|
||||
var small = Resampler.Thumbnail(frame, maxLongEdge);
|
||||
frame.Dispose();
|
||||
frame = small;
|
||||
}
|
||||
return ValueTask.FromResult(frame);
|
||||
}
|
||||
catch
|
||||
{
|
||||
frame.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static void InterlockedMax(ref int target, int value)
|
||||
{
|
||||
var current = Volatile.Read(ref target);
|
||||
while (value > current)
|
||||
{
|
||||
var seen = Interlocked.CompareExchange(ref target, value, current);
|
||||
if (seen == current) return;
|
||||
current = seen;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Motion;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>Least-recently-used cache of prepared (corrected and warped) frames by source index; owns its buffers.</summary>
|
||||
internal sealed class PreparedFrameCache(int capacity) : IDisposable
|
||||
{
|
||||
private readonly List<(int Index, ImageBuffer Frame)> _entries = new(capacity + 1);
|
||||
|
||||
public bool TryGet(int index, out ImageBuffer frame)
|
||||
{
|
||||
for (var i = 0; i < _entries.Count; i++)
|
||||
{
|
||||
if (_entries[i].Index != index) continue;
|
||||
var entry = _entries[i];
|
||||
_entries.RemoveAt(i);
|
||||
_entries.Add(entry);
|
||||
frame = entry.Frame;
|
||||
return true;
|
||||
}
|
||||
frame = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Add(int index, ImageBuffer frame)
|
||||
{
|
||||
_entries.Add((index, frame));
|
||||
while (_entries.Count > capacity)
|
||||
{
|
||||
_entries[0].Frame.Dispose();
|
||||
_entries.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var (_, frame) in _entries) frame.Dispose();
|
||||
_entries.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Flow fields between two source frames (forward, and backward when synthesis needed it).</summary>
|
||||
internal sealed record FlowPair(MotionField Forward, MotionField? Backward);
|
||||
|
||||
/// <summary>Least-recently-used cache of flow fields by source pair; owns its fields.</summary>
|
||||
internal sealed class FlowCache(int capacity) : IDisposable
|
||||
{
|
||||
private readonly List<(int From, int To, FlowPair Flows)> _entries = new(capacity + 1);
|
||||
|
||||
public bool TryGet(int from, int to, bool needBackward, out FlowPair flows)
|
||||
{
|
||||
for (var i = 0; i < _entries.Count; i++)
|
||||
{
|
||||
var entry = _entries[i];
|
||||
if (entry.From != from || entry.To != to) continue;
|
||||
if (needBackward && entry.Flows.Backward is null) break;
|
||||
_entries.RemoveAt(i);
|
||||
_entries.Add(entry);
|
||||
flows = entry.Flows;
|
||||
return true;
|
||||
}
|
||||
flows = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Adds (or replaces) the flows of a pair.</summary>
|
||||
public void Add(int from, int to, FlowPair flows)
|
||||
{
|
||||
var existing = _entries.FindIndex(e => e.From == from && e.To == to);
|
||||
if (existing >= 0)
|
||||
{
|
||||
Release(_entries[existing].Flows);
|
||||
_entries.RemoveAt(existing);
|
||||
}
|
||||
_entries.Add((from, to, flows));
|
||||
while (_entries.Count > capacity)
|
||||
{
|
||||
Release(_entries[0].Flows);
|
||||
_entries.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var entry in _entries) Release(entry.Flows);
|
||||
_entries.Clear();
|
||||
}
|
||||
|
||||
private static void Release(FlowPair flows)
|
||||
{
|
||||
flows.Forward.Dispose();
|
||||
flows.Backward?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>
|
||||
/// Decoded source frames of a render by index. The application backs it with the image decoders and the sliding
|
||||
/// <c>FrameWindow</c> (read-ahead, disk spill); tests and the self-test use synthetic sources. Sequential index order is
|
||||
/// the common access pattern; neighbours may be requested again for flow and interpolation.
|
||||
/// </summary>
|
||||
public interface IRenderFrameSource
|
||||
{
|
||||
int FrameCount { get; }
|
||||
|
||||
/// <summary>Full-resolution width after orientation.</summary>
|
||||
int Width { get; }
|
||||
|
||||
/// <summary>Full-resolution height after orientation.</summary>
|
||||
int Height { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Frame <paramref name="index"/> in linear light, its long edge at most <paramref name="maxLongEdge"/> (0 = full size).
|
||||
/// A source may return a smaller frame of the same aspect (e.g. an embedded preview). The caller owns the buffer.
|
||||
/// </summary>
|
||||
ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Capture metadata of one source frame used by the plan and the preparation.</summary>
|
||||
/// <param name="CapturedAt">Camera clock (clock-corrected when available); null when unknown.</param>
|
||||
/// <param name="ExposureTime">Shutter time in seconds (real shutter angle for motion blur).</param>
|
||||
/// <param name="ExposureValue">EV at ISO 100 (holy-grail steps).</param>
|
||||
public readonly record struct SourceFrameInfo(DateTime? CapturedAt, double? ExposureTime, double? ExposureValue)
|
||||
{
|
||||
/// <summary>Metadata of archived frames, optionally with clock-corrected times (<c>LightAnalysisReport.AdjustedTimes</c>).</summary>
|
||||
public static SourceFrameInfo[] From(IReadOnlyList<Frame> frames, IReadOnlyList<DateTime?>? adjustedTimes = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
if (adjustedTimes is not null && adjustedTimes.Count != frames.Count) throw new ArgumentException("One time per frame is required.", nameof(adjustedTimes));
|
||||
var result = new SourceFrameInfo[frames.Count];
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
var f = frames[i];
|
||||
result[i] = new SourceFrameInfo(adjustedTimes is null ? f.CapturedAt : adjustedTimes[i], f.ExposureTime, f.ExposureValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>
|
||||
/// Output size, decode size and per-frame warp of a render. <see cref="CameraSettings.Crop"/> is a normalised
|
||||
/// [x, y, width, height] rectangle of the camera view; the output aspect is the export's when it fixes both dimensions,
|
||||
/// otherwise the camera aspect (source = frame aspect). Virtual-camera keyframes are keyed to source frame positions, so
|
||||
/// they stay attached to the content when timing, frame rate or fitting change. The stabiliser correction, the camera
|
||||
/// pose (zoomed by the stabilisation zoom) and the crop become one output→source map, resampled once.
|
||||
/// </summary>
|
||||
public sealed class RenderGeometry
|
||||
{
|
||||
private static readonly CameraState Neutral = new(0.5, 0.5, 1, 0);
|
||||
private readonly VirtualCamera? _camera;
|
||||
private readonly RectD _crop;
|
||||
private readonly double _offsetX;
|
||||
private readonly double _offsetY;
|
||||
private readonly double _stabilizationZoom;
|
||||
private readonly double _fittedWidth;
|
||||
private readonly double _fittedHeight;
|
||||
private readonly double _maxZoom;
|
||||
private readonly int _maxWorkingLongEdge;
|
||||
|
||||
private RenderGeometry(VirtualCamera? camera, RectD crop, double offsetX, double offsetY, double stabilizationZoom, int sourceWidth, int sourceHeight,
|
||||
int outputWidth, int outputHeight, double fittedWidth, double fittedHeight, double maxZoom, int maxWorkingLongEdge, IReadOnlyList<RenderWarning> warnings)
|
||||
{
|
||||
_camera = camera;
|
||||
_crop = crop;
|
||||
_offsetX = offsetX;
|
||||
_offsetY = offsetY;
|
||||
_stabilizationZoom = stabilizationZoom;
|
||||
SourceWidth = sourceWidth;
|
||||
SourceHeight = sourceHeight;
|
||||
OutputWidth = outputWidth;
|
||||
OutputHeight = outputHeight;
|
||||
_fittedWidth = fittedWidth;
|
||||
_fittedHeight = fittedHeight;
|
||||
_maxZoom = maxZoom;
|
||||
_maxWorkingLongEdge = maxWorkingLongEdge;
|
||||
Warnings = warnings;
|
||||
}
|
||||
|
||||
public int SourceWidth { get; }
|
||||
public int SourceHeight { get; }
|
||||
public int OutputWidth { get; }
|
||||
public int OutputHeight { get; }
|
||||
|
||||
/// <summary>Remarks about ignored camera values.</summary>
|
||||
public IReadOnlyList<RenderWarning> Warnings { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Long edge to decode source frames at: enough that the most zoomed-in view still has one source pixel per output
|
||||
/// pixel, never more than the source, capped by <see cref="RenderOptions.MaxWorkingLongEdge"/>.
|
||||
/// </summary>
|
||||
public int WorkingLongEdge
|
||||
{
|
||||
get
|
||||
{
|
||||
var needed = double.Max(OutputWidth / _fittedWidth, OutputHeight / _fittedHeight) * _maxZoom;
|
||||
var edge = (int)double.Ceiling(int.Max(SourceWidth, SourceHeight) * double.Min(1, needed));
|
||||
edge = int.Clamp(edge, int.Min(16, int.Max(SourceWidth, SourceHeight)), int.Max(SourceWidth, SourceHeight));
|
||||
return _maxWorkingLongEdge > 0 ? int.Min(edge, _maxWorkingLongEdge) : edge;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plans the geometry of <paramref name="export"/> for a source of the given full-resolution size.</summary>
|
||||
/// <param name="stabilizationZoom">Zoom that hides stabilisation borders (<see cref="RenderCorrections.StabilizationZoom"/>).</param>
|
||||
/// <param name="maxWorkingLongEdge">Decode-size cap (0 = none); it also caps source-sized outputs.</param>
|
||||
public static RenderGeometry Create(CameraSettings camera, ResolvedExport export, int sourceWidth, int sourceHeight, double stabilizationZoom = 1, int maxWorkingLongEdge = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(camera);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
|
||||
var warnings = new List<RenderWarning>();
|
||||
var crop = NormalisedCrop(camera.Crop, warnings);
|
||||
if (!AspectRatio.TryParse(camera.Aspect.Resolve("source"), out var aspect))
|
||||
{
|
||||
warnings.Add(new RenderWarning("Export.Render.AspectIgnored", camera.Aspect.Resolve(string.Empty)));
|
||||
aspect = AspectRatio.Source;
|
||||
}
|
||||
var fixedSize = export.Width > 0 && export.Height > 0;
|
||||
var ratio = fixedSize ? export.Width / (double)export.Height : aspect.Resolve(sourceWidth, sourceHeight);
|
||||
if (fixedSize && !aspect.IsSource && double.Abs(aspect.Resolve(sourceWidth, sourceHeight) / ratio - 1) > 0.01)
|
||||
warnings.Add(new RenderWarning("Export.Render.AspectFromPreset", aspect.ToString(), string.Create(CultureInfo.InvariantCulture, $"{export.Width}:{export.Height}")));
|
||||
var cropPixels = new RectD(crop.X * sourceWidth, crop.Y * sourceHeight, crop.Width * sourceWidth, crop.Height * sourceHeight);
|
||||
var fitted = AspectRatio.FitCrop(cropPixels, ratio, camera.OffsetX, camera.OffsetY);
|
||||
|
||||
int width, height;
|
||||
if (fixedSize) (width, height) = (export.Width, export.Height);
|
||||
else if (export.Width > 0) (width, height) = (export.Width, (int)double.Round(export.Width / ratio));
|
||||
else if (export.Height > 0) (width, height) = ((int)double.Round(export.Height * ratio), export.Height);
|
||||
else
|
||||
{
|
||||
var scale = maxWorkingLongEdge > 0 ? double.Min(1, maxWorkingLongEdge / double.Max(fitted.Width, fitted.Height)) : 1;
|
||||
(width, height) = ((int)double.Round(fitted.Width * scale), (int)double.Round(fitted.Height * scale));
|
||||
}
|
||||
if (!VideoCodecInfo.IsManaged(export.Codec))
|
||||
{
|
||||
width &= ~1;
|
||||
height &= ~1;
|
||||
}
|
||||
width = int.Max(VideoCodecInfo.IsManaged(export.Codec) ? 1 : 2, width);
|
||||
height = int.Max(VideoCodecInfo.IsManaged(export.Codec) ? 1 : 2, height);
|
||||
|
||||
var cameraPath = Camera(camera.Keyframes, warnings);
|
||||
var maxZoom = (cameraPath?.Keyframes.Max(k => k.Zoom) ?? 1) * stabilizationZoom;
|
||||
return new RenderGeometry(cameraPath, crop, camera.OffsetX, camera.OffsetY, stabilizationZoom, sourceWidth, sourceHeight, width, height,
|
||||
fitted.Width, fitted.Height, maxZoom, maxWorkingLongEdge, warnings);
|
||||
}
|
||||
|
||||
/// <summary>The same geometry rendering into a different output size (e.g. capped by the encoder).</summary>
|
||||
public RenderGeometry WithOutputSize(int width, int height) => width == OutputWidth && height == OutputHeight
|
||||
? this
|
||||
: new RenderGeometry(_camera, _crop, _offsetX, _offsetY, _stabilizationZoom, SourceWidth, SourceHeight, width, height, _fittedWidth, _fittedHeight,
|
||||
_maxZoom, _maxWorkingLongEdge, Warnings);
|
||||
|
||||
/// <summary>Camera pose at a (fractional) source position, including the stabilisation zoom.</summary>
|
||||
public CameraState PoseAt(double sourcePosition)
|
||||
{
|
||||
var pose = _camera?.Evaluate(sourcePosition) ?? Neutral;
|
||||
return pose with { Zoom = pose.Zoom * _stabilizationZoom };
|
||||
}
|
||||
|
||||
/// <summary>Geometry of one decoded frame of <paramref name="frameWidth"/>×<paramref name="frameHeight"/> pixels.</summary>
|
||||
/// <param name="stabilization">The frame's stabiliser correction at this frame size (source → stabilised).</param>
|
||||
public GeometrySettings For(int frameWidth, int frameHeight, double sourcePosition, Affine2D stabilization)
|
||||
{
|
||||
var view = VirtualCamera.ViewToSource(PoseAt(sourcePosition), frameWidth, frameHeight);
|
||||
return new GeometrySettings
|
||||
{
|
||||
Crop = new RectD(_crop.X * frameWidth, _crop.Y * frameHeight, _crop.Width * frameWidth, _crop.Height * frameHeight),
|
||||
Aspect = AspectRatio.Source,
|
||||
OffsetX = _offsetX,
|
||||
OffsetY = _offsetY,
|
||||
OutputWidth = OutputWidth,
|
||||
OutputHeight = OutputHeight,
|
||||
Warp = stabilization.IsIdentity() ? view : stabilization.Invert() * view,
|
||||
Border = BorderMode.Clamp,
|
||||
};
|
||||
}
|
||||
|
||||
private static RectD NormalisedCrop(double[]? crop, List<RenderWarning> warnings)
|
||||
{
|
||||
var full = new RectD(0, 0, 1, 1);
|
||||
if (crop is null) return full;
|
||||
if (crop.Length != 4 || !crop.All(double.IsFinite))
|
||||
{
|
||||
warnings.Add(new RenderWarning("Export.Render.CropIgnored"));
|
||||
return full;
|
||||
}
|
||||
var x = double.Clamp(crop[0], 0, 1);
|
||||
var y = double.Clamp(crop[1], 0, 1);
|
||||
var w = double.Min(crop[2], 1 - x);
|
||||
var h = double.Min(crop[3], 1 - y);
|
||||
if (w <= 1e-3 || h <= 1e-3)
|
||||
{
|
||||
warnings.Add(new RenderWarning("Export.Render.CropIgnored"));
|
||||
return full;
|
||||
}
|
||||
return new RectD(x, y, w, h);
|
||||
}
|
||||
|
||||
private static VirtualCamera? Camera(IReadOnlyList<CameraKey> keys, List<RenderWarning> warnings)
|
||||
{
|
||||
if (keys.Count == 0) return null;
|
||||
var frames = new Dictionary<int, CameraKeyframe>();
|
||||
foreach (var k in keys)
|
||||
{
|
||||
if (!double.IsFinite(k.CenterX + k.CenterY + k.Zoom + k.Rotation))
|
||||
{
|
||||
warnings.Add(new RenderWarning("Export.Render.KeyframeIgnored", k.Frame.ToString(CultureInfo.InvariantCulture)));
|
||||
continue;
|
||||
}
|
||||
frames[k.Frame] = new CameraKeyframe(k.Frame, k.CenterX, k.CenterY, double.Max(1, k.Zoom), k.Rotation) { Easing = Easing(k.Easing, warnings) };
|
||||
}
|
||||
return frames.Count == 0 ? null : new VirtualCamera(frames.Values);
|
||||
}
|
||||
|
||||
/// <summary>"Linear", "EaseIn", "EaseOut", "EaseInOut" or "x1,y1,x2,y2" control points (CSS cubic-bezier).</summary>
|
||||
private static BezierEasing Easing(string? text, List<RenderWarning> warnings)
|
||||
{
|
||||
switch (text?.Trim().ToLowerInvariant())
|
||||
{
|
||||
case null or "" or "easeinout": return BezierEasing.EaseInOut;
|
||||
case "linear": return BezierEasing.Linear;
|
||||
case "easein": return BezierEasing.EaseIn;
|
||||
case "easeout": return BezierEasing.EaseOut;
|
||||
}
|
||||
var parts = text.Split(',');
|
||||
if (parts.Length == 4
|
||||
&& double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var x1) && x1 is >= 0 and <= 1
|
||||
&& double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var y1) && double.IsFinite(y1)
|
||||
&& double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var x2) && x2 is >= 0 and <= 1
|
||||
&& double.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var y2) && double.IsFinite(y2))
|
||||
return new BezierEasing(x1, y1, x2, y2);
|
||||
warnings.Add(new RenderWarning("Export.Render.EasingIgnored", text));
|
||||
return BezierEasing.EaseInOut;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>Everything a render of one sequence reads, shared by every preset of a batch.</summary>
|
||||
public sealed record RenderInput
|
||||
{
|
||||
public required IRenderFrameSource Source { get; init; }
|
||||
|
||||
/// <summary>Capture metadata, one entry per source frame.</summary>
|
||||
public required IReadOnlyList<SourceFrameInfo> Frames { get; init; }
|
||||
|
||||
public required ProjectSettings Project { get; init; }
|
||||
|
||||
/// <summary>Cached deep-analysis results; missing parts are measured by the preparation pass.</summary>
|
||||
public PrecomputedAnalysis? Analysis { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>One output of a render: the resolved export values and where the file (or sequence folder) goes.</summary>
|
||||
/// <param name="OutputPath">Full path of the file, or of the folder for image sequences (see <see cref="ExportNaming.OutputPath"/>).</param>
|
||||
public sealed record RenderTarget(ResolvedExport Export, string OutputPath);
|
||||
|
||||
/// <summary>Tuning of a render that is not part of the project.</summary>
|
||||
public sealed record RenderOptions
|
||||
{
|
||||
public static RenderOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Long edge of the frames measured by the preparation pass.</summary>
|
||||
public int AnalysisLongEdge { get; init; } = 512;
|
||||
|
||||
/// <summary>Upper bound of the decode size (0 = as large as the output geometry needs); previews set a small value.</summary>
|
||||
public int MaxWorkingLongEdge { get; init; }
|
||||
|
||||
/// <summary>A downscaled copy of every n-th rendered frame is reported for the live preview (0 = never).</summary>
|
||||
public int PreviewInterval { get; init; }
|
||||
|
||||
public int PreviewLongEdge { get; init; } = 640;
|
||||
|
||||
/// <summary>Prepared (exposure-corrected, warped) frames kept for flow and interpolation neighbours (at least 3).</summary>
|
||||
public int CacheFrames { get; init; } = 4;
|
||||
|
||||
/// <summary>Optical-flow quality of a project that neither the user nor the advisor set (the host's quality profile).</summary>
|
||||
public FlowQualitySetting DefaultFlowQuality { get; init; } = FlowQualitySetting.Balanced;
|
||||
|
||||
public RenderPlanOptions Plan { get; init; } = RenderPlanOptions.Default;
|
||||
}
|
||||
|
||||
public enum RenderStage
|
||||
{
|
||||
/// <summary>Measuring the sequence (luminance, colour, camera path).</summary>
|
||||
Preparing,
|
||||
|
||||
/// <summary>Rendering and encoding output frames.</summary>
|
||||
Rendering,
|
||||
|
||||
/// <summary>Flushing and committing the output.</summary>
|
||||
Finishing,
|
||||
}
|
||||
|
||||
/// <summary>Progress of a render. <see cref="Preview"/> (when present) belongs to the receiver, which disposes it.</summary>
|
||||
/// <param name="Done">Frames measured (Preparing) or output frames rendered (Rendering).</param>
|
||||
/// <param name="Total">Frames of the current stage.</param>
|
||||
/// <param name="FramesPerSecond">Recent throughput of the current stage.</param>
|
||||
/// <param name="Remaining">Estimated time to the end of the stage; null until measurable.</param>
|
||||
public sealed record RenderProgress(RenderStage Stage, int Done, int Total, double FramesPerSecond, TimeSpan Elapsed, TimeSpan? Remaining, ImageBuffer? Preview = null)
|
||||
{
|
||||
public double Fraction => Total > 0 ? (double)Done / Total : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Results of the advisor's deep analysis reused by the preparation (all arrays have one entry per source frame).
|
||||
/// Invalid or mismatched parts are ignored and measured again.
|
||||
/// </summary>
|
||||
public sealed record PrecomputedAnalysis
|
||||
{
|
||||
/// <summary>Trimmed-mean log2 luminance (NaN = unusable frame).</summary>
|
||||
public double[]? LogLuminance { get; init; }
|
||||
|
||||
/// <summary>Mean linear red, green and blue (white-balance smoothing).</summary>
|
||||
public double[]? MeanRed { get; init; }
|
||||
|
||||
public double[]? MeanGreen { get; init; }
|
||||
public double[]? MeanBlue { get; init; }
|
||||
|
||||
/// <summary>Sky/land mask with the region series measured through it.</summary>
|
||||
public RegionMask? Regions { get; init; }
|
||||
|
||||
public double[]? SkyLogLuminance { get; init; }
|
||||
public double[]? LandLogLuminance { get; init; }
|
||||
|
||||
/// <summary>Stabilisation solved over the sequence, one correction per source frame, in pixels of a frame of
|
||||
/// <see cref="StabilizationWidth"/>×<see cref="StabilizationHeight"/>.</summary>
|
||||
public StabilizationResult? Stabilization { get; init; }
|
||||
|
||||
public int StabilizationWidth { get; init; }
|
||||
public int StabilizationHeight { get; init; }
|
||||
|
||||
/// <summary>Path smoothing σ the stabilisation was solved with; a different project value triggers a new solve.</summary>
|
||||
public double StabilizationSmoothing { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A localisable remark about a render (key plus invariant-culture arguments).</summary>
|
||||
public sealed record RenderWarning(string Key, IReadOnlyList<string> Args)
|
||||
{
|
||||
public RenderWarning(string key, params string[] args) : this(key, (IReadOnlyList<string>)args)
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => Args.Count == 0 ? Key : $"{Key}({string.Join(", ", Args)})";
|
||||
}
|
||||
|
||||
/// <summary>A render that cannot start or continue for a reason the user can act on.</summary>
|
||||
public sealed class RenderException : Exception
|
||||
{
|
||||
public RenderException(string reasonKey, string message, IReadOnlyList<string>? args = null, Exception? innerException = null)
|
||||
: base(message, innerException)
|
||||
{
|
||||
ReasonKey = reasonKey;
|
||||
Args = args ?? [];
|
||||
}
|
||||
|
||||
/// <summary>Localisation key of the reason (e.g. <see cref="EncoderNotices.NeedsRenderNode"/>).</summary>
|
||||
public string ReasonKey { get; }
|
||||
|
||||
public IReadOnlyList<string> Args { get; }
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>
|
||||
/// Renders sequences (BRIEF §11). For every planned output frame: source frames come from the
|
||||
/// <see cref="IRenderFrameSource"/> at the working size; per-frame exposure corrections (deflicker, holy grail, white
|
||||
/// balance, regions) are applied; stabilisation, virtual camera and crop are resampled once to the output size;
|
||||
/// fractional positions are synthesised from the bidirectional flow; motion blur follows the flow with shutter-angle
|
||||
/// composition; stacking (median, mean, star trails) and the highlight knee come last, then the encoder. Encoding of a
|
||||
/// frame overlaps the processing of the next. Cancellation and failures leave no output behind (sessions delete their
|
||||
/// partial files on dispose) and every background task is awaited, so exceptions surface exactly once.
|
||||
/// </summary>
|
||||
public sealed class RenderPipeline(IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host = EncoderHost.Client)
|
||||
{
|
||||
internal const string LogCategory = "Render";
|
||||
|
||||
/// <summary>Encoder providers in priority order (client: Media Foundation, then managed; server: managed).</summary>
|
||||
public IReadOnlyList<IVideoEncoderProvider> Encoders { get; } = encoders ?? throw new ArgumentNullException(nameof(encoders));
|
||||
|
||||
public EncoderHost Host { get; } = host;
|
||||
|
||||
/// <summary>Geometry, encoder and plan of a target without rendering (Export tab, estimates).</summary>
|
||||
public RenderSetup Setup(RenderInput input, RenderTarget target, RenderOptions? options = null, RenderCorrections? corrections = null) =>
|
||||
RenderSetup.Create(input, target, Encoders, Host, options, corrections);
|
||||
|
||||
/// <summary>Prepares the sequence and renders one target.</summary>
|
||||
public async Task<RenderResult> RenderAsync(RenderInput input, RenderTarget target, RenderOptions? options = null, IProgress<RenderProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var corrections = await RenderPreparation.PrepareAsync(input, options, progress, cancellationToken).ConfigureAwait(false);
|
||||
return await RenderAsync(input, corrections, target, options, progress, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Renders one target with corrections prepared earlier (shared by a batch).</summary>
|
||||
/// <exception cref="RenderException">No encoder can produce the target, or every frame is excluded.</exception>
|
||||
public async Task<RenderResult> RenderAsync(RenderInput input, RenderCorrections corrections, RenderTarget target, RenderOptions? options = null,
|
||||
IProgress<RenderProgress>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
ArgumentNullException.ThrowIfNull(corrections);
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
options ??= RenderOptions.Default;
|
||||
if (corrections.FrameCount != input.Source.FrameCount) throw new ArgumentException("The corrections belong to another sequence.", nameof(corrections));
|
||||
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var setup = Setup(input, target, options, corrections);
|
||||
if (!setup.Encoder.IsReady)
|
||||
{
|
||||
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
|
||||
throw new RenderException(notice.Key, $"No encoder can produce {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args);
|
||||
}
|
||||
if (setup.Plan.Frames.Count == 0) throw new RenderException("Export.Render.NoFrames", "Every frame is excluded.");
|
||||
using var run = new RenderRun(input, corrections, setup, options, progress);
|
||||
return await run.ExecuteAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders several targets of one sequence one after the other, preparing the sequence once. A failing target is
|
||||
/// reported and the batch continues; cancellation stops the batch.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<BatchItemResult>> RenderBatchAsync(RenderInput input, IReadOnlyList<RenderTarget> targets, RenderOptions? options = null,
|
||||
IProgress<RenderProgress>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(targets);
|
||||
var corrections = await RenderPreparation.PrepareAsync(input, options, progress, cancellationToken).ConfigureAwait(false);
|
||||
var results = new List<BatchItemResult>(targets.Count);
|
||||
foreach (var target in targets)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
results.Add(new BatchItemResult(target, await RenderAsync(input, corrections, target, options, progress, cancellationToken).ConfigureAwait(false), null));
|
||||
}
|
||||
catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Warning(LogCategory, $"Batch target {target.OutputPath} failed", ex);
|
||||
results.Add(new BatchItemResult(target, null, ex));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>State of one render: caches, flow, stacking, the encoder session and the encode in flight.</summary>
|
||||
internal sealed class RenderRun : IDisposable
|
||||
{
|
||||
/// <summary>Largest speed (source frames per output period) that scales motion blur; faster plans blur no further.</summary>
|
||||
private const double MaxBlurSpeed = 4;
|
||||
|
||||
private readonly RenderInput _input;
|
||||
private readonly RenderCorrections _corrections;
|
||||
private readonly RenderSetup _setup;
|
||||
private readonly RenderOptions _options;
|
||||
private readonly IProgress<RenderProgress>? _progress;
|
||||
private readonly RenderPlan _plan;
|
||||
private readonly RenderGeometry _geometry;
|
||||
private readonly PreparedFrameCache _prepared;
|
||||
private readonly FlowCache _flows = new(2);
|
||||
private readonly MotionBlurRenderer _blur = new();
|
||||
private readonly List<RenderWarning> _warnings = [];
|
||||
private readonly Stopwatch _clock = new();
|
||||
private readonly int _workingEdge;
|
||||
private readonly float? _knee;
|
||||
private readonly double _targetShutter;
|
||||
private readonly FlowQuality _flowQuality;
|
||||
private OpticalFlowEngine? _flowEngine;
|
||||
private RegionMask? _mask;
|
||||
private IVideoEncoderSession? _session;
|
||||
private Task? _encoding;
|
||||
private int _done;
|
||||
|
||||
public RenderRun(RenderInput input, RenderCorrections corrections, RenderSetup setup, RenderOptions options, IProgress<RenderProgress>? progress)
|
||||
{
|
||||
_input = input;
|
||||
_corrections = corrections;
|
||||
_setup = setup;
|
||||
_options = options;
|
||||
_progress = progress;
|
||||
_plan = setup.Plan;
|
||||
_geometry = setup.Geometry;
|
||||
_prepared = new PreparedFrameCache(int.Max(3, options.CacheFrames));
|
||||
_workingEdge = _geometry.WorkingLongEdge;
|
||||
var exposure = input.Project.Exposure;
|
||||
if (exposure.HighlightKnee is { } knee)
|
||||
{
|
||||
if (knee is > 0 and < 1) _knee = (float)knee;
|
||||
else _warnings.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture)));
|
||||
}
|
||||
var motion = input.Project.Motion;
|
||||
_targetShutter = double.Clamp(motion.TargetShutterAngle.Resolve(180.0), 0, 360);
|
||||
_flowQuality = motion.FlowQuality.Resolve(options.DefaultFlowQuality) switch
|
||||
{
|
||||
FlowQualitySetting.Draft => FlowQuality.Draft,
|
||||
FlowQualitySetting.Best => FlowQuality.Best,
|
||||
_ => FlowQuality.Balanced,
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<RenderResult> ExecuteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = _setup.Encoder.Settings;
|
||||
_clock.Start();
|
||||
Log.Info(RenderPipeline.LogCategory, $"Rendering {_plan.Frames.Count} frames ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}");
|
||||
var session = _session = _setup.Encoder.Open();
|
||||
try
|
||||
{
|
||||
await RenderFramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
await FlushEncodingAsync().ConfigureAwait(false);
|
||||
_progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _plan.Frames.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
|
||||
session.Complete();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await ObserveEncodingAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
session.Dispose();
|
||||
}
|
||||
_clock.Stop();
|
||||
var warnings = new List<RenderWarning>(_setup.Warnings);
|
||||
warnings.AddRange(_corrections.Report.Warnings);
|
||||
warnings.AddRange(_warnings);
|
||||
var result = new RenderResult
|
||||
{
|
||||
OutputPath = settings.OutputPath,
|
||||
PresetId = _setup.Target.Export.PresetId,
|
||||
Codec = settings.Codec,
|
||||
Width = settings.Width,
|
||||
Height = settings.Height,
|
||||
FrameRate = settings.FrameRate,
|
||||
DurationSeconds = _plan.DurationSeconds,
|
||||
FrameCount = _plan.Frames.Count,
|
||||
Bytes = RenderResult.SizeOf(settings.OutputPath),
|
||||
EncoderName = session.EncoderName,
|
||||
Hardware = session.IsHardware,
|
||||
Elapsed = _clock.Elapsed,
|
||||
Warnings = warnings,
|
||||
};
|
||||
Log.Info(RenderPipeline.LogCategory, $"Rendered {result.FrameCount} frames in {result.Elapsed.TotalSeconds:F1} s with {result.EncoderName}: {result.Bytes} bytes");
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_prepared.Dispose();
|
||||
_flows.Dispose();
|
||||
_flowEngine?.Dispose();
|
||||
}
|
||||
|
||||
private async Task RenderFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var stack = _input.Project.Stack;
|
||||
switch (stack.Mode)
|
||||
{
|
||||
case StackSetting.Median or StackSetting.Mean:
|
||||
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case StackSetting.StarTrails:
|
||||
using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity)))
|
||||
{
|
||||
foreach (var planned in _plan.Frames)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) trails.Add(frame);
|
||||
await EmitAsync(trails.Result!.Clone(), planned.Duration90k).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
foreach (var planned in _plan.Frames)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = await RenderFrameAsync(planned, _setup.MotionBlur, cancellationToken).ConfigureAwait(false);
|
||||
await EmitAsync(frame, planned.Duration90k).ConfigureAwait(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Centred median/mean window: output k is emitted once frame k + half has been pushed (the tail reuses the
|
||||
/// last full window).</summary>
|
||||
private async Task RenderWindowStackAsync(StackSettings stack, CancellationToken cancellationToken)
|
||||
{
|
||||
var window = int.Max(1, stack.Length);
|
||||
var half = (window - 1) / 2;
|
||||
using var stacker = new TemporalStacker(window, stack.Mode == StackSetting.Median ? StackMode.Median : StackMode.Mean);
|
||||
var pending = new Queue<PlannedFrame>();
|
||||
foreach (var planned in _plan.Frames)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) stacker.Push(frame);
|
||||
pending.Enqueue(planned);
|
||||
if (pending.Count > half) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
while (pending.Count > 0) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task EmitStackAsync(TemporalStacker stacker, PlannedFrame planned, CancellationToken cancellationToken)
|
||||
{
|
||||
var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false);
|
||||
try
|
||||
{
|
||||
stacker.Render(output, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
output.Dispose();
|
||||
throw;
|
||||
}
|
||||
await EmitAsync(output, planned.Duration90k).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The picture of one planned frame at the output size (a new buffer owned by the caller).</summary>
|
||||
private async Task<ImageBuffer> RenderFrameAsync(PlannedFrame planned, bool blur, CancellationToken cancellationToken)
|
||||
{
|
||||
if (planned.Fraction == 0)
|
||||
{
|
||||
var frame = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false);
|
||||
if (blur && BlurPair(planned.From) is { } pair && BlurFraction(pair.From, pair.To, planned.Speed) is var fraction and > 0)
|
||||
{
|
||||
var flows = await FlowAsync(pair.From, pair.To, needBackward: false, cancellationToken).ConfigureAwait(false);
|
||||
frame = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false);
|
||||
return Blurred(frame, flows.Forward, fraction, cancellationToken);
|
||||
}
|
||||
return frame.Clone();
|
||||
}
|
||||
|
||||
var pairFlows = await FlowAsync(planned.From, planned.To, needBackward: true, cancellationToken).ConfigureAwait(false);
|
||||
var a = await PreparedAsync(planned.From, cancellationToken).ConfigureAwait(false);
|
||||
var b = await PreparedAsync(planned.To, cancellationToken).ConfigureAwait(false);
|
||||
var synthesised = new ImageBuffer(a.Width, a.Height, a.Channels, clear: false);
|
||||
try
|
||||
{
|
||||
FrameInterpolator.Synthesize(a, b, pairFlows.Forward, pairFlows.Backward!, planned.Fraction, synthesised, cancellationToken: cancellationToken);
|
||||
var fraction = blur ? BlurFraction(planned.From, planned.To, planned.Speed) : 0;
|
||||
if (fraction <= 0) return synthesised;
|
||||
using (synthesised) return Blurred(synthesised, pairFlows.Forward, fraction, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
synthesised.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private ImageBuffer Blurred(ImageBuffer source, MotionField flow, double fraction, CancellationToken cancellationToken)
|
||||
{
|
||||
var output = new ImageBuffer(source.Width, source.Height, source.Channels, clear: false);
|
||||
try
|
||||
{
|
||||
_blur.Render(source, flow, fraction, output, cancellationToken);
|
||||
return output;
|
||||
}
|
||||
catch
|
||||
{
|
||||
output.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Continuous neighbours whose flow describes the motion at <paramref name="index"/>.</summary>
|
||||
private (int From, int To)? BlurPair(int index)
|
||||
{
|
||||
var next = _plan.NextContinuous(index);
|
||||
if (next >= 0) return (index, next);
|
||||
var previous = _plan.PreviousContinuous(index);
|
||||
return previous >= 0 ? (previous, index) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fraction of the <paramref name="from"/>→<paramref name="to"/> flow to smear: the target shutter is relative to the
|
||||
/// output period, which spans <paramref name="speed"/> source intervals, and the camera's own exposure already
|
||||
/// blurred <see cref="ShutterAngle.FromExposure"/> of one interval (√(target² − real²) composition, §11.1).
|
||||
/// </summary>
|
||||
private double BlurFraction(int from, int to, double speed)
|
||||
{
|
||||
var steps = to - from;
|
||||
if (steps <= 0) return 0;
|
||||
var real = 0.0;
|
||||
var info = _input.Frames[from];
|
||||
if (info.ExposureTime is > 0 and var exposure && info.CapturedAt is { } t0 && _input.Frames[to].CapturedAt is { } t1 && t1 > t0)
|
||||
real = double.Min(360, ShutterAngle.FromExposure(exposure, (t1 - t0).TotalSeconds / steps));
|
||||
return ShutterAngle.BlurFraction(_targetShutter * double.Clamp(double.Abs(speed), 0, MaxBlurSpeed), real) / steps;
|
||||
}
|
||||
|
||||
private async Task<FlowPair> FlowAsync(int from, int to, bool needBackward, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_flows.TryGet(from, to, needBackward, out var cached)) return cached;
|
||||
var a = await PreparedAsync(from, cancellationToken).ConfigureAwait(false);
|
||||
var b = await PreparedAsync(to, cancellationToken).ConfigureAwait(false);
|
||||
_flowEngine ??= new OpticalFlowEngine(_flowQuality);
|
||||
FlowPair flows;
|
||||
if (needBackward)
|
||||
{
|
||||
var (forward, backward) = _flowEngine.ComputeBidirectional(a, b, cancellationToken);
|
||||
flows = new FlowPair(forward, backward);
|
||||
}
|
||||
else
|
||||
{
|
||||
flows = new FlowPair(_flowEngine.Compute(a, b, cancellationToken), null);
|
||||
}
|
||||
_flows.Add(from, to, flows);
|
||||
return flows;
|
||||
}
|
||||
|
||||
/// <summary>Source frame <paramref name="index"/> decoded, exposure-corrected and warped to the output size (cached).</summary>
|
||||
private async Task<ImageBuffer> PreparedAsync(int index, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_prepared.TryGet(index, out var cached)) return cached;
|
||||
var raw = await _input.Source.GetFrameAsync(index, _workingEdge, DecodePurpose.Render, cancellationToken).ConfigureAwait(false);
|
||||
ImageBuffer prepared;
|
||||
try
|
||||
{
|
||||
raw = Rgb(raw);
|
||||
ApplyExposure(raw, index);
|
||||
var settings = _geometry.For(raw.Width, raw.Height, index, _corrections.StabilizationAt(index, raw.Width, raw.Height));
|
||||
prepared = GeometryStage.Apply(raw, settings, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
raw.Dispose();
|
||||
}
|
||||
_prepared.Add(index, prepared);
|
||||
return prepared;
|
||||
}
|
||||
|
||||
/// <summary>Gray sources become RGB and alpha is dropped, so every stage and encoder sees three channels.</summary>
|
||||
private static ImageBuffer Rgb(ImageBuffer frame)
|
||||
{
|
||||
if (frame.Channels == 3) return frame;
|
||||
using (frame)
|
||||
{
|
||||
if (frame.Channels == 1) return PixelConvert.GrayToRgb(frame);
|
||||
var rgb = new ImageBuffer(frame.Width, frame.Height, 3, clear: false);
|
||||
frame.Data[..(3 * frame.PlaneLength)].CopyTo(rgb.Data);
|
||||
return rgb;
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyExposure(ImageBuffer frame, int index)
|
||||
{
|
||||
var gains = _corrections.WhiteBalance?[index];
|
||||
if (_corrections is { Regions: { } mask, SkyEv: { } sky, LandEv: { } land })
|
||||
{
|
||||
if (_mask is null || _mask.Width != frame.Width || _mask.Height != frame.Height) _mask = mask.Resample(frame.Width, frame.Height);
|
||||
ExposureProcessor.ApplyRegion(frame, _mask.Sky, sky[index], land[index], gains);
|
||||
return;
|
||||
}
|
||||
var ev = _corrections.ExposureEv[index];
|
||||
if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains);
|
||||
}
|
||||
|
||||
/// <summary>Applies the knee and hands the frame to the encoder once the previous frame is encoded; owns <paramref name="frame"/>.</summary>
|
||||
private async Task EmitAsync(ImageBuffer frame, long duration90k)
|
||||
{
|
||||
ImageBuffer? preview = null;
|
||||
try
|
||||
{
|
||||
await FlushEncodingAsync().ConfigureAwait(false);
|
||||
if (_knee is { } knee) ExposureProcessor.Apply(frame, 0, null, knee);
|
||||
_done++;
|
||||
if (_options.PreviewInterval > 0 && (_done - 1) % _options.PreviewInterval == 0) preview = Resampler.Thumbnail(frame, _options.PreviewLongEdge);
|
||||
}
|
||||
catch
|
||||
{
|
||||
frame.Dispose();
|
||||
throw;
|
||||
}
|
||||
var session = _session!;
|
||||
_encoding = Task.Run(() =>
|
||||
{
|
||||
using (frame) session.WriteFrame(frame, duration90k);
|
||||
}, CancellationToken.None);
|
||||
if (_progress is not null)
|
||||
{
|
||||
var fps = Fps();
|
||||
_progress.Report(new RenderProgress(RenderStage.Rendering, _done, _plan.Frames.Count, fps, _clock.Elapsed,
|
||||
fps > 0 ? TimeSpan.FromSeconds((_plan.Frames.Count - _done) / fps) : null, preview));
|
||||
}
|
||||
else
|
||||
{
|
||||
preview?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private double Fps() => _done / double.Max(_clock.Elapsed.TotalSeconds, 1e-6);
|
||||
|
||||
/// <summary>Waits for the encode in flight; its failure propagates here (once).</summary>
|
||||
private async Task FlushEncodingAsync()
|
||||
{
|
||||
var encoding = _encoding;
|
||||
_encoding = null;
|
||||
if (encoding is not null) await encoding.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>After a failure: waits for the encode in flight and logs (never throws) a second error.</summary>
|
||||
private async Task ObserveEncodingAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await FlushEncodingAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning(RenderPipeline.LogCategory, "The encoder also failed while the render was stopping", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Mathematics;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
[Flags]
|
||||
public enum PlannedFrameFlags
|
||||
{
|
||||
None = 0,
|
||||
|
||||
/// <summary>Synthesised between two included source frames from the motion field.</summary>
|
||||
Interpolated = 1,
|
||||
|
||||
/// <summary>Shown for more than one output frame period.</summary>
|
||||
Held = 2,
|
||||
}
|
||||
|
||||
/// <summary>One output frame of a <see cref="RenderPlan"/>.</summary>
|
||||
/// <param name="SourcePosition">Source frame index; fractional for synthesised frames (it may fall on an excluded frame).</param>
|
||||
/// <param name="From">Included source frame at or before the position.</param>
|
||||
/// <param name="To">Included source frame after the position; equals <paramref name="From"/> for whole frames.</param>
|
||||
/// <param name="Fraction">Blend position between <paramref name="From"/> (0) and <paramref name="To"/> (1); 0 for whole frames.</param>
|
||||
/// <param name="Start90k">Presentation time on the 90 kHz clock.</param>
|
||||
/// <param name="Duration90k">Display duration on the 90 kHz clock.</param>
|
||||
/// <param name="StartSlot">First output frame period at <see cref="RenderPlan.FrameRate"/>.</param>
|
||||
/// <param name="Slots">Output frame periods covered (more than one = held).</param>
|
||||
/// <param name="Speed">Source frames advanced per output frame period towards the next planned frame (scales motion blur).</param>
|
||||
public readonly record struct PlannedFrame(
|
||||
double SourcePosition,
|
||||
int From,
|
||||
int To,
|
||||
double Fraction,
|
||||
long Start90k,
|
||||
long Duration90k,
|
||||
int StartSlot,
|
||||
int Slots,
|
||||
double Speed,
|
||||
PlannedFrameFlags Flags)
|
||||
{
|
||||
public bool IsInterpolated => (Flags & PlannedFrameFlags.Interpolated) != 0;
|
||||
|
||||
public bool IsHeld => (Flags & PlannedFrameFlags.Held) != 0;
|
||||
}
|
||||
|
||||
/// <summary>Rules of the timing modes (documented defaults; BRIEF §11.1).</summary>
|
||||
public sealed record RenderPlanOptions
|
||||
{
|
||||
public static RenderPlanOptions Default { get; } = new();
|
||||
|
||||
/// <summary>An interval longer than this multiple of the median capture interval is a gap: Adaptive compresses
|
||||
/// it and motion (blur, synthesis) is treated as discontinuous across it.</summary>
|
||||
public double GapFactor { get; init; } = 3;
|
||||
|
||||
/// <summary>Adaptive: longest display of a compressed gap, in playback frames (gaps are shown as
|
||||
/// GapFactor + log2(ratio / GapFactor) frames up to this cap).</summary>
|
||||
public double MaxGapFrames { get; init; } = 5;
|
||||
|
||||
/// <summary>Adaptive: an interval of at least this multiple of the median and <see cref="MinimumPauseSeconds"/> is a
|
||||
/// deliberate pause and becomes a fixed visual cut.</summary>
|
||||
public double PauseFactor { get; init; } = 20;
|
||||
|
||||
public double MinimumPauseSeconds { get; init; } = 120;
|
||||
|
||||
/// <summary>Adaptive: video seconds the frame before a deliberate pause stays on screen.</summary>
|
||||
public double PauseCutSeconds { get; init; } = 0.2;
|
||||
|
||||
/// <summary>Interpolated: most consecutive missing (or excluded) frames synthesised in one gap; longer gaps are cuts.</summary>
|
||||
public int MaxSynthesizedFrames { get; init; } = 3;
|
||||
}
|
||||
|
||||
/// <summary>Figures for the Time tab's plan chart.</summary>
|
||||
/// <param name="SourceFrames">Frames in the sequence.</param>
|
||||
/// <param name="ExcludedFrames">Frames excluded by the user.</param>
|
||||
/// <param name="ShownFrames">Included frames shown whole at least once.</param>
|
||||
/// <param name="SkippedFrames">Included frames never shown nor used for synthesis (dropped by speed-ups).</param>
|
||||
/// <param name="OutputFrames">Planned frames (held frames count once).</param>
|
||||
/// <param name="OutputSlots">Output frame periods at the plan frame rate.</param>
|
||||
/// <param name="HeldFrames">Planned frames covering several periods.</param>
|
||||
/// <param name="InterpolatedFrames">Planned frames synthesised between two source frames.</param>
|
||||
/// <param name="Cuts">Motion discontinuities (gaps, pauses, long exclusion runs).</param>
|
||||
/// <param name="MedianIntervalSeconds">Median capture interval, when capture times are known.</param>
|
||||
public sealed record RenderPlanStatistics(
|
||||
int SourceFrames,
|
||||
int ExcludedFrames,
|
||||
int ShownFrames,
|
||||
int SkippedFrames,
|
||||
int OutputFrames,
|
||||
int OutputSlots,
|
||||
int HeldFrames,
|
||||
int InterpolatedFrames,
|
||||
int Cuts,
|
||||
double DurationSeconds,
|
||||
double MinimumSpeed,
|
||||
double MaximumSpeed,
|
||||
double? MedianIntervalSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// The list of output frames of a render (BRIEF §11.1): every timing mode produces planned frames with a (possibly
|
||||
/// fractional) source position and a duration on the output frame grid.
|
||||
/// <list type="bullet">
|
||||
/// <item>The playback rate (<see cref="TimingSettings.FrameRate"/>, default the output rate) is how many source frames
|
||||
/// one second of video shows; the output grid is the export frame rate.</item>
|
||||
/// <item>Constant: every included frame lasts one playback frame (whole frames only).</item>
|
||||
/// <item>Adaptive: a frame lasts its capture interval in median intervals; intervals up to <see cref="RenderPlanOptions.GapFactor"/>
|
||||
/// are kept proportional (bursts play faster, small gaps are held), longer gaps are compressed logarithmically and
|
||||
/// capped, deliberate pauses become a fixed cut of <see cref="RenderPlanOptions.PauseCutSeconds"/>; unknown or
|
||||
/// non-positive intervals count as one.</item>
|
||||
/// <item>Interpolated: like Constant, but gaps of up to <see cref="RenderPlanOptions.MaxSynthesizedFrames"/> missing or
|
||||
/// excluded frames get their periods back with synthesised in-betweens, and slower-than-real-time playback is
|
||||
/// synthesised rather than held.</item>
|
||||
/// <item>Remapped: a Fritsch–Carlson monotone spline through <see cref="TimingSettings.RemapCurve"/> maps output time to
|
||||
/// source time (both 0–1); fractional positions are synthesised.</item>
|
||||
/// </list>
|
||||
/// <see cref="TimingSettings.FitToSeconds"/> rescales the output time axis. Each output period shows one picture
|
||||
/// (synthesised stretches sampled at the period start, whole frames at its centre); consecutive periods showing the
|
||||
/// same picture merge into one held frame. Durations are differences of the rounded 90 kHz times of period boundaries,
|
||||
/// so they add up exactly to the total.
|
||||
/// </summary>
|
||||
public sealed class RenderPlan
|
||||
{
|
||||
private const double SnapEpsilon = 1e-6;
|
||||
private readonly bool[] _cutBefore;
|
||||
private readonly int[] _includedOrder;
|
||||
|
||||
private RenderPlan(TimingMode mode, Rational frameRate, double playbackRate, PlannedFrame[] frames, int slots, int[] included,
|
||||
bool[] cutBefore, RenderPlanStatistics statistics, IReadOnlyList<string> warnings)
|
||||
{
|
||||
Mode = mode;
|
||||
FrameRate = frameRate;
|
||||
PlaybackRate = playbackRate;
|
||||
Frames = frames;
|
||||
SlotCount = slots;
|
||||
Duration90k = TicksAt(frameRate, slots);
|
||||
IncludedFrames = included;
|
||||
_cutBefore = cutBefore;
|
||||
_includedOrder = new int[cutBefore.Length];
|
||||
Array.Fill(_includedOrder, -1);
|
||||
for (var k = 0; k < included.Length; k++) _includedOrder[included[k]] = k;
|
||||
Statistics = statistics;
|
||||
Warnings = warnings;
|
||||
}
|
||||
|
||||
public TimingMode Mode { get; }
|
||||
|
||||
/// <summary>Output frame rate (the grid of every duration).</summary>
|
||||
public Rational FrameRate { get; }
|
||||
|
||||
/// <summary>Source frames per second of video before fitting.</summary>
|
||||
public double PlaybackRate { get; }
|
||||
|
||||
public IReadOnlyList<PlannedFrame> Frames { get; }
|
||||
|
||||
/// <summary>Output frame periods covered by the plan.</summary>
|
||||
public int SlotCount { get; }
|
||||
|
||||
/// <summary>Exact total duration on the 90 kHz clock.</summary>
|
||||
public long Duration90k { get; }
|
||||
|
||||
public double DurationSeconds => Duration90k / 90000.0;
|
||||
|
||||
/// <summary>Source indices that are not excluded, ascending.</summary>
|
||||
public IReadOnlyList<int> IncludedFrames { get; }
|
||||
|
||||
public RenderPlanStatistics Statistics { get; }
|
||||
|
||||
/// <summary>Localisation keys of planning remarks (e.g. Adaptive without capture times).</summary>
|
||||
public IReadOnlyList<string> Warnings { get; }
|
||||
|
||||
/// <summary>True when motion is discontinuous between <paramref name="sourceIndex"/> and the included frame before it.</summary>
|
||||
public bool IsCutBefore(int sourceIndex) => _cutBefore[sourceIndex];
|
||||
|
||||
/// <summary>The included frame after <paramref name="sourceIndex"/> with continuous motion, or −1.</summary>
|
||||
public int NextContinuous(int sourceIndex)
|
||||
{
|
||||
var k = _includedOrder[sourceIndex];
|
||||
if (k < 0 || k + 1 >= IncludedFrames.Count) return -1;
|
||||
var next = IncludedFrames[k + 1];
|
||||
return _cutBefore[next] ? -1 : next;
|
||||
}
|
||||
|
||||
/// <summary>The included frame before <paramref name="sourceIndex"/> with continuous motion, or −1.</summary>
|
||||
public int PreviousContinuous(int sourceIndex)
|
||||
{
|
||||
var k = _includedOrder[sourceIndex];
|
||||
return k <= 0 || _cutBefore[sourceIndex] ? -1 : IncludedFrames[k - 1];
|
||||
}
|
||||
|
||||
/// <summary>Start of output period <paramref name="slot"/> on the 90 kHz clock, rounded half up.</summary>
|
||||
public static long TicksAt(Rational frameRate, long slot) =>
|
||||
(slot * 90000L * frameRate.Denominator * 2 + frameRate.Numerator) / (2L * frameRate.Numerator);
|
||||
|
||||
/// <summary>Builds the plan for a sequence.</summary>
|
||||
/// <param name="captureTimes">Capture time per source frame (clock-corrected when available, e.g.
|
||||
/// <c>LightAnalysisReport.AdjustedTimes</c>); null for unknown.</param>
|
||||
/// <param name="project">Timing settings and excluded frames.</param>
|
||||
/// <param name="frameRate">Output (encoded) frame rate.</param>
|
||||
public static RenderPlan Build(IReadOnlyList<DateTime?> captureTimes, ProjectSettings project, Rational frameRate, RenderPlanOptions? options = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(captureTimes);
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate));
|
||||
options ??= RenderPlanOptions.Default;
|
||||
var n = captureTimes.Count;
|
||||
var timing = project.Timing;
|
||||
var mode = timing.Mode.Resolve(TimingMode.Constant);
|
||||
var warnings = new List<string>();
|
||||
var playbackText = timing.FrameRate.Resolve(string.Empty);
|
||||
var playback = FrameRateText.TryParse(playbackText, out var rate) ? rate.Value : frameRate.Value;
|
||||
if (playbackText.Length > 0 && rate.Numerator == 0) warnings.Add("Export.Plan.FrameRateIgnored");
|
||||
|
||||
var excluded = new bool[n];
|
||||
foreach (var i in project.ExcludedFrames)
|
||||
{
|
||||
if ((uint)i < (uint)n) excluded[i] = true;
|
||||
}
|
||||
var included = new List<int>(n);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
if (!excluded[i]) included.Add(i);
|
||||
}
|
||||
|
||||
var median = MedianInterval(captureTimes);
|
||||
if (mode is TimingMode.Adaptive or TimingMode.Interpolated && median is null) warnings.Add("Export.Plan.NoCaptureTimes");
|
||||
var cutBefore = new bool[n];
|
||||
var entries = Timeline(captureTimes, included, mode, playback, median, options, cutBefore);
|
||||
if (entries.Length == 0)
|
||||
{
|
||||
warnings.Add("Export.Plan.NoFrames");
|
||||
var empty = new RenderPlanStatistics(n, n - included.Count, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, median);
|
||||
return new RenderPlan(mode, frameRate, playback, [], 0, [.. included], cutBefore, empty, warnings);
|
||||
}
|
||||
|
||||
var total = entries[^1].Start + entries[^1].Length;
|
||||
var seconds = timing.FitToSeconds is { } fit && fit > 0 ? fit : total / playback;
|
||||
var slots = (int)long.Clamp((long)double.Round(seconds * frameRate.Value), 1, int.MaxValue / 2);
|
||||
var remap = mode == TimingMode.Remapped ? RemapSpline(timing.RemapCurve, warnings) : null;
|
||||
|
||||
var frames = new List<PlannedFrame>();
|
||||
Sample? open = null;
|
||||
var openStart = 0;
|
||||
for (var k = 0; k <= slots; k++)
|
||||
{
|
||||
Sample? sample = null;
|
||||
if (k < slots)
|
||||
{
|
||||
sample = Locate(entries, TimelinePosition(k, slots, total, remap), TimelinePosition(k + 0.5, slots, total, remap), total);
|
||||
if (open is { } current && current.SameAs(sample.Value)) continue;
|
||||
}
|
||||
if (open is { } done) frames.Add(Planned(done, openStart, k - openStart, frameRate));
|
||||
open = sample;
|
||||
openStart = k;
|
||||
}
|
||||
|
||||
var planned = frames.ToArray();
|
||||
AssignSpeeds(planned);
|
||||
var statistics = Summarise(n, n - included.Count, included, planned, slots, cutBefore, frameRate, median);
|
||||
return new RenderPlan(mode, frameRate, playback, planned, slots, [.. included], cutBefore, statistics, warnings);
|
||||
}
|
||||
|
||||
/// <summary>A stretch of the playback timeline shown by one included frame.</summary>
|
||||
/// <param name="Start">Start in playback frames.</param>
|
||||
/// <param name="Length">Length in playback frames (> 0).</param>
|
||||
/// <param name="Index">Source index shown at the start.</param>
|
||||
/// <param name="Next">Next included source index, −1 for the last.</param>
|
||||
/// <param name="Continuous">The position moves linearly towards <paramref name="Next"/> across the stretch (synthesis).</param>
|
||||
private readonly record struct Entry(double Start, double Length, int Index, int Next, bool Continuous);
|
||||
|
||||
private readonly record struct Sample(int From, int To, double Fraction, double Position)
|
||||
{
|
||||
public bool SameAs(Sample other) => From == other.From && To == other.To && Fraction == other.Fraction;
|
||||
}
|
||||
|
||||
private static Entry[] Timeline(IReadOnlyList<DateTime?> times, List<int> included, TimingMode mode, double playback, double? median,
|
||||
RenderPlanOptions options, bool[] cutBefore)
|
||||
{
|
||||
var entries = new Entry[included.Count];
|
||||
double start = 0;
|
||||
for (var k = 0; k < included.Count; k++)
|
||||
{
|
||||
var index = included[k];
|
||||
var next = k + 1 < included.Count ? included[k + 1] : -1;
|
||||
double length = 1;
|
||||
var continuous = false;
|
||||
if (next >= 0)
|
||||
{
|
||||
var seconds = times[index] is { } a && times[next] is { } b ? (b - a).TotalSeconds : double.NaN;
|
||||
var ratio = median is { } m && seconds > 0 ? seconds / m : double.NaN;
|
||||
var steps = next - index;
|
||||
var gap = double.Max(double.IsNaN(ratio) ? steps : ratio, steps) > options.GapFactor;
|
||||
switch (mode)
|
||||
{
|
||||
case TimingMode.Adaptive:
|
||||
length = AdaptiveLength(ratio, seconds, playback, options, ref gap);
|
||||
break;
|
||||
case TimingMode.Interpolated:
|
||||
var periods = int.Max(steps, double.IsNaN(ratio) ? 1 : (int)double.Min(double.Round(ratio), int.MaxValue / 2));
|
||||
gap = periods - 1 > options.MaxSynthesizedFrames;
|
||||
if (!gap)
|
||||
{
|
||||
length = periods;
|
||||
continuous = true;
|
||||
}
|
||||
break;
|
||||
case TimingMode.Remapped:
|
||||
continuous = !gap;
|
||||
break;
|
||||
}
|
||||
cutBefore[next] = gap;
|
||||
}
|
||||
entries[k] = new Entry(start, length, index, next, continuous);
|
||||
start += length;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static double AdaptiveLength(double ratio, double seconds, double playback, RenderPlanOptions options, ref bool gap)
|
||||
{
|
||||
if (double.IsNaN(ratio)) return 1;
|
||||
if (ratio <= options.GapFactor) return ratio;
|
||||
gap = true;
|
||||
if (ratio >= options.PauseFactor && seconds >= options.MinimumPauseSeconds) return double.Max(options.PauseCutSeconds * playback, 1e-3);
|
||||
return double.Min(options.MaxGapFrames, options.GapFactor + double.Log2(ratio / options.GapFactor));
|
||||
}
|
||||
|
||||
/// <summary>Playback-timeline position of output period <paramref name="slot"/> (fractional slots address its interior).</summary>
|
||||
private static double TimelinePosition(double slot, int slots, double total, MonotoneSpline? remap)
|
||||
{
|
||||
var x = slot / slots;
|
||||
return remap is null ? x * total : double.Clamp(remap.Evaluate(x), 0, 1) * total;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The picture of an output period. Synthesised stretches are sampled at the period start (so equal rates give whole
|
||||
/// frames); whole-frame stretches at the period centre, which rounds every frame boundary to the nearest period
|
||||
/// (ties keep the earlier frame, so a 2× speed-up shows frames 0, 2, 4…).
|
||||
/// </summary>
|
||||
private static Sample Locate(Entry[] entries, double start, double centre, double total)
|
||||
{
|
||||
var e = entries[Find(entries, double.Clamp(start, 0, total), atBoundary: true)];
|
||||
if (e.Continuous && e.Next >= 0)
|
||||
{
|
||||
var fraction = double.Clamp((start - e.Start) / e.Length, 0, 1);
|
||||
if (fraction < SnapEpsilon) return new Sample(e.Index, e.Index, 0, e.Index);
|
||||
if (fraction > 1 - SnapEpsilon) return new Sample(e.Next, e.Next, 0, e.Next);
|
||||
return new Sample(e.Index, e.Next, fraction, e.Index + fraction * (e.Next - e.Index));
|
||||
}
|
||||
var index = entries[Find(entries, double.Clamp(centre, 0, total), atBoundary: false)].Index;
|
||||
return new Sample(index, index, 0, index);
|
||||
}
|
||||
|
||||
/// <summary>Entry containing <paramref name="u"/>; a position within 1e-9 of a boundary belongs to the entry starting
|
||||
/// there when <paramref name="atBoundary"/>, else to the one ending there.</summary>
|
||||
private static int Find(Entry[] entries, double u, bool atBoundary)
|
||||
{
|
||||
var limit = atBoundary ? u + 1e-9 : u - 1e-9;
|
||||
int lo = 0, hi = entries.Length - 1;
|
||||
while (lo < hi)
|
||||
{
|
||||
var mid = (lo + hi + 1) >> 1;
|
||||
if (atBoundary ? entries[mid].Start <= limit : entries[mid].Start < limit) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
private static PlannedFrame Planned(Sample s, int startSlot, int slots, Rational rate)
|
||||
{
|
||||
var start = TicksAt(rate, startSlot);
|
||||
var flags = (s.Fraction > 0 ? PlannedFrameFlags.Interpolated : PlannedFrameFlags.None) | (slots > 1 ? PlannedFrameFlags.Held : PlannedFrameFlags.None);
|
||||
return new PlannedFrame(s.Position, s.From, s.To, s.Fraction, start, TicksAt(rate, startSlot + slots) - start, startSlot, slots, 0, flags);
|
||||
}
|
||||
|
||||
private static void AssignSpeeds(PlannedFrame[] frames)
|
||||
{
|
||||
for (var k = 0; k + 1 < frames.Length; k++)
|
||||
frames[k] = frames[k] with { Speed = (frames[k + 1].SourcePosition - frames[k].SourcePosition) / frames[k].Slots };
|
||||
if (frames.Length > 1) frames[^1] = frames[^1] with { Speed = frames[^2].Speed };
|
||||
else if (frames.Length == 1) frames[0] = frames[0] with { Speed = 1 };
|
||||
}
|
||||
|
||||
/// <summary>Sorted, clamped and made non-decreasing so the spline (and the remap) is monotone.</summary>
|
||||
private static MonotoneSpline? RemapSpline(IReadOnlyList<CurvePoint> curve, List<string> warnings)
|
||||
{
|
||||
var points = curve.Where(p => double.IsFinite(p.X) && double.IsFinite(p.Y))
|
||||
.Select(p => (X: double.Clamp(p.X, 0, 1), Y: double.Clamp(p.Y, 0, 1)))
|
||||
.OrderBy(p => p.X)
|
||||
.ToList();
|
||||
if (points.Count == 0) return null;
|
||||
var xs = new List<double>(points.Count);
|
||||
var ys = new List<double>(points.Count);
|
||||
var adjusted = false;
|
||||
foreach (var (x, y) in points)
|
||||
{
|
||||
var value = y;
|
||||
if (ys.Count > 0 && value < ys[^1])
|
||||
{
|
||||
value = ys[^1];
|
||||
adjusted = true;
|
||||
}
|
||||
if (xs.Count > 0 && x == xs[^1])
|
||||
{
|
||||
ys[^1] = double.Max(ys[^1], value);
|
||||
continue;
|
||||
}
|
||||
xs.Add(x);
|
||||
ys.Add(value);
|
||||
}
|
||||
if (adjusted) warnings.Add("Export.Plan.RemapNotMonotonic");
|
||||
return new MonotoneSpline(xs.ToArray(), ys.ToArray());
|
||||
}
|
||||
|
||||
private static double? MedianInterval(IReadOnlyList<DateTime?> times)
|
||||
{
|
||||
var intervals = new List<double>(times.Count);
|
||||
for (var i = 1; i < times.Count; i++)
|
||||
{
|
||||
if (times[i - 1] is { } a && times[i] is { } b && b > a) intervals.Add((b - a).TotalSeconds);
|
||||
}
|
||||
return intervals.Count == 0 ? null : Mathematics.Statistics.Median(intervals.ToArray());
|
||||
}
|
||||
|
||||
private static RenderPlanStatistics Summarise(int sourceFrames, int excludedFrames, List<int> included, PlannedFrame[] frames, int slots,
|
||||
bool[] cutBefore, Rational rate, double? median)
|
||||
{
|
||||
var shown = new HashSet<int>();
|
||||
var used = new HashSet<int>();
|
||||
int held = 0, interpolated = 0;
|
||||
double minSpeed = double.PositiveInfinity, maxSpeed = double.NegativeInfinity;
|
||||
foreach (var f in frames)
|
||||
{
|
||||
used.Add(f.From);
|
||||
used.Add(f.To);
|
||||
if (f.Fraction == 0) shown.Add(f.From);
|
||||
if (f.IsHeld) held++;
|
||||
if (f.IsInterpolated) interpolated++;
|
||||
minSpeed = double.Min(minSpeed, f.Speed);
|
||||
maxSpeed = double.Max(maxSpeed, f.Speed);
|
||||
}
|
||||
var cuts = cutBefore.Count(c => c);
|
||||
return new RenderPlanStatistics(sourceFrames, excludedFrames, shown.Count, included.Count - used.Count, frames.Length, slots, held, interpolated,
|
||||
cuts, TicksAt(rate, slots) / 90000.0, frames.Length > 0 ? minSpeed : 0, frames.Length > 0 ? maxSpeed : 0, median);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>Diagnostics of <see cref="RenderPreparation"/> for the editor's measuring tools and the render log.</summary>
|
||||
public sealed record RenderPreparationReport
|
||||
{
|
||||
/// <summary>Frames decoded by the preparation pass (0 when cached analysis covered everything needed).</summary>
|
||||
public int MeasuredFrames { get; init; }
|
||||
|
||||
public DeflickerDiagnostics? Deflicker { get; init; }
|
||||
|
||||
/// <summary>Holy-grail transitions (received and ignored steps).</summary>
|
||||
public IReadOnlyList<ExposureTransition> Transitions { get; init; } = [];
|
||||
|
||||
/// <summary>Largest frame-to-frame change of the holy-grail target, in EV.</summary>
|
||||
public double? MaxTargetStepEv { get; init; }
|
||||
|
||||
public double? ShakeRms { get; init; }
|
||||
|
||||
public RegionMethod? RegionMethod { get; init; }
|
||||
|
||||
public IReadOnlyList<RenderWarning> Warnings { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Per-source-frame corrections computed once per render (every array has one entry per source frame).</summary>
|
||||
public sealed record RenderCorrections
|
||||
{
|
||||
public required int FrameCount { get; init; }
|
||||
|
||||
/// <summary>Measured log2 luminance (NaN where not measured): the amber curve of the Exposure chart.</summary>
|
||||
public required double[] MeasuredLogLuminance { get; init; }
|
||||
|
||||
/// <summary>Global exposure correction in EV, including the project's exposure offset.</summary>
|
||||
public required double[] ExposureEv { get; init; }
|
||||
|
||||
/// <summary>White-balance gains; null when smoothing is off.</summary>
|
||||
public ChannelGains[]? WhiteBalance { get; init; }
|
||||
|
||||
/// <summary>Sky/land mask; when set, <see cref="SkyEv"/> and <see cref="LandEv"/> replace <see cref="ExposureEv"/>.</summary>
|
||||
public RegionMask? Regions { get; init; }
|
||||
|
||||
public double[]? SkyEv { get; init; }
|
||||
public double[]? LandEv { get; init; }
|
||||
|
||||
/// <summary>Stabiliser corrections (source → stabilised) in pixels of a <see cref="StabilizationWidth"/>-wide frame.</summary>
|
||||
public Affine2D[]? Stabilization { get; init; }
|
||||
|
||||
public int StabilizationWidth { get; init; }
|
||||
public int StabilizationHeight { get; init; }
|
||||
|
||||
/// <summary>Zoom applied about the centre so stabilisation borders stay outside the picture (1 = none).</summary>
|
||||
public double StabilizationZoom { get; init; } = 1;
|
||||
|
||||
public RenderPreparationReport Report { get; init; } = new();
|
||||
|
||||
/// <summary>Target log2 luminance (measured + correction): the accent curve of the Exposure chart.</summary>
|
||||
public double[] TargetLogLuminance()
|
||||
{
|
||||
var target = new double[FrameCount];
|
||||
for (var i = 0; i < FrameCount; i++) target[i] = MeasuredLogLuminance[i] + ExposureEv[i];
|
||||
return target;
|
||||
}
|
||||
|
||||
/// <summary>The stabiliser correction of frame <paramref name="index"/> for a frame of <paramref name="width"/>×<paramref name="height"/>.</summary>
|
||||
public Affine2D StabilizationAt(int index, int width, int height)
|
||||
{
|
||||
if (Stabilization is null) return Affine2D.Identity;
|
||||
var c = Stabilization[index];
|
||||
if (c.IsIdentity() || (width == StabilizationWidth && height == StabilizationHeight)) return c;
|
||||
// Pixel-centre scaling between the two frame sizes: x' = (x + ½)·s − ½.
|
||||
double sx = (double)width / StabilizationWidth, sy = (double)height / StabilizationHeight;
|
||||
var toFrame = new Affine2D(sx, 0, 0, sy, (sx - 1) / 2, (sy - 1) / 2);
|
||||
return toFrame * c * toFrame.Invert();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The pass over the sequence that a render needs before its first frame (BRIEF §11.1–§11.2): luminance, colour and
|
||||
/// region series for deflicker / holy grail / white balance / region deflicker, and the stabilisation path. Values the
|
||||
/// cached <see cref="PrecomputedAnalysis"/> provides are reused; the rest is measured on frames decoded at
|
||||
/// <see cref="RenderOptions.AnalysisLongEdge"/> one at a time (memory does not grow with the sequence).
|
||||
/// <list type="bullet">
|
||||
/// <item>Modules switch on only when their setting resolves to true; Auto without advice changes nothing.</item>
|
||||
/// <item>Deflicker keeps metadata exposure steps (as intentional offsets); holy grail turns the received steps into
|
||||
/// ramps (alone, or on top of deflicker); region deflicker gives sky and land their own curves.</item>
|
||||
/// <item>Stabilisation analyses the included frames only and zooms in by 1 / crop scale (at most 1 / 0.75) to hide borders.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public static class RenderPreparation
|
||||
{
|
||||
/// <summary>Smallest stabilisation crop scale compensated by zooming; below it borders may show.</summary>
|
||||
public const double MinimumCropScale = 0.75;
|
||||
|
||||
/// <summary>Region masks below this confidence are not used when the region mode is Auto.</summary>
|
||||
public const double MinimumRegionConfidence = 0.3;
|
||||
|
||||
public static async Task<RenderCorrections> PrepareAsync(RenderInput input, RenderOptions? options = null, IProgress<RenderProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
options ??= RenderOptions.Default;
|
||||
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
|
||||
var n = input.Source.FrameCount;
|
||||
if (input.Frames.Count != n) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input));
|
||||
var exposure = input.Project.Exposure;
|
||||
var motion = input.Project.Motion;
|
||||
var cached = input.Analysis;
|
||||
var warnings = new List<RenderWarning>();
|
||||
var included = Included(input.Project.ExcludedFrames, n);
|
||||
var excluded = new bool[n];
|
||||
Array.Fill(excluded, true);
|
||||
foreach (var i in included) excluded[i] = false;
|
||||
|
||||
var deflicker = exposure.Deflicker.Resolve(false);
|
||||
var holyGrail = exposure.HolyGrail.Resolve(false);
|
||||
var regionMode = deflicker ? exposure.Regions.Resolve(RegionMode.Off) : RegionMode.Off;
|
||||
var whiteBalance = exposure.WhiteBalanceSmoothing.Resolve(false);
|
||||
var stabilize = motion.Stabilize.Resolve(false);
|
||||
var smoothing = motion.StabilizeSmoothing.Resolve(new StabilizerOptions().SmoothingSigma);
|
||||
|
||||
var luminance = deflicker || holyGrail ? Valid(cached?.LogLuminance, excluded) : null;
|
||||
var measureLuminance = (deflicker || holyGrail) && luminance is null;
|
||||
double[]? red = null, green = null, blue = null;
|
||||
if (whiteBalance && Valid(cached?.MeanRed, excluded) is { } r && Valid(cached?.MeanGreen, excluded) is { } g && Valid(cached?.MeanBlue, excluded) is { } b)
|
||||
(red, green, blue) = (r, g, b);
|
||||
var measureColour = whiteBalance && red is null;
|
||||
RegionMask? mask = null;
|
||||
double[]? sky = null, land = null;
|
||||
if (regionMode != RegionMode.Off && cached?.Regions is { } m && Valid(cached.SkyLogLuminance, excluded) is { } s && Valid(cached.LandLogLuminance, excluded) is { } l)
|
||||
(mask, sky, land) = (m, s, l);
|
||||
var stabilization = stabilize ? CachedStabilization(cached, n, smoothing) : null;
|
||||
var measureStabilization = stabilize && stabilization is null;
|
||||
|
||||
if (regionMode != RegionMode.Off && mask is null && included.Count > 0)
|
||||
{
|
||||
mask = await SegmentAsync(input.Source, included, regionMode, options.AnalysisLongEdge, cancellationToken).ConfigureAwait(false);
|
||||
if (mask is null) warnings.Add(new RenderWarning("Export.Render.RegionsUnavailable"));
|
||||
else if (regionMode == RegionMode.Auto && mask.Confidence < MinimumRegionConfidence)
|
||||
{
|
||||
warnings.Add(new RenderWarning("Export.Render.RegionsUnreliable", mask.Confidence.ToString("0.00", CultureInfo.InvariantCulture)));
|
||||
mask = null;
|
||||
}
|
||||
}
|
||||
var measureRegions = mask is not null && sky is null;
|
||||
|
||||
var pass = new MeasurementPass(n, measureLuminance, measureColour, measureRegions ? mask : null, measureStabilization, smoothing);
|
||||
if (pass.Needed)
|
||||
{
|
||||
await pass.RunAsync(input.Source, included, options.AnalysisLongEdge, progress, cancellationToken).ConfigureAwait(false);
|
||||
luminance ??= pass.Luminance;
|
||||
red ??= pass.Red;
|
||||
green ??= pass.Green;
|
||||
blue ??= pass.Blue;
|
||||
sky ??= pass.Sky;
|
||||
land ??= pass.Land;
|
||||
if (measureStabilization)
|
||||
{
|
||||
stabilization = pass.SolveStabilization(included, n);
|
||||
if (stabilization is null) warnings.Add(new RenderWarning("Export.Render.StabilizationUnavailable"));
|
||||
}
|
||||
}
|
||||
|
||||
return Combine(input, excluded, luminance, red, green, blue, mask, sky, land, stabilization, deflicker, holyGrail, pass.MeasuredFrames, warnings);
|
||||
}
|
||||
|
||||
private static RenderCorrections Combine(RenderInput input, bool[] excluded, double[]? luminance, double[]? red, double[]? green, double[]? blue, RegionMask? mask,
|
||||
double[]? sky, double[]? land, StabilizationData? stabilization, bool deflicker, bool holyGrail, int measured, List<RenderWarning> warnings)
|
||||
{
|
||||
var n = input.Source.FrameCount;
|
||||
var exposure = input.Project.Exposure;
|
||||
var ev = new double[n];
|
||||
double[]? skyEv = null, landEv = null;
|
||||
DeflickerDiagnostics? diagnostics = null;
|
||||
HolyGrailResult? hg = null;
|
||||
if (luminance is not null)
|
||||
{
|
||||
var options = new DeflickerOptions
|
||||
{
|
||||
Window = int.Max(3, exposure.DeflickerWindow.Resolve(0) is var w and > 0 ? w : RecommendedWindow(luminance)),
|
||||
Strength = double.Clamp(exposure.DeflickerStrength.Resolve(1.0), 0, 1),
|
||||
};
|
||||
var evs = new double?[n];
|
||||
// Excluded frames (test shots, bumps) must not create exposure steps.
|
||||
for (var i = 0; i < n; i++) evs[i] = excluded[i] ? null : input.Frames[i].ExposureValue;
|
||||
if (holyGrail)
|
||||
{
|
||||
var transition = exposure.TransitionLength.Resolve(0);
|
||||
hg = HolyGrailEngine.Compute(luminance, evs, new HolyGrailOptions { TransitionFrames = transition > 0 ? transition : null, Deflicker = options });
|
||||
}
|
||||
var offsets = hg?.StepOffsets ?? DeflickerEngine.OffsetsFromExposure(evs);
|
||||
if (deflicker && hg is not null)
|
||||
{
|
||||
Array.Copy(hg.CorrectionEv, ev, n);
|
||||
diagnostics = hg.Deflicker.Diagnostics;
|
||||
}
|
||||
else if (deflicker)
|
||||
{
|
||||
var result = DeflickerEngine.Compute(luminance, options, offsets);
|
||||
Array.Copy(result.CorrectionEv, ev, n);
|
||||
diagnostics = result.Diagnostics;
|
||||
}
|
||||
else if (hg is not null)
|
||||
{
|
||||
for (var i = 0; i < n; i++) ev[i] = hg.SmoothedOffsets[i] - hg.StepOffsets[i];
|
||||
}
|
||||
if (mask is not null && sky is not null && land is not null)
|
||||
{
|
||||
var regions = RegionDeflicker.Compute(sky, land, options, offsets);
|
||||
skyEv = new double[n];
|
||||
landEv = new double[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var ramp = hg is null ? 0 : hg.SmoothedOffsets[i] - hg.StepOffsets[i];
|
||||
skyEv[i] = regions.Sky.CorrectionEv[i] + ramp + exposure.ExposureOffsetEv;
|
||||
landEv[i] = regions.Land.CorrectionEv[i] + ramp + exposure.ExposureOffsetEv;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < n; i++) ev[i] += exposure.ExposureOffsetEv;
|
||||
|
||||
ChannelGains[]? gains = red is not null && green is not null && blue is not null ? WhiteBalanceSmoother.Smooth(red, green, blue).Gains : null;
|
||||
var zoom = 1.0;
|
||||
if (stabilization is not null)
|
||||
{
|
||||
zoom = 1 / double.Max(stabilization.CropScale, MinimumCropScale);
|
||||
if (stabilization.CropScale < MinimumCropScale)
|
||||
warnings.Add(new RenderWarning("Export.Render.StabilizationBorders", stabilization.CropScale.ToString("0.00", CultureInfo.InvariantCulture)));
|
||||
}
|
||||
var measuredLuminance = luminance ?? NaNs(n);
|
||||
return new RenderCorrections
|
||||
{
|
||||
FrameCount = n,
|
||||
MeasuredLogLuminance = measuredLuminance,
|
||||
ExposureEv = ev,
|
||||
WhiteBalance = gains,
|
||||
Regions = skyEv is null ? null : mask,
|
||||
SkyEv = skyEv,
|
||||
LandEv = landEv,
|
||||
Stabilization = stabilization?.Corrections,
|
||||
StabilizationWidth = stabilization?.Width ?? 0,
|
||||
StabilizationHeight = stabilization?.Height ?? 0,
|
||||
StabilizationZoom = zoom,
|
||||
Report = new RenderPreparationReport
|
||||
{
|
||||
MeasuredFrames = measured,
|
||||
Deflicker = diagnostics,
|
||||
Transitions = hg?.Transitions ?? [],
|
||||
MaxTargetStepEv = hg?.MaxFrameStepEv,
|
||||
ShakeRms = stabilization?.ShakeRms,
|
||||
RegionMethod = skyEv is null ? null : mask!.Method,
|
||||
Warnings = warnings,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Corrections for every source frame (identity for excluded ones) with the frame size they are measured in.</summary>
|
||||
private sealed record StabilizationData(Affine2D[] Corrections, int Width, int Height, double CropScale, double ShakeRms);
|
||||
|
||||
private static StabilizationData? CachedStabilization(PrecomputedAnalysis? cached, int n, double smoothing)
|
||||
{
|
||||
if (cached?.Stabilization is not { } result || result.Corrections.Count != n || cached.StabilizationWidth <= 0 || cached.StabilizationHeight <= 0
|
||||
|| double.Abs(cached.StabilizationSmoothing - smoothing) > 1e-9) return null;
|
||||
return new StabilizationData([.. result.Corrections], cached.StabilizationWidth, cached.StabilizationHeight, result.CropScale, result.ShakeRms);
|
||||
}
|
||||
|
||||
private static int RecommendedWindow(double[] luminance)
|
||||
{
|
||||
var finite = luminance.Where(double.IsFinite).ToArray();
|
||||
return finite.Length >= 16 ? FlickerSpectrum.Analyze(finite).RecommendedWindow : DeflickerOptions.Default.Window;
|
||||
}
|
||||
|
||||
private static List<int> Included(IReadOnlyList<int> excluded, int n)
|
||||
{
|
||||
var skip = new bool[n];
|
||||
foreach (var i in excluded)
|
||||
{
|
||||
if ((uint)i < (uint)n) skip[i] = true;
|
||||
}
|
||||
var result = new List<int>(n);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
if (!skip[i]) result.Add(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>A copy of a cached series with excluded frames marked unusable, or null when it does not fit the sequence.</summary>
|
||||
private static double[]? Valid(double[]? values, bool[] excluded)
|
||||
{
|
||||
if (values is null || values.Length != excluded.Length) return null;
|
||||
var copy = (double[])values.Clone();
|
||||
for (var i = 0; i < copy.Length; i++)
|
||||
{
|
||||
if (excluded[i]) copy[i] = double.NaN;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static double[] NaNs(int n)
|
||||
{
|
||||
var values = new double[n];
|
||||
Array.Fill(values, double.NaN);
|
||||
return values;
|
||||
}
|
||||
|
||||
private static async Task<RegionMask?> SegmentAsync(IRenderFrameSource source, List<int> included, RegionMode mode, int longEdge, CancellationToken cancellationToken)
|
||||
{
|
||||
var options = new RegionSegmenterOptions
|
||||
{
|
||||
// Horizon mode accepts any detected horizon; Luminance mode lets the horizon win only when it is more confident.
|
||||
MinimumHorizonConfidence = mode switch { RegionMode.Horizon => 0, RegionMode.Luminance => 2, _ => RegionSegmenterOptions.Default.MinimumHorizonConfidence },
|
||||
};
|
||||
var count = int.Min(options.MaxFrames, included.Count);
|
||||
var frames = new List<ImageBuffer>(count);
|
||||
try
|
||||
{
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var index = included[(int)((long)k * (included.Count - 1) / int.Max(1, count - 1))];
|
||||
var frame = await source.GetFrameAsync(index, longEdge, DecodePurpose.Analysis, cancellationToken).ConfigureAwait(false);
|
||||
frames.Add(frames.Count == 0 ? frame : Conform(frame, frames[0].Width, frames[0].Height));
|
||||
}
|
||||
return frames[0].Height < 8 ? null : RegionSegmenter.Segment(frames, options);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var f in frames) f.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resizes <paramref name="frame"/> to the given size (disposing it) when a source returns frames of varying size.</summary>
|
||||
internal static ImageBuffer Conform(ImageBuffer frame, int width, int height)
|
||||
{
|
||||
if (frame.Width == width && frame.Height == height) return frame;
|
||||
try
|
||||
{
|
||||
return Resampler.Resize(frame, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
frame.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One sequential pass that measures whatever the cache did not provide.</summary>
|
||||
private sealed class MeasurementPass(int n, bool luminance, bool colour, RegionMask? regions, bool stabilization, double smoothing)
|
||||
{
|
||||
public bool Needed => luminance || colour || regions is not null || stabilization;
|
||||
public int MeasuredFrames { get; private set; }
|
||||
public double[]? Luminance { get; } = luminance ? NaNs(n) : null;
|
||||
public double[]? Red { get; } = colour ? NaNs(n) : null;
|
||||
public double[]? Green { get; } = colour ? NaNs(n) : null;
|
||||
public double[]? Blue { get; } = colour ? NaNs(n) : null;
|
||||
public double[]? Sky { get; } = regions is not null ? NaNs(n) : null;
|
||||
public double[]? Land { get; } = regions is not null ? NaNs(n) : null;
|
||||
private Stabilizer? _stabilizer;
|
||||
|
||||
public async Task RunAsync(IRenderFrameSource source, List<int> included, int longEdge, IProgress<RenderProgress>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
RegionMask? fitted = null;
|
||||
var stabilize = stabilization;
|
||||
try
|
||||
{
|
||||
foreach (var index in included)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = await source.GetFrameAsync(index, longEdge, DecodePurpose.Analysis, cancellationToken).ConfigureAwait(false);
|
||||
using (frame)
|
||||
{
|
||||
if (Luminance is not null) Luminance[index] = FrameStatistics.MeasureLogLuminance(frame);
|
||||
if (Red is not null) (Red[index], Green![index], Blue![index]) = Means(frame);
|
||||
if (regions is not null && Sky is not null)
|
||||
{
|
||||
if (fitted is null || fitted.Width != frame.Width || fitted.Height != frame.Height) fitted = regions.Resample(frame.Width, frame.Height);
|
||||
(Sky[index], Land![index]) = RegionDeflicker.Measure(frame, fitted);
|
||||
}
|
||||
if (stabilize) stabilize = AddToStabilizer(frame);
|
||||
}
|
||||
MeasuredFrames++;
|
||||
if (progress is not null)
|
||||
{
|
||||
var elapsed = clock.Elapsed;
|
||||
var fps = MeasuredFrames / double.Max(elapsed.TotalSeconds, 1e-6);
|
||||
progress.Report(new RenderProgress(RenderStage.Preparing, MeasuredFrames, included.Count, fps, elapsed,
|
||||
TimeSpan.FromSeconds((included.Count - MeasuredFrames) / fps)));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
_stabilizer?.Dispose();
|
||||
_stabilizer = null;
|
||||
throw;
|
||||
}
|
||||
if (!stabilize)
|
||||
{
|
||||
_stabilizer?.Dispose();
|
||||
_stabilizer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>False when the frames are too small to stabilise.</summary>
|
||||
private bool AddToStabilizer(ImageBuffer frame)
|
||||
{
|
||||
if (_stabilizer is null)
|
||||
{
|
||||
if (frame.Width < 16 || frame.Height < 16) return false;
|
||||
_stabilizer = new Stabilizer(frame.Width, frame.Height, new StabilizerOptions { SmoothingSigma = smoothing });
|
||||
}
|
||||
if (frame.Width == _stabilizer.Width && frame.Height == _stabilizer.Height)
|
||||
{
|
||||
_stabilizer.AddFrame(frame);
|
||||
return true;
|
||||
}
|
||||
using var resized = Resampler.Resize(frame, _stabilizer.Width, _stabilizer.Height);
|
||||
_stabilizer.AddFrame(resized);
|
||||
return true;
|
||||
}
|
||||
|
||||
public StabilizationData? SolveStabilization(List<int> included, int frameCount)
|
||||
{
|
||||
var stabilizer = _stabilizer;
|
||||
_stabilizer = null;
|
||||
if (stabilizer is null) return null;
|
||||
using (stabilizer)
|
||||
{
|
||||
if (stabilizer.FrameCount == 0) return null;
|
||||
var result = stabilizer.Solve();
|
||||
var corrections = new Affine2D[frameCount];
|
||||
Array.Fill(corrections, Affine2D.Identity);
|
||||
for (var k = 0; k < included.Count; k++) corrections[included[k]] = result.Corrections[k];
|
||||
return new StabilizationData(corrections, stabilizer.Width, stabilizer.Height, result.CropScale, result.ShakeRms);
|
||||
}
|
||||
}
|
||||
|
||||
private static (double R, double G, double B) Means(ImageBuffer image)
|
||||
{
|
||||
var count = image.PlaneLength;
|
||||
var r = Sum(image.Plane(0)) / count;
|
||||
if (image.Channels < 3) return (r, r, r);
|
||||
return (r, Sum(image.Plane(1)) / count, Sum(image.Plane(2)) / count);
|
||||
}
|
||||
|
||||
private static double Sum(ReadOnlySpan<float> values)
|
||||
{
|
||||
double sum = 0;
|
||||
foreach (var v in values) sum += v;
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>A finished render, for the render history and the database (<see cref="Model.Render"/>).</summary>
|
||||
public sealed record RenderResult
|
||||
{
|
||||
/// <summary>The output file, or folder for image sequences.</summary>
|
||||
public required string OutputPath { get; init; }
|
||||
|
||||
/// <summary>Effective preset id (or <see cref="ExportResolver.CustomId"/>).</summary>
|
||||
public required string PresetId { get; init; }
|
||||
|
||||
public required VideoCodec Codec { get; init; }
|
||||
public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec);
|
||||
public required int Width { get; init; }
|
||||
public required int Height { get; init; }
|
||||
public required Rational FrameRate { get; init; }
|
||||
public required double DurationSeconds { get; init; }
|
||||
|
||||
/// <summary>Output pictures rendered (held frames count once).</summary>
|
||||
public required int FrameCount { get; init; }
|
||||
|
||||
/// <summary>Size of the file, or of every file of a sequence.</summary>
|
||||
public required long Bytes { get; init; }
|
||||
|
||||
public required string EncoderName { get; init; }
|
||||
public required bool Hardware { get; init; }
|
||||
public required TimeSpan Elapsed { get; init; }
|
||||
|
||||
/// <summary>Plan, geometry, encoder and preparation remarks.</summary>
|
||||
public IReadOnlyList<RenderWarning> Warnings { get; init; } = [];
|
||||
|
||||
/// <summary>The render-history entity.</summary>
|
||||
/// <param name="presetName">Display name of the preset at render time.</param>
|
||||
/// <param name="settingsJson">The project settings used (<see cref="Project.ProjectSettings.ToJson"/>).</param>
|
||||
/// <param name="producedBy">Client or render-node name.</param>
|
||||
public Model.Render ToEntity(Guid sequenceId, string presetName, string? settingsJson, string? producedBy) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequenceId,
|
||||
PresetName = presetName,
|
||||
SettingsJson = settingsJson,
|
||||
OutputPath = OutputPath,
|
||||
Codec = Codec.ToString(),
|
||||
Width = Width,
|
||||
Height = Height,
|
||||
Fps = FrameRate.Value,
|
||||
DurationSeconds = DurationSeconds,
|
||||
Bytes = Bytes,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
ProducedBy = producedBy,
|
||||
};
|
||||
|
||||
/// <summary>Bytes of a file, or the total of the files in a folder.</summary>
|
||||
internal static long SizeOf(string path)
|
||||
{
|
||||
if (File.Exists(path)) return new FileInfo(path).Length;
|
||||
if (!Directory.Exists(path)) return 0;
|
||||
long total = 0;
|
||||
foreach (var file in new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories)) total += file.Length;
|
||||
return total;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Outcome of one target of <see cref="RenderPipeline.RenderBatchAsync"/>: a result or the failure that stopped it.</summary>
|
||||
public sealed record BatchItemResult(RenderTarget Target, RenderResult? Result, Exception? Error)
|
||||
{
|
||||
public bool Succeeded => Result is not null;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>
|
||||
/// What a render will do, decided before its first frame: output geometry, encoder (with its adjustments) and plan.
|
||||
/// The Export tab uses it for the output size, encoder notices, plan chart and estimates.
|
||||
/// </summary>
|
||||
public sealed record RenderSetup
|
||||
{
|
||||
public required RenderTarget Target { get; init; }
|
||||
public required RenderGeometry Geometry { get; init; }
|
||||
public required EncoderSelection Encoder { get; init; }
|
||||
public required RenderPlan Plan { get; init; }
|
||||
|
||||
/// <summary>Synthetic motion blur applies (it is off while stacking).</summary>
|
||||
public bool MotionBlur { get; init; }
|
||||
|
||||
/// <summary>The preparation pass decodes frames (no corrections were supplied and a module needs measurements).</summary>
|
||||
public bool NeedsPreparation { get; init; }
|
||||
|
||||
/// <summary>Geometry, plan and encoder remarks.</summary>
|
||||
public IReadOnlyList<RenderWarning> Warnings { get; init; } = [];
|
||||
|
||||
/// <summary>Decides geometry, encoder and plan for one target.</summary>
|
||||
/// <param name="corrections">Prepared corrections when available (their stabilisation zoom affects the decode size).</param>
|
||||
public static RenderSetup Create(RenderInput input, RenderTarget target, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host,
|
||||
RenderOptions? options = null, RenderCorrections? corrections = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(encoders);
|
||||
options ??= RenderOptions.Default;
|
||||
if (input.Frames.Count != input.Source.FrameCount) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input));
|
||||
var project = input.Project;
|
||||
var geometry = RenderGeometry.Create(project.Camera, target.Export, input.Source.Width, input.Source.Height,
|
||||
corrections?.StabilizationZoom ?? 1, options.MaxWorkingLongEdge);
|
||||
var selection = EncoderSelector.Select(target.Export.ToEncodeSettings(target.OutputPath, geometry.OutputWidth, geometry.OutputHeight), encoders, host);
|
||||
geometry = geometry.WithOutputSize(selection.Settings.Width, selection.Settings.Height);
|
||||
var times = new DateTime?[input.Frames.Count];
|
||||
for (var i = 0; i < times.Length; i++) times[i] = input.Frames[i].CapturedAt;
|
||||
var plan = RenderPlan.Build(times, project, selection.Settings.FrameRate, options.Plan);
|
||||
|
||||
var warnings = new List<RenderWarning>(geometry.Warnings);
|
||||
warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k)));
|
||||
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
|
||||
var stacking = project.Stack.Mode != StackSetting.None;
|
||||
var blur = project.Motion.MotionBlur.Resolve(false);
|
||||
if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking"));
|
||||
var exposure = project.Exposure;
|
||||
var measuring = exposure.Deflicker.Resolve(false) || exposure.HolyGrail.Resolve(false)
|
||||
|| exposure.WhiteBalanceSmoothing.Resolve(false) || project.Motion.Stabilize.Resolve(false);
|
||||
return new RenderSetup
|
||||
{
|
||||
Target = target,
|
||||
Geometry = geometry,
|
||||
Encoder = selection,
|
||||
Plan = plan,
|
||||
MotionBlur = blur && !stacking,
|
||||
NeedsPreparation = corrections is null && measuring,
|
||||
Warnings = warnings,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The render's workload in the units of <see cref="ExportEstimator"/>.</summary>
|
||||
public ExportWorkload Workload()
|
||||
{
|
||||
var edge = Geometry.WorkingLongEdge;
|
||||
var shortEdge = (long)double.Round(edge * (double)int.Min(Geometry.SourceWidth, Geometry.SourceHeight) / int.Max(Geometry.SourceWidth, Geometry.SourceHeight));
|
||||
var flowFrames = MotionBlur ? Plan.Frames.Count : Plan.Statistics.InterpolatedFrames;
|
||||
return new ExportWorkload(Plan.Frames.Count, Plan.SlotCount, Plan.DurationSeconds, Geometry.OutputWidth, Geometry.OutputHeight, edge * shortEdge,
|
||||
flowFrames, NeedsPreparation ? Plan.IncludedFrames.Count : 0, Encoder.Capability?.Hardware ?? false);
|
||||
}
|
||||
|
||||
/// <summary>Size and time estimates for the values the encoder will actually use.</summary>
|
||||
public ExportEstimate Estimate(ThroughputModel? model = null)
|
||||
{
|
||||
var s = Encoder.Settings;
|
||||
return ExportEstimator.Estimate(Target.Export with { Codec = s.Codec, BitRate = s.BitRate, BitDepth = s.BitDepth, Quality = s.Quality }, Workload(), model);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user