Files
Chronos/src/Titano.App/Editor/ExportTab.cs
T
Claude 2ffc0268a7 feat(app): .titano project files that open their sequence with its settings
Setup registered .titano with Titano.exe "%1", but nothing wrote such a file
and Titano ignored the argument (BRIEF §18).

- Core ProjectBundle: versioned UTF-8 JSON ("titano-project", format 1) with
  the archive (id, name, path), the sequence (id, folder, title, frame
  count) and the project settings as project.json holds them; newer or
  foreign files are refused, frame positions apply only to the frames they
  were saved for, saving never replaces an earlier file.
- Data ProjectBundles: the file for a sequence of the index, and the sequence
  a file names (by id, else the same folder of the same archive).
- Editor: "Save project file" on the Export tab (sequences of this PC's
  archives); opening a file shows its sequence and applies the settings as
  one undo step with an Undo toast, or says in one sentence why not (not in
  the library, unreadable, a job runs).
- Titano.exe opens its file argument once the index is open and runs once
  per data folder: a later launch hands its file over a current-user named
  pipe, lets the running window come to the front and exits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 10:29:37 +00:00

668 lines
30 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Settings;
using Titano.Core.Advice;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Video;
using Titano.Data.Processing;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Editor;
/// <summary>A preset card of the Export tab (Export.html): what it renders and what it will cost on this machine.</summary>
public sealed class PresetCard(ExportTab owner, ExportChoice choice) : ObservableObject
{
private string? _format;
private string? _encoding;
private string? _estimate;
private bool _isSelected;
public ExportChoice Choice { get; } = choice;
public string Name => Choice.Name;
public bool IsRecommended => Choice.IsRecommended;
/// <summary>Sequence presets apply full settings; export presets only choose the output.</summary>
public bool IsSequencePreset => Choice.Sequence is not null;
/// <summary>What choosing the card does, or why it cannot be chosen now (a job runs, the project cannot change).</summary>
public string ToolTip => owner.Editor.LockedToolTip ?? (Choice.Reason is { } reason
? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason)
: Loc.L("Tooltips.Editor.Export.Preset", Name));
public string BatchToolTip => owner.Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.InBatch");
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
public string? Format { get => _format; private set => Set(ref _format, value); }
/// <summary>"120 Mb/s · 0.07 bpp · NVENC".</summary>
public string? Encoding { get => _encoding; private set => Set(ref _encoding, value); }
/// <summary>"2.2 GB · about 5 min".</summary>
public string? Estimate { get => _estimate; private set => Set(ref _estimate, value); }
public bool IsSelected { get => _isSelected; set => Set(ref _isSelected, value); }
/// <summary>Ticked for "Batch…" (export presets only).</summary>
public bool IsInBatch
{
get => owner.IsInBatch(Choice.ExportPresetId);
set => owner.SetInBatch(Choice.ExportPresetId, value);
}
public bool CanBatch => !IsSequencePreset;
public ICommand SelectCommand => owner.SelectCommand;
/// <remarks>A server sequence renders on the server: this PC's encoders neither name nor rule out the encoding.</remarks>
public void Update(ExportPlan? plan)
{
if (plan is null)
{
Format = Encoding = Estimate = null;
return;
}
var settings = plan.Setup.Encoder.Settings;
var remote = owner.Editor.IsRemote;
Format = EditorText.Format(plan.Export, settings.Width, settings.Height);
Encoding = EditorText.Encoding(plan.Export, settings.BitRate, remote ? null : plan.Setup.Encoder.Capability?.Name);
Estimate = remote || plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable");
}
public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch));
/// <summary>A job of the sequence started or ended, or the project became read-only: the tooltips say why the card waits.</summary>
public void RefreshLocked()
{
OnPropertyChanged(nameof(ToolTip));
OnPropertyChanged(nameof(BatchToolTip));
}
}
/// <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>
/// Export (Export.html, BRIEF §11.4–11.5): preset cards with size and time estimates, the Output panel (container,
/// codec, size, frame rate, quality, encoder, colour depth, name template, folder) with the estimate and the encoder's
/// notices, 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),
];
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<PresetCard> _cards = [];
private IReadOnlyList<CodecChoice> _codecChoices = [];
private IReadOnlyList<Choice> _encoders = [];
private IReadOnlyList<SaveChoice> _saveChoices = [];
private IReadOnlyList<Choice> _depths = [];
private IReadOnlyList<string> _notices = [];
private bool _refreshing;
public ExportTab(EditorViewModel editor)
: base(editor, "Export", AdvisorSection.Export)
{
SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !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);
HistoryCommand = new RelayCommand(OpenHistory);
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal);
_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(() => EditOverrides(o => o with { FrameRate = null }));
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"));
_selectedCopy = SavedCopies.FirstOrDefault();
LoadCards();
Refresh();
}
public IReadOnlyList<PresetCard> Cards { get => _cards; private set => Set(ref _cards, value); }
public ICommand SelectCommand { get; }
public ICommand RenderNowCommand => _renderNow;
public ICommand AddToQueueCommand => _addToQueue;
public ICommand BatchCommand => _batch;
/// <summary>Jobs, filtered on this sequence (its renders and analyses).</summary>
public ICommand HistoryCommand { get; }
/// <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");
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.Editor.Export.Batch"));
public bool HasHistory => Editor.Session.Content.Renders.Count > 0;
/// <summary>The "history" link opens this PC's Jobs screen, which does not list a server's jobs.</summary>
public bool CanOpenHistory => !Editor.IsRemote;
/// <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>
/// Saves a <c>.titano</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.
/// </summary>
public ICommand SaveProjectCommand { get; }
public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save");
// ---- Export "Sync" (Export.html, next to Save to) ----
/// <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;
// ---- "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;
public ICommand ResetFrameRateCommand { get; }
/// <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);
}
}
public EditableField Width { get; }
public EditableField Height { get; }
/// <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) EditOverrides(o => o with { FrameRate = 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));
/// <summary>Bit rate in Mb/s (video) or quality 1–100 (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");
}
}
public bool IsBitRate => !VideoCodecInfo.IsManaged(Resolved.Codec);
public double QualityMaximum => IsBitRate ? 400 : 100;
public bool IsQualityApplicable => IsBitRate || Resolved.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif;
public string? QualityNotApplicable => IsQualityApplicable ? null : Loc.L("Tooltips.Editor.NotApplicable.Lossless");
public string QualityText => IsBitRate ? EditorText.BitRate((long)(Quality * 1e6)) : Quality.ToString("0", Loc.Culture);
public string QualityToolTip => Loc.L(IsBitRate ? "Tooltips.Editor.Export.BitRate" : "Tooltips.Editor.Export.Quality");
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;
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;
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);
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 (localised notices and render remarks).</summary>
public IReadOnlyList<string> Notices { get => _notices; private set => Set(ref _notices, value); }
/// <summary>"Previous renders of this sequence: 2 · last 2026-09-21".</summary>
public string HistoryText => Editor.Session.Content.Renders is { Count: > 0 } renders
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory");
public IReadOnlyList<string> Batch => Export.Batch;
/// <summary>Completes when the card estimates in flight are done.</summary>
public Task EstimatesIdle => _estimates.Idle;
private ExportSettings Export => Editor.Session.Project.Export;
private ResolvedExport Resolved => Editor.Plan?.Export ?? ExportResolver.Resolve(Export);
/// <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))] });
}
public override void Refresh()
{
base.Refresh();
_refreshing = true;
try
{
UpdateLists();
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);
OnAllPropertiesChanged();
}
finally
{
_refreshing = false;
}
SelectCards();
foreach (var card in Cards) card.RefreshBatch();
_ = EstimateCardsAsync();
}
public override void OnPlanChanged()
{
_refreshing = true;
try
{
var settings = Editor.Plan?.Setup.Encoder.Settings;
if (!Width.IsDirty) Width.Load(settings?.Width.ToString(CultureInfo.InvariantCulture) ?? string.Empty);
if (!Height.IsDirty) Height.Load(settings?.Height.ToString(CultureInfo.InvariantCulture) ?? string.Empty);
UpdateLists();
Notices = Editor.Plan is { } plan ? PlanNotices(plan) : [];
OnAllPropertiesChanged();
}
finally
{
_refreshing = false;
}
// The plan follows the preset a read-only session chose to render.
SelectCards();
}
public override void OnBusyChanged()
{
base.OnBusyChanged();
foreach (var card in Cards) card.RefreshLocked();
}
public override void OnContentChanged()
{
LoadCards();
if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
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));
}
public override void Dispose()
{
_estimates.Dispose();
base.Dispose();
}
/// <summary>The choices that depend on the resolved codec (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))];
}
private void LoadCards() => Cards = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetCard(this, c))];
/// <summary>The card of the export preset the plan renders.</summary>
private void SelectCards()
{
foreach (var card in Cards)
card.IsSelected = card.Choice.Sequence is null && string.Equals(card.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).
/// </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))).Distinct()];
}
/// <summary>Estimates every card off the UI thread for the project as it is now (latest request wins).</summary>
private async Task EstimateCardsAsync()
{
var project = Editor.Session.Project;
var cards = Cards;
var plans = new ExportPlan?[cards.Count];
var done = false;
try
{
await _estimates.Schedule(token =>
{
for (var i = 0; i < cards.Count; i++)
{
token.ThrowIfCancellationRequested();
var export = project.Export with { Preset = project.Export.Preset.WithManual(cards[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)
{
Core.Diagnostics.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(cards, Cards) || !ReferenceEquals(project, Editor.Session.Project)) return;
for (var i = 0; i < cards.Count; i++) cards[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 OpenHistory()
{
Editor.Shell.Jobs.Filter = Jobs.JobFilter.All;
Editor.Shell.Jobs.SearchText = Editor.Title;
Editor.Shell.Navigate(Shell.SectionKey.Jobs);
}
private void Select(PresetCard? card)
{
if (card is null) return;
if (card.Choice.Sequence is { } preset) Editor.Session.ApplyPreset(preset);
else EditExport(e => e with { Preset = e.Preset.WithManual(card.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,
});
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);
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;
}
}