using System.Diagnostics; using System.Globalization; using Titano.Core.Codecs.Png; using Titano.Core.Diagnostics.Synthetic; using Titano.Core.Export; using Titano.Core.Imaging; using Titano.Core.Project; using Titano.Core.Video; using Titano.Core.Video.Managed; namespace Titano.Core.Render.Diagnostics; public enum SelfTestOutcome { Passed, Failed, /// The check needs something this machine does not have (e.g. an MP4 encoder). Skipped, } /// Outcome of one self-test check; carries the measured figures or the failure. public sealed record SelfTestResult(string Id, string Group, string Description, SelfTestOutcome Outcome, string Detail, TimeSpan Elapsed); /// What a check may use: its own empty folder, the encoders, and the run's cancellation. public sealed record SelfTestContext(string WorkDirectory, IReadOnlyList Encoders, IReadOnlyList PlatformEncoders, CancellationToken Cancellation); /// One end-to-end check; it returns a short detail on success and throws on failure. public sealed record SelfTestCheck(string Id, string Group, string Description, Func> Run); public sealed record SelfTestOptions { /// Platform encoders tested in addition to the managed ones (the desktop passes Media Foundation). public IReadOnlyList PlatformEncoders { get; init; } = []; /// Parent folder of the run's scratch folder (deleted afterwards); default the system temp folder. public string? WorkDirectory { get; init; } /// Run only checks whose id starts with one of these prefixes (all when empty). public IReadOnlyList Filters { get; init; } = []; } /// /// The engine's end-to-end self-test (BRIEF §20.2, §20.4), shared by Titano.Tools selftest 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. /// public static partial class SelfTest { public static IReadOnlyList Checks { get; } = [.. PlanChecks(), .. ExportChecks(), .. CodecChecks(), .. RenderChecks(), .. ProcessingChecks(), .. RobustnessChecks()]; public static async Task> RunAsync(SelfTestOptions? options = null, IProgress? progress = null, CancellationToken cancellationToken = default) { options ??= new SelfTestOptions(); var root = Path.Combine(options.WorkDirectory ?? Path.GetTempPath(), "titano-selftest-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(root); IVideoEncoderProvider[] encoders = [.. options.PlatformEncoders, new ManagedEncoderProvider()]; var results = new List(); 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) { Titano.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> run) => new(id, id[..id.IndexOf('.', StringComparison.Ordinal)], description, run); private static SelfTestCheck Check(string id, string description, Func run) => Check(id, description, _ => Task.FromResult(run())); private static string Invariant(FormattableString text) => text.ToString(CultureInfo.InvariantCulture); /// No module and no knee: renders reproduce the source. private static ProjectSettings Plain { get; } = new() { Exposure = new ExposureSettings { HighlightKnee = null } }; private static Auto Manual(T value) => new Auto().WithManual(value); private static SyntheticFrameSource Synthetic(int frames, Func? configure = null, Func? 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 }; /// A built-in preset's values at the synthetic frame size (or another size; 0×0 = source). 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); /// Renders to a 16-bit PNG sequence and decodes every picture back (linear light). private static async Task> 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(); 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 frames) { foreach (var f in frames) f.Dispose(); } /// Peak signal-to-noise ratio of the 8-bit sRGB encodings, optionally inside a margin. 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 values) { var mean = values.Average(); return double.Sqrt(values.Sum(v => (v - mean) * (v - mean)) / values.Count); } /// RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve. private static double FrameToFrameResidual(IReadOnlyList series, IReadOnlyList 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)); } /// Largest |series − truth − c| with c the mean offset (the measurement constant). private static double MaxDeviation(IReadOnlyList series, IReadOnlyList 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; } /// Synchronous progress sink (Progress<T> would post to the thread pool). private sealed class Sink(Action report) : IProgress { public void Report(T value) => report(value); } }