merge: RAW/DNG decoding, managed decoder provider, frame window and thumbnails

# Conflicts:
#	src/Titano.Tools/Program.cs
This commit is contained in:
Claude committed 2026-10-02 12:32:14 +00:00
commit 9ee2d482b6
40 files changed
+8350

No files matched your search

@@ -0,0 +1,84 @@
using System.Text.Json;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Metadata;
using Titano.Testing;
namespace Titano.Core.Tests.Decoding;
/// <summary>Real camera files from tests/fixtures/manifest.json (fetched by <c>Titano.Tools fixtures</c>); each test is
/// skipped when its file is absent. A native decode must reach the expected size and look like the camera's own
/// embedded preview (luminance correlation), which catches wrong byte orders, CFA phases or colour matrices.</summary>
public sealed class ExternalFixtureTests(TestContext context)
{
private const int Edge = 256;
private static JsonElement Entry(string name)
{
var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(TestContext.FixturesDirectory, "manifest.json")));
foreach (var f in manifest.RootElement.GetProperty("files").EnumerateArray())
{
if (f.GetProperty("name").GetString() == name) return f.Clone();
}
throw new InvalidOperationException("No manifest entry " + name);
}
[Theory]
[Case("google-pixel-4a.dng")]
[Case("canon-eos-5d-mark-iii.cr2")]
[Case("nikon-d850.nef")]
[Case("sony-ilce-7m3.arw")]
[Case("fujifilm-x-t2.raf")]
[Case("pentax-k-1.pef")]
[Timeout(20_000)]
public void DecodesNativelyAndMatchesThePreview(string name)
{
var path = Path.Combine(TestContext.FixturesDirectory, "external", name);
if (!File.Exists(path)) TestContext.Skip($"{name} not fetched (run Titano.Tools fixtures)");
var entry = Entry(name);
var metadata = MetadataReader.Read(path);
Assert.Equal(entry.GetProperty("format").GetString(), metadata.Format.ToString());
var probe = new ManagedDecoderProvider().Probe(path);
context.Log($"{name}: {probe}; {metadata.Make} {metadata.Model}, {metadata.Width}x{metadata.Height}, orientation {metadata.Orientation}");
Assert.Equal(DecodeTier.Native, probe.Tier);
var decoder = DecoderFactory.CreateServer();
using var native = decoder.Decode(new DecodeRequest(path, Edge, DecodePurpose.Render, ApplyOrientation: false));
Assert.Equal(DecodeTier.Native, native!.Tier);
var (w, h) = (entry.GetProperty("width").GetInt32(), entry.GetProperty("height").GetInt32());
Assert.InRange(native.SourceWidth, w * 0.98, w * 1.02);
Assert.InRange(native.SourceHeight, h * 0.98, h * 1.02);
foreach (var v in native.Pixels.Data)
{
if (!float.IsFinite(v)) Assert.Fail("non-finite pixel");
}
using var preview = decoder.Decode(new DecodeRequest(path, Edge, DecodePurpose.Render, ApplyOrientation: false, ForcePreview: true));
if (preview is null || preview.Tier != DecodeTier.EmbeddedPreview) TestContext.Skip("no embedded preview to compare with");
var correlation = Correlation(native.Pixels, preview.Pixels);
context.Log($"luminance correlation with the embedded preview: {correlation:F3}");
Assert.Greater(correlation, 0.8);
}
/// <summary>Pearson correlation of sRGB-encoded luminance after resizing both to a common 64-pixel-wide grid.</summary>
private static double Correlation(ImageBuffer a, ImageBuffer b)
{
var height = int.Max(1, (int)double.Round(64.0 * a.Height / a.Width));
using var ra = Resampler.Resize(a, 64, height, ResampleFilter.Box);
using var rb = Resampler.Resize(b, 64, height, ResampleFilter.Box);
var n = ra.PlaneLength;
double sa = 0, sb = 0, saa = 0, sbb = 0, sab = 0;
for (var i = 0; i < n; i++)
{
double la = ColorSpace.EncodeFast(ColorSpace.Luminance(ra.Plane(0)[i], ra.Plane(1)[i], ra.Plane(2)[i]));
double lb = ColorSpace.EncodeFast(ColorSpace.Luminance(rb.Plane(0)[i], rb.Plane(1)[i], rb.Plane(2)[i]));
sa += la;
sb += lb;
saa += la * la;
sbb += lb * lb;
sab += la * lb;
}
var cov = sab / n - sa / n * (sb / n);
return cov / double.Sqrt(double.Max(saa / n - sa / n * (sa / n), 1e-12) * double.Max(sbb / n - sb / n * (sb / n), 1e-12));
}
}
@@ -0,0 +1,197 @@
using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Decoding;
/// <summary><see cref="FrameWindow"/>: memory bound independent of sequence length, spill round trip, read-ahead,
/// cancellation and deterministic disposal (BRIEF §8.4, §20.4 memory and cancellation gates).</summary>
public sealed class FrameWindowTests(TestContext context)
{
private const int Size = 64;
private const long FrameBytes = Size * Size * 3 * sizeof(float);
/// <summary>Synthetic loader whose frames encode their index; records every buffer it hands out.</summary>
private sealed class Source
{
private readonly List<ImageBuffer> _made = [];
public int Loads;
public TimeSpan Delay;
public async ValueTask<ImageBuffer> Load(int index, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Loads);
if (Delay > TimeSpan.Zero) await Task.Delay(Delay, cancellationToken);
var image = new ImageBuffer(Size, Size, 3, clear: false);
image.Data.Fill(index);
image[1, 5, 7] = index + 0.25f;
lock (_made) _made.Add(image);
return image;
}
/// <summary>Loader-made buffers not yet disposed (independent of the window's own counters).</summary>
public int Live()
{
lock (_made)
{
var live = 0;
foreach (var b in _made)
{
try
{
_ = b.Storage;
live++;
}
catch (ObjectDisposedException)
{
}
}
return live;
}
}
}
private static void AssertFrame(FrameLease lease)
{
Assert.Equal((float)lease.Index, lease.Image[0, 10, 10]);
Assert.Equal(lease.Index + 0.25f, lease.Image[1, 5, 7]);
}
/// <summary>Render loop: each step moves the window and reads the frame plus its three predecessors — four frames
/// needed per step against a three-frame budget, so in-window frames must be spilled and read back.</summary>
private async Task<(FrameWindowStatistics Stats, int PeakLive, string? Spill)> Render(int frames, string spillDirectory)
{
var source = new Source();
var options = new FrameWindowOptions { Behind = 3, Ahead = 4, MemoryBudget = 3 * FrameBytes, SpillDirectory = spillDirectory };
var peakLive = 0;
FrameWindowStatistics stats;
string? spill;
await using (var window = new FrameWindow(frames, source.Load, options))
{
for (var i = 0; i < frames; i++)
{
window.MoveTo(i);
using (var current = await window.GetAsync(i)) AssertFrame(current);
for (var back = 1; back <= 3 && i - back >= 0; back++)
{
using var previous = await window.GetAsync(i - back);
AssertFrame(previous);
}
peakLive = int.Max(peakLive, source.Live());
Assert.LessOrEqual(window.Statistics.LiveBytes, options.MemoryBudget);
}
stats = window.Statistics;
spill = window.SpillPath;
Assert.FileExists(spill!);
}
Assert.Equal(0, source.Live());
return (stats, peakLive, spill);
}
[Test]
[Timeout(30_000)]
public async Task PeakMemoryIsBoundedAndIndependentOfSequenceLength()
{
var dir = context.CreateTempDirectory();
var shortRun = await Render(40, dir);
var longRun = await Render(400, dir);
context.Log($"40 frames: {shortRun.Stats}, peak live {shortRun.PeakLive}; 400 frames: {longRun.Stats}, peak live {longRun.PeakLive}");
foreach (var run in new[] { shortRun, longRun })
{
Assert.LessOrEqual(run.Stats.PeakLiveBytes, 3 * FrameBytes);
Assert.LessOrEqual(run.PeakLive, 3);
Assert.Greater(run.Stats.SpillWrites, 0);
Assert.Greater(run.Stats.SpillReads, 0);
// Spill extents are reused: only frames inside the window (3 behind + current + 4 ahead) are ever on disk.
Assert.LessOrEqual(run.Stats.SpillFileBytes, 8 * FrameBytes);
Assert.FileMissing(run.Spill!);
}
Assert.Equal(shortRun.Stats.PeakLiveBytes, longRun.Stats.PeakLiveBytes);
Assert.Equal(shortRun.PeakLive, longRun.PeakLive);
Assert.LessOrEqual(longRun.Stats.SpillFileBytes, shortRun.Stats.SpillFileBytes);
}
[Test]
[Timeout(10_000)]
public async Task ReadAheadDecodesInTheBackground()
{
var source = new Source();
await using var window = new FrameWindow(100, source.Load, new FrameWindowOptions { Ahead = 3, MemoryBudget = 10 * FrameBytes });
window.MoveTo(0);
using (var first = await window.GetAsync(0)) AssertFrame(first);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (source.Loads < 4 && DateTime.UtcNow < deadline) await Task.Delay(5);
Assert.Equal(4, source.Loads);
using var ahead = await window.GetAsync(3);
AssertFrame(ahead);
Assert.Equal(4, source.Loads);
}
[Test]
[Timeout(10_000)]
public async Task CancellationLeavesNoSpillFileAndNoUnobservedErrors()
{
var unobserved = 0;
void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
TaskScheduler.UnobservedTaskException += OnUnobserved;
try
{
var dir = context.CreateTempDirectory();
var source = new Source();
string? spill;
using var cts = new CancellationTokenSource();
var window = new FrameWindow(50, source.Load, new FrameWindowOptions { Behind = 3, Ahead = 2, MemoryBudget = 2 * FrameBytes, SpillDirectory = dir });
try
{
for (var i = 0; i < 6; i++)
{
window.MoveTo(i);
using var a = await window.GetAsync(i);
if (i > 0)
{
using var b = await window.GetAsync(i - 1);
}
}
spill = window.SpillPath;
Assert.NotNull(spill);
Assert.FileExists(spill!);
source.Delay = TimeSpan.FromSeconds(30);
window.MoveTo(20);
var pending = window.GetAsync(20, cts.Token);
cts.CancelAfter(50);
await Assert.ThrowsAsync<OperationCanceledException>(async () => await pending);
}
finally
{
await window.DisposeAsync();
}
Assert.FileMissing(spill!);
Assert.Equal(0, source.Live());
await Assert.ThrowsAsync<OperationCanceledException>(async () => await window.GetAsync(1));
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
TaskScheduler.UnobservedTaskException -= OnUnobserved;
}
Assert.Equal(0, unobserved);
}
[Test]
public async Task LoaderFailuresSurfaceAndCanBeRetried()
{
var attempts = 0;
async ValueTask<ImageBuffer> Flaky(int index, CancellationToken ct)
{
await Task.Yield();
if (index == 2 && Interlocked.Increment(ref attempts) == 1) throw new InvalidDataException("bad frame");
var image = new ImageBuffer(8, 8, 3);
image.Data.Fill(index);
return image;
}
await using var window = new FrameWindow(5, Flaky, new FrameWindowOptions { Ahead = 0 });
await Assert.ThrowsAsync<InvalidDataException>(async () => await window.GetAsync(2));
using var retried = await window.GetAsync(2);
Assert.Equal(2f, retried.Image[0, 0, 0]);
}
}
@@ -0,0 +1,217 @@
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Png;
using Titano.Core.Codecs.Raw;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Metadata;
using Titano.Core.Tests.Raw;
using Titano.Testing;
using static Titano.Core.Tests.Raw.NativeRawWriters;
namespace Titano.Core.Tests.Decoding;
/// <summary>Tier selection (native → embedded preview → unavailable), decoder chains and <see cref="DecodeRequest"/> fast paths.</summary>
public sealed class ManagedDecoderProviderTests(TestContext context)
{
private const int W = 96, H = 64;
private readonly string _dir = context.CreateTempDirectory();
private string Write(string name, byte[] data)
{
var path = Path.Combine(_dir, name);
File.WriteAllBytes(path, data);
return path;
}
private static byte[] Cr2File(string model, int orientation = 1)
{
using var scene = SyntheticRaw.Smooth(W, H);
var active = new RawRect(24, 4, 24 + W, 4 + H);
return Cr2(Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, active.Left, active.Top, 2048, 16383), active, orientation, model);
}
private static byte[] JpegFile(int width, int height, int orientation)
{
using var image = SyntheticRaw.Smooth(width, height);
var exif = ExifWriter.BuildTiff(new FrameMetadata { Make = "TestCam", Model = "T1", Orientation = orientation });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [[.. "Exif\0\0"u8, .. exif]] });
}
[Test]
public void ServerFormatTableReportsTiers()
{
var rows = DecoderFactory.DescribeFormats(DecoderFactory.CreateServer()).ToDictionary(r => r.Format.Format);
foreach (var f in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff, ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Arw, ImageFileFormat.Pef, ImageFileFormat.Raf })
{
Assert.Equal(DecodeTier.Native, rows[f].Tier);
Assert.Equal("managed", rows[f].Provider);
}
foreach (var f in new[] { ImageFileFormat.Cr3, ImageFileFormat.Orf, ImageFileFormat.Rw2, ImageFileFormat.Heif }) Assert.Equal(DecodeTier.EmbeddedPreview, rows[f].Tier);
foreach (var f in new[] { ImageFileFormat.WebP, ImageFileFormat.JpegXl, ImageFileFormat.Gif })
{
Assert.Equal(DecodeTier.Unavailable, rows[f].Tier);
Assert.Null(rows[f].Provider);
}
}
[Test]
public void ClientChainPrefersTheWindowsProvider()
{
var wic = new FakeProvider();
var decoder = DecoderFactory.CreateClient(wic);
Assert.Equal(2, decoder.Providers.Count);
var rows = DecoderFactory.DescribeFormats(decoder).ToDictionary(r => r.Format.Format);
Assert.Equal("fake", rows[ImageFileFormat.Cr3].Provider);
Assert.Equal(DecodeTier.Native, rows[ImageFileFormat.Cr3].Tier);
Assert.Equal("fake", rows[ImageFileFormat.Jpeg].Provider);
Assert.Equal("managed", rows[ImageFileFormat.Dng].Provider);
// The Windows provider declines this file: the managed provider decodes it.
var path = Write("a.jpg", JpegFile(64, 48, 1));
using var image = decoder.Decode(new DecodeRequest(path));
Assert.Equal(1, wic.Calls);
Assert.Equal("managed-jpeg", image!.Decoder);
Assert.Count(1, DecoderFactory.CreateClient(null).Providers);
}
[Test]
public void SupportedRawDecodesNatively()
{
var path = Write("IMG_1.CR2", Cr2File("Canon EOS 5D Mark III"));
var provider = new ManagedDecoderProvider();
Assert.Equal(DecodeTier.Native, provider.Probe(path).Tier);
using var image = DecoderFactory.CreateServer().Decode(new DecodeRequest(path));
Assert.Equal(DecodeTier.Native, image!.Tier);
Assert.Equal("managed-cr2", image.Decoder);
Assert.Equal(W, image.Pixels.Width);
Assert.Equal(W, image.SourceWidth);
}
[Test]
public void UnsupportedBodyFallsBackToTheOrientedPreview()
{
var path = Write("IMG_2.CR2", Cr2File("Canon EOS R99", orientation: 6));
var probe = new ManagedDecoderProvider().Probe(path);
Assert.Equal(DecodeTier.EmbeddedPreview, probe.Tier);
Assert.Contains("no colour matrix", probe.Reason);
using var image = DecoderFactory.CreateServer().Decode(new DecodeRequest(path));
Assert.Equal(DecodeTier.EmbeddedPreview, image!.Tier);
Assert.Equal("managed-preview", image.Decoder);
// The 64×48 preview is rotated by the RAW's orientation (6).
Assert.Equal(48, image.Pixels.Width);
Assert.Equal(64, image.Pixels.Height);
Assert.Equal(48, image.SourceWidth);
Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(path, AllowPreview: false)));
}
[Test]
public void ForcePreviewSkipsNativeDevelopment()
{
var path = Write("IMG_3.CR2", Cr2File("Canon EOS 5D Mark III"));
using var image = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, ForcePreview: true));
Assert.Equal(DecodeTier.EmbeddedPreview, image!.Tier);
Assert.Equal(64, image.Pixels.Width);
}
[Test]
public void FilesWithoutDecoderOrPreviewAreUnavailable()
{
// A NEF whose body has no matrix and no preview, and a WebP.
using var scene = SyntheticRaw.Smooth(W, H);
var nef = Nef(Sensor(scene, "Nikon D850", CfaPattern.Bayer("RGGB"), W, H, 0, 0, 600, 16383), 14, NefEncoding.Lossless);
var text = System.Text.Encoding.Latin1.GetString(nef).Replace("NIKON D850", "NIKON Z99X");
var path = Write("DSC_9.NEF", System.Text.Encoding.Latin1.GetBytes(text));
Assert.Equal(DecodeTier.Unavailable, new ManagedDecoderProvider().Probe(path).Tier);
Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(path)));
var webp = Write("x.webp", Metadata.Builders.Fixtures.WebP());
Assert.Null(DecoderFactory.CreateServer().Decode(new DecodeRequest(webp)));
Assert.Equal(DecodeTier.Unavailable, new ManagedDecoderProvider().Probe(webp).Tier);
}
[Test]
public void JpegUsesDctScalingAndOrientation()
{
var path = Write("big.jpg", JpegFile(1600, 1200, 6));
using var small = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, MaxLongEdge: 300));
Assert.Equal(225, small!.Pixels.Width);
Assert.Equal(300, small.Pixels.Height);
Assert.Equal(1200, small.SourceWidth);
Assert.Equal(1600, small.SourceHeight);
using var stored = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, MaxLongEdge: 300, ApplyOrientation: false));
Assert.Equal(300, stored!.Pixels.Width);
Assert.Equal(3, stored.Pixels.Channels);
}
[Test]
public void RawFastPathsBinAndFit()
{
using var scene = SyntheticRaw.Smooth(W, H);
var path = Write("f.dng", SyntheticDng.Write(scene, new DngSpec()));
using var thumb = DecoderFactory.CreateServer().Decode(new DecodeRequest(path, MaxLongEdge: 40, Purpose: DecodePurpose.Thumbnail));
Assert.Equal(40, thumb!.Pixels.Width);
Assert.Equal(27, thumb.Pixels.Height);
Assert.Equal(W, thumb.SourceWidth);
using var expected = Resampler.Resize(scene, 40, 27, ResampleFilter.Box);
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, thumb.Pixels, 1), 35);
}
[Test]
public void PngAndTiffDecodeToRgb()
{
using var gray = new ImageBuffer(20, 10, 1);
gray.Plane(0).Fill(0.25f);
var png = Write("g.png", PngEncoder.Encode(gray));
using var p = DecoderFactory.CreateServer().Decode(new DecodeRequest(png));
Assert.Equal(3, p!.Pixels.Channels);
Assert.Approximately(0.25, p.Pixels[2, 5, 5], 0.01);
var tif = Write("g.tif", TiffWriter.Write(gray));
using var t = DecoderFactory.CreateServer().Decode(new DecodeRequest(tif, MaxLongEdge: 10));
Assert.Equal(3, t!.Pixels.Channels);
Assert.Equal(10, t.Pixels.Width);
Assert.Equal("managed-tiff", t.Decoder);
}
[Test]
public void CorruptedRawFilesOnlyRaiseInvalidDataOrReturnNull()
{
var file = Cr2File("Canon EOS 5D Mark III");
var provider = new ManagedDecoderProvider();
var random = new Random(17);
for (var i = 0; i < 60; i++)
{
var variant = i < 20 ? file[..(file.Length * i / 20)] : (byte[])file.Clone();
if (i >= 20)
{
for (var k = 0; k < 3; k++) variant[random.Next(variant.Length)] = (byte)random.Next(256);
}
var path = Write($"fuzz{i}.cr2", variant);
try
{
provider.Probe(path);
using var image = provider.Decode(new DecodeRequest(path, MaxLongEdge: i % 2 == 0 ? 0 : 32, Purpose: DecodePurpose.Thumbnail));
}
catch (InvalidDataException)
{
}
catch (Exception ex)
{
Assert.Fail($"variant {i}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
}
/// <summary>A Windows-like provider claiming native support for everything but declining every file.</summary>
private sealed class FakeProvider : IImageDecoderProvider
{
public int Calls { get; private set; }
public string Name => "fake";
public DecodeTier? TierFor(ImageFileFormat format) => format is ImageFileFormat.Jpeg or ImageFileFormat.Cr3 ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
Calls++;
return null;
}
}
}
@@ -0,0 +1,277 @@
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Raw;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Imaging.Thumbnails;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Tests.Raw;
using Titano.Testing;
namespace Titano.Core.Tests.Decoding;
/// <summary><see cref="ThumbnailPack"/> format behaviour, <see cref="ThumbnailCache{TKey}"/> and <see cref="ProxyBuilder"/>.</summary>
public sealed class ThumbnailTests(TestContext context)
{
private readonly string _dir = context.CreateTempDirectory();
private static ImageBuffer Frame(int seed, int width = 400, int height = 300)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
image[0, x, y] = (x + seed * 13) % 97 / 96f;
image[1, x, y] = (y + seed * 7) % 89 / 88f;
image[2, x, y] = seed % 5 / 5f;
}
}
return image;
}
/// <summary>Small distinct JPEGs (cheap to make in bulk).</summary>
private static byte[] Jpeg(int seed)
{
using var image = Frame(seed, 40, 30);
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80 });
}
private static Guid Id(int i) => new(i, 0, 0, [0, 0, 0, 0, 0, 0, 0, 1]);
[Test]
public void RoundTripAppendAndReplace()
{
var path = Path.Combine(_dir, "thumbs.pack");
using (var pack = ThumbnailPack.Open(path))
{
for (var i = 0; i < 20; i++)
{
using var frame = Frame(i);
var e = pack.Add(Id(i), frame);
Assert.Equal(320, e.Width);
Assert.Equal(240, e.Height);
}
}
using (var pack = ThumbnailPack.Open(path))
{
Assert.Equal(20, pack.Count);
Assert.Empty(pack.Warnings);
for (var i = 20; i < 25; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30);
pack.AddJpeg(Id(3), Jpeg(1000), 40, 30);
}
using var reader = ThumbnailPack.Open(path, writable: false);
Assert.Equal(25, reader.Count);
Assert.BytesEqual(Jpeg(1000), reader.ReadJpeg(Id(3)));
Assert.BytesEqual(Jpeg(22), reader.ReadJpeg(Id(22)));
var thumb = Thumbnail.FromJpeg(reader.ReadJpeg(Id(7))!);
Assert.Equal(320, thumb.Width);
Assert.Null(reader.ReadJpeg(Id(99)));
Assert.Greater(reader.WastedBytes, 0);
}
[Test]
public void EntriesAfterTheLastIndexAreRecovered()
{
var path = Path.Combine(_dir, "crash.pack");
var copy = Path.Combine(_dir, "crash-copy.pack");
var count = ThumbnailPack.IndexInterval + 6;
using (var pack = ThumbnailPack.Open(path))
{
for (var i = 0; i < count; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30);
// Simulated crash: the file as it is before the closing index write.
File.Copy(path, copy);
}
using var recovered = ThumbnailPack.Open(copy, writable: false);
Assert.Equal(count, recovered.Count);
Assert.Contains(recovered.Warnings, w => w.Contains("Recovered 6"));
Assert.BytesEqual(Jpeg(count - 1), recovered.ReadJpeg(Id(count - 1)));
}
[Test]
public void TruncatedAndDamagedFilesOpen()
{
var path = Path.Combine(_dir, "full.pack");
using (var pack = ThumbnailPack.Open(path))
{
for (var i = 0; i < 40; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30);
}
var bytes = File.ReadAllBytes(path);
for (var cut = 0; cut <= 40; cut++)
{
var file = Path.Combine(_dir, $"cut{cut}.pack");
File.WriteAllBytes(file, bytes[..(int)((long)bytes.Length * cut / 40)]);
using var pack = ThumbnailPack.Open(file, writable: false);
foreach (var id in pack.FrameIds) Assert.NotNull(pack.ReadJpeg(id));
Assert.LessOrEqual(pack.Count, 40);
}
// A damaged newest header slot falls back to the other one (or a scan).
var damaged = (byte[])bytes.Clone();
for (var i = 0; i < 128; i++) damaged[i] ^= 0x5A;
var damagedPath = Path.Combine(_dir, "damaged.pack");
File.WriteAllBytes(damagedPath, damaged);
using (var pack = ThumbnailPack.Open(damagedPath, writable: false))
{
Assert.Equal(40, pack.Count);
Assert.Contains(pack.Warnings, w => w.Contains("No valid header"));
}
// A flipped JPEG byte is caught by its CRC on read.
var flipped = (byte[])bytes.Clone();
flipped[128 + 40] ^= 0xFF;
var flippedPath = Path.Combine(_dir, "flipped.pack");
File.WriteAllBytes(flippedPath, flipped);
using var f = ThumbnailPack.Open(flippedPath, writable: false);
Assert.Null(f.ReadJpeg(Id(0)));
Assert.NotNull(f.ReadJpeg(Id(1)));
}
[Test]
public void CompactionDropsDeadEntries()
{
var path = Path.Combine(_dir, "compact.pack");
using var pack = ThumbnailPack.Open(path);
for (var i = 0; i < 30; i++) pack.AddJpeg(Id(i), Jpeg(i), 40, 30);
for (var i = 0; i < 10; i++) pack.AddJpeg(Id(i), Jpeg(i + 500), 40, 30);
for (var i = 25; i < 30; i++) Assert.True(pack.Remove(Id(i)));
pack.Flush();
var before = new FileInfo(path).Length;
var wasted = pack.WastedBytes;
pack.Compact();
var after = new FileInfo(path).Length;
context.Log($"compaction {before} → {after} bytes (wasted {wasted})");
Assert.Less(after, before - wasted / 2);
Assert.Equal(25, pack.Count);
Assert.Null(pack.ReadJpeg(Id(27)));
Assert.BytesEqual(Jpeg(503), pack.ReadJpeg(Id(3)));
pack.AddJpeg(Id(100), Jpeg(100), 40, 30);
pack.Flush();
using var reopened = ThumbnailPack.Open(path, writable: false);
Assert.Equal(26, reopened.Count);
Assert.Empty(reopened.Warnings);
Assert.BytesEqual(Jpeg(15), reopened.ReadJpeg(Id(15)));
}
[Test]
[Timeout(20_000)]
public async Task ConcurrentReadsWhileWriting()
{
var path = Path.Combine(_dir, "concurrent.pack");
var jpegs = Enumerable.Range(0, 200).Select(Jpeg).ToArray();
using var pack = ThumbnailPack.Open(path);
for (var i = 0; i < 10; i++) pack.AddJpeg(Id(i), jpegs[i], 40, 30);
pack.Flush();
using var done = new CancellationTokenSource();
var writer = Task.Run(() =>
{
for (var i = 10; i < 200; i++) pack.AddJpeg(Id(i), jpegs[i], 40, 30);
pack.Flush();
done.Cancel();
});
var readers = Enumerable.Range(0, 4).Select(r => Task.Run(() =>
{
var random = new Random(r);
var reads = 0;
while (!done.IsCancellationRequested || reads < 50)
{
var ids = pack.FrameIds.ToArray();
var id = ids[random.Next(ids.Length)];
var data = pack.ReadJpeg(id);
Assert.NotNull(data);
Assert.BytesEqual(jpegs[id.ToByteArray()[0] | id.ToByteArray()[1] << 8], data);
reads++;
}
return reads;
})).ToArray();
var other = Task.Run(() =>
{
using var view = ThumbnailPack.Open(path, writable: false);
while (!done.IsCancellationRequested)
{
view.Refresh();
foreach (var id in view.FrameIds) Assert.NotNull(view.ReadJpeg(id));
}
});
await Task.WhenAll([writer, other, .. readers]);
Assert.Equal(200, pack.Count);
context.Log($"reads: {string.Join(", ", readers.Select(r => r.Result))}");
}
[Test]
public async Task CacheEvictsLeastRecentlyUsedAndCoalescesLoads()
{
var cache = new ThumbnailCache<int>(3 * (300 + 64));
Thumbnail T() => new(10, 10, new byte[300]);
cache.Set(1, T());
cache.Set(2, T());
cache.Set(3, T());
Assert.True(cache.TryGet(1, out _));
cache.Set(4, T());
Assert.False(cache.TryGet(2, out _));
Assert.True(cache.TryGet(1, out _));
Assert.Equal(3, cache.Count);
Assert.LessOrEqual(cache.Bytes, cache.Budget);
cache.Set(5, new Thumbnail(100, 100, new byte[30000]));
Assert.False(cache.TryGet(5, out _));
var loads = 0;
var gate = new TaskCompletionSource();
async Task<Thumbnail?> Loader(int key, CancellationToken ct)
{
Interlocked.Increment(ref loads);
await gate.Task;
return Thumbnail.FromJpeg(Jpeg(key));
}
var large = new ThumbnailCache<int>(1 << 20);
var requests = Enumerable.Range(0, 10).Select(_ => large.GetOrLoadAsync(42, Loader)).ToArray();
gate.SetResult();
var results = await Task.WhenAll(requests);
Assert.Equal(1, loads);
Assert.True(results.All(r => ReferenceEquals(r, results[0])));
Assert.Equal(40, results[0]!.Width);
Assert.True(large.TryGet(42, out _));
}
[Test]
public void ProxyCarriesUprightPixelsAndCaptureExif()
{
var captured = new DateTime(2025, 7, 14, 21, 3, 9, DateTimeKind.Unspecified).AddTicks(4_500_000);
var metadata = new FrameMetadata { Make = "TestCam", Model = "T1", Orientation = 6, CapturedAt = captured, UtcOffsetMinutes = 120, Iso = 800, ExposureTime = 1 / 250.0 };
using var image = Frame(1, 2000, 1500);
var exif = ExifWriter.BuildTiff(metadata);
var source = Path.Combine(_dir, "src.jpg");
File.WriteAllBytes(source, JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [[.. "Exif\0\0"u8, .. exif]] }));
var proxy = ProxyBuilder.Write(DecoderFactory.CreateServer(), source, Path.Combine(_dir, "proxy.jpg"), ProxySize.Edge1280);
Assert.NotNull(proxy);
Assert.Equal(960, proxy!.Width);
Assert.Equal(1280, proxy.Height);
Assert.Equal(DecodeTier.Native, proxy.Tier);
var back = MetadataReader.Read(Path.Combine(_dir, "proxy.jpg"));
Assert.Equal(captured, back.CapturedAt);
Assert.Equal(120, back.UtcOffsetMinutes);
Assert.Equal(TimestampSource.ExifOriginal, back.TimestampSource);
Assert.Equal(1, back.Orientation);
Assert.Equal("TestCam", back.Make);
Assert.Equal(800, back.Iso);
Assert.Equal(960, back.Width);
Assert.Equal(1280, back.Height);
var info = JpegDecoder.ReadInfo(proxy.Jpeg);
Assert.Equal(960, info.Width);
var full = ProxyBuilder.Build(DecoderFactory.CreateServer(), source, ProxySize.Full);
Assert.Equal(1500, full!.Width);
}
[Test]
public void ProxyOfAnUnsupportedRawUsesThePreviewTier()
{
using var scene = SyntheticRaw.Smooth(96, 64);
var active = new RawRect(24, 4, 120, 68);
var cr2 = NativeRawWriters.Cr2(NativeRawWriters.Sensor(scene, "Canon EOS 5D Mark III", CfaPattern.Bayer("RGGB"), 128, 72, 24, 4, 2048, 16383), active, 1, "Canon EOS R99");
var path = Path.Combine(_dir, "x.cr2");
File.WriteAllBytes(path, cr2);
var proxy = ProxyBuilder.Build(DecoderFactory.CreateServer(), path);
Assert.Equal(DecodeTier.EmbeddedPreview, proxy!.Tier);
Assert.Equal(64, proxy.Width);
}
}
@@ -0,0 +1,139 @@
using Titano.Core.Codecs.Raw;
using Titano.Core.Imaging;
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.Core.Tests.Raw;
/// <summary>Demosaic accuracy against the full-colour scene a mosaic was sampled from.</summary>
public sealed class DemosaicTests(TestContext context)
{
/// <summary>Fujifilm X-Trans layout (6×6).</summary>
internal static readonly CfaPattern XTrans = new(6, 6,
[
1, 1, 0, 1, 1, 2,
1, 1, 2, 1, 1, 0,
2, 0, 1, 0, 2, 1,
1, 1, 2, 1, 1, 0,
1, 1, 0, 1, 1, 2,
0, 2, 1, 2, 0, 1,
]);
/// <summary>Smooth colour scene modelled like a photograph: luminance texture at 10–30 px periods multiplied by a
/// slowly varying chroma field (high frequencies correlate across channels, as in natural images).</summary>
private static ImageBuffer Scene(int w, int h)
{
var image = new ImageBuffer(w, h);
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
var l = 0.3 + 0.1 * double.Sin(x * 0.31 + y * 0.12) + 0.06 * double.Sin(y * 0.45 - x * 0.2) + 0.04 * double.Cos((x - y) * 0.6);
image[0, x, y] = (float)(l * (1 + 0.35 * double.Sin(x * 0.02 + 0.5)));
image[1, x, y] = (float)(l * (1 + 0.15 * double.Cos(y * 0.03)));
image[2, x, y] = (float)(l * (1 + 0.35 * double.Cos(x * 0.015 - y * 0.02)));
}
}
return image;
}
internal static ImageBuffer Mosaic(ImageBuffer scene, CfaPattern cfa)
{
var m = new ImageBuffer(scene.Width, scene.Height, 1);
for (var y = 0; y < scene.Height; y++)
{
for (var x = 0; x < scene.Width; x++) m[0, x, y] = scene[cfa.ColorAt(x, y), x, y];
}
return m;
}
[Theory]
[Case("RGGB")]
[Case("GBRG")]
public void AhdAndBilinearMeetTheirAccuracyGates(string layout)
{
var cfa = CfaPattern.Bayer(layout);
using var scene = Scene(256, 192);
using var mosaic = Mosaic(scene, cfa);
using var ahd = AhdDemosaic.Run(mosaic, cfa, Matrix3.Rec709ToXyz, -1, default);
using var bilinear = Demosaic.Bilinear(mosaic, cfa, -1, default);
var pAhd = SyntheticRaw.Psnr(scene, ahd, 2);
var pBilinear = SyntheticRaw.Psnr(scene, bilinear, 2);
context.Log($"{layout}: AHD {pAhd:F1} dB, bilinear {pBilinear:F1} dB");
Assert.GreaterOrEqual(pAhd, 38);
Assert.GreaterOrEqual(pBilinear, 32);
Assert.Greater(pAhd, pBilinear);
}
[Test]
public void AhdDoesNotZipperAlongEdges()
{
var cfa = CfaPattern.Bayer("RGGB");
using var scene = SyntheticRaw.Edges(128, 128);
using var mosaic = Mosaic(scene, cfa);
using var ahd = AhdDemosaic.Run(mosaic, cfa, Matrix3.Rec709ToXyz, -1, default);
using var bilinear = Demosaic.Bilinear(mosaic, cfa, -1, default);
var (zipAhd, fringeAhd) = EdgeArtefacts(ahd);
var (zipBilinear, fringeBilinear) = EdgeArtefacts(bilinear);
context.Log($"zipper AHD {zipAhd:F5} bilinear {zipBilinear:F5}; fringe AHD {fringeAhd:F5} bilinear {fringeBilinear:F5}");
Assert.Less(zipAhd, 0.002);
Assert.Less(fringeAhd, 0.002);
Assert.Less(fringeAhd, fringeBilinear);
}
[Test]
public void XTransNeighbourhoodInterpolationAndBinning()
{
using var scene = Scene(240, 180);
using var mosaic = Mosaic(scene, XTrans);
Assert.Equal(3, XTrans.BinSize);
Assert.False(XTrans.IsBayer);
using var full = Demosaic.Neighbourhood(mosaic, XTrans, -1, default);
var psnr = SyntheticRaw.Psnr(scene, full, 2);
using var third = Demosaic.Bin(mosaic, XTrans, 3, -1, default);
using var expected = Resampler.Resize(scene, 80, 60, ResampleFilter.Box);
var binned = SyntheticRaw.Psnr(expected, third, 1);
context.Log($"X-Trans neighbourhood {psnr:F1} dB, binned {binned:F1} dB");
Assert.GreaterOrEqual(psnr, 34);
Assert.GreaterOrEqual(binned, 34);
}
[Test]
public void PatternReductionAndShift()
{
var bayer = new CfaPattern(4, 4, [0, 1, 0, 1, 1, 2, 1, 2, 0, 1, 0, 1, 1, 2, 1, 2]);
Assert.Equal(2, bayer.Width);
Assert.True(bayer.IsBayer);
Assert.Equal("RGGB", bayer.ToString());
Assert.Equal("GRBG", bayer.Shift(1, 0).ToString());
Assert.Equal("BGGR", bayer.Shift(-1, -1).ToString());
Assert.Throws<InvalidDataException>(() => new CfaPattern(2, 2, [0, 1, 1, 1]));
Assert.Throws<InvalidDataException>(() => new CfaPattern(2, 2, [0, 1, 3, 2]));
}
/// <summary>Zipper: second difference along each edge; fringe: chroma |R−G| + |B−G| next to the edges of a gray scene.</summary>
private static (double Zipper, double Fringe) EdgeArtefacts(ImageBuffer image)
{
double zipper = 0, fringe = 0;
var n = 0;
int w = image.Width, h = image.Height;
for (var d = -2; d <= 1; d++)
{
for (var k = 8; k < h - 8; k++)
{
if (k is > 56 and < 72) continue;
// Vertical edge at x = w/2 (columns w/2-2 .. w/2+1), and horizontal edge at y = h/2.
int vx = w / 2 + d, hy = h / 2 + d;
for (var c = 0; c < 3; c++)
{
zipper += double.Abs(image[c, vx, k] - (image[c, vx, k - 1] + image[c, vx, k + 1]) / 2);
zipper += double.Abs(image[c, k, hy] - (image[c, k - 1, hy] + image[c, k + 1, hy]) / 2);
}
fringe += double.Abs(image[0, vx, k] - image[1, vx, k]) + double.Abs(image[2, vx, k] - image[1, vx, k]);
fringe += double.Abs(image[0, k, hy] - image[1, k, hy]) + double.Abs(image[2, k, hy] - image[1, k, hy]);
n += 2;
}
}
return (zipper / (3 * n), fringe / n);
}
}
@@ -0,0 +1,277 @@
using Titano.Core.Codecs.Dng;
using Titano.Core.Codecs.Raw;
using Titano.Core.Imaging;
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.Core.Tests.Raw;
/// <summary>Synthetic DNG round trips: a known linear scene is mosaicked through a known camera model, written with the
/// DNG feature under test, decoded, and compared with the scene.</summary>
public sealed class DngDecoderTests(TestContext context)
{
private const int W = 96, H = 72;
private static RawDecodeResult Decode(byte[] dng, RawDecodeOptions? options = null) =>
RawDecoder.Decode(new MemoryStream(dng), "test.dng", options);
[Theory]
[Case("RGGB")]
[Case("BGGR")]
[Case("GRBG")]
[Case("GBRG")]
public void BayerPatternsRoundTrip(string layout)
{
using var scene = SyntheticRaw.Smooth(W, H);
var dng = SyntheticDng.Write(scene, new DngSpec { Cfa = CfaPattern.Bayer(layout) });
using var result = Decode(dng);
Assert.Equal(W, result.Image.Width);
Assert.Equal(H, result.Image.Height);
Assert.Equal(layout, result.Info.Layout);
var psnr = SyntheticRaw.Psnr(scene, result.Image, 4);
var de = SyntheticRaw.MeanDeltaE(scene, result.Image, 4);
context.Log($"{layout}: PSNR {psnr:F1} dB, mean ΔE {de:F2}");
Assert.GreaterOrEqual(psnr, 40);
Assert.Less(de, 1.0);
}
[Theory]
[Case(1, false)]
[Case(7, false)]
[Case(7, true)]
[Case(8, false)]
public void CompressionsDecodeIdentically(int compression, bool twoComponents)
{
using var scene = SyntheticRaw.Smooth(W, H);
using var reference = Decode(SyntheticDng.Write(scene, new DngSpec { Compression = 1 }));
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Compression = compression, TwoComponentTiles = twoComponents, RawInSubIfd = true }));
Assert.Empty(result.Warnings);
Assert.SequenceEqual(reference.Image.Data.ToArray(), result.Image.Data.ToArray());
}
[Test]
public void LossyJpegTilesWithLinearizationTable()
{
// Compression 34892: 8-bit JPEG tiles of sRGB-shaped codes, mapped back to linear by a 256-entry table.
var table = Enumerable.Range(0, 256).Select(i => (ushort)double.Round(ColorSpace.SrgbToLinear(i / 255.0) * 16383)).ToArray();
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null, Compression = 34892, Linearization = table, Black = [0], TileSize = 32 }));
var psnr = SyntheticRaw.Psnr(scene, result.Image, 0);
context.Log($"lossy JPEG DNG: PSNR {psnr:F1} dB");
Assert.GreaterOrEqual(psnr, 36);
}
[Theory]
[Case(false)]
[Case(true)]
public void FloatingPointPredictorWithDeflate(bool mosaic)
{
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = mosaic ? CfaPattern.Bayer("RGGB") : null, FloatingPoint = true }));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), mosaic ? 40 : 60);
}
[Test]
public void CameraCalibrationAndAnalogBalanceEnterTheColourTransform()
{
var cc = Matrix3.Diagonal(1.08, 1.0, 0.93);
var ab = new Vector3D(1.05, 1.0, 0.97);
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec
{
Cfa = null,
CameraCalibration1 = cc,
AnalogBalance = ab,
CaptureMatrix = Matrix3.Diagonal(ab.X, ab.Y, ab.Z) * cc * SyntheticRaw.CameraMatrix,
};
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 0), 55);
}
[Test]
public void ValueMappingOpcodesInListThreeSeeUnbalancedValues()
{
// Stored halved; MapPolynomial ×2 in OpcodeList3 restores the scene only if applied before white balance.
var ops = new OpcodeListBuilder().Add(8, 0, p =>
{
OpcodeListBuilder.Area(p, 0, 0, H, W, planes: 3);
p.U32(1).F64(0).F64(2);
}).Build();
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null, OpcodeList3 = ops, RawTransform = (_, _, v) => v / 2 }));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 0), 55);
}
[Test]
public void LinearRawRoundTripsExactly()
{
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null }));
Assert.Equal("linear", result.Info.Layout);
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 0), 60);
}
[Test]
public void BlackLevelPatternAndDeltasAreSubtracted()
{
using var scene = SyntheticRaw.Smooth(W, H);
var deltaH = Enumerable.Range(0, W).Select(x => (double)(x % 7)).ToArray();
var deltaV = Enumerable.Range(0, H).Select(y => y * 0.5).ToArray();
var spec = new DngSpec { BlackRows = 2, BlackColumns = 2, Black = [500, 520, 530, 510], BlackDeltaH = deltaH, BlackDeltaV = deltaV, MarginLeft = 4, MarginTop = 2 };
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 40);
}
[Test]
public void LinearizationTableIsApplied()
{
using var scene = SyntheticRaw.Smooth(W, H);
// 4096 codes covering 0..16383 with a square law: dense in the shadows, sparse in the highlights.
var table = Enumerable.Range(0, 4096).Select(i => (ushort)double.Round(16383.0 * i * i / (4095.0 * 4095.0))).ToArray();
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Linearization = table, Black = [0] }));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
}
[Test]
public void ActiveAreaAndDefaultCropSelectTheImage()
{
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec { MarginLeft = 6, MarginTop = 4, MarginRight = 2, MarginBottom = 3, Crop = new RawRect(8, 6, 8 + 64, 6 + 48) };
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.Equal(64, result.Image.Width);
Assert.Equal(48, result.Image.Height);
Assert.Equal(64, result.Info.Width);
using var expected = Crop(scene, 8, 6, 64, 48);
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 2), 40);
}
[Theory]
[Case(false)]
[Case(true)]
public void WhiteBalanceFromAsShotNeutralOrWhiteXy(bool whiteXy)
{
// Scene lit by tungsten (2850 K): decoding must adapt it back to the D65 scene.
using var scene = SyntheticRaw.Smooth(W, H);
var tungsten = new Chromaticity(0.44757, 0.40745);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { SceneWhite = tungsten, WriteWhiteXy = whiteXy }));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
Assert.Less(SyntheticRaw.MeanDeltaE(scene, result.Image, 4), 1.5);
}
[Test]
public void DualIlluminantMatricesInterpolateByTemperature()
{
var profile = new DngColorProfile
{
ColorMatrix1 = SyntheticRaw.TungstenMatrix,
CalibrationIlluminant1 = 17,
ColorMatrix2 = SyntheticRaw.CameraMatrix,
CalibrationIlluminant2 = 21,
};
var warm = new Chromaticity(0.44757, 0.40745);
var mid = ColorTemperatureXy(4200);
Assert.Approximately(2850, DngColorProfile.Temperature(warm), 15);
Assert.Approximately(6504, DngColorProfile.Temperature(Chromaticity.D65), 30);
AssertMatrix(SyntheticRaw.TungstenMatrix, profile.XyzToCamera(warm), 1e-3);
AssertMatrix(SyntheticRaw.CameraMatrix, profile.XyzToCamera(Chromaticity.D65), 1e-9);
// Between the calibrations the weight is linear in inverse temperature.
var t = DngColorProfile.Temperature(mid);
var g = (1 / t - 1 / 6500.0) / (1 / 2850.0 - 1 / 6500.0);
Assert.Approximately(g * SyntheticRaw.TungstenMatrix.M11 + (1 - g) * SyntheticRaw.CameraMatrix.M11, profile.XyzToCamera(mid).M11, 1e-9);
// A DNG with both matrices, shot at 4200 K, decodes back to the scene.
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec
{
ColorMatrix1 = SyntheticRaw.TungstenMatrix,
Illuminant1 = 17,
ColorMatrix2 = SyntheticRaw.CameraMatrix,
Illuminant2 = 21,
CaptureMatrix = profile.XyzToCamera(mid),
SceneWhite = mid,
};
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
}
[Test]
public void ForwardMatrixMapsNeutralToWhite()
{
// ForwardMatrix = Rec.709 → XYZ(D50) with camera = linear Rec.709: a gray scene must stay gray.
var fm = Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), Chromaticity.D50.ToXyz()) * Matrix3.Rec709ToXyz;
using var scene = new ImageBuffer(32, 32);
scene.Data.Fill(0.4f);
var spec = new DngSpec { Cfa = null, ColorMatrix1 = Matrix3.XyzToRec709, ForwardMatrix1 = fm };
using var result = Decode(SyntheticDng.Write(scene, spec));
for (var c = 0; c < 3; c++) Assert.Approximately(0.4, result.Image[c, 16, 16], 2e-3);
}
[Test]
public void BaselineExposureScalesOutput()
{
using var scene = SyntheticRaw.Smooth(W, H);
using var plain = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null }));
using var bright = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null, BaselineExposure = 1 }));
Assert.Approximately(2 * plain.Image[1, 40, 30], bright.Image[1, 40, 30], 1e-4);
}
[Theory]
[Case((ushort)6)]
[Case((ushort)3)]
public void OrientationIsApplied(ushort orientation)
{
using var scene = SyntheticRaw.Smooth(W, H);
var dng = SyntheticDng.Write(scene, new DngSpec { Cfa = null, Orientation = orientation });
using var oriented = Decode(dng);
using var stored = Decode(dng, new RawDecodeOptions { ApplyOrientation = false });
using var expected = PixelConvert.ApplyOrientation(stored.Image, orientation);
Assert.Equal(expected.Width, oriented.Image.Width);
Assert.Equal(expected.Width, oriented.Info.Width);
Assert.SequenceEqual(expected.Data.ToArray(), oriented.Image.Data.ToArray());
}
[Theory]
[Case(DemosaicQuality.Best)]
[Case(DemosaicQuality.Draft)]
public void BinningHalvesTheSize(DemosaicQuality quality)
{
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec()), new RawDecodeOptions { MaxLongEdge = W / 2, Quality = quality });
Assert.Equal(W / 2, result.Image.Width);
Assert.Equal(H / 2, result.Image.Height);
using var expected = Resampler.Resize(scene, W / 2, H / 2, ResampleFilter.Box);
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 1), 34);
}
[Test]
public void ProbeDescribesWithoutDecoding()
{
using var scene = SyntheticRaw.Smooth(W, H);
var dng = SyntheticDng.Write(scene, new DngSpec { Orientation = 6, Crop = new RawRect(2, 2, 66, 50) });
var probe = RawDecoder.Probe(new MemoryStream(dng), "x.dng");
Assert.True(probe.IsSupported);
Assert.Equal(48, probe.Info!.Width);
Assert.Equal(64, probe.Info.Height);
Assert.Equal("managed-dng", probe.Info.Decoder);
Assert.Equal("Synthetic", probe.Info.Model);
}
internal static ImageBuffer Crop(ImageBuffer source, int x0, int y0, int w, int h)
{
var result = new ImageBuffer(w, h, source.Channels);
for (var c = 0; c < source.Channels; c++)
{
for (var y = 0; y < h; y++) source.Row(c, y0 + y).Slice(x0, w).CopyTo(result.Row(c, y));
}
return result;
}
private static Chromaticity ColorTemperatureXy(double kelvin) => Titano.Core.Analysis.ColorTemperature.PlanckianChromaticity(kelvin);
private static void AssertMatrix(Matrix3 expected, Matrix3 actual, double tolerance)
{
double[] e = [expected.M11, expected.M12, expected.M13, expected.M21, expected.M22, expected.M23, expected.M31, expected.M32, expected.M33];
double[] a = [actual.M11, actual.M12, actual.M13, actual.M21, actual.M22, actual.M23, actual.M31, actual.M32, actual.M33];
for (var i = 0; i < 9; i++) Assert.Approximately(e[i], a[i], tolerance);
}
}
@@ -0,0 +1,221 @@
using Titano.Core.Codecs.Raw;
using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Raw;
/// <summary>DNG opcode lists: raw data is distorted by the inverse of an opcode, the decoder must undo it.</summary>
public sealed class DngOpcodeTests(TestContext context)
{
private const int W = 96, H = 72;
private static RawDecodeResult Decode(byte[] dng) => RawDecoder.Decode(new MemoryStream(dng), "op.dng");
/// <summary>Bilinear grid interpolation as DNG §7 GainMap defines it (independent of the decoder's implementation).</summary>
private static double GainAt(double[,] grid, double spacingV, double spacingH, int x, int y)
{
int rows = grid.GetLength(0), cols = grid.GetLength(1);
double fr = double.Clamp(y / (double)H / spacingV, 0, rows - 1), fc = double.Clamp(x / (double)W / spacingH, 0, cols - 1);
int r0 = (int)fr, c0 = (int)fc, r1 = int.Min(r0 + 1, rows - 1), c1 = int.Min(c0 + 1, cols - 1);
double a = fr - r0, b = fc - c0;
return (grid[r0, c0] * (1 - b) + grid[r0, c1] * b) * (1 - a) + (grid[r1, c0] * (1 - b) + grid[r1, c1] * b) * a;
}
[Test]
public void GainMapRestoresShading()
{
double[,] grid = { { 1.6, 1.3, 1.6 }, { 1.2, 1.0, 1.25 }, { 1.7, 1.35, 1.5 } };
var ops = new OpcodeListBuilder().Add(9, 0, p =>
{
OpcodeListBuilder.Area(p, 0, 0, H, W);
p.U32(3).U32(3).F64(0.5).F64(0.5).F64(0).F64(0).U32(1);
for (var r = 0; r < 3; r++)
{
for (var c = 0; c < 3; c++) p.F32((float)grid[r, c]);
}
}).Build();
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec { OpcodeList2 = ops, RawTransform = (x, y, v) => (float)(v / GainAt(grid, 0.5, 0.5, x, y)) };
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.Empty(result.Warnings);
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
}
[Test]
public void GainMapWithPitchTargetsOneCfaColour()
{
// Red sites of RGGB (even rows and columns) were attenuated by 1/1.5.
var ops = new OpcodeListBuilder().Add(9, 0, p =>
{
OpcodeListBuilder.Area(p, 0, 0, H, W, rowPitch: 2, colPitch: 2);
p.U32(1).U32(1).F64(1).F64(1).F64(0).F64(0).U32(1).F32(1.5f);
}).Build();
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec { OpcodeList2 = ops, RawTransform = (x, y, v) => x % 2 == 0 && y % 2 == 0 ? v / 1.5f : v };
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
}
[Test]
public void FixVignetteRadialRestoresFalloff()
{
double k0 = 0.4, k1 = 0.2;
var ops = new OpcodeListBuilder().Add(3, 0, p => p.F64(k0).F64(k1).F64(0).F64(0).F64(0).F64(0.5).F64(0.5)).Build();
var m = double.Hypot(W / 2.0, H / 2.0);
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec
{
OpcodeList2 = ops,
RawTransform = (x, y, v) =>
{
var r2 = ((x - W / 2.0) * (x - W / 2.0) + (y - H / 2.0) * (y - H / 2.0)) / (m * m);
return (float)(v / (1 + k0 * r2 + k1 * r2 * r2));
},
};
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
}
[Theory]
[Case(false)]
[Case(true)]
public void WarpRectilinearMovesPointsToTheirCorrectedPositions(bool mosaic)
{
// Corrected position p maps to source position f(p) (radial + tangential model, DNG §7 WarpRectilinear).
const int w = 160, h = 120;
double[] k = [1.0, 0.06, -0.01, 0.0, 0.002, -0.0015];
double cx = 0.48, cy = 0.53;
var ops = new OpcodeListBuilder().Add(1, 0, p =>
{
p.U32(1);
foreach (var v in k) p.F64(v);
p.F64(cx).F64(cy);
}).Build();
double ox = cx * w, oy = cy * h;
var m = new[] { (0.0, 0.0), (w, 0.0), (0.0, h), (w, h) }.Max(c => double.Hypot(c.Item1 - ox, c.Item2 - oy));
(double X, double Y) Source(double x, double y)
{
double dx = (x - ox) / m, dy = (y - oy) / m, r2 = dx * dx + dy * dy;
var f = k[0] + r2 * (k[1] + r2 * (k[2] + r2 * k[3]));
return (ox + m * (f * dx + k[4] * 2 * dx * dy + k[5] * (r2 + 2 * dx * dx)), oy + m * (f * dy + k[5] * 2 * dx * dy + k[4] * (r2 + 2 * dy * dy)));
}
(double X, double Y)[] targets = [(20, 18), (130, 25), (80, 60), (30, 100), (140, 104), (60, 40)];
using var distorted = new ImageBuffer(w, h);
foreach (var (tx, ty) in targets)
{
var (sx, sy) = Source(tx, ty);
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
var g = (float)(0.6 * double.Exp(-((x - sx) * (x - sx) + (y - sy) * (y - sy)) / (2 * 2.0 * 2.0)));
for (var c = 0; c < 3; c++) distorted[c, x, y] += g;
}
}
}
for (var i = 0; i < distorted.Data.Length; i++) distorted.Data[i] += 0.02f;
var spec = new DngSpec { Cfa = mosaic ? CfaPattern.Bayer("RGGB") : null, OpcodeList3 = ops };
using var result = Decode(SyntheticDng.Write(distorted, spec));
Assert.Empty(result.Warnings);
foreach (var (tx, ty) in targets)
{
var (x, y) = Centroid(result.Image, (int)tx, (int)ty, 6);
context.Log($"target ({tx}, {ty}) → ({x:F3}, {y:F3})");
Assert.Within(tx, ty, x, y, mosaic ? 0.2 : 0.1);
}
}
[Test]
public void TrimBoundsAndDefaultCropCompose()
{
var ops = new OpcodeListBuilder().Add(6, 0, p => p.U32(4).U32(10).U32(60).U32(90)).Build();
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { OpcodeList3 = ops, Crop = new RawRect(0, 0, 80, 64) }));
Assert.Equal(70, result.Image.Width);
Assert.Equal(56, result.Image.Height);
using var expected = DngDecoderTests.Crop(scene, 10, 4, 70, 56);
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 2), 38);
}
[Test]
public void FixBadPixelsConstantAndListRepairMosaic()
{
(int X, int Y)[] dead = [(10, 10), (41, 20), (70, 33)];
(int X, int Y)[] hot = [(30, 50), (55, 12)];
var list1 = new OpcodeListBuilder().Add(4, 0, p => p.U32(0).U32(0)).Build();
var list2 = new OpcodeListBuilder().Add(5, 0, p =>
{
p.U32(0).U32((uint)hot.Length).U32(1);
foreach (var (x, y) in hot) p.U32((uint)y).U32((uint)x);
p.U32(60).U32(80).U32(62).U32(83);
}).Build();
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec
{
OpcodeList1 = list1,
OpcodeList2 = list2,
RawTransform = (x, y, v) => dead.Contains((x, y)) ? -1f : hot.Contains((x, y)) || (y is >= 60 and < 62 && x is >= 80 and < 83) ? 1f : v,
};
using var result = Decode(SyntheticDng.Write(scene, spec));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
}
[Test]
public void MapTableAndMapPolynomialInvertEncodings()
{
// Raw stored as v² is mapped back by a square-root table; then halved values are doubled by a polynomial.
var table = Enumerable.Range(0, 65536).Select(i => (ushort)double.Round(double.Sqrt(i / 65535.0) * 65535)).ToArray();
var ops = new OpcodeListBuilder()
.Add(7, 0, p =>
{
OpcodeListBuilder.Area(p, 0, 0, H, W);
p.U32((uint)table.Length);
foreach (var t in table) p.U16(t);
})
.Add(8, 0, p =>
{
OpcodeListBuilder.Area(p, 0, 0, H, W);
p.U32(1).F64(0).F64(2);
})
.Build();
using var scene = SyntheticRaw.Smooth(W, H);
var spec = new DngSpec { Black = [0], OpcodeList2 = ops, RawTransform = (_, _, v) => float.Max(0, v / 2) * float.Max(0, v / 2) };
using var result = Decode(SyntheticDng.Write(scene, spec));
var psnr = SyntheticRaw.Psnr(scene, result.Image, 4);
context.Log($"MapTable+MapPolynomial PSNR {psnr:F1} dB");
Assert.GreaterOrEqual(psnr, 36);
}
[Test]
public void UnknownAndMalformedOpcodesWarnAndContinue()
{
var ops = new OpcodeListBuilder()
.Add(99, 1, p => p.U32(1))
.Add(98, 0, p => p.U32(1))
.Add(9, 0, p => p.U32(1))
.Build();
using var scene = SyntheticRaw.Smooth(W, H);
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { OpcodeList3 = ops }));
Assert.Contains(result.Warnings, w => w.Contains("optional opcode 99"));
Assert.Contains(result.Warnings, w => w.Contains("required opcode 98"));
Assert.Contains(result.Warnings, w => w.Contains("GainMap") && w.Contains("malformed"));
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 40);
}
/// <summary>Intensity-weighted centroid above the background in a window around (x, y).</summary>
private static (double X, double Y) Centroid(ImageBuffer image, int cx, int cy, int radius)
{
double sum = 0, sx = 0, sy = 0;
for (var y = cy - radius; y <= cy + radius; y++)
{
for (var x = cx - radius; x <= cx + radius; x++)
{
var v = double.Max(0, image[1, x, y] - 0.05);
sum += v;
sx += v * x;
sy += v * y;
}
}
return (sx / sum, sy / sum);
}
}
@@ -0,0 +1,75 @@
using Titano.Core.Codecs.Raw;
using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Raw;
/// <summary>Clip-aware highlight reconstruction on decoded DNGs.</summary>
public sealed class HighlightTests(TestContext context)
{
private const int W = 96, H = 64;
/// <summary>Scene with three gray patches: unclipped (0.4), green clipped only (1.3) and fully clipped (3.0).</summary>
private static ImageBuffer Patches()
{
var scene = new ImageBuffer(W, H);
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
var v = x < 32 ? 0.4f : x < 64 ? 1.3f : 3.0f;
for (var c = 0; c < 3; c++) scene[c, x, y] = v;
}
}
return scene;
}
[Theory]
[Case(DemosaicQuality.Best, false)]
[Case(DemosaicQuality.Draft, true)]
public void ClippedGrayStaysNeutral(DemosaicQuality quality, bool binning)
{
using var scene = Patches();
var dng = SyntheticDng.Write(scene, new DngSpec());
using var result = RawDecoder.Decode(new MemoryStream(dng), "h.dng", new RawDecodeOptions { Quality = quality, MaxLongEdge = binning ? 1 : 0 });
var s = binning ? 2 : 1;
var (r0, g0, b0) = Pixel(result.Image, 16 / s, 32 / s);
var (r1, g1, b1) = Pixel(result.Image, 48 / s, 32 / s);
var (r2, g2, b2) = Pixel(result.Image, 80 / s, 32 / s);
context.Log($"0.4 → ({r0:F3}, {g0:F3}, {b0:F3}); 1.3 → ({r1:F3}, {g1:F3}, {b1:F3}); 3.0 → ({r2:F3}, {g2:F3}, {b2:F3})");
// Unclipped: exact.
Assert.Approximately(0.4, g0, 0.01);
Assert.Approximately(r0, b0, 0.01);
// Only green clipped: rebuilt from red and blue, neutral and at its true level (no magenta cast).
Assert.Approximately(1.3, g1, 0.03);
Assert.Approximately(1.3, r1, 0.03);
Assert.Approximately(1.3, b1, 0.03);
// Everything clipped: neutral, at least as bright as the partially clipped patch.
Assert.Approximately(r2, g2, 1e-3);
Assert.Approximately(b2, g2, 1e-3);
Assert.GreaterOrEqual(g2, g1);
}
[Test]
public void SaturatedColourKeepsItsHue()
{
// A red highlight clips the red channel while green and blue stay low: it must stay red, not turn white.
using var scene = new ImageBuffer(W, H);
for (var i = 0; i < scene.PlaneLength; i++)
{
scene.Plane(0)[i] = 5f;
scene.Plane(1)[i] = 0.15f;
scene.Plane(2)[i] = 0.1f;
}
using var result = RawDecoder.Decode(new MemoryStream(SyntheticDng.Write(scene, new DngSpec())), "red.dng");
var (r, g, b) = Pixel(result.Image, W / 2, H / 2);
context.Log($"red highlight → ({r:F3}, {g:F3}, {b:F3})");
Assert.Greater(r, 4 * g);
Assert.Greater(r, 4 * b);
}
private static (float R, float G, float B) Pixel(ImageBuffer image, int x, int y) => (image[0, x, y], image[1, x, y], image[2, x, y]);
}
@@ -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, 12)]
[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 { MaxLongEdge = 1 });
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), (ushort)(s.Samples[i] << 4));
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.WriteUInt16LittleEndian(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 "";
}
}
}
@@ -0,0 +1,94 @@
using System.Buffers.Binary;
using System.Diagnostics;
using System.Reflection;
using Titano.Core.Codecs.Raw;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Metadata.Tiff;
using Titano.Testing;
namespace Titano.Core.Tests.Raw;
/// <summary>24-megapixel Bayer DNG development timing: AHD at full size and binned Draft at half size, all cores.</summary>
[Serial]
[Category("Performance")]
public sealed class RawPerformanceTests(TestContext context)
{
private const int W = 6000, H = 4000;
[Test]
[Timeout(60_000)]
public void Develops24MegapixelDngWithinBudget()
{
// A Debug build disables the JIT optimiser in Titano.Core: timings would measure the build, not the pipeline.
if (typeof(RawDecoder).Assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITOptimizerDisabled == true)
TestContext.Skip("timing gate needs an optimised build (dotnet run -c Release)");
var dng = Mosaic();
var ahd = Best(dng, RawDecodeOptions.Default, out var size);
Assert.Equal(W, size.Width);
var half = Best(dng, new RawDecodeOptions { Quality = DemosaicQuality.Draft, MaxLongEdge = W / 2 }, out var halfSize);
Assert.Equal(W / 2, halfSize.Width);
context.Log($"24 MP DNG: AHD full size {ahd.TotalMilliseconds:F0} ms, binned half size {half.TotalMilliseconds:F0} ms ({Environment.ProcessorCount} cores)");
Console.WriteLine($"[perf] {context.LogText.Trim()}");
Assert.Less(ahd.TotalSeconds, 4.0);
Assert.Less(half.TotalSeconds, 1.0);
}
/// <summary>Best of two runs (the machine is shared; the first run also pays JIT warm-up).</summary>
private static TimeSpan Best(byte[] dng, RawDecodeOptions options, out (int Width, int Height) size)
{
var best = TimeSpan.MaxValue;
size = default;
for (var run = 0; run < 2; run++)
{
var sw = Stopwatch.StartNew();
using var result = RawDecoder.Decode(new MemoryStream(dng, writable: false), "perf.dng", options);
best = sw.Elapsed < best ? sw.Elapsed : best;
size = (result.Image.Width, result.Image.Height);
}
return best;
}
/// <summary>Uncompressed 14-bit RGGB DNG with photo-like texture (smooth illumination plus detail and noise).</summary>
private static byte[] Mosaic()
{
var data = new byte[W * H * 2];
Parallel.For(0, H, y =>
{
var state = (uint)(y * 2654435761u + 7);
for (var x = 0; x < W; x++)
{
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
var colour = (y & 1) * 2 + (x & 1);
var level = 1500 + 5000 * (0.5 + 0.5 * double.Sin(x * 0.01) * double.Cos(y * 0.013)) * (colour is 1 or 2 ? 1.0 : 0.6)
+ 800 * double.Sin(x * 0.4 + y * 0.3) + (state & 127);
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan((y * W + x) * 2), (ushort)double.Clamp(level, 0, 16383));
}
});
using var output = new MemoryStream();
output.Write("II*\0\0\0\0\0"u8);
var ifd = new TiffDirectory();
ifd.Long(TiffTags.NewSubfileType, 0);
ifd.Long(TiffTags.ImageWidth, W);
ifd.Long(TiffTags.ImageLength, H);
ifd.Short(TiffTags.BitsPerSample, 16);
ifd.Short(TiffTags.Compression, 1);
ifd.Short(TiffTags.PhotometricInterpretation, 32803);
ifd.Short(TiffTags.SamplesPerPixel, 1);
ifd.Long(TiffTags.StripOffsets, 8);
ifd.Long(TiffTags.StripByteCounts, (uint)data.Length);
ifd.Long(TiffTags.RowsPerStrip, H);
ifd.Short(TiffTags.CfaRepeatPatternDim, 2, 2);
ifd.Bytes(TiffTags.CfaPattern, 0, 1, 1, 2);
ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0);
ifd.Short(TiffTags.BlackLevel, 1024);
ifd.Short(TiffTags.WhiteLevel, 16383);
ifd.SRational(TiffTags.ColorMatrix1, (6722, 10000), (-635, 10000), (-963, 10000), (-4287, 10000), (12460, 10000), (2028, 10000), (-908, 10000), (2162, 10000), (5668, 10000));
ifd.Short(TiffTags.CalibrationIlluminant1, 21);
ifd.Rational(TiffTags.AsShotNeutral, (500u, 1000u), (1000u, 1000u), (700u, 1000u));
output.Write(data);
TiffWriter.WriteDirectory(output, 0, ifd);
return output.ToArray();
}
}
+503
View File
@@ -0,0 +1,503 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Codecs.Dng;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Raw;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Imaging;
using Titano.Core.Mathematics;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Tests.Raw;
/// <summary>Synthetic scenes and the camera model used to turn them into raw data with known answers.</summary>
internal static class SyntheticRaw
{
/// <summary>Canon EOS 5D Mark III ColorMatrix (XYZ → camera, D65), the adobe_coeff values divided by 10 000.</summary>
public static Matrix3 CameraMatrix { get; } = new(0.6722, -0.0635, -0.0963, -0.4287, 1.2460, 0.2028, -0.0908, 0.2162, 0.5668);
/// <summary>A second (tungsten) matrix for interpolation tests: the D65 one with a warmer bias.</summary>
public static Matrix3 TungstenMatrix { get; } = new(0.7300, -0.1100, -0.0800, -0.4000, 1.2000, 0.2400, -0.0500, 0.1500, 0.7400);
/// <summary>Smooth colourful linear Rec.709 scene with values in roughly 0.03–0.7.</summary>
public static ImageBuffer Smooth(int width, int height)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
double u = x / (double)width, v = y / (double)height;
image[0, x, y] = (float)(0.25 + 0.2 * double.Sin(2 * double.Pi * (u * 1.3 + 0.1)) * double.Cos(2 * double.Pi * v * 0.7));
image[1, x, y] = (float)(0.3 + 0.2 * double.Cos(2 * double.Pi * (u * 0.8 - v * 0.9)));
image[2, x, y] = (float)(0.2 + 0.15 * double.Sin(2 * double.Pi * (v * 1.1 + u * 0.4 + 0.3)));
}
}
return image;
}
/// <summary>Gray scene with a sharp vertical edge (dark left, bright right) and a sharp horizontal one.</summary>
public static ImageBuffer Edges(int width, int height)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var v = (x >= width / 2 ? 0.6f : 0.08f) * (y >= height / 2 ? 0.5f : 1f);
for (var c = 0; c < 3; c++) image[c, x, y] = v;
}
}
return image;
}
/// <summary>Camera response of a scene lit by <paramref name="white"/>: Bradford(D65 → white) · Rec.709 → XYZ, then
/// XYZ → camera, scaled so the white's camera neutral peaks at 1. Returns per-pixel camera RGB and that neutral.</summary>
public static (float[][] Camera, Vector3D Neutral) ToCamera(ImageBuffer scene, Matrix3 xyzToCamera, Chromaticity white)
{
var whiteXyz = white.ToXyz();
var neutral = xyzToCamera * whiteXyz;
var s = double.Max(neutral.X, double.Max(neutral.Y, neutral.Z));
var m = xyzToCamera * Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), whiteXyz) * Matrix3.Rec709ToXyz;
var camera = new float[3][];
for (var c = 0; c < 3; c++) camera[c] = new float[scene.PlaneLength];
for (var i = 0; i < scene.PlaneLength; i++)
{
var v = m * new Vector3D(scene.Plane(0)[i], scene.Plane(1)[i], scene.Plane(2)[i]);
camera[0][i] = (float)(v.X / s);
camera[1][i] = (float)(v.Y / s);
camera[2][i] = (float)(v.Z / s);
}
return (camera, new Vector3D(neutral.X / s, neutral.Y / s, neutral.Z / s));
}
/// <summary>PSNR in dB between two RGB buffers on sRGB-encoded values, ignoring <paramref name="border"/> pixels.</summary>
public static double Psnr(ImageBuffer expected, ImageBuffer actual, int border)
{
double sum = 0;
long n = 0;
for (var c = 0; c < 3; c++)
{
for (var y = border; y < expected.Height - border; y++)
{
for (var x = border; x < expected.Width - border; x++)
{
var d = ColorSpace.EncodeFast(expected[c, x, y]) - ColorSpace.EncodeFast(actual[c, x, y]);
sum += d * d;
n++;
}
}
}
return 10 * double.Log10(1 / double.Max(sum / n, 1e-12));
}
/// <summary>Mean CIE76 ΔE between two linear Rec.709 buffers (D65 white), ignoring <paramref name="border"/> pixels.</summary>
public static double MeanDeltaE(ImageBuffer expected, ImageBuffer actual, int border)
{
double sum = 0;
long n = 0;
for (var y = border; y < expected.Height - border; y++)
{
for (var x = border; x < expected.Width - border; x++)
{
var a = Lab(expected, x, y);
var b = Lab(actual, x, y);
sum += double.Sqrt((a.L - b.L) * (a.L - b.L) + (a.A - b.A) * (a.A - b.A) + (a.B - b.B) * (a.B - b.B));
n++;
}
}
return sum / n;
}
private static (double L, double A, double B) Lab(ImageBuffer image, int x, int y)
{
var xyz = Matrix3.Rec709ToXyz * new Vector3D(image[0, x, y], image[1, x, y], image[2, x, y]);
var w = Chromaticity.D65.ToXyz();
static double F(double t) => t > 216.0 / 24389 ? double.Cbrt(t) : (24389.0 / 27 * t + 16) / 116;
double fx = F(xyz.X / w.X), fy = F(xyz.Y / w.Y), fz = F(xyz.Z / w.Z);
return (116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz));
}
}
/// <summary>Description of a synthetic DNG written by <see cref="SyntheticDng"/>.</summary>
internal sealed record DngSpec
{
/// <summary>CFA pattern anchored at the active area; null writes a 3-sample LinearRaw image.</summary>
public CfaPattern? Cfa { get; init; } = CfaPattern.Bayer("RGGB");
/// <summary>Masked border around the scene (active area offset); the crop is relative to the active area.</summary>
public int MarginLeft { get; init; }
public int MarginTop { get; init; }
public int MarginRight { get; init; }
public int MarginBottom { get; init; }
/// <summary>DefaultCrop relative to the active area (null: none).</summary>
public RawRect? Crop { get; init; }
public int White { get; init; } = 16383;
/// <summary>Black pattern (rows × columns) or a single value.</summary>
public int BlackRows { get; init; } = 1;
public int BlackColumns { get; init; } = 1;
public double[] Black { get; init; } = [512];
public double[]? BlackDeltaH { get; init; }
public double[]? BlackDeltaV { get; init; }
/// <summary>Forward linearisation table (stored code → linear value).</summary>
public ushort[]? Linearization { get; init; }
/// <summary>1 (uncompressed), 7 (lossless JPEG), 8 (Deflate with horizontal predictor) or 34892 (lossy JPEG tiles of
/// 8-bit codes; pair it with a 256-entry <see cref="Linearization"/>).</summary>
public int Compression { get; init; } = 7;
/// <summary>Store 32-bit floats (raw camera values, white 1.0) with Deflate and the floating-point predictor.</summary>
public bool FloatingPoint { get; init; }
public Matrix3? CameraCalibration1 { get; init; }
public Vector3D? AnalogBalance { get; init; }
/// <summary>Lossless JPEG tiles encode CFA rows as two interleaved components at half width (as the DNG SDK does).</summary>
public bool TwoComponentTiles { get; init; } = true;
public int TileSize { get; init; } = 64;
public Matrix3 ColorMatrix1 { get; init; } = SyntheticRaw.CameraMatrix;
/// <summary>XYZ → camera used to synthesise the raw values (default: <see cref="ColorMatrix1"/>).</summary>
public Matrix3? CaptureMatrix { get; init; }
public int Illuminant1 { get; init; } = 21;
public Matrix3? ColorMatrix2 { get; init; }
public int Illuminant2 { get; init; }
public Matrix3? ForwardMatrix1 { get; init; }
/// <summary>Scene illuminant; the file records it as AsShotNeutral or, with <see cref="WriteWhiteXy"/>, AsShotWhiteXY.</summary>
public Chromaticity SceneWhite { get; init; } = Chromaticity.D65;
public bool WriteWhiteXy { get; init; }
public double BaselineExposure { get; init; }
public byte[]? OpcodeList1 { get; init; }
public byte[]? OpcodeList2 { get; init; }
public byte[]? OpcodeList3 { get; init; }
public ushort Orientation { get; init; } = 1;
/// <summary>Put the raw image in a SubIFD behind an IFD0 thumbnail, like camera DNGs.</summary>
public bool RawInSubIfd { get; init; }
/// <summary>Raw-value transform applied after mosaicking (e.g. the inverse of a gain map), stored-unit domain.</summary>
public Func<int, int, float, float>? RawTransform { get; init; }
}
/// <summary>Writes synthetic DNGs from a linear scene with a known camera model (test-side writer).</summary>
internal static class SyntheticDng
{
public static byte[] Write(ImageBuffer scene, DngSpec spec)
{
var (camera, neutral) = SyntheticRaw.ToCamera(scene, spec.CaptureMatrix ?? spec.ColorMatrix1, spec.SceneWhite);
int sw = scene.Width, sh = scene.Height;
int w = sw + spec.MarginLeft + spec.MarginRight, h = sh + spec.MarginTop + spec.MarginBottom;
var spp = spec.Cfa is null ? 3 : 1;
var samples = new ushort[w * h * spp];
var floats = spec.FloatingPoint ? new float[w * h * spp] : null;
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
int ax = x - spec.MarginLeft, ay = y - spec.MarginTop;
var inside = ax >= 0 && ay >= 0 && ax < sw && ay < sh;
for (var s = 0; s < spp; s++)
{
var black = BlackAt(spec, ax, ay, s, spp);
double linear = black;
if (inside)
{
var c = spec.Cfa?.ColorAt(ax, ay) ?? s;
var raw = camera[c][ay * sw + ax];
if (spec.RawTransform is { } t) raw = t(ax, ay, raw);
if (floats is not null) floats[(y * w + x) * spp + s] = raw;
linear = black + raw * (spec.White - black);
}
linear = double.Clamp(linear, 0, spec.White);
samples[(y * w + x) * spp + s] = spec.Linearization is { } table ? Inverse(table, linear) : (ushort)double.Round(linear);
}
}
}
return Assemble(spec, samples, floats, w, h, spp, neutral);
}
/// <summary>Black level of the spec at active-area coordinates (outside the area: the pattern without deltas).</summary>
public static double BlackAt(DngSpec spec, int ax, int ay, int s, int spp)
{
var row = ((ay % spec.BlackRows) + spec.BlackRows) % spec.BlackRows;
var col = ((ax % spec.BlackColumns) + spec.BlackColumns) % spec.BlackColumns;
var b = spec.Black.Length == 1 ? spec.Black[0] : spec.Black[(row * spec.BlackColumns + col) * spp + s];
if (spec.BlackDeltaH is { } dh && ax >= 0 && ax < dh.Length) b += dh[ax];
if (spec.BlackDeltaV is { } dv && ay >= 0 && ay < dv.Length) b += dv[ay];
return b;
}
private static ushort Inverse(ushort[] table, double value)
{
var best = 0;
for (var i = 1; i < table.Length; i++)
{
if (double.Abs(table[i] - value) < double.Abs(table[best] - value)) best = i;
}
return (ushort)best;
}
private static byte[] Assemble(DngSpec spec, ushort[] samples, float[]? floats, int w, int h, int spp, Vector3D neutral)
{
using var output = new MemoryStream();
output.Write("II*\0\0\0\0\0"u8);
var raw = new TiffDirectory();
raw.Long(TiffTags.NewSubfileType, 0);
raw.Long(TiffTags.ImageWidth, (uint)w);
raw.Long(TiffTags.ImageLength, (uint)h);
var bits = floats is not null ? 32 : spec.Compression == 34892 ? 8 : 16;
raw.Short(TiffTags.BitsPerSample, [.. Enumerable.Repeat((ushort)bits, spp)]);
if (floats is not null) raw.Short(TiffTags.SampleFormat, [.. Enumerable.Repeat((ushort)3, spp)]);
raw.Short(TiffTags.Compression, (ushort)spec.Compression);
raw.Short(TiffTags.PhotometricInterpretation, (ushort)(spec.Cfa is null ? 34892 : 32803));
raw.Short(TiffTags.SamplesPerPixel, (ushort)spp);
raw.Short(TiffTags.PlanarConfiguration, 1);
if (floats is not null)
{
raw.Short(TiffTags.Compression, 8);
raw.Short(TiffTags.Predictor, 3);
WriteFloats(raw, output, floats, w, h, spp);
}
else
{
if (spec.Compression == 8) raw.Short(TiffTags.Predictor, 2);
WriteData(spec, raw, output, samples, w, h, spp);
}
if (spec.Cfa is { } cfa)
{
raw.Short(TiffTags.CfaRepeatPatternDim, (ushort)cfa.Height, (ushort)cfa.Width);
var pattern = new byte[cfa.Width * cfa.Height];
for (var i = 0; i < pattern.Length; i++) pattern[i] = (byte)cfa.ColorAt(i % cfa.Width, i / cfa.Width);
raw.Bytes(TiffTags.CfaPattern, pattern);
raw.Bytes(TiffTags.CfaPlaneColor, 0, 1, 2);
raw.Short(TiffTags.CfaLayout, 1);
}
if (spec.MarginLeft + spec.MarginTop + spec.MarginRight + spec.MarginBottom > 0)
raw.Long(TiffTags.ActiveArea, (uint)spec.MarginTop, (uint)spec.MarginLeft, (uint)(h - spec.MarginBottom), (uint)(w - spec.MarginRight));
if (spec.Crop is { } crop)
{
raw.Long(TiffTags.DefaultCropOrigin, (uint)crop.Left, (uint)crop.Top);
raw.Long(TiffTags.DefaultCropSize, (uint)crop.Width, (uint)crop.Height);
}
if (spec.Linearization is { } table) raw.Short(TiffTags.LinearizationTable, table);
if (spec.BlackRows * spec.BlackColumns > 1) raw.Short(TiffTags.BlackLevelRepeatDim, (ushort)spec.BlackRows, (ushort)spec.BlackColumns);
if (floats is null) raw.Rational(TiffTags.BlackLevel, [.. spec.Black.Select(b => ((uint)double.Round(b * 100), 100u))]);
if (spec.BlackDeltaH is { } dh) raw.SRational(TiffTags.BlackLevelDeltaH, [.. dh.Select(d => ((int)double.Round(d * 100), 100))]);
if (spec.BlackDeltaV is { } dv) raw.SRational(TiffTags.BlackLevelDeltaV, [.. dv.Select(d => ((int)double.Round(d * 100), 100))]);
if (floats is null) raw.Long(TiffTags.WhiteLevel, [.. Enumerable.Repeat((uint)spec.White, spp)]);
if (spec.OpcodeList1 is { } o1) raw.Add(TiffTags.OpcodeList1, TiffType.Undefined, o1.Length, o1);
if (spec.OpcodeList2 is { } o2) raw.Add(TiffTags.OpcodeList2, TiffType.Undefined, o2.Length, o2);
if (spec.OpcodeList3 is { } o3) raw.Add(TiffTags.OpcodeList3, TiffType.Undefined, o3.Length, o3);
var ifd0 = raw;
if (spec.RawInSubIfd)
{
ifd0 = new TiffDirectory();
ifd0.Long(TiffTags.NewSubfileType, 1);
ifd0.Long(TiffTags.ImageWidth, 4);
ifd0.Long(TiffTags.ImageLength, 4);
ifd0.Short(TiffTags.BitsPerSample, 8, 8, 8);
ifd0.Short(TiffTags.Compression, 1);
ifd0.Short(TiffTags.PhotometricInterpretation, 2);
ifd0.Short(TiffTags.SamplesPerPixel, 3);
ifd0.Long(TiffTags.StripOffsets, 8);
ifd0.Long(TiffTags.StripByteCounts, 48);
ifd0.Child(TiffTags.SubIfds, raw);
}
ifd0.Ascii(TiffTags.Make, "Titano");
ifd0.Ascii(TiffTags.Model, "Synthetic");
ifd0.Short(TiffTags.Orientation, spec.Orientation);
ifd0.Bytes(TiffTags.DngVersion, 1, 6, 0, 0);
ifd0.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0);
ifd0.Ascii(TiffTags.UniqueCameraModel, "Titano Synthetic");
ifd0.SRational(TiffTags.ColorMatrix1, Rationals(spec.ColorMatrix1));
ifd0.Short(TiffTags.CalibrationIlluminant1, (ushort)spec.Illuminant1);
if (spec.ColorMatrix2 is { } cm2)
{
ifd0.SRational(TiffTags.ColorMatrix2, Rationals(cm2));
ifd0.Short(TiffTags.CalibrationIlluminant2, (ushort)spec.Illuminant2);
}
if (spec.ForwardMatrix1 is { } fm) ifd0.SRational(TiffTags.ForwardMatrix1, Rationals(fm));
if (spec.CameraCalibration1 is { } cc) ifd0.SRational(TiffTags.CameraCalibration1, Rationals(cc));
if (spec.AnalogBalance is { } ab) ifd0.Rational(TiffTags.AnalogBalance, R(ab.X), R(ab.Y), R(ab.Z));
if (spec.WriteWhiteXy)
{
ifd0.Rational(TiffTags.AsShotWhiteXy, ((uint)double.Round(spec.SceneWhite.X * 1e6), 1_000_000u), ((uint)double.Round(spec.SceneWhite.Y * 1e6), 1_000_000u));
}
else
{
ifd0.Rational(TiffTags.AsShotNeutral, R(neutral.X), R(neutral.Y), R(neutral.Z));
}
ifd0.SRational(TiffTags.BaselineExposure, ((int)double.Round(spec.BaselineExposure * 1000), 1000));
TiffWriter.WriteDirectory(output, 0, ifd0);
return output.ToArray();
}
private static (uint, uint) R(double v) => ((uint)double.Round(v * 1_000_000), 1_000_000u);
private static (int, int)[] Rationals(Matrix3 m) =>
[.. new[] { m.M11, m.M12, m.M13, m.M21, m.M22, m.M23, m.M31, m.M32, m.M33 }.Select(v => ((int)double.Round(v * 1_000_000), 1_000_000))];
/// <summary>32-bit float rows with the TIFF floating-point predictor (bytes split into MSB-first planes, then
/// differenced with a stride of one pixel), Deflate-compressed in one strip.</summary>
private static void WriteFloats(TiffDirectory raw, Stream output, float[] floats, int w, int h, int spp)
{
var count = w * spp;
var rows = new byte[floats.Length * 4];
for (var y = 0; y < h; y++)
{
var row = rows.AsSpan(y * count * 4, count * 4);
for (var i = 0; i < count; i++)
{
var bitsValue = BitConverter.SingleToUInt32Bits(floats[y * count + i]);
for (var k = 0; k < 4; k++) row[k * count + i] = (byte)(bitsValue >> (24 - 8 * k));
}
for (var i = row.Length - 1; i >= spp; i--) row[i] -= row[i - spp];
}
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(rows);
var bytes = ms.ToArray();
raw.Long(TiffTags.StripOffsets, (uint)output.Position);
raw.Long(TiffTags.StripByteCounts, (uint)bytes.Length);
raw.Long(TiffTags.RowsPerStrip, (uint)h);
output.Write(bytes);
}
private static void WriteData(DngSpec spec, TiffDirectory raw, Stream output, ushort[] samples, int w, int h, int spp)
{
if (spec.Compression is 7 or 34892)
{
var t = spec.TileSize;
int across = (w + t - 1) / t, down = (h + t - 1) / t;
var offsets = new uint[across * down];
var counts = new uint[across * down];
for (var ty = 0; ty < down; ty++)
{
for (var tx = 0; tx < across; tx++)
{
var tile = new ushort[t * t * spp];
for (var y = 0; y < t; y++)
{
for (var x = 0; x < t; x++)
{
int sx = int.Min(tx * t + x, w - 1), sy = int.Min(ty * t + y, h - 1);
for (var s = 0; s < spp; s++) tile[(y * t + x) * spp + s] = samples[(sy * w + sx) * spp + s];
}
}
var twoComponents = spec.TwoComponentTiles && spp == 1;
var jpeg = spec.Compression == 34892
? JpegEncoder.Encode([.. tile.Select(v => (byte)v)], t, t, spp, new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444 })
: twoComponents ? JpegLosslessEncoder.Encode(tile, t / 2, t, 2, 16) : JpegLosslessEncoder.Encode(tile, t, t, spp, 16);
offsets[ty * across + tx] = (uint)output.Position;
counts[ty * across + tx] = (uint)jpeg.Length;
output.Write(jpeg);
if (output.Position % 2 != 0) output.WriteByte(0);
}
}
raw.Long(TiffTags.TileWidth, (uint)t);
raw.Long(TiffTags.TileLength, (uint)t);
raw.Long(TiffTags.TileOffsets, offsets);
raw.Long(TiffTags.TileByteCounts, counts);
return;
}
var bytes = new byte[samples.Length * 2];
if (spec.Compression == 8)
{
// Horizontal differencing per row (Predictor 2), then zlib.
var rowSamples = w * spp;
var diff = new ushort[samples.Length];
for (var y = 0; y < h; y++)
{
for (var i = 0; i < rowSamples; i++)
{
var k = y * rowSamples + i;
diff[k] = i < spp ? samples[k] : (ushort)(samples[k] - samples[k - spp]);
}
}
for (var i = 0; i < diff.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), diff[i]);
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(bytes);
bytes = ms.ToArray();
}
else
{
for (var i = 0; i < samples.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), samples[i]);
}
raw.Long(TiffTags.StripOffsets, (uint)output.Position);
raw.Long(TiffTags.StripByteCounts, (uint)bytes.Length);
raw.Long(TiffTags.RowsPerStrip, (uint)h);
output.Write(bytes);
}
}
/// <summary>Big-endian opcode list builder for tests (DNG 1.6 chapter 7 layout).</summary>
internal sealed class OpcodeListBuilder
{
private readonly List<byte[]> _ops = [];
public OpcodeListBuilder Add(uint id, uint flags, Action<BigEndian> parameters)
{
var p = new BigEndian();
parameters(p);
var body = p.ToArray();
var head = new BigEndian().U32(id).U32(0x01030000).U32(flags).U32((uint)body.Length).ToArray();
_ops.Add([.. head, .. body]);
return this;
}
public byte[] Build() => [.. new BigEndian().U32((uint)_ops.Count).ToArray(), .. _ops.SelectMany(o => o)];
/// <summary>Area spec (top, left, bottom, right, plane, planes, row pitch, column pitch).</summary>
public static void Area(BigEndian p, int top, int left, int bottom, int right, int plane = 0, int planes = 1, int rowPitch = 1, int colPitch = 1) =>
p.U32((uint)top).U32((uint)left).U32((uint)bottom).U32((uint)right).U32((uint)plane).U32((uint)planes).U32((uint)rowPitch).U32((uint)colPitch);
internal sealed class BigEndian
{
private readonly MemoryStream _ms = new();
public BigEndian U32(uint v)
{
Span<byte> b = stackalloc byte[4];
BinaryPrimitives.WriteUInt32BigEndian(b, v);
_ms.Write(b);
return this;
}
public BigEndian U16(ushort v)
{
Span<byte> b = stackalloc byte[2];
BinaryPrimitives.WriteUInt16BigEndian(b, v);
_ms.Write(b);
return this;
}
public BigEndian F32(float v)
{
Span<byte> b = stackalloc byte[4];
BinaryPrimitives.WriteSingleBigEndian(b, v);
_ms.Write(b);
return this;
}
public BigEndian F64(double v)
{
Span<byte> b = stackalloc byte[8];
BinaryPrimitives.WriteDoubleBigEndian(b, v);
_ms.Write(b);
return this;
}
public byte[] ToArray() => _ms.ToArray();
}
}
+78
View File
@@ -0,0 +1,78 @@
{
"description": "CC0 RAW samples from raw.pixls.us (one per managed RAW decoder), fetched by 'Titano.Tools fixtures' into tests/fixtures/external (git-ignored, CI-cached on this file). sha256 null: the first download records its hash in external/recorded-hashes.json and prints it for pinning here. width/height: size the managed decoder develops (before orientation). urlVerified false: the URL follows the site's data/<make>/<model>/ layout but was written without network access; replace it with the sample's download link if the fetch reports 404.",
"license": "CC0-1.0",
"files": [
{
"name": "google-pixel-4a.dng",
"url": "https://raw.pixls.us/data/Google/Pixel%204a/PXL_20201101_120000000.dng",
"sha256": null,
"size": null,
"format": "Dng",
"make": "Google",
"model": "Pixel 4a",
"width": 4032,
"height": 3024,
"urlVerified": false
},
{
"name": "canon-eos-5d-mark-iii.cr2",
"url": "https://raw.pixls.us/data/Canon/EOS%205D%20Mark%20III/IMG_0001.CR2",
"sha256": null,
"size": null,
"format": "Cr2",
"make": "Canon",
"model": "Canon EOS 5D Mark III",
"width": 5760,
"height": 3840,
"urlVerified": false
},
{
"name": "nikon-d850.nef",
"url": "https://raw.pixls.us/data/Nikon/D850/DSC_0001.NEF",
"sha256": null,
"size": null,
"format": "Nef",
"make": "NIKON CORPORATION",
"model": "NIKON D850",
"width": 8288,
"height": 5520,
"urlVerified": false
},
{
"name": "sony-ilce-7m3.arw",
"url": "https://raw.pixls.us/data/Sony/ILCE-7M3/DSC00001.ARW",
"sha256": null,
"size": null,
"format": "Arw",
"make": "SONY",
"model": "ILCE-7M3",
"width": 6048,
"height": 4024,
"urlVerified": false
},
{
"name": "fujifilm-x-t2.raf",
"url": "https://raw.pixls.us/data/Fujifilm/X-T2/DSCF0001.RAF",
"sha256": null,
"size": null,
"format": "Raf",
"make": "FUJIFILM",
"model": "X-T2",
"width": 6000,
"height": 4000,
"urlVerified": false
},
{
"name": "pentax-k-1.pef",
"url": "https://raw.pixls.us/data/Pentax/K-1/IMGP0001.PEF",
"sha256": null,
"size": null,
"format": "Pef",
"make": "RICOH IMAGING COMPANY, LTD.",
"model": "PENTAX K-1",
"width": 7392,
"height": 4950,
"urlVerified": false
}
]
}