Skip to content

Recover PSIN metadata across the whole archive, including stored blocks - #17

Merged
breadbbbb merged 1 commit into
breadbbbb:mainfrom
iamvillain:psin-full-scan
Nov 23, 2026
Merged

breadbbbb merged 1 commit into
breadbbbb:mainfrom
iamvillain:psin-full-scan

Conversation

@iamvillain

Copy link
Copy Markdown
Contributor

Why

PSIN metadata is only searched for in the first 16 MiB after the header, and only when every block of a container is zlib. Two things follow:

  • Containers further into a file are never listed. pack/story000/story000_script.rpf holds 2,309 PSIN containers, the first at 0x3150000. main lists none, and Scan entire archive does not look for PSIN at all.
  • A container with a stored block cannot be joined. A 64 KiB block that does not compress is stored as it is, with no zlib header. The join stops there, the container fails validation and is dropped. 39 of those 2,309 containers have at least one stored block.

A third gap showed up while measuring: anim.rpf has two containers that use the section list PSIN, PMAP, PSCH, PSIG, STDN, STNS, CHKS instead of PSIN, LSCH, LENM, LSNS, LGID, LRSC, CHKS.

Change

  • New Core/Rpf9PsinRecovery.cs. A page scan over the whole file.
    • A container starts at a 4 KiB page with a zlib block whose data begins with PSIN. All 2,325 containers in the two archives below start on a page.
    • It continues at the next 16-byte boundary for as long as the previous block is exactly 64 KiB. A continuation block is zlib, or stored: 64 KiB, or only the remaining bytes when it is the last block.
    • The join ends when the seven section headers give the total length. A stored last block is trimmed to that length.
    • A container is listed only when its sections, its CHKS length and its CHKS checksum all match.
  • Core/PsinMetadata.cs.
    • InternalChecksumVerified is now computed. The checksum is Jenkins one-at-a-time over the whole container, seeded with 0x3FAC7125, taking bytes as signed and reading the CHKS length and checksum fields as zero. It matches all 2,325 containers.
    • The PMAP… section list is accepted next to the LSCH… one, chosen by the second tag.
    • New RequiredLength returns the total length once the section headers are readable.
  • Full scan and cache. PayloadIndexBuilder.Build gains a PSIN stage and RecoveryIndexCache a psin kind (stored segments allowed). On open, a container that is both in the first-16-MiB result and in the index is listed once, from the index.
  • Preview text reports whether the checksum matches instead of saying it is not decoded.
  • Rpf9ModelRecovery.Block, TryInflate, ZeroPadding and ZlibHeader become internal so the new file reuses them.

The existing first-16-MiB search in Rpf9StructuredRecovery is unchanged apart from accepting the second section list through PsinMetadata.Inspect. It still does not require the checksum.

Results

Measured on the 1.0.2.1 package, on the archives I have complete copies of.

Archive Listed on e293917 (open) Candidates (full scan) Recovered With stored blocks
pack/story000/story000_script.rpf 0 2,309 2,309 39 (41 blocks)
anim.rpf 1 16 16 5 (101 blocks)
common.rpf, appdata0.rpf, pack/story000_bvh4/story000_bvh4.rpf, pack/story000_restofworld/story000_restofworld.rpf 0 0 0 0
  • Independent check. The 2,309 story000_script.rpf containers were first reassembled by a separate Python script written before this code. Reading each recovered entry back through ArchiveReader.Open and ReadPreview gives the same bytes for all 2,309 (SHA-256).
  • Checksums. All 2,325 recovered containers have a matching CHKS checksum when read back.
  • Sizes. 75.7 MB in story000_script.rpf; the largest container, in anim.rpf, is 9.2 MB in 140 blocks, 88 of them stored.
  • Section lists. 2,323 containers use LSCH…; 2 in anim.rpf use PMAP….
  • On open, nothing changes until a full scan has been run: anim.rpf still lists 1 PSIN entry, common.rpf 259 XML documents and story000_bvh4.rpf 4.
  • Time. story000_script.rpf (78 MB): 0.7 s to scan, 1.1 s to recover. anim.rpf (4.4 GB): 45 s to scan.

Not covered: a container whose stored last block would be 1 to 5 bytes long is skipped, because a segment under 6 bytes cannot be read back by ZlibSegmentsStream or stored in the index. None of the 2,325 is affected. I could not measure the larger archives (levels.rpf, packs.rpf, data.rpf): my copies are incomplete.

Tests

main ignores Tests/, so, as in #8 to #11, the fixture is below rather than in the PR. It builds PSIN containers in code with a valid checksum and writes them to a test archive with each block either zlib or stored. It checks:

  • a generated container verifies, one changed byte breaks the checksum, and RequiredLength answers for a complete container, a prefix and non-PSIN bytes;
  • the PMAP… section list is accepted;
  • the scanner finds, and recovery joins, six layouts: one block, three zlib blocks, a stored block in the middle, a stored last block, two stored blocks, and a PMAP… container with a stored block;
  • each cached entry reads back byte for byte through ArchiveReader.Open and ReadPreview;
  • a container with a wrong checksum is not listed.

While writing it, the stored-last-block case failed: a stored block shorter than 64 KiB at the end of a file was skipped. That is fixed in this PR.

The fixture is generated in code and contains no game data.

Copy both files to Tests/PsinRecoverySmoke/ and run dotnet run --project Tests/PsinRecoverySmoke -c Release.

Tests/PsinRecoverySmoke/PsinRecoverySmoke.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="../../Core/RpfPreview.Core.csproj" />
  </ItemGroup>
</Project>
Tests/PsinRecoverySmoke/Program.cs
using System.Buffers.Binary;
using System.IO.Compression;
using RpfPreview.Core;

// A PSIN container starts at a 4 KiB page and is split into 64 KiB blocks. A block is zlib or stored as it is.
// The fixture is generated in code (seeded filler bytes); it contains no game data.
const long CandidateOffset = 4096;

byte[] small = Make(bodyBytes: 3000);
Check(PsinMetadata.Inspect(small) is { InternalChecksumVerified: true, Sections.Count: 7 }, "a generated container has a matching checksum");
Check(PsinMetadata.RequiredLength(small) == small.Length, "the required length is the container length");
Check(PsinMetadata.RequiredLength(small.AsSpan(0, 100)) == -1, "a prefix that ends before the last section header needs more bytes");
Check(PsinMetadata.RequiredLength(new byte[64]) == 0, "bytes that are not PSIN are rejected");
byte[] damaged = (byte[])small.Clone(); damaged[40] ^= 1;
Check(PsinMetadata.Inspect(damaged) is { InternalChecksumVerified: false }, "one changed byte breaks the checksum");

byte[] large = Make(bodyBytes: 150000);
byte[] mapped = Make(bodyBytes: 150000, ["PSIN", "PMAP", "PSCH", "PSIG", "STDN", "STNS", "CHKS"]);
Check(PsinMetadata.Inspect(mapped) is { InternalChecksumVerified: true } && PsinMetadata.Inspect(mapped)!.Sections[1].Tag == "PMAP", "the PMAP section list is accepted");
Check(PsinMetadata.RequiredLength(mapped.AsSpan(0, 65536)) == -1, "the section list is not chosen before the PSIN section has been read");
var directory = Directory.CreateTempSubdirectory("rpf9-psin-test-");
string path = Path.Combine(directory.FullName, "psin.rpf");
try
{
    // Each case names the blocks in order: z = zlib, s = stored.
    foreach (var (container, layout, what) in new[] {
        (small, "z", "a one-block container"), (large, "zzz", "three zlib blocks"),
        (large, "zsz", "a stored block in the middle"), (large, "zzs", "a stored last block"), (large, "zss", "two stored blocks"), (mapped, "zsz", "a PMAP container with a stored block") })
    {
        Write(path, container, layout);
        long length = new FileInfo(path).Length;
        var candidates = Rpf9PsinRecovery.FindCandidateOffsets(path, length);
        Check(candidates.SequenceEqual([CandidateOffset]), "the scanner finds " + what);
        var entry = Rpf9PsinRecovery.RecoverAtOffsets(path, length, candidates).Single();
        Check(entry.Size == container.Length && entry.Segments!.Count == layout.Length &&
            entry.Segments.Select(s => s.IsRaw ? 's' : 'z').SequenceEqual(layout), "recovery joins " + what);
        RecoveryIndexCache.Save("psin", path, [entry], "test");
        var document = ArchiveReader.Open(path);
        var listed = document.Entries.Single(e => e.Extension == ".psin");
        Check(document.ReadPreview(listed, 16 * 1024 * 1024).AsSpan().SequenceEqual(container), "the cached entry reads back byte for byte: " + what);
        File.Delete(RecoveryIndexCache.CachePath("psin", path));
    }
    Write(path, damaged, "z");
    Check(Rpf9PsinRecovery.RecoverAtOffsets(path, new FileInfo(path).Length, [CandidateOffset]).Count == 0, "a container with a wrong checksum is not listed");
}
finally
{
    string cache = RecoveryIndexCache.CachePath("psin", path);
    if (File.Exists(cache)) File.Delete(cache);
    if (File.Exists(path)) File.Delete(path);
    directory.Delete();
}
Console.WriteLine("PSIN recovery checks passed.");

static void Check(bool condition, string what)
{
    if (!condition) throw new Exception("Failed: " + what);
}

static void Write(string path, byte[] container, string layout)
{
    using var file = File.Create(path);
    var header = new byte[64]; "9FPR"u8.CopyTo(header); file.Write(header);
    file.Position = 4096;
    for (int block = 0; block < layout.Length; block++)
    {
        var bytes = container.AsSpan(block * 65536, Math.Min(65536, container.Length - block * 65536));
        if (layout[block] == 's') file.Write(bytes);
        else using (var z = new ZLibStream(file, CompressionLevel.Optimal, leaveOpen: true)) z.Write(bytes);
        file.Write(new byte[(int)((-file.Position) & 15)]);
    }
    file.Write(new byte[4096]);
}

// Seven sections with the PSIN body filled from a fixed seed, then the CHKS length and checksum.
static byte[] Make(int bodyBytes, string[]? sectionTags = null)
{
    string[] tags = sectionTags ?? ["PSIN", "LSCH", "LENM", "LSNS", "LGID", "LRSC", "CHKS"];
    int[] lengths = [8 + bodyBytes, 40, 24, 68, 8, 88, 20];
    byte[] data = new byte[lengths.Sum()]; new Random(7).NextBytes(data);
    // A stored block must not look like the start of a zlib stream.
    for (int at = 65536; at < data.Length; at += 65536) data[at] = 0xFF;
    int position = 0;
    for (int i = 0; i < tags.Length; i++)
    {
        System.Text.Encoding.ASCII.GetBytes(tags[i]).CopyTo(data, position);
        BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(position + 4), (uint)lengths[i]);
        position += lengths[i];
    }
    int trailer = data.Length - 20;
    BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(trailer + 8), 0); BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(trailer + 12), 0);
    uint hash = 0x3FAC7125;
    foreach (byte b in data) { hash += (uint)(sbyte)b; hash += hash << 10; hash ^= hash >> 6; }
    hash += hash << 3; hash ^= hash >> 11; hash += hash << 15;
    BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(trailer + 8), (uint)data.Length);
    BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(trailer + 12), hash);
    return data;
}

Overlap with #16

#16 (clip dictionaries) and this PR are independent, but both add a kind to RecoveryIndexCache, a stage to PayloadIndexBuilder.Build and a field to PayloadIndexResult, and both make the same four Rpf9ModelRecovery members internal. Whichever merges second needs a small rebase on those lines; I will do it.

Testing environment

Tested on Windows 10 x64 with .NET SDK 10.0.101. Core, App and Tools/IndexBuilder build in Release with 0 warnings and 0 errors, on top of e293917. I did not exercise the changed preview text in the running app window; the listing and read path behind it were checked through Core as described above.

AI-assisted: an AI agent (Claude, Anthropic) did the investigation, code, tests and measurements on the author's behalf, and a second agent pass reviewed the diff independently. No game data is included here.

🤖 Generated with Claude Code

Adds Rpf9PsinRecovery: a page scan that finds PSIN containers anywhere in
an RPF9 file and joins their 64 KiB blocks, whether a block is zlib or
stored as it is. A container is listed only when its sections, CHKS
length and CHKS checksum match. PsinMetadata now verifies the checksum
and accepts the PMAP section list next to the LSCH one. The full archive
scan and index cache gain a PSIN stage.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@breadbbbb breadbbbb left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked fe9159f. No blocking defect reproduced within the documented scope. The supplied smoke passed six compressed/stored framing layouts. An additional 15,002 checks over 1,154 retained PSIN containers verified historical source hashes, checksums, required lengths, altered-body rejection, prefix handling, and oversized-section controls. The new PMAP section-list branch was exercised synthetically; the retained ledger did not contain that variant. Core, App, and IndexBuilder Release builds passed without warnings or errors.

When combining this with #16, please preserve both cache kinds/result fields and both scan stages with correct progress totals. A merge-tree check found the expected conflicts in App/MainWindow.Indexing.cs, Core/PayloadIndexBuilder.cs, Core/RecoveryIndexCache.cs, README.md, and README.txt. Full archive-corpus counts were not reproduced because the original archives are unavailable.

@breadbbbb breadbbbb left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at fe9159f. Leonida aa2988cc555b directly references this Core library. Its rpf9dump exporter and Rpf9DumpDiagnostics built with warnings treated as errors against this exact PR Core. The diagnostic suite and both exporter failure/retry tests passed. This verifies exporter compatibility; a complete game-engine or full-archive run was not performed.

The earlier retained-PSIN and generated framing checks also passed. Preserve the separate clip/PSIN cache and scan stages when rebasing alongside #16.

@breadbbbb
breadbbbb merged commit 79973d1 into breadbbbb:main Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants