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,175 @@
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Text.RegularExpressions;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Core.Tests.Analysis.Deep;
using Chronos.Testing;
namespace Chronos.Core.Tests.Advice;
public sealed partial class AdvisorLocalizationTests(TestContext context)
{
private static readonly CultureInfo English = CultureInfo.GetCultureInfo("en");
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it");
private const string LogPrefix = "Advisor.Log.";
[Test]
public void EveryAdvisorKeyHasEnglishAndItalianTextWithTheSamePlaceholders()
{
var manager = new ResourceManager("Chronos.Core.i18n.Advisor", typeof(Loc).Assembly);
var english = Entries(manager.GetResourceSet(CultureInfo.InvariantCulture, createIfNotExists: true, tryParents: false)!);
var italian = Entries(manager.GetResourceSet(Italian, createIfNotExists: true, tryParents: false)!);
// Job log lines (Advisor.Log.*) are written by the analysis job handlers in Chronos.Data, not by the advisor itself.
var keys = Keys(typeof(AdvisorKeys)).Concat(Keys(typeof(FindingKeys))).Concat(Keys(typeof(DeepFindingKeys)))
.Concat(english.Keys.Where(k => k.StartsWith(LogPrefix, StringComparison.Ordinal))).ToList();
Assert.Greater(keys.Count, 90);
var forms = 0;
foreach (var key in keys)
{
// A key that counts something is a plural stem (BRIEF §16) whose count is its first argument.
string[] names = english.ContainsKey(key) ? [key] : [key + ".one", key + ".other"];
if (names.Length == 2) Assert.Contains("0", Placeholders(english.GetValueOrDefault(key + ".other") ?? string.Empty), $"{key}.other counts with {{0}}");
foreach (var name in names)
{
Assert.True(english.TryGetValue(name, out var en), $"English text missing for {name}");
Assert.True(italian.TryGetValue(name, out var it), $"Italian text missing for {name}");
Assert.SequenceEqual(Placeholders(en!), Placeholders(it!), name);
Assert.LessOrEqual(en!.Length, 200);
forms++;
}
}
Assert.Equal(english.Count, forms);
}
[Test]
public void ACountOfOneReadsInTheSingularInBothLanguages()
{
Assert.Equal("1 frame is black (lens cap or missed exposure).", Loc.Text(DeepFindingKeys.BlackFrames, [1.0], English));
Assert.Equal("3 frames are black (lens cap or missed exposure).", Loc.Text(DeepFindingKeys.BlackFrames, [3.0], English));
Assert.Equal("1 fotogramma è nero (tappo sull'obiettivo o scatto mancato).", Loc.Text(DeepFindingKeys.BlackFrames, [1.0], Italian));
Assert.Equal("The lens changes once.", Loc.Text(FindingKeys.LensChanged, [1], English));
Assert.Equal("L'obiettivo cambia 2 volte.", Loc.Text(FindingKeys.LensChanged, [2], Italian));
Assert.Equal("2 exposure changes reached the pixels: each is spread over a smooth transition.", Loc.Text(AdvisorKeys.HolyGrailReceived, [2], English));
// Advisor windows are measured in tenths of a frame: a fraction takes the plural.
Assert.Equal("Flicker stays correlated over 1.5 frames: a 7-frame window spans four times that.", Loc.Text(AdvisorKeys.WindowCorrelation, [1.5, 7], English));
Assert.Equal("Flicker stays correlated over 1 frame: a 5-frame window spans four times that.", Loc.Text(AdvisorKeys.WindowCorrelation, [1.0, 5], English));
// Keys without a count read as before.
Assert.Equal("Clouds cover about 42% of the sky on average.", Loc.Text(DeepFindingKeys.Clouds, [42.0], English));
}
[Test]
public void ASingleExposureChangeHasNoSpacing()
{
var frames = Enumerable.Range(0, 20).Select(i => new LightFrame
{
Index = i,
CapturedAt = new DateTime(2026, 6, 1, 20, 0, 0, DateTimeKind.Utc).AddSeconds(10 * i),
ExposureTime = i < 12 ? 1.0 / 250 : 1.0 / 125,
FNumber = 8,
Iso = 100,
}).ToList();
var single = LightAnalyzer.Analyze(frames).Findings.Single(f => f.Key == FindingKeys.ExposureStep);
Assert.SequenceEqual([12], single.Frames);
Assert.Equal("One exposure change of -1.0 EV.", Loc.Text(single.Key, single.Arguments, English));
Assert.Equal("Un solo cambio di esposizione di -1,0 EV.", Loc.Text(single.Key, single.Arguments, Italian));
Assert.DoesNotContain(FindingKeys.ExposureSteps, LightAnalyzer.Analyze(frames).Findings.Select(f => f.Key));
}
[Test]
public async Task EveryReasonAndFindingOfTheGoldenScenesFormatsInBothLanguages()
{
var scenes = new List<(SyntheticFrameSource Source, DeepAnalysisReport? Deep)>
{
(new SyntheticFrameSource(DeepScenes.NightSky()), await DeepReports.Night),
(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), await DeepReports.NightJitter),
(new SyntheticFrameSource(DeepScenes.HolyGrail()), await DeepReports.HolyGrail),
(new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true }, null),
};
var rendered = 0;
foreach (var (source, deep) in scenes)
{
var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
var light = LightAnalyzer.Analyze(frames);
var sequence = new SequenceContext { FrameCount = frames.Count, SourceWidth = 6000, SourceHeight = 4000, MedianExposureSeconds = 1.0 / 250 };
var result = Advisor.Recommend(light, deep, sequence);
foreach (var r in result.Recommendations) rendered += Render(r.ReasonKey, [.. r.ReasonArgs]);
foreach (var f in result.Findings) rendered += Render(f.Key, f.Arguments);
foreach (var p in SequencePresets.Generate(light, deep, sequence))
{
rendered += Render(p.NameKey, [.. p.NameArgs]);
rendered += Render(p.ReasonKey!, [.. p.ReasonArgs]);
}
// Stored reasons (culture-neutral strings) render with the current culture's numbers.
var applied = Advisor.Apply(new ProjectSettings(), result);
Assert.DoesNotContain('⟦', Advisor.Explain(applied.Exposure.HolyGrail.ReasonKey!, applied.Exposure.HolyGrail.ReasonArgs));
}
context.Log($"{rendered} texts rendered");
Assert.Greater(rendered, 80);
}
[Test]
public void StoredNumericArgumentsAreLocalisedWhenExplained()
{
var text = Format(Loc.Get(AdvisorKeys.DeflickerOn, Italian)!, Italian, 0.125);
Assert.Contains("0,125", text);
Assert.Contains("0.125", Format(Loc.Get(AdvisorKeys.DeflickerOn, English)!, English, 0.125));
}
[Test]
public async Task PresetsRoundTripAsJsonAndSaveAsUserPresets()
{
var source = new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2);
var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
var presets = SequencePresets.Generate(LightAnalyzer.Analyze(frames), await DeepReports.NightJitter, new SequenceContext { SourceWidth = 6000, SourceHeight = 4000 });
foreach (var preset in presets)
{
var json = preset.ToJson();
Assert.Equal(json, SequencePreset.FromJson(json).ToJson());
}
var user = presets[0].AsUserPreset(" My night ");
Assert.True(user.IsUser);
Assert.Equal("My night", user.Name);
Assert.NotEqual(presets[0].Id, user.Id);
var restored = SequencePreset.FromJson(user.ToJson());
Assert.Equal("My night", restored.DisplayName());
Assert.Equal(presets[0].Settings.ToJson(), restored.Settings.ToJson());
Assert.Equal(presets[0].ExportPresetId, restored.ExportPresetId);
}
private static int Render(string key, object?[] args)
{
foreach (var culture in new[] { English, Italian })
{
var text = Loc.Text(key, args, culture);
Assert.False(text.Contains('⟦'), $"{key} has no {culture.Name} text");
Assert.False(text.Contains('{'), $"{key} left a placeholder: {text}");
}
return 1;
}
private static string Format(string format, CultureInfo culture, params object?[] args) => string.Format(culture, format, args);
private static Dictionary<string, string> Entries(ResourceSet set)
{
var entries = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (DictionaryEntry entry in set) entries[(string)entry.Key] = (string)entry.Value!;
return entries;
}
private static IEnumerable<string> Keys(Type type) =>
type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string) && f.Name != nameof(AdvisorKeys.MissingPrefix)).Select(f => (string)f.GetRawConstantValue()!)
.Concat(type.GetProperties(BindingFlags.Public | BindingFlags.Static).Where(p => p.PropertyType == typeof(string)).Select(p => (string)p.GetValue(null)!));
private static IEnumerable<string> Placeholders(string text) => PlaceholderRegex().Matches(text).Select(m => m.Groups[1].Value).Order();
[GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")]
private static partial Regex PlaceholderRegex();
}
@@ -0,0 +1,361 @@
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Mathematics;
using Chronos.Core.Project;
using Chronos.Core.Tests.Analysis.Deep;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.Core.Tests.Advice;
// The class shares its name with the namespace, which an enclosing Chronos.Core.* namespace would resolve first.
public sealed class AdvisorTests(TestContext context)
{
[Test]
public async Task NightSkyGetsTheNightPresetDeflickerAndNoStabilisation()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky()));
var deep = await DeepReports.Night;
var result = Advisor.Recommend(light, deep, sequence);
Log(result);
Assert.Equal(true, Value(result, AdvisorParameters.Deflicker));
Assert.Equal(15, Value(result, AdvisorParameters.DeflickerWindow));
Assert.Equal(false, Value(result, AdvisorParameters.Stabilize));
Assert.Equal(AdvisorKeys.StabilizeOff, result.Find(AdvisorParameters.Stabilize)!.ReasonKey);
Assert.Equal("3840x2160", Value(result, AdvisorParameters.Resolution));
Assert.Equal("4k-hevc10-archive", Value(result, AdvisorParameters.ExportPreset));
// 15 s exposures every 20 s are a 270° shutter: already beyond the 180° target.
Assert.Equal(false, Value(result, AdvisorParameters.MotionBlur));
Assert.Equal(AdvisorKeys.MotionBlurAlready, result.Find(AdvisorParameters.MotionBlur)!.ReasonKey);
Assert.Equal(TimingMode.Constant, Value(result, AdvisorParameters.TimingMode));
Assert.Equal("24", Value(result, AdvisorParameters.FrameRate));
Assert.Equal(AdvisorKeys.WindowMinimum, result.Find(AdvisorParameters.DeflickerWindow)!.ReasonKey);
var presets = SequencePresets.Generate(light, deep, sequence);
var night = presets[0];
Assert.Equal("night-sky", night.Id);
Assert.Equal(AdvisorKeys.PresetNightSky, night.NameKey);
Assert.SequenceEqual(["4K", "HEVC Main10", "24", "15"], night.NameArgs);
Assert.Equal("4k-hevc10-archive", night.ExportPresetId);
Assert.Equal("24", night.Settings.Timing.FrameRate.Resolve("30"));
Assert.True(night.Settings.Exposure.Deflicker.Resolve(false));
Assert.False(night.Settings.Motion.Stabilize.Resolve(true));
Assert.Equal("social-vertical", presets[^1].Id);
Assert.DoesNotContain("holy-grail", presets.Select(p => p.Id));
}
[Test]
public async Task InjectedJitterTurnsStabilisationOn()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2));
var deep = await DeepReports.NightJitter;
var result = Advisor.Recommend(light, deep, sequence);
var stabilize = result.Find(AdvisorParameters.Stabilize)!;
Assert.Equal(true, stabilize.Value);
Assert.Equal(AdvisorKeys.StabilizeOn, stabilize.ReasonKey);
// 2 px RMS on a 160-px source is 48 px at 3840 px.
Assert.InRange((double)stabilize.ReasonArgs[0], 40, 60);
Assert.Equal(12.0, Value(result, AdvisorParameters.StabilizeSmoothing));
var night = SequencePresets.Generate(light, deep, sequence)[0];
Assert.Equal(AdvisorKeys.PresetNightSkyStabilised, night.NameKey);
Assert.False(night.Settings.Motion.Stabilize.IsAuto);
Assert.True(night.Settings.Motion.Stabilize.Manual);
}
[Test]
public async Task HolyGrailSunsetGetsTransitionsOfHalfTheStepSpacing()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()));
var deep = await DeepReports.HolyGrail;
var result = Advisor.Recommend(light, deep, sequence);
Log(result);
var holyGrail = result.Find(AdvisorParameters.HolyGrail)!;
Assert.Equal(true, holyGrail.Value);
Assert.Equal(AdvisorKeys.HolyGrailReceived, holyGrail.ReasonKey);
Assert.SequenceEqual([5], holyGrail.ReasonArgs.Cast<int>());
var transition = result.Find(AdvisorParameters.TransitionLength)!;
Assert.Equal(20, transition.Value);
Assert.Equal(AdvisorKeys.TransitionSpacing, transition.ReasonKey);
Assert.SequenceEqual([40.0, 20.0], transition.ReasonArgs.Select(Convert.ToDouble));
Assert.Equal(false, Value(result, AdvisorParameters.MotionBlur));
Assert.Equal(AdvisorKeys.MotionBlurLittle, result.Find(AdvisorParameters.MotionBlur)!.ReasonKey);
var presets = SequencePresets.Generate(light, deep, sequence);
var grail = presets[0];
Assert.Equal("holy-grail", grail.Id);
Assert.SequenceEqual(["4K", "HEVC", "30", "20"], grail.NameArgs);
Assert.Equal("4k-hevc", grail.ExportPresetId);
Assert.True(grail.Settings.Exposure.HolyGrail.Resolve(false));
Assert.Equal(20, grail.Settings.Exposure.TransitionLength.Resolve(0));
// Without pixels the metadata steps are trusted, with the same spacing rule and less confidence.
var metadataOnly = Advisor.Recommend(light, null, sequence);
Assert.Equal(AdvisorKeys.HolyGrailMetadata, metadataOnly.Find(AdvisorParameters.HolyGrail)!.ReasonKey);
Assert.Equal(20, Value(metadataOnly, AdvisorParameters.TransitionLength));
Assert.Less(metadataOnly.Find(AdvisorParameters.HolyGrail)!.Confidence, holyGrail.Confidence);
}
[Test]
public void IrregularCadenceWithNightlyPausesIsAdaptive()
{
const double night = 14 * 3600;
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = 300,
IntervalSeconds = 600,
IntervalJitterSeconds = 20,
TimeShifts = [new(60, night), new(120, night), new(180, night), new(240, night)],
}));
var (light, sequence) = Inputs(source);
var result = Advisor.Recommend(light, null, sequence);
Log(result);
var mode = result.Find(AdvisorParameters.TimingMode)!;
Assert.Equal(TimingMode.Adaptive, mode.Value);
Assert.Equal(AdvisorKeys.TimingSessions, mode.ReasonKey);
Assert.Equal(5, mode.ReasonArgs[0]);
Assert.Approximately(14.2, (double)mode.ReasonArgs[1], 0.051);
Assert.Equal("30", Value(result, AdvisorParameters.FrameRate));
// Pixel-based parameters wait for the deep analysis.
foreach (var parameter in new[] { AdvisorParameters.Deflicker, AdvisorParameters.Stabilize, AdvisorParameters.Regions, AdvisorParameters.Hero })
{
var missing = result.Find(parameter)!;
Assert.True(missing.IsMissingData);
Assert.Equal(AdvisorKeys.MissingDeep, missing.ReasonKey);
}
var presets = SequencePresets.Generate(light, null, sequence);
Assert.SequenceEqual(["construction", "social-vertical"], presets.Select(p => p.Id));
Assert.Equal(TimingMode.Adaptive, presets[0].Settings.Timing.Mode.Resolve(TimingMode.Constant));
Assert.Equal("1080p-h264", presets[0].ExportPresetId);
}
[Test]
public async Task SparseGapsWithStillContentAreInterpolated()
{
var gapped = SyntheticSequence.Create(DeepScenes.HolyGrail().Options with { TimeShifts = [new(100, 40)] });
var (light, sequence) = Inputs(new SyntheticFrameSource(gapped));
var result = Advisor.Recommend(light, await DeepReports.HolyGrail, sequence);
Assert.Equal(TimingMode.Interpolated, Value(result, AdvisorParameters.TimingMode));
Assert.Equal(FlowQualitySetting.Best, Value(result, AdvisorParameters.FlowQuality));
Assert.Equal(TimingMode.Constant, Value(Advisor.Recommend(light, null, sequence), AdvisorParameters.TimingMode));
}
[Test]
public async Task PeriodicFlickerWindowIsFourPeriods()
{
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = 240,
FlickerEv = 0.15,
FlickerPeriodFrames = 8,
}));
var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options);
var (light, sequence) = Inputs(source);
var window = Advisor.Recommend(light, deep, sequence).Find(AdvisorParameters.DeflickerWindow)!;
Assert.Equal(33, window.Value);
Assert.Equal(AdvisorKeys.WindowPeriod, window.ReasonKey);
Assert.Equal(8.0, window.ReasonArgs[0]);
}
[Test]
public void MissingExposureMetadataIsReportedAndChangesNothing()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true });
Assert.True(light.ExposureValues.All(v => v is null));
var result = Advisor.Recommend(light, null, sequence);
foreach (var parameter in new[] { AdvisorParameters.HolyGrail, AdvisorParameters.TransitionLength, AdvisorParameters.TargetShutterAngle, AdvisorParameters.MotionBlur })
{
var missing = result.Find(parameter)!;
Assert.Null(missing.Value);
Assert.Equal(0.0, missing.Confidence);
Assert.Equal(AdvisorKeys.MissingExposure, missing.ReasonKey);
}
var advised = new ProjectSettings
{
Exposure = new ExposureSettings
{
HolyGrail = new Auto<bool>().WithAdvice(true, AdvisorKeys.HolyGrailReceived, "5"),
TransitionLength = new Auto<int>().WithAdvice(20, AdvisorKeys.TransitionSpacing, "40", "20"),
},
};
var applied = Advisor.Apply(advised, result);
Assert.Same(advised.Exposure.HolyGrail, applied.Exposure.HolyGrail);
Assert.Same(advised.Exposure.TransitionLength, applied.Exposure.TransitionLength);
Assert.Empty(Advisor.Optimise(AdvisorSection.Exposure, advised, result).Changes.Where(c => c.Parameter is AdvisorParameters.HolyGrail or AdvisorParameters.TransitionLength));
// A fresh project keeps its values and learns why there is no advice.
var fresh = Advisor.Apply(new ProjectSettings(), result);
Assert.False(fresh.Exposure.HolyGrail.AutoValue);
Assert.Equal(AdvisorKeys.MissingExposure, fresh.Exposure.HolyGrail.ReasonKey);
Assert.Equal(0, fresh.Exposure.TransitionLength.AutoValue);
Assert.Equal(0.0, fresh.Motion.TargetShutterAngle.AutoValue);
Assert.Equal(AdvisorKeys.MissingExposure, fresh.Motion.TargetShutterAngle.ReasonKey);
}
[Test]
public async Task ApplyNeverOverwritesManualValues()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky()));
var result = Advisor.Recommend(light, await DeepReports.Night, sequence);
var manual = new ProjectSettings
{
Timing = new TimingSettings { FrameRate = new Auto<string>().WithManual("50") },
Exposure = new ExposureSettings
{
Deflicker = new Auto<bool>().WithManual(false),
DeflickerWindow = new Auto<int>().WithManual(99),
},
HeroFrame = 7,
ExcludedFrames = [3],
};
var applied = Advisor.Apply(manual, result);
Assert.False(applied.Exposure.Deflicker.IsAuto);
Assert.False(applied.Exposure.Deflicker.Resolve(true));
Assert.True(applied.Exposure.Deflicker.AutoValue);
Assert.Equal(99, applied.Exposure.DeflickerWindow.Resolve(0));
Assert.Equal(15, applied.Exposure.DeflickerWindow.AutoValue);
Assert.Equal("50", applied.Timing.FrameRate.Resolve("30"));
Assert.Equal("24", applied.Timing.FrameRate.AutoValue);
Assert.Equal(7, applied.HeroFrame);
Assert.SequenceEqual([3], applied.ExcludedFrames);
// Auto values carry the reason with culture-neutral arguments.
Assert.Equal(AdvisorKeys.WindowMinimum, applied.Exposure.DeflickerWindow.ReasonKey);
Assert.SequenceEqual(["15"], applied.Exposure.DeflickerWindow.ReasonArgs!);
Assert.True(applied.Motion.Stabilize.ReasonKey == AdvisorKeys.StabilizeOff && !applied.Motion.Stabilize.AutoValue);
Assert.Equal(applied.ToJson(), ProjectSettings.FromJson(applied.ToJson()).ToJson());
}
[Test]
public async Task OptimiseTakesModuleDecisionsAndReportsChanges()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2));
var result = Advisor.Recommend(light, await DeepReports.NightJitter, sequence);
var settings = new ProjectSettings
{
Motion = new MotionSettings { Stabilize = new Auto<bool>().WithManual(false), StabilizeSmoothing = new Auto<double>().WithManual(30) },
ExcludedFrames = [3],
};
var motion = Advisor.Optimise(AdvisorSection.Motion, settings, result);
Assert.True(motion.Settings.Motion.Stabilize.IsAuto);
Assert.True(motion.Settings.Motion.Stabilize.Resolve(false));
Assert.Equal(30.0, motion.Settings.Motion.StabilizeSmoothing.Resolve(12));
var change = motion.Changes.Single(c => c.Parameter == AdvisorParameters.Stabilize);
Assert.Equal(false, change.Before);
Assert.Equal(true, change.After);
Assert.Equal(AdvisorKeys.StabilizeOn, change.ReasonKey);
Assert.DoesNotContain(AdvisorParameters.StabilizeSmoothing, motion.Changes.Select(c => c.Parameter));
Assert.Null(motion.Settings.HeroFrame);
var frames = Advisor.Optimise(AdvisorSection.Frames, settings, result);
Assert.Equal(result.Find(AdvisorParameters.Hero)!.Value, frames.Settings.HeroFrame);
Assert.SequenceEqual([AdvisorParameters.Hero], frames.Changes.Select(c => c.Parameter));
Assert.SequenceEqual([3], frames.Settings.ExcludedFrames);
var exposure = Advisor.Optimise(AdvisorSection.Exposure, settings, result);
var deflicker = exposure.Changes.Single(c => c.Parameter == AdvisorParameters.Deflicker);
Assert.Null(deflicker.Before);
Assert.Equal(true, deflicker.After);
Assert.Equal(settings.Motion, exposure.Settings.Motion);
// Optimising again changes nothing.
Assert.Empty(Advisor.Optimise(AdvisorSection.Motion, motion.Settings, result).Changes);
}
[Test]
public async Task OptimiseExcludesFlaggedFramesAndCapsTheOutput()
{
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = 40,
FlickerEv = 0.05,
BlackFrames = [5],
DuplicateFrames = [9],
}));
var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options);
var (light, sequence) = Inputs(source);
var result = Advisor.Recommend(light, deep, sequence with { PreviewOnlyCount = 12, PreviewWidth = 1620, PreviewHeight = 1080 });
var frames = Advisor.Optimise(AdvisorSection.Frames, new ProjectSettings { ExcludedFrames = [2] }, result);
Assert.SequenceEqual([2, 5, 9], frames.Settings.ExcludedFrames);
Assert.Equal(AdvisorKeys.Exclude, frames.Changes.Single(c => c.Parameter == AdvisorParameters.Excluded).ReasonKey);
var resolution = result.Find(AdvisorParameters.Resolution)!;
Assert.Equal("1280x720", resolution.Value);
Assert.Equal(AdvisorKeys.ResolutionPreview, resolution.ReasonKey);
var big = new ProjectSettings { Export = new ExportSettings { Preset = new Auto<string>().WithManual("4k-hevc") } };
var export = Advisor.Optimise(AdvisorSection.Export, big, result);
Assert.Equal("720p-preview", export.Settings.Export.Preset.Resolve("4k-hevc"));
Assert.Null(export.Settings.Export.Overrides.Width);
}
[Test]
public void OutputSizeFollowsSourceShapeAndEncoders()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()));
var h264Only = sequence with { Codecs = [new EncoderCapability(VideoCodec.H264, "Software H.264", false, 1920, 1088, false)] };
var limited = Advisor.Recommend(light, null, h264Only);
Assert.Equal("1920x1080", Value(limited, AdvisorParameters.Resolution));
Assert.Equal(AdvisorKeys.ResolutionCodec, limited.Find(AdvisorParameters.Resolution)!.ReasonKey);
Assert.Equal("1080p-h264", Value(limited, AdvisorParameters.ExportPreset));
var portrait = Advisor.Recommend(light, null, sequence with { SourceWidth = 4000, SourceHeight = 6000 });
Assert.Equal("9:16", Value(portrait, AdvisorParameters.Aspect));
Assert.Equal("1080x1920", Value(portrait, AdvisorParameters.Resolution));
Assert.Equal("vertical-1080x1920", Value(portrait, AdvisorParameters.ExportPreset));
var landscape = Advisor.Recommend(light, null, sequence);
Assert.Equal("16:9", Value(landscape, AdvisorParameters.Aspect));
Assert.SequenceEqual([6000.0, 4000.0, 84.0], landscape.Find(AdvisorParameters.Aspect)!.ReasonArgs.Select(Convert.ToDouble));
var wide = Advisor.Recommend(light, null, sequence with { SourceWidth = 6000, SourceHeight = 2500 });
Assert.Equal(AdvisorKeys.AspectWide, wide.Find(AdvisorParameters.Aspect)!.ReasonKey);
Assert.Equal(74.0, wide.Find(AdvisorParameters.Aspect)!.ReasonArgs[2]);
Assert.Equal("3840x2160", Value(wide, AdvisorParameters.Resolution));
}
[Test]
public async Task RecommendationsAreDeterministic()
{
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky()));
var deep = await DeepReports.Night;
var first = Advisor.Recommend(light, deep, sequence);
var second = Advisor.Recommend(light, DeepAnalysisReport.FromJson(deep.ToJson()), sequence);
Assert.SequenceEqual(first.Recommendations.Select(Describe), second.Recommendations.Select(Describe));
}
private static (LightAnalysisReport Light, SequenceContext Context) Inputs(SyntheticFrameSource source, int width = 6000, int height = 4000)
{
var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
var exposures = frames.Where(f => f.ExposureTime is > 0).Select(f => f.ExposureTime!.Value).ToArray();
return (LightAnalyzer.Analyze(frames), new SequenceContext
{
FrameCount = frames.Count,
SourceWidth = width,
SourceHeight = height,
MedianExposureSeconds = exposures.Length > 0 ? Statistics.Median(exposures) : null,
});
}
private static object? Value(AdvisorResult result, string parameter) => (result.Find(parameter) ?? throw new InvalidOperationException(parameter + " not recommended")).Value;
private static string Describe(Recommendation r) =>
$"{r.Parameter}={(r.Value is int[] list ? string.Join(",", list) : r.Value)} {r.Confidence} {r.ReasonKey} [{string.Join(";", r.ReasonArgs)}]";
private void Log(AdvisorResult result)
{
foreach (var r in result.Recommendations) context.Log(Describe(r));
}
}