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
73 changes: 39 additions & 34 deletions src/Sdcb.SimdCodecs.Tiff/IfdBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,52 +94,57 @@ public async Task<long> WriteAsync(TiffFileTarget target, CancellationToken ct =
{
await target.AlignAsync(ct).ConfigureAwait(false);
var ifdStart = target.Position;
var bytes = Serialize(ifdStart, out var nextIfdField);
await target.WriteAsync(bytes, ct).ConfigureAwait(false);
return ifdStart + nextIfdField;
}

var entryCount = (ushort)_entries.Count;
/// <summary>
/// The IFD as it is stored at file offset <paramref name="ifdStart"/> (a word boundary): the entry count, the
/// entries in tag order, the NextIFD pointer (0; the caller patches it) and then every value longer than four bytes,
/// in entry order. <paramref name="nextIfdField"/> is the NextIFD pointer's offset within the returned bytes.
/// </summary>
public byte[] Serialize(long ifdStart, out int nextIfdField)
{
const int entrySize = 12; // tag(2) + type(2) + count(4) + value/offset(4)

// Entry count
await target.WriteUInt16Async(entryCount, ct).ConfigureAwait(false);

// Compute where overflow data starts (after all entries + NextIFD pointer)
var overflowOffset = (uint)(ifdStart + 2 + entryCount * entrySize + 4);

// Collect overflow data to write after the directory
var overflowData = new List<byte[]>();
var entryBytes = new byte[entrySize];

var entryCount = (ushort)_entries.Count;
nextIfdField = 2 + entryCount * entrySize;
var length = (long)nextIfdField + 4;
foreach (var (_, (_, _, valueBytes)) in _entries)
if (valueBytes.Length > 4)
length += valueBytes.Length;
if (ifdStart + length > uint.MaxValue)
throw new IOException("The TIFF file would pass 4 GiB, the most a classic TIFF offset addresses.");

var bytes = new byte[length];
var span = bytes.AsSpan();
MemoryMarshal.Write(span, in entryCount);

// Overflow data starts after all entries + NextIFD pointer.
var overflowOffset = (uint)(ifdStart + nextIfdField + 4);
var at = 2;
var overflowAt = nextIfdField + 4;
foreach (var (tag, (type, count, valueBytes)) in _entries)
{
var typeShort = (ushort)type;
MemoryMarshal.Write(entryBytes.AsSpan(0, 2), in tag);
MemoryMarshal.Write(entryBytes.AsSpan(2, 2), in typeShort);
MemoryMarshal.Write(entryBytes.AsSpan(4, 4), in count);

MemoryMarshal.Write(span.Slice(at, 2), in tag);
MemoryMarshal.Write(span.Slice(at + 2, 2), in typeShort);
MemoryMarshal.Write(span.Slice(at + 4, 4), in count);
if (valueBytes.Length <= 4)
{
// Inline: pad to 4 bytes
entryBytes.AsSpan(8, 4).Clear();
valueBytes.CopyTo(entryBytes.AsSpan(8));
// Inline: padded to 4 bytes (the array is zeroed).
valueBytes.CopyTo(span.Slice(at + 8));
}
else
{
// Overflow: write offset to data area
MemoryMarshal.Write(entryBytes.AsSpan(8, 4), in overflowOffset);
MemoryMarshal.Write(span.Slice(at + 8, 4), in overflowOffset);
overflowOffset += (uint)valueBytes.Length;
overflowData.Add(valueBytes);
valueBytes.CopyTo(span.Slice(overflowAt));
overflowAt += valueBytes.Length;
}

await target.WriteAsync(entryBytes, ct).ConfigureAwait(false);
at += entrySize;
}

// NextIFD pointer (0 = no next page; caller patches this)
var nextIfdPatchOffset = target.Position;
await target.WriteUInt32Async(0, ct).ConfigureAwait(false);

// Write overflow value data
foreach (var data in overflowData)
await target.WriteAsync(data, ct).ConfigureAwait(false);

return nextIfdPatchOffset;
// NextIFD pointer stays 0 (no next page) until the caller patches it.
return bytes;
}
}
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.TiffImageEncoder.Create(System.IO.Stream! output, Sdcb.SimdCodecs.Abstractions.EncodeOptions? options = null, bool leaveOpen = false) -> Sdcb.SimdCodecs.Abstractions.IImageEncoderSession!
11 changes: 11 additions & 0 deletions src/Sdcb.SimdCodecs.Tiff/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,14 @@ A `DecodeOptions.Region` reads only the strips or tiles it intersects, and `TryD
## 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.

`TiffImageEncoder.Create(Stream)` streams a file to a writable, seekable stream as the rows arrive: each strip, or each row of tiles, is compressed and written once its rows are in, and a page's IFD follows its last segment. Memory is one band of rows (a 64 KiB deflate input slice for strips, one row of tiles for a tiled page), whatever the page size. The header's and each IFD's forward offsets are patched by seeking, so a non-seekable stream is refused with `ArgumentException`; encode into an `IBufferWriter<byte>` (`TiffImageEncoder.Create(IBufferWriter<byte>)`, buffered) and copy instead. The streamed file is byte for byte the buffered encoder's for the same pixels and options (`TiffStreamingEncodeTests`).

```csharp
using var file = File.Create("scan.tif");
using var session = TiffImageEncoder.Create(file, new TiffEncodeOptions { Page = new TiffPageOptions { RowsPerStrip = 64 } });
var page = session.AddFrame(width, height, PixelFormat.Rgb24);
foreach (var (band, rows) in Bands()) // any band size
page.WriteRows(band, rows);
session.Commit(); // patches the first-IFD offset; the file is complete
```
89 changes: 60 additions & 29 deletions src/Sdcb.SimdCodecs.Tiff/TiffImageEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,43 @@ public sealed class TiffImageEncoder : IImageEncoder
/// <remarks><paramref name="options"/> is a <see cref="TiffEncodeOptions"/> (null means the defaults; any other type
/// throws <see cref="ArgumentException"/>).</remarks>
public static IImageEncoderSession Create(IBufferWriter<byte> output, EncodeOptions? options = null) =>
new Session(output, options switch
{
null => new TiffEncodeOptions(),
TiffEncodeOptions o => o,
_ => throw new ArgumentException($"TIFF encoding takes TiffEncodeOptions, not {options.GetType().Name}.", nameof(options)),
});
new Session(output, Options(options));

/// <summary>
/// Starts a streaming session that writes the file to <paramref name="output"/> as the rows arrive
/// (<see cref="IImageEncoderSession.IsStreaming"/> is true): each strip, or each row of tiles, is compressed and written
/// once its rows are in, and a page's IFD follows its last segment, so memory stays at a band of rows whatever the
/// image size. The file is byte for byte the one <see cref="Create(IBufferWriter{byte}, EncodeOptions?)"/> writes.
/// </summary>
/// <remarks>
/// A TIFF header and each IFD point forward to an IFD written later, so the session patches those offsets by seeking:
/// <paramref name="output"/> must be writable and seekable (for a non-seekable stream, encode into an
/// <see cref="IBufferWriter{T}"/> and copy). The file starts at the stream's current position, and offsets count from
/// there. The file is complete once <see cref="IImageEncoderSession.Commit"/> returns; a session disposed before that
/// leaves a truncated file behind. Disposing the session disposes <paramref name="output"/> unless
/// <paramref name="leaveOpen"/> is set. <paramref name="options"/> is a <see cref="TiffEncodeOptions"/> (null means the
/// defaults; any other type throws <see cref="ArgumentException"/>). A compression the writer cannot apply, or an Exif
/// block in <see cref="TiffPageOptions.Exif"/> that is not a TIFF structure, fails at
/// <see cref="IImageEncoderSession.AddFrame"/>, before the page is written.
/// </remarks>
public static IImageEncoderSession Create(Stream output, EncodeOptions? options = null, bool leaveOpen = false)
{
ArgumentNullException.ThrowIfNull(output);
if (!output.CanWrite)
throw new ArgumentException("The stream is not writable.", nameof(output));
if (!output.CanSeek)
throw new ArgumentException("A streaming TIFF session patches offsets and needs a seekable stream; for a non-seekable one, use Create(IBufferWriter<byte>, EncodeOptions?) and copy the result.", nameof(output));
return TiffStreamingEncoderSession.Create(output, Options(options), leaveOpen);
}

private static TiffEncodeOptions Options(EncodeOptions? options) => options switch
{
null => new TiffEncodeOptions(),
TiffEncodeOptions o => o,
_ => throw new ArgumentException($"TIFF encoding takes TiffEncodeOptions, not {options.GetType().Name}.", nameof(options)),
};

private static PixelFormat Native(PixelFormat f) => f.Layout switch
internal static PixelFormat Native(PixelFormat f) => f.Layout switch
{
ChannelLayout.Rgba or ChannelLayout.Bgra => new PixelFormat(ChannelLayout.Rgba, f.Sample),
ChannelLayout.Rgb or ChannelLayout.Bgr => new PixelFormat(ChannelLayout.Rgb, f.Sample),
Expand All @@ -67,7 +96,7 @@ protected override void Encode(IReadOnlyList<BufferedFrame> frames, Cancellation
cancellationToken.ThrowIfCancellationRequested();
var native = Native(frame.Format);
var pixels = frame.PixelsAs(native).ToArray();
writer.AddPageAsync(pixels, frame.Width, frame.Height, PageOptions(native, frame), cancellationToken)
writer.AddPageAsync(pixels, frame.Width, frame.Height, PageOptions(options, native, frame.Metadata), cancellationToken)
.GetAwaiter().GetResult();
}
}
Expand All @@ -77,29 +106,31 @@ protected override void Encode(IReadOnlyList<BufferedFrame> frames, Cancellation
}
WriteOutput(stream.ToArray());
}
}

private TiffPageOptions PageOptions(PixelFormat native, BufferedFrame frame)
/// <summary>The page a frame in <paramref name="native"/> format becomes: the template with the frame's sample layout
/// and metadata (shared by the buffered and the streaming session).</summary>
internal static TiffPageOptions PageOptions(TiffEncodeOptions options, PixelFormat native, ImageMetadata? metadata)
{
var gray = native.Layout is ChannelLayout.Gray or ChannelLayout.GrayAlpha;
var alpha = native.Layout is ChannelLayout.GrayAlpha or ChannelLayout.Rgba;
var o = (options.Page ?? TiffPageOptions.Default) with
{
var gray = native.Layout is ChannelLayout.Gray or ChannelLayout.GrayAlpha;
var alpha = native.Layout is ChannelLayout.GrayAlpha or ChannelLayout.Rgba;
var o = (options.Page ?? TiffPageOptions.Default) with
{
SamplesPerPixel = native.Layout switch { ChannelLayout.Rgba => 4, ChannelLayout.Rgb => 3, ChannelLayout.GrayAlpha => 2, _ => 1 },
BitsPerSample = native.Sample == SampleFormat.UInt16 ? 16 : 8,
SampleFormat = TiffSampleFormat.Uint,
Photometric = gray ? TiffPhotometric.MinIsBlack : TiffPhotometric.Rgb,
ExtraSamples = alpha ? TiffExtraSamples.UnassociatedAlpha : null,
};
if (frame.Metadata is { } m)
{
if (!m.Icc.IsEmpty)
o = o with { IccProfile = m.Icc };
if (!m.Xmp.IsEmpty)
o = o with { Xmp = m.Xmp };
if (!m.Exif.IsEmpty && TiffExif.ParseBlock(m.Exif.Span) is not null)
o = o with { Exif = m.Exif };
}
return o;
SamplesPerPixel = native.Layout switch { ChannelLayout.Rgba => 4, ChannelLayout.Rgb => 3, ChannelLayout.GrayAlpha => 2, _ => 1 },
BitsPerSample = native.Sample == SampleFormat.UInt16 ? 16 : 8,
SampleFormat = TiffSampleFormat.Uint,
Photometric = gray ? TiffPhotometric.MinIsBlack : TiffPhotometric.Rgb,
ExtraSamples = alpha ? TiffExtraSamples.UnassociatedAlpha : null,
};
if (metadata is { } m)
{
if (!m.Icc.IsEmpty)
o = o with { IccProfile = m.Icc };
if (!m.Xmp.IsEmpty)
o = o with { Xmp = m.Xmp };
if (!m.Exif.IsEmpty && TiffExif.ParseBlock(m.Exif.Span) is not null)
o = o with { Exif = m.Exif };
}
return o;
}
}
Loading