fix(proxies): get proxies of undecodable originals from clients and nodes
The server decodes with managed decoders only, so HEIF originals had no
proxies, thumbnails from their small previews and no pixels for analysis or
managed renders, and nothing could send it proxies (ENG-05). Manifests now
carry the archive's proxy spec and, per frame, its flags and whether the
server wants its proxy. PUT /api/v1/frames/{id}/proxy (Edit or RenderNode)
stores a JPEG of at most 64 MiB that decodes and whose Exif capture time is
the frame's, then queues thumbnails and the proxy pass. An upload from the
desktop makes and sends the wanted proxies after the originals and counts
them as local changes; a render node sends those it can make from the
originals it fetched once the job is done. The server never makes such a
proxy from a preview, drops one left by a renumbered frame, takes thumbnails
from a proxy, and analyses and renders those frames from their proxies.
Render nodes fetched every frame of the manifest: frames missing, corrupt or
excluded on the server failed the download, and originals not hashed yet
failed the SHA-256 check (ENG-07). Nodes now skip those frames, fetch unhashed
originals into the job folder with a size check, judge decodability with their
own decoders, and use the proxy of a frame they cannot decode.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
28 files changed
+1005
-94
No files matched your search
@@ -0,0 +1,129 @@
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Testing;
|
||||
using static Titano.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
namespace Titano.Data.Tests.Archiving;
|
||||
|
||||
/// <summary>Proxies of originals a host cannot decode (BRIEF §2.3, §8.5): sent by a client or render node, checked, kept, thumbnailed.</summary>
|
||||
[Category("archive")]
|
||||
public sealed class ProxyTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void OnlyFormatsAHostCannotDecodeTakeTheirPixelsFromProxies()
|
||||
{
|
||||
var server = DecoderFactory.CreateServer();
|
||||
Assert.True(ArchiveImages.NeedsProxy(server, ImageFileFormat.Heif), "HEIF previews are thumbnails at best");
|
||||
Assert.True(ArchiveImages.NeedsProxy(server, ImageFileFormat.Avif));
|
||||
Assert.True(ArchiveImages.NeedsProxy(server, ImageFileFormat.WebP), "no decoder at all");
|
||||
Assert.False(ArchiveImages.NeedsProxy(server, ImageFileFormat.Cr3), "a RAW's embedded full-size preview");
|
||||
Assert.False(ArchiveImages.NeedsProxy(server, ImageFileFormat.Dng));
|
||||
Assert.False(ArchiveImages.NeedsProxy(new ImageDecoder([]), ImageFileFormat.Jpeg), "proxies are JPEGs");
|
||||
Assert.False(ArchiveImages.NeedsProxy(server, ImageFileFormat.Unknown));
|
||||
// A desktop whose decoders read HEIF makes the proxies a server asks for.
|
||||
Assert.False(ArchiveImages.NeedsProxy(new ImageDecoder([new NativeHeif()]), ImageFileFormat.Heif));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxySentForAFrameThisHostCannotDecodeIsCheckedKeptAndThumbnailed()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var images = fx.Service.Images;
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Invalid, images.StoreProxy(fx.Archive, sequence, frames[0], "not a photo"u8.ToArray()));
|
||||
Assert.Equal(ProxyStoreResult.WrongFrame, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[1].CapturedAt!.Value, 1)));
|
||||
Assert.FileMissing(folder.Proxy(0));
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], proxy));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
|
||||
// The proxy pass keeps what was sent and makes none from the originals here, even when forced.
|
||||
var proxies = await images.BuildProxiesAsync(fx.Archive, sequence, force: true, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 1), (proxies.Built, proxies.Reused, proxies.Undecodable));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
Assert.FileMissing(folder.Proxy(1));
|
||||
|
||||
// The thumbnail comes from the proxy; the frame without one has none yet.
|
||||
var thumbs = await images.BuildThumbnailsAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((1, 0, 1), (thumbs.Built, thumbs.Reused, thumbs.Undecodable));
|
||||
using (var pack = ThumbPackReader.Open(folder.ThumbsPackPath))
|
||||
{
|
||||
var entry = pack.Entries[0];
|
||||
Assert.Equal((FrameImageRenderer.ThumbnailLongEdge, 240), (entry.Width, entry.Height));
|
||||
}
|
||||
var again = await images.BuildThumbnailsAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 1), (again.Built, again.Reused, again.Undecodable));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyLeftByARenumberedFrameIsAskedForAgain()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(1), Proxy(frames[0].CapturedAt!.Value, 3), fx.Ct);
|
||||
|
||||
var proxies = await fx.Service.Images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
|
||||
Assert.Equal(2, proxies.Undecodable);
|
||||
Assert.FileMissing(folder.Proxy(1));
|
||||
Assert.False((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.ProxiesBuilt));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnArchiveWithoutProxiesRefusesThem()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
|
||||
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { ProxyPolicy = new ProxyPolicy { LongEdge = ProxyPolicy.Disabled } });
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Disabled, fx.Service.Images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 4)));
|
||||
Assert.FileMissing(fx.Paths.Sequence(sequence.Folder).Proxy(0));
|
||||
}
|
||||
|
||||
/// <summary>Two ingested frames whose originals the archive engine takes for HEIF (its decoders read none).</summary>
|
||||
private static async Task<(Sequence Sequence, IReadOnlyList<Frame> Frames)> HeifSequenceAsync(ArchiveFixture fx)
|
||||
{
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
var staged = fx.Stage(Start.AddSeconds(10 * i), 40 + i);
|
||||
id = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, "heif", staged.Path, $"IMG_{i:0000}.HEIC",
|
||||
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
|
||||
}
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id, fx.Ct))!;
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, sidecar with { Frames = [.. sidecar.Frames.Select(f => f with { Format = ImageFileFormat.Heif })] });
|
||||
return (sequence, await fx.Db.Frames.ListBySequenceAsync(id));
|
||||
}
|
||||
|
||||
/// <summary>A 320 × 240 JPEG proxy with <paramref name="captured"/> in its Exif, as a client makes it.</summary>
|
||||
private static byte[] Proxy(DateTime captured, int seed)
|
||||
{
|
||||
using var image = new ImageBuffer(320, 240);
|
||||
var level = 0.2f + seed % 5 * 0.1f;
|
||||
for (var c = 0; c < 3; c++) image.Plane(c).Fill(level + c * 0.05f);
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { CapturedAt = captured, Software = "Titano" });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
/// <summary>A provider that decodes HEIF natively (WIC with the HEIF extension on a desktop).</summary>
|
||||
private sealed class NativeHeif : IImageDecoderProvider
|
||||
{
|
||||
public string Name => "native-heif";
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Heif ? DecodeTier.Native : null;
|
||||
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,33 @@ public sealed class RenderJobTests(TestContext context)
|
||||
Assert.Equal(3, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.RenderedCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesThisHostCannotDecodeRenderFromTheirProxies()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var folder = fx.Folder(sequence);
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
foreach (var frame in await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))
|
||||
{
|
||||
// The originals are HEIF this host cannot read (BRIEF §2.3): only the proxies a client sent have pixels here.
|
||||
var original = fx.Archive.Paths.FromRelative(frame.RelativePath);
|
||||
File.Copy(original, folder.Proxy(frame.Index));
|
||||
await File.WriteAllBytesAsync(original, [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8], fx.Ct);
|
||||
}
|
||||
await using (var session = await fx.Db.Database.OpenAsync(fx.Ct))
|
||||
await session.ExecuteAsync("UPDATE frames SET format = $1 WHERE sequence_id = $2", [(int)ImageFileFormat.Heif, sequence.Id], fx.Ct);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// The job does not ask for proxies: the host takes them because it cannot decode the originals.
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.FileExists(Path.Combine(folder.Exports, "clip-MJPEG.avi"));
|
||||
var decoded = fx.Decoder.Requests.Where(r => r.Purpose == DecodePurpose.Render).Select(r => Path.GetDirectoryName(r.Path)).Distinct().ToList();
|
||||
Assert.SequenceEqual([folder.Proxies], decoded);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACancelledRenderLeavesNothingBehind()
|
||||
{
|
||||
|
||||
@@ -38,6 +38,9 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
/// <summary>Proxy and thumbnail downloads fail with a server error.</summary>
|
||||
public bool FailAssets { get; set; }
|
||||
|
||||
/// <summary>Proxies clients sent, by frame id (for sequences the server cannot decode).</summary>
|
||||
public Dictionary<Guid, byte[]> SentProxies { get; } = [];
|
||||
|
||||
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
|
||||
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
|
||||
{
|
||||
@@ -96,7 +99,7 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
{
|
||||
ManifestCalls++;
|
||||
if (Refused.Contains(id)) throw new TitanoApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
|
||||
return Task.FromResult(Find(id).Manifest());
|
||||
return Task.FromResult(Find(id).Manifest(SentProxies.ContainsKey));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +174,18 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
await destination.WriteAsync(bytes.AsMemory(offset), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Like the server: only a frame whose proxy it asks for takes one, and only a JPEG.</summary>
|
||||
public Task UploadProxyAsync(Guid frameId, byte[] jpeg, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!Sequences.Values.Any(s => s.Undecodable && s.Frames.Any(f => f.Id == frameId))) throw NotFound();
|
||||
if (jpeg is not [0xFF, 0xD8, ..]) throw new TitanoApiException(HttpStatusCode.UnprocessableEntity, new ApiError("invalid_proxy", "not a JPEG"));
|
||||
SentProxies[frameId] = jpeg;
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
FakeRender render;
|
||||
@@ -225,6 +240,10 @@ internal sealed class FakeSequence
|
||||
public int SettingsVersion { get; set; } = 1;
|
||||
public int FramesVersion { get; set; }
|
||||
public SequenceStatus Status { get; set; }
|
||||
|
||||
/// <summary>The server cannot decode these originals (HEIF): its manifest asks for proxies of them.</summary>
|
||||
public bool Undecodable { get; set; }
|
||||
|
||||
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
|
||||
public DateTime? FirstCapture { get; set; }
|
||||
public string? CameraModel { get; set; } = "Canon EOS R5";
|
||||
@@ -243,9 +262,10 @@ internal sealed class FakeSequence
|
||||
public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", CameraModel, null, FirstCapture, null, Frames.Count, 10,
|
||||
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
|
||||
|
||||
public SequenceManifest Manifest() => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
|
||||
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, f.Sha256, (Status & SequenceStatus.ProxiesBuilt) != 0,
|
||||
(Status & SequenceStatus.ThumbsBuilt) != 0))], [.. Renders.Select(r => r.Dto())]);
|
||||
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
|
||||
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, f.Sha256, (Status & SequenceStatus.ProxiesBuilt) != 0 || proxySent(f.Id),
|
||||
(Status & SequenceStatus.ThumbsBuilt) != 0, WantsProxy: Undecodable && !proxySent(f.Id)))], [.. Renders.Select(r => r.Dto())],
|
||||
Undecodable ? new ProxySpec(1280, 90) : null);
|
||||
}
|
||||
|
||||
internal sealed record FakeRender(Guid Id, string FileName, string PresetName, byte[] Bytes)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Data.Sync;
|
||||
@@ -32,6 +34,34 @@ public sealed class SyncTransferTests(TestContext context)
|
||||
Assert.Equal(remote.Id, entry.Link!.RemoteId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadSendsTheProxiesTheServerCannotMakeItself()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Holy grail", photos);
|
||||
// The server has the originals already (the Uploader sent them) but cannot decode them (HEIF, BRIEF §2.3).
|
||||
var remote = f.Remote.Add("Holy grail", photos);
|
||||
remote.Undecodable = true;
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var ahead = await f.EntryAsync("Holy grail");
|
||||
Assert.Equal((SyncStatus.LocalAhead, 3), (ahead.Status, ahead.Link!.MissingRemote));
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.True(f.Remote.SentProxies.Keys.ToHashSet().SetEquals(remote.Frames.Select(r => r.Id)), "a proxy of every frame");
|
||||
foreach (var proxy in f.Remote.SentProxies.Values)
|
||||
{
|
||||
var info = JpegDecoder.ReadInfo(proxy);
|
||||
Assert.True(info.Width <= 1280 && info.Height <= 1280, "made as the server's policy says");
|
||||
}
|
||||
Assert.Contains(Loc.L("Archive.Log.ProxiesSent", 3, 0), done.LogTail);
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AResumedUploadSendsOnlyWhatTheServerLacks()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user