Reads CFA and LinearRaw DNGs (compression 1/7/8/34892), linearises with LinearizationTable, BlackLevel (repeat + deltas) and WhiteLevel over the ActiveArea, applies OpcodeList1-3 (GainMap, WarpRectilinear, FixVignetteRadial, FixBadPixels*, TrimBounds, MapTable/MapPolynomial, Delta/ScalePer*), solves white balance per DNG 1.6 chapter 6 (CCT interpolation, ForwardMatrix, Bradford to D65), demosaics with AHD (Hirakawa & Parks 2005), bilinear, a neighbourhood interpolation for non-Bayer CFAs or binning, and reconstructs clipped highlights. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
713 lines
31 KiB
C#
713 lines
31 KiB
C#
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));
|
||
}
|
||
}
|