HandyMusic engine

HandyMusic is a script-driven, macro-instrument BGM + SFX sound driver for the Atari Lynx by Osman Celimli, ported into lynxcc as an opt-in runtime library (lib/lynx-handymusic.lib, <lynx/handymusic.h>). Instruments and sound effects are byte-code envelope scripts, music is four parallel track scripts, all compiled from text by the hmcc host tool. It is a heavier, more capable alternative to the snd engine and its sfx catalogue — a game opts into one engine or the other, never both. This page covers how the ca65 driver is laid out, the reserved memory model, the VBL tick, the C API, and the worked example. The script languages live on the hmcc page and are not repeated here.

1. What HandyMusic is

HandyMusic plays four independent track scripts across Mikey's four audio channels. Each track references instruments — small envelope programs that shape a channel's waveform, volume and frequency over time — and can fire sound effects, which are the same kind of envelope script but requested on demand and slotted into a channel by priority. Everything is authored as text and compiled to compact byte-code blobs by hmcc; the driver walks those blobs once per frame and writes Mikey's registers. Writing those scripts from a piece of sheet music — pitches to nXo tokens, note values to ticks — is covered in Encoding sheet music for HandyMusic.

Because it carries a full instrument model, per-channel frequency and volume envelopes, loop/pattern control and a priority mixer, HandyMusic is larger than the snd engine. The two are mutually exclusive by design: link one library or the other. Reach for HandyMusic when you want its instrument/envelope expressiveness and pattern reuse; reach for snd when a lighter compiled-stream player is enough.

This port covers music, SFX and PCM samples. PCM is RAM-sourced — short 8 kHz one-shots streamed to channel 0 by a timer-3 interrupt (section 6).

2. Building against the engine

HandyMusic needs two things at link time: its library, and a memory config that reserves the data regions. The library is pulled in automatically — it is on the SDK auto-library manifest, so any program that references a handymusic_* symbol drags the driver out of lib/lynx-handymusic.lib with no -l flag. The config is the one thing you must select explicitly, exactly as the collision demo selects lynx-coll.cfg:

#include <lynx/handymusic.h>
...
cl65 -C lynx-handymusic.cfg -o game.lnx game.o data.o

cfg/lynx-handymusic.cfg is the stock Lynx cart layout with MAIN shrunk so that two fixed regions sit above the C stack, reserved for the compiled song and SFX blobs (section 3). The engine installs its own 60 Hz update on the VBL interrupt chain, so the VBL timer must be running before you play anything — call gfx_init (which enables the VBL interrupt) and CLI() first.

3. The reserved data regions

hmcc emits two blobs: a song (.mus) and a SFX block (.sfx). lynx-handymusic.cfg reserves a fixed base for each, exported as __HMMUS_START__ and __HMSFX_START__, in the RAM just below the hardware page and above the stack:

MAIN code + data C stack (grows down) SFX blob __HMSFX_ START__ song blob __HMMUS_ START__ $0200 $AE00 $B000 $C038
The reserved regions sit above the stack, so the heap can never grow into them.

3.1. Why the data is absolute

hmcc bakes absolute pointer tables into each blob at a base address you hand it on the command line (see hmcc §5). The song header at __HMMUS_START__ holds absolute track and instrument-table pointers; the SFX block holds absolute script addresses. The blob is therefore only valid when it lives at the base it was compiled for. That is the whole reason the config reserves fixed bases: build the blobs at $AE00/$B000 and place them there. A relocatable object mode for hmcc is deliberately out of scope.

3.2. Copying the blobs at startup

The blobs ride in the cart as ordinary resident data (a small .incbin glue file). The Lynx boot loader copies the main image contiguously and the stack sits directly above MAIN, so the reserved regions cannot themselves be part of the loaded image; instead the program copies each blob to its base once, at startup, before playing:

memcpy ((void *)0xB000, hm_music_data, music_len);   /* __HMMUS_START__ */
memcpy ((void *)0xAE00, hm_sfx_data,   sfx_len);     /* __HMSFX_START__ */

After the copy, every pointer hmcc baked in resolves and the song is ready to play. The copies are one-time; the regions are otherwise untouched by the runtime.

4. Channels, the VBL tick and decoding

HandyMusic keeps per-channel state for all four Mikey channels: a script decode pointer, a priority, base and offset frequencies with their per-frame adjustments (16.8 fixed point), a volume with its adjustment (8.8), loop stacks, and note-off pointers. Each frame the driver runs HandyMusic_Main, which for every channel decodes any due script commands, advances the frequency and volume envelopes, computes the final divider and writes Mikey's timer, volume and control registers — skipping the register write when the frequency has not changed, to avoid clicks.

The library owns its own tick. Rather than making the game call Main from its own handler, the driver registers HandyMusic_Main as an interruptor on the VBL IRQ chain, so it runs once per vertical blank as soon as the VBL interrupt is enabled. A game therefore only ever calls init / play / stop / pause; it never touches Main. Priorities arbitrate the four channels between music notes and sound effects: a higher-priority request wins a busy channel, and a note or effect that sets its priority to zero is silent. Reserve distinct priority bands for notes versus effects so handymusic_stop_sfx stays useful.

5. The C API

The public surface is <lynx/handymusic.h>. Single-byte arguments pass in the accumulator, matching the driver's assembly entry points exactly.

5.1. Playback control

FunctionEffect
handymusic_init (void)Initialize the engine and audio hardware (stereo on, all channels idle). Call once, after the VBL interrupt is running.
handymusic_play_music (void)Start the song resident at __HMMUS_START__. Stop the current song before loading another.
handymusic_stop_music (void)Stop the song, freeing the channels it still controls. A note whose priority no longer matches its track is left to ring out; use handymusic_stop_all for a hard stop.
handymusic_play_sfx (unsigned char n)Queue effect n (an SFX_* index from the hmcc .equ) to start next frame.
handymusic_stop_sfx (unsigned char prio)Stop the first sound (effect or note) whose priority equals prio.
handymusic_stop_all (void)Force-stop every track and effect, freeing all four channels.
handymusic_pause (void) / handymusic_unpause (void)Mute and restore all channels. Both are double-call safe.
handymusic_play_pcm (buf, len)Play an 8 kHz PCM sample from a RAM buffer straight away (section 6).
handymusic_register_pcm (num, buf, len)Register a sample in slot num so the song's “play sample” command can trigger it.
handymusic_pcm_playing (void)Nonzero while a PCM sample is streaming; zero once channel 0 is handed back.

5.2. Pointing the driver at the SFX tables

hmcc emits an .equ file with the absolute addresses of the SFX block's three tables (low-byte addresses, high-byte addresses, priorities) and one SFX_* index per effect. Before the first handymusic_play_sfx, point the driver at those three tables. They are contiguous at base, base+count and base+2×count, so the helper macro takes the three addresses directly:

handymusic_set_sfx_tables (HandyMusic_SFX_ATableLo,
                           HandyMusic_SFX_ATableHi,
                           HandyMusic_SFX_PTable);

The three underlying pointers (handymusic_sfx_addr_lo, handymusic_sfx_addr_hi, handymusic_sfx_prio) live in zero page and are exported for direct use as well.

6. PCM sample playback

The original driver streamed single-channel 8 kHz PCM off the cart via BLL filesystem primitives that do not exist in lynxcc. This port keeps the same timer-3 8 kHz interrupt and channel-0 capture but makes PCM RAM-sourced: a sample is an ordinary resident byte array (signed 8-bit), and playback runs off a plain pointer and length instead of a cart stream. Long PCM is a poor trade on the Lynx regardless; this suits the short one-shots PCM is actually good for — drum hits, stingers.

Call handymusic_play_pcm (buf, len) to play a buffer immediately. The sample borrows channel 0 from the music engine and the interrupt hands it back automatically when the buffer is exhausted; handymusic_pcm_playing() is nonzero in the meantime. To let a song trigger samples, register them first with handymusic_register_pcm (num, buf, len): the music “play sample” command carries a sample number that indexes this small registry (up to eight slots), so sample 0 in a track plays whatever the game registered as slot 0. An unregistered slot plays nothing. The handymusic_disable_pcm variable is a runtime mute for the whole PCM path; music and SFX are unaffected.

The interrupt is installed as a second entry on the shared IRQ chain (like the engine's VBL tick), so it coexists with gfx page-flipping and leaves set_irq free for the game.

7. Worked example: handymusic.c

examples/mikey/handymusic plays Osman Celimli's HandyMusic demo song and lets you trigger its effects. Its Makefile shows the whole flow: run hmcc to compile the SFX and track scripts to blobs at $AE00/$B000, turn the SFX .equ into a C header, .incbin the blobs, and link with -C lynx-handymusic.cfg. At runtime it copies the blobs to their bases, points the driver at the SFX tables, handymusic_init(), registers two short PCM blips as samples 0 and 1 (so the demo song's own sample commands play them), handymusic_play_music(), then fires effects on button A and a PCM blip on Option 1. It is the reference for wiring the engine into a project.

8. License

The ca65 driver and the <lynx/handymusic.h> surface are a derived work of Osman Celimli's HandyMusic driver, and so — like the hmcc tool — carry Celimli's original “completely free to use and modify” grant rather than the MPL that covers most of the fork. That grant, the attribution to Osman Celimli, and the list of derived files are reproduced on the Licenses page.