diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/BmpBenchmarks.cs b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/BmpBenchmarks.cs
index 7beb16f..bd6a796 100644
--- a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/BmpBenchmarks.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/BmpBenchmarks.cs
@@ -39,7 +39,13 @@ public class BmpDecodeBenchmarks
[Benchmark]
public void Wic() => _run[Names.Wic]();
- public static readonly string[] Methods = [Names.Current, Names.CurrentBgra, Names.Baseline, Names.ImageSharp, Names.Wic];
+ [Benchmark]
+ public void CurrentRows() => _run[Names.CurrentRows]();
+
+ [Benchmark]
+ public void CurrentReadAll() => _run[Names.CurrentReadAll]();
+
+ public static readonly string[] Methods = [Names.Current, Names.CurrentRows, Names.CurrentReadAll, Names.CurrentBgra, Names.Baseline, Names.ImageSharp, Names.Wic];
}
/// BenchmarkDotNet over the encode cases; see .
@@ -76,7 +82,10 @@ public class BmpEncodeBenchmarks
[Benchmark]
public void BaselineStream() => _run[Names.BaselineStream]();
- public static readonly string[] Methods = [Names.Current, Names.CurrentStream, Names.CurrentBgra, Names.Baseline, Names.BaselineStream, Names.ImageSharp, Names.Wic];
+ [Benchmark]
+ public void CurrentSession() => _run[Names.CurrentSession]();
+
+ public static readonly string[] Methods = [Names.Current, Names.CurrentStream, Names.CurrentSession, Names.CurrentBgra, Names.Baseline, Names.BaselineStream, Names.ImageSharp, Names.Wic];
}
/// Runs every contestant of a case back to back before the next case, in the matrix's order.
diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Cases.cs b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Cases.cs
index a1e6ee4..01a7081 100644
--- a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Cases.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Cases.cs
@@ -117,7 +117,7 @@ internal sealed record EncodeCase(string Content, string Format)
public static IReadOnlyList All { get; } =
[
.. from content in SourceImage.Contents
- from format in new[] { "rgb24", "argb32", "rgb565", "p8", "rle8", "ico-set" }
+ from format in new[] { "rgb24", "argb32", "rgb24-topdown", "argb32-topdown", "rgb565", "p8", "rle8", "ico-set" }
select new EncodeCase(content, format),
];
@@ -125,15 +125,18 @@ .. from content in SourceImage.Contents
public static EncodeCase Find(string name) => All.Single(c => c.Name == name);
- public bool Alpha => Format is "argb32" or "ico-set";
+ public bool Alpha => Format is "argb32" or "argb32-topdown" or "ico-set";
/// Whether a decode of the output must give the source back exactly.
- public bool Lossless => Format is "rgb24" or "argb32" or "ico-set";
+ public bool Lossless => Format is "rgb24" or "argb32" or "rgb24-topdown" or "argb32-topdown" or "ico-set";
public BmpEncodeOptions Options => Format switch
{
"rgb24" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb24 },
"argb32" => new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32 },
+ // Top-down direct colour: the layouts the encoder session streams.
+ "rgb24-topdown" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb24, TopDown = true },
+ "argb32-topdown" => new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32, TopDown = true },
"rgb565" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb565 },
"p8" => new BmpEncodeOptions { Format = BmpEncodeFormat.Indexed8 },
_ => new BmpEncodeOptions { Format = BmpEncodeFormat.Indexed8, Rle = true },
diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Contestants.cs b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Contestants.cs
index 77205d1..891e3b9 100644
--- a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Contestants.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Contestants.cs
@@ -67,6 +67,41 @@ bool Current(byte[] into, PixelFormat format) => icon
if (Want(Names.Current)) setup.Contestants.Add(new(Names.Current, () => Current(rgba, PixelFormat.Rgba32)));
if (Want(Names.CurrentBgra)) setup.Contestants.Add(new(Names.CurrentBgra, () => Current(bgra, PixelFormat.Bgra32)));
+ // The streaming reader over a seekable stream (a bottom-up bitmap streams by seeking back a band at a time), RGBA
+ // rows a band of 64 at a time into the same kind of buffer: what reading a file costs next to decoding its bytes.
+ if (!icon && Want(Names.CurrentRows))
+ {
+ var buffer = new byte[w * h * 4];
+ void Rows()
+ {
+ using var reader = BmpImageDecoder.CreateRowReader(
+ new Abstractions.CodecSupport.StreamInput(new MemoryStream(data, writable: false)), PixelFormat.Rgba32, null);
+ reader.Initialize();
+ while (reader.RowsRead < reader.Height)
+ reader.ReadRows(buffer.AsSpan(reader.RowsRead * w * 4), 64);
+ }
+ if (only is null)
+ {
+ Rows();
+ if (!buffer.AsSpan().SequenceEqual(rgba))
+ throw new InvalidOperationException($"{c.Name}: the streaming reader's rows differ from TryDecodeInto's; refusing to benchmark.");
+ }
+ setup.Contestants.Add(new(Names.CurrentRows, Rows));
+ }
+
+ // What a caller without the reader does with a stream: read it whole (into a reused buffer of the right size,
+ // the cheapest way), then decode the bytes.
+ if (!icon && Want(Names.CurrentReadAll))
+ {
+ var file = new byte[data.Length];
+ setup.Contestants.Add(new(Names.CurrentReadAll, () =>
+ {
+ using var stream = new MemoryStream(data, writable: false);
+ stream.ReadExactly(file);
+ BmpImageDecoder.TryDecodeInto(file, rgba, 0, PixelFormat.Rgba32);
+ }));
+ }
+
if (Baseline.IsBuilt && Want(Names.Baseline) && Baseline.CanDecode(icon))
{
var buffer = new byte[w * h * 4];
@@ -184,14 +219,38 @@ void Check(string name, byte[] bmp)
}));
}
+ // The encoder session, 64 rows at a time into a reused writer: it streams for the top-down cases.
+ if (Want(Names.CurrentSession) && BmpEncoder.CanStream(options))
+ {
+ var writer = new System.Buffers.ArrayBufferWriter();
+ void Session()
+ {
+ writer.ResetWrittenCount();
+ using var session = BmpImageEncoder.Create(writer, options);
+ var frame = session.AddFrame(w, h, PixelFormat.Rgba32);
+ for (var y = 0; y < h; y += 64)
+ {
+ var n = Math.Min(64, h - y);
+ frame.WriteRows(rgba.AsSpan(y * w * 4, n * w * 4), n);
+ }
+ session.Commit();
+ }
+ Session();
+ var file = writer.WrittenSpan.ToArray();
+ if (only is null && !file.AsSpan().SequenceEqual(BmpEncoder.Encode(rgba, w, h, PixelFormat.Rgba32, options)))
+ throw new InvalidOperationException($"{c.Name}: the session's bytes differ from BmpEncoder.Encode's; refusing to benchmark.");
+ Check(Names.CurrentSession, file);
+ setup.Contestants.Add(new(Names.CurrentSession, Session));
+ }
+
// B, G, R(, A) input, for the layouts WIC writes.
byte[]? native = c.Format switch
{
- "rgb24" => Swizzle(rgba, 3),
- "argb32" => Swizzle(rgba, 4),
+ "rgb24" or "rgb24-topdown" => Swizzle(rgba, 3),
+ "argb32" or "argb32-topdown" => Swizzle(rgba, 4),
_ => null,
};
- var nativeFormat = c.Format == "rgb24" ? PixelFormat.Bgr24 : PixelFormat.Bgra32;
+ var nativeFormat = c.Format is "rgb24" or "rgb24-topdown" ? PixelFormat.Bgr24 : PixelFormat.Bgra32;
if (native is not null && Want(Names.CurrentBgra))
{
var stream = new MemoryStream();
@@ -225,8 +284,8 @@ void Check(string name, byte[] bmp)
IsBits? bits = c.Format switch
{
- "rgb24" => IsBits.Pixel24,
- "argb32" => IsBits.Pixel32,
+ "rgb24" or "rgb24-topdown" => IsBits.Pixel24,
+ "argb32" or "argb32-topdown" => IsBits.Pixel32,
"rgb565" => IsBits.Pixel16,
"p8" => IsBits.Pixel8,
_ => null, // ImageSharp writes no RLE
diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Infrastructure.cs b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Infrastructure.cs
index d82406d..df37292 100644
--- a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Infrastructure.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Infrastructure.cs
@@ -64,6 +64,9 @@ internal static class Names
public const string Current = "Current";
public const string CurrentBgra = "CurrentBgra";
public const string CurrentStream = "CurrentStream";
+ public const string CurrentRows = "CurrentRows";
+ public const string CurrentReadAll = "CurrentReadAll";
+ public const string CurrentSession = "CurrentSession";
public const string Baseline = "Baseline";
public const string BaselineStream = "BaselineStream";
public const string ImageSharp = "ImageSharp";
@@ -74,6 +77,9 @@ internal static class Names
Current => "current",
CurrentBgra => "current BGR(A)",
CurrentStream => "current → stream",
+ CurrentRows => "current rows ← stream",
+ CurrentReadAll => "current ← read whole stream",
+ CurrentSession => "current session → writer",
Baseline => "baseline",
BaselineStream => "baseline → stream",
Wic => "WIC",
diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Matrix.cs b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Matrix.cs
index 447f7dd..74eaa46 100644
--- a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Matrix.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/Matrix.cs
@@ -45,25 +45,26 @@ public static string RenderDecode(IReadOnlyList<(DecodeSetup Setup, Dictionary` + `CopyPixelDataTo`, one thread " +
"(it reads no icons); WIC = WPF's `BitmapDecoder` + `FormatConvertedBitmap` to BGRA. Ratios below 1 mean we are " +
"faster: current ÷ ImageSharp (both RGBA), current BGR(A) ÷ WIC (both BGRA). Every timed output was checked " +
- "against the others first.");
+ "against the others first. `current rows ← stream` = the streaming reader (`BmpImageDecoder.CreateRowReader`) " +
+ "over a seekable `MemoryStream`, RGBA rows 64 at a time; `current ← read whole stream` = the same stream read whole into a reused buffer, then `TryDecodeInto`: what streaming replaces. `rows ÷ current` is what streaming costs over decoding bytes already in memory, `rows ÷ read whole` over reading the stream first.");
sb.AppendLine();
- sb.AppendLine("| Case | KB | MP | current | current BGR(A) | baseline | ImageSharp | WIC | current MP/s | ÷ ImageSharp | ÷ WIC | ÷ baseline |");
- sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|");
+ sb.AppendLine("| Case | KB | MP | current | current rows ← stream | current ← read whole stream | current BGR(A) | baseline | ImageSharp | WIC | current MP/s | ÷ ImageSharp | ÷ WIC | ÷ baseline | rows ÷ current | rows ÷ read whole |");
+ sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|");
var notes = new List();
foreach (var (s, ms) in rows)
{
var mp = s.Width * (double)s.Height / 1e6;
- sb.AppendLine($"| `{s.Case.Name}` | {s.Data.Length / 1024.0:F0} | {mp:F2} | {Ms(ms, Names.Current)} | {Ms(ms, Names.CurrentBgra)} | " +
+ sb.AppendLine($"| `{s.Case.Name}` | {s.Data.Length / 1024.0:F0} | {mp:F2} | {Ms(ms, Names.Current)} | {Ms(ms, Names.CurrentRows)} | {Ms(ms, Names.CurrentReadAll)} | {Ms(ms, Names.CurrentBgra)} | " +
$"{Ms(ms, Names.Baseline)} | {Ms(ms, Names.ImageSharp)} | {Ms(ms, Names.Wic)} | " +
$"{(Get(ms, Names.Current) is { } c ? (mp / (c / 1000)).ToString("F0", CultureInfo.InvariantCulture) : "—")} | " +
- $"{Ratio(ms, Names.Current, Names.ImageSharp)} | {Ratio(ms, Names.CurrentBgra, Names.Wic)} | {Ratio(ms, Names.Current, Names.Baseline)} |");
+ $"{Ratio(ms, Names.Current, Names.ImageSharp)} | {Ratio(ms, Names.CurrentBgra, Names.Wic)} | {Ratio(ms, Names.Current, Names.Baseline)} | {Ratio(ms, Names.CurrentRows, Names.Current)} | {Ratio(ms, Names.CurrentRows, Names.CurrentReadAll)} |");
notes.AddRange(s.Notes.Select(n => $"`{s.Case.Name}`: {n}"));
}
sb.AppendLine();
sb.AppendLine("Geometric means over the cases both decode:");
sb.AppendLine();
- foreach (var (a, b) in new[] { (Names.Current, Names.ImageSharp), (Names.CurrentBgra, Names.Wic), (Names.Current, Names.Baseline) })
+ foreach (var (a, b) in new[] { (Names.Current, Names.ImageSharp), (Names.CurrentBgra, Names.Wic), (Names.Current, Names.Baseline), (Names.CurrentRows, Names.Current), (Names.CurrentRows, Names.CurrentReadAll) })
{
foreach (var content in SourceImage.Contents)
{
@@ -75,7 +76,7 @@ public static string RenderDecode(IReadOnlyList<(DecodeSetup Setup, Dictionary (r.Setup.Case.Name, r.Setup.Allocated)).ToList(),
- [Names.Current, Names.CurrentBgra, Names.Baseline, Names.ImageSharp, Names.Wic]);
+ [Names.Current, Names.CurrentRows, Names.CurrentReadAll, Names.CurrentBgra, Names.Baseline, Names.ImageSharp, Names.Wic]);
AppendNotes(sb, notes);
return sb.ToString();
}
@@ -89,20 +90,20 @@ public static string RenderEncode(IReadOnlyList<(EncodeSetup Setup, Dictionary` built beforehand; WIC = WPF's `BmpBitmapEncoder` over a `BitmapSource` of B, G, " +
- "R(, A), into a reused stream (24- and 32-bit only). Every output decodes, and the lossless layouts give the source back.");
+ "R(, A), into a reused stream (24- and 32-bit only); `current session → writer` = `BmpImageEncoder.Create`, 64 rows per `WriteRows` into a reused `ArrayBufferWriter` (streaming only for the top-down cases). Every output decodes, and the lossless layouts give the source back.");
sb.AppendLine();
- sb.AppendLine("| Case | current | KB | current → stream | current BGR(A) | baseline | baseline → stream | ImageSharp | KB | WIC | KB | stream ÷ ImageSharp | BGR(A) ÷ WIC | ÷ baseline | stream ÷ baseline |");
- sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|");
+ sb.AppendLine("| Case | current | KB | current → stream | current session → writer | current BGR(A) | baseline | baseline → stream | ImageSharp | KB | WIC | KB | stream ÷ ImageSharp | BGR(A) ÷ WIC | ÷ baseline | stream ÷ baseline | session ÷ stream |");
+ sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|");
var notes = new List();
foreach (var (s, ms) in rows)
{
- sb.AppendLine($"| `{s.Case.Name}` | {Ms(ms, Names.Current)} | {Kb(s, Names.Current)} | {Ms(ms, Names.CurrentStream)} | {Ms(ms, Names.CurrentBgra)} | " +
+ sb.AppendLine($"| `{s.Case.Name}` | {Ms(ms, Names.Current)} | {Kb(s, Names.Current)} | {Ms(ms, Names.CurrentStream)} | {Ms(ms, Names.CurrentSession)} | {Ms(ms, Names.CurrentBgra)} | " +
$"{Ms(ms, Names.Baseline)} | {Ms(ms, Names.BaselineStream)} | {Ms(ms, Names.ImageSharp)} | {Kb(s, Names.ImageSharp)} | {Ms(ms, Names.Wic)} | {Kb(s, Names.Wic)} | " +
- $"{Ratio(ms, Names.CurrentStream, Names.ImageSharp)} | {Ratio(ms, Names.CurrentBgra, Names.Wic)} | {Ratio(ms, Names.Current, Names.Baseline)} | {Ratio(ms, Names.CurrentStream, Names.BaselineStream)} |");
+ $"{Ratio(ms, Names.CurrentStream, Names.ImageSharp)} | {Ratio(ms, Names.CurrentBgra, Names.Wic)} | {Ratio(ms, Names.Current, Names.Baseline)} | {Ratio(ms, Names.CurrentStream, Names.BaselineStream)} | {Ratio(ms, Names.CurrentSession, Names.CurrentStream)} |");
notes.AddRange(s.Notes.Select(n => $"`{s.Case.Name}`: {n}"));
}
AppendAllocations(sb, rows.Select(r => (r.Setup.Case.Name, r.Setup.Allocated)).ToList(),
- [Names.Current, Names.CurrentStream, Names.CurrentBgra, Names.Baseline, Names.BaselineStream, Names.ImageSharp, Names.Wic]);
+ [Names.Current, Names.CurrentStream, Names.CurrentSession, Names.CurrentBgra, Names.Baseline, Names.BaselineStream, Names.ImageSharp, Names.Wic]);
AppendNotes(sb, notes);
return sb.ToString();
}
diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/README.md b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/README.md
index 60eb2d6..d40de51 100644
--- a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/README.md
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/README.md
@@ -18,7 +18,7 @@ Every bitmap is `1920×1080` (`--size WxH`), cut from the PNG benchmark's two so
|---|---|---|
| decode | `rgb24`, `bgra32` (32-bit with alpha), `rgb16`, `p8`, `p4`, `p1` | ImageSharp, a foreign encoder |
| decode | `rgb24-topdown`, `argb32-v4` (V4 alpha mask), `rgb565`, `rle8`, `rle4`, `ico256-bmp32`, `ico256-png`, `ico48-bmp8` | ours (layouts ImageSharp does not write) |
-| encode | `rgb24`, `argb32`, `rgb565`, `p8`, `rle8` from RGBA; `ico-set` (16, 32, 48 as DIB, 256 as PNG) | — |
+| encode | `rgb24`, `argb32`, `rgb24-topdown`, `argb32-topdown` (the layouts the encoder session streams), `rgb565`, `p8`, `rle8` from RGBA; `ico-set` (16, 32, 48 as DIB, 256 as PNG) | — |
## Contestants
@@ -26,6 +26,7 @@ Every bitmap is `1920×1080` (`--size WxH`), cut from the PNG benchmark's two so
|---|---|---|
| `current` | `BmpImageDecoder` / `IcoImageDecoder.TryDecodeInto` to RGBA in a reused buffer | `BmpEncoder` / `IcoEncoder`, from RGBA |
| `current BGR(A)` | the same to BGRA, WIC's layout | the same from the B, G, R(, A) input WIC gets |
+| `current rows ← stream` / `current session → writer` | `BmpImageDecoder.CreateRowReader` over a seekable `MemoryStream`, RGBA rows 64 at a time (bitmaps only) | `BmpImageEncoder.Create`, 64 rows per `WriteRows` into a reused `ArrayBufferWriter` (the cases whose options stream) |
| `baseline` | the previous commit's decoder, same process (`baseline [git-ref]`) | the previous commit's encoder, to an array and (`baseline → stream`) into a reused stream |
| ImageSharp 3.1.12 | `Image.Load` + `CopyPixelDataTo`, `MaxDegreeOfParallelism = 1` (no icons: it has no ICO codec) | `BmpEncoder` with the same bits per pixel, into a reused stream (no RLE) |
| WIC | WPF's `BitmapDecoder` + `FormatConvertedBitmap` to BGRA (Windows only) | WPF's `BmpBitmapEncoder` from B, G, R(, A) into a reused stream (24- and 32-bit) |
diff --git a/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/results/streaming-2026-11-23-amd-ryzen-7-5800x.md b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/results/streaming-2026-11-23-amd-ryzen-7-5800x.md
new file mode 100644
index 0000000..f5d3192
--- /dev/null
+++ b/benchmarks/Sdcb.SimdCodecs.Bmp.Benchmarks/results/streaming-2026-11-23-amd-ryzen-7-5800x.md
@@ -0,0 +1,148 @@
+# BMP streaming reader and encoder session (240c053 vs 533b03e)
+
+`matrix all --rounds 31`, run while other jobs shared the machine: differences under ~5% between `current` and `baseline` are noise. `rows ÷ current` is the streaming reader over a `MemoryStream` against the span decoder on bytes already in memory (the reader copies every byte into its buffer, twice for a bottom-up file); `rows ÷ read whole` is against reading the stream into a buffer and then decoding it, which is what streaming replaces.
+
+- CPU: AMD Ryzen 7 5800X 8-Core Processor
+- OS: Microsoft Windows 10.0.26200 (X64)
+- .NET: .NET 10.0.15 (win-x64), process X64
+- Logical processors: 16
+- Vector128.IsHardwareAccelerated: True, Vector256.IsHardwareAccelerated: True, Vector512.IsHardwareAccelerated: False
+- AVX2: True, AVX-512F: False
+- Bitmap size: 1920×1080; icons 256×256 and 48×48
+- `photo` source: centre crop of landscape-almsee.png (JPEG benchmark corpus master)
+- `screen` source: synthetic
+- ImageSharp: 3.1.12
+- WIC: WindowsCodecs.dll 10.0.26100.8115 (WinBuild.160101.0800), through WPF
+- Baseline: 533b03e2f35a Merge feature/streaming-foundation: streaming plumbing in Abstractions
+
+### Decode (in-process medians of 31 interleaved rounds, ms)
+
+`current` = `BmpImageDecoder` / `IcoImageDecoder.TryDecodeInto` to RGBA in a caller buffer; `current BGR(A)` = the same to BGRA, the layout WIC produces; ImageSharp = `Image.Load` + `CopyPixelDataTo`, one thread (it reads no icons); WIC = WPF's `BitmapDecoder` + `FormatConvertedBitmap` to BGRA. Ratios below 1 mean we are faster: current ÷ ImageSharp (both RGBA), current BGR(A) ÷ WIC (both BGRA). Every timed output was checked against the others first. `current rows ← stream` = the streaming reader (`BmpImageDecoder.CreateRowReader`) over a seekable `MemoryStream`, RGBA rows 64 at a time; `current ← read whole stream` = the same stream read whole into a reused buffer, then `TryDecodeInto`: what streaming replaces. `rows ÷ current` is what streaming costs over decoding bytes already in memory, `rows ÷ read whole` over reading the stream first.
+
+| Case | KB | MP | current | current rows ← stream | current ← read whole stream | current BGR(A) | baseline | ImageSharp | WIC | current MP/s | ÷ ImageSharp | ÷ WIC | ÷ baseline | rows ÷ current | rows ÷ read whole |
+|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
+| `photo-rgb24` | 6075 | 2.07 | 0.2921 | 0.5290 | 0.6277 | 0.2978 | 0.3002 | 1.251 | 2.241 | 7098 | 0.23× | 0.13× | 0.97× | 1.81× | 0.84× |
+| `photo-rgb24-topdown` | 6075 | 2.07 | 0.2814 | 0.3956 | 0.6313 | 0.2859 | 0.2785 | 1.238 | 2.292 | 7369 | 0.23× | 0.12× | 1.01× | 1.41× | 0.63× |
+| `photo-bgra32` | 8100 | 2.07 | 0.2409 | 0.6070 | 0.8679 | 0.2339 | 0.2355 | 5.814 | 2.295 | 8606 | 0.04× | 0.10× | 1.02× | 2.52× | 0.70× |
+| `photo-argb32-v4` | 8100 | 2.07 | 0.2023 | 0.5328 | 0.7614 | 0.2144 | 0.2104 | 5.719 | 2.134 | 10251 | 0.04× | 0.10× | 0.96× | 2.63× | 0.70× |
+| `photo-rgb16` | 4050 | 2.07 | 0.6309 | 0.7667 | 0.9076 | 0.5015 | 0.5037 | 7.668 | 5.636 | 3287 | 0.08× | 0.09× | 1.25× | 1.22× | 0.84× |
+| `photo-rgb565` | 4050 | 2.07 | 0.3917 | 0.5617 | 0.6006 | 0.3949 | 0.3995 | 6.237 | 4.562 | 5294 | 0.06× | 0.09× | 0.98× | 1.43× | 0.94× |
+| `photo-p8` | 2026 | 2.07 | 0.9288 | 1.041 | 1.022 | 0.9295 | 0.9302 | 5.135 | 2.599 | 2233 | 0.18× | 0.36× | 1.00× | 1.12× | 1.02× |
+| `photo-p4` | 1013 | 2.07 | 0.7079 | 0.7689 | 0.7380 | 0.7058 | 0.6453 | 5.083 | 1.784 | 2929 | 0.14× | 0.40× | 1.10× | 1.09× | 1.04× |
+| `photo-p1` | 253 | 2.07 | 0.5579 | 0.5701 | 0.5666 | 0.5602 | 0.5605 | 4.776 | 1.203 | 3717 | 0.12× | 0.47× | 1.00× | 1.02× | 1.01× |
+| `photo-rle8` | 2074 | 2.07 | 2.077 | 2.971 | 2.200 | 2.096 | 2.132 | 6.314 | 4.135 | 998 | 0.33× | 0.51× | 0.97× | 1.43× | 1.35× |
+| `photo-rle4` | 1345 | 2.07 | 4.342 | 5.134 | 4.403 | 4.369 | 4.304 | 9.830 | 5.432 | 478 | 0.44× | 0.80× | 1.01× | 1.18× | 1.17× |
+| `photo-ico256-bmp32` | 264 | 0.07 | 0.0075 | — | — | 0.0077 | 0.0082 | — | 0.4061 | 8778 | — | 0.02× | 0.91× | — | — |
+| `photo-ico256-png` | 129 | 0.07 | 1.008 | — | — | 1.062 | 1.007 | — | 0.9823 | 65 | — | 1.08× | 1.00× | — | — |
+| `photo-ico48-bmp8` | 4 | 0.00 | 0.0042 | — | — | 0.0055 | 0.0035 | — | 0.0727 | 542 | — | 0.08× | 1.23× | — | — |
+| `screen-rgb24` | 6075 | 2.07 | 0.2869 | 0.5112 | 0.6107 | 0.2859 | 0.2878 | 1.234 | 2.158 | 7227 | 0.23× | 0.13× | 1.00× | 1.78× | 0.84× |
+| `screen-rgb24-topdown` | 6075 | 2.07 | 0.2756 | 0.3922 | 0.5945 | 0.2743 | 0.2761 | 1.168 | 2.228 | 7523 | 0.24× | 0.12× | 1.00× | 1.42× | 0.66× |
+| `screen-bgra32` | 8100 | 2.07 | 0.1871 | 0.4828 | 0.6944 | 0.1847 | 0.1724 | 5.533 | 2.093 | 11084 | 0.03× | 0.09× | 1.08× | 2.58× | 0.70× |
+| `screen-argb32-v4` | 8100 | 2.07 | 0.2239 | 0.5292 | 0.8339 | 0.2033 | 0.2414 | 6.313 | 2.585 | 9261 | 0.04× | 0.08× | 0.93× | 2.36× | 0.63× |
+| `screen-rgb16` | 4050 | 2.07 | 0.4115 | 0.5886 | 0.6529 | 0.4021 | 0.4021 | 6.253 | 4.934 | 5039 | 0.07× | 0.08× | 1.02× | 1.43× | 0.90× |
+| `screen-rgb565` | 4050 | 2.07 | 0.3945 | 0.5577 | 0.6036 | 0.3972 | 0.4044 | 6.330 | 4.640 | 5256 | 0.06× | 0.09× | 0.98× | 1.41× | 0.92× |
+| `screen-p8` | 2026 | 2.07 | 0.9111 | 1.017 | 1.000 | 0.9124 | 0.9160 | 5.058 | 2.486 | 2276 | 0.18× | 0.37× | 0.99× | 1.12× | 1.02× |
+| `screen-p4` | 1013 | 2.07 | 0.6931 | 0.7504 | 0.7220 | 0.6921 | 0.6342 | 5.026 | 1.736 | 2992 | 0.14× | 0.40× | 1.09× | 1.08× | 1.04× |
+| `screen-p1` | 253 | 2.07 | 0.5298 | 0.5559 | 0.5349 | 0.5365 | 0.5347 | 4.548 | 1.151 | 3914 | 0.12× | 0.47× | 0.99× | 1.05× | 1.04× |
+| `screen-rle8` | 190 | 2.07 | 0.5376 | 0.7986 | 0.5612 | 0.5292 | 0.5792 | 4.772 | 2.528 | 3857 | 0.11× | 0.21× | 0.93× | 1.49× | 1.42× |
+| `screen-rle4` | 145 | 2.07 | 0.5862 | 0.9181 | 0.6189 | 0.5962 | 0.6053 | 5.177 | 2.867 | 3537 | 0.11× | 0.21× | 0.97× | 1.57× | 1.48× |
+| `screen-ico256-bmp32` | 264 | 0.07 | 0.0080 | — | — | 0.0079 | 0.0077 | — | 0.4001 | 8228 | — | 0.02× | 1.03× | — | — |
+| `screen-ico256-png` | 1 | 0.07 | 0.1713 | — | — | 0.2234 | 0.1719 | — | 0.2353 | 383 | — | 0.95× | 1.00× | — | — |
+| `screen-ico48-bmp8` | 3 | 0.00 | 0.0035 | — | — | 0.0038 | 0.0032 | — | 0.0537 | 666 | — | 0.07× | 1.07× | — | — |
+
+Geometric means over the cases both decode:
+
+- current ÷ ImageSharp, photo: 0.13× (11 cases)
+- current ÷ ImageSharp, screen: 0.10× (11 cases)
+- current BGR(A) ÷ WIC, photo: 0.18× (14 cases)
+- current BGR(A) ÷ WIC, screen: 0.15× (14 cases)
+- current ÷ baseline, photo: 1.03× (14 cases)
+- current ÷ baseline, screen: 1.00× (14 cases)
+- current rows ← stream ÷ current, photo: 1.46× (11 cases)
+- current rows ← stream ÷ current, screen: 1.51× (11 cases)
+- current rows ← stream ÷ current ← read whole stream, photo: 0.91× (11 cases)
+- current rows ← stream ÷ current ← read whole stream, screen: 0.93× (11 cases)
+
+Managed bytes allocated per operation, KB (one warm operation on the timing thread). ImageSharp keeps pixel buffers in its own unmanaged pool and WIC allocates natively, so neither shows here: compare working sets with `peakmem`.
+
+| Case | current | current rows ← stream | current ← read whole stream | current BGR(A) | baseline | ImageSharp | WIC |
+|---|---:|---:|---:|---:|---:|---:|---:|
+| `photo-rgb24` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `photo-rgb24-topdown` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `photo-bgra32` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `photo-argb32-v4` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `photo-rgb16` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `photo-rgb565` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `photo-p8` | 0.0 | 1.5 | 0.1 | 0.0 | 0.0 | 3.2 | 23.4 |
+| `photo-p4` | 0.0 | 1.5 | 0.1 | 0.0 | 0.0 | 2.2 | 3.6 |
+| `photo-p1` | 0.0 | 1.5 | 0.1 | 0.0 | 0.0 | 2.2 | 2.6 |
+| `photo-rle8` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 215.5 | 2.2 |
+| `photo-rle4` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.4 | 2.2 |
+| `photo-ico256-bmp32` | 0.1 | — | — | 0.1 | 0.1 | — | 2.7 |
+| `photo-ico256-png` | 1.8 | — | — | 0.8 | 1.8 | — | 2.7 |
+| `photo-ico48-bmp8` | 0.1 | — | — | 0.1 | 0.1 | — | 23.9 |
+| `screen-rgb24` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `screen-rgb24-topdown` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `screen-bgra32` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `screen-argb32-v4` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `screen-rgb16` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `screen-rgb565` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.1 | 2.2 |
+| `screen-p8` | 0.0 | 1.5 | 0.1 | 0.0 | 0.0 | 3.2 | 23.4 |
+| `screen-p4` | 0.0 | 1.5 | 0.1 | 0.0 | 0.0 | 2.2 | 3.6 |
+| `screen-p1` | 0.0 | 1.5 | 0.1 | 0.0 | 0.0 | 2.2 | 2.6 |
+| `screen-rle8` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 3.3 | 2.2 |
+| `screen-rle4` | 0.0 | 0.5 | 0.1 | 0.0 | 0.0 | 2.4 | 2.2 |
+| `screen-ico256-bmp32` | 0.1 | — | — | 0.1 | 0.1 | — | 2.7 |
+| `screen-ico256-png` | 1.8 | — | — | 0.8 | 1.8 | — | 2.7 |
+| `screen-ico48-bmp8` | 0.1 | — | — | 0.1 | 0.1 | — | 8.1 |
+
+### Encode (in-process medians of 31 interleaved rounds, ms; sizes in KB)
+
+`current` = `BmpEncoder.Encode` from RGBA to a new array (`IcoEncoder.Encode` for the icon set); `current → stream` = the `Stream` overload into a reused stream, as ImageSharp and WIC write; `baseline` / `baseline → stream` = the same two for the previous commit; `current BGR(A)` = that from the B, G, R(, A) input WIC gets; ImageSharp = `BmpEncoder` with the same bits per pixel into a reused stream, one thread, from an `Image` built beforehand; WIC = WPF's `BmpBitmapEncoder` over a `BitmapSource` of B, G, R(, A), into a reused stream (24- and 32-bit only); `current session → writer` = `BmpImageEncoder.Create`, 64 rows per `WriteRows` into a reused `ArrayBufferWriter` (streaming only for the top-down cases). Every output decodes, and the lossless layouts give the source back.
+
+| Case | current | KB | current → stream | current session → writer | current BGR(A) | baseline | baseline → stream | ImageSharp | KB | WIC | KB | stream ÷ ImageSharp | BGR(A) ÷ WIC | ÷ baseline | stream ÷ baseline | session ÷ stream |
+|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
+| `photo-rgb24` | 0.5800 | 6075 | 0.3636 | — | 0.3303 | 0.5943 | 0.4398 | 0.3062 | 6075 | 4.840 | 6075 | 1.19× | 0.07× | 0.98× | 0.83× | — |
+| `photo-argb32` | 0.9200 | 8100 | 0.2433 | — | 0.2332 | 0.7971 | 0.2574 | 0.2363 | 8100 | 5.335 | 8100 | 1.03× | 0.04× | 1.15× | 0.95× | — |
+| `photo-rgb24-topdown` | 0.5797 | 6075 | 0.3439 | 0.3106 | 0.1745 | 0.5167 | 0.3342 | 0.3018 | 6075 | 4.314 | 6075 | 1.14× | 0.04× | 1.12× | 1.03× | 0.90× |
+| `photo-argb32-topdown` | 0.6951 | 8100 | 0.4278 | 0.2958 | 0.4432 | 0.7222 | 0.4091 | 0.2304 | 8100 | 5.166 | 8100 | 1.86× | 0.09× | 0.96× | 1.05× | 0.69× |
+| `photo-rgb565` | 2.176 | 4050 | 2.226 | — | — | 2.128 | 2.228 | 14.7 | 4050 | — | — | 0.15× | — | 1.02× | 1.00× | — |
+| `photo-p8` | 100.8 | 2026 | 103.8 | — | — | 100.5 | 100.6 | 216.4 | 2026 | — | — | 0.48× | — | 1.00× | 1.03× | — |
+| `photo-rle8` | 104.6 | 2074 | 104.5 | — | — | 103.7 | 103.2 | — | — | — | — | — | — | 1.01× | 1.01× | — |
+| `photo-ico-set` | 9.561 | 144 | — | — | — | — | — | — | — | — | — | — | — | — | — | — |
+| `screen-rgb24` | 0.8539 | 6075 | 0.7664 | — | 0.2450 | 0.8190 | 0.4614 | 0.6124 | 6075 | 6.978 | 6075 | 1.25× | 0.04× | 1.04× | 1.66× | — |
+| `screen-argb32` | 0.6229 | 8100 | 0.2715 | — | 0.2340 | 0.6506 | 0.2800 | 0.2260 | 8100 | 5.339 | 8100 | 1.20× | 0.04× | 0.96× | 0.97× | — |
+| `screen-rgb24-topdown` | 0.5381 | 6075 | 0.3549 | 0.3152 | 0.2979 | 0.4647 | 0.3423 | 0.3035 | 6075 | 4.352 | 6075 | 1.17× | 0.07× | 1.16× | 1.04× | 0.89× |
+| `screen-argb32-topdown` | 1.173 | 8100 | 0.2759 | 0.2728 | 0.2283 | 0.8637 | 0.2748 | 0.2314 | 8100 | 5.844 | 8100 | 1.19× | 0.04× | 1.36× | 1.00× | 0.99× |
+| `screen-rgb565` | 2.396 | 4050 | 2.212 | — | — | 2.348 | 2.194 | 14.9 | 4050 | — | — | 0.15× | — | 1.02× | 1.01× | — |
+| `screen-p8` | 44.1 | 2026 | 49.6 | — | — | 50.5 | 49.4 | 105.4 | 2026 | — | — | 0.47× | — | 0.87× | 1.00× | — |
+| `screen-rle8` | 72.6 | 190 | 66.8 | — | — | 69.7 | 69.2 | — | — | — | — | — | — | 1.04× | 0.96× | — |
+| `screen-ico-set` | 4.517 | 16 | — | — | — | — | — | — | — | — | — | — | — | — | — | — |
+
+Managed bytes allocated per operation, KB (one warm operation on the timing thread). ImageSharp keeps pixel buffers in its own unmanaged pool and WIC allocates natively, so neither shows here: compare working sets with `peakmem`.
+
+| Case | current | current → stream | current session → writer | current BGR(A) | baseline | baseline → stream | ImageSharp | WIC |
+|---|---:|---:|---:|---:|---:|---:|---:|---:|
+| `photo-rgb24` | 6075.1 | 0.0 | — | 0.0 | 6075.1 | 0.0 | 0.2 | 6102.1 |
+| `photo-argb32` | 8100.1 | 0.0 | — | 0.0 | 8100.1 | 0.0 | 0.2 | 8127.1 |
+| `photo-rgb24-topdown` | 6075.1 | 0.0 | 0.2 | 0.0 | 6075.1 | 0.0 | 0.2 | 6102.1 |
+| `photo-argb32-topdown` | 8100.1 | 0.0 | 0.3 | 0.0 | 8100.1 | 0.0 | 0.2 | 8127.1 |
+| `photo-rgb565` | 4050.1 | 0.0 | — | — | 4050.1 | 0.0 | 0.2 | — |
+| `photo-p8` | 35764.2 | 33738.2 | — | — | 35764.2 | 33738.1 | 25896.7 | — |
+| `photo-rle8` | 44972.6 | 42898.7 | — | — | 44972.6 | 42898.7 | — | — |
+| `photo-ico-set` | 1051.7 | — | — | — | — | — | — | — |
+| `screen-rgb24` | 6075.1 | 0.0 | — | 0.0 | 6075.1 | 0.0 | 0.2 | 6102.1 |
+| `screen-argb32` | 8100.1 | 0.0 | — | 0.0 | 8100.1 | 0.0 | 0.2 | 8127.1 |
+| `screen-rgb24-topdown` | 6075.1 | 0.0 | 0.2 | 0.0 | 6075.1 | 0.0 | 0.2 | 6102.1 |
+| `screen-argb32-topdown` | 8100.1 | 0.0 | 0.3 | 0.0 | 8100.1 | 0.0 | 0.2 | 8127.1 |
+| `screen-rgb565` | 4050.1 | 0.0 | — | — | 4050.1 | 0.0 | 0.2 | — |
+| `screen-p8` | 16526.9 | 14500.8 | — | — | 16526.9 | 14500.8 | 3088.0 | — |
+| `screen-rle8` | 15892.2 | 15702.2 | — | — | 15892.2 | 15702.2 | — | — |
+| `screen-ico-set` | 293.0 | — | — | — | — | — | — | — |
+
+Notes:
+
+- `photo-rgb565`: ImageSharp's 16-bit layout is its own (it may be 5-5-5); sizes are equal either way
+- `photo-ico-set`: 16, 32 and 48 as 32-bit DIBs, 256 as PNG; neither ImageSharp 3.1 nor WIC writes icons
+- `screen-rgb565`: ImageSharp's 16-bit layout is its own (it may be 5-5-5); sizes are equal either way
+- `screen-ico-set`: 16, 32 and 48 as 32-bit DIBs, 256 as PNG; neither ImageSharp 3.1 nor WIC writes icons
diff --git a/src/Sdcb.SimdCodecs.Bmp/BmpEncoder.cs b/src/Sdcb.SimdCodecs.Bmp/BmpEncoder.cs
index d816956..b76dcd4 100644
--- a/src/Sdcb.SimdCodecs.Bmp/BmpEncoder.cs
+++ b/src/Sdcb.SimdCodecs.Bmp/BmpEncoder.cs
@@ -214,6 +214,120 @@ private static byte[] Write(ReadOnlySpan pixels, int width, int height, Pi
: format == PixelFormat.Gray8 ? BmpEncodeFormat.Indexed8
: BmpEncodeFormat.Rgb24;
}
+ var plan = PlanFile(layout, options, iconImage);
+ Validate(options, layout, plan.Header, width, height, iconImage);
+ var bpp = plan.Bpp;
+ var indexed = plan.Indexed;
+
+ // Palette and indices, or nothing for direct colour.
+ int[] palette = [];
+ byte[]? indices = null;
+ if (indexed) (palette, indices) = Palettize(input, 1 << bpp, options.Dither, blackTransparent: iconImage);
+
+ // The pixel bytes: rows of whole 32-bit words, or the RLE stream.
+ var rowBytes = plan.RowBytes(width);
+ var usedBytes = plan.UsedBytes(width);
+ byte[]? rle = options.Rle ? Rle.Encode(indices!, width, height, bpp) : null;
+ var pixelBytes = rle?.Length ?? (long)rowBytes * height;
+ var maskStride = (width + 31) / 32 * 4;
+ var maskBytes = iconImage ? (long)maskStride * height : 0;
+ var icc = plan.Header == BmpHeaderVersion.V5 ? options.IccProfile.Span : default;
+
+ var pixelOffset = plan.PixelOffset(file, palette.Length); // at most 1174
+ var total = pixelOffset + pixelBytes + maskBytes + icc.Length;
+ if (total > (stream is null ? Array.MaxLength : uint.MaxValue))
+ throw new ArgumentOutOfRangeException(nameof(width), "The bitmap would be larger than the format or an array can hold.");
+
+ // Headers, masks and palette.
+ Span o = stackalloc byte[pixelOffset];
+ WriteHeaders(o, plan, width, height, options, file, iconImage, palette, pixelBytes, maskBytes, icc.Length, total);
+
+ var output = stream is null ? GC.AllocateUninitializedArray((int)total) : null;
+ byte[]? pooled = stream is null ? null : ArrayPool.Shared.Rent(Math.Max(Math.Max(rowBytes, maskStride), pixelOffset));
+ try
+ {
+ var at = 0L;
+ // The next `length` bytes of the file: in the array, or in the pooled row until Flush writes it out.
+ Span Next(int length) => output is not null ? output.AsSpan((int)at, length) : pooled.AsSpan(0, length);
+ void Flush(int length)
+ {
+ if (stream is not null) stream.Write(pooled!, 0, length);
+ at += length;
+ }
+
+ o.CopyTo(Next(pixelOffset));
+ Flush(pixelOffset);
+
+ if (rle is not null)
+ {
+ if (output is not null) rle.CopyTo(Next(rle.Length));
+ else stream!.Write(rle);
+ at += rle.Length;
+ }
+ else
+ {
+ for (var r = 0; r < height; r++)
+ {
+ var y = options.TopDown ? r : height - 1 - r;
+ var row = Next(rowBytes);
+ if (indexed)
+ {
+ row.Clear(); // PackIndices ORs bits in
+ PackIndices(indices.AsSpan(y * width, width), row, bpp);
+ }
+ else
+ {
+ row[usedBytes..].Clear(); // the padding to a 32-bit word
+ WriteDirect(input, y, row, layout, iconImage);
+ }
+ Flush(rowBytes);
+ }
+ }
+
+ if (iconImage)
+ {
+ for (var r = 0; r < height; r++)
+ {
+ var y = height - 1 - r;
+ var row = Next(maskStride);
+ row.Clear();
+ for (var x = 0; x < width; x++)
+ {
+ if (input.Alpha(x, y) < 128) row[x >> 3] |= (byte)(0x80 >> (x & 7));
+ }
+ Flush(maskStride);
+ }
+ }
+
+ if (output is not null) icc.CopyTo(output.AsSpan((int)at));
+ else stream!.Write(icc);
+ return output;
+ }
+ finally
+ {
+ if (pooled is not null) ArrayPool.Shared.Return(pooled);
+ }
+ }
+
+ /// The file layout a set of options gives: header version, depth, compression and where things go.
+ internal readonly record struct FilePlan(BmpEncodeFormat Layout, BmpHeaderVersion Header, int Bpp, bool Bitfields,
+ uint Compression, int HeaderSize, int MasksAfterHeader)
+ {
+ public bool Indexed => Bpp <= 8;
+ public int EntrySize => Header == BmpHeaderVersion.Core ? 3 : 4;
+ public int RowBytes(int width) => (int)(((long)width * Bpp + 31) / 32 * 4);
+ public int UsedBytes(int width) => (int)(((long)width * Bpp + 7) / 8);
+
+ // A core header has no colour count, so its palette is always full; direct colour has none.
+ public int PaletteEntries(int paletteLength) => Header == BmpHeaderVersion.Core && Indexed ? 1 << Bpp : paletteLength;
+
+ public int PixelOffset(bool file, int paletteLength) =>
+ (file ? 14 : 0) + HeaderSize + MasksAfterHeader + PaletteEntries(paletteLength) * EntrySize;
+ }
+
+ /// The plan for a resolved (not ) layout.
+ internal static FilePlan PlanFile(BmpEncodeFormat layout, BmpEncodeOptions options, bool iconImage)
+ {
var header = options.Header;
if (header == BmpHeaderVersion.Auto)
{
@@ -222,8 +336,6 @@ private static byte[] Write(ReadOnlySpan pixels, int width, int height, Pi
: layout == BmpEncodeFormat.Argb32 ? BmpHeaderVersion.V4
: BmpHeaderVersion.Info;
}
- Validate(options, layout, header, width, height, iconImage);
-
var bpp = layout switch
{
BmpEncodeFormat.Indexed1 => 1,
@@ -233,7 +345,6 @@ private static byte[] Write(ReadOnlySpan pixels, int width, int height, Pi
BmpEncodeFormat.Rgb24 => 24,
_ => 32,
};
- var indexed = bpp <= 8;
var bitfields = layout == BmpEncodeFormat.Rgb565 || (layout == BmpEncodeFormat.Argb32 && header >= BmpHeaderVersion.V4);
var compression = options.Rle ? (bpp == 8 ? 1u : 2u) : bitfields ? 3u : 0u;
var headerSize = header switch
@@ -244,32 +355,18 @@ private static byte[] Write(ReadOnlySpan pixels, int width, int height, Pi
_ => 124,
};
var masksAfterHeader = bitfields && header == BmpHeaderVersion.Info ? 12 : 0;
+ return new FilePlan(layout, header, bpp, bitfields, compression, headerSize, masksAfterHeader);
+ }
- // Palette and indices, or nothing for direct colour.
- int[] palette = [];
- byte[]? indices = null;
- if (indexed) (palette, indices) = Palettize(input, 1 << bpp, options.Dither, blackTransparent: iconImage);
- // A core header has no colour count, so its palette is always full; direct colour has none.
- var paletteEntries = header == BmpHeaderVersion.Core && indexed ? 1 << bpp : palette.Length;
- var entrySize = header == BmpHeaderVersion.Core ? 3 : 4;
-
- // The pixel bytes: rows of whole 32-bit words, or the RLE stream.
- var rowBytes = (int)(((long)width * bpp + 31) / 32 * 4);
- var usedBytes = (int)(((long)width * bpp + 7) / 8);
- byte[]? rle = options.Rle ? Rle.Encode(indices!, width, height, bpp) : null;
- var pixelBytes = rle?.Length ?? (long)rowBytes * height;
- var maskStride = (width + 31) / 32 * 4;
- var maskBytes = iconImage ? (long)maskStride * height : 0;
- var icc = header == BmpHeaderVersion.V5 ? options.IccProfile.Span : default;
-
+ /// The file header (when ), bitmap header, masks and palette, into
+ /// ( bytes).
+ private static void WriteHeaders(Span o, FilePlan plan, int width, int height, BmpEncodeOptions options, bool file,
+ bool iconImage, int[] palette, long pixelBytes, long maskBytes, int iccLength, long total)
+ {
+ var (layout, header, bpp, bitfields) = (plan.Layout, plan.Header, plan.Bpp, plan.Bitfields);
+ var (indexed, headerSize, masksAfterHeader, entrySize) = (plan.Indexed, plan.HeaderSize, plan.MasksAfterHeader, plan.EntrySize);
var fileHeader = file ? 14 : 0;
- var pixelOffset = fileHeader + headerSize + masksAfterHeader + paletteEntries * entrySize; // at most 1174
- var total = pixelOffset + pixelBytes + maskBytes + icc.Length;
- if (total > (stream is null ? Array.MaxLength : uint.MaxValue))
- throw new ArgumentOutOfRangeException(nameof(width), "The bitmap would be larger than the format or an array can hold.");
-
- // Headers, masks and palette.
- Span o = stackalloc byte[pixelOffset];
+ var pixelOffset = plan.PixelOffset(file, palette.Length);
o.Clear();
if (file)
{
@@ -295,7 +392,7 @@ private static byte[] Write(ReadOnlySpan pixels, int width, int height, Pi
BinaryPrimitives.WriteInt32LittleEndian(h[8..], storedHeight);
BinaryPrimitives.WriteUInt16LittleEndian(h[12..], 1);
BinaryPrimitives.WriteUInt16LittleEndian(h[14..], (ushort)bpp);
- BinaryPrimitives.WriteUInt32LittleEndian(h[16..], compression);
+ BinaryPrimitives.WriteUInt32LittleEndian(h[16..], plan.Compression);
BinaryPrimitives.WriteUInt32LittleEndian(h[20..], (uint)(pixelBytes + maskBytes));
BinaryPrimitives.WriteInt32LittleEndian(h[24..], options.PixelsPerMeterX);
BinaryPrimitives.WriteInt32LittleEndian(h[28..], options.PixelsPerMeterY);
@@ -317,91 +414,70 @@ private static byte[] Write(ReadOnlySpan pixels, int width, int height, Pi
if (header >= BmpHeaderVersion.V4)
{
// Endpoints and gamma stay 0: they are read only for LCS_CALIBRATED_RGB.
- BinaryPrimitives.WriteUInt32LittleEndian(h[56..], icc.IsEmpty ? SrgbTag : ProfileEmbedded);
+ BinaryPrimitives.WriteUInt32LittleEndian(h[56..], iccLength == 0 ? SrgbTag : ProfileEmbedded);
if (header == BmpHeaderVersion.V5)
{
BinaryPrimitives.WriteUInt32LittleEndian(h[108..], ImagesIntent);
- if (!icc.IsEmpty)
+ if (iccLength != 0)
{
- BinaryPrimitives.WriteUInt32LittleEndian(h[112..], (uint)(total - icc.Length - fileHeader));
- BinaryPrimitives.WriteUInt32LittleEndian(h[116..], (uint)icc.Length);
+ BinaryPrimitives.WriteUInt32LittleEndian(h[112..], (uint)(total - iccLength - fileHeader));
+ BinaryPrimitives.WriteUInt32LittleEndian(h[116..], (uint)iccLength);
}
}
}
- var pal = o.Slice(fileHeader + headerSize + masksAfterHeader, paletteEntries * entrySize);
+ var pal = o.Slice(fileHeader + headerSize + masksAfterHeader, plan.PaletteEntries(palette.Length) * entrySize);
for (var i = 0; i < palette.Length; i++)
{
pal[i * entrySize] = (byte)palette[i];
pal[i * entrySize + 1] = (byte)(palette[i] >> 8);
pal[i * entrySize + 2] = (byte)(palette[i] >> 16);
}
+ }
- var output = stream is null ? GC.AllocateUninitializedArray((int)total) : null;
- byte[]? pooled = stream is null ? null : ArrayPool.Shared.Rent(Math.Max(Math.Max(rowBytes, maskStride), pixelOffset));
- try
- {
- var at = 0L;
- // The next `length` bytes of the file: in the array, or in the pooled row until Flush writes it out.
- Span Next(int length) => output is not null ? output.AsSpan((int)at, length) : pooled.AsSpan(0, length);
- void Flush(int length)
- {
- if (stream is not null) stream.Write(pooled!, 0, length);
- at += length;
- }
-
- o.CopyTo(Next(pixelOffset));
- Flush(pixelOffset);
+ // ---- Streaming ---------------------------------------------------------------------------------------------
- if (rle is not null)
- {
- if (output is not null) rle.CopyTo(Next(rle.Length));
- else stream!.Write(rle);
- at += rle.Length;
- }
- else
- {
- for (var r = 0; r < height; r++)
- {
- var y = options.TopDown ? r : height - 1 - r;
- var row = Next(rowBytes);
- if (indexed)
- {
- row.Clear(); // PackIndices ORs bits in
- PackIndices(indices.AsSpan(y * width, width), row, bpp);
- }
- else
- {
- row[usedBytes..].Clear(); // the padding to a 32-bit word
- WriteDirect(input, y, row, layout, iconImage);
- }
- Flush(rowBytes);
- }
- }
+ ///
+ /// True when fix the file's size and every offset before any pixel is seen, so a session
+ /// can write the file a row at a time in file order: top-down, a direct-colour layout named explicitly (not
+ /// , which scans the image for alpha; not a palette, which needs every colour),
+ /// and no RLE.
+ ///
+ internal static bool CanStream(BmpEncodeOptions options) => options.TopDown && !options.Rle
+ && options.Format is BmpEncodeFormat.Rgb555 or BmpEncodeFormat.Rgb565 or BmpEncodeFormat.Rgb24
+ or BmpEncodeFormat.Rgb32 or BmpEncodeFormat.Argb32;
- if (iconImage)
- {
- for (var r = 0; r < height; r++)
- {
- var y = height - 1 - r;
- var row = Next(maskStride);
- row.Clear();
- for (var x = 0; x < width; x++)
- {
- if (input.Alpha(x, y) < 128) row[x >> 3] |= (byte)(0x80 >> (x & 7));
- }
- Flush(maskStride);
- }
- }
+ ///
+ /// The headers of a streamed file ( options), checked as
+ /// checks them: the same bytes it writes before the rows. The rows then come from , the
+ /// options' V5 profile after them.
+ ///
+ /// The size or options do not fit.
+ internal static byte[] StreamHeaders(int width, int height, BmpEncodeOptions options, out FilePlan plan)
+ {
+ if (width < 1 || height < 1)
+ throw new ArgumentOutOfRangeException(nameof(width), $"A bitmap is at least 1x1, not {width}x{height}.");
+ if ((long)width * height > BmpHeader.MaximumPixels)
+ throw new ArgumentOutOfRangeException(nameof(width), $"{width}x{height} is above the limit of {BmpHeader.MaximumPixels:N0} pixels.");
+ plan = PlanFile(options.Format, options, iconImage: false);
+ Validate(options, options.Format, plan.Header, width, height, iconImage: false);
+ var iccLength = plan.Header == BmpHeaderVersion.V5 ? options.IccProfile.Length : 0;
+ var pixelBytes = (long)plan.RowBytes(width) * height;
+ var pixelOffset = plan.PixelOffset(file: true, 0);
+ var total = pixelOffset + pixelBytes + iccLength;
+ if (total > uint.MaxValue)
+ throw new ArgumentOutOfRangeException(nameof(width), "The bitmap would be larger than the format can hold (4 GiB).");
+ var headers = new byte[pixelOffset];
+ WriteHeaders(headers, plan, width, height, options, file: true, iconImage: false, [], pixelBytes, 0, iccLength, total);
+ return headers;
+ }
- if (output is not null) icc.CopyTo(output.AsSpan((int)at));
- else stream!.Write(icc);
- return output;
- }
- finally
- {
- if (pooled is not null) ArrayPool.Shared.Return(pooled);
- }
+ /// One stored row ( bytes, padding cleared) from one input row in
+ /// , an 8-bit basic layout: what the whole-image encoder writes for that row.
+ internal static void WriteStreamRow(ReadOnlySpan source, int width, PixelFormat format, FilePlan plan, Span row)
+ {
+ row[plan.UsedBytes(width)..].Clear();
+ WriteDirect(new Input(source, width, 1, format, width * format.BytesPerPixel), 0, row, plan.Layout, iconImage: false);
}
private static void Validate(BmpEncodeOptions options, BmpEncodeFormat layout, BmpHeaderVersion header, int width, int height, bool iconImage)
diff --git a/src/Sdcb.SimdCodecs.Bmp/BmpHeader.cs b/src/Sdcb.SimdCodecs.Bmp/BmpHeader.cs
index 6ad0d23..ead622c 100644
--- a/src/Sdcb.SimdCodecs.Bmp/BmpHeader.cs
+++ b/src/Sdcb.SimdCodecs.Bmp/BmpHeader.cs
@@ -54,6 +54,10 @@ internal readonly struct BmpHeader
public int IccOffset { get; private init; }
public int IccLength { get; private init; }
+ /// A prefix's header (): an embedded profile is declared
+ /// whose bytes are not in the prefix, so whether it is used depends on the rest of the file.
+ public bool IccBeyondPrefix { get; private init; }
+
/// Bytes per stored row of an uncompressed bitmap: whole 32-bit words.
public int Stride => (int)(((long)Width * BitsPerPixel + 31) / 32 * 4);
@@ -72,6 +76,26 @@ public static bool HasSignature(ReadOnlySpan header)
return header[0] == 'B' && header[1] == 'A' && header[14] == 'B' && header[15] == 'M';
}
+ ///
+ /// How much of a file with prefix needs: the larger of the
+ /// pixel offset (, from the file header) and 16 bytes past the bitmap header. −1 when
+ /// is too short to tell yet; 0 when its first bytes already show a file
+ /// refuses.
+ ///
+ public static long PrefixLength(ReadOnlySpan data, out long pixelOffset)
+ {
+ pixelOffset = 0;
+ if (data.Length < 2) return -1;
+ if (data[0] != 'B' || data[1] is not ((byte)'M' or (byte)'A')) return 0;
+ var fileHeader = data[1] == 'A' ? 14 : 0;
+ if (data.Length < fileHeader + 18) return -1;
+ if (fileHeader != 0 && (data[14] != 'B' || data[15] != 'M')) return 0;
+ var size = BinaryPrimitives.ReadUInt32LittleEndian(data[(fileHeader + 14)..]);
+ if (!IsHeaderSize(size)) return 0;
+ pixelOffset = BinaryPrimitives.ReadUInt32LittleEndian(data[(fileHeader + 10)..]);
+ return Math.Max(pixelOffset, fileHeader + 14 + size + 16);
+ }
+
// Core (12); OS/2 2.x, cut after any of its fields (16 to 40 in 4-byte steps, then 42, 44, 46, 48, 52, 56,
// 60 and 64), which also covers the 40-, 52- and 56-byte Windows headers; V4 (108); V5 (124, or longer).
private static bool IsHeaderSize(uint size) =>
@@ -80,7 +104,16 @@ private static bool IsHeaderSize(uint size) =>
/// Parses a bitmap file: a BITMAPFILEHEADER and the DIB after it, or the first bitmap of an
/// OS/2 bitmap array.
/// The data is not a bitmap this reader decodes.
- public static BmpHeader ReadFile(ReadOnlySpan data)
+ public static BmpHeader ReadFile(ReadOnlySpan data) => ReadFile(data, prefix: false);
+
+ ///
+ /// , or with over the start of a file only: the
+ /// streaming reader's header. A prefix must reach the file header's pixel offset (which must not point into the
+ /// headers) and 16 bytes past the bitmap header; then the header comes out as it would from the whole file, except
+ /// that the raster is not checked for truncation (the reader finds that as it reads) and a profile whose bytes lie
+ /// beyond the prefix sets instead of being dropped.
+ ///
+ public static BmpHeader ReadFile(ReadOnlySpan data, bool prefix)
{
if (data.Length < 18 || data[0] != 'B')
throw new InvalidDataException("Not a BMP file: no 'BM' signature.");
@@ -99,7 +132,7 @@ public static BmpHeader ReadFile(ReadOnlySpan data)
throw new InvalidDataException("Not a BMP file: no 'BM' signature.");
}
var offBits = BinaryPrimitives.ReadUInt32LittleEndian(data[(fileHeader + 10)..]);
- return Parse(data, fileHeader + 14, offBits, iconMask: false);
+ return Parse(data, fileHeader + 14, offBits, iconMask: false, prefix);
}
/// Parses a packed DIB: a bitmap header, its masks and palette, then the pixels, as the clipboard
@@ -107,9 +140,9 @@ public static BmpHeader ReadFile(ReadOnlySpan data)
/// An icon image: the header's height counts the colour bitmap and the 1-bit AND
/// mask after it, which says which pixels are transparent.
/// The data is not a DIB this reader decodes.
- public static BmpHeader ReadDib(ReadOnlySpan data, bool iconMask) => Parse(data, 0, null, iconMask);
+ public static BmpHeader ReadDib(ReadOnlySpan data, bool iconMask) => Parse(data, 0, null, iconMask, prefix: false);
- private static BmpHeader Parse(ReadOnlySpan data, int dib, uint? offBits, bool iconMask)
+ private static BmpHeader Parse(ReadOnlySpan data, int dib, uint? offBits, bool iconMask, bool prefix)
{
if (data.Length - dib < 4) throw Truncated();
var size = BinaryPrimitives.ReadUInt32LittleEndian(data[dib..]);
@@ -268,7 +301,7 @@ private static BmpHeader Parse(ReadOnlySpan data, int dib, uint? offBits,
// Every row must be there; the last may stop short of its padding, which some writers leave out.
var stride = (long)header.Stride;
var needed = stride * (height - 1) + (width * bitCount + 7) / 8;
- if (header.PixelLength < needed)
+ if (!prefix && header.PixelLength < needed)
throw new InvalidDataException($"The pixel data is truncated: {header.PixelLength} of {needed} bytes.");
if (iconMask)
{
@@ -288,6 +321,12 @@ private static BmpHeader Parse(ReadOnlySpan data, int dib, uint? offBits,
var length = (long)BinaryPrimitives.ReadUInt32LittleEndian(h[116..]);
if (length > 0 && offset >= dib + size && offset + length <= data.Length)
header = header.WithIcc((int)offset, (int)length);
+ else if (prefix && length > 0 && offset >= dib + size)
+ header = header with { IccBeyondPrefix = true };
+ // In a prefix, one after the pixel offset counts as beyond it however much was read: what streams then
+ // does not depend on how the stream arrived.
+ if (prefix && header.IccLength > 0 && offset + length > pixels)
+ header = header.WithIcc(0, 0) with { IccBeyondPrefix = true };
}
return header;
}
diff --git a/src/Sdcb.SimdCodecs.Bmp/BmpImageDecoder.cs b/src/Sdcb.SimdCodecs.Bmp/BmpImageDecoder.cs
index 5add7da..4757502 100644
--- a/src/Sdcb.SimdCodecs.Bmp/BmpImageDecoder.cs
+++ b/src/Sdcb.SimdCodecs.Bmp/BmpImageDecoder.cs
@@ -11,7 +11,7 @@ namespace Sdcb.SimdCodecs.Bmp;
/// writes the caller's buffer directly. Malformed data makes the Try methods return false rather
/// than throw.
///
-public sealed class BmpImageDecoder : IImageDecoder
+public sealed class BmpImageDecoder : IStreamingImageDecoder
{
/// The registration for ImageCodecs.Register, built from this type's method groups.
public static ImageDecoderRegistration Registration { get; } = new()
@@ -25,6 +25,7 @@ public sealed class BmpImageDecoder : IImageDecoder
TryDecodeInto = TryDecodeInto,
TryReadMetadata = TryReadMetadata,
TryDecodeThumbnail = TryDecodeThumbnail,
+ CreateRowReader = CreateRowReader,
};
///
@@ -44,16 +45,7 @@ public static bool TryReadInfo(ReadOnlySpan data, out ImageInfo info)
{
try
{
- var header = BmpHeader.ReadFile(data);
- var bmp = BmpDecoder.Info(data, header);
- info = new ImageInfo(bmp.Width, bmp.Height, bmp.Channels, SampleFormat.UInt8)
- {
- Format = ImageFormat.Bmp,
- ColorEncoding = ColorOf(data, header),
- BitDepth = BmpDecoder.BitDepth(header),
- Resolution = header.XPelsPerMeter == 0 && header.YPelsPerMeter == 0 ? null
- : new Resolution(header.XPelsPerMeter, header.YPelsPerMeter, ResolutionUnit.PerMeter),
- };
+ info = InfoOf(data, BmpHeader.ReadFile(data));
return true;
}
catch (InvalidDataException)
@@ -63,6 +55,31 @@ public static bool TryReadInfo(ReadOnlySpan data, out ImageInfo info)
}
}
+ // The header as ImageInfo; `data` holds the file from its start, at least through the profile when there is one.
+ internal static ImageInfo InfoOf(ReadOnlySpan data, BmpHeader header)
+ {
+ var bmp = BmpDecoder.Info(data, header);
+ return new ImageInfo(bmp.Width, bmp.Height, bmp.Channels, SampleFormat.UInt8)
+ {
+ Format = ImageFormat.Bmp,
+ ColorEncoding = ColorOf(data, header),
+ BitDepth = BmpDecoder.BitDepth(header),
+ Resolution = header.XPelsPerMeter == 0 && header.YPelsPerMeter == 0 ? null
+ : new Resolution(header.XPelsPerMeter, header.YPelsPerMeter, ResolutionUnit.PerMeter),
+ };
+ }
+
+ ///
+ ///
+ /// Uncompressed bitmaps (every depth, palettes and channel masks) stream to the 8-bit basic formats at full size: a
+ /// top-down bitmap from any stream; a bottom-up one, or a 32-bit BI_RGB one decoded with alpha (whose fourth
+ /// byte is alpha only if some pixel's is not 0), from a seekable stream, which the reader reads forward once and then
+ /// seeks back a band of rows at a time. Memory is a band of rows either way. RLE, Huffman 1D, BI_PNG, other
+ /// formats or options, a V5 profile stored after the pixels, and the cases above on a stream that cannot seek, are
+ /// decoded whole behind the same reader ( false).
+ ///
+ public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) =>
+ new BmpRowReader(input, format, options);
///
public static bool TryGetClosestSize(ReadOnlySpan data, int requestedWidth, int requestedHeight,
out int width, out int height, out int scaleDenominator) =>
diff --git a/src/Sdcb.SimdCodecs.Bmp/BmpImageEncoder.cs b/src/Sdcb.SimdCodecs.Bmp/BmpImageEncoder.cs
index 83a563d..2aa3562 100644
--- a/src/Sdcb.SimdCodecs.Bmp/BmpImageEncoder.cs
+++ b/src/Sdcb.SimdCodecs.Bmp/BmpImageEncoder.cs
@@ -39,14 +39,89 @@ public sealed class BmpImageEncoder : IImageEncoder
///
/// is a (null means the defaults; any other
/// type throws ). An ICC profile given to overrides the matching
- /// option.
- public static IImageEncoderSession Create(IBufferWriter output, EncodeOptions? options = null) =>
- new Session(output, options switch
+ /// option.
+ ///
+ /// The session streams () when the options fix the file's size and
+ /// offsets before any pixel arrives: , an explicit direct-colour
+ /// (, ,
+ /// , , )
+ /// and no RLE. Each band of rows is then written as it arrives, the same bytes as the buffered session's (which
+ /// writes an array, so stops at bytes where a streamed file may reach 4 GiB). Its
+ /// options are checked at , where the headers are written, rather than
+ /// at commit. Otherwise (bottom-up, , a palette) the image is collected and
+ /// encoded at commit.
+ ///
+ ///
+ public static IImageEncoderSession Create(IBufferWriter output, EncodeOptions? options = null)
+ {
+ var o = options switch
{
null => new BmpEncodeOptions(),
- BmpEncodeOptions o => o,
+ BmpEncodeOptions b => b,
_ => throw new ArgumentException($"BMP encoding takes BmpEncodeOptions, not {options.GetType().Name}.", nameof(options)),
- });
+ };
+ return BmpEncoder.CanStream(o) ? new StreamingSession(output, o) : new Session(output, o);
+ }
+
+ private static BmpEncodeOptions WithMetadata(BmpEncodeOptions options, ImageMetadata? metadata) =>
+ metadata is { } m && !m.Icc.IsEmpty ? options with { IccProfile = m.Icc } : options;
+
+ /// A top-down direct-colour file, written in file order: headers at the frame, rows as they come, the
+ /// profile at commit.
+ private sealed class StreamingSession(IBufferWriter output, BmpEncodeOptions options) : StreamingEncoderSession(output)
+ {
+ private BmpEncodeOptions _options = options;
+ private BmpEncoder.FilePlan _plan;
+ private PixelFormat _input, _native;
+ private int _width;
+ private byte[]? _converted;
+
+ public override int MaxFrames => 1;
+
+ protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color,
+ ImageMetadata? metadata, TimeSpan? duration)
+ {
+ _options = WithMetadata(_options, metadata);
+ var headers = BmpEncoder.StreamHeaders(width, height, _options, out _plan);
+ (_width, _input, _native) = (width, format, GetClosestInputFormat(format));
+ if (_native != _input)
+ _converted = ArrayPool.Shared.Rent(checked(width * _native.BytesPerPixel));
+ WriteOutput(headers);
+ }
+
+ protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken)
+ {
+ var rowBytes = _plan.RowBytes(_width);
+ var inBytes = _width * _input.BytesPerPixel;
+ for (var i = 0; i < rowCount; i++)
+ {
+ if ((i & 63) == 0) cancellationToken.ThrowIfCancellationRequested();
+ var source = rows.Slice(i * stride, inBytes);
+ if (_converted is not null)
+ {
+ var native = _converted.AsSpan(0, _width * _native.BytesPerPixel);
+ PixelConverter.ConvertRow(source, _input, native, _native, _width);
+ source = native;
+ }
+ var row = Output.GetSpan(rowBytes)[..rowBytes];
+ BmpEncoder.WriteStreamRow(source, _width, _native, _plan, row);
+ Output.Advance(rowBytes);
+ }
+ }
+
+ protected override void Finish(CancellationToken cancellationToken)
+ {
+ if (_plan.Header == BmpHeaderVersion.V5)
+ WriteOutput(_options.IccProfile.Span);
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (_converted is not null)
+ ArrayPool.Shared.Return(_converted);
+ _converted = null;
+ }
+ }
private sealed class Session(IBufferWriter output, BmpEncodeOptions options) : BufferedEncoderSession(output)
{
@@ -58,17 +133,11 @@ protected override void Encode(IReadOnlyList frames, Cancellation
var frame = frames[0];
var native = GetClosestInputFormat(frame.Format);
var pixels = frame.PixelsAs(native);
- var o = WithFrame(options, frame);
+ var o = WithMetadata(options, frame.Metadata);
+
var file = BmpEncoder.Encode(pixels, frame.Width, frame.Height, native, o);
WriteOutput(file);
}
- private static BmpEncodeOptions WithFrame(BmpEncodeOptions options, BufferedFrame frame)
- {
- var o = options;
- if (frame.Metadata is { } m && !m.Icc.IsEmpty)
- o = o with { IccProfile = m.Icc };
- return o;
- }
}
}
diff --git a/src/Sdcb.SimdCodecs.Bmp/BmpPixels.cs b/src/Sdcb.SimdCodecs.Bmp/BmpPixels.cs
index f665d42..d6736dd 100644
--- a/src/Sdcb.SimdCodecs.Bmp/BmpPixels.cs
+++ b/src/Sdcb.SimdCodecs.Bmp/BmpPixels.cs
@@ -70,7 +70,66 @@ private static void DecodePng(ReadOnlySpan data, BmpHeader h, Span d
// ---- Uncompressed ------------------------------------------------------------------------------------------
- private enum RowKind { Indexed, Copy24, Expand24, Swap24, Shuffle32, Pack32, Expand16, Fields }
+ internal enum RowKind { Indexed, Copy24, Expand24, Swap24, Shuffle32, Pack32, Expand16, Fields }
+
+ ///
+ /// How an uncompressed bitmap's rows decode to , chosen once per image: the row kernel, its
+ /// shuffle (4 bytes) and the bits it s, and the format it writes
+ /// (: , or RGBA when the output needs a converted detour).
+ ///
+ internal static RowKind PlanRows(BmpHeader h, PixelFormat format, Span control, out uint set, out PixelFormat target)
+ {
+ target = format;
+ var kind = Choose(h, format, control, out set);
+ if (kind is null)
+ {
+ target = PixelFormat.Rgba32;
+ kind = Choose(h, target, control, out set) ?? RowKind.Fields;
+ }
+ return kind.Value;
+ }
+
+ /// The per-mask channel decoder needs; null for any other kind.
+ internal static Fields? FieldsFor(RowKind kind, BmpHeader h) => kind == RowKind.Fields ? new Fields(h) : null;
+
+ ///
+ /// Decodes one stored row (: the row, or as much of the last row as the file holds, at least
+ /// its pixels) into in the planned target format.
+ ///
+ /// The row's pixels ORed together in a 32-bit layout, for the kinds that track alpha; 0 otherwise.
+ // Inlined into the span decoder's row loop: called a row at a time, a call per row is measurable on small images.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static uint DecodeRow(RowKind kind, in BmpHeader h, PixelFormat target, ReadOnlySpan source, Span output,
+ ReadOnlySpan lut, ReadOnlySpan control, uint set, Fields? fields, int tier)
+ {
+ var width = h.Width;
+ switch (kind)
+ {
+ case RowKind.Indexed:
+ ExpandIndexed(source, output, width, h.BitsPerPixel, lut, target.BytesPerPixel);
+ return 0;
+ case RowKind.Copy24:
+ source[..(3 * width)].CopyTo(output);
+ return 0;
+ case RowKind.Expand24:
+ BmpKernels.Expand24(source, output, width, swap: target == PixelFormat.Rgba32, tier);
+ return 0;
+ case RowKind.Swap24:
+ BmpKernels.Swap24(source, output, width, tier);
+ return 0;
+ case RowKind.Shuffle32:
+ return BmpKernels.Shuffle32(source, output, width, control, set, tier);
+ case RowKind.Pack32:
+ BmpKernels.Pack32To24(source, output, width, control, tier);
+ return 0;
+ case RowKind.Expand16:
+ BmpKernels.Expand16(source, output, width, green6: h.GreenMask == 0x07E0,
+ rgba: target == PixelFormat.Rgba32, BmpKernels.BestArithmeticTier);
+ return 0;
+ default:
+ return fields!.Decode(source, output, width, h.BitsPerPixel);
+ }
+ }
/// Every decoded pixel ORed together in the output's 32-bit layout, for 4-byte outputs (so its top
/// byte, alpha in both RGBA and BGRA, says whether any pixel had alpha); 0 otherwise.
@@ -82,17 +141,11 @@ private static uint DecodeUncompressed(ReadOnlySpan data, BmpHeader h, Spa
var tier = BmpKernels.BestTier;
// The row kernel, chosen once. A layout without one decodes to RGBA in a pooled row, then converts.
- var target = format;
Span control = stackalloc byte[4];
- var kind = Choose(h, format, control, out var set);
- if (kind is null)
- {
- target = PixelFormat.Rgba32;
- kind = Choose(h, target, control, out set) ?? RowKind.Fields;
- }
+ var kind = PlanRows(h, format, control, out var set, out var target);
Span lut = stackalloc uint[bpp <= 8 ? 256 : 0];
if (bpp <= 8) BuildPalette(data, h, target, lut);
- var fields = kind == RowKind.Fields ? new Fields(h) : null;
+ var fields = FieldsFor(kind, h);
byte[]? scratch = target == format ? null : ArrayPool.Shared.Rent(width * 4);
uint seen = 0;
try
@@ -105,34 +158,7 @@ private static uint DecodeUncompressed(ReadOnlySpan data, BmpHeader h, Spa
var y = h.TopDown ? r : height - 1 - r;
var row = destination.Slice(y * rowStride, width * outBytes);
var output = scratch is null ? row : scratch.AsSpan(0, width * 4);
- switch (kind)
- {
- case RowKind.Indexed:
- ExpandIndexed(source, output, width, bpp, lut, target.BytesPerPixel);
- break;
- case RowKind.Copy24:
- source[..(3 * width)].CopyTo(output);
- break;
- case RowKind.Expand24:
- BmpKernels.Expand24(source, output, width, swap: target == PixelFormat.Rgba32, tier);
- break;
- case RowKind.Swap24:
- BmpKernels.Swap24(source, output, width, tier);
- break;
- case RowKind.Shuffle32:
- seen |= BmpKernels.Shuffle32(source, output, width, control, set, tier);
- break;
- case RowKind.Pack32:
- BmpKernels.Pack32To24(source, output, width, control, tier);
- break;
- case RowKind.Expand16:
- BmpKernels.Expand16(source, output, width, green6: h.GreenMask == 0x07E0,
- rgba: target == PixelFormat.Rgba32, BmpKernels.BestArithmeticTier);
- break;
- default:
- seen |= fields!.Decode(source, output, width, bpp);
- break;
- }
+ seen |= DecodeRow(kind, in h, target, source, output, lut, control, set, fields, tier);
if (scratch is not null)
PixelConverter.ConvertRow(output, 4, SampleFormat.UInt8, row, format, width);
}
@@ -198,7 +224,7 @@ private static uint DecodeUncompressed(ReadOnlySpan data, BmpHeader h, Spa
};
/// Arbitrary channel masks, a pixel at a time, to RGBA or BGRA.
- private sealed class Fields
+ internal sealed class Fields
{
private readonly Channel _r, _g, _b, _a;
diff --git a/src/Sdcb.SimdCodecs.Bmp/BmpRowReader.cs b/src/Sdcb.SimdCodecs.Bmp/BmpRowReader.cs
new file mode 100644
index 0000000..6f0934d
--- /dev/null
+++ b/src/Sdcb.SimdCodecs.Bmp/BmpRowReader.cs
@@ -0,0 +1,304 @@
+using System.Buffers;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using Sdcb.SimdCodecs.Abstractions;
+using Sdcb.SimdCodecs.Abstractions.CodecSupport;
+
+namespace Sdcb.SimdCodecs.Bmp;
+
+///
+/// The streaming BMP reader (): uncompressed rows (BI_RGB,
+/// BI_BITFIELDS, BI_ALPHABITFIELDS, every depth and palette) decoded a band at a time with the span
+/// decoder's row kernels, so its rows are 's byte for byte.
+///
+/// - A top-down bitmap streams from any stream, front to back.
+/// -
+/// A bottom-up bitmap stores its top row last. From a seekable stream the reader reads forward to the end of the pixels,
+/// then seeks back a band of stored rows at a time (about ) and hands the band out last stored row
+/// first: memory stays a band, at the cost of reading the pixels twice. From a stream that cannot seek it falls back.
+///
+/// -
+/// A 32-bit BI_RGB bitmap's fourth byte is alpha unless it is 0 in every pixel, which only the last pixel can
+/// settle. Decoded to a format with alpha from a seekable stream, the reader scans every pixel's fourth byte first
+/// (in the forward pass a bottom-up bitmap makes anyway), then streams; from a stream that cannot seek it falls back. To a
+/// format without alpha the byte is never read, and the bitmap streams as any other.
+///
+/// -
+/// Everything else falls back ( false): RLE, Huffman 1D, BI_PNG,
+/// output formats other than the 8-bit basic ones, decode options other than the whole image, a pixel offset that points
+/// into the headers or more than bytes in, and a V5 profile stored after the pixels (the image's
+/// comes from the profile, so could not be
+/// known before the rows).
+///
+///
+///
+internal sealed class BmpRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) : StreamingRowReader(input, format)
+{
+ /// The bytes of stored rows a bottom-up band holds (at least one row).
+ internal const int BandBytes = 256 * 1024;
+
+ /// The furthest pixel offset streamed: the headers, palette and anything before the pixels are buffered whole.
+ internal const int MaxPrefix = 1 << 20;
+
+ private bool _fallback;
+ private BmpHeader _h;
+ private BmpPixels.RowKind _kind;
+ private PixelFormat _target;
+ private readonly byte[] _control = new byte[4];
+ private uint _set;
+ private uint[]? _lut;
+ private BmpPixels.Fields? _fields;
+ private byte[]? _scratch;
+ private int _tier;
+ private int _stride, _lastRowLength;
+ private long _regionLength; // the pixel bytes the decode reads: every stored row, the last one possibly short
+
+ // The forward pass of a bottom-up bitmap or an alpha scan.
+ private bool _scanning, _scanAlpha, _forceOpaque;
+ private long _scanned;
+ private uint _alphaSeen;
+
+ // Rows.
+ private int _row; // output rows written
+ private int _bandStart, _next; // bottom-up: the band's first stored row, and the next stored row to hand out
+
+ protected override OperationStatus DecodeHeader(ReadOnlySpan input, bool isFinal, out int consumed,
+ out ImageInfo info, out int width, out int height)
+ {
+ consumed = 0;
+ info = default;
+ width = height = 0;
+ if (!_fallback)
+ {
+ var needed = BmpHeader.PrefixLength(input, out var pixelOffset);
+ if (needed == 0)
+ {
+ BmpHeader.ReadFile(input); // throws the reason
+ throw new InvalidDataException("Not a BMP file.");
+ }
+ if (needed < 0 || needed > input.Length)
+ {
+ if (needed > MaxPrefix || isFinal)
+ _fallback = true;
+ else
+ return OperationStatus.NeedMoreData;
+ }
+ if (!_fallback)
+ {
+ var h = BmpHeader.ReadFile(input, prefix: true);
+ if (TryStream(h, pixelOffset))
+ {
+ info = BmpImageDecoder.InfoOf(input, h);
+ (width, height) = (h.Width, h.Height);
+ consumed = h.PixelOffset;
+ Plan(input, h);
+ return OperationStatus.Done;
+ }
+ _fallback = true;
+ }
+ }
+
+ // The fallback decodes the whole file, so its header is read from the whole file too: wait for the end.
+ if (!isFinal)
+ return OperationStatus.NeedMoreData;
+ if (!BmpImageDecoder.TryReadInfo(input, out info))
+ {
+ BmpHeader.ReadFile(input); // throws the reason, when it is the header
+ throw new InvalidDataException("The bitmap could not be read.");
+ }
+ UseBufferedFallback(BmpImageDecoder.TryDecodeInto, options);
+ (width, height) = (options ?? DecodeOptions.Default).GetOutputSize(info);
+ return OperationStatus.Done;
+ }
+
+ // Whether this header streams, and whether it needs the seekable forward pass.
+ private bool TryStream(BmpHeader h, long pixelOffset)
+ {
+ if (!IsFullImage(options) || !Format.IsBasic8)
+ return false;
+ if (h.Compression is not (BmpCompression.Rgb or BmpCompression.Bitfields or BmpCompression.AlphaBitfields))
+ return false;
+ // An offset into the headers makes the whole-file parser derive the pixels' place from the file's length.
+ if (h.PixelOffset != pixelOffset || h.IccBeyondPrefix)
+ return false;
+ // Going back needs a seekable stream, or one whose bytes the input retains (then the file is in memory anyway,
+ // but the output frame is not).
+ var seekable = Input.Length >= 0;
+ var scanAlpha = h.AlphaUnlessAllZero && Format.HasAlpha;
+ if ((!h.TopDown || scanAlpha) && !Input.CanRewind)
+ return false;
+
+ _stride = h.Stride;
+ _lastRowLength = (int)(((long)h.Width * h.BitsPerPixel + 7) / 8);
+ var needed = (long)_stride * (h.Height - 1) + _lastRowLength;
+ if (seekable)
+ {
+ var available = Input.Length - h.PixelOffset;
+ if (available < needed)
+ throw new InvalidDataException($"The pixel data is truncated: {Math.Max(0, available)} of {needed} bytes.");
+ }
+ _regionLength = (long)_stride * (h.Height - 1) + _lastRowLength;
+ _scanAlpha = scanAlpha;
+ // A bottom-up bitmap passes over its pixels even without the alpha scan: the input goes back, never forward,
+ // so the last band is reached by reading up to it.
+ _scanning = !h.TopDown || scanAlpha;
+ return true;
+ }
+
+ private void Plan(ReadOnlySpan prefix, BmpHeader h)
+ {
+ _h = h;
+ _tier = BmpKernels.BestTier;
+ _kind = BmpPixels.PlanRows(h, Format, _control, out _set, out _target);
+ if (h.BitsPerPixel <= 8)
+ {
+ _lut = new uint[256];
+ BmpPixels.BuildPalette(prefix, h, _target, _lut);
+ }
+ _fields = BmpPixels.FieldsFor(_kind, h);
+ if (_target != Format)
+ _scratch = ArrayPool.Shared.Rent(h.Width * 4);
+ _next = h.Height - 1;
+ _bandStart = h.Height; // no band yet
+ }
+
+ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed,
+ Span destination, int stride, int rowCount, out int rowsWritten)
+ {
+ consumed = rowsWritten = 0;
+ if (_scanning)
+ {
+ var take = (int)Math.Min(input.Length, _regionLength - _scanned);
+ if (_scanAlpha)
+ _alphaSeen |= AlphaOr(input[..take], _scanned);
+ _scanned += take;
+ if (_scanned < _regionLength)
+ {
+ consumed = take;
+ return OperationStatus.NeedMoreData;
+ }
+ // The whole raster has gone by: go back to the first rows handed out.
+ Input.Consume(take);
+ _scanning = false;
+ _forceOpaque = _scanAlpha && (_alphaSeen == 0);
+ if (_h.TopDown)
+ {
+ Input.Rewind(_h.PixelOffset);
+ }
+ else
+ {
+ StartBand(_h.Height);
+ }
+ input = Input.Buffered;
+ }
+ return _h.TopDown
+ ? TopDownRows(input, ref consumed, destination, stride, rowCount, ref rowsWritten)
+ : BottomUpRows(input, destination, stride, rowCount, ref rowsWritten);
+ }
+
+ private OperationStatus TopDownRows(ReadOnlySpan input, ref int consumed,
+ Span destination, int stride, int rowCount, ref int rowsWritten)
+ {
+ var height = _h.Height;
+ while (rowsWritten < rowCount)
+ {
+ // The last row may stop short of its padding, which some writers leave out; the kernels read only a row's
+ // pixels, so it decodes from its pixel bytes whatever follows them.
+ var available = input.Length - consumed;
+ var last = _row == height - 1;
+ if (available < (last ? _lastRowLength : _stride))
+ return OperationStatus.NeedMoreData;
+ var length = last ? Math.Min(available, _stride) : _stride;
+ Row(input.Slice(consumed, length), destination.Slice(rowsWritten * stride));
+ consumed += length;
+ rowsWritten++;
+ if (++_row == height)
+ return OperationStatus.Done;
+ }
+ return OperationStatus.Done;
+ }
+
+ private OperationStatus BottomUpRows(ReadOnlySpan input, Span destination, int stride, int rowCount,
+ ref int rowsWritten)
+ {
+ // The input starts at the band's first stored row; nothing is consumed until the band is done.
+ while (rowsWritten < rowCount)
+ {
+ var bandLength = BandLength(_bandStart, _next);
+ if (input.Length < bandLength)
+ return OperationStatus.NeedMoreData;
+ var at = (long)(_next - _bandStart) * _stride;
+ var length = _next == _h.Height - 1 ? _lastRowLength : _stride;
+ Row(input.Slice((int)at, length), destination.Slice(rowsWritten * stride));
+ rowsWritten++;
+ _row++;
+ if (--_next < _bandStart)
+ {
+ if (_row == _h.Height)
+ return OperationStatus.Done;
+ StartBand(_bandStart);
+ input = Input.Buffered;
+ }
+ }
+ return OperationStatus.Done;
+ }
+
+ // Moves the input back to the band that ends before stored row `end`.
+ private void StartBand(int end)
+ {
+ var rows = Math.Max(1, BandBytes / _stride);
+ _bandStart = Math.Max(0, end - rows);
+ _next = end - 1;
+ Input.Rewind(_h.PixelOffset + (long)_bandStart * _stride);
+ }
+
+ // The bytes from stored row `start` through `last` (the file's last row possibly short).
+ private int BandLength(int start, int last) =>
+ (int)((long)(last - start) * _stride + (last == _h.Height - 1 ? _lastRowLength : _stride));
+
+ private void Row(ReadOnlySpan source, Span destination)
+ {
+ var width = _h.Width;
+ var row = destination[..(width * Format.BytesPerPixel)];
+ var output = _scratch is null ? row : _scratch.AsSpan(0, width * 4);
+ BmpPixels.DecodeRow(_kind, in _h, _target, source, output, _lut, _control, _set, _fields, _tier);
+ if (_scratch is not null)
+ PixelConverter.ConvertRow(output, 4, SampleFormat.UInt8, row, Format, width);
+ if (_forceOpaque)
+ {
+ for (var x = 3; x < row.Length; x += 4) row[x] = 255;
+ }
+ }
+
+ // The fourth byte of every 32-bit pixel in `bytes`, which starts `offset` bytes into the raster, ORed together:
+ // the bytes before the first whole pixel and after the last one a byte at a time, the whole pixels as 32-bit words
+ // ORed with Vector (any width, or one element without vector hardware: OR is the same in every order).
+ [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
+ internal static uint AlphaOr(ReadOnlySpan bytes, long offset)
+ {
+ uint seen = 0;
+ var head = (int)Math.Min(bytes.Length, (4 - (offset & 3)) & 3);
+ for (var i = (int)((3 - (offset & 3)) & 3); i < head; i += 4)
+ seen |= bytes[i];
+ var words = MemoryMarshal.Cast(bytes[head..]);
+ var vectors = MemoryMarshal.Cast>(words);
+ var acc = Vector.Zero;
+ foreach (var v in vectors) acc |= v;
+ uint all = 0;
+ for (var i = 0; i < Vector.Count; i++) all |= acc[i];
+ for (var i = vectors.Length * Vector.Count; i < words.Length; i++) all |= words[i];
+ // A part pixel after the words holds no fourth byte.
+ return seen | all >> 24;
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && _scratch is not null)
+ {
+ ArrayPool.Shared.Return(_scratch);
+ _scratch = null;
+ }
+ base.Dispose(disposing);
+ }
+}
diff --git a/src/Sdcb.SimdCodecs.Bmp/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Bmp/PublicAPI.Unshipped.txt
index 7dc5c58..8f61077 100644
--- a/src/Sdcb.SimdCodecs.Bmp/PublicAPI.Unshipped.txt
+++ b/src/Sdcb.SimdCodecs.Bmp/PublicAPI.Unshipped.txt
@@ -1 +1,2 @@
#nullable enable
+static Sdcb.SimdCodecs.Bmp.BmpImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader!
diff --git a/src/Sdcb.SimdCodecs.Bmp/README.md b/src/Sdcb.SimdCodecs.Bmp/README.md
index 1bf415f..5c5b88a 100644
--- a/src/Sdcb.SimdCodecs.Bmp/README.md
+++ b/src/Sdcb.SimdCodecs.Bmp/README.md
@@ -46,6 +46,21 @@ byte[] rle = BmpEncoder.Encode(rgba, width, height, PixelFormat.Rgba32,
Input is any `PixelFormat` (B, G, R input written as 24- or 32-bit is copied as it is), or 1 / 3 / 4 channels. `BmpEncoder.EncodeDib` writes a packed DIB; with `iconImage: true`, an icon or cursor image: a 40-byte header with the doubled height, then the AND mask (alpha below 128 is transparent).
+## Streaming
+
+`BmpImageDecoder.CreateRowReader` reads rows top to bottom from a `StreamInput`, synchronously or asynchronously, holding a band of rows rather than the file. Its rows equal `TryDecodeInto`'s byte for byte, and its `Info` equals `TryReadInfo`'s.
+
+| Bitmap | Stream that cannot seek | Seekable stream |
+|---|---|---|
+| Uncompressed (`BI_RGB`, `BI_BITFIELDS`, `BI_ALPHABITFIELDS`, every depth and palette), top-down | Streams | Streams |
+| The same, bottom-up | Falls back | Streams: one forward pass to the end of the pixels, then a seek back to each band of about 256 KiB of stored rows, handed out last stored row first. The pixels are read twice |
+| 32-bit `BI_RGB` read to a layout with alpha | Falls back: its fourth byte is alpha only if some pixel's is not 0, which the last pixel can settle | Streams after a forward pass that reads every fourth byte (the bottom-up pass when there is one) |
+| RLE, Huffman 1D, `BI_PNG`; a layout other than 8-bit RGBA / BGRA / RGB / BGR / grey; decode options other than the whole image; a pixel offset into the headers or more than 1 MiB in; a V5 profile stored after the pixels | Falls back | Falls back |
+
+A `StreamInput` made with `retainConsumed: true` counts as seekable here: it goes back within the bytes it keeps (the file, then, but not a decoded frame). A reader that falls back reads the whole stream and decodes it with `TryDecodeInto` behind the same API (`IsStreaming` false). The profile case falls back because the image's `ColorEncoding` comes from the profile, and the reader's `Info` is settled before any row. A truncated stream throws `InvalidDataException` when the rows reach the missing bytes (at `Initialize` for a seekable stream, whose length says so).
+
+`BmpImageEncoder.Create` returns a streaming session (`IsStreaming` true) when `TopDown` is set, `Format` names a direct-colour layout (`Rgb555`, `Rgb565`, `Rgb24`, `Rgb32`, `Argb32`) and `Rle` is off: the file's size and offsets are then known before any pixel, so the headers go out with the frame and each band of rows as it is written, the profile at `Commit`. The bytes equal the buffered session's for the same options. Bottom-up files, `Auto` (which scans the image for alpha) and palettes are collected and encoded at `Commit`.
+
## Decisions
Where the documentation leaves a choice to the decoder, it is made as WIC (Windows' own decoder) makes it, with the exceptions marked; the test suite holds every one of them against WIC, ImageMagick or a hand-built stream.
diff --git a/tests/Sdcb.SimdCodecs.Tests/BmpStreamingTests.cs b/tests/Sdcb.SimdCodecs.Tests/BmpStreamingTests.cs
new file mode 100644
index 0000000..e9751a3
--- /dev/null
+++ b/tests/Sdcb.SimdCodecs.Tests/BmpStreamingTests.cs
@@ -0,0 +1,695 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Diagnostics.CodeAnalysis;
+using ImageMagick;
+using Sdcb.SimdCodecs.Abstractions;
+using Sdcb.SimdCodecs.Abstractions.CodecSupport;
+using Sdcb.SimdCodecs.Bmp;
+using Sdcb.SimdCodecs.Tests.Streaming;
+using Shouldly;
+
+namespace Sdcb.SimdCodecs.Tests;
+
+///
+/// BMP streaming: hands out TryDecodeInto's rows for every
+/// uncompressed layout — top-down from any stream, bottom-up from a seekable one (read forward, then seeked back a
+/// band at a time), a 32-bit BI_RGB alpha scan — and falls back for what it cannot stream; the streaming
+/// encoder writes exactly the buffered session's bytes before Commit.
+///
+public sealed class BmpStreamingTests
+{
+ private static readonly StreamingAssert.Feed[] Seekable = [StreamingAssert.Feed.Whole];
+ private static readonly StreamingAssert.Feed[] Unseekable =
+ [StreamingAssert.Feed.OneByte, StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly];
+
+ private static readonly PixelFormat[] Formats =
+ [PixelFormat.Rgba32, PixelFormat.Bgra32, PixelFormat.Rgb24, PixelFormat.Bgr24, PixelFormat.Gray8];
+
+ private static readonly PixelFormat[] OtherFormats = [PixelFormat.Rgba64, PixelFormat.GrayAlpha16];
+
+ private static ImageDecoderRegistration Decoder => BmpImageDecoder.Registration;
+
+ private static bool Basic(PixelFormat format) => format.IsBasic8;
+
+ /// A seeded pseudo-random pixel for (x, y) in bits, its channels staying in
+ /// range for the masks the layouts below use.
+ private static uint Value(int x, int y, int bitCount)
+ {
+ var v = (uint)(x * 7919 + y * 104729 + 12345);
+ v ^= v >> 13;
+ return bitCount switch
+ {
+ 1 or 2 or 4 or 8 => v & ((1u << bitCount) - 1),
+ 16 => v & 0xFFFF,
+ _ => bitCount == 24 ? v & 0xFFFFFF : v,
+ };
+ }
+
+ private static int[] Palette(int colors) => [.. Enumerable.Range(0, colors).Select(i => (i * 0x010307 * 37) & 0xFFFFFF)];
+
+ /// The layouts streamed, each a whole file: name, file, whether a stream that cannot seek can stream it
+ /// (top-down, and no alpha scan for a 32-bit BI_RGB).
+ public static TheoryData Variants() =>
+ ["rgb24", "rgb32", "bitfields32", "alphabitfields32", "rgb555", "rgb565", "bitfields16", "p8", "p4", "p2", "p1", "core24", "core8"];
+
+ [Theory]
+ [MemberData(nameof(Variants))]
+ public void Rows_equal_decode_into_every_feed(string variant)
+ {
+ foreach (var (file, topDown, alphaAmbiguous) in Files(variant))
+ {
+ foreach (var format in AllFormats)
+ {
+ var because = $"{variant} {file.Length} bytes to {format}";
+ var streaming = Basic(format) && topDown && !(alphaAmbiguous && format.HasAlpha);
+ if (Basic(format))
+ StreamingAssert.RowsEqualDecodeInto(Decoder, file, format, expectStreaming: true, feeds: Seekable);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, file, format, expectStreaming: streaming, feeds: Unseekable);
+ InfoMatches(file, format, because);
+ }
+ }
+ }
+
+ private static PixelFormat[] AllFormats => [.. Formats, .. OtherFormats];
+
+ private static void InfoMatches(byte[] file, PixelFormat format, string because)
+ {
+ var create = Decoder.CreateRowReader!;
+ using var reader = create(new StreamInput(new MemoryStream(file, writable: false)), format, null);
+ reader.Initialize(TestContext.Current.CancellationToken);
+ BmpImageDecoder.TryReadInfo(file, out var info).ShouldBeTrue(because);
+ reader.Width.ShouldBe(info.Width, because);
+ reader.Height.ShouldBe(info.Height, because);
+ reader.Info.Channels.ShouldBe(info.Channels, because);
+ reader.Info.BitDepth.ShouldBe(info.BitDepth, because);
+ reader.Info.Resolution.ShouldBe(info.Resolution, because);
+ reader.Info.ColorEncoding.ShouldBe(info.ColorEncoding, because);
+ }
+
+ /// Small files of each layout, top-down and bottom-up (pixels at least 3×3 where a palette needs a few).
+ private static (byte[] File, bool TopDown, bool AlphaAmbiguous)[] Files(string variant)
+ {
+ const int width = 37, height = 21;
+ var random = new Random(variant.Length * 31 + 7);
+ byte[] Build(bool topDown) => variant switch
+ {
+ "rgb24" => TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 24, 0),
+ [], TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24), topDown)),
+ "rgb32" => TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 32, 0),
+ [], TestBmpWriter.Rows(width, height, 32, (x, y) => Value(x, y, 32), topDown)),
+ "bitfields32" => TestBmpWriter.File(
+ TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 32, 3),
+ TestBmpWriter.Masks(0x00FF0000, 0x0000FF00, 0x000000FF),
+ TestBmpWriter.Rows(width, height, 32, (x, y) => Value(x, y, 32), topDown)),
+ "alphabitfields32" => TestBmpWriter.File(
+ TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 32, 6),
+ TestBmpWriter.Masks(0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000),
+ TestBmpWriter.Rows(width, height, 32, (x, y) => Value(x, y, 32), topDown)),
+ "rgb555" => TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 16, 0),
+ [], TestBmpWriter.Rows(width, height, 16, (x, y) => Value(x, y, 16) & 0x7FFF, topDown)),
+ "rgb565" => TestBmpWriter.File(
+ TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 16, 3),
+ TestBmpWriter.Masks(0xF800, 0x07E0, 0x001F),
+ TestBmpWriter.Rows(width, height, 16, (x, y) => Value(x, y, 16), topDown)),
+ "bitfields16" => TestBmpWriter.File(
+ TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 16, 3),
+ TestBmpWriter.Masks(0x7C00, 0x03E0, 0x001F),
+ TestBmpWriter.Rows(width, height, 16, (x, y) => Value(x, y, 16) & 0x7FFF, topDown)),
+ "p8" or "p4" or "p2" or "p1" => PaletteFile(width, height, topDown, variant[1] - '0'),
+ "core24" => TestBmpWriter.File(TestBmpWriter.CoreHeader(width, height, 24), [],
+ TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24), topDown)),
+ "core8" => TestBmpWriter.File(TestBmpWriter.CoreHeader(width, height, 8),
+ TestBmpWriter.Palette(Palette(256), entrySize: 3),
+ TestBmpWriter.Rows(width, height, 8, (x, y) => Value(x, y, 8), topDown)),
+ _ => throw new ArgumentOutOfRangeException(nameof(variant)),
+ };
+ var alphaAmbiguous = variant == "rgb32";
+ var core = variant.StartsWith("core", StringComparison.Ordinal); // a core header cannot be top-down
+ return [(Build(topDown: false), false, alphaAmbiguous), (Build(topDown: !core), !core, alphaAmbiguous)];
+ }
+
+ private static byte[] PaletteFile(int width, int height, bool topDown, int bits)
+ {
+ var colors = 1 << bits;
+ return TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, bits, 0),
+ TestBmpWriter.Palette(Palette(colors)),
+ TestBmpWriter.Rows(width, height, bits, (x, y) => Value(x, y, bits), topDown));
+ }
+
+ [Fact]
+ public void Alpha_scan_matches_the_whole_image_decision()
+ {
+ const int width = 33, height = 9;
+ // Fourth byte 0 everywhere: opaque, as a whole-image decode decides.
+ var zero = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, height, 32, 0), [],
+ TestBmpWriter.Rows(width, height, 32, (x, y) => Value(x, y, 24)));
+ // One pixel with alpha: the fourth byte is alpha, kept.
+ var one = (byte[])zero.Clone();
+ var pixelOffset = (int)BinaryPrimitives.ReadUInt32LittleEndian(zero.AsSpan(10));
+ one[pixelOffset + 4 * (height * width - 1) + 3] = 0x40;
+ foreach (var file in new[] { zero, one })
+ {
+ StreamingAssert.RowsEqualDecodeInto(Decoder, file, PixelFormat.Rgba32, expectStreaming: true, feeds: Seekable);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, file, PixelFormat.Rgba32, expectStreaming: false, feeds: Unseekable);
+ }
+ var rows = new byte[width * height * 4];
+ BmpImageDecoder.TryDecodeInto(zero, rows, width * 4, PixelFormat.Rgba32, null, TestContext.Current.CancellationToken).ShouldBeTrue();
+ for (var i = 3; i < rows.Length; i += 4) rows[i].ShouldBe((byte)255, "a zero fourth byte is not alpha");
+ }
+
+ [Fact]
+ public void Last_rows_missing_padding_stream()
+ {
+ const int width = 19, height = 5;
+ var stride = (width * 24 + 31) / 32 * 4;
+ var rows = TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24));
+ // The file stops after the last row's pixels: 1 byte of its 3 padding bytes missing.
+ var shortFile = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, height, 24, 0), [],
+ rows[..^1]);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, shortFile, PixelFormat.Rgba32, expectStreaming: true, feeds: Seekable);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, shortFile, PixelFormat.Rgba32, expectStreaming: false, feeds: Unseekable);
+ var topDown = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, -height, 24, 0), [], rows[..^1]);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, topDown, PixelFormat.Bgr24, expectStreaming: true);
+ stride.ShouldBeGreaterThan(3 * width); // the case is the padding, not the pixels
+ }
+
+ [Fact]
+ public void Unstreamable_variants_fall_back()
+ {
+ const int width = 17, height = 6;
+ var rle = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, height, 8, 1), TestBmpWriter.Palette(Palette(256)),
+ new TestBmpWriter.Rle(width, height, 8, Palette(256)).Run(width * height, 3).Stream);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, rle, PixelFormat.Rgba32, expectStreaming: false);
+
+ var topDown = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, -height, 24, 0), [],
+ TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24), topDown: true));
+
+ // Decode options other than the whole image.
+ var scaled = new DecodeOptions { ScaleDenominator = 2 };
+ StreamingAssert.RowsEqualDecodeInto(Decoder, topDown, PixelFormat.Rgba32, scaled, expectStreaming: false);
+ var region = new DecodeOptions { Region = new PixelRect(0, 0, 8, 4) };
+ StreamingAssert.RowsEqualDecodeInto(Decoder, topDown, PixelFormat.Rgba32, region, expectStreaming: false);
+
+ // Output formats other than the 8-bit basic ones.
+ StreamingAssert.RowsEqualDecodeInto(Decoder, topDown, PixelFormat.Rgba64, expectStreaming: false);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, topDown, PixelFormat.GrayAlpha16, expectStreaming: false);
+
+ // A pixel offset into the headers: the whole-file parser derives the pixels' place from the file's length.
+ var intoHeader = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, -height, 24, 0), [],
+ TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24), topDown: true), offBits: 20);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, intoHeader, PixelFormat.Rgba32, expectStreaming: false);
+
+ // A V5 profile stored after the pixels: what ColorEncoding says depends on it.
+ var v5 = V5Profile(width, height, profileBeforePixels: false);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, v5, PixelFormat.Rgba32, expectStreaming: false);
+
+ // A BI_PNG bitmap.
+ using var image = BmpMagickTests.Source(width, height, 4, false, 3);
+ var png = BmpFromPng(image);
+ StreamingAssert.RowsEqualDecodeInto(Decoder, png, PixelFormat.Rgba32, expectStreaming: false);
+ }
+
+ private static byte[] BmpFromPng(MagickImage image)
+ {
+ var png = image.ToByteArray(MagickFormat.Png32);
+ var header = TestBmpWriter.InfoHeader(40, (int)image.Width, (int)image.Height, 0, 5);
+ return TestBmpWriter.File(header, [], png);
+ }
+
+ private static readonly byte[] Profile = [.. Enumerable.Range(0, 40).Select(i => (byte)(i * 7 + 1))];
+
+ private static byte[] V5Profile(int width, int height, bool profileBeforePixels)
+ {
+ const int headerSize = 124;
+ var rows = TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24), topDown: true);
+ // bV5ProfileData counts from the bitmap header's start; the mask of a V5 header is inside it.
+ var profileOffset = profileBeforePixels ? headerSize : headerSize + rows.Length;
+ var header = TestBmpWriter.InfoHeader(headerSize, width, -height, 24, 0, colorSpace: 0x4D424544,
+ profileOffset: (uint)profileOffset, profileSize: (uint)Profile.Length);
+ return profileBeforePixels
+ ? TestBmpWriter.File(header, Profile, rows)
+ : TestBmpWriter.File(header, [], TestBmpWriter.Concat(rows, Profile));
+ }
+
+ [Fact]
+ public void Profile_before_the_pixels_streams_with_its_colour()
+ {
+ var file = V5Profile(21, 13, profileBeforePixels: true);
+ var rows = StreamingAssert.RowsEqualDecodeInto(Decoder, file, PixelFormat.Rgba32, expectStreaming: true, feeds: Seekable);
+ rows.Length.ShouldBe(21 * 13 * 4);
+ BmpImageDecoder.TryReadMetadata(file, out var metadata).ShouldBeTrue();
+ metadata!.Icc.ToArray().ShouldBe(Profile);
+ }
+
+ [Fact]
+ public void Truncated_pixels_throw_invalid_data()
+ {
+ const int width = 41, height = 11;
+ foreach (var topDown in new[] { false, true })
+ {
+ var file = TestBmpWriter.File(TestBmpWriter.InfoHeader(40, width, topDown ? -height : height, 24, 0), [],
+ TestBmpWriter.Rows(width, height, 24, (x, y) => Value(x, y, 24), topDown));
+ foreach (var cut in new[] { file.Length - 3 * width * height / 2, file.Length - 2, file.Length - 2 * width * 3 })
+ {
+ if (cut <= 54) continue;
+ var truncated = file[..cut];
+ foreach (var feed in StreamingAssert.AllFeeds)
+ {
+ Stream stream = feed == StreamingAssert.Feed.Whole
+ ? new MemoryStream(truncated, writable: false) as Stream
+ : new ChunkedStream(truncated, maxChunk: feed == StreamingAssert.Feed.OneByte ? 1 : 4096,
+ asyncOnly: feed == StreamingAssert.Feed.AsyncOnly);
+ using var input = new StreamInput(stream, initialCapacity: 16);
+ using var reader = Decoder.CreateRowReader!(input, PixelFormat.Rgba32, null);
+ var because = $"topDown {topDown}, cut at {cut} of {file.Length}, {feed}";
+ if (feed == StreamingAssert.Feed.AsyncOnly)
+ Should.Throw(() => DrainAsync(reader).GetAwaiter().GetResult(), because);
+ else
+ Should.Throw(() => Drain(reader), because);
+ }
+ }
+ }
+ }
+
+ private static async Task DrainAsync(StreamingRowReader reader)
+ {
+ await reader.InitializeAsync(TestContext.Current.CancellationToken);
+ var row = new byte[reader.Width * reader.Format.BytesPerPixel];
+ while (reader.RowsRead < reader.Height)
+ await reader.ReadRowsAsync(row, 1, 0, TestContext.Current.CancellationToken);
+ }
+
+ private static void Drain(StreamingRowReader reader)
+ {
+ reader.Initialize(TestContext.Current.CancellationToken);
+ var row = new byte[reader.Width * reader.Format.BytesPerPixel];
+ while (reader.RowsRead < reader.Height)
+ reader.ReadRows(row, 1, 0, TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ public void Decode_streams_bounded_memory()
+ {
+ const int width = 8192, height = 4096;
+ var file = TopDown(width, height, 24);
+ StreamingAssert.AllocatesLessThan(8 * 1024 * 1024, () =>
+ {
+ using var input = new StreamInput(new ChunkedStream(file, maxChunk: 4001, seed: 5), initialCapacity: 64 * 1024);
+ using var reader = (StreamingRowReader)Decoder.CreateRowReader!(input, PixelFormat.Bgra32, null);
+ reader.Initialize(TestContext.Current.CancellationToken);
+ reader.IsStreaming.ShouldBeTrue();
+ reader.ReadRows(new byte[width * 4], 1, 0, TestContext.Current.CancellationToken);
+ }, "streaming a 8192x4096 bitmap");
+ }
+
+ private static byte[] TopDown(int width, int height, int bits)
+ {
+ var stride = (int)(((long)width * bits + 31) / 32 * 4);
+ var file = new byte[54 + (long)stride * height];
+ TestBmpWriter.InfoHeader(40, width, -height, bits, 0).CopyTo(file, 14);
+ file[0] = (byte)'B';
+ file[1] = (byte)'M';
+ BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(2), (uint)file.Length);
+ BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(10), 54);
+ for (var i = 54; i < file.Length; i++) file[i] = (byte)(i * 31 + (i >> 8));
+ return file;
+ }
+
+ // ---- Encoder -----------------------------------------------------------------------------------------------
+
+ private static IImageEncoderSession CreateSession(IBufferWriter output, EncodeOptions? options) =>
+ BmpImageEncoder.Create(output, options);
+
+ public static TheoryData EncodeLayouts() => ["rgb24", "rgb32", "argb32", "rgb565", "rgb555", "argb32-v5"];
+
+ [Theory]
+ [MemberData(nameof(EncodeLayouts))]
+ public void Encoder_streams_the_buffered_bytes(string layout)
+ {
+ const int width = 43, height = 17;
+ var options = layout switch
+ {
+ "rgb24" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb24, TopDown = true },
+ "rgb32" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb32, TopDown = true },
+ "argb32" => new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32, TopDown = true },
+ "rgb565" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb565, TopDown = true },
+ "rgb555" => new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb555, TopDown = true, Header = BmpHeaderVersion.V5 },
+ _ => new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32, TopDown = true, IccProfile = Profile },
+ };
+ foreach (var format in AllFormats)
+ {
+ var pixels = RandomPixels(width, height, format, layout.Length);
+ var streamed = StreamingAssert.EncoderEmitsBeforeCommit(o => CreateSession(o, options), pixels, width, height, format);
+ // What the buffered session writes: the whole image, converted to the 8-bit layout BMP takes, encoded.
+ var native = BmpImageEncoder.GetClosestInputFormat(format);
+ var whole = native == format ? pixels : PixelConverter.ToPacked(pixels, 0, format, native, width, height);
+ var buffered = BmpEncoder.Encode(whole, width, height, native, options);
+ streamed.ShouldBe(buffered, $"streamed {layout} from {format}");
+ // The same bytes written in random bands with padded strides.
+ ChunkedEncode(pixels, width, height, format, options, layout.Length).ShouldBe(buffered, $"banded {layout} from {format}");
+ InfoDecodes(streamed, width, height, layout);
+ }
+ }
+
+ private static byte[] ChunkedEncode(byte[] pixels, int width, int height, PixelFormat format, BmpEncodeOptions options, int seed)
+ {
+ var output = new ArrayBufferWriter(16);
+ using var session = BmpImageEncoder.Create(output, options);
+ session.IsStreaming.ShouldBeTrue();
+ var frame = session.AddFrame(width, height, format);
+ var random = new Random(seed);
+ var rowBytes = width * format.BytesPerPixel;
+ for (var y = 0; y < height;)
+ {
+ var n = Math.Min(height - y, random.Next(1, 6));
+ var stride = rowBytes + random.Next(0, 9);
+ var band = new byte[stride * n];
+ for (var i = 0; i < n; i++) pixels.AsSpan((y + i) * rowBytes, rowBytes).CopyTo(band.AsSpan(i * stride));
+ frame.WriteRows(band, n, stride, TestContext.Current.CancellationToken);
+ y += n;
+ }
+ session.Commit(TestContext.Current.CancellationToken);
+ return output.WrittenSpan.ToArray();
+ }
+
+ private static void InfoDecodes(byte[] file, int width, int height, string layout)
+ {
+ BmpImageDecoder.TryReadInfo(file, out var info).ShouldBeTrue(layout);
+ (info.Width, info.Height).ShouldBe((width, height), layout);
+ var back = new byte[width * height * 4];
+ BmpImageDecoder.TryDecodeInto(file, back, width * 4, PixelFormat.Rgba32).ShouldBeTrue(layout);
+ }
+
+ private static byte[] RandomPixels(int width, int height, PixelFormat format, int seed)
+ {
+ var pixels = new byte[width * height * format.BytesPerPixel];
+ new Random(seed).NextBytes(pixels);
+ return pixels;
+ }
+
+ [Fact]
+ public void Encoder_does_not_stream_what_it_cannot()
+ {
+ foreach (var options in new EncodeOptions[]
+ {
+ new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb24 },
+ new BmpEncodeOptions { Format = BmpEncodeFormat.Auto, TopDown = true },
+ new BmpEncodeOptions { Format = BmpEncodeFormat.Indexed8, TopDown = true },
+ new BmpEncodeOptions { Format = BmpEncodeFormat.Indexed8, Rle = true },
+ })
+ {
+ using var session = BmpImageEncoder.Create(new ArrayBufferWriter(), options);
+ session.IsStreaming.ShouldBeFalse(options.ToString());
+ }
+ foreach (var options in new EncodeOptions[]
+ {
+ new BmpEncodeOptions { Format = BmpEncodeFormat.Rgb24, TopDown = true },
+ new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32, TopDown = true },
+ })
+ {
+ using var session = BmpImageEncoder.Create(new ArrayBufferWriter(), options);
+ session.IsStreaming.ShouldBeTrue(options.ToString());
+ }
+ }
+
+ [Fact]
+ public void Encoder_writes_bounded_memory()
+ {
+ const int width = 8192, height = 4096;
+ var pixels = new byte[width * height * 4];
+ var options = new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32, TopDown = true };
+ var sink = new CountingWriter();
+ StreamingAssert.AllocatesLessThan(4 * 1024 * 1024, () =>
+ {
+ sink.Reset();
+ using var session = BmpImageEncoder.Create(sink, options);
+ session.IsStreaming.ShouldBeTrue();
+ var frame = session.AddFrame(width, height, PixelFormat.Rgba32);
+ frame.WriteRows(pixels, height, 0, TestContext.Current.CancellationToken);
+ session.Commit(TestContext.Current.CancellationToken);
+ }, "streaming a 8192x4096 bitmap");
+ sink.Count.ShouldBe(14 + 108 + 8192 * 4 * 4096); // a V4 header for alpha
+ }
+
+ /// An output that keeps only the count, so a streaming write allocates nothing new.
+ private sealed class CountingWriter : IBufferWriter
+ {
+ private byte[] _buffer = new byte[64 * 1024];
+
+ public long Count { get; private set; }
+
+ public void Reset() => Count = 0;
+
+ public void Advance(int count) => Count += count;
+
+ public Memory GetMemory(int sizeHint = 0)
+ {
+ if (_buffer.Length < sizeHint) _buffer = new byte[sizeHint];
+ return _buffer;
+ }
+
+ public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span;
+ }
+
+ // ---- End to end --------------------------------------------------------------------------------------------
+
+ [Fact]
+ public void Magick_bottom_up_file_streams_from_a_file_and_falls_back_from_a_body()
+ {
+ using var image = BmpMagickTests.Source(64, 40, 500, false, 11);
+ var file = image.ToByteArray(MagickFormat.Bmp3);
+ BmpDecoder.ReadInfo(file).TopDown.ShouldBeFalse();
+ var name = Path.Combine(Path.GetTempPath(), $"bmp-stream-{Environment.ProcessId}.bmp");
+ try
+ {
+ File.WriteAllBytes(name, file);
+ using var actual = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true);
+ using var reader = Decoder.CreateRowReader!(new StreamInput(actual), PixelFormat.Rgba32, null);
+ reader.Initialize(TestContext.Current.CancellationToken);
+ reader.IsStreaming.ShouldBeTrue();
+ var rows = new byte[64 * 40 * 4];
+ while (reader.RowsRead < reader.Height)
+ reader.ReadRows(rows.AsSpan(reader.RowsRead * 64 * 4), reader.Height - reader.RowsRead, 0,
+ TestContext.Current.CancellationToken);
+ var expected = new byte[rows.Length];
+ BmpImageDecoder.TryDecodeInto(file, expected, 64 * 4, PixelFormat.Rgba32, null, TestContext.Current.CancellationToken).ShouldBeTrue();
+ rows.ShouldBe(expected);
+ }
+ finally
+ {
+ File.Delete(name);
+ }
+ StreamingAssert.RowsEqualDecodeInto(Decoder, file, PixelFormat.Rgba32, expectStreaming: false, feeds: Unseekable);
+ }
+
+ [Fact]
+ public void Top_down_file_round_trips_through_the_streaming_encoder()
+ {
+ const int width = 61, height = 23;
+ var pixels = RandomPixels(width, height, PixelFormat.Bgra32, 9);
+ var options = new BmpEncodeOptions { Format = BmpEncodeFormat.Argb32, TopDown = true };
+ var encoded = StreamingAssert.EncoderEmitsBeforeCommit(o => BmpImageEncoder.Create(o, options), pixels, width, height, PixelFormat.Bgra32);
+ BmpDecoder.ReadInfo(encoded).TopDown.ShouldBeTrue();
+ var name = Path.Combine(Path.GetTempPath(), $"bmp-rt-{Environment.ProcessId}.bmp");
+ try
+ {
+ File.WriteAllBytes(name, encoded);
+ using var file = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true);
+ using var reader = Decoder.CreateRowReader!(new StreamInput(file), PixelFormat.Bgra32, null);
+ reader.Initialize(TestContext.Current.CancellationToken);
+ reader.IsStreaming.ShouldBeTrue();
+ var rows = new byte[pixels.Length];
+ while (reader.RowsRead < reader.Height)
+ reader.ReadRows(rows.AsSpan(reader.RowsRead * width * 4), reader.Height - reader.RowsRead, 0,
+ TestContext.Current.CancellationToken);
+ rows.ShouldBe(pixels);
+ }
+ finally
+ {
+ File.Delete(name);
+ }
+ }
+
+ /// Mutations of seed bitmaps, fed every way: BMP_STREAM_FUZZ_ITERATIONS (default 600; soak at 300000).
+ private static int FuzzIterations =>
+ int.TryParse(Environment.GetEnvironmentVariable("BMP_STREAM_FUZZ_ITERATIONS"), out var n) ? n : 600;
+
+ [Fact]
+ public void Bottom_up_bands_from_a_seekable_stream()
+ {
+ // Several bands (BmpRowReader.BandBytes each), a band boundary inside a row band the caller asks for, and short
+ // reads, so that seeking back meets a part-filled buffer.
+ foreach (var (width, height, bits) in new[] { (1000, 300, 24), (700, 211, 32), (3001, 97, 8), (90000, 5, 24) })
+ {
+ var rows = TestBmpWriter.Rows(width, height, bits, (x, y) => Value(x, y, bits));
+ var header = TestBmpWriter.InfoHeader(40, width, height, bits, 0);
+ var file = bits == 8
+ ? TestBmpWriter.File(header, TestBmpWriter.Palette(Palette(256)), rows)
+ : TestBmpWriter.File(header, [], rows);
+ foreach (var format in Formats)
+ {
+ var expected = StreamingAssert.RowsEqualDecodeInto(Decoder, file, format, expectStreaming: true, feeds: Seekable);
+ foreach (var seed in new[] { 1, 2 })
+ {
+ var actual = StreamingAssert.ReadAll(file, StreamingAssert.Feed.RandomChunks,
+ input => Decoder.CreateRowReader!(new StreamInput(new SeekableChunkedStream(file, 70000, seed), initialCapacity: 16), format, null),
+ out var streaming, out _, out _, seed);
+ streaming.ShouldBeTrue();
+ actual.AsSpan().SequenceEqual(expected).ShouldBeTrue($"{width}x{height}x{bits} to {format}, seed {seed}");
+ }
+ }
+ }
+ }
+
+ [Fact]
+ public void Bottom_up_streams_bounded_memory()
+ {
+ const int width = 8192, height = 4096;
+ var file = TopDown(width, height, 32);
+ // Bottom-up, 32-bit BI_RGB to RGBA: the forward pass also scans the alpha bytes.
+ BinaryPrimitives.WriteInt32LittleEndian(file.AsSpan(22), height);
+ StreamingAssert.AllocatesLessThan(8 * 1024 * 1024, () =>
+ {
+ using var input = new StreamInput(new MemoryStream(file, writable: false));
+ using var reader = Decoder.CreateRowReader!(input, PixelFormat.Rgba32, null);
+ reader.Initialize(TestContext.Current.CancellationToken);
+ reader.IsStreaming.ShouldBeTrue();
+ var band = new byte[width * 4 * 16];
+ while (reader.RowsRead < reader.Height)
+ reader.ReadRows(band, 16, 0, TestContext.Current.CancellationToken);
+ }, "streaming a bottom-up 8192x4096 bitmap");
+ }
+
+ [Fact]
+ public void Retained_input_streams_bottom_up_without_seeking()
+ {
+ // An input that keeps every byte read can go back without seeking: no output frame is buffered.
+ var (file, _, _) = Files("rgb32")[0];
+ var expected = new byte[37 * 21 * 4];
+ BmpImageDecoder.TryDecodeInto(file, expected, 0, PixelFormat.Rgba32, null, TestContext.Current.CancellationToken).ShouldBeTrue();
+ foreach (var feed in new[] { StreamingAssert.Feed.OneByte, StreamingAssert.Feed.RandomChunks })
+ {
+ var rows = StreamingAssert.ReadAll(file, feed,
+ input => Decoder.CreateRowReader!(new StreamInput(new ChunkedStream(file, feed == StreamingAssert.Feed.OneByte ? 1 : 300),
+ retainConsumed: true, initialCapacity: 16), PixelFormat.Rgba32, null), out var streaming, out _, out _);
+ streaming.ShouldBeTrue(feed.ToString());
+ rows.ShouldBe(expected, feed.ToString());
+ }
+ }
+
+ [Fact]
+ public void Alpha_or_matches_a_byte_at_a_time()
+ {
+ var random = new Random(77);
+ for (var i = 0; i < 2000; i++)
+ {
+ var bytes = new byte[random.Next(0, 300)];
+ if (random.Next(3) > 0)
+ {
+ // Mostly zero fourth bytes, with now and then one set, so that a missed byte shows.
+ random.NextBytes(bytes);
+ var offset0 = random.Next(4);
+ for (var k = (3 - offset0 + 4) % 4; k < bytes.Length; k += 4) bytes[k] = 0;
+ if (bytes.Length > 0 && random.Next(2) == 0) bytes[random.Next(bytes.Length)] = (byte)random.Next(1, 256);
+ Check(bytes, offset0 + 4L * random.Next(1000));
+ }
+ else
+ {
+ random.NextBytes(bytes);
+ Check(bytes, random.Next(1 << 20));
+ }
+ }
+
+ static void Check(byte[] bytes, long offset)
+ {
+ uint expected = 0;
+ for (var k = 0; k < bytes.Length; k++)
+ if (((offset + k) & 3) == 3) expected |= bytes[k];
+ BmpRowReader.AlphaOr(bytes, offset).ShouldBe(expected, $"{bytes.Length} bytes at {offset}");
+ }
+ }
+
+ /// A seekable stream that returns 1..maxChunk bytes per read.
+ private sealed class SeekableChunkedStream(byte[] data, int maxChunk, int seed) : MemoryStream(data, writable: false)
+ {
+ private readonly Random _random = new(seed);
+
+ public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, _random.Next(1, maxChunk + 1)));
+
+ public override int Read(Span buffer) => base.Read(buffer[..Math.Min(buffer.Length, _random.Next(1, maxChunk + 1))]);
+
+ public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) =>
+ base.ReadAsync(buffer[..Math.Min(buffer.Length, _random.Next(1, maxChunk + 1))], cancellationToken);
+ }
+
+ [Fact]
+ public void Nothing_but_invalid_data_from_malformed_streams()
+ {
+ var seeds = new List();
+ foreach (var variant in new[] { "rgb24", "p8", "rgb32", "alphabitfields32" })
+ {
+ var (file, _, _) = Files(variant)[0];
+ seeds.Add(file);
+ seeds.Add(Files(variant)[1].File);
+ }
+ seeds.Add(V5Profile(9, 5, profileBeforePixels: true));
+ var random = new Random(20261123);
+ for (var i = 0; i < FuzzIterations; i++)
+ {
+ var file = (byte[])seeds[random.Next(seeds.Count)].Clone();
+ var edits = random.Next(1, 6);
+ for (var e = 0; e < edits && file.Length > 0; e++)
+ file[random.Next(file.Length)] = (byte)random.Next(256);
+ if (random.Next(4) == 0 && file.Length > 60)
+ file = file[..random.Next(40, file.Length)];
+ var feed = random.Next(4);
+ CheckStreaming(file, feed);
+ }
+ }
+
+ private static void CheckStreaming(byte[] file, int feed)
+ {
+ var format = feed == 2 ? PixelFormat.Bgra32 : PixelFormat.Rgba32;
+ Stream stream = feed switch
+ {
+ 0 => new ChunkedStream(file, maxChunk: 1 + (file.Length % 97), seed: 3),
+ 1 => new MemoryStream(file, writable: false),
+ 3 => new SeekableChunkedStream(file, maxChunk: 1 + (file.Length % 61), seed: 5),
+ _ => new ChunkedStream(file, maxChunk: 4096, seed: 4, asyncOnly: true),
+ };
+ var expected = new byte[(long)4 * 1 << 16];
+ var decoded = BmpImageDecoder.TryReadInfo(file, out var info)
+ && PixelConverter.TryGetLayout(info.Width, info.Height, format, 0, expected.Length, out var stride)
+ && BmpImageDecoder.TryDecodeInto(file, expected, stride, format, null, default);
+ try
+ {
+ using var input = new StreamInput(stream, initialCapacity: 16);
+ using var reader = BmpImageDecoder.CreateRowReader(input, format, null);
+ var ct = TestContext.Current.CancellationToken;
+ if (feed == 2) reader.InitializeAsync(ct).AsTask().GetAwaiter().GetResult();
+ else reader.Initialize(ct);
+ var rowBytes = reader.Width * format.BytesPerPixel;
+ var rows = ArrayPool.Shared.Rent(rowBytes * reader.Height);
+ try
+ {
+ while (reader.RowsRead < reader.Height)
+ {
+ var at = reader.RowsRead * rowBytes;
+ var n = Math.Min(7, reader.Height - reader.RowsRead);
+ if (feed == 2) reader.ReadRowsAsync(rows.AsMemory(at), n, 0, ct).AsTask().GetAwaiter().GetResult();
+ else reader.ReadRows(rows.AsSpan(at), n, 0, ct);
+ }
+ decoded.ShouldBeTrue("streaming decoded what TryDecodeInto refused");
+ rows.AsSpan(0, rowBytes * reader.Height).SequenceEqual(expected.AsSpan(0, rowBytes * reader.Height)).ShouldBeTrue(
+ "the mutated file streamed to different rows");
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(rows);
+ }
+ }
+ catch (InvalidDataException)
+ {
+ }
+ }
+}