Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Baseline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ private sealed class Bound

public static bool CanEncode(bool qoi) => IsBuilt && (qoi ? Loaded.Value.QoiEncode : Loaded.Value.PnmEncode) != IntPtr.Zero;

/// <summary>The baseline's <c>QoiImageDecoder</c> / <c>PnmImageDecoder.TryDecodeInto</c>, to RGBA.</summary>
/// <summary>The baseline's <c>QoiImageDecoder</c> / <c>PnmImageDecoder.TryDecodeInto</c> (the 2.0 six-parameter form), to RGBA.</summary>
public static bool TryDecodeInto(bool qoi, ReadOnlySpan<byte> data, Span<byte> rgba) =>
((delegate*<ReadOnlySpan<byte>, Span<byte>, int, PixelFormat, bool>)(qoi ? Loaded.Value.QoiDecodeInto : Loaded.Value.PnmDecodeInto))(
data, rgba, 0, PixelFormat.Rgba32);
((delegate*<ReadOnlySpan<byte>, Span<byte>, int, PixelFormat, DecodeOptions?, CancellationToken, bool>)(qoi ? Loaded.Value.QoiDecodeInto : Loaded.Value.PnmDecodeInto))(
data, rgba, 0, PixelFormat.Rgba32, null, default);

/// <summary>The baseline's <c>QoiEncoder.Encode(pixels, width, height, format, Srgb, 0)</c>.</summary>
public static byte[] EncodeQoi(byte[] pixels, int width, int height, PixelFormat format) =>
Expand Down Expand Up @@ -72,15 +72,15 @@ private static Bound Load()
if (File.Exists(Path.Combine(dir, "Sdcb.SimdCodecs.Qoi.dll")))
{
var qoi = alc.LoadFromAssemblyName(new AssemblyName("Sdcb.SimdCodecs.Qoi"));
bound.QoiDecodeInto = Pointer(qoi.GetType("Sdcb.SimdCodecs.Qoi.QoiImageDecoder"), "TryDecodeInto", 4);
bound.QoiDecodeInto = Pointer(qoi.GetType("Sdcb.SimdCodecs.Qoi.QoiImageDecoder"), "TryDecodeInto", 6);
bound.QoiEncode = qoi.GetType("Sdcb.SimdCodecs.Qoi.QoiEncoder")?.GetMethods(BindingFlags.Public | BindingFlags.Static).SingleOrDefault(m =>
m.Name == "Encode" && m.GetParameters() is { Length: 6 } p && p[4].ParameterType.Name == "QoiColorSpace")
?.MethodHandle.GetFunctionPointer() ?? IntPtr.Zero;
}
if (File.Exists(Path.Combine(dir, "Sdcb.SimdCodecs.Pnm.dll")))
{
var pnm = alc.LoadFromAssemblyName(new AssemblyName("Sdcb.SimdCodecs.Pnm"));
bound.PnmDecodeInto = Pointer(pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmImageDecoder"), "TryDecodeInto", 4);
bound.PnmDecodeInto = Pointer(pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmImageDecoder"), "TryDecodeInto", 6);
bound.PnmOptionsType = pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmEncodeOptions");
bound.PnmEncode = pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmEncoder")?.GetMethods(BindingFlags.Public | BindingFlags.Static).SingleOrDefault(m =>
m.Name == "Encode" && m.GetParameters() is { Length: 6 } p && p[3].ParameterType.Name == nameof(PixelFormat) && p[4].ParameterType.Name == "PnmEncodeOptions")
Expand Down
51 changes: 46 additions & 5 deletions benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.Buffers;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Sdcb.SimdCodecs.Abstractions;
using Sdcb.SimdCodecs.Abstractions.CodecSupport;
using Sdcb.SimdCodecs.Png.Benchmarks;
using Sdcb.SimdCodecs.Pnm;
using Sdcb.SimdCodecs.Qoi;
Expand Down Expand Up @@ -167,6 +169,22 @@ public static Setup Decode(Case c)
}
setup.Contestants.Add(new(Names.Current, () => Ours(rgba)));

if (c.Qoi)
{
// The streaming reader over a stream of the file, 16 rows a call, into the same kind of buffer.
var streamed = new byte[rgba.Length];
void Stream()
{
using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(data, writable: false)), PixelFormat.Rgba32, null);
reader.Initialize();
while (reader.RowsRead < reader.Height)
reader.ReadRows(streamed.AsSpan(reader.RowsRead * w * 4), 16);
}
Stream();
if (!streamed.AsSpan().SequenceEqual(rgba)) throw new InvalidOperationException($"{c.Name}: the streaming reader differs from current");
setup.Contestants.Add(new(Names.Streaming, Stream));
}

if (Baseline.CanDecode(c.Qoi))
{
var other = new byte[rgba.Length];
Expand Down Expand Up @@ -233,6 +251,29 @@ void Check(string name, byte[] output)
toStream();
}));

if (c.Qoi)
{
// The streaming session, 16 rows a band, into a reused writer.
var writer = new ArrayBufferWriter<byte>(ours.Length + 64);
var rowBytes = w * format.BytesPerPixel;
void Session()
{
writer.ResetWrittenCount();
using var session = QoiImageEncoder.Create(writer);
var frame = session.AddFrame(w, h, format);
for (var y = 0; y < h; y += 16)
{
var n = Math.Min(16, h - y);
frame.WriteRows(pixels.AsSpan(y * rowBytes, n * rowBytes), n);
}
session.Commit();
}
Session();
if (!writer.WrittenSpan.SequenceEqual(ours)) throw new InvalidOperationException($"{c.Name}: the streaming session's bytes differ from current");
setup.Sizes[Names.Streaming] = writer.WrittenCount;
setup.Contestants.Add(new(Names.Streaming, Session));
}

if (c.Format is not ("pfm" or "ppm16") && Baseline.CanEncode(c.Qoi))
{
Func<byte[]> baseline;
Expand Down Expand Up @@ -295,17 +336,17 @@ public static string Run(bool decode, int rounds)
}

var names = decode
? new[] { Names.Current, Names.Baseline, Names.ImageSharp }
: [Names.Current, Names.CurrentStream, Names.Baseline, Names.ImageSharp];
? new[] { Names.Current, Names.Streaming, Names.Baseline, Names.ImageSharp }
: [Names.Current, Names.CurrentStream, Names.Streaming, Names.Baseline, Names.ImageSharp];
var compare = decode ? Names.Current : Names.CurrentStream;
var sb = new StringBuilder();
sb.AppendLine($"### {(decode ? "Decode" : "Encode")} (in-process medians of {rounds} interleaved rounds, ms)");
sb.AppendLine();
sb.AppendLine(decode
? "`current` = `QoiImageDecoder` / `PnmImageDecoder.TryDecodeInto` to RGBA in a caller buffer (PFM: `PnmDecoder.Decode` to " +
"floats); ImageSharp = `Image.Load<Rgba32>` + `CopyPixelDataTo`, one thread. Every timed output was checked against ours first."
"floats); `streaming` = QOI's `CreateRowReader` over a `MemoryStream`, 16 rows a call; ImageSharp = `Image.Load<Rgba32>` + `CopyPixelDataTo`, one thread. Every timed output was checked against ours first."
: "`current` = `QoiEncoder` / `PnmEncoder.Encode` to a new array; `current → stream` = the `Stream` overload into a reused " +
"stream, as ImageSharp writes; ImageSharp = its encoder from an image built beforehand into a reused stream, one thread. " +
"stream, as ImageSharp writes; `streaming` = QOI's streaming session in 16-row bands into a reused writer; ImageSharp = its encoder from an image built beforehand into a reused stream, one thread. " +
"Every output decodes to the input.");
sb.AppendLine();
sb.AppendLine("| Case | KB | " + string.Join(" | ", names.Select(Names.Label)) + $" | {Names.Label(compare)} ÷ ImageSharp | ÷ baseline |");
Expand All @@ -319,7 +360,7 @@ public static string Run(bool decode, int rounds)
notes.AddRange(s.Notes.Select(n => $"`{s.Case.Name}`: {n}"));
}
sb.AppendLine();
foreach (var (a, b) in new[] { (compare, Names.ImageSharp), (compare, Names.Baseline) })
foreach (var (a, b) in new[] { (compare, Names.ImageSharp), (compare, Names.Baseline), (Names.Streaming, Names.Current) })
{
foreach (var codec in new[] { "qoi", "pnm" })
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,15 @@ internal static class Names
{
public const string Current = "Current";
public const string CurrentStream = "CurrentStream";
public const string Streaming = "Streaming";
public const string Baseline = "Baseline";
public const string ImageSharp = "ImageSharp";

public static string Label(string name) => name switch
{
Current => "current",
CurrentStream => "current → stream",
Streaming => "streaming",
Baseline => "baseline",
_ => name,
};
Expand Down
1 change: 1 addition & 0 deletions src/Sdcb.SimdCodecs.Qoi/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static Sdcb.SimdCodecs.Qoi.QoiImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader!
48 changes: 45 additions & 3 deletions src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,37 @@ public Reader(bool opaque)
_px = 0xFF000000u;
}

/// <summary>
/// The offset in the data of the next chunk: <see cref="HeaderSize"/> for a whole file; a streaming decoder
/// that hands the reader a window of the file sets it to the window's first unread byte.
/// </summary>
public int Position
{
readonly get => _position;
set => _position = value;
}

/// <summary>Decodes the next <c>pixels.Length</c> pixels.</summary>
/// <exception cref="InvalidDataException">The chunks end first.</exception>
public void Read(ReadOnlySpan<byte> data, Span<uint> pixels) => Read<ThrowAtEnd>(data, pixels);

/// <summary>
/// Decodes the next <c>pixels.Length</c> pixels; false when the chunks end first (a chunk would run past the
/// data). Every byte is a valid chunk opcode, so running out is the only way to fail. After false the state is
/// partly advanced: a caller that retries with more data restores a copy taken before the call.
/// </summary>
public bool TryRead(ReadOnlySpan<byte> data, Span<uint> pixels)
{
Read<ReturnAtEnd>(data, pixels);
return _position >= 0;
}

// One loop, two instantiations over a struct marker; the typeof test is a constant in each (also under Mono AOT).
// The throwing one is the loop as it was before streaming: its end checks are cold throw blocks and it returns
// nothing. (A shared loop returning bool cost the whole-image decode 4-8%, measured.) The other marks running
// out with a position of -1: the state is discarded after a failed read anyway.
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public void Read(ReadOnlySpan<byte> data, Span<uint> pixels)
private void Read<TEnd>(ReadOnlySpan<byte> data, Span<uint> pixels) where TEnd : struct
{
var n = pixels.Length;
var i = 0;
Expand Down Expand Up @@ -122,7 +149,12 @@ public void Read(ReadOnlySpan<byte> data, Span<uint> pixels)
{
var remaining = tailBase < 0 ? data.Length - p : 0;
if (remaining <= 0)
throw new InvalidDataException("QOI data ends before the last pixel.");
{
if (typeof(TEnd) == typeof(ThrowAtEnd))
throw new InvalidDataException("QOI data ends before the last pixel.");
_position = -1;
return;
}
tail.Clear();
data[p..].CopyTo(tail);
tailBase = p;
Expand Down Expand Up @@ -189,7 +221,12 @@ public void Read(ReadOnlySpan<byte> data, Span<uint> pixels)
if (tailBase >= 0)
{
if (p > limit + 1)
throw new InvalidDataException("QOI data ends inside the last chunk.");
{
if (typeof(TEnd) == typeof(ThrowAtEnd))
throw new InvalidDataException("QOI data ends inside the last chunk.");
_position = -1;
return;
}
p += tailBase;
}
_position = p;
Expand Down Expand Up @@ -219,6 +256,11 @@ private static uint SubBytes(uint a, uint b)
}
}

/// <summary>Markers for what <see cref="Reader"/> does when the chunks end before the pixels asked for.</summary>
internal struct ThrowAtEnd;

internal struct ReturnAtEnd;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ReadUInt32(ref byte source)
{
Expand Down
67 changes: 40 additions & 27 deletions src/Sdcb.SimdCodecs.Qoi/QoiDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,41 +64,54 @@ internal static void Decode(ReadOnlySpan<byte> data, QoiInfo info, Span<byte> de
{
var reader = new QoiCodec.Reader(info.Channels == 3);
int width = info.Width, height = info.Height;
if (format == PixelFormat.Rgba32 || format == PixelFormat.Bgra32)
if (format == PixelFormat.Rgba32 && rowStride == width * 4 && !cancellationToken.CanBeCanceled)
{
// RGBA pixels land in place; BGRA swaps them where they are.
var rowBytes = width * 4;
if (rowStride == rowBytes && format == PixelFormat.Rgba32 && !cancellationToken.CanBeCanceled)
{
reader.Read(data, MemoryMarshal.Cast<byte, uint>(destination[..(rowBytes * height)]));
return;
}
for (var y = 0; y < height; y++)
{
if ((y & 63) == 0)
cancellationToken.ThrowIfCancellationRequested();
var row = destination.Slice(y * rowStride, rowBytes);
reader.Read(data, MemoryMarshal.Cast<byte, uint>(row));
if (format == PixelFormat.Bgra32)
PixelConverter.ConvertRow(row, PixelFormat.Rgba32, row, PixelFormat.Bgra32, width);
}
// RGBA pixels land in place, the whole image in one call.
reader.Read(data, MemoryMarshal.Cast<byte, uint>(destination[..(width * 4 * height)]));
return;
}

const int Chunk = 512;
Span<uint> chunk = stackalloc uint[Chunk];
var bpp = format.BytesPerPixel;
Span<uint> chunk = stackalloc uint[RowChunk];
var rowBytes = width * format.BytesPerPixel;
for (var y = 0; y < height; y++)
{
if ((y & 63) == 0)
cancellationToken.ThrowIfCancellationRequested();
var row = destination.Slice(y * rowStride, width * bpp);
for (var x = 0; x < width; x += Chunk)
{
var n = Math.Min(Chunk, width - x);
reader.Read(data, chunk[..n]);
PixelConverter.ConvertRow(MemoryMarshal.AsBytes(chunk[..n]), PixelFormat.Rgba32, row[(x * bpp)..], format, n);
}
if (!TryDecodeRow(ref reader, data, destination.Slice(y * rowStride, rowBytes), width, format, chunk))
throw new InvalidDataException("QOI data ends before the last pixel.");
}
}

/// <summary>The pixels <see cref="TryDecodeRow"/> converts at a time when the format is not RGBA or BGRA.</summary>
internal const int RowChunk = 512;

/// <summary>
/// Decodes the next row into <paramref name="row"/> (<c>width × format.BytesPerPixel</c> bytes) as
/// <paramref name="format"/>: the one row step of both the span decoder and the streaming reader, so their rows
/// are the same bytes. False when <paramref name="data"/> ends first; the reader is then partly advanced.
/// </summary>
/// <param name="chunk">Scratch of <see cref="RowChunk"/> pixels.</param>
internal static bool TryDecodeRow(ref QoiCodec.Reader reader, ReadOnlySpan<byte> data, Span<byte> row, int width,
PixelFormat format, Span<uint> chunk)
{
if (format == PixelFormat.Rgba32 || format == PixelFormat.Bgra32)
{
// RGBA pixels land in place; BGRA swaps them where they are.
if (!reader.TryRead(data, MemoryMarshal.Cast<byte, uint>(row)))
return false;
if (format == PixelFormat.Bgra32)
PixelConverter.ConvertRow(row, PixelFormat.Rgba32, row, PixelFormat.Bgra32, width);
return true;
}

var bpp = format.BytesPerPixel;
for (var x = 0; x < width; x += RowChunk)
{
var n = Math.Min(RowChunk, width - x);
if (!reader.TryRead(data, chunk[..n]))
return false;
PixelConverter.ConvertRow(MemoryMarshal.AsBytes(chunk[..n]), PixelFormat.Rgba32, row[(x * bpp)..], format, n);
}
return true;
}
}
Loading