Files
Chronos/src/Titano.Data/Archiving/FrameTiers.cs
T
Alby96andClaude Opus 5.5 34d03051f5 fix: stalled jobs, editor cancellation stops and GoPro DNG decoding
Owner review 1, phase 1 (docs/requests/2026-10-15-owner-review-1.md).

Thumbnail and proxy jobs over several sequences counted sequences while
they checkpointed inside one: the rate decayed until the time left
overflowed TimeSpan, the job failed while publishing progress and again
while saving it, and stayed Running. The throughput is now seeded by the
first window with progress, the time left is bounded (JobEta), saving
progress never throws, image passes count frames, and job speeds use the
right unit (bytes for verify and import).

The debugger stops in WicDecoderProvider.cs when presets changed were
cancelled preview decodes leaving synchronous thread-pool delegates; the
editor's sources, LatestRunner and the render node's proxy task now keep
them in their own tasks, and a cancellation is never an unreadable frame.

GoPro DNGs converted by Adobe software were classified GPR and read only
through their 8-bit preview, and Windows' preview-only DNG decoder was
reported as a native decode. A DNG is GPR only when its raw image is
VC-5, WIC decodes RAW only through the Raw Image Extension and never DNG,
analyses and previews take an adequate embedded preview by choice while
renders develop natively, and frames already indexed as GPR are
reclassified by the next light analysis.

Also records the owner's request (docs/requests), the BRIEF amendments
(§8.1, §8.2, new §24), DECISIONS, CHANGELOG, STATUS and ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:20:26 +02:00

148 lines
9.6 KiB
C#

using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.Model;
using Titano.Data.Repositories;
namespace Titano.Data.Archiving;
/// <summary>
/// Decode tiers of archived frames (BRIEF §8.2) written to the sidecar and the index together: the tier, the
/// <see cref="FrameFlags.PreviewOnly"/> and <see cref="FrameFlags.Undecodable"/> flags that follow it and the preview
/// size, then the sequence row (its preview-only count for the Library chip). A sequence that gains undecodable frames
/// shows a warning at once; its next light analysis lists them. Tiers describe the host that probed or decoded the files
/// last. Only a file in a format this host decodes natively is flagged undecodable (it is damaged); one beyond this
/// host's decoders (HEIF or an unsupported RAW without a preview on the server) keeps its tier but no flag, so render
/// nodes and proxies can still provide its pixels, and a host that decodes a flagged frame clears the flag. A frame whose
/// original this host reads through its proxy (<see cref="ArchiveImages.NeedsProxy(ImageFileFormat)"/>) is preview-only
/// only while it has none: with its proxy it is not rendered from the embedded preview, so it caps nothing.
/// </summary>
internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
{
/// <summary>
/// The tier of every frame of <paramref name="manifest"/> whose tier is not known yet, that decodes only through a
/// preview whose size is not known (the output cap needs it), or that is a GPR whose JPEG in another sequence
/// (<see cref="GprCompanions"/>; an upload may index it after the GPR was probed) is larger than its stored preview,
/// or that is stored as GPR without the .gpr extension (indexed before GoPro DNGs converted by Adobe software counted as
/// DNG; R4, owner review 1), probed with the host's decoders without decoding pixels; missing and unreadable files are
/// left for later.
/// </summary>
public async Task<Dictionary<Guid, FileTier>> ProbeUnknownAsync(Archive archive, SequencePaths folder, SequenceManifest manifest,
CancellationToken cancellationToken)
{
var tiers = new Dictionary<Guid, FileTier>();
var present = manifest.Frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var companions = await GprCompanions.FindWithSizesAsync(db, archive, present, cancellationToken).ConfigureAwait(false);
var unknown = present.Where(f => f.Tier == 0 || (f.Tier == DecodeTier.EmbeddedPreview && f.PreviewW is null) || IsStaleGpr(f)
|| (companions.TryGetValue(f.Id, out var jpeg)
&& int.Max(f.PreviewW ?? 0, f.PreviewH ?? 0) < int.Max(jpeg.Width, jpeg.Height)));
foreach (var frame in unknown)
{
cancellationToken.ThrowIfCancellationRequested();
var path = folder.File(frame.File);
try
{
var tier = writer.Options.Decoder.Probe(path, frame.Format, companions.TryGetValue(frame.Id, out var companion) ? companion.Path : null);
Core.Diagnostics.Log.Debug("archive", $"{frame.File}: {tier.Tier} via {tier.Decoder ?? "none"}{(tier.Reason is { } why ? $" ({why})" : "")}");
tiers[frame.Id] = tier;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("archive", $"{path} could not be probed", ex);
}
}
return tiers;
}
/// <summary>
/// Records <paramref name="tiers"/> (by frame id) where they change what the sidecar says, and returns the sequence's
/// frames as the sidecar has them afterwards (none when there was nothing to record). Frames no longer in the
/// sequence are ignored. The <see cref="FrameFlags.PreviewOnly"/> flag of a frame whose original this host reads
/// through its proxy follows whether its own proxy is there when the sidecar is written
/// (<see cref="ArchiveImages.IsProxyOf"/>, <see cref="SequenceFrames.WithProxy"/>), not when the caller looked: proxies
/// arrive while analyses and renders run, and another worker may have recorded them already.
/// </summary>
/// <param name="proxies">Whether every such frame follows its proxy even where no tier is recorded (analyses and the
/// proxy pass); otherwise only the frames in <paramref name="tiers"/> do.</param>
/// <remarks>
/// The sidecar and the index are written under one lease, the index from the sidecar read under it, and the index
/// row gets only what tiers change (<see cref="SequenceRepository.RecordTiersAsync"/>): a whole row written back
/// would undo what another writer committed meanwhile, an ingest's frames or a settings edit (the server's PATCH
/// takes no lease). The folder's scan stamps are recorded only when the index held the folder as it was
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, SequencePaths, SequenceManifest, CancellationToken)"/>).
/// </remarks>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
public async Task<IReadOnlyList<SidecarFrame>> RecordAsync(Archive archive, Sequence sequence, IReadOnlyDictionary<Guid, FileTier> tiers,
bool proxies, CancellationToken cancellationToken)
{
if (tiers.Count == 0 && !proxies) return [];
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var m = SequenceWriter.ReadLocked(folder, sequence.Id);
var changed = new List<SidecarFrame>();
var gained = false;
ProxyPolicy? policy = null;
var frames = new SidecarFrame[m.Frames.Count];
for (var i = 0; i < frames.Length; i++)
{
var frame = m.Frames[i];
frames[i] = frame;
var tier = tiers.GetValueOrDefault(frame.Id);
if (tier is null && !proxies) continue;
bool? proxied = (frame.Flags & FrameFlags.Missing) == 0 && ArchiveImages.NeedsProxy(writer.Options.Decoder, frame.Format)
? ArchiveImages.IsProxyOf(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H,
policy ??= ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy)
: null;
SidecarFrame updated;
if (tier is not null) updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format), proxied == true);
else if (proxied is { } own) updated = SequenceFrames.WithProxy(frame, own);
else continue;
if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH
&& updated.Format == frame.Format)
continue;
gained |= (updated.Flags & ~frame.Flags & FrameFlags.Undecodable) != 0;
frames[i] = updated;
changed.Add(updated);
}
if (changed.Count == 0) return m.Frames;
var inStep = await indexer.InStepAsync(archive, folder, m, cancellationToken).ConfigureAwait(false);
var manifest = m with
{
Frames = frames,
Status = gained ? m.Status | SequenceStatus.HasWarnings : m.Status,
UpdatedAt = DateTimeOffset.UtcNow,
};
ManifestStore.WriteSequence(folder.ManifestPath, manifest);
await using (var tx = await db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
// The row before its frames (SequenceRepository.GetForUpdateAsync): a scan holding the row would otherwise wait
// for these frames while this waits for the row, and PostgreSQL would abort one of them.
await tx.Sequences.RecordTiersAsync(sequence.Id, gained ? SequenceStatus.HasWarnings : SequenceStatus.None,
frames.Count(f => (f.Flags & FrameFlags.PreviewOnly) != 0), cancellationToken).ConfigureAwait(false);
await tx.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0, f.Format)), cancellationToken)
.ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (inStep) await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
return manifest.Frames;
}
}
/// <summary>
/// A frame stored as GPR whose file is not a .gpr: before owner review 1 every DNG with Make=GoPro counted as GPR, so
/// Adobe-converted GoPro DNGs were recorded preview-only; probing reads its signature again (<see cref="SequenceFrames.WithTier"/>
/// then stores the format found).
/// </summary>
internal static bool IsStaleGpr(SidecarFrame frame) =>
frame.Format == ImageFileFormat.Gpr && !frame.File.EndsWith(".gpr", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Whether this host decodes <paramref name="format"/> natively, so a file of it that yields no pixels is damaged
/// rather than beyond this host (JPEG always: the managed JPEG decoder is part of every host).
/// </summary>
private bool DecodesNatively(ImageFileFormat format) =>
format == ImageFileFormat.Jpeg || writer.Options.Decoder.TierFor(format) == DecodeTier.Native;
}