"""Audio for the ROM: the Z80 driver binary and the sample stream, frame-locked. The Z80 plays one sample per 3 FM periods = MCLK / 3024, and the player shows one video frame per 2 hardware frames = 2 x 313 x 3420 MCLK on PAL. So a video frame lasts exactly 707.976 samples on the console, while the source has rate / 25 per frame. Resampling the source by that ratio locks sound to picture by construction (the content plays 0.6 % slow on PAL - 10 cents - which nobody will hear). """ from __future__ import annotations from pathlib import Path import numpy as np from .toolchain import ROOT, assemble_z80 PAGE = 0x80000 MCLK_PER_SAMPLE = 3024 MCLK_PER_VIDEO_FRAME_PAL = 2 * 313 * 3420 SAMPLES_PER_VIDEO_FRAME = MCLK_PER_VIDEO_FRAME_PAL / MCLK_PER_SAMPLE # 707.976 SOURCE_FPS = 25.0 TAIL_SILENCE = 2 * 17594 # two seconds of 0x80 after the stream def resample_locked(samples: np.ndarray, source_rate: float) -> np.ndarray: """Linear resampling so that each source video frame spans SAMPLES_PER_VIDEO_FRAME.""" per_frame_in = source_rate / SOURCE_FPS ratio = SAMPLES_PER_VIDEO_FRAME / per_frame_in n_out = int(round(len(samples) * ratio)) x_out = np.arange(n_out) / ratio return np.interp(x_out, np.arange(len(samples)), samples.astype(np.float64)) def test_tone(seconds: float = 36.0) -> np.ndarray: """Pseudo-random walk, never two equal neighbours: order and drops are unambiguous. Long enough (> 512 KB) to cross a mapper page boundary.""" rng = np.random.default_rng(7) n = int(seconds * 17594) steps = rng.integers(1, 10, n) * rng.choice([-1, 1], n) out = np.empty(n, dtype=np.int64) v = 128 for i, s in enumerate(steps): v += s if v > 250 or v < 5: v -= 2 * s out[i] = v return out.astype(np.uint8) def prepare_audio(out: Path, source: Path | None, source_rate: float, tone: bool, skip_seconds: float = 0.0, length_seconds: float | None = None) -> dict: # fmt: skip """Write out/audio.u8 (frame-locked, silence-padded) and out/pcm.bin; return the ROM page the stream will occupy (the first page after the video data). ``skip_seconds``/``length_seconds`` select the slice of the source matching the encoded frames, measured in the source's own time.""" if tone: samples = test_tone() locked = samples.astype(np.float64) # the tone is a test pattern, not timed material else: assert source is not None samples = np.frombuffer(source.read_bytes(), dtype=np.uint8) first = int(round(skip_seconds * source_rate)) last = len(samples) if length_seconds is None else first + int(round(length_seconds * source_rate)) locked = resample_locked(samples[first:last], source_rate) stream = np.clip(np.rint(locked), 0, 255).astype(np.uint8) stream = np.concatenate([stream, np.full(TAIL_SILENCE, 0x80, dtype=np.uint8)]) (out / "audio.u8").write_bytes(stream.tobytes()) assemble_z80(ROOT / "player" / "pcm.z80", out / "pcm.bin") data_end = 0x10000 + (out / "data.bin").stat().st_size page = -(-data_end // PAGE) # first page boundary at or after the video data return {"page": page, "samples": int(len(stream)), "seconds": len(stream) / 17594, "rom_end": page * PAGE + len(stream), "samples_per_video_frame": SAMPLES_PER_VIDEO_FRAME} # fmt: skip