using Titano.Core.Archiving; using Titano.Core.Imaging; using Titano.Core.Model; using Titano.Data.Repositories; namespace Titano.Data.Archiving; /// /// Decode tiers of archived frames (BRIEF ยง8.2) written to the sidecar and the index together: the tier, the /// and 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. A frame whose /// original this host reads through its proxy () is preview-only /// only while it has none: with its proxy it is not rendered from the embedded preview, so it caps nothing. /// internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer) { /// /// The tier of every frame of 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 /// (; an upload may index it after the GPR was probed) is larger than its stored preview, /// or that is stored as GPR without the .gpr extension (indexed before GoPro DNGs converted by Adobe software counted as /// DNG; R4, owner review 1), probed with the host's decoders without decoding pixels; missing and unreadable files are /// left for later. /// public async Task> ProbeUnknownAsync(Archive archive, SequencePaths folder, SequenceManifest manifest, CancellationToken cancellationToken) { var tiers = new Dictionary(); 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) || IsStaleGpr(f) || (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; } /// /// Records (by frame id) where they change what the sidecar says, and returns the sequence's /// frames as the sidecar has them afterwards (none when there was nothing to record). Frames no longer in the /// sequence are ignored. The flag of a frame whose original this host reads /// through its proxy follows whether its own proxy is there when the sidecar is written /// (, ), not when the caller looked: proxies /// arrive while analyses and renders run, and another worker may have recorded them already. /// /// Whether every such frame follows its proxy even where no tier is recorded (analyses and the /// proxy pass); otherwise only the frames in do. /// /// The sidecar and the index are written under one lease, the index from the sidecar read under it, and the index /// row gets only what tiers change (): a whole row written back /// would undo what another writer committed meanwhile, an ingest's frames or a settings edit (the server's PATCH /// takes no lease). The folder's scan stamps are recorded only when the index held the folder as it was /// (). /// /// The archive is offline or read-only. public async Task> RecordAsync(Archive archive, Sequence sequence, IReadOnlyDictionary tiers, bool proxies, CancellationToken cancellationToken) { if (tiers.Count == 0 && !proxies) return []; var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); var folder = paths.Sequence(sequence.Folder); await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false)) { var m = SequenceWriter.ReadLocked(folder, sequence.Id); var changed = new List(); var gained = false; ProxyPolicy? policy = null; var frames = new SidecarFrame[m.Frames.Count]; for (var i = 0; i < frames.Length; i++) { var frame = m.Frames[i]; frames[i] = frame; var tier = tiers.GetValueOrDefault(frame.Id); if (tier is null && !proxies) continue; bool? proxied = (frame.Flags & FrameFlags.Missing) == 0 && ArchiveImages.NeedsProxy(writer.Options.Decoder, frame.Format) ? ArchiveImages.IsProxyOf(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, policy ??= ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy) : null; SidecarFrame updated; if (tier is not null) updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format), proxied == true); else if (proxied is { } own) updated = SequenceFrames.WithProxy(frame, own); else continue; if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH && updated.Format == frame.Format) continue; gained |= (updated.Flags & ~frame.Flags & FrameFlags.Undecodable) != 0; frames[i] = updated; changed.Add(updated); } if (changed.Count == 0) return m.Frames; var inStep = await indexer.InStepAsync(archive, folder, m, cancellationToken).ConfigureAwait(false); var manifest = m with { Frames = frames, Status = gained ? m.Status | SequenceStatus.HasWarnings : m.Status, UpdatedAt = DateTimeOffset.UtcNow, }; ManifestStore.WriteSequence(folder.ManifestPath, manifest); await using (var tx = await db.BeginAsync(cancellationToken).ConfigureAwait(false)) { // The row before its frames (SequenceRepository.GetForUpdateAsync): a scan holding the row would otherwise wait // for these frames while this waits for the row, and PostgreSQL would abort one of them. await tx.Sequences.RecordTiersAsync(sequence.Id, gained ? SequenceStatus.HasWarnings : SequenceStatus.None, frames.Count(f => (f.Flags & FrameFlags.PreviewOnly) != 0), cancellationToken).ConfigureAwait(false); await tx.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0, f.Format)), cancellationToken) .ConfigureAwait(false); await tx.CommitAsync(cancellationToken).ConfigureAwait(false); } if (inStep) await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false); return manifest.Frames; } } /// /// A frame stored as GPR whose file is not a .gpr: before owner review 1 every DNG with Make=GoPro counted as GPR, so /// Adobe-converted GoPro DNGs were recorded preview-only; probing reads its signature again ( /// then stores the format found). /// internal static bool IsStaleGpr(SidecarFrame frame) => frame.Format == ImageFileFormat.Gpr && !frame.File.EndsWith(".gpr", StringComparison.OrdinalIgnoreCase); /// /// Whether this host decodes 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). /// private bool DecodesNatively(ImageFileFormat format) => format == ImageFileFormat.Jpeg || writer.Options.Decoder.TierFor(format) == DecodeTier.Native; }