diff options
Diffstat (limited to 'src/host')
| -rw-r--r-- | src/host/Host.zig | 5 | ||||
| -rw-r--r-- | src/host/audio.zig | 89 |
2 files changed, 88 insertions, 6 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig index 4f45ace..002c704 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -486,6 +486,7 @@ fn draw(self: *Host, now: u64, started: u64) !u64 { } } self.input.streams = self.audio.streamStatus(); + self.input.lead = self.audio.lead; self.input.sample_rate = sound.sample_rate; self.input.microphone = self.audio.record(arena); self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{}; @@ -513,6 +514,10 @@ fn draw(self: *Host, now: u64, started: u64) !u64 { .voice => |voice| self.audio.declare(voice), .gain => |g| self.audio.gains[g.group] = g.gain, .audio => |a| self.audio.push(a.key, a.samples, a.clear), + .audio_buffer => |a| if (self.passes) |*g| if (a.count > 0) { + const samples = try arena.alloc(f32, a.count); + if (g.read(a.buffer, a.offset, std.mem.sliceAsBytes(samples))) self.audio.push(a.key, samples, false) else |err| self.print("gpu audio: {t} ({s})", .{ err, c.SDL_GetError() }); + }, .quit => self.quit = true, .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), .post_process => |p| if (self.passes) |*g| self.runPostProcess(g, p.source, p.target, p.effect) catch |err| self.print("gpu postprocess: {t} ({s})", .{ err, c.SDL_GetError() }), diff --git a/src/host/audio.zig b/src/host/audio.zig index bf5fdc4..e95e38e 100644 --- a/src/host/audio.zig +++ b/src/host/audio.zig @@ -28,6 +28,19 @@ pub const Audio = struct { heard_gains: [8]f32 = @splat(1), streams: std.ArrayList(Stream) = .empty, status: std.ArrayList(abi.Stream) = .empty, + /// Samples the device takes from each stream at once. + pull: u32 = 1024, + /// The wall-clock time (ns) between the ends of the last frames' + /// commands, where pushes are done; and when the last ended. + intervals: [64]u64 = @splat(0), + frame: u64 = 0, + last_frame: u64 = 0, + /// Grown by underruns, shrinking back while there are none. + margin: u32 = 0, + /// A stream ran dry since the lead was last worked out. + dry: bool = false, + /// `Input.lead`: see `lead`. + lead: u32 = 4800, scope: Scope = .{}, /// The default recording device, bound to this stream while declared. microphone: ?*c.SDL_AudioStream = null, @@ -44,12 +57,25 @@ pub const Audio = struct { /// Mixed since a script last asked (`expect-audio`). sounded: bool = false, }; - const Stream = struct { key: u32, out: *c.SDL_AudioStream, pushed: u64 = 0 }; + const Stream = struct { + key: u32, + out: *c.SDL_AudioStream, + pushed: u64 = 0, + /// Pushed to this frame, and the last. + fed: bool = false, + was_fed: bool = false, + underruns: u32 = 0, + }; pub fn open(self: *Audio) !void { const device = c.SDL_OpenAudioDevice(c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec); if (device == 0) return error.OpenAudio; self.device = device; + var format: c.SDL_AudioSpec = undefined; + var frames: c_int = 0; + if (c.SDL_GetAudioDeviceFormat(device, &format, &frames) and frames > 0 and format.freq > 0) { + self.pull = @intCast(@divFloor(@as(i64, frames) * sample_rate + format.freq - 1, format.freq)); + } self.voices_out = try self.bind(); self.scope.attach(device) catch {}; } @@ -176,9 +202,18 @@ pub const Audio = struct { if (clear) { _ = c.SDL_ClearAudioStream(s.out); s.pushed = 0; + s.was_fed = false; } if (samples.len == 0) return; + // Fed last frame and empty now: the device came up short since + // (counted at the push, as a pull before it would hide it by the + // next frame). + if (s.was_fed and !s.fed and c.SDL_GetAudioStreamQueued(s.out) == 0) { + s.underruns += 1; + self.dry = true; + } if (c.SDL_PutAudioStreamData(s.out, samples.ptr, @intCast(samples.len * @sizeOf(f32)))) s.pushed += samples.len; + s.fed = true; } fn streamFor(self: *Audio, key: u32) ?*Stream { @@ -192,14 +227,22 @@ pub const Audio = struct { return &self.streams.items[self.streams.items.len - 1]; } - /// Drops undeclared voices, keeps the voice mix queued ahead, and opens - /// or closes the microphone. + /// Drops undeclared voices, works out the lead for the next frame, keeps + /// the voice mix queued ahead, and opens or closes the microphone. pub fn endFrame(self: *Audio) void { self.reconcileMicrophone(); var i: usize = 0; while (i < self.voices.items.len) { if (self.voices.items[i].seen) i += 1 else _ = self.voices.swapRemove(i); } + const now = c.SDL_GetTicksNS(); + if (self.last_frame != 0) { + self.intervals[self.frame % self.intervals.len] = now -| self.last_frame; + self.frame += 1; + } + self.last_frame = now; + self.lead = lead(self.intervals, self.pull, &self.margin, self.dry); + self.dry = false; const out = self.voices_out orelse return; const queued = c.SDL_GetAudioStreamQueued(out); if (queued < 0) return; @@ -257,16 +300,33 @@ pub const Audio = struct { return false; } + /// The streams as a frame starts. pub fn streamStatus(self: *Audio) []const abi.Stream { self.status.clearRetainingCapacity(); - for (self.streams.items) |s| { - const queued = c.SDL_GetAudioStreamQueued(s.out); - self.status.append(self.gpa, .{ .key = s.key, .queued = @intCast(@divFloor(@max(queued, 0), @sizeOf(f32))), .pushed = s.pushed }) catch {}; + for (self.streams.items) |*s| { + const queued: u32 = @intCast(@divFloor(@max(c.SDL_GetAudioStreamQueued(s.out), 0), @sizeOf(f32))); + s.was_fed = s.fed; + s.fed = false; + self.status.append(self.gpa, .{ .key = s.key, .queued = queued, .pushed = s.pushed, .underruns = s.underruns }) catch {}; } return self.status.items; } }; +/// How many samples to keep queued: the slowest of the last frames' worth +/// (pushes come once a frame, `intervals` apart), plus the device's pull +/// (it takes that much at once), plus `margin`: half a pull more at each +/// underrun (`dry`), back down by a sample a frame. +fn lead(intervals: [64]u64, pull: u32, margin: *u32, dry: bool) u32 { + var slowest: u64 = 0; + for (intervals) |ns| slowest = @max(slowest, ns); + margin.* = if (dry) @min(margin.* + pull / 2, max_lead) else margin.* -| 1; + const frame: u32 = @intCast(@min(slowest * sample_rate / std.time.ns_per_s, 1 << 20)); + return @min(frame + pull + margin.*, max_lead); +} +/// 170 ms: a frame slower than that is a stall, not a pace. +const max_lead = 8192; + /// Where the voice mix stops being passed through: -2.5 dBFS. Quieter /// mixes keep their true volume to the bit; a clip normalised to full scale /// only has its peaks bent (1 comes out at 0.875). @@ -462,3 +522,20 @@ test "voices at another rate are resampled linearly, and a group's gain scales i try std.testing.expect(out[0] > 0.375 and out[0] < 0.38); try std.testing.expectEqual(@as(f32, 0.5), out[1023]); } + +test "the lead the mixer gives streams outlasts the slowest recent frame and the device's pull, more after an underrun" { + const expectEqual = std.testing.expectEqual; + var intervals: [64]u64 = @splat(20 * std.time.ns_per_ms); + var margin: u32 = 0; + // 50 Hz and a pull of 1024: a frame's 960 samples and the pull. + try expectEqual(@as(u32, 960 + 1024), lead(intervals, 1024, &margin, false)); + // One 50 ms frame in the window sets it. + intervals[5] = 50 * std.time.ns_per_ms; + try expectEqual(@as(u32, 2400 + 1024), lead(intervals, 1024, &margin, false)); + // An underrun adds half a pull, which goes a sample a frame. + try expectEqual(@as(u32, 2400 + 1024 + 512), lead(intervals, 1024, &margin, true)); + try expectEqual(@as(u32, 2400 + 1024 + 511), lead(intervals, 1024, &margin, false)); + // A stall is not a pace: the lead stops at 170 ms. + intervals[6] = std.time.ns_per_s; + try expectEqual(@as(u32, max_lead), lead(intervals, 1024, &margin, false)); +} |
