using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
namespace Titano.Core.Archiving;
/// A JPEG made from a frame.
public sealed record EncodedImage(byte[] Jpeg, int Width, int Height, DecodeTier Tier);
///
/// 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. says how the pixels were obtained.
///
public sealed class FrameImageRenderer(ImageDecoder decoder)
{
public const int ThumbnailLongEdge = 320;
public const int ThumbnailQuality = 80;
/// A 320 px q80 thumbnail, or null when no decoder can read the frame.
/// Where a GPR's JPEG is kept when it is not beside it ().
public EncodedImage? Thumbnail(SequencePaths sequence, SidecarFrame frame, CancellationToken cancellationToken = default, string? companion = null)
{
using var decoded = Decode(sequence.File(frame.File), frame, ThumbnailLongEdge, DecodePurpose.Thumbnail, preferPreview: true, companion, cancellationToken);
if (decoded is null) return null;
using var small = Resampler.Thumbnail(decoded.Pixels, ThumbnailLongEdge);
return Encode(small, new JpegEncodeOptions { Quality = ThumbnailQuality }, decoded.Tier);
}
/// A proxy at the policy's long edge and quality with capture time and camera in its Exif; null when undecodable.
/// Where a GPR's JPEG is kept when it is not beside it ().
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, 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);
using var resized = Resampler.Resize(source, w, h);
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata
{
Make = camera?.Make,
Model = camera?.Model,
BodySerial = camera?.Serial,
CapturedAt = frame.CapturedAt,
UtcOffsetMinutes = frame.UtcOffset,
ExposureTime = frame.Exposure,
FNumber = frame.FNumber,
Iso = frame.Iso,
FocalLength = frame.Focal,
ExposureBias = frame.Bias,
Software = "Titano",
});
// The encoder takes the APP1 payload; ExifWriter returns the whole segment (marker and length first).
return Encode(resized, new JpegEncodeOptions { Quality = policy.Quality, App1Segments = [exif[4..]] }, decoded.Tier);
}
private static EncodedImage Encode(ImageBuffer pixels, JpegEncodeOptions options, DecodeTier tier) =>
new(JpegEncoder.Encode(pixels, options), pixels.Width, pixels.Height, tier);
///
/// The frame's pixels: a JPEG through the managed decoder, the stored embedded preview when
/// and it reaches (a smaller one would be upscaled or leave the thumbnail short), then
/// the host's decoders (with the GPR's ), and the stored preview as the last resort. Null
/// when nothing decodes.
///
/// The file could not be read.
private DecodedFrame? Decode(string path, SidecarFrame frame, int maxLongEdge, DecodePurpose purpose, bool preferPreview, string? companion,
CancellationToken cancellationToken)
{
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 (preview ?? ReadPreview(path, frame)) is { } fallback ? DecodeJpeg(fallback, maxLongEdge, frame.Orientation, DecodeTier.EmbeddedPreview) : null;
}
///
/// Whether the stored preview's long edge reaches , 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.
///
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)
{
ImageBuffer decoded;
try
{
decoded = JpegDecoder.DecodeToLinear(data, new JpegDecodeOptions { MaxLongEdge = System.Math.Max(0, maxLongEdge) }, expandGray: true);
}
catch (InvalidDataException)
{
return null;
}
if (orientation is <= 1 or > 8) return new DecodedFrame(decoded, tier);
using (decoded) return new DecodedFrame(PixelConvert.ApplyOrientation(decoded, orientation), tier);
}
private static byte[]? ReadPreview(string path, SidecarFrame frame)
{
if (frame.PreviewOffset is not { } offset || frame.PreviewLength is not ({ } length and > 0 and < int.MaxValue)) return null;
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, FileOptions.RandomAccess);
if (offset < 0 || offset + length > stream.Length) return null;
var data = new byte[length];
stream.Position = offset;
stream.ReadExactly(data);
return data;
}
private sealed record DecodedFrame(ImageBuffer Pixels, DecodeTier Tier) : IDisposable
{
public void Dispose() => Pixels.Dispose();
}
}