Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions crates/sgv2-supervisor/src/lease.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
//! consecutive clean ticks. With nothing playing (no demand) a clean tick
//! releases too, as idle rather than a fault: the kernel holds the amps at
//! its floor and refuses every start, as macOS powers the speaker path down
//! when nothing plays. The checks keep running while idle, so the grant
//! comes back on the first tick with demand once two clean ticks have
//! passed.
//! when nothing plays. The checks keep running while idle; the protect
//! stage stops with the last stream, so the heartbeat check holds again
//! only once the next stream runs it, and the grant comes on the second
//! clean tick with demand.

/// What one tick observed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
Expand Down
1 change: 1 addition & 0 deletions crates/sgv2-supervisor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod kernel;
pub mod lease;
pub mod machine;
pub mod observe;
pub mod pace;
pub mod selfcheck;
pub mod supervise;
pub mod thermal;
238 changes: 203 additions & 35 deletions crates/sgv2-supervisor/src/main.rs

Large diffs are not rendered by default.

30 changes: 18 additions & 12 deletions crates/sgv2-supervisor/src/observe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@
//!
//! The heartbeat must be fresh in every PCM state, Closed included: the
//! lease is never renewed on a page that merely exists. That works because
//! the protect stage runs before the amps are linked (`node.always-process`,
//! driven by PipeWire's dummy driver until the amps' sink joins its graph).
//! The grant-before-start sequence is:
//! the protect stage runs before the amps are linked: a client stream runs
//! it on PipeWire's dummy driver until the amps' sink joins its graph, and
//! the session helper's link to the hold (a sink with no device) keeps it
//! running while the speakers are wanted. The grant-before-start sequence
//! is:
//!
//! 1. The supervisor owns "Speaker Protection"; the kernel holds the floor.
//! 2. PipeWire instantiates the plugin, which maps the page, and the protect
//! stage runs on the dummy driver: the heartbeat advances while the
//! speaker PCM is Closed.
//! 2. PipeWire instantiates the plugin, which maps the page. A client
//! stream starts and runs the protect stage on the dummy driver: the
//! heartbeat advances while the speaker PCM is Closed.
//! 3. Two clean ticks (fresh heartbeat, plugin healthy with the published
//! parameters, the helper's report fresh with only allowed links, the
//! speaker mux on the watched PCM, the amps at the operating point) and
Expand All @@ -42,16 +44,20 @@
//! PAUSED, SUSPENDED, an unknown state, or an XRUN that outlasts the
//! heartbeat bound releases at once, as does any other fault. The kernel stops the stream, the
//! helper unlinks the amps, the protect stage falls back to the dummy
//! driver and beats again; the sink keeps the PCM PREPARED and retries its
//! start, and the sequence resumes at 3 from there.
//! driver (the hold or the client keeps it running) and beats again; the
//! sink keeps the PCM PREPARED and retries its start, and the sequence
//! resumes at 3 from there.
//! 6. With no client stream playing (the helper reports `play=0` once it has
//! unlinked and suspended the amps and the sense, so both PCMs are
//! Closed), a clean tick gives the grant back as idle: the kernel floors
//! the amps and refuses every start, so a closed PCM is never left
//! granted for anyone to open. The protect stage keeps beating on the
//! dummy driver and every check keeps running; on `play=1` the grant
//! comes back on that tick (the clean run has carried on) and the
//! sequence continues at 4.
//! granted for anyone to open. The helper then unlinks the hold and the
//! protect stage stops with the last stream, as macOS stops its speaker
//! engine; the heartbeat goes stale, which grants nothing while nothing
//! is wanted, and every other check keeps running (at the idle pace, see
//! `pace`). The next stream runs the stage again from its first frame,
//! the report says `play=1`, and the grant comes once the engine has
//! beaten for two clean ticks; the sequence continues at 4.
//!
//! The heartbeat bound is two quanta plus a tick, plus [`START_GRACE_NS`]
//! where the driver switch happens and nothing can play:
Expand Down
141 changes: 141 additions & 0 deletions crates/sgv2-supervisor/src/pace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
//! How fast the supervisor looks while nothing plays.
//!
//! With a stream playing, the loop ticks every 10 ms and its two pollers
//! (the speaker PCM's `/proc` status and the session helper's liveness)
//! every millisecond, so a fault releases the grant within a poll. With
//! nothing playing there is no grant to release: the kernel holds the amps
//! at its floor and refuses every start. Polling at full rate then only
//! costs power (about 2 x 1000 wakeups a second from the pollers alone),
//! while macOS stops its speaker engine shortly after the last client.
//!
//! So once the path has been quiet (no grant, no demand in the helper's
//! report) for [`IDLE_AFTER_NS`], the supervisor goes idle: the pollers run
//! every [`IDLE_POLL_NS`] and the loop every [`IDLE_TICK_NS`], or at once
//! when the helper renames a new report into place or the PCM reader sees
//! a change, and the loop drops its frequency floor. Every check keeps running at that pace (hard amp faults still
//! latch, the kernel-side checks still gate the next grant).
//!
//! Leaving idle is the first thing a demand does. The tick that sees a
//! demand while idle does not act on it: it wakes the pollers to full rate
//! and schedules the next tick [`WAKE_TICK_NS`] later, after their fresh
//! readings. A grant therefore always comes from a tick whose PCM snapshot
//! and helper verdict were taken at full rate, and the lease's rule is
//! unchanged: two clean ticks in a row, each clean only if every reading
//! in it was fresh.

/// Quiet this long (no grant, no demand) before going idle.
pub const IDLE_AFTER_NS: u64 = 500_000_000;
/// The loop's tick while idle. A new report wakes it at once; where the
/// report's directory cannot be watched the loop keeps its 10 ms tick.
pub const IDLE_TICK_NS: u64 = 250_000_000;
/// The pollers' period while idle. Their snapshots are then older than the
/// RT loop accepts as proof, which is harmless with nothing to grant.
pub const IDLE_POLL_NS: u64 = 100_000_000;
/// After leaving idle, the next tick comes this soon: long enough for the
/// woken pollers to take fresh readings.
pub const WAKE_TICK_NS: u64 = 2_000_000;

/// What changed after a tick.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
None,
/// The path has been quiet long enough: slow down.
Idle,
/// A demand or a grant: full rate from now on.
Active,
}

#[derive(Debug, Default)]
pub struct Pace {
idle: bool,
quiet_since: Option<u64>,
}

impl Pace {
/// Whether the supervisor is idle (slow pollers, slow loop).
pub fn idle(&self) -> bool {
self.idle
}

/// The demand a tick may act on: none while idle, so a grant never
/// rests on a reading taken at the idle pace.
pub fn demand(&self, demand: bool) -> bool {
demand && !self.idle
}

/// After each tick: `busy` is a grant held or a demand seen on this
/// tick (before [`Pace::demand`] gated it).
pub fn after_tick(&mut self, now_ns: u64, busy: bool) -> Change {
if busy {
self.quiet_since = None;
if self.idle {
self.idle = false;
return Change::Active;
}
return Change::None;
}
let since = *self.quiet_since.get_or_insert(now_ns);
if !self.idle && now_ns.saturating_sub(since) >= IDLE_AFTER_NS {
self.idle = true;
return Change::Idle;
}
Change::None
}
}

#[cfg(test)]
mod tests {
use super::*;

const MS: u64 = 1_000_000;

#[test]
fn goes_idle_only_after_a_quiet_spell() {
let mut p = Pace::default();
assert!(!p.idle());
assert_eq!(p.after_tick(0, false), Change::None);
assert_eq!(p.after_tick(IDLE_AFTER_NS - MS, false), Change::None);
assert!(!p.idle());
assert_eq!(p.after_tick(IDLE_AFTER_NS, false), Change::Idle);
assert!(p.idle());
// stays idle, no repeated change
assert_eq!(p.after_tick(IDLE_AFTER_NS + 100 * MS, false), Change::None);
assert!(p.idle());
}

#[test]
fn any_busy_tick_restarts_the_quiet_spell() {
let mut p = Pace::default();
p.after_tick(0, false);
p.after_tick(400 * MS, true);
assert_eq!(p.after_tick(410 * MS, false), Change::None);
assert_eq!(p.after_tick(400 * MS + IDLE_AFTER_NS, false), Change::None);
assert_eq!(p.after_tick(410 * MS + IDLE_AFTER_NS, false), Change::Idle);
}

#[test]
fn a_demand_while_idle_wakes_first_and_counts_only_from_the_next_tick() {
let mut p = Pace::default();
p.after_tick(0, false);
p.after_tick(IDLE_AFTER_NS, false);
assert!(p.idle());
// the tick that sees the demand while idle may not act on it
assert!(!p.demand(true));
assert_eq!(p.after_tick(IDLE_AFTER_NS + 50 * MS, true), Change::Active);
assert!(!p.idle());
// the next tick may
assert!(p.demand(true));
assert!(!p.demand(false));
// and it stays active while busy
assert_eq!(p.after_tick(IDLE_AFTER_NS + 60 * MS, true), Change::None);
}

#[test]
fn a_grant_alone_keeps_it_active() {
let mut p = Pace::default();
for t in 0..100 {
assert_eq!(p.after_tick(t * 10 * MS, true), Change::None);
}
assert!(!p.idle());
}
}
2 changes: 1 addition & 1 deletion docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ It renews the interlock only while a client stream plays into the protect stage
- the sense carrier is at unity;
- the speaker PCM belongs to the process hosting the plugin.

Any failure releases the interlock at once, and the kernel's own safe level applies. With nothing playing the helper unlinks and suspends the amps and the sense (both PCMs close) and the supervisor gives the interlock back, so an idle Mac holds its speaker path at the floor with its PCMs and DMA stopped, as macOS powers it down. The protect stage keeps running on PipeWire's dummy driver, so its heartbeat, checks and thermal model carry on, and the next stream is granted within one tick of the helper's report. That safe level is the hardware floor whenever no protection holds the amplifiers. There is no chaining to other daemons.
Any failure releases the interlock at once, and the kernel's own safe level applies. With nothing playing the helper unlinks and suspends the amps and the sense (both PCMs close) and the supervisor gives the interlock back, so an idle Mac holds its speaker path at the floor with its PCMs and DMA stopped, as macOS powers it down. The protect stage and the voicing stop with the last stream too (the helper unlinks the hold, a sink with no device that keeps the stage running while the speakers are wanted), and the supervisor and its pollers slow to an idle pace and drop their frequency floor. The next stream runs the stage from its first frame on PipeWire's dummy driver, with its first frames held for the amps; the grant comes once the engine has beaten for two clean ticks. The plugin keeps its thermal model across the pause: a stage PipeWire reactivates restores it cooled for the time since, one that only paused resumes it as it stopped (never cooler than the model allows). That safe level is the hardware floor whenever no protection holds the amplifiers. There is no chaining to other daemons.

## Binding a blob to its machine

Expand Down
42 changes: 36 additions & 6 deletions packaging/pipewire/sgv2-j274.conf
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,32 @@ context.objects = [
monitor.channel-volumes = false
}
}
{ factory = adapter
args = {
factory.name = support.null-audio-sink
node.name = "sgv2.hold.j274"
node.description = "Mac mini J274 speaker protection hold (no device)"
media.class = "Audio/Sink/Internal"
# No device and no clock of its own (not a driver), outside the
# amps' group. The session helper links the protect stage's
# output here while the speakers are wanted, so the stage keeps
# running between a stream's end and the grant's end (the amps
# may not be linked yet); with nothing playing it is unlinked
# and the stage stops with the last stream.
audio.rate = 48000
node.force-rate = 48000
audio.channels = 1
audio.position = [ AUX0 ]
node.driver = false
priority.driver = 0
priority.session = 0
node.autoconnect = false
node.pause-on-idle = true
resample.disable = true
channelmix.disable = true
monitor.channel-volumes = false
}
}
]

context.modules = [
Expand Down Expand Up @@ -71,10 +97,12 @@ context.modules = [
priority.driver = 0
node.lock-quantum = true
node.pause-on-idle = false
# Runs from the start, on any driver: the plugin is
# instantiated and beating before the grant, which waits for
# it, and before the amps are linked.
node.always-process = true
# Runs while anything feeds it or its output is linked (the
# amps, or the hold while the speakers are wanted), on
# whichever driver that brings: the plugin beats before the
# grant, which waits for it, and before the amps are linked.
# With nothing playing it stops, as macOS stops its speaker
# engine after the last client.
stream.dont-remix = true
channelmix.disable = true
resample.disable = true
Expand All @@ -93,9 +121,11 @@ context.modules = [
audio.position = [ AUX0 ]
node.autoconnect = false
node.dont-reconnect = true
node.passive = true
# Not passive: a link from here (to the amps, or to the hold)
# keeps the stage and the amps running with no client, until
# the session helper unlinks it.
node.passive = false
node.pause-on-idle = false
node.always-process = true
stream.dont-remix = true
channelmix.disable = true
resample.disable = true
Expand Down
42 changes: 36 additions & 6 deletions packaging/pipewire/sgv2-j293.conf
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,32 @@ context.objects = [
monitor.channel-volumes = false
}
}
{ factory = adapter
args = {
factory.name = support.null-audio-sink
node.name = "sgv2.hold.j293"
node.description = "MacBook Pro J293 speaker protection hold (no device)"
media.class = "Audio/Sink/Internal"
# No device and no clock of its own (not a driver), outside the
# amps' group. The session helper links the protect stage's
# output here while the speakers are wanted, so the stage keeps
# running between a stream's end and the grant's end (the amps
# may not be linked yet); with nothing playing it is unlinked
# and the stage stops with the last stream.
audio.rate = 48000
node.force-rate = 48000
audio.channels = 4
audio.position = [ AUX0 AUX1 AUX2 AUX3 ]
node.driver = false
priority.driver = 0
priority.session = 0
node.autoconnect = false
node.pause-on-idle = true
resample.disable = true
channelmix.disable = true
monitor.channel-volumes = false
}
}
]

context.modules = [
Expand Down Expand Up @@ -71,10 +97,12 @@ context.modules = [
priority.driver = 0
node.lock-quantum = true
node.pause-on-idle = false
# Runs from the start, on any driver: the plugin is
# instantiated and beating before the grant, which waits for
# it, and before the amps are linked.
node.always-process = true
# Runs while anything feeds it or its output is linked (the
# amps, or the hold while the speakers are wanted), on
# whichever driver that brings: the plugin beats before the
# grant, which waits for it, and before the amps are linked.
# With nothing playing it stops, as macOS stops its speaker
# engine after the last client.
stream.dont-remix = true
channelmix.disable = true
resample.disable = true
Expand All @@ -93,9 +121,11 @@ context.modules = [
audio.position = [ AUX0 AUX1 AUX2 AUX3 ]
node.autoconnect = false
node.dont-reconnect = true
node.passive = true
# Not passive: a link from here (to the amps, or to the hold)
# keeps the stage and the amps running with no client, until
# the session helper unlinks it.
node.passive = false
node.pause-on-idle = false
node.always-process = true
stream.dont-remix = true
channelmix.disable = true
resample.disable = true
Expand Down
Loading
Loading