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.Mvvm; namespace Titano.App.Editor; /// A preset card of the Export tab (Export.html): what it renders and what it will cost on this machine. 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; /// Sequence presets apply full settings; export presets only choose the output. public bool IsSequencePreset => Choice.Sequence is not null; public string ToolTip => Choice.Reason is { } reason ? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason) : Loc.L("Tooltips.Editor.Export.Preset", Name); /// "MP4 · HEVC Main10 · 3840×2160 · 24 fps". public string? Format { get => _format; private set => Set(ref _format, value); } /// "120 Mb/s · 0.07 bpp · NVENC". public string? Encoding { get => _encoding; private set => Set(ref _encoding, value); } /// "2.2 GB · about 5 min". public string? Estimate { get => _estimate; private set => Set(ref _estimate, value); } public bool IsSelected { get => _isSelected; set => Set(ref _isSelected, value); } /// Ticked for "Batch…" (export presets only). public bool IsInBatch { get => owner.IsInBatch(Choice.ExportPresetId); set => owner.SetInBatch(Choice.ExportPresetId, value); } public bool CanBatch => !IsSequencePreset; public ICommand SelectCommand => owner.SelectCommand; public void Update(ExportPlan? plan) { if (plan is null) { Format = Encoding = Estimate = null; return; } var settings = plan.Setup.Encoder.Settings; Format = EditorText.Format(plan.Export, settings.Width, settings.Height); Encoding = EditorText.Encoding(plan.Export, settings.BitRate, plan.Setup.Encoder.Capability?.Name); Estimate = plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable"); } public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch)); } /// 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('\\', '/')); } /// /// 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). /// 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), ]; private readonly LatestRunner _estimates = new(TimeSpan.FromMilliseconds(250)); private IReadOnlyList _cards = []; private IReadOnlyList _codecChoices = []; private IReadOnlyList _encoders = []; private IReadOnlyList _saveChoices = []; private IReadOnlyList _depths = []; private IReadOnlyList _notices = []; private bool _refreshing; public ExportTab(EditorViewModel editor) : base(editor, "Export", AdvisorSection.Export) { SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !Editor.IsBusy); RenderNowCommand = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: false), () => Editor.CanRender); AddToQueueCommand = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.Normal, batch: false), () => Editor.CanRender); BatchCommand = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: true), () => Editor.CanRender && Batch.Count > 0); HistoryCommand = new RelayCommand(() => Editor.Shell.Navigate(Shell.SectionKey.Jobs)); 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")); LoadCards(); Refresh(); } public IReadOnlyList Cards { get => _cards; private set => Set(ref _cards, value); } public ICommand SelectCommand { get; } public ICommand RenderNowCommand { get; } public ICommand AddToQueueCommand { get; } public ICommand BatchCommand { get; } public ICommand HistoryCommand { get; } public ICommand ResetFrameRateCommand { get; } /// "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); } } public EditableField Width { get; } public EditableField Height { get; } /// "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) EditOverrides(o => o with { FrameRate = 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)); /// Bit rate in Mb/s (video) or quality 1–100 (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"); } } 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 Encoders { get => _encoders; private set => Set(ref _encoders, value); } 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" (the word, not a colour, carries the state). public string? EncoderKind => Editor.Plan?.Setup.Encoder.Capability is { } c ? Loc.L(c.Hardware ? "Editor.Export.Hardware" : "Editor.Export.Software") : null; public bool IsHardware => Editor.Plan?.Setup.Encoder.Capability?.Hardware == true; 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; public EditableField NameTemplate { get; } public IReadOnlyList SaveChoices { get => _saveChoices; private set => Set(ref _saveChoices, value); } public SaveChoice? SelectedSave { get => SaveChoices.FirstOrDefault(c => !c.Browse && c.Folder == Export.Folder); 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 => Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty); public string? EstimatedSize => Editor.Plan is { Setup.Encoder.IsReady: true } plan ? Formatting.Bytes(plan.Estimate.Bytes) : null; public string? EstimatedTime => Editor.Plan is { Setup.Encoder.IsReady: true } plan ? Loc.L("Editor.Export.About", Formatting.Duration(plan.Estimate.Time)) + (plan.Setup.Encoder.Capability is { } c ? " · " + c.Name : string.Empty) : null; public string? ResultName => Editor.Plan?.FileName; /// What the encoder changed or cannot do (localised notices and render remarks). public IReadOnlyList Notices { get => _notices; private set => Set(ref _notices, value); } /// "Previous renders of this sequence: 2 · last 2026-09-21". 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 Batch => Export.Batch; /// Completes when the card estimates in flight are done. public Task EstimatesIdle => _estimates.Idle; private ExportSettings Export => Editor.Session.Project.Export; private ResolvedExport Resolved => Editor.Plan?.Export ?? ExportResolver.Resolve(Export); 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 = 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; } foreach (var card in Cards) { card.IsSelected = card.Choice.Sequence is null && string.Equals(card.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase); 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 ? [.. plan.Setup.Warnings.Select(w => Loc.L(w.Key, [.. w.Args])).Concat(plan.Export.Warnings.Select(k => Loc.L(k))).Distinct()] : []; OnAllPropertiesChanged(); } finally { _refreshing = false; } } public override void OnContentChanged() { LoadCards(); base.OnContentChanged(); } public override void Dispose() { _estimates.Dispose(); base.Dispose(); } /// The choices that depend on the resolved codec (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))]; } private void LoadCards() => Cards = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetCard(this, c))]; /// Estimates every card off the UI thread for the project as it is now (latest request wins). private async Task EstimateCardsAsync() { var project = Editor.Session.Project; var cards = Cards; var plans = new ExportPlan?[cards.Count]; 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); } return Task.CompletedTask; }); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { Core.Diagnostics.Log.Warning("editor", "Preset estimates failed", ex); return; } if (!ReferenceEquals(cards, Cards) || !ReferenceEquals(project, Editor.Session.Project)) return; for (var i = 0; i < cards.Count; i++) cards[i].Update(plans[i]); } 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 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); 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; } }