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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,26 @@ API between minor releases.

- `CompressedPool.ReadSubgroups()` reads BL-tagged records from decoded pools and reports incomplete payloads.

- `PlaReaderOptions` (with `Default`) caps what the readers decode into memory: `MaxGlobalStreamBytes` bounds the
decoded global stream and the window a mode-2 `ReadPayload` builds (default: the most one in-memory stream can
hold), `MaxDecodedPoolBytes` bounds one decoded pool (default: 512 MiB) and `MaxCoverBytes` bounds the `.bimx`
cover image (default: 64 MiB, previously fixed). The options are immutable — build a new instance to change a
limit — and come through added overloads (`Open(string, PlaReaderOptions?)`, `Open(Stream, bool,
PlaReaderOptions?)`; the 0.1.0 entry-point signatures are unchanged). A read past a cap throws
`InvalidDataException` naming it. The caps are reader limits, not facts of the format.

- `PlaStream.SkippedBlocks`: the indexed blocks that failed to decode to their declared size (false entries of the
scan), in file order — the blocks behind `UnreliableFrom`.

### Changed

- The core library follows the IOExtend reference layout (RvtIO, NwcIO): the entry points (`PlaDocument`,
`BimxDocument`, `PlaFile`, `PlaReaderOptions`) stay in `PlaIO`, while the document types moved to the namespace
`PlaIO.Model` (`FdbHeader`, `PlaBlock` + `PlaBlockMode`, `ObjectDirectory` + `ObjectDirectoryRecord`,
`CompressedPool`, `PoolSubgroup`, `PlaStream`). The mode-2 global-window decode moved out of `PlaDocument` into
internal machinery; the public surface and behavior are unchanged apart from the namespaces, and the entry-point
signatures of the 0.1.0 surface keep their forms.

- The release workflow follows the IOExtend release order: the NuGet packages are pushed before the GitHub release is
created (a refused first publication can be fixed and the job re-run, because `--skip-duplicate` makes the push
repeatable), and a tag whose version contains a hyphen is published as a prerelease. The changelog section for the
Expand Down
1 change: 1 addition & 0 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ dotnet add package PlaIO
using System;
using System.IO;
using PlaIO;
using PlaIO.Model;

using (var doc = PlaDocument.Open("project.pln"))
{
Expand Down
34 changes: 27 additions & 7 deletions docs/public-api.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# Public API

The `PlaIO` package is the supported surface listed here; every public type is in the namespace `PlaIO`. Everything else
(the block scanner, the header parser, the payload decoder, the directory search, the PNG chunk walker) is `internal` in
`PlaIO.Internal`; it can change in any release and is visible only to the test project through `InternalsVisibleTo`.
The `PlaIO` package is the supported surface listed here. The entry points (`PlaDocument`, `BimxDocument`, `PlaFile`,
`PlaReaderOptions`) are in the namespace `PlaIO`; the types that describe the opened document (`PlaBlock`,
`ObjectDirectory`, `CompressedPool`, `PoolSubgroup`, `PlaStream`, `FdbHeader`) are in `PlaIO.Model`. Everything else
(the block scanner, the header parser, the payload decoders, the directory search, the PNG chunk walker) is `internal`
in `PlaIO.Internal`; it can change in any release and is visible only to the test project through `InternalsVisibleTo`.

## File kind

Expand All @@ -13,11 +15,26 @@ The `PlaIO` package is the supported surface listed here; every public type is i
| `PlaFile.DetectKind(ReadOnlySpan<byte> head)` | The kind of a file whose first bytes are `head`. |
| `PlaFile.DetectKind(string path)` | Reads at most 8 bytes of the file; I/O errors propagate. |

## Reader options

| Member | Use |
|---|---|
| `PlaReaderOptions.Default` | The options a reader uses when the caller passes none. |
| `PlaReaderOptions.MaxGlobalStreamBytes` | Cap on the decoded global stream (`OpenStream`) and on the window a mode-2 `ReadPayload` builds (default: the most one in-memory stream can hold). A block whose declared size grows the window past the cap throws `InvalidDataException` before it is decoded. |
| `PlaReaderOptions.MaxDecodedPoolBytes` | Cap on the decoded size of one compressed pool (default: 512 MiB). A pool that declares more makes `Decode` throw `InvalidDataException`. |
| `PlaReaderOptions.MaxCoverBytes` | Cap on the `.bimx` cover image read into memory (default: 64 MiB). A larger cover makes `ReadCover` throw `InvalidDataException`. |

The caps are reader limits, not facts of the format. The options are immutable — build a new instance to change a
limit; `Default` cannot be mutated, so one reader never changes the limits of another. The entry-point signatures of
the 0.1.0 surface are unchanged: the options come through added overloads (`Open(string, PlaReaderOptions?)` and
`Open(Stream, bool, PlaReaderOptions?)`; the same for `BimxDocument`).

## FDB container (`.pla`, `.pln`)

| Member | Use |
|---|---|
| `PlaDocument.Open(string path)`, `PlaDocument.Open(Stream stream, bool leaveOpen = false)` | Opens a container and builds its block index. The stream must be readable and seekable (`ArgumentException` otherwise); data that is not an FDB container or is shorter than 32 bytes throws `InvalidDataException`. The document owns the stream unless `leaveOpen` is true; when `Open` throws, the stream stays with the caller. |
| `PlaDocument.Open(string path, PlaReaderOptions? options)`, `PlaDocument.Open(Stream stream, bool leaveOpen, PlaReaderOptions? options)` | The same opens with explicit reader options. |
| `PlaDocument.Length` | Length of the file in bytes. |
| `PlaDocument.Header` | The `FdbHeader`. |
| `PlaDocument.Blocks` | The block index in file order, found by scanning from offset 32. No on-disk block map is known, so completeness is not claimed. The scan can take a byte run for a block header, so the index may contain false entries. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. |
Expand All @@ -26,12 +43,13 @@ The `PlaIO` package is the supported surface listed here; every public type is i
| `PlaDocument.OpenStream()` | The document's decoded global stream (`PlaStream`): every block's payload decoded in block order. Blocks that fail to decode are skipped and mark the remaining offsets as unreliable. The stream holds the decoded bytes in memory and can outlive the document. |
| `PlaDocument.Dispose()` | Releases the stream unless the document was opened with `leaveOpen`. |
| `FdbHeader` | `Size` (64), `LayoutVersion` (u16 at offset 8), `FormatVersion` (u16 at offset 10), `Field12` (u32 at offset 12; meaning not documented), `Raw` (the first min(64, file length) bytes; bytes 32..63 overlap the first block). |
| `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200). |
| `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200): an LZ token stream decoded against the global window. |
| `PlaBlock` | One indexed block: `Offset`, `Tag` (`BL` or `DY`), `Id` and `Kind` (raw), `Version` (0 or 1), `Flags` (raw), `SizeClass` (`Flags & 0xF`), `Mode`, `Guid` (present when flag 0x20 is set), `PackedSize`, `UnpackedSize`, `Extra` (present when flag 0x400 is set; raw), `PayloadOffset`, `HeaderLength`, `End`. |
| `ObjectDirectory` | A run of directory records inside a raw block: `Block`, `RecordOffset` (payload offset of the first record), `Phase` (`RecordOffset % 30`), `Records`, `AbuttingPairs`, `OverlappingPairs`, `DuplicatePositions`. The run is an estimate and can be shorter than the real directory: it stops after more than 8 consecutive records without an abutting neighbour. |
| `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. The position and count name a byte extent of the decoded global stream — the object's data (see `PlaDocument.OpenStream`). The class number is not mapped to a class name. |
| `PlaStream.Length` | Length of the decoded stream in bytes, including the bytes beyond the unreliable boundary. |
| `PlaStream.UnreliableFrom` | The offset of the first indexed block that failed to decode, or null when every indexed block decoded. |
| `PlaStream.SkippedBlocks` | The indexed blocks that failed to decode to their declared size (false entries of the scan), in file order. |
| `PlaStream.ReadExtent(long position, long count)` | The bytes of one extent. Throws `ArgumentOutOfRangeException` for negative or out-of-bounds extents and `InvalidDataException` for extents that reach the unreliable range. |
| `PlaStream.ReadExtent(ObjectDirectoryRecord record)` | The bytes addressed by a directory record. Throws `InvalidDataException` if the extent exceeds the stream or reaches the unreliable range. |

Expand All @@ -47,7 +65,7 @@ independent decoding of saved-file frames verified the correspondence. PlaIO has
| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. Computed on each call. |
| `CompressedPool.Offset` and `End` | File offsets of the pool marker and of the end of the pool. |
| `CompressedPool.TotalDecompressed` and `BlockCount` | Decoded byte count and number of frames in the pool. |
| `CompressedPool.Decode()` | Decoded frame payloads in order. Throws `InvalidDataException` on invalid framing or data and `ObjectDisposedException` after disposing the document. |
| `CompressedPool.Decode()` | Decoded frame payloads in order. Throws `InvalidDataException` on invalid framing or data (a pool past `PlaReaderOptions.MaxDecodedPoolBytes` included) and `ObjectDisposedException` after disposing the document. |

### Pool subgroups

Expand All @@ -67,18 +85,20 @@ Offsets are relative to the decoded pool. The scanner retries an unmatched BL ca
| Member | Use |
|---|---|
| `BimxDocument.Open(string path)`, `BimxDocument.Open(Stream stream, bool leaveOpen = false)` | Opens a `.bimx` file and measures its cover image without reading it. Same exceptions as `PlaDocument.Open`; a cover cut short also throws `InvalidDataException`. |
| `BimxDocument.Open(string path, PlaReaderOptions? options)`, `BimxDocument.Open(Stream stream, bool leaveOpen, PlaReaderOptions? options)` | The same opens with explicit reader options. |
| `BimxDocument.Length` | Length of the file in bytes. |
| `BimxDocument.CoverOffset` | Offset of the PNG cover image: always 4, right after the signature. |
| `BimxDocument.CoverLength` | Length of the cover, from the PNG signature through the IEND chunk and its CRC. |
| `BimxDocument.ContentOffset` | `CoverOffset + CoverLength`. The content after the cover is not interpreted. |
| `BimxDocument.ReadCover()` | The PNG cover image. Throws `InvalidDataException` when the cover is larger than 64 MiB. |
| `BimxDocument.ReadCover()` | The PNG cover image. Throws `InvalidDataException` when the cover is larger than `PlaReaderOptions.MaxCoverBytes` (64 MiB by default). |
| `BimxDocument.Dispose()` | Releases the stream unless the document was opened with `leaveOpen`. |

## Resources and threads

`PlaDocument` and `BimxDocument` never load the whole file into memory: the block index is built by scanning through the
stream once, at `Open`, and payloads and the cover are read on request. The exception is `OpenStream`: its decoded global
stream holds the whole decoded file in memory by design. A document is not thread-safe; use one per thread.
stream holds the whole decoded file in memory by design, bounded by `PlaReaderOptions.MaxGlobalStreamBytes`. A document
is not thread-safe; use one per thread.
After `Dispose`, `ReadPayload`, `FindDirectories`, `OpenStream` and `ReadCover` throw `ObjectDisposedException`.

## Diagnostics
Expand Down
1 change: 1 addition & 0 deletions src/PlaIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using PlaIO.Model;
using System.Globalization;
using System.Reflection;

Expand Down
1 change: 1 addition & 0 deletions src/PlaIO.Cli/DirectoryJson.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using PlaIO.Model;
using System.Text.Json;

namespace PlaIO.CommandLine;
Expand Down
20 changes: 16 additions & 4 deletions src/PlaIO/BimxDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,17 @@ private BimxDocument(Stream stream, bool leaveOpen, long length, long coverLengt
/// <summary>Opens the file at <paramref name="path"/> for reading.</summary>
/// <exception cref="InvalidDataException">The file is not a .bimx file or its cover image is cut short.</exception>
public static BimxDocument Open(string path)
=> Open(path, options: null);

/// <summary>Opens the file at <paramref name="path"/> for reading with explicit reader options.</summary>
/// <exception cref="InvalidDataException">The file is not a .bimx file or its cover image is cut short.</exception>
public static BimxDocument Open(string path, PlaReaderOptions? options)
{
ArgumentNullException.ThrowIfNull(path);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, FileOptions.RandomAccess);
try
{
return Open(stream, leaveOpen: false);
return Open(stream, leaveOpen: false, options);
}
catch
{
Expand All @@ -54,13 +59,20 @@ public static BimxDocument Open(string path)
/// the caller.</summary>
/// <exception cref="ArgumentException">The stream cannot read or seek.</exception>
/// <exception cref="InvalidDataException">The data is not a .bimx file or its cover image is cut short.</exception>
public static BimxDocument Open(Stream stream, bool leaveOpen = false) => Open(stream, leaveOpen, FdbFormat.MaxCoverLength);
public static BimxDocument Open(Stream stream, bool leaveOpen = false)
=> Open(stream, leaveOpen, options: null);

internal static BimxDocument Open(Stream stream, bool leaveOpen, long maxCoverLength)
/// <summary>Opens a .bimx file from a readable, seekable stream with explicit reader options and measures the cover
/// image without reading it. The document owns the stream unless <paramref name="leaveOpen"/> is true; when this
/// method throws, the stream stays with the caller.</summary>
/// <exception cref="ArgumentException">The stream cannot read or seek.</exception>
/// <exception cref="InvalidDataException">The data is not a .bimx file or its cover image is cut short.</exception>
public static BimxDocument Open(Stream stream, bool leaveOpen, PlaReaderOptions? options)
{
ArgumentNullException.ThrowIfNull(stream);
if (!stream.CanRead || !stream.CanSeek)
throw new ArgumentException("The stream must be readable and seekable.", nameof(stream));
options ??= PlaReaderOptions.Default;

long length = stream.Length;
var head = new byte[Math.Min(PlaFile.SignatureLength, length)];
Expand All @@ -70,7 +82,7 @@ internal static BimxDocument Open(Stream stream, bool leaveOpen, long maxCoverLe
throw new InvalidDataException($"Not a BIMx file (detected kind: {kind}).");

long coverLength = PngChunks.Measure(stream, 4, length);
return new BimxDocument(stream, leaveOpen, length, coverLength, maxCoverLength);
return new BimxDocument(stream, leaveOpen, length, coverLength, options.MaxCoverBytes);
}

/// <summary>The PNG cover image.</summary>
Expand Down
1 change: 1 addition & 0 deletions src/PlaIO/Internal/BlockHeaderParser.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Buffers.Binary;
using System.Diagnostics.CodeAnalysis;
using PlaIO.Model;

namespace PlaIO.Internal;

Expand Down
2 changes: 2 additions & 0 deletions src/PlaIO/Internal/BlockScanner.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using PlaIO.Model;

namespace PlaIO.Internal;

/// <summary>Builds the block index in one forward pass: from offset 32, look for a "BL" or "DY" tag, accept a block whose
Expand Down
1 change: 1 addition & 0 deletions src/PlaIO/Internal/DirectoryFinder.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Buffers.Binary;
using System.Numerics;
using PlaIO.Model;

namespace PlaIO.Internal;

Expand Down
7 changes: 7 additions & 0 deletions src/PlaIO/Internal/FdbFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,11 @@ internal static class FdbFormat

/// <summary>Reader limit, not a format fact: the largest .bimx cover image that is read into memory.</summary>
public const long MaxCoverLength = 64L << 20;

/// <summary>Reader limit, not a format fact: the most bytes one decoded global stream may hold — the largest
/// in-memory buffer the reader can build on the running runtime.</summary>
public static readonly long MaxGlobalStreamBytes = Array.MaxLength;

/// <summary>Reader limit, not a format fact: the largest pool one document may decode into memory.</summary>
public const long MaxDecodedPoolBytes = 512L << 20;
}
77 changes: 77 additions & 0 deletions src/PlaIO/Internal/GlobalStreamDecoder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using PlaIO.Model;

namespace PlaIO.Internal;

/// <summary>Decodes the global stream: the payloads of every indexed block in file order appended to one window,
/// because a mode-2 token stream may reference the output of any preceding block. A block that does not decode to its
/// declared size (a false entry of the scan) is not part of the real stream: it is skipped and reported with the window
/// offset it would have contributed, and the window stays as if it were not there. The window never grows past
/// <c>maxBytes</c>: a block whose declared unpacked size would cross the cap throws before it is decoded.</summary>
internal static class GlobalStreamDecoder
{
/// <summary>Decodes every block of the document into a fresh window. The skipped blocks are reported in file
/// order.</summary>
public static List<byte> DecodeAll(PlaDocument document, long maxBytes, out IReadOnlyList<(PlaBlock Block, long WindowPosition)> skipped)
{
var window = new List<byte>();
var failed = new List<(PlaBlock, long)>();
foreach (var block in document.Blocks)
{
int before = window.Count;
if (!TryAppend(document, block, window, maxBytes)) failed.Add((block, before));
}
skipped = failed.AsReadOnly();
return window;
}

/// <summary>Decodes every block before <paramref name="through"/> into a fresh window, skipping the blocks that do
/// not decode as <see cref="DecodeAll"/> does. The block itself is not decoded.</summary>
public static List<byte> DecodePrefix(PlaDocument document, PlaBlock through, long maxBytes)
{
var window = new List<byte>();
foreach (var block in document.Blocks)
{
if (ReferenceEquals(block, through)) break;
TryAppend(document, block, window, maxBytes);
}
return window;
}

/// <summary>Appends the decoded payload of one block to the window, or leaves the window unchanged and returns
/// false when the block does not decode to its declared size (a false entry of the scan, so a partial decode is
/// rolled back).</summary>
public static bool TryAppend(PlaDocument document, PlaBlock block, List<byte> window, long maxBytes)
{
// The cap is a property of the whole window, so it is checked against the declared contribution before any
// decoding; a block that fails the cap is an error, not a skipped false entry.
if (window.Count + block.UnpackedSize > maxBytes)
throw new InvalidDataException($"The decoded global stream would grow past {maxBytes} bytes (the reader's cap) at the block at 0x{block.Offset:x}.");
int before = window.Count;
try
{
Append(document, block, window);
return true;
}
catch (InvalidDataException)
{
window.RemoveRange(before, window.Count - before);
return false;
}
}

/// <summary>Appends one block's full contribution to the window: raw payloads as they are, zero-mask payloads as
/// their full decode, mode-2 payloads as their token-stream output with the declared tail zero-filled (the
/// directory addresses the buffer space, so the window holds it). Throws <see cref="InvalidDataException"/> when
/// the block does not decode to its declared size.</summary>
private static void Append(PlaDocument document, PlaBlock block, List<byte> window)
{
if (block.Mode != PlaBlockMode.Lz)
{
window.AddRange(document.ReadPayload(block));
return;
}

document.ReadLzPayload(block, window, out int produced, out _);
if (produced < block.UnpackedSize) window.AddRange(new byte[(int)(block.UnpackedSize - produced)]);
}
}
Loading