Skip to Content

From the Machine to Your Speakers: Sound in an Emulator

Here is a puzzle for you. The Next’s sound can change on any of 28 million clock ticks a second. Your computer’s sound card wants 48,000 numbers a second, evenly spaced, delivered on time, every time. And the emulator in between runs the machine in bursts: it races through a whole frame in a few milliseconds, then sits idle until the next one is due, and now and then it stops dead at a breakpoint for as long as you like. So how does anything smooth ever come out of the speakers?

You hear the answer every time you run a program in Klive, and you notice it only when it goes wrong. A sound that clicks at every frame, a tone that rattles with notes nobody wrote, a delay between a key press and its beep, an echo of old sound after the debugger stops: each of these is a decision made somewhere on the way from the machine to your ears. This last sound chapter is about those decisions, and I will tell you which ones I am proud of and which ones are compromises.

Everything before was the Next. This chapter is Klive. It builds on The Mixer: One Sum, Three Outputs, which tells how the Next adds its sources and builds its three outputs, and on the background chapter How a Computer Makes Sound for samples, sample rates and aliasing.

The road ahead

We start with the two clocks that never agree, the machine’s and the sound card’s, and the small piece of arithmetic that keeps them in step across every frame. Then we look at what a sample actually is: a moment, or a window? That choice decides whether a high beeper note plays clean or grows notes of its own, and I will show you both. Next comes Klive’s mixer: how it adds the sources into one stream, and which of the Next’s three outputs that stream plays. A short stop at the beeper’s DC filter follows. Then the samples travel: out of the core, across to the audio thread, into a queue, and on to the sound card. The queue is the hero of the second half, the part I would ask you to remember, because it is what turns a machine that runs in bursts into sound that flows. We see what it does when the machine stops, steps or replays, how Klive tests its own sound, and we end with the whole sound system in one picture.

The numbers are for the Next’s 28 MHz master clock, 128K timing (a frame of 456 × 311 positions, 20.26 ms) and a sound card at 48,000 samples a second. Klive plays at your sound card’s own rate, so yours may be 44,100 or another; the arithmetic is the same. Levels are in the units of the Next’s mixer. The counts, the spectra and Klive’s mix of the beeper are captured from Klive’s emulated Next; the hardware’s sum beside that mix is worked out from the hardware’s rules; the queue is Klive’s audio code run on a timeline.

Two clocks that never agree

A sample every 28,000,000 ÷ 48,000 = 583.33 master clocks. A frame is 456 × 311 positions of the 7 MHz dot clock, four master clocks each: 567,264 clocks. Divide one by the other and a frame holds 972.45 samples. Not 972, not 973. The sound card does not care about frames, of course; it wants its 48,000 a second whatever the machine is doing.

So Klive keeps the time of the next sample in master clocks, multiplied by the sample rate so that it stays a whole number, and it never starts that count afresh. When a frame ends, the schedule moves back by a frame’s length and carries on. I think of it as the leap-year rule: a calendar cannot have 365.24 days in a year, so most years get 365 and now and then one gets a day more, and nobody’s birthday drifts. Here most frames get 972 samples and now and then one gets 973. The next frame’s first sample comes 583.33 clocks after the previous frame’s last one, wherever that falls:

+319+903+1,486frame endsnext framea sample every 28,000,000 ÷ 48,000 = 583.3 clocks; the numbers are clocks into the new framesamples in each of 40 frames, capturedgrey: 972, red: 973; the average, 972.45, is exact over every run of frames
Samples across a frame’s end. The schedule runs on, so the first sample of the next frame keeps its distance from the last one, and each frame carries 972 or 973 samples, 972.45 on average.

Why does that fraction matter so much? Well, suppose each frame restarted its samples at the frame’s first clock. Then every frame would throw away its 0.45 of a sample: 22 samples a second, gone. The sound would play a little slow, the queue would slowly run dry, and at every frame’s end two samples would sit a fraction too far apart, a tiny click 49 times a second. With the fraction carried, every run of frames holds within one sample of the exact total, as the capture shows. Of all the code on the way to your speakers, this is the smallest piece I would defend the hardest: a few lines of integer arithmetic, and a whole class of clicks never happens.

A moment or a window?

The next question sounds philosophical, but I promise you it is not. When Klive takes a sample, should it take the level at that moment, or the average over the window since the last sample?

For the DACs and the Pi it hardly matters: their level changes only when a new value arrives, and a sample takes the value standing at its moment. For the beeper and the AY chips it matters a lot. A beeper edge or an AY tone edge can fall anywhere between two samples, and here is what each choice makes of it:

the wave9,358 HzpointHDMIaveragedjack, speakergrid: one sample window, 1/48,000 s
A 9,358 Hz beeper tone, sampled two ways. Point sampling moves each edge to the next sample; averaging the window gives a sample that an edge cuts the share of the window the wave spent high.

Point sampling moves every edge to the next sample, up to 21 µs late. Averaging keeps each edge’s position in the size of the sample it cuts: an edge a third of the way into a window gives that sample two thirds of the high level. Klive averages the beeper’s EAR and MIC bits over each window, weighted by the time they spent high, and the AY chips’ outputs over the chip ticks in the window. That is the default, for the jack and the speaker. For HDMI it point-samples, because the Next’s HDMI audio really does take the sum’s value at each of its 48,000 moments, as the mixer chapter’s HDMI audio explains.

You can hear the difference. A square wave is not one tone: it has harmonics at three, five, seven times its pitch, and a 9,358 Hz tone has its fifth harmonic at 46,791 Hz, far above what 48,000 samples a second can hold. Point sampling folds it back down, to 48,000 − 46,791 = 1,209 Hz, a low growl the program never asked for. Here are the two captured:

0-20-40-60pointHDMI0-20-40-60averagedjack, speakeralias 1.2 kHzthe tonealias 19.9 kHzalias 1.2 kHzthe tonealias 19.9 kHz0 kHz4 kHz8 kHz12 kHz16 kHz20 kHz24 kHzdB below the tone
The same beeper tone captured through HDMI (point sampling) and the jack (averaging), as spectra. Point sampling adds an alias at 1.2 kHz; averaging all but removes it. The alias at 19.9 kHz, the third harmonic folded back, survives both.

Averaging takes the 1,209 Hz alias down to half a per cent of the tone. But let me warn you not to think of it as a perfect filter. An average over one window is a rough one: it nearly removes what lies close to 48,000 Hz and its multiples, and much less of what lies between. The third harmonic, 28,075 Hz, folds back to 19,925 Hz, and the average only halves it. Luckily that one sits at the very top of human hearing, where most of us hear nothing at all. A truly clean result needs a real low-pass filter before sampling, which costs far more than an average, and the beeper rarely plays that high. Klive chose the average: cheap, exact in its timing, and good where it counts. I would make the same choice again.

One stream, three outputs

The Next has three outputs, the audio jack, the internal speaker and HDMI, all fed from one sum. Your computer has one pair of speakers. So Klive makes one stream of samples, at the rate the IDE’s audio runs at (48,000 a second by default), and hands it to your computer’s sound card. That stream plays one of the Next’s outputs: the one chosen under Machine › Sound › Output (also in Settings › Emulator), the audio jack unless you choose otherwise.

Which point of the chain should a sample stand for? The hardware’s sum is a number inside the FPGA; what reaches your headphones is that sum after the converter and the circuit that removes its constant level. Klive’s samples stand for that later point, the sound after the capacitor, which is why they move around zero. I find that the honest choice: you are listening, after all, not probing the FPGA.

Each time it needs a sample, Klive’s mixer asks every source for its level at that moment and adds them in the hardware’s units, with three changes that play the capacitor’s part:

  • The DACs and the Pi are counted from their resting levels: a DAC channel at $80 and the Pi at 512 add 0. Silence is 0 instead of 1,536.
  • The beeper’s EAR and MIC pass through a filter that removes their constant level slowly (a constant falls to about a third in a little over a tenth of a second), as the capacitor after the jack’s converters does. A beeper wave ends up moving around zero. The next section has the details.
  • The AY chips are added as they are, from 0 upwards.

The sum is then multiplied by 12.8 and becomes a signed 16-bit sample, −32,768 to 32,767. Why 12.8? Because it gives Klive the jack’s headroom. The jack plays the sum cleanly up to 4,095, which is 2,559 above the silent 1,536; Klive maps 2,559 units to 2,559 × 12.8 = 32,755, just inside its largest sample. So every mix the jack plays cleanly, Klive plays without loss, nine AY channels at full volume and the beeper included. If you ask me, that is the number that matters most in this section: it means the advice of the mixer chapter’s Headroom holds in Klive word for word.

Each of the three outputs is played as the hardware builds it, from the same sum:

  • Audio jack: the sum’s lowest 12 bits. A mix past 4,095 wraps around as it does on the real jack (the mixer chapter’s Headroom): Klive works out the hardware’s sum beside its own mix, and takes 4,096 off its sample each time the sum passed 4,096. Below the limit, the jack’s sample is exactly the mix described above.
  • Internal speaker: the left and right jack values added into one mono mix, on both sides of the stream, multiplied by 6.4 (the speaker’s room above its silent 3,072 is twice the jack’s). Bit 4 of the Peripheral 3 Setting register, NextReg $08, off silences it. With bit 6 of the Peripheral 2 Setting register, NextReg $06, set, it plays only the beeper, EAR at 1,024 and MIC at 256: as loud as the beeper is on the jack, which then no longer carries it. Klive follows the later boards’ speaker; the earliest boards bias the speaker’s word for their transistor.
  • HDMI: the whole sum, never wrapping, multiplied by 7.34 so that even every source at its largest (4,462 above silence) fits. Like the hardware, it takes the sum’s value at each sample’s moment: the beeper’s level and the AY chips’ output at that instant, not their average since the last sample (the point sampling of the previous section). Bit 2 of the Peripheral 4 Setting register, NextReg $09, silences it.

The choice belongs to Klive, not to the machine: it survives a reset, and switching it never restarts the machine.

Klive’s tape deck feeds the Next’s EAR socket: its level passes the machine’s own input stage (the debounce that drops pulses under about 1.14 µs, the relaxation that turns a level held at 1 into 0 after about 1.15 ms), and the result reaches port $FE bit 6 and the MIC line, so a loading tape is heard at MIC’s level as on the real machine.

What Klive leaves out are three small differences that come from its way of removing the constant level. I would rather tell you about them than have you find them. None of them can be heard, since a constant level never is:

  • Only the beeper is filtered. The real capacitor removes the constant level of the whole sum. Klive filters the beeper and counts the DACs and the Pi from their fixed resting levels, but leaves the AY chips as they are: an AY channel held at a fixed volume stays in Klive’s samples as a steady offset, where the real circuit would let it fade to zero. Filtering the whole sum instead would cost room: a sudden step passes a filter at full size, so the samples would reach Klive’s limit sooner.
  • How fast the constant level fades. Klive’s filter is tuned to about a tenth of a second; the values of the real board’s resistor and capacitor are not part of the machine’s design, so the real jack may fade faster or slower.
  • HDMI’s constant level. The Next’s HDMI samples carry the silent level, 1,536 × 4 = 6,144 in every word; Klive’s HDMI output is centred on zero like its other outputs.

The beeper’s DC filter

One more thing happens to the beeper before it reaches the mix. The Next adds only levels from 0 upwards, so a beeper that is switched on adds 512 units and stays there; the capacitor after the hardware’s converters removes that constant level before your speaker ever sees it. Klive does the same job with a high-pass filter at 1.4 Hz on EAR and MIC: far below any pitch, so every note passes untouched, but a level that stays put drifts back to zero over a few tenths of a second. Here is the beeper switched on from silence, as the hardware sums it inside the FPGA and as Klive mixes it:

the hardware’s digital sum, inside the FPGA (worked out from the rules)01,5362,048Klive’s mix (captured): the sound after the jack’s capacitor−2560+256+5120 s0.1 s0.2 s0.3 s0.4 s
The beeper switched on from silence, at two points of the chain. Top, the hardware’s digital sum inside the FPGA, worked out from the rules: 1,536 and 2,048, all of it above zero. Bottom, Klive’s mix, captured from the emulated machine, which stands for the sound after the jack’s capacitor: the same 512-unit square, sliding down to centre on zero within about a tenth of a second. The real jack’s output slides to zero in the same way.

So the two traces do not disagree: they show the sound before and after the capacitor, and Klive’s is the one you hear. The constant level and its slow drift are far below any pitch. A waveform drawn from Klive’s samples sits around zero, which is why the captures in these sound chapters are drawn about their middle level. I like this figure because it settles an argument before it starts: two pictures that look different, and both are right.

From a frame to the sound card

The core collects a frame’s samples, left and right, as the frame runs. When the frame ends, they set off:

emulatedNexta frame at a time;a sample every583 clocksa frame’ssamples972 or 973 pairs,when theframe endsrendererone block ofnumbers, handedover, not copiedworkleta ring of 8 frames;3 held back:about 60 mssound cardpulls 512samples every10.7 msthe emulator’s thread: the core (WebAssembly) and the rendererthe audio thread and the card
The way out. A frame’s samples leave the core when the frame ends, travel to the audio thread in one block, wait in the worklet’s queue, and are pulled by the sound card at its own pace.
  1. The emulator’s thread takes the frame’s 972 or 973 sample pairs from the core.
  2. The renderer copies them into one block of floating-point numbers, scaled by your volume setting, and hands the block to the browser’s audio thread without copying it again. That detail matters more than it looks: a plain list of 1,900 numbers every frame made garbage the browser had to clean up, and the clean-up could stall the frame loop long enough to starve the sound.
  3. On the audio thread, an audio worklet, a small piece of code the browser runs right next to the sound card, puts the block in its queue.
  4. The sound card pulls samples from the worklet in callbacks of 512, about every 10.7 ms at 48,000 a second (as measured on a Mac), whatever the emulator is doing at that moment.

A queue against the jitter

Now look at the timing. Frames arrive every 20.26 ms, but never exactly then: the emulator’s timer, the browser and the rest of your computer push each one a few milliseconds earlier or later. The sound card, meanwhile, pulls every 10.7 ms like clockwork. If the queue holds only what the last frame brought, sooner or later the card asks for samples that have not arrived yet. So the worklet keeps a cushion.

I call this queue the water tower. A town’s pump fills its tower in bursts, whenever it runs; the taps below draw from it at whatever rate people open them, and the pressure stays steady because the tower holds more than any single burst. Frames are the pump, the sound card is the taps, and the rules below decide how full the tower is kept:

  • It holds a ring of eight frames’ worth of samples.
  • Before it plays, at the start and after it has run dry, it holds back three frames: about 60 ms between the machine and your ears. Why three? With one, the queue fell to a few milliseconds just before each frame arrived; with two, it still ran dry now and then, and every dry spell faded out and back in, a click every few seconds. Three keep a good 25 ms in hand at the lowest point, even when frames arrive 10 ms late.
  • A lone frame is the exception: one frame and then nothing, as when the debugger steps the machine. Once two frames’ worth of time has passed with nothing new, the worklet plays what it has instead of waiting for ever. Two, not one, because the card asks every 10.7 ms, so two callbacks, more than a frame’s time, often pass between two frames of a machine that is keeping up perfectly well.
  • If it ever holds more than five frames, because frames came in faster than they were played, it drops the oldest. I would rather skip a little than let the delay grow: a late beep feels broken in a way a tiny skip never does.
  • When it runs dry, it does not cut to zero, which would click. It fades the last level out over a few milliseconds, and when sound arrives again it fades in over about 2 ms.

Here is the queue at work, its rules run over 1.2 seconds, with a stretch in the middle where the machine delivers a frame only every 30 ms, as a busy debugging session can:

0 ms20 ms40 ms60 ms80 ms100 msa frame every 30 msqueuedsoundplaying0.0 s0.2 s0.4 s0.6 s0.8 s1.0 s1.2 s
How much sound waits in the queue, by the worklet’s own rules. In step with real time it rides between about 34 and 53 ms; when frames come too slowly it drains, runs dry and plays in gaps, then refills once the machine is back in step.

Look at what the slow stretch sounds like: gaps, not a stutter. Once the water tower is dry, the worklet waits again, as it did at the start, before it plays, so you hear short pieces of correct sound with silence in between, rather than a sound that stops and starts with every sample. To my ear, gaps are by far the lesser evil. So if your program sounds choppy only while the debugger is busy, now you know why, and you know it is not your program.

When the machine stops

The emulator does more than run. Here is what you hear in each of its other moods, and in every one of them the rule, as I see it, is the same: never play a sound at a moment it does not belong to.

  • Paused or stopped, at a breakpoint or by your hand: Klive suspends the sound card’s audio and empties the queue. Nothing old is left to play when you go on, so you never hear an echo of the moment before the stop.
  • Running under the debugger: while the machine keeps up with real time, you hear the sound as usual. When it falls behind, as when the debugger runs it an instruction at a time, or it waits for the SD card, you hear the sound in gaps.
  • Stepping: only a finished frame sends sound, and a single step rarely finishes one, so stepping is silent. A lone frame that arrives with nothing after it is not kept waiting for ever: once two frames’ worth of time has passed, the worklet plays what it has.
  • Reverse debugging and replays: to show you an earlier moment, Klive runs the machine again from a saved state. Those frames reach neither the screen nor the speakers. They are history being retraced at whatever speed the computer can manage, and playing them would be sound from the past at the wrong pace.
  • Rendering a recording to a video file: the machine runs as fast as it can, so the live sound is muted, and every sample goes to the recording instead, which plays it later at the right speed.

Testing it, and reading the code

All of this chapter has been Klive, so this section is short: how Klive makes sure its sound is right, and where each piece lives.

The sound is tested like the rest of the machine. The Next’s test harness runs the real core and records the samples of every completed frame, exactly as the IDE gets them. I trust a measurement far more than my ears here, so the tests check what can be measured: a tone’s pitch from its edges, a level’s size in mixer units, which side a channel lands on, the samples each frame carries. Every waveform in the sound chapters comes from such a test, which first checks the facts its chapter states and only then writes the capture the figure is drawn from. The worklet has tests of its own for its queue.

If you want to read the code yourself, and I hope you do, here is where it lives:

WhatWhere
The sample schedule, averaging, the DC filter, the outputssrc/emu/machines/zxNext/wasm/zxnext/zxnext-audio-mixer.c
The sum, the resting levels, the factors and the limitthe same file
The jack’s wrap and the beeper-only switchthe same file
The sound output settingsrc/common/settings/next-audio-output.ts
The DACs’ and the Pi’s levelszxnext-dac.c, zxnext-pi-i2s.c in the same folder
The tape deck and the EAR input stagezxnext-tape.c in the same folder
The beeper’s time-weighted EAR and MICzxnext-beeper.c in the same folder
The AY chips’ average over a sample’s windowzxnext-psg.c in the same folder
A frame’s samples to the renderer and the recordersrc/renderer/features/emulator/audioFrameRendering.ts
The audio context and the block handed to the audio threadsrc/renderer/features/emulator/AudioRenderer.ts
The queue: hold-back, trimming, fadingsrc/renderer/features/emulator/Sampling.worklet.js
Frames paced to real time, and what a replay sendssrc/emu/machines/MachineController.ts
The scenes behind the sound chapters’ figurestest/zxnext-hw/audio/next-audio-scene.test.ts

What to take home

Time to step back and look at the whole sound system, from the first chapter to this one:

beeper, EAR, MICand the tapethree AY chipsbehind TurboSoundfour 8-bitDACsthe RaspberryPi’s audioone mixerleft sideright sideaudio jackinternal speakerHDMIback to the PiKlive: one of the outputs, 48,000 samples a second,to your computer’s sound card
The Next’s sound system as the sound chapters told it, and the last step, Klive’s.

On the Next, four kinds of source make sound. The beeper is two bits of port $FE, with the tape on the same line. Three AY chips play tones, noise and envelopes by themselves, and TurboSound puts all three behind the 128K’s two ports. Four 8-bit DACs play whatever numbers a program, the CTC, the DMA or the Copper writes, on the ports of six old sound cards. The Raspberry Pi streams samples over I2S, and can even play a tape into the Next’s EAR input. One mixer adds them all, a left and a right side, and its sums leave through the audio jack, the internal speaker, HDMI and back to the Pi.

Klive plays one of those outputs, the one you choose, in one stream of samples that stand for the sound after the jack’s capacitor: the DACs and the Pi counted from their resting levels, the beeper’s constant level filtered away, and the sum multiplied by 12.8, so that every mix the jack plays cleanly, Klive plays without loss. It takes a sample every 583.33 master clocks and carries the fraction from frame to frame, so a frame holds 972 or 973 samples and none is ever lost. It averages the beeper and the AY chips over each sample’s window, which keeps a high beeper note from growling, and point-samples HDMI as the real one does. Each finished frame’s samples travel to an audio worklet, whose queue, the water tower, holds three frames back, about 60 ms, rides about 34 to 53 ms ahead of your ears, trims beyond five frames, and fades rather than clicks when it runs dry. Stop the machine and the queue empties; replay history and nothing plays.

And that is the whole journey, from a bit flipped by a Z80 to the cone of your speaker. Go and make some noise.

Last updated on