fix(imaging): record only what decoding proves and find GPR JPEGs across sequences
- Preview sizes come from probes and unscaled decodes: a size-limited decode picks the smallest preview that reaches its edge (CR3 PRVW 1620x1080), so renders and deep passes record its tier without a size and the output cap keeps the largest preview's. - A read error is not an undecodable file: ImageDecoder.Decode throws the IOException when a provider could not read the file and none produced pixels. Deep passes never flag frames they could not read or that vanished, and frames only an interrupted earlier run found undecodable are decoded again before they are flagged. - Renders resolve stand-ins only for frames the pipeline asks for; frames the read-ahead meets on the way (skipped by speed-ups) are left alone. - A GoPro GPR finds its JPEG in the index when an import or upload kept it in a sequence of its own (same original stem and capture time), for probes, deep analysis, renders, thumbnails, proxies and the editor; GPRs whose JPEG is indexed later are probed again. - Thumbnails judge an embedded preview by its own JPEG header. - PostgreSQL writes tier fields 1000 frames per statement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
19 files changed
+689
-111
No files matched your search
@@ -9,6 +9,7 @@ using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Tests.Analysis.Deep;
|
||||
using Titano.Core.Tests.Raw;
|
||||
using Titano.Testing;
|
||||
@@ -101,11 +102,12 @@ public sealed class DecodeTierTests(TestContext context)
|
||||
var dng = SyntheticDng.Write(scene, new DngSpec());
|
||||
var renderer = new FrameImageRenderer(DecoderFactory.CreateServer());
|
||||
|
||||
EncodedImage Thumbnail(string name, int previewWidth, bool sizeKnown)
|
||||
EncodedImage Thumbnail(string name, int previewWidth, bool sizeKnown, int? storedWidth = null)
|
||||
{
|
||||
// The preview is appended after the DNG, which the TIFF offsets never reach.
|
||||
var preview = TestPhotos.Jpeg(Start, 3, width: previewWidth, height: previewWidth * 3 / 4);
|
||||
File.WriteAllBytes(Path.Combine(sequence.Originals, name), [.. dng, .. preview]);
|
||||
var stored = storedWidth ?? previewWidth;
|
||||
var frame = new SidecarFrame
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
@@ -115,8 +117,8 @@ public sealed class DecodeTierTests(TestContext context)
|
||||
H = 480,
|
||||
PreviewOffset = dng.Length,
|
||||
PreviewLength = preview.Length,
|
||||
PreviewW = sizeKnown ? previewWidth : null,
|
||||
PreviewH = sizeKnown ? previewWidth * 3 / 4 : null,
|
||||
PreviewW = sizeKnown ? stored : null,
|
||||
PreviewH = sizeKnown ? stored * 3 / 4 : null,
|
||||
};
|
||||
return renderer.Thumbnail(sequence, frame)!;
|
||||
}
|
||||
@@ -126,6 +128,9 @@ public sealed class DecodeTierTests(TestContext context)
|
||||
Assert.Equal((320, 240, DecodeTier.Native), (small.Width, small.Height, small.Tier));
|
||||
var unknown = Thumbnail("unknown.dng", 200, sizeKnown: false);
|
||||
Assert.Equal((320, DecodeTier.Native), (unknown.Width, unknown.Tier));
|
||||
// The stored size can be a GPR companion's, larger than the embedded preview: the JPEG's own header decides.
|
||||
var companionSized = Thumbnail("companion.dng", 200, sizeKnown: true, storedWidth: 4000);
|
||||
Assert.Equal((320, DecodeTier.Native), (companionSized.Width, companionSized.Tier));
|
||||
var large = Thumbnail("large.dng", 400, sizeKnown: true);
|
||||
Assert.Equal((320, 240, DecodeTier.EmbeddedPreview), (large.Width, large.Height, large.Tier));
|
||||
Assert.Equal(320, JpegDecoder.ReadInfo(large.Jpeg).Width);
|
||||
@@ -177,22 +182,60 @@ public sealed class DecodeTierTests(TestContext context)
|
||||
[Test]
|
||||
public async Task FramesBothAnalysesFoundUndecodableAreListedOnce()
|
||||
{
|
||||
// Frame 4 does not decode; frame 7 is not read either (missing, or beyond this host), which never flags it.
|
||||
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 12 }))
|
||||
{
|
||||
Undecodable = [4],
|
||||
Undecodable = [4, 7],
|
||||
};
|
||||
var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options);
|
||||
var metadata = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
|
||||
var context = new SequenceContext { FrameCount = source.Count, SourceWidth = 96, SourceHeight = 64 };
|
||||
|
||||
// Before the deep pass flagged the frame, only its own finding names it.
|
||||
// Before the deep pass flagged the frame, only its own finding names them.
|
||||
var unflagged = Advisor.Recommend(LightAnalyzer.Analyze(metadata), deep, context).Findings.Where(f => f.Key == DeepFindingKeys.UnreadableFrames).ToList();
|
||||
Assert.SequenceEqual([4], unflagged.Single().Frames);
|
||||
Assert.SequenceEqual([4, 7], unflagged.Single().Frames);
|
||||
|
||||
// Once flagged, the light analysis lists it and the deep finding is not repeated.
|
||||
// Once frame 4 is flagged both analyses report it: one finding over both lists, counted once.
|
||||
var flagged = metadata.Select(m => m.Index == 4 ? m with { Flags = FrameFlags.Undecodable } : m).ToList();
|
||||
var light = LightAnalyzer.Analyze(flagged);
|
||||
var findings = Advisor.Recommend(light, deep, context).Findings.Where(f => f.Key == DeepFindingKeys.UnreadableFrames).ToList();
|
||||
Assert.Same(light.Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames), findings.Single());
|
||||
Assert.SequenceEqual([4], light.Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames).Frames);
|
||||
var merged = Advisor.Recommend(light, deep, context).Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames);
|
||||
Assert.SequenceEqual([4, 7], merged.Frames);
|
||||
Assert.Equal((FindingSeverity.Warning, 2), (merged.Severity, Convert.ToInt32(merged.Arguments.Single())));
|
||||
|
||||
// A frame flagged since the deep pass (a render found it broken) joins the list too.
|
||||
var later = LightAnalyzer.Analyze(flagged.Select(m => m.Index == 9 ? m with { Flags = FrameFlags.Undecodable } : m).ToList());
|
||||
var all = Advisor.Recommend(later, deep, context).Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames);
|
||||
Assert.Equal((3, 3), (all.Frames.Count, Convert.ToInt32(all.Arguments.Single())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FramesTheCamerasIntervalometerShotTimeTheirGapsAdaptively()
|
||||
{
|
||||
var metadata = new FrameMetadata { Format = ImageFileFormat.Rw2, IntervalShooting = true };
|
||||
Assert.Equal(FrameFlags.Intervalometer, SequenceFrames.FromMetadata(Guid.CreateVersion7(), "a.rw2", "a.rw2", 10, null, metadata).Flags);
|
||||
Assert.Equal(FrameFlags.None, SequenceFrames.FromMetadata(Guid.CreateVersion7(), "b.rw2", "b.rw2", 10, null, metadata with { IntervalShooting = false }).Flags);
|
||||
|
||||
// 60 frames 10 s apart with one 40 s gap: a sparse gap alone keeps the timing constant (motion unmeasured).
|
||||
LightFrame Frame(int i, FrameFlags flags) => new()
|
||||
{
|
||||
Index = i,
|
||||
CapturedAt = Start.AddSeconds(10 * i + (i >= 30 ? 30 : 0)),
|
||||
Width = 6000,
|
||||
Height = 4000,
|
||||
Flags = flags,
|
||||
};
|
||||
var context = new SequenceContext { FrameCount = 60, SourceWidth = 6000, SourceHeight = 4000 };
|
||||
var plain = LightAnalyzer.Analyze([.. Enumerable.Range(0, 60).Select(i => Frame(i, FrameFlags.None))]);
|
||||
Assert.Equal(0, plain.IntervalometerFrames);
|
||||
var free = Advisor.Recommend(plain, null, context).Find(AdvisorParameters.TimingMode)!;
|
||||
Assert.Equal((AdvisorKeys.TimingSparseGaps, (object?)TimingMode.Constant), (free.ReasonKey, free.Value));
|
||||
|
||||
// The camera's own intervalometer shot them: its pause was deliberate, so adaptive timing keeps it short.
|
||||
var shot = LightAnalyzer.Analyze([.. Enumerable.Range(0, 60).Select(i => Frame(i, FrameFlags.Intervalometer))]);
|
||||
Assert.Equal(60, shot.IntervalometerFrames);
|
||||
var advice = Advisor.Recommend(shot, null, context).Find(AdvisorParameters.TimingMode)!;
|
||||
Assert.Equal((AdvisorKeys.TimingIntervalometer, (object?)TimingMode.Adaptive), (advice.ReasonKey, advice.Value));
|
||||
Assert.Equal(1, Convert.ToInt32(advice.ReasonArgs.Single()));
|
||||
}
|
||||
}
|
||||
@@ -260,6 +260,52 @@ public sealed class ManagedDecoderProviderTests(TestContext context)
|
||||
Assert.Equal("managed-preview", new ManagedDecoderProvider().Probe(big).Decoder);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GoProRawDecodesThroughItsJpegWhereTheImportKeptIt()
|
||||
{
|
||||
// An import splits sessions per format: the JPEG lives in another sequence folder, under its imported name.
|
||||
var gpr = Write("GOPR0003.GPR", Gpr(previewWidth: 64, previewHeight: 48));
|
||||
var elsewhere = Path.Combine(context.CreateTempDirectory("jpeg-sequence"), "2026-09-28_0003.JPG");
|
||||
File.WriteAllBytes(elsewhere, JpegFile(160, 120, 1));
|
||||
var server = DecoderFactory.CreateServer();
|
||||
|
||||
using (var decoded = server.Decode(new DecodeRequest(gpr, Companion: elsewhere)))
|
||||
Assert.Equal(("managed-sidecar", 160, 120), (decoded!.Decoder, decoded.SourceWidth, decoded.SourceHeight));
|
||||
var probe = server.Probe(gpr, ImageFileFormat.Gpr, elsewhere);
|
||||
Assert.Equal((DecodeTier.EmbeddedPreview, "managed-sidecar", 160, 120), (probe.Tier, probe.Decoder, probe.Width, probe.Height));
|
||||
|
||||
// A JPEG that is gone (deleted since) leaves the embedded preview; other formats ignore the companion.
|
||||
var gone = Path.Combine(_dir, "gone.JPG");
|
||||
using (var preview = server.Decode(new DecodeRequest(gpr, Companion: gone)))
|
||||
Assert.Equal(("managed-preview", 64), (preview!.Decoder, preview.Pixels.Width));
|
||||
Assert.Equal("managed-preview", server.Probe(gpr, ImageFileFormat.Gpr, gone).Decoder);
|
||||
var jpeg = Write("plain.jpg", JpegFile(64, 48, 1));
|
||||
using (var plain = server.Decode(new DecodeRequest(jpeg, Companion: elsewhere)))
|
||||
Assert.Equal(("managed-jpeg", 64), (plain!.Decoder, plain.SourceWidth));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFileNoProviderCouldReadIsAReadErrorNotAnUndecodableFile()
|
||||
{
|
||||
var path = Write("locked.jpg", JpegFile(64, 48, 1));
|
||||
// Every provider failed to read the file (locked by another program, a network read failed): nothing is known
|
||||
// about its content, so the caller gets the read error instead of "nothing decodes it".
|
||||
var unreadable = new ImageDecoder([new ScriptedProvider("a", _ => throw new IOException("sharing violation"))]);
|
||||
Assert.Throws<IOException>(() => unreadable.Decode(new DecodeRequest(path)));
|
||||
// One provider read it and found nothing, another could not read it: still unproven.
|
||||
var mixed = new ImageDecoder([new ScriptedProvider("a", _ => null), new ScriptedProvider("b", _ => throw new IOException("short read"))]);
|
||||
Assert.Throws<IOException>(() => mixed.Decode(new DecodeRequest(path)));
|
||||
// A provider that produces pixels wins over one that could not read the file.
|
||||
var recovered = new ImageDecoder([new ScriptedProvider("a", _ => throw new IOException("busy")), new ManagedDecoderProvider()]);
|
||||
using (var image = recovered.Decode(new DecodeRequest(path)))
|
||||
Assert.Equal("managed-jpeg", image!.Decoder);
|
||||
// Providers that read the file and found it malformed prove it undecodable.
|
||||
var damaged = new ImageDecoder([new ScriptedProvider("a", _ => throw new InvalidDataException("bad marker"))]);
|
||||
Assert.Null(damaged.Decode(new DecodeRequest(path)));
|
||||
Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(Write("garbage.jpg", new byte[3000]))));
|
||||
Assert.Throws<FileNotFoundException>(() => DecoderFactory.CreateServer().Decode(new DecodeRequest(Path.Combine(_dir, "vanished.jpg"))));
|
||||
}
|
||||
|
||||
/// <summary>A GoPro GPR as far as Titano reads it: a DNG made by "GoPro" whose only decodable image is a YCbCr JPEG preview.</summary>
|
||||
private static byte[] Gpr(int previewWidth, int previewHeight)
|
||||
{
|
||||
@@ -286,4 +332,12 @@ public sealed class ManagedDecoderProviderTests(TestContext context)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A JPEG provider whose decode does what the test says (return nothing, or throw).</summary>
|
||||
private sealed class ScriptedProvider(string name, Func<DecodeRequest, DecodedImage?> decode) : IImageDecoderProvider
|
||||
{
|
||||
public string Name => name;
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Jpeg ? DecodeTier.Native : null;
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => decode(request);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,16 @@ using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Dng;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Import;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Data.Processing.Jobs;
|
||||
using Titano.Data.Repositories;
|
||||
@@ -134,6 +139,138 @@ public sealed class AnalysisJobTests(TestContext context)
|
||||
Assert.Equal(JobState.Done, done.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImportedGoProRawDecodesThroughTheJpegItsImportKeptInAnotherSequence()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
// A GoPro card: each GPR (VC-5, without a usable embedded image here) has the camera's full-size JPEG beside it.
|
||||
// An upload may send the GPRs first: they arrive as two cards here.
|
||||
var raws = Path.Combine(context.CreateTempDirectory("card"), "DCIM", "100GOPRO");
|
||||
var jpegs = Path.Combine(context.CreateTempDirectory("card"), "DCIM", "100GOPRO");
|
||||
Directory.CreateDirectory(raws);
|
||||
Directory.CreateDirectory(jpegs);
|
||||
var start = new DateTime(2026, 9, 28, 18, 0, 0);
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var metadata = new FrameMetadata { Make = "GoPro", Model = "HERO12 Black", BodySerial = "C3501", CapturedAt = start.AddSeconds(5 * i) };
|
||||
using var sensor = new ImageBuffer(64, 48);
|
||||
File.WriteAllBytes(Path.Combine(raws, $"GOPR{i + 1:0000}.GPR"),
|
||||
LinearDngWriter.Write(sensor, new LinearDngOptions { Exif = ExifWriter.BuildTiff(metadata), TileSize = 64 }));
|
||||
using var picture = new ImageBuffer(160, 120);
|
||||
picture.Plane(1).Fill(0.25f * (i + 1));
|
||||
File.WriteAllBytes(Path.Combine(jpegs, $"GOPR{i + 1:0000}.JPG"),
|
||||
JpegEncoder.Encode(picture, new JpegEncodeOptions { App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]] }));
|
||||
}
|
||||
var service = fx.Archive.Service;
|
||||
async Task<ImportPlan> ImportAsync(string card)
|
||||
{
|
||||
var plan = await service.PlanImportAsync(fx.Archive.Archive.Id, Path.GetDirectoryName(Path.GetDirectoryName(card))!, new ImportOptions(),
|
||||
cancellationToken: fx.Ct);
|
||||
await service.Imports.ExecuteAsync(new ImportJobParameters(fx.Archive.Archive.Id, plan, null, true, null), Guid.NewGuid(), 0,
|
||||
_ => ValueTask.CompletedTask, null, fx.Ct);
|
||||
return plan;
|
||||
}
|
||||
var gprSession = (await ImportAsync(raws)).Sessions.Single();
|
||||
Assert.Equal(ImageFileFormat.Gpr, gprSession.Format);
|
||||
var id = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Archive.Id, gprSession.SessionKey, fx.Ct);
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id!.Value, fx.Ct))!;
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// Alone, a GPR without an embedded preview gives no pixels here, which proves nothing about the file.
|
||||
var first = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(first.Id, JobState.Done);
|
||||
var alone = ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames;
|
||||
Assert.True(alone.All(f => f is { Tier: DecodeTier.Unavailable, Flags: FrameFlags.None, PreviewW: null }), "unavailable, not flagged");
|
||||
|
||||
// The JPEGs arrive as a sequence of their own (the import splits per file format, DECISIONS 2026-10-02); the next
|
||||
// probe finds each GPR's JPEG there, so the output cap is the JPEG's size.
|
||||
Assert.Equal(ImageFileFormat.Jpeg, (await ImportAsync(jpegs)).Sessions.Single().Format);
|
||||
var jpegFrame = (await fx.Db.Frames.ListByCaptureRangeAsync(fx.Archive.Archive.Id, ImageFileFormat.Jpeg, start, start.AddMinutes(1), fx.Ct))[0];
|
||||
Assert.NotEqual(Path.GetDirectoryName(fx.Folder(sequence).File(alone[0].File)), Path.GetDirectoryName(fx.Archive.Paths.FromRelative(jpegFrame.RelativePath)),
|
||||
"not beside the GPR");
|
||||
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(light.Id, JobState.Done);
|
||||
var sidecar = ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames;
|
||||
Assert.True(sidecar.All(f => f is { Tier: DecodeTier.EmbeddedPreview, Flags: FrameFlags.PreviewOnly, PreviewW: 160, PreviewH: 120 }),
|
||||
"preview-only at the JPEG's size");
|
||||
|
||||
// The deep pass decodes the GPRs through those JPEGs (decoder "managed-sidecar"), never failing a frame.
|
||||
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(deep.Id, JobState.Done);
|
||||
var gprs = fx.Decoder.Decoded.Where(d => d.File.EndsWith(".GPR", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
Assert.NotEmpty(gprs);
|
||||
Assert.True(gprs.All(d => d.Decoder == "managed-sidecar"), string.Join(", ", gprs.Select(d => d.Decoder).Distinct()));
|
||||
Assert.Empty(SequenceAnalyser.ReadReport(fx.Folder(sequence), sequence.FrameCount)!.Issues.Undecodable);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeepAnalysisNeverFlagsFramesThatVanishedOrCouldNotBeRead()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Flickering(12));
|
||||
// Deleted after indexing (a verify flags it missing), and held by another program during the pass.
|
||||
File.Delete(Path.Combine(fx.Folder(sequence).Folder, ProcessingFixture.FileName(3)));
|
||||
fx.Decoder.Unreadable[ProcessingFixture.FileName(6)] = 0;
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// The pass could not read them, so it lists them as unreadable, but nothing proves the files undecodable.
|
||||
var report = SequenceAnalyser.ReadReport(fx.Folder(sequence), sequence.FrameCount)!;
|
||||
Assert.SequenceEqual([3, 6], report.Issues.Undecodable);
|
||||
var sidecar = ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames;
|
||||
foreach (var index in new[] { 3, 6 })
|
||||
{
|
||||
Assert.Equal(FrameFlags.None, sidecar[index].Flags & FrameFlags.Undecodable);
|
||||
Assert.NotEqual(DecodeTier.Unavailable, sidecar[index].Tier);
|
||||
}
|
||||
var rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
|
||||
Assert.True(rows.All(f => (f.Flags & FrameFlags.Undecodable) == 0), "no frame flagged in the index");
|
||||
var unreadable = Advisor.Recommend(LightAnalyzer.Analyze(rows), report, SequenceContext.FromFrames(rows)).Findings
|
||||
.Single(f => f.Key == DeepFindingKeys.UnreadableFrames);
|
||||
Assert.SequenceEqual([3, 6], unreadable.Frames);
|
||||
|
||||
// Back in place and readable, the next pass reads both frames.
|
||||
fx.Decoder.Unreadable.Clear();
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(sequence).Folder, ProcessingFixture.FileName(3)),
|
||||
await File.ReadAllBytesAsync(Path.Combine(fx.Folder(sequence).Folder, ProcessingFixture.FileName(2)), fx.Ct), fx.Ct);
|
||||
var again = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(again.Id, JobState.Done);
|
||||
Assert.Empty(SequenceAnalyser.ReadReport(fx.Folder(sequence), sequence.FrameCount)!.Issues.Undecodable);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AResumedDeepAnalysisDecodesAgainWhatTheEarlierRunCouldNotRead()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Flickering());
|
||||
// The first run cannot read frame 12 (held by another program) and is cancelled later, at frame 26.
|
||||
fx.Decoder.Unreadable[ProcessingFixture.FileName(11)] = 0;
|
||||
fx.Decoder.HoldFrame(25);
|
||||
await fx.StartEngineAsync();
|
||||
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);
|
||||
|
||||
// Readable again; the resumed run takes frame 12 from its checkpoint (it is not in the region sample).
|
||||
fx.Decoder.Unreadable.Clear();
|
||||
fx.Decoder.Hold = null;
|
||||
while (fx.Decoder.Requests.TryDequeue(out _))
|
||||
{
|
||||
}
|
||||
await fx.Engine.ResumeAsync(job.Id, fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Contains(11, SequenceAnalyser.ReadReport(fx.Folder(sequence), sequence.FrameCount)!.Issues.Undecodable);
|
||||
// That verdict was a read error: decoding the frame again shows it is fine, so nothing flags it.
|
||||
Assert.Count(1, fx.Decoder.Requests.Where(r => Path.GetFileName(r.Path) == ProcessingFixture.FileName(11)));
|
||||
var frame = ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames[11];
|
||||
Assert.Equal((DecodeTier.Native, FrameFlags.None), (frame.Tier, frame.Flags & FrameFlags.Undecodable));
|
||||
Assert.Equal(FrameFlags.None, (await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))[11].Flags);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeepAnalysisResumesAfterCancellationWithTheSameReport()
|
||||
{
|
||||
|
||||
@@ -123,25 +123,43 @@ internal sealed class GateDecoder : IImageDecoderProvider
|
||||
Hold = ProcessingFixture.FileName(index);
|
||||
}
|
||||
|
||||
/// <summary>Tiers <see cref="Probe"/> reports per file name instead of the managed provider's (a host that reads them
|
||||
/// only as previews, or not at all).</summary>
|
||||
/// <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();
|
||||
|
||||
/// <summary>Files (by name) whose decodes report the embedded-preview tier from a preview of this oriented size, as
|
||||
/// a size-limited decode that picked a smaller preview would.</summary>
|
||||
public ConcurrentDictionary<string, (int Width, int Height)> PreviewDecodes { get; } = new();
|
||||
|
||||
/// <summary>Files (by name) that cannot be read: their decodes throw <see cref="IOException"/> (a sharing violation).</summary>
|
||||
public ConcurrentDictionary<string, byte> Unreadable { get; } = new();
|
||||
|
||||
/// <summary>File name and decoder of every decode that produced pixels.</summary>
|
||||
public ConcurrentQueue<(string File, string Decoder)> Decoded { get; } = new();
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => _managed.TierFor(format);
|
||||
|
||||
public FileTier Probe(string path, ImageFileFormat format) =>
|
||||
Tiers.TryGetValue(Path.GetFileName(path), out var tier) ? tier : _managed.Probe(path, format);
|
||||
public FileTier Probe(string path, ImageFileFormat format) => Probe(path, format, null);
|
||||
|
||||
public FileTier Probe(string path, ImageFileFormat format, string? companion) =>
|
||||
Tiers.TryGetValue(Path.GetFileName(path), out var tier) ? tier : _managed.Probe(path, format, companion);
|
||||
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Requests.Enqueue(request);
|
||||
if (Hold is { } hold && Path.GetFileName(request.Path) == hold && (HoldPurpose ?? request.Purpose) == request.Purpose
|
||||
var name = Path.GetFileName(request.Path);
|
||||
if (Hold is { } hold && name == hold && (HoldPurpose ?? request.Purpose) == request.Purpose
|
||||
&& (HoldEdge ?? request.MaxLongEdge) == request.MaxLongEdge)
|
||||
{
|
||||
Holding.TrySetResult();
|
||||
cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(30));
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
}
|
||||
return _managed.Decode(request, cancellationToken);
|
||||
if (Unreadable.ContainsKey(name)) throw new IOException($"The process cannot access the file '{request.Path}' because it is being used by another process.");
|
||||
var decoded = _managed.Decode(request, cancellationToken);
|
||||
if (decoded is null) return null;
|
||||
Decoded.Enqueue((name, decoded.Decoder));
|
||||
if (!PreviewDecodes.TryGetValue(name, out var preview)) return decoded;
|
||||
return new DecodedImage(decoded.Pixels, DecodeTier.EmbeddedPreview, "test-preview", preview.Width, preview.Height);
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,105 @@ public sealed class RenderJobTests(TestContext context)
|
||||
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFrameThatCannotBeReadIsShownAsItsNeighbourButNeverFlagged()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
// Another program holds the file during the render (antivirus, backup): a read error says nothing about the file.
|
||||
fx.Decoder.Unreadable[ProcessingFixture.FileName(10)] = 0;
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
var done = await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Contains(Loc.L("Export.Log.StandIns", "11"), done.LogTail);
|
||||
var sidecar = Titano.Core.Archiving.ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath);
|
||||
Assert.Equal(FrameFlags.None, sidecar.Frames[10].Flags & FrameFlags.Undecodable);
|
||||
Assert.NotEqual(DecodeTier.Unavailable, sidecar.Frames[10].Tier);
|
||||
Assert.False(sidecar.Status.HasFlag(SequenceStatus.HasWarnings), "no warning");
|
||||
Assert.Equal(FrameFlags.None, (await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))[10].Flags);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASmallRenderKeepsTheStoredSizeOfTheLargestPreview()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
// A CR3 on the server: the probe finds its full-size 6000×4000 preview, which caps the output.
|
||||
for (var i = 0; i < Frames; i++)
|
||||
fx.Decoder.Tiers[ProcessingFixture.FileName(i)] = new FileTier(ImageFileFormat.Jpeg, DecodeTier.EmbeddedPreview, "test-preview", "test", 6000, 4000);
|
||||
await fx.StartEngineAsync();
|
||||
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
|
||||
await fx.WaitForAsync(light.Id, JobState.Done);
|
||||
var probed = Titano.Core.Archiving.ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames[3];
|
||||
Assert.Equal((FrameFlags.PreviewOnly, (int?)6000, (int?)4000), (probed.Flags, probed.PreviewW, probed.PreviewH));
|
||||
|
||||
// A small render decodes the smallest preview that reaches its size (1620×1080): that is not the largest.
|
||||
for (var i = 0; i < Frames; i++) fx.Decoder.PreviewDecodes[ProcessingFixture.FileName(i)] = (1620, 1080);
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var frames = Titano.Core.Archiving.ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames;
|
||||
Assert.True(frames.All(f => f is { Tier: DecodeTier.EmbeddedPreview, PreviewW: 6000, PreviewH: 4000 }), "sidecar preview sizes kept");
|
||||
var rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
|
||||
Assert.True(rows.All(f => (f.PreviewWidth, f.PreviewHeight) == (6000, 4000)), "index preview sizes kept");
|
||||
Assert.Equal((6000, 4000), (Titano.Core.Advice.SequenceContext.FromFrames(rows).PreviewWidth, Titano.Core.Advice.SequenceContext.FromFrames(rows).PreviewHeight));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FramesARenderNodeReceivesKeepTheirTierFields()
|
||||
{
|
||||
var dto = new Titano.Protocol.FrameDto(Guid.CreateVersion7(), Guid.CreateVersion7(), 3, "IMG_0004.CR3", 25_000_000, new string('a', 64),
|
||||
new DateTime(2026, 9, 28, 18, 0, 20), 120, 1.0 / 250, 8, 100, 24, 6, 6000, 4000, "cr3",
|
||||
(long)(FrameFlags.PreviewOnly | FrameFlags.Intervalometer), 1620, 1080);
|
||||
|
||||
var frame = RenderNodeClient.ToFrame(dto);
|
||||
Assert.Equal((ImageFileFormat.Cr3, FrameFlags.PreviewOnly | FrameFlags.Intervalometer, 1620, 1080),
|
||||
(frame.Format, frame.Flags, frame.PreviewWidth, frame.PreviewHeight));
|
||||
// The node's advisor caps a portrait sequence at its previews, oriented like the main image.
|
||||
var tiers = Titano.Core.Advice.SequenceContext.FromFrames([frame]);
|
||||
Assert.Equal((1, 1080, 1620), (tiers.PreviewOnlyCount, tiers.PreviewWidth, tiers.PreviewHeight));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnlyFramesTheRenderShowsGetAStandIn()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
foreach (var i in new[] { 1, 3 })
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(i)), new byte[5000], fx.Ct);
|
||||
var frames = await SequenceFrames.LoadAsync(fx.Db, fx.Archive.Archive, sequence, useProxies: false, fx.Ct);
|
||||
|
||||
// A plan that skips the odd frames (a speed-up): the read-ahead meets frames 1 and 3, the pipeline never asks.
|
||||
var source = new SequenceFrameSource(frames, frames.LightFrames(), new ImageDecoder([fx.Decoder]), new FrameWindowOptions { Ahead = 4 })
|
||||
{
|
||||
Originals = true,
|
||||
RenderExcluded = new HashSet<int>(),
|
||||
};
|
||||
await using (source)
|
||||
{
|
||||
foreach (var index in new[] { 0, 2, 4, 6 })
|
||||
{
|
||||
using var frame = await source.GetFrameAsync(index, 64, DecodePurpose.Render, fx.Ct);
|
||||
Assert.Equal(64, frame.Width);
|
||||
}
|
||||
// The read-ahead decodes in the background: wait until it has met frame 4 (index 3).
|
||||
for (var waited = 0; !source.Observed.ContainsKey(3) && waited < 200; waited++) await Task.Delay(50, fx.Ct);
|
||||
}
|
||||
Assert.Equal(DecodeTier.Unavailable, source.Observed[3].Tier);
|
||||
Assert.Empty(source.StandIns);
|
||||
|
||||
// Asked for, a damaged frame shows its neighbour and is listed.
|
||||
await using var asked = new SequenceFrameSource(frames, frames.LightFrames(), new ImageDecoder([fx.Decoder]))
|
||||
{
|
||||
RenderExcluded = new HashSet<int>(),
|
||||
};
|
||||
using (var standIn = await asked.GetFrameAsync(3, 64, DecodePurpose.Render, fx.Ct))
|
||||
Assert.Equal(64, standIn.Width);
|
||||
Assert.SequenceEqual([3], asked.StandIns);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderInterruptedByACrashStartsItsOutputAgainCleanly()
|
||||
{
|
||||
|
||||
@@ -318,17 +318,19 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var frames = Enumerable.Range(0, 40).Select(i => TestData.Frame(sequence.Id, i) with { Flags = FrameFlags.Duplicate }).ToList();
|
||||
// More frames than one batched PostgreSQL statement holds.
|
||||
const int count = 1205;
|
||||
var frames = Enumerable.Range(0, count).Select(i => TestData.Frame(sequence.Id, i) with { Flags = FrameFlags.Duplicate }).ToList();
|
||||
await db.Frames.BulkInsertAsync(frames, Ct);
|
||||
|
||||
var tiers = frames.Select(f => new FrameTierFields(f.Id, f.Index % 2 == 0 ? FrameFlags.PreviewOnly : FrameFlags.Undecodable, 1620 + f.Index, 1080)).ToList();
|
||||
Assert.Equal(40, await db.Frames.UpdateTiersAsync(tiers, Ct));
|
||||
var read = await db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: Ct);
|
||||
Assert.Equal(count, await db.Frames.UpdateTiersAsync(tiers, Ct));
|
||||
var read = await Titano.Data.Processing.SequenceFrames.ListAsync(db, sequence.Id, Ct);
|
||||
Assert.SequenceEqual(tiers.Select(t => (t.Flags, t.PreviewWidth, t.PreviewHeight)), read.Select(f => (f.Flags, f.PreviewWidth, f.PreviewHeight)));
|
||||
|
||||
// A sync from the sidecar writes the tier fields like every other one.
|
||||
await db.Frames.SyncSequenceAsync(sequence.Id, [.. read.Select(f => f with { PreviewWidth = 4, PreviewHeight = 3, Flags = FrameFlags.None })], Ct);
|
||||
Assert.True((await db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: Ct)).All(f => (f.Flags, f.PreviewWidth, f.PreviewHeight) == (FrameFlags.None, 4, 3)));
|
||||
Assert.True((await Titano.Data.Processing.SequenceFrames.ListAsync(db, sequence.Id, Ct)).All(f => (f.Flags, f.PreviewWidth, f.PreviewHeight) == (FrameFlags.None, 4, 3)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
Reference in new issue
Block a user