diff --git a/CHANGELOG.md b/CHANGELOG.md index a535d27..fdd8377 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,3 +35,7 @@ change between minor versions. 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. +- The white balance of the shot: `RawMetadata.WhiteBalance` and `RawImage.WhiteBalance`, a `RawWhiteBalance` with the + multipliers of the red, two green and blue photosites and where they were read (`RawWhiteBalanceSource`), taken from the plain + record of the Nikon MakerNote. It is null when the file holds none or one that is not plausible (non-positive, tiny or very large + multipliers). It is not applied to the samples. The record that Nikon cameras scramble with the serial number is not read yet. diff --git a/src/Eleris.RawNet/Internal/NefStructureReader.cs b/src/Eleris.RawNet/Internal/NefStructureReader.cs index 317e2ea..c09ba2e 100644 --- a/src/Eleris.RawNet/Internal/NefStructureReader.cs +++ b/src/Eleris.RawNet/Internal/NefStructureReader.cs @@ -13,8 +13,9 @@ 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, NikonBlackLevelTag = 0x3D; + private const ushort NikonSerialTag = 0x1D, NikonActiveAreaTag = 0x45, NikonShutterCountTag = 0xA7, NikonCompressionTag = 0x96, NikonBlackLevelTag = 0x3D, NikonWhiteBalanceTag = 0x0C; private const int NikonHeaderBytes = 10; + private const double MaxWhiteBalanceMultiplier = 64; private const int CfaPhotometric = 32803; private const int MaxSubDirectories = 64; private const int MaxStrips = 65536; @@ -108,6 +109,7 @@ public NefStructure Read(ByteSource source) ImageWidth = raw.Width, ImageHeight = raw.Height, ActiveArea = activeArea, + WhiteBalance = ReadWhiteBalance(makerNote), BlackLevel = raw.Pattern == CfaPattern.Rggb && raw.Bits == 14 ? ReadBlackLevel(makerNote, raw.Bits) : null, CfaPattern = raw.Pattern, BitsPerSample = raw.Bits, @@ -349,6 +351,26 @@ 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 rationals in the order red, blue, green, green; a value outside 1/64 to 64 makes the record unusable. + private static RawWhiteBalance? ReadWhiteBalance((TiffReader Reader, Ifd Directory)? note) + { + if (note is not { } n || !n.Directory.TryGet(NikonWhiteBalanceTag, out IfdEntry entry) || entry.Count != 4) + { + return null; + } + + Span v = stackalloc double[4]; + for (int i = 0; i < 4; i++) + { + if (!n.Reader.TryReadRational(entry, i, out v[i]) || !(v[i] >= 1 / MaxWhiteBalanceMultiplier && v[i] <= MaxWhiteBalanceMultiplier)) + { + return null; + } + } + + return new RawWhiteBalance(v[0], v[2], v[3], v[1], RawWhiteBalanceSource.NikonMakerNoteLevels); + } + // 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) { diff --git a/src/Eleris.RawNet/RawFile.cs b/src/Eleris.RawNet/RawFile.cs index 2a776f9..20fbffe 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, metadata.BlackLevel, mosaic); + return new RawImage(metadata.ImageWidth, metadata.ImageHeight, metadata.ActiveArea, metadata.CfaPattern, metadata.BitsPerSample, metadata.BlackLevel, metadata.WhiteBalance, 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 013edb7..d3c2d4f 100644 --- a/src/Eleris.RawNet/RawImage.cs +++ b/src/Eleris.RawNet/RawImage.cs @@ -6,7 +6,7 @@ namespace Eleris.RawNet; /// public sealed class RawImage { - internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfaPattern, int bitsPerSample, RawBlackLevel? blackLevel, ushort[] mosaic) + internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfaPattern, int bitsPerSample, RawBlackLevel? blackLevel, RawWhiteBalance? whiteBalance, ushort[] mosaic) { Width = width; Height = height; @@ -14,6 +14,7 @@ internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfa CfaPattern = cfaPattern; BitsPerSample = bitsPerSample; BlackLevel = blackLevel; + WhiteBalance = whiteBalance; Mosaic = mosaic; } @@ -35,6 +36,9 @@ internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfa /// 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 as-shot white balance, or null (see ); it is not applied to the samples. + public RawWhiteBalance? WhiteBalance { 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 cbb2b5c..f19f44d 100644 --- a/src/Eleris.RawNet/RawMetadata.cs +++ b/src/Eleris.RawNet/RawMetadata.cs @@ -73,6 +73,9 @@ private bool PrintMembers(System.Text.StringBuilder builder) /// 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 as-shot white balance: the multipliers the camera would apply to the samples of each channel (read from the plain record of the Nikon MakerNote, the record holds them in the order red, blue, green, green), or null when the file holds none or one that is not plausible. The order of the red and blue values of the record is the documented one; it cannot be checked on near-neutral files. The samples are not changed by it. + public RawWhiteBalance? WhiteBalance { 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/src/Eleris.RawNet/RawWhiteBalance.cs b/src/Eleris.RawNet/RawWhiteBalance.cs new file mode 100644 index 0000000..79d5083 --- /dev/null +++ b/src/Eleris.RawNet/RawWhiteBalance.cs @@ -0,0 +1,25 @@ +namespace Eleris.RawNet; + +/// Where the white balance of a comes from. +public enum RawWhiteBalanceSource +{ + /// Not known; the value of a default instance. + Unknown = 0, + + /// The camera recorded the multipliers in plain form in the Nikon MakerNote. + NikonMakerNoteLevels = 1, +} + +/// +/// The as-shot white balance: the multipliers the camera would apply to the samples of each channel of the raw mosaic to bring +/// them to a neutral grey, as it recorded them. They are not applied to the samples, and not normalised by the library (a camera +/// usually records them relative to green, so green is near 1). The channels are listed in the order of a red, green, green, +/// blue pattern. +/// +/// The multiplier of the red photosites. +/// The multiplier of the first green value of the record. The two green values are equal on every camera +/// file checked, so which green photosite each one belongs to is not established. +/// The multiplier of the second green value of the record. +/// The multiplier of the blue photosites. +/// Where the values were read. +public readonly record struct RawWhiteBalance(double Red, double Green1, double Green2, double Blue, RawWhiteBalanceSource Source); diff --git a/tests/Eleris.RawNet.Tests/WhiteBalanceTests.cs b/tests/Eleris.RawNet.Tests/WhiteBalanceTests.cs new file mode 100644 index 0000000..66c8b98 --- /dev/null +++ b/tests/Eleris.RawNet.Tests/WhiteBalanceTests.cs @@ -0,0 +1,120 @@ +using Eleris.RawNet.Tests.Synthetic; + +namespace Eleris.RawNet.Tests; + +public class WhiteBalanceTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void The_multipliers_are_read_from_the_record_of_the_maker_note(bool bigEndian) + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { BigEndian = bigEndian })); + + RawWhiteBalance balance = raw.Metadata.WhiteBalance!.Value; + + Assert.Equal(854 / 512.0, balance.Red); + Assert.Equal(683 / 512.0, balance.Blue); + Assert.Equal(1.0, balance.Green1); + Assert.Equal(1.0, balance.Green2); + Assert.Equal(RawWhiteBalanceSource.NikonMakerNoteLevels, balance.Source); + } + + [Fact] + public void The_order_of_the_record_is_red_blue_green_green() + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { WhiteBalance = [(2, 1), (3, 1), (5, 4), (7, 4)] })); + + Assert.Equal(new RawWhiteBalance(2, 1.25, 1.75, 3, RawWhiteBalanceSource.NikonMakerNoteLevels), raw.Metadata.WhiteBalance); + } + + [Theory] + [InlineData(0u, 1u, 0)] + [InlineData(1u, 0u, 1)] + [InlineData(1000u, 1u, 2)] + [InlineData(1u, 4294967295u, 3)] + [InlineData(65u, 1u, 0)] + [InlineData(1u, 65u, 1)] + public void A_record_with_an_impossible_multiplier_is_no_white_balance(uint numerator, uint denominator, int position) + { + var record = new (uint, uint)[] { (2, 1), (3, 1), (1, 1), (1, 1) }; + record[position] = (numerator, denominator); + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { WhiteBalance = record })); + + Assert.Null(raw.Metadata.WhiteBalance); + } + + [Theory] + [InlineData(64u, 1u)] + [InlineData(1u, 64u)] + public void The_limits_of_the_plausible_range_are_accepted(uint numerator, uint denominator) + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { WhiteBalance = [(numerator, denominator), (numerator, denominator), (numerator, denominator), (numerator, denominator)] })); + + Assert.NotNull(raw.Metadata.WhiteBalance); + } + + [Theory] + [InlineData(0)] + [InlineData(3)] + [InlineData(5)] + public void A_record_that_does_not_hold_four_values_is_no_white_balance(int count) + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { WhiteBalance = [.. Enumerable.Repeat((2u, 1u), count)] })); + + Assert.Null(raw.Metadata.WhiteBalance); + } + + [Fact] + public void The_decoded_image_carries_the_white_balance() + { + byte[] file = SyntheticNef.Build(new SyntheticNefOptions + { + RawWidth = 16, + RawHeight = 8, + BitsPerSample = 14, + Compression = 1, + ActiveArea = [0, 0, 16, 8], + RawStrip = DecodeTests.Pack(new ushort[16 * 8], 16, 14), + }); + using RawFile raw = RawFile.Open(file); + + RawImage image = raw.Decode(); + + Assert.Equal(raw.Metadata.WhiteBalance, image.WhiteBalance); + Assert.NotNull(image.WhiteBalance); + } + + [Fact] + public void A_default_white_balance_has_an_unknown_source() + { + Assert.Equal(RawWhiteBalanceSource.Unknown, default(RawWhiteBalance).Source); + } + + [Fact] + public void A_white_balance_is_read_whatever_the_colour_filter_pattern() + { + using RawFile raw = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { CfaPattern = [1, 0, 2, 1] })); + + Assert.NotNull(raw.Metadata.WhiteBalance); + } + + [SkippableFact] + public void Every_real_file_has_a_plausible_white_balance() + { + 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) + { + RawWhiteBalance balance = RawFile.ReadMetadata(path).WhiteBalance + ?? throw new Xunit.Sdk.XunitException("A real file has no white balance."); + Assert.InRange(balance.Red, 0.5, 8); + Assert.InRange(balance.Blue, 0.5, 8); + Assert.InRange(balance.Green1, 0.5, 2); + Assert.InRange(balance.Green2, 0.5, 2); + } + } +}