Publish the reproducible Sound Lab and FPGA Colour Lab sources

This commit is contained in:
bholman committed 2026-11-18 12:28:31 -07:00
commit 88254d7e24
27 files changed
+4574

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
# Sound Lab coverage and remaining acceptance
This is an initial diagnostic disk and listening toolkit, not completion of the
entire Sound Lab specification. The current set contains 114 authored vectors
with vector-set CRC `62E5`. Adding more vectors will require an explicit vector
revision and renewed artifact receipts; existing reports must remain attributable
to their original bytes.
Reference: **Sound Lab shared CoCo Sound/Speech diagnostic specification**,
Revision 1, November 17, 2026, repository blob
`8b2b303cfce4a3a7e4d1bf377b6a8fca68e62b16`:
[original specification](https://vccplus-git.brianholman.com/VCCPlus/Coco3FPGAResearch/src/branch/codex/timing-de1-investigation/docs/VCC_SSC_DIAGNOSTIC_SPEC.md).
## How to interpret the coverage
**Implemented packet** means an authored packet exists and passes the host's
grammar/identity checks. **Partial** means only part of a specified activity is
implemented. **Deferred** means it cannot be accepted using this disk's current
cases. None of these labels means Brian heard a sound, that a physical cartridge
passed, or that the FPGA implementation is correct.
Vector subcase IDs distinguish individual packets from whole specification
chapters. For example, `BUF01-SP1` addresses speech slot 1; it does not prove
the full `BUF01` overwrite-isolation/sharing requirement. `ALP01-01` is just
pause address 1 within the specification's 64-address `ALP01` chapter. The
mappings below are authoritative for this initial set.
The seven-case showcase is `TXT01`, `TON01-A`, `TON04`, `TON05`, `NOI01`,
`FUN01-TUNE`, `MIX01`. The guided group has 14 cases. The engineering group and
individual case selector expose the other packets. The engineering menu currently
still asks for a human response after each case; it is not an unattended sweep.
Duration targets of three minutes and 10–15 minutes depend on listener responses
and have not been qualified as fixed-duration experiences.
## Specification-to-implementation matrix
| Specification ID | Current implementation / local vector IDs | Remaining requirement and acceptance |
| --- | --- | --- |
| SET01 | **Partial.** Guest asks target, CoCo model, NTSC/PAL and disk/screen-only mode; user confirms normal speed and configured cartridge. Existing SDK routing token is saved/restored. No floating-status auto-detection or MPI bank changes. | Cartridge model/modification, actual MPI slot arrangement, audio path and emulator/core identity are not all collected as structured guest fields. Record these in accompanying run notes. Physical routing/interrupt preservation still needs observation. |
| RST01 | **Partial infrastructure.** Startup uses FF7D=1 then0; subsequent output has bounded ready polling. | No separately recorded cold-reset test, startup status timeline or reset-silence listening result. A click or sustained sound cannot be inferred from a later ready bit. |
| TXT01 | **Implemented packet.** Exact original greeting, followed by explicit space/CR; replay and HUMAN score supported. | Native/emulated execution evidence and real-card listening are separate. Record recognizability; do not substitute modern text-to-speech pronunciation. |
| TXT02 | **Partial.** `TXT02-READ` says an authored sentence with words and spelled-out numbers; exact ASCII is in manifest. | Minimal pairs, digit-character cases and an actual countdown are not implemented. |
| TXT03 | **Partial.** `TXT01`/`TXT03-LONG` provide different sentence lengths and manual replay. | Exact lengths 1/31/62, delayed submission, firmware boundary behavior and maximum-capacity qualification are not tested. Host rejection of oversized packets is not a firmware acceptance test. |
| ALP01 | **Implemented packet series.** Local `ALP01-00`–`ALP01-63` request all 64 addresses independently, label each and explain addresses 0–4 as silent pauses; final pause and FF included. | Group navigation is sequential cases, not an authored small-group lesson. All pronunciation, pause timing and physical listening remain unqualified. |
| ALP02 | **Deferred.** Individual codes do not make a word-comparison activity. | Add original hand-authored words versus equivalent text words, exact code arrays, repeated A/B playback and optional blind transcript reveal. |
| BUF01 | **Partial.** `BUF01-SP0`–`BUF01-SP7` independently load and execute all eight text slot addresses using unique spoken labels. | These cases do not prove retained neighbors, overwrite isolation, repeated playback without reload, or text/allophone sharing. Add one multi-step script that loads all slots, replays them, overwrites one, and replays its neighbors without reloading. |
| BUF02 | **Partial.** `BUF02-SN0`–`BUF02-SN7` independently load and execute all eight sound slot addresses with distinct pitches. | No semantic sound-slot isolation or simultaneous speech-buffer independence proof. Load all first, replay without reload, overwrite one and verify unchanged neighbors and stored speech. |
| CMD01 | **Partial.** Immediate text, stored text, sound, allophone and direct-register packets exist. Local `CMD01` sends C7/CF/00. `TIM01` sends 8F. | No chained-buffer vectors, stored-register B8–BF/F8–FF execution vectors, stop/retain/replay sequence, reload recovery lesson, or dedicated command-family equivalence assertions. FF boundary/data handling is tested on the host and has `REG02`/`TIM02` guest packets. |
| TON01 | **Implemented packet components.** Local `TON01-A`/`TON01-B`/`TON01-C` independently exercise A/B/C with period 254 and amplitude 10; `TON05` is a three-voice chord. | Requires actual execution/listening and comparative measurements. These are three mono voices, not three stereo positions. |
| TON02 | **Partial.** `TON04` steps through periods 428/339/254. | Specified 250/500/1000 and engineering boundaries 1/4095 are absent. The channel B packet is `TON01-B`; it does not stand in for this pitch ladder. |
| AMP01 | **Partial.** Local `AMP01` uses amplitudes 2/5/9/13 at one pitch, followed by explicit silence. | Exact ladder 0/1/4/8/12/15 with zero-volume rest and repeat is absent. No linear-loudness or equal-gain assertion is made. |
| NOI01 | **Partial.** Local `NOI01` uses noise A periods 1/8/31; `NOI02` exercises retain-previous-amplitude bit. | Noise B/C, periods 0/16, percussion lesson and tone-plus-noise mixer cases are absent. Analog noise is not expected to be sample-identical across devices. |
| ENV01 | **Partial.** `ENV01-00`–`ENV01-15` request every shape with documented tone/envelope ordering and explicit final silence. | All use one envelope period and one channel. Short/long comparison, retrigger during playback, two-channel sharing and richer A/B descriptions are absent. `ENV01-10` belongs to the guided group; the other 15 shapes are engineering cases. |
| REG01 | **Partial.** `REG01` programs toneA fine/coarse, mixer and fixed amplitude through AF; `REG02` includes legal FF register data. | Direct envelope/multi-channel/mixer isolation matrix is absent. No unsupported AY register readback is invented. |
| TIM01 | **Partial.** Local `TIM01` sets base 16 and plays one finite tone; `TIM02` uses duration FF. | No controlled multi-duration/multi-base matrix, precise note-on/off timestamps or repeated-gap distributions. A declared timer baseline is required between cases; coarse guest ticks are not calibrated audio timing. |
| STS01 | **Partial infrastructure.** Guest records full status before/after, transmitted-byte count, elapsed VSYNC ticks and whether a wait-mask busy state was observed. | No continuous transition timeline, startup/decay latency distribution or calibrated polling resolution. A missed pulse is unresolved, not evidence of no pulse. Status 40/20 meanings remain source/hardware qualification work. |
| MIX01 | **Partial.** `TXT01`, tone cases and local `MIX01` offer speech alone, sound alone and a held tone under an authored phrase; bounded global cleanup stops both. | No independent speech-stop versus sound-stop listening sequence or structured clipping/dropout comparison. Held-tone cleanup must be confirmed in execution. |
| MUX01 | **Deferred.** Routing is set on entry and restored on exit. | No mid-play cartridge mux/speaker gating exercise, inaudible-progress comparison or normal CoCo SOUND/DAC regression. Entry/exit restoration is not equivalent to this test. |
| RST02 | **Partial safety infrastructure only.** Timeout/interrupted packets reset before recovery. | No deliberate active-tone, active-speech, combined-play or incomplete-load reset cases with independently recorded recovery and explicit buffer reinitialization. |
| REP01 | **Deferred.** The user can repeat a selected case. | No numbered repeated speech sequence covering cumulative 4096 speech samples, no stale-ring/frozen-speech detector. A guest cannot read internal speech sample counts. |
| REP02 | **Deferred.** Sequential engineering cases have deterministic order and bounded waits. | No timed 60-second/5-minute alternating stress script, unattended mode or qualified drift measurement. |
| FUN01 | **Partial experience.** Local `FUN01-TUNE` plays an original finite tune with note-off; greeting and other labels are separate cases. | No interactive musical keyboard or spoken note labels. Local ID does not satisfy the whole proposed activity. |
| FUN02 | **Partial ingredients.** `TON05`, `NOI01`, `FUN01-TUNE` and `MIX01` supply chord/noise/tune/spaceport-message components. | No integrated countdown, layered engine, launch motif, radio message, landing chime and final quiet timeline. Local `MIX01` is a short finale, not the full scene. |
| ORC01 | **Deferred optional extension.** No FF7A/FF7B packets are sent. | Separate Orchestra-90 profile and left/right tests may follow. Not applicable to SSC-only acceptance; SSC is mono. |
| EXT01 | **Deferred MiSTer integration.** No extended-video-palette operations are performed. | FPGA team must test its bus ownership/graphics/ordinary sound/Orchestra interactions. Not applicable to a plain physical SSC. |
## Other specification requirements
The build produces ordinary 6809 `.BIN`, Disk BASIC `.BAS`, 35-track raw `.DSK`,
SHA-256 artifact receipts and the exact vector manifest. The same guest bytes
can be copied to each target; platform selection only changes report metadata.
The guest has no network, OS-9, GUI debugger or emulator-private API dependency.
The guest polls once per actual bus read, waits before each byte, uses a VSYNC
deadline plus an independent iteration limit, and resets after partial-packet
failure. These paths exist in source. Their presence is distinct from proving
all timeout, panic, IRQ-mask, PAL, counter-wrap and recovery behavior on hardware.
The test never selects a faster physical CoCo clock. A speed comparison is not
part of this initial disk.
Disk reports use unique names, CRLF, per-case flushes, explicit partial/complete
footers, record counts and CRCs. Screen-only mode and RAM paging are present.
The bounded RAM report can span multiple report files; preserve all files for a
run session. The host extractor/parser compares build/vector identities and
keeps AUTO and HUMAN outcomes separate. The initial guest records observations,
not automatic hardware PASS. Complete physical disk-full/write-protect/retry,
interrupted-report, no-disk and photograph usability checks remain acceptance
work. Host synthetic filesystem fixtures do not prove a real drive's behavior.
The optional WAV analyzer accepts manually marked intervals, measures basic
PCM levels, isolated-tone crossings, clipping and repeated-case differences.
Automatic case-marker alignment, spectrum comparison, calibrated capture-clock
tolerances and full audio timeline integration remain deferred. WAV generation
from an emulator is not a physical recording, and a text report is not audio.
The specification's comprehensive chip-internal suite and timestamped PIC/AY/SP
tracing are a separate deferred engineering effort. The initial native runner
can exercise actual emulator DOS boot, selected guest interactions, report disk
writes, signal presence and absent-card recovery. It does not implement all
timer/IRQ/DDR/cycle-debt, ROM-loader, ALD/DRQ, envelope/noise, coefficient/filter
saturation tests or negative-control fault injections requested in that section.
Existing unrelated SSC tests must be cited individually before reusing their
evidence; they are not silently counted as completion of this disk's spec.
## Verification layers and evidence limits
1. **Source/packet checks:** six vector host tests passed during initial authoring,
including CCITT-FALSE reference value, malformed packets, FF operand handling,
all slots/codes/shapes, deterministic outputs and selected fixed vector CRCs.
The source catalog records a hashed OCR/typeset Tandy reproduction whose
command-table pixels were inspected. Original photographic scan comparison
remains pending. Successful validation proves the declared packet structure
and identity, not firmware execution or audible fidelity.
2. **Native/emulated checks:** use the coordinator's final build/test receipt for
exact artifact hashes, source revision and actual results. A compiled runner
or generated disk alone is not a passed test. Signal detection must stay
separate from HUMAN listening. Any emulator findings describe the current
comparison baseline; they do not revise physical expectations to fit it.
3. **Physical acceptance:** not performed by this coverage review. Brian must
boot this exact disk on a real CoCo, listen/repeat, save/reload reports and
verify safe recovery. Physical Intel/macOS testing is unrelated to the CoCo
cartridge's analog behavior.
4. **FPGA acceptance:** pending research-core availability and its pre-install
checks. Use the same disk/vector identities, identify stock versus research
cores, and compare observations with the physical baseline. VCC-only success
cannot stand in for real-card or MiSTer acceptance.
No speech/sound engine, SDK or application implementation change is authorized
by this document. The emulator baseline remains unchanged while FPGA work is
finished and recommendations are reviewed.
## Next checks for Brian and the FPGA project
1. Keep an unchanged master disk and manifest. Use a fresh writable copy per
platform; verify its starting SHA-256 before first use. After testing, retain
the changed disk and all `SNDxxxx.TXT` files rather than comparing its modified
hash to the pristine artifact hash.
2. Record CoCo model, NTSC/PAL, normal speed,26-3144/3144A/unknown cartridge,
known modifications, MPI/disk slots, speaker/audio path and emulator or FPGA
build identity. Do not guess physical ROM hashes. No hardware modification
or cartridge hot-swap is required.
3. Boot with `DOS` on VCC Plus and a real CoCo. Run **Meet the Robot** at low
volume. Score each case, repeat `TXT01`, mark an intentionally uncertain
result, add a note and confirm each sound stops. The current seven cases are
listed above; missing full-spec scenes must not be marked complete.
4. Quit normally, relaunch and run again. Verify a new report filename is used.
Safely copy the disk, extract reports, convert them using the matching build
manifest, and verify their checksum/count/footer and build/vector identities.
Keep actual VCC and physical reports together with any photographs/recordings.
5. Select individual `REG01`, `REG02`, `TIM02`, representative envelope cases
and `ALP01-00`–`ALP01-04`. Confirm legal FF operands do not terminate early, held
tones end at cleanup, pause cases are intentionally quiet, and no physical
timeout threshold is inferred from the emulator's observed count.
6. Exercise **X** during an audible wait and confirm a bounded return to menu;
repeat `TXT01` afterward. With no SSC configured, run screen-only mode and
confirm bounded handling/no false detected-card claim. Preserve any timeout
or interrupted report instead of treating it as a pass.
7. On disposable media only, separately test screen-only, write-protected or
full disk, retry-save, RAM paging and interrupted-run report extraction.
Confirm the app never formats a disk or overwrites an earlier run. A full
RAM report may need a new file/run; save or photograph before clearing.
8. If recording audio, use fixed gain and preferably 48 kHz/16-bit PCM with lead-in
and trailing silence. Mark exact intervals manually, retain the raw WAV and
capture notes, and compare measured changes without demanding identical
analog waveforms or absolute loudness. Record human judgments independently.
9. Give the FPGA team the same pristine disk, `.BIN`/`.BAS`, full manifest,
parser/analyzer, this coverage map and actual physical reports. Run first on
the separately identified research core after its own build/pre-install
checks. Report discrepancies without modifying the emulator baseline.
10. Expand deferred tests deliberately: first buffer isolation/sharing and reset
recovery; then exact tone/amplitude/noise/timing matrices; then mux controls,
stress runs and chip-internal negative controls. Address the ID mapping
explicitly in that next vector revision, preserving subcase suffixes so an
individual packet cannot be mistaken for a complete specification chapter.
+161
View File
@@ -0,0 +1,161 @@
# Sound Lab — diagnostic disk
Sound Lab is a standalone, keyboard-driven CoCo program for comparing the Tandy
Speech/Sound Cartridge in VCC Plus, on a real CoCo, and eventually in the research
FPGA core. It does **not** change VCC Plus's speech/sound implementation. This
first disk provides a useful listening baseline; [coverage](COVERAGE.md) identifies
the larger diagnostic specification's remaining work explicitly.
## Start here
Keep `SOUNDLAB.DSK` as an unchanged master. Make a **writable copy** for each test
environment. The disk is ordinary single-sided Disk BASIC: 35 tracks, 18 sectors
per track, 256 bytes per sector, 161,280 bytes in total. No cartridge ROM is in
the disk or delivery archive.
1. Use a 64-KiB-or-larger CoCo, Disk BASIC, a Speech/Sound Cartridge and **normal
CPU speed**. Start with low speaker volume. In VCC Plus, use Disk BASIC with
the Speech/Sound Cartridge configured. Do not use an OS-9 preset.
2. Insert the writable disk in **FD0**, then type `DOS` and press Return.
Alternatively type `RUN"SOUNDLAB"`. The supplied BASIC loader uses `PCLEAR1`
and `CLEAR32` before loading the machine-language program at `$1600`.
Do not bypass that setup with a bare `LOADM` in an arbitrary existing session.
3. Choose the platform, CoCo model and NTSC/PAL setting. These are descriptions,
**not automatic cartridge detection**. Confirm your own physical cartridge,
MPI arrangement and speaker path separately. The program does not switch MPI
banks or enable double-speed mode.
4. Choose **D** to save reports to the writable FD0 copy, or **M** for screen-only
operation. Use the diagnostic disk, never an important software/data disk.
5. Start **1 — Meet the Robot**. The brief showcase includes a greeting, a tone,
rising notes, a chord, noise, a small original tune and a spaceport voice.
**2** selects more guided examples. **3** requires explicit confirmation for
the larger engineering set. **4** runs a case ID from the manifest.
Disk loading and simultaneous cartridge use require compatible hardware routing,
usually a Multi-Pak plus disk controller. Do not hot-swap powered cartridges to
work around a single cartridge slot. Screen-only mode suppresses report disk I/O;
it does not invent a new way to load the program.
## Listen, repeat and recover
Read the listening prompt, then press **Return** to play (or **X** for the menu).
Each result waits for your response:
| Key | Meaning |
| --- | --- |
| H | Heard the expected example |
| W | Heard something wrong |
| N | No sound |
| U | Unsure |
| R | Record this attempt and repeat the example |
| S | Skip |
| T | Add a short note, then choose a result |
| X | Return to the menu; also interrupts bounded playback waits |
The first five allophone addresses are **pauses**: silence is intentional.
Three AY tone channels mix to mono; they are not three stereo positions. A saved
`AUTO=OBSERVED` describes register/timing observations, not successful listening.
Only your response supplies `HUMAN=HEARD`. Test timing is in video-frame ticks;
PAL/NTSC, polling overhead and firmware latency prevent treating it as calibrated
audio duration. Analog tolerances remain `MEASURE_BASELINE`.
Sound Lab resets the cartridge at each case's beginning to establish a consistent
timer/buffer baseline. It records that prelude separately from the vector bytes.
It sends the documented stop-both command after each case, or resets after an
interrupted/unfinished packet or timeout. The cartridge's stored buffers are
diagnostic scratch space. **Q** saves the final report, resets the cartridge and
returns to BASIC with the saved PIA audio routing restored. It leaves the CPU
speed and MPI selection alone. The loader's text mode/graphics-page allocation
is part of this standalone program, not a preserved running CoCo application.
## Reports
The program reserves unused `SND0001.TXT`, `SND0002.TXT`, … filenames. Existing
reports are never intentionally replaced. It flushes observations **between**
cases, not during sound playback. The small CoCo RAM log rolls into additional
numbered files; retain **all** of them. The displayed attempt number is a session
sequence and distinguishes repeats and later re-selection of the same case.
Keep the disk inserted during a session. Before updating a checkpoint, the
program checks the saved file's bytes against its prior checkpoint. A changed or
swapped file is refused with error250. Disk errors leave the current RAM log
available: use **5** to page/photograph it, or **6** to retry saving after fixing
the original media problem. A partially failed physical write may require keeping
the RAM photographs rather than retrying over an uncertain file. Do not swap a
different disk into the open report. No formatting or repair is attempted.
In screen-only mode, a full log pauses before the next case. Photograph its
pages before explicitly choosing **C** to clear it for another report segment.
**X** keeps it and returns to the menu. There is no silent log eviction.
Safely save/eject the disk in VCC Plus, or transfer the physical disk image using
your normal hardware workflow. Work from a saved host copy:
```sh
python3 host/soundlab_reports.py extract MYTEST.DSK --output extracted
python3 host/soundlab_reports.py convert extracted/SND0001.TXT \
--output readable --manifest SOUNDLAB-manifest.json
```
See [host report instructions](host/README.md) for comparison and JSON/CSV/HTML
exports. Keep the original modified DSK, raw TXT files, manifest and any WAVs or
photographs. The pristine disk hash changes when reports are saved; this is
expected and does not invalidate the original build receipt.
Optional [WAV analysis](audio/README.md) accepts manually marked intervals and
measures signal levels, clipping and qualified isolated-tone estimates. It never
relabels measurements as human listening or analog hardware acceptance.
## Rebuild and validate
In the VCC Plus repository:
```sh
python3 examples/sound-lab/build.py
python3 -m unittest discover -s examples/sound-lab/tests -v
```
For the isolated real-ROM run, use the retained core library and explicit private
ROM folder (these inputs are never copied into the delivery):
```sh
python3 examples/sound-lab/check.py \
--core .build/371-release-native/Build/Products/Release/libVCCCore.a \
--roms platforms/macos/LocalResources/ROMs
```
The default output is `.build/sound-lab`. An exported project accepts explicit
`--toolchain /path/to/Toolchain --output /path/to/new-build` arguments. Use the
bundled VCC Plus toolchain, **CMOC0.1.101**, with its matching LWTools, SSC and
public-domain `decbfile` libraries. The supported driver uses ordinary Disk BASIC
ROM services; no separately licensed standalone disk driver is copied here.
Python is only a build/reporting dependency on the host, not on the CoCo.
`SOUNDLAB-manifest.json` binds the short guest build ID and vector CRCs to full
source/artifact SHA-256 hashes. `SHA256SUMS` covers the BIN, BASIC loader and DSK.
The host BASIC source uses LF; its disk member uses the disk writer's explicit
leading-CR and CR line-ending conversion. Both forms contain the same loader.
The compiler's `$7A00` limit and retained map check ordinary memory bounds. The
text-only guest uses the otherwise unused, `PCLEAR1`-reserved PMODE page at
`$0E00–$13FF` as a1536-byte log. Compiled assembly is checked for one actual
`LDB $FF7E` per status-reader call. Ready and completion loops have elapsed-tick
and independent iteration limits.
The [native runner](native/run.cpp) boots the disk through actual Disk BASIC and
FD502 emulation with existing private local ROM inputs. It does not launch or
operate the user's app. The build receipt records what was tested. Physical CoCo
listening, physical disk behavior and future FPGA acceptance remain separate.
## Sources and license
Sound Lab guest, generator, original vectors, host utilities and tests are
GPL-3.0-or-later, like the VCC Plus SDK. The tiny DOS bootstrap retains Pierre
Sarrazin's public-domain attribution. CMOC library/dependency notices remain in
the toolchain distribution; this project does not redistribute the compiler or
private firmware. The delivery's `COPYING` is the GPL license text.
[Packet/source notes](vectors/PROTOCOL.md) cite a downloaded, hashed OCR/typeset
reproduction of Tandy's original publication. It is not a photographic scan.
The diagnostic bytes are newly authored; manual PDFs and ROM contents are not
included in the disk or source archive. No checksum establishes redistribution
rights or proof of hardware fidelity.
+118
View File
@@ -0,0 +1,118 @@
# Optional audio measurements
`analyze.py` measures a pre-existing uncompressed integer PCM WAV with Python
3.9 or later and no extra packages. It does not capture audio, operate an emulator,
change a cartridge, or identify hardware. Keep the raw WAV and its interval
manifest as evidence; the report includes SHA-256 digests of both inputs.
```sh
python3 examples/sound-lab/audio/analyze.py capture.wav intervals.json --output measurements.json
```
Reports go to standard output when `--output` is absent. Existing report files
are protected; `--overwrite` explicitly replaces a report, but cannot replace
either input. No command modifies the WAV or manifest. These potentially large
and private recordings belong outside Git.
## Capture and interval preparation
Use an external line-level recorder or the platform's audio export. Ideally
record uncompressed **48 kHz, 16-bit PCM**, with a fixed gain and without AGC,
noise suppression, equalization or other processing. Record lead-in and trailing
silence. Record the connection path (real analog, emulator export, HDMI or other),
gain, cartridge/configuration and any resampling in your own capture notes.
WAV header values describe the file; they do not calibrate a real capture clock.
Use displayed/counted markers or an optional marker sound outside measured
windows to locate each case. Enter actual offsets into the manifest after
reviewing the recording. Guest counters and marker ticks do **not** necessarily
coincide with audio sample boundaries. This analyzer does not infer markers or
align recordings automatically.
```json
{
"capture_context": {
"source": "real analog — user reported, not verified",
"gain_notes": "fixed recorder gain; no AGC",
"marker_notes": "start measured manually after the count-in"
},
"segments": [
{
"case_id": "TONE-EXAMPLE",
"vector_id": "exact-vector-identity-from-run",
"kind": "tone",
"start_seconds": 1.25,
"end_seconds": 3.25,
"nominal_hz": 440.0
}
]
}
```
A top-level array of segment objects is also accepted. Each segment requires a
nonempty `case_id`, explicit finite `start_seconds` and `end_seconds`, and a
`kind` of `tone`, `noise`, `speech` or `silence`. Overlapping windows are allowed
for deliberate analysis of the same samples. Windows must be within the file
and contain at least one sample. Samples with timestamps `start <= n/rate < end`
are included. Reports retain requested offsets, zero-based start/exclusive stop
frames, PCM payload byte offsets and actual sample-window duration. Byte offsets
refer to decoded PCM payload, **not** offsets into the WAV container.
`vector_id` is optional for individual measurements, but required for repeated
case comparison. Use the exact vector identity or CRC from the guest run. Only
matching `case_id`, `vector_id` and `kind` are compared; matching labels are
user assertions, not independently proven guest provenance.
## Meaning and limits
The analyzer supports `WAVE_FORMAT_PCM` with 8-bit unsigned and 16/24/32-bit signed
integer PCM. It rejects compressed, floating-point or extensible-format WAV,
truncated payloads and unsupported sample widths. Convert unsupported containers
explicitly and preserve both the original and conversion notes. Channels are
measured independently without mixing or resampling.
RMS, AC RMS, peak and DC offset are normalized to signed full scale. The
`clipping_count` counts exact positive/negative PCM rails; reaching a rail is
evidence to inspect, not proof of a defective device. `near_zero_ratio` counts
samples within one LSB of digital zero; it is not a perceptual silence threshold.
For `tone` only, a frequency estimate uses linearly interpolated upward zero
crossings after removing the window's mean DC offset. At least three crossings
are required. The report includes crossing-period variation. This is appropriate
for an isolated pure tone: harmonics, noise, clipping, modulation and transients
can create extra crossings or bias the fundamental. Review the signal and window
before interpreting an estimate. No frequency estimate is made for noise or
speech, and silence cannot establish an output-stage fault.
The default assessment is `MEASURE_BASELINE` with observations `OBSERVED` and
human listening `NOT_OBSERVED`. No measured value establishes `HEARD`, general
success, analog waveform equality, real hardware identity or accurate clocks.
Repeated-case reports give differences, without an automatic pass/fail judgment.
Keep human listening results separate in the diagnostic run report.
If a qualified frequency tolerance has independently been established, a tone
segment with `nominal_hz` may additionally specify:
```json
"frequency_tolerance": {
"absolute_hz": 2.0,
"qualification": "Example only: replace with the documented hardware/clock basis and reference"
}
```
This enables a **measurement-only** `WITHIN_QUALIFIED_TOLERANCE` or
`OUTSIDE_QUALIFIED_TOLERANCE` assessment on that channel when frequency can be
estimated. It does not certify the supplied justification or convert an
observation into a listening or compatibility pass. The report as a whole remains
`MEASURE_BASELINE`. Do not invent tolerances from an arbitrary passing run.
## Portable checks
From the repository root:
```sh
python3 -m unittest discover -s examples/sound-lab/tests -p test_audio.py -v
```
Tests author their own temporary WAVs, including tones at both 44.1 and 48 kHz,
silence, integer rails, different stereo channels and malformed inputs. They
verify measurements and input preservation, not audible quality or hardware.
+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Measure explicitly identified Sound Lab intervals; never infer listening success."""
import argparse
import hashlib
import io
import json
import math
from pathlib import Path
import statistics
import sys
import wave
KINDS = {"tone", "noise", "speech", "silence"}
def finite_number(value, label):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ValueError(label + " must be a finite number")
return float(value)
def sha256(data):
return hashlib.sha256(data).hexdigest()
def load_pcm(path):
"""Return integer samples and the capture's declared format, without resampling."""
raw = Path(path).read_bytes()
# New Python versions also accept IEEE float through wave. Enforce the same
# integer-only, portable WAVE_FORMAT_PCM contract on every supported Python.
if len(raw) < 12 or raw[:4] != b"RIFF" or raw[8:12] != b"WAVE":
raise ValueError("expected a little-endian RIFF/WAVE file")
offset = 12
format_tag = None
while offset + 8 <= len(raw):
size = int.from_bytes(raw[offset + 4:offset + 8], "little")
if raw[offset:offset + 4] == b"fmt ":
if size < 16 or offset + 8 + size > len(raw):
raise ValueError("invalid WAV format chunk")
format_tag = int.from_bytes(raw[offset + 8:offset + 10], "little")
break
offset += 8 + size + (size % 2)
if format_tag != 1:
raise ValueError("only WAVE_FORMAT_PCM integer WAV is supported; convert compressed, float or extensible WAV explicitly")
try:
with wave.open(io.BytesIO(raw), "rb") as source:
if source.getcomptype() != "NONE":
raise ValueError("only uncompressed integer PCM WAV is supported")
width = source.getsampwidth()
channels = source.getnchannels()
rate = source.getframerate()
frames = source.getnframes()
if width not in (1, 2, 3, 4):
raise ValueError("supported PCM widths are 8, 16, 24 and 32 bits")
if rate <= 0 or channels <= 0 or frames <= 0:
raise ValueError("WAV must contain samples at a positive rate")
payload = source.readframes(frames)
except (wave.Error, EOFError) as error:
raise ValueError("unsupported or invalid PCM WAV: " + str(error)) from error
if len(payload) != frames * channels * width:
raise ValueError("truncated WAV sample data")
samples = [[] for _ in range(channels)]
for index in range(0, len(payload), width):
value = int.from_bytes(payload[index:index + width], "little", signed=width != 1)
if width == 1:
value -= 128
samples[(index // width) % channels].append(value)
return samples, {
"filename": Path(path).name, "sha256": sha256(raw), "byte_count": len(raw),
"sample_rate_hz": rate, "channels": channels, "bit_depth": width * 8,
"frame_count": frames, "duration_seconds": frames / rate,
"format": "uncompressed integer PCM", "sample_rate_source": "WAV header; not clock calibration",
}
def validate_manifest(document, info):
if isinstance(document, list):
segments = document
elif isinstance(document, dict):
segments = document.get("segments")
else:
segments = None
if not isinstance(segments, list) or not segments:
raise ValueError("manifest must contain a nonempty segments list")
checked = []
for index, segment in enumerate(segments):
label = "segment " + str(index)
if not isinstance(segment, dict):
raise ValueError(label + " must be an object")
case_id = segment.get("case_id")
if not isinstance(case_id, str) or not case_id.strip():
raise ValueError(label + " needs a nonempty case_id")
if segment.get("kind") not in KINDS:
raise ValueError(label + " has unsupported kind")
start = finite_number(segment.get("start_seconds"), label + " start_seconds")
end = finite_number(segment.get("end_seconds"), label + " end_seconds")
if start < 0 or end <= start or end > info["duration_seconds"]:
raise ValueError(label + " interval must satisfy 0 <= start < end <= WAV duration")
# Samples at timestamps start <= n/rate < end; no implied counter alignment.
first = math.ceil(start * info["sample_rate_hz"])
stop = min(info["frame_count"], math.ceil(end * info["sample_rate_hz"]))
if stop <= first:
raise ValueError(label + " interval contains no sample timestamps")
item = dict(segment)
item.update(start_seconds=start, end_seconds=end, start_frame=first, stop_frame=stop)
vector_id = item.get("vector_id")
if vector_id is not None and (not isinstance(vector_id, str) or not vector_id.strip()):
raise ValueError(label + " vector_id must be a nonempty string when supplied")
if "nominal_hz" in item:
nominal = finite_number(item["nominal_hz"], label + " nominal_hz")
if item["kind"] != "tone" or not 0 < nominal < info["sample_rate_hz"] / 2:
raise ValueError(label + " nominal_hz needs a tone below the Nyquist frequency")
item["nominal_hz"] = nominal
tolerance = item.get("frequency_tolerance")
if tolerance is not None:
if not isinstance(tolerance, dict) or "nominal_hz" not in item:
raise ValueError(label + " frequency_tolerance needs nominal_hz")
limit = finite_number(tolerance.get("absolute_hz"), label + " absolute_hz")
qualification = tolerance.get("qualification")
if limit < 0 or not isinstance(qualification, str) or not qualification.strip():
raise ValueError(label + " tolerance needs a nonnegative absolute_hz and qualification")
checked.append(item)
return checked
def tone_estimate(values, rate):
"""Interpolated upward crossings after DC removal, meaningful only for pure tones."""
mean = statistics.fmean(values)
crossings = []
for index in range(1, len(values)):
before, after = values[index - 1] - mean, values[index] - mean
if before < 0 <= after:
crossings.append(index - 1 + (-before / (after - before)))
result = {
"technique": "DC-removed linearly interpolated upward zero crossings",
"limitations": "Pure-tone estimate only. Harmonics, noise, clipping and transients can add crossings or bias the fundamental. No clock calibration is inferred.",
"upward_crossing_count": len(crossings), "estimated_hz": None,
}
if len(crossings) < 3:
result["availability"] = "INSUFFICIENT_CROSSINGS"
return result
periods = [b - a for a, b in zip(crossings, crossings[1:])]
mean_period = statistics.fmean(periods)
result.update(
availability="OBSERVED", estimated_hz=rate / mean_period,
crossing_period_variation_ratio=statistics.pstdev(periods) / mean_period,
measured_span_seconds=(crossings[-1] - crossings[0]) / rate,
)
return result
def channel_metrics(values, bits, rate, segment):
full_scale = 2 ** (bits - 1)
count = len(values)
dc = statistics.fmean(values)
result = {
"rms_full_scale": math.sqrt(sum(value * value for value in values) / count) / full_scale,
"ac_rms_full_scale": math.sqrt(sum((value - dc) ** 2 for value in values) / count) / full_scale,
"peak_full_scale": max(abs(value) for value in values) / full_scale,
"dc_offset_full_scale": dc / full_scale,
"clipping_count": sum(value in (-full_scale, full_scale - 1) for value in values),
"near_zero_ratio": sum(abs(value) <= 1 for value in values) / count,
"near_zero_definition": "absolute signed PCM value <= 1 LSB; a measurement, not an audibility threshold",
"assessment": "MEASURE_BASELINE",
}
if segment["kind"] == "tone":
estimate = tone_estimate(values, rate)
result["frequency"] = estimate
if "nominal_hz" in segment and estimate["estimated_hz"] is not None:
delta = estimate["estimated_hz"] - segment["nominal_hz"]
estimate["nominal_hz"] = segment["nominal_hz"]
estimate["difference_hz"] = delta
tolerance = segment.get("frequency_tolerance")
if tolerance:
estimate["qualified_tolerance"] = tolerance
result["assessment"] = ("WITHIN_QUALIFIED_TOLERANCE" if abs(delta) <= tolerance["absolute_hz"]
else "OUTSIDE_QUALIFIED_TOLERANCE")
return result
def repeated_cases(segments):
groups = {}
for index, segment in enumerate(segments):
if segment.get("vector_id"):
groups.setdefault((segment["case_id"], segment["vector_id"]), []).append(index)
comparisons = []
for (case_id, vector_id), indexes in groups.items():
if len(indexes) < 2:
continue
reference = segments[indexes[0]]
for index in indexes[1:]:
current = segments[index]
if current["kind"] != reference["kind"]:
continue
channels = []
for base, observed in zip(reference["channels"], current["channels"]):
delta = {key + "_difference": observed[key] - base[key]
for key in ("rms_full_scale", "peak_full_scale", "dc_offset_full_scale")}
a = base.get("frequency", {}).get("estimated_hz")
b = observed.get("frequency", {}).get("estimated_hz")
if a is not None and b is not None:
delta["estimated_hz_difference"] = b - a
channels.append(delta)
comparisons.append({
"case_id": case_id, "vector_id": vector_id,
"reference_segment_index": indexes[0], "observed_segment_index": index,
"duration_difference_seconds": current["sample_duration_seconds"] - reference["sample_duration_seconds"],
"channels": channels, "assessment": "OBSERVED",
})
return comparisons
def analyze(wav_path, manifest_path):
samples, info = load_pcm(wav_path)
manifest_bytes = Path(manifest_path).read_bytes()
try:
document = json.loads(manifest_bytes)
except (ValueError, UnicodeDecodeError) as error:
raise ValueError("invalid JSON manifest: " + str(error)) from error
segments = validate_manifest(document, info)
measurements = []
for segment in segments:
first, stop = segment["start_frame"], segment["stop_frame"]
item = dict(segment)
item.update(
sample_count_per_channel=stop - first,
first_sample_seconds=first / info["sample_rate_hz"],
exclusive_stop_seconds=stop / info["sample_rate_hz"],
sample_duration_seconds=(stop - first) / info["sample_rate_hz"],
byte_offset_in_pcm_payload=first * info["channels"] * (info["bit_depth"] // 8),
observation_status="OBSERVED", human_status="NOT_OBSERVED",
channels=[channel_metrics(values[first:stop], info["bit_depth"], info["sample_rate_hz"], segment)
for values in samples],
)
measurements.append(item)
return {
"schema_version": 1, "capture": info,
"manifest": {"filename": Path(manifest_path).name, "sha256": sha256(manifest_bytes)},
"reported_capture_context": document.get("capture_context", {}) if isinstance(document, dict) else {},
"assessment": "MEASURE_BASELINE", "human_status": "NOT_OBSERVED",
"interval_convention": "[start_seconds,end_seconds); include sample timestamps n/rate in that interval; frames are zero based",
"limitations": "Measurements do not establish listening success, hardware identity, calibrated clock accuracy, analog equality or cross-target compatibility. Capture context is supplied by the user, not verified.",
"segments": measurements, "repeated_cases": repeated_cases(measurements),
}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("wav", type=Path)
parser.add_argument("manifest", type=Path)
parser.add_argument("--output", type=Path, help="JSON output; stdout if omitted; existing files protected")
parser.add_argument("--overwrite", action="store_true", help="explicitly replace an existing report (never an input)")
args = parser.parse_args(argv)
try:
if args.output and args.output.resolve() in (args.wav.resolve(), args.manifest.resolve()):
raise ValueError("report output cannot replace either input")
report = analyze(args.wav, args.manifest)
serialized = json.dumps(report, indent=2, allow_nan=False) + "\n"
if args.output:
with args.output.open("w" if args.overwrite else "x", encoding="utf-8") as output:
output.write(serialized)
else:
sys.stdout.write(serialized)
except (ValueError, OSError) as error:
parser.exit(2, "error: " + str(error) + "\n")
return 0
if __name__ == "__main__":
sys.exit(main())
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Build the standalone 35-track Sound Lab disk using the pinned CMOC bundle."""
# SPDX-License-Identifier: GPL-3.0-or-later
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
PROJECT = Path(__file__).resolve().parent
REPO = PROJECT.parents[1]
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def run(*args, **kwargs):
subprocess.run([str(a) for a in args], check=True, **kwargs)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--toolchain', type=Path, default=REPO/'platforms/macos/LocalResources/ToolchainBundle')
parser.add_argument('--output', type=Path, default=REPO/'.build/sound-lab')
args = parser.parse_args()
output, runtime = args.output.resolve(), args.toolchain.resolve()
if output == PROJECT or PROJECT in output.parents:
parser.error('Choose a build output outside the source project so generated files cannot become source inputs.')
output.mkdir(parents=True, exist_ok=True)
env = dict(os.environ, PATH=str(runtime/'bin')+os.pathsep+os.environ.get('PATH', ''))
version = subprocess.check_output([runtime/'bin/cmoc', '--version'], text=True).strip()
if '0.1.101' not in version:
parser.error('This revision is qualified with CMOC 0.1.101; review a different compiler explicitly.')
assembler = subprocess.check_output([runtime/'bin/lwasm', '--version'], text=True).strip()
if assembler != 'lwasm from lwtools 4.25':
parser.error('This revision is qualified with LWTools 4.25.')
run('python3', PROJECT/'vectors/generate.py', '--output', output/'generated')
vectors = json.loads((output/'generated/vectors.json').read_text())
sources = sorted(p for p in PROJECT.rglob('*') if p.is_file() and '__pycache__' not in p.parts)
source_hash = hashlib.sha256()
for source in sources:
source_hash.update(source.relative_to(PROJECT).as_posix().encode()+b'\0'+source.read_bytes())
build_id = 'SL1-'+source_hash.hexdigest()[:8].upper()
(output/'generated/build.h').write_text(
'#define SOUNDLAB_BUILD "'+build_id+'"\n#define SOUND_VECTOR_SET_CRC16 0x'+vectors['vector_set_crc16']+'\n')
shutil.copy2(PROJECT/'guest/main.c', output/'main.c')
run(runtime/'bin/cmoc', '--coco', '-O2', '--intermediate', '--org=1600', '--limit=7A00',
'--stack-space=1024', '-Igenerated', '-o', 'SOUNDLAB.BIN', 'main.c', '-lssc', '-ldecbfile', cwd=output, env=env)
(output/'SOUNDLAB.BAS').write_bytes(b'10 PCLEAR1:CLEAR 32\n20 LOADM"SOUNDLAB":EXEC\n')
# Public-domain DOS hook by Pierre Sarrazin, retained with its attribution.
# Keep the hook itself as a normal source, with no Makefile parsing at build time.
shutil.copy2(PROJECT/'guest/boot.c', output/'boot.c')
run(runtime/'bin/cmoc', '--dos', '-O0', '--limit=2800', '-o', 'BOOT.BIN', 'boot.c', cwd=output, env=env)
disk = output/'SOUNDLAB.DSK'
disk.write_bytes(b'\xff'*(35*18*256))
run(runtime/'bin/install-coco-boot-loader', disk, output/'BOOT.BIN', env=env)
for name in ('SOUNDLAB.BIN', 'SOUNDLAB.BAS'):
run(runtime/'bin/writecocofile', *(['--newlines'] if name.endswith('.BAS') else ['--binary']), disk, name, cwd=output, env=env)
manifest = dict(vectors, build_id=build_id, compiler=version,
assembler=assembler,
toolchain_manifest_sha256=digest(runtime/'manifest.json'),
libraries=[dict(filename=name,sha256=digest(runtime/'share/cmoc/lib'/name))
for name in ('libssc.a','libdecbfile.a')],
sources=[dict(path=p.relative_to(PROJECT).as_posix(),sha256=digest(p)) for p in sources],
guest_cpu='MC6809', minimum_ram_kib=64, format='DECB 35x18x256',
source_sha256=source_hash.hexdigest(),
artifacts=[dict(filename=name, bytes=(output/name).stat().st_size, sha256=digest(output/name))
for name in ('SOUNDLAB.BIN', 'SOUNDLAB.BAS', 'SOUNDLAB.DSK')])
(output/'SOUNDLAB-manifest.json').write_text(json.dumps(manifest, indent=2)+'\n')
(output/'SHA256SUMS').write_text(''.join(f"{item['sha256']} {item['filename']}\n" for item in manifest['artifacts']))
print(f'Built {build_id}: {disk}')
if __name__ == '__main__':
main()
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Build/check Sound Lab; optional isolated native qualification uses explicit private inputs."""
# SPDX-License-Identifier: GPL-3.0-or-later
import argparse
import os
from pathlib import Path
import subprocess
import sys
PROJECT=Path(__file__).resolve().parent
REPO=PROJECT.parents[1]
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--toolchain',type=Path,default=REPO/'platforms/macos/LocalResources/ToolchainBundle')
parser.add_argument('--output',type=Path,default=REPO/'.build/sound-lab')
parser.add_argument('--core',type=Path,help='Existing libVCCCore.a; never changes or rebuilds the emulator')
parser.add_argument('--roms',type=Path,help='Private local CoCo3/Disk BASIC/PIC/SP ROM directory; not packaged')
args=parser.parse_args()
if bool(args.core)!=bool(args.roms): parser.error('--core and --roms must be supplied together')
output=args.output.resolve()
env=dict(os.environ,PYTHONDONTWRITEBYTECODE='1')
def run(*command): subprocess.run([str(p) for p in command],check=True,env=env)
run(sys.executable,'-m','unittest','discover','-s',PROJECT/'tests','-v')
run(sys.executable,PROJECT/'build.py','--toolchain',args.toolchain,'--output',output)
assembly=(output/'main.s').read_text()
status=assembly.split('_raw_status\tEQU\t*',1)[1].split('funcend_raw_status',1)[0]
if status.upper().count('LDB $FF7E')!=1:
raise RuntimeError('Generated raw status reader must contain exactly one actual FF7E load')
if args.core:
run('xcrun','clang++','-std=c++17','-O2','-mmacosx-version-min=14.0',
PROJECT/'native/run.cpp',args.core.resolve(),'-o',output/'run')
run(output/'run',args.roms.resolve(),output/'SOUNDLAB.DSK',output/'qualification')
run(sys.executable,PROJECT/'verify_reports.py','--build-dir',output)
else:
print('Native execution SKIPPED: provide --core and --roms for real-ROM qualification.')
if __name__=='__main__': main()
+38
View File
@@ -0,0 +1,38 @@
/* Public domain. Adapted from Pierre Sarrazin's autostart.c 0.1.2 (2018-08-04).
* http://sarrazip.com/ -- Roger Schrag, The Rainbow, Nov 1984, p.140.
* DOS feeds an ordinary Disk BASIC command; no emulator-specific loader.
*/
#include <coco.h>
static byte oldHookInstr;
static word oldHookAddr;
static const char *basicLineReader;
void feedKeyboard(void)
{
word preservedX;
byte nextBasicByte;
asm("stx", preservedX);
*(byte *)0x70=0;
nextBasicByte=*basicLineReader++;
if(!nextBasicByte) {
*(byte *)0x016A=oldHookInstr;
*(word *)0x016B=oldHookAddr;
nextBasicByte='\r';
}
asm {
lda nextBasicByte
ldx preservedX
tfr u,s
leas 4,s
rts
}
}
int main(void)
{
*(byte *)0=-*(byte *)0;
basicLineReader="PCLEAR1:CLEAR32:LOADM\"SOUNDLAB\":EXEC";
oldHookInstr=*(byte *)0x016A; oldHookAddr=*(word *)0x016B;
*(byte *)0x016A=0x7E; *(void **)0x016B=(void *)feedKeyboard;
*(word *)0x2600=0;
asm("jmp", "$ac7c");
return 0;
}
+317
View File
@@ -0,0 +1,317 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Sound Lab: ordinary 6809/Disk BASIC guest. No emulator-private API.
* Audio routing uses the existing GPL VCC Plus SSC SDK unchanged.
*/
#include <cmoc.h>
#include <coco.h>
#include <decbfile.h>
#include <vcc/ssc.h>
#include "vectors.h"
#include "build.h"
#define LOG_CAPACITY 1536
/* PCLEAR1 reserves the one unused PMODE page at $0E00..$13FF.
* Sound Lab is text-only; using that page leaves ample native stack space. */
#define logbuf ((char *)0x0E00)
static char linebuf[180], note[49];
static unsigned used, records, checksum, runno=1, route, transmitted, elapsed;
static unsigned saved_used, saved_records, saved_checksum;
static unsigned char saved_complete, have_checkpoint;
static unsigned char disk_mode, created, aborted, timedout, before, after, busy_seen;
static unsigned char disk_error, group, target, video, model;
static unsigned attempt;
static DECBDrive drives[1];
static DECBFile report;
static char filename[13];
static const char *targets[]={"VCCPLUS","REAL_COCO","MISTER"};
static const char *models[]={"COCO3","COCO2_64K","UNKNOWN_64K"};
/* Unlike a C volatile expression, each call really reads the bus once. */
asm unsigned char raw_status(void) { asm { ldb $FF7E } }
asm unsigned ticks(void) { asm { ldd $0112 } }
asm void put_byte(unsigned char value) { asm { ldb 3,s
stb $FF7E } }
static unsigned crc_byte(unsigned crc, unsigned char c)
{
unsigned char bit;
crc ^= (unsigned)c << 8;
for(bit=0;bit<8;++bit) crc=(crc&0x8000)?(crc<<1)^0x1021:crc<<1;
return crc;
}
static void record(const char *s)
{
unsigned n=strlen(s), i;
if(used+n+2>=LOG_CAPACITY) return; /* Caller reserves one full case. */
for(i=0;i<n;++i) { logbuf[used++]=s[i]; checksum=crc_byte(checksum,s[i]); }
logbuf[used++]='\r'; checksum=crc_byte(checksum,'\r');
logbuf[used++]='\n'; checksum=crc_byte(checksum,'\n');
++records;
}
static unsigned char key(void)
{
unsigned char c;
do c=inkey(); while(!c);
return (unsigned char)toupper(c);
}
static void header(const char *title)
{
cls(0); printf("SOUND LAB %s\n%s\n\n",SOUNDLAB_BUILD,title);
}
static void make_name(void) { sprintf(filename,"SND%04u.TXT",runno); }
static unsigned char reserve_report(void)
{
unsigned char err;
while(runno<=9999) {
make_name();
err=decb_createSectorFile(&report,0,filename,DECB_TYPE_ASCII_TEXT,DECB_FORMAT_ASCII);
if(err==DECB_OK) { created=1; return decb_closeSectorFile(&report); }
if(err!=DECB_ERR_ALREADY_EXISTS) return err;
++runno;
}
return DECB_ERR_OUT_OF_SPACE;
}
/* Rewrites only the file reserved by this run, never an existing report.
* RAM remains authoritative after an I/O failure. Close flushes FAT+directory.
* No disk I/O occurs while a test is producing sound.
*/
static void footer_text(char *footer,unsigned char complete,unsigned count,unsigned crc)
{
unsigned n;
sprintf(footer,"ENDRUN=%04u COMPLETE=%s RECORD_COUNT=%u CHECKSUM_CRC16=%04X",
runno,complete?"YES":"NO",count,crc);
n=strlen(footer); footer[n++]='\r'; footer[n++]='\n'; footer[n]=0;
}
static unsigned char save_report(unsigned char complete)
{
char footer[110];
unsigned length, index, offset, i, n;
unsigned char sector[256], err;
unsigned sectors;
dword file_size;
if(!disk_mode) return 0;
if(!created) { err=reserve_report(); if(err) return err; }
footer_text(footer,complete,records,checksum);
length=used+strlen(footer);
err=decb_openSectorFile(&report,0,filename); if(err) return err;
if(have_checkpoint) {
footer_text(footer,saved_complete,saved_records,saved_checksum);
if(decb_getOpenFileSize(&report,&sectors,&file_size)==255 || file_size!=(dword)(saved_used+strlen(footer))) return 250;
for(index=0,offset=0;offset<file_size;++index) {
err=decb_readSector(&report,sector,index); if(err) return err;
n=(unsigned)file_size-offset; if(n>256) n=256;
for(i=0;i<n;++i) if(sector[i]!=(unsigned char)((offset+i<saved_used)?logbuf[offset+i]:footer[offset+i-saved_used])) return 250;
offset+=n;
}
footer_text(footer,complete,records,checksum);
}
for(index=0,offset=0;offset<length;++index) {
n=length-offset; if(n>256) n=256;
memset(sector,0,256);
for(i=0;i<n;++i) sector[i]=(offset+i<used)?logbuf[offset+i]:footer[offset+i-used];
err=decb_writeSector(&report,sector,index);
if(err) { decb_closeSectorFile(&report); return err; }
offset+=n;
}
err=decb_setNumBytesUsedInLastSector(&report,n);
if(!err) err=decb_closeSectorFile(&report);
if(!err) { saved_used=used; saved_records=records; saved_checksum=checksum; saved_complete=complete; have_checkpoint=1; }
return err;
}
static void begin_report(void)
{
used=records=0; checksum=0xFFFF;
created=have_checkpoint=0;
if(disk_mode) disk_error=reserve_report();
make_name();
record("FORMAT=SOUNDLAB-1");
sprintf(linebuf,"RUN=%04u TARGET=%s BUILD_ID=%s VECTOR_SET_CRC16=%04X",runno,targets[target],SOUNDLAB_BUILD,SOUND_VECTOR_SET_CRC16); record(linebuf);
sprintf(linebuf,"MODEL=%s VIDEO=%s SPEED=NORMAL_USER_CONFIRMED",models[model],video?"PAL":"NTSC"); record(linebuf);
record("CARTRIDGE=USER_CONFIRMED_NO_AUTODETECTION");
record("MPI_SLOT=USER_CONFIGURED_NO_BANK_SWITCH");
record("TIMING=VSYNC_TICKS_NOT_AUDIO_SAMPLES");
record("ANALOG_LIMITS=MEASURE_BASELINE");
if(disk_mode && !disk_error) disk_error=save_report(0);
}
/* A tick deadline AND independent iteration bound; X interrupts a wait.
* No claim that an idle bit proves a cartridge is present or audible.
*/
static unsigned char ready_write(unsigned char value)
{
unsigned start=ticks();
unsigned long polls=0;
unsigned char status;
for(;;) {
status=raw_status();
if(status&0x80) { put_byte(value); ++transmitted; return 1; }
if((unsigned)(ticks()-start)>=180 || ++polls>=150000UL) { timedout=1; return 0; }
if((polls&255)==0 && toupper(inkey())=='X') { aborted=1; return 0; }
}
}
static void settle(const SoundVector *v)
{
unsigned start=ticks(), d;
unsigned long polls=0;
unsigned char status;
for(;;) {
status=raw_status();
d=ticks()-start;
if(v->wait_mask && (status&v->wait_mask)!=v->wait_mask) busy_seen=1;
if(d>=v->hold_ticks && (!v->wait_mask || ((status&v->wait_mask)==v->wait_mask && (busy_seen || d>=45)))) break;
if(d>=1800 || ++polls>=1500000UL) { timedout=1; break; }
if((polls&255)==0 && toupper(inkey())=='X') { aborted=1; break; }
}
elapsed=ticks()-start;
}
static void stop_case(void)
{
if(aborted || timedout) ssc_reset(); /* Partial packets require reset. */
else if(!ready_write(0)) ssc_reset(); /* Manual: stop speech + sound. */
}
static void get_note(void)
{
unsigned char c, n=0;
printf("NOTE (48 CHARS, ENTER ENDS):\n");
while((c=key())!='\r') {
if(c==8 && n) { --n; putchar(8); }
else if(c>=32 && c<=126 && c!='\\' && n<48) { note[n++]=c; putchar(c); }
}
note[n]=0;
}
static unsigned char run_case(const SoundVector *v)
{
unsigned i, sent;
unsigned char answer;
unsigned repeat;
const char *human, *automatic;
do {
if(used>LOG_CAPACITY-450) {
if(!disk_mode) {
printf("RAM REPORT FULL. PHOTOGRAPH IT.\nX MENU / C CLEAR FOR NEXT RUN\n");
if(key()!='C') return 0;
}
disk_error=save_report(1);
if(disk_error) { printf("REPORT FULL. SAVE FIRST.\n"); key(); return 0; }
++runno; begin_report();
}
repeat=attempt++;
header(v->id);
ssc_reset(); /* Declared per-case baseline; never inherited timer state. */
printf("%s\n\n%s\n\nX: PANIC / RETURN TO MENU\n",v->title,v->prompt);
printf("\nENTER TO PLAY / X MENU\n");
do answer=key(); while(answer!='\r' && answer!='X');
if(answer=='X') return 0;
printf("PLAYING...\n");
transmitted=elapsed=0; aborted=timedout=busy_seen=0;
before=raw_status();
for(i=0;i<v->length;++i) if(!ready_write(v->tx[i])) break;
sent=transmitted;
if(!aborted && !timedout) settle(v);
after=raw_status();
stop_case();
header(v->id);
printf("ATTEMPT %u CRC %04X TX %u/%u\nSTATUS %02X > %02X TICKS %u\n%s\n\n",
repeat,v->crc16,sent,v->length,before,after,elapsed,aborted?"ABORTED":timedout?"TIMEOUT / RESET":"AUTO: OBSERVED ONLY");
printf("H HEARD W WRONG\nN NO SOUND U UNSURE\nR REPEAT S SKIP\nT ADD NOTE X MENU\n\n");
note[0]=0;
do { answer=key(); if(answer=='T') get_note(); }
while(!strchr("HWNURSX",answer));
human=answer=='H'?"HEARD":answer=='W'?"WRONG":answer=='N'?"NO_SOUND":answer=='U'?"UNSURE":answer=='S'?"SKIPPED":"NOT_OBSERVED";
automatic=timedout?"TIMEOUT":aborted&&!sent?"NOT_RUN":"OBSERVED";
sprintf(linebuf,"CASE=%s VECTOR_CRC16=%04X AUTO=%s HUMAN=%s",v->id,v->crc16,automatic,human); record(linebuf);
sprintf(linebuf,"TX_COUNT=%u TX_EXPECTED=%u TICKS=%u STATUS_BEFORE=%02X STATUS_AFTER=%02X BUSY_SEEN=%s",sent,v->length,elapsed,before,after,busy_seen?"YES":"NO"); record(linebuf);
record("PRELUDE=RESET_01_00 TIMER=RESET_DEFAULT");
sprintf(linebuf,"ABORTED=%s CLEANUP=%s REPEAT=%u",aborted?"YES":"NO",(aborted||timedout)?"RESET":"00",repeat); record(linebuf);
sprintf(linebuf,"NOTE_LENGTH=%u",strlen(note)); record(linebuf);
sprintf(linebuf,"NOTE=%s",note); record(linebuf);
sprintf(linebuf,"ENDCASE=%s",v->id); record(linebuf);
disk_error=save_report(0);
if(disk_error) { printf("DISK ERROR %u: RAM RETAINED\n",disk_error); key(); }
if(answer=='X') return 0;
} while(answer=='R');
return 1;
}
static void show_report(void)
{
unsigned offset=0, rows;
header("FROZEN REPORT");
while(offset<used) {
cls(0); rows=0;
while(offset<used && rows<11) {
unsigned col=0;
while(offset<used && logbuf[offset]!='\r' && col<30) { putchar(logbuf[offset++]); ++col; }
if(offset<used && logbuf[offset]=='\r') offset+=2;
putchar('\n'); ++rows;
}
printf("\nRUN %04u %s\nANY KEY NEXT / X MENU",runno,filename);
if(key()=='X') break;
}
}
int main(void)
{
unsigned i;
unsigned char choice;
width(32);
header("WELCOME, LISTENER");
printf("NORMAL SPEED, 64K+, DISK BASIC\nSSC RAM/BUFFERS WILL BE RESET.\nLOW SPEAKER VOLUME TO START.\n\n1 VCC PLUS 2 REAL COCO\n3 MISTER\n");
do choice=key(); while(choice<'1'||choice>'3'); target=choice-'1';
header("SETUP");
printf("1 COCO 3 2 COCO 2 3 OTHER\n");
do choice=key(); while(choice<'1'||choice>'3'); model=choice-'1';
printf("N NTSC / P PAL\n"); do choice=key(); while(choice!='N'&&choice!='P'); video=choice=='P';
printf("\nD SAVE REPORTS TO THIS FD0\nM SCREEN ONLY / NO DISK I/O\nUSE A DISPOSABLE DISK COPY!\n");
do choice=key(); while(choice!='D'&&choice!='M'); disk_mode=choice=='D';
if(disk_mode) {
disk_error=decb_init(drives,1);
if(!disk_error) disk_error=decb_registerDrive(0);
if(disk_error) disk_mode=0;
}
route=ssc_route_audio();
ssc_reset();
begin_report();
for(;;) {
header("MAIN MENU");
printf("1 MEET THE ROBOT\n2 GUIDED LISTENING LAB\n3 ENGINEERING (OPT IN)\n4 CHOOSE A CASE\n5 VIEW RAM REPORT\n6 RETRY SAVE\nQ SAVE AND QUIT TO BASIC\n\nRUN %04u %s\n%s\n",runno,filename,!disk_mode?"SCREEN ONLY":disk_error?"DISK ERROR / RAM RETAINED":"REPORT SAVED BETWEEN CASES");
choice=key();
if(choice=='Q') {
disk_error=save_report(1);
if(disk_error) { printf("SAVE FAILED. X DISCARD OR RETRY\n"); if(key()!='X') continue; }
break;
}
if(choice=='5') { show_report(); continue; }
if(choice=='6') { disk_error=save_report(0); continue; }
if(choice=='4') {
char id[16]; unsigned char n=0,c;
header("CHOOSE CASE"); printf("CASE ID (UPPERCASE), ENTER:\n");
while((c=key())!='\r') if(n<15 && ((c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='-')) { id[n++]=c; putchar(c); }
id[n]=0;
for(i=0;i<SOUND_VECTOR_COUNT;++i) if(!strcmp(id,sound_vectors[i].id)) { run_case(&sound_vectors[i]); break; }
if(i==SOUND_VECTOR_COUNT) { printf("\nUNKNOWN CASE. SEE MANIFEST.\n"); key(); }
continue;
}
if(choice<'1'||choice>'3') continue;
group=(unsigned char)(1<<(choice-'1'));
if(group==4) { header("ENGINEERING"); printf("MANY LOUD/REPEATED EXAMPLES.\nLOWER VOLUME. Y CONTINUE\n"); if(key()!='Y') continue; }
for(i=0;i<SOUND_VECTOR_COUNT;++i) if(sound_vectors[i].group&group) if(!run_case(&sound_vectors[i])) break;
}
ssc_reset();
ssc_restore_audio(route);
if(disk_mode) decb_shutdown();
cls(0); printf("SOUND LAB FINISHED\nREPORT %s\n",disk_mode?(const char *)filename:"SCREEN ONLY");
return 0;
}
+157
View File
@@ -0,0 +1,157 @@
# Sound Lab host reports
`python3 soundlab_reports.py` requires Python 3.10 or later and only the standard
library. It reads existing disk images and report files; it does not run the
emulator, touch a mounted disk, contact a service or modify source inputs.
## Extract and preserve reports
Quit or safely eject/save the writable diagnostic disk first, then copy it to a
host working folder. Extract from that saved copy:
```sh
python3 examples/sound-lab/host/soundlab_reports.py extract /path/to/SOUNDLAB.DSK \
--output /path/to/run-exports
```
The input must be a raw, single-sided, standard 35-track Disk BASIC disk image:
35 tracks × 18 sectors × 256 bytes = 161,280 bytes. DMK, images with headers and
other geometries are rejected rather than guessed. Selected filenames are
`SND0000.TXT` through `SND9999.TXT`, case-insensitively. Reports must have the
Disk BASIC ASCII flag `FF`; the guest writes directory type 3 (text). The tool
preserves every selected file's exact bytes, normalizes its output filename to
uppercase, and writes `extraction.json` with the original disk's SHA-256, each
report's SHA-256/byte count and its granule chain.
Validation covers the directory, file type/ASCII flag, final-sector byte count,
FAT values, fragmented chains, cycles, free granules in a file chain, duplicate
names, unsafe names and crosslinks involving *any* active file. The directory
track is excluded from granule addressing. Unclaimed FAT allocations are allowed
because interrupted writes can leave them; the extractor does not repair them.
It validates filesystem structure, not the authenticity of the disk's contents.
An existing output is never replaced implicitly. Prefer a fresh output folder
for each run. `--overwrite` permits replacement of ordinary output files only;
symlinks, inputs and hardlinks to inputs are still rejected. Keep the source
`.DSK` and extracted `.TXT` as original evidence. The extractor never reformats,
repairs or writes back to the disk.
## Convert and compare
```sh
python3 examples/sound-lab/host/soundlab_reports.py convert \
/path/to/run-exports/SND0001.TXT --output /path/to/readable-run \
--manifest .build/sound-lab/SOUNDLAB-manifest.json
python3 examples/sound-lab/host/soundlab_reports.py compare \
/path/to/vcc/SND0001.TXT /path/to/real-coco/SND0001.TXT \
--output /path/to/comparison \
--manifest .build/sound-lab/SOUNDLAB-manifest.json
```
Conversion writes JSON, CSV and a self-contained readable HTML file. The JSON
retains all recorded run metadata and per-case fields; CSV keeps raw timing/status
fields as columns. The HTML escapes report text and includes no scripts or remote
assets. No audio files or listening claims are manufactured.
The optional authoritative manifest has this supported structure (other fields
such as artifact hashes may also be present):
```json
{
"build_id": "BUILD-IDENTITY",
"vector_set_crc16": "1234",
"vectors": [{"case_id": "TON01-A", "crc16": "7ABC"}]
}
```
The vector list may alternatively be an object such as
`"vectors": {"TON01-A": "7ABC"}`. CRC values in the manifest may be four-digit
hex strings, strings prefixed with `0x`, or JSON integers. Use ordinary four-digit
hex in report records. Uppercase manifest keys `BUILD_ID` and
`VECTOR_SET_CRC16` are accepted aliases. A manifest binds the guest's short build
and vector IDs to the host build receipt; a CRC is not a cryptographic signature.
The separate artifact hashes establish which binary/disk bytes were built.
Comparison requires the same nonempty `BUILD_ID`, `VECTOR_SET_CRC16` and matching
per-case `VECTOR_CRC16`. With a manifest, both reports must match its declared
identities too. Without one, the result explicitly states
`identity_basis=REPORT_CLAIMS_ONLY`. Different/missing identities, missing cases,
partial reports or failed integrity checks produce `NOT_COMPARABLE`, with the
recorded evidence still shown. Comparable cases show `SAME` or `DIFFERENT` and
list differing metrics, raw status, timings or notes. Matching these values does
**not** establish matching audible output or equal analog timing precision.
`AUTO` and `HUMAN` are separate columns. `AUTO=OBSERVED` never becomes
`HUMAN=HEARD`. Missing outcomes remain `UNKNOWN`; unknown timing resolution stays
unknown. The tool checks report consistency and identities; it does not certify
the author's automatic verdict or make hardware pass/fail assertions.
Exit status is 0 for successful valid conversion/comparison or extraction, 1 for
an unreadable/unsupported input or refused output, and 2 when result files were
written but evidence is partial, invalid or not comparable. Inspect the JSON/HTML
issues instead of treating exit 2 as a completed run. Optional absent checksum or
count fields are explicitly `NOT_PROVIDED`, never `VERIFIED`.
## SOUNDLAB-1 record contract
The first nonblank line is exactly `FORMAT=SOUNDLAB-1`. Subsequent ordinary lines
contain space-separated `KEY=VALUE` tokens with uppercase keys and nonempty values.
Values containing whitespace belong in escaped `NOTE` records. CRLF is preferred;
LF is accepted. Bare CR, non-ASCII bytes and unescaped control characters are
rejected. Empty/whitespace-only lines are ignored for record counts and checksums.
Unknown metadata and per-case keys are retained for forward-compatible evidence.
A different `FORMAT` requires a new parser version.
A header declares the run, target and build/vector identity. A case starts with
`CASE=... VECTOR_CRC16=HHHH AUTO=... HUMAN=...`; subsequent lines carry its metrics.
`ENDCASE` must match that case's identity. A per-case `REPEAT=0` field identifies
the first attempt, `REPEAT=1` the next, and so on. Each `(CASE, REPEAT)` pair must
be unique within a report. Omitted `REPEAT` defaults to 0 for early SOUNDLAB-1
compatibility. Attempts are retained separately in JSON/CSV/HTML and compared by
that pair, even if recorded in a different order. An interrupted case/run is preserved
and marked incomplete. Case IDs and outcome enumerations compare
case-insensitively; the original text/fields remain available.
Allowed automatic values: `PASS`, `FAIL`, `OBSERVED`, `TIMEOUT`, `NOT_RUN`,
`NOT_APPLICABLE`. Allowed human values: `HEARD`, `WRONG`, `NO_SOUND`, `UNSURE`,
`NOT_OBSERVED`, `SKIPPED`.
An optional note consists of two consecutive records inside a case:
```text
NOTE_LENGTH=18
NOTE=FIRST LINE\nSECOND!\n
```
`NOTE_LENGTH` counts decoded ASCII **bytes**, not the serialized escape length.
Escapes are `\\`, `\n`, `\r`, `\t` and `\xHH` (ASCII 00–7F). `NOTE=` consumes the
rest of its line, including spaces. Length mismatch, unknown escapes, a dangling
length or a note outside a case is reported as invalid/incomplete evidence.
A finished run ends with one footer, with no following nonblank records:
```text
ENDRUN=0001 COMPLETE=YES RECORD_COUNT=8 CHECKSUM_CRC16=1234
```
The run number must match `RUN`. `COMPLETE=NO` explicitly retains an interrupted
run. Footer integrity fields are optional for interoperability; the diagnostic
writer supplies both. `RECORD_COUNT` is the number of preceding nonblank lines,
including `FORMAT` and every case, note and `ENDCASE` line, excluding the footer.
`CHECKSUM_CRC16` is CRC-16/CCITT-FALSE: polynomial `1021`, initial `FFFF`, no
reflection, no final XOR. It covers those same original nonblank lines joined
with CRLF, **including a final CRLF**, and excludes the footer. Lowercase and
uppercase hex are equivalent. Example footer values above are schematic.
## ROM-free checks
```sh
python3 -m unittest discover -s examples/sound-lab/tests -p test_reports.py -v
```
The authored fixtures cover fragmented disks across the reserved track, full
sectors/granules, truncation, malformed FAT and loops/crosslinks, report end
markers, notes, count/checksum validation, independent outcome comparisons,
manifest identities, raw metric differences and output preservation. They use no
private ROMs, real reports or actual hardware recordings.
+525
View File
@@ -0,0 +1,525 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only Sound Lab Disk BASIC extraction and evidence reporting (stdlib only)."""
from __future__ import annotations
import argparse
import csv
import hashlib
import html
import io
import json
from pathlib import Path
import re
import sys
from typing import Any
DISK_SIZE = 35 * 18 * 256
FAT_OFFSET = (17 * 18 + 1) * 256
DIRECTORY_OFFSET = (17 * 18 + 2) * 256
REPORT_NAME = re.compile(r"SND[0-9]{4}\.TXT", re.IGNORECASE)
KEY = re.compile(r"[A-Z][A-Z0-9_]*")
AUTO = frozenset("PASS FAIL OBSERVED TIMEOUT NOT_RUN NOT_APPLICABLE".split())
HUMAN = frozenset("HEARD WRONG NO_SOUND UNSURE NOT_OBSERVED SKIPPED".split())
class SoundLabError(ValueError):
"""An invalid disk/report or unsafe output operation."""
def crc16(data: bytes) -> int:
"""CRC-16/CCITT-FALSE: polynomial 1021, initial FFFF, no reflection/xor."""
result = 0xFFFF
for value in data:
result ^= value << 8
for _ in range(8):
result = ((result << 1) ^ (0x1021 if result & 0x8000 else 0)) & 0xFFFF
return result
def granule_offset(granule: int) -> int:
track = granule // 2 + (1 if granule >= 34 else 0)
return (track * 18 + (granule % 2) * 9) * 256
def extract_reports(disk: bytes) -> list[dict[str, Any]]:
"""Validate active DECB files, return SNDnnnn.TXT ASCII bytes; never mutate disk.
All active files are walked to catch crosslinks into a selected report. Unused
FAT allocations are tolerated: they can remain after an interrupted write.
"""
if len(disk) != DISK_SIZE:
raise SoundLabError(f"Expected raw 35-track DSK ({DISK_SIZE} bytes), got {len(disk)}")
fat = disk[FAT_OFFSET:FAT_OFFSET + 68]
for index, value in enumerate(fat):
if not (value < 68 or 0xC0 <= value <= 0xC9 or value == 0xFF):
raise SoundLabError(f"Invalid FAT value {value:02X} at granule {index}")
owned: dict[int, str] = {}
names: set[str] = set()
reports = []
for index in range(72):
entry = disk[DIRECTORY_OFFSET + index * 32:DIRECTORY_OFFSET + (index + 1) * 32]
if entry[0] in (0, 0xFF):
continue
try:
base = entry[:8].decode("ascii").rstrip(" ")
ext = entry[8:11].decode("ascii").rstrip(" ")
except UnicodeDecodeError as error:
raise SoundLabError(f"Non-ASCII directory name at entry {index}") from error
if not base or any(ord(c) < 33 or c in '/\\:.' for c in base + ext):
raise SoundLabError(f"Unsafe directory name at entry {index}")
name = f"{base}.{ext}" if ext else base
normalized = name.upper()
if normalized in names:
raise SoundLabError(f"Duplicate directory name: {name}")
names.add(normalized)
if entry[11] > 3 or entry[12] not in (0, 0xFF):
raise SoundLabError(f"Invalid file type/ASCII flag for {name}")
last_bytes = int.from_bytes(entry[14:16], "big")
if last_bytes > 256:
raise SoundLabError(f"Invalid final-sector byte count for {name}")
chain = []
current = entry[13]
while True:
if current >= 68:
raise SoundLabError(f"Out-of-range granule {current} for {name}")
if current in chain:
raise SoundLabError(f"FAT loop for {name}")
if current in owned:
raise SoundLabError(f"Crosslinked granule {current}: {name} and {owned[current]}")
chain.append(current)
owned[current] = name
value = fat[current]
if 0xC0 <= value <= 0xC9:
final_sectors = value - 0xC0
if final_sectors == 0 and (len(chain) != 1 or last_bytes != 0):
raise SoundLabError(f"Invalid empty final granule for {name}")
if final_sectors > 0 and last_bytes == 0:
# DOS stores 256, not zero, for a completely used last sector.
raise SoundLabError(f"Missing final-sector bytes for {name}")
break
if value == 0xFF:
raise SoundLabError(f"Allocated file {name} points to free granule {current}")
current = value
length = (len(chain) - 1) * 2304
if final_sectors:
length += (final_sectors - 1) * 256 + last_bytes
if REPORT_NAME.fullmatch(name):
if entry[12] != 0xFF:
raise SoundLabError(f"Report {name} is not marked Disk BASIC ASCII")
content = b"".join(disk[granule_offset(g):granule_offset(g) + 2304] for g in chain)[:length]
reports.append({"filename": normalized, "data": content,
"byte_count": len(content), "sha256": hashlib.sha256(content).hexdigest(),
"granules": chain, "directory_type": entry[11]})
return sorted(reports, key=lambda item: item["filename"])
def decode_note(value: str) -> str:
decoded = bytearray()
i = 0
while i < len(value):
char = value[i]
if char != "\\":
if not 32 <= ord(char) <= 126:
raise SoundLabError("Notes must use printable ASCII or escaped control bytes")
decoded.append(ord(char))
i += 1
continue
i += 1
if i >= len(value):
raise SoundLabError("Incomplete note escape")
escaped = value[i]
if escaped in "\\nrt":
decoded.append({"\\": 92, "n": 10, "r": 13, "t": 9}[escaped])
i += 1
elif escaped == "x" and i + 2 < len(value) and re.fullmatch(r"[0-9A-Fa-f]{2}", value[i + 1:i + 3]):
byte = int(value[i + 1:i + 3], 16)
if byte > 127:
raise SoundLabError("Escaped notes must remain ASCII")
decoded.append(byte)
i += 3
else:
raise SoundLabError(f"Unknown note escape at position {i}")
return decoded.decode("ascii")
def parse_tokens(line: str) -> dict[str, str]:
fields = {}
for token in line.split():
if "=" not in token:
raise SoundLabError(f"Expected KEY=VALUE token: {token}")
key, value = token.split("=", 1)
if not KEY.fullmatch(key) or not value or key in fields:
raise SoundLabError(f"Invalid or duplicate token: {token}")
fields[key] = value
if not fields:
raise SoundLabError("Empty record")
return fields
def parse_report(data: bytes, source: str = "") -> dict[str, Any]:
"""Parse evidence without turning automatic observations into listening results.
Incomplete files are useful evidence, returned with complete=False and issues.
Structural and integrity failures likewise remain visible in JSON/HTML; a
malformed header/encoding is rejected because it is not a SOUNDLAB-1 report.
"""
try:
text = data.decode("ascii")
except UnicodeDecodeError as error:
raise SoundLabError("Report is not ASCII") from error
if "\x00" in text or re.search(r"[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]", text):
raise SoundLabError("Report contains unescaped control bytes")
if "\r" in text.replace("\r\n", ""):
raise SoundLabError("Report has bare CR line endings")
lines = [line for line in text.replace("\r\n", "\n").split("\n") if line.strip()]
if not lines or lines[0] != "FORMAT=SOUNDLAB-1":
raise SoundLabError("Missing supported FORMAT=SOUNDLAB-1 header")
result: dict[str, Any] = {"format": "SOUNDLAB-1", "source": source,
"source_sha256": hashlib.sha256(data).hexdigest(),
"metadata": {}, "cases": [], "issues": [], "complete": False,
"integrity": {"record_count": "NOT_PROVIDED", "checksum_crc16": "NOT_PROVIDED"}}
current = None
footer = None
note_length = None
records = []
def issue(message: str) -> None:
result["issues"].append(message)
def merge(target: dict[str, str], fields: dict[str, str], number: int) -> None:
for key, value in fields.items():
if key in target:
issue(f"Line {number}: duplicate field {key}")
else:
target[key] = value
for number, line in enumerate(lines, 1):
if footer is not None:
issue(f"Line {number}: record after ENDRUN")
continue
if line.startswith("NOTE="):
records.append(line)
try:
note = decode_note(line[5:])
if current is None:
issue(f"Line {number}: NOTE outside CASE")
elif note_length is None:
issue(f"Line {number}: NOTE without NOTE_LENGTH")
else:
current["notes"].append(note)
if len(note.encode("ascii")) != note_length:
issue(f"Line {number}: NOTE_LENGTH mismatch")
except SoundLabError as error:
issue(f"Line {number}: {error}")
note_length = None
continue
if note_length is not None:
issue(f"Line {number}: NOTE_LENGTH not followed by NOTE")
note_length = None
try:
fields = parse_tokens(line)
except SoundLabError as error:
records.append(line)
issue(f"Line {number}: {error}")
continue
controls = set(fields) & {"FORMAT", "RUN", "CASE", "ENDCASE", "ENDRUN", "NOTE_LENGTH"}
if len(controls) > 1:
issue(f"Line {number}: conflicting control records")
if "FORMAT" in fields and number != 1:
issue(f"Line {number}: repeated FORMAT header")
if "RUN" in fields and (current is not None or result["cases"]):
issue(f"Line {number}: RUN header after CASE")
if "ENDRUN" in fields:
footer = fields
result["footer"] = fields
if current is not None:
issue(f"Line {number}: ENDRUN before ENDCASE")
if fields["ENDRUN"] != result["metadata"].get("RUN"):
issue(f"Line {number}: ENDRUN does not match RUN")
if fields.get("COMPLETE", "").upper() not in ("YES", "NO"):
issue(f"Line {number}: COMPLETE must be YES or NO")
continue
records.append(line)
if number == 1:
continue
if "CASE" in fields:
if current is not None:
issue(f"Line {number}: CASE before previous ENDCASE")
identifier = fields["CASE"].upper()
current = {"id": identifier, "fields": {}, "notes": [], "closed": False}
result["cases"].append(current)
merge(current["fields"], fields, number)
elif "ENDCASE" in fields:
if current is None:
issue(f"Line {number}: ENDCASE outside CASE")
else:
if fields["ENDCASE"].upper() != current["id"]:
issue(f"Line {number}: ENDCASE does not match CASE")
else:
current["closed"] = True
current = None
if len(fields) != 1:
issue(f"Line {number}: unexpected ENDCASE fields")
elif "NOTE_LENGTH" in fields:
if len(fields) != 1 or current is None:
issue(f"Line {number}: NOTE_LENGTH must be alone inside CASE")
try:
note_length = int(fields["NOTE_LENGTH"])
if note_length < 0 or note_length > 65535:
raise ValueError()
except ValueError:
note_length = None
issue(f"Line {number}: invalid NOTE_LENGTH")
else:
merge(current["fields"] if current is not None else result["metadata"], fields, number)
if note_length is not None:
issue("Truncated NOTE after NOTE_LENGTH")
if not result["metadata"].get("RUN"):
issue("Missing RUN identity")
attempts: set[tuple[str, int]] = set()
for case in result["cases"]:
try:
repeat_text = case["fields"].get("REPEAT", "0")
if not re.fullmatch(r"[0-9]+", repeat_text):
raise ValueError()
repeat = int(repeat_text)
if repeat > 65535:
raise ValueError()
case["repeat"] = repeat
identity = (case["id"], repeat)
if identity in attempts:
issue(f"CASE {case['id']}: duplicate REPEAT={repeat}")
attempts.add(identity)
except ValueError:
case["repeat"] = None
issue(f"CASE {case['id']}: invalid REPEAT")
for key, allowed in (("AUTO", AUTO), ("HUMAN", HUMAN)):
value = case["fields"].get(key)
if value is None:
# UNKNOWN is deliberate: absence is not a positive or negative observation.
case[key.lower()] = "UNKNOWN"
issue(f"CASE {case['id']}: missing {key}")
else:
case[key.lower()] = value.upper()
if value.upper() not in allowed:
issue(f"CASE {case['id']}: unknown {key} value {value}")
vector_crc = case["fields"].get("VECTOR_CRC16", "")
if not re.fullmatch(r"[0-9A-Fa-f]{4}", vector_crc):
issue(f"CASE {case['id']}: missing or invalid VECTOR_CRC16")
if not case["closed"]:
issue(f"CASE {case['id']}: missing ENDCASE")
if footer is None:
issue("Missing ENDRUN; partial run")
else:
if "RECORD_COUNT" in footer:
try:
valid_count = int(footer["RECORD_COUNT"]) == len(records)
except ValueError:
valid_count = False
result["integrity"]["record_count"] = "VERIFIED" if valid_count else "FAILED"
if not valid_count:
issue("RECORD_COUNT mismatch")
if "CHECKSUM_CRC16" in footer:
canonical = ("\r\n".join(records) + "\r\n").encode("ascii")
expected = f"{crc16(canonical):04X}"
valid_crc = footer["CHECKSUM_CRC16"].upper() == expected
result["integrity"]["checksum_crc16"] = "VERIFIED" if valid_crc else "FAILED"
if not valid_crc:
issue(f"CHECKSUM_CRC16 mismatch (calculated {expected})")
if footer.get("COMPLETE", "").upper() != "YES":
issue("Run marked incomplete")
result["record_count"] = len(records)
result["complete"] = footer is not None and footer.get("COMPLETE", "").upper() == "YES" and not result["issues"]
result["valid"] = not result["issues"]
return result
def validate_manifest(report: dict[str, Any], manifest: dict[str, Any]) -> list[str]:
"""Return exact identity failures; a manifest is evidence, not a trust signature."""
if not isinstance(manifest, dict):
raise SoundLabError("Manifest must be a JSON object")
problems = []
metadata = report["metadata"]
def crc_text(value: Any) -> str:
if isinstance(value, int):
return f"{value:04X}"
return str(value).upper().removeprefix("0X")
for key in ("BUILD_ID", "VECTOR_SET_CRC16"):
expected = manifest.get(key.lower(), manifest.get(key))
expected_text = crc_text(expected) if key.endswith("CRC16") else str(expected).upper()
if expected is None or expected_text != metadata.get(key, "").upper():
problems.append(f"{key} differs from manifest or is absent")
vectors = manifest.get("vectors", {})
if isinstance(vectors, list):
if not all(isinstance(item, dict) for item in vectors):
raise SoundLabError("Manifest vectors must be objects")
vectors = {item.get("id", item.get("case_id", "")): item.get("crc16", item.get("vector_crc16", "")) for item in vectors}
if not isinstance(vectors, dict):
raise SoundLabError("Manifest vectors must be a list or object")
vectors = {str(key).upper(): crc_text(value) for key, value in vectors.items()}
for case in report["cases"]:
expected = vectors.get(case["id"])
if expected is None or expected != case["fields"].get("VECTOR_CRC16", "").upper():
problems.append(f"CASE {case['id']}: vector differs from manifest or is absent")
return problems
def compare_reports(left: dict[str, Any], right: dict[str, Any], manifest: dict[str, Any] | None = None) -> dict[str, Any]:
problems = []
for key in ("BUILD_ID", "VECTOR_SET_CRC16"):
a, b = left["metadata"].get(key), right["metadata"].get(key)
if not a or not b or a.upper() != b.upper():
problems.append(f"{key} differs or is absent")
if manifest is not None:
problems.extend("Left: " + value for value in validate_manifest(left, manifest))
problems.extend("Right: " + value for value in validate_manifest(right, manifest))
if not left["valid"] or not right["valid"]:
problems.append("One or both reports are partial or invalid; outcomes are provisional")
by_id = [{(case["id"], case["repeat"]): case for case in report["cases"]} for report in (left, right)]
rows = []
for identity in sorted(set(by_id[0]) | set(by_id[1]), key=lambda item: (item[0], -1 if item[1] is None else item[1])):
identifier, repeat = identity
a, b = by_id[0].get(identity), by_id[1].get(identity)
reason = list(problems)
if a is None or b is None:
reason.append("CASE missing from one report")
elif a["fields"].get("VECTOR_CRC16", "").upper() != b["fields"].get("VECTOR_CRC16", "").upper():
reason.append("VECTOR_CRC16 differs")
row = {"case": identifier, "repeat": repeat, "left_auto": a["auto"] if a else "UNKNOWN",
"right_auto": b["auto"] if b else "UNKNOWN", "left_human": a["human"] if a else "UNKNOWN",
"right_human": b["human"] if b else "UNKNOWN", "reasons": reason}
changes = {}
if a is not None and b is not None:
for key in sorted(set(a["fields"]) | set(b["fields"])):
if key in ("CASE", "REPEAT", "VECTOR_CRC16", "AUTO", "HUMAN"):
continue
av, bv = a["fields"].get(key), b["fields"].get(key)
if av != bv:
changes[key] = {"left": av, "right": bv}
if a["notes"] != b["notes"]:
changes["NOTES"] = {"left": a["notes"], "right": b["notes"]}
row["recorded_differences"] = changes
outcomes_equal = row["left_auto"] == row["right_auto"] and row["left_human"] == row["right_human"]
row["comparison"] = "NOT_COMPARABLE" if reason else ("SAME" if outcomes_equal and not changes else "DIFFERENT")
rows.append(row)
return {"left": left["source"], "right": right["source"], "identity_issues": problems,
"manifest_checked": manifest is not None, "identity_basis": "MANIFEST" if manifest is not None else "REPORT_CLAIMS_ONLY", "cases": rows,
"notice": "Matching automatic observations do not establish audible equivalence. HUMAN is independent."}
def render_html(document: dict[str, Any]) -> str:
esc = lambda value: html.escape(str(value))
comparison = "left" in document
title = "Sound Lab comparison" if comparison else "Sound Lab report"
pieces = [f'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{title}</title>',
'<style>body{font:16px system-ui;max-width:75rem;margin:2rem auto;padding:0 1rem;line-height:1.5;color:#20252b;background:#fff}table{border-collapse:collapse;width:100%}td,th{padding:.5rem;border:1px solid #999;text-align:left;vertical-align:top}pre{white-space:pre-wrap;overflow-wrap:anywhere}.warning{background:#fff0c2;padding:1rem}code{overflow-wrap:anywhere}</style>', f'<h1>{title}</h1>', '<p>Automatic observations and human listening results are separate evidence. Unknown means unreported; it never means heard.</p>']
issues = document.get("identity_issues", document.get("issues", []))
if issues:
pieces.append('<div class="warning"><strong>Incomplete or unverified evidence</strong><ul>' + ''.join(f'<li>{esc(value)}</li>' for value in issues) + '</ul></div>')
if comparison:
keys = ["case", "repeat", "left_auto", "right_auto", "left_human", "right_human", "comparison", "recorded_differences", "reasons"]
rows = document["cases"]
else:
pieces.append(f'<p>Source: <code>{esc(document["source"])}</code><br>SHA-256: <code>{esc(document["source_sha256"])}</code><br>Complete: {esc(document["complete"])}</p>')
pieces.append('<h2>Run metadata and integrity</h2><pre>' + esc(json.dumps({"metadata": document["metadata"], "integrity": document["integrity"]}, indent=2)) + '</pre>')
keys = ["case", "repeat", "auto", "human", "closed", "notes", "recorded_fields"]
rows = [{"case": case["id"], "repeat": case["repeat"], "auto": case["auto"], "human": case["human"], "closed": case["closed"], "notes": "\n".join(case["notes"]), "recorded_fields": json.dumps(case["fields"], sort_keys=True)} for case in document["cases"]]
pieces.append('<h2>Cases</h2><table><thead><tr>' + ''.join(f'<th scope="col">{esc(key)}</th>' for key in keys) + '</tr></thead><tbody>')
for row in rows:
pieces.append('<tr>' + ''.join(f'<td><pre>{esc(row.get(key, ""))}</pre></td>' for key in keys) + '</tr>')
pieces.append('</tbody></table></html>')
return '\n'.join(pieces)
def render_csv(document: dict[str, Any]) -> str:
stream = io.StringIO(newline="")
if "left" in document:
fields = ["case", "repeat", "left_auto", "right_auto", "left_human", "right_human", "comparison", "recorded_differences", "reasons"]
rows = document["cases"]
else:
# Union preserves timing/status fields, rather than reducing reports to outcomes.
extra = sorted({key for case in document["cases"] for key in case["fields"]} - {"CASE", "REPEAT", "AUTO", "HUMAN"})
fields = ["case", "repeat", "auto", "human", "closed", "notes"] + extra
rows = [{"case": case["id"], "repeat": case["repeat"], "auto": case["auto"], "human": case["human"], "closed": case["closed"], "notes": '\n'.join(case["notes"]), **{key: case["fields"].get(key, "") for key in extra}} for case in document["cases"]]
writer = csv.DictWriter(stream, fieldnames=fields)
writer.writeheader()
writer.writerows(rows)
return stream.getvalue()
def write_outputs(outputs: dict[Path, bytes], overwrite: bool = False) -> None:
"""Preflight every target before any writes; originals are never implicitly replaced."""
for path in outputs:
if path.is_symlink() or (path.exists() and (not overwrite or not path.is_file())):
raise SoundLabError(f"Refusing to replace {path}; select a fresh folder or use --overwrite for regular files")
for path, data in outputs.items():
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb" if overwrite else "xb") as handle:
handle.write(data)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="operation", required=True)
for operation in ("extract", "convert", "compare"):
command = sub.add_parser(operation)
command.add_argument("source", type=Path)
if operation == "compare":
command.add_argument("other", type=Path)
command.add_argument("--output", required=True, type=Path)
command.add_argument("--overwrite", action="store_true")
if operation != "extract":
command.add_argument("--manifest", type=Path, help="Authoritative build/vector JSON manifest")
args = parser.parse_args(argv)
try:
outputs = {}
if args.operation == "extract":
disk = args.source.read_bytes()
reports = extract_reports(disk)
if not reports:
raise SoundLabError("No SNDnnnn.TXT ASCII reports found")
receipt = {"disk": args.source.name, "disk_byte_count": len(disk), "disk_sha256": hashlib.sha256(disk).hexdigest(), "reports": []}
for report in reports:
outputs[args.output / report["filename"]] = report["data"]
receipt["reports"].append({key: value for key, value in report.items() if key != "data"})
outputs[args.output / "extraction.json"] = (json.dumps(receipt, indent=2) + '\n').encode()
else:
left = parse_report(args.source.read_bytes(), args.source.name)
manifest = json.loads(args.manifest.read_text()) if args.manifest else None
if args.manifest and not isinstance(manifest, dict):
raise SoundLabError("Manifest must be a JSON object")
if args.operation == "compare":
document = compare_reports(left, parse_report(args.other.read_bytes(), args.other.name), manifest)
stem = "comparison"
else:
document = left
if manifest is not None:
document["manifest_issues"] = validate_manifest(document, manifest)
document["issues"].extend(document["manifest_issues"])
document["valid"] = document["valid"] and not document["manifest_issues"]
document["complete"] = document["complete"] and document["valid"]
stem = args.source.stem
outputs = {args.output / f"{stem}.json": (json.dumps(document, indent=2) + '\n').encode(), args.output / f"{stem}.csv": render_csv(document).encode(), args.output / f"{stem}.html": render_html(document).encode()}
# Never allow an output to alias any supplied source, even with --overwrite.
sources = [args.source] + ([args.other] if args.operation == "compare" else [])
if getattr(args, "manifest", None):
sources.append(args.manifest)
source_paths = {path.resolve() for path in sources}
if any(path.resolve() in source_paths or any(path.exists() and path.samefile(source) for source in sources) for path in outputs):
raise SoundLabError("Output would replace an input; choose another folder")
write_outputs(outputs, args.overwrite)
print(f"Wrote {len(outputs)} files to {args.output}")
if args.operation != "extract" and (document.get("issues") or document.get("identity_issues") or any(row.get("comparison") == "NOT_COMPARABLE" for row in document["cases"])):
print("Warning: evidence is incomplete, invalid, or not comparable; inspect JSON/HTML", file=sys.stderr)
return 2
return 0
except (OSError, SoundLabError, json.JSONDecodeError) as error:
print(f"soundlab: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+122
View File
@@ -0,0 +1,122 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Isolated headless test: real Disk BASIC/FD502 path, private local ROM inputs.
#include "../../../tests/toolchain/ssc/session.h"
static void type(Session& run, const std::string& text) {
for(char c:text) {
if(c>='A' && c<='Z') run.press(c-'@');
else if(c>='0' && c<='9') run.press(32+c-'0');
else if(c=='-') run.press(45);
else if(c=='"') run.press(34,true);
else if(c=='\r') run.press(48);
else throw std::runtime_error("Unsupported input character");
}
}
static void capture(Session& run,const fs::path& path) {
for(unsigned i=0;i<3;++i) run.tick();
auto frame=run.machine.snapshot().frame;
require(frame && frame->pixels.size()==Frame::width*Frame::height,"No guest raster");
std::ofstream file(path,std::ios::binary);
file<<"P6\n"<<Frame::width<<' '<<Frame::height<<"\n255\n";
for(auto pixel:frame->pixels) { file.put(char(pixel>>16));file.put(char(pixel>>8));file.put(char(pixel)); }
}
static void select(Session& run,const std::string& id) {
type(run,"4"); run.until("CASE ID"); type(run,id+"\r");
run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("H HEARD",2400);
}
struct NeverReady final:CartridgeDevice {
unsigned reads=0,writes=0;
void reset() override {}
void horizontalSync(DeviceHost&) override {}
std::uint8_t readMemory(std::uint16_t)const override{return 0;}
std::uint8_t readPort(std::uint8_t p,DeviceHost&)override {if(p==0x7e){++reads;return 1;}return 0;}
void writePort(std::uint8_t p,std::uint8_t,DeviceHost&)override {if(p==0x7e)++writes;}
};
static void writeFile(const fs::path& path,const Bytes& bytes) {
std::ofstream file(path,std::ios::binary);
file.write(reinterpret_cast<const char*>(bytes.data()),bytes.size());
require(bool(file),"Cannot write owned test output");
}
int main(int argc,char**argv) {
try {
require(argc==4,"Usage: run ROM_DIRECTORY SOUNDLAB.DSK OUTPUT_DIRECTORY");
fs::path roms=argv[1], out=argv[3]; fs::create_directories(out);
auto system=readFile(roms/"coco3.rom"), diskrom=readFile(roms/"disk11.rom");
auto chips=readFile(roms/"pic-7040-510.bin"), speech=readFile(roms/"sp0256-al2.bin");
chips.insert(chips.end(),speech.begin(),speech.end());
for(auto cpu:{Processor::MC6809,Processor::HD6309}) {
std::string label=cpu==Processor::MC6809?"6809":"6309";
Session run(cpu,system,diskrom,std::make_shared<SpeechSoundDevice>(chips));
run.floppy->mount(0,DiskImage::load(readFile(argv[2])));
type(run,"DOS\r"); run.until("WELCOME, LISTENER",1200);
type(run,"11ND"); run.until("MAIN MENU",2400);
if(cpu==Processor::MC6809) { run.until("REPORT SAVED",2400); capture(run,out/"main-menu.ppm"); }
run.audio.clear();
type(run,"1"); run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("H HEARD",2400);
run.checkSignal(0); // PCM signal only; never a listening verdict.
type(run,"R"); run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("ATTEMPT 1",2400); run.until("H HEARD",2400);
type(run,"U"); run.until("ENTER TO PLAY",2400); type(run,"\r"); run.until("H HEARD",2400);
type(run,"X"); run.until("MAIN MENU",2400);
type(run,"Q"); run.until("SOUND LAB FINISHED",2400);
for(unsigned i=0;i<30;++i) run.tick();
require(run.contains("OK"),"Did not return to BASIC");
require(run.floppy->writeEvents(0)>0,"No report disk writes");
writeFile(out/(label+"-reports.dsk"),run.floppy->image(0)->bytes());
saveWav(out/(label+"-showcase.wav"),run.audio);
std::ofstream(out/(label+"-final.txt"))<<run.machine.copyScreenText();
std::cout<<"PASS "<<label<<" actual DOS boot, speech PCM, repeat, uncertain/abort, reports, BASIC return\n";
}
// No physical-presence inference: absent hardware still permits menu/quit.
{
Session absent(Processor::MC6809,system,diskrom,nullptr);
absent.floppy->mount(0,DiskImage::load(readFile(argv[2]),true));
type(absent,"RUN\"SOUNDLAB\"\r"); absent.until("WELCOME, LISTENER",1200);
type(absent,"11NM"); absent.until("MAIN MENU");
type(absent,"1"); absent.until("ENTER TO PLAY"); type(absent,"\r"); absent.until("H HEARD",3000);
type(absent,"X"); absent.until("MAIN MENU"); type(absent,"Q"); absent.until("SOUND LAB FINISHED");
require(absent.floppy->writeEvents(0)==0,"Screen-only run wrote disk");
std::cout<<"PASS absent SSC bounded observation and screen-only return without writes\n";
}
{
Session engineering(Processor::MC6809,system,diskrom,std::make_shared<SpeechSoundDevice>(chips));
engineering.floppy->mount(0,DiskImage::load(readFile(out/"6809-reports.dsk")));
type(engineering,"DOS\r"); engineering.until("WELCOME, LISTENER",1200);
type(engineering,"11ND"); engineering.until("MAIN MENU",2400);
engineering.until("REPORT SAVED",2400);
require(!engineering.contains("SND0001.TXT"),"Existing report filename was reused on relaunch");
for(const auto&id:{"REG01","REG02","NOI01","ENV01-10","ALP01-00"}) {
auto first=engineering.audio.size();
select(engineering,id);
if(std::string(id)!="ALP01-00") engineering.checkSignal(first);
if(std::string(id)=="REG01") capture(engineering,out/"direct-register-result.ppm");
type(engineering,"X"); engineering.until("MAIN MENU",2400);
}
type(engineering,"Q"); engineering.until("SOUND LAB FINISHED",2400);
for(unsigned i=0;i<30;++i) engineering.tick();
writeFile(out/"engineering-reports.dsk",engineering.floppy->image(0)->bytes());
std::cout<<"PASS held AY/direct FF data, noise, envelope, silent pause, report rollover and filename preservation\n";
}
{
auto stall=std::make_shared<NeverReady>();
Session stopped(Processor::MC6809,system,diskrom,nullptr,false,stall);
stopped.floppy->mount(0,DiskImage::load(readFile(argv[2]),true));
type(stopped,"DOS\r"); stopped.until("WELCOME, LISTENER",1200);
type(stopped,"11NM"); stopped.until("MAIN MENU");
type(stopped,"1"); stopped.until("ENTER TO PLAY"); type(stopped,"\r"); stopped.until("TIMEOUT / RESET",1200);
require(stall->reads>1 && stall->writes==0,"Bounded ready polling wrote to a not-ready device");
type(stopped,"X"); stopped.until("MAIN MENU"); type(stopped,"Q"); stopped.until("SOUND LAB FINISHED");
std::cout<<"PASS never-ready bounded timeout with zero command writes\n";
}
{
Session panic(Processor::MC6809,system,diskrom,std::make_shared<SpeechSoundDevice>(chips));
panic.floppy->mount(0,DiskImage::load(readFile(argv[2]),true));
type(panic,"DOS\r"); panic.until("WELCOME, LISTENER",1200);
type(panic,"11NM"); panic.until("MAIN MENU"); type(panic,"1"); panic.until("ENTER TO PLAY"); type(panic,"\r"); panic.until("PLAYING");
type(panic,"X"); panic.until("ABORTED",1200); panic.until("H HEARD");
type(panic,"X"); panic.until("MAIN MENU"); type(panic,"Q"); panic.until("SOUND LAB FINISHED");
require(panic.floppy->writeEvents(0)==0,"Panic screen-only path wrote disk");
std::cout<<"PASS panic during playback and safe return\n";
}
return 0;
} catch(const std::exception&e) { std::cerr<<e.what()<<'\n'; return 1; }
}
+169
View File
@@ -0,0 +1,169 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Authored PCM fixtures; no ROMs, hardware, dependencies or listening claims."""
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
import wave
SCRIPT = Path(__file__).resolve().parents[1] / "audio" / "analyze.py"
SPEC = importlib.util.spec_from_file_location("sound_lab_audio", SCRIPT)
audio = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(audio)
class AudioTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="soundlab-audio-")
self.addCleanup(self.temporary.cleanup)
self.directory = Path(self.temporary.name)
def wav(self, channels, rate=48000, width=2):
path = self.directory / "capture.wav"
payload = bytearray()
for frame in zip(*channels):
for value in frame:
payload.extend((value + 128 if width == 1 else value).to_bytes(width, "little", signed=width != 1))
with wave.open(str(path), "wb") as output:
output.setnchannels(len(channels))
output.setsampwidth(width)
output.setframerate(rate)
output.writeframes(payload)
return path
def manifest(self, duration=1, **kwargs):
segment = dict(case_id="AUTHORED", kind="tone", start_seconds=0, end_seconds=duration)
segment.update(kwargs)
path = self.directory / "intervals.json"
path.write_text(json.dumps({"segments": [segment]}))
return path
def sine(self, rate, hz, amplitude=16384):
return [round(amplitude * math.sin(2 * math.pi * hz * index / rate)) for index in range(rate)]
def test_tone_both_sample_rates_and_input_hashes(self):
for rate in (44100, 48000):
with self.subTest(rate=rate):
wav = self.wav([self.sine(rate, 440)], rate)
manifest = self.manifest(nominal_hz=440)
original = wav.read_bytes()
report = audio.analyze(wav, manifest)
channel = report["segments"][0]["channels"][0]
self.assertEqual(report["capture"]["sample_rate_hz"], rate)
self.assertAlmostEqual(channel["frequency"]["estimated_hz"], 440, delta=0.02)
self.assertAlmostEqual(channel["rms_full_scale"], 0.5 / math.sqrt(2), delta=0.0001)
self.assertEqual(report["capture"]["sha256"], hashlib.sha256(original).hexdigest())
self.assertEqual(wav.read_bytes(), original)
self.assertEqual(report["human_status"], "NOT_OBSERVED")
self.assertEqual(channel["assessment"], "MEASURE_BASELINE")
def test_silence_and_rails(self):
wav = self.wav([[0] * 48000])
report = audio.analyze(wav, self.manifest(kind="silence"))
channel = report["segments"][0]["channels"][0]
self.assertEqual(channel["rms_full_scale"], 0)
self.assertEqual(channel["near_zero_ratio"], 1)
self.assertNotIn("frequency", channel)
wav = self.wav([[-32768, 32767, 0, 1]])
channel = audio.analyze(wav, self.manifest(duration=4 / 48000, kind="noise"))["segments"][0]["channels"][0]
self.assertEqual(channel["clipping_count"], 2)
self.assertEqual(channel["peak_full_scale"], 1)
self.assertEqual(channel["near_zero_ratio"], 0.5)
def test_stereo_keeps_different_channels(self):
wav = self.wav([self.sine(48000, 440), self.sine(48000, 880, 8192)])
channels = audio.analyze(wav, self.manifest())["segments"][0]["channels"]
self.assertAlmostEqual(channels[0]["frequency"]["estimated_hz"], 440, delta=0.02)
self.assertAlmostEqual(channels[1]["frequency"]["estimated_hz"], 880, delta=0.02)
self.assertAlmostEqual(channels[0]["rms_full_scale"] / channels[1]["rms_full_scale"], 2, delta=0.001)
def test_supported_integer_widths(self):
for width in (1, 2, 3, 4):
with self.subTest(width=width):
wav = self.wav([[0, 1, -1, 2]], width=width)
report = audio.analyze(wav, self.manifest(duration=4 / 48000, kind="silence"))
self.assertEqual(report["capture"]["bit_depth"], width * 8)
self.assertEqual(report["segments"][0]["channels"][0]["near_zero_ratio"], 0.75)
def test_interval_validation_and_rounding(self):
wav = self.wav([[0] * 48000])
for kwargs in ({"start_seconds": -1}, {"end_seconds": 2}, {"end_seconds": 0},
{"start_seconds": 0.5, "end_seconds": 0.4}, {"start_seconds": float("nan")},
{"kind": "unknown"}, {"end_seconds": True}, {"case_id": ""},
{"start_seconds": 0.000001, "end_seconds": 0.000002}):
with self.subTest(kwargs=kwargs):
with self.assertRaises(ValueError):
audio.analyze(wav, self.manifest(**kwargs))
report = audio.analyze(wav, self.manifest(start_seconds=0.00001, end_seconds=0.00005))
self.assertEqual(report["segments"][0]["start_frame"], 1)
self.assertEqual(report["segments"][0]["stop_frame"], 3)
self.assertEqual(report["segments"][0]["byte_offset_in_pcm_payload"], 2)
def test_compression_float_width_and_truncation_rejected(self):
wav = self.wav([[0] * 48])
original = wav.read_bytes()
for format_tag, bits, block_align in ((6, 16, 2), (3, 32, 4), (1, 40, 5)):
with self.subTest(format_tag=format_tag, bits=bits):
damaged = bytearray(original)
struct.pack_into("<H", damaged, 20, format_tag)
struct.pack_into("<H", damaged, 34, bits)
struct.pack_into("<H", damaged, 32, block_align)
wav.write_bytes(damaged)
with self.assertRaises(ValueError):
audio.load_pcm(wav)
wav.write_bytes(original[:-5])
with self.assertRaises(ValueError):
audio.load_pcm(wav)
def test_explicit_tolerance_and_no_inferred_listening(self):
wav = self.wav([self.sine(48000, 440)])
tolerance = {"absolute_hz": 1, "qualification": "Authored digital fixture; known sample rate"}
report = audio.analyze(wav, self.manifest(nominal_hz=440, frequency_tolerance=tolerance))
self.assertEqual(report["segments"][0]["channels"][0]["assessment"], "WITHIN_QUALIFIED_TOLERANCE")
report = audio.analyze(wav, self.manifest(nominal_hz=450, frequency_tolerance=tolerance))
self.assertEqual(report["segments"][0]["channels"][0]["assessment"], "OUTSIDE_QUALIFIED_TOLERANCE")
self.assertEqual(report["assessment"], "MEASURE_BASELINE")
with self.assertRaises(ValueError):
audio.analyze(wav, self.manifest(nominal_hz=440, frequency_tolerance={"absolute_hz": 1}))
wav = self.wav([[0] * 48000])
channel = audio.analyze(wav, self.manifest())["segments"][0]["channels"][0]
self.assertIsNone(channel["frequency"]["estimated_hz"])
def test_repeated_comparison_requires_both_identities(self):
wav = self.wav([self.sine(48000, 440)])
manifest = self.manifest(vector_id="VECTOR-A")
first = json.loads(manifest.read_text())["segments"][0]
cases = [first, dict(first), dict(first, vector_id="VECTOR-B"),
dict(first, case_id="OTHER"), {k: v for k, v in first.items() if k != "vector_id"}]
manifest.write_text(json.dumps(cases))
comparisons = audio.analyze(wav, manifest)["repeated_cases"]
self.assertEqual(len(comparisons), 1)
self.assertEqual(comparisons[0]["observed_segment_index"], 1)
self.assertEqual(comparisons[0]["assessment"], "OBSERVED")
def test_cli_protects_existing_reports_and_inputs(self):
wav = self.wav([[0] * 48])
manifest = self.manifest(duration=0.001)
output = self.directory / "report.json"
command = [sys.executable, str(SCRIPT), str(wav), str(manifest), "--output", str(output)]
result = subprocess.run(command, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
original_report = output.read_bytes()
self.assertEqual(subprocess.run(command, capture_output=True).returncode, 2)
self.assertEqual(output.read_bytes(), original_report)
self.assertEqual(subprocess.run(command + ["--overwrite"], capture_output=True).returncode, 0)
original = wav.read_bytes()
self.assertEqual(subprocess.run(command[:-1] + [str(wav), "--overwrite"], capture_output=True).returncode, 2)
self.assertEqual(wav.read_bytes(), original)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,113 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Authored integration fixtures for post-native Sound Lab report qualification."""
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
fixture = load('soundlab_report_fixtures', ROOT / 'tests' / 'test_reports.py')
verify = load('soundlab_verify_reports', ROOT / 'verify_reports.py')
def run_text(number=1, human='UNSURE'):
text = fixture.make_report(human='NOT_OBSERVED', ending=False).decode('ascii')
header, body = text.split('CASE=', 1)
header = header.replace('RUN=0001', f'RUN={number:04d}')
case0 = 'CASE=' + body.replace('ENDCASE=', 'REPEAT=0\r\nNOTE_LENGTH=0\r\nNOTE=\r\nENDCASE=')
case1 = case0.replace('REPEAT=0', 'REPEAT=1').replace('HUMAN=NOT_OBSERVED', 'HUMAN=' + human)
text = header + case0 + case1
raw = text.encode('ascii')
footer = f'ENDRUN={number:04d} COMPLETE=YES RECORD_COUNT={len(text.splitlines())} CHECKSUM_CRC16={verify.reports.crc16(raw):04X}\r\n'
return raw + footer.encode('ascii')
def setup_build(root, *, bad_human=False, changed_binary=False, retained_changed=False):
(root / 'qualification').mkdir()
binary = b'Authored loader fixture; not executable.'
basic_source = b'10 PRINT "FIXTURE"\n'
basic_disk = b'\r' + basic_source.replace(b'\n', b'\r')
pristine = [('SOUNDLAB.BIN', binary, [0]), ('SOUNDLAB.BAS', basic_disk, [1])]
(root / 'SOUNDLAB.BIN').write_bytes(binary)
(root / 'SOUNDLAB.BAS').write_bytes(basic_source)
(root / 'SOUNDLAB.DSK').write_bytes(fixture.make_disk(pristine))
manifest = {'build_id': 'TEST-1', 'vector_set_crc16': '1234', 'vectors': [{'case_id': 'TON01-A', 'crc16': '7ABC'}], 'artifacts': []}
for name in ('SOUNDLAB.BIN', 'SOUNDLAB.BAS', 'SOUNDLAB.DSK'):
data = (root / name).read_bytes()
manifest['artifacts'].append({'filename': name, 'bytes': len(data), 'sha256': verify.sha256(data)})
(root / 'SOUNDLAB-manifest.json').write_text(json.dumps(manifest))
for label in ('6809', '6309', 'engineering'):
files = list(pristine)
if changed_binary and label == '6309':
files[0] = ('SOUNDLAB.BIN', b'Changed fixture', [0])
text = run_text(human='HEARD' if bad_human and label == '6309' else 'UNSURE')
if retained_changed and label == 'engineering':
text = text.replace(b'HUMAN=UNSURE', b'HUMAN=NO_SOUND')
# Restore valid footer so preservation is independently tested.
text = text.split(b'ENDRUN=')[0]
text += f'ENDRUN=0001 COMPLETE=YES RECORD_COUNT={len(text.splitlines())} CHECKSUM_CRC16={verify.reports.crc16(text):04X}\r\n'.encode()
files.append(('SND0001.TXT', text, [2]))
if label == 'engineering':
files.append(('SND0002.TXT', run_text(2), [3]))
(root / 'qualification' / f'{label}-reports.dsk').write_bytes(fixture.make_disk(files))
class GuestContractTests(unittest.TestCase):
def test_complete_native_contract_preserves_sources(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
setup_build(root)
inputs = {path: path.read_bytes() for path in root.rglob('*') if path.is_file()}
result = verify.qualify(root)
self.assertTrue(result['passed'])
self.assertTrue(result['engineering_original_reports_byte_identical'])
self.assertEqual(result['engineering_new_reports'], ['SND0002.TXT'])
self.assertTrue(all(run['repeat_observed'] and run['unsure_recorded'] for run in result['runs'].values()))
self.assertEqual(inputs, {path: path.read_bytes() for path in inputs})
def test_native_contract_rejects_fabricated_heard(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
setup_build(root, bad_human=True)
with self.assertRaisesRegex(verify.reports.SoundLabError, 'fabricate HUMAN=HEARD'):
verify.qualify(root)
def test_native_contract_rejects_changed_binary(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
setup_build(root, changed_binary=True)
with self.assertRaisesRegex(verify.reports.SoundLabError, 'SOUNDLAB.BIN missing or changed'):
verify.qualify(root)
def test_native_contract_rejects_changed_retained_report(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
setup_build(root, retained_changed=True)
with self.assertRaisesRegex(verify.reports.SoundLabError, 'modified or removed original 6809 report'):
verify.qualify(root)
def test_optional_receipt_never_implicitly_replaces_existing_output(self):
with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
root = Path(directory)
setup_build(root)
receipt = root / 'receipt.json'
args = ['--build-dir', str(root), '--receipt', str(receipt)]
self.assertEqual(verify.main(args), 0)
self.assertEqual(verify.main(args), 1)
self.assertEqual(verify.main(args + ['--overwrite']), 0)
self.assertEqual(verify.main(['--build-dir', str(root), '--receipt', str(root / 'SOUNDLAB.DSK'), '--overwrite']), 1)
self.assertTrue(verify.qualify(root)['passed'])
if __name__ == '__main__':
unittest.main()
+358
View File
@@ -0,0 +1,358 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Authored, ROM-free fixtures for Sound Lab report evidence and DECB extraction."""
import hashlib
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
MODULE = Path(__file__).resolve().parents[1] / "host" / "soundlab_reports.py"
spec = importlib.util.spec_from_file_location("soundlab_reports", MODULE)
reports = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reports)
def make_report(*, auto="OBSERVED", human="HEARD", ending=True, case="TON01-A", crc="7ABC", build="TEST-1", vector_set="1234", note=None):
lines = ["FORMAT=SOUNDLAB-1", f"RUN=0001 TARGET=REALCOCO BUILD_ID={build} VECTOR_SET_CRC16={vector_set}",
"MACHINE=COCO3 VIDEO=NTSC SPEED=NORMAL CART=26-3144A MOD=UNKNOWN",
f"CASE={case} VECTOR_CRC16={crc} AUTO={auto} HUMAN={human}",
"TX_COUNT=11 READY_TIMEOUTS=0 TICK_UNIT=VSYNC TICK_RATE_NUM=60000 TICK_RATE_DEN=1001",
"START_TICK=1234 END_TICK=1260 POLL_RESOLUTION_US=UNKNOWN", "STATUS_BEFORE=E0 STATUS_AFTER=E0"]
if note is not None:
lines.extend([f"NOTE_LENGTH={len(reports.decode_note(note))}", "NOTE=" + note])
lines.append(f"ENDCASE={case}")
if ending:
checksum = reports.crc16(('\r\n'.join(lines) + '\r\n').encode())
lines.append(f"ENDRUN=0001 COMPLETE=YES RECORD_COUNT={len(lines)} CHECKSUM_CRC16={checksum:04X}")
return ('\r\n'.join(lines) + '\r\n').encode()
def make_disk(files):
"""files is (name, data, explicit fragmented granule chain) tuples."""
disk = bytearray([0xFF] * reports.DISK_SIZE)
for index, (name, data, chain) in enumerate(files):
if not 0 < len(data) <= 2304 * len(chain) or len(data) <= 2304 * (len(chain) - 1):
raise ValueError("Fixture chain must exactly cover nonempty data")
base, ext = name.split(".")
entry = bytearray(32)
entry[:8] = base.encode().ljust(8, b' ')
entry[8:11] = ext.encode().ljust(3, b' ')
entry[11:14] = bytes([3, 0xFF, chain[0]])
entry[14:16] = (((len(data) - 1) % 256) + 1).to_bytes(2, 'big')
start = reports.DIRECTORY_OFFSET + index * 32
disk[start:start + 32] = entry
for position, granule in enumerate(chain):
last = position == len(chain) - 1
remaining = len(data) - position * 2304
disk[reports.FAT_OFFSET + granule] = 0xC0 + ((remaining + 255) // 256) if last else chain[position + 1]
chunk = data[position * 2304:(position + 1) * 2304]
offset = reports.granule_offset(granule)
disk[offset:offset + len(chunk)] = chunk
return disk
class DiskTests(unittest.TestCase):
def test_fragmented_chain_skips_directory_track_and_preserves_original(self):
content = b'A' * 2304 + b'B' * 2304 + b'END\r\n'
disk = make_disk([('snd0001.txt', content, [33, 34, 5])])
original = bytes(disk)
selected = reports.extract_reports(disk)
self.assertEqual(selected[0]['data'], content)
self.assertEqual(selected[0]['filename'], 'SND0001.TXT')
self.assertEqual(selected[0]['granules'], [33, 34, 5])
self.assertEqual(bytes(disk), original)
self.assertEqual(selected[0]['sha256'], hashlib.sha256(content).hexdigest())
self.assertEqual(reports.granule_offset(34), 18 * 18 * 256)
def test_full_sector_and_full_granule(self):
for size in (256, 2304, 2305):
with self.subTest(size=size):
data = bytes(i % 256 for i in range(size))
disk = make_disk([('SND0001.TXT', data, [0] if size <= 2304 else [0, 67])])
self.assertEqual(reports.extract_reports(disk)[0]['data'], data)
def test_only_report_names_extracted_and_binary_reports_rejected(self):
disk = make_disk([('NOTES.TXT', b'notes', [0]), ('SND0002.TXT', b'report', [1])])
self.assertEqual([item['filename'] for item in reports.extract_reports(disk)], ['SND0002.TXT'])
disk[reports.DIRECTORY_OFFSET + 32 + 12] = 0
with self.assertRaisesRegex(reports.SoundLabError, 'not marked.*ASCII'):
reports.extract_reports(disk)
def test_wrong_size_rejected_including_truncation(self):
for size in (0, reports.DISK_SIZE - 1, reports.DISK_SIZE + 1):
with self.subTest(size=size), self.assertRaises(reports.SoundLabError):
reports.extract_reports(bytes(size))
def test_invalid_fat_value(self):
disk = make_disk([('SND0001.TXT', b'hello', [0])])
disk[reports.FAT_OFFSET] = 0xCA
with self.assertRaisesRegex(reports.SoundLabError, 'Invalid FAT'):
reports.extract_reports(disk)
def test_fat_loop(self):
disk = make_disk([('SND0001.TXT', b'hello', [0])])
disk[reports.FAT_OFFSET] = 2
disk[reports.FAT_OFFSET + 2] = 0
with self.assertRaisesRegex(reports.SoundLabError, 'loop'):
reports.extract_reports(disk)
def test_free_granule_inside_chain(self):
disk = make_disk([('SND0001.TXT', b'hello', [0])])
disk[reports.FAT_OFFSET] = 0xFF
with self.assertRaisesRegex(reports.SoundLabError, 'free granule'):
reports.extract_reports(disk)
def test_crosslinks_with_unselected_file(self):
disk = make_disk([('SND0001.TXT', b'hello', [0]), ('OTHER.DAT', b'data', [1])])
disk[reports.DIRECTORY_OFFSET + 32 + 13] = 0
with self.assertRaisesRegex(reports.SoundLabError, 'Crosslinked'):
reports.extract_reports(disk)
def test_final_sector_count_and_empty_marker(self):
for byte_count in (257, 65535):
disk = make_disk([('SND0001.TXT', b'hello', [0])])
disk[reports.DIRECTORY_OFFSET + 14:reports.DIRECTORY_OFFSET + 16] = byte_count.to_bytes(2, 'big')
with self.subTest(byte_count=byte_count), self.assertRaisesRegex(reports.SoundLabError, 'byte count'):
reports.extract_reports(disk)
disk = make_disk([('SND0001.TXT', b'hello', [0])])
disk[reports.FAT_OFFSET] = 0xC0
with self.assertRaisesRegex(reports.SoundLabError, 'empty final granule'):
reports.extract_reports(disk)
def test_duplicate_names_and_unsafe_name(self):
disk = make_disk([('SND0001.TXT', b'a', [0]), ('snd0001.txt', b'b', [1])])
with self.assertRaisesRegex(reports.SoundLabError, 'Duplicate'):
reports.extract_reports(disk)
disk = make_disk([('SND0001.TXT', b'a', [0])])
disk[reports.DIRECTORY_OFFSET] = ord('/')
with self.assertRaisesRegex(reports.SoundLabError, 'Unsafe'):
reports.extract_reports(disk)
class ReportTests(unittest.TestCase):
def test_crc_known_vector(self):
self.assertEqual(reports.crc16(b'123456789'), 0x29B1)
def test_complete_report_and_escaped_note(self):
result = reports.parse_report(make_report(note=r'LINE\nTWO\\END\x21'))
self.assertTrue(result['complete'], result['issues'])
self.assertEqual(result['cases'][0]['notes'], ['LINE\nTWO\\END!'])
self.assertEqual(result['integrity'], {'record_count': 'VERIFIED', 'checksum_crc16': 'VERIFIED'})
self.assertEqual(result['cases'][0]['fields']['POLL_RESOLUTION_US'], 'UNKNOWN')
def test_lf_and_crlf_same_canonical_checksum(self):
self.assertTrue(reports.parse_report(make_report().replace(b'\r\n', b'\n'))['complete'])
def test_partial_run_keeps_case_evidence(self):
text = make_report(ending=False).rsplit(b'ENDCASE=', 1)[0]
result = reports.parse_report(text)
self.assertFalse(result['complete'])
self.assertFalse(result['cases'][0]['closed'])
self.assertEqual(result['cases'][0]['human'], 'HEARD')
self.assertTrue(any('partial' in issue for issue in result['issues']))
def test_bad_checksum_and_count(self):
data = make_report().replace(b'TX_COUNT=11', b'TX_COUNT=12').replace(b'RECORD_COUNT=8', b'RECORD_COUNT=7')
result = reports.parse_report(data)
self.assertFalse(result['valid'])
self.assertEqual(result['integrity']['checksum_crc16'], 'FAILED')
self.assertEqual(result['integrity']['record_count'], 'FAILED')
def test_optional_integrity_fields_are_honestly_unverified(self):
data = make_report().split(b' RECORD_COUNT=')[0] + b'\r\n'
result = reports.parse_report(data)
self.assertTrue(result['complete'])
self.assertEqual(result['integrity']['checksum_crc16'], 'NOT_PROVIDED')
def test_missing_human_never_infers_heard(self):
data = make_report().replace(b' HUMAN=HEARD', b'')
result = reports.parse_report(data)
self.assertEqual(result['cases'][0]['human'], 'UNKNOWN')
self.assertFalse(result['valid'])
def test_endcase_identity_and_trailing_records(self):
data = make_report().replace(b'ENDCASE=TON01-A', b'ENDCASE=OTHER') + b'CASE=LATE\r\n'
result = reports.parse_report(data)
self.assertFalse(result['valid'])
self.assertTrue(any('ENDCASE does not match' in value for value in result['issues']))
self.assertTrue(any('after ENDRUN' in value for value in result['issues']))
def test_notes_length_and_unknown_escape(self):
for bad in (b'NOTE_LENGTH=99\r\nNOTE=OK', b'NOTE_LENGTH=2\r\nNOTE=\\q'):
data = make_report(note='OK').replace(b'NOTE_LENGTH=2\r\nNOTE=OK', bad)
result = reports.parse_report(data)
self.assertFalse(result['valid'])
self.assertTrue(any('NOTE_LENGTH mismatch' in value or 'escape' in value for value in result['issues']))
def test_incomplete_note_and_run_identity(self):
data = make_report(ending=False).replace(b'ENDCASE=TON01-A\r\n', b'NOTE_LENGTH=3\r\n')
self.assertTrue(any('Truncated NOTE' in issue for issue in reports.parse_report(data)['issues']))
result = reports.parse_report(make_report().replace(b'ENDRUN=0001', b'ENDRUN=0002'))
self.assertTrue(any('does not match RUN' in issue for issue in result['issues']))
def test_invalid_ascii_and_format(self):
for data in (b'FORMAT=SOUNDLAB-2\n', b'FORMAT=SOUNDLAB-1\rRUN=1', b'FORMAT=SOUNDLAB-1\nNOTE=\xff', b'FORMAT=SOUNDLAB-1\n\x00'):
with self.subTest(data=data), self.assertRaises(reports.SoundLabError):
reports.parse_report(data)
def test_mixed_case_outcomes_compare_separately(self):
left = reports.parse_report(make_report(auto='observed', human='heard', case='ton01-a', crc='7abc'), 'left')
right = reports.parse_report(make_report(), 'right')
result = reports.compare_reports(left, right)
self.assertEqual(result['cases'][0]['comparison'], 'SAME')
other = reports.parse_report(make_report(human='NO_SOUND'), 'other')
result = reports.compare_reports(right, other)
self.assertEqual(result['cases'][0]['left_auto'], result['cases'][0]['right_auto'])
self.assertEqual(result['cases'][0]['comparison'], 'DIFFERENT')
def test_identity_mismatch_makes_not_comparable(self):
baseline = reports.parse_report(make_report())
for changed in (make_report(crc='ABCD'), make_report(build='OTHER'), make_report(vector_set='FFFF'), make_report(case='OTHER')):
result = reports.compare_reports(baseline, reports.parse_report(changed))
self.assertTrue(all(case['comparison'] == 'NOT_COMPARABLE' for case in result['cases']))
def test_authoritative_manifest_identity(self):
report = reports.parse_report(make_report())
manifest = {'build_id': 'TEST-1', 'vector_set_crc16': '1234', 'vectors': [{'case_id': 'TON01-A', 'crc16': '7ABC'}]}
self.assertEqual(reports.validate_manifest(report, manifest), [])
manifest['vectors'][0]['crc16'] = '1234'
compared = reports.compare_reports(report, report, manifest)
self.assertEqual(compared['cases'][0]['comparison'], 'NOT_COMPARABLE')
def test_repeated_attempts_preserved_and_compared_by_repeat(self):
base = make_report(ending=False).decode('ascii')
header, body = base.split('CASE=', 1)
case0 = 'CASE=' + body.replace('ENDCASE=', 'REPEAT=0\r\nENDCASE=')
case1 = case0.replace('REPEAT=0', 'REPEAT=1').replace('HUMAN=HEARD', 'HUMAN=UNSURE')
def finish(text):
raw = text.encode('ascii')
count = len(text.splitlines())
return raw + f'ENDRUN=0001 COMPLETE=YES RECORD_COUNT={count} CHECKSUM_CRC16={reports.crc16(raw):04X}\r\n'.encode('ascii')
left = reports.parse_report(finish(header + case0 + case1))
self.assertTrue(left['valid'], left['issues'])
self.assertEqual([case['repeat'] for case in left['cases']], [0, 1])
right = reports.parse_report(finish(header + case1 + case0))
self.assertTrue(right['valid'], right['issues'])
comparison = reports.compare_reports(left, right)
self.assertEqual([row['repeat'] for row in comparison['cases']], [0, 1])
self.assertEqual([row['comparison'] for row in comparison['cases']], ['SAME', 'SAME'])
changed = reports.parse_report(finish(header + case0 + case1.replace('HUMAN=UNSURE', 'HUMAN=NO_SOUND')))
comparison = reports.compare_reports(left, changed)
self.assertEqual([row['comparison'] for row in comparison['cases']], ['SAME', 'DIFFERENT'])
self.assertIn('case,repeat,auto,human', reports.render_csv(left))
self.assertIn('<th scope="col">repeat</th>', reports.render_html(left))
duplicate = reports.parse_report(finish(header + case0 + case0))
self.assertFalse(duplicate['valid'])
self.assertTrue(any('duplicate REPEAT=0' in issue for issue in duplicate['issues']))
def test_bad_repeat_and_missing_repeat_are_honest(self):
baseline = make_report(ending=False)
for value in ('-1', '65536', 'abc'):
invalid = baseline.replace(b'ENDCASE=', f'REPEAT={value}\r\nENDCASE='.encode()) + b'ENDRUN=0001 COMPLETE=YES\r\n'
parsed = reports.parse_report(invalid)
self.assertFalse(parsed['valid'])
self.assertIsNone(parsed['cases'][0]['repeat'])
self.assertEqual(reports.parse_report(make_report())['cases'][0]['repeat'], 0)
def test_raw_metric_differences_visible_even_with_same_outcomes(self):
a = make_report()
b = a.replace(b'TX_COUNT=11', b'TX_COUNT=12').split(b' RECORD_COUNT=')[0] + b'\r\n'
# Remove optional integrity from both: this fixture isolates metrics comparison.
a = a.split(b' RECORD_COUNT=')[0] + b'\r\n'
result = reports.compare_reports(reports.parse_report(a), reports.parse_report(b))
self.assertEqual(result['cases'][0]['comparison'], 'DIFFERENT')
self.assertEqual(result['cases'][0]['recorded_differences']['TX_COUNT'], {'left': '11', 'right': '12'})
def test_manifest_crc_aliases_and_invalid_schema(self):
report = reports.parse_report(make_report())
manifest = {'build_id': 'TEST-1', 'vector_set_crc16': 0x1234, 'vectors': {'TON01-A': '0x7abc'}}
self.assertEqual(reports.validate_manifest(report, manifest), [])
for bad in ([], {'vectors': 3}, {'vectors': ['not an object']}):
with self.subTest(manifest=bad), self.assertRaises(reports.SoundLabError):
reports.validate_manifest(report, bad)
def test_repeated_header_or_conflicting_controls(self):
for changed in (make_report().replace(b'ENDCASE=TON01-A', b'FORMAT=SOUNDLAB-1\r\nENDCASE=TON01-A'),
make_report().replace(b'CASE=TON01-A VECTOR', b'CASE=TON01-A RUN=0001 VECTOR')):
self.assertFalse(reports.parse_report(changed)['valid'])
def test_html_escapes_notes_and_csv_keeps_timing(self):
result = reports.parse_report(make_report(note='<script>alert(1)</script>'))
rendered = reports.render_html(result)
self.assertNotIn('<script>', rendered)
self.assertIn('&lt;script&gt;', rendered)
csv = reports.render_csv(result)
self.assertIn('TICK_RATE_DEN', csv)
self.assertIn('1001', csv)
class CliTests(unittest.TestCase):
def test_extract_convert_and_no_overwrites(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
disk = root / 'SOUNDLAB.DSK'
disk.write_bytes(make_disk([('SND0001.TXT', make_report(), [0])]))
output = root / 'reports'
self.assertEqual(reports.main(['extract', str(disk), '--output', str(output)]), 0)
self.assertEqual((output / 'SND0001.TXT').read_bytes(), make_report())
self.assertEqual(reports.main(['extract', str(disk), '--output', str(output)]), 1)
self.assertEqual(reports.main(['convert', str(output / 'SND0001.TXT'), '--output', str(root / 'converted')]), 0)
result = json.loads((root / 'converted' / 'SND0001.json').read_text())
self.assertTrue(result['complete'])
self.assertEqual(reports.main(['compare', str(output / 'SND0001.TXT'), str(output / 'SND0001.TXT'), '--output', str(root / 'comparison')]), 0)
def test_partial_conversion_returns_warning_with_evidence(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
report = root / 'partial.txt'
report.write_bytes(make_report(ending=False))
self.assertEqual(reports.main(['convert', str(report), '--output', str(root / 'result')]), 2)
self.assertTrue((root / 'result' / 'partial.html').is_file())
def test_inputs_cannot_be_overwritten_even_explicitly(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
# A source named *.json is still parsed as text, but conversion would target it.
report = root / 'report.json'
data = make_report()
report.write_bytes(data)
self.assertEqual(reports.main(['convert', str(report), '--output', str(root), '--overwrite']), 1)
self.assertEqual(report.read_bytes(), data)
def test_hardlinked_source_cannot_be_overwritten(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
report = root / 'report.txt'
report.write_bytes(make_report())
(root / 'report.json').hardlink_to(report)
self.assertEqual(reports.main(['convert', str(report), '--output', str(root), '--overwrite']), 1)
self.assertEqual(report.read_bytes(), make_report())
def test_explicit_overwrite_and_invalid_manifest(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
report = root / 'report.txt'
report.write_bytes(make_report())
output = root / 'output'
self.assertEqual(reports.main(['convert', str(report), '--output', str(output)]), 0)
self.assertEqual(reports.main(['convert', str(report), '--output', str(output), '--overwrite']), 0)
manifest = root / 'bad.json'
for invalid in ('[]', 'null'):
manifest.write_text(invalid)
self.assertEqual(reports.main(['convert', str(report), '--output', str(root / 'bad'), '--manifest', str(manifest)]), 1)
def test_preflight_rejects_all_outputs_before_writing(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'exists').write_bytes(b'old')
with self.assertRaises(reports.SoundLabError):
reports.write_outputs({root / 'new': b'new', root / 'exists': b'replace'})
self.assertFalse((root / 'new').exists())
(root / 'link').symlink_to(root / 'exists')
with self.assertRaises(reports.SoundLabError):
reports.write_outputs({root / 'link': b'replace'}, overwrite=True)
if __name__ == '__main__':
unittest.main()
+69
View File
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Host tests for authored packet boundaries and deterministic vector identities."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
SPEC = importlib.util.spec_from_file_location('sound_vectors', Path(__file__).resolve().parents[1] / 'vectors' / 'generate.py')
V = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(V)
class VectorTests(unittest.TestCase):
def test_ccitt_false_check_value(self):
self.assertEqual(V.crc16(b'123456789'), 0x29B1)
def test_operand_ff_is_not_a_terminator(self):
self.assertEqual(len(V.sound_events([15, 0, 255, 255, 0, 0, 255, 0, 255])), 2)
V.validate_tx([0xAF, 0, 255, 11, 255, 255])
def test_malformed_packets_are_rejected(self):
invalid = ([0x98, 15, 0, 12, 255], # FF consumed as duration, no boundary terminator
[0x98, 15, 16, 12, 0, 255], # invalid tone high nibble
[0x98, 0x8F, 0x60, 1, 255], # reserved noise bits
[0xB0, 64, 0, 255], [0xB0, 5, 255], # invalid code / lacks final pause
[0xAF, 14, 0, 255], [0xAF, 1, 16, 255],
[0xAF, 0, 255], # FF is operand; missing terminator
[0x90, 65], [0x8F], [256], [])
for tx in invalid:
with self.subTest(tx=tx), self.assertRaises(ValueError):
V.validate_tx(list(tx))
def test_slots_allophones_and_shapes_are_complete(self):
cases = {v['id']: v for v in V.authored_vectors()}
for slot in range(8):
self.assertEqual(cases[f'BUF01-SP{slot}']['tx'][0], 0x90 + slot)
self.assertEqual(cases[f'BUF02-SN{slot}']['tx'][0], 0x98 + slot)
for code in range(64):
self.assertEqual(cases[f'ALP01-{code:02d}']['tx'], [0xB0, code, 0, 255, 0xF0])
for shape in range(16):
self.assertIn(0x60 + shape, cases[f'ENV01-{shape:02d}']['tx'])
def test_reproducible_manifest_and_header(self):
with tempfile.TemporaryDirectory() as temp:
one, two = Path(temp) / 'one', Path(temp) / 'two'
a, b = V.emit(one), V.emit(two)
self.assertEqual(a, b)
for name in ('vectors.h', 'vectors.json'):
self.assertEqual((one / name).read_bytes(), (two / name).read_bytes())
manifest = json.loads((one / 'vectors.json').read_text())
for case in manifest['vectors']:
self.assertEqual(case['crc16_ccitt_false'], f"{V.crc16(case['tx']):04X}")
self.assertEqual(case['tx_hex'], bytes(case['tx']).hex(' ').upper())
def test_version_one_packet_identities(self):
manifest = V.build_manifest()
self.assertEqual(manifest['vector_set_crc16'], '62E5')
cases = {v['case_id']: v['crc16'] for v in manifest['vectors']}
self.assertEqual({key: cases[key] for key in ('TXT01', 'REG01', 'FUN01-TUNE', 'ALP01-63', 'ENV01-10')},
{'TXT01': 'DEB7', 'REG01': 'E5E2', 'FUN01-TUNE': 'AF2A',
'ALP01-63': '2BD5', 'ENV01-10': 'BB15'})
for case in manifest['vectors']:
self.assertLessEqual(len(case['title']), 26)
self.assertLessEqual(len(case['prompt']), 62)
if __name__ == '__main__':
unittest.main()
+115
View File
@@ -0,0 +1,115 @@
# Sound Lab packet contract
The generator authors new diagnostic packets. It does not copy a manual's BASIC
listings, include ROM bytes, call an emulator-private interface, or alter the SDK.
Run it with the standard Python library:
```sh
python3 examples/sound-lab/vectors/generate.py --output .build/sound-lab/generated
python3 -m unittest discover -s examples/sound-lab/tests -p test_vectors.py -v
```
`vectors.json` records exact command-port bytes, byte counts, SHA-256 and
CRC-16/CCITT-FALSE for each stable case ID. `vector_set_crc16` covers those bytes
concatenated in manifest order. Its checksum is an identity, not a claim that a
cartridge produced the intended sound. The manifest SHA covers canonical sorted
JSON before its own `manifest_sha256` property is appended.
`vectors.h` is generated into the requested output folder. Each `SoundVector`
has `id`, `title`, `prompt`, `tx`, `length`, `crc16`, `wait_mask`, `hold_ticks`,
and `group`. Group bits are 1 showcase, 2 short guided lab, 4 engineering sweep.
The titles and prompts fit the guest's 32-column presentation with wrapping.
The `wait_mask` conventions are current SDK/model observations: 40 speech idle,
20 sound idle, 60 both. They must be logged as observations and never used to
infer physical cartridge presence. `hold_ticks` adds a bounded observation time
before the runner sends a safety stop. An NTSC60Hz tick assumption belongs in
the report; a PAL machine must be identified separately.
Before each TX byte, including terminators, poll ready80 at FF7E with a bounded
timeout. The runner owns reset, machine/sound routing preservation, timeout
recovery, report I/O, manual sound checks and the safety stop after every case.
The runner must record any timer/reset/control prelude and cleanup separately
from these vector bytes so their receipt does not silently disagree with actual
bus traffic. Use the same prelude, TX bytes and cleanup on all three platforms.
Reset/control operations are not inferred from the text of a listening prompt.
## Source qualification
The primary publication is Tandy's1984 owner's manual. `sources.json` identifies
the retrieved54-page2004 Tim Lindner OCR/typeset reproduction by URL, SHA-256 and
byte count. This is a reproduction of the primary publication, **not a photographic
scan**. The command-table, direct-register and event-grammar page pixels were
rendered and inspected. Original-paper/photographic comparison remains pending;
that limitation must remain visible in the build's qualification notes.
The Archive's old filename no longer downloads. Its currently downloadable
`Speech-Sound Cartridge Manual (Tandy).pdf` is a newer57-page re-typeset edition.
It is retained only as discovery evidence and is not silently substituted for
the edition/page numbering cited here. No PDF is tracked or included on disk.
The primary source contains inconsistencies. Printed24 says register1–13 in
introductory prose but its table, note and printed25 example use register0.
Appendix B describes R8–R10 bit4 for envelope amplitude although the compact
printed24 table only lists fixed amplitudes0–15. Printed19 contains contradictory
parenthetical wording about noise replacement; the explicit Byte2 bit7 paragraph
defines retain-previous-amplitude behavior. We preserve these qualifications
rather than inventing undocumented commands.
## Source-qualified packet grammar
All numbers below are hexadecimal. Sources are printed pages in the54-page
edition, with1-based PDF page equal to the printed page.
| Operation | Bytes | Primary source |
| --- | --- | --- |
| Immediate text | printable uppercase ASCII, space,0D | pp9–11; space is Sound Lab's explicit flush policy |
| Stored text slot n | 90+n, text, space,0D; execute D0+n | Appendix A pp26–28 |
| Allophone slot n | B0+n, codes00–3F, final pause00–04,FF; execute F0+n | pp13–14, Appendix A pp27–29 |
| Sound slot n | 98+n, complete events,FF; execute D8+n | pp15–20, Appendix A pp26–29 |
| Register-string slot n | B8+n, register/value pairs,FF; execute F8+n | Appendix A pp28–30 |
| Direct AY register writes | AF, register,value pairs,FF | pp24–25, Appendix A p27 |
| Timer base | 8F,value00–FF | Appendix A p26 |
| Speech stop | C7 | Appendix A p28 |
| Sound stop | CF | Appendix A p28 |
| Stop both, retain buffers | 00 | Appendix A p30 |
Slots n range0–7. Text/allophone representations use the same eight speech
slots. Sound events/register strings use the same eight sound slots. Consecutive
multi-buffer operations exist but are deliberately outside this initial
single-slot packet validator. Its conservative maximum64-byte body includes
the terminator. It rejects overflow instead of relying on firmware truncation.
Tone event: channel00/20/40 OR amplitude00–0F (or envelope bit10), coarse00–0F,
fine00–FF,duration00–FF. Noise event:80/A0/C0 OR amplitude, period00–1F with
optional retain-amplitude bit80,duration. Envelope event:60 OR shape00–0F,
coarse00–FF,fine00–FF,duration. The manual also permits bit7 set on the envelope
operation; Sound Lab uses the simpler60 family.
An FF at a sound-event boundary ends the stream. FF consumed as a tone fine
period, duration or envelope operand is data. In direct/register strings, FF is
an end marker only where a register number is expected; a register's value may
be FF when its field width permits it. It is not correct to split all packets
at the first FF byte.
Event duration is the interval before the next event; it does **not** turn off
the final note. Finite vectors include explicit amplitude-zero events. REG01,
REG02 and MIX01 deliberately hold an audible output, then depend on the runner's
bounded stop. TIM01 intentionally changes the timer base; the runner resets or
restores a declared baseline between cases. Absolute milliseconds, ready-poll
counts, intonation, analog waveform fidelity and comparative envelope shape are
`MEASURE_BASELINE`, never an invented source pass.
## Existing SDK conventions kept separate
The source of the current SDK helpers is useful integration evidence, not a
substitute for the publication. Its text62-character cap and appended space are
conservative API rules. Its cold one-shot envelope prime/retrigger sequence is
an implementation workaround: these vectors instead issue the documented
envelope-enabled tone immediately followed by its envelope event. Allophone
mnemonics are labels only; an observed or heard sound still needs a HUMAN result.
The generator's eight stored speech and eight stored sound cases exercise slot
addressing independently. The64 allophone cases include five explicit silent
pause cases. The16 envelope cases request each shape without asserting that
the current emulator or future FPGA is already physically accurate. No audible
or real-hardware validation is claimed by successful Python tests.
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Authored Sound Lab vectors; no emulator, ROM or third-party Python required."""
import argparse
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent
def crc16(data):
"""CRC-16/CCITT-FALSE: poly1021, initFFFF, refin=false, xorout0000."""
crc = 0xFFFF
for byte in data:
crc ^= byte << 8
for _ in range(8):
crc = ((crc << 1) ^ (0x1021 if crc & 0x8000 else 0)) & 0xFFFF
return crc
def sound_events(data):
"""Parse event boundaries; FF is legal inside operands, not at a boundary."""
pos = 0
events = []
while pos < len(data):
op = data[pos]
if op == 0xFF:
if pos != len(data) - 1:
raise ValueError('bytes after sound terminator')
return events
width = 4 if op & 0x60 == 0x60 or not op & 0x80 else 3
if pos + width >= len(data):
raise ValueError('incomplete sound event or missing terminator')
if width == 4 and op & 0x60 != 0x60 and data[pos + 1] > 15:
raise ValueError('tone coarse period outside 12-bit range')
if width == 3 and data[pos + 1] & 0x60:
raise ValueError('noise reserved period bits set')
events.append(data[pos:pos + width])
pos += width
raise ValueError('missing sound terminator')
def register_pairs(data):
pos = 0
while pos < len(data):
reg = data[pos]
if reg == 0xFF:
if pos != len(data) - 1:
raise ValueError('bytes after register terminator')
return
if reg > 13 or pos + 1 >= len(data):
raise ValueError('invalid or incomplete register pair')
maximum = (15 if reg in (1, 3, 5, 13) else
31 if reg in (6, 8, 9, 10) else 63 if reg == 7 else 255)
if data[pos + 1] > maximum:
raise ValueError('register value outside documented field width')
pos += 2
raise ValueError('missing register terminator')
def validate_tx(data):
"""Validate the deliberately bounded, single-slot command subset used here."""
if not data or any(type(b) is not int or not 0 <= b <= 255 for b in data):
raise ValueError('TX must contain bytes')
pos = 0
while pos < len(data):
cmd = data[pos]
pos += 1
if cmd in (0, 0xC7, 0xCF) or 0xD0 <= cmd <= 0xDF or 0xF0 <= cmd <= 0xFF:
continue
if cmd == 0x8F:
if pos == len(data):
raise ValueError('timer lacks operand')
pos += 1
continue
if 0x20 <= cmd < 0x80 or 0x90 <= cmd <= 0x97:
start = pos - 1 if cmd < 0x80 else pos
try:
end = data.index(13, start)
except ValueError:
raise ValueError('text lacks CR') from None
payload = data[start:end]
if not payload or any(not 32 <= b <= 126 for b in payload):
raise ValueError('non-printable text')
if len(payload) + 1 > 64:
raise ValueError('single text buffer exceeds 64 bytes')
pos = end + 1
continue
if 0x98 <= cmd <= 0x9F:
start = pos
while pos < len(data):
op = data[pos]
if op == 255:
pos += 1
break
pos += 4 if op & 0x60 == 0x60 or not op & 0x80 else 3
body = data[start:pos]
sound_events(body)
elif 0xB0 <= cmd <= 0xB7:
start = pos
while pos < len(data) and data[pos] != 255:
if data[pos] > 63:
raise ValueError('allophone outside AL2 range')
pos += 1
if pos == len(data) or pos == start or data[pos - 1] > 4:
raise ValueError('allophones need final pause and FF')
pos += 1
body = data[start:pos]
elif cmd == 0xAF or 0xB8 <= cmd <= 0xBF:
start = pos
while pos < len(data) and data[pos] != 255:
pos += 2
if pos == len(data):
raise ValueError('register packet lacks boundary terminator')
pos += 1
body = data[start:pos]
register_pairs(body)
else:
raise ValueError(f'unsupported command {cmd:02X}')
if cmd != 0xAF and len(body) > 64:
raise ValueError('single buffer exceeds 64 bytes')
return True
def tone(channel, period, volume=10, ticks=15):
if not 0 <= channel <= 2 or not 0 <= period <= 4095 or not 0 <= volume <= 31:
raise ValueError('invalid tone fields')
return [channel * 32 + volume, period >> 8, period & 255, ticks]
def noise(channel, period, volume=8, ticks=15):
return [0x80 + channel * 32 + volume, period, ticks]
def stored_sound(events, slot=0):
return [0x98 + slot] + events + [255, 0xD8 + slot]
def authored_vectors():
out = []
def add(identity, title, prompt, tx, wait=0x20, hold=0, group=2,
source='TANDY-SOUND', expectation='MEASURE_BASELINE'):
validate_tx(tx)
out.append(dict(id=identity, title=title, prompt=prompt, tx=tx,
wait_mask=wait, hold_ticks=hold, group=group,
source_claims=[source], expectation=expectation))
def text(s):
return list((s + ' \r').encode('ascii'))
add('TXT01', 'MEET YOUR ROBOT', 'HEAR THE GREETING?',
text('HELLO BRIAN. WELCOME TO THE SOUND LAB.'), 0x40, group=3,
source='TANDY-TEXT')
add('TXT02-READ', 'WORDS AND NUMBERS', 'WORDS CLEAR? NOTE PRONUNCIATION.',
text('READY PLAYER ONE. LEVEL TWO. SCORE ONE HUNDRED.'), 0x40,
source='TANDY-TEXT')
add('TXT03-LONG', 'SHORT THEN LONG', 'COMPARE WITH THE FIRST GREETING.',
text('THE ROBOT CAN SPEAK A LONGER SENTENCE.'), 0x40,
source='TANDY-TEXT')
for channel in range(3):
add('TON01-' + 'ABC'[channel], 'TONE ' + 'ABC'[channel],
'ONE CLEAR PITCH; THEN SILENCE.',
stored_sound(tone(channel, 254) + tone(channel, 254, 0, 0)),
group=3 if channel == 0 else 2)
add('TON04', 'RISING STEPS', 'DO THE THREE NOTES RISE?',
stored_sound(sum((tone(0, p, 10, 12) for p in (428, 339, 254)), []) + tone(0, 254, 0, 0)), group=3)
add('TON05', 'THREE VOICE CHORD', 'THREE NOTES TOGETHER, THEN OFF.',
stored_sound(tone(0, 428, 8, 0) + tone(1, 339, 8, 0) + tone(2, 285, 8, 24)
+ tone(0, 428, 0, 0) + tone(1, 339, 0, 0) + tone(2, 285, 0, 0)), group=3)
add('AMP01', 'SOFT TO LOUD', 'DO THE FOUR STEPS GET LOUDER?',
stored_sound(sum((tone(0, 254, v, 10) for v in (2, 5, 9, 13)), []) + tone(0, 254, 0, 0)))
add('NOI01', 'NOISE COLORS', 'NOISE CHANGES FROM HISS TO RUMBLE.',
stored_sound(sum((noise(0, p, 7, 12) for p in (1, 8, 31)), []) + noise(0, 31, 0, 0)), group=3)
add('NOI02', 'NOISE CONTINUE', 'TWO NOISE EVENTS; SAME VOLUME.',
stored_sound(noise(0, 8, 7, 15) + noise(0, 0x80 | 16, 0, 15) + noise(0, 16, 0, 0)), group=4)
# AF writes an audible fixed tone. Parent waits hold_ticks, sends00 and confirms silence.
add('REG01', 'DIRECT AY REGISTERS', 'STEADY TONE; PANIC MUST SILENCE.',
[0xAF, 0, 254, 1, 0, 7, 62, 8, 9, 255], 0, 40, 2, 'TANDY-REGISTERS')
add('REG02', 'FF IS REGISTER DATA', 'STEADY TONE; FF DATA IS NOT END.',
[0xAF, 0, 255, 1, 0, 7, 62, 8, 8, 255], 0, 40, 4, 'TANDY-REGISTERS')
add('CMD01', 'STOP AND CONTROL', 'NO SOUND AFTER ALL THREE STOPS.',
[0xC7, 0xCF, 0], 0x60, group=4, source='TANDY-COMMANDS', expectation='DOCUMENTED_CONTROL')
add('TIM01', 'BASE TIMER', 'RECORD DURATION; NO FIXED MS CLAIM.',
[0x8F, 16] + stored_sound(tone(0, 254, 8, 4) + tone(0, 254, 0, 0)), group=4,
source='TANDY-TIMER')
add('TIM02', 'FF IS DURATION DATA', 'LONG EVENT, THEN SILENCE.',
stored_sound(tone(0, 254, 8, 255) + tone(0, 254, 0, 0)), group=4)
add('FUN01-TUNE', 'ORIGINAL SHORT TUNE', 'HEAR A SMALL RISING AND FALLING TUNE.',
stored_sound(sum((tone(0, p, 9, 9) for p in (428, 339, 285, 254, 285, 339, 428)), [])
+ tone(0, 428, 0, 0)), group=3)
# Shared speech slots and independent sound slots; each case executes only its own slot.
for slot in range(8):
add(f'BUF01-SP{slot}', f'SPEECH SLOT {slot}', 'HEAR THE CORRECT SLOT NUMBER?',
[0x90 + slot] + text('BUFFER ' + ('ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN')[slot])
+ [0xD0 + slot], 0x40, group=4, source='TANDY-COMMANDS')
add(f'BUF02-SN{slot}', f'SOUND SLOT {slot}', 'MATCH SLOT AND SHORT TONE.',
stored_sound(tone(0, 428 - 24 * slot, 8, 8) + tone(0, 254, 0, 0), slot),
group=4, source='TANDY-COMMANDS')
names = ('PA1 PA2 PA3 PA4 PA5 OY AY EH KK3 PP JH NN1 IH TT2 RR1 AX MM TT1 DH1 IY EY DD1 UW1 AO AA YY2 AE HH1 BB1 TH UH UW2 AW DD2 GG3 VV GG1 SH ZH RR2 FF KK2 KK1 ZZ NG LL WW XR WH YY1 CH ER1 ER2 OW DH2 SS NN2 HH2 OR AR YR GG2 EL BB2').split()
for code, name in enumerate(names):
add(f'ALP01-{code:02d}', f'ALLOPHONE {code:02d} {name}',
'PAUSE: EXPECT NO VOICE.' if code < 5 else 'RECORD WHAT YOU HEAR.',
[0xB0, code, 0, 255, 0xF0], 0x40, group=4, source='TANDY-ALLOPHONES')
for shape in range(16):
# Documented grammar: envelope-enabled tone immediately followed by envelope event.
events = tone(0, 254, 16, 0) + [0x60 | shape, 3, 0, 35] + tone(0, 254, 0, 0)
add(f'ENV01-{shape:02d}', f'ENVELOPE {shape:02X}', 'COMPARE SHAPE AND END SILENCE.',
stored_sound(events), group=2 if shape == 10 else 4, source='TANDY-ENVELOPE')
add('MIX01', 'ROBOT SPACEPORT', 'VOICE OVER AN AMBIENT TONE.',
stored_sound(tone(0, 339, 5, 0)) + text('WELCOME TO THE SPACE PORT.'),
0x40, 20, 3, 'TANDY-COMMANDS')
return out
def build_manifest():
vectors = authored_vectors()
for case in vectors:
raw = bytes(case['tx'])
case.update(case_id=case['id'], crc16=f'{crc16(raw):04X}',
tx_hex=raw.hex(' ').upper(), byte_count=len(raw),
crc16_ccitt_false=f'{crc16(raw):04X}', sha256=hashlib.sha256(raw).hexdigest())
identities = [v['id'] for v in vectors]
if len(set(identities)) != len(identities):
raise ValueError('duplicate vector ID')
body = dict(schema='vccplus.sound-lab.vectors.v1', vector_version='1.0',
vector_set_crc16=f"{crc16(bytes(b for case in vectors for b in case['tx'])):04X}",
authored=True, crc='CRC-16/CCITT-FALSE',
result_policy='HUMAN listening is never an AUTO pass; timings are MEASURE_BASELINE.',
source_catalog=json.loads((ROOT / 'sources.json').read_text()), vectors=vectors)
canonical = json.dumps(body, sort_keys=True, separators=(',', ':')).encode()
body['manifest_sha256'] = hashlib.sha256(canonical).hexdigest()
return body
def emit(output):
manifest = build_manifest()
output.mkdir(parents=True, exist_ok=True)
(output / 'vectors.json').write_text(json.dumps(manifest, indent=2) + '\n')
lines = ['/* Generated by vectors/generate.py; do not edit. */', '#ifndef SOUND_LAB_VECTORS_H',
'#define SOUND_LAB_VECTORS_H',
'typedef struct { const char *id; const char *title; const char *prompt;',
'const unsigned char *tx; unsigned length; unsigned crc16;',
'unsigned char wait_mask; unsigned char hold_ticks; unsigned char group; } SoundVector;']
for i, case in enumerate(manifest['vectors']):
lines.append('static const unsigned char sound_tx_%u[] = {%s};' %
(i, ','.join('0x%02X' % b for b in case['tx'])))
lines.append('static const SoundVector sound_vectors[] = {')
for i, case in enumerate(manifest['vectors']):
lines.append('{%s,%s,%s,sound_tx_%u,%u,0x%s,0x%02X,%u,%u},' %
(json.dumps(case['id']), json.dumps(case['title']), json.dumps(case['prompt']),
i, case['byte_count'], case['crc16_ccitt_false'], case['wait_mask'],
case['hold_ticks'], case['group']))
lines += ['};', '#define SOUND_VECTOR_COUNT %u' % len(manifest['vectors']),
'#define SOUND_VECTOR_VERSION "1.0"',
'#define SOUND_MANIFEST_SHA256 "%s"' % manifest['manifest_sha256'], '#endif', '']
(output / 'vectors.h').write_text('\n'.join(lines))
return manifest
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
result = emit(args.output)
print(f"{len(result['vectors'])} vectors; manifest {result['manifest_sha256']}")
+74
View File
@@ -0,0 +1,74 @@
{
"schema": "vccplus.sound-lab.sources.v1",
"sources": [
{
"id": "TANDY-OWNER-1984",
"title": "Color Computer Speech/Sound Cartridge Owner's Manual",
"publisher": "Tandy Corporation",
"year": 1984,
"url": "https://colorcomputerarchive.com/repo/Documents/Manuals/Hardware/Speech-Sound%20Cartridge%20%28Tandy%29.pdf",
"sha256": "80aa645aa57da31121f7741d7373f21c5e5c69825f5a5eff8a86ad899055c92a",
"qualification": "Primary Tandy publication reproduced/OCR-typeset by Tim Lindner; 54-page2004 PDF retrieved2026-11-17. Page pixels24,26,28 inspected for AF/register0-13, timer8F, single slots and C7/CF controls. This is not a photographic original scan: original-paper comparison remains pending. Archive old filename404s; current alternate Manual filename is a newer57-page reproduction, retained separately and not used as the cited edition.",
"page_numbering": "Printed page =1-based PDF page in the54-page cited edition.",
"claims": [
{
"id": "TANDY-TEXT",
"pages": "9-11",
"section": "Speaking of the S/SC",
"fact": "Printable text is sent at FF7E with ready polling; CR completes input. The diagnostic appends a space to flush a final word as its explicit conservative authoring policy."
},
{
"id": "TANDY-COMMANDS",
"pages": "12-14,26-30",
"section": "Straight Talk; Appendix A",
"fact": "Eight speech slots support text or allophones; eight sound slots support events or register strings. Single-slot load and execute commands are used. 00 stops speech and sound without clearing stored buffers; C7 stops speech; CF stops sound."
},
{
"id": "TANDY-SOUND",
"pages": "15-20",
"section": "Sound Advice; Dial Tone; As Plain as the Noise",
"fact": "Tone events consume4 bytes, noise3; event-boundary FF terminates, operand FF is data. Final amplitude-zero events silence sustained output. Duration is between events, not an automatic noteoff."
},
{
"id": "TANDY-TIMER",
"pages": "18,20,23,26",
"section": "Event duration; Appendix A8F",
"fact": "8F accepts one0-255 base-time operand. Larger values increase event duration. No absolute event timing is asserted here."
},
{
"id": "TANDY-ENVELOPE",
"pages": "21-23,33-34",
"section": "The Envelope, Please; Appendix B",
"fact": "Envelope event is4 bytes: operation60+shape, coarse period, fine period, duration. All channels share one envelope generator. Envelope-enabled tone/noise is immediately followed by envelope group."
},
{
"id": "TANDY-REGISTERS",
"pages": "24-25,27,31-34",
"section": "Scaling the Sound Registers; Appendices A/B",
"fact": "AF enters direct register/value access; FF at a register boundary exits. Table and example explicitly include register0 despite the introductory prose saying1-13. Register operands may equalFF. R8-R10 bit4 envelope mode is documented in Appendix B though compact table lists only fixed0-15."
},
{
"id": "TANDY-ALLOPHONES",
"pages": "13-14,35-36",
"section": "Straight Talk; Appendix C",
"fact": "AL2 addresses0-63;0-4 are pauses. Allophone strings end with a pause then FF. Code order and mnemonic labels follow Appendix C; sound fidelity and duration remain measurements."
}
],
"retrieved_url": "https://tlindner.macmess.org/wp-content/uploads/2006/09/sscmanual.pdf",
"byte_count": 211234,
"alternate_reproduction": {
"url": "https://colorcomputerarchive.com/repo/Documents/Manuals/Hardware/Speech-Sound%20Cartridge%20Manual%20(Tandy).pdf",
"sha256": "7170a1c33164d654f2d92af8c708bc38bac14dbd53f3fa142da1cd724201f1de",
"pages": 57,
"role": "Discovery evidence only, not cited for command grammar."
}
}
],
"non_assertions": [
"No physical cartridge, FPGA, human listening or analog fidelity pass is claimed by this manifest.",
"Speech standby40 and sound idle20 are current SDK/model observation conventions, not source-qualified hardware acceptance assertions in this manifest.",
"No automatic controller or cartridge presence detection is inferred from a floating status byte.",
"The SDK's priming/retrigger workaround for cold one-shot envelopes is not substituted for documented packet grammar.",
"Single-slot sound/register payloads include the terminator within64 bytes. Allophone and text slots share storage; this is not16 independent speech buffers."
]
}
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only post-native Sound Lab qualification checks; no emulator changes."""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import sys
from typing import Any
_MODULE = Path(__file__).resolve().parent / "host" / "soundlab_reports.py"
_SPEC = importlib.util.spec_from_file_location("soundlab_reports", _MODULE)
reports = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(reports)
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def disk_files(data: bytes) -> dict[str, bytes]:
"""Read all ordinary files after the host extractor validates every active chain."""
reports.extract_reports(data)
files = {}
fat = data[reports.FAT_OFFSET:reports.FAT_OFFSET + 68]
for index in range(72):
offset = reports.DIRECTORY_OFFSET + index * 32
entry = data[offset:offset + 32]
if entry[0] in (0, 0xFF):
continue
base = entry[:8].decode('ascii').rstrip(' ')
extension = entry[8:11].decode('ascii').rstrip(' ')
name = (base + ('.' + extension if extension else '')).upper()
current, chain = entry[13], []
while True:
chain.append(current)
successor = fat[current]
if successor >= 0xC0:
sectors = successor - 0xC0
break
current = successor
last_bytes = int.from_bytes(entry[14:16], 'big')
length = (len(chain) - 1) * 2304 + ((sectors - 1) * 256 + last_bytes if sectors else 0)
files[name] = b''.join(data[reports.granule_offset(g):reports.granule_offset(g) + 2304] for g in chain)[:length]
return files
def qualify(build_dir: Path) -> dict[str, Any]:
manifest_path = build_dir / 'SOUNDLAB-manifest.json'
manifest_bytes = manifest_path.read_bytes()
manifest = json.loads(manifest_bytes)
if not isinstance(manifest, dict) or not isinstance(manifest.get('artifacts'), list):
raise reports.SoundLabError('Build manifest lacks its artifact list')
artifacts = {item['filename'].upper(): item for item in manifest['artifacts']}
pristine_path = build_dir / 'SOUNDLAB.DSK'
pristine_bytes = pristine_path.read_bytes()
artifact = artifacts.get('SOUNDLAB.DSK')
if not artifact or artifact.get('sha256') != sha256(pristine_bytes) or artifact.get('bytes') != len(pristine_bytes):
raise reports.SoundLabError('Pristine SOUNDLAB.DSK does not match build manifest')
pristine = disk_files(pristine_bytes)
protected = {name: data for name, data in pristine.items() if name.endswith(('.BIN', '.BAS'))}
if not protected or 'SOUNDLAB.BIN' not in protected or 'SOUNDLAB.BAS' not in protected:
raise reports.SoundLabError('Pristine disk lacks the declared Sound Lab BIN/BAS files')
for name, data in protected.items():
if name not in artifacts:
continue
source = (build_dir / name).read_bytes()
if artifacts[name].get('sha256') != sha256(source) or artifacts[name].get('bytes') != len(source):
raise reports.SoundLabError(f'Host {name} differs from manifest artifact')
expected = source
if name.endswith('.BAS'):
# build.py uses writecocofile --newlines: a leading empty CR line,
# then every LF-terminated native source line followed by CR.
if not source.endswith(b'\n') or b'\r' in source:
raise reports.SoundLabError(f'Host {name} is not the expected LF-terminated BASIC source')
expected = b'\r' + source.replace(b'\n', b'\r')
if data != expected:
raise reports.SoundLabError(f'Pristine {name} differs from its declared build input conversion')
outcome: dict[str, Any] = {
'schema': 'vccplus.sound-lab.native-report-qualification.v1',
'build_id': manifest.get('build_id'), 'vector_set_crc16': manifest.get('vector_set_crc16'),
'manifest_sha256': sha256(manifest_bytes), 'pristine_disk_sha256': sha256(pristine_bytes),
'protected_files': {name: {'bytes': len(data), 'sha256': sha256(data)} for name, data in sorted(protected.items())},
'runs': {},
'evidence_limits': ['Native emulator checks only; no real-cartridge, FPGA or listening acceptance.',
'HUMAN=UNSURE and NOT_OBSERVED are automation input choices, not a listening verdict.',
'All source disks were read-only host inputs; no source files were modified.']}
extracted: dict[str, dict[str, bytes]] = {}
for label in ('6809', '6309', 'engineering'):
path = build_dir / 'qualification' / (label + '-reports.dsk')
raw = path.read_bytes()
contents = disk_files(raw)
for name, expected in protected.items():
if contents.get(name) != expected:
raise reports.SoundLabError(f'{label}: pristine {name} missing or changed')
selected = reports.extract_reports(raw)
if not selected:
raise reports.SoundLabError(f'{label}: no native report files')
extracted[label] = {item['filename']: item['data'] for item in selected}
run_result = {'disk_sha256': sha256(raw), 'protected_files_unchanged': True, 'reports': [],
'repeat_observed': False, 'unsure_recorded': False, 'human_heard_fabricated': False}
for item in selected:
name = item['filename']
parsed = reports.parse_report(item['data'], name)
identity_issues = reports.validate_manifest(parsed, manifest)
if not parsed['complete'] or not parsed['valid']:
raise reports.SoundLabError(f"{label}/{name}: partial/invalid report: {'; '.join(parsed['issues'])}")
if parsed['integrity'] != {'record_count': 'VERIFIED', 'checksum_crc16': 'VERIFIED'}:
raise reports.SoundLabError(f'{label}/{name}: count/checksum not both verified')
if identity_issues:
raise reports.SoundLabError(f"{label}/{name}: {'; '.join(identity_issues)}")
if parsed['metadata'].get('RUN') != name[3:7]:
raise reports.SoundLabError(f'{label}/{name}: RUN does not match filename')
case_summary = []
for case in parsed['cases']:
if case['human'] == 'HEARD':
raise reports.SoundLabError(f'{label}/{name}/{case["id"]}: native automation must not fabricate HUMAN=HEARD')
run_result['repeat_observed'] |= case['repeat'] > 0
run_result['unsure_recorded'] |= case['human'] == 'UNSURE'
case_summary.append({'case': case['id'], 'repeat': case['repeat'], 'auto': case['auto'], 'human': case['human'],
'vector_crc16': case['fields']['VECTOR_CRC16']})
run_result['reports'].append({'filename': name, 'sha256': item['sha256'], 'bytes': item['byte_count'],
'complete': True, 'integrity': parsed['integrity'], 'cases': case_summary})
if label in ('6809', '6309') and (not run_result['repeat_observed'] or not run_result['unsure_recorded']):
raise reports.SoundLabError(f'{label}: required repeat and UNSURE inputs were not recorded')
outcome['runs'][label] = run_result
for name, data in extracted['6809'].items():
if extracted['engineering'].get(name) != data:
raise reports.SoundLabError(f'Engineering continuation modified or removed original 6809 report {name}')
added = sorted(set(extracted['engineering']) - set(extracted['6809']))
if not added:
raise reports.SoundLabError('Engineering continuation did not create any additional reports')
outcome['engineering_original_reports_byte_identical'] = True
outcome['engineering_new_reports'] = added
outcome['passed'] = True
return outcome
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--build-dir', type=Path, default=Path('.build/sound-lab'))
parser.add_argument('--receipt', type=Path, help='Optional JSON receipt; no output files are written by default')
parser.add_argument('--overwrite', action='store_true', help='Explicitly replace an existing regular receipt file')
args = parser.parse_args(argv)
try:
result = qualify(args.build_dir)
if args.receipt:
inputs = [args.build_dir / 'SOUNDLAB-manifest.json', args.build_dir / 'SOUNDLAB.DSK']
inputs.extend(args.build_dir / 'qualification' / f'{label}-reports.dsk' for label in ('6809', '6309', 'engineering'))
if any(args.receipt.resolve() == path.resolve() or (args.receipt.exists() and args.receipt.samefile(path)) for path in inputs):
raise reports.SoundLabError('Receipt would replace an input')
reports.write_outputs({args.receipt: (json.dumps(result, indent=2) + '\n').encode('utf-8')}, args.overwrite)
print(f"PASS Sound Lab reports: build {result['build_id']}; " + ', '.join(f"{label}={len(run['reports'])}" for label, run in result['runs'].items()))
print('Verified complete reports, checksums/counts, manifest identities, repeated/UNSURE inputs, unchanged BIN/BAS and retained originals.')
print('No HUMAN=HEARD result or physical/listening acceptance is claimed.')
return 0
except (OSError, ValueError, KeyError, TypeError) as error:
print(f'Sound Lab report qualification failed: {error}', file=sys.stderr)
return 1
if __name__ == '__main__':
raise SystemExit(main())