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
1 change: 1 addition & 0 deletions src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static Sdcb.SimdCodecs.Tiff.TiffImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader!
2 changes: 2 additions & 0 deletions src/Sdcb.SimdCodecs.Tiff/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ Old-style JPEG (Compression 6), CIELab, subsampled YCbCr stored in separate plan

A `DecodeOptions.Region` reads only the strips or tiles it intersects, and `TryDecodeInto` writes integer pages band by band into the caller's buffer without a page raster; both give exactly the pixels of decoding the page whole and then cropping and converting it (`TiffRegionDecodeTests`).

`TiffImageDecoder.CreateRowReader` reads the first page from a stream, rows top to bottom, synchronously or asynchronously, with exactly `TryDecodeInto`'s rows (`TiffStreamingDecodeTests`). A TIFF needs random access, so it streams only from a seekable stream: it reads the directory by offset, then one strip or row of tiles at a time, holding that band and its coded bytes rather than the file or the page. A stream that cannot seek, a float page, an option other than the whole image at full size, and a file whose bands or directories lie so scattered that streaming would read through more than twice the file (separate planes stored one after another, as libtiff writes them) are read whole and decoded instead; `IsStreaming` says which. `TiffReader.Read(Stream)` reads a seekable stream by offset as well, without copying it.

## Writing

`TiffWriter` writes classic TIFF (never BigTIFF): uncompressed or Deflate, strips or tiles, 8/16/32-bit integer and float samples, with ICC, XMP and Exif.
53 changes: 47 additions & 6 deletions src/Sdcb.SimdCodecs.Tiff/TiffIfd.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ internal interface ITiffBytes

/// <summary>Fills <paramref name="destination"/> from <paramref name="offset"/>; throws <see cref="InvalidDataException"/> when the range is not inside the file.</summary>
void Read(long offset, scoped Span<byte> destination);

/// <summary>
/// <paramref name="length"/> bytes from <paramref name="offset"/>, where the caller checked they lie inside the file:
/// a slice of the bytes when they are in memory, else read into <paramref name="buffer"/> (rented from the shared
/// pool, grown as needed; the caller returns it). Valid until the next call with the same buffer.
/// </summary>
ReadOnlySpan<byte> View(long offset, int length, ref byte[]? buffer);
}

internal readonly ref struct SpanBytes(ReadOnlySpan<byte> bytes) : ITiffBytes
Expand All @@ -27,18 +34,44 @@ public void Read(long offset, scoped Span<byte> destination)
throw new InvalidDataException("TIFF data extends past the end of the file");
_bytes.Slice((int)offset, destination.Length).CopyTo(destination);
}

public ReadOnlySpan<byte> View(long offset, int length, ref byte[]? buffer)
{
if (offset < 0 || offset + length > _bytes.Length)
throw new InvalidDataException("TIFF data extends past the end of the file");
return _bytes.Slice((int)offset, length);
}
}

/// <summary>A seekable stream as TIFF bytes. Every read seeks, so only what is asked for is touched.</summary>
internal static class TiffBuffers
{
/// <summary>Rents <paramref name="buffer"/> from the shared pool at <paramref name="length"/> bytes or more; returns its first <paramref name="length"/> bytes.</summary>
public static Span<byte> Ensure(ref byte[]? buffer, int length)
{
if (buffer is null || buffer.Length < length)
{
if (buffer is not null) System.Buffers.ArrayPool<byte>.Shared.Return(buffer);
buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(length);
}
return buffer.AsSpan(0, length);
}
}

/// <summary>
/// A seekable stream as TIFF bytes, offsets counted from <c>origin</c> (where the TIFF starts in the stream). Every
/// read seeks, so only what is asked for is touched.
/// </summary>
internal sealed class StreamBytes : ITiffBytes
{
private readonly Stream _stream;
private readonly long _origin;

public StreamBytes(Stream stream)
public StreamBytes(Stream stream, long origin = 0)
{
if (!stream.CanSeek) throw new ArgumentException("The stream must be seekable", nameof(stream));
_stream = stream;
Length = stream.Length;
_origin = origin;
Length = Math.Max(0, stream.Length - origin);
}

public long Length { get; }
Expand All @@ -47,7 +80,7 @@ public void Read(long offset, scoped Span<byte> destination)
{
if (offset < 0 || offset + destination.Length > Length)
throw new InvalidDataException("TIFF data extends past the end of the file");
_stream.Position = offset;
_stream.Position = _origin + offset;
var done = 0;
while (done < destination.Length)
{
Expand All @@ -56,6 +89,13 @@ public void Read(long offset, scoped Span<byte> destination)
done += n;
}
}

public ReadOnlySpan<byte> View(long offset, int length, ref byte[]? buffer)
{
var span = TiffBuffers.Ensure(ref buffer, length);
Read(offset, span);
return span;
}
}

/// <summary>
Expand Down Expand Up @@ -123,7 +163,7 @@ internal static class TiffIfdParser
internal const int MaxSamplesPerPixel = 256;

/// <summary>Entries a BigTIFF directory may declare (its count is 64-bit); a classic one holds at most 65535.</summary>
private const long MaxEntries = 1 << 20;
internal const long MaxEntries = 1 << 20;

/// <summary>
/// Parses the header at the start of <paramref name="src"/>: classic TIFF (TIFF 6.0 §2, 8 bytes) or BigTIFF (the
Expand Down Expand Up @@ -575,7 +615,8 @@ private static byte[] Value<T>(ref T src, ulong count, int elemSize, ReadOnlySpa
var total = (long)count * elemSize;
if (total <= f.OffsetSize) return valueSpan[..(int)total].ToArray();
var offset = Offset(valueSpan, f);
if (total > src.Length || offset > src.Length - total)
// A stream may be longer than an array holds; a span never is, so the last test changes nothing for it.
if (total > src.Length || offset > src.Length - total || total > Array.MaxLength)
throw new InvalidDataException("Tag value extends past the end of the file");
var buffer = new byte[total];
src.Read(offset, buffer);
Expand Down
56 changes: 39 additions & 17 deletions src/Sdcb.SimdCodecs.Tiff/TiffImageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ namespace Sdcb.SimdCodecs.Tiff;
/// per row of tiles and per page.
/// </para>
/// </summary>
public sealed class TiffImageDecoder : IMultiFrameImageDecoder
public sealed class TiffImageDecoder : IMultiFrameImageDecoder, IStreamingImageDecoder
{
/// <summary>The registration for <c>ImageCodecs.Register</c>, built from this type's method groups.</summary>
public static ImageDecoderRegistration Registration { get; } = new()
Expand All @@ -55,6 +55,7 @@ public sealed class TiffImageDecoder : IMultiFrameImageDecoder
TryReadMetadata = TryReadMetadata,
TryDecodeThumbnail = TryDecodeThumbnail,
TryOpenFrames = TryOpenFrames,
CreateRowReader = CreateRowReader,
};

/// <inheritdoc />
Expand Down Expand Up @@ -117,6 +118,21 @@ public static bool TryOpenFrames(ReadOnlyMemory<byte> data, [NotNullWhen(true)]
return true;
}

/// <inheritdoc />
/// <remarks>
/// The first page, a band of rows at a time. TIFF needs random access (the directory is usually written after the
/// pixels), so the reader streams only when the stream can seek: it reads the header, the first page's directory
/// and the IFD chain's next pointers by offset, then each strip, or row of tiles (every plane's segments, for a
/// planar page), decodes it exactly as <see cref="TryDecodeInto"/> does and hands out its rows; it holds one band
/// and its coded bytes, never the file or the page. The input moves forward only by reading, so a file whose bands
/// (or directories) would make it read through more than twice the file -- separate planes stored one after another,
/// a chain that jumps back and forth -- is decoded whole instead, as are a stream that cannot seek, a float page
/// (which <see cref="TryDecodeInto"/> has no integer projection for) and any option but the whole image at full
/// size (<see cref="IImageRowReader.IsStreaming"/> false). The rows are <see cref="TryDecodeInto"/>'s either way.
/// </remarks>
public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) =>
new TiffRowReader(input, format, options);

/// <summary>The layout <see cref="TryDecodePage"/> gives page <paramref name="pageIndex"/>, from its directory alone.</summary>
internal static bool TryReadPageInfo(ReadOnlySpan<byte> data, int pageIndex, out ImageInfo info)
{
Expand All @@ -126,14 +142,7 @@ internal static bool TryReadPageInfo(ReadOnlySpan<byte> data, int pageIndex, out
var layout = TiffReader.ReadLayout(data, pageIndex);
if (!TiffColor.TryCreate(layout, out var plan))
return false;
info = new ImageInfo(layout.Width, layout.Height, plan.OutChannels, plan.OutFormat)
{
Format = ImageFormat.Tiff,
BitDepth = layout.Photometric == TiffPhotometric.Palette ? (layout.StoredBitsPerSample == 16 ? 16 : 8) : layout.StoredBitsPerSample,
Orientation = (ImageOrientation)layout.Orientation,
ColorEncoding = ColorOf(layout),
Resolution = ResolutionOf(layout),
};
info = InfoOf(layout, plan);
return true;
}
catch (Exception e) when (e is InvalidDataException or ArgumentException or NotSupportedException)
Expand All @@ -142,6 +151,17 @@ internal static bool TryReadPageInfo(ReadOnlySpan<byte> data, int pageIndex, out
}
}

/// <summary>The <see cref="ImageInfo"/> of the page <paramref name="layout"/> describes (one frame).</summary>
internal static ImageInfo InfoOf(TiffPageLayout layout, TiffColor plan) =>
new(layout.Width, layout.Height, plan.OutChannels, plan.OutFormat)
{
Format = ImageFormat.Tiff,
BitDepth = layout.Photometric == TiffPhotometric.Palette ? (layout.StoredBitsPerSample == 16 ? 16 : 8) : layout.StoredBitsPerSample,
Orientation = (ImageOrientation)layout.Orientation,
ColorEncoding = ColorOf(layout),
Resolution = ResolutionOf(layout),
};

/// <inheritdoc />
/// <remarks>TIFF has no scaling. Integer pages are decoded strip by strip (or by row of tiles) straight into
/// <paramref name="destination"/>: only the segments a <see cref="DecodeOptions.Region"/> intersects are read, and
Expand Down Expand Up @@ -187,6 +207,7 @@ internal static bool TryDecodePageInto(ReadOnlySpan<byte> data, int pageIndex, S
var bandRows = Math.Min(layout.Geometry.SegmentHeight, rect.Height);
var bandStride = rect.Width * plan.OutBytesPerPixel;
var band = ArrayPool<byte>.Shared.Rent(bandRows * bandStride);
var src = new SpanBytes(data);
try
{
var first = layout.Geometry.DownIndexForRow(rect.Y);
Expand All @@ -195,7 +216,7 @@ internal static bool TryDecodePageInto(ReadOnlySpan<byte> data, int pageIndex, S
{
cancellationToken.ThrowIfCancellationRequested();
var (y0, rows) = BandRows(layout, rect, down);
DecodeBand(data, layout, plan, rect, down, band.AsSpan(0, rows * bandStride), bandStride);
DecodeBand(ref src, layout, plan, rect, down, band.AsSpan(0, rows * bandStride), bandStride);
for (var r = 0; r < rows; r++)
{
PixelConverter.ConvertRow(band.AsSpan(r * bandStride, bandStride), plan.OutChannels, plan.OutFormat,
Expand All @@ -215,7 +236,7 @@ internal static bool TryDecodePageInto(ReadOnlySpan<byte> data, int pageIndex, S
}

/// <summary>The first image row of segment row <paramref name="down"/> inside <paramref name="rect"/>, and how many there are.</summary>
private static (int Y0, int Rows) BandRows(TiffPageLayout layout, PixelRect rect, int down)
internal static (int Y0, int Rows) BandRows(TiffPageLayout layout, PixelRect rect, int down)
{
var g = layout.Geometry;
var y0 = Math.Max(rect.Y, g.FirstRow(down));
Expand All @@ -231,8 +252,8 @@ private static (int Y0, int Rows) BandRows(TiffPageLayout layout, PixelRect rect
/// equals the same rectangle of the whole page; a chunky strip the file does not list (a short strip list, which
/// the whole-page read tolerates) is left as zeros, as the whole-page read leaves it.
/// </summary>
private static void DecodeBand(ReadOnlySpan<byte> data, TiffPageLayout layout, TiffColor plan, PixelRect rect,
int down, Span<byte> band, int bandStride)
internal static void DecodeBand<T>(ref T src, TiffPageLayout layout, TiffColor plan, PixelRect rect,
int down, Span<byte> band, int bandStride) where T : ITiffBytes, allows ref struct
{
var g = layout.Geometry;
var (y0, rows) = BandRows(layout, rect, down);
Expand Down Expand Up @@ -261,7 +282,7 @@ private static void DecodeBand(ReadOnlySpan<byte> data, TiffPageLayout layout, T
if (segment is not null) ArrayPool<byte>.Shared.Return(segment);
segment = ArrayPool<byte>.Shared.Rent(need);
}
TiffReader.ReadSegment(data, layout, index, segment);
TiffReader.ReadSegmentCore(ref src, layout, index, segment);
var segStride = seg.Width * inBpp;
for (var r = 0; r < rows; r++)
{
Expand Down Expand Up @@ -369,14 +390,15 @@ internal static IDecodedImage DecodePage(ReadOnlySpan<byte> data, int pageIndex,
try
{
var target = result.WritablePixels;
var src = new SpanBytes(data);
var bandStride = region.Width * plan.OutBytesPerPixel;
var first = layout.Geometry.DownIndexForRow(region.Y);
var last = layout.Geometry.DownIndexForRow(region.Y + region.Height - 1);
for (var down = first; down <= last; down++)
{
cancellationToken.ThrowIfCancellationRequested();
var (y0, rows) = BandRows(layout, region, down);
DecodeBand(data, layout, plan, region, down,
DecodeBand(ref src, layout, plan, region, down,
target.Slice((y0 - region.Y) * bandStride, rows * bandStride), bandStride);
}
}
Expand Down Expand Up @@ -427,12 +449,12 @@ internal static IDecodedImage DecodePage(ReadOnlySpan<byte> data, int pageIndex,

// A reader exception other than InvalidDataException (an argument the file's numbers make invalid, a compression
// or layout the reader does not support) as the InvalidDataException Decode throws for untrusted input.
private static InvalidDataException Undecodable(Exception e) =>
internal static InvalidDataException Undecodable(Exception e) =>
new(e is NotSupportedException ? $"The TIFF uses a feature this decoder does not support: {e.Message}"
: $"The TIFF data is invalid: {e.Message}", e);

// The refusal of TiffColor.TryCreate, named: what the page stores that IDecodedImage has no layout for.
private static InvalidDataException Unpresentable(TiffPageLayout layout, int pageIndex) =>
internal static InvalidDataException Unpresentable(TiffPageLayout layout, int pageIndex) =>
new($"Page {pageIndex + 1} stores {layout.SamplesPerPixel} sample(s) per pixel of {layout.BitsPerSample}-bit " +
$"{layout.SampleFormat} data as {layout.Photometric}, a layout this decoder does not present (it decodes grey, " +
"RGB, palette, CMYK and YCbCr with 8- or 16-bit unsigned samples, and grey or RGB with 16- or 32-bit float samples).");
Expand Down
6 changes: 3 additions & 3 deletions src/Sdcb.SimdCodecs.Tiff/TiffReader.Segment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ public static TiffSegmentRect ReadSegment(string path, TiffPageLayout layout, in
private static FileStream OpenForSegments(string path) =>
new(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1);

private static TiffPageLayout ReadLayoutCore<T>(ref T src, int pageIndex) where T : ITiffBytes, allows ref struct
internal static TiffPageLayout ReadLayoutCore<T>(ref T src, int pageIndex) where T : ITiffBytes, allows ref struct
{
ArgumentOutOfRangeException.ThrowIfNegative(pageIndex);
var (format, ifdOffset) = TiffIfdParser.ReadHeader(ref src);
Expand All @@ -273,7 +273,7 @@ private static TiffPageLayout ReadLayoutCore<T>(ref T src, int pageIndex) where
return new TiffPageLayout(pageIndex, format, TiffIfdParser.Parse(ref src, ifdOffset, format), ifdOffset);
}

private static TiffSegmentRect ReadSegmentCore<T>(ref T src, TiffPageLayout layout, int segmentIndex,
internal static TiffSegmentRect ReadSegmentCore<T>(ref T src, TiffPageLayout layout, int segmentIndex,
Span<byte> destination) where T : ITiffBytes, allows ref struct
{
var rect = layout.SegmentRectangle(segmentIndex); // throws ArgumentOutOfRangeException
Expand Down Expand Up @@ -349,7 +349,7 @@ private static TiffSegmentRect ReadSegmentCore<T>(ref T src, TiffPageLayout layo
publiclyVisible: true);
}

var samples = DecodeSegment(raw, 0, count, index, format, staging, false, scratch, inflateSource,
var samples = DecodeSegment(raw.AsSpan(0, (int)count), format, staging, false, scratch, inflateSource,
scratchStream, capacity);

// The same normalisation ReadInto applies, at the same widths.
Expand Down
Loading