Merge branch 'fix/imaging-metadata': decode tiers, preview-only and undecodable frames, GPR companions, MakerNote fields

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 11:46:58 +00:00
commit 348d580d4d
70 files changed
+2201 -124

No files matched your search

+57 -8
View File
@@ -35,7 +35,8 @@ public enum ProxyStoreResult
/// 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. A frame whose original this host cannot
/// decode (<see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/>) gets its proxy from a client or render node that can
/// (<see cref="StoreProxy"/>, BRIEF §2.3) and its thumbnail from that proxy.
/// (<see cref="StoreProxy"/>, BRIEF §2.3) and its thumbnail from that proxy. 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
{
@@ -51,6 +52,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)
{
@@ -58,6 +60,7 @@ public sealed class ArchiveImages
_writer = writer;
_indexer = indexer;
_renderer = new FrameImageRenderer(writer.Options.Decoder);
_tiers = new FrameTiers(db, writer, indexer);
}
/// <summary>
@@ -156,6 +159,8 @@ 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>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
// 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))
@@ -181,8 +186,12 @@ public sealed class ArchiveImages
reused++;
continue;
}
var source = fromProxy ? ProxySource(frame) : frame;
if (Render(() => _renderer.Thumbnail(folder, source, policy, cancellationToken)) is { } image)
var companion = companions.GetValueOrDefault(frame.Id);
// A thumbnail drawn from the proxy says nothing about how this host decodes the original.
var image = fromProxy
? Render(folder, frame, null, null, () => _renderer.Thumbnail(folder, ProxySource(frame), policy, cancellationToken))
: Render(folder, frame, companion, tiers, () => _renderer.Thumbnail(folder, frame, policy, cancellationToken, companion));
if (image is not null)
{
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
built++;
@@ -199,6 +208,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);
}
@@ -215,6 +225,8 @@ 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 companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
var cadence = new Cadence();
for (var i = startFrame; i < manifest.Frames.Count; i++)
{
@@ -243,7 +255,8 @@ public sealed class ArchiveImages
reused++;
continue;
}
else if (Render(() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken)) is { } image)
else if (Render(folder, frame, companions.GetValueOrDefault(frame.Id), tiers,
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken, companions.GetValueOrDefault(frame.Id))) is { } image)
{
AtomicFile.WriteAllBytes(path, image.Jpeg);
built++;
@@ -254,6 +267,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);
}
@@ -330,18 +344,53 @@ 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"/> (when given): 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, string? companion, 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 (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
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 (tiers is null) return image;
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, companion, 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, string? companion, DecodeTier decoded)
{
try
{
if (_writer.Options.Decoder.Probe(path, frame.Format, companion) 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>
+105
View File
@@ -0,0 +1,105 @@
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, 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,
/// 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)
|| (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 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;
}
@@ -0,0 +1,63 @@
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.Model;
namespace Titano.Data.Archiving;
/// <summary>A GPR's JPEG: its absolute path and its size as the index has it (before orientation).</summary>
internal readonly record struct GprCompanion(string Path, int Width, int Height);
/// <summary>
/// The JPEG a GoPro writes with each GPR, the server's pixel source for GPR (BRIEF §8.1; VC-5 is out of scope). In a
/// folder adopted in place it sits beside the GPR, where the decoder finds it itself. A card import or an upload splits
/// sessions per file format (DECISIONS 2026-10-02), so there it is a frame of another sequence: the archive's JPEG frame
/// whose original name has the GPR's stem and whose capture time is the GPR's (within a second). Looked up in the index
/// when frames are decoded, so renaming or moving either sequence never breaks the pair.
/// </summary>
public static class GprCompanions
{
private static readonly TimeSpan Tolerance = TimeSpan.FromSeconds(1);
/// <summary>
/// The absolute path of the JPEG of each GPR frame of <paramref name="frames"/> (index rows), by frame id; frames
/// without one are left out. One index query, none when no frame is a GPR.
/// </summary>
public static async Task<IReadOnlyDictionary<Guid, string>> FindAsync(TitanoDatabase db, Archive archive, IReadOnlyList<Frame> frames,
CancellationToken cancellationToken) =>
Paths(await FindAsync(db, archive, [.. frames.Where(f => f.Format == ImageFileFormat.Gpr).Select(f => (f.Id, f.OriginalFileName ?? f.FileName, f.CapturedAt))],
cancellationToken).ConfigureAwait(false));
/// <inheritdoc cref="FindAsync(TitanoDatabase, Archive, IReadOnlyList{Frame}, CancellationToken)"/>
public static async Task<IReadOnlyDictionary<Guid, string>> FindAsync(TitanoDatabase db, Archive archive, IReadOnlyList<SidecarFrame> frames,
CancellationToken cancellationToken) =>
Paths(await FindWithSizesAsync(db, archive, frames, cancellationToken).ConfigureAwait(false));
/// <summary>The JPEG of each GPR frame of <paramref name="frames"/> (sidecar frames) with its indexed size, by frame id.</summary>
internal static Task<Dictionary<Guid, GprCompanion>> FindWithSizesAsync(TitanoDatabase db, Archive archive, IReadOnlyList<SidecarFrame> frames,
CancellationToken cancellationToken) =>
FindAsync(db, archive, [.. frames.Where(f => f.Format == ImageFileFormat.Gpr).Select(f => (f.Id, f.Original ?? Path.GetFileName(f.File), f.CapturedAt))],
cancellationToken);
private static async Task<Dictionary<Guid, GprCompanion>> FindAsync(TitanoDatabase db, Archive archive,
List<(Guid Id, string Name, DateTime? CapturedAt)> gprs, CancellationToken cancellationToken)
{
var found = new Dictionary<Guid, GprCompanion>();
var timed = gprs.Where(g => g.CapturedAt is not null).Select(g => (g.Id, Stem: Stem(g.Name), At: g.CapturedAt!.Value)).ToList();
if (timed.Count == 0) return found;
var jpegs = await db.Frames.ListByCaptureRangeAsync(archive.Id, ImageFileFormat.Jpeg, timed.Min(g => g.At) - Tolerance,
timed.Max(g => g.At) + Tolerance, cancellationToken).ConfigureAwait(false);
var byStem = jpegs.Where(j => (j.Flags & FrameFlags.Missing) == 0 && j.CapturedAt is not null)
.ToLookup(j => Stem(j.OriginalFileName ?? j.FileName), StringComparer.OrdinalIgnoreCase);
var paths = new ArchivePaths(archive.RootPath);
foreach (var (id, stem, at) in timed)
{
var match = byStem[stem].Where(j => (j.CapturedAt!.Value - at).Duration() <= Tolerance).MinBy(j => (j.CapturedAt!.Value - at).Duration());
if (match is not null) found[id] = new GprCompanion(paths.FromRelative(match.RelativePath), match.Width, match.Height);
}
return found;
}
private static Dictionary<Guid, string> Paths(Dictionary<Guid, GprCompanion> companions) => companions.ToDictionary(kv => kv.Key, kv => kv.Value.Path);
private static string Stem(string fileName) => Path.GetFileNameWithoutExtension(fileName);
}
@@ -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),
};
}