diff --git a/internal/pipmix/dump.go b/internal/pipmix/dump.go index dcce269..3ec13ec 100644 --- a/internal/pipmix/dump.go +++ b/internal/pipmix/dump.go @@ -154,7 +154,11 @@ func dumpNodes(w io.Writer, s *pw.Snapshot, shown map[uint32]bool, opts options) fmt.Fprintln(w, " hidden: duplicates a multi-channel stream") } for _, ch := range n.Channels { - fmt.Fprintf(w, " %-4s %3.0f%%\n", ch.Name, ch.Volume*100) + if n.JACK { + fmt.Fprintf(w, " %s\n", ch.Name) + } else { + fmt.Fprintf(w, " %-4s %3.0f%%\n", ch.Name, ch.Volume*100) + } } for i, r := range n.Routes { mark := " " diff --git a/internal/pipmix/meters.go b/internal/pipmix/meters.go index bf6c99a..b4c6896 100644 --- a/internal/pipmix/meters.go +++ b/internal/pipmix/meters.go @@ -51,8 +51,10 @@ const ( var meterLookFlags = []string{"solid", "shade", "dot"} -type meterMsg struct{} -type meterTickMsg struct{} +type ( + meterMsg struct{} + meterTickMsg struct{} +) func (m *mixer) waitMeter() tea.Cmd { if m.meter == nil { @@ -93,7 +95,7 @@ func (m *mixer) meterTargets() map[uint32]pulse.Target { } func meterTarget(n *pw.Node) (pulse.Target, bool) { - if n == nil || n.JACK || len(n.Channels) == 0 { + if n == nil || len(n.Channels) == 0 { return pulse.Target{}, false } var names []string @@ -101,12 +103,16 @@ func meterTarget(n *pw.Node) (pulse.Target, bool) { names = append(names, c.Name) } t := pulse.Target{Name: n.Name, Channels: names} - switch n.Class { - case pw.Sink: + switch { + case n.JACK && n.Class == pw.Playback: + t.Kind, t.Serial, t.Name = pulse.JACK, n.ID, "" + case n.JACK: + return pulse.Target{}, false + case n.Class == pw.Sink: t.Kind = pulse.Sink - case pw.Source: + case n.Class == pw.Source: t.Kind = pulse.Source - case pw.Playback: + case n.Class == pw.Playback: serial, err := strconv.ParseUint(n.Props["object.serial"], 10, 32) if err != nil { return pulse.Target{}, false @@ -222,7 +228,9 @@ func (m *mixer) setLevels(snap *pulse.Snapshot, now time.Time) (moving bool) { func (m *mixer) shown(raw map[uint32][]float64) map[uint32][]float64 { nodes := make(map[uint32]*pw.Node) for i := range m.snap.Nodes { - nodes[m.snap.Nodes[i].ID] = &m.snap.Nodes[i] + if len(m.snap.Nodes[i].Channels) > 0 { + nodes[m.snap.Nodes[i].ID] = &m.snap.Nodes[i] + } } shown := make(map[uint32][]float64) for id, levels := range raw { diff --git a/internal/pipmix/meters_test.go b/internal/pipmix/meters_test.go index c91ea7a..b0d910d 100644 --- a/internal/pipmix/meters_test.go +++ b/internal/pipmix/meters_test.go @@ -21,7 +21,8 @@ func meterSnapshot() *pw.Snapshot { } 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}, + 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.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}}}, ) return s @@ -42,13 +43,23 @@ func TestMeterTargets(t *testing.T) { m.refocus() got := m.meterTargets() - if keys := targetKeys(got); !slices.Equal(keys, []uint32{10, 11, 12}) { - t.Fatalf("playback targets %v, want 10 11 12 (no JACK client)", keys) + if keys := targetKeys(got); !slices.Equal(keys, []uint32{10, 11, 12, 41}) { + t.Fatalf("playback targets %v, want 10 11 12 41", keys) } want := pulse.Target{Kind: pulse.Stream, Serial: 101, Channels: []string{"FL", "FR"}} if !got[11].Equal(want) { t.Errorf("target of 11 = %+v, want %+v", got[11], want) } + 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) + } + + m.opts.jack = false + if keys := targetKeys(m.meterTargets()); !slices.Equal(keys, []uint32{10, 11, 12}) { + t.Fatalf("playback targets without jack %v, want 10 11 12", keys) + } + m.opts.jack = true m.setTab(tabOutputs) want = pulse.Target{Kind: pulse.Sink, Name: "sink", Channels: []string{"FL", "FR"}} @@ -118,10 +129,11 @@ func TestLevels(t *testing.T) { 10: {0.125, 1}, // a stream: after its volume already 12: {1, 1}, // muted 20: {0.125, 0.125}, // a sink at 100%: before its volume + 41: {0.125, 0.512}, // a duplex JACK client: uses its playback channels 99: {1}, // gone 11: {1}, // channels don't match }), now) - for id, want := range map[uint32][]float64{10: {0.5, 1}, 12: {0, 0}, 20: {0.5, 0.5}, 99: nil, 11: nil} { + for id, want := range map[uint32][]float64{10: {0.5, 1}, 12: {0, 0}, 20: {0.5, 0.5}, 41: {0.5, 0.8}, 99: nil, 11: nil} { if !near(m.fill[id], want) || !near(m.dot[id], want) { t.Errorf("node %d: fill %v, peak %v; want %v", id, m.fill[id], m.dot[id], want) } @@ -226,6 +238,20 @@ func TestBarLevel(t *testing.T) { t.Errorf("bar(%v, %v, %v, 16, %v, look %d) = %q, want %q", tc.v, tc.level, tc.peak, tc.muted, tc.look, got, tc.want) } } + for _, tc := range []struct { + level, peak float64 + look meterLook + want string + }{ + {0, 0, meterSolid, "░░░░░░░░░░░░░░░░"}, + {0.3, 0.7, meterSolid, "███░░░█░░░░░░░░░"}, + {0.5, 0, meterDot, "░░░░█░░░░░░░░░░░"}, + {0.5, 0.7, meterOff, "░░░░░░░░░░░░░░░░"}, + } { + if got := ansi.Strip(meterBar(tc.level, tc.peak, 16, 1.5, tc.look)); got != tc.want { + t.Errorf("meterBar(%v, %v, 16, look %d) = %q, want %q", tc.level, tc.peak, tc.look, got, tc.want) + } + } } func TestMeterFadeIn(t *testing.T) { diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index 18f0e40..4f8b1ba 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -151,8 +151,10 @@ func newMixer(c *pw.Client, media *mpris.Watcher, meter *pulse.Meter, quitKeys s } } -type snapshotMsg struct{} -type mediaMsg struct{} +type ( + snapshotMsg struct{} + mediaMsg struct{} +) type noticeMsg struct { text string diff --git a/internal/pipmix/mixer_test.go b/internal/pipmix/mixer_test.go index 76e7c3b..3b94f86 100644 --- a/internal/pipmix/mixer_test.go +++ b/internal/pipmix/mixer_test.go @@ -26,8 +26,10 @@ func testSnapshot() *pw.Snapshot { {ID: 10, Class: pw.Playback, Name: "a", Title: "Player A", Channels: stereo(0.5)}, {ID: 11, Class: pw.Playback, Name: "b", Title: "Player B", Channels: stereo(1)}, {ID: 12, Class: pw.Playback, Name: "c", Title: "Player C", Channels: stereo(1.2), Mute: true}, - {ID: 20, Class: pw.Sink, Name: "sink", Title: "Speakers", Channels: stereo(1), Default: true, - Routes: []pw.Route{{Index: 0, Description: "Speakers"}, {Index: 1, Description: "Headphones"}}, Route: 1}, + { + ID: 20, Class: pw.Sink, Name: "sink", Title: "Speakers", Channels: stereo(1), Default: true, + Routes: []pw.Route{{Index: 0, Description: "Speakers"}, {Index: 1, Description: "Headphones"}}, Route: 1, + }, }, Cards: []pw.Card{{ID: 30, Title: "Card", Profile: 0, Profiles: []pw.Profile{ {Index: 0, Description: "Duplex"}, {Index: 1, Description: "Off"}, @@ -419,8 +421,10 @@ func TestCardsSpaced(t *testing.T) { func TestTitleColumns(t *testing.T) { m := testMixer() s := testSnapshot() - s.Nodes = append(s.Nodes, pw.Node{ID: 21, Class: pw.Sink, Name: "hdmi", Title: "HDMI Output With A Long Name", Channels: stereo(1), - Routes: []pw.Route{{Index: 0, Description: "HDMI"}}, Route: 0, Mute: true}) + s.Nodes = append(s.Nodes, pw.Node{ + ID: 21, Class: pw.Sink, Name: "hdmi", Title: "HDMI Output With A Long Name", Channels: stereo(1), + Routes: []pw.Route{{Index: 0, Description: "HDMI"}}, Route: 0, Mute: true, + }) m.snap = s m.handleKey("4") lines := strings.Split(ansi.Strip(m.view()), "\n") @@ -513,8 +517,12 @@ func TestTypeStrip(t *testing.T) { id uint32 strip string }{ - {tabDefault, 20, strip(pw.Sink)}, {tabDefault, 10, strip(pw.Playback)}, {tabPlayback, 10, strip(pw.Playback)}, - {tabRecording, 40, strip(pw.Recording)}, {tabOutputs, 20, strip(pw.Sink)}, {tabInputs, 22, strip(pw.Source)}, + {tabDefault, 20, strip(pw.Sink)}, + {tabDefault, 10, strip(pw.Playback)}, + {tabPlayback, 10, strip(pw.Playback)}, + {tabRecording, 40, strip(pw.Recording)}, + {tabOutputs, 20, strip(pw.Sink)}, + {tabInputs, 22, strip(pw.Source)}, {tabCards, 30, card}, } { m.setTab(tc.tab) @@ -550,7 +558,10 @@ func TestTypeStrip(t *testing.T) { func TestJACKClient(t *testing.T) { m := testMixer() - jack := pw.Node{ID: 5, Class: pw.Playback, Name: "dtime", Title: "dtime", JACK: true} + jack := pw.Node{ + ID: 5, Class: pw.Playback, Name: "dtime", Title: "dtime", JACK: true, + Channels: []pw.Channel{{Name: "out_1", Volume: 1}, {Name: "out_2", Volume: 1}}, + } m.snap.Nodes = append([]pw.Node{jack}, m.snap.Nodes...) m.refocus() for _, tb := range []tab{tabDefault, tabPlayback} { @@ -564,9 +575,16 @@ func TestJACKClient(t *testing.T) { t.Fatalf("G: focus %d, want 5", id) } view := ansi.Strip(m.view()) - if !strings.Contains(view, strings.Repeat(faderEmpty, m.barWidth())) || !strings.Contains(view, symSpeaker) || !strings.Contains(view, "JACK: dtime") { + if !strings.Contains(view, strings.Repeat(faderEmpty, m.barWidth())) || !strings.Contains(view, symSpeaker) || !strings.Contains(view, "JACK: dtime") || !strings.Contains(view, "2ch") { t.Errorf("view:\n%s", view) } + // Space unfolds individual JACK output ports to inspect their levels. + m.handleKey("space") + view = ansi.Strip(m.view()) + if !strings.Contains(view, "┌ out_1") || !strings.Contains(view, "└ out_2") { + t.Errorf("unfolded JACK view:\n%s", view) + } + m.handleKey("space") for _, key := range []string{"l", "m"} { cmd := m.handleKey(key) if cmd == nil { @@ -576,12 +594,14 @@ func TestJACKClient(t *testing.T) { t.Errorf("%s: %+v, want a JACK notice", key, msg) } } - cmd := m.click(tea.Mouse{X: muteX, Y: 7, Button: tea.MouseLeft}) - if cmd == nil { - t.Fatal("click on the speaker: no notice") - } - if msg, ok := cmd().(noticeMsg); !ok || !strings.Contains(msg.text, "JACK client") { - t.Errorf("click on the speaker: %+v, want a JACK notice", msg) + for _, pt := range []struct{ x, y int }{{muteX, 7}, {barX + 2, 8}} { + cmd := m.click(tea.Mouse{X: pt.x, Y: pt.y, Button: tea.MouseLeft}) + if cmd == nil { + t.Fatalf("click at (%d,%d): no notice", pt.x, pt.y) + } + if msg, ok := cmd().(noticeMsg); !ok || !strings.Contains(msg.text, "JACK client") { + t.Errorf("click at (%d,%d): %+v, want a JACK notice", pt.x, pt.y, msg) + } } } diff --git a/internal/pipmix/mouse.go b/internal/pipmix/mouse.go index ca29ecc..d2d1f6f 100644 --- a/internal/pipmix/mouse.go +++ b/internal/pipmix/mouse.go @@ -60,6 +60,9 @@ func (m *mixer) click(mouse tea.Mouse) tea.Cmd { if mouse.X < barX-2 || mouse.X >= barX+m.barWidth() { return nil } + if it.node.JACK { + return m.setVolume100() + } channel := -1 if m.isUnlocked(it) { channel = line.channel @@ -91,6 +94,9 @@ func (m *mixer) click(mouse tea.Mouse) tea.Cmd { if mouse.X < barX-2 || mouse.X >= barX+m.barWidth() { return nil } + if it.node.JACK { + return m.setVolume100() + } channel := -1 if m.isUnlocked(it) { channel = line.channel diff --git a/internal/pipmix/pipmix.go b/internal/pipmix/pipmix.go index 13f4b74..7e8415e 100644 --- a/internal/pipmix/pipmix.go +++ b/internal/pipmix/pipmix.go @@ -54,10 +54,9 @@ func Run(args []string) error { go http.Serve(ln, nil) } - client := pw.NewClient(clientLog) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - go client.Run(ctx) + var media *mpris.Watcher if opts.titles { media = mpris.NewWatcher(clientLog) @@ -69,6 +68,12 @@ func Run(args []string) error { meter = pulse.NewMeter(clientLog, opts.meterRate) go meter.Run(ctx) } + + client := pw.NewClient(clientLog) + if meter != nil { + meter.JACKReady = client.JackMeterReady + } + go client.Run(ctx) if debug.dump { return dump(ctx, os.Stdout, &dumpLog, fs, opts, client, media, meter) } diff --git a/internal/pipmix/view.go b/internal/pipmix/view.go index e9cd7dc..f921845 100644 --- a/internal/pipmix/view.go +++ b/internal/pipmix/view.go @@ -518,15 +518,18 @@ func (m *mixer) channelLine(it item, i int, focused bool) string { var c pw.Channel var nameStr string - if i < 0 { + if i < 0 && len(n.Channels) > 1 { c = n.Channels[0] nameStr = foldedName(n.Channels) } else { - c = n.Channels[i] - nameStr = c.Name + c = n.Channels[max(i, 0)] + nameStr = ansi.Truncate(c.Name, labelWidth, "…") + } + name := strings.Repeat(" ", max(0, labelWidth-ansi.StringWidth(nameStr))) + nameStr + vol := " " + if !n.JACK { + vol = fmt.Sprintf("%3d", percent(c.Volume)) } - name := fmt.Sprintf("%*s", labelWidth, nameStr) - vol := fmt.Sprintf("%3d", percent(c.Volume)) if chanFocused { name = boldStyle.Render(name) vol = boldStyle.Render(vol) @@ -575,6 +578,9 @@ func (m *mixer) channelLine(it item, i int, focused bool) string { } label := prefix + name + " " + vol + " " + if n.JACK { + return label + meterBar(m.level(it, i), m.peak(it, i), m.barWidth(), m.opts.limit, m.look()) + } return label + bar(c.Volume, m.level(it, i), m.peak(it, i), m.barWidth(), m.opts.limit, n.Mute, m.look()) } @@ -588,6 +594,59 @@ func fixedBar(width int) string { return strings.Repeat(" ", barX-contentX) + dimStyle.Render(strings.Repeat(faderEmpty, max(width, 0))) } +// meterBar renders a level meter of width cells without a volume fader. +func meterBar(level, peak float64, width int, limit float64, look meterLook) string { + if width <= 0 { + return "" + } + lit, pk := 0, 0 + if look != meterOff { + if level > 0 { + lit = knobCell(level, limit, width) + } + if peak > 0 { + pk = knobCell(peak, limit, width) + } + } + if lit == 0 && pk == 0 { + return dimStyle.Render(strings.Repeat(faderEmpty, width)) + } + hundred := knobCell(1, limit, width) + styles := [...]lipgloss.Style{barFullStyle, barOverStyle, brightFull, brightOver, dimStyle} + type cell struct { + glyph string + style int + } + cells := make([]cell, width) + for i := range cells { + over := 0 + if i > hundred { + over = 1 + } + c := cell{faderEmpty, 4} + switch { + case i < lit && (look == meterSolid || look == meterShade): + c = cell{faderKnob, over} + case i == lit-1 && look == meterDot: + c = cell{faderKnob, 2 + over} + } + if i == pk-1 { + c = cell{faderKnob, 2 + over} + } + cells[i] = c + } + var b strings.Builder + for i := 0; i < len(cells); { + j := i + 1 + for j < len(cells) && cells[j] == cells[i] { + j++ + } + b.WriteString(styles[cells[i].style].Render(strings.Repeat(cells[i].glyph, j-i))) + i = j + } + return b.String() +} + var ( emptyOverStyle = lipgloss.NewStyle().Foreground(lipgloss.Red).Faint(true) brightFull = lipgloss.NewStyle().Foreground(lipgloss.BrightGreen) diff --git a/internal/pulse/meter.go b/internal/pulse/meter.go index a193b59..9d93f48 100644 --- a/internal/pulse/meter.go +++ b/internal/pulse/meter.go @@ -37,13 +37,14 @@ const ( Sink Kind = iota Source Stream + JACK ) // A Target is a node to measure. type Target struct { Kind Kind Name string // node.name of a Sink or Source - Serial uint32 // object.serial of a Stream + Serial uint32 // object.serial of a Stream, or node ID of a JACK client Channels []string } @@ -53,6 +54,8 @@ func (t Target) String() string { return "sink " + t.Name case Source: return "source " + t.Name + case JACK: + return fmt.Sprintf("jack node %d", t.Serial) } return fmt.Sprintf("stream serial %d", t.Serial) } @@ -67,13 +70,24 @@ type Snapshot struct { Averages map[uint32][]float64 } +var meterInst atomic.Uint32 // distinguishes meter instances within the same process + // A Meter measures the levels of a set of targets. type Meter struct { + // Prefix is the prefix used for naming PipeWire nodes of meter streams. + Prefix string + + // JACKReady is invoked with the meter stream's PipeWire node.name once a + // JACK record stream is created, so its non-JACK links can be removed + // before peaks are read. + JACKReady func(ctx context.Context, name string) + log *log.Logger rate int want chan map[uint32]Target snap atomic.Pointer[Snapshot] updated chan struct{} + seq atomic.Uint32 // ensures unique node.name per stream across concurrent workers } // NewMeter returns a meter whose streams send rate peaks per second @@ -85,7 +99,9 @@ func NewMeter(logger *log.Logger, rate int) *Meter { if rate <= 0 { rate = DefaultRate } + inst := meterInst.Add(1) m := &Meter{ + Prefix: fmt.Sprintf("pipmix.meter.%d.%d.", os.Getpid(), inst), log: logger, rate: rate, want: make(chan map[uint32]Target, 1), @@ -281,10 +297,21 @@ func (m *Meter) stream(ctx context.Context, t Target, send func(peaks, avgs []fl stop := context.AfterFunc(ctx, func() { nc.Close() }) defer stop() + var nodeName string + switch t.Kind { + case JACK: + nodeName = fmt.Sprintf("%sjack.%d.%d", m.Prefix, t.Serial, m.seq.Add(1)) + case Sink: + nodeName = fmt.Sprintf("%ssink.%d", m.Prefix, m.seq.Add(1)) + case Source: + nodeName = fmt.Sprintf("%ssource.%d", m.Prefix, m.seq.Add(1)) + case Stream: + nodeName = fmt.Sprintf("%sstream.%d.%d", m.Prefix, t.Serial, m.seq.Add(1)) + } nc.SetReadDeadline(time.Now().Add(createWait)) m.log.Printf("pulse: %v: creating a record stream; the reply waits for the node to run", t) asked := time.Now() - index, channels, err := c.create(t, m.rate) + index, channels, err := c.create(t, m.rate, nodeName) var ne net.Error if errors.As(err, &ne) && ne.Timeout() { return false, errIdle @@ -292,6 +319,9 @@ func (m *Meter) stream(ctx context.Context, t Target, send func(peaks, avgs []fl if err != nil { return false, err } + if t.Kind == JACK && m.JACKReady != nil { + m.JACKReady(ctx, nodeName) + } nc.SetDeadline(time.Time{}) m.log.Printf("pulse: %v: record stream %d created after %v", t, index, time.Since(asked).Round(time.Millisecond)) @@ -300,9 +330,14 @@ func (m *Meter) stream(ctx context.Context, t Target, send func(peaks, avgs []fl alpha := 1 - math.Exp(-1/(float64(m.rate)*averageTime.Seconds())) var last, lastAvgs []float64 silent, since := true, time.Now() + skip := t.Kind == JACK + if skip { + nc.SetReadDeadline(time.Now().Add(max(stale, 3*m.Interval()))) + } for { p, err := readPacket(nc) if errors.As(err, &ne) && ne.Timeout() { + skip = false nc.SetReadDeadline(time.Time{}) silent, since = true, time.Now() m.log.Printf("pulse: %v: no peaks for %v; showing 0 until they come", t, max(stale, 3*m.Interval())) @@ -328,6 +363,11 @@ func (m *Meter) stream(ctx context.Context, t Target, send func(peaks, avgs []fl if len(p.data) < frame { continue } + if skip { + skip = false + nc.SetReadDeadline(time.Now().Add(max(stale, 3*m.Interval()))) + continue + } // Usually one frame; if more came, each channel's largest. peaks := make([]float64, channels) for f := 0; f+frame <= len(p.data); f += frame { @@ -460,7 +500,7 @@ func (c *conn) handshake() error { // create opens a peak-detect record stream for t and returns its index and // channel count. -func (c *conn) create(t Target, rate int) (uint32, int, error) { +func (c *conn) create(t Target, rate int, nodeName string) (uint32, int, error) { positions := []byte{0} if len(t.Channels) > 0 { positions = positions[:0] @@ -478,6 +518,8 @@ func (c *conn) create(t Target, rate int) (uint32, int, error) { b.string(t.Name + ".monitor") case Source: b.string(t.Name) + case JACK: + b.string("@DEFAULT_MONITOR@") default: b.null() } @@ -491,7 +533,11 @@ func (c *conn) create(t Target, rate int) (uint32, int, error) { } b.bool(true) // peak_detect b.bool(true) // adjust_latency - b.proplist([][2]string{{"media.name", "Peak meter"}}) + props := [][2]string{{"media.name", "Peak meter"}} + if nodeName != "" { + props = append(props, [2]string{"node.name", nodeName}) + } + b.proplist(props) direct := uint32(invalidIndex) if t.Kind == Stream { direct = t.Serial @@ -507,9 +553,11 @@ func (c *conn) create(t Target, rate int) (uint32, int, error) { } b.cvolume(volumes) // muted, volume_set, muted_set, relative_volume, passthrough - for range 5 { - b.bool(false) - } + b.bool(false) // muted + b.bool(true) // volume_set + b.bool(true) // muted_set + b.bool(false) // relative_volume + b.bool(false) // passthrough if err := writePacket(c.c, b.b); err != nil { return 0, 0, err } diff --git a/internal/pulse/meter_test.go b/internal/pulse/meter_test.go index 99eed55..fadb9c0 100644 --- a/internal/pulse/meter_test.go +++ b/internal/pulse/meter_test.go @@ -19,9 +19,16 @@ func TestPosition(t *testing.T) { i int want byte }{ - {"MONO", 0, 0}, {"FL", 0, 1}, {"FR", 1, 2}, {"LFE", 3, 7}, {"SR", 5, 11}, - {"AUX0", 0, 12}, {"AUX5", 0, 17}, {"AUX31", 0, 43}, - {"UNKNOWN", 2, 14}, {"AUX99", 1, 13}, + {"MONO", 0, 0}, + {"FL", 0, 1}, + {"FR", 1, 2}, + {"LFE", 3, 7}, + {"SR", 5, 11}, + {"AUX0", 0, 12}, + {"AUX5", 0, 17}, + {"AUX31", 0, 43}, + {"UNKNOWN", 2, 14}, + {"AUX99", 1, 13}, } { if got := position(tc.name, tc.i); got != tc.want { t.Errorf("position(%q, %d) = %d, want %d", tc.name, tc.i, got, tc.want) @@ -401,3 +408,43 @@ func TestMeterAverage(t *testing.T) { t.Errorf("peaks %v, want [0.5]", p) } } + +func TestMeterJACK(t *testing.T) { + s := newFakeServer(t) + m := NewMeter(nil, 0) + m2 := NewMeter(nil, 0) + if m2.Prefix == m.Prefix { + t.Errorf("m2 Prefix %q == m Prefix %q", m2.Prefix, m.Prefix) + } + m.Prefix = "pipmix.meter." + var readyName atomic.Value + m.JACKReady = func(_ context.Context, name string) { + readyName.Store(name) + } + ctx := t.Context() + go m.Run(ctx) + + m.Watch(map[uint32]Target{ + 5: {Kind: JACK, Serial: 137, Channels: []string{"out_1", "out_2"}}, + }) + c := s.conn() + if c.source != "@DEFAULT_MONITOR@" || c.channels != 2 { + t.Fatalf("JACK stream records %q, %d channels; want @DEFAULT_MONITOR@, 2", c.source, c.channels) + } + for range 100 { + if readyName.Load() != nil { + break + } + time.Sleep(5 * time.Millisecond) + } + if got, _ := readyName.Load().(string); got != "pipmix.meter.jack.137.1" { + t.Fatalf("readyName = %q, want pipmix.meter.jack.137.1", got) + } + // First frame after flush is skipped; the next frame is published. + c.peaks(t, 0.9, 0.9) + time.Sleep(5 * time.Millisecond) + c.peaks(t, 0.25, 0.75) + waitLevels(t, m, func(l map[uint32][]float64) bool { + return slices.Equal(l[5], []float64{0.25, 0.75}) + }) +} diff --git a/internal/pw/client.go b/internal/pw/client.go index 1747efa..2dafe09 100644 --- a/internal/pw/client.go +++ b/internal/pw/client.go @@ -5,6 +5,7 @@ import ( "context" "io" "log" + "os" "sync/atomic" "time" ) @@ -16,6 +17,10 @@ const ( // A Client is a connection to PipeWire that reconnects when lost. type Client struct { + // PID is the process ID used to identify this instance's meter streams. + // Defaults to os.Getpid() if zero. + PID int + log *log.Logger cmds chan func(*session) snap atomic.Pointer[Snapshot] @@ -28,6 +33,7 @@ func NewClient(logger *log.Logger) *Client { logger = log.New(io.Discard, "", 0) } c := &Client{ + PID: os.Getpid(), log: logger, cmds: make(chan func(*session), 256), updated: make(chan struct{}, 1), @@ -98,6 +104,18 @@ func (c *Client) SetDefault(node uint32) { c.do(func(s *session) { s.setDefault(node) }) } +// JackMeterReady unlinks a JACK meter stream from its initial target once +// pipewire-pulse has created the stream, leaving only the JACK node's links. +func (c *Client) JackMeterReady(ctx context.Context, name string) { + done := make(chan struct{}) + c.do(func(s *session) { s.jackMeterReady(name, done) }) + select { + case <-done: + case <-ctx.Done(): + case <-time.After(time.Second): + } +} + // Run connects and keeps the connection up until ctx is done. func (c *Client) Run(ctx context.Context) { backoff := minBackoff @@ -153,7 +171,7 @@ func (c *Client) session(ctx context.Context) error { } }() - s := newSession(conn, c.log) + s := newSession(conn, c.log, c.PID) s.start() var expiry *time.Timer for s.err == nil { diff --git a/internal/pw/live_test.go b/internal/pw/live_test.go index b733503..c90b67b 100644 --- a/internal/pw/live_test.go +++ b/internal/pw/live_test.go @@ -2,11 +2,14 @@ package pw import ( "context" + "fmt" "log" "math" "os" "os/exec" "path/filepath" + "strconv" + "strings" "syscall" "testing" "time" @@ -36,6 +39,8 @@ context.objects = [ media.class = Stream/Output/Audio audio.position = [ FL FR ] } } { factory = spa-node-factory args = { factory.name = support.null-audio-sink node.name = test-jack node.description = "Test JACK" client.api = jack media.type = Audio audio.position = [ MONO ] } } + { factory = adapter args = { factory.name = support.null-audio-sink node.name = pipmix.meter.%d.sink.1 + node.description = "Test Meter Sink" media.class = Stream/Input/Audio audio.position = [ FL FR ] } } ] ` @@ -52,7 +57,7 @@ func startPipeWire(t *testing.T) (stop func()) { } dir := t.TempDir() conf := filepath.Join(dir, "test.conf") - if err := os.WriteFile(conf, []byte(testConf), 0o600); err != nil { + if err := os.WriteFile(conf, []byte(fmt.Sprintf(testConf, os.Getpid())), 0o600); err != nil { t.Fatal(err) } t.Setenv("PIPEWIRE_RUNTIME_DIR", dir) @@ -179,6 +184,63 @@ func TestLive(t *testing.T) { n := findNode(s, "test-sink") return n != nil && n.Default }) + + meterNodeName := fmt.Sprintf("pipmix.meter.%d.sink.1", os.Getpid()) + if findNode(s, meterNodeName) != nil { + t.Errorf("meter node should not be in snapshot") + } + var meterGlobalID uint32 + meterChecked := make(chan bool, 1) + c.do(func(sess *session) { + for id := range sess.meters { + meterGlobalID = id + } + meterChecked <- len(sess.meters) == 1 + }) + select { + case ok := <-meterChecked: + if !ok { + t.Errorf("expected 1 meter node in session") + } + case <-time.After(2 * time.Second): + t.Fatalf("timed out waiting for session command") + } + + // External tool alters meter volume / mute; pipmix resets them to 100% unmuted. + cmd := exec.Command("pw-cli", "s", strconv.FormatUint(uint64(meterGlobalID), 10), "Props", `{ "channelVolumes": [ 0.3, 0.3 ], "mute": true }`) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("pw-cli set-param failed: %v: %s", err, out) + } + + // Verify the meter node is reset to volume 1.0 and unmuted. + deadline := time.After(3 * time.Second) + for { + out, err := exec.Command("pw-cli", "e", strconv.FormatUint(uint64(meterGlobalID), 10), "Props").CombinedOutput() + sout := string(out) + if err == nil && strings.Contains(sout, "Bool false") && (strings.Contains(sout, "1.000000") || strings.Contains(sout, "1,000000")) { + break + } + select { + case <-deadline: + t.Fatalf("timed out waiting for meter node volume reset; last props: %s", out) + case <-time.After(50 * time.Millisecond): + } + } + + // A client from another instance (with another PID) hides foreign meter + // streams from its snapshot, and does not track or enforce volume on them. + cOther := NewClient(log.New(testWriter{t}, "other: ", 0)) + cOther.PID = 99999 + go cOther.Run(ctx) + sOther := waitFor(t, cOther, "other client", func(s *Snapshot) bool { return findNode(s, "test-sink") != nil }) + if findNode(sOther, meterNodeName) != nil { + t.Errorf("other instance should hide foreign meter node from snapshot") + } + cOther.do(func(sess *session) { + if len(sess.meters) != 0 { + t.Errorf("other instance should not track foreign meter node, got %d", len(sess.meters)) + } + }) } // TestReconnect restarts PipeWire under a connected client. diff --git a/internal/pw/pod.go b/internal/pw/pod.go index b67bdf1..f042e16 100644 --- a/internal/pw/pod.go +++ b/internal/pw/pod.go @@ -433,7 +433,7 @@ func (p *parser) dict() map[string]string { return m } -// paramInfo reads the param list of an Info event, +// paramInfo reads the param list of a Node::info or Device::info event, // Struct(Int n, (Id id, Int flags)*), as a map from id to flags. func (p *parser) paramInfo() map[uint32]uint32 { f := p.fields() diff --git a/internal/pw/proto.go b/internal/pw/proto.go index 9c01d52..ff2b569 100644 --- a/internal/pw/proto.go +++ b/internal/pw/proto.go @@ -5,6 +5,8 @@ import "strconv" // Interface types, as announced by Registry::Global. const ( ifaceNode = "PipeWire:Interface:Node" + ifacePort = "PipeWire:Interface:Port" + ifaceLink = "PipeWire:Interface:Link" ifaceDevice = "PipeWire:Interface:Device" ifaceMetadata = "PipeWire:Interface:Metadata" ifaceClient = "PipeWire:Interface:Client" @@ -15,10 +17,15 @@ const ( versionCore = 4 versionRegistry = 3 versionNode = 3 + versionLink = 3 versionDevice = 3 versionMetadata = 3 ) +// MeterPrefix prefixes the node.name of peak-detect streams created for +// sinks, sources, streams, and JACK clients. +const MeterPrefix = "pipmix.meter." + // Fixed proxy ids. const ( idCore = 0 @@ -27,10 +34,12 @@ const ( // Core methods and events. const ( - coreHello = 1 - coreSync = 2 - corePong = 3 - coreGetRegistry = 5 + coreHello = 1 + coreSync = 2 + corePong = 3 + coreGetRegistry = 5 + coreCreateObject = 6 + coreDestroy = 7 coreEventInfo = 0 coreEventDone = 1 @@ -42,7 +51,8 @@ const ( const clientUpdateProperties = 2 const ( - registryBind = 1 + registryBind = 1 + registryDestroy = 2 registryEventGlobal = 0 registryEventGlobalRemove = 1 @@ -62,7 +72,7 @@ const ( metadataEventProperty = 0 ) -// Info change mask bits. +// Node::info and Device::info change mask bits. const ( nodeChangeProps = 1 << 3 nodeChangeParams = 1 << 4 diff --git a/internal/pw/session.go b/internal/pw/session.go index 5c84132..a353bf9 100644 --- a/internal/pw/session.go +++ b/internal/pw/session.go @@ -11,6 +11,7 @@ import ( "path/filepath" "slices" "strconv" + "strings" "time" ) @@ -56,108 +57,136 @@ const ( kindNode kindDevice kindMetadata + kindLink ) // A proxy is the client side of a bound object. type proxy struct { - id uint32 - kind proxyKind - global uint32 + id uint32 // client-side proxy identifier + kind proxyKind // object type represented by this proxy + global uint32 // PipeWire registry global ID } type node struct { - id, proxy uint32 - class Class - props map[string]string - params map[uint32]uint32 // param id → flags, from the last Info - - // jack marks a JACK client. It has no media class and no volume; its - // ports tell whether it plays, records or both. - jack bool - inPorts, outPorts int32 - - known bool // volumes, channels and mute have been read - volumes []float32 // linear - channels []uint32 - mute bool - - // What the client last set, and until when it wins. - pendingVolumes []float32 - pendingMute *bool - pendingUntil time.Time + id uint32 // PipeWire registry global ID + proxy uint32 // client-side proxy ID + class Class // stream/device media class + props map[string]string // node properties from registry + params map[uint32]uint32 // param ID → flags from last Node::info event + jack bool // true if JACK client without media class + meter bool // true if peak meter stream node + own bool // true if meter node owned by this instance + inPorts int32 // count of input ports + outPorts int32 // count of output ports + known bool // true once volumes, channels, and mute are populated + volumes []float32 // current channel volumes (linear) + channels []uint32 // channel map positions (e.g. FL, FR) + mute bool // true if node is muted + 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 } type device struct { - id, proxy uint32 - props map[string]string - params map[uint32]uint32 - - profiles []Profile // EnumProfile - profile int32 // active profile index, -1 if none - routes []routeInfo - active []activeRoute + id uint32 // PipeWire registry global ID + proxy uint32 // client-side proxy ID + props map[string]string // device properties from registry + params map[uint32]uint32 // param ID → flags from last Device::info event + profiles []Profile // available card profiles from EnumProfile + profile int32 // active profile index, -1 if none + routes []routeInfo // available routes from EnumRoute + active []activeRoute // active card profile routes } // A routeInfo is an EnumRoute entry: a port the device can use. type routeInfo struct { - Route - direction uint32 - devices []int32 // card profile devices it applies to - profiles []int32 // profiles it's available in + Route // embedded public route metadata + direction uint32 // SPA_DIRECTION_INPUT (0) or SPA_DIRECTION_OUTPUT (1) + devices []int32 // card profile devices this route applies to + profiles []int32 // profiles this route is available in } // An activeRoute is a Route entry: the port a card profile device uses. type activeRoute struct { - index, device int32 + index int32 // route index on the device + device int32 // card profile device ID } // An enumReq collects the replies to one EnumParams. type enumReq struct { - seq int32 - proxy, global uint32 - param uint32 - values []pod + seq int32 // sequence number of EnumParams request + proxy uint32 // proxy ID targeted by the request + global uint32 // registry global ID of the object + param uint32 // parameter ID being enumerated + values []pod // collected reply pods +} + +type portInfo struct { + id uint32 // PipeWire registry global ID of the port + node uint32 // node ID this port belongs to + portID int32 // port.id property identifying channel index + name string // port.name property (e.g. "playback_FL") + out bool // true for output ports, false for input +} + +// A jackMeter tracks a pipewire-pulse peak-detect stream for a JACK client. +type jackMeter struct { + target uint32 // target JACK node ID + node uint32 // meter stream's PipeWire node ID (0 until announced) + ready bool // true once pipewire-pulse replied to stream creation + linked int // count of port pairs linked so far + unwanted []uint32 // default monitor link IDs queued for removal + done chan struct{} // channel closed when links are established + syncSeq int32 // sequence number of core sync awaiting completion } // A session is one connection to PipeWire and everything known through it. // All of its methods run on the client's loop goroutine. type session struct { - conn *conn - log *log.Logger - - ids idMap - registry uint32 - proxies map[uint32]*proxy - nodes map[uint32]*node - devices map[uint32]*device - clients map[uint32]map[string]string // global id → client props - meta *proxy // the default metadata, nil if not bound - defaults map[string]string // default metadata key → node name - - seq int32 - enums map[int32]*enumReq // by EnumParams seq - syncs map[int32][]*enumReq // by Sync seq, committed on its Done - - gen, sentGen uint64 // registry generation received, and sent back - - readySeq int32 // the initial Sync - ready bool - dirty bool - err error // the first write error, which ends the session + conn *conn // low-level PipeWire connection + log *log.Logger // logger for protocol diagnostics + ids idMap // allocator for client-side proxy IDs + registry uint32 // proxy ID of the PipeWire registry + 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 + 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 + devices map[uint32]*device // global ID → audio device/card + clients map[uint32]map[string]string // global ID → client properties + meta *proxy // default metadata proxy, nil if not bound + defaults map[string]string // default metadata key → node name + seq int32 // next request sequence number + enums map[int32]*enumReq // active EnumParams requests by sequence number + syncs map[int32][]*enumReq // queued EnumParams commits waiting for core sync + gen uint64 // registry generation received from server + sentGen uint64 // registry generation acknowledged back to server + readySeq int32 // sequence number of initial sync marking session ready + ready bool // true once initial sync completes + dirty bool // true if snapshot needs recomputing + err error // first fatal error ending the session } -func newSession(c *conn, logger *log.Logger) *session { +func newSession(c *conn, logger *log.Logger, pid int) *session { + if pid == 0 { + pid = os.Getpid() + } return &session{ - conn: c, - log: logger, - ids: idMap{next: idClient + 1}, - proxies: make(map[uint32]*proxy), - nodes: make(map[uint32]*node), - devices: make(map[uint32]*device), - clients: make(map[uint32]map[string]string), - defaults: make(map[string]string), - enums: make(map[int32]*enumReq), - syncs: make(map[int32][]*enumReq), + conn: c, + log: logger, + ids: idMap{next: idClient + 1}, + proxies: make(map[uint32]*proxy), + nodes: make(map[uint32]*node), + ports: make(map[uint32]portInfo), + jackMeters: make(map[string]*jackMeter), + meters: make(map[uint32]*node), + meterPrefix: fmt.Sprintf("%s%d.", MeterPrefix, pid), + devices: make(map[uint32]*device), + clients: make(map[uint32]map[string]string), + defaults: make(map[string]string), + enums: make(map[int32]*enumReq), + syncs: make(map[int32][]*enumReq), } } @@ -314,6 +343,12 @@ func (s *session) coreEvent(op uint8, f *parser) error { s.commit(r) } } + for _, jm := range s.jackMeters { + if jm.done != nil && jm.syncSeq == seq { + close(jm.done) + jm.done = nil + } + } if seq == s.readySeq && !s.ready { s.ready = true s.dirty = true @@ -353,9 +388,13 @@ func (s *session) removeProxy(id uint32) { } delete(s.proxies, id) s.ids.release(id) + if p.kind == kindLink { + return + } switch { case p.kind == kindNode && s.nodes[p.global] != nil && s.nodes[p.global].proxy == id: delete(s.nodes, p.global) + delete(s.meters, p.global) case p.kind == kindDevice && s.devices[p.global] != nil && s.devices[p.global].proxy == id: delete(s.devices, p.global) case p.kind == kindMetadata && s.meta == p: @@ -382,7 +421,25 @@ func (s *session) registryEvent(op uint8, f *parser) error { if f.err != nil { return f.err } + if p, ok := s.ports[id]; ok { + delete(s.ports, id) + if n := s.nodes[p.node]; n != nil && n.jack { + s.dirty = true + } + return nil + } delete(s.nodes, id) + delete(s.meters, id) + for name, jm := range s.jackMeters { + if jm.node == id { + if jm.done != nil { + close(jm.done) + jm.done = nil + } + delete(s.jackMeters, name) + break + } + } delete(s.devices, id) delete(s.clients, id) if s.meta != nil && s.meta.global == id { @@ -400,13 +457,71 @@ func (s *session) global(id uint32, typ string, version int32, props map[string] case ifaceClient: s.clients[id] = props case ifaceNode: + name := props[propNodeName] + meter := strings.HasPrefix(name, MeterPrefix) class, ok := mediaClasses[props[propMediaClass]] jack := props[propMediaClass] == "" && props[propClientAPI] == "jack" && props[propMediaType] == "Audio" - if !ok && !jack { + if !ok && !jack && !meter { return } + own := strings.HasPrefix(name, s.meterPrefix) p := s.bind(id, typ, min(version, versionNode), kindNode) - s.nodes[id] = &node{id: id, proxy: p.id, class: class, props: props, jack: jack} + n := &node{id: id, proxy: p.id, class: class, props: props, jack: jack, meter: meter, own: own} + s.nodes[id] = n + if meter { + if own { + s.meters[id] = n + if target, ok := parseJackMeterTarget(name); ok { + jm := s.ensureJackMeter(name, target) + jm.node = id + s.syncJackMeter(jm) + } + } + return + } + case ifacePort: + if props["port.monitor"] == "true" { + return + } + if dsp := props["format.dsp"]; dsp != "" && !strings.Contains(dsp, "audio") { + return + } + dir := props["port.direction"] + if dir != "in" && dir != "out" { + return + } + nodeID, err1 := strconv.ParseUint(props["node.id"], 10, 32) + portID, err2 := strconv.ParseInt(props["port.id"], 10, 32) + if err1 != nil || err2 != nil { + return + } + nid := uint32(nodeID) + s.ports[id] = portInfo{id: id, node: nid, portID: int32(portID), name: props["port.name"], out: dir == "out"} + if n := s.nodes[nid]; n != nil && n.jack { + s.dirty = true + } + for _, jm := range s.jackMeters { + if jm.node == nid || jm.target == nid { + s.syncJackMeter(jm) + } + } + return + case ifaceLink: + inNode, err1 := strconv.ParseUint(props["link.input.node"], 10, 32) + outNode, err2 := strconv.ParseUint(props["link.output.node"], 10, 32) + if err1 != nil || err2 != nil { + return + } + for _, jm := range s.jackMeters { + if jm.node == uint32(inNode) && uint32(outNode) != jm.target { + if jm.ready { + s.destroyLink(id) + } else { + jm.unwanted = append(jm.unwanted, id) + } + } + } + return case ifaceDevice: if props[propMediaClass] != mediaClassAudioDevice { return @@ -424,6 +539,104 @@ func (s *session) global(id uint32, typ string, version int32, props map[string] s.dirty = true } +func parseJackMeterTarget(name string) (uint32, bool) { + _, after, ok := strings.Cut(name, ".jack.") + if !ok { + return 0, false + } + idStr, _, _ := strings.Cut(after, ".") + id, err := strconv.ParseUint(idStr, 10, 32) + return uint32(id), err == nil +} + +func (s *session) ensureJackMeter(name string, target uint32) *jackMeter { + jm := s.jackMeters[name] + if jm == nil { + jm = &jackMeter{target: target} + s.jackMeters[name] = jm + } + return jm +} + +func (s *session) jackMeterReady(name string, done chan struct{}) { + target, ok := parseJackMeterTarget(name) + if !ok { + close(done) + return + } + jm := s.ensureJackMeter(name, target) + jm.ready = true + jm.done = done + s.syncJackMeter(jm) +} + +func (s *session) syncJackMeter(jm *jackMeter) { + if !jm.ready || jm.node == 0 { + return + } + outPorts := s.nodePorts(jm.target, true) + inPorts := s.nodePorts(jm.node, false) + for jm.linked < len(outPorts) && jm.linked < len(inPorts) { + outPort := outPorts[jm.linked] + inPort := inPorts[jm.linked] + jm.linked++ + pid := s.ids.alloc() + s.proxies[pid] = &proxy{id: pid, kind: kindLink} + s.send(idCore, coreCreateObject, func(b *builder) { + b.structure(func() { + b.string("link-factory") + b.string(ifaceLink) + b.int(versionLink) + b.dict([][2]string{ + {"link.output.port", strconv.FormatUint(uint64(outPort.id), 10)}, + {"link.input.port", strconv.FormatUint(uint64(inPort.id), 10)}, + }) + b.int(int32(pid)) + }) + }) + } + for _, id := range jm.unwanted { + s.destroyLink(id) + } + jm.unwanted = nil + if jm.done != nil { + jm.syncSeq = s.sync() + } +} + +func (s *session) destroyLink(id uint32) { + s.send(s.registry, registryDestroy, func(b *builder) { + b.structure(func() { b.int(int32(id)) }) + }) +} + +func (s *session) resetMeterVolume(n *node) { + channels := max(1, len(n.volumes)) + vols := make([]float32, channels) + for i := range vols { + vols[i] = 1.0 + } + s.setProps(n, func(b *builder) { + b.prop(propChannelVolumes) + b.floatArray(vols) + b.prop(propMute) + b.bool(false) + }) +} + +func (s *session) nodePorts(nodeID uint32, out bool) []portInfo { + var ports []portInfo + for _, p := range s.ports { + if p.node == nodeID && p.out == out { + ports = append(ports, p) + } + } + slices.SortFunc(ports, func(a, b portInfo) int { + return cmp.Or(cmp.Compare(a.portID, b.portID), cmp.Compare(a.id, b.id)) + }) + return ports +} + func (s *session) bind(global uint32, typ string, version int32, kind proxyKind) *proxy { p := &proxy{id: s.ids.alloc(), kind: kind, global: global} s.proxies[p.id] = p @@ -466,7 +679,9 @@ func (s *session) nodeEvent(p *proxy, op uint8, f *parser) error { } if change&nodeChangeProps != 0 { n.props = props - s.dirty = true + if !n.meter { + s.dirty = true + } } if change&nodeChangeParams != 0 { s.enumerate(p, changedParams(n.params, params, paramProps)) @@ -610,6 +825,12 @@ func (s *session) commitProps(n *node, values []pod) { n.mute = mute } n.known = true + if n.meter { + if n.own && (n.mute || slices.ContainsFunc(n.volumes, func(v float32) bool { return v != 1.0 })) { + s.resetMeterVolume(n) + } + return + } s.dirty = true return } @@ -941,7 +1162,7 @@ func (s *session) snapshot(now time.Time) *Snapshot { snap := &Snapshot{Connected: true} for _, id := range slices.Sorted(maps.Keys(s.nodes)) { n := s.nodes[id] - if n.props[propStreamMonitor] == "true" { + if n.meter || n.props[propStreamMonitor] == "true" { continue } if !n.jack { @@ -955,6 +1176,12 @@ func (s *session) snapshot(now time.Time) *Snapshot { if c.ports > 0 { v := s.nodeView(n, now) v.Class, v.JACK = c.class, true + if c.class == Playback { + for i, p := range s.nodePorts(n.id, true) { + name := cmp.Or(p.name, "CH"+strconv.Itoa(i+1)) + v.Channels = append(v.Channels, Channel{Name: name, Volume: 1}) + } + } snap.Nodes = append(snap.Nodes, v) } } @@ -1048,8 +1275,8 @@ func cardView(d *device) Card { // freed by Core::RemoveId is reused first, last freed first, else the // next new one. type idMap struct { - next uint32 - free []uint32 + next uint32 // next unallocated proxy ID + free []uint32 // pool of released proxy IDs available for reuse } func (m *idMap) alloc() uint32 {