fix(proxies): judge proxies by one rule and record tiers and reports as they stand

- ArchiveImages.IsProxyOf compares capture times to the microsecond the index
  keeps (sidecars and Exif keep 100 ns ticks), and for frames read through
  proxies also applies the policy's size rule, so the proxy pass, uploads,
  thumbnails, renders, analyses, tiers, manifests and downloads agree.
- Proxy headers are cached per file while length and write time are unchanged
  (and the file has settled), so manifests cost a stat per proxy.
- FrameTiers.RecordAsync checks proxy presence when it writes the sidecar and
  returns the sequence's frames as they are, so a deep analysis or render that
  ran while proxies arrived no longer flags the frames preview-only again, and
  the analysis advises from the current flags.
- Server manifests ignore ProxiesBuilt for frames the server cannot decode, so
  frames added since the last proxy pass are asked for their proxies.
- GET /sequences/{id}/analysis/report answers 404 for a report that found
  frames unreadable before their proxies arrived (DeepReports.ReadCurrentAsync).
- The deep checkpoint key marks only frames read from proxies, so checkpoints
  written by earlier versions still resume.

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-12 16:52:30 +00:00
1 parent b4f1fa32d5
commit 4014b0e669
16 files changed
+514 -99

No files matched your search

+99 -21
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
@@ -47,9 +48,26 @@ public sealed class ArchiveImages
private const int CommitFrames = 200;
private const int ProbeLongEdge = 64;
/// <summary>Proxy headers kept at most (<see cref="Headers"/>): some 30 MB, the proxies of a few large sequences.</summary>
private const int MaxHeaders = 1 << 17;
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
/// <summary>
/// Age of a proxy file under which its header is not kept: a file system's clock may give a file written again at
/// once (with the same length) the same write time, at a granularity of up to two seconds.
/// </summary>
private static readonly TimeSpan Settling = TimeSpan.FromSeconds(3);
private static readonly ImageDecoder ServerDecoders = DecoderFactory.CreateServer();
/// <summary>
/// The capture time and size of proxies read lately, by path, while the file keeps its length and write time: the
/// server's manifests and tier records check every proxy of a sequence, so an unchanged one costs a stat.
/// </summary>
private static readonly ConcurrentDictionary<string, ProxyHeader> Headers = new(StringComparer.Ordinal);
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
@@ -90,12 +108,18 @@ public sealed class ArchiveImages
/// <summary>
/// Whether the file at <paramref name="proxy"/> (a sequence's <c>proxies/0001.jpg</c>) is the proxy of the frame
/// captured at <paramref name="capturedAt"/>: its Exif capture time is the frame's, or the frame has none to compare
/// with. Proxies are named by frame index, so one left by a frame renumbered since (frames inserted before it) is
/// another photo's: renders, analyses and the server's manifests and downloads treat it as missing, and the proxy
/// pass removes it (<see cref="BuildProxiesAsync"/>).
/// captured at <paramref name="capturedAt"/>, of <paramref name="width"/> × <paramref name="height"/>: its Exif capture
/// time is the frame's to the microsecond (the index's precision), or the frame has none to compare with; and, for a
/// frame whose original this host takes from its proxy (<paramref name="policy"/> given: the archive's), it is not
/// smaller than the policy's (<see cref="TooSmall"/>: one an earlier version made from an embedded preview). Proxies
/// are named by frame index, so one left by a frame renumbered since (frames inserted before it) is another photo's.
/// Renders, analyses, decode tiers and the server's manifests and downloads treat a proxy that fails this as missing,
/// and the proxy pass removes it (<see cref="BuildProxiesAsync"/>).
/// </summary>
public static bool IsProxyOf(string proxy, DateTime? capturedAt) => ReadProxy(proxy, capturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
/// <param name="policy">The archive's proxy policy for a frame whose original this host cannot decode (its proxy comes
/// from a client or render node); null for one this host decodes and makes the proxy of itself.</param>
public static bool IsProxyOf(string proxy, DateTime? capturedAt, int width, int height, ProxyPolicy? policy) =>
Check(proxy, capturedAt, width, height, policy).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
/// <summary>
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxy"/>):
@@ -151,11 +175,13 @@ public sealed class ArchiveImages
if (frame.CapturedAt is { } captured)
{
using var stream = new MemoryStream(jpeg, writable: false);
if (MetadataReader.Read(stream, "proxy.jpg").CapturedAt != captured) return ProxyStoreResult.WrongFrame;
if (!SameCapture(MetadataReader.Read(stream, "proxy.jpg").CapturedAt, captured)) return ProxyStoreResult.WrongFrame;
}
var folder = paths.Sequence(sequence.Folder);
Directory.CreateDirectory(folder.Proxies);
AtomicFile.WriteAllBytes(folder.Proxy(frame.Index), jpeg);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
Headers.TryRemove(path, out _);
return ProxyStoreResult.Stored;
}
@@ -167,7 +193,8 @@ public sealed class ArchiveImages
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ThumbnailPolicy;
var archiveManifest = ManifestStore.ReadArchive(paths.ManifestPath);
var policy = archiveManifest.ThumbnailPolicy;
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
int built = 0, reused = 0, undecodable = 0;
@@ -198,7 +225,7 @@ public sealed class ArchiveImages
// preview, whose smaller thumbnail the proxy's replaces.
var fromProxy = false;
if (NeedsProxy(frame.Format) && !(current && edge >= policy.LongEdge)
&& ReadProxy(folder.Proxy(frame.I), frame.CapturedAt) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
&& Check(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, archiveManifest.ProxyPolicy) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
fromProxy = !current || edge < System.Math.Min(policy.LongEdge, proxy.LongEdge);
if (current && !fromProxy)
{
@@ -227,7 +254,7 @@ public sealed class ArchiveImages
}
pack.Commit();
}
await _tiers.RecordAsync(archive, sequence, tiers, cancellationToken).ConfigureAwait(false);
await _tiers.RecordAsync(archive, sequence, tiers, proxies: false, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ThumbsBuilt, complete && undecodable == 0, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable);
}
@@ -252,7 +279,6 @@ public sealed class ArchiveImages
int built = 0, reused = 0, undecodable = 0, waiting = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var proxied = new Dictionary<Guid, bool>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
var cadence = new Cadence();
for (var i = 0; i < manifest.Frames.Count; i++)
@@ -266,11 +292,9 @@ public sealed class ArchiveImages
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
// does one smaller than the policy's (made here from a preview by an earlier version).
var (check, longEdge) = ReadProxy(path, frame.CapturedAt);
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && TooSmall(longEdge, frame.W, frame.H, policy)) check = ProxyCheck.Stale;
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
if (check == ProxyCheck.Stale) File.Delete(path);
proxied[frame.Id] = usable;
if (check == ProxyCheck.Stale) Delete(path);
complete &= usable;
if (done) continue;
if (usable) reused++;
@@ -292,6 +316,7 @@ public sealed class ArchiveImages
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken, companions.GetValueOrDefault(frame.Id))) is { } image)
{
AtomicFile.WriteAllBytes(path, image.Jpeg);
Headers.TryRemove(path, out _);
built++;
}
else
@@ -301,7 +326,7 @@ public sealed class ArchiveImages
}
if (cadence.Due()) await checkpoint(i + 1, manifest.Frames.Count).ConfigureAwait(false);
}
await _tiers.RecordAsync(archive, sequence, tiers, proxied, cancellationToken).ConfigureAwait(false);
await _tiers.RecordAsync(archive, sequence, tiers, proxies: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ProxiesBuilt, complete, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable, waiting);
}
@@ -317,27 +342,80 @@ public sealed class ArchiveImages
/// <summary>The frame has no capture time to compare with.</summary>
Unverifiable,
/// <summary>Made from another frame (frames were renumbered since).</summary>
/// <summary>Made from another frame (frames were renumbered since), or too small (<see cref="Check"/>).</summary>
Stale,
}
/// <summary>A proxy's Exif capture time and oriented long edge, read when the file had this length and write time.</summary>
private readonly record struct ProxyHeader(long Length, long WriteTicks, DateTime? CapturedAt, int LongEdge);
/// <summary>
/// Where the proxy at <paramref name="proxy"/> stands for the frame captured at <paramref name="capturedAt"/>, of
/// <paramref name="width"/> × <paramref name="height"/>, and its long edge: <see cref="ProxyCheck.Stale"/> also when
/// <paramref name="policy"/> is given and the proxy is <see cref="TooSmall"/> for it (<see cref="IsProxyOf"/>).
/// </summary>
private static (ProxyCheck Check, int LongEdge) Check(string proxy, DateTime? capturedAt, int width, int height, ProxyPolicy? policy)
{
var (check, longEdge) = ReadProxy(proxy, capturedAt);
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && policy is not null && TooSmall(longEdge, width, height, policy)) check = ProxyCheck.Stale;
return (check, longEdge);
}
/// <summary>Where the proxy at <paramref name="proxy"/> stands for the frame captured at <paramref name="capturedAt"/>, and its long edge.</summary>
private static (ProxyCheck Check, int LongEdge) ReadProxy(string proxy, DateTime? capturedAt)
{
if (!File.Exists(proxy)) return (ProxyCheck.Missing, 0);
if (ReadHeader(proxy) is not { } header) return (ProxyCheck.Missing, 0);
var check = capturedAt is not { } captured ? ProxyCheck.Unverifiable : SameCapture(header.CapturedAt, captured) ? ProxyCheck.Current : ProxyCheck.Stale;
return (check, header.LongEdge);
}
/// <summary>
/// The header of the proxy at <paramref name="proxy"/>; null when there is none or it cannot be read. Kept in
/// <see cref="Headers"/> while the file's length and write time stay as they were when it was read (taken first, so
/// a file replaced meanwhile is read again next time), once the file is older than <see cref="Settling"/>; a full
/// cache starts over.
/// </summary>
private static ProxyHeader? ReadHeader(string proxy)
{
try
{
var file = new FileInfo(proxy);
if (!file.Exists) return null;
var (length, written) = (file.Length, file.LastWriteTimeUtc);
if (Headers.TryGetValue(proxy, out var cached) && cached.Length == length && cached.WriteTicks == written.Ticks) return cached;
var metadata = MetadataReader.Read(proxy);
var (width, height) = metadata.OrientedSize;
var check = capturedAt is null ? ProxyCheck.Unverifiable : metadata.CapturedAt == capturedAt ? ProxyCheck.Current : ProxyCheck.Stale;
return (check, System.Math.Max(width, height));
var header = new ProxyHeader(length, written.Ticks, metadata.CapturedAt, System.Math.Max(width, height));
if (DateTime.UtcNow - written < Settling)
{
Headers.TryRemove(proxy, out _);
return header;
}
if (Headers.Count >= MaxHeaders) Headers.Clear();
Headers[proxy] = header;
return header;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return (ProxyCheck.Missing, 0);
return null;
}
}
/// <summary>
/// Whether a proxy's Exif capture time is the frame's <paramref name="captured"/> to the microsecond: the index keeps
/// capture times to the microsecond, sidecars and Exif to the 100 ns tick, so a proxy made from either record of the
/// frame (here from the sidecar, by a client from the server's index) matches both.
/// </summary>
private static bool SameCapture(DateTime? proxy, DateTime captured) =>
proxy is { } time && time.Ticks / TimeSpan.TicksPerMicrosecond == captured.Ticks / TimeSpan.TicksPerMicrosecond;
/// <summary>Removes the proxy at <paramref name="path"/> and what is known of it.</summary>
private static void Delete(string path)
{
File.Delete(path);
Headers.TryRemove(path, out _);
}
/// <summary>
/// Whether a proxy whose long edge is <paramref name="longEdge"/> falls short of the policy's for a frame of
/// <paramref name="width"/> × <paramref name="height"/> (the policy's long edge, or the frame's own when smaller or
+22 -17
View File
@@ -51,25 +51,26 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
return tiers;
}
/// <inheritdoc cref="RecordAsync(Archive, Sequence, IReadOnlyDictionary{Guid, FileTier}, IReadOnlyDictionary{Guid, bool}?, CancellationToken)"/>
public Task<IReadOnlyList<SidecarFrame>> RecordAsync(Archive archive, Sequence sequence, IReadOnlyDictionary<Guid, FileTier> tiers,
CancellationToken cancellationToken) => RecordAsync(archive, sequence, tiers, null, cancellationToken);
/// <summary>
/// Records <paramref name="tiers"/> (by frame id) where they change what the sidecar says, and returns the frames that
/// changed as they are now. Frames no longer in the sequence are ignored.
/// Records <paramref name="tiers"/> (by frame id) where they change what the sidecar says, and returns the sequence's
/// frames as the sidecar has them afterwards (none when there was nothing to record). Frames no longer in the
/// sequence are ignored. The <see cref="FrameFlags.PreviewOnly"/> flag of a frame whose original this host reads
/// through its proxy follows whether its own proxy is there when the sidecar is written
/// (<see cref="ArchiveImages.IsProxyOf"/>, <see cref="SequenceFrames.WithProxy"/>), not when the caller looked: proxies
/// arrive while analyses and renders run, and another worker may have recorded them already.
/// </summary>
/// <param name="proxied">By frame id, for frames whose original this host reads through its proxy, whether the frame's
/// own proxy is there now (<see cref="SequenceFrames.WithProxy"/>); their <see cref="FrameFlags.PreviewOnly"/> follows
/// it even where no tier is recorded.</param>
/// <param name="proxies">Whether every such frame follows its proxy even where no tier is recorded (analyses and the
/// proxy pass); otherwise only the frames in <paramref name="tiers"/> do.</param>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
public async Task<IReadOnlyList<SidecarFrame>> RecordAsync(Archive archive, Sequence sequence, IReadOnlyDictionary<Guid, FileTier> tiers,
IReadOnlyDictionary<Guid, bool>? proxied, CancellationToken cancellationToken)
bool proxies, CancellationToken cancellationToken)
{
if (tiers.Count == 0 && proxied is not { Count: > 0 }) return [];
if (tiers.Count == 0 && !proxies) return [];
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
var changed = new List<SidecarFrame>();
ProxyPolicy? policy = null;
var manifest = await writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
{
changed.Clear();
@@ -79,10 +80,15 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
{
var frame = m.Frames[i];
frames[i] = frame;
bool? hasProxy = proxied is not null && proxied.TryGetValue(frame.Id, out var found) ? found : null;
var tier = tiers.GetValueOrDefault(frame.Id);
if (tier is null && !proxies) continue;
bool? proxied = (frame.Flags & FrameFlags.Missing) == 0 && ArchiveImages.NeedsProxy(writer.Options.Decoder, frame.Format)
? ArchiveImages.IsProxyOf(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H,
policy ??= ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy)
: null;
SidecarFrame updated;
if (tiers.TryGetValue(frame.Id, out var tier)) updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format), hasProxy == true);
else if (hasProxy is { } proxy) updated = SequenceFrames.WithProxy(frame, proxy);
if (tier is not null) updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format), proxied == true);
else if (proxied is { } own) updated = SequenceFrames.WithProxy(frame, own);
else continue;
if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH)
continue;
@@ -98,14 +104,13 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
UpdatedAt = DateTimeOffset.UtcNow,
};
}, cancellationToken).ConfigureAwait(false);
if (changed.Count == 0) return [];
if (changed.Count == 0) return manifest.Frames;
await db.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0)), cancellationToken)
.ConfigureAwait(false);
var folder = paths.Sequence(sequence.Folder);
if (await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is { } existing)
await db.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, folder, existing), cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
return changed;
return manifest.Frames;
}
/// <summary>
+28
View File
@@ -0,0 +1,28 @@
using Titano.Core.Analysis.Deep;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.Model;
namespace Titano.Data.Processing;
/// <summary>
/// Saved deep-analysis reports (<c>.titano/analysis.json</c>, BRIEF §10.2) for hosts that hand them on: a server serves
/// one to the editors of its clients only while it still describes the sequence (§14.5).
/// </summary>
public static class DeepReports
{
/// <summary>
/// The saved report of <paramref name="sequence"/> when it describes its frames as a host with
/// <paramref name="decoder"/> reads them now; null when there is none, it covers another number of frames, or it
/// found unreadable a frame that has been read from its proxy since (an original that host cannot decode, whose proxy
/// arrived after the analysis): its verdict and its advice to exclude that frame no longer hold.
/// </summary>
public static async Task<DeepAnalysisReport?> ReadCurrentAsync(TitanoDatabase db, Archive archive, Sequence sequence, ImageDecoder decoder,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(sequence);
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, useProxies: false, decoder, cancellationToken).ConfigureAwait(false);
return SequenceAnalyser.ReadReport(new ArchivePaths(archive.RootPath).Sequence(sequence.Folder), frames);
}
}
@@ -94,11 +94,12 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
if (render.StandIns.Count > 0)
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", render.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
// Recorded without the job's token: what decoding found holds even if the job is cancelled meanwhile, and a
// sidecar that cannot be written now only leaves it to the next analysis or render.
// sidecar that cannot be written now only leaves it to the next analysis or render. A frame decoded from its
// preview whose proxy arrived during the render is not preview-only: FrameTiers looks for the proxy as it records.
try
{
var decoded = render.Decoded.ToDictionary(kv => frames.Frames[kv.Key].Id, kv => kv.Value);
await tiers.RecordAsync(archive, sequence, decoded, CancellationToken.None).ConfigureAwait(false);
await tiers.RecordAsync(archive, sequence, decoded, proxies: false, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException
or ArchiveOfflineException)
+14 -12
View File
@@ -46,17 +46,18 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
var folder = paths.Sequence(sequence.Folder);
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, useProxies: false, options.Archive.Decoder, cancellationToken).ConfigureAwait(false);
// Format tiers (BRIEF §10.1): frames indexed since the last analysis are probed with this host's decoders. A frame
// read from its proxy is not preview-only whatever its original's tier, so it caps nothing (BRIEF §8.1, §8.2).
// read from its proxy is not preview-only whatever its original's tier, so it caps nothing (BRIEF §8.1, §8.2); the
// flags are taken as the sidecar has them once recorded, so ones another worker recorded meanwhile count too.
var probed = await _tiers.ProbeUnknownAsync(archive, folder, ManifestStore.ReadSequence(folder.ManifestPath), cancellationToken).ConfigureAwait(false);
var proxied = frames.ProxyStates(options.Archive.Decoder);
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, probed, proxied, cancellationToken).ConfigureAwait(false));
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, probed, proxies: true, cancellationToken).ConfigureAwait(false));
var metadata = frames.LightFrames();
DeepAnalysisReport? report;
if (deep)
{
// Proxies may have arrived during the pass: the advice below follows the frames as they are at its end.
(report, var decoded) = await AnalyseDeepAsync(archive, frames, metadata, folder, progress, cancellationToken).ConfigureAwait(false);
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, decoded, proxied, cancellationToken).ConfigureAwait(false));
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, decoded, proxies: true, cancellationToken).ConfigureAwait(false));
metadata = [.. metadata.Select((m, i) => m with { Flags = frames.Frames[i].Flags })];
}
else
@@ -139,11 +140,11 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
}
}
/// <summary>The frame rows with the tier fields of <paramref name="changed"/> sidecar frames.</summary>
private static SequenceFrames WithTiers(SequenceFrames frames, IReadOnlyList<SidecarFrame> changed)
/// <summary>The frame rows with the flags and preview sizes of the <paramref name="current"/> sidecar frames.</summary>
private static SequenceFrames WithTiers(SequenceFrames frames, IReadOnlyList<SidecarFrame> current)
{
if (changed.Count == 0) return frames;
var byId = changed.ToDictionary(f => f.Id);
if (current.Count == 0) return frames;
var byId = current.ToDictionary(f => f.Id);
var rows = frames.Frames.Select(f => byId.TryGetValue(f.Id, out var s)
? f with { Flags = s.Flags, PreviewWidth = s.PreviewW ?? 0, PreviewHeight = s.PreviewH ?? 0 }
: f).ToList();
@@ -215,15 +216,16 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
/// <summary>Identity of the analysed content: frames replaced or renumbered since a checkpoint was written (with the
/// same count), or now read from their proxies where they were read from their originals (or the other way round),
/// make it stale, like changed options do.</summary>
private static string ContentKey(SequenceFrames frames)
/// make it stale, like changed options do. Only frames read from proxies are marked, so the key of a sequence read
/// from its originals is what it was before proxies counted, and checkpoints written then still resume.</summary>
internal static string ContentKey(SequenceFrames frames)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
for (var i = 0; i < frames.Count; i++)
{
var f = frames.Frames[i];
var source = frames.Proxied is { } proxied && proxied[i] ? "proxy" : "original";
hash.AppendData(Encoding.UTF8.GetBytes($"{f.Id:N}/{f.Sha256}/{f.Size}/{f.Flags & SequenceFrames.NotAnalysed}/{source};"));
var source = frames.Proxied is { } proxied && proxied[i] ? "/proxy" : "";
hash.AppendData(Encoding.UTF8.GetBytes($"{f.Id:N}/{f.Sha256}/{f.Size}/{f.Flags & SequenceFrames.NotAnalysed}{source};"));
}
return Convert.ToHexStringLower(hash.GetHashAndReset())[..16];
}
+7 -19
View File
@@ -35,7 +35,8 @@ internal sealed record SequenceFrames(Sequence Sequence, IReadOnlyList<Frame> Fr
/// Every frame row of <paramref name="sequence"/> with its archive file: the proxy when asked, and whenever the
/// original is one <paramref name="decoder"/> cannot decode (<see cref="ArchiveImages.NeedsProxy(ImageDecoder, ImageFileFormat)"/>:
/// HEIF on the server, BRIEF §2.3, §8.5), as long as the frame's own proxy is there (<see cref="ArchiveImages.IsProxyOf"/>:
/// not one left at its index by a frame renumbered since); else the original.
/// not one left at its index by a frame renumbered since, nor, for an original this host cannot decode, one smaller
/// than the archive's policy); else the original.
/// </summary>
public static async Task<SequenceFrames> LoadAsync(TitanoDatabase db, Archive archive, Sequence sequence, bool useProxies, ImageDecoder decoder,
CancellationToken cancellationToken)
@@ -46,13 +47,16 @@ internal sealed record SequenceFrames(Sequence Sequence, IReadOnlyList<Frame> Fr
var files = new string?[frames.Count];
var originals = new string?[frames.Count];
var proxied = new bool[frames.Count];
ProxyPolicy? policy = null;
for (var i = 0; i < files.Length; i++)
{
var frame = frames[i];
if ((frame.Flags & FrameFlags.Missing) != 0) continue;
originals[i] = paths.FromRelative(frame.RelativePath);
var proxy = useProxies || ArchiveImages.NeedsProxy(decoder, frame.Format) ? folder.Proxy(frame.Index) : null;
proxied[i] = proxy is not null && ArchiveImages.IsProxyOf(proxy, frame.CapturedAt);
var needs = ArchiveImages.NeedsProxy(decoder, frame.Format);
var proxy = useProxies || needs ? folder.Proxy(frame.Index) : null;
proxied[i] = proxy is not null && ArchiveImages.IsProxyOf(proxy, frame.CapturedAt, frame.Width, frame.Height,
needs ? policy ??= ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy : null);
files[i] = proxied[i] ? proxy : originals[i];
}
return new SequenceFrames(sequence, frames, files) { Proxied = proxied, Originals = originals };
@@ -95,22 +99,6 @@ internal sealed record SequenceFrames(Sequence Sequence, IReadOnlyList<Frame> Fr
return light;
}
/// <summary>
/// By frame id, whether each frame whose original <paramref name="decoder"/> cannot decode (it is read from its proxy,
/// <see cref="LoadAsync"/>) has its own proxy now: what its <see cref="FrameFlags.PreviewOnly"/> follows
/// (<see cref="FrameTiers.RecordAsync(Archive, Sequence, IReadOnlyDictionary{Guid, FileTier}, IReadOnlyDictionary{Guid, bool}?, CancellationToken)"/>).
/// Missing frames are left out.
/// </summary>
public Dictionary<Guid, bool> ProxyStates(ImageDecoder decoder)
{
var states = new Dictionary<Guid, bool>();
for (var i = 0; i < Frames.Count; i++)
{
if (Files[i] is not null && ArchiveImages.NeedsProxy(decoder, Frames[i].Format)) states[Frames[i].Id] = Proxied is { } proxied && proxied[i];
}
return states;
}
/// <summary>Positions of the frames a render must skip besides the project's exclusions.</summary>
public IEnumerable<int> NotRenderable()
{