// SPDX-FileCopyrightText: © 2012 Salvatore Sanfilippo // SPDX-FileCopyrightText: © 2016-2021 Oliver Jowett // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Where the samples come from. //! //! A source runs as its own task: it fills blocks from the `fifo` and hands //! them over, and never waits on anything downstream. That separation is not //! decoration — a radio delivering samples over USB will not wait, and a //! source that blocks on the demodulator loses samples outright. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const adaptive = @import("adaptive.zig"); const convert = @import("convert.zig"); const fifo = @import("fifo.zig"); const mag_buf = @import("mag_buf.zig"); const sdr_rtlsdr = @import("sdr_rtlsdr.zig"); const stats = @import("stats.zig"); /// Which kind of source to use. pub const Kind = enum { /// No radio at all: for a receiver that only takes messages over the /// network. none, /// A recording, or a pipe, in one of the raw sample formats. ifile, /// An RTL-SDR dongle. rtlsdr, pub fn parse(text: []const u8) ?Kind { inline for (comptime std.enums.values(Kind)) |kind| { if (std.ascii.eqlIgnoreCase(text, @tagName(kind))) return kind; } return null; } }; /// How to open a source. pub const Options = struct { kind: Kind = .none, /// The recording to read, or "-" for standard input. path: ?[]const u8 = null, /// The sample format the recording is in. format: convert.InputFormat = .uc8, /// Whether to read the recording at the speed it was captured, rather /// than as fast as the file can be read. throttle: bool = false, /// The rate the samples were taken at. sample_rate: f64 = mag_buf.sample_rate, /// Whether to remove the DC component. Not supported by any converter. filter_dc: bool = false, /// Which radio to use: an index, or a serial number or part of one. device: ?[]const u8 = null, /// What to set the tuner gain to. gain: sdr_rtlsdr.Gain = .max, /// The frequency to tune to. frequency: u32 = 1_090_000_000, /// Oscillator error correction, in parts per million. ppm: i32 = 0, /// Enable the radio's digital automatic gain control. digital_agc: bool = false, /// Direct sampling input, if any. direct_sampling: u2 = 0, }; /// Why a source could not be opened. pub const OpenError = error{ /// `--ifile` was not given a path. MissingPath, } || Allocator.Error || convert.Error || Io.File.OpenError || sdr_rtlsdr.OpenError; /// A configured sample source. pub const Source = union(Kind) { none, ifile: IFile, rtlsdr: sdr_rtlsdr.RtlSdr, pub fn open(gpa: Allocator, io: Io, options: Options) OpenError!Source { return switch (options.kind) { .none => .none, .ifile => .{ .ifile = try .open(gpa, io, options) }, .rtlsdr => .{ .rtlsdr = try .open(gpa, io, .{ .device = options.device, .gain = options.gain, .frequency = options.frequency, .sample_rate = options.sample_rate, .ppm = options.ppm, .digital_agc = options.digital_agc, .direct_sampling = options.direct_sampling, .filter_dc = options.filter_dc, }) }, }; } pub fn close(self: *Source, gpa: Allocator, io: Io) void { switch (self.*) { .none => {}, .ifile => |*ifile| ifile.close(gpa, io), .rtlsdr => |*radio| radio.close(gpa, io), } self.* = .none; } /// Ask a source that blocks in `run` to return. The file reader notices /// `running` on its own; a radio is inside a driver loop and has to be /// interrupted. pub fn stop(self: *Source) void { switch (self.*) { .none, .ifile => {}, .rtlsdr => |*radio| radio.stop(), } } /// The gain step in use, or null if the source has no gain control. pub fn gainStep(self: *const Source) ?u8 { return switch (self.*) { .none, .ifile => null, .rtlsdr => |*radio| if (radio.gains.len == 0) null else radio.current_gain, }; } /// Say what was opened, which for a radio is worth knowing: an /// unexpected serial number is the usual explanation for a receiver that /// suddenly hears nothing. pub fn describe(self: *const Source, w: *Io.Writer) Io.Writer.Error!void { switch (self.*) { .none, .ifile => {}, .rtlsdr => |*radio| { const info = radio.info orelse return; try w.print("rtlsdr: using device #{d}: {s} ({s}, {s}, SN {s})\n", .{ info.index, info.name, info.manufacturer.slice(), info.product.slice(), info.serial.slice(), }); if (radio.gains.len > 0) { try w.print("rtlsdr: tuner gain set to {d:.1} dB (gain step {d})\n", .{ radio.gainDb(radio.current_gain), radio.current_gain, }); } }, } } /// The gain in decibels at a step. pub fn gainDb(self: *const Source, step: u8) f64 { return switch (self.*) { .none, .ifile => 0, .rtlsdr => |*radio| radio.gainDb(step), }; } /// The gain control, for the adaptive gain controller. /// /// Steps are signed here where the rest of this file uses `u8`, because /// the controller works in "one step below the current one" and expects /// to be able to ask for step −1 and be told no. pub fn gainControl(self: *Source) adaptive.Radio { return .{ .context = self, .vtable = &gain_vtable }; } const gain_vtable: adaptive.Radio.VTable = .{ .gain = struct { fn f(context: *anyopaque) i32 { const self: *Source = @ptrCast(@alignCast(context)); return if (self.gainStep()) |step| step else -1; } }.f, .maxGain = struct { fn f(context: *anyopaque) i32 { const self: *Source = @ptrCast(@alignCast(context)); return switch (self.*) { .none, .ifile => -1, .rtlsdr => |*device| if (device.gains.len == 0) -1 else @as(i32, device.maxGainStep()), }; } }.f, .gainDb = struct { fn f(context: *anyopaque, step: i32) f64 { const self: *Source = @ptrCast(@alignCast(context)); return self.gainDb(clampStep(self, step)); } }.f, .setGain = struct { fn f(context: *anyopaque, step: i32) i32 { const self: *Source = @ptrCast(@alignCast(context)); return switch (self.*) { .none, .ifile => 0, .rtlsdr => |*device| @as(i32, device.setGain(clampStep(self, step))), }; } }.f, }; fn clampStep(self: *const Source, step: i32) u8 { return switch (self.*) { .none, .ifile => 0, .rtlsdr => |*device| if (device.gains.len == 0) 0 else @intCast(std.math.clamp(step, 0, @as(i32, device.maxGainStep()))), }; } /// The dynamic range the adaptive controller should aim for when the /// user did not say, which depends on what the tuner can do. pub fn defaultRangeTarget(self: *const Source) f32 { return switch (self.*) { .none, .ifile => 0, .rtlsdr => 30.0, }; } /// Fill blocks until the source runs out or `running` is cleared. /// /// Runs on its own task. `running` must be cleared *before* the queue is /// halted, so that a source waiting for a free block wakes up and sees /// that it should stop rather than going round again. pub fn run(self: *Source, io: Io, queue: *fifo.Fifo, running: *std.atomic.Value(bool)) void { switch (self.*) { .none => {}, .ifile => |*ifile| ifile.run(io, queue, running), .rtlsdr => |*radio| radio.run(io, queue, running), } } /// Whether this source produces samples at all. A `none` source does not, /// so the demodulator has nothing to wait for. pub fn producesSamples(self: Source) bool { return self != .none; } /// Processor time the source has used, in milliseconds. pub fn cpuMilliseconds(self: *const Source) u64 { return switch (self.*) { .none, .rtlsdr => 0, .ifile => |*ifile| ifile.cpu.milliseconds(), }; } }; /// A recording or a pipe. pub const IFile = struct { file: Io.File, /// Whether to close the file: standard input is not ours to close. owned: bool, converter: convert.Converter, /// Raw samples, before conversion to magnitudes. read_buf: []u8, throttle: bool, sample_rate: f64, /// Processor time spent reading and converting samples. cpu: stats.CpuTimer = .{}, pub fn open(gpa: Allocator, io: Io, options: Options) OpenError!IFile { const path = options.path orelse return error.MissingPath; const is_stdin = std.mem.eql(u8, path, "-"); const file: Io.File = if (is_stdin) .stdin() else try Io.Dir.cwd().openFile(io, path, .{}); errdefer if (!is_stdin) file.close(io); var converter: convert.Converter = try .init(gpa, options.format, .{ .sample_rate = options.sample_rate, .filter_dc = options.filter_dc, }); errdefer converter.deinit(gpa); const read_buf = try gpa.alloc(u8, mag_buf.default_block_samples * converter.bytesPerSample()); return .{ .file = file, .owned = !is_stdin, .converter = converter, .read_buf = read_buf, .throttle = options.throttle, .sample_rate = options.sample_rate, }; } pub fn close(self: *IFile, gpa: Allocator, io: Io) void { gpa.free(self.read_buf); self.converter.deinit(gpa); if (self.owned) self.file.close(io); self.* = undefined; } pub fn run(self: *IFile, io: Io, queue: *fifo.Fifo, running: *std.atomic.Value(bool)) void { var reader_buf: [4096]u8 = undefined; // Streaming rather than positional: samples are only ever read // forward, and standard input is a pipe, which cannot be seeked. var reader = self.file.readerStreaming(io, &reader_buf); var sample_counter: u64 = 0; var next_delivery = Io.Timestamp.now(io, .awake).withClock(.awake); while (running.load(.acquire)) { // A hundred milliseconds is long enough that a busy demodulator // is given a chance, and short enough that a stop request is // noticed promptly. const buf = queue.acquire(io, fifo.millis(100)) orelse continue; // The clock is derived from the sample count rather than read, // because a recording has no real arrival times: what matters is // that the intervals are right. buf.sample_timestamp = @intFromFloat(@as(f64, @floatFromInt(sample_counter)) * mag_buf.receive_clock_rate / self.sample_rate); buf.system_timestamp_ms = nowMillis(io); const bytes_per_sample = self.converter.bytesPerSample(); const wanted = @min( (buf.data.len - buf.overlap) * bytes_per_sample, self.read_buf.len, ); // `readSliceShort` fills the slice unless the stream ended, so // a short read is the end of the recording rather than a pipe // handing over what it happened to have. const got = reader.interface.readSliceShort(self.read_buf[0..wanted]) catch 0; const at_end = got < wanted; const samples = got / bytes_per_sample; self.cpu.start(io); buf.level = self.converter.convertAndMeasure( self.read_buf[0 .. samples * bytes_per_sample], buf.data[buf.overlap..][0..samples], ); self.cpu.stop(io); buf.valid = buf.overlap + samples; buf.discontinuous = false; if (self.throttle) { next_delivery.wait(io) catch {}; const elapsed_ns: i96 = @intFromFloat(@as(f64, @floatFromInt(samples)) * std.time.ns_per_s / self.sample_rate); next_delivery.raw = next_delivery.raw.addDuration(.fromNanoseconds(elapsed_ns)); } queue.enqueue(io, buf); sample_counter += samples; if (at_end) break; } // Let the demodulator finish what is queued, so the tail of the // recording is not thrown away. queue.drain(io); } }; /// Wall-clock milliseconds, which is what message timestamps are quoted in. pub 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 "source kinds parse case-insensitively" { try testing.expectEqual(Kind.none, Kind.parse("none").?); try testing.expectEqual(Kind.ifile, Kind.parse("IFile").?); try testing.expectEqual(Kind.rtlsdr, Kind.parse("RTLSDR").?); try testing.expectEqual(@as(?Kind, null), Kind.parse("bladerf")); } test "a file source needs a path" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); try testing.expectError( error.MissingPath, Source.open(testing.allocator, threaded.io(), .{ .kind = .ifile }), ); } test "the no-radio source produces nothing and stops immediately" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var source: Source = try .open(testing.allocator, io, .{ .kind = .none }); defer source.close(testing.allocator, io); try testing.expect(!source.producesSamples()); var queue: fifo.Fifo = try .init(testing.allocator, .{ .buffer_count = 2 }); defer queue.deinit(); var running: std.atomic.Value(bool) = .init(true); source.run(io, &queue, &running); try testing.expectEqual(@as(usize, 0), queue.queueDepth(io)); }