using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using Chronos.App.Editor;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Data.Processing;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
///
/// The Export step's Output panel (owner review 1, R3 and R8): what the advanced encoding rows offer per codec, the
/// keyframe interval kept in seconds across a frame rate change, a standard resolution fitted to the chosen proportions,
/// a playback that raises the settings format, the collapsed groups' summaries and open state, the preset table's
/// groups, and the footer's Batch (n) and Videos (n).
///
[Serial]
public sealed class ExportTabTests
{
private static readonly Rational Fps24 = new(24, 1);
private static readonly Rational Fps30 = new(30, 1);
private static ExportSettings Preset(string id)
{
var export = new ProjectSettings().Export;
return export with { Preset = export.Preset.WithManual(id) };
}
[Test]
public void RateControlBFramesAndProfileFollowTheCodecAndDepth()
{
Assert.True(ExportRules.HasRateControl(VideoCodec.H264));
Assert.True(ExportRules.HasRateControl(VideoCodec.Hevc));
Assert.Null(ExportRules.RateControlBlocked(VideoCodec.Av1));
Assert.Null(ExportRules.KeyframesBlocked(VideoCodec.Hevc));
foreach (var managed in new[] { VideoCodec.Mjpeg, VideoCodec.Gif, VideoCodec.Apng, VideoCodec.PngSequence, VideoCodec.JpegSequence })
{
Assert.False(ExportRules.HasRateControl(managed), $"{managed} has no rate control");
Assert.NotNull(ExportRules.RateControlBlocked(managed), $"{managed}: the tooltip says why");
Assert.Equal(Loc.L("Tooltips.Export.KeyframesNA", Loc.L("Export.Codec." + managed)), ExportRules.KeyframesBlocked(managed), $"{managed}: no keyframe interval");
Assert.NotNull(ExportRules.BFramesBlocked(managed, CodecProfile.Auto), $"{managed} takes no B-frames");
Assert.Empty(ExportRules.Profiles(managed, 8));
Assert.NotNull(ExportRules.ProfileBlocked(managed, 8));
}
Assert.NotNull(ExportRules.BFramesBlocked(VideoCodec.H264, CodecProfile.H264Baseline), "Baseline takes no B-frames");
Assert.Null(ExportRules.BFramesBlocked(VideoCodec.H264, CodecProfile.H264High));
Assert.Null(ExportRules.BFramesBlocked(VideoCodec.Hevc, CodecProfile.HevcMain10));
Assert.SequenceEqual([CodecProfile.H264Baseline, CodecProfile.H264Main, CodecProfile.H264High], ExportRules.Profiles(VideoCodec.H264, 8));
Assert.Null(ExportRules.ProfileBlocked(VideoCodec.H264, 8), "H.264 offers three profiles");
Assert.SequenceEqual([CodecProfile.HevcMain], ExportRules.Profiles(VideoCodec.Hevc, 8));
Assert.SequenceEqual([CodecProfile.HevcMain10], ExportRules.Profiles(VideoCodec.Hevc, 10), "HEVC at 10 bits is Main 10");
Assert.NotNull(ExportRules.ProfileBlocked(VideoCodec.Hevc, 10), "one profile: nothing to choose");
Assert.SequenceEqual([CodecProfile.Av1Main], ExportRules.Profiles(VideoCodec.Av1, 10));
}
[Test]
public void TheKeyframeIntervalKeepsItsSecondsWhenTheFrameRateChanges()
{
Assert.Equal(36, ExportRules.GopFrames(1.5, Fps24));
Assert.Equal(1, ExportRules.GopFrames(0.01, Fps24), "at least one frame");
Assert.Approximately(1.5, ExportRules.GopSeconds(36, Fps24), 1e-9);
Assert.Equal(30, ExportRules.RescaleGop(24, Fps24, Fps30), "1 s at 24 fps is 1 s at 30 fps");
Assert.Equal(60, ExportRules.RescaleGop(48, Fps24, Fps30));
Assert.Approximately(1.0, ExportRules.NearestKeyframeSeconds(31, Fps30), 1e-9, "shown as the nearest offered interval");
Assert.Approximately(10.0, ExportRules.NearestKeyframeSeconds(10_000, Fps30), 1e-9, "at most the longest offered");
Assert.Equal(20, ExportRules.KeyframeSeconds.Count);
Assert.Approximately(0.5, ExportRules.KeyframeSeconds[0], 1e-9);
}
[Test]
public void AStandardResolutionIsTheLandscapeBoxTheChosenProportionsFitIn()
{
var uhd = ExportRules.StandardResolutions.Single(r => r.Key == "4k");
Assert.Equal((3840, 2160), (uhd.Width, uhd.Height));
Assert.Equal("Export.Resolution.Uhd4k", uhd.LabelKey);
Assert.True(ExportRules.StandardResolutions.All(r => Loc.L(r.LabelKey) != r.LabelKey), "every label is a resource");
Assert.Equal(ExportTab.PresetResolution, ExportTab.ResolutionKey(new ExportOverrides()));
Assert.Equal(ExportTab.SourceResolution, ExportTab.ResolutionKey(new ExportOverrides { Width = 0, Height = 0 }));
Assert.Equal("4k", ExportTab.ResolutionKey(new ExportOverrides { Width = 3840, Height = 2160 }));
Assert.Equal(ExportTab.CustomResolution, ExportTab.ResolutionKey(new ExportOverrides { Width = 3000, Height = 2000 }));
Assert.Equal(ExportTab.CustomResolution, ExportTab.ResolutionKey(new ExportOverrides { Width = 3840, Height = 2160 }, custom: true));
}
[Test]
public void APlaybackThatIsNotTheDefaultNeedsSettingsFormat3()
{
var project = new ProjectSettings();
Assert.True(project.RequiredFormat < 3);
var reverse = project with { Export = project.Export with { Playback = new PlaybackSettings { Direction = PlaybackDirection.Reverse } } };
Assert.Equal(3, reverse.RequiredFormat);
Assert.NotNull(ServerJobs.NeedsNewerServer(ProcessingJobs.RequiredFormat(reverse, reverse.Export, 96, 64), 2), "a format 2 server cannot render it");
Assert.Null(ServerJobs.NeedsNewerServer(ProcessingJobs.RequiredFormat(project, project.Export, 96, 64), 2));
var faded = project with { Export = project.Export with { Playback = new PlaybackSettings { FadeIn = 1 } } };
Assert.Equal(3, faded.RequiredFormat);
}
[Test]
public void TheCollapsedGroupsSummariseTheirValues()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal("Forward · no fades", ExportSummaries.Playback(null));
Assert.Equal("Boomerang · ×2 · fades 1 s / 1.5 s · hold 2 s", ExportSummaries.Playback(new PlaybackSettings
{
Direction = PlaybackDirection.Boomerang,
Loops = 2,
FadeIn = 1,
FadeOut = 1.5,
HoldEnd = 2,
}));
Assert.Equal("Reverse · no fades", ExportSummaries.Playback(new PlaybackSettings { Direction = PlaybackDirection.Reverse }));
Assert.Equal("Forward", ExportSummaries.DirectionLabel("unknown"), "an unknown direction plays forward");
var h264 = ExportResolver.Resolve(Preset("1080p-h264"));
var encoding = ExportSummaries.Encoding(h264, 40_000_000);
Assert.True(encoding.StartsWith(Loc.L("Export.RateControl." + h264.RateControl) + " · ", StringComparison.Ordinal), encoding);
Assert.Contains("GOP ", encoding);
Assert.Contains("B " + h264.BFrames.ToString(CultureInfo.InvariantCulture), encoding);
Assert.True(encoding.EndsWith("High", StringComparison.Ordinal), encoding);
var png = ExportSummaries.Encoding(ExportResolver.Resolve(Preset("png-sequence")), 0);
Assert.False(png.Contains("GOP", StringComparison.Ordinal), "an image sequence has no rate control");
Assert.Equal("clip.mp4 · " + Loc.L("Editor.Export.Sync"), ExportSummaries.File("clip.mp4", "Renders", sync: true));
Assert.Equal("Renders", ExportSummaries.File(null, "Renders", sync: false));
var footer = ExportSummaries.Footer("clip.mp4", null, 42, 1260);
Assert.True(footer.StartsWith("clip.mp4 · ", StringComparison.Ordinal), footer);
Assert.True(footer.EndsWith(Loc.Plural("Export.Footer.Frames", 1260), StringComparison.Ordinal), footer);
Assert.Equal(3, footer.Split(" · ").Length, "no size or time without an estimate");
}
[Test]
public void AGroupsOpenStateIsKeptAndSavedByTheApp()
{
var states = new GroupStates();
states.Set("export.encoding", true);
var store = new Dictionary(StringComparer.Ordinal);
var saves = 0;
states.Bind(store, () => saves++);
Assert.True(store["export.encoding"], "a toggle made before the settings were attached stays");
Assert.True(states.IsExpanded("export.encoding", fallback: false));
Assert.False(states.IsExpanded("export.playback", fallback: false), "never toggled: the default");
states.Set("export.playback", true);
Assert.Equal(1, saves);
Assert.True(store["export.playback"]);
states.Set("export.playback", true);
Assert.Equal(1, saves, "no change, no save");
var key = "test." + Guid.NewGuid().ToString("N");
var group = new SettingGroup(key, "Export.Group.Encoding", "Tooltips.Export.Group.Encoding", expandedByDefault: false);
Assert.False(group.IsExpanded);
group.ToggleCommand.Execute(null);
Assert.True(group.IsExpanded);
Assert.True(new SettingGroup(key, "Export.Group.Encoding", "Tooltips.Export.Group.Encoding", expandedByDefault: false).IsExpanded,
"another editor opens it as it was left");
}
[Test]
public void TheVideosLinkFiltersTheVideosSectionAndShowsIt()
{
var shown = new List();
Assert.False(VideosLink.Open([], shown.Add, Guid.NewGuid()), "no Videos section yet: nothing happens");
var videos = new FakeVideos();
var id = Guid.NewGuid();
Assert.True(VideosLink.Open([videos], shown.Add, id));
Assert.Equal(id, videos.Shown);
Assert.SequenceEqual([SectionKey.Jobs], shown);
videos.Dispose();
}
/// The Output panel on the synthetic sunset at 9:16: resolution, keyframes, playback, footer and preset groups.
[Test]
[WindowsOnly]
[Timeout(300_000)]
public Task ThePanelWritesTheOverridesAndThePlaybackItShows() => ScreenHost.RunAsync(async () =>
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var project = new ProjectSettings();
project = project with
{
Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual("9:16") },
Export = project.Export with { Preset = project.Export.Preset.WithManual("1080p-h264") },
};
var content = EditorFixture.Content(EditorFixture.Sunset, project);
var editor = new EditorViewModel(app.Shell, new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content), content, []), [], EncoderHost.Client);
await using (editor)
{
var export = editor.Tabs.OfType().Single();
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
// 4K UHD at 9:16: the landscape box in the overrides, the portrait size rendered.
Assert.Equal(ExportTab.PresetResolution, export.SelectedResolution?.Value);
export.SelectedResolution = export.Resolutions.Single(r => Equals(r.Value, "4k"));
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.Equal<(int?, int?)>((3840, 2160), (editor.Session.Project.Export.Overrides.Width, editor.Session.Project.Export.Overrides.Height));
Assert.Equal("2160 × 3840", export.OutputSizeText);
Assert.False(export.IsCustomResolution);
export.SelectedResolution = export.Resolutions.Single(r => Equals(r.Value, ExportTab.CustomResolution));
Assert.True(export.IsCustomResolution, "Custom shows Width × Height");
// Keyframes: 1 s at the preset's 30 fps, then 24 fps keeps 1 s.
export.SelectedKeyframes = export.KeyframeChoices.Single(c => (double)c.Value == 1.0);
Assert.Equal(30, editor.Session.Project.Export.Overrides.GopFrames);
export.SelectedFrameRate = export.FrameRates.Single(c => FrameRateText.TryParse((string)c.Value, out var r) && FrameRateText.AreEqual(r, Fps24));
Assert.Equal(24, editor.Session.Project.Export.Overrides.GopFrames, "the interval keeps its seconds");
Assert.Approximately(1.0, (double)export.SelectedKeyframes!.Value, 1e-9);
// Baseline takes no B-frames.
Assert.True(export.CanChooseProfile);
export.SelectedProfile = export.ProfileChoices.Single(c => Equals(c.Value, CodecProfile.H264Baseline));
Assert.Equal(0, editor.Session.Project.Export.Overrides.BFrames);
Assert.False(export.CanChooseBFrames);
// A reverse playback raises the settings format; Reset writes none again.
Assert.True(export.IsPlaybackDefault);
export.SelectedDirection = export.Directions.Single(d => Equals(d.Value, PlaybackDirection.Reverse));
Assert.Equal(PlaybackDirection.Reverse, editor.Session.Project.Export.Playback?.Direction);
Assert.Equal(3, editor.Session.Project.RequiredFormat);
Assert.False(export.IsPlaybackDefault);
export.FadeIn = 1.5;
Assert.Equal(1.5, editor.Session.Project.Export.Playback?.FadeIn);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.Equal("Reverse · fades 1.5 s / 0 s", export.PlaybackGroup.Summary);
export.ResetPlaybackCommand.Execute(null);
Assert.Null(editor.Session.Project.Export.Playback);
Assert.True(editor.Session.Project.RequiredFormat < 3);
// The preset table: every preset once, in the built-in order of the groups, one group open at least.
Assert.Equal(export.Presets.Count, export.PresetGroups.Sum(g => g.Rows.Count));
var order = ExportPresets.BuiltIn.Select(p => p.Group).Distinct(StringComparer.Ordinal).ToList();
Assert.SequenceEqual(order.Where(g => export.PresetGroups.Any(p => p.Key == g)), export.PresetGroups.Select(g => g.Key));
Assert.True(export.PresetGroups.Any(g => g.IsExpanded));
var social = export.PresetGroups.Single(g => g.Key == "social");
Assert.Equal($"Social ({export.Presets.Count(p => p.Group == "social")})", social.Header, "a sequence preset sits in its export preset's group");
Assert.True(social.Rows.Count >= 3);
// The footer: Batch (n) counts the ticked presets, Videos (n) the renders.
Assert.Equal("Batch (0)", export.BatchText);
export.Presets.First(p => p.CanBatch).IsInBatch = true;
Assert.Equal("Batch (1)", export.BatchText);
Assert.Equal(Loc.L("Export.Footer.Videos", content.Renders.Count.ToString("N0", Loc.Culture)), export.VideosText);
Assert.NotNull(export.FooterSummary);
// A library sequence saves its .chronos project file from the footer; a workspace project has it in its project ▾ menu.
var panel = new ContentControl { Content = export };
panel.Resources.MergedDictionaries.Add(new ResourceDictionary
{
Source = new Uri("pack://application:,,,/Chronos;component/Editor/EditorPanels.xaml", UriKind.Absolute),
});
panel.Measure(new Size(420, 4000));
panel.Arrange(new Rect(0, 0, 420, 4000));
panel.UpdateLayout();
var save = Assert.NotNull(Descendants