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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ change between minor versions.
- The embedded JPEG previews: `RawFile.Previews` (largest first), `ReadPreviewJpeg()` for the largest, `ReadPreviewJpeg(preview)`
and a variant that fills a buffer of the caller without allocating. They are found in the sub-directories and in the Nikon
MakerNote; one that does not lie inside the file is left out, and data that does not start with a JPEG start-of-image marker is reported as corrupt.
- 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
and has not yet been checked on a camera file.
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,16 @@ if (file.Previews.Count > 0)
}
```

What is implemented, and what is next, is tracked in the [issues](https://github.com/sputier/raw-net/issues): the metadata and the
previews work today; the decoding of the raw mosaic comes next.
An uncompressed raw image is decoded to its mosaic of 16-bit samples, unscaled; the Nikon compression is not decoded yet:

```csharp
RawImage image = file.Decode(); // image.Mosaic, Width, Height, ActiveArea, CfaPattern
ushort[] mine = new ushort[m.ImageWidth * m.ImageHeight];
file.Decode(mine); // or into a buffer you reuse
```

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.

## Build and test

Expand Down
8 changes: 4 additions & 4 deletions src/Eleris.RawNet/Internal/NefStructureReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public NefStructure Read(ByteSource source)
}

var previews = new List<ByteRange>();
RawImage raw = ReadRawImage(reader, main, source.Length, previews);
RawSubImage raw = ReadRawImage(reader, main, source.Length, previews);
Ifd? exif = null;
if (main.TryGet(ExifTag, out IfdEntry exifEntry) && reader.TryReadInteger(exifEntry, 0, out long exifOffset))
{
Expand Down Expand Up @@ -122,9 +122,9 @@ internal static ByteRange[] LargestFirst(List<ByteRange> previews)
return result;
}

private sealed record RawImage(int Width, int Height, int Bits, int Compression, CfaPattern Pattern, ByteRange[] Strips);
private sealed record RawSubImage(int Width, int Height, int Bits, int Compression, CfaPattern Pattern, ByteRange[] Strips);

private static RawImage ReadRawImage(TiffReader reader, Ifd main, long fileLength, List<ByteRange> previews)
private static RawSubImage ReadRawImage(TiffReader reader, Ifd main, long fileLength, List<ByteRange> previews)
{
if (!main.TryGet(SubIfdsTag, out IfdEntry subEntry))
{
Expand Down Expand Up @@ -193,7 +193,7 @@ private static RawImage ReadRawImage(TiffReader reader, Ifd main, long fileLengt
throw new CorruptRawFileException("The raw image has an impossible compression code");
}

return new RawImage((int)w, (int)h, (int)bits, (int)compression, ReadPattern(reader, best), ReadStrips(reader, best, fileLength));
return new RawSubImage((int)w, (int)h, (int)bits, (int)compression, ReadPattern(reader, best), ReadStrips(reader, best, fileLength));
}

private static CfaPattern ReadPattern(TiffReader reader, Ifd raw)
Expand Down
134 changes: 134 additions & 0 deletions src/Eleris.RawNet/Internal/UncompressedDecoder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using System.Buffers;

namespace Eleris.RawNet.Internal;

/// <summary>
/// Decodes a raw image whose samples are stored as they are: the samples of a row follow one another, most significant bit first
/// and without padding between them, and each row starts on a byte boundary (the packing rules of TIFF for a sample size that is
/// not a whole number of bytes). The strips are read as one continuous run of bytes.
/// </summary>
internal static class UncompressedDecoder
{
private const int ChunkBytes = 1 << 20;

/// <summary>The sample sizes that are decoded.</summary>
public static bool IsSupported(int bitsPerSample) => bitsPerSample is 12 or 14;

/// <summary>The size in bytes of a row of <paramref name="width"/> samples.</summary>
public static long RowBytes(int width, int bitsPerSample) => (((long)width * bitsPerSample) + 7) / 8;

/// <summary>
/// Checks that the image can be decoded, before anything is allocated for it: its samples fit in an array, its strips do not
/// overlap (so the bytes they hold are distinct bytes of the file) and they hold the whole image.
/// </summary>
public static void CheckStrips(NefStructure structure)
{
RawMetadata metadata = structure.Metadata;
if ((long)metadata.ImageWidth * metadata.ImageHeight > Array.MaxLength)
{
throw new UnsupportedFormatException("The raw image has more samples than an array can hold.");
}

long needed = RowBytes(metadata.ImageWidth, metadata.BitsPerSample) * metadata.ImageHeight;
ByteRange[] sorted = [.. structure.RawStrips];
Array.Sort(sorted, static (a, b) => a.Offset.CompareTo(b.Offset));
long available = 0, end = 0;
foreach (ByteRange strip in sorted)
{
if (strip.Length > 0 && strip.Offset < end)
{
throw new CorruptRawFileException("The strips of the raw image overlap", strip.Offset);
}

end = Math.Max(end, strip.Offset + strip.Length);
available += strip.Length;
}

if (available < needed)
{
throw new CorruptRawFileException($"The raw image needs {needed} bytes and its strips hold {available}");
}
}

public static void Decode(ByteSource source, NefStructure structure, Span<ushort> destination, CancellationToken cancellationToken, int chunkBytes = ChunkBytes)
{
RawMetadata metadata = structure.Metadata;
int width = metadata.ImageWidth, height = metadata.ImageHeight, bits = metadata.BitsPerSample;
int rowBytes = checked((int)RowBytes(width, bits));
int rowsPerChunk = Math.Min(height, Math.Max(1, chunkBytes / rowBytes));
byte[] buffer = ArrayPool<byte>.Shared.Rent(checked(rowsPerChunk * rowBytes));
try
{
var stream = new StripStream(source, structure.RawStrips);
for (int row = 0; row < height; row += rowsPerChunk)
{
cancellationToken.ThrowIfCancellationRequested();
int rows = Math.Min(rowsPerChunk, height - row);
stream.ReadExactly(buffer.AsSpan(0, rows * rowBytes));
for (int r = 0; r < rows; r++)
{
Unpack(buffer.AsSpan(r * rowBytes, rowBytes), bits, destination.Slice((row + r) * width, width));
}
}
}
catch (EndOfStreamException ex)
{
throw new CorruptRawFileException("The file ends inside the raw image", null, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}

/// <summary>Unpacks the samples of a row, <paramref name="bits"/> bits each, most significant bit first.</summary>
internal static void Unpack(ReadOnlySpan<byte> row, int bits, Span<ushort> samples)
{
uint mask = (1u << bits) - 1;
ulong accumulator = 0;
int held = 0, next = 0;
for (int i = 0; i < samples.Length; i++)
{
while (held < bits)
{
accumulator = (accumulator << 8) | row[next++];
held += 8;
}

held -= bits;
samples[i] = (ushort)((uint)(accumulator >> held) & mask);
}
}

/// <summary>The strips of the raw image read as one continuous run of bytes.</summary>
private sealed class StripStream(ByteSource source, IReadOnlyList<ByteRange> strips)
{
private int _strip;
private long _used;

public void ReadExactly(Span<byte> destination)
{
while (destination.Length > 0)
{
if (_strip >= strips.Count)
{
throw new EndOfStreamException();
}

ByteRange range = strips[_strip];
long left = range.Length - _used;
if (left == 0)
{
_strip++;
_used = 0;
continue;
}

int count = (int)Math.Min(left, destination.Length);
source.ReadExactly(range.Offset + _used, destination[..count]);
_used += count;
destination = destination[count..];
}
}
}
}
61 changes: 61 additions & 0 deletions src/Eleris.RawNet/RawFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,49 @@ public int ReadPreviewJpeg(RawPreview preview, Span<byte> destination)
return preview.ByteCount;
}

/// <summary>Decodes the raw image into a new array.</summary>
/// <param name="cancellationToken">Cancels the decoding.</param>
/// <returns>The mosaic and what describes it.</returns>
/// <exception cref="UnsupportedCompressionException">The samples use a compression the library does not decode yet; only uncompressed samples are decoded for now.</exception>
/// <exception cref="UnsupportedFormatException">The samples have a size the library does not decode (12 and 14 bits are).</exception>
/// <exception cref="CorruptRawFileException">The strips of the raw image are too short for the image.</exception>
/// <exception cref="ObjectDisposedException">The file is disposed.</exception>
/// <exception cref="OperationCanceledException">The decoding was cancelled.</exception>
/// <remarks>The array of a full-frame image is tens of megabytes; to decode many images, use <see cref="Decode(Span{ushort}, CancellationToken)"/> with a buffer you reuse.</remarks>
public RawImage Decode(CancellationToken cancellationToken = default)
{
PrepareDecode();
RawMetadata metadata = Metadata;
ushort[] mosaic = GC.AllocateUninitializedArray<ushort>(checked(metadata.ImageWidth * metadata.ImageHeight));
UncompressedDecoder.Decode(_source, _structure, mosaic, cancellationToken);
return new RawImage(metadata.ImageWidth, metadata.ImageHeight, metadata.ActiveArea, metadata.CfaPattern, metadata.BitsPerSample, mosaic);
}

/// <summary>Decodes the raw image into a buffer of the caller, row after row, without allocating the mosaic.</summary>
/// <param name="destination">The buffer; it must hold at least <see cref="RawMetadata.ImageWidth"/> times <see cref="RawMetadata.ImageHeight"/> samples.</param>
/// <param name="cancellationToken">Cancels the decoding.</param>
/// <returns>The number of samples written.</returns>
/// <exception cref="ArgumentException"><paramref name="destination"/> is too small.</exception>
/// <exception cref="UnsupportedCompressionException">The samples use a compression the library does not decode yet; only uncompressed samples are decoded for now.</exception>
/// <exception cref="UnsupportedFormatException">The samples have a size the library does not decode (12 and 14 bits are).</exception>
/// <exception cref="CorruptRawFileException">The strips of the raw image are too short for the image.</exception>
/// <exception cref="ObjectDisposedException">The file is disposed.</exception>
/// <exception cref="OperationCanceledException">The decoding was cancelled.</exception>
/// <remarks>When the decoding fails, <paramref name="destination"/> may be partly written. Disposing the file during a decoding is not supported.</remarks>
public int Decode(Span<ushort> destination, CancellationToken cancellationToken = default)
{
PrepareDecode();
RawMetadata metadata = Metadata;
int count = checked(metadata.ImageWidth * metadata.ImageHeight);
if (destination.Length < count)
{
throw new ArgumentException($"The buffer holds {destination.Length} samples and the image has {count}.", nameof(destination));
}

UncompressedDecoder.Decode(_source, _structure, destination[..count], cancellationToken);
return count;
}

/// <summary>
/// Opens a raw file from a path. The structure of the file is checked as a whole: a file cut inside its raw data fails with a
/// <see cref="CorruptRawFileException"/> even though its metadata could be read.
Expand Down Expand Up @@ -158,6 +201,24 @@ public ValueTask DisposeAsync()
return ValueTask.CompletedTask;
}

// Everything that can be refused before a byte of the image is read or allocated.
private void PrepareDecode()
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
RawMetadata metadata = Metadata;
if (metadata.Compression != RawCompression.Uncompressed)
{
throw new UnsupportedCompressionException(metadata.CompressionCode, metadata.Compression == RawCompression.NikonCompressed ? "Nikon compressed" : null);
}

if (!UncompressedDecoder.IsSupported(metadata.BitsPerSample))
{
throw new UnsupportedFormatException($"Uncompressed samples of {metadata.BitsPerSample} bits are not decoded (12 and 14 bits are).");
}

UncompressedDecoder.CheckStrips(_structure);
}

private void CheckPreview(RawPreview preview)
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
Expand Down
36 changes: 36 additions & 0 deletions src/Eleris.RawNet/RawImage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace Eleris.RawNet;

/// <summary>
/// The decoded raw image: the mosaic of samples the sensor recorded, one sample per photosite, before any demosaicing,
/// black-level subtraction or scaling.
/// </summary>
public sealed class RawImage
{
internal RawImage(int width, int height, RawRectangle activeArea, CfaPattern cfaPattern, int bitsPerSample, ushort[] mosaic)
{
Width = width;
Height = height;
ActiveArea = activeArea;
CfaPattern = cfaPattern;
BitsPerSample = bitsPerSample;
Mosaic = mosaic;
}

/// <summary>The width in pixels of the mosaic, margins included.</summary>
public int Width { get; }

/// <summary>The height in pixels of the mosaic, margins included.</summary>
public int Height { get; }

/// <summary>The part of the mosaic that holds the picture, as <see cref="RawMetadata.ActiveArea"/> says.</summary>
public RawRectangle ActiveArea { get; }

/// <summary>The colour filter pattern from the top-left sample of the mosaic.</summary>
public CfaPattern CfaPattern { get; }

/// <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 samples, row after row, <see cref="Width"/> times <see cref="Height"/> of them.</summary>
public ReadOnlyMemory<ushort> Mosaic { get; }
}
Loading