docs(nuguland): audio event-driven-state design + plan
f90827ae5401e2599cc4a3088af6ac2532369975
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 48eaccb20502
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
bugabingas dorkfiles
f90827ae5401e2599cc4a3088af6ac2532369975
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
+404 / −0 text lines
new file mode 100644+311 / −0 text lines
# Audio Event-Driven State Implementation Plan> **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.**Goal:** Remove continuous PipeWire audio capture from the nuguland shell, deriving all audio activity facts from event-driven link state instead.**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.**Tech Stack:** Quickshell (QML), Quickshell.Services.Pipewire (`PwNode`, `PwObjectTracker`, `Pipewire.links`), systemd user service `quickshell.service`.## Global Constraints- 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.- The shell is symlinked: `~/.config/quickshell/nuguland` → `/home/oli/Workspace/dotfiles/quickshell/nuguland`. Edits to the repo are live after a service restart.- Repo root (git toplevel): `/home/oli/Workspace/dotfiles`. Current branch `trunk` is the default branch — create a feature branch before the first commit.- `PwNode` exposes **no** `.state` field; link presence (`nodeActive`) is the only event-driven "audio flowing" proxy. Do not invent a `.state` read.- 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.---### Task 0: Feature branch**Files:** none (git only)- [ ] **Step 1: Create and switch to a feature branch**Run:```bashcd /home/oli/Workspace/dotfilesgit switch -c audio-event-driven-state```Expected: `Switched to a new branch 'audio-event-driven-state'`---### Task 1: Drop the unrendered amplitude consumer in Media.qmlDo this first so that when Task 2 removes `outputLevelSmooth`, no consumer reads a missing property.**Files:**- Modify: `quickshell/nuguland/Media.qml` (function `mediaEnergyValue`, ~line 155)**Interfaces:**- Consumes: `mediaPlayingValue()` (existing, returns `1` when the active MPRIS player is playing, else `0`).- 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.- [ ] **Step 1: Replace the function body**Find:```qml function mediaEnergyValue() { const level = audioService ? audioService.outputLevelSmooth : mediaPlayingValue(); return mediaPlayingValue() * Math.max(0, Math.min(1, Number(level || 0) * 6)); }```Replace with:```qml function mediaEnergyValue() { // Amplitude VU removed (no audio capture). Energy now reflects playback state only. return mediaPlayingValue(); }```- [ ] **Step 2: Restart the shell**Run:```bashsystemctl --user restart quickshell.service```- [ ] **Step 3: Verify no load errors**Run:```bashjournalctl --user -u quickshell.service --since "30 seconds ago" --no-pager | grep -iE "error|warn|undefined|TypeError|is not" || echo CLEAN```Expected: `CLEAN` (plus the normal `INFO: Configuration Loaded` line in full output).- [ ] **Step 4: Commit**```bashcd /home/oli/Workspace/dotfilesgit add quickshell/nuguland/Media.qmlgit commit -m "refactor(audio): drop amplitude term from media energy value"```---### Task 2: Remove audio capture; derive activity from link state (Audio.qml)**Files:**- Modify: `quickshell/nuguland/Audio.qml` - Properties block (~lines 9–25) - `stateObject()` sampler + shader sections (~lines 374–411) - Smoothing `Timer` (~lines 537–545 after the earlier WIP edit) - Both `PwNodePeakMonitor` blocks (~lines 558–565 after the earlier WIP edit)**Interfaces:**- Consumes: `nodeActive(node)` (existing — returns true when an active `Pipewire.links` entry touches the node), `nodeMuted(node)`, `defaultSinkNode()`, `defaultSourceNode()`, `outputMutedValue()`, `inputMutedValue()`.- Produces: - `outputActive: bool` — readonly binding, true when an active link reaches the default sink and it is not muted. - `inputActive: bool` — readonly binding, true when an active link reaches the default source and it is not muted. - Removes properties: `outputLevel`, `inputLevel`, `outputLevelSmooth`, `inputLevelSmooth`, `audioSamplerOutputActive`, `audioSamplerInputActive`, `levelsSettling`. Removes functions `shouldMonitorOutput()`, `shouldMonitorInput()`. No remaining code may reference these.- [ ] **Step 1: Replace the level properties with event-driven activity bindings**Find (the current head of the `Item`, including the earlier WIP `levelsSettling` block):```qml readonly property real outputLevel: shouldMonitorOutput() ? Math.max(0, Math.min(1, Number(outputPeak.peak || 0))) : 0 readonly property real inputLevel: shouldMonitorInput() ? Math.max(0, Math.min(1, Number(inputPeak.peak || 0))) : 0 property real outputLevelSmooth: 0 property real inputLevelSmooth: 0 readonly property string audioSamplerBackend: "PwNodePeakMonitor" readonly property bool audioSamplerOutputActive: outputLevel > 0.005 readonly property bool audioSamplerInputActive: inputLevel > 0.005 // TODO(you): gate the 33ms VU-smoothing timer so it sleeps when nothing moves. // Return true only while the smoothed values still need to chase the live peaks. // When the native peak monitor pushes a new outputLevel/inputLevel, this binding // re-evaluates for free and wakes the timer (same trick AuroraBackdrop.qml:83 uses). // Pick an epsilon: too small never sleeps (float never reaches 0), too big drops // the visible tail of the fade. ~0.004 is a reasonable start. readonly property bool levelsSettling: false // <-- replace with your condition```Replace with:```qml readonly property string audioSamplerBackend: "Pipewire.links" // Audio activity is derived from PipeWire link presence (event-driven), not from // capturing audio. nodeActive() scans Pipewire.links for an active link touching // the node, so these re-evaluate when links change — no capture stream, no timer. readonly property bool outputActive: nodeActive(defaultSinkNode()) && !nodeMuted(defaultSinkNode()) readonly property bool inputActive: nodeActive(defaultSourceNode()) && !nodeMuted(defaultSourceNode())```- [ ] **Step 2: Delete the two `shouldMonitor*` functions**Find:```qml function shouldMonitorOutput() { const sink = defaultSinkNode(); return !!(sink && !nodeMuted(sink)); } function shouldMonitorInput() { const source = defaultSourceNode(); return !!(source && !nodeMuted(source) && nodeActive(source)); }```Replace with nothing (remove the block entirely, including the trailing blank line).- [ ] **Step 3: Update the `sampler` block in `stateObject()`**Find:```qml "sampler": { "backend": "PwNodePeakMonitor", "outputLevel": outputLevel, "inputLevel": inputLevel, "channels": outputPeak.channels.length || inputPeak.channels.length || 0, "outputActive": audioSamplerOutputActive, "inputActive": audioSamplerInputActive, "targets": shouldMonitorInput() ? ["defaultAudioSink", "defaultAudioSource"] : ["defaultAudioSink"], "efficient": true, "native": true },```Replace with:```qml "sampler": { "backend": "Pipewire.links", "outputActive": outputActive, "inputActive": inputActive, "targets": inputActive ? ["defaultAudioSink", "defaultAudioSource"] : ["defaultAudioSink"], "efficient": true, "native": true, "capture": false },```- [ ] **Step 4: Update the `shader` values array (unrendered, schema kept length-4)**Find:```qml "values": [outputLevelSmooth, outputMutedValue(), inputLevelSmooth, inputMutedValue()],```Replace with:```qml "values": [outputActive ? 1 : 0, outputMutedValue(), inputActive ? 1 : 0, inputMutedValue()],```- [ ] **Step 5: Delete the smoothing `Timer`**Find:```qml Timer { interval: 33 repeat: true running: root.levelsSettling onTriggered: { outputLevelSmooth += (outputLevel - outputLevelSmooth) * 0.18; inputLevelSmooth += (inputLevel - inputLevelSmooth) * 0.18; } }```Replace with nothing (remove the block, including the trailing blank line).- [ ] **Step 6: Delete both `PwNodePeakMonitor` blocks**Find:```qml PwNodePeakMonitor { id: outputPeak node: root.defaultSinkNode() enabled: root.shouldMonitorOutput() } PwNodePeakMonitor { id: inputPeak node: root.defaultSourceNode() enabled: root.shouldMonitorInput() }```Replace with nothing (remove both blocks). Keep the `PwObjectTracker` block above them.- [ ] **Step 7: Verify no dangling references remain**Run:```bashcd /home/oli/Workspace/dotfiles/quickshell/nugulandgrep -nE "outputLevel|inputLevel|outputLevelSmooth|inputLevelSmooth|audioSampler(Output|Input)Active|shouldMonitor(Output|Input)|levelsSettling|PwNodePeakMonitor|outputPeak|inputPeak" Audio.qml Media.qml || echo NO-DANGLING```Expected: `NO-DANGLING`.- [ ] **Step 8: Restart and verify clean load**Run:```bashsystemctl --user restart quickshell.servicesleep 2journalctl --user -u quickshell.service --since "30 seconds ago" --no-pager | grep -iE "error|warn|undefined|TypeError|is not|ReferenceError" || echo CLEAN```Expected: `CLEAN`.- [ ] **Step 9: Verify audio state serializes and privacy still works**Run:```bashqs -c nuguland ipc call nuguland systemWidgetState >/dev/null 2>&1; echo "ipc-reachable=$?"```Expected: `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.- [ ] **Step 10: Commit**```bashcd /home/oli/Workspace/dotfilesgit add quickshell/nuguland/Audio.qmlgit commit -m "refactor(audio): replace peak capture with event-driven link state"```---### Task 3: Confirm the energy/battery win**Files:** none (measurement only)**Interfaces:**- Consumes: a running shell on the new code.- Produces: evidence the capture streams are gone and idle CPU dropped.- [ ] **Step 1: Confirm no peak-capture stream and the sink can suspend when idle**With no audio playing, run:```bashpw-dump | grep -iE "peak|nuguland" | headpw-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```Expected: 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).- [ ] **Step 2: Sample idle CPU**Run (popout closed, no audio):```bashPID=$(systemctl --user show -p MainPID --value quickshell.service)top -b -d 3 -n2 -p "$PID" | grep -E "^ *$PID"```Expected: 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.- [ ] **Step 3: No commit**Measurement task — nothing to commit.---## Self-Review**Spec coverage:**- Delete both `PwNodePeakMonitor` → Task 2 Step 6. ✓- Delete 33 ms timer → Task 2 Step 5. ✓- Delete level/sampler props + `shouldMonitor*` + staged `levelsSettling` → Task 2 Steps 1–2, verified Step 7. ✓- Add event-driven `outputActive`/`inputActive` → Task 2 Step 1. ✓- Update `audioWidgetState`/`stateObject` serialization → Task 2 Steps 3–4. ✓- `Media.qml` `mediaEnergyValue` drop level term → Task 1. ✓- Keep `PwObjectTracker`, volume/mute, privacy → preserved; verified Task 2 Step 9. ✓- Result: no capture, node can suspend, idle CPU down → Task 3. ✓**Placeholder scan:** No TBD/TODO; all edits show exact find/replace code. ✓**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. ✓new file mode 100644+93 / −0 text lines
# Audio: event-driven state, zero capture**Date:** 2026-06-26**Project:** nuguland (quickshell)**Status:** approved (design)## ProblemThe x230 shell feels sluggish (popouts slow to open). Profiling showed idleCPU ~3–4% on the main thread with periodic spikes — not the lifetime-cumulative~20% first observed (that figure was inflated by an earlier on-AC run with theaurora shader live).The one always-on hot path is audio level metering:- `Audio.qml` runs two `PwNodePeakMonitor` capture streams — output **always** (`shouldMonitorOutput()` = sink exists && unmuted, effectively always true) and input when the mic is active. Each attaches a PipeWire capture stream, keeping the audio node from suspending and waking the CPU per quantum, 24/7, on battery.- A 33 ms (`~30 Hz`) `Timer` exponentially smooths the captured peaks into `outputLevelSmooth` / `inputLevelSmooth`.Crucially, **nothing on screen renders any of this**. The repo's only real`ShaderEffect` instances are Aurora and Lock. The "media-waveform" /"system-mini-graph" shaders are JSON *metadata descriptors*, not executed. Thepeak-derived values are consumed only inside serialization(`Audio.qml` `audioWidgetState()` 376–410, `Media.qml` `mediaEnergyValue()` 156),which is read on demand and rendered by nothing continuous.So the shell continuously captures audio to compute numbers it never displays.## DecisionThe shell needs *facts*, not amplitude: is output active, is mic/cam live, whatis the playback state, what is the volume. The user confirmed a trueaudio-amplitude VU/waveform is **not** wanted anywhere ("state is enough").All required facts are already available **event-driven**, with no capture:- **Output active / mic-in-use** — PipeWire link presence. `linkedNodeId(node)` already scans `Pipewire.links`, filters by `linkActive`, and matches either direction; `nodeActive(node)` = an active link exists. This is the same mechanism the privacy (mic/cam) indicator already trusts. Recomputes on link change — push-based, no timer.- **Playback state** — MPRIS `playbackState` (`Media.qml`), already used by `mediaPlayingValue()`.- **Volume / mute** — `PwNodeAudio` properties via the existing `PwObjectTracker` (kept; used live by the audio popout).PipeWire's `PwNode` exposes **no** `state` (running/suspended) field (confirmedagainst Quickshell master docs), so link state is the correct event-driven proxyfor "audio flowing."## Changes### `Audio.qml`- **Delete** both `PwNodePeakMonitor` instances (`~550`, `~557`) — stops the two continuous capture streams (the actual battery drain).- **Delete** the 33 ms smoothing `Timer` (`~539`).- **Delete** level properties: `outputLevel`, `inputLevel`, `outputLevelSmooth`, `inputLevelSmooth`, `audioSamplerOutputActive`, `audioSamplerInputActive`, the staged `levelsSettling` WIP, and `shouldMonitorOutput` / `shouldMonitorInput` (their mute + link logic folds into the new booleans).- **Add** event-driven readonly bindings (off `Pipewire.links`, no polling): - `outputActive: nodeActive(defaultSinkNode()) && !nodeMuted(defaultSinkNode())` - `inputActive: nodeActive(defaultSourceNode()) && !nodeMuted(defaultSourceNode())`- **Update** `audioWidgetState()` (`376–410`): drop `outputLevel`, `inputLevel`, and the smoothed fields; keep `outputActive` / `inputActive` sourced from the new bindings; the shader `values` array loses its level entries.- **Keep** `PwObjectTracker` and all volume/mute logic.### `Media.qml`- `mediaEnergyValue()` (`156`): drop the `audioService.outputLevelSmooth` term — energy derives from playback state only. Keeps the JSON schema stable; nothing renders the value.## Result- No continuous audio capture; no 30 Hz timer.- Audio nodes free to suspend → lower idle CPU and a real battery win on the x230.- Mic/cam privacy and playback indicators unchanged (already link / MPRIS based).## Risk- Link-state "output active" may lag an actual PipeWire suspend by a beat — acceptable for an indicator. Privacy (mic) detection is unchanged.## Out of scope- Resource (CPU/mem/disk/temp) polling at 2 s — already low frequency, untouched.- Any future amplitude VU — explicitly not wanted now; approaches B (disable monitors, keep plumbing) and C (lazy on-demand capture) were rejected in favor of full removal.