Merge branch 'fix/proxies-render-sync': proxies from clients and nodes, node manifests, sync and mass-rename fixes, server polling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
45 files changed
+1833
-179
No files matched your search
@@ -1,5 +1,8 @@
|
||||
using System.Diagnostics;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
@@ -9,15 +12,40 @@ namespace Titano.Data.Archiving;
|
||||
/// <summary>Frames processed by one thumbnail or proxy pass over a sequence.</summary>
|
||||
public sealed record ImagePassResult(int Built, int Reused, int Undecodable);
|
||||
|
||||
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxy"/>).</summary>
|
||||
public enum ProxyStoreResult
|
||||
{
|
||||
Stored,
|
||||
|
||||
/// <summary>The archive's proxy policy makes no proxies.</summary>
|
||||
Disabled,
|
||||
|
||||
/// <summary>Not a JPEG that decodes, or larger than <see cref="ArchiveImages.MaxProxyBytes"/>.</summary>
|
||||
Invalid,
|
||||
|
||||
/// <summary>Its Exif capture time is not the frame's: it was made from another photo.</summary>
|
||||
WrongFrame,
|
||||
|
||||
/// <summary>Smaller than the archive's proxies of that frame: made from an embedded preview, not the original.</summary>
|
||||
TooSmall,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thumbnails (<c>thumbs.pack</c>) and proxies (<c>proxies/0001.jpg</c>) of sequences (BRIEF §8.5). Both are
|
||||
/// regenerable and self-validating: a thumbnail carries its source fingerprint, a proxy its capture time, so after
|
||||
/// frames were renumbered the stale ones are rebuilt and the rest reused.
|
||||
/// frames were renumbered the stale ones are rebuilt and the rest reused. A frame whose original this host cannot
|
||||
/// decode (<see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/>) gets its proxy from a client or render node that can
|
||||
/// (<see cref="StoreProxy"/>, BRIEF §2.3) and its thumbnail from that proxy.
|
||||
/// </summary>
|
||||
public sealed class ArchiveImages
|
||||
{
|
||||
/// <summary>Largest proxy a client or render node may send: a full-size proxy of a large sensor at q92 fits.</summary>
|
||||
public const long MaxProxyBytes = 64L << 20;
|
||||
|
||||
private const int CommitFrames = 200;
|
||||
private const int ProbeLongEdge = 64;
|
||||
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
|
||||
private static readonly ImageDecoder ServerDecoders = DecoderFactory.CreateServer();
|
||||
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
@@ -32,6 +60,91 @@ public sealed class ArchiveImages
|
||||
_renderer = new FrameImageRenderer(writer.Options.Decoder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a host with <paramref name="decoder"/> takes the pixels of a <paramref name="format"/> original from its
|
||||
/// proxy: no decoder reads the format, or only previews of a HEIF, which embeds thumbnails at best (BRIEF §2.3,
|
||||
/// §8.1: the server keeps HEIF originals and relies on proxies made by a Windows client or render node). Never for a
|
||||
/// JPEG (proxies are JPEGs: a host that reads them reads it) or a file no format was recognised in.
|
||||
/// </summary>
|
||||
public static bool NeedsProxy(ImageDecoder decoder, ImageFileFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
if (format is ImageFileFormat.Unknown or ImageFileFormat.Jpeg) return false;
|
||||
var tier = decoder.TierFor(format);
|
||||
return tier == DecodeTier.Unavailable || (tier != DecodeTier.Native && ImageFormatInfo.Of(format).Family == ImageFamily.Heif);
|
||||
}
|
||||
|
||||
/// <summary><see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/> with this archive engine's decoders.</summary>
|
||||
public bool NeedsProxy(ImageFileFormat format) => NeedsProxy(_writer.Options.Decoder, format);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/> on a Titano Server, whose decoders are managed only (BRIEF
|
||||
/// §4.2): it asks clients and render nodes for the proxies of those originals.
|
||||
/// </summary>
|
||||
public static bool ServerNeedsProxy(ImageFileFormat format) => NeedsProxy(ServerDecoders, format);
|
||||
|
||||
/// <summary>
|
||||
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxy"/>):
|
||||
/// at <paramref name="longEdge"/> (0 = full size) and <paramref name="quality"/>, with <paramref name="frame"/>'s capture
|
||||
/// data (the server's record, which it checks) and <paramref name="camera"/> in its Exif. Null when
|
||||
/// <paramref name="decoder"/> cannot decode the original either.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The original cannot be read.</exception>
|
||||
public static byte[]? MakeProxy(ImageDecoder decoder, string path, Frame frame, SidecarCamera? camera, int longEdge, int quality,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
if (NeedsProxy(decoder, frame.Format)) return null;
|
||||
// The original's folder stands in for a sequence folder: the renderer reads frames relative to one.
|
||||
var folder = new ArchivePaths(Path.GetDirectoryName(Path.GetFullPath(path))!).Sequence(string.Empty);
|
||||
var source = new SidecarFrame
|
||||
{
|
||||
Id = frame.Id,
|
||||
I = frame.Index,
|
||||
File = Path.GetFileName(path),
|
||||
Size = frame.Size,
|
||||
CapturedAt = frame.CapturedAt,
|
||||
UtcOffset = frame.UtcOffsetMinutes,
|
||||
Exposure = frame.ExposureTime,
|
||||
FNumber = frame.FNumber,
|
||||
Iso = frame.Iso,
|
||||
Focal = frame.FocalLength,
|
||||
Bias = frame.ExposureBias,
|
||||
Orientation = frame.Orientation,
|
||||
Format = frame.Format,
|
||||
};
|
||||
var policy = new ProxyPolicy { LongEdge = longEdge, Quality = quality };
|
||||
return new FrameImageRenderer(decoder).Proxy(folder, source, camera, policy, cancellationToken)?.Jpeg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Files a proxy made elsewhere (a client or render node whose decoders read the original) as the frame's proxy,
|
||||
/// replacing the one there: a JPEG of at most <see cref="MaxProxyBytes"/> that decodes, whose Exif capture time is the
|
||||
/// frame's (proxies carry it, so the proxy counts as current and cannot belong to another photo) and whose size is
|
||||
/// the policy's (<see cref="TooSmall"/>), written atomically.
|
||||
/// </summary>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
public ProxyStoreResult StoreProxy(Archive archive, Sequence sequence, Frame frame, byte[] jpeg)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(jpeg);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
|
||||
if (policy.LongEdge == ProxyPolicy.Disabled) return ProxyStoreResult.Disabled;
|
||||
if (jpeg.Length is 0 or > (int)MaxProxyBytes || !Decodes(jpeg)) return ProxyStoreResult.Invalid;
|
||||
var info = JpegDecoder.ReadInfo(jpeg);
|
||||
if (TooSmall(System.Math.Max(info.Width, info.Height), frame.Width, frame.Height, policy)) return ProxyStoreResult.TooSmall;
|
||||
if (frame.CapturedAt is { } captured)
|
||||
{
|
||||
using var stream = new MemoryStream(jpeg, writable: false);
|
||||
if (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);
|
||||
return ProxyStoreResult.Stored;
|
||||
}
|
||||
|
||||
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run).</param>
|
||||
/// <param name="checkpoint">Called with the next frame index whenever the pack has been committed.</param>
|
||||
public async Task<ImagePassResult> BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
||||
@@ -54,12 +167,22 @@ public sealed class ArchiveImages
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var fingerprint = ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size);
|
||||
if (!force && pack.Entries.TryGetValue(frame.I, out var entry) && entry.SourceHash.AsSpan().SequenceEqual(fingerprint))
|
||||
var entry = pack.Entries.GetValueOrDefault(frame.I);
|
||||
var edge = entry is null ? 0 : System.Math.Max(entry.Width, entry.Height);
|
||||
var current = !force && entry is not null && entry.SourceHash.AsSpan().SequenceEqual(fingerprint);
|
||||
// A frame this host cannot decode shows its proxy once one arrived; until then its original's embedded
|
||||
// preview, whose smaller thumbnail the proxy's replaces.
|
||||
var fromProxy = false;
|
||||
if (NeedsProxy(frame.Format) && !(current && edge >= FrameImageRenderer.ThumbnailLongEdge)
|
||||
&& ReadProxy(folder.Proxy(frame.I), frame) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
|
||||
fromProxy = !current || edge < System.Math.Min(FrameImageRenderer.ThumbnailLongEdge, proxy.LongEdge);
|
||||
if (current && !fromProxy)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
if (Render(() => _renderer.Thumbnail(folder, frame, policy, cancellationToken)) is { } image)
|
||||
var source = fromProxy ? ProxySource(frame) : frame;
|
||||
if (Render(() => _renderer.Thumbnail(folder, source, policy, cancellationToken)) is { } image)
|
||||
{
|
||||
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
|
||||
built++;
|
||||
@@ -98,12 +221,29 @@ public sealed class ArchiveImages
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = manifest.Frames[i];
|
||||
var path = folder.Proxy(frame.I);
|
||||
if (!force && IsCurrent(path, frame))
|
||||
if (NeedsProxy(frame.Format))
|
||||
{
|
||||
// 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);
|
||||
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && TooSmall(longEdge, frame.W, frame.H, policy)) check = ProxyCheck.Stale;
|
||||
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable)
|
||||
{
|
||||
reused++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (check == ProxyCheck.Stale) File.Delete(path);
|
||||
undecodable++;
|
||||
}
|
||||
}
|
||||
else if (!force && ReadProxy(path, frame).Check == ProxyCheck.Current)
|
||||
{
|
||||
reused++;
|
||||
continue;
|
||||
}
|
||||
if (Render(() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
|
||||
else if (Render(() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
|
||||
{
|
||||
AtomicFile.WriteAllBytes(path, image.Jpeg);
|
||||
built++;
|
||||
@@ -118,15 +258,73 @@ public sealed class ArchiveImages
|
||||
return new ImagePassResult(built, reused, undecodable);
|
||||
}
|
||||
|
||||
/// <summary>A proxy is current when its Exif capture time is the frame's (frames renumbered since make it stale).</summary>
|
||||
private static bool IsCurrent(string proxy, SidecarFrame frame)
|
||||
/// <summary>Where a frame's proxy stands; only a capture time tells whether it is the frame's.</summary>
|
||||
private enum ProxyCheck
|
||||
{
|
||||
if (!File.Exists(proxy)) return false;
|
||||
Missing,
|
||||
|
||||
/// <summary>Its Exif capture time is the frame's.</summary>
|
||||
Current,
|
||||
|
||||
/// <summary>The frame has no capture time to compare with.</summary>
|
||||
Unverifiable,
|
||||
|
||||
/// <summary>Made from another frame (frames were renumbered since).</summary>
|
||||
Stale,
|
||||
}
|
||||
|
||||
/// <summary>Where the proxy at <paramref name="proxy"/> stands for <paramref name="frame"/>, and its long edge.</summary>
|
||||
private static (ProxyCheck Check, int LongEdge) ReadProxy(string proxy, SidecarFrame frame)
|
||||
{
|
||||
if (!File.Exists(proxy)) return (ProxyCheck.Missing, 0);
|
||||
try
|
||||
{
|
||||
return MetadataReader.Read(proxy).CapturedAt == frame.CapturedAt && frame.CapturedAt is not null;
|
||||
var metadata = MetadataReader.Read(proxy);
|
||||
var (width, height) = metadata.OrientedSize;
|
||||
var check = frame.CapturedAt is null ? ProxyCheck.Unverifiable : metadata.CapturedAt == frame.CapturedAt ? ProxyCheck.Current : ProxyCheck.Stale;
|
||||
return (check, System.Math.Max(width, height));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return (ProxyCheck.Missing, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// at full size): one made from an embedded preview. A frame of unknown size is never judged (a small original's
|
||||
/// proxy would be refused again and again); a tenth of slack spares decoders that crop a few pixels.
|
||||
/// </summary>
|
||||
private static bool TooSmall(int longEdge, int width, int height, ProxyPolicy policy)
|
||||
{
|
||||
var own = System.Math.Max(width, height);
|
||||
if (own <= 0) return false;
|
||||
var expected = policy.LongEdge == ProxyPolicy.FullSize ? own : System.Math.Min(own, policy.LongEdge);
|
||||
return longEdge * 10L < expected * 9L;
|
||||
}
|
||||
|
||||
/// <summary>The frame's proxy as the frame to draw: a JPEG already oriented, under <c>proxies/</c>.</summary>
|
||||
private static SidecarFrame ProxySource(SidecarFrame frame) => frame with
|
||||
{
|
||||
File = ArchiveLayout.ProxiesFolder + "/" + ArchiveLayout.ProxyFileName(frame.I),
|
||||
Format = ImageFileFormat.Jpeg,
|
||||
Orientation = 1,
|
||||
PreviewOffset = null,
|
||||
PreviewLength = null,
|
||||
};
|
||||
|
||||
/// <summary>A colour or grey JPEG whose headers parse and whose scans decode (at a small DCT-scaled size).</summary>
|
||||
private static bool Decodes(byte[] jpeg)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = JpegDecoder.ReadInfo(jpeg);
|
||||
if (info.Process == JpegProcess.Lossless || info.Components is not (1 or 3) || info.Width < 1 || info.Height < 1) return false;
|
||||
using var probe = JpegDecoder.DecodeToLinear(jpeg, new JpegDecodeOptions { MaxLongEdge = ProbeLongEdge });
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or NotSupportedException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user