Wire the phase 5 parcels into one working whole. - Save frame works in a workspace project. WorkspaceSequenceSource now makes still jobs (IProjectStills) routed like its renders: with the originals on this PC, a WorkspaceRender still into exports/; with proxies only, the home's still job with the portable settings and the project id. The tooltip for a source that saves no frames is now a real string. - The Export footer has Save project file again for library sequences; workspace projects keep it in their project menu only. - Sync render downloads are hashed and compared with the server's sha256 (one retry, then the job fails without filing the file), and uploads and downloads carry the render kind, so a saved frame no longer counts as a recent preset. - Add the missing en/it strings: still frame out of the sequence (Core and both job handlers), keyframes not applicable, workspace stills, Videos refresh / clear sequence / play-from-server tips, the videos-folder creation error, and the admin panel kind labels, play and trash tips. - Delete the export history, batch and card strings no longer used from English and prune them from every culture. - Videos: the sequence chip clears only the sequence filter (desktop and admin panel), the desktop remembers cards or list, and a Refresh button. Refs #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1085 lines
52 KiB
C#
1085 lines
52 KiB
C#
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;
|
||
|
||
/// <summary>A codec choice of the Output panel with the profile and depth it implies.</summary>
|
||
public sealed record CodecChoice(VideoCodec Codec, CodecProfile Profile, int BitDepth)
|
||
{
|
||
public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec);
|
||
|
||
public string Label => EditorText.CodecName(Codec, Profile, BitDepth);
|
||
}
|
||
|
||
/// <summary>Where renders go: the sequence's exports folder or a folder the user picked.</summary>
|
||
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('\\', '/'));
|
||
}
|
||
|
||
/// <summary>A choice that may not apply now (Boomerang with star trails): disabled in the list, its reason in the tooltip.</summary>
|
||
public sealed record GatedChoice(object Value, string Label, bool IsAvailable, string ToolTip);
|
||
|
||
/// <summary>
|
||
/// 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).
|
||
/// </summary>
|
||
public sealed class ExportTab : EditorTab
|
||
{
|
||
public static IReadOnlyList<CodecChoice> 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),
|
||
];
|
||
|
||
/// <summary>The Resolution choice's value for the preset's own box (no override).</summary>
|
||
public const string PresetResolution = "preset";
|
||
|
||
/// <summary>The Resolution choice's value for the source size (a box of 0 × 0).</summary>
|
||
public const string SourceResolution = "source";
|
||
|
||
/// <summary>The Resolution choice's value that shows the Width × Height fields.</summary>
|
||
public const string CustomResolution = "custom";
|
||
|
||
/// <summary>The longest fade or hold the sliders reach (seconds); the fields take up to the playback's own limits.</summary>
|
||
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<PresetRow> _presets = [];
|
||
private IReadOnlyList<PresetGroup> _presetGroups = [];
|
||
private IReadOnlyList<CodecChoice> _codecChoices = [];
|
||
private IReadOnlyList<Choice> _encoders = [];
|
||
private IReadOnlyList<SaveChoice> _saveChoices = [];
|
||
private IReadOnlyList<Choice> _depths = [];
|
||
private IReadOnlyList<Choice> _keyframeChoices = [];
|
||
private IReadOnlyList<Choice> _bFrameChoices = [];
|
||
private IReadOnlyList<Choice> _profileChoices = [];
|
||
private IReadOnlyList<GatedChoice> _directions = [];
|
||
private IReadOnlyList<string> _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) ----
|
||
|
||
/// <summary>Every preset, in table order.</summary>
|
||
public IReadOnlyList<PresetRow> Presets { get => _presets; private set => Set(ref _presets, value); }
|
||
|
||
/// <summary>The presets by group (Video, Social, Intermediate, Image sequence, Web), each one opened or closed.</summary>
|
||
public IReadOnlyList<PresetGroup> 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;
|
||
|
||
/// <summary>"Reveal in Explorer" for the newest render (BRIEF §11.5 follow-up).</summary>
|
||
public ICommand RevealLastCommand { get; }
|
||
|
||
public string AddToQueueToolTip => Editor.RenderBlockedReason ?? Loc.L("Tooltips.Editor.Export.AddToQueue");
|
||
|
||
/// <summary>"Batch (2)": the ticked presets.</summary>
|
||
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"));
|
||
|
||
/// <summary>The newest render is a file on this PC (a server's renders stay on the server).</summary>
|
||
public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
|
||
|
||
/// <summary>"Videos (3)": the renders of this sequence.</summary>
|
||
public string VideosText => Loc.L("Export.Footer.Videos", Editor.Session.Content.Renders.Count.ToString("N0", Loc.Culture));
|
||
|
||
/// <summary>Opens the Videos section filtered on this sequence (owner review 1, R9).</summary>
|
||
public ICommand VideosCommand { get; }
|
||
|
||
/// <summary>The app has a Videos section to open.</summary>
|
||
public bool CanOpenVideos => VideosLink.Find(Editor.Shell.AllSections) is not null;
|
||
|
||
/// <summary>
|
||
/// "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.
|
||
/// </summary>
|
||
public string? FooterSummary => Editor.Plan is { } plan
|
||
? ExportSummaries.Footer(plan.FileName, Estimated?.Estimate, plan.DurationSeconds, plan.FrameCount)
|
||
: null;
|
||
|
||
/// <summary>
|
||
/// Saves a <c>.chronos</c> 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.
|
||
/// </summary>
|
||
public ICommand SaveProjectCommand { get; }
|
||
|
||
public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save");
|
||
|
||
// ---- File: Sync ----
|
||
|
||
/// <summary>Send each render made on this PC to the server the sequence is linked to; remembered in the project.</summary>
|
||
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;
|
||
|
||
/// <summary>What Sync does, or why it cannot be used for this sequence now.</summary>
|
||
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",
|
||
});
|
||
|
||
/// <summary>A server sequence renders into its exports folder on the server.</summary>
|
||
public bool CanChooseFolder => !Editor.IsRemote;
|
||
|
||
// ---- File: "Save both" copies of this PC's settings ----
|
||
|
||
public IReadOnlyList<SavedCopy> SavedCopies => Editor.Session.Content.SavedCopies;
|
||
|
||
public bool HasSavedCopies => SavedCopies.Count > 0;
|
||
|
||
/// <summary>The copy Restore makes the project: the newest unless another is chosen in the menu.</summary>
|
||
public SavedCopy? SelectedCopy
|
||
{
|
||
get => _selectedCopy;
|
||
set
|
||
{
|
||
if (!Set(ref _selectedCopy, value)) return;
|
||
OnPropertyChanged(nameof(RestoreText));
|
||
OnPropertyChanged(nameof(RestoreToolTip));
|
||
_restore.RaiseCanExecuteChanged();
|
||
}
|
||
}
|
||
|
||
/// <summary>"Restore settings · 03/10/2026 14:22".</summary>
|
||
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 ----
|
||
|
||
/// <summary>"Output · 4K archive".</summary>
|
||
public string Title => Loc.L("Editor.Export.Output", Editor.Plan?.PresetName ?? ProcessingJobs.PresetName(ExportResolver.Resolve(Export)));
|
||
|
||
public IReadOnlyList<Choice> 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<CodecChoice> 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);
|
||
}
|
||
}
|
||
|
||
/// <summary>Preset, Source, the standard sizes (720p … 8K) and Custom (decision 7).</summary>
|
||
public IReadOnlyList<Choice> 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"),
|
||
];
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
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 });
|
||
}
|
||
}
|
||
|
||
/// <summary>Custom is chosen: the Width × Height fields show.</summary>
|
||
public bool IsCustomResolution => Equals(SelectedResolution?.Value, CustomResolution);
|
||
|
||
public EditableField Width { get; }
|
||
|
||
public EditableField Height { get; }
|
||
|
||
/// <summary>
|
||
/// "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.
|
||
/// </summary>
|
||
public string? OutputSizeText => Editor.Plan is { } plan ? OutputSizeOf(plan) : null;
|
||
|
||
/// <summary>Where the output size comes from, or the largest size the encoder takes when it capped it.</summary>
|
||
public string OutputSizeToolTip => OutputSizeToolTipOf(Editor.Plan);
|
||
|
||
/// <summary>The Output size row of <paramref name="plan"/>: "2160 × 3840", or "1080 × 1920 (capped)".</summary>
|
||
public static string OutputSizeOf(ExportPlan plan)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(plan);
|
||
return plan.IsCapped ? Loc.L("Editor.Export.Capped", SizeText(plan.EncodedSize)) : SizeText(plan.OutputSize);
|
||
}
|
||
|
||
/// <summary>The Output size row's tooltip for <paramref name="plan"/>.</summary>
|
||
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");
|
||
|
||
/// <summary>"16:9".</summary>
|
||
public string AspectText => Editor.Plan is { } plan ? Aspect(plan.Setup.Encoder.Settings.Width, plan.Setup.Encoder.Settings.Height) : string.Empty;
|
||
|
||
public IReadOnlyList<Choice> 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);
|
||
}
|
||
}
|
||
|
||
/// <summary>The preset's own frame rate is in force (no override).</summary>
|
||
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<Choice> 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<Choice> Encoders { get => _encoders; private set => Set(ref _encoders, value); }
|
||
|
||
/// <summary>The encoder is this PC's choice only for its own renders; the server or its render node picks its own.</summary>
|
||
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 });
|
||
}
|
||
}
|
||
|
||
/// <summary>"hardware", "software" for this PC's encoder (the word, not a colour, carries the state).</summary>
|
||
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;
|
||
|
||
/// <summary>Variable, constant, quality (H.264, HEVC and AV1 only).</summary>
|
||
public IReadOnlyList<Choice> RateControls { get; } =
|
||
[.. Enum.GetValues<RateControl>().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() });
|
||
}
|
||
}
|
||
|
||
/// <summary>The codec has a rate control (and a keyframe interval) to choose.</summary>
|
||
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; }
|
||
|
||
/// <summary>Bit rate in Mb/s (variable and constant rate) or quality 1–100 (quality rate control, JPEG, MJPEG, GIF).</summary>
|
||
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");
|
||
}
|
||
}
|
||
|
||
/// <summary>The slider sets the bit rate: a video codec at variable or constant rate.</summary>
|
||
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");
|
||
|
||
/// <summary>"Bit rate" or "Quality": the row's label follows what the slider sets.</summary>
|
||
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; }
|
||
|
||
/// <summary>Auto (the preset's), then 0.5 to 10 s.</summary>
|
||
public IReadOnlyList<Choice> KeyframeChoices { get => _keyframeChoices; private set => Set(ref _keyframeChoices, value); }
|
||
|
||
/// <summary>
|
||
/// The keyframe interval in seconds (decision 6), stored as whole frames at the export's rate
|
||
/// (<see cref="ExportOverrides.GopFrames"/>); 0 is Auto (the preset's).
|
||
/// </summary>
|
||
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");
|
||
|
||
/// <summary>Auto (the preset's), then 0 to 4.</summary>
|
||
public IReadOnlyList<Choice> BFrameChoices { get => _bFrameChoices; private set => Set(ref _bFrameChoices, value); }
|
||
|
||
/// <summary>B-frames, −1 for Auto (the preset's).</summary>
|
||
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 });
|
||
}
|
||
}
|
||
|
||
/// <summary>Baseline, MJPEG, GIF, APNG and the image sequences take no B-frames.</summary>
|
||
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");
|
||
|
||
/// <summary>The profiles of the codec at the chosen depth.</summary>
|
||
public IReadOnlyList<Choice> 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) ----
|
||
|
||
/// <summary>Forward, Reverse, Boomerang; Boomerang is not offered with star trails (decision 11).</summary>
|
||
public IReadOnlyList<GatedChoice> 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 });
|
||
}
|
||
}
|
||
|
||
/// <summary>Passes of the whole video, 1 to 10.</summary>
|
||
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");
|
||
}
|
||
}
|
||
|
||
/// <summary>"×2".</summary>
|
||
public string LoopsText => Loc.L("Export.Summary.Loops", Playback.EffectiveLoops);
|
||
|
||
/// <summary>Seconds of fade from black (slider 0–10, step 0.5; the field takes up to 30).</summary>
|
||
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");
|
||
}
|
||
|
||
/// <summary>Seconds the last frame stays (slider 0–10, step 0.5; the field takes up to 60).</summary>
|
||
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; }
|
||
|
||
/// <summary>Forward, once, without fades or hold: the project writes no playback (and keeps its settings format).</summary>
|
||
public bool IsPlaybackDefault => Export.Playback is null or { IsDefault: true };
|
||
|
||
public ICommand ResetPlaybackCommand { get; }
|
||
|
||
// ---- File ----
|
||
|
||
public EditableField NameTemplate { get; }
|
||
|
||
public IReadOnlyList<SaveChoice> SaveChoices { get => _saveChoices; private set => Set(ref _saveChoices, value); }
|
||
|
||
/// <summary>The project's folder; a server sequence always renders into its exports folder on the server.</summary>
|
||
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;
|
||
|
||
/// <summary>"about 5 min · NVENC"; without this PC's encoder for a server sequence.</summary>
|
||
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;
|
||
|
||
/// <summary>What the encoder changed or cannot do, and what the playback could not do (localised notices and render remarks).</summary>
|
||
public IReadOnlyList<string> Notices { get => _notices; private set => Set(ref _notices, value); }
|
||
|
||
/// <summary>A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".</summary>
|
||
public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
|
||
|
||
/// <summary>Send again: queues the sending home of every render made here not sent yet; disabled while one is queued from here.</summary>
|
||
public ICommand SendAgainCommand => _sendAgain ??= new AsyncRelayCommand(SendAgainAsync, () => HasUnsent && !_sendQueued);
|
||
|
||
private AsyncRelayCommand? _sendAgain;
|
||
|
||
/// <summary>A send was queued from here and the ledger was not read again since.</summary>
|
||
private bool _sendQueued;
|
||
|
||
/// <summary>What Send again does, worded for the project's home.</summary>
|
||
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace.</summary>
|
||
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<string> Batch => Export.Batch;
|
||
|
||
/// <summary>Completes when the preset estimates in flight are done.</summary>
|
||
public Task EstimatesIdle => _estimates.Idle;
|
||
|
||
private ExportSettings Export => Editor.Session.Project.Export;
|
||
|
||
private PlaybackSettings Playback => Export.Playback ?? new PlaybackSettings();
|
||
|
||
/// <summary>The project's export as the plan resolves it, read at once (the plan follows an edit later).</summary>
|
||
private ResolvedExport Resolved => ExportResolver.Resolve(Export);
|
||
|
||
/// <summary>The export's preset without overrides: what Auto and Reset go back to.</summary>
|
||
private ResolvedExport PresetValues => ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() });
|
||
|
||
/// <summary>The plan when its estimates mean something: this PC can encode it, or the server renders it.</summary>
|
||
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))] });
|
||
}
|
||
|
||
/// <summary>The preset table takes more of the height than the preview (Export.html).</summary>
|
||
public override bool PrefersTallMeasure => true;
|
||
|
||
/// <summary>
|
||
/// The Resolution choice of <paramref name="overrides"/>: Preset without a box of its own, Source for 0 × 0, a standard
|
||
/// size for its box, else Custom (also while <paramref name="custom"/>, chosen to type a size).
|
||
/// </summary>
|
||
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();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
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));
|
||
}
|
||
|
||
/// <summary>The one-line summaries the groups show while collapsed.</summary>
|
||
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);
|
||
|
||
/// <summary>"2160 × 3840".</summary>
|
||
private static string SizeText((int Width, int Height) size) =>
|
||
size.Width.ToString(Loc.Culture) + " × " + size.Height.ToString(Loc.Culture);
|
||
|
||
/// <summary>
|
||
/// The encoder's largest size turned as the output is (as <see cref="EncoderSelector"/> fits it) when the output is
|
||
/// larger; otherwise the codec level capped it, and the size made is the largest it takes.
|
||
/// </summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>The choices that depend on the resolved codec and the project (new lists only when they change, so selections stay bound).</summary>
|
||
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<object>().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"));
|
||
}),
|
||
];
|
||
}
|
||
}
|
||
|
||
/// <summary>"Auto · 1 s".</summary>
|
||
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);
|
||
}
|
||
|
||
/// <summary>The row of the export preset the plan renders.</summary>
|
||
private void SelectRows()
|
||
{
|
||
foreach (var row in Presets)
|
||
row.IsSelected = row.Choice.Sequence is null && string.Equals(row.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
private IReadOnlyList<string> 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()];
|
||
}
|
||
|
||
/// <summary>Estimates every preset off the UI thread for the project as it is now (latest request wins).</summary>
|
||
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]);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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).
|
||
/// </summary>
|
||
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,
|
||
});
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
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<Choice> 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<ExportSettings, ExportSettings> change, string? mergeKey = null) =>
|
||
Editor.Session.Edit(p => p with { Export = change(p.Export) }, mergeKey);
|
||
|
||
private void EditOverrides(Func<ExportOverrides, ExportOverrides> change, string? mergeKey = null) =>
|
||
EditExport(e => e with { Overrides = change(e.Overrides) }, mergeKey);
|
||
|
||
/// <summary>
|
||
/// 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).
|
||
/// </summary>
|
||
private void EditPlayback(Func<PlaybackSettings, PlaybackSettings> change, string? mergeKey = null) =>
|
||
EditExport(e => e with { Playback = change(e.Playback ?? new PlaybackSettings()) is var p && p.IsDefault ? null : p.Normalized() }, mergeKey);
|
||
|
||
/// <summary>A slider of seconds: snapped to 0.5 s; a value the field set above the slider's end stays until the slider moves.</summary>
|
||
private void SetSeconds(double value, double current, Func<PlaybackSettings, double?, PlaybackSettings> 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<PlaybackSettings, double?, PlaybackSettings> 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));
|
||
|
||
/// <summary>"1.5" in the UI language.</summary>
|
||
private static string SecondsText(double seconds) => seconds.ToString("0.##", Loc.Culture);
|
||
|
||
/// <summary>Seconds 0..<paramref name="maximum"/> in the UI language (or with a point); null when the text is not one.</summary>
|
||
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;
|
||
}
|
||
}
|