// SPDX-FileCopyrightText: © 2020-2021 Oliver Jowett // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Turning I/Q samples into the magnitude envelope the demodulator works on. //! //! This is the only genuinely hot code in the program: a receiver at 2.4 //! million samples a second has to get through this at real time or it falls //! behind and drops messages, and everything above it runs on the tiny //! fraction of samples that turn out to contain a transmission. //! //! Upstream solves that with a code generator. Each kernel is written twice — //! plain C and ARM NEON intrinsics — and then compiled several times over //! with different `-march` settings, giving a dozen or so variants; at //! startup a dispatcher benchmarks them and picks, guided by a table of //! previously measured timings shipped per architecture. That is about three //! and a half thousand lines of generated C to solve a problem Zig does not //! have: `@Vector` compiles to whatever the target actually has, and the //! target is known at build time. //! //! What is reproduced exactly is the *arithmetic* of the variants upstream's //! own timing tables select, because the numbers reach the demodulator's //! thresholds and changing them changes which messages are decoded: //! //! * `magnitude_uc8` uses the 64K lookup table, not the direct calculation — //! the two disagree, since the table rounds and the direct version //! truncates. //! * `magnitude_sc16` and `magnitude_sc16q11` use the direct float //! calculation, which truncates. //! * `mean_power_u16` accumulates in 32-bit blocks, throwing away the low //! sixteen bits of each squared sample. const std = @import("std"); const Allocator = std.mem.Allocator; /// The mean signal level and mean power of a block of samples, both as a /// fraction of full scale. pub const Level = struct { /// Mean magnitude, 0 to 1. mean_level: f64, /// Mean power, 0 to 1. Not the square of `mean_level`: the mean of the /// squares, which is what a noise floor is measured in. mean_power: f64, }; /// The magnitude of every possible (I, Q) byte pair. /// /// A UC8 sample is two bytes, so the whole input alphabet is 65,536 values /// and the magnitude of each can simply be looked up. That is both faster and /// *different* from computing it: the table rounds to nearest where the /// direct calculation truncates, and upstream's timing tables pick the table /// on every architecture, so the table is what the demodulator has been tuned /// against. /// /// It is built at startup rather than at compile time. Sixty-five thousand /// square roots is a fraction of a millisecond once, against two seconds /// added to every build of the module. pub const Uc8Table = struct { entries: []u16, pub fn init(gpa: Allocator) Allocator.Error!Uc8Table { const entries = try gpa.alloc(u16, 65536); for (0..256) |i| { for (0..256) |q| { // The nominal centre of the ADC's range is 127.4 rather than // 127.5: the RTL-SDR's is measurably offset, and this is the // value upstream settled on. const fi: f32 = @floatCast((@as(f64, @floatFromInt(i)) - 127.4) / 128.0); const fq: f32 = @floatCast((@as(f64, @floatFromInt(q)) - 127.4) / 128.0); const magsq: f32 = fi * fi + fq * fq; var mag: f32 = @round(@sqrt(magsq) * 65536.0); if (mag > 65535.0) mag = 65535.0; entries[index(@intCast(i), @intCast(q))] = @intFromFloat(mag); } } return .{ .entries = entries }; } pub fn deinit(self: *Uc8Table, gpa: Allocator) void { gpa.free(self.entries); self.* = undefined; } /// Where a sample's magnitude lives in the table. /// /// Upstream indexes by reinterpreting the two sample bytes as a 16-bit /// integer, which makes the layout depend on the host's byte order. /// Spelling it out avoids that, and gives the same answer on the /// little-endian machines upstream is built on. inline fn index(i: u8, q: u8) u16 { return @as(u16, i) | (@as(u16, q) << 8); } /// Convert UC8 samples to magnitudes. `in` is two bytes per sample. pub fn convert(self: Uc8Table, in: []const u8, out: []u16) void { std.debug.assert(in.len == out.len * 2); for (out, 0..) |*magnitude, i| { magnitude.* = self.entries[index(in[i * 2], in[i * 2 + 1])]; } } }; /// Convert signed 16-bit I/Q samples to magnitudes. /// /// The samples are full-scale signed 16-bit, so the magnitude is twice the /// component values — the extra bit that comes of a signed range being half /// as wide as an unsigned one. pub fn magnitudeSc16(in: []const u8, out: []u16) void { magnitudeSigned(in, out, 2); } /// The same for the bladeRF's Q11 format, where the sample is an eleven-bit /// fraction in a sixteen-bit word. pub fn magnitudeSc16q11(in: []const u8, out: []u16) void { magnitudeSigned(in, out, 32); } /// Both signed formats, which differ only in how far the sample has to be /// scaled to reach full scale. fn magnitudeSigned(in: []const u8, out: []u16, comptime scale: comptime_int) void { std.debug.assert(in.len == out.len * 4); for (out, 0..) |*magnitude, n| { const i = std.mem.readInt(i16, in[n * 4 ..][0..2], .little); const q = std.mem.readInt(i16, in[n * 4 + 2 ..][0..2], .little); // Only the squares are used, so the sign is irrelevant — which is // just as well, since upstream negates the most negative sample // rather than taking its absolute value. const fi: f32 = @floatFromInt(@as(i32, @abs(i)) * scale); const fq: f32 = @floatFromInt(@as(i32, @abs(q)) * scale); var mag: f32 = @sqrt(fi * fi + fq * fq); if (mag > 65535.0) mag = 65535.0; magnitude.* = @intFromFloat(mag); } } /// The mean level and mean power of a block of magnitudes. /// /// The squared terms are shifted down by sixteen bits before they are summed, /// which throws away the bottom half of each one. That is upstream's chosen /// implementation and not an approximation to work around: the demodulator's /// noise thresholds are calibrated against these numbers. pub fn meanPower(magnitudes: []const u16) Level { // Blocks small enough that a 32-bit accumulator cannot overflow: the // largest per-sample term is 65535, and 65536 of those is just inside // 2^32. const block_size = 65536; const lanes = std.simd.suggestVectorLength(u32) orelse 1; var sum: u64 = 0; var sumsq: u64 = 0; var offset: usize = 0; while (offset < magnitudes.len) { const block = magnitudes[offset..@min(offset + block_size, magnitudes.len)]; offset += block.len; var block_sum: u32 = 0; var block_sumsq: u32 = 0; var i: usize = 0; if (lanes > 1) { var vector_sum: @Vector(lanes, u32) = @splat(0); var vector_sumsq: @Vector(lanes, u32) = @splat(0); while (i + lanes <= block.len) : (i += lanes) { const mag: @Vector(lanes, u32) = block[i..][0..lanes].*; vector_sum +%= mag; vector_sumsq +%= (mag * mag) >> @splat(16); } block_sum = @reduce(.Add, vector_sum); block_sumsq = @reduce(.Add, vector_sumsq); } while (i < block.len) : (i += 1) { const mag: u32 = block[i]; block_sum +%= mag; block_sumsq +%= (mag * mag) >> 16; } sum += block_sum; sumsq += block_sumsq; } const count: f64 = @floatFromInt(magnitudes.len); return .{ .mean_level = @as(f64, @floatFromInt(sum)) / count / 65536.0, .mean_power = @as(f64, @floatFromInt(sumsq)) / count / 65536.0, }; } /// How many of these magnitudes are at or above a threshold, which is how the /// adaptive gain control measures how often the receiver is being overloaded. pub fn countAbove(magnitudes: []const u16, threshold: u16) usize { const lanes = std.simd.suggestVectorLength(u16) orelse 1; var count: usize = 0; var i: usize = 0; if (lanes > 1) { const limit: @Vector(lanes, u16) = @splat(threshold); const zero: @Vector(lanes, u16) = @splat(0); const one: @Vector(lanes, u16) = @splat(1); while (i + lanes <= magnitudes.len) : (i += lanes) { const values: @Vector(lanes, u16) = magnitudes[i..][0..lanes].*; count += @reduce(.Add, @select(u16, values >= limit, one, zero)); } } while (i < magnitudes.len) : (i += 1) { if (magnitudes[i] >= threshold) count += 1; } return count; } const testing = std.testing; test "the magnitude table matches the direct calculation it stands in for" { var table: Uc8Table = try .init(testing.allocator); defer table.deinit(testing.allocator); // Full scale in every corner. try testing.expectEqual(@as(u16, 65535), table.entries[Uc8Table.index(0, 0)]); try testing.expectEqual(@as(u16, 65535), table.entries[Uc8Table.index(255, 255)]); // The quiet centre of the range, where the offset from 127.5 shows. try testing.expectEqual(@as(u16, 290), table.entries[Uc8Table.index(127, 127)]); try testing.expectEqual(@as(u16, 369), table.entries[Uc8Table.index(127, 128)]); } test "UC8 conversion is a table lookup per sample" { var table: Uc8Table = try .init(testing.allocator); defer table.deinit(testing.allocator); const samples = [_]u8{ 0, 0, 127, 127, 255, 255, 200, 60 }; var magnitudes: [4]u16 = undefined; table.convert(&samples, &magnitudes); try testing.expectEqual(table.entries[Uc8Table.index(0, 0)], magnitudes[0]); try testing.expectEqual(table.entries[Uc8Table.index(127, 127)], magnitudes[1]); try testing.expectEqual(table.entries[Uc8Table.index(255, 255)], magnitudes[2]); try testing.expectEqual(table.entries[Uc8Table.index(200, 60)], magnitudes[3]); } test "signed conversion scales to full scale and clamps" { // 16384 is half of full scale; doubled that is 32768, and with both // components equal the magnitude is that times root two. var magnitudes: [3]u16 = undefined; const samples = [_]u8{ 0x00, 0x40, 0x00, 0x40, // +16384, +16384 0x00, 0x00, 0x00, 0x00, // silence 0x00, 0x80, 0x00, 0x80, // the most negative sample, both components }; magnitudeSc16(&samples, &magnitudes); try testing.expectEqual(@as(u16, @intFromFloat(32768.0 * @sqrt(2.0))), magnitudes[0]); try testing.expectEqual(@as(u16, 0), magnitudes[1]); // Full scale in both components overflows the 16-bit magnitude, so it // clamps rather than wrapping. try testing.expectEqual(@as(u16, 65535), magnitudes[2]); } test "Q11 conversion scales by 32 rather than 2" { var sc16: [1]u16 = undefined; var q11: [1]u16 = undefined; const samples = [_]u8{ 0x00, 0x04, 0x00, 0x00 }; // +1024, 0 magnitudeSc16(&samples, &sc16); magnitudeSc16q11(&samples, &q11); try testing.expectEqual(@as(u16, 2048), sc16[0]); try testing.expectEqual(@as(u16, 32768), q11[0]); } test "mean power of a constant signal" { const magnitudes: [1000]u16 = @splat(32768); const level = meanPower(&magnitudes); try testing.expectApproxEqAbs(@as(f64, 0.5), level.mean_level, 1e-9); // Half amplitude is a quarter power — less whatever the sixteen-bit // shift threw away, which at this amplitude is nothing. try testing.expectApproxEqAbs(@as(f64, 0.25), level.mean_power, 1e-9); } test "mean power of silence" { const magnitudes: [64]u16 = @splat(0); const level = meanPower(&magnitudes); try testing.expectEqual(@as(f64, 0), level.mean_level); try testing.expectEqual(@as(f64, 0), level.mean_power); } test "the vector and scalar paths agree" { var magnitudes: [10_000]u16 = undefined; var prng: std.Random.DefaultPrng = .init(0x1090); const random = prng.random(); for (&magnitudes) |*magnitude| magnitude.* = random.int(u16); const whole = meanPower(&magnitudes); // A length that is not a multiple of any plausible vector width, so the // scalar tail is exercised, and summed a piece at a time to check the // blocking. var sum: f64 = 0; var sumsq: f64 = 0; for (0..magnitudes.len) |i| { const one = meanPower(magnitudes[i .. i + 1]); sum += one.mean_level; sumsq += one.mean_power; } try testing.expectApproxEqRel(whole.mean_level, sum / magnitudes.len, 1e-12); try testing.expectApproxEqRel(whole.mean_power, sumsq / magnitudes.len, 1e-12); } test "counting samples above a threshold" { var magnitudes: [1000]u16 = undefined; for (&magnitudes, 0..) |*magnitude, i| magnitude.* = @intCast(i); try testing.expectEqual(@as(usize, 1000), countAbove(&magnitudes, 0)); try testing.expectEqual(@as(usize, 500), countAbove(&magnitudes, 500)); try testing.expectEqual(@as(usize, 1), countAbove(&magnitudes, 999)); try testing.expectEqual(@as(usize, 0), countAbove(&magnitudes, 1000)); // Including the ragged tail after the last full vector. try testing.expectEqual(@as(usize, 3), countAbove(magnitudes[0..1000], 997)); }