// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Adaptive gain control. //! //! A receiver has one knob that matters and no good way to set it from the //! armchair: too little gain and distant aircraft vanish into the noise, too //! much and every nearby aircraft arrives clipped and undecodable. The right //! setting depends on the antenna, the cable, the amplifier, and what else is //! transmitting nearby, so this measures the signal that is actually arriving //! and turns the knob itself. //! //! Two independent controllers share the knob, and either can be enabled on //! its own: //! //! * **Burst control** watches for loud runs of samples that the demodulator //! failed to decode. A 40 µs run of near-full-scale samples is the shape of //! an over-amplified Mode S message, and a high rate of them means the gain //! is too high for the traffic overhead. It can lower the gain, and it can //! veto a rise, but on its own it never raises the gain past the limit the //! range controller found. //! //! * **Dynamic range control** measures the noise floor — the Nth percentile //! sample magnitude over a second — and works out how many decibels of //! headroom are left between it and full scale. It scans the gain upwards //! while the headroom stays above the target, backs down when it does not, //! and re-probes upwards occasionally in case conditions changed. //! //! Measurement is organised into three aligned levels, and all three are //! sized in samples so that the arithmetic is exact: //! //! * a **window** is about 40 µs, the length of a long Mode S message, and is //! the unit burst detection counts loud samples over; //! * a **subblock** is 1250 windows, about 50 ms, and is the unit the duty //! cycle switches on and off, so that a receiver need not pay for measuring //! every sample; //! * a **block** is 20 subblocks, about one second, and is the unit control //! decisions are made at. //! //! The samples arrive here from the demodulator, labelled with whether they //! were part of a message it decoded: a decoded message is not evidence of //! too much gain however loud it is, so those runs are skipped by the burst //! detector and excluded from the noise floor. const std = @import("std"); const log_mod = @import("log.zig"); const Allocator = std.mem.Allocator; const Io = std.Io; const dsp = @import("dsp.zig"); const fmt = @import("fmt.zig"); const mag_buf = @import("mag_buf.zig"); const Message = @import("message.zig").Message; const stats = @import("stats.zig"); /// The gain control of whatever is producing samples. /// /// Gain is addressed by *step* rather than by decibels, because that is what /// a tuner actually offers: a short list of settings, not a continuum. Steps /// are signed, and a negative step is not an error — the controller routinely /// computes "one below the current one" and lets the setter clamp it, and a /// source with no gain control at all reports its current step as −1. pub const Radio = struct { context: *anyopaque, vtable: *const VTable, pub const VTable = struct { /// The step in use, or −1 if the source has no gain control. gain: *const fn (context: *anyopaque) i32, /// The highest step, or −1 if the source has no gain control. maxGain: *const fn (context: *anyopaque) i32, /// The gain at a step, in decibels. Out-of-range steps clamp. gainDb: *const fn (context: *anyopaque, step: i32) f64, /// Move to a step, returning the step actually in use afterwards. setGain: *const fn (context: *anyopaque, step: i32) i32, }; pub fn gain(self: Radio) i32 { return self.vtable.gain(self.context); } pub fn maxGain(self: Radio) i32 { return self.vtable.maxGain(self.context); } pub fn gainDb(self: Radio, step: i32) f64 { return self.vtable.gainDb(self.context, step); } pub fn setGain(self: Radio, step: i32) i32 { return self.vtable.setGain(self.context, step); } /// A radio with no gain control, which disables the whole mechanism. pub const none: Radio = .{ .context = &none_context, .vtable = &none_vtable }; }; var none_context: u8 = 0; const none_vtable: Radio.VTable = .{ .gain = struct { fn f(_: *anyopaque) i32 { return -1; } }.f, .maxGain = struct { fn f(_: *anyopaque) i32 { return -1; } }.f, .gainDb = struct { fn f(_: *anyopaque, _: i32) f64 { return 0; } }.f, .setGain = struct { fn f(_: *anyopaque, _: i32) i32 { return 0; } }.f, }; /// Subblocks in a block, which is also the denominator of the duty cycle. pub const subblocks_per_block = 20; /// Windows in a subblock. pub const windows_per_subblock = 1250; /// How many distinct magnitudes the noise-floor histogram counts, which is /// every value a `u16` magnitude can take. pub const magnitude_values = 1 << 16; /// What the two controllers are allowed to do, and how hard they push. /// /// The delays and run lengths are all counted in blocks, which is to say in /// seconds; the defaults are upstream's. pub const Options = struct { /// Lower the gain when too many loud messages fail to decode. burst_control: bool = false, /// Move the gain to keep a target amount of dynamic range. range_control: bool = false, /// The controllers will not choose a step quieter than this. min_gain_db: f32 = 0, /// ...nor louder than this. max_gain_db: f32 = 99999, /// The fraction of each block that is actually measured. Measuring /// costs processor time and half of a second is plenty of evidence. duty_cycle: f32 = 0.5, /// Smoothing factor for the burst rates: smaller is more smoothing. burst_alpha: f32 = 2.0 / 6.0, /// Blocks to ignore after a gain change, while the rates catch up. burst_change_delay: u32 = 5, /// Loud undecoded bursts per block above which the gain is too high. burst_loud_rate: f32 = 5.0, /// Consecutive such blocks needed before the gain comes down. burst_loud_runlength: u32 = 10, /// Loud decoded messages per block below which a rise is safe. burst_quiet_rate: f32 = 5.0, /// Consecutive such blocks needed before a rise is allowed. burst_quiet_runlength: u32 = 10, /// Smoothing factor for the noise floor: smaller is more smoothing. range_alpha: f32 = 2.0 / 6.0, /// Which percentile of sample magnitude counts as the noise floor. range_percentile: u32 = 40, /// The headroom to aim for, in decibels below full scale. /// /// Zero means "whatever the source thinks sensible"; `sdr.Source` fills /// it in when the radio is opened, because the answer depends on the /// tuner's own range. range_target: f32 = 0, /// Blocks to ignore after a gain change, while the noise floor settles. range_change_delay: u32 = 10, /// Blocks to wait before rescanning after backing off from noise. range_scan_delay: u32 = 300, /// Blocks to wait between periodic upward re-probes. range_rescan_delay: u32 = 3600, /// The sample rate, which sets the size of a window. sample_rate: u32 = mag_buf.sample_rate, }; /// Where the dynamic range controller is in its search. pub const RangeState = enum { /// Not scanning; watching for the noise floor to rise, and counting /// down to the next periodic re-probe. idle, /// Raising the gain a step at a time while the headroom holds up. scan_up, /// Lowering the gain a step at a time until the headroom is enough. scan_down, /// As `scan_up`, but reached from `idle` by the periodic re-probe. rescan_up, /// As `scan_down`, but part of a re-probe rather than a fresh scan. rescan_down, }; /// What the controller has to say for the statistics. pub const Counters = struct { /// Whether any of the rest means anything, which it does once a block /// has completed. valid: bool = false, /// Seconds spent at each gain step. gain_seconds: [stats.gain_step_count]u64 = @splat(0), /// Loud runs of samples that never became a message. loud_undecoded: u64 = 0, /// Messages that decoded but arrived close to full scale. loud_decoded: u64 = 0, /// Gain changes this controller made. gain_changes: u64 = 0, /// The smoothed noise floor, in decibels below full scale. noise_dbfs: f64 = 0, /// The highest step the dynamic range controller found acceptable. range_gain_limit: i32 = 0, }; /// The threshold a sample must reach to count as loud: −3 dBFS. /// /// A magnitude is a `u16` where 65535 is full scale, and 10^(−3/20) of that /// is 46395. pub const loud_sample_threshold: u16 = 46395; /// The adaptive gain controller. pub const Control = struct { options: Options, radio: Radio, /// Where the running commentary goes, if anywhere. The messages are the /// only way to see what the controller is doing, so they are worth /// having, but nothing depends on them and a write failure is ignored. log: ?*log_mod.Log = null, /// Whether either controller is running. False if both were switched off, /// or if the source turned out to have no gain control. enabled: bool = false, /// The steps the controllers may choose between, from the decibel limits. gain_min: i32 = 0, gain_max: i32 = 0, /// What one step up, and one step down, is worth in decibels here. The /// steps a tuner offers are not evenly spaced, so this is recomputed /// after every change. gain_up_db: f32 = 0, gain_down_db: f32 = 0, // Block, subblock and window bookkeeping. samples_per_window: u32 = 0, samples_per_subblock: u32 = 0, subblock_samples_remaining: u32 = 0, subblocks_remaining: u32 = subblocks_per_block, subblock_active: bool = false, /// Numerator of the duty cycle; the denominator is `subblocks_per_block`. dutycycle_n: u32 = 0, dutycycle_counter: u32 = 0, // Burst detection. burst_window_remaining: u32 = 0, burst_window_counter: u32 = 0, burst_runlength: u32 = 0, burst_block_loud_undecoded: u32 = 0, burst_block_loud_decoded: u32 = 0, burst_loud_undecoded_smoothed: f64 = 0, burst_loud_decoded_smoothed: f64 = 0, burst_change_timer: u32 = 0, /// The signal level above which a decoded message counts as loud, /// as a power ratio rather than decibels. burst_loud_threshold: f64 = 0, burst_loud_blocks: u32 = 0, burst_quiet_blocks: u32 = 0, // Noise floor measurement. /// One counter per possible magnitude: a radix sort in disguise, which is /// how a percentile is found over a second of samples without keeping /// the samples. radix: []u32 = &.{}, radix_counter: u32 = 0, range_smoothed: f64 = 0, range_state: RangeState = .rescan_up, range_change_timer: u32 = 0, range_rescan_timer: u32 = 0, range_gain_limit: i32 = 0, counters: Counters = .{}, /// A controller that does nothing, for a source with no gain control. pub const disabled: Control = .{ .options = .{}, .radio = .none }; /// Set up the controller and bring the current gain within the limits. /// /// Returns a disabled controller, after saying so, if the source has no /// gain control; asking for adaptive gain on a recording is a mistake /// worth mentioning rather than a reason to stop. pub fn init(gpa: Allocator, radio: Radio, options: Options, log: ?*log_mod.Log) Allocator.Error!Control { var self: Control = .{ .options = options, .radio = radio, .log = log }; const max_gain = radio.maxGain(); if (max_gain < 0) { if (options.burst_control or options.range_control) { self.note("warning: adaptive gain control requested, but SDR gain control not available, ignored.\n", .{}); } self.options.burst_control = false; self.options.range_control = false; } if (!self.options.burst_control and !self.options.range_control) return self; // A window is 40 µs, the length of a long message; a subblock is // 1250 of them, which is close enough to 50 ms and exactly a whole // number of windows. self.samples_per_window = options.sample_rate / 25000; self.samples_per_subblock = self.samples_per_window * windows_per_subblock; self.subblock_samples_remaining = self.samples_per_subblock; self.burst_window_remaining = self.samples_per_window; // The active subblocks are spread through the block by adding N to a // counter modulo D and taking the subblock each time it wraps, which // is a Bresenham line and gives 2 in 5 as "on off on off off" rather // than two at the start. var n = @round(@as(f32, @floatFromInt(subblocks_per_block)) * options.duty_cycle); if (n <= 0) n = 1; if (n > subblocks_per_block) n = subblocks_per_block; self.note("adaptive: using {f}% duty cycle\n", .{ fmt.f0(100.0 * @as(f64, n) / @as(f64, subblocks_per_block)), }); self.dutycycle_n = @intFromFloat(n); self.radix = try gpa.alloc(u32, magnitude_values); @memset(self.radix, 0); // The gain limits are the innermost steps that satisfy the decibel // limits, so that a limit falling between two steps never picks the // step on the wrong side of it. self.gain_min = 0; while (self.gain_min < max_gain) : (self.gain_min += 1) { if (radio.gainDb(self.gain_min) >= options.min_gain_db) break; } self.gain_max = max_gain; while (self.gain_max > self.gain_min) : (self.gain_max -= 1) { if (radio.gainDb(self.gain_max) <= options.max_gain_db) break; } self.note("adaptive: enabled adaptive gain control with gain limits {f}dB (step {d}) .. {f}dB (step {d})\n", .{ fmt.f1(radio.gainDb(self.gain_min)), self.gain_min, fmt.f1(radio.gainDb(self.gain_max)), self.gain_max, }); if (self.options.range_control) { self.note("adaptive: enabled dynamic range control, target dynamic range {f}dB\n", .{ fmt.f1(options.range_target), }); } if (self.options.burst_control) { self.note("adaptive: enabled burst control\n", .{}); } _ = self.setGain(radio.gain(), "constraining gain to adaptive gain limits"); self.gainChanged(); self.range_gain_limit = radio.gain(); self.enabled = true; return self; } pub fn deinit(self: *Control, gpa: Allocator) void { if (self.radix.len > 0) gpa.free(self.radix); self.radix = &.{}; } /// Feed samples in, labelled with the message they belong to if any. /// /// Any number of samples may be passed; the run is cut up into subblocks /// here, so that everything below can assume it never crosses a boundary. pub fn update(self: *Control, magnitudes: []const u16, decoded: ?*const Message) void { if (!self.enabled) return; var rest = magnitudes; while (rest.len >= self.subblock_samples_remaining) { const take = self.subblock_samples_remaining; if (self.subblock_active) self.updateSubblock(rest[0..take], decoded); rest = rest[take..]; self.subblock_samples_remaining = self.samples_per_subblock; self.dutycycle_counter += self.dutycycle_n; if (self.dutycycle_counter >= subblocks_per_block) { self.dutycycle_counter -= subblocks_per_block; self.subblock_active = true; } else { self.subblock_active = false; // Pretend a quiet window went by, so that a run of loud // windows does not survive across the gap we did not look at. self.burstEndOfWindow(0); } self.subblocks_remaining -= 1; if (self.subblocks_remaining == 0) { self.subblocks_remaining = subblocks_per_block; self.endOfBlock(); } } if (rest.len > 0) { if (self.subblock_active) self.updateSubblock(rest, decoded); self.subblock_samples_remaining -= @intCast(rest.len); } } /// Samples from within one subblock, which the duty cycle says to look at. fn updateSubblock(self: *Control, magnitudes: []const u16, decoded: ?*const Message) void { if (decoded) |mm| { if (mm.signal_level >= self.burst_loud_threshold) self.burst_block_loud_decoded += 1; self.burstSkip(magnitudes.len); } else { self.burstUpdate(magnitudes); self.rangeUpdate(magnitudes); } } // ---- Burst detection ---- /// Step the window bookkeeping past samples that were a decoded message. /// /// They are not evidence of anything: a message that decoded is a message /// the gain was fine for, however loud it was. fn burstSkip(self: *Control, length_in: usize) void { if (!self.options.burst_control) return; var length = length_in; if (length < self.burst_window_remaining) { self.burst_window_remaining -= @intCast(length); return; } self.burstEndOfWindow(self.burst_window_counter); length -= self.burst_window_remaining; const windows = length / self.samples_per_window; for (0..windows) |_| self.burstEndOfWindow(0); length -= windows * self.samples_per_window; self.burst_window_counter = 0; self.burst_window_remaining = self.samples_per_window - @as(u32, @intCast(length)); } /// Count loud samples in a run that was not part of any message. The run /// may cross window boundaries, but never a block boundary. fn burstUpdate(self: *Control, magnitudes: []const u16) void { if (!self.options.burst_control) return; var rest = magnitudes; if (rest.len < self.burst_window_remaining) { self.burst_window_counter += @intCast(countLoud(rest)); self.burst_window_remaining -= @intCast(rest.len); return; } // Finish the window that was already part filled. const n = self.burst_window_remaining; self.burstEndOfWindow(self.burst_window_counter + @as(u32, @intCast(countLoud(rest[0..n])))); rest = rest[n..]; const windows = rest.len / self.samples_per_window; for (0..windows) |_| { self.burstEndOfWindow(@intCast(countLoud(rest[0..self.samples_per_window]))); rest = rest[self.samples_per_window..]; } self.burst_window_counter = @intCast(countLoud(rest)); self.burst_window_remaining = self.samples_per_window - @as(u32, @intCast(rest.len)); } fn countLoud(magnitudes: []const u16) usize { return dsp.countAbove(magnitudes, loud_sample_threshold); } /// A window ended with `counter` loud samples in it. fn burstEndOfWindow(self: *Control, counter: u32) void { if (counter > self.samples_per_window / 4) { // Loud: extend the current run. self.burst_runlength += 1; } else { // Quiet. A run of two to five loud windows is 80–200 µs, which is // about the length of a Mode S message: something transmitted, // it was loud, and nothing decoded it. if (self.burst_runlength >= 2 and self.burst_runlength <= 5) { self.burst_block_loud_undecoded += 1; } self.burst_runlength = 0; } } fn burstEndOfBlock(self: *Control) void { if (!self.options.burst_control) return; // Only part of the block was measured, so scale the counts up to what // a whole block would have held. const scale = @as(f64, subblocks_per_block) / @as(f64, @floatFromInt(self.dutycycle_n)); const alpha = self.options.burst_alpha; // As above, `1 - alpha` is worked out in single precision and then // widened, where the rest of each line is double. const decay: f64 = 1 - alpha; self.counters.loud_undecoded += self.burst_block_loud_undecoded; self.burst_loud_undecoded_smoothed = self.burst_loud_undecoded_smoothed * decay + scale * @as(f64, @floatFromInt(self.burst_block_loud_undecoded)) * alpha; self.burst_block_loud_undecoded = 0; self.counters.loud_decoded += self.burst_block_loud_decoded; self.burst_loud_decoded_smoothed = self.burst_loud_decoded_smoothed * decay + scale * @as(f64, @floatFromInt(self.burst_block_loud_decoded)) * alpha; self.burst_block_loud_decoded = 0; } // ---- Noise floor ---- /// Tally sample magnitudes for this block's percentile. fn rangeUpdate(self: *Control, magnitudes: []const u16) void { if (!self.options.range_control) return; self.radix_counter += @intCast(magnitudes.len); for (magnitudes) |magnitude| self.radix[magnitude] += 1; } fn rangeEndOfBlock(self: *Control) void { if (!self.options.range_control) return; // Walk the buckets until the requested percentile is passed. const count_n = @as(u64, self.radix_counter) * self.options.range_percentile / 100; var n: u64 = 0; var i: usize = 0; while (i < magnitude_values and n <= count_n) : (i += 1) n += self.radix[i]; const percentile: f32 = @floatFromInt(i - 1); // The widths are upstream's, and they are not uniform: C works the // second term out in single precision, because a `uint16_t` times a // `float` is a `float`, and only widens it to add. Matching that is // the difference between the same noise floor and one that drifts. const alpha = self.options.range_alpha; self.range_smoothed = self.range_smoothed * @as(f64, 1 - alpha) + @as(f64, percentile * alpha); self.counters.noise_dbfs = if (self.range_smoothed > 0) 20 * @log10(self.range_smoothed / 65536.0) else 0; @memset(self.radix, 0); self.radix_counter = 0; } // ---- Control ---- /// Move to a step, clamped to the limits, saying why. Returns whether the /// gain actually moved. fn setGain(self: *Control, step_in: i32, why: []const u8) bool { const step = std.math.clamp(step_in, self.gain_min, self.gain_max); const current = self.radio.gain(); if (current == step) return false; self.note("adaptive: changing gain from {f}dB (step {d}) to {f}dB (step {d}) because: {s}\n", .{ fmt.f1(self.radio.gainDb(current)), current, fmt.f1(self.radio.gainDb(step)), step, why, }); const new_gain = self.radio.setGain(step); const changed = current != new_gain; if (changed) self.counters.gain_changes += 1; return changed; } /// Recompute what the neighbouring steps are worth, after a change. fn gainChanged(self: *Control) void { const gain = self.radio.gain(); self.gain_up_db = @floatCast(self.radio.gainDb(gain + 1) - self.radio.gainDb(gain)); self.gain_down_db = @floatCast(self.radio.gainDb(gain) - self.radio.gainDb(gain - 1)); // A decoded message counts as loud if it is within one gain step of // full scale, less three decibels of slack: raising the gain would // have clipped it. const loud_threshold_dbfs: f64 = 0 - @as(f64, self.gain_up_db) - 3.0; self.burst_loud_threshold = std.math.pow(f64, 10, loud_threshold_dbfs / 10.0); self.range_change_timer = self.options.range_change_delay; self.burst_change_timer = self.options.burst_change_delay; self.burst_loud_blocks = 0; self.burst_quiet_blocks = 0; } fn increaseGain(self: *Control, why: []const u8) void { if (self.setGain(self.radio.gain() + 1, why)) self.gainChanged(); } fn decreaseGain(self: *Control, why: []const u8) void { if (self.setGain(self.radio.gain() - 1, why)) self.gainChanged(); } /// A block ended: fold in the measurements and act on them. fn endOfBlock(self: *Control) void { self.rangeEndOfBlock(); self.burstEndOfBlock(); self.controlUpdate(); self.counters.valid = true; self.counters.range_gain_limit = self.range_gain_limit; const current = self.radio.gain(); if (current >= 0) { const index: usize = @intCast(@min(current, stats.gain_step_count - 1)); self.counters.gain_seconds[index] += 1; } } /// Decide what to do with the gain, and do it. fn controlUpdate(self: *Control) void { // The two controllers vote. "Not up" overlaps with "down" without // being the same thing: burst control often wants to stop the gain // rising without wanting it to fall. var gain_up = false; var gain_up_reason: []const u8 = ""; var gain_down = false; var gain_down_reason: []const u8 = ""; var gain_not_up = false; const current_gain = self.radio.gain(); if (self.burst_change_timer > 0) self.burst_change_timer -= 1; if (self.range_change_timer > 0) self.range_change_timer -= 1; if (self.range_rescan_timer > 0) self.range_rescan_timer -= 1; if (self.options.burst_control and self.burst_change_timer == 0) { if (self.burst_loud_undecoded_smoothed > self.options.burst_loud_rate) { self.burst_quiet_blocks = 0; self.burst_loud_blocks += 1; } else if (self.burst_loud_decoded_smoothed < self.options.burst_quiet_rate) { self.burst_loud_blocks = 0; self.burst_quiet_blocks += 1; } else { self.burst_loud_blocks = 0; self.burst_quiet_blocks = 0; } if (self.burst_loud_blocks >= self.options.burst_loud_runlength) { gain_down = true; gain_not_up = true; gain_down_reason = "high rate of loud undecoded messages"; // Pulling the gain down underneath a downward scan would // confuse it; stop it and start again once we are out of the // reduced-gain state. if (self.range_state == .scan_down or self.range_state == .rescan_down) { self.range_state = .idle; self.range_rescan_timer = 0; } } else if (self.burst_quiet_blocks < self.options.burst_quiet_runlength) { // Fine where we are, but not yet confident enough to rise. gain_not_up = true; } else if (current_gain < self.range_gain_limit) { gain_up = true; gain_up_reason = "low loud message rate and gain below dynamic range limit"; } } if (self.options.range_control and self.range_change_timer == 0) { // Single precision, as upstream: it declares this a `float`, and // a comparison against the target can fall either way at the // boundary depending on which width it is made in. const available_range: f32 = @floatCast(-20 * @log10(self.range_smoothed / 65536.0)); const target = self.options.range_target; // The limit may rise as soon as a step proves acceptable. // Lowering it is done per state, because idle wants slightly // different rules to give the whole thing some hysteresis. if (available_range >= target and current_gain > self.range_gain_limit) { self.range_gain_limit = current_gain; } switch (self.range_state) { .scan_up, .rescan_up => { if (available_range < target) { self.note("adaptive: available dynamic range ({f}dB) < required dynamic range ({f}dB), switching to downward scan\n", .{ fmt.f1(available_range), fmt.f1(target), }); gain_down = true; gain_not_up = true; gain_down_reason = "probing dynamic range gain lower bound"; self.range_state = if (self.range_state == .rescan_up) .rescan_down else .scan_down; if (self.range_gain_limit >= current_gain) self.range_gain_limit = current_gain - 1; } else if (self.radio.gain() >= self.gain_max) { self.note("adaptive: reached upper gain limit, halting dynamic range scan here\n", .{}); self.range_state = .idle; self.range_rescan_timer = self.options.range_rescan_delay; } else if (!gain_not_up) { // This step is fine and there are more to try. If // burst control has vetoed a rise, do nothing and ask // again next block. self.note("adaptive: available dynamic range ({f}dB) >= required dynamic range ({f}dB), continuing upward scan\n", .{ fmt.f1(available_range), fmt.f1(target), }); gain_up = true; gain_up_reason = "probing dynamic range gain upper bound"; } }, .scan_down, .rescan_down => { if (available_range >= target) { self.note("adaptive: available dynamic range ({f}dB) >= required dynamic range ({f}dB), stopping downwards scan here\n", .{ fmt.f1(available_range), fmt.f1(target), }); self.range_state = .idle; // Upstream assigns the idle state first and then asks // which scan it was, so this is always the rescan // delay; kept as it is, because the timer is only a // "look again in a while" and changing it would move // every downward scan's recovery by an hour. self.range_rescan_timer = self.options.range_rescan_delay; } else { if (self.range_gain_limit >= current_gain) self.range_gain_limit = current_gain - 1; if (self.radio.gain() <= self.gain_min) { self.note("adaptive: reached lower gain limit, halting dynamic range scan here\n", .{}); self.range_state = .idle; self.range_rescan_timer = self.options.range_rescan_delay; } else { self.note("adaptive: available dynamic range ({f}dB) < required dynamic range ({f}dB), continuing downwards scan\n", .{ fmt.f1(available_range), fmt.f1(target), }); gain_down = true; gain_not_up = true; gain_down_reason = "probing dynamic range gain lower bound"; } } }, .idle => { // Watch for noise that a lower gain would cope with. Done // even while waiting to rescan and even with burst // control active, because it only ever lowers the gain. const half_step_down = self.gain_down_db / 2; if (available_range + half_step_down < target and self.radio.gain() > self.gain_min) { self.note("adaptive: available dynamic range ({f}dB) + half gain step down ({f}dB) < required dynamic range ({f}dB), starting downward scan\n", .{ fmt.f1(available_range), fmt.f1(half_step_down), fmt.f1(target), }); if (self.range_gain_limit >= current_gain) self.range_gain_limit = current_gain - 1; self.range_state = .scan_down; gain_down = true; gain_not_up = true; gain_down_reason = "dynamic range fell below target value"; } else if (self.range_rescan_timer == 0 and !gain_not_up) { // Occasionally try a higher gain, in case the noise // floor here is not coming from the tuner at all and // a low gain is buying nothing. if (available_range >= target and self.radio.gain() < self.gain_max) { self.note("adaptive: start periodic scan for acceptable dynamic range at increased gain\n", .{}); gain_up = true; gain_up_reason = "periodic re-probing of dynamic range gain upper bound"; self.range_state = .rescan_up; } else { self.range_rescan_timer = self.options.range_rescan_delay; } } }, } } if (gain_down) { self.decreaseGain(gain_down_reason); } else if (gain_up and !gain_not_up) { self.increaseGain(gain_up_reason); } } fn note(self: *Control, comptime format: []const u8, args: anytype) void { const l = self.log orelse return; l.print(format, args); } }; const testing = std.testing; /// A gain control with evenly spaced steps, for testing without a radio. const FakeRadio = struct { steps: u8, step_db: f64 = 1.0, current: i32 = 0, changes: u32 = 0, fn gain(context: *anyopaque) i32 { const self: *FakeRadio = @ptrCast(@alignCast(context)); return self.current; } fn maxGain(context: *anyopaque) i32 { const self: *FakeRadio = @ptrCast(@alignCast(context)); return @as(i32, self.steps) - 1; } fn gainDb(context: *anyopaque, step: i32) f64 { const self: *FakeRadio = @ptrCast(@alignCast(context)); const clamped = std.math.clamp(step, 0, @as(i32, self.steps) - 1); return @as(f64, @floatFromInt(clamped)) * self.step_db; } fn setGain(context: *anyopaque, step: i32) i32 { const self: *FakeRadio = @ptrCast(@alignCast(context)); self.current = std.math.clamp(step, 0, @as(i32, self.steps) - 1); self.changes += 1; return self.current; } const vtable: Radio.VTable = .{ .gain = gain, .maxGain = maxGain, .gainDb = gainDb, .setGain = setGain, }; fn radio(self: *FakeRadio) Radio { return .{ .context = self, .vtable = &vtable }; } }; test "a source with no gain control disables the controller" { var control: Control = try .init(testing.allocator, .none, .{ .range_control = true }, null); defer control.deinit(testing.allocator); try testing.expect(!control.enabled); try testing.expect(!control.options.range_control); // And feeding it samples does nothing at all. const magnitudes: [1000]u16 = @splat(60000); control.update(&magnitudes, null); try testing.expect(!control.counters.valid); } test "gain limits are the innermost steps satisfying the decibel limits" { var fake: FakeRadio = .{ .steps = 30, .current = 20 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .range_control = true, .min_gain_db = 5.5, .max_gain_db = 24.5, }, null); defer control.deinit(testing.allocator); // 5.5 dB falls between steps 5 and 6, so the lowest usable step is 6; // 24.5 dB falls between 24 and 25, so the highest is 24. try testing.expectEqual(@as(i32, 6), control.gain_min); try testing.expectEqual(@as(i32, 24), control.gain_max); } test "the current gain is brought inside the limits at startup" { var fake: FakeRadio = .{ .steps = 30, .current = 29 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .range_control = true, .max_gain_db = 10.0, }, null); defer control.deinit(testing.allocator); try testing.expectEqual(@as(i32, 10), fake.current); try testing.expectEqual(@as(u64, 1), control.counters.gain_changes); try testing.expectEqual(@as(i32, 10), control.range_gain_limit); } test "the duty cycle spreads active subblocks through the block" { var fake: FakeRadio = .{ .steps = 30, .current = 10 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .range_control = true, .duty_cycle = 0.25, }, null); defer control.deinit(testing.allocator); try testing.expectEqual(@as(u32, 5), control.dutycycle_n); // Step through one block a subblock at a time, recording which ones the // duty cycle turned on. Five in twenty, evenly spaced. const subblock = try testing.allocator.alloc(u16, control.samples_per_subblock); defer testing.allocator.free(subblock); @memset(subblock, 0); var active: [subblocks_per_block]bool = @splat(false); for (&active) |*slot| { control.update(subblock, null); slot.* = control.subblock_active; } try testing.expectEqualSlices(bool, &.{ false, false, false, true, false, false, false, true, false, false, false, true, false, false, false, true, false, false, false, true, }, &active); } test "the noise floor is the requested percentile of sample magnitude" { var fake: FakeRadio = .{ .steps = 30, .current = 10 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .range_control = true, .duty_cycle = 1.0, // No smoothing, so one block's measurement is the answer. .range_alpha = 1.0, .range_percentile = 50, .range_target = 30, // Nothing should move the gain during the test. .range_change_delay = 1000, }, null); defer control.deinit(testing.allocator); // Seven samples in ten at 1000 and the rest at 3000, so that the median // is unambiguously 1000 whichever side of the bucket the walk stops on. const block = try testing.allocator.alloc(u16, control.samples_per_subblock * subblocks_per_block); defer testing.allocator.free(block); for (block, 0..) |*slot, i| slot.* = if (i % 10 < 7) 1000 else 3000; control.update(block, null); try testing.expect(control.counters.valid); try testing.expectApproxEqAbs(@as(f64, 1000), control.range_smoothed, 1); try testing.expectApproxEqAbs( 20 * @log10(1000.0 / 65536.0), control.counters.noise_dbfs, 0.05, ); try testing.expectEqual(@as(i32, 10), fake.current); try testing.expectEqual(@as(u64, 1), control.counters.gain_seconds[10]); } test "a run of loud windows that decoded nothing is a loud undecoded burst" { var fake: FakeRadio = .{ .steps = 30, .current = 10 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .burst_control = true, .duty_cycle = 1.0, .burst_alpha = 1.0, // Long enough that the test's own block never triggers a change. .burst_change_delay = 1000, }, null); defer control.deinit(testing.allocator); const window = control.samples_per_window; const block = try testing.allocator.alloc(u16, control.samples_per_subblock * subblocks_per_block); defer testing.allocator.free(block); @memset(block, 0); // The first subblock of a block is always skipped, because the duty cycle // counter only rolls over at its end, so the run goes in the second. const second = control.samples_per_subblock; // Three consecutive loud windows, which is 120 µs: a message-shaped run. @memset(block[second + 10 * window ..][0 .. 3 * window], 60000); // And a single loud window, which is too short to be a message. @memset(block[second + 100 * window ..][0..window], 60000); control.update(block, null); try testing.expectEqual(@as(u64, 1), control.counters.loud_undecoded); } test "samples belonging to a decoded message are not counted as bursts" { var fake: FakeRadio = .{ .steps = 30, .current = 10 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .burst_control = true, .duty_cycle = 1.0, .burst_alpha = 1.0, .burst_change_delay = 1000, }, null); defer control.deinit(testing.allocator); const window = control.samples_per_window; const subblock = control.samples_per_subblock; const block = try testing.allocator.alloc(u16, subblock * subblocks_per_block); defer testing.allocator.free(block); @memset(block, 0); // The same three loud windows, but this time labelled as a message the // demodulator decoded. They go in the second subblock, because the first // is always skipped by the duty cycle. @memset(block[subblock..][0 .. 3 * window], 60000); var mm: Message = .{}; mm.signal_level = 1.0; control.update(block[0..subblock], null); control.update(block[subblock..][0 .. 3 * window], &mm); control.update(block[subblock + 3 * window ..], null); try testing.expectEqual(@as(u64, 0), control.counters.loud_undecoded); // It was within a gain step of full scale, so it counts as loud. try testing.expectEqual(@as(u64, 1), control.counters.loud_decoded); } test "the dynamic range scan walks the gain up and stops where it must" { var fake: FakeRadio = .{ .steps = 30, .current = 10 }; var control: Control = try .init(testing.allocator, fake.radio(), .{ .range_control = true, .duty_cycle = 1.0, .range_alpha = 1.0, .range_percentile = 50, // The noise floor below is at 20 log10(1000/65536) = -36.3 dBFS, so // 30 dB of headroom is available and 40 dB is not. .range_target = 30, .range_change_delay = 0, }, null); defer control.deinit(testing.allocator); const block = try testing.allocator.alloc(u16, control.samples_per_subblock * subblocks_per_block); defer testing.allocator.free(block); @memset(block, 1000); // Each block is one step up, until the upper limit is reached. for (0..40) |_| control.update(block, null); try testing.expectEqual(@as(i32, 29), fake.current); try testing.expectEqual(RangeState.idle, control.range_state); try testing.expectEqual(@as(i32, 29), control.range_gain_limit); // Now the noise floor rises past what the target allows, and the scan // turns round and walks back down to the bottom. control.options.range_target = 90; for (0..80) |_| control.update(block, null); try testing.expectEqual(@as(i32, 0), fake.current); try testing.expectEqual(RangeState.idle, control.range_state); }