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:
48 files changed
+1132
-87
No files matched your search
@@ -16,14 +16,17 @@ public static class Advisor
|
||||
{
|
||||
/// <summary>
|
||||
/// Recommendations for every parameter the rules cover (see <see cref="AdvisorRules"/>), in section order, plus
|
||||
/// every finding of both analyses. Without a deep report, pixel-based parameters get missing-data recommendations.
|
||||
/// every finding of both analyses; a finding both report (frames that cannot be decoded: the light analysis reads
|
||||
/// the flags the deep pass recorded) is listed once, as the light analysis has it. Without a deep report,
|
||||
/// pixel-based parameters get missing-data recommendations.
|
||||
/// </summary>
|
||||
public static AdvisorResult Recommend(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(light);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var findings = new List<Finding>(light.Findings);
|
||||
if (deep is not null) findings.AddRange(deep.Findings.Select(f => f.ToFinding()));
|
||||
var lightKeys = light.Findings.Select(f => f.Key).ToHashSet(StringComparer.Ordinal);
|
||||
if (deep is not null) findings.AddRange(deep.Findings.Select(f => f.ToFinding()).Where(f => !lightKeys.Contains(f.Key)));
|
||||
return new AdvisorResult(new AdvisorRules(light, deep, context).Run(), findings);
|
||||
}
|
||||
|
||||
|
||||
@@ -143,27 +143,38 @@ public sealed record SequenceContext
|
||||
/// <summary>Wanted video length ("fit to N seconds"), when the user set one.</summary>
|
||||
public double? TargetDurationSeconds { get; init; }
|
||||
|
||||
/// <summary>Context from the archive's frame rows: count, dominant oriented size, preview-only count, median shutter time.</summary>
|
||||
/// <summary>
|
||||
/// Context from the archive's frame rows: count, dominant oriented size, preview-only count with the dominant oriented
|
||||
/// size of those frames' previews, median shutter time.
|
||||
/// </summary>
|
||||
public static SequenceContext FromFrames(IReadOnlyList<Frame> frames, IReadOnlyList<EncoderCapability>? codecs = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
var sizes = new Dictionary<(int, int), int>();
|
||||
var previews = new Dictionary<(int, int), int>();
|
||||
var exposures = new List<double>();
|
||||
var previewOnly = 0;
|
||||
foreach (var f in frames)
|
||||
{
|
||||
var size = f.Orientation is >= 5 and <= 8 ? (f.Height, f.Width) : (f.Width, f.Height);
|
||||
var rotated = f.Orientation is >= 5 and <= 8;
|
||||
var size = rotated ? (f.Height, f.Width) : (f.Width, f.Height);
|
||||
if (size.Item1 > 0 && size.Item2 > 0) sizes[size] = sizes.GetValueOrDefault(size) + 1;
|
||||
if (f.ExposureTime is > 0 and var t) exposures.Add(t);
|
||||
if ((f.Flags & FrameFlags.PreviewOnly) != 0) previewOnly++;
|
||||
if ((f.Flags & FrameFlags.PreviewOnly) == 0) continue;
|
||||
previewOnly++;
|
||||
var preview = rotated ? (f.PreviewHeight, f.PreviewWidth) : (f.PreviewWidth, f.PreviewHeight);
|
||||
if (preview.Item1 > 0 && preview.Item2 > 0) previews[preview] = previews.GetValueOrDefault(preview) + 1;
|
||||
}
|
||||
var (width, height) = sizes.Count > 0 ? sizes.MaxBy(kv => kv.Value).Key : (0, 0);
|
||||
var (previewWidth, previewHeight) = previews.Count > 0 ? previews.MaxBy(kv => kv.Value).Key : (0, 0);
|
||||
return new SequenceContext
|
||||
{
|
||||
FrameCount = frames.Count,
|
||||
SourceWidth = width,
|
||||
SourceHeight = height,
|
||||
PreviewOnlyCount = previewOnly,
|
||||
PreviewWidth = previewWidth,
|
||||
PreviewHeight = previewHeight,
|
||||
MedianExposureSeconds = exposures.Count > 0 ? Statistics.Median(exposures.ToArray()) : null,
|
||||
Codecs = codecs ?? [],
|
||||
};
|
||||
|
||||
@@ -114,6 +114,7 @@ public sealed record DeepFinding(string Key, FindingSeverity Severity, double[]
|
||||
/// <summary>Resource keys of the findings produced by the deep analysis; arguments are numbers.</summary>
|
||||
public static class DeepFindingKeys
|
||||
{
|
||||
/// <summary>Frames nothing decodes; the light analysis reports the frames flagged so under it too (format tier 3).</summary>
|
||||
public const string UnreadableFrames = "Advisor.Finding.UnreadableFrames";
|
||||
public const string BlackFrames = "Advisor.Finding.BlackFrames";
|
||||
public const string WhiteFrames = "Advisor.Finding.WhiteFrames";
|
||||
|
||||
@@ -33,6 +33,9 @@ public static class FindingKeys
|
||||
public const string LensChanged = "Advisor.Finding.LensChanged";
|
||||
public const string MixedResolution = "Advisor.Finding.MixedResolution";
|
||||
public const string MixedOrientation = "Advisor.Finding.MixedOrientation";
|
||||
|
||||
/// <summary>Frames that decode only through their embedded preview (format tier 2); {0} frame count.</summary>
|
||||
public const string PreviewOnly = "Advisor.Finding.PreviewOnly";
|
||||
public const string TimeZoneEstimated = "Advisor.Finding.TimeZoneEstimated";
|
||||
public const string DayNightTransition = "Advisor.Finding.DayNightTransition";
|
||||
}
|
||||
@@ -131,5 +131,11 @@ public sealed record LightAnalysisReport
|
||||
/// <summary>Light condition per frame from GPS position and capture time; all null without GPS.</summary>
|
||||
public DayPhase?[] DayPhases { get; init; } = [];
|
||||
|
||||
/// <summary>Frames that decode only through their embedded preview (format tier 2, BRIEF §8.2).</summary>
|
||||
public IReadOnlyList<int> PreviewOnlyFrames { get; init; } = [];
|
||||
|
||||
/// <summary>Frames that nothing decodes (format tier 3): renders skip them.</summary>
|
||||
public IReadOnlyList<int> UndecodableFrames { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<Finding> Findings { get; init; } = [];
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Model;
|
||||
|
||||
@@ -5,8 +6,9 @@ namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>
|
||||
/// Metadata-only sequence analysis run at import/scan (BRIEF §10.1): cadence, gaps and sessions, timestamp
|
||||
/// sanity, exposure series and steps, camera/lens identity, size and orientation consistency, and day phases
|
||||
/// from GPS. Linear in the number of frames apart from two medians; deterministic.
|
||||
/// sanity, exposure series and steps, camera/lens identity, size and orientation consistency, format tiers (from the
|
||||
/// frames' decode-tier flags) and day phases from GPS. Linear in the number of frames apart from two medians;
|
||||
/// deterministic.
|
||||
/// </summary>
|
||||
public static class LightAnalyzer
|
||||
{
|
||||
@@ -31,6 +33,7 @@ public static class LightAnalyzer
|
||||
var exposure = AnalyzeExposure(frames, options, findings);
|
||||
var identity = AnalyzeIdentity(frames, findings);
|
||||
var (dominantSize, sizeOutliers, orientation, orientationOutliers) = AnalyzeGeometry(frames, findings);
|
||||
var (previewOnly, undecodable) = AnalyzeTiers(frames, findings);
|
||||
var phases = AnalyzeDayPhases(frames, timing.Adjusted, findings);
|
||||
|
||||
return new LightAnalysisReport
|
||||
@@ -56,6 +59,8 @@ public static class LightAnalyzer
|
||||
DominantOrientation = orientation,
|
||||
OrientationOutliers = orientationOutliers,
|
||||
DayPhases = phases,
|
||||
PreviewOnlyFrames = previewOnly,
|
||||
UndecodableFrames = undecodable,
|
||||
Findings = findings,
|
||||
};
|
||||
}
|
||||
@@ -331,6 +336,25 @@ public static class LightAnalyzer
|
||||
return (dominant, sizeOutliers, orientation, orientationOutliers);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Format tiers (BRIEF §8.2): frames that decode only through their embedded preview, which caps the output at the
|
||||
/// preview size, and frames that nothing decodes, which renders skip (a warning, under the key the deep analysis uses
|
||||
/// for the frames it could not decode, so the advisor lists them once).
|
||||
/// </summary>
|
||||
private static (List<int> PreviewOnly, List<int> Undecodable) AnalyzeTiers(IReadOnlyList<LightFrame> frames, List<Finding> findings)
|
||||
{
|
||||
var previewOnly = new List<int>();
|
||||
var undecodable = new List<int>();
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
if ((frames[i].Flags & FrameFlags.Undecodable) != 0) undecodable.Add(i);
|
||||
else if ((frames[i].Flags & FrameFlags.PreviewOnly) != 0) previewOnly.Add(i);
|
||||
}
|
||||
if (previewOnly.Count > 0) findings.Add(new Finding(FindingKeys.PreviewOnly, FindingSeverity.Info, [previewOnly.Count], Cap(previewOnly)));
|
||||
if (undecodable.Count > 0) findings.Add(new Finding(DeepFindingKeys.UnreadableFrames, FindingSeverity.Warning, [undecodable.Count], Cap(undecodable)));
|
||||
return (previewOnly, undecodable);
|
||||
}
|
||||
|
||||
private static DayPhase?[] AnalyzeDayPhases(IReadOnlyList<LightFrame> frames, DateTime?[] adjusted, List<Finding> findings)
|
||||
{
|
||||
var n = frames.Count;
|
||||
|
||||
@@ -31,6 +31,9 @@ public sealed record LightFrame
|
||||
/// <summary>GPS (satellite) UTC time stamp, used to infer the camera clock's UTC offset.</summary>
|
||||
public DateTime? GpsUtc { get; init; }
|
||||
|
||||
/// <summary>The archived frame's flags; the decode-tier bits feed the format-tier findings.</summary>
|
||||
public FrameFlags Flags { get; init; }
|
||||
|
||||
/// <summary>Exposure value at ISO 100: log2(N²/t) − log2(ISO/100).</summary>
|
||||
public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0
|
||||
? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso is > 0 ? Iso.Value : 100) / 100.0)
|
||||
@@ -54,6 +57,7 @@ public sealed record LightFrame
|
||||
Width = frame.Width,
|
||||
Height = frame.Height,
|
||||
Orientation = frame.Orientation,
|
||||
Flags = frame.Flags,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,9 @@ namespace Titano.Core.Archiving;
|
||||
public sealed record EncodedImage(byte[] Jpeg, int Width, int Height, DecodeTier Tier);
|
||||
|
||||
/// <summary>
|
||||
/// Makes thumbnails and proxies of frames (BRIEF §8.5): the embedded preview or the managed JPEG decoder first, then
|
||||
/// the host's decode providers (WIC on Windows); orientation applied, resampled in linear light, encoded in-house.
|
||||
/// Makes thumbnails and proxies of frames (BRIEF §8.5): the managed JPEG decoder, or for thumbnails an embedded preview
|
||||
/// at least 320 px long, first, then the host's decode providers (WIC on Windows); orientation applied, resampled in
|
||||
/// linear light, encoded in-house. <see cref="EncodedImage.Tier"/> says how the pixels were obtained.
|
||||
/// </summary>
|
||||
public sealed class FrameImageRenderer(ImageDecoder decoder)
|
||||
{
|
||||
@@ -55,13 +56,37 @@ public sealed class FrameImageRenderer(ImageDecoder decoder)
|
||||
private static EncodedImage Encode(ImageBuffer pixels, JpegEncodeOptions options, DecodeTier tier) =>
|
||||
new(JpegEncoder.Encode(pixels, options), pixels.Width, pixels.Height, tier);
|
||||
|
||||
/// <summary>
|
||||
/// The frame's pixels: a JPEG through the managed decoder, the stored embedded preview when <paramref name="preferPreview"/>
|
||||
/// and it reaches <paramref name="maxLongEdge"/> (a smaller one would be upscaled or leave the thumbnail short), then
|
||||
/// the host's decoders, and the stored preview as the last resort. Null when nothing decodes.
|
||||
/// </summary>
|
||||
private DecodedFrame? Decode(string path, SidecarFrame frame, int maxLongEdge, DecodePurpose purpose, bool preferPreview, CancellationToken cancellationToken)
|
||||
{
|
||||
if (frame.Format == ImageFileFormat.Jpeg) return DecodeJpeg(File.ReadAllBytes(path), maxLongEdge, frame.Orientation, DecodeTier.Native);
|
||||
if (preferPreview && ReadPreview(path, frame) is { } preview) return DecodeJpeg(preview, maxLongEdge, frame.Orientation, DecodeTier.EmbeddedPreview);
|
||||
if (frame.Format == ImageFileFormat.Jpeg && DecodeJpeg(File.ReadAllBytes(path), maxLongEdge, frame.Orientation, DecodeTier.Native) is { } jpeg) return jpeg;
|
||||
byte[]? preview = null;
|
||||
if (preferPreview && (preview = ReadPreview(path, frame)) is not null && Reaches(preview, frame, maxLongEdge)
|
||||
&& DecodeJpeg(preview, maxLongEdge, frame.Orientation, DecodeTier.EmbeddedPreview) is { } fast)
|
||||
return fast;
|
||||
var request = new DecodeRequest(path, System.Math.Max(0, maxLongEdge), purpose, ApplyOrientation: true, AllowPreview: true);
|
||||
if (decoder.Decode(request, cancellationToken) is { } decoded) return new DecodedFrame(decoded.Pixels, decoded.Tier);
|
||||
return ReadPreview(path, frame) is { } fallback ? DecodeJpeg(fallback, maxLongEdge, frame.Orientation, DecodeTier.EmbeddedPreview) : null;
|
||||
return (preview ?? ReadPreview(path, frame)) is { } fallback ? DecodeJpeg(fallback, maxLongEdge, frame.Orientation, DecodeTier.EmbeddedPreview) : null;
|
||||
}
|
||||
|
||||
/// <summary>Whether the stored preview's long edge reaches <paramref name="maxLongEdge"/> (the sidecar's size, else the JPEG's own).</summary>
|
||||
private static bool Reaches(byte[] preview, SidecarFrame frame, int maxLongEdge)
|
||||
{
|
||||
if (maxLongEdge <= 0) return true;
|
||||
if (frame is { PreviewW: { } w, PreviewH: { } h }) return int.Max(w, h) >= maxLongEdge;
|
||||
try
|
||||
{
|
||||
var info = JpegDecoder.ReadInfo(preview);
|
||||
return int.Max(info.Width, info.Height) >= maxLongEdge;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static DecodedFrame? DecodeJpeg(byte[] data, int maxLongEdge, int orientation, DecodeTier tier)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
|
||||
@@ -42,9 +43,32 @@ public static class SequenceFrames
|
||||
Format = metadata.Format,
|
||||
PreviewOffset = metadata.LargestPreview?.Offset,
|
||||
PreviewLength = metadata.LargestPreview?.Length,
|
||||
PreviewW = Positive(metadata.LargestPreview?.Width),
|
||||
PreviewH = Positive(metadata.LargestPreview?.Height),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame with its decode tier (BRIEF §8.2) and the flags that follow it: <see cref="FrameFlags.PreviewOnly"/> for
|
||||
/// the embedded-preview tier, <see cref="FrameFlags.Undecodable"/> for none. <paramref name="tier"/>'s size, oriented
|
||||
/// like every <see cref="FileTier"/>, replaces the stored preview size when it is a preview's.
|
||||
/// </summary>
|
||||
/// <param name="damaged">For the unavailable tier: whether that proves the file unreadable. False when the host has no
|
||||
/// native decoder for the format, so a client or render node with one (or a proxy) may still produce its pixels: the
|
||||
/// tier is kept and <see cref="FrameFlags.Undecodable"/> is left as it was.</param>
|
||||
public static SidecarFrame WithTier(SidecarFrame frame, FileTier tier, bool damaged = true)
|
||||
{
|
||||
var flags = frame.Flags & ~(FrameFlags.PreviewOnly | FrameFlags.Undecodable);
|
||||
if (tier.Tier == DecodeTier.EmbeddedPreview) flags |= FrameFlags.PreviewOnly;
|
||||
else if (tier.Tier == DecodeTier.Unavailable) flags |= damaged ? FrameFlags.Undecodable : frame.Flags & FrameFlags.Undecodable;
|
||||
var (w, h) = tier.Tier == DecodeTier.EmbeddedPreview && tier.Width > 0 && tier.Height > 0
|
||||
? PixelConvert.OrientedSize(tier.Width, tier.Height, frame.Orientation)
|
||||
: (frame.PreviewW ?? 0, frame.PreviewH ?? 0);
|
||||
return frame with { Tier = tier.Tier, Flags = flags, PreviewW = Positive(w), PreviewH = Positive(h) };
|
||||
}
|
||||
|
||||
private static int? Positive(int? value) => value > 0 ? value : null;
|
||||
|
||||
/// <summary>
|
||||
/// Merges <paramref name="added"/> into the frame list by capture time (existing frames keep their relative order),
|
||||
/// renumbers indexes and bumps the frames version.
|
||||
|
||||
@@ -109,6 +109,20 @@ public sealed record SidecarFrame
|
||||
public long? PreviewOffset { get; init; }
|
||||
public long? PreviewLength { get; init; }
|
||||
|
||||
/// <summary>Size of the largest embedded preview (or GPR companion JPEG), stored like <see cref="W"/> and <see cref="H"/>
|
||||
/// before orientation; null when the file has none or it is not known yet.</summary>
|
||||
public int? PreviewW { get; init; }
|
||||
|
||||
public int? PreviewH { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Decode tier of the file (BRIEF §8.2) as the host that indexed or decoded it last found it; omitted until it is
|
||||
/// known. <see cref="FrameFlags.PreviewOnly"/> and <see cref="FrameFlags.Undecodable"/> follow it.
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(TolerantEnumConverter<DecodeTier>))]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public DecodeTier Tier { get; init; }
|
||||
|
||||
/// <summary><see cref="FrameFlags"/> bits, stored as a number so bits of newer builds survive.</summary>
|
||||
public FrameFlags Flags { get; init; }
|
||||
|
||||
|
||||
@@ -7,19 +7,11 @@ using Titano.Core.Metadata;
|
||||
|
||||
namespace Titano.Core.Imaging.Decoders;
|
||||
|
||||
/// <summary>Tier a provider would use for one specific file, with the reason when it is not native.</summary>
|
||||
/// <param name="Format">Format detected from the file's signature (extension only breaks ties).</param>
|
||||
/// <param name="Tier">Best tier available for this file.</param>
|
||||
/// <param name="Decoder">Decoder that would produce it ("managed-cr2", "managed-preview"…), null when unavailable.</param>
|
||||
/// <param name="Reason">Why the native tier is not used (unsupported body or encoding), else null.</param>
|
||||
/// <param name="Width">Full-size width that tier delivers (developed RAW, preview or image size), oriented; 0 when unknown.</param>
|
||||
/// <param name="Height">Full-size height, oriented; 0 when unknown.</param>
|
||||
public sealed record FileTier(ImageFileFormat Format, DecodeTier Tier, string? Decoder, string? Reason, int Width, int Height);
|
||||
|
||||
/// <summary>
|
||||
/// The managed decoder (BRIEF §8.2), available on every platform and the only one on the server: JPEG, PNG and TIFF
|
||||
/// natively; DNG and the supported camera RAWs (CR2, NEF, ARW, PEF, RAF) through <see cref="RawDecoder"/>; every other
|
||||
/// RAW, CR3 and HEIF through the largest suitable embedded JPEG preview; nothing for formats without either.
|
||||
/// RAW, CR3 and HEIF through the largest suitable embedded JPEG preview, and GoPro GPR through the JPEG the camera writes
|
||||
/// beside it when that is larger (BRIEF §8.1; VC-5 is out of scope); nothing for formats without either.
|
||||
/// <see cref="DecodeRequest"/> fast paths: JPEG DCT scaling and RAW CFA binning when <see cref="DecodeRequest.MaxLongEdge"/>
|
||||
/// allows, bilinear demosaicing for thumbnails and analysis, and <see cref="DecodeRequest.ForcePreview"/> to skip native
|
||||
/// RAW development. Results fit within MaxLongEdge (never upscaled) and are always RGB.
|
||||
@@ -29,6 +21,7 @@ public sealed class ManagedDecoderProvider : IImageDecoderProvider
|
||||
private const string LogCategory = "Decode";
|
||||
private const int FileBufferSize = 1 << 16;
|
||||
private const long MaxPreviewBytes = 256L << 20;
|
||||
private static readonly string[] CompanionExtensions = [".JPG", ".jpg", ".JPEG", ".jpeg"];
|
||||
|
||||
public string Name => "managed";
|
||||
|
||||
@@ -62,6 +55,18 @@ public sealed class ManagedDecoderProvider : IImageDecoderProvider
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tier for a file whose signature format is already known (the index's): JPEG, PNG and TIFF decode natively
|
||||
/// whatever they hold (damage shows only when decoding), so only RAW and HEIF files are opened.
|
||||
/// </summary>
|
||||
public FileTier Probe(string path, ImageFileFormat format)
|
||||
{
|
||||
var family = ImageFormatInfo.Of(format).Family;
|
||||
if (family is not (ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff)) return Probe(path);
|
||||
var decoder = family switch { ImageFamily.Jpeg => "managed-jpeg", ImageFamily.Png => "managed-png", _ => "managed-tiff" };
|
||||
return new FileTier(format, DecodeTier.Native, decoder, null, 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>The tier this provider would use for the file at <paramref name="path"/>, without decoding pixels.</summary>
|
||||
public FileTier Probe(string path)
|
||||
{
|
||||
@@ -88,11 +93,32 @@ public sealed class ManagedDecoderProvider : IImageDecoderProvider
|
||||
reason = $"no managed decoder for {format}";
|
||||
}
|
||||
var metadata = MetadataReader.Read(stream, path);
|
||||
if (metadata.LargestPreview is not { } preview) return new FileTier(format, DecodeTier.Unavailable, null, reason + "; no embedded preview", 0, 0);
|
||||
var (pw, ph) = PixelConvert.OrientedSize(preview.Width, preview.Height, metadata.Orientation);
|
||||
var (pw, ph) = metadata.LargestPreview is { } preview ? PixelConvert.OrientedSize(preview.Width, preview.Height, metadata.Orientation) : (0, 0);
|
||||
if (format == ImageFileFormat.Gpr && CompanionJpeg(path) is { } companion)
|
||||
{
|
||||
var jpeg = MetadataReader.Read(companion);
|
||||
var (cw, ch) = jpeg.OrientedSize;
|
||||
if (jpeg.Format == ImageFileFormat.Jpeg && int.Max(cw, ch) > int.Max(pw, ph))
|
||||
return new FileTier(format, DecodeTier.EmbeddedPreview, "managed-sidecar", reason, cw, ch);
|
||||
}
|
||||
if (metadata.LargestPreview is null) return new FileTier(format, DecodeTier.Unavailable, null, reason + "; no embedded preview", 0, 0);
|
||||
return new FileTier(format, DecodeTier.EmbeddedPreview, "managed-preview", reason, pw, ph);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The JPEG a GoPro writes beside a GPR (same name, <c>.JPG</c>), or null. Only the usual spellings are tried, so a
|
||||
/// folder of thousands of frames is never listed once per frame.
|
||||
/// </summary>
|
||||
internal static string? CompanionJpeg(string path)
|
||||
{
|
||||
var stem = Path.Combine(Path.GetDirectoryName(path) ?? string.Empty, Path.GetFileNameWithoutExtension(path));
|
||||
foreach (var extension in CompanionExtensions)
|
||||
{
|
||||
if (File.Exists(stem + extension)) return stem + extension;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static FileStream Open(string path) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess);
|
||||
|
||||
@@ -147,7 +173,37 @@ public sealed class ManagedDecoderProvider : IImageDecoderProvider
|
||||
Log.Debug(LogCategory, $"{Path.GetFileName(request.Path)}: native decode unavailable ({ex.Message}); trying the embedded preview");
|
||||
}
|
||||
}
|
||||
return request.AllowPreview || request.ForcePreview ? Preview(stream, request, adequateOnly: false, cancellationToken) : null;
|
||||
if (!request.AllowPreview && !request.ForcePreview) return null;
|
||||
if (format == ImageFileFormat.Gpr && Companion(stream, request, cancellationToken) is { } companion) return companion;
|
||||
return Preview(stream, request, adequateOnly: false, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GPR's pixel source: the GoPro's own JPEG beside it when it is larger than every embedded preview (the camera writes
|
||||
/// it at full size), decoded with DCT scaling and oriented by its own Exif; null when there is none.
|
||||
/// </summary>
|
||||
private static DecodedImage? Companion(Stream raw, DecodeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (CompanionJpeg(request.Path) is not { } path) return null;
|
||||
var previews = MetadataReader.Read(raw, request.Path, cancellationToken: cancellationToken).Previews;
|
||||
var largestPreview = previews.Count > 0 ? int.Max(previews[0].Width, previews[0].Height) : 0;
|
||||
using var stream = Open(path);
|
||||
if (stream.Length > MaxPreviewBytes) return null;
|
||||
var data = ReadAll(stream);
|
||||
JpegInfo info;
|
||||
try
|
||||
{
|
||||
info = JpegDecoder.ReadInfo(data);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Debug(LogCategory, $"{Path.GetFileName(path)}: not a usable JPEG ({ex.Message}); using the embedded preview");
|
||||
return null;
|
||||
}
|
||||
if (int.Max(info.Width, info.Height) <= largestPreview) return null;
|
||||
var image = JpegDecoder.DecodeToLinear(data, new JpegDecodeOptions { MaxLongEdge = request.MaxLongEdge }, expandGray: true);
|
||||
var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, path, cancellationToken: cancellationToken).Orientation : 1;
|
||||
return Finish(image, orientation, request, info.Width, info.Height, DecodeTier.EmbeddedPreview, "managed-sidecar");
|
||||
}
|
||||
|
||||
/// <summary>Embedded-preview tier: the smallest preview whose long edge still reaches MaxLongEdge (the largest when none
|
||||
|
||||
@@ -53,6 +53,15 @@ public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string dec
|
||||
public void Dispose() => Pixels.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Tier a provider would use for one specific file, with the reason when it is not native.</summary>
|
||||
/// <param name="Format">Format of the file (detected from its signature; the extension only breaks ties).</param>
|
||||
/// <param name="Tier">Best tier available for this file.</param>
|
||||
/// <param name="Decoder">Decoder that would produce it ("managed-cr2", "managed-preview"…), null when unavailable.</param>
|
||||
/// <param name="Reason">Why the native tier is not used (unsupported body or encoding), else null.</param>
|
||||
/// <param name="Width">Full-size width that tier delivers (developed RAW, preview or image size), oriented; 0 when unknown.</param>
|
||||
/// <param name="Height">Full-size height, oriented; 0 when unknown.</param>
|
||||
public sealed record FileTier(ImageFileFormat Format, DecodeTier Tier, string? Decoder, string? Reason, int Width, int Height);
|
||||
|
||||
/// <summary>A platform image decoder (WIC on Windows, managed codecs everywhere).</summary>
|
||||
public interface IImageDecoderProvider
|
||||
{
|
||||
@@ -64,6 +73,17 @@ public interface IImageDecoderProvider
|
||||
|
||||
bool CanDecode(ImageFormatInfo format) => TierFor(format.Format) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The tier this provider would use for the file at <paramref name="path"/>, whose signature says
|
||||
/// <paramref name="format"/>, without decoding pixels. The default trusts <see cref="TierFor"/>; a provider whose
|
||||
/// support depends on the file itself (camera body, encoding, embedded previews) looks inside it.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
/// <exception cref="InvalidDataException">The file is malformed where the provider looks.</exception>
|
||||
FileTier Probe(string path, ImageFileFormat format) => TierFor(format) is { } tier
|
||||
? new FileTier(format, tier, Name, null, 0, 0)
|
||||
: new FileTier(format, DecodeTier.Unavailable, null, $"{Name}: no decoder for {format}", 0, 0);
|
||||
|
||||
/// <summary>Decodes or returns null when this provider cannot handle the specific file.</summary>
|
||||
DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -84,6 +104,39 @@ public sealed class ImageDecoder(IReadOnlyList<IImageDecoderProvider> providers)
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tier this chain would use for the file at <paramref name="path"/> (signature format <paramref name="format"/>)
|
||||
/// without decoding pixels (BRIEF §8.2): the first provider whose probe reaches the native tier, else the largest
|
||||
/// embedded preview a provider offers, else unavailable with the first reason given. A provider that finds the file
|
||||
/// malformed is skipped like in <see cref="Decode"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public FileTier Probe(string path, ImageFileFormat format)
|
||||
{
|
||||
FileTier? preview = null;
|
||||
string? reason = null;
|
||||
foreach (var provider in Providers.OrderBy(p => p.TierFor(format) ?? DecodeTier.Unavailable))
|
||||
{
|
||||
if (provider.TierFor(format) is null) continue;
|
||||
FileTier tier;
|
||||
try
|
||||
{
|
||||
tier = provider.Probe(path, format);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or NotSupportedException or FormatException or InvalidOperationException
|
||||
or System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
reason ??= $"{provider.Name}: {ex.Message}";
|
||||
continue;
|
||||
}
|
||||
if (tier.Tier == DecodeTier.Native) return tier;
|
||||
if (tier.Tier == DecodeTier.EmbeddedPreview && (preview is null || long.Max(tier.Width, tier.Height) > long.Max(preview.Width, preview.Height)))
|
||||
preview = tier;
|
||||
reason ??= tier.Reason;
|
||||
}
|
||||
return preview ?? new FileTier(format, DecodeTier.Unavailable, null, reason ?? $"no decoder for {format}", 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Decodes with the first provider that succeeds; null means <see cref="DecodeTier.Unavailable"/>.</summary>
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
|
||||
@@ -59,6 +59,10 @@ public sealed record Sequence
|
||||
public int FramesVersion { get; init; }
|
||||
public Guid? OwnerUserId { get; init; }
|
||||
public int WarningCount { get; init; }
|
||||
|
||||
/// <summary>Frames that decode only through their embedded preview (<see cref="FrameFlags.PreviewOnly"/>, BRIEF §8.2).</summary>
|
||||
public int PreviewOnlyCount { get; init; }
|
||||
|
||||
public DateTimeOffset UpdatedAt { get; init; }
|
||||
|
||||
/// <summary>The title, else capture date and camera, else the folder name (never empty).</summary>
|
||||
@@ -112,6 +116,12 @@ public sealed record Frame
|
||||
public long? PreviewOffset { get; init; }
|
||||
public long? PreviewLength { get; init; }
|
||||
|
||||
/// <summary>Size of the largest embedded preview like <see cref="Width"/> and <see cref="Height"/> (before orientation);
|
||||
/// 0 when there is none or it is not known.</summary>
|
||||
public int PreviewWidth { get; init; }
|
||||
|
||||
public int PreviewHeight { get; init; }
|
||||
|
||||
/// <summary>Mean log2 luminance once analysed.</summary>
|
||||
public double? MeanLogLuminance { get; init; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user