merge: proxy and decode-tier fixes (V-1, V-24, V-25, V-26, V-27, V-28)
Merge branch fix2/proxies-tiers into the verification branch. 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
+1049
-92
No files matched your search
@@ -56,6 +56,24 @@ public sealed class DecodeTierTests(TestContext context)
|
||||
SequenceFrames.WithTier(none, new FileTier(ImageFileFormat.Cr2, DecodeTier.Unavailable, null, "nothing here", 0, 0), damaged: false).Flags);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFrameReadFromItsProxyKeepsItsPreviewTierButIsNotPreviewOnly()
|
||||
{
|
||||
// A HEIF on the server: its decoders find only the Exif thumbnail, but renders read the proxy a client sent.
|
||||
var heif = Sidecar() with { File = "originals/IMG_0001.HEIC", Format = ImageFileFormat.Heif, Flags = FrameFlags.Duplicate };
|
||||
var thumbnail = new FileTier(ImageFileFormat.Heif, DecodeTier.EmbeddedPreview, "managed-preview", "no managed decoder for Heif", 160, 120);
|
||||
var proxied = SequenceFrames.WithTier(heif, thumbnail, damaged: false, proxied: true);
|
||||
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.Duplicate, (int?)160, (int?)120), (proxied.Tier, proxied.Flags, proxied.PreviewW, proxied.PreviewH));
|
||||
|
||||
// The flag follows the proxy, the tier and preview size stay the original's.
|
||||
var gone = SequenceFrames.WithProxy(proxied, proxied: false);
|
||||
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.Duplicate | FrameFlags.PreviewOnly, (int?)160), (gone.Tier, gone.Flags, gone.PreviewW));
|
||||
Assert.Equal(FrameFlags.Duplicate, SequenceFrames.WithProxy(gone, proxied: true).Flags);
|
||||
// Other tiers have no preview-only flag to follow.
|
||||
var unavailable = SequenceFrames.WithTier(heif, new FileTier(ImageFileFormat.Heif, DecodeTier.Unavailable, null, "nothing", 0, 0), damaged: false);
|
||||
Assert.Same(unavailable, SequenceFrames.WithProxy(unavailable, proxied: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SidecarsKeepTheTierAndThePreviewSizeAndOlderOnesReadAsUnknown()
|
||||
{
|
||||
|
||||
@@ -100,13 +100,28 @@ public sealed class ArchiveJobTests(TestContext context)
|
||||
Assert.NotNull(pack.Read(4));
|
||||
}
|
||||
Assert.SequenceEqual(["0004.jpg", "0005.jpg", "0006.jpg"], Directory.GetFiles(sequence.Proxies).Select(Path.GetFileName).Order());
|
||||
// The resumed passes saw every frame after the resume point done, but the frames before it have nothing: the
|
||||
// sequence has neither all its thumbnails nor all its proxies (a server would ask for none of the missing ones).
|
||||
var status = (await fx.Db.Sequences.GetAsync(a.Id))!.Status;
|
||||
Assert.True(status.HasFlag(SequenceStatus.ThumbsBuilt) && status.HasFlag(SequenceStatus.ProxiesBuilt));
|
||||
Assert.False(status.HasFlag(SequenceStatus.ThumbsBuilt) || status.HasFlag(SequenceStatus.ProxiesBuilt), status.ToString());
|
||||
|
||||
// A full pass reuses what is current and builds the rest.
|
||||
var all = await engine.EnqueueAsync(ArchiveJobs.Thumbnails([a.Id]), cancellationToken: fx.Ct);
|
||||
var done = await fx.WaitForAsync(all.Id, JobState.Done);
|
||||
Assert.Contains("made 3, reused 3", done.LogTail);
|
||||
var allProxies = await engine.EnqueueAsync(ArchiveJobs.Proxies([a.Id]), cancellationToken: fx.Ct);
|
||||
Assert.Contains("made 3, reused 3, unreadable 0, waiting 0", (await fx.WaitForAsync(allProxies.Id, JobState.Done)).LogTail);
|
||||
status = (await fx.Db.Sequences.GetAsync(a.Id))!.Status;
|
||||
Assert.True(status.HasFlag(SequenceStatus.ThumbsBuilt) && status.HasFlag(SequenceStatus.ProxiesBuilt), status.ToString());
|
||||
|
||||
// Resumed once every frame has them, a pass sets both again.
|
||||
await fx.Db.Sequences.UpdateStatusAsync(a.Id, SequenceStatus.None, SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt, fx.Ct);
|
||||
var resumedThumbs = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Thumbnails([a.Id]), "0:3");
|
||||
await fx.WaitForAsync(resumedThumbs.Id, JobState.Done);
|
||||
var resumedProxies = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Proxies([a.Id]), "0:3");
|
||||
await fx.WaitForAsync(resumedProxies.Id, JobState.Done);
|
||||
status = (await fx.Db.Sequences.GetAsync(a.Id))!.Status;
|
||||
Assert.True(status.HasFlag(SequenceStatus.ThumbsBuilt) && status.HasFlag(SequenceStatus.ProxiesBuilt), status.ToString());
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Metadata;
|
||||
|
||||
namespace Titano.Data.Tests.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// HEIF files as phones and cameras write them, as far as a host without a HEVC decoder reads them (the server, BRIEF
|
||||
/// §8.1): the primary image's size (<c>ispe</c>) and an Exif item with the capture time and, in IFD1, a small JPEG
|
||||
/// thumbnail, the only pixels such a host finds in the file.
|
||||
/// </summary>
|
||||
internal static class HeifFile
|
||||
{
|
||||
/// <summary>A <paramref name="width"/> × <paramref name="height"/> HEIF captured at <paramref name="captured"/>, its Exif
|
||||
/// thumbnail <paramref name="thumbnailWidth"/> × <paramref name="thumbnailHeight"/>.</summary>
|
||||
public static byte[] Create(DateTime captured, int width, int height, int thumbnailWidth = 160, int thumbnailHeight = 120)
|
||||
{
|
||||
using var small = new ImageBuffer(thumbnailWidth, thumbnailHeight);
|
||||
for (var c = 0; c < 3; c++) small.Plane(c).Fill(0.2f + c * 0.2f);
|
||||
var thumbnail = JpegEncoder.Encode(small, new JpegEncodeOptions { Quality = 80 });
|
||||
var tiff = WithThumbnail(ExifWriter.BuildTiff(new FrameMetadata { Make = "TestCam", Model = "H-1", CapturedAt = captured }), thumbnail);
|
||||
byte[] exif = [.. U32(6), .. "Exif\0\0"u8, .. tiff];
|
||||
// The HEVC-coded primary image, which no managed decoder reads.
|
||||
var coded = new byte[64];
|
||||
|
||||
byte[] Build(int mdat) =>
|
||||
[
|
||||
.. Box("ftyp", "heic"u8.ToArray(), U32(0), "mif1heic"u8.ToArray()),
|
||||
.. FullBox("meta", 0,
|
||||
FullBox("hdlr", 0, U32(0), "pict"u8.ToArray(), new byte[13]),
|
||||
FullBox("pitm", 0, U16(1)),
|
||||
FullBox("iinf", 0, U16(2), FullBox("infe", 2, U16(1), U16(0), "hvc1\0"u8.ToArray()), FullBox("infe", 2, U16(2), U16(0), "Exif\0"u8.ToArray())),
|
||||
FullBox("iloc", 1, [0x44, 0x00], U16(2),
|
||||
U16(1), U16(0), U16(0), U16(1), U32(mdat), U32(coded.Length),
|
||||
U16(2), U16(0), U16(0), U16(1), U32(mdat + coded.Length), U32(exif.Length)),
|
||||
Box("iprp", Box("ipco", FullBox("ispe", 0, U32(width), U32(height))), FullBox("ipma", 0, U32(1), U16(1), [1, 0x81]))),
|
||||
];
|
||||
|
||||
var head = Build(0);
|
||||
head = Build(head.Length + 8);
|
||||
return [.. head, .. Box("mdat", coded, exif)];
|
||||
}
|
||||
|
||||
/// <summary><paramref name="tiff"/> (a single IFD0 chain, as <see cref="ExifWriter.BuildTiff"/> writes it) with an IFD1 holding <paramref name="thumbnail"/>.</summary>
|
||||
private static byte[] WithThumbnail(byte[] tiff, byte[] thumbnail)
|
||||
{
|
||||
const int Entries = 3;
|
||||
var ifd1 = (tiff.Length + 1) & ~1;
|
||||
var jpeg = ifd1 + 2 + 12 * Entries + 4;
|
||||
var result = new byte[jpeg + thumbnail.Length];
|
||||
tiff.CopyTo(result, 0);
|
||||
var ifd0Entries = BinaryPrimitives.ReadUInt16LittleEndian(result.AsSpan(8));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(result.AsSpan(8 + 2 + 12 * ifd0Entries), (uint)ifd1);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(ifd1), Entries);
|
||||
Entry(result, ifd1 + 2, 0x0103, 3, 6); // Compression: JPEG
|
||||
Entry(result, ifd1 + 14, 0x0201, 4, (uint)jpeg); // JPEGInterchangeFormat
|
||||
Entry(result, ifd1 + 26, 0x0202, 4, (uint)thumbnail.Length); // JPEGInterchangeFormatLength
|
||||
thumbnail.CopyTo(result, jpeg);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>A little-endian IFD entry with one value.</summary>
|
||||
private static void Entry(byte[] data, int at, ushort tag, ushort type, uint value)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(at), tag);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(at + 2), type);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(at + 4), 1);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(at + 8), value);
|
||||
}
|
||||
|
||||
private static byte[] Box(string type, params byte[][] payload) => [.. U32(8 + payload.Sum(p => p.Length)), .. Encoding.ASCII.GetBytes(type), .. payload.SelectMany(p => p)];
|
||||
|
||||
private static byte[] FullBox(string type, byte version, params byte[][] payload) => Box(type, [[version, 0, 0, 0], .. payload]);
|
||||
|
||||
private static byte[] U16(int value)
|
||||
{
|
||||
var bytes = new byte[2];
|
||||
BinaryPrimitives.WriteUInt16BigEndian(bytes, (ushort)value);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static byte[] U32(int value)
|
||||
{
|
||||
var bytes = new byte[4];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(bytes, (uint)value);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
// 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.Equal((0, 1, 0, 1), (proxies.Built, proxies.Reused, proxies.Undecodable, proxies.Waiting));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
Assert.FileMissing(folder.Proxy(1));
|
||||
|
||||
@@ -73,7 +73,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
var proxies = await fx.Service.Images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
|
||||
Assert.Equal(2, proxies.Undecodable);
|
||||
Assert.Equal((0, 2), (proxies.Undecodable, proxies.Waiting));
|
||||
Assert.FileMissing(folder.Proxy(1));
|
||||
Assert.False((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.ProxiesBuilt));
|
||||
}
|
||||
@@ -93,7 +93,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
var proxies = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
|
||||
Assert.Equal((0, 0, 2), (proxies.Built, proxies.Reused, proxies.Undecodable));
|
||||
Assert.Equal((0, 0, 0, 2), (proxies.Built, proxies.Reused, proxies.Undecodable, proxies.Waiting));
|
||||
Assert.FileMissing(folder.Proxy(0));
|
||||
Assert.False((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.ProxiesBuilt), "asked for again");
|
||||
|
||||
@@ -102,7 +102,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
Assert.Equal(ProxyStoreResult.TooSmall, images.StoreProxy(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 6, 160, 120)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 7, 1920, 1440)));
|
||||
var again = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 1), (again.Built, again.Reused, again.Undecodable));
|
||||
Assert.Equal((0, 1, 0, 1), (again.Built, again.Reused, again.Undecodable, again.Waiting));
|
||||
Assert.FileExists(folder.Proxy(0));
|
||||
}
|
||||
|
||||
@@ -118,9 +118,246 @@ public sealed class ProxyTests(TestContext context)
|
||||
Assert.FileMissing(fx.Paths.Sequence(sequence.Folder).Proxy(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnlyAFramesOwnProxyIsReadForIt()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
// Proxies are named by frame index: after a frame was inserted before both, frame 1's place holds frame 0's.
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(0), Proxy(frames[0].CapturedAt!.Value, 1), fx.Ct);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(1), Proxy(frames[0].CapturedAt!.Value, 2), fx.Ct);
|
||||
|
||||
var (width, height) = (frames[0].Width, frames[0].Height);
|
||||
Assert.True(ArchiveImages.IsProxyOf(folder.Proxy(0), frames[0].CapturedAt, width, height, new ProxyPolicy()));
|
||||
Assert.False(ArchiveImages.IsProxyOf(folder.Proxy(1), frames[1].CapturedAt, width, height, new ProxyPolicy()), "another photo's");
|
||||
Assert.True(ArchiveImages.IsProxyOf(folder.Proxy(1), null, width, height, new ProxyPolicy()), "a frame without a capture time cannot tell");
|
||||
Assert.False(ArchiveImages.IsProxyOf(folder.Proxy(2), frames[1].CapturedAt, width, height, null), "none there");
|
||||
|
||||
// Renders and analyses read frame 1 from its original, whether the host takes HEIF from proxies or was asked to.
|
||||
foreach (var useProxies in new[] { false, true })
|
||||
{
|
||||
var loaded = await Titano.Data.Processing.SequenceFrames.LoadAsync(fx.Db, fx.Archive, sequence, useProxies, new ImageDecoder([]), fx.Ct);
|
||||
Assert.SequenceEqual([true, false], loaded.Proxied!);
|
||||
Assert.SequenceEqual([folder.Proxy(0), fx.Paths.FromRelative(frames[1].RelativePath)], loaded.Files);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyMatchesItsFrameToTheMicrosecondTheIndexKeeps()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
// A frame timed to the 100 ns tick (seven sub-second digits, or a file time): the sidecar keeps every digit, the
|
||||
// index six.
|
||||
var captured = Start.AddTicks(1_234_567);
|
||||
var staged = fx.Stage(captured, 50);
|
||||
var id = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, "ticks", staged.Path, "IMG_0001.JPG",
|
||||
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 frame = (await fx.Db.Frames.ListBySequenceAsync(id))[0];
|
||||
Assert.Equal(captured, ManifestStore.ReadSequence(folder.ManifestPath).Frames[0].CapturedAt);
|
||||
Assert.Equal(captured.AddTicks(-7), frame.CapturedAt, "the index keeps microseconds");
|
||||
|
||||
// The proxy pass writes the sidecar's time into the proxy it makes; a render asked to use proxies takes it.
|
||||
var images = fx.Service.Images;
|
||||
var made = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((1, 0), (made.Built, made.Reused));
|
||||
Assert.True(ArchiveImages.IsProxyOf(folder.Proxy(0), frame.CapturedAt, frame.Width, frame.Height, null));
|
||||
var loaded = await Titano.Data.Processing.SequenceFrames.LoadAsync(fx.Db, fx.Archive, sequence, useProxies: true, new ImageDecoder([]), fx.Ct);
|
||||
Assert.SequenceEqual([folder.Proxy(0)], loaded.Files);
|
||||
|
||||
// A client makes one from the index's time: it is kept, and the next pass reuses it rather than making its own.
|
||||
var sent = Proxy(frame.CapturedAt!.Value, 1);
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frame, sent));
|
||||
var again = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1), (again.Built, again.Reused));
|
||||
Assert.SequenceEqual(sent, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AThumbnailSizedProxyIsNoProxyOfAFrameReadThroughProxies()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx, 4032, 3024);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
// An earlier version made frame 0's proxy here from the original's 160 × 120 Exif thumbnail.
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(0), Proxy(frames[0].CapturedAt!.Value, 1, 160, 120), fx.Ct);
|
||||
|
||||
Assert.False(ArchiveImages.IsProxyOf(folder.Proxy(0), frames[0].CapturedAt, 4032, 3024, new ProxyPolicy()), "under the policy's 1920 px");
|
||||
Assert.True(ArchiveImages.IsProxyOf(folder.Proxy(0), frames[0].CapturedAt, 4032, 3024, null), "a host that decodes the original judges no size");
|
||||
// Renders and analyses read the original as the proxy pass would see it: no proxy.
|
||||
var loaded = await Titano.Data.Processing.SequenceFrames.LoadAsync(fx.Db, fx.Archive, sequence, useProxies: false, new ImageDecoder([]), fx.Ct);
|
||||
Assert.SequenceEqual([false, false], loaded.Proxied!);
|
||||
|
||||
await File.WriteAllBytesAsync(folder.Proxy(0), Proxy(frames[0].CapturedAt!.Value, 2, 1920, 1440), fx.Ct);
|
||||
loaded = await Titano.Data.Processing.SequenceFrames.LoadAsync(fx.Db, fx.Archive, sequence, useProxies: false, new ImageDecoder([]), fx.Ct);
|
||||
Assert.SequenceEqual([true, false], loaded.Proxied!);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PreviewOnlyFollowsTheProxyThereWhenTiersAreRecorded()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx, 4032, 3024);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var writer = new SequenceWriter(new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
|
||||
var tiers = new FrameTiers(fx.Db, writer, new ArchiveIndexer(fx.Db, writer));
|
||||
// A render decoded both originals from their thumbnails. Frame 0's proxy arrived meanwhile; frame 1's place holds
|
||||
// a thumbnail-sized one an earlier version made.
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(0), Proxy(frames[0].CapturedAt!.Value, 1, 1920, 1440), fx.Ct);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(1), Proxy(frames[1].CapturedAt!.Value, 2, 160, 120), fx.Ct);
|
||||
var preview = new FileTier(ImageFileFormat.Heif, DecodeTier.EmbeddedPreview, "managed", null, 160, 120);
|
||||
await tiers.RecordAsync(fx.Archive, sequence, new Dictionary<Guid, FileTier> { [frames[0].Id] = preview, [frames[1].Id] = preview },
|
||||
proxies: false, fx.Ct);
|
||||
|
||||
var recorded = ManifestStore.ReadSequence(folder.ManifestPath).Frames;
|
||||
Assert.Equal((DecodeTier.EmbeddedPreview, (int?)160, FrameFlags.None), (recorded[0].Tier, recorded[0].PreviewW, recorded[0].Flags & FrameFlags.PreviewOnly));
|
||||
Assert.Equal(FrameFlags.PreviewOnly, recorded[1].Flags & FrameFlags.PreviewOnly);
|
||||
Assert.Equal(1, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
|
||||
// Once frame 0's proxy is gone, an analysis (every frame follows its proxy) makes it preview-only again, and
|
||||
// hands back every frame as the sidecar has it.
|
||||
File.Delete(folder.Proxy(0));
|
||||
var current = await tiers.RecordAsync(fx.Archive, sequence, new Dictionary<Guid, FileTier>(), proxies: true, fx.Ct);
|
||||
Assert.True(current.Count == 2 && current.All(f => f.Flags.HasFlag(FrameFlags.PreviewOnly)), "both preview-only");
|
||||
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
Assert.Count(2, await tiers.RecordAsync(fx.Archive, sequence, new Dictionary<Guid, FileTier>(), proxies: true, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUnchangedProxyIsNotReadAgain()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var path = fx.Paths.Sequence(sequence.Folder).Proxy(0);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 1);
|
||||
bool Own() => ArchiveImages.IsProxyOf(path, frames[0].CapturedAt, frames[0].Width, frames[0].Height, null);
|
||||
await File.WriteAllBytesAsync(path, proxy, fx.Ct);
|
||||
var written = DateTime.UtcNow.AddMinutes(-5);
|
||||
File.SetLastWriteTimeUtc(path, written);
|
||||
Assert.True(Own());
|
||||
|
||||
// Same length and write time: a manifest listing thousands of proxies costs a stat per proxy, not a read.
|
||||
await File.WriteAllBytesAsync(path, new byte[proxy.Length], fx.Ct);
|
||||
File.SetLastWriteTimeUtc(path, written);
|
||||
Assert.True(Own(), "known");
|
||||
File.SetLastWriteTimeUtc(path, written.AddSeconds(1));
|
||||
Assert.False(Own(), "written since: read again");
|
||||
|
||||
// A file written moments ago is read every time: its clock may give a quick second write the same time.
|
||||
await File.WriteAllBytesAsync(path, proxy, fx.Ct);
|
||||
var now = File.GetLastWriteTimeUtc(path);
|
||||
Assert.True(Own());
|
||||
await File.WriteAllBytesAsync(path, new byte[proxy.Length], fx.Ct);
|
||||
File.SetLastWriteTimeUtc(path, now);
|
||||
Assert.False(Own(), "read again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AResumedProxyPassSetsTheBuiltStatusOnlyWhenEveryFrameHasItsProxy()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[1], Proxy(frames[1].CapturedAt!.Value, 1)));
|
||||
|
||||
// A pass resumed at frame 1 (paused, retried or restarted) finds that frame done, but frame 0 still waits: the
|
||||
// status must not tell a server's clients that nothing is wanted.
|
||||
var resumed = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 1, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 0, 0), (resumed.Built, resumed.Reused, resumed.Undecodable, resumed.Waiting));
|
||||
Assert.False(await ProxiesBuiltAsync(fx, sequence), "frame 0 has no proxy");
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2)));
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 1, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.True(await ProxiesBuiltAsync(fx, sequence), "every frame has its proxy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFrameReadFromItsProxyIsNotPreviewOnly()
|
||||
{
|
||||
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;
|
||||
// As a server probes them: its decoders read these HEIF files only through a 160 × 120 Exif thumbnail.
|
||||
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, sidecar with
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f with { Tier = DecodeTier.EmbeddedPreview, Flags = f.Flags | FrameFlags.PreviewOnly, PreviewW = 160, PreviewH = 120 })],
|
||||
});
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1)));
|
||||
|
||||
// Frame 0 now renders from its proxy, not from the thumbnail: it caps nothing. Its tier stays the original's.
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
var after = ManifestStore.ReadSequence(folder.ManifestPath).Frames;
|
||||
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.None, (int?)160), (after[0].Tier, after[0].Flags & FrameFlags.PreviewOnly, after[0].PreviewW));
|
||||
Assert.Equal(FrameFlags.PreviewOnly, after[1].Flags & FrameFlags.PreviewOnly);
|
||||
Assert.Equal(FrameFlags.None, (await fx.Db.Frames.GetAsync(frames[0].Id, fx.Ct))!.Flags & FrameFlags.PreviewOnly);
|
||||
Assert.Equal(1, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
|
||||
// Another photo's proxy in its place is no proxy of frame 0: the pass removes it, and the frame is preview-only again.
|
||||
await File.WriteAllBytesAsync(folder.Proxy(0), Proxy(frames[1].CapturedAt!.Value, 2), fx.Ct);
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.FileMissing(folder.Proxy(0));
|
||||
Assert.Equal(FrameFlags.PreviewOnly, ManifestStore.ReadSequence(folder.ManifestPath).Frames[0].Flags & FrameFlags.PreviewOnly);
|
||||
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThumbnailsDrawnFromProxiesFollowTheArchivesThumbnailSize()
|
||||
{
|
||||
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.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1, 640, 480)));
|
||||
Task<ImagePassResult> ThumbnailsAsync(bool force = false) =>
|
||||
images.BuildThumbnailsAsync(fx.Archive, sequence, force, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
(int, int) Entry()
|
||||
{
|
||||
using var pack = ThumbPackReader.Open(folder.ThumbsPackPath);
|
||||
return (pack.Entries[0].Width, pack.Entries[0].Height);
|
||||
}
|
||||
|
||||
var first = await ThumbnailsAsync();
|
||||
Assert.Equal((1, 0, 1), (first.Built, first.Reused, first.Undecodable));
|
||||
Assert.Equal((320, 240), Entry());
|
||||
|
||||
// A larger size in Settings › Archive: the proxy's thumbnail is drawn again at it, once.
|
||||
SetThumbnailEdge(fx, 480);
|
||||
var larger = await ThumbnailsAsync();
|
||||
Assert.Equal((1, 0), (larger.Built, larger.Reused));
|
||||
Assert.Equal((480, 360), Entry());
|
||||
var same = await ThumbnailsAsync();
|
||||
Assert.Equal((0, 1), (same.Built, same.Reused));
|
||||
|
||||
// A smaller one: once drawn at it, the thumbnail is reused, not drawn and appended to the pack on every pass.
|
||||
SetThumbnailEdge(fx, 240);
|
||||
Assert.Equal(1, (await ThumbnailsAsync(force: true)).Built);
|
||||
Assert.Equal((240, 180), Entry());
|
||||
var length = new FileInfo(folder.ThumbsPackPath).Length;
|
||||
var again = await ThumbnailsAsync();
|
||||
Assert.Equal((0, 1, 1), (again.Built, again.Reused, again.Undecodable));
|
||||
Assert.Equal(length, new FileInfo(folder.ThumbsPackPath).Length);
|
||||
}
|
||||
|
||||
private static void SetThumbnailEdge(ArchiveFixture fx, int longEdge)
|
||||
{
|
||||
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
|
||||
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { ThumbnailPolicy = manifest.ThumbnailPolicy with { LongEdge = longEdge } });
|
||||
}
|
||||
|
||||
private static async Task<bool> ProxiesBuiltAsync(ArchiveFixture fx, Sequence sequence) =>
|
||||
(await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.ProxiesBuilt);
|
||||
|
||||
/// <summary>
|
||||
/// Two ingested frames whose originals the archive engine takes for HEIF (its decoders read none), their size in the
|
||||
/// sidecar <paramref name="width"/> × <paramref name="height"/> when given.
|
||||
/// sidecar and the index <paramref name="width"/> × <paramref name="height"/> when given.
|
||||
/// </summary>
|
||||
private static async Task<(Sequence Sequence, IReadOnlyList<Frame> Frames)> HeifSequenceAsync(ArchiveFixture fx, int? width = null, int? height = null)
|
||||
{
|
||||
@@ -138,6 +375,12 @@ public sealed class ProxyTests(TestContext context)
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f with { Format = ImageFileFormat.Heif, W = width ?? f.W, H = height ?? f.H })],
|
||||
});
|
||||
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, id], fx.Ct);
|
||||
if (width is { } w && height is { } h)
|
||||
await session.ExecuteAsync("UPDATE frames SET width = $1, height = $2 WHERE sequence_id = $3", [w, h, id], fx.Ct);
|
||||
}
|
||||
return (sequence, await fx.Db.Frames.ListBySequenceAsync(id));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
@@ -5,16 +7,20 @@ using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Dng;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Import;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Data.Processing.Jobs;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Data.Tests.Archiving;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Processing;
|
||||
@@ -115,6 +121,163 @@ public sealed class AnalysisJobTests(TestContext context)
|
||||
Assert.Equal(written, File.GetLastWriteTimeUtc(folder.ManifestPath));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AHeifFrameTheServerReadsFromItsProxyCapsNothing()
|
||||
{
|
||||
// The server's decoders (BRIEF §4.2, §8.1): a HEIF gives them only the 160 × 120 JPEG thumbnail of its Exif.
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { Archive = o.Archive with { Decoder = DecoderFactory.CreateServer() } });
|
||||
var directory = Path.Combine(fx.Archive.Paths.Root, "Heif");
|
||||
Directory.CreateDirectory(directory);
|
||||
var start = new DateTime(2026, 9, 28, 18, 0, 0);
|
||||
for (var i = 0; i < 4; i++)
|
||||
await File.WriteAllBytesAsync(Path.Combine(directory, $"IMG_{i + 1:0000}.HEIC"), HeifFile.Create(start.AddSeconds(10 * i), 4032, 3024), fx.Ct);
|
||||
await fx.Archive.ScanAsync(ScanMode.Full);
|
||||
var location = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Archive.Id, fx.Ct)).Single(l => l.Folder == "Heif");
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(location.Id, fx.Ct))!;
|
||||
var folder = fx.Folder(sequence);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// Without proxies the server has nothing better than those thumbnails: preview-only, and the advisor caps the output.
|
||||
await LightAnalysisAsync(fx, sequence);
|
||||
var probed = ManifestStore.ReadSequence(folder.ManifestPath).Frames;
|
||||
Assert.True(probed.All(f => f is { Tier: DecodeTier.EmbeddedPreview, PreviewW: 160, PreviewH: 120 } && f.Flags.HasFlag(FrameFlags.PreviewOnly)),
|
||||
"preview-only at the thumbnail's size");
|
||||
Assert.Equal(4, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
var rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
|
||||
var capped = Advisor.Recommend(LightAnalyzer.Analyze(rows), null, SequenceContext.FromFrames(rows));
|
||||
Assert.Equal((AdvisorKeys.ResolutionPreview, "720p-preview"), (capped.Find(AdvisorParameters.Resolution)!.ReasonKey, capped.Find(AdvisorParameters.ExportPreset)!.Value as string));
|
||||
Assert.True(capped.Findings.Any(f => f.Key == FindingKeys.PreviewOnly), "preview-only finding");
|
||||
|
||||
// A client sends their proxies (BRIEF §2.3) at the policy's 1920 px: the server renders the frames from them, so none
|
||||
// is preview-only and the advice follows. The tier and preview size stay the originals'.
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
foreach (var frame in rows) await File.WriteAllBytesAsync(folder.Proxy(frame.Index), Proxy(frame.CapturedAt!.Value, 1920, 1440), fx.Ct);
|
||||
await LightAnalysisAsync(fx, sequence);
|
||||
var proxied = ManifestStore.ReadSequence(folder.ManifestPath).Frames;
|
||||
Assert.True(proxied.All(f => f is { Tier: DecodeTier.EmbeddedPreview, PreviewW: 160 } && !f.Flags.HasFlag(FrameFlags.PreviewOnly)), "not preview-only");
|
||||
Assert.Equal(0, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
|
||||
Assert.True(rows.All(f => !f.Flags.HasFlag(FrameFlags.PreviewOnly)), "index flags");
|
||||
var advice = Advisor.Recommend(LightAnalyzer.Analyze(rows), null, SequenceContext.FromFrames(rows));
|
||||
Assert.Equal((AdvisorKeys.ResolutionSource, "4k-hevc"), (advice.Find(AdvisorParameters.Resolution)!.ReasonKey, advice.Find(AdvisorParameters.ExportPreset)!.Value as string));
|
||||
Assert.False(advice.Findings.Any(f => f.Key == FindingKeys.PreviewOnly), "no preview-only finding");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesThatArriveDuringADeepAnalysisStillCount()
|
||||
{
|
||||
// A server, whose advisor rules no codec out: it reads these HEIF files only through their 160 × 120 Exif
|
||||
// thumbnails until proxies come (BRIEF §2.3).
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { Host = EncoderHost.Server });
|
||||
var directory = Path.Combine(fx.Archive.Paths.Root, "Heif");
|
||||
Directory.CreateDirectory(directory);
|
||||
var start = new DateTime(2026, 9, 28, 18, 0, 0);
|
||||
for (var i = 0; i < 4; i++)
|
||||
await File.WriteAllBytesAsync(Path.Combine(directory, $"IMG_{i + 1:0000}.HEIC"), HeifFile.Create(start.AddSeconds(10 * i), 4032, 3024), fx.Ct);
|
||||
await fx.Archive.ScanAsync(ScanMode.Full);
|
||||
var location = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Archive.Id, fx.Ct)).Single(l => l.Folder == "Heif");
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(location.Id, fx.Ct))!;
|
||||
var folder = fx.Folder(sequence);
|
||||
await fx.StartEngineAsync(workers: 2);
|
||||
async Task<string?> PresetAsync() => ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct)).Export.Preset.AutoValue;
|
||||
await LightAnalysisAsync(fx, sequence);
|
||||
Assert.Equal(4, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
Assert.Equal("720p-preview", await PresetAsync());
|
||||
|
||||
// A deep analysis starts on the originals; while it runs, the proxies arrive and a light analysis on the other
|
||||
// worker counts them.
|
||||
fx.Decoder.Hold = "IMG_0001.HEIC";
|
||||
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
foreach (var frame in await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))
|
||||
await File.WriteAllBytesAsync(folder.Proxy(frame.Index), Proxy(frame.CapturedAt!.Value, 1920, 1440), fx.Ct);
|
||||
await LightAnalysisAsync(fx, sequence);
|
||||
Assert.Equal(0, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
Assert.Equal("4k-hevc", await PresetAsync());
|
||||
fx.Decoder.Release();
|
||||
await fx.WaitForAsync(deep.Id, JobState.Done);
|
||||
|
||||
// The deep pass decoded the originals from their thumbnails, yet the frames are read from their proxies by now:
|
||||
// it flags none preview-only again, and its advice caps nothing.
|
||||
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Frames.All(f => f.Tier == DecodeTier.EmbeddedPreview && !f.Flags.HasFlag(FrameFlags.PreviewOnly)),
|
||||
"not preview-only");
|
||||
Assert.Equal(0, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
|
||||
Assert.Equal("4k-hevc", await PresetAsync());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFrameTheDeepAnalysisCouldNotReadIsReadAgainOnceItsProxyArrives()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Flickering());
|
||||
var folder = fx.Folder(sequence);
|
||||
// Frame 4 is a HEIF this host reads only from its proxy (BRIEF §2.3); the proxy a client sends shows the photo.
|
||||
var original = Path.Combine(folder.Folder, ProcessingFixture.FileName(3));
|
||||
var photo = await File.ReadAllBytesAsync(original, fx.Ct);
|
||||
await File.WriteAllBytesAsync(original, [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8], fx.Ct);
|
||||
var frame = (await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))[3];
|
||||
await using (var session = await fx.Db.Database.OpenAsync(fx.Ct))
|
||||
await session.ExecuteAsync("UPDATE frames SET format = $1 WHERE id = $2", [(int)ImageFileFormat.Heif, frame.Id], fx.Ct);
|
||||
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, sidecar with
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f.Id == frame.Id ? f with { Format = ImageFileFormat.Heif } : f)],
|
||||
});
|
||||
fx.Decoder.HoldFrame(25);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A deep analysis reads the original, finds no pixels, and is interrupted once its checkpoint holds that verdict.
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
await fx.Engine.CancelAsync(job.Id, fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Cancelled);
|
||||
|
||||
// The proxy arrives meanwhile: the frame is no longer read as the checkpoint read it, so the resumed run starts over.
|
||||
Directory.CreateDirectory(folder.Proxies);
|
||||
await File.WriteAllBytesAsync(folder.Proxy(3), photo, fx.Ct);
|
||||
fx.Decoder.Hold = null;
|
||||
await fx.Engine.ResumeAsync(job.Id, fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
var report = SequenceAnalyser.ReadReport(folder, sequence.FrameCount)!;
|
||||
Assert.Empty(report.Issues.Undecodable);
|
||||
Assert.SequenceEqual([3], report.ProxyFrames!);
|
||||
|
||||
// Without its proxy, a deep analysis lists the frame as unreadable, a sequence warning...
|
||||
File.Delete(folder.Proxy(3));
|
||||
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(deep.Id, JobState.Done);
|
||||
Assert.SequenceEqual([3], SequenceAnalyser.ReadReport(folder, sequence.FrameCount)!.Issues.Undecodable);
|
||||
var unreadable = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
|
||||
Assert.True(unreadable.Status.HasFlag(SequenceStatus.AnalyzedDeep | SequenceStatus.HasWarnings), unreadable.Status.ToString());
|
||||
|
||||
// ...a verdict that no longer holds once the proxy is there: the next light analysis drops the report and its warning.
|
||||
await File.WriteAllBytesAsync(folder.Proxy(3), photo, fx.Ct);
|
||||
await LightAnalysisAsync(fx, sequence);
|
||||
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
|
||||
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), "the report is stale");
|
||||
Assert.Less(row.WarningCount, unreadable.WarningCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACheckpointOfASequenceReadFromItsOriginalsKeepsTheKeyEarlierVersionsWrote()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Flickering(4));
|
||||
var frames = await Titano.Data.Processing.SequenceFrames.LoadAsync(fx.Db, fx.Archive.Archive, sequence, useProxies: false, new ImageDecoder([fx.Decoder]), fx.Ct);
|
||||
Assert.SequenceEqual([false, false, false, false], frames.Proxied!);
|
||||
|
||||
// A deep analysis interrupted before an upgrade resumes after it (a server restarted mid-run does not start over).
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var f in frames.Frames)
|
||||
hash.AppendData(Encoding.UTF8.GetBytes($"{f.Id:N}/{f.Sha256}/{f.Size}/{f.Flags & Titano.Data.Processing.SequenceFrames.NotAnalysed};"));
|
||||
var earlier = Convert.ToHexStringLower(hash.GetHashAndReset())[..16];
|
||||
Assert.Equal(earlier, SequenceAnalyser.ContentKey(frames));
|
||||
|
||||
// A frame read from its proxy since makes the checkpoint stale.
|
||||
Assert.NotEqual(earlier, SequenceAnalyser.ContentKey(frames with { Proxied = [false, true, false, false] }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeepAnalysisFlagsFramesItCannotDecodeAndListsThemOnce()
|
||||
{
|
||||
@@ -386,6 +549,21 @@ public sealed class AnalysisJobTests(TestContext context)
|
||||
foreach (var text in new[] { null, "6", "2;3", "2;x", "a" }) Assert.Equal(0, AnalyseJobHandler.Parse(text, 5).Next);
|
||||
}
|
||||
|
||||
private static async Task LightAnalysisAsync(ProcessingFixture fx, Sequence sequence)
|
||||
{
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
}
|
||||
|
||||
/// <summary>A JPEG (320 × 240 unless sized) with <paramref name="captured"/> in its Exif, as a client makes a proxy.</summary>
|
||||
private static byte[] Proxy(DateTime captured, int width = 320, int height = 240)
|
||||
{
|
||||
using var image = new ImageBuffer(width, height);
|
||||
for (var c = 0; c < 3; c++) image.Plane(c).Fill(0.3f + c * 0.1f);
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { CapturedAt = captured, Software = "Titano" });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
private static async Task<List<bool>> AnalysedAsync(ProcessingFixture fx, params Sequence[] sequences)
|
||||
{
|
||||
var analysed = new List<bool>();
|
||||
|
||||
@@ -95,7 +95,7 @@ internal sealed class ProcessingFixture : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Managed decoding that records every request and can hold one file's decode until the job is cancelled.</summary>
|
||||
/// <summary>Managed decoding that records every request and can hold one file's decode until the job is cancelled or the decode is released.</summary>
|
||||
internal sealed class GateDecoder : IImageDecoderProvider
|
||||
{
|
||||
private readonly ManagedDecoderProvider _managed = new();
|
||||
@@ -116,13 +116,19 @@ internal sealed class GateDecoder : IImageDecoderProvider
|
||||
/// <summary>Completed when a decode of <see cref="Hold"/> started waiting.</summary>
|
||||
public TaskCompletionSource Holding { get; private set; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
private TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public void HoldFrame(int index, DecodePurpose? purpose = null, int? edge = null)
|
||||
{
|
||||
Holding = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_released = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
(HoldPurpose, HoldEdge) = (purpose, edge);
|
||||
Hold = ProcessingFixture.FileName(index);
|
||||
}
|
||||
|
||||
/// <summary>Lets the held decode go on, as a slow read would.</summary>
|
||||
public void Release() => _released.TrySetResult();
|
||||
|
||||
/// <summary>Tiers <see cref="Probe(string, ImageFileFormat)"/> reports per file name instead of the managed provider's (a
|
||||
/// host that reads them only as previews, or not at all).</summary>
|
||||
public ConcurrentDictionary<string, FileTier> Tiers { get; } = new();
|
||||
@@ -152,7 +158,13 @@ internal sealed class GateDecoder : IImageDecoderProvider
|
||||
&& (HoldEdge ?? request.MaxLongEdge) == request.MaxLongEdge)
|
||||
{
|
||||
Holding.TrySetResult();
|
||||
cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(30));
|
||||
try
|
||||
{
|
||||
_released.Task.Wait(TimeSpan.FromSeconds(30), cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
}
|
||||
if (Unreadable.ContainsKey(name)) throw new IOException($"The process cannot access the file '{request.Path}' because it is being used by another process.");
|
||||
|
||||
@@ -32,10 +32,14 @@ public sealed class RemoteEditingTests(TestContext context)
|
||||
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
|
||||
var path = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).AnalysisPath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
const string report = """{"version":1,"frameCount":1}""";
|
||||
var report = Reports.Minimal(1).ToJson();
|
||||
await File.WriteAllTextAsync(path, report, context.Cancellation);
|
||||
Assert.Equal(report, await client.GetAnalysisReportAsync(frame.SequenceId, context.Cancellation));
|
||||
|
||||
// One made for other frames is not this sequence's report.
|
||||
await File.WriteAllTextAsync(path, Reports.Minimal(2).ToJson(), context.Cancellation);
|
||||
Assert.Null(await client.GetAnalysisReportAsync(frame.SequenceId, context.Cancellation), "another frame count");
|
||||
|
||||
var gone = await Assert.ThrowsAsync<TitanoApiException>(() => client.GetAnalysisReportAsync(Guid.CreateVersion7(), context.Cancellation));
|
||||
Assert.Equal(HttpStatusCode.NotFound, gone.Status);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using Titano.Core.Analysis.Deep;
|
||||
|
||||
namespace Titano.Server.Tests;
|
||||
|
||||
/// <summary>Deep-analysis reports as a server keeps them in <c>.titano/analysis.json</c>.</summary>
|
||||
internal static class Reports
|
||||
{
|
||||
/// <summary>A report of <paramref name="frames"/> frames that found <paramref name="undecodable"/> unreadable and measured nothing else.</summary>
|
||||
public static DeepAnalysisReport Minimal(int frames, params int[] undecodable) => new()
|
||||
{
|
||||
FrameCount = frames,
|
||||
Flicker = new FlickerSummary(0, 0, null, 0, 0, 1),
|
||||
Exposure = new ExposureSummary(0, 0, null, null, 0, []),
|
||||
WhiteBalance = new WhiteBalanceSummary(0, 0, null, null),
|
||||
Shake = new ShakeSummary(0, 0, 0, 0, false, 0),
|
||||
Motion = new MotionSummary(0, null, null, null),
|
||||
Sky = new SkySummary(DayNight.Unknown, 0, 0, 0, null, false, null),
|
||||
Issues = new FrameIssues(undecodable, [], [], [], []),
|
||||
};
|
||||
}
|
||||
@@ -63,6 +63,28 @@ public sealed class ProcessingModuleTests(TestContext context)
|
||||
Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "settings" } changed && changed.SequenceId == sequenceId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyThatArrivesHasTheSequenceAnalysedAgain()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: Production);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
// A HEIF original the server cannot decode (BRIEF §2.3): what it renders depends on the proxy a client sends.
|
||||
var upload = await Uploads.UploadAsync(editor, [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, 1)], "IMG_0001.HEIC",
|
||||
sessionKey: "roof");
|
||||
await LightAnalysesAsync(server, upload.SequenceId, 1);
|
||||
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
|
||||
|
||||
using var image = new Core.Imaging.ImageBuffer(320, 240);
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { CapturedAt = frame.CapturedAt, Software = "Titano" });
|
||||
using var proxy = new ByteArrayContent(JpegEncoder.Encode(image, new JpegEncodeOptions { App1Segments = [exif[4..]] }));
|
||||
proxy.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
|
||||
using (var stored = await editor.PutAsync($"/api/v1/frames/{frame.Id}/proxy", proxy))
|
||||
await stored.ExpectAsync(HttpStatusCode.NoContent);
|
||||
|
||||
// A frame read from its proxy is no longer preview-only, so the advisor's Auto values are worked out again.
|
||||
await LightAnalysesAsync(server, upload.SequenceId, 2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerRendersManagedFormatsAndLeavesMp4ToRenderNodes()
|
||||
{
|
||||
@@ -196,6 +218,19 @@ public sealed class ProcessingModuleTests(TestContext context)
|
||||
return drained;
|
||||
}
|
||||
|
||||
/// <summary>Waits until <paramref name="count"/> light analyses of the sequence have finished.</summary>
|
||||
private static async Task LightAnalysesAsync(TestServer server, Guid sequenceId, int count)
|
||||
{
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (true)
|
||||
{
|
||||
var done = (await server.Database.Jobs.ListAsync(JobState.Done, JobKind.LightAnalyse, 200)).Items.Count(j => j.TargetIds.Contains(sequenceId));
|
||||
if (done >= count) return;
|
||||
Assert.True(DateTime.UtcNow < until, $"light analyses finished: {done} of {count}");
|
||||
await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Uploads a synthetic scene with Exif into one new sequence; returns its id.</summary>
|
||||
private static async Task<Guid> UploadSceneAsync(HttpClient editor)
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Net.Http.Headers;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Storage;
|
||||
using Titano.Testing;
|
||||
@@ -62,6 +63,94 @@ public sealed class ProxyUploadTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnotherPhotosProxyInTheFramesPlaceIsAskedForAgainAndNeverServed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var upload = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
|
||||
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
|
||||
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(upload.SequenceId));
|
||||
// Proxies are named by frame index: after a frame was inserted before this one, its place holds another photo's.
|
||||
var path = new Core.Archiving.ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).Proxy(frame.Index);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
await File.WriteAllBytesAsync(path, Proxy(frame.CapturedAt!.Value.AddSeconds(-10)));
|
||||
|
||||
Assert.Equal((true, false), Wanted((await ManifestAsync(editor, upload.SequenceId)).Frames.Single()));
|
||||
using (var served = await editor.GetAsync($"/api/v1/frames/{frame.Id}/proxy"))
|
||||
Assert.Equal("asset_missing", (await served.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
|
||||
// The frame's own proxy takes its place.
|
||||
var proxy = Proxy(frame.CapturedAt!.Value);
|
||||
using (var stored = await PutAsync(editor, frame.Id, proxy))
|
||||
await stored.ExpectAsync(HttpStatusCode.NoContent);
|
||||
Assert.Equal((false, true), Wanted((await ManifestAsync(editor, upload.SequenceId)).Frames.Single()));
|
||||
await Http.BytesEqualAsync(proxy, editor.GetByteArrayAsync($"/api/v1/frames/{frame.Id}/proxy"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesAddedAfterEveryProxyArrivedAreAskedForTheirs()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var first = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
|
||||
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
|
||||
using (var stored = await PutAsync(editor, frame.Id, Proxy(frame.CapturedAt!.Value)))
|
||||
await stored.ExpectAsync(HttpStatusCode.NoContent);
|
||||
|
||||
// A frame comes after the proxy pass found every proxy there: until the next pass the status still says so, yet
|
||||
// the new frame is asked for its proxy and the first keeps its own.
|
||||
var second = await Uploads.UploadAsync(editor, Heif(2), "IMG_0002.HEIC", sessionKey: "roof");
|
||||
Assert.Equal(first.SequenceId, second.SequenceId);
|
||||
await server.Database.Sequences.UpdateStatusAsync(first.SequenceId, SequenceStatus.ProxiesBuilt, SequenceStatus.None, context.Cancellation);
|
||||
var frames = (await ManifestAsync(editor, first.SequenceId)).Frames;
|
||||
Assert.Equal((false, true), Wanted(frames.Single(f => f.Id == first.FrameId)));
|
||||
Assert.Equal((true, false), Wanted(frames.Single(f => f.Id == second.FrameId)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyTheServerMadeIsServedForAFrameTimedToTheTick()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
// Seven sub-second digits: the sidecar, and the proxy made from it, keep them all; the index keeps six.
|
||||
var upload = await Uploads.UploadAsync(editor, Proxy(new DateTime(2026, 9, 28, 18, 2, 11).AddTicks(1_234_567)), "IMG_0001.JPG", sessionKey: "roof");
|
||||
|
||||
// The proxy pass the upload queued makes the frame's proxy, and the server serves it.
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (true)
|
||||
{
|
||||
using var proxy = await editor.GetAsync($"/api/v1/frames/{upload.FrameId}/proxy");
|
||||
if (proxy.StatusCode == HttpStatusCode.OK) break;
|
||||
Assert.True(DateTime.UtcNow < until, $"proxy not served: {(int)proxy.StatusCode}");
|
||||
await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AReportThatFoundAFrameUnreadableBeforeItsProxyCameIsNotServed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var upload = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
|
||||
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
|
||||
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(upload.SequenceId));
|
||||
// A deep analysis ran before the proxy came and found no pixels in the HEIF original.
|
||||
var path = new Core.Archiving.ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).AnalysisPath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
Reports.Minimal(1, undecodable: 0).Save(path);
|
||||
var url = $"/api/v1/sequences/{sequence.Id}/analysis/report";
|
||||
using (var before = await editor.GetAsync(url))
|
||||
await before.ExpectAsync(HttpStatusCode.OK);
|
||||
|
||||
// Once the frame is read from its proxy, that verdict and its advice to exclude the frame no longer hold, even
|
||||
// before a light analysis has dropped the deep status.
|
||||
using (var stored = await PutAsync(editor, frame.Id, Proxy(frame.CapturedAt!.Value)))
|
||||
await stored.ExpectAsync(HttpStatusCode.NoContent);
|
||||
using var after = await editor.GetAsync(url);
|
||||
Assert.Equal("analysis", (await after.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesTheServerDecodesAskForNoProxy()
|
||||
{
|
||||
@@ -87,6 +176,8 @@ public sealed class ProxyUploadTests(TestContext context)
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
private static (bool WantsProxy, bool HasProxy) Wanted(ManifestFrame frame) => (frame.WantsProxy, frame.HasProxy);
|
||||
|
||||
private static Task<HttpResponseMessage> PutAsync(HttpClient client, Guid frameId, byte[] body)
|
||||
{
|
||||
var content = new ByteArrayContent(body);
|
||||
|
||||
Reference in new issue
Block a user