using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Codecs.Raw;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Diagnostics;
using Chronos.Core.Metadata;
namespace Chronos.Core.Imaging.Decoders;
///
/// 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 ; every other
/// 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 says an import put it) when that is larger
/// (BRIEF §8.1; VC-5 is out of scope); nothing for formats without either.
/// fast paths: JPEG DCT scaling and RAW CFA binning when
/// allows, bilinear demosaicing for thumbnails and analysis, and to skip native
/// RAW development. Results fit within MaxLongEdge (never upscaled) and are always RGB.
///
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"];
/// The provider whose probes read headers (); it holds nothing else.
private static readonly ManagedDecoderProvider HeaderProbes = new() { ReadsHeaders = true };
public string Name => "managed";
///
/// Whether probes read the headers of JPEG, PNG and TIFF files too ()
/// and find unreadable what refuses before decoding pixels: an encoding, layout or colour model its
/// decoders do not read (a CMYK, CIELab or palette TIFF, a compression it lacks, arithmetic coding), more pixels than
/// they take, a file larger than it reads whole. A conversion's decoders do ():
/// its dry run promises what it lists. Off, those files are not even opened.
///
public bool ReadsHeaders { get; init; }
/// A provider whose probes read the headers of JPEG, PNG and TIFF files ().
public IImageDecoderProvider WithHeaderProbes() => ReadsHeaders ? this : HeaderProbes;
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;
}
/// Decodes the file, or returns null when it has no decodable pixels here (no native decoder and no preview).
/// A JPEG, PNG or TIFF is malformed.
/// The file cannot be read.
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;
}
///
/// The tier for a file whose signature format is already known (the index's): JPEG, PNG and TIFF are taken to decode
/// natively, so only RAW and HEIF files are opened, unless the provider .
///
/// With : a JPEG, PNG or TIFF that
/// refuses from its headers ().
public FileTier Probe(string path, ImageFileFormat format) => Probe(path, format, null);
///
/// Where a GPR's JPEG is kept when it is not beside it ().
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);
if (ReadsHeaders) return ReadHeaders(path, companion);
return new FileTier(format, DecodeTier.Native, DecoderName(family), null, 0, 0);
}
///
/// The tier of the file at from its headers, as would reach it: a JPEG, PNG
/// or TIFF (by its signature) is native, at its oriented size, only when its decoder takes what its headers describe
/// (, , )
/// and a JPEG or PNG is no larger than one array holds (it is read whole); any other file is probed as
/// probes it.
///
/// The file is malformed, or holds what does not decode.
/// The file cannot be read.
private FileTier ReadHeaders(string path, string? companion)
{
using (var stream = Open(path))
{
var format = ImageSignature.Detect(stream, path);
var family = ImageFormatInfo.Of(format).Family;
if (family is ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff)
{
// JPEG and PNG files are decoded from one array holding them whole.
if (family != ImageFamily.Tiff && stream.Length > Array.MaxLength) throw new InvalidDataException($"{format}: the file is larger than one array holds");
var (width, height) = family switch
{
ImageFamily.Jpeg => JpegSize(stream),
ImageFamily.Png => PngSize(stream),
_ => TiffImageReader.ReadInfo(stream),
};
(width, height) = PixelConvert.OrientedSize(width, height, MetadataReader.Read(stream, path).Orientation);
return new FileTier(format, DecodeTier.Native, DecoderName(family), null, width, height);
}
}
// The signature says another format than the index: probed as any file.
return Probe(path, companion);
}
private static string DecoderName(ImageFamily family) => family switch { ImageFamily.Jpeg => "managed-jpeg", ImageFamily.Png => "managed-png", _ => "managed-tiff" };
/// The size of a JPEG its decoder takes, from the markers before its first scan.
private static (int Width, int Height) JpegSize(Stream stream)
{
var scanner = new Metadata.Jpeg.JpegParser.SegmentScanner(stream, 0, stream.Length, long.MaxValue);
if (!scanner.StartsWithSoi()) throw new InvalidDataException("JPEG: missing SOI marker");
var end = 0L;
while (scanner.Next(out var segment))
{
if (segment.Marker is 0xD9) break;
if (segment.Marker != 0xDA) continue;
end = segment.Payload + segment.Length;
break;
}
if (end == 0) throw new InvalidDataException("JPEG: no scan");
var head = new byte[end];
stream.Position = 0;
stream.ReadExactly(head);
var info = JpegDecoder.ReadDecodableInfo(head);
return (info.Width, info.Height);
}
/// The size of a PNG its decoder takes, from its header chunk.
private static (int Width, int Height) PngSize(Stream stream)
{
var head = new byte[33];
stream.Position = 0;
if (stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false) < head.Length) throw new InvalidDataException("PNG: missing signature or IHDR");
var info = PngDecoder.ReadInfo(head);
if ((long)info.Width * info.Height > PngDecoder.MaxPixels) throw new InvalidDataException($"PNG: {info.Width}x{info.Height} exceeds the pixel limit");
return (info.Width, info.Height);
}
/// The tier this provider would use for the file at , without decoding pixels.
/// Where a GPR's JPEG is kept when it is not beside it ().
public FileTier Probe(string path, string? companion = null)
{
using var stream = Open(path);
var format = ImageSignature.Detect(stream, path);
var family = ImageFormatInfo.Of(format).Family;
if (family is ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff)
{
var (w, h) = MetadataReader.Read(stream, path).OrientedSize;
return new FileTier(format, DecodeTier.Native, DecoderName(family), null, w, h);
}
if (family is not (ImageFamily.Dng or ImageFamily.CameraRaw or ImageFamily.Heif))
return new FileTier(format, DecodeTier.Unavailable, null, $"no managed decoder for {format}", 0, 0);
string reason;
if (RawDecoder.Formats.Contains(format))
{
var probe = RawDecoder.Probe(stream, path);
if (probe.Info is { } info) return new FileTier(format, DecodeTier.Native, info.Decoder, null, info.Width, info.Height);
reason = probe.Reason ?? "unsupported";
}
else
{
reason = $"no managed decoder for {format}";
}
var metadata = MetadataReader.Read(stream, path);
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);
}
///
/// The JPEG a GoPro writes with a GPR: 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, .JPG), or
/// null. Only the usual spellings are tried, so a folder of thousands of frames is never listed once per frame.
///
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;
}
/// Oriented size of the GPR's JPEG (see ), or null when there is none.
/// The JPEG cannot be read.
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);
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.PreferPreview && !request.ForcePreview && request.MaxLongEdge > 0 && RawDecoder.Formats.Contains(format)
&& Preview(stream, request, adequateOnly: true, cancellationToken) is { } quick)
return quick.AsChoice();
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");
}
}
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);
}
///
/// GPR's pixel source: the GoPro's own JPEG (, 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.
///
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");
}
/// 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 ), decoded with DCT scaling and oriented like the
/// main image.
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");
}
/// Applies orientation, fits within MaxLongEdge, and wraps the result (takes ownership of ).
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;
}
}