feat(raw): native CR2, NEF, ARW, PEF and RAF decoders
Each container reader builds a RawFrame for the shared pipeline: CR2 sliced lossless JPEG with SensorInfo crop, masked-column black and ColorData WB; NEF uncompressed and Nikon Huffman (lossy type 1, lossless, lossy type 2 incl. split); ARW uncompressed and ARW2 cRAW with tone curve; PEF uncompressed and Pentax Huffman; RAF uncompressed Bayer and X-Trans with FujiIFD. Colour comes from a dcraw adobe_coeff matrix table; bodies without an entry are reported unsupported so the caller uses the embedded preview. Native RAWs detect the sensor's saturation level for clipping only, never rescaling per frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
14 files changed
+1974
-24
No files matched your search
@@ -0,0 +1,183 @@
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Testing;
|
||||
using static Titano.Core.Tests.Raw.NativeRawWriters;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>Native RAW decoders on synthetic files written in each container's layout: the decoded image must match the
|
||||
/// scene the sensor data was generated from (camera matrix, as-shot white balance, black/white levels, crop).</summary>
|
||||
public sealed class NativeRawTests(TestContext context)
|
||||
{
|
||||
private const int W = 96, H = 64;
|
||||
|
||||
private RawDecodeResult Decode(byte[] file, string name, RawDecodeOptions? options = null)
|
||||
{
|
||||
var result = RawDecoder.Decode(new MemoryStream(file), name, options);
|
||||
context.Log($"{name}: {result.Info} warnings: {string.Join("; ", result.Warnings)}");
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void AssertScene(ImageBuffer scene, ImageBuffer image, double minimum, TestContext context)
|
||||
{
|
||||
Assert.Equal(scene.Width, image.Width);
|
||||
Assert.Equal(scene.Height, image.Height);
|
||||
var psnr = SyntheticRaw.Psnr(scene, image, 4);
|
||||
context.Log($"PSNR {psnr:F1} dB");
|
||||
Assert.GreaterOrEqual(psnr, minimum);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Cr2SlicedLosslessJpegWithMaskedBlack()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
// 24 masked columns left and 4 rows on top; Canon's CFA is RGGB at the raster origin.
|
||||
var active = new RawRect(24, 4, 24 + W, 4 + H);
|
||||
var sensor = Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383);
|
||||
using var result = Decode(Cr2(sensor, active), "IMG_0001.CR2");
|
||||
Assert.Equal("managed-cr2", result.Info.Decoder);
|
||||
Assert.Equal("RGGB", result.Info.Layout);
|
||||
AssertScene(scene, result.Image, 38, context);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(NefEncoding.Lossless, 14)]
|
||||
[Case(NefEncoding.Lossless, 12)]
|
||||
[Case(NefEncoding.Unpacked, 14)]
|
||||
[Case(NefEncoding.Packed, 12)]
|
||||
public void NefEncodings(NefEncoding encoding, int bits)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var sensor = Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600 >> (14 - bits), (1 << bits) - 1);
|
||||
using var result = Decode(Nef(sensor, bits, encoding), "DSC_0001.NEF");
|
||||
Assert.Equal("managed-nef", result.Info.Decoder);
|
||||
AssertScene(scene, result.Image, 38, context);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(NefEncoding.LossyType1, 12, 0)]
|
||||
[Case(NefEncoding.LossyType2, 14, 0)]
|
||||
[Case(NefEncoding.LossyType2, 14, 40)]
|
||||
public void NefLossyCurves(NefEncoding encoding, int bits, int split)
|
||||
{
|
||||
// A square-law curve: dense codes in the shadows, coarse in the highlights.
|
||||
var size = encoding == NefEncoding.LossyType1 ? 683 : 1 << bits;
|
||||
var curve = Enumerable.Range(0, size).Select(i => (ushort)double.Round(((1 << bits) - 1) * (i / (double)(size - 1)) * (i / (double)(size - 1)))).ToArray();
|
||||
var white = encoding == NefEncoding.LossyType1 ? curve[^1] : InterpolatedCurve(curve, bits).Max();
|
||||
// After the split row the tree has no unshifted codes for 9–12-bit differences: keep that scene gentle.
|
||||
using var scene = split > 0 ? Gentle() : SyntheticRaw.Smooth(W, H);
|
||||
var sensor = Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600 >> (14 - bits), white);
|
||||
using var result = Decode(Nef(sensor, bits, encoding, curve: curve, split: split), "DSC_0002.NEF");
|
||||
AssertScene(scene, result.Image, 36, context);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(true)]
|
||||
[Case(false)]
|
||||
public void ArwCompressedAndUncompressed(bool compressed)
|
||||
{
|
||||
ushort[] knots = [8000, 10400, 12900, 14100];
|
||||
var curve = ToneCurve(knots);
|
||||
double white = compressed ? curve[0x7FF << 1] : 16383;
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var sensor = Sensor(scene, "Sony ILCE-7M3", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 512, white);
|
||||
using var result = Decode(Arw(sensor, knots, compressed), "DSC00001.ARW");
|
||||
Assert.Equal("managed-arw", result.Info.Decoder);
|
||||
Assert.Contains(result.Warnings, w => w.Contains("daylight"));
|
||||
AssertScene(scene, result.Image, compressed ? 36 : 38, context);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(true)]
|
||||
[Case(false)]
|
||||
public void PefHuffmanAndUncompressed(bool compressed)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var sensor = Sensor(scene, "Pentax K-1", CfaPattern.Bayer("BGGR"), W, H, 0, 0, 512, 16383);
|
||||
using var result = Decode(Pef(sensor, 14, compressed), "IMGP0001.PEF");
|
||||
Assert.Equal("managed-pef", result.Info.Decoder);
|
||||
Assert.Equal("BGGR", result.Info.Layout);
|
||||
AssertScene(scene, result.Image, 38, context);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(true)]
|
||||
[Case(false)]
|
||||
public void RafXTransAndBayerLayouts(bool xtrans)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var rasterCfa = xtrans ? DemosaicTests.XTrans : CfaPattern.Bayer("GRBG");
|
||||
// Crop starts at an odd offset so the pattern must be re-anchored.
|
||||
var crop = new RawRect(5, 3, 5 + W, 3 + H);
|
||||
var sensor = Sensor(scene, "Fujifilm X-T2", rasterCfa, W + 8, H + 6, crop.Left, crop.Top, 1024, 16383);
|
||||
using var result = Decode(Raf(sensor, Expand(rasterCfa), crop, orientation: 1), "DSCF0001.RAF");
|
||||
Assert.Equal("managed-raf", result.Info.Decoder);
|
||||
Assert.Equal("X-T2", result.Info.Model);
|
||||
AssertScene(scene, result.Image, xtrans ? 34 : 38, context);
|
||||
using var binned = Decode(Raf(sensor, Expand(rasterCfa), crop), "DSCF0001.RAF", new RawDecodeOptions { Binning = true });
|
||||
Assert.Equal(W / (xtrans ? 3 : 2), binned.Image.Width);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OrientationComesFromTheContainer()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var sensor = Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600, 16383);
|
||||
using var result = Decode(Nef(sensor, 14, NefEncoding.Lossless, orientation: 8), "DSC_0003.NEF");
|
||||
Assert.Equal(H, result.Image.Width);
|
||||
Assert.Equal(W, result.Image.Height);
|
||||
Assert.Equal(H, result.Info.Width);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnknownBodyIsUnsupported()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var active = new RawRect(24, 4, 24 + W, 4 + H);
|
||||
var sensor = Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383);
|
||||
var probe = RawDecoder.Probe(new MemoryStream(Cr2(sensor, active, model: "Canon EOS R99")), "x.cr2");
|
||||
Assert.False(probe.IsSupported);
|
||||
Assert.Contains("no colour matrix", probe.Reason);
|
||||
Assert.Throws<InvalidDataException>(() => RawDecoder.Decode(new MemoryStream(Cr2(sensor, active, model: "Canon EOS R99")), "x.cr2"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CameraNamesNormalise()
|
||||
{
|
||||
Assert.Equal("Nikon D850", NativeRaw.CameraName("NIKON CORPORATION", "NIKON D850"));
|
||||
Assert.Equal("Canon EOS 5D Mark III", NativeRaw.CameraName("Canon", "Canon EOS 5D Mark III"));
|
||||
Assert.Equal("Sony ILCE-7M3", NativeRaw.CameraName("SONY", "ILCE-7M3"));
|
||||
Assert.Equal("Pentax K-1", NativeRaw.CameraName("RICOH IMAGING COMPANY, LTD.", "PENTAX K-1"));
|
||||
Assert.Equal("Fujifilm X-T2", NativeRaw.CameraName("FUJIFILM", "X-T2"));
|
||||
// Every tabulated matrix maps D65 to a positive camera neutral with green the strongest channel.
|
||||
foreach (var name in CameraMatrices.Names)
|
||||
{
|
||||
var m = CameraMatrices.Find(name)!.Value;
|
||||
var n = m * Titano.Core.Mathematics.Chromaticity.D65.ToXyz();
|
||||
Assert.True(n.X > 0 && n.Z > 0 && n.Y > n.X && n.Y > n.Z, name);
|
||||
}
|
||||
}
|
||||
|
||||
private static ImageBuffer Gentle()
|
||||
{
|
||||
var scene = new ImageBuffer(W, H);
|
||||
for (var y = 0; y < H; y++)
|
||||
{
|
||||
for (var x = 0; x < W; x++)
|
||||
{
|
||||
scene[0, x, y] = 0.3f + 0.03f * x / W;
|
||||
scene[1, x, y] = 0.32f + 0.02f * y / H;
|
||||
scene[2, x, y] = 0.25f + 0.01f * (x + y) / (W + H);
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
}
|
||||
|
||||
/// <summary>The pattern written into the RAF layout record, expanded to 6×6.</summary>
|
||||
private static CfaPattern Expand(CfaPattern cfa)
|
||||
{
|
||||
var colors = new byte[36];
|
||||
for (var i = 0; i < 36; i++) colors[i] = (byte)cfa.ColorAt(i % 6, i / 6);
|
||||
return new CfaPattern(6, 6, colors);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
using System.Buffers.Binary;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
using Titano.Core.Tests.Metadata.Builders;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>Payload encodings of the synthetic NEF writer.</summary>
|
||||
public enum NefEncoding
|
||||
{
|
||||
Lossless,
|
||||
LossyType1,
|
||||
LossyType2,
|
||||
Unpacked,
|
||||
Packed,
|
||||
}
|
||||
|
||||
/// <summary>A synthetic sensor readout: stored samples of a scene through a camera model, plus the as-shot neutral.</summary>
|
||||
internal sealed record SensorData(ushort[] Samples, int Width, int Height, Vector3D Neutral);
|
||||
|
||||
/// <summary>
|
||||
/// Test-side writers for native RAW containers. Each follows the layout its reader documents (and dcraw/LibRaw decode):
|
||||
/// CR2 sliced lossless JPEG with Canon MakerNote, NEF Nikon Huffman with type-3 MakerNote, ARW2 cRAW blocks with tone
|
||||
/// curve, PEF Pentax Huffman with AOC MakerNote, RAF with FujiIFD and RAF directory.
|
||||
/// </summary>
|
||||
internal static class NativeRawWriters
|
||||
{
|
||||
/// <summary>Stored sensor values of <paramref name="scene"/> placed at (left, top) of a raster, CFA anchored at the raster
|
||||
/// origin, outside pixels at black.</summary>
|
||||
public static SensorData Sensor(ImageBuffer scene, string camera, CfaPattern cfa, int width, int height, int left, int top, double black, double white)
|
||||
{
|
||||
var matrix = CameraMatrices.Find(camera) ?? throw new ArgumentException("No matrix for " + camera);
|
||||
var (rgb, neutral) = SyntheticRaw.ToCamera(scene, matrix, Chromaticity.D65);
|
||||
var samples = new ushort[width * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
int sx = x - left, sy = y - top;
|
||||
var v = black;
|
||||
if (sx >= 0 && sy >= 0 && sx < scene.Width && sy < scene.Height) v += rgb[cfa.ColorAt(x, y)][sy * scene.Width + sx] * (white - black);
|
||||
samples[y * width + x] = (ushort)double.Clamp(double.Round(v), 0, white);
|
||||
}
|
||||
}
|
||||
return new SensorData(samples, width, height, neutral);
|
||||
}
|
||||
|
||||
/// <summary>Real JPEG preview with an Exif block (make, model, orientation).</summary>
|
||||
public static byte[] Preview(string make, string model, int orientation, int width = 64, int height = 48)
|
||||
{
|
||||
using var image = new ImageBuffer(width, height);
|
||||
for (var i = 0; i < image.PlaneLength; i++)
|
||||
{
|
||||
image.Plane(0)[i] = 0.5f;
|
||||
image.Plane(1)[i] = 0.3f;
|
||||
image.Plane(2)[i] = 0.2f;
|
||||
}
|
||||
var exif = ExifWriter.BuildTiff(new FrameMetadata { Make = make, Model = model, Orientation = orientation });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [[.. "Exif\0\0"u8, .. exif]] });
|
||||
}
|
||||
|
||||
/// <summary>Canon CR2: "CR" header, IFD0 JPEG preview, two dummy IFDs, IFD3 lossless raw in two slices.</summary>
|
||||
public static byte[] Cr2(SensorData s, RawRect active, int orientation = 1, string model = "Canon EOS 5D Mark III")
|
||||
{
|
||||
const int components = 2;
|
||||
var sliceWidth = s.Width / 2;
|
||||
var stream = new ushort[s.Samples.Length];
|
||||
var k = 0;
|
||||
foreach (var x0 in new[] { 0, sliceWidth })
|
||||
{
|
||||
for (var y = 0; y < s.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < sliceWidth; x++) stream[k++] = s.Samples[y * s.Width + x0 + x];
|
||||
}
|
||||
}
|
||||
var jpeg = JpegLosslessEncoder.Encode(stream, s.Width / components, s.Height, components, 14);
|
||||
var sensor = new ushort[17];
|
||||
sensor[1] = (ushort)s.Width;
|
||||
sensor[2] = (ushort)s.Height;
|
||||
sensor[5] = (ushort)active.Left;
|
||||
sensor[6] = (ushort)active.Top;
|
||||
sensor[7] = (ushort)(active.Right - 1);
|
||||
sensor[8] = (ushort)(active.Bottom - 1);
|
||||
var colorData = new ushort[1338];
|
||||
colorData[63] = (ushort)double.Round(1024 * s.Neutral.Y / s.Neutral.X);
|
||||
colorData[64] = colorData[65] = 1024;
|
||||
colorData[66] = (ushort)double.Round(1024 * s.Neutral.Y / s.Neutral.Z);
|
||||
var makerNote = new IfdSpec().Short(0x00E0, sensor).Short(0x4001, colorData);
|
||||
var exif = new IfdSpec().Ascii(TiffTags.DateTimeOriginal, "2024:05:01 12:00:00").Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true);
|
||||
var preview = Preview("Canon", model, orientation);
|
||||
var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "Canon").Ascii(TiffTags.Model, model).Short(TiffTags.Orientation, (ushort)orientation)
|
||||
.Short(TiffTags.Compression, 6).Strip(preview).Child(TiffTags.ExifIfd, exif);
|
||||
var ifd1 = new IfdSpec().Short(TiffTags.Compression, 6);
|
||||
var ifd2 = new IfdSpec().Short(TiffTags.Compression, 1);
|
||||
var ifd3 = new IfdSpec().Short(TiffTags.Compression, 6).Strip(jpeg).Short(0xC640, 1, (ushort)sliceWidth, (ushort)(s.Width - sliceWidth));
|
||||
ifd0.Next = ifd1;
|
||||
ifd1.Next = ifd2;
|
||||
ifd2.Next = ifd3;
|
||||
return TiffFile.Build(ifd0, true, headerExtra: [(byte)'C', (byte)'R', 2, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
/// <summary>Canonical codes of a dcraw-layout Huffman specification: symbol → (code, length).</summary>
|
||||
public static Dictionary<int, (int Code, int Length)> Codes(byte[] spec)
|
||||
{
|
||||
var max = 16;
|
||||
while (spec[max - 1] == 0) max--;
|
||||
var codes = new Dictionary<int, (int, int)>();
|
||||
var h = 0;
|
||||
var symbol = 16;
|
||||
for (var len = 1; len <= max; len++)
|
||||
{
|
||||
for (var i = 0; i < spec[len - 1]; i++, symbol++)
|
||||
{
|
||||
codes.TryAdd(spec[symbol], (h >> (max - len), len));
|
||||
h += 1 << (max - len);
|
||||
}
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/// <summary>JPEG difference category and its bits (negative values one's-complement style).</summary>
|
||||
public static (int Length, int Bits) Category(int diff)
|
||||
{
|
||||
if (diff == 0) return (0, 0);
|
||||
var len = 32 - int.LeadingZeroCount(int.Abs(diff));
|
||||
return (len, diff > 0 ? diff : diff + (1 << len) - 1);
|
||||
}
|
||||
|
||||
/// <summary>Two-column horizontal prediction seeded by per-row-parity vertical predictors (Nikon and Pentax).</summary>
|
||||
public static byte[] PredictiveHuffman(ushort[] values, int width, int height, Func<int, Dictionary<int, (int Code, int Length)>> codesForRow, ushort[] initial)
|
||||
{
|
||||
var w = new BitWriter();
|
||||
var vpred = (int[])[initial[0], initial[1], initial[2], initial[3]];
|
||||
var hpred = new int[2];
|
||||
for (var row = 0; row < height; row++)
|
||||
{
|
||||
var codes = codesForRow(row);
|
||||
for (var col = 0; col < width; col++)
|
||||
{
|
||||
int v = values[row * width + col], predicted;
|
||||
if (col < 2)
|
||||
{
|
||||
predicted = vpred[(row & 1) * 2 + col];
|
||||
vpred[(row & 1) * 2 + col] = v;
|
||||
hpred[col] = v;
|
||||
}
|
||||
else
|
||||
{
|
||||
predicted = hpred[col & 1];
|
||||
hpred[col & 1] = v;
|
||||
}
|
||||
var (len, bits) = Category(v - predicted);
|
||||
var (code, codeLength) = codes[len];
|
||||
w.Write(code, codeLength);
|
||||
w.Write(bits, len);
|
||||
}
|
||||
}
|
||||
return w.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Big-endian Nikon NEF: IFD0 thumbnail, SubIFD CFA raw, Exif with a type-3 MakerNote.</summary>
|
||||
public static byte[] Nef(SensorData s, int bits, NefEncoding encoding, int orientation = 1, ushort[]? curve = null, int split = 0)
|
||||
{
|
||||
byte[] data;
|
||||
uint compression = 34713;
|
||||
var meta = new List<byte> { 0x46, 0x30 };
|
||||
ushort[] vpred = [100, 200, 300, 400];
|
||||
switch (encoding)
|
||||
{
|
||||
case NefEncoding.Lossless:
|
||||
data = PredictiveHuffman(s.Samples, s.Width, s.Height, _ => Codes(NefTrees(bits == 14 ? 5 : 2)), vpred);
|
||||
break;
|
||||
case NefEncoding.LossyType1:
|
||||
{
|
||||
meta = [0x44, 0x10];
|
||||
var indices = Indices(s.Samples, curve!);
|
||||
data = PredictiveHuffman(indices, s.Width, s.Height, _ => Codes(NefTrees(bits == 14 ? 3 : 0)), vpred);
|
||||
break;
|
||||
}
|
||||
case NefEncoding.LossyType2:
|
||||
{
|
||||
meta = [0x44, 0x20];
|
||||
var indices = Indices(s.Samples, InterpolatedCurve(curve!, bits));
|
||||
var tree = bits == 14 ? 3 : 0;
|
||||
data = PredictiveHuffman(indices, s.Width, s.Height, row => Codes(NefTrees(split > 0 && row >= split ? tree + 1 : tree)), vpred);
|
||||
break;
|
||||
}
|
||||
case NefEncoding.Unpacked:
|
||||
data = new byte[s.Samples.Length * 2];
|
||||
for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), s.Samples[i]);
|
||||
break;
|
||||
default:
|
||||
compression = 1;
|
||||
data = Packed(s.Samples, s.Width, s.Height, bits);
|
||||
break;
|
||||
}
|
||||
foreach (var v in vpred) meta.AddRange([(byte)(v >> 8), (byte)v]);
|
||||
if (encoding == NefEncoding.LossyType1)
|
||||
{
|
||||
meta.AddRange([(byte)(curve!.Length >> 8), (byte)curve.Length]);
|
||||
foreach (var v in curve) meta.AddRange([(byte)(v >> 8), (byte)v]);
|
||||
}
|
||||
else if (encoding == NefEncoding.LossyType2)
|
||||
{
|
||||
// Curve sampled every 'step' codes; split row at byte 562.
|
||||
meta.AddRange([(byte)(CurvePoints >> 8), unchecked((byte)CurvePoints)]);
|
||||
foreach (var v in CurveSamples(curve!, bits)) meta.AddRange([(byte)(v >> 8), (byte)v]);
|
||||
while (meta.Count < 562) meta.Add(0);
|
||||
meta.AddRange([(byte)(split >> 8), (byte)split]);
|
||||
}
|
||||
else
|
||||
{
|
||||
meta.AddRange([0, 0]);
|
||||
}
|
||||
var nikon = new IfdSpec()
|
||||
.Rational(0x000C, ((uint)double.Round(1e5 * s.Neutral.Y / s.Neutral.X), 100000u), ((uint)double.Round(1e5 * s.Neutral.Y / s.Neutral.Z), 100000u), (1u, 1u), (1u, 1u))
|
||||
.Short(0x003D, 600, 600, 600, 600)
|
||||
.Short(0x0093, (ushort)(encoding == NefEncoding.Lossless ? 3 : encoding == NefEncoding.LossyType1 ? 1 : encoding == NefEncoding.LossyType2 ? 4 : 2))
|
||||
.Undefined(0x0096, [.. meta]);
|
||||
var exif = new IfdSpec().Undefined(TiffTags.MakerNote, [.. "Nikon\0"u8, 2, 0x11, 0, 0, .. TiffFile.Build(nikon, littleEndian: false)]);
|
||||
var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0)
|
||||
.Long(TiffTags.ImageWidth, (uint)s.Width).Long(TiffTags.ImageLength, (uint)s.Height)
|
||||
.Short(TiffTags.BitsPerSample, (ushort)bits).Short(TiffTags.Compression, (ushort)compression)
|
||||
.Short(TiffTags.PhotometricInterpretation, 32803)
|
||||
.Short(TiffTags.CfaRepeatPatternDim, 2, 2).Bytes(TiffTags.CfaPattern, 0, 1, 1, 2)
|
||||
.Strip(data);
|
||||
var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "NIKON CORPORATION").Ascii(TiffTags.Model, "NIKON D850")
|
||||
.Short(TiffTags.Orientation, (ushort)orientation).Long(TiffTags.NewSubfileType, 1)
|
||||
.Child(TiffTags.SubIfds, raw).Child(TiffTags.ExifIfd, exif);
|
||||
return TiffFile.Build(ifd0, littleEndian: false);
|
||||
}
|
||||
|
||||
private static byte[] NefTrees(int index) => NefReader.Trees[index];
|
||||
|
||||
private const int CurvePoints = 257;
|
||||
|
||||
private static ushort[] CurveSamples(ushort[] curve, int bits)
|
||||
{
|
||||
var step = (1 << bits & 0x7FFF) / (CurvePoints - 1);
|
||||
return [.. Enumerable.Range(0, CurvePoints).Select(i => curve[int.Min(i * step, curve.Length - 1)])];
|
||||
}
|
||||
|
||||
/// <summary>The curve a lossy type-2 decoder rebuilds: samples every step codes, linearly interpolated.</summary>
|
||||
public static ushort[] InterpolatedCurve(ushort[] curve, int bits)
|
||||
{
|
||||
var max = 1 << bits & 0x7FFF;
|
||||
var step = max / (CurvePoints - 1);
|
||||
var samples = CurveSamples(curve, bits);
|
||||
var result = new ushort[max];
|
||||
for (var i = 0; i < max; i++)
|
||||
{
|
||||
int k = i % step, a = i / step;
|
||||
result[i] = (ushort)((samples[a] * (step - k) + samples[int.Min(a + 1, samples.Length - 1)] * k) / step);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Curve indices whose values are nearest to the samples (monotonic curve).</summary>
|
||||
public static ushort[] Indices(ushort[] samples, ushort[] curve)
|
||||
{
|
||||
var result = new ushort[samples.Length];
|
||||
for (var i = 0; i < samples.Length; i++)
|
||||
{
|
||||
var target = samples[i];
|
||||
int lo = 0, hi = curve.Length - 1;
|
||||
while (lo < hi)
|
||||
{
|
||||
var mid = (lo + hi) / 2;
|
||||
if (curve[mid] < target) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
if (lo > 0 && target - curve[lo - 1] < curve[lo] - target) lo--;
|
||||
result[i] = (ushort)lo;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>MSB-first packed samples (TIFF convention), rows padded to whole bytes.</summary>
|
||||
public static byte[] Packed(ushort[] samples, int width, int height, int bits)
|
||||
{
|
||||
var w = new BitWriter();
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++) w.Write(samples[y * width + x], bits);
|
||||
w.Align();
|
||||
}
|
||||
return w.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Sony ARW2 (cRAW): 16-pixel blocks of one colour in 32-column groups, values through the inverse tone curve.</summary>
|
||||
public static byte[] Arw(SensorData s, ushort[] knots, bool compressed, int orientation = 1)
|
||||
{
|
||||
byte[] data;
|
||||
uint compression = 32767;
|
||||
if (compressed)
|
||||
{
|
||||
var curve = ToneCurve(knots);
|
||||
var even = new ushort[2048];
|
||||
for (var i = 0; i < even.Length; i++) even[i] = curve[i << 1];
|
||||
var codes = Indices(s.Samples, even);
|
||||
data = new byte[s.Width * s.Height];
|
||||
for (var y = 0; y < s.Height; y++)
|
||||
{
|
||||
for (var group = 0; group < s.Width; group += 32)
|
||||
{
|
||||
for (var parity = 0; parity < 2; parity++)
|
||||
{
|
||||
var block = data.AsSpan(y * s.Width + group + parity * 16, 16);
|
||||
var pix = new int[16];
|
||||
for (var i = 0; i < 16; i++) pix[i] = codes[y * s.Width + group + parity + 2 * i];
|
||||
EncodeBlock(pix, block);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
data = new byte[s.Samples.Length * 2];
|
||||
for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(2 * i), s.Samples[i]);
|
||||
}
|
||||
var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0)
|
||||
.Long(TiffTags.ImageWidth, (uint)s.Width).Long(TiffTags.ImageLength, (uint)s.Height)
|
||||
.Short(TiffTags.BitsPerSample, (ushort)(compressed ? 8 : 14)).Short(TiffTags.Compression, (ushort)compression)
|
||||
.Short(TiffTags.PhotometricInterpretation, 32803)
|
||||
.Short(TiffTags.CfaRepeatPatternDim, 2, 2).Bytes(TiffTags.CfaPattern, 0, 1, 1, 2)
|
||||
.Short(0x7010, knots).Short(0x7310, 512, 512, 512, 512)
|
||||
.Strip(data);
|
||||
var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "SONY").Ascii(TiffTags.Model, "ILCE-7M3").Short(TiffTags.Orientation, (ushort)orientation)
|
||||
.Long(TiffTags.NewSubfileType, 1).Child(TiffTags.SubIfds, raw);
|
||||
return TiffFile.Build(ifd0);
|
||||
}
|
||||
|
||||
/// <summary>The reader's tone curve (slopes 1, 2, 4, 8, 16 between the knots).</summary>
|
||||
public static ushort[] ToneCurve(ushort[] knots)
|
||||
{
|
||||
int[] k = [0, knots[0] >> 2 & 0xFFF, knots[1] >> 2 & 0xFFF, knots[2] >> 2 & 0xFFF, knots[3] >> 2 & 0xFFF, 4095];
|
||||
var curve = new ushort[4096];
|
||||
for (var i = 0; i < curve.Length; i++) curve[i] = (ushort)i;
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
for (var j = k[i] + 1; j <= k[i + 1]; j++) curve[j] = (ushort)(curve[j - 1] + (1 << i));
|
||||
}
|
||||
return curve;
|
||||
}
|
||||
|
||||
private static void EncodeBlock(int[] pix, Span<byte> block)
|
||||
{
|
||||
int imax = 0, imin = 0;
|
||||
for (var i = 1; i < 16; i++)
|
||||
{
|
||||
if (pix[i] > pix[imax]) imax = i;
|
||||
if (pix[i] < pix[imin]) imin = i;
|
||||
}
|
||||
if (imax == imin) imin = imax == 0 ? 1 : 0;
|
||||
int max = pix[imax], min = pix[imin];
|
||||
var sh = 0;
|
||||
while (sh < 4 && 0x80 << sh <= max - min) sh++;
|
||||
var bits = new System.Collections.BitArray(130);
|
||||
void Put(int value, int at, int count)
|
||||
{
|
||||
for (var b = 0; b < count; b++) bits[at + b] = (value >> b & 1) != 0;
|
||||
}
|
||||
Put(max, 0, 11);
|
||||
Put(min, 11, 11);
|
||||
Put(imax, 22, 4);
|
||||
Put(imin, 26, 4);
|
||||
var bit = 30;
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
if (i == imax || i == imin) continue;
|
||||
Put(int.Min((pix[i] - min) >> sh, 0x7F), bit, 7);
|
||||
bit += 7;
|
||||
}
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
byte v = 0;
|
||||
for (var b = 0; b < 8; b++) v |= (byte)(bits[i * 8 + b] ? 1 << b : 0);
|
||||
block[i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pentax PEF: big-endian, raw in IFD0, AOC MakerNote with black, WB and the Huffman table.</summary>
|
||||
public static byte[] Pef(SensorData s, int bits, bool compressed, int orientation = 1)
|
||||
{
|
||||
// Prefix code over difference lengths 0..14 (Kraft sum below 1).
|
||||
int[] lengths = [3, 3, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 10];
|
||||
var codes = new Dictionary<int, (int Code, int Length)>();
|
||||
var code = 0;
|
||||
var previous = lengths[0];
|
||||
for (var c = 0; c < lengths.Length; c++)
|
||||
{
|
||||
code <<= lengths[c] - previous;
|
||||
previous = lengths[c];
|
||||
codes[c] = (code, lengths[c]);
|
||||
code++;
|
||||
}
|
||||
var table = new List<byte> { 0, (byte)((lengths.Length - 12) & 15) };
|
||||
table.AddRange(new byte[12]);
|
||||
for (var c = 0; c < lengths.Length; c++)
|
||||
{
|
||||
var aligned = codes[c].Code << (12 - codes[c].Length);
|
||||
table.AddRange([(byte)(aligned >> 8), (byte)aligned]);
|
||||
}
|
||||
foreach (var len in lengths) table.Add((byte)len);
|
||||
var data = compressed ? PredictiveHuffman(s.Samples, s.Width, s.Height, _ => codes, [0, 0, 0, 0]) : Packed(s.Samples, s.Width, s.Height, bits);
|
||||
var levels = new ushort[] { (ushort)double.Round(1000 * s.Neutral.Y / s.Neutral.X), 1000, 1000, (ushort)double.Round(1000 * s.Neutral.Y / s.Neutral.Z) };
|
||||
var pentax = new IfdSpec().Short(0x0200, 512, 512, 512, 512).Short(0x0201, levels).Undefined(0x0220, [.. table]);
|
||||
var exif = new IfdSpec().Embedded(TiffTags.MakerNote, [.. "AOC\0MM"u8], pentax, relativeToTiff: true, littleEndian: false);
|
||||
var ifd0 = new IfdSpec().Ascii(TiffTags.Make, "RICOH IMAGING COMPANY, LTD.").Ascii(TiffTags.Model, "PENTAX K-1")
|
||||
.Short(TiffTags.Orientation, (ushort)orientation).Long(TiffTags.NewSubfileType, 0)
|
||||
.Long(TiffTags.ImageWidth, (uint)s.Width).Long(TiffTags.ImageLength, (uint)s.Height)
|
||||
.Short(TiffTags.BitsPerSample, (ushort)bits).Short(TiffTags.Compression, (ushort)(compressed ? 65535 : 1))
|
||||
.Short(TiffTags.PhotometricInterpretation, 32803)
|
||||
.Short(TiffTags.CfaRepeatPatternDim, 2, 2).Bytes(TiffTags.CfaPattern, 2, 1, 1, 0)
|
||||
.Strip(data).Child(TiffTags.ExifIfd, exif);
|
||||
return TiffFile.Build(ifd0, littleEndian: false);
|
||||
}
|
||||
|
||||
/// <summary>Fujifilm RAF: header, JPEG with Exif, RAF directory (crop, layout, WB), FujiIFD block with 16-bit data.</summary>
|
||||
public static byte[] Raf(SensorData s, CfaPattern rasterCfa, RawRect crop, int orientation = 1, string model = "X-T2")
|
||||
{
|
||||
var jpeg = Preview("FUJIFILM", model, orientation);
|
||||
var pattern = new byte[36];
|
||||
for (var i = 0; i < 36; i++) pattern[35 - i] = (byte)rasterCfa.ColorAt(i % 6, i / 6);
|
||||
var records = new List<byte>();
|
||||
void Record(ushort tag, byte[] payload) => records.AddRange([.. Box.U16(tag), .. Box.U16((ushort)payload.Length), .. payload]);
|
||||
Record(0x0100, [.. Box.U16((ushort)s.Height), .. Box.U16((ushort)s.Width)]);
|
||||
Record(0x0110, [.. Box.U16((ushort)crop.Top), .. Box.U16((ushort)crop.Left)]);
|
||||
Record(0x0111, [.. Box.U16((ushort)crop.Height), .. Box.U16((ushort)crop.Width)]);
|
||||
Record(0x0130, [0, 8, 0, 0]);
|
||||
Record(0x0131, pattern);
|
||||
Record(0x2FF0, [.. Box.U16(302), .. Box.U16((ushort)double.Round(302 * s.Neutral.Y / s.Neutral.X)), .. Box.U16(302), .. Box.U16((ushort)double.Round(302 * s.Neutral.Y / s.Neutral.Z))]);
|
||||
byte[] directory = [.. Box.U32(6), .. records];
|
||||
var data = new byte[s.Samples.Length * 2];
|
||||
for (var i = 0; i < s.Samples.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(2 * i), s.Samples[i]);
|
||||
var fuji = new IfdSpec().Long(0xF001, (uint)s.Width).Long(0xF002, (uint)s.Height).Long(0xF003, 14)
|
||||
.Long(0xF00A, [.. Enumerable.Repeat(1024u, 36)]).Blob(0xF007, 0xF008, data);
|
||||
var block = TiffFile.Build(new IfdSpec().Child(0xF000, fuji), littleEndian: false);
|
||||
var jpegOffset = 0x6C;
|
||||
var directoryOffset = jpegOffset + jpeg.Length;
|
||||
var blockOffset = directoryOffset + directory.Length;
|
||||
var header = new byte[0x6C];
|
||||
"FUJIFILMCCD-RAW 0201FF129502"u8.CopyTo(header);
|
||||
System.Text.Encoding.ASCII.GetBytes(model).CopyTo(header.AsSpan(0x1C));
|
||||
uint[] fields = [(uint)jpegOffset, (uint)jpeg.Length, (uint)directoryOffset, (uint)directory.Length, (uint)blockOffset, (uint)block.Length];
|
||||
for (var i = 0; i < fields.Length; i++) BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(0x54 + 4 * i), fields[i]);
|
||||
return [.. header, .. jpeg, .. directory, .. block];
|
||||
}
|
||||
|
||||
/// <summary>MSB-first bit writer.</summary>
|
||||
internal sealed class BitWriter
|
||||
{
|
||||
private readonly List<byte> _bytes = [];
|
||||
private int _accumulator;
|
||||
private int _count;
|
||||
|
||||
public void Write(int value, int bits)
|
||||
{
|
||||
for (var b = bits - 1; b >= 0; b--)
|
||||
{
|
||||
_accumulator = _accumulator << 1 | (value >> b & 1);
|
||||
if (++_count == 8)
|
||||
{
|
||||
_bytes.Add((byte)_accumulator);
|
||||
_accumulator = _count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Align()
|
||||
{
|
||||
if (_count > 0) Write(0, 8 - _count);
|
||||
}
|
||||
|
||||
public byte[] ToArray()
|
||||
{
|
||||
Align();
|
||||
return [.. _bytes, 0, 0, 0, 0];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Testing;
|
||||
using static Titano.Core.Tests.Raw.NativeRawWriters;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>Truncated and corrupted RAW files may only raise <see cref="InvalidDataException"/> (or decode).</summary>
|
||||
public sealed class RawFuzzTests(TestContext context)
|
||||
{
|
||||
private const int W = 48, H = 32;
|
||||
|
||||
private static byte[] Sample(string format)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
return format switch
|
||||
{
|
||||
"dng" => SyntheticDng.Write(scene, new DngSpec { TileSize = 16, OpcodeList2 = GainMapList(), OpcodeList3 = new OpcodeListBuilder().Add(3, 0, p => p.F64(0.1).F64(0).F64(0).F64(0).F64(0).F64(0.5).F64(0.5)).Build() }),
|
||||
"linear.dng" => SyntheticDng.Write(scene, new DngSpec { Cfa = null, Compression = 8 }),
|
||||
"cr2" => Cr2(Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 80, 36, 24, 4, 2048, 16383), new RawRect(24, 4, 24 + W, 4 + H)),
|
||||
"nef" => Nef(Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600, 16383), 14, NefEncoding.Lossless),
|
||||
"arw" => Arw(Sensor(scene, "Sony ILCE-7M3", CfaPattern.Bayer("RGGB"), 64, H, 0, 0, 512, 16000), [8000, 10400, 12900, 14100], compressed: true),
|
||||
"pef" => Pef(Sensor(scene, "Pentax K-1", CfaPattern.Bayer("BGGR"), W, H, 0, 0, 512, 16383), 14, compressed: true),
|
||||
_ => Raf(Sensor(scene, "Fujifilm X-T2", DemosaicTests.XTrans, W + 6, H + 6, 3, 3, 1024, 16383), DemosaicTests.XTrans, new RawRect(3, 3, 3 + W, 3 + H)),
|
||||
};
|
||||
}
|
||||
|
||||
private static byte[] GainMapList() => new OpcodeListBuilder().Add(9, 0, p =>
|
||||
{
|
||||
OpcodeListBuilder.Area(p, 0, 0, H, W);
|
||||
p.U32(2).U32(2).F64(1).F64(1).F64(0).F64(0).U32(1).F32(1).F32(1.1f).F32(1.2f).F32(1.3f);
|
||||
}).Build();
|
||||
|
||||
[Theory]
|
||||
[Case("dng")]
|
||||
[Case("linear.dng")]
|
||||
[Case("cr2")]
|
||||
[Case("nef")]
|
||||
[Case("arw")]
|
||||
[Case("pef")]
|
||||
[Case("raf")]
|
||||
public void TruncatedAndCorruptedFilesOnlyRaiseInvalidData(string format)
|
||||
{
|
||||
var file = Sample(format);
|
||||
var name = "fuzz." + format.Split('.').Last();
|
||||
var options = new RawDecodeOptions { Quality = DemosaicQuality.Draft, MaxDegreeOfParallelism = 1 };
|
||||
using (var clean = RawDecoder.Decode(new MemoryStream(file), name, options)) Assert.Equal(format == "arw" ? 64 : W, clean.Image.Width);
|
||||
var random = new Random(format.Length * 7919);
|
||||
var outcomes = new Dictionary<string, int>();
|
||||
for (var i = 0; i < 120; i++)
|
||||
{
|
||||
byte[] variant;
|
||||
if (i < 40)
|
||||
{
|
||||
variant = file[..(int)((long)file.Length * i / 40)];
|
||||
}
|
||||
else
|
||||
{
|
||||
variant = (byte[])file.Clone();
|
||||
var flips = 1 + random.Next(4);
|
||||
for (var k = 0; k < flips; k++)
|
||||
{
|
||||
// Bias corruption toward the headers, where structure lives.
|
||||
var at = random.Next(2) == 0 ? random.Next(int.Min(variant.Length, 512)) : random.Next(variant.Length);
|
||||
variant[at] = (byte)random.Next(256);
|
||||
}
|
||||
}
|
||||
var outcome = Run(variant, name, options);
|
||||
outcomes[outcome] = outcomes.GetValueOrDefault(outcome) + 1;
|
||||
}
|
||||
context.Log($"{format}: " + string.Join(", ", outcomes.Select(o => $"{o.Key} {o.Value}")));
|
||||
}
|
||||
|
||||
private static string Run(byte[] data, string name, RawDecodeOptions options)
|
||||
{
|
||||
try
|
||||
{
|
||||
RawDecoder.Probe(new MemoryStream(data), name);
|
||||
using var result = RawDecoder.Decode(new MemoryStream(data), name, options);
|
||||
return "decoded";
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return "invalid";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Assert.Fail($"{ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user