Something went wrong. Try again.
A port of FlightAware's dump1090, a Mode S and ADS-B decoder for software defined radios, to Zig 0.16.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466// SPDX-FileCopyrightText: © 2014, 2015 Oliver Jowett <oliver@mutability.co.uk>// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: GPL-2.0-or-later
//! The Mode S CRC, and the syndrome tables that turn a failed check into a//! list of bits to flip.//!//! Mode S protects every frame with a 24-bit CRC whose remainder is folded//! into the last three bytes of the frame rather than appended to it, so a//! frame that arrived intact checksums to zero. When it does not, the non-zero//! remainder — the *syndrome* — is not merely a failure flag: it is a function//! of which bits were corrupted and nothing else, so a table mapping syndromes//! back to bit positions recovers the frame outright.//!//! That table is what `Table` builds. Enumerating every one- and two-bit error//! pattern over a 112-bit frame is only 6,328 entries, but many-bit errors//! alias onto those syndromes, and "correcting" such a frame invents an//! aircraft out of noise. So the two-bit table is built with the three- and//! four-bit patterns enumerated as well, purely to strike out any one- or//! two-bit entry they collide with. That costs about six million syndrome//! computations at startup and, for a 112-bit frame, two fifths of the//! two-bit coverage — but it is the difference between error correction and//! fiction. A 56-bit frame has few enough bit pairs that none of them//! collide, so its coverage survives intact.
const std = @import("std");const Allocator = std.mem.Allocator;
const modes = @import("modes.zig");const MessageLength = modes.MessageLength;
/// The most bit errors this module will ever offer to correct, and so the/// width of `ErrorInfo.bits`.pub const max_bit_errors = 2;
/// Generator polynomial for the Mode S CRC.const generator_poly: u32 = 0xfff409;
/// The CRC of each single-byte message, which turns the bit-at-a-time/// polynomial division into a byte-at-a-time table lookup.const crc_table: [256]u32 = blk: { @setEvalBranchQuota(20_000); var table: [256]u32 = undefined; for (&table, 0..) |*entry, i| { var c: u32 = @as(u32, i) << 16; for (0..8) |_| { c = if (c & 0x800000 != 0) (c << 1) ^ generator_poly else c << 1; // Only bit 23 is ever tested, so trimming here rather than at the // end changes nothing and keeps the shift inside 32 bits. c &= 0xffffff; } entry.* = c; } break :blk table;};
/// The syndrome produced by corrupting each single bit of a 112-bit frame.////// A short frame's bit *i* has the same syndrome as a long frame's bit/// *i + 56*: the leading seven bytes of the long frame are zero, so the/// division has produced nothing by the time it reaches the short frame's/// first bit. That is why one table of 112 entries serves both lengths, and/// why the table builders below carry an `offset` of `112 - bits`.const single_bit_syndrome: [modes.max_message_bits]u24 = blk: { @setEvalBranchQuota(20_000); var message: [modes.max_message_bytes]u8 = @splat(0); var table: [modes.max_message_bits]u24 = undefined; for (&table, 0..) |*entry, i| { message[i / 8] ^= @as(u8, 0x80) >> @intCast(i % 8); entry.* = checksum(&message); message[i / 8] ^= @as(u8, 0x80) >> @intCast(i % 8); } break :blk table;};
/// The Mode S CRC of a whole frame, which is zero for a frame that arrived/// intact and otherwise identifies which bits did not.////// `message` must be at least three bytes long, because the last three are the/// parity field the remainder is folded into rather than data.pub fn checksum(message: []const u8) u24 { std.debug.assert(message.len >= 3);
var rem: u32 = 0; for (message[0 .. message.len - 3]) |byte| { rem = ((rem << 8) ^ crc_table[byte ^ @as(u8, @truncate(rem >> 16))]) & 0xffffff; }
const tail = message[message.len - 3 ..]; return @truncate(rem ^ (@as(u32, tail[0]) << 16) ^ (@as(u32, tail[1]) << 8) ^ tail[2]);}
/// A syndrome and the bit positions that produce it: what to flip to turn a/// frame that failed its CRC back into the frame that was transmitted.pub const ErrorInfo = struct { /// The syndrome this pattern produces. syndrome: u24, /// How many entries of `bits` are meaningful. error_count: u8, /// Bit positions, counted from the first bit of the frame. bits: [max_bit_errors]u8,
/// The descriptor for a frame that checksummed to zero: nothing to fix. pub const none: ErrorInfo = .{ .syndrome = 0, .error_count = 0, .bits = @splat(0) };
/// The bit positions to flip. pub fn errorBits(self: *const ErrorInfo) []const u8 { return self.bits[0..self.error_count]; }
/// Flip those bits, correcting `message` in place. pub fn apply(self: *const ErrorInfo, message: []u8) void { for (self.errorBits()) |bit| { message[bit / 8] ^= @as(u8, 0x80) >> @intCast(bit % 8); } }};
/// How hard to try at correcting a frame that failed its CRC.pub const FixBits = enum { /// Do not correct anything; a bad CRC is simply a bad frame. none, /// Correct single-bit errors. Every two-, three- and four-bit error has a /// distinct syndrome from every single-bit one, so there is nothing to /// rule out and the table is exact. one, /// Correct one- and two-bit errors, minus the entries that three- and /// four-bit errors alias onto. Upstream's default. two,
/// The widest error pattern to put in the table. fn maxCorrect(self: FixBits) u8 { return switch (self) { .none => 0, .one => 1, .two => 2, }; }
/// The widest error pattern to enumerate when striking out collisions. fn maxDetect(self: FixBits) u8 { return switch (self) { .none => 0, .one => 1, .two => 4, }; }};
/// The syndrome tables, one per frame length, sorted by syndrome.pub const Table = struct { /// Syndromes for 56-bit frames. short: []const ErrorInfo, /// Syndromes for 112-bit frames. long: []const ErrorInfo,
/// Tables that correct nothing. pub const none: Table = .{ .short = &.{}, .long = &.{} };
/// Build the tables. With `.two` this enumerates roughly six million error /// patterns and takes a noticeable moment; the caller is expected to say /// so if it is going to be waited on. pub fn init(gpa: Allocator, fix_bits: FixBits) Allocator.Error!Table { if (fix_bits == .none) return .none;
const short = try prepare(gpa, .short, fix_bits); errdefer gpa.free(short); const long = try prepare(gpa, .long, fix_bits); return .{ .short = short, .long = long }; }
pub fn deinit(self: *Table, gpa: Allocator) void { gpa.free(self.short); gpa.free(self.long); self.* = undefined; }
/// What to do about a frame whose CRC came out as `syndrome`: `.none` if /// it was zero, a correctable pattern if the syndrome names exactly one, /// and null if the frame is beyond repair. pub fn diagnose(self: Table, syndrome: u24, length: MessageLength) ?ErrorInfo { if (syndrome == 0) return .none; const table = switch (length) { .short => self.short, .long => self.long, }; const index = find(table, syndrome) orelse return null; return table[index]; }};
/// Build one length's table: enumerate, sort, discard ambiguity, shrink.fn prepare(gpa: Allocator, length: MessageLength, fix_bits: FixBits) Allocator.Error![]ErrorInfo { const bits = length.bits(); const max_correct = fix_bits.maxCorrect(); const max_detect = fix_bits.maxDetect();
var capacity: usize = 0; for (1..max_correct + 1) |i| capacity += combinations(bits, i);
var table = try gpa.alloc(ErrorInfo, capacity); errdefer gpa.free(table);
// A short frame's bits sit at the tail of the 112-bit syndrome table. const offset = modes.max_message_bits - bits;
var used: usize = 0; enumerate(table, &used, offset, 0, bits, .none, 0, max_correct); std.debug.assert(used == capacity);
std.sort.pdq(ErrorInfo, table[0..used], {}, lessThanSyndrome); used = discardAmbiguous(table[0..used]);
// Strike out anything a wider error pattern also produces, so that noise // is rejected rather than "corrected" into a plausible-looking frame. if (max_detect > max_correct) { var flagged = try std.DynamicBitSet.initEmpty(gpa, used); defer flagged.deinit();
_ = flagCollisions(table[0..used], &flagged, offset, 0, bits, 0, 1, max_correct + 1, max_detect);
var out: usize = 0; for (0..used) |i| { if (flagged.isSet(i)) continue; table[out] = table[i]; out += 1; } used = out; }
return try gpa.realloc(table, used);}
/// Enumerate every error pattern of up to `max_errors` bits over/// `[startbit, endbit)`, appending each to `table`.////// `base` is the pattern built so far and `error_bit` how many bits it holds,/// so each level of the recursion adds one more bit to the right of the last.fn enumerate( table: []ErrorInfo, used: *usize, offset: u8, startbit: u8, endbit: u8, base: ErrorInfo, error_bit: u8, max_errors: u8,) void { if (error_bit >= max_errors) return;
var i = startbit; while (i < endbit) : (i += 1) { var entry = base; entry.syndrome ^= single_bit_syndrome[i + offset]; entry.error_count = error_bit + 1; entry.bits[error_bit] = i;
table[used.*] = entry; used.* += 1;
enumerate(table, used, offset, i + 1, endbit, entry, error_bit + 1, max_errors); }}
/// Drop every syndrome that more than one error pattern produces: with such a/// syndrome in hand there is no way to tell which pattern was the real one.////// `table` must be sorted by syndrome. Returns the new length.fn discardAmbiguous(table: []ErrorInfo) usize { var out: usize = 0; var i: usize = 0; while (i < table.len) { var j = i + 1; while (j < table.len and table[j].syndrome == table[i].syndrome) j += 1; if (j == i + 1) { table[out] = table[i]; out += 1; } i = j; } return out;}
/// Enumerate error patterns of `first_error` to `last_error` bits and flag any/// table entry whose syndrome one of them also produces.////// Returns how many entries were newly flagged.fn flagCollisions( table: []const ErrorInfo, flagged: *std.DynamicBitSet, offset: u8, startbit: u8, endbit: u8, base_syndrome: u24, error_bit: u8, first_error: u8, last_error: u8,) usize { if (error_bit > last_error) return 0;
var count: usize = 0; var i = startbit; while (i < endbit) : (i += 1) { const syndrome = base_syndrome ^ single_bit_syndrome[i + offset];
if (error_bit >= first_error) { if (find(table, syndrome)) |index| { if (!flagged.isSet(index)) { flagged.set(index); count += 1; } } }
count += flagCollisions(table, flagged, offset, i + 1, endbit, syndrome, error_bit + 1, first_error, last_error); }
return count;}
fn lessThanSyndrome(_: void, a: ErrorInfo, b: ErrorInfo) bool { return a.syndrome < b.syndrome;}
/// Binary search a syndrome-sorted table. The table holds no duplicate/// syndromes, so there is never a choice of which match to return.fn find(table: []const ErrorInfo, syndrome: u24) ?usize { var low: usize = 0; var high: usize = table.len; while (low < high) { const mid = low + (high - low) / 2; const found = table[mid].syndrome; if (found == syndrome) return mid; if (found < syndrome) low = mid + 1 else high = mid; } return null;}
/// (n k), the number of ways of choosing k of n items.fn combinations(n: usize, k: usize) usize { if (k == 0 or k == n) return 1; if (k > n) return 0;
var result: usize = 1; for (1..k + 1) |i| { // Exact at every step: the product of i consecutive integers is // always divisible by i!. result = result * (n - i + 1) / i; } return result;}
const testing = std.testing;
/// A real DF17 extended squitter, which checksums to zero.const good_df17 = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 };
test "an intact frame checksums to zero" { try testing.expectEqual(@as(u24, 0), checksum(&good_df17));}
test "the syndrome of a corrupt frame is the syndrome of its error pattern" { for (0..modes.max_message_bits) |bit| { var message = good_df17; message[bit / 8] ^= @as(u8, 0x80) >> @intCast(bit % 8); try testing.expectEqual(single_bit_syndrome[bit], checksum(&message)); }}
test "a short frame's bit i matches a long frame's bit i + 56" { for (0..modes.MessageLength.short.bits()) |bit| { var short: [7]u8 = @splat(0); short[bit / 8] ^= @as(u8, 0x80) >> @intCast(bit % 8); try testing.expectEqual(single_bit_syndrome[bit + 56], checksum(&short)); }}
test "single-bit errors are corrected" { var table: Table = try .init(testing.allocator, .one); defer table.deinit(testing.allocator);
// Every single-bit error is correctable, in both lengths. try testing.expectEqual(@as(usize, 112), table.long.len); try testing.expectEqual(@as(usize, 56), table.short.len);
for (0..modes.max_message_bits) |bit| { var message = good_df17; message[bit / 8] ^= @as(u8, 0x80) >> @intCast(bit % 8);
const info = table.diagnose(checksum(&message), .long).?; try testing.expectEqual(@as(u8, 1), info.error_count); try testing.expectEqual(@as(u8, @intCast(bit)), info.bits[0]);
info.apply(&message); try testing.expectEqualSlices(u8, &good_df17, &message); }}
test "an intact frame needs no correction" { var table: Table = try .init(testing.allocator, .one); defer table.deinit(testing.allocator);
const info = table.diagnose(checksum(&good_df17), .long).?; try testing.expectEqual(@as(u8, 0), info.error_count);}
test "correcting nothing diagnoses nothing" { const table: Table = .none; try testing.expectEqual(@as(u8, 0), table.diagnose(0, .long).?.error_count); try testing.expectEqual(@as(?ErrorInfo, null), table.diagnose(0x123456, .long));}
test "two-bit correction keeps only syndromes wider errors cannot forge" { var table: Table = try .init(testing.allocator, .two); defer table.deinit(testing.allocator);
// These are upstream's counts, checked by dumping both tables from // dump1090 11.1's own crc.c and diffing: every entry matches, in the same // order. Of the 6216 two-bit patterns over a long frame, 3582 survive; // all 1540 over a short frame do. try testing.expectEqual(@as(usize, 112 + 3582), table.long.len); try testing.expectEqual(@as(usize, 56 + 1540), table.short.len);
// Whatever survives has to actually work. for (table.long) |info| { var message: [14]u8 = @splat(0); info.apply(&message); try testing.expectEqual(info.syndrome, checksum(&message)); } for (table.short) |info| { var message: [7]u8 = @splat(0); info.apply(&message); try testing.expectEqual(info.syndrome, checksum(&message)); }
// And every two-bit error the table does claim is corrected exactly. var corrected: usize = 0; for (table.long) |info| { if (info.error_count != 2) continue; var message = good_df17; info.apply(&message); table.diagnose(checksum(&message), .long).?.apply(&message); try testing.expectEqualSlices(u8, &good_df17, &message); corrected += 1; } try testing.expectEqual(@as(usize, 3582), corrected);}
test "the tables hold no duplicate syndromes and stay sorted" { var table: Table = try .init(testing.allocator, .two); defer table.deinit(testing.allocator);
for ([_][]const ErrorInfo{ table.short, table.long }) |entries| { for (entries[1..], entries[0 .. entries.len - 1]) |next, prev| { try testing.expect(prev.syndrome < next.syndrome); } }}
test "combinations" { try testing.expectEqual(@as(usize, 1), combinations(112, 0)); try testing.expectEqual(@as(usize, 112), combinations(112, 1)); try testing.expectEqual(@as(usize, 6216), combinations(112, 2)); try testing.expectEqual(@as(usize, 227_920), combinations(112, 3));}