Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
24 changes: 23 additions & 1 deletion src/Eleris.RawNet/Internal/NefStructureReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<double> 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)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Eleris.RawNet/RawFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public RawImage Decode(CancellationToken cancellationToken = default)
RawMetadata metadata = Metadata;
ushort[] mosaic = GC.AllocateUninitializedArray<ushort>(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);
}

/// <summary>Decodes the raw image into a buffer of the caller, row after row, without allocating the mosaic.</summary>
Expand Down
6 changes: 5 additions & 1 deletion src/Eleris.RawNet/RawImage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ namespace Eleris.RawNet;
/// </summary>
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;
ActiveArea = activeArea;
CfaPattern = cfaPattern;
BitsPerSample = bitsPerSample;
BlackLevel = blackLevel;
WhiteBalance = whiteBalance;
Mosaic = mosaic;
}

Expand All @@ -35,6 +36,9 @@ internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfa
/// <summary>The black level the camera recorded, or null when the file holds none or the library does not read it (see <see cref="RawMetadata.BlackLevel"/>); it is not subtracted from the samples.</summary>
public RawBlackLevel? BlackLevel { get; }

/// <summary>The as-shot white balance, or null (see <see cref="RawMetadata.WhiteBalance"/>); it is not applied to the samples.</summary>
public RawWhiteBalance? WhiteBalance { get; }

/// <summary>The samples, row after row, <see cref="Width"/> times <see cref="Height"/> of them.</summary>
public ReadOnlyMemory<ushort> Mosaic { get; }
}
3 changes: 3 additions & 0 deletions src/Eleris.RawNet/RawMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ private bool PrintMembers(System.Text.StringBuilder builder)
/// <summary>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.</summary>
public RawBlackLevel? BlackLevel { get; init; }

/// <summary>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.</summary>
public RawWhiteBalance? WhiteBalance { get; init; }

/// <summary>The colour filter pattern from the top-left pixel of the raw image (not of the active area).</summary>
public required CfaPattern CfaPattern { get; init; }

Expand Down
25 changes: 25 additions & 0 deletions src/Eleris.RawNet/RawWhiteBalance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Eleris.RawNet;

/// <summary>Where the white balance of a <see cref="RawWhiteBalance"/> comes from.</summary>
public enum RawWhiteBalanceSource
{
/// <summary>Not known; the value of a default instance.</summary>
Unknown = 0,

/// <summary>The camera recorded the multipliers in plain form in the Nikon MakerNote.</summary>
NikonMakerNoteLevels = 1,
}

/// <summary>
/// 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.
/// </summary>
/// <param name="Red">The multiplier of the red photosites.</param>
/// <param name="Green1">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.</param>
/// <param name="Green2">The multiplier of the second green value of the record.</param>
/// <param name="Blue">The multiplier of the blue photosites.</param>
/// <param name="Source">Where the values were read.</param>
public readonly record struct RawWhiteBalance(double Red, double Green1, double Green2, double Blue, RawWhiteBalanceSource Source);
120 changes: 120 additions & 0 deletions tests/Eleris.RawNet.Tests/WhiteBalanceTests.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
}