How a software radio works, and how this one was built
Every step of the receiver, in the same four parts: feel it (play with a widget running the app's real code), why it works (the math), the code (the actual lines from our app), and how it was tested. No background needed beyond school trigonometry.
This page is a quick reference. To really understand it from the ground up, start the course: Radio from scratch (16 chapters, starting with spinning arrows).
The big picture
A radio station is a signal at one frequency, for example 98.7 MHz: 98.7 million oscillations per second. Your speakers need audio, at most ~20 thousand oscillations per second. A receiver's job is to find one station among hundreds, pull it out, and turn it back into audio.
An old radio did all of that with coils and capacitors. In a software-defined radio, a tiny bit of hardware does the first step, and everything after it is arithmetic in your computer:
Here is the whole trip of one station, 98.7 FM, from the air to your speakers. Click any block (or press Walk me through) to see what happens there, what the signal looks like at that point, and where to read more: this page, the course chapter, the build guide. Dashed blocks are other things the same machine can do.
The orange blocks, numbered 0–6, are the sections of Spectrum Lab, and of this page. Each answers one question:
- 0–1: What's in the slice of radio band we captured?
- 2–4: How do I keep only my station, as cheaply as possible?
- 5–6: Where is the sound hidden in it, and how do I get it out?
How this app is built
Five small files, each doing one job. Bytes flow left to right:
r820t.ts + rtlsdr.tsUSB driver: talk to the dongle→ bytes →
iq.tsbytes → numbers→
dsp.tssteps 1–6, the math→
main.tsplots, buttons, audio
For listening from another computer, server.ts runs the same driver on the Mac mini and sends the same bytes over the network to remote.ts in your browser. Everything after the bytes is identical.
Two design decisions shaped the code:
- Synthetic signals first.
synth()makes fake stations (FM, AM, USB) with known content. That allowed testing every step with exact expected answers before touching any hardware. The widgets below use it too. - Every step is a streaming block. Live radio arrives in chunks of ~55 ms. A filter needs the last few dozen samples of the previous chunk, the mixer needs to continue its angle, and the FM demodulator needs the previous sample. If a block forgot that at each chunk edge, you'd hear a click 18 times a second. So each block is a small class that keeps its memory between
process()calls. Processing a file is just one big chunk.
The USB driver has its own chapters in the course: inside the dongle (how the tuner's PLL is programmed), USB from zero and writing the driver (every message, decoded, and the 19 kHz pilot test).
0I/Q: why every sample is two numbers
The tuner shifts the band so the frequency you tuned to sits at 0 Hz. A station above it lands at a positive frequency (+300 kHz), and one below at a negative one (−300 kHz). But with one number per sample, +300 kHz and −300 kHz give identical samples, because cos(−x) = cos(x). The receiver couldn't tell them apart.
blue = I, the arrow's shadow on the horizontal axis · orange = Q, its shadow on the vertical axis
TRY Switch between +1 and −1. The blue trace doesn't change at all; only orange flips. One number (I) can't see the direction of spin; two numbers can.
Measure the signal twice per sample, with two copies of the oscillator 90° apart: I (cosine part) and Q (sine part). Treat the pair as a complex number I + jQ, a point on a plane. A pure tone is then a point going around a circle:
x(t) = cos(2πft) + j·sin(2πft) = ej2πft
Positive frequencies spin counter-clockwise, negative ones clockwise. That's why the spectrum on the page runs from −fs/2 to +fs/2: at 2.4 million complex samples per second, the full 2.4 MHz is usable.
iq.ts
The dongle sends I, Q, I, Q… as bytes from 0 to 255, where 127.5 means zero. Turning them into numbers between −1 and +1 is one line:
for (let i = 0; i < out.length; i++) out[i] = (u[i] - 127.5) / 127.5;
The result stays interleaved: [I0, Q0, I1, Q1, …]. Every function in dsp.ts takes arrays in this layout.
Bytes 0 and 255 must decode to −1 and +1, and 127/128 to about 0 (dsp.test.ts).
1Spectrum & waterfall: the FFT
Reading the Spectrum Lab graph: horizontal is frequency relative to the center (0); in the plots, vertical is strength in decibels (+10 dB = 10× the power); in the waterfall, color is strength and each line is one moment. An FM station is a hump ~200 kHz wide. The flat rectangles beside many NYC stations are HD Radio, digital audio sent alongside the analog signal.
But how does a computer turn a list of samples into "how much of each frequency"?
The signal (32 samples) hides two tones. Left: each sample multiplied by a test tone spinning the opposite way, drawn as 32 small arrows head to tail. Orange = their sum. Right: the length of the sum for every test frequency, which is the spectrum.
TRY Slide slowly to 3. The arrows straighten into one long line, because you found a tone. Now find the other one (it's weaker). Then park between them: the arrows curl into a tight knot and cancel.
To ask "how much of frequency k is in this signal?", multiply the signal by a tone spinning at −k and add everything up:
X[k] = Σn x[n] · e−j2πkn/N
If the signal contains frequency k, the two spins cancel exactly, every product points the same way, and the sum is large. If not, the products keep turning and cancel out. The FFT computes this for all N test frequencies at once, using a clever reuse of shared work: N·log N operations instead of N² (for N = 1024: ~10 000 vs ~1 000 000).
Why decibels: a strong local station can be a million times stronger than a weak one; a log scale fits both on one graph. Why a window: chopping the signal into blocks makes sharp edges, which create fake frequencies; fading each block in and out (a "Hann" curve) removes them.
powerSpectrum() in dsp.ts
const w = 0.5 - 0.5 * Math.cos((TAU * i) / n); // Hann window: fade in and out
re[i] = iq[2 * (start + i)] * w; // windowed I
im[i] = iq[2 * (start + i) + 1] * w; // windowed Q
// … fft(re, im) …
const j = (i + n / 2) % n; // "fftshift": put 0 Hz in the middle
out[i] = 10 * Math.log10((re[j] ** 2 + im[j] ** 2) / wsum ** 2 + 1e-20); // power in dB
The FFT itself (fft(), ~25 lines) is the classic radix-2 version: reorder the samples by bit-reversed index, then combine pairs, then pairs of pairs, and so on.
A tone at exactly 1/8 of the sample rate must land exactly 128 bins right of center in a 1024-point FFT.
2Mixer: move your station to the center
The demo signal: an FM station at +200 kHz, an AM one at −150 kHz and an SSB tone at +350 kHz. The orange line marks 0.
TRY Shift by +200: the FM station's hump lands on the orange line. Shift by −150 to center the AM station instead. Push it far right: the spectrum wraps around the edge, because frequencies in a sampled signal live on a circle too.
Multiplying two spinning arrows adds their angles. So multiplying every sample by an arrow spinning at −f0 subtracts f0 from every frequency in the signal:
ej2πft · e−j2πf₀t = ej2π(f − f₀)t
Why bother centering? The filter in step 3 can then simply be "keep what's near 0", the simplest filter there is, and the demodulators in step 5 assume the station sits at 0.
Mixer in dsp.ts
const c = Math.cos(ph), s = Math.sin(ph); // the arrow at its current angle
out[k] = iq[k] * c - iq[k + 1] * s; // complex multiply: real part
out[k + 1] = iq[k] * s + iq[k + 1] * c; // imaginary part
ph += this.step; // step = −2π·f0/fs per sample
if (ph < -Math.PI) ph += TAU; else if (ph > Math.PI) ph -= TAU; // keep the angle small
This is an NCO (numerically controlled oscillator). ph lives on the object, so the next chunk continues exactly where this one stopped. The last line matters too: an angle that grows forever slowly loses precision.
3Low-pass filter: keep only your station
Reading the Spectrum Lab graph: blue is the centered spectrum, orange is the filter's response. The flat top passes your station unchanged; the comb of dips on both sides is everything the filter rejects (50 dB or more, i.e. at least 100 000× less power).
TRY Raise the taps: the edge between pass and reject gets steeper. Lower the cutoff: the sinc on the left gets wider and the passband on the right narrower, because they're mirror images. Then untick the window: the rejection gets much worse (bumps around −20 dB) even with many taps.
A digital filter (FIR) is a weighted moving average: each output is the last N inputs times N fixed weights (the taps), added up.
y[n] = h[0]·x[n] + h[1]·x[n−1] + … + h[N−1]·x[n−N+1]
Which weights keep the middle and block the rest? The key fact: a filter's frequency response is the Fourier transform of its weights. We want a response shaped like a rectangle, and the shape whose Fourier transform is a rectangle is sinc(x) = sin(x)/x. So the weights are samples of a sinc.
A true sinc goes on forever. Chopping it off makes ripples in the response, the same edge problem as the FFT window, so we fade its ends with a window. That's why it's called a "windowed-sinc" filter.
firLowpass() in dsp.ts
let n = Math.ceil(3.3 / transitionNorm); // steeper edge → more taps (Hamming rule of thumb)
for (let i = 0; i < n; i++) {
const x = i - (n - 1) / 2; // centered index
const sinc = x === 0 ? 2 * cutoffNorm : Math.sin(TAU * cutoffNorm * x) / (Math.PI * x);
h[i] = sinc * (0.54 - 0.46 * Math.cos((TAU * i) / (n - 1))); // × Hamming window
}
// then divide by the sum, so a 0 Hz signal passes at exactly 1×
At 0 Hz the response must be 0 dB (±0.1); at twice the cutoff it must be below −40 dB.
4Decimate: drop samples you don't need
An FM station is ~200 kHz wide, but we're carrying 2.4 million samples per second: 12× more than it needs. Keeping only every 8th sample (→ 300 thousand per second) makes every later step 8× cheaper. But throwing samples away has a trap.
Sampled 10 times per second. grey = the real wave · dots = the samples · blue = the slowest wave through the dots, which is what the samples "look like".
TRY Up to 5 Hz, blue matches grey. Go to 9 Hz: the dots now trace a 1 Hz wave. At 10 Hz the wave seems to stand still. This is aliasing, the same effect that makes car wheels spin backwards on video.
The demo signal, FM station centered, then every 4th sample kept (1.024 MS/s → 256 kS/s). The shaded band is your station.
To capture a signal B hertz wide with complex samples, you need at least B samples per second. Anything faster than half the new sample rate doesn't disappear when you drop samples: it disguises itself as a slower frequency and lands inside the new range, possibly right on your station. Once it's there, it's indistinguishable from real signal. So the filter must run before the sample rate drops, removing everything that could fold over.
FirDecimator in dsp.ts
// Only compute the outputs we keep: every m-th one.
for (let o = 0, j = this.next; o < count; o++, j += m) {
let r = 0, i = 0;
for (let k = 0; k < t; k++) { // the weighted moving average
const idx = base - 2 * k;
r += buf[idx] * h[k]; i += buf[idx + 1] * h[k];
}
out[2 * o] = r; out[2 * o + 1] = i;
}
this.hist = buf.slice(buf.length - this.hist.length); // remember the tail for the next chunk
Filtering and decimating in one loop is a classic optimization: there's no point computing the 7 out of 8 outputs we'd throw away. hist and next are the block's memory between chunks.
The streaming test feeds the same signal in odd-sized chunks (12 345 samples) and as one buffer. The outputs must be bit-identical, which proves the memory between chunks is right. It passes for FM, AM and SSB.
5Demodulate: the sound is in the spin speed
Reading the Spectrum Lab graph: this is no longer a spectrum. It's 10 ms of the recovered audio over time: horizontal is time, vertical is where the speaker cone should be.
TRY Watch the top wave: it squeezes where the audio is high and stretches where it's low. That's FM: the audio changes the frequency, never the height. Below, our FmDemod recovers the audio (orange) exactly on top of the original (grey). Change the deviation: the top wave squeezes more, but the recovered audio stays the same.
Frequency is how fast the arrow spins. So the audio at each moment is how far the arrow turned since the previous sample. Multiplying a sample by the conjugate (mirror image) of the previous one subtracts their angles, the opposite of the mixer:
audio[n] = angle( x[n] · conj(x[n−1]) )
That one line is a complete FM demodulator. Bonus: it doesn't care how long the arrow is, so a strong and a weak station come out at the same volume.
De-emphasis: FM noise grows with frequency, so broadcasters boost treble before sending and every receiver cuts it back by the same amount (a 75 µs low-pass in the Americas). The noise gets cut along with it.
AM puts the sound in the arrow's length instead: audio = |x| minus its average. SSB sends only one half of an AM signal: shift that half to straddle 0, filter off the other half, shift back, take the real part.
FmDemod in dsp.ts
const i = iq[k], q = iq[k + 1]; // this sample
out[k / 2] = Math.atan2(q * pi - i * pq, i * pi + q * pq);
pi = i; pq = q; // remember it for the next one
Where the formula comes from: (i + jq)·(pi − jpq) = (i·pi + q·pq) + j(q·pi − i·pq). atan2(imaginary, real) gives that product's angle, which is the angle difference.
Synthetic FM, AM and SSB stations carry known tones (1000, 600 and 800 Hz). Each demodulated output is checked by counting zero crossings: it must be within 5% of its tone.
6Audio: make it speaker-ready
The demodulator's output still runs at ~300 thousand samples per second and carries more than music: broadcast FM includes a 19 kHz pilot tone (marking a stereo station), the stereo difference signal around 38 kHz, and station data (RDS) at 57 kHz. One more filter keeps 0–15 kHz, the mono audio, then one more decimation brings it to ~48–50 thousand samples per second, what sound cards expect.
In live mode an AGC (automatic gain control) follows the loudest recent peak and scales the audio to keep the volume steady.
The best end-to-end check doesn't need ears: before that last filter, a real stereo FM station must show its 19 kHz pilot as a sharp, steady tone. On 98.7 FM it stood 45–63 dB above everything around it. If tuning, sample rate, I/Q or the demodulator were wrong, it wouldn't be there.
Build it yourself, in the order it was built
Each step ends with a check that tells you it's right before you go on. Write each in Python with numpy first if that's easier, then compare with our TypeScript.
- A fake station generator. A tone that spins at a chosen frequency, plus noise. Check: plot I and Q; they should be 90° apart.
- The FFT. Check: a tone at fs/8 lands exactly fs/8 right of center.
- The mixer. Check: the peak moves by exactly the amount you shift.
- The windowed-sinc filter. Check: plot its response; 0 dB in the middle, below −40 dB well outside.
- Decimation. Check: try it without the filter and see a neighbor fold in (like the widget above).
- FM, AM and SSB demodulators. Check: each recovers its fake station's tone.
- Make every block streaming. Check: chunked output equals whole-buffer output, bit for bit.
- Real samples. Record a station with
rtl_sdrand load the file. Check: the 19 kHz pilot. Then write your own USB driver (course chapters 13–14 and the build guide) and run the same check live.
Glossary
- Hz, kHz, MHz
- Oscillations per second: 1 / 1 000 / 1 000 000.
- Sample rate (fs)
- Measurements per second. USB live mode: 2.4 MS/s (million samples per second); server SDR: 1.024 MS/s.
- I/Q
- The two halves of a complex sample (cos and sin parts). Together they tell positive from negative frequencies.
- dB
- A ratio on a log scale: +10 dB = 10× the power, +3 dB ≈ 2×.
- FFT
- Fast Fourier transform: how much of each frequency a block of samples contains.
- FIR, taps
- A filter that's a weighted moving average; the taps are the weights.
- Decimation
- Keeping every M-th sample to lower the sample rate, after filtering.
- Aliasing
- A frequency too fast for the sample rate disguising itself as a slower one.
- NCO
- Numerically controlled oscillator: a digital spinning arrow, used by the mixer.
- Demodulation
- Recovering the sound: from the frequency (FM), the strength (AM) or one sideband (SSB).
Back to Spectrum Lab: load the demo, click the three signals one by one, and match each graph to its section here.
Last updated