// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The server's clock, as seen from this one: an offset and a drift, //! estimated from NTP-style exchanges by a two-dimensional Kalman filter. //! //! Every audio chunk carries the server time at which it is to be heard, so //! a player has to know what that time is here. Each `client/time` → //! `server/time` exchange gives four timestamps, from which a measurement of //! the offset follows, with half the round trip as how far off it might be: //! //! ``` //! offset = ((server_received - client_transmitted) + (server_transmitted - client_received)) / 2 //! max_error = ((client_received - client_transmitted) - (server_transmitted - server_received)) / 2 //! ``` //! //! The filter tracks the offset and how fast it changes, weighting each //! measurement by its uncertainty, and forgets faster when a measurement //! lands far from the prediction -- a network hiccup, or the server's clock //! being stepped. //! //! This is a line-for-line port of aiosendspin's `SendspinTimeFilter`, itself //! a port of ESPHome's, so that every Sendspin client agrees with every other //! about where the server's clock is. The tests check it against numbers the //! Python produced from the same measurements -- which is why its rounding //! is Python's, halves to even, rather than Zig's. const TimeFilter = @This(); const std = @import("std"); /// A residual beyond this fraction of the measurement's `max_error` counts /// as a surprise, and triggers forgetting. const adaptive_forgetting_cutoff = 0.75; last_update: i64 = 0, count: u32 = 0, offset: f64 = 0, drift: f64 = 0, offset_covariance: f64 = std.math.inf(f64), offset_drift_covariance: f64 = 0, drift_covariance: f64 = 0, process_variance: f64, forget_variance_factor: f64, /// The parameters conversions use, fixed at each update. current: Element = .{}, const Element = struct { last_update: i64 = 0, offset: f64 = 0, drift: f64 = 0, }; pub fn init() TimeFilter { return initWith(0.01, 1.001); } pub fn initWith(process_std_dev: f64, forget_factor: f64) TimeFilter { return .{ .process_variance = process_std_dev * process_std_dev, .forget_variance_factor = forget_factor * forget_factor, }; } /// One measurement: the offset it found, half the round trip it took, and /// when (client microseconds) it was taken. pub fn update(self: *TimeFilter, measurement: i64, max_error: i64, time_added: i64) void { if (time_added == self.last_update) return; // Wide, since the times come from the server and can be anything. const dt: f64 = @floatFromInt(@as(i128, time_added) - self.last_update); self.last_update = time_added; const update_std_dev: f64 = @floatFromInt(max_error); const measurement_variance = update_std_dev * update_std_dev; const m: f64 = @floatFromInt(measurement); // The first measurement is the offset; there is no drift yet. if (self.count == 0) { self.count += 1; self.offset = m; self.offset_covariance = measurement_variance; self.drift = 0; self.current = .{ .last_update = self.last_update, .offset = self.offset, .drift = self.drift }; return; } // The second gives a first drift, by difference. if (self.count == 1) { self.count += 1; self.drift = (m - self.offset) / dt; self.offset = m; self.drift_covariance = (self.offset_covariance + measurement_variance) / dt; self.offset_covariance = measurement_variance; self.current = .{ .last_update = self.last_update, .offset = self.offset, .drift = self.drift }; return; } // Predict. const offset = self.offset + self.drift * dt; const dt_squared = dt * dt; var new_drift_covariance = self.drift_covariance; var new_offset_drift_covariance = self.offset_drift_covariance + self.drift_covariance * dt; var new_offset_covariance = self.offset_covariance + 2 * self.offset_drift_covariance * dt + self.drift_covariance * dt_squared + dt * self.process_variance; // The innovation, and forgetting when it is a surprise. const residual = m - offset; const max_residual_cutoff = update_std_dev * adaptive_forgetting_cutoff; if (self.count < 100) { self.count += 1; } else if (residual > max_residual_cutoff) { new_drift_covariance *= self.forget_variance_factor; new_offset_drift_covariance *= self.forget_variance_factor; new_offset_covariance *= self.forget_variance_factor; } // Correct. const uncertainty = 1.0 / (new_offset_covariance + measurement_variance); const offset_gain = new_offset_covariance * uncertainty; const drift_gain = new_offset_drift_covariance * uncertainty; self.offset = offset + offset_gain * residual; self.drift += drift_gain * residual; self.drift_covariance = new_drift_covariance - drift_gain * new_offset_drift_covariance; self.offset_drift_covariance = new_offset_drift_covariance - drift_gain * new_offset_covariance; self.offset_covariance = new_offset_covariance - offset_gain * new_offset_covariance; self.current = .{ .last_update = self.last_update, .offset = self.offset, .drift = self.drift }; } /// A measurement from one `server/time` reply, received at `client_received`. /// /// The sums are Python's, whose integers do not overflow, so they are taken /// wide here: the server's timestamps can be anything at all. pub fn exchange(self: *TimeFilter, client_transmitted: i64, server_received: i64, server_transmitted: i64, client_received: i64) void { const ct: i128 = client_transmitted; const sr: i128 = server_received; const st: i128 = server_transmitted; const cr: i128 = client_received; const offset: f64 = @as(f64, @floatFromInt((sr - ct) + (st - cr))) / 2; const delay: f64 = @as(f64, @floatFromInt((cr - ct) - (st - sr))) / 2; self.update(roundHalfEven(offset), roundHalfEven(delay), client_received); } /// The server time that is `client_time` here. pub fn serverTime(self: *const TimeFilter, client_time: i64) i64 { const dt: f64 = @floatFromInt(@as(i128, client_time) - self.current.last_update); return client_time +| roundHalfEven(self.current.offset + self.current.drift * dt); } /// The time here that is `server_time` on the server. pub fn clientTime(self: *const TimeFilter, server_time: i64) i64 { const e = self.current; const last: f64 = @floatFromInt(e.last_update); return roundHalfEven((@as(f64, @floatFromInt(server_time)) - e.offset + e.drift * last) / (1.0 + e.drift)); } /// Two measurements, and a finite uncertainty: enough to schedule by. pub fn synchronized(self: *const TimeFilter) bool { return self.count >= 2 and !std.math.isInf(self.offset_covariance); } /// The standard deviation of the offset estimate, in microseconds. pub fn errorUs(self: *const TimeFilter) i64 { return roundHalfEven(@sqrt(self.offset_covariance)); } pub fn reset(self: *TimeFilter) void { self.* = initWith(@sqrt(self.process_variance), @sqrt(self.forget_variance_factor)); } /// How long to wait before the next exchange: often while the estimate is /// poor, rarely once it is good. pub fn nextIntervalMs(self: *const TimeFilter) u32 { if (!self.synchronized()) return 200; const e = self.errorUs(); if (e < 1_000) return 3_000; if (e < 2_000) return 1_000; if (e < 5_000) return 500; return 200; } /// Python's `round`: to the nearest integer, halves to the even one. Where /// Python would give an integer too big for an `i64`, or raise, this gives /// the nearest `i64`, or zero for NaN: a server that sends absurd times gets /// an absurd clock, not a crash. fn roundHalfEven(x: f64) i64 { if (std.math.isNan(x)) return 0; // 2^63, the first float past the largest i64. const limit: f64 = 9223372036854775808.0; if (x >= limit) return std.math.maxInt(i64); if (x < -limit) return std.math.minInt(i64); const r = @round(x); if (@abs(x - @trunc(x)) == 0.5) { const f = @floor(x); return @intFromFloat(if (@mod(f, 2) == 0) f else f + 1); } return @intFromFloat(r); } const testing = std.testing; test "half to even" { try testing.expectEqual(@as(i64, std.math.maxInt(i64)), roundHalfEven(std.math.inf(f64))); try testing.expectEqual(@as(i64, std.math.minInt(i64)), roundHalfEven(-1e300)); try testing.expectEqual(@as(i64, 0), roundHalfEven(std.math.nan(f64))); try testing.expectEqual(@as(i64, 2), roundHalfEven(2.5)); try testing.expectEqual(@as(i64, 4), roundHalfEven(3.5)); try testing.expectEqual(@as(i64, -2), roundHalfEven(-2.5)); try testing.expectEqual(@as(i64, 3), roundHalfEven(2.6)); } test "agrees with aiosendspin's filter, measurement for measurement" { // Produced by aiosendspin 4.4.0's SendspinTimeFilter from the same // measurements: a server clock five seconds ahead and drifting 50 ppm, // round trips of 1.5 to 2.3 ms with jitter, a faster exchange rate while // it settles, and one outlier 40 ms out at the tenth. const Row = struct { measurement: i64, max_error: i64, time: i64, client_of: i64, server_of: i64, err: i64 }; const rows = [_]Row{ .{ .measurement = 4999452, .max_error = 1831, .time = 1200000, .client_of = 9995000548, .server_of = 6699452, .err = 1831 }, .{ .measurement = 5000451, .max_error = 1904, .time = 1400000, .client_of = 9945329621, .server_of = 6902948, .err = 1904 }, .{ .measurement = 4999453, .max_error = 1549, .time = 1600000, .client_of = 10045117265, .server_of = 7096958, .err = 1549 }, .{ .measurement = 4999451, .max_error = 2048, .time = 1800000, .client_of = 10020863474, .server_of = 7297920, .err = 1784 }, .{ .measurement = 5000356, .max_error = 1874, .time = 2000000, .client_of = 9994800051, .server_of = 7499907, .err = 1594 }, .{ .measurement = 5000369, .max_error = 1559, .time = 2200000, .client_of = 9989444236, .server_of = 7700503, .err = 1296 }, .{ .measurement = 4999376, .max_error = 1719, .time = 3200000, .client_of = 9997519275, .server_of = 8699488, .err = 1567 }, .{ .measurement = 5000304, .max_error = 1588, .time = 4200000, .client_of = 9994476784, .server_of = 9700089, .err = 1370 }, .{ .measurement = 4999439, .max_error = 1928, .time = 5200000, .client_of = 9995595340, .server_of = 10699737, .err = 1385 }, .{ .measurement = 5039622, .max_error = 1746, .time = 6200000, .client_of = 9942556372, .server_of = 11723374, .err = 1267 }, .{ .measurement = 5001066, .max_error = 2064, .time = 7200000, .client_of = 9962091364, .server_of = 12718318, .err = 1263 }, .{ .measurement = 5000788, .max_error = 1560, .time = 8200000, .client_of = 9979014452, .server_of = 13711332, .err = 1094 }, }; var f: TimeFilter = .init(); for (rows) |r| { f.update(r.measurement, r.max_error, r.time); try testing.expectEqual(r.client_of, f.clientTime(10_000_000_000)); try testing.expectEqual(r.server_of, f.serverTime(r.time + 500_000)); try testing.expectEqual(r.err, f.errorUs()); } try testing.expect(f.synchronized()); }