feat(raw): DNG development pipeline with AHD demosaic, opcodes and DNG colour
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
This commit is contained in:
15 files changed
+3559
No files matched your search
@@ -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,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,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,126 @@
|
||||
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>Bin CFA blocks into RGB pixels instead of demosaicing: half size for Bayer, one third for X-Trans.
|
||||
/// Ignored for linear (already demosaiced) data and for patterns that cannot be binned.</summary>
|
||||
public bool Binning { get; init; }
|
||||
|
||||
/// <summary>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"/>,
|
||||
/// developed by the shared 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];
|
||||
|
||||
/// <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),
|
||||
_ => 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,316 @@
|
||||
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>LibRaw's adjust_maximum_thr: the data maximum replaces the nominal white level above this fraction of it.</summary>
|
||||
private const double AdjustMaximumThreshold = 0.75;
|
||||
|
||||
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 = (double[])frame.White.Clone();
|
||||
if (frame.AdjustWhiteToData) AdjustWhite(samples, active, white, warnings);
|
||||
|
||||
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, 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, options, warnings, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Pixels.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static ImageBuffer DevelopColour(RawFrame frame, OpcodeImage stage, 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 = options.Binning ? cfa.BinSize : 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, 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);
|
||||
}
|
||||
using var cropped = Crop(frame, image);
|
||||
ApplyMatrix(cropped, colour.BalancedToRec709, dop, cancellationToken);
|
||||
return Finish(frame, cropped, options);
|
||||
}
|
||||
finally
|
||||
{
|
||||
image.Pixels.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
using var cropped = Crop(frame, image);
|
||||
Scale(cropped.Plane(0), (float)double.Exp2(frame.Color.BaselineExposure));
|
||||
using var rgb = PixelConvert.GrayToRgb(cropped);
|
||||
return Finish(frame, rgb, options);
|
||||
}
|
||||
finally
|
||||
{
|
||||
image.Pixels.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Default scale, then orientation; always returns a new buffer.</summary>
|
||||
private static ImageBuffer Finish(RawFrame frame, ImageBuffer image, RawDecodeOptions options)
|
||||
{
|
||||
var (sh, sv) = frame.DefaultScale;
|
||||
ImageBuffer? scaled = null;
|
||||
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(image.Width * ratio), image.Height) : (image.Width, (int)double.Round(image.Height / ratio));
|
||||
scaled = Resampler.Resize(image, int.Max(1, w), int.Max(1, h));
|
||||
}
|
||||
var source = scaled ?? image;
|
||||
try
|
||||
{
|
||||
return options.ApplyOrientation && frame.Orientation is >= 2 and <= 8
|
||||
? PixelConvert.ApplyOrientation(source, frame.Orientation)
|
||||
: source.Clone();
|
||||
}
|
||||
finally
|
||||
{
|
||||
scaled?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, 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 >= ClipThreshold)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
private static void AdjustWhite(RawSamples samples, RawRect active, double[] white, ICollection<string> warnings)
|
||||
{
|
||||
var max = 0f;
|
||||
for (var y = active.Top; y < active.Bottom; y++)
|
||||
{
|
||||
var o = (long)y * samples.Width * samples.SamplesPerPixel;
|
||||
for (var x = active.Left * samples.SamplesPerPixel; x < active.Right * samples.SamplesPerPixel; x++) max = float.Max(max, samples[o + x]);
|
||||
}
|
||||
for (var s = 0; s < white.Length; s++)
|
||||
{
|
||||
if (max > 0 && max < white[s] && max > white[s] * AdjustMaximumThreshold) white[s] = max;
|
||||
}
|
||||
if (max > white.Max()) warnings.Add($"RAW: samples exceed the white level ({max} > {white.Max()})");
|
||||
}
|
||||
|
||||
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.</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;
|
||||
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));
|
||||
}
|
||||
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>Lower the white level to the data maximum when that exceeds 75 % of it (LibRaw adjust_maximum_thr): native
|
||||
/// RAWs state a nominal bit-depth maximum while sensors saturate earlier.</summary>
|
||||
public bool AdjustWhiteToData { 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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user