using System.Globalization; using System.IO; using System.Windows.Input; using Chronos.App.Infrastructure; using Chronos.App.Settings; using Chronos.App.Shell; using Chronos.App.Workspace; using Chronos.Core.Advice; using Chronos.Core.Diagnostics; using Chronos.Core.Export; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Project; using Chronos.Core.Video; using Chronos.Data; using Chronos.Data.Processing; using Chronos.Ui.Controls; using Chronos.Ui.Mvvm; namespace Chronos.App.Editor; /// A codec choice of the Output panel with the profile and depth it implies. public sealed record CodecChoice(VideoCodec Codec, CodecProfile Profile, int BitDepth) { public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec); public string Label => EditorText.CodecName(Codec, Profile, BitDepth); } /// Where renders go: the sequence's exports folder or a folder the user picked. public sealed record SaveChoice(string? Folder, bool Browse = false) { public string Label => Browse ? Loc.L("Editor.Export.Browse") : Folder is null ? Loc.L("Editor.Export.SequenceFolder") : Path.GetFileName(Folder.TrimEnd('\\', '/')); } /// A choice that may not apply now (Boomerang with star trails): disabled in the list, its reason in the tooltip. public sealed record GatedChoice(object Value, string Label, bool IsAvailable, string ToolTip); /// /// Export (Export.html, BRIEF §11.4–11.5, owner review 1 R3/R8): the preset table with size and time estimates, the Output /// panel in four collapsible groups (Output: container, codec, resolution, frame rate, colour depth; Encoding: encoder, /// rate control, bit rate or quality, keyframes, B-frames, profile; Playback: direction, loops, fades, hold; File: name /// template, folder, sync, restore), the encoder's notices, and a fixed footer with the result line and the render /// actions (now, queue, batch). Editing a value makes the preset "Custom" (§11.4). /// public sealed class ExportTab : EditorTab { public static IReadOnlyList Codecs { get; } = [ new(VideoCodec.H264, CodecProfile.H264High, 8), new(VideoCodec.Hevc, CodecProfile.HevcMain, 8), new(VideoCodec.Hevc, CodecProfile.HevcMain10, 10), new(VideoCodec.Av1, CodecProfile.Av1Main, 10), new(VideoCodec.Mjpeg, CodecProfile.Auto, 8), new(VideoCodec.Gif, CodecProfile.Auto, 8), new(VideoCodec.Apng, CodecProfile.Auto, 8), new(VideoCodec.PngSequence, CodecProfile.Auto, 8), new(VideoCodec.JpegSequence, CodecProfile.Auto, 8), new(VideoCodec.Tiff16Sequence, CodecProfile.Auto, 16), new(VideoCodec.LinearDngSequence, CodecProfile.Auto, 16), ]; /// The Resolution choice's value for the preset's own box (no override). public const string PresetResolution = "preset"; /// The Resolution choice's value for the source size (a box of 0 × 0). public const string SourceResolution = "source"; /// The Resolution choice's value that shows the Width × Height fields. public const string CustomResolution = "custom"; /// The longest fade or hold the sliders reach (seconds); the fields take up to the playback's own limits. public const double SliderSeconds = 10; private readonly LatestRunner _estimates = new(TimeSpan.FromMilliseconds(250)); private readonly AsyncRelayCommand _renderNow; private readonly AsyncRelayCommand _addToQueue; private readonly AsyncRelayCommand _batch; private readonly AsyncRelayCommand _restore; private SavedCopy? _selectedCopy; private IReadOnlyList _presets = []; private IReadOnlyList _presetGroups = []; private IReadOnlyList _codecChoices = []; private IReadOnlyList _encoders = []; private IReadOnlyList _saveChoices = []; private IReadOnlyList _depths = []; private IReadOnlyList _keyframeChoices = []; private IReadOnlyList _bFrameChoices = []; private IReadOnlyList _profileChoices = []; private IReadOnlyList _directions = []; private IReadOnlyList _notices = []; private bool _refreshing; private bool _customResolution; public ExportTab(EditorViewModel editor) : base(editor, "Export", AdvisorSection.Export) { SelectCommand = new RelayCommand(p => Select(p as PresetRow), _ => !Editor.IsLocked); _renderNow = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: false), () => Editor.CanRender); _addToQueue = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.Normal, batch: false), () => Editor.CanRender); _batch = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: true), () => Editor.CanRender && Batch.Count > 0); RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal); VideosCommand = new RelayCommand(OpenVideos, () => CanOpenVideos); _restore = new AsyncRelayCommand(RestoreAsync, () => !Editor.IsLocked && SelectedCopy is not null); SaveProjectCommand = new AsyncRelayCommand(() => new ProjectFiles(Editor.Shell).SaveAsync(Editor.Session), () => !Editor.IsRemote); ResetFrameRateCommand = new RelayCommand(() => SetFrameRate(null)); ResetRateControlCommand = new RelayCommand(() => EditOverrides(o => o with { RateControl = null })); ResetQualityCommand = new RelayCommand(() => EditOverrides(o => o with { BitRate = null, Quality = null })); ResetProfileCommand = new RelayCommand(() => EditOverrides(o => o with { Profile = null, BFrames = IsBaseline(o.Profile) ? null : o.BFrames })); ResetPlaybackCommand = new RelayCommand(() => EditExport(e => e with { Playback = null }), () => !IsPlaybackDefault); Width = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Width = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Width")); Height = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Height = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Height")); NameTemplate = new EditableField(string.Empty, ValidateTemplate, v => EditExport(e => e with { NameTemplate = v }), () => Loc.L("Tooltips.Editor.Export.Name")); FadeInField = SecondsField(PlaybackSettings.MaxFadeSeconds, (p, v) => p with { FadeIn = v }, "Tooltips.Export.FadeIn"); FadeOutField = SecondsField(PlaybackSettings.MaxFadeSeconds, (p, v) => p with { FadeOut = v }, "Tooltips.Export.FadeOut"); HoldEndField = SecondsField(PlaybackSettings.MaxHoldSeconds, (p, v) => p with { HoldEnd = v }, "Tooltips.Export.HoldEnd"); OutputGroup = new SettingGroup("export.output", "Export.Group.Output", "Tooltips.Export.Group.Output", expandedByDefault: true); EncodingGroup = new SettingGroup("export.encoding", "Export.Group.Encoding", "Tooltips.Export.Group.Encoding", expandedByDefault: false); PlaybackGroup = new SettingGroup("export.playback", "Export.Group.Playback", "Tooltips.Export.Group.Playback", expandedByDefault: false); FileGroup = new SettingGroup("export.file", "Export.Group.File", "Tooltips.Export.Group.File", expandedByDefault: true); _selectedCopy = SavedCopies.FirstOrDefault(); LoadTable(); Refresh(); } // ---- Preset table (measure area) ---- /// Every preset, in table order. public IReadOnlyList Presets { get => _presets; private set => Set(ref _presets, value); } /// The presets by group (Video, Social, Intermediate, Image sequence, Web), each one opened or closed. public IReadOnlyList PresetGroups { get => _presetGroups; private set => Set(ref _presetGroups, value); } public ICommand SelectCommand { get; } // ---- The groups of the Output panel ---- public SettingGroup OutputGroup { get; } public SettingGroup EncodingGroup { get; } public SettingGroup PlaybackGroup { get; } public SettingGroup FileGroup { get; } // ---- Footer ---- public ICommand RenderNowCommand => _renderNow; public ICommand AddToQueueCommand => _addToQueue; public ICommand BatchCommand => _batch; /// "Reveal in Explorer" for the newest render (BRIEF §11.5 follow-up). public ICommand RevealLastCommand { get; } public string AddToQueueToolTip => Editor.RenderBlockedReason ?? Loc.L("Tooltips.Editor.Export.AddToQueue"); /// "Batch (2)": the ticked presets. public string BatchText => Loc.L("Export.Footer.Batch", Batch.Count.ToString("N0", Loc.Culture)); public string BatchToolTip => Editor.RenderBlockedReason ?? (Batch.Count == 0 ? Loc.L("Tooltips.Editor.Export.BatchEmpty") : Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.BatchServer", Editor.ServerName) : Loc.L("Tooltips.Export.Footer.Batch")); /// The newest render is a file on this PC (a server's renders stay on the server). public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..]; /// "Videos (3)": the renders of this sequence. public string VideosText => Loc.L("Export.Footer.Videos", Editor.Session.Content.Renders.Count.ToString("N0", Loc.Culture)); /// Opens the Videos section filtered on this sequence (owner review 1, R9). public ICommand VideosCommand { get; } /// The app has a Videos section to open. public bool CanOpenVideos => VideosLink.Find(Editor.Shell.AllSections) is not null; /// /// "2026-09-28 Harbour sunset - 4K archive.mp4 · 1.2 GB · about 4 min · 42 s · 1,260 frames": the result, its estimates, /// and the video's duration and frames as the playback plays them; null before the plan. /// public string? FooterSummary => Editor.Plan is { } plan ? ExportSummaries.Footer(plan.FileName, Estimated?.Estimate, plan.DurationSeconds, plan.FrameCount) : null; /// /// Saves a .chronos project file of this sequence and its settings (BRIEF §18); a server sequence has no /// archive on this PC for the file to name. Offered in the project ▾ menu. /// public ICommand SaveProjectCommand { get; } public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save"); // ---- File: Sync ---- /// Send each render made on this PC to the server the sequence is linked to; remembered in the project. public bool SyncToServer { get => Export.SyncToServer; set { if (!_refreshing && value != Export.SyncToServer) EditExport(e => e with { SyncToServer = value }); } } public bool CanSync => Editor.SyncGate == ExportSyncGate.Available; /// What Sync does, or why it cannot be used for this sequence now. public string SyncToolTip => Loc.L(Editor.SyncGate switch { ExportSyncGate.Remote => "Tooltips.Editor.Export.SyncRemote", ExportSyncGate.SignedOut => "Tooltips.Editor.Export.SyncSignedOut", ExportSyncGate.NotLinked => "Tooltips.Editor.Export.SyncNotLinked", ExportSyncGate.NoUpload => "Tooltips.Editor.Export.SyncNoUpload", _ => "Tooltips.Editor.Export.Sync", }); /// A server sequence renders into its exports folder on the server. public bool CanChooseFolder => !Editor.IsRemote; // ---- File: "Save both" copies of this PC's settings ---- public IReadOnlyList SavedCopies => Editor.Session.Content.SavedCopies; public bool HasSavedCopies => SavedCopies.Count > 0; /// The copy Restore makes the project: the newest unless another is chosen in the menu. public SavedCopy? SelectedCopy { get => _selectedCopy; set { if (!Set(ref _selectedCopy, value)) return; OnPropertyChanged(nameof(RestoreText)); OnPropertyChanged(nameof(RestoreToolTip)); _restore.RaiseCanExecuteChanged(); } } /// "Restore settings · 03/10/2026 14:22". public string RestoreText => Loc.L("Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty); public string RestoreToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty); public ICommand RestoreCommand => _restore; // ---- Output ---- /// "Output · 4K archive". public string Title => Loc.L("Editor.Export.Output", Editor.Plan?.PresetName ?? ProcessingJobs.PresetName(ExportResolver.Resolve(Export))); public IReadOnlyList Containers { get; } = [ new(ContainerFormat.Mp4, "Export.Container.Mp4"), new(ContainerFormat.Avi, "Export.Container.Avi"), new(ContainerFormat.Gif, "Export.Container.Gif"), new(ContainerFormat.Apng, "Export.Container.Apng"), new(ContainerFormat.ImageSequence, "Export.Container.ImageSequence"), ]; public Choice? SelectedContainer { get => Containers.FirstOrDefault(c => Equals(c.Value, Resolved.Container)); set { if (_refreshing || value?.Value is not ContainerFormat container || container == Resolved.Container) return; SelectCodec(Codecs.First(c => c.Container == container)); } } public IReadOnlyList CodecChoices { get => _codecChoices; private set => Set(ref _codecChoices, value); } public CodecChoice? SelectedCodec { get => CodecChoices.FirstOrDefault(c => c.Codec == Resolved.Codec && (c.Codec != VideoCodec.Hevc || (c.BitDepth > 8) == (Resolved.BitDepth > 8))); set { if (!_refreshing && value is not null) SelectCodec(value); } } /// Preset, Source, the standard sizes (720p … 8K) and Custom (decision 7). public IReadOnlyList Resolutions { get; } = [ new(PresetResolution, "Export.Resolution.Preset"), new(SourceResolution, "Export.Resolution.Source"), .. ExportRules.StandardResolutions.Select(r => new Choice(r.Key, r.LabelKey)), new(CustomResolution, "Export.Resolution.Custom"), ]; /// /// The size the export asks for: the preset's box, the source, a standard box (written into the overrides as landscape, /// so the chosen proportions are fitted in it: 4K at 9:16 renders 2160 × 3840), or Custom with Width × Height. /// public Choice? SelectedResolution { get => Resolutions.FirstOrDefault(c => Equals(c.Value, ResolutionKey(Export.Overrides, _customResolution))); set { if (_refreshing || value?.Value is not string key) return; _customResolution = key == CustomResolution; if (_customResolution) { OnPropertyChanged(); OnPropertyChanged(nameof(IsCustomResolution)); return; } var (width, height) = key switch { PresetResolution => ((int?)null, (int?)null), SourceResolution => (0, 0), _ => ExportRules.StandardResolutions.Where(r => r.Key == key).Select(r => ((int?)r.Width, (int?)r.Height)).First(), }; Width.Revert(); Height.Revert(); EditOverrides(o => o with { Width = width, Height = height }); } } /// Custom is chosen: the Width × Height fields show. public bool IsCustomResolution => Equals(SelectedResolution?.Value, CustomResolution); public EditableField Width { get; } public EditableField Height { get; } /// /// "2160 × 3840": what the render makes of the box (Width × Height) and the chosen proportions (owner review 1, R5), /// "(capped)" when the encoder takes no more; null before the plan. /// public string? OutputSizeText => Editor.Plan is { } plan ? OutputSizeOf(plan) : null; /// Where the output size comes from, or the largest size the encoder takes when it capped it. public string OutputSizeToolTip => OutputSizeToolTipOf(Editor.Plan); /// The Output size row of : "2160 × 3840", or "1080 × 1920 (capped)". public static string OutputSizeOf(ExportPlan plan) { ArgumentNullException.ThrowIfNull(plan); return plan.IsCapped ? Loc.L("Editor.Export.Capped", SizeText(plan.EncodedSize)) : SizeText(plan.OutputSize); } /// The Output size row's tooltip for . public static string OutputSizeToolTipOf(ExportPlan? plan) => plan is { IsCapped: true } ? Loc.L("Tooltips.Editor.Export.OutputCapped", SizeText(LargestTaken(plan))) : Loc.L("Tooltips.Editor.Export.OutputSize"); /// "16:9". public string AspectText => Editor.Plan is { } plan ? Aspect(plan.Setup.Encoder.Settings.Width, plan.Setup.Encoder.Settings.Height) : string.Empty; public IReadOnlyList FrameRates { get; } = [.. ExportPresets.FrameRates.Select(r => new Choice(FrameRateText.Format(r), "Editor.Value.Number", EditorText.FrameRate(r)))]; public Choice? SelectedFrameRate { get => FrameRates.FirstOrDefault(c => FrameRateText.TryParse((string)c.Value, out var r) && FrameRateText.AreEqual(r, Resolved.FrameRate)); set { if (!_refreshing && value?.Value is string rate) SetFrameRate(rate); } } /// The preset's own frame rate is in force (no override). public bool IsFrameRateAuto => Export.Overrides.FrameRate is null; public string FrameRateAutoToolTip => Loc.L("Tooltips.Editor.Export.FrameRateAuto", EditorText.FrameRate(ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() }).FrameRate)); public ICommand ResetFrameRateCommand { get; } public IReadOnlyList Depths { get => _depths; private set => Set(ref _depths, value); } public Choice? SelectedDepth { get => Depths.FirstOrDefault(d => (int)d.Value == Resolved.BitDepth) ?? Depths[0]; set { if (_refreshing || value?.Value is not int depth || depth == Resolved.BitDepth) return; EditOverrides(o => o with { BitDepth = depth, Profile = Resolved.Codec == VideoCodec.Hevc ? (depth > 8 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain).ToString() : o.Profile, }); } } public bool CanChooseDepth => Depths.Count > 1; // ---- Encoding ---- public IReadOnlyList Encoders { get => _encoders; private set => Set(ref _encoders, value); } /// The encoder is this PC's choice only for its own renders; the server or its render node picks its own. public bool CanChooseEncoder => !Editor.IsRemote; public string EncoderToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.EncoderServer", Editor.ServerName) : Loc.L("Tooltips.Editor.Export.Encoder"); public Choice? SelectedEncoder { get => Encoders.FirstOrDefault(e => Equals(e.Value, Export.Overrides.Encoder ?? string.Empty)); set { if (!_refreshing && value?.Value is string name) EditOverrides(o => o with { Encoder = name.Length == 0 ? null : name }); } } /// "hardware", "software" for this PC's encoder (the word, not a colour, carries the state). public string? EncoderKind => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability is { } c ? Loc.L(c.Hardware ? "Editor.Export.Hardware" : "Editor.Export.Software") : null; public bool IsHardware => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability?.Hardware == true; /// Variable, constant, quality (H.264, HEVC and AV1 only). public IReadOnlyList RateControls { get; } = [.. Enum.GetValues().Select(r => new Choice(r, "Export.RateControl." + r))]; public Choice? SelectedRateControl { get => RateControls.FirstOrDefault(c => Equals(c.Value, Resolved.RateControl)); set { if (_refreshing || value?.Value is not RateControl rateControl || rateControl == Resolved.RateControl) return; // The preset's own rate control (every preset is variable) is no override. EditOverrides(o => o with { RateControl = rateControl == PresetValues.RateControl ? null : rateControl.ToString().ToLowerInvariant() }); } } /// The codec has a rate control (and a keyframe interval) to choose. public bool HasRateControl => ExportRules.HasRateControl(Resolved.Codec); public string RateControlToolTip => ExportRules.RateControlBlocked(Resolved.Codec) ?? Loc.L("Tooltips.Export.RateControl"); public bool IsRateControlSet => HasRateControl && Export.Overrides.RateControl is not null; public ICommand ResetRateControlCommand { get; } /// Bit rate in Mb/s (variable and constant rate) or quality 1–100 (quality rate control, JPEG, MJPEG, GIF). public double Quality { get => IsBitRate ? (Editor.Plan?.Setup.Encoder.Settings.BitRate ?? Resolved.BitRate) / 1e6 : Resolved.Quality; set { if (_refreshing) return; if (IsBitRate) EditOverrides(o => o with { BitRate = (long)(double.Round(value) * 1e6) }, "Export.Quality"); else EditOverrides(o => o with { Quality = (int)double.Round(value) }, "Export.Quality"); } } /// The slider sets the bit rate: a video codec at variable or constant rate. public bool IsBitRate => HasRateControl && Resolved.RateControl != RateControl.Quality; public double QualityMaximum => IsBitRate ? 400 : 100; public bool IsQualityApplicable => HasRateControl || Resolved.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif; public string? QualityNotApplicable => IsQualityApplicable ? null : Loc.L("Tooltips.Editor.NotApplicable.Lossless"); /// "Bit rate" or "Quality": the row's label follows what the slider sets. public string QualityHeader => Loc.L(IsBitRate ? "Export.BitRate" : "Editor.Export.Quality"); public string QualityText => IsBitRate ? EditorText.BitRate((long)(Quality * 1e6)) : Quality.ToString("0", Loc.Culture); public string QualityToolTip => Loc.L(IsBitRate ? "Tooltips.Export.BitRate" : "Tooltips.Export.Quality"); public bool IsQualitySet => IsQualityApplicable && (IsBitRate ? Export.Overrides.BitRate : Export.Overrides.Quality) is not null; public ICommand ResetQualityCommand { get; } /// Auto (the preset's), then 0.5 to 10 s. public IReadOnlyList KeyframeChoices { get => _keyframeChoices; private set => Set(ref _keyframeChoices, value); } /// /// The keyframe interval in seconds (decision 6), stored as whole frames at the export's rate /// (); 0 is Auto (the preset's). /// public Choice? SelectedKeyframes { get { var seconds = Export.Overrides.GopFrames is { } gop ? ExportRules.NearestKeyframeSeconds(gop, Resolved.FrameRate) : 0.0; return KeyframeChoices.FirstOrDefault(c => (double)c.Value == seconds); } set { if (_refreshing || value?.Value is not double seconds) return; var rate = Resolved.FrameRate; EditOverrides(o => o with { GopFrames = seconds <= 0 ? null : ExportRules.GopFrames(seconds, rate) }); } } public string KeyframesToolTip => ExportRules.KeyframesBlocked(Resolved.Codec) ?? Loc.L("Tooltips.Export.Keyframes"); /// Auto (the preset's), then 0 to 4. public IReadOnlyList BFrameChoices { get => _bFrameChoices; private set => Set(ref _bFrameChoices, value); } /// B-frames, −1 for Auto (the preset's). public Choice? SelectedBFrames { get => BFrameChoices.FirstOrDefault(c => (int)c.Value == (Export.Overrides.BFrames ?? -1)); set { if (_refreshing || value?.Value is not int count) return; EditOverrides(o => o with { BFrames = count < 0 ? null : count }); } } /// Baseline, MJPEG, GIF, APNG and the image sequences take no B-frames. public bool CanChooseBFrames => ExportRules.BFramesBlocked(Resolved.Codec, Resolved.Profile) is null; public string BFramesToolTip => ExportRules.BFramesBlocked(Resolved.Codec, Resolved.Profile) ?? Loc.L("Tooltips.Export.BFrames"); /// The profiles of the codec at the chosen depth. public IReadOnlyList ProfileChoices { get => _profileChoices; private set => Set(ref _profileChoices, value); } public Choice? SelectedProfile { get => ProfileChoices.FirstOrDefault(c => Equals(c.Value, Resolved.Profile)) ?? ProfileChoices.FirstOrDefault(); set { if (_refreshing || value?.Value is not CodecProfile profile || profile == Resolved.Profile) return; // Baseline takes no B-frames: none are asked for while it is chosen, the preset's again once it is not. EditOverrides(o => o with { Profile = profile.ToString(), BFrames = profile == CodecProfile.H264Baseline ? 0 : IsBaseline(o.Profile) ? null : o.BFrames, }); } } public bool CanChooseProfile => ProfileChoices.Count > 1; public string ProfileToolTip => ExportRules.ProfileBlocked(Resolved.Codec, Resolved.BitDepth) ?? Loc.L("Tooltips.Export.Profile"); public bool IsProfileSet => CanChooseProfile && Export.Overrides.Profile is not null; public ICommand ResetProfileCommand { get; } // ---- Playback (settings format 3) ---- /// Forward, Reverse, Boomerang; Boomerang is not offered with star trails (decision 11). public IReadOnlyList Directions { get => _directions; private set => Set(ref _directions, value); } public GatedChoice? SelectedDirection { get => Directions.FirstOrDefault(d => Equals(d.Value, Playback.EffectiveDirection)); set { if (_refreshing || value is not { IsAvailable: true, Value: string direction } || direction == Playback.EffectiveDirection) return; EditPlayback(p => p with { Direction = direction }); } } /// Passes of the whole video, 1 to 10. public double Loops { get => Playback.EffectiveLoops; set { var loops = int.Clamp((int)double.Round(value), 1, PlaybackSettings.MaxLoops); if (_refreshing || loops == Playback.EffectiveLoops) return; EditPlayback(p => p with { Loops = loops }, "Export.Loops"); } } /// "×2". public string LoopsText => Loc.L("Export.Summary.Loops", Playback.EffectiveLoops); /// Seconds of fade from black (slider 0–10, step 0.5; the field takes up to 30). public double FadeIn { get => double.Min(Playback.EffectiveFadeIn, SliderSeconds); set => SetSeconds(value, Playback.EffectiveFadeIn, (p, v) => p with { FadeIn = v }, "Export.FadeIn"); } public double FadeOut { get => double.Min(Playback.EffectiveFadeOut, SliderSeconds); set => SetSeconds(value, Playback.EffectiveFadeOut, (p, v) => p with { FadeOut = v }, "Export.FadeOut"); } /// Seconds the last frame stays (slider 0–10, step 0.5; the field takes up to 60). public double HoldEnd { get => double.Min(Playback.EffectiveHoldEnd, SliderSeconds); set => SetSeconds(value, Playback.EffectiveHoldEnd, (p, v) => p with { HoldEnd = v }, "Export.HoldEnd"); } public EditableField FadeInField { get; } public EditableField FadeOutField { get; } public EditableField HoldEndField { get; } /// Forward, once, without fades or hold: the project writes no playback (and keeps its settings format). public bool IsPlaybackDefault => Export.Playback is null or { IsDefault: true }; public ICommand ResetPlaybackCommand { get; } // ---- File ---- public EditableField NameTemplate { get; } public IReadOnlyList SaveChoices { get => _saveChoices; private set => Set(ref _saveChoices, value); } /// The project's folder; a server sequence always renders into its exports folder on the server. public SaveChoice? SelectedSave { get => SaveChoices.FirstOrDefault(c => !c.Browse && c.Folder == (CanChooseFolder ? Export.Folder : null)); set { if (_refreshing || value is null) return; if (!value.Browse) { EditExport(e => e with { Folder = value.Folder }); return; } var folder = Editor.Shell.Services.Dialogs.PickFolder(Loc.L("Editor.Export.Browse"), Export.Folder ?? Editor.Session.Content.ExportsFolder); if (folder is not null) EditExport(e => e with { Folder = folder }); else OnPropertyChanged(nameof(SelectedSave)); } } public string SaveToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.FolderServer") : Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty); // ---- Estimate and notices ---- public string? EstimatedSize => Estimated is { } plan ? Formatting.Bytes(plan.Estimate.Bytes) : null; /// "about 5 min · NVENC"; without this PC's encoder for a server sequence. public string? EstimatedTime => Estimated is { } plan ? Loc.L("Editor.Export.About", Formatting.Duration(plan.Estimate.Time)) + (!Editor.IsRemote && plan.Setup.Encoder.Capability is { } c ? Loc.Separator + c.Name : string.Empty) : null; public string? ResultName => Editor.Plan?.FileName; /// What the encoder changed or cannot do, and what the playback could not do (localised notices and render remarks). public IReadOnlyList Notices { get => _notices; private set => Set(ref _notices, value); } /// A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent". public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 }; /// Send again: queues the sending home of every render made here not sent yet; disabled while one is queued from here. public ICommand SendAgainCommand => _sendAgain ??= new AsyncRelayCommand(SendAgainAsync, () => HasUnsent && !_sendQueued); private AsyncRelayCommand? _sendAgain; /// A send was queued from here and the ledger was not read again since. private bool _sendQueued; /// What Send again does, worded for the project's home. public string SendAgainToolTip => WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", Editor.Session.Source is WorkspaceSequenceSource { IsServerHome: true }); private async Task SendAgainAsync() { if (Editor.Session.Source is not WorkspaceSequenceSource source) return; try { _sendQueued = await Editor.Shell.Services.Workspace.SendRendersAsync(source.ProjectId); _sendAgain?.RaiseCanExecuteChanged(); if (_sendQueued) Editor.Shell.Notify(Loc.L("Editor.Render.Sending"), Editor.Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Editor.Shell.Navigate(SectionKey.Jobs)); } catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException) { Log.Warning("editor", $"The renders of workspace project {source.ProjectId} could not be queued to be sent", ex); Editor.Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true); } } /// Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace. public string? UnsentToolTip => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 } source ? Loc.L(source.IsServerHome ? "Tooltips.Editor.Render.NotSent.Server" : "Tooltips.Editor.Render.NotSent") : null; public IReadOnlyList Batch => Export.Batch; /// Completes when the preset estimates in flight are done. public Task EstimatesIdle => _estimates.Idle; private ExportSettings Export => Editor.Session.Project.Export; private PlaybackSettings Playback => Export.Playback ?? new PlaybackSettings(); /// The project's export as the plan resolves it, read at once (the plan follows an edit later). private ResolvedExport Resolved => ExportResolver.Resolve(Export); /// The export's preset without overrides: what Auto and Reset go back to. private ResolvedExport PresetValues => ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() }); /// The plan when its estimates mean something: this PC can encode it, or the server renders it. private ExportPlan? Estimated => Editor.Plan is { } plan && (Editor.IsRemote || plan.Setup.Encoder.IsReady) ? plan : null; public bool IsInBatch(string presetId) => Export.Batch.Contains(presetId, StringComparer.OrdinalIgnoreCase); public void SetInBatch(string presetId, bool value) { if (value == IsInBatch(presetId)) return; EditExport(e => e with { Batch = value ? [.. e.Batch, presetId] : [.. e.Batch.Where(b => !b.Equals(presetId, StringComparison.OrdinalIgnoreCase))] }); } /// The preset table takes more of the height than the preview (Export.html). public override bool PrefersTallMeasure => true; /// /// The Resolution choice of : Preset without a box of its own, Source for 0 × 0, a standard /// size for its box, else Custom (also while , chosen to type a size). /// public static string ResolutionKey(ExportOverrides overrides, bool custom = false) { ArgumentNullException.ThrowIfNull(overrides); if (custom) return CustomResolution; return (overrides.Width, overrides.Height) switch { (null, null) => PresetResolution, (0, 0) => SourceResolution, ({ } w, { } h) when ExportRules.StandardResolutions.FirstOrDefault(r => r.Width == w && r.Height == h) is { Key: { } key } => key, _ => CustomResolution, }; } public override void Refresh() { base.Refresh(); _refreshing = true; try { UpdateLists(); LoadFields(); SaveChoices = !CanChooseFolder ? [new SaveChoice(null)] : Export.Folder is { } folder ? [new SaveChoice(null), new SaveChoice(folder), new SaveChoice(null, Browse: true)] : [new SaveChoice(null), new SaveChoice(null, Browse: true)]; if (!NameTemplate.IsDirty) NameTemplate.Load(Export.NameTemplate); UpdateSummaries(); OnAllPropertiesChanged(); } finally { _refreshing = false; } SelectRows(); foreach (var row in Presets) row.RefreshBatch(); _ = EstimateRowsAsync(); } public override void OnPlanChanged() { _refreshing = true; try { LoadFields(); UpdateLists(); Notices = Editor.Plan is { } plan ? PlanNotices(plan) : []; UpdateSummaries(); OnAllPropertiesChanged(); } finally { _refreshing = false; } // The plan follows the preset a read-only session chose to render. SelectRows(); } public override void OnBusyChanged() { base.OnBusyChanged(); foreach (var row in Presets) row.RefreshLocked(); } public override void OnContentChanged() { // The ledger was read again: Send again goes by what it holds now. _sendQueued = false; _sendAgain?.RaiseCanExecuteChanged(); LoadTable(); if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault(); // The rows and groups keep texts in objects (a language switch comes this way too). _keyframeChoices = _bFrameChoices = _profileChoices = []; _directions = []; foreach (var group in new[] { OutputGroup, EncodingGroup, PlaybackGroup, FileGroup }) group.Refresh(); base.OnContentChanged(); } public override void RefreshCommands() { _renderNow.RaiseCanExecuteChanged(); _addToQueue.RaiseCanExecuteChanged(); _batch.RaiseCanExecuteChanged(); _restore.RaiseCanExecuteChanged(); OnPropertyChanged(nameof(AddToQueueToolTip)); OnPropertyChanged(nameof(BatchToolTip)); OnPropertyChanged(nameof(RestoreToolTip)); } public override void OnSyncGateChanged() { OnPropertyChanged(nameof(CanSync)); OnPropertyChanged(nameof(SyncToolTip)); FileGroup.Summary = FileSummary(); } public override void Dispose() { _estimates.Dispose(); base.Dispose(); } /// /// Width and Height edit the preset's box, which the chosen proportions are fitted in (owner review 1, R5): they show the /// resolved box (empty for a side the preset leaves to the source), not the size rendered (Output size). The playback /// fields show the seconds in force. /// private void LoadFields() { var resolved = Resolved; if (!Width.IsDirty) Width.Load(resolved.Width > 0 ? resolved.Width.ToString(CultureInfo.InvariantCulture) : string.Empty); if (!Height.IsDirty) Height.Load(resolved.Height > 0 ? resolved.Height.ToString(CultureInfo.InvariantCulture) : string.Empty); var playback = Playback; if (!FadeInField.IsDirty) FadeInField.Load(SecondsText(playback.EffectiveFadeIn)); if (!FadeOutField.IsDirty) FadeOutField.Load(SecondsText(playback.EffectiveFadeOut)); if (!HoldEndField.IsDirty) HoldEndField.Load(SecondsText(playback.EffectiveHoldEnd)); } /// The one-line summaries the groups show while collapsed. private void UpdateSummaries() { var resolved = Resolved; var settings = Editor.Plan?.Setup.Encoder.Settings; OutputGroup.Summary = EditorText.Format(resolved, settings?.Width ?? resolved.Width, settings?.Height ?? resolved.Height); EncodingGroup.Summary = ExportSummaries.Encoding(resolved, settings?.BitRate ?? resolved.BitRate); PlaybackGroup.Summary = ExportSummaries.Playback(Export.Playback); FileGroup.Summary = FileSummary(); } private string FileSummary() => ExportSummaries.File(ResultName, SelectedSave?.Label ?? Loc.L("Editor.Export.SequenceFolder"), SyncToServer && CanSync); /// "2160 × 3840". private static string SizeText((int Width, int Height) size) => size.Width.ToString(Loc.Culture) + " × " + size.Height.ToString(Loc.Culture); /// /// The encoder's largest size turned as the output is (as fits it) when the output is /// larger; otherwise the codec level capped it, and the size made is the largest it takes. /// private static (int Width, int Height) LargestTaken(ExportPlan plan) { var (width, height) = plan.OutputSize; if (plan.Setup.Encoder.Capability is not { } capability) return plan.EncodedSize; var (maxWidth, maxHeight) = (width >= height) == (capability.MaxWidth >= capability.MaxHeight) ? (capability.MaxWidth, capability.MaxHeight) : (capability.MaxHeight, capability.MaxWidth); return width > maxWidth || height > maxHeight ? (maxWidth, maxHeight) : plan.EncodedSize; } /// The choices that depend on the resolved codec and the project (new lists only when they change, so selections stay bound). private void UpdateLists() { var resolved = Resolved; if (CodecChoices.FirstOrDefault()?.Container != resolved.Container) CodecChoices = [.. Codecs.Where(c => c.Container == resolved.Container)]; var encoders = EncoderChoices(resolved.Codec); if (!encoders.Select(e => e.Value).SequenceEqual(Encoders.Select(e => e.Value))) Encoders = encoders; int[] depths = resolved.Codec switch { VideoCodec.Hevc or VideoCodec.Av1 => [8, 10], VideoCodec.PngSequence or VideoCodec.Tiff16Sequence => [8, 16], _ => [resolved.BitDepth], }; if (!depths.SequenceEqual(Depths.Select(d => (int)d.Value))) Depths = [.. depths.Select(d => new Choice(d, "Editor.Export.Depth", d))]; // Auto names the preset's own value (its keyframe interval is in seconds, whatever the frame rate). var preset = PresetValues; var autoKeyframes = Auto(ExportRules.Seconds(ExportRules.GopSeconds(preset.GopFrames, preset.FrameRate))); if (KeyframeChoices.FirstOrDefault()?.Label != autoKeyframes) KeyframeChoices = [new Choice(0.0, "Editor.Value.Text", autoKeyframes), .. ExportRules.KeyframeSeconds.Select(s => new Choice(s, "Editor.Value.Text", ExportRules.Seconds(s)))]; var autoBFrames = Auto(preset.BFrames.ToString(Loc.Culture)); if (BFrameChoices.FirstOrDefault()?.Label != autoBFrames) BFrameChoices = [new Choice(-1, "Editor.Value.Text", autoBFrames), .. ExportRules.BFrameCounts.Select(n => new Choice(n, "Editor.Value.Number", n))]; var profiles = ExportRules.Profiles(resolved.Codec, resolved.BitDepth); if (!profiles.Cast().SequenceEqual(ProfileChoices.Select(c => c.Value))) ProfileChoices = [.. profiles.Select(p => new Choice(p, "Editor.Value.Text", ExportRules.ProfileLabel(p)))]; var starTrails = Editor.Session.Project.Stack.Mode == StackSetting.StarTrails; if (Directions.Count == 0 || Directions.Any(d => (string)d.Value == PlaybackDirection.Boomerang && d.IsAvailable == starTrails)) { Directions = [ .. PlaybackDirection.All.Select(d => { var blocked = starTrails && d == PlaybackDirection.Boomerang; return new GatedChoice(d, ExportSummaries.DirectionLabel(d), !blocked, Loc.L(blocked ? "Tooltips.Export.BoomerangStack" : "Tooltips.Export.Direction")); }), ]; } } /// "Auto · 1 s". private static string Auto(string value) => Loc.L("Export.Auto") + Loc.Separator + value; private void LoadTable() { Presets = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetRow(this, c))]; PresetGroups = PresetTable.Build(Presets, Resolved.PresetId); } /// The row of the export preset the plan renders. private void SelectRows() { foreach (var row in Presets) row.IsSelected = row.Choice.Sequence is null && string.Equals(row.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase); } /// /// What the plan changed or cannot do, localised; for a server sequence without this PC's encoder notices (the server /// or its render node picks the encoder). The output program's remarks (fades shortened, a direction not known) follow. /// private IReadOnlyList PlanNotices(ExportPlan plan) { var encoder = Editor.IsRemote ? plan.Setup.Encoder.Notices.Select(n => n.Key).ToHashSet(StringComparer.Ordinal) : []; return [.. plan.Setup.Warnings.Where(w => !encoder.Contains(w.Key)).Select(w => Loc.L(w.Key, [.. w.Args])) .Concat(plan.Export.Warnings.Select(k => Loc.L(k))) .Concat(plan.Program?.Warnings.Select(w => Loc.L(w.Key, [.. w.Args])) ?? []).Distinct()]; } /// Estimates every preset off the UI thread for the project as it is now (latest request wins). private async Task EstimateRowsAsync() { var project = Editor.Session.Project; var rows = Presets; var plans = new ExportPlan?[rows.Count]; var done = false; try { await _estimates.Schedule(token => { for (var i = 0; i < rows.Count; i++) { token.ThrowIfCancellationRequested(); // The playback stays: a preset renders with the loops and holds of the export (batch presets inherit it). var export = project.Export with { Preset = project.Export.Preset.WithManual(rows[i].Choice.ExportPresetId), Overrides = new ExportOverrides(), Batch = [] }; plans[i] = Editor.Planner.Plan(project, export); } done = true; return Task.CompletedTask; }); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { Log.Warning("editor", "Preset estimates failed", ex); return; } // A superseded request stops part way (or never starts); undo can bring back the same project instance. if (!done || !ReferenceEquals(rows, Presets) || !ReferenceEquals(project, Editor.Session.Project)) return; for (var i = 0; i < rows.Count; i++) rows[i].Update(plans[i]); } /// /// Makes the chosen copy the project as one undo step. The toast's Undo brings back the project as it was before, as /// a new step, while the restore is still the last change of this editor (a later edit would otherwise be undone). /// private async Task RestoreAsync() { if (SelectedCopy is not { } copy) return; ProjectRestore? restore; try { restore = await Editor.Session.RestoreAsync(copy); } catch (InvalidDataException ex) { Editor.Shell.ReportError(ex); return; } if (restore is null) { Editor.Shell.Notify(Loc.L("Editor.Copy.Same"), copy.Label); return; } var editor = Editor; editor.Shell.ShowToast(new Toast { Title = Loc.L("Editor.Copy.Restored"), Message = copy.Label, ActionText = Loc.L("Editor.Copy.Undo"), ActionToolTip = Loc.L("Tooltips.Editor.Copy.Undo"), // Only in the editor that made it: another sequence opened meanwhile has its own project. ActionCommand = new RelayCommand(() => restore.Undo(), () => ReferenceEquals(editor.Shell.Sequence.Editor, editor) && restore.CanUndo), }); } private void OpenVideos() => Editor.Shell.OpenVideos(Editor.Session.Content.Sequence.Id, Editor.Title); private void Select(PresetRow? row) { if (row is null) return; _customResolution = false; if (row.Choice.Sequence is { } preset) Editor.Session.ApplyPreset(preset); else EditExport(e => e with { Preset = e.Preset.WithManual(row.Choice.ExportPresetId), Overrides = new ExportOverrides() }); } private void SelectCodec(CodecChoice choice) => EditOverrides(o => o with { Codec = ProcessingJobs.CodecName(choice.Codec), Profile = choice.Profile == CodecProfile.Auto ? null : choice.Profile.ToString(), BitDepth = choice.BitDepth, BitRate = null, Encoder = null, }); /// /// Sets the frame rate (null: the preset's). A keyframe interval chosen by hand is kept in seconds (decision 6), so /// its frames follow the new rate. /// private void SetFrameRate(string? rate) { var from = Resolved.FrameRate; var to = rate is not null && FrameRateText.TryParse(rate, out var parsed) ? parsed : PresetValues.FrameRate; EditOverrides(o => o with { FrameRate = rate, GopFrames = o.GopFrames is { } gop ? ExportRules.RescaleGop(gop, from, to) : null }); } private IReadOnlyList EncoderChoices(VideoCodec codec) { var names = Editor.Planner.Encoders.SelectMany(p => p.Capabilities).Where(c => c.Codec == codec).Select(c => c.Name).Distinct(); return [new Choice(string.Empty, "Editor.Export.EncoderAuto"), .. names.Select(n => new Choice(n, "Editor.Value.Text", n))]; } private void EditExport(Func change, string? mergeKey = null) => Editor.Session.Edit(p => p with { Export = change(p.Export) }, mergeKey); private void EditOverrides(Func change, string? mergeKey = null) => EditExport(e => e with { Overrides = change(e.Overrides) }, mergeKey); /// /// Changes the playback; at its default (forward, once, no fades or hold) the export holds none, so an ordinary project /// keeps its settings format (decision 8). /// private void EditPlayback(Func change, string? mergeKey = null) => EditExport(e => e with { Playback = change(e.Playback ?? new PlaybackSettings()) is var p && p.IsDefault ? null : p.Normalized() }, mergeKey); /// A slider of seconds: snapped to 0.5 s; a value the field set above the slider's end stays until the slider moves. private void SetSeconds(double value, double current, Func set, string mergeKey) { var seconds = double.Round(double.Clamp(value, 0, SliderSeconds) * 2) / 2; if (_refreshing || seconds == double.Min(current, SliderSeconds)) return; EditPlayback(p => set(p, seconds), mergeKey); } private EditableField SecondsField(double maximum, Func set, string toolTipKey) => new(SecondsText(0), text => ParseSeconds(text, maximum) is null ? Loc.L("Errors.Number.DecimalRange", 0.ToString("0.##", Loc.Culture), maximum.ToString("0.##", Loc.Culture)) : null, text => EditPlayback(p => set(p, ParseSeconds(text, maximum))), () => Loc.L(toolTipKey)); /// "1.5" in the UI language. private static string SecondsText(double seconds) => seconds.ToString("0.##", Loc.Culture); /// Seconds 0.. in the UI language (or with a point); null when the text is not one. private static double? ParseSeconds(string text, double maximum) { var trimmed = text.Trim(); if (trimmed.Length == 0) return 0; return (double.TryParse(trimmed, NumberStyles.Float, Loc.Culture, out var v) || double.TryParse(trimmed, NumberStyles.Float, CultureInfo.InvariantCulture, out v)) && double.IsFinite(v) && v >= 0 && v <= maximum ? v : null; } private static bool IsBaseline(string? profile) => string.Equals(profile, nameof(CodecProfile.H264Baseline), StringComparison.OrdinalIgnoreCase); private static string? ValidateSize(string text) => text.Length == 0 || (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) && v is >= 16 and <= 16384) ? null : Loc.L("Tooltips.Editor.Export.SizeInvalid"); private static int? ParseSize(string text) => int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : null; private static string? ValidateTemplate(string text) => ExportPlanner.NameError(ExportNaming.Expand(text, new ExportNameContext { Date = DateTime.Today, PresetName = "x", Codec = VideoCodec.H264, }).Errors); private static string Aspect(int width, int height) { if (width <= 0 || height <= 0) return string.Empty; var gcd = (int)Gcd(width, height); var (w, h) = (width / gcd, height / gcd); return w > 64 || h > 64 ? (width / (double)height).ToString("0.00", Loc.Culture) + ":1" : $"{w}:{h}"; } private static long Gcd(long a, long b) { while (b != 0) (a, b) = (b, a % b); return a; } }