feat(app): editor view models for every section, preset cards and render actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 17:14:48 +00:00
1 parent e6d1317aab
commit f6ad822fbb
15 files changed
+2666 -6

No files matched your search

+265
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class CameraTab : EditorTab
{
/// <summary>Zoom at the top of the curve editor.</summary>
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<string>(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();
}
/// <summary>Keyframes as curve points: X = frame / (count − 1), Y = (zoom − 1) / (<see cref="MaxZoom"/> − 1). Edited in place by the curve editor.</summary>
public ObservableCollection<Point> KeyPoints { get; } = [];
public int SelectedKey
{
get => _selectedKey;
set
{
if (!Set(ref _selectedKey, value)) return;
OnSelectedKeyChanged();
}
}
public bool HasSelectedKey => SelectedKey >= 0 && SelectedKey < Keys.Count;
/// <summary>Framing of the selected keyframe: centre (0–1) and zoom.</summary>
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));
/// <summary>"Keyframe 2 of 3 · frame 0413".</summary>
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<double, string> XFormatter => x => EditorText.Position((int)double.Round(x * (Editor.FrameCount - 1)), Editor.FrameCount);
public Func<double, string> 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<CameraKey> 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();
}
/// <summary>The curve editor finished an edit (add, move, delete): the points become the keyframes, keeping each one's framing.</summary>
public void CommitCurve()
{
var old = Keys.OrderBy(k => k.Frame).ToList();
var keys = new List<CameraKey>();
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<CameraKey, CameraKey> 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));
}
}
/// <summary>
/// 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.
/// </summary>
public sealed class TimeTab : EditorTab
{
private Func<double, double>? _evaluator;
private string? _planText;
public TimeTab(EditorViewModel editor)
: base(editor, "Time", AdvisorSection.Timing)
{
var s = editor.Session;
Rows =
[
new AutoChoiceRow<TimingMode>(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<string>(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();
}
/// <summary>Remap control points (output fraction → source fraction), edited in place by the curve editor.</summary>
public ObservableCollection<Point> RemapPoints { get; } = [];
/// <summary>The monotone spline through <see cref="RemapPoints"/>.</summary>
public Func<double, double>? Evaluator { get => _evaluator; private set => Set(ref _evaluator, value); }
/// <summary>"3,600 frames → 2 min 30 s · 24 fps".</summary>
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<double, string> XFormatter { get; } = x => Loc.L("Editor.Time.Output", (x * 100).ToString("0", Loc.Culture));
public Func<double, string> 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));
}
/// <summary>The curve editor finished an edit: the points become the remap curve, and the timing mode follows it.</summary>
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<double, double>? Spline(IReadOnlyList<Point> 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);
}
}
+53
View File
@@ -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;
/// <summary>Linear-light frames as frozen sRGB bitmaps the UI thread can show (created on any thread).</summary>
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;
}
}
/// <summary>
/// Filmstrip thumbnails decoded through the editor's <see cref="ISequenceSource"/> (embedded previews when large
/// enough), at most a few at a time so scrolling the strip never floods the decoders.
/// </summary>
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<ImageSource?> 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();
}
}
}
+18
View File
@@ -98,6 +98,24 @@ public sealed class EditorSession : IAsyncDisposable
/// <summary>Makes <paramref name="frame"/> the hero frame (sequence thumbnail).</summary>
public bool SetHero(int frame) => (uint)frame < (uint)Content.Count && Edit(p => p with { HeroFrame = frame });
/// <summary>
/// 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.
/// </summary>
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() },
});
}
/// <summary>
/// A render of <paramref name="export"/> 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).
+72
View File
@@ -0,0 +1,72 @@
using System.Windows.Input;
using Titano.Core.Advice;
using Titano.Core.Localization;
using Titano.Ui.Mvvm;
namespace Titano.App.Editor;
/// <summary>
/// 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". <see cref="Refresh"/> runs after every project change.
/// </summary>
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; }
/// <summary>"Frames", "Exposure"… (resource key suffix).</summary>
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);
/// <summary>Settings rows of the right column (empty for tabs with their own panel).</summary>
public IReadOnlyList<SettingRow> Rows { get; protected init; } = [];
/// <summary>The advisor has heavier decisions for this section (stacking has none).</summary>
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; }
/// <summary>Re-reads the project (any change).</summary>
public virtual void Refresh()
{
foreach (var row in Rows) row.Refresh();
}
/// <summary>The sequence was read again: new analyses (charts, findings).</summary>
public virtual void OnContentChanged() => Refresh();
/// <summary>The preview's corrections were prepared for the current settings (target curves).</summary>
public virtual void OnCorrectionsChanged()
{
}
/// <summary>The export plan of the project changed (durations, sizes).</summary>
public virtual void OnPlanChanged()
{
}
public override void Dispose()
{
foreach (var row in Rows) row.Dispose();
base.Dispose();
}
}
+104
View File
@@ -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;
/// <summary>The editor's composed texts (header summary, shot data, preset card lines), in the current UI language.</summary>
public static class EditorText
{
private const string Separator = " · ";
/// <summary>"3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings".</summary>
public static string Summary(SequenceContent content, int warnings)
{
ArgumentNullException.ThrowIfNull(content);
var s = content.Sequence;
var parts = new List<string> { 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);
}
/// <summary>"0413 / 3,600 · 18:02:11 · 1/8 s · f/8 · ISO 400 · 24 mm".</summary>
public static string Shot(Frame frame, int index, int count)
{
ArgumentNullException.ThrowIfNull(frame);
var parts = new List<string> { 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);
}
/// <summary>"0413 / 3,600".</summary>
public static string Position(int index, int count) =>
(index + 1).ToString("D4", Loc.Culture) + " / " + count.ToString("N0", Loc.Culture);
/// <summary>"1/250 s", "1/8 s", "2 s".</summary>
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));
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
public static string Format(ResolvedExport export, int width, int height)
{
ArgumentNullException.ThrowIfNull(export);
var parts = new List<string> { 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);
}
/// <summary>"120 Mb/s · 0.07 bpp · NVENC" for video, "Quality 95 · Titano" for frames.</summary>
public static string Encoding(ResolvedExport export, long bitRate, string? encoder)
{
ArgumentNullException.ThrowIfNull(export);
var parts = new List<string>();
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);
}
/// <summary>"2.2 GB · about 5 min".</summary>
public static string Estimate(ExportEstimate estimate)
{
ArgumentNullException.ThrowIfNull(estimate);
return Formatting.Bytes(estimate.Bytes) + Separator + Loc.L("Editor.Export.About", Formatting.Duration(estimate.Time));
}
/// <summary>"120 Mb/s".</summary>
public static string BitRate(long bitsPerSecond) => Loc.L("Editor.Export.Mbps", (bitsPerSecond / 1e6).ToString(bitsPerSecond >= 10_000_000 ? "0" : "0.#", Loc.Culture));
/// <summary>"3840×2160".</summary>
public static string Size(int width, int height) => width.ToString(Loc.Culture) + "×" + height.ToString(Loc.Culture);
/// <summary>"23.976", "24".</summary>
public static string FrameRate(Rational rate) => rate.Denominator == 1 ? rate.Numerator.ToString(Loc.Culture) : rate.Value.ToString("0.###", Loc.Culture);
/// <summary>Technical codec name ("H.264 High", "HEVC Main10", "PNG"…).</summary>
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);
}
+675
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
{
public const int DefaultPreviewEdge = 1280;
private static readonly TimeSpan Debounce = TimeSpan.FromMilliseconds(150);
private readonly IReadOnlyList<IVideoEncoderProvider> _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<Guid, Job> _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<Point>? _regionBoundary;
private IReadOnlyList<MotionVector>? _motionVectors;
private int _previewEdge = DefaultPreviewEdge;
private int _previewVersion;
private bool _previewBusy;
private RenderCorrections? _correctionsValue;
private ExportPlan? _plan;
private IReadOnlyList<TimelineMarker> _markers = [];
private IThumbnailSource _thumbnails;
private int _playLimit;
private bool _disposed;
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList<IVideoEncoderProvider> 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;
/// <summary>"3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings".</summary>
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<EditorTab> 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();
}
}
/// <summary>The Export tab swaps the preview tools for compare, crop mask and a 10-second preview (Export.html).</summary>
public bool IsExportTab => SelectedTab is ExportTab;
// ---- Frames ----
public int FrameCount => Session.Content.Count;
/// <summary>The frame on screen; the filmstrip, the charts and the frame table seek it.</summary>
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<CameraTab>()) tab.OnCurrentFrameChanged();
foreach (var tab in Tabs.OfType<TimeTab>()) tab.OnCurrentFrameChanged();
UpdateInfo();
RequestPreview(immediate: _player.IsEnabled);
}
}
public IThumbnailSource Thumbnails { get => _thumbnails; private set => Set(ref _thumbnails, value); }
/// <summary>Exposure steps (as received), warnings and keyframes above the filmstrip.</summary>
public IReadOnlyList<TimelineMarker> 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));
}
}
/// <summary>The 1:1 tool (raw pixels).</summary>
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<Point>? RegionBoundary { get => _regionBoundary; private set => Set(ref _regionBoundary, value); }
public IReadOnlyList<MotionVector>? MotionVectors { get => _motionVectors; private set => Set(ref _motionVectors, value); }
/// <summary>Gain on vector lengths so a pixel of motion stays visible.</summary>
public double VectorScale => 4;
public string WipeLabel => Loc.L("Editor.Preview.Wipe");
/// <summary>Shot data (bottom-right pill): frame, time, exposure; on the Export tab output time and size.</summary>
public string? InfoText { get; private set; }
/// <summary>Long edge of the preview picture in device pixels (the view reports its size).</summary>
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 ----
/// <summary>The corrections of the current exposure settings, once prepared (target curves).</summary>
public RenderCorrections? Corrections { get => _correctionsValue; private set => Set(ref _correctionsValue, value); }
/// <summary>What the project's export will produce (size, time, encoder, name).</summary>
public ExportPlan? Plan { get => _plan; private set => Set(ref _plan, value); }
/// <summary>An analysis or render of this sequence is running: settings wait, viewing tools stay live.</summary>
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<Choice> RenderChoices { get; }
/// <summary>The export preset the Render button renders (choosing another one sets it).</summary>
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() } });
}
}
/// <summary>"Render · 4K archive".</summary>
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; }
/// <summary>Exposure steps of the sequence: as received by the pixels when the deep analysis measured them, else from the metadata.</summary>
public static IReadOnlyList<TimelineMarker> 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))))];
}
/// <summary>"Optimise section": the advisor's heavier decisions, reported in a toast (what changed, from what to what).</summary>
public void Optimise(AdvisorSection section) => Report(Session.Optimise(section));
/// <summary>Queues a render of the project's export (with its batch presets when <paramref name="batch"/>).</summary>
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));
}
/// <summary>Loads the jobs of this sequence already queued or running (busy state).</summary>
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));
}
/// <summary>Next frame while playing; frames are skipped rather than queued when the preview is slower than the clock.</summary>
private void Advance()
{
if (_previewBusy) return;
if (CurrentIndex >= FrameCount - 1 || (_playLimit > 0 && --_playLimit == 0))
{
TogglePlay(0);
return;
}
CurrentIndex++;
}
/// <summary>Source frames that make ten seconds of video.</summary>
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<TimelineMarker>(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<SettingChange> 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<object>().LongCount()),
IFormattable f => f.ToString(null, Loc.Culture),
_ => value.ToString() ?? string.Empty,
};
/// <summary>A rendered preview as frozen bitmaps and overlays in picture pixels (built off the UI thread).</summary>
private sealed record PreviewResult(ImageSource Corrected, ImageSource Original, Rect Crop, IReadOnlyList<Point> Horizon, IReadOnlyList<MotionVector> 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))]);
}
}
+4 -1
View File
@@ -32,6 +32,9 @@ public sealed record ExportPlan(ResolvedExport Export, RenderSetup Setup, Export
/// </summary>
public sealed class ExportPlanner(SequenceContent content, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host, ThroughputModel? model = null)
{
/// <summary>Encoder providers of the machine that renders, in priority order.</summary>
public IReadOnlyList<IVideoEncoderProvider> Encoders { get; } = encoders;
/// <summary>Sequence presets that fit the content, then every built-in export preset.</summary>
public static IReadOnlyList<ExportChoice> Choices(IReadOnlyList<SequencePreset> presets, AdvisorResult advice)
{
@@ -69,7 +72,7 @@ public sealed class ExportPlanner(SequenceContent content, IReadOnlyList<IVideoE
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 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);
}
+466
View File
@@ -0,0 +1,466 @@
using System.Globalization;
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Settings;
using Titano.Core.Advice;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Video;
using Titano.Data.Processing;
using Titano.Ui.Mvvm;
namespace Titano.App.Editor;
/// <summary>A preset card of the Export tab (Export.html): what it renders and what it will cost on this machine.</summary>
public sealed class PresetCard(ExportTab owner, ExportChoice choice) : ObservableObject
{
private string? _format;
private string? _encoding;
private string? _estimate;
private bool _isSelected;
public ExportChoice Choice { get; } = choice;
public string Name => Choice.Name;
public bool IsRecommended => Choice.IsRecommended;
/// <summary>Sequence presets apply full settings; export presets only choose the output.</summary>
public bool IsSequencePreset => Choice.Sequence is not null;
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);
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
public string? Format { get => _format; private set => Set(ref _format, value); }
/// <summary>"120 Mb/s · 0.07 bpp · NVENC".</summary>
public string? Encoding { get => _encoding; private set => Set(ref _encoding, value); }
/// <summary>"2.2 GB · about 5 min".</summary>
public string? Estimate { get => _estimate; private set => Set(ref _estimate, value); }
public bool IsSelected { get => _isSelected; set => Set(ref _isSelected, value); }
/// <summary>Ticked for "Batch…" (export presets only).</summary>
public bool IsInBatch
{
get => owner.IsInBatch(Choice.ExportPresetId);
set => owner.SetInBatch(Choice.ExportPresetId, value);
}
public bool CanBatch => !IsSequencePreset;
public ICommand SelectCommand => owner.SelectCommand;
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));
}
/// <summary>A codec choice of the Output panel with the profile and depth it implies.</summary>
public sealed record CodecChoice(VideoCodec Codec, CodecProfile Profile, int BitDepth)
{
public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec);
public string Label => EditorText.CodecName(Codec, Profile, BitDepth);
}
/// <summary>Where renders go: the sequence's exports folder or a folder the user picked.</summary>
public sealed record SaveChoice(string? Folder, bool Browse = false)
{
public string Label => Browse ? Loc.L("Editor.Export.Browse") : Folder is null ? Loc.L("Editor.Export.SequenceFolder") : Path.GetFileName(Folder.TrimEnd('\\', '/'));
}
/// <summary>
/// Export (Export.html, BRIEF §11.4–11.5): preset cards with size and time estimates, the Output panel (container,
/// codec, size, frame rate, quality, encoder, colour depth, name template, folder) with the estimate and the encoder's
/// notices, and the render actions (now, queue, batch). Editing a value makes the preset "Custom" (§11.4).
/// </summary>
public sealed class ExportTab : EditorTab
{
public static IReadOnlyList<CodecChoice> Codecs { get; } =
[
new(VideoCodec.H264, CodecProfile.H264High, 8), new(VideoCodec.Hevc, CodecProfile.HevcMain, 8), new(VideoCodec.Hevc, CodecProfile.HevcMain10, 10),
new(VideoCodec.Av1, CodecProfile.Av1Main, 10), new(VideoCodec.Mjpeg, CodecProfile.Auto, 8), new(VideoCodec.Gif, CodecProfile.Auto, 8),
new(VideoCodec.Apng, CodecProfile.Auto, 8), new(VideoCodec.PngSequence, CodecProfile.Auto, 8), new(VideoCodec.JpegSequence, CodecProfile.Auto, 8),
new(VideoCodec.Tiff16Sequence, CodecProfile.Auto, 16), new(VideoCodec.LinearDngSequence, CodecProfile.Auto, 16),
];
private readonly LatestRunner _estimates = new(TimeSpan.FromMilliseconds(250));
private IReadOnlyList<PresetCard> _cards = [];
private IReadOnlyList<CodecChoice> _codecChoices = [];
private IReadOnlyList<Choice> _encoders = [];
private IReadOnlyList<SaveChoice> _saveChoices = [];
private IReadOnlyList<Choice> _depths = [];
private IReadOnlyList<string> _notices = [];
private bool _refreshing;
public ExportTab(EditorViewModel editor)
: base(editor, "Export", AdvisorSection.Export)
{
SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !Editor.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<PresetCard> 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; }
/// <summary>"Output · 4K archive".</summary>
public string Title => Loc.L("Editor.Export.Output", Editor.Plan?.PresetName ?? ProcessingJobs.PresetName(ExportResolver.Resolve(Export)));
public IReadOnlyList<Choice> Containers { get; } =
[
new(ContainerFormat.Mp4, "Export.Container.Mp4"), new(ContainerFormat.Avi, "Export.Container.Avi"), new(ContainerFormat.Gif, "Export.Container.Gif"),
new(ContainerFormat.Apng, "Export.Container.Apng"), new(ContainerFormat.ImageSequence, "Export.Container.ImageSequence"),
];
public Choice? SelectedContainer
{
get => Containers.FirstOrDefault(c => Equals(c.Value, Resolved.Container));
set
{
if (_refreshing || value?.Value is not ContainerFormat container || container == Resolved.Container) return;
SelectCodec(Codecs.First(c => c.Container == container));
}
}
public IReadOnlyList<CodecChoice> CodecChoices { get => _codecChoices; private set => Set(ref _codecChoices, value); }
public CodecChoice? SelectedCodec
{
get => CodecChoices.FirstOrDefault(c => c.Codec == Resolved.Codec && (c.Codec != VideoCodec.Hevc || (c.BitDepth > 8) == (Resolved.BitDepth > 8)));
set
{
if (!_refreshing && value is not null) SelectCodec(value);
}
}
public EditableField Width { get; }
public EditableField Height { get; }
/// <summary>"16:9".</summary>
public string AspectText => Editor.Plan is { } plan ? Aspect(plan.Setup.Encoder.Settings.Width, plan.Setup.Encoder.Settings.Height) : string.Empty;
public IReadOnlyList<Choice> FrameRates { get; } = [.. ExportPresets.FrameRates.Select(r => new Choice(FrameRateText.Format(r), "Editor.Value.Number", EditorText.FrameRate(r)))];
public Choice? SelectedFrameRate
{
get => FrameRates.FirstOrDefault(c => FrameRateText.TryParse((string)c.Value, out var r) && FrameRateText.AreEqual(r, Resolved.FrameRate));
set
{
if (!_refreshing && value?.Value is string rate) EditOverrides(o => o with { FrameRate = rate });
}
}
/// <summary>The preset's own frame rate is in force (no override).</summary>
public bool IsFrameRateAuto => Export.Overrides.FrameRate is null;
public string FrameRateAutoToolTip => Loc.L("Tooltips.Editor.Export.FrameRateAuto", EditorText.FrameRate(ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() }).FrameRate));
/// <summary>Bit rate in Mb/s (video) or quality 1–100 (JPEG, MJPEG, GIF).</summary>
public double Quality
{
get => IsBitRate ? (Editor.Plan?.Setup.Encoder.Settings.BitRate ?? Resolved.BitRate) / 1e6 : Resolved.Quality;
set
{
if (_refreshing) return;
if (IsBitRate) EditOverrides(o => o with { BitRate = (long)(double.Round(value) * 1e6) }, "Export.Quality");
else EditOverrides(o => o with { Quality = (int)double.Round(value) }, "Export.Quality");
}
}
public bool IsBitRate => !VideoCodecInfo.IsManaged(Resolved.Codec);
public double QualityMaximum => IsBitRate ? 400 : 100;
public bool IsQualityApplicable => IsBitRate || Resolved.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif;
public string? QualityNotApplicable => IsQualityApplicable ? null : Loc.L("Tooltips.Editor.NotApplicable.Lossless");
public string QualityText => IsBitRate ? EditorText.BitRate((long)(Quality * 1e6)) : Quality.ToString("0", Loc.Culture);
public string QualityToolTip => Loc.L(IsBitRate ? "Tooltips.Editor.Export.BitRate" : "Tooltips.Editor.Export.Quality");
public IReadOnlyList<Choice> Encoders { get => _encoders; private set => Set(ref _encoders, value); }
public Choice? SelectedEncoder
{
get => Encoders.FirstOrDefault(e => Equals(e.Value, Export.Overrides.Encoder ?? string.Empty));
set
{
if (!_refreshing && value?.Value is string name) EditOverrides(o => o with { Encoder = name.Length == 0 ? null : name });
}
}
/// <summary>"hardware", "software" (the word, not a colour, carries the state).</summary>
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<Choice> Depths { get => _depths; private set => Set(ref _depths, value); }
public Choice? SelectedDepth
{
get => Depths.FirstOrDefault(d => (int)d.Value == Resolved.BitDepth) ?? Depths[0];
set
{
if (_refreshing || value?.Value is not int depth || depth == Resolved.BitDepth) return;
EditOverrides(o => o with
{
BitDepth = depth,
Profile = Resolved.Codec == VideoCodec.Hevc ? (depth > 8 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain).ToString() : o.Profile,
});
}
}
public bool CanChooseDepth => Depths.Count > 1;
public EditableField NameTemplate { get; }
public IReadOnlyList<SaveChoice> SaveChoices { get => _saveChoices; private set => Set(ref _saveChoices, value); }
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;
/// <summary>What the encoder changed or cannot do (localised notices and render remarks).</summary>
public IReadOnlyList<string> Notices { get => _notices; private set => Set(ref _notices, value); }
/// <summary>"Previous renders of this sequence: 2 · last 2026-09-21".</summary>
public string HistoryText => Editor.Session.Content.Renders is { Count: > 0 } renders
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory");
public IReadOnlyList<string> Batch => Export.Batch;
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();
}
/// <summary>The choices that depend on the resolved codec (new lists only when they change, so selections stay bound).</summary>
private void UpdateLists()
{
var resolved = Resolved;
if (CodecChoices.FirstOrDefault()?.Container != resolved.Container) CodecChoices = [.. Codecs.Where(c => c.Container == resolved.Container)];
var encoders = EncoderChoices(resolved.Codec);
if (!encoders.Select(e => e.Value).SequenceEqual(Encoders.Select(e => e.Value))) Encoders = encoders;
int[] depths = resolved.Codec switch
{
VideoCodec.Hevc or VideoCodec.Av1 => [8, 10],
VideoCodec.PngSequence or VideoCodec.Tiff16Sequence => [8, 16],
_ => [resolved.BitDepth],
};
if (!depths.SequenceEqual(Depths.Select(d => (int)d.Value))) Depths = [.. depths.Select(d => new Choice(d, "Editor.Export.Depth", d))];
}
private void LoadCards() => Cards = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetCard(this, c))];
/// <summary>Estimates every card off the UI thread for the project as it is now (latest request wins).</summary>
private async Task EstimateCardsAsync()
{
var project = Editor.Session.Project;
var cards = Cards;
var plans = new ExportPlan?[cards.Count];
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<Choice> EncoderChoices(VideoCodec codec)
{
var names = Editor.Planner.Encoders.SelectMany(p => p.Capabilities).Where(c => c.Codec == codec).Select(c => c.Name).Distinct();
return [new Choice(string.Empty, "Editor.Export.EncoderAuto"), .. names.Select(n => new Choice(n, "Editor.Value.Text", n))];
}
private void EditExport(Func<ExportSettings, ExportSettings> change, string? mergeKey = null) =>
Editor.Session.Edit(p => p with { Export = change(p.Export) }, mergeKey);
private void EditOverrides(Func<ExportOverrides, ExportOverrides> change, string? mergeKey = null) =>
EditExport(e => e with { Overrides = change(e.Overrides) }, mergeKey);
private static string? ValidateSize(string text) =>
text.Length == 0 || (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) && v is >= 16 and <= 16384)
? null
: Loc.L("Tooltips.Editor.Export.SizeInvalid");
private static int? ParseSize(string text) => int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : null;
private static string? ValidateTemplate(string text) => ExportPlanner.NameError(ExportNaming.Expand(text, new ExportNameContext
{
Date = DateTime.Today,
PresetName = "x",
Codec = VideoCodec.H264,
}).Errors);
private static string Aspect(int width, int height)
{
if (width <= 0 || height <= 0) return string.Empty;
var gcd = (int)Gcd(width, height);
var (w, h) = (width / gcd, height / gcd);
return w > 64 || h > 64 ? (width / (double)height).ToString("0.00", Loc.Culture) + ":1" : $"{w}:{h}";
}
private static long Gcd(long a, long b)
{
while (b != 0) (a, b) = (b, a % b);
return a;
}
}
+112
View File
@@ -0,0 +1,112 @@
using Titano.Core.Advice;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Ui.Visuals;
namespace Titano.App.Editor;
/// <summary>
/// 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.
/// </summary>
public sealed class ExposureTab : EditorTab
{
private IReadOnlyList<ChartSeries> _series = [];
private IReadOnlyList<ChartLegendItem> _legend = [];
private IReadOnlyList<TimelineMarker> _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<int>(s, EditorSettings.DeflickerWindow, "Editor.Exposure.Window", "Tooltips.Editor.Exposure.Window", 5, 151, 2, "0", NoDeflicker),
new AutoNumberRow<double>(s, EditorSettings.DeflickerStrength, "Editor.Exposure.Strength", "Tooltips.Editor.Exposure.Strength", 0, 1, 0.05, "0.00", NoDeflicker),
new AutoChoiceRow<RegionMode>(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<int>(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<ChartSeries> Series { get => _series; private set => Set(ref _series, value); }
public IReadOnlyList<ChartLegendItem> Legend { get => _legend; private set => Set(ref _legend, value); }
public IReadOnlyList<TimelineMarker> Markers { get => _markers; private set => Set(ref _markers, value); }
/// <summary>"flicker −67 % · max step 0.21 EV".</summary>
public string? Summary { get => _summary; private set => Set(ref _summary, value); }
public Func<double, string> 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<ChartSeries> { new(Loc.L("Editor.Chart.Measured"), measured, "Brush.Sun") };
var legend = new List<ChartLegendItem> { 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<string>();
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);
}
}
+199
View File
@@ -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;
/// <summary>One frame of the Frames table; texts are formatted when shown (the table is virtualised).</summary>
public sealed class FrameRow(FramesTab owner, Frame frame, int index) : ObservableObject
{
/// <summary>Archive flags named in the table (the others are internal or shown elsewhere).</summary>
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;
/// <summary>Decode tier: the format, and "preview" when only the embedded preview decodes.</summary>
public string Tier => (frame.Flags & FrameFlags.PreviewOnly) != 0 ? Loc.L("Editor.Frames.PreviewOnly", frame.Format) : frame.Format.ToString();
/// <summary>"Excluded · black", the project's exclusion first, then the archive's flags.</summary>
public string Flags
{
get
{
var parts = new List<string>();
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");
/// <summary>The project's exclusions or hero changed.</summary>
public void Refresh()
{
OnPropertyChanged(nameof(IsExcluded));
OnPropertyChanged(nameof(IsHero));
OnPropertyChanged(nameof(Flags));
OnPropertyChanged(nameof(ExcludeText));
OnPropertyChanged(nameof(ExcludeToolTip));
}
}
/// <summary>A finding of the analyses with the frame to jump to.</summary>
public sealed record FindingItem(StatusKind Kind, string Text, int? Frame);
/// <summary>
/// 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.
/// </summary>
public sealed class FramesTab : EditorTab
{
private HashSet<int> _excluded = [];
private int? _hero;
private IReadOnlyList<FrameRow> _frames = [];
private IReadOnlyList<FindingItem> _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<FrameRow> Frames { get => _frames; private set => Set(ref _frames, value); }
public IReadOnlyList<FindingItem> Findings { get => _findings; private set => Set(ref _findings, value); }
/// <summary>The row of the current frame (selecting a row seeks the preview).</summary>
public FrameRow? Selected
{
get => _selected;
set
{
if (!Set(ref _selected, value) || value is null) return;
Editor.CurrentIndex = value.Index;
}
}
public int? HeroIndex => _hero;
/// <summary>"Frame 0413", or "Not set".</summary>
public string HeroText => _hero is { } h ? Loc.L("Editor.Frames.HeroValue", (h + 1).ToString("D4", Loc.Culture)) : Loc.L("Editor.Frames.HeroNone");
/// <summary>"12 frames", "None".</summary>
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<int>(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));
}
+3 -1
View File
@@ -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)
{
+159
View File
@@ -0,0 +1,159 @@
using Titano.Core.Advice;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Ui.Visuals;
namespace Titano.App.Editor;
/// <summary>Motion (BRIEF §12.3): motion blur, flow quality and stabilisation, with the measured camera path (shake) chart.</summary>
public sealed class MotionTab : EditorTab
{
private IReadOnlyList<ChartSeries> _series = [];
private IReadOnlyList<ChartLegendItem> _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<double>(s, EditorSettings.ShutterAngle, "Editor.Motion.Shutter", "Tooltips.Editor.Motion.Shutter", 0, 360, 15, "0", NoBlur),
new AutoChoiceRow<FlowQualitySetting>(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<double>(s, EditorSettings.StabilizeSmoothing, "Editor.Motion.Smoothing", "Tooltips.Editor.Motion.Smoothing", 2, 60, 1, "0", NoStabilize),
];
Refresh();
BuildChart();
}
public IReadOnlyList<ChartSeries> Series { get => _series; private set => Set(ref _series, value); }
public IReadOnlyList<ChartLegendItem> Legend { get => _legend; private set => Set(ref _legend, value); }
/// <summary>"shake 0.42 px · crop 1.8 %".</summary>
public string? Summary { get => _summary; private set => Set(ref _summary, value); }
public Func<double, string> YFormatter { get; } = v => Loc.L("Editor.Value.Pixels", v.ToString("0.#", Loc.Culture));
public override void OnContentChanged()
{
base.OnContentChanged();
BuildChart();
}
/// <summary>The camera path: per-frame content shifts accumulated from the first frame (gaps hold the last position).</summary>
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<string>
{
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;
}
}
/// <summary>Stack (BRIEF §12.3): median, mean or star-trail stacking; the chart shows the star field and cloud measurements.</summary>
public sealed class StackTab : EditorTab
{
private IReadOnlyList<ChartSeries> _series = [];
private IReadOnlyList<ChartLegendItem> _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();
}
/// <summary>The advisor never stacks on its own (a temporal median erases moving stars).</summary>
public override bool CanOptimise => false;
public IReadOnlyList<ChartSeries> Series { get => _series; private set => Set(ref _series, value); }
public IReadOnlyList<ChartLegendItem> Legend { get => _legend; private set => Set(ref _legend, value); }
public string? Summary { get => _summary; private set => Set(ref _summary, value); }
public Func<double, string> 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");
}
}
+393
View File
@@ -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;
/// <summary>One row of a section's settings column; <see cref="Refresh"/> re-reads the project after any change.</summary>
public abstract class SettingRow(string headerKey, string toolTipKey) : LocalizedViewModel
{
private bool _refreshing;
public string Header => Loc.L(headerKey);
/// <summary>What the control does and what moving it the wrong way costs (BRIEF §12.3).</summary>
public string ToolTip => Loc.L(toolTipKey);
public void Refresh()
{
_refreshing = true;
try
{
Read();
}
finally
{
_refreshing = false;
}
}
/// <summary>True while <see cref="Refresh"/> pushes values into the bindings (they must not edit the project back).</summary>
protected bool IsRefreshing => _refreshing;
protected abstract void Read();
/// <summary>The tooltip of an Auto pill: the stored reason, else the advisor's current one, else why there is none.</summary>
protected static string Reason<T>(EditorSession session, AutoSetting<T> 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");
}
}
/// <summary>
/// An Auto/manual slider (<see cref="Ui.Controls.AutoSlider"/>). Non-generic so the view can template it; the setting's
/// value type lives in <see cref="AutoNumberRow{T}"/>.
/// </summary>
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;
/// <summary>The slider value; the user moving it stores a manual value (one undo step per drag).</summary>
public double Value
{
get => _value;
set
{
if (!Set(ref _value, value) || IsRefreshing || _isAuto) return;
StoreManual(value);
}
}
/// <summary>Touching the slider clears it (manual at the current value); the reset button sets it.</summary>
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);
/// <summary>True: back to the advice; false: the value in force becomes manual.</summary>
protected abstract void StoreAuto(bool auto);
}
/// <summary><see cref="AutoNumberRow"/> over an <see cref="AutoSetting{T}"/> of <typeparamref name="T"/>.</summary>
public sealed class AutoNumberRow<T> : AutoNumberRow
where T : struct, INumber<T>
{
private readonly EditorSession _session;
private readonly AutoSetting<T> _setting;
private readonly Func<ProjectSettings, string?>? _notApplicable;
/// <param name="notApplicable">Why the setting does nothing with the current project (shown as "n/a"); null when it applies.</param>
public AutoNumberRow(EditorSession session, AutoSetting<T> setting, string headerKey, string toolTipKey, double minimum, double maximum, double step,
string format, Func<ProjectSettings, string?>? 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);
}
/// <summary>An Auto/manual switch (module on/off): the pill shows the advisor's choice, the switch takes it over.</summary>
public sealed class AutoSwitchRow : SettingRow
{
private readonly EditorSession _session;
private readonly AutoSetting<bool> _setting;
private bool _isOn;
private bool _isAuto;
private string _autoText = string.Empty;
private string? _autoReason;
public AutoSwitchRow(EditorSession session, AutoSetting<bool> 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); }
/// <summary>"Auto · On".</summary>
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);
}
}
/// <summary>A labelled value of a choice list.</summary>
public sealed record Choice(object Value, string LabelKey, params object[] Args)
{
public string Label => Loc.L(LabelKey, Args);
}
/// <summary>An Auto/manual drop-down (regions, flow quality, timing mode, aspect, playback rate); non-generic for the view.</summary>
public abstract class AutoChoiceRow(string headerKey, string toolTipKey, IReadOnlyList<Choice> options) : SettingRow(headerKey, toolTipKey)
{
private Choice? _selected;
private bool _isAuto;
private string _autoText = string.Empty;
private string? _autoReason;
private string? _notApplicableReason;
public IReadOnlyList<Choice> 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); }
/// <summary>"Auto · horizon".</summary>
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);
}
/// <summary><see cref="AutoChoiceRow"/> over an <see cref="AutoSetting{T}"/> of <typeparamref name="T"/>.</summary>
public sealed class AutoChoiceRow<T> : AutoChoiceRow
where T : notnull
{
private readonly EditorSession _session;
private readonly AutoSetting<T> _setting;
private readonly Func<ProjectSettings, string?>? _notApplicable;
public AutoChoiceRow(EditorSession session, AutoSetting<T> setting, string headerKey, string toolTipKey, IReadOnlyList<Choice> options,
Func<ProjectSettings, string?>? 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);
}
}
/// <summary>A plain slider (no advice): exposure offset, placement, stack length, fit-to duration.</summary>
public sealed class NumberRow : SettingRow
{
private readonly EditorSession _session;
private readonly Func<ProjectSettings, double> _get;
private readonly Func<ProjectSettings, double, ProjectSettings> _set;
private readonly Func<double, string> _display;
private readonly Func<ProjectSettings, string?>? _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<ProjectSettings, double> get, Func<ProjectSettings, double, ProjectSettings> set, Func<double, string> display,
Func<ProjectSettings, string?>? 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);
}
}
/// <summary>A plain drop-down (stacking mode).</summary>
public sealed class ChoiceRow : SettingRow
{
private readonly EditorSession _session;
private readonly Func<ProjectSettings, object> _get;
private readonly Func<ProjectSettings, object, ProjectSettings> _set;
private Choice? _selected;
public ChoiceRow(EditorSession session, string headerKey, string toolTipKey, IReadOnlyList<Choice> options, Func<ProjectSettings, object> get,
Func<ProjectSettings, object, ProjectSettings> set)
: base(headerKey, toolTipKey)
{
(_session, _get, _set, Options) = (session, get, set, options);
Refresh();
}
public IReadOnlyList<Choice> 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));
}
}
/// <summary>A measured value shown read-only, "n/a" with the reason when there is none (colour temperature).</summary>
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();
}
+121 -4
View File
@@ -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;
/// <summary>Sequence editor (BRIEF §12.3).</summary>
public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
/// <summary>
/// The Sequence section (BRIEF §12.3): opens the sequence the Library (or Jobs) chose into an <see cref="EditorViewModel"/>
/// and closes the previous one after saving it; without a sequence it shows the empty state.
/// </summary>
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; }
/// <summary>The open sequence; null shows the empty state.</summary>
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;
/// <summary>"Titano — Harbour sunset" while a sequence is open.</summary>
public override string Title => _editor?.Title ?? Label;
/// <summary>Opens <paramref name="sequenceId"/> (the editor of another sequence is saved and closed first).</summary>
public Task OpenAsync(Guid sequenceId)
{
_switch = SwitchAsync(_switch, sequenceId);
return _switch;
}
/// <summary>Saves and closes the open sequence.</summary>
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));
}
}
}
@@ -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()
{