repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

docs(nuguland): audio event-driven-state design + plan

f90827ae5401e2599cc4a3088af6ac2532369975

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Changed files (2)

+404 / −0 text lines

Diff layout

quickshell/nuguland/docs/superpowers/plans/2026-06-26-audio-event-driven-state.md

Added
new file mode 100644

+311 / −0 text lines

1# Audio Event-Driven State Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Remove continuous PipeWire audio capture from the nuguland shell, deriving all audio activity facts from event-driven link state instead.
6
7**Architecture:** Delete both `PwNodePeakMonitor` capture streams and the 30 Hz smoothing timer in `Audio.qml`. Replace the peak-derived "active" signals with readonly bindings off `Pipewire.links` (`nodeActive` already scans active links). Drop the unrendered amplitude consumer in `Media.qml`. Volume/mute and privacy (mic/cam) logic are already link/property based and stay untouched.
8
9**Tech Stack:** Quickshell (QML), Quickshell.Services.Pipewire (`PwNode`, `PwObjectTracker`, `Pipewire.links`), systemd user service `quickshell.service`.
11## Global Constraints
13- No unit-test harness exists for this QML project. Verification is runtime: `systemctl --user restart quickshell.service`, then `journalctl`/`qs log` for errors and `qs -c nuguland ipc call ...` for behavior. Copy these verbatim.
14- The shell is symlinked: `~/.config/quickshell/nuguland` → `/home/oli/Workspace/dotfiles/quickshell/nuguland`. Edits to the repo are live after a service restart.
15- Repo root (git toplevel): `/home/oli/Workspace/dotfiles`. Current branch `trunk` is the default branch — create a feature branch before the first commit.
16- `PwNode` exposes **no** `.state` field; link presence (`nodeActive`) is the only event-driven "audio flowing" proxy. Do not invent a `.state` read.
17- Keep the JSON schema of `stateObject()` shape-stable (same keys/array lengths) — external IPC readers depend on it. Replace values, do not delete keys, unless a key names a now-deleted concept.
19---
21### Task 0: Feature branch
23**Files:** none (git only)
25- [ ] **Step 1: Create and switch to a feature branch**
27Run:
28```bash
29cd /home/oli/Workspace/dotfiles
30git switch -c audio-event-driven-state
31```
32Expected: `Switched to a new branch 'audio-event-driven-state'`
34---
36### Task 1: Drop the unrendered amplitude consumer in Media.qml
38Do this first so that when Task 2 removes `outputLevelSmooth`, no consumer reads a missing property.
40**Files:**
41- Modify: `quickshell/nuguland/Media.qml` (function `mediaEnergyValue`, ~line 155)
43**Interfaces:**
44- Consumes: `mediaPlayingValue()` (existing, returns `1` when the active MPRIS player is playing, else `0`).
45- Produces: `mediaEnergyValue()` still returns a `0..1` real; now `0` (paused/stopped) or `1` (playing). Consumed only by `mediaWidgetState()` serialization (`Media.qml:212`); nothing renders it.
47- [ ] **Step 1: Replace the function body**
49Find:
50```qml
51 function mediaEnergyValue() {
52 const level = audioService ? audioService.outputLevelSmooth : mediaPlayingValue();
53 return mediaPlayingValue() * Math.max(0, Math.min(1, Number(level || 0) * 6));
54 }
55```
56Replace with:
57```qml
58 function mediaEnergyValue() {
59 // Amplitude VU removed (no audio capture). Energy now reflects playback state only.
60 return mediaPlayingValue();
61 }
62```
64- [ ] **Step 2: Restart the shell**
66Run:
67```bash
68systemctl --user restart quickshell.service
69```
71- [ ] **Step 3: Verify no load errors**
73Run:
74```bash
75journalctl --user -u quickshell.service --since "30 seconds ago" --no-pager | grep -iE "error|warn|undefined|TypeError|is not" || echo CLEAN
76```
77Expected: `CLEAN` (plus the normal `INFO: Configuration Loaded` line in full output).
79- [ ] **Step 4: Commit**
81```bash
82cd /home/oli/Workspace/dotfiles
83git add quickshell/nuguland/Media.qml
84git commit -m "refactor(audio): drop amplitude term from media energy value"
85```
87---
89### Task 2: Remove audio capture; derive activity from link state (Audio.qml)
91**Files:**
92- Modify: `quickshell/nuguland/Audio.qml`
93 - Properties block (~lines 9–25)
94 - `stateObject()` sampler + shader sections (~lines 374–411)
95 - Smoothing `Timer` (~lines 537–545 after the earlier WIP edit)
96 - Both `PwNodePeakMonitor` blocks (~lines 558–565 after the earlier WIP edit)
98**Interfaces:**
99- Consumes: `nodeActive(node)` (existing — returns true when an active `Pipewire.links` entry touches the node), `nodeMuted(node)`, `defaultSinkNode()`, `defaultSourceNode()`, `outputMutedValue()`, `inputMutedValue()`.
100- Produces:
101 - `outputActive: bool` — readonly binding, true when an active link reaches the default sink and it is not muted.
102 - `inputActive: bool` — readonly binding, true when an active link reaches the default source and it is not muted.
103 - Removes properties: `outputLevel`, `inputLevel`, `outputLevelSmooth`, `inputLevelSmooth`, `audioSamplerOutputActive`, `audioSamplerInputActive`, `levelsSettling`. Removes functions `shouldMonitorOutput()`, `shouldMonitorInput()`. No remaining code may reference these.
105- [ ] **Step 1: Replace the level properties with event-driven activity bindings**
107Find (the current head of the `Item`, including the earlier WIP `levelsSettling` block):
108```qml
109 readonly property real outputLevel: shouldMonitorOutput() ? Math.max(0, Math.min(1, Number(outputPeak.peak || 0))) : 0
110 readonly property real inputLevel: shouldMonitorInput() ? Math.max(0, Math.min(1, Number(inputPeak.peak || 0))) : 0
111 property real outputLevelSmooth: 0
112 property real inputLevelSmooth: 0
113 readonly property string audioSamplerBackend: "PwNodePeakMonitor"
114 readonly property bool audioSamplerOutputActive: outputLevel > 0.005
115 readonly property bool audioSamplerInputActive: inputLevel > 0.005
116 // TODO(you): gate the 33ms VU-smoothing timer so it sleeps when nothing moves.
117 // Return true only while the smoothed values still need to chase the live peaks.
118 // When the native peak monitor pushes a new outputLevel/inputLevel, this binding
119 // re-evaluates for free and wakes the timer (same trick AuroraBackdrop.qml:83 uses).
120 // Pick an epsilon: too small never sleeps (float never reaches 0), too big drops
121 // the visible tail of the fade. ~0.004 is a reasonable start.
122 readonly property bool levelsSettling: false // <-- replace with your condition
123```
124Replace with:
125```qml
126 readonly property string audioSamplerBackend: "Pipewire.links"
127 // Audio activity is derived from PipeWire link presence (event-driven), not from
128 // capturing audio. nodeActive() scans Pipewire.links for an active link touching
129 // the node, so these re-evaluate when links change — no capture stream, no timer.
130 readonly property bool outputActive: nodeActive(defaultSinkNode()) && !nodeMuted(defaultSinkNode())
131 readonly property bool inputActive: nodeActive(defaultSourceNode()) && !nodeMuted(defaultSourceNode())
132```
134- [ ] **Step 2: Delete the two `shouldMonitor*` functions**
136Find:
137```qml
138 function shouldMonitorOutput() {
139 const sink = defaultSinkNode();
140 return !!(sink && !nodeMuted(sink));
141 }
143 function shouldMonitorInput() {
144 const source = defaultSourceNode();
145 return !!(source && !nodeMuted(source) && nodeActive(source));
146 }
148```
149Replace with nothing (remove the block entirely, including the trailing blank line).
151- [ ] **Step 3: Update the `sampler` block in `stateObject()`**
153Find:
154```qml
155 "sampler": {
156 "backend": "PwNodePeakMonitor",
157 "outputLevel": outputLevel,
158 "inputLevel": inputLevel,
159 "channels": outputPeak.channels.length || inputPeak.channels.length || 0,
160 "outputActive": audioSamplerOutputActive,
161 "inputActive": audioSamplerInputActive,
162 "targets": shouldMonitorInput() ? ["defaultAudioSink", "defaultAudioSource"] : ["defaultAudioSink"],
163 "efficient": true,
164 "native": true
165 },
166```
167Replace with:
168```qml
169 "sampler": {
170 "backend": "Pipewire.links",
171 "outputActive": outputActive,
172 "inputActive": inputActive,
173 "targets": inputActive ? ["defaultAudioSink", "defaultAudioSource"] : ["defaultAudioSink"],
174 "efficient": true,
175 "native": true,
176 "capture": false
177 },
178```
180- [ ] **Step 4: Update the `shader` values array (unrendered, schema kept length-4)**
182Find:
183```qml
184 "values": [outputLevelSmooth, outputMutedValue(), inputLevelSmooth, inputMutedValue()],
185```
186Replace with:
187```qml
188 "values": [outputActive ? 1 : 0, outputMutedValue(), inputActive ? 1 : 0, inputMutedValue()],
189```
191- [ ] **Step 5: Delete the smoothing `Timer`**
193Find:
194```qml
195 Timer {
196 interval: 33
197 repeat: true
198 running: root.levelsSettling
199 onTriggered: {
200 outputLevelSmooth += (outputLevel - outputLevelSmooth) * 0.18;
201 inputLevelSmooth += (inputLevel - inputLevelSmooth) * 0.18;
202 }
203 }
205```
206Replace with nothing (remove the block, including the trailing blank line).
208- [ ] **Step 6: Delete both `PwNodePeakMonitor` blocks**
210Find:
211```qml
212 PwNodePeakMonitor {
213 id: outputPeak
215 node: root.defaultSinkNode()
216 enabled: root.shouldMonitorOutput()
217 }
219 PwNodePeakMonitor {
220 id: inputPeak
222 node: root.defaultSourceNode()
223 enabled: root.shouldMonitorInput()
224 }
225```
226Replace with nothing (remove both blocks). Keep the `PwObjectTracker` block above them.
228- [ ] **Step 7: Verify no dangling references remain**
230Run:
231```bash
232cd /home/oli/Workspace/dotfiles/quickshell/nuguland
233grep -nE "outputLevel|inputLevel|outputLevelSmooth|inputLevelSmooth|audioSampler(Output|Input)Active|shouldMonitor(Output|Input)|levelsSettling|PwNodePeakMonitor|outputPeak|inputPeak" Audio.qml Media.qml || echo NO-DANGLING
234```
235Expected: `NO-DANGLING`.
237- [ ] **Step 8: Restart and verify clean load**
239Run:
240```bash
241systemctl --user restart quickshell.service
242sleep 2
243journalctl --user -u quickshell.service --since "30 seconds ago" --no-pager | grep -iE "error|warn|undefined|TypeError|is not|ReferenceError" || echo CLEAN
244```
245Expected: `CLEAN`.
247- [ ] **Step 9: Verify audio state serializes and privacy still works**
249Run:
250```bash
251qs -c nuguland ipc call nuguland systemWidgetState >/dev/null 2>&1; echo "ipc-reachable=$?"
252```
253Expected: `ipc-reachable=0` (shell IPC alive). Then manually confirm: open the audio popout — volume sliders and mute still work; with a mic-using app open, the privacy/mic indicator still lights. These paths use `nodeRow`/`privacyLabel`/MPRIS, unchanged by this task.
255- [ ] **Step 10: Commit**
257```bash
258cd /home/oli/Workspace/dotfiles
259git add quickshell/nuguland/Audio.qml
260git commit -m "refactor(audio): replace peak capture with event-driven link state"
261```
263---
265### Task 3: Confirm the energy/battery win
267**Files:** none (measurement only)
269**Interfaces:**
270- Consumes: a running shell on the new code.
271- Produces: evidence the capture streams are gone and idle CPU dropped.
273- [ ] **Step 1: Confirm no peak-capture stream and the sink can suspend when idle**
275With no audio playing, run:
276```bash
277pw-dump | grep -iE "peak|nuguland" | head
278pw-cli info $(pw-cli ls Node 2>/dev/null | grep -i 'alsa.*sink' | head -1 | awk '{print $2}' | tr -d :) 2>/dev/null | grep -i state || true
279```
280Expected: no `nuguland`/peak capture node present; the sink node state is `suspended`/`idle` when nothing plays (it could not suspend while the monitor held a capture stream).
282- [ ] **Step 2: Sample idle CPU**
284Run (popout closed, no audio):
285```bash
286PID=$(systemctl --user show -p MainPID --value quickshell.service)
287top -b -d 3 -n2 -p "$PID" | grep -E "^ *$PID"
288```
289Expected: sustained `%CPU` lower than before (baseline was ~3–4% with spikes from the 30 Hz timer). Record the numbers in the commit/PR description if opening one.
291- [ ] **Step 3: No commit**
293Measurement task — nothing to commit.
295---
297## Self-Review
299**Spec coverage:**
300- Delete both `PwNodePeakMonitor` → Task 2 Step 6. ✓
301- Delete 33 ms timer → Task 2 Step 5. ✓
302- Delete level/sampler props + `shouldMonitor*` + staged `levelsSettling` → Task 2 Steps 1–2, verified Step 7. ✓
303- Add event-driven `outputActive`/`inputActive` → Task 2 Step 1. ✓
304- Update `audioWidgetState`/`stateObject` serialization → Task 2 Steps 3–4. ✓
305- `Media.qml` `mediaEnergyValue` drop level term → Task 1. ✓
306- Keep `PwObjectTracker`, volume/mute, privacy → preserved; verified Task 2 Step 9. ✓
307- Result: no capture, node can suspend, idle CPU down → Task 3. ✓
309**Placeholder scan:** No TBD/TODO; all edits show exact find/replace code. ✓
311**Type consistency:** `outputActive`/`inputActive` are `bool`, defined in Task 2 Step 1 and consumed as booleans in Steps 3–4 (coerced `? 1 : 0` for the numeric `values` array). `mediaEnergyValue()` returns a `0..1` real before and after. ✓

quickshell/nuguland/docs/superpowers/specs/2026-06-26-audio-event-driven-state-design.md

Added
new file mode 100644

+93 / −0 text lines

1# Audio: event-driven state, zero capture
2
3**Date:** 2026-06-26
4**Project:** nuguland (quickshell)
5**Status:** approved (design)
6
7## Problem
8
9The x230 shell feels sluggish (popouts slow to open). Profiling showed idle
10CPU ~3–4% on the main thread with periodic spikes — not the lifetime-cumulative
11~20% first observed (that figure was inflated by an earlier on-AC run with the
12aurora shader live).
14The one always-on hot path is audio level metering:
16- `Audio.qml` runs two `PwNodePeakMonitor` capture streams — output **always**
17 (`shouldMonitorOutput()` = sink exists && unmuted, effectively always true) and
18 input when the mic is active. Each attaches a PipeWire capture stream, keeping
19 the audio node from suspending and waking the CPU per quantum, 24/7, on battery.
20- A 33 ms (`~30 Hz`) `Timer` exponentially smooths the captured peaks into
21 `outputLevelSmooth` / `inputLevelSmooth`.
23Crucially, **nothing on screen renders any of this**. The repo's only real
24`ShaderEffect` instances are Aurora and Lock. The "media-waveform" /
25"system-mini-graph" shaders are JSON *metadata descriptors*, not executed. The
26peak-derived values are consumed only inside serialization
27(`Audio.qml` `audioWidgetState()` 376–410, `Media.qml` `mediaEnergyValue()` 156),
28which is read on demand and rendered by nothing continuous.
30So the shell continuously captures audio to compute numbers it never displays.
32## Decision
34The shell needs *facts*, not amplitude: is output active, is mic/cam live, what
35is the playback state, what is the volume. The user confirmed a true
36audio-amplitude VU/waveform is **not** wanted anywhere ("state is enough").
38All required facts are already available **event-driven**, with no capture:
40- **Output active / mic-in-use** — PipeWire link presence. `linkedNodeId(node)`
41 already scans `Pipewire.links`, filters by `linkActive`, and matches either
42 direction; `nodeActive(node)` = an active link exists. This is the same
43 mechanism the privacy (mic/cam) indicator already trusts. Recomputes on link
44 change — push-based, no timer.
45- **Playback state** — MPRIS `playbackState` (`Media.qml`), already used by
46 `mediaPlayingValue()`.
47- **Volume / mute** — `PwNodeAudio` properties via the existing
48 `PwObjectTracker` (kept; used live by the audio popout).
50PipeWire's `PwNode` exposes **no** `state` (running/suspended) field (confirmed
51against Quickshell master docs), so link state is the correct event-driven proxy
52for "audio flowing."
54## Changes
56### `Audio.qml`
57- **Delete** both `PwNodePeakMonitor` instances (`~550`, `~557`) — stops the two
58 continuous capture streams (the actual battery drain).
59- **Delete** the 33 ms smoothing `Timer` (`~539`).
60- **Delete** level properties: `outputLevel`, `inputLevel`, `outputLevelSmooth`,
61 `inputLevelSmooth`, `audioSamplerOutputActive`, `audioSamplerInputActive`, the
62 staged `levelsSettling` WIP, and `shouldMonitorOutput` / `shouldMonitorInput`
63 (their mute + link logic folds into the new booleans).
64- **Add** event-driven readonly bindings (off `Pipewire.links`, no polling):
65 - `outputActive: nodeActive(defaultSinkNode()) && !nodeMuted(defaultSinkNode())`
66 - `inputActive: nodeActive(defaultSourceNode()) && !nodeMuted(defaultSourceNode())`
67- **Update** `audioWidgetState()` (`376–410`): drop `outputLevel`, `inputLevel`,
68 and the smoothed fields; keep `outputActive` / `inputActive` sourced from the
69 new bindings; the shader `values` array loses its level entries.
70- **Keep** `PwObjectTracker` and all volume/mute logic.
72### `Media.qml`
73- `mediaEnergyValue()` (`156`): drop the `audioService.outputLevelSmooth` term —
74 energy derives from playback state only. Keeps the JSON schema stable; nothing
75 renders the value.
77## Result
79- No continuous audio capture; no 30 Hz timer.
80- Audio nodes free to suspend → lower idle CPU and a real battery win on the x230.
81- Mic/cam privacy and playback indicators unchanged (already link / MPRIS based).
83## Risk
85- Link-state "output active" may lag an actual PipeWire suspend by a beat —
86 acceptable for an indicator. Privacy (mic) detection is unchanged.
88## Out of scope
90- Resource (CPU/mem/disk/temp) polling at 2 s — already low frequency, untouched.
91- Any future amplitude VU — explicitly not wanted now; approaches B (disable
92 monitors, keep plumbing) and C (lazy on-demand capture) were rejected in favor
93 of full removal.