diff --git a/CHANGELOG.md b/CHANGELOG.md index fa78a30..a535d27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,3 +31,7 @@ change between minor versions. files of a Nikon Z 6 (every row decoded, every sample in range, the stream ending at the end of its strip), by an encoder-decoder round trip on synthetic files, and with damaged files. Decoding a 24-megapixel image into a reused buffer takes about 0.26 s and allocates nothing but a few bytes. The lossy variant is reported with an `UnsupportedCompressionException`. +- The black level recorded by the camera: `RawMetadata.BlackLevel` and `RawImage.BlackLevel`, a `RawBlackLevel` with the value of + each of the four photosites of the colour filter pattern (in the order of the pattern, which for a red, green, green, blue + pattern is red, green, green, blue) and `At(column, row)`. It is null when the file holds none or one that does not fit the + samples, and it is only read for a red, green, green, blue pattern and 14 bit samples (the layout checked on camera files). It is not subtracted from the samples. On the 570 real files of a Nikon Z 6 the four values are present and equal. diff --git a/src/Eleris.RawNet/Internal/NefStructureReader.cs b/src/Eleris.RawNet/Internal/NefStructureReader.cs index 4c943a0..317e2ea 100644 --- a/src/Eleris.RawNet/Internal/NefStructureReader.cs +++ b/src/Eleris.RawNet/Internal/NefStructureReader.cs @@ -13,7 +13,7 @@ internal sealed class NefStructureReader : INefStructureReader private const ushort JpegOffsetTag = 513, JpegLengthTag = 514; private const int MaxPreviewBytes = 64 * 1024 * 1024; private const ushort NikonPreviewTag = 0x11; - private const ushort NikonSerialTag = 0x1D, NikonActiveAreaTag = 0x45, NikonShutterCountTag = 0xA7, NikonCompressionTag = 0x96; + private const ushort NikonSerialTag = 0x1D, NikonActiveAreaTag = 0x45, NikonShutterCountTag = 0xA7, NikonCompressionTag = 0x96, NikonBlackLevelTag = 0x3D; private const int NikonHeaderBytes = 10; private const int CfaPhotometric = 32803; private const int MaxSubDirectories = 64; @@ -108,6 +108,7 @@ public NefStructure Read(ByteSource source) ImageWidth = raw.Width, ImageHeight = raw.Height, ActiveArea = activeArea, + BlackLevel = raw.Pattern == CfaPattern.Rggb && raw.Bits == 14 ? ReadBlackLevel(makerNote, raw.Bits) : null, CfaPattern = raw.Pattern, BitsPerSample = raw.Bits, Compression = Enum.IsDefined((RawCompression)raw.Compression) ? (RawCompression)raw.Compression : RawCompression.Unknown, @@ -348,6 +349,28 @@ private static RawRectangle ReadActiveArea((TiffReader Reader, Ifd Directory)? n return fits ? new RawRectangle((int)v[0], (int)v[1], (int)v[2], (int)v[3]) : whole; } + // Four values, one per photosite of the 2 x 2 pattern. Only asked for the layout that was checked on camera files (a red, green, green, blue pattern and 14 bit samples): for another pattern the order of the values (by colour or by position) and for another depth their scale are not established; a missing, short or implausible record is no black level. + private static RawBlackLevel? ReadBlackLevel((TiffReader Reader, Ifd Directory)? note, int bits) + { + if (note is not { } n || !n.Directory.TryGet(NikonBlackLevelTag, out IfdEntry entry) || entry.Count != 4) + { + return null; + } + + Span v = stackalloc int[4]; + for (int i = 0; i < 4; i++) + { + if (!n.Reader.TryReadInteger(entry, i, out long value) || value < 0 || value >= (1L << bits)) + { + return null; + } + + v[i] = (int)value; + } + + return new RawBlackLevel(v[0], v[1], v[2], v[3]); + } + private static long? Integer(TiffReader reader, Ifd directory, ushort tag) => directory.TryGet(tag, out IfdEntry entry) && reader.TryReadInteger(entry, 0, out long value) ? value : null; diff --git a/src/Eleris.RawNet/RawBlackLevel.cs b/src/Eleris.RawNet/RawBlackLevel.cs new file mode 100644 index 0000000..bed6ddb --- /dev/null +++ b/src/Eleris.RawNet/RawBlackLevel.cs @@ -0,0 +1,25 @@ +namespace Eleris.RawNet; + +/// +/// The black level the camera recorded: the value a sample takes in the dark, for each of the four photosites of the 2 x 2 +/// colour filter pattern, in the order of the pattern read from its top-left photosite (row by row), which for a red, green, +/// green, blue pattern is red, green, green, blue. The values are in the units of the samples of the raw image. +/// +/// The level of the top-left photosite of the pattern. +/// The level of the top-right photosite. +/// The level of the bottom-left photosite. +/// The level of the bottom-right photosite. +public readonly record struct RawBlackLevel(int TopLeft, int TopRight, int BottomLeft, int BottomRight) +{ + /// The level of the photosite at a column and a row of the raw image, whose pattern starts at its top-left sample. + /// The column of the sample. + /// The row of the sample. + /// The black level that applies to it. + public int At(int column, int row) => ((column & 1) == 0, (row & 1) == 0) switch + { + (true, true) => TopLeft, + (false, true) => TopRight, + (true, false) => BottomLeft, + _ => BottomRight, + }; +} diff --git a/src/Eleris.RawNet/RawFile.cs b/src/Eleris.RawNet/RawFile.cs index b9a9c58..2a776f9 100644 --- a/src/Eleris.RawNet/RawFile.cs +++ b/src/Eleris.RawNet/RawFile.cs @@ -95,7 +95,7 @@ public RawImage Decode(CancellationToken cancellationToken = default) RawMetadata metadata = Metadata; ushort[] mosaic = GC.AllocateUninitializedArray(checked(metadata.ImageWidth * metadata.ImageHeight)); DecodeSamples(mosaic, cancellationToken); - return new RawImage(metadata.ImageWidth, metadata.ImageHeight, metadata.ActiveArea, metadata.CfaPattern, metadata.BitsPerSample, mosaic); + return new RawImage(metadata.ImageWidth, metadata.ImageHeight, metadata.ActiveArea, metadata.CfaPattern, metadata.BitsPerSample, metadata.BlackLevel, mosaic); } /// Decodes the raw image into a buffer of the caller, row after row, without allocating the mosaic. diff --git a/src/Eleris.RawNet/RawImage.cs b/src/Eleris.RawNet/RawImage.cs index 056cdd3..013edb7 100644 --- a/src/Eleris.RawNet/RawImage.cs +++ b/src/Eleris.RawNet/RawImage.cs @@ -6,13 +6,14 @@ namespace Eleris.RawNet; /// public sealed class RawImage { - internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfaPattern, int bitsPerSample, ushort[] mosaic) + internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfaPattern, int bitsPerSample, RawBlackLevel? blackLevel, ushort[] mosaic) { Width = width; Height = height; ActiveArea = activeArea; CfaPattern = cfaPattern; BitsPerSample = bitsPerSample; + BlackLevel = blackLevel; Mosaic = mosaic; } @@ -31,6 +32,9 @@ internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfa /// The number of bits of a sample: every sample is smaller than 1 << BitsPerSample. public int BitsPerSample { get; } + /// The black level the camera recorded, or null when the file holds none or the library does not read it (see ); it is not subtracted from the samples. + public RawBlackLevel? BlackLevel { get; } + /// The samples, row after row, times of them. public ReadOnlyMemory Mosaic { get; } } diff --git a/src/Eleris.RawNet/RawMetadata.cs b/src/Eleris.RawNet/RawMetadata.cs index 1caa96b..cbb2b5c 100644 --- a/src/Eleris.RawNet/RawMetadata.cs +++ b/src/Eleris.RawNet/RawMetadata.cs @@ -70,6 +70,9 @@ private bool PrintMembers(System.Text.StringBuilder builder) /// public required RawRectangle ActiveArea { get; init; } + /// The black level the camera recorded for the four photosites of the colour filter pattern, or null when the file holds none, or holds one that does not fit the samples of the image. It is only read for a red, green, green, blue pattern and 14 bit samples, the layout checked on camera files: for any other the order of the four values and their scale are not established. + public RawBlackLevel? BlackLevel { get; init; } + /// The colour filter pattern from the top-left pixel of the raw image (not of the active area). public required CfaPattern CfaPattern { get; init; } diff --git a/tests/Eleris.RawNet.Tests/BlackLevelTests.cs b/tests/Eleris.RawNet.Tests/BlackLevelTests.cs new file mode 100644 index 0000000..0ea5b06 --- /dev/null +++ b/tests/Eleris.RawNet.Tests/BlackLevelTests.cs @@ -0,0 +1,102 @@ +using Eleris.RawNet.Tests.Synthetic; + +namespace Eleris.RawNet.Tests; + +public class BlackLevelTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void The_black_level_of_the_four_photosites_is_read_in_the_order_of_the_pattern(bool bigEndian) + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { BlackLevel = [1008, 1010, 1012, 1014], BigEndian = bigEndian })); + + Assert.Equal(new RawBlackLevel(1008, 1010, 1012, 1014), raw.Metadata.BlackLevel); + } + + [Fact] + public void The_default_synthetic_file_has_the_black_level_of_a_Z6() + { + using RawFile raw = RawFile.Open(SyntheticNef.Build()); + + Assert.Equal(new RawBlackLevel(1008, 1008, 1008, 1008), raw.Metadata.BlackLevel); + } + + [Theory] + [InlineData(0)] + [InlineData(3)] + [InlineData(5)] + public void A_record_that_does_not_hold_four_values_is_no_black_level(int count) + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { BlackLevel = [.. Enumerable.Repeat((ushort)1008, count)] })); + + Assert.Null(raw.Metadata.BlackLevel); + } + + [Theory] + [InlineData(12, 0, 1, 1, 2)] + [InlineData(14, 1, 0, 2, 1)] + [InlineData(14, 1, 2, 0, 1)] + [InlineData(14, 2, 1, 1, 0)] + public void A_black_level_is_only_read_for_the_layout_that_was_checked_on_camera_files(int bits, byte a, byte b, byte c, byte d) + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { BlackLevel = [100, 100, 100, 100], BitsPerSample = bits, CfaPattern = [a, b, c, d] })); + + Assert.Null(raw.Metadata.BlackLevel); + } + + [Fact] + public void A_value_that_does_not_fit_the_samples_is_no_black_level() + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { BlackLevel = [1008, 1008, 1008, 1 << 14], BitsPerSample = 14 })); + Assert.Null(raw.Metadata.BlackLevel); + + using RawFile zero = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { BlackLevel = [0, 16383, 0, 16383] })); + Assert.Equal(new RawBlackLevel(0, 16383, 0, 16383), zero.Metadata.BlackLevel); + } + + [Fact] + public void The_level_of_a_sample_follows_its_place_in_the_pattern() + { + var level = new RawBlackLevel(1, 2, 3, 4); + + Assert.Equal([1, 2, 1, 2], new[] { level.At(0, 0), level.At(1, 0), level.At(2, 0), level.At(3, 2) }); + Assert.Equal([3, 4, 3, 4], new[] { level.At(0, 1), level.At(1, 1), level.At(2, 3), level.At(3, 5) }); + } + + [Fact] + public void The_decoded_image_carries_the_black_level() + { + ushort[] samples = new ushort[16 * 8]; + byte[] file = SyntheticNef.Build(new SyntheticNefOptions + { + RawWidth = 16, + RawHeight = 8, + BitsPerSample = 14, + Compression = 1, + ActiveArea = [0, 0, 16, 8], + BlackLevel = [10, 20, 30, 40], + RawStrip = DecodeTests.Pack(samples, 16, 14), + }); + using RawFile raw = RawFile.Open(file); + + Assert.Equal(new RawBlackLevel(10, 20, 30, 40), raw.Decode().BlackLevel); + } + + [SkippableFact] + public void Every_real_file_has_a_black_level_that_fits_its_samples() + { + string? directory = Environment.GetEnvironmentVariable("RAWNET_SAMPLES_DIR"); + Skip.If(string.IsNullOrEmpty(directory) || !Directory.Exists(directory), "RAWNET_SAMPLES_DIR is not set to a folder."); + string[] files = [.. Directory.EnumerateFiles(directory!, "*.NEF")]; + Skip.If(files.Length == 0, "No .NEF file in RAWNET_SAMPLES_DIR."); + + foreach (string path in files) + { + RawMetadata metadata = RawFile.ReadMetadata(path); + Assert.NotNull(metadata.BlackLevel); + RawBlackLevel level = metadata.BlackLevel.Value; + Assert.All(new[] { level.TopLeft, level.TopRight, level.BottomLeft, level.BottomRight }, v => Assert.InRange(v, 0, (1 << metadata.BitsPerSample) - 1)); + } + } +}