Projects · Amateur Radio · Web SDR

How the Web SDR works

A technical tour of the receiver behind the Web SDR page: the hardware, the server that does the signal processing, how audio and the waterfall get to your browser, and how the whole thing is deployed and configured.

01Overview

An RTL-SDR USB dongle plugged into the station server is the only radio. Two programs share it:

  • rtl_tcp, the standard RTL-SDR network server, reads raw samples from the dongle and serves them on TCP port 1234. Desktop SDR programs on the home network (SDR++, GQRX, SDR#) can connect to it directly.
  • The SDR gateway (sdr_gateway.py), a small Python server, is itself an rtl_tcp client. It does all the signal processing on the server and sends each browser a ready-to-draw waterfall and ready-to-play audio over a WebSocket.

The browser never sees raw radio samples. That is the key design decision: the dongle produces about 3.8 MB/s of data, far too much to push through a home internet uplink to every visitor, while the gateway's output is about 20 kB/s for the waterfall plus 24 kB/s for audio.

Signal path: the RTL-SDR dongle feeds rtl_tcp over USB; rtl_tcp feeds the SDR gateway and LAN desktop apps; the gateway's WebSocket is proxied by nginx, carried by cloudflared and Cloudflare to the browser. rtlsdr pod (rootless podman) RTL-SDR R820T dongle rtl_tcp :1234 · raw IQ sdr-gateway :8073 · DSP + WebSocket USB IQ 3.84 MB/s → ← tune / gain cmds Desktop SDR apps LAN / ZeroTier only host.containers.internal:8073 WebSocket /sdr/ws raydynamics-web pod cloudflared outbound tunnel nginx / static · /sdr/ proxy Cloudflare edge · HTTPS Browser sdr.html + sdr.js
The signal path. Amber lines carry the WebSocket that every browser shares with the gateway; grey lines are local to the server.

02Hardware

  • Receiver: a generic RTL-SDR dongle: a Realtek RTL2832U demodulator chip with a Rafael Micro R820T tuner. The RTL2832U delivers 8-bit I/Q samples; the gateway runs it at 1.92 MS/s, which gives a 1.92 MHz wide view of the spectrum.
  • Coverage: the R820T tunes from about 24 MHz to 1.77 GHz. Below 24 MHz the gateway switches the dongle into direct sampling (Q branch): the antenna is fed straight into the RTL2832U's analogue-to-digital converter, bypassing the tuner. That reaches the HF bands down to about 500 kHz with no upconverter, at modest sensitivity.
  • Server: a small Intel Core i3-4010U box running Fedora, which also hosts the web site. All the DSP fits comfortably on this two-core laptop-class CPU (see CPU budget).

03The gateway

The gateway is a single Python file built on asyncio and aiohttp (web server and WebSockets), with numpy and scipy doing the number crunching. It has three moving parts:

  1. The radio loop connects to rtl_tcp, sends it the sample rate, frequency, gain and frequency-correction commands, and then reads samples in 50 ms blocks (96,000 complex samples, 192 kB each).
  2. The DSP thread. Each block is handed to a single worker thread, so the heavy numpy work never stalls the network code. It produces one waterfall frame for everybody and one audio packet for each listener.
  3. One sender per browser. Each connected browser gets its own outgoing queue (60 messages deep). If a visitor's connection is too slow to keep up, waterfall and audio frames for that visitor are dropped rather than letting the queue grow; state messages are never dropped.

The gateway only holds the rtl_tcp connection while someone has the page open, plus a 10-second grace period. rtl_tcp serves one client at a time, so when the page is idle a desktop SDR app on the LAN can use the dongle directly. If a desktop app has it when a visitor arrives, the gateway notices that rtl_tcp accepted the connection but never sent its greeting, reports “tuner busy”, and retries every few seconds.

It also serves a small JSON health check at /sdr/status (status, centre frequency, sample rate, tuner type, listener count).

04Signal processing

The waterfall

From each 50 ms block the gateway takes 16 evenly spaced 2,048-point slices, applies a Hann window, runs an FFT on each, and averages their power. Two blocks are averaged per frame, giving 10 frames per second. Each frame is converted to decibels, mapped from −140…0 dB onto 0…255, and sent as 2,048 bytes, about 20 kB/s per viewer. The browser does the colouring.

A shared channelizer

Each listener can tune anywhere inside the visible span, so every listener needs a narrow slice of the spectrum, filtered and brought down to a low sample rate. Doing that separately for each listener (mix, filter, decimate) costs a lot of CPU per person. The gateway instead uses an overlap-save fast-convolution channelizer, so most of the work is shared:

  1. Once per block, the incoming samples are cut into 16 overlapping frames of 10,240 samples, and each frame is FFT'd. This is shared by every listener, and skipped entirely when nobody is listening.
  2. For each listener, the gateway picks out only the FFT bins around that listener's frequency (one bin is 187.5 Hz wide), multiplies them by the frequency response of that mode's channel filter, and runs a small inverse FFT: 1,280 points for wideband FM, 128 for everything else.
  3. Because the bins kept span exactly the output sample rate, that small inverse FFT is the decimation. WFM comes out at 240 kHz and every other mode comes out directly at the 24 kHz audio rate, already filtered. The equivalent FIR filter is over 4,000 taps long, so channel edges are steep.
  4. A phase correction lines up consecutive frames, and a tiny numerically controlled oscillator removes the leftover tuning offset smaller than one bin, so tuning is exact to the hertz.

Listeners on the same frequency, mode and squelch setting share one demodulator outright, so a crowd on one station costs about the same as one person.

Demodulators

ModeChannelProcessing
WFM±100 kHzFM discriminator at 240 kHz (scaled for 75 kHz deviation), 75 µs de-emphasis, 11 kHz low-pass, decimate by 10 to 24 kHz. Mono.
NFM±7 kHzFM discriminator at 24 kHz (scaled for 5 kHz deviation), then a 300–3,400 Hz voice band-pass, which also removes CTCSS sub-audible tones.
AM±4.5 kHzEnvelope detector, carrier (DC) removal with a slow running average, then audio AGC.
USB / LSB300–2,800 HzThe channel filter is a one-sided complex band-pass, so it already removes the opposite sideband; the audio is simply its real part, then AGC.

The AGC used for AM and SSB has a fast attack and a slow release (6–8 dB per second), with the gain ramped smoothly across each block so it never clicks. The squelch compares the channel power with the listener's threshold and has 3 dB of hysteresis, so it doesn't chatter on a signal right at the threshold.

Audio encoding

Audio is sent as 8-bit μ-law at 24 kHz: 24 kB/s, small enough for a phone on a cellular connection, with the familiar sound of telephone-grade companding. Each 50 ms packet also carries the signal level for the meter. While the squelch is closed, the gateway sends a four-byte “silence” packet instead, so the browser keeps its timing without receiving any audio.

CPU budget

Each 50 ms block must be processed in less than 50 ms. On the i3-4010U, an extra SSB, AM or NFM listener costs about 1 ms per block (a dozen SSB listeners take about 20 ms), and a WFM listener about 8 ms. The gateway logs its average DSP time every minute.

05Sharing one tuner

There is one physical tuner, so a few things are necessarily shared by everybody:

  • The visible span. Each listener tunes freely inside it. When someone tunes to a frequency whose passband would fall outside the flat middle 90% of the span, the gateway moves the tuner for everyone, placing the new frequency 288 kHz off-centre so the dongle's DC spike stays out of the passband. Other listeners whose frequency has scrolled off-screen see a “go back” prompt. Re-tuning is rate-limited (once per second per visitor) so one person can't sweep the tuner continuously.
  • RF gain. Auto or one of the R820T's 29 gain steps (0–49.6 dB), shared and labelled as such on the page. In HF direct-sampling mode the tuner's gain stages are bypassed, so the gateway turns on the RTL2832U's digital AGC instead; without it, strong AM broadcast stations clip the 8-bit samples and fill the band with intermodulation products.
  • Where newcomers land. A new visitor starts on the frequency and mode most recently tuned, so they hear what's on the screen.

Per-visitor settings (frequency within the span, mode, squelch, and whether audio is on) are private. Audio starts off for every visitor; browsers only allow sound after a click, and the gateway doesn't spend CPU demodulating for someone who is only watching the waterfall.

To limit abuse, the gateway accepts at most 10 simultaneous visitors and 3 per IP address (taken from Cloudflare's CF-Connecting-IP header). Extra connections get a polite error message, and the page waits 30 seconds before trying again.

06Wire protocol

Everything travels over one WebSocket at /sdr/ws. Control messages are JSON text; the high-rate data is binary (little-endian) to avoid any encoding overhead.

Server → browser

MessageContents
state (JSON)Shared radio state: status, centre frequency, sample rate, tuner type, gain and gain table, listener count, frequency limits, mode passbands. Sent to everyone whenever any of it changes.
you (JSON)This visitor's own frequency, mode, squelch, and whether their frequency is outside the current span.
notice / errorA message to show the visitor. error means the connection was refused (receiver full).
0x01 waterfallu8 type, u32 centre Hz, u32 sample rate, 2,048 × u8 power bins.
0x02 audiou8 type, u8 level (dBFS + 150), then μ-law samples at 24 kHz (1,200 per packet).
0x03 silenceu8 type, u8 level, u16 sample count (squelch closed).

Browser → server

{"type": "tune",    "freq": 146520000, "center": 146000000}   // center is optional
{"type": "mode",    "mode": "wfm" | "nfm" | "am" | "usb" | "lsb"}
{"type": "squelch", "level": -60}                           // dBFS, or null for off
{"type": "gain",    "gain": "auto"}                         // or an index into the gain table
{"type": "audio",   "on": true}

The gateway validates every field (frequency limits, known modes, finite numbers, gain index in range) and answers anything malformed with a notice instead of acting on it.

07The web interface

The page is plain HTML, CSS and one dependency-free script (sdr.js), served as static files by nginx. Everything it knows about the radio (coverage, gain steps, passbands) comes from the gateway's state messages, so the page adapts automatically if the receiver configuration changes. For example, presets outside the receiver's coverage are hidden, and the coverage text in the introduction is filled in from the gateway's limits.

Controls

ControlWhat it does
FrequencyType a frequency and press Enter. Units are optional: 146.52, 7200k, 1000 kHz and 1.2G all work. A bare number is read as MHz unless it only makes sense as kHz or Hz.
WaterfallClick (or tap) to tune. When focused, the arrow keys step by one tuning step, and Page Up/Page Down by ten. A mouse cursor shows the frequency under the pointer. The amber band shows the passband of the current mode.
ModeWFM, NFM, AM, USB or LSB. Changing mode also picks a sensible tuning step (100 kHz for WFM, 5 kHz for NFM and AM, 100 Hz for SSB).
Listen / StopStarts or stops audio for this visitor only.
Tune step, −/+Steps from 100 Hz to 200 kHz, including the 6.25, 8.33 and 12.5 kHz channel spacings.
VolumeLocal playback volume only.
SquelchMutes audio below a signal level; processed on the server, per visitor.
RF gainShared tuner gain (see Sharing one tuner).
PresetsOne-click jumps to useful frequencies, each with a mode and a centre chosen to show the surrounding band.

Status bar

StatusMeaning
LiveThe gateway is streaming from the dongle.
Connecting / StartingThe page is opening the WebSocket, or the gateway is connecting to rtl_tcp for the first visitor.
Tuner busyA desktop SDR app on the LAN is using rtl_tcp. The page reconnects when it's free.
OfflineThe gateway is up but rtl_tcp isn't, usually because the dongle is unplugged.
UnreachableThe page can't reach the gateway at all (nginx returns an error, or the server is down).
FullThe visitor limit has been reached.

Drawing and playback

  • Waterfall: each frame's 2,048 bytes are mapped through a 256-entry colour table (dark blue-grey through teal and amber to warm white) and written as one new row of a canvas, while the spectrum trace above it is redrawn from the same data.
  • Audio: μ-law bytes are expanded through a lookup table into Web Audio buffers and scheduled back to back, with about 250 ms queued to absorb network jitter. If the browser falls more than a second behind (a background tab, a stalled connection), packets are dropped so the delay can't keep growing. Silence packets advance the schedule without playing anything.
  • Reconnecting: if the connection drops, the page retries with exponential back-off (2, 4, 8… up to 32 seconds) and then restores the visitor's audio state. A tab that is in the background and not playing audio disconnects after a minute to free its slot, and reconnects when it is brought back.

08Deployment

Every service on the server runs as a Podman container managed by systemd through quadlet files (a future page will cover quadlets in general). The receiver is a rootless pod named rtlsdr with two containers built from one small Debian-based image with rtl-sdr, numpy, scipy and aiohttp:

  • rtl-tcp has access to the USB bus. Its systemd unit is bound to the dongle's device node, so unplugging the dongle stops it and plugging it back in starts a fresh container. A udev rule gives the dongle to the service account, and a module blacklist keeps the Linux DVB-T TV driver from claiming it.
  • sdr-gateway reaches rtl_tcp on localhost inside the pod and listens on port 8073.

The web site runs in a separate pod: nginx serves the static files, and cloudflared opens an outbound tunnel to Cloudflare, so the server has no inbound ports open to the internet. nginx forwards /sdr/ to the gateway's port and handles the WebSocket upgrade, with buffering off and long timeouts so the stream flows continuously. Cloudflare terminates HTTPS, which is why the page connects with wss://.

Security notes. rtl_tcp has no authentication, so the host firewall allows port 1234 only from the LAN (and the ZeroTier VPN); it is never exposed through the tunnel. Only the rtl-tcp container runs without SELinux confinement, because confined containers can't open USB devices; the internet-facing gateway stays fully confined and never touches hardware. The gateway accepts small JSON messages only (4 kB maximum) and validates every field.

09Configuration

The receiver is configured with environment variables in the gateway's quadlet file, sdr-gateway.container. The main settings:

VariableCurrentPurpose
SDR_SAMPLE_RATE1920000Width of the visible span in samples per second. Must be a multiple of 240,000; higher rates cost proportionally more CPU.
SDR_DEFAULT_FREQ162550000Where the very first visitor lands (NOAA weather radio).
SDR_DEFAULT_CENTER162200000Initial centre of the span.
SDR_DEFAULT_MODEnfmInitial mode.
SDR_PPM0Frequency correction for the dongle's crystal error, in parts per million.
SDR_DEEMPHASIS_US75FM broadcast de-emphasis: 75 µs in the Americas, 50 µs elsewhere.
SDR_DIRECT_SAMPLING2HF below 24 MHz via Q-branch direct sampling; 0 disables HF.
SDR_MAX_CLIENTS10Maximum simultaneous visitors.
SDR_MAX_PER_IP3Maximum visitors from one IP address.

Less common options (SDR_MIN_FREQ, SDR_MAX_FREQ, SDR_IDLE_GRACE, and the rtl_tcp host and port) are listed at the top of sdr_gateway.py. After changing a setting, re-running the install script reloads systemd and restarts the gateway; the page picks up the new limits on its own.

10Further reading