diff --git a/CHANGELOG.md b/CHANGELOG.md index d3dd546..e11d8a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)` 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. diff --git a/README.md b/README.md index b6cf5e4..1d2114c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/Eleris.RawNet/Internal/NefStructureReader.cs b/src/Eleris.RawNet/Internal/NefStructureReader.cs index 2a9396b..8e8995e 100644 --- a/src/Eleris.RawNet/Internal/NefStructureReader.cs +++ b/src/Eleris.RawNet/Internal/NefStructureReader.cs @@ -40,7 +40,7 @@ public NefStructure Read(ByteSource source) } var previews = new List(); - 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)) { @@ -122,9 +122,9 @@ internal static ByteRange[] LargestFirst(List 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 previews) + private static RawSubImage ReadRawImage(TiffReader reader, Ifd main, long fileLength, List previews) { if (!main.TryGet(SubIfdsTag, out IfdEntry subEntry)) { @@ -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) diff --git a/src/Eleris.RawNet/Internal/UncompressedDecoder.cs b/src/Eleris.RawNet/Internal/UncompressedDecoder.cs new file mode 100644 index 0000000..8de8847 --- /dev/null +++ b/src/Eleris.RawNet/Internal/UncompressedDecoder.cs @@ -0,0 +1,134 @@ +using System.Buffers; + +namespace Eleris.RawNet.Internal; + +/// +/// 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. +/// +internal static class UncompressedDecoder +{ + private const int ChunkBytes = 1 << 20; + + /// The sample sizes that are decoded. + public static bool IsSupported(int bitsPerSample) => bitsPerSample is 12 or 14; + + /// The size in bytes of a row of samples. + public static long RowBytes(int width, int bitsPerSample) => (((long)width * bitsPerSample) + 7) / 8; + + /// + /// 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. + /// + 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 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.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.Shared.Return(buffer); + } + } + + /// Unpacks the samples of a row, bits each, most significant bit first. + internal static void Unpack(ReadOnlySpan row, int bits, Span 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); + } + } + + /// The strips of the raw image read as one continuous run of bytes. + private sealed class StripStream(ByteSource source, IReadOnlyList strips) + { + private int _strip; + private long _used; + + public void ReadExactly(Span 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..]; + } + } + } +} diff --git a/src/Eleris.RawNet/RawFile.cs b/src/Eleris.RawNet/RawFile.cs index 4913a3c..f2309d1 100644 --- a/src/Eleris.RawNet/RawFile.cs +++ b/src/Eleris.RawNet/RawFile.cs @@ -80,6 +80,49 @@ public int ReadPreviewJpeg(RawPreview preview, Span destination) return preview.ByteCount; } + /// Decodes the raw image into a new array. + /// Cancels the decoding. + /// The mosaic and what describes it. + /// The samples use a compression the library does not decode yet; only uncompressed samples are decoded for now. + /// The samples have a size the library does not decode (12 and 14 bits are). + /// The strips of the raw image are too short for the image. + /// The file is disposed. + /// The decoding was cancelled. + /// The array of a full-frame image is tens of megabytes; to decode many images, use with a buffer you reuse. + public RawImage Decode(CancellationToken cancellationToken = default) + { + PrepareDecode(); + RawMetadata metadata = Metadata; + ushort[] mosaic = GC.AllocateUninitializedArray(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); + } + + /// Decodes the raw image into a buffer of the caller, row after row, without allocating the mosaic. + /// The buffer; it must hold at least times samples. + /// Cancels the decoding. + /// The number of samples written. + /// is too small. + /// The samples use a compression the library does not decode yet; only uncompressed samples are decoded for now. + /// The samples have a size the library does not decode (12 and 14 bits are). + /// The strips of the raw image are too short for the image. + /// The file is disposed. + /// The decoding was cancelled. + /// When the decoding fails, may be partly written. Disposing the file during a decoding is not supported. + public int Decode(Span 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; + } + /// /// 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. @@ -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); diff --git a/src/Eleris.RawNet/RawImage.cs b/src/Eleris.RawNet/RawImage.cs new file mode 100644 index 0000000..056cdd3 --- /dev/null +++ b/src/Eleris.RawNet/RawImage.cs @@ -0,0 +1,36 @@ +namespace Eleris.RawNet; + +/// +/// The decoded raw image: the mosaic of samples the sensor recorded, one sample per photosite, before any demosaicing, +/// black-level subtraction or scaling. +/// +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; + } + + /// The width in pixels of the mosaic, margins included. + public int Width { get; } + + /// The height in pixels of the mosaic, margins included. + public int Height { get; } + + /// The part of the mosaic that holds the picture, as says. + public RawRectangle ActiveArea { get; } + + /// The colour filter pattern from the top-left sample of the mosaic. + public CfaPattern CfaPattern { get; } + + /// The number of bits of a sample: every sample is smaller than 1 << BitsPerSample. + public int BitsPerSample { get; } + + /// The samples, row after row, times of them. + public ReadOnlyMemory Mosaic { get; } +} diff --git a/tests/Eleris.RawNet.Tests/DecodeTests.cs b/tests/Eleris.RawNet.Tests/DecodeTests.cs new file mode 100644 index 0000000..59ccbc6 --- /dev/null +++ b/tests/Eleris.RawNet.Tests/DecodeTests.cs @@ -0,0 +1,376 @@ +using Eleris.RawNet.Internal; +using Eleris.RawNet.Tests.Synthetic; + +namespace Eleris.RawNet.Tests; + +public class DecodeTests +{ + /// Packs samples the way an uncompressed raw image stores them: most significant bit first, each row on a byte boundary. + internal static byte[] Pack(ushort[] samples, int width, int bits) + { + int height = samples.Length / width; + int rowBytes = ((width * bits) + 7) / 8; + byte[] packed = new byte[rowBytes * height]; + for (int row = 0; row < height; row++) + { + for (int col = 0; col < width; col++) + { + int start = col * bits; + for (int bit = 0; bit < bits; bit++) + { + if ((samples[(row * width) + col] >> (bits - 1 - bit) & 1) != 0) + { + int position = start + bit; + packed[(row * rowBytes) + (position >> 3)] |= (byte)(0x80 >> (position & 7)); + } + } + } + } + + return packed; + } + + private static ushort[] RandomSamples(int count, int bits, int seed) + { + var random = new Random(seed); + ushort[] samples = new ushort[count]; + for (int i = 0; i < samples.Length; i++) + { + samples[i] = (ushort)random.Next(1 << bits); + } + + return samples; + } + + private static byte[] Uncompressed(ushort[] samples, int width, int height, int bits, bool bigEndian = false, int[]? activeArea = null) => + SyntheticNef.Build(new SyntheticNefOptions + { + RawWidth = width, + RawHeight = height, + BitsPerSample = bits, + Compression = 1, + BigEndian = bigEndian, + ActiveArea = activeArea is null ? [0, 0, (ushort)width, (ushort)height] : [.. activeArea.Select(v => (ushort)v)], + RawStrip = Pack(samples, width, bits), + }); + + [Theory] + [InlineData(12, 64, 48, false)] + [InlineData(14, 64, 48, false)] + [InlineData(12, 64, 48, true)] + [InlineData(14, 64, 48, true)] + [InlineData(12, 9, 7, false)] + [InlineData(14, 11, 5, true)] + [InlineData(14, 1, 1, false)] + public void The_samples_of_an_uncompressed_image_are_decoded_whatever_the_width(int bits, int width, int height, bool bigEndian) + { + ushort[] expected = RandomSamples(width * height, bits, width + height); + using RawFile raw = RawFile.Open(Uncompressed(expected, width, height, bits, bigEndian)); + + RawImage image = raw.Decode(); + + Assert.Equal(width, image.Width); + Assert.Equal(height, image.Height); + Assert.Equal(bits, image.BitsPerSample); + Assert.Equal(expected, image.Mosaic.ToArray()); + } + + [Fact] + public void The_extreme_samples_are_kept() + { + foreach (int bits in new[] { 12, 14 }) + { + ushort max = (ushort)((1 << bits) - 1); + ushort[] expected = [0, max, max, 0, max, 0, 0, max]; + using RawFile raw = RawFile.Open(Uncompressed(expected, 4, 2, bits)); + + Assert.Equal(expected, raw.Decode().Mosaic.ToArray()); + } + } + + [Fact] + public void The_image_carries_what_describes_it() + { + ushort[] samples = RandomSamples(16 * 8, 14, 3); + using RawFile raw = RawFile.Open(Uncompressed(samples, 16, 8, 14, activeArea: [2, 1, 12, 6])); + + RawImage image = raw.Decode(); + + Assert.Equal(raw.Metadata.ActiveArea, image.ActiveArea); + Assert.Equal(new RawRectangle(2, 1, 12, 6), image.ActiveArea); + Assert.Equal(raw.Metadata.CfaPattern, image.CfaPattern); + } + + [Fact] + public void An_image_can_be_decoded_into_a_buffer_that_is_larger_than_needed() + { + ushort[] expected = RandomSamples(10 * 6, 12, 9); + using RawFile raw = RawFile.Open(Uncompressed(expected, 10, 6, 12)); + ushort[] buffer = new ushort[(10 * 6) + 5]; + Array.Fill(buffer, (ushort)0xFFFF); + + int written = raw.Decode(buffer); + + Assert.Equal(60, written); + Assert.Equal(expected, buffer[..60]); + Assert.All(buffer[60..], v => Assert.Equal(0xFFFF, v)); + Assert.Throws(() => raw.Decode(new ushort[59])); + } + + [Fact] + public void Decoding_into_a_buffer_does_not_allocate_more_than_a_little() + { + ushort[] samples = RandomSamples(64 * 48, 14, 5); + using RawFile raw = RawFile.Open(Uncompressed(samples, 64, 48, 14)); + ushort[] buffer = new ushort[64 * 48]; + raw.Decode(buffer); + + long before = GC.GetAllocatedBytesForCurrentThread(); + raw.Decode(buffer); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(allocated <= 512, $"{allocated} bytes allocated"); + } + + [Fact] + public void Strips_that_end_inside_a_row_are_read_as_one_run_of_bytes() + { + const int width = 9, height = 6, bits = 14; + ushort[] expected = RandomSamples(width * height, bits, 11); + byte[] data = Pack(expected, width, bits); + // Three strips of unequal sizes, the first two ending inside a row, in the middle of a file with other bytes around. + int[] cuts = [0, 7, 40, data.Length]; + byte[] file = new byte[1000]; + var strips = new List(); + long place = 100; + for (int i = 0; i < 3; i++) + { + data.AsSpan(cuts[i], cuts[i + 1] - cuts[i]).CopyTo(file.AsSpan((int)place)); + strips.Add(new ByteRange(place, cuts[i + 1] - cuts[i])); + place += 300; + } + + RawMetadata metadata = new() + { + MediaType = RawMediaTypes.NikonNef, + Make = "m", + Model = "m", + ImageWidth = width, + ImageHeight = height, + ActiveArea = new RawRectangle(0, 0, width, height), + CfaPattern = CfaPattern.Rggb, + BitsPerSample = bits, + Compression = RawCompression.Uncompressed, + CompressionCode = 1, + }; + var structure = new NefStructure(metadata, strips, []); + ushort[] decoded = new ushort[width * height]; + + UncompressedDecoder.Decode(ByteSource.FromMemory(file), structure, decoded, CancellationToken.None); + + Assert.Equal(expected, decoded); + } + + private static NefStructure Structure(int width, int height, int bits, List strips) => + new( + new RawMetadata + { + MediaType = RawMediaTypes.NikonNef, + Make = "m", + Model = "m", + ImageWidth = width, + ImageHeight = height, + ActiveArea = new RawRectangle(0, 0, width, height), + CfaPattern = CfaPattern.Rggb, + BitsPerSample = bits, + Compression = RawCompression.Uncompressed, + CompressionCode = 1, + }, + strips, + []); + + [Theory] + [InlineData(1)] + [InlineData(20)] + [InlineData(41)] + [InlineData(1000)] + public void Decoding_by_blocks_of_any_size_gives_the_same_samples(int chunkBytes) + { + const int width = 13, height = 11, bits = 14; + ushort[] expected = RandomSamples(width * height, bits, 21); + byte[] data = Pack(expected, width, bits); + ushort[] decoded = new ushort[width * height]; + + UncompressedDecoder.Decode(ByteSource.FromMemory(data), Structure(width, height, bits, [new ByteRange(0, 50), new ByteRange(50, data.Length - 50)]), decoded, CancellationToken.None, chunkBytes); + + Assert.Equal(expected, decoded); + } + + [Fact] + public void Strips_that_overlap_are_refused_but_strips_given_out_of_order_are_not() + { + const int width = 8, height = 4, bits = 12; + int rowBytes = width * bits / 8; + + Assert.Throws(() => UncompressedDecoder.CheckStrips(Structure(width, height, bits, [new ByteRange(0, rowBytes * 3), new ByteRange(0, rowBytes * 3)]))); + Assert.Throws(() => UncompressedDecoder.CheckStrips(Structure(width, height, bits, [new ByteRange(0, rowBytes * 2), new ByteRange(rowBytes, rowBytes * 2)]))); + UncompressedDecoder.CheckStrips(Structure(width, height, bits, [new ByteRange(rowBytes * 2, rowBytes * 2), new ByteRange(0, rowBytes * 2), new ByteRange(rowBytes * 4, 0)])); + } + + [Fact] + public void An_image_with_more_samples_than_an_array_can_hold_is_refused_before_anything_is_allocated() + { + byte[] huge = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 1 << 20, RawHeight = 1 << 20, BitsPerSample = 12, Compression = 1, RawStrip = new byte[64] }); + using RawFile raw = RawFile.Open(huge); + Assert.Throws(() => raw.Decode()); + + byte[] large = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 40000, RawHeight = 40000, BitsPerSample = 12, Compression = 1, RawStrip = new byte[64] }); + using RawFile other = RawFile.Open(large); + Assert.Throws(() => other.Decode()); + } + + [Fact] + public void A_file_opened_from_a_stream_is_decoded_and_leaves_the_stream_where_it_can_be_reused() + { + ushort[] expected = RandomSamples(20 * 10, 12, 6); + using var stream = new MemoryStream(Uncompressed(expected, 20, 10, 12)); + using RawFile raw = RawFile.Open(stream); + + Assert.Equal(expected, raw.Decode().Mosaic.ToArray()); + Assert.Equal(expected, raw.Decode().Mosaic.ToArray()); + } + + [Theory] + [InlineData(12)] + [InlineData(14)] + [InlineData(13)] + [InlineData(16)] + public void Unpacking_matches_a_reading_bit_by_bit(int bits) + { + ushort[] expected = RandomSamples(37, bits, bits); + byte[] packed = Pack(expected, 37, bits); + ushort[] samples = new ushort[37]; + + UncompressedDecoder.Unpack(packed, bits, samples); + + Assert.Equal(expected, samples); + } + + [Fact] + public void Samples_of_a_size_the_library_does_not_decode_are_refused() + { + byte[] file = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 8, RawHeight = 4, BitsPerSample = 16, Compression = 1, RawStrip = new byte[64] }); + using RawFile raw = RawFile.Open(file); + + Assert.Throws(() => raw.Decode()); + Assert.Throws(() => raw.Decode(new ushort[32])); + } + + [Fact] + public void A_compression_the_library_does_not_decode_is_reported_with_its_code() + { + using RawFile nikon = RawFile.Open(SyntheticNef.Build()); + var error = Assert.Throws(() => nikon.Decode()); + Assert.Equal(34713, error.Code); + Assert.Equal("Nikon compressed", error.Name); + + using RawFile other = RawFile.Open(SyntheticNef.Build(new SyntheticNefOptions { Compression = 7 })); + var unknown = Assert.Throws(() => other.Decode(new ushort[64 * 48])); + Assert.Equal(7, unknown.Code); + Assert.Null(unknown.Name); + } + + [Fact] + public void Strips_that_are_too_short_for_the_image_are_reported_as_corrupt_before_anything_is_allocated() + { + ushort[] samples = RandomSamples(16 * 8, 12, 1); + byte[] packed = Pack(samples, 16, 12); + byte[] file = SyntheticNef.Build(new SyntheticNefOptions { RawWidth = 16, RawHeight = 8, BitsPerSample = 12, Compression = 1, RawStrip = packed[..^1] }); + using RawFile raw = RawFile.Open(file); + + Assert.Throws(() => raw.Decode()); + Assert.Throws(() => raw.Decode(new ushort[16 * 8])); + } + + [Fact] + public void A_cancelled_decoding_stops() + { + using RawFile raw = RawFile.Open(Uncompressed(RandomSamples(64 * 48, 14, 2), 64, 48, 14)); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + + Assert.Throws(() => raw.Decode(cancelled.Token)); + Assert.Equal(64 * 48, raw.Decode().Mosaic.Length); + } + + [Fact] + public void A_disposed_file_cannot_be_decoded() + { + RawFile raw = RawFile.Open(Uncompressed(RandomSamples(64 * 48, 14, 2), 64, 48, 14)); + raw.Dispose(); + + Assert.Throws(() => raw.Decode()); + Assert.Throws(() => raw.Decode(new ushort[64 * 48])); + } + + [Fact] + public void A_file_opened_from_a_path_is_decoded_by_several_threads() + { + ushort[] expected = RandomSamples(64 * 48, 14, 8); + string path = Path.Combine(Path.GetTempPath(), $"rawnet-{Guid.NewGuid():N}.nef"); + File.WriteAllBytes(path, Uncompressed(expected, 64, 48, 14)); + try + { + using RawFile raw = RawFile.Open(path); + + Parallel.For(0, 100, _ => Assert.Equal(expected, raw.Decode().Mosaic.ToArray())); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void A_damaged_file_fails_to_decode_only_with_a_raw_exception() + { + byte[] intact = Uncompressed(RandomSamples(32 * 16, 14, 4), 32, 16, 14); + var random = new Random(42); + for (int attempt = 0; attempt < 2000; attempt++) + { + byte[] file = (byte[])intact.Clone(); + for (int k = 0; k < 1 + random.Next(4); k++) + { + file[random.Next(file.Length)] = (byte)random.Next(256); + } + + if (attempt % 5 == 0) + { + file = file[..random.Next(file.Length)]; + } + + try + { + using RawFile raw = RawFile.Open(file); + raw.Decode(); + } + catch (RawException) + { + } + } + } + + [SkippableFact] + public void A_real_file_that_is_compressed_is_refused_cleanly_until_its_compression_is_decoded() + { + 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? path = Directory.EnumerateFiles(directory!, "*.NEF").Order(StringComparer.Ordinal).FirstOrDefault(); + Skip.If(path is null, "No .NEF file in RAWNET_SAMPLES_DIR."); + + using RawFile raw = RawFile.Open(path!); + Skip.If(raw.Metadata.Compression == RawCompression.Uncompressed, "The sample is uncompressed."); + + Assert.Throws(() => raw.Decode()); + } +}