fix(imaging): record decode tiers per frame and keep undecodable frames out of renders

BRIEF §8.2 tiers 2 and 3 had no writer: PreviewOnly and Undecodable were never set,
so the advisor could not cap the output at the preview size and one unreadable frame
failed a whole render.

- ImageDecoder.Probe names a file's tier without decoding it (JPEG, PNG and TIFF
  without opening the file); the light analysis probes frames whose tier is unknown,
  and the deep analysis, renders from originals and thumbnail/proxy passes record
  what decoding actually found (FrameTiers). Sidecar frames gain "tier", "previewW"
  and "previewH"; the index gains frames.preview_width/height and
  sequences.preview_only_count (migration 0005, SQLite and PostgreSQL).
- SequenceContext takes the preview size from preview-only frames, so the advisor's
  output cap applies; the light analysis reports format tiers (preview-only frames as
  information, undecodable ones as a warning under the deep analysis' key, listed
  once); a sequence that gains undecodable frames warns at once.
- Only a file in a format the host decodes natively is flagged undecodable; files
  beyond the host's decoders keep their tier without the flag, so render nodes and
  proxies can still supply them.
- A frame that stops decoding during a render is replaced by its nearest planned
  neighbour and logged instead of failing the job; the render fails only when no
  planned frame decodes.
- The Library card shows a preview-only chip with the count (local and server
  sequences: SequenceDto.PreviewOnlyCount, FrameDto preview size).
- GoPro GPR decodes through the JPEG the camera writes beside it when that is larger
  than the embedded preview (BRIEF §8.1).
- Thumbnails use a stored embedded preview only when it reaches 320 px; a smaller one
  sends the frame through the host's decoders instead (BRIEF §8.5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 09:58:36 +00:00
1 parent 61d913baa9
commit 4d321a84b0
48 files changed
+1132 -87

No files matched your search

+49 -7
View File
@@ -1,5 +1,6 @@
using System.Diagnostics;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.IO;
using Titano.Core.Metadata;
using Titano.Core.Model;
@@ -12,7 +13,8 @@ public sealed record ImagePassResult(int Built, int Reused, int Undecodable);
/// <summary>
/// Thumbnails (<c>thumbs.pack</c>) and proxies (<c>proxies/0001.jpg</c>) of sequences (BRIEF §8.5). Both are
/// regenerable and self-validating: a thumbnail carries its source fingerprint, a proxy its capture time, so after
/// frames were renumbered the stale ones are rebuilt and the rest reused.
/// frames were renumbered the stale ones are rebuilt and the rest reused. A frame nothing decodes is flagged undecodable
/// (BRIEF §8.2 tier 3); one flagged so that decodes after all gets its tier probed again.
/// </summary>
public sealed class ArchiveImages
{
@@ -23,6 +25,7 @@ public sealed class ArchiveImages
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
private readonly FrameImageRenderer _renderer;
private readonly FrameTiers _tiers;
internal ArchiveImages(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
{
@@ -30,6 +33,7 @@ public sealed class ArchiveImages
_writer = writer;
_indexer = indexer;
_renderer = new FrameImageRenderer(writer.Options.Decoder);
_tiers = new FrameTiers(db, writer, indexer);
}
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run).</param>
@@ -42,6 +46,7 @@ public sealed class ArchiveImages
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
int built = 0, reused = 0, undecodable = 0;
var tiers = new Dictionary<Guid, FileTier>();
// Thumbnail writers exclude each other only; ingest keeps committing meanwhile.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
@@ -58,7 +63,7 @@ public sealed class ArchiveImages
reused++;
continue;
}
if (Render(() => _renderer.Thumbnail(folder, frame, cancellationToken)) is { } image)
if (Render(folder, frame, tiers, () => _renderer.Thumbnail(folder, frame, cancellationToken)) is { } image)
{
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
built++;
@@ -75,6 +80,7 @@ public sealed class ArchiveImages
}
pack.Commit();
}
await _tiers.RecordAsync(archive, sequence, tiers, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ThumbsBuilt, undecodable == 0, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable);
}
@@ -91,6 +97,7 @@ public sealed class ArchiveImages
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Directory.CreateDirectory(folder.Proxies);
int built = 0, reused = 0, undecodable = 0;
var tiers = new Dictionary<Guid, FileTier>();
var cadence = new Cadence();
for (var i = startFrame; i < manifest.Frames.Count; i++)
{
@@ -102,7 +109,7 @@ public sealed class ArchiveImages
reused++;
continue;
}
if (Render(() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
if (Render(folder, frame, tiers, () => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
{
AtomicFile.WriteAllBytes(path, image.Jpeg);
built++;
@@ -113,6 +120,7 @@ public sealed class ArchiveImages
}
if (cadence.Due()) await checkpoint(i + 1, manifest.Frames.Count).ConfigureAwait(false);
}
await _tiers.RecordAsync(archive, sequence, tiers, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ProxiesBuilt, undecodable == 0, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable);
}
@@ -131,18 +139,52 @@ public sealed class ArchiveImages
}
}
/// <summary>A frame no decoder can read is skipped and counted; it never stops the pass.</summary>
private static EncodedImage? Render(Func<EncodedImage?> render)
/// <summary>
/// A frame no decoder can read is skipped and counted; it never stops the pass. What decoding found goes into
/// <paramref name="tiers"/>: unavailable when nothing decoded a file that is there (a read error proves nothing), and
/// the probed tier when a frame flagged undecodable decoded after all.
/// </summary>
private EncodedImage? Render(SequencePaths folder, SidecarFrame frame, Dictionary<Guid, FileTier> tiers, Func<EncodedImage?> render)
{
var path = folder.File(frame.File);
EncodedImage? image;
try
{
return render();
image = render();
}
catch (Exception ex) when (ex is IOException or InvalidDataException or NotSupportedException)
catch (IOException ex)
{
Core.Diagnostics.Log.Warning("archive", "Frame image could not be rendered", ex);
return null;
}
catch (Exception ex) when (ex is InvalidDataException or NotSupportedException)
{
Core.Diagnostics.Log.Warning("archive", "Frame image could not be rendered", ex);
image = null;
}
if (image is null)
{
if (File.Exists(path)) tiers[frame.Id] = new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0);
}
else if ((frame.Flags & FrameFlags.Undecodable) != 0)
{
tiers[frame.Id] = Reprobe(path, frame, image.Tier);
}
return image;
}
/// <summary>The tier of a frame that decoded after it was flagged undecodable (the image's own tier when probing finds none).</summary>
private FileTier Reprobe(string path, SidecarFrame frame, DecodeTier decoded)
{
try
{
if (_writer.Options.Decoder.Probe(path, frame.Format) is { Tier: not DecodeTier.Unavailable } tier) return tier;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("archive", $"{path} could not be probed", ex);
}
return new FileTier(frame.Format, decoded, null, null, 0, 0);
}
/// <summary>Commit/checkpoint rhythm: every <see cref="CommitFrames"/> rendered frames or <see cref="CommitInterval"/>.</summary>
+98
View File
@@ -0,0 +1,98 @@
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.
/// </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, probed with the host's decoders
/// without decoding pixels; missing and unreadable files are left for later.
/// </summary>
public Dictionary<Guid, FileTier> ProbeUnknown(SequencePaths folder, SequenceManifest manifest, CancellationToken cancellationToken)
{
var tiers = new Dictionary<Guid, FileTier>();
foreach (var frame in manifest.Frames)
{
if (frame.Tier != 0 || (frame.Flags & FrameFlags.Missing) != 0) continue;
cancellationToken.ThrowIfCancellationRequested();
var path = folder.File(frame.File);
try
{
var tier = writer.Options.Decoder.Probe(path, frame.Format);
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 frames that
/// changed as they are now. Frames no longer in the sequence are ignored.
/// </summary>
/// <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,
CancellationToken cancellationToken)
{
if (tiers.Count == 0) return [];
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var changed = new List<SidecarFrame>();
var manifest = await writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
{
changed.Clear();
var gained = false;
var frames = new SidecarFrame[m.Frames.Count];
for (var i = 0; i < frames.Length; i++)
{
var frame = m.Frames[i];
frames[i] = frame;
if (!tiers.TryGetValue(frame.Id, out var tier)) continue;
var updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format));
if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH)
continue;
gained |= (updated.Flags & ~frame.Flags & FrameFlags.Undecodable) != 0;
frames[i] = updated;
changed.Add(updated);
}
if (changed.Count == 0) return null;
return m with
{
Frames = frames,
Status = gained ? m.Status | SequenceStatus.HasWarnings : m.Status,
UpdatedAt = DateTimeOffset.UtcNow,
};
}, cancellationToken).ConfigureAwait(false);
if (changed.Count == 0) return [];
await db.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0)), cancellationToken)
.ConfigureAwait(false);
var folder = paths.Sequence(sequence.Folder);
if (await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is { } existing)
await db.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, folder, existing), cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
return changed;
}
/// <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;
}
@@ -32,6 +32,8 @@ internal static class SequenceMapping
Format = f.Format,
PreviewOffset = f.PreviewOffset,
PreviewLength = f.PreviewLength,
PreviewWidth = f.PreviewW ?? 0,
PreviewHeight = f.PreviewH ?? 0,
Flags = f.Flags,
};
@@ -76,6 +78,7 @@ internal static class SequenceMapping
SyncState = existing?.SyncState ?? SyncState.LocalOnly,
OwnerUserId = existing?.OwnerUserId ?? (Guid.TryParse(m.CreatedBy, out var owner) ? owner : null),
WarningCount = existing?.WarningCount ?? 0,
PreviewOnlyCount = m.Frames.Count(f => (f.Flags & FrameFlags.PreviewOnly) != 0),
};
}