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),
};
}
@@ -0,0 +1,7 @@
-- Decode tiers (BRIEF §8.2): the size of each frame's largest embedded preview (before orientation, like width and
-- height), which caps the output of sequences whose frames decode only through it, and per sequence the number of
-- those preview-only frames for the Library chip. Mirrors sqlite/0005_decode_tiers.sql.
ALTER TABLE frames ADD COLUMN preview_width integer NOT NULL DEFAULT 0;
ALTER TABLE frames ADD COLUMN preview_height integer NOT NULL DEFAULT 0;
ALTER TABLE sequences ADD COLUMN preview_only_count integer NOT NULL DEFAULT 0;
@@ -0,0 +1,7 @@
-- Decode tiers (BRIEF §8.2): the size of each frame's largest embedded preview (before orientation, like width and
-- height), which caps the output of sequences whose frames decode only through it, and per sequence the number of
-- those preview-only frames for the Library chip. Mirrors postgres/0005_decode_tiers.sql.
ALTER TABLE frames ADD COLUMN preview_width INTEGER NOT NULL DEFAULT 0;
ALTER TABLE frames ADD COLUMN preview_height INTEGER NOT NULL DEFAULT 0;
ALTER TABLE sequences ADD COLUMN preview_only_count INTEGER NOT NULL DEFAULT 0;
@@ -6,6 +6,7 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Render;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
namespace Titano.Data.Processing.Jobs;
@@ -14,14 +15,15 @@ namespace Titano.Data.Processing.Jobs;
/// <see cref="JobKind.Render"/> on this machine (BRIEF §11.5): target = the sequence; parameters = Protocol
/// <c>RenderJobParameters</c> whose preset JSON is the export section of a project (preset, overrides, name template,
/// folder, batch). The project is the embedded one or the sequence's own; frames flagged missing, corrupt, excluded or
/// undecodable are left out. The preset and every batch preset render after one preparation pass into the sequence's
/// <c>exports/</c> (or the export folder, never on a server), named by the template without taking a name another render
/// of this process is writing, and each finished output is recorded at once (its row id derives from the job and the
/// entry, so every attempt knows what is recorded). Checkpoint: the entries recorded and the output being written, so a
/// crashed attempt's leftovers are removed and only unfinished entries render again. A failed entry fails the job after
/// the others ran; retrying renders it alone.
/// undecodable are left out, and a frame found undecodable while rendering is shown as its nearest neighbour, logged
/// and (when the originals were read) flagged so later renders leave it out (BRIEF §8.2). The preset and every batch
/// preset render after one preparation pass into the sequence's <c>exports/</c> (or the export folder, never on a
/// server), named by the template without taking a name another render of this process is writing, and each finished
/// output is recorded at once (its row id derives from the job and the entry, so every attempt knows what is recorded).
/// Checkpoint: the entries recorded and the output being written, so a crashed attempt's leftovers are removed and only
/// unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone.
/// </summary>
internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions options) : IJobHandler
internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions options, FrameTiers tiers) : IJobHandler
{
public JobKind Kind => JobKind.Render;
@@ -64,7 +66,7 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, cancellation).ConfigureAwait(false);
IReadOnlyList<TargetOutcome> outcomes;
await using (var render = new SequenceRender(frames, project, SequenceAnalyser.ReadReport(folder, frames.Count), options))
await using (var render = new SequenceRender(frames, project, SequenceAnalyser.ReadReport(folder, frames.Count), options, originals: !parameters.UseProxies))
{
outcomes = await render.RenderAllAsync(
targets,
@@ -87,6 +89,20 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
if (render.StandIns.Count > 0)
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", render.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
// Recorded without the job's token: what decoding found holds even if the job is cancelled meanwhile, and a
// sidecar that cannot be written now only leaves it to the next analysis or render.
try
{
var decoded = render.Decoded.ToDictionary(kv => frames.Frames[kv.Key].Id, kv => kv.Value);
await tiers.RecordAsync(archive, sequence, decoded, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException
or ArchiveOfflineException)
{
Core.Diagnostics.Log.Warning("processing", $"The decode tiers of {sequence.DisplayTitle} could not be recorded", ex);
}
}
var failed = outcomes.Where(o => o.Error is not null).ToList();
foreach (var outcome in failed) context.Log(Loc.L("Export.Log.Failed", outcome.Target.PresetName, outcome.Error));
@@ -17,6 +17,7 @@ public sealed class ProcessingService : IJobHandlerProvider
{
private readonly TitanoDatabase _db;
private readonly SequenceAnalyser _analyser;
private readonly FrameTiers _tiers;
public ProcessingService(TitanoDatabase db, ProcessingOptions? options = null)
{
@@ -24,7 +25,9 @@ public sealed class ProcessingService : IJobHandlerProvider
Options = options ?? new ProcessingOptions();
// Sidecar and project writes coordinate with the archive engine through the archive's lease files.
var writer = new SequenceWriter(Options.Archive);
_analyser = new SequenceAnalyser(db, Options, writer, new ArchiveIndexer(db, writer), new ProjectStore(db, writer));
var indexer = new ArchiveIndexer(db, writer);
_tiers = new FrameTiers(db, writer, indexer);
_analyser = new SequenceAnalyser(db, Options, writer, indexer, new ProjectStore(db, writer));
}
public ProcessingOptions Options { get; }
@@ -32,7 +35,7 @@ public sealed class ProcessingService : IJobHandlerProvider
/// <summary>Handlers for <see cref="JobKind.LightAnalyse"/>, <see cref="JobKind.DeepAnalyse"/> and <see cref="JobKind.Render"/>.</summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers()
{
var render = new RenderJobHandler(_db, Options);
var render = new RenderJobHandler(_db, Options, _tiers);
return
[
new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
@@ -464,6 +464,8 @@ public sealed class RenderNodeClient : IAsyncDisposable
Height = f.Height,
Format = Enum.TryParse<ImageFileFormat>(f.Format, ignoreCase: true, out var format) ? format : default,
Flags = (FrameFlags)f.Flags,
PreviewWidth = f.PreviewWidth,
PreviewHeight = f.PreviewHeight,
};
/// <summary>
+60 -12
View File
@@ -4,6 +4,7 @@ using Titano.Core.Advice;
using Titano.Core.Analysis;
using Titano.Core.Analysis.Deep;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
@@ -20,13 +21,17 @@ internal sealed record AnalysisOutcome(Sequence Sequence, int Frames, int Warnin
/// <summary>
/// Light (BRIEF §10.1) and deep (§10.2) analysis of archived sequences, followed by the advisor (§10.3–10.4) filling the
/// Auto values of the project. The light pass reads the index only (plus one file for the GPS fix); the deep pass decodes
/// every frame, checkpointing into <c>.titano/analysis.partial</c> so a cancelled, paused or crashed run resumes, and
/// saves <c>analysis.json</c> atomically. Results land in the sidecar status, the index (status, warning count, compact
/// summary, per-frame light statistics) and <c>project.json</c>.
/// Auto values of the project. The light pass reads the index, probes the decode tier (§8.2) of frames whose tier is not
/// known yet (headers only, once per frame) and reads one file for the GPS fix; the deep pass decodes every frame,
/// checkpointing into <c>.titano/analysis.partial</c> so a cancelled, paused or crashed run resumes, records the tier
/// each frame decoded at (or that it did not decode) and saves <c>analysis.json</c> atomically. Results land in the
/// sidecar (status, tiers), the index (status, warning count, compact summary, tier flags, per-frame light statistics)
/// and <c>project.json</c>.
/// </summary>
internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions options, SequenceWriter writer, ArchiveIndexer indexer, ProjectStore projects)
{
private readonly FrameTiers _tiers = new(db, writer, indexer);
/// <summary>Analyses one sequence; null when it is no longer in the index.</summary>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
public async Task<AnalysisOutcome?> AnalyseAsync(Guid sequenceId, bool deep, IProgress<AnalysisProgress>? progress, CancellationToken cancellationToken)
@@ -37,12 +42,23 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, useProxies: false, cancellationToken).ConfigureAwait(false);
// Format tiers (BRIEF §10.1): frames indexed since the last analysis are probed with this host's decoders.
var probed = _tiers.ProbeUnknown(folder, ManifestStore.ReadSequence(folder.ManifestPath), cancellationToken);
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, probed, cancellationToken).ConfigureAwait(false));
var metadata = frames.LightFrames();
var light = LightAnalyzer.Analyze(metadata);
var report = deep
? await AnalyseDeepAsync(frames, metadata, folder, progress, cancellationToken).ConfigureAwait(false)
: ReadReport(folder, frames.Count);
DeepAnalysisReport? report;
if (deep)
{
(report, var observed) = await AnalyseDeepAsync(frames, metadata, folder, progress, cancellationToken).ConfigureAwait(false);
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, Decoded(frames, report, observed), cancellationToken).ConfigureAwait(false));
metadata = [.. metadata.Select((m, i) => m with { Flags = frames.Frames[i].Flags })];
}
else
{
report = ReadReport(folder, frames.Count);
}
var light = LightAnalyzer.Analyze(metadata);
var context = SequenceContext.FromFrames(frames.Frames, options.AdvisorCodecs);
bool changed, unreadable = false;
@@ -100,15 +116,47 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
}
}
private async Task<DeepAnalysisReport> AnalyseDeepAsync(SequenceFrames frames, IReadOnlyList<LightFrame> metadata, SequencePaths folder,
IProgress<AnalysisProgress>? progress, CancellationToken cancellationToken)
/// <summary>The frame rows with the tier fields of <paramref name="changed"/> sidecar frames.</summary>
private static SequenceFrames WithTiers(SequenceFrames frames, IReadOnlyList<SidecarFrame> changed)
{
if (changed.Count == 0) return frames;
var byId = changed.ToDictionary(f => f.Id);
var rows = frames.Frames.Select(f => byId.TryGetValue(f.Id, out var s)
? f with { Flags = s.Flags, PreviewWidth = s.PreviewW ?? 0, PreviewHeight = s.PreviewH ?? 0 }
: f).ToList();
return frames with { Frames = rows };
}
/// <summary>
/// What the deep pass learnt about each frame's tier: the tier this run decoded it at, else (for frames analysed by
/// an interrupted earlier run) unavailable when the report says it did not decode. Missing and corrupt frames are not
/// decoded at all, so they say nothing.
/// </summary>
private static Dictionary<Guid, FileTier> Decoded(SequenceFrames frames, DeepAnalysisReport report, IReadOnlyDictionary<int, FileTier> observed)
{
var tiers = new Dictionary<Guid, FileTier>();
foreach (var (index, tier) in observed) tiers[frames.Frames[index].Id] = tier;
foreach (var index in report.Issues.Undecodable)
{
if (index >= frames.Count || observed.ContainsKey(index) || frames.Files[index] is null
|| (frames.Frames[index].Flags & SequenceFrames.NotAnalysed) != 0) continue;
var frame = frames.Frames[index];
tiers[frame.Id] = new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0);
}
return tiers;
}
private async Task<(DeepAnalysisReport Report, IReadOnlyDictionary<int, FileTier> Observed)> AnalyseDeepAsync(SequenceFrames frames,
IReadOnlyList<LightFrame> metadata, SequencePaths folder, IProgress<AnalysisProgress>? progress, CancellationToken cancellationToken)
{
var file = new DeepAnalysisCheckpointFile(Path.Combine(folder.MetaDirectory, DeepAnalysisCheckpointFile.FileName));
DeepAnalysisReport report;
await using (var source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder))
IReadOnlyDictionary<int, FileTier> observed;
await using (var source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder) { Originals = true })
{
report = await DeepAnalyzer.AnalyzeAsync(source, options.DeepAnalysis, new FramesCheckpoint(file, ContentKey(frames)), progress, cancellationToken)
.ConfigureAwait(false);
observed = source.Observed.ToDictionary();
}
report.Save(folder.AnalysisPath);
file.Delete();
@@ -118,7 +166,7 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
for (var i = 0; i < stats.Length; i++)
stats[i] = new FrameLightStats(frames.Frames[i].Id, columns.LogLuminance[i], columns.ClipLow[i], columns.ClipHigh[i]);
await db.Frames.UpdateLightStatsAsync(stats, cancellationToken).ConfigureAwait(false);
return report;
return (report, observed);
}
/// <summary>Identity of the analysed content: frames replaced or renumbered since a checkpoint was written (with the
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Globalization;
using Titano.Core.Advice;
using Titano.Core.Analysis;
@@ -10,9 +11,11 @@ namespace Titano.Data.Processing;
/// <summary>
/// The frames of a <see cref="SequenceFrames"/> decoded by the host's <see cref="ImageDecoder"/> (oriented, linear
/// light, embedded previews when nothing else decodes). For the deep analysis a frame that is missing, corrupt or
/// unreadable is null, as <see cref="IFrameSource"/> expects. Renders exclude flagged frames from the plan, so a
/// frame that still cannot be decoded stops the render with <see cref="FrameUnreadableKey"/>; render reads go through
/// a <see cref="FrameWindow"/> per decode size, which decodes ahead in index order and spills under memory pressure.
/// unreadable is null, as <see cref="IFrameSource"/> expects. Renders exclude flagged frames from the plan; a frame that
/// still cannot be decoded stops the render with <see cref="FrameUnreadableKey"/>, unless the render gave
/// <see cref="RenderExcluded"/>: then the nearest planned frame that decodes stands in for it (BRIEF §8.2 tier 3: one
/// unreadable frame never stops a render) and it is listed in <see cref="StandIns"/>. Render reads go through a
/// <see cref="FrameWindow"/> per decode size, which decodes ahead in index order and spills under memory pressure.
/// </summary>
internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IAsyncDisposable
{
@@ -27,6 +30,9 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
private readonly FrameWindowOptions _windowOptions;
private readonly Lazy<(int Width, int Height)> _size;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly ConcurrentDictionary<int, FileTier> _observed = new();
private readonly ConcurrentDictionary<int, byte> _standIns = new();
private readonly ConcurrentDictionary<int, byte> _failed = new();
private FrameWindow? _window;
private (int Edge, DecodePurpose Purpose) _windowKey;
@@ -40,6 +46,24 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
_size = new Lazy<(int, int)>(MeasureSize);
}
/// <summary>The files are the archive's originals, so what decoding finds describes the frames (<see cref="Observed"/>).</summary>
public bool Originals { get; init; }
/// <summary>
/// Positions the render plan leaves out. When set, a render frame that does not decode is replaced by the nearest
/// planned frame that does, instead of failing the render.
/// </summary>
public IReadOnlySet<int>? RenderExcluded { get; init; }
/// <summary>
/// Decode tier each frame decoded at, or <see cref="DecodeTier.Unavailable"/> when nothing decoded its file (sizes
/// oriented, as <see cref="DecodedImage"/> reports them); recorded only for <see cref="Originals"/>.
/// </summary>
public IReadOnlyDictionary<int, FileTier> Observed => _observed;
/// <summary>Positions a render showed a neighbour for because they did not decode, ascending.</summary>
public IReadOnlyList<int> StandIns => [.. _standIns.Keys.Order()];
public int Count => _frames.Count;
public int FrameCount => _frames.Count;
@@ -92,35 +116,77 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
}
}
private ImageBuffer DecodeForRender(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) =>
Decode(index, maxLongEdge, purpose, cancellationToken)?.Pixels ?? throw Unreadable(index);
private ImageBuffer DecodeForRender(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if (Decode(index, maxLongEdge, purpose, cancellationToken) is { } decoded) return decoded.Pixels;
// A frame the plan leaves out is reached only by the window's read-ahead, which never hands it to the pipeline.
if (RenderExcluded is not { } excluded || excluded.Contains(index)) throw Unreadable(index);
// Flagged frames never get here, so this one became unreadable after it was last analysed (or is beyond this host's
// decoders): the nearest planned frame stands in, earlier first, and the render job records what decoding found.
_failed.TryAdd(index, 0);
for (var distance = 1; distance < Count; distance++)
{
ReadOnlySpan<int> neighbours = [index - distance, index + distance];
foreach (var neighbour in neighbours)
{
if (neighbour < 0 || neighbour >= Count || excluded.Contains(neighbour) || _failed.ContainsKey(neighbour)) continue;
if (Decode(neighbour, maxLongEdge, purpose, cancellationToken) is not { } standIn)
{
_failed.TryAdd(neighbour, 0);
continue;
}
_standIns.TryAdd(index, 0);
Core.Diagnostics.Log.Warning("processing", $"Frame {index + 1} ({_frames.Frames[index].FileName}) does not decode; frame {neighbour + 1} stands in");
return standIn.Pixels;
}
}
throw Unreadable(index);
}
private DecodedImage? Decode(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if (_frames.Files[index] is not { } file) return null;
DecodedImage? decoded;
try
{
return _decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose), cancellationToken);
decoded = _decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose), cancellationToken);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("processing", $"Frame {file} could not be read", ex);
return null;
}
// A file that vanished is missing, not undecodable (a verify flags it); only what decoding found is recorded.
if (Originals && (decoded is not null || File.Exists(file)))
{
var format = _frames.Frames[index].Format;
_observed[index] = decoded is null
? new FileTier(format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0)
: new FileTier(format, decoded.Tier, decoded.Decoder, null, decoded.SourceWidth, decoded.SourceHeight);
}
return decoded;
}
/// <summary>The dominant oriented size from the metadata, else the size the first renderable frame decodes to.</summary>
/// <summary>
/// The dominant oriented size from the metadata, else the size the first renderable frame decodes to (frames that do
/// not decode are passed over while a render may stand in for them).
/// </summary>
private (int, int) MeasureSize()
{
var context = SequenceContext.FromFrames(_frames.Frames);
if (context.SourceWidth > 0 && context.SourceHeight > 0) return (context.SourceWidth, context.SourceHeight);
var skipped = _frames.NotRenderable().ToHashSet();
if (RenderExcluded is { } excluded) skipped.UnionWith(excluded);
int? first = null;
for (var i = 0; i < Count; i++)
{
if (skipped.Contains(i)) continue;
using var probe = Decode(i, ProbeLongEdge, DecodePurpose.Thumbnail, CancellationToken.None) ?? throw Unreadable(i);
return (probe.SourceWidth, probe.SourceHeight);
using var probe = Decode(i, ProbeLongEdge, DecodePurpose.Thumbnail, CancellationToken.None);
if (probe is not null) return (probe.SourceWidth, probe.SourceHeight);
first ??= i;
if (RenderExcluded is null) break;
}
if (first is { } unreadable) throw Unreadable(unreadable);
throw new RenderException("Export.Render.NoFrames", "Every frame is excluded.");
}
+17 -3
View File
@@ -1,6 +1,7 @@
using Titano.Core.Analysis;
using Titano.Core.Analysis.Deep;
using Titano.Core.Export;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
@@ -30,23 +31,36 @@ internal sealed class SequenceRender : IAsyncDisposable
private readonly RenderOptions _options;
/// <param name="analysis">The sequence's deep report, when current: its luminance spares the preparation a decode pass.</param>
public SequenceRender(SequenceFrames frames, ProjectSettings project, DeepAnalysisReport? analysis, ProcessingOptions options)
/// <param name="originals">The frames' files are the archive's originals (no proxies), so <see cref="Decoded"/> describes them.</param>
public SequenceRender(SequenceFrames frames, ProjectSettings project, DeepAnalysisReport? analysis, ProcessingOptions options, bool originals = false)
{
var metadata = frames.LightFrames();
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow);
var planned = project with { ExcludedFrames = [.. project.ExcludedFrames.Union(frames.NotRenderable()).Order()] };
// A frame that turns out not to decode is shown as its nearest planned neighbour instead of failing the render.
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow)
{
Originals = originals,
RenderExcluded = planned.ExcludedFrames.ToHashSet(),
};
_processing = options;
_options = options.Render;
Input = new RenderInput
{
Source = _source,
Frames = SourceFrameInfo.From(frames.Frames, LightAnalyzer.Analyze(metadata).AdjustedTimes),
Project = project with { ExcludedFrames = [.. project.ExcludedFrames.Union(frames.NotRenderable()).Order()] },
Project = planned,
Analysis = analysis?.FrameCount == frames.Count ? new PrecomputedAnalysis { LogLuminance = Luminance(analysis.Frames) } : null,
};
}
public RenderInput Input { get; }
/// <summary>Positions that did not decode during the render; a neighbour stood in for each (ascending).</summary>
public IReadOnlyList<int> StandIns => _source.StandIns;
/// <summary>The decode tier each frame was read at so far (unavailable when it did not decode); originals only.</summary>
public IReadOnlyDictionary<int, FileTier> Decoded => _source.Observed;
/// <summary>Encoder, geometry and plan of an export before its output is named.</summary>
public RenderSetup Setup(ResolvedExport export) => Pipeline(export).Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
@@ -16,6 +16,9 @@ public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId
/// <summary>Light statistics of one frame, written by the analysis job.</summary>
public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh);
/// <summary>Decode-tier fields of one frame (BRIEF §8.2): its flags and the stored size of its largest embedded preview.</summary>
public readonly record struct FrameTierFields(Guid FrameId, FrameFlags Flags, int PreviewWidth, int PreviewHeight);
/// <summary>Per-format totals and flagged-frame counts of one sequence.</summary>
public sealed record SequenceFrameStats(IReadOnlyList<FormatBucket> ByFormat, long Missing, long Corrupt, long Duplicate, long Excluded);
@@ -27,7 +30,7 @@ public sealed class FrameRepository
"id", "sequence_id", "idx", "relative_path", "file_name", "original_file_name", "size", "sha256", "captured_at",
"utc_offset_minutes", "timestamp_source", "exposure_time", "f_number", "iso", "focal_length", "exposure_bias",
"white_balance", "orientation", "width", "height", "format", "preview_offset", "preview_length",
"mean_log_luminance", "clip_low", "clip_high", "flags",
"mean_log_luminance", "clip_low", "clip_high", "flags", "preview_width", "preview_height",
];
private static readonly string Columns = string.Join(", ", ColumnNames);
@@ -37,7 +40,7 @@ public sealed class FrameRepository
/// <summary>Rows per statement of the batched PostgreSQL updates (4 or fewer parameters per row).</summary>
private const int Batch = 1000;
/// <summary>Rows per multi-row upsert: 30 x 27 parameters stays below SQLite's historical 999-variable limit.</summary>
/// <summary>Rows per multi-row upsert: 30 x 29 parameters stays below SQLite's historical 999-variable limit.</summary>
private const int UpsertRows = 30;
/// <summary>Light statistics belong to the analysis job; a sync from the sidecar never clears them.</summary>
@@ -130,6 +133,19 @@ public sealed class FrameRepository
return updated;
}, cancellationToken);
/// <summary>Writes the decode-tier fields of many frames in one transaction; returns the number of frames updated.</summary>
public Task<int> UpdateTiersAsync(IReadOnlyList<FrameTierFields> frames, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
var updated = 0;
foreach (var f in frames)
{
updated += await session.ExecuteAsync("UPDATE frames SET flags = $2, preview_width = $3, preview_height = $4 WHERE id = $1",
[f.FrameId, (int)f.Flags, f.PreviewWidth, f.PreviewHeight], cancellationToken).ConfigureAwait(false);
}
return updated;
}, cancellationToken);
/// <summary>
/// Makes the frames of a sequence exactly <paramref name="frames"/> (from its sidecar): rows are upserted by id,
/// rows not listed are deleted, light statistics of kept rows survive. Indexes may be renumbered freely.
@@ -239,7 +255,7 @@ public sealed class FrameRepository
f.Id, f.SequenceId, f.Index, f.RelativePath, f.FileName, f.OriginalFileName, f.Size, f.Sha256?.ToLowerInvariant(),
SequenceRepository.Wall(f.CapturedAt), f.UtcOffsetMinutes, (int)f.TimestampSource, f.ExposureTime, f.FNumber, f.Iso,
f.FocalLength, f.ExposureBias, f.WhiteBalance, f.Orientation, f.Width, f.Height, (int)f.Format, f.PreviewOffset,
f.PreviewLength, f.MeanLogLuminance, f.ClipLow, f.ClipHigh, (int)f.Flags,
f.PreviewLength, f.MeanLogLuminance, f.ClipLow, f.ClipHigh, (int)f.Flags, f.PreviewWidth, f.PreviewHeight,
];
private static Frame Map(DbRow r) => new()
@@ -271,5 +287,7 @@ public sealed class FrameRepository
ClipLow = r.GetDoubleOrNull(24),
ClipHigh = r.GetDoubleOrNull(25),
Flags = (FrameFlags)r.GetInt32(26),
PreviewWidth = r.GetInt32(27),
PreviewHeight = r.GetInt32(28),
};
}
@@ -122,7 +122,8 @@ public sealed class SequenceRepository
private const string Columns =
"s.id, s.archive_id, s.title, s.folder, s.camera_make, s.camera_model, s.camera_serial, s.lens, s.first_capture, s.last_capture, " +
"s.frame_count, s.median_interval, s.total_bytes, s.status, s.rendered_count, s.verified_at, s.hero_frame_id, s.rating, s.notes, " +
"s.settings_json, s.analysis_json, s.origin, s.sync_state, s.settings_version, s.frames_version, s.owner_user_id, s.warning_count, s.updated_at";
"s.settings_json, s.analysis_json, s.origin, s.sync_state, s.settings_version, s.frames_version, s.owner_user_id, s.warning_count, s.updated_at, " +
"s.preview_only_count";
/// <summary>rendered_count is owned by <see cref="RenderRepository"/> once the row exists.</summary>
private static readonly string UpsertSql = SqlDialect.Upsert("sequences",
@@ -130,12 +131,12 @@ public sealed class SequenceRepository
"id", "archive_id", "title", "title_key", "search_text", "folder", "camera_make", "camera_model", "camera_serial", "lens",
"first_capture", "last_capture", "frame_count", "median_interval", "total_bytes", "status", "rendered_count", "verified_at",
"hero_frame_id", "rating", "notes", "settings_json", "analysis_json", "origin", "sync_state", "settings_version",
"frames_version", "owner_user_id", "warning_count", "updated_at",
"frames_version", "owner_user_id", "warning_count", "updated_at", "preview_only_count",
], 1, ["rendered_count"]);
/// <summary>Ordinal of the tag list after <see cref="Columns"/>, and of the sort key a listing appends after it.</summary>
private const int TagsOrdinal = 28;
private const int SortKeyOrdinal = 29;
private const int TagsOrdinal = 29;
private const int SortKeyOrdinal = 30;
private readonly DbAccess _db;
private readonly string _select;
@@ -445,7 +446,7 @@ public sealed class SequenceRepository
s.Id, s.ArchiveId, s.Title, s.DisplayTitle.ToLowerInvariant(), search, s.Folder, s.CameraMake, s.CameraModel, s.CameraSerial, s.Lens,
Wall(s.FirstCapture), Wall(s.LastCapture), s.FrameCount, s.MedianInterval, s.TotalBytes, (int)s.Status, s.RenderedCount, s.VerifiedAt,
s.HeroFrameId, s.Rating, s.Notes, DbParam.Json(s.SettingsJson), DbParam.Json(s.AnalysisJson), (int)s.Origin, (int)s.SyncState,
s.SettingsVersion, s.FramesVersion, s.OwnerUserId, s.WarningCount, s.UpdatedAt,
s.SettingsVersion, s.FramesVersion, s.OwnerUserId, s.WarningCount, s.UpdatedAt, s.PreviewOnlyCount,
], cancellationToken);
}
@@ -523,6 +524,7 @@ public sealed class SequenceRepository
OwnerUserId = r.GetGuidOrNull(25),
WarningCount = r.GetInt32(26),
UpdatedAt = r.GetDateTimeOffset(27),
PreviewOnlyCount = r.GetInt32(28),
Tags = tags,
};
}