refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

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. 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) and
  pe-check.

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,146 @@
using Chronos.Core.Export;
using Chronos.Core.Tests.Render;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
using Chronos.Testing;
namespace Chronos.Core.Tests.Export;
public sealed class EncoderSelectorTests
{
private static readonly EncoderCapability SoftwareH264 = new(VideoCodec.H264, "Microsoft H.264", false, 4096, 2304, false);
private static readonly EncoderCapability HardwareH264 = new(VideoCodec.H264, "NVENC H.264", true, 4096, 4096, false, "NVIDIA");
private static readonly EncoderCapability HardwareHevc = new(VideoCodec.Hevc, "NVENC HEVC", true, 8192, 8192, true, "NVIDIA");
private static readonly EncoderCapability HardwareHevc8 = new(VideoCodec.Hevc, "QSV HEVC", true, 8192, 8192, false, "Intel");
private static EncodeSettings Request(VideoCodec codec, int width = 3840, int height = 2160, int bitDepth = 8, long bitRate = 20_000_000, Rational? fps = null) => new()
{
OutputPath = "/exports/out" + VideoCodecInfo.FileExtension(codec),
Codec = codec,
Width = width,
Height = height,
FrameRate = fps ?? new Rational(30, 1),
BitDepth = bitDepth,
BitRate = bitRate,
Profile = bitDepth == 10 ? CodecProfile.HevcMain10 : CodecProfile.Auto,
};
private static IVideoEncoderProvider[] Client(params EncoderCapability[] capabilities) =>
[new CapturingEncoderProvider("Media Foundation", capabilities), new ManagedEncoderProvider()];
[Test]
public void ManagedCodecsUseTheManagedProviderEverywhere()
{
foreach (var host in new[] { EncoderHost.Client, EncoderHost.Server })
{
var selection = EncoderSelector.Select(Request(VideoCodec.Mjpeg, bitDepth: 8), Client(HardwareH264), host);
Assert.True(selection.IsReady);
Assert.Equal(ManagedEncoderProvider.ProviderName, selection.Provider!.Name);
Assert.Equal("Managed MJPEG", selection.Capability!.Name);
Assert.Empty(selection.Notices);
}
}
[Test]
public void ManagedBitDepthsAreAdjustedWithANotice()
{
var png = EncoderSelector.Select(Request(VideoCodec.PngSequence, bitDepth: 10), [new ManagedEncoderProvider()], EncoderHost.Server);
Assert.Equal(16, png.Settings.BitDepth);
Assert.Equal(EncoderNotices.BitDepthAdjusted, png.Notices.Single().Key);
Assert.SequenceEqual(new[] { "10", "16" }, png.Notices.Single().Args);
var jpeg = EncoderSelector.Select(Request(VideoCodec.JpegSequence, bitDepth: 16), [new ManagedEncoderProvider()], EncoderHost.Server);
Assert.Equal(8, jpeg.Settings.BitDepth);
}
[Test]
public void ServerNeedsARenderNodeForMp4()
{
var selection = EncoderSelector.Select(Request(VideoCodec.H264), [new ManagedEncoderProvider()], EncoderHost.Server);
Assert.Equal(EncoderSelectionStatus.NeedsRenderNode, selection.Status);
Assert.Null(selection.Provider);
Assert.Equal(EncoderNotices.NeedsRenderNode, selection.Notices.Single().Key);
Assert.Throws<InvalidOperationException>(() => selection.Open());
}
[Test]
public void HardwareIsPreferredUnlessSoftwareIsAsked()
{
var providers = Client(SoftwareH264, HardwareH264);
var hardware = EncoderSelector.Select(Request(VideoCodec.H264), providers, EncoderHost.Client);
Assert.True(hardware.IsReady);
Assert.Equal("NVENC H.264", hardware.Capability!.Name);
Assert.Empty(hardware.Notices);
Assert.Equal(new CodecLevel(VideoCodec.H264, 5, 1), hardware.Level);
var software = EncoderSelector.Select(Request(VideoCodec.H264) with { PreferHardware = false }, providers, EncoderHost.Client);
Assert.Equal("Microsoft H.264", software.Capability!.Name);
var named = EncoderSelector.Select(Request(VideoCodec.H264) with { EncoderName = "Microsoft H.264" }, providers, EncoderHost.Client);
Assert.Equal("Microsoft H.264", named.Capability!.Name);
Assert.Equal(EncoderNotices.SoftwareOnly, named.Notices.Single().Key);
}
[Test]
public void HevcFallsBackToH264WhenNoEncoderExists()
{
var selection = EncoderSelector.Select(Request(VideoCodec.Hevc, bitDepth: 10, bitRate: 14_000_000), Client(SoftwareH264), EncoderHost.Client);
Assert.True(selection.IsReady);
Assert.Equal(VideoCodec.H264, selection.Settings.Codec);
Assert.Equal(8, selection.Settings.BitDepth);
Assert.Equal(CodecProfile.H264High, selection.Settings.Profile);
Assert.Equal(20_000_000L, selection.Settings.BitRate);
Assert.Equal(EncoderNotices.FallbackToH264, selection.Notices[0].Key);
Assert.SequenceEqual(new[] { "Hevc" }, selection.Notices[0].Args);
Assert.Contains(selection.Notices, n => n.Key == EncoderNotices.SoftwareOnly);
Assert.Equal(".mp4", Path.GetExtension(selection.Settings.OutputPath));
}
[Test]
public void TenBitNeedsATenBitEncoder()
{
var eightOnly = EncoderSelector.Select(Request(VideoCodec.Hevc, bitDepth: 10), Client(HardwareHevc8), EncoderHost.Client);
Assert.Equal(8, eightOnly.Settings.BitDepth);
Assert.Equal(CodecProfile.HevcMain, eightOnly.Settings.Profile);
Assert.Equal(EncoderNotices.TenBitUnavailable, eightOnly.Notices.Single().Key);
var tenBit = EncoderSelector.Select(Request(VideoCodec.Hevc, bitDepth: 10), Client(HardwareHevc8, HardwareHevc), EncoderHost.Client);
Assert.Equal("NVENC HEVC", tenBit.Capability!.Name);
Assert.Equal(10, tenBit.Settings.BitDepth);
Assert.Empty(tenBit.Notices);
}
[Test]
public void SizeIsCappedByEncoderAndLevel()
{
var encoder = EncoderSelector.Select(Request(VideoCodec.H264, 7680, 4320), Client(HardwareH264), EncoderHost.Client);
Assert.Equal((4096, 2304), (encoder.Settings.Width, encoder.Settings.Height));
Assert.Equal(EncoderNotices.ResolutionCappedByEncoder, encoder.Notices.Single().Key);
Assert.SequenceEqual(new[] { "NVENC H.264", "4096×2304" }, encoder.Notices.Single().Args);
var level = EncoderSelector.Select(Request(VideoCodec.Hevc, 7680, 4320, fps: new Rational(240, 1)), Client(HardwareHevc), EncoderHost.Client);
Assert.Equal(EncoderNotices.ResolutionCappedByLevel, level.Notices[0].Key);
Assert.Less(level.Settings.Width, 7680);
Assert.Equal(0, level.Settings.Width % 2);
Assert.Approximately(16.0 / 9, level.Settings.Width / (double)level.Settings.Height, 0.01);
Assert.True(CodecLimits.Check(VideoCodec.Hevc, level.Settings.Width, level.Settings.Height, 240, level.Settings.BitRate).Fits);
var odd = EncoderSelector.Select(Request(VideoCodec.H264, 1081, 607), Client(HardwareH264), EncoderHost.Client);
Assert.Equal((1080, 606), (odd.Settings.Width, odd.Settings.Height));
}
[Test]
public void BitRateIsCappedByTheHighestLevel()
{
var selection = EncoderSelector.Select(Request(VideoCodec.H264, 1920, 1080, bitRate: 2_000_000_000), Client(HardwareH264), EncoderHost.Client);
Assert.Equal(1_000_000_000L, selection.Settings.BitRate);
Assert.Equal(EncoderNotices.BitRateCapped, selection.Notices.Single().Key);
}
[Test]
public void NoVideoEncoderMeansUnavailable()
{
var selection = EncoderSelector.Select(Request(VideoCodec.Av1), [new ManagedEncoderProvider()], EncoderHost.Client);
Assert.Equal(EncoderSelectionStatus.Unavailable, selection.Status);
Assert.SequenceEqual(new[] { EncoderNotices.FallbackToH264, EncoderNotices.NoEncoder }, selection.Notices.Select(n => n.Key));
}
}
@@ -0,0 +1,61 @@
using Chronos.Core.Export;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Export;
public sealed class ExportEstimateTests
{
private static ExportWorkload Workload(int frames = 600, int width = 3840, int height = 2160, int flow = 0, int analysis = 0, bool hardware = true) =>
new(frames, frames, frames / 24.0, width, height, (long)width * height, flow, analysis, hardware);
private static ResolvedExport Preset(string id) => ExportResolver.FromPreset(ExportPresets.Find(id)!);
[Test]
public void VideoSizeIsBitRateTimesDuration()
{
var export = Preset("4k-h264");
var bytes = ExportEstimator.EstimateBytes(export, Workload());
var expected = 0.10 * 3840 * 2160 * 24 * 25 / 8 * 1.01;
Assert.Approximately(expected, bytes, 1);
Assert.InRange(bytes / 1e6, 60, 70); // ≈ 63 MB for 25 s of 4K at 19.9 Mb/s
}
[Test]
public void FrameBasedSizesScaleWithPicturesAndDepth()
{
var png8 = ExportResolver.FromPreset(ExportPresets.Find("png-sequence")!) with { Width = 1920, Height = 1080 };
var png16 = png8 with { BitDepth = 16 };
var w = Workload(240, 1920, 1080) with { OutputPeriods = 480 };
Assert.Equal(2 * ExportEstimator.EstimateBytes(png8, Workload(240, 1920, 1080)), ExportEstimator.EstimateBytes(png8, w));
Assert.Greater(ExportEstimator.EstimateBytes(png16, w), 2 * ExportEstimator.EstimateBytes(png8, w));
var gif = Preset("gif-preview");
Assert.Less(ExportEstimator.EstimateBytes(gif, Workload(240, 480, 270)), ExportEstimator.EstimateBytes(Preset("apng"), Workload(240, 480, 270)));
Assert.Monotonic(Enumerable.Range(1, 100).Select(q => ExportEstimator.JpegBitsPerPixel(q)), strict: true);
Assert.Approximately(2.8, ExportEstimator.JpegBitsPerPixel(90), 1e-12);
var mjpeg = Preset("mjpeg-avi");
Assert.Greater(ExportEstimator.EstimateBytes(mjpeg, Workload()), ExportEstimator.EstimateBytes(Preset("4k-hevc10-archive"), Workload()));
}
[Test]
public void TimeGrowsWithWorkAndCalibrationRescalesIt()
{
var export = Preset("4k-hevc");
var model = ThroughputModel.Default;
var plain = ExportEstimator.EstimateTime(export.Codec, Workload(), model);
Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(flow: 600), model).TotalSeconds, 2 * plain.TotalSeconds);
Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(analysis: 600), model).TotalSeconds, plain.TotalSeconds);
Assert.Greater(ExportEstimator.EstimateTime(export.Codec, Workload(hardware: false), model).TotalSeconds, plain.TotalSeconds);
Assert.InRange(plain.TotalSeconds, 30, 600); // ≈ 4 frames per second of 4K on the default model
var faster = model.Calibrate(plain, plain / 2, weight: 1);
Assert.Approximately(2.0, faster.Scale, 1e-9);
Assert.Approximately(plain.TotalSeconds / 2, ExportEstimator.EstimateTime(export.Codec, Workload(), faster).TotalSeconds, 1e-6);
Assert.Approximately(Math.Sqrt(2), model.Calibrate(plain, plain / 2).Scale, 1e-9);
Assert.Same(model, model.Calibrate(TimeSpan.Zero, plain));
var estimate = ExportEstimator.Estimate(export, Workload());
Assert.Equal(ExportEstimator.EstimateBytes(export, Workload()), estimate.Bytes);
Assert.Equal(plain, estimate.Time);
}
}
@@ -0,0 +1,83 @@
using Chronos.Core.Export;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Export;
public sealed class ExportNamingTests
{
private readonly TestContext _context;
public ExportNamingTests(TestContext context) => _context = context;
private static ExportNameContext Context(VideoCodec codec = VideoCodec.Hevc, string? title = "Harbour sunset") => new()
{
Date = new DateTime(2024, 6, 21, 19, 30, 0),
Title = title,
PresetName = "4K UHD HEVC",
Width = 3840,
Height = 2160,
FrameRate = Rational.Fps2997,
Codec = codec,
};
[Test]
public void DefaultTemplateNamesTheRender()
{
var name = ExportNaming.Expand("{date} {title} - {preset}", Context());
Assert.Equal("2024-06-21 Harbour sunset - 4K UHD HEVC", name.Name);
Assert.True(name.IsValid);
}
[Test]
public void EveryTokenExpands()
{
var name = ExportNaming.Expand("{date:yyyyMMdd}_{width}x{height}_{fps}fps_{codec}_{{raw}}", Context());
Assert.Equal("20240621_3840x2160_29.97fps_HEVC_{raw}", name.Name);
Assert.Equal("PNG", ExportNaming.CodecLabel(VideoCodec.PngSequence));
Assert.Equal("H.264", ExportNaming.CodecLabel(VideoCodec.H264));
}
[Test]
public void IllegalCharactersAndProblemsAreReported()
{
var name = ExportNaming.Expand("{title} {bogus} {", Context(title: "a/b:c*d?"));
Assert.Equal("a-b_c_d_ {", name.Name);
Assert.Count(2, name.Errors);
Assert.Equal("UnknownToken", name.Errors[0].Code);
Assert.Equal("UnclosedBrace", name.Errors[1].Code);
Assert.Equal(ExportNaming.FallbackName, ExportNaming.Expand("{title}", Context(title: null)).Name);
Assert.Equal("2024-06-21 - 4K UHD HEVC", ExportNaming.Expand("{date} {title} - {preset}", Context(title: null)).Name);
}
[Test]
public void CollisionsGetANumberedSuffix()
{
var dir = _context.CreateTempDirectory();
var first = ExportNaming.OutputPath(dir, "{title}", Context());
Assert.Equal(Path.Combine(dir, "Harbour sunset.mp4"), first);
File.WriteAllBytes(first, [1]);
var second = ExportNaming.OutputPath(dir, "{title}", Context());
Assert.Equal(Path.Combine(dir, "Harbour sunset (2).mp4"), second);
File.WriteAllBytes(second, [1]);
Assert.Equal(Path.Combine(dir, "Harbour sunset (3).mp4"), ExportNaming.OutputPath(dir, "{title}", Context()));
var sequence = ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence));
Assert.Equal(Path.Combine(dir, "Harbour sunset"), sequence);
Directory.CreateDirectory(sequence);
Assert.Equal(Path.Combine(dir, "Harbour sunset (2)"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.PngSequence)));
Assert.Equal(Path.Combine(dir, "Harbour sunset.gif"), ExportNaming.OutputPath(dir, "{title}", Context(VideoCodec.Gif)));
}
[Test]
public void ProjectSettingsChooseFolderAndTemplate()
{
var exports = _context.CreateTempDirectory("exports");
var custom = _context.CreateTempDirectory("custom");
var byDefault = ExportNaming.OutputPath(new ExportSettings(), exports, Context());
Assert.Equal(Path.Combine(exports, "2024-06-21 Harbour sunset - 4K UHD HEVC.mp4"), byDefault);
var chosen = ExportNaming.OutputPath(new ExportSettings { Folder = custom, NameTemplate = "{title} {width}" }, exports, Context());
Assert.Equal(Path.Combine(custom, "Harbour sunset 3840.mp4"), chosen);
}
}
@@ -0,0 +1,131 @@
using Chronos.Core.Export;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Export;
public sealed class ExportResolverTests
{
private static ExportSettings Export(string preset, ExportOverrides? overrides = null) =>
new() { Preset = new Auto<string>().WithManual(preset), Overrides = overrides ?? new ExportOverrides() };
[Test]
public void EveryBuiltInPresetResolvesToItself()
{
foreach (var preset in ExportPresets.BuiltIn)
{
var resolved = ExportResolver.Resolve(Export(preset.Id));
Assert.Equal(preset.Id, resolved.PresetId);
Assert.False(resolved.IsCustom);
Assert.Equal(preset.NameKey, resolved.NameKey);
Assert.Equal(preset.Codec, resolved.Codec);
Assert.Empty(resolved.Warnings);
}
}
[Test]
public void EditingAValueMakesTheExportCustom()
{
var resolved = ExportResolver.Resolve(Export("4k-hevc", new ExportOverrides { BitRate = 50_000_000 }));
Assert.True(resolved.IsCustom);
Assert.Equal(ExportResolver.CustomId, resolved.PresetId);
Assert.Equal("4k-hevc", resolved.BasePresetId);
Assert.Null(resolved.NameKey);
Assert.Equal(50_000_000L, resolved.EffectiveBitRate(3840, 2160));
Assert.Equal(3840, resolved.Width);
}
[Test]
public void ValuesEqualToThePresetRestoreItsName()
{
var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides
{
Codec = "h.264",
Container = "mp4",
Width = 1920,
Height = 1080,
FrameRate = "30",
BitRate = 6_220_800, // the preset's 0.10 bpp at 1920×1080×30
GopFrames = 30,
Profile = "H264High",
RateControl = "vbr",
}));
Assert.Equal("1080p-h264", resolved.PresetId);
Assert.Empty(resolved.Warnings);
}
[Test]
public void ValuesEqualToAnotherPresetTakeItsName()
{
var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { FrameRate = "60" }));
Assert.Equal("1080p60", resolved.PresetId);
Assert.Equal(60, resolved.GopFrames);
Assert.Equal("1080p-h264", resolved.BasePresetId);
}
[Test]
public void FractionalRatesAndGopFollowTheOverride()
{
var resolved = ExportResolver.Resolve(Export("4k-h264", new ExportOverrides { FrameRate = "24000/1001" }));
Assert.True(resolved.IsCustom);
Assert.Equal(Rational.Fps23976, resolved.FrameRate);
Assert.Equal(24, resolved.GopFrames);
var settings = resolved.ToEncodeSettings("x.mp4", 3840, 2160);
Assert.Equal(24, settings.GopLength);
Assert.Equal((long)Math.Round(0.10 * 3840 * 2160 * 24000 / 1001.0), settings.BitRate);
Assert.Equal(CodecProfile.H264High, settings.Profile);
}
[Test]
public void BadOverridesAreIgnoredWithWarnings()
{
var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { Codec = "divx", FrameRate = "fast", Container = "avi", Profile = "ultra", RateControl = "magic" }));
Assert.Equal("1080p-h264", resolved.PresetId);
Assert.SequenceEqual(new[] { "Export.Warning.UnknownCodec", "Export.Warning.ContainerIgnored", "Export.Warning.UnknownProfile", "Export.Warning.UnknownFrameRate", "Export.Warning.UnknownRateControl" }, resolved.Warnings);
}
[Test]
public void UnknownOrCustomSelectionsStartFromTheDefaultPreset()
{
var unknown = ExportResolver.Resolve(Export("deleted-user-preset"));
Assert.Equal(ExportResolver.DefaultPresetId, unknown.PresetId);
Assert.Contains("Export.Warning.UnknownPreset", unknown.Warnings);
var custom = ExportResolver.Resolve(Export("custom", new ExportOverrides { Codec = "png", Width = 0, Height = 0, BitDepth = 16, FrameRate = "30", GopFrames = 30, BFrames = 0, Quality = 92 }));
Assert.Empty(custom.Warnings);
Assert.Equal(VideoCodec.PngSequence, custom.Codec);
Assert.True(custom.IsCustom);
var auto = ExportResolver.Resolve(new ExportSettings());
Assert.Equal(ExportResolver.DefaultPresetId, auto.PresetId);
}
[Test]
public void ChangingTheCodecResetsCodecSpecificValues()
{
var resolved = ExportResolver.Resolve(Export("1080p-h264", new ExportOverrides { Codec = "HEVC" }));
Assert.Equal(VideoCodec.Hevc, resolved.Codec);
Assert.Equal(CodecProfile.Auto, resolved.Profile);
Assert.Equal((long)Math.Round(0.07 * 1920 * 1080 * 30), resolved.EffectiveBitRate(1920, 1080));
Assert.True(resolved.IsCustom);
Assert.True(ExportResolver.TryParseCodec("TIFF-16", out var tiff) && tiff == VideoCodec.Tiff16Sequence);
Assert.False(ExportResolver.TryParseCodec("", out _));
}
[Test]
public void FrameRateTextRoundTrips()
{
Assert.True(FrameRateText.TryParse("30000/1001", out var ntsc));
Assert.Equal(Rational.Fps2997, ntsc);
Assert.True(FrameRateText.TryParse("29.97", out var decimalNtsc));
Assert.Equal(Rational.Fps2997, decimalNtsc);
Assert.True(FrameRateText.TryParse(" 25 ", out var pal));
Assert.Equal("25", FrameRateText.Format(pal));
Assert.Equal("24000/1001", FrameRateText.Format(Rational.Fps23976));
Assert.True(FrameRateText.AreEqual(new Rational(48000, 2002), Rational.Fps23976));
Assert.False(FrameRateText.TryParse("0", out _));
Assert.False(FrameRateText.TryParse("1/0", out _));
Assert.False(FrameRateText.TryParse(null, out _));
}
}
@@ -0,0 +1,213 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Render.Diagnostics;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
using Chronos.Testing;
namespace Chronos.Core.Tests.Export;
public sealed class ManagedEncoderTests
{
private const int Width = 48;
private const int Height = 32;
private static readonly Rational Fps = new(30, 1);
private readonly TestContext _context;
public ManagedEncoderTests(TestContext context) => _context = context;
private static ImageBuffer Frame(int seed)
{
var image = new ImageBuffer(Width, Height);
for (var y = 0; y < Height; y++)
{
for (var x = 0; x < Width; x++)
{
image[0, x, y] = (x + seed * 7) % Width / (float)Width;
image[1, x, y] = y / (float)Height * 0.8f;
image[2, x, y] = (x * y + seed * 13) % 23 / 22f * 0.5f;
}
}
return image;
}
private static EncodeSettings Settings(string path, VideoCodec codec, int bitDepth = 8) =>
new() { OutputPath = path, Codec = codec, Width = Width, Height = Height, FrameRate = Fps, BitDepth = bitDepth, Quality = 95 };
/// <summary>Three distinct frames lasting one, two and one periods.</summary>
private static void Encode(IVideoEncoderSession session)
{
long[] durations = [3000, 6000, 3000];
for (var i = 0; i < 3; i++)
{
using var frame = Frame(i);
session.WriteFrame(frame, durations[i]);
}
session.Complete();
}
private static double Psnr(ImageBuffer expected, ImageBuffer actual)
{
var a = PixelConvert.ToInterleaved8(expected, 3);
var b = PixelConvert.ToInterleaved8(actual, 3);
double sum = 0;
for (var i = 0; i < a.Length; i++) sum += (a[i] - b[i]) * (a[i] - b[i]);
return sum == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255 / (sum / a.Length));
}
[Test]
public void MjpegAviRepeatsHeldFramesOnTheConstantRateGrid()
{
var dir = _context.CreateTempDirectory();
var path = Path.Combine(dir, "out.avi");
using (var session = new ManagedEncoderProvider().Open(Settings(path, VideoCodec.Mjpeg))) Encode(session);
var avi = AviReader.Read(File.ReadAllBytes(path));
Assert.Equal(4, avi.Frames.Count);
Assert.Equal(4, avi.HeaderFrames);
Assert.Equal(4, avi.IndexEntries);
Assert.Equal(Fps, avi.FrameRate);
Assert.BytesEqual(avi.Frames[1], avi.Frames[2]);
using var decoded = JpegDecoder.DecodeToLinear(avi.Frames[3]);
using var expected = Frame(2);
Assert.Greater(Psnr(expected, decoded), 35);
Assert.SequenceEqual(new[] { "out.avi" }, Directory.GetFiles(dir).Select(Path.GetFileName));
}
[Theory]
[Case(VideoCodec.JpegSequence, 8)]
[Case(VideoCodec.PngSequence, 8)]
[Case(VideoCodec.PngSequence, 16)]
[Case(VideoCodec.Tiff16Sequence, 16)]
[Case(VideoCodec.LinearDngSequence, 16)]
public void SequencesWriteNumberedFilesIntoTheOutputFolder(VideoCodec codec, int bitDepth)
{
var dir = _context.CreateTempDirectory();
var folder = Path.Combine(dir, "Harbour - sequence");
using (var session = new ManagedEncoderProvider().Open(Settings(folder, codec, bitDepth))) Encode(session);
Assert.SequenceEqual(new[] { "Harbour - sequence" }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));
var ext = VideoCodecInfo.FileExtension(codec);
var files = Directory.GetFiles(folder).Order(StringComparer.Ordinal).ToArray();
Assert.SequenceEqual(Enumerable.Range(1, 4).Select(i => $"Harbour - sequence_{i:D6}{ext}"), files.Select(Path.GetFileName));
Assert.BytesEqual(File.ReadAllBytes(files[1]), File.ReadAllBytes(files[2]));
using var expected = Frame(2);
var bytes = File.ReadAllBytes(files[3]);
switch (codec)
{
case VideoCodec.JpegSequence:
using (var jpeg = JpegDecoder.DecodeToLinear(bytes)) Assert.Greater(Psnr(expected, jpeg), 35);
break;
case VideoCodec.PngSequence when bitDepth == 8:
Assert.BytesEqual(PixelConvert.ToInterleaved8(expected, 3), PngDecoder.Decode(bytes).Pixels8);
break;
case VideoCodec.PngSequence:
Assert.SequenceEqual(PixelConvert.ToInterleaved16(expected, 3), PngDecoder.Decode(bytes).Pixels16!);
break;
case VideoCodec.Tiff16Sequence:
using (var tiff = TiffImageReader.Decode(bytes))
{
for (var i = 0; i < tiff.Data.Length; i += 7) Assert.Approximately(expected.Data[i], tiff.Data[i], 2e-4);
}
break;
default:
using (var dng = TiffImageReader.Decode(bytes))
{
for (var i = 0; i < dng.Data.Length; i += 7) Assert.Approximately(expected.Data[i], dng.Data[i], 1.0 / 65535);
}
break;
}
}
[Theory]
[Case(VideoCodec.Gif)]
[Case(VideoCodec.Apng)]
public void AnimationsKeepVariableDurations(VideoCodec codec)
{
var dir = _context.CreateTempDirectory();
var path = Path.Combine(dir, "out" + VideoCodecInfo.FileExtension(codec));
using (var session = new ManagedEncoderProvider().Open(Settings(path, codec))) Encode(session);
var bytes = File.ReadAllBytes(path);
var animation = codec == VideoCodec.Gif ? GifReader.Decode(bytes) : ApngReader.Decode(bytes);
Assert.Equal(3, animation.Frames.Count);
if (codec == VideoCodec.Apng)
{
Assert.SequenceEqual(new long[] { 3000, 6000, 3000 }, animation.Frames.Select(f => f.Duration90k));
using var decoded = animation.ToLinear(1);
using var expected = Frame(1);
Assert.True(Psnr(expected, decoded) > 60);
}
else
{
Assert.Approximately(12000, animation.Duration90k, 900);
using var decoded = animation.ToLinear(1);
using var expected = Frame(1);
Assert.Greater(Psnr(expected, decoded), 22);
}
}
[Theory]
[Case(VideoCodec.Mjpeg)]
[Case(VideoCodec.PngSequence)]
[Case(VideoCodec.Gif)]
[Case(VideoCodec.Apng)]
public void DisposingWithoutCompleteLeavesNothing(VideoCodec codec)
{
var dir = _context.CreateTempDirectory();
var path = Path.Combine(dir, "partial" + (VideoCodecInfo.DefaultContainer(codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(codec)));
using (var session = new ManagedEncoderProvider().Open(Settings(path, codec)))
{
using var frame = Frame(0);
session.WriteFrame(frame, 3000);
session.WriteFrame(frame, 3000);
}
Assert.Empty(Directory.GetFileSystemEntries(dir));
}
[Test]
public void SequenceWriteFailuresSurfaceAndLeaveNothing()
{
var dir = _context.CreateTempDirectory();
var session = new ManagedEncoderProvider().Open(Settings(Path.Combine(dir, "seq"), VideoCodec.PngSequence));
using var frame = Frame(0);
session.WriteFrame(frame, 3000);
Directory.Delete(Directory.GetDirectories(dir, ".seq.*.tmp").Single(), recursive: true);
Exception? error = null;
try
{
for (var i = 0; i < 20; i++) session.WriteFrame(frame, 3000);
session.Complete();
}
catch (Exception ex)
{
error = ex;
}
session.Dispose();
Assert.True(error is IOException, $"unexpected {error?.GetType().Name}");
Assert.Empty(Directory.GetFileSystemEntries(dir));
}
[Test]
public void SessionsValidateTheirInput()
{
var dir = _context.CreateTempDirectory();
var provider = new ManagedEncoderProvider();
using (var session = provider.Open(Settings(Path.Combine(dir, "a.avi"), VideoCodec.Mjpeg)))
{
using var wrong = new ImageBuffer(Width + 2, Height);
Assert.Throws<ArgumentException>(() => session.WriteFrame(wrong, 3000));
Assert.Throws<InvalidOperationException>(session.Complete);
}
Assert.Empty(Directory.GetFileSystemEntries(dir));
var existing = Directory.CreateDirectory(Path.Combine(dir, "taken")).FullName;
Assert.Throws<IOException>(() => provider.Open(Settings(existing, VideoCodec.PngSequence)));
Assert.False(provider.CanEncode(Settings(Path.Combine(dir, "x.mp4"), VideoCodec.H264)));
Assert.False(provider.CanEncode(Settings(Path.Combine(dir, "x"), VideoCodec.PngSequence, bitDepth: 10)));
Assert.True(provider.CanEncode(Settings(Path.Combine(dir, "x"), VideoCodec.PngSequence, bitDepth: 16)));
Assert.Throws<NotSupportedException>(() => provider.Open(Settings(Path.Combine(dir, "x.mp4"), VideoCodec.Hevc)));
Assert.Equal(7, provider.Capabilities.Count);
Assert.True(provider.Capabilities.All(c => !c.Hardware && VideoCodecInfo.IsManaged(c.Codec)));
}
}