using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
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.Controls;
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 (at the source's own size for 1:1 and
/// wheel zoom), the filmstrip with markers, the section tabs and the keyboard (space, arrows, Ctrl+Z/Y, Ctrl+0/1,
/// Ctrl+R, Ctrl+Shift+A). 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 readonly AsyncRelayCommand _analyse;
private readonly AsyncRelayCommand _render;
private PreviewRenderer _renderer;
private int _currentIndex;
private EditorTab _selectedTab;
private ImageSource? _previewImage;
private ImageSource? _originalImage;
private ImageSource? _waveformImage;
private string? _previewMessage;
private bool _isCompare = true;
private bool _showVectors;
private bool _showRegions;
private bool _showCropMask;
private bool _exportCropMask = true;
private CropMaskMode _cropMaskMode = CropMaskMode.ShowLoss;
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 bool _planned;
private IReadOnlyList _markers = [];
private IThumbnailSource _thumbnails;
private int _playLimit;
private double? _analysisSecondsPerFrame;
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();
BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsBusy && !IsAnalysing);
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsBusy);
_render = 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, () => !IsExportTab);
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))];
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"; on the Export tab what the video will be:
/// "3,600 frames · 24 fps · 2 min 30 s · 3840×2160 · source 8192×5464" (Export.html).
///
public string Summary => IsExportTab && Plan is { } plan
? EditorText.OutputSummary(Session.Content, plan)
: 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));
OnPropertyChanged(nameof(Summary));
OnToolsChanged();
// 1:1 is not a tool of the Export tab (Export.html): its picture fits the view.
if (IsExportTab) ZoomMode = PreviewZoomMode.Fit;
UpdateInfo();
RequestPreview(immediate: true);
CommandManager.InvalidateRequerySuggested();
}
}
/// 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;
foreach (var tab in Tabs) 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); }
/// Luma waveform of the corrected preview (Exposure tab), as an alpha mask drawn in the accent colour.
public ImageSource? WaveformImage { get => _waveformImage; private set => Set(ref _waveformImage, value); }
/// One sentence over the preview when the frame on screen cannot be shown; null otherwise.
public string? PreviewMessage { get => _previewMessage; private set => Set(ref _previewMessage, value); }
public bool IsCompare { get => _isCompare; set => Set(ref _isCompare, value); }
/// The Vectors tool (kept while the Export tab hides it, shown again on the other tabs).
public bool ShowVectors
{
get => _showVectors;
set
{
if (!Set(ref _showVectors, value)) return;
OnPropertyChanged(nameof(ViewVectors));
RequestPreview(immediate: true);
}
}
public bool ShowRegions
{
get => _showRegions;
set
{
if (!Set(ref _showRegions, value)) return;
OnPropertyChanged(nameof(ViewRegions));
RequestPreview(immediate: true);
}
}
/// The Crop mask tool of the current tab: the Export tab has its own, on by default (Export.html).
public bool ShowCropMask
{
get => IsExportTab ? _exportCropMask : _showCropMask;
set
{
if (value == ShowCropMask) return;
if (IsExportTab) _exportCropMask = value;
else _showCropMask = value;
OnPropertyChanged();
RequestPreview(immediate: true);
}
}
/// Overlays the viewport draws: only tools that have a button on the current tab.
public bool ViewVectors => ShowVectors && !IsExportTab;
public bool ViewRegions => ShowRegions && !IsExportTab;
/// The crop mask shows "how it will look" (outside hidden) instead of "what I lose" (outside dimmed).
public bool IsCropResult
{
get => _cropMaskMode == CropMaskMode.ShowResult;
set
{
if (!Set(ref _cropMaskMode, value ? CropMaskMode.ShowResult : CropMaskMode.ShowLoss, nameof(CropMaskMode))) return;
OnPropertyChanged();
OnPropertyChanged(nameof(CropModeToolTip));
}
}
public CropMaskMode CropMaskMode => _cropMaskMode;
public string CropModeToolTip => Loc.L(IsCropResult ? "Tooltips.Editor.Preview.CropLoss" : "Tooltips.Editor.Preview.CropResult");
public PreviewZoomMode ZoomMode
{
get => _zoomMode;
set
{
if (!Set(ref _zoomMode, value)) return;
OnPropertyChanged(nameof(IsActualSize));
// Fit renders at the view's size; 1:1 and wheel zoom need the source's own pixels.
RequestPreview(immediate: true);
}
}
/// 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 view in device pixels (the view reports its size); Fit renders at this size.
public int PreviewEdge
{
get => _previewEdge;
set
{
var rounded = int.Clamp((value + 63) / 64 * 64, 256, 4096);
if (Set(ref _previewEdge, rounded) && _zoomMode == PreviewZoomMode.Fit) RequestPreview();
}
}
/// Long edge the preview renders at: the view's in Fit, the source's own when zoomed (1:1 shows raw pixels).
public int RenderEdge => _zoomMode == PreviewZoomMode.Fit || SourceEdge <= 0 ? PreviewEdge : SourceEdge;
private int SourceEdge => int.Max(Session.Content.SourceWidth, Session.Content.SourceHeight);
// ---- 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);
/// A deep analysis of this sequence is queued or running (Analyse would queue it twice).
public bool IsAnalysing => _jobs.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
public bool IsEditable => !IsBusy;
public string? BusyToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy") : null;
/// What Analyse does and costs ("about 6 min" from the speed of the last analysis), or why it is disabled.
public string AnalyseToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy")
: IsAnalysing ? Loc.L("Tooltips.Editor.AnalyseQueued")
: _analysisSecondsPerFrame is { } perFrame ? Loc.L("Tooltips.Editor.AnalyseCost", Formatting.Duration(TimeSpan.FromSeconds(perFrame * FrameCount)))
: Loc.L("Tooltips.Editor.Analyse");
public string OptimiseAllToolTip => Loc.L(IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.OptimiseAll");
public bool IsPlaying => _player.IsEnabled;
public string PlayToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Play");
public string PlayName => Loc.L(IsPlaying ? "Editor.Preview.Pause" : "Editor.Preview.Play");
/// "Preview 10 s" (Export tab): plays ten seconds of the video's frames, or pauses them.
public string ClipToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Preview.Clip");
// ---- 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 => RenderBlockedReason ?? Loc.L("Tooltips.Editor.Render");
public bool CanRender => RenderBlockedReason is null;
/// Why the project's export cannot be rendered now, localised; null when it can.
public string? RenderBlockedReason => Plan switch
{
null when _planned => Loc.L("Tooltips.Editor.Render.NoSource"),
null => Loc.L("Tooltips.Editor.Render.Planning"),
{ NameError: { } error } => Loc.L("Tooltips.Editor.Render.NameError", error),
{ Setup.Encoder.IsReady: false } plan => plan.Setup.Encoder.Notices.LastOrDefault() is { } notice
? Loc.L(notice.Key, [.. notice.Args])
: Loc.L("Editor.Export.Unavailable"),
{ Setup.Plan.Frames.Count: 0 } => Loc.L("Tooltips.Editor.Render.NoFrames"),
_ => null,
};
public ICommand BackCommand { get; }
public ICommand AnalyseCommand => _analyse;
public ICommand OptimiseAllCommand { get; }
public ICommand RenderCommand => _render;
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", EditorText.Ev(s.MeasuredEv ?? s.ExpectedEv))))];
}
return [.. content.Light.ExposureSteps.Select(s => new TimelineMarker(s.Index, MarkerKind.ExposureStep, Loc.L("Editor.Marker.Step", EditorText.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));
}
/// Re-reads the enabled state of every command (the async ones keep their own event).
public void RefreshCommands()
{
_analyse.RaiseCanExecuteChanged();
_render.RaiseCanExecuteChanged();
foreach (var tab in Tabs) tab.RefreshCommands();
CommandManager.InvalidateRequerySuggested();
}
/// The Exposure tab switched to or from its waveform: the preview measures it.
public void OnWaveformNeeded() => RequestPreview(immediate: true);
///
/// Completes once the preview, corrections, plan, estimates and filmstrip thumbnails in flight are done (capture and
/// tests); a finished step may start the next (corrections re-render the preview), so it waits until all are quiet.
///
/// False when the work was still going on after .
public async Task WhenIdleAsync(TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (deadline - DateTime.UtcNow is { Ticks: > 0 } left)
{
var work = Work();
try
{
await Task.WhenAll(work).WaitAsync(left);
}
catch (TimeoutException)
{
return false;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// A failed run was already logged by its owner; it counts as done.
}
await Task.Delay(50);
// Quiet means nothing new was scheduled meanwhile (the same tasks) and no thumbnail is loading.
if (work.SequenceEqual(Work()) && (Thumbnails as EditorThumbnails)?.Pending is null or 0) return true;
}
return false;
Task[] Work() => [_preview.Idle, _corrections.Idle, _plans.Idle, .. Tabs.OfType().Select(t => t.EstimatesIdle)];
}
/// Loads the jobs of this sequence already queued or running (busy state) and the speed of the last analysis.
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);
foreach (var job in page.Items.OrderBy(j => j.Finished)) LearnAnalysisSpeed(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 || ViewRegions ? PreviewFraming.Source : PreviewFraming.Output;
var waveform = SelectedTab is ExposureTab { ChartMode: ExposureChart.Waveform };
var request = new PreviewRequest(CurrentIndex, Session.Project, RenderEdge, framing, ViewVectors, waveform);
var version = ++_previewVersion;
_ = RunPreviewAsync(request, version, immediate);
}
private async Task RunPreviewAsync(PreviewRequest request, int version, bool immediate)
{
var renderer = _renderer;
PreviewResult? result = null;
var ran = false;
_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);
ran = true;
}, immediate);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Log.Warning("editor", $"Preview of frame {request.Index + 1} failed", ex);
ran = true;
}
finally
{
if (version == _previewVersion) _previewBusy = false;
}
if (version != _previewVersion || _disposed || !ran) return;
if (result is not { } r)
{
// The frame on screen cannot be shown: never leave the previous frame's picture under this frame's shot data.
PreviewImage = OriginalImage = null;
MotionVectors = null;
WaveformImage = null;
PreviewMessage = Loc.L("Editor.Preview.Unreadable");
return;
}
PreviewMessage = null;
PreviewImage = r.Corrected;
OriginalImage = r.Original;
CropRect = r.Crop;
RegionBoundary = ViewRegions ? r.Horizon : null;
MotionVectors = ViewVectors ? r.Vectors : null;
WaveformImage = r.Waveform;
}
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;
_planned = true;
Plan = plan;
OnPropertyChanged(nameof(RenderText));
OnPropertyChanged(nameof(RenderToolTip));
OnPropertyChanged(nameof(RenderBlockedReason));
OnPropertyChanged(nameof(CanRender));
OnPropertyChanged(nameof(SelectedRenderChoice));
OnPropertyChanged(nameof(Summary));
foreach (var tab in Tabs) tab.OnPlanChanged();
UpdateInfo();
RefreshCommands();
}
// ---- 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));
OnPropertyChanged(nameof(PlayName));
OnPropertyChanged(nameof(ClipToolTip));
}
/// 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 OnToolsChanged()
{
OnPropertyChanged(nameof(ShowCropMask));
OnPropertyChanged(nameof(ViewVectors));
OnPropertyChanged(nameof(ViewRegions));
}
private void OnProjectChanged()
{
foreach (var tab in Tabs) tab.Refresh();
UpdateMarkers();
RequestCorrections();
RequestPlan();
RequestPreview();
RefreshCommands();
}
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);
}
/// The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once.
private void OnSaveFailed(Exception ex) => Shell.ShowToast(new Toast
{
Title = Loc.L("Editor.Save.Failed"),
Message = ex.Message,
ActionText = Loc.L("Editor.Save.Retry"),
ActionToolTip = Loc.L("Tooltips.Editor.Save.Retry"),
ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()),
});
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", EditorText.Clock(position), EditorText.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", EditorText.ParameterLabel(c.Parameter), EditorText.Value(c.Parameter, c.Before),
EditorText.Value(c.Parameter, 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);
LearnAnalysisSpeed(job);
OnBusyChanged();
if (wasActive && job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null);
});
}
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);
}
/// Seconds per frame of the latest finished deep analysis (any sequence): the cost Analyse announces.
private void LearnAnalysisSpeed(Job job)
{
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done, ItemsPerSecond: > 0 and var speed }) _analysisSecondsPerFrame = 1 / speed;
}
/// Reads the sequence again after a job; a finished render offers its follow-ups (BRIEF §11.5).
private async Task ReloadAsync(Job? render)
{
try
{
await Session.ReloadAsync();
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException)
{
Shell.ReportError(ex);
return;
}
if (render is null || _disposed) return;
var output = Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath;
Shell.ShowToast(new Toast
{
Title = Loc.L("Editor.Render.Done"),
Message = output is null ? render.TargetLabel : System.IO.Path.GetFileName(output),
ActionText = output is null ? null : Loc.L("Editor.Render.Reveal"),
ActionToolTip = output is null ? null : Loc.L("Tooltips.Editor.Render.Reveal"),
ActionCommand = output is null ? null : new RelayCommand(() => ShellActions.Reveal(output)),
});
}
private void OnBusyChanged()
{
OnPropertyChanged(nameof(IsBusy));
OnPropertyChanged(nameof(IsAnalysing));
OnPropertyChanged(nameof(IsEditable));
OnPropertyChanged(nameof(BusyToolTip));
OnPropertyChanged(nameof(AnalyseToolTip));
OnPropertyChanged(nameof(OptimiseAllToolTip));
foreach (var tab in Tabs) tab.OnBusyChanged();
RefreshCommands();
}
/// 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,
ImageSource? Waveform)
{
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))],
frame.Waveform is { } waveform ? EditorImages.ToMask(waveform) : null);
}
}