How it works · write-up
Sound improvement plan
Working notes, rendered as they are: they were written while building the game, so expect ROM addresses, register names and references to source files that are not published.
Updated: 2026-11-03. Backlog 383 (overall), 384 (sound explorer), 407 (packed MP3 bank). Canonical samples, independent live effects, emitter identity and native 3D positioning are implemented under384–387. Recording, seeking and stereo export are implemented under388. Verification results and remaining device/listening coverage are recorded below and in RESEARCH388.
The effect bank now uses one indexed binary pack containing 37 independently
encoded mono MP3 streams across live play, the explorer, recording replay and
video export. npm run audio:samples encodes each stream from synthesized PCM
before concatenation; playback slices its exact byte range before decoding.
npm run build verifies every range. The earlier WAV/MP3 listening comparison
was retired under 406.
The complete clean-checkout command order and required ROM, C64 and FFmpeg
inputs are in README.md. The audio step produces only
assets/audio/effects/effects.bin; it must run before npm run build, including
when following the separate 3D model guide.
The user chose canonical samples after listening to the retained-state comparisons in research 382. Use one consistent rendition of each effect. Do not reproduce differences caused by previous sounds, chip phase or the original global envelope clock. Numerical waveform differences alone are not a reason to add runtime machinery.
Intended result
- Clear, positioned effects that can overlap without the original sound-slot limits.
- Moving sources follow the actual object that emitted them.
- Independent choices of arcade/C64 music and arcade/C64 effect samples.
- Correct starts, repeats, changes and stops; no stuck engine or cinematic sounds.
- The same mix in live play, recordings, seeking and exported video.
- Keep existing music synthesis and intentional music transitions. This is not a project to rewrite either music driver or increase the instruments in a song.
Original driver limits (removed from normal effect playback)
| Path | Current behavior |
|---|---|
| Arcade effects | Two SSG groups, each selecting one of four priority records. An effect can use three tone/noise voices within its selected group. A higher-priority record pauses a lower one; a request to the same record replaces it. |
| Arcade music and musical cues | A separate set of four candidate FM banks, with up to six FM voices in the selected bank. Only the highest active bank advances. Themes, fanfares and death/clear cues can replace or interrupt one another. They do not take SSG effect slots. |
| Original C64 driver | Music and effects share one three-voice SID. An effect uses voices 1 and 2, displacing their music output; another effect replaces it. |
| Current browser with C64 music selected | C64 music replaces mapped music cues. Unmapped musical cues use arcade FM. Effects independently use the selected sample pack: verified C64 equivalents or explicit arcade fallbacks, with no effect-slot limit. |
Sources: arcade-driver.ts bank selection/command initialization,
audio-engine.ts music mapping, the original C64 $53A5/$5531 effect paths,
and research 382. The three/six voices inside a music arrangement are distinct
from the restrictive effect slots. We do not need unlimited simultaneous songs.
1. Build the canonical effect library
Extend the existing audio asset build, using the supplied local ROM/PRG and existing synthesizers. No downloads of recordings or manually recorded browser audio are needed. Generated audio stays out of Git, like other ROM-derived assets.
For each effect, render from a documented clean state and fixed clock phase. Store independently encoded mono MP3 streams in one pack with an embedded index: named effect/source ID, exact byte offset and length, hash, sample rate and optional loop start/end. Decode each isolated stream once, then share its buffer among playback instances.
Finite effects include their complete decay. Keep sensible relative levels; do not independently normalize every effect to maximum loudness. Remove unwanted DC offset and choose clean boundaries during asset preparation, with listening verification. This preparation is shared by every playback, not performed per event.
All 21 arcade SSG effects and 16 C64 presets remain available to the explorer. Unused presets stay labelled unused and do not acquire invented gameplay uses. For the C64 gameplay pack, explicitly map verified equivalents; use an identified arcade fallback for missing equivalents rather than guessing from sound names. FM musical cues such as player death $2B retain their existing music-cue policy; do not also trigger a second death sound merely because a C64 preset has that name.
2. Repeating sounds: one asset, an optional intro, and a loop region
Yes: prepare the sound once and let the sample player handle repetition. The sample buffer can contain an introduction followed by the reusable loop region. The player reaches the loop end, wraps to its loop start, and continues until an explicit stop/change or the source's lifetime ends. It does not launch a new sound on every game update or use a browser timer to schedule each repetition.
| Arcade ID | Sound | Asset behavior |
|---|---|---|
| $0C | Unused tone/noise rattle | Loop; explorer only unless a real caller is established. |
| $10 | Helicopter landing | Loop while that helicopter's landing cue is active. |
| $12 | Helicopter area transfer | Loop while that helicopter's transfer cue is active. |
| $15 | Emplacement enters | Intro and loop as required by the prepared sound; stop with the relevant lifecycle/control event. |
The software sequences repeat, but their exact cycle boundaries are not guaranteed to be seamless audio boundaries. Prepare and listen to a stable loop, using a short baked crossfade only if needed. Do not export an arbitrarily truncated sample and assume its endpoints join cleanly. Test several audible repetitions.
$0B Moving vehicle and $0D Transport resumes are finite, about 3.83 s and 2.10 s. They play once per actual request, while following the source if it moves. Do not invent indefinite engine loops. The C64 presets are finite; a C64 pack without a suitable repeating equivalent uses the documented arcade fallback.
A repeated start request for an already-active loop belonging to the same object and purpose does not create a second loop. A cue change replaces that object's previous cue. Different objects can play the same loop independently. Ordinary one-shot requests remain separate events and may overlap.
Stopping a loop uses a short click-prevention release. Replacing it does not let the old loop finish another whole repetition. Pause freezes playback position; resume continues it; reset clears active effects. A loop is never tied to a reused actor-slot number without its lifetime identity.
3. Browser audio nodes and a small emission contract
Use the browser's native Web Audio graph, not a custom PCM mixer or panner.
Each instance has an AudioBufferSourceNode sharing its canonical buffer, a
GainNode, and a PannerNode when spatial positioning is needed. The browser
mixes connected nodes. Keep only instance IDs, timing, emitter association and
lifecycle in our code. sounds.html already uses shared buffers and independent
source nodes; it does not yet position them in space.
Share graph construction between AudioContext for live playback and
OfflineAudioContext for recorded audio/video rendering. Existing music synthesis
can feed the music branch; it does not need to be rewritten. The reference PCM
worklet remains useful for streamed synthesized music, not for reimplementing
sample mixing.
Each legitimate effect event gets an independent voice. There is no two-group, four-bank or three-SID-voice ceiling, and no priority-based dropping of distinct effects. Natural completion, explicit stop and reset remove voices. Keep output headroom and a final limiter for loud overlaps. Profile before adding any other voice-budget policy; do not silently restore the old limits under another name.
Capture a small, ordered audio event at the existing gameplay sound producer: effect ID, update/order, start/stop/change operation, stable emitter identity when available, and emission position. Only add fields needed by the consumer. Reuse existing actor/compound lifetime identities; do not identify an emitter from its sprite, appearance, proximity or current occupant of an old slot.
The original gameplay sound queue, returned values and ordered gameplay effects remain unchanged. The presentation journal observes requests before the lossy latch and legacy sound-bank selection. Sampled effects consume that journal once; they do not also consume the same effect from $C800. This deliberately removes original suppression and queue-delay artifacts from effect playback. Use the emission update as the effect timestamp, in stable producer order. Music can continue consuming its existing published commands and cue policy. Rendering a frame again must not emit sounds again; audio availability must not affect gameplay, RNG or actor updates.
Record removal and control events explicitly where needed. Translate controls into meaningful scopes, not "stop everything that once shared RAM bank $4560." For example, gate-entry $16 stops the applicable emplacement sound; helicopter cue changes affect that helicopter; a session effects reset clears all effects. Review the six SSG terminators and their callers before implementing their scope. Some old bank collisions are artifacts to remove, not reasons to cut off an unrelated pickup sound. Unknown ownership stays explicit until resolved.
4. Native 3D position and movement
Use PannerNode positions/orientations and the context's AudioListener.
The browser supports distance attenuation, directional cones and HRTF spatialization;
use HRTF for positioned world sounds, with modest distance attenuation and
omnidirectional sources unless an effect has a reason to be directional. This
uses the browser's implementation, not new acoustic algorithms. Occlusion,
reverberation and Doppler are outside this work.
- Gunshots, explosions and impacts use their emission/impact position.
- Vehicle and helicopter sounds attach to the emitting object and follow its gameplay position each update. A compound vehicle uses its proved parent identity.
- Coin, menu, extra-life and musical cues are centered, without distance fading.
- An attached finite sound whose owner disappears finishes at its last known position; an owner-dependent loop stops. Slot reuse cannot attach either to the replacement actor.
Map unwrapped gameplay coordinates to one documented 3D audio space (ground plane plus real height where known); never invent height from artwork. Use the player as the normal listener, with orientation consistent with the view; cinematics use a declared scene/listener anchor. Record listener position/orientation alongside source positions. Arcade and model renderers share actor identities and gameplay positions without deriving them from sprites or mesh vertices. A rotating 3D view supplies its listener orientation through this same small contract.
3D input and stereo output are compatible. The native panner produces two channels representing what the listener hears. A normal MP4 therefore remains stereo, including the baked spatial cues for the recorded viewpoint. The game recording retains source/listener data so it can be spatialized again; the MP4 does not retain independently movable audio objects or head tracking.
5. Music stays independent
Keep runtime synthesis for both music backends and the existing game-defined theme/clear/death/game-over transitions. In the new mixer, effects from either sample pack never steal music voices or pause music. C64 samples do not execute inside the music SID. The music keeps its composed instruments and internal timing.
Music cues may still deliberately replace or interrupt other music cues. This is useful musical behavior, not an effect-slot limit to remove. Do not mix all themes simultaneously or introduce a new music-priority framework. If a specific musical transition is later judged undesirable, change that transition separately. Maintain music/effects/master controls; changing volume or spatial position must not restart either music backend (AI-291).
The normal effects path uses samples. Retain the existing synthesis code where needed for music, asset generation and reference auditions; do not maintain two complete competing gameplay audio systems or add a retained-state fidelity option.
6. Recording, replay and export
Extend the existing audio journal with effect events, active-emitter/listener position changes and effect-pack settings. Save the canonical bank version/hash. Use a bundled content-addressed bank for ordinary playback; a portable recording export includes the referenced sample bank so it does not depend on a mutable URL. Reject mismatched assets clearly rather than playing a different rendition.
Reuse the existing audio prefix/reconstruction mechanism to recover active finite sounds and loop offsets when recording starts mid-game or playback seeks. Positions must be recorded while sounds are active, not only at their start. Reconstruct silently to the seek point, then resume without replaying old sound onsets aloud. Do not serialize browser audio nodes or chip internals for sampled effects.
Render the shared Web Audio graph with OfflineAudioContext, including the saved
position automation and music, then encode its two-channel result for MP4. Reuse
the graph setup rather than write a separate software spatializer for export.
Keep export memory bounded for complete runs; if rendering in chunks, verify
continuation and processing tails at each boundary. Do not assume HRTF output is
bit-identical across browser implementations; validate event/position timing and
audible results, with numerical comparisons within the same browser.
Keep playback buffers and MP4 audio stereo end to end. Preserve pitch at playback speeds above/below 1x by applying the existing tempo treatment consistently to both channels. Keep audio on/off, pause, ending capture and complete-run export.
Bump the recording audio format/engine identity. No compatibility with old recordings is required. New recordings must reproduce their saved effects, positions, loop phases, music and mix settings through forward/backward seeking.
Delivery order and verification
Implement one bounded step at a time, preserving gameplay and verifying it before the next step. Tests use the real browser audio nodes and existing runtime owners.
- Canonical assets and index. Build both libraries, verify every audible
preset, separately classify silent controls, and listen to finite tails and
repeated loop seams through
sounds.html. No history-dependent variants. - Emission identity and lifecycle. Add the observation journal at existing producers, with explicit ownership/control mappings. Verify gameplay state, command order and source queue results stay unchanged; no duplicate events.
- Native graph and positioning. Route both effect packs through the shared Web Audio graph. Verify simultaneous shots/explosions, two independent moving emitters, loop replacement/removal, slot reuse and no music interruption. Reuse the sound explorer and add focused behavior-lab scenarios, not another large UI page.
- Recording and stereo export. Extend the current format and shared renderer. Compare live versus offline-rendered audio; seek within a moving sound, intro, repeating region and stop; verify stereo MP4 and pitch-preserving speed changes.
- Integration and listening. Check title/coin, combat, gate, death/restart, helicopter transitions, bonuses and the full ending with both music/effect choices. Run existing audio/recording tests and an established full winning replay for unchanged gameplay. Measure frame cost, mixing cost, underruns and active-voice cleanup during dense combat. Record perceptual feedback separately from numerical PCM comparisons; do not expand the design solely to eliminate inaudible waveform differences.
Newly inferred gameplay control meanings require ASM/raw-ROM review and bounded MAME checks. Sample playback is an intentional presentation improvement, not a claim of exact original-board sound. Update the backlog and architecture when each part is implemented.
Delivered integration (388)
New audio schema2 stores emitter lifetime events, position changes, listener axes, effect-pack/mix changes and the canonical bank hash. Portable Export embeds sample bytes. Old audio formats are rejected, with no compatibility adapter. Music keeps its existing synthesis and pre-roll; independent sampled effects retain their start time, loop offset and final position after removal.
Live play and recording rendering share SpatialSoundGraph. Native offline renders produce two-second stereo blocks with one second of filter history and preserve the native 128-sample quantum phase. Replay prefetches the next block. Stereo tempo processing uses shared grain alignment so playback speed preserves pitch and image. Export encodes H264/AAC at224×256/60fps, using native audio on the page and video encoding in its worker. PCM working memory is bounded; compressed MP4 output still occupies memory until download. A native output ceiling protects extreme coincident bursts that exceed the compressor's attack response; normal-range samples pass unchanged.
Verification includes real native audio nodes, four independent music/effect-pack combinations, seek/cancel/moving-loop continuation, changed block boundaries, head rotation,100 simultaneous effects, output cleanup, portable asset validation, stereo tempo tests, a six-second MP4 and a full winning MP4 including both endings. All903 Node tests pass. All40009 gameplay states match the pre-change baseline, including demonstrations, lives and final state. This establishes unchanged game behavior, not new original-board audio fidelity. HRTF output varies by browser; headphone preference and physical VR-headset listening remain device acceptance.
Correction 389 (2026-10-27): 388's MP4 checks established metadata and successful encoding, but missed corrupted audio content. Delivery acceptance now requires decoding the AAC and comparing it to native replay PCM, including block boundaries and the complete run. The regenerated winning movie passes every block (aggregate SNR 20.37dB, lowest audible block 15.98dB, no drift). See AI-324 and RESEARCH389.
API references: PannerNode and spatialization (W3C), AudioBufferSourceNode, and OfflineAudioContext.