From 00757d361a57a8bcc921d6be99adbea5db942ef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 01/10] decide -version from the command line only PIPMIX_VERSION in the environment no longer sets it, and a broken config file no longer stops it. --- internal/pipmix/config_test.go | 19 +++++++++++++++++ internal/pipmix/pipmix.go | 8 ++++++- internal/pipmix/version.go | 39 ++++++++++++++++++++++++++++------ 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/internal/pipmix/config_test.go b/internal/pipmix/config_test.go index ea3181a..645ecc0 100644 --- a/internal/pipmix/config_test.go +++ b/internal/pipmix/config_test.go @@ -191,3 +191,22 @@ func TestOpenDebugLog(t *testing.T) { t.Errorf("log at %s, want %s", f.Name(), path) } } + +func TestVersionCommandLineOnly(t *testing.T) { + t.Setenv("PIPMIX_VERSION", "1.4.0") + t.Setenv("PIPMIX_VERSION_INFO", "true") + args := []string{"-config", filepath.Join(t.TempDir(), "none.toml")} + fs := flag.NewFlagSet("pipmix", flag.ContinueOnError) + v := addVersionFlags(fs) + addFlags(fs) + if err := fs.Parse(args); err != nil { + t.Fatal(err) + } + v.lock() + if err := parseFlags(fs, args); err != nil { + t.Fatalf("PIPMIX_VERSION in the environment: %v", err) + } + if v.print(io.Discard) { + t.Error("the environment set -version") + } +} diff --git a/internal/pipmix/pipmix.go b/internal/pipmix/pipmix.go index f5c023a..249f963 100644 --- a/internal/pipmix/pipmix.go +++ b/internal/pipmix/pipmix.go @@ -24,12 +24,18 @@ func Run(args []string) error { version := addVersionFlags(fs) debug := addDebugFlags(fs) values := addFlags(fs) - if err := parseFlags(fs, args); err != nil { + // The command line alone decides -version, so that PIPMIX_VERSION in the + // environment doesn't set it and a broken config file doesn't stop it. + if err := fs.Parse(args); err != nil { return err } if version.print(os.Stdout) { return nil } + version.lock() + if err := parseFlags(fs, args); err != nil { + return err + } opts, err := values.check() if err != nil { return err diff --git a/internal/pipmix/version.go b/internal/pipmix/version.go index 4a21b08..871140a 100644 --- a/internal/pipmix/version.go +++ b/internal/pipmix/version.go @@ -5,23 +5,28 @@ import ( "fmt" "io" "runtime/debug" + "strconv" ) type versionFlags struct { - version bool - info bool + version cliBool + info cliBool } func addVersionFlags(fs *flag.FlagSet) *versionFlags { v := &versionFlags{} - fs.BoolVar(&v.version, "version", false, "print the version and exit") - fs.BoolVar(&v.info, "version.info", false, "print the version, Go build info and module versions, and exit") + fs.Var(&v.version, "version", "print the version and exit; command line only") + fs.Var(&v.info, "version.info", "print the version, Go build info and module versions, and exit; command line only") return v } +// lock makes the flags ignore the environment and the config file, which +// are read after the command line. +func (v *versionFlags) lock() { v.version.locked, v.info.locked = true, true } + // print writes what the set flags ask for to w and reports whether any was set. func (v *versionFlags) print(w io.Writer) bool { - if !v.version && !v.info { + if !v.version.v && !v.info.v { return false } bi, ok := debug.ReadBuildInfo() @@ -30,8 +35,30 @@ func (v *versionFlags) print(w io.Writer) bool { return true } fmt.Fprintln(w, "pipmix", bi.Main.Version) - if v.info { + if v.info.v { fmt.Fprint(w, bi) } return true } + +// A cliBool is a bool flag that ignores Set once locked. +type cliBool struct { + v bool + locked bool +} + +func (b *cliBool) String() string { return strconv.FormatBool(b.v) } + +func (b *cliBool) Set(s string) error { + if b.locked { + return nil + } + v, err := strconv.ParseBool(s) + if err != nil { + return err + } + b.v = v + return nil +} + +func (b *cliBool) IsBoolFlag() bool { return true } From 9f27cd73811cec1a1d67925cb3d7c0a866900089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 02/10] track node state and links in snapshots Snapshot nodes now say whether they are active, and which nodes a stream plays to or records from. --- internal/pw/proto.go | 1 + internal/pw/session.go | 115 ++++++++++++++++++++++-- internal/pw/session_test.go | 168 ++++++++++++++++++++++++++++++++++++ internal/pw/snapshot.go | 33 +++++++ 4 files changed, 312 insertions(+), 5 deletions(-) diff --git a/internal/pw/proto.go b/internal/pw/proto.go index ff2b569..d32b8a0 100644 --- a/internal/pw/proto.go +++ b/internal/pw/proto.go @@ -74,6 +74,7 @@ const ( // Node::info and Device::info change mask bits. const ( + nodeChangeState = 1 << 2 nodeChangeProps = 1 << 3 nodeChangeParams = 1 << 4 deviceChangeProps = 1 << 0 diff --git a/internal/pw/session.go b/internal/pw/session.go index 523ed42..2fe29aa 100644 --- a/internal/pw/session.go +++ b/internal/pw/session.go @@ -84,6 +84,7 @@ type node struct { volumes []float32 // current channel volumes (linear) channels []uint32 // channel map positions (e.g. FL, FR) mute bool // true if node is muted + state State // processing state from last Node::info event pendingVolumes []float32 // last volume set by client while pending pendingMute *bool // last mute state set by client while pending pendingUntil time.Time // deadline until client pending values win @@ -123,6 +124,11 @@ type enumReq struct { values []pod // collected reply pods } +// A link connects an output node to an input node. +type link struct { + out, in uint32 // global IDs of the nodes +} + type portInfo struct { id uint32 // PipeWire registry global ID of the port node uint32 // node ID this port belongs to @@ -152,6 +158,7 @@ type session struct { proxies map[uint32]*proxy // proxy ID → proxy object nodes map[uint32]*node // global ID → audio node ports map[uint32]portInfo // global ID → audio port info + links map[uint32]link // global ID → link between nodes jackMeters map[string]*jackMeter // meter node name → JACK meter tracker meters map[uint32]*node // global ID → meter stream nodes owned by this instance meterPrefix string // prefix of meter stream nodes owned by this instance @@ -182,6 +189,7 @@ func newSession(c *conn, logger *log.Logger, pid int) *session { proxies: make(map[uint32]*proxy), nodes: make(map[uint32]*node), ports: make(map[uint32]portInfo), + links: make(map[uint32]link), jackMeters: make(map[string]*jackMeter), meters: make(map[uint32]*node), meterPrefix: fmt.Sprintf("%s%d.", MeterPrefix, pid), @@ -435,6 +443,13 @@ func (s *session) registryEvent(op uint8, f *parser) error { } return nil } + if l, ok := s.links[id]; ok { + delete(s.links, id) + if s.linkCounts(l) { + s.dirty = true + } + return nil + } delete(s.nodes, id) delete(s.meters, id) for name, jm := range s.jackMeters { @@ -523,6 +538,11 @@ func (s *session) global(id uint32, typ string, version int32, props map[string] if err1 != nil || err2 != nil { return } + l := link{out: uint32(outNode), in: uint32(inNode)} + s.links[id] = l + if s.linkCounts(l) { + s.dirty = true + } for _, jm := range s.jackMeters { if jm.node == uint32(inNode) && uint32(outNode) != jm.target { if jm.ready { @@ -675,13 +695,19 @@ func (s *session) nodeEvent(p *proxy, op uint8, f *parser) error { change := f.long() inPorts := f.int() outPorts := f.int() - f.u32() // state - f.string() + state := State(f.int()) + f.string() // error props := f.dict() params := f.paramInfo() if f.err != nil { return f.err } + if change&nodeChangeState != 0 && state != n.state { + n.state = state + if !n.meter { + s.dirty = true + } + } if inPorts != n.inPorts || outPorts != n.outPorts { n.inPorts, n.outPorts = inPorts, outPorts if n.jack { @@ -1171,15 +1197,93 @@ func (s *session) setDefault(id uint32) { s.dirty = true } +// metering reports whether n only measures levels, as pipmix's meters and +// the monitor streams of other mixers do. +func metering(n *node) bool { + return n.meter || n.props[propStreamMonitor] == "true" +} + +// linkCounts reports whether adding or removing l can change a snapshot. +// That is the case if at least one end is a node pipmix tracks and neither +// end is a level meter. Meter links are ignored because they are created and +// removed every time the set of metered nodes changes. +func (s *session) linkCounts(l link) bool { + in, out := s.nodes[l.in], s.nodes[l.out] + return (in != nil || out != nil) && (in == nil || !metering(in)) && (out == nil || !metering(out)) +} + +// linkInfo walks the links once and returns what a snapshot needs from +// them. Links with a level meter at either end are skipped. +// +// - from maps each recording stream to the IDs of the nodes linked into +// it, sorted. +// - to maps each playback stream to the IDs of the nodes it is linked +// into, sorted. +// - active holds the devices that are running and linked to a running +// node. A linked node that pipmix doesn't track counts as running. +func (s *session) linkInfo() (from, to map[uint32][]uint32, active map[uint32]bool) { + add := func(m map[uint32][]uint32, k, v uint32) map[uint32][]uint32 { + if m == nil { + m = make(map[uint32][]uint32) + } + if !slices.Contains(m[k], v) { + m[k] = append(m[k], v) + } + return m + } + // device marks node id active if it is a running device and peer, the + // node at the other end of the link, is running or untracked. + device := func(id uint32, n, peer *node) { + if n == nil || n.jack || n.class != Sink && n.class != Source || n.state != StateRunning { + return + } + if peer != nil && peer.state != StateRunning { + return + } + if active == nil { + active = make(map[uint32]bool) + } + active[id] = true + } + for _, l := range s.links { + if !s.linkCounts(l) { + continue + } + in, out := s.nodes[l.in], s.nodes[l.out] + if in != nil && !in.jack && in.class == Recording { + from = add(from, l.in, l.out) + } + if out != nil && !out.jack && out.class == Playback { + to = add(to, l.out, l.in) + } + device(l.in, in, out) + device(l.out, out, in) + } + for _, ids := range from { + slices.Sort(ids) + } + for _, ids := range to { + slices.Sort(ids) + } + return from, to, active +} + func (s *session) snapshot(now time.Time) *Snapshot { snap := &Snapshot{Connected: true} + from, to, active := s.linkInfo() for _, id := range slices.Sorted(maps.Keys(s.nodes)) { n := s.nodes[id] - if n.meter || n.props[propStreamMonitor] == "true" { + if metering(n) { continue } if !n.jack { - snap.Nodes = append(snap.Nodes, s.nodeView(n, now)) + v := s.nodeView(n, now) + v.Active = n.state == StateRunning + if n.class == Sink || n.class == Source { + v.Active = active[id] + } + v.From, v.To = from[id], to[id] + snap.Nodes = append(snap.Nodes, v) continue } for _, c := range []struct { @@ -1188,7 +1292,7 @@ func (s *session) snapshot(now time.Time) *Snapshot { }{{Playback, n.outPorts}, {Recording, n.inPorts}} { if c.ports > 0 { v := s.nodeView(n, now) - v.Class, v.JACK = c.class, true + v.Class, v.JACK, v.Active = c.class, true, n.state == StateRunning if c.class == Playback { for i, p := range s.nodePorts(n.id, true) { name := cmp.Or(p.name, "CH"+strconv.Itoa(i+1)) @@ -1233,6 +1337,7 @@ func (s *session) nodeView(n *node, now time.Time) Node { Class: n.class, Name: n.props[propNodeName], Props: props, + State: n.state, Route: -1, } v.Client = cmp.Or(props[propNodeDescription], v.Name, props[propApplicationName]) diff --git a/internal/pw/session_test.go b/internal/pw/session_test.go index a27b4f1..8d3eb97 100644 --- a/internal/pw/session_test.go +++ b/internal/pw/session_test.go @@ -3,6 +3,8 @@ package pw import ( "net" "path/filepath" + "slices" + "strconv" "testing" "time" ) @@ -92,3 +94,169 @@ func TestConnFillCompaction(t *testing.T) { t.Fatalf("buf grew to %d bytes; expected compaction to reuse 8192-byte buffer", len(c.buf)) } } + +func TestNodeInfoState(t *testing.T) { + s := newSession(nil, nil, 1) + p := &proxy{id: 5, kind: kindNode, global: 10} + n := &node{id: 10, proxy: p.id, class: Recording} + s.nodes[n.id] = n + + info := func(change int64, state State) { + t.Helper() + var b builder + b.structure(func() { + b.int(int32(n.id)) + b.int(0) // max input ports + b.int(0) // max output ports + b.long(change) + b.int(0) // input ports + b.int(0) // output ports + b.int(int32(state)) + b.none() // error + b.dict(nil) + b.structure(func() { b.int(0) }) // params + }) + pd, _, err := readPod(b.buf) + if err != nil { + t.Fatal(err) + } + f, err := pd.fields() + if err != nil { + t.Fatal(err) + } + s.dirty = false + if err := s.nodeEvent(p, eventInfo, f); err != nil { + t.Fatal(err) + } + } + + info(nodeChangeState, StateRunning) + if v := s.nodeView(n, time.Now()); v.State != StateRunning || !s.dirty { + t.Fatalf("after running: state %v, dirty %v; want running, true", v.State, s.dirty) + } + info(0, StateIdle) // state not in the change mask + if n.state != StateRunning || s.dirty { + t.Fatalf("unchanged mask: state %v, dirty %v; want running, false", n.state, s.dirty) + } + info(nodeChangeState, StateRunning) // same state again + if s.dirty { + t.Fatal("repeated state marked the session dirty") + } + info(nodeChangeState, StateSuspended) + if n.state != StateSuspended || !s.dirty { + t.Fatalf("after suspend: state %v, dirty %v; want suspended, true", n.state, s.dirty) + } +} + +func TestActiveDevices(t *testing.T) { + s := newSession(nil, nil, 1) + add := func(id uint32, class Class, state State, props map[string]string) *node { + n := &node{id: id, class: class, state: state, props: props} + s.nodes[id] = n + return n + } + sink := add(1, Sink, StateRunning, nil) + add(2, Recording, StateRunning, nil).meter = true // pipmix's meter + add(3, Recording, StateRunning, map[string]string{propStreamMonitor: "true"}) // another mixer's + firefox := add(4, Playback, StateIdle, nil) // paused + add(5, Source, StateRunning, nil) + s.links[10] = link{out: 1, in: 2} + s.links[11] = link{out: 1, in: 3} + s.links[12] = link{out: 4, in: 1} + + active := func() bool { + snap := s.snapshot(time.Now()) + for _, n := range snap.Nodes { + if n.ID == 1 { + return n.Active + } + } + t.Fatal("sink not in snapshot") + return false + } + if active() { + t.Error("sink active with only meters and a paused stream linked") + } + firefox.state = StateRunning + if !active() { + t.Error("sink inactive with a running stream linked") + } + sink.state = StateSuspended + if active() { + t.Error("suspended sink active") + } + sink.state = StateRunning + delete(s.links, 12) + s.links[13] = link{out: 99, in: 1} // a node pipmix doesn't track + if !active() { + t.Error("sink inactive with an untracked node linked") + } +} + +func TestStreamLinks(t *testing.T) { + s := newSession(nil, nil, 1) + for _, n := range []*node{ + {id: 1, class: Source}, {id: 2, class: Sink}, {id: 3, class: Recording}, + {id: 4, class: Recording, meter: true}, + {id: 5, class: Playback}, + } { + s.nodes[n.id] = n + } + s.links[10] = link{out: 1, in: 3} // FL + s.links[11] = link{out: 1, in: 3} // FR + s.links[12] = link{out: 2, in: 3} + s.links[13] = link{out: 1, in: 4} // a meter + s.links[14] = link{out: 5, in: 2} + s.links[15] = link{out: 5, in: 4} // a meter + for _, n := range s.snapshot(time.Now()).Nodes { + if n.ID == 3 && !slices.Equal(n.From, []uint32{1, 2}) { + t.Errorf("recording 3 from %v, want [1 2]", n.From) + } + if n.ID != 3 && n.From != nil { + t.Errorf("node %d from %v, want none", n.ID, n.From) + } + if n.ID == 5 && !slices.Equal(n.To, []uint32{2}) { + t.Errorf("playback 5 to %v, want [2]", n.To) + } + } +} + +// TestLinkDirty checks which new links change the snapshot: those that bear +// on whether a device is active, or on what a stream plays to or records +// from. +func TestLinkDirty(t *testing.T) { + s := newSession(nil, nil, 1) + for _, n := range []*node{ + {id: 1, class: Sink}, {id: 2, class: Source}, + {id: 3, class: Recording}, {id: 5, class: Playback}, + {id: 4, class: Recording, meter: true}, // pipmix's meter + {id: 6, class: Recording, props: map[string]string{propStreamMonitor: "true"}}, // another mixer's + } { + s.nodes[n.id] = n + } + for _, tc := range []struct { + name string + out, in uint32 + want bool + }{ + {"stream to device", 5, 1, true}, + {"device to stream", 2, 3, true}, + {"stream to stream", 5, 3, true}, + {"untracked to device", 99, 1, true}, + {"stream to untracked", 5, 99, true}, + {"untracked to stream", 99, 3, true}, + {"device to meter", 1, 4, false}, + {"device to another mixer's meter", 1, 6, false}, + {"stream to meter", 5, 4, false}, + {"untracked to untracked", 98, 99, false}, + } { + s.dirty = false + s.global(100, ifaceLink, 3, map[string]string{ + "link.output.node": strconv.Itoa(int(tc.out)), + "link.input.node": strconv.Itoa(int(tc.in)), + }) + if s.dirty != tc.want { + t.Errorf("%s: dirty %v, want %v", tc.name, s.dirty, tc.want) + } + } +} diff --git a/internal/pw/snapshot.go b/internal/pw/snapshot.go index 046fbde..596df35 100644 --- a/internal/pw/snapshot.go +++ b/internal/pw/snapshot.go @@ -1,5 +1,7 @@ package pw +import "strconv" + // A Snapshot is the mixer's state at one moment. type Snapshot struct { Connected bool @@ -30,8 +32,39 @@ type Node struct { Channels []Channel Mute bool Default bool + State State Routes []Route Route int // active index in Routes, or -1 + + // Active reports whether the node processes audio for more than level + // meters: a stream that runs, or a device that runs with a running + // stream or other client linked to it. + Active bool + + // From lists, in order, the nodes that link audio into a recording + // stream, and To the nodes a playback stream links audio into, leaving + // out level meters. + From, To []uint32 +} + +// A State is a node's processing state. +type State int + +const ( + StateError State = -1 + StateCreating State = 0 + StateSuspended State = 1 + StateIdle State = 2 + StateRunning State = 3 +) + +var stateNames = [...]string{"error", "creating", "suspended", "idle", "running"} + +func (s State) String() string { + if i := int(s) + 1; i >= 0 && i < len(stateNames) { + return stateNames[i] + } + return "state(" + strconv.Itoa(int(s)) + ")" } // A Channel is one channel's volume on the cubic scale (1 is 100%). From 43cd2df4217c67d27a4a9ecf9634b3daefb9ecb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 03/10] name ALSA plugin streams after their process The plugin names every stream "ALSA Playback" or "ALSA Capture". --- internal/pw/session.go | 45 ++++++++++++++++++++++++++++++++++--- internal/pw/session_test.go | 32 ++++++++++++++++++++++++++ internal/pw/snapshot.go | 5 +++++ 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/internal/pw/session.go b/internal/pw/session.go index 2fe29aa..05d4155 100644 --- a/internal/pw/session.go +++ b/internal/pw/session.go @@ -480,6 +480,12 @@ func (s *session) registryEvent(op uint8, f *parser) error { func (s *session) global(id uint32, typ string, version int32, props map[string]string) { switch typ { case ifaceClient: + if alsaClient(props) { + if name := localProcessName(props); name != "" { + props = maps.Clone(props) + props[PropProcessName] = name + } + } s.clients[id] = props s.clientsGen++ case ifaceNode: @@ -1197,6 +1203,35 @@ func (s *session) setDefault(id uint32) { s.dirty = true } +// alsaClient reports whether a client's registry properties are those of +// PipeWire's ALSA plugin. The registry leaves out client.api, but the plugin +// names the application "PipeWire ALSA [binary]". +func alsaClient(props map[string]string) bool { + return props[propClientAPI] == "alsa" || strings.HasPrefix(props[propApplicationName], "PipeWire ALSA [") +} + +// localProcessName returns the name of a client's process, if it runs on +// this host. PipeWire takes pipewire.sec.pid from the client's socket. +var localProcessName = func(props map[string]string) string { + pid, err := strconv.Atoi(props["pipewire.sec.pid"]) + if err != nil { + pid, err = strconv.Atoi(props[propApplicationProcessID]) + if host := props["application.process.host"]; host != "" { + if h, herr := os.Hostname(); herr != nil || h != host { + return "" + } + } + } + if err != nil || pid <= 0 { + return "" + } + b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/comm") + if err != nil { + return "" + } + return strings.TrimSpace(string(b)) +} + // metering reports whether n only measures levels, as pipmix's meters and // the monitor streams of other mixers do. func metering(n *node) bool { @@ -1316,7 +1351,7 @@ func (s *session) nodeView(n *node, now time.Time) Node { if clientID, err := strconv.ParseUint(n.props["client.id"], 10, 32); err == nil { if cp := s.clients[uint32(clientID)]; cp != nil { cloned := false - for _, k := range []string{propApplicationProcessID, propApplicationName} { + for _, k := range []string{propApplicationProcessID, propApplicationName, PropProcessName} { if _, ok := props[k]; !ok { if val := cp[k]; val != "" { if !cloned { @@ -1340,9 +1375,13 @@ func (s *session) nodeView(n *node, now time.Time) Node { State: n.state, Route: -1, } - v.Client = cmp.Or(props[propNodeDescription], v.Name, props[propApplicationName]) + v.Client = cmp.Or(props[PropProcessName], props[propNodeDescription], v.Name, props[propApplicationName]) v.Title = v.Client - if media := props[propMediaName]; media != "" && media != v.Title { + media := props[propMediaName] + if props[PropProcessName] != "" && (media == "ALSA Playback" || media == "ALSA Capture") { + media = "" // the ALSA plugin's default, which says nothing + } + if media != "" && media != v.Title { v.Title += ": " + media } if n.known { diff --git a/internal/pw/session_test.go b/internal/pw/session_test.go index 8d3eb97..e4ecd0b 100644 --- a/internal/pw/session_test.go +++ b/internal/pw/session_test.go @@ -193,6 +193,38 @@ func TestActiveDevices(t *testing.T) { } } +func TestALSAClientName(t *testing.T) { + defer func(f func(map[string]string) string) { localProcessName = f }(localProcessName) + localProcessName = func(props map[string]string) string { + if props["pipewire.sec.pid"] == "135588" { + return "claude" + } + return "" + } + s := newSession(nil, nil, 1) + // The registry announces clients without client.api. + s.global(165, ifaceClient, 3, map[string]string{propApplicationName: "PipeWire ALSA [2.1.332]", "pipewire.sec.pid": "135588"}) + s.global(166, ifaceClient, 3, map[string]string{propApplicationName: "pipmix", "pipewire.sec.pid": "135588"}) // not ALSA + view := func(client, media string) Node { + n := &node{id: 10, class: Recording, props: map[string]string{ + "client.id": client, propNodeName: "alsa_capture.2.1.332", + propNodeDescription: "ALSA Capture [2.1.332]", propMediaName: media, + }} + return s.nodeView(n, time.Now()) + } + for _, tc := range []struct { + client, media, wantClient, wantTitle string + }{ + {"165", "ALSA Capture", "claude", "claude"}, + {"165", "Dictation", "claude", "claude: Dictation"}, + {"166", "ALSA Capture", "ALSA Capture [2.1.332]", "ALSA Capture [2.1.332]: ALSA Capture"}, + } { + if v := view(tc.client, tc.media); v.Client != tc.wantClient || v.Title != tc.wantTitle { + t.Errorf("client %s, media %q: client %q, title %q; want %q, %q", tc.client, tc.media, v.Client, v.Title, tc.wantClient, tc.wantTitle) + } + } +} + func TestStreamLinks(t *testing.T) { s := newSession(nil, nil, 1) for _, n := range []*node{ diff --git a/internal/pw/snapshot.go b/internal/pw/snapshot.go index 596df35..8de71bf 100644 --- a/internal/pw/snapshot.go +++ b/internal/pw/snapshot.go @@ -47,6 +47,11 @@ type Node struct { From, To []uint32 } +// PropProcessName is the property in Node.Props that names the local +// process of a stream from PipeWire's ALSA plugin, which names its streams +// generically. pipmix reads it from /proc. +const PropProcessName = "pipmix.process.name" + // A State is a node's processing state. type State int From 7b8676ae7e141131a4e6ae3f52fba812a90ec364 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 04/10] share pulse meter streams and allow a rate per target Two meter streams made at once on one source can leave PipeWire running only the first for seconds. --- internal/pulse/meter.go | 131 ++++++++++++++++++++++++----------- internal/pulse/meter_test.go | 81 +++++++++++++++++++++- 2 files changed, 169 insertions(+), 43 deletions(-) diff --git a/internal/pulse/meter.go b/internal/pulse/meter.go index df936af..8eb5fd0 100644 --- a/internal/pulse/meter.go +++ b/internal/pulse/meter.go @@ -2,12 +2,14 @@ package pulse import ( + "cmp" "context" "encoding/binary" "errors" "fmt" "io" "log" + "maps" "math" "net" "os" @@ -45,6 +47,11 @@ type Target struct { Name string // node.name of a Sink or Source Serial uint32 // object.serial of a Stream, or node ID of a JACK client Channels []string + + // Rate is how many peaks a second the target's stream sends, or 0 for + // the meter's own rate. At any rate, each peak is the highest level + // since the peak before it. A lower rate wakes this process less often. + Rate int } func (t Target) String() string { @@ -60,6 +67,12 @@ func (t Target) String() string { } func (t Target) Equal(u Target) bool { + return t.Rate == u.Rate && t.sameNode(u) +} + +// sameNode reports whether t and u measure the same channels of the same +// node, at whatever rates. +func (t Target) sameNode(u Target) bool { return t.Kind == u.Kind && t.Name == u.Name && t.Serial == u.Serial && slices.Equal(t.Channels, u.Channels) } @@ -90,7 +103,7 @@ type Meter struct { } // NewMeter returns a meter whose streams send rate peaks per second -// (DefaultRate if rate <= 0). +// (DefaultRate if rate <= 0), unless their Target sets a rate of its own. func NewMeter(logger *log.Logger, rate int) *Meter { if logger == nil { logger = log.New(io.Discard, "", 0) @@ -134,10 +147,13 @@ func (m *Meter) Watch(targets map[uint32]Target) { } } -// A worker measures one target. +// A worker measures one target, for all the keys watching it. Only +// Meter.Run reads and writes keys and prev. type worker struct { target Target cancel context.CancelFunc + keys []uint32 // the keys watching the target, sorted + prev []uint32 // keys as it was before the Watch call being applied } // inlineChannels is the channel count carried inline in a level message @@ -147,7 +163,6 @@ const inlineChannels = 8 // A level is a worker's latest peaks and averages; n < 0 when it has none. type level struct { w *worker - key uint32 n int peaksBuf [inlineChannels]float64 avgsBuf [inlineChannels]float64 @@ -170,9 +185,11 @@ type meterState struct { avgs []float64 } -// Run measures until ctx is done. +// Run measures until ctx is done. Keys watching equal targets share one +// stream: two streams made at once on one source can leave PipeWire running +// only the first for seconds. func (m *Meter) Run(ctx context.Context) { - workers := make(map[uint32]*worker) + var workers []*worker states := make(map[uint32]*meterState) updates := make(chan level, 64) var published time.Time @@ -190,49 +207,80 @@ func (m *Meter) Run(ctx context.Context) { } return case targets := <-m.want: - for key, w := range workers { - if t, ok := targets[key]; !ok || !t.Equal(w.target) { - m.log.Printf("pulse: %v: unwatched", w.target) - w.cancel() - delete(workers, key) - if _, ok := states[key]; ok { - delete(states, key) - dirty = true - } - } + // Give each key to the worker with an equal target, starting + // a worker if there is none. + for _, w := range workers { + w.prev, w.keys = w.keys, nil } - for key, t := range targets { - if workers[key] == nil { + for _, key := range slices.Sorted(maps.Keys(targets)) { + t := targets[key] + i := slices.IndexFunc(workers, func(w *worker) bool { return w.target.Equal(t) }) + if i < 0 { wctx, cancel := context.WithCancel(ctx) w := &worker{target: t, cancel: cancel} - workers[key] = w - m.log.Printf("pulse: %v: watched as %d", t, key) - go m.measure(wctx, w, key, updates) + go m.measure(wctx, w, updates) + i = len(workers) + workers = append(workers, w) } + workers[i].keys = append(workers[i].keys, key) } + // Drop the levels of keys that left their worker, and stop the + // workers that no key watches any more. A key whose target only + // changed its rate stays in the snapshots while its stream is + // replaced, with levels of 0 until the new stream sends some. + // Readers take a missing key to mean that the meter has no levels for + // the node. + workers = slices.DeleteFunc(workers, func(w *worker) bool { + for _, key := range w.prev { + st, ok := states[key] + if !ok || slices.Contains(w.keys, key) { + continue + } + if t, ok := targets[key]; ok && t.sameNode(w.target) { + clear(st.latest) + clear(st.avgs) + } else { + delete(states, key) + } + dirty = true + } + if len(w.keys) == 0 { + m.log.Printf("pulse: %v: unwatched", w.target) + w.cancel() + return true + } + if !slices.Equal(w.keys, w.prev) { + m.log.Printf("pulse: %v: watched as %v", w.target, w.keys) + } + return false + }) case l := <-updates: - if workers[l.key] != l.w { + if !slices.Contains(workers, l.w) { break // from a worker since cancelled } if l.n < 0 { - delete(states, l.key) + for _, key := range l.w.keys { + delete(states, key) + } } else { peaks, avg := l.slices() - st := states[l.key] - if st == nil || len(st.latest) != len(peaks) { - buf := make([]float64, 3*len(peaks)) - st = &meterState{ - latest: buf[:len(peaks)], - held: buf[len(peaks) : 2*len(peaks)], - avgs: buf[2*len(peaks):], + for _, key := range l.w.keys { + st := states[key] + if st == nil || len(st.latest) != len(peaks) { + buf := make([]float64, 3*len(peaks)) + st = &meterState{ + latest: buf[:len(peaks)], + held: buf[len(peaks) : 2*len(peaks)], + avgs: buf[2*len(peaks):], + } + states[key] = st } - states[l.key] = st - } - copy(st.latest, peaks) - for i, v := range peaks { - st.held[i] = max(st.held[i], v) + copy(st.latest, peaks) + for i, v := range peaks { + st.held[i] = max(st.held[i], v) + } + copy(st.avgs, avg) } - copy(st.avgs, avg) } dirty = true case <-flush.C: @@ -282,9 +330,9 @@ func (m *Meter) Run(ctx context.Context) { // measure runs w's streams until ctx is done, waiting longer after each // that fails before it makes another, and sends their peaks to updates. -func (m *Meter) measure(ctx context.Context, w *worker, key uint32, updates chan<- level) { +func (m *Meter) measure(ctx context.Context, w *worker, updates chan<- level) { send := func(peaks, avgs []float64) bool { - l := level{w: w, key: key, n: -1} + l := level{w: w, n: -1} if peaks != nil { l.n = len(peaks) if len(peaks) <= inlineChannels { @@ -359,10 +407,11 @@ func (m *Meter) stream(ctx context.Context, t Target, send func(peaks, avgs []fl case Stream: nodeName = fmt.Sprintf("%sstream.%d.%d", m.Prefix, t.Serial, m.seq.Add(1)) } + rate := cmp.Or(t.Rate, m.rate) nc.SetReadDeadline(time.Now().Add(createWait)) - m.log.Printf("pulse: %v: creating a record stream; the reply waits for the node to run", t) + m.log.Printf("pulse: %v: creating a record stream at %d peaks a second; the reply waits for the node to run", t, rate) asked := time.Now() - index, channels, err := c.create(t, m.rate, nodeName) + index, channels, err := c.create(t, rate, nodeName) var ne net.Error if errors.As(err, &ne) && ne.Timeout() { return false, errIdle @@ -382,8 +431,8 @@ func (m *Meter) stream(ctx context.Context, t Target, send func(peaks, avgs []fl avgs := make([]float64, channels) last := make([]float64, 0, channels) lastAvgs := make([]float64, 0, channels) - alpha := 1 - math.Exp(-1/(float64(m.rate)*averageTime.Seconds())) - timeout := max(stale, 3*m.Interval()) + alpha := 1 - math.Exp(-1/(float64(rate)*averageTime.Seconds())) + timeout := max(stale, 3*time.Second/time.Duration(rate)) var lastAt time.Time armed := false arm := func(now time.Time) { diff --git a/internal/pulse/meter_test.go b/internal/pulse/meter_test.go index 53fcadd..567d38f 100644 --- a/internal/pulse/meter_test.go +++ b/internal/pulse/meter_test.go @@ -86,6 +86,7 @@ type fakeServer struct { type fakeConn struct { c net.Conn channels int + rate uint32 // the peaks a second asked for source string // the source name asked for direct uint32 // direct_on_input closed chan struct{} @@ -135,8 +136,8 @@ func (s *fakeServer) serve(c net.Conn) { b = reply(tag) b.u32(1) case cmdCreateRecordStream: - _, ch, _ := r.sampleSpec() - fc.channels = int(ch) + _, ch, rate := r.sampleSpec() + fc.channels, fc.rate = int(ch), rate // Skip the channel map and the source index to the name. r.take(2 + int(ch)) r.u32() @@ -527,3 +528,79 @@ func TestMeterContinuousAndManyChannels(t *testing.T) { } } } + +func TestMeterShared(t *testing.T) { + s := newFakeServer(t) + m := NewMeter(nil, 0) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go m.Run(ctx) + + mic := Target{Kind: Source, Name: "mic", Channels: []string{"FL", "FR"}} + m.Watch(map[uint32]Target{290: mic, 310: mic}) + a := s.conn() + select { + case c := <-s.conns: + t.Fatalf("a second stream on %q for an equal target", c.source) + case <-time.After(200 * time.Millisecond): + } + a.peaks(t, 0.5, 0.25) + waitLevels(t, m, func(l map[uint32][]float64) bool { + return slices.Equal(l[290], []float64{0.5, 0.25}) && slices.Equal(l[310], []float64{0.5, 0.25}) + }) + + // One key going keeps the stream for the other. + m.Watch(map[uint32]Target{310: mic}) + waitLevels(t, m, func(l map[uint32][]float64) bool { _, ok := l[290]; return !ok }) + a.peaks(t, 0.75, 0.75) + waitLevels(t, m, func(l map[uint32][]float64) bool { return slices.Equal(l[310], []float64{0.75, 0.75}) }) + select { + case <-a.closed: + t.Fatal("the shared stream closed while a key still watches it") + default: + } + + // The last going closes it. + m.Watch(nil) + select { + case <-a.closed: + case <-time.After(5 * time.Second): + t.Fatal("the shared stream stays open") + } +} + +// A target that only changes its rate gets a new stream at that rate, and +// its key stays in the snapshots while the stream is replaced. +func TestMeterRateChange(t *testing.T) { + s := newFakeServer(t) + m := NewMeter(nil, 0) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go m.Run(ctx) + + mic := Target{Kind: Source, Name: "mic", Channels: []string{"FL", "FR"}} + m.Watch(map[uint32]Target{1: mic}) + a := s.conn() + if a.rate != DefaultRate { + t.Errorf("first stream asks for %d peaks a second, want %d", a.rate, DefaultRate) + } + a.peaks(t, 0.5, 0.25) + waitLevels(t, m, func(l map[uint32][]float64) bool { return slices.Equal(l[1], []float64{0.5, 0.25}) }) + + slow := mic + slow.Rate = 4 + m.Watch(map[uint32]Target{1: slow}) + b := s.conn() + if b.rate != 4 { + t.Errorf("second stream asks for %d peaks a second, want 4", b.rate) + } + select { + case <-a.closed: + case <-time.After(5 * time.Second): + t.Fatal("the stream at the old rate stays open") + } + // The key stays, at 0, until the new stream sends levels. + waitLevels(t, m, func(l map[uint32][]float64) bool { return slices.Equal(l[1], []float64{0, 0}) }) + b.peaks(t, 0.75, 0.5) + waitLevels(t, m, func(l map[uint32][]float64) bool { return slices.Equal(l[1], []float64{0.75, 0.5}) }) +} From 66858f659b84e0cbba89e18dbdd8c8dd82c8e5a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 05/10] meter only active streams, and recording streams at their source Idle streams have no levels to show, and a recording stream's own levels can't be read. --- README.md | 2 +- internal/pipmix/dump.go | 2 +- internal/pipmix/meters.go | 52 +++++++++++++++++++++++++++++++--- internal/pipmix/meters_test.go | 38 ++++++++++++++++++++++++- 4 files changed, 87 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f33c00b..6f80cc7 100644 --- a/README.md +++ b/README.md @@ -70,5 +70,5 @@ enable = true # list JACK clients ## Technical Details - **Pure Go PipeWire protocol implementation**: Speaks PipeWire's native SPA POD protocol directly over the PipeWire Unix socket to track graph state and control volumes, mutes, routes, card profiles, and default devices, reconnecting automatically if PipeWire restarts. -- **On-demand metering via `pipewire-pulse`**: Level meters connect directly to the `pipewire-pulse` native socket with peak-detect streams only for the nodes currently visible on screen. When a node scrolls out of view, meters are toggled off (`a`), or the terminal loses focus, its meter streams are closed and the render loop goes quiet so that laptops can save on battery power. +- **On-demand metering via `pipewire-pulse`**: Level meters connect directly to the `pipewire-pulse` native socket with peak-detect streams only for the nodes currently visible on screen, and only for streams that are playing or recording. When a node scrolls out of view, meters are toggled off (`a`), or the terminal loses focus, its meter streams are closed and the render loop goes quiet so that laptops can save on battery power. - **MPRIS matching over D-Bus**: Watches `org.mpris.MediaPlayer2` players on the session bus and matches them to PipeWire streams by process ID (walking ancestor PIDs so multi-process browsers match their audio streams). diff --git a/internal/pipmix/dump.go b/internal/pipmix/dump.go index 3ec13ec..48e6869 100644 --- a/internal/pipmix/dump.go +++ b/internal/pipmix/dump.go @@ -99,7 +99,7 @@ func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet fmt.Fprintln(w, "\n[pulse]") targets := make(map[uint32]pulse.Target) for i := range s.Nodes { - if t, ok := meterTarget(&s.Nodes[i]); ok { + if t, ok := meterTarget(s, &s.Nodes[i]); ok { targets[s.Nodes[i].ID] = t } } diff --git a/internal/pipmix/meters.go b/internal/pipmix/meters.go index d62791e..ecd2c16 100644 --- a/internal/pipmix/meters.go +++ b/internal/pipmix/meters.go @@ -103,14 +103,34 @@ func (m *mixer) meterTargetsItems(items []item) map[uint32]pulse.Target { if y <= off || top >= off+h { continue } - if t, ok := meterTarget(it.node); ok { + if !meterable(it.node) { + continue + } + if t, ok := meterTarget(m.snap, it.node); ok { targets[it.id] = t } } return targets } -func meterTarget(n *pw.Node) (pulse.Target, bool) { +// meterable reports whether n is worth metering now. Streams that aren't +// active have no levels to show, and their meters can hold up PipeWire +// starting other meters, so they get none. +func meterable(n *pw.Node) bool { + if n == nil { + return false + } + switch n.Class { + case pw.Playback, pw.Recording: + return n.Active + } + return true +} + +// meterTarget returns what to meter for node n of snapshot s. A recording +// stream is metered at the node it records from, as its own levels can't be +// read. +func meterTarget(s *pw.Snapshot, n *pw.Node) (pulse.Target, bool) { if n == nil || len(n.Channels) == 0 { return pulse.Target{}, false } @@ -118,6 +138,18 @@ func meterTarget(n *pw.Node) (pulse.Target, bool) { for _, c := range n.Channels { names = append(names, c.Name) } + if n.Class == pw.Recording && !n.JACK { + if len(n.From) != 1 { + return pulse.Target{}, false + } + from := snapNode(s, n.From[0]) + if from == nil || from.Class == pw.Recording { + return pulse.Target{}, false + } + t, ok := meterTarget(s, from) + t.Channels = names + return t, ok + } t := pulse.Target{Name: n.Name, Channels: names} switch { case n.JACK && n.Class == pw.Playback: @@ -288,12 +320,24 @@ func (m *mixer) meterNode(id uint32, raw []float64) *pw.Node { return nil } +// snapNode returns node id of s, or nil. JACK clients, listed twice under +// one ID, are left out. +func snapNode(s *pw.Snapshot, id uint32) *pw.Node { + for i := range s.Nodes { + if n := &s.Nodes[i]; n.ID == id && !n.JACK { + return n + } + } + return nil +} + // scale appends raw levels of n to dst on the cubic volume scale, applying -// sink volume and mute state. +// the volume and mute state of outputs and recording streams, whose levels +// are measured before them. func scale(n *pw.Node, raw, dst []float64) []float64 { for ch, l := range raw { v := math.Cbrt(l) - if n.Class == pw.Sink { + if n.Class == pw.Sink || n.Class == pw.Recording && !n.JACK { v *= n.Channels[ch].Volume } if n.Mute { diff --git a/internal/pipmix/meters_test.go b/internal/pipmix/meters_test.go index 92835f2..f48679f 100644 --- a/internal/pipmix/meters_test.go +++ b/internal/pipmix/meters_test.go @@ -16,10 +16,11 @@ func meterSnapshot() *pw.Snapshot { s := testSnapshot() for i := range 3 { s.Nodes[i].Props = map[string]string{"object.serial": strconv.Itoa(100 + i)} + s.Nodes[i].Active = true } s.Nodes = append(s.Nodes, pw.Node{ID: 40, Class: pw.Recording, Name: "rec", Title: "Recorder", Channels: stereo(1)}, - pw.Node{ID: 41, Class: pw.Playback, Name: "jack", Title: "jackd", JACK: true, Channels: []pw.Channel{{Name: "out_1", Volume: 1}, {Name: "out_2", Volume: 1}}}, + pw.Node{ID: 41, Class: pw.Playback, Name: "jack", Title: "jackd", JACK: true, Active: true, Channels: []pw.Channel{{Name: "out_1", Volume: 1}, {Name: "out_2", Volume: 1}}}, pw.Node{ID: 41, Class: pw.Recording, Name: "jack", Title: "jackd", JACK: true}, pw.Node{ID: 42, Class: pw.Source, Name: "mic", Title: "Mic", Channels: []pw.Channel{{Name: "MONO", Volume: 1}}}, ) @@ -48,6 +49,11 @@ func TestMeterTargets(t *testing.T) { if !got[11].Equal(want) { t.Errorf("target of 11 = %+v, want %+v", got[11], want) } + m.snap.Nodes[1].Active = false + if keys := targetKeys(m.meterTargets()); !slices.Equal(keys, []uint32{10, 12, 41}) { + t.Errorf("targets with 11 idle %v, want 10 12 41", keys) + } + m.snap.Nodes[1].Active = true wantJACK := pulse.Target{Kind: pulse.JACK, Serial: 41, Channels: []string{"out_1", "out_2"}} if !got[41].Equal(wantJACK) { t.Errorf("target of 41 = %+v, want %+v", got[41], wantJACK) @@ -306,3 +312,33 @@ func TestMeterWaitOnce(t *testing.T) { t.Error("focus after the new wait: got a command, want none") } } + +func TestRecordingMeterTarget(t *testing.T) { + s := &pw.Snapshot{Nodes: []pw.Node{ + {ID: 1, Class: pw.Source, Name: "mic", Channels: stereo(1)}, + {ID: 2, Class: pw.Sink, Name: "speakers", Channels: stereo(1)}, + {ID: 3, Class: pw.Recording, Name: "claude", From: []uint32{1}, Channels: []pw.Channel{{Name: "MONO", Volume: 0.5}}}, + {ID: 4, Class: pw.Recording, Name: "obs", From: []uint32{2}, Channels: stereo(1)}, + {ID: 5, Class: pw.Recording, Name: "both", From: []uint32{1, 2}, Channels: stereo(1)}, + {ID: 6, Class: pw.Recording, Name: "unlinked", Channels: stereo(1)}, + }} + for _, tc := range []struct { + id uint32 + want pulse.Target + ok bool + }{ + {3, pulse.Target{Kind: pulse.Source, Name: "mic", Channels: []string{"MONO"}}, true}, + {4, pulse.Target{Kind: pulse.Sink, Name: "speakers", Channels: []string{"FL", "FR"}}, true}, + {5, pulse.Target{}, false}, + {6, pulse.Target{}, false}, + } { + got, ok := meterTarget(s, snapNode(s, tc.id)) + if ok != tc.ok || ok && !got.Equal(tc.want) { + t.Errorf("node %d: %v, %v; want %v, %v", tc.id, got, ok, tc.want, tc.ok) + } + } + // The source's level, through the stream's volume. + if got := scale(&s.Nodes[2], []float64{1}, nil); len(got) != 1 || got[0] != 0.5 { + t.Errorf("recording at 50%% scaled to %v, want [0.5]", got) + } +} From 8ceab1f439c0a57598042013bde056d9a6be7175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 06/10] label streams with the device they play to or record from Playback streams only get a label while more than one output is in use. --- internal/pipmix/view.go | 120 +++++++++++++++++++++++++++++++++-- internal/pipmix/view_test.go | 58 +++++++++++++++++ 2 files changed, 173 insertions(+), 5 deletions(-) diff --git a/internal/pipmix/view.go b/internal/pipmix/view.go index 6bc99fe..6645141 100644 --- a/internal/pipmix/view.go +++ b/internal/pipmix/view.go @@ -3,6 +3,9 @@ package pipmix import ( "fmt" "math" + "regexp" + "slices" + "strconv" "strings" "github.com/charmbracelet/x/ansi" @@ -317,15 +320,46 @@ type tabLayout struct { items []item focus int portWidth int + outputs bool // playback streams play to more than one node + short bool // stream labels use short device names } func (m *mixer) tabLayout(t tab) tabLayout { items := m.items(t) - return tabLayout{ + l := tabLayout{ items: items, focus: m.focusIndex(t, items), portWidth: m.portWidth(items), + outputs: playbackOutputs(m.snap) > 1, } + // If one stream's label doesn't fit beside its title, all are short. + room := m.labelRoom() + for _, it := range items { + if label := m.streamLabel(it, l.outputs, false); label != "" && + ansi.StringWidth(shownTitle(it))+1+ansi.StringWidth(label) > room { + l.short = true + break + } + } + return l +} + +// shownTitle returns the title drawn on the title line of it: its group's, +// if grouped. +func shownTitle(it item) string { + if it.groupCount > 1 && it.groupTitle != "" { + return it.groupTitle + } + return it.title() +} + +// labelRoom returns the width that a stream's title and label share. +func (m *mixer) labelRoom() int { + room := max(0, m.innerWidth()-toolbarWidth) + if t := m.tagsWidth(); t > 0 { + room -= t + 1 + } + return room } func (l tabLayout) isGroupMuted(it item) bool { @@ -446,6 +480,73 @@ func (m *mixer) titleColumns(width, portW int) (title, port int) { return max(rest, 0), port } +// playbackOutputs returns how many nodes playback streams play to. +func playbackOutputs(s *pw.Snapshot) int { + var seen []uint32 + for i := range s.Nodes { + n := &s.Nodes[i] + if n.Class != pw.Playback || n.JACK { + continue + } + for _, id := range n.To { + if !slices.Contains(seen, id) { + seen = append(seen, id) + } + } + } + return len(seen) +} + +// streamLabel returns what stream it records from or, if outputs is set, +// plays to, as a label for its title line. short shortens device names. +func (m *mixer) streamLabel(it item, outputs, short bool) string { + n := it.node + if n == nil || n.JACK { + return "" + } + var ids []uint32 + var many string + switch { + case n.Class == pw.Recording: + ids, many = n.From, "sources" + case n.Class == pw.Playback && outputs: + ids, many = n.To, "outputs" + default: + return "" + } + switch len(ids) { + case 0: + return "" + case 1: + default: + return strconv.Itoa(len(ids)) + " " + many + } + other := snapNode(m.snap, ids[0]) + if other == nil { + return "" + } + name := other.Title + if short { + name = shortDeviceName(name) + } + if n.Class == pw.Recording && other.Class == pw.Sink { + return "monitor of " + name + } + return name +} + +// profileSuffix matches the profile PipeWire appends to device names, such +// as " Analog Stereo" or " Mono", before any parenthesized detail. +var profileSuffix = regexp.MustCompile(`(?:\s+(?:Analog|Digital|Pro))?\s+(?:Stereo|Mono|Surround \d+(?:\.\d+)?)(\s+\(.*\))?$`) + +// shortDeviceName returns device name without the profile PipeWire appends. +func shortDeviceName(name string) string { + if short := profileSuffix.ReplaceAllString(name, "$1"); short != "" { + return short + } + return name +} + func portText(it item) string { if it.node == nil || len(it.node.Routes) == 0 { return "" @@ -479,10 +580,7 @@ func (m *mixer) drawToolbar(p *tui.Pen, it item, focused bool, layout tabLayout) // drawTitle draws the title line of it into p, which spans the inner width. func (m *mixer) drawTitle(p *tui.Pen, it item, focused bool, layout tabLayout) { - title := it.title() - if it.groupCount > 1 && it.groupTitle != "" { - title = it.groupTitle - } + title := shownTitle(it) titleStyle := plain if focused { titleStyle = focusTitleStyle @@ -503,6 +601,18 @@ func (m *mixer) drawTitle(p *tui.Pen, it item, focused bool, layout tabLayout) { return } titleW, portW = m.titleColumns(avail, layout.portWidth) + } else if label := m.streamLabel(it, layout.outputs, layout.short); label != "" { + // Streams show what they play to or record from, at the right, up + // to the tag column of devices. + room := m.labelRoom() + lw := min(ansi.StringWidth(label), room-1-min(minTitle, room/2)) + if lw >= minPortRoom { + p.Fit(title, room-lw-1, titleStyle, plain) + p.Text(" ", plain) + p.Fit(label, lw, dimStyle, dimStyle) + p.Pad(plain) + return + } } p.Fit(title, titleW, titleStyle, plain) if portW > 0 { diff --git a/internal/pipmix/view_test.go b/internal/pipmix/view_test.go index 4b3959d..97e1bc2 100644 --- a/internal/pipmix/view_test.go +++ b/internal/pipmix/view_test.go @@ -78,3 +78,61 @@ func TestItemHeightMatchesItemLines(t *testing.T) { } } } + +func TestShortDeviceName(t *testing.T) { + for name, want := range map[string]string{ + "Arctis Nova Pro Wireless Analog Stereo": "Arctis Nova Pro Wireless", + "Arctis Nova Pro Wireless Mono": "Arctis Nova Pro Wireless", + "DUO-CAPTURE EX Analog Stereo": "DUO-CAPTURE EX", + "AD102 High Definition Audio Controller Digital Stereo (HDMI)": "AD102 High Definition Audio Controller (HDMI)", + "Built-in Audio Analog Surround 5.1": "Built-in Audio", + "Stereo": "Stereo", + "My Speakers": "My Speakers", + } { + if got := shortDeviceName(name); got != want { + t.Errorf("shortDeviceName(%q) = %q, want %q", name, got, want) + } + } +} + +func TestStreamLabels(t *testing.T) { + m := newMixer(pw.NewClient(nil), nil, nil, quitKeys(), defaultOptions()) + chrome := map[string]string{"application.process.id": "14744"} + m.snap = &pw.Snapshot{Connected: true, Nodes: []pw.Node{ + {ID: 35, Class: pw.Sink, Name: "duo", Title: "DUO-CAPTURE EX Analog Stereo", Channels: stereo(1), Default: true}, + {ID: 44, Class: pw.Source, Name: "arctis", Title: "Arctis Nova Pro Wireless Mono", Channels: stereo(1)}, + {ID: 45, Class: pw.Sink, Name: "arctis-out", Title: "Arctis Nova Pro Wireless Analog Stereo", Channels: stereo(1)}, + {ID: 98, Class: pw.Recording, Title: "Google Chrome input: RecordStream", Client: "Google Chrome input", Props: chrome, From: []uint32{44}, Channels: stereo(1)}, + {ID: 144, Class: pw.Recording, Title: "Google Chrome input: RecordStream", Client: "Google Chrome input", Props: chrome, From: []uint32{44}, Channels: stereo(1)}, + {ID: 150, Class: pw.Recording, Title: "Google Chrome input: RecordStream", Client: "Google Chrome input", Props: chrome, From: []uint32{35}, Channels: stereo(1)}, + {ID: 133, Class: pw.Playback, Title: "mpd", Channels: stereo(1), To: []uint32{35}}, + {ID: 220, Class: pw.Playback, Title: "Google Chrome: Playback", Props: chrome, To: []uint32{35}, Channels: stereo(1)}, + }} + m.setSize(100, 30) + m.setTab(tabRecording) + m.refocus() + + view := ansi.Strip(m.view()) + for _, want := range []string{"Arctis Nova Pro Wireless Mono", "monitor of DUO-CAPTURE EX Analog Stereo"} { + if !strings.Contains(view, want) { + t.Errorf("Recording tab lacks %q:\n%s", want, view) + } + } + + m.setTab(tabPlayback) + m.refocus() + if view := ansi.Strip(m.view()); strings.Contains(view, "DUO-CAPTURE") { + t.Errorf("playback streams labelled with one output in use:\n%s", view) + } + m.snap.Nodes[7].To = []uint32{45} + if view := ansi.Strip(m.view()); !strings.Contains(view, "Arctis Nova Pro Wireless Analog Stereo") || !strings.Contains(view, "DUO-CAPTURE EX Analog Stereo") { + t.Errorf("playback streams not labelled with two outputs in use:\n%s", view) + } + + m.setSize(80, 30) + m.setTab(tabRecording) + m.refocus() + if view := ansi.Strip(m.view()); !strings.Contains(view, "monitor of DUO-CAPTURE EX") || strings.Contains(view, "EX Analog") { + t.Errorf("narrow Recording tab doesn't shorten device names:\n%s", view) + } +} From 96bed7b6461f24b6dfa4f3bf0bf6ad526c18f86f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 13:54:12 +0100 Subject: [PATCH 07/10] group recording streams by application --- internal/pipmix/mixer.go | 65 ++++++++++++++++++----------------- internal/pipmix/mixer_test.go | 28 +++++++++++++++ 2 files changed, 62 insertions(+), 31 deletions(-) diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index f2c1904..35ed981 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -1,6 +1,7 @@ package pipmix import ( + "fmt" "slices" "strconv" "time" @@ -345,61 +346,63 @@ func (m *mixer) items(t tab) []item { } } all := append(items, fixed...) + if t == tabRecording { + return groupStreams(all) + } if t != tabDefault && t != tabPlayback { return all } if m.opts.dedup { all = filterDuplicates(all) } - return groupPlaybackItems(all) + return groupStreams(all) } -func playbackGroupKey(it item) string { - if it.node == nil || it.node.Class != pw.Playback || it.node.JACK { +// streamGroupKey returns a key that is equal for streams that belong in +// the same group: playback streams of one process that play to the same +// nodes, or recording streams of one process that record from the same +// nodes. It returns "" if it is not a stream or can't be grouped. +func streamGroupKey(it item) string { + n := it.node + if n == nil || n.JACK || n.Class != pw.Playback && n.Class != pw.Recording { + return "" + } + pid := n.Props["application.process.id"] + if pid == "" { return "" } - return it.node.Props["application.process.id"] + return fmt.Sprintf("%d %s %v %v", n.Class, pid, n.From, n.To) } -// groupPlaybackItems groups multiple playback streams from the same application -// so they appear together under a single application header. -func groupPlaybackItems(items []item) []item { - hasGroups := false -scan: - for i := range items { - ki := playbackGroupKey(items[i]) - if ki == "" { - continue - } - for j := i + 1; j < len(items); j++ { - if playbackGroupKey(items[j]) == ki { - hasGroups = true - break scan - } - } - } - if !hasGroups { - return items - } +// groupStreams groups multiple playback or recording streams from the same +// application so they appear together under a single application header. +func groupStreams(items []item) []item { + keys := make([]string, len(items)) counts := make(map[string]int) - for _, it := range items { - if k := playbackGroupKey(it); k != "" { + grouped := false + for i, it := range items { + if k := streamGroupKey(it); k != "" { + keys[i] = k counts[k]++ + grouped = grouped || counts[k] > 1 } } + if !grouped { + return items + } groupItems := make(map[string][]item) - for _, it := range items { - if k := playbackGroupKey(it); k != "" && counts[k] > 1 { + for i, it := range items { + if k := keys[i]; counts[k] > 1 { groupItems[k] = append(groupItems[k], it) } } var res []item placed := make(map[string]bool) - for _, it := range items { - k := playbackGroupKey(it) - if k == "" || counts[k] <= 1 { + for i, it := range items { + k := keys[i] + if counts[k] <= 1 { res = append(res, it) continue } diff --git a/internal/pipmix/mixer_test.go b/internal/pipmix/mixer_test.go index ab6c357..4ed31fd 100644 --- a/internal/pipmix/mixer_test.go +++ b/internal/pipmix/mixer_test.go @@ -761,6 +761,34 @@ func TestPlaybackGrouping(t *testing.T) { } } +func TestRecordingGrouping(t *testing.T) { + m := newMixer(pw.NewClient(nil), nil, nil, quitKeys(), defaultOptions()) + chrome := map[string]string{"application.process.id": "14744", "media.name": "RecordStream"} + m.snap = &pw.Snapshot{Connected: true, Nodes: []pw.Node{ + {ID: 98, Class: pw.Recording, Name: "Google Chrome input", Client: "Google Chrome input", Title: "Google Chrome input: RecordStream", Props: chrome, From: []uint32{44}, Channels: stereo(1)}, + {ID: 144, Class: pw.Recording, Name: "Google Chrome input", Client: "Google Chrome input", Title: "Google Chrome input: RecordStream", Props: chrome, From: []uint32{44}, Channels: stereo(1)}, + {ID: 150, Class: pw.Recording, Name: "Google Chrome input", Client: "Google Chrome input", Title: "Google Chrome input: RecordStream", Props: chrome, From: []uint32{35}, Channels: stereo(1)}, + {ID: 220, Class: pw.Playback, Name: "Google Chrome", Client: "Google Chrome", Title: "Google Chrome: Playback", Props: map[string]string{"application.process.id": "14744"}, Channels: stereo(1)}, + }} + m.setSize(80, 20) + m.refocus() + for _, tab := range []tab{tabRecording} { + var recs []item + for _, it := range m.items(tab) { + switch { + case it.id == 98 || it.id == 144: + recs = append(recs, it) + case it.groupKey != "": + t.Errorf("tab %d: %d grouped with %q", tab, it.id, it.groupKey) + } + } + if len(recs) != 2 || recs[0].groupKey == "" || recs[0].groupKey != recs[1].groupKey || + !recs[0].groupLeader || recs[1].groupLeader || recs[0].groupTitle != "Google Chrome input" { + t.Errorf("tab %d: streams recording from one source not grouped: %+v", tab, recs) + } + } +} + func TestToggleSolo(t *testing.T) { m := testMixer() findNode := func(id uint32) *pw.Node { From 32427e89eceefaa05ce4f8771f5018731e17fc2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 14:02:13 +0100 Subject: [PATCH 08/10] show recording streams and other devices on the Default tab -default.recording, -default.outputs and -default.inputs choose which ones are listed: none, those in use, or all. By default only recording streams are added, while they record. --- README.md | 7 +- internal/pipmix/activity.go | 138 +++++++++++++++++++++++++++++ internal/pipmix/activity_test.go | 146 +++++++++++++++++++++++++++++++ internal/pipmix/config_test.go | 8 ++ internal/pipmix/dump.go | 5 +- internal/pipmix/keys.go | 9 +- internal/pipmix/loop.go | 15 ++++ internal/pipmix/mixer.go | 48 ++++++++-- internal/pipmix/mixer_test.go | 10 ++- internal/pipmix/options.go | 20 +++++ internal/pipmix/options_test.go | 5 +- internal/pipmix/view_test.go | 4 +- 12 files changed, 400 insertions(+), 15 deletions(-) create mode 100644 internal/pipmix/activity.go create mode 100644 internal/pipmix/activity_test.go diff --git a/README.md b/README.md index 6f80cc7..faa2230 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Press  ?  inside  pipmix  for context-sensitive key and mouse help. ## Features -- **Default overview tab**: Keeps your default output device and active playback streams together in one view, alongside dedicated tabs for Playback, Recording, Output Devices, Input Devices, and Cards (`1`–`6` or `Tab`). +- **Default overview tab**: Keeps your default output device and active playback streams together in one view, alongside dedicated tabs for Playback, Recording, Output Devices, Input Devices, and Cards (`1`–`6` or `Tab`). Which streams and devices it shows is configurable. - **Live level meters**: Smooth per-channel average and peak-hold meters directly inside the volume faders, automatically paused when the terminal loses focus. - **MPRIS media integration**: Displays currently playing track titles on playback streams, with controls to play/pause (`p`) or solo a stream (`s`). - **Full keyboard and mouse control**: Emacs and Vim-style keyboard navigation, per-channel volume unlocking (`Space`), port and card profile menus (`p`/`P`), default device switching (`D`), and click-and-drag faders. @@ -65,6 +65,11 @@ enable = true # disable to allow normal terminal text selection [jack] enable = true # list JACK clients + +[default] +recording = "active" # recording streams on the Default tab: off, active (while recording, and 5s after), or all; JACK clients only show on the Recording tab +outputs = "default" # output devices: default, active (others too while in use, and 5s after), or all +inputs = "off" # input devices: off, active (those in use, and 5s after), or all ``` ## Technical Details diff --git a/internal/pipmix/activity.go b/internal/pipmix/activity.go new file mode 100644 index 0000000..0d3cabb --- /dev/null +++ b/internal/pipmix/activity.go @@ -0,0 +1,138 @@ +package pipmix + +import ( + "maps" + "time" + + "github.com/some-programs/pipmix/internal/pw" +) + +// activeLinger is how long a stream or device stays on the Default tab +// after it stops being active, when it is only shown because it was active. +const activeLinger = 5 * time.Second + +// A nodeState is the per-node data that activity keeps for one node of the +// latest PipeWire snapshot. trackNodes rebuilds it on every new snapshot and +// copies the timestamps over from the node's previous state. +type nodeState struct { + active bool // the node is active + idleAt time.Time // when the node went from active to not active; zero if that was never seen +} + +// activity holds the state used to decide which nodes the Default tab +// shows: which nodes are active, and since when they are not. +type activity struct { + snap *pw.Snapshot // the PipeWire snapshot that nodes was built from + nodes map[uint32]nodeState // state of each listable node in snap, by node ID + + shown map[uint32]bool // nodes to show because they are active or stopped less than activeLinger ago + wakeAt time.Time // the next time updateShown must run because a delay runs out; zero if none +} + +// listable reports whether the Default tab can list n. It can't list the +// recording side of a JACK client. A JACK client with both inputs and outputs +// appears in the snapshot twice with the same ID, once as playback and once +// as recording, and rows, focus and activity are all keyed by ID. Only the +// Recording tab lists the recording side. +func listable(n *pw.Node) bool { return !(n.JACK && n.Class == pw.Recording) } + +// trackNodes rebuilds m.act.nodes from the current PipeWire snapshot. It +// does nothing if the snapshot is the one it last saw. updateShown calls it. +func (m *mixer) trackNodes(now time.Time) { + a := &m.act + if a.snap == m.snap { + return + } + a.snap = m.snap + nodes := make(map[uint32]nodeState) + for i := range m.snap.Nodes { + n := &m.snap.Nodes[i] + if !listable(n) { + continue + } + prev := a.nodes[n.ID] + st := nodeState{ + active: n.Active, + } + switch { + case st.active: + case prev.active: + st.idleAt = now + default: + st.idleAt = prev.idleAt + } + nodes[n.ID] = st + } + a.nodes = nodes +} + +// defaultShow returns the -default.recording, -default.outputs or +// -default.inputs setting that applies to n, or showAll for nodes that the +// Default tab always lists. +func (m *mixer) defaultShow(n *pw.Node) showWhen { + switch { + case n.Class == pw.Recording: + return m.opts.recording + case n.Class == pw.Sink && !n.Default: + return m.opts.outputs + case n.Class == pw.Source: + return m.opts.inputs + } + return showAll +} + +// updateShown takes in the current PipeWire snapshot if it is new, then +// recomputes m.act.shown for the time now, and reports whether it changed. +// It sets m.act.wakeAt to the earliest time at which the result can change +// without a new snapshot. +func (m *mixer) updateShown(now time.Time) (changed bool) { + m.trackNodes(now) + a := &m.act + var next time.Time + // until reports whether t is after now. If it is, t becomes the wake + // time unless an earlier one is already set. + until := func(t time.Time) bool { + if !now.Before(t) { + return false + } + if next.IsZero() || t.Before(next) { + next = t + } + return true + } + // active reports whether the node is active or stopped being active less + // than d ago. + active := func(st nodeState, d time.Duration) bool { + return st.active || !st.idleAt.IsZero() && until(st.idleAt.Add(d)) + } + + var shown map[uint32]bool + for i := range m.snap.Nodes { + n := &m.snap.Nodes[i] + if !listable(n) { + continue + } + st := a.nodes[n.ID] + if m.defaultShow(n) == showActive && active(st, activeLinger) { + if shown == nil { + shown = make(map[uint32]bool) + } + shown[n.ID] = true + } + } + a.wakeAt = next + changed = !maps.Equal(shown, a.shown) + a.shown = shown + return changed +} + +// refreshShown calls updateShown. If the set of visible nodes changed, it +// asks for a redraw and updates focus, scrolling and the metered nodes. +func (m *mixer) refreshShown(now time.Time) { + if !m.updateShown(now) { + return + } + m.redraw = true + m.refocus() + m.watchMeters() +} diff --git a/internal/pipmix/activity_test.go b/internal/pipmix/activity_test.go new file mode 100644 index 0000000..33db0f2 --- /dev/null +++ b/internal/pipmix/activity_test.go @@ -0,0 +1,146 @@ +package pipmix + +import ( + "slices" + "testing" + "time" + + "github.com/some-programs/pipmix/internal/pulse" + "github.com/some-programs/pipmix/internal/pw" +) + +// activityMixer returns a mixer on the Default tab with a default output, +// a default input, a FluidSynth stream, and a recording stream. +func activityMixer(opts options) *mixer { + m := newMixer(pw.NewClient(nil), nil, pulse.NewMeter(nil, 40), quitKeys(), opts) + m.snap = &pw.Snapshot{Connected: true, Nodes: []pw.Node{ + {ID: 10, Class: pw.Playback, Name: "FluidSynth", Props: map[string]string{"node.name": "FluidSynth", "object.serial": "100"}, Channels: stereo(1), State: pw.StateRunning, Active: true}, + {ID: 11, Class: pw.Playback, Name: "firefox", Props: map[string]string{"node.name": "firefox", "object.serial": "101"}, Channels: stereo(1)}, + {ID: 12, Class: pw.Playback, Name: "jack", JACK: true, Channels: stereo(1)}, + {ID: 20, Class: pw.Sink, Name: "sink", Props: map[string]string{"node.name": "sink"}, Channels: stereo(1), Default: true}, + {ID: 21, Class: pw.Source, Name: "mic", Props: map[string]string{"node.name": "mic"}, Channels: stereo(1), Default: true}, + {ID: 22, Class: pw.Source, Name: "other-mic", Channels: stereo(1)}, + {ID: 23, Class: pw.Sink, Name: "hdmi", Channels: stereo(1)}, + {ID: 30, Class: pw.Recording, Name: "obs", Props: map[string]string{"node.name": "obs"}, Channels: stereo(1)}, + {ID: 31, Class: pw.Recording, Name: "jack", JACK: true, Channels: stereo(1)}, + }} + m.setSize(80, 40) + m.refocus() + return &m +} + +// setNode applies f to node id in a new snapshot, as PipeWire would, and +// updates m at now. +func setNode(m *mixer, id uint32, f func(n *pw.Node), now time.Time) { + snap := *m.snap + snap.Nodes = slices.Clone(snap.Nodes) + for i := range snap.Nodes { + if snap.Nodes[i].ID == id { + f(&snap.Nodes[i]) + } + } + m.snap = &snap + m.refreshShown(now) +} + +// setState sets node id's state, as setNode does. +func setState(m *mixer, id uint32, s pw.State, now time.Time) { + setNode(m, id, func(n *pw.Node) { + n.State = s + n.Active = s == pw.StateRunning + }, now) +} + +// wantShown fails the test with the formatted message if the Default tab +// doesn't list node id. +func wantShown(t *testing.T, m *mixer, id uint32, format string, args ...any) { + t.Helper() + if got := defaultIDs(m); !slices.Contains(got, id) { + t.Errorf(format+": rows %v", append(args, got)...) + } +} + +// wantHidden fails the test with the formatted message if the Default tab +// lists node id. +func wantHidden(t *testing.T, m *mixer, id uint32, format string, args ...any) { + t.Helper() + if got := defaultIDs(m); slices.Contains(got, id) { + t.Errorf(format+": rows %v", append(args, got)...) + } +} + +func defaultIDs(m *mixer) []uint32 { + var ids []uint32 + for _, it := range m.items(tabDefault) { + ids = append(ids, it.id) + } + return ids +} + +func TestRecordingRows(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions()) + m.refreshShown(now) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12}; !slices.Equal(got, want) { + t.Fatalf("nothing recording: %v, want %v", got, want) + } + + setState(m, 30, pw.StateRunning, now) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 30}; !slices.Equal(got, want) { + t.Fatalf("recording: %v, want %v (recording last)", got, want) + } + if !m.redraw { + t.Error("recording row appeared without redraw") + } + + setState(m, 30, pw.StateIdle, now.Add(time.Second)) + wantShown(t, m, 30, "recording gone right after it stopped") + if want := now.Add(time.Second + activeLinger); !m.act.wakeAt.Equal(want) { + t.Errorf("wake at %v, want %v", m.act.wakeAt, want) + } + m.refreshShown(now.Add(time.Second + activeLinger)) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12}; !slices.Equal(got, want) { + t.Fatalf("after the linger: %v, want %v", got, want) + } + if !m.act.wakeAt.IsZero() { + t.Errorf("wake at %v with nothing to wait for", m.act.wakeAt) + } + + o := defaultOptions() + o.recording = showAll + m = activityMixer(o) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 30}; !slices.Equal(got, want) { + t.Errorf("-default.recording=all: %v, want %v", got, want) + } + o.recording = showNone + m = activityMixer(o) + setState(m, 30, pw.StateRunning, now) + wantHidden(t, m, 30, "-default.recording=off shows a recording") +} + +func TestDeviceRows(t *testing.T) { + now := time.Now() + o := defaultOptions() + o.outputs, o.inputs = showActive, showActive + m := activityMixer(o) + m.refreshShown(now) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12}; !slices.Equal(got, want) { + t.Fatalf("nothing in use: %v, want %v", got, want) + } + setState(m, 23, pw.StateRunning, now) + setState(m, 22, pw.StateRunning, now) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 23, 22}; !slices.Equal(got, want) { + t.Fatalf("hdmi and other mic in use: %v, want %v (outputs, then inputs, at the bottom)", got, want) + } + setState(m, 30, pw.StateRunning, now) + setState(m, 21, pw.StateRunning, now) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 23, 21, 22, 30}; !slices.Equal(got, want) { + t.Fatalf("recording from the default input too: %v, want %v (default input first)", got, want) + } + + o.outputs, o.inputs = showAll, showAll + m = activityMixer(o) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 23, 21, 22}; !slices.Equal(got, want) { + t.Errorf("all devices: %v, want %v", got, want) + } +} diff --git a/internal/pipmix/config_test.go b/internal/pipmix/config_test.go index 645ecc0..64f6b94 100644 --- a/internal/pipmix/config_test.go +++ b/internal/pipmix/config_test.go @@ -64,6 +64,11 @@ enable = false [jack] enable = false +[default] +recording = "off" +outputs = "all" +inputs = "active" + [debug] log = true log-file = "/tmp/pipmix-test.log" @@ -86,6 +91,9 @@ dump = true fineStep: 0.005, limit: 1.2, tab: tabOutputs, + recording: showNone, + outputs: showAll, + inputs: showActive, } if o != want { t.Errorf("options:\ngot %+v\nwant %+v", o, want) diff --git a/internal/pipmix/dump.go b/internal/pipmix/dump.go index 48e6869..341a99e 100644 --- a/internal/pipmix/dump.go +++ b/internal/pipmix/dump.go @@ -126,7 +126,10 @@ func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet func dumpNodes(w io.Writer, s *pw.Snapshot, shown map[uint32]bool, opts options) { classes := []string{"playback", "recording", "sink", "source"} for _, n := range s.Nodes { - fmt.Fprintf(w, "node %d %s %q (%s)", n.ID, classes[n.Class], n.Title, n.Name) + fmt.Fprintf(w, "node %d %s %q (%s) %s", n.ID, classes[n.Class], n.Title, n.Name, n.State) + if n.Active { + fmt.Fprint(w, " active") + } if n.Default { fmt.Fprint(w, " default") } diff --git a/internal/pipmix/keys.go b/internal/pipmix/keys.go index ac980e6..ce79a32 100644 --- a/internal/pipmix/keys.go +++ b/internal/pipmix/keys.go @@ -37,9 +37,12 @@ func deviceKeys() section { }} } -func defaultOutputKeys() section { - return section{"Default output", []binding{ +// defaultTabDeviceKeys are deviceKeys for the Default tab, where p also +// plays or pauses a stream. +func defaultTabDeviceKeys() section { + return section{"Devices", []binding{ {[]string{"p"}, "Choose the port", "click the port", (*mixer).portOrPlayPause}, + {[]string{"D"}, "Make it the default", "", (*mixer).setDefault}, }} } @@ -137,7 +140,7 @@ func (m *mixer) tabSections() []section { var own []section switch m.tab { case tabDefault: - own = []section{volumeKeys(m.opts), defaultOutputKeys(), playbackKeys()} + own = []section{volumeKeys(m.opts), defaultTabDeviceKeys(), playbackKeys()} case tabPlayback: own = []section{volumeKeys(m.opts), playbackKeys()} case tabOutputs, tabInputs: diff --git a/internal/pipmix/loop.go b/internal/pipmix/loop.go index ab32aea..3485a97 100644 --- a/internal/pipmix/loop.go +++ b/internal/pipmix/loop.go @@ -71,6 +71,7 @@ func run(ctx context.Context, m *mixer) error { frame = time.Second / time.Duration(m.opts.fps) ticker = time.NewTicker(frame) timer = time.NewTimer(frame) + wake = time.NewTimer(time.Hour) tickC <-chan time.Time // the ticker's channel while the meters move frameC <-chan time.Time // the timer's channel while a frame waits sized bool // the size of the terminal is known @@ -80,6 +81,7 @@ func run(ctx context.Context, m *mixer) error { ) ticker.Stop() timer.Stop() + wake.Stop() for { select { case <-done: @@ -119,6 +121,19 @@ func run(ctx context.Context, m *mixer) error { case <-frameC: frameC = nil m.flushDrag(false) + case <-wake.C: + m.refreshShown(time.Now()) + } + + if m.redraw { + m.redraw = false + full = true + } + // Set the wake timer to the time updateShown last asked for. + if m.act.wakeAt.IsZero() { + wake.Stop() + } else { + wake.Reset(time.Until(m.act.wakeAt)) } if m.ticking != (tickC != nil) { diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index 35ed981..b653104 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -28,7 +28,7 @@ const ( var tabNames = [tabCount]string{"Default", "Playback", "Recording", "Output Devices", "Input Devices", "Cards"} -var tabClasses = [tabCards][]pw.Class{{pw.Sink, pw.Playback}, {pw.Playback}, {pw.Recording}, {pw.Sink}, {pw.Source}} +var tabClasses = [tabCards][]pw.Class{{pw.Sink, pw.Playback, pw.Recording, pw.Source}, {pw.Playback}, {pw.Recording}, {pw.Sink}, {pw.Source}} type item struct { id uint32 @@ -133,6 +133,8 @@ type mixer struct { meterMode meterMode quitKeys section opts options + act activity + redraw bool // the screen needs drawing for a change made outside update tab tab focus [tabCount]focus @@ -280,6 +282,7 @@ func (m *mixer) update(msg message) command { case snapshotMsg: m.snap = m.client.Snapshot() m.findMedia() + m.updateShown(time.Now()) items := m.refocus() m.watchMetersItems(items) return m.waitSnapshot() @@ -316,9 +319,10 @@ func (m *mixer) update(msg message) command { } // items returns the items for tab t, with the default device first and JACK -// clients last. +// clients last. The Default tab lists other output devices below those, +// then input devices, then recording streams. func (m *mixer) items(t tab) []item { - var items, fixed []item + var items, fixed, outputs, inputs, recording []item if t == tabCards { for i := range m.snap.Cards { c := &m.snap.Cards[i] @@ -328,7 +332,7 @@ func (m *mixer) items(t tab) []item { } for i := range m.snap.Nodes { n := &m.snap.Nodes[i] - if !slices.Contains(tabClasses[t], n.Class) || t == tabDefault && n.Class == pw.Sink && !n.Default || n.JACK && !m.opts.jack { + if !m.listed(t, n) { continue } var player *mpris.Player @@ -337,6 +341,16 @@ func (m *mixer) items(t tab) []item { } it := item{id: n.ID, node: n, media: m.mediaTitles[n.ID], player: player} switch { + case t == tabDefault && n.Class == pw.Sink && !n.Default: + outputs = append(outputs, it) + case t == tabDefault && n.Class == pw.Source: + if n.Default { + inputs = slices.Insert(inputs, 0, it) + } else { + inputs = append(inputs, it) + } + case t == tabDefault && n.Class == pw.Recording: + recording = append(recording, it) case n.JACK: fixed = append(fixed, it) case n.Default: @@ -355,7 +369,31 @@ func (m *mixer) items(t tab) []item { if m.opts.dedup { all = filterDuplicates(all) } - return groupStreams(all) + all = groupStreams(all) + if t != tabDefault { + return all + } + return slices.Concat(all, outputs, inputs, groupStreams(recording)) +} + +// listed reports whether tab t lists node n. +func (m *mixer) listed(t tab, n *pw.Node) bool { + if !slices.Contains(tabClasses[t], n.Class) || n.JACK && !m.opts.jack { + return false + } + if t != tabDefault { + return true + } + if !listable(n) { + return false + } + switch m.defaultShow(n) { + case showAll: + return true + case showActive: + return m.act.shown[n.ID] + } + return false } // streamGroupKey returns a key that is equal for streams that belong in diff --git a/internal/pipmix/mixer_test.go b/internal/pipmix/mixer_test.go index 4ed31fd..9089122 100644 --- a/internal/pipmix/mixer_test.go +++ b/internal/pipmix/mixer_test.go @@ -256,6 +256,10 @@ func TestHelp(t *testing.T) { t.Errorf("help on Output Devices lacks %q:\n%s", want, view) } } + m.handleKey("1") + if view := ansi.Strip(m.view()); !strings.Contains(view, "Make it the default") { + t.Errorf("help on Default lacks D:\n%s", view) + } m.handleKey("6") // the help follows the tab if view := ansi.Strip(m.view()); !strings.Contains(view, "Choose the profile") || strings.Contains(view, "Louder") { t.Errorf("help on Cards:\n%s", view) @@ -762,7 +766,9 @@ func TestPlaybackGrouping(t *testing.T) { } func TestRecordingGrouping(t *testing.T) { - m := newMixer(pw.NewClient(nil), nil, nil, quitKeys(), defaultOptions()) + o := defaultOptions() + o.recording = showAll + m := newMixer(pw.NewClient(nil), nil, nil, quitKeys(), o) chrome := map[string]string{"application.process.id": "14744", "media.name": "RecordStream"} m.snap = &pw.Snapshot{Connected: true, Nodes: []pw.Node{ {ID: 98, Class: pw.Recording, Name: "Google Chrome input", Client: "Google Chrome input", Title: "Google Chrome input: RecordStream", Props: chrome, From: []uint32{44}, Channels: stereo(1)}, @@ -772,7 +778,7 @@ func TestRecordingGrouping(t *testing.T) { }} m.setSize(80, 20) m.refocus() - for _, tab := range []tab{tabRecording} { + for _, tab := range []tab{tabRecording, tabDefault} { var recs []item for _, it := range m.items(tab) { switch { diff --git a/internal/pipmix/options.go b/internal/pipmix/options.go index 0bd1870..b465dc8 100644 --- a/internal/pipmix/options.go +++ b/internal/pipmix/options.go @@ -27,6 +27,8 @@ type options struct { tab tab mouse bool jack bool + recording showWhen + outputs, inputs showWhen } func defaultOptions() options { @@ -43,9 +45,24 @@ func defaultOptions() options { limit: 1.5, mouse: true, jack: true, + recording: showActive, } } +// A showWhen says which nodes of a kind the Default tab shows. +type showWhen int + +const ( + showNone showWhen = iota // none, or only the default output + showActive // those active, and for a while after + showAll // all +) + +var ( + showFlags = []string{"off", "active", "all"} + outputFlags = []string{"default", "active", "all"} +) + type meterWhen int const ( @@ -97,6 +114,9 @@ func addFlags(fs *flag.FlagSet) *flagValues { fs.Var(tabFlag{&v.tab}, "ui.tab", "`tab` to start on: "+strings.Join(tabFlags[:], ", ")+", or 1 to 6") fs.BoolVar(&v.mouseEnable, "mouse.enable", v.mouseEnable, "use the mouse; disable to let terminal selection work") fs.BoolVar(&v.jackEnable, "jack.enable", v.jackEnable, "list JACK clients") + fs.Var(&choice[showWhen]{&v.recording, showFlags}, "default.recording", "recording streams the Default tab shows, at the bottom: off, active (while recording, and a few seconds after), or all; JACK clients only show on the Recording tab") + fs.Var(&choice[showWhen]{&v.outputs, outputFlags}, "default.outputs", "output devices the Default tab shows: default, active (also others while in use, and a few seconds after), or all") + fs.Var(&choice[showWhen]{&v.inputs, showFlags}, "default.inputs", "input devices the Default tab shows, above recording streams: off, active (those in use, and a few seconds after), or all") return v } diff --git a/internal/pipmix/options_test.go b/internal/pipmix/options_test.go index bc4e4dd..f675663 100644 --- a/internal/pipmix/options_test.go +++ b/internal/pipmix/options_test.go @@ -30,10 +30,11 @@ func TestFlags(t *testing.T) { } o, err = parseOptions("-meter.always", "-meter.rate", "20", "-meter.mode", "peak", "-meter.look", "dot", "-meter.speed", "slowest", "-meter.peak-hold", "0", "-ui.fps", "30", "-mpris.enable=false", "-dedup.enable=false", "-volume.step", "2.5", "-volume.fine-step", "0.5", - "-volume.max", "100", "-ui.tab", "outputs", "-mouse.enable=false", "-jack.enable=false") + "-volume.max", "100", "-ui.tab", "outputs", "-mouse.enable=false", "-jack.enable=false", + "-default.recording", "all", "-default.outputs", "active", "-default.inputs", "all") want := options{ meters: metersAlways, meterRate: 20, meterMode: modePeak, meterLook: meterDot, smoothing: 4, fps: 30, - step: 0.025, fineStep: 0.005, limit: 1, tab: tabOutputs, + step: 0.025, fineStep: 0.005, limit: 1, tab: tabOutputs, recording: showAll, outputs: showActive, inputs: showAll, } if err != nil || o != want { t.Errorf("all flags: %+v, %v; want %+v", o, err, want) diff --git a/internal/pipmix/view_test.go b/internal/pipmix/view_test.go index 97e1bc2..d24e4c5 100644 --- a/internal/pipmix/view_test.go +++ b/internal/pipmix/view_test.go @@ -96,7 +96,9 @@ func TestShortDeviceName(t *testing.T) { } func TestStreamLabels(t *testing.T) { - m := newMixer(pw.NewClient(nil), nil, nil, quitKeys(), defaultOptions()) + o := defaultOptions() + o.recording = showAll + m := newMixer(pw.NewClient(nil), nil, nil, quitKeys(), o) chrome := map[string]string{"application.process.id": "14744"} m.snap = &pw.Snapshot{Connected: true, Nodes: []pw.Node{ {ID: 35, Class: pw.Sink, Name: "duo", Title: "DUO-CAPTURE EX Analog Stereo", Channels: stereo(1), Default: true}, From 13dc9cbbb6c5ee04e3e75a4fc779cf0d0af80523 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 14:02:13 +0100 Subject: [PATCH 09/10] add hide rules for the Default tab [[default.hide]] tables in the config file hide the nodes they match: always, while idle, or while muted. --- README.md | 31 +++++ internal/pipmix/activity.go | 67 ++++++++-- internal/pipmix/activity_test.go | 96 +++++++++++++- internal/pipmix/config.go | 7 ++ internal/pipmix/config_test.go | 4 + internal/pipmix/dump.go | 24 +++- internal/pipmix/dump_test.go | 2 +- internal/pipmix/hide.go | 209 +++++++++++++++++++++++++++++++ internal/pipmix/hide_test.go | 98 +++++++++++++++ internal/pipmix/mixer.go | 26 ++-- internal/pipmix/mixer_test.go | 8 ++ internal/pipmix/pipmix.go | 7 +- 12 files changed, 553 insertions(+), 26 deletions(-) create mode 100644 internal/pipmix/hide.go create mode 100644 internal/pipmix/hide_test.go diff --git a/README.md b/README.md index faa2230..c4c15d2 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,37 @@ outputs = "default" # output devices: default, active (others too while in use inputs = "off" # input devices: off, active (those in use, and 5s after), or all ``` +### Hide rules + +`[[default.hide]]` rules hide nodes from the Default tab; the other tabs still list everything. They can only be set in the config file. A node is hidden while any rule matching it says so, even when focused. + +```toml +# Hide Firefox's streams while they don't run. +[[default.hide]] +match = { binary = "firefox" } +when = "idle" + +# Hide playback streams as soon as they are muted. +[[default.hide]] +match = { type = "playback" } +when = "muted" +after = "0s" +``` + +- `match` selects nodes; every key given must match. `pipmix -debug.dump` lists the properties of each node, and the rules each node matches. + - `type`: `playback`, `recording`, `output`, or `input`. + - `name`: a regular expression on `node.name`. + - `description`: a regular expression on `node.description`. + - `app`: a regular expression on `application.name`, or on the process name of a stream from PipeWire's ALSA plugin. + - `binary`: a regular expression on `application.process.binary`. + + Regular expressions are unanchored: `firefox` matches anywhere in the value, `^firefox$` only the whole value. +- `when` says when matching nodes hide: + - `always` (the default): always. + - `idle`: while nothing plays or records through the node. + - `muted`: while the node is muted. A volume of 0% doesn't count. +- `after` is how long `idle` or `muted` must last before the node hides; it is 10s unless set. A node shows again as soon as the condition ends, and nodes start out hidden if the condition already holds. + ## Technical Details - **Pure Go PipeWire protocol implementation**: Speaks PipeWire's native SPA POD protocol directly over the PipeWire Unix socket to track graph state and control volumes, mutes, routes, card profiles, and default devices, reconnecting automatically if PipeWire restarts. diff --git a/internal/pipmix/activity.go b/internal/pipmix/activity.go index 0d3cabb..2114f4c 100644 --- a/internal/pipmix/activity.go +++ b/internal/pipmix/activity.go @@ -15,17 +15,22 @@ const activeLinger = 5 * time.Second // latest PipeWire snapshot. trackNodes rebuilds it on every new snapshot and // copies the timestamps over from the node's previous state. type nodeState struct { - active bool // the node is active - idleAt time.Time // when the node went from active to not active; zero if that was never seen + known bool // the node's volume and mute have been reported + active bool // the node is active + idleAt time.Time // when the node went from active to not active; zero if that was never seen + muted bool // the node is muted + mutedAt time.Time // when the node went from unmuted to muted; zero if that was never seen + rules []int // indexes in mixer.hide of the hide rules that match the node } // activity holds the state used to decide which nodes the Default tab -// shows: which nodes are active, and since when they are not. +// shows: which nodes are active or muted, and since when. type activity struct { snap *pw.Snapshot // the PipeWire snapshot that nodes was built from nodes map[uint32]nodeState // state of each listable node in snap, by node ID shown map[uint32]bool // nodes to show because they are active or stopped less than activeLinger ago + hidden map[uint32]bool // nodes that a hide rule currently hides wakeAt time.Time // the next time updateShown must run because a delay runs out; zero if none } @@ -52,7 +57,9 @@ func (m *mixer) trackNodes(now time.Time) { } prev := a.nodes[n.ID] st := nodeState{ + known: len(n.Channels) > 0, active: n.Active, + muted: n.Mute && !n.JACK, } switch { case st.active: @@ -61,6 +68,25 @@ func (m *mixer) trackNodes(now time.Time) { default: st.idleAt = prev.idleAt } + // PipeWire reports a new node as unmuted until it has sent the node's + // volume and mute. So mutedAt is only set if the node was unmuted in + // a snapshot where its mute was already known. A node that is muted + // when its mute first becomes known gets no mutedAt, and a muted rule + // hides it without waiting. + switch { + case !st.muted: + case prev.known && !prev.muted: + st.mutedAt = now + default: + st.mutedAt = prev.mutedAt + } + for ri := range m.hide { + r := &m.hide[ri] + if !r.Match.matches(n) { + continue + } + st.rules = append(st.rules, ri) + } nodes[n.ID] = st } a.nodes = nodes @@ -82,9 +108,9 @@ func (m *mixer) defaultShow(n *pw.Node) showWhen { } // updateShown takes in the current PipeWire snapshot if it is new, then -// recomputes m.act.shown for the time now, and reports whether it changed. -// It sets m.act.wakeAt to the earliest time at which the result can change -// without a new snapshot. +// recomputes m.act.shown and m.act.hidden for the time now, and reports +// whether either changed. It sets m.act.wakeAt to the earliest +// time at which the result can change without a new snapshot. func (m *mixer) updateShown(now time.Time) (changed bool) { m.trackNodes(now) a := &m.act @@ -106,7 +132,7 @@ func (m *mixer) updateShown(now time.Time) (changed bool) { return st.active || !st.idleAt.IsZero() && until(st.idleAt.Add(d)) } - var shown map[uint32]bool + var shown, hidden map[uint32]bool for i := range m.snap.Nodes { n := &m.snap.Nodes[i] if !listable(n) { @@ -119,10 +145,33 @@ func (m *mixer) updateShown(now time.Time) (changed bool) { } shown[n.ID] = true } + hide := false + for _, ri := range st.rules { + r := &m.hide[ri] + switch r.When { + case hideAlways: + hide = true + case hideIdle: + hide = !active(st, r.after) + case hideMuted: + // With a zero mutedAt the delay has always run out, so the + // node hides at once. + hide = st.muted && !until(st.mutedAt.Add(r.after)) + } + if hide { + break + } + } + if hide { + if hidden == nil { + hidden = make(map[uint32]bool) + } + hidden[n.ID] = true + } } a.wakeAt = next - changed = !maps.Equal(shown, a.shown) - a.shown = shown + changed = !maps.Equal(shown, a.shown) || !maps.Equal(hidden, a.hidden) + a.shown, a.hidden = shown, hidden return changed } diff --git a/internal/pipmix/activity_test.go b/internal/pipmix/activity_test.go index 33db0f2..63034e3 100644 --- a/internal/pipmix/activity_test.go +++ b/internal/pipmix/activity_test.go @@ -1,6 +1,7 @@ package pipmix import ( + "regexp" "slices" "testing" "time" @@ -11,8 +12,14 @@ import ( // activityMixer returns a mixer on the Default tab with a default output, // a default input, a FluidSynth stream, and a recording stream. -func activityMixer(opts options) *mixer { +func activityMixer(opts options, hide ...hideRule) *mixer { m := newMixer(pw.NewClient(nil), nil, pulse.NewMeter(nil, 40), quitKeys(), opts) + for i := range hide { + if err := hide[i].check(); err != nil { + panic(err) + } + } + m.hide = hide m.snap = &pw.Snapshot{Connected: true, Nodes: []pw.Node{ {ID: 10, Class: pw.Playback, Name: "FluidSynth", Props: map[string]string{"node.name": "FluidSynth", "object.serial": "100"}, Channels: stereo(1), State: pw.StateRunning, Active: true}, {ID: 11, Class: pw.Playback, Name: "firefox", Props: map[string]string{"node.name": "firefox", "object.serial": "101"}, Channels: stereo(1)}, @@ -118,6 +125,55 @@ func TestRecordingRows(t *testing.T) { wantHidden(t, m, 30, "-default.recording=off shows a recording") } +func rule(match nodeMatch, when hideWhen, after time.Duration) hideRule { + d := tomlDuration(after) + r := hideRule{Match: match, When: when} + if when != hideAlways { + r.After = &d + } + return r +} + +func nameIs(s string) nodeMatch { return nodeMatch{Name: regexp.MustCompile("^" + s + "$")} } + +func TestHideAlwaysAndIdle(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), + rule(nameIs("sink"), hideAlways, 0), + rule(nameIs("firefox"), hideIdle, 10*time.Second)) + m.refreshShown(now) + if got, want := defaultIDs(m), []uint32{10, 12}; !slices.Equal(got, want) { + t.Fatalf("hidden output and idle firefox: %v, want %v", got, want) + } + + setState(m, 11, pw.StateRunning, now) + if got, want := defaultIDs(m), []uint32{10, 11, 12}; !slices.Equal(got, want) { + t.Fatalf("firefox running: %v, want %v", got, want) + } + setState(m, 11, pw.StateSuspended, now.Add(time.Second)) + wantShown(t, m, 11, "firefox hidden before after") + m.refreshShown(now.Add(11 * time.Second)) + wantHidden(t, m, 11, "firefox shown after 10s idle") + if got := m.items(tabPlayback); len(got) != 3 { + t.Errorf("the Playback tab hides rows too: %d items", len(got)) + } +} + +func TestHideFocused(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("firefox"), hideIdle, time.Second)) + setState(m, 11, pw.StateRunning, now) + items := m.items(tabDefault) + i := slices.IndexFunc(items, func(it item) bool { return it.id == 11 }) + m.setFocus(items, i, 0) + setState(m, 11, pw.StateIdle, now) + m.refreshShown(now.Add(time.Second)) + wantHidden(t, m, 11, "focused row shown after its rule's after") + if it, j := m.focused(); it.id == 11 || j != i { + t.Errorf("focus on %d at %d, want the row that took %d's place, at %d", it.id, j, 11, i) + } +} + func TestDeviceRows(t *testing.T) { now := time.Now() o := defaultOptions() @@ -143,4 +199,42 @@ func TestDeviceRows(t *testing.T) { if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 23, 21, 22}; !slices.Equal(got, want) { t.Errorf("all devices: %v, want %v", got, want) } + m = activityMixer(o, rule(nodeMatch{Type: new(nodeType(pw.Source))}, hideAlways, 0)) + m.refreshShown(now) + setState(m, 30, pw.StateRunning, now) + if got, want := defaultIDs(m), []uint32{20, 10, 11, 12, 23, 30}; !slices.Equal(got, want) { + t.Errorf("all devices, inputs hidden: %v, want %v", got, want) + } +} + +func TestHideMuted(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nodeMatch{Type: new(nodeType(pw.Playback))}, hideMuted, 10*time.Second)) + m.snap.Nodes[1].Mute = true // firefox starts muted + m.snap.Nodes[2].Mute = true // a JACK client has no mute to hide it by + m.refreshShown(now) + if got, want := defaultIDs(m), []uint32{20, 10, 12}; !slices.Equal(got, want) { + t.Fatalf("muted from the start: %v, want %v", got, want) + } + + set := func(at time.Time, f func(n *pw.Node)) { setNode(m, 10, f, at) } // FluidSynth + set(now, func(n *pw.Node) { n.Channels = stereo(0) }) + m.refreshShown(now.Add(time.Hour)) + wantShown(t, m, 10, "hidden at 0%%, unmuted") + set(now, func(n *pw.Node) { n.Mute = true }) + m.refreshShown(now.Add(9 * time.Second)) + wantShown(t, m, 10, "hidden 9s after muted") + m.refreshShown(now.Add(10 * time.Second)) + wantHidden(t, m, 10, "shown 10s after muted") + set(now.Add(11*time.Second), func(n *pw.Node) { n.Mute = false }) + if got, want := defaultIDs(m), []uint32{20, 10, 12}; !slices.Equal(got, want) { + t.Errorf("unmuted, a muted JACK client: %v, want %v", got, want) + } + + // PipeWire lists a node before its volume and mute, unmuted until then. + m = activityMixer(defaultOptions(), rule(nodeMatch{Type: new(nodeType(pw.Playback))}, hideMuted, 10*time.Second)) + m.snap.Nodes[1].Channels = nil + m.refreshShown(now) + setNode(m, 11, func(n *pw.Node) { n.Channels, n.Mute = stereo(1), true }, now.Add(time.Second)) + wantHidden(t, m, 11, "firefox, muted when its mute got known, shown") } diff --git a/internal/pipmix/config.go b/internal/pipmix/config.go index 2ab4c1f..6f2673e 100644 --- a/internal/pipmix/config.go +++ b/internal/pipmix/config.go @@ -26,6 +26,7 @@ func parseFlags(fs *flag.FlagSet, args []string) error { } // parseTOML is an ff.ConfigFileParser that maps [table] key to flag table.key. +// It skips [[default.hide]], which loadHideRules reads. func parseTOML(r io.Reader, set func(name, value string) error) error { var m map[string]map[string]any if err := toml.NewDecoder(r).Decode(&m); err != nil { @@ -37,6 +38,12 @@ func parseTOML(r io.Reader, set func(name, value string) error) error { } for _, table := range slices.Sorted(maps.Keys(m)) { for _, key := range slices.Sorted(maps.Keys(m[table])) { + if table == "default" && key == "hide" { + if _, ok := m[table][key].([]any); !ok { + return errors.New("config: write [[default.hide]], with double brackets, for each hide rule") + } + continue + } if err := set(table+"."+key, fmt.Sprint(m[table][key])); err != nil { return err } diff --git a/internal/pipmix/config_test.go b/internal/pipmix/config_test.go index 64f6b94..9fedca4 100644 --- a/internal/pipmix/config_test.go +++ b/internal/pipmix/config_test.go @@ -69,6 +69,9 @@ recording = "off" outputs = "all" inputs = "active" +[[default.hide]] # read by loadHideRules, not as flags +match = { name = "x" } + [debug] log = true log-file = "/tmp/pipmix-test.log" @@ -138,6 +141,7 @@ func TestConfigErrors(t *testing.T) { }{ {"syntax error", "[volume\n", "config 1:"}, {"unknown key", "[volume]\nstpe = 5\n", `"volume.stpe" not defined`}, + {"hide rule in single brackets", "[default.hide]\nmatch = { name = \"x\" }\n", "write [[default.hide]], with double brackets"}, } { p := writeConfigFile(t, tc.toml) _, _, err := parseAll("-config", p) diff --git a/internal/pipmix/dump.go b/internal/pipmix/dump.go index 341a99e..49bc350 100644 --- a/internal/pipmix/dump.go +++ b/internal/pipmix/dump.go @@ -13,6 +13,7 @@ import ( "os" "runtime" "runtime/debug" + "strconv" "strings" "sync" "time" @@ -29,7 +30,7 @@ var dumpEnv = []string{ } // dump writes diagnostic information for -debug.dump. -func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet, opts options, c *pw.Client, media *mpris.Watcher, meter *pulse.Meter) error { +func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet, opts options, hide []hideRule, c *pw.Client, media *mpris.Watcher, meter *pulse.Meter) error { fmt.Fprintln(w, "[build]") dumpBuild(w) @@ -45,6 +46,9 @@ func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet flags.Visit(func(f *flag.Flag) { fmt.Fprintf(w, "flag -%s=%s\n", f.Name, f.Value) }) + for i, r := range hide { + fmt.Fprintf(w, "default.hide %d: %v\n", i+1, r) + } fmt.Fprintln(w, "\n[environment]") for _, k := range dumpEnv { @@ -74,7 +78,7 @@ func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet for _, it := range m.items(tabPlayback) { shown[it.id] = true } - dumpNodes(w, s, shown, opts) + dumpNodes(w, s, shown, opts, hide) fmt.Fprintln(w, "\n[mpris]") switch { @@ -123,10 +127,9 @@ func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet return nil } -func dumpNodes(w io.Writer, s *pw.Snapshot, shown map[uint32]bool, opts options) { - classes := []string{"playback", "recording", "sink", "source"} +func dumpNodes(w io.Writer, s *pw.Snapshot, shown map[uint32]bool, opts options, hide []hideRule) { for _, n := range s.Nodes { - fmt.Fprintf(w, "node %d %s %q (%s) %s", n.ID, classes[n.Class], n.Title, n.Name, n.State) + fmt.Fprintf(w, "node %d %s %q (%s) %s", n.ID, nodeTypeNames[n.Class], n.Title, n.Name, n.State) if n.Active { fmt.Fprint(w, " active") } @@ -141,7 +144,7 @@ func dumpNodes(w io.Writer, s *pw.Snapshot, shown map[uint32]bool, opts options) } fmt.Fprintln(w) var props []string - for _, k := range []string{"object.serial", "application.process.id", "application.process.binary"} { + for _, k := range []string{"object.serial", "node.description", "application.name", pw.PropProcessName, "application.process.id", "application.process.binary"} { if v := n.Props[k]; v != "" { props = append(props, k+"="+v) } @@ -149,6 +152,15 @@ func dumpNodes(w io.Writer, s *pw.Snapshot, shown map[uint32]bool, opts options) if len(props) > 0 { fmt.Fprintf(w, " %s\n", strings.Join(props, " ")) } + var rules []string + for i, r := range hide { + if listable(&n) && r.Match.matches(&n) { + rules = append(rules, strconv.Itoa(i+1)) + } + } + if rules != nil { + fmt.Fprintf(w, " matches default.hide %s\n", strings.Join(rules, ", ")) + } switch { case n.Class != pw.Playback || shown[n.ID]: case n.JACK && !opts.jack: diff --git a/internal/pipmix/dump_test.go b/internal/pipmix/dump_test.go index c709c6a..a1f0427 100644 --- a/internal/pipmix/dump_test.go +++ b/internal/pipmix/dump_test.go @@ -39,7 +39,7 @@ func TestDumpNotConnected(t *testing.T) { go meter.Run(ctx) var out bytes.Buffer - err = dump(ctx, &out, &logBuffer{}, fs, opts, client, media, meter) + err = dump(ctx, &out, &logBuffer{}, fs, opts, nil, client, media, meter) for _, want := range []string{"[pipewire]\nnot connected: ", "[mpris]\nnot connected: ", "[pulse]\nnot connected: "} { if !strings.Contains(out.String(), want) { t.Errorf("dump lacks %q:\n%s", want, out.String()) diff --git a/internal/pipmix/hide.go b/internal/pipmix/hide.go new file mode 100644 index 0000000..0d19186 --- /dev/null +++ b/internal/pipmix/hide.go @@ -0,0 +1,209 @@ +package pipmix + +import ( + "bytes" + "errors" + "fmt" + "io/fs" + "os" + "regexp" + "slices" + "strings" + "time" + + "github.com/pelletier/go-toml/v2" + + "github.com/some-programs/pipmix/internal/pw" +) + +// defaultHideAfter is how long a rule's condition must hold, unless the +// rule sets after. +const defaultHideAfter = 10 * time.Second + +// A hideRule is a [[default.hide]] table: it hides the nodes it matches +// from the Default tab while its condition holds. +type hideRule struct { + Match nodeMatch `toml:"match"` + When hideWhen `toml:"when"` + After *tomlDuration `toml:"after"` + + after time.Duration +} + +// A hideWhen is the condition under which a rule hides a node. +type hideWhen int + +const ( + hideAlways hideWhen = iota // always + hideIdle // the node isn't active + hideMuted // the node is muted; 0% isn't enough +) + +var hideWhenNames = []string{"always", "idle", "muted"} + +func (w hideWhen) String() string { return hideWhenNames[w] } + +func (w *hideWhen) UnmarshalText(b []byte) error { + i := slices.Index(hideWhenNames, string(b)) + if i < 0 { + return fmt.Errorf("when %q: want one of %s", b, strings.Join(hideWhenNames, ", ")) + } + *w = hideWhen(i) + return nil +} + +// A tomlDuration is a time.Duration written as a string, such as "30s". +type tomlDuration time.Duration + +func (d *tomlDuration) UnmarshalText(b []byte) error { + v, err := time.ParseDuration(string(b)) + if err != nil { + return err + } + if v < 0 { + return fmt.Errorf("duration %q: want 0 or more", b) + } + *d = tomlDuration(v) + return nil +} + +// A nodeMatch selects nodes. Each field set must match; Type matches the +// node's kind and the others are unanchored regexps on node properties. +type nodeMatch struct { + Type *nodeType `toml:"type"` + Name *regexp.Regexp `toml:"name"` // node.name + Description *regexp.Regexp `toml:"description"` // node.description + App *regexp.Regexp `toml:"app"` // application.name, or the process name of an ALSA client + Binary *regexp.Regexp `toml:"binary"` // application.process.binary +} + +// A matchProp pairs a nodeMatch field with its key and node property. +type matchProp struct { + key, prop string + re *regexp.Regexp +} + +func (m nodeMatch) props() [4]matchProp { + return [...]matchProp{ + {"name", "node.name", m.Name}, + {"description", "node.description", m.Description}, + {"app", "application.name", m.App}, + {"binary", "application.process.binary", m.Binary}, + } +} + +func (m nodeMatch) matches(n *pw.Node) bool { + if m.Type != nil && pw.Class(*m.Type) != n.Class { + return false + } + for _, p := range m.props() { + if p.re == nil || p.re.MatchString(n.Props[p.prop]) { + continue + } + if alt := n.Props[pw.PropProcessName]; p.key == "app" && alt != "" && p.re.MatchString(alt) { + continue + } + return false + } + return true +} + +func (m nodeMatch) String() string { + var parts []string + if m.Type != nil { + parts = append(parts, fmt.Sprintf("type = %q", m.Type)) + } + for _, p := range m.props() { + if p.re != nil { + parts = append(parts, fmt.Sprintf("%s = %q", p.key, p.re)) + } + } + return "{ " + strings.Join(parts, ", ") + " }" +} + +// A nodeType is the kind of node a rule matches, as written in the config. +type nodeType pw.Class + +// nodeTypeNames are the config's names for pw.Class values, in order. +var nodeTypeNames = []string{"playback", "recording", "output", "input"} + +func (t nodeType) String() string { return nodeTypeNames[t] } + +func (t *nodeType) UnmarshalText(b []byte) error { + i := slices.Index(nodeTypeNames, string(b)) + if i < 0 { + return fmt.Errorf("type %q: want one of %s", b, strings.Join(nodeTypeNames, ", ")) + } + *t = nodeType(i) + return nil +} + +func (r hideRule) String() string { + s := fmt.Sprintf("match = %v, when = %q", r.Match, r.When) + if r.When != hideAlways { + s += fmt.Sprintf(", after = %q", r.after) + } + return s +} + +// loadHideRules reads the [[default.hide]] rules from the config file at +// path, which may be missing. +func loadHideRules(path string) ([]hideRule, error) { + if path == "" { + return nil, nil + } + b, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var cfg struct { + Default struct { + Hide []hideRule `toml:"hide"` + } `toml:"default"` + } + d := toml.NewDecoder(bytes.NewReader(b)) + d.DisallowUnknownFields() + err = d.Decode(&cfg) + if se, ok := errors.AsType[*toml.StrictMissingError](err); ok { + // Keys outside [[default.hide]] belong to flags, checked already. + err = nil + for _, e := range se.Errors { + if k := e.Key(); len(k) > 2 && k[0] == "default" && k[1] == "hide" { + row, col := e.Position() + return nil, fmt.Errorf("config %d:%d: unknown key %s in [[default.hide]]\n%s", row, col, strings.Join(k[2:], "."), e.String()) + } + } + } + if de, ok := errors.AsType[*toml.DecodeError](err); ok { + row, col := de.Position() + return nil, fmt.Errorf("config %d:%d: %s\n%s", row, col, de.Error(), de.String()) + } + if err != nil { + return nil, fmt.Errorf("config: %w", err) + } + rules := cfg.Default.Hide + for i := range rules { + if err := rules[i].check(); err != nil { + return nil, fmt.Errorf("config: [[default.hide]] number %d: %w", i+1, err) + } + } + return rules, nil +} + +// check validates r and fills in its defaults. +func (r *hideRule) check() error { + switch { + case r.Match == nodeMatch{}: + return errors.New("match: want at least one of type, name, description, app, binary") + case r.When == hideAlways && r.After != nil: + return errors.New(`after: not used with when = "always"`) + } + r.after = defaultHideAfter + if r.After != nil { + r.after = time.Duration(*r.After) + } + return nil +} diff --git a/internal/pipmix/hide_test.go b/internal/pipmix/hide_test.go new file mode 100644 index 0000000..80b8996 --- /dev/null +++ b/internal/pipmix/hide_test.go @@ -0,0 +1,98 @@ +package pipmix + +import ( + "regexp" + "slices" + "strings" + "testing" + + "github.com/some-programs/pipmix/internal/pw" +) + +func TestLoadHideRules(t *testing.T) { + p := writeConfigFile(t, ` +[ui] +fps = 30 + +[default] +recording = "all" + +[[default.hide]] +match = { type = "playback", name = "^FluidSynth$" } +when = "muted" +after = "30s" + +[[default.hide]] +match = { binary = "firefox" } +when = "idle" + +[[default.hide]] +match = { description = "HDMI" } +`) + rules, err := loadHideRules(p) // ignoring the flags' tables + if err != nil { + t.Fatal(err) + } + var got []string + for _, r := range rules { + got = append(got, r.String()) + } + want := []string{ + `match = { type = "playback", name = "^FluidSynth$" }, when = "muted", after = "30s"`, + `match = { binary = "firefox" }, when = "idle", after = "10s"`, + `match = { description = "HDMI" }, when = "always"`, + } + if !slices.Equal(got, want) { + t.Errorf("rules:\ngot %q\nwant %q", got, want) + } + + if rules, err := loadHideRules(p + ".missing"); rules != nil || err != nil { + t.Errorf("missing file: %v, %v; want no rules and no error", rules, err) + } +} + +func TestLoadHideRulesErrors(t *testing.T) { + for _, tc := range []struct { + name, toml, want string + }{ + {"unknown key", "[[default.hide]]\nmatch = { nmae = \"x\" }\n", "config 2:11: unknown key nmae in [[default.hide]]"}, + {"unknown rule key", "[[default.hide]]\nmatch = { name = \"x\" }\nwen = \"idle\"\n", "config 3:1: unknown key wen"}, + {"bad regexp", "[[default.hide]]\nmatch = { name = \"(x\" }\n", "config 2:18: toml: error parsing regexp"}, + {"bad type", "[[default.hide]]\nmatch = { type = \"sink\" }\n", `type "sink": want one of playback, recording, output, input`}, + {"bad when", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"quiet\"\n", `when "quiet": want one of always, idle, muted`}, + {"bad after", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"idle\"\nafter = \"-1s\"\n", `want 0 or more`}, + {"empty match", "[[default.hide]]\nwhen = \"idle\"\n", "number 1: match: want at least one of type, name, description, app, binary"}, + {"after with always", "[[default.hide]]\nmatch = { name = \"x\" }\nafter = \"1s\"\n", `after: not used with when = "always"`}, + {"second rule", "[[default.hide]]\nmatch = { name = \"x\" }\n[[default.hide]]\n", "number 2: match"}, + } { + _, err := loadHideRules(writeConfigFile(t, tc.toml)) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: err = %v, want containing %q", tc.name, err, tc.want) + } + } +} + +func TestNodeMatch(t *testing.T) { + fluid := nodeMatch{Type: new(nodeType(pw.Playback)), Name: regexp.MustCompile("^FluidSynth$")} + n := &pw.Node{Class: pw.Playback, Props: map[string]string{"node.name": "FluidSynth"}} + if !fluid.matches(n) { + t.Error("type and name don't match FluidSynth") + } + n.Class = pw.Sink + if fluid.matches(n) { + t.Error("type playback matches an output named FluidSynth") + } + + m := nodeMatch{App: regexp.MustCompile("^claude$")} + alsa := &pw.Node{Props: map[string]string{"application.name": "PipeWire ALSA [2.1.332]", pw.PropProcessName: "claude"}} + if !m.matches(alsa) { + t.Error("app doesn't match an ALSA client's process name") + } + if m.matches(&pw.Node{Props: map[string]string{"application.name": "firefox"}}) { + t.Error("app matches another application") + } + m.App = regexp.MustCompile("ALSA") + if !m.matches(alsa) { + t.Error("app doesn't match an ALSA client's application.name") + } +} diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index b653104..e319285 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -133,6 +133,7 @@ type mixer struct { meterMode meterMode quitKeys section opts options + hide []hideRule // [[default.hide]] rules act activity redraw bool // the screen needs drawing for a change made outside update @@ -322,7 +323,7 @@ func (m *mixer) update(msg message) command { // clients last. The Default tab lists other output devices below those, // then input devices, then recording streams. func (m *mixer) items(t tab) []item { - var items, fixed, outputs, inputs, recording []item + var items, fixed, outputs, inputs, recording, hidden []item if t == tabCards { for i := range m.snap.Cards { c := &m.snap.Cards[i] @@ -333,6 +334,10 @@ func (m *mixer) items(t tab) []item { for i := range m.snap.Nodes { n := &m.snap.Nodes[i] if !m.listed(t, n) { + // A stream that a rule hides still has its duplicates dropped. + if t == tabDefault && n.Class == pw.Playback && m.act.hidden[n.ID] && m.listed(tabPlayback, n) { + hidden = append(hidden, item{id: n.ID, node: n, media: m.mediaTitles[n.ID]}) + } continue } var player *mpris.Player @@ -367,7 +372,11 @@ func (m *mixer) items(t tab) []item { return all } if m.opts.dedup { - all = filterDuplicates(all) + among := all + if len(hidden) > 0 { + among = slices.Concat(all, hidden) + } + all = filterDuplicates(all, among) } all = groupStreams(all) if t != tabDefault { @@ -384,7 +393,7 @@ func (m *mixer) listed(t tab, n *pw.Node) bool { if t != tabDefault { return true } - if !listable(n) { + if !listable(n) || m.act.hidden[n.ID] { return false } switch m.defaultShow(n) { @@ -532,17 +541,18 @@ func (m *mixer) toggleGroupMute(groupKey string) { } } -// filterDuplicates returns items without mono playback streams that duplicate -// a multi-channel stream from the same application or media. -func filterDuplicates(items []item) []item { +// filterDuplicates returns items without the mono playback streams that +// duplicate a multi-channel stream in among, from the same application or +// media. +func filterDuplicates(items, among []item) []item { for i, it := range items { - if !isDuplicate(it, items) { + if !isDuplicate(it, among) { continue } filtered := make([]item, 0, len(items)-1) filtered = append(filtered, items[:i]...) for _, rest := range items[i+1:] { - if !isDuplicate(rest, items) { + if !isDuplicate(rest, among) { filtered = append(filtered, rest) } } diff --git a/internal/pipmix/mixer_test.go b/internal/pipmix/mixer_test.go index 9089122..8895eab 100644 --- a/internal/pipmix/mixer_test.go +++ b/internal/pipmix/mixer_test.go @@ -706,6 +706,14 @@ func TestDedupPlayback(t *testing.T) { if items := m.items(tabPlayback); len(items) != 3 { t.Errorf("different media titles: got %d items, want 3", len(items)) } + + // A rule hiding the multi-channel stream doesn't bring its duplicate back. + m = newMixer(pw.NewClient(nil), nil, nil, quitKeys(), defaultOptions()) + m.snap = snap + m.act.hidden = map[uint32]bool{10: true} + if items := m.items(tabDefault); len(items) != 1 || items[0].id != 12 { + t.Errorf("Default tab, multi-channel stream hidden: got items %v, want [12]", items) + } } func TestPlaybackGrouping(t *testing.T) { diff --git a/internal/pipmix/pipmix.go b/internal/pipmix/pipmix.go index 249f963..e063965 100644 --- a/internal/pipmix/pipmix.go +++ b/internal/pipmix/pipmix.go @@ -40,6 +40,10 @@ func Run(args []string) error { if err != nil { return err } + hide, err := loadHideRules(fs.Lookup("config").Value.String()) + if err != nil { + return err + } var clientLog *log.Logger if debug.log { f, err := openDebugLog(debug.logFile) @@ -83,9 +87,10 @@ func Run(args []string) error { } go client.Run(ctx) if debug.dump { - return dump(ctx, os.Stdout, &dumpLog, fs, opts, client, media, meter) + return dump(ctx, os.Stdout, &dumpLog, fs, opts, hide, client, media, meter) } m := newMixer(client, media, meter, quitKeys(), opts) + m.hide = hide return run(ctx, &m) } From af5555bad6378fa54236b8710ffdfd17cecdb6cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Sat, 28 Nov 2026 14:02:13 +0100 Subject: [PATCH 10/10] add the silent condition to hide rules A rule with when = "silent" hides a node while its level stays below a threshold. Nodes that such a rule matches are metered even while no meter is drawn. --- README.md | 12 +- internal/pipmix/activity.go | 189 ++++++++++++++++++++++++++++++- internal/pipmix/activity_test.go | 160 ++++++++++++++++++++++++++ internal/pipmix/dump.go | 7 +- internal/pipmix/hide.go | 34 +++++- internal/pipmix/hide_test.go | 9 +- internal/pipmix/loop.go | 12 +- internal/pipmix/meters.go | 51 +++++++-- internal/pipmix/meters_test.go | 23 ++++ internal/pipmix/mixer.go | 4 +- internal/pipmix/options.go | 2 +- internal/pipmix/options_test.go | 14 ++- internal/pipmix/pipmix.go | 14 +-- 13 files changed, 490 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index c4c15d2..24a9ae4 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ fps = 60 # max redraws per second (1 to 240) tab = "default" # starting tab: default, playback, recording, outputs, inputs, cards (or 1 to 6) [meter] -enable = true +enable = true # draw level meters always = false # keep metering when the terminal is unfocused rate = 40 # peaks per second per meter (1 to 200) mode = "both" # both, average, or peak @@ -77,6 +77,13 @@ inputs = "off" # input devices: off, active (those in use, and 5s after), `[[default.hide]]` rules hide nodes from the Default tab; the other tabs still list everything. They can only be set in the config file. A node is hidden while any rule matching it says so, even when focused. ```toml +# Hide FluidSynth once it has been silent for 5 seconds. +[[default.hide]] +match = { type = "playback", name = "^FluidSynth$" } +when = "silent" +after = "5s" +threshold = -80 # dBFS; quieter peaks count as silence + # Hide Firefox's streams while they don't run. [[default.hide]] match = { binary = "firefox" } @@ -101,7 +108,8 @@ after = "0s" - `always` (the default): always. - `idle`: while nothing plays or records through the node. - `muted`: while the node is muted. A volume of 0% doesn't count. -- `after` is how long `idle` or `muted` must last before the node hides; it is 10s unless set. A node shows again as soon as the condition ends, and nodes start out hidden if the condition already holds. + - `silent`: while its level stays below `threshold` (-80 dBFS unless set). Muted nodes and nodes at 0% stay visible; use `muted` for those. +- `after` is how long `idle`, `muted`, or `silent` must last before the node hides; it is 10s unless set. A node shows again as soon as the condition ends, and nodes start out hidden if the condition already holds. ## Technical Details diff --git a/internal/pipmix/activity.go b/internal/pipmix/activity.go index 2114f4c..b117b3b 100644 --- a/internal/pipmix/activity.go +++ b/internal/pipmix/activity.go @@ -2,8 +2,10 @@ package pipmix import ( "maps" + "slices" "time" + "github.com/some-programs/pipmix/internal/pulse" "github.com/some-programs/pipmix/internal/pw" ) @@ -11,6 +13,13 @@ import ( // after it stops being active, when it is only shown because it was active. const activeLinger = 5 * time.Second +// A ruleNode identifies one hide rule applied to one node: the index of +// the rule in mixer.hide and the ID of the node. +type ruleNode struct { + rule int + id uint32 +} + // A nodeState is the per-node data that activity keeps for one node of the // latest PipeWire snapshot. trackNodes rebuilds it on every new snapshot and // copies the timestamps over from the node's previous state. @@ -20,15 +29,27 @@ type nodeState struct { idleAt time.Time // when the node went from active to not active; zero if that was never seen muted bool // the node is muted mutedAt time.Time // when the node went from unmuted to muted; zero if that was never seen + quiet bool // the node is muted or at 0%, so its meter reads silence even while it plays + gain []float64 // per channel, the factor its volume scales levels by; nil if levels are measured before volume rules []int // indexes in mixer.hide of the hide rules that match the node + + silent bool // a silent rule matches the node and the node can be metered + target pulse.Target // what to meter for the node, if silent is set + metered bool // the latest meter snapshot has levels for the node } // activity holds the state used to decide which nodes the Default tab -// shows: which nodes are active or muted, and since when. +// shows: which nodes are active, muted or silent, and since when. type activity struct { snap *pw.Snapshot // the PipeWire snapshot that nodes was built from nodes map[uint32]nodeState // state of each listable node in snap, by node ID + // heard records, for each silent rule and node it matches, the last time + // the node's level was above the rule's threshold. A missing entry means + // the node has not been above the threshold yet. + heard map[ruleNode]time.Time + heardSnap *pulse.Snapshot // the last meter snapshot passed to hear + shown map[uint32]bool // nodes to show because they are active or stopped less than activeLinger ago hidden map[uint32]bool // nodes that a hide rule currently hides wakeAt time.Time // the next time updateShown must run because a delay runs out; zero if none @@ -60,6 +81,8 @@ func (m *mixer) trackNodes(now time.Time) { known: len(n.Channels) > 0, active: n.Active, muted: n.Mute && !n.JACK, + quiet: inaudible(n), + gain: volumeGain(n), } switch { case st.active: @@ -80,16 +103,43 @@ func (m *mixer) trackNodes(now time.Time) { default: st.mutedAt = prev.mutedAt } + if a.heardSnap != nil { + _, st.metered = a.heardSnap.Peaks[n.ID] + } for ri := range m.hide { r := &m.hide[ri] if !r.Match.matches(n) { continue } st.rules = append(st.rules, ri) + if r.When != hideSilent { + continue + } + if !st.silent { + st.target, st.silent = meterTarget(m.snap, n) + } + // The node was muted or at 0% and now isn't. Count that as + // heard now, so the rule waits its full delay before hiding it. + if st.silent && prev.quiet && !st.quiet { + a.hearAt(ruleNode{ri, n.ID}, now) + } } nodes[n.ID] = st } a.nodes = nodes + maps.DeleteFunc(a.heard, func(k ruleNode, _ time.Time) bool { + st := nodes[k.id] + return !st.silent || !slices.Contains(st.rules, k.rule) + }) +} + +// hearAt records t as the last time the node of k was above the threshold +// of the rule of k. +func (a *activity) hearAt(k ruleNode, t time.Time) { + if a.heard == nil { + a.heard = make(map[ruleNode]time.Time) + } + a.heard[k] = t } // defaultShow returns the -default.recording, -default.outputs or @@ -110,7 +160,7 @@ func (m *mixer) defaultShow(n *pw.Node) showWhen { // updateShown takes in the current PipeWire snapshot if it is new, then // recomputes m.act.shown and m.act.hidden for the time now, and reports // whether either changed. It sets m.act.wakeAt to the earliest -// time at which the result can change without a new snapshot. +// time at which the result can change without a new snapshot or meter level. func (m *mixer) updateShown(now time.Time) (changed bool) { m.trackNodes(now) a := &m.act @@ -157,6 +207,16 @@ func (m *mixer) updateShown(now time.Time) (changed bool) { // With a zero mutedAt the delay has always run out, so the // node hides at once. hide = st.muted && !until(st.mutedAt.Add(r.after)) + case hideSilent: + switch { + case !st.silent: // the node can't be metered, so stays visible + case st.quiet: // muted or at 0%: its meter says nothing about what it plays + case st.active && !st.metered: // the meter has no levels for it yet + default: + // A node with no entry in heard gets the zero time, so + // the delay has always run out and it hides at once. + hide = !until(a.heard[ruleNode{ri, n.ID}].Add(r.after)) + } } if hide { break @@ -175,6 +235,37 @@ func (m *mixer) updateShown(now time.Time) (changed bool) { return changed } +// meteredAfterVolume reports whether n's levels are measured after its +// volume and mute apply: true for playback streams and input devices. +func meteredAfterVolume(n *pw.Node) bool { + return !n.JACK && n.Class != pw.Sink && n.Class != pw.Recording +} + +// volumeGain returns the factor that each channel's volume scales its level +// by, the cube of the volume, or nil if n's levels are measured before volume. +func volumeGain(n *pw.Node) []float64 { + if !meteredAfterVolume(n) { + return nil + } + gain := make([]float64, len(n.Channels)) + for i, c := range n.Channels { + gain[i] = c.Volume * c.Volume * c.Volume + } + return gain +} + +// inaudible reports whether n's meter reads silence because n is muted or +// has every channel at 0%, even while n plays. +func inaudible(n *pw.Node) bool { + if !meteredAfterVolume(n) { + return false + } + if n.Mute { + return true + } + return len(n.Channels) > 0 && !slices.ContainsFunc(n.Channels, func(c pw.Channel) bool { return c.Volume > 0 }) +} + // refreshShown calls updateShown. If the set of visible nodes changed, it // asks for a redraw and updates focus, scrolling and the metered nodes. func (m *mixer) refreshShown(now time.Time) { @@ -185,3 +276,97 @@ func (m *mixer) refreshShown(now time.Time) { m.refocus() m.watchMeters() } + +// hear processes a new meter snapshot for the silent rules. For each node +// that a silent rule matches, it records in m.act.heard when a peak is above +// the rule's threshold, and updates whether the meter has levels for the +// node. It calls refreshShown if that can change which nodes are visible. +// Peaks are compared as the level they have at a volume of 100%. +func (m *mixer) hear(snap *pulse.Snapshot, now time.Time) { + a := &m.act + if snap == a.heardSnap { + return + } + a.heardSnap = snap + woke := false + for id, st := range a.nodes { + if !st.silent { + continue + } + peaks, ok := snap.Peaks[id] + if ok != st.metered { + st.metered = ok + a.nodes[id] = st + woke = true + } + for _, ri := range st.rules { + r := &m.hide[ri] + if r.When != hideSilent || !st.above(peaks, r.level) { + continue + } + a.hearAt(ruleNode{ri, id}, now) + woke = woke || a.hidden[id] + } + } + if woke { + m.refreshShown(now) + } +} + +// listenRate is how many peaks a second the meter streams send while no +// meter is drawn and only silent rules use the levels. Hide delays are +// counted in seconds, so a few peaks a second are enough, and they wake the +// process several times less often than the rate the meters are drawn at. +const listenRate = 4 + +// above reports whether any of peaks, scaled to a volume of 100%, is above +// level. +func (st nodeState) above(peaks []float64, level float64) bool { + for ch, p := range peaks { + if ch < len(st.gain) { + if p > level*st.gain[ch] { + return true + } + } else if p > level { + return true + } + } + return false +} + +// silentTargets adds the active nodes that silent rules match to targets, +// the set of nodes to meter, and returns the result along with the IDs it +// added. Silent rules need levels for these nodes even when no meter for +// them is on screen: when they are hidden or scrolled out of view, or when +// the meters are paused because the terminal isn't focused. Nodes that +// aren't active are not metered, and silent rules treat them as silent. +// +// While no meter is drawn at all, the nodes it adds are metered at +// listenRate, or at -meter.rate if that is lower. +func (m *mixer) silentTargets(targets map[uint32]pulse.Target) (all map[uint32]pulse.Target, added map[uint32]bool) { + if m.meter == nil { + return targets, nil + } + rate := 0 + if m.metersOff() { + rate = min(listenRate, m.opts.meterRate) + } + for id, st := range m.act.nodes { + if !st.silent || !st.active { + continue + } + if _, ok := targets[id]; ok { + continue + } + if targets == nil { + targets = make(map[uint32]pulse.Target) + } + if added == nil { + added = make(map[uint32]bool) + } + t := st.target + t.Rate = rate + targets[id], added[id] = t, true + } + return targets, added +} diff --git a/internal/pipmix/activity_test.go b/internal/pipmix/activity_test.go index 63034e3..0d3986e 100644 --- a/internal/pipmix/activity_test.go +++ b/internal/pipmix/activity_test.go @@ -159,6 +159,166 @@ func TestHideAlwaysAndIdle(t *testing.T) { } } +// With -meter.enable=false no meter is drawn, and a silent rule still +// listens to the node it matches, at the low rate. +func TestHideSilentMetersDisabled(t *testing.T) { + now := time.Now() + opts := defaultOptions() + opts.meters = metersOff + m := activityMixer(opts, rule(nameIs("FluidSynth"), hideSilent, 30*time.Second)) + m.refreshShown(now) + m.watchMeters() + if keys := targetKeys(m.watched); !slices.Equal(keys, []uint32{10}) { + t.Fatalf("metered with -meter.enable=false: %v, want only FluidSynth", keys) + } + if got := m.watched[10].Rate; got != listenRate { + t.Errorf("FluidSynth metered at rate %d, want %d", got, listenRate) + } +} + +func TestHideSilent(t *testing.T) { + t.Run("heard, then silent", func(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("FluidSynth"), hideSilent, 30*time.Second)) + m.refreshShown(now) + wantShown(t, m, 10, "playing FluidSynth hidden before the meter has levels for it") + if targets, _ := m.silentTargets(nil); targets[10].Serial != 100 { + t.Errorf("FluidSynth not metered: %v", targets) + } + + quiet := &pulse.Snapshot{Peaks: map[uint32][]float64{10: {0.00005, 0}}} + m.hear(quiet, now) + wantHidden(t, m, 10, "FluidSynth shown at -86 dBFS") + // Hidden, its levels move no meter, so the render loop can rest. + m.watchMeters() + levels := map[uint32][]float64{10: {0.00005, 0}} + m.setLevels(&pulse.Snapshot{Peaks: levels, Averages: levels}, now) + levels = map[uint32][]float64{10: {0.0001, 0.0003}} + if m.setLevels(&pulse.Snapshot{Peaks: levels, Averages: levels}, now.Add(20*time.Millisecond)) { + t.Error("levels of hidden FluidSynth keep the meters moving") + } + loud := &pulse.Snapshot{Peaks: map[uint32][]float64{10: {0, 0.5}}} + m.hear(loud, now.Add(time.Second)) + wantShown(t, m, 10, "playing FluidSynth hidden") + if want := now.Add(31 * time.Second); !m.act.wakeAt.Equal(want) { + t.Errorf("wake at %v, want %v", m.act.wakeAt, want) + } + + // With the terminal not focused, the meters on screen pause, but + // FluidSynth's goes on, at the lower rate that is enough for the + // rule. + m.watchMeters() + if got := m.watched[10].Rate; got != 0 { + t.Errorf("FluidSynth metered at rate %d while its meter shows, want 0 for the meter's rate", got) + } + m.blurred = true + m.watchMeters() + if keys := targetKeys(m.watched); !slices.Equal(keys, []uint32{10}) { + t.Errorf("metered while the terminal isn't focused: %v, want only FluidSynth", keys) + } + if got := m.watched[10].Rate; got != listenRate { + t.Errorf("FluidSynth metered at rate %d while the terminal isn't focused, want %d", got, listenRate) + } + m.opts.meterRate = 2 + m.watchMeters() + if got := m.watched[10].Rate; got != 2 { + t.Errorf("FluidSynth metered at rate %d with -meter.rate 2, want 2", got) + } + }) + t.Run("at a low volume", func(t *testing.T) { + // At 19% the volume multiplies levels by 0.19 cubed, about 0.0069. + // A peak of 0.00005 is below the threshold of 0.0001 as measured, + // and above it as the level at 100%, about 0.0073. + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("FluidSynth"), hideSilent, 10*time.Second)) + m.refreshShown(now) + peaks := &pulse.Snapshot{Peaks: map[uint32][]float64{10: {0.00005, 0}}} + m.hear(peaks, now) + wantHidden(t, m, 10, "FluidSynth at 100% shown at -86 dBFS") + + setNode(m, 10, func(n *pw.Node) { n.Channels = stereo(0.19) }, now) + m.hear(&pulse.Snapshot{Peaks: peaks.Peaks}, now.Add(time.Second)) + wantShown(t, m, 10, "FluidSynth at 19% hidden while it sends -43 dBFS") + // The same factor applies to the noise floor: 0.0000005 measured + // at 19% is about -83 dBFS at 100%, below the threshold. + m.hear(&pulse.Snapshot{Peaks: map[uint32][]float64{10: {0.0000005, 0}}}, now.Add(2*time.Second)) + m.refreshShown(now.Add(11*time.Second + time.Millisecond)) + wantHidden(t, m, 10, "FluidSynth at 19% shown 10s after its last peak above the threshold") + + // Output devices are measured before their volume. + if got := volumeGain(&pw.Node{Class: pw.Sink, Channels: stereo(0.5)}); got != nil { + t.Errorf("volumeGain of an output device = %v, want nil", got) + } + }) + t.Run("unmetered", func(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("obs"), hideSilent, time.Second)) + setState(m, 30, pw.StateRunning, now) + m.refreshShown(now.Add(time.Hour)) + wantShown(t, m, 30, "silent rule hid a stream it can't meter") + }) + t.Run("at 0% or muted", func(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("FluidSynth"), hideSilent, 10*time.Second)) + m.refreshShown(now) + m.hear(&pulse.Snapshot{Peaks: map[uint32][]float64{10: {0, 0}}}, now) + m.refreshShown(now) + wantHidden(t, m, 10, "never-heard FluidSynth shown") + for i, tc := range []struct { + name string + set func(n *pw.Node) + }{ + {"at 0%", func(n *pw.Node) { n.Channels = stereo(0) }}, + {"muted", func(n *pw.Node) { n.Mute = true }}, + } { + start := now.Add(time.Duration(i) * time.Hour) + setNode(m, 10, tc.set, start) + m.refreshShown(start.Add(time.Minute)) + wantShown(t, m, 10, "FluidSynth %s hidden", tc.name) + // Turned up again a while later, it gets the rule's after + // before hiding. + up := start.Add(5 * time.Minute) + setNode(m, 10, func(n *pw.Node) { n.Channels, n.Mute = stereo(1), false }, up) + wantShown(t, m, 10, "FluidSynth hidden as soon as turned up from %s", tc.name) + m.refreshShown(up.Add(9 * time.Second)) + wantShown(t, m, 10, "FluidSynth hidden 9s after %s", tc.name) + m.refreshShown(up.Add(10 * time.Second)) + wantHidden(t, m, 10, "FluidSynth shown 10s after %s", tc.name) + } + if inaudible(&pw.Node{Class: pw.Recording, Mute: true, Channels: stereo(1)}) { + t.Error("a muted recording stream's meter reads silence, but it is measured before its mute") + } + }) + t.Run("no meter levels", func(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("FluidSynth"), hideSilent, 10*time.Second)) + m.refreshShown(now) + wantShown(t, m, 10, "playing FluidSynth hidden with the meter down") + if !m.act.wakeAt.IsZero() { + t.Errorf("wake at %v with nothing to wait for", m.act.wakeAt) + } + // The meter comes up and reads silence, then loses the stream again. + up := now.Add(time.Minute) + m.hear(&pulse.Snapshot{Peaks: map[uint32][]float64{10: {0, 0}}}, up) + wantHidden(t, m, 10, "silent FluidSynth shown once metered") + m.hear(&pulse.Snapshot{}, up.Add(time.Minute)) + wantShown(t, m, 10, "FluidSynth hidden after the meter lost it") + }) + t.Run("idle", func(t *testing.T) { + now := time.Now() + m := activityMixer(defaultOptions(), rule(nameIs("FluidSynth"), hideSilent, 10*time.Second)) + m.refreshShown(now) + m.hear(&pulse.Snapshot{Peaks: map[uint32][]float64{10: {0.5, 0.5}}}, now) + wantShown(t, m, 10, "playing FluidSynth hidden") + setState(m, 10, pw.StateIdle, now) + if targets, _ := m.silentTargets(nil); len(targets) != 0 { + t.Errorf("idle FluidSynth metered: %v", targets) + } + m.refreshShown(now.Add(10 * time.Second)) + wantHidden(t, m, 10, "idle FluidSynth shown after 10s") + }) +} + func TestHideFocused(t *testing.T) { now := time.Now() m := activityMixer(defaultOptions(), rule(nameIs("firefox"), hideIdle, time.Second)) diff --git a/internal/pipmix/dump.go b/internal/pipmix/dump.go index 49bc350..e154e48 100644 --- a/internal/pipmix/dump.go +++ b/internal/pipmix/dump.go @@ -107,9 +107,10 @@ func dump(ctx context.Context, w io.Writer, logs *logBuffer, flags *flag.FlagSet targets[s.Nodes[i].ID] = t } } - if meter == nil { - fmt.Fprintln(w, "off") - } else if err := probePulse(ctx); err != nil { + if opts.meters == metersOff { + fmt.Fprintln(w, "meters are not drawn: -meter.enable=false") + } + if err := probePulse(ctx); err != nil { fmt.Fprintf(w, "not connected: %v\n", err) failed = append(failed, "pulse") } else { diff --git a/internal/pipmix/hide.go b/internal/pipmix/hide.go index 0d19186..3583968 100644 --- a/internal/pipmix/hide.go +++ b/internal/pipmix/hide.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io/fs" + "math" "os" "regexp" "slices" @@ -20,14 +21,22 @@ import ( // rule sets after. const defaultHideAfter = 10 * time.Second +// defaultThreshold is the level, in dBFS, below which a silent rule +// counts a node as silent, unless the rule sets threshold. It is just above +// the dither noise of 16-bit audio, about -90 dBFS. +const defaultThreshold = -80.0 + // A hideRule is a [[default.hide]] table: it hides the nodes it matches // from the Default tab while its condition holds. type hideRule struct { - Match nodeMatch `toml:"match"` - When hideWhen `toml:"when"` - After *tomlDuration `toml:"after"` - - after time.Duration + Match nodeMatch `toml:"match"` + When hideWhen `toml:"when"` + After *tomlDuration `toml:"after"` + Threshold *float64 `toml:"threshold"` // dBFS + + after time.Duration + threshold float64 // dBFS + level float64 // threshold as a linear peak } // A hideWhen is the condition under which a rule hides a node. @@ -36,10 +45,11 @@ type hideWhen int const ( hideAlways hideWhen = iota // always hideIdle // the node isn't active + hideSilent // the node's peaks stay below the threshold hideMuted // the node is muted; 0% isn't enough ) -var hideWhenNames = []string{"always", "idle", "muted"} +var hideWhenNames = []string{"always", "idle", "silent", "muted"} func (w hideWhen) String() string { return hideWhenNames[w] } @@ -143,6 +153,9 @@ func (r hideRule) String() string { if r.When != hideAlways { s += fmt.Sprintf(", after = %q", r.after) } + if r.When == hideSilent { + s += fmt.Sprintf(", threshold = %g", r.threshold) + } return s } @@ -200,10 +213,19 @@ func (r *hideRule) check() error { return errors.New("match: want at least one of type, name, description, app, binary") case r.When == hideAlways && r.After != nil: return errors.New(`after: not used with when = "always"`) + case r.When != hideSilent && r.Threshold != nil: + return errors.New(`threshold: only used with when = "silent"`) + case r.Threshold != nil && *r.Threshold > 0: + return fmt.Errorf("threshold %g: want 0 dBFS or less", *r.Threshold) } r.after = defaultHideAfter if r.After != nil { r.after = time.Duration(*r.After) } + r.threshold = defaultThreshold + if r.Threshold != nil { + r.threshold = *r.Threshold + } + r.level = math.Pow(10, r.threshold/20) return nil } diff --git a/internal/pipmix/hide_test.go b/internal/pipmix/hide_test.go index 80b8996..f4ddd82 100644 --- a/internal/pipmix/hide_test.go +++ b/internal/pipmix/hide_test.go @@ -19,8 +19,9 @@ recording = "all" [[default.hide]] match = { type = "playback", name = "^FluidSynth$" } -when = "muted" +when = "silent" after = "30s" +threshold = -20 # 20*log10(10^(-20/20)) isn't -20 [[default.hide]] match = { binary = "firefox" } @@ -38,7 +39,7 @@ match = { description = "HDMI" } got = append(got, r.String()) } want := []string{ - `match = { type = "playback", name = "^FluidSynth$" }, when = "muted", after = "30s"`, + `match = { type = "playback", name = "^FluidSynth$" }, when = "silent", after = "30s", threshold = -20`, `match = { binary = "firefox" }, when = "idle", after = "10s"`, `match = { description = "HDMI" }, when = "always"`, } @@ -59,10 +60,12 @@ func TestLoadHideRulesErrors(t *testing.T) { {"unknown rule key", "[[default.hide]]\nmatch = { name = \"x\" }\nwen = \"idle\"\n", "config 3:1: unknown key wen"}, {"bad regexp", "[[default.hide]]\nmatch = { name = \"(x\" }\n", "config 2:18: toml: error parsing regexp"}, {"bad type", "[[default.hide]]\nmatch = { type = \"sink\" }\n", `type "sink": want one of playback, recording, output, input`}, - {"bad when", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"quiet\"\n", `when "quiet": want one of always, idle, muted`}, + {"bad when", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"quiet\"\n", `when "quiet": want one of always, idle, silent, muted`}, {"bad after", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"idle\"\nafter = \"-1s\"\n", `want 0 or more`}, {"empty match", "[[default.hide]]\nwhen = \"idle\"\n", "number 1: match: want at least one of type, name, description, app, binary"}, {"after with always", "[[default.hide]]\nmatch = { name = \"x\" }\nafter = \"1s\"\n", `after: not used with when = "always"`}, + {"threshold without silent", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"idle\"\nthreshold = -50\n", "threshold: only used"}, + {"threshold above 0", "[[default.hide]]\nmatch = { name = \"x\" }\nwhen = \"silent\"\nthreshold = 3\n", "want 0 dBFS or less"}, {"second rule", "[[default.hide]]\nmatch = { name = \"x\" }\n[[default.hide]]\n", "number 2: match"}, } { _, err := loadHideRules(writeConfigFile(t, tc.toml)) diff --git a/internal/pipmix/loop.go b/internal/pipmix/loop.go index 3485a97..27b2932 100644 --- a/internal/pipmix/loop.go +++ b/internal/pipmix/loop.go @@ -110,11 +110,17 @@ func run(ctx context.Context, m *mixer) error { full = true } case msg := <-msgs: - if _, ok := msg.(quitMsg); ok { + switch msg.(type) { + case quitMsg: return nil + case meterMsg: + // New levels redraw the meters, if they show. + exec(m.update(msg)) + meters = meters || !m.metersOff() + default: + exec(m.update(msg)) + full = true } - exec(m.update(msg)) - full = true case <-tickC: exec(m.tickMetering()) meters = true diff --git a/internal/pipmix/meters.go b/internal/pipmix/meters.go index ecd2c16..2102343 100644 --- a/internal/pipmix/meters.go +++ b/internal/pipmix/meters.go @@ -73,10 +73,18 @@ func (m *mixer) nextMeter() command { } } +// metersOff reports whether no meter is drawn now: -meter.enable is false, +// the meters are toggled off, the help shows, or the terminal isn't focused +// and the meters only run while it is. Hide rules with when = "silent" still +// listen to the levels of the nodes they match. func (m *mixer) metersOff() bool { - return m.help || m.blurred && m.opts.meters != metersAlways || m.metersHidden + return m.metersDisabled() || m.help || m.blurred && m.opts.meters != metersAlways || m.metersHidden } +// metersDisabled reports whether the mixer never draws meters, because +// -meter.enable is false. +func (m *mixer) metersDisabled() bool { return m.opts.meters == metersOff } + // meterTargets returns the visible nodes that can be metered. func (m *mixer) meterTargets() map[uint32]pulse.Target { if m.metersOff() { @@ -187,7 +195,8 @@ func (m *mixer) watchMetersItems(items []item) { if m.meter == nil { return } - targets := m.meterTargetsItems(items) + targets, unshown := m.silentTargets(m.meterTargetsItems(items)) + m.unshown = unshown if maps.EqualFunc(targets, m.watched, pulse.Target.Equal) { return } @@ -208,7 +217,7 @@ func (m *mixer) startMetering() command { if m.ticking { return nil } - if !m.setLevels(m.meterSnapshot(), time.Now()) { + if !m.readLevels() { return m.waitMeter() } m.ticking = true @@ -218,13 +227,36 @@ func (m *mixer) startMetering() command { // tickMetering moves the meters on. The event loop calls it every frame // while m.ticking is set. func (m *mixer) tickMetering() command { - if !m.setLevels(m.meterSnapshot(), time.Now()) { + if !m.readLevels() { m.ticking = false return m.waitMeter() } return nil } +// readLevels passes the latest levels to the hide rules and, if the meters +// show, updates them, reporting whether any is still moving. If the meters +// don't show, only hide rules listen: nothing moves, and the levels shown go. +func (m *mixer) readLevels() (moving bool) { + snap, now := m.meterSnapshot(), time.Now() + m.hear(snap, now) + if m.metersOff() { + m.clearLevels() + return false + } + return m.setLevels(snap, now) +} + +// clearLevels forgets the levels shown, so the meters show none, and asks +// for a redraw if there were any. +func (m *mixer) clearLevels() { + if len(m.fill) == 0 && len(m.dot) == 0 { + return + } + m.fill, m.fillStart, m.dot, m.dotHold = nil, nil, nil, nil + m.redraw = true +} + // setLevels updates the fill and peak positions at now and reports whether // any meter is still moving. func (m *mixer) setLevels(snap *pulse.Snapshot, now time.Time) (moving bool) { @@ -309,6 +341,9 @@ func (m *mixer) setLevels(snap *pulse.Snapshot, now time.Time) (moving bool) { // meterNode returns the node that raw levels for id belong to, or nil if // they are not shown. func (m *mixer) meterNode(id uint32, raw []float64) *pw.Node { + if m.unshown[id] { + return nil + } for i := range m.snap.Nodes { if n := &m.snap.Nodes[i]; n.ID == id && len(n.Channels) > 0 { if len(raw) != len(n.Channels) { @@ -395,7 +430,7 @@ func channelLevel(levels []float64, ch int) float64 { func (m *mixer) toggleMeterAlways() command { switch m.opts.meters { case metersOff: - return notify("Meters are off (-meter.disable)") + return notify("Meters are off (-meter.enable=false)") case metersAlways: m.opts.meters = metersFocused return notify("Meters only while the terminal is focused") @@ -405,8 +440,8 @@ func (m *mixer) toggleMeterAlways() command { } func (m *mixer) toggleMeters() command { - if m.meter == nil { - return notify("Meters are off (-meter.disable)") + if m.meter == nil || m.metersDisabled() { + return notify("Meters are off (-meter.enable=false)") } m.metersHidden = !m.metersHidden if m.metersHidden { @@ -416,7 +451,7 @@ func (m *mixer) toggleMeters() command { } func (m *mixer) look() meterLook { - if m.metersHidden || m.meter == nil { + if m.metersHidden || m.meter == nil || m.metersDisabled() { return meterOff } return m.opts.meterLook diff --git a/internal/pipmix/meters_test.go b/internal/pipmix/meters_test.go index f48679f..dbc2dae 100644 --- a/internal/pipmix/meters_test.go +++ b/internal/pipmix/meters_test.go @@ -313,6 +313,29 @@ func TestMeterWaitOnce(t *testing.T) { } } +func TestMeterBlurClearsLevels(t *testing.T) { + for _, ticking := range []bool{false, true} { + m := testMixer() + m.snap = meterSnapshot() + m.refocus() + it := m.items(tabPlayback)[0] + snap := &pulse.Snapshot{Averages: map[uint32][]float64{it.id: {0.5, 0.5}}} + m.setLevels(snap, time.Now()) + m.setLevels(snap, time.Now().Add(time.Second)) // faded in + if m.level(it, -1) == 0 { + t.Fatal("no level to clear") + } + m.ticking, m.redraw = ticking, false + m.update(tui.BlurEvent{}) + if ticking { + m.tickMetering() + } + if l := m.level(it, -1); l != 0 || !m.redraw || m.ticking { + t.Errorf("ticking %v, after blur: level %v, redraw %v, ticking %v; want 0, true, false", ticking, l, m.redraw, m.ticking) + } + } +} + func TestRecordingMeterTarget(t *testing.T) { s := &pw.Snapshot{Nodes: []pw.Node{ {ID: 1, Class: pw.Source, Name: "mic", Channels: stereo(1)}, diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index e319285..0e6c771 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -116,6 +116,7 @@ type mixer struct { mediaPlayers map[uint32]mpris.Player meter *pulse.Meter watched map[uint32]pulse.Target + unshown map[uint32]bool // nodes watched only for silent rules, with no meter on screen fill map[uint32][]float64 fillStart map[uint32]time.Time dot map[uint32][]float64 @@ -158,9 +159,6 @@ type mixer struct { } func newMixer(c *pw.Client, media *mpris.Watcher, meter *pulse.Meter, quitKeys section, opts options) mixer { - if opts.meters == metersOff { - meter = nil - } return mixer{ client: c, snap: c.Snapshot(), media: media, meter: meter, quitKeys: quitKeys, opts: opts, tab: opts.tab, meterMode: opts.meterMode, smoothing: opts.smoothing, diff --git a/internal/pipmix/options.go b/internal/pipmix/options.go index b465dc8..1326b5c 100644 --- a/internal/pipmix/options.go +++ b/internal/pipmix/options.go @@ -98,7 +98,7 @@ func addFlags(fs *flag.FlagSet) *flagValues { jackEnable: o.jack, } fs.String("config", defaultConfigPath(), "read config from `file`") - fs.BoolVar(&v.meterEnable, "meter.enable", v.meterEnable, "level meters and pipewire-pulse connection") + fs.BoolVar(&v.meterEnable, "meter.enable", v.meterEnable, "draw level meters; if false, pipewire-pulse is only used for hide rules with when = \"silent\"") fs.BoolVar(&v.meterAlways, "meter.always", v.meterAlways, "meter while the terminal isn't focused too") fs.IntVar(&v.meterRate, "meter.rate", v.meterRate, "peaks a second per meter, 1 to 200; above ~46 PipeWire may shorten its quantum for all audio") fs.Var(&choice[meterMode]{&v.meterMode, meterModeFlags}, "meter.mode", "meter `mode`: both (the average, and a cell at the peak), average, or peak") diff --git a/internal/pipmix/options_test.go b/internal/pipmix/options_test.go index f675663..378eb53 100644 --- a/internal/pipmix/options_test.go +++ b/internal/pipmix/options_test.go @@ -82,9 +82,19 @@ func TestMetersAlways(t *testing.T) { t.Error("A back to always: no targets while not focused") } + // -meter.enable=false: no meter is drawn or metered, focused or not, and + // the keys that turn meters on leave them off. o.meters = metersOff - if m := newMixer(pw.NewClient(nil), nil, pulse.NewMeter(nil, 0), quitKeys(), o); m.meter != nil { - t.Error("-meter.enable=false: the mixer has a meter") + m = newMixer(pw.NewClient(nil), nil, pulse.NewMeter(nil, 0), quitKeys(), o) + m.snap = meterSnapshot() + m.setSize(60, 20) + m.handleKey("a") + m.handleKey("A") + if got := m.meterTargets(); len(got) != 0 { + t.Errorf("-meter.enable=false: targets %v, want none", targetKeys(got)) + } + if got := m.look(); got != meterOff { + t.Errorf("-meter.enable=false: look %v, want meterOff", got) } } diff --git a/internal/pipmix/pipmix.go b/internal/pipmix/pipmix.go index e063965..3e8709b 100644 --- a/internal/pipmix/pipmix.go +++ b/internal/pipmix/pipmix.go @@ -75,16 +75,14 @@ func Run(args []string) error { go media.Run(ctx) } - var meter *pulse.Meter - if opts.meters != metersOff { - meter = pulse.NewMeter(clientLog, opts.meterRate) - go meter.Run(ctx) - } + // The meter always runs, also with -meter.enable=false, for the hide + // rules that listen to levels. It connects to pipewire-pulse only while + // it has a node to measure. + meter := pulse.NewMeter(clientLog, opts.meterRate) + go meter.Run(ctx) client := pw.NewClient(clientLog) - if meter != nil { - meter.JACKReady = client.JackMeterReady - } + meter.JACKReady = client.JackMeterReady go client.Run(ctx) if debug.dump { return dump(ctx, os.Stdout, &dumpLog, fs, opts, hide, client, media, meter)