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:
70 files changed
+2201
-124
No files matched your search
@@ -16,14 +16,32 @@ 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. Frames that cannot be decoded are reported by both (the light analysis reads the
|
||||
/// undecodable flags, the deep pass also counts missing and corrupt files and those beyond this host's decoders):
|
||||
/// they are listed once, over the union of both lists, at the higher severity. 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()));
|
||||
foreach (var finding in deep?.Findings.Select(f => f.ToFinding()) ?? [])
|
||||
{
|
||||
var shared = finding.Key == DeepFindingKeys.UnreadableFrames ? findings.FindIndex(f => f.Key == finding.Key) : -1;
|
||||
if (shared < 0)
|
||||
{
|
||||
findings.Add(finding);
|
||||
continue;
|
||||
}
|
||||
var unreadable = light.UndecodableFrames.Union(deep!.Issues.Undecodable).Order().ToList();
|
||||
findings[shared] = findings[shared] with
|
||||
{
|
||||
Severity = (FindingSeverity)int.Max((int)findings[shared].Severity, (int)finding.Severity),
|
||||
Arguments = [unreadable.Count],
|
||||
Frames = [.. unreadable.Take(Finding.MaxFrames)],
|
||||
};
|
||||
}
|
||||
return new AdvisorResult(new AdvisorRules(light, deep, context).Run(), findings);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ public static class AdvisorKeys
|
||||
|
||||
public static string TimingSessions { get; } = LocKey("Advisor.Reason.Timing.Sessions");
|
||||
public static string TimingIrregular { get; } = LocKey("Advisor.Reason.Timing.Irregular");
|
||||
public static string TimingIntervalometer { get; } = LocKey("Advisor.Reason.Timing.Intervalometer");
|
||||
public static string TimingSparseGapsSmooth { get; } = LocKey("Advisor.Reason.Timing.SparseGapsSmooth");
|
||||
public static string TimingSparseGaps { get; } = LocKey("Advisor.Reason.Timing.SparseGaps");
|
||||
public static string TimingManyGaps { get; } = LocKey("Advisor.Reason.Timing.ManyGaps");
|
||||
|
||||
@@ -185,11 +185,13 @@ internal sealed class AdvisorRules
|
||||
|
||||
/// <summary>
|
||||
/// Timing mode, in order: several capture sessions (pauses ≥ the session gap) → Adaptive; jitter above 10 % of the
|
||||
/// median interval → Adaptive; gaps that are sparse (≤ 2 % of intervals, each ≤ 10 × median) with smooth measured
|
||||
/// motion (95th percentile ≤ 1 % of the long edge per frame) → Interpolated, or Constant when motion is unknown or
|
||||
/// fast; denser gaps → Adaptive; otherwise Constant. Frame rate, in order: "fit to N s" target → the standard rate
|
||||
/// nearest frames/N; under 240 frames → 24 (clip ≥ 10 s); over 10 min at 30 fps → 60; several sessions → 30; fast
|
||||
/// motion (≥ 1 % of the long edge per frame) → 24; measured moderate motion (≥ 0.2 %) → 24; otherwise 30.
|
||||
/// median interval → Adaptive; gaps in a sequence the camera's own intervalometer shot (most frames carry its
|
||||
/// MakerNote hint), so its pauses were deliberate → Adaptive; gaps that are sparse (≤ 2 % of intervals, each ≤ 10 ×
|
||||
/// median) with smooth measured motion (95th percentile ≤ 1 % of the long edge per frame) → Interpolated, or Constant
|
||||
/// when motion is unknown or fast; denser gaps → Adaptive; otherwise Constant. Frame rate, in order: "fit to N s"
|
||||
/// target → the standard rate nearest frames/N; under 240 frames → 24 (clip ≥ 10 s); over 10 min at 30 fps → 60;
|
||||
/// several sessions → 30; fast motion (≥ 1 % of the long edge per frame) → 24; measured moderate motion (≥ 0.2 %) →
|
||||
/// 24; otherwise 30.
|
||||
/// </summary>
|
||||
private void Timing()
|
||||
{
|
||||
@@ -222,6 +224,11 @@ internal sealed class AdvisorRules
|
||||
_timing = TimingMode.Adaptive;
|
||||
Add(section, parameter, _timing, 0.7, AdvisorKeys.TimingIrregular, R(jitter, 2), R(median, 2));
|
||||
}
|
||||
else if (gaps.Count > 0 && 2 * _light.IntervalometerFrames > _light.FrameCount)
|
||||
{
|
||||
_timing = TimingMode.Adaptive;
|
||||
Add(section, parameter, _timing, 0.8, AdvisorKeys.TimingIntervalometer, gaps.Count);
|
||||
}
|
||||
else if (gaps.Count > 0)
|
||||
{
|
||||
var sparse = gaps.Count <= double.Max(1, 0.02 * _light.Intervals.Count) && gaps.All(g => g.Seconds <= 10 * median);
|
||||
|
||||
@@ -144,27 +144,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";
|
||||
|
||||
@@ -36,6 +36,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,14 @@ 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; } = [];
|
||||
|
||||
/// <summary>Frames the camera's own interval-shooting mode took (MakerNote hint, <see cref="Model.FrameFlags.Intervalometer"/>).</summary>
|
||||
public int IntervalometerFrames { 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,9 @@ public static class LightAnalyzer
|
||||
DominantOrientation = orientation,
|
||||
OrientationOutliers = orientationOutliers,
|
||||
DayPhases = phases,
|
||||
PreviewOnlyFrames = previewOnly,
|
||||
UndecodableFrames = undecodable,
|
||||
IntervalometerFrames = frames.Count(f => (f.Flags & FrameFlags.Intervalometer) != 0),
|
||||
Findings = findings,
|
||||
};
|
||||
}
|
||||
@@ -334,6 +340,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)
|
||||
{
|
||||
@@ -21,19 +22,23 @@ public sealed class FrameImageRenderer(ImageDecoder decoder)
|
||||
Thumbnail(sequence, frame, new ThumbnailPolicy(), cancellationToken);
|
||||
|
||||
/// <summary>A thumbnail at the policy's long edge and quality (the archive's, BRIEF §8.5), or null when no decoder can read the frame.</summary>
|
||||
public EncodedImage? Thumbnail(SequencePaths sequence, SidecarFrame frame, ThumbnailPolicy policy, CancellationToken cancellationToken = default)
|
||||
/// <param name="companion">Where a GPR's JPEG is kept when it is not beside it (<see cref="DecodeRequest.Companion"/>).</param>
|
||||
public EncodedImage? Thumbnail(SequencePaths sequence, SidecarFrame frame, ThumbnailPolicy policy, CancellationToken cancellationToken = default,
|
||||
string? companion = null)
|
||||
{
|
||||
using var decoded = Decode(sequence.File(frame.File), frame, policy.LongEdge, DecodePurpose.Thumbnail, preferPreview: true, cancellationToken);
|
||||
using var decoded = Decode(sequence.File(frame.File), frame, policy.LongEdge, DecodePurpose.Thumbnail, preferPreview: true, companion, cancellationToken);
|
||||
if (decoded is null) return null;
|
||||
using var small = Resampler.Thumbnail(decoded.Pixels, policy.LongEdge);
|
||||
return Encode(small, new JpegEncodeOptions { Quality = policy.Quality }, decoded.Tier);
|
||||
}
|
||||
|
||||
/// <summary>A proxy at the policy's long edge and quality with capture time and camera in its Exif; null when undecodable.</summary>
|
||||
public EncodedImage? Proxy(SequencePaths sequence, SidecarFrame frame, SidecarCamera? camera, ProxyPolicy policy, CancellationToken cancellationToken = default)
|
||||
/// <param name="companion">Where a GPR's JPEG is kept when it is not beside it (<see cref="DecodeRequest.Companion"/>).</param>
|
||||
public EncodedImage? Proxy(SequencePaths sequence, SidecarFrame frame, SidecarCamera? camera, ProxyPolicy policy, CancellationToken cancellationToken = default,
|
||||
string? companion = null)
|
||||
{
|
||||
if (policy.LongEdge == ProxyPolicy.Disabled) throw new InvalidOperationException("Proxies are disabled for this archive.");
|
||||
using var decoded = Decode(sequence.File(frame.File), frame, policy.LongEdge, DecodePurpose.Proxy, preferPreview: false, cancellationToken);
|
||||
using var decoded = Decode(sequence.File(frame.File), frame, policy.LongEdge, DecodePurpose.Proxy, preferPreview: false, companion, cancellationToken);
|
||||
if (decoded is null) return null;
|
||||
var source = decoded.Pixels;
|
||||
var (w, h) = policy.LongEdge == ProxyPolicy.FullSize ? (source.Width, source.Height) : Resampler.FitWithin(source.Width, source.Height, policy.LongEdge);
|
||||
@@ -59,13 +64,42 @@ 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);
|
||||
|
||||
private DecodedFrame? Decode(string path, SidecarFrame frame, int maxLongEdge, DecodePurpose purpose, bool preferPreview, CancellationToken cancellationToken)
|
||||
/// <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 (with the GPR's <paramref name="companion"/>), and the stored preview as the last resort. Null
|
||||
/// when nothing decodes.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file could not be read.</exception>
|
||||
private DecodedFrame? Decode(string path, SidecarFrame frame, int maxLongEdge, DecodePurpose purpose, bool preferPreview, string? companion,
|
||||
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);
|
||||
var request = new DecodeRequest(path, System.Math.Max(0, maxLongEdge), purpose, ApplyOrientation: true, AllowPreview: true);
|
||||
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, 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, Companion: companion);
|
||||
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"/>, from the JPEG's own header: the
|
||||
/// sidecar's preview size may be a GPR companion's, larger than the preview embedded in the file.
|
||||
/// </summary>
|
||||
private static bool Reaches(byte[] preview, int maxLongEdge)
|
||||
{
|
||||
if (maxLongEdge <= 0) return true;
|
||||
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;
|
||||
|
||||
@@ -13,7 +14,7 @@ public static class SequenceFrames
|
||||
return byTime != 0 ? byTime : string.CompareOrdinal(a.File, b.File);
|
||||
});
|
||||
|
||||
/// <summary>A frame record from light metadata.</summary>
|
||||
/// <summary>A frame record from light metadata (with <see cref="FrameFlags.Intervalometer"/> when the MakerNote says so).</summary>
|
||||
/// <param name="file">Path relative to the sequence folder.</param>
|
||||
/// <param name="fallbackCapture">Used when the file records no capture time of its own (only a file-system date).</param>
|
||||
public static SidecarFrame FromMetadata(Guid id, string file, string? original, long size, string? sha256, FrameMetadata metadata,
|
||||
@@ -42,9 +43,33 @@ 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),
|
||||
Flags = metadata.IntervalShooting == true ? FrameFlags.Intervalometer : FrameFlags.None,
|
||||
};
|
||||
}
|
||||
|
||||
/// <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,12 @@ 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
|
||||
/// with it (beside it, or where <see cref="DecodeRequest.Companion"/> says an import put 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 +22,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,8 +56,25 @@ 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) => Probe(path, format, null);
|
||||
|
||||
/// <inheritdoc cref="Probe(string, ImageFileFormat)"/>
|
||||
/// <param name="companion">Where a GPR's JPEG is kept when it is not beside it (<see cref="DecodeRequest.Companion"/>).</param>
|
||||
public FileTier Probe(string path, ImageFileFormat format, string? companion)
|
||||
{
|
||||
var family = ImageFormatInfo.Of(format).Family;
|
||||
if (family is not (ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff)) return Probe(path, companion);
|
||||
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)
|
||||
/// <param name="companion">Where a GPR's JPEG is kept when it is not beside it (<see cref="DecodeRequest.Companion"/>).</param>
|
||||
public FileTier Probe(string path, string? companion = null)
|
||||
{
|
||||
using var stream = Open(path);
|
||||
var format = ImageSignature.Detect(stream, path);
|
||||
@@ -88,11 +99,38 @@ 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 && CompanionSize(path, companion) is var (cw, ch) && 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 with a GPR: <paramref name="companion"/> when the caller found it elsewhere (an import
|
||||
/// keeps it in a sequence of its own) and it is there, else the one beside the 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, string? companion = null)
|
||||
{
|
||||
if (companion is not null && File.Exists(companion)) return companion;
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Oriented size of the GPR's JPEG (see <see cref="CompanionJpeg"/>), or null when there is none.</summary>
|
||||
/// <exception cref="IOException">The JPEG cannot be read.</exception>
|
||||
private static (int Width, int Height)? CompanionSize(string path, string? companion)
|
||||
{
|
||||
if (CompanionJpeg(path, companion) is not { } file) return null;
|
||||
var jpeg = MetadataReader.Read(file);
|
||||
return jpeg.Format == ImageFileFormat.Jpeg ? jpeg.OrientedSize : null;
|
||||
}
|
||||
|
||||
private static FileStream Open(string path) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess);
|
||||
|
||||
@@ -147,7 +185,38 @@ 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 (<see cref="DecodeRequest.Companion"/>, else 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, request.Companion) 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
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
|
||||
namespace Titano.Core.Imaging;
|
||||
|
||||
/// <summary>How a frame's pixels were obtained (BRIEF §8.2). Logged per frame.</summary>
|
||||
@@ -28,13 +30,16 @@ public enum DecodePurpose
|
||||
/// <param name="ApplyOrientation">Rotate/flip according to the Exif orientation.</param>
|
||||
/// <param name="AllowPreview">Accept the embedded-preview tier when native decode is impossible.</param>
|
||||
/// <param name="ForcePreview">Use the embedded preview even when native decode is possible (fast paths).</param>
|
||||
/// <param name="Companion">The JPEG a GoPro wrote with this GPR when it is kept elsewhere than beside it (an import puts
|
||||
/// it in a sequence of its own); null looks beside the file. Other formats ignore it.</param>
|
||||
public sealed record DecodeRequest(
|
||||
string Path,
|
||||
int MaxLongEdge = 0,
|
||||
DecodePurpose Purpose = DecodePurpose.Render,
|
||||
bool ApplyOrientation = true,
|
||||
bool AllowPreview = true,
|
||||
bool ForcePreview = false);
|
||||
bool ForcePreview = false,
|
||||
string? Companion = null);
|
||||
|
||||
/// <summary>Decoded pixels plus how they were produced. Dispose to return the buffer to the pool.</summary>
|
||||
public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string decoder, int sourceWidth, int sourceHeight) : IDisposable
|
||||
@@ -53,6 +58,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 +78,24 @@ 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>
|
||||
/// <see cref="Probe(string, ImageFileFormat)"/> for a file whose camera companion (see
|
||||
/// <see cref="DecodeRequest.Companion"/>) is kept at <paramref name="companion"/>; a provider that uses no
|
||||
/// companion ignores it.
|
||||
/// </summary>
|
||||
FileTier Probe(string path, ImageFileFormat format, string? companion) => Probe(path, format);
|
||||
|
||||
/// <summary>Decodes or returns null when this provider cannot handle the specific file.</summary>
|
||||
DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -84,11 +116,51 @@ public sealed class ImageDecoder(IReadOnlyList<IImageDecoderProvider> providers)
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Decodes with the first provider that succeeds; null means <see cref="DecodeTier.Unavailable"/>.</summary>
|
||||
/// <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>
|
||||
/// <param name="companion">Where a GoPro GPR's JPEG is kept when it is not beside the file (<see cref="DecodeRequest.Companion"/>).</param>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public FileTier Probe(string path, ImageFileFormat format, string? companion = null)
|
||||
{
|
||||
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, companion);
|
||||
}
|
||||
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"/>: the providers read
|
||||
/// the file and none produced pixels. When one could not read it (locked by another program, vanished, a network
|
||||
/// read failed) and none produced pixels, nothing is known about the content, so that read error is thrown instead.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file could not be read and no provider produced pixels.</exception>
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var format = ImageFormatInfo.FromPath(request.Path);
|
||||
List<Exception>? errors = null;
|
||||
IOException? unread = null;
|
||||
foreach (var provider in Providers.OrderBy(p => p.TierFor(format.Format) ?? DecodeTier.Unavailable))
|
||||
{
|
||||
if (provider.TierFor(format.Format) is null) continue;
|
||||
@@ -105,8 +177,10 @@ public sealed class ImageDecoder(IReadOnlyList<IImageDecoderProvider> providers)
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or NotSupportedException or FormatException or InvalidOperationException or System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
(errors ??= []).Add(ex);
|
||||
if (ex is IOException io) unread ??= io;
|
||||
}
|
||||
}
|
||||
if (unread is not null) ExceptionDispatchInfo.Throw(unread);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,19 @@ public enum PreviewKind
|
||||
FullSize,
|
||||
}
|
||||
|
||||
/// <summary>Resolution a camera recorded its RAW at (BRIEF §9 sRaw flags).</summary>
|
||||
public enum RawSize
|
||||
{
|
||||
/// <summary>Full sensor resolution.</summary>
|
||||
Full,
|
||||
|
||||
/// <summary>Canon mRAW (sRAW1), Nikon RAW M.</summary>
|
||||
Medium,
|
||||
|
||||
/// <summary>Canon sRAW (sRAW2), Nikon RAW S and sRAW.</summary>
|
||||
Small,
|
||||
}
|
||||
|
||||
/// <summary>An embedded JPEG inside a RAW/TIFF/HEIF/JPEG(MPF) container.</summary>
|
||||
public sealed record EmbeddedPreview(long Offset, long Length, int Width, int Height, PreviewKind Kind);
|
||||
|
||||
@@ -59,6 +72,15 @@ public sealed record FrameMetadata
|
||||
public long? ShutterCount { get; init; }
|
||||
public bool? ImageStabilization { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Intervalometer hint from the MakerNote: true when the camera's own interval-shooting or time-lapse mode took the
|
||||
/// photo, false when the MakerNote names another drive mode, null when it says nothing (BRIEF §9).
|
||||
/// </summary>
|
||||
public bool? IntervalShooting { get; init; }
|
||||
|
||||
/// <summary>Resolution of a camera RAW from the MakerNote (sRAW/mRAW, RAW M/S); null when not recorded.</summary>
|
||||
public RawSize? RawSize { get; init; }
|
||||
|
||||
/// <summary>Embedded JPEGs, largest first.</summary>
|
||||
public IReadOnlyList<EmbeddedPreview> Previews { get; init; } = [];
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Canon MakerNote: a bare IFD whose offsets are relative to the enclosing TIFF header (also CR3 CMT3).</summary>
|
||||
/// <summary>
|
||||
/// Canon MakerNote: a bare IFD whose offsets are relative to the enclosing TIFF header (also CR3 CMT3). CameraSettings
|
||||
/// gives the stabiliser, the exposure mode and the sRAW size; Canon records no interval-shooting hint there.
|
||||
/// </summary>
|
||||
internal static class CanonMakerNote
|
||||
{
|
||||
private const ushort CameraSettings = 0x0001;
|
||||
@@ -11,7 +15,9 @@ internal static class CanonMakerNote
|
||||
private const ushort LensModel = 0x0095;
|
||||
private const ushort InternalSerialNumber = 0x0096;
|
||||
private const ushort ColorTemperature = 0x00AE;
|
||||
private const int ExposureModeIndex = 20;
|
||||
private const int ImageStabilizationIndex = 34;
|
||||
private const int SRawQualityIndex = 46;
|
||||
|
||||
public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
@@ -25,7 +31,21 @@ internal static class CanonMakerNote
|
||||
v.BodySerial ??= IfdValue.String(r, ifd, InternalSerialNumber);
|
||||
v.LensModel ??= IfdValue.String(r, ifd, LensModel);
|
||||
v.ColorTemperature ??= IfdValue.Int(r, ifd, ColorTemperature) is { } kelvin and > 0 and < 65535 ? kelvin : null;
|
||||
if (IfdValue.UInts(r, ifd, CameraSettings) is { Length: > ImageStabilizationIndex } settings)
|
||||
if (IfdValue.UInts(r, ifd, CameraSettings) is not { } settings) return;
|
||||
if (settings.Length > ExposureModeIndex)
|
||||
{
|
||||
// CanonExposureMode: 1 Program, 2 Tv, 3 Av, 4 Manual, 5 Depth-of-field AE, 6 M-Dep, 7 Bulb, 8 Fv; 0 Easy (scene).
|
||||
v.ExposureProgram ??= settings[ExposureModeIndex] switch
|
||||
{
|
||||
1 or 8 => 2,
|
||||
2 => 4,
|
||||
3 => 3,
|
||||
4 or 7 => 1,
|
||||
5 or 6 => 5,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
if (settings.Length > ImageStabilizationIndex)
|
||||
{
|
||||
// 0 Off, 1 On, 2 Shoot only, 3 Panning, 4 Dynamic; +256 for the "(2)" variants.
|
||||
v.ImageStabilization ??= (settings[ImageStabilizationIndex] & 0xFF) switch
|
||||
@@ -35,5 +55,16 @@ internal static class CanonMakerNote
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
if (settings.Length > SRawQualityIndex && m.Format is ImageFileFormat.Cr2 or ImageFileFormat.Cr3)
|
||||
{
|
||||
// SRAWQuality: 0 full-size RAW, 1 sRAW1 (mRAW), 2 sRAW2 (sRAW).
|
||||
v.RawSize ??= settings[SRawQualityIndex] switch
|
||||
{
|
||||
0 => RawSize.Full,
|
||||
1 => RawSize.Medium,
|
||||
2 => RawSize.Small,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ internal static class FujifilmMakerNote
|
||||
{
|
||||
private const ushort SerialNumber = 0x0010;
|
||||
private const ushort ColorTemperature = 0x1005;
|
||||
private const ushort PictureMode = 0x1031;
|
||||
private const ushort ImageStabilization = 0x1422;
|
||||
|
||||
public static void Parse(MetadataBuilder m, long start, ReadOnlySpan<byte> header)
|
||||
@@ -27,5 +28,17 @@ internal static class FujifilmMakerNote
|
||||
// [0] type (0 none, 1 optical, 2 sensor-shift, …), [1] mode (0 off, 1/2 on).
|
||||
if (IfdValue.UInts(r, ifd, ImageStabilization) is [var type, var mode, ..])
|
||||
v.ImageStabilization ??= type != 0 && mode != 0;
|
||||
// PictureMode: 0x300 Manual, 6 Program AE, 0x100 Aperture priority, 0x200 Shutter priority, 1 Portrait, 2 Landscape, 4 Sports.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, ifd, PictureMode) switch
|
||||
{
|
||||
0x300 => 1,
|
||||
6 => 2,
|
||||
0x100 => 3,
|
||||
0x200 => 4,
|
||||
4 => 6,
|
||||
1 => 7,
|
||||
2 => 8,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -9,4 +9,14 @@ internal sealed class MakerNoteValues
|
||||
public bool? ImageStabilization { get; set; }
|
||||
public int? Iso { get; set; }
|
||||
public int? ColorTemperature { get; set; }
|
||||
|
||||
/// <summary>The vendor's exposure mode as an Exif <c>ExposureProgram</c> value (1 manual, 2 program, 3 aperture
|
||||
/// priority, 4 shutter priority, 5 creative, 6 action, 7 portrait, 8 landscape); scene modes without one stay null.</summary>
|
||||
public int? ExposureProgram { get; set; }
|
||||
|
||||
/// <summary>True when the camera's own interval-shooting or time-lapse mode took the photo, false for another known mode.</summary>
|
||||
public bool? IntervalShooting { get; set; }
|
||||
|
||||
/// <summary>Resolution of a camera RAW (Canon sRAW/mRAW, Nikon RAW M/S).</summary>
|
||||
public RawSize? RawSize { get; set; }
|
||||
}
|
||||
@@ -3,14 +3,19 @@ using Titano.Core.Metadata.Tiff;
|
||||
namespace Titano.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Nikon MakerNote. Type 3 ("Nikon\0" + version 2.x) embeds its own TIFF header 10 bytes in; type 1
|
||||
/// ("Nikon\0" + version 1) has an IFD at +8 and headerless type 2 an IFD at +0, both relative to the Exif TIFF.</summary>
|
||||
/// ("Nikon\0" + version 1) has an IFD at +8 and headerless type 2 an IFD at +0, both relative to the Exif TIFF.
|
||||
/// The RAW size comes from ImageSizeRAW or the "small" NEF compression; the interval-shooting state lives only in the
|
||||
/// encrypted ShotInfo, which is not decoded.</summary>
|
||||
internal static class NikonMakerNote
|
||||
{
|
||||
private const ushort Iso = 0x0002;
|
||||
private const ushort SerialNumber = 0x001D;
|
||||
private const ushort VrInfo = 0x001F;
|
||||
private const ushort ImageSizeRaw = 0x003E;
|
||||
private const ushort Lens = 0x0084;
|
||||
private const ushort NefCompression = 0x0093;
|
||||
private const ushort ShutterCount = 0x00A7;
|
||||
private const uint SmallNef = 8;
|
||||
|
||||
public static void Parse(TiffReader exif, long start, ReadOnlySpan<byte> header, MetadataBuilder m)
|
||||
{
|
||||
@@ -50,5 +55,13 @@ internal static class NikonMakerNote
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
// ImageSizeRAW: 1 Large, 2 Medium, 3 Small; NEFCompression 8 is the older sRAW ("Small").
|
||||
v.RawSize ??= IfdValue.UInt(r, ifd, ImageSizeRaw) switch
|
||||
{
|
||||
1 => RawSize.Full,
|
||||
2 => RawSize.Medium,
|
||||
3 => RawSize.Small,
|
||||
_ => IfdValue.UInt(r, ifd, NefCompression) is SmallNef ? RawSize.Small : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,8 @@ namespace Titano.Core.Metadata.MakerNotes;
|
||||
/// <summary>
|
||||
/// Olympus / OM System MakerNote. "OLYMPUS\0II\3\0" (IFD at +12) and "OM SYSTEM\0\0\0II\4\0" (IFD at +16) use offsets
|
||||
/// relative to the MakerNote start and their own byte order; legacy "OLYMP\0" has its IFD at +8 relative to the
|
||||
/// Exif TIFF. Equipment (0x2010) gives serial and lens; CameraSettings (0x2020) gives the ORF preview and stabiliser.
|
||||
/// Exif TIFF. Equipment (0x2010) gives serial and lens; CameraSettings (0x2020) gives the ORF preview, the stabiliser
|
||||
/// and the exposure mode.
|
||||
/// </summary>
|
||||
internal static class OlympusMakerNote
|
||||
{
|
||||
@@ -17,6 +18,7 @@ internal static class OlympusMakerNote
|
||||
private const ushort PreviewImageValid = 0x0100;
|
||||
private const ushort PreviewImageStart = 0x0101;
|
||||
private const ushort PreviewImageLength = 0x0102;
|
||||
private const ushort ExposureMode = 0x0200;
|
||||
private const ushort ImageStabilization = 0x0604;
|
||||
|
||||
public static void Parse(TiffReader exif, long start, ReadOnlySpan<byte> header, MetadataBuilder m)
|
||||
@@ -52,6 +54,15 @@ internal static class OlympusMakerNote
|
||||
>= 1 and <= 4 => true,
|
||||
_ => null,
|
||||
};
|
||||
// 1 Manual, 2 Program, 3 Aperture priority, 4 Shutter priority, 5 Program shift.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, settings, ExposureMode) switch
|
||||
{
|
||||
1 => 1,
|
||||
2 or 5 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
_ => null,
|
||||
};
|
||||
if (IfdValue.UInt(r, settings, PreviewImageValid) != 0
|
||||
&& IfdValue.UInt(r, settings, PreviewImageStart) is { } offset and > 0
|
||||
&& IfdValue.UInt(r, settings, PreviewImageLength) is { } length and > 0)
|
||||
|
||||
@@ -2,13 +2,17 @@ using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Panasonic MakerNote: "Panasonic\0\0\0" then an IFD whose offsets are relative to the Exif TIFF.</summary>
|
||||
/// <summary>Panasonic MakerNote: "Panasonic\0\0\0" then an IFD whose offsets are relative to the Exif TIFF. Besides
|
||||
/// identity and stabiliser it gives the shooting mode and TimerRecording, which says whether the camera's time-lapse
|
||||
/// mode took the photo.</summary>
|
||||
internal static class PanasonicMakerNote
|
||||
{
|
||||
private const ushort ImageStabilization = 0x001A;
|
||||
private const ushort ShootingMode = 0x001F;
|
||||
private const ushort InternalSerialNumber = 0x0025;
|
||||
private const ushort ColorTempKelvin = 0x0044;
|
||||
private const ushort LensType = 0x0051;
|
||||
private const ushort TimerRecording = 0x0096;
|
||||
|
||||
public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
@@ -23,5 +27,24 @@ internal static class PanasonicMakerNote
|
||||
2 or (>= 4 and <= 7) or (>= 9 and <= 12) => true,
|
||||
_ => null,
|
||||
};
|
||||
// ShootingMode: 2 Portrait, 3 Scenery, 4 Sports, 6 Program, 7 Aperture priority, 8 Shutter priority, 11 Manual.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, ifd, ShootingMode) switch
|
||||
{
|
||||
11 => 1,
|
||||
6 => 2,
|
||||
7 => 3,
|
||||
8 => 4,
|
||||
4 => 6,
|
||||
2 => 7,
|
||||
3 => 8,
|
||||
_ => null,
|
||||
};
|
||||
// TimerRecording: 0 Off, 1 Time Lapse, 2 Stop-motion Animation, 3 Focus Bracketing.
|
||||
v.IntervalShooting ??= IfdValue.UInt(r, ifd, TimerRecording) switch
|
||||
{
|
||||
1 => true,
|
||||
0 or 2 or 3 => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,14 @@ using Titano.Core.Metadata.Tiff;
|
||||
namespace Titano.Core.Metadata.MakerNotes;
|
||||
|
||||
/// <summary>Sony MakerNote ("SONY DSC/CAM" 12-byte header or headerless; offsets relative to the Exif TIFF).
|
||||
/// Lens: the unencrypted LensSpec (BCD focal/aperture range); numeric LensType tables are not shipped.</summary>
|
||||
/// Lens: the unencrypted LensSpec (BCD focal/aperture range); numeric LensType tables are not shipped. Exposure mode
|
||||
/// from ExposureMode (0xB041).</summary>
|
||||
internal static class SonyMakerNote
|
||||
{
|
||||
private const ushort ColorTemperature = 0xB021;
|
||||
private const ushort ImageStabilization = 0xB026;
|
||||
private const ushort LensSpec = 0xB02A;
|
||||
private const ushort ExposureMode = 0xB041;
|
||||
|
||||
public static void Parse(TiffReader r, Ifd ifd, MetadataBuilder m)
|
||||
{
|
||||
@@ -22,6 +24,18 @@ internal static class SonyMakerNote
|
||||
1 => true,
|
||||
_ => null,
|
||||
};
|
||||
// 0 Program AE, 1 Portrait, 3 Sports, 5 Landscape, 7 Aperture priority, 8 Shutter priority, 15 Manual.
|
||||
v.ExposureProgram ??= IfdValue.UInt(r, ifd, ExposureMode) switch
|
||||
{
|
||||
15 => 1,
|
||||
0 => 2,
|
||||
7 => 3,
|
||||
8 => 4,
|
||||
3 => 6,
|
||||
1 => 7,
|
||||
5 => 8,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bytes 1–2 short focal, 3–4 long focal (BCD mm), 5–6 apertures (BCD ×10); flags 0 and 7 are not decoded.</summary>
|
||||
|
||||
@@ -153,7 +153,7 @@ internal sealed class MetadataBuilder
|
||||
FocalLength = FocalLength,
|
||||
FocalLength35 = FocalLength35,
|
||||
ExposureBias = ExposureBias,
|
||||
ExposureProgram = ExposureProgram,
|
||||
ExposureProgram = ExposureProgram ?? MakerNote.ExposureProgram,
|
||||
MeteringMode = MeteringMode,
|
||||
WhiteBalanceMode = WhiteBalanceMode,
|
||||
ColorTemperature = MakerNote.ColorTemperature,
|
||||
@@ -167,6 +167,8 @@ internal sealed class MetadataBuilder
|
||||
Label = Xmp.Label,
|
||||
ShutterCount = MakerNote.ShutterCount,
|
||||
ImageStabilization = MakerNote.ImageStabilization,
|
||||
IntervalShooting = MakerNote.IntervalShooting,
|
||||
RawSize = MakerNote.RawSize,
|
||||
Previews = ResolvePreviews(main is { } m ? Math.Max(m.Width, m.Height) : 0),
|
||||
Warnings = _warnings.ToArray(),
|
||||
};
|
||||
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@ public enum FrameFlags
|
||||
Undecodable = 32,
|
||||
Black = 64,
|
||||
White = 128,
|
||||
|
||||
/// <summary>
|
||||
/// The camera's own interval-shooting or time-lapse mode took the frame (MakerNote hint, BRIEF §9): a capture fact,
|
||||
/// not a problem; its pauses were deliberate (§10.3 adaptive timing).
|
||||
/// </summary>
|
||||
Intervalometer = 256,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
|
||||
Reference in new issue
Block a user