diff --git a/src/Player.zig b/src/Player.zig index a66fc1b..2837b49 100644 --- a/src/Player.zig +++ b/src/Player.zig @@ -255,7 +255,7 @@ fn playFlac(self: *Player, f: *Flac, timestamp_us: i64, data: []const u8) !void for (0..n) |i| for (channels, 0..) |plane, c| { out[i * channels.len + c] = @as(f32, @floatFromInt(plane[i])) * f.scale; }; - const at = timestamp_us + @as(i64, @intCast(played * std.time.us_per_s / f.rate)); + const at = timestamp_us +| @as(i64, @intCast(played * std.time.us_per_s / f.rate)); _ = self.scheduler.push(at, out); played += n; } diff --git a/src/Scheduler.zig b/src/Scheduler.zig index 834ae40..230f664 100644 --- a/src/Scheduler.zig +++ b/src/Scheduler.zig @@ -182,13 +182,18 @@ pub fn fadeOut(self: *Scheduler, fade_us: u64, hold_us: u64) void { defer self.lock.unlock(); if (self.rate == 0) return; self.fade = .{ .out = .{ - .total = @max(1, fade_us * self.rate / std.time.us_per_s), + .total = @max(1, usToFrames(fade_us, self.rate)), .done = 0, - .hold = hold_us * self.rate / std.time.us_per_s, + .hold = usToFrames(hold_us, self.rate), } }; } /// Take the output through whatever fade is under way, frame by frame. +/// +/// Where one stage of the fade gives way to the next, what the next is made +/// from is copied out first: `f` points into `self.fade`, and building the +/// new stage in its place would overwrite fields of the old one before they +/// were read. fn applyFade(self: *Scheduler, planes: []const []f32, frames: u32) void { for (0..frames) |i| { const g: f32 = switch (self.fade) { @@ -196,12 +201,17 @@ fn applyFade(self: *Scheduler, planes: []const []f32, frames: u32) void { .out => |*f| blk: { const g = equalPower(f.done, f.total, false); f.done += 1; - if (f.done >= f.total) self.fade = .{ .silent = .{ .left = f.hold, .total = f.total } }; + if (f.done >= f.total) { + const hold = f.hold; + const total = f.total; + self.fade = .{ .silent = .{ .left = hold, .total = total } }; + } break :blk g; }, .silent => |*f| blk: { if (f.left == 0) { - self.fade = .{ .in = .{ .total = f.total, .done = 0 } }; + const total = f.total; + self.fade = .{ .in = .{ .total = total, .done = 0 } }; } else f.left -= 1; break :blk 0; }, @@ -275,8 +285,8 @@ pub fn push(self: *Scheduler, timestamp_us: i64, interleaved: []const f32) usize // A chunk that carries on exactly where the last one ended is part of // the same run; anything else starts a new one. const continues = if (self.lastSegment()) |last| blk: { - const expected = last.timestamp_us + framesToUs(self.write_frame - last.frame, self.rate); - break :blk @abs(timestamp_us - expected) <= framesToUs(1, self.rate); + const expected = last.timestamp_us +| framesToUs(self.write_frame - last.frame, self.rate); + break :blk @abs(timestamp_us -| expected) <= framesToUs(1, self.rate); } else false; if (!continues) { if (self.segment_count == max_segments) { @@ -337,12 +347,13 @@ fn fillLocked(self: *Scheduler, planes: []const []f32, frames: u32, play_at_us: self.locked_on = false; return; } - const off = self.timeOf(self.read_frame) - due; + // Saturating: the timestamps are the server's, and can be anything. + const off = self.timeOf(self.read_frame) -| due; if (!self.locked_on or @abs(off) > self.options.resync_us) { if (off < 0) { // Too late: skip what can no longer be heard on time. - const late = @min(usToFrames(-off, self.rate), self.write_frame - self.read_frame); + const late = @min(usToFrames(@abs(off), self.rate), self.write_frame - self.read_frame); self.read_frame += late; self.counters.late_frames += late; if (self.read_frame == self.write_frame) { @@ -352,7 +363,7 @@ fn fillLocked(self: *Scheduler, planes: []const []f32, frames: u32, play_at_us: } } else { // Too early: silence until it is due. - const early = usToFrames(off, self.rate); + const early = usToFrames(@intCast(off), self.rate); if (early >= frames) { self.locked_on = false; return; @@ -409,7 +420,7 @@ fn timeOf(self: *const Scheduler, frame: u64) i64 { found = s; } const s = found orelse return 0; - return s.timestamp_us + framesToUs(frame - s.frame, self.rate); + return s.timestamp_us +| framesToUs(frame - s.frame, self.rate); } fn lastSegment(self: *const Scheduler) ?Segment { @@ -434,8 +445,9 @@ fn framesToUs(frames: u64, rate: u32) i64 { return @intCast(frames * std.time.us_per_s / rate); } -fn usToFrames(us: i64, rate: u32) u64 { - return @intCast(@divTrunc(us * rate, std.time.us_per_s)); +/// Frames in `us`, as many as a `u64` holds. +fn usToFrames(us: u64, rate: u32) u64 { + return @intCast(@min(@as(u128, us) * rate / std.time.us_per_s, std.math.maxInt(u64))); } /// This machine's clock, as the clock filter and `fill` want it: monotonic @@ -641,3 +653,40 @@ test "a fade out goes quiet, stays quiet until replaced, and comes back if not" _ = s.fill(&planes, 10, 40_000); try testing.expectEqual(@as(f32, 1), plane[0]); } + +test "timestamps at the ends of an i64 play as silence rather than overflow" { + var s: Scheduler = .init(testing.allocator, .{ .capacity_us = 1_000_000 }); + defer s.deinit(); + try s.start(1, 48000); + s.setClock(fixedClock(0)); + var chunk: [100]f32 = undefined; + var plane: [10]f32 = undefined; + const planes = [_][]f32{&plane}; + // The server's times are whatever it says; so is where the device is. + for ([_]i64{ std.math.minInt(i64), std.math.maxInt(i64), -1, 0 }) |at| { + _ = s.push(at, ramp(&chunk, 1)); + _ = s.push(at +% 1, ramp(&chunk, 1)); + _ = s.fill(&planes, 10, std.math.maxInt(i64)); + _ = s.fill(&planes, 10, std.math.minInt(i64)); + } + s.fadeOut(std.math.maxInt(u64), std.math.maxInt(u64)); + _ = s.fill(&planes, 10, 0); +} + +test "a fade out, its silence and its fade back in stay finite" { + var s: Scheduler = .init(testing.allocator, .{ .capacity_us = 1_000_000 }); + defer s.deinit(); + try s.start(1, 1000); + s.setClock(fixedClock(0)); + var chunk: [100]f32 = undefined; + for (&chunk) |*c| c.* = 1; + _ = s.push(0, &chunk); + // Two frames down, none held: the silence gives way at once to the + // fade back in, which must know how long it is. + s.fadeOut(2_000, 0); + var plane: [10]f32 = undefined; + const planes = [_][]f32{&plane}; + _ = s.fill(&planes, 10, 0); + for (plane) |x| try testing.expect(std.math.isFinite(x)); + try testing.expectEqual(@as(f32, 1), plane[9]); +} diff --git a/src/TimeFilter.zig b/src/TimeFilter.zig index 19768e2..d2bfbb3 100644 --- a/src/TimeFilter.zig +++ b/src/TimeFilter.zig @@ -66,7 +66,8 @@ pub fn initWith(process_std_dev: f64, forget_factor: f64) TimeFilter { /// 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; - const dt: f64 = @floatFromInt(time_added - self.last_update); + // 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); @@ -128,16 +129,23 @@ pub fn update(self: *TimeFilter, measurement: i64, max_error: i64, time_added: i } /// 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 offset: f64 = @as(f64, @floatFromInt((server_received - client_transmitted) + (server_transmitted - client_received))) / 2; - const delay: f64 = @as(f64, @floatFromInt((client_received - client_transmitted) - (server_transmitted - server_received))) / 2; + 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(client_time - self.current.last_update); - return client_time + roundHalfEven(self.current.offset + self.current.drift * dt); + 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. @@ -172,8 +180,16 @@ pub fn nextIntervalMs(self: *const TimeFilter) u32 { return 200; } -/// Python's `round`: to the nearest integer, halves to the even one. +/// 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); @@ -185,6 +201,9 @@ fn roundHalfEven(x: f64) i64 { 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)); diff --git a/src/secure.zig b/src/secure.zig index dfe730a..88138b5 100644 --- a/src/secure.zig +++ b/src/secure.zig @@ -239,9 +239,15 @@ pub const Channel = struct { } /// Seal a binary message -- `data` starting with its own type byte -- - /// handing each frame to `sink`. + /// handing each frame to `sink`. The type bytes that mark a sealed + /// frame as JSON or as a fragment are not binary types, and a message + /// with one would open as something else: `error.InvalidMessageType`. pub fn sealBinary(self: *Channel, data: []const u8, sink: anytype) !void { - std.debug.assert(data.len > 0); + if (data.len == 0) return error.InvalidMessageType; + switch (data[0]) { + json_body, fragment_more, fragment_end => return error.InvalidMessageType, + else => {}, + } return self.sealTyped(data[0], data[1..], sink); }