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
42 changes: 40 additions & 2 deletions benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
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 @@ -166,6 +167,19 @@ public static Setup Decode(Case c)
if (!rgba.AsSpan().SequenceEqual(expected)) throw new InvalidOperationException($"{c.Name}: current does not give the source back");
}
setup.Contestants.Add(new(Names.Current, () => Ours(rgba)));
if (!c.Qoi)
{
// The streaming reader over the same bytes, 16 rows a call, into the same kind of buffer.
var rows = new byte[rgba.Length];
void ReadRows()
{
using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(data, writable: false)), PixelFormat.Rgba32, null);
while (reader.ReadRows(rows.AsSpan(reader.RowsRead * w * 4), 16) > 0) { }
}
ReadRows();
if (!rows.AsSpan().SequenceEqual(rgba)) throw new InvalidOperationException($"{c.Name}: the row reader differs from TryDecodeInto");
setup.Contestants.Add(new(Names.PnmRows, ReadRows));
}

if (Baseline.CanDecode(c.Qoi))
{
Expand Down Expand Up @@ -233,6 +247,30 @@ void Check(string name, byte[] output)
toStream();
}));

if (!c.Qoi && c.Format != "pfm")
{
// The streaming session, 16 rows a call, into a reused writer: the bytes of the whole-image encode.
var sessionFormat = c.Format == "ppm16" ? PixelFormat.Rgb48 : format;
var writer = new System.Buffers.ArrayBufferWriter<byte>(ours.Length);
void Session()
{
writer.ResetWrittenCount();
using var session = PnmImageEncoder.Create(writer, c.Format == "ppm16" ? null : c.PnmOptions);
var frame = session.AddFrame(w, h, sessionFormat);
var rowBytes = w * sessionFormat.BytesPerPixel;
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 Encode's");
setup.Sizes[Names.PnmSession] = writer.WrittenCount;
setup.Contestants.Add(new(Names.PnmSession, Session));
}

if (c.Format is not ("pfm" or "ppm16") && Baseline.CanEncode(c.Qoi))
{
Func<byte[]> baseline;
Expand Down Expand Up @@ -295,8 +333,8 @@ 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.PnmRows, Names.Baseline, Names.ImageSharp }
: [Names.Current, Names.CurrentStream, Names.PnmSession, 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)");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,15 @@ internal static class Names
public const string CurrentStream = "CurrentStream";
public const string Baseline = "Baseline";
public const string ImageSharp = "ImageSharp";
public const string PnmRows = "PnmRows";
public const string PnmSession = "PnmSession";

public static string Label(string name) => name switch
{
Current => "current",
CurrentStream => "current → stream",
PnmRows => "PNM row reader",
PnmSession => "PNM streaming session",
Baseline => "baseline",
_ => name,
};
Expand Down
93 changes: 84 additions & 9 deletions src/Sdcb.SimdCodecs.Pnm/PnmEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,11 @@ public static Input Of(ReadOnlySpan<byte> samples, int width, int height, int ch
return new Input(samples, width, height, (int)rowStride, channels, sixteen, false, format);
}

/// <summary>A band of rows in a native layout (<see cref="PixelFormat.ForChannels"/>), 8- or 16-bit, <paramref name="stride"/>
/// bytes apart; the caller has checked the size and the buffer.</summary>
public static Input OfRows(ReadOnlySpan<byte> rows, int width, int rowCount, int stride, PixelFormat native) =>
new(rows, width, rowCount, stride, native.Channels, native.Sample == SampleFormat.UInt16, false, native);

public ReadOnlySpan<byte> Row(int y) => Pixels.Slice(y * Stride, Width * Channels * (Sixteen ? 2 : 1));
}

Expand All @@ -266,25 +271,28 @@ private readonly record struct Target(PnmFormat Format, int Channels, int MaxVal
};
}

private static Target Plan(in Input input, PnmEncodeOptions? options)
private static Target Plan(in Input input, PnmEncodeOptions? options) =>
Plan(input.Width, input.Height, input.Channels, input.Sixteen, options);

private static Target Plan(int width, int height, int inputChannels, bool sixteen, PnmEncodeOptions? options)
{
options ??= new PnmEncodeOptions();
var format = options.Format switch
{
PnmFormat.Auto => input.Channels switch { 1 => PnmFormat.Graymap, 3 => PnmFormat.Pixmap, _ => PnmFormat.Arbitrary },
PnmFormat.Auto => inputChannels switch { 1 => PnmFormat.Graymap, 3 => PnmFormat.Pixmap, _ => PnmFormat.Arbitrary },
>= PnmFormat.PlainBitmap and <= PnmFormat.Arbitrary => options.Format,
_ => throw new ArgumentException($"{options.Format} is not a PBM, PGM, PPM or PAM format; PFM is written by EncodePfm.", nameof(options)),
};
var channels = format switch
{
PnmFormat.PlainBitmap or PnmFormat.Bitmap or PnmFormat.PlainGraymap or PnmFormat.Graymap => 1,
PnmFormat.PlainPixmap or PnmFormat.Pixmap => 3,
_ => input.Channels,
_ => inputChannels,
};
if (input.Sixteen && (channels != input.Channels || format is PnmFormat.PlainBitmap or PnmFormat.Bitmap))
throw new ArgumentException($"16-bit input of {input.Channels} channels cannot be written as {format}.", nameof(options));
if (sixteen && (channels != inputChannels || format is PnmFormat.PlainBitmap or PnmFormat.Bitmap))
throw new ArgumentException($"16-bit input of {inputChannels} channels cannot be written as {format}.", nameof(options));
var maxValue = format is PnmFormat.PlainBitmap or PnmFormat.Bitmap ? 1
: options.MaxValue == 0 ? (input.Sixteen ? 65535 : 255)
: options.MaxValue == 0 ? (sixteen ? 65535 : 255)
: options.MaxValue;
if (maxValue is < 1 or > 65535)
throw new ArgumentException($"Maximum value {maxValue} is not 1..65535.", nameof(options));
Expand All @@ -296,13 +304,13 @@ private static Target Plan(in Input input, PnmEncodeOptions? options)
var tupleType = options.TupleType ?? channels switch { 1 => "GRAYSCALE", 2 => "GRAYSCALE_ALPHA", 3 => "RGB", _ => "RGB_ALPHA" };
if (tupleType.Length == 0 || tupleType.Any(c => c is < ' ' or > '~'))
throw new ArgumentException("The tuple type must be printable ASCII on one line.", nameof(options));
header = $"P7\nWIDTH {input.Width}\nHEIGHT {input.Height}\nDEPTH {channels}\nMAXVAL {maxValue}\nTUPLTYPE {tupleType}\nENDHDR\n";
header = $"P7\nWIDTH {width}\nHEIGHT {height}\nDEPTH {channels}\nMAXVAL {maxValue}\nTUPLTYPE {tupleType}\nENDHDR\n";
}
else
{
header = maxValue == 1 && format is PnmFormat.PlainBitmap or PnmFormat.Bitmap
? $"P{magic}\n{input.Width} {input.Height}\n"
: $"P{magic}\n{input.Width} {input.Height}\n{maxValue}\n";
? $"P{magic}\n{width} {height}\n"
: $"P{magic}\n{width} {height}\n{maxValue}\n";
}
return new Target(format, channels, maxValue, Encoding.ASCII.GetBytes(header));
}
Expand Down Expand Up @@ -343,6 +351,73 @@ private static void ToStream(in Input input, Target target, Stream output)
private static void Write(in Input input, Target target, IBufferWriter<byte> output)
{
output.Write(target.Header);
WriteRaster(input, target, output);
}

/// <summary>
/// Writes a file a band of rows at a time: the header at <see cref="Begin"/>, then each band's raster as it arrives.
/// Every row of a Netpbm raster is written on its own (a plain raster starts each row on a new line), so the bytes
/// are those of the whole-image encode however the rows are split.
/// </summary>
internal sealed class RowWriter : IDisposable
{
private readonly Target _target;
private readonly int _width;
private readonly PixelFormat _format, _native;
private byte[]? _scratch;

private RowWriter(Target target, int width, PixelFormat format, PixelFormat native)
{
_target = target;
_width = width;
_format = format;
_native = native;
}

/// <summary>
/// Plans a <paramref name="width"/> × <paramref name="height"/> image of <paramref name="format"/> rows and writes its
/// header. The rows are encoded as <paramref name="format"/>'s channels at its depth, straight alpha, RGB order: the
/// layout the buffered encode converts its input to.
/// </summary>
/// <exception cref="ArgumentException">The size or options do not fit.</exception>
public static RowWriter Begin(int width, int height, PixelFormat format, PnmEncodeOptions? options, IBufferWriter<byte> output)
{
CheckSize(width, height);
var native = PixelFormat.ForChannels(format.Channels, format.Sample);
var target = Plan(width, height, native.Channels, native.Sample == SampleFormat.UInt16, options);
output.Write(target.Header);
return new RowWriter(target, width, format, native);
}

/// <summary>Encodes <paramref name="rowCount"/> rows, <paramref name="stride"/> bytes apart (the caller checked both).</summary>
public void Write(ReadOnlySpan<byte> rows, int rowCount, int stride, IBufferWriter<byte> output)
{
if (_format == _native)
{
WriteRaster(Input.OfRows(rows, _width, rowCount, stride, _native), _target, output);
return;
}
var inBytes = _width * _format.BytesPerPixel;
var nativeBytes = _width * _native.BytesPerPixel;
_scratch ??= ArrayPool<byte>.Shared.Rent(nativeBytes);
var row = _scratch.AsSpan(0, nativeBytes);
for (var y = 0; y < rowCount; y++)
{
PixelConverter.ConvertRow(rows.Slice(y * stride, inBytes), _format, row, _native, _width);
WriteRaster(Input.OfRows(row, _width, 1, nativeBytes, _native), _target, output);
}
}

public void Dispose()
{
if (_scratch is not null)
ArrayPool<byte>.Shared.Return(_scratch);
_scratch = null;
}
}

private static void WriteRaster(in Input input, Target target, IBufferWriter<byte> output)
{
int width = input.Width, channels = target.Channels, max = target.MaxValue;
if (IsVerbatim(input, target))
{
Expand Down
30 changes: 22 additions & 8 deletions src/Sdcb.SimdCodecs.Pnm/PnmImageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ namespace Sdcb.SimdCodecs.Pnm;
/// into the <c>Sdcb.SimdCodecs</c> facade. An image decodes as 8-bit samples up to a maximum value of 255,
/// 16-bit above. <see cref="TryDecodeInto"/> writes the caller's buffer directly. Malformed data makes the
/// <c>Try</c> methods return false rather than throw. PFM has its own adapter, <see cref="PfmImageDecoder"/>.
/// <see cref="CreateRowReader"/> decodes from a forward-only stream a row at a time.
/// </summary>
public sealed class PnmImageDecoder : IImageDecoder
public sealed class PnmImageDecoder : IStreamingImageDecoder
{
/// <summary>The registration for <c>ImageCodecs.Register</c>, built from this type's method groups.</summary>
public static ImageDecoderRegistration Registration { get; } = new()
Expand All @@ -25,8 +26,19 @@ public sealed class PnmImageDecoder : IImageDecoder
TryDecodeInto = TryDecodeInto,
TryReadMetadata = TryReadMetadata,
TryDecodeThumbnail = TryDecodeThumbnail,
CreateRowReader = CreateRowReader,
};

/// <inheritdoc />
/// <remarks>
/// Every P1 to P7 image streams: the header is read whole (at most 1 MiB, comments included; a longer one throws
/// <see cref="InvalidDataException"/>), then each raw row as soon as its bytes are there and each plain row token by
/// token, holding a row of input and of samples. Options other than the whole image at full size decode the whole
/// stream first (<see cref="IImageRowReader.IsStreaming"/> false). PFM is not read here: see <see cref="PfmImageDecoder"/>.
/// </remarks>
public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) =>
new PnmRowReader(input, format, options);

/// <inheritdoc />
/// <remarks><c>P1</c> to <c>P7</c> and a whitespace byte.</remarks>
public static int SignatureLength => 3;
Expand Down Expand Up @@ -154,13 +166,7 @@ public static bool TryReadInfo(ReadOnlySpan<byte> data, bool pfm, out ImageInfo
{
try
{
var pnm = Read(data, pfm, out _);
info = new ImageInfo(pnm.Width, pnm.Height, pnm.Channels, pnm.SampleFormat)
{
Format = pfm ? ImageFormat.Pfm : ImageFormat.Pnm,
BitDepth = pfm ? 32 : 32 - BitOperations.LeadingZeroCount((uint)pnm.MaxValue),
ColorEncoding = pfm ? LinearFloat : ColorEncoding.AssumedSrgb,
};
info = ToImageInfo(Read(data, pfm, out _), pfm);
return true;
}
catch (InvalidDataException)
Expand All @@ -170,6 +176,14 @@ public static bool TryReadInfo(ReadOnlySpan<byte> data, bool pfm, out ImageInfo
}
}

public static ImageInfo ToImageInfo(in PnmInfo pnm, bool pfm) =>
new(pnm.Width, pnm.Height, pnm.Channels, pnm.SampleFormat)
{
Format = pfm ? ImageFormat.Pfm : ImageFormat.Pnm,
BitDepth = pfm ? 32 : 32 - BitOperations.LeadingZeroCount((uint)pnm.MaxValue),
ColorEncoding = pfm ? LinearFloat : ColorEncoding.AssumedSrgb,
};

public static IDecodedImage Decode(ReadOnlySpan<byte> data, bool pfm, DecodeOptions? options,
CancellationToken cancellationToken)
{
Expand Down
34 changes: 24 additions & 10 deletions src/Sdcb.SimdCodecs.Pnm/PnmImageEncoder.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Buffers;
using System.Collections.Generic;
using System.Threading;
using Sdcb.SimdCodecs.Abstractions;
using Sdcb.SimdCodecs.Abstractions.CodecSupport;
Expand All @@ -9,7 +8,8 @@ namespace Sdcb.SimdCodecs.Pnm;
/// <summary>
/// <see cref="IImageEncoder"/> for Netpbm: the encoder abstraction's adapter over <see cref="PnmEncoder"/>.
/// Netpbm stores 8- and 16-bit grey, grey + alpha, RGB, or RGBA, so <see cref="GetClosestInputFormat"/> keeps depth,
/// straight alpha, and RGB order.
/// straight alpha, and RGB order. Every session streams (<see cref="IImageEncoderSession.IsStreaming"/>): the header
/// reaches the writer at <c>AddFrame</c> and each band of rows as it is written.
/// </summary>
public sealed class PnmImageEncoder : IImageEncoder
{
Expand Down Expand Up @@ -40,18 +40,32 @@ public static IImageEncoderSession Create(IBufferWriter<byte> output, EncodeOpti
_ => throw new ArgumentException($"Netpbm encoding takes PnmEncodeOptions, not {options.GetType().Name}.", nameof(options)),
});

private sealed class Session(IBufferWriter<byte> output, PnmEncodeOptions options) : BufferedEncoderSession(output)
// Every Netpbm option encodes row by row (a plain raster starts each row on a new line), so every session streams:
// the header at AddFrame, each band's raster as WriteRows hands it over.
private sealed class Session(IBufferWriter<byte> output, PnmEncodeOptions options) : StreamingEncoderSession(output)
{
private PnmEncoder.RowWriter? _writer;

public override int MaxFrames => 1;

protected override void Encode(IReadOnlyList<BufferedFrame> frames, CancellationToken cancellationToken)
protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color,
ImageMetadata? metadata, TimeSpan? duration) =>
_writer = PnmEncoder.RowWriter.Begin(width, height, format, options, Output);

protected override void EncodeRows(ReadOnlySpan<byte> rows, int rowCount, int stride, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var frame = frames[0];
var native = GetClosestInputFormat(frame.Format);
var pixels = frame.PixelsAs(native);
var file = PnmEncoder.Encode(pixels, frame.Width, frame.Height, native, options);
WriteOutput(file);
_writer!.Write(rows, rowCount, stride, Output);
}

protected override void Finish(CancellationToken cancellationToken) { }

protected override void Dispose(bool disposing)
{
if (disposing)
_writer?.Dispose();
_writer = null;
base.Dispose(disposing);
}
}
}
}
Loading