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; /// Frames processed by one thumbnail or proxy pass over a sequence. public sealed record ImagePassResult(int Built, int Reused, int Undecodable); /// /// Thumbnails (thumbs.pack) and proxies (proxies/0001.jpg) 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. /// 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); } /// Resume point inside the sequence (frames before it were done by an earlier run). /// Called with the next frame index whenever the pack has been committed. public async Task BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame, Func 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(); 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); } /// public async Task BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame, Func 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(); 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); } /// A proxy is current when its Exif capture time is the frame's (frames renumbered since make it stale). 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; } } /// /// A frame no decoder can read is skipped and counted; it never stops the pass. What decoding found goes into /// : 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. /// private EncodedImage? Render(SequencePaths folder, SidecarFrame frame, string? companion, Dictionary tiers, Func 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; } /// The tier of a frame that decoded after it was flagged undecodable (the image's own tier when probing finds none). 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); } /// Commit/checkpoint rhythm: every rendered frames or . 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); } }