merge: deep analysis, advisor and sequence presets
This commit is contained in:
24 files changed
+3979
No files matched your search
@@ -0,0 +1,132 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Resources;
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Core.Advisor;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Tests.Analysis.Deep;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Advisor;
|
||||
|
||||
using AdvisorApi = Titano.Core.Advisor.Advisor;
|
||||
|
||||
public sealed partial class AdvisorLocalizationTests(TestContext context)
|
||||
{
|
||||
private static readonly CultureInfo English = CultureInfo.GetCultureInfo("en");
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it");
|
||||
|
||||
[Test]
|
||||
public void EveryAdvisorKeyHasEnglishAndItalianTextWithTheSamePlaceholders()
|
||||
{
|
||||
var manager = new ResourceManager("Titano.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)!);
|
||||
var keys = Keys(typeof(AdvisorKeys)).Concat(Keys(typeof(FindingKeys))).Concat(Keys(typeof(DeepFindingKeys))).ToList();
|
||||
Assert.Greater(keys.Count, 90);
|
||||
foreach (var key in keys)
|
||||
{
|
||||
Assert.True(english.TryGetValue(key, out var en), $"English text missing for {key}");
|
||||
Assert.True(italian.TryGetValue(key, out var it), $"Italian text missing for {key}");
|
||||
Assert.SequenceEqual(Placeholders(en!), Placeholders(it!), key);
|
||||
Assert.LessOrEqual(en!.Length, 200);
|
||||
}
|
||||
Assert.Equal(english.Count, keys.Count);
|
||||
}
|
||||
|
||||
[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 = AdvisorApi.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 = AdvisorApi.Apply(new ProjectSettings(), result);
|
||||
Assert.DoesNotContain('⟦', AdvisorApi.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 format = Loc.Get(key, culture);
|
||||
Assert.NotNull(format);
|
||||
var text = Format(format!, culture, args);
|
||||
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,349 @@
|
||||
using Titano.Core.Advisor;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Tests.Analysis.Deep;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Advisor;
|
||||
|
||||
// The class shares its name with the namespace, which an enclosing Titano.Core.* namespace would resolve first.
|
||||
using AdvisorApi = Titano.Core.Advisor.Advisor;
|
||||
|
||||
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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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(AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.Apply(advised, result);
|
||||
Assert.Same(advised.Exposure.HolyGrail, applied.Exposure.HolyGrail);
|
||||
Assert.Same(advised.Exposure.TransitionLength, applied.Exposure.TransitionLength);
|
||||
Assert.Empty(AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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(AdvisorApi.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 = AdvisorApi.Recommend(light, deep, sequence with { PreviewOnlyCount = 12, PreviewWidth = 1620, PreviewHeight = 1080 });
|
||||
|
||||
var frames = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.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 = AdvisorApi.Recommend(light, deep, sequence);
|
||||
var second = AdvisorApi.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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Analysis.Deep;
|
||||
|
||||
public sealed class DeepAnalyzerTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task NightSkyShowsStarsDarknessFlickerAndNoShake()
|
||||
{
|
||||
var report = await DeepReports.Night;
|
||||
context.Log($"{report.Sky} {report.Flicker} {report.Shake}");
|
||||
Assert.True(report.Sky.StarField);
|
||||
Assert.Equal(DayNight.Night, report.Sky.Light);
|
||||
Assert.Equal(report.FrameCount, report.Sky.StarFrames);
|
||||
// Uniform ±0.12 EV flicker has an RMS of 0.069 EV.
|
||||
Assert.Approximately(0.069, report.Flicker.AmplitudeEv, 0.01);
|
||||
Assert.Equal(15, report.Flicker.RecommendedWindow);
|
||||
Assert.Less(report.Shake.RmsPx, 0.05);
|
||||
Assert.Equal(1.0, report.Shake.MeasuredFraction);
|
||||
Assert.Empty(report.Issues.SceneChanges);
|
||||
Assert.Equal(0.0, report.Motion.P95Px!.Value);
|
||||
Assert.Equal(RegionMethod.Horizon, report.Regions!.Method);
|
||||
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.StarField);
|
||||
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Flicker);
|
||||
Assert.True(report.Frames.FlagsOf(0).HasFlag(DeepFrameFlags.StarField | DeepFrameFlags.Dark));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InjectedCameraJitterIsMeasuredAsShake()
|
||||
{
|
||||
var report = await DeepReports.NightJitter;
|
||||
context.Log($"{report.Shake} {report.Motion}");
|
||||
// Integer offsets uniform in −2..2 per axis: 2 px RMS in 2D.
|
||||
Assert.InRange(report.Shake.RmsPx, 1.6, 2.4);
|
||||
Assert.InRange(report.Shake.CropCost, 0.02, 0.2);
|
||||
Assert.False(report.Shake.PanDetected);
|
||||
Assert.Greater(report.Motion.P95Px!.Value, 1);
|
||||
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Shake);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HolyGrailStepsAreReceivedAndSpacedByHalfTheirDistance()
|
||||
{
|
||||
var report = await DeepReports.HolyGrail;
|
||||
Assert.Equal(5, report.Exposure.MetadataSteps);
|
||||
Assert.Equal(5, report.Exposure.ReceivedSteps);
|
||||
Assert.Equal(40.0, report.Exposure.TypicalSpacing);
|
||||
Assert.Equal(20, report.Exposure.TransitionLength);
|
||||
Assert.True(report.Exposure.Steps.All(s => s.MeasuredEv is > 0.9 and < 1.1));
|
||||
Assert.InRange(report.Exposure.SceneRangeEv, 5, 6);
|
||||
Assert.Equal(DayNight.DayToNight, report.Sky.Light);
|
||||
// Brightness ramps and steps are levelled before the flow, so the static scene shows no motion.
|
||||
Assert.Equal(0.0, report.Motion.P95Px!.Value);
|
||||
Assert.Empty(report.Issues.SceneChanges);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(8.0, 33)]
|
||||
[Case(12.5, 51)]
|
||||
[Case(40.0, 151)]
|
||||
public async Task PeriodicFlickerGivesAWindowOfFourPeriods(double period, int window)
|
||||
{
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = period,
|
||||
});
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options);
|
||||
Assert.Approximately(period, report.Flicker.PeriodFrames!.Value, 0.05 * period);
|
||||
Assert.Equal(window, report.Flicker.RecommendedWindow);
|
||||
Assert.Equal(1, window % 2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task BlackWhiteDuplicateAndUnreadableFramesAreFlagged()
|
||||
{
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 60, FlickerEv = 0.02, BlackFrames = [10], WhiteFrames = [20], DuplicateFrames = [30],
|
||||
});
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence) { Undecodable = [40] }, DeepScenes.Options);
|
||||
Assert.SequenceEqual([10], report.Issues.Black);
|
||||
Assert.SequenceEqual([20], report.Issues.White);
|
||||
Assert.SequenceEqual([30], report.Issues.Duplicate);
|
||||
Assert.SequenceEqual([40], report.Issues.Undecodable);
|
||||
Assert.SequenceEqual([10, 20, 30, 40], report.Issues.Excludable());
|
||||
Assert.Empty(report.Issues.SceneChanges);
|
||||
Assert.Null(report.Frames.LogLuminance[40]);
|
||||
Assert.True(report.Frames.FlagsOf(40).HasFlag(DeepFrameFlags.Undecodable));
|
||||
Assert.False(report.Issues.Excludable().Contains(report.HeroIndex!.Value));
|
||||
foreach (var key in new[] { DeepFindingKeys.BlackFrames, DeepFindingKeys.WhiteFrames, DeepFindingKeys.DuplicateFrames, DeepFindingKeys.UnreadableFrames })
|
||||
Assert.Equal(FindingSeverity.Warning, report.Findings.Single(f => f.Key == key).Severity);
|
||||
Assert.Equal(4, AnalysisSummary.From(report).WarningCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACutToAnotherViewIsASceneChange()
|
||||
{
|
||||
var first = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05 }));
|
||||
var second = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05, Seed = 5, HorizonFraction = 0.75, SkyLevel = 0.6, LandLevel = 0.01,
|
||||
}));
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(first, second, 30), DeepScenes.Options);
|
||||
Assert.SequenceEqual([30], report.Issues.SceneChanges);
|
||||
Assert.True(report.Frames.FlagsOf(30).HasFlag(DeepFrameFlags.SceneChange));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ResumingFromACheckpointGivesTheSameReport()
|
||||
{
|
||||
var expected = (await DeepReports.HolyGrail).ToJson();
|
||||
var checkpoint = new MemoryCheckpoint();
|
||||
var crashing = new SyntheticFrameSource(DeepScenes.HolyGrail())
|
||||
{
|
||||
OnLoad = i =>
|
||||
{
|
||||
if (i == 101) throw new IOException("simulated crash");
|
||||
},
|
||||
};
|
||||
await Assert.ThrowsAsync<IOException>(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, checkpoint));
|
||||
var persisted = checkpoint.Frames.Count;
|
||||
Assert.InRange(persisted, 90, 101);
|
||||
|
||||
var resumed = new SyntheticFrameSource(DeepScenes.HolyGrail());
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(resumed, DeepScenes.Options, checkpoint);
|
||||
Assert.Equal(expected, report.ToJson());
|
||||
// Region sample + one priming frame + the frames not yet persisted.
|
||||
Assert.Equal(DeepScenes.Options.RegionSampleFrames + 1 + (240 - persisted), resumed.Loads);
|
||||
Assert.Equal(240, checkpoint.Frames.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FileCheckpointDropsATornLineAndResumes()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), ".titano", DeepAnalysisCheckpointFile.FileName);
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, DuplicateFrames = [7] });
|
||||
var expected = (await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options)).ToJson();
|
||||
var file = new DeepAnalysisCheckpointFile(path);
|
||||
var crashing = new SyntheticFrameSource(sequence) { OnLoad = i => { if (i == 21) throw new IOException("crash"); } };
|
||||
await Assert.ThrowsAsync<IOException>(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, file));
|
||||
await File.AppendAllTextAsync(path, "{\"index\":20,\"flags\":\"No", context.Cancellation);
|
||||
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, file);
|
||||
Assert.Equal(expected, report.ToJson());
|
||||
Assert.Equal(41, File.ReadAllLines(path).Length);
|
||||
|
||||
// Other options: the stale checkpoint is discarded instead of mixed in.
|
||||
var other = DeepScenes.Options with { FlowEvery = 3 };
|
||||
var fresh = await new DeepAnalysisCheckpointFile(path).LoadAsync(DeepAnalyzer.Fingerprint(40, other), context.Cancellation);
|
||||
Assert.Empty(fresh);
|
||||
file.Delete();
|
||||
Assert.FileMissing(path);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReportRoundTripsThroughJsonWithinTheSizeBudget()
|
||||
{
|
||||
var report = await DeepReports.NightJitter;
|
||||
var json = report.ToJson();
|
||||
var copy = DeepAnalysisReport.FromJson(json);
|
||||
Assert.Equal(json, copy.ToJson());
|
||||
var perFrame = (double)System.Text.Encoding.UTF8.GetByteCount(json) / report.FrameCount;
|
||||
context.Log($"{perFrame:0.0} bytes per frame");
|
||||
Assert.LessOrEqual(perFrame, 120);
|
||||
|
||||
var path = Path.Combine(context.CreateTempDirectory(), DeepAnalysisReport.FileName);
|
||||
report.Save(path);
|
||||
Assert.Equal(json, DeepAnalysisReport.Load(path).ToJson());
|
||||
|
||||
var summary = AnalysisSummary.From(report);
|
||||
Assert.Equal(summary, AnalysisSummary.FromJson(summary.ToJson()));
|
||||
Assert.True(summary.StarField);
|
||||
Assert.Equal(DayNight.Night, summary.Light);
|
||||
Assert.Equal(report.HeroIndex, summary.HeroIndex);
|
||||
Assert.Less(summary.ToJson().Length, 400);
|
||||
Assert.Throws<InvalidDataException>(() => DeepAnalysisReport.FromJson(json.Replace("\"version\":1", "\"version\":99", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ResultsDoNotDependOnParallelism()
|
||||
{
|
||||
var sequence = DeepScenes.NightSky(frames: 40, jitter: 2);
|
||||
var serial = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 1 });
|
||||
var parallel = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 3 });
|
||||
Assert.Equal(serial.ToJson(), parallel.ToJson());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CancellationStopsWithinOneBatch()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var checkpoint = new MemoryCheckpoint();
|
||||
var source = new SyntheticFrameSource(DeepScenes.HolyGrail())
|
||||
{
|
||||
OnLoad = i =>
|
||||
{
|
||||
if (i == 50) cancellation.Cancel();
|
||||
},
|
||||
};
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options, checkpoint, null, cancellation.Token));
|
||||
Assert.LessOrEqual(source.Loads, DeepScenes.Options.RegionSampleFrames + 52);
|
||||
Assert.Equal(50, checkpoint.Frames.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProgressCountsEveryFrameUpToTheTotal()
|
||||
{
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 21 });
|
||||
var reports = new List<AnalysisProgress>();
|
||||
await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, progress: new SyncProgress(reports.Add));
|
||||
Assert.Equal(11, reports.Count);
|
||||
Assert.Monotonic(reports.Select(r => (double)r.Done), strict: true);
|
||||
Assert.Equal(21, reports[^1].Done);
|
||||
Assert.True(reports.All(r => r.Total == 21 && r.FramesPerSecond > 0));
|
||||
Assert.Equal(TimeSpan.Zero, reports[^1].Eta);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EmptyAndUnreadableSequencesGiveEmptyReports()
|
||||
{
|
||||
var empty = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(new SyntheticFrameSource(DeepScenes.HolyGrail()), null!, 0) { Count = 0 }, DeepScenes.Options);
|
||||
Assert.Equal(0, empty.FrameCount);
|
||||
Assert.Equal(DayNight.Unknown, empty.Sky.Light);
|
||||
Assert.Empty(empty.Findings);
|
||||
|
||||
var unreadable = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 3 })) { Undecodable = [0, 1, 2] }, DeepScenes.Options);
|
||||
Assert.Equal(DayNight.Unknown, unreadable.Sky.Light);
|
||||
Assert.Null(unreadable.HeroIndex);
|
||||
Assert.Null(unreadable.Regions);
|
||||
Assert.SequenceEqual([0, 1, 2], unreadable.Issues.Undecodable);
|
||||
Assert.Equal(unreadable.ToJson(), DeepAnalysisReport.FromJson(unreadable.ToJson()).ToJson());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StarDetectorCountsPointsButNotBlobs()
|
||||
{
|
||||
using var image = new ImageBuffer(128, 96, 3);
|
||||
image.Data.Fill(1f / 2048);
|
||||
var random = new Random(3);
|
||||
var stars = 0;
|
||||
for (var y = 6; y < 90; y += 12)
|
||||
{
|
||||
for (var x = 6; x < 122; x += 12)
|
||||
{
|
||||
var v = (float)(0.2 + 0.8 * random.NextDouble());
|
||||
for (var c = 0; c < 3; c++) image[c, x, y] = v;
|
||||
stars++;
|
||||
}
|
||||
}
|
||||
// A lit window: 4×4 bright block (extended, not a star).
|
||||
for (var y = 40; y < 44; y++)
|
||||
{
|
||||
for (var x = 60; x < 64; x++)
|
||||
{
|
||||
for (var c = 0; c < 3; c++) image[c, x, y] = 0.8f;
|
||||
}
|
||||
}
|
||||
var density = StarFieldDetector.Density(image, noiseSigma: 0);
|
||||
Assert.Approximately(stars * 1e6 / (128 * 96), density, 1e-6);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CloudCoverageCountsTexturedSkyBlocks()
|
||||
{
|
||||
using var image = new ImageBuffer(128, 64, 3);
|
||||
var sky = new float[image.PlaneLength];
|
||||
var random = new Random(9);
|
||||
for (var y = 0; y < 64; y++)
|
||||
{
|
||||
for (var x = 0; x < 128; x++)
|
||||
{
|
||||
var i = y * 128 + x;
|
||||
sky[i] = y < 32 ? 1 : 0;
|
||||
// Smooth gradient everywhere; cloud texture on the left half of the sky.
|
||||
var v = 0.2 + 0.002 * y + (y < 32 && x < 64 ? 0.15 * random.NextDouble() : 0);
|
||||
for (var c = 0; c < 3; c++) image[c, x, y] = (float)v;
|
||||
}
|
||||
}
|
||||
Assert.Approximately(0.5, CloudCoverage.Estimate(image, sky), 1e-9);
|
||||
Assert.True(double.IsNaN(CloudCoverage.Estimate(image, new float[image.PlaneLength])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HistogramDistanceIgnoresExposureButNotContent()
|
||||
{
|
||||
using var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64 }).Render(0);
|
||||
using var brighter = scene.Clone();
|
||||
foreach (ref var v in brighter.Data) v *= 1.7f;
|
||||
using var other = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, HorizonFraction = 0.8, SkyLevel = 0.6 }).Render(0);
|
||||
var a = FrameStatistics.Measure(scene);
|
||||
Assert.Less(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(brighter)), 0.02);
|
||||
Assert.Greater(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(other)), 0.3);
|
||||
}
|
||||
|
||||
/// <summary>Frames of <paramref name="first"/> before <paramref name="cut"/>, then frames of <paramref name="second"/>.</summary>
|
||||
private sealed class SplicedSource(IFrameSource first, IFrameSource second, int cut) : IFrameSource
|
||||
{
|
||||
public int Count { get; init; } = first.Count;
|
||||
|
||||
public LightFrame Metadata(int index) => first.Metadata(index);
|
||||
|
||||
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) =>
|
||||
(index < cut ? first : second).LoadAsync(index, maxLongEdge, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Reports synchronously (Progress<T> posts to the thread pool and may reorder).</summary>
|
||||
private sealed class SyncProgress(Action<AnalysisProgress> report) : IProgress<AnalysisProgress>
|
||||
{
|
||||
public void Report(AnalysisProgress value) => report(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deep reports of the shared scenes, computed once per test run.</summary>
|
||||
internal static class DeepReports
|
||||
{
|
||||
private static readonly Lazy<Task<DeepAnalysisReport>> NightReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky()), DeepScenes.Options));
|
||||
private static readonly Lazy<Task<DeepAnalysisReport>> NightJitterReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), DeepScenes.Options));
|
||||
private static readonly Lazy<Task<DeepAnalysisReport>> HolyGrailReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.HolyGrail()), DeepScenes.Options));
|
||||
|
||||
public static Task<DeepAnalysisReport> Night => NightReport.Value;
|
||||
public static Task<DeepAnalysisReport> NightJitter => NightJitterReport.Value;
|
||||
public static Task<DeepAnalysisReport> HolyGrail => HolyGrailReport.Value;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Tests.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IFrameSource"/> over a <see cref="SyntheticSequence"/>. With <paramref name="jitter"/> > 0 the sequence is
|
||||
/// rendered <paramref name="jitter"/> pixels larger on every side and each frame is cropped at a seeded integer offset
|
||||
/// in ±jitter, which shakes the camera by a known amount.
|
||||
/// </summary>
|
||||
internal sealed class SyntheticFrameSource(SyntheticSequence sequence, int jitter = 0, int seed = 11) : IFrameSource
|
||||
{
|
||||
private readonly (int X, int Y)[] _offsets = Offsets(sequence.Count, jitter, seed);
|
||||
private int _loads;
|
||||
|
||||
public SyntheticSequence Sequence { get; } = sequence;
|
||||
|
||||
public int Width => Sequence.Options.Width - 2 * jitter;
|
||||
public int Height => Sequence.Options.Height - 2 * jitter;
|
||||
public int Count => Sequence.Count;
|
||||
|
||||
/// <summary>Total calls of <see cref="LoadAsync"/>.</summary>
|
||||
public int Loads => Volatile.Read(ref _loads);
|
||||
|
||||
/// <summary>Frames that "fail to decode".</summary>
|
||||
public HashSet<int> Undecodable { get; init; } = [];
|
||||
|
||||
/// <summary>Called on every load before decoding (may throw to simulate a crash, or cancel a token).</summary>
|
||||
public Action<int>? OnLoad { get; set; }
|
||||
|
||||
/// <summary>Metadata without shutter time and aperture when true.</summary>
|
||||
public bool StripExposure { get; init; }
|
||||
|
||||
public LightFrame Metadata(int index)
|
||||
{
|
||||
var frame = LightFrame.From(Sequence.Metadata[index], index) with { Width = Width, Height = Height };
|
||||
return StripExposure ? frame with { ExposureTime = null, FNumber = null } : frame;
|
||||
}
|
||||
|
||||
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Interlocked.Increment(ref _loads);
|
||||
OnLoad?.Invoke(index);
|
||||
if (Undecodable.Contains(index)) return ValueTask.FromResult<ImageBuffer?>(null);
|
||||
using var full = Sequence.Render(index);
|
||||
var (dx, dy) = _offsets[index];
|
||||
var image = new ImageBuffer(Width, Height, 3, clear: false);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
for (var y = 0; y < Height; y++)
|
||||
full.Row(c, y + jitter + dy).Slice(jitter + dx, Width).CopyTo(image.Row(c, y));
|
||||
}
|
||||
if (int.Max(Width, Height) <= maxLongEdge) return ValueTask.FromResult<ImageBuffer?>(image);
|
||||
using (image) return ValueTask.FromResult<ImageBuffer?>(AnalysisImage.Downscale(image, maxLongEdge));
|
||||
}
|
||||
|
||||
private static (int, int)[] Offsets(int count, int jitter, int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var offsets = new (int, int)[count];
|
||||
for (var i = 0; i < count; i++) offsets[i] = jitter > 0 ? (random.Next(-jitter, jitter + 1), random.Next(-jitter, jitter + 1)) : (0, 0);
|
||||
return offsets;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>In-memory checkpoint that records what was persisted.</summary>
|
||||
internal sealed class MemoryCheckpoint : IDeepAnalysisCheckpoint
|
||||
{
|
||||
private string? _fingerprint;
|
||||
|
||||
public List<DeepFrame> Frames { get; } = [];
|
||||
|
||||
public ValueTask<IReadOnlyList<DeepFrame>> LoadAsync(string fingerprint, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_fingerprint != fingerprint) Frames.Clear();
|
||||
_fingerprint = fingerprint;
|
||||
return ValueTask.FromResult<IReadOnlyList<DeepFrame>>([.. Frames]);
|
||||
}
|
||||
|
||||
public ValueTask AppendAsync(IReadOnlyList<DeepFrame> frames, CancellationToken cancellationToken)
|
||||
{
|
||||
Frames.AddRange(frames);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The synthetic scenes the deep-analysis and advisor tests share (small frames, fast).</summary>
|
||||
internal static class DeepScenes
|
||||
{
|
||||
/// <summary>Options for the tests: small sources are analysed at native size, flow on every 5th pair, two workers.</summary>
|
||||
public static DeepAnalysisOptions Options { get; } = new() { MinAnalysisLongEdge = 64, FlowEvery = 5, MaxDegreeOfParallelism = 2, RegionSampleFrames = 9 };
|
||||
|
||||
/// <summary>Night sky with stars over dark land and random flicker.</summary>
|
||||
public static SyntheticSequence NightSky(int frames = 90, int jitter = 0) => SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 160 + 2 * jitter,
|
||||
Height = 112 + 2 * jitter,
|
||||
FrameCount = frames,
|
||||
IntervalSeconds = 20,
|
||||
BaseExposureTime = 15,
|
||||
BaseFNumber = 2.8,
|
||||
BaseIso = 3200,
|
||||
StarField = true,
|
||||
StarCount = 160,
|
||||
FlickerEv = 0.12,
|
||||
Start = new DateTime(2024, 8, 12, 23, 0, 0),
|
||||
});
|
||||
|
||||
/// <summary>Sunset: the scene darkens 6 EV while the camera opens up 1 EV every 40 frames.</summary>
|
||||
public static SyntheticSequence HolyGrail(int frames = 240) => SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 160,
|
||||
Height = 112,
|
||||
FrameCount = frames,
|
||||
IntervalSeconds = 15,
|
||||
BaseExposureTime = 1.0 / 250,
|
||||
StartEv = 0.5,
|
||||
EndEv = -5.5,
|
||||
FlickerEv = 0.03,
|
||||
ExposureSteps = [new(40, -1), new(80, -1), new(120, -1), new(160, -1), new(200, -1)],
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user