refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,222 @@
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Import;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>New sequences get their light analysis (and so their Auto values) without any user action (BRIEF §1.1).</summary>
[Category("processing")]
public sealed class AnalysisFollowUpTests(TestContext context)
{
[Test]
public async Task AnAdoptingScanQueuesLightAnalysisOfTheNewSequencesOnly()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
await fx.StartEngineAsync(withArchive: true);
var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true));
await fx.WaitForAsync(scan.Id, JobState.Done);
var light = Assert.NotNull(await SingleLightJobAsync(fx));
await fx.WaitForAsync(light.Id, JobState.Done);
var sequence = (await fx.Db.Sequences.GetAsync(light.TargetIds.Single(), fx.Ct))!;
Assert.Equal("Roof", sequence.Folder);
Assert.True(sequence.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed");
Assert.True(ProjectSettings.FromJson(await File.ReadAllTextAsync(fx.Folder(sequence).ProjectPath, fx.Ct)).Timing.Mode.HasAdvice, "advised");
// Scans that find nothing new queue nothing more.
foreach (var full in new[] { false, true })
{
var again = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full));
await fx.WaitForAsync(again.Id, JobState.Done);
}
Assert.Equal(light.Id, (await SingleLightJobAsync(fx))?.Id);
}
[Test]
public async Task AnImportQueuesLightAnalysisOfTheSequencesItFilled()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var card = context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), ArchiveFixture.Start, 10);
var plan = await fx.Archive.Service.PlanImportAsync(fx.Archive.Archive.Id, card, new ImportOptions(), null, null, fx.Ct);
await fx.StartEngineAsync(withArchive: true);
var import = await fx.Engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive.Archive, plan, null), createdBy: Guid.CreateVersion7(), cancellationToken: fx.Ct);
await fx.WaitForAsync(import.Id, JobState.Done);
var light = Assert.NotNull(await SingleLightJobAsync(fx));
await fx.WaitForAsync(light.Id, JobState.Done);
var sequenceId = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Archive.Id, plan.Sessions.Single().SessionKey, fx.Ct);
Assert.SequenceEqual([Assert.NotNull(sequenceId)], light.TargetIds);
Assert.Equal(import.CreatedBy, light.CreatedBy);
Assert.Equal(JobPriority.Background, light.Priority);
Assert.True((await fx.Db.Sequences.GetAsync(sequenceId.Value, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed");
}
[Test]
public async Task PhotosAddedToAnAnalysedFolderAreAnalysedAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
await fx.StartEngineAsync(withArchive: true);
var first = await fx.EnqueueAsync(Chronos.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(first.Id, JobState.Done);
// The camera kept shooting into the folder: the next scan indexes the new photos and analyses the sequence again.
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 18 }), "Roof", first: 12);
var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive));
await fx.WaitForAsync(scan.Id, JobState.Done);
var again = (await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.Single(j => j.Id != first.Id);
await fx.WaitForAsync(again.Id, JobState.Done);
var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(18, analysed.FrameCount);
Assert.True(analysed.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed again");
Assert.True(ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
}
[Test]
public async Task PhotosTheOrphansFixIndexesAreAnalysedAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
var folder = fx.Folder(sequence);
await fx.StartEngineAsync(withArchive: true);
var first = await fx.EnqueueAsync(Chronos.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(first.Id, JobState.Done);
// A server sharing the archive drew the twelve frames and made their proxies.
const SequenceStatus images = SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt;
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
ManifestStore.WriteSequence(folder.ManifestPath, manifest with { Status = manifest.Status | images });
await fx.Db.Sequences.UpdateStatusAsync(sequence.Id, images, SequenceStatus.None, fx.Ct);
// Photos copied into the folder by hand: the Archive screen's orphans check lists them, and its fix indexes them. The
// light analysis it queues waits on the first new photo's probe, so what the fix left can be seen.
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 18 }), "Roof", first: 12);
fx.Decoder.HoldProbeOf(12);
await fx.Archive.Service.ReconcileAsync(sequence.Id, fx.Engine, deepAnalysis: false, fx.Ct);
const SequenceStatus covering = SequenceStatus.AnalyzedLight | images;
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal((18, SequenceStatus.None), (row.FrameCount, row.Status & covering));
Assert.Equal(SequenceStatus.None, ManifestStore.ReadSequence(folder.ManifestPath).Status & covering);
var again = (await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.Single(j => j.Id != first.Id);
Assert.SequenceEqual([sequence.Id], again.TargetIds);
Assert.Empty((await fx.Db.Jobs.ListAsync(null, JobKind.DeepAnalyse, cancellationToken: fx.Ct)).Items);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Release();
await fx.WaitForAsync(again.Id, JobState.Done);
row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed again");
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.Contains("18", ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct)).Timing.FrameRate.ReasonArgs!);
}
[Test]
public async Task PhotosTheOrphansFixIndexesGetTheDeepAnalysisAScanWouldQueue()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
var lake = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Lake");
var folder = fx.Folder(sequence);
await fx.StartEngineAsync(withArchive: true);
Task<IReadOnlyList<Job>> QueuedDeepAsync() => fx.Db.Jobs.ListQueuedAsync(JobKind.DeepAnalyse, 50, fx.Ct);
// The host asks for a deep analysis after scans: the orphans fix queues one in the background too, behind the light
// analysis, which waits on the first new photo's probe so the queue can be seen.
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 18 }), "Roof", first: 12);
fx.Decoder.HoldProbeOf(12);
await fx.Archive.Service.ReconcileAsync(sequence.Id, fx.Engine, deepAnalysis: true, fx.Ct);
var light = (await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.Single();
var deep = (await QueuedDeepAsync()).Single();
Assert.SequenceEqual([sequence.Id], deep.TargetIds);
Assert.Equal(JobPriority.Background, deep.Priority);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
// The user cancels it, and asks for a deep analysis of both sequences instead. More photos and the fix again: the
// one waiting covers them, so no other is queued.
await fx.Engine.CancelAsync(deep.Id, fx.Ct);
var both = await fx.EnqueueAsync(Chronos.Data.Processing.ProcessingJobs.DeepAnalysis([lake.Id, sequence.Id]));
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 20 }), "Roof", first: 18);
await fx.Archive.Service.ReconcileAsync(sequence.Id, fx.Engine, deepAnalysis: true, fx.Ct);
Assert.SequenceEqual([both.Id], (await QueuedDeepAsync()).Select(j => j.Id));
fx.Decoder.Release();
await fx.WaitForAsync(light.Id, JobState.Done);
await fx.WaitForAsync(both.Id, JobState.Done);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(20, row.FrameCount);
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), row.Status.ToString());
Assert.Equal(20, Chronos.Data.Processing.SequenceAnalyser.ReadReport(folder, 20)?.FrameCount);
}
[Test]
public async Task AScanAskedForDeepAnalysisQueuesItInTheBackgroundForNewSequencesOnly()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
await fx.StartEngineAsync(withArchive: true);
var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true, deepAnalysis: true));
await fx.WaitForAsync(scan.Id, JobState.Done);
var deep = (await fx.Db.Jobs.ListAsync(null, JobKind.DeepAnalyse, cancellationToken: fx.Ct)).Items.Single();
Assert.Equal(JobPriority.Background, deep.Priority);
Assert.NotNull(await SingleLightJobAsync(fx));
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
var sequence = (await fx.Db.Sequences.GetAsync(done.TargetIds.Single(), fx.Ct))!;
Assert.Equal("Roof", sequence.Folder);
Assert.True(sequence.Status.HasFlag(SequenceStatus.AnalyzedDeep), "analysed in depth");
// A scan that indexes nothing new asks for nothing; a scan without the option never does.
var again = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true, deepAnalysis: true));
await fx.WaitForAsync(again.Id, JobState.Done);
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Lake");
var plain = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive));
await fx.WaitForAsync(plain.Id, JobState.Done);
Assert.Count(1, (await fx.Db.Jobs.ListAsync(null, JobKind.DeepAnalyse, cancellationToken: fx.Ct)).Items);
}
[Test]
public async Task ASequenceWaitingForLightAnalysisIsNotQueuedAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
// Queued before the scan, which runs first (user priority) and finds the sequence not analysed yet.
var waiting = await QueueAsync(fx, Chronos.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
var scan = await QueueAsync(fx, ArchiveJobs.Scan(fx.Archive.Archive, full: true));
await fx.StartEngineAsync(withArchive: true);
await fx.WaitForAsync(scan.Id, JobState.Done);
await fx.WaitForAsync(waiting.Id, JobState.Done);
Assert.Equal(waiting.Id, (await SingleLightJobAsync(fx))?.Id);
}
/// <summary>Queues a job before the engine starts.</summary>
private static async Task<Job> QueueAsync(ProcessingFixture fx, Chronos.Data.Archiving.Jobs.ArchiveJobRequest request)
{
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
TargetLabel = request.Label,
ParametersJson = request.ParametersJson,
Priority = request.Priority,
State = JobState.Queued,
Created = DateTimeOffset.UtcNow,
};
await fx.Db.Jobs.EnqueueAsync(job, fx.Ct);
return job;
}
private static async Task<Job?> SingleLightJobAsync(ProcessingFixture fx) =>
(await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.SingleOrDefault();
}
@@ -0,0 +1,995 @@
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Dng;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Import;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
[Category("processing")]
public sealed class AnalysisJobTests(TestContext context)
{
private static SyntheticSequence Flickering(int frames = 40) => SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = frames,
FlickerEv = 0.1,
StartEv = 0.5,
EndEv = -1.5,
Latitude = 45.4,
Longitude = 12.3,
});
[Test]
public async Task LightAnalysisFillsAutoValuesAndKeepsManualOnes()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering());
var manual = new ProjectSettings();
// The user's frame rate, and the highlight knee turned off (hard clip).
manual = manual with
{
Timing = manual.Timing with { FrameRate = manual.Timing.FrameRate.WithManual("25") },
Exposure = manual.Exposure with { HighlightKnee = null },
};
await fx.Db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = manual.ToJson() }, null, fx.Ct);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id], sequence.DisplayTitle));
var done = await fx.WaitForAsync(job.Id, JobState.Done);
var folder = fx.Folder(sequence);
var project = ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct));
Assert.Equal((false, "25"), (project.Timing.FrameRate.IsAuto, project.Timing.FrameRate.Resolve("30")));
Assert.Null(project.Exposure.HighlightKnee);
Assert.True(project.Timing.Mode.HasAdvice, "timing mode advised");
Assert.True(project.Timing.FrameRate.HasAdvice, "the advice is kept next to the manual frame rate");
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(project.ToJson(), ProjectSettings.FromJson(row.SettingsJson!).ToJson());
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), "no deep status without a report");
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.Contains(Loc.L("Advisor.Log.AutoUpdated", sequence.DisplayTitle), done.LogTail);
// Idempotent: a second pass changes nothing.
var version = row.SettingsVersion;
var again = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(again.Id, JobState.Done);
Assert.Equal(version, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.SettingsVersion);
}
[Test]
public async Task LightAnalysisRecordsFormatTiersAndTheAdvisorCapsTheOutputAtThePreviews()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
// This host reads the first ten files only through 48×32 embedded previews and cannot decode the last one.
for (var i = 0; i < 10; i++)
fx.Decoder.Tiers[ProcessingFixture.FileName(i)] = new FileTier(ImageFileFormat.Jpeg, DecodeTier.EmbeddedPreview, "test-preview", "test", 48, 32);
fx.Decoder.Tiers[ProcessingFixture.FileName(11)] = new FileTier(ImageFileFormat.Jpeg, DecodeTier.Unavailable, null, "test", 0, 0);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(job.Id, JobState.Done);
var folder = fx.Folder(sequence);
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath).Frames;
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.PreviewOnly, (int?)48, (int?)32), (sidecar[0].Tier, sidecar[0].Flags, sidecar[0].PreviewW, sidecar[0].PreviewH));
Assert.Equal((DecodeTier.Native, FrameFlags.None), (sidecar[10].Tier, sidecar[10].Flags));
Assert.Equal((DecodeTier.Unavailable, FrameFlags.Undecodable), (sidecar[11].Tier, sidecar[11].Flags));
var rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
Assert.Equal((FrameFlags.PreviewOnly, 48, 32), (rows[3].Flags, rows[3].PreviewWidth, rows[3].PreviewHeight));
Assert.Equal(FrameFlags.Undecodable, rows[11].Flags);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(10, row.PreviewOnlyCount);
Assert.GreaterOrEqual(row.WarningCount, 1);
Assert.True(row.Status.HasFlag(SequenceStatus.HasWarnings), "the undecodable frame is a sequence warning");
// The advisor reads the preview size from the index and caps the output there (BRIEF §8.2 tier 2).
var tiers = SequenceContext.FromFrames(rows);
Assert.Equal((10, 48, 32), (tiers.PreviewOnlyCount, tiers.PreviewWidth, tiers.PreviewHeight));
var light = LightAnalyzer.Analyze(rows);
var advice = Advisor.Recommend(light, null, tiers);
Assert.Equal(AdvisorKeys.ResolutionPreview, advice.Find(AdvisorParameters.Resolution)!.ReasonKey);
Assert.Contains(advice.Findings, f => f.Key == FindingKeys.PreviewOnly && Equals(f.Arguments[0], 10));
Assert.Contains(advice.Findings, f => f.Key == DeepFindingKeys.UnreadableFrames && f.Frames.SequenceEqual([11]));
// Probed once: a second pass opens no file for its tier and leaves the sidecar alone.
fx.Decoder.Tiers.Clear();
var written = File.GetLastWriteTimeUtc(folder.ManifestPath);
var again = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(again.Id, JobState.Done);
Assert.Equal(FrameFlags.PreviewOnly, ManifestStore.ReadSequence(folder.ManifestPath).Frames[0].Flags);
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 ProxiesThatArriveDuringADeepAnalysisOfHeifsWithoutThumbnailsMakeItsUnreadableVerdictStale()
{
// A server, which finds no pixels at all in these HEIF files (they carry no Exif thumbnail) 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, thumbnailWidth: 0),
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> AutoValuesAsync() =>
File.Exists(folder.ProjectPath) ? ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct)).ToJson() : string.Empty;
// A deep analysis starts on the originals; while it runs, the proxies arrive and a light analysis on the other
// worker reads the frames from 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);
var light = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
var advice = await AutoValuesAsync();
fx.Decoder.Release();
await fx.WaitForAsync(deep.Id, JobState.Done);
// The deep pass found no pixels in any original, a verdict the proxies made stale before it ended, as every reader
// of its report finds: it records no deep status, and neither warnings nor advice of its own.
Assert.Count(4, SequenceAnalyser.ReadReport(folder, sequence.FrameCount)!.Issues.Undecodable);
var now = await Chronos.Data.Processing.SequenceFrames.LoadAsync(fx.Db, fx.Archive.Archive, sequence, useProxies: false,
new ImageDecoder([fx.Decoder]), fx.Ct);
Assert.Null(SequenceAnalyser.ReadReport(folder, now));
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), row.Status.ToString());
Assert.False(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedDeep), "sidecar status");
Assert.Equal((light.WarningCount, light.Status.HasFlag(SequenceStatus.HasWarnings)), (row.WarningCount, row.Status.HasFlag(SequenceStatus.HasWarnings)));
Assert.Equal(advice, await AutoValuesAsync());
}
[Test]
public async Task ADeepAnalysisMadeStaleByProxiesLeavesTheReportALaterPassMadeFromThem()
{
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, thumbnailWidth: 0),
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);
// A deep analysis starts on the originals, in which the server finds no pixels; while it runs, the proxies arrive
// and a second deep analysis, on the other worker, measures every frame from them and records its report.
fx.Decoder.Hold = "IMG_0001.HEIC";
var stale = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Hold = null;
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);
var current = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.WaitForAsync(current.Id, JobState.Done);
var report = await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct);
var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(analysed.Status.HasFlag(SequenceStatus.AnalyzedDeep), analysed.Status.ToString());
fx.Decoder.Release();
await fx.WaitForAsync(stale.Id, JobState.Done);
// The first pass's verdict on the originals no longer describes the frames: it leaves the report made from the
// proxies, and with it the deep status, in place.
Assert.Equal(report, await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct));
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), row.Status.ToString());
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedDeep), "sidecar status");
Assert.Equal(analysed.AnalysisJson, row.AnalysisJson);
}
[Test]
public async Task FramesAddedDuringADeepAnalysisKeepTheLightAnalysisOfTheFramesAsTheyAre()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync(workers: 2);
// A deep analysis starts on twelve frames; while it runs, a thirteenth photo this host cannot decode is indexed,
// and a light analysis on the other worker analyses all thirteen.
fx.Decoder.HoldFrame(0);
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Tiers[ProcessingFixture.FileName(12)] = new FileTier(ImageFileFormat.Jpeg, DecodeTier.Unavailable, null, "test", 0, 0);
await fx.AddAsync(Flickering(13), first: 12);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(light.Id, JobState.Done);
var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
var advice = await ProjectJsonAsync(fx, folder);
Assert.Equal(13, analysed.FrameCount);
Assert.Contains("13", ProjectSettings.FromJson(advice).Timing.FrameRate.ReasonArgs!);
Assert.True(analysed.Status.HasFlag(SequenceStatus.HasWarnings), "the photo this host cannot decode is a warning");
fx.Decoder.Release();
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
// The deep pass measured twelve of them: it saved its report but applied none of it (neither the Auto values nor
// the status and warnings of twelve frames), and queued a light analysis of the frames as they are.
Assert.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), done.LogTail);
Assert.Equal(12, SequenceAnalyser.ReadReport(folder, 12)!.FrameCount);
var again = Assert.Contains(await LightJobsAsync(fx), j => j.Id != light.Id);
await fx.WaitForAsync(again.Id, JobState.Done);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal((analysed.WarningCount, analysed.Status), (row.WarningCount, row.Status));
Assert.Null(row.AnalysisJson);
Assert.Equal(advice, await ProjectJsonAsync(fx, folder));
}
[Test]
public async Task ADeepAnalysisOvertakenByOneOfTheFramesAsTheyAreLeavesThatOnesReport()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync(workers: 2);
// A deep analysis starts on twelve frames; while it runs, a thirteenth photo is indexed and a second deep analysis,
// on the other worker, analyses all thirteen and records its report.
fx.Decoder.HoldFrame(0);
var overtaken = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Hold = null;
await fx.AddAsync(Flickering(13), first: 12);
var current = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.WaitForAsync(current.Id, JobState.Done);
var report = await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct);
Assert.Equal(13, SequenceAnalyser.ReadReport(folder, 13)!.FrameCount);
var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(analysed.Status.HasFlag(SequenceStatus.AnalyzedDeep), analysed.Status.ToString());
fx.Decoder.Release();
var done = await fx.WaitForAsync(overtaken.Id, JobState.Done);
// The first pass measured twelve: it leaves the report of the thirteen in place, so the light analysis it queues
// keeps the deep status and its summary.
Assert.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), done.LogTail);
Assert.Equal(report, await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct));
Assert.FileMissing(Path.Combine(folder.MetaDirectory, DeepAnalysisCheckpointFile.FileName));
var light = Assert.Contains(await LightJobsAsync(fx), j => j.TargetIds.Contains(sequence.Id));
await fx.WaitForAsync(light.Id, JobState.Done);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), row.Status.ToString());
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedDeep), "sidecar status");
Assert.Equal(analysed.AnalysisJson, row.AnalysisJson);
}
[Test]
public async Task ADeepAnalysisThatLeavesTheReportInPlaceRecordsThatReport()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
var first = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.WaitForAsync(first.Id, JobState.Done);
var measured = SequenceAnalyser.ReadReport(folder, 12)!;
// A deep analysis starts on the twelve frames on the only worker. Meanwhile another Chronos sharing the archive files
// them again, at the next frames version, and saves its own analysis of them; this index's scan indexes them, and
// their light analysis waits in the queue.
fx.Decoder.HoldFrame(0);
var overtaken = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Hold = null;
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
ManifestStore.WriteSequence(folder.ManifestPath, manifest with
{
Versions = manifest.Versions with { Frames = manifest.Versions.Frames + 1 },
UpdatedAt = DateTimeOffset.UtcNow,
});
Assert.Contains(sequence.Id, (await fx.Archive.ScanAsync()).Sequences);
var theirs = measured with { HeroIndex = measured.HeroIndex == 5 ? 6 : 5 };
theirs.Save(folder.AnalysisPath);
var report = await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
fx.Decoder.Release();
await fx.WaitForAsync(overtaken.Id, JobState.Done);
// The pass leaves that report in place, and records it rather than its own: the summary in the index is the one of
// the file every reader opens, and the light analysis that follows keeps it.
Assert.Equal(report, await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct));
var summary = AnalysisSummary.From(theirs);
Assert.NotEqual(AnalysisSummary.From(measured), summary);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), row.Status.ToString());
Assert.Equal(summary, AnalysisSummary.FromJson(row.AnalysisJson!));
await fx.WaitForAsync(light.Id, JobState.Done);
row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedDeep), row.Status.ToString());
Assert.Equal(summary, AnalysisSummary.FromJson(row.AnalysisJson!));
}
[Test]
public async Task AnAnalysisOvertakenWhileALightAnalysisWaitsRecordsAndThatOneReplacesIt()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
// A deep analysis starts on twelve frames on the only worker; while it runs a thirteenth photo is indexed, and its
// light analysis waits in the queue, as during an upload burst.
fx.Decoder.HoldFrame(0);
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await fx.AddAsync(Flickering(13), first: 12);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
fx.Decoder.Hold = null;
fx.Decoder.Release();
// The light analysis waits on the new photo's probe, so what the deep pass left can be seen.
fx.Decoder.HoldProbeOf(12);
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
// The deep pass records the analysis of the frames it read meanwhile, and queues nothing more.
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Contains(Loc.L("Advisor.Log.DeepDone", sequence.DisplayTitle, 12, row.WarningCount), done.LogTail);
Assert.False(done.LogTail!.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), StringComparison.Ordinal), done.LogTail);
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.SequenceEqual([light.Id], (await LightJobsAsync(fx)).Select(j => j.Id));
// The light analysis that waited replaces it with the analysis of all thirteen.
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Release();
await fx.WaitForAsync(light.Id, JobState.Done);
Assert.Contains("13", ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.ReasonArgs!);
}
[Test]
public async Task ALightAnalysisOvertakenByAScanMarksNothingAnalysedAndRunsAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
// A light analysis reads twelve frames; before it records, a scan indexes a thirteenth photo copied into the folder.
fx.Decoder.HoldProbeOf(0);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await fx.AddAsync(Flickering(13), first: 12);
fx.Decoder.Release();
// The light analysis that follows waits on the new photo's probe, so what the first one left can be seen.
fx.Decoder.HoldProbeOf(12);
var done = await fx.WaitForAsync(light.Id, JobState.Done);
Assert.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), done.LogTail);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(13, row.FrameCount);
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.False(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.False(ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.HasAdvice, "no advice for twelve frames");
var again = Assert.Contains(await LightJobsAsync(fx), j => j.Id != light.Id);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Release();
await fx.WaitForAsync(again.Id, JobState.Done);
row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.Contains("13", ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.ReasonArgs!);
}
[Test]
public async Task AnAnalysisOfPhotosAnotherChronosChangedLeavesWhatThatChronosRecorded()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
// A server sharing this desktop's archive, with its own index and analysis.
await using var serverDb = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("server"), "chronos.db")), fx.Ct);
var serverOptions = fx.Processing.Options with
{
Archive = new ArchiveServiceOptions { Decoder = new ImageDecoder([new ManagedDecoderProvider()]), Owner = "server", LeaseWait = TimeSpan.FromSeconds(20) },
};
var server = new ArchiveService(serverDb, serverOptions.Archive);
var archive = await server.OpenAsync(fx.Archive.Archive.RootPath, fx.Ct);
await server.Indexer.ScanAsync(archive, ScanMode.Incremental, null, _ => ValueTask.CompletedTask, fx.Ct);
await using var serverEngine = new JobEngine(serverDb, new ProcessingService(serverDb, serverOptions).CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "server", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await serverEngine.StartAsync(fx.Ct);
// A light analysis here reads twelve frames; before it records, the server takes a thirteenth photo and analyses
// the sequence as it is now, in the shared sidecar and project.
fx.Decoder.HoldProbeOf(0);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
var staged = fx.Archive.Stage(new DateTime(2024, 6, 21, 19, 2, 0), seed: 90);
await server.Ingest.CommitAsync(new IngestRequest(archive.Id, sequence.Id, null, null, staged.Path, "IMG_0013.JPG", staged.Size, staged.Sha256, null, null),
fx.Ct);
var analysed = await serverEngine.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]), cancellationToken: fx.Ct);
for (var until = DateTime.UtcNow.AddSeconds(60); (await serverDb.Jobs.GetAsync(analysed.Id, fx.Ct))!.State != JobState.Done;)
{
Assert.True(DateTime.UtcNow < until, "the server's light analysis ends");
await Task.Delay(20, fx.Ct);
}
var advice = await ProjectJsonAsync(fx, folder);
Assert.Contains("13", ProjectSettings.FromJson(advice).Timing.FrameRate.ReasonArgs!);
var status = ManifestStore.ReadSequence(folder.ManifestPath).Status;
Assert.True(status.HasFlag(SequenceStatus.AnalyzedLight), "the server's status");
fx.Decoder.Release();
var done = await fx.WaitForAsync(light.Id, JobState.Done);
// This index still holds twelve frames: the analysis here records nothing over the server's, and queues nothing.
Assert.Contains(Loc.L("Advisor.Log.FramesChangedElsewhere", sequence.DisplayTitle), done.LogTail);
Assert.Equal(advice, await ProjectJsonAsync(fx, folder));
Assert.Equal(status, ManifestStore.ReadSequence(folder.ManifestPath).Status);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(12, row.FrameCount);
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.SequenceEqual([light.Id], (await LightJobsAsync(fx)).Select(j => j.Id));
// The next scan here indexes the photo with the server's analysis, which a desktop keeps.
Assert.Contains(sequence.Id, (await fx.Archive.ScanAsync()).Sequences);
row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(13, row.FrameCount);
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.Equal(advice, await ProjectJsonAsync(fx, folder));
}
[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 Chronos.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 & Chronos.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()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
// Damaged after indexing: the header probe still says JPEG, only decoding finds out.
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(sequence).Folder, ProcessingFixture.FileName(4)), new byte[3000], fx.Ct);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
var done = await fx.WaitForAsync(job.Id, JobState.Done);
var sidecar = ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Frames;
Assert.Equal((DecodeTier.Unavailable, FrameFlags.Undecodable), (sidecar[4].Tier, sidecar[4].Flags));
Assert.Equal(DecodeTier.Native, sidecar[5].Tier);
Assert.Equal(FrameFlags.Undecodable, (await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))[4].Flags);
var report = SequenceAnalyser.ReadReport(fx.Folder(sequence), sequence.FrameCount)!;
var rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
var findings = Advisor.Recommend(LightAnalyzer.Analyze(rows), report, SequenceContext.FromFrames(rows)).Findings;
Assert.Count(1, findings.Where(f => f.Key == DeepFindingKeys.UnreadableFrames));
Assert.True((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.WarningCount >= 1, "listed in the sequence warnings");
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);
}
/// <summary>
/// The owner's archive (R4, owner review 1): GoPro DNGs converted by Adobe software were indexed as GPR and recorded
/// preview-only. The scan follow-up lists their sequences again, and the light analysis probes them: they become
/// DNGs decoded natively, in the sidecar and the index.
/// </summary>
[Test]
public async Task GoProDngsIndexedAsGprAreProbedAgainAndBecomeNativeDngs()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var card = Path.Combine(context.CreateTempDirectory("card"), "DCIM", "100GOPRO");
Directory.CreateDirectory(card);
var start = new DateTime(2024, 10, 11, 18, 0, 0);
for (var i = 0; i < 3; i++)
{
var metadata = new FrameMetadata { Make = "GoPro", Model = "HERO8 Black", BodySerial = "C3441", CapturedAt = start.AddSeconds(5 * i) };
using var sensor = new ImageBuffer(64, 48);
sensor.Plane(1).Fill(0.2f + 0.1f * i);
File.WriteAllBytes(Path.Combine(card, $"GOPR{i + 1:0000}.dng"),
LinearDngWriter.Write(sensor, new LinearDngOptions { Exif = ExifWriter.BuildTiff(metadata), TileSize = 64 }));
}
var service = fx.Archive.Service;
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);
var session = plan.Sessions.Single();
Assert.Equal(ImageFileFormat.Dng, session.Format);
var id = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Archive.Id, session.SessionKey, fx.Ct);
var sequence = (await fx.Db.Sequences.GetAsync(id!.Value, fx.Ct))!;
// What an index from before owner review 1 holds: GPR, preview-only, already light-analysed.
var folder = fx.Folder(sequence);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
ManifestStore.WriteSequence(folder.ManifestPath, manifest with
{
Frames = [.. manifest.Frames.Select(f => f with { Format = ImageFileFormat.Gpr, Tier = DecodeTier.EmbeddedPreview, Flags = f.Flags | FrameFlags.PreviewOnly, PreviewW = 64, PreviewH = 48 })],
});
var rows = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
await fx.Db.Frames.UpdateTiersAsync([.. rows.Select(r => new FrameTierFields(r.Id, r.Flags | FrameFlags.PreviewOnly, 64, 48, ImageFileFormat.Gpr))], fx.Ct);
await fx.Db.Sequences.UpsertAsync(sequence with { Status = sequence.Status | SequenceStatus.AnalyzedLight }, fx.Ct);
Assert.Contains(sequence.Id, await AnalysisFollowUp.UnanalysedAsync(fx.Db, fx.Archive.Archive.Id, fx.Ct));
await fx.StartEngineAsync();
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(light.Id, JobState.Done);
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath).Frames;
Assert.True(sidecar.All(f => f is { Format: ImageFileFormat.Dng, Tier: DecodeTier.Native } && (f.Flags & FrameFlags.PreviewOnly) == 0),
string.Join(", ", sidecar.Select(f => $"{f.Format}/{f.Tier}/{f.Flags}")));
var indexed = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
Assert.True(indexed.All(f => f.Format == ImageFileFormat.Dng && (f.Flags & FrameFlags.PreviewOnly) == 0), "the index follows");
Assert.Equal(0, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.PreviewOnlyCount);
Assert.DoesNotContain(sequence.Id, await AnalysisFollowUp.UnanalysedAsync(fx.Db, fx.Archive.Archive.Id, fx.Ct));
}
[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()
{
await using var reference = await ProcessingFixture.CreateAsync(context);
var expectedSequence = await reference.AddAsync(Flickering());
await reference.StartEngineAsync();
var full = await reference.EnqueueAsync(ProcessingJobs.DeepAnalysis([expectedSequence.Id]));
await reference.WaitForAsync(full.Id, JobState.Done);
var expected = await File.ReadAllTextAsync(reference.Folder(expectedSequence).AnalysisPath, reference.Ct);
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering());
var folder = fx.Folder(sequence);
var partial = Path.Combine(folder.MetaDirectory, DeepAnalysisCheckpointFile.FileName);
// Frame 25 is not in the region sample, so the hold stops the pass inside the batch of frames 24–25.
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);
var saved = File.ReadAllLines(partial).Length - 1;
Assert.Equal(24, saved);
Assert.FileMissing(folder.AnalysisPath);
fx.Decoder.Hold = null;
while (fx.Decoder.Requests.TryDequeue(out _))
{
}
await fx.Engine.ResumeAsync(job.Id, fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(expected, await File.ReadAllTextAsync(folder.AnalysisPath, fx.Ct));
Assert.FileMissing(partial);
// After the region sample, only the last checkpointed frame is decoded again (to restore the comparison state).
var analysed = fx.Decoder.Requests.Skip(ProcessingFixture.DeepOptions.RegionSampleFrames)
.Select(r => int.Parse(Path.GetFileNameWithoutExtension(r.Path)[4..]) - 1).ToList();
Assert.Equal(saved - 1, analysed.Min());
Assert.Equal(sequence.FrameCount, (int)done.ProgressDone);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedDeep | SequenceStatus.AnalyzedLight), "index status");
var summary = AnalysisSummary.FromJson(row.AnalysisJson!);
Assert.Equal(sequence.FrameCount, summary.FrameCount);
Assert.NotNull((await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))[5].MeanLogLuminance);
var project = ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct));
Assert.True(project.Exposure.Deflicker.HasAdvice, "deflicker advised from the pixels");
Assert.Contains(Loc.L("Advisor.Log.Presets", string.Empty), done.LogTail);
}
[Test]
public async Task EachDeepAnalysisTakesTheHostsTuningOfThatMoment()
{
// The desktop's Settings › Analysis: the width cap the user sets now applies to the next analysis.
var cap = 40;
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with
{
Tune = basis => basis with { DeepAnalysis = basis.DeepAnalysis with { MinAnalysisLongEdge = 16, MaxAnalysisLongEdge = cap } },
});
var first = await fx.AddAsync(Flickering(10), "A");
var second = await fx.AddAsync(Flickering(10), "B");
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([first.Id]));
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(40, DeepAnalysisReport.Load(fx.Folder(first).AnalysisPath).AnalysisLongEdge);
cap = 32;
job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([second.Id]));
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(32, DeepAnalysisReport.Load(fx.Folder(second).AnalysisPath).AnalysisLongEdge);
}
[Test]
public async Task ASequenceThatFailsDoesNotStopTheOthersAndARetryRedoesOnlyIt()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var a = await fx.AddAsync(Flickering(10), "A");
var b = await fx.AddAsync(Flickering(10), "B");
var c = await fx.AddAsync(Flickering(10), "C");
// B's sidecar is gone for a while: its status cannot be recorded.
var sidecar = fx.Folder(b).ManifestPath;
var saved = await File.ReadAllBytesAsync(sidecar, fx.Ct);
File.Delete(sidecar);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([a.Id, b.Id, c.Id]));
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.True(failed.Error!.StartsWith(Loc.L("Advisor.Log.Failed", b.DisplayTitle, string.Empty), StringComparison.Ordinal), failed.Error);
Assert.Equal("3;1", failed.Checkpoint);
Assert.SequenceEqual([true, false, true], await AnalysedAsync(fx, a, b, c));
await File.WriteAllBytesAsync(sidecar, saved, fx.Ct);
await fx.Engine.ResumeAsync(job.Id, fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.SequenceEqual([true, true, true], await AnalysedAsync(fx, a, b, c));
Assert.Equal((3L, 3L), (done.ProgressDone, done.ProgressTotal));
// The retry analysed B alone.
var lightOfA = Loc.L("Advisor.Log.LightDone", a.DisplayTitle, 10, 0).Split(',')[0];
Assert.Equal(1, done.LogTail!.Split('\n').Count(line => line.Contains(lightOfA, StringComparison.Ordinal)));
}
[Test]
public void AnalysisCheckpointsKeepTheFailedTargets()
{
Assert.Equal("3", AnalyseJobHandler.Format(3, []));
Assert.Equal("4;0,2", AnalyseJobHandler.Format(4, [2, 0]));
var (next, retry) = AnalyseJobHandler.Parse("4;0,2", 5);
Assert.Equal(4, next);
Assert.SequenceEqual([0, 2], retry);
Assert.Equal(2, AnalyseJobHandler.Parse("2", 5).Next);
// Anything else starts over: no checkpoint, beyond the targets, a failed target not yet reached, garbage.
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 = "Chronos" });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
private static async Task<IReadOnlyList<Job>> LightJobsAsync(ProcessingFixture fx) =>
(await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, 100, null, fx.Ct)).Items;
/// <summary>The project as <c>project.json</c> holds it (the defaults before any analysis wrote it).</summary>
private static async Task<string> ProjectJsonAsync(ProcessingFixture fx, SequencePaths folder) =>
(File.Exists(folder.ProjectPath) ? ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct)) : new ProjectSettings()).ToJson();
private static async Task<List<bool>> AnalysedAsync(ProcessingFixture fx, params Sequence[] sequences)
{
var analysed = new List<bool>();
foreach (var s in sequences) analysed.Add((await fx.Db.Sequences.GetAsync(s.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedLight));
return analysed;
}
[Test]
public async Task LightAnalysisAfterNewFramesDropsTheStaleDeepStatus()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
await fx.StartEngineAsync();
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.WaitForAsync(deep.Id, JobState.Done);
Assert.True((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedDeep), "deep status");
// A thirteenth frame arrives: the report describes 12 frames, so it no longer counts.
await fx.AddAsync(Flickering(13), first: 12);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(light.Id, JobState.Done);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(13, row.FrameCount);
Assert.Equal((true, false), (row.Status.HasFlag(SequenceStatus.AnalyzedLight), row.Status.HasFlag(SequenceStatus.AnalyzedDeep)));
}
}
@@ -0,0 +1,176 @@
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
using Chronos.Testing;
using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
namespace Chronos.Data.Tests.Processing;
/// <summary>
/// Photos decoded at once (owner review 1, R2): the whole parallelism, unless developing large originals whole would
/// exceed the memory budget. Only the decodes that develop an original count: a JPEG at least twice the size asked for
/// decodes scaled down, and a frame read through its proxy or an embedded preview of that size needs no development.
/// </summary>
public sealed class DecodeParallelismTests
{
/// <summary>2 GiB: two 24 MP developments (some 768 MB each), one of 45 MP.</summary>
private const long Budget = 2L << 30;
private static readonly ImageDecoder Server = DecoderFactory.CreateServer();
[Test]
public void WhatADecodeDevelopsWholeDependsOnTheFormatTheSizeAskedForAndThePreview()
{
const int w = 6000, h = 4000;
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 320, preferPreview: false));
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 3000, preferPreview: false));
// A 4K render of a 24 MP JPEG decodes it nearly whole; full size (0) always does.
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 3840, preferPreview: false));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 0, preferPreview: true));
// A preview reaching the size serves only decodes that prefer previews; a render develops the RAW.
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Cr2, w, h, 1620, 512, preferPreview: true));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Cr2, w, h, 1620, 512, preferPreview: false));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Cr2, w, h, 1620, 2048, preferPreview: true));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Tiff, w, h, 0, 320, preferPreview: true));
// Only RAW decoders take a preview by choice: a TIFF's or a HEIF's is never a shortcut.
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Tiff, w, h, w, 512, preferPreview: true));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Heif, w, h, 512, 512, preferPreview: true));
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Dng, w, h, 1024, 512, preferPreview: true));
Assert.Equal(DecodeBudget.UnknownPixels, DecodeBudget.Developed(ImageFileFormat.Png, 0, 0, 0, 320, preferPreview: true));
}
[Test]
public void ThumbnailAndProxyPassesHoldBackOnlyForTheOriginalsTheyDevelop()
{
static SidecarFrame Frame(ImageFileFormat format, int width, int height, int? preview = null) =>
new() { Id = Guid.NewGuid(), File = "f", Format = format, W = width, H = height, PreviewW = preview, PreviewH = preview * 2 / 3 };
static int Thumbnails(params SidecarFrame[] frames) => ArchiveImages.PassParallelism(8, Budget, frames, 320, preferPreview: true, Server);
static int Proxies(int edge, params SidecarFrame[] frames) => ArchiveImages.PassParallelism(8, Budget, frames, edge, preferPreview: false, Server);
Assert.Equal(8, Thumbnails(Frame(ImageFileFormat.Jpeg, 8192, 5464), Frame(ImageFileFormat.Cr2, 8192, 5464, preview: 1620)));
// A HEIF the server reads through its proxy or preview develops nothing either.
Assert.Equal(8, Thumbnails(Frame(ImageFileFormat.Heif, 8192, 5464)));
// A 45 MP TIFF is decoded whole: one at a time within 2 GiB, whatever the JPEGs beside it.
Assert.Equal(1, Thumbnails(Frame(ImageFileFormat.Jpeg, 8192, 5464), Frame(ImageFileFormat.Tiff, 8192, 5464)));
// A RAW whose preview is smaller than the thumbnail is developed; a size nobody knows counts as 24 MP.
Assert.Equal(2, Thumbnails(Frame(ImageFileFormat.Cr2, 6000, 4000, preview: 160)));
Assert.Equal(2, Thumbnails(Frame(ImageFileFormat.Png, 0, 0)));
Assert.Equal(1, ArchiveImages.PassParallelism(0, Budget, [Frame(ImageFileFormat.Jpeg, 48, 32)], 320, preferPreview: true, Server));
// Proxies of 2048 px scale JPEGs down but develop every RAW, preview or not; full-size proxies decode JPEGs whole.
Assert.Equal(8, Proxies(2048, Frame(ImageFileFormat.Jpeg, 8192, 5464)));
Assert.Equal(2, Proxies(2048, Frame(ImageFileFormat.Cr2, 6000, 4000, preview: 6000)));
Assert.Equal(2, Proxies(0, Frame(ImageFileFormat.Jpeg, 6000, 4000)));
}
[Test]
public void ADeepAnalysisHoldsBackOnlyForTheOriginalsItDevelops()
{
var analysis = DeepAnalysisOptions.Default with { MaxDegreeOfParallelism = 8 };
Assert.Equal(8, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Jpeg, 8192, 5464, 0)), Budget));
// A DNG whose embedded preview reaches the analysis size (half the long edge, at most 2048 px) develops nothing.
Assert.Equal(8, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Dng, 5568, 4872, 2784)), Budget));
Assert.Equal(1, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Dng, 5568, 4872, 1024), (ImageFileFormat.Tiff, 8192, 5464, 0)), Budget));
// Frames read through their proxies decode as JPEGs.
Assert.Equal(8, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Tiff, 8192, 5464, 0)) with { Proxied = [true] }, Budget));
}
[Test]
public async Task AWindowHoldsBackWheneverItsDecodesDevelopOriginals()
{
var window = new FrameWindowOptions { MemoryBudget = Budget, MaxConcurrentLoads = 8, Ahead = 8 };
var tiffs = Frames((ImageFileFormat.Tiff, 8192, 5464, 0), (ImageFileFormat.Tiff, 8192, 5464, 0));
// A render node renders downloaded originals without counting what they decode (Originals unset): still held back.
await using (var node = new SequenceFrameSource(tiffs, tiffs.LightFrames(), Server, window))
{
Assert.Equal(1, node.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
// A preparation pass decodes TIFFs whole too.
Assert.Equal(1, node.WindowOptions(512, DecodePurpose.Analysis).MaxConcurrentLoads);
Assert.Equal((Budget, 8), (node.WindowOptions(1920, DecodePurpose.Render).MemoryBudget, node.WindowOptions(1920, DecodePurpose.Render).Ahead));
}
// RAWs whose previews reach the preparation's size: the preparation runs them all, the render develops them.
var raws = Frames((ImageFileFormat.Cr2, 6000, 4000, 1620), (ImageFileFormat.Cr2, 6000, 4000, 1620));
await using (var raw = new SequenceFrameSource(raws, raws.LightFrames(), Server, window) { Originals = true })
{
Assert.Equal(8, raw.WindowOptions(512, DecodePurpose.Analysis).MaxConcurrentLoads);
Assert.Equal(2, raw.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
}
// Proxies decode as JPEGs, flagged or found in a proxy cache's .jpg files.
await using (var proxied = new SequenceFrameSource(tiffs with { Proxied = [true, true] }, tiffs.LightFrames(), Server, window))
Assert.Equal(8, proxied.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
var cached = raws with { Files = ["cache/0001.jpg", "cache/0002.JPG"] };
await using var cache = new SequenceFrameSource(cached, cached.LightFrames(), Server, window);
Assert.Equal(8, cache.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
}
[Test]
public async Task ADemandLoadWaitsForTheReadAheadOfADevelopingWindow()
{
// The window caps its read-ahead only: a render that skips frames (a speed-up) asks for a frame the read-ahead is
// not decoding while it develops another, and both would run. One development at a time fits this budget.
var decoder = new CountingDecoder();
var tiffs = Frames([.. Enumerable.Repeat((ImageFileFormat.Tiff, 8192, 5464, 0), 8)]);
var frames = tiffs with { Files = [.. tiffs.Files.Select(f => f + ".tif")] };
var window = new FrameWindowOptions { MemoryBudget = Budget, MaxConcurrentLoads = 8, Ahead = 8 };
await using (var source = new SequenceFrameSource(frames, frames.LightFrames(), new ImageDecoder([decoder]), window))
{
Assert.Equal(1, source.DevelopingLimit(1920, DecodePurpose.Render));
foreach (var index in new[] { 0, 2, 4, 6 })
using (await source.GetFrameAsync(index, 1920, DecodePurpose.Render, CancellationToken.None)) { }
}
Assert.Equal(1, decoder.Peak);
Assert.Greater(decoder.Decodes, 4);
}
/// <summary>Decodes anything as a tiny frame, slowly, and counts how many decodes run at once.</summary>
private sealed class CountingDecoder : IImageDecoderProvider
{
private int _running;
private int _peak;
private int _decodes;
public int Peak => Volatile.Read(ref _peak);
public int Decodes => Volatile.Read(ref _decodes);
public string Name => "counting";
public DecodeTier? TierFor(ImageFileFormat format) => DecodeTier.Native;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
var now = Interlocked.Increment(ref _running);
int seen;
while ((seen = Volatile.Read(ref _peak)) < now && Interlocked.CompareExchange(ref _peak, now, seen) != seen)
{
}
Interlocked.Increment(ref _decodes);
Thread.Sleep(40);
Interlocked.Decrement(ref _running);
return new DecodedImage(new ImageBuffer(8, 6), DecodeTier.Native, Name, 8192, 5464);
}
}
private static SequenceFrames Frames(params (ImageFileFormat Format, int Width, int Height, int Preview)[] specs)
{
var sequence = new Sequence { Id = Guid.NewGuid(), ArchiveId = Guid.NewGuid(), Folder = "a" };
var frames = specs.Select((s, i) => new Frame
{
Id = Guid.NewGuid(),
SequenceId = sequence.Id,
Index = i,
RelativePath = $"a/IMG_{i:0000}",
FileName = $"IMG_{i:0000}",
CapturedAt = new DateTime(2026, 10, 16, 6, 0, 0).AddSeconds(10 * i),
Width = s.Width,
Height = s.Height,
Format = s.Format,
PreviewWidth = s.Preview,
PreviewHeight = s.Preview * 2 / 3,
}).ToList();
return new SequenceFrames(sequence, frames, [.. frames.Select(f => (string?)f.RelativePath)]);
}
}
@@ -0,0 +1,83 @@
using Chronos.Core.Export;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
using Chronos.Data.Processing;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>Settings › Rendering "Software only" and "Hardware for previews only" keep renders off the GPU encoders.</summary>
[Category("processing")]
public sealed class HardwarePolicyTests
{
/// <summary>A PC with GPU HEVC and H.264 encoders and the software H.264 encoder; records what it opens.</summary>
private sealed class GpuProvider : IVideoEncoderProvider
{
public List<EncodeSettings> Opened { get; } = [];
public string Name => "gpu";
public IReadOnlyList<EncoderCapability> Capabilities { get; } =
[
new(VideoCodec.Hevc, "GPU HEVC", true, 8192, 8192, true),
new(VideoCodec.H264, "GPU H.264", true, 4096, 4096, false),
new(VideoCodec.H264, "Software H.264", false, 4096, 2304, false),
];
public bool CanEncode(EncodeSettings settings) =>
Capabilities.Any(c => c.Codec == settings.Codec && (settings.EncoderName is null || settings.EncoderName == c.Name)
&& settings.Width <= c.MaxWidth && settings.Height <= c.MaxHeight);
public IVideoEncoderSession Open(EncodeSettings settings)
{
Opened.Add(settings);
throw new NotSupportedException("recorded");
}
}
private static EncodeSettings Hevc4k(string? encoder = null) => new()
{
OutputPath = "out.mp4",
Codec = VideoCodec.Hevc,
Width = 3840,
Height = 2160,
FrameRate = new Rational(30, 1),
BitRate = 40_000_000,
EncoderName = encoder,
};
[Test]
public void SoftwareOnlyFallsBackToTheSoftwareEncoder()
{
var gpu = new GpuProvider();
var options = new ProcessingOptions { Encoders = [gpu, new ManagedEncoderProvider()], AllowsHardware = _ => false };
var selection = EncoderSelector.Select(Hevc4k(), options.SoftwareEncoders, EncoderHost.Client);
Assert.True(selection.IsReady, "software H.264 instead");
Assert.Equal((VideoCodec.H264, "Software H.264"), (selection.Settings.Codec, selection.Capability!.Name));
Assert.Contains(selection.Notices, n => n.Key == EncoderNotices.FallbackToH264);
Assert.Throws<NotSupportedException>(() => selection.Open());
Assert.Equal(("Software H.264", false), (gpu.Opened.Single().EncoderName, gpu.Opened.Single().PreferHardware));
// A GPU encoder named in the export is not used either.
var named = EncoderSelector.Select(Hevc4k("GPU H.264") with { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }, options.SoftwareEncoders, EncoderHost.Client);
Assert.Equal("Software H.264", named.Capability?.Name);
Assert.True(options.SoftwareEncoders[1] is ManagedEncoderProvider, "managed encoders are untouched");
}
[Test]
public void ARenderNodeOffersGpuEncodersOnlyWhenRendersMayUseThem()
{
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "studio-pc");
var nodeOptions = new RenderNodeOptions { ClientName = "studio-pc", CacheDirectory = Path.GetTempPath() };
string[] Offered(Func<string, bool> allows) =>
[
.. new RenderNodeClient(client, new ProcessingOptions { Encoders = [new GpuProvider()], AllowsHardware = allows }, nodeOptions).Encoders
.Select(e => e.Name),
];
Assert.SequenceEqual(["GPU HEVC", "GPU H.264", "Software H.264"], Offered(_ => true));
Assert.SequenceEqual(["Software H.264"], Offered(id => id == "720p-preview"));
}
}
@@ -0,0 +1,197 @@
using System.Collections.Concurrent;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>A temporary archive holding synthetic sequences (JPEGs with Exif), a processing engine and its job engine.</summary>
internal sealed class ProcessingFixture : IAsyncDisposable
{
/// <summary>Small sources are analysed at native size; batches of two frames between checkpoints.</summary>
public static readonly DeepAnalysisOptions DeepOptions = new() { MinAnalysisLongEdge = 64, FlowEvery = 5, MaxDegreeOfParallelism = 2, RegionSampleFrames = 9 };
private JobEngine? _engine;
private ProcessingFixture(ArchiveFixture archive, GateDecoder decoder, Func<ProcessingOptions, ProcessingOptions>? configure)
{
Archive = archive;
Decoder = decoder;
var options = new ProcessingOptions
{
Archive = new ArchiveServiceOptions { Decoder = new ImageDecoder([decoder]), Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
DeepAnalysis = DeepOptions,
ProducedBy = "test-pc",
};
Processing = new ProcessingService(archive.Db, configure?.Invoke(options) ?? options);
}
public ArchiveFixture Archive { get; }
public GateDecoder Decoder { get; }
public ProcessingService Processing { get; }
public ChronosDatabase Db => Archive.Db;
public CancellationToken Ct => Archive.Ct;
public JobEngine Engine => _engine ?? throw new InvalidOperationException("Start the engine first.");
/// <param name="configure">Changes to the processing options (a server's host and render-node check).</param>
public static async Task<ProcessingFixture> CreateAsync(TestContext context, Func<ProcessingOptions, ProcessingOptions>? configure = null) =>
new(await ArchiveFixture.CreateAsync(context), new GateDecoder(), configure);
/// <summary>A started engine with the processing handlers, and the archive's when asked (one worker unless asked, fast checkpoints).</summary>
public async Task<JobEngine> StartEngineAsync(bool withArchive = false, int workers = 1)
{
_engine = new JobEngine(Db, [.. withArchive ? Archive.Service.CreateJobHandlers() : [], .. Processing.CreateJobHandlers()],
new JobEngineOptions { Workers = workers, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await _engine.StartAsync(Ct);
return _engine;
}
public Task<Job> EnqueueAsync(Chronos.Data.Archiving.Jobs.ArchiveJobRequest request) => Engine.EnqueueAsync(request, cancellationToken: Ct);
public Task<Job> WaitForAsync(Guid jobId, JobState state) => Archive.WaitForAsync(jobId, state, 60);
/// <summary>Writes frames <paramref name="first"/>… of <paramref name="sequence"/> as JPEGs with their Exif into
/// <paramref name="folder"/> (adopted in place) and indexes the archive.</summary>
public async Task<Sequence> AddAsync(SyntheticSequence sequence, string folder = "Synthetic", int first = 0)
{
Write(sequence, folder, first);
await Archive.ScanAsync(ScanMode.Full);
var location = (await Db.Sequences.ListLocationsAsync(Archive.Archive.Id, Ct)).Single(l => l.Folder == folder);
return (await Db.Sequences.GetAsync(location.Id, Ct))!;
}
/// <summary>Writes frames <paramref name="first"/>… of <paramref name="sequence"/> as JPEGs with their Exif into <paramref name="folder"/>.</summary>
public void Write(SyntheticSequence sequence, string folder = "Synthetic", int first = 0)
{
var directory = Path.Combine(Archive.Paths.Root, folder);
Directory.CreateDirectory(directory);
for (var i = first; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(directory, FileName(i)), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 95, App1Segments = [exif[4..]] }));
}
}
public static string FileName(int index) => $"IMG_{index + 1:0000}.JPG";
public SequencePaths Folder(Sequence sequence) => Archive.Paths.Sequence(sequence.Folder);
public async ValueTask DisposeAsync()
{
if (_engine is not null) await _engine.DisposeAsync();
await Archive.DisposeAsync();
}
}
/// <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();
public string Name => "gate";
public ConcurrentQueue<DecodeRequest> Requests { get; } = new();
/// <summary>File name whose decode waits for cancellation; null decodes everything.</summary>
public string? Hold { get; set; }
/// <summary>Holds only decodes of this purpose (null: any).</summary>
public DecodePurpose? HoldPurpose { get; set; }
/// <summary>Holds only decodes with this long edge (null: any).</summary>
public int? HoldEdge { get; set; }
/// <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>File name whose tier probe waits until <see cref="Release"/> (a light analysis probes frames whose tier is
/// not known yet, and decodes nothing); null probes everything.</summary>
public string? HoldProbe { get; private set; }
/// <summary>Holds the next tier probe of frame <paramref name="index"/>'s file, as <see cref="HoldFrame"/> holds a decode.</summary>
public void HoldProbeOf(int index)
{
Holding = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_released = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
HoldProbe = 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();
/// <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) => Probe(path, format, null);
public FileTier Probe(string path, ImageFileFormat format, string? companion)
{
var name = Path.GetFileName(path);
if (HoldProbe is { } hold && name == hold)
{
Holding.TrySetResult();
_released.Task.Wait(TimeSpan.FromSeconds(30));
}
return Tiers.TryGetValue(name, out var tier) ? tier : _managed.Probe(path, format, companion);
}
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
Requests.Enqueue(request);
var name = Path.GetFileName(request.Path);
if (Hold is { } hold && name == hold && (HoldPurpose ?? request.Purpose) == request.Purpose
&& (HoldEdge ?? request.MaxLongEdge) == request.MaxLongEdge)
{
Holding.TrySetResult();
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.");
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);
}
}
@@ -0,0 +1,65 @@
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>A <c>.chronos</c> project file names a sequence of this index, found again by id or by its folder (BRIEF §18).</summary>
public abstract class ProjectBundlesTests(TestContext context) : RepositoryTest(context)
{
[Test]
public async Task TheFileNamesTheSequenceAndItsArchive()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive("Main");
await db.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id, title: "Harbour sunset");
await db.Sequences.UpsertAsync(sequence, Ct);
var project = new ProjectSettings { ExcludedFrames = [2] };
var bundle = await ProjectBundles.CreateAsync(db, sequence.Id, project, frames: 120, Ct);
Assert.Equal(new BundleArchive(archive.Id, "Main", archive.RootPath), bundle.Archive);
Assert.Equal(new BundleSequence(sequence.Id, sequence.Folder, "Harbour sunset", 120), bundle.Sequence);
Assert.Same(project, bundle.Project);
Assert.Equal(sequence.Id, (await ProjectBundles.ResolveAsync(db, ProjectBundle.Parse(bundle.ToJson()), Ct))!.Id);
await Assert.ThrowsAsync<InvalidOperationException>(() => ProjectBundles.CreateAsync(db, Guid.CreateVersion7(), project, 0, Ct));
}
[Test]
public async Task ASequenceWithANewIdIsFoundByItsFolderInTheSameArchive()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive("Main");
var other = TestData.Archive("Other");
await db.Archives.UpsertAsync(archive, Ct);
await db.Archives.UpsertAsync(other, Ct);
var adoptedAgain = TestData.Sequence(archive.Id) with { Folder = "2026/2026-09-28 Harbour" };
var elsewhere = TestData.Sequence(other.Id) with { Folder = "2026/2026-09-28 Roof" };
await db.Sequences.UpsertAsync(adoptedAgain, Ct);
await db.Sequences.UpsertAsync(elsewhere, Ct);
var bundle = Bundle(archive.Id, Guid.CreateVersion7(), "2026/2026-09-28 HARBOUR");
Assert.Equal(adoptedAgain.Id, (await ProjectBundles.ResolveAsync(db, bundle, Ct))!.Id);
// A folder of another archive, an unknown folder or an archive this index does not have: not found.
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(archive.Id, Guid.CreateVersion7(), "2026/2026-09-28 Roof"), Ct));
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(archive.Id, Guid.CreateVersion7(), "2025/missing"), Ct));
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(Guid.CreateVersion7(), Guid.CreateVersion7(), "2026/2026-09-28 Harbour"), Ct));
}
private static ProjectBundle Bundle(Guid archiveId, Guid sequenceId, string folder) =>
new(new BundleArchive(archiveId, "Main", null), new BundleSequence(sequenceId, folder, "Harbour", 10), new ProjectSettings(), TestData.Now);
}
public sealed class SqliteProjectBundlesTests(TestContext context) : ProjectBundlesTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresProjectBundlesTests(TestContext context) : ProjectBundlesTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,476 @@
using System.Text;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
[Category("processing")]
public sealed class RenderJobTests(TestContext context)
{
private const int Frames = 24;
/// <summary>MJPEG at the source size, named by codec so the tests know the file names.</summary>
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
/// <summary>HEVC (a render node's codec) at the size of <see cref="Mjpeg"/>.</summary>
private static readonly ExportSettings Hevc = Mjpeg with { Preset = new Auto<string>().WithManual("4k-hevc") };
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
[Test]
public async Task ABatchWritesPlayableManagedOutputsIntoExportsAndRecordsThem()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["png-sequence", "gif-preview"] }, 96, 64));
await fx.WaitForAsync(job.Id, JobState.Done);
var exports = fx.Folder(sequence).Exports;
var avi = await File.ReadAllBytesAsync(Path.Combine(exports, "clip-MJPEG.avi"), fx.Ct);
Assert.Equal(("RIFF", "AVI "), (Encoding.ASCII.GetString(avi, 0, 4), Encoding.ASCII.GetString(avi, 8, 4)));
Assert.Contains("idx1", Encoding.ASCII.GetString(avi));
var pngs = Directory.GetFiles(Path.Combine(exports, "clip-PNG")).Order().ToList();
Assert.Equal(Frames, pngs.Count);
Assert.Equal("clip-PNG_000001.png", Path.GetFileName(pngs[0]));
using (var decoded = DecoderFactory.CreateServer().Decode(new DecodeRequest(pngs[^1])))
Assert.Equal((96, 64), (Assert.NotNull(decoded).Pixels.Width, decoded.Pixels.Height));
var gif = await File.ReadAllBytesAsync(Path.Combine(exports, "clip-GIF.gif"), fx.Ct);
Assert.Equal("GIF89a", Encoding.ASCII.GetString(gif, 0, 6));
Assert.Empty(Directory.EnumerateFileSystemEntries(exports, ".*"));
var renders = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).OrderBy(r => r.OutputPath, StringComparer.Ordinal).ToList();
Assert.SequenceEqual(["Synthetic/exports/clip-GIF.gif", "Synthetic/exports/clip-MJPEG.avi", "Synthetic/exports/clip-PNG"], renders.Select(r => r.OutputPath));
var mjpeg = renders[1];
Assert.Equal((Loc.L("Export.Preset.Custom"), "Mjpeg", 96, 64, "test-pc", (long)avi.Length),
(mjpeg.PresetName, mjpeg.Codec, mjpeg.Width, mjpeg.Height, mjpeg.ProducedBy, mjpeg.Bytes));
Assert.Equal(Loc.L("Export.Preset.Gif"), renders[0].PresetName);
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()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
fx.Decoder.HoldFrame(12, DecodePurpose.Render);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
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);
await WaitUntilIdleAsync(fx, job.Id);
Assert.Empty(Entries(fx.Folder(sequence).Exports));
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task AFailedRenderLeavesNothingBehindAndSaysWhy()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
// Every file damaged after indexing: nothing flags them, and no frame can stand in for another.
for (var i = 0; i < Frames; i++)
await File.WriteAllBytesAsync(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(i)), new byte[5000], fx.Ct);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L(SequenceFrameSource.FrameUnreadableKey, "1", ProcessingFixture.FileName(0)), failed.Error);
Assert.Empty(Entries(fx.Folder(sequence).Exports));
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task AFrameThatNoLongerDecodesIsReplacedByItsNeighbourAndLeftOutNextTime()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
// Damaged after indexing: nothing flags the frame, so only decoding finds out (BRIEF §8.2 tier 3).
await File.WriteAllBytesAsync(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(10)), new byte[5000], fx.Ct);
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);
Assert.SequenceEqual(["clip-MJPEG.avi"], Entries(fx.Folder(sequence).Exports));
var row = (await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct))[10];
Assert.Equal(FrameFlags.Undecodable, row.Flags);
var sidecar = Chronos.Core.Archiving.ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath);
Assert.Equal((DecodeTier.Unavailable, FrameFlags.Undecodable), (sidecar.Frames[10].Tier, sidecar.Frames[10].Flags));
Assert.Equal(DecodeTier.Native, sidecar.Frames[9].Tier);
Assert.True(sidecar.Status.HasFlag(SequenceStatus.HasWarnings), "the sequence warns at once");
Assert.True((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.HasWarnings), "index status");
// The next render plans without the frame, so nothing has to stand in for it.
var again = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
var second = await fx.WaitForAsync(again.Id, JobState.Done);
Assert.False(second.LogTail?.Contains(Loc.L("Export.Log.StandIns", "11"), StringComparison.Ordinal) == true, "no stand-in");
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 = Chronos.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 = Chronos.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 = Chronos.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), (Chronos.Core.Advice.SequenceContext.FromFrames(rows).PreviewWidth, Chronos.Core.Advice.SequenceContext.FromFrames(rows).PreviewHeight));
}
[Test]
public void FramesARenderNodeReceivesKeepTheirTierFields()
{
var dto = new Chronos.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 = Chronos.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 decoder = new ImageDecoder([fx.Decoder]);
var frames = await SequenceFrames.LoadAsync(fx.Db, fx.Archive.Archive, sequence, useProxies: false, decoder, 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(), 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()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var exports = fx.Folder(sequence).Exports;
var output = Path.Combine(exports, "clip-MJPEG.avi");
// The crashed attempt left its encoder's temporary file and a finished output it never recorded.
Directory.CreateDirectory(exports);
await File.WriteAllBytesAsync(Path.Combine(exports, ".clip-MJPEG.avi.0badf00d.tmp"), new byte[100], fx.Ct);
await File.WriteAllBytesAsync(output, new byte[100], fx.Ct);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64),
new RenderCheckpoint([], 0, output).ToJson());
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.SequenceEqual(["clip-GIF.gif", "clip-MJPEG.avi"], Entries(exports));
Assert.Equal("RIFF", Encoding.ASCII.GetString((await File.ReadAllBytesAsync(output, fx.Ct))[..4]));
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ARenderInterruptedAfterRecordingAnOutputResumesWithTheNextOne()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var exports = fx.Folder(sequence).Exports;
var output = Path.Combine(exports, "clip-MJPEG.avi");
Directory.CreateDirectory(exports);
var recorded = Encoding.ASCII.GetBytes("RIFF recorded before the crash");
await File.WriteAllBytesAsync(output, recorded, fx.Ct);
// The crash came after the job recorded its first entry and before its checkpoint said so.
var jobId = Guid.CreateVersion7();
await fx.Db.Renders.InsertAsync(RecordedRender(sequence, Chronos.Data.Processing.Jobs.RenderJobHandler.RenderId(jobId, 0)), fx.Ct);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64),
new RenderCheckpoint([], 0, output).ToJson(), jobId);
await fx.WaitForAsync(job.Id, JobState.Done);
var kept = await File.ReadAllBytesAsync(output, fx.Ct);
Assert.BytesEqual(recorded, kept);
Assert.SequenceEqual(["clip-GIF.gif", "clip-MJPEG.avi"], Entries(exports));
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ARenderResumedAfterAnotherRecordedItsNameKeepsThatOutput()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var exports = fx.Folder(sequence).Exports;
var output = Path.Combine(exports, "clip-MJPEG.avi");
Directory.CreateDirectory(exports);
// While this job waited to resume, another render of the same preset finished under the name it had chosen.
var other = Encoding.ASCII.GetBytes("RIFF another render's output");
await File.WriteAllBytesAsync(output, other, fx.Ct);
await fx.Db.Renders.InsertAsync(RecordedRender(sequence, Guid.CreateVersion7()), fx.Ct);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64), new RenderCheckpoint([], 0, output).ToJson());
await fx.WaitForAsync(job.Id, JobState.Done);
var kept = await File.ReadAllBytesAsync(output, fx.Ct);
Assert.BytesEqual(other, kept);
Assert.SequenceEqual(["clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(exports));
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ConcurrentRendersOfOnePresetKeepBothOutputs()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync(workers: 2);
var first = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
var second = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
await fx.WaitForAsync(first.Id, JobState.Done);
await fx.WaitForAsync(second.Id, JobState.Done);
Assert.SequenceEqual(["clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(fx.Folder(sequence).Exports));
var renders = await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct);
Assert.Equal(2, renders.Select(r => r.OutputPath).Distinct().Count());
}
[Test]
public void ANameBeingWrittenIsNotPickedAgain()
{
var folder = context.CreateTempDirectory("exports");
var name = new ExportNameContext { Date = new DateTime(2026, 6, 1), Title = "Roof", PresetName = "MJPEG", Codec = VideoCodec.Mjpeg };
using var a = new OutputNames();
using var b = new OutputNames();
var first = a.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken));
var second = b.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken));
Assert.Equal((Path.Combine(folder, "Roof.avi"), Path.Combine(folder, "Roof (2).avi")), (first, second));
Assert.False(b.TryReserve(first), "held by the first render");
a.Dispose();
using var c = new OutputNames();
Assert.Equal(first, c.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken)));
}
[Test]
public void RenderRowIdsAreStablePerJobAndEntry()
{
var job = Guid.CreateVersion7();
var id = Chronos.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 0);
Assert.Equal(id, Chronos.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 0));
Assert.NotEqual(id, Chronos.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 1));
Assert.NotEqual(id, Chronos.Data.Processing.Jobs.RenderJobHandler.RenderId(Guid.CreateVersion7(), 0));
Assert.Equal(8, id.Version);
}
[Test]
public async Task AServerTakesOnlyTheRendersItsManagedEncodersProduce()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var server = new ProcessingService(fx.Db, new ProcessingOptions { Host = EncoderHost.Server, AwaitsRenderNode = (_, _, _) => Task.FromResult(true) });
var handler = Assert.NotNull(server.CreateJobHandlers().Single(h => h.Kind == JobKind.Render) as ISelectiveJobHandler);
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic" };
Job Job(ExportSettings export) => new() { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = ProcessingJobs.Render(sequence, export, 96, 64).ParametersJson };
async Task<bool> AcceptsAsync(string? parametersJson) =>
await handler.AcceptsAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = parametersJson }, fx.Ct);
Assert.True(await handler.AcceptsAsync(Job(Mjpeg with { Batch = ["png-sequence", "gif-preview"] }), fx.Ct), "managed outputs only");
Assert.False(await handler.AcceptsAsync(Job(Hevc), fx.Ct), "HEVC waits for a render node");
Assert.False(await handler.AcceptsAsync(Job(Mjpeg with { Batch = ["1080p-h264"] }), fx.Ct), "one MP4 in the batch");
Assert.True(await handler.AcceptsAsync(Job(Hevc) with { Checkpoint = """{"done":[],"pending":0}""" }, fx.Ct), "started here: resumes here");
Assert.True(await AcceptsAsync("{}"), "unreadable: fails with its reason");
Assert.True(await AcceptsAsync(WithPreset("""{"preset":{},"Preset":{}}""")), "a member given twice: fails with its reason");
Assert.True(await AcceptsAsync(WithPreset("""{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"batch":null}""")), "a null batch is no batch");
var client = new ProcessingService(fx.Db).CreateJobHandlers().Single(h => h.Kind == JobKind.Render);
Assert.False(client is ISelectiveJobHandler, "a client renders whatever it is given");
}
[Test]
public async Task AServerTakesMp4JobsOnceNoRenderNodeCanAndOnlyThen()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic" };
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = ProcessingJobs.Render(sequence, Hevc, 96, 64).ParametersJson };
async Task<bool> AcceptsAsync(Func<Job, Chronos.Protocol.RenderJobParameters, CancellationToken, Task<bool>>? awaits)
{
var server = new ProcessingService(fx.Db, new ProcessingOptions { Host = EncoderHost.Server, AwaitsRenderNode = awaits });
return await ((ISelectiveJobHandler)server.CreateJobHandlers().Single(h => h.Kind == JobKind.Render)).AcceptsAsync(job, fx.Ct);
}
Chronos.Protocol.RenderJobParameters? asked = null;
Assert.True(await AcceptsAsync((_, p, _) => { asked = p; return Task.FromResult(false); }), "no node can take it");
Assert.Equal(("hevc", 96, 64), (asked!.Codec, asked.Width, asked.Height));
Assert.False(await AcceptsAsync(null), "without a node check, MP4 jobs always wait");
Assert.False(await AcceptsAsync((_, _, _) => throw new InvalidOperationException("database unreachable")), "unknown: keeps waiting");
}
[Test]
public async Task AServerRendersAsMjpegWhatNoRenderNodeTookAndSaysSo()
{
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { Host = EncoderHost.Server, AwaitsRenderNode = (_, _, _) => Task.FromResult(false) });
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync();
var request = ProcessingJobs.Render(sequence, Hevc, 96, 64);
var job = await fx.WaitForAsync((await fx.EnqueueAsync(request)).Id, JobState.Done);
var avi = await File.ReadAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi"), fx.Ct);
Assert.Equal(("RIFF", "AVI "), (Encoding.ASCII.GetString(avi, 0, 4), Encoding.ASCII.GetString(avi, 8, 4)));
var render = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single();
var preset = Loc.L("Export.Preset.Custom");
Assert.Equal((preset, "Mjpeg", 96, 64), (render.PresetName, render.Codec, render.Width, render.Height));
Assert.Contains(Loc.L("Export.Log.NoRenderNode", preset, "HEVC", "MJPEG"), job.LogTail);
}
[Test]
public void ABatchForAServerBecomesOneJobPerPreset()
{
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic", Title = "Roof" };
var jobs = ProcessingJobs.RenderEach(sequence, Mjpeg with { Batch = ["mjpeg-avi", "gif-preview", "GIF-preview", "4k-hevc"] }, 96, 64);
var parameters = jobs.Select(j => System.Text.Json.JsonSerializer.Deserialize(j.ParametersJson!, Chronos.Protocol.ProtocolJson.Default.RenderJobParameters)!).ToList();
Assert.SequenceEqual(["mjpeg", "gif", "hevc"], parameters.Select(p => p.Codec));
Assert.True(jobs.All(j => j.Kind == JobKind.Render && j.Targets.SequenceEqual([sequence.Id])), "render jobs of the sequence");
Assert.True(parameters.All(p => ProcessingJobs.ReadExport(p.PresetJson).Batch.Count == 0), "no job carries a batch");
Assert.Equal((3840, 2160), (parameters[2].Width, parameters[2].Height));
// A posted batch written by hand may hold blank entries: they name no preset.
var posted = System.Text.Json.JsonSerializer.Deserialize(WithPreset("""{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"batch":[null," ","gif-preview"]}"""),
Chronos.Protocol.ProtocolJson.Default.RenderJobParameters)!;
Assert.SequenceEqual(["mjpeg", "gif"], ProcessingJobs.Split(posted, 96, 64).Select(p => p.Codec));
}
/// <summary>MJPEG job parameters whose preset JSON is <paramref name="presetJson"/>.</summary>
private static string WithPreset(string presetJson) => System.Text.Json.JsonSerializer.Serialize(
new Chronos.Protocol.RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), Chronos.Protocol.ProtocolJson.Default.RenderJobParameters);
private static Render RecordedRender(Sequence sequence, Guid id) => new()
{
Id = id,
SequenceId = sequence.Id,
PresetName = "MJPEG",
OutputPath = "Synthetic/exports/clip-MJPEG.avi",
Created = DateTimeOffset.UtcNow,
};
private static List<string> Entries(string folder) =>
Directory.Exists(folder) ? [.. Directory.EnumerateFileSystemEntries(folder).Select(e => Path.GetFileName(e)).Order(StringComparer.Ordinal)] : [];
/// <summary>The engine marks a job cancelled before its handler has unwound; wait until the worker let it go.</summary>
private static async Task WaitUntilIdleAsync(ProcessingFixture fx, Guid jobId)
{
var until = DateTime.UtcNow.AddSeconds(30);
while (fx.Engine.RunningJobIds.Contains(jobId))
{
Assert.True(DateTime.UtcNow < until, "the render did not stop");
await Task.Delay(20, fx.Ct);
}
}
}