- Preview sizes come from probes and unscaled decodes: a size-limited decode picks the smallest preview that reaches its edge (CR3 PRVW 1620x1080), so renders and deep passes record its tier without a size and the output cap keeps the largest preview's. - A read error is not an undecodable file: ImageDecoder.Decode throws the IOException when a provider could not read the file and none produced pixels. Deep passes never flag frames they could not read or that vanished, and frames only an interrupted earlier run found undecodable are decoded again before they are flagged. - Renders resolve stand-ins only for frames the pipeline asks for; frames the read-ahead meets on the way (skipped by speed-ups) are left alone. - A GoPro GPR finds its JPEG in the index when an import or upload kept it in a sequence of its own (same original stem and capture time), for probes, deep analysis, renders, thumbnails, proxies and the editor; GPRs whose JPEG is indexed later are probed again. - Thumbnails judge an embedded preview by its own JPEG header. - PostgreSQL writes tier fields 1000 frames per statement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
221 lines
10 KiB
C#
221 lines
10 KiB
C#
using System.Diagnostics;
|
|
using Titano.Core.Archiving;
|
|
using Titano.Core.Imaging;
|
|
using Titano.Core.IO;
|
|
using Titano.Core.Metadata;
|
|
using Titano.Core.Model;
|
|
|
|
namespace Titano.Data.Archiving;
|
|
|
|
/// <summary>Frames processed by one thumbnail or proxy pass over a sequence.</summary>
|
|
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. 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
|
|
{
|
|
private const int CommitFrames = 200;
|
|
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
|
|
|
|
private readonly TitanoDatabase _db;
|
|
private readonly SequenceWriter _writer;
|
|
private readonly ArchiveIndexer _indexer;
|
|
private readonly FrameImageRenderer _renderer;
|
|
private readonly FrameTiers _tiers;
|
|
|
|
internal ArchiveImages(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
|
{
|
|
_db = db;
|
|
_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>
|
|
/// <param name="checkpoint">Called with the next frame index whenever the pack has been committed.</param>
|
|
public async Task<ImagePassResult> BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
|
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
|
{
|
|
var paths = new ArchivePaths(archive.RootPath);
|
|
ArchiveVolume.EnsureWritable(paths);
|
|
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))
|
|
using (var pack = ThumbPackWriter.Open(folder.ThumbsPackPath))
|
|
{
|
|
var cadence = new Cadence();
|
|
for (var i = startFrame; i < manifest.Frames.Count; i++)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
var frame = manifest.Frames[i];
|
|
var fingerprint = ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size);
|
|
if (!force && pack.Entries.TryGetValue(frame.I, out var entry) && entry.SourceHash.AsSpan().SequenceEqual(fingerprint))
|
|
{
|
|
reused++;
|
|
continue;
|
|
}
|
|
var companion = companions.GetValueOrDefault(frame.Id);
|
|
if (Render(folder, frame, companion, tiers, () => _renderer.Thumbnail(folder, frame, cancellationToken, companion)) is { } image)
|
|
{
|
|
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
|
|
built++;
|
|
}
|
|
else
|
|
{
|
|
undecodable++;
|
|
}
|
|
if (cadence.Due())
|
|
{
|
|
pack.Commit();
|
|
await checkpoint(i + 1, manifest.Frames.Count).ConfigureAwait(false);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
|
|
/// <inheritdoc cref="BuildThumbnailsAsync"/>
|
|
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
|
|
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
|
|
{
|
|
var paths = new ArchivePaths(archive.RootPath);
|
|
ArchiveVolume.EnsureWritable(paths);
|
|
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
|
|
if (policy.LongEdge == ProxyPolicy.Disabled) return new ImagePassResult(0, 0, 0);
|
|
var folder = paths.Sequence(sequence.Folder);
|
|
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++)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
var frame = manifest.Frames[i];
|
|
var path = folder.Proxy(frame.I);
|
|
if (!force && IsCurrent(path, frame))
|
|
{
|
|
reused++;
|
|
continue;
|
|
}
|
|
var companion = companions.GetValueOrDefault(frame.Id);
|
|
if (Render(folder, frame, companion, tiers, () => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken, companion)) is { } image)
|
|
{
|
|
AtomicFile.WriteAllBytes(path, image.Jpeg);
|
|
built++;
|
|
}
|
|
else
|
|
{
|
|
undecodable++;
|
|
}
|
|
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);
|
|
}
|
|
|
|
/// <summary>A proxy is current when its Exif capture time is the frame's (frames renumbered since make it stale).</summary>
|
|
private static bool IsCurrent(string proxy, SidecarFrame frame)
|
|
{
|
|
if (!File.Exists(proxy)) return false;
|
|
try
|
|
{
|
|
return MetadataReader.Read(proxy).CapturedAt == frame.CapturedAt && frame.CapturedAt is not null;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <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, string? companion, Dictionary<Guid, FileTier> tiers, Func<EncodedImage?> render)
|
|
{
|
|
var path = folder.File(frame.File);
|
|
EncodedImage? image;
|
|
try
|
|
{
|
|
image = render();
|
|
}
|
|
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 (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>
|
|
private sealed class Cadence
|
|
{
|
|
private readonly Stopwatch _clock = Stopwatch.StartNew();
|
|
private int _frames;
|
|
|
|
public bool Due()
|
|
{
|
|
if (++_frames < CommitFrames && _clock.Elapsed < CommitInterval) return false;
|
|
_frames = 0;
|
|
_clock.Restart();
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private async Task MarkAsync(Archive archive, ArchivePaths paths, Sequence sequence, SequenceStatus flag, bool complete, CancellationToken cancellationToken)
|
|
{
|
|
await _writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
|
|
{
|
|
var status = complete ? m.Status | flag : m.Status & ~flag;
|
|
return status == m.Status ? null : m with { Status = status, UpdatedAt = DateTimeOffset.UtcNow };
|
|
}, cancellationToken).ConfigureAwait(false);
|
|
await _db.Sequences.UpdateStatusAsync(sequence.Id, complete ? flag : SequenceStatus.None, complete ? SequenceStatus.None : flag, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
await _indexer.RecordStampsAsync(archive, paths.Sequence(sequence.Folder), sequence.Id, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|