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

@@ -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;
@@ -63,8 +65,10 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
if (targets.Count == 0) return;
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, options.Archive.Decoder, cancellation).ConfigureAwait(false);
var companions = await GprCompanions.FindAsync(db, archive, frames.Frames, 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,
companions))
{
outcomes = await render.RenderAllAsync(
targets,
@@ -87,6 +91,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),
@@ -565,6 +565,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>
+77 -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,20 @@ 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)
{
/// <summary>Long edge of the decode that confirms a frame an interrupted earlier run found undecodable.</summary>
private const int ConfirmLongEdge = 64;
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 +45,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, options.Archive.Decoder, cancellationToken).ConfigureAwait(false);
// Format tiers (BRIEF §10.1): frames indexed since the last analysis are probed with this host's decoders.
var probed = await _tiers.ProbeUnknownAsync(archive, folder, ManifestStore.ReadSequence(folder.ManifestPath), cancellationToken).ConfigureAwait(false);
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 decoded) = await AnalyseDeepAsync(archive, frames, metadata, folder, progress, cancellationToken).ConfigureAwait(false);
frames = WithTiers(frames, await _tiers.RecordAsync(archive, sequence, decoded, 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,18 +119,64 @@ 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, by frame id: the tier this run decoded it at. A frame this run
/// tried to read and recorded nothing for vanished or could not be read, which says nothing about its content. A frame
/// only an interrupted earlier run analysed and found undecodable is decoded again (small) to confirm it: that run's
/// failure may have been a read error too. Missing and corrupt frames are not decoded at all.
/// </summary>
private Dictionary<Guid, FileTier> Decoded(SequenceFrames frames, DeepAnalysisReport report, SequenceFrameSource source,
IReadOnlyDictionary<Guid, string> companions, CancellationToken cancellationToken)
{
var tiers = new Dictionary<Guid, FileTier>();
foreach (var (index, tier) in source.Observed) tiers[frames.Frames[index].Id] = tier;
var read = source.Read.ToHashSet();
foreach (var index in report.Issues.Undecodable)
{
if (index >= frames.Count || read.Contains(index) || frames.Files[index] is not { } path
|| (frames.Frames[index].Flags & SequenceFrames.NotAnalysed) != 0) continue;
var frame = frames.Frames[index];
try
{
using var decoded = options.Archive.Decoder.Decode(
new DecodeRequest(path, ConfirmLongEdge, DecodePurpose.Analysis, Companion: companions.GetValueOrDefault(frame.Id)), cancellationToken);
if (decoded is not null) tiers[frame.Id] = new FileTier(frame.Format, decoded.Tier, decoded.Decoder, null, 0, 0);
else if (File.Exists(path)) tiers[frame.Id] = new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("processing", $"Frame {path} could not be read", ex);
}
}
return tiers;
}
private async Task<(DeepAnalysisReport Report, Dictionary<Guid, FileTier> Decoded)> AnalyseDeepAsync(Archive archive, SequenceFrames frames,
IReadOnlyList<LightFrame> metadata, SequencePaths folder, IProgress<AnalysisProgress>? progress, CancellationToken cancellationToken)
{
var file = new DeepAnalysisCheckpointFile(Path.Combine(folder.MetaDirectory, DeepAnalysisCheckpointFile.FileName));
// The host's analysis parameters as they are now (Settings › Analysis on the desktop). Those that change per-frame
// results are part of the checkpoint's fingerprint, so a partial run made with other values starts again.
var analysis = options.Current.DeepAnalysis;
var companions = await GprCompanions.FindAsync(db, archive, frames.Frames, cancellationToken).ConfigureAwait(false);
DeepAnalysisReport report;
await using (var source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder))
Dictionary<Guid, FileTier> decoded;
await using (var source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder) { Originals = true, Companions = companions })
{
report = await DeepAnalyzer.AnalyzeAsync(source, analysis, new FramesCheckpoint(file, ContentKey(frames)), progress, cancellationToken)
.ConfigureAwait(false);
decoded = Decoded(frames, report, source, companions, cancellationToken);
}
report.Save(folder.AnalysisPath);
file.Delete();
@@ -121,7 +186,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, decoded);
}
/// <summary>Identity of the analysed content: frames replaced or renumbered since a checkpoint was written (with the
+130 -16
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Globalization;
using Titano.Core.Advice;
using Titano.Core.Analysis;
@@ -10,9 +11,12 @@ 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; only
/// frames the pipeline asks for get a stand-in, not those the read-ahead met on the way (a speed-up skips them).
/// </summary>
internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IAsyncDisposable
{
@@ -27,6 +31,10 @@ 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 readonly ConcurrentDictionary<int, byte> _read = new();
private FrameWindow? _window;
private (int Edge, DecodePurpose Purpose) _windowKey;
@@ -40,6 +48,37 @@ 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>
/// The JPEG a GoPro wrote with each GPR frame that is not beside it, by frame id (<see cref="DecodeRequest.Companion"/>).
/// </summary>
public IReadOnlyDictionary<Guid, string>? Companions { get; init; }
/// <summary>
/// Decode tier each frame decoded at, or <see cref="DecodeTier.Unavailable"/> when the decoders read its file and none
/// produced pixels; recorded only for <see cref="Originals"/>. Sizes are oriented and given only where they are the
/// full size the tier delivers: a size-limited decode of a preview picks the smallest one that reaches the limit, so
/// it reports none and the stored size of the largest preview stays.
/// </summary>
public IReadOnlyDictionary<int, FileTier> Observed => _observed;
/// <summary>
/// Positions whose file this source tried to decode, whatever came of it (a read error or a vanished file records no
/// tier in <see cref="Observed"/>).
/// </summary>
public IReadOnlyCollection<int> Read => [.. _read.Keys];
/// <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;
@@ -66,11 +105,11 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
{
if (_window is not null) await _window.DisposeAsync().ConfigureAwait(false);
_windowKey = (maxLongEdge, purpose);
_window = new FrameWindow(Count, (i, ct) => ValueTask.FromResult(DecodeForRender(i, maxLongEdge, purpose, ct)), _windowOptions);
_window = new FrameWindow(Count, (i, ct) => ValueTask.FromResult(Load(i, maxLongEdge, purpose, ct)), _windowOptions);
}
_window.MoveTo(index);
using var lease = await _window.GetAsync(index, cancellationToken).ConfigureAwait(false);
return lease.Image.Clone();
return await ReadAsync(_window, index, cancellationToken).ConfigureAwait(false)
?? await StandInAsync(_window, index, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -92,35 +131,107 @@ 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);
/// <summary>
/// The window's loader, for the pipeline's reads and the read-ahead alike: the decoded frame, else
/// <see cref="NotDecodedException"/>, remembered so the read-ahead does not decode the file again.
/// </summary>
private ImageBuffer Load(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if (!_failed.ContainsKey(index) && Decode(index, maxLongEdge, purpose, cancellationToken) is { } decoded) return decoded.Pixels;
_failed.TryAdd(index, 0);
throw new NotDecodedException();
}
private DecodedImage? Decode(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
/// <summary>A copy of the window's frame, or null when it does not decode.</summary>
private static async ValueTask<ImageBuffer?> ReadAsync(FrameWindow window, int index, CancellationToken cancellationToken)
{
if (_frames.Files[index] is not { } file) return null;
try
{
return _decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose), cancellationToken);
using var lease = await window.GetAsync(index, cancellationToken).ConfigureAwait(false);
return lease.Image.Clone();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
catch (NotDecodedException)
{
Core.Diagnostics.Log.Warning("processing", $"Frame {file} could not be read", ex);
return null;
}
}
/// <summary>The dominant oriented size from the metadata, else the size the first renderable frame decodes to.</summary>
/// <summary>
/// The pixels shown for a frame the pipeline asked for that does not decode. Flagged frames are not planned, so this
/// one became unreadable after it was last analysed (or is beyond this host's decoders): the nearest planned frame
/// that decodes stands in, earlier first, and the render job records what decoding found. Without
/// <see cref="RenderExcluded"/>, or when nothing decodes, the render stops.
/// </summary>
private async ValueTask<ImageBuffer> StandInAsync(FrameWindow window, int index, CancellationToken cancellationToken)
{
if (RenderExcluded is not { } excluded || excluded.Contains(index)) throw Unreadable(index);
for (var distance = 1; distance < Count; distance++)
{
for (var side = -1; side <= 1; side += 2)
{
var neighbour = index + side * distance;
if (neighbour < 0 || neighbour >= Count || excluded.Contains(neighbour) || _failed.ContainsKey(neighbour)) continue;
if (await ReadAsync(window, neighbour, cancellationToken).ConfigureAwait(false) is not { } standIn) 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;
}
}
throw Unreadable(index);
}
private DecodedImage? Decode(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if (_frames.Files[index] is not { } file) return null;
_read.TryAdd(index, 0);
var frame = _frames.Frames[index];
// A frame read from its proxy (an original this host cannot decode) says nothing about its original.
var proxied = _frames.Proxied is { } proxies && proxies[index];
DecodedImage? decoded;
try
{
var companion = proxied ? null : Companions?.GetValueOrDefault(frame.Id);
decoded = _decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose, Companion: companion), cancellationToken);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The file was not read (locked, vanished, a network read failed): that says nothing about its content.
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 && !proxied && (decoded is not null || File.Exists(file)))
{
_observed[index] = decoded switch
{
null => new FileTier(frame.Format, DecodeTier.Unavailable, null, "no decoder produced pixels", 0, 0),
{ Tier: DecodeTier.EmbeddedPreview } when maxLongEdge > 0 => new FileTier(frame.Format, decoded.Tier, decoded.Decoder, null, 0, 0),
_ => new FileTier(frame.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 (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.");
}
@@ -130,4 +241,7 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
return new RenderException(FrameUnreadableKey, $"Frame {index + 1} ({name}) could not be decoded.",
[(index + 1).ToString(CultureInfo.InvariantCulture), name]);
}
/// <summary>A frame of the window that does not decode; <see cref="GetFrameAsync"/> resolves it, nothing else sees it.</summary>
private sealed class NotDecodedException : Exception;
}
+20 -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,25 +31,41 @@ 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>
/// <param name="companions">The JPEG of each GPR frame kept in another sequence, by frame id (<see cref="Archiving.GprCompanions"/>).</param>
public SequenceRender(SequenceFrames frames, ProjectSettings project, DeepAnalysisReport? analysis, ProcessingOptions options, bool originals = false,
IReadOnlyDictionary<Guid, string>? companions = null)
{
// The host's tuning as it is now (memory budget, quality profile): a change applies from the next render.
options = options.Current;
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(),
Companions = companions,
};
_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);