diff --git a/internal/pipmix/meters.go b/internal/pipmix/meters.go index b4c6896..9f3c612 100644 --- a/internal/pipmix/meters.go +++ b/internal/pipmix/meters.go @@ -3,6 +3,7 @@ package pipmix import ( "maps" "math" + "slices" "strconv" "time" @@ -56,7 +57,17 @@ type ( meterTickMsg struct{} ) +// waitMeter waits for the next meter snapshot, unless a wait is already +// pending. func (m *mixer) waitMeter() tea.Cmd { + if m.meter == nil || m.meterWaiting { + return nil + } + m.meterWaiting = true + return m.nextMeter() +} + +func (m *mixer) nextMeter() tea.Cmd { if m.meter == nil { return nil } @@ -136,18 +147,33 @@ func (m *mixer) watchMeters() { m.meter.Watch(targets) } -func (m *mixer) updateLevels() tea.Cmd { +func (m *mixer) startMetering() tea.Cmd { + if m.ticking { + return nil + } snap := &pulse.Snapshot{} if m.meter != nil { snap = m.meter.Snapshot() } - if !m.setLevels(snap, time.Now()) || m.ticking { - return nil + if !m.setLevels(snap, time.Now()) { + return m.waitMeter() } m.ticking = true return tea.Tick(time.Second/time.Duration(m.opts.fps), func(time.Time) tea.Msg { return meterTickMsg{} }) } +func (m *mixer) tickMetering() tea.Cmd { + snap := &pulse.Snapshot{} + if m.meter != nil { + snap = m.meter.Snapshot() + } + if !m.setLevels(snap, time.Now()) { + m.ticking = false + return m.waitMeter() + } + return tea.Tick(time.Second/time.Duration(m.opts.fps), func(time.Time) tea.Msg { return meterTickMsg{} }) +} + // 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) { @@ -160,97 +186,110 @@ func (m *mixer) setLevels(snap *pulse.Snapshot, now time.Time) (moving bool) { sm := smoothings[m.smoothing] attack := 1 - math.Exp(-dt/sm.attack.Seconds()) release := 1 - math.Exp(-dt/sm.release.Seconds()) + var buf [32]float64 - fill := make(map[uint32][]float64) - for id, target := range m.shown(source) { - prev := m.fill[id] - v := make([]float64, len(target)) + shown := func(id uint32) bool { return m.meterNode(id, source[id]) != nil } + m.fill, m.fillStart = prune(m.fill, shown), prune(m.fillStart, shown) + for id, raw := range source { + n := m.meterNode(id, raw) + if n == nil { + continue + } + start, ok := m.fillStart[id] + if !ok { + start = now + m.fillStart[id] = start + } + if now.Sub(start) < fadeIn { + moving = true + } + target, v := scale(n, raw, buf[:0]), m.fill[id] + if len(v) != len(target) { + m.fill[id] = slices.Clone(target) + continue + } for ch, t := range target { - if ch >= len(prev) { - v[ch] = t - continue - } k := release - if t > prev[ch] { + if t > v[ch] { k = attack } - v[ch] = prev[ch] + k*(t-prev[ch]) + v[ch] += k * (t - v[ch]) if math.Abs(t-v[ch]) < settled { v[ch] = t } else { moving = true } } - fill[id] = v } - m.fill = fill - starts := make(map[uint32]time.Time) - for id := range fill { - start, ok := m.fillStart[id] - if !ok { - start = now + shown = func(id uint32) bool { return m.meterNode(id, snap.Peaks[id]) != nil } + m.dot, m.dotHold = prune(m.dot, shown), prune(m.dotHold, shown) + for id, raw := range snap.Peaks { + n := m.meterNode(id, raw) + if n == nil { + continue } - starts[id] = start - if now.Sub(start) < fadeIn { - moving = true + target, v, hold := scale(n, raw, buf[:0]), m.dot[id], m.dotHold[id] + if len(v) != len(target) || len(hold) != len(target) { + // Zero rises to the target and holds it. + v, hold = make([]float64, len(target)), make([]time.Time, len(target)) + m.dot[id], m.dotHold[id] = v, hold } - } - m.fillStart = starts - - dot := make(map[uint32][]float64) - holds := make(map[uint32][]time.Time) - for id, target := range m.shown(snap.Peaks) { - prev, prevHold := m.dot[id], m.dotHold[id] - v := make([]float64, len(target)) - hold := make([]time.Time, len(target)) for ch, t := range target { switch { - case ch >= len(prev) || ch >= len(prevHold) || t >= prev[ch]: + case t >= v[ch]: v[ch], hold[ch] = t, now.Add(m.opts.peakHold) - case now.Before(prevHold[ch]): - v[ch], hold[ch] = prev[ch], prevHold[ch] + case now.Before(hold[ch]): + // Hold the peak. default: - v[ch], hold[ch] = max(t, prev[ch]-m.opts.limit*dt), prevHold[ch] + v[ch] = max(t, v[ch]-m.opts.limit*dt) } if v[ch] > t { moving = true } } - dot[id], holds[id] = v, hold } - m.dot, m.dotHold = dot, holds return moving } -// shown scales raw levels to the cubic volume scale, applying sink volume and -// mute state. -func (m *mixer) shown(raw map[uint32][]float64) map[uint32][]float64 { - nodes := make(map[uint32]*pw.Node) +// 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 { for i := range m.snap.Nodes { - if len(m.snap.Nodes[i].Channels) > 0 { - nodes[m.snap.Nodes[i].ID] = &m.snap.Nodes[i] + if n := &m.snap.Nodes[i]; n.ID == id && len(n.Channels) > 0 { + if len(raw) != len(n.Channels) { + return nil + } + return n } } - shown := make(map[uint32][]float64) - for id, levels := range raw { - n := nodes[id] - if n == nil || len(levels) != len(n.Channels) { - continue + return nil +} + +// scale appends raw levels of n to dst on the cubic volume scale, applying +// sink volume and mute state. +func scale(n *pw.Node, raw, dst []float64) []float64 { + for ch, l := range raw { + v := math.Cbrt(l) + if n.Class == pw.Sink { + v *= n.Channels[ch].Volume } - v := make([]float64, len(levels)) - for ch, l := range levels { - v[ch] = math.Cbrt(l) - if n.Class == pw.Sink { - v[ch] *= n.Channels[ch].Volume - } - if n.Mute { - v[ch] = 0 - } + if n.Mute { + v = 0 } - shown[id] = v + dst = append(dst, v) + } + return dst +} + +// prune deletes the entries of levels whose id is not kept, making levels +// if it is nil. +func prune[V any](levels map[uint32]V, keep func(id uint32) bool) map[uint32]V { + if levels == nil { + return make(map[uint32]V) } - return shown + maps.DeleteFunc(levels, func(id uint32, _ V) bool { return !keep(id) }) + return levels } func (m *mixer) level(it item, ch int) float64 { diff --git a/internal/pipmix/meters_test.go b/internal/pipmix/meters_test.go index b0d910d..acdfc5e 100644 --- a/internal/pipmix/meters_test.go +++ b/internal/pipmix/meters_test.go @@ -284,3 +284,25 @@ func TestMeterFadeIn(t *testing.T) { t.Errorf("restarted meter's level %v, want 0", l) } } + +// TestMeterWaitOnce checks that a meter wait is never started while one is +// pending. +func TestMeterWaitOnce(t *testing.T) { + m := testMixer() + m.snap = meterSnapshot() + m.meter = pulse.NewMeter(nil, 0) + m.meterWaiting = true // as after init + + for _, msg := range []tea.Msg{tea.BlurMsg{}, tea.FocusMsg{}} { + if cmd := m.update(msg); cmd != nil { + t.Errorf("%T with a wait pending: got a command, want none", msg) + } + } + // A snapshot with nothing moving waits again, once. + if cmd := m.update(meterMsg{}); cmd == nil || !m.meterWaiting { + t.Fatal("snapshot with settled levels: no new wait") + } + if cmd := m.update(tea.FocusMsg{}); cmd != nil { + t.Error("focus after the new wait: got a command, want none") + } +} diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index 4f8b1ba..abccb9a 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -113,6 +113,7 @@ type mixer struct { dotHold map[uint32][]time.Time levelsAt time.Time ticking bool + meterWaiting bool // a waitMeter command is pending blurred bool smoothing int metersHidden bool @@ -148,6 +149,8 @@ func newMixer(c *pw.Client, media *mpris.Watcher, meter *pulse.Meter, quitKeys s client: c, snap: c.Snapshot(), media: media, meter: meter, quitKeys: quitKeys, opts: opts, tab: opts.tab, meterMode: opts.meterMode, smoothing: opts.smoothing, unlocked: make(map[string]bool), + // init starts the first wait, on a copy of the mixer. + meterWaiting: meter != nil, } } @@ -186,7 +189,7 @@ func (m *mixer) waitMedia() tea.Cmd { } } -func (m *mixer) init() tea.Cmd { return tea.Batch(m.waitSnapshot(), m.waitMedia(), m.waitMeter()) } +func (m *mixer) init() tea.Cmd { return tea.Batch(m.waitSnapshot(), m.waitMedia(), m.nextMeter()) } // findMedia matches playback streams to MPRIS players by process ID. func (m *mixer) findMedia() { @@ -236,19 +239,25 @@ func (m *mixer) update(msg tea.Msg) tea.Cmd { m.snap = m.client.Snapshot() m.findMedia() m.refocus() + m.watchMeters() return m.waitSnapshot() case mediaMsg: m.findMedia() + m.watchMeters() return m.waitMedia() case meterMsg: - return tea.Batch(m.updateLevels(), m.waitMeter()) + m.meterWaiting = false + return m.startMetering() case meterTickMsg: - m.ticking = false - return m.updateLevels() + return m.tickMetering() case tea.FocusMsg: m.blurred = false + m.watchMeters() + return m.startMetering() case tea.BlurMsg: m.blurred = true + m.watchMeters() + return m.startMetering() case noticeMsg: m.notice, m.noticeErr = msg.text, msg.err m.noticeSeq++ diff --git a/internal/pipmix/mixer_test.go b/internal/pipmix/mixer_test.go index 3b94f86..e284b56 100644 --- a/internal/pipmix/mixer_test.go +++ b/internal/pipmix/mixer_test.go @@ -532,8 +532,9 @@ func TestTypeStrip(t *testing.T) { continue } found = true + layout := m.tabLayout(tc.tab) for _, focused := range []bool{false, true} { - lines := m.renderItem(it, focused) + lines := m.renderItem(it, focused, layout) if strings.Contains(lines[0], focusTitleStyle.Render(it.title())) != focused { t.Errorf("tab %s, item %d, focused %v: title line %q, want the name bold and underlined only when focused", tabNames[tc.tab], tc.id, focused, lines[0]) } diff --git a/internal/pipmix/pipmix.go b/internal/pipmix/pipmix.go index 7e8415e..a685bcd 100644 --- a/internal/pipmix/pipmix.go +++ b/internal/pipmix/pipmix.go @@ -143,14 +143,16 @@ func (a app) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.WindowSizeMsg: a.mixer.setSize(msg.Width, msg.Height) + a.mixer.watchMeters() case tea.KeyPressMsg: cmd = a.mixer.handleKey(msg.String()) + a.mixer.watchMeters() case tea.MouseMsg: cmd = a.mixer.handleMouse(msg) + a.mixer.watchMeters() default: cmd = a.mixer.update(msg) } - a.mixer.watchMeters() return a, cmd } diff --git a/internal/pipmix/view.go b/internal/pipmix/view.go index f921845..0bad434 100644 --- a/internal/pipmix/view.go +++ b/internal/pipmix/view.go @@ -168,12 +168,11 @@ func (m *mixer) view() string { if m.help { list = m.helpView(m.width, h) } else { - items := m.items(m.tab) - fi := m.focusIndex(m.tab, items) - for i, it := range items { - list = append(list, m.renderItem(it, i == fi)...) + layout := m.tabLayout(m.tab) + for i, it := range layout.items { + list = append(list, m.renderItem(it, i == layout.focus, layout)...) } - if len(items) == 0 && m.snap.Connected { + if len(layout.items) == 0 && m.snap.Connected { list = []string{dimStyle.Render(" Nothing here")} } off := min(m.offset[m.tab], max(len(list)-h, 0)) @@ -234,7 +233,43 @@ func (m *mixer) statusLine() string { return "" } -func (m *mixer) renderItem(it item, focused bool) []string { +type tabLayout struct { + items []item + focus int + portWidth int +} + +func (m *mixer) tabLayout(t tab) tabLayout { + items := m.items(t) + return tabLayout{ + items: items, + focus: m.focusIndex(t, items), + portWidth: m.portWidth(items), + } +} + +func (l tabLayout) isGroupMuted(it item) bool { + if it.groupCount <= 1 { + return it.node != nil && it.node.Mute + } + for _, other := range l.items { + if other.groupKey == it.groupKey && other.node != nil { + if !other.node.Mute { + return false + } + } + } + return true +} + +func (l tabLayout) isGroupFocused(it item) bool { + if it.groupCount <= 1 || it.groupKey == "" || l.focus < 0 || l.focus >= len(l.items) { + return false + } + return l.items[l.focus].groupKey == it.groupKey +} + +func (m *mixer) renderItem(it item, focused bool, layout tabLayout) []string { w := m.width if w < contentX+2 { return nil @@ -242,19 +277,25 @@ func (m *mixer) renderItem(it item, focused bool) []string { inner := m.innerWidth() gutter := " " + typeStrip(it) line := func(s string) string { return gutter + " " + fit(s, inner) + " " } + cLine := func(s string) string { + if m.barWidth() > 0 { + return gutter + " " + s + " " + } + return line(s) + } var lines []string for _, l := range m.itemLines(it) { switch l.kind { case lineBlank: lines = append(lines, "") case lineTitle: - groupFocused := focused || m.isGroupFocused(it) - lines = append(lines, line(m.titleLine(it, groupFocused, inner))) + groupFocused := focused || layout.isGroupFocused(it) + lines = append(lines, line(m.titleLine(it, groupFocused, inner, layout))) case lineChannel: - lines = append(lines, line(m.channelLine(it, l.channel, focused))) + lines = append(lines, cLine(m.channelLine(it, l.channel, focused))) case lineNoVolume: if it.node.JACK { - lines = append(lines, line(fixedBar(m.barWidth()))) + lines = append(lines, cLine(fixedBar(m.barWidth()))) break } lines = append(lines, line(dimStyle.Render("volume not known yet"))) @@ -301,20 +342,28 @@ func (m *mixer) tagsWidth() int { return 0 } +func (m *mixer) portWidth(items []item) int { + if m.tab == tabCards { + return 0 + } + port := 0 + for _, it := range items { + port = max(port, ansi.StringWidth(portText(it))) + } + return port +} + // titleColumns returns the widths of the title and port columns for the // current tab. -func (m *mixer) titleColumns(width int) (title, port int) { +func (m *mixer) titleColumns(width, portW int) (title, port int) { if m.tab == tabCards { return width, 0 } - for _, it := range m.items(m.tab) { - port = max(port, ansi.StringWidth(portText(it))) - } rest := width if tw := m.tagsWidth(); tw > 0 { rest -= tw + 1 } - port = min(port, rest-1-min(minTitle, rest/2)) + port = min(portW, rest-1-min(minTitle, rest/2)) if port < minPortRoom { port = 0 } @@ -347,40 +396,14 @@ func tagsText(it item) string { const toolbarWidth = barX - contentX -func (m *mixer) isGroupMuted(it item) bool { - if it.groupCount <= 1 { - return it.node != nil && it.node.Mute - } - for _, other := range m.items(m.tab) { - if other.groupKey == it.groupKey && other.node != nil { - if !other.node.Mute { - return false - } - } - } - return true -} - -func (m *mixer) isGroupFocused(it item) bool { - if it.groupCount <= 1 || it.groupKey == "" { - return false - } - items := m.items(m.tab) - fi := m.focusIndex(m.tab, items) - if fi < 0 || fi >= len(items) { - return false - } - return items[fi].groupKey == it.groupKey -} - -func (m *mixer) toolbar(it item, focused bool) string { +func (m *mixer) toolbar(it item, focused bool, layout tabLayout) string { if it.node == nil { return "" } var b strings.Builder muted := it.node.Mute if it.groupCount > 1 { - muted = m.isGroupMuted(it) + muted = layout.isGroupMuted(it) } b.WriteString(muteSymbol(muted, it.node.JACK, focused)) if btn := playButton(it, focused); btn != "" { @@ -394,7 +417,7 @@ func (m *mixer) toolbar(it item, focused bool) string { return b.String() } -func (m *mixer) titleLine(it item, focused bool, width int) string { +func (m *mixer) titleLine(it item, focused bool, width int, layout tabLayout) string { title := it.title() if it.groupCount > 1 && it.groupTitle != "" { title = it.groupTitle @@ -402,7 +425,7 @@ func (m *mixer) titleLine(it item, focused bool, width int) string { if focused { title = focusTitleStyle.Render(title) } - tb := m.toolbar(it, focused) + tb := m.toolbar(it, focused, layout) avail := width if it.node != nil { avail = max(0, width-toolbarWidth) @@ -412,17 +435,17 @@ func (m *mixer) titleLine(it item, focused bool, width int) string { } tw := 0 titleW := avail - portW := 0 + finalPortW := 0 if it.node.Class == pw.Sink || it.node.Class == pw.Source { tw = m.tagsWidth() if avail < tw+2 { return tb + title } - titleW, portW = m.titleColumns(avail) + titleW, finalPortW = m.titleColumns(avail, layout.portWidth) } line := tb + fit(title, titleW) - if portW > 0 { - line += " " + dimStyle.Render(fit(portText(it), portW)) + if finalPortW > 0 { + line += " " + dimStyle.Render(fit(portText(it), finalPortW)) } if tw > 0 { line += " " + tagsText(it) @@ -439,7 +462,7 @@ func (m *mixer) portSpan(it item) (start, end int, ok bool) { return 0, 0, false } avail := max(0, inner-toolbarWidth) - titleW, portW := m.titleColumns(avail) + titleW, portW := m.titleColumns(avail, m.portWidth(m.items(m.tab))) if portW == 0 { return 0, 0, false } @@ -613,29 +636,32 @@ func meterBar(level, peak float64, width int, limit float64, look meterLook) str } hundred := knobCell(1, limit, width) styles := [...]lipgloss.Style{barFullStyle, barOverStyle, brightFull, brightOver, dimStyle} - type cell struct { - glyph string - style int + var cellBuf [256]barCell + var cells []barCell + if width <= len(cellBuf) { + cells = cellBuf[:width] + } else { + cells = make([]barCell, width) } - cells := make([]cell, width) for i := range cells { over := 0 if i > hundred { over = 1 } - c := cell{faderEmpty, 4} + c := barCell{faderEmpty, 4} switch { case i < lit && (look == meterSolid || look == meterShade): - c = cell{faderKnob, over} + c = barCell{faderKnob, over} case i == lit-1 && look == meterDot: - c = cell{faderKnob, 2 + over} + c = barCell{faderKnob, 2 + over} } if i == pk-1 { - c = cell{faderKnob, 2 + over} + c = barCell{faderKnob, 2 + over} } cells[i] = c } var b strings.Builder + b.Grow(width * 6) for i := 0; i < len(cells); { j := i + 1 for j < len(cells) && cells[j] == cells[i] { @@ -647,6 +673,11 @@ func meterBar(level, peak float64, width int, limit float64, look meterLook) str return b.String() } +type barCell struct { + glyph string + style int +} + var ( emptyOverStyle = lipgloss.NewStyle().Foreground(lipgloss.Red).Faint(true) brightFull = lipgloss.NewStyle().Foreground(lipgloss.BrightGreen) @@ -661,6 +692,7 @@ func bar(v, level, peak float64, width int, limit float64, muted bool, look mete knob := knobCell(v, limit, width) hundred := knobCell(1, limit, width) var b strings.Builder + b.Grow(width * 6) run := func(s string, from, to int, style lipgloss.Style) { if to > from { b.WriteString(style.Render(strings.Repeat(s, to-from))) @@ -677,10 +709,6 @@ func bar(v, level, peak float64, width int, limit float64, muted bool, look mete knobStyle = barOverStyle } styles := [...]lipgloss.Style{barFullStyle, barOverStyle, brightFull, brightOver} - type cell struct { - glyph string - style int - } lit, pk := 0, 0 if look != meterOff { if level > 0 { @@ -690,23 +718,29 @@ func bar(v, level, peak float64, width int, limit float64, muted bool, look mete pk = min(knobCell(peak, limit, width), knob) } } - cells := make([]cell, knob) + var cellBuf [256]barCell + var cells []barCell + if knob <= len(cellBuf) { + cells = cellBuf[:knob] + } else { + cells = make([]barCell, knob) + } for i := range cells { over := 0 if i > hundred { over = 1 } - c := cell{faderFull, over} + c := barCell{faderFull, over} switch { case i < lit && (look == meterSolid || look == meterShade): c.glyph = faderKnob case i == lit-1 && look == meterDot: - c = cell{faderKnob, 2 + over} + c = barCell{faderKnob, 2 + over} case look == meterShade: c.glyph = "▒" } if i == pk-1 { - c = cell{faderKnob, 2 + over} + c = barCell{faderKnob, 2 + over} } cells[i] = c }