diff --git a/README.md b/README.md index d2929fb..6f31c33 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,11 @@ it means. | `src/convert.zig` | `convert.c` | Done | | `src/mag_buf.zig` | `fifo.h` | The sample block and its overlap | | `src/demod_2400.zig` | `demod_2400.c` | Done; 4M samples demodulate identically, messages and counters alike | +| `src/fifo.zig` | `fifo.c` | Done; pthreads replaced by `std.Io` | +| `src/sdr.zig` | `sdr.c`, `sdr_ifile.c`, `sdr_stub.c` | File and no-radio inputs done; RTL-SDR still to do | +| `src/output.zig` | `net_io.c` | The AVR and Beast wire formats | +| `src/display.zig` | `mode_s.c` | `--raw` and `--onlyaddr`; the verbose display still to do | +| `src/main.zig` | `dump1090.c` | Runs end to end; most options still to do | ## Scope @@ -54,6 +59,16 @@ Structurally it is not a transliteration. The generated SIMD dispatch under upstream's `dsp/` is replaced by Zig's `@Vector`, the pthreads and the bundled `anet.c` by `std.Io`, and C's sentinel returns by error sets and tagged unions. +## Checking it against upstream + +The port is checked by running both programs over the same recording and +diffing the output. On synthetic recordings of a few million samples, with +real frames planted at every sub-sample phase and amplitude, `--raw` output is +byte-for-byte identical across every combination of `--fix`, `--fix-2bit`, +`--no-fix`, `--no-fix-df`, `--mlat` and `--modeac`, in both UC8 and SC16 — +including the noisy recordings where error correction changes what gets +decoded. + ## Building ``` diff --git a/src/demod_2400.zig b/src/demod_2400.zig index 805b871..aaa0f74 100644 --- a/src/demod_2400.zig +++ b/src/demod_2400.zig @@ -101,7 +101,7 @@ fn advance(offset: usize, phase: u3) struct { offset: usize, phase: u3 } { /// the downlink formats worth demodulating are exactly those the decoder can /// make sense of. pub const Options = struct { - fix_bits: crc.FixBits = .one, + fix_bits: crc.FixBits = .none, fix_df: bool = true, enable_df24: bool = false, }; diff --git a/src/display.zig b/src/display.zig new file mode 100644 index 0000000..26c064e --- /dev/null +++ b/src/display.zig @@ -0,0 +1,75 @@ +// 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 + +//! What a message looks like on standard output. +//! +//! This is the human-facing side of the program, and deliberately unfiltered: +//! everything the decoder accepted is shown, including the frames the network +//! outputs would hold back as too doubtful to forward. Somebody watching a +//! terminal is debugging, and wants to see what arrived. + +const std = @import("std"); +const Io = std.Io; + +const message = @import("message.zig"); +const Message = message.Message; + +/// One frame as a line of hex, which is what `--raw` prints. +/// +/// Lower case, unlike the network AVR output, which is upper. The two are the +/// same format and disagree about it; both are reproduced as they are, +/// because tools exist that read each. +pub fn raw(w: *Io.Writer, mm: *const Message, with_timestamp: bool) Io.Writer.Error!void { + if (with_timestamp and mm.timestamp_12mhz != 0) { + try w.print("@{X:0>12}", .{mm.timestamp_12mhz}); + } else { + try w.writeByte('*'); + } + + for (mm.bytes()) |byte| try w.print("{x:0>2}", .{byte}); + try w.writeAll(";\n"); +} + +/// Just the address, which is what `--onlyaddr` prints. +pub fn address(w: *Io.Writer, mm: *const Message) Io.Writer.Error!void { + try w.print("{x:0>6}\n", .{mm.address}); +} + +const testing = std.testing; + +const df17 = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; + +test "the raw display is lower case" { + var mm: Message = .empty; + @memcpy(mm.msg[0..df17.len], &df17); + mm.len = df17.len; + + var buf: [128]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + try raw(&w, &mm, false); + try testing.expectEqualStrings("*8d4840d6202cc371c32ce0576098;\n", w.buffered()); +} + +test "the raw display can carry the receiver clock" { + var mm: Message = .empty; + @memcpy(mm.msg[0..df17.len], &df17); + mm.len = df17.len; + mm.timestamp_12mhz = 0xabcdef012345; + + var buf: [128]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + try raw(&w, &mm, true); + try testing.expectEqualStrings("@ABCDEF0123458d4840d6202cc371c32ce0576098;\n", w.buffered()); +} + +test "only the address" { + var mm: Message = .empty; + mm.address = 0x4840d6; + + var buf: [32]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + try address(&w, &mm); + try testing.expectEqualStrings("4840d6\n", w.buffered()); +} diff --git a/src/fifo.zig b/src/fifo.zig new file mode 100644 index 0000000..edac05d --- /dev/null +++ b/src/fifo.zig @@ -0,0 +1,439 @@ +// SPDX-FileCopyrightText: © 2020-2021 Oliver Jowett +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: GPL-2.0-or-later + +//! The handoff of sample blocks from the radio to the demodulator. +//! +//! The radio delivers samples on its own schedule and will not wait: a USB +//! device hands over a completed transfer and expects the buffer back +//! promptly, and anything that blocks there loses samples outright. So the +//! two halves run as separate tasks with a fixed pool of buffers between +//! them, and the pool is fixed on purpose — when the demodulator falls +//! behind, the right thing is to drop samples and say so, not to grow a queue +//! that hides the problem until memory runs out. +//! +//! The queue also owns the overlap between blocks. A message that begins near +//! the end of one block runs into the next, so each block starts with a copy +//! of the previous one's tail; keeping that here means neither the radio nor +//! the demodulator has to know about it. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const Io = std.Io; + +const mag_buf = @import("mag_buf.zig"); +const MagBuf = mag_buf.MagBuf; + +/// How the queue is sized. +pub const Options = struct { + /// How many buffers to preallocate. More buffering absorbs longer stalls + /// at the cost of latency and memory. + buffer_count: usize = mag_buf.default_block_count, + /// Samples per buffer, including the leading overlap. + buffer_size: usize = mag_buf.default_block_samples + mag_buf.trailing_samples, + /// Samples of overlap between adjacent buffers. + overlap: usize = mag_buf.trailing_samples, +}; + +/// A condition variable that can time out. +/// +/// `Io.Condition` has no timed wait, and the queue needs one: a consumer must +/// be able to go and do its periodic work even when the radio has gone quiet. +/// This is the same epoch-counter trick `Io.Condition` uses internally, with +/// the timeout passed through to the futex. +const Signal = struct { + epoch: std.atomic.Value(u32) = .init(0), + + /// Release `mutex`, wait to be signalled or for the timeout to pass, then + /// take `mutex` again. Spurious wakeups are possible, so callers must + /// re-check the condition they were waiting on. + fn wait(self: *Signal, io: Io, mutex: *Io.Mutex, timeout: Io.Timeout) void { + const seen = self.epoch.load(.acquire); + mutex.unlock(io); + defer mutex.lockUncancelable(io); + io.futexWaitTimeout(u32, &self.epoch.raw, seen, timeout) catch {}; + } + + /// Wake everything waiting. The caller should hold the mutex. + fn broadcast(self: *Signal, io: Io) void { + _ = self.epoch.fetchAdd(1, .release); + io.futexWake(u32, &self.epoch.raw, std.math.maxInt(u32)); + } +}; + +/// A fixed pool of sample buffers, and the queue of the filled ones. +pub const Fifo = struct { + gpa: Allocator, + + /// The buffers themselves, and the one allocation their samples live in. + buffers: []MagBuf, + storage: []u16, + + /// Guards everything below. + mutex: Io.Mutex = .init, + /// Signalled when a buffer is queued. + not_empty: Signal = .{}, + /// Signalled when the queue becomes empty. + empty: Signal = .{}, + /// Signalled when a buffer returns to the free list. + free_available: Signal = .{}, + + /// Buffers nobody is using, most recently released first. + free: std.ArrayList(*MagBuf), + /// Buffers waiting to be demodulated, oldest first. + queued: std.ArrayList(*MagBuf), + /// Set once shutdown has begun; every wait returns immediately after. + halted: bool = false, + + /// The tail of the last enqueued block, to be copied into the front of + /// the next one. + overlap: []u16, + + pub fn init(gpa: Allocator, options: Options) Allocator.Error!Fifo { + std.debug.assert(options.buffer_size > options.overlap); + std.debug.assert(options.overlap >= mag_buf.minimum_overlap); + + const storage = try gpa.alloc(u16, options.buffer_count * options.buffer_size); + errdefer gpa.free(storage); + @memset(storage, 0); + + const buffers = try gpa.alloc(MagBuf, options.buffer_count); + errdefer gpa.free(buffers); + + const overlap = try gpa.alloc(u16, options.overlap); + errdefer gpa.free(overlap); + @memset(overlap, 0); + + var free: std.ArrayList(*MagBuf) = try .initCapacity(gpa, options.buffer_count); + errdefer free.deinit(gpa); + const queued: std.ArrayList(*MagBuf) = try .initCapacity(gpa, options.buffer_count); + + for (buffers, 0..) |*buf, i| { + buf.* = .{ + .data = storage[i * options.buffer_size ..][0..options.buffer_size], + .valid = 0, + .overlap = options.overlap, + .sample_timestamp = 0, + .system_timestamp_ms = 0, + .discontinuous = false, + .dropped = 0, + .level = .{ .mean_level = 0, .mean_power = 0 }, + }; + free.appendAssumeCapacity(buf); + } + + return .{ + .gpa = gpa, + .buffers = buffers, + .storage = storage, + .free = free, + .queued = queued, + .overlap = overlap, + }; + } + + /// Not safe to call while anything is still using the queue; halt and + /// join first. + pub fn deinit(self: *Fifo) void { + self.free.deinit(self.gpa); + self.queued.deinit(self.gpa); + self.gpa.free(self.overlap); + self.gpa.free(self.buffers); + self.gpa.free(self.storage); + self.* = undefined; + } + + /// Take a buffer to fill. + /// + /// Returns null if the queue has been halted, or if no buffer became free + /// within `timeout` — which is the producer's signal that the consumer + /// has fallen behind and samples are about to be dropped. + pub fn acquire(self: *Fifo, io: Io, timeout: Io.Timeout) ?*MagBuf { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + const deadline = timeout.toDeadline(io); + while (!self.halted and self.free.items.len == 0) { + if (deadline == .none) return null; // non-blocking + const before = self.free.items.len; + self.free_available.wait(io, &self.mutex, deadline); + if (self.free.items.len == before and timedOut(io, deadline)) return null; + } + if (self.halted) return null; + + const buf = self.free.pop().?; + buf.valid = buf.overlap; + buf.sample_timestamp = 0; + buf.system_timestamp_ms = 0; + buf.discontinuous = false; + buf.dropped = 0; + buf.level = .{ .mean_level = 0, .mean_power = 0 }; + return buf; + } + + /// Hand a filled buffer over to the consumer. + /// + /// The caller should have set everything but the leading overlap, which + /// is filled in here from the previous block. + pub fn enqueue(self: *Fifo, io: Io, buf: *MagBuf) void { + std.debug.assert(buf.valid <= buf.data.len); + std.debug.assert(buf.valid >= buf.overlap); + + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + if (self.halted) { + self.free.appendAssumeCapacity(buf); + return; + } + + if (buf.discontinuous) { + // Samples were lost, so the previous block's tail does not lead + // into this one. Silence is a better lie than stale samples: it + // decodes to nothing rather than to a message that was never + // sent. + @memset(buf.data[0..buf.overlap], 0); + } else { + @memcpy(buf.data[0..buf.overlap], self.overlap); + } + + @memcpy(self.overlap, buf.data[buf.valid - buf.overlap ..][0..buf.overlap]); + + self.queued.appendAssumeCapacity(buf); + if (self.queued.items.len == 1) self.not_empty.broadcast(io); + } + + /// Take the oldest filled buffer. + /// + /// Returns null if the queue has been halted, or if nothing arrived + /// within `timeout`. + pub fn dequeue(self: *Fifo, io: Io, timeout: Io.Timeout) ?*MagBuf { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + const deadline = timeout.toDeadline(io); + while (!self.halted and self.queued.items.len == 0) { + if (deadline == .none) return null; + self.not_empty.wait(io, &self.mutex, deadline); + if (self.queued.items.len == 0 and timedOut(io, deadline)) return null; + } + if (self.halted) return null; + + const buf = self.queued.orderedRemove(0); + if (self.queued.items.len == 0) self.empty.broadcast(io); + return buf; + } + + /// Give a buffer back once it has been demodulated. + pub fn release(self: *Fifo, io: Io, buf: *MagBuf) void { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + const was_empty = self.free.items.len == 0; + self.free.appendAssumeCapacity(buf); + if (was_empty) self.free_available.broadcast(io); + } + + /// Block until everything queued has been taken. + pub fn drain(self: *Fifo, io: Io) void { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + while (self.queued.items.len > 0 and !self.halted) { + self.empty.wait(io, &self.mutex, .none); + } + } + + /// Begin shutting down: every waiter wakes and every later call returns + /// immediately. + pub fn halt(self: *Fifo, io: Io) void { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + + while (self.queued.pop()) |buf| self.free.appendAssumeCapacity(buf); + self.halted = true; + + self.not_empty.broadcast(io); + self.empty.broadcast(io); + self.free_available.broadcast(io); + } + + /// How many buffers are waiting to be demodulated, which is how far + /// behind the consumer is. + pub fn queueDepth(self: *Fifo, io: Io) usize { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + return self.queued.items.len; + } +}; + +/// A timeout is a non-blocking poll when it is zero, and unbounded when it is +/// `.none`; anything else is a real deadline. +fn timedOut(io: Io, deadline: Io.Timeout) bool { + const timestamp = deadline.toTimestamp(io) orelse return false; + return Io.Timestamp.now(io, timestamp.clock).nanoseconds >= timestamp.raw.nanoseconds; +} + +/// A timeout of a number of milliseconds, which is how the rest of the +/// program talks about time. +pub fn millis(ms: u64) Io.Timeout { + return .{ + .duration = .{ + .raw = .fromMilliseconds(@intCast(ms)), + // `awake` rather than `real`: a timeout should not be affected by + // somebody setting the system clock. + .clock = .awake, + }, + }; +} + +const testing = std.testing; + +fn testFifo(gpa: Allocator) !Fifo { + return .init(gpa, .{ .buffer_count = 3, .buffer_size = 1024, .overlap = mag_buf.minimum_overlap }); +} + +test "a buffer goes round the loop" { + var threaded: Io.Threaded = .init(testing.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + var fifo = try testFifo(testing.allocator); + defer fifo.deinit(); + + const buf = fifo.acquire(io, millis(100)).?; + try testing.expectEqual(mag_buf.minimum_overlap, buf.valid); + try testing.expectEqual(@as(usize, 2), fifo.free.items.len); + + buf.valid = 1024; + fifo.enqueue(io, buf); + try testing.expectEqual(@as(usize, 1), fifo.queueDepth(io)); + + const got = fifo.dequeue(io, millis(100)).?; + try testing.expectEqual(buf, got); + try testing.expectEqual(@as(usize, 0), fifo.queueDepth(io)); + + fifo.release(io, got); + try testing.expectEqual(@as(usize, 3), fifo.free.items.len); +} + +test "buffers come back in order" { + var threaded: Io.Threaded = .init(testing.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + var fifo = try testFifo(testing.allocator); + defer fifo.deinit(); + + var enqueued: [3]*MagBuf = undefined; + for (&enqueued, 0..) |*slot, i| { + const buf = fifo.acquire(io, millis(100)).?; + buf.valid = 1024; + buf.sample_timestamp = i; + fifo.enqueue(io, buf); + slot.* = buf; + } + + // The pool is exhausted; asking for another times out rather than + // blocking forever. + try testing.expectEqual(@as(?*MagBuf, null), fifo.acquire(io, millis(10))); + + for (enqueued) |expected| { + const got = fifo.dequeue(io, millis(100)).?; + try testing.expectEqual(expected.sample_timestamp, got.sample_timestamp); + fifo.release(io, got); + } +} + +test "the overlap carries from one block to the next" { + var threaded: Io.Threaded = .init(testing.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + var fifo = try testFifo(testing.allocator); + defer fifo.deinit(); + + const overlap = mag_buf.minimum_overlap; + + const first = fifo.acquire(io, millis(100)).?; + first.valid = 1024; + first.discontinuous = true; + for (first.data[overlap..], 0..) |*sample, i| sample.* = @intCast(1000 + i); + fifo.enqueue(io, first); + + // A discontinuous block has no previous tail to lead into it, so its + // overlap is silence. + for (first.data[0..overlap]) |sample| try testing.expectEqual(@as(u16, 0), sample); + + const second = fifo.acquire(io, millis(100)).?; + _ = fifo.dequeue(io, millis(100)).?; + second.valid = 1024; + @memset(second.data[overlap..], 7); + fifo.enqueue(io, second); + + // The second block's overlap is the first block's tail. + try testing.expectEqualSlices(u16, first.data[1024 - overlap ..][0..overlap], second.data[0..overlap]); +} + +test "halting wakes everyone and returns the buffers" { + var threaded: Io.Threaded = .init(testing.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + var fifo = try testFifo(testing.allocator); + defer fifo.deinit(); + + const buf = fifo.acquire(io, millis(100)).?; + buf.valid = 1024; + fifo.enqueue(io, buf); + + fifo.halt(io); + + try testing.expectEqual(@as(usize, 3), fifo.free.items.len); + try testing.expectEqual(@as(?*MagBuf, null), fifo.dequeue(io, millis(1000))); + try testing.expectEqual(@as(?*MagBuf, null), fifo.acquire(io, millis(1000))); + + // Enqueueing after a halt just returns the buffer rather than losing it. + fifo.halted = false; + const another = fifo.acquire(io, millis(100)).?; + fifo.halted = true; + another.valid = 1024; + fifo.enqueue(io, another); + try testing.expectEqual(@as(usize, 3), fifo.free.items.len); +} + +test "a producer and a consumer make progress at the same time" { + var threaded: Io.Threaded = .init(testing.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + var fifo = try testFifo(testing.allocator); + defer fifo.deinit(); + + const block_count = 200; + + const Producer = struct { + fn run(f: *Fifo, i: Io) void { + for (0..block_count) |n| { + const buf = f.acquire(i, millis(5000)) orelse return; + buf.valid = 1024; + buf.sample_timestamp = n; + f.enqueue(i, buf); + } + } + }; + + var group: Io.Group = .init; + defer group.cancel(io); + try group.concurrent(io, Producer.run, .{ &fifo, io }); + + // The pool holds three buffers, so the consumer has to keep up for the + // producer to get through two hundred blocks at all. + for (0..block_count) |n| { + const buf = fifo.dequeue(io, millis(5000)) orelse return error.TimedOut; + try testing.expectEqual(n, buf.sample_timestamp); + fifo.release(io, buf); + } + + try group.await(io); +} diff --git a/src/mag_buf.zig b/src/mag_buf.zig index f7365b7..288e74f 100644 --- a/src/mag_buf.zig +++ b/src/mag_buf.zig @@ -26,8 +26,6 @@ //! ``` const std = @import("std"); -const Allocator = std.mem.Allocator; - const dsp = @import("dsp.zig"); const modes = @import("modes.zig"); @@ -43,6 +41,19 @@ pub const receive_clock_rate = 12_000_000; /// the preamble it looks past, one sample of slack, and the longest message. pub const minimum_overlap = 19 + 1 + 269; +/// The overlap actually used: the preamble, the longest message, and sixteen +/// bits of margin, converted from microseconds to samples. +pub const trailing_samples = (8 + 112 + 16) * sample_rate / 1_000_000; + +/// Samples per block. About a twentieth of a second at 2.4 MHz, and exactly +/// what one USB transfer from an RTL-SDR holds. +pub const default_block_samples = 16 * 16384 / 2; + +/// How many blocks to keep in flight. Fewer than the radio has transfers +/// outstanding, so that running out of blocks throttles the radio rather than +/// the other way about. +pub const default_block_count = 12; + /// One block of magnitude samples. pub const MagBuf = struct { /// The samples. Its length is the allocated size; `valid` says how much @@ -85,15 +96,6 @@ pub const MagBuf = struct { return self.data[self.overlap..]; } - /// Copy this block's trailing overlap into the front of the next one, and - /// carry the timestamps forward accordingly. - pub fn carryOverlapTo(self: *const MagBuf, next: *MagBuf) void { - std.debug.assert(next.overlap == self.overlap); - @memcpy(next.data[0..self.overlap], self.data[self.valid - self.overlap ..][0..self.overlap]); - next.sample_timestamp = self.sample_timestamp + - elapsedClock(self.valid - self.overlap); - } - /// How many receiver-clock ticks a number of samples takes: five ticks /// per sample at 2.4 MHz. pub fn elapsedClock(sample_count: usize) u64 { @@ -126,33 +128,6 @@ test "the searchable region stops short of the trailing overlap" { try testing.expectEqual(@as(usize, 700), buf.writable().len); } -test "the overlap carries forward with the clock" { - var first_data: [100]u16 = @splat(0); - var second_data: [100]u16 = @splat(0); - for (&first_data, 0..) |*sample, i| sample.* = @intCast(i); - - const first: MagBuf = .{ - .data = &first_data, - .valid = 100, - .overlap = 10, - .sample_timestamp = 1000, - .system_timestamp_ms = 0, - .discontinuous = false, - .dropped = 0, - .level = .{ .mean_level = 0, .mean_power = 0 }, - }; - var second = first; - second.data = &second_data; - - first.carryOverlapTo(&second); - - // The last ten samples of the first block are now the first ten of the - // second. - try testing.expectEqualSlices(u16, first_data[90..100], second_data[0..10]); - // And the second block starts 90 samples, or 450 clock ticks, later. - try testing.expectEqual(@as(u64, 1000 + 450), second.sample_timestamp); -} - test "clock arithmetic is in twelfths of a microsecond" { try testing.expectEqual(@as(u64, 5), MagBuf.elapsedClock(1)); try testing.expectEqual(@as(u64, 12_000_000), MagBuf.elapsedClock(sample_rate)); diff --git a/src/main.zig b/src/main.zig index b286728..a0a5a24 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,9 +1,314 @@ +// 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 +//! dump1090: the program. +//! +//! Two tasks run concurrently. One fills blocks of samples from the radio and +//! puts them on a queue; the other takes them off, demodulates, decodes, +//! tracks and writes output. They are separate because a radio will not wait +//! — a USB transfer that is not collected promptly is a transfer of samples +//! that no longer exist — while the work of turning samples into aircraft is +//! bursty and occasionally slow. + const std = @import("std"); +const Io = std.Io; + const dump1090 = @import("dump1090"); +const convert = dump1090.convert; +const crc = dump1090.crc; +const demod_2400 = dump1090.demod_2400; +const display = dump1090.display; +const fifo = dump1090.fifo; +const mag_buf = dump1090.mag_buf; +const message = dump1090.message; +const mode_s = dump1090.mode_s; +const output = dump1090.output; +const sdr = dump1090.sdr; +const track = dump1090.track; + +const Message = message.Message; + +/// Everything the program was asked to do. +const Config = struct { + source: sdr.Options = .{}, + decode: mode_s.Options = .{}, + receiver: track.Receiver = .{}, + + /// Write every frame to standard output in the AVR text format. + raw: bool = false, + /// Prefix raw output with the receiver's clock. + mlat_timestamps: bool = false, + /// Also demodulate Mode A/C replies. + mode_ac: bool = false, + /// Say nothing on standard output except what was asked for. + quiet: bool = false, +}; + +const usage = + \\dump1090: a Mode S and ADS-B decoder. + \\ + \\ --device-type where to get samples from: none, ifile + \\ --ifile read samples from a file, or "-" for standard input + \\ --iformat the sample format: UC8, SC16, SC16Q11 + \\ --throttle read a recording at the speed it was captured + \\ + \\ --raw write every frame to standard output as hex + \\ --mlat prefix raw output with the receiver clock + \\ --modeac also decode Mode A/C replies + \\ --fix correct one-bit errors + \\ --fix-2bit correct one- and two-bit errors + \\ --no-fix do not correct any bit errors (the default) + \\ --no-fix-df do not try to correct the downlink format field + \\ --enable-df24 decode Comm-D extended length messages + \\ + \\ --lat the receiver's latitude + \\ --lon the receiver's longitude + \\ --max-range the furthest an aircraft can plausibly be + \\ + \\ --quiet say nothing but the requested output + \\ --help this message + \\ +; + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const io = init.io; + + var stderr_buf: [4096]u8 = undefined; + var stderr_writer = Io.File.stderr().writer(io, &stderr_buf); + const stderr = &stderr_writer.interface; + defer stderr.flush() catch {}; + + const config = parseArgs(gpa, init.minimal.args, stderr) catch |err| switch (err) { + error.HelpRequested => { + try stderr.writeAll(usage); + try stderr.flush(); + return; + }, + else => return err, + }; + + try run(gpa, io, stderr, config); +} + +fn parseArgs(gpa: std.mem.Allocator, argv: std.process.Args, stderr: *Io.Writer) !Config { + var config: Config = .{}; + + var args: std.process.Args.Iterator = try .initAllocator(argv, gpa); + defer args.deinit(); + + // Skip the program name. + _ = args.next(); + + while (args.next()) |option| { + if (eq(option, "--help") or eq(option, "-h")) return error.HelpRequested; + + if (eq(option, "--device-type")) { + const value = try nextValue(&args, stderr, option); + config.source.kind = sdr.Kind.parse(value) orelse { + try stderr.print("unknown device type '{s}'\n", .{value}); + return error.BadArgument; + }; + } else if (eq(option, "--ifile")) { + config.source.path = try nextValue(&args, stderr, option); + config.source.kind = .ifile; + } else if (eq(option, "--iformat")) { + const value = try nextValue(&args, stderr, option); + config.source.format = convert.InputFormat.parse(value) orelse { + try stderr.print("unknown sample format '{s}'\n", .{value}); + return error.BadArgument; + }; + } else if (eq(option, "--throttle")) { + config.source.throttle = true; + } else if (eq(option, "--raw")) { + config.raw = true; + } else if (eq(option, "--mlat")) { + config.mlat_timestamps = true; + } else if (eq(option, "--modeac")) { + config.mode_ac = true; + } else if (eq(option, "--no-fix")) { + config.decode.fix_bits = .none; + } else if (eq(option, "--fix")) { + // Never weakens a stronger setting given earlier. + if (config.decode.fix_bits == .none) config.decode.fix_bits = .one; + } else if (eq(option, "--fix-2bit")) { + config.decode.fix_bits = .two; + } else if (eq(option, "--no-fix-df")) { + config.decode.fix_df = false; + } else if (eq(option, "--enable-df24")) { + config.decode.enable_df24 = true; + } else if (eq(option, "--lat")) { + const value = try nextValue(&args, stderr, option); + const latitude = try parseFloat(stderr, option, value); + config.receiver.position = .{ + .latitude = latitude, + .longitude = if (config.receiver.position) |p| p.longitude else 0, + }; + } else if (eq(option, "--lon")) { + const value = try nextValue(&args, stderr, option); + const longitude = try parseFloat(stderr, option, value); + config.receiver.position = .{ + .latitude = if (config.receiver.position) |p| p.latitude else 0, + .longitude = longitude, + }; + } else if (eq(option, "--max-range")) { + const value = try nextValue(&args, stderr, option); + config.receiver.max_range = try parseFloat(stderr, option, value) * 1852.0; + } else if (eq(option, "--quiet")) { + config.quiet = true; + } else { + try stderr.print("unknown option '{s}'\n", .{option}); + return error.BadArgument; + } + } + + return config; +} + +fn eq(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +fn nextValue(args: *std.process.Args.Iterator, stderr: *Io.Writer, option: []const u8) ![]const u8 { + return args.next() orelse { + try stderr.print("{s} needs a value\n", .{option}); + return error.BadArgument; + }; +} + +fn parseFloat(stderr: *Io.Writer, option: []const u8, value: []const u8) !f64 { + return std.fmt.parseFloat(f64, value) catch { + try stderr.print("{s}: '{s}' is not a number\n", .{ option, value }); + return error.BadArgument; + }; +} + +/// The demodulating half of the program, and the sink the demodulator calls +/// back into. +const Receiver = struct { + io: Io, + config: Config, + decoder: *mode_s.Decoder, + tracker: *track.Tracker, + out: *Io.Writer, + + /// How many messages were decoded, for the closing summary. + message_count: u64 = 0, + + /// Called by the demodulator for each decoded frame. + pub fn onMessage(self: *Receiver, mm: *Message) void { + self.message_count += 1; + + const aircraft = self.tracker.update(mm) catch |err| switch (err) { + error.OutOfMemory => null, + }; + + _ = aircraft; + + // The terminal display shows everything the decoder accepted; the + // network outputs are the ones that filter. + if (self.config.raw and !self.config.quiet) { + display.raw(self.out, mm, self.config.mlat_timestamps) catch {}; + } + } + + /// Called with runs of samples, labelled as message or not. The adaptive + /// gain control will want these; nothing does yet. + pub fn onSamples(self: *Receiver, magnitudes: []const u16, mm: ?*const Message) void { + _ = self; + _ = magnitudes; + _ = mm; + } +}; + +fn run(gpa: std.mem.Allocator, io: Io, stderr: *Io.Writer, config: Config) !void { + var decoder: mode_s.Decoder = init: { + if (config.decode.fix_bits == .two and !config.quiet) { + // Building the two-bit tables enumerates about six million error + // patterns, which takes a noticeable moment. + try stderr.writeAll("Preparing error correction tables... "); + try stderr.flush(); + } + const d: mode_s.Decoder = try .init(gpa, config.decode); + if (config.decode.fix_bits == .two and !config.quiet) { + try stderr.writeAll("done.\n"); + try stderr.flush(); + } + break :init d; + }; + defer decoder.deinit(gpa); + + var tracker: track.Tracker = .init(gpa, config.receiver); + defer tracker.deinit(); + + var demodulator: demod_2400.Demodulator = .init(&decoder, .{ + .fix_bits = config.decode.fix_bits, + .fix_df = config.decode.fix_df, + .enable_df24 = config.decode.enable_df24, + }); + + var source: sdr.Source = sdr.Source.open(gpa, io, config.source) catch |err| { + try stderr.print("could not open the sample source: {t}\n", .{err}); + return err; + }; + defer source.close(gpa, io); + + var queue: fifo.Fifo = try .init(gpa, .{}); + defer queue.deinit(); + + var out_buf: [64 * 1024]u8 = undefined; + var out_writer = Io.File.stdout().writer(io, &out_buf); + const out = &out_writer.interface; + defer out.flush() catch {}; + + var receiver: Receiver = .{ + .io = io, + .config = config, + .decoder = &decoder, + .tracker = &tracker, + .out = out, + }; + + var running: std.atomic.Value(bool) = .init(true); + + var group: Io.Group = .init; + defer group.cancel(io); + try group.concurrent(io, sdr.Source.run, .{ &source, io, &queue, &running }); + + // A source that produces nothing would leave this loop waiting forever. + if (!source.producesSamples()) { + running.store(false, .release); + queue.halt(io); + try group.await(io); + try stderr.writeAll("no sample source configured; nothing to do\n"); + return; + } + + while (queue.dequeue(io, fifo.millis(100))) |buf| { + demodulator.demodulate(buf, &receiver); + if (config.mode_ac) demodulator.demodulateModeAc(buf, &receiver); + queue.release(io, buf); + + // Housekeeping runs between blocks; it rate-limits itself internally. + const now = sdr.nowMillis(io); + tracker.periodic(now); + decoder.filter.expire(now); + + try out.flush(); + } + + running.store(false, .release); + queue.halt(io); + try group.await(io); + try out.flush(); -pub fn main() !void { - return error.NotImplementedYet; + if (!config.quiet) { + const counters = demodulator.counters; + try stderr.print( + "{d} messages decoded from {d} candidate preambles ({d} aircraft)\n", + .{ receiver.message_count, counters.preambles, tracker.counters.unique_aircraft }, + ); + } } diff --git a/src/mode_s.zig b/src/mode_s.zig index e468fe1..8cdd5ae 100644 --- a/src/mode_s.zig +++ b/src/mode_s.zig @@ -41,8 +41,10 @@ const ScoreRank = Message.ScoreRank; /// How the decoder should behave. pub const Options = struct { - /// How many bit errors to try to correct. - fix_bits: crc.FixBits = .one, + /// How many bit errors to try to correct. Off by default, as upstream + /// has it: a corrected frame is a guess, and a receiver feeding an + /// aggregator should be forwarding what it heard. + fix_bits: crc.FixBits = .none, /// Whether to attempt corrections to the downlink format field as well as /// to the body. Correcting the format is much more expensive, because a /// frame that looks like an unreadable format has to be checked at both diff --git a/src/output.zig b/src/output.zig new file mode 100644 index 0000000..2229268 --- /dev/null +++ b/src/output.zig @@ -0,0 +1,279 @@ +// 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 + +//! The wire formats a decoded frame is passed on in. +//! +//! Both of these carry the frame itself rather than the decode, because what +//! is downstream of a receiver is usually another decoder — an aggregator, a +//! multilateration server, another copy of this program — which would rather +//! have the bits and make its own judgements. What the receiver adds is the +//! two things only it knows: when the frame arrived, on its own clock, and +//! how strong it was. +//! +//! Each format also decides *which* frames to pass on, and those rules are +//! here with them, since they are as much part of the format's contract as +//! the byte layout. The distinction that matters is `verbatim` against +//! `cooked`: verbatim output forwards the frame exactly as received, error +//! correction and all left undone, so that the receiver downstream can make +//! its own decision; cooked output forwards the corrected frame and drops +//! the ones this receiver does not believe. + +const std = @import("std"); +const Io = std.Io; + +const message = @import("message.zig"); +const modes = @import("modes.zig"); +const Message = message.Message; + +/// Whether a frame is worth passing on in a cooked stream. +/// +/// `track_is_reliable` is what the tracker thinks of the aircraft, or null if +/// the frame was never tracked. An unreliable frame about an aircraft nobody +/// believes in is very likely noise that decoded. +pub fn isCooked(mm: *const Message, track_is_reliable: ?bool) bool { + // Two-bit correction is a guess too far to hand to somebody else as + // though it were a received frame. + if (mm.corrected_bits >= 2) return false; + + if (track_is_reliable) |reliable| { + if (!reliable and !mm.reliable) return false; + } + + return true; +} + +/// The AVR text format: a line of hex per frame. +/// +/// The oldest of the formats and the easiest to read by eye, which is what it +/// is for. A frame is written as `*8D4840D6...;`, or with a leading +/// `@`-prefixed timestamp when the receiver's clock is being passed on too. +pub const raw = struct { + /// Write one frame. + /// + /// `with_timestamp` prefixes the receiver's 12 MHz clock, which is what a + /// multilateration client needs and what nothing else wants. + pub fn write(w: *Io.Writer, mm: *const Message, with_timestamp: bool) Io.Writer.Error!void { + if (with_timestamp and mm.timestamp_12mhz != 0) { + try w.print("@{X:0>12}", .{mm.timestamp_12mhz}); + } else { + try w.writeByte('*'); + } + + for (mm.bytes()) |byte| try w.print("{X:0>2}", .{byte}); + try w.writeAll(";\n"); + } + + /// Sent when nothing else has been for a while, so that a reader can tell + /// a quiet receiver from a dead one. + pub const heartbeat = "*0000;\n"; + + /// Whether to forward a frame at all. Multilateration results are never + /// forwarded in this format: they are not received frames and the format + /// has no way of saying so. + pub fn shouldSend(mm: *const Message, track_is_reliable: ?bool) bool { + if (mm.source == .mlat) return false; + return isCooked(mm, track_is_reliable); + } +}; + +/// The Beast binary format, as the Mode-S Beast and the Radarcape produce it. +/// +/// A frame becomes an escape byte, a type, a six-byte timestamp, a signal +/// level and the frame itself. Any `0x1a` in the payload is doubled, which is +/// what makes the escape byte findable again after a resynchronisation. +pub const beast = struct { + /// The byte that begins every frame, and which is doubled when it occurs + /// inside one. + pub const escape = 0x1a; + + /// What kind of frame follows the escape. + pub const Kind = enum(u8) { + mode_ac = '1', + mode_s_short = '2', + mode_s_long = '3', + + /// The kind a frame of this many bytes is, or null if no Beast frame + /// is that size. + pub fn fromLength(len: usize) ?Kind { + return switch (len) { + 2 => .mode_ac, + 7 => .mode_s_short, + 14 => .mode_s_long, + else => null, + }; + } + }; + + /// Write one frame. + /// + /// `frame` is the bytes to send, which is the corrected frame for cooked + /// output and the received one for verbatim. + pub fn write(w: *Io.Writer, timestamp: u64, signal_level: f64, frame: []const u8) Io.Writer.Error!void { + const kind = Kind.fromLength(frame.len) orelse return; + + try w.writeByte(escape); + try w.writeByte(@intFromEnum(kind)); + + // The timestamp is six bytes, big-endian: the low 48 bits of the + // receiver's 12 MHz clock, which wraps about every six and a half + // hours. + var shift: u6 = 40; + while (true) : (shift -= 8) { + try writeEscaped(w, @truncate(timestamp >> shift)); + if (shift == 0) break; + } + + try writeEscaped(w, encodeSignalLevel(signal_level)); + for (frame) |byte| try writeEscaped(w, byte); + } + + /// The signal level as one byte: the amplitude rather than the power, so + /// that the scale is linear in what a receiver's AGC sees. + /// + /// Zero is reserved for "no signal information", so a frame that really + /// was received, however faintly, is reported as at least one. + pub fn encodeSignalLevel(signal_level: f64) u8 { + const scaled = @round(@sqrt(signal_level) * 255); + if (scaled > 255) return 255; + if (scaled < 1) return if (signal_level > 0) 1 else 0; + return @intFromFloat(scaled); + } + + fn writeEscaped(w: *Io.Writer, byte: u8) Io.Writer.Error!void { + try w.writeByte(byte); + if (byte == escape) try w.writeByte(escape); + } + + /// A Mode A/C frame of all zeros, sent to keep a quiet connection alive. + pub const heartbeat = [_]u8{ escape, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + /// Whether to forward a frame in a cooked Beast stream. + pub fn shouldSendCooked(mm: *const Message, track_is_reliable: ?bool, forward_mlat: bool) bool { + if (mm.source == .mlat and !forward_mlat) return false; + return isCooked(mm, track_is_reliable); + } + + /// Whether to forward a frame in a verbatim Beast stream, which passes on + /// everything it can. + pub fn shouldSendVerbatim(mm: *const Message, forward_mlat: bool) bool { + return !(mm.source == .mlat and !forward_mlat); + } +}; + +const testing = std.testing; + +fn testMessage(frame: []const u8) Message { + var mm: Message = .empty; + @memcpy(mm.msg[0..frame.len], frame); + @memcpy(mm.verbatim[0..frame.len], frame); + mm.len = @intCast(frame.len); + mm.format = .{ .mode_s = @truncate(frame[0] >> 3) }; + return mm; +} + +const df17 = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; + +test "raw output is a line of hex" { + var buf: [128]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + + var mm = testMessage(&df17); + try raw.write(&w, &mm, false); + try testing.expectEqualStrings("*8D4840D6202CC371C32CE0576098;\n", w.buffered()); +} + +test "raw output can carry the receiver clock" { + var buf: [128]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + + var mm = testMessage(&df17); + mm.timestamp_12mhz = 0x0123456789ab; + try raw.write(&w, &mm, true); + try testing.expectEqualStrings("@0123456789AB8D4840D6202CC371C32CE0576098;\n", w.buffered()); + + // A frame with no timestamp falls back to the plain form rather than + // claiming a time of zero. + var without = testMessage(&df17); + var second: Io.Writer = .fixed(&buf); + try raw.write(&second, &without, true); + try testing.expectEqual(@as(u8, '*'), second.buffered()[0]); +} + +test "Beast output is escape, type, timestamp, level, frame" { + var buf: [128]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + + try beast.write(&w, 0x0123456789ab, 0.25, &df17); + + const written = w.buffered(); + try testing.expectEqual(@as(u8, 0x1a), written[0]); + try testing.expectEqual(@as(u8, '3'), written[1]); + try testing.expectEqualSlices(u8, &.{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab }, written[2..8]); + // sqrt(0.25) * 255 = 127.5, rounded away from zero. + try testing.expectEqual(@as(u8, 128), written[8]); + try testing.expectEqualSlices(u8, &df17, written[9..]); +} + +test "Beast doubles the escape byte inside a frame" { + var buf: [128]u8 = undefined; + var w: Io.Writer = .fixed(&buf); + + // A short frame whose first byte is the escape byte, and a timestamp + // containing one too. + const frame = [_]u8{ 0x1a, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x1a }; + try beast.write(&w, 0x1a0000000000, 0, &frame); + + const written = w.buffered(); + try testing.expectEqual(@as(u8, 0x1a), written[0]); + try testing.expectEqual(@as(u8, '2'), written[1]); + // The first timestamp byte is 0x1a, so it is doubled. + try testing.expectEqualSlices(u8, &.{ 0x1a, 0x1a }, written[2..4]); + // Three escape bytes in the payload, so three extra bytes overall: two + // header, six timestamp plus one doubled, one level, seven payload plus + // three doubled. + try testing.expectEqual(@as(usize, 2 + 7 + 1 + 10), written.len); +} + +test "signal levels map onto a byte without losing a weak signal" { + try testing.expectEqual(@as(u8, 0), beast.encodeSignalLevel(0)); + try testing.expectEqual(@as(u8, 255), beast.encodeSignalLevel(1.0)); + try testing.expectEqual(@as(u8, 255), beast.encodeSignalLevel(2.0)); // clamped + // A real but very faint signal still reports as received. + try testing.expectEqual(@as(u8, 1), beast.encodeSignalLevel(1e-9)); +} + +test "Beast frame kinds follow the frame length" { + try testing.expectEqual(beast.Kind.mode_ac, beast.Kind.fromLength(2).?); + try testing.expectEqual(beast.Kind.mode_s_short, beast.Kind.fromLength(7).?); + try testing.expectEqual(beast.Kind.mode_s_long, beast.Kind.fromLength(14).?); + try testing.expectEqual(@as(?beast.Kind, null), beast.Kind.fromLength(9)); +} + +test "cooked output drops guesses and unbelieved frames" { + var mm = testMessage(&df17); + mm.reliable = true; + try testing.expect(isCooked(&mm, null)); + try testing.expect(isCooked(&mm, true)); + try testing.expect(isCooked(&mm, false)); // the frame vouches for itself + + mm.reliable = false; + try testing.expect(isCooked(&mm, null)); // never tracked, so no opinion + try testing.expect(isCooked(&mm, true)); + try testing.expect(!isCooked(&mm, false)); + + mm.reliable = true; + mm.corrected_bits = 2; + try testing.expect(!isCooked(&mm, true)); +} + +test "multilateration results are never sent as raw frames" { + var mm = testMessage(&df17); + mm.reliable = true; + mm.source = .mlat; + try testing.expect(!raw.shouldSend(&mm, null)); + // Beast will forward them, but only when asked to. + try testing.expect(!beast.shouldSendCooked(&mm, null, false)); + try testing.expect(beast.shouldSendCooked(&mm, null, true)); +} diff --git a/src/root.zig b/src/root.zig index da7ac3c..59c7284 100644 --- a/src/root.zig +++ b/src/root.zig @@ -16,12 +16,16 @@ pub const comm_b = @import("comm_b.zig"); pub const convert = @import("convert.zig"); pub const cpr = @import("cpr.zig"); pub const demod_2400 = @import("demod_2400.zig"); +pub const display = @import("display.zig"); pub const dsp = @import("dsp.zig"); +pub const fifo = @import("fifo.zig"); pub const geo = @import("geo.zig"); pub const icao_filter = @import("icao_filter.zig"); pub const mag_buf = @import("mag_buf.zig"); pub const message = @import("message.zig"); pub const mode_ac = @import("mode_ac.zig"); +pub const output = @import("output.zig"); +pub const sdr = @import("sdr.zig"); pub const track = @import("track.zig"); pub const mode_s = @import("mode_s.zig"); pub const modes = @import("modes.zig"); diff --git a/src/sdr.zig b/src/sdr.zig new file mode 100644 index 0000000..dfcc573 --- /dev/null +++ b/src/sdr.zig @@ -0,0 +1,247 @@ +// 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 convert = @import("convert.zig"); +const fifo = @import("fifo.zig"); +const mag_buf = @import("mag_buf.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, + + 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, +}; + +/// 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; + +/// A configured sample source. +pub const Source = union(Kind) { + none, + ifile: IFile, + + pub fn open(gpa: Allocator, io: Io, options: Options) OpenError!Source { + return switch (options.kind) { + .none => .none, + .ifile => .{ .ifile = try .open(gpa, io, options) }, + }; + } + + pub fn close(self: *Source, gpa: Allocator, io: Io) void { + switch (self.*) { + .none => {}, + .ifile => |*ifile| ifile.close(gpa, io), + } + self.* = .none; + } + + /// 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), + } + } + + /// 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; + } +}; + +/// 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, + + 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; + var reader = self.file.reader(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, + ); + + var got: usize = 0; + while (got < wanted) { + const n = reader.interface.readSliceShort(self.read_buf[got..wanted]) catch 0; + if (n == 0) break; + got += n; + } + + const samples = got / bytes_per_sample; + buf.level = self.converter.convertAndMeasure( + self.read_buf[0 .. samples * bytes_per_sample], + buf.data[buf.overlap..][0..samples], + ); + 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 (samples == 0 or got < wanted) break; // end of the recording + } + + // 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(@as(?Kind, null), Kind.parse("rtlsdr")); +} + +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)); +}