Files
Chronos/tests/Chronos.Core.Tests/Render/PlaybackRenderTests.cs
T
Alby96andClaude Opus 5.5 3c2cce8031 feat(P1): output program with direction, loops, hold and fades; still frames
Completes the Core side of owner review 1 phase 5 (R8): OutputProgram turns the plan into the emitted entries (reverse, boomerang without a doubled turn, loops, a hold of whole periods, fades split per period over held frames and shortened with a warning when longer than half the program). The render follows the program: star trails accumulate in program order, median/mean windows stay per plan frame in either direction, a boomerang with trails plays forward with a warning, and the fade gain is the last FrameFinish step. Workload and estimates come from the program, so loops and holds show in time and size.

A still target (RenderTarget.StillFrame) renders one source frame with every correction and no playback into one PNG, JPEG or TIFF 16-bit file (EncodeSettings.SingleImage, StillImageSession), named by ExportNaming.StillPath and recorded with kind still, fps 0 and duration 0.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:07:58 +01:00

232 lines
12 KiB
C#

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.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
/// <summary>Renders of the output program (owner review 1, R8) and of a still ("Save frame").</summary>
public sealed class PlaybackRenderTests
{
private readonly TestContext _context;
public PlaybackRenderTests(TestContext context) => _context = context;
[Test]
public async Task TheResultCountsTheFramesAndTheDurationOfTheProgram()
{
var source = Source(6);
var input = Input(source, Playing(new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 2, HoldEnd = 1 }));
var setup = Pipeline().Setup(input, new RenderTarget(Preset("png-sequence"), "out"));
// 6 + 5 frames, then 5 + 5 from the second frame on.
Assert.Equal(21, setup.Program.Count);
Assert.SequenceEqual([0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0], setup.Program.Entries.Select(e => e.PlanIndex));
var (encode, result) = await CaptureAsync(input, cancellationToken: _context.Cancellation);
Assert.Equal(21, result.FrameCount);
Assert.Equal(21, encode.Frames.Count);
Assert.Equal(setup.Program.Duration90k, encode.Durations.Sum());
Assert.Approximately((21 + 30) / 30.0, result.DurationSeconds, 1e-9);
Assert.Equal(3000L + 90000, encode.Durations[^1]);
Assert.Null(result.Kind);
// The way back shows the very pictures of the way out.
Assert.True(double.IsPositiveInfinity(Psnr(encode.Frames[4], encode.Frames[6])));
}
[Test]
public async Task FadesStartAndEndInBlackAndLeaveTheMiddleAlone()
{
var source = Source(12);
var (plain, _) = await CaptureAsync(Input(source), cancellationToken: _context.Cancellation);
var (faded, result) = await CaptureAsync(Input(source, Playing(new PlaybackSettings { FadeIn = 0.1, FadeOut = 0.1 })), cancellationToken: _context.Cancellation);
Assert.Equal(12, faded.Frames.Count);
Assert.Equal(0, result.Warnings.Count(w => w.Key == OutputProgram.FadesShortenedWarning));
Assert.LessOrEqual(Peak(faded.Frames[0]), 1e-6);
Assert.LessOrEqual(Peak(faded.Frames[^1]), 1e-6);
Assert.Less(Mean(faded.Frames[1]), Mean(plain.Frames[1]));
Assert.True(double.IsPositiveInfinity(Psnr(plain.Frames[6], faded.Frames[6])));
// The ramp brightens in and darkens out.
Assert.Monotonic(faded.Frames.Take(4).Select(Mean));
Assert.Monotonic(faded.Frames.TakeLast(4).Select(Mean), decreasing: true);
}
[Test]
public async Task ReversedStarTrailsGrowFromTheEnd()
{
var stars = Source(10, motion: i => (1.0 * i, 0), configure: o => o with { StarField = true, StartEv = 0, EndEv = 0, StarCount = 60 });
var trails = new StackSettings { Mode = StackSetting.StarTrails, Length = 0 };
var (plain, _) = await CaptureAsync(Input(stars), cancellationToken: _context.Cancellation);
var (reversed, _) = await CaptureAsync(Input(stars, Playing(new PlaybackSettings { Direction = PlaybackDirection.Reverse }) with { Stack = trails }),
cancellationToken: _context.Cancellation);
Assert.Equal(10, reversed.Frames.Count);
// The first picture is the last frame alone; every later one only adds trails.
Assert.True(double.IsPositiveInfinity(Psnr(plain.Frames[^1], reversed.Frames[0])));
for (var k = 1; k < reversed.Frames.Count; k++)
{
var previous = reversed.Frames[k - 1].Data;
var current = reversed.Frames[k].Data;
for (var i = 0; i < current.Length; i++) Assert.True(current[i] >= previous[i] - 1e-6f, $"pixel {i} darkened at frame {k}");
}
// A boomerang with trails plays forward and says so.
var (boomerang, result) = await CaptureAsync(Input(stars, Playing(new PlaybackSettings { Direction = PlaybackDirection.Boomerang }) with { Stack = trails }),
cancellationToken: _context.Cancellation);
Assert.Equal(10, boomerang.Frames.Count);
Assert.Contains(result.Warnings, w => w.Key == OutputProgram.BoomerangStackWarning);
}
[Test]
public async Task AMedianWindowIsTheSameFrameInEitherDirection()
{
var source = Source(9);
var median = new StackSettings { Mode = StackSetting.Median, Length = 5 };
var (forward, _) = await CaptureAsync(Input(source, Plain with { Stack = median }), cancellationToken: _context.Cancellation);
var (boomerang, _) = await CaptureAsync(Input(source, Playing(new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 2 }) with { Stack = median }),
cancellationToken: _context.Cancellation);
int[] order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0];
Assert.Equal(order.Length, boomerang.Frames.Count);
for (var k = 0; k < order.Length; k++)
Assert.True(double.IsPositiveInfinity(Psnr(forward.Frames[order[k]], boomerang.Frames[k])), $"program frame {k} (plan frame {order[k]})");
}
[Test]
public void TheEstimateGrowsWithTheLoopsAndTheHold()
{
var source = Source(12);
var export = Preset("png-sequence");
var once = Pipeline().Setup(Input(source), new RenderTarget(export, "out"));
var thrice = Pipeline().Setup(Input(source, Playing(new PlaybackSettings { Loops = 3, HoldEnd = 1 })), new RenderTarget(export, "out"));
Assert.Equal(3 * once.Workload().OutputFrames, thrice.Workload().OutputFrames);
Assert.Equal(3 * 12 + 30, thrice.Workload().OutputPeriods);
Assert.Approximately(once.Workload().DurationSeconds * 3 + 1, thrice.Workload().DurationSeconds, 1e-9);
Assert.Greater(thrice.Estimate().Time.TotalSeconds, once.Estimate().Time.TotalSeconds);
Assert.Greater(thrice.Estimate().Bytes, 3 * once.Estimate().Bytes);
}
[Theory]
[Case("png-sequence", 8)]
[Case("jpeg-sequence", 8)]
[Case("tiff16-sequence", 8)]
public async Task AStillWritesOneImageAtTheOutputSize(string presetId, int bitDepth)
{
var dir = _context.CreateTempDirectory();
var source = Source(8);
var export = Preset(presetId) with { BitDepth = bitDepth };
var context = new ExportNameContext { Date = new DateTime(2026, 9, 28), Title = "Harbour", PresetName = "Still", Codec = export.Codec };
var path = ExportNaming.StillPath(dir, "{date} {title}", context, 4);
Assert.Equal("2026-09-28 Harbour - 0005" + VideoCodecInfo.FileExtension(export.Codec), Path.GetFileName(path));
// Playback never reaches a still.
var input = Input(source, Playing(new PlaybackSettings { Direction = PlaybackDirection.Reverse, FadeIn = 5 }));
var target = new RenderTarget(export, path, StillFrame: 4);
var setup = Pipeline().Setup(input, target);
Assert.Equal(1, setup.Program.Count);
Assert.True(setup.Encoder.Settings.SingleImage);
Assert.Equal(export.Codec == VideoCodec.Tiff16Sequence ? 16 : 8, setup.Encoder.Settings.BitDepth);
Assert.Equal((1, 1, 0.0), (setup.Workload().OutputFrames, setup.Workload().OutputPeriods, setup.Workload().DurationSeconds));
var result = await Pipeline().RenderAsync(input, target, cancellationToken: _context.Cancellation);
Assert.SequenceEqual([Path.GetFileName(path)], Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));
Assert.Equal((1, 0.0, RenderKind.Still), (result.FrameCount, result.DurationSeconds, result.Kind));
Assert.Equal(new FileInfo(path).Length, result.Bytes);
var entity = result.ToEntity(Guid.NewGuid(), "PNG", null, "test");
Assert.Equal((RenderKind.Still, 0.0, 0.0), (entity.Kind, entity.Fps, entity.DurationSeconds));
var bytes = File.ReadAllBytes(path);
using var decoded = export.Codec switch
{
VideoCodec.JpegSequence => JpegDecoder.DecodeToLinear(bytes),
VideoCodec.PngSequence => PngDecoder.DecodeToLinear(bytes),
_ => TiffImageReader.Decode(bytes),
};
Assert.Equal((96, 64), (decoded.Width, decoded.Height));
using var expected = source.Sequence.Render(4);
_context.Log($"{presetId}: {result.Bytes} bytes, PSNR {Psnr(expected, decoded):F1} dB");
Assert.Greater(Psnr(expected, decoded), 25);
}
[Test]
public async Task AStillRendersTheFrameItNames()
{
var source = Source(8);
var (plain, _) = await CaptureAsync(Input(source), cancellationToken: _context.Cancellation);
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 8192, 8192, true));
var result = await Pipeline(capture).RenderAsync(Input(source), new RenderTarget(Preset("png-sequence"), "still.png", 6), cancellationToken: _context.Cancellation);
var encode = capture.Encodes.Single();
Assert.True(encode.Settings.SingleImage);
Assert.Equal(1, encode.Frames.Count);
Assert.True(double.IsPositiveInfinity(Psnr(plain.Frames[6], encode.Frames[0])));
Assert.Equal(RenderKind.Still, result.Kind);
}
[Test]
public async Task AStillOfAFrameTheSequenceDoesNotHaveIsARenderError()
{
var source = Source(4);
var error = await Assert.ThrowsAsync<RenderException>(() => Pipeline().RenderAsync(Input(source), new RenderTarget(Preset("png-sequence"), "x.png", 4)));
Assert.Equal("Tooltips.Export.StillNeedsFrame", error.ReasonKey);
Assert.Throws<RenderException>(() => Pipeline().Setup(Input(source), new RenderTarget(Preset("png-sequence"), "x.png", -1)));
}
[Test]
public void AStillIsOneFileWhateverTheSequenceCodec()
{
var provider = new Chronos.Core.Video.Managed.ManagedEncoderProvider();
EncodeSettings Still(VideoCodec codec, int depth) => new() { OutputPath = "x", Codec = codec, Width = 8, Height = 8, FrameRate = new Rational(30, 1), BitDepth = depth, SingleImage = true };
Assert.True(provider.CanEncode(Still(VideoCodec.PngSequence, 16)));
Assert.True(provider.CanEncode(Still(VideoCodec.JpegSequence, 8)));
Assert.True(provider.CanEncode(Still(VideoCodec.Tiff16Sequence, 16)));
Assert.False(provider.CanEncode(Still(VideoCodec.LinearDngSequence, 16)));
Assert.False(provider.CanEncode(Still(VideoCodec.Gif, 8)));
Assert.False(provider.CanEncode(Still(VideoCodec.Mjpeg, 8)));
}
[Test]
public void AStillTargetNeedsFormatThree()
{
var export = ExportResolver.Resolve(new ExportSettings());
Assert.Equal(1, RenderRules.RequiredFormat(new ProjectSettings(), new RenderTarget(export, "x"), 6000, 4000));
Assert.Equal(RenderRules.StillFormat, RenderRules.RequiredFormat(new ProjectSettings(), new RenderTarget(export, "x", 3), 6000, 4000));
// The playback a job renders raises the settings it carries to format 3.
var playing = new ProjectSettings { Export = new ExportSettings { Playback = new PlaybackSettings { Direction = PlaybackDirection.Reverse } } };
Assert.Equal(ProjectSettings.PlaybackVersion, RenderRules.RequiredFormat(playing, new RenderTarget(export, "x"), 6000, 4000));
}
[Test]
public void AFadeScalesEverySampleInPlace()
{
using var frame = new ImageBuffer(7, 5, 3);
frame.Data.Fill(0.5f);
FrameFinish.Fade(frame, 1);
Assert.True(frame.Data.ToArray().All(v => v == 0.5f));
FrameFinish.Fade(frame, 0.5);
Assert.True(frame.Data.ToArray().All(v => v == 0.25f));
FrameFinish.Fade(frame, double.NaN);
Assert.True(frame.Data.ToArray().All(v => v == 0.25f));
FrameFinish.Fade(frame, 0);
Assert.True(frame.Data.ToArray().All(v => v == 0));
}
private static ProjectSettings Playing(PlaybackSettings playback) => Plain with { Export = Plain.Export with { Playback = playback } };
private static double Peak(ImageBuffer frame)
{
var peak = 0f;
foreach (var v in frame.Data) peak = float.Max(peak, v);
return peak;
}
private static double Mean(ImageBuffer frame)
{
double sum = 0;
foreach (var v in frame.Data) sum += v;
return sum / frame.Data.Length;
}
}