feat(imaging): managed decoder provider, decoder chains and format tiers
ManagedDecoderProvider decodes JPEG/PNG/TIFF natively, DNG and the supported RAWs through RawDecoder, and falls back to the largest suitable embedded JPEG (oriented like the main image) for other RAWs, CR3, HEIF and unsupported bodies. Requests use JPEG DCT scaling, CFA binning when MaxLongEdge allows, bilinear demosaic for thumbnails and analysis, and ForcePreview. DecoderFactory builds the client (WIC then managed) and server chains and the per-format tier table; Probe gives the per-file tier without decoding. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
9 files changed
+493
-8
No files matched your search
@@ -21,9 +21,10 @@ public sealed record RawDecodeOptions
|
||||
|
||||
public DemosaicQuality Quality { get; init; } = DemosaicQuality.Best;
|
||||
|
||||
/// <summary>Bin CFA blocks into RGB pixels instead of demosaicing: half size for Bayer, one third for X-Trans.
|
||||
/// Ignored for linear (already demosaiced) data and for patterns that cannot be binned.</summary>
|
||||
public bool Binning { get; init; }
|
||||
/// <summary>Target long edge (0 = full size). When the CFA can be binned (half size for Bayer, one third for X-Trans)
|
||||
/// and the binned image keeps at least this long edge, blocks are binned into RGB pixels instead of demosaiced. The
|
||||
/// result is not resized further; linear (already demosaiced) data is always developed at full size.</summary>
|
||||
public int MaxLongEdge { get; init; }
|
||||
|
||||
/// <summary>Rotate/flip according to the file's orientation.</summary>
|
||||
public bool ApplyOrientation { get; init; } = true;
|
||||
|
||||
@@ -87,7 +87,8 @@ internal static class RawDeveloper
|
||||
if (stage.Cfa is { } cfa)
|
||||
{
|
||||
ScaleMosaic(stage.Pixels, cfa, wb, dop, cancellationToken);
|
||||
var bin = options.Binning ? cfa.BinSize : 0;
|
||||
var bin = cfa.BinSize;
|
||||
if (options.MaxLongEdge <= 0 || int.Max(stage.Width, stage.Height) / int.Max(bin, 1) < options.MaxLongEdge) bin = 0;
|
||||
if (bin > 0)
|
||||
{
|
||||
rgb = Demosaic.Bin(stage.Pixels, cfa, bin, dop, cancellationToken);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace Titano.Core.Imaging.Decoders;
|
||||
|
||||
/// <summary>One row of the "Settings › Formats" table: the best tier a decoder chain reaches for a format, and who
|
||||
/// delivers it.</summary>
|
||||
/// <param name="Format">Format with its family and extensions.</param>
|
||||
/// <param name="Tier">Best tier across the chain's providers.</param>
|
||||
/// <param name="Provider">Name of the provider delivering that tier ("wic", "managed"), null when unavailable.</param>
|
||||
public sealed record FormatSupport(ImageFormatInfo Format, DecodeTier Tier, string? Provider);
|
||||
|
||||
/// <summary>
|
||||
/// Builds the decoder chains of BRIEF §8.2. The desktop client tries the Windows provider (WIC) first and the managed
|
||||
/// one second (<see cref="ImageDecoder"/> keeps that order among providers offering the same tier); the server and
|
||||
/// render nodes without WIC use the managed provider alone.
|
||||
/// </summary>
|
||||
public static class DecoderFactory
|
||||
{
|
||||
/// <summary>Client chain: <paramref name="windowsProvider"/> (WIC on Windows; null elsewhere) then managed.</summary>
|
||||
public static ImageDecoder CreateClient(IImageDecoderProvider? windowsProvider) =>
|
||||
new(windowsProvider is null ? [new ManagedDecoderProvider()] : [windowsProvider, new ManagedDecoderProvider()]);
|
||||
|
||||
/// <summary>Server chain: managed decoders only.</summary>
|
||||
public static ImageDecoder CreateServer() => new([new ManagedDecoderProvider()]);
|
||||
|
||||
/// <summary>Per-format tier on this machine for every known format, in <see cref="ImageFormatInfo.Known"/> order.</summary>
|
||||
public static IReadOnlyList<FormatSupport> DescribeFormats(ImageDecoder decoder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
var rows = new List<FormatSupport>();
|
||||
foreach (var info in ImageFormatInfo.Known)
|
||||
{
|
||||
var tier = DecodeTier.Unavailable;
|
||||
string? provider = null;
|
||||
foreach (var p in decoder.Providers)
|
||||
{
|
||||
if (p.TierFor(info.Format) is { } t && t < tier)
|
||||
{
|
||||
tier = t;
|
||||
provider = p.Name;
|
||||
}
|
||||
}
|
||||
rows.Add(new FormatSupport(info, tier, provider));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Codecs.Png;
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Codecs.Tiff;
|
||||
using Titano.Core.Diagnostics;
|
||||
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>
|
||||
public sealed record FileTier(ImageFileFormat Format, DecodeTier Tier, string? Decoder, string? Reason);
|
||||
|
||||
/// <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.
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public sealed class ManagedDecoderProvider : IImageDecoderProvider
|
||||
{
|
||||
private const string LogCategory = "Decode";
|
||||
private const int FileBufferSize = 1 << 16;
|
||||
private const long MaxPreviewBytes = 256L << 20;
|
||||
|
||||
public string Name => "managed";
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format)
|
||||
{
|
||||
var info = ImageFormatInfo.Of(format);
|
||||
if (format is ImageFileFormat.Jpeg or ImageFileFormat.Png or ImageFileFormat.Tiff || RawDecoder.Formats.Contains(format)) return DecodeTier.Native;
|
||||
return info.Family is ImageFamily.CameraRaw or ImageFamily.Heif ? DecodeTier.EmbeddedPreview : null;
|
||||
}
|
||||
|
||||
/// <summary>Decodes the file, or returns null when it has no decodable pixels here (no native decoder and no preview).</summary>
|
||||
/// <exception cref="InvalidDataException">A JPEG, PNG or TIFF is malformed.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using var stream = Open(request.Path);
|
||||
var format = ImageSignature.Detect(stream, request.Path);
|
||||
var family = ImageFormatInfo.Of(format).Family;
|
||||
var result = family switch
|
||||
{
|
||||
ImageFamily.Jpeg => request.ForcePreview && Preview(stream, request, adequateOnly: true, cancellationToken) is { } p ? p : Jpeg(stream, request),
|
||||
ImageFamily.Png => Png(stream, request),
|
||||
ImageFamily.Tiff => Tiff(stream, request),
|
||||
ImageFamily.Dng or ImageFamily.CameraRaw => Raw(stream, format, request, cancellationToken),
|
||||
ImageFamily.Heif => request.AllowPreview || request.ForcePreview ? Preview(stream, request, adequateOnly: false, cancellationToken) : null,
|
||||
_ => null,
|
||||
};
|
||||
Log.Debug(LogCategory, $"{Path.GetFileName(request.Path)}: {(result is null ? "unavailable" : $"{result.Tier} via {result.Decoder}")}");
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The tier this provider would use for the file at <paramref name="path"/>, without decoding pixels.</summary>
|
||||
public FileTier Probe(string path)
|
||||
{
|
||||
using var stream = Open(path);
|
||||
var format = ImageSignature.Detect(stream, path);
|
||||
var family = ImageFormatInfo.Of(format).Family;
|
||||
switch (family)
|
||||
{
|
||||
case ImageFamily.Jpeg:
|
||||
return new FileTier(format, DecodeTier.Native, "managed-jpeg", null);
|
||||
case ImageFamily.Png:
|
||||
return new FileTier(format, DecodeTier.Native, "managed-png", null);
|
||||
case ImageFamily.Tiff:
|
||||
return new FileTier(format, DecodeTier.Native, "managed-tiff", null);
|
||||
}
|
||||
string? reason = null;
|
||||
if (family is ImageFamily.Dng or ImageFamily.CameraRaw && RawDecoder.Formats.Contains(format))
|
||||
{
|
||||
var probe = RawDecoder.Probe(stream, path);
|
||||
if (probe.IsSupported) return new FileTier(format, DecodeTier.Native, probe.Info!.Decoder, null);
|
||||
reason = probe.Reason;
|
||||
}
|
||||
else if (family is ImageFamily.Dng or ImageFamily.CameraRaw or ImageFamily.Heif)
|
||||
{
|
||||
reason = $"no managed decoder for {format}";
|
||||
}
|
||||
else
|
||||
{
|
||||
return new FileTier(format, DecodeTier.Unavailable, null, $"no managed decoder for {format}");
|
||||
}
|
||||
var previews = MetadataReader.Read(stream, path).Previews;
|
||||
return previews.Count > 0
|
||||
? new FileTier(format, DecodeTier.EmbeddedPreview, "managed-preview", reason)
|
||||
: new FileTier(format, DecodeTier.Unavailable, null, reason + "; no embedded preview");
|
||||
}
|
||||
|
||||
private static FileStream Open(string path) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileBufferSize, FileOptions.RandomAccess);
|
||||
|
||||
private static DecodedImage Jpeg(Stream stream, DecodeRequest request)
|
||||
{
|
||||
var data = ReadAll(stream);
|
||||
var info = JpegDecoder.ReadInfo(data);
|
||||
var image = JpegDecoder.DecodeToLinear(data, new JpegDecodeOptions { MaxLongEdge = request.MaxLongEdge }, expandGray: true);
|
||||
var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, request.Path).Orientation : 1;
|
||||
return Finish(image, orientation, request, info.Width, info.Height, DecodeTier.Native, "managed-jpeg");
|
||||
}
|
||||
|
||||
private static DecodedImage Png(Stream stream, DecodeRequest request)
|
||||
{
|
||||
var data = ReadAll(stream);
|
||||
var image = PngDecoder.DecodeToLinear(data, expandGray: true);
|
||||
var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, request.Path).Orientation : 1;
|
||||
return Finish(image, orientation, request, image.Width, image.Height, DecodeTier.Native, "managed-png");
|
||||
}
|
||||
|
||||
private static DecodedImage Tiff(Stream stream, DecodeRequest request)
|
||||
{
|
||||
var decoded = TiffImageReader.Decode(stream);
|
||||
var image = decoded;
|
||||
if (decoded.Channels == 1)
|
||||
{
|
||||
image = PixelConvert.GrayToRgb(decoded);
|
||||
decoded.Dispose();
|
||||
}
|
||||
var orientation = request.ApplyOrientation ? MetadataReader.Read(stream, request.Path).Orientation : 1;
|
||||
return Finish(image, orientation, request, image.Width, image.Height, DecodeTier.Native, "managed-tiff");
|
||||
}
|
||||
|
||||
private static DecodedImage? Raw(Stream stream, ImageFileFormat format, DecodeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!request.ForcePreview && RawDecoder.Formats.Contains(format))
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = new RawDecodeOptions
|
||||
{
|
||||
Quality = request.Purpose is DecodePurpose.Thumbnail or DecodePurpose.Analysis ? DemosaicQuality.Draft : DemosaicQuality.Best,
|
||||
MaxLongEdge = request.MaxLongEdge,
|
||||
ApplyOrientation = request.ApplyOrientation,
|
||||
};
|
||||
var raw = RawDecoder.Decode(stream, request.Path, options, cancellationToken);
|
||||
foreach (var warning in raw.Warnings) Log.Debug(LogCategory, $"{Path.GetFileName(request.Path)}: {warning}");
|
||||
return Finish(raw.Image, 1, request, raw.Info.Width, raw.Info.Height, DecodeTier.Native, raw.Info.Decoder, oriented: true);
|
||||
}
|
||||
catch (InvalidDataException ex) when (request.AllowPreview)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Embedded-preview tier: the smallest preview whose long edge still reaches MaxLongEdge (the largest when none
|
||||
/// does or no limit is set; null then if <paramref name="adequateOnly"/>), decoded with DCT scaling and oriented like the
|
||||
/// main image.</summary>
|
||||
private static DecodedImage? Preview(Stream stream, DecodeRequest request, bool adequateOnly, CancellationToken cancellationToken)
|
||||
{
|
||||
var metadata = MetadataReader.Read(stream, request.Path, cancellationToken: cancellationToken);
|
||||
if (metadata.Previews.Count == 0) return null;
|
||||
EmbeddedPreview? adequate = null;
|
||||
foreach (var p in metadata.Previews)
|
||||
{
|
||||
if (request.MaxLongEdge > 0 && int.Max(p.Width, p.Height) >= request.MaxLongEdge) adequate = p;
|
||||
}
|
||||
if (adequate is null && adequateOnly) return null;
|
||||
var preview = adequate ?? metadata.Previews[0];
|
||||
if (preview.Length > MaxPreviewBytes || preview.Offset < 0 || preview.Offset > stream.Length - preview.Length)
|
||||
throw new InvalidDataException("Preview: embedded JPEG outside the file");
|
||||
var data = new byte[preview.Length];
|
||||
stream.Position = preview.Offset;
|
||||
stream.ReadExactly(data);
|
||||
var image = JpegDecoder.DecodeToLinear(data, new JpegDecodeOptions { MaxLongEdge = request.MaxLongEdge }, expandGray: true);
|
||||
var orientation = request.ApplyOrientation ? metadata.Orientation : 1;
|
||||
return Finish(image, orientation, request, preview.Width, preview.Height, DecodeTier.EmbeddedPreview, "managed-preview");
|
||||
}
|
||||
|
||||
/// <summary>Applies orientation, fits within MaxLongEdge, and wraps the result (takes ownership of <paramref name="image"/>).</summary>
|
||||
private static DecodedImage Finish(ImageBuffer image, int orientation, DecodeRequest request, int sourceWidth, int sourceHeight, DecodeTier tier, string decoder, bool oriented = false)
|
||||
{
|
||||
var current = image;
|
||||
try
|
||||
{
|
||||
if (orientation is >= 2 and <= 8)
|
||||
{
|
||||
var rotated = PixelConvert.ApplyOrientation(current, orientation);
|
||||
current.Dispose();
|
||||
current = rotated;
|
||||
}
|
||||
if (!oriented) (sourceWidth, sourceHeight) = PixelConvert.OrientedSize(sourceWidth, sourceHeight, orientation);
|
||||
if (request.MaxLongEdge > 0)
|
||||
{
|
||||
var (w, h) = Resampler.FitWithin(current.Width, current.Height, request.MaxLongEdge);
|
||||
if (w != current.Width || h != current.Height)
|
||||
{
|
||||
var filter = request.Purpose == DecodePurpose.Thumbnail ? ResampleFilter.Box : ResampleFilter.Auto;
|
||||
var resized = Resampler.Resize(current, w, h, filter);
|
||||
current.Dispose();
|
||||
current = resized;
|
||||
}
|
||||
}
|
||||
return new DecodedImage(current, tier, decoder, sourceWidth, sourceHeight);
|
||||
}
|
||||
catch
|
||||
{
|
||||
current.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] ReadAll(Stream stream)
|
||||
{
|
||||
if (stream.Length > int.MaxValue) throw new InvalidDataException("Image file too large");
|
||||
var data = new byte[stream.Length];
|
||||
stream.Position = 0;
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user