merge: RAW/DNG decoding, managed decoder provider, frame window and thumbnails
# Conflicts: # src/Titano.Tools/Program.cs
This commit is contained in:
40 files changed
+8350
No files matched your search
@@ -0,0 +1,239 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Codecs.Dng;
|
||||
|
||||
/// <summary>Result of <see cref="DngColorProfile.Solve"/>: white balance and the matrix to linear Rec.709.</summary>
|
||||
/// <param name="CameraNeutral">Camera response to the scene white, largest entry 1 (white-balance multipliers are its reciprocals).</param>
|
||||
/// <param name="White">Scene white chromaticity found by the iterative solve.</param>
|
||||
/// <param name="Temperature">Correlated colour temperature of <paramref name="White"/> (Robertson), in kelvin.</param>
|
||||
/// <param name="BalancedToRec709">White-balanced camera RGB (raw ÷ neutral) → linear Rec.709 (D65), BaselineExposure included.</param>
|
||||
/// <param name="BalancedToXyz">White-balanced camera RGB → CIE XYZ (D65 adapted, Y = 1 at white), for demosaic metrics.</param>
|
||||
public sealed record DngColorSolution(Vector3D CameraNeutral, Chromaticity White, double Temperature, Matrix3 BalancedToRec709, Matrix3 BalancedToXyz);
|
||||
|
||||
/// <summary>
|
||||
/// Camera colour description of a DNG (or of a native RAW with a tabulated matrix) and the colour math of DNG 1.6
|
||||
/// chapter 6 "Mapping Camera Color Space to CIE XYZ Space": ColorMatrix1/2 and CameraCalibration1/2 interpolated by
|
||||
/// inverse correlated colour temperature between CalibrationIlluminant1/2, AnalogBalance, the iterative white solve for
|
||||
/// AsShotNeutral (or the neutral implied by AsShotWhiteXY), ForwardMatrix1/2 when present, then Bradford adaptation from
|
||||
/// the D50 profile connection space to D65 and the XYZ → Rec.709 matrix.
|
||||
/// </summary>
|
||||
public sealed class DngColorProfile
|
||||
{
|
||||
/// <summary>Default scene white when the file records none: D55, as the DNG SDK assumes.</summary>
|
||||
public static Chromaticity DefaultWhite { get; } = new(0.3324, 0.3474);
|
||||
|
||||
public Matrix3? ColorMatrix1 { get; init; }
|
||||
public Matrix3? ColorMatrix2 { get; init; }
|
||||
public Matrix3? CameraCalibration1 { get; init; }
|
||||
public Matrix3? CameraCalibration2 { get; init; }
|
||||
public Matrix3? ForwardMatrix1 { get; init; }
|
||||
public Matrix3? ForwardMatrix2 { get; init; }
|
||||
|
||||
/// <summary>Exif LightSource codes of the two calibrations (0 = unknown).</summary>
|
||||
public int CalibrationIlluminant1 { get; init; }
|
||||
|
||||
public int CalibrationIlluminant2 { get; init; }
|
||||
public Vector3D AnalogBalance { get; init; } = new(1, 1, 1);
|
||||
public Vector3D? AsShotNeutral { get; init; }
|
||||
public Chromaticity? AsShotWhite { get; init; }
|
||||
|
||||
/// <summary>Exposure offset in EV applied to the rendered values (DNG BaselineExposure).</summary>
|
||||
public double BaselineExposure { get; init; }
|
||||
|
||||
/// <summary>Solves white balance and builds the output matrices.</summary>
|
||||
/// <exception cref="InvalidDataException">No usable colour matrix (missing, singular or non-finite).</exception>
|
||||
public DngColorSolution Solve(ICollection<string> warnings)
|
||||
{
|
||||
if (ColorMatrix1 is not { } cm1 || !Usable(cm1)) throw new InvalidDataException("DNG: ColorMatrix1 missing or singular");
|
||||
Chromaticity white;
|
||||
Vector3D neutral;
|
||||
if (AsShotNeutral is { } asShot && asShot.X > 0 && asShot.Y > 0 && asShot.Z > 0)
|
||||
{
|
||||
neutral = Normalize(asShot);
|
||||
white = NeutralToXy(neutral);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (AsShotWhite is { } xy && xy.X > 0 && xy.Y > 0 && xy.X + xy.Y < 1)
|
||||
{
|
||||
white = xy;
|
||||
}
|
||||
else
|
||||
{
|
||||
white = DefaultWhite;
|
||||
warnings.Add("DNG: no as-shot white balance; D55 assumed");
|
||||
}
|
||||
neutral = Normalize(XyzToCamera(white) * white.ToXyz());
|
||||
}
|
||||
// Clamp like the DNG SDK so a degenerate neutral cannot produce infinite multipliers.
|
||||
neutral = new Vector3D(double.Clamp(neutral.X, 0.001, 1), double.Clamp(neutral.Y, 0.001, 1), double.Clamp(neutral.Z, 0.001, 1));
|
||||
|
||||
var cameraToPcs = CameraToPcs(white, neutral);
|
||||
var d50 = Chromaticity.D50.ToXyz();
|
||||
var d65 = Chromaticity.D65.ToXyz();
|
||||
var balancedToD65 = Matrix3.BradfordAdaptation(d50, d65) * cameraToPcs * Matrix3.Diagonal(neutral.X, neutral.Y, neutral.Z);
|
||||
var gain = double.Exp2(BaselineExposure);
|
||||
var toRec709 = Scale(Matrix3.XyzToRec709 * balancedToD65, gain);
|
||||
return new DngColorSolution(neutral, white, Temperature(white), toRec709, balancedToD65);
|
||||
}
|
||||
|
||||
/// <summary>XYZ → camera at the given scene white: AnalogBalance · CameraCalibration · ColorMatrix, both interpolated
|
||||
/// by the white's inverse temperature (DNG §6 "Translating White Balance xy Coordinates to Camera Neutral").</summary>
|
||||
public Matrix3 XyzToCamera(Chromaticity white)
|
||||
{
|
||||
var g = Weight(white);
|
||||
var cm = Blend(ColorMatrix1!.Value, ColorMatrix2, g);
|
||||
var cc = Blend(CameraCalibration1 ?? Matrix3.Identity, CameraCalibration2 ?? (CameraCalibration1 is null ? null : Matrix3.Identity), g);
|
||||
return Matrix3.Diagonal(AnalogBalance.X, AnalogBalance.Y, AnalogBalance.Z) * cc * cm;
|
||||
}
|
||||
|
||||
/// <summary>Iterative white solve of DNG §6 "Translating Camera Neutral Coordinates to White Balance xy Coordinates":
|
||||
/// start at D50, map the neutral through the inverse of the matrix interpolated at the current estimate, repeat until it
|
||||
/// moves less than 1e-7 (30 passes at most; a two-value oscillation is averaged).</summary>
|
||||
public Chromaticity NeutralToXy(Vector3D neutral)
|
||||
{
|
||||
const int maxPasses = 30;
|
||||
var last = Chromaticity.D50;
|
||||
for (var pass = 0; pass < maxPasses; pass++)
|
||||
{
|
||||
if (!XyzToCamera(last).TryInvert(out var cameraToXyz)) return last;
|
||||
var next = Chromaticity.FromXyz(cameraToXyz * neutral);
|
||||
if (!double.IsFinite(next.X) || !double.IsFinite(next.Y) || next.Y <= 0) return last;
|
||||
if (double.Abs(next.X - last.X) + double.Abs(next.Y - last.Y) < 1e-7) return next;
|
||||
if (pass == maxPasses - 1) next = new Chromaticity((last.X + next.X) / 2, (last.Y + next.Y) / 2);
|
||||
last = next;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
/// <summary>Camera → XYZ(D50) with the white-balanced neutral mapping to the D50 white (Y = 1): through the
|
||||
/// interpolated ForwardMatrix when present, otherwise the inverse of ColorMatrix adapted from D50 to the scene white
|
||||
/// (DNG §6 "Camera to XYZ (D50) Transform").</summary>
|
||||
private Matrix3 CameraToPcs(Chromaticity white, Vector3D neutral)
|
||||
{
|
||||
var d50 = Chromaticity.D50.ToXyz();
|
||||
if (ForwardMatrix1 is { } fm1 && Usable(fm1))
|
||||
{
|
||||
var g = Weight(white);
|
||||
var fm = NormalizeForward(Blend(fm1, ForwardMatrix2 is { } fm2 && Usable(fm2) ? fm2 : null, g), d50);
|
||||
var cc = Blend(CameraCalibration1 ?? Matrix3.Identity, CameraCalibration2 ?? (CameraCalibration1 is null ? null : Matrix3.Identity), g);
|
||||
var individualToReference = (Matrix3.Diagonal(AnalogBalance.X, AnalogBalance.Y, AnalogBalance.Z) * cc).Inverse();
|
||||
var reference = individualToReference * neutral;
|
||||
return fm * Matrix3.Diagonal(1 / reference.X, 1 / reference.Y, 1 / reference.Z) * individualToReference;
|
||||
}
|
||||
var pcsToCamera = XyzToCamera(white) * Matrix3.BradfordAdaptation(d50, white.ToXyz());
|
||||
var atWhite = pcsToCamera * d50;
|
||||
var scale = double.Max(atWhite.X, double.Max(atWhite.Y, atWhite.Z));
|
||||
if (!(scale > 0)) throw new InvalidDataException("DNG: colour matrix maps white outside the camera gamut");
|
||||
return Scale(pcsToCamera, 1 / scale).Inverse();
|
||||
}
|
||||
|
||||
/// <summary>Weight of calibration 1 for a scene white: 1 at or below its temperature, 0 at or above calibration 2's,
|
||||
/// linear in inverse temperature between (DNG §6 "Linear Interpolation Based on Correlated Color Temperature").</summary>
|
||||
private double Weight(Chromaticity white)
|
||||
{
|
||||
if (ColorMatrix2 is null) return 1;
|
||||
var t1 = IlluminantTemperature(CalibrationIlluminant1);
|
||||
var t2 = IlluminantTemperature(CalibrationIlluminant2);
|
||||
if (t1 <= 0 || t2 <= 0 || t1 == t2) return 1;
|
||||
var t = Temperature(white);
|
||||
var swap = t1 > t2;
|
||||
var (lo, hi) = swap ? (t2, t1) : (t1, t2);
|
||||
double g;
|
||||
if (t <= lo) g = 1;
|
||||
else if (t >= hi) g = 0;
|
||||
else g = (1 / t - 1 / hi) / (1 / lo - 1 / hi);
|
||||
return swap ? 1 - g : g;
|
||||
}
|
||||
|
||||
/// <summary>Temperatures the DNG SDK assigns to the Exif LightSource codes (fluorescents use the band centre); 0 when unknown.</summary>
|
||||
public static double IlluminantTemperature(int lightSource) => lightSource switch
|
||||
{
|
||||
17 or 3 => 2850,
|
||||
24 => 3200,
|
||||
23 => 5000,
|
||||
20 or 1 or 9 or 4 or 18 => 5500,
|
||||
21 or 19 or 10 => 6500,
|
||||
22 or 11 => 7500,
|
||||
12 => (5700 + 7100) / 2.0,
|
||||
13 => (4600 + 5500) / 2.0,
|
||||
14 or 2 => (3800 + 4500) / 2.0,
|
||||
15 => (3250 + 3800) / 2.0,
|
||||
16 => (2600 + 3250) / 2.0,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>Correlated colour temperature by Robertson's method (isotemperature lines in CIE 1960 uv,
|
||||
/// Wyszecki & Stiles table) as the DNG SDK computes it; results clamp to 1 667–100 000 K.</summary>
|
||||
public static double Temperature(Chromaticity xy)
|
||||
{
|
||||
var d = 1.5 - xy.X + 6 * xy.Y;
|
||||
var u = 2 * xy.X / d;
|
||||
var v = 3 * xy.Y / d;
|
||||
double lastDt = 0;
|
||||
var table = Robertson;
|
||||
for (var i = 1; i < table.Length; i++)
|
||||
{
|
||||
var (_, tu, tv, slope) = table[i];
|
||||
var len = double.Sqrt(1 + slope * slope);
|
||||
double du = 1 / len, dv = slope / len;
|
||||
var dt = -(u - tu) * dv + (v - tv) * du;
|
||||
if (dt <= 0 || i == table.Length - 1)
|
||||
{
|
||||
if (dt > 0) dt = 0;
|
||||
dt = -dt;
|
||||
var f = i == 1 ? 0 : dt / (lastDt + dt);
|
||||
return 1e6 / (table[i - 1].Mired * f + table[i].Mired * (1 - f));
|
||||
}
|
||||
lastDt = dt;
|
||||
}
|
||||
return 1e6 / table[^1].Mired;
|
||||
}
|
||||
|
||||
/// <summary>Robertson (1968) isotemperature lines: mired, u, v, slope.</summary>
|
||||
private static readonly (double Mired, double U, double V, double Slope)[] Robertson =
|
||||
[
|
||||
(0, 0.18006, 0.26352, -0.24341), (10, 0.18066, 0.26589, -0.25479), (20, 0.18133, 0.26846, -0.26876),
|
||||
(30, 0.18208, 0.27119, -0.28539), (40, 0.18293, 0.27407, -0.30470), (50, 0.18388, 0.27709, -0.32675),
|
||||
(60, 0.18494, 0.28021, -0.35156), (70, 0.18611, 0.28342, -0.37915), (80, 0.18740, 0.28668, -0.40955),
|
||||
(90, 0.18880, 0.28997, -0.44278), (100, 0.19032, 0.29326, -0.47888), (125, 0.19462, 0.30141, -0.58204),
|
||||
(150, 0.19962, 0.30921, -0.70471), (175, 0.20525, 0.31647, -0.84901), (200, 0.21142, 0.32312, -1.0182),
|
||||
(225, 0.21807, 0.32909, -1.2168), (250, 0.22511, 0.33439, -1.4512), (275, 0.23247, 0.33904, -1.7298),
|
||||
(300, 0.24010, 0.34308, -2.0637), (325, 0.24702, 0.34655, -2.4681), (350, 0.25591, 0.34951, -2.9641),
|
||||
(375, 0.26400, 0.35200, -3.5814), (400, 0.27218, 0.35407, -4.3633), (425, 0.28039, 0.35577, -5.3762),
|
||||
(450, 0.28863, 0.35714, -6.7262), (475, 0.29685, 0.35823, -8.5955), (500, 0.30505, 0.35907, -11.324),
|
||||
(525, 0.31320, 0.35968, -15.628), (550, 0.32129, 0.36011, -23.325), (575, 0.32931, 0.36038, -40.770),
|
||||
(600, 0.33724, 0.36051, -116.45),
|
||||
];
|
||||
|
||||
/// <summary>Rows scaled so that the camera neutral (1, 1, 1) maps exactly to the D50 white (DNG SDK NormalizeForwardMatrix).</summary>
|
||||
private static Matrix3 NormalizeForward(Matrix3 m, Vector3D d50)
|
||||
{
|
||||
var one = m * new Vector3D(1, 1, 1);
|
||||
if (!(one.X > 0 && one.Y > 0 && one.Z > 0)) return m;
|
||||
return Matrix3.Diagonal(d50.X / one.X, d50.Y / one.Y, d50.Z / one.Z) * m;
|
||||
}
|
||||
|
||||
private static Matrix3 Blend(Matrix3 a, Matrix3? b, double weightA)
|
||||
{
|
||||
if (b is not { } m || weightA >= 1) return a;
|
||||
var wb = 1 - weightA;
|
||||
return new Matrix3(
|
||||
a.M11 * weightA + m.M11 * wb, a.M12 * weightA + m.M12 * wb, a.M13 * weightA + m.M13 * wb,
|
||||
a.M21 * weightA + m.M21 * wb, a.M22 * weightA + m.M22 * wb, a.M23 * weightA + m.M23 * wb,
|
||||
a.M31 * weightA + m.M31 * wb, a.M32 * weightA + m.M32 * wb, a.M33 * weightA + m.M33 * wb);
|
||||
}
|
||||
|
||||
private static Matrix3 Scale(Matrix3 m, double s) => new(
|
||||
m.M11 * s, m.M12 * s, m.M13 * s, m.M21 * s, m.M22 * s, m.M23 * s, m.M31 * s, m.M32 * s, m.M33 * s);
|
||||
|
||||
private static Vector3D Normalize(Vector3D v)
|
||||
{
|
||||
var max = double.Max(v.X, double.Max(v.Y, v.Z));
|
||||
if (!(max > 0) || !double.IsFinite(max)) throw new InvalidDataException("DNG: camera neutral is not positive");
|
||||
return new Vector3D(v.X / max, v.Y / max, v.Z / max);
|
||||
}
|
||||
|
||||
private static bool Usable(Matrix3 m) =>
|
||||
double.IsFinite(m.Determinant) && m.TryInvert(out _);
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Codecs.Dng;
|
||||
|
||||
/// <summary>
|
||||
/// Image an opcode list runs on (DNG 1.6 §7): list 1 sees the stored raw values divided by 65535, list 2 the linearised
|
||||
/// mosaic (0 = black, 1 = white), list 3 the demosaiced planes. Coordinates of opcode parameters are full-resolution
|
||||
/// stage coordinates; a binned (half-size) image covers <see cref="Step"/> stage pixels per buffer pixel.
|
||||
/// </summary>
|
||||
internal sealed class OpcodeImage(ImageBuffer pixels, int left, int top, int step, CfaPattern? cfa)
|
||||
{
|
||||
public ImageBuffer Pixels { get; set; } = pixels;
|
||||
|
||||
/// <summary>Stage coordinates of buffer pixel (0, 0)'s block.</summary>
|
||||
public int Left { get; set; } = left;
|
||||
|
||||
public int Top { get; set; } = top;
|
||||
|
||||
/// <summary>Stage pixels per buffer pixel along each axis (1 at full resolution).</summary>
|
||||
public int Step { get; } = step;
|
||||
|
||||
/// <summary>CFA of a mosaic, anchored at buffer pixel (0, 0); null for planar images.</summary>
|
||||
public CfaPattern? Cfa { get; set; } = cfa;
|
||||
|
||||
/// <summary>Per-pixel clip flags that must stay aligned with <see cref="Pixels"/> (trimmed together).</summary>
|
||||
public byte[]? ClipMask { get; set; }
|
||||
|
||||
public int Width => Pixels.Width;
|
||||
public int Height => Pixels.Height;
|
||||
|
||||
/// <summary>Stage bounds covered by the buffer.</summary>
|
||||
public RawRect Bounds => new(Left, Top, Left + Width * Step, Top + Height * Step);
|
||||
|
||||
/// <summary>Stage coordinate of a buffer column's centre (integer at full resolution).</summary>
|
||||
public double StageX(int x) => Left + x * Step + (Step - 1) / 2.0;
|
||||
|
||||
public double StageY(int y) => Top + y * Step + (Step - 1) / 2.0;
|
||||
|
||||
/// <summary>Buffer coordinate of a stage coordinate.</summary>
|
||||
public double BufferX(double stageX) => (stageX - Left - (Step - 1) / 2.0) / Step;
|
||||
|
||||
public double BufferY(double stageY) => (stageY - Top - (Step - 1) / 2.0) / Step;
|
||||
}
|
||||
|
||||
/// <summary>One parsed opcode. Flag bit 0 marks it optional, bit 1 "may be skipped for previews".</summary>
|
||||
internal abstract class DngOpcode(uint id, uint flags)
|
||||
{
|
||||
public uint Id { get; } = id;
|
||||
public uint Flags { get; } = flags;
|
||||
public bool Optional => (Flags & 1) != 0;
|
||||
|
||||
/// <summary>True when the opcode works on value magnitudes in a way that does not commute with white-balance scaling.</summary>
|
||||
public virtual bool NeedsUnbalancedValues => false;
|
||||
|
||||
public abstract string Name { get; }
|
||||
|
||||
public abstract void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DNG opcode lists (DNG 1.6 chapter 7, big-endian): WarpRectilinear (1), FixVignetteRadial (3), FixBadPixelsConstant (4),
|
||||
/// FixBadPixelsList (5), TrimBounds (6), MapTable (7), MapPolynomial (8), GainMap (9), DeltaPerRow/Column (10/11) and
|
||||
/// ScalePerRow/Column (12/13). Other opcodes (WarpFisheye, WarpRectilinear2, vendor extensions) are skipped with a warning
|
||||
/// that says whether the file marked them optional.
|
||||
/// </summary>
|
||||
internal static class DngOpcodes
|
||||
{
|
||||
private const int MaxOpcodes = 256;
|
||||
private const long MaxGainMapPoints = 1 << 22;
|
||||
|
||||
/// <summary>Parses an OpcodeList tag value; malformed opcodes are dropped with a warning.</summary>
|
||||
public static List<DngOpcode> Parse(byte[]? data, int list, ICollection<string> warnings)
|
||||
{
|
||||
var result = new List<DngOpcode>();
|
||||
if (data is null || data.Length < 4) return result;
|
||||
var count = BinaryPrimitives.ReadUInt32BigEndian(data);
|
||||
var pos = 4;
|
||||
for (var i = 0; i < count && i < MaxOpcodes; i++)
|
||||
{
|
||||
if (pos + 16 > data.Length)
|
||||
{
|
||||
warnings.Add($"DNG: opcode list {list} truncated");
|
||||
break;
|
||||
}
|
||||
var id = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos));
|
||||
var flags = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos + 8));
|
||||
var size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(pos + 12));
|
||||
pos += 16;
|
||||
if (size > data.Length - pos)
|
||||
{
|
||||
warnings.Add($"DNG: opcode list {list} truncated");
|
||||
break;
|
||||
}
|
||||
var reader = new ParamReader(data.AsSpan(pos, (int)size));
|
||||
pos += (int)size;
|
||||
var op = Create(id, flags, ref reader);
|
||||
if (op is null)
|
||||
{
|
||||
warnings.Add((flags & 1) != 0
|
||||
? $"DNG: optional opcode {id} in list {list} not supported; skipped"
|
||||
: $"DNG: required opcode {id} in list {list} not supported; skipped, rendering may differ");
|
||||
}
|
||||
else if (!reader.Ok)
|
||||
{
|
||||
warnings.Add($"DNG: opcode {op.Name} in list {list} has malformed parameters; skipped");
|
||||
}
|
||||
else
|
||||
{
|
||||
result.Add(op);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Applies every opcode in order.</summary>
|
||||
public static void Apply(IReadOnlyList<DngOpcode> opcodes, OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var op in opcodes)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
op.Apply(image, warnings, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private static DngOpcode? Create(uint id, uint flags, ref ParamReader r) => id switch
|
||||
{
|
||||
1 => WarpRectilinear.Read(flags, ref r),
|
||||
3 => new FixVignetteRadial(flags, r.F64(), r.F64(), r.F64(), r.F64(), r.F64(), r.F64(), r.F64()),
|
||||
4 => FixBadPixelsConstant.Read(flags, ref r),
|
||||
5 => FixBadPixelsList.Read(flags, ref r),
|
||||
6 => TrimBounds.Read(flags, ref r),
|
||||
7 => MapTable.Read(flags, ref r),
|
||||
8 => MapPolynomial.Read(flags, ref r),
|
||||
9 => GainMap.Read(flags, ref r),
|
||||
10 or 11 or 12 or 13 => PerLine.Read(id, flags, ref r),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Big-endian parameter reader that turns overruns into <see cref="Ok"/> = false instead of throwing.</summary>
|
||||
internal ref struct ParamReader(ReadOnlySpan<byte> data)
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _data = data;
|
||||
private int _pos;
|
||||
|
||||
public bool Ok { get; private set; } = true;
|
||||
public int Remaining => _data.Length - _pos;
|
||||
|
||||
public uint U32() => Take(4) ? BinaryPrimitives.ReadUInt32BigEndian(_data[(_pos - 4)..]) : 0;
|
||||
|
||||
/// <summary>A 32-bit coordinate limited to the int range.</summary>
|
||||
public uint Bounded()
|
||||
{
|
||||
var v = U32();
|
||||
if (v > int.MaxValue / 4) Ok = false;
|
||||
return v;
|
||||
}
|
||||
|
||||
public ushort U16() => Take(2) ? BinaryPrimitives.ReadUInt16BigEndian(_data[(_pos - 2)..]) : (ushort)0;
|
||||
|
||||
public float F32() => Take(4) ? BinaryPrimitives.ReadSingleBigEndian(_data[(_pos - 4)..]) : 0;
|
||||
|
||||
public double F64()
|
||||
{
|
||||
var v = Take(8) ? BinaryPrimitives.ReadDoubleBigEndian(_data[(_pos - 8)..]) : 0;
|
||||
if (!double.IsFinite(v)) Ok = false;
|
||||
return v;
|
||||
}
|
||||
|
||||
public void Fail() => Ok = false;
|
||||
|
||||
private bool Take(int n)
|
||||
{
|
||||
if (!Ok || _pos + n > _data.Length)
|
||||
{
|
||||
Ok = false;
|
||||
return false;
|
||||
}
|
||||
_pos += n;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Area of effect shared by the per-pixel opcodes: rectangle, plane range and row/column pitch.</summary>
|
||||
internal readonly record struct AreaSpec(RawRect Area, int Plane, int Planes, int RowPitch, int ColPitch)
|
||||
{
|
||||
public static AreaSpec Read(ref ParamReader r)
|
||||
{
|
||||
var top = (int)r.Bounded();
|
||||
var left = (int)r.Bounded();
|
||||
var bottom = (int)r.Bounded();
|
||||
var right = (int)r.Bounded();
|
||||
var plane = (int)r.Bounded();
|
||||
var planes = (int)r.Bounded();
|
||||
var rowPitch = (int)r.Bounded();
|
||||
var colPitch = (int)r.Bounded();
|
||||
if (rowPitch < 1 || colPitch < 1 || planes < 1) r.Fail();
|
||||
return new AreaSpec(new RawRect(left, top, right, bottom), plane, planes, rowPitch, colPitch);
|
||||
}
|
||||
|
||||
/// <summary>Visits every affected (plane, buffer x, buffer y, stage x, stage y) on the pitch grid; rows run in
|
||||
/// parallel, so <paramref name="pixel"/> may only touch its own pixel.</summary>
|
||||
public void ForEach(OpcodeImage image, Action<int, int, int, int, int> pixel, ICollection<string> warnings, string name, CancellationToken cancellationToken)
|
||||
{
|
||||
if (image.Step != 1 && (RowPitch != 1 || ColPitch != 1))
|
||||
{
|
||||
warnings.Add($"DNG: {name} with pitch cannot apply to a binned image; skipped");
|
||||
return;
|
||||
}
|
||||
var area = Area.Intersect(image.Bounds);
|
||||
if (area.IsEmpty) return;
|
||||
var lastPlane = int.Min(image.Pixels.Channels, Plane + Planes);
|
||||
var firstRow = Area.Top + Ceil(area.Top - Area.Top, RowPitch);
|
||||
var firstCol = Area.Left + Ceil(area.Left - Area.Left, ColPitch);
|
||||
var rowStep = RowPitch * image.Step;
|
||||
var colStep = ColPitch * image.Step;
|
||||
var rows = (area.Bottom - firstRow + rowStep - 1) / rowStep;
|
||||
if (rows <= 0 || firstCol >= area.Right) return;
|
||||
var plane = Plane;
|
||||
Parallel.For(0, rows, new ParallelOptions { CancellationToken = cancellationToken }, k =>
|
||||
{
|
||||
var sy = firstRow + k * rowStep;
|
||||
var y = (int)double.Round(image.BufferY(sy));
|
||||
if ((uint)y >= (uint)image.Height) return;
|
||||
for (var p = plane; p < lastPlane; p++)
|
||||
{
|
||||
for (var sx = firstCol; sx < area.Right; sx += colStep)
|
||||
{
|
||||
var x = (int)double.Round(image.BufferX(sx));
|
||||
if ((uint)x < (uint)image.Width) pixel(p, x, y, sx, sy);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static int Ceil(int offset, int pitch) => (offset + pitch - 1) / pitch * pitch;
|
||||
}
|
||||
|
||||
/// <summary>Distance from the normalised optical centre to the farthest corner of the stage bounds.</summary>
|
||||
private static (double Cx, double Cy, double MaxDistance) Centre(RawRect bounds, double cx, double cy)
|
||||
{
|
||||
var x = bounds.Left + cx * bounds.Width;
|
||||
var y = bounds.Top + cy * bounds.Height;
|
||||
var m = 0.0;
|
||||
foreach (var (px, py) in (ReadOnlySpan<(int, int)>)[(bounds.Left, bounds.Top), (bounds.Right, bounds.Top), (bounds.Left, bounds.Bottom), (bounds.Right, bounds.Bottom)])
|
||||
m = double.Max(m, double.Hypot(px - x, py - y));
|
||||
return (x, y, double.Max(m, 1e-9));
|
||||
}
|
||||
|
||||
/// <summary>WarpRectilinear: radial (kr0–kr3) and tangential (kt0, kt1) distortion per plane, mapping each corrected
|
||||
/// pixel to its source position; resampled with Catmull-Rom.</summary>
|
||||
private sealed class WarpRectilinear(uint flags, double[][] coefficients, double cx, double cy) : DngOpcode(1, flags)
|
||||
{
|
||||
public override string Name => "WarpRectilinear";
|
||||
|
||||
public static WarpRectilinear? Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
var n = r.U32();
|
||||
if (n is < 1 or > 4)
|
||||
{
|
||||
r.Fail();
|
||||
return new WarpRectilinear(flags, [], 0, 0);
|
||||
}
|
||||
var k = new double[n][];
|
||||
for (var i = 0; i < n; i++) k[i] = [r.F64(), r.F64(), r.F64(), r.F64(), r.F64(), r.F64()];
|
||||
return new WarpRectilinear(flags, k, r.F64(), r.F64());
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
if (image.Cfa is not null)
|
||||
{
|
||||
warnings.Add("DNG: WarpRectilinear on mosaic data is not supported; skipped");
|
||||
return;
|
||||
}
|
||||
var src = image.Pixels;
|
||||
var dst = new ImageBuffer(src.Width, src.Height, src.Channels, clear: false);
|
||||
var (cxs, cys, m) = Centre(image.Bounds, cx, cy);
|
||||
Parallel.For(0, src.Height, new ParallelOptions { CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var sy = image.StageY(y);
|
||||
for (var p = 0; p < src.Channels; p++)
|
||||
{
|
||||
var k = coefficients[int.Min(p, coefficients.Length - 1)];
|
||||
var plane = src.Plane(p);
|
||||
var row = dst.Row(p, y);
|
||||
for (var x = 0; x < src.Width; x++)
|
||||
{
|
||||
var dx = (image.StageX(x) - cxs) / m;
|
||||
var dy = (sy - cys) / m;
|
||||
var r2 = dx * dx + dy * dy;
|
||||
var f = k[0] + r2 * (k[1] + r2 * (k[2] + r2 * k[3]));
|
||||
var tx = k[4] * 2 * dx * dy + k[5] * (r2 + 2 * dx * dx);
|
||||
var ty = k[5] * 2 * dx * dy + k[4] * (r2 + 2 * dy * dy);
|
||||
var xs = image.BufferX(cxs + m * (f * dx + tx));
|
||||
var ys = image.BufferY(cys + m * (f * dy + ty));
|
||||
row[x] = Sampling.CatmullRom(plane, src.Width, src.Height, xs, ys);
|
||||
}
|
||||
}
|
||||
});
|
||||
src.Dispose();
|
||||
image.Pixels = dst;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>FixVignetteRadial: gain 1 + k0·r² + k1·r⁴ + k2·r⁶ + k3·r⁸ + k4·r¹⁰ about the normalised centre.</summary>
|
||||
private sealed class FixVignetteRadial(uint flags, double k0, double k1, double k2, double k3, double k4, double cx, double cy) : DngOpcode(3, flags)
|
||||
{
|
||||
public override string Name => "FixVignetteRadial";
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var (cxs, cys, m) = Centre(image.Bounds, cx, cy);
|
||||
var pixels = image.Pixels;
|
||||
Parallel.For(0, pixels.Height, new ParallelOptions { CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var dy = (image.StageY(y) - cys) / m;
|
||||
for (var x = 0; x < pixels.Width; x++)
|
||||
{
|
||||
var dx = (image.StageX(x) - cxs) / m;
|
||||
var r2 = dx * dx + dy * dy;
|
||||
var gain = (float)(1 + r2 * (k0 + r2 * (k1 + r2 * (k2 + r2 * (k3 + r2 * k4)))));
|
||||
for (var p = 0; p < pixels.Channels; p++) pixels.Row(p, y)[x] *= gain;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>FixBadPixelsConstant: pixels whose 16-bit value equals the constant are replaced from good neighbours.</summary>
|
||||
/// <remarks>The BayerPhase parameter is not needed: the frame's own CFA pattern identifies same-colour neighbours.</remarks>
|
||||
private sealed class FixBadPixelsConstant(uint flags, uint constant) : DngOpcode(4, flags)
|
||||
{
|
||||
public override string Name => "FixBadPixelsConstant";
|
||||
public override bool NeedsUnbalancedValues => true;
|
||||
|
||||
public static FixBadPixelsConstant Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
var constant = r.U32();
|
||||
r.U32();
|
||||
return new FixBadPixelsConstant(flags, constant);
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
if (constant > 65535) return;
|
||||
var pixels = image.Pixels;
|
||||
var bad = new List<(int X, int Y)>();
|
||||
for (var y = 0; y < pixels.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < pixels.Width; x++)
|
||||
{
|
||||
for (var p = 0; p < pixels.Channels; p++)
|
||||
{
|
||||
if (Sampling.Code16(pixels.Row(p, y)[x]) != constant) continue;
|
||||
bad.Add((x, y));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
BadPixelRepair.Repair(image, bad);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>FixBadPixelsList: listed points (row, column) and rectangles are replaced from good neighbours.</summary>
|
||||
private sealed class FixBadPixelsList(uint flags, (int Row, int Col)[] points, RawRect[] rects) : DngOpcode(5, flags)
|
||||
{
|
||||
private const int MaxEntries = 1 << 22;
|
||||
|
||||
public override string Name => "FixBadPixelsList";
|
||||
|
||||
public static FixBadPixelsList Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
r.U32();
|
||||
var pointCount = r.U32();
|
||||
var rectCount = r.U32();
|
||||
if (pointCount > MaxEntries || rectCount > MaxEntries || (long)pointCount * 8 + (long)rectCount * 16 > r.Remaining)
|
||||
{
|
||||
r.Fail();
|
||||
return new FixBadPixelsList(flags, [], []);
|
||||
}
|
||||
var points = new (int, int)[pointCount];
|
||||
for (var i = 0; i < points.Length; i++) points[i] = ((int)r.Bounded(), (int)r.Bounded());
|
||||
var rects = new RawRect[rectCount];
|
||||
for (var i = 0; i < rects.Length; i++)
|
||||
{
|
||||
var top = (int)r.Bounded();
|
||||
var left = (int)r.Bounded();
|
||||
var bottom = (int)r.Bounded();
|
||||
var right = (int)r.Bounded();
|
||||
rects[i] = new RawRect(left, top, right, bottom);
|
||||
}
|
||||
return new FixBadPixelsList(flags, points, rects);
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
if (image.Step != 1)
|
||||
{
|
||||
warnings.Add("DNG: FixBadPixelsList cannot apply to a binned image; skipped");
|
||||
return;
|
||||
}
|
||||
var bad = new List<(int X, int Y)>();
|
||||
var bounds = image.Bounds;
|
||||
foreach (var (row, col) in points)
|
||||
{
|
||||
if (col >= bounds.Left && col < bounds.Right && row >= bounds.Top && row < bounds.Bottom) bad.Add((col - image.Left, row - image.Top));
|
||||
}
|
||||
foreach (var rect in rects)
|
||||
{
|
||||
var r = rect.Intersect(bounds);
|
||||
for (var y = r.Top; y < r.Bottom && bad.Count < MaxEntries; y++)
|
||||
{
|
||||
for (var x = r.Left; x < r.Right; x++) bad.Add((x - image.Left, y - image.Top));
|
||||
}
|
||||
}
|
||||
BadPixelRepair.Repair(image, bad);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>TrimBounds: crops the image to a stage rectangle.</summary>
|
||||
private sealed class TrimBounds(uint flags, RawRect bounds) : DngOpcode(6, flags)
|
||||
{
|
||||
public override string Name => "TrimBounds";
|
||||
|
||||
public static TrimBounds Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
var top = (int)r.Bounded();
|
||||
var left = (int)r.Bounded();
|
||||
var bottom = (int)r.Bounded();
|
||||
var right = (int)r.Bounded();
|
||||
return new TrimBounds(flags, new RawRect(left, top, right, bottom));
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var b = bounds.Intersect(image.Bounds);
|
||||
var x0 = (int)double.Ceiling(image.BufferX(b.Left) - 1e-9);
|
||||
var y0 = (int)double.Ceiling(image.BufferY(b.Top) - 1e-9);
|
||||
var x1 = int.Min(image.Width, (int)double.Floor(image.BufferX(b.Right - 1) + 1e-9) + 1);
|
||||
var y1 = int.Min(image.Height, (int)double.Floor(image.BufferY(b.Bottom - 1) + 1e-9) + 1);
|
||||
x0 = int.Max(0, x0);
|
||||
y0 = int.Max(0, y0);
|
||||
if (x1 - x0 <= 0 || y1 - y0 <= 0)
|
||||
{
|
||||
warnings.Add("DNG: TrimBounds outside the image; skipped");
|
||||
return;
|
||||
}
|
||||
if (x0 == 0 && y0 == 0 && x1 == image.Width && y1 == image.Height) return;
|
||||
var src = image.Pixels;
|
||||
var dst = new ImageBuffer(x1 - x0, y1 - y0, src.Channels, clear: false);
|
||||
for (var p = 0; p < src.Channels; p++)
|
||||
{
|
||||
for (var y = y0; y < y1; y++) src.Row(p, y).Slice(x0, x1 - x0).CopyTo(dst.Row(p, y - y0));
|
||||
}
|
||||
if (image.ClipMask is { } mask)
|
||||
{
|
||||
var trimmed = new byte[dst.PlaneLength];
|
||||
for (var y = y0; y < y1; y++) mask.AsSpan(y * src.Width + x0, x1 - x0).CopyTo(trimmed.AsSpan((y - y0) * dst.Width));
|
||||
image.ClipMask = trimmed;
|
||||
}
|
||||
if (image.Cfa is { } cfa) image.Cfa = cfa.Shift(x0, y0);
|
||||
image.Left += x0 * image.Step;
|
||||
image.Top += y0 * image.Step;
|
||||
src.Dispose();
|
||||
image.Pixels = dst;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>MapTable: 16-bit lookup over the area (inputs beyond the table use its last entry).</summary>
|
||||
private sealed class MapTable(uint flags, AreaSpec area, ushort[] table) : DngOpcode(7, flags)
|
||||
{
|
||||
public override string Name => "MapTable";
|
||||
public override bool NeedsUnbalancedValues => true;
|
||||
|
||||
public static MapTable Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
var area = AreaSpec.Read(ref r);
|
||||
var size = r.U32();
|
||||
if (size is < 1 or > 65536 || size * 2 > r.Remaining)
|
||||
{
|
||||
r.Fail();
|
||||
return new MapTable(flags, area, [0]);
|
||||
}
|
||||
var table = new ushort[size];
|
||||
for (var i = 0; i < table.Length; i++) table[i] = r.U16();
|
||||
return new MapTable(flags, area, table);
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var pixels = image.Pixels;
|
||||
var last = table.Length - 1;
|
||||
area.ForEach(image, (p, x, y, _, _) =>
|
||||
{
|
||||
var row = pixels.Row(p, y);
|
||||
row[x] = table[int.Min(Sampling.Code16(row[x]), last)] / 65535f;
|
||||
}, warnings, Name, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>MapPolynomial: out = Σ cᵢ·inⁱ on normalised values.</summary>
|
||||
private sealed class MapPolynomial(uint flags, AreaSpec area, double[] coefficients) : DngOpcode(8, flags)
|
||||
{
|
||||
public override string Name => "MapPolynomial";
|
||||
public override bool NeedsUnbalancedValues => true;
|
||||
|
||||
public static MapPolynomial Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
var area = AreaSpec.Read(ref r);
|
||||
var degree = r.U32();
|
||||
if (degree > 8)
|
||||
{
|
||||
r.Fail();
|
||||
return new MapPolynomial(flags, area, [0]);
|
||||
}
|
||||
var c = new double[degree + 1];
|
||||
for (var i = 0; i < c.Length; i++) c[i] = r.F64();
|
||||
return new MapPolynomial(flags, area, c);
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var pixels = image.Pixels;
|
||||
area.ForEach(image, (p, x, y, _, _) =>
|
||||
{
|
||||
var row = pixels.Row(p, y);
|
||||
double v = row[x], acc = 0;
|
||||
for (var i = coefficients.Length - 1; i >= 0; i--) acc = acc * v + coefficients[i];
|
||||
row[x] = (float)acc;
|
||||
}, warnings, Name, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>GainMap: a grid of gains (normalised origin and spacing over the image bounds), bilinearly interpolated
|
||||
/// and clamped at the grid edges, multiplied into the area.</summary>
|
||||
private sealed class GainMap(uint flags, AreaSpec area, int pointsV, int pointsH, double spacingV, double spacingH, double originV, double originH, int mapPlanes, float[] gains) : DngOpcode(9, flags)
|
||||
{
|
||||
public override string Name => "GainMap";
|
||||
|
||||
public static GainMap Read(uint flags, ref ParamReader r)
|
||||
{
|
||||
var area = AreaSpec.Read(ref r);
|
||||
var pv = r.U32();
|
||||
var ph = r.U32();
|
||||
var sv = r.F64();
|
||||
var sh = r.F64();
|
||||
var ov = r.F64();
|
||||
var oh = r.F64();
|
||||
var planes = r.U32();
|
||||
var count = (long)pv * ph * planes;
|
||||
if (pv < 1 || ph < 1 || planes < 1 || count > MaxGainMapPoints || count * 4 > r.Remaining || !(sv > 0) || !(sh > 0))
|
||||
{
|
||||
r.Fail();
|
||||
return new GainMap(flags, area, 1, 1, 1, 1, 0, 0, 1, [1]);
|
||||
}
|
||||
var gains = new float[count];
|
||||
for (var i = 0; i < gains.Length; i++) gains[i] = r.F32();
|
||||
return new GainMap(flags, area, (int)pv, (int)ph, sv, sh, ov, oh, (int)planes, gains);
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var pixels = image.Pixels;
|
||||
var bounds = image.Bounds;
|
||||
area.ForEach(image, (p, x, y, _, _) =>
|
||||
{
|
||||
var plane = int.Min(p - area.Plane, mapPlanes - 1);
|
||||
var (r0, r1, fr) = Index((image.StageY(y) - bounds.Top) / bounds.Height, originV, spacingV, pointsV);
|
||||
var (c0, c1, fc) = Index((image.StageX(x) - bounds.Left) / bounds.Width, originH, spacingH, pointsH);
|
||||
var g00 = gains[(r0 * pointsH + c0) * mapPlanes + plane];
|
||||
var g01 = gains[(r0 * pointsH + c1) * mapPlanes + plane];
|
||||
var g10 = gains[(r1 * pointsH + c0) * mapPlanes + plane];
|
||||
var g11 = gains[(r1 * pointsH + c1) * mapPlanes + plane];
|
||||
var top = g00 + (g01 - g00) * fc;
|
||||
var bottom = g10 + (g11 - g10) * fc;
|
||||
pixels.Row(p, y)[x] *= (float)(top + (bottom - top) * fr);
|
||||
}, warnings, Name, cancellationToken);
|
||||
}
|
||||
|
||||
private static (int I0, int I1, double Fraction) Index(double position, double origin, double spacing, int points)
|
||||
{
|
||||
var f = (position - origin) / spacing;
|
||||
if (!(f > 0)) return (0, 0, 0);
|
||||
if (f >= points - 1) return (points - 1, points - 1, 0);
|
||||
var i = (int)f;
|
||||
return (i, i + 1, f - i);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>DeltaPerRow/Column (offsets, normalised units) and ScalePerRow/Column (gains), one value per pitch step.</summary>
|
||||
private sealed class PerLine(uint id, uint flags, AreaSpec area, float[] values) : DngOpcode(id, flags)
|
||||
{
|
||||
public override string Name => Id switch { 10 => "DeltaPerRow", 11 => "DeltaPerColumn", 12 => "ScalePerRow", _ => "ScalePerColumn" };
|
||||
public override bool NeedsUnbalancedValues => Id is 10 or 11;
|
||||
|
||||
public static PerLine Read(uint id, uint flags, ref ParamReader r)
|
||||
{
|
||||
var area = AreaSpec.Read(ref r);
|
||||
var count = r.U32();
|
||||
if (count > 1 << 20 || count * 4 > r.Remaining)
|
||||
{
|
||||
r.Fail();
|
||||
return new PerLine(id, flags, area, []);
|
||||
}
|
||||
var values = new float[count];
|
||||
for (var i = 0; i < values.Length; i++) values[i] = r.F32();
|
||||
return new PerLine(id, flags, area, values);
|
||||
}
|
||||
|
||||
public override void Apply(OpcodeImage image, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var pixels = image.Pixels;
|
||||
var perRow = Id is 10 or 12;
|
||||
var add = Id is 10 or 11;
|
||||
area.ForEach(image, (p, x, y, sx, sy) =>
|
||||
{
|
||||
var index = perRow ? (sy - area.Area.Top) / area.RowPitch : (sx - area.Area.Left) / area.ColPitch;
|
||||
if ((uint)index >= (uint)values.Length) return;
|
||||
ref var v = ref pixels.Row(p, y)[x];
|
||||
v = add ? v + values[index] : v * values[index];
|
||||
}, warnings, Name, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bad-pixel replacement shared by the FixBadPixels opcodes: mean of the nearest good pixels of the same CFA colour
|
||||
/// (5×5, widened to 9×9 when needed), or of the 8 neighbours per plane for planar images.</summary>
|
||||
internal static class BadPixelRepair
|
||||
{
|
||||
public static void Repair(OpcodeImage image, List<(int X, int Y)> bad)
|
||||
{
|
||||
if (bad.Count == 0) return;
|
||||
var pixels = image.Pixels;
|
||||
int w = pixels.Width, h = pixels.Height;
|
||||
var isBad = new HashSet<long>(bad.Count);
|
||||
foreach (var (x, y) in bad) isBad.Add((long)y * w + x);
|
||||
var replacements = new float[bad.Count * pixels.Channels];
|
||||
for (var i = 0; i < bad.Count; i++)
|
||||
{
|
||||
var (x, y) = bad[i];
|
||||
for (var p = 0; p < pixels.Channels; p++)
|
||||
{
|
||||
var plane = pixels.Plane(p);
|
||||
var value = plane[y * w + x];
|
||||
for (var radius = image.Cfa is null ? 1 : 2; radius <= 4; radius += 2)
|
||||
{
|
||||
double sum = 0;
|
||||
var n = 0;
|
||||
for (var dy = -radius; dy <= radius; dy++)
|
||||
{
|
||||
for (var dx = -radius; dx <= radius; dx++)
|
||||
{
|
||||
int nx = x + dx, ny = y + dy;
|
||||
if ((dx | dy) == 0 || (uint)nx >= (uint)w || (uint)ny >= (uint)h || isBad.Contains((long)ny * w + nx)) continue;
|
||||
if (image.Cfa is { } cfa && cfa.ColorAt(nx, ny) != cfa.ColorAt(x, y)) continue;
|
||||
sum += plane[ny * w + nx];
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n > 0)
|
||||
{
|
||||
value = (float)(sum / n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
replacements[i * pixels.Channels + p] = value;
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < bad.Count; i++)
|
||||
{
|
||||
var (x, y) = bad[i];
|
||||
for (var p = 0; p < pixels.Channels; p++) pixels.Plane(p)[y * w + x] = replacements[i * pixels.Channels + p];
|
||||
// A repaired sample no longer carries the sensor's clipping (a hot pixel is not a highlight).
|
||||
if (image.ClipMask is { } mask) mask[y * w + x] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sampling helpers for the opcode and pipeline stages.</summary>
|
||||
internal static class Sampling
|
||||
{
|
||||
/// <summary>Normalised value → 16-bit code (rounded, clamped), the integer domain of MapTable and FixBadPixelsConstant.</summary>
|
||||
public static int Code16(float v) => v >= 1f ? 65535 : v > 0f ? (int)(v * 65535f + 0.5f) : 0;
|
||||
|
||||
/// <summary>Catmull-Rom interpolation of a plane at a fractional position (edges clamped; far outside reads the edge).</summary>
|
||||
public static float CatmullRom(ReadOnlySpan<float> plane, int width, int height, double x, double y)
|
||||
{
|
||||
x = double.Clamp(x, -2, width + 1);
|
||||
y = double.Clamp(y, -2, height + 1);
|
||||
var ix = (int)double.Floor(x);
|
||||
var iy = (int)double.Floor(y);
|
||||
var (x0, x1, x2, x3) = Weights((float)(x - ix));
|
||||
var (y0, y1, y2, y3) = Weights((float)(y - iy));
|
||||
int c0 = int.Clamp(ix - 1, 0, width - 1), c1 = int.Clamp(ix, 0, width - 1), c2 = int.Clamp(ix + 1, 0, width - 1), c3 = int.Clamp(ix + 2, 0, width - 1);
|
||||
var sum = 0f;
|
||||
for (var j = 0; j < 4; j++)
|
||||
{
|
||||
var o = int.Clamp(iy - 1 + j, 0, height - 1) * width;
|
||||
var r = x0 * plane[o + c0] + x1 * plane[o + c1] + x2 * plane[o + c2] + x3 * plane[o + c3];
|
||||
sum += r * (j switch { 0 => y0, 1 => y1, 2 => y2, _ => y3 });
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
private static (float, float, float, float) Weights(float t)
|
||||
{
|
||||
var t2 = t * t;
|
||||
var t3 = t2 * t;
|
||||
return (0.5f * (-t3 + 2 * t2 - t), 0.5f * (3 * t3 - 5 * t2 + 2), 0.5f * (-3 * t3 + 4 * t2 + t), 0.5f * (t3 - t2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Codecs.Tiff;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Dng;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the raw image description of a DNG (DNG 1.6 chapters 4–6) into a <see cref="RawFrame"/>: the full-resolution
|
||||
/// CFA (PhotometricInterpretation 32803) or LinearRaw (34892) IFD among IFD0 and its SubIFDs; compression 1, 7 (lossless
|
||||
/// JPEG, including two-component interleaved tiles), 8 (Deflate with integer or floating-point predictors) and 34892
|
||||
/// (lossy JPEG); CFA pattern and plane colours; LinearizationTable; BlackLevel with BlackLevelRepeatDim and DeltaH/V;
|
||||
/// WhiteLevel; ActiveArea; DefaultCropOrigin/Size and DefaultScale; the colour tags; OpcodeList1–3; Orientation.
|
||||
/// Raster tags are taken from the raw IFD (falling back to IFD0), colour tags from IFD0 (falling back to the raw IFD).
|
||||
/// </summary>
|
||||
internal static class DngReader
|
||||
{
|
||||
private const uint PhotometricCfa = 32803, PhotometricLinearRaw = 34892;
|
||||
private const ushort CameraCalibrationSignature = 0xC6F3, ProfileCalibrationSignature = 0xC6F4;
|
||||
private const long MaxPixels = 1L << 28;
|
||||
private const int MaxSubIfds = 16;
|
||||
|
||||
/// <exception cref="InvalidDataException">Not a DNG, no supported raw IFD, or inconsistent tags.</exception>
|
||||
public static RawFrame Read(Stream stream)
|
||||
{
|
||||
var r = TiffReader.Open(stream) ?? throw new InvalidDataException("DNG: missing TIFF header");
|
||||
var chain = r.ReadChain();
|
||||
if (chain.Count == 0) throw new InvalidDataException("DNG: no image directory");
|
||||
var ifd0 = chain[0];
|
||||
if (!ifd0.Has(TiffTags.DngVersion)) throw new InvalidDataException("DNG: DNGVersion missing");
|
||||
var raw = FindRawIfd(r, chain) ?? throw new InvalidDataException("DNG: no full-resolution CFA or LinearRaw image");
|
||||
|
||||
var width = (int)long.Min(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, int.MaxValue);
|
||||
var height = (int)long.Min(r.GetUInt(raw, TiffTags.ImageLength) ?? 0, int.MaxValue);
|
||||
if (width <= 0 || height <= 0 || (long)width * height > MaxPixels) throw new InvalidDataException($"DNG: unsupported raster size {width}x{height}");
|
||||
var spp = (int)(r.GetUInt(raw, TiffTags.SamplesPerPixel) ?? 1);
|
||||
var photometric = r.GetUInt(raw, TiffTags.PhotometricInterpretation);
|
||||
var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1;
|
||||
if (compression is not (1 or 7 or 8 or 34892)) throw new InvalidDataException($"DNG: compression {compression} is not supported");
|
||||
if (compression is 1 or 7) RequirePayload(r, raw, (long)width * height * spp);
|
||||
var floating = (r.GetUInt(raw, TiffTags.SampleFormat) ?? 1) == 3;
|
||||
var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 16);
|
||||
|
||||
CfaPattern? cfa = null;
|
||||
if (photometric == PhotometricCfa)
|
||||
{
|
||||
if (spp != 1) throw new InvalidDataException("DNG: CFA data must have one sample per pixel");
|
||||
cfa = ReadCfa(r, raw);
|
||||
}
|
||||
else if (spp is not (1 or 3))
|
||||
{
|
||||
throw new InvalidDataException($"DNG: LinearRaw with {spp} samples per pixel is not supported");
|
||||
}
|
||||
|
||||
var activeArea = new RawRect(0, 0, width, height);
|
||||
if (Values(r, raw, ifd0, TiffTags.ActiveArea, 4) is [var top, var left, var bottom, var right, ..])
|
||||
{
|
||||
activeArea = new RawRect((int)left, (int)top, (int)right, (int)bottom).Intersect(activeArea);
|
||||
if (activeArea.IsEmpty) throw new InvalidDataException("DNG: empty ActiveArea");
|
||||
}
|
||||
|
||||
var warnings = new List<string>();
|
||||
var frame = new RawFrame
|
||||
{
|
||||
Decoder = "managed-dng",
|
||||
Width = width,
|
||||
Height = height,
|
||||
SamplesPerPixel = spp,
|
||||
Cfa = cfa,
|
||||
ActiveArea = activeArea,
|
||||
DefaultCrop = ReadCrop(r, raw, ifd0, activeArea),
|
||||
DefaultScale = Values(r, raw, ifd0, TiffTags.DefaultScale, 2) is [var sh, var sv, ..] && sh > 0 && sv > 0 && sh < 16 && sv < 16 ? (sh, sv) : (1, 1),
|
||||
Linearization = ReadLinearization(r, raw, ifd0),
|
||||
Black = ReadBlack(r, raw, ifd0, spp, activeArea, warnings),
|
||||
White = ReadWhite(r, raw, ifd0, spp, floating ? 1.0 : bits is >= 1 and <= 16 ? (1 << bits) - 1 : 65535),
|
||||
Color = ReadColor(r, ifd0, raw, spp == 1 && cfa is null, warnings),
|
||||
OpcodeList1 = Bytes(r, raw, ifd0, TiffTags.OpcodeList1),
|
||||
OpcodeList2 = Bytes(r, raw, ifd0, TiffTags.OpcodeList2),
|
||||
OpcodeList3 = Bytes(r, raw, ifd0, TiffTags.OpcodeList3),
|
||||
Orientation = (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1) is var o and >= 1 and <= 8 ? o : 1,
|
||||
Make = r.GetString(ifd0, TiffTags.Make),
|
||||
Model = r.GetString(ifd0, TiffTags.Model) ?? r.GetString(ifd0, TiffTags.UniqueCameraModel),
|
||||
Loader = new TiffRasterLoader(r, raw),
|
||||
};
|
||||
frame.Warnings.AddRange(warnings);
|
||||
frame.Warnings.AddRange(r.Warnings);
|
||||
return frame;
|
||||
}
|
||||
|
||||
/// <summary>Uncompressed and lossless-JPEG data hold at least one bit per sample; checked before the raster is allocated
|
||||
/// so a corrupted size cannot trigger a huge allocation.</summary>
|
||||
private static void RequirePayload(TiffReader r, Ifd raw, long samples)
|
||||
{
|
||||
var counts = r.GetUInts(raw, raw.Has(TiffTags.TileByteCounts) ? TiffTags.TileByteCounts : TiffTags.StripByteCounts);
|
||||
long total = 0;
|
||||
foreach (var c in counts ?? []) total += c;
|
||||
if (total * 8 < samples) throw new InvalidDataException("DNG: image data too short for the raster");
|
||||
}
|
||||
|
||||
/// <summary>First IFD with NewSubfileType 0 and a CFA/LinearRaw photometric: IFD0, its SubIFDs (two levels), the chain.</summary>
|
||||
private static Ifd? FindRawIfd(TiffReader r, IReadOnlyList<Ifd> chain)
|
||||
{
|
||||
var visited = new HashSet<long>();
|
||||
foreach (var ifd in chain) visited.Add(ifd.Position);
|
||||
var queue = new List<(Ifd Ifd, int Depth)> { (chain[0], 0) };
|
||||
for (var i = 0; i < queue.Count; i++)
|
||||
{
|
||||
var (ifd, depth) = queue[i];
|
||||
if (IsRaw(r, ifd)) return ifd;
|
||||
if (depth < 2 && ifd.Entries.TryGetValue(TiffTags.SubIfds, out var sub) && sub.Count <= MaxSubIfds)
|
||||
{
|
||||
foreach (var offset in r.GetUInts(sub) ?? [])
|
||||
{
|
||||
if (r.ReadIfd(offset, visited) is { } child) queue.Add((child, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var ifd in chain)
|
||||
{
|
||||
if (IsRaw(r, ifd)) return ifd;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsRaw(TiffReader r, Ifd ifd) =>
|
||||
(r.GetUInt(ifd, TiffTags.NewSubfileType) ?? 0) == 0
|
||||
&& r.GetUInt(ifd, TiffTags.PhotometricInterpretation) is PhotometricCfa or PhotometricLinearRaw;
|
||||
|
||||
private static CfaPattern ReadCfa(TiffReader r, Ifd raw)
|
||||
{
|
||||
if ((r.GetUInt(raw, TiffTags.CfaLayout) ?? 1) != 1) throw new InvalidDataException("DNG: non-rectangular CFA layouts are not supported");
|
||||
var dim = IfdValue.UInts(r, raw, TiffTags.CfaRepeatPatternDim) ?? [2, 2];
|
||||
if (dim.Length < 2) throw new InvalidDataException("DNG: bad CFARepeatPatternDim");
|
||||
int rows = (int)dim[0], cols = (int)dim[1];
|
||||
if (rows is < 1 or > CfaPattern.MaxSize || cols is < 1 or > CfaPattern.MaxSize) throw new InvalidDataException($"DNG: CFA pattern {rows}x{cols} is not supported");
|
||||
var pattern = IfdValue.UInts(r, raw, TiffTags.CfaPattern) ?? throw new InvalidDataException("DNG: CFAPattern missing");
|
||||
if (pattern.Length < rows * cols) throw new InvalidDataException("DNG: CFAPattern too short");
|
||||
var planeColor = IfdValue.UInts(r, raw, TiffTags.CfaPlaneColor) ?? [0, 1, 2];
|
||||
var colors = new byte[rows * cols];
|
||||
for (var i = 0; i < colors.Length; i++)
|
||||
{
|
||||
// CFAPattern holds colour codes (0 red, 1 green, 2 blue, 3+ CMY/white); CFAPlaneColor names the planes.
|
||||
var code = pattern[i];
|
||||
if (code > 2 || planeColor.Length != 3 || Array.IndexOf(planeColor, code) < 0)
|
||||
throw new InvalidDataException("DNG: only red/green/blue CFAs are supported");
|
||||
colors[i] = (byte)code;
|
||||
}
|
||||
return new CfaPattern(cols, rows, colors);
|
||||
}
|
||||
|
||||
private static RawRect? ReadCrop(TiffReader r, Ifd raw, Ifd ifd0, RawRect active)
|
||||
{
|
||||
if (Values(r, raw, ifd0, TiffTags.DefaultCropOrigin, 2) is not [var ox, var oy, ..] || Values(r, raw, ifd0, TiffTags.DefaultCropSize, 2) is not [var cw, var ch, ..])
|
||||
return null;
|
||||
var crop = new RawRect((int)double.Round(ox), (int)double.Round(oy), (int)double.Round(ox + cw), (int)double.Round(oy + ch))
|
||||
.Intersect(new RawRect(0, 0, active.Width, active.Height));
|
||||
return crop.IsEmpty ? null : crop;
|
||||
}
|
||||
|
||||
private static ushort[]? ReadLinearization(TiffReader r, Ifd raw, Ifd ifd0)
|
||||
{
|
||||
var ifd = raw.Has(TiffTags.LinearizationTable) ? raw : ifd0;
|
||||
if (!ifd.Entries.TryGetValue(TiffTags.LinearizationTable, out var e) || e.Count is 0 or > 65536) return null;
|
||||
return r.GetUInts(e) is { } values ? Array.ConvertAll(values, v => (ushort)uint.Min(v, 65535)) : null;
|
||||
}
|
||||
|
||||
private static RawBlackLevel ReadBlack(TiffReader r, Ifd raw, Ifd ifd0, int spp, RawRect active, ICollection<string> warnings)
|
||||
{
|
||||
var dim = Values(r, raw, ifd0, TiffTags.BlackLevelRepeatDim, 2) is [var dr, var dc, ..] ? ((int)dr, (int)dc) : (1, 1);
|
||||
var (rows, cols) = dim;
|
||||
if (rows is < 1 or > 64 || cols is < 1 or > 64)
|
||||
{
|
||||
warnings.Add("DNG: bad BlackLevelRepeatDim ignored");
|
||||
(rows, cols) = (1, 1);
|
||||
}
|
||||
var values = new float[rows * cols * spp];
|
||||
if (Doubles(r, raw, ifd0, TiffTags.BlackLevel, 1 << 14) is { Length: > 0 } black)
|
||||
{
|
||||
if (black.Length != values.Length && black.Length != 1) warnings.Add($"DNG: BlackLevel has {black.Length} values, {values.Length} expected");
|
||||
for (var i = 0; i < values.Length; i++) values[i] = (float)black[black.Length == values.Length ? i : i % black.Length];
|
||||
}
|
||||
var deltaH = Doubles(r, raw, ifd0, TiffTags.BlackLevelDeltaH, 1 << 20) is { } h && h.Length >= active.Width ? Array.ConvertAll(h, v => (float)v) : null;
|
||||
var deltaV = Doubles(r, raw, ifd0, TiffTags.BlackLevelDeltaV, 1 << 20) is { } v && v.Length >= active.Height ? Array.ConvertAll(v, x => (float)x) : null;
|
||||
return new RawBlackLevel(rows, cols, values, deltaH, deltaV);
|
||||
}
|
||||
|
||||
private static double[] ReadWhite(TiffReader r, Ifd raw, Ifd ifd0, int spp, double fallback)
|
||||
{
|
||||
var white = new double[spp];
|
||||
var tag = Doubles(r, raw, ifd0, TiffTags.WhiteLevel, 16);
|
||||
for (var i = 0; i < spp; i++) white[i] = tag is { Length: > 0 } t ? t[int.Min(i, t.Length - 1)] : fallback;
|
||||
return white;
|
||||
}
|
||||
|
||||
private static DngColorProfile ReadColor(TiffReader r, Ifd ifd0, Ifd raw, bool monochrome, ICollection<string> warnings)
|
||||
{
|
||||
Matrix3? M(ushort tag) => Doubles(r, ifd0, raw, tag, 64) is { Length: 9 } m ? new Matrix3(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]) : null;
|
||||
Mathematics.Vector3D? V(ushort tag) => Doubles(r, ifd0, raw, tag, 16) is { Length: 3 } v ? new Mathematics.Vector3D(v[0], v[1], v[2]) : null;
|
||||
var baseline = Doubles(r, ifd0, raw, TiffTags.BaselineExposure, 1) is [var b] && double.Abs(b) < 16 ? b : 0;
|
||||
if (monochrome) return new DngColorProfile { BaselineExposure = baseline };
|
||||
|
||||
// CameraCalibration only applies when its signature matches the profile's (DNG §6, "CameraCalibrationSignature").
|
||||
var useCalibration = r.GetString(ifd0, CameraCalibrationSignature) == r.GetString(ifd0, ProfileCalibrationSignature);
|
||||
if (!useCalibration && (ifd0.Has(TiffTags.CameraCalibration1) || ifd0.Has(TiffTags.CameraCalibration2)))
|
||||
warnings.Add("DNG: CameraCalibration ignored (signature does not match the profile)");
|
||||
var cm1 = M(TiffTags.ColorMatrix1) ?? throw new InvalidDataException("DNG: ColorMatrix1 missing");
|
||||
return new DngColorProfile
|
||||
{
|
||||
ColorMatrix1 = cm1,
|
||||
ColorMatrix2 = M(TiffTags.ColorMatrix2),
|
||||
CameraCalibration1 = useCalibration ? M(TiffTags.CameraCalibration1) : null,
|
||||
CameraCalibration2 = useCalibration ? M(TiffTags.CameraCalibration2) : null,
|
||||
ForwardMatrix1 = M(TiffTags.ForwardMatrix1),
|
||||
ForwardMatrix2 = M(TiffTags.ForwardMatrix2),
|
||||
CalibrationIlluminant1 = (int)(r.GetUInt(ifd0, TiffTags.CalibrationIlluminant1) ?? 0),
|
||||
CalibrationIlluminant2 = (int)(r.GetUInt(ifd0, TiffTags.CalibrationIlluminant2) ?? 0),
|
||||
AnalogBalance = V(TiffTags.AnalogBalance) is { } ab && ab.X > 0 && ab.Y > 0 && ab.Z > 0 ? ab : new(1, 1, 1),
|
||||
AsShotNeutral = V(TiffTags.AsShotNeutral),
|
||||
AsShotWhite = Doubles(r, ifd0, raw, TiffTags.AsShotWhiteXy, 2) is [var x, var y] ? new Chromaticity(x, y) : null,
|
||||
BaselineExposure = baseline,
|
||||
};
|
||||
}
|
||||
|
||||
private static byte[]? Bytes(TiffReader r, Ifd raw, Ifd ifd0, ushort tag)
|
||||
{
|
||||
var ifd = raw.Has(tag) ? raw : ifd0;
|
||||
return ifd.Entries.TryGetValue(tag, out var e) ? r.ReadBytes(e) : null;
|
||||
}
|
||||
|
||||
/// <summary>Finite numeric values of a tag from the first IFD that has it, or null (also when there are more than <paramref name="max"/>).</summary>
|
||||
private static double[]? Doubles(TiffReader r, Ifd first, Ifd second, ushort tag, int max)
|
||||
{
|
||||
var ifd = first.Has(tag) ? first : second;
|
||||
if (!ifd.Entries.TryGetValue(tag, out var e) || e.Count == 0 || e.Count > max) return null;
|
||||
var values = r.GetDoubles(e);
|
||||
if (values is null) return null;
|
||||
foreach (var v in values)
|
||||
{
|
||||
if (!double.IsFinite(v)) return null;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static double[]? Values(TiffReader r, Ifd first, Ifd second, ushort tag, int count) =>
|
||||
Doubles(r, first, second, tag, 16) is { } v && v.Length >= count && v.All(x => x >= 0 && x < int.MaxValue / 2) ? v : null;
|
||||
}
|
||||
|
||||
/// <summary>Loads a TIFF/DNG raster IFD through <see cref="TiffImageReader.ReadRaster"/>.</summary>
|
||||
internal sealed class TiffRasterLoader(TiffReader reader, Ifd ifd) : RawLoader
|
||||
{
|
||||
public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var raster = TiffImageReader.ReadRaster(reader, ifd, new TiffDecodeOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism });
|
||||
var samples = new RawSamples(raster.Width, raster.Height, raster.SamplesPerPixel, raster.Samples, raster.FloatSamples);
|
||||
samples.Warnings.AddRange(raster.Warnings);
|
||||
return samples;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
using System.Buffers;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Adaptive Homogeneity-Directed demosaicing (K. Hirakawa, T. W. Parks, "Adaptive homogeneity-directed demosaicing
|
||||
/// algorithm", IEEE Trans. Image Processing 14(3), 2005), in the formulation of dcraw's <c>ahd_interpolate</c>:
|
||||
/// green is interpolated horizontally and vertically (gradient-corrected, limited to its two neighbours), red and blue
|
||||
/// follow by colour-difference interpolation in each direction, both candidates are converted to CIELab, and each pixel
|
||||
/// takes the direction whose 3×3 neighbourhood is most homogeneous (Lab distances within adaptive luminance and chroma
|
||||
/// thresholds), or the average on a tie. Works on float data in tiles processed in parallel; a 5-pixel border is
|
||||
/// bilinear.
|
||||
/// </summary>
|
||||
internal static unsafe class AhdDemosaic
|
||||
{
|
||||
private const int Ts = 256;
|
||||
private const int LutSize = 1 << 16;
|
||||
private const float LutScale = LutSize / 2f;
|
||||
|
||||
/// <summary>CIELab f(t) for t in [0, 2): cube root above (6/29)³, the linear toe below.</summary>
|
||||
private static readonly float[] LabF = BuildLabF();
|
||||
|
||||
/// <param name="balancedToXyz">White-balanced camera RGB → XYZ (white at Y = 1), used only for the Lab metric.</param>
|
||||
public static ImageBuffer Run(ImageBuffer mosaic, CfaPattern cfa, Matrix3 balancedToXyz, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cfa.IsBayer) throw new ArgumentException("Bayer pattern expected", nameof(cfa));
|
||||
int w = mosaic.Width, h = mosaic.Height;
|
||||
if (w < 16 || h < 16) return Demosaic.Bilinear(mosaic, cfa, maxDegreeOfParallelism, cancellationToken);
|
||||
var output = new ImageBuffer(w, h, 3, clear: false);
|
||||
Demosaic.BilinearBorder(mosaic, cfa, output, 5);
|
||||
|
||||
// Rows of the matrix are divided by the white's XYZ so that Lab sees X/Xn, Y/Yn, Z/Zn directly.
|
||||
var white = balancedToXyz * new Vector3D(1, 1, 1);
|
||||
var m = new float[9];
|
||||
double[] rows = [balancedToXyz.M11, balancedToXyz.M12, balancedToXyz.M13, balancedToXyz.M21, balancedToXyz.M22, balancedToXyz.M23, balancedToXyz.M31, balancedToXyz.M32, balancedToXyz.M33];
|
||||
double[] whites = [white.X, white.Y, white.Z];
|
||||
for (var i = 0; i < 9; i++) m[i] = (float)(rows[i] / (whites[i / 3] > 0 ? whites[i / 3] : 1));
|
||||
|
||||
var tops = new List<int>();
|
||||
for (var top = 2; top < h - 5; top += Ts - 6) tops.Add(top);
|
||||
var lefts = new List<int>();
|
||||
for (var left = 2; left < w - 5; left += Ts - 6) lefts.Add(left);
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken };
|
||||
var colors = new int[4];
|
||||
for (var i = 0; i < 4; i++) colors[i] = cfa.ColorAt(i & 1, i >> 1);
|
||||
Parallel.For(0, tops.Count * lefts.Count, options, () => new Workspace(), (t, _, ws) =>
|
||||
{
|
||||
Tile(mosaic, output, colors, m, tops[t / lefts.Count], lefts[t % lefts.Count], ws);
|
||||
return ws;
|
||||
}, ws => ws.Dispose());
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>Per-thread tile buffers: two directional RGB and Lab images plus homogeneity counts.</summary>
|
||||
private sealed class Workspace : IDisposable
|
||||
{
|
||||
public readonly float[] Rgb = ArrayPool<float>.Shared.Rent(6 * Ts * Ts);
|
||||
public readonly float[] Lab = ArrayPool<float>.Shared.Rent(6 * Ts * Ts);
|
||||
public readonly byte[] Homo = ArrayPool<byte>.Shared.Rent(2 * Ts * Ts);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
ArrayPool<float>.Shared.Return(Rgb);
|
||||
ArrayPool<float>.Shared.Return(Lab);
|
||||
ArrayPool<byte>.Shared.Return(Homo);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Tile(ImageBuffer mosaic, ImageBuffer output, int[] colors, float[] xyz, int top, int left, Workspace ws)
|
||||
{
|
||||
int w = mosaic.Width, h = mosaic.Height;
|
||||
const int plane = Ts * Ts;
|
||||
fixed (float* image = mosaic.Storage, rgbBase = ws.Rgb, labBase = ws.Lab, mat = xyz, lut = LabF)
|
||||
fixed (byte* homoBase = ws.Homo)
|
||||
fixed (float* outBase = output.Storage)
|
||||
{
|
||||
// Direction d: R, G, B planes at rgbBase + (3d + c)·plane; Lab likewise.
|
||||
var rowEnd = int.Min(top + Ts, h - 2);
|
||||
var colEnd = int.Min(left + Ts, w - 2);
|
||||
|
||||
// 1. Green horizontally and vertically at red/blue sites.
|
||||
for (var row = top; row < rowEnd; row++)
|
||||
{
|
||||
var col = left + (Color(colors, left, row) == 1 ? 1 : 0);
|
||||
var gh = rgbBase + plane + (row - top) * Ts - left;
|
||||
var gv = rgbBase + 4 * plane + (row - top) * Ts - left;
|
||||
for (; col < colEnd; col += 2)
|
||||
{
|
||||
var pix = image + row * w + col;
|
||||
var val = ((pix[-1] + pix[0] + pix[1]) * 2 - pix[-2] - pix[2]) * 0.25f;
|
||||
gh[col] = Limit(val, pix[-1], pix[1]);
|
||||
val = ((pix[-w] + pix[0] + pix[w]) * 2 - pix[-2 * w] - pix[2 * w]) * 0.25f;
|
||||
gv[col] = Limit(val, pix[-w], pix[w]);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Red and blue in each direction, then CIELab.
|
||||
rowEnd = int.Min(top + Ts - 1, h - 3);
|
||||
colEnd = int.Min(left + Ts - 1, w - 3);
|
||||
for (var d = 0; d < 2; d++)
|
||||
{
|
||||
var rgb = rgbBase + 3 * d * plane;
|
||||
var lab = labBase + 3 * d * plane;
|
||||
for (var row = top + 1; row < rowEnd; row++)
|
||||
{
|
||||
for (var col = left + 1; col < colEnd; col++)
|
||||
{
|
||||
var pix = image + row * w + col;
|
||||
var i = (row - top) * Ts + col - left;
|
||||
var r = rgb + i;
|
||||
var own = Color(colors, col, row);
|
||||
float red, green, blue;
|
||||
if (own == 1)
|
||||
{
|
||||
// Colour of the vertical neighbours; the horizontal ones carry the other one.
|
||||
var vertical = Color(colors, col, row + 1);
|
||||
var h0 = pix[0] + (pix[-1] + pix[1] - r[plane - 1] - r[plane + 1]) * 0.5f;
|
||||
var v0 = pix[0] + (pix[-w] + pix[w] - r[plane - Ts] - r[plane + Ts]) * 0.5f;
|
||||
green = pix[0];
|
||||
if (vertical == 0) (red, blue) = (v0, h0);
|
||||
else (red, blue) = (h0, v0);
|
||||
}
|
||||
else
|
||||
{
|
||||
green = r[plane];
|
||||
var opposite = green + (pix[-w - 1] + pix[-w + 1] + pix[w - 1] + pix[w + 1]
|
||||
- r[plane - Ts - 1] - r[plane - Ts + 1] - r[plane + Ts - 1] - r[plane + Ts + 1]) * 0.25f;
|
||||
(red, blue) = own == 0 ? (pix[0], opposite) : (opposite, pix[0]);
|
||||
}
|
||||
red = float.Max(red, 0f);
|
||||
blue = float.Max(blue, 0f);
|
||||
r[0] = red;
|
||||
r[plane] = green;
|
||||
r[2 * plane] = blue;
|
||||
var fx = F(lut, mat[0] * red + mat[1] * green + mat[2] * blue);
|
||||
var fy = F(lut, mat[3] * red + mat[4] * green + mat[5] * blue);
|
||||
var fz = F(lut, mat[6] * red + mat[7] * green + mat[8] * blue);
|
||||
var l = lab + i;
|
||||
l[0] = 116f * fy - 16f;
|
||||
l[plane] = 500f * (fx - fy);
|
||||
l[2 * plane] = 200f * (fy - fz);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Homogeneity: neighbours within adaptive luminance and chroma thresholds.
|
||||
new Span<byte>(homoBase, 2 * plane).Clear();
|
||||
rowEnd = int.Min(top + Ts - 2, h - 4);
|
||||
colEnd = int.Min(left + Ts - 2, w - 4);
|
||||
var labH = labBase;
|
||||
var labV = labBase + 3 * plane;
|
||||
for (var row = top + 2; row < rowEnd; row++)
|
||||
{
|
||||
for (var col = left + 2; col < colEnd; col++)
|
||||
{
|
||||
var i = (row - top) * Ts + col - left;
|
||||
var lh = labH + i;
|
||||
var lv = labV + i;
|
||||
float lh0 = Diff(lh, -1), lh1 = Diff(lh, 1), lh2 = Diff(lh, -Ts), lh3 = Diff(lh, Ts);
|
||||
float lv0 = Diff(lv, -1), lv1 = Diff(lv, 1), lv2 = Diff(lv, -Ts), lv3 = Diff(lv, Ts);
|
||||
float ah0 = Chroma(lh, -1, plane), ah1 = Chroma(lh, 1, plane), ah2 = Chroma(lh, -Ts, plane), ah3 = Chroma(lh, Ts, plane);
|
||||
float av0 = Chroma(lv, -1, plane), av1 = Chroma(lv, 1, plane), av2 = Chroma(lv, -Ts, plane), av3 = Chroma(lv, Ts, plane);
|
||||
var leps = float.Min(float.Max(lh0, lh1), float.Max(lv2, lv3));
|
||||
var abeps = float.Min(float.Max(ah0, ah1), float.Max(av2, av3));
|
||||
homoBase[i] = (byte)(Count(lh0, ah0, leps, abeps) + Count(lh1, ah1, leps, abeps) + Count(lh2, ah2, leps, abeps) + Count(lh3, ah3, leps, abeps));
|
||||
homoBase[plane + i] = (byte)(Count(lv0, av0, leps, abeps) + Count(lv1, av1, leps, abeps) + Count(lv2, av2, leps, abeps) + Count(lv3, av3, leps, abeps));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Most homogeneous direction over 3×3 (average on a tie).
|
||||
rowEnd = int.Min(top + Ts - 3, h - 5);
|
||||
colEnd = int.Min(left + Ts - 3, w - 5);
|
||||
var outPlane = w * h;
|
||||
for (var row = top + 3; row < rowEnd; row++)
|
||||
{
|
||||
for (var col = left + 3; col < colEnd; col++)
|
||||
{
|
||||
var i = (row - top) * Ts + col - left;
|
||||
int hm0 = 0, hm1 = 0;
|
||||
for (var k = -Ts; k <= Ts; k += Ts)
|
||||
{
|
||||
var p = homoBase + i + k;
|
||||
hm0 += p[-1] + p[0] + p[1];
|
||||
hm1 += p[plane - 1] + p[plane] + p[plane + 1];
|
||||
}
|
||||
var o = outBase + row * w + col;
|
||||
var a = rgbBase + i;
|
||||
var b = rgbBase + 3 * plane + i;
|
||||
if (hm0 > hm1)
|
||||
{
|
||||
o[0] = a[0];
|
||||
o[outPlane] = a[plane];
|
||||
o[2 * outPlane] = a[2 * plane];
|
||||
}
|
||||
else if (hm1 > hm0)
|
||||
{
|
||||
o[0] = b[0];
|
||||
o[outPlane] = b[plane];
|
||||
o[2 * outPlane] = b[2 * plane];
|
||||
}
|
||||
else
|
||||
{
|
||||
o[0] = (a[0] + b[0]) * 0.5f;
|
||||
o[outPlane] = (a[plane] + b[plane]) * 0.5f;
|
||||
o[2 * outPlane] = (a[2 * plane] + b[2 * plane]) * 0.5f;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int Color(int[] colors, int x, int y) => colors[(y & 1) << 1 | x & 1];
|
||||
|
||||
private static float Limit(float v, float a, float b) => a < b ? float.Clamp(v, a, b) : float.Clamp(v, b, a);
|
||||
|
||||
private static float F(float* lut, float t)
|
||||
{
|
||||
var i = (int)(t * LutScale);
|
||||
return lut[i < 0 ? 0 : i >= LutSize ? LutSize - 1 : i];
|
||||
}
|
||||
|
||||
private static float Diff(float* l, int offset) => float.Abs(l[0] - l[offset]);
|
||||
|
||||
private static float Chroma(float* l, int offset, int plane)
|
||||
{
|
||||
var da = l[plane] - l[plane + offset];
|
||||
var db = l[2 * plane] - l[2 * plane + offset];
|
||||
return da * da + db * db;
|
||||
}
|
||||
|
||||
private static int Count(float l, float ab, float leps, float abeps) => l <= leps && ab <= abeps ? 1 : 0;
|
||||
|
||||
private static float[] BuildLabF()
|
||||
{
|
||||
var lut = new float[LutSize];
|
||||
for (var i = 0; i < LutSize; i++)
|
||||
{
|
||||
var t = i / (double)LutScale;
|
||||
lut[i] = (float)(t > 216.0 / 24389 ? double.Cbrt(t) : (24389.0 / 27 * t + 16) / 116);
|
||||
}
|
||||
return lut;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Sony ARW: the CFA SubIFD holds uncompressed 16-bit words (or packed samples) or ARW2 "cRAW" (Compression 32767 with
|
||||
/// one byte per pixel): 16-pixel blocks of one colour storing an 11-bit maximum and minimum with their positions and
|
||||
/// fourteen 7-bit deltas scaled by a shift, expanded through the tone curve of tag 0x7010 (dcraw
|
||||
/// <c>sony_arw2_load_raw</c>). Black and white come from tags 0x7310/0x787F when present (14-bit scale), otherwise
|
||||
/// 512 and the curve's top (cRAW) or 16383. As-shot white balance sits in the encrypted SR2 block, which is not read: ARW files develop with daylight
|
||||
/// balance. ARW1 (DSLR-A100) and the lossless ARW 5.0 codec are not supported.
|
||||
/// </summary>
|
||||
internal static class ArwReader
|
||||
{
|
||||
private const uint CompressionSony = 32767;
|
||||
private const ushort ToneCurveTag = 0x7010;
|
||||
private const ushort BlackLevelTag = 0x7310;
|
||||
private const ushort WhiteLevelTag = 0x787F;
|
||||
|
||||
public static RawFrame Read(Stream stream)
|
||||
{
|
||||
var r = TiffReader.Open(stream) ?? throw new InvalidDataException("ARW: missing TIFF header");
|
||||
var chain = r.ReadChain();
|
||||
if (chain.Count == 0) throw new InvalidDataException("ARW: no image directory");
|
||||
var ifd0 = chain[0];
|
||||
var raw = NefReader.FindCfa(r, ifd0) ?? throw new InvalidDataException("ARW: CFA image missing");
|
||||
var (width, height) = NativeRaw.Size(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, r.GetUInt(raw, TiffTags.ImageLength) ?? 0);
|
||||
var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 0);
|
||||
var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1;
|
||||
var (offset, length) = NefReader.Strip(r, raw);
|
||||
var warnings = new List<string>();
|
||||
var cfa = NativeRaw.TiffEpCfa(r, raw);
|
||||
if (cfa is null)
|
||||
{
|
||||
cfa = CfaPattern.Bayer("RGGB");
|
||||
warnings.Add("ARW: CFA pattern missing; RGGB assumed");
|
||||
}
|
||||
if (!cfa.IsBayer) throw new InvalidDataException("ARW: only Bayer sensors are supported");
|
||||
|
||||
RawLoader loader;
|
||||
double black, white;
|
||||
if (compression == CompressionSony && length == (long)width * height)
|
||||
{
|
||||
if (width < 32 || width % 32 != 0) throw new InvalidDataException("ARW: cRAW width must be a multiple of 32");
|
||||
var curve = ToneCurve(r, raw, ifd0);
|
||||
loader = new Arw2Loader(offset, width, height, curve);
|
||||
// Sensor saturation is the largest 11-bit code through the curve.
|
||||
(black, white) = (512, curve[0x7FF << 1]);
|
||||
}
|
||||
else if (length >= (long)width * height * 2)
|
||||
{
|
||||
loader = new PlainRawLoader(offset, length, width, height, 16, words: true, littleEndian: r.LittleEndian);
|
||||
(black, white) = (512, 16383);
|
||||
}
|
||||
else if (compression == 1 && bits is 12 or 14 && length >= ((long)width * bits + 7) / 8 * height)
|
||||
{
|
||||
loader = new PlainRawLoader(offset, length, width, height, bits, words: false, littleEndian: false);
|
||||
(black, white) = (128 << (bits - 12), (1 << bits) - 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidDataException($"ARW: compression {compression} with {length} bytes is not supported");
|
||||
}
|
||||
|
||||
var blackLevel = IfdValue.UInts(r, raw, BlackLevelTag) is { Length: 4 } b
|
||||
? NativeRaw.Black2x2(cfa, [b[0], b[1], b[2], b[3]])
|
||||
: NativeRaw.Black(black);
|
||||
if (IfdValue.UInts(r, raw, WhiteLevelTag) is { Length: > 0 } w) white = w.Max();
|
||||
return NativeRaw.Frame("managed-arw", width, height, cfa, new RawRect(0, 0, width, height), blackLevel, white, null,
|
||||
(int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), r.GetString(ifd0, TiffTags.Make), r.GetString(ifd0, TiffTags.Model), loader, warnings);
|
||||
}
|
||||
|
||||
/// <summary>Tone curve from the four breakpoints of tag 0x7010: slopes 1, 2, 4, 8, 16 between 0, the breakpoints and 4095.</summary>
|
||||
private static ushort[] ToneCurve(TiffReader r, Ifd raw, Ifd ifd0)
|
||||
{
|
||||
Span<int> knots = [0, 0, 0, 0, 0, 4095];
|
||||
if ((IfdValue.UInts(r, raw, ToneCurveTag) ?? IfdValue.UInts(r, ifd0, ToneCurveTag)) is { Length: >= 4 } t)
|
||||
{
|
||||
for (var i = 0; i < 4; i++) knots[i + 1] = (int)(t[i] >> 2 & 0xFFF);
|
||||
}
|
||||
var curve = new ushort[0x1000];
|
||||
for (var i = 0; i < curve.Length; i++) curve[i] = (ushort)i;
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
for (var j = knots[i] + 1; j <= knots[i + 1] && j < curve.Length; j++) curve[j] = (ushort)(curve[j - 1] + (1 << i));
|
||||
}
|
||||
return curve;
|
||||
}
|
||||
|
||||
private sealed class Arw2Loader(long offset, int width, int height, ushort[] curve) : RawLoader
|
||||
{
|
||||
public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var data = NativeRaw.ReadPayload(stream, offset, (long)width * height);
|
||||
var samples = new ushort[width * height];
|
||||
Parallel.For(0, height, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, row =>
|
||||
{
|
||||
// One spare byte: the last delta of a block is read as a 16-bit word that reaches one byte past it.
|
||||
Span<byte> line = stackalloc byte[width + 2];
|
||||
line.Clear();
|
||||
data.AsSpan(row * width, width).CopyTo(line);
|
||||
Span<int> pix = stackalloc int[16];
|
||||
var dst = samples.AsSpan(row * width, width);
|
||||
var dp = 0;
|
||||
for (var col = 0; col < width - 30; dp += 16)
|
||||
{
|
||||
var val = BinaryPrimitives.ReadUInt32LittleEndian(line[dp..]);
|
||||
int max = (int)(val & 0x7FF), min = (int)(val >> 11 & 0x7FF), imax = (int)(val >> 22 & 0xF), imin = (int)(val >> 26 & 0xF);
|
||||
var sh = 0;
|
||||
while (sh < 4 && 0x80 << sh <= max - min) sh++;
|
||||
var bit = 30;
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
if (i == imax)
|
||||
{
|
||||
pix[i] = max;
|
||||
}
|
||||
else if (i == imin)
|
||||
{
|
||||
pix[i] = min;
|
||||
}
|
||||
else
|
||||
{
|
||||
pix[i] = int.Min(((BinaryPrimitives.ReadUInt16LittleEndian(line[(dp + (bit >> 3))..]) >> (bit & 7) & 0x7F) << sh) + min, 0x7FF);
|
||||
bit += 7;
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < 16; i++, col += 2) dst[col] = curve[pix[i] << 1];
|
||||
col -= (col & 1) != 0 ? 1 : 31;
|
||||
}
|
||||
});
|
||||
return new RawSamples(width, height, 1, samples, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Camera colour matrices (XYZ → camera, D65 calibration, values × 10 000) for bodies whose native RAW files Titano
|
||||
/// develops, keyed by the normalised "Brand Model" name. The numbers are the public adobe_coeff table of Dave Coffin's
|
||||
/// dcraw (public-domain origin, also carried by LibRaw), which reproduces the ColorMatrix2 values Adobe DNG Converter
|
||||
/// writes for these cameras; they are data, not code. A body missing here is decoded through its embedded preview.
|
||||
/// </summary>
|
||||
internal static class CameraMatrices
|
||||
{
|
||||
private static readonly Dictionary<string, short[]> Table = Build();
|
||||
|
||||
/// <summary>Matrix for a normalised camera name (see <see cref="NativeRaw.CameraName"/>), or null.</summary>
|
||||
public static Matrix3? Find(string? cameraName)
|
||||
{
|
||||
if (cameraName is null || !Table.TryGetValue(cameraName, out var m)) return null;
|
||||
return new Matrix3(m[0] / 1e4, m[1] / 1e4, m[2] / 1e4, m[3] / 1e4, m[4] / 1e4, m[5] / 1e4, m[6] / 1e4, m[7] / 1e4, m[8] / 1e4);
|
||||
}
|
||||
|
||||
/// <summary>Normalised names with an entry (for diagnostics and tests).</summary>
|
||||
public static IEnumerable<string> Names => Table.Keys;
|
||||
|
||||
private static Dictionary<string, short[]> Build()
|
||||
{
|
||||
var t = new Dictionary<string, short[]>(StringComparer.OrdinalIgnoreCase);
|
||||
void Add(short[] m, params string[] names)
|
||||
{
|
||||
foreach (var n in names) t[n] = m;
|
||||
}
|
||||
|
||||
// Canon (CR2).
|
||||
Add([6347, -479, -972, -8297, 15954, 2480, -1968, 2131, 7649], "Canon EOS 5D");
|
||||
Add([4716, 603, -830, -7798, 15474, 2480, -1496, 1937, 6651], "Canon EOS 5D Mark II");
|
||||
Add([6722, -635, -963, -4287, 12460, 2028, -908, 2162, 5668], "Canon EOS 5D Mark III");
|
||||
Add([6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348], "Canon EOS 5D Mark IV");
|
||||
Add([6250, -711, -808, -5153, 12794, 2636, -1249, 2198, 5610], "Canon EOS 5DS", "Canon EOS 5DS R");
|
||||
Add([7034, -804, -1014, -4420, 12564, 2058, -851, 1994, 5758], "Canon EOS 6D", "Canon EOS 70D");
|
||||
Add([6875, -970, -932, -4691, 12459, 2501, -874, 1953, 5809], "Canon EOS 6D Mark II");
|
||||
Add([6844, -996, -856, -3876, 11761, 2396, -593, 1772, 6198], "Canon EOS 7D");
|
||||
Add([7268, -1082, -969, -4186, 11839, 2663, -825, 2029, 5839], "Canon EOS 7D Mark II");
|
||||
Add([6071, -747, -856, -7653, 15365, 2441, -2025, 2553, 7315], "Canon EOS 40D");
|
||||
Add([4920, 616, -593, -6493, 13964, 2784, -1774, 3178, 7005], "Canon EOS 50D");
|
||||
Add([6719, -994, -925, -4408, 12426, 2211, -887, 2129, 6051], "Canon EOS 60D");
|
||||
Add([7457, -671, -937, -4849, 12495, 2643, -1213, 2354, 5492], "Canon EOS 80D");
|
||||
Add([6941, -1164, -857, -3825, 11597, 2534, -416, 1540, 6039], "Canon EOS 550D", "Canon EOS Rebel T2i", "Canon EOS Kiss X4");
|
||||
Add([6461, -907, -882, -4300, 12184, 2378, -819, 1944, 5931], "Canon EOS 600D", "Canon EOS Rebel T3i", "Canon EOS Kiss X5",
|
||||
"Canon EOS 1200D", "Canon EOS Rebel T5", "Canon EOS Kiss X70");
|
||||
Add([6602, -841, -939, -4472, 12458, 2247, -975, 2039, 6148], "Canon EOS 650D", "Canon EOS Rebel T4i", "Canon EOS Kiss X6i",
|
||||
"Canon EOS 700D", "Canon EOS Rebel T5i", "Canon EOS Kiss X7i", "Canon EOS 100D", "Canon EOS Rebel SL1", "Canon EOS Kiss X7", "Canon EOS M");
|
||||
Add([6362, -823, -847, -4426, 12109, 2616, -743, 1857, 5635], "Canon EOS 750D", "Canon EOS Rebel T6i", "Canon EOS Kiss X8i",
|
||||
"Canon EOS 760D", "Canon EOS Rebel T6s", "Canon EOS 8000D");
|
||||
Add([7377, -742, -998, -4235, 11981, 2549, -673, 1918, 5538], "Canon EOS 77D", "Canon EOS 9000D", "Canon EOS 800D", "Canon EOS Rebel T7i", "Canon EOS Kiss X9i");
|
||||
Add([6847, -614, -1014, -4669, 12737, 2139, -1197, 2488, 6846], "Canon EOS-1D X");
|
||||
Add([7596, -978, -967, -4808, 12571, 2503, -1398, 2567, 5752], "Canon EOS-1D X Mark II");
|
||||
|
||||
// Nikon (NEF).
|
||||
Add([7309, -1403, -519, -8474, 16008, 2622, -2434, 2826, 8064], "Nikon D90");
|
||||
Add([9030, -1992, -715, -8465, 16302, 2255, -2689, 3217, 8069], "Nikon D300", "Nikon D300S");
|
||||
Add([8139, -2171, -663, -8747, 16541, 2295, -1925, 2008, 8093], "Nikon D3", "Nikon D700");
|
||||
Add([8828, -2406, -694, -4874, 12603, 2541, -660, 1509, 7587], "Nikon D3S");
|
||||
Add([7171, -1986, -648, -8085, 15555, 2718, -2170, 2512, 7457], "Nikon D3X");
|
||||
Add([8598, -2848, -857, -5618, 13606, 2195, -1002, 1773, 7137], "Nikon D4", "Nikon Df");
|
||||
Add([9200, -3522, -992, -5755, 13803, 2117, -753, 1486, 6338], "Nikon D5");
|
||||
Add([7911, -2167, -813, -5327, 13150, 2408, -1288, 2483, 7968], "Nikon D3100");
|
||||
Add([7013, -1408, -635, -5268, 12902, 2640, -1470, 2801, 7379], "Nikon D3200");
|
||||
Add([6988, -1384, -714, -5631, 13410, 2447, -1485, 2204, 7318], "Nikon D3300", "Nikon D3400", "Nikon D5300");
|
||||
Add([8198, -2239, -724, -4871, 12389, 2798, -1043, 2050, 7181], "Nikon D5100", "Nikon D7000");
|
||||
Add([8322, -3112, -1047, -6367, 14342, 2179, -988, 1638, 6394], "Nikon D5200", "Nikon D7100", "Nikon D7200");
|
||||
Add([8821, -2938, -785, -4178, 12142, 2287, -824, 1651, 6860], "Nikon D5500", "Nikon D5600");
|
||||
Add([8813, -3210, -1036, -4703, 12868, 2021, -1054, 1940, 6129], "Nikon D500", "Nikon D7500");
|
||||
Add([8178, -2245, -609, -4857, 12394, 2776, -1207, 2086, 7298], "Nikon D600", "Nikon D610");
|
||||
Add([9020, -2890, -715, -4535, 12436, 2348, -934, 1919, 7086], "Nikon D750");
|
||||
Add([7866, -2108, -555, -4869, 12483, 2681, -1176, 2069, 7501], "Nikon D800", "Nikon D800E");
|
||||
Add([9369, -3195, -791, -4488, 12430, 2301, -893, 1796, 6872], "Nikon D810");
|
||||
Add([10405, -3755, -1270, -5461, 13787, 1793, -1040, 2015, 6785], "Nikon D850", "Nikon Z 7");
|
||||
Add([8210, -2534, -683, -5355, 13338, 2212, -1143, 1929, 6464], "Nikon Z 6");
|
||||
|
||||
// Sony (ARW).
|
||||
Add([5271, -712, -347, -6153, 13653, 2763, -1601, 2366, 7242], "Sony ILCE-7", "Sony ILCE-7M2");
|
||||
Add([7374, -2389, -551, -5435, 13162, 2519, -1006, 1795, 6552], "Sony ILCE-7M3");
|
||||
Add([4913, -541, -202, -6130, 13513, 2906, -1564, 2151, 7183], "Sony ILCE-7R");
|
||||
Add([6629, -1900, -483, -4618, 12349, 2550, -622, 1381, 6514], "Sony ILCE-7RM2");
|
||||
Add([6640, -1847, -503, -5238, 13010, 2474, -993, 1673, 6527], "Sony ILCE-7RM3");
|
||||
Add([5838, -1430, -246, -3497, 11477, 2297, -748, 1885, 5778], "Sony ILCE-7S", "Sony ILCE-7SM2");
|
||||
Add([5991, -1456, -455, -4764, 12135, 2980, -707, 1425, 6701], "Sony ILCE-6000", "Sony ILCE-5100", "Sony SLT-A57");
|
||||
Add([5973, -1695, -419, -3826, 11797, 2293, -639, 1398, 5789], "Sony ILCE-6300", "Sony ILCE-6500", "Sony ILCE-6400");
|
||||
Add([5491, -1192, -363, -4951, 12342, 2948, -911, 1722, 7192], "Sony NEX-7", "Sony SLT-A65", "Sony SLT-A77");
|
||||
Add([8651, -2754, -1057, -3464, 12207, 1373, -568, 1398, 4434], "Sony DSC-RX100");
|
||||
Add([6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181], "Sony DSC-RX100M2");
|
||||
|
||||
// Pentax (PEF).
|
||||
Add([9566, -2863, -803, -7170, 15172, 2112, -818, 803, 9705], "Pentax K10D");
|
||||
Add([9427, -2714, -868, -7493, 16092, 1373, -2199, 3264, 7180], "Pentax K20D");
|
||||
Add([9142, -2947, -678, -8648, 16967, 1663, -2224, 2898, 8615], "Pentax K-7");
|
||||
Add([8713, -2833, -743, -4342, 11900, 2772, -722, 1543, 6247], "Pentax K-5");
|
||||
Add([8170, -2725, -639, -4440, 12017, 2744, -771, 1465, 6599], "Pentax K-5 II", "Pentax K-5 II s");
|
||||
Add([8843, -2837, -625, -5025, 12644, 2668, -411, 1234, 7410], "Pentax K-x");
|
||||
Add([9895, -3077, -850, -5304, 13035, 2521, -883, 1768, 6936], "Pentax K-r");
|
||||
Add([8710, -2632, -1167, -3995, 12301, 1881, -981, 1719, 6535], "Pentax K-30");
|
||||
Add([7415, -2052, -721, -5186, 12788, 2682, -1446, 2157, 6773], "Pentax K-3");
|
||||
Add([8596, -2981, -639, -4202, 12046, 2431, -685, 1424, 6122], "Pentax K-1");
|
||||
|
||||
// Fujifilm (RAF).
|
||||
Add([10413, -3996, -993, -3721, 11640, 2361, -733, 1540, 6011], "Fujifilm X-E1", "Fujifilm X-Pro1", "Fujifilm X-M1");
|
||||
Add([10592, -4262, -1008, -3514, 11355, 2465, -870, 2025, 6386], "Fujifilm X100S", "Fujifilm X20");
|
||||
Add([8458, -2451, -855, -4597, 12447, 2407, -1475, 2482, 6526], "Fujifilm X-T1", "Fujifilm X-E2", "Fujifilm X-T10", "Fujifilm X100T", "Fujifilm X30");
|
||||
Add([11434, -4948, -1210, -3746, 12042, 1903, -666, 1479, 5235], "Fujifilm X-T2", "Fujifilm X-Pro2", "Fujifilm X-T20", "Fujifilm X100F", "Fujifilm X-E3");
|
||||
Add([13426, -6334, -1177, -4244, 12136, 2371, -580, 1303, 5980], "Fujifilm X-T3", "Fujifilm X-T30");
|
||||
Add([11086, -4555, -839, -3512, 11310, 2517, -815, 1341, 5940], "Fujifilm X-A1");
|
||||
return t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Colour filter array layout (DNG 1.6 §"CFARepeatPatternDim"/"CFAPattern"): the colour of every cell of a pattern
|
||||
/// that repeats over the image, 0 = red, 1 = green, 2 = blue. The origin is the top-left pixel of the image the pattern
|
||||
/// is attached to (the DNG active area); <see cref="Shift"/> re-anchors it for a sub-image.
|
||||
/// </summary>
|
||||
public sealed class CfaPattern
|
||||
{
|
||||
public const int MaxSize = 8;
|
||||
|
||||
private readonly byte[] _colors;
|
||||
|
||||
/// <exception cref="InvalidDataException">The size is outside 1–8, a colour is not 0–2, or a primary is missing.</exception>
|
||||
public CfaPattern(int width, int height, ReadOnlySpan<byte> colors)
|
||||
{
|
||||
if (width is < 1 or > MaxSize || height is < 1 or > MaxSize || colors.Length < width * height)
|
||||
throw new InvalidDataException($"CFA: unsupported pattern size {width}x{height}");
|
||||
Span<bool> seen = stackalloc bool[3];
|
||||
foreach (var c in colors[..(width * height)])
|
||||
{
|
||||
if (c > 2) throw new InvalidDataException($"CFA: colour {c} is not red, green or blue");
|
||||
seen[c] = true;
|
||||
}
|
||||
if (!seen[0] || !seen[1] || !seen[2]) throw new InvalidDataException("CFA: pattern lacks a primary colour");
|
||||
(Width, Height, _colors) = Reduce(width, height, colors[..(width * height)]);
|
||||
}
|
||||
|
||||
/// <summary>Repeat width after reduction to the smallest period (a 4×4 Bayer description becomes 2×2).</summary>
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
/// <summary>A 2×2 pattern with one red, one blue and two diagonal greens.</summary>
|
||||
public bool IsBayer => Width == 2 && Height == 2 && (_colors[0] == 1 && _colors[3] == 1 || _colors[1] == 1 && _colors[2] == 1);
|
||||
|
||||
/// <summary>Block edge for colour binning (half-size decoding): 2 for Bayer, 3 when every aligned 3×3 block holds all
|
||||
/// three primaries (X-Trans), 0 when the pattern cannot be binned.</summary>
|
||||
public int BinSize
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsBayer) return 2;
|
||||
if (Width % 3 != 0 || Height % 3 != 0) return 0;
|
||||
for (var by = 0; by < Height; by += 3)
|
||||
{
|
||||
for (var bx = 0; bx < Width; bx += 3)
|
||||
{
|
||||
var mask = 0;
|
||||
for (var y = 0; y < 3; y++)
|
||||
{
|
||||
for (var x = 0; x < 3; x++) mask |= 1 << ColorAt(bx + x, by + y);
|
||||
}
|
||||
if (mask != 7) return 0;
|
||||
}
|
||||
}
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Colour at image coordinates (non-negative).</summary>
|
||||
public int ColorAt(int x, int y) => _colors[y % Height * Width + x % Width];
|
||||
|
||||
/// <summary>Pattern of the sub-image whose top-left pixel is (<paramref name="dx"/>, <paramref name="dy"/>) here.</summary>
|
||||
public CfaPattern Shift(int dx, int dy)
|
||||
{
|
||||
var colors = new byte[Width * Height];
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++) colors[y * Width + x] = (byte)ColorAt(x + PositiveModulo(dx, Width), y + PositiveModulo(dy, Height));
|
||||
}
|
||||
return new CfaPattern(Width, Height, colors);
|
||||
}
|
||||
|
||||
/// <summary>Bayer pattern from its top-left 2×2 letters ("RGGB", "BGGR", "GRBG", "GBRG").</summary>
|
||||
public static CfaPattern Bayer(string layout)
|
||||
{
|
||||
if (layout.Length != 4) throw new ArgumentException("Four letters expected", nameof(layout));
|
||||
var colors = new byte[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
colors[i] = char.ToUpperInvariant(layout[i]) switch
|
||||
{
|
||||
'R' => 0,
|
||||
'G' => 1,
|
||||
'B' => 2,
|
||||
_ => throw new ArgumentException("Letters must be R, G or B", nameof(layout)),
|
||||
};
|
||||
}
|
||||
return new CfaPattern(2, 2, colors);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(Width * Height + 8);
|
||||
for (var i = 0; i < Width * Height; i++) sb.Append("RGB"[_colors[i]]);
|
||||
return Width == 2 && Height == 2 ? sb.ToString() : $"{Width}x{Height}:{sb}";
|
||||
}
|
||||
|
||||
private static int PositiveModulo(int value, int m) => (value % m + m) % m;
|
||||
|
||||
private static (int Width, int Height, byte[] Colors) Reduce(int width, int height, ReadOnlySpan<byte> colors)
|
||||
{
|
||||
var w = width;
|
||||
for (var p = 1; p < width; p++)
|
||||
{
|
||||
if (width % p == 0 && Periodic(colors, width, height, p, 0))
|
||||
{
|
||||
w = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
var h = height;
|
||||
for (var p = 1; p < height; p++)
|
||||
{
|
||||
if (height % p == 0 && Periodic(colors, width, height, 0, p))
|
||||
{
|
||||
h = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
var reduced = new byte[w * h];
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++) reduced[y * w + x] = colors[y * width + x];
|
||||
}
|
||||
return (w, h, reduced);
|
||||
}
|
||||
|
||||
private static bool Periodic(ReadOnlySpan<byte> colors, int width, int height, int px, int py)
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
if (colors[y * width + x] != colors[(y + py) % height * width + (x + px) % width]) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Canon CR2: the fourth IFD holds one lossless-JPEG (SOF3) strip whose samples are laid out in vertical slices
|
||||
/// (tag 0xC640 cr2_slice = count, slice width, last slice width; dcraw <c>lossless_jpeg_load_raw</c>). The MakerNote
|
||||
/// supplies SensorInfo (0x00E0: sensor borders, i.e. the active area) and ColorData (0x4001: as-shot RGGB levels at a
|
||||
/// version-dependent offset). Black is measured on the masked left columns. sRAW/mRAW (subsampled YCbCr) is not
|
||||
/// supported and falls back to the preview.
|
||||
/// </summary>
|
||||
internal static class Cr2Reader
|
||||
{
|
||||
private const ushort SliceTag = 0xC640;
|
||||
private const ushort SensorInfoTag = 0x00E0;
|
||||
private const ushort ColorDataTag = 0x4001;
|
||||
private const int RawIfdIndex = 3;
|
||||
private const int HeaderProbeBytes = 64 * 1024;
|
||||
|
||||
public static RawFrame Read(Stream stream)
|
||||
{
|
||||
var r = TiffReader.Open(stream) ?? throw new InvalidDataException("CR2: missing TIFF header");
|
||||
var chain = r.ReadChain();
|
||||
if (chain.Count <= RawIfdIndex) throw new InvalidDataException("CR2: raw IFD missing");
|
||||
var ifd0 = chain[0];
|
||||
var raw = chain[RawIfdIndex];
|
||||
var offset = r.GetUInt(raw, TiffTags.StripOffsets) ?? throw new InvalidDataException("CR2: raw strip missing");
|
||||
var length = r.GetUInt(raw, TiffTags.StripByteCounts) ?? throw new InvalidDataException("CR2: raw strip length missing");
|
||||
if (offset + (long)length > stream.Length || length < 16) throw new InvalidDataException("CR2: raw strip outside the file");
|
||||
|
||||
var head = NativeRaw.ReadPayload(stream, offset, long.Min(length, HeaderProbeBytes));
|
||||
JpegInfo info;
|
||||
try
|
||||
{
|
||||
info = JpegDecoder.ReadInfo(head);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
throw new InvalidDataException("CR2: raw strip is not a JPEG: " + ex.Message);
|
||||
}
|
||||
if (info.Process != JpegProcess.Lossless) throw new InvalidDataException("CR2: raw strip is not lossless JPEG");
|
||||
if (info.Sampling.Any(s => s != (1, 1))) throw new InvalidDataException("CR2: sRAW/mRAW is not supported");
|
||||
var rawWidth = (long)info.Width * info.Components;
|
||||
var slices = IfdValue.UInts(r, raw, SliceTag);
|
||||
if (slices is [var count, var sliceWidth, var lastWidth, ..] && count + sliceWidth + lastWidth > 0)
|
||||
{
|
||||
if (count * (long)sliceWidth + lastWidth != rawWidth || lastWidth == 0 || count > 0 && sliceWidth == 0)
|
||||
throw new InvalidDataException("CR2: slice layout does not match the JPEG frame");
|
||||
}
|
||||
else
|
||||
{
|
||||
slices = null;
|
||||
}
|
||||
var (width, height) = NativeRaw.Size(rawWidth, info.Height);
|
||||
NativeRaw.RequireBits(length, (long)width * height);
|
||||
|
||||
var make = r.GetString(ifd0, TiffTags.Make);
|
||||
var model = r.GetString(ifd0, TiffTags.Model);
|
||||
var warnings = new List<string>();
|
||||
var makerNote = MakerNote(r, ifd0);
|
||||
var active = new RawRect(0, 0, width, height);
|
||||
if (makerNote is not null && IfdValue.UInts(r, makerNote, SensorInfoTag) is { Length: >= 9 } sensor)
|
||||
{
|
||||
// SensorInfo borders are inclusive pixel indices.
|
||||
var area = new RawRect((int)sensor[5], (int)sensor[6], (int)sensor[7] + 1, (int)sensor[8] + 1).Intersect(active);
|
||||
if (!area.IsEmpty && sensor[7] > sensor[5] && sensor[8] > sensor[6]) active = area;
|
||||
else warnings.Add("CR2: SensorInfo borders ignored");
|
||||
}
|
||||
else
|
||||
{
|
||||
warnings.Add("CR2: SensorInfo missing; full raster used");
|
||||
}
|
||||
var cfa = CfaPattern.Bayer("RGGB").Shift(active.Left, active.Top);
|
||||
var white = (1 << info.Precision) - 1;
|
||||
var loader = new Cr2Loader(offset, length, width, height, slices, active);
|
||||
return NativeRaw.Frame("managed-cr2", width, height, cfa, active, NativeRaw.Black(0), white,
|
||||
Multipliers(r, makerNote), (int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), make, model, loader, warnings);
|
||||
}
|
||||
|
||||
/// <summary>Canon MakerNote: a plain IFD inside the Exif IFD, offsets relative to the TIFF header.</summary>
|
||||
private static Ifd? MakerNote(TiffReader r, Ifd ifd0)
|
||||
{
|
||||
if (NativeRaw.ExifIfd(r, ifd0) is not { } exif || !exif.Entries.TryGetValue(TiffTags.MakerNote, out var note) || note.IsInline) return null;
|
||||
return r.ReadIfd(note.ValueOffset);
|
||||
}
|
||||
|
||||
/// <summary>As-shot RGGB levels from ColorData; the offset (in 16-bit words) depends on the record's length (dcraw).</summary>
|
||||
private static Vector3D? Multipliers(TiffReader r, Ifd? makerNote)
|
||||
{
|
||||
if (makerNote is null || !makerNote.Entries.TryGetValue(ColorDataTag, out var e) || e.Count <= 500 || e.Count > 8192) return null;
|
||||
var data = r.GetUInts(e);
|
||||
if (data is null) return null;
|
||||
var at = data.Length switch { 582 => 25, 653 => 34, 5120 => 71, _ => 63 };
|
||||
if (at + 4 > data.Length) return null;
|
||||
double red = data[at], green = (data[at + 1] + data[at + 2]) / 2.0, blue = data[at + 3];
|
||||
return red > 0 && green > 0 && blue > 0 ? new Vector3D(red / green, 1, blue / green) : null;
|
||||
}
|
||||
|
||||
/// <summary>Decodes the strip, places samples by slice, and measures black on the masked columns left of the active area.</summary>
|
||||
private sealed class Cr2Loader(long offset, long length, int width, int height, uint[]? slices, RawRect active) : RawLoader
|
||||
{
|
||||
public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var data = NativeRaw.ReadPayload(stream, offset, length);
|
||||
var jpeg = JpegLosslessDecoder.Decode(data);
|
||||
var src = jpeg.Samples;
|
||||
if ((long)jpeg.Width * jpeg.Components != width || jpeg.Height != height) throw new InvalidDataException("CR2: JPEG frame changed size");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
ushort[] samples;
|
||||
if (slices is null)
|
||||
{
|
||||
samples = src;
|
||||
}
|
||||
else
|
||||
{
|
||||
samples = new ushort[src.Length];
|
||||
int count = (int)slices[0], sliceWidth = (int)slices[1], lastWidth = (int)slices[2];
|
||||
var perSlice = (long)sliceWidth * height;
|
||||
Parallel.For(0, count + 1, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, s =>
|
||||
{
|
||||
var w = s < count ? sliceWidth : lastWidth;
|
||||
var start = s * perSlice;
|
||||
for (var row = 0; row < height; row++)
|
||||
{
|
||||
src.AsSpan((int)(start + (long)row * w), w).CopyTo(samples.AsSpan(row * width + s * sliceWidth, w));
|
||||
}
|
||||
});
|
||||
}
|
||||
var result = new RawSamples(width, height, 1, samples, null);
|
||||
result.MeasuredBlack = MaskedBlack(samples, result.Warnings);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Per-CFA-colour mean of the masked columns (4 px away from both edges of the mask).</summary>
|
||||
private RawBlackLevel MaskedBlack(ushort[] samples, List<string> warnings)
|
||||
{
|
||||
if (active.Left < 12)
|
||||
{
|
||||
warnings.Add("CR2: no masked columns; black level 0 assumed");
|
||||
return NativeRaw.Black(0);
|
||||
}
|
||||
Span<double> sum = stackalloc double[4];
|
||||
Span<long> n = stackalloc long[4];
|
||||
for (var y = active.Top; y < active.Bottom; y++)
|
||||
{
|
||||
for (var x = 4; x < active.Left - 4; x++)
|
||||
{
|
||||
// Cell index relative to the active area's CFA phase.
|
||||
var cell = ((y - active.Top) & 1) * 2 + ((x - active.Left) & 1);
|
||||
sum[cell] += samples[y * width + x];
|
||||
n[cell]++;
|
||||
}
|
||||
}
|
||||
var values = new float[4];
|
||||
for (var i = 0; i < 4; i++) values[i] = n[i] > 0 ? (float)(sum[i] / n[i]) : 0f;
|
||||
return new RawBlackLevel(2, 2, values, null, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Fast CFA reconstructions: bilinear for Bayer mosaics (Draft quality), a colour-difference neighbourhood interpolation
|
||||
/// for any other pattern (X-Trans), and colour binning (half/third size). Inputs are single-plane mosaics with the pattern
|
||||
/// anchored at pixel (0, 0); outputs are R, G, B planes.
|
||||
/// </summary>
|
||||
internal static class Demosaic
|
||||
{
|
||||
/// <summary>Bilinear interpolation of a Bayer mosaic: missing greens from the 4 orthogonal neighbours, red/blue from the
|
||||
/// 2 or 4 nearest of their colour. Borders mirror around the edge pixel, which preserves the CFA phase.</summary>
|
||||
public static ImageBuffer Bilinear(ImageBuffer mosaic, CfaPattern cfa, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cfa.IsBayer) throw new ArgumentException("Bayer pattern expected", nameof(cfa));
|
||||
int w = mosaic.Width, h = mosaic.Height;
|
||||
var output = new ImageBuffer(w, h, 3, clear: false);
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken };
|
||||
Parallel.For(0, h, options, y =>
|
||||
{
|
||||
var interior = y >= 1 && y < h - 1;
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
if (interior && x >= 1 && x < w - 1) BilinearInterior(mosaic, cfa, output, x, y);
|
||||
else BilinearAt(mosaic, cfa, output, x, y);
|
||||
}
|
||||
});
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>Bilinear values for the pixels within <paramref name="band"/> of the border (AHD leaves them to this).</summary>
|
||||
public static void BilinearBorder(ImageBuffer mosaic, CfaPattern cfa, ImageBuffer output, int band)
|
||||
{
|
||||
int w = mosaic.Width, h = mosaic.Height;
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var edgeRow = y < band || y >= h - band;
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
if (!edgeRow && x == band) x = int.Max(x, w - band);
|
||||
if (x < w) BilinearAt(mosaic, cfa, output, x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void BilinearInterior(ImageBuffer mosaic, CfaPattern cfa, ImageBuffer output, int x, int y)
|
||||
{
|
||||
var m = mosaic.Plane(0);
|
||||
var w = mosaic.Width;
|
||||
var i = y * w + x;
|
||||
var c = cfa.ColorAt(x, y);
|
||||
float r, g, b;
|
||||
if (c == 1)
|
||||
{
|
||||
var horizontal = (m[i - 1] + m[i + 1]) * 0.5f;
|
||||
var vertical = (m[i - w] + m[i + w]) * 0.5f;
|
||||
g = m[i];
|
||||
if (cfa.ColorAt(x + 1, y) == 0) (r, b) = (horizontal, vertical);
|
||||
else (r, b) = (vertical, horizontal);
|
||||
}
|
||||
else
|
||||
{
|
||||
g = (m[i - 1] + m[i + 1] + m[i - w] + m[i + w]) * 0.25f;
|
||||
var diagonal = (m[i - w - 1] + m[i - w + 1] + m[i + w - 1] + m[i + w + 1]) * 0.25f;
|
||||
(r, b) = c == 0 ? (m[i], diagonal) : (diagonal, m[i]);
|
||||
}
|
||||
output.Plane(0)[i] = r;
|
||||
output.Plane(1)[i] = g;
|
||||
output.Plane(2)[i] = b;
|
||||
}
|
||||
|
||||
private static void BilinearAt(ImageBuffer mosaic, CfaPattern cfa, ImageBuffer output, int x, int y)
|
||||
{
|
||||
Span<float> sum = stackalloc float[3];
|
||||
Span<int> count = stackalloc int[3];
|
||||
var own = cfa.ColorAt(x, y);
|
||||
for (var dy = -1; dy <= 1; dy++)
|
||||
{
|
||||
for (var dx = -1; dx <= 1; dx++)
|
||||
{
|
||||
// Greens come from orthogonal neighbours only; the diagonal ones belong to the other green rows.
|
||||
var sx = Mirror(x + dx, mosaic.Width);
|
||||
var sy = Mirror(y + dy, mosaic.Height);
|
||||
var c = cfa.ColorAt(sx, sy);
|
||||
if (c == own && (dx | dy) != 0) continue;
|
||||
if (c == 1 && dx != 0 && dy != 0) continue;
|
||||
sum[c] += mosaic.Plane(0)[sy * mosaic.Width + sx];
|
||||
count[c]++;
|
||||
}
|
||||
}
|
||||
var i = y * mosaic.Width + x;
|
||||
for (var c = 0; c < 3; c++) output.Plane(c)[i] = count[c] > 0 ? sum[c] / count[c] : 0f;
|
||||
}
|
||||
|
||||
private static int Mirror(int v, int size) => v < 0 ? int.Min(-v, size - 1) : v >= size ? int.Max(2 * size - 2 - v, 0) : v;
|
||||
|
||||
/// <summary>
|
||||
/// Colour-difference interpolation for any CFA (used for X-Trans): green from the greens of the 3×3 neighbourhood, then
|
||||
/// red and blue as interpolated green plus the mean (colour − green) difference of their own 3×3 samples (5×5 when the
|
||||
/// 3×3 holds none). Simpler than Markesteijn's X-Trans algorithm but artefact-free on smooth content.
|
||||
/// </summary>
|
||||
public static ImageBuffer Neighbourhood(ImageBuffer mosaic, CfaPattern cfa, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
int w = mosaic.Width, h = mosaic.Height;
|
||||
var output = new ImageBuffer(w, h, 3, clear: false);
|
||||
var m = mosaic.Storage;
|
||||
var green = output.Storage.AsMemory(w * h, w * h);
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken };
|
||||
Parallel.For(0, h, options, y =>
|
||||
{
|
||||
var g = green.Span;
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
g[y * w + x] = cfa.ColorAt(x, y) == 1 ? m[y * w + x] : Mean(m, w, h, cfa, x, y, 1, null);
|
||||
}
|
||||
});
|
||||
Parallel.For(0, h, options, y =>
|
||||
{
|
||||
var g = green.Span;
|
||||
var red = output.Row(0, y);
|
||||
var blue = output.Row(2, y);
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var own = cfa.ColorAt(x, y);
|
||||
var gv = g[y * w + x];
|
||||
red[x] = own == 0 ? m[y * w + x] : float.Max(0f, gv + Mean(m, w, h, cfa, x, y, 0, g));
|
||||
blue[x] = own == 2 ? m[y * w + x] : float.Max(0f, gv + Mean(m, w, h, cfa, x, y, 2, g));
|
||||
}
|
||||
});
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>Mean of colour <paramref name="color"/> samples around (x, y) — of (sample − green) when
|
||||
/// <paramref name="green"/> is given — over 3×3, widened to 5×5 when the 3×3 holds none.</summary>
|
||||
private static float Mean(float[] m, int w, int h, CfaPattern cfa, int x, int y, int color, Span<float> green)
|
||||
{
|
||||
for (var r = 1; r <= 2; r++)
|
||||
{
|
||||
var sum = 0f;
|
||||
var n = 0;
|
||||
for (var dy = -r; dy <= r; dy++)
|
||||
{
|
||||
var sy = y + dy;
|
||||
if ((uint)sy >= (uint)h) continue;
|
||||
for (var dx = -r; dx <= r; dx++)
|
||||
{
|
||||
var sx = x + dx;
|
||||
if ((uint)sx >= (uint)w || (dx | dy) == 0 || cfa.ColorAt(sx, sy) != color) continue;
|
||||
var i = sy * w + sx;
|
||||
sum += green.IsEmpty ? m[i] : m[i] - green[i];
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n > 0) return sum / n;
|
||||
}
|
||||
return 0f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Colour binning: each aligned <paramref name="size"/>×<paramref name="size"/> block becomes one RGB pixel holding the
|
||||
/// mean of its samples of each colour (dcraw's half-size mode for Bayer; one third for X-Trans). Partial blocks at the
|
||||
/// right/bottom edge are dropped.
|
||||
/// </summary>
|
||||
public static ImageBuffer Bin(ImageBuffer mosaic, CfaPattern cfa, int size, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
int w = mosaic.Width / size, h = mosaic.Height / size;
|
||||
if (w < 1 || h < 1) throw new InvalidDataException("RAW: image too small to bin");
|
||||
var output = new ImageBuffer(w, h, 3, clear: false);
|
||||
var src = mosaic.Storage;
|
||||
var stride = mosaic.Width;
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken };
|
||||
Parallel.For(0, h, options, by =>
|
||||
{
|
||||
Span<float> sum = stackalloc float[3];
|
||||
Span<int> count = stackalloc int[3];
|
||||
var r = output.Row(0, by);
|
||||
var g = output.Row(1, by);
|
||||
var b = output.Row(2, by);
|
||||
for (var bx = 0; bx < w; bx++)
|
||||
{
|
||||
sum.Clear();
|
||||
count.Clear();
|
||||
for (var dy = 0; dy < size; dy++)
|
||||
{
|
||||
var y = by * size + dy;
|
||||
for (var dx = 0; dx < size; dx++)
|
||||
{
|
||||
var x = bx * size + dx;
|
||||
var c = cfa.ColorAt(x, y);
|
||||
sum[c] += src[y * stride + x];
|
||||
count[c]++;
|
||||
}
|
||||
}
|
||||
r[bx] = sum[0] / count[0];
|
||||
g[bx] = sum[1] / count[1];
|
||||
b[bx] = sum[2] / count[2];
|
||||
}
|
||||
});
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Clip-aware highlight reconstruction on white-balanced camera RGB. Per pixel, the channels whose raw samples clipped
|
||||
/// (bit c of the clip map) are only known to be at least their clip level; they are raised to the mean of the unclipped
|
||||
/// channels when that is larger (a near-white highlight that clipped green first comes back neutral instead of magenta),
|
||||
/// then the pixel is desaturated toward a grey at its brightest channel as the unclipped channels approach their own clip
|
||||
/// levels. Fully clipped pixels become that grey at no less than the highest clip level. Pixels without clipped samples
|
||||
/// are untouched.
|
||||
/// </summary>
|
||||
internal static class HighlightReconstruction
|
||||
{
|
||||
/// <summary>Fraction of its clip level at which an unclipped channel starts pulling the pixel toward white.</summary>
|
||||
private const float DesaturationStart = 0.7f;
|
||||
|
||||
/// <param name="rgb">White-balanced camera RGB, modified in place.</param>
|
||||
/// <param name="clipBits">Per pixel: bit c set when channel c is built from clipped raw samples.</param>
|
||||
/// <param name="clipLevels">Clip level of each channel in <paramref name="rgb"/>'s units (the white-balance multipliers
|
||||
/// when raw white is 1).</param>
|
||||
public static void Apply(ImageBuffer rgb, byte[] clipBits, ReadOnlySpan<float> clipLevels, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var levels = clipLevels.ToArray();
|
||||
var top = float.Max(levels[0], float.Max(levels[1], levels[2]));
|
||||
int w = rgb.Width;
|
||||
Parallel.For(0, rgb.Height, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var r = rgb.Row(0, y);
|
||||
var g = rgb.Row(1, y);
|
||||
var b = rgb.Row(2, y);
|
||||
var bits = clipBits.AsSpan(y * w, w);
|
||||
Span<float> v = stackalloc float[3];
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var clipped = bits[x] & 7;
|
||||
if (clipped == 0) continue;
|
||||
v[0] = r[x];
|
||||
v[1] = g[x];
|
||||
v[2] = b[x];
|
||||
if (clipped == 7)
|
||||
{
|
||||
var level = float.Max(top, float.Max(v[0], float.Max(v[1], v[2])));
|
||||
r[x] = g[x] = b[x] = level;
|
||||
continue;
|
||||
}
|
||||
float sum = 0, closeness = float.MaxValue;
|
||||
var n = 0;
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
if ((clipped & 1 << c) != 0) continue;
|
||||
sum += v[c];
|
||||
n++;
|
||||
closeness = float.Min(closeness, v[c] / levels[c]);
|
||||
}
|
||||
var estimate = sum / n;
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
if ((clipped & 1 << c) != 0) v[c] = float.Max(v[c], estimate);
|
||||
}
|
||||
var t = float.Clamp((closeness - DesaturationStart) / (1 - DesaturationStart), 0f, 1f);
|
||||
t = t * t * (3 - 2 * t);
|
||||
var grey = float.Max(v[0], float.Max(v[1], v[2]));
|
||||
r[x] = v[0] + (grey - v[0]) * t;
|
||||
g[x] = v[1] + (grey - v[1]) * t;
|
||||
b[x] = v[2] + (grey - v[2]) * t;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Channel clip bits of a demosaiced image: the OR of the mosaic's clip flags over each pixel's 3×3
|
||||
/// neighbourhood (the samples its interpolation draws on).</summary>
|
||||
public static byte[] Dilate(byte[] mask, int width, int height)
|
||||
{
|
||||
var horizontal = new byte[mask.Length];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var o = y * width;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var v = mask[o + x];
|
||||
if (x > 0) v |= mask[o + x - 1];
|
||||
if (x < width - 1) v |= mask[o + x + 1];
|
||||
horizontal[o + x] = v;
|
||||
}
|
||||
}
|
||||
var result = new byte[mask.Length];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var o = y * width;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var v = horizontal[o + x];
|
||||
if (y > 0) v |= horizontal[o - width + x];
|
||||
if (y < height - 1) v |= horizontal[o + width + x];
|
||||
result[o + x] = v;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Clip bits of a binned image: the OR over each <paramref name="size"/>×<paramref name="size"/> block.</summary>
|
||||
public static byte[] Bin(byte[] mask, int width, int size, int outWidth, int outHeight)
|
||||
{
|
||||
var result = new byte[outWidth * outHeight];
|
||||
for (var by = 0; by < outHeight; by++)
|
||||
{
|
||||
for (var bx = 0; bx < outWidth; bx++)
|
||||
{
|
||||
byte v = 0;
|
||||
for (var dy = 0; dy < size; dy++)
|
||||
{
|
||||
for (var dx = 0; dx < size; dx++) v |= mask[(by * size + dy) * width + bx * size + dx];
|
||||
}
|
||||
result[by * outWidth + bx] = v;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
using Titano.Core.Codecs.Dng;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>Shared pieces of the native (non-DNG) RAW readers: camera naming, frame construction, MakerNote access and
|
||||
/// bounded payload reads.</summary>
|
||||
internal static class NativeRaw
|
||||
{
|
||||
/// <summary>Largest raw raster accepted (256 megapixels).</summary>
|
||||
public const long MaxPixels = 1L << 28;
|
||||
|
||||
/// <summary>"Brand Model" as keyed in <see cref="CameraMatrices"/>: "NIKON CORPORATION" + "NIKON D850" → "Nikon D850".</summary>
|
||||
public static string? CameraName(string? make, string? model)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(model)) return null;
|
||||
var m = make?.Trim() ?? string.Empty;
|
||||
string brand;
|
||||
if (m.StartsWith("Canon", StringComparison.OrdinalIgnoreCase)) brand = "Canon";
|
||||
else if (m.StartsWith("NIKON", StringComparison.OrdinalIgnoreCase)) brand = "Nikon";
|
||||
else if (m.StartsWith("SONY", StringComparison.OrdinalIgnoreCase)) brand = "Sony";
|
||||
else if (m.StartsWith("PENTAX", StringComparison.OrdinalIgnoreCase) || m.StartsWith("RICOH", StringComparison.OrdinalIgnoreCase) || m.StartsWith("ASAHI", StringComparison.OrdinalIgnoreCase)) brand = "Pentax";
|
||||
else if (m.StartsWith("FUJIFILM", StringComparison.OrdinalIgnoreCase)) brand = "Fujifilm";
|
||||
else brand = m.Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty;
|
||||
var words = model.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
|
||||
if (words.Count > 1 && (words[0].Equals(brand, StringComparison.OrdinalIgnoreCase) || words[0].Equals("PENTAX", StringComparison.OrdinalIgnoreCase)))
|
||||
words.RemoveAt(0);
|
||||
return words.Count == 0 ? null : $"{brand} {string.Join(' ', words)}";
|
||||
}
|
||||
|
||||
/// <summary>Builds the frame of a native RAW developed with a tabulated D65 matrix.</summary>
|
||||
/// <param name="multipliers">As-shot white-balance multipliers (R, G, B); null falls back to daylight.</param>
|
||||
/// <exception cref="InvalidDataException">The body has no colour matrix (the caller falls back to the preview).</exception>
|
||||
public static RawFrame Frame(string decoder, int width, int height, CfaPattern cfa, RawRect active, RawBlackLevel black, double white,
|
||||
Vector3D? multipliers, int orientation, string? make, string? model, RawLoader loader, IEnumerable<string> warnings)
|
||||
{
|
||||
var name = CameraName(make, model);
|
||||
var matrix = CameraMatrices.Find(name) ?? throw new InvalidDataException($"RAW: no colour matrix for {name ?? "unknown camera"}");
|
||||
if (active.IsEmpty || active.Left < 0 || active.Top < 0 || active.Right > width || active.Bottom > height)
|
||||
throw new InvalidDataException("RAW: sensor area outside the raster");
|
||||
Vector3D? neutral = multipliers is { } m && m.X > 0 && m.Y > 0 && m.Z > 0 && double.IsFinite(m.X + m.Y + m.Z)
|
||||
? new Vector3D(1 / m.X, 1 / m.Y, 1 / m.Z)
|
||||
: null;
|
||||
var frame = new RawFrame
|
||||
{
|
||||
Decoder = decoder,
|
||||
Width = width,
|
||||
Height = height,
|
||||
Cfa = cfa,
|
||||
ActiveArea = active,
|
||||
Black = black,
|
||||
White = [white],
|
||||
DetectSaturation = true,
|
||||
Color = new DngColorProfile
|
||||
{
|
||||
ColorMatrix1 = matrix,
|
||||
CalibrationIlluminant1 = 21,
|
||||
AsShotNeutral = neutral,
|
||||
AsShotWhite = neutral is null ? Chromaticity.D65 : null,
|
||||
},
|
||||
Orientation = orientation is >= 1 and <= 8 ? orientation : 1,
|
||||
Make = make,
|
||||
Model = model,
|
||||
Loader = loader,
|
||||
};
|
||||
frame.Warnings.AddRange(warnings);
|
||||
if (neutral is null) frame.Warnings.Add("RAW: as-shot white balance unavailable; daylight assumed");
|
||||
return frame;
|
||||
}
|
||||
|
||||
/// <summary>Validated raster size.</summary>
|
||||
public static (int Width, int Height) Size(long width, long height)
|
||||
{
|
||||
if (width <= 0 || height <= 0 || width * height > MaxPixels) throw new InvalidDataException($"RAW: unsupported raster size {width}x{height}");
|
||||
return ((int)width, (int)height);
|
||||
}
|
||||
|
||||
/// <summary>Rejects entropy-coded payloads too short to hold one bit per sample, before the raster is allocated (a
|
||||
/// corrupted size must not trigger a huge allocation).</summary>
|
||||
public static void RequireBits(long payloadBytes, long samples)
|
||||
{
|
||||
if (payloadBytes * 8 < samples) throw new InvalidDataException("RAW: compressed data too short for the raster");
|
||||
}
|
||||
|
||||
/// <summary>Uniform black level for every CFA cell.</summary>
|
||||
public static RawBlackLevel Black(double value) => new(1, 1, [(float)value], null, null);
|
||||
|
||||
/// <summary>Black level of a 2×2 CFA from values in R, G1, G2, B order, re-anchored at the active area.</summary>
|
||||
public static RawBlackLevel Black2x2(CfaPattern cfa, ReadOnlySpan<double> rggb)
|
||||
{
|
||||
var values = new float[4];
|
||||
for (var y = 0; y < 2; y++)
|
||||
{
|
||||
for (var x = 0; x < 2; x++)
|
||||
{
|
||||
var c = cfa.ColorAt(x, y);
|
||||
// The second green of a 2×2 cell is the one sharing a row with blue.
|
||||
var index = c == 0 ? 0 : c == 2 ? 3 : cfa.ColorAt(x ^ 1, y) == 0 ? 1 : 2;
|
||||
values[y * 2 + x] = (float)rggb[index];
|
||||
}
|
||||
}
|
||||
return new RawBlackLevel(2, 2, values, null, null);
|
||||
}
|
||||
|
||||
/// <summary>Exif IFD of IFD0, or null.</summary>
|
||||
public static Ifd? ExifIfd(TiffReader r, Ifd ifd0) => r.GetUInt(ifd0, TiffTags.ExifIfd) is { } offset and > 0 ? r.ReadIfd(offset) : null;
|
||||
|
||||
/// <summary>Reads <paramref name="length"/> bytes at an absolute position (bounded by the stream).</summary>
|
||||
public static byte[] ReadPayload(Stream stream, long position, long length)
|
||||
{
|
||||
if (position < 0 || length <= 0 || length > int.MaxValue || position > stream.Length - length)
|
||||
throw new InvalidDataException("RAW: image data outside the file");
|
||||
var data = new byte[length];
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>CFA pattern from TIFF/EP CFARepeatPatternDim/CFAPattern tags (as written in NEF/ARW/PEF raw IFDs), or null.</summary>
|
||||
public static CfaPattern? TiffEpCfa(TiffReader r, Ifd ifd)
|
||||
{
|
||||
if (IfdValue.UInts(r, ifd, TiffTags.CfaPattern) is not { } pattern) return null;
|
||||
var dim = IfdValue.UInts(r, ifd, TiffTags.CfaRepeatPatternDim) ?? [2, 2];
|
||||
if (dim.Length < 2 || dim[0] is < 1 or > CfaPattern.MaxSize || dim[1] is < 1 or > CfaPattern.MaxSize || pattern.Length < dim[0] * dim[1]) return null;
|
||||
var colors = new byte[dim[0] * dim[1]];
|
||||
for (var i = 0; i < colors.Length; i++)
|
||||
{
|
||||
if (pattern[i] > 2) return null;
|
||||
colors[i] = (byte)pattern[i];
|
||||
}
|
||||
try
|
||||
{
|
||||
return new CfaPattern((int)dim[1], (int)dim[0], colors);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Uncompressed raw payloads: 16-bit words (either byte order, optionally holding the value shifted left by
|
||||
/// <paramref name="shift"/> bits) or MSB-first packed samples (TIFF convention).</summary>
|
||||
internal sealed class PlainRawLoader(long offset, long length, int width, int height, int bits, bool words, bool littleEndian, int shift = 0) : RawLoader
|
||||
{
|
||||
public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var rowBytes = words ? width * 2L : (width * (long)bits + 7) / 8;
|
||||
if (rowBytes * height > length) throw new InvalidDataException("RAW: image data truncated");
|
||||
var data = NativeRaw.ReadPayload(stream, offset, rowBytes * height);
|
||||
var samples = new ushort[width * height];
|
||||
var mask = (1 << bits) - 1;
|
||||
Parallel.For(0, height, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var row = data.AsSpan((int)(y * rowBytes), (int)rowBytes);
|
||||
var dst = samples.AsSpan(y * width, width);
|
||||
if (words)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
dst[x] = (ushort)((littleEndian ? row[2 * x] | row[2 * x + 1] << 8 : row[2 * x] << 8 | row[2 * x + 1]) >> shift & mask);
|
||||
return;
|
||||
}
|
||||
long bit = 0;
|
||||
for (var x = 0; x < width; x++, bit += bits)
|
||||
{
|
||||
var b = (int)(bit >> 3);
|
||||
// Up to 16 bits spanning at most three bytes.
|
||||
var window = row[b] << 16 | (b + 1 < row.Length ? row[b + 1] << 8 : 0) | (b + 2 < row.Length ? row[b + 2] : 0);
|
||||
dst[x] = (ushort)(window >> (24 - (int)(bit & 7) - bits) & mask);
|
||||
}
|
||||
});
|
||||
return new RawSamples(width, height, 1, samples, null);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>MSB-first bit reader without byte stuffing (Nikon and Pentax Huffman streams). Reading past the end yields
|
||||
/// zero bits and sets <see cref="Overrun"/>.</summary>
|
||||
internal ref struct MsbBitReader(ReadOnlySpan<byte> data)
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _data = data;
|
||||
private int _pos;
|
||||
private ulong _buffer;
|
||||
private int _bits;
|
||||
|
||||
public readonly bool Overrun => _pos > _data.Length + 8;
|
||||
|
||||
/// <summary>Next <paramref name="n"/> bits (n ≤ 32) without consuming them.</summary>
|
||||
public uint Peek(int n)
|
||||
{
|
||||
if (n == 0) return 0;
|
||||
while (_bits < n)
|
||||
{
|
||||
_buffer = _buffer << 8 | (_pos < _data.Length ? _data[_pos] : 0u);
|
||||
_pos++;
|
||||
_bits += 8;
|
||||
}
|
||||
return (uint)(_buffer >> (_bits - n)) & (uint)((1UL << n) - 1);
|
||||
}
|
||||
|
||||
public void Skip(int n) => _bits -= n;
|
||||
|
||||
public uint Read(int n)
|
||||
{
|
||||
var v = Peek(n);
|
||||
_bits -= n;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Huffman lookup in dcraw's <c>make_decoder</c> layout: code-length counts for lengths 1–16 followed by symbols,
|
||||
/// codes assigned canonically; each table entry is (length << 8 | symbol) indexed by the next <see cref="Bits"/> bits.</summary>
|
||||
internal sealed class HuffmanTable
|
||||
{
|
||||
private readonly ushort[] _lut;
|
||||
|
||||
public HuffmanTable(ReadOnlySpan<byte> countsAndSymbols)
|
||||
{
|
||||
var bits = 16;
|
||||
while (bits > 0 && countsAndSymbols[bits - 1] == 0) bits--;
|
||||
if (bits == 0) throw new InvalidDataException("RAW: empty Huffman table");
|
||||
Bits = bits;
|
||||
_lut = new ushort[1 << bits];
|
||||
var h = 0;
|
||||
var symbol = 16;
|
||||
for (var len = 1; len <= bits; len++)
|
||||
{
|
||||
for (var i = 0; i < countsAndSymbols[len - 1]; i++, symbol++)
|
||||
{
|
||||
var value = symbol < countsAndSymbols.Length ? countsAndSymbols[symbol] : (byte)0;
|
||||
for (var j = 0; j < 1 << (bits - len) && h < _lut.Length; j++) _lut[h++] = (ushort)(len << 8 | value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wraps a prebuilt lookup (Pentax tables).</summary>
|
||||
public HuffmanTable(ushort[] lut, int bits)
|
||||
{
|
||||
_lut = lut;
|
||||
Bits = bits;
|
||||
}
|
||||
|
||||
public int Bits { get; }
|
||||
|
||||
/// <summary>Decodes one symbol.</summary>
|
||||
public int Decode(ref MsbBitReader reader)
|
||||
{
|
||||
var entry = _lut[reader.Peek(Bits)];
|
||||
reader.Skip(entry >> 8);
|
||||
return entry & 0xFF;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Nikon NEF: the CFA SubIFD is uncompressed (16-bit words or MSB-packed samples) or Nikon-compressed (Compression
|
||||
/// 34713): lossy type 1, lossless and lossy type 2 including the "after split" variant, decoded as dcraw's
|
||||
/// <c>nikon_load_raw</c> does from the MakerNote decode info (0x0096: version, vertical predictors, tone curve, split row)
|
||||
/// with Nikon's six Huffman trees and two-column horizontal prediction. White balance comes from MakerNote 0x000C, black
|
||||
/// from 0x003D. Packed 12-bit "uncompressed" variants, YUV NEFs and the high-efficiency (TicoRAW) codec are not supported
|
||||
/// and fall back to the preview.
|
||||
/// </summary>
|
||||
internal static class NefReader
|
||||
{
|
||||
private const ushort WbLevelsTag = 0x000C;
|
||||
private const ushort BlackLevelTag = 0x003D;
|
||||
private const ushort DecodeInfoTag = 0x0096;
|
||||
private const uint CompressionNikon = 34713;
|
||||
|
||||
/// <summary>Nikon Huffman trees (dcraw <c>nikon_tree</c>): 16 code-length counts, then the symbols (len | shift << 4).</summary>
|
||||
internal static readonly byte[][] Trees =
|
||||
[
|
||||
[0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12, 0, 0, 0],
|
||||
[0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12, 0, 0],
|
||||
[0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12, 0, 0, 0],
|
||||
[0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14, 0],
|
||||
[0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14, 0],
|
||||
[0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14, 0],
|
||||
];
|
||||
|
||||
public static RawFrame Read(Stream stream)
|
||||
{
|
||||
var r = TiffReader.Open(stream) ?? throw new InvalidDataException("NEF: missing TIFF header");
|
||||
var chain = r.ReadChain();
|
||||
if (chain.Count == 0) throw new InvalidDataException("NEF: no image directory");
|
||||
var ifd0 = chain[0];
|
||||
var raw = FindCfa(r, ifd0) ?? throw new InvalidDataException("NEF: CFA image missing");
|
||||
var (width, height) = NativeRaw.Size(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, r.GetUInt(raw, TiffTags.ImageLength) ?? 0);
|
||||
var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 0);
|
||||
if (bits is not (12 or 14)) throw new InvalidDataException($"NEF: {bits}-bit data is not supported");
|
||||
var (offset, length) = Strip(r, raw);
|
||||
var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1;
|
||||
var note = MakerNote(stream, r, ifd0);
|
||||
var warnings = new List<string>();
|
||||
var cfa = NativeRaw.TiffEpCfa(r, raw);
|
||||
if (cfa is null)
|
||||
{
|
||||
cfa = CfaPattern.Bayer("RGGB");
|
||||
warnings.Add("NEF: CFA pattern missing; RGGB assumed");
|
||||
}
|
||||
if (!cfa.IsBayer) throw new InvalidDataException("NEF: only Bayer sensors are supported");
|
||||
|
||||
RawLoader loader;
|
||||
double white = (1 << bits) - 1;
|
||||
if (compression == CompressionNikon && length != (long)width * height * 2)
|
||||
{
|
||||
if (note is not { } mn || !mn.Ifd.Entries.TryGetValue(DecodeInfoTag, out var meta) || mn.Reader.ReadBytes(meta) is not { } info)
|
||||
throw new InvalidDataException("NEF: compressed data without decode information");
|
||||
NativeRaw.RequireBits(length, (long)width * height);
|
||||
var decode = DecodeInfo.Parse(info, mn.Reader.LittleEndian, bits);
|
||||
white = decode.White;
|
||||
loader = new NikonHuffmanLoader(offset, length, width, height, decode);
|
||||
}
|
||||
else if (compression == CompressionNikon)
|
||||
{
|
||||
// Unpacked data under the Nikon compression tag: big-endian words holding the value shifted left by 4 (LibRaw).
|
||||
loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: false, shift: 4);
|
||||
}
|
||||
else if (compression == 1 && length >= (long)width * height * 2)
|
||||
{
|
||||
loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: r.LittleEndian);
|
||||
}
|
||||
else if (compression == 1 && length >= ((long)width * bits + 7) / 8 * height)
|
||||
{
|
||||
loader = new PlainRawLoader(offset, length, width, height, bits, words: false, littleEndian: false);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidDataException($"NEF: compression {compression} with {length} bytes is not supported");
|
||||
}
|
||||
|
||||
var black = NativeRaw.Black(0);
|
||||
if (note is { } n && IfdValue.UInts(n.Reader, n.Ifd, BlackLevelTag) is { Length: 4 } b)
|
||||
{
|
||||
// Stored on a 14-bit scale whatever the bit depth.
|
||||
black = NativeRaw.Black2x2(cfa, [b[0] >> (14 - bits), b[1] >> (14 - bits), b[2] >> (14 - bits), b[3] >> (14 - bits)]);
|
||||
}
|
||||
Vector3D? multipliers = note is { } w && IfdValue.Doubles(w.Reader, w.Ifd, WbLevelsTag, 2) is [var red, var blue, ..] ? new Vector3D(red, 1, blue) : null;
|
||||
return NativeRaw.Frame("managed-nef", width, height, cfa, new RawRect(0, 0, width, height), black, white, multipliers,
|
||||
(int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), r.GetString(ifd0, TiffTags.Make), r.GetString(ifd0, TiffTags.Model), loader, warnings);
|
||||
}
|
||||
|
||||
/// <summary>The full-resolution CFA IFD: IFD0 or one of its SubIFDs.</summary>
|
||||
internal static Ifd? FindCfa(TiffReader r, Ifd ifd0)
|
||||
{
|
||||
bool IsRaw(Ifd ifd) => (r.GetUInt(ifd, TiffTags.NewSubfileType) ?? 0) == 0 && r.GetUInt(ifd, TiffTags.PhotometricInterpretation) == 32803;
|
||||
if (IsRaw(ifd0)) return ifd0;
|
||||
if (!ifd0.Entries.TryGetValue(TiffTags.SubIfds, out var sub) || sub.Count > 16) return null;
|
||||
foreach (var offset in r.GetUInts(sub) ?? [])
|
||||
{
|
||||
if (r.ReadIfd(offset) is { } child && IsRaw(child)) return child;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Absolute position and length of the image data (several strips must be contiguous).</summary>
|
||||
internal static (long Offset, long Length) Strip(TiffReader r, Ifd ifd)
|
||||
{
|
||||
var offsets = IfdValue.UInts(r, ifd, TiffTags.StripOffsets) ?? r.GetUInts(ifd, TiffTags.StripOffsets);
|
||||
var counts = IfdValue.UInts(r, ifd, TiffTags.StripByteCounts) ?? r.GetUInts(ifd, TiffTags.StripByteCounts);
|
||||
if (offsets is not { Length: > 0 } || counts is null || counts.Length < offsets.Length) throw new InvalidDataException("RAW: strip offsets missing");
|
||||
long length = 0;
|
||||
for (var i = 0; i < offsets.Length; i++)
|
||||
{
|
||||
if (offsets[i] != offsets[0] + length) throw new InvalidDataException("RAW: non-contiguous strips are not supported");
|
||||
length += counts[i];
|
||||
}
|
||||
var offset = r.Base + offsets[0];
|
||||
if (offset + length > r.StreamLength) throw new InvalidDataException("RAW: image data outside the file");
|
||||
return (offset, length);
|
||||
}
|
||||
|
||||
/// <summary>Nikon type-3 MakerNote: "Nikon\0", version, then an embedded TIFF header 10 bytes in.</summary>
|
||||
private static (TiffReader Reader, Ifd Ifd)? MakerNote(Stream stream, TiffReader r, Ifd ifd0)
|
||||
{
|
||||
if (NativeRaw.ExifIfd(r, ifd0) is not { } exif || !exif.Entries.TryGetValue(TiffTags.MakerNote, out var e) || e.IsInline || e.Count < 18) return null;
|
||||
var start = e.ValuePosition(r.Base);
|
||||
var head = r.ReadRelative(start - r.Base, 6);
|
||||
if (head is null || !head.AsSpan().SequenceEqual("Nikon\0"u8)) return null;
|
||||
var reader = TiffReader.Open(stream, start + 10);
|
||||
return reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd ? (reader, ifd) : null;
|
||||
}
|
||||
|
||||
/// <summary>Parsed MakerNote 0x0096: Huffman tree, initial vertical predictors, tone curve and split row.</summary>
|
||||
internal sealed record DecodeInfo(int Tree, ushort[] Predictors, ushort[] Curve, int Split, double White)
|
||||
{
|
||||
public static DecodeInfo Parse(byte[] meta, bool littleEndian, int bits)
|
||||
{
|
||||
if (meta.Length < 12) throw new InvalidDataException("NEF: decode information truncated");
|
||||
var pos = 0;
|
||||
ushort U16()
|
||||
{
|
||||
if (pos + 2 > meta.Length) throw new InvalidDataException("NEF: decode information truncated");
|
||||
var v = littleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(meta.AsSpan(pos)) : BinaryPrimitives.ReadUInt16BigEndian(meta.AsSpan(pos));
|
||||
pos += 2;
|
||||
return v;
|
||||
}
|
||||
int ver0 = meta[0], ver1 = meta[1];
|
||||
pos = ver0 == 0x49 || ver1 == 0x58 ? 2 + 2110 : 2;
|
||||
var tree = (ver0 == 0x46 ? 2 : 0) + (bits == 14 ? 3 : 0);
|
||||
ushort[] predictors = [U16(), U16(), U16(), U16()];
|
||||
var max = 1 << bits & 0x7FFF;
|
||||
var curve = new ushort[0x10000];
|
||||
for (var i = 0; i < curve.Length; i++) curve[i] = (ushort)i;
|
||||
var size = U16();
|
||||
var step = size > 1 ? max / (size - 1) : 0;
|
||||
var split = 0;
|
||||
var top = max;
|
||||
if (ver0 == 0x44 && ver1 == 0x20 && step > 0)
|
||||
{
|
||||
// Lossy type 2: curve sampled every 'step' codes, linearly interpolated; split row at offset 562.
|
||||
for (var i = 0; i < size; i++) curve[int.Min(i * step, curve.Length - 1)] = U16();
|
||||
for (var i = 0; i < max; i++)
|
||||
{
|
||||
var k = i % step;
|
||||
var a = i - k;
|
||||
curve[i] = (ushort)((curve[a] * (step - k) + curve[int.Min(a + step, curve.Length - 1)] * k) / step);
|
||||
}
|
||||
if (meta.Length >= 564)
|
||||
{
|
||||
pos = 562;
|
||||
split = U16();
|
||||
}
|
||||
}
|
||||
else if (ver0 != 0x46 && size <= 0x4001)
|
||||
{
|
||||
// Lossy type 1: the curve is stored in full.
|
||||
for (var i = 0; i < size; i++) curve[i] = U16();
|
||||
top = size;
|
||||
}
|
||||
double white = 0;
|
||||
for (var i = 0; i < int.Max(top, 1); i++) white = double.Max(white, curve[i]);
|
||||
return new DecodeInfo(tree, predictors, curve, split, white);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>dcraw <c>nikon_load_raw</c>.</summary>
|
||||
private sealed class NikonHuffmanLoader(long offset, long length, int width, int height, DecodeInfo info) : RawLoader
|
||||
{
|
||||
public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var data = NativeRaw.ReadPayload(stream, offset, length);
|
||||
var samples = new ushort[width * height];
|
||||
var huff = new HuffmanTable(Trees[info.Tree]);
|
||||
var reader = new MsbBitReader(data);
|
||||
Span<ushort> vpred = stackalloc ushort[4];
|
||||
info.Predictors.CopyTo(vpred);
|
||||
Span<ushort> hpred = stackalloc ushort[2];
|
||||
var curve = info.Curve;
|
||||
for (var row = 0; row < height; row++)
|
||||
{
|
||||
if (info.Split > 0 && row == info.Split && info.Tree + 1 < Trees.Length) huff = new HuffmanTable(Trees[info.Tree + 1]);
|
||||
if ((row & 63) == 0) cancellationToken.ThrowIfCancellationRequested();
|
||||
var dst = samples.AsSpan(row * width, width);
|
||||
for (var col = 0; col < width; col++)
|
||||
{
|
||||
var symbol = huff.Decode(ref reader);
|
||||
int len = symbol & 15, shl = symbol >> 4;
|
||||
var diff = 0;
|
||||
if (len > 0)
|
||||
{
|
||||
diff = (int)(((reader.Read(int.Max(len - shl, 0)) << 1) + 1) << shl >> 1);
|
||||
if ((diff & 1 << (len - 1)) == 0) diff -= (1 << len) - (shl == 0 ? 1 : 0);
|
||||
}
|
||||
ushort predicted;
|
||||
if (col < 2)
|
||||
{
|
||||
ref var v = ref vpred[(row & 1) * 2 + col];
|
||||
v = (ushort)(v + diff);
|
||||
predicted = hpred[col] = v;
|
||||
}
|
||||
else
|
||||
{
|
||||
predicted = hpred[col & 1] = (ushort)(hpred[col & 1] + diff);
|
||||
}
|
||||
dst[col] = curve[int.Clamp((short)predicted, 0, 0x3FFF)];
|
||||
}
|
||||
if (reader.Overrun) throw new InvalidDataException($"NEF: compressed data ends at row {row}");
|
||||
}
|
||||
return new RawSamples(width, height, 1, samples, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Pentax PEF: the CFA image in IFD0 is uncompressed or Pentax-Huffman coded (Compression 65535): a code table from
|
||||
/// MakerNote 0x0220 (code values left-aligned in 12 bits and their lengths, dcraw <c>pentax_load_raw</c>), JPEG-style
|
||||
/// difference magnitudes, and two-column horizontal prediction seeded per row parity. Black (0x0200) and as-shot RGGB
|
||||
/// levels (0x0201) come from the "AOC" MakerNote, whose offsets are relative to the TIFF header.
|
||||
/// </summary>
|
||||
internal static class PefReader
|
||||
{
|
||||
private const uint CompressionPentax = 65535;
|
||||
private const ushort BlackPointTag = 0x0200;
|
||||
private const ushort WhiteBalanceTag = 0x0201;
|
||||
private const ushort HuffmanTag = 0x0220;
|
||||
|
||||
public static RawFrame Read(Stream stream)
|
||||
{
|
||||
var r = TiffReader.Open(stream) ?? throw new InvalidDataException("PEF: missing TIFF header");
|
||||
var chain = r.ReadChain();
|
||||
if (chain.Count == 0) throw new InvalidDataException("PEF: no image directory");
|
||||
var ifd0 = chain[0];
|
||||
var raw = NefReader.FindCfa(r, ifd0) ?? throw new InvalidDataException("PEF: CFA image missing");
|
||||
var (width, height) = NativeRaw.Size(r.GetUInt(raw, TiffTags.ImageWidth) ?? 0, r.GetUInt(raw, TiffTags.ImageLength) ?? 0);
|
||||
var bits = (int)(r.GetUInt(raw, TiffTags.BitsPerSample) ?? 0);
|
||||
if (bits is not (12 or 14)) throw new InvalidDataException($"PEF: {bits}-bit data is not supported");
|
||||
var compression = r.GetUInt(raw, TiffTags.Compression) ?? 1;
|
||||
var (offset, length) = NefReader.Strip(r, raw);
|
||||
var note = MakerNote(stream, r, ifd0);
|
||||
var warnings = new List<string>();
|
||||
var cfa = NativeRaw.TiffEpCfa(r, raw);
|
||||
if (cfa is null)
|
||||
{
|
||||
cfa = CfaPattern.Bayer("RGGB");
|
||||
warnings.Add("PEF: CFA pattern missing; RGGB assumed");
|
||||
}
|
||||
if (!cfa.IsBayer) throw new InvalidDataException("PEF: only Bayer sensors are supported");
|
||||
|
||||
RawLoader loader;
|
||||
if (compression == CompressionPentax)
|
||||
{
|
||||
if (note is not { } mn || !mn.Ifd.Entries.TryGetValue(HuffmanTag, out var e) || mn.Reader.ReadBytes(e) is not { } table)
|
||||
throw new InvalidDataException("PEF: Huffman table missing");
|
||||
NativeRaw.RequireBits(length, (long)width * height);
|
||||
loader = new PentaxLoader(offset, length, width, height, bits, Table(table, mn.Reader.LittleEndian));
|
||||
}
|
||||
else if (compression == 1 && length >= (long)width * height * 2)
|
||||
{
|
||||
loader = new PlainRawLoader(offset, length, width, height, bits, words: true, littleEndian: r.LittleEndian);
|
||||
}
|
||||
else if (compression == 1 && length >= ((long)width * bits + 7) / 8 * height)
|
||||
{
|
||||
loader = new PlainRawLoader(offset, length, width, height, bits, words: false, littleEndian: false);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidDataException($"PEF: compression {compression} is not supported");
|
||||
}
|
||||
|
||||
var black = note is { } n && IfdValue.UInts(n.Reader, n.Ifd, BlackPointTag) is { Length: 4 } b
|
||||
? NativeRaw.Black2x2(cfa, [b[0], b[1], b[2], b[3]])
|
||||
: NativeRaw.Black(0);
|
||||
Vector3D? multipliers = note is { } w && IfdValue.UInts(w.Reader, w.Ifd, WhiteBalanceTag) is { Length: 4 } wb && wb[1] + wb[2] > 0
|
||||
? new Vector3D(wb[0] * 2.0 / (wb[1] + wb[2]), 1, wb[3] * 2.0 / (wb[1] + wb[2]))
|
||||
: null;
|
||||
return NativeRaw.Frame("managed-pef", width, height, cfa, new RawRect(0, 0, width, height), black, (1 << bits) - 1, multipliers,
|
||||
(int)(r.GetUInt(ifd0, TiffTags.Orientation) ?? 1), r.GetString(ifd0, TiffTags.Make), r.GetString(ifd0, TiffTags.Model), loader, warnings);
|
||||
}
|
||||
|
||||
/// <summary>"AOC\0" + byte order ("MM"/"II", else the file's) + IFD; offsets relative to the file's TIFF header.</summary>
|
||||
private static (TiffReader Reader, Ifd Ifd)? MakerNote(Stream stream, TiffReader r, Ifd ifd0)
|
||||
{
|
||||
if (NativeRaw.ExifIfd(r, ifd0) is not { } exif || !exif.Entries.TryGetValue(TiffTags.MakerNote, out var e) || e.IsInline || e.Count < 8) return null;
|
||||
var start = e.ValuePosition(r.Base);
|
||||
var head = r.ReadRelative(start - r.Base, 6);
|
||||
if (head is null || !head.AsSpan(0, 4).SequenceEqual("AOC\0"u8)) return null;
|
||||
var littleEndian = head[4] == 'I' && head[5] == 'I' || !(head[4] == 'M' && head[5] == 'M') && r.LittleEndian;
|
||||
var reader = TiffReader.ForEmbedded(stream, r.Base, littleEndian);
|
||||
return reader.ReadIfd((uint)(start + 6 - r.Base)) is { } ifd ? (reader, ifd) : null;
|
||||
}
|
||||
|
||||
/// <summary>12-bit lookup from MakerNote 0x0220: a code count, 12 skipped bytes, left-aligned code values (16-bit) and
|
||||
/// code lengths (8-bit); every 12-bit prefix of a code maps to (length, difference magnitude).</summary>
|
||||
internal static HuffmanTable Table(byte[] table, bool littleEndian)
|
||||
{
|
||||
if (table.Length < 14) throw new InvalidDataException("PEF: Huffman table truncated");
|
||||
ushort U16(int at) => littleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(table.AsSpan(at)) : BinaryPrimitives.ReadUInt16BigEndian(table.AsSpan(at));
|
||||
var depth = (U16(0) + 12) & 15;
|
||||
if (table.Length < 14 + depth * 3) throw new InvalidDataException("PEF: Huffman table truncated");
|
||||
var lut = new ushort[4096];
|
||||
for (var c = 0; c < depth; c++)
|
||||
{
|
||||
int code = U16(14 + 2 * c), len = table[14 + 2 * depth + c];
|
||||
if (code > 4095 || len > 12) continue;
|
||||
var end = (code + (4096 >> len) - 1) & 4095;
|
||||
for (var i = code; i <= end; i++) lut[i] = (ushort)(len << 8 | c);
|
||||
}
|
||||
return new HuffmanTable(lut, 12);
|
||||
}
|
||||
|
||||
private sealed class PentaxLoader(long offset, long length, int width, int height, int bits, HuffmanTable huff) : RawLoader
|
||||
{
|
||||
public override RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken)
|
||||
{
|
||||
var data = NativeRaw.ReadPayload(stream, offset, length);
|
||||
var samples = new ushort[width * height];
|
||||
var reader = new MsbBitReader(data);
|
||||
Span<int> vpred = stackalloc int[4];
|
||||
Span<int> hpred = stackalloc int[2];
|
||||
var limit = (1 << bits) - 1;
|
||||
var outOfRange = false;
|
||||
for (var row = 0; row < height; row++)
|
||||
{
|
||||
if ((row & 63) == 0) cancellationToken.ThrowIfCancellationRequested();
|
||||
var dst = samples.AsSpan(row * width, width);
|
||||
for (var col = 0; col < width; col++)
|
||||
{
|
||||
var len = huff.Decode(ref reader);
|
||||
var diff = 0;
|
||||
if (len == 16)
|
||||
{
|
||||
diff = -32768;
|
||||
}
|
||||
else if (len > 0)
|
||||
{
|
||||
diff = (int)reader.Read(len);
|
||||
if ((diff & 1 << (len - 1)) == 0) diff -= (1 << len) - 1;
|
||||
}
|
||||
int value;
|
||||
if (col < 2) value = hpred[col] = vpred[(row & 1) * 2 + col] += diff;
|
||||
else value = hpred[col & 1] += diff;
|
||||
if ((uint)value > (uint)limit)
|
||||
{
|
||||
outOfRange = true;
|
||||
value = int.Clamp(value, 0, limit);
|
||||
}
|
||||
dst[col] = (ushort)value;
|
||||
}
|
||||
if (reader.Overrun) throw new InvalidDataException($"PEF: compressed data ends at row {row}");
|
||||
}
|
||||
var result = new RawSamples(width, height, 1, samples, null);
|
||||
if (outOfRange) result.Warnings.Add("PEF: predicted values outside the bit depth were clamped");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// Fujifilm RAF, uncompressed: the header's CFA offset (0x64) points to a big-endian TIFF block whose FujiIFD (0xF000)
|
||||
/// gives the raster size (0xF001/0xF002), bit depth (0xF003), the data offset relative to that block (0xF007), its length
|
||||
/// (0xF008) and black levels (0xF00A); the RAF directory supplies the crop (0x0110 top-left, 0x0111 size), the 6×6
|
||||
/// colour layout (0x0131, stored reversed, anchored at the raster origin; Bayer bodies describe their 2×2 pattern the same
|
||||
/// way) and the as-shot GRGB levels (0x2FF0). Samples are little-endian 16-bit words whatever the block's byte order, as
|
||||
/// LibRaw reads them. Compressed RAFs and
|
||||
/// SuperCCD (45°) layouts are not supported and fall back to the preview.
|
||||
/// </summary>
|
||||
internal static class RafReader
|
||||
{
|
||||
private const int HeaderLength = 0x6C;
|
||||
private const int MaxDirectoryBytes = 1 << 20;
|
||||
private const ushort FullSizeRecord = 0x0100, CropTopLeftRecord = 0x0110, CropSizeRecord = 0x0111;
|
||||
private const ushort LayoutRecord = 0x0130, CfaRecord = 0x0131, WhiteBalanceRecord = 0x2FF0;
|
||||
private const ushort FujiIfdTag = 0xF000, WidthTag = 0xF001, HeightTag = 0xF002, BitsTag = 0xF003;
|
||||
private const ushort OffsetTag = 0xF007, LengthTag = 0xF008, BlackTag = 0xF00A;
|
||||
|
||||
public static RawFrame Read(Stream stream)
|
||||
{
|
||||
var header = new byte[HeaderLength];
|
||||
stream.Position = 0;
|
||||
if (stream.ReadAtLeast(header, HeaderLength, throwOnEndOfStream: false) < HeaderLength || !header.AsSpan().StartsWith("FUJIFILMCCD-RAW "u8))
|
||||
throw new InvalidDataException("RAF: header missing");
|
||||
var records = Directory(stream, BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x5C)), BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x60)));
|
||||
if (records.TryGetValue(LayoutRecord, out var layout) && layout.Length >= 2 && (layout[1] & 8) == 0)
|
||||
throw new InvalidDataException("RAF: SuperCCD layouts are not supported");
|
||||
if (!records.TryGetValue(CfaRecord, out var pattern) || pattern.Length < 36) throw new InvalidDataException("RAF: colour layout record missing");
|
||||
|
||||
var blockBase = BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x64));
|
||||
var r = TiffReader.Open(stream, blockBase) ?? throw new InvalidDataException("RAF: raw block is not TIFF-structured");
|
||||
var fuji = r.ReadIfd(r.FirstIfdOffset) is { } top && r.GetUInt(top, FujiIfdTag) is { } sub ? r.ReadIfd(sub) : null;
|
||||
if (fuji is null) throw new InvalidDataException("RAF: FujiIFD missing");
|
||||
var (width, height) = NativeRaw.Size(r.GetUInt(fuji, WidthTag) ?? 0, r.GetUInt(fuji, HeightTag) ?? 0);
|
||||
var bits = (int)(r.GetUInt(fuji, BitsTag) ?? 0);
|
||||
if (bits is < 12 or > 16) throw new InvalidDataException($"RAF: {bits}-bit data is not supported");
|
||||
var offset = blockBase + (long)(r.GetUInt(fuji, OffsetTag) ?? 0);
|
||||
var length = (long)(r.GetUInt(fuji, LengthTag) ?? 0);
|
||||
if (length < (long)width * height * 2) throw new InvalidDataException("RAF: compressed RAF is not supported");
|
||||
|
||||
var warnings = new List<string>();
|
||||
var active = new RawRect(0, 0, width, height);
|
||||
if (records.TryGetValue(CropTopLeftRecord, out var tl) && tl.Length >= 4 && records.TryGetValue(CropSizeRecord, out var size) && size.Length >= 4)
|
||||
{
|
||||
int top0 = BinaryPrimitives.ReadUInt16BigEndian(tl), left0 = BinaryPrimitives.ReadUInt16BigEndian(tl.AsSpan(2));
|
||||
int h = BinaryPrimitives.ReadUInt16BigEndian(size), w = BinaryPrimitives.ReadUInt16BigEndian(size.AsSpan(2));
|
||||
var crop = new RawRect(left0, top0, left0 + w, top0 + h).Intersect(active);
|
||||
if (!crop.IsEmpty) active = crop;
|
||||
}
|
||||
var colors = new byte[36];
|
||||
for (var i = 0; i < 36; i++) colors[35 - i] = (byte)(pattern[i] & 3);
|
||||
var cfa = new CfaPattern(6, 6, colors).Shift(active.Left, active.Top);
|
||||
|
||||
var black = NativeRaw.Black(1024 >> (14 - int.Min(bits, 14)));
|
||||
if (fuji.Entries.TryGetValue(BlackTag, out var be) && be.Count is > 0 and <= 64 && r.GetUInts(be) is { } levels)
|
||||
{
|
||||
if (levels.Length >= 36)
|
||||
{
|
||||
// A 6×6 grid anchored at the raster origin, re-anchored at the active area.
|
||||
var grid = new float[36];
|
||||
for (var y = 0; y < 6; y++)
|
||||
{
|
||||
for (var x = 0; x < 6; x++) grid[y * 6 + x] = levels[(y + active.Top) % 6 * 6 + (x + active.Left) % 6];
|
||||
}
|
||||
black = new RawBlackLevel(6, 6, grid, null, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
black = NativeRaw.Black(levels.Average(v => (double)v));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
warnings.Add("RAF: black level missing; default used");
|
||||
}
|
||||
|
||||
Vector3D? multipliers = null;
|
||||
if (records.TryGetValue(WhiteBalanceRecord, out var wb) && wb.Length >= 8)
|
||||
{
|
||||
double g = BinaryPrimitives.ReadUInt16BigEndian(wb), red = BinaryPrimitives.ReadUInt16BigEndian(wb.AsSpan(2)), blue = BinaryPrimitives.ReadUInt16BigEndian(wb.AsSpan(6));
|
||||
if (g > 0) multipliers = new Vector3D(red / g, 1, blue / g);
|
||||
}
|
||||
var metadata = MetadataReader.Read(stream, "frame.raf");
|
||||
var loader = new PlainRawLoader(offset, length, width, height, 16, words: true, littleEndian: true);
|
||||
return NativeRaw.Frame("managed-raf", width, height, cfa, active, black, (1 << bits) - 1, multipliers, metadata.Orientation,
|
||||
metadata.Make ?? "FUJIFILM", metadata.Model, loader, warnings);
|
||||
}
|
||||
|
||||
/// <summary>RAF directory: u32 record count, then (u16 tag, u16 size, data) records, big-endian.</summary>
|
||||
private static Dictionary<ushort, byte[]> Directory(Stream stream, uint offset, uint length)
|
||||
{
|
||||
var result = new Dictionary<ushort, byte[]>();
|
||||
if (offset < HeaderLength || length < 4 || length > MaxDirectoryBytes || offset > stream.Length - length) throw new InvalidDataException("RAF: directory missing");
|
||||
var data = NativeRaw.ReadPayload(stream, offset, length);
|
||||
var count = BinaryPrimitives.ReadUInt32BigEndian(data);
|
||||
var pos = 4;
|
||||
for (var i = 0; i < count && pos + 4 <= data.Length; i++)
|
||||
{
|
||||
var tag = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(pos));
|
||||
var size = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(pos + 2));
|
||||
pos += 4;
|
||||
if (pos + size > data.Length) break;
|
||||
result.TryAdd(tag, data.AsSpan(pos, size).ToArray());
|
||||
pos += size;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using Titano.Core.Codecs.Dng;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Metadata;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>Demosaic quality: AHD for renders and proxies, bilinear for thumbnails and analysis.</summary>
|
||||
public enum DemosaicQuality
|
||||
{
|
||||
/// <summary>Bilinear (Bayer) — fast, slightly soft, some colour fringing on fine detail.</summary>
|
||||
Draft,
|
||||
|
||||
/// <summary>Adaptive homogeneity-directed (Bayer); X-Trans always uses the neighbourhood interpolation.</summary>
|
||||
Best,
|
||||
}
|
||||
|
||||
/// <summary>Options for <see cref="RawDecoder"/>.</summary>
|
||||
public sealed record RawDecodeOptions
|
||||
{
|
||||
public static RawDecodeOptions Default { get; } = new();
|
||||
|
||||
public DemosaicQuality Quality { get; init; } = DemosaicQuality.Best;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>Worker limit (-1 = all cores).</summary>
|
||||
public int MaxDegreeOfParallelism { get; init; } = -1;
|
||||
}
|
||||
|
||||
/// <summary>What a RAW container holds, read without decoding its pixels.</summary>
|
||||
/// <param name="Format">Container format.</param>
|
||||
/// <param name="Decoder">Decoder that would develop it ("managed-dng", "managed-cr2"…).</param>
|
||||
/// <param name="Width">Developed width at full size, after crop and orientation.</param>
|
||||
/// <param name="Height">Developed height at full size, after crop and orientation.</param>
|
||||
/// <param name="Layout">CFA pattern ("RGGB", "6x6:…") or "linear".</param>
|
||||
/// <param name="Orientation">Exif orientation applied when requested.</param>
|
||||
public sealed record RawImageInfo(ImageFileFormat Format, string Decoder, string? Make, string? Model, int Width, int Height, string Layout, int Orientation);
|
||||
|
||||
/// <summary>Result of <see cref="RawDecoder.Probe"/>: native support plus the reason when unsupported.</summary>
|
||||
public sealed record RawProbe(RawImageInfo? Info, string? Reason, IReadOnlyList<string> Warnings)
|
||||
{
|
||||
public bool IsSupported => Info is not null;
|
||||
}
|
||||
|
||||
/// <summary>A developed RAW: linear Rec.709 (D65) RGB, BaselineExposure applied. Dispose to return the pixels to the pool.</summary>
|
||||
public sealed class RawDecodeResult(ImageBuffer image, RawImageInfo info, IReadOnlyList<string> warnings) : IDisposable
|
||||
{
|
||||
public ImageBuffer Image { get; } = image;
|
||||
public RawImageInfo Info { get; } = info;
|
||||
public IReadOnlyList<string> Warnings { get; } = warnings;
|
||||
|
||||
public void Dispose() => Image.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Managed RAW decoding (BRIEF §8.2): DNG (CFA and LinearRaw) through <see cref="DngReader"/>, and the native containers
|
||||
/// Canon CR2, Nikon NEF, Sony ARW, Pentax PEF and Fujifilm RAF, all developed by the same pipeline. Bodies or encodings
|
||||
/// without support are reported by <see cref="Probe"/> so callers can fall back to the embedded preview.
|
||||
/// </summary>
|
||||
public static class RawDecoder
|
||||
{
|
||||
/// <summary>Formats with a managed decoder (individual files may still be unsupported).</summary>
|
||||
public static IReadOnlyList<ImageFileFormat> Formats { get; } =
|
||||
[ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Arw, ImageFileFormat.Pef, ImageFileFormat.Raf];
|
||||
|
||||
/// <summary>Parses the container and decides whether it can be developed natively; never reads the pixel payload.</summary>
|
||||
public static RawProbe Probe(Stream stream, string? fileName = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var warnings = new List<string>();
|
||||
try
|
||||
{
|
||||
var (format, frame) = Open(stream, fileName);
|
||||
warnings.AddRange(frame.Warnings);
|
||||
return new RawProbe(Describe(format, frame, RawDecodeOptions.Default), null, warnings);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
return new RawProbe(null, ex.Message, warnings);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
return new RawProbe(null, "I/O error: " + ex.Message, warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Develops the RAW in <paramref name="stream"/> (readable and seekable).</summary>
|
||||
/// <param name="fileName">Breaks signature ties between formats sharing a container (see <see cref="ImageSignature"/>).</param>
|
||||
/// <exception cref="InvalidDataException">Malformed file, or a body/encoding without native support.</exception>
|
||||
public static RawDecodeResult Decode(Stream stream, string? fileName = null, RawDecodeOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var o = options ?? RawDecodeOptions.Default;
|
||||
var (format, frame) = Open(stream, fileName);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var samples = frame.Loader.Load(stream, o.MaxDegreeOfParallelism, cancellationToken);
|
||||
var warnings = new List<string>(frame.Warnings);
|
||||
warnings.AddRange(samples.Warnings);
|
||||
var image = RawDeveloper.Develop(frame, samples, o, warnings, cancellationToken);
|
||||
return new RawDecodeResult(image, Describe(format, frame, o), warnings);
|
||||
}
|
||||
|
||||
private static (ImageFileFormat Format, RawFrame Frame) Open(Stream stream, string? fileName)
|
||||
{
|
||||
if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream));
|
||||
var format = ImageSignature.Detect(stream, fileName);
|
||||
var frame = format switch
|
||||
{
|
||||
ImageFileFormat.Dng => DngReader.Read(stream),
|
||||
ImageFileFormat.Cr2 => Cr2Reader.Read(stream),
|
||||
ImageFileFormat.Nef => NefReader.Read(stream),
|
||||
ImageFileFormat.Arw => ArwReader.Read(stream),
|
||||
ImageFileFormat.Pef => PefReader.Read(stream),
|
||||
ImageFileFormat.Raf => RafReader.Read(stream),
|
||||
_ => throw new InvalidDataException($"RAW: no managed decoder for {format}"),
|
||||
};
|
||||
return (format, frame);
|
||||
}
|
||||
|
||||
private static RawImageInfo Describe(ImageFileFormat format, RawFrame frame, RawDecodeOptions options)
|
||||
{
|
||||
var (w, h) = frame.OutputSize;
|
||||
if (options.ApplyOrientation && frame.Orientation is >= 5 and <= 8) (w, h) = (h, w);
|
||||
return new RawImageInfo(format, frame.Decoder, frame.Make, frame.Model, w, h, frame.Cfa?.ToString() ?? "linear", frame.Orientation);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
using Titano.Core.Codecs.Dng;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>
|
||||
/// The raw development pipeline shared by DNG and the native RAW readers (BRIEF §8.2; DNG 1.6 chapter 5 "Mapping Raw
|
||||
/// Values to Linear Reference Values" and chapter 6): OpcodeList1 on stored values → linearisation table, black level
|
||||
/// (repeat pattern + row/column deltas) and white scaling to 0..1 over the active area, with a clip map of saturated
|
||||
/// samples → OpcodeList2 → white-balance multipliers → demosaic (AHD, bilinear, neighbourhood or binning) → highlight
|
||||
/// reconstruction → OpcodeList3 → default crop → camera → linear Rec.709 matrix with BaselineExposure → default scale →
|
||||
/// orientation.
|
||||
/// </summary>
|
||||
internal static class RawDeveloper
|
||||
{
|
||||
/// <summary>Normalised level at or above which a sample counts as clipped.</summary>
|
||||
private const float ClipThreshold = 0.999f;
|
||||
|
||||
/// <summary>A pile-up of samples at the data maximum counts as sensor saturation only above this fraction of the white level.</summary>
|
||||
private const double SaturationFloor = 0.75;
|
||||
|
||||
/// <summary>Samples that must sit at the data maximum for it to count as saturation rather than the brightest detail.</summary>
|
||||
private const int SaturationPileUp = 16;
|
||||
|
||||
public static ImageBuffer Develop(RawFrame frame, RawSamples samples, RawDecodeOptions options, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
if (samples.Width != frame.Width || samples.Height != frame.Height || samples.SamplesPerPixel != frame.SamplesPerPixel)
|
||||
throw new InvalidDataException("RAW: decoded payload does not match the declared raster");
|
||||
var dop = options.MaxDegreeOfParallelism;
|
||||
var spp = frame.SamplesPerPixel;
|
||||
var active = frame.ActiveArea;
|
||||
var black = samples.MeasuredBlack ?? frame.Black;
|
||||
var white = frame.White;
|
||||
var saturation = frame.DetectSaturation && frame.Linearization is null && spp == 1 ? Saturation(samples, active, black, white[0]) : 1f;
|
||||
|
||||
var list1 = DngOpcodes.Parse(frame.OpcodeList1, 1, warnings);
|
||||
ImageBuffer? stage1 = null;
|
||||
if (list1.Count > 0)
|
||||
{
|
||||
stage1 = ToStage1(samples, dop, cancellationToken);
|
||||
var image = new OpcodeImage(stage1, 0, 0, 1, spp == 1 ? frame.Cfa?.Shift(-active.Left, -active.Top) : null);
|
||||
DngOpcodes.Apply(list1, image, warnings, cancellationToken);
|
||||
stage1 = image.Pixels;
|
||||
if (stage1.Width != samples.Width || stage1.Height != samples.Height)
|
||||
{
|
||||
stage1.Dispose();
|
||||
throw new InvalidDataException("RAW: OpcodeList1 changed the raster size");
|
||||
}
|
||||
}
|
||||
|
||||
ImageBuffer linear;
|
||||
byte[]? clip;
|
||||
try
|
||||
{
|
||||
(linear, clip) = Linearize(frame, samples, stage1, black, white, saturation * ClipThreshold, dop, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage1?.Dispose();
|
||||
}
|
||||
|
||||
var stage = new OpcodeImage(linear, 0, 0, 1, frame.Cfa) { ClipMask = clip };
|
||||
try
|
||||
{
|
||||
DngOpcodes.Apply(DngOpcodes.Parse(frame.OpcodeList2, 2, warnings), stage, warnings, cancellationToken);
|
||||
return frame.Cfa is null && spp == 1
|
||||
? DevelopMonochrome(frame, stage, options, warnings, cancellationToken)
|
||||
: DevelopColour(frame, stage, saturation, options, warnings, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Pixels.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static ImageBuffer DevelopColour(RawFrame frame, OpcodeImage stage, float saturation, RawDecodeOptions options, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var dop = options.MaxDegreeOfParallelism;
|
||||
var colour = frame.Color.Solve(warnings);
|
||||
var n = colour.CameraNeutral;
|
||||
float[] wb = [(float)(1 / n.X), (float)(1 / n.Y), (float)(1 / n.Z)];
|
||||
|
||||
ImageBuffer rgb;
|
||||
byte[]? bits = null;
|
||||
var step = 1;
|
||||
if (stage.Cfa is { } cfa)
|
||||
{
|
||||
ScaleMosaic(stage.Pixels, cfa, wb, dop, cancellationToken);
|
||||
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);
|
||||
step = bin;
|
||||
if (stage.ClipMask is { } mask) bits = HighlightReconstruction.Bin(mask, stage.Width, bin, rgb.Width, rgb.Height);
|
||||
}
|
||||
else
|
||||
{
|
||||
rgb = !cfa.IsBayer ? Demosaic.Neighbourhood(stage.Pixels, cfa, dop, cancellationToken)
|
||||
: options.Quality == DemosaicQuality.Best ? AhdDemosaic.Run(stage.Pixels, cfa, colour.BalancedToXyz, dop, cancellationToken)
|
||||
: Demosaic.Bilinear(stage.Pixels, cfa, dop, cancellationToken);
|
||||
if (stage.ClipMask is { } mask) bits = HighlightReconstruction.Dilate(mask, stage.Width, stage.Height);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
rgb = stage.Pixels.Clone();
|
||||
for (var c = 0; c < 3; c++) Scale(rgb.Plane(c), wb[c]);
|
||||
bits = stage.ClipMask;
|
||||
}
|
||||
|
||||
var image = new OpcodeImage(rgb, stage.Left, stage.Top, step, null);
|
||||
try
|
||||
{
|
||||
if (bits is not null) HighlightReconstruction.Apply(rgb, bits, [wb[0] * saturation, wb[1] * saturation, wb[2] * saturation], dop, cancellationToken);
|
||||
var list3 = DngOpcodes.Parse(frame.OpcodeList3, 3, warnings);
|
||||
if (list3.Count > 0)
|
||||
{
|
||||
// Value-mapping opcodes are defined on unbalanced camera values; gains and warps commute with the multipliers.
|
||||
var unbalance = list3.Exists(o => o.NeedsUnbalancedValues);
|
||||
if (unbalance) ScalePlanes(image.Pixels, [1 / wb[0], 1 / wb[1], 1 / wb[2]]);
|
||||
DngOpcodes.Apply(list3, image, warnings, cancellationToken);
|
||||
if (unbalance) ScalePlanes(image.Pixels, wb);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
image.Pixels.Dispose();
|
||||
throw;
|
||||
}
|
||||
var cropped = Crop(frame, image);
|
||||
try
|
||||
{
|
||||
ApplyMatrix(cropped, colour.BalancedToRec709, dop, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
cropped.Dispose();
|
||||
throw;
|
||||
}
|
||||
return Finish(frame, cropped, options);
|
||||
}
|
||||
|
||||
private static ImageBuffer DevelopMonochrome(RawFrame frame, OpcodeImage stage, RawDecodeOptions options, ICollection<string> warnings, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = new OpcodeImage(stage.Pixels.Clone(), stage.Left, stage.Top, 1, null);
|
||||
try
|
||||
{
|
||||
DngOpcodes.Apply(DngOpcodes.Parse(frame.OpcodeList3, 3, warnings), image, warnings, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
image.Pixels.Dispose();
|
||||
throw;
|
||||
}
|
||||
ImageBuffer rgb;
|
||||
using (var cropped = Crop(frame, image))
|
||||
{
|
||||
Scale(cropped.Plane(0), (float)double.Exp2(frame.Color.BaselineExposure));
|
||||
rgb = PixelConvert.GrayToRgb(cropped);
|
||||
}
|
||||
return Finish(frame, rgb, options);
|
||||
}
|
||||
|
||||
/// <summary>Default scale, then orientation. Takes ownership of <paramref name="image"/>: returns it when nothing
|
||||
/// changes, otherwise a new buffer (the input is disposed).</summary>
|
||||
private static ImageBuffer Finish(RawFrame frame, ImageBuffer image, RawDecodeOptions options)
|
||||
{
|
||||
var current = image;
|
||||
try
|
||||
{
|
||||
var (sh, sv) = frame.DefaultScale;
|
||||
if (sh != sv && sh > 0 && sv > 0)
|
||||
{
|
||||
// Only the ratio matters for square output pixels; stretch the axis with the larger factor.
|
||||
var ratio = sh / sv;
|
||||
var (w, h) = ratio > 1 ? ((int)double.Round(current.Width * ratio), current.Height) : (current.Width, (int)double.Round(current.Height / ratio));
|
||||
current = Replace(current, Resampler.Resize(current, int.Max(1, w), int.Max(1, h)));
|
||||
}
|
||||
if (options.ApplyOrientation && frame.Orientation is >= 2 and <= 8)
|
||||
current = Replace(current, PixelConvert.ApplyOrientation(current, frame.Orientation));
|
||||
return current;
|
||||
}
|
||||
catch
|
||||
{
|
||||
current.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static ImageBuffer Replace(ImageBuffer old, ImageBuffer next)
|
||||
{
|
||||
old.Dispose();
|
||||
return next;
|
||||
}
|
||||
|
||||
/// <summary>Stored values as floats divided by 65535 (the stage-1 domain of the opcodes), sample planes split.</summary>
|
||||
private static ImageBuffer ToStage1(RawSamples samples, int dop, CancellationToken cancellationToken)
|
||||
{
|
||||
int w = samples.Width, h = samples.Height, spp = samples.SamplesPerPixel;
|
||||
var image = new ImageBuffer(w, h, spp == 1 ? 1 : 3, clear: false);
|
||||
Parallel.For(0, h, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
for (var s = 0; s < image.Channels; s++)
|
||||
{
|
||||
var row = image.Row(s, y);
|
||||
var o = (long)y * w * spp + s;
|
||||
for (var x = 0; x < w; x++) row[x] = samples[o + (long)x * spp] / 65535f;
|
||||
}
|
||||
});
|
||||
return image;
|
||||
}
|
||||
|
||||
/// <summary>Linear reference values over the active area plus a clip map (bit = CFA colour or sample plane), or null
|
||||
/// when nothing clipped.</summary>
|
||||
private static (ImageBuffer Image, byte[]? Clip) Linearize(RawFrame frame, RawSamples samples, ImageBuffer? stage1, RawBlackLevel black, double[] white, float clipLevel, int dop, CancellationToken cancellationToken)
|
||||
{
|
||||
var active = frame.ActiveArea;
|
||||
int w = active.Width, h = active.Height, spp = frame.SamplesPerPixel;
|
||||
var planes = spp == 1 ? 1 : 3;
|
||||
var image = new ImageBuffer(w, h, planes, clear: false);
|
||||
var clip = new byte[w * h];
|
||||
var anyClip = 0;
|
||||
var table = frame.Linearization;
|
||||
var scale = new float[planes];
|
||||
for (var s = 0; s < planes; s++)
|
||||
{
|
||||
var range = white[int.Min(s, white.Length - 1)] - black.Max(s, spp);
|
||||
if (!(range > 0)) throw new InvalidDataException("RAW: white level not above black level");
|
||||
scale[s] = (float)(1 / range);
|
||||
}
|
||||
var cfa = frame.Cfa;
|
||||
Parallel.For(0, h, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var sy = active.Top + y;
|
||||
var blackRow = y % black.RepeatRows * black.RepeatColumns * spp;
|
||||
var deltaV = black.DeltaV is { } dv && y < dv.Length ? dv[y] : 0f;
|
||||
var rowClip = 0;
|
||||
for (var s = 0; s < planes; s++)
|
||||
{
|
||||
var row = image.Row(s, y);
|
||||
var source = stage1 is null ? default : stage1.Row(s, sy);
|
||||
var o = (long)sy * samples.Width * spp + s;
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var sx = active.Left + x;
|
||||
var v = source.IsEmpty ? samples[o + (long)sx * spp] : source[sx] * 65535f;
|
||||
if (table is not null) v = table[int.Clamp((int)(v + 0.5f), 0, table.Length - 1)];
|
||||
var b = black.Values[blackRow + x % black.RepeatColumns * spp + s] + deltaV
|
||||
+ (black.DeltaH is { } dh && x < dh.Length ? dh[x] : 0f);
|
||||
var value = (v - b) * scale[s];
|
||||
row[x] = value;
|
||||
if (value >= clipLevel)
|
||||
{
|
||||
clip[y * w + x] |= (byte)(1 << (cfa is null ? s : cfa.ColorAt(x, y)));
|
||||
rowClip = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rowClip != 0) Volatile.Write(ref anyClip, 1);
|
||||
});
|
||||
return (image, anyClip != 0 ? clip : null);
|
||||
}
|
||||
|
||||
/// <summary>Normalised saturation level of a native RAW: the data maximum when at least <see cref="SaturationPileUp"/>
|
||||
/// samples reach it and it lies between <see cref="SaturationFloor"/> and 1 of the white level, else 1. It only moves
|
||||
/// the clip threshold; scaling stays tied to the white level so brightness never depends on frame content.</summary>
|
||||
private static float Saturation(RawSamples samples, RawRect active, RawBlackLevel black, double white)
|
||||
{
|
||||
var max = 0f;
|
||||
var count = 0;
|
||||
for (var y = active.Top; y < active.Bottom; y++)
|
||||
{
|
||||
var o = (long)y * samples.Width;
|
||||
for (var x = active.Left; x < active.Right; x++)
|
||||
{
|
||||
var v = samples[o + x];
|
||||
if (v > max + 1)
|
||||
{
|
||||
max = v;
|
||||
count = 1;
|
||||
}
|
||||
else if (v >= max - 1)
|
||||
{
|
||||
count++;
|
||||
max = float.Max(max, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count < SaturationPileUp || max >= white || max < white * SaturationFloor) return 1f;
|
||||
var floor = black.Max(0, 1);
|
||||
return (float)double.Clamp((max - 1 - floor) / (white - floor), 0.5, 1);
|
||||
}
|
||||
|
||||
private static void ScaleMosaic(ImageBuffer mosaic, CfaPattern cfa, float[] wb, int dop, CancellationToken cancellationToken)
|
||||
{
|
||||
Parallel.For(0, mosaic.Height, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var row = mosaic.Row(0, y);
|
||||
Span<float> phase = stackalloc float[CfaPattern.MaxSize];
|
||||
for (var i = 0; i < cfa.Width; i++) phase[i] = wb[cfa.ColorAt(i, y)];
|
||||
for (var x = 0; x < row.Length; x++) row[x] *= phase[x % cfa.Width];
|
||||
});
|
||||
}
|
||||
|
||||
private static void ScalePlanes(ImageBuffer image, float[] factors)
|
||||
{
|
||||
for (var c = 0; c < 3; c++) Scale(image.Plane(c), factors[c]);
|
||||
}
|
||||
|
||||
private static void Scale(Span<float> values, float factor)
|
||||
{
|
||||
for (var i = 0; i < values.Length; i++) values[i] *= factor;
|
||||
}
|
||||
|
||||
/// <summary>Default crop (stage coordinates relative to the active area) intersected with what the opcodes left. Takes
|
||||
/// ownership of the image's pixels: returns them when nothing is cut, otherwise a new buffer (the input is disposed).</summary>
|
||||
private static ImageBuffer Crop(RawFrame frame, OpcodeImage image)
|
||||
{
|
||||
var crop = frame.DefaultCrop ?? new RawRect(0, 0, frame.ActiveArea.Width, frame.ActiveArea.Height);
|
||||
var area = crop.Intersect(image.Bounds);
|
||||
if (area.IsEmpty) area = image.Bounds;
|
||||
var x0 = int.Clamp((int)double.Ceiling(image.BufferX(area.Left) - 1e-9), 0, image.Width - 1);
|
||||
var y0 = int.Clamp((int)double.Ceiling(image.BufferY(area.Top) - 1e-9), 0, image.Height - 1);
|
||||
var x1 = int.Clamp((int)double.Floor(image.BufferX(area.Right - 1) + 1e-9) + 1, x0 + 1, image.Width);
|
||||
var y1 = int.Clamp((int)double.Floor(image.BufferY(area.Bottom - 1) + 1e-9) + 1, y0 + 1, image.Height);
|
||||
var src = image.Pixels;
|
||||
if (x0 == 0 && y0 == 0 && x1 == src.Width && y1 == src.Height) return src;
|
||||
var dst = new ImageBuffer(x1 - x0, y1 - y0, src.Channels, clear: false);
|
||||
for (var c = 0; c < src.Channels; c++)
|
||||
{
|
||||
for (var y = y0; y < y1; y++) src.Row(c, y).Slice(x0, x1 - x0).CopyTo(dst.Row(c, y - y0));
|
||||
}
|
||||
src.Dispose();
|
||||
return dst;
|
||||
}
|
||||
|
||||
private static void ApplyMatrix(ImageBuffer image, Matrix3 m, int dop, CancellationToken cancellationToken)
|
||||
{
|
||||
float m11 = (float)m.M11, m12 = (float)m.M12, m13 = (float)m.M13;
|
||||
float m21 = (float)m.M21, m22 = (float)m.M22, m23 = (float)m.M23;
|
||||
float m31 = (float)m.M31, m32 = (float)m.M32, m33 = (float)m.M33;
|
||||
Parallel.For(0, image.Height, new ParallelOptions { MaxDegreeOfParallelism = dop, CancellationToken = cancellationToken }, y =>
|
||||
{
|
||||
var r = image.Row(0, y);
|
||||
var g = image.Row(1, y);
|
||||
var b = image.Row(2, y);
|
||||
for (var x = 0; x < r.Length; x++)
|
||||
{
|
||||
float vr = r[x], vg = g[x], vb = b[x];
|
||||
r[x] = m11 * vr + m12 * vg + m13 * vb;
|
||||
g[x] = m21 * vr + m22 * vg + m23 * vb;
|
||||
b[x] = m31 * vr + m32 * vg + m33 * vb;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using Titano.Core.Codecs.Dng;
|
||||
|
||||
namespace Titano.Core.Codecs.Raw;
|
||||
|
||||
/// <summary>Integer rectangle (left, top inclusive; right, bottom exclusive).</summary>
|
||||
public readonly record struct RawRect(int Left, int Top, int Right, int Bottom)
|
||||
{
|
||||
public int Width => Right - Left;
|
||||
public int Height => Bottom - Top;
|
||||
public bool IsEmpty => Width <= 0 || Height <= 0;
|
||||
|
||||
public RawRect Intersect(RawRect other) => new(
|
||||
int.Max(Left, other.Left), int.Max(Top, other.Top), int.Min(Right, other.Right), int.Min(Bottom, other.Bottom));
|
||||
|
||||
public override string ToString() => $"{Left},{Top} {Width}x{Height}";
|
||||
}
|
||||
|
||||
/// <summary>Black level description (DNG BlackLevelRepeatDim, BlackLevel, BlackLevelDeltaH/V), relative to the active area.</summary>
|
||||
internal sealed class RawBlackLevel
|
||||
{
|
||||
public static RawBlackLevel Zero(int samplesPerPixel) => new(1, 1, new float[samplesPerPixel], null, null);
|
||||
|
||||
public RawBlackLevel(int repeatRows, int repeatColumns, float[] values, float[]? deltaH, float[]? deltaV)
|
||||
{
|
||||
RepeatRows = repeatRows;
|
||||
RepeatColumns = repeatColumns;
|
||||
Values = values;
|
||||
DeltaH = deltaH;
|
||||
DeltaV = deltaV;
|
||||
}
|
||||
|
||||
public int RepeatRows { get; }
|
||||
public int RepeatColumns { get; }
|
||||
|
||||
/// <summary>rows × columns × samples-per-pixel values, sample index fastest.</summary>
|
||||
public float[] Values { get; }
|
||||
|
||||
public float[]? DeltaH { get; }
|
||||
public float[]? DeltaV { get; }
|
||||
|
||||
/// <summary>Largest black level of a sample plane, deltas included (the white-scaling reference of the DNG SDK).</summary>
|
||||
public float Max(int sample, int samplesPerPixel)
|
||||
{
|
||||
var max = float.MinValue;
|
||||
for (var i = sample; i < Values.Length; i += samplesPerPixel) max = float.Max(max, Values[i]);
|
||||
return max + (DeltaH is { Length: > 0 } h ? MaxOf(h) : 0) + (DeltaV is { Length: > 0 } v ? MaxOf(v) : 0);
|
||||
}
|
||||
|
||||
private static float MaxOf(float[] values)
|
||||
{
|
||||
var max = float.MinValue;
|
||||
foreach (var v in values) max = float.Max(max, v);
|
||||
return max;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Decoded raw samples as stored in the file: interleaved, <see cref="Width"/> × <see cref="Height"/> ×
|
||||
/// <see cref="SamplesPerPixel"/>, integers or floats.</summary>
|
||||
internal sealed class RawSamples(int width, int height, int samplesPerPixel, ushort[]? integers, float[]? floats)
|
||||
{
|
||||
public int Width { get; } = width;
|
||||
public int Height { get; } = height;
|
||||
public int SamplesPerPixel { get; } = samplesPerPixel;
|
||||
public ushort[]? Integers { get; } = integers;
|
||||
public float[]? Floats { get; } = floats;
|
||||
public List<string> Warnings { get; } = [];
|
||||
|
||||
/// <summary>Black level measured by the loader (e.g. from masked sensor columns), overriding the frame's own.</summary>
|
||||
public RawBlackLevel? MeasuredBlack { get; set; }
|
||||
|
||||
public float this[long index] => Integers is { } i ? i[index] : Floats![index];
|
||||
}
|
||||
|
||||
/// <summary>Reads the pixel payload of one container; created by the container parser, run by the pipeline.</summary>
|
||||
internal abstract class RawLoader
|
||||
{
|
||||
/// <exception cref="InvalidDataException">The payload is malformed or uses an unsupported encoding.</exception>
|
||||
public abstract RawSamples Load(Stream stream, int maxDegreeOfParallelism, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Everything the development pipeline needs about one raw image, independent of the container: raster geometry, CFA,
|
||||
/// linearisation, black/white levels, crops, colour profile, opcode lists and orientation. Built by the DNG reader and the
|
||||
/// native RAW readers without touching the pixel payload.
|
||||
/// </summary>
|
||||
internal sealed class RawFrame
|
||||
{
|
||||
/// <summary>Decoder name for logs ("managed-dng", "managed-cr2"…).</summary>
|
||||
public required string Decoder { get; init; }
|
||||
|
||||
public required int Width { get; init; }
|
||||
public required int Height { get; init; }
|
||||
|
||||
/// <summary>1 for CFA and monochrome data, 3 for LinearRaw RGB.</summary>
|
||||
public int SamplesPerPixel { get; init; } = 1;
|
||||
|
||||
/// <summary>CFA layout anchored at the active area's top-left; null for linear (already demosaiced) data.</summary>
|
||||
public CfaPattern? Cfa { get; init; }
|
||||
|
||||
/// <summary>Image area holding valid pixels, in stored coordinates.</summary>
|
||||
public required RawRect ActiveArea { get; init; }
|
||||
|
||||
/// <summary>Final crop relative to the active area (DNG DefaultCropOrigin/Size); null = the whole active area.</summary>
|
||||
public RawRect? DefaultCrop { get; init; }
|
||||
|
||||
/// <summary>DNG DefaultScale (horizontal, vertical) for non-square pixels.</summary>
|
||||
public (double H, double V) DefaultScale { get; init; } = (1, 1);
|
||||
|
||||
public ushort[]? Linearization { get; init; }
|
||||
public required RawBlackLevel Black { get; init; }
|
||||
|
||||
/// <summary>White level per sample plane, in linearised units.</summary>
|
||||
public required double[] White { get; init; }
|
||||
|
||||
/// <summary>Find the clip threshold in the data: native RAWs state a nominal bit-depth maximum while sensors saturate
|
||||
/// earlier. Only clip detection uses it; the white level keeps scaling every frame the same (no flicker).</summary>
|
||||
public bool DetectSaturation { get; init; }
|
||||
|
||||
public required DngColorProfile Color { get; init; }
|
||||
public byte[]? OpcodeList1 { get; init; }
|
||||
public byte[]? OpcodeList2 { get; init; }
|
||||
public byte[]? OpcodeList3 { get; init; }
|
||||
|
||||
/// <summary>Exif orientation 1–8.</summary>
|
||||
public int Orientation { get; init; } = 1;
|
||||
|
||||
public string? Make { get; init; }
|
||||
public string? Model { get; init; }
|
||||
public required RawLoader Loader { get; init; }
|
||||
public List<string> Warnings { get; } = [];
|
||||
|
||||
/// <summary>Size of the developed image before orientation (active area or default crop, default scale applied).</summary>
|
||||
public (int Width, int Height) OutputSize
|
||||
{
|
||||
get
|
||||
{
|
||||
var crop = DefaultCrop ?? new RawRect(0, 0, ActiveArea.Width, ActiveArea.Height);
|
||||
return (int.Max(1, (int)double.Round(crop.Width * DefaultScale.H)), int.Max(1, (int)double.Round(crop.Height * DefaultScale.V)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,218 @@
|
||||
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>
|
||||
/// <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.
|
||||
/// <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;
|
||||
if (family is ImageFamily.Jpeg or ImageFamily.Png or ImageFamily.Tiff)
|
||||
{
|
||||
var (w, h) = MetadataReader.Read(stream, path).OrientedSize;
|
||||
var decoder = family switch { ImageFamily.Jpeg => "managed-jpeg", ImageFamily.Png => "managed-png", _ => "managed-tiff" };
|
||||
return new FileTier(format, DecodeTier.Native, decoder, 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);
|
||||
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);
|
||||
return new FileTier(format, DecodeTier.EmbeddedPreview, "managed-preview", reason, pw, ph);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Titano.Core.Imaging;
|
||||
|
||||
/// <summary>Options for <see cref="FrameWindow"/>.</summary>
|
||||
public sealed record FrameWindowOptions
|
||||
{
|
||||
/// <summary>Frames before the render position that stay available (temporal filters look back).</summary>
|
||||
public int Behind { get; init; } = 2;
|
||||
|
||||
/// <summary>Frames after the render position decoded in the background.</summary>
|
||||
public int Ahead { get; init; } = 4;
|
||||
|
||||
/// <summary>Upper bound on the bytes of decoded frames held in memory, in-flight decodes included.</summary>
|
||||
public long MemoryBudget { get; init; } = 1L << 30;
|
||||
|
||||
/// <summary>Directory of the spill file (null: the system temporary directory).</summary>
|
||||
public string? SpillDirectory { get; init; }
|
||||
|
||||
/// <summary>Background decodes running at once.</summary>
|
||||
public int MaxConcurrentLoads { get; init; } = 2;
|
||||
}
|
||||
|
||||
/// <summary>Counters of a <see cref="FrameWindow"/>, for diagnostics and the memory self-tests.</summary>
|
||||
public readonly record struct FrameWindowStatistics(long LiveBytes, long PeakLiveBytes, int Loads, int SpillWrites, int SpillReads, long SpillFileBytes);
|
||||
|
||||
/// <summary>A frame kept resident while the lease is held. The image must not be modified (it may be shared with a spill copy).</summary>
|
||||
public sealed class FrameLease : IDisposable
|
||||
{
|
||||
private FrameWindow? _window;
|
||||
|
||||
internal FrameLease(FrameWindow window, int index, ImageBuffer image)
|
||||
{
|
||||
_window = window;
|
||||
Index = index;
|
||||
Image = image;
|
||||
}
|
||||
|
||||
public int Index { get; }
|
||||
public ImageBuffer Image { get; }
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _window, null)?.Release(Index);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sliding window of decoded frames around the render position (BRIEF §8.4). Frames from <c>position − Behind</c> to
|
||||
/// <c>position + Ahead</c> are kept; those ahead are decoded on background tasks as the memory budget allows. When a
|
||||
/// demanded frame needs room, unleased frames outside the window are dropped first, then in-window frames farthest from
|
||||
/// the position are evicted to a spill file and read back on demand (cheaper than decoding a RAW again). Live memory
|
||||
/// therefore stays within <see cref="FrameWindowOptions.MemoryBudget"/> (exceeded only by frames the caller holds
|
||||
/// leases on), and the spill file within the window's size: both are independent of the sequence length.
|
||||
/// <para>The spill file stores raw float32 planes: renders stay bit-identical whether or not a frame was spilled (a
|
||||
/// float16 spill would halve disk traffic but make output depend on memory pressure). It is deleted on disposal,
|
||||
/// including after cancellation, and opened delete-on-close as a backstop.</para>
|
||||
/// </summary>
|
||||
public sealed class FrameWindow : IDisposable, IAsyncDisposable
|
||||
{
|
||||
private readonly Func<int, CancellationToken, ValueTask<ImageBuffer>> _loader;
|
||||
private readonly FrameWindowOptions _options;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _demand = new(1, 1);
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly Dictionary<int, Slot> _slots = [];
|
||||
private SpillFile? _spill;
|
||||
private long _liveBytes, _peakLiveBytes, _estimate;
|
||||
private int _position, _backgroundLoads, _loads, _spillWrites, _spillReads;
|
||||
private bool _disposed;
|
||||
|
||||
/// <param name="frameCount">Frames in the sequence.</param>
|
||||
/// <param name="loader">Decodes frame <c>i</c>; called on background threads, at most once per residency.</param>
|
||||
public FrameWindow(int frameCount, Func<int, CancellationToken, ValueTask<ImageBuffer>> loader, FrameWindowOptions? options = null)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(frameCount);
|
||||
ArgumentNullException.ThrowIfNull(loader);
|
||||
_options = options ?? new FrameWindowOptions();
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(_options.Behind);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(_options.Ahead);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(_options.MemoryBudget);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(_options.MaxConcurrentLoads);
|
||||
Count = frameCount;
|
||||
_loader = loader;
|
||||
}
|
||||
|
||||
public int Count { get; }
|
||||
|
||||
public int Position
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _position;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Path of the spill file once created (it is removed on disposal).</summary>
|
||||
public string? SpillPath
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _spill?.Path;
|
||||
}
|
||||
}
|
||||
|
||||
public FrameWindowStatistics Statistics
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return new FrameWindowStatistics(_liveBytes, _peakLiveBytes, _loads, _spillWrites, _spillReads, _spill?.Length ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves the render position: frames that left the window are released and read-ahead starts.</summary>
|
||||
public void MoveTo(int position)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(position);
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
_position = position;
|
||||
foreach (var slot in _slots.Values.ToList())
|
||||
{
|
||||
if (!InWindow(slot.Index) && slot.Leases == 0 && slot.Loading is null && !slot.Spilling) Drop(slot);
|
||||
}
|
||||
ScheduleReadAhead();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns frame <paramref name="index"/>, decoding it (or reading it back from the spill file) when needed.
|
||||
/// Does not move the window.</summary>
|
||||
/// <exception cref="OperationCanceledException">Cancelled, or the window was disposed.</exception>
|
||||
public async ValueTask<FrameLease> GetAsync(int index, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token);
|
||||
var token = linked.Token;
|
||||
while (true)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
Task<Exception?>? pending;
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_slots.TryGetValue(index, out var slot) && slot.Image is { } image)
|
||||
{
|
||||
slot.Leases++;
|
||||
return new FrameLease(this, index, image);
|
||||
}
|
||||
pending = slot?.Loading;
|
||||
}
|
||||
if (pending is not null)
|
||||
{
|
||||
if (await pending.WaitAsync(token).ConfigureAwait(false) is { } error) throw error is OperationCanceledException ? new OperationCanceledException(error.Message, error, token) : error;
|
||||
continue;
|
||||
}
|
||||
await _demand.WaitAsync(token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await LoadWithinBudgetAsync(index, token).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_demand.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>Cancels background decodes, waits for them and for an eviction in progress, releases every frame and
|
||||
/// deletes the spill file. The semaphore and token source are left undisposed on purpose: callers racing the disposal
|
||||
/// may still release or observe them, and neither holds an unmanaged resource here.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
}
|
||||
_cts.Cancel();
|
||||
await _demand.WaitAsync().ConfigureAwait(false);
|
||||
Task[] pending;
|
||||
lock (_gate) pending = [.. _slots.Values.Select(s => s.Loading).OfType<Task>()];
|
||||
await Task.WhenAll(pending).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var slot in _slots.Values)
|
||||
{
|
||||
slot.Image?.Dispose();
|
||||
slot.Image = null;
|
||||
}
|
||||
_slots.Clear();
|
||||
_liveBytes = 0;
|
||||
_spill?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
internal void Release(int index)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || !_slots.TryGetValue(index, out var slot)) return;
|
||||
slot.Leases--;
|
||||
if (slot.Leases == 0 && !InWindow(index) && slot.Loading is null && !slot.Spilling) Drop(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private bool InWindow(int index) => index >= _position - _options.Behind && index <= _position + _options.Ahead;
|
||||
|
||||
/// <summary>Starts the decode (or spill read) of <paramref name="index"/> once its size fits the budget: unleased frames
|
||||
/// outside the window are dropped first, then in-window frames farthest from the position are spilled. The check and
|
||||
/// the start happen under one lock so background read-ahead cannot take the room in between. The budget is exceeded
|
||||
/// only when every resident frame is leased. Callers hold the demand semaphore (one eviction at a time).</summary>
|
||||
private async Task LoadWithinBudgetAsync(int index, CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Slot victim;
|
||||
ImageBuffer image;
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (!_slots.TryGetValue(index, out var slot))
|
||||
{
|
||||
slot = new Slot(index);
|
||||
_slots[index] = slot;
|
||||
}
|
||||
if (slot.Image is not null || slot.Loading is not null) return;
|
||||
var required = slot.Spill?.Bytes ?? _estimate;
|
||||
Slot? best = null;
|
||||
if (_liveBytes + required > _options.MemoryBudget)
|
||||
{
|
||||
foreach (var s in _slots.Values)
|
||||
{
|
||||
if (s.Index == index || s.Image is null || s.Leases > 0 || s.Spilling) continue;
|
||||
if (best is null || Priority(s) > Priority(best)) best = s;
|
||||
}
|
||||
}
|
||||
if (best is null)
|
||||
{
|
||||
StartLoad(slot, background: false);
|
||||
return;
|
||||
}
|
||||
if (!InWindow(best.Index))
|
||||
{
|
||||
Drop(best);
|
||||
continue;
|
||||
}
|
||||
if (best.Spill is not null)
|
||||
{
|
||||
Unload(best);
|
||||
continue;
|
||||
}
|
||||
best.Spilling = true;
|
||||
_spill ??= new SpillFile(_options.SpillDirectory);
|
||||
(victim, image) = (best, best.Image!);
|
||||
}
|
||||
SpillExtent extent;
|
||||
try
|
||||
{
|
||||
extent = await Task.Run(() => _spill!.Write(image), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
lock (_gate) victim.Spilling = false;
|
||||
throw;
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
victim.Spilling = false;
|
||||
victim.Spill = extent;
|
||||
_spillWrites++;
|
||||
if (victim.Leases == 0) Unload(victim);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Eviction order: outside the window first, then the farthest from the position (behind before ahead).</summary>
|
||||
private double Priority(Slot s)
|
||||
{
|
||||
var distance = s.Index < _position ? (_position - s.Index) * 1.5 : s.Index - _position;
|
||||
return InWindow(s.Index) ? distance : 1e9 + distance;
|
||||
}
|
||||
|
||||
/// <summary>Starts a decode (or spill read) for the slot, reserving the estimated size. Caller holds the gate.</summary>
|
||||
private void StartLoad(Slot slot, bool background)
|
||||
{
|
||||
var reserved = slot.Spill?.Bytes ?? _estimate;
|
||||
slot.Reserved = reserved;
|
||||
_liveBytes += reserved;
|
||||
_peakLiveBytes = long.Max(_peakLiveBytes, _liveBytes);
|
||||
if (background) _backgroundLoads++;
|
||||
var spill = slot.Spill;
|
||||
var token = _cts.Token;
|
||||
slot.Loading = Task.Run(async () =>
|
||||
{
|
||||
ImageBuffer? image = null;
|
||||
try
|
||||
{
|
||||
if (spill is not null) image = _spill!.Read(spill);
|
||||
else image = await _loader(slot.Index, token).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
slot.Loading = null;
|
||||
if (background) _backgroundLoads--;
|
||||
_liveBytes -= slot.Reserved;
|
||||
slot.Reserved = 0;
|
||||
if (_disposed)
|
||||
{
|
||||
image.Dispose();
|
||||
return new OperationCanceledException("The frame window was disposed.");
|
||||
}
|
||||
slot.Image = image;
|
||||
_liveBytes += image.ByteSize;
|
||||
_peakLiveBytes = long.Max(_peakLiveBytes, _liveBytes);
|
||||
if (spill is null)
|
||||
{
|
||||
_loads++;
|
||||
_estimate = image.ByteSize;
|
||||
}
|
||||
else
|
||||
{
|
||||
_spillReads++;
|
||||
}
|
||||
ScheduleReadAhead();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
image?.Dispose();
|
||||
lock (_gate)
|
||||
{
|
||||
if (slot.Loading is not null)
|
||||
{
|
||||
slot.Loading = null;
|
||||
if (background) _backgroundLoads--;
|
||||
_liveBytes -= slot.Reserved;
|
||||
slot.Reserved = 0;
|
||||
}
|
||||
if (slot.Image is null && slot.Spill is null && slot.Leases == 0) _slots.Remove(slot.Index);
|
||||
}
|
||||
return (Exception?)ex;
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>Starts background decodes of missing frames ahead while the budget allows. Caller holds the gate.</summary>
|
||||
private void ScheduleReadAhead()
|
||||
{
|
||||
if (_disposed) return;
|
||||
var last = int.Min(Count - 1, _position + _options.Ahead);
|
||||
for (var i = _position; i <= last && _backgroundLoads < _options.MaxConcurrentLoads; i++)
|
||||
{
|
||||
if (_slots.TryGetValue(i, out var existing) && (existing.Image is not null || existing.Loading is not null || existing.Spill is not null)) continue;
|
||||
// The first frame's size is unknown: allow one decode to learn it.
|
||||
if (_estimate == 0 ? _loads + _backgroundLoads > 0 : _liveBytes + _estimate > _options.MemoryBudget) return;
|
||||
if (existing is null)
|
||||
{
|
||||
existing = new Slot(i);
|
||||
_slots[i] = existing;
|
||||
}
|
||||
StartLoad(existing, background: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Releases the frame's memory (its spill copy, if any, stays). Caller holds the gate.</summary>
|
||||
private void Unload(Slot slot)
|
||||
{
|
||||
if (slot.Image is null) return;
|
||||
_liveBytes -= slot.Image.ByteSize;
|
||||
slot.Image.Dispose();
|
||||
slot.Image = null;
|
||||
}
|
||||
|
||||
/// <summary>Forgets the frame entirely (memory and spill extent). Caller holds the gate.</summary>
|
||||
private void Drop(Slot slot)
|
||||
{
|
||||
Unload(slot);
|
||||
if (slot.Spill is { } extent) _spill?.Free(extent);
|
||||
slot.Spill = null;
|
||||
_slots.Remove(slot.Index);
|
||||
}
|
||||
|
||||
private sealed class Slot(int index)
|
||||
{
|
||||
public int Index { get; } = index;
|
||||
public ImageBuffer? Image { get; set; }
|
||||
public Task<Exception?>? Loading { get; set; }
|
||||
public SpillExtent? Spill { get; set; }
|
||||
public bool Spilling { get; set; }
|
||||
public int Leases { get; set; }
|
||||
public long Reserved { get; set; }
|
||||
}
|
||||
|
||||
private sealed record SpillExtent(long Offset, int Width, int Height, int Channels)
|
||||
{
|
||||
public long Bytes => (long)Width * Height * Channels * sizeof(float);
|
||||
}
|
||||
|
||||
/// <summary>Temporary file of float32 planes; freed extents are reused by frames of the same size.</summary>
|
||||
private sealed class SpillFile : IDisposable
|
||||
{
|
||||
private readonly SafeFileHandle _handle;
|
||||
private readonly List<SpillExtent> _free = [];
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public SpillFile(string? directory)
|
||||
{
|
||||
var dir = directory ?? System.IO.Path.GetTempPath();
|
||||
Directory.CreateDirectory(dir);
|
||||
Path = System.IO.Path.Combine(dir, $"titano-spill-{Guid.NewGuid():N}.tmp");
|
||||
_handle = File.OpenHandle(Path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileOptions.DeleteOnClose | FileOptions.RandomAccess);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
public long Length { get; private set; }
|
||||
|
||||
public SpillExtent Write(ImageBuffer image)
|
||||
{
|
||||
SpillExtent extent;
|
||||
lock (_gate)
|
||||
{
|
||||
var reuse = _free.FindIndex(e => e.Width == image.Width && e.Height == image.Height && e.Channels == image.Channels);
|
||||
if (reuse >= 0)
|
||||
{
|
||||
extent = _free[reuse];
|
||||
_free.RemoveAt(reuse);
|
||||
}
|
||||
else
|
||||
{
|
||||
extent = new SpillExtent(Length, image.Width, image.Height, image.Channels);
|
||||
Length += extent.Bytes;
|
||||
}
|
||||
}
|
||||
var planeBytes = (long)image.PlaneLength * sizeof(float);
|
||||
for (var c = 0; c < image.Channels; c++) RandomAccess.Write(_handle, MemoryMarshal.AsBytes((ReadOnlySpan<float>)image.Plane(c)), extent.Offset + c * planeBytes);
|
||||
return extent;
|
||||
}
|
||||
|
||||
public ImageBuffer Read(SpillExtent extent)
|
||||
{
|
||||
var image = new ImageBuffer(extent.Width, extent.Height, extent.Channels, clear: false);
|
||||
try
|
||||
{
|
||||
var planeBytes = (long)image.PlaneLength * sizeof(float);
|
||||
for (var c = 0; c < image.Channels; c++)
|
||||
{
|
||||
var bytes = MemoryMarshal.AsBytes(image.Plane(c));
|
||||
var done = 0;
|
||||
while (done < bytes.Length)
|
||||
{
|
||||
var n = RandomAccess.Read(_handle, bytes[done..], extent.Offset + c * planeBytes + done);
|
||||
if (n == 0) throw new IOException("Spill file truncated");
|
||||
done += n;
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
catch
|
||||
{
|
||||
image.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Free(SpillExtent extent)
|
||||
{
|
||||
lock (_gate) _free.Add(extent);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_handle.Dispose();
|
||||
try
|
||||
{
|
||||
if (File.Exists(Path)) File.Delete(Path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Metadata;
|
||||
|
||||
namespace Titano.Core.Imaging.Thumbnails;
|
||||
|
||||
/// <summary>Proxy long-edge policy (BRIEF §8.5).</summary>
|
||||
public enum ProxySize
|
||||
{
|
||||
/// <summary>Source resolution.</summary>
|
||||
Full = 0,
|
||||
Edge1280 = 1280,
|
||||
Edge1920 = 1920,
|
||||
Edge2560 = 2560,
|
||||
}
|
||||
|
||||
/// <summary>A built proxy and how its pixels were obtained.</summary>
|
||||
/// <param name="Jpeg">JPEG file bytes with an Exif block.</param>
|
||||
/// <param name="Width">Proxy width (oriented).</param>
|
||||
/// <param name="Height">Proxy height (oriented).</param>
|
||||
/// <param name="Tier">Decode tier of the source (an embedded preview caps the proxy at the preview's size).</param>
|
||||
public sealed record ProxyResult(byte[] Jpeg, int Width, int Height, DecodeTier Tier);
|
||||
|
||||
/// <summary>
|
||||
/// Builds proxies (BRIEF §8.5): the source decoded at the policy long edge (1280/1920/2560 or full) with its orientation
|
||||
/// applied, encoded as JPEG q92, carrying an Exif block written by <see cref="ExifWriter.BuildJpegApp1"/> from the
|
||||
/// source metadata (capture time, camera, exposure, GPS) with orientation reset to 1 because the pixels are upright.
|
||||
/// </summary>
|
||||
public static class ProxyBuilder
|
||||
{
|
||||
public const int Quality = 92;
|
||||
|
||||
/// <summary>Default policy.</summary>
|
||||
public const ProxySize DefaultSize = ProxySize.Edge1920;
|
||||
|
||||
/// <summary>Decodes and encodes the proxy of <paramref name="sourcePath"/>; null when no tier can decode it.</summary>
|
||||
/// <param name="metadata">Source metadata; read from the file when null.</param>
|
||||
public static ProxyResult? Build(ImageDecoder decoder, string sourcePath, ProxySize size = DefaultSize, FrameMetadata? metadata = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
using var decoded = decoder.Decode(new DecodeRequest(sourcePath, (int)size, DecodePurpose.Proxy), cancellationToken);
|
||||
if (decoded is null) return null;
|
||||
metadata ??= MetadataReader.Read(sourcePath, cancellationToken);
|
||||
return new ProxyResult(Encode(decoded.Pixels, metadata), decoded.Pixels.Width, decoded.Pixels.Height, decoded.Tier);
|
||||
}
|
||||
|
||||
/// <summary>Builds the proxy and writes it crash-safely to <paramref name="proxyPath"/>.</summary>
|
||||
public static ProxyResult? Write(ImageDecoder decoder, string sourcePath, string proxyPath, ProxySize size = DefaultSize, FrameMetadata? metadata = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = Build(decoder, sourcePath, size, metadata, cancellationToken);
|
||||
if (result is not null) AtomicFile.WriteAllBytes(proxyPath, result.Jpeg);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Encodes upright linear-light pixels as a proxy JPEG with the source's Exif (orientation 1).</summary>
|
||||
public static byte[] Encode(ImageBuffer image, FrameMetadata metadata)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
ArgumentNullException.ThrowIfNull(metadata);
|
||||
var segment = ExifWriter.BuildJpegApp1(metadata with { Orientation = 1, Width = image.Width, Height = image.Height });
|
||||
// The encoder takes APP1 payloads: drop the marker and length that BuildJpegApp1 puts in front.
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = Quality, App1Segments = [segment[4..]], OptimizeHuffman = true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
|
||||
namespace Titano.Core.Imaging.Thumbnails;
|
||||
|
||||
/// <summary>A decoded thumbnail ready for display: interleaved 8-bit sRGB RGB.</summary>
|
||||
public sealed class Thumbnail(int width, int height, byte[] rgb)
|
||||
{
|
||||
public int Width { get; } = width;
|
||||
public int Height { get; } = height;
|
||||
|
||||
/// <summary>Width × height × 3 bytes, sRGB-encoded, top-down.</summary>
|
||||
public byte[] Rgb { get; } = rgb;
|
||||
|
||||
/// <summary>Memory charged against a <see cref="ThumbnailCache{TKey}"/> budget.</summary>
|
||||
public long ByteSize => Rgb.Length + 64;
|
||||
|
||||
/// <summary>Decodes a thumbnail JPEG (gray is expanded to RGB).</summary>
|
||||
/// <exception cref="InvalidDataException">The JPEG is malformed.</exception>
|
||||
public static Thumbnail FromJpeg(ReadOnlySpan<byte> jpeg)
|
||||
{
|
||||
var image = JpegDecoder.Decode(jpeg);
|
||||
var pixels = image.Pixels8 ?? throw new InvalidDataException("Thumbnail: not an 8-bit JPEG");
|
||||
if (image.Components == 3) return new Thumbnail(image.Width, image.Height, pixels);
|
||||
var rgb = new byte[pixels.Length * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) rgb[3 * i] = rgb[3 * i + 1] = rgb[3 * i + 2] = pixels[i];
|
||||
return new Thumbnail(image.Width, image.Height, rgb);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In-memory LRU of decoded thumbnails under a byte budget (BRIEF §8.5). Thread-safe; concurrent requests for the same
|
||||
/// key share one load (<see cref="GetOrLoadAsync"/>), so a scrolling UI never decodes a thumbnail twice.
|
||||
/// </summary>
|
||||
public sealed class ThumbnailCache<TKey> where TKey : notnull
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<TKey, LinkedListNode<(TKey Key, Thumbnail Value)>> _map = [];
|
||||
private readonly LinkedList<(TKey Key, Thumbnail Value)> _lru = new();
|
||||
private readonly Dictionary<TKey, Task<Thumbnail?>> _loading = [];
|
||||
private long _bytes;
|
||||
|
||||
/// <param name="byteBudget">Upper bound on the bytes held (a thumbnail larger than the budget is never cached).</param>
|
||||
public ThumbnailCache(long byteBudget)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(byteBudget);
|
||||
Budget = byteBudget;
|
||||
}
|
||||
|
||||
public long Budget { get; }
|
||||
|
||||
public long Bytes
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _map.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns a cached thumbnail and marks it most recently used.</summary>
|
||||
public bool TryGet(TKey key, out Thumbnail thumbnail)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_map.TryGetValue(key, out var node))
|
||||
{
|
||||
_lru.Remove(node);
|
||||
_lru.AddFirst(node);
|
||||
thumbnail = node.Value.Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
thumbnail = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Adds or replaces a thumbnail, evicting least recently used ones to stay within the budget.</summary>
|
||||
public void Set(TKey key, Thumbnail thumbnail)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(thumbnail);
|
||||
lock (_gate)
|
||||
{
|
||||
RemoveLocked(key);
|
||||
if (thumbnail.ByteSize > Budget) return;
|
||||
_map[key] = _lru.AddFirst((key, thumbnail));
|
||||
_bytes += thumbnail.ByteSize;
|
||||
while (_bytes > Budget && _lru.Last is { } last)
|
||||
{
|
||||
RemoveLocked(last.Value.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(TKey key)
|
||||
{
|
||||
lock (_gate) return RemoveLocked(key);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_map.Clear();
|
||||
_lru.Clear();
|
||||
_bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cached thumbnail, or the result of <paramref name="loader"/> (cached when not null). Concurrent calls for
|
||||
/// the same key await the same load; each caller's <paramref name="cancellationToken"/> only cancels its own wait.</summary>
|
||||
public async Task<Thumbnail?> GetOrLoadAsync(TKey key, Func<TKey, CancellationToken, Task<Thumbnail?>> loader, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(loader);
|
||||
if (TryGet(key, out var hit)) return hit;
|
||||
Task<Thumbnail?> task;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_loading.TryGetValue(key, out task!))
|
||||
{
|
||||
task = LoadAsync(key, loader);
|
||||
_loading[key] = task;
|
||||
}
|
||||
}
|
||||
return await task.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<Thumbnail?> LoadAsync(TKey key, Func<TKey, CancellationToken, Task<Thumbnail?>> loader)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Yield();
|
||||
var value = await loader(key, CancellationToken.None).ConfigureAwait(false);
|
||||
if (value is not null) Set(key, value);
|
||||
return value;
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate) _loading.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private bool RemoveLocked(TKey key)
|
||||
{
|
||||
if (!_map.Remove(key, out var node)) return false;
|
||||
_lru.Remove(node);
|
||||
_bytes -= node.Value.Value.ByteSize;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Hashing;
|
||||
using Titano.Core.IO;
|
||||
|
||||
namespace Titano.Core.Imaging.Thumbnails;
|
||||
|
||||
/// <summary>Index entry of one thumbnail in a <see cref="ThumbnailPack"/>.</summary>
|
||||
/// <param name="FrameId">Frame the thumbnail belongs to.</param>
|
||||
/// <param name="Offset">File offset of the entry record.</param>
|
||||
/// <param name="Length">JPEG length in bytes.</param>
|
||||
/// <param name="Width">Thumbnail width in pixels.</param>
|
||||
/// <param name="Height">Thumbnail height in pixels.</param>
|
||||
/// <param name="Crc">CRC-32 of the JPEG bytes.</param>
|
||||
public readonly record struct ThumbnailEntry(Guid FrameId, long Offset, int Length, int Width, int Height, uint Crc);
|
||||
|
||||
/// <summary>
|
||||
/// The per-sequence thumbnail file <c>thumbs.pack</c> (BRIEF §8.5): 320-pixel JPEG (q80) thumbnails appended to one file.
|
||||
/// <para>Layout (little-endian): two 64-byte header slots at 0 and 64 (magic "TTPK", version, generation, offset/length/
|
||||
/// count of the current index record, the file length it covers, CRC-32); from 128, self-describing records — entries
|
||||
/// ("TENT": frame id, size, JPEG length and CRC, then the JPEG) and index tables ("TIDX": count, then frame id → offset,
|
||||
/// length, size, CRC per entry, then the record's CRC).</para>
|
||||
/// <para>Writes only append. Every <see cref="IndexInterval"/> appends (and on <see cref="Flush"/>/<see cref="Dispose"/>)
|
||||
/// a new index record is appended and flushed, then the header slot not holding the newest generation is overwritten and
|
||||
/// flushed: a crash leaves the previous slot valid. Opening takes the newest valid slot, then recovers entries appended
|
||||
/// after its index by scanning forward until the first damaged record, so truncated or partially written files lose
|
||||
/// only their damaged tail. <see cref="Compact"/> rewrites live entries into a fresh file committed with
|
||||
/// <see cref="AtomicFile"/>. Reads use positional I/O and run concurrently with one writer.</para>
|
||||
/// </summary>
|
||||
public sealed class ThumbnailPack : IDisposable
|
||||
{
|
||||
public const int LongEdge = 320;
|
||||
public const int Quality = 80;
|
||||
public const int IndexInterval = 64;
|
||||
|
||||
private const uint HeaderMagic = 0x4B505454; // "TTPK"
|
||||
private const uint EntryMagic = 0x544E4554; // "TENT"
|
||||
private const uint IndexMagic = 0x58444954; // "TIDX"
|
||||
private const ushort Version = 1;
|
||||
private const int SlotSize = 64;
|
||||
private const int DataStart = 2 * SlotSize;
|
||||
private const int EntryHeaderSize = 32;
|
||||
private const int IndexEntrySize = 36;
|
||||
private const int MaxJpegBytes = 16 << 20;
|
||||
|
||||
private readonly ReaderWriterLockSlim _handleLock = new(LockRecursionPolicy.NoRecursion);
|
||||
private readonly Lock _writeLock = new();
|
||||
private readonly List<string> _warnings = [];
|
||||
private ConcurrentDictionary<Guid, ThumbnailEntry> _index = new();
|
||||
private SafeFileHandle _handle;
|
||||
private long _tail;
|
||||
private ulong _generation;
|
||||
private int _activeSlot;
|
||||
private int _unindexed;
|
||||
private long _liveBytes;
|
||||
private bool _disposed;
|
||||
|
||||
private ThumbnailPack(string path, bool writable, SafeFileHandle handle)
|
||||
{
|
||||
Path = path;
|
||||
Writable = writable;
|
||||
_handle = handle;
|
||||
Load();
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
public bool Writable { get; }
|
||||
|
||||
/// <summary>Problems met while opening or refreshing (damaged slots, records dropped from the tail).</summary>
|
||||
public IReadOnlyList<string> Warnings
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_warnings) return [.. _warnings];
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => Volatile.Read(ref _index).Count;
|
||||
|
||||
/// <summary>Snapshot of the frames with a thumbnail.</summary>
|
||||
public IReadOnlyCollection<Guid> FrameIds => [.. Volatile.Read(ref _index).Keys];
|
||||
|
||||
/// <summary>Bytes held by superseded or removed entries (reclaimed by <see cref="Compact"/>).</summary>
|
||||
public long WastedBytes => long.Max(0, _tail - DataStart - Volatile.Read(ref _liveBytes));
|
||||
|
||||
/// <summary>Opens (creating when writable and missing) a pack.</summary>
|
||||
public static ThumbnailPack Open(string path, bool writable = true)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
if (writable && !File.Exists(path)) AtomicFile.WriteAllBytes(path, EmptyFile());
|
||||
var handle = File.OpenHandle(path, FileMode.Open, writable ? FileAccess.ReadWrite : FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess);
|
||||
return new ThumbnailPack(path, writable, handle);
|
||||
}
|
||||
|
||||
/// <summary>Downscales a linear-light image to the thumbnail long edge and encodes it (JPEG q80).</summary>
|
||||
public static (byte[] Jpeg, int Width, int Height) Encode(ImageBuffer image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
using var small = Resampler.Thumbnail(image, LongEdge);
|
||||
return (JpegEncoder.Encode(small, new JpegEncodeOptions { Quality = Quality }), small.Width, small.Height);
|
||||
}
|
||||
|
||||
public bool TryGetEntry(Guid frameId, out ThumbnailEntry entry) => Volatile.Read(ref _index).TryGetValue(frameId, out entry);
|
||||
|
||||
/// <summary>The JPEG bytes of a frame's thumbnail; null when absent or damaged (CRC mismatch).</summary>
|
||||
public byte[]? ReadJpeg(Guid frameId)
|
||||
{
|
||||
if (!TryGetEntry(frameId, out var e)) return null;
|
||||
var data = new byte[e.Length];
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (RandomAccess.Read(_handle, data, e.Offset + EntryHeaderSize) != data.Length) return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
return Crc32.Compute(data) == e.Crc ? data : null;
|
||||
}
|
||||
|
||||
/// <summary>Encodes and appends the thumbnail of <paramref name="image"/>, replacing any previous one for the frame.</summary>
|
||||
public ThumbnailEntry Add(Guid frameId, ImageBuffer image)
|
||||
{
|
||||
var (jpeg, w, h) = Encode(image);
|
||||
return AddJpeg(frameId, jpeg, w, h);
|
||||
}
|
||||
|
||||
/// <summary>Appends an encoded thumbnail, replacing any previous one for the frame.</summary>
|
||||
public ThumbnailEntry AddJpeg(Guid frameId, ReadOnlySpan<byte> jpeg, int width, int height)
|
||||
{
|
||||
if (!Writable) throw new InvalidOperationException("The pack is open read-only.");
|
||||
if (jpeg.Length is 0 or > MaxJpegBytes) throw new ArgumentOutOfRangeException(nameof(jpeg));
|
||||
if (width is < 1 or > ushort.MaxValue || height is < 1 or > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(width));
|
||||
lock (_writeLock)
|
||||
{
|
||||
var record = new byte[EntryHeaderSize + jpeg.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record, EntryMagic);
|
||||
frameId.TryWriteBytes(record.AsSpan(4));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(20), (ushort)width);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(22), (ushort)height);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(record.AsSpan(24), jpeg.Length);
|
||||
var crc = Crc32.Compute(jpeg);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(28), crc);
|
||||
jpeg.CopyTo(record.AsSpan(EntryHeaderSize));
|
||||
var entry = new ThumbnailEntry(frameId, _tail, jpeg.Length, width, height, crc);
|
||||
WriteAt(record, _tail);
|
||||
_tail += record.Length;
|
||||
if (_index.TryGetValue(frameId, out var old)) Interlocked.Add(ref _liveBytes, -(EntryHeaderSize + old.Length));
|
||||
_index[frameId] = entry;
|
||||
Interlocked.Add(ref _liveBytes, record.Length);
|
||||
if (++_unindexed >= IndexInterval) WriteIndex();
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops a frame's thumbnail from the index (its bytes stay until <see cref="Compact"/>).</summary>
|
||||
public bool Remove(Guid frameId)
|
||||
{
|
||||
if (!Writable) throw new InvalidOperationException("The pack is open read-only.");
|
||||
lock (_writeLock)
|
||||
{
|
||||
if (!_index.TryRemove(frameId, out var old)) return false;
|
||||
Interlocked.Add(ref _liveBytes, -(EntryHeaderSize + old.Length));
|
||||
_unindexed++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes the index now (appended record, then the alternate header slot).</summary>
|
||||
public void Flush()
|
||||
{
|
||||
if (!Writable) return;
|
||||
lock (_writeLock)
|
||||
{
|
||||
if (_unindexed > 0) WriteIndex();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rewrites the live entries into a new file and atomically replaces this one.</summary>
|
||||
public void Compact()
|
||||
{
|
||||
if (!Writable) throw new InvalidOperationException("The pack is open read-only.");
|
||||
lock (_writeLock)
|
||||
{
|
||||
var temp = AtomicFile.TempPathFor(Path);
|
||||
var entries = Volatile.Read(ref _index).Values.OrderBy(e => e.Offset).ToList();
|
||||
var moved = new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
using (var output = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16))
|
||||
{
|
||||
output.Write(new byte[DataStart]);
|
||||
var buffer = new byte[EntryHeaderSize + MaxJpegBytes / 16];
|
||||
foreach (var e in entries)
|
||||
{
|
||||
var size = EntryHeaderSize + e.Length;
|
||||
if (buffer.Length < size) buffer = new byte[size];
|
||||
_handleLock.EnterReadLock();
|
||||
int read;
|
||||
try
|
||||
{
|
||||
read = RandomAccess.Read(_handle, buffer.AsSpan(0, size), e.Offset);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
if (read != size || Crc32.Compute(buffer.AsSpan(EntryHeaderSize, e.Length)) != e.Crc)
|
||||
{
|
||||
Warn($"Thumbnail of {e.FrameId} damaged; dropped during compaction");
|
||||
continue;
|
||||
}
|
||||
moved[e.FrameId] = e with { Offset = output.Position };
|
||||
output.Write(buffer, 0, size);
|
||||
}
|
||||
var indexOffset = output.Position;
|
||||
var index = IndexRecord(moved.Values);
|
||||
output.Write(index);
|
||||
output.Position = 0;
|
||||
output.Write(HeaderSlot(_generation + 1, indexOffset, index.Length, moved.Count, indexOffset + index.Length));
|
||||
}
|
||||
_handleLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_handle.Dispose();
|
||||
AtomicFile.Commit(temp, Path);
|
||||
_handle = File.OpenHandle(Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess);
|
||||
_index = moved;
|
||||
_generation++;
|
||||
_activeSlot = 0;
|
||||
_tail = RandomAccess.GetLength(_handle);
|
||||
_liveBytes = moved.Values.Sum(e => (long)EntryHeaderSize + e.Length);
|
||||
_unindexed = 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the file (read-only instances use it to see entries written by another instance).</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
if (Writable) return;
|
||||
_handleLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
_handle.Dispose();
|
||||
_handle = File.OpenHandle(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitWriteLock();
|
||||
}
|
||||
Load();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
if (Writable)
|
||||
{
|
||||
try
|
||||
{
|
||||
Flush();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Warn("Index not written on close: " + ex.Message);
|
||||
}
|
||||
}
|
||||
_handleLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_disposed = true;
|
||||
_handle.Dispose();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitWriteLock();
|
||||
}
|
||||
_handleLock.Dispose();
|
||||
}
|
||||
|
||||
private static byte[] EmptyFile()
|
||||
{
|
||||
var file = new byte[DataStart];
|
||||
HeaderSlot(1, 0, 0, 0, DataStart).CopyTo(file, 0);
|
||||
return file;
|
||||
}
|
||||
|
||||
private static byte[] HeaderSlot(ulong generation, long indexOffset, int indexLength, int count, long dataEnd)
|
||||
{
|
||||
var slot = new byte[SlotSize];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(slot, HeaderMagic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(slot.AsSpan(4), Version);
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(slot.AsSpan(8), generation);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(slot.AsSpan(16), indexOffset);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(slot.AsSpan(24), indexLength);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(slot.AsSpan(28), count);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(slot.AsSpan(32), dataEnd);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(slot.AsSpan(SlotSize - 4), Crc32.Compute(slot.AsSpan(0, SlotSize - 4)));
|
||||
return slot;
|
||||
}
|
||||
|
||||
private static byte[] IndexRecord(IEnumerable<ThumbnailEntry> entries)
|
||||
{
|
||||
var list = entries.ToList();
|
||||
var record = new byte[8 + list.Count * IndexEntrySize + 4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record, IndexMagic);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(record.AsSpan(4), list.Count);
|
||||
for (var i = 0; i < list.Count; i++)
|
||||
{
|
||||
var s = record.AsSpan(8 + i * IndexEntrySize, IndexEntrySize);
|
||||
var e = list[i];
|
||||
e.FrameId.TryWriteBytes(s);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(s[16..], e.Offset);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(s[24..], e.Length);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(s[28..], (ushort)e.Width);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(s[30..], (ushort)e.Height);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(s[32..], e.Crc);
|
||||
}
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(record.Length - 4), Crc32.Compute(record.AsSpan(0, record.Length - 4)));
|
||||
return record;
|
||||
}
|
||||
|
||||
/// <summary>Appends an index record, flushes, then commits it through the header slot not holding the newest generation.</summary>
|
||||
private void WriteIndex()
|
||||
{
|
||||
var index = Volatile.Read(ref _index);
|
||||
var record = IndexRecord(index.Values);
|
||||
var offset = _tail;
|
||||
WriteAt(record, offset);
|
||||
_tail += record.Length;
|
||||
RandomAccess.FlushToDisk(_handle);
|
||||
var slot = 1 - _activeSlot;
|
||||
WriteAt(HeaderSlot(_generation + 1, offset, record.Length, index.Count, _tail), slot * SlotSize);
|
||||
RandomAccess.FlushToDisk(_handle);
|
||||
_generation++;
|
||||
_activeSlot = slot;
|
||||
_unindexed = 0;
|
||||
}
|
||||
|
||||
private void WriteAt(ReadOnlySpan<byte> data, long offset)
|
||||
{
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
RandomAccess.Write(_handle, data, offset);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
private void Warn(string message)
|
||||
{
|
||||
lock (_warnings)
|
||||
{
|
||||
if (_warnings.Count < 32) _warnings.Add(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the newest valid header slot and its index, then recovers entries appended after it.</summary>
|
||||
private void Load()
|
||||
{
|
||||
long length;
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
length = RandomAccess.GetLength(_handle);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
var index = new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
long scanFrom = DataStart;
|
||||
(_generation, _activeSlot) = (0, 1);
|
||||
var slots = new byte[DataStart];
|
||||
var slotBytes = ReadAt(slots, 0);
|
||||
for (var s = 0; s < 2; s++)
|
||||
{
|
||||
if (slotBytes < (s + 1) * SlotSize || ParseSlot(slots.AsSpan(s * SlotSize, SlotSize)) is not { } h)
|
||||
{
|
||||
if (slotBytes >= (s + 1) * SlotSize && slots.AsSpan(s * SlotSize, SlotSize).ContainsAnyExcept((byte)0)) Warn($"Header slot {s} damaged");
|
||||
continue;
|
||||
}
|
||||
if (h.Generation <= _generation) continue;
|
||||
var loaded = h.IndexLength > 0 ? ReadIndex(h.IndexOffset, h.IndexLength, length) : new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
if (loaded is null)
|
||||
{
|
||||
Warn($"Index of header slot {s} damaged");
|
||||
continue;
|
||||
}
|
||||
(_generation, _activeSlot) = (h.Generation, s);
|
||||
index = loaded;
|
||||
scanFrom = h.DataEnd;
|
||||
}
|
||||
if (_generation == 0) Warn("No valid header; entries recovered by scanning");
|
||||
_tail = length <= DataStart ? DataStart : Recover(index, long.Clamp(scanFrom, DataStart, length), length);
|
||||
_index = index;
|
||||
_liveBytes = index.Values.Sum(e => (long)EntryHeaderSize + e.Length);
|
||||
_unindexed = 0;
|
||||
}
|
||||
|
||||
private readonly record struct Slot(ulong Generation, long IndexOffset, int IndexLength, long DataEnd);
|
||||
|
||||
private static Slot? ParseSlot(ReadOnlySpan<byte> s)
|
||||
{
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != HeaderMagic || BinaryPrimitives.ReadUInt16LittleEndian(s[4..]) != Version) return null;
|
||||
if (Crc32.Compute(s[..(SlotSize - 4)]) != BinaryPrimitives.ReadUInt32LittleEndian(s[(SlotSize - 4)..])) return null;
|
||||
return new Slot(BinaryPrimitives.ReadUInt64LittleEndian(s[8..]), BinaryPrimitives.ReadInt64LittleEndian(s[16..]),
|
||||
BinaryPrimitives.ReadInt32LittleEndian(s[24..]), BinaryPrimitives.ReadInt64LittleEndian(s[32..]));
|
||||
}
|
||||
|
||||
private ConcurrentDictionary<Guid, ThumbnailEntry>? ReadIndex(long offset, int length, long fileLength)
|
||||
{
|
||||
if (offset < DataStart || length < 12 || offset > fileLength - length || (length - 12) % IndexEntrySize != 0) return null;
|
||||
var record = new byte[length];
|
||||
if (ReadAt(record, offset) != length) return null;
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(record) != IndexMagic
|
||||
|| Crc32.Compute(record.AsSpan(0, length - 4)) != BinaryPrimitives.ReadUInt32LittleEndian(record.AsSpan(length - 4))) return null;
|
||||
var count = BinaryPrimitives.ReadInt32LittleEndian(record.AsSpan(4));
|
||||
if (count != (length - 12) / IndexEntrySize) return null;
|
||||
var index = new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var s = record.AsSpan(8 + i * IndexEntrySize, IndexEntrySize);
|
||||
var e = new ThumbnailEntry(new Guid(s[..16]), BinaryPrimitives.ReadInt64LittleEndian(s[16..]), BinaryPrimitives.ReadInt32LittleEndian(s[24..]),
|
||||
BinaryPrimitives.ReadUInt16LittleEndian(s[28..]), BinaryPrimitives.ReadUInt16LittleEndian(s[30..]), BinaryPrimitives.ReadUInt32LittleEndian(s[32..]));
|
||||
if (e.Offset >= DataStart && e.Length is > 0 and <= MaxJpegBytes && e.Offset <= fileLength - EntryHeaderSize - e.Length) index[e.FrameId] = e;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>Walks records from <paramref name="position"/>, adding valid entries (later ones win) and skipping index
|
||||
/// records; stops at the first damaged or truncated record. Returns the end of the last good record.</summary>
|
||||
private long Recover(ConcurrentDictionary<Guid, ThumbnailEntry> index, long position, long length)
|
||||
{
|
||||
var head = new byte[EntryHeaderSize];
|
||||
var recovered = 0;
|
||||
while (position + 12 <= length)
|
||||
{
|
||||
var n = ReadAt(head.AsSpan(0, (int)long.Min(EntryHeaderSize, length - position)), position);
|
||||
var magic = BinaryPrimitives.ReadUInt32LittleEndian(head);
|
||||
if (magic == IndexMagic && n >= 8)
|
||||
{
|
||||
var count = BinaryPrimitives.ReadInt32LittleEndian(head.AsSpan(4));
|
||||
var size = 12L + (long)count * IndexEntrySize;
|
||||
if (count < 0 || position + size > length || ReadIndex(position, (int)long.Min(size, int.MaxValue), length) is null) break;
|
||||
position += size;
|
||||
continue;
|
||||
}
|
||||
if (magic != EntryMagic || n < EntryHeaderSize) break;
|
||||
var jpegLength = BinaryPrimitives.ReadInt32LittleEndian(head.AsSpan(24));
|
||||
if (jpegLength is <= 0 or > MaxJpegBytes || position + EntryHeaderSize + jpegLength > length) break;
|
||||
var jpeg = new byte[jpegLength];
|
||||
if (ReadAt(jpeg, position + EntryHeaderSize) != jpegLength) break;
|
||||
var crc = BinaryPrimitives.ReadUInt32LittleEndian(head.AsSpan(28));
|
||||
if (Crc32.Compute(jpeg) != crc) break;
|
||||
var id = new Guid(head.AsSpan(4, 16));
|
||||
index[id] = new ThumbnailEntry(id, position, jpegLength, BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(20)), BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(22)), crc);
|
||||
position += EntryHeaderSize + jpegLength;
|
||||
recovered++;
|
||||
}
|
||||
if (position < length) Warn($"Ignored {length - position} damaged bytes at the end of the pack");
|
||||
if (recovered > 0) Warn($"Recovered {recovered} thumbnail(s) appended after the last index");
|
||||
return position;
|
||||
}
|
||||
|
||||
private int ReadAt(Span<byte> buffer, long offset)
|
||||
{
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
var total = 0;
|
||||
while (total < buffer.Length)
|
||||
{
|
||||
var n = RandomAccess.Read(_handle, buffer[total..], offset + total);
|
||||
if (n == 0) break;
|
||||
total += n;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user