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 @@ -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.
25 changes: 24 additions & 1 deletion src/Eleris.RawNet/Internal/NefStructureReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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>((RawCompression)raw.Compression) ? (RawCompression)raw.Compression : RawCompression.Unknown,
Expand Down Expand Up @@ -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<int> 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;

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

/// <summary>
/// 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.
/// </summary>
/// <param name="TopLeft">The level of the top-left photosite of the pattern.</param>
/// <param name="TopRight">The level of the top-right photosite.</param>
/// <param name="BottomLeft">The level of the bottom-left photosite.</param>
/// <param name="BottomRight">The level of the bottom-right photosite.</param>
public readonly record struct RawBlackLevel(int TopLeft, int TopRight, int BottomLeft, int BottomRight)
{
/// <summary>The level of the photosite at a column and a row of the raw image, whose pattern starts at its top-left sample.</summary>
/// <param name="column">The column of the sample.</param>
/// <param name="row">The row of the sample.</param>
/// <returns>The black level that applies to it.</returns>
public int At(int column, int row) => ((column & 1) == 0, (row & 1) == 0) switch
{
(true, true) => TopLeft,
(false, true) => TopRight,
(true, false) => BottomLeft,
_ => BottomRight,
};
}
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, mosaic);
return new RawImage(metadata.ImageWidth, metadata.ImageHeight, metadata.ActiveArea, metadata.CfaPattern, metadata.BitsPerSample, metadata.BlackLevel, 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,13 +6,14 @@ namespace Eleris.RawNet;
/// </summary>
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;
}

Expand All @@ -31,6 +32,9 @@ internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfa
/// <summary>The number of bits of a sample: every sample is smaller than <c>1 &lt;&lt; BitsPerSample</c>.</summary>
public int BitsPerSample { get; }

/// <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 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 @@ -70,6 +70,9 @@ private bool PrintMembers(System.Text.StringBuilder builder)
/// </summary>
public required RawRectangle ActiveArea { get; init; }

/// <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 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
102 changes: 102 additions & 0 deletions tests/Eleris.RawNet.Tests/BlackLevelTests.cs
Original file line number Diff line number Diff line change
@@ -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));
}
}
}