Radio from scratch · Chapter 11

From numbers to speakers

Before you startThis chapter uses:

The demodulator hands us numbers: about 48 000 per second, each saying where the speaker cone should be. Getting them to come out of the speakers smoothly, for hours, turns out to involve four practical problems that every radio, phone and video call has to solve: (1) the dongle's clock and the sound card's clock slowly drift apart, (2) their sample rates (say 50 000 vs 48 000 Hz) don't match, (3) AM and SSB volume swings wildly with signal strength, and (4) an empty two-way channel blasts loud hiss between transmissions. None of them is hard, but each one, ignored, makes the radio sound broken.

Two clocks that never agree

The dongle decides how fast samples arrive, using its own crystal (28.8 MHz): a sliver of quartz that vibrates at one extremely steady rate, the chip's metronome. The sound card decides how fast they're played, using a different crystal. No two crystals are exactly alike: they differ by some parts per million (ppm). 50 ppm sounds like nothing, but it means that every hour, one side gets 180 ms ahead of the other.

Two crystals differ by 20 ppm (20 millionths). After four hours, how far apart are the two clocks, in milliseconds?

4 hours = 14,400 s, and 20 × 10⁻⁶ × 14,400 s = 0.288 s = 288 ms. Small differences, given hours, become audible.

Chapter 8's audio cushion (↩) absorbs this, for a while. Here's the cushion over four hours:

If the dongle runs fast, sound piles up faster than it's played, until the queue is more than 600 ms long; then our player drops a chunk, a barely noticeable skip. If the dongle runs slow, the queue drains until it's nearly empty; then the player waits to rebuild the cushion, a short silence. Either way, one small glitch every hour or two. Professional systems avoid even those by measuring the drift and stretching or squeezing the sound by a tiny amount to match (another use of the rate conversion below).

Playing at a different rate

Our sound comes out at whatever rate the last decimation gave (chapter 7): for FM at 2.4 MS/s, exactly 50 000 samples per second (chapter 7's 300 000, then one in 6 once chapter 9 has turned the station into sound). The sound card might run at 44 100 or 48 000. So someone has to produce new samples between the ones we have, at different moments: resampling.

The radio's audio is 50,000 samples per second and the sound card plays 48,000. For each sample it plays, how far does the player move through ours (in our samples, three decimals)?

50,000 / 48,000 ≈ 1.042 of our samples per output sample, landing between samples most of the time: that's why it has to guess values in between.

The simplest way to guess a value between two samples is to draw a straight line between them and read off the height. It's not exact, since the real sound curves, but the closer together the samples are, the smaller the error: with 10 samples per wave it's under 5%, with 50 it's 0.2%. Our audio has well over 10 samples per wave for every note that matters, and browsers use smarter curves than straight lines. In this site's receiver, the browser's Web Audio system does the resampling: we tell it our rate, and it converts.

Automatic volume

FM's output level depends only on how loud the music is (chapter 9), so a fixed volume works. But AM and SSB get louder and softer with the signal strength (chapter 10), which changes with distance, weather and every passing bus. A receiver therefore adjusts its own volume: automatic gain control (AGC).

Ours follows the loudest recent peak and divides by it. When the sound gets louder, it reacts instantly (the "attack"), so a sudden loud signal never blasts your ears. When the sound gets quieter, it raises the volume slowly (the "release"). Make the release very short and listen to the result in the picture: the quiet passages get pumped up to full volume right away, so loud and quiet parts of speech end up equally loud, and the background noise "breathes" up in every pause. Make it very long and a fade stays quiet for seconds. Around half a second is a common compromise.

Squelch: silence between transmissions

Two-way radio (airport towers, police, taxis, hams) is silent most of the time, and automatic volume (section 3 above) makes that silence worse: when nobody is talking, AGC sees the quiet background fuzz and turns the volume all the way up! A receiver tuned to an empty channel then plays a loud hiss for minutes between every short message. A squelch mutes the sound whenever the channel is too weak to contain a transmission:

The squelch measures the channel's strength every 20 ms (the average length² of its arrows, in dB: chapter 4's power). Above the threshold, the sound is on; below it, muted. Two details make it pleasant to use:

Set the threshold too low and noise gets through; too high and the start of weak messages is cut off. Real radios have a squelch knob for exactly this.

Between the demodulator and the speaker: a cushion absorbs two clocks' drift, resampling converts the rate, AGC evens out the volume, and a squelch mutes the empty channel.

Why does a tiny clock difference become a glitch?
  1. The dongle delivers samples at its rate f; the sound card plays them at f · (1 + ε), with ε a few parts per million.
  2. After t seconds, the card has played ε · f · t more samples than arrived.
  3. That's ε · t seconds of sound, taken from the cushion.
  4. At 50 ppm and one hour: 50 × 10⁻⁶ × 3600 s = 0.18 s.
  5. A cushion of a few hundred milliseconds therefore runs dry, or overflows, within hours: a glitch, unless the player stretches or squeezes the sound to match.
Where it breaks

Straight-line resampling is only good when there are many samples per wave. This chapter's script: with 50 samples per wave the worst error is 0.20%, with 10 it's 4.9%, and with only 4 it's 21%. Speech at a 48 kHz sound card has well over 10 samples per wave for every note that matters, but music's highest notes come close to 4, which is why good players use smoother curves than straight lines.

Why does the squelch close 3 dB below where it opens, instead of at the same threshold?

A signal hovering right at one threshold would cross it many times a second, chopping the sound into stutter. With a gap (hysteresis), once open it stays open until the signal clearly drops: the same trick every thermostat uses.
The math, step by step

\[ \text{drift} = \text{ppm} \times 10^{-6} \times t \qquad\text{e.g. } 50 \times 10^{-6} \times 3600\,\text{s} = 0.18\,\text{s} \]

\[ y(n + f) \approx (1 - f)\,y[n] + f\,y[n+1], \qquad 0 \le f \lt 1 \]

\[ \text{step} = \frac{f_\text{radio}}{f_\text{card}} = \frac{50\,000}{48\,000} \approx 1.042 \]

\[ g = \frac{\text{target}}{\text{peak}}, \qquad \text{peak} \leftarrow \begin{cases} |x| & |x| > \text{peak} \;(\text{attack: at once})\\ \text{peak}\cdot r & \text{otherwise} \;(\text{release: } r \text{ a bit under } 1) \end{cases} \]

Lab: the complete receiver

Everything from chapters 5 to 11, playing live, with a signal meter. The airport tower is the best test of the squelch: watch the meter jump when a pilot or controller transmits.

In code

Show the real code (optional: everything it does is explained above)

Scheduling sound (LivePlayer): each chunk is scheduled to start exactly when the previous one ends, with the cushion and the two drift rules. (Spectrum Lab has since moved to one continuous stream that corrects drift smoothly instead: chapter 19.)

Names in this code: now is the sound card's clock, in seconds; this.t is when the next batch of sound should start, so this.t − now is the cushion. ctx is the browser's sound system, and src.start asks it to play the batch at that moment.

if (this.t < now + 0.05) this.t = now + 0.15;   // ran dry: rebuild a 150 ms cushion
if (this.t > now + 0.6) return;                 // too far ahead (clocks drift apart): drop this chunk
const buf = ctx.createBuffer(1, samples.length, rate);   // we say our rate; the browser resamples
src.start(this.t);  this.t += buf.duration;

Automatic volume (Agc): instant attack, slow release:

Names in this code: env is the loudest recent peak, the level being followed; decay is a number just below 1 that it's multiplied by every sample, which is the slow release; target is the loudness we want out.

const a = Math.abs(x[i]);
this.env = a > this.env ? a : Math.max(1e-4, this.env * this.decay);   // jump up, sink slowly
out[i] = (x[i] * target) / this.env;

Squelch (Squelch): power in dB, smoothed, with 3 dB of hysteresis:

const db = 10 * Math.log10(p / (channel.length / 2) + 1e-20);   // average power of this chunk
this.level = 0.7 * this.level + 0.3 * db;                       // smoothing
if (!this.open && this.level > this.threshold) this.open = true;
else if (this.open && this.level < this.threshold - 3) this.open = false;

Where this chapter's numbers come from. The numbers this chapter computes come from a short checking script behind this page, which also checks each claim and stops if one is wrong. Its output:

clocks  10 ppm apart: the buffer drifts  36 ms per hour → first glitch after 750 min (fast dongle) or 167 min (slow dongle)
clocks  50 ppm apart: the buffer drifts 180 ms per hour → first glitch after 150 min (fast dongle) or 33 min (slow dongle)
clocks 200 ppm apart: the buffer drifts 720 ms per hour → first glitch after 38 min (fast dongle) or 8 min (slow dongle)
straight-line resampling,  4 samples per wave: worst error 21.05%
straight-line resampling, 10 samples per wave: worst error 4.89%
straight-line resampling, 50 samples per wave: worst error 0.20%
AGC: loud part peaks at 0.50, quiet part (10× weaker in) peaks at 0.50 once it has adjusted
squelch: 97 chunks had a transmission, 97 were let through, 12 disagreed: at most 2 chunks (40 ms) late at each of the 6 edges, from smoothing the level
all checks passed

Check yourself

Two clocks differ by 100 ppm. How far apart do they get in an hour?

100 millionths of 3600 seconds: 0.36 seconds, i.e. 360 ms per hour.

Why does AGC react instantly to loud sounds but slowly to quiet ones?

Reacting slowly to a sudden loud signal would blast your ears for a moment. Reacting quickly to quiet moments would pump the volume up in every pause, making background noise surge.

Why does a squelch close a little below the level where it opens?

So a signal hovering right at the threshold doesn't make it flicker on and off. The 3 dB gap means a signal must clearly drop before the sound is cut.

Last updated