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 @@ -12,3 +12,8 @@ change between minor versions.
- The `RawException` hierarchy: `UnsupportedFormatException`, `UnsupportedCameraException`,
`UnsupportedCompressionException` and `CorruptRawFileException`.
- Test infrastructure: a builder of small synthetic NEF files, and a benchmarks project (not packaged).
- Reading the metadata of a NEF without decoding any pixel: `RawFile.Open` (from a path, a seekable stream or memory) and
`RawFile.ReadMetadata`, giving a `RawMetadata` (camera, serial number, lens, exposure, ISO, capture date and clock offset,
shutter count, image size, active area, colour filter pattern, bit depth, compression), the media type `image/x-nikon-nef`
(`RawMediaTypes.NikonNef`), and typed errors for a file that is not a NEF, comes from another maker, or is damaged or
truncated. A damaged file fails with a `RawException` and nothing else (checked by truncating and corrupting files).
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@ Targets: net10.0, no dependency, no native code, compatible with trimming and Na
- **Speed**: allocation budgets and timings are tested, and measured with BenchmarkDotNet (in `benchmarks/`, never part of the
package).

## Usage

```csharp
using Eleris.RawNet;

// Only the structure of the file is read, a few small reads: no pixel is decoded.
using RawFile file = RawFile.Open("DSC_0001.NEF");
RawMetadata m = file.Metadata;
Console.WriteLine($"{m.Model}, ISO {m.Iso}, {m.ExposureTimeSeconds} s, {m.ImageWidth} x {m.ImageHeight}, {m.CfaPattern}");
```

`RawFile.ReadMetadata(path)` does the same and closes the file. A file that is not a NEF, comes from another maker or is damaged
fails with a `RawException` (`UnsupportedFormatException`, `UnsupportedCameraException`, `CorruptRawFileException`...), and with
nothing else; an unreadable file fails with the usual `IOException`.

What is implemented, and what is next, is tracked in the [issues](https://github.com/sputier/raw-net/issues): reading the
metadata works today; the embedded preview and the decoding of the raw mosaic come next.

## Build and test

You need the .NET SDK pinned by [`global.json`](global.json).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
<PackageReference Include="BenchmarkDotNet" />
</ItemGroup>

<ItemGroup>
<!-- The synthetic file builder of the tests, compiled here too (no copy). -->
<Compile Include="..\..\tests\Eleris.RawNet.Tests\Synthetic\*.cs" Exclude="..\..\tests\Eleris.RawNet.Tests\Synthetic\SyntheticNefTests.cs" LinkBase="Synthetic" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Eleris.RawNet\Eleris.RawNet.csproj" />
</ItemGroup>
Expand Down
36 changes: 36 additions & 0 deletions benchmarks/Eleris.RawNet.Benchmarks/MetadataBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using BenchmarkDotNet.Attributes;
using Eleris.RawNet.Tests.Synthetic;

namespace Eleris.RawNet.Benchmarks;

/// <summary>
/// Reading the metadata of a file: from memory (a synthetic file) and, when the environment variable RAWNET_SAMPLES_DIR names a
/// folder of NEF files, from the first file of that folder (read only).
/// </summary>
[MemoryDiagnoser]
public class MetadataBenchmarks
{
private byte[] _synthetic = [];
private string? _realFile;

[GlobalSetup]
public void Setup()
{
_synthetic = SyntheticNef.Build();
string? directory = Environment.GetEnvironmentVariable("RAWNET_SAMPLES_DIR");
if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory))
{
_realFile = Directory.EnumerateFiles(directory, "*.NEF").Order(StringComparer.Ordinal).FirstOrDefault();
}
}

[Benchmark]
public RawMetadata SyntheticInMemory()
{
using RawFile file = RawFile.Open(_synthetic);
return file.Metadata;
}

[Benchmark]
public RawMetadata? RealFileFromPath() => _realFile is null ? null : RawFile.ReadMetadata(_realFile);
}
23 changes: 23 additions & 0 deletions src/Eleris.RawNet/CfaPattern.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Eleris.RawNet;

/// <summary>
/// The 2 x 2 colour filter array of the sensor, read in row order from the top-left pixel of the raw image: the first two
/// letters are the first row, the last two the second row.
/// </summary>
public enum CfaPattern
{
/// <summary>The file does not describe a pattern the library knows.</summary>
Unknown = 0,

/// <summary>Red, green / green, blue.</summary>
Rggb,

/// <summary>Green, red / blue, green.</summary>
Grbg,

/// <summary>Green, blue / red, green.</summary>
Gbrg,

/// <summary>Blue, green / green, red.</summary>
Bggr,
}
96 changes: 96 additions & 0 deletions src/Eleris.RawNet/Internal/ByteSource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using Microsoft.Win32.SafeHandles;

namespace Eleris.RawNet.Internal;

/// <summary>Random access to the bytes of a file, wherever they are: a handle, a seekable stream or memory.</summary>
internal abstract class ByteSource : IDisposable
{
/// <summary>The length of the file in bytes.</summary>
public abstract long Length { get; }

/// <summary>Reads exactly <c>destination.Length</c> bytes at <paramref name="offset"/>; the range must lie inside the file.</summary>
public abstract void ReadExactly(long offset, Span<byte> destination);

public virtual void Dispose()
{
}

public static ByteSource FromMemory(ReadOnlyMemory<byte> data) => new MemorySource(data);

public static ByteSource FromHandle(SafeFileHandle handle) => new HandleSource(handle);

public static ByteSource FromStream(Stream stream, bool leaveOpen) => new StreamSource(stream, leaveOpen);

private sealed class MemorySource(ReadOnlyMemory<byte> data) : ByteSource
{
public override long Length => data.Length;

public override void ReadExactly(long offset, Span<byte> destination) =>
data.Span.Slice(checked((int)offset), destination.Length).CopyTo(destination);
}

private sealed class HandleSource : ByteSource
{
private readonly SafeFileHandle _handle;

public HandleSource(SafeFileHandle handle)
{
_handle = handle;
Length = RandomAccess.GetLength(handle);
}

public override long Length { get; }

public override void ReadExactly(long offset, Span<byte> destination)
{
while (destination.Length > 0)
{
int read = RandomAccess.Read(_handle, destination, offset);
if (read == 0)
{
throw new EndOfStreamException();
}

destination = destination[read..];
offset += read;
}
}

public override void Dispose()
{
_handle.Dispose();
base.Dispose();
}
}

private sealed class StreamSource : ByteSource
{
private readonly Stream _stream;
private readonly bool _leaveOpen;

public StreamSource(Stream stream, bool leaveOpen)
{
_stream = stream;
_leaveOpen = leaveOpen;
Length = stream.Length;
}

public override long Length { get; }

public override void ReadExactly(long offset, Span<byte> destination)
{
_stream.Position = offset;
_stream.ReadExactly(destination);
}

public override void Dispose()
{
if (!_leaveOpen)
{
_stream.Dispose();
}

base.Dispose();
}
}
}
21 changes: 21 additions & 0 deletions src/Eleris.RawNet/Internal/NefStructure.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace Eleris.RawNet.Internal;

/// <summary>Where a piece of the raw image is stored in the file.</summary>
/// <param name="Offset">The position of its first byte.</param>
/// <param name="Length">The number of bytes.</param>
internal readonly record struct RawStrip(long Offset, long Length);

/// <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>
internal sealed record NefStructure(RawMetadata Metadata, IReadOnlyList<RawStrip> RawStrips);

/// <summary>
/// Reads the structure of a NEF file. It is a seam: the implementation of the library reads the TIFF directories itself, and
/// another one could rely on a TIFF library without any change to the rest.
/// </summary>
internal interface INefStructureReader
{
/// <summary>Reads the structure, or fails with a <see cref="RawException"/>.</summary>
NefStructure Read(ByteSource source);
}
Loading
Loading