// 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 builtin = @import("builtin"); const std = @import("std"); const Io = std.Io; const datetime = @import("datetime"); const build_options = @import("build_options"); const dump1090 = @import("dump1090"); const adaptive = dump1090.adaptive; const Log = dump1090.log.Log; const adept = dump1090.adept; const convert = dump1090.convert; const crc = dump1090.crc; const demod_2400 = dump1090.demod_2400; const display = dump1090.display; const fifo = dump1090.fifo; const fmt = dump1090.fmt; const mag_buf = dump1090.mag_buf; const input = dump1090.input; const json = dump1090.json; const message = dump1090.message; const mode_s = dump1090.mode_s; const net = dump1090.net; const output = dump1090.output; const sdr = dump1090.sdr; const config_mod = dump1090.config; const Config = config_mod.Config; const stats = dump1090.stats; const track = dump1090.track; const Message = message.Message; /// What this build calls itself, in the version field of `receiver.json`. pub const version = "zig-dump1090 0.1.0-dev"; /// Set from the signal handler when the program has been asked to stop, and /// which signal it was. The handler does nothing else: the message is logged /// and the shutdown run from the main loop, where writing to a buffered /// stream and taking a lock are allowed. var caught_signal: std.atomic.Value(u32) = .init(0); fn onSignal(sig: std.posix.SIG) callconv(.c) void { caught_signal.store(@intFromEnum(sig), .release); // Put the default handler back, so that a second one gets through if the // clean shutdown gets stuck. Upstream does the same, for the same reason. var action: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.DFL }, .mask = std.posix.sigemptyset(), .flags = 0, }; std.posix.sigaction(sig, &action, null); } fn installSignalHandlers() void { if (builtin.os.tag == .windows) return; var action: std.posix.Sigaction = .{ .handler = .{ .handler = onSignal }, .mask = std.posix.sigemptyset(), .flags = 0, }; std.posix.sigaction(.INT, &action, null); std.posix.sigaction(.TERM, &action, null); } /// Log a line about the program's own lifetime, stamped the way upstream /// stamps them. fn logWithTimestamp(l: *Log, zone: ?datetime.TimeZone, io: Io, comptime format: []const u8, args: anytype) void { // Rendered whole and handed over in one piece, because the timestamp and // the message have to reach the log together: writing them as two calls // would let another task's line land between them. var buf: [512]u8 = undefined; var w: Io.Writer = .fixed(&buf); stats.writeTimestamp(&w, zone, sdr.nowMillis(io)) catch return; w.writeAll(" ") catch return; w.print(format ++ "\n", args) catch return; l.write(w.buffered()); } /// How a run ended, which is also the exit status. /// /// Upstream returns 1 unless it was asked to stop, so a recording that plays /// to its end reports failure. That is surprising, and it is the contract /// every script written against dump1090 has been living with, so it is kept. const Outcome = enum { /// Asked to stop, by a signal. normal, /// Anything else, including reaching the end of a recording. abnormal, fn status(self: Outcome) u8 { return switch (self) { .normal => 0, .abnormal => 1, }; } }; /// The level `--snip` was given, which `parseArgs` leaves here on its way /// out. A global because the option takes effect before there is a `Config` /// to put it in, exactly as upstream runs it from inside its argument loop. var snip_level: i32 = 0; /// Copy an I/Q recording from `in` to `out`, dropping the quiet stretches. /// /// A sample counts as quiet when both its I and its Q are within `level` of /// the mid-point, and a run of them longer than a preamble is thrown away — /// which is how a recording of a whole afternoon becomes one small enough to /// keep as a test fixture without losing any of the messages in it. fn snip(in: *Io.Reader, out: *Io.Writer, level: i32) !void { // Two bytes at a time: one sample is an I and a Q. const preamble_samples = (8 * 2) * @sizeOf(u16); var quiet: u64 = 0; while (true) { const i = in.takeByte() catch break; const q = in.takeByte() catch break; if (@abs(@as(i32, i) - 127) < level and @abs(@as(i32, q) - 127) < level) { quiet += 1; if (quiet > preamble_samples) continue; } else { quiet = 0; } try out.writeByte(i); try out.writeByte(q); } } /// The banner `--version` prints, in upstream's shape: a boxed line naming /// the build, then what it was built with. Upstream also lists which of its /// generated SIMD implementations it chose at runtime; there is nothing to /// list here, because `@Vector` settles that when the program is compiled. fn writeVersion(w: *Io.Writer) Io.Writer.Error!void { const rule = "-" ** 77; try w.print("{s}\n", .{rule}); try w.print("| dump1090 ModeS Receiver {s: >45} |\n", .{version}); try w.print("| build options: {s: <58} |\n", .{if (build_options.rtlsdr) "ENABLE_RTLSDR" else ""}); try w.print("{s}\n", .{rule}); } const usage = \\dump1090: a Mode S and ADS-B decoder. \\ \\Settings live in a configuration file; the options below are the ones \\that describe a single run rather than how the receiver is set up. \\ \\ --config read settings from a file \\ \\ --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 \\ --snip copy stdin to stdout, dropping the quiet stretches \\ \\ --fix correct one-bit errors \\ --fix-2bit correct one- and two-bit errors \\ --no-fix do not correct any bit errors (the default) \\ --modeac also decode Mode A/C replies \\ \\ --raw write every frame to standard output as hex \\ --onlyaddr write only the ICAO addresses \\ --show-only show only this ICAO address \\ --quiet say nothing but the requested output \\ \\ --stats print a statistics report when stopping \\ --stats-every print one every s seconds \\ --stats-range include the range histogram in the report \\ \\ --version print the version banner \\ --help this message \\ \\Everything else -- the radio, the network outputs and inputs, the feeds \\to push to, the JSON files, and the adaptive gain control -- is set in \\the configuration file. See doc/dump1090.zon for a commented example. \\ ; pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; var stderr_buf: [4096]u8 = undefined; // Streaming rather than positional. `File.writer` prefers `pwrite`, which // writes at an offset this program tracks itself — and standard output and // standard error are then two writers each counting from zero into the // same file whenever the shell was asked for `> log 2>&1`, so whichever // wrote second would overwrite the other. Appending is what a program's // own output is expected to do. var stderr_writer = Io.File.stderr().writerStreaming(io, &stderr_buf); const stderr = &stderr_writer.interface; defer stderr.flush() catch {}; var config_source: ?[:0]u8 = null; defer if (config_source) |source| gpa.free(source); // Everything a configuration file contributes lives here, for as long as // the program does. var config_arena: std.heap.ArenaAllocator = .init(gpa); defer config_arena.deinit(); const config = parseArgs(gpa, config_arena.allocator(), io, init.minimal.args, stderr, &config_source) catch |err| switch (err) { error.HelpRequested => { try stderr.writeAll(usage); try stderr.flush(); return; }, error.SnipRequested => { var out_buf: [64 * 1024]u8 = undefined; var out_writer = Io.File.stdout().writerStreaming(io, &out_buf); var in_buf: [64 * 1024]u8 = undefined; var in_reader = Io.File.stdin().readerStreaming(io, &in_buf); try snip(&in_reader.interface, &out_writer.interface, snip_level); try out_writer.interface.flush(); return; }, error.VersionRequested => { try writeVersion(stderr); try stderr.flush(); return; }, else => return err, }; // The BaseStation output stamps every line with a local wall-clock time, // so the machine's zone has to be resolved before anything is written. // Reading the environment here rather than inside the library keeps the // library from going looking for globals behind our back. var zone = openLocalZone(gpa, io, init.environ_map); defer if (zone) |*z| z.deinit(gpa); installSignalHandlers(); const outcome = try run(gpa, io, stderr, config, zone); try stderr.flush(); if (outcome != .normal) std.process.exit(outcome.status()); } /// The machine's timezone, honouring `TZ` and `TZDIR`, or null if there is no /// timezone data to be had — a container image, say, where UTC is the honest /// answer rather than a reason to refuse to start. fn openLocalZone(gpa: std.mem.Allocator, io: Io, environ: *std.process.Environ.Map) ?datetime.TimeZone { if (!datetime.tzdb.system.available) return null; const directory = environ.get("TZDIR"); switch (datetime.tzdb.system.resolveTz(environ.get("TZ"))) { .local => return datetime.tzdb.system.loadLocal(io, gpa, null) catch null, .path => |path| return datetime.tzdb.system.loadLocal(io, gpa, path) catch null, .name => |name| { if (directory) |dir| return datetime.tzdb.system.load(io, gpa, dir, name) catch null; for (datetime.tzdb.system.search_directories) |dir| { return datetime.tzdb.system.load(io, gpa, dir, name) catch continue; } return null; }, // A bare POSIX rule with no file behind it, and the explicit request // for UTC, both end up here: neither is a zone to load. .rule, .utc => return null, } } fn parseArgs( gpa: std.mem.Allocator, /// Holds the strings a configuration file contributes, so it has to /// outlive the config this returns. arena: std.mem.Allocator, io: Io, argv: std.process.Args, stderr: *Io.Writer, /// The configuration file's text, which the result borrows paths and /// hosts from. The caller owns it and must keep it as long as the config. source_out: *?[:0]u8, ) !Config { var config: Config = .{}; // Grown as `--net-connector` is seen; handed to the config at the end. var connectors: std.ArrayList(net.Connector) = .empty; errdefer connectors.deinit(gpa); // Read before anything else is applied, so that a command-line option // overrides the file rather than the other way round. var args: std.process.Args.Iterator = try .initAllocator(argv, gpa); defer args.deinit(); // Skip the program name. _ = args.next(); // The file is read and applied before any option is looked at, so that // an option on the command line overrides the file rather than being // quietly overwritten by it. if (try findConfigPath(gpa, argv, stderr)) |path| { const source = readFile(gpa, io, path) catch { try stderr.print("could not read the configuration file '{s}'\n", .{path}); return error.BadArgument; }; source_out.* = source; // Deinited with the allocator the parse used. var diagnostics: std.zon.parse.Diagnostics = .{}; defer diagnostics.deinit(arena); config_mod.apply(arena, gpa, &config, source, &connectors, &diagnostics) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.Unreadable => unreachable, error.Invalid => { try stderr.print("{s}:\n{f}", .{ path, diagnostics }); return error.BadArgument; }, }; } while (args.next()) |option| { if (eq(option, "--help") or eq(option, "-h")) return error.HelpRequested; if (eq(option, "--version")) return error.VersionRequested; if (eq(option, "--config")) { // Read in an earlier pass; skipped here so that its value is not // mistaken for another option. _ = try nextValue(&args, stderr, option); } 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, "--snip")) { const value = try nextValue(&args, stderr, option); snip_level = std.fmt.parseInt(i32, value, 10) catch { try stderr.print("{s}: '{s}' is not a level\n", .{ option, value }); return error.BadArgument; }; return error.SnipRequested; } 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, "--modeac")) { config.mode_ac = true; } else if (eq(option, "--raw")) { config.raw = true; } else if (eq(option, "--onlyaddr")) { config.only_address = true; } else if (eq(option, "--show-only")) { const value = try nextValue(&args, stderr, option); config.show_only = std.fmt.parseInt(u32, value, 16) catch { try stderr.print("{s}: '{s}' is not a hexadecimal ICAO address\n", .{ option, value }); return error.BadArgument; }; } else if (eq(option, "--quiet")) { config.quiet = true; } else if (eq(option, "--stats")) { config.stats_at_exit = true; } else if (eq(option, "--stats-every")) { const seconds = try parseFloat(stderr, option, try nextValue(&args, stderr, option)); config.stats_every_ms = @intFromFloat(seconds * 1000); config.stats_at_exit = true; } else if (eq(option, "--stats-range")) { config.stats_range_histogram = true; config.receiver.range_histogram = true; } else { try stderr.print("unknown option '{s}'\n", .{option}); if (std.mem.startsWith(u8, option, "--")) { try stderr.writeAll("the receiver's settings live in a configuration file; see --help\n"); } return error.BadArgument; } } // `--net` on its own means the default ports, but a port given // explicitly is not overridden by it. config.net.mode_ac = config.mode_ac; config.net.mlat_timestamps = config.mlat_timestamps; config.net.connectors = try connectors.toOwnedSlice(gpa); return config; } /// Rewrite `receiver.json`, which says how to talk to this receiver. fn writeReceiverJson(io: Io, writer: *json.Writer, config: Config) !void { try writer.writeReceiver(io, version, if (config.receiver.position) |p| .{ .latitude = p.latitude, .longitude = p.longitude, } else null, config.json_location_accuracy); } /// Collect the running totals every subsystem keeps into one report. /// /// The subsystems count cumulatively and know nothing about windows; the /// windowing is done by differencing successive calls to this. fn gather( receiver: *const Receiver, source_produces_samples: bool, cpu: struct { demod: u64, reader: u64, background: u64 }, ) stats.Stats { var st: stats.Stats = .empty; st.demod_cpu_ms = cpu.demod; st.reader_cpu_ms = cpu.reader; st.background_cpu_ms = cpu.background; const demod = receiver.demodulator.counters; st.demod_preambles = demod.preambles; st.demod_rejected_bad = demod.rejected_bad; st.demod_rejected_unknown_icao = demod.rejected_unknown_icao; st.demod_accepted = demod.accepted; st.demod_modeac = demod.modeac; st.signal_power_sum = demod.signal_power_sum; st.signal_power_count = demod.signal_power_count; st.peak_signal_power = demod.peak_signal_power; st.strong_signal_count = demod.strong_signal_count; st.noise_power_sum = demod.noise_power_sum; st.noise_power_count = demod.noise_power_count; st.samples_processed = if (source_produces_samples) demod.noise_power_count else 0; st.cpr_filtered = receiver.decoder.cpr_filtered; const tracked = receiver.tracker.counters; st.unique_aircraft = tracked.unique_aircraft; st.single_message_aircraft = tracked.single_message_aircraft; st.unreliable_aircraft = tracked.unreliable_aircraft; st.cpr_surface = tracked.cpr_surface; st.cpr_airborne = tracked.cpr_airborne; st.cpr_global_ok = tracked.cpr_global_ok; st.cpr_global_bad = tracked.cpr_global_bad; st.cpr_global_skipped = tracked.cpr_global_skipped; st.cpr_global_range_checks = tracked.cpr_global_range_checks; st.cpr_global_speed_checks = tracked.cpr_global_speed_checks; st.cpr_local_ok = tracked.cpr_local_ok; st.cpr_local_skipped = tracked.cpr_local_skipped; st.cpr_local_range_checks = tracked.cpr_local_range_checks; st.cpr_local_speed_checks = tracked.cpr_local_speed_checks; for (tracked.range_histogram, &st.range_histogram) |count, *slot| slot.* = count; st.sdr_gain = receiver.gain_step; const gain = receiver.adaptive.counters; st.adaptive_valid = gain.valid; st.adaptive_gain_seconds = gain.gain_seconds; st.adaptive_loud_undecoded = gain.loud_undecoded; st.adaptive_loud_decoded = gain.loud_decoded; st.adaptive_gain_changes = gain.gain_changes; st.adaptive_noise_dbfs = gain.noise_dbfs; st.adaptive_range_gain_limit = if (gain.valid) gain.range_gain_limit else null; st.messages_total = receiver.message_count; st.messages_by_df = receiver.messages_by_df; st.remote_received_modes = receiver.remote_received_modes; st.remote_received_modeac = receiver.remote_received_modeac; st.remote_rejected_bad = receiver.remote_rejected_bad; st.remote_rejected_unknown_icao = receiver.remote_rejected_unknown_icao; st.remote_accepted = receiver.remote_accepted; return st; } /// Decode whatever arrived over the network since the last pass. /// /// The decoder and the tracker belong to this task, so the network readers /// leave frames in a queue rather than calling in; this is where they are /// picked up. fn decodeInbound( io: Io, server: *net.Server, receiver: *Receiver, buffer: *std.ArrayList(net.Inbound), log: *Log, zone: ?datetime.TimeZone, ) !void { buffer.clearRetainingCapacity(); server.inbound.drain(io, buffer); for (buffer.items) |item| { switch (item) { .frame => |arrival| { var mm: Message = .empty; // Frames from elsewhere are marked as such, so that this // receiver does not pass them off as its own when forwarding. mm.remote = true; mm.timestamp_12mhz = arrival.frame.timestamp; mm.system_timestamp_ms = arrival.arrived_ms; mm.signal_level = arrival.frame.signal_level; if (arrival.frame.isModeAc()) { receiver.remote_received_modeac += 1; mode_s.decodeModeAC(&mm, arrival.frame.modeAcCode()); } else { receiver.remote_received_modes += 1; mode_s.decode(receiver.decoder, &mm, arrival.frame.bytes()) catch |err| { switch (err) { error.Implausible => receiver.remote_rejected_bad += 1, error.Unacceptable => receiver.remote_rejected_unknown_icao += 1, } continue; }; receiver.remote_accepted[mm.corrected_bits] += 1; } receiver.onMessage(&mm); }, // A Radarcape announcing where it is. Adopted only when nothing // else has said where the antenna is: moving the reference out // from under the position decoder mid-run would invalidate every // relative decode made against the old one. .receiver_position => |position| { if (receiver.tracker.receiver.position != null) continue; if (!std.math.isFinite(position.latitude) or position.latitude < -90 or position.latitude > 90 or !std.math.isFinite(position.longitude) or position.longitude < -180 or position.longitude > 180 or !std.math.isFinite(position.altitude)) continue; receiver.tracker.receiver.position = .{ .latitude = position.latitude, .longitude = position.longitude, }; server.queueFatsvPosition(io, position.latitude, position.longitude, position.altitude, sdr.nowMillis(io)); logWithTimestamp(log, zone, io, "Autodetected receiver location: {f}, {f} at {f}m AMSL", .{ fmt.Fixed(5){ .value = position.latitude }, fmt.Fixed(5){ .value = position.longitude }, fmt.f0(position.altitude), }); }, } } } /// Run the source, then say so. /// /// The consumer cannot tell a source that has finished from one that is /// merely quiet, so the source has to announce it — and wake the consumer, /// which may be part way through a hundred-millisecond wait. fn runSource( source: *sdr.Source, io: Io, queue: *fifo.Fifo, running: *std.atomic.Value(bool), finished: *std.atomic.Value(bool), ) void { source.run(io, queue, running); finished.store(true, .release); // Wake a consumer that is part way through a wait — but only if there was // ever going to be anything to wait for. Halting the queue when there is // no source at all would turn the consumer's wait into a busy loop. if (source.producesSamples()) queue.halt(io); } 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; }; } /// Find `--config ` without acting on anything else, so that the file /// can be applied before the options that override it. fn findConfigPath(gpa: std.mem.Allocator, argv: std.process.Args, stderr: *Io.Writer) !?[]const u8 { var args: std.process.Args.Iterator = try .initAllocator(argv, gpa); defer args.deinit(); _ = args.next(); var path: ?[]const u8 = null; while (args.next()) |option| { if (eq(option, "--config")) path = try nextValue(&args, stderr, option); } return path; } /// Read a whole file, with the terminating zero the ZON parser wants. fn readFile(gpa: std.mem.Allocator, io: Io, path: []const u8) ![:0]u8 { var file = try Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); var buffer: [4096]u8 = undefined; var reader = file.readerStreaming(io, &buffer); var contents: std.Io.Writer.Allocating = .init(gpa); errdefer contents.deinit(); _ = try reader.interface.streamRemaining(&contents.writer); return contents.toOwnedSliceSentinel(0); } 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, /// The network outputs, if any are listening. server: ?*net.Server, /// The demodulator, so its counters can be collected. demodulator: *const demod_2400.Demodulator, /// The adaptive gain control, which every sample is fed to. adaptive: *adaptive.Control, /// The radio's gain step, if it has one. gain_step: ?u8 = null, /// How many messages were decoded, for the closing summary. message_count: u64 = 0, /// ...and how many of each downlink format. messages_by_df: [32]u64 = @splat(0), /// Messages that arrived over the network rather than the radio. remote_received_modes: u64 = 0, remote_received_modeac: u64 = 0, remote_rejected_bad: u64 = 0, remote_rejected_unknown_icao: u64 = 0, remote_accepted: [crc.max_bit_errors + 1]u64 = @splat(0), /// Called by the demodulator for each decoded frame. pub fn onMessage(self: *Receiver, mm: *Message) void { self.message_count += 1; switch (mm.format) { .mode_s => |df| self.messages_by_df[df] += 1, .mode_ac => {}, } const aircraft = self.tracker.update(mm) catch |err| switch (err) { error.OutOfMemory => null, }; if (self.server) |server| { // The BaseStation format carries both when the message arrived // and when the line was written, so the current time is needed // as well as the message's own. server.queue(self.io, mm, aircraft, sdr.nowMillis(self.io)); server.queueFatsvEvent(self.io, mm, aircraft); } // The terminal display shows everything the decoder accepted, bar // the one address filter; the network outputs are the ones that // filter in earnest. if (self.config.quiet) return; if (self.config.show_only) |address| { if (mm.address != address) return; } if (self.config.only_address) { display.address(self.out, mm) catch {}; } else if (self.config.raw) { display.raw(self.out, mm, self.config.mlat_timestamps) catch {}; } else { display.verbose(self.out, mm, self.config.mlat_timestamps) catch {}; } } /// Called with runs of samples, labelled with the message they belong to /// if the demodulator decoded one, which is what the adaptive gain /// control measures. pub fn onSamples(self: *Receiver, magnitudes: []const u16, mm: ?*const Message) void { self.adaptive.update(magnitudes, mm); } }; fn run(gpa: std.mem.Allocator, io: Io, stderr: *Io.Writer, config: Config, zone: ?datetime.TimeZone) !Outcome { // One log for every task that reports: the decoding loop, the accept and // connect loops, the adaptive gain control and the FlightAware uplink all // write here, and an `Io.Writer` used from several tasks at once is a data // race rather than merely untidy output. var shared_log: Log = .init(io, stderr); logWithTimestamp(&shared_log, zone, io, "{s} starting up.", .{version}); var outcome: Outcome = .abnormal; 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); // Watching for one aircraft means its DF11 replies should be believed // from the first message, rather than only once it has announced itself. if (config.show_only) |address| _ = decoder.filter.add(address); 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}); if (err == error.DeviceNotFound) dump1090.sdr_rtlsdr.listDevices(gpa, io, stderr) catch {}; try stderr.flush(); return err; }; defer source.close(gpa, io); if (!config.quiet) { try source.describe(stderr); try stderr.flush(); } // The adaptive controller takes over the gain knob, so it goes after the // source has said what it opened and settled on a starting gain. var adaptive_options = config.adaptive; if (adaptive_options.range_target == 0) adaptive_options.range_target = source.defaultRangeTarget(); var gain: adaptive.Control = try .init(gpa, source.gainControl(), adaptive_options, &shared_log); defer gain.deinit(gpa); // The decibels at each gain step, so that the statistics can report a // step as a gain without reaching back into the source. var gain_table_storage: [stats.gain_step_count]f64 = undefined; const gain_table: []const f64 = table: { const control = source.gainControl(); const max_step = control.maxGain(); if (max_step < 0) break :table &.{}; const count = @min(@as(usize, @intCast(max_step)) + 1, gain_table_storage.len); for (gain_table_storage[0..count], 0..) |*slot, step| slot.* = control.gainDb(@intCast(step)); break :table gain_table_storage[0..count]; }; var queue: fifo.Fifo = try .init(gpa, .{}); defer queue.deinit(); var json_writer: ?json.Writer = if (config.json_dir) |dir| blk: { var writer = json.Writer.init(gpa, io, dir, config.json_interval_ms) catch |err| { try stderr.print("could not open the JSON directory '{s}': {t}\n", .{ dir, err }); return err; }; writeReceiverJson(io, &writer, config) catch {}; break :blk writer; } else null; defer if (json_writer) |*writer| writer.deinit(io); var out_buf: [64 * 1024]u8 = undefined; var out_writer = Io.File.stdout().writerStreaming(io, &out_buf); const out = &out_writer.interface; defer out.flush() catch {}; var server: net.Server = .init(gpa, config.net, zone); server.log = &shared_log; defer server.deinit(io); defer server.stop(io); if (config.net_enabled) { server.start(io) catch |err| { // Through the shared log: `start` brings services up one at a // time, so a failure partway leaves earlier accept loops already // running and reporting. shared_log.print("could not listen: {t}\n", .{err}); return err; }; if (!config.quiet) { for (server.services.items) |service| { // A connector dials out; it has no port to be listening on, // and says for itself when it connects. if (service.connector != null) continue; shared_log.print("{s} listening on port {d}\n", .{ service.protocol.description(), service.port, }); } for (server.input_services.items) |service| { shared_log.print("{s} listening on port {d}\n", .{ service.protocol.description(), service.port, }); } try stderr.flush(); } } // The FlightAware uplink. It is set on the server before any track can // be generated, because whether tracks are generated at all depends on // something wanting them — and with no FATSV port configured, this is // the only thing that does. var flightaware: adept.Client = undefined; var flightaware_running = false; // Outlives the client, which borrows rather than copies it. var feeder_id_text: ?[:0]u8 = null; defer if (feeder_id_text) |text| gpa.free(text); if (config.flightaware) |uplink| { var options = uplink; options.version = version; if (options.feeder_id == null) { if (config.feeder_id_file) |path| { // No file yet is the normal state before a first login: the // server issues an identifier and it gets written then. if (readFile(gpa, io, path)) |text| { feeder_id_text = text; const trimmed = std.mem.trim(u8, text, " \t\r\n"); if (trimmed.len != 0) options.feeder_id = trimmed; // The source stays `cache` whether or not the file had // anything in it: it describes where an identifier is // kept, not whether one has been issued yet. } else |_| {} } } flightaware = .{ .gpa = gpa, .options = options, .log = &shared_log, .feeder_id_file = config.feeder_id_file, }; flightaware_running = true; server.adept = &flightaware; } defer if (flightaware_running) flightaware.deinit(); var receiver: Receiver = .{ .io = io, .config = config, .decoder = &decoder, .tracker = &tracker, .out = out, .server = if (config.net_enabled) &server else null, .demodulator = &demodulator, .adaptive = &gain, .gain_step = source.gainStep(), }; var windows: stats.Windows = .{}; var demod_cpu: stats.CpuTimer = .{}; var background_cpu: stats.CpuTimer = .{}; const stats_options: stats.Options = .{ .local = source.producesSamples(), .net = config.net_enabled, .fix_bits = config.decode.fix_bits, .range_histogram = config.stats_range_histogram, .max_range = config.receiver.max_range, .gain_db = gain_table, }; var next_stats_ms: u64 = 0; var next_json_stats_ms: u64 = 0; var next_fatsv_ms: u64 = 0; // Reused between passes, so that draining the queue does not allocate // once a second forever. var inbound_buffer: std.ArrayList(net.Inbound) = .empty; defer inbound_buffer.deinit(gpa); var running: std.atomic.Value(bool) = .init(true); var source_finished: std.atomic.Value(bool) = .init(false); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, runSource, .{ &source, io, &queue, &running, &source_finished }); if (flightaware_running) try group.concurrent(io, adept.Client.run, .{ &flightaware, io }); // Whatever goes wrong below, the source has to be told to stop and the // queue woken before the group is joined: a source waiting for a free // block is asleep on a futex that only `halt` wakes, and cancelling the // task does not reach it. errdefer { running.store(false, .release); source.stop(); if (flightaware_running) flightaware.stop(io); queue.halt(io); } // A source that produces nothing never finishes, so with no network // services there would be nothing at all to wait for. An uplink is not a // reason to stay: with no source there are no tracks to send it. if (!source.producesSamples() and !config.net_enabled) { running.store(false, .release); if (flightaware_running) flightaware.stop(io); queue.halt(io); try group.await(io); try stderr.writeAll("no sample source configured; nothing to do\n"); return .abnormal; } // About thirty seconds of empty dequeues. A radio that has stopped // delivering is usually wedged, and a receiver that quietly hears nothing // for half a minute is worse than one that gives up and lets whatever // supervises it start again. var watchdog: i32 = 300; while (true) { const signal = caught_signal.load(.acquire); if (signal != 0) { logWithTimestamp(&shared_log, zone, io, "Caught SIG{s}, shutting down..\n", .{ if (signal == @intFromEnum(std.posix.SIG.TERM)) "TERM" else "INT", }); outcome = .normal; break; } if (queue.dequeue(io, fifo.millis(100))) |buf| { watchdog = 300; demod_cpu.start(io); demodulator.demodulate(buf, &receiver); // An attached Beast reader can turn Mode A/C on and off, so the // answer is asked for again each block rather than settled once. const mode_ac = if (config.net_enabled) server.mode_ac.load(.acquire) else config.mode_ac; if (mode_ac) demodulator.demodulateModeAc(buf, &receiver); demod_cpu.stop(io); queue.release(io, buf); } else if (source_finished.load(.acquire) and source.producesSamples()) { // Nothing waiting and nothing more coming. A source that never // produced anything — `--net-only` — has always "finished", and // is not a reason to stop. break; } else if (source.producesSamples()) { watchdog -= 1; if (watchdog <= 0) { logWithTimestamp(&shared_log, zone, io, "No samples received from the SDR for a long time. Maybe the hardware is wedged? Giving up.", .{}); break; } } // Housekeeping between blocks, and while waiting for one. It // rate-limits itself internally, so calling it often costs nothing. background_cpu.start(io); defer background_cpu.stop(io); if (config.net_enabled) try decodeInbound(io, &server, &receiver, &inbound_buffer, &shared_log, zone); const now = sdr.nowMillis(io); // The adaptive controller may have moved it since the last pass, // and the Stratux output reports it with every message. receiver.gain_step = source.gainStep(); server.gain_db = if (receiver.gain_step) |step| source.gainDb(step) else 0; tracker.periodic(now); // FATSV reports tracks rather than messages, so it walks the tracker // once a second rather than being fed as frames arrive. if (config.net_enabled and now >= next_fatsv_ms) { next_fatsv_ms = now + 1000; server.writeFatsv(io, &tracker, now); } decoder.filter.expire(now); windows.update(gather(&receiver, source.producesSamples(), .{ .demod = demod_cpu.milliseconds(), .reader = source.cpuMilliseconds(), .background = background_cpu.milliseconds(), }), now); _ = windows.rollMinute(now); // `stats.json` is on a clock of its own rather than the minute roll, // because --json-stats-every can ask for it far more often than that. if (config.json_dir != null and now >= next_json_stats_ms) { if (next_json_stats_ms == 0) { next_json_stats_ms = now + config.json_stats_interval_ms; } else { if (json_writer) |*writer| writer.writeStatsSnapshot(io, &windows, stats_options) catch {}; next_json_stats_ms += config.json_stats_interval_ms; } } if (config.stats_every_ms != 0) { if (next_stats_ms == 0) { next_stats_ms = now + config.stats_every_ms; } else if (now >= next_stats_ms) { next_stats_ms = now + config.stats_every_ms; try stats.writeText(out, windows.takePeriodic(), stats_options, zone); } } if (json_writer) |*writer| { _ = writer.periodic(io, &tracker, now, receiver.message_count) catch {}; // A new history snapshot changes how many there are, which // `receiver.json` publishes. const count_changed = writer.periodicHistory(io, &tracker, now, receiver.message_count) catch false; if (count_changed) writeReceiverJson(io, writer, config) catch {}; } // Standard output going away — `dump1090 --raw | head`, most often — // is the end of the run rather than a failure. Upstream is killed by // SIGPIPE at this point; stopping quietly comes to the same thing, // and skips a stack trace nobody wants. out.flush() catch break; } if (source.producesSamples()) { logWithTimestamp(&shared_log, zone, io, "Waiting for receive thread termination", .{}); } running.store(false, .release); // A radio is inside its driver's own loop and has to be interrupted. source.stop(); // So is the uplink: its task is asleep on a socket read or a futex, and // cancelling the group does not reach either. if (flightaware_running) flightaware.stop(io); queue.halt(io); try group.await(io); try out.flush(); windows.update(gather(&receiver, source.producesSamples(), .{ .demod = demod_cpu.milliseconds(), .reader = source.cpuMilliseconds(), .background = background_cpu.milliseconds(), }), sdr.nowMillis(io)); if (config.stats_at_exit) { try stats.writeText(out, windows.total(), stats_options, zone); try out.flush(); } if (json_writer) |*writer| writer.writeStatsSnapshot(io, &windows, stats_options) catch {}; 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 }, ); } logWithTimestamp(&shared_log, zone, io, "{s} exit.", .{if (outcome == .normal) "Normal" else "Abnormal"}); return outcome; } const testing = std.testing; test "--snip keeps the loud stretches and a preamble either side" { // Thirty-two quiet samples are kept; the thirty-third onwards go. var samples: std.ArrayList(u8) = .empty; defer samples.deinit(testing.allocator); try samples.appendSlice(testing.allocator, &.{ 200, 200 }); for (0..100) |_| try samples.appendSlice(testing.allocator, &.{ 127, 127 }); try samples.appendSlice(testing.allocator, &.{ 10, 250 }); var in: Io.Reader = .fixed(samples.items); var buf: [1024]u8 = undefined; var out: Io.Writer = .fixed(&buf); try snip(&in, &out, 8); const written = out.buffered(); // The loud sample, thirty-two quiet ones, and the loud sample after them. try testing.expectEqual(@as(usize, 2 + 32 * 2 + 2), written.len); try testing.expectEqual(@as(u8, 200), written[0]); try testing.expectEqual(@as(u8, 127), written[2]); try testing.expectEqual(@as(u8, 250), written[written.len - 1]); } test "--snip at level zero keeps everything, since nothing is quiet enough" { const samples = [_]u8{ 127, 127, 127, 127 }; var in: Io.Reader = .fixed(&samples); var buf: [64]u8 = undefined; var out: Io.Writer = .fixed(&buf); try snip(&in, &out, 0); try testing.expectEqualSlices(u8, &samples, out.buffered()); }