// 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); }