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
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,11 @@ change between minor versions.
- Decoding of an uncompressed raw image (12 or 14 bits per sample, packed most significant bit first, each row on a byte
boundary): `RawFile.Decode()` gives a `RawImage` (the mosaic of `ushort`, its size, active area, colour filter pattern and bit
depth), and `Decode(Span<ushort>)` fills a buffer of the caller. The Nikon compression is reported with an
`UnsupportedCompressionException` until it is decoded. The packing follows the TIFF rules; it is checked with synthetic files
`UnsupportedCompressionException` unless it is the lossless variant (see below). The packing follows the TIFF rules; it is checked with synthetic files
and has not yet been checked on a camera file.
- Decoding of the lossless Nikon compression (TIFF compression 34713, 12 and 14 bits), through the same `RawFile.Decode`. The
format facts it relies on (the prefix codes, the bit order, the difference and prediction rules, the compression record of
the MakerNote) are written in the documentation of `NikonLosslessDecoder`; the code is written from them. Checked on 570 real
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`.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ if (file.Previews.Count > 0)
}
```

An uncompressed raw image is decoded to its mosaic of 16-bit samples, unscaled; the Nikon compression is not decoded yet:
The raw image is decoded to its mosaic of 16-bit samples, unscaled (uncompressed, and the lossless Nikon compression of 12 and 14 bit images):

```csharp
RawImage image = file.Decode(); // image.Mosaic, Width, Height, ActiveArea, CfaPattern
Expand All @@ -56,7 +56,7 @@ file.Decode(mine); // or into a buffer
```

What is implemented, and what is next, is tracked in the [issues](https://github.com/sputier/raw-net/issues): the metadata, the
previews and the uncompressed mosaic work today; the Nikon compression comes next.
previews and the mosaic work today; the levels and the white balance come next.

## Build and test

Expand Down
34 changes: 34 additions & 0 deletions benchmarks/Eleris.RawNet.Benchmarks/DecodeBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using BenchmarkDotNet.Attributes;

namespace Eleris.RawNet.Benchmarks;

/// <summary>
/// Decoding the raw image of the first file of the folder named by RAWNET_SAMPLES_DIR (read only) into a buffer that is reused.
/// Without the variable the benchmarks do nothing.
/// </summary>
[MemoryDiagnoser]
public class DecodeBenchmarks
{
private RawFile? _file;
private ushort[] _buffer = [];

[GlobalSetup]
public void Setup()
{
string? directory = Environment.GetEnvironmentVariable("RAWNET_SAMPLES_DIR");
string? path = !string.IsNullOrEmpty(directory) && Directory.Exists(directory)
? Directory.EnumerateFiles(directory, "*.NEF").Order(StringComparer.Ordinal).FirstOrDefault()
: null;
if (path is not null)
{
_file = RawFile.Open(path);
_buffer = new ushort[_file.Metadata.ImageWidth * _file.Metadata.ImageHeight];
}
}

[GlobalCleanup]
public void Cleanup() => _file?.Dispose();

[Benchmark]
public int IntoBuffer() => _file is null ? 0 : _file.Decode(_buffer);
}
15 changes: 14 additions & 1 deletion src/Eleris.RawNet/Internal/NefStructure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,24 @@ namespace Eleris.RawNet.Internal;
/// <param name="Length">The number of bytes.</param>
internal readonly record struct ByteRange(long Offset, long Length);

/// <summary>
/// The start of the Nikon "linearization" record of the MakerNote (tag 0x96), which tells how the raw image is compressed: two
/// version bytes, then the four starting values of the predictors.
/// </summary>
internal readonly record struct NikonCompressionHeader(byte Version0, byte Version1, ushort Predictor0, ushort Predictor1, ushort Predictor2, ushort Predictor3)
{
/// <summary>The first version byte of the lossless variant.</summary>
public const byte LosslessVersion = 0x46;

public bool IsLossless => Version0 == LosslessVersion;
}

/// <summary>What the structure of a NEF file says: the metadata, and where the raw image is stored.</summary>
/// <param name="Metadata">The metadata of the file.</param>
/// <param name="RawStrips">The strips of the raw image, in order.</param>
/// <param name="Previews">The JPEG previews that lie inside the file, largest first.</param>
internal sealed record NefStructure(RawMetadata Metadata, IReadOnlyList<ByteRange> RawStrips, IReadOnlyList<ByteRange> Previews);
/// <param name="CompressionHeader">The Nikon compression record of the MakerNote, or null if the file has none.</param>
internal sealed record NefStructure(RawMetadata Metadata, IReadOnlyList<ByteRange> RawStrips, IReadOnlyList<ByteRange> Previews, NikonCompressionHeader? CompressionHeader = null);

/// <summary>
/// Reads the structure of a NEF file. It is a seam: the implementation of the library reads the TIFF directories itself, and
Expand Down
21 changes: 19 additions & 2 deletions src/Eleris.RawNet/Internal/NefStructureReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ 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;
private const ushort NikonSerialTag = 0x1D, NikonActiveAreaTag = 0x45, NikonShutterCountTag = 0xA7, NikonCompressionTag = 0x96;
private const int NikonHeaderBytes = 10;
private const int CfaPhotometric = 32803;
private const int MaxSubDirectories = 64;
private const int MaxStrips = 65536;
Expand Down Expand Up @@ -73,6 +74,22 @@ public NefStructure Read(ByteSource source)
}
}

NikonCompressionHeader? compression = null;
if (makerNote is { } header
&& header.Directory.TryGet(NikonCompressionTag, out IfdEntry compressionEntry)
&& compressionEntry.ByteLength >= NikonHeaderBytes)
{
Span<byte> bytes = stackalloc byte[NikonHeaderBytes];
source.ReadExactly(compressionEntry.ValueOffset, bytes);
compression = new NikonCompressionHeader(
bytes[0],
bytes[1],
header.Reader.ReadUInt16(bytes[2..]),
header.Reader.ReadUInt16(bytes[4..]),
header.Reader.ReadUInt16(bytes[6..]),
header.Reader.ReadUInt16(bytes[8..]));
}

var metadata = new RawMetadata
{
MediaType = RawMediaTypes.NikonNef,
Expand All @@ -96,7 +113,7 @@ public NefStructure Read(ByteSource source)
Compression = Enum.IsDefined<RawCompression>((RawCompression)raw.Compression) ? (RawCompression)raw.Compression : RawCompression.Unknown,
CompressionCode = raw.Compression,
};
return new NefStructure(metadata, raw.Strips, LargestFirst(previews));
return new NefStructure(metadata, raw.Strips, LargestFirst(previews), compression);
}

// The previews, largest first, each place once (a preview can be listed by several directories).
Expand Down
245 changes: 245 additions & 0 deletions src/Eleris.RawNet/Internal/NikonLosslessDecoder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
using System.Buffers;
using System.Buffers.Binary;

namespace Eleris.RawNet.Internal;

/// <summary>
/// Decodes the lossless variant of the Nikon compression (TIFF compression 34713). The facts of the format it relies on:
/// <list type="bullet">
/// <item>The samples of the image are stored row after row in one bit stream, most significant bit first, with no padding
/// between rows and no stuffing.</item>
/// <item>Each sample is a difference from a prediction: a prefix code gives the number n of bits that follow, then n bits give
/// the difference in the usual JPEG way (a value whose top bit is clear stands for that value minus 2^n minus 1).</item>
/// <item>For the first two samples of a row the prediction is the first or second sample two rows above (the rows alternate
/// between two pairs of starting values); for the others it is the sample two positions to the left, in the same row. The four
/// starting values are in the compression record of the MakerNote.</item>
/// <item>The prefix code is a canonical one given by the number of codes of each length 1 to 16 and the list of the symbols in
/// code order; there is one for 12 bit samples and one for 14 bit samples.</item>
/// <item>The record of the lossless variant holds no linearization curve: the decoded values are the samples.</item>
/// </list>
/// </summary>
internal static class NikonLosslessDecoder
{
private const int BufferBytes = 1 << 18;

// Number of codes of each length (1 to 16), then the symbols (the number of bits that follow) in code order.
internal static readonly byte[] Counts12 = [0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0];
internal static readonly byte[] Symbols12 = [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12];
internal static readonly byte[] Counts14 = [0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0];
internal static readonly byte[] Symbols14 = [7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14];

private static readonly int MaxLength12 = MaxLengthOf(Counts12), MaxLength14 = MaxLengthOf(Counts14);
private static readonly ushort[] Table12 = BuildTable(Counts12, Symbols12, MaxLength12);
private static readonly ushort[] Table14 = BuildTable(Counts14, Symbols14, MaxLength14);

public static bool IsSupported(int bitsPerSample) => bitsPerSample is 12 or 14;

private static readonly int MinBits12 = MinBitsOf(Counts12, Symbols12), MinBits14 = MinBitsOf(Counts14, Symbols14);

/// <summary>The fewest bytes a stream of the lossless format can have for an image: every sample takes at least the bits of its shortest code with its difference.</summary>
public static long MinimumBytes(int width, int height, int bitsPerSample) =>
(((long)width * height * (bitsPerSample == 12 ? MinBits12 : MinBits14)) + 7) / 8;

/// <summary>
/// Decodes the image into <paramref name="destination"/> and returns the number of bytes of the strips the stream used.
/// </summary>
public static long Decode(ByteSource source, NefStructure structure, NikonCompressionHeader header, Span<ushort> destination, CancellationToken cancellationToken)
{
RawMetadata metadata = structure.Metadata;
int width = metadata.ImageWidth, height = metadata.ImageHeight, bits = metadata.BitsPerSample;
ushort[] table = bits == 12 ? Table12 : Table14;
int tableBits = bits == 12 ? MaxLength12 : MaxLength14;
uint limit = 1u << bits;
long total = 0;
foreach (ByteRange strip in structure.RawStrips)
{
total += strip.Length;
}

var stream = new StripStream(source, structure.RawStrips);
byte[] buffer = ArrayPool<byte>.Shared.Rent(BufferBytes);
try
{
var reader = new BitReader(stream, buffer);
Span<int> vertical = [header.Predictor0, header.Predictor1, header.Predictor2, header.Predictor3];
for (int row = 0; row < height; row++)
{
cancellationToken.ThrowIfCancellationRequested();

Span<ushort> line = destination.Slice(row * width, width);
int h0 = 0, h1 = 0;
for (int col = 0; col < width; col++)
{
reader.Ensure();
ushort entry = table[reader.Peek(tableBits)];
int length = entry >> 8;
if (length == 0)
{
throw new CorruptRawFileException("The compressed raw image holds a code that does not exist", null);
}

reader.Skip(length);
int count = entry & 0xFF;
int difference = 0;
if (count > 0)
{
difference = (int)reader.Peek(count);
reader.Skip(count);
if (difference < (1 << (count - 1)))
{
difference -= (1 << count) - 1;
}
}

int value;
if (col < 2)
{
ref int predictor = ref vertical[((row & 1) * 2) + col];
predictor += difference;
value = predictor;
if (col == 0)
{
h0 = value;
}
else
{
h1 = value;
}
}
else if ((col & 1) == 0)
{
h0 += difference;
value = h0;
}
else
{
h1 += difference;
value = h1;
}

if ((uint)value >= limit)
{
throw new CorruptRawFileException("The compressed raw image holds a sample out of range", null);
}

line[col] = (ushort)value;
}
}

long used = reader.BytesUsed;
if (used > total)
{
throw new CorruptRawFileException("The compressed raw image goes beyond the end of its strips", null);
}

return used;
}
catch (EndOfStreamException ex)
{
throw new CorruptRawFileException("The file ends inside the raw image", null, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}

private static int MaxLengthOf(byte[] counts) => Array.FindLastIndex(counts, c => c > 0) + 1;

private static int MinBitsOf(byte[] counts, byte[] symbols)
{
int min = int.MaxValue, next = 0;
for (int length = 1; length <= counts.Length; length++)
{
for (int i = 0; i < counts[length - 1]; i++)
{
min = Math.Min(min, length + symbols[next++]);
}
}

return min;
}

/// <summary>A lookup table indexed by the next <c>maxLength</c> bits: the length of the code in the high byte, its symbol in the low byte; zero for no code.</summary>
private static ushort[] BuildTable(byte[] counts, byte[] symbols, int maxLength)
{

ushort[] table = new ushort[1 << maxLength];
int code = 0, next = 0;
for (int length = 1; length <= maxLength; length++)
{
for (int i = 0; i < counts[length - 1]; i++)
{
int first = code << (maxLength - length);
for (int j = 0; j < 1 << (maxLength - length); j++)
{
table[first + j] = (ushort)((length << 8) | symbols[next]);
}

code++;
next++;
}

code <<= 1;
}

return table;
}

/// <summary>Reads bits, most significant first, from the strips through a buffer. Past the end of the data it supplies zeros.</summary>
private ref struct BitReader(StripStream stream, byte[] buffer)
{
private ulong _bits;
private int _held;
private int _position;
private int _end;
private long _fed;

/// <summary>The number of bytes of the stream that were consumed.</summary>
public readonly long BytesUsed => ((_fed * 8) - _held + 7) / 8;

/// <summary>Makes sure at least 32 bits are held.</summary>
public void Ensure()
{
if (_held > 32)
{
return;
}

if (_end - _position < 4)
{
Refill();
}

_bits = (_bits << 32) | BinaryPrimitives.ReadUInt32BigEndian(buffer.AsSpan(_position, 4));
_position += 4;
_fed += 4;
_held += 32;
}

public readonly uint Peek(int count) => (uint)(_bits >> (_held - count)) & ((1u << count) - 1);

public void Skip(int count) => _held -= count;

private void Refill()
{
int left = _end - _position;
buffer.AsSpan(_position, left).CopyTo(buffer);
_position = 0;
_end = left;
while (_end < 4)
{
int read = stream.Read(buffer.AsSpan(_end, buffer.Length - _end));
if (read == 0)
{
// Past the last strip: zeros; the caller detects that more bits were used than the strips hold.
buffer.AsSpan(_end, 4 - _end).Clear();
_end = 4;
break;
}

_end += read;
}
}
}
}
Loading