Sound
snd) is a single,
compiled-stream music player for Mikey's four audio channels, plus a small set of
direct-register helpers (mikey_snd_*) for sound effects. Tunes are
written in human-readable ABC text and compiled offline into a byte-coded event
stream by the abccc tool; on target the engine
walks that stream under a dedicated timer interrupt. This page explains how playback
works; composing tunes with abccc and auditioning them with
abcrom have their own tool pages. The authoritative
reference is design/LYNX_SND_ENGINE_DESIGN.md.1. Overview
Mikey provides four independent audio channels. Each is an 8-byte register
block (volume, feedback, output, shift register, timer reload, control, counter)
that produces a tone or noise from a polynomial shift register clocked by a timer.
The snd engine drives all four from a per-channel software state: it
reads a compiled event stream — notes interleaved with opcodes that
set instruments, envelopes, loops and the like — and writes the channel
registers every interrupt. Like the rest of the Lynx runtime, snd is a static, smart-linked library: there is nothing to install and nothing that can fail to load.
Authoring and playback are deliberately split. You write a tune in the
ABC source language; the standalone abccc
compiler turns it into the binary stream at build time; and the engine replays
that stream on target with no ASCII parsing. For one-off sound effects that do not
need the stream machinery, the mikey_snd_* helpers poke a single Mikey
register directly.
The snd engine is not the only music option. HandyMusic
is a heavier, opt-in alternative BGM+SFX engine (Osman Celimli's
macro-instrument driver, compiled with hmcc): richer
instrument and envelope control plus RAM-sourced 8 kHz PCM one-shots, at a
larger footprint. The two are mutually
exclusive — link one engine or the other. This page covers snd;
see the HandyMusic page for that engine.
2. How playback works
Call snd_init() once at startup. It programs a dedicated Mikey
timer (STIMCTLA/STIMBKUP, ~240 Hz by default) and
installs the sound-interrupt handler, which is finer than a 60 Hz vertical
blank and gives smoother envelopes. Then hand a compiled stream to a channel with
snd_play(channel, stream); if that channel is already sounding it
is retriggered in place — the old stream is force-stopped and the new one
starts on the same channel. Playback advances on its own from then on — your
program is free between calls. snd_pause()/snd_continue()
suspend and resume every channel, snd_stop() and
snd_stop_channel() silence all or one, and snd_active()
returns a bitmask of the channels still playing. Any of these three stops —
an explicit snd_stop*() call or a snd_play() retrigger
— fades the channel's volume out over a few ticks (~17 ms at 240 Hz)
instead of cutting it instantly, so repeatedly firing a short effect doesn't click;
see §6.5.
The interpreter reads a lead byte each step. With bit 7 clear the
byte is a note; with bit 7 set it is an opcode
($80 + index) whose operands follow; $00 ends the
stream and the channel goes idle. Each handler reports how many bytes to advance
and whether to keep processing in the same frame, so several configuration events
can run on one note boundary while notes themselves wait out their duration (in
interrupt frames).
Two stream features keep tunes compact and expressive while remaining
backward compatible: every byte in an existing stream decodes
exactly as before, and new behaviour lives in opcodes $93 and up,
which old streams never contain.
- Compact notes. A legacy note is two bytes,
[pitch][duration]. EmittingMode 1($93) switches a channel to 1-byte notes that take their duration fromSetDur($94) — about a third smaller for a typical melody. - Integrate / taps.
SetInteg($95) stores a per-channel bit that is OR-ed into the CONTROL register, switching a channel to the integrated waveform (ABCI1) or selecting the 9th feedback tap (high ABCX). Defaulting to 0 leaves the legacy square wave untouched.
3. Composing with abccc
Tunes are written in ABC, a compact text notation, and compiled
to the binary event stream by the abccc tool before the normal build
runs — ABC is the authoring format only and is never parsed on
target. The full ABC language (notes, durations, the
V/R/H/K/T/O/I/X inline commands, repeats and AHD / looping envelopes),
together with the tool's options and its Makefile build-flow rule, lives on the
dedicated abccc tool page. In short, one rule turns each
.abc tune into a linkable stream:
assets/%.s: assets/%.abc
abccc -f s -l $(notdir $*)_music -o $@ $<
The worked examples in section 4 show the streams
abccc emits and the C that plays them; to hear a tune without a full
build, preview it as a runnable cartridge with abcrom
(section 5).
4. Worked examples
4.1. A single beep (no stream)
The direct helpers make a tone without any stream. Pick the feedback taps (so the poly counter oscillates rather than holding a DC level), select the octave band — which also enables the channel timer — set the pitch within it, then the volume; clear the volume to stop.
#include <lynx/lynx.h>
void main(void) {
snd_init(); /* timers + IRQ; channels start silent */
mikey_snd_taps (0, 1); /* feedback: a near-square tone (required) */
mikey_snd_octave(0, 4); /* clock band + enable the channel timer */
mikey_snd_pitch (0, 90); /* reload within the band */
mikey_snd_volume(0, 80); /* on */
/* ... wait ... */
mikey_snd_volume(0, 0); /* off */
for (;;) { }
}
Omitting mikey_snd_taps leaves the feedback register at zero, so
the channel emits a constant level and you hear nothing — a non-zero tap is
what makes it swing between +volume and -volume.
4.2. A one-voice melody
An ascending scale with an AHD instrument. The source:
T36 V100 R8 H12 K4
|: CDEF GABc :|
z4
The tempo T36 (36 player ticks per unit ≈ 150 ms at the
default ~240 Hz rate) gives each note time to ramp through its attack to full
volume; a very small T would cut every note off in its attack and you
would hear only faint clicks.
Compiled with abccc -f s -l theme_music -o theme.s theme.abc, the
stream is (annotated):
$93 $01 ; Mode: compact notes
$80 $00 ; Loop (count 0 = repeat)
$84 00 00 01 00 64 ; SetInstr: square tone, vol 0, ceiling V=100
$88 $01 <env> ; DefEnvVol 1 -> AHD volume envelope
$89 $01 ; SetEnvVol 1
$94 $24 ; SetDur 36 frames (1 unit x T36) — emitted before the first note
$24 $26 $28 $29 $2B $2D $2F $30 ; C D E F G A B c (compact notes)
$81 ; Do (loop back)
$82 $90 ; Pause 144 frames (z4 x T36)
$00 ; END
; env: 00 03 0D 08 0C 00 19 FC (loopStart, 3 segs: +R, hold, -K)
and the C simply plays it:
#include <lynx/lynx.h>
#include "theme.h" /* extern const unsigned char theme_music[]; */
void main(void) {
snd_init();
snd_play(0, theme_music);
for (;;) { } /* the IRQ advances the stream */
}
4.3. A looped two-voice tune
Compile two ABC tunes and start each on its own channel; both loop independently:
snd_init();
snd_play(0, bass_music); /* |: C,2 G,2 :| */
snd_play(1, lead_music); /* |: ceg c'eg :| */
4.4. An expressive instrument
A held note with a looping frequency envelope (vibrato) and a looping volume
envelope (tremolo) gives a singing, sustained voice. Define the envelopes with
DefEnvFrq/DefEnvVol, select them with
SetEnvFrq/SetEnvVol, then play a long note; the engine
re-applies the segment increments every interrupt for as long as the note sounds.
4.5. A sound effect
Percussion and noise come from the feedback taps and the integrate bit —
either inside a stream (ABC X/I, opcode
SetInteg) or directly:
mikey_snd_taps (2, 0x3F); /* wide tap set -> noisy timbre */
mikey_snd_integrate(2, 1); /* integrated wave */
mikey_snd_octave (2, 2);
mikey_snd_volume (2, 96); /* a short burst -> snare-like hit */
5. Auditioning with abcrom
The abcrom tool patches a compiled tune stream into a runnable
.lnx with no toolchain at test time: it drops the stream into a reserved
region of a pre-assembled template ROM (the snd engine plus a boot
harness), so a tune reaches a playable cartridge in milliseconds and plays on load in
any Lynx emulator. It is a pure file-to-file transform — you compile the stream
with abccc -f bin first, then launch the written ROM in your emulator
yourself:
abccc -f bin -o tune.bin tune.abc
abcrom -o test.lnx tune.bin
handy test.lnx
The template, its rebuild (make abcrom-template), the channel
mapping and every option are documented on the dedicated
abcrom tool page.
6. Sound effects (sfx)
The sfx layer is a batteries-included pack of ready-made sound
effects — a coin pickup, a laser, an explosion, a menu blip, a looping
alarm, and around fifty more. Each effect is a small, pre-built compiled event
stream played through the snd engine above; a game just calls a
sfx_<name>(ch) macro and the interrupt renders it. It adds no
new runtime code and no new stream opcodes — every effect is realised with
features the engine already has (frequency envelopes for pitch sweeps, volume
envelopes for decay, the LFSR taps and integrate bit for noise and timbre, and
multi-note runs for arpeggios). The sfx pack is to sound effects
what the standard font is to text: drop it in, or drop a layer down and build
your own when you want something bespoke.
sfx_* effect is a stream handed
to snd_play; power users can drop to snd_* or poke
mikey_snd_* directly.Include <lynx/lynx.h> (which pulls in
<lynx/sfx.h>) and fire an effect:
#define SFX_CH 3
snd_init();
sfx_jump(SFX_CH); /* fire-and-forget; the IRQ renders it */
...
sfx_coin(SFX_CH); /* replaces whatever was on the channel */
Each effect also exposes its stream symbol
(sfx_coin_data, …), so anything that takes a stream pointer
accepts it directly: snd_play(3, sfx_coin_data) is exactly what the
macro expands to.
6.1. Channels, one-shot and looping
Effects share Mikey's four channels with music. The convention is to reserve
one channel for effects — channel 3 by recommendation — and keep
music on 0–2, so an effect ducks only itself. There is no mixer or priority
engine: snd_play replaces whatever was sounding on the channel, so the
last effect on a channel wins, which is what most retro games do. The old sound is
faded out over a few ticks rather than cut instantly (§6.5), so firing the same
short effect repeatedly sounds like clean retriggers, not a click.
Most effects are one-shot: their stream ends on its own and the channel
goes idle. A handful are continuous by nature (sfx_alarm,
sfx_ambient_hum, sfx_engine, sfx_heartbeat)
— these loop and must be stopped explicitly:
sfx_alarm(3); /* starts the looping siren */
...
snd_stop_channel(3); /* silence it */
A game-pause still uses snd_pause() / snd_continue(),
which cover the effect channels too.
6.2. Linkage — pay only for what you use
Each effect is its own object file
(libraries/audio/sfx/sfx_<name>.s) archived as a separate member
of lib/lynx-audio.lib. The linker pulls a member in only if its symbol
is referenced, so calling sfx_coin(3) drags in
sfx_coin.o and nothing else; unused effects never reach the cart. A
one-shot stream is ~10–30 bytes of RODATA, and the audio library
is already on the cl65 auto-libs manifest, so no build-flag change is
needed.
6.3. Authoring your own
Effects are hand-authored as short ca65 sources using the SFX_*
macro vocabulary in asminc/lynx/sfx.inc, which hides the raw opcode
bytes. A whole effect reads declaratively:
.include "lynx/sfx.inc"
SFX_BEGIN coin ; exports sfx_coin_data
SFX_WAVE SQ ; square timbre (SQ / TRI / NOISE / METAL)
SFX_VOL 90 ; base loudness 0..127
SFX_DUR 4 ; compact notes, 4 frames each
SFX_DECAY 5, 12 ; volume fade to silence
SFX_ARP 72, 79 ; two rising notes
SFX_END
The macros cover timbre (SFX_WAVE, SFX_VOL,
SFX_FEEDBACK), pitch and shape (SFX_SWEEP,
SFX_DECAY, SFX_SWELL, SFX_SHIMMER), notes
(SFX_DUR, SFX_NOTE, SFX_ARP,
SFX_REST) and looping (SFX_LOOP_FOREVER …
SFX_LOOP_END). Because they emit only existing engine opcodes, an
effect replays byte-identically on the shipped player. Save the file under
libraries/audio/sfx/, add an extern + play macro to
include/lynx/sfx.h, and it links like the rest. Since “sounds
right” is the only real test, tune the indices and rates on the emulator or
hardware.
6.4. The catalogue
All 56 effects, grouped by role and one row each describing what it actually sounds like (all one-shot unless noted):
| Effect | Sound |
|---|---|
| Pickups, power, progression | |
sfx_coin | Bright square blip arpeggiating up (72→79) with a snappy decay — a classic coin-get ping. |
sfx_extra_life | Square arpeggio climbing five notes (60→76) into a longer held high note — a small triumphant fanfare. |
sfx_power_up | Square tone sweeping upward while arpeggiating through four rising notes — an energising boost. |
sfx_power_down | Soft triangle tone sliding downward and fading out — a deflating loss of energy. |
sfx_confirm | Short two-note square blip (67→74) with a quick decay — a crisp acknowledgement click. |
sfx_level_complete | Bright square arpeggio climbing six notes into a sustained high note — a short victory jingle. |
sfx_checkpoint | Gentle square two-note arpeggio (64→71) with a longer fade — a soft “saved” chime. |
sfx_secret_found | Square three-note arpeggio (61→66→73) — a bright, curious little lift. |
sfx_recharge | Fast five-note rising square arpeggio (60→72) — a quick trickle-up refill. |
sfx_charge_up | Square tone swelling in volume while sweeping upward over 90 frames — a building power-up drone. |
| Movement and platforming | |
sfx_jump | Square tone sweeping upward with a quick decay — a light, springy hop. |
sfx_double_jump | Faster, higher square sweep upward — a snappier second hop in mid-air. |
sfx_land | Short, low noise thud with a fast decay — a soft footfall landing. |
sfx_footstep | Very short, quiet, low noise tick — a single footstep tap. |
sfx_bounce | Square tone sweeping upward with a longer, springier decay — a rubbery bounce. |
sfx_bounce_wall | Bright metallic tone sweeping upward — a harder, clangier bounce off a wall. |
sfx_whoosh | Noise sweeping upward with a decay — a quick rush of air. |
sfx_cursor_move | Very short, high, quiet square tick — a subtle UI-cursor nudge. |
| Combat and damage | |
sfx_attack | Noise sweeping downward with a decay — a quick weapon swing or whiff. |
sfx_laser | High square tone sweeping sharply downward — a classic laser “pew”. |
sfx_explosion_small | Noise sweeping downward with a matching decay — a compact bang. |
sfx_explosion_large | Louder noise sweeping downward over more than a second — a big, rumbling boom. |
sfx_hit | Short, sharp noise thump with equal attack and decay — a solid impact. |
sfx_player_death | Falling five-note square arpeggio with a long fade — a defeated, sinking descent. |
sfx_enemy_death | Square tone sweeping downward — an enemy's quick dying whine. |
sfx_magic_cast | Shimmering triangle tone arpeggiating upward — a sparkly spell cast. |
sfx_magic_impact | Bright metallic two-note arpeggio (84→88) — a sharp magical strike. |
sfx_shield | Triangle tone that swells in and shimmers, then holds — a humming protective barrier. |
| Spawning, teleport, environment | |
sfx_spawn | Square tone sweeping upward while shimmering — a materialising pop. |
sfx_teleport | Shimmering triangle tone sweeping upward with a long fade — a warping teleport. |
sfx_fire | Sustained low noise with a slow decay — a crackling flame. |
sfx_wind | Noise sweeping upward slowly over 72 frames — a long gust of wind. |
sfx_thunder | Loud, low noise with a very long, rumbling decay — a distant thunderclap. |
sfx_water_drop | Triangle tone sweeping upward with a quick decay — a rounded plink of a falling drop. |
sfx_splash | Noise sweeping downward with a decay — a watery splash. |
sfx_bubble | Triangle tone sweeping upward with a decay — a rising bubble popping. |
| Objects, doors, items | |
sfx_door_open | Noise sweeping upward with a long decay — a door creaking open. |
sfx_door_close | Low noise thud with a decay and no sweep — a door slamming shut. |
sfx_switch | Metallic tone with a snappy decay — a mechanical switch flipping. |
sfx_button | High, very short square blip — a crisp button press. |
sfx_chest_open | Metallic four-note rising arpeggio (60→79) — a chest lid creaking open. |
sfx_item_equip | Metallic two-note arpeggio (67→74) — a quick equip clink. |
sfx_key_pickup | Metallic three-note rising arpeggio (72→84) — a bright key jingle. |
sfx_unlock | Metallic falling two-note arpeggio (55→48) — a lock releasing. |
sfx_crumble | Noise sweeping downward over more than a second — crumbling debris breaking apart. |
sfx_falling_rock | Five-note falling, scattering noise arpeggio — loose rocks tumbling down. |
| Menus and UI | |
sfx_menu_select | Short square blip with a snappy decay — a menu item selected. |
sfx_menu_back | The same short square blip, one octave lower — backing out of a menu. |
sfx_error | Falling three-note square arpeggio (55→50→45) — a buzzy “that's wrong” alert. |
sfx_typing | Very short, high, quiet square tick — a single keystroke click. |
sfx_countdown | Single square tone with a moderate decay — a steady countdown tick. |
| Continuous / ambient (looping) | |
sfx_alarm | Looping two-note square siren alternating pitch — a repeating alarm wail. |
sfx_ambient_hum | Looping low triangle drone — a continuous background hum. |
sfx_engine | Looping low square tone — a steady engine idle. |
sfx_heartbeat | Looping double-thump triangle pulse with rests between beats — a beating heart. |
sfx_game_over | Falling four-note square arpeggio with a long fade (one-shot, not looping) — a somber game-over close. |
The four looping effects (sfx_alarm, sfx_ambient_hum,
sfx_engine, sfx_heartbeat) run until
snd_stop_channel; every other entry, including sfx_game_over,
is a one-shot. Full recipes and design rationale are in
design/LYNX_SFX_LIBRARY_DESIGN.md; see
examples/mikey/sfxdemo.c for a playable sound test.
6.5. Stopping and retriggering — the fade-out
Whenever a channel is force-stopped — an explicit snd_stop() /
snd_stop_channel(), or snd_play() retriggering a channel
that's still sounding — the engine ramps that channel's volume down by a fixed
step every sound-timer tick until it reaches zero, then finishes the stop. From full
volume (127) that's at most 4 ticks, under 17 ms at the default 240 Hz
tick rate. snd_active() reports the channel busy for the whole fade, so
a caller polling it (or the busy-wait inside snd_play itself, when
retriggering) simply waits those few extra ticks before the new stream starts.
Before this, a forced stop set the volume register to zero on the very next tick
— instant, but audible as a click when it interrupted a note mid-sound. That
matters most for short, soft one-shots: sfx_water_drop's whole “plink”
lasts only ~50–60 ms (a SFX_SWEEP + SFX_DECAY over
12–14 ticks), so retriggering it faster than that window used to hard-cut the
tail every time. A natural end-of-stream (the stream's own SFX_END,
reached when its note duration runs out) is unaffected by this — it already
relies on the effect's own SFX_DECAY having faded the note out by then,
which is why well-tuned effects keep SFX_DUR at or above their decay
length.
A related quirk affects integrate-mode effects
(SFX_WAVE TRI, i.e. CONTROL bit 5). In integrate mode the
channel's DAC output register ($FD22, AUDxOUTVAL)
accumulates rather than being reloaded each tick, and the engine never
otherwise writes it — so a finished note can leave the output railed near
±full scale. A long integrate effect walks that offset back into range
on its own, but a short one-shot could not swing far enough to be audible
when replayed, leaving sfx_water_drop and sfx_bubble
seemingly silent on repeat while longer integrate effects
(sfx_power_down, sfx_teleport) were fine. The engine now
clears $FD22 whenever it fully reprograms an integrate-mode channel,
so every note starts from silence. Square (non-integrate) channels reload the DAC
from hardware every tick and are left untouched.
7. Reference
The engine API (snd_init, snd_play,
snd_stop, snd_stop_channel, snd_pause,
snd_continue, snd_active) and the direct helpers
(mikey_snd_octave, mikey_snd_pitch,
mikey_snd_taps, mikey_snd_integrate,
mikey_snd_volume) are documented in the
function reference and declared in
lynx/lynx.h. The stream format, opcode map and ABC grammar are
specified in full in design/LYNX_SND_ENGINE_DESIGN.md; the
abccc and abcrom tools live under
tools/ and build into bin/.