feat(editor): open server sequences with proxies, hero frame to the index, export sync and saved copies
Server sequences that are not in the local index open through a RemoteSequenceSource: proxies from the cache, project from the server's settings with their version (a 409 merges again), analysis report from the server, analyses and renders posted as server jobs (one per preset) and followed through the server's events. Set hero now reaches the index (SequenceEdit.HeroFrameId) so the Library card shows it. The Export tab gains the Sync option (remembered in the project) and restores "Save both" copies through undo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
36 files changed
+1307
-116
No files matched your search
@@ -0,0 +1,302 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A server sequence opened with proxies (BRIEF §4.4, §14.5 "edit with proxies, render where the originals are"):
|
||||
/// frames and thumbnails from this PC's proxy cache (<see cref="RemoteSequence.OpenFrames"/>), the project from the
|
||||
/// server's settings with their version, the deep analysis from the server's report. Saves send the settings with the
|
||||
/// version they were made from; a 409 (someone changed them meanwhile) reads the server's settings and merges again as
|
||||
/// the local archive does (<see cref="ProjectMerge"/>: the editor wins on members both changed). Nothing is written to a
|
||||
/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
|
||||
/// </summary>
|
||||
public sealed class RemoteSequenceSource : ISequenceSource
|
||||
{
|
||||
private const int SaveAttempts = 3;
|
||||
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
|
||||
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly RemoteSequence _remote;
|
||||
private readonly IRemoteSequenceApi _api;
|
||||
private readonly IRenderFrameSource _frames;
|
||||
private readonly IFrameSource _pixels;
|
||||
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
|
||||
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Task _listening;
|
||||
private ProjectSettings? _stored;
|
||||
private int _version;
|
||||
|
||||
public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
ArgumentNullException.ThrowIfNull(api);
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
_remote = remote;
|
||||
_api = api;
|
||||
_frames = remote.OpenFrames(decoder);
|
||||
_pixels = (IFrameSource)_frames;
|
||||
var stopping = _stopping.Token;
|
||||
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
|
||||
}
|
||||
|
||||
public bool IsRemote => true;
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>The server sequence's id.</summary>
|
||||
public Guid Id => _remote.Sequence.Id;
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var dto = await Call(() => _api.GetSequenceAsync(Id, cancellationToken));
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
var report = await Call(() => _api.GetAnalysisReportAsync(Id, cancellationToken));
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var project = Parse(manifest.SettingsJson);
|
||||
(_stored, _version) = (project, manifest.SettingsVersion);
|
||||
var frames = _remote.Frames;
|
||||
var sequence = _remote.Sequence with
|
||||
{
|
||||
Title = dto.Title,
|
||||
Tags = dto.Tags,
|
||||
Rating = dto.Rating,
|
||||
Notes = dto.Notes,
|
||||
Status = (SequenceStatus)dto.Status,
|
||||
RenderedCount = dto.RenderedCount,
|
||||
HeroFrameId = dto.HeroFrameId,
|
||||
WarningCount = dto.WarningCount,
|
||||
SettingsJson = manifest.SettingsJson,
|
||||
SettingsVersion = manifest.SettingsVersion,
|
||||
UpdatedAt = dto.UpdatedAt,
|
||||
};
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
var renders = manifest.Renders.OrderByDescending(r => r.Created).Select(r => new Render
|
||||
{
|
||||
Id = r.Id,
|
||||
SequenceId = Id,
|
||||
PresetName = r.PresetName,
|
||||
OutputPath = string.Empty,
|
||||
Codec = r.Codec,
|
||||
Width = r.Width,
|
||||
Height = r.Height,
|
||||
Fps = r.Fps,
|
||||
DurationSeconds = r.DurationSeconds,
|
||||
Bytes = r.Bytes,
|
||||
Created = r.Created,
|
||||
ProducedBy = r.ProducedBy,
|
||||
}).ToList();
|
||||
return new SequenceContent(sequence, frames, project, LightAnalyzer.Analyze(frames), Report(report, frames.Count), context.SourceWidth,
|
||||
context.SourceHeight, null, renders, []);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((uint)index >= (uint)_remote.Frames.Count) return null;
|
||||
return await Task.Run(() => _pixels.LoadAsync(index, maxLongEdge, cancellationToken).AsTask(), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var stored = _stored ?? throw new InvalidOperationException("LoadAsync first.");
|
||||
var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
|
||||
if (ProjectMerge.SameValues(merged, stored)) return merged;
|
||||
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
|
||||
try
|
||||
{
|
||||
var updated = await Call(() => _api.UpdateSequenceAsync(Id, new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), _version, hero),
|
||||
cancellationToken));
|
||||
(_stored, _version) = (merged, updated.SettingsVersion);
|
||||
return merged;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
// Changed on the server since this editor read it: merge again on top of the server's settings.
|
||||
if (attempt == SaveAttempts) throw new IOException(Loc.L("Editor.Error.SaveConflict"), ex);
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
(_stored, _version) = (Parse(manifest.SettingsJson), manifest.SettingsVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
|
||||
// The server's events may have reported the job already; its first state never replaces a later one.
|
||||
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) JobChanged?.Invoke(job);
|
||||
return dto.Id;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
|
||||
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
|
||||
foreach (var job in mine) _jobs[job.Id] = job;
|
||||
return mine;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _stopping.CancelAsync();
|
||||
await _listening;
|
||||
_stopping.Dispose();
|
||||
if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
|
||||
_api.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Follows the server's job events, reconnecting with a growing delay (events lost meanwhile are read back from the job).</summary>
|
||||
private async Task ListenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var failures = 0;
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
failures = 0;
|
||||
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}");
|
||||
}
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromTicks(Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10))), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job):
|
||||
Publish(job with
|
||||
{
|
||||
State = JobState.Running,
|
||||
ProgressDone = progress.Done,
|
||||
ProgressTotal = progress.Total,
|
||||
ItemsPerSecond = progress.ItemsPerSecond,
|
||||
Eta = progress.EtaSeconds is { } eta ? TimeSpan.FromSeconds(eta) : null,
|
||||
});
|
||||
break;
|
||||
case JobStateEvent state when !_foreign.ContainsKey(state.JobId):
|
||||
await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
|
||||
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (JobWire.FromDto(await _api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
|
||||
else _foreign[jobId] = 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
|
||||
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
|
||||
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void Publish(Job job)
|
||||
{
|
||||
_jobs[job.Id] = job;
|
||||
JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
|
||||
|
||||
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
|
||||
private Guid HeroFrameId(ProjectSettings project) =>
|
||||
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
|
||||
|
||||
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</exception>
|
||||
private static ProjectSettings Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(json);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server's deep report when it describes the frames this PC has.</summary>
|
||||
private DeepAnalysisReport? Report(string? json, int frameCount)
|
||||
{
|
||||
if (json is null) return null;
|
||||
try
|
||||
{
|
||||
var report = DeepAnalysisReport.FromJson(json);
|
||||
return report.FrameCount == frameCount ? report : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("editor", $"The analysis of {_remote.Sequence.DisplayTitle} on the server cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
|
||||
private static async Task<T> Call<T>(Func<Task<T>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await call();
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user