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: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ API between minor releases.
- `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`.

- `CompressedPool.ReadSubgroups()` decodes mode-2 pool subgroups. A mode-2 payload is an LZ token stream like a
mode-2 block payload; it may start with a 13-byte pool header (a u32, the 0x47 marker, the packed payload length
and the unpacked size) or with the file block's 9-byte stream header. Its back-references reach into the pool
stream — the reconstruction of every preceding pool of the document and of this pool before the record — so a read
decodes the pools before the named one; reading the pools in file order advances one shared window, so every pool
decodes once. A skipped pool or an undecodable mode-2 subgroup resets the history. A mode-2 payload that cannot
decode is reported with empty data and `Partial`. The decoder discards history beyond the maximum back-reference
distance between records. `FindCompressedPools` caches its list after the first scan, so the pool objects stay
identical between calls.

### Changed

- The core library follows the IOExtend reference layout (RvtIO, NwcIO): the entry points (`PlaDocument`,
Expand Down
18 changes: 13 additions & 5 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,23 +62,31 @@ independent decoding of saved-file frames verified the correspondence. PlaIO has

| Member | Use |
|---|---|
| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. Computed on each call. |
| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. The first call scans the file; later calls return the cached list, so the pool objects stay identical. |
| `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 (a pool past `PlaReaderOptions.MaxDecodedPoolBytes` included) and `ObjectDisposedException` after disposing the document. |

### Pool subgroups

The subgroup header uses the FDB size field widths and may carry a GUID. It does not contain the file-level extra field.
Offsets are relative to the decoded pool. The scanner retries an unmatched BL candidate at the next byte.
Offsets are relative to the decoded pool. The scanner retries an unmatched BL candidate at the next byte. A mode-2
payload is an LZ token stream like a mode-2 block payload: it may start with a 13-byte pool header (a u32, the 0x47
marker, the packed payload length and the unpacked size) or with the file block's 9-byte stream header, and its
back-references reach into the pool stream — the reconstruction of every preceding pool of the document and of this
pool before the record — so a read decodes the pools before the named one. Reading the pools in file order advances
one shared window, so every pool decodes once. A read that names an earlier pool rebuilds the window. A skipped
pool or an undecodable mode-2 subgroup resets the history. A reference into missing history returns empty data
with `Partial` set. Subgroups can continue to reference bytes decoded after the gap. A back-reference distance is a
u16, so the decoder can discard older history between records.

| Member | Use |
|---|---|
| `CompressedPool.ReadSubgroups()` | Decodes the pool and returns the recognised BL-tagged records in pool order. |
| `CompressedPool.ReadSubgroups()` | Decodes the pool and returns the recognised BL-tagged records in pool order, with mode-2 payloads decoded against the pool stream. |
| `PoolSubgroup.Offset` | Start of the subgroup header in the decoded pool. |
| `PoolSubgroup.Kind`, `Version`, `Flags` and `ObjectId` | Raw header metadata and the optional GUID. |
| `PoolSubgroup.Mode` and `Data` | Raw or zero-mask payload bytes. Mode 2 is reported with empty data. |
| `PoolSubgroup.Partial` | True for unavailable mode 2 data or an incomplete zero-mask literal. A zero-mask stream ending at a group boundary can leave valid zero padding. |
| `PoolSubgroup.Mode` and `Data` | The payload bytes: raw as they are, zero-mask and mode-2 as their decoded output. A mode-2 payload that does not decode is reported with empty data and `Partial`. |
| `PoolSubgroup.Partial` | True for a mode-2 payload that does not decode (or produces less than declared) or an incomplete zero-mask literal. A zero-mask stream ending at a group boundary can leave valid zero padding. |

## BIMx file (`.bimx`)

Expand Down
74 changes: 64 additions & 10 deletions src/PlaIO/Internal/PoolSubgroupReader.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
using System.Buffers.Binary;
using PlaIO.Model;

namespace PlaIO.Internal;

/// <summary>Reads the BL-tagged records of one decoded pool. A mode-2 payload is an LZ token stream like a mode-2
/// block payload; its back-references reach into the pool stream — the reconstruction of every preceding pool of the
/// document (each subgroup's header, raw payloads as they are, zero-mask and mode-2 payloads as their full decodes,
/// concatenated in pool order), followed by this pool's own reconstruction so far. The window keeps only its tail: a
/// back-reference distance is a u16, so nothing reaches further back than <see cref="WindowTail"/> bytes and the
/// memory stays constant in the size of the file.</summary>
internal static class PoolSubgroupReader
{
public static IReadOnlyList<PoolSubgroup> Read(byte[] pool)
/// <summary>The window tail kept for back-references: the largest distance the format can name.</summary>
private const int WindowTail = 1 << 16;

/// <summary>Walks one decoded pool: parses each BL-tagged record, decodes its payload against
/// <paramref name="window"/>, and appends the record's contribution to the window — its header bytes and its
/// payload exactly once — so the following subgroups can reference it. A truncated zero-mask payload contributes
/// its stored bytes. An undecodable mode-2 payload resets the history.</summary>
internal static IReadOnlyList<PoolSubgroup> ReadPool(byte[] pool, List<byte> window)
{
var subgroups = new List<PoolSubgroup>();
int pos = 0;
Expand All @@ -20,26 +34,66 @@ public static IReadOnlyList<PoolSubgroup> Read(byte[] pool)
}

ReadOnlySpan<byte> payload = pool.AsSpan((int)header.PayloadOffset, (int)header.PackedSize);
ReadOnlySpan<byte> headerBytes = pool.AsSpan(pos, (int)header.PayloadOffset - pos);
byte[] data;
bool partial;
switch (header.Mode)
if (header.Mode == PlaBlockMode.Lz)
{
// The LZ decoder appends every produced byte to the window itself, so the header goes in first and
// the payload's contribution is made exactly once — inside DecodeLz.
window.AddRange(headerBytes);
(data, partial) = DecodeLz(payload, header, window);
}
else
{
case PlaBlockMode.Raw:
if (header.Mode == PlaBlockMode.Raw)
{
data = payload.ToArray();
partial = false;
break;
case PlaBlockMode.ZeroMask:
}
else
{
data = new byte[header.UnpackedSize];
PayloadDecoder.DecodeZeroMask(payload, data, out _, out partial);
break;
default:
data = [];
partial = true;
break;
}
window.AddRange(headerBytes);
// A truncated zero-mask literal leaves the rest of its buffer zero-filled; the window takes the raw
// bytes instead, because that is what the saved stream addresses.
window.AddRange(partial ? payload.ToArray() : data);
}
subgroups.Add(new PoolSubgroup(header, data, partial));
if (window.Count > 4 * WindowTail) window.RemoveRange(0, window.Count - WindowTail);
pos = (int)header.End;
}
return subgroups.AsReadOnly();
}

/// <summary>Decodes one mode-2 subgroup payload. A 13-byte header — a u32, the marker 0x47 at +4, then the packed
/// payload length at +5 (the length including the header) and the unpacked size at +9 — precedes the token stream;
/// without it the payload starts with the file block's 9-byte stream header or with the tokens themselves.
/// Returns the declared unpacked buffer with a zero tail when the stream produces less than declared (partial),
/// or empty data with partial set when the stream does not decode at all. The window receives the payload's
/// contribution exactly once: the decoder appends the produced bytes, this method adds the declared tail of a
/// buffer block. A failed stream resets the history so later references cannot reach across the missing output.</summary>
private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan<byte> payload, PlaBlock header, List<byte> window)
{
bool hasPoolHeader = payload.Length > 13 && payload[4] == 0x47
&& BinaryPrimitives.ReadUInt32LittleEndian(payload[5..]) == (uint)header.PackedSize
&& BinaryPrimitives.ReadUInt32LittleEndian(payload[9..]) == (uint)header.UnpackedSize;
ReadOnlySpan<byte> body = hasPoolHeader ? payload[13..] : payload;

var output = new byte[header.UnpackedSize];
try
{
LzPayloadDecoder.Decode(body, output, window, header.Offset, out int produced);
if (produced < header.UnpackedSize)
window.AddRange(new byte[(int)(header.UnpackedSize - produced)]); // the buffer space stays addressed
return (output, produced < header.UnpackedSize);
}
catch (InvalidDataException)
{
window.Clear();
return ([], true);
}
}
}
14 changes: 11 additions & 3 deletions src/PlaIO/Model/CompressedPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ public sealed class CompressedPool
{
private readonly PlaDocument _document;

internal CompressedPool(PlaDocument document, PoolRange range)
internal CompressedPool(PlaDocument document, PoolRange range, int index)
{
_document = document;
Index = index;
Offset = range.Offset;
End = range.End;
TotalDecompressed = range.UnpackedSize;
BlockCount = range.FrameCount;
}

internal int Index { get; }

/// <summary>The file offset of the pool marker.</summary>
public long Offset { get; }

Expand All @@ -34,8 +37,13 @@ internal CompressedPool(PlaDocument document, PoolRange range)
/// <exception cref="ObjectDisposedException">The owning document is disposed.</exception>
public byte[] Decode() => _document.DecodePool(Offset);

/// <summary>Decodes the pool and reads BL-tagged records in pool order.</summary>
/// <summary>Decodes the pool and reads BL-tagged records in pool order. A mode-2 payload is an LZ token stream
/// whose back-references reach into the pool stream — the reconstruction of every preceding pool of the document
/// and of this pool before the record — so the pools are decoded in order until this one and the cost of the call
/// grows with the size of the file. Reading the pools in file order advances one shared window, so every pool
/// decodes once; a read that names an earlier pool rebuilds the window. An unreadable preceding pool resets
/// the history, and a subgroup that references missing bytes returns empty data with Partial set.</summary>
/// <exception cref="InvalidDataException">The pool does not decode.</exception>
/// <exception cref="ObjectDisposedException">The owning document is disposed.</exception>
public IReadOnlyList<PoolSubgroup> ReadSubgroups() => PoolSubgroupReader.Read(Decode());
public IReadOnlyList<PoolSubgroup> ReadSubgroups() => _document.ReadPoolSubgroups(this);
}
2 changes: 1 addition & 1 deletion src/PlaIO/Model/PoolSubgroup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ internal PoolSubgroup(PlaBlock header, byte[] data, bool partial)
/// <summary>The object GUID when present in the header.</summary>
public Guid? ObjectId { get; }

/// <summary>The decoded payload. Mode 2 returns empty data pending a supported decoder.</summary>
/// <summary>The decoded payload. Mode 2 returns empty data when its stream cannot be decoded.</summary>
public byte[] Data { get; }

/// <summary>True when decoding is unavailable or the zero-mask stream ends inside a literal group.
Expand Down
47 changes: 45 additions & 2 deletions src/PlaIO/PlaDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public sealed class PlaDocument : IDisposable
private readonly bool _leaveOpen;
private readonly List<PlaBlock> _blocks;
private readonly PlaReaderOptions _options;
private IReadOnlyList<CompressedPool>? _pools;
private bool _disposed;

private PlaDocument(Stream stream, bool leaveOpen, long length, FdbHeader header, List<PlaBlock> blocks, PlaReaderOptions options)
Expand Down Expand Up @@ -212,11 +213,14 @@ public IReadOnlyList<ObjectDirectory> FindDirectories()
return found.AsReadOnly();
}

/// <summary>Finds compressed pools whose marker and frame headers parse, outside indexed block payloads.</summary>
/// <summary>Finds compressed pools whose marker and frame headers parse, outside indexed block payloads. The first
/// call scans the file; later calls return the cached list, so the pool objects stay identical.</summary>
public IReadOnlyList<CompressedPool> FindCompressedPools()
{
ObjectDisposedException.ThrowIf(_disposed, this);
return PoolReader.Find(_stream, Length, Blocks).Select(range => new CompressedPool(this, range)).ToList().AsReadOnly();
if (_pools is null)
_pools = PoolReader.Find(_stream, Length, Blocks).Select((range, index) => new CompressedPool(this, range, index)).ToList().AsReadOnly();
return _pools;
}

internal byte[] DecodePool(long offset)
Expand All @@ -225,6 +229,45 @@ internal byte[] DecodePool(long offset)
return PoolReader.Decode(_stream, Length, offset, _options.MaxDecodedPoolBytes);
}

/// <summary>The window that <see cref="Model.PoolSubgroup"/> decoding builds while the pools are read in order:
/// the tail of the pool-stream reconstruction up to the pool with index <see cref="_poolWindowThrough"/> (that
/// pool excluded). Reading the pools in file order advances the window, so every pool decodes once; a read that
/// names an earlier pool rebuilds the window from the start.</summary>
private List<byte>? _poolWindow;
private int _poolWindowThrough;

/// <summary>Reads the subgroups of one pool of this document, decoding the pool stream up to it (see
/// <see cref="Model.CompressedPool.ReadSubgroups"/>). A preceding pool that fails to decode resets the
/// history. Subgroups of the named pool can still use bytes decoded after that gap.</summary>
internal IReadOnlyList<PoolSubgroup> ReadPoolSubgroups(CompressedPool pool)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var pools = FindCompressedPools();
int target = pool.Index;
if ((uint)target >= (uint)pools.Count || !ReferenceEquals(pools[target], pool))
throw new ArgumentException("The pool is not one of the compressed pools of this document.", nameof(pool));

if (_poolWindow is null || target < _poolWindowThrough)
{
_poolWindow = new List<byte>();
_poolWindowThrough = 0;
}
for (; _poolWindowThrough < target; _poolWindowThrough++)
{
try
{
PoolSubgroupReader.ReadPool(pools[_poolWindowThrough].Decode(), _poolWindow);
}
catch (InvalidDataException)
{
_poolWindow.Clear();
}
}
var subgroups = PoolSubgroupReader.ReadPool(pools[target].Decode(), _poolWindow);
_poolWindowThrough = target + 1;
return subgroups;
}

/// <summary>Releases the stream unless the document was opened with leaveOpen.</summary>
public void Dispose()
{
Expand Down
Loading