// SPDX-FileCopyrightText: © 2012 Salvatore Sanfilippo // SPDX-FileCopyrightText: © 2014-2021 Oliver Jowett // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Samples from an RTL-SDR. //! //! The driver underneath is [zig-rtlsdr], a port of librtlsdr onto Zig that //! talks to Linux's usbfs directly, so there is no C in the build and nothing //! to link. That also means the dongle no longer has to be prised away from //! the kernel by hand: the driver detaches `dvb_usb_rtl28xxu` when it opens //! the device and puts it back when it closes, where librtlsdr as most //! distributions build it refuses to open the device and tells you to //! blacklist the module. //! //! It is Linux-only, since the USB layer is written against usbfs, which is //! why the input is compiled in only for Linux targets. //! //! The awkward part is the same as it ever was: whose thread the samples //! arrive on. `readAsync` runs its own loop and calls back with each //! completed USB transfer. That callback must not block — the buffer it was //! handed is one of a small ring the driver reuses, and anything slow there //! loses samples outright. So it does the least it can: convert, and hand the //! block to the queue; and if no free block is waiting it drops the samples //! and says so, rather than waiting for one. //! //! [zig-rtlsdr]: https://git.jcollie.dev/jeff/zig-rtlsdr const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const build_options = @import("build_options"); const convert = @import("convert.zig"); const fifo = @import("fifo.zig"); const mag_buf = @import("mag_buf.zig"); /// Whether this build can talk to an RTL-SDR at all. pub const available = build_options.rtlsdr; const rtlsdr = if (available) @import("rtlsdr") else struct { pub const Device = opaque {}; }; /// How many USB transfers to keep outstanding. More absorbs a longer stall in /// the rest of the program; fewer means less latency and less to lose. pub const transfer_count = 4; /// How the tuner's gain should be set. pub const Gain = union(enum) { /// The tuner's own automatic gain control. Fewer messages in practice /// than a fixed high gain, because the tuner's loop is tuned for /// broadcast signals rather than for hundred-microsecond bursts. tuner_agc, /// The highest fixed gain the tuner offers, which is upstream's default /// and usually the right answer for a receiver with a decent antenna. max, /// A particular gain, in decibels. The nearest step the tuner supports /// is used. db: f32, }; /// How to open the radio. pub const Options = struct { /// Which device: an index, or a serial number, or a prefix or suffix of /// one. Null takes the first. device: ?[]const u8 = null, gain: Gain = .max, /// The frequency to tune to. 1090 MHz unless something odd is going on. frequency: u32 = 1_090_000_000, sample_rate: f64 = mag_buf.sample_rate, /// Oscillator error correction, in parts per million. ppm: i32 = 0, /// Enable the *digital* automatic gain control, which is a different /// thing from the tuner's and generally does more harm than good. digital_agc: bool = false, /// Direct sampling input, for receiving below the tuner's range. Not /// useful at 1090 MHz, but the option exists because the hardware does. direct_sampling: u2 = 0, /// Whether to remove the DC component. filter_dc: bool = false, }; /// Why the radio could not be opened. pub const OpenError = error{ /// No RTL-SDR is plugged in. NoDeviceFound, /// A device was named and no device matches. DeviceNotFound, /// The device is there but would not open — usually the udev rules that /// grant access to SDR dongles are missing, or another program has it. OpenFailed, /// The tuner would not say what gains it supports. NoTunerGains, /// This build was made without RTL-SDR support. NotSupported, } || Allocator.Error || convert.Error; /// What a device says about itself over USB. pub const DeviceInfo = struct { index: u32, /// The driver's name for the chipset, such as "Generic RTL2832U OEM". name: []const u8, manufacturer: Text = .{}, product: Text = .{}, serial: Text = .{}, /// A fixed-size string, so that a `DeviceInfo` can outlive the arena the /// device list was read into. pub const Text = struct { buffer: [256]u8 = @splat(0), pub fn slice(self: *const Text) []const u8 { return std.mem.sliceTo(&self.buffer, 0); } fn from(text: []const u8) Text { var self: Text = .{}; const n = @min(text.len, self.buffer.len - 1); @memcpy(self.buffer[0..n], text[0..n]); return self; } }; }; /// How many RTL-SDRs are plugged in. pub fn deviceCount(gpa: Allocator, io: Io) u32 { if (!available) return 0; return @intCast(rtlsdr.deviceCount(gpa, io) catch 0); } /// What device `index` is, or null if it will not say. pub fn deviceInfo(gpa: Allocator, io: Io, index: u32) ?DeviceInfo { if (!available) return null; var list = rtlsdr.enumerate(gpa, io) catch return null; defer list.deinit(); if (index >= list.items.len) return null; return infoFrom(index, list.items[index]); } fn infoFrom(index: u32, entry: anytype) DeviceInfo { return .{ .index = index, .name = entry.name, .manufacturer = .from(entry.manufacturer), .product = .from(entry.product), .serial = .from(entry.serial), }; } /// List what is plugged in, which is what to print when the requested device /// is not among them. pub fn listDevices(gpa: Allocator, io: Io, w: *Io.Writer) Io.Writer.Error!void { if (!available) { try w.writeAll("rtlsdr: this build has no RTL-SDR support\n"); return; } var list = rtlsdr.enumerate(gpa, io) catch { try w.writeAll("rtlsdr: unable to enumerate devices\n"); return; }; defer list.deinit(); try w.print("rtlsdr: found {d} device(s):\n", .{list.items.len}); for (list.items, 0..) |entry, i| { try w.print(" {d}: {s}, {s}, SN: {s}\n", .{ i, entry.manufacturer, entry.product, entry.serial, }); } } /// An open RTL-SDR. pub const RtlSdr = struct { device: if (available) *rtlsdr.Device else void, converter: convert.Converter, /// The `Io` the device was opened with, kept because every call into the /// driver needs one and the gain can be changed from places that have no /// `Io` to hand — the adaptive controller reaches the radio through a /// vtable of plain functions. io: Io = undefined, /// The gains the tuner supports, in tenths of a decibel, ascending. The /// last is not a real gain: see `readGains`. gains: []i32, /// Which of them is in use. current_gain: u8 = 0, /// State the callback needs, in an allocation that does not move: its /// address is handed to the driver and comes back on the streaming loop. context: *Context, /// Which device this is, for the line printed at startup. info: ?DeviceInfo = null, /// What the callback needs to do its work. pub const Context = struct { io: Io, queue: *fifo.Fifo, converter: convert.Converter, sample_rate: f64, running: *std.atomic.Value(bool), /// Samples counted since the radio started, which is what the /// receive clock is derived from. sample_counter: u64 = 0, /// Samples dropped since the last block was queued, which the next /// one reports so that the demodulator knows not to trust its /// overlap. dropped: usize = 0, /// Samples dropped in total, for the statistics. total_dropped: u64 = 0, }; pub fn open(gpa: Allocator, io: Io, options: Options) OpenError!RtlSdr { if (!available) return error.NotSupported; var list = rtlsdr.enumerate(gpa, io) catch return error.NoDeviceFound; defer list.deinit(); if (list.items.len == 0) return error.NoDeviceFound; const index: u32 = if (options.device) |name| findDevice(name, list.items) orelse return error.DeviceNotFound else 0; const info = infoFrom(index, list.items[index]); const device = rtlsdr.Device.open(gpa, io, index, .{}) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.NoDevice => return error.DeviceNotFound, else => return error.OpenFailed, }; errdefer device.close(io); var converter: convert.Converter = try .init(gpa, .uc8, .{ .sample_rate = options.sample_rate, .filter_dc = options.filter_dc, }); errdefer converter.deinit(gpa); var self: RtlSdr = .{ .device = device, .converter = converter, .io = io, .gains = &.{}, .context = undefined, .info = info, }; if (options.direct_sampling != 0) { device.setDirectSampling(io, switch (options.direct_sampling) { 1 => .i_branch, 2 => .q_branch, else => .off, }) catch {}; } else { self.gains = try readGains(gpa, device); _ = self.setGain(self.chooseGain(options.gain)); } errdefer if (self.gains.len > 0) gpa.free(self.gains); if (options.digital_agc) device.setAgcMode(io, true) catch {}; device.setFreqCorrection(io, options.ppm) catch {}; device.setCenterFreq(io, options.frequency) catch {}; device.setSampleRate(io, @intFromFloat(options.sample_rate)) catch {}; device.resetBuffer(io) catch {}; self.context = try gpa.create(Context); return self; } pub fn close(self: *RtlSdr, gpa: Allocator, io: Io) void { if (!available) return; self.device.close(io); if (self.gains.len > 0) gpa.free(self.gains); self.converter.deinit(gpa); gpa.destroy(self.context); self.* = undefined; } /// Read samples until the radio stops or `running` is cleared. pub fn run(self: *RtlSdr, io: Io, queue: *fifo.Fifo, running: *std.atomic.Value(bool)) void { if (!available) return; self.context.* = .{ .io = io, .queue = queue, .converter = self.converter, .sample_rate = mag_buf.sample_rate, .running = running, }; self.device.readAsync(io, .{ .buffer_count = transfer_count, .buffer_len = mag_buf.default_block_samples * 2, }, self.context, callback) catch {}; } /// Ask `run` to return. Safe to call from another task. pub fn stop(self: *RtlSdr) void { if (!available) return; self.device.cancelAsync(); } /// The gain in decibels at a given step. pub fn gainDb(self: *const RtlSdr, step: u8) f64 { if (self.gains.len == 0) return 0; const index = @min(step, self.gains.len - 1); return @as(f64, @floatFromInt(self.gains[index])) / 10.0; } /// The highest step there is. pub fn maxGainStep(self: *const RtlSdr) u8 { if (self.gains.len == 0) return 0; return @intCast(self.gains.len - 1); } /// Set the tuner gain, returning the step actually used. pub fn setGain(self: *RtlSdr, step: u8) u8 { const io = self.io; if (!available or self.gains.len == 0) return 0; const wanted = @min(step, self.gains.len - 1); if (wanted == self.gains.len - 1) { // The top step is the fake one: hand control to the tuner. self.device.setTunerGainMode(io, .auto) catch return self.current_gain; } else { self.device.setTunerGainMode(io, .manual) catch return self.current_gain; self.device.setTunerGain(io, self.gains[wanted]) catch return self.current_gain; } self.current_gain = @intCast(wanted); return self.current_gain; } /// Which step a gain setting asks for. fn chooseGain(self: *const RtlSdr, gain: Gain) u8 { if (self.gains.len == 0) return 0; return switch (gain) { .tuner_agc => @intCast(self.gains.len - 1), .max => @intCast(self.gains.len - 2), .db => |wanted| blk: { var best: usize = 0; for (self.gains, 0..) |step, i| { const here = @abs(@as(f32, @floatFromInt(step)) / 10.0 - wanted); const there = @abs(@as(f32, @floatFromInt(self.gains[best])) / 10.0 - wanted); if (here < there) best = i; } break :blk @intCast(best); }, }; } /// The gains the tuner supports, sorted, with one more on the end. /// /// That last entry is not a real gain. Enabling the tuner's own automatic /// control behaves, as far as everything above here is concerned, like a /// gain higher than the highest manual one — so it is given a step of its /// own, nine decibels above the real maximum, and the adaptive gain /// control can then treat "AGC" as simply the top of the range. fn readGains(gpa: Allocator, device: *rtlsdr.Device) OpenError![]i32 { const reported = device.tunerGains(); if (reported.len == 0) return error.NoTunerGains; const gains = try gpa.alloc(i32, reported.len + 1); errdefer gpa.free(gains); @memcpy(gains[0..reported.len], reported); std.mem.sort(i32, gains[0..reported.len], {}, std.sort.asc(i32)); gains[gains.len - 1] = gains[gains.len - 2] + 90; return gains; } /// Which device a name refers to: an index, or a serial number, or a /// prefix or suffix of one. fn findDevice(name: []const u8, entries: anytype) ?u32 { if (std.fmt.parseInt(u32, name, 10)) |index| { if (index < entries.len) return index; } else |_| {} var best_suffix: ?u32 = null; var best_prefix: ?u32 = null; for (entries, 0..) |entry, i| { const index: u32 = @intCast(i); const text = entry.serial; if (std.mem.eql(u8, text, name)) return index; if (best_prefix == null and std.mem.startsWith(u8, text, name)) best_prefix = index; if (best_suffix == null and name.len < text.len and std.mem.endsWith(u8, text, name)) best_suffix = index; } return best_prefix orelse best_suffix; } }; /// Called by the driver, on the streaming loop, once per completed USB /// transfer. fn callback(ctx: ?*anyopaque, buffer: []const u8) void { const context: *RtlSdr.Context = @ptrCast(@alignCast(ctx.?)); // An odd trailing byte is half a sample and there is nothing to be done // with it. const samples = buffer.len / 2; if (samples == 0) return; if (!context.running.load(.acquire)) return; // Do not wait: the buffer being written into belongs to the driver, and // holding it up loses samples that are still arriving. const buf = context.queue.acquire(context.io, .{ .duration = .{ .raw = .fromMilliseconds(0), .clock = .awake, } }) orelse { context.dropped += samples; context.total_dropped += samples; context.sample_counter += samples; return; }; buf.discontinuous = context.dropped > 0; buf.dropped = context.dropped; context.dropped = 0; // The clock is counted from samples rather than read, so that it stays // exactly proportional to the number of samples seen however late a // transfer was collected. buf.sample_timestamp = @intFromFloat(@as(f64, @floatFromInt(context.sample_counter)) * mag_buf.receive_clock_rate / context.sample_rate); context.sample_counter += samples; // The block *began* a block's duration ago, which is what the arrival // times of the messages in it are relative to. const duration_ms: u64 = @intFromFloat(1000.0 * @as(f64, @floatFromInt(samples)) / context.sample_rate); buf.system_timestamp_ms = nowMillis(context.io) -| duration_ms; // A transfer larger than a block should not happen, but if it does, the // tail is dropped rather than written past the end. var usable: usize = samples; if (usable + buf.overlap > buf.data.len) { usable = buf.data.len - buf.overlap; context.dropped += samples - usable; context.total_dropped += samples - usable; } buf.level = context.converter.convertAndMeasure( buffer[0 .. usable * 2], buf.data[buf.overlap..][0..usable], ); buf.valid = buf.overlap + usable; context.queue.enqueue(context.io, buf); } fn nowMillis(io: Io) u64 { const now = Io.Timestamp.now(io, .real); return @intCast(@divTrunc(now.nanoseconds, std.time.ns_per_ms)); } const testing = std.testing; test "a build without the driver says so rather than pretending" { if (available) return error.SkipZigTest; try testing.expectError(error.NotSupported, RtlSdr.open(testing.allocator, testing.io, .{})); } test "gain settings choose a step" { // The gain table is the tuner's, so this exercises the choosing against a // made-up one: the R820T's real steps, plus the fake AGC step on the end. var gains = [_]i32{ 0, 9, 14, 27, 37, 77, 87, 125, 144, 157, 166, 197, 207, 229, 254, 280, 297, 328, 338, 364, 372, 386, 402, 421, 434, 439, 445, 480, 496, 496 + 90 }; var radio: RtlSdr = .{ .device = if (available) undefined else {}, .converter = undefined, .gains = &gains, .context = undefined, }; // The top step is the tuner's own control; the one below it is the // highest real gain. try testing.expectEqual(@as(u8, 29), radio.chooseGain(.tuner_agc)); try testing.expectEqual(@as(u8, 28), radio.chooseGain(.max)); // A named gain picks the nearest step, not the next one up. try testing.expectEqual(@as(u8, 0), radio.chooseGain(.{ .db = 0 })); try testing.expectEqual(@as(u8, 5), radio.chooseGain(.{ .db = 7.7 })); try testing.expectEqual(@as(u8, 5), radio.chooseGain(.{ .db = 7.9 })); // A gain higher than the tuner offers lands on the tuner's own control, // since that step is nominally nine decibels above the real maximum and // is therefore the nearest. Upstream does the same. try testing.expectEqual(@as(u8, 29), radio.chooseGain(.{ .db = 100 })); try testing.expectApproxEqAbs(@as(f64, 49.6), radio.gainDb(28), 1e-9); try testing.expectApproxEqAbs(@as(f64, 58.6), radio.gainDb(29), 1e-9); // Out of range clamps rather than reading past the end. try testing.expectApproxEqAbs(@as(f64, 58.6), radio.gainDb(200), 1e-9); try testing.expectEqual(@as(u8, 29), radio.maxGainStep()); } test "a radio with no gain table reports nothing rather than indexing into it" { var radio: RtlSdr = .{ .device = if (available) undefined else {}, .converter = undefined, .gains = &.{}, .context = undefined, }; try testing.expectEqual(@as(f64, 0), radio.gainDb(0)); try testing.expectEqual(@as(u8, 0), radio.maxGainStep()); try testing.expectEqual(@as(u8, 0), radio.chooseGain(.max)); }