From e6d1317aab32d1f855a98bfeaaedf4c02e7354c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 17:00:26 +0000 Subject: [PATCH 1/9] feat(app): editor session, project history, local source, preview renderer and export planner Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Editor.resx | 3 + i18n/it/Editor.it.resx | 3 + src/Titano.App/Editor/EditorSession.cs | 172 ++++++++++ src/Titano.App/Editor/EditorSettings.cs | 131 ++++++++ src/Titano.App/Editor/ExportPlanner.cs | 110 ++++++ src/Titano.App/Editor/ISequenceSource.cs | 69 ++++ src/Titano.App/Editor/LatestRunner.cs | 50 +++ src/Titano.App/Editor/LocalSequenceSource.cs | 151 +++++++++ src/Titano.App/Editor/PreviewRenderer.cs | 318 ++++++++++++++++++ src/Titano.App/Editor/ProjectHistory.cs | 76 +++++ src/Titano.App/Editor/ProjectMerge.cs | 42 +++ src/Titano.App/Editor/ProjectSaver.cs | 89 +++++ .../Titano.App.Tests/Editor/EditorFixture.cs | 132 ++++++++ .../Editor/EditorSessionTests.cs | 206 ++++++++++++ .../Editor/ExportPlannerTests.cs | 93 +++++ .../Editor/PreviewRendererTests.cs | 121 +++++++ .../Editor/ProjectHistoryTests.cs | 90 +++++ .../Editor/ProjectStoreTests.cs | 157 +++++++++ .../Editor/SchedulingTests.cs | 133 ++++++++ 19 files changed, 2146 insertions(+) create mode 100644 src/Titano.App/Editor/EditorSession.cs create mode 100644 src/Titano.App/Editor/EditorSettings.cs create mode 100644 src/Titano.App/Editor/ExportPlanner.cs create mode 100644 src/Titano.App/Editor/ISequenceSource.cs create mode 100644 src/Titano.App/Editor/LatestRunner.cs create mode 100644 src/Titano.App/Editor/LocalSequenceSource.cs create mode 100644 src/Titano.App/Editor/PreviewRenderer.cs create mode 100644 src/Titano.App/Editor/ProjectHistory.cs create mode 100644 src/Titano.App/Editor/ProjectMerge.cs create mode 100644 src/Titano.App/Editor/ProjectSaver.cs create mode 100644 tests/Titano.App.Tests/Editor/EditorFixture.cs create mode 100644 tests/Titano.App.Tests/Editor/EditorSessionTests.cs create mode 100644 tests/Titano.App.Tests/Editor/ExportPlannerTests.cs create mode 100644 tests/Titano.App.Tests/Editor/PreviewRendererTests.cs create mode 100644 tests/Titano.App.Tests/Editor/ProjectHistoryTests.cs create mode 100644 tests/Titano.App.Tests/Editor/ProjectStoreTests.cs create mode 100644 tests/Titano.App.Tests/Editor/SchedulingTests.cs diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index 2de00b56..c212191c 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -5,4 +5,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Pick a sequence in the Library + This sequence is no longer in the archive.long + Jobs cannot run until the archive index is open.long + The settings of this sequence cannot be read.long diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index a0b523f2..f8da3819 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -5,4 +5,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Scegli una sequenza in Libreria + Questa sequenza non è più nell’archivio. + I lavori non possono partire finché l’indice dell’archivio non è aperto. + Le impostazioni di questa sequenza non sono leggibili. diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs new file mode 100644 index 00000000..4fc40fef --- /dev/null +++ b/src/Titano.App/Editor/EditorSession.cs @@ -0,0 +1,172 @@ +using Titano.Core.Advice; +using Titano.Core.Export; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Data.Archiving.Jobs; +using Titano.Data.Processing; + +namespace Titano.App.Editor; + +/// +/// One sequence open in the editor (BRIEF §12.3): its content, the advisor's view of it (§10.3), the project with undo +/// and redo, and the actions of every section — edit, Optimise (§10.4), Reset, exclusions and hero, analysis and render +/// jobs. Every change is saved shortly after it is made (); a change stored meanwhile by +/// someone else (an analysis job, another client) is merged in. Call from one thread (the UI thread). +/// +public sealed class EditorSession : IAsyncDisposable +{ + public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400); + + /// Sections "Optimise all" walks through, in panel order. + public static IReadOnlyList OptimisedSections { get; } = + [AdvisorSection.Frames, AdvisorSection.Timing, AdvisorSection.Exposure, AdvisorSection.Motion, AdvisorSection.Camera, AdvisorSection.Export]; + + private readonly IReadOnlyList _codecs; + private readonly ProjectSaver _saver; + private ProjectSettings _basis; + + public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList codecs, TimeSpan? saveDelay = null) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(content); + Source = source; + _codecs = codecs ?? []; + _basis = content.Project; + History = new ProjectHistory(content.Project); + History.Changed += OnProjectChanged; + _saver = new ProjectSaver(SaveAsync, saveDelay ?? DefaultSaveDelay); + _saver.Failed += ex => SaveFailed?.Invoke(ex); + (Content, Context, Advice, Presets) = Analyse(content, _codecs); + } + + /// The project changed (edit, undo, redo, Optimise, a merge). + public event Action? ProjectChanged; + + /// The sequence was read again (after an analysis): frames, reports, advice and presets. + public event Action? ContentChanged; + + /// Saving the project failed; the next change tries again. + public event Action? SaveFailed; + + public ISequenceSource Source { get; } + + public SequenceContent Content { get; private set; } + + public SequenceContext Context { get; private set; } + + /// The advisor's recommendations and findings for the current analyses. + public AdvisorResult Advice { get; private set; } + + /// Sequence presets that fit the content, best first (BRIEF §10.3). + public IReadOnlyList Presets { get; private set; } + + public ProjectHistory History { get; } + + public ProjectSettings Project => History.Current; + + /// Applies as an undoable step; false when it changes nothing. + /// Consecutive edits with the same key are one undo step (a slider drag). + public bool Edit(Func change, string? mergeKey = null) + { + ArgumentNullException.ThrowIfNull(change); + return History.Apply(change(Project), mergeKey); + } + + public bool Undo() => History.Undo(); + + public bool Redo() => History.Redo(); + + /// "Optimise section": the advisor's heavier decisions for , one undo step; returns what changed. + public IReadOnlyList Optimise(AdvisorSection section) => Optimise([section]); + + /// "Optimise all": every section, one undo step. + public IReadOnlyList OptimiseAll() => Optimise(OptimisedSections); + + /// "Reset": the section's Auto settings back to Auto. + public bool ResetSection(AdvisorSection section) => Edit(p => EditorSettings.ResetSection(p, section)); + + /// Adds frames to, or removes them from, the project's exclusions. + public bool SetExcluded(IEnumerable frames, bool excluded) + { + var chosen = frames.Where(i => (uint)i < (uint)Content.Count).ToHashSet(); + return Edit(p => p with + { + ExcludedFrames = excluded ? [.. p.ExcludedFrames.Union(chosen).Order()] : [.. p.ExcludedFrames.Where(i => !chosen.Contains(i))], + }); + } + + /// Makes the hero frame (sequence thumbnail). + public bool SetHero(int frame) => (uint)frame < (uint)Content.Count && Edit(p => p with { HeroFrame = frame }); + + /// + /// A render of with the project as it is now (the job embeds it, so a render queued before + /// the save lands still renders what the user sees). + /// + public ArchiveJobRequest RenderRequest(ExportSettings export, bool useProxies = false) => + ProcessingJobs.Render(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }, useProxies); + + /// The export of the project with preset chosen (own values, no batch). + public ExportSettings ExportFor(string presetId) => + Project.Export with { Preset = Project.Export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] }; + + public ArchiveJobRequest AnalysisRequest() => ProcessingJobs.DeepAnalysis([Content.Sequence.Id], Content.Sequence.DisplayTitle); + + public Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken); + + /// Reads the sequence again (an analysis finished): new reports and advice, the stored project merged into the open one. + public async Task ReloadAsync(CancellationToken cancellationToken = default) + { + await _saver.FlushAsync(); + var content = await Source.LoadAsync(cancellationToken); + var merged = ProjectMerge.Merge(_basis, Project, content.Project); + _basis = content.Project; + (Content, Context, Advice, Presets) = Analyse(content, _codecs); + History.Replace(merged); + ContentChanged?.Invoke(); + } + + /// Stores pending changes now. + public Task FlushAsync() => _saver.FlushAsync(); + + public async ValueTask DisposeAsync() + { + History.Changed -= OnProjectChanged; + await _saver.FlushAsync(); + await Source.DisposeAsync(); + } + + private static (SequenceContent, SequenceContext, AdvisorResult, IReadOnlyList) Analyse(SequenceContent content, + IReadOnlyList codecs) + { + var context = SequenceContext.FromFrames(content.Frames, codecs); + return (content, context, Advisor.Recommend(content.Light, content.Deep, context), SequencePresets.Generate(content.Light, content.Deep, context)); + } + + private IReadOnlyList Optimise(IReadOnlyList sections) + { + var settings = Project; + var changes = new List(); + foreach (var section in sections) + { + var result = Advisor.Optimise(section, settings, Advice); + settings = result.Settings; + changes.AddRange(result.Changes); + } + History.Apply(settings); + return changes; + } + + private void OnProjectChanged() + { + _saver.Schedule(Project); + ProjectChanged?.Invoke(); + } + + private async Task SaveAsync(ProjectSettings project) + { + var stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None); + _basis = stored; + // Someone else's change was merged in: show it without an undo step (edits made since the save are kept). + if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored)); + } +} diff --git a/src/Titano.App/Editor/EditorSettings.cs b/src/Titano.App/Editor/EditorSettings.cs new file mode 100644 index 00000000..bfa047bb --- /dev/null +++ b/src/Titano.App/Editor/EditorSettings.cs @@ -0,0 +1,131 @@ +using Titano.Core.Advice; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Export; +using Titano.Core.Motion; +using Titano.Core.Project; + +namespace Titano.App.Editor; + +/// An advisor-decided setting of the editor, whatever its value type. +public interface IAutoSetting +{ + /// id. + string Id { get; } + + AdvisorSection Section { get; } + + bool IsAuto(ProjectSettings project); + + /// Drops the manual value so the advice applies. + ProjectSettings Reset(ProjectSettings project); +} + +/// +/// One member of the project (BRIEF §10.4) and the value the engine uses when the advisor has +/// none (, from the deep analysis when it measured one). +/// +public sealed class AutoSetting( + string id, + AdvisorSection section, + Func> get, + Func, ProjectSettings> set, + Func fallback) : IAutoSetting + where T : notnull +{ + public string Id { get; } = id; + + public AdvisorSection Section { get; } = section; + + public Auto Get(ProjectSettings project) => get(project); + + public bool IsAuto(ProjectSettings project) => get(project).IsAuto; + + /// The advisor's value, else what the engine uses without advice. + public T AutoValue(ProjectSettings project, DeepAnalysisReport? deep) => get(project) is { HasAdvice: true, AutoValue: { } advised } ? advised : fallback(project, deep); + + /// The value in force. + public T Effective(ProjectSettings project, DeepAnalysisReport? deep) => get(project).Resolve(fallback(project, deep)); + + /// Touching the control: the value becomes manual. + public ProjectSettings WithManual(ProjectSettings project, T value) => set(project, get(project).WithManual(value)); + + public ProjectSettings Reset(ProjectSettings project) => set(project, get(project).Reset()); +} + +/// The Auto settings of the editor's sections, in panel order. +public static class EditorSettings +{ + public static readonly AutoSetting TimingMode = new(AdvisorParameters.TimingMode, AdvisorSection.Timing, + p => p.Timing.Mode, (p, a) => p with { Timing = p.Timing with { Mode = a } }, (_, _) => Core.Project.TimingMode.Constant); + + /// Playback rate; without a value it equals the export frame rate (DECISIONS: export fps vs playback rate). + public static readonly AutoSetting FrameRate = new(AdvisorParameters.FrameRate, AdvisorSection.Timing, + p => p.Timing.FrameRate, (p, a) => p with { Timing = p.Timing with { FrameRate = a } }, + (p, _) => FrameRateText.Format(ExportResolver.Resolve(p.Export).FrameRate)); + + public static readonly AutoSetting Deflicker = new(AdvisorParameters.Deflicker, AdvisorSection.Exposure, + p => p.Exposure.Deflicker, (p, a) => p with { Exposure = p.Exposure with { Deflicker = a } }, (_, _) => false); + + public static readonly AutoSetting DeflickerWindow = new(AdvisorParameters.DeflickerWindow, AdvisorSection.Exposure, + p => p.Exposure.DeflickerWindow, (p, a) => p with { Exposure = p.Exposure with { DeflickerWindow = a } }, + (_, deep) => deep?.Flicker.RecommendedWindow ?? DeflickerOptions.Default.Window); + + public static readonly AutoSetting DeflickerStrength = new(AdvisorParameters.DeflickerStrength, AdvisorSection.Exposure, + p => p.Exposure.DeflickerStrength, (p, a) => p with { Exposure = p.Exposure with { DeflickerStrength = a } }, (_, _) => DeflickerOptions.Default.Strength); + + public static readonly AutoSetting Regions = new(AdvisorParameters.Regions, AdvisorSection.Exposure, + p => p.Exposure.Regions, (p, a) => p with { Exposure = p.Exposure with { Regions = a } }, (_, _) => RegionMode.Off); + + public static readonly AutoSetting HolyGrail = new(AdvisorParameters.HolyGrail, AdvisorSection.Exposure, + p => p.Exposure.HolyGrail, (p, a) => p with { Exposure = p.Exposure with { HolyGrail = a } }, (_, _) => false); + + public static readonly AutoSetting TransitionLength = new(AdvisorParameters.TransitionLength, AdvisorSection.Exposure, + p => p.Exposure.TransitionLength, (p, a) => p with { Exposure = p.Exposure with { TransitionLength = a } }, + (_, deep) => deep?.Exposure.TransitionLength ?? new HolyGrailOptions().SingleStepTransitionFrames); + + public static readonly AutoSetting WhiteBalance = new(AdvisorParameters.WhiteBalanceSmoothing, AdvisorSection.Exposure, + p => p.Exposure.WhiteBalanceSmoothing, (p, a) => p with { Exposure = p.Exposure with { WhiteBalanceSmoothing = a } }, (_, _) => false); + + public static readonly AutoSetting MotionBlur = new(AdvisorParameters.MotionBlur, AdvisorSection.Motion, + p => p.Motion.MotionBlur, (p, a) => p with { Motion = p.Motion with { MotionBlur = a } }, (_, _) => false); + + public static readonly AutoSetting ShutterAngle = new(AdvisorParameters.TargetShutterAngle, AdvisorSection.Motion, + p => p.Motion.TargetShutterAngle, (p, a) => p with { Motion = p.Motion with { TargetShutterAngle = a } }, (_, _) => 180.0); + + public static readonly AutoSetting FlowQuality = new(AdvisorParameters.FlowQuality, AdvisorSection.Motion, + p => p.Motion.FlowQuality, (p, a) => p with { Motion = p.Motion with { FlowQuality = a } }, (_, _) => FlowQualitySetting.Balanced); + + public static readonly AutoSetting Stabilize = new(AdvisorParameters.Stabilize, AdvisorSection.Motion, + p => p.Motion.Stabilize, (p, a) => p with { Motion = p.Motion with { Stabilize = a } }, (_, _) => false); + + public static readonly AutoSetting StabilizeSmoothing = new(AdvisorParameters.StabilizeSmoothing, AdvisorSection.Motion, + p => p.Motion.StabilizeSmoothing, (p, a) => p with { Motion = p.Motion with { StabilizeSmoothing = a } }, (_, _) => new StabilizerOptions().SmoothingSigma); + + public static readonly AutoSetting Aspect = new(AdvisorParameters.Aspect, AdvisorSection.Camera, + p => p.Camera.Aspect, (p, a) => p with { Camera = p.Camera with { Aspect = a } }, (_, _) => "source"); + + public static readonly AutoSetting ExportPreset = new(AdvisorParameters.ExportPreset, AdvisorSection.Export, + p => p.Export.Preset, (p, a) => p with { Export = p.Export with { Preset = a } }, (_, _) => ExportResolver.DefaultPresetId); + + public static IReadOnlyList All { get; } = + [ + TimingMode, FrameRate, Deflicker, DeflickerWindow, DeflickerStrength, Regions, HolyGrail, TransitionLength, WhiteBalance, + MotionBlur, ShutterAngle, FlowQuality, Stabilize, StabilizeSmoothing, Aspect, ExportPreset, + ]; + + /// "Reset": every Auto setting of back to Auto; stacking (no advice) back to off. + public static ProjectSettings ResetSection(ProjectSettings project, AdvisorSection section) + { + ArgumentNullException.ThrowIfNull(project); + foreach (var setting in All) + { + if (setting.Section == section) project = setting.Reset(project); + } + return section == AdvisorSection.Stack ? project with { Stack = new StackSettings() } : project; + } + + /// True when every Auto setting of is in Auto. + public static bool IsSectionAuto(ProjectSettings project, AdvisorSection section) => + All.Where(s => s.Section == section).All(s => s.IsAuto(project)); +} diff --git a/src/Titano.App/Editor/ExportPlanner.cs b/src/Titano.App/Editor/ExportPlanner.cs new file mode 100644 index 00000000..96630024 --- /dev/null +++ b/src/Titano.App/Editor/ExportPlanner.cs @@ -0,0 +1,110 @@ +using Titano.Core.Advice; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Localization; +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Core.Video; +using Titano.Data.Processing; + +namespace Titano.App.Editor; + +/// A choice of the Export tab: a built-in export preset, or a sequence preset (full settings plus an export preset). +/// The export preset the card renders. +/// The sequence preset it applies, null for a plain export preset. +/// The advisor's export choice for this sequence. +/// Why it fits (advisor reason), localised; null for plain presets. +public sealed record ExportChoice(string Id, string Name, string ExportPresetId, SequencePreset? Sequence, bool IsRecommended, string? Reason); + +/// What one export will produce: resolved values, encoder, plan, size and time estimate, file name. +/// Output name with extension (a folder name for image sequences). +/// The first problem of the name template, localised; null when it is valid. +public sealed record ExportPlan(ResolvedExport Export, RenderSetup Setup, ExportEstimate Estimate, string FileName, string? NameError) +{ + public string PresetName => ProcessingJobs.PresetName(Export); +} + +/// +/// The Export tab's numbers (BRIEF §11.4–11.5): the preset list (sequence presets first, then the built-in presets, the +/// advisor's pick marked), and for any export the encoder this machine would use with its notices, the plan, the size +/// and time estimates () and the output name (). Nothing decodes: +/// the plan needs only the frame metadata and the source size. +/// +public sealed class ExportPlanner(SequenceContent content, IReadOnlyList encoders, EncoderHost host, ThroughputModel? model = null) +{ + /// Sequence presets that fit the content, then every built-in export preset. + public static IReadOnlyList Choices(IReadOnlyList presets, AdvisorResult advice) + { + ArgumentNullException.ThrowIfNull(presets); + ArgumentNullException.ThrowIfNull(advice); + var recommended = advice.Find(AdvisorParameters.ExportPreset)?.Value as string; + var choices = new List(); + foreach (var preset in presets) + { + choices.Add(new ExportChoice("sequence:" + preset.Id, preset.DisplayName(), preset.ExportPresetId, preset, false, + preset.ReasonKey is { } key ? Advisor.Explain(key, preset.ReasonArgs) : null)); + } + var reason = advice.Find(AdvisorParameters.ExportPreset) is { IsMissingData: false } r ? Advisor.Explain(r) : null; + foreach (var preset in ExportPresets.BuiltIn) + { + var isRecommended = string.Equals(preset.Id, recommended, StringComparison.OrdinalIgnoreCase); + choices.Add(new ExportChoice(preset.Id, Loc.L(preset.NameKey), preset.Id, null, isRecommended, isRecommended ? reason : null)); + } + return choices; + } + + /// The project's own export. + public ExportPlan? Plan(ProjectSettings project) => Plan(project, project.Export); + + /// What would produce with ; null when the source size is unknown. + public ExportPlan? Plan(ProjectSettings project, ExportSettings export) + { + ArgumentNullException.ThrowIfNull(project); + ArgumentNullException.ThrowIfNull(export); + if (content.SourceWidth <= 0 || content.SourceHeight <= 0 || content.Count == 0) return null; + var resolved = ExportResolver.Resolve(export); + var input = new RenderInput + { + Source = new SizeOnly(content), + Frames = SourceFrameInfo.From(content.Frames, content.Light.AdjustedTimes.Length == content.Count ? content.Light.AdjustedTimes : null), + Project = project with { Export = export, ExcludedFrames = [.. project.ExcludedFrames.Union(content.NotRenderable()).Order()] }, + }; + var setup = RenderSetup.Create(input, new RenderTarget(resolved, ExportNaming.FallbackName), encoders, host); + var (name, error) = FileName(export.NameTemplate, resolved, setup); + return new ExportPlan(resolved, setup, setup.Estimate(model), name, error); + } + + /// The first problem of a name template, localised; null when it is valid. + public static string? NameError(IReadOnlyList errors) => + errors.Count == 0 ? null : Loc.L("Errors.Template." + errors[0].Code, errors[0].Token ?? string.Empty, errors[0].Position + 1); + + private (string Name, string? Error) FileName(string template, ResolvedExport export, RenderSetup setup) + { + var settings = setup.Encoder.Settings; + var expanded = ExportNaming.Expand(template, new ExportNameContext + { + Date = content.Sequence.FirstCapture ?? DateTime.Now, + Title = content.Sequence.DisplayTitle, + PresetName = ProcessingJobs.PresetName(export), + Width = settings.Width, + Height = settings.Height, + FrameRate = settings.FrameRate, + Codec = settings.Codec, + }); + var extension = VideoCodecInfo.DefaultContainer(settings.Codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(settings.Codec); + return (expanded.Name + extension, NameError(expanded.Errors)); + } + + /// The render setup reads sizes and counts only. + private sealed class SizeOnly(SequenceContent content) : IRenderFrameSource + { + public int FrameCount => content.Count; + + public int Width => content.SourceWidth; + + public int Height => content.SourceHeight; + + public ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) => + throw new NotSupportedException("Export planning never decodes."); + } +} diff --git a/src/Titano.App/Editor/ISequenceSource.cs b/src/Titano.App/Editor/ISequenceSource.cs new file mode 100644 index 00000000..1423c73f --- /dev/null +++ b/src/Titano.App/Editor/ISequenceSource.cs @@ -0,0 +1,69 @@ +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Data.Archiving.Jobs; + +namespace Titano.App.Editor; + +/// +/// Where the sequence open in the editor lives: the local archive () or a server the +/// client is connected to (a source that reads proxies and posts jobs to the API). The editor reads frames, saves the +/// project and queues jobs only through this interface. +/// +public interface ISequenceSource : IAsyncDisposable +{ + /// Everything the editor shows of the sequence; read off the UI thread. + /// The project cannot be read (corrupt, or written by a newer Titano). + Task LoadAsync(CancellationToken cancellationToken); + + /// + /// Frame in linear light, oriented, long edge at most ; null + /// when the frame cannot be read. The caller owns the buffer. + /// + ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken); + + /// + /// Stores , edited from (the version last loaded or saved). A + /// change made meanwhile by someone else is kept where this edit left the value alone (). + /// Returns the stored project. + /// + Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken); + + /// Queues an analysis or render job for the sequence; returns the job id. + Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken); +} + +/// A sequence as the editor opens it. +/// Frame rows in index order. +/// Light analysis of the frame metadata (BRIEF §10.1). +/// The saved deep analysis when it describes the current frames, else null. +/// Dominant oriented full-resolution width (0 when unknown). +/// Default output folder of renders; null when the sequence is not on this PC. +/// Finished renders, newest first. +public sealed record SequenceContent( + Sequence Sequence, + IReadOnlyList Frames, + ProjectSettings Project, + LightAnalysisReport Light, + DeepAnalysisReport? Deep, + int SourceWidth, + int SourceHeight, + string? ExportsFolder, + IReadOnlyList Renders) +{ + /// Flags of frames that never reach a render (as the render job skips them). + public const FrameFlags NotRendered = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Excluded | FrameFlags.Undecodable; + + public int Count => Frames.Count; + + /// Frames the render skips besides the project's exclusions. + public IEnumerable NotRenderable() + { + for (var i = 0; i < Frames.Count; i++) + { + if ((Frames[i].Flags & NotRendered) != 0) yield return i; + } + } +} diff --git a/src/Titano.App/Editor/LatestRunner.cs b/src/Titano.App/Editor/LatestRunner.cs new file mode 100644 index 00000000..32376b43 --- /dev/null +++ b/src/Titano.App/Editor/LatestRunner.cs @@ -0,0 +1,50 @@ +namespace Titano.App.Editor; + +/// +/// Runs only the latest of a stream of requests (preview frames, estimates): scheduling cancels the request pending or +/// running before it, waits the debounce delay, then runs the work on the thread pool. A superseded run ends quietly; +/// other failures surface from the task returns. +/// +public sealed class LatestRunner(TimeSpan delay) : IDisposable +{ + private CancellationTokenSource? _current; + + /// Completes when the latest scheduled run has finished or been superseded. + public Task Idle { get; private set; } = Task.CompletedTask; + + public TimeSpan Delay { get; } = delay; + + /// Skip the debounce delay (playback, the first frame). + public Task Schedule(Func work, bool immediate = false) + { + ArgumentNullException.ThrowIfNull(work); + var cts = new CancellationTokenSource(); + Interlocked.Exchange(ref _current, cts)?.Cancel(); + var run = RunAsync(work, immediate ? TimeSpan.Zero : Delay, cts); + Idle = run; + return run; + } + + /// Cancels the pending or running request. + public void Cancel() => Interlocked.Exchange(ref _current, null)?.Cancel(); + + public void Dispose() => Cancel(); + + private async Task RunAsync(Func work, TimeSpan wait, CancellationTokenSource cts) + { + var token = cts.Token; + try + { + if (wait > TimeSpan.Zero) await Task.Delay(wait, token).ConfigureAwait(false); + await Task.Run(() => work(token), token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + } + finally + { + // Only the run that is still current releases the source; a superseded one was cancelled by its successor. + if (Interlocked.CompareExchange(ref _current, null, cts) == cts) cts.Dispose(); + } + } +} diff --git a/src/Titano.App/Editor/LocalSequenceSource.cs b/src/Titano.App/Editor/LocalSequenceSource.cs new file mode 100644 index 00000000..ddbedea3 --- /dev/null +++ b/src/Titano.App/Editor/LocalSequenceSource.cs @@ -0,0 +1,151 @@ +using System.IO; +using System.Text.Json; +using Titano.Core.Advice; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Archiving; +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.IO; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Archiving.Jobs; +using Titano.Data.Jobs; +using Titano.Data.Repositories; + +namespace Titano.App.Editor; + +/// +/// A sequence of an archive on this PC: rows from the index, originals decoded by the client's decoder chain, the +/// project in .titano/project.json mirrored in the index's settings column, jobs on this PC's engine. Project +/// writes follow the archive engine's protocol: under the sequence's lease file (so the server and the job engine wait +/// for it), file first (atomically), then the index with its settings version as an optimistic check. +/// +public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, ImageDecoder decoder, JobEngine? engine, ArchiveServiceOptions? lease = null) + : ISequenceSource +{ + private const int PageSize = 1000; + private const int SaveAttempts = 3; + + private readonly ArchiveServiceOptions _lease = lease ?? new ArchiveServiceOptions(); + private string?[] _files = []; + private ArchivePaths? _paths; + private SequencePaths? _folder; + + public async Task LoadAsync(CancellationToken cancellationToken) + { + var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken) ?? throw Missing(); + var archive = await db.Archives.GetAsync(sequence.ArchiveId, cancellationToken) ?? throw Missing(); + var frames = new List(); + while (true) + { + var page = await db.Frames.ListBySequenceAsync(sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken); + frames.AddRange(page); + if (page.Count < PageSize) break; + } + var renders = await db.Renders.ListBySequenceAsync(sequenceId, cancellationToken); + return await Task.Run(() => + { + var paths = new ArchivePaths(archive.RootPath); + var folder = paths.Sequence(sequence.Folder); + var files = new string?[frames.Count]; + for (var i = 0; i < files.Length; i++) + { + if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath); + } + (_paths, _folder, _files) = (paths, folder, files); + var context = SequenceContext.FromFrames(frames); + return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), ReadReport(folder, frames.Count), + context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)]); + }, cancellationToken); + } + + public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null; + return await Task.Run(() => + { + try + { + return decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose), cancellationToken)?.Pixels; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("editor", $"Frame {file} could not be read", ex); + return null; + } + }, cancellationToken); + } + + public Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(project); + ArgumentNullException.ThrowIfNull(basis); + var (paths, folder) = (_paths, _folder); + if (paths is null || folder is null) throw new InvalidOperationException("LoadAsync first."); + return Task.Run(async () => + { + ArchiveVolume.EnsureWritable(paths); + using var held = await LeaseFile.AcquireAsync(paths.LocksDirectory, $"seq-{sequenceId:N}", _lease.Owner, _lease.LeaseWait, _lease.LeaseDuration, + cancellationToken); + for (var attempt = 1; ; attempt++) + { + var row = await db.Sequences.GetAsync(sequenceId, cancellationToken) ?? throw Missing(); + var stored = ReadProject(row, folder); + var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored); + var json = merged.ToJson(); + if (json == stored.ToJson()) return merged; + AtomicFile.WriteAllText(folder.ProjectPath, json); + var result = await db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = json }, row.SettingsVersion, cancellationToken); + // A conflict means the settings moved in the index meanwhile (server API): merge again on top of them. + if (result.Outcome != SequenceEditOutcome.Conflict || attempt == SaveAttempts) return merged; + } + }, cancellationToken); + } + + public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) + { + if (engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); + var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken); + return job.Id; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + + /// The settings in force: the index copy, else project.json, else defaults. + /// The settings are not a project or come from a newer Titano. + internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder) + { + var json = sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null); + if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings(); + try + { + return ProjectSettings.FromJson(json); + } + catch (JsonException ex) + { + throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex); + } + } + + /// The saved deep report when it describes the current frames. + private static DeepAnalysisReport? ReadReport(SequencePaths folder, int frameCount) + { + if (!File.Exists(folder.AnalysisPath)) return null; + try + { + var report = DeepAnalysisReport.Load(folder.AnalysisPath); + return report.FrameCount == frameCount ? report : null; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException) + { + Log.Warning("editor", $"{folder.AnalysisPath} cannot be read", ex); + return null; + } + } + + private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing")); +} diff --git a/src/Titano.App/Editor/PreviewRenderer.cs b/src/Titano.App/Editor/PreviewRenderer.cs new file mode 100644 index 00000000..cd887cfb --- /dev/null +++ b/src/Titano.App/Editor/PreviewRenderer.cs @@ -0,0 +1,318 @@ +using Titano.Core.Analysis; +using Titano.Core.Export; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Geometry; +using Titano.Core.Motion; +using Titano.Core.Project; +using Titano.Core.Render; + +namespace Titano.App.Editor; + +/// What the preview shows of the frame: the output picture, or the whole source frame with the crop marked. +public enum PreviewFraming +{ + /// Through the render geometry (stabilisation, virtual camera, crop): what the video shows. + Output, + + /// The whole frame, exposure-corrected; marks what the output keeps. + Source, +} + +/// Long edge of the preview picture in pixels. +/// Also measure the motion field to the next frame. +public sealed record PreviewRequest(int Index, ProjectSettings Project, int LongEdge, PreviewFraming Framing, bool Vectors = false); + +/// A motion sample in preview pixels: origin and displacement to the next frame. +public readonly record struct VectorSample(float X, float Y, float Dx, float Dy); + +/// One rendered preview: the corrected and the original picture over the same area, and the overlays. +public sealed class PreviewFrame(int index, ImageBuffer corrected, ImageBuffer original) : IDisposable +{ + public int Index { get; } = index; + + public ImageBuffer Corrected { get; } = corrected; + + public ImageBuffer Original { get; } = original; + + /// The output's part of the picture, normalised (the whole picture in ). + public RectD Crop { get; init; } = new(0, 0, 1, 1); + + /// Sky/land boundary in picture pixels; empty when the analysis found no horizon. + public IReadOnlyList<(double X, double Y)> Horizon { get; init; } = []; + + public IReadOnlyList Vectors { get; init; } = []; + + public void Dispose() + { + Corrected.Dispose(); + Original.Dispose(); + } +} + +/// +/// The corrected-frame preview through the render pipeline at preview size (BRIEF §12.3). Corrections come from +/// exactly as a render prepares them (the deep analysis' luminance reused, the rest +/// measured on small decodes), cached per exposure/stabilisation settings; each frame then goes through the render's +/// exposure stage, its single geometry warp and the highlight knee. The render pipeline has no single-frame entry +/// point, so the per-frame steps of RenderRun are followed here; stacking and motion blur need neighbouring +/// frames and are left to the render. +/// +public sealed class PreviewRenderer(SequenceContent content, ISequenceSource source) +{ + /// Long edge of the frames the preparation measures (the render uses 512; the preview trades precision for speed). + public const int AnalysisLongEdge = 128; + + private const int VectorLongEdge = 320; + private const int VectorSpacing = 24; + + private readonly CachedFrames _frames = new(content, source); + private readonly Lock _gate = new(); + private (string Key, RenderCorrections Corrections)? _latest; + + /// Corrections for when already prepared, else null. + public RenderCorrections? Cached(ProjectSettings project) + { + var key = Key(project); + lock (_gate) return _latest is { } latest && latest.Key == key ? latest.Corrections : null; + } + + /// The most recently prepared corrections, whatever settings they were made for. + public RenderCorrections? Latest + { + get + { + lock (_gate) return _latest?.Corrections; + } + } + + /// + /// Prepares the corrections for (or returns them when prepared already). Requests come + /// one after the other (the editor cancels the previous one), so nothing is shared between calls but the cache. + /// + public async Task PrepareAsync(ProjectSettings project, CancellationToken cancellationToken) + { + if (Cached(project) is { } cached) return cached; + var key = Key(project); + var corrections = await RenderPreparation.PrepareAsync(Input(project), new RenderOptions { AnalysisLongEdge = AnalysisLongEdge }, null, cancellationToken) + .ConfigureAwait(false); + lock (_gate) _latest = (key, corrections); + return corrections; + } + + /// Renders one preview with (identity when null); null when the frame cannot be read. + public async Task RenderAsync(PreviewRequest request, RenderCorrections? corrections, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var setup = Geometry(request, corrections); + if (setup is null) return null; + var (geometry, edge) = setup.Value; + var frame = await PictureAsync(request.Index, request, corrections, geometry, edge, cancellationToken).ConfigureAwait(false); + if (frame is null) return null; + var (corrected, original, plan) = frame.Value; + try + { + var vectors = request.Vectors && request.Index + 1 < content.Count + ? await VectorsAsync(request, corrections, geometry, edge, corrected, cancellationToken).ConfigureAwait(false) + : []; + return new PreviewFrame(request.Index, corrected, original) + { + Crop = request.Framing == PreviewFraming.Source ? CropOf(plan, corrected.Width, corrected.Height) : new RectD(0, 0, 1, 1), + Horizon = request.Framing == PreviewFraming.Source ? HorizonOf(corrected.Width, corrected.Height) : [], + Vectors = vectors, + }; + } + catch + { + corrected.Dispose(); + original.Dispose(); + throw; + } + } + + /// Cache key: the settings reads. + internal static string Key(ProjectSettings project) => new ProjectSettings + { + Exposure = project.Exposure, + Motion = new MotionSettings { Stabilize = project.Motion.Stabilize, StabilizeSmoothing = project.Motion.StabilizeSmoothing }, + ExcludedFrames = project.ExcludedFrames, + }.ToJson(); + + private RenderInput Input(ProjectSettings project) => new() + { + Source = _frames, + Frames = SourceFrameInfo.From(content.Frames, content.Light.AdjustedTimes.Length == content.Count ? content.Light.AdjustedTimes : null), + Project = project with { ExcludedFrames = [.. project.ExcludedFrames.Union(content.NotRenderable()).Order()] }, + Analysis = content.Deep is { } deep && deep.FrameCount == content.Count + ? new PrecomputedAnalysis { LogLuminance = [.. deep.Frames.LogLuminance.Select(v => v ?? double.NaN)] } + : null, + }; + + private (RenderGeometry Geometry, int DecodeEdge)? Geometry(PreviewRequest request, RenderCorrections? corrections) + { + if ((uint)request.Index >= (uint)content.Count || content.SourceWidth <= 0 || content.SourceHeight <= 0) return null; + var export = ExportResolver.Resolve(request.Project.Export); + var full = RenderGeometry.Create(request.Project.Camera, export, content.SourceWidth, content.SourceHeight, corrections?.StabilizationZoom ?? 1, + request.LongEdge); + var (width, height) = Resampler.FitWithin(full.OutputWidth, full.OutputHeight, request.LongEdge); + var geometry = full.WithOutputSize(int.Max(1, width), int.Max(1, height)); + var edge = request.Framing == PreviewFraming.Source ? request.LongEdge : geometry.WorkingLongEdge; + return (geometry, int.Max(16, edge)); + } + + /// Decodes, corrects and frames one source frame: (corrected, original, output→picture plan). + private async Task<(ImageBuffer, ImageBuffer, GeometryPlan?)?> PictureAsync(int index, PreviewRequest request, RenderCorrections? corrections, + RenderGeometry geometry, int edge, CancellationToken cancellationToken) + { + var decoded = await source.DecodeAsync(index, edge, DecodePurpose.Proxy, cancellationToken).ConfigureAwait(false); + if (decoded is null) return null; + var raw = Rgb(decoded); + ImageBuffer? corrected = null; + try + { + corrected = raw.Clone(); + if (corrections is not null && corrections.FrameCount == content.Count) ApplyExposure(corrected, index, corrections); + var settings = geometry.For(raw.Width, raw.Height, index, corrections?.StabilizationAt(index, raw.Width, raw.Height) ?? Affine2D.Identity); + var plan = GeometryStage.Plan(raw.Width, raw.Height, settings); + if (request.Framing == PreviewFraming.Output) + { + var framed = GeometryStage.Apply(corrected, settings, cancellationToken); + corrected.Dispose(); + corrected = framed; + framed = GeometryStage.Apply(raw, settings, cancellationToken); + raw.Dispose(); + raw = framed; + } + if (request.Project.Exposure.HighlightKnee is > 0 and < 1 and var knee) ExposureProcessor.Apply(corrected, 0, null, knee); + return (corrected, raw, request.Framing == PreviewFraming.Output ? null : plan); + } + catch + { + corrected?.Dispose(); + raw.Dispose(); + throw; + } + } + + /// The render's exposure stage: region curves through the resampled sky mask, else the global correction, with white-balance gains. + private static void ApplyExposure(ImageBuffer frame, int index, RenderCorrections corrections) + { + var gains = corrections.WhiteBalance?[index]; + if (corrections is { Regions: { } mask, SkyEv: { } sky, LandEv: { } land }) + { + ExposureProcessor.ApplyRegion(frame, mask.Resample(frame.Width, frame.Height).Sky, sky[index], land[index], gains); + return; + } + var ev = corrections.ExposureEv[index]; + if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains); + } + + /// Optical flow from this frame to the next, both prepared the same way, sampled on a grid in picture pixels. + private async Task> VectorsAsync(PreviewRequest request, RenderCorrections? corrections, RenderGeometry geometry, int edge, + ImageBuffer current, CancellationToken cancellationToken) + { + var next = await PictureAsync(request.Index + 1, request, corrections, geometry, edge, cancellationToken).ConfigureAwait(false); + if (next is null) return []; + var (nextCorrected, nextOriginal, _) = next.Value; + nextOriginal.Dispose(); + using (nextCorrected) + { + var scale = double.Min(1, (double)VectorLongEdge / int.Max(current.Width, current.Height)); + var (w, h) = ((int)double.Max(8, current.Width * scale), (int)double.Max(8, current.Height * scale)); + using var a = Resampler.Resize(current, w, h); + using var b = Resampler.Resize(nextCorrected, w, h); + using var engine = new OpticalFlowEngine(FlowQuality.Draft); + using var field = engine.Compute(a, b, cancellationToken); + var samples = new List(); + for (var y = VectorSpacing / 2.0; y < current.Height; y += VectorSpacing) + { + for (var x = VectorSpacing / 2.0; x < current.Width; x += VectorSpacing) + { + var (u, v) = field.Sample(x * w / current.Width, y * h / current.Height); + samples.Add(new VectorSample((float)x, (float)y, (float)(u * current.Width / w), (float)(v * current.Height / h))); + } + } + return samples; + } + } + + /// The output's footprint on the source picture (bounding box of the warped output corners), normalised. + private static RectD CropOf(GeometryPlan? plan, int width, int height) + { + if (plan is not { } p) return new RectD(0, 0, 1, 1); + double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue; + foreach (var (u, v) in new[] { (-0.5, -0.5), (p.OutputWidth - 0.5, -0.5), (-0.5, p.OutputHeight - 0.5), (p.OutputWidth - 0.5, p.OutputHeight - 0.5) }) + { + var (x, y) = p.OutputToSource.Apply(u, v); + (left, top, right, bottom) = (double.Min(left, x + 0.5), double.Min(top, y + 0.5), double.Max(right, x + 0.5), double.Max(bottom, y + 0.5)); + } + left = double.Clamp(left / width, 0, 1); + top = double.Clamp(top / height, 0, 1); + return new RectD(left, top, double.Clamp(right / width, 0, 1) - left, double.Clamp(bottom / height, 0, 1) - top); + } + + /// The analysed horizon (normalised rows at evenly spaced columns) in pixels of the whole-frame picture. + private IReadOnlyList<(double X, double Y)> HorizonOf(int width, int height) + { + if (content.Deep?.Regions is not { Horizon: { Length: > 1 } rows }) return []; + var points = new (double X, double Y)[rows.Length]; + for (var k = 0; k < rows.Length; k++) points[k] = ((double)k / (rows.Length - 1) * width, rows[k] * height); + return points; + } + + /// Gray sources become RGB and alpha is dropped, as in the render. + private static ImageBuffer Rgb(ImageBuffer frame) + { + if (frame.Channels == 3) return frame; + using (frame) + { + if (frame.Channels == 1) return PixelConvert.GrayToRgb(frame); + var rgb = new ImageBuffer(frame.Width, frame.Height, 3, clear: false); + frame.Data[..(3 * frame.PlaneLength)].CopyTo(rgb.Data); + return rgb; + } + } + + /// + /// The sequence as the preparation reads it, with small decodes kept (within a memory budget) so changing a setting + /// does not decode the sequence again. + /// + private sealed class CachedFrames(SequenceContent content, ISequenceSource source) : IRenderFrameSource + { + private const long Budget = 64L << 20; + private readonly Lock _gate = new(); + private readonly Dictionary<(int Index, int Edge), ImageBuffer> _cache = []; + private readonly Queue<(int Index, int Edge)> _order = new(); + private long _bytes; + + public int FrameCount => content.Count; + + public int Width => content.SourceWidth; + + public int Height => content.SourceHeight; + + public async ValueTask GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + lock (_gate) + { + if (_cache.TryGetValue((index, maxLongEdge), out var hit)) return hit.Clone(); + } + var frame = await source.DecodeAsync(index, maxLongEdge, purpose, cancellationToken).ConfigureAwait(false) + ?? throw new RenderException("Export.Render.FrameUnreadable", $"Frame {index + 1} could not be decoded.", + [(index + 1).ToString(System.Globalization.CultureInfo.InvariantCulture), content.Frames[index].FileName]); + lock (_gate) + { + if (frame.ByteSize <= Budget && _cache.TryAdd((index, maxLongEdge), frame.Clone())) + { + _order.Enqueue((index, maxLongEdge)); + _bytes += frame.ByteSize; + while (_bytes > Budget && _order.TryDequeue(out var oldest) && _cache.Remove(oldest, out var dropped)) + { + _bytes -= dropped.ByteSize; + dropped.Dispose(); + } + } + } + return frame; + } + } +} diff --git a/src/Titano.App/Editor/ProjectHistory.cs b/src/Titano.App/Editor/ProjectHistory.cs new file mode 100644 index 00000000..55c75df5 --- /dev/null +++ b/src/Titano.App/Editor/ProjectHistory.cs @@ -0,0 +1,76 @@ +using Titano.Core.Project; + +namespace Titano.App.Editor; + +/// +/// Undo and redo of the editor's project (Ctrl+Z / Ctrl+Y). Projects are immutable, so each step is a snapshot. +/// Consecutive edits with the same mergeKey (one slider drag, typing in one field) form a single step; any +/// other edit, undo or redo ends the run. The oldest steps are dropped beyond . +/// +public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200) +{ + private readonly LinkedList _undo = new(); + private readonly Stack _redo = new(); + private string? _runKey; + + /// The project, after any edit, undo, redo or . + public event Action? Changed; + + public ProjectSettings Current { get; private set; } = initial ?? throw new ArgumentNullException(nameof(initial)); + + public int Capacity { get; } = capacity > 0 ? capacity : throw new ArgumentOutOfRangeException(nameof(capacity)); + + public bool CanUndo => _undo.Count > 0; + + public bool CanRedo => _redo.Count > 0; + + /// Makes current as an undoable step; false (and nothing recorded) when it stores the same values. + public bool Apply(ProjectSettings next, string? mergeKey = null) + { + ArgumentNullException.ThrowIfNull(next); + if (ProjectMerge.SameValues(next, Current)) return false; + if (mergeKey is null || mergeKey != _runKey || _undo.Count == 0) + { + _undo.AddLast(Current); + if (_undo.Count > Capacity) _undo.RemoveFirst(); + } + _runKey = mergeKey; + _redo.Clear(); + Current = next; + Changed?.Invoke(); + return true; + } + + public bool Undo() + { + if (_undo.Last is not { } previous) return false; + _undo.RemoveLast(); + _redo.Push(Current); + return Move(previous.Value); + } + + public bool Redo() + { + if (!_redo.TryPop(out var next)) return false; + _undo.AddLast(Current); + return Move(next); + } + + /// Adopts a project changed outside the editor (analysis advice, a merge on save) without an undo step. + public void Replace(ProjectSettings current) + { + ArgumentNullException.ThrowIfNull(current); + if (ProjectMerge.SameValues(current, Current)) return; + _runKey = null; + Current = current; + Changed?.Invoke(); + } + + private bool Move(ProjectSettings target) + { + _runKey = null; + Current = target; + Changed?.Invoke(); + return true; + } +} diff --git a/src/Titano.App/Editor/ProjectMerge.cs b/src/Titano.App/Editor/ProjectMerge.cs new file mode 100644 index 00000000..720726a9 --- /dev/null +++ b/src/Titano.App/Editor/ProjectMerge.cs @@ -0,0 +1,42 @@ +using System.Text.Json.Nodes; +using Titano.Core.Project; + +namespace Titano.App.Editor; + +/// +/// Three-way merge of projects: the editor's edit (ours) and a change stored meanwhile by someone else +/// (theirs: an analysis filling Auto values, another client through the server), both made from basis. +/// Values are compared member by member down the JSON tree; a member only one side changed takes that side's value, a +/// member both changed takes the editor's (the user is looking at it). +/// +public static class ProjectMerge +{ + public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) + { + ArgumentNullException.ThrowIfNull(basis); + ArgumentNullException.ThrowIfNull(ours); + ArgumentNullException.ThrowIfNull(theirs); + var b = JsonNode.Parse(basis.ToJson()); + var o = JsonNode.Parse(ours.ToJson()); + var t = JsonNode.Parse(theirs.ToJson()); + return ProjectSettings.FromJson(Merge(b, o, t)?.ToJsonString() ?? "{}"); + } + + /// True when both projects store the same values. + public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson(); + + private static JsonNode? Merge(JsonNode? basis, JsonNode? ours, JsonNode? theirs) + { + if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone(); + if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone(); + if (ours is not JsonObject mine || theirs is not JsonObject other) return ours?.DeepClone(); + var common = basis as JsonObject; + var merged = new JsonObject(); + foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key))) + { + var value = Merge(common?[name], mine[name], other[name]); + if (value is not null || mine.ContainsKey(name)) merged[name] = value; + } + return merged; + } +} diff --git a/src/Titano.App/Editor/ProjectSaver.cs b/src/Titano.App/Editor/ProjectSaver.cs new file mode 100644 index 00000000..c8b254a6 --- /dev/null +++ b/src/Titano.App/Editor/ProjectSaver.cs @@ -0,0 +1,89 @@ +using Titano.Core.Project; + +namespace Titano.App.Editor; + +/// +/// Writes the editor's project shortly after the last change: one write at a time, always the newest project, never +/// cancelled half way (a write is a file plus an index row). skips the wait and returns once +/// everything scheduled is stored. A failed write is reported and the next change tries again. +/// +public sealed class ProjectSaver(Func save, TimeSpan delay) +{ + private readonly Lock _gate = new(); + private ProjectSettings? _pending; + private bool _running; + private Task _loop = Task.CompletedTask; + private CancellationTokenSource _wait = new(); + + /// A write failed (raised on the context that scheduled the write). + public event Action? Failed; + + public bool HasPendingChanges + { + get + { + lock (_gate) return _running; + } + } + + public void Schedule(ProjectSettings project) + { + ArgumentNullException.ThrowIfNull(project); + TaskCompletionSource start; + lock (_gate) + { + _pending = project; + if (_running) return; + _running = true; + if (!_wait.TryReset()) _wait = new CancellationTokenSource(); + start = new TaskCompletionSource(); + _loop = LoopAsync(start.Task, _wait.Token); + } + // The loop starts outside the lock: with nothing to wait for it would otherwise save while holding it. + start.SetResult(); + } + + /// Stores what is pending now, without the delay. + public Task FlushAsync() + { + lock (_gate) + { + _wait.Cancel(); + return _loop; + } + } + + private async Task LoopAsync(Task started, CancellationToken wait) + { + await started; + try + { + await Task.Delay(delay, wait); + } + catch (OperationCanceledException) + { + } + while (true) + { + ProjectSettings next; + lock (_gate) + { + if (_pending is null) + { + _running = false; + return; + } + next = _pending; + _pending = null; + } + try + { + await save(next); + } + catch (Exception ex) + { + Failed?.Invoke(ex); + } + } + } +} diff --git a/tests/Titano.App.Tests/Editor/EditorFixture.cs b/tests/Titano.App.Tests/Editor/EditorFixture.cs new file mode 100644 index 00000000..1e06fdd8 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/EditorFixture.cs @@ -0,0 +1,132 @@ +using System.Globalization; +using Titano.App.Editor; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Core.Render.Diagnostics; +using Titano.Data.Archiving.Jobs; + +namespace Titano.App.Tests.Editor; + +/// A synthetic sunset with flicker and two exposure steps, as the editor tests open it. +internal static class EditorFixture +{ + private static readonly Lazy Shared = new(() => Sequence()); + + static EditorFixture() => Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + + public static SyntheticSequence Sunset => Shared.Value; + + public static SyntheticSequence Sequence(int frames = 72) => SyntheticSequence.Create(new SyntheticSequenceOptions + { + Width = 96, + Height = 64, + FrameCount = frames, + StartEv = 0, + EndEv = -2, + FlickerEv = 0.25, + ExposureSteps = [new SyntheticExposureStep(24, -1), new SyntheticExposureStep(48, -1)], + StartKelvin = 5200, + EndKelvin = 3400, + }); + + /// The sequence as returns it, with a deep analysis when asked. + public static SequenceContent Content(SyntheticSequence sequence, ProjectSettings? project = null, bool deep = true) + { + var id = Guid.CreateVersion7(); + var frames = sequence.Frames.Select(f => f with { SequenceId = id }).ToList(); + var row = new Sequence + { + Id = id, + ArchiveId = Guid.CreateVersion7(), + Title = "Harbour sunset", + Folder = "2026/2026-09-28 Synthetic", + CameraMake = sequence.Options.CameraMake, + CameraModel = sequence.Options.CameraModel, + FirstCapture = frames[0].CapturedAt, + LastCapture = frames[^1].CapturedAt, + FrameCount = frames.Count, + MedianInterval = sequence.Options.IntervalSeconds, + }; + var report = deep ? DeepAnalyzer.AnalyzeAsync(new Frames(sequence)).GetAwaiter().GetResult() : null; + return new SequenceContent(row, frames, project ?? new ProjectSettings(), LightAnalyzer.Analyze(frames), report, sequence.Options.Width, + sequence.Options.Height, null, []); + } + + /// Synthetic frames as the deep analysis reads them. + private sealed class Frames(SyntheticSequence sequence) : IFrameSource + { + public int Count => sequence.Count; + + public LightFrame Metadata(int index) => LightFrame.From(sequence.Metadata[index], index); + + public ValueTask LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) => + ValueTask.FromResult(sequence.Render(index)); + } +} + +/// +/// An in-memory : synthetic pixels, a stored project with the same merge rule as the +/// archive, recorded jobs. simulates someone else changing the stored project before a save. +/// +internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceContent content) : ISequenceSource +{ + private readonly SyntheticFrameSource _pixels = new(sequence); + + public ProjectSettings Stored { get; set; } = content.Project; + + public SequenceContent Content { get; set; } = content; + + public List Submitted { get; } = []; + + public int Saves { get; private set; } + + public int Decodes { get; private set; } + + /// Applied to the stored project before the next save reads it. + public Func? ExternalEdit { get; set; } + + /// Thrown by the next save. + public Exception? FailNextSave { get; set; } + + /// Awaited by every decode (tests of cancellation). + public Task DecodeGate { get; set; } = Task.CompletedTask; + + public Task LoadAsync(CancellationToken cancellationToken) => Task.FromResult(Content with { Project = Stored }); + + public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) + { + await DecodeGate.WaitAsync(cancellationToken); + Decodes++; + return await _pixels.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken); + } + + public Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken) + { + if (FailNextSave is { } failure) + { + FailNextSave = null; + return Task.FromException(failure); + } + if (ExternalEdit is { } edit) + { + Stored = edit(Stored); + ExternalEdit = null; + } + Stored = ProjectMerge.SameValues(Stored, basis) ? project : ProjectMerge.Merge(basis, project, Stored); + Saves++; + return Task.FromResult(Stored); + } + + public Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) + { + Submitted.Add(request); + return Task.FromResult(Guid.CreateVersion7()); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs new file mode 100644 index 00000000..055251d4 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs @@ -0,0 +1,206 @@ +using System.IO; +using System.Text.Json; +using Titano.App.Editor; +using Titano.Core.Advice; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Protocol; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +public sealed class EditorSessionTests +{ + private static (EditorSession Session, FakeSequenceSource Source) Open(ProjectSettings? project = null, bool deep = true) + { + var content = EditorFixture.Content(EditorFixture.Sunset, project, deep); + var source = new FakeSequenceSource(EditorFixture.Sunset, content); + return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source); + } + + [Test] + public async Task EditsAreSavedAndUndoable() + { + var (session, source) = Open(); + await using (session) + { + Assert.True(session.Edit(p => EditorSettings.Deflicker.WithManual(p, true))); + await session.FlushAsync(); + Assert.True(source.Stored.Exposure.Deflicker is { IsAuto: false, Manual: true }); + + Assert.True(session.Undo()); + await session.FlushAsync(); + Assert.True(source.Stored.Exposure.Deflicker.IsAuto, "undo is saved too"); + Assert.True(session.Redo()); + await session.FlushAsync(); + Assert.False(source.Stored.Exposure.Deflicker.IsAuto); + } + } + + [Test] + public async Task RapidEditsSaveOnce() + { + var (session, source) = Open(); + await using (session) + { + for (var i = 1; i <= 20; i++) session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = i / 20.0 } }, "offset"); + await session.FlushAsync(); + Assert.Equal(1, source.Saves); + Assert.Equal(1.0, source.Stored.Exposure.ExposureOffsetEv); + } + } + + [Test] + public async Task AChangeStoredMeanwhileIsMergedIntoTheEditor() + { + var (session, source) = Open(); + await using (session) + { + source.ExternalEdit = p => p with { Camera = p.Camera with { OffsetY = -0.2 } }; + session.Edit(p => p with { HeroFrame = 5 }); + await session.FlushAsync(); + Assert.Equal(5, session.Project.HeroFrame); + Assert.Equal(-0.2, session.Project.Camera.OffsetY, "their change shows up in the editor"); + Assert.True(session.Undo()); + Assert.Null(session.Project.HeroFrame); + } + } + + [Test] + public async Task AFailedSaveIsReportedAndRetriedByTheNextChange() + { + var (session, source) = Open(); + await using (session) + { + Exception? reported = null; + session.SaveFailed += ex => reported = ex; + source.FailNextSave = new IOException("share offline"); + session.Edit(p => p with { HeroFrame = 1 }); + await session.FlushAsync(); + Assert.NotNull(reported); + session.Edit(p => p with { HeroFrame = 2 }); + await session.FlushAsync(); + Assert.Equal(2, source.Stored.HeroFrame); + } + } + + [Test] + public async Task OptimiseSectionTakesTheHeavierDecisionsAsOneStep() + { + // The user turned deflicker off by hand; the analysis measured flicker, so Optimise returns it to Auto (on). + var start = new ProjectSettings(); + start = start with { Exposure = start.Exposure with { Deflicker = start.Exposure.Deflicker.WithManual(false) } }; + var (session, _) = Open(start); + await using (session) + { + var advice = session.Advice.Find(AdvisorParameters.Deflicker); + Assert.NotNull(advice); + Assert.Equal(true, advice!.Value); + session.Edit(p => Advisor.Apply(p, session.Advice)); + Assert.False(EditorSettings.Deflicker.Effective(session.Project, null), "advice never overrides a manual value"); + + var changes = session.Optimise(AdvisorSection.Exposure); + Assert.True(EditorSettings.Deflicker.Effective(session.Project, null)); + Assert.True(session.Project.Exposure.Deflicker.IsAuto); + var change = Assert.Contains(changes, c => c.Parameter == AdvisorParameters.Deflicker); + Assert.Equal(false, change.Before); + Assert.Equal(true, change.After); + + Assert.True(session.Undo()); + Assert.False(session.Project.Exposure.Deflicker.IsAuto, "one undo restores the manual choice"); + } + } + + [Test] + public async Task WithoutAnalysisOptimiseChangesNothingItCannotMeasure() + { + var (session, _) = Open(deep: false); + await using (session) + { + Assert.True(session.Advice.Find(AdvisorParameters.Deflicker)!.IsMissingData); + var changes = session.Optimise(AdvisorSection.Exposure); + Assert.DoesNotContain(AdvisorParameters.Deflicker, changes.Select(c => c.Parameter)); + Assert.False(session.Project.Exposure.Deflicker.HasAdvice); + } + } + + [Test] + public async Task ResetReturnsTheSectionToAuto() + { + var (session, _) = Open(); + await using (session) + { + session.Edit(p => EditorSettings.Stabilize.WithManual(p, true)); + session.Edit(p => EditorSettings.ShutterAngle.WithManual(p, 90.0)); + session.Edit(p => EditorSettings.Deflicker.WithManual(p, true)); + Assert.False(EditorSettings.IsSectionAuto(session.Project, AdvisorSection.Motion)); + Assert.True(session.ResetSection(AdvisorSection.Motion)); + Assert.True(EditorSettings.IsSectionAuto(session.Project, AdvisorSection.Motion)); + Assert.False(session.Project.Exposure.Deflicker.IsAuto, "other sections keep their values"); + } + } + + [Test] + public async Task ExclusionsAndHeroAreFrameIndices() + { + var (session, _) = Open(); + await using (session) + { + Assert.True(session.SetExcluded([5, 3, 400], excluded: true)); + Assert.SequenceEqual([3, 5], session.Project.ExcludedFrames); + Assert.True(session.SetExcluded([3], excluded: false)); + Assert.SequenceEqual([5], session.Project.ExcludedFrames); + Assert.False(session.SetHero(999)); + Assert.True(session.SetHero(10)); + Assert.Equal(10, session.Project.HeroFrame); + } + } + + [Test] + public async Task RenderRequestsEmbedTheProjectAndTheExport() + { + var (session, source) = Open(); + await using (session) + { + session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.7 } }); + var export = session.ExportFor("4k-hevc"); + Assert.Empty(export.Batch); + var request = session.RenderRequest(export with { Batch = ["1080p-h264"] }); + Assert.Equal(JobKind.Render, request.Kind); + Assert.SequenceEqual([session.Content.Sequence.Id], request.Targets); + Assert.Equal(JobPriority.User, request.Priority); + var parameters = JsonSerializer.Deserialize(request.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!; + Assert.Equal("hevc", parameters.Codec); + Assert.Equal(3840, parameters.Width); + Assert.Contains("1080p-h264", parameters.PresetJson); + var embedded = ProjectSettings.FromJson(parameters.SettingsJson!); + Assert.Equal(0.7, embedded.Exposure.ExposureOffsetEv); + Assert.Equal("4k-hevc", embedded.Export.Preset.Manual); + + await session.SubmitAsync(request); + await session.SubmitAsync(session.AnalysisRequest()); + Assert.Equal(2, source.Submitted.Count); + Assert.Equal(JobKind.DeepAnalyse, source.Submitted[1].Kind); + } + } + + [Test] + public async Task ReloadBringsNewAnalysisAndKeepsUserValues() + { + var (session, source) = Open(deep: false); + await using (session) + { + Assert.Null(session.Content.Deep); + session.Edit(p => p with { HeroFrame = 2 }); + source.Content = EditorFixture.Content(EditorFixture.Sunset, deep: true) with { Sequence = session.Content.Sequence }; + source.Stored = Advisor.Apply(source.Stored, session.Advice); + var changed = 0; + session.ContentChanged += () => changed++; + await session.ReloadAsync(); + Assert.Equal(1, changed); + Assert.NotNull(session.Content.Deep); + Assert.False(session.Advice.Find(AdvisorParameters.Deflicker)!.IsMissingData, "advice from the new analysis"); + Assert.Equal(2, session.Project.HeroFrame); + } + } +} diff --git a/tests/Titano.App.Tests/Editor/ExportPlannerTests.cs b/tests/Titano.App.Tests/Editor/ExportPlannerTests.cs new file mode 100644 index 00000000..fa4fb3d4 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/ExportPlannerTests.cs @@ -0,0 +1,93 @@ +using Titano.App.Editor; +using Titano.Core.Advice; +using Titano.Core.Export; +using Titano.Core.Project; +using Titano.Core.Video; +using Titano.Core.Video.Managed; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +public sealed class ExportPlannerTests +{ + private static readonly SequenceContent Content = EditorFixture.Content(EditorFixture.Sunset); + + private static ExportPlanner Planner(EncoderHost host = EncoderHost.Client) => new(Content, [new ManagedEncoderProvider()], host); + + [Test] + public void TheListHasSequencePresetsFirstThenEveryBuiltInPreset() + { + var context = SequenceContext.FromFrames(Content.Frames); + var advice = Advisor.Recommend(Content.Light, Content.Deep, context); + var presets = SequencePresets.Generate(Content.Light, Content.Deep, context); + var choices = ExportPlanner.Choices(presets, advice); + + Assert.Equal(presets.Count + ExportPresets.BuiltIn.Count, choices.Count); + Assert.True(choices.Take(presets.Count).All(c => c.Sequence is not null)); + Assert.SequenceEqual(ExportPresets.BuiltIn.Select(p => p.Id), choices.Skip(presets.Count).Select(c => c.Id)); + var recommended = Assert.Contains(choices, c => c.IsRecommended); + Assert.Equal(advice.Find(AdvisorParameters.ExportPreset)!.Value, recommended.ExportPresetId); + Assert.NotNull(recommended.Reason); + Assert.True(choices.All(c => c.Name.Length > 0 && !c.Name.StartsWith("Export.", StringComparison.Ordinal)), "names are localised"); + } + + [Test] + public void AnImageSequenceIsEstimatedAndNamedAsAFolder() + { + var project = new ProjectSettings(); + project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("png-sequence"), NameTemplate = "{title} {width}x{height} {codec}" } }; + var plan = Planner().Plan(project); + Assert.NotNull(plan); + Assert.True(plan!.Setup.Encoder.IsReady); + Assert.Equal(96, plan.Setup.Encoder.Settings.Width); + Assert.Equal("Harbour sunset 96x64 PNG", plan.FileName, "no extension: a folder of frames"); + Assert.Null(plan.NameError); + var workload = plan.Setup.Workload(); + Assert.Equal(ExportEstimator.EstimateBytes(plan.Export with { Codec = VideoCodec.PngSequence }, workload), plan.Estimate.Bytes); + Assert.Greater(plan.Estimate.Bytes, 0); + Assert.Greater(plan.Estimate.Time.TotalSeconds, 0); + } + + [Test] + public void ExcludedFramesShortenTheEstimate() + { + var project = new ProjectSettings(); + project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("jpeg-sequence") } }; + var all = Planner().Plan(project)!; + var fewer = Planner().Plan(project with { ExcludedFrames = [.. Enumerable.Range(0, 36)] })!; + Assert.Equal(Content.Count, all.Setup.Plan.Frames.Count); + Assert.Less(fewer.Estimate.Bytes, all.Estimate.Bytes); + } + + [Test] + public void VideoWithoutAnEncoderExplainsWhy() + { + var plan = Planner().Plan(new ProjectSettings())!; + Assert.False(plan.Setup.Encoder.IsReady, "only managed encoders here; H.264 needs Media Foundation or a render node"); + Assert.Contains(plan.Setup.Encoder.Notices, n => n.Key == EncoderNotices.NoEncoder); + + var server = Planner(EncoderHost.Server).Plan(new ProjectSettings())!; + Assert.Equal(EncoderSelectionStatus.NeedsRenderNode, server.Setup.Encoder.Status); + } + + [Test] + public void ABrokenTemplateIsExplainedAndStillNamesTheFile() + { + var project = new ProjectSettings(); + project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("gif-preview"), NameTemplate = "{title} {nope}" } }; + var plan = Planner().Plan(project)!; + Assert.Equal("Unknown token “nope” at position 9.", plan.NameError); + Assert.Equal("Harbour sunset.gif", plan.FileName); + } + + [Test] + public void EditingAValueMakesThePresetCustom() + { + var project = new ProjectSettings(); + project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("png-sequence"), Overrides = new ExportOverrides { Width = 48 } } }; + var plan = Planner().Plan(project)!; + Assert.True(plan.Export.IsCustom); + Assert.Equal("Custom", plan.PresetName); + Assert.Equal(48, plan.Setup.Encoder.Settings.Width); + } +} diff --git a/tests/Titano.App.Tests/Editor/PreviewRendererTests.cs b/tests/Titano.App.Tests/Editor/PreviewRendererTests.cs new file mode 100644 index 00000000..cbf38189 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/PreviewRendererTests.cs @@ -0,0 +1,121 @@ +using Titano.App.Editor; +using Titano.Core.Imaging; +using Titano.Core.Project; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +/// The corrected-frame preview through the render pipeline at preview size. +public sealed class PreviewRendererTests +{ + private static (PreviewRenderer Renderer, FakeSequenceSource Source) Create() + { + var content = EditorFixture.Content(EditorFixture.Sunset); + var source = new FakeSequenceSource(EditorFixture.Sunset, content); + return (new PreviewRenderer(content, source), source); + } + + private static ProjectSettings Deflickered() + { + var p = new ProjectSettings(); + return p with { Exposure = p.Exposure with { Deflicker = p.Exposure.Deflicker.WithManual(true), HighlightKnee = null } }; + } + + [Test] + public async Task DeflickerFlattensThePreviewedLuminance() + { + var (renderer, _) = Create(); + var project = Deflickered(); + var corrections = await renderer.PrepareAsync(project, CancellationToken.None); + Assert.Same(corrections, renderer.Cached(project)); + Assert.Null(renderer.Cached(new ProjectSettings()), "other exposure settings need their own preparation"); + + var corrected = new List(); + var original = new List(); + for (var i = 4; i < 20; i++) + { + using var frame = await renderer.RenderAsync(new PreviewRequest(i, project, 64, PreviewFraming.Output), corrections, CancellationToken.None); + Assert.NotNull(frame); + corrected.Add(LogMean(frame!.Corrected)); + original.Add(LogMean(frame.Original)); + } + Assert.Less(Spread(corrected), Spread(original) * 0.6, "flicker removed between the steps"); + } + + [Test] + public async Task OutputFramingFollowsTheExportAspect() + { + var (renderer, _) = Create(); + var project = new ProjectSettings(); + project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("square-1440") } }; + using var output = await renderer.RenderAsync(new PreviewRequest(0, project, 80, PreviewFraming.Output), null, CancellationToken.None); + Assert.Equal(80, output!.Corrected.Width, "the square output at the preview's long edge"); + Assert.Equal(80, output.Corrected.Height); + Assert.Equal(output.Corrected.Width, output.Original.Width); + + using var source = await renderer.RenderAsync(new PreviewRequest(0, project, 80, PreviewFraming.Source), null, CancellationToken.None); + Assert.Equal(80, source!.Corrected.Width); + Assert.Approximately(64.0 / 96, source.Crop.Width, 0.02, "the square crop keeps two thirds of the 3:2 frame"); + Assert.Approximately(1, source.Crop.Height, 0.02); + Assert.Approximately((1 - 64.0 / 96) / 2, source.Crop.X, 0.02, "centred"); + } + + [Test] + public async Task VectorsDescribeTheMotionToTheNextFrame() + { + var (renderer, _) = Create(); + using var frame = await renderer.RenderAsync(new PreviewRequest(10, new ProjectSettings(), 96, PreviewFraming.Source, Vectors: true), null, + CancellationToken.None); + Assert.NotEmpty(frame!.Vectors); + Assert.True(frame.Vectors.All(v => v.X >= 0 && v.X < 96 && v.Y >= 0 && v.Y < 64)); + using var last = await renderer.RenderAsync(new PreviewRequest(EditorFixture.Sunset.Count - 1, new ProjectSettings(), 96, PreviewFraming.Source, true), + null, CancellationToken.None); + Assert.Empty(last!.Vectors); + } + + [Test] + public async Task ACancelledPreviewStopsWhileDecoding() + { + var (renderer, source) = Create(); + source.DecodeGate = new TaskCompletionSource().Task; + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + await Assert.ThrowsAsync(() => renderer.RenderAsync(new PreviewRequest(0, new ProjectSettings(), 64, PreviewFraming.Output), null, cts.Token)); + } + + [Test] + public async Task AnUnknownFrameHasNoPreview() + { + var (renderer, _) = Create(); + Assert.Null(await renderer.RenderAsync(new PreviewRequest(-1, new ProjectSettings(), 64, PreviewFraming.Output), null, CancellationToken.None)); + Assert.Null(await renderer.RenderAsync(new PreviewRequest(10_000, new ProjectSettings(), 64, PreviewFraming.Output), null, CancellationToken.None)); + } + + [Test] + public async Task PreparedDecodesAreReused() + { + var (renderer, source) = Create(); + var project = new ProjectSettings(); + project = project with { Exposure = project.Exposure with { WhiteBalanceSmoothing = project.Exposure.WhiteBalanceSmoothing.WithManual(true) } }; + await renderer.PrepareAsync(project, CancellationToken.None); + var decodes = source.Decodes; + Assert.GreaterOrEqual(decodes, EditorFixture.Sunset.Count, "white balance is measured on every frame"); + await renderer.PrepareAsync(project with { Exposure = project.Exposure with { ExposureOffsetEv = 0.5 } }, CancellationToken.None); + Assert.Equal(decodes, source.Decodes); + } + + private static double LogMean(ImageBuffer image) + { + double sum = 0; + var n = image.PlaneLength; + for (var i = 0; i < n; i++) sum += 0.2126 * image.Plane(0)[i] + 0.7152 * image.Plane(1)[i] + 0.0722 * image.Plane(2)[i]; + return Math.Log2(sum / n); + } + + /// Standard deviation of the frame-to-frame differences (flicker, not the slow ramp). + private static double Spread(List values) + { + var diffs = values.Zip(values.Skip(1), (a, b) => b - a).ToList(); + var mean = diffs.Average(); + return Math.Sqrt(diffs.Sum(d => (d - mean) * (d - mean)) / diffs.Count); + } +} diff --git a/tests/Titano.App.Tests/Editor/ProjectHistoryTests.cs b/tests/Titano.App.Tests/Editor/ProjectHistoryTests.cs new file mode 100644 index 00000000..95cf5b20 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/ProjectHistoryTests.cs @@ -0,0 +1,90 @@ +using Titano.App.Editor; +using Titano.Core.Project; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +public sealed class ProjectHistoryTests +{ + private static ProjectSettings WithOffset(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } }; + + [Test] + public void UndoAndRedoWalkTheSnapshots() + { + var start = new ProjectSettings(); + var history = new ProjectHistory(start); + var changes = 0; + history.Changed += () => changes++; + + Assert.True(history.Apply(WithOffset(start, 0.5))); + Assert.True(history.Apply(WithOffset(history.Current, 1.0))); + Assert.Equal(1.0, history.Current.Exposure.ExposureOffsetEv); + + Assert.True(history.Undo()); + Assert.Equal(0.5, history.Current.Exposure.ExposureOffsetEv); + Assert.True(history.Undo()); + Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv); + Assert.False(history.Undo(), "nothing left to undo"); + Assert.True(history.CanRedo); + + Assert.True(history.Redo()); + Assert.Equal(0.5, history.Current.Exposure.ExposureOffsetEv); + Assert.Equal(5, changes); + } + + [Test] + public void ANewEditClearsRedo() + { + var history = new ProjectHistory(new ProjectSettings()); + history.Apply(WithOffset(history.Current, 0.5)); + history.Undo(); + history.Apply(WithOffset(history.Current, -0.5)); + Assert.False(history.CanRedo); + Assert.False(history.Redo()); + } + + [Test] + public void EditsWithTheSameKeyAreOneStep() + { + var history = new ProjectHistory(new ProjectSettings()); + for (var i = 1; i <= 10; i++) history.Apply(WithOffset(history.Current, i / 10.0), "Exposure.Offset"); + history.Apply(history.Current with { HeroFrame = 3 }, "Frames.Hero"); + + Assert.True(history.Undo()); + Assert.Equal(1.0, history.Current.Exposure.ExposureOffsetEv, "the hero step undone"); + Assert.True(history.Undo()); + Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv, "the whole drag undone in one step"); + Assert.False(history.CanUndo); + } + + [Test] + public void AnEditThatChangesNothingIsNotAStep() + { + var history = new ProjectHistory(new ProjectSettings()); + Assert.False(history.Apply(new ProjectSettings()), "equal values, even as a new instance"); + Assert.False(history.CanUndo); + } + + [Test] + public void ReplaceAdoptsWithoutAnUndoStep() + { + var history = new ProjectHistory(new ProjectSettings()); + history.Apply(WithOffset(history.Current, 0.5)); + history.Replace(history.Current with { HeroFrame = 7 }); + Assert.Equal(7, history.Current.HeroFrame); + Assert.True(history.Undo()); + Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv); + Assert.False(history.CanUndo); + } + + [Test] + public void TheOldestStepsAreDroppedBeyondCapacity() + { + var history = new ProjectHistory(new ProjectSettings(), capacity: 3); + for (var i = 1; i <= 5; i++) history.Apply(history.Current with { HeroFrame = i }); + var undone = 0; + while (history.Undo()) undone++; + Assert.Equal(3, undone); + Assert.Equal(2, history.Current.HeroFrame); + } +} diff --git a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs new file mode 100644 index 00000000..e29a2aaa --- /dev/null +++ b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs @@ -0,0 +1,157 @@ +using System.IO; +using Titano.App.Editor; +using Titano.Core.Archiving; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Metadata; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Jobs; +using Titano.Data.Processing; +using Titano.Data.Repositories; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +/// Project merges, and the local source over a real SQLite index and archive folder. +public sealed class ProjectStoreTests(TestContext context) +{ + [Test] + public void AMemberOnlyTheyChangedIsKept() + { + var basis = new ProjectSettings(); + var ours = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.5 } }; + var theirs = basis with { HeroFrame = 12 }; + var merged = ProjectMerge.Merge(basis, ours, theirs); + Assert.Equal(0.5, merged.Exposure.ExposureOffsetEv); + Assert.Equal(12, merged.HeroFrame); + } + + [Test] + public void AdviceMergesIntoAManualValueOfTheSameSetting() + { + var basis = new ProjectSettings(); + var ours = basis with { Exposure = basis.Exposure with { Deflicker = basis.Exposure.Deflicker.WithManual(true) } }; + var theirs = basis with { Exposure = basis.Exposure with { Deflicker = basis.Exposure.Deflicker.WithAdvice(false, "Advisor.Reason.Deflicker.Off") } }; + var merged = ProjectMerge.Merge(basis, ours, theirs).Exposure.Deflicker; + Assert.False(merged.IsAuto, "the user's manual choice stays"); + Assert.True(merged.Manual); + Assert.True(merged.HasAdvice, "the new advice is stored next to it"); + Assert.Equal("Advisor.Reason.Deflicker.Off", merged.ReasonKey); + } + + [Test] + public void WhenBothChangedAValueTheEditorWins() + { + var basis = new ProjectSettings(); + var merged = ProjectMerge.Merge(basis, basis with { HeroFrame = 3 }, basis with { HeroFrame = 9 }); + Assert.Equal(3, merged.HeroFrame); + } + + [Test] + public async Task TheLocalSourceReadsDecodesSavesAndQueues() + { + var (db, sequenceId, root) = await ArchiveAsync(12); + await using (db) + { + var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }; + await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options); + var content = await source.LoadAsync(context.Cancellation); + Assert.Equal(12, content.Count); + Assert.Equal(96, content.SourceWidth); + Assert.Equal(64, content.SourceHeight); + Assert.Null(content.Deep, "not analysed yet"); + Assert.NotNull(content.ExportsFolder); + Assert.Contains("exports", content.ExportsFolder!); + + using (var frame = await source.DecodeAsync(3, 32, DecodePurpose.Thumbnail, context.Cancellation)) + { + Assert.NotNull(frame); + Assert.LessOrEqual(Math.Max(frame!.Width, frame.Height), 32); + } + Assert.Null(await source.DecodeAsync(99, 32, DecodePurpose.Thumbnail, context.Cancellation)); + + // A save writes project.json and the index row together. + var edited = content.Project with { HeroFrame = 4, Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.3 } }; + var stored = await source.SaveProjectAsync(edited, content.Project, context.Cancellation); + Assert.True(ProjectMerge.SameValues(edited, stored)); + var projectPath = Path.Combine(root, "Synthetic", ".titano", "project.json"); + Assert.FileExists(projectPath); + Assert.Equal(edited.ToJson(), File.ReadAllText(projectPath)); + var row = await db.Sequences.GetAsync(sequenceId); + Assert.Equal(edited.ToJson(), row!.SettingsJson); + + // Someone else changes the settings meanwhile (the server API): both edits survive the next save. + var theirs = stored with { Camera = stored.Camera with { OffsetY = 0.25 } }; + await db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = theirs.ToJson() }, row.SettingsVersion); + var mine = stored with { HeroFrame = 7 }; + var merged = await source.SaveProjectAsync(mine, stored, context.Cancellation); + Assert.Equal(7, merged.HeroFrame); + Assert.Equal(0.25, merged.Camera.OffsetY); + Assert.Equal(merged.ToJson(), File.ReadAllText(projectPath)); + Assert.Equal(merged.ToJson(), (await db.Sequences.GetAsync(sequenceId))!.SettingsJson); + + var reloaded = await source.LoadAsync(context.Cancellation); + Assert.True(ProjectMerge.SameValues(merged, reloaded.Project), "the index copy is read back"); + + await Assert.ThrowsAsync(() => source.SubmitAsync(ProcessingJobs.DeepAnalysis([sequenceId]), context.Cancellation)); + } + } + + [Test] + public async Task JobsGoToTheEngine() + { + var (db, sequenceId, _) = await ArchiveAsync(4); + await using (db) + { + await using var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "test" }); + await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), engine); + var content = await source.LoadAsync(context.Cancellation); + var session = new EditorSession(source, content, []); + var id = await session.SubmitAsync(session.AnalysisRequest(), context.Cancellation); + var job = await db.Jobs.GetAsync(id); + Assert.Equal(JobKind.DeepAnalyse, job!.Kind); + Assert.Equal(JobState.Queued, job.State); + Assert.SequenceEqual([sequenceId], job.TargetIds); + } + } + + [Test] + public async Task AnUnreadableProjectIsReportedNotReplaced() + { + var (db, sequenceId, root) = await ArchiveAsync(4); + await using (db) + { + var path = Path.Combine(root, "Synthetic", ".titano", "project.json"); + File.WriteAllText(path, "{ not json"); + await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null); + await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation)); + Assert.Equal("{ not json", File.ReadAllText(path)); + } + } + + /// A temporary archive with one adopted folder of synthetic JPEGs, indexed. + private async Task<(TitanoDatabase Db, Guid SequenceId, string Root)> ArchiveAsync(int frames) + { + var directory = context.CreateTempDirectory("editor"); + var root = Path.Combine(directory, "archive"); + var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db"))); + var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }); + var archive = await service.CreateAsync(root, "Test"); + var sequence = EditorFixture.Sequence(frames); + var folder = Path.Combine(root, "Synthetic"); + Directory.CreateDirectory(folder); + for (var i = 0; i < sequence.Count; i++) + { + using var image = sequence.Render(i); + var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]); + File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] })); + } + await service.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation); + var location = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single(); + return (db, location.Id, root); + } +} diff --git a/tests/Titano.App.Tests/Editor/SchedulingTests.cs b/tests/Titano.App.Tests/Editor/SchedulingTests.cs new file mode 100644 index 00000000..1df14a74 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/SchedulingTests.cs @@ -0,0 +1,133 @@ +using System.Collections.Concurrent; +using Titano.App.Editor; +using Titano.Core.Project; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +/// Debouncing and cancellation of preview work, and the coalescing project writer. +public sealed class SchedulingTests +{ + [Test] + public async Task OnlyTheLastOfRapidRequestsRuns() + { + using var runner = new LatestRunner(TimeSpan.FromMilliseconds(80)); + var ran = new ConcurrentQueue(); + var tasks = Enumerable.Range(0, 10).Select(i => runner.Schedule(_ => + { + ran.Enqueue(i); + return Task.CompletedTask; + })).ToList(); + await Task.WhenAll(tasks); + Assert.SequenceEqual([9], ran); + } + + [Test] + public async Task ANewRequestCancelsTheRunningOne() + { + using var runner = new LatestRunner(TimeSpan.Zero); + var started = new TaskCompletionSource(); + var cancelled = false; + var first = runner.Schedule(async token => + { + started.SetResult(); + try + { + await Task.Delay(Timeout.Infinite, token); + } + catch (OperationCanceledException) + { + cancelled = true; + throw; + } + }); + await started.Task; + var second = runner.Schedule(_ => Task.CompletedTask); + await Task.WhenAll(first, second); + Assert.True(cancelled, "the superseded run saw its token cancelled"); + Assert.True(first.IsCompletedSuccessfully, "a superseded run ends quietly"); + } + + [Test] + public async Task ImmediateRequestsSkipTheDelay() + { + using var runner = new LatestRunner(TimeSpan.FromSeconds(30)); + var ran = false; + await runner.Schedule(_ => + { + ran = true; + return Task.CompletedTask; + }, immediate: true).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(ran); + } + + [Test] + public async Task FailuresSurfaceFromTheRun() + { + using var runner = new LatestRunner(TimeSpan.Zero); + await Assert.ThrowsAsync(() => runner.Schedule(_ => throw new InvalidOperationException("broken"))); + } + + [Test] + public async Task CancelStopsThePendingRequest() + { + using var runner = new LatestRunner(TimeSpan.FromMilliseconds(200)); + var ran = false; + var run = runner.Schedule(_ => + { + ran = true; + return Task.CompletedTask; + }); + runner.Cancel(); + await run; + Assert.False(ran); + } + + [Test] + public async Task TheSaverWritesTheNewestProjectOnce() + { + var saved = new List(); + var saver = new ProjectSaver(p => + { + saved.Add(p.HeroFrame); + return Task.CompletedTask; + }, TimeSpan.FromMilliseconds(50)); + for (var i = 0; i < 5; i++) saver.Schedule(new ProjectSettings { HeroFrame = i }); + await saver.FlushAsync(); + Assert.SequenceEqual([(int?)4], saved); + Assert.False(saver.HasPendingChanges); + } + + [Test] + public async Task FlushSkipsTheDelay() + { + var saved = 0; + var saver = new ProjectSaver(_ => + { + saved++; + return Task.CompletedTask; + }, TimeSpan.FromMinutes(5)); + saver.Schedule(new ProjectSettings()); + await saver.FlushAsync().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(1, saved); + } + + [Test] + public async Task AChangeDuringAWriteIsWrittenAfterIt() + { + var gate = new TaskCompletionSource(); + var saved = new List(); + var saver = new ProjectSaver(async p => + { + saved.Add(p.HeroFrame); + if (saved.Count == 1) await gate.Task; + }, TimeSpan.Zero); + saver.Schedule(new ProjectSettings { HeroFrame = 1 }); + while (saved.Count == 0) await Task.Delay(5); + saver.Schedule(new ProjectSettings { HeroFrame = 2 }); + saver.Schedule(new ProjectSettings { HeroFrame = 3 }); + gate.SetResult(); + await saver.FlushAsync(); + Assert.SequenceEqual([(int?)1, 3], saved); + } +} From f6ad822fbb862ba3d8f06ec2b24931ef00b89166 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 17:14:48 +0000 Subject: [PATCH 2/9] feat(app): editor view models for every section, preset cards and render actions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.App/Editor/CameraTab.cs | 265 +++++++ src/Titano.App/Editor/EditorImages.cs | 53 ++ src/Titano.App/Editor/EditorSession.cs | 18 + src/Titano.App/Editor/EditorTab.cs | 72 ++ src/Titano.App/Editor/EditorText.cs | 104 +++ src/Titano.App/Editor/EditorViewModel.cs | 675 ++++++++++++++++++ src/Titano.App/Editor/ExportPlanner.cs | 5 +- src/Titano.App/Editor/ExportTab.cs | 466 ++++++++++++ src/Titano.App/Editor/ExposureTab.cs | 112 +++ src/Titano.App/Editor/FramesTab.cs | 199 ++++++ src/Titano.App/Editor/LocalSequenceSource.cs | 4 +- src/Titano.App/Editor/MotionTab.cs | 159 +++++ src/Titano.App/Editor/SettingRows.cs | 393 ++++++++++ src/Titano.App/Sections/SequenceViewModel.cs | 125 +++- .../Editor/EditorSessionTests.cs | 22 + 15 files changed, 2666 insertions(+), 6 deletions(-) create mode 100644 src/Titano.App/Editor/CameraTab.cs create mode 100644 src/Titano.App/Editor/EditorImages.cs create mode 100644 src/Titano.App/Editor/EditorTab.cs create mode 100644 src/Titano.App/Editor/EditorText.cs create mode 100644 src/Titano.App/Editor/EditorViewModel.cs create mode 100644 src/Titano.App/Editor/ExportTab.cs create mode 100644 src/Titano.App/Editor/ExposureTab.cs create mode 100644 src/Titano.App/Editor/FramesTab.cs create mode 100644 src/Titano.App/Editor/MotionTab.cs create mode 100644 src/Titano.App/Editor/SettingRows.cs diff --git a/src/Titano.App/Editor/CameraTab.cs b/src/Titano.App/Editor/CameraTab.cs new file mode 100644 index 00000000..0ef6c3cc --- /dev/null +++ b/src/Titano.App/Editor/CameraTab.cs @@ -0,0 +1,265 @@ +using System.Collections.ObjectModel; +using System.Windows; +using System.Windows.Input; +using Titano.App.Infrastructure; +using Titano.Core.Advice; +using Titano.Core.Export; +using Titano.Core.Localization; +using Titano.Core.Mathematics; +using Titano.Core.Project; +using Titano.Ui.Mvvm; + +namespace Titano.App.Editor; + +/// +/// Camera (BRIEF §12.3): output aspect and crop placement, and virtual-camera keyframes edited as a zoom curve over the +/// sequence (X = frame, Y = zoom) with the selected keyframe's framing below. +/// +public sealed class CameraTab : EditorTab +{ + /// Zoom at the top of the curve editor. + public const double MaxZoom = 4; + + private int _selectedKey = -1; + + public CameraTab(EditorViewModel editor) + : base(editor, "Camera", AdvisorSection.Camera) + { + var s = editor.Session; + Rows = + [ + new AutoChoiceRow(s, EditorSettings.Aspect, "Editor.Camera.Aspect", "Tooltips.Editor.Camera.Aspect", + [ + new Choice("source", "Editor.Aspect.Source"), new Choice("16:9", "Editor.Aspect.Ratio", "16:9"), new Choice("21:9", "Editor.Aspect.Ratio", "21:9"), + new Choice("4:3", "Editor.Aspect.Ratio", "4:3"), new Choice("3:2", "Editor.Aspect.Ratio", "3:2"), new Choice("1:1", "Editor.Aspect.Ratio", "1:1"), + new Choice("9:16", "Editor.Aspect.Ratio", "9:16"), new Choice("4:5", "Editor.Aspect.Ratio", "4:5"), + ]), + new NumberRow(s, "Editor.Camera.OffsetX", "Tooltips.Editor.Camera.OffsetX", -1, 1, 0.05, p => p.Camera.OffsetX, + (p, v) => p with { Camera = p.Camera with { OffsetX = v } }, Placement), + new NumberRow(s, "Editor.Camera.OffsetY", "Tooltips.Editor.Camera.OffsetY", -1, 1, 0.05, p => p.Camera.OffsetY, + (p, v) => p with { Camera = p.Camera with { OffsetY = v } }, Placement), + ]; + AddKeyCommand = new RelayCommand(AddKey, () => !Editor.IsBusy && Keys.All(k => k.Frame != Editor.CurrentIndex)); + RemoveKeyCommand = new RelayCommand(RemoveKey, () => !Editor.IsBusy && SelectedKey >= 0); + Refresh(); + } + + /// Keyframes as curve points: X = frame / (count − 1), Y = (zoom − 1) / ( − 1). Edited in place by the curve editor. + public ObservableCollection KeyPoints { get; } = []; + + public int SelectedKey + { + get => _selectedKey; + set + { + if (!Set(ref _selectedKey, value)) return; + OnSelectedKeyChanged(); + } + } + + public bool HasSelectedKey => SelectedKey >= 0 && SelectedKey < Keys.Count; + + /// Framing of the selected keyframe: centre (0–1) and zoom. + public double SelectedCenterX + { + get => HasSelectedKey ? Keys[SelectedKey].CenterX : 0.5; + set => EditSelected(k => k with { CenterX = double.Clamp(value, 0, 1) }); + } + + public double SelectedCenterY + { + get => HasSelectedKey ? Keys[SelectedKey].CenterY : 0.5; + set => EditSelected(k => k with { CenterY = double.Clamp(value, 0, 1) }); + } + + public double SelectedZoom + { + get => HasSelectedKey ? Keys[SelectedKey].Zoom : 1; + set => EditSelected(k => k with { Zoom = double.Clamp(value, 1, MaxZoom) }); + } + + public string SelectedZoomText => Loc.L("Editor.Value.Zoom", SelectedZoom.ToString("0.00", Loc.Culture)); + + /// "Keyframe 2 of 3 · frame 0413". + public string KeyText => HasSelectedKey + ? Loc.L("Editor.Camera.KeyOf", SelectedKey + 1, Keys.Count, (Keys[SelectedKey].Frame + 1).ToString("D4", Loc.Culture)) + : Loc.Plural("Editor.Camera.Keys", Keys.Count); + + public double Playhead => Editor.FrameCount > 1 ? (double)Editor.CurrentIndex / (Editor.FrameCount - 1) : double.NaN; + + public Func XFormatter => x => EditorText.Position((int)double.Round(x * (Editor.FrameCount - 1)), Editor.FrameCount); + + public Func YFormatter { get; } = y => Loc.L("Editor.Value.Zoom", (1 + y * (MaxZoom - 1)).ToString("0.00", Loc.Culture)); + + public ICommand AddKeyCommand { get; } + + public ICommand RemoveKeyCommand { get; } + + private IReadOnlyList Keys => Editor.Session.Project.Camera.Keyframes; + + public override void Refresh() + { + base.Refresh(); + var points = Keys.OrderBy(k => k.Frame).Select(ToPoint).ToList(); + if (!points.SequenceEqual(KeyPoints)) + { + KeyPoints.Clear(); + foreach (var p in points) KeyPoints.Add(p); + } + if (SelectedKey >= Keys.Count) SelectedKey = Keys.Count - 1; + OnSelectedKeyChanged(); + } + + /// The curve editor finished an edit (add, move, delete): the points become the keyframes, keeping each one's framing. + public void CommitCurve() + { + var old = Keys.OrderBy(k => k.Frame).ToList(); + var keys = new List(); + foreach (var point in KeyPoints.OrderBy(p => p.X)) + { + var frame = (int)double.Round(point.X * double.Max(1, Editor.FrameCount - 1)); + var zoom = 1 + double.Clamp(point.Y, 0, 1) * (MaxZoom - 1); + var nearest = old.MinBy(k => int.Abs(k.Frame - frame)); + keys.Add(nearest is null ? new CameraKey(frame, 0.5, 0.5, zoom, 0) : nearest with { Frame = frame, Zoom = zoom }); + } + Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. keys.DistinctBy(k => k.Frame)] } }); + } + + public void OnCurrentFrameChanged() => OnPropertyChanged(nameof(Playhead)); + + private static string Placement(double value) => value == 0 ? Loc.L("Editor.Value.Centred") : value.ToString("+0.00;−0.00", Loc.Culture); + + private Point ToPoint(CameraKey key) => new(Editor.FrameCount > 1 ? (double)key.Frame / (Editor.FrameCount - 1) : 0, (key.Zoom - 1) / (MaxZoom - 1)); + + private void AddKey() + { + var frame = Editor.CurrentIndex; + var key = new CameraKey(frame, 0.5, 0.5, 1, 0); + Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. p.Camera.Keyframes.Append(key).OrderBy(k => k.Frame)] } }); + SelectedKey = Keys.Select((k, i) => (k, i)).First(t => t.k.Frame == frame).i; + } + + private void RemoveKey() + { + if (!HasSelectedKey) return; + var frame = Keys[SelectedKey].Frame; + Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. p.Camera.Keyframes.Where(k => k.Frame != frame)] } }); + } + + private void EditSelected(Func change) + { + if (!HasSelectedKey) return; + var index = SelectedKey; + Editor.Session.Edit(p => + { + var keys = p.Camera.Keyframes.OrderBy(k => k.Frame).ToList(); + keys[index] = change(keys[index]); + return p with { Camera = p.Camera with { Keyframes = keys } }; + }, "Camera.Key"); + } + + private void OnSelectedKeyChanged() + { + OnPropertyChanged(nameof(HasSelectedKey)); + OnPropertyChanged(nameof(SelectedCenterX)); + OnPropertyChanged(nameof(SelectedCenterY)); + OnPropertyChanged(nameof(SelectedZoom)); + OnPropertyChanged(nameof(SelectedZoomText)); + OnPropertyChanged(nameof(KeyText)); + } +} + +/// +/// Time (BRIEF §12.3): timing mode, playback rate, fit-to duration and the time-remap curve (output time → source +/// position, Fritsch–Carlson as the render evaluates it), with the plan in numbers. +/// +public sealed class TimeTab : EditorTab +{ + private Func? _evaluator; + private string? _planText; + + public TimeTab(EditorViewModel editor) + : base(editor, "Time", AdvisorSection.Timing) + { + var s = editor.Session; + Rows = + [ + new AutoChoiceRow(s, EditorSettings.TimingMode, "Editor.Time.Mode", "Tooltips.Editor.Time.Mode", + [ + new Choice(TimingMode.Constant, "Editor.Timing.Constant"), new Choice(TimingMode.Adaptive, "Editor.Timing.Adaptive"), + new Choice(TimingMode.Interpolated, "Editor.Timing.Interpolated"), new Choice(TimingMode.Remapped, "Editor.Timing.Remapped"), + ]), + new AutoChoiceRow(s, EditorSettings.FrameRate, "Editor.Time.Rate", "Tooltips.Editor.Time.Rate", + [.. ExportPresets.FrameRates.Select(r => new Choice(FrameRateText.Format(r), "Editor.Value.Fps", EditorText.FrameRate(r)))]), + new NumberRow(s, "Editor.Time.Fit", "Tooltips.Editor.Time.Fit", 0, 600, 5, p => p.Timing.FitToSeconds ?? 0, + (p, v) => p with { Timing = p.Timing with { FitToSeconds = v > 0 ? v : null } }, + v => v > 0 ? Formatting.Duration(TimeSpan.FromSeconds(v)) : Loc.L("Editor.Value.Off")), + ]; + Refresh(); + } + + /// Remap control points (output fraction → source fraction), edited in place by the curve editor. + public ObservableCollection RemapPoints { get; } = []; + + /// The monotone spline through . + public Func? Evaluator { get => _evaluator; private set => Set(ref _evaluator, value); } + + /// "3,600 frames → 2 min 30 s · 24 fps". + public string? PlanText { get => _planText; private set => Set(ref _planText, value); } + + public double Playhead => Editor.FrameCount > 1 ? (double)Editor.CurrentIndex / (Editor.FrameCount - 1) : double.NaN; + + public Func XFormatter { get; } = x => Loc.L("Editor.Time.Output", (x * 100).ToString("0", Loc.Culture)); + + public Func YFormatter { get; } = y => Loc.L("Editor.Time.Source", (y * 100).ToString("0", Loc.Culture)); + + public override void Refresh() + { + base.Refresh(); + var curve = Editor.Session.Project.Timing.RemapCurve; + var points = curve.Select(p => new Point(p.X, p.Y)).ToList(); + if (!points.SequenceEqual(RemapPoints)) + { + RemapPoints.Clear(); + foreach (var p in points) RemapPoints.Add(p); + } + Evaluator = Spline(points); + } + + public override void OnPlanChanged() + { + if (Editor.Plan is not { } plan) + { + PlanText = null; + return; + } + var render = plan.Setup.Plan; + PlanText = Loc.Plural("Editor.Time.Plan", render.Frames.Count, Formatting.Duration(TimeSpan.FromSeconds(render.DurationSeconds)), + EditorText.FrameRate(render.FrameRate)); + } + + /// The curve editor finished an edit: the points become the remap curve, and the timing mode follows it. + public void CommitCurve() + { + var curve = RemapPoints.OrderBy(p => p.X).Select(p => new CurvePoint(double.Clamp(p.X, 0, 1), double.Clamp(p.Y, 0, 1))).ToList(); + Editor.Session.Edit(p => p with + { + Timing = p.Timing with + { + RemapCurve = curve, + Mode = EditorSettings.TimingMode.Effective(p, null) == TimingMode.Remapped ? p.Timing.Mode : p.Timing.Mode.WithManual(TimingMode.Remapped), + }, + }); + } + + public void OnCurrentFrameChanged() => OnPropertyChanged(nameof(Playhead)); + + private static Func? Spline(IReadOnlyList points) + { + if (points.Count < 2) return null; + var ordered = points.OrderBy(p => p.X).DistinctBy(p => p.X).ToList(); + if (ordered.Count < 2) return null; + var spline = new MonotoneSpline([.. ordered.Select(p => p.X)], [.. ordered.Select(p => p.Y)]); + return x => double.Clamp(spline.Evaluate(x), 0, 1); + } +} diff --git a/src/Titano.App/Editor/EditorImages.cs b/src/Titano.App/Editor/EditorImages.cs new file mode 100644 index 00000000..aebf09a6 --- /dev/null +++ b/src/Titano.App/Editor/EditorImages.cs @@ -0,0 +1,53 @@ +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Ui.Visuals; + +namespace Titano.App.Editor; + +/// Linear-light frames as frozen sRGB bitmaps the UI thread can show (created on any thread). +public static class EditorImages +{ + public static BitmapSource ToBitmap(ImageBuffer image) + { + ArgumentNullException.ThrowIfNull(image); + var channels = int.Min(3, image.Channels); + var pixels = PixelConvert.ToInterleaved8(image, channels); + var format = channels == 1 ? PixelFormats.Gray8 : PixelFormats.Rgb24; + var bitmap = BitmapSource.Create(image.Width, image.Height, 96, 96, format, null, pixels, image.Width * channels); + bitmap.Freeze(); + return bitmap; + } +} + +/// +/// Filmstrip thumbnails decoded through the editor's (embedded previews when large +/// enough), at most a few at a time so scrolling the strip never floods the decoders. +/// +public sealed class EditorThumbnails(ISequenceSource source, int count) : IThumbnailSource +{ + private readonly SemaphoreSlim _decoders = new(int.Clamp(Environment.ProcessorCount / 2, 2, 6)); + + public int Count { get; } = count; + + public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken) + { + await _decoders.WaitAsync(cancellationToken); + try + { + // Long edge for frames up to 16:9 tall or wide; the cache rounds requests, so nearby widths share a decode. + using var frame = await source.DecodeAsync(index, int.Clamp(pixelWidth, 32, 512), DecodePurpose.Thumbnail, cancellationToken); + return frame is null ? null : EditorImages.ToBitmap(frame); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Debug("editor", $"No thumbnail for frame {index}: {ex.Message}"); + return null; + } + finally + { + _decoders.Release(); + } + } +} diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs index 4fc40fef..4a243957 100644 --- a/src/Titano.App/Editor/EditorSession.cs +++ b/src/Titano.App/Editor/EditorSession.cs @@ -98,6 +98,24 @@ public sealed class EditorSession : IAsyncDisposable /// Makes the hero frame (sequence thumbnail). public bool SetHero(int frame) => (uint)frame < (uint)Content.Count && Edit(p => p with { HeroFrame = frame }); + /// + /// Applies a sequence preset (BRIEF §10.3) as one undoable step: its timing, exposure, motion, aspect and export + /// preset; the user's frames (exclusions, hero), crop, keyframes, remap curve, exposure offset and output naming stay. + /// + public bool ApplyPreset(SequencePreset preset) + { + ArgumentNullException.ThrowIfNull(preset); + var s = preset.Settings; + return Edit(p => p with + { + Timing = s.Timing with { RemapCurve = p.Timing.RemapCurve, FitToSeconds = p.Timing.FitToSeconds }, + Exposure = s.Exposure with { ExposureOffsetEv = p.Exposure.ExposureOffsetEv, HighlightKnee = p.Exposure.HighlightKnee }, + Motion = s.Motion, + Camera = p.Camera with { Aspect = s.Camera.Aspect }, + Export = p.Export with { Preset = s.Export.Preset, Overrides = new ExportOverrides() }, + }); + } + /// /// A render of with the project as it is now (the job embeds it, so a render queued before /// the save lands still renders what the user sees). diff --git a/src/Titano.App/Editor/EditorTab.cs b/src/Titano.App/Editor/EditorTab.cs new file mode 100644 index 00000000..99fa5247 --- /dev/null +++ b/src/Titano.App/Editor/EditorTab.cs @@ -0,0 +1,72 @@ +using System.Windows.Input; +using Titano.Core.Advice; +using Titano.Core.Localization; +using Titano.Ui.Mvvm; + +namespace Titano.App.Editor; + +/// +/// One section of the editor (BRIEF §12.3): a tab with its measuring tool below the filmstrip and its settings column on +/// the right, with "Optimise section" and "Reset". runs after every project change. +/// +public abstract class EditorTab : LocalizedViewModel +{ + protected EditorTab(EditorViewModel editor, string key, AdvisorSection section) + { + Editor = editor; + Key = key; + Section = section; + OptimiseCommand = new RelayCommand(() => Editor.Optimise(Section), () => CanOptimise && !Editor.IsBusy); + ResetCommand = new RelayCommand(() => Editor.Session.ResetSection(Section), () => CanReset && !Editor.IsBusy); + } + + public EditorViewModel Editor { get; } + + /// "Frames", "Exposure"… (resource key suffix). + public string Key { get; } + + public AdvisorSection Section { get; } + + public string Header => Loc.L("Editor.Tab." + Key); + + public string ToolTip => Loc.L("Tooltips.Editor.Tab." + Key); + + /// Settings rows of the right column (empty for tabs with their own panel). + public IReadOnlyList Rows { get; protected init; } = []; + + /// The advisor has heavier decisions for this section (stacking has none). + public virtual bool CanOptimise => true; + + public virtual bool CanReset => true; + + public string OptimiseToolTip => Loc.L(CanOptimise ? "Tooltips.Editor.OptimiseSection" : "Tooltips.Editor.OptimiseNone"); + + public ICommand OptimiseCommand { get; } + + public ICommand ResetCommand { get; } + + /// Re-reads the project (any change). + public virtual void Refresh() + { + foreach (var row in Rows) row.Refresh(); + } + + /// The sequence was read again: new analyses (charts, findings). + public virtual void OnContentChanged() => Refresh(); + + /// The preview's corrections were prepared for the current settings (target curves). + public virtual void OnCorrectionsChanged() + { + } + + /// The export plan of the project changed (durations, sizes). + public virtual void OnPlanChanged() + { + } + + public override void Dispose() + { + foreach (var row in Rows) row.Dispose(); + base.Dispose(); + } +} diff --git a/src/Titano.App/Editor/EditorText.cs b/src/Titano.App/Editor/EditorText.cs new file mode 100644 index 00000000..c47c97e4 --- /dev/null +++ b/src/Titano.App/Editor/EditorText.cs @@ -0,0 +1,104 @@ +using Titano.App.Infrastructure; +using Titano.Core.Export; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Core.Video; + +namespace Titano.App.Editor; + +/// The editor's composed texts (header summary, shot data, preset card lines), in the current UI language. +public static class EditorText +{ + private const string Separator = " · "; + + /// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings". + public static string Summary(SequenceContent content, int warnings) + { + ArgumentNullException.ThrowIfNull(content); + var s = content.Sequence; + var parts = new List { Loc.Plural("Editor.Summary.Frames", content.Count) }; + if (s.CameraModel is { Length: > 0 } camera) parts.Add(camera); + if (content.Light.MedianIntervalSeconds is > 0 and var interval) parts.Add(Loc.L("Editor.Summary.Interval", Number(interval))); + if (content.Light.CaptureSpan > TimeSpan.Zero) parts.Add(Formatting.Duration(content.Light.CaptureSpan)); + if (warnings > 0) parts.Add(Loc.Plural("Editor.Summary.Warnings", warnings)); + return string.Join(Separator, parts); + } + + /// "0413 / 3,600 · 18:02:11 · 1/8 s · f/8 · ISO 400 · 24 mm". + public static string Shot(Frame frame, int index, int count) + { + ArgumentNullException.ThrowIfNull(frame); + var parts = new List { Position(index, count) }; + if (frame.CapturedAt is { } at) parts.Add(at.ToString("T", Loc.Culture)); + if (frame.ExposureTime is > 0 and var t) parts.Add(Shutter(t)); + if (frame.FNumber is > 0 and var f) parts.Add(Loc.L("Editor.Shot.Aperture", Number(f))); + if (frame.Iso is > 0 and var iso) parts.Add(Loc.L("Editor.Shot.Iso", iso)); + if (frame.FocalLength is > 0 and var mm) parts.Add(Loc.L("Editor.Shot.Focal", Number(mm))); + return string.Join(Separator, parts); + } + + /// "0413 / 3,600". + public static string Position(int index, int count) => + (index + 1).ToString("D4", Loc.Culture) + " / " + count.ToString("N0", Loc.Culture); + + /// "1/250 s", "1/8 s", "2 s". + public static string Shutter(double seconds) => seconds >= 0.3 + ? Loc.L("Editor.Shot.Shutter", Number(seconds)) + : Loc.L("Editor.Shot.Shutter", "1/" + double.Round(1 / seconds).ToString("0", Loc.Culture)); + + /// "MP4 · HEVC Main10 · 3840×2160 · 24 fps". + public static string Format(ResolvedExport export, int width, int height) + { + ArgumentNullException.ThrowIfNull(export); + var parts = new List { Loc.L("Export.Container." + VideoCodecInfo.DefaultContainer(export.Codec)), CodecName(export.Codec, export.Profile, export.BitDepth) }; + if (width > 0 && height > 0) parts.Add(Size(width, height)); + parts.Add(Loc.L("Editor.Export.Fps", FrameRate(export.FrameRate))); + return string.Join(Separator, parts); + } + + /// "120 Mb/s · 0.07 bpp · NVENC" for video, "Quality 95 · Titano" for frames. + public static string Encoding(ResolvedExport export, long bitRate, string? encoder) + { + ArgumentNullException.ThrowIfNull(export); + var parts = new List(); + if (!VideoCodecInfo.IsManaged(export.Codec)) + { + parts.Add(BitRate(bitRate)); + var bpp = export.BitsPerPixel > 0 ? export.BitsPerPixel : ExportPreset.DefaultBitsPerPixel(export.Codec); + if (export.BitRate == 0 && bpp > 0) parts.Add(Loc.L("Editor.Export.Bpp", bpp.ToString("0.00", Loc.Culture))); + } + else if (export.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif) + { + parts.Add(Loc.L("Editor.Export.QualityValue", export.Quality)); + } + if (encoder is { Length: > 0 }) parts.Add(encoder); + return string.Join(Separator, parts); + } + + /// "2.2 GB · about 5 min". + public static string Estimate(ExportEstimate estimate) + { + ArgumentNullException.ThrowIfNull(estimate); + return Formatting.Bytes(estimate.Bytes) + Separator + Loc.L("Editor.Export.About", Formatting.Duration(estimate.Time)); + } + + /// "120 Mb/s". + public static string BitRate(long bitsPerSecond) => Loc.L("Editor.Export.Mbps", (bitsPerSecond / 1e6).ToString(bitsPerSecond >= 10_000_000 ? "0" : "0.#", Loc.Culture)); + + /// "3840×2160". + public static string Size(int width, int height) => width.ToString(Loc.Culture) + "×" + height.ToString(Loc.Culture); + + /// "23.976", "24". + public static string FrameRate(Rational rate) => rate.Denominator == 1 ? rate.Numerator.ToString(Loc.Culture) : rate.Value.ToString("0.###", Loc.Culture); + + /// Technical codec name ("H.264 High", "HEVC Main10", "PNG"…). + public static string CodecName(VideoCodec codec, CodecProfile profile, int bitDepth) => codec switch + { + VideoCodec.Hevc when profile == CodecProfile.HevcMain10 || bitDepth > 8 => Loc.L("Export.Codec.HevcMain10"), + VideoCodec.Hevc => Loc.L("Export.Codec.Hevc"), + VideoCodec.H264 => Loc.L("Export.Codec.H264"), + _ => Loc.L("Export.Codec." + codec), + }; + + private static string Number(double value) => value.ToString(value >= 10 ? "0" : "0.#", Loc.Culture); +} diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs new file mode 100644 index 00000000..09ccf623 --- /dev/null +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -0,0 +1,675 @@ +using System.Collections; +using System.Globalization; +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; +using Titano.App.Shell; +using Titano.Core.Advice; +using Titano.Core.Analysis; +using Titano.Core.Diagnostics; +using Titano.Core.Export; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Core.Render; +using Titano.Core.Video; +using Titano.Ui.Mvvm; +using Titano.Ui.Visuals; + +namespace Titano.App.Editor; + +/// +/// The sequence editor of one open sequence (BRIEF §12.3, Editor.html): header actions, the preview with its tools +/// (wipe compare, zoom, overlays) rendered through the pipeline at preview size, the filmstrip with markers, the +/// section tabs and the keyboard (space, arrows, Ctrl+Z/Y, Ctrl+0/1, Ctrl+R). Preview frames, corrections, the export +/// plan and the card estimates are computed off the UI thread; each request cancels the previous one. While an analysis +/// or render of this sequence runs, settings are disabled and viewing tools stay live. +/// +public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable +{ + public const int DefaultPreviewEdge = 1280; + private static readonly TimeSpan Debounce = TimeSpan.FromMilliseconds(150); + + private readonly IReadOnlyList _encoders; + private readonly EncoderHost _host; + private readonly Dispatcher _dispatcher; + private readonly LatestRunner _preview = new(Debounce); + private readonly LatestRunner _corrections = new(Debounce); + private readonly LatestRunner _plans = new(Debounce); + private readonly DispatcherTimer _player; + private readonly Dictionary _jobs = []; + private PreviewRenderer _renderer; + private int _currentIndex; + private EditorTab _selectedTab; + private ImageSource? _previewImage; + private ImageSource? _originalImage; + private bool _isCompare = true; + private bool _showVectors; + private bool _showRegions; + private bool _showCropMask; + private PreviewZoomMode _zoomMode = PreviewZoomMode.Fit; + private Rect _cropRect = new(0, 0, 1, 1); + private IReadOnlyList? _regionBoundary; + private IReadOnlyList? _motionVectors; + private int _previewEdge = DefaultPreviewEdge; + private int _previewVersion; + private bool _previewBusy; + private RenderCorrections? _correctionsValue; + private ExportPlan? _plan; + private IReadOnlyList _markers = []; + private IThumbnailSource _thumbnails; + private int _playLimit; + private bool _disposed; + + public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList encoders, EncoderHost host) + { + Shell = shell; + Session = session; + _encoders = encoders; + _host = host; + _dispatcher = Dispatcher.CurrentDispatcher; + _renderer = new PreviewRenderer(session.Content, session.Source); + Planner = new ExportPlanner(session.Content, encoders, host); + _thumbnails = new EditorThumbnails(session.Source, session.Content.Count); + _player = new DispatcherTimer(DispatcherPriority.Background, _dispatcher); + _player.Tick += (_, _) => Advance(); + + Frames = new FramesTab(this); + Exposure = new ExposureTab(this); + Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)]; + _selectedTab = Exposure; + _currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0; + RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))]; + + BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library)); + AnalyseCommand = new AsyncRelayCommand(AnalyseAsync, () => !IsBusy); + OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsBusy); + RenderCommand = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: false), () => CanRender); + UndoCommand = new RelayCommand(() => Session.Undo(), () => !IsBusy && Session.History.CanUndo); + RedoCommand = new RelayCommand(() => Session.Redo(), () => !IsBusy && Session.History.CanRedo); + PlayCommand = new RelayCommand(() => TogglePlay(limit: 0)); + PreviewClipCommand = new RelayCommand(() => TogglePlay(limit: ClipFrames())); + StepBackCommand = new RelayCommand(() => CurrentIndex--); + StepForwardCommand = new RelayCommand(() => CurrentIndex++); + FitCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Fit); + ActualSizeCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Actual); + + session.ProjectChanged += OnProjectChanged; + session.ContentChanged += OnContentChanged; + session.SaveFailed += OnSaveFailed; + if (shell.Services.Jobs is { } jobs) jobs.JobChanged += OnJobChanged; + UpdateMarkers(); + RequestCorrections(); + RequestPlan(); + RequestPreview(immediate: true); + } + + public ShellViewModel Shell { get; } + + public EditorSession Session { get; } + + public ExportPlanner Planner { get; private set; } + + public string Title => Session.Content.Sequence.DisplayTitle; + + /// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings". + public string Summary => EditorText.Summary(Session.Content, Session.Advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning)); + + public FramesTab Frames { get; } + + public ExposureTab Exposure { get; } + + public IReadOnlyList Tabs { get; } + + public EditorTab SelectedTab + { + get => _selectedTab; + set + { + if (value is null || !Set(ref _selectedTab, value)) return; + OnPropertyChanged(nameof(IsExportTab)); + if (IsExportTab && !ShowCropMask) ShowCropMask = true; + UpdateInfo(); + } + } + + /// The Export tab swaps the preview tools for compare, crop mask and a 10-second preview (Export.html). + public bool IsExportTab => SelectedTab is ExportTab; + + // ---- Frames ---- + + public int FrameCount => Session.Content.Count; + + /// The frame on screen; the filmstrip, the charts and the frame table seek it. + public int CurrentIndex + { + get => _currentIndex; + set + { + var clamped = FrameCount == 0 ? 0 : int.Clamp(value, 0, FrameCount - 1); + if (!Set(ref _currentIndex, clamped)) return; + Frames.OnCurrentFrameChanged(); + foreach (var tab in Tabs.OfType()) tab.OnCurrentFrameChanged(); + foreach (var tab in Tabs.OfType()) tab.OnCurrentFrameChanged(); + UpdateInfo(); + RequestPreview(immediate: _player.IsEnabled); + } + } + + public IThumbnailSource Thumbnails { get => _thumbnails; private set => Set(ref _thumbnails, value); } + + /// Exposure steps (as received), warnings and keyframes above the filmstrip. + public IReadOnlyList Markers { get => _markers; private set => Set(ref _markers, value); } + + // ---- Preview ---- + + public ImageSource? PreviewImage { get => _previewImage; private set => Set(ref _previewImage, value); } + + public ImageSource? OriginalImage { get => _originalImage; private set => Set(ref _originalImage, value); } + + public bool IsCompare { get => _isCompare; set => Set(ref _isCompare, value); } + + public bool ShowVectors + { + get => _showVectors; + set + { + if (Set(ref _showVectors, value)) RequestPreview(immediate: true); + } + } + + public bool ShowRegions + { + get => _showRegions; + set + { + if (Set(ref _showRegions, value)) RequestPreview(immediate: true); + } + } + + public bool ShowCropMask + { + get => _showCropMask; + set + { + if (Set(ref _showCropMask, value)) RequestPreview(immediate: true); + } + } + + public PreviewZoomMode ZoomMode + { + get => _zoomMode; + set + { + if (Set(ref _zoomMode, value)) OnPropertyChanged(nameof(IsActualSize)); + } + } + + /// The 1:1 tool (raw pixels). + public bool IsActualSize + { + get => _zoomMode == PreviewZoomMode.Actual; + set => ZoomMode = value ? PreviewZoomMode.Actual : PreviewZoomMode.Fit; + } + + public Rect CropRect { get => _cropRect; private set => Set(ref _cropRect, value); } + + public IReadOnlyList? RegionBoundary { get => _regionBoundary; private set => Set(ref _regionBoundary, value); } + + public IReadOnlyList? MotionVectors { get => _motionVectors; private set => Set(ref _motionVectors, value); } + + /// Gain on vector lengths so a pixel of motion stays visible. + public double VectorScale => 4; + + public string WipeLabel => Loc.L("Editor.Preview.Wipe"); + + /// Shot data (bottom-right pill): frame, time, exposure; on the Export tab output time and size. + public string? InfoText { get; private set; } + + /// Long edge of the preview picture in device pixels (the view reports its size). + public int PreviewEdge + { + get => _previewEdge; + set + { + var rounded = int.Clamp((value + 63) / 64 * 64, 256, 4096); + if (Set(ref _previewEdge, rounded)) RequestPreview(); + } + } + + // ---- Analysis, plan, jobs ---- + + /// The corrections of the current exposure settings, once prepared (target curves). + public RenderCorrections? Corrections { get => _correctionsValue; private set => Set(ref _correctionsValue, value); } + + /// What the project's export will produce (size, time, encoder, name). + public ExportPlan? Plan { get => _plan; private set => Set(ref _plan, value); } + + /// An analysis or render of this sequence is running: settings wait, viewing tools stay live. + public bool IsBusy => _jobs.Values.Any(j => j.State == JobState.Running); + + public bool IsEditable => !IsBusy; + + public string? BusyToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy") : null; + + public bool IsPlaying => _player.IsEnabled; + + public string PlayToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Play"); + + // ---- Render ---- + + public IReadOnlyList RenderChoices { get; } + + /// The export preset the Render button renders (choosing another one sets it). + public Choice? SelectedRenderChoice + { + get => RenderChoices.FirstOrDefault(c => string.Equals((string)c.Value, Plan?.Export.PresetId ?? EditorSettings.ExportPreset.Effective(Session.Project, null), + StringComparison.OrdinalIgnoreCase)); + set + { + if (value?.Value is not string id) return; + Session.Edit(p => p with { Export = p.Export with { Preset = p.Export.Preset.WithManual(id), Overrides = new ExportOverrides() } }); + } + } + + /// "Render · 4K archive". + public string RenderText => Loc.L("Editor.Render", Plan?.PresetName ?? string.Empty); + + public string RenderToolTip => Plan is { } plan && !plan.Setup.Encoder.IsReady && plan.Setup.Encoder.Notices.LastOrDefault() is { } notice + ? Loc.L(notice.Key, [.. notice.Args]) + : Loc.L("Tooltips.Editor.Render"); + + public bool CanRender => Plan is { NameError: null, Setup: { Encoder.IsReady: true, Plan.Frames.Count: > 0 } }; + + public ICommand BackCommand { get; } + public ICommand AnalyseCommand { get; } + public ICommand OptimiseAllCommand { get; } + public ICommand RenderCommand { get; } + public ICommand UndoCommand { get; } + public ICommand RedoCommand { get; } + public ICommand PlayCommand { get; } + public ICommand PreviewClipCommand { get; } + public ICommand StepBackCommand { get; } + public ICommand StepForwardCommand { get; } + public ICommand FitCommand { get; } + public ICommand ActualSizeCommand { get; } + + /// Exposure steps of the sequence: as received by the pixels when the deep analysis measured them, else from the metadata. + public static IReadOnlyList StepMarkers(SequenceContent content) + { + ArgumentNullException.ThrowIfNull(content); + if (content.Deep is { } deep) + { + return [.. deep.Exposure.Steps.Select(s => new TimelineMarker(s.Index, s.Received ? MarkerKind.ExposureStep : MarkerKind.Warning, + Loc.L(s.Received ? "Editor.Marker.Step" : "Editor.Marker.StepIgnored", Ev(s.MeasuredEv ?? s.ExpectedEv))))]; + } + return [.. content.Light.ExposureSteps.Select(s => new TimelineMarker(s.Index, MarkerKind.ExposureStep, Loc.L("Editor.Marker.Step", Ev(s.DeltaEv))))]; + } + + /// "Optimise section": the advisor's heavier decisions, reported in a toast (what changed, from what to what). + public void Optimise(AdvisorSection section) => Report(Session.Optimise(section)); + + /// Queues a render of the project's export (with its batch presets when ). + public async Task RenderAsync(JobPriority priority, bool batch) + { + var export = batch ? Session.Project.Export : Session.Project.Export with { Batch = [] }; + var request = Session.RenderRequest(export) with { Priority = priority }; + await Session.SubmitAsync(request); + Shell.Notify(Loc.L("Editor.Render.Queued"), request.Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); + } + + /// Loads the jobs of this sequence already queued or running (busy state). + public async Task AttachJobsAsync() + { + if (Shell.Services.Jobs is not { } jobs) return; + var page = await jobs.ListAsync(null, 200); + foreach (var job in page.Items) Track(job); + OnBusyChanged(); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) return; + _disposed = true; + _player.Stop(); + _preview.Dispose(); + _corrections.Dispose(); + _plans.Dispose(); + Session.ProjectChanged -= OnProjectChanged; + Session.ContentChanged -= OnContentChanged; + Session.SaveFailed -= OnSaveFailed; + if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged; + foreach (var tab in Tabs) tab.Dispose(); + base.Dispose(); + await Session.DisposeAsync(); + } + + public override void Dispose() => _ = DisposeAsync().AsTask(); + + // ---- Preview pipeline ---- + + private void RequestPreview(bool immediate = false) + { + if (_disposed || FrameCount == 0) return; + var framing = ShowCropMask || ShowRegions ? PreviewFraming.Source : PreviewFraming.Output; + var request = new PreviewRequest(CurrentIndex, Session.Project, PreviewEdge, framing, ShowVectors); + var version = ++_previewVersion; + _ = RunPreviewAsync(request, version, immediate); + } + + private async Task RunPreviewAsync(PreviewRequest request, int version, bool immediate) + { + var renderer = _renderer; + PreviewResult? result = null; + _previewBusy = true; + try + { + await _preview.Schedule(async token => + { + using var frame = await renderer.RenderAsync(request, renderer.Cached(request.Project) ?? renderer.Latest, token); + if (frame is not null) result = PreviewResult.From(frame); + }, immediate); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Warning("editor", $"Preview of frame {request.Index + 1} failed", ex); + } + finally + { + if (version == _previewVersion) _previewBusy = false; + } + if (result is not { } r || version != _previewVersion || _disposed) return; + PreviewImage = r.Corrected; + OriginalImage = r.Original; + CropRect = r.Crop; + RegionBoundary = ShowRegions ? r.Horizon : null; + MotionVectors = ShowVectors ? r.Vectors : null; + } + + private void RequestCorrections() + { + if (_disposed) return; + var renderer = _renderer; + var project = Session.Project; + if (renderer.Cached(project) is { } cached) + { + Corrections = cached; + NotifyCorrections(); + return; + } + _ = RunCorrectionsAsync(renderer, project); + } + + private async Task RunCorrectionsAsync(PreviewRenderer renderer, ProjectSettings project) + { + RenderCorrections? prepared = null; + try + { + await _corrections.Schedule(async token => prepared = await renderer.PrepareAsync(project, token)); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Warning("editor", "Preparing the preview corrections failed", ex); + } + if (prepared is null || _disposed || !ReferenceEquals(renderer, _renderer) || !ReferenceEquals(project, Session.Project)) return; + Corrections = prepared; + NotifyCorrections(); + RequestPreview(immediate: true); + } + + private void NotifyCorrections() + { + foreach (var tab in Tabs) tab.OnCorrectionsChanged(); + } + + private void RequestPlan() => _ = RunPlanAsync(Planner, Session.Project); + + private async Task RunPlanAsync(ExportPlanner planner, ProjectSettings project) + { + ExportPlan? plan = null; + try + { + await _plans.Schedule(_ => + { + plan = planner.Plan(project); + return Task.CompletedTask; + }); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or RenderException) + { + Log.Warning("editor", "Planning the export failed", ex); + } + if (_disposed || !ReferenceEquals(planner, Planner) || !ReferenceEquals(project, Session.Project)) return; + Plan = plan; + OnPropertyChanged(nameof(RenderText)); + OnPropertyChanged(nameof(RenderToolTip)); + OnPropertyChanged(nameof(SelectedRenderChoice)); + foreach (var tab in Tabs) tab.OnPlanChanged(); + UpdateInfo(); + CommandManager.InvalidateRequerySuggested(); + } + + // ---- Playback ---- + + private void TogglePlay(int limit) + { + if (_player.IsEnabled) + { + _player.Stop(); + } + else + { + if (CurrentIndex >= FrameCount - 1) CurrentIndex = 0; + _playLimit = limit; + var fps = double.Clamp(Plan?.Setup.Plan.FrameRate.Value ?? 24, 5, 30); + _player.Interval = TimeSpan.FromSeconds(1 / fps); + _player.Start(); + } + OnPropertyChanged(nameof(IsPlaying)); + OnPropertyChanged(nameof(PlayToolTip)); + } + + /// Next frame while playing; frames are skipped rather than queued when the preview is slower than the clock. + private void Advance() + { + if (_previewBusy) return; + if (CurrentIndex >= FrameCount - 1 || (_playLimit > 0 && --_playLimit == 0)) + { + TogglePlay(0); + return; + } + CurrentIndex++; + } + + /// Source frames that make ten seconds of video. + private int ClipFrames() + { + if (Plan is not { } plan || plan.Setup.Plan.DurationSeconds <= 0) return 240; + return int.Max(1, (int)(plan.Setup.Plan.IncludedFrames.Count * double.Min(1, 10 / plan.Setup.Plan.DurationSeconds))); + } + + // ---- Changes ---- + + private void OnProjectChanged() + { + foreach (var tab in Tabs) tab.Refresh(); + UpdateMarkers(); + RequestCorrections(); + RequestPlan(); + RequestPreview(); + CommandManager.InvalidateRequerySuggested(); + } + + private void OnContentChanged() + { + _renderer = new PreviewRenderer(Session.Content, Session.Source); + Planner = new ExportPlanner(Session.Content, _encoders, _host); + if (Thumbnails.Count != FrameCount) Thumbnails = new EditorThumbnails(Session.Source, FrameCount); + Corrections = null; + foreach (var tab in Tabs) tab.OnContentChanged(); + OnPropertyChanged(nameof(Summary)); + OnPropertyChanged(nameof(FrameCount)); + CurrentIndex = int.Min(CurrentIndex, int.Max(0, FrameCount - 1)); + UpdateMarkers(); + RequestCorrections(); + RequestPlan(); + RequestPreview(immediate: true); + } + + private void OnSaveFailed(Exception ex) => Shell.ReportError(ex); + + private void UpdateMarkers() + { + var content = Session.Content; + var markers = new List(StepMarkers(content)); + foreach (var finding in Session.Advice.Findings.Where(f => f.Severity >= FindingSeverity.Warning)) + { + var text = Loc.L(finding.Key, finding.Arguments); + markers.AddRange(finding.Frames.Take(64).Select(i => new TimelineMarker(i, finding.Severity == FindingSeverity.Error ? MarkerKind.Error : MarkerKind.Warning, text))); + } + markers.AddRange(Session.Project.Camera.Keyframes.Select(k => new TimelineMarker(k.Frame, MarkerKind.Keyframe, Loc.L("Editor.Marker.Keyframe")))); + if (!markers.SequenceEqual(Markers)) Markers = markers; + } + + private void UpdateInfo() + { + if (FrameCount == 0) + { + InfoText = null; + } + else if (IsExportTab && Plan is { } plan) + { + var settings = plan.Setup.Encoder.Settings; + var position = plan.Setup.Plan.DurationSeconds * CurrentIndex / double.Max(1, FrameCount - 1); + InfoText = string.Join(" · ", EditorText.Position(CurrentIndex, FrameCount), + Loc.L("Editor.Preview.OutputTime", Clock(position), Clock(plan.Setup.Plan.DurationSeconds)), + Loc.L("Editor.Preview.OutputSize", EditorText.Size(settings.Width, settings.Height))); + } + else + { + InfoText = EditorText.Shot(Session.Content.Frames[CurrentIndex], CurrentIndex, FrameCount); + } + OnPropertyChanged(nameof(InfoText)); + } + + private void OptimiseAll() => Report(Session.OptimiseAll()); + + private void Report(IReadOnlyList changes) + { + if (changes.Count == 0) + { + Shell.Notify(Loc.L("Editor.Optimise.Nothing")); + return; + } + var lines = changes.Select(c => Loc.L("Editor.Optimise.Change", ParameterLabel(c.Parameter), ValueText(c.Before), ValueText(c.After))); + Shell.Notify(Loc.Plural("Editor.Optimise.Done", changes.Count), string.Join(Environment.NewLine, lines)); + } + + private async Task AnalyseAsync() + { + await Session.SubmitAsync(Session.AnalysisRequest()); + Shell.Notify(Loc.L("Editor.Analyse.Queued"), Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); + } + + private void OnJobChanged(Job job) + { + if (!job.TargetIds.Contains(Session.Content.Sequence.Id) || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render)) return; + _dispatcher.BeginInvoke(() => + { + if (_disposed) return; + var wasActive = _jobs.ContainsKey(job.Id); + Track(job); + OnBusyChanged(); + if (wasActive && job.State == JobState.Done) _ = ReloadAsync(); + }); + } + + private void Track(Job job) + { + if (!job.TargetIds.Contains(Session.Content.Sequence.Id) || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render)) return; + if (job.State is JobState.Queued or JobState.Running) _jobs[job.Id] = job; + else _jobs.Remove(job.Id); + } + + private async Task ReloadAsync() + { + try + { + await Session.ReloadAsync(); + } + catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException) + { + Shell.ReportError(ex); + } + } + + private void OnBusyChanged() + { + OnPropertyChanged(nameof(IsBusy)); + OnPropertyChanged(nameof(IsEditable)); + OnPropertyChanged(nameof(BusyToolTip)); + CommandManager.InvalidateRequerySuggested(); + } + + private static string Clock(double seconds) + { + var t = TimeSpan.FromSeconds(double.Max(0, seconds)); + return ((int)t.TotalMinutes).ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture) + Loc.Culture.NumberFormat.NumberDecimalSeparator + + (t.Milliseconds / 100).ToString(Loc.Culture); + } + + private static string Ev(double ev) => ev.ToString("+0.0;−0.0;0.0", Loc.Culture); + + private static string ParameterLabel(string parameter) => parameter switch + { + AdvisorParameters.Hero => Loc.L("Editor.Frames.HeroLabel"), + AdvisorParameters.Excluded => Loc.L("Editor.Frames.ExcludedLabel"), + AdvisorParameters.TimingMode => Loc.L("Editor.Time.Mode"), + AdvisorParameters.FrameRate => Loc.L("Editor.Time.Rate"), + AdvisorParameters.FitToSeconds => Loc.L("Editor.Time.Fit"), + AdvisorParameters.Deflicker => Loc.L("Editor.Exposure.Deflicker"), + AdvisorParameters.DeflickerWindow => Loc.L("Editor.Exposure.Window"), + AdvisorParameters.DeflickerStrength => Loc.L("Editor.Exposure.Strength"), + AdvisorParameters.Regions => Loc.L("Editor.Exposure.Regions"), + AdvisorParameters.HolyGrail => Loc.L("Editor.Exposure.HolyGrail"), + AdvisorParameters.TransitionLength => Loc.L("Editor.Exposure.Transitions"), + AdvisorParameters.WhiteBalanceSmoothing => Loc.L("Editor.Exposure.WhiteBalance"), + AdvisorParameters.MotionBlur => Loc.L("Editor.Motion.Blur"), + AdvisorParameters.TargetShutterAngle => Loc.L("Editor.Motion.Shutter"), + AdvisorParameters.FlowQuality => Loc.L("Editor.Motion.Flow"), + AdvisorParameters.Stabilize => Loc.L("Editor.Motion.Stabilize"), + AdvisorParameters.StabilizeSmoothing => Loc.L("Editor.Motion.Smoothing"), + AdvisorParameters.Aspect => Loc.L("Editor.Camera.Aspect"), + AdvisorParameters.OffsetY => Loc.L("Editor.Camera.OffsetY"), + AdvisorParameters.ExportPreset => Loc.L("Editor.Export.Preset"), + AdvisorParameters.Resolution => Loc.L("Editor.Export.Resolution"), + _ => parameter, + }; + + private static string ValueText(object? value) => value switch + { + null => Loc.L("Editor.Value.None"), + bool b => Loc.L(b ? "Editor.Value.On" : "Editor.Value.Off"), + TimingMode m => Loc.L("Editor.Timing." + m), + RegionMode m => m == RegionMode.Off ? Loc.L("Editor.Value.Off") : Loc.L("Editor.Regions." + m), + FlowQualitySetting q => Loc.L("Editor.Flow." + q), + string id when ExportPresets.Find(id) is { } preset => Loc.L(preset.NameKey), + string text => text, + double d => d.ToString("0.##", Loc.Culture), + IEnumerable list => Loc.Plural("Editor.Value.Frames", list.Cast().LongCount()), + IFormattable f => f.ToString(null, Loc.Culture), + _ => value.ToString() ?? string.Empty, + }; + + /// A rendered preview as frozen bitmaps and overlays in picture pixels (built off the UI thread). + private sealed record PreviewResult(ImageSource Corrected, ImageSource Original, Rect Crop, IReadOnlyList Horizon, IReadOnlyList Vectors) + { + public static PreviewResult From(PreviewFrame frame) => new( + EditorImages.ToBitmap(frame.Corrected), + EditorImages.ToBitmap(frame.Original), + new Rect(frame.Crop.X, frame.Crop.Y, frame.Crop.Width, frame.Crop.Height), + [.. frame.Horizon.Select(p => new Point(p.X, p.Y))], + [.. frame.Vectors.Select(v => new MotionVector(v.X, v.Y, v.Dx, v.Dy))]); + } +} diff --git a/src/Titano.App/Editor/ExportPlanner.cs b/src/Titano.App/Editor/ExportPlanner.cs index 96630024..3ceb06ae 100644 --- a/src/Titano.App/Editor/ExportPlanner.cs +++ b/src/Titano.App/Editor/ExportPlanner.cs @@ -32,6 +32,9 @@ public sealed record ExportPlan(ResolvedExport Export, RenderSetup Setup, Export /// public sealed class ExportPlanner(SequenceContent content, IReadOnlyList encoders, EncoderHost host, ThroughputModel? model = null) { + /// Encoder providers of the machine that renders, in priority order. + public IReadOnlyList Encoders { get; } = encoders; + /// Sequence presets that fit the content, then every built-in export preset. public static IReadOnlyList Choices(IReadOnlyList presets, AdvisorResult advice) { @@ -69,7 +72,7 @@ public sealed class ExportPlanner(SequenceContent content, IReadOnlyListA 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; + + 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; + } +} diff --git a/src/Titano.App/Editor/ExposureTab.cs b/src/Titano.App/Editor/ExposureTab.cs new file mode 100644 index 00000000..54fce348 --- /dev/null +++ b/src/Titano.App/Editor/ExposureTab.cs @@ -0,0 +1,112 @@ +using Titano.Core.Advice; +using Titano.Core.Localization; +using Titano.Core.Project; +using Titano.Ui.Visuals; + +namespace Titano.App.Editor; + +/// +/// Exposure (BRIEF §12.3): deflicker, regions, holy-grail transitions and white balance; the chart shows the measured +/// luminance (Sun) against the target curve the corrections produce (Accent), the sky region (dashed) and the exposure +/// steps as received. +/// +public sealed class ExposureTab : EditorTab +{ + private IReadOnlyList _series = []; + private IReadOnlyList _legend = []; + private IReadOnlyList _markers = []; + private string? _summary; + + public ExposureTab(EditorViewModel editor) + : base(editor, "Exposure", AdvisorSection.Exposure) + { + var s = editor.Session; + string? NoDeflicker(ProjectSettings p) => EditorSettings.Deflicker.Effective(p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.DeflickerOff"); + string? NoHolyGrail(ProjectSettings p) => EditorSettings.HolyGrail.Effective(p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.HolyGrailOff"); + Rows = + [ + new AutoSwitchRow(s, EditorSettings.Deflicker, "Editor.Exposure.Deflicker", "Tooltips.Editor.Exposure.Deflicker"), + new AutoNumberRow(s, EditorSettings.DeflickerWindow, "Editor.Exposure.Window", "Tooltips.Editor.Exposure.Window", 5, 151, 2, "0", NoDeflicker), + new AutoNumberRow(s, EditorSettings.DeflickerStrength, "Editor.Exposure.Strength", "Tooltips.Editor.Exposure.Strength", 0, 1, 0.05, "0.00", NoDeflicker), + new AutoChoiceRow(s, EditorSettings.Regions, "Editor.Exposure.Regions", "Tooltips.Editor.Exposure.Regions", + [ + new Choice(RegionMode.Off, "Editor.Value.Off"), new Choice(RegionMode.Auto, "Editor.Regions.Auto"), + new Choice(RegionMode.Horizon, "Editor.Regions.Horizon"), new Choice(RegionMode.Luminance, "Editor.Regions.Luminance"), + ], NoDeflicker), + new AutoSwitchRow(s, EditorSettings.HolyGrail, "Editor.Exposure.HolyGrail", "Tooltips.Editor.Exposure.HolyGrail"), + new AutoNumberRow(s, EditorSettings.TransitionLength, "Editor.Exposure.Transitions", "Tooltips.Editor.Exposure.Transitions", 0, 120, 1, "0", NoHolyGrail), + new AutoSwitchRow(s, EditorSettings.WhiteBalance, "Editor.Exposure.WhiteBalance", "Tooltips.Editor.Exposure.WhiteBalance"), + new InfoRow("Editor.Exposure.Temperature", "Tooltips.Editor.Exposure.Temperature", Temperature), + new NumberRow(s, "Editor.Exposure.Offset", "Tooltips.Editor.Exposure.Offset", -3, 3, 0.1, p => p.Exposure.ExposureOffsetEv, + (p, v) => p with { Exposure = p.Exposure with { ExposureOffsetEv = v } }, v => Loc.L("Editor.Value.Ev", v.ToString("+0.0;−0.0;0.0", Loc.Culture))), + ]; + Refresh(); + BuildChart(); + } + + public IReadOnlyList Series { get => _series; private set => Set(ref _series, value); } + + public IReadOnlyList Legend { get => _legend; private set => Set(ref _legend, value); } + + public IReadOnlyList Markers { get => _markers; private set => Set(ref _markers, value); } + + /// "flicker −67 % · max step 0.21 EV". + public string? Summary { get => _summary; private set => Set(ref _summary, value); } + + public Func YFormatter { get; } = v => v.ToString("0.0", Loc.Culture); + + public override void OnContentChanged() + { + base.OnContentChanged(); + BuildChart(); + } + + public override void OnCorrectionsChanged() => BuildChart(); + + private (string?, string?) Temperature() + { + if (Editor.Session.Content.Deep is not { } deep) return (null, Loc.L("Tooltips.Editor.NotApplicable.NeedsAnalysis")); + if (deep.WhiteBalance is { KelvinLow: { } low, KelvinHigh: { } high }) + return (Loc.L("Editor.Value.Kelvin", double.Round(low, -1).ToString("N0", Loc.Culture), double.Round(high, -1).ToString("N0", Loc.Culture)), null); + return (null, Loc.L("Tooltips.Editor.NotApplicable.Kelvin")); + } + + private void BuildChart() + { + var content = Editor.Session.Content; + var n = content.Count; + var corrections = Editor.Corrections is { } c && c.FrameCount == n ? c : null; + double[] measured = corrections?.MeasuredLogLuminance is { } m && m.Any(double.IsFinite) + ? m + : content.Deep is { } deep ? [.. deep.Frames.LogLuminance.Select(v => v ?? double.NaN)] : [.. content.Frames.Select(f => f.MeanLogLuminance ?? double.NaN)]; + var series = new List { new(Loc.L("Editor.Chart.Measured"), measured, "Brush.Sun") }; + var legend = new List { new(Loc.L("Editor.Chart.Measured"), "Brush.Sun") }; + if (corrections is not null && measured.Any(double.IsFinite)) + { + series.Add(new ChartSeries(Loc.L("Editor.Chart.Target"), corrections.TargetLogLuminance(), "Brush.Accent") { Thickness = 2 }); + legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Target"), "Brush.Accent")); + } + if (content.Deep is { Regions: not null } withSky && withSky.Frames.SkyLogLuminance.Any(v => v is not null)) + { + series.Add(new ChartSeries(Loc.L("Editor.Chart.Sky"), withSky.Frames.SkyLogLuminance.Select(v => v ?? double.NaN).ToArray(), "Brush.Region") + { Dash = LineDash.Dashed }); + legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Sky"), "Brush.Region", LegendSwatch.DashedLine)); + } + var markers = EditorViewModel.StepMarkers(content); + if (markers.Count > 0) legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Steps"), "Brush.Sun", LegendSwatch.Triangle)); + Series = series; + Legend = legend; + Markers = markers; + Summary = SummaryOf(corrections); + } + + private static string? SummaryOf(Core.Render.RenderCorrections? corrections) + { + if (corrections is null) return null; + var parts = new List(); + if (corrections.Report.Deflicker is { FlickerBefore: > 0 } d) + parts.Add(Loc.L("Editor.Exposure.FlickerChange", double.Round((d.FlickerAfter / d.FlickerBefore - 1) * 100).ToString("+0;−0;0", Loc.Culture))); + if (corrections.Report.MaxTargetStepEv is { } step) parts.Add(Loc.L("Editor.Exposure.MaxStep", step.ToString("0.00", Loc.Culture))); + return parts.Count == 0 ? null : string.Join(" · ", parts); + } +} diff --git a/src/Titano.App/Editor/FramesTab.cs b/src/Titano.App/Editor/FramesTab.cs new file mode 100644 index 00000000..6bc8bb6d --- /dev/null +++ b/src/Titano.App/Editor/FramesTab.cs @@ -0,0 +1,199 @@ +using System.Windows.Input; +using Titano.Core.Advice; +using Titano.Core.Analysis; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Ui.Controls; +using Titano.Ui.Mvvm; + +namespace Titano.App.Editor; + +/// One frame of the Frames table; texts are formatted when shown (the table is virtualised). +public sealed class FrameRow(FramesTab owner, Frame frame, int index) : ObservableObject +{ + /// Archive flags named in the table (the others are internal or shown elsewhere). + private static readonly FrameFlags[] ShownFlags = + [FrameFlags.Missing, FrameFlags.Corrupt, FrameFlags.Duplicate, FrameFlags.Undecodable, FrameFlags.Black, FrameFlags.White]; + + public int Index { get; } = index; + + public string Number => (Index + 1).ToString("D4", Loc.Culture); + + public string Time => frame.CapturedAt?.ToString("T", Loc.Culture) ?? string.Empty; + + public string Exposure => frame.ExposureTime is > 0 and var t ? EditorText.Shutter(t) : string.Empty; + + public string Iso => frame.Iso?.ToString(Loc.Culture) ?? string.Empty; + + public string Aperture => frame.FNumber is > 0 and var f ? Loc.L("Editor.Shot.Aperture", f.ToString("0.#", Loc.Culture)) : string.Empty; + + public string Size => frame.Width > 0 ? EditorText.Size(frame.Width, frame.Height) : string.Empty; + + /// Decode tier: the format, and "preview" when only the embedded preview decodes. + public string Tier => (frame.Flags & FrameFlags.PreviewOnly) != 0 ? Loc.L("Editor.Frames.PreviewOnly", frame.Format) : frame.Format.ToString(); + + /// "Excluded · black", the project's exclusion first, then the archive's flags. + public string Flags + { + get + { + var parts = new List(); + if (IsExcluded) parts.Add(Loc.L("Editor.Frames.Excluded")); + if (IsHero) parts.Add(Loc.L("Editor.Frames.Hero")); + foreach (var flag in ShownFlags) + { + if ((frame.Flags & flag) != 0) parts.Add(Loc.L("Editor.Frames.Flag." + flag)); + } + return string.Join(" · ", parts); + } + } + + public bool IsExcluded => owner.IsExcluded(Index); + + public bool IsHero => owner.HeroIndex == Index; + + public string ExcludeText => Loc.L(IsExcluded ? "Editor.Frames.Include" : "Editor.Frames.Exclude"); + + public string ExcludeToolTip => Loc.L(IsExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude"); + + /// The project's exclusions or hero changed. + public void Refresh() + { + OnPropertyChanged(nameof(IsExcluded)); + OnPropertyChanged(nameof(IsHero)); + OnPropertyChanged(nameof(Flags)); + OnPropertyChanged(nameof(ExcludeText)); + OnPropertyChanged(nameof(ExcludeToolTip)); + } + +} + +/// A finding of the analyses with the frame to jump to. +public sealed record FindingItem(StatusKind Kind, string Text, int? Frame); + +/// +/// Frames (BRIEF §12.3): the virtualised frame table (index, time, exposure, ISO, aperture, size, tier, flags) with +/// exclude/include and hero, and the warnings of the analyses; Optimise adds the advised exclusions and hero. +/// +public sealed class FramesTab : EditorTab +{ + private HashSet _excluded = []; + private int? _hero; + private IReadOnlyList _frames = []; + private IReadOnlyList _findings = []; + private FrameRow? _selected; + + public FramesTab(EditorViewModel editor) + : base(editor, "Frames", AdvisorSection.Frames) + { + ToggleExcludeCommand = new RelayCommand(p => ToggleExcluded(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsBusy); + SetHeroCommand = new RelayCommand(p => Editor.Session.SetHero(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsBusy); + SeekCommand = new RelayCommand(p => + { + if (p is FindingItem { Frame: { } frame }) Editor.CurrentIndex = frame; + }); + Load(); + } + + public IReadOnlyList Frames { get => _frames; private set => Set(ref _frames, value); } + + public IReadOnlyList Findings { get => _findings; private set => Set(ref _findings, value); } + + /// The row of the current frame (selecting a row seeks the preview). + public FrameRow? Selected + { + get => _selected; + set + { + if (!Set(ref _selected, value) || value is null) return; + Editor.CurrentIndex = value.Index; + } + } + + public int? HeroIndex => _hero; + + /// "Frame 0413", or "Not set". + public string HeroText => _hero is { } h ? Loc.L("Editor.Frames.HeroValue", (h + 1).ToString("D4", Loc.Culture)) : Loc.L("Editor.Frames.HeroNone"); + + /// "12 frames", "None". + public string ExcludedText => _excluded.Count > 0 ? Loc.Plural("Editor.Value.Frames", _excluded.Count) : Loc.L("Editor.Frames.ExcludedNone"); + + public bool IsCurrentExcluded => IsExcluded(Editor.CurrentIndex); + + public string CurrentExcludeText => Loc.L(IsCurrentExcluded ? "Editor.Frames.IncludeFrame" : "Editor.Frames.ExcludeFrame"); + + public string CurrentExcludeToolTip => Loc.L(IsCurrentExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude"); + + public override bool CanReset => false; + + public ICommand ToggleExcludeCommand { get; } + + public ICommand SetHeroCommand { get; } + + public ICommand SeekCommand { get; } + + public bool IsExcluded(int index) => _excluded.Contains(index); + + public override void Refresh() + { + base.Refresh(); + var project = Editor.Session.Project; + var excluded = project.ExcludedFrames.ToHashSet(); + if (excluded.SetEquals(_excluded) && project.HeroFrame == _hero) return; + var changed = new HashSet(excluded); + changed.SymmetricExceptWith(_excluded); + if (_hero is { } oldHero) changed.Add(oldHero); + if (project.HeroFrame is { } newHero) changed.Add(newHero); + _excluded = excluded; + _hero = project.HeroFrame; + foreach (var index in changed) + { + if ((uint)index < (uint)Frames.Count) Frames[index].Refresh(); + } + OnPropertyChanged(nameof(HeroText)); + OnPropertyChanged(nameof(ExcludedText)); + OnCurrentFrameChanged(); + } + + public override void OnContentChanged() + { + Load(); + base.OnContentChanged(); + } + + public void OnCurrentFrameChanged() + { + var index = Editor.CurrentIndex; + if ((uint)index < (uint)Frames.Count && !ReferenceEquals(_selected, Frames[index])) + { + _selected = Frames[index]; + OnPropertyChanged(nameof(Selected)); + } + OnPropertyChanged(nameof(IsCurrentExcluded)); + OnPropertyChanged(nameof(CurrentExcludeText)); + OnPropertyChanged(nameof(CurrentExcludeToolTip)); + } + + private void Load() + { + var content = Editor.Session.Content; + _excluded = Editor.Session.Project.ExcludedFrames.ToHashSet(); + _hero = Editor.Session.Project.HeroFrame; + Frames = [.. content.Frames.Select((f, i) => new FrameRow(this, f, i))]; + Findings = [.. Editor.Session.Advice.Findings.OrderByDescending(f => f.Severity).Select(ToItem)]; + _selected = null; + OnCurrentFrameChanged(); + } + + private static FindingItem ToItem(Finding finding) => new( + finding.Severity switch + { + FindingSeverity.Error => StatusKind.Error, + FindingSeverity.Warning => StatusKind.Warning, + _ => StatusKind.NotAnalysed, + }, + Loc.L(finding.Key, finding.Arguments), + finding.Frames.Count > 0 ? finding.Frames[0] : null); + + private void ToggleExcluded(int index) => Editor.Session.SetExcluded([index], !IsExcluded(index)); +} diff --git a/src/Titano.App/Editor/LocalSequenceSource.cs b/src/Titano.App/Editor/LocalSequenceSource.cs index ddbedea3..d9065b5e 100644 --- a/src/Titano.App/Editor/LocalSequenceSource.cs +++ b/src/Titano.App/Editor/LocalSequenceSource.cs @@ -70,7 +70,9 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag { try { - return decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose), cancellationToken)?.Pixels; + // Thumbnails take an embedded preview when it is large enough (no RAW development for a filmstrip cell). + var request = new DecodeRequest(file, maxLongEdge, purpose, ForcePreview: purpose == DecodePurpose.Thumbnail); + return decoder.Decode(request, cancellationToken)?.Pixels; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { diff --git a/src/Titano.App/Editor/MotionTab.cs b/src/Titano.App/Editor/MotionTab.cs new file mode 100644 index 00000000..57f697e2 --- /dev/null +++ b/src/Titano.App/Editor/MotionTab.cs @@ -0,0 +1,159 @@ +using Titano.Core.Advice; +using Titano.Core.Localization; +using Titano.Core.Project; +using Titano.Ui.Visuals; + +namespace Titano.App.Editor; + +/// Motion (BRIEF §12.3): motion blur, flow quality and stabilisation, with the measured camera path (shake) chart. +public sealed class MotionTab : EditorTab +{ + private IReadOnlyList _series = []; + private IReadOnlyList _legend = []; + private string? _summary; + + public MotionTab(EditorViewModel editor) + : base(editor, "Motion", AdvisorSection.Motion) + { + var s = editor.Session; + string? NoBlur(ProjectSettings p) => EditorSettings.MotionBlur.Effective(p, null) ? null : Loc.L("Tooltips.Editor.NotApplicable.BlurOff"); + string? NoFlow(ProjectSettings p) => + EditorSettings.MotionBlur.Effective(p, null) || EditorSettings.TimingMode.Effective(p, null) == TimingMode.Interpolated + ? null + : Loc.L("Tooltips.Editor.NotApplicable.NoFlow"); + string? NoStabilize(ProjectSettings p) => EditorSettings.Stabilize.Effective(p, null) ? null : Loc.L("Tooltips.Editor.NotApplicable.StabilizeOff"); + Rows = + [ + new AutoSwitchRow(s, EditorSettings.MotionBlur, "Editor.Motion.Blur", "Tooltips.Editor.Motion.Blur"), + new AutoNumberRow(s, EditorSettings.ShutterAngle, "Editor.Motion.Shutter", "Tooltips.Editor.Motion.Shutter", 0, 360, 15, "0", NoBlur), + new AutoChoiceRow(s, EditorSettings.FlowQuality, "Editor.Motion.Flow", "Tooltips.Editor.Motion.Flow", + [ + new Choice(FlowQualitySetting.Draft, "Editor.Flow.Draft"), new Choice(FlowQualitySetting.Balanced, "Editor.Flow.Balanced"), + new Choice(FlowQualitySetting.Best, "Editor.Flow.Best"), + ], NoFlow), + new AutoSwitchRow(s, EditorSettings.Stabilize, "Editor.Motion.Stabilize", "Tooltips.Editor.Motion.Stabilize"), + new AutoNumberRow(s, EditorSettings.StabilizeSmoothing, "Editor.Motion.Smoothing", "Tooltips.Editor.Motion.Smoothing", 2, 60, 1, "0", NoStabilize), + ]; + Refresh(); + BuildChart(); + } + + public IReadOnlyList Series { get => _series; private set => Set(ref _series, value); } + + public IReadOnlyList Legend { get => _legend; private set => Set(ref _legend, value); } + + /// "shake 0.42 px · crop 1.8 %". + public string? Summary { get => _summary; private set => Set(ref _summary, value); } + + public Func YFormatter { get; } = v => Loc.L("Editor.Value.Pixels", v.ToString("0.#", Loc.Culture)); + + public override void OnContentChanged() + { + base.OnContentChanged(); + BuildChart(); + } + + /// The camera path: per-frame content shifts accumulated from the first frame (gaps hold the last position). + private void BuildChart() + { + if (Editor.Session.Content.Deep is not { } deep) + { + Series = []; + Legend = []; + Summary = Loc.L("Editor.Chart.NotAnalysed"); + return; + } + var x = Accumulate(deep.Frames.ShiftX); + var y = Accumulate(deep.Frames.ShiftY); + Series = + [ + new ChartSeries(Loc.L("Editor.Chart.PathX"), x, "Brush.Accent"), + new ChartSeries(Loc.L("Editor.Chart.PathY"), y, "Brush.TextMuted") { Dash = LineDash.Dashed }, + ]; + Legend = [new ChartLegendItem(Loc.L("Editor.Chart.PathX"), "Brush.Accent"), new ChartLegendItem(Loc.L("Editor.Chart.PathY"), "Brush.TextMuted", LegendSwatch.DashedLine)]; + var shake = deep.Shake; + var parts = new List + { + Loc.L("Editor.Motion.ShakeValue", shake.RmsPx.ToString("0.00", Loc.Culture)), + Loc.L("Editor.Motion.CropValue", (shake.CropCost * 100).ToString("0.0", Loc.Culture)), + }; + if (shake.PanDetected) parts.Add(Loc.L("Editor.Motion.PanValue", shake.PanPxPerFrame.ToString("0.0", Loc.Culture))); + Summary = string.Join(" · ", parts); + } + + private static double[] Accumulate(double?[] shifts) + { + var path = new double[shifts.Length]; + double position = 0; + for (var i = 0; i < shifts.Length; i++) + { + position += shifts[i] ?? 0; + path[i] = position; + } + return path; + } +} + +/// Stack (BRIEF §12.3): median, mean or star-trail stacking; the chart shows the star field and cloud measurements. +public sealed class StackTab : EditorTab +{ + private IReadOnlyList _series = []; + private IReadOnlyList _legend = []; + private string? _summary; + + public StackTab(EditorViewModel editor) + : base(editor, "Stack", AdvisorSection.Stack) + { + var s = editor.Session; + Rows = + [ + new ChoiceRow(s, "Editor.Stack.Mode", "Tooltips.Editor.Stack.Mode", + [ + new Choice(StackSetting.None, "Editor.Value.Off"), new Choice(StackSetting.Median, "Editor.Stack.Median"), + new Choice(StackSetting.Mean, "Editor.Stack.Mean"), new Choice(StackSetting.StarTrails, "Editor.Stack.StarTrails"), + ], + p => p.Stack.Mode, (p, v) => p with { Stack = p.Stack with { Mode = (StackSetting)v } }), + new NumberRow(s, "Editor.Stack.Length", "Tooltips.Editor.Stack.Length", 3, 199, 2, p => p.Stack.Length, + (p, v) => p with { Stack = p.Stack with { Length = (int)v } }, v => Loc.Plural("Editor.Value.Frames", (long)v), + p => p.Stack.Mode == StackSetting.None ? Loc.L("Tooltips.Editor.NotApplicable.StackOff") : null), + ]; + Refresh(); + BuildChart(); + } + + /// The advisor never stacks on its own (a temporal median erases moving stars). + public override bool CanOptimise => false; + + public IReadOnlyList Series { get => _series; private set => Set(ref _series, value); } + + public IReadOnlyList Legend { get => _legend; private set => Set(ref _legend, value); } + + public string? Summary { get => _summary; private set => Set(ref _summary, value); } + + public Func YFormatter { get; } = v => v.ToString("0.#", Loc.Culture); + + public override void OnContentChanged() + { + base.OnContentChanged(); + BuildChart(); + } + + private void BuildChart() + { + if (Editor.Session.Content.Deep is not { } deep) + { + Series = []; + Legend = []; + Summary = Loc.L("Editor.Chart.NotAnalysed"); + return; + } + Series = + [ + new ChartSeries(Loc.L("Editor.Chart.Stars"), deep.Frames.StarDensity.Select(v => v ?? double.NaN).ToArray(), "Brush.Accent"), + new ChartSeries(Loc.L("Editor.Chart.Clouds"), deep.Frames.CloudCoverage.Select(v => v is { } c ? c * 100 : double.NaN).ToArray(), "Brush.TextMuted") + { Dash = LineDash.Dashed }, + ]; + Legend = [new ChartLegendItem(Loc.L("Editor.Chart.Stars"), "Brush.Accent"), new ChartLegendItem(Loc.L("Editor.Chart.Clouds"), "Brush.TextMuted", LegendSwatch.DashedLine)]; + Summary = Loc.L(deep.Sky.StarField ? "Editor.Stack.StarField" : "Editor.Stack.NoStarField"); + } +} diff --git a/src/Titano.App/Editor/SettingRows.cs b/src/Titano.App/Editor/SettingRows.cs new file mode 100644 index 00000000..fb3d1a2e --- /dev/null +++ b/src/Titano.App/Editor/SettingRows.cs @@ -0,0 +1,393 @@ +using System.Numerics; +using System.Windows.Input; +using Titano.Core.Advice; +using Titano.Core.Localization; +using Titano.Core.Project; +using Titano.Ui.Mvvm; + +namespace Titano.App.Editor; + +/// One row of a section's settings column; re-reads the project after any change. +public abstract class SettingRow(string headerKey, string toolTipKey) : LocalizedViewModel +{ + private bool _refreshing; + + public string Header => Loc.L(headerKey); + + /// What the control does and what moving it the wrong way costs (BRIEF §12.3). + public string ToolTip => Loc.L(toolTipKey); + + public void Refresh() + { + _refreshing = true; + try + { + Read(); + } + finally + { + _refreshing = false; + } + } + + /// True while pushes values into the bindings (they must not edit the project back). + protected bool IsRefreshing => _refreshing; + + protected abstract void Read(); + + /// The tooltip of an Auto pill: the stored reason, else the advisor's current one, else why there is none. + protected static string Reason(EditorSession session, AutoSetting setting) + where T : notnull + { + var auto = setting.Get(session.Project); + if (auto.ReasonKey is { } key) return Advisor.Explain(key, auto.ReasonArgs); + return session.Advice.Find(setting.Id) is { } recommendation ? Advisor.Explain(recommendation) : Loc.L("Tooltips.Editor.Auto.Default"); + } +} + +/// +/// An Auto/manual slider (). Non-generic so the view can template it; the setting's +/// value type lives in . +/// +public abstract class AutoNumberRow(string headerKey, string toolTipKey, double minimum, double maximum, double step, string format) + : SettingRow(headerKey, toolTipKey) +{ + private double _value; + private bool _isAuto = true; + private double _autoValue; + private string? _autoReason; + private string? _notApplicableReason; + + public double Minimum { get; } = minimum; + public double Maximum { get; } = maximum; + public double Step { get; } = step; + public string Format { get; } = format; + + /// The slider value; the user moving it stores a manual value (one undo step per drag). + public double Value + { + get => _value; + set + { + if (!Set(ref _value, value) || IsRefreshing || _isAuto) return; + StoreManual(value); + } + } + + /// Touching the slider clears it (manual at the current value); the reset button sets it. + public bool IsAuto + { + get => _isAuto; + set + { + if (!Set(ref _isAuto, value) || IsRefreshing) return; + StoreAuto(value); + } + } + + public double AutoValue { get => _autoValue; protected set => Set(ref _autoValue, value); } + + public string? AutoReason { get => _autoReason; protected set => Set(ref _autoReason, value); } + + public bool IsApplicable => _notApplicableReason is null; + + public string? NotApplicableReason + { + get => _notApplicableReason; + protected set + { + if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable)); + } + } + + protected abstract void StoreManual(double value); + + /// True: back to the advice; false: the value in force becomes manual. + protected abstract void StoreAuto(bool auto); +} + +/// over an of . +public sealed class AutoNumberRow : AutoNumberRow + where T : struct, INumber +{ + private readonly EditorSession _session; + private readonly AutoSetting _setting; + private readonly Func? _notApplicable; + + /// Why the setting does nothing with the current project (shown as "n/a"); null when it applies. + public AutoNumberRow(EditorSession session, AutoSetting setting, string headerKey, string toolTipKey, double minimum, double maximum, double step, + string format, Func? notApplicable = null) + : base(headerKey, toolTipKey, minimum, maximum, step, format) + { + (_session, _setting, _notApplicable) = (session, setting, notApplicable); + Refresh(); + } + + protected override void StoreManual(double value) => _session.Edit(p => _setting.WithManual(p, Convert(value)), _setting.Id); + + protected override void StoreAuto(bool auto) => + _session.Edit(p => auto ? _setting.Reset(p) : _setting.WithManual(p, _setting.Effective(p, _session.Content.Deep)), _setting.Id); + + protected override void Read() + { + var project = _session.Project; + AutoValue = double.CreateChecked(_setting.AutoValue(project, _session.Content.Deep)); + IsAuto = _setting.IsAuto(project); + Value = double.CreateChecked(_setting.Effective(project, _session.Content.Deep)); + AutoReason = Reason(_session, _setting); + NotApplicableReason = _notApplicable?.Invoke(project); + } + + private static T Convert(double value) => typeof(T) == typeof(int) ? T.CreateChecked(double.Round(value)) : T.CreateChecked(value); +} + +/// An Auto/manual switch (module on/off): the pill shows the advisor's choice, the switch takes it over. +public sealed class AutoSwitchRow : SettingRow +{ + private readonly EditorSession _session; + private readonly AutoSetting _setting; + private bool _isOn; + private bool _isAuto; + private string _autoText = string.Empty; + private string? _autoReason; + + public AutoSwitchRow(EditorSession session, AutoSetting setting, string headerKey, string toolTipKey) + : base(headerKey, toolTipKey) + { + (_session, _setting) = (session, setting); + ResetCommand = new RelayCommand(() => _session.Edit(_setting.Reset)); + Refresh(); + } + + public bool IsOn + { + get => _isOn; + set + { + if (!Set(ref _isOn, value) || IsRefreshing) return; + _session.Edit(p => _setting.WithManual(p, value)); + } + } + + public bool IsAuto { get => _isAuto; private set => Set(ref _isAuto, value); } + + /// "Auto · On". + public string AutoText { get => _autoText; private set => Set(ref _autoText, value); } + + public string? AutoReason { get => _autoReason; private set => Set(ref _autoReason, value); } + + public ICommand ResetCommand { get; } + + protected override void Read() + { + var project = _session.Project; + IsOn = _setting.Effective(project, _session.Content.Deep); + IsAuto = _setting.IsAuto(project); + AutoText = Loc.L("Common.Auto") + " · " + Loc.L(IsOn ? "Editor.Value.On" : "Editor.Value.Off"); + AutoReason = Reason(_session, _setting); + } +} + +/// A labelled value of a choice list. +public sealed record Choice(object Value, string LabelKey, params object[] Args) +{ + public string Label => Loc.L(LabelKey, Args); +} + +/// An Auto/manual drop-down (regions, flow quality, timing mode, aspect, playback rate); non-generic for the view. +public abstract class AutoChoiceRow(string headerKey, string toolTipKey, IReadOnlyList options) : SettingRow(headerKey, toolTipKey) +{ + private Choice? _selected; + private bool _isAuto; + private string _autoText = string.Empty; + private string? _autoReason; + private string? _notApplicableReason; + + public IReadOnlyList Options { get; } = options; + + public Choice? Selected + { + get => _selected; + set + { + if (!Set(ref _selected, value) || IsRefreshing || value is null) return; + StoreManual(value.Value); + } + } + + public bool IsAuto { get => _isAuto; protected set => Set(ref _isAuto, value); } + + /// "Auto · horizon". + public string AutoText { get => _autoText; protected set => Set(ref _autoText, value); } + + public string? AutoReason { get => _autoReason; protected set => Set(ref _autoReason, value); } + + public bool IsApplicable => _notApplicableReason is null; + + public string? NotApplicableReason + { + get => _notApplicableReason; + protected set + { + if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable)); + } + } + + public abstract ICommand ResetCommand { get; } + + protected abstract void StoreManual(object value); +} + +/// over an of . +public sealed class AutoChoiceRow : AutoChoiceRow + where T : notnull +{ + private readonly EditorSession _session; + private readonly AutoSetting _setting; + private readonly Func? _notApplicable; + + public AutoChoiceRow(EditorSession session, AutoSetting setting, string headerKey, string toolTipKey, IReadOnlyList options, + Func? notApplicable = null) + : base(headerKey, toolTipKey, options) + { + (_session, _setting, _notApplicable) = (session, setting, notApplicable); + ResetCommand = new RelayCommand(() => _session.Edit(_setting.Reset)); + Refresh(); + } + + public override ICommand ResetCommand { get; } + + protected override void StoreManual(object value) + { + if (value is T chosen) _session.Edit(p => _setting.WithManual(p, chosen)); + } + + protected override void Read() + { + var project = _session.Project; + var value = _setting.Effective(project, _session.Content.Deep); + Selected = Options.FirstOrDefault(o => Equals(o.Value, value)); + IsAuto = _setting.IsAuto(project); + var auto = _setting.AutoValue(project, _session.Content.Deep); + AutoText = Loc.L("Common.Auto") + " · " + (Options.FirstOrDefault(o => Equals(o.Value, auto))?.Label ?? auto.ToString()); + AutoReason = Reason(_session, _setting); + NotApplicableReason = _notApplicable?.Invoke(project); + } +} + +/// A plain slider (no advice): exposure offset, placement, stack length, fit-to duration. +public sealed class NumberRow : SettingRow +{ + private readonly EditorSession _session; + private readonly Func _get; + private readonly Func _set; + private readonly Func _display; + private readonly Func? _notApplicable; + private readonly string _mergeKey; + private double _value; + private string _displayValue = string.Empty; + private string? _notApplicableReason; + + public NumberRow(EditorSession session, string headerKey, string toolTipKey, double minimum, double maximum, double step, + Func get, Func set, Func display, + Func? notApplicable = null) + : base(headerKey, toolTipKey) + { + (_session, _get, _set, _display, _notApplicable, _mergeKey) = (session, get, set, display, notApplicable, headerKey); + (Minimum, Maximum, Step) = (minimum, maximum, step); + Refresh(); + } + + public double Minimum { get; } + public double Maximum { get; } + public double Step { get; } + + public double Value + { + get => _value; + set + { + var snapped = Step > 0 ? double.Round(value / Step) * Step : value; + if (!Set(ref _value, snapped)) return; + DisplayValue = _display(snapped); + if (!IsRefreshing) _session.Edit(p => _set(p, snapped), _mergeKey); + } + } + + public string DisplayValue { get => _displayValue; private set => Set(ref _displayValue, value); } + + public bool IsApplicable => _notApplicableReason is null; + + public string? NotApplicableReason + { + get => _notApplicableReason; + private set + { + if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable)); + } + } + + protected override void Read() + { + Value = _get(_session.Project); + DisplayValue = _display(_value); + NotApplicableReason = _notApplicable?.Invoke(_session.Project); + } +} + +/// A plain drop-down (stacking mode). +public sealed class ChoiceRow : SettingRow +{ + private readonly EditorSession _session; + private readonly Func _get; + private readonly Func _set; + private Choice? _selected; + + public ChoiceRow(EditorSession session, string headerKey, string toolTipKey, IReadOnlyList options, Func get, + Func set) + : base(headerKey, toolTipKey) + { + (_session, _get, _set, Options) = (session, get, set, options); + Refresh(); + } + + public IReadOnlyList Options { get; } + + public Choice? Selected + { + get => _selected; + set + { + if (!Set(ref _selected, value) || IsRefreshing || value is null) return; + _session.Edit(p => _set(p, value.Value)); + } + } + + protected override void Read() + { + var current = _get(_session.Project); + Selected = Options.FirstOrDefault(o => Equals(o.Value, current)); + } +} + +/// A measured value shown read-only, "n/a" with the reason when there is none (colour temperature). +public sealed class InfoRow(string headerKey, string toolTipKey, Func<(string? Value, string? NotApplicableReason)> read) : SettingRow(headerKey, toolTipKey) +{ + private string? _value; + private string? _notApplicableReason; + + public string? Value { get => _value; private set => Set(ref _value, value); } + + public bool IsApplicable => _notApplicableReason is null; + + public string? NotApplicableReason + { + get => _notApplicableReason; + private set + { + if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable)); + } + } + + protected override void Read() => (Value, NotApplicableReason) = read(); +} diff --git a/src/Titano.App/Sections/SequenceViewModel.cs b/src/Titano.App/Sections/SequenceViewModel.cs index 7dcd5229..a6624b1a 100644 --- a/src/Titano.App/Sections/SequenceViewModel.cs +++ b/src/Titano.App/Sections/SequenceViewModel.cs @@ -1,12 +1,129 @@ +using System.ComponentModel; +using System.IO; using System.Windows.Input; +using Titano.App.Editor; using Titano.App.Shell; +using Titano.Core.Diagnostics; +using Titano.Core.Export; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Localization; +using Titano.Data.Archiving; using Titano.Ui.Mvvm; namespace Titano.App.Sections; -/// Sequence editor (BRIEF §12.3). -public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence") +/// +/// The Sequence section (BRIEF §12.3): opens the sequence the Library (or Jobs) chose into an +/// and closes the previous one after saving it; without a sequence it shows the empty state. +/// +public sealed class SequenceViewModel : SectionViewModel { - public ShellViewModel Shell { get; } = shell; - public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library)); + private EditorViewModel? _editor; + private Guid? _openId; + private bool _isLoading; + private Task _switch = Task.CompletedTask; + + public SequenceViewModel(ShellViewModel shell) + : base(SectionKey.Sequence, "Icon.Sequence") + { + Shell = shell; + OpenLibraryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library)); + shell.PropertyChanged += OnShellChanged; + } + + public ShellViewModel Shell { get; } + + public ICommand OpenLibraryCommand { get; } + + /// The open sequence; null shows the empty state. + public EditorViewModel? Editor + { + get => _editor; + private set + { + if (!Set(ref _editor, value)) return; + OnPropertyChanged(nameof(IsEmpty)); + OnPropertyChanged(nameof(Title)); + } + } + + public bool IsLoading { get => _isLoading; private set => Set(ref _isLoading, value); } + + public bool IsEmpty => _editor is null && !_isLoading; + + /// "Titano — Harbour sunset" while a sequence is open. + public override string Title => _editor?.Title ?? Label; + + /// Opens (the editor of another sequence is saved and closed first). + public Task OpenAsync(Guid sequenceId) + { + _switch = SwitchAsync(_switch, sequenceId); + return _switch; + } + + /// Saves and closes the open sequence. + public async Task CloseAsync() + { + await _switch; + if (Editor is not { } editor) return; + Editor = null; + _openId = null; + await editor.DisposeAsync(); + } + + public override void Dispose() + { + Shell.PropertyChanged -= OnShellChanged; + Editor?.Dispose(); + base.Dispose(); + } + + protected override void OnActivated() + { + if (Shell.CurrentSequenceId is { } id && id != _openId) _ = OpenAsync(id); + } + + private void OnShellChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId) && IsSelected) OnActivated(); + } + + private async Task SwitchAsync(Task previous, Guid sequenceId) + { + await previous; + if (sequenceId == _openId) return; + var services = Shell.Services; + IsLoading = true; + OnPropertyChanged(nameof(IsEmpty)); + try + { + if (Editor is { } old) + { + Editor = null; + await old.DisposeAsync(); + } + _openId = sequenceId; + if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); + var processing = services.Processing?.Options; + var source = new LocalSequenceSource(db, sequenceId, processing?.Archive.Decoder ?? DecoderFactory.CreateClient(null), services.Engine, + processing?.Archive); + var content = await source.LoadAsync(CancellationToken.None); + var encoders = processing?.Encoders ?? []; + var session = new EditorSession(source, content, [.. encoders.SelectMany(e => e.Capabilities)]); + var editor = new EditorViewModel(Shell, session, encoders, processing?.Host ?? EncoderHost.Client); + Editor = editor; + await editor.AttachJobsAsync(); + } + catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + _openId = null; + Log.Warning("editor", $"Sequence {sequenceId} could not be opened", ex); + Shell.ReportError(ex); + } + finally + { + IsLoading = false; + OnPropertyChanged(nameof(IsEmpty)); + } + } } diff --git a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs index 055251d4..af26f11a 100644 --- a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs @@ -184,6 +184,28 @@ public sealed class EditorSessionTests } } + [Test] + public async Task ASequencePresetKeepsTheUsersFramesAndNaming() + { + var (session, _) = Open(); + await using (session) + { + session.SetExcluded([1, 2], excluded: true); + session.SetHero(9); + session.Edit(p => p with { Export = p.Export with { NameTemplate = "{title}", Overrides = new ExportOverrides { Width = 640 } } }); + var preset = session.Presets.First(p => p.Id == "social-vertical"); + Assert.True(session.ApplyPreset(preset)); + Assert.Equal("9:16", session.Project.Camera.Aspect.Manual); + Assert.Equal("vertical-1080x1920", session.Project.Export.Preset.Manual); + Assert.Null(session.Project.Export.Overrides.Width, "the preset's own values"); + Assert.SequenceEqual([1, 2], session.Project.ExcludedFrames); + Assert.Equal(9, session.Project.HeroFrame); + Assert.Equal("{title}", session.Project.Export.NameTemplate); + Assert.True(session.Undo()); + Assert.Equal(640, session.Project.Export.Overrides.Width); + } + } + [Test] public async Task ReloadBringsNewAnalysisAndKeepsUserValues() { From 37703b13f9f254f42ab92f0537078649a266b8bb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 17:26:54 +0000 Subject: [PATCH 3/9] feat(app): sequence editor view with preview tools, filmstrip, section tabs and Export panel Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Editor.resx | 196 ++++++++ i18n/en/Export.resx | 16 + i18n/en/Tooltips.resx | 91 ++++ i18n/it/Editor.it.resx | 175 +++++++ i18n/it/Export.it.resx | 2 + i18n/it/Tooltips.it.resx | 91 ++++ src/Titano.App/Editor/CameraTab.cs | 17 +- src/Titano.App/Editor/CurveCommit.cs | 28 ++ src/Titano.App/Editor/EditorMeasures.xaml | 178 ++++++++ src/Titano.App/Editor/EditorPanels.xaml | 427 ++++++++++++++++++ src/Titano.App/Editor/EditorStyles.xaml | 113 +++++ src/Titano.App/Editor/FramesTab.cs | 11 +- src/Titano.App/Editor/FullScreenPreview.xaml | 30 ++ .../Editor/FullScreenPreview.xaml.cs | 55 +++ src/Titano.App/Sections/SequenceView.xaml | 144 +++++- src/Titano.App/Sections/SequenceView.xaml.cs | 40 ++ 16 files changed, 1606 insertions(+), 8 deletions(-) create mode 100644 src/Titano.App/Editor/CurveCommit.cs create mode 100644 src/Titano.App/Editor/EditorMeasures.xaml create mode 100644 src/Titano.App/Editor/EditorPanels.xaml create mode 100644 src/Titano.App/Editor/EditorStyles.xaml create mode 100644 src/Titano.App/Editor/FullScreenPreview.xaml create mode 100644 src/Titano.App/Editor/FullScreenPreview.xaml.cs diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index c212191c..243ae6ed 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -4,8 +4,204 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Analyse + Analysis queued + {0}invariant + Source + Back + Add keyframe + Aspect + Horizontal centre + Vertical centre + Keyframes + Keyframe {0} of {1} · {2} + {0} keyframe + {0} keyframes + Horizontal placement + Vertical placement + Remove keyframe + Zoom + cloud cover % + measured luminance + Not analysed yet + horizontal path + vertical path + sky region + stars per Mpx + exposure steps as received + target curve Pick a sequence in the Library This sequence is no longer in the archive.long Jobs cannot run until the archive index is open.long The settings of this sequence cannot be read.long + about {0} + Add to queue + Batch… + {0} bppinvariant + Choose folder… + Codec + Colour + Container + Rec.709 {0}-bitinvariant + Encoder + Auto + File name + {0} fpsinvariant + Frame rate + hardware + Height + Previous renders: {0} · last {1}long + Previous renders: {0} · last {1}long + history + In batch + {0} Mb/sinvariant + No renders yet + Output · {0} + Export preset + Quality + Quality {0} + Recommended + Render now + Resolution + Result + Save to + Sequence exports/ + Estimated size + software + Estimated time + No encoder here + Width + Deflicker + flicker {0} % + Holy grail + max step {0} EV + Exposure offset + Regions + Strength + Colour temperature + Transitions + White balance smoothing + Deflicker window + Filmstrip + Balanced + Best + Draft + finvariant + Exposure + Flags + ISOinvariant + #invariant + Size + Decode + Time + Exclude + Exclude frame + excluded + Excluded + None + black + corrupt + duplicate + missing + unreadable + white + hero + Hero frame + Not set + Frame {0} + Include + Include frame + No warnings + {0} preview + Set hero + Warnings + Opening sequence + Keyframe + Exposure step {0} EV + Step {0} EV not received + Motion blur + crop {0} % + Flow quality + pan {0} px/frame + shake {0} px + Shutter angle + Path smoothing + Stabilise + {0}: {1} → {2}invariant + {0} setting changed + {0} settings changed + Nothing to change + Optimise all + Optimise section + Preview + 1:1invariant + Preview 10 s + Compare + Crop mask + Exit full screen + Full screen + output {0} + {0} of {1} + Play + Regions + Shot data + Vectors + original | corrected + Auto + Horizon + Luminance + Render · {0} + Render queued + Render + Reset + Back to Auto + Sections + f/{0}invariant + {0} mminvariant + ISO {0}invariant + {0} sinvariant + Length + Mean + Median + Stacking + No star field found + Star field found + Star trails + {0:N0} frame + {0:N0} frames + {0} s interval + {0} warning + {0} warnings + Camera + Export + Exposure + Frames + Motion + Stack + Time + Speed curve + Fit to duration + Timing + output {0} % + {0:N0} frame → {1} · {2} fpslong + {0:N0} frames → {1} · {2} fpslong + Playback rate + source {0} % + Adaptive + Constant + Interpolated + Remapped + Centred + {0} EVinvariant + {0} fpsinvariant + {0:N0} frame + {0:N0} frames + {0}–{1} Kinvariant + None + {0}invariant + Off + On + {0} pxinvariant + {0}invariant + {0}×invariant diff --git a/i18n/en/Export.resx b/i18n/en/Export.resx index 3477a2d4..d2aac8a4 100644 --- a/i18n/en/Export.resx +++ b/i18n/en/Export.resx @@ -4,6 +4,22 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + APNGinvariant + AV1invariant + GIFinvariant + H.264 Highinvariant + HEVC Maininvariant + HEVC Main10invariant + JPEGinvariant + Linear DNG + MJPEGinvariant + PNGinvariant + TIFF 16-bitinvariant + APNGinvariant + AVIinvariant + GIFinvariant + Image sequence + MP4invariant {0}-bit output is not available with this encoder; encoding at {1}-bit.long; {0} requested bit depth; {1} bit depth used Bit rate capped at {1} bit/s, the maximum of level {0}.long; {0} codec level name; {1} maximum bit rate in bit/s No {0} encoder on this PC; H.264 is used instead.long; {0} codec name diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 7ca6cbe4..4709ec9f 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -15,6 +15,97 @@ Dismiss Open the folder with the log files Return to the advisor's value + Read every frame again and refresh the analysis; runs as a background job + Auto: no advice yet, the engine’s default applies; Analyse lets the advisor decide + Back to Library + An analysis or render of this sequence is running; settings wait until it ends + Add a keyframe at the current frame + Output aspect ratio; a preset with a fixed size uses its own + Horizontal centre of the selected keyframe’s view + Vertical centre of the selected keyframe’s view + Virtual-camera keyframes: zoom and framing at chosen frames, eased in between + Moves the crop left or right inside the frame + Moves the crop up or down inside the frame + Remove the selected keyframe + Zoom of the selected keyframe; 1 shows the whole crop, more zooms in and softens + Add this render to the queue and keep editing + Apply this sequence preset to every section · {0} + Queue every ticked preset as one job; the sequence is prepared once + Average bit rate; more keeps detail and gradients, files grow + Video or image codec; 10-bit HEVC keeps sky gradients clean + Rec.709 colour; 10-bit avoids banding in skies, HDR is not offered + MP4, AVI, GIF, APNG or a folder of images; the codec list follows + Encoder on this PC; Auto prefers hardware + Where renders go: {0} + Frames per second of the video file + Auto: the preset’s {0} fps + Return to the preset’s frame rate + Output height in pixels; empty follows the width · Enter applies, Esc reverts + Open Jobs to see the renders of this sequence + Include this preset when Batch queues the render + Tokens: {date} {title} {preset} {codec} {width} {height} {fps} · Enter applies, Esc reverts + Render with {0}; editing a value makes it Custom + Image quality; 95 looks lossless, lower makes smaller files + Advisor pick: {0} + Enter a size between 16 and 16384 pixels + Output width in pixels; empty uses the preset or the source · Enter applies, Esc reverts + Removes frame-to-frame brightness flicker; off keeps the camera’s own exposure + Turns ISO, shutter and aperture steps into smooth ramps; off keeps the jumps + Brightens or darkens the whole video after correction, in stops + Sky and landscape get their own curve; off treats the frame as one + How much of the measured flicker is removed; 1.0 removes it all + Colour temperature range measured over the sequence + Frames over which each ISO, shutter or aperture step is spread; 0 keeps the steps + Smooths the colour ratios so auto white balance stops flickering while the sunset drift stays + Frames used to estimate the flicker-free curve; too short leaves flicker, too long flattens real light changes + Leave this frame out of every render; the photo is not deleted + Show the first frame concerned + Use the frame as the sequence thumbnail + Use this frame in renders again + Click a row to show the frame + Adds blur along the motion like a slower shutter; costs optical flow on every frame + Optical flow precision for blur and synthesised frames; Best is the slowest + Target shutter angle; 180° is the film look, more smears moving things + Frames over which the camera path is smoothed; too high crops more on deliberate pans + Removes camera shake by cropping slightly; the crop grows with the shake + Not applicable: motion blur is off + Not applicable: deflicker is off + Not applicable: holy grail is off + Not applicable: the frames sit off the daylight locus (night or mixed light) + Not applicable: this format is lossless + Needs the deep analysis: press Analyse + Not applicable: used only by motion blur and interpolated timing + Not applicable: stabilisation is off + Not applicable: stacking is off + Let the advisor set every section from the analysis and list what changed + The advisor never stacks on its own: a median erases moving stars + Apply the advisor’s heavier choices for this section and list what changed · Ctrl+Z undoes + Pause · Space + Play the frames · Space; arrows step one frame + Show pixels at 1:1 without interpolation · Ctrl+1; Ctrl+0 fits + Play ten seconds of the video’s frames with the current settings + Wipe compare: original on the left, corrected on the right; drag the line + Show the whole frame and darken what the output will cut + Close full screen · Esc + Full screen at native resolution · Esc closes + Show the sky and landscape boundary used by region deflicker + Show or hide the shot data + Overlay the motion to the next frame measured by the engine + Render with the selected preset; progress in the job bar · Ctrl+R + Choose another preset + Return every control of this section to Auto · Ctrl+Z undoes + Frames combined into each output frame; trails and smoothing grow with it + Median and mean remove noise and moving things; star trails keep the brightest pixels + Crop, aspect, virtual camera moves + Presets, output, batch, history + Deflicker, regions, day-night transitions, white balance + Frame table, warnings, exclusions + Motion blur, optical flow, stabilisation + Median and star-trail stacking + Frame rate, timing mode, speed curve + Scales the timing so the video lasts this long; off keeps the playback rate + Constant: one frame per photo; Adaptive: follows capture time; Interpolated: fills gaps; Remapped: follows the curve + Photos shown per second of video; more plays the sequence faster Stop this job; Retry continues later from its last checkpoint Hide finished jobs from the list; they stay in the history Every job diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index f8da3819..b4b30d0c 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -4,8 +4,183 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Analizza + Analisi in coda + Sorgente + Indietro + Aggiungi chiave + Formato + Centro orizzontale + Centro verticale + Fotogrammi chiave + Chiave {0} di {1} · {2} + {0} chiave + {0} chiavi + Posizione orizzontale + Posizione verticale + Rimuovi chiave + Zoom + copertura nuvolosa % + luminanza misurata + Non ancora analizzata + percorso orizzontale + percorso verticale + regione del cielo + stelle per Mpx + salti di esposizione ricevuti + curva obiettivo Scegli una sequenza in Libreria Questa sequenza non è più nell’archivio. I lavori non possono partire finché l’indice dell’archivio non è aperto. Le impostazioni di questa sequenza non sono leggibili. + circa {0} + Metti in coda + In serie… + Scegli cartella… + Codec + Colore + Contenitore + Encoder + Auto + Nome file + Fotogrammi al secondo + hardware + Altezza + Render precedenti: {0} · ultimo {1} + Render precedenti: {0} · ultimo {1} + cronologia + In serie + Ancora nessun render + Uscita · {0} + Preset di esportazione + Qualità + Qualità {0} + Consigliato + Renderizza ora + Risoluzione + Risultato + Salva in + exports/ della sequenza + Dimensione stimata + software + Tempo stimato + Nessun encoder qui + Larghezza + Deflicker + flicker {0} % + Holy grail + salto max {0} EV + Compensazione + Regioni + Intensità + Temperatura colore + Transizioni + Bilanciamento del bianco + Finestra deflicker + Pellicola + Bilanciata + Massima + Bozza + Esposizione + Note + Dimensioni + Decodifica + Ora + Escludi + Escludi fotogramma + escluso + Esclusi + Nessuno + nero + danneggiato + duplicato + mancante + illeggibile + bianco + copertina + Copertina + Non impostata + Fotogramma {0} + Includi + Includi fotogramma + Nessun avviso + anteprima {0} + Imposta copertina + Avvisi + Apertura sequenza + Fotogramma chiave + Salto di esposizione {0} EV + Salto {0} EV non ricevuto + Mosso + ritaglio {0} % + Qualità del flusso + panoramica {0} px/fotogr. + tremolio {0} px + Angolo otturatore + Smussatura percorso + Stabilizza + {0} impostazione cambiata + {0} impostazioni cambiate + Niente da cambiare + Ottimizza tutto + Ottimizza sezione + Anteprima + Anteprima 10 s + Confronta + Maschera ritaglio + Esci da schermo intero + Schermo intero + uscita {0} + {0} di {1} + Riproduci + Regioni + Dati di scatto + Vettori + originale | corretto + Auto + Orizzonte + Luminanza + Renderizza · {0} + Render in coda + Renderizza + Ripristina + Torna ad Auto + Sezioni + Lunghezza + Media + Mediana + Stacking + Nessun campo stellare + Campo stellare trovato + Scie stellari + {0:N0} fotogramma + {0:N0} fotogrammi + intervallo {0} s + {0} avviso + {0} avvisi + Inquadratura + Esporta + Esposizione + Fotogrammi + Movimento + Stacking + Tempo + Curva di velocità + Adatta alla durata + Tempi + uscita {0} % + {0:N0} fotogramma → {1} · {2} fps + {0:N0} fotogrammi → {1} · {2} fps + Velocità + sorgente {0} % + Adattivo + Costante + Interpolato + Su curva + Centrato + {0:N0} fotogramma + {0:N0} fotogrammi + Nessuno + Disattivo + Attivo diff --git a/i18n/it/Export.it.resx b/i18n/it/Export.it.resx index 27aed9a6..c4a1ce9b 100644 --- a/i18n/it/Export.it.resx +++ b/i18n/it/Export.it.resx @@ -4,6 +4,8 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + DNG lineare + Sequenza di immagini Uscita a {0} bit non disponibile con questo encoder; codifica a {1} bit. Bit rate limitato a {1} bit/s, il massimo del livello {0}. Nessun encoder {0} su questo PC; viene usato H.264. diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index c81ad08f..eda5c4e9 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -15,6 +15,97 @@ Chiudi Apri la cartella dei file di log Torna al valore consigliato + Rilegge ogni fotogramma e aggiorna l’analisi; gira come lavoro in background + Auto: ancora nessun consiglio, vale il valore predefinito; Analizza lascia decidere al consulente + Torna alla Libreria + È in corso un’analisi o un render di questa sequenza; le impostazioni attendono la fine + Aggiunge una chiave al fotogramma corrente + Formato dell’uscita; un preset con dimensioni fisse usa il proprio + Centro orizzontale dell’inquadratura della chiave scelta + Centro verticale dell’inquadratura della chiave scelta + Chiavi della camera virtuale: zoom e inquadratura in fotogrammi scelti, raccordati tra loro + Sposta il ritaglio a sinistra o a destra nel fotogramma + Sposta il ritaglio in alto o in basso nel fotogramma + Rimuove la chiave selezionata + Zoom della chiave scelta; 1 mostra tutto il ritaglio, di più ingrandisce e ammorbidisce + Mette in coda questo render e continui a modificare + Applica questo preset di sequenza a tutte le sezioni · {0} + Mette in coda i preset spuntati come un unico lavoro; la sequenza si prepara una volta + Bit rate medio; di più conserva dettagli e sfumature, i file crescono + Codec video o immagine; HEVC a 10 bit mantiene pulite le sfumature del cielo + Colore Rec.709; 10 bit evitano il banding nel cielo, l’HDR non è disponibile + MP4, AVI, GIF, APNG o una cartella di immagini; l’elenco dei codec si adegua + Encoder di questo PC; Auto preferisce l’hardware + Dove vanno i render: {0} + Fotogrammi al secondo del file video + Auto: i {0} fps del preset + Torna ai fotogrammi al secondo del preset + Altezza in pixel; vuoto segue la larghezza · Invio applica, Esc annulla + Apre Lavori per vedere i render di questa sequenza + Include questo preset quando In serie mette in coda il render + Segnaposto: {date} {title} {preset} {codec} {width} {height} {fps} · Invio applica, Esc annulla + Renderizza con {0}; modificare un valore lo rende Personalizzato + Qualità dell’immagine; 95 sembra senza perdite, meno fa file più piccoli + Scelta del consulente: {0} + Inserisci una dimensione tra 16 e 16384 pixel + Larghezza in pixel; vuoto usa il preset o la sorgente · Invio applica, Esc annulla + Elimina lo sfarfallio di luminosità tra fotogrammi; spento lascia l’esposizione della fotocamera + Trasforma i salti di ISO, tempo e diaframma in rampe morbide; spento li lascia + Schiarisce o scurisce tutto il video dopo la correzione, in stop + Cielo e paesaggio hanno una curva ciascuno; spento tratta il fotogramma come uno + Quanto dello sfarfallio misurato viene tolto; 1,0 lo toglie tutto + Intervallo di temperatura colore misurato nella sequenza + Fotogrammi su cui si distribuisce ogni salto di ISO, tempo o diaframma; 0 lascia i salti + Smussa i rapporti di colore: il bilanciamento automatico smette di sfarfallare e la deriva del tramonto resta + Fotogrammi usati per stimare la curva senza sfarfallio; troppo corta lo lascia, troppo lunga appiattisce i veri cambi di luce + Lascia fuori questo fotogramma da ogni render; la foto non viene eliminata + Mostra il primo fotogramma interessato + Usa il fotogramma come copertina della sequenza + Usa di nuovo questo fotogramma nei render + Fai clic su una riga per mostrare il fotogramma + Aggiunge mosso lungo il movimento come un tempo più lungo; richiede il flusso ottico su ogni fotogramma + Precisione del flusso ottico per mosso e fotogrammi sintetici; Massima è la più lenta + Angolo otturatore obiettivo; 180° è l’aspetto cinema, di più impasta ciò che si muove + Fotogrammi su cui si smussa il percorso della camera; troppi ritagliano di più nelle panoramiche volute + Elimina il tremolio con un leggero ritaglio; il ritaglio cresce col tremolio + Non applicabile: il mosso è spento + Non applicabile: il deflicker è spento + Non applicabile: l’holy grail è spento + Non applicabile: i fotogrammi sono fuori dal luogo della luce diurna (notte o luce mista) + Non applicabile: questo formato è senza perdite + Serve l’analisi approfondita: premi Analizza + Non applicabile: serve solo al mosso e ai tempi interpolati + Non applicabile: la stabilizzazione è spenta + Non applicabile: lo stacking è spento + Lascia che il consulente imposti ogni sezione dall’analisi ed elenchi cosa è cambiato + Il consulente non fa mai stacking da solo: una mediana cancella le stelle in movimento + Applica le scelte più incisive del consulente per questa sezione ed elenca cosa è cambiato · Ctrl+Z annulla + Pausa · Spazio + Riproduce i fotogrammi · Spazio; le frecce avanzano di uno + Mostra i pixel 1:1 senza interpolazione · Ctrl+1; Ctrl+0 adatta + Riproduce dieci secondi dei fotogrammi del video con le impostazioni attuali + Confronto a tendina: originale a sinistra, corretto a destra; trascina la linea + Mostra tutto il fotogramma e scurisce ciò che l’uscita taglierà + Chiudi schermo intero · Esc + Schermo intero alla risoluzione nativa · Esc chiude + Mostra il confine tra cielo e paesaggio usato dal deflicker per regioni + Mostra o nasconde i dati di scatto + Sovrappone il movimento verso il fotogramma successivo misurato dal motore + Renderizza con il preset scelto; avanzamento nella barra dei lavori · Ctrl+R + Scegli un altro preset + Riporta in Auto ogni controllo di questa sezione · Ctrl+Z annulla + Fotogrammi combinati in ogni fotogramma d’uscita; scie e levigatura crescono con esso + Mediana e media tolgono rumore e ciò che si muove; le scie stellari tengono i pixel più luminosi + Ritaglio, formato, movimenti della camera virtuale + Preset, uscita, serie, cronologia + Deflicker, regioni, transizioni giorno-notte, bilanciamento del bianco + Tabella dei fotogrammi, avvisi, esclusioni + Mosso, flusso ottico, stabilizzazione + Stacking a mediana e scie stellari + Velocità, modo dei tempi, curva di velocità + Scala i tempi perché il video duri così; spento mantiene la velocità + Costante: un fotogramma per foto; Adattivo: segue l’ora di scatto; Interpolato: riempie i vuoti; Su curva: segue la curva + Foto mostrate per secondo di video; di più accelera la sequenza Ferma questa attività; Riprova la continua più tardi dall'ultimo punto di ripresa Nasconde le attività concluse dall'elenco; restano nella cronologia Tutte le attività diff --git a/src/Titano.App/Editor/CameraTab.cs b/src/Titano.App/Editor/CameraTab.cs index 0ef6c3cc..dd52d241 100644 --- a/src/Titano.App/Editor/CameraTab.cs +++ b/src/Titano.App/Editor/CameraTab.cs @@ -41,6 +41,7 @@ public sealed class CameraTab : EditorTab ]; AddKeyCommand = new RelayCommand(AddKey, () => !Editor.IsBusy && Keys.All(k => k.Frame != Editor.CurrentIndex)); RemoveKeyCommand = new RelayCommand(RemoveKey, () => !Editor.IsBusy && SelectedKey >= 0); + CommitCurveCommand = new RelayCommand(CommitCurve); Refresh(); } @@ -95,12 +96,16 @@ public sealed class CameraTab : EditorTab public ICommand RemoveKeyCommand { get; } - private IReadOnlyList Keys => Editor.Session.Project.Camera.Keyframes; + /// Run by the curve editor after each finished edit. + public ICommand CommitCurveCommand { get; } + + /// Keyframes in frame order (the order of ). + private List Keys => [.. Editor.Session.Project.Camera.Keyframes.OrderBy(k => k.Frame)]; public override void Refresh() { base.Refresh(); - var points = Keys.OrderBy(k => k.Frame).Select(ToPoint).ToList(); + var points = Keys.Select(ToPoint).ToList(); if (!points.SequenceEqual(KeyPoints)) { KeyPoints.Clear(); @@ -113,7 +118,7 @@ public sealed class CameraTab : EditorTab /// The curve editor finished an edit (add, move, delete): the points become the keyframes, keeping each one's framing. public void CommitCurve() { - var old = Keys.OrderBy(k => k.Frame).ToList(); + var old = Keys; var keys = new List(); foreach (var point in KeyPoints.OrderBy(p => p.X)) { @@ -136,7 +141,7 @@ public sealed class CameraTab : EditorTab var frame = Editor.CurrentIndex; var key = new CameraKey(frame, 0.5, 0.5, 1, 0); Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. p.Camera.Keyframes.Append(key).OrderBy(k => k.Frame)] } }); - SelectedKey = Keys.Select((k, i) => (k, i)).First(t => t.k.Frame == frame).i; + SelectedKey = Keys.FindIndex(k => k.Frame == frame); } private void RemoveKey() @@ -195,6 +200,7 @@ public sealed class TimeTab : EditorTab (p, v) => p with { Timing = p.Timing with { FitToSeconds = v > 0 ? v : null } }, v => v > 0 ? Formatting.Duration(TimeSpan.FromSeconds(v)) : Loc.L("Editor.Value.Off")), ]; + CommitCurveCommand = new RelayCommand(CommitCurve); Refresh(); } @@ -204,6 +210,9 @@ public sealed class TimeTab : EditorTab /// The monotone spline through . public Func? Evaluator { get => _evaluator; private set => Set(ref _evaluator, value); } + /// Run by the curve editor after each finished edit. + public ICommand CommitCurveCommand { get; } + /// "3,600 frames → 2 min 30 s · 24 fps". public string? PlanText { get => _planText; private set => Set(ref _planText, value); } diff --git a/src/Titano.App/Editor/CurveCommit.cs b/src/Titano.App/Editor/CurveCommit.cs new file mode 100644 index 00000000..5c79f29d --- /dev/null +++ b/src/Titano.App/Editor/CurveCommit.cs @@ -0,0 +1,28 @@ +using System.Windows; +using System.Windows.Input; +using Titano.Ui.Visuals; + +namespace Titano.App.Editor; + +/// Runs a command after every finished edit of a (add, move, delete, nudge). +public static class CurveCommit +{ + public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached( + "Command", typeof(ICommand), typeof(CurveCommit), new PropertyMetadata(null, OnCommandChanged)); + + public static ICommand? GetCommand(DependencyObject d) => (ICommand?)d.GetValue(CommandProperty); + + public static void SetCommand(DependencyObject d, ICommand? value) => d.SetValue(CommandProperty, value); + + private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is not CurveEditor editor) return; + editor.EditCompleted -= OnEditCompleted; + if (e.NewValue is not null) editor.EditCompleted += OnEditCompleted; + } + + private static void OnEditCompleted(object sender, RoutedEventArgs e) + { + if (GetCommand((DependencyObject)sender) is { } command && command.CanExecute(null)) command.Execute(null); + } +} diff --git a/src/Titano.App/Editor/EditorMeasures.xaml b/src/Titano.App/Editor/EditorMeasures.xaml new file mode 100644 index 00000000..21d43e4f --- /dev/null +++ b/src/Titano.App/Editor/EditorMeasures.xaml @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.App/Editor/EditorPanels.xaml b/src/Titano.App/Editor/EditorPanels.xaml new file mode 100644 index 00000000..2d1867f3 --- /dev/null +++ b/src/Titano.App/Editor/EditorPanels.xaml @@ -0,0 +1,427 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +