diff --git a/CHANGELOG.md b/CHANGELOG.md index 6922a32..c86976d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/README.md b/README.md index 6c3b9ac..86f146b 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/benchmarks/Eleris.RawNet.Benchmarks/Eleris.RawNet.Benchmarks.csproj b/benchmarks/Eleris.RawNet.Benchmarks/Eleris.RawNet.Benchmarks.csproj index 6b3c130..a2dbaf2 100644 --- a/benchmarks/Eleris.RawNet.Benchmarks/Eleris.RawNet.Benchmarks.csproj +++ b/benchmarks/Eleris.RawNet.Benchmarks/Eleris.RawNet.Benchmarks.csproj @@ -11,6 +11,11 @@ + + + + + diff --git a/benchmarks/Eleris.RawNet.Benchmarks/MetadataBenchmarks.cs b/benchmarks/Eleris.RawNet.Benchmarks/MetadataBenchmarks.cs new file mode 100644 index 0000000..00e9139 --- /dev/null +++ b/benchmarks/Eleris.RawNet.Benchmarks/MetadataBenchmarks.cs @@ -0,0 +1,36 @@ +using BenchmarkDotNet.Attributes; +using Eleris.RawNet.Tests.Synthetic; + +namespace Eleris.RawNet.Benchmarks; + +/// +/// 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). +/// +[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); +} diff --git a/src/Eleris.RawNet/CfaPattern.cs b/src/Eleris.RawNet/CfaPattern.cs new file mode 100644 index 0000000..902f39e --- /dev/null +++ b/src/Eleris.RawNet/CfaPattern.cs @@ -0,0 +1,23 @@ +namespace Eleris.RawNet; + +/// +/// 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. +/// +public enum CfaPattern +{ + /// The file does not describe a pattern the library knows. + Unknown = 0, + + /// Red, green / green, blue. + Rggb, + + /// Green, red / blue, green. + Grbg, + + /// Green, blue / red, green. + Gbrg, + + /// Blue, green / green, red. + Bggr, +} diff --git a/src/Eleris.RawNet/Internal/ByteSource.cs b/src/Eleris.RawNet/Internal/ByteSource.cs new file mode 100644 index 0000000..75eba86 --- /dev/null +++ b/src/Eleris.RawNet/Internal/ByteSource.cs @@ -0,0 +1,96 @@ +using Microsoft.Win32.SafeHandles; + +namespace Eleris.RawNet.Internal; + +/// Random access to the bytes of a file, wherever they are: a handle, a seekable stream or memory. +internal abstract class ByteSource : IDisposable +{ + /// The length of the file in bytes. + public abstract long Length { get; } + + /// Reads exactly destination.Length bytes at ; the range must lie inside the file. + public abstract void ReadExactly(long offset, Span destination); + + public virtual void Dispose() + { + } + + public static ByteSource FromMemory(ReadOnlyMemory 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 data) : ByteSource + { + public override long Length => data.Length; + + public override void ReadExactly(long offset, Span 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 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 destination) + { + _stream.Position = offset; + _stream.ReadExactly(destination); + } + + public override void Dispose() + { + if (!_leaveOpen) + { + _stream.Dispose(); + } + + base.Dispose(); + } + } +} diff --git a/src/Eleris.RawNet/Internal/NefStructure.cs b/src/Eleris.RawNet/Internal/NefStructure.cs new file mode 100644 index 0000000..ae1a1e4 --- /dev/null +++ b/src/Eleris.RawNet/Internal/NefStructure.cs @@ -0,0 +1,21 @@ +namespace Eleris.RawNet.Internal; + +/// Where a piece of the raw image is stored in the file. +/// The position of its first byte. +/// The number of bytes. +internal readonly record struct RawStrip(long Offset, long Length); + +/// What the structure of a NEF file says: the metadata, and where the raw image is stored. +/// The metadata of the file. +/// The strips of the raw image, in order. +internal sealed record NefStructure(RawMetadata Metadata, IReadOnlyList RawStrips); + +/// +/// 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. +/// +internal interface INefStructureReader +{ + /// Reads the structure, or fails with a . + NefStructure Read(ByteSource source); +} diff --git a/src/Eleris.RawNet/Internal/NefStructureReader.cs b/src/Eleris.RawNet/Internal/NefStructureReader.cs new file mode 100644 index 0000000..420b122 --- /dev/null +++ b/src/Eleris.RawNet/Internal/NefStructureReader.cs @@ -0,0 +1,316 @@ +using System.Globalization; + +namespace Eleris.RawNet.Internal; + +/// Reads the structure of a NEF file with the TIFF reader of the library. +internal sealed class NefStructureReader : INefStructureReader +{ + private const ushort MakeTag = 271, ModelTag = 272, SoftwareTag = 305, DateTimeTag = 306, SubIfdsTag = 330, ExifTag = 34665; + private const ushort WidthTag = 256, HeightTag = 257, BitsTag = 258, CompressionTag = 259, PhotometricTag = 262, StripOffsetsTag = 273, StripByteCountsTag = 279; + private const ushort CfaDimensionTag = 33421, CfaPatternTag = 33422; + private const ushort ExposureTimeTag = 33434, FNumberTag = 33437, IsoTag = 34855, DateTimeOriginalTag = 36867, OffsetTimeTag = 36880, OffsetTimeOriginalTag = 36881; + private const ushort FocalLengthTag = 37386, MakerNoteTag = 37500, BodySerialTag = 42033, LensModelTag = 42036; + private const ushort NikonSerialTag = 0x1D, NikonActiveAreaTag = 0x45, NikonShutterCountTag = 0xA7; + private const int CfaPhotometric = 32803; + private const int MaxSubDirectories = 64; + private const int MaxStrips = 65536; + private const int MaxDimension = 1 << 20; + + public NefStructure Read(ByteSource source) + { + if (!TiffReader.TryReadHeader(source, 0, out TiffReader reader, out long firstDirectory)) + { + throw new UnsupportedFormatException("The file is not a TIFF based file, so it is not a NEF."); + } + + Ifd main = reader.ReadIfd(firstDirectory); + string? make = main.TryGet(MakeTag, out IfdEntry makeEntry) ? reader.ReadText(makeEntry) : null; + string? model = main.TryGet(ModelTag, out IfdEntry modelEntry) ? reader.ReadText(modelEntry) : null; + if (string.IsNullOrEmpty(make)) + { + throw new UnsupportedFormatException("The TIFF file does not say which camera made it, so it is not a camera raw file."); + } + + if (!make.Contains("NIKON", StringComparison.OrdinalIgnoreCase)) + { + throw new UnsupportedCameraException(make, model); + } + + RawImage raw = ReadRawImage(reader, main, source.Length); + Ifd? exif = null; + if (main.TryGet(ExifTag, out IfdEntry exifEntry) && reader.TryReadInteger(exifEntry, 0, out long exifOffset)) + { + exif = reader.ReadIfd(exifOffset); + } + + (TiffReader Reader, Ifd Directory)? makerNote = exif is not null ? ReadMakerNote(reader, exif) : null; + RawRectangle activeArea = ReadActiveArea(makerNote, raw.Width, raw.Height); + + // The clock offset must be the one of the date that is reported: OffsetTimeOriginal goes with DateTimeOriginal, OffsetTime with DateTime. + string? dateText = Text(reader, exif, DateTimeOriginalTag); + string? offsetText = dateText is null ? null : Text(reader, exif, OffsetTimeOriginalTag); + if (dateText is null) + { + dateText = Text(reader, main, DateTimeTag); + offsetText = Text(reader, exif, OffsetTimeTag); + } + string? serial = Text(reader, exif, BodySerialTag); + long? shutterCount = null; + if (makerNote is { } note) + { + serial ??= Text(note.Reader, note.Directory, NikonSerialTag); + if (note.Directory.TryGet(NikonShutterCountTag, out IfdEntry countEntry) && note.Reader.TryReadInteger(countEntry, 0, out long count)) + { + shutterCount = count; + } + } + + var metadata = new RawMetadata + { + MediaType = RawMediaTypes.NikonNef, + Make = make, + Model = model ?? string.Empty, + SerialNumber = string.IsNullOrEmpty(serial) ? null : serial, + Software = Text(reader, main, SoftwareTag), + LensModel = Text(reader, exif, LensModelTag), + FocalLengthMillimetres = Rational(reader, exif, FocalLengthTag), + FNumber = Rational(reader, exif, FNumberTag), + ExposureTimeSeconds = Rational(reader, exif, ExposureTimeTag), + Iso = exif is not null && exif.TryGet(IsoTag, out IfdEntry isoEntry) && reader.TryReadInteger(isoEntry, 0, out long iso) && iso is > 0 and <= int.MaxValue ? (int)iso : null, + CaptureDateTime = ParseDateTime(dateText), + CaptureUtcOffset = ParseOffset(offsetText), + ShutterCount = shutterCount, + ImageWidth = raw.Width, + ImageHeight = raw.Height, + ActiveArea = activeArea, + CfaPattern = raw.Pattern, + BitsPerSample = raw.Bits, + Compression = Enum.IsDefined((RawCompression)raw.Compression) ? (RawCompression)raw.Compression : RawCompression.Unknown, + CompressionCode = raw.Compression, + }; + return new NefStructure(metadata, raw.Strips); + } + + private sealed record RawImage(int Width, int Height, int Bits, int Compression, CfaPattern Pattern, RawStrip[] Strips); + + private static RawImage ReadRawImage(TiffReader reader, Ifd main, long fileLength) + { + if (!main.TryGet(SubIfdsTag, out IfdEntry subEntry)) + { + throw new UnsupportedFormatException("The file has no sub-directory, so it holds no raw image."); + } + + // The raw image is the largest colour filter array image of the sub-directories (the file also holds reduced ones). + // A sub-directory that cannot be read is skipped: another one may hold the image. + Ifd? best = null; + long bestArea = 0; + bool damaged = false; + int count = (int)Math.Min(subEntry.Count, MaxSubDirectories); + for (int i = 0; i < count; i++) + { + if (!reader.TryReadInteger(subEntry, i, out long offset)) + { + break; + } + + Ifd sub; + try + { + sub = reader.ReadIfd(offset); + } + catch (CorruptRawFileException) + { + damaged = true; + continue; + } + + if (sub.TryGet(PhotometricTag, out IfdEntry photometric) + && reader.TryReadInteger(photometric, 0, out long value) + && value == CfaPhotometric + && Integer(reader, sub, WidthTag) is > 0 and <= MaxDimension and long width + && Integer(reader, sub, HeightTag) is > 0 and <= MaxDimension and long height + && width * height > bestArea) + { + best = sub; + bestArea = width * height; + } + } + + if (best is null) + { + throw damaged + ? new CorruptRawFileException("The sub-directories that should hold the raw image are damaged") + : new UnsupportedFormatException("The file holds no raw image of a kind the library reads (no colour filter array image in its sub-directories)."); + } + + long w = Integer(reader, best, WidthTag) ?? 0, h = Integer(reader, best, HeightTag) ?? 0; + if (w is <= 0 or > MaxDimension || h is <= 0 or > MaxDimension) + { + throw new CorruptRawFileException("The raw image has an impossible size"); + } + + long bits = Integer(reader, best, BitsTag) ?? throw new CorruptRawFileException("The raw image does not say how many bits its samples have"); + if (bits is < 1 or > 32) + { + throw new CorruptRawFileException("The raw image has an impossible sample size"); + } + + long compression = Integer(reader, best, CompressionTag) ?? 1; + if (compression is < 0 or > ushort.MaxValue) + { + 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)); + } + + private static CfaPattern ReadPattern(TiffReader reader, Ifd raw) + { + if (!raw.TryGet(CfaDimensionTag, out IfdEntry dimension) + || !reader.TryReadInteger(dimension, 0, out long columns) + || !reader.TryReadInteger(dimension, 1, out long rows) + || columns != 2 + || rows != 2 + || !raw.TryGet(CfaPatternTag, out IfdEntry pattern) + || pattern.Count != 4) + { + return CfaPattern.Unknown; + } + + Span colours = stackalloc byte[4]; + if (!reader.TryReadBytes(pattern, colours)) + { + return CfaPattern.Unknown; + } + + // The colours are 0 red, 1 green, 2 blue. + return (colours[0], colours[1], colours[2], colours[3]) switch + { + (0, 1, 1, 2) => CfaPattern.Rggb, + (1, 0, 2, 1) => CfaPattern.Grbg, + (1, 2, 0, 1) => CfaPattern.Gbrg, + (2, 1, 1, 0) => CfaPattern.Bggr, + _ => CfaPattern.Unknown, + }; + } + + private static RawStrip[] ReadStrips(TiffReader reader, Ifd raw, long fileLength) + { + if (!raw.TryGet(StripOffsetsTag, out IfdEntry offsets) || !raw.TryGet(StripByteCountsTag, out IfdEntry counts)) + { + throw new CorruptRawFileException("The raw image does not say where its data is"); + } + + if (offsets.Count == 0 || offsets.Count > MaxStrips || offsets.Count != counts.Count) + { + throw new CorruptRawFileException("The raw image has an impossible number of strips"); + } + + var strips = new RawStrip[offsets.Count]; + for (int i = 0; i < strips.Length; i++) + { + if (!reader.TryReadInteger(offsets, i, out long offset) || !reader.TryReadInteger(counts, i, out long length)) + { + throw new CorruptRawFileException("The strips of the raw image cannot be read"); + } + + if (offset < 0 || length < 0 || offset > fileLength || length > fileLength - offset) + { + throw new CorruptRawFileException("The raw data extends beyond the end of the file (the file is truncated)", offset); + } + + strips[i] = new RawStrip(offset, length); + } + + return strips; + } + + private static (TiffReader Reader, Ifd Directory)? ReadMakerNote(TiffReader reader, Ifd exif) + { + if (!exif.TryGet(MakerNoteTag, out IfdEntry entry) || entry.Count < 18) + { + return null; + } + + Span prefix = stackalloc byte[6]; + reader.Source.ReadExactly(entry.ValueOffset, prefix); + if (!prefix.SequenceEqual("Nikon\0"u8) + || !TiffReader.TryReadHeader(reader.Source, entry.ValueOffset + 10, out TiffReader noteReader, out long firstDirectory)) + { + return null; + } + + // The note is optional: a damaged one costs the values it holds, not the file. + try + { + return (noteReader, noteReader.ReadIfd(firstDirectory)); + } + catch (CorruptRawFileException) + { + return null; + } + } + + private static RawRectangle ReadActiveArea((TiffReader Reader, Ifd Directory)? note, int width, int height) + { + var whole = new RawRectangle(0, 0, width, height); + if (note is not { } n || !n.Directory.TryGet(NikonActiveAreaTag, out IfdEntry entry) || entry.Count != 4) + { + return whole; + } + + long[] v = new long[4]; + for (int i = 0; i < 4; i++) + { + if (!n.Reader.TryReadInteger(entry, i, out v[i])) + { + return whole; + } + } + + bool fits = v[0] >= 0 && v[1] >= 0 && v[2] > 0 && v[3] > 0 && v[0] + v[2] <= width && v[1] + v[3] <= height; + return fits ? new RawRectangle((int)v[0], (int)v[1], (int)v[2], (int)v[3]) : whole; + } + + 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; + + private static string? Text(TiffReader reader, Ifd? directory, ushort tag) + { + if (directory is null || !directory.TryGet(tag, out IfdEntry entry)) + { + return null; + } + + string? text = reader.ReadText(entry); + return string.IsNullOrEmpty(text) ? null : text; + } + + private static double? Rational(TiffReader reader, Ifd? directory, ushort tag) => + directory is not null && directory.TryGet(tag, out IfdEntry entry) && reader.TryReadRational(entry, 0, out double value) && double.IsFinite(value) && value > 0 ? value : null; + + private static DateTime? ParseDateTime(string? text) + { + if (text is null || text.Length < 19) + { + return null; + } + + return DateTime.TryParseExact(text.AsSpan(0, 19), "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime value) ? value : null; + } + + private static TimeSpan? ParseOffset(string? text) + { + // "+01:00" or "-05:30". + if (text is not { Length: 6 } || (text[0] != '+' && text[0] != '-') || text[3] != ':' + || !int.TryParse(text.AsSpan(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out int hours) + || !int.TryParse(text.AsSpan(4, 2), NumberStyles.None, CultureInfo.InvariantCulture, out int minutes) + || hours > 14 || minutes > 59) + { + return null; + } + + var offset = new TimeSpan(hours, minutes, 0); + return text[0] == '-' ? -offset : offset; + } +} diff --git a/src/Eleris.RawNet/Internal/TiffReader.cs b/src/Eleris.RawNet/Internal/TiffReader.cs new file mode 100644 index 0000000..31a5060 --- /dev/null +++ b/src/Eleris.RawNet/Internal/TiffReader.cs @@ -0,0 +1,248 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Text; + +namespace Eleris.RawNet.Internal; + +/// The type of a TIFF directory entry (the values the library reads). +internal static class TiffTypes +{ + public const ushort Byte = 1, Ascii = 2, Short = 3, Long = 4, Rational = 5, SignedByte = 6, Undefined = 7, SignedShort = 8, SignedLong = 9, SignedRational = 10, Float = 11, Double = 12, Ifd = 13; + + /// The size in bytes of one value, or 0 for a type the library does not know (the entry is then ignored). + public static int Size(ushort type) => type switch + { + Byte or Ascii or SignedByte or Undefined => 1, + Short or SignedShort => 2, + Long or SignedLong or Float or Ifd => 4, + Rational or SignedRational or Double => 8, + _ => 0, + }; +} + +/// An entry of a TIFF directory whose value lies inside the file. +/// The tag. +/// The type of the values. +/// The number of values. +/// The position in the file of the first byte of the values. +internal readonly record struct IfdEntry(ushort Tag, ushort Type, uint Count, long ValueOffset) +{ + public long ByteLength => (long)Count * TiffTypes.Size(Type); +} + +/// The entries of one directory, in file order. +internal sealed class Ifd(IfdEntry[] entries) +{ + public IfdEntry[] Entries { get; } = entries; + + public bool TryGet(ushort tag, out IfdEntry entry) + { + foreach (IfdEntry candidate in Entries) + { + if (candidate.Tag == tag) + { + entry = candidate; + return true; + } + } + + entry = default; + return false; + } +} + +/// +/// Reads TIFF directories and their values from a . The offsets stored in the directories count from +/// origin: 0 for the file, the position of the embedded TIFF header for a Nikon MakerNote. +/// +internal sealed class TiffReader(ByteSource source, long origin, bool littleEndian) +{ + private const int MaxTextLength = 256; + + public ByteSource Source { get; } = source; + + public long Origin { get; } = origin; + + public bool LittleEndian { get; } = littleEndian; + + /// + /// Reads the directory at , a position in the file. The position is absolute, whereas the offsets of the values stored in the directory count from the origin of the reader. An entry whose value lies outside the file or + /// whose type is unknown is left out, as TIFF readers do; a directory that does not fit in the file is an error. + /// + public Ifd ReadIfd(long offset) + { + long length = Source.Length; + if (offset < 0 || offset > length - 2) + { + throw new CorruptRawFileException("A directory starts outside the file", offset); + } + + Span countBytes = stackalloc byte[2]; + Source.ReadExactly(offset, countBytes); + int count = ReadUInt16(countBytes); + int byteCount = count * 12; + if (offset + 2 + byteCount > length) + { + throw new CorruptRawFileException("A directory ends outside the file", offset); + } + + byte[] buffer = ArrayPool.Shared.Rent(Math.Max(byteCount, 1)); + try + { + Source.ReadExactly(offset + 2, buffer.AsSpan(0, byteCount)); + var entries = new List(count); + for (int i = 0; i < count; i++) + { + ReadOnlySpan slot = buffer.AsSpan(i * 12, 12); + ushort type = ReadUInt16(slot[2..]); + int size = TiffTypes.Size(type); + if (size == 0) + { + continue; + } + + uint valueCount = ReadUInt32(slot[4..]); + long byteLength = (long)valueCount * size; + long valueOffset = byteLength <= 4 + ? offset + 2 + (i * 12L) + 8 + : Origin + ReadUInt32(slot[8..]); + if (valueOffset < 0 || valueOffset + byteLength > length) + { + continue; + } + + entries.Add(new IfdEntry(ReadUInt16(slot), type, valueCount, valueOffset)); + } + + return new Ifd([.. entries]); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Reads one integer value (BYTE, SHORT, LONG, IFD or their signed forms) of an entry. + public bool TryReadInteger(in IfdEntry entry, int index, out long value) + { + value = 0; + int size = TiffTypes.Size(entry.Type); + if ((uint)index >= entry.Count || entry.Type is TiffTypes.Ascii or TiffTypes.Rational or TiffTypes.SignedRational or TiffTypes.Undefined or TiffTypes.Float or TiffTypes.Double) + { + return false; + } + + Span bytes = stackalloc byte[4]; + Source.ReadExactly(entry.ValueOffset + (index * (long)size), bytes[..size]); + value = entry.Type switch + { + TiffTypes.Byte => bytes[0], + TiffTypes.SignedByte => (sbyte)bytes[0], + TiffTypes.Short => ReadUInt16(bytes), + TiffTypes.SignedShort => (short)ReadUInt16(bytes), + TiffTypes.SignedLong => (int)ReadUInt32(bytes), + _ => ReadUInt32(bytes), + }; + return true; + } + + /// Reads one RATIONAL value as a number; false when the entry is not a rational or the denominator is zero. + public bool TryReadRational(in IfdEntry entry, int index, out double value) + { + value = 0; + if ((uint)index >= entry.Count || entry.Type is not (TiffTypes.Rational or TiffTypes.SignedRational)) + { + return false; + } + + Span bytes = stackalloc byte[8]; + Source.ReadExactly(entry.ValueOffset + (index * 8L), bytes); + double numerator, denominator; + if (entry.Type == TiffTypes.Rational) + { + numerator = ReadUInt32(bytes); + denominator = ReadUInt32(bytes[4..]); + } + else + { + numerator = (int)ReadUInt32(bytes); + denominator = (int)ReadUInt32(bytes[4..]); + } + + if (denominator == 0) + { + return false; + } + + value = numerator / denominator; + return true; + } + + /// Reads an ASCII value (at most 256 characters, up to the first NUL), or null when the entry is not text. + public string? ReadText(in IfdEntry entry) + { + if (entry.Type != TiffTypes.Ascii) + { + return null; + } + + int length = (int)Math.Min(entry.Count, MaxTextLength); + Span bytes = stackalloc byte[MaxTextLength]; + bytes = bytes[..length]; + Source.ReadExactly(entry.ValueOffset, bytes); + int end = bytes.IndexOf((byte)0); + if (end >= 0) + { + bytes = bytes[..end]; + } + + return Encoding.ASCII.GetString(bytes).Trim(); + } + + /// Reads the bytes of a value into ; false when it does not fit. + public bool TryReadBytes(in IfdEntry entry, Span destination) + { + if (entry.ByteLength > destination.Length) + { + return false; + } + + Source.ReadExactly(entry.ValueOffset, destination[..(int)entry.ByteLength]); + return true; + } + + public ushort ReadUInt16(ReadOnlySpan bytes) => + LittleEndian ? BinaryPrimitives.ReadUInt16LittleEndian(bytes) : BinaryPrimitives.ReadUInt16BigEndian(bytes); + + public uint ReadUInt32(ReadOnlySpan bytes) => + LittleEndian ? BinaryPrimitives.ReadUInt32LittleEndian(bytes) : BinaryPrimitives.ReadUInt32BigEndian(bytes); + + /// Reads the 8-byte TIFF header at and returns a reader and the offset of the first directory. + public static bool TryReadHeader(ByteSource source, long position, out TiffReader reader, out long firstDirectory) + { + reader = null!; + firstDirectory = 0; + if (position < 0 || position + 8 > source.Length) + { + return false; + } + + Span header = stackalloc byte[8]; + source.ReadExactly(position, header); + bool little = header[0] == (byte)'I' && header[1] == (byte)'I'; + bool big = header[0] == (byte)'M' && header[1] == (byte)'M'; + if (!little && !big) + { + return false; + } + + reader = new TiffReader(source, position, little); + if (reader.ReadUInt16(header[2..]) != 42) + { + return false; + } + + firstDirectory = position + reader.ReadUInt32(header[4..]); + return true; + } +} diff --git a/src/Eleris.RawNet/RawCompression.cs b/src/Eleris.RawNet/RawCompression.cs new file mode 100644 index 0000000..38b0799 --- /dev/null +++ b/src/Eleris.RawNet/RawCompression.cs @@ -0,0 +1,14 @@ +namespace Eleris.RawNet; + +/// How the pixels of the raw image are stored in the file. +public enum RawCompression +{ + /// A compression the library does not know; see . + Unknown = 0, + + /// The samples are stored as they are. + Uncompressed = 1, + + /// The compression of Nikon NEF files (TIFF compression code 34713). + NikonCompressed = 34713, +} diff --git a/src/Eleris.RawNet/RawFile.cs b/src/Eleris.RawNet/RawFile.cs new file mode 100644 index 0000000..c4532e7 --- /dev/null +++ b/src/Eleris.RawNet/RawFile.cs @@ -0,0 +1,120 @@ +using Eleris.RawNet.Internal; + +namespace Eleris.RawNet; + +/// +/// An opened raw file. Opening reads only the structure of the file (a few small reads), never its pixels, so +/// is available at once. Dispose the file to release what it holds. +/// +/// +/// A file opened from a path or from memory can be used by several threads. A file opened from a stream uses the position of +/// that stream and must not be used by several threads at once. +/// +public sealed class RawFile : IDisposable, IAsyncDisposable +{ + // The seam of the structure reader, kept as the interface on purpose (a TIFF library could implement it). + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1859:Use concrete types when possible for improved performance", Justification = "A seam.")] + private static readonly INefStructureReader StructureReader = new NefStructureReader(); + + private readonly ByteSource _source; + private readonly NefStructure _structure; + + private RawFile(ByteSource source, NefStructure structure) + { + _source = source; + _structure = structure; + } + + /// What the file says about the shot and about its raw image. + public RawMetadata Metadata => _structure.Metadata; + + /// + /// 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 + /// even though its metadata could be read. + /// + /// The path of the file. + /// The opened file. + /// is empty or null. + /// The file is not a raw file the library reads, or is damaged. + /// The file cannot be read (the usual I/O and access exceptions of the file system propagate unchanged). + public static RawFile Open(string path) + { + ArgumentException.ThrowIfNullOrEmpty(path); + Microsoft.Win32.SafeHandles.SafeFileHandle handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess); + ByteSource source; + try + { + source = ByteSource.FromHandle(handle); + } + catch + { + handle.Dispose(); + throw; + } + + return Create(source); + } + + /// Opens a raw file from a seekable stream. + /// A readable, seekable stream positioned anywhere; the library sets the position it needs. + /// True to leave the stream open when the file is disposed. + /// The opened file. + /// The stream is null, cannot be read or cannot seek. + /// The content is not a raw file the library reads, or is damaged. + public static RawFile Open(Stream stream, bool leaveOpen = false) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead || !stream.CanSeek) + { + throw new ArgumentException("The stream must be readable and seekable.", nameof(stream)); + } + + return Create(ByteSource.FromStream(stream, leaveOpen)); + } + + /// Opens a raw file held in memory. The memory must not change while the file is in use. + /// The whole file. + /// The opened file. + /// The content is not a raw file the library reads, or is damaged. + public static RawFile Open(ReadOnlyMemory data) => Create(ByteSource.FromMemory(data)); + + /// Reads the metadata of the file at and closes it. + /// The path of the file. + /// The metadata. + /// is empty or null. + /// The file is not a raw file the library reads, or is damaged. + /// The file cannot be read (the usual I/O and access exceptions of the file system propagate unchanged). + public static RawMetadata ReadMetadata(string path) + { + using RawFile file = Open(path); + return file.Metadata; + } + + /// Releases the file or the stream this object holds. + public void Dispose() => _source.Dispose(); + + /// + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + + private static RawFile Create(ByteSource source) + { + try + { + return new RawFile(source, StructureReader.Read(source)); + } + catch (EndOfStreamException ex) + { + source.Dispose(); + throw new CorruptRawFileException("The file ends before the end of its structure", null, ex); + } + catch + { + source.Dispose(); + throw; + } + } +} diff --git a/src/Eleris.RawNet/RawMediaTypes.cs b/src/Eleris.RawNet/RawMediaTypes.cs new file mode 100644 index 0000000..6366e62 --- /dev/null +++ b/src/Eleris.RawNet/RawMediaTypes.cs @@ -0,0 +1,8 @@ +namespace Eleris.RawNet; + +/// The media types of the formats the library reads. A NEF is TIFF based but is not an image/tiff. +public static class RawMediaTypes +{ + /// The media type of a Nikon NEF file. + public const string NikonNef = "image/x-nikon-nef"; +} diff --git a/src/Eleris.RawNet/RawMetadata.cs b/src/Eleris.RawNet/RawMetadata.cs new file mode 100644 index 0000000..1caa96b --- /dev/null +++ b/src/Eleris.RawNet/RawMetadata.cs @@ -0,0 +1,84 @@ +namespace Eleris.RawNet; + +/// +/// What a raw file says about the shot and about its raw image, read without decoding any pixel. A value the file does not +/// hold, or holds in a form the library cannot read, is null. +/// +public sealed record RawMetadata +{ + // The serial number identifies a body: ToString, which logs and debuggers call, leaves it out. + private bool PrintMembers(System.Text.StringBuilder builder) + { + builder.Append(System.Globalization.CultureInfo.InvariantCulture, $"Make = {Make}, Model = {Model}, Iso = {Iso}, ExposureTimeSeconds = {ExposureTimeSeconds}, "); + builder.Append(System.Globalization.CultureInfo.InvariantCulture, $"ImageWidth = {ImageWidth}, ImageHeight = {ImageHeight}, CfaPattern = {CfaPattern}, BitsPerSample = {BitsPerSample}, "); + builder.Append(System.Globalization.CultureInfo.InvariantCulture, $"Compression = {Compression}"); + return true; + } + + /// The media type of the file, see . + public required string MediaType { get; init; } + + /// The manufacturer as written in the file, for example "NIKON CORPORATION". + public required string Make { get; init; } + + /// The camera model as written in the file, for example "NIKON Z 6". + public required string Model { get; init; } + + /// The serial number of the camera body, or null. It identifies the body: it is not part of . + public string? SerialNumber { get; init; } + + /// The firmware or software version written by the camera, or null. + public string? Software { get; init; } + + /// The model of the lens, or null. + public string? LensModel { get; init; } + + /// The focal length in millimetres, or null. + public double? FocalLengthMillimetres { get; init; } + + /// The aperture as an f-number (1.8 for f/1.8), or null. + public double? FNumber { get; init; } + + /// The exposure time in seconds, or null. + public double? ExposureTimeSeconds { get; init; } + + /// The ISO speed, or null. + public int? Iso { get; init; } + + /// + /// The date and time of the shot as the camera clock showed them (its is + /// ), or null. Use to place it on the UTC timeline. + /// + public DateTime? CaptureDateTime { get; init; } + + /// The offset of the camera clock from UTC when the file records it, or null when it is not known. + public TimeSpan? CaptureUtcOffset { get; init; } + + /// The number of times the shutter had been released when the shot was taken, or null. + public long? ShutterCount { get; init; } + + /// The width in pixels of the raw image, margins included. + public required int ImageWidth { get; init; } + + /// The height in pixels of the raw image, margins included. + public required int ImageHeight { get; init; } + + /// + /// The crop area the camera recorded in the file, inside the raw image: for a Nikon Z 6 in full-frame mode, the part of the + /// raw image that holds the picture, the rest being the margins of the sensor. When the file records none, or an area that does + /// not fit in the image, it is the whole image. + /// + public required RawRectangle ActiveArea { get; init; } + + /// The colour filter pattern from the top-left pixel of the raw image (not of the active area). + public required CfaPattern CfaPattern { get; init; } + + /// The number of bits of a sample of the raw image. + public required int BitsPerSample { get; init; } + + /// How the samples are stored. + public required RawCompression Compression { get; init; } + + /// The TIFF compression code stored in the file, whether or not the library decodes it. + public required int CompressionCode { get; init; } +} diff --git a/src/Eleris.RawNet/RawRectangle.cs b/src/Eleris.RawNet/RawRectangle.cs new file mode 100644 index 0000000..2064036 --- /dev/null +++ b/src/Eleris.RawNet/RawRectangle.cs @@ -0,0 +1,15 @@ +namespace Eleris.RawNet; + +/// A rectangle of pixels of the raw image: its top-left corner and its size. +/// The column of the first pixel. +/// The row of the first pixel. +/// The number of columns. +/// The number of rows. +public readonly record struct RawRectangle(int Left, int Top, int Width, int Height) +{ + /// The column after the last pixel. + public int Right => Left + Width; + + /// The row after the last pixel. + public int Bottom => Top + Height; +} diff --git a/tests/Eleris.RawNet.Tests/RawFileTests.cs b/tests/Eleris.RawNet.Tests/RawFileTests.cs new file mode 100644 index 0000000..bf3bc2c --- /dev/null +++ b/tests/Eleris.RawNet.Tests/RawFileTests.cs @@ -0,0 +1,414 @@ +using Eleris.RawNet.Tests.Synthetic; + +namespace Eleris.RawNet.Tests; + +public class RawFileTests +{ + private static RawMetadata Read(byte[] file) + { + using RawFile raw = RawFile.Open(file); + return raw.Metadata; + } + + [Fact] + public void The_metadata_of_a_file_describes_the_shot_and_the_raw_image() + { + RawMetadata m = Read(SyntheticNef.Build()); + + Assert.Equal(RawMediaTypes.NikonNef, m.MediaType); + Assert.Equal("NIKON CORPORATION", m.Make); + Assert.Equal("NIKON Z 6", m.Model); + Assert.Equal("1234567", m.SerialNumber); + Assert.Equal("Ver.00.00", m.Software); + Assert.Equal("Test lens 50mm f/1.8", m.LensModel); + Assert.Equal(50.0, m.FocalLengthMillimetres); + Assert.Equal(1.8, m.FNumber); + Assert.Equal(1.6, m.ExposureTimeSeconds); + Assert.Equal(1600, m.Iso); + Assert.Equal(new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Unspecified), m.CaptureDateTime); + Assert.Equal(TimeSpan.FromHours(1), m.CaptureUtcOffset); + Assert.Equal(100, m.ShutterCount); + Assert.Equal(64, m.ImageWidth); + Assert.Equal(48, m.ImageHeight); + Assert.Equal(new RawRectangle(4, 4, 56, 40), m.ActiveArea); + Assert.Equal(CfaPattern.Rggb, m.CfaPattern); + Assert.Equal(14, m.BitsPerSample); + Assert.Equal(RawCompression.NikonCompressed, m.Compression); + Assert.Equal(34713, m.CompressionCode); + } + + [Fact] + public void A_big_endian_file_reads_the_same_as_a_little_endian_one() + { + Assert.Equal(Read(SyntheticNef.Build()), Read(SyntheticNef.Build(new SyntheticNefOptions { BigEndian = true }))); + } + + [Theory] + [InlineData(new byte[] { 0, 1, 1, 2 }, CfaPattern.Rggb)] + [InlineData(new byte[] { 1, 0, 2, 1 }, CfaPattern.Grbg)] + [InlineData(new byte[] { 1, 2, 0, 1 }, CfaPattern.Gbrg)] + [InlineData(new byte[] { 2, 1, 1, 0 }, CfaPattern.Bggr)] + [InlineData(new byte[] { 0, 1, 2, 1 }, CfaPattern.Unknown)] + public void The_colour_filter_pattern_is_read_from_the_file(byte[] colours, CfaPattern expected) + { + Assert.Equal(expected, Read(SyntheticNef.Build(new SyntheticNefOptions { CfaPattern = colours })).CfaPattern); + } + + [Theory] + [InlineData(1, RawCompression.Uncompressed)] + [InlineData(34713, RawCompression.NikonCompressed)] + [InlineData(99, RawCompression.Unknown)] + public void The_compression_is_named_when_the_library_knows_it_and_its_code_is_always_kept(int code, RawCompression expected) + { + RawMetadata m = Read(SyntheticNef.Build(new SyntheticNefOptions { Compression = code })); + + Assert.Equal(expected, m.Compression); + Assert.Equal(code, m.CompressionCode); + } + + [Fact] + public void The_bit_depth_comes_from_the_file() + { + Assert.Equal(12, Read(SyntheticNef.Build(new SyntheticNefOptions { BitsPerSample = 12 })).BitsPerSample); + } + + [Theory] + [InlineData(new ushort[] { 0, 0, 0, 0 })] + [InlineData(new ushort[] { 4, 4, 100, 40 })] + [InlineData(new ushort[] { 60, 4, 10, 40 })] + public void An_impossible_active_area_falls_back_to_the_whole_image(ushort[] area) + { + Assert.Equal(new RawRectangle(0, 0, 64, 48), Read(SyntheticNef.Build(new SyntheticNefOptions { ActiveArea = area })).ActiveArea); + } + + [Fact] + public void The_serial_number_falls_back_to_the_MakerNote() + { + Assert.Equal("7654321", Read(SyntheticNef.Build(new SyntheticNefOptions { SerialNumber = "7654321", IncludeExifSerial = false })).SerialNumber); + } + + [Fact] + public void Values_the_library_cannot_read_are_null_and_do_not_fail_the_file() + { + RawMetadata m = Read(SyntheticNef.Build(new SyntheticNefOptions + { + ExposureTime = (1, 0), + DateTime = "not a date at all.", + OffsetTime = "later", + })); + + Assert.Null(m.ExposureTimeSeconds); + Assert.Null(m.CaptureDateTime); + Assert.Null(m.CaptureUtcOffset); + } + + [Theory] + [InlineData("+01:00", 60)] + [InlineData("-05:30", -330)] + [InlineData("+00:00", 0)] + public void The_clock_offset_is_read_with_its_sign(string text, int minutes) + { + Assert.Equal(TimeSpan.FromMinutes(minutes), Read(SyntheticNef.Build(new SyntheticNefOptions { OffsetTime = text })).CaptureUtcOffset); + } + + [Fact] + public void A_file_from_another_maker_is_an_unsupported_camera() + { + var error = Assert.Throws(() => Read(SyntheticNef.Build(new SyntheticNefOptions { Make = "OTHER", Model = "Y 1" }))); + + Assert.Equal("OTHER", error.Make); + Assert.Equal("Y 1", error.Model); + } + + [Theory] + [InlineData(new byte[0])] + [InlineData(new byte[] { 1, 2, 3 })] + [InlineData(new byte[] { (byte)'I', (byte)'I', 42, 0 })] + [InlineData(new byte[] { (byte)'P', (byte)'K', 3, 4, 0, 0, 0, 0, 0, 0 })] + [InlineData(new byte[] { (byte)'I', (byte)'I', 43, 0, 8, 0, 0, 0 })] + public void Something_that_is_not_a_TIFF_based_file_is_an_unsupported_format(byte[] content) + { + Assert.Throws(() => Read(content)); + } + + [Fact] + public void A_file_cut_in_its_raw_data_is_reported_as_corrupt_with_a_position() + { + byte[] file = SyntheticNef.Build(); + + var error = Assert.Throws(() => Read(file[..^1])); + + Assert.NotNull(error.Position); + } + + [Fact] + public void A_file_cut_in_its_directories_is_reported_as_corrupt() + { + byte[] file = SyntheticNef.Build(); + + Assert.Throws(() => Read(file[..20])); + } + + [Fact] + public void A_path_a_stream_and_memory_give_the_same_metadata() + { + byte[] file = SyntheticNef.Build(); + string path = Path.Combine(Path.GetTempPath(), $"rawnet-{Guid.NewGuid():N}.nef"); + File.WriteAllBytes(path, file); + try + { + using var stream = new MemoryStream(file); + using RawFile fromStream = RawFile.Open(stream, leaveOpen: true); + + Assert.Equal(Read(file), fromStream.Metadata); + Assert.Equal(Read(file), RawFile.ReadMetadata(path)); + using RawFile fromPath = RawFile.Open(path); + Assert.Equal(Read(file), fromPath.Metadata); + Assert.True(stream.CanRead); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void Disposing_a_file_closes_a_stream_unless_it_was_left_open() + { + byte[] file = SyntheticNef.Build(); + var closed = new MemoryStream(file); + var open = new MemoryStream(file); + + RawFile.Open(closed).Dispose(); + RawFile.Open(open, leaveOpen: true).Dispose(); + + Assert.False(closed.CanRead); + Assert.True(open.CanRead); + } + + [Fact] + public async Task Disposing_asynchronously_releases_the_stream() + { + var stream = new MemoryStream(SyntheticNef.Build()); + + await RawFile.Open(stream).DisposeAsync(); + + Assert.False(stream.CanRead); + } + + [Fact] + public void A_wrong_call_is_an_ArgumentException() + { + Assert.Throws(() => RawFile.Open((Stream)null!)); + Assert.Throws(() => RawFile.Open(new NonSeekableStream())); + Assert.Throws(() => RawFile.Open(string.Empty)); + Assert.Throws(() => RawFile.Open((string)null!)); + } + + [Fact] + public void A_stream_is_read_from_its_start_whatever_its_position() + { + using var stream = new MemoryStream(SyntheticNef.Build()) { Position = 37 }; + + using RawFile file = RawFile.Open(stream, leaveOpen: true); + + Assert.Equal("NIKON Z 6", file.Metadata.Model); + } + + [Fact] + public void The_offset_belongs_to_the_date_that_is_reported() + { + var options = new SyntheticNefOptions { OffsetTime = "+02:00", OffsetTimeOriginal = "+05:00" }; + + Assert.Equal(TimeSpan.FromHours(5), Read(SyntheticNef.Build(options)).CaptureUtcOffset); + RawMetadata withoutOriginal = Read(SyntheticNef.Build(options with { IncludeDateTimeOriginal = false })); + Assert.Equal(new DateTime(2026, 1, 2, 3, 4, 5), withoutOriginal.CaptureDateTime); + Assert.Equal(TimeSpan.FromHours(2), withoutOriginal.CaptureUtcOffset); + } + + [Fact] + public void A_focal_length_or_an_iso_of_zero_means_unknown() + { + RawMetadata m = Read(SyntheticNef.Build(new SyntheticNefOptions { FocalLength = (0, 1), Iso = 0, FNumber = (0, 1) })); + + Assert.Null(m.FocalLengthMillimetres); + Assert.Null(m.Iso); + Assert.Null(m.FNumber); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void The_raw_image_is_the_largest_colour_filter_array_image_whatever_its_place(bool bigEndian) + { + RawMetadata m = Read(SyntheticNef.Build(new SyntheticNefOptions { SmallCfaSubImage = true, BigEndian = bigEndian })); + + Assert.Equal(64, m.ImageWidth); + Assert.Equal(48, m.ImageHeight); + Assert.Equal(14, m.BitsPerSample); + } + + [Fact] + public void A_damaged_MakerNote_costs_its_values_and_not_the_file() + { + byte[] file = SyntheticNef.Build(new SyntheticNefOptions { ShutterCount = 77 }); + int start = file.AsSpan().IndexOf("Nikon\0"u8); + file[start] = (byte)'X'; + + RawMetadata m = Read(file); + + Assert.Null(m.ShutterCount); + Assert.Equal(new RawRectangle(0, 0, 64, 48), m.ActiveArea); + Assert.Equal("1234567", m.SerialNumber); + Assert.Equal("NIKON Z 6", m.Model); + } + + [Fact] + public void A_sub_directory_that_cannot_be_read_is_reported_as_corrupt_not_unsupported() + { + byte[] file = SyntheticNef.Build(); + List main = TinyTiff.ReadIfd(file, 8); + TinyEntry subs = TinyTiff.Find(main, 330); + // Point both sub-directories past the end of the file. + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan((int)subs.ValueOffset), 0x7FFFFFF0); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan((int)subs.ValueOffset + 4), 0x7FFFFFF0); + + Assert.Throws(() => Read(file)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Boundary_values_in_every_field_of_the_structure_never_fail_with_anything_but_a_RawException(bool bigEndian) + { + byte[] original = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 8, RawHeight = 4, BigEndian = bigEndian, SmallCfaSubImage = true }); + uint[] values = [0, 1, 0x7FFF, 0xFFFF, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 64, 4096]; + var watch = System.Diagnostics.Stopwatch.StartNew(); + + for (int position = 0; position + 4 <= original.Length; position++) + { + foreach (uint value in values) + { + foreach (int width in new[] { 2, 4 }) + { + byte[] file = (byte[])original.Clone(); + Span target = file.AsSpan(position, width); + if (width == 2) + { + if (bigEndian) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(target, (ushort)value); + } + else + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(target, (ushort)value); + } + } + else if (bigEndian) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(target, value); + } + else + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(target, value); + } + + Exception? error = Record.Exception(() => Read(file)); + Assert.True(error is null or RawException, $"position {position}, value {value:X}, width {width}: {error?.GetType().Name}: {error?.Message}"); + } + } + } + + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(60), "A damaged file must not make the reader loop or crawl."); + } + + [Fact] + public void A_failed_open_closes_the_stream_it_owns() + { + var stream = new MemoryStream([1, 2, 3, 4, 5, 6, 7, 8, 9]); + + Assert.Throws(() => RawFile.Open(stream)); + + Assert.False(stream.CanRead); + } + + [Fact] + public void A_missing_file_fails_with_an_IOException_not_a_RawException() + { + Assert.ThrowsAny(() => RawFile.Open(Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.nef"))); + } + + [Fact] + public void Truncating_a_file_anywhere_fails_with_a_RawException_and_nothing_else() + { + byte[] file = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 8, RawHeight = 4 }); + + for (int length = 0; length < file.Length; length++) + { + byte[] cut = file[..length]; + Exception? error = Record.Exception(() => Read(cut)); + Assert.True(error is RawException, $"length {length}: {error?.GetType().Name ?? "no error"}"); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Damaging_bytes_never_fails_with_anything_but_a_RawException(bool bigEndian) + { + byte[] original = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 8, RawHeight = 4, BigEndian = bigEndian }); + var random = new Random(12345); + + for (int iteration = 0; iteration < 5000; iteration++) + { + byte[] file = (byte[])original.Clone(); + int changes = random.Next(1, 6); + for (int i = 0; i < changes; i++) + { + file[random.Next(file.Length)] = (byte)random.Next(256); + } + + Exception? error = Record.Exception(() => Read(file)); + Assert.True(error is null or RawException, $"iteration {iteration}: {error?.GetType().Name}: {error?.Message}"); + } + } + + [Fact] + public void Reading_the_metadata_of_a_file_in_memory_stays_within_an_allocation_budget() + { + byte[] file = SyntheticNef.Build(); + Read(file); + + long before = GC.GetAllocatedBytesForCurrentThread(); + RawMetadata metadata = Read(file); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.NotNull(metadata); + Assert.True(allocated < 4_000, $"{allocated} bytes allocated"); + } + + [SkippableFact] + public void Every_real_file_of_the_sample_folder_can_be_read_quickly() + { + 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.GetFiles(directory!, "*.NEF"); + Skip.If(files.Length == 0, "No .NEF file in RAWNET_SAMPLES_DIR."); + RawFile.ReadMetadata(files[0]); + + var watch = System.Diagnostics.Stopwatch.StartNew(); + foreach (string file in files) + { + RawMetadata m = RawFile.ReadMetadata(file); + Assert.True(m.ImageWidth > 0 && m.ImageHeight > 0 && m.CfaPattern != CfaPattern.Unknown && m.Iso > 0); + } + + double perFile = watch.Elapsed.TotalMilliseconds / files.Length; + Assert.True(perFile < 50, $"{perFile:F2} ms per file"); + } + + private sealed class NonSeekableStream : MemoryStream + { + public override bool CanSeek => false; + } +} diff --git a/tests/Eleris.RawNet.Tests/Synthetic/IfdBuilder.cs b/tests/Eleris.RawNet.Tests/Synthetic/IfdBuilder.cs index 464a633..3ec0fd4 100644 --- a/tests/Eleris.RawNet.Tests/Synthetic/IfdBuilder.cs +++ b/tests/Eleris.RawNet.Tests/Synthetic/IfdBuilder.cs @@ -4,7 +4,7 @@ namespace Eleris.RawNet.Tests.Synthetic; /// Builds one little-endian TIFF directory, with the values that do not fit in the entry stored right after it. -internal sealed class IfdBuilder +internal sealed class IfdBuilder(bool bigEndian = false) { private const int ByteType = 1, AsciiType = 2, ShortType = 3, LongType = 4, RationalType = 5, UndefinedType = 7; @@ -33,7 +33,7 @@ public IfdBuilder Shorts(int tag, params ushort[] values) => Add(tag, ShortType, byte[] bytes = new byte[values.Length * 2]; for (int i = 0; i < values.Length; i++) { - BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(i * 2), values[i]); + Put16(bytes.AsSpan(i * 2), values[i]); } return bytes; @@ -48,7 +48,7 @@ public IfdBuilder LazyLongs(int tag, int count, Func values) => Add(tag, byte[] bytes = new byte[v.Length * 4]; for (int i = 0; i < v.Length; i++) { - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(i * 4), v[i]); + Put32(bytes.AsSpan(i * 4), v[i]); } return bytes; @@ -59,8 +59,8 @@ public IfdBuilder Rationals(int tag, params (uint Numerator, uint Denominator)[] byte[] bytes = new byte[values.Length * 8]; for (int i = 0; i < values.Length; i++) { - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(i * 8), values[i].Numerator); - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan((i * 8) + 4), values[i].Denominator); + Put32(bytes.AsSpan(i * 8), values[i].Numerator); + Put32(bytes.AsSpan((i * 8) + 4), values[i].Denominator); } return bytes; @@ -70,15 +70,15 @@ public IfdBuilder Rationals(int tag, params (uint Numerator, uint Denominator)[] public byte[] Serialize(long offset) { byte[] buffer = new byte[Size]; - BinaryPrimitives.WriteUInt16LittleEndian(buffer, (ushort)_entries.Count); + Put16(buffer, (ushort)_entries.Count); int dataPosition = 2 + (12 * _entries.Count) + 4; int index = 0; foreach (Entry entry in _entries.OrderBy(e => e.Tag)) { Span slot = buffer.AsSpan(2 + (12 * index++), 12); - BinaryPrimitives.WriteUInt16LittleEndian(slot, (ushort)entry.Tag); - BinaryPrimitives.WriteUInt16LittleEndian(slot[2..], (ushort)entry.Type); - BinaryPrimitives.WriteUInt32LittleEndian(slot[4..], (uint)entry.Count); + Put16(slot, (ushort)entry.Tag); + Put16(slot[2..], (ushort)entry.Type); + Put32(slot[4..], (uint)entry.Count); byte[] value = entry.Value(); if (value.Length != entry.ByteLength) { @@ -91,7 +91,7 @@ public byte[] Serialize(long offset) } else { - BinaryPrimitives.WriteUInt32LittleEndian(slot[8..], (uint)(offset + dataPosition)); + Put32(slot[8..], (uint)(offset + dataPosition)); value.CopyTo(buffer.AsSpan(dataPosition)); dataPosition += Even(value.Length); } @@ -111,6 +111,30 @@ private IfdBuilder Add(int tag, int type, int count, Func value) return this; } + private void Put16(Span destination, ushort value) + { + if (bigEndian) + { + BinaryPrimitives.WriteUInt16BigEndian(destination, value); + } + else + { + BinaryPrimitives.WriteUInt16LittleEndian(destination, value); + } + } + + private void Put32(Span destination, uint value) + { + if (bigEndian) + { + BinaryPrimitives.WriteUInt32BigEndian(destination, value); + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(destination, value); + } + } + private static int Even(int length) => (length + 1) & ~1; private static int TypeSize(int type) => type switch diff --git a/tests/Eleris.RawNet.Tests/Synthetic/SyntheticNef.cs b/tests/Eleris.RawNet.Tests/Synthetic/SyntheticNef.cs index fd57cf5..a9633fb 100644 --- a/tests/Eleris.RawNet.Tests/Synthetic/SyntheticNef.cs +++ b/tests/Eleris.RawNet.Tests/Synthetic/SyntheticNef.cs @@ -50,6 +50,21 @@ internal sealed record SyntheticNefOptions public ushort Iso { get; init; } = 1600; + /// True to write the file (and its MakerNote) in big-endian byte order, as older Nikon bodies do. + public bool BigEndian { get; init; } + + /// False to leave the body serial number out of the Exif directory (it stays in the MakerNote). + public bool IncludeExifSerial { get; init; } = true; + + /// False to leave DateTimeOriginal (and so its offset) out: only the date of the main directory remains. + public bool IncludeDateTimeOriginal { get; init; } = true; + + /// The OffsetTimeOriginal tag; when null it has the value of . + public string? OffsetTimeOriginal { get; init; } + + /// True to add a small reduced raw image (16 x 8, 12 bit) as the first sub-directory, as the camera does. + public bool SmallCfaSubImage { get; init; } + /// The bytes of the raw strip; by default a repeatable pattern of RawWidth * RawHeight * 2 bytes. public byte[]? RawStrip { get; init; } @@ -77,22 +92,46 @@ public static byte[] Build(SyntheticNefOptions? options = null) uint thumbnailOffset = 0, previewOffset = 0, rawOffset = 0, previewIfd = 0, rawIfd = 0, exifIfd = 0; byte[] makerNote = BuildMakerNote(options); - IfdBuilder exif = new IfdBuilder() + IfdBuilder exif = new IfdBuilder(options.BigEndian) .Rationals(33434, options.ExposureTime) .Rationals(33437, options.FNumber) .Shorts(34855, options.Iso) - .Text(36867, options.DateTime) .Text(36880, options.OffsetTime) + .Text(36881, options.OffsetTimeOriginal ?? options.OffsetTime) .Rationals(37386, options.FocalLength) .Undefined(37500, makerNote) - .Text(42033, options.SerialNumber) .Text(42036, options.LensModel); - IfdBuilder preview = new IfdBuilder() + if (options.IncludeExifSerial) + { + exif.Text(42033, options.SerialNumber); + } + + if (options.IncludeDateTimeOriginal) + { + exif.Text(36867, options.DateTime); + } + + uint smallIfd = 0; + IfdBuilder small = new IfdBuilder(options.BigEndian) + .Longs(254, 1) + .Longs(256, 16) + .Longs(257, 8) + .Shorts(258, 12) + .Shorts(259, (ushort)options.Compression) + .Shorts(262, CfaPhotometric) + .LazyLongs(273, 1, () => [thumbnailOffset]) + .Shorts(277, 1) + .Longs(278, 8) + .Longs(279, 4) + .Shorts(33421, 2, 2) + .Bytes(33422, options.CfaPattern); + + IfdBuilder preview = new IfdBuilder(options.BigEndian) .Longs(254, 1) .Shorts(259, 6) .LazyLongs(513, 1, () => [previewOffset]) .Longs(514, (uint)options.PreviewJpeg.Length); - IfdBuilder raw = new IfdBuilder() + IfdBuilder raw = new IfdBuilder(options.BigEndian) .Longs(254, 0) .Longs(256, (uint)options.RawWidth) .Longs(257, (uint)options.RawHeight) @@ -105,7 +144,7 @@ public static byte[] Build(SyntheticNefOptions? options = null) .Longs(279, (uint)rawStrip.Length) .Shorts(33421, 2, 2) .Bytes(33422, options.CfaPattern); - IfdBuilder main = new IfdBuilder() + IfdBuilder main = new IfdBuilder(options.BigEndian) .Longs(254, 1) .Longs(256, 8) .Longs(257, 6) @@ -121,7 +160,7 @@ public static byte[] Build(SyntheticNefOptions? options = null) .Longs(279, (uint)thumbnail.Length) .Text(305, options.Software) .Text(306, options.DateTime) - .LazyLongs(330, 2, () => [previewIfd, rawIfd]) + .LazyLongs(330, options.SmallCfaSubImage ? 3 : 2, () => options.SmallCfaSubImage ? [smallIfd, previewIfd, rawIfd] : [previewIfd, rawIfd]) .LazyLongs(34665, 1, () => [exifIfd]); // Layout: header, main directory, sub-directories, Exif directory, then the pixel data, all on even offsets. @@ -134,6 +173,12 @@ public static byte[] Build(SyntheticNefOptions? options = null) position += raw.Size; exifIfd = (uint)position; position += exif.Size; + smallIfd = (uint)position; + if (options.SmallCfaSubImage) + { + position += small.Size; + } + thumbnailOffset = (uint)position; position += thumbnail.Length; previewOffset = (uint)position; @@ -142,14 +187,26 @@ public static byte[] Build(SyntheticNefOptions? options = null) position += Even(rawStrip.Length); byte[] file = new byte[position]; - file[0] = (byte)'I'; - file[1] = (byte)'I'; - BinaryPrimitives.WriteUInt16LittleEndian(file.AsSpan(2), 42); - BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(4), (uint)mainIfd); + file[0] = file[1] = options.BigEndian ? (byte)'M' : (byte)'I'; + if (options.BigEndian) + { + BinaryPrimitives.WriteUInt16BigEndian(file.AsSpan(2), 42); + BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(4), (uint)mainIfd); + } + else + { + BinaryPrimitives.WriteUInt16LittleEndian(file.AsSpan(2), 42); + BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(4), (uint)mainIfd); + } main.Serialize(mainIfd).CopyTo(file, mainIfd); preview.Serialize(previewIfd).CopyTo(file, previewIfd); raw.Serialize(rawIfd).CopyTo(file, rawIfd); exif.Serialize(exifIfd).CopyTo(file, exifIfd); + if (options.SmallCfaSubImage) + { + small.Serialize(smallIfd).CopyTo(file, smallIfd); + } + thumbnail.CopyTo(file, thumbnailOffset); options.PreviewJpeg.CopyTo(file, previewOffset); rawStrip.CopyTo(file, rawOffset); @@ -159,7 +216,7 @@ public static byte[] Build(SyntheticNefOptions? options = null) /// The MakerNote: the "Nikon" header, then a TIFF header and a directory whose offsets count from that header. private static byte[] BuildMakerNote(SyntheticNefOptions options) { - IfdBuilder directory = new IfdBuilder() + IfdBuilder directory = new IfdBuilder(options.BigEndian) .Text(0x04, "RAW") .Rationals(0x0C, options.WhiteBalance) .Text(0x1D, options.SerialNumber) @@ -167,7 +224,9 @@ private static byte[] BuildMakerNote(SyntheticNefOptions options) .Shorts(0x45, options.ActiveArea) .Longs(0xA7, options.ShutterCount); byte[] header = [(byte)'N', (byte)'i', (byte)'k', (byte)'o', (byte)'n', 0, 2, 0x11, 0, 0]; - byte[] tiffHeader = [(byte)'I', (byte)'I', 42, 0, 8, 0, 0, 0]; + byte[] tiffHeader = options.BigEndian + ? [(byte)'M', (byte)'M', 0, 42, 0, 0, 0, 8] + : [(byte)'I', (byte)'I', 42, 0, 8, 0, 0, 0]; return [.. header, .. tiffHeader, .. directory.Serialize(8)]; }