CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
345 lines
17 KiB
C#
345 lines
17 KiB
C#
using Chronos.Data.Projects;
|
|
using System.Collections.Concurrent;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Text.Json;
|
|
using Chronos.Core.Advice;
|
|
using Chronos.Core.Analysis;
|
|
using Chronos.Core.Analysis.Deep;
|
|
using Chronos.Core.Diagnostics;
|
|
using Chronos.Core.Imaging;
|
|
using Chronos.Core.Localization;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Core.Project;
|
|
using Chronos.Core.Render;
|
|
using Chronos.Data.Archiving.Jobs;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Data.Sync;
|
|
using Chronos.Protocol;
|
|
using Chronos.Protocol.Client;
|
|
|
|
namespace Chronos.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
|
|
/// (<see cref="ProjectMerge"/>) when the two changes touch different settings. A setting both changed to different
|
|
/// values is a conflict the user settles (BRIEF §14.5 "explicit conflict prompt"): <see cref="ProjectConflictException"/>,
|
|
/// and nothing is sent until the editor's next save names the server's settings as its basis. Nothing is written to a
|
|
/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
|
|
/// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames
|
|
/// throws <see cref="ProxiesOutdatedException"/>, and frames that change on the server while the sequence is open make
|
|
/// it <see cref="IsOutdated"/> (read-only, nothing saved or rendered). Saves name the frames version the editor's frames
|
|
/// are at, so the server refuses one made against frames it no longer has even before its event arrives.
|
|
/// </summary>
|
|
public sealed class RemoteSequenceSource : ISequenceSource
|
|
{
|
|
private const int SaveAttempts = 3;
|
|
|
|
private readonly RemoteSequence _remote;
|
|
private readonly IRemoteSequenceApi _api;
|
|
private readonly IRenderFrameSource _frames;
|
|
private readonly IFrameSource _pixels;
|
|
private readonly ServerJobs _jobs;
|
|
private readonly bool _noEditRight;
|
|
private readonly int _serverFormat;
|
|
private Stored? _stored;
|
|
private int _framesVersion = -1;
|
|
private int _outdated;
|
|
private int _disposed;
|
|
|
|
/// <param name="readOnly">The account may look at the sequence but not change it (no Edit right on the server).</param>
|
|
/// <param name="serverFormat">
|
|
/// The highest settings format the server reads (<see cref="Chronos.App.Server.SyncHost.SettingsFormat"/>; an older server's 1): settings
|
|
/// that need more are never sent to it (owner review 1, phase 4), it would store them and then fail every render of them.
|
|
/// </param>
|
|
public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder, bool readOnly = false,
|
|
int serverFormat = ProjectSettings.CurrentVersion)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(remote);
|
|
ArgumentNullException.ThrowIfNull(api);
|
|
ArgumentNullException.ThrowIfNull(decoder);
|
|
_remote = remote;
|
|
_api = api;
|
|
_noEditRight = readOnly;
|
|
_serverFormat = serverFormat;
|
|
_frames = remote.OpenFrames(decoder);
|
|
_pixels = (IFrameSource)_frames;
|
|
_jobs = new ServerJobs(api, remote.Sequence.Id, remote.Sequence.DisplayTitle, job => JobChanged?.Invoke(job), OnEventAsync, OnReconnectedAsync);
|
|
}
|
|
|
|
public bool IsRemote => true;
|
|
|
|
public bool IsReadOnly => _noEditRight || IsOutdated;
|
|
|
|
public bool IsOutdated => Volatile.Read(ref _outdated) == 1;
|
|
|
|
public event Action? ReadOnlyChanged;
|
|
|
|
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));
|
|
if (!SameFrames(manifest)) throw Outdated();
|
|
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
|
var report = await Call(() => _api.GetAnalysisReportAsync(Id, cancellationToken));
|
|
return await Task.Run(() =>
|
|
{
|
|
var project = Parse(manifest.SettingsJson);
|
|
Volatile.Write(ref _stored, new Stored(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,
|
|
PreviewOnlyCount = dto.PreviewOnlyCount,
|
|
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,
|
|
Sha256 = r.Sha256,
|
|
Kind = r.Kind,
|
|
}).ToList();
|
|
var (deep, otherFrames) = Report(report, frames.Count);
|
|
return new SequenceContent(sequence, frames, project, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
|
|
{
|
|
DeepOfOtherFrames = otherFrames,
|
|
};
|
|
}, cancellationToken);
|
|
}
|
|
|
|
/// <remarks>Read from the server's manifest: a sequence whose frames are not this PC's becomes outdated.</remarks>
|
|
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (IsOutdated) return false;
|
|
return Compare(await Call(() => _api.GetManifestAsync(Id, cancellationToken)));
|
|
}
|
|
|
|
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
|
{
|
|
if ((uint)index >= (uint)_remote.Frames.Count) return null;
|
|
// The loader decodes synchronously: an async delegate keeps a superseded decode's cancellation in user code (R4).
|
|
return await Task.Run(async () => await _pixels.LoadAsync(index, maxLongEdge, cancellationToken).ConfigureAwait(false), 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, version) = Volatile.Read(ref _stored) ?? throw new InvalidOperationException("LoadAsync first.");
|
|
var changedThere = !ProjectMerge.SameValues(stored, basis);
|
|
var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project;
|
|
if (ProjectMerge.SameValues(merged, stored)) return merged;
|
|
if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
|
if (_noEditRight) throw new EditorException(Loc.L("Editor.Error.RemoteReadOnly"));
|
|
// A turn, a mirror, a straighten or a look needs format 2, which an older server cannot read: kept here (the
|
|
// toast says why) until the edit is undone or the server is updated.
|
|
if (ServerJobs.NeedsNewerServer(merged.WrittenFormat, _serverFormat) is { } newer) throw new EditorException(newer);
|
|
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
|
|
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
|
|
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
|
|
// The positions name the frames this editor holds: the server refuses them (409 frames_conflict) once its
|
|
// frames changed, also before its event says so. A server that predates the check ignores it.
|
|
var request = new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero, Volatile.Read(ref _framesVersion));
|
|
try
|
|
{
|
|
var updated = await Call(() => _api.UpdateSequenceAsync(Id, request, cancellationToken));
|
|
Volatile.Write(ref _stored, new Stored(merged, updated.SettingsVersion));
|
|
return merged;
|
|
}
|
|
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
|
{
|
|
// Changed on the server since this editor read it, its settings or its frames: other frames make the
|
|
// editor outdated (its proxies are not the server's), otherwise the edit merges again on top of the
|
|
// server's settings, at the frames version they are at.
|
|
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
|
if (!SameFrames(manifest)) throw Outdated();
|
|
if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex);
|
|
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
|
Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <remarks>
|
|
/// The server queues every job at the user's priority; another priority ("Add to queue") is set right after. A
|
|
/// render embeds the project, whose frame positions mean nothing once the frames changed: refused while outdated.
|
|
/// </remarks>
|
|
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(request);
|
|
if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
|
return _jobs.SubmitAsync(request, cancellationToken);
|
|
}
|
|
|
|
public Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) => _jobs.ListAsync(cancellationToken);
|
|
|
|
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.CancelAsync(jobId, cancellationToken);
|
|
|
|
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.RetryAsync(jobId, cancellationToken);
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
|
try
|
|
{
|
|
// Stops following the events, and closes the connection.
|
|
await _jobs.DisposeAsync();
|
|
}
|
|
finally
|
|
{
|
|
if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
/// <summary>The server's events besides the jobs': frames added or removed on the server make the sequence outdated.</summary>
|
|
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
|
|
{
|
|
if (e is SequenceChangedEvent changed && changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion))
|
|
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>A frames change announced while the event socket was down is found now rather than at the next save.</summary>
|
|
private async Task OnReconnectedAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Frames added or removed on the server: whether this PC's frames are still the sequence's.</summary>
|
|
private async Task CheckFramesAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
Compare(await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false));
|
|
}
|
|
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|
|
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
|
{
|
|
Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} could not be compared: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Takes the server's frames as <paramref name="manifest"/> lists them: their frames version when they are this PC's
|
|
/// (saves name it), outdated otherwise. Returns whether they are.
|
|
/// </summary>
|
|
private bool Compare(SequenceManifest manifest)
|
|
{
|
|
if (!SameFrames(manifest))
|
|
{
|
|
MarkOutdated();
|
|
return false;
|
|
}
|
|
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames).</summary>
|
|
private bool SameFrames(SequenceManifest manifest) =>
|
|
manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id));
|
|
|
|
/// <summary>The frames changed on the server: from now on the project is only shown.</summary>
|
|
private ProxiesOutdatedException Outdated()
|
|
{
|
|
MarkOutdated();
|
|
return new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
|
}
|
|
|
|
private void MarkOutdated()
|
|
{
|
|
if (Interlocked.Exchange(ref _outdated, 1) == 1) return;
|
|
Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} changed on the server; its proxies are out of date");
|
|
ReadOnlyChanged?.Invoke();
|
|
}
|
|
|
|
/// <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="EditorException">The settings are not a project or come from a newer Chronos.</exception>
|
|
private static ProjectSettings Parse(string? json)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
|
|
try
|
|
{
|
|
return ProjectSettings.FromJson(json);
|
|
}
|
|
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
|
{
|
|
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
|
|
}
|
|
}
|
|
|
|
/// <summary>The server's deep report when it describes the frames this PC has; whether one of another number of frames came instead.</summary>
|
|
private (DeepAnalysisReport? Report, bool OtherFrames) Report(string? json, int frameCount)
|
|
{
|
|
if (json is null) return (null, false);
|
|
try
|
|
{
|
|
var report = DeepAnalysisReport.FromJson(json);
|
|
return report.FrameCount == frameCount ? (report, false) : (null, true);
|
|
}
|
|
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, false);
|
|
}
|
|
}
|
|
|
|
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
|
|
private static Task<T> Call<T>(Func<Task<T>> call) => ServerJobs.Call(call);
|
|
|
|
/// <summary>The server's settings as last read or written, with the version a save must name.</summary>
|
|
private sealed record Stored(ProjectSettings Project, int Version);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Settings the editor changed were changed to other values on the server meanwhile (BRIEF §14.5): nothing is saved
|
|
/// until the user keeps the editor's values or takes the server's (<see cref="EditorSession.ResolveConflict"/>).
|
|
/// </summary>
|
|
/// <param name="server">The server's project now.</param>
|
|
/// <param name="differences">The settings both changed: the editor's value, then the server's.</param>
|
|
public sealed class ProjectConflictException(string message, ProjectSettings server, IReadOnlyList<SettingsDifference> differences) : IOException(message)
|
|
{
|
|
public ProjectSettings Server { get; } = server;
|
|
|
|
public IReadOnlyList<SettingsDifference> Differences { get; } = differences;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched):
|
|
/// they must be fetched again before the sequence can be edited.
|
|
/// </summary>
|
|
public sealed class ProxiesOutdatedException(string message) : EditorException(message);
|