diff --git a/CHANGELOG.md b/CHANGELOG.md index 386f1bf..07c6e4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ Notable changes to `samplerdisc`. Format-level findings live in [docs/formats/]( ### Fixed +- **An AKAI sample displaced by blocks lost *inside* a partition now converts instead of being refused as somebody else's audio.** An AKAI rip can drop a run of 32 KB container blocks from the middle of a partition rather than from the blocks a partition header sits on. No header goes missing, so the disc looks complete by the partition table's `declared == present` arithmetic — while a tail run of one volume's samples has slid forward, and its directory entry now points at the audio that took its place. D19's payload check refused these and named them (**104** samples across nine discs, e.g. all but one of `Best Service - Alpha Dance II`'s `AC.DRUMLOOPS`); they are now recovered. When a sample's payload is not the file its entry placed, `samplerdisc` searches **backward from the declared position, in the container's own block size, for a header restating that entry's own name and word count** (`size == words×2 + header_len`), stopping at the start of the file's partition, and reads the file from there. **102 of the 104 convert** — `AC.DRUMLOOPS` goes from 1 of 22 written to 22 of 22 — on `AKAI.S3000.Sound.Library.1` and `.5`, `Best Service - Alpha Dance I` and `II`, `AMG - Kickin' Lunatic Beats 2 CD1` and `Global Trance Mission 2`, and `Audio Factory - Classical Wild Takes`. **If you extracted any of those, extract them again.** The two that stay refused are named, not written: `AMG - Loop Soup`'s one record whose start block lands mid-sample (no header earlier to find), and `AKAI.S3000.Sound.Library.3`'s `20 CHINA2-R`, whose only match is a *different* volume's same-named, same-sized file in the previous partition — its bytes, not this one's, so the partition floor refuses it. Displaced programs are left as-is: a program's payload carries no name to confirm a relocation by. ([docs/formats/akai-fs.md](docs/formats/akai-fs.md), [ADR-0045](docs/adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md), [ADR-0027](docs/adr/0027-a-payload-must-be-the-file-its-entry-placed.md), [#35](https://github.com/bmxcode/samplerdisc/issues/35)) + + **The recovery is not blind, and the three measurements #35 asked for are what make it safe.** The displacement is always a whole number of container blocks. The allocation-map chain does *not* notice the gap — it lives in the intact header and describes the disk the rip was made from, so every displaced file's chain still matches its declared size, which means there is no cheaper detector than the payload check. And the name-plus-word-count anchor — D19's name test, which had zero positives on real data until now — matches **exactly one** position per recovered file across the whole collection and never coincides with another intact file's bytes. The suite pins the recovered count per disc, checks each recovered WAV's PCM against the disc's own bytes at the displaced offset, and holds the collection-wide invariant that no sample is written whose payload header names a different file — now over 102 real recoveries rather than trivially. + - **The E-mu `.EBL` reader no longer misreads banks other than Vintage Pro.** D33 shipped the mono reader verified byte-for-byte against Vintage Pro, but three of its constants were that one bank's values rather than the format's, and a second bank — E-mu Classic Series Vol 13 Dance 2000 — exposed all three. The channel count was taken from the two spans' equality, which *inverts* on Dance 2000 (its stereo files have equal spans, its mono files unequal), so the shipped rule would have refused every mono file and passed every stereo file through the mono copy path as noise — the ADR-0026 failure the project guards against. The audio offset assumed an 8-byte pad (`block + 184`); Dance 2000's is 4 (`block + 180`). And the mono length `V4 − V3 + 2` yields 0 there. The reader now reads what generalises: the **channel byte of the `V12` field** (`(V12 >> 16) & 0xFF` — `0x03` stereo, else mono; a `0x02` value is a mono sub-type, 38 files on Vintage Pro, that the naïve reading would have misclassified), the audio **anchored at `V2`** (`block + V2 − 4`, so the pad is read not assumed), and the **length taken to the loop trailer or the end of the file** (which the per-bank field formulas cannot, the length living in a different field on each bank). Verified against two banks' publisher renders: Vintage Pro stays byte-identical (1 007 / 1 007, no regression) and Dance 2000's mono half now decodes PCM byte-for-byte (819 uniquely-named files, the one exception a render hand-resampled 44 001 → 44 100). Stereo is still refused, now for the right reason — the record's channel field — with the interleave deferred to [#57](https://github.com/bmxcode/samplerdisc/issues/57). This is a latent correctness fix in the shipped reader, independent of stereo. ([docs/formats/emu-ebl.md](docs/formats/emu-ebl.md), [#73](https://github.com/bmxcode/samplerdisc/issues/73)) - **A fragmented E-mu `FORM/E4B0` bank no longer loses the samples past its first fragment.** These banks were read straight from the image, contiguously, which is right for every bank on nine discs and every `FORM` bank but one — `Miroslav Vitous … String Ensembles`'s `CES 1`, whose data is three separate cluster runs. The contiguous read stopped at the first break and listed **12** of the bank's **20** samples; the other eight (`CES E_2 2` … `STR:VcsD_5 2`, the upper half of a velocity layer) sat stranded in the tail. `samplerdisc` now reads such a bank along the real **block-2 FAT** — the allocation table every EMU3 disc carries, whose cluster chains say where a file's bytes actually are — so a fragmented bank is gathered from the right clusters and a sample whose audio straddles a fragment boundary is read whole. `Vitous` goes **852 → 860 samples**; the eight are mono one-shots, so its loop and stereo counts are unchanged. **If you extracted this disc, extract it again for the eight.** No other disc changes — every other bank in the collection is contiguous and reads byte-for-byte as before. The FAT also now corroborates every bank/sample address the reader locates, an independent check the per-disc allocation fit never had. ([docs/formats/emu3.md](docs/formats/emu3.md), [ADR-0037](docs/adr/0037-a-fragmented-form-bank-is-read-along-the-fat-chain.md), [#67](https://github.com/bmxcode/samplerdisc/issues/67)) diff --git a/docs/README.md b/docs/README.md index e66ad6e..555b6cc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -76,14 +76,14 @@ All of that vanishes into a working parser. Six months on, the code says *what* | D35 | Loose E-mu `.ebl` banks (Proteus 1/2/3, shipped as files in the clear) convert through a dedicated `extract-banks` source that runs the verified decoder — a directory of sample files is a source, not a container ([ADR-0042](adr/0042-loose-sample-banks-are-a-source-not-a-container.md)) | done | | D36 | E-IV disc provenance read from the sample-free `Credits`/`E-mu Systems 96` text banks' `E4P1` name field — the credit line alone, never the preset — into a per-disc `Credits.txt` sidecar under `--metadata`; eight banks, 89 lines across five discs ([ADR-0043](adr/0043-eiv-credits-are-metadata-read-from-the-e4p1-name-field.md)) | done | | D37 | `eiv-analogia`'s residual E-IV loops given the disc's own confirmation by a period / pre-start window — four of its six splice at their own period as a clear local maximum where the forward oracle had no power; the two that do not (`Conscience Call`, `Got Scratch?`) are named, not hidden. A measurement wired into the suite; no emission, loop count or digest moved ([ADR-0044](adr/0044-the-eiv-residual-loop-is-confirmed-by-its-period.md)) | done | +| D38 | An AKAI sample displaced by a run of blocks lost *inside* a partition the table calls complete is recovered — searched for backward in the container's unit for a header restating the entry's own name and word count, floored at the partition. 102 of the 104 refused across nine discs are written; the two that are not (`Loop Soup`'s mid-sample record, `Library.3`'s cross-partition namesake) are named. The chain cannot see the gap, so the payload check is the sole detector; ADR-0027's name test is the anchor, exercised on real data at last ([ADR-0045](adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md)) | done | Across the local collection, by listing: 96 of 104 images claimed, 4 270 volumes, 161 213 files, 126 361 of them samples. The AKAI discs are 45 of those images and 86 487 of those files, read across 318 partitions — 279 where the disk's table puts them and 39 displaced by blocks the rip lost. Before D15 they were 14 783 files, because only the partition at the origin was read. ## What is not done - **70 declared AKAI partitions are still unread, and 60 of them are not absent.** A header is there and it is inside a partition already being read — 31 would overlap one, 29 land exactly on one. `Best Service - Alpha Dance I` is the whole disc's worth of that: its one displaced partition sits four blocks inside partition 4, so the disc recovers nothing at all. Reading them would mean putting one run of bytes under two partitions' bookkeeping, and this project has no field that says how much shorter than its declared size a partition preceding a gap really is ([ADR-0028](adr/0028-a-displaced-partition-is-anchored-quantised-and-floored.md), [#25](https://github.com/bmxcode/samplerdisc/issues/25)). The other 10 have no header at any position the search may look at. -- **104 AKAI files are displaced inside a partition the table calls complete.** `Best Service - Alpha Dance II` declares six partitions and holds all six, and 21 of `AC.DRUMLOOPS`'s 22 samples are somebody else's audio; `AKAI.S3000.Sound.Library.5`'s recovered partitions lose 23 the same way. The rip dropped a run of blocks *inside* a partition rather than the blocks a header sat on, so nothing in the partition table registers a gap. **The mechanism is now measured rather than supposed: 103 of the 104 are sitting intact, carrying their entry's own name, a whole number of container blocks earlier.** They are still refused and named rather than written ([ADR-0027](adr/0027-a-payload-must-be-the-file-its-entry-placed.md)); recovering them would mean locating a volume's blocks by something other than the chain the allocation map declares, which is the search [ADR-0022](adr/0022-a-volume-is-explained-by-the-allocation-map.md) and [ADR-0023](adr/0023-partitions-come-from-the-table-the-disc-declares.md) both refused, and unlike a partition a file has no declared position to search back from ([#35](https://github.com/bmxcode/samplerdisc/issues/35), [ADR-0028](adr/0028-a-displaced-partition-is-anchored-quantised-and-floored.md)). -- **The AKAI payload name check still has no positives on real data.** It is the test that separates *"this payload is a sample"* from *"this payload is **this** sample"*, and across all 44 discs it now fires 104 times and never once without the id and valid tests having fired too. D20 was the deliverable expected to change that — a displacement landing exactly on another sample's header is the case it exists for, and recovering 15 808 more samples from displaced partitions produced none. It remains exercised only synthetically ([ADR-0027](adr/0027-a-payload-must-be-the-file-its-entry-placed.md)). +- **Two AKAI samples displaced inside a partition cannot be recovered, and are named rather than written.** D38 recovers 102 of the 104 that a run of lost blocks displaced inside a partition the table calls complete — searched for backward by the entry's own name and word count, floored at the partition ([ADR-0045](adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md), [#35](https://github.com/bmxcode/samplerdisc/issues/35)). The two that do not are `AMG - Loop Soup`'s one directory record whose start block lands mid-sample, so no header exists earlier to find, and `AKAI.S3000.Sound.Library.3`'s `20 CHINA2-R`, whose only backward match is a same-named, same-sized file in the previous partition — its bytes, not this file's. Both are refused and named, and the second is the standing proof the partition floor is doing real work ([ADR-0027](adr/0027-a-payload-must-be-the-file-its-entry-placed.md)). - **What wrote the stale partition headers in free space is unestablished.** `ProSamples vol.14` carries 148 byte-identical copies of one, `vol.12` 86, and `Global Trance Mission 2` three distinct ones repeated 288, 58 and 19 times, every one in a block the allocation map calls free. Filler from the mastering and a header from an earlier state of the disk both fit. It matters only as the reason a partition header may never be scanned for, and for that the reading does not need settling ([ADR-0028](adr/0028-a-displaced-partition-is-anchored-quantised-and-floored.md)). - **What the AKAI valid byte's low bits mean is unestablished.** `0x81` on 29 samples and `0x9c` on two, against `0x80` on 56 397. The `0x80` flag is the sample-is-valid bit and the rest is unread; three combinations on two discs is not enough to read them from. diff --git a/docs/adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md b/docs/adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md new file mode 100644 index 0000000..90f430f --- /dev/null +++ b/docs/adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md @@ -0,0 +1,67 @@ +# ADR-0045 · A displaced AKAI sample is recovered by searching backward for its own name and word count, under the partition floor + +**Status:** accepted · 2026-09-05 + +## Context + +[Issue #35](https://github.com/bmxcode/samplerdisc/issues/35) records the fault [ADR-0028](0028-a-displaced-partition-is-anchored-quantised-and-floored.md) deferred: an AKAI rip can lose a run of 32 KB container blocks from *inside* a partition rather than from the blocks a partition header sits on. No header goes missing, so the partition table's declared-against-present arithmetic reads clean and the disc looks whole — while a tail run of one volume's samples has slid forward and now decodes as somebody else's audio. [ADR-0027](0027-a-payload-must-be-the-file-its-entry-placed.md) refuses these and names them: **104 samples across nine discs**, `Best Service - Alpha Dance II`'s `AC.DRUMLOOPS` (21 of 22) the clean specimen, on a disc complete by every other measure. + +ADR-0028 recovered the *sibling* case — a partition header displaced — and explicitly declined this one, "a partition has a declared position to search back from and a file has only the chain its allocation map states." Issue #35 asked for three measurements before any recovery, and they are the reason this is now buildable rather than blind. + +**The displacement is always a whole number of container blocks.** `AC.DRUMLOOPS` shifts one block, then two; `Library.1`'s `3084 B.BEAT6` one; `Library.3`'s one record 134. Every one is an exact multiple of `image.granularity` — 32 768 cooked bytes for these `.mdx` images — the same fault as the short images of [#25](https://github.com/bmxcode/samplerdisc/issues/25), one layer down. + +**The allocation map does not notice, so there is no cheaper detector.** The map lives in the partition header, ahead of the gap and intact, and it describes the disk the rip was *made from*: every displaced file's chain is exactly `ceil(size / BLOCK_SIZE)` blocks long, agreeing with its declared size, because nothing about losing payload bytes changes the metadata in front of them. (The one chain that disagrees anywhere among the 104 is `Loop Soup`'s record whose start block lands mid-sample — a bogus start, not a gap the map caught.) #35 hoped a short chain on these volumes would be a cheap second detector; it is not, and the ADR-0027 payload-header check remains the only structure that sees this at all. That check reads a header per sample already, so nothing cheaper was on offer. + +**The displacement is per file, not a per-volume constant** — `AC.DRUMLOOPS` moves by one block and then by two mid-volume, as a second gap accumulates — so a single correction per volume would be wrong. But searching backward from each declared position, in the container's unit, for a header that restates **this entry's own name and word count**, finds each recoverable file at **exactly one** position, never two, across the whole collection. Name says *which* file; the word-count identity `size == words*2 + header_len` is an independent structure confirming it. This is the "which file is this?" answer ADR-0028 said recovery would need — and it is exactly the name test ADR-0027 built and the docs called "exercised only synthetically." This deliverable exercises it on real data. + +The falsifying case is the whole reason for the floor. On `AKAI.S3000.Sound.Library.3` the one refused record — `VOLUME 001`/`20 CHINA2-R` in partition 12 — has its only backward match **in partition 11**, a *different* volume's `20 CHINA2-R`, same name and same size, intact where it sits. Its bytes belong to that file; writing them under partition 12's entry would be the exact failure ADR-0027 exists to prevent. The search must not leave the file's own partition. + +## Decision + +**A sample whose payload at its declared position is not the file its entry placed is searched for backward, in the container's storage unit, for a header restating this entry's name and word count — and never below the start of its own partition.** Found, it is read from there; not found, it stays refused and named. + +Five parts, deliberately the shape of ADR-0028 one layer down. + +**Only when the declared position fails, and only for samples.** A payload that is already the file its entry placed is read where it sits — every file on a complete image, and the fast path, so a healthy disc pays nothing. Programs are not relocated: the anchor is the payload repeating the directory's name, and a program has no such field to confirm by. + +**Backward from the declared position, in the container's unit.** A short image has *lost* bytes, so everything after a gap moved towards the front and nothing away from it; the real bytes sit a whole number of `image.granularity` blocks earlier. The filesystem asks the container for the unit and does not name it ([ADR-0003](0003-brand-neutral-pluggable-backends.md), ADR-0028). + +**Confirmed by this entry's name and word count.** `is_placed_here` requires id 3, the valid flag, a name equal to the entry's, a plausible rate, and `size == words*2 + header_len`. Placement by the search, confirmation by two independent fields, the shape [ADR-0020](0020-read-e-iv-through-its-sample-directory.md)/[ADR-0021](0021-a-bank-owns-the-run-its-header-declares.md)/ADR-0023/ADR-0028 all use. + +**Never below the partition floor.** This is the whole safety argument and it does all the rejecting: the `Library.3` cross-partition namesake is below the floor and never examined, so it stays refused rather than recovered wrongly. Within a partition, measured across the collection, exactly one position per recovered file passes the anchor and none coincides with any other intact entry's bytes. + +**A recovered sample carries its displacement.** `Extracted.displaced` is the byte distance, per file because it grows down a volume; `list` prints a recovered-count line and `batch` records it per disc. Per file rather than per partition — unlike ADR-0028's partition displacement, which was constant across a partition's thousands of files — because here it varies file to file. + +The result: **102 of the 104 recover** and verify against their own headers; the collection's written samples rise by 102 and its refused-mismatch count falls from 104 to **2**. The two are named, not hidden: `Loop Soup`'s one directory record whose start block lands mid-sample (no header exists earlier to find), and `Library.3`'s `20 CHINA2-R`, whose only match is the cross-partition namesake the floor refuses. ADR-0028's loose "103 found intact" figure counted that namesake as a find; it is not a safe recovery, and this record corrects it to 102. + +## Alternatives rejected + +**Leave them refused (ADR-0027's conservatism).** The right answer while a recovered payload could not be told from a coincidence. It can now: name and word count give exactly one within-partition match per file and zero collisions with any intact entry, measured across the collection. Refusing readable audio that proves it is the file its entry placed, on a rule whose stated reason has been answered, is not conservatism. + +**Recover by one displacement constant per volume.** Simpler, and wrong: `AC.DRUMLOOPS` displaces by one block and then two as a second gap accumulates mid-volume. Each file must confirm its own displacement, which the per-file anchor does. + +**Drop the partition floor, or loosen it to the disc origin.** This is what the `Library.3` case forbids: without the floor its record's nearest match is a different volume's same-named, same-sized sample in the previous partition, and recovering it would put one sample's audio under another's name. The floor is not a cost bound that happens to be safe — it is the safety. + +**Anchor on the name alone, or the word count alone.** Name alone admits the `Library.3` namesake (same name, different file); word count alone admits any same-sized sample. Together, under the floor, they are unambiguous. Both are kept. + +**Recover programs too.** A program's payload does not repeat its directory name, so there is no field to confirm a relocation by — the anchor that makes this safe does not exist for them. A displaced program stays where its entry puts it; if a specimen shows this costs real files, it gets its own issue. + +**Walk the allocation-map chain to place a file's blocks.** The map is in the intact header and describes the original disk, so it is blind to the gap (measured: every damaged file's chain equals its declared length). It cannot place the moved bytes, and reading a file by its map chain rather than its contiguous extent is the search ADR-0022 and ADR-0023 refused for other reasons. + +**Search forward as well as backward.** A rip makes an image short, never long; every one of the 104 is displaced towards the front. Forward search would double the candidates for a fault nothing produces (ADR-0028 rejected the same for partitions). + +## Consequences + +**Good, and the headline.** 102 samples on nine discs that were refused as somebody else's audio are now written, each read from where its own header sits and each verified by name and word count against the directory entry that placed it. `Alpha Dance II`'s `AC.DRUMLOOPS` goes from 1 of 22 to 22 of 22. + +**Good.** ADR-0027's name test finally has positives on real data — 102 of them — and is the load-bearing anchor rather than a synthetic-only check. `test_an_akai_payload_is_never_written_under_another_files_name` stops holding trivially and starts holding because the recovery respects it. + +**Good.** The `declared == present` caveat #35 insisted on keeping is now backed by a recovery rather than only a refusal: a complete-looking image with an internal gap says so, in the recovered-count line, per disc. + +**Bad, and stated plainly.** Two samples stay refused. `Loop Soup`'s record genuinely has no header to find; `Library.3`'s has one, and it is the wrong file's. Both are named, and the second is the standing proof that the floor is doing real work. + +**Bad.** Extraction on nine discs writes 102 files that were not there before, and `--keep-originals` writes their `.s3s`/`.s1s` from the displaced offset too. Anyone who extracted those discs should do it again. + +**Watch for.** A disc where two same-named, same-sized samples sit within *one* partition, one displaced onto the other. The floor does not protect against that; the word-count identity and the single-match measurement are what would, and a second match appearing where the collection shows exactly one is the signal that the anchor has weakened. The measurement is wired into the suite for that reason. + +**Watch for.** `Extracted.displaced` growing meanings. It is the byte distance a sample's bytes were found from where its entry declared them, and nothing else — not an alignment, not a container fact. The container's `granularity` says what the rip lost whole numbers of; this says how many of them fell in front of one file. diff --git a/docs/adr/README.md b/docs/adr/README.md index 83c524d..2ae103b 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -50,3 +50,4 @@ If you find yourself writing an ADR with no rejected alternative, you are writin | [0042](0042-loose-sample-banks-are-a-source-not-a-container.md) | A loose `.ebl` bank is converted as a source (a dedicated `extract-banks` verb running the verified decoder), not forced through the container/filesystem stack — reversing ADR-0033/0041's refusal to serve bare bank folders now they are content the user holds, not a test fixture | Keeping the refusal; modelling the directory as a `Backend` over a synthetic `SectorImage`; overloading `extract` to accept a directory | | [0043](0043-eiv-credits-are-metadata-read-from-the-e4p1-name-field.md) | E-IV credits are metadata, read from the `E4P1` name field alone — a per-disc `Credits.txt` sidecar under `--metadata`, from the sample-free `Credits`/`E-mu Systems 96` text banks, never the preset | Reading the `TOC1` concatenation instead; dumping every disc's TOC and preset names; folding the sidecar into `--keep-originals`; always writing `Credits.txt`; carrying the credits in a WAV `LIST`/`INFO` chunk | | [0044](0044-the-eiv-residual-loop-is-confirmed-by-its-period.md) | The E-IV residual loop is confirmed by its period — the pre-start window, which survives on a loop running to the last frame — not the forward window; wired into the suite as a disc-local oracle, not the parser | The forward window (no power on a near-whole-extent loop); a wrong-start control (a sustained tone self-correlates); dropping `Conscience Call`/`Got Scratch?` from emission; stating the borrowed evidence in docs only | +| [0045](0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md) | A sample displaced by blocks lost inside its partition is recovered by searching backward in the container's unit for a header restating this entry's name and word count, floored at the partition — 102 of 104, ADR-0027's name test the anchor at last | Leaving them refused; one displacement constant per volume; dropping or loosening the partition floor (the `Library.3` namesake); anchoring on name or word count alone; recovering programs; walking the map chain; searching forward | diff --git a/docs/formats/akai-fs.md b/docs/formats/akai-fs.md index e73ea09..84968df 100644 --- a/docs/formats/akai-fs.md +++ b/docs/formats/akai-fs.md @@ -171,7 +171,7 @@ A short image also shows up in the table's arithmetic alone: `Kickin' Lunatic Be The visible consequence inside partition 1 is not only the four empty volumes. **Nine files in `13-TRACK 06` no longer hold their own audio**: everything past the first gap has slid, so their payload is mid-PCM rather than a header. They are refused and named, one line each saying which fields disagree and which entry placed them ([ADR-0027](../adr/0027-a-payload-must-be-the-file-its-entry-placed.md)). [Issue #23](https://github.com/bmxcode/samplerdisc/issues/23) proposed that check believing they were being written out; they were already being refused, with a message that said neither which test failed nor that a directory entry was involved. -The same damage appears **without a partition going missing**, which is worth stating separately because the table's arithmetic cannot see it. `Alpha Dance II` declares six partitions and holds all six, and 21 of `AC.DRUMLOOPS`'s 22 samples are displaced; `AKAI.S3000.Sound.Library.1` and `.3` are the same shape, 25 files across the three. The rip lost a run of blocks inside a partition rather than the blocks a header sat on. +The same damage appears **without a partition going missing**, which is worth stating separately because the table's arithmetic cannot see it. `Alpha Dance II` declares six partitions and holds all six, and 21 of `AC.DRUMLOOPS`'s 22 samples are displaced; `AKAI.S3000.Sound.Library.1` and `.3` are the same shape. The rip lost a run of blocks inside a partition rather than the blocks a header sat on, so it is the payload check — never the partition table — that catches it, and D38 recovers the file from its own header a whole number of container blocks earlier (*The payload repeats what the directory said* below, [ADR-0045](../adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md)). Observed volume names, useful as a smoke test that charset and offsets are both right: @@ -273,27 +273,37 @@ Nine of the 44 discs are affected: `AKAI.S3000.Sound.Library.1`–`7` (4 451, 3 Every sample payload restates the file's id, its valid flag and its name, and the directory entry states the name and the size independently. Where they disagree, the payload is not the file the entry placed and it is refused rather than written under that entry's name — a WAV that opens, plays, and is somebody else's audio is the worst failure this format offers ([ADR-0027](../adr/0027-a-payload-must-be-the-file-its-entry-placed.md), [issue #23](https://github.com/bmxcode/samplerdisc/issues/23)). -**104 of the 72 298 samples disagree**, on nine discs; the other 35 have none. The name test's unique catch is still **zero** — every payload whose name disagrees also has a wrong id and a cleared valid flag, because a displacement lands mid-audio and mid-audio does not look like a header. It is kept anyway: the other three ask whether the payload is *a* sample, and only this one asks whether it is *this* sample. +**104 of the 72 298 samples disagree at their declared position**, on nine discs; the other 35 have none. Almost all are a *displacement*, not damage: the run has slid forward inside its partition and the real bytes sit a whole number of container blocks earlier, carrying the file's own header — so the payload that disagrees at the declared offset is somebody else's audio, and the file itself is intact a little way back. D38 reads it from there ([ADR-0045](../adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md); see *Recovering a sample the rip displaced* below), so **102 of the 104 recover** and only **2 stay refused**. The name test that was "zero unique catch" through D20 is now the anchor those 102 recoveries turn on: it is what says a candidate position holds *this* file, where the id and valid flag only say it holds *a* sample. -Where they are: +Where the 104 are, and what becomes of them: -| Disc | Mismatches | Where | Partitions declared / read | +| Disc | Displaced | Where | Recovered | |---|---:|---|---| -| `AKAI.S3000.Sound.Library.5` | 30 | `HIT NOISE` last 17 of 20, `SURDO` last 7 of 13, `BELL TREE` last 6 of 13 | 9 / 6 | -| `Kickin' Lunatic Beats 2 CD1` | 24 | `09-TRACK 37` last 15 of 26, `13-TRACK 06` last 9 of 20 | 11 / 8 | -| `Best Service - Alpha Dance II` | 21 | `AC.DRUMLOOPS`, last 21 of 22 | **6 / 6** | -| `Best Service - Alpha Dance I` | 15 | `ATTACK BANK2`, last 15 of 18 | 5 / 4 | -| `AMG - Global Trance Mission 2` | 8 | `SYNTH 10` last 5 of 6, `AMBIENT PAD2` last 3 of 6 | 9 / 7 | -| `AKAI.S3000.Sound.Library.1` | 3 | `3084 B.BEAT6`, last 3 of 8 | 13 / 13 | -| `AKAI.S3000.Sound.Library.3` | 1 | `VOLUME 001`, its only file | 13 / 13 | -| `Audio Factory - Classical Wild Takes` | 1 | `VOLUME 002`, last of 2 | 11 / 10 | -| `AMG - Loop Soup` | 1 | `SOUP 101-103`, entry 27 of 39 | 9 / 9 | +| `AKAI.S3000.Sound.Library.5` | 30 | `HIT NOISE` last 17 of 20, `SURDO` last 7 of 13, `BELL TREE` last 6 of 13 | 30 | +| `Kickin' Lunatic Beats 2 CD1` | 24 | `09-TRACK 37` last 15 of 26, `13-TRACK 06` last 9 of 20 | 24 | +| `Best Service - Alpha Dance II` | 21 | `AC.DRUMLOOPS`, last 21 of 22 | 21 | +| `Best Service - Alpha Dance I` | 15 | `ATTACK BANK2`, last 15 of 18 | 15 | +| `AMG - Global Trance Mission 2` | 8 | `SYNTH 10` last 5 of 6, `AMBIENT PAD2` last 3 of 6 | 8 | +| `AKAI.S3000.Sound.Library.1` | 3 | `3084 B.BEAT6`, last 3 of 8 | 3 | +| `Audio Factory - Classical Wild Takes` | 1 | `VOLUME 002`, last of 2 | 1 | +| `AKAI.S3000.Sound.Library.3` | 1 | `VOLUME 001`, its only file | **0** | +| `AMG - Loop Soup` | 1 | `SOUP 101-103`, entry 27 of 39 | **0** | -Four more samples are refused for a corrupt rate byte with an otherwise perfect header — `EG 2MUTE` at 0 Hz, `M.VOICE A1` and `SYN 1` at 519, `HOUSE BASS` at 1280. Those *are* the files their entries placed, with one field unusable, and are counted apart. +Four more samples are refused for a corrupt rate byte with an otherwise perfect header — `EG 2MUTE` at 0 Hz, `M.VOICE A1` and `SYN 1` at 519, `HOUSE BASS` at 1280. Those *are* the files their entries placed, with one field unusable, and are counted apart; the recovery does not touch them. -**103 of the 104 are a run to the end of one volume**, which is what a lost run of blocks looks like from inside a directory; the exception is `Loop Soup`'s one directory record whose start block lands mid-sample. And the run is a *displacement*, now measured rather than inferred: **103 of the 104 refused payloads are sitting intact, carrying their entry's own name, a whole number of container blocks earlier** — one block back for `Alpha Dance II`'s 21, 134 for `Library.3`'s one, one to four for the rest. Recovering them is [issue #35](https://github.com/bmxcode/samplerdisc/issues/35) and is not done: a partition has a declared position to search back from and a file has only the chain its allocation map states ([ADR-0028](../adr/0028-a-displaced-partition-is-anchored-quantised-and-floored.md)). +**The two that do not recover are the interesting ones.** `Loop Soup`'s record's start block lands mid-sample, so there is no earlier header to find. `Library.3`'s `VOLUME 001`/`20 CHINA2-R` has one — but it is a *different* volume's `20 CHINA2-R` in the previous partition, same name and same size, intact where it sits. Its bytes belong to that file, and the recovery refuses to leave the partition rather than write them here. Both stay refused and named ([ADR-0045](../adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md)). -**A tail run does not require a missing partition.** `Alpha Dance II` declares six partitions and holds all six; `Library.1` and `Library.3` likewise. Their damage is a run of blocks lost *inside* a partition, so no header goes missing and the table's declared-against-present arithmetic sees nothing. Declared equalling present is not a clean bill of health. +**A tail run does not require a missing partition.** `Alpha Dance II` declares six partitions and holds all six; `Library.1` and `Library.3` likewise. Their damage is a run of blocks lost *inside* a partition, so no header goes missing and the table's declared-against-present arithmetic sees nothing. Declared equalling present is not a clean bill of health — which is why the payload check, and now the recovery, are the only structures that see this. + +### Recovering a sample the rip displaced + +A gap inside a partition removes whole container blocks, so a file after it sits that much nearer the front while its directory entry — in the intact header ahead of the gap — still points where the file was on the disk. Its real bytes are therefore a whole number of container blocks before the declared position, carrying the file's own header. The recovery searches **backward from the declared position, in the container's storage unit, for a header restating this entry's name and word count** (`size == words*2 + header_len`), and **stops at the start of the file's own partition** ([ADR-0045](../adr/0045-a-displaced-sample-is-recovered-by-its-own-name-and-word-count.md), [issue #35](https://github.com/bmxcode/samplerdisc/issues/35)). + +Three measurements make this a recovery and not a scan: + +- **The displacement is always a whole number of container blocks** — one block for `Alpha Dance II`'s first refused file and two for the rest, 134 for `Library.3`'s namesake, one to a few elsewhere. +- **The allocation map does not notice, so there is no cheaper detector.** The map is in the intact header and describes the disk the rip was made from: every displaced file's chain is still exactly as long as its declared size demands. A short chain on these volumes would have been a cheaper check than reading a payload header per sample; there is none. The payload check is the only structure that sees the gap. +- **Exactly one position per recovered file passes the anchor**, and none coincides with any other intact entry's bytes — which is why the partition floor, not a match count, is the safety. `Library.3` is the standing proof: its only match is the cross-partition namesake, below the floor, refused. ## Where a directory ends diff --git a/src/samplerdisc/batch.py b/src/samplerdisc/batch.py index 0cbee13..7676103 100644 --- a/src/samplerdisc/batch.py +++ b/src/samplerdisc/batch.py @@ -65,6 +65,12 @@ class DiscReport: #: filesystem and the data have come apart, which on these discs means the #: image is short of the disc it was made from (ADR-0027). mismatches: int = 0 + #: Samples written whose bytes were displaced inside a partition by blocks + #: the rip lost and recovered a whole number of container blocks earlier, + #: each confirmed by its own header (issue #35, ADR-0045). A subset of + #: ``samples``: says how many of them the image would have had wrong, or + #: refused, before recovery. + recovered: int = 0 audio_tracks: int = 0 skipped: list[dict[str, object]] = field(default_factory=list) error: str | None = None @@ -141,6 +147,8 @@ def convert_disc( report.samples += 1 if result.channels > 1: report.stereo_samples += 1 + if result.displaced: + report.recovered += 1 entry = volumes.setdefault( (result.partition, result.volume), {"name": result.volume, "partition": result.partition, "samples": 0}, @@ -242,6 +250,7 @@ def write_manifest(path: str, reports: list[DiscReport]) -> None: "skipped": sum(len(r.skipped) for r in reports), "duplicates": sum(r.duplicates for r in reports), "mismatches": sum(r.mismatches for r in reports), + "recovered": sum(r.recovered for r in reports), }, } directory = os.path.dirname(os.path.abspath(path)) diff --git a/src/samplerdisc/cli.py b/src/samplerdisc/cli.py index ef1f514..a3badbd 100644 --- a/src/samplerdisc/cli.py +++ b/src/samplerdisc/cli.py @@ -118,6 +118,7 @@ def cmd_extract(args: argparse.Namespace) -> int: skipped = 0 duplicates = 0 mismatches = 0 + recovered = 0 credited: Credited | None = None results = extract_disc( image, @@ -137,6 +138,8 @@ def cmd_extract(args: argparse.Namespace) -> int: written += 1 if result.channels > 1: stereo += 1 + if result.displaced: + recovered += 1 if args.verbose: seconds = result.frames / result.rate if result.rate else 0 channels = "stereo" if result.channels > 1 else "mono" @@ -175,6 +178,12 @@ def cmd_extract(args: argparse.Namespace) -> int: # Not damage, and saying so matters: a disc that lists 423 skips reads # as a bad rip when every one of them is a sound already written. print(f"skipped {duplicates} duplicates of audio already written") + if recovered: + # The image is short of its disc by blocks lost *inside* a partition, + # so these samples' bytes slid forward and were read a whole number of + # container blocks earlier, each confirmed by its own header carrying + # this entry's name and word count (issue #35, ADR-0045). + print(f"recovered {recovered} samples displaced inside a partition by lost blocks") if mismatches: # The loudest line on a short image, and the one ADR-0012's argument # applies to: a payload that is not the file the directory placed is diff --git a/src/samplerdisc/extract.py b/src/samplerdisc/extract.py index f4479a4..2836939 100644 --- a/src/samplerdisc/extract.py +++ b/src/samplerdisc/extract.py @@ -97,6 +97,14 @@ class Extracted: #: (ADR-0026) or a stereo AIFF -- which is a different thing from the #: ``Joined`` file an -L/-R pair produces, and counted apart from it. channels: int = 1 + #: Bytes this sample's payload was displaced by inside its partition, 0 for + #: one sitting where its entry placed it. Non-zero says the image is short + #: of the disc it was made from: a run of container blocks was lost *inside* + #: a partition the table calls complete, so this file's bytes slid forward + #: and were recovered a whole number of blocks earlier, carrying its own + #: header (issue #35, ADR-0045). Per file, because the displacement grows + #: down a volume as gaps accumulate rather than being one constant. + displaced: int = 0 @dataclass @@ -247,8 +255,17 @@ def extract_volume( continue if entry.kind != "sample": continue + # A backend whose container can be short of its disc reports where the + # file's bytes really are and how far they were displaced; the rest + # place every file where its entry declares (ADR-0045). + placement = getattr(backend, "placement", None) + displaced = 0 try: - payload = backend.read_file(image, origin, entry) + if placement is not None: + read_offset, displaced = placement(image, origin, entry) + payload = image.read(read_offset, entry.size) + else: + payload = backend.read_file(image, origin, entry) except OSError as exc: # pragma: no cover - filesystem-level failure yield Skipped(volume.name, entry.name, f"unreadable: {exc}", volume.partition) continue @@ -308,6 +325,7 @@ def extract_volume( pitch=pitch if pitch is not None else 0, partition=volume.partition, channels=channels, + displaced=displaced, ) for entry in deferred: diff --git a/src/samplerdisc/fs/akai.py b/src/samplerdisc/fs/akai.py index 5666393..00c2d76 100644 --- a/src/samplerdisc/fs/akai.py +++ b/src/samplerdisc/fs/akai.py @@ -276,6 +276,67 @@ def displaced_header( return None +#: Bytes read at a candidate position to test whether a sample header sits +#: there. The last field the anchor reads is the rate at 138, so 256 is ample +#: and one short read per candidate -- the payload itself is fetched once, only +#: after the search settles. +_SAMPLE_HEADER_PROBE = 256 + + +def displaced_sample(image: SectorImage, origin: int, entry: File) -> int | None: + """Where a sample's real bytes are, when a run of blocks was lost *inside* + its partition (issue #35, ADR-0045). + + This is ``displaced_header`` one layer down, and it carries the same three + load-bearing words. It searches **backwards from the byte position the + directory entry places this file at**, in **the container's own storage + unit**, for a header that restates **this entry's own name and word count** + -- and it **stops at the start of the entry's own partition**. Returns the + offset or None. + + A gap inside a partition removes whole container blocks, so every file after + it sits that much nearer the front while its directory entry -- in the intact + header ahead of the gap -- still points where the file was on the disk. The + real bytes are therefore a whole number of container blocks before the + declared position, carrying the file's own header (ADR-0027's identity, now + the anchor rather than only the refusal). + + **The floor is the partition, and it is the whole safety argument.** On + `AKAI.S3000.Sound.Library.3` the one refused file's only backward match is a + *different* volume's `20 CHINA2-R` in the previous partition -- same name, + same size, intact where it sits. Its bytes belong to that file; writing them + here would be the one failure ADR-0027 exists to prevent. Flooring at the + partition start refuses it, so that file stays named rather than recovered + wrongly. Within a partition no such collision occurs: across the collection + exactly one position per recovered file passes the anchor, never two. + """ + step = image.granularity + if step <= 0: + return None + s3000 = bool(entry.raw_type & 0x80) + floor = origin + entry.origin + declared = floor + entry.start_block * BLOCK_SIZE + position = declared - step + while position >= floor: + head = image.read(position, _SAMPLE_HEADER_PROBE) + if _placed_here(head, entry.name, entry.size, s3000): + return position + position -= step + return None + + +def _placed_here(payload: bytes, name: str, size: int, s3000: bool) -> bool: + """``sample.akai.is_placed_here``, imported late to break the import cycle. + + ``sample.akai`` imports the charset and name helpers from this module, so a + top-level import would be circular -- the same reason ``parse_sample`` + imports it inside the method. + """ + from samplerdisc.sample.akai import is_placed_here + + return is_placed_here(payload, name, size, s3000) + + def partitions(image: SectorImage, origin: int) -> Iterator[Partition]: """Every partition of the disk that this image actually holds. @@ -598,11 +659,45 @@ def _files( origin=partition_offset, ) + def placement(self, image: SectorImage, origin: int, entry: File) -> tuple[int, int]: + """Where to read this file from, and how far it is displaced (bytes). + + The declared position and 0 for every file that is where its entry puts + it -- which is all of them on a complete image and the fast path here. + When a sample's payload at the declared position is *not* the file its + entry placed, though, the image may be short of the disc it was made + from by whole container blocks lost *inside* a partition: the real bytes + then sit that much earlier, still carrying this file's own header, and + ``displaced_sample`` finds them under the partition floor (issue #35, + ADR-0045). + + Only samples relocate: the anchor that makes the search safe is the + payload repeating the directory's name and word count, and a program has + no such field to confirm by (ADR-0045). A sample that finds nothing -- + `Loop Soup`'s mid-sample record, `Library.3`'s cross-partition namesake, + a corrupt-in-place rate byte -- stays at its declared position and is + refused and named downstream exactly as before. + """ + declared = origin + entry.origin + entry.start_block * BLOCK_SIZE + if entry.kind != "sample": + return declared, 0 + head = image.read(declared, _SAMPLE_HEADER_PROBE) + if _placed_here(head, entry.name, entry.size, bool(entry.raw_type & 0x80)): + return declared, 0 + found = displaced_sample(image, origin, entry) + if found is None: + return declared, 0 + return found, declared - found + def read_file(self, image: SectorImage, origin: int, entry: File) -> bytes: # entry.origin is where the file's partition begins; its start block is # relative to that, so the same number in two partitions is two - # different files and dropping the term reads the wrong audio. - return image.read(origin + entry.origin + entry.start_block * BLOCK_SIZE, entry.size) + # different files and dropping the term reads the wrong audio. A sample + # displaced by blocks the rip lost inside its partition is read from + # where its own header actually sits, so every consumer -- the WAV path, + # --keep-originals, the stereo joiner -- gets the real bytes (ADR-0045). + offset, _ = self.placement(image, origin, entry) + return image.read(offset, entry.size) def layout(self, image: SectorImage, offset: int) -> str: """One line on how the disk is divided, for ``list``. diff --git a/src/samplerdisc/fs/base.py b/src/samplerdisc/fs/base.py index cdd58b7..8628ca2 100644 --- a/src/samplerdisc/fs/base.py +++ b/src/samplerdisc/fs/base.py @@ -124,6 +124,20 @@ def read_file(self, image: SectorImage, offset: int, entry: File) -> bytes: """Return the raw bytes of one file.""" ... + def placement(self, image: SectorImage, offset: int, entry: File) -> tuple[int, int]: + """``(byte offset to read this file from, bytes it is displaced by)``. + + Optional. The declared position and 0 for a file that is where its + directory entry puts it, which is every file on a complete image. A + backend whose container can be *short of the disc it was made from* -- + whole units lost inside it, so a file's bytes sit nearer the front than + its entry declares -- may relocate the read here and report the + distance, which ``list`` and the manifest surface. AKAI is the only one + today (issue #35, ADR-0045). A backend that does not implement it has + every file at its declared position, which ``read_file`` reads. + """ + ... + def original_suffix(self, entry: File) -> str: """Filename suffix for this file's bytes as stored on disc. diff --git a/src/samplerdisc/sample/akai.py b/src/samplerdisc/sample/akai.py index f9e8688..2ad7d93 100644 --- a/src/samplerdisc/sample/akai.py +++ b/src/samplerdisc/sample/akai.py @@ -152,6 +152,39 @@ def _check_identity(payload: bytes, declared_name: str | None) -> str: return name +def header_len(s3000: bool) -> int: + """The bytes in front of the audio: 192 on the S3000 family, 150 on S1000.""" + return HEADER_LEN_S3000 if s3000 else HEADER_LEN_S1000 + + +def is_placed_here(payload: bytes, declared_name: str, declared_size: int, s3000: bool) -> bool: + """Is *this* directory entry's sample header sitting at the front of ``payload``? + + The full anchor a displaced-sample search confirms a candidate position by, + read from the header alone (~192 bytes): the id, the valid flag, the name + equal to the entry's, a plausible rate, and the word-count identity the + directory's declared size states independently -- ``size == words*2 + + header_len``. Name says *which* file this is; the word count is a second + structure confirming it, which is the shape ADR-0028 recovers a partition + by, one layer down. It is what makes searching backward for a lost run of + blocks a confirmation rather than a scan: on the 103 recoverable payloads + across the collection exactly one backward position passes this, never two + (ADR-0045, #35). + """ + if len(payload) <= OFF_RATE + 2: + return False + if payload[OFF_ID] != SAMPLE_ID or not payload[OFF_VALID] & VALID_FLAG: + return False + raw = payload[OFF_NAME : OFF_NAME + NAME_LEN] + if not is_plausible_name(raw) or decode_name(raw) != declared_name: + return False + (rate,) = struct.unpack_from(" bytearray: + """A flat image with ``sample`` at byte ``real`` and mid-audio at the + entry's declared position -- the shape a run of blocks lost inside a + partition produces.""" + from samplerdisc.fs.akai import BLOCK_SIZE + + declared = part_off + start_block * BLOCK_SIZE + data = bytearray(declared + BLOCK_SIZE) + if real is not None: + data[real : real + len(sample)] = sample + # The declared position holds mid-PCM, not a header -- what the slide leaves. + data[declared : declared + size] = b"\x11" * size + return data + + +def test_a_sample_displaced_inside_its_partition_is_recovered(tmp_path): + """A gap inside a partition pulls a sample's bytes a whole container unit + towards the front; placement finds them by the entry's own header and the + read follows (ADR-0045).""" + from samplerdisc.fs.akai import BLOCK_SIZE + from samplerdisc.fs.base import File + + sample = fixtures.akai_sample("KICK 1") # 278 bytes, S1000 header + start_block, unit = 10, 32768 + declared = start_block * BLOCK_SIZE + real = declared - unit + image = image_of(tmp_path, bytes(_sample_at(len(sample), start_block, 0, real, sample))) + entry = File("KICK 1", "sample", len(sample), start_block, raw_type=0x73, origin=0) + assert BACKEND.placement(image, 0, entry) == (real, unit) + assert BACKEND.read_file(image, 0, entry) == sample + + +def test_a_sample_already_where_its_entry_places_it_is_not_searched_for(tmp_path): + """The fast path: a correct payload relocates nothing and reports 0.""" + from samplerdisc.fs.akai import BLOCK_SIZE + from samplerdisc.fs.base import File + + sample = fixtures.akai_sample("KICK 1") + start_block = 10 + declared = start_block * BLOCK_SIZE + data = bytearray(declared + BLOCK_SIZE) + data[declared : declared + len(sample)] = sample + image = image_of(tmp_path, bytes(data)) + entry = File("KICK 1", "sample", len(sample), start_block, raw_type=0x73, origin=0) + assert BACKEND.placement(image, 0, entry) == (declared, 0) + + +def test_a_sample_with_no_header_to_find_stays_at_its_declared_position(tmp_path): + """`Loop Soup`'s residual: nothing matches, so it stays refused downstream.""" + from samplerdisc.fs.akai import BLOCK_SIZE + from samplerdisc.fs.base import File + + sample = fixtures.akai_sample("KICK 1") + start_block = 10 + declared = start_block * BLOCK_SIZE + image = image_of(tmp_path, bytes(_sample_at(len(sample), start_block, 0, None, sample))) + entry = File("KICK 1", "sample", len(sample), start_block, raw_type=0x73, origin=0) + assert BACKEND.placement(image, 0, entry) == (declared, 0) + + +def test_a_sample_is_never_recovered_from_before_its_partition(tmp_path): + """`Library.3`'s case, and the whole safety argument. + + The only matching header is a same-named, same-sized file in the previous + partition, below the floor. Taking it would write one sample's audio under + another's name, so the search refuses to leave the partition and the sample + stays a mismatch (ADR-0045, ADR-0027). + """ + from samplerdisc.fs.akai import BLOCK_SIZE, _placed_here + from samplerdisc.fs.base import File + + sample = fixtures.akai_sample("KICK 1") + part_off, start_block, unit = 20 * BLOCK_SIZE, 5, 32768 + declared = part_off + start_block * BLOCK_SIZE + below = part_off - unit # a valid namesake header, but before the partition + image = image_of(tmp_path, bytes(_sample_at(len(sample), start_block, part_off, below, sample))) + entry = File("KICK 1", "sample", len(sample), start_block, raw_type=0x73, origin=part_off) + # The match really is there ... + assert _placed_here(image.read(below, 256), "KICK 1", len(sample), False) + # ... and is refused for being below the partition floor. + assert BACKEND.placement(image, 0, entry) == (declared, 0) + + +def test_a_displaced_program_is_not_relocated(tmp_path): + """Only samples relocate: a program's payload has no name to confirm by.""" + from samplerdisc.fs.akai import BLOCK_SIZE + from samplerdisc.fs.base import File + + start_block = 10 + declared = start_block * BLOCK_SIZE + image = image_of(tmp_path, bytes(bytearray(declared + BLOCK_SIZE))) + entry = File("PROG 1", "program", 278, start_block, raw_type=0x70, origin=0) + assert BACKEND.placement(image, 0, entry) == (declared, 0) + + def test_the_search_steps_in_the_unit_the_container_states(tmp_path): """The step is the container's word, not the filesystem's guess (ADR-0003). diff --git a/tests/test_batch.py b/tests/test_batch.py index 1b89c15..e4c1301 100644 --- a/tests/test_batch.py +++ b/tests/test_batch.py @@ -136,6 +136,7 @@ def test_manifest_records_totals_and_failures(tmp_path): "skipped": 0, "duplicates": 0, "mismatches": 0, + "recovered": 0, } failed = [d for d in payload["discs"] if d["error"]] assert len(failed) == 1 diff --git a/tests/test_discs.py b/tests/test_discs.py index 0a8457c..c20e5a6 100644 --- a/tests/test_discs.py +++ b/tests/test_discs.py @@ -1963,43 +1963,51 @@ def test_akai_discs_list_their_volumes_and_files(label: str) -> None: #: displacement that stopped being one would mean the search had begun stepping #: in something that is not the container's unit. #: -#: The last five columns are for the **displaced partitions alone**, not the -#: whole disc, which is the same reasoning as `_AKAI_FIRST_PARTITION` the other -#: way round: pinned apart, they say what recovery contributed rather than -#: leaving it to be subtracted. `refused` counts payloads that are not the file -#: their entry placed, and it is pinned as tightly as the rest -- 43 of the -#: 15 808 recovered samples, 99.7 % passing, is what says these partitions are -#: the disc's own and not something header-shaped (ADR-0027). +#: The last columns are for the **displaced partitions alone**, not the whole +#: disc, which is the same reasoning as `_AKAI_FIRST_PARTITION` the other way +#: round: pinned apart, they say what recovery contributed rather than leaving +#: it to be subtracted. `refused` counts payloads that are not the file their +#: entry placed. It was 43 across these partitions when D20 shipped -- a gap +#: inside a displaced partition displacing a file a second time, which the +#: partition-level search could not follow; D38 now recovers those by the file's +#: own name and word count, so `refused` is 0 here and `recovered` carries what +#: it caught (ADR-0027, ADR-0045, issue #35). #: ``label: (size, declared, present, {index: displacement in blocks}, volumes, -#: files, samples, written, refused)``. +#: files, samples, written, refused, recovered)``. ``recovered`` counts, of the +#: written samples in the displaced partitions, how many had *also* slipped by a +#: gap inside the partition and were read back a whole number of container blocks +#: earlier, confirmed by their own name and word count (issue #35, ADR-0045). It +#: is what once was ``refused`` on the three discs that carried a second gap: +#: `Library.5`, `Global Trance Mission 2` and `Kickin' CD1` recover 23, 5 and 15 +#: this way, so their displaced partitions now refuse nothing. _AKAI_SHORT = { "AMG - Kickin' Lunatic Beats 2 AKAI CD1": ( 378_443_564, 11, 8, {3: 52, 4: 52, 5: 52, 6: 52, 7: 52, 8: 52, 10: 200}, - 121, 7723, 7308, 7293, 15, + 121, 7723, 7308, 7308, 0, 15, ), "AMG - Kickin' Lunatic Beats 2 AKAI CD2": ( 371_768_845, 9, 8, {3: 4, 4: 4, 5: 4, 6: 4, 7: 4, 8: 4, 9: 4}, - 100, 6203, 5912, 5912, 0, + 100, 6203, 5912, 5912, 0, 0, ), "AKAI.S3000.Sound.Library.5": ( - 294_252_089, 9, 6, {5: 12, 7: 32, 8: 32}, 34, 473, 400, 377, 23, + 294_252_089, 9, 6, {5: 12, 7: 32, 8: 32}, 34, 473, 400, 400, 0, 23, ), "AKAI.S3000.Sound.Library.6": ( 320_291_524, 9, 8, {3: 68, 4: 68, 5: 68, 6: 68, 7: 68, 8: 68, 9: 68}, - 84, 1054, 955, 955, 0, + 84, 1054, 955, 955, 0, 0, ), "AKAI.S3000.Sound.Library.7": ( - 221_665_577, 11, 4, {3: 5508, 4: 2028, 5: 512}, 20, 660, 546, 546, 0, + 221_665_577, 11, 4, {3: 5508, 4: 2028, 5: 512}, 20, 660, 546, 546, 0, 0, ), "Back In Time Rrcords - Elektra Vox AKAI": ( 353_568_222, 13, 6, {3: 488, 5: 964, 7: 1844, 9: 2664, 11: 1928}, - 33, 661, 463, 463, 0, + 33, 661, 463, 463, 0, 0, ), "AMG - Global Trance Mission 2 AKAI": ( - 392_438_329, 9, 7, {6: 8, 7: 8, 9: 32}, 22, 217, 144, 139, 5, + 392_438_329, 9, 7, {6: 8, 7: 8, 9: 32}, 22, 217, 144, 144, 0, 5, ), "Audio Factory - Classical Wild Takes AKAI": ( - 226_074_906, 11, 10, {8: 16, 9: 16, 10: 16, 11: 16}, 18, 189, 80, 80, 0, + 226_074_906, 11, 10, {8: 16, 9: 16, 10: 16, 11: 16}, 18, 189, 80, 80, 0, 0, ), } # fmt: skip @@ -2023,22 +2031,33 @@ def test_a_short_akai_image_yields_the_partitions_the_lost_blocks_moved(label: s the table gave *that* partition, and never reaching into a partition already read, finds 39 of them across the eight. - Four things are asserted together and each would fail differently. The + Five things are asserted together and each would fail differently. The **displacement per partition** is the finding. The **volume and file counts** - are the yield. The **written and refused counts** are what says the audio is - the disc's own: a displaced partition's directory and its audio moved - together, so the payload check that condemns a misplaced file passes on - 99.7 % of what this recovers. And **every recovered partition's header block - is distinct** from every other partition's on the disc, which is what - separates a partition from the stale copies of a header that sit in these - discs' free space -- 148 byte-identical ones on `ProSamples vol.14`. + are the yield. The **written, refused and recovered counts** are what says + the audio is the disc's own: a displaced partition's directory and its audio + moved together, and where a gap inside one displaced a file a second time D38 + reads it from its own header -- so `refused` is 0 on all eight and + `recovered` is the residual D20 could not follow (ADR-0045, #35). And + **every recovered partition's header block is distinct** from every other + partition's on the disc, which is what separates a partition from the stale + copies of a header that sit in these discs' free space -- 148 byte-identical + ones on `ProSamples vol.14`. """ from samplerdisc.fs.akai import BLOCK_SIZE, partition_table, partitions from samplerdisc.sample import NotASample, PayloadMismatch - size, declared, present, displacements, volumes, files, samples, written, refused = _AKAI_SHORT[ - label - ] + ( + size, + declared, + present, + displacements, + volumes, + files, + samples, + written, + refused, + recovered_expected, + ) = _AKAI_SHORT[label] with open_image(_pinned_disc(label, size)) as image: origin = find_origin(image) assert origin is not None and origin.backend.name == "akai" @@ -2066,7 +2085,7 @@ def test_a_short_akai_image_yields_the_partitions_the_lost_blocks_moved(label: s heads[head] = part.index moved = {index for index, _ in displacements.items()} - seen = kept = mismatched = 0 + seen = kept = mismatched = recovered = 0 volumes_seen = files_seen = 0 for volume in origin.backend.volumes(image, origin.offset): if volume.partition not in moved: @@ -2076,7 +2095,11 @@ def test_a_short_akai_image_yields_the_partitions_the_lost_blocks_moved(label: s files_seen += len(volume.files) for entry in volume.samples(): seen += 1 - payload = origin.backend.read_file(image, origin.offset, entry) + # A gap inside a displaced partition displaces a file again, on + # top of the partition's own shift: placement reports where the + # bytes really are and how far, and the read follows it (#35). + read_offset, displaced = origin.backend.placement(image, origin.offset, entry) + payload = image.read(read_offset, entry.size) try: origin.backend.parse_sample(entry, payload) except PayloadMismatch: @@ -2085,12 +2108,15 @@ def test_a_short_akai_image_yields_the_partitions_the_lost_blocks_moved(label: s pass else: kept += 1 - assert (volumes_seen, files_seen, seen, kept, mismatched) == ( + if displaced: + recovered += 1 + assert (volumes_seen, files_seen, seen, kept, mismatched, recovered) == ( volumes, files, samples, written, refused, + recovered_expected, ) @@ -2275,28 +2301,33 @@ def test_akai_keeps_the_files_of_a_volume_the_allocation_map_calls_free() -> Non #: AKAI discs pinned by what their **payloads** say, as opposed to what their #: directories say above. ``label: (size, samples, s3000 headers, mismatches, -#: damaged)``, where the last two account for every sample not written: -#: a *mismatch* is a payload that is not the file its entry placed, and -#: *damaged* is one that is that file with a field unusable -- four corrupt -#: rate bytes across the collection, and nothing else (ADR-0027). +#: damaged, recovered)``, where mismatches, damaged and recovered account for +#: every sample not written at its declared position: a *mismatch* is a payload +#: that is not the file its entry placed and could not be found elsewhere, a +#: *damaged* one is that file with a field unusable -- four corrupt rate bytes +#: across the collection, and nothing else -- and a *recovered* one is a sample +#: displaced by a gap inside its partition, read back from its own header a whole +#: number of container blocks earlier (ADR-0027, ADR-0045, issue #35). #: #: The eight are chosen to cover every case the collection offers. Four whole #: S3000 discs, because the 192-byte header was read as 150 on every sample of #: them and a regression would be silent -- the WAVs would still open. Three -#: discs carrying mismatches, one of which (`Alpha Dance II`) declares six -#: partitions and holds all six, so its 21 refusals are damage the partition -#: table cannot see. And `Advance Orchestra`, which is 2 236 samples with -#: nothing wrong anywhere: the control that says these numbers measure the -#: discs and not the checks. +#: discs that carried mismatches before D38, one of which (`Alpha Dance II`) +#: declares six partitions and holds all six, so its 21 displaced samples are +#: damage the partition table cannot see -- all 21 now recovered. `Loop Soup` +#: keeps its one true mismatch, a record whose start block lands mid-sample with +#: no header to find. And `Advance Orchestra`, 2 236 samples with nothing wrong +#: anywhere: the control that says these numbers measure the discs, not the +#: checks. _AKAI_PAYLOAD = { - "AKAI.S3000.Sound.Library.1": (264_088_447, 4455, 4451, 3, 1), - "AKAI.S3000.Sound.Library.2": (298_155_354, 3086, 3083, 0, 3), - "East Connexion Piano": (277_092_352, 730, 730, 0, 0), - "AMG - Now CD-Rom for (AKAI)": (521_322_496, 1193, 1193, 0, 0), - "Best Service - Alpha Dance II AKAI": (309_865_547, 1740, 0, 21, 0), - "AMG - Kickin' Lunatic Beats 2 AKAI CD1": (378_443_564, 7932, 0, 24, 0), - "AMG - Loop Soup AKAI": (542_419_100, 3434, 0, 1, 0), - "AKAI Advance Orchestra Upgrade 97 Vol.1": (545_720_320, 2236, 0, 0, 0), + "AKAI.S3000.Sound.Library.1": (264_088_447, 4455, 4454, 0, 1, 3), + "AKAI.S3000.Sound.Library.2": (298_155_354, 3086, 3083, 0, 3, 0), + "East Connexion Piano": (277_092_352, 730, 730, 0, 0, 0), + "AMG - Now CD-Rom for (AKAI)": (521_322_496, 1193, 1193, 0, 0, 0), + "Best Service - Alpha Dance II AKAI": (309_865_547, 1740, 0, 0, 0, 21), + "AMG - Kickin' Lunatic Beats 2 AKAI CD1": (378_443_564, 7932, 0, 0, 0, 24), + "AMG - Loop Soup AKAI": (542_419_100, 3434, 0, 1, 0, 0), + "AKAI Advance Orchestra Upgrade 97 Vol.1": (545_720_320, 2236, 0, 0, 0, 0), } @@ -2315,27 +2346,38 @@ def test_akai_payloads_are_the_files_their_directory_entries_placed(label: str) 56 490** AKAI samples read before D20, on nine discs, and four of them are pinned here whole. - **The identity.** 65 payloads across the 44 discs are not the file their - entry placed or are that file with a field unusable, and all 65 were - already being refused -- as "does not begin with an AKAI sample header", - which is true of a payload that is mid-audio and of one that is a perfectly - good sample under the wrong name alike. The mismatch count is pinned as - tightly as the sample count for ADR-0012's reason: a refusal appearing - where none was measured is a check that has started condemning real audio, - and one disappearing is a check that has stopped looking. + **The identity.** A payload that is not the file its entry placed is refused + -- unless the reason is a run of blocks lost inside its partition, in which + case D38 finds the real bytes a whole number of container blocks earlier by + the entry's own name and word count and reads them there (ADR-0045). So a + displaced sample now counts as `recovered`, not `mismatched`: `Alpha Dance + II`'s 21, `Kickin' CD1`'s 24 and `Library.1`'s 3 all move columns. What stays + a mismatch is a payload with no such header to find -- `Loop Soup`'s one + mid-sample record. Each of mismatch, damaged and recovered is pinned as + tightly as the sample count for ADR-0012's reason: a refusal appearing where + none was measured is a check condemning real audio, one disappearing is a + check that stopped looking, and a recovery appearing where none was is the + search reaching a file it should not. """ from samplerdisc.sample import NotASample, PayloadMismatch from samplerdisc.sample.akai import HEADER_LEN_S1000, HEADER_LEN_S3000 - size, samples, s3000_expected, mismatch_expected, damaged_expected = _AKAI_PAYLOAD[label] + size, samples, s3000_expected, mismatch_expected, damaged_expected, recovered_expected = ( + _AKAI_PAYLOAD[label] + ) with open_image(_pinned_disc(label, size)) as image: origin = find_origin(image) assert origin is not None and origin.backend.name == "akai" - seen = s3000 = mismatched = damaged = 0 + seen = s3000 = mismatched = damaged = recovered = 0 for volume in origin.backend.volumes(image, origin.offset): for entry in volume.samples(): seen += 1 - payload = origin.backend.read_file(image, origin.offset, entry) + # placement relocates a sample the rip displaced inside its + # partition to where its own header sits; read_file follows it, + # so the identity below is checked at the recovered offset and a + # recovered sample is no longer a mismatch (ADR-0045, #35). + read_offset, displaced = origin.backend.placement(image, origin.offset, entry) + payload = image.read(read_offset, entry.size) try: sample = origin.backend.parse_sample(entry, payload) except PayloadMismatch: @@ -2344,6 +2386,8 @@ def test_akai_payloads_are_the_files_their_directory_entries_placed(label: str) except NotASample: damaged += 1 continue + if displaced: + recovered += 1 assert sample.header_len in (HEADER_LEN_S1000, HEADER_LEN_S3000) if sample.header_len == HEADER_LEN_S3000: s3000 += 1 @@ -2362,11 +2406,12 @@ def test_akai_payloads_are_the_files_their_directory_entries_placed(label: str) # merely the right number of them. A count cannot see a 42-byte # slip; this is the check that would have caught it. assert sample.pcm == payload[sample.header_len : sample.header_len + words * 2] - assert (seen, s3000, mismatched, damaged) == ( + assert (seen, s3000, mismatched, damaged, recovered) == ( samples, s3000_expected, mismatch_expected, damaged_expected, + recovered_expected, ) @@ -2376,10 +2421,13 @@ def test_an_akai_payload_is_never_written_under_another_files_name(path: Path) - The tables above are this collection's; this is the invariant, and it is the one issue #23 asked for: **no AKAI sample is written whose payload - header names a different file**. It holds trivially now, since such a - payload is refused -- which is the point. If a future change relaxes the - name test, or reads the header at an offset where another file's name - happens to land, this fails on any shelf rather than on ours. + header names a different file**. It stopped holding trivially with D38: 102 + samples that were refused are now written, each read from a position the + recovery *chose*, and this is what says the recovery chose right -- the + header it landed on carries the entry's own name. If the search ever reads a + header at an offset where a different file's name happens to land, or a + future change relaxes the name test, this fails on any shelf rather than on + ours (ADR-0045). """ from samplerdisc.fs.akai import NAME_LEN, decode_name from samplerdisc.sample import NotASample