Add live peak meters (pavucontrol-style level bars)
CI / check (push) Successful in 10s
CI / native (push) Successful in 1m39s

Each row on Playback, Output Devices and Input Devices gets a level bar
under its slider. A meter is a small capture pw_stream on WirePlumber's
pw_core with the properties pipewire-pulse gives pavucontrol's peak
streams (stream.monitor, target.object, stream.capture.sink for sinks);
its process callback folds samples into a peak that a 40 ms GUI timer
reads, maps with the slider's cubic curve and decays smoothly.

- Only the visible tab is metered; output/stream meters are passive.
- stream.monitor nodes (ours and pavucontrol's) are hidden from the tabs.
- moonmix-probe gains `meter <id>`; the smoke test now plays noise and
  checks the stream and sink meters see it.
- Screenshot mode holds the meters still before capturing, since a
  constantly redrawing window never yields a frame under broadway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Opus 5.5 committed 2026-11-22 16:33:12 -08:00
1 parent 92ae5cdbfe
commit f08f241edb
17 files changed
+503 -18

No files matched your search

+16 -4
View File
@@ -24,6 +24,10 @@ on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`,
- **Recording**: capture streams, same controls, input device selector. - **Recording**: capture streams, same controls, input device selector.
- **Output Devices** / **Input Devices**: sinks and sources with volume, mute - **Output Devices** / **Input Devices**: sinks and sources with volume, mute
and a *Default* toggle that shows and sets the default device. and a *Default* toggle that shows and sets the default device.
- **Live peak meters** under each slider on Playback, Output Devices and
Input Devices, on the same cubic scale as the slider. Only the visible
tab is metered; meters on outputs and app streams are passive, so they
never keep an idle device running.
- Volumes in percent exactly like pavucontrol/wpctl: the cubic mapping of - Volumes in percent exactly like pavucontrol/wpctl: the cubic mapping of
PipeWire's linear `channelVolumes`, up to 150%, with the dB value next to PipeWire's linear `channelVolumes`, up to 150%, with the dB value next to
it. One slider moves all channels, keeping the channel balance. it. One slider moves all channels, keeping the channel balance.
@@ -32,7 +36,7 @@ on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`,
show up immediately. show up immediately.
Not yet included: the Configuration tab (card profiles), per-channel Not yet included: the Configuration tab (card profiles), per-channel
sliders, peak meters, monitor sources in Input Devices. sliders, monitor sources in Input Devices, meters for recording streams.
## Architecture ## Architecture
@@ -62,7 +66,13 @@ flowchart LR
route, which is where pavucontrol's numbers live. The **default-nodes-api** route, which is where pavucontrol's numbers live. The **default-nodes-api**
plugin reads and sets the default sink and source. To move a stream, plugin reads and sets the default sink and source. To move a stream,
moonmix sets `target.object` in the `default` metadata, as pipewire-pulse moonmix sets `target.object` in the `default` metadata, as pipewire-pulse
does for pavucontrol. The C layer sends MoonBit one callback per change, does for pavucontrol. Peak meters are small capture `pw_stream`s on
WirePlumber's own `pw_core`, created with the properties pipewire-pulse
gives pavucontrol's peak streams (`stream.monitor`, `target.object`,
`stream.capture.sink` for sinks); their `process` callback only folds
samples into a peak value that a 40 ms GUI timer reads and resets. Nodes
with `stream.monitor` (ours and pavucontrol's) are hidden from the tabs.
The C layer sends MoonBit one callback per change,
`(kind, id)`. MoonBit then pulls node properties and volumes through small `(kind, id)`. MoonBit then pulls node properties and volumes through small
accessor functions, so no C structs cross the FFI boundary. accessor functions, so no C structs cross the FFI boundary.
- **One main loop.** WirePlumber and GTK4 both run on the default GLib main - **One main loop.** WirePlumber and GTK4 both run on the default GLib main
@@ -128,6 +138,7 @@ $P volume alsa_output.pci-0000_00_1f.3.analog-stereo 40
$P mute 57 1 # node id or node.name $P mute 57 1 # node id or node.name
$P default bluez_output.XX_XX.1 $P default bluez_output.XX_XX.1
$P move <stream-id> <sink-id-or-name> $P move <stream-id> <sink-id-or-name>
$P meter <id> # peak over ~1.5 s; exit 6 if silent
``` ```
## Testing ## Testing
@@ -140,8 +151,9 @@ tools/smoke-test.sh /tmp/shot # needs pipewire, wireplumber, pw-cat, gtk4-
`tools/smoke-test.sh` starts a private PipeWire and WirePlumber in a temp `tools/smoke-test.sh` starts a private PipeWire and WirePlumber in a temp
`XDG_RUNTIME_DIR`. The instance has two null sinks, a loopback virtual `XDG_RUNTIME_DIR`. The instance has two null sinks, a loopback virtual
microphone, and one playback and one capture stream created with `pw-cat`; the CLI is used only microphone, one playback stream of noise and one capture stream created with `pw-cat`; the CLI is used only
by the test harness. The script runs every probe action and checks its effect, by the test harness. The script runs every probe action and checks its effect, checks that peak
meters on the stream and its sink see the signal,
then starts the GUI under GTK's broadway backend. With `MOONMIX_SCREENSHOT` then starts the GUI under GTK's broadway backend. With `MOONMIX_SCREENSHOT`
set, the GUI renders each tab offscreen to a PNG and exits. set, the GUI renders each tab offscreen to a PNG and exits.
+26 -1
View File
@@ -9,6 +9,8 @@
// moonmix-probe mute <id> <0|1> // moonmix-probe mute <id> <0|1>
// moonmix-probe default <id> make sink/source the default // moonmix-probe default <id> make sink/source the default
// moonmix-probe move <stream> <dev> route a stream to a device // moonmix-probe move <stream> <dev> route a stream to a device
// moonmix-probe meter <id> peak level of a sink/source/playback
// stream over ~1.5 s (exit 6 if silent)
///| ///|
extern "C" fn c_exit(code : Int32) = "exit" extern "C" fn c_exit(code : Int32) = "exit"
@@ -99,6 +101,7 @@ fn main {
let argv = @env.args() let argv = @env.args()
let args = if argv.length() > 1 { argv[1:].to_owned() } else { [] } let args = if argv.length() > 1 { argv[1:].to_owned() } else { [] }
let state = @model.State::new() let state = @model.State::new()
let meter_id : Ref[Int32] = { val: -1, }
@wp.on_event(fn(ev) { @wp.on_event(fn(ev) {
for e in @wp.to_model_events(ev) { for e in @wp.to_model_events(ev) {
let _ = state.apply(e) let _ = state.apply(e)
@@ -108,7 +111,20 @@ fn main {
Ready => @wp.timeout(300, 2) Ready => @wp.timeout(300, 2)
Timeout(2) => { Timeout(2) => {
print_state(state) print_state(state)
if args.length() > 0 { if args is ["meter", id] {
let id = resolve(state, id)
let kind = match state.nodes.get(id) {
Some(n) => n.kind()
None => Other
}
meter_id.val = id
let ok = @wp.meter_start(id, kind)
println("== meter \{id}: \{if ok { "started" } else { "FAILED" }}")
if !ok {
c_exit(6)
}
@wp.timeout(1500, 3)
} else if args.length() > 0 {
let ok = act(state, args) let ok = act(state, args)
println( println(
"== action \{args.join(" ")}: \{if ok { "ok" } else { "FAILED" }}", "== action \{args.join(" ")}: \{if ok { "ok" } else { "FAILED" }}",
@@ -118,6 +134,15 @@ fn main {
@wp.quit() @wp.quit()
} }
} }
Timeout(3) => {
let peak = @wp.meter_take(meter_id.val).unwrap_or(0.0)
println("== meter \{meter_id.val}: peak \{peak}")
@wp.meter_stop(meter_id.val)
if peak <= 0.0 {
c_exit(6)
}
@wp.quit()
}
Timeout(1) => { Timeout(1) => {
print_state(state) print_state(state)
@wp.quit() @wp.quit()
+137 -5
View File
@@ -4,6 +4,9 @@
// @model.rows per tab -> @model.diff_rows -> create/update/remove widgets. // @model.rows per tab -> @model.diff_rows -> create/update/remove widgets.
// User actions go straight to @wp setters; the resulting change comes back // User actions go straight to @wp setters; the resulting change comes back
// as a normal event. // as a normal event.
//
// Peak meters run only for the visible tab: switching tabs starts capture
// streams for its rows and stops the others, and a 40 ms timer moves the bars.
///| ///|
extern "C" fn c_exit(code : Int32) = "exit" extern "C" fn c_exit(code : Int32) = "exit"
@@ -17,6 +20,8 @@ struct RowView {
subtitle : @gtk.Widget subtitle : @gtk.Widget
scale : @gtk.Widget scale : @gtk.Widget
volume_label : @gtk.Widget volume_label : @gtk.Widget
meter : @gtk.Widget
mut shown_level : Double
mute : @gtk.Widget mute : @gtk.Widget
default_btn : @gtk.Widget? default_btn : @gtk.Widget?
device : @gtk.Widget? device : @gtk.Widget?
@@ -41,14 +46,25 @@ struct App {
status : @gtk.Widget status : @gtk.Widget
window : @gtk.Widget window : @gtk.Widget
notebook : @gtk.Widget notebook : @gtk.Widget
/// Index of the visible tab.
current : Ref[Int32]
/// Nodes with a running peak meter.
metered : Map[Int32, Bool]
/// Screenshot mode: hold the bars still so the window can be captured.
meters_paused : Ref[Bool]
} }
///|
const METER_INTERVAL_MS : Int32 = 40
///| ///|
const CSS : String = const CSS : String =
#|.mm-title { font-weight: bold; } #|.mm-title { font-weight: bold; }
#|.mm-subtitle { opacity: 0.7; font-size: smaller; } #|.mm-subtitle { opacity: 0.7; font-size: smaller; }
#|.mm-row { padding: 6px 12px; } #|.mm-row { padding: 6px 12px; }
#|.mm-status { padding: 4px 8px; opacity: 0.8; font-size: smaller; } #|.mm-status { padding: 4px 8px; opacity: 0.8; font-size: smaller; }
#|levelbar.mm-meter trough, levelbar.mm-meter block { min-height: 4px; }
#|levelbar.mm-meter { margin: 0 10px; }
///| ///|
fn mute_icon(muted : Bool) -> String { fn mute_icon(muted : Bool) -> String {
@@ -148,7 +164,15 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
} }
}) })
tags.push(scale_tag) tags.push(scale_tag)
slider_row.append(scale) // Peak meter under the slider, as wide as it.
let meter = @gtk.level_bar()
meter.add_css_class("mm-meter")
meter.set_visible(tab.has_meter())
let column = @gtk.vbox(2)
column.set_hexpand(true)
column.append(scale)
column.append(meter)
slider_row.append(column)
slider_row.append(volume_label) slider_row.append(volume_label)
root.append(slider_row) root.append(slider_row)
let view = { let view = {
@@ -158,6 +182,8 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView {
subtitle, subtitle,
scale, scale,
volume_label, volume_label,
meter,
shown_level: 0.0,
mute, mute,
default_btn, default_btn,
device, device,
@@ -273,6 +299,87 @@ fn App::render(self : App) -> Unit {
for t in self.tabs { for t in self.tabs {
self.render_tab(t) self.render_tab(t)
} }
self.sync_meters()
}
///|
fn @model.Tab::has_meter(self : @model.Tab) -> Bool {
// Like pavucontrol: a capture stream has no output of its own to meter.
!(self is Recording)
}
///|
/// Run peak meters for exactly the rows of the visible tab.
fn App::sync_meters(self : App) -> Unit {
let want : Map[Int32, @model.NodeKind] = Map([])
match self.tabs.get(self.current.val) {
Some(t) =>
if t.tab.has_meter() {
for row in t.rows {
want.set(row.id, t.tab.node_kind())
}
}
None => ()
}
let stale = []
for id, _ in self.metered {
if !want.contains(id) {
stale.push(id)
}
}
for id in stale {
@wp.meter_stop(id)
self.metered.remove(id)
for t in self.tabs {
match t.views.get(id) {
Some(v) => {
v.shown_level = 0.0
v.meter.set_level(0.0)
}
None => ()
}
}
}
for id, kind in want {
if !self.metered.contains(id) && @wp.meter_start(id, kind) {
self.metered.set(id, true)
}
}
}
///|
/// Move the bars of the visible tab to the latest peaks.
fn App::tick_meters(self : App) -> Unit {
if self.meters_paused.val {
return
}
match self.tabs.get(self.current.val) {
Some(t) =>
for id, v in t.views {
match @wp.meter_take(id) {
Some(peak) => {
let next = @model.meter_step(
v.shown_level,
@model.meter_level(peak),
)
if next != v.shown_level {
v.shown_level = next
v.meter.set_level(next)
}
}
None => ()
}
}
None => ()
}
}
///|
fn App::start_meter_timer(self : App) -> Unit {
@gtk.timeout(METER_INTERVAL_MS, fn() {
self.tick_meters()
self.start_meter_timer()
})
} }
///| ///|
@@ -295,7 +402,11 @@ fn App::on_wp_event(self : App, ev : @wp.Event) -> Unit {
} }
match ev { match ev {
Ready => self.set_status("Connected to PipeWire via WirePlumber") Ready => self.set_status("Connected to PipeWire via WirePlumber")
Disconnected => self.set_status("Disconnected from PipeWire") Disconnected => {
// The streams died with the connection.
self.metered.clear()
self.set_status("Disconnected from PipeWire")
}
PluginError => PluginError =>
self.set_status( self.set_status(
"Could not load WirePlumber's mixer-api / default-nodes-api modules", "Could not load WirePlumber's mixer-api / default-nodes-api modules",
@@ -312,7 +423,12 @@ fn build_ui() -> App {
@gtk.load_css(CSS) @gtk.load_css(CSS)
let window = @gtk.window("Volume Control (moonmix)", 640, 480) let window = @gtk.window("Volume Control (moonmix)", 640, 480)
let outer = @gtk.vbox(0) let outer = @gtk.vbox(0)
let nb = @gtk.notebook() let current : Ref[Int32] = { val: 0, }
let on_switch : Ref[(Int32) -> Unit] = { val: fn(_) { }, }
let nb = @gtk.notebook(on_switch=fn(i) {
current.val = i
(on_switch.val)(i)
})
let tabs = [] let tabs = []
for tab in @model.Tab::all() { for tab in @model.Tab::all() {
let list = @gtk.vbox(0) let list = @gtk.vbox(0)
@@ -329,7 +445,18 @@ fn build_ui() -> App {
status.add_css_class("mm-status") status.add_css_class("mm-status")
outer.append(status) outer.append(status)
window.set_child(outer) window.set_child(outer)
{ state: @model.State::new(), tabs, status, window, notebook: nb, } let app = {
state: @model.State::new(),
tabs,
status,
window,
notebook: nb,
current,
metered: Map([]),
meters_paused: { val: false, },
}
on_switch.val = fn(_) { app.sync_meters() }
app
} }
///| ///|
@@ -348,7 +475,11 @@ fn screenshot_mode(app : App, prefix : String) -> Unit {
if attempt == 0 { if attempt == 0 {
app.select_tab(i) app.select_tab(i)
} }
@gtk.timeout(400, fn() { // Let the meters run, then hold them still: a window that redraws every
// tick never has a finished frame to capture under broadway.
app.meters_paused.val = false
@gtk.timeout(400, fn() { app.meters_paused.val = true })
@gtk.timeout(600, fn() {
let path = "\{prefix}-\{i}.png" let path = "\{prefix}-\{i}.png"
if app.window.save_png(path) { if app.window.save_png(path) {
println("moonmix: wrote \{path}") println("moonmix: wrote \{path}")
@@ -382,6 +513,7 @@ fn main {
app.set_status("Cannot connect to PipeWire. Is pipewire running?") app.set_status("Cannot connect to PipeWire. Is pipewire running?")
} }
app.window.present() app.window.present()
app.start_meter_timer()
match env_var("MOONMIX_SCREENSHOT") { match env_var("MOONMIX_SCREENSHOT") {
Some(prefix) if prefix != "" => screenshot_mode(app, prefix) Some(prefix) if prefix != "" => screenshot_mode(app, prefix)
_ => () _ => ()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

+17
View File
@@ -136,6 +136,12 @@ extern "C" fn ffi_dropdown_new(tag : Int32) -> Widget = "mm_gtk_dropdown_new"
#borrow(items) #borrow(items)
extern "C" fn ffi_dropdown_set(dd : Widget, items : Bytes, selected : Int32) = "mm_gtk_dropdown_set" extern "C" fn ffi_dropdown_set(dd : Widget, items : Bytes, selected : Int32) = "mm_gtk_dropdown_set"
///|
extern "C" fn ffi_levelbar_new() -> Widget = "mm_gtk_levelbar_new"
///|
extern "C" fn ffi_levelbar_set(lb : Widget, v : Double) = "mm_gtk_levelbar_set"
///| ///|
#borrow(text) #borrow(text)
extern "C" fn ffi_set_tooltip(w : Widget, text : Bytes) = "mm_gtk_widget_set_tooltip" extern "C" fn ffi_set_tooltip(w : Widget, text : Bytes) = "mm_gtk_widget_set_tooltip"
@@ -436,6 +442,17 @@ pub fn Widget::set_items(
ffi_dropdown_set(self, cstr(clean.join("\n")), selected) ffi_dropdown_set(self, cstr(clean.join("\n")), selected)
} }
///|
/// A 0..1 level bar (peak meter).
pub fn level_bar() -> Widget {
ffi_levelbar_new()
}
///|
pub fn Widget::set_level(self : Widget, v : Double) -> Unit {
ffi_levelbar_set(self, v)
}
///| ///|
pub fn Widget::set_tooltip(self : Widget, text : String) -> Unit { pub fn Widget::set_tooltip(self : Widget, text : String) -> Unit {
ffi_set_tooltip(self, cstr(text)) ffi_set_tooltip(self, cstr(text))
+22 -1
View File
@@ -7,6 +7,7 @@
* widgets programmatically (mm_gtk_set_*), callbacks are suppressed so model * widgets programmatically (mm_gtk_set_*), callbacks are suppressed so model
* updates never echo back into PipeWire. * updates never echo back into PipeWire.
*/ */
#include <stdio.h>
#include <string.h> #include <string.h>
#include <gtk/gtk.h> #include <gtk/gtk.h>
#include "moonbit.h" #include "moonbit.h"
@@ -314,6 +315,22 @@ MOONBIT_FFI_EXPORT void mm_gtk_dropdown_set(GtkWidget *dd,
g_suppress--; g_suppress--;
} }
/* Thin 0..1 level bar for peak meters, without GTK's low/high/full colour
* offsets (a quiet signal is not a warning). */
MOONBIT_FFI_EXPORT GtkWidget *mm_gtk_levelbar_new(void) {
GtkWidget *lb = gtk_level_bar_new_for_interval(0.0, 1.0);
GtkLevelBar *l = GTK_LEVEL_BAR(lb);
gtk_level_bar_remove_offset_value(l, GTK_LEVEL_BAR_OFFSET_LOW);
gtk_level_bar_remove_offset_value(l, GTK_LEVEL_BAR_OFFSET_HIGH);
gtk_level_bar_remove_offset_value(l, GTK_LEVEL_BAR_OFFSET_FULL);
gtk_widget_set_hexpand(lb, TRUE);
return lb;
}
MOONBIT_FFI_EXPORT void mm_gtk_levelbar_set(GtkWidget *lb, double v) {
gtk_level_bar_set_value(GTK_LEVEL_BAR(lb), v);
}
/* ---- generic widget properties ------------------------------------------ */ /* ---- generic widget properties ------------------------------------------ */
MOONBIT_FFI_EXPORT void mm_gtk_widget_set_tooltip(GtkWidget *w, MOONBIT_FFI_EXPORT void mm_gtk_widget_set_tooltip(GtkWidget *w,
@@ -356,8 +373,10 @@ MOONBIT_FFI_EXPORT void mm_gtk_widget_set_valign_center(GtkWidget *w) {
MOONBIT_FFI_EXPORT int32_t mm_gtk_save_png(GtkWidget *w, moonbit_bytes_t path) { MOONBIT_FFI_EXPORT int32_t mm_gtk_save_png(GtkWidget *w, moonbit_bytes_t path) {
int width = gtk_widget_get_width(w), height = gtk_widget_get_height(w); int width = gtk_widget_get_width(w), height = gtk_widget_get_height(w);
GtkNative *native = gtk_widget_get_native(w); GtkNative *native = gtk_widget_get_native(w);
if (width <= 0 || height <= 0 || !native) if (width <= 0 || height <= 0 || !native) {
fprintf(stderr, "moonmix: save_png: not realized (%dx%d)\n", width, height);
return 0; return 0;
}
GdkPaintable *paintable = gtk_widget_paintable_new(w); GdkPaintable *paintable = gtk_widget_paintable_new(w);
GtkSnapshot *snap = gtk_snapshot_new(); GtkSnapshot *snap = gtk_snapshot_new();
gdk_paintable_snapshot(paintable, snap, width, height); gdk_paintable_snapshot(paintable, snap, width, height);
@@ -368,6 +387,8 @@ MOONBIT_FFI_EXPORT int32_t mm_gtk_save_png(GtkWidget *w, moonbit_bytes_t path) {
graphene_rect_t bounds = GRAPHENE_RECT_INIT(0, 0, width, height); graphene_rect_t bounds = GRAPHENE_RECT_INIT(0, 0, width, height);
GdkTexture *tex = gsk_renderer_render_texture(r, node, &bounds); GdkTexture *tex = gsk_renderer_render_texture(r, node, &bounds);
ok = gdk_texture_save_to_png(tex, s(path)); ok = gdk_texture_save_to_png(tex, s(path));
if (!ok)
fprintf(stderr, "moonmix: save_png: writing %s failed\n", s(path));
g_object_unref(tex); g_object_unref(tex);
gsk_render_node_unref(node); gsk_render_node_unref(node);
} }
+3
View File
@@ -12,6 +12,8 @@ pub fn init_gtk() -> Bool
pub fn label(String) -> Widget pub fn label(String) -> Widget
pub fn level_bar() -> Widget
pub fn load_css(String) -> Unit pub fn load_css(String) -> Unit
pub fn notebook(on_switch? : (Int32) -> Unit) -> Widget pub fn notebook(on_switch? : (Int32) -> Unit) -> Widget
@@ -58,6 +60,7 @@ pub fn Widget::set_child(Self, Self) -> Unit
pub fn Widget::set_hexpand(Self, Bool) -> Unit pub fn Widget::set_hexpand(Self, Bool) -> Unit
pub fn Widget::set_icon(Self, String) -> Unit pub fn Widget::set_icon(Self, String) -> Unit
pub fn Widget::set_items(Self, Array[String], Int32) -> Unit pub fn Widget::set_items(Self, Array[String], Int32) -> Unit
pub fn Widget::set_level(Self, Double) -> Unit
pub fn Widget::set_margins(Self, Int32) -> Unit pub fn Widget::set_margins(Self, Int32) -> Unit
pub fn Widget::set_page(Self, Int32) -> Unit pub fn Widget::set_page(Self, Int32) -> Unit
pub fn Widget::set_sensitive(Self, Bool) -> Unit pub fn Widget::set_sensitive(Self, Bool) -> Unit
+36
View File
@@ -0,0 +1,36 @@
// Peak meter display: maps a linear sample peak to the bar position and
// lets the bar fall back smoothly instead of flickering.
///|
/// How much of the full bar a falling meter drops per update (~25 updates
/// per second, so silence empties a full bar in about a second).
pub const METER_DECAY : Double = 0.04
///|
/// Bar position 0..1 for a linear peak. Uses the same cubic curve as the
/// volume sliders, so a full-scale signal at 50% volume shows at half the bar
/// and quiet sounds are still visible.
pub fn meter_level(linear_peak : Double) -> Double {
if linear_peak <= 0.0 {
0.0
} else if linear_peak >= 1.0 {
1.0
} else {
@math.cbrt(linear_peak)
}
}
///|
/// Next bar position: jump up at once, fall by at most METER_DECAY.
pub fn meter_step(shown : Double, level : Double) -> Double {
if level >= shown {
level
} else {
let fallen = shown - METER_DECAY
if fallen > level {
fallen
} else {
level
}
}
}
+18
View File
@@ -0,0 +1,18 @@
///|
test "meter_level uses the cubic volume curve and clamps" {
assert_eq(@model.meter_level(0.0), 0.0)
assert_eq(@model.meter_level(-0.5), 0.0)
assert_eq(@model.meter_level(1.0), 1.0)
assert_eq(@model.meter_level(1.7), 1.0)
assert_true((@model.meter_level(0.125) - 0.5).abs() < 1.0e-9)
}
///|
test "meter_step rises at once and decays slowly" {
assert_eq(@model.meter_step(0.2, 0.9), 0.9)
assert_true(
(@model.meter_step(0.9, 0.0) - (0.9 - @model.METER_DECAY)).abs() < 1.0e-9,
)
assert_eq(@model.meter_step(0.5, 0.48), 0.48)
assert_eq(@model.meter_step(0.01, 0.0), 0.0)
}
+6
View File
@@ -8,6 +8,8 @@ import {
// Values // Values
pub const MAX_PERCENT : Double = 150.0 pub const MAX_PERCENT : Double = 150.0
pub const METER_DECAY : Double = 0.04
pub const NORM_PERCENT : Double = 100.0 pub const NORM_PERCENT : Double = 100.0
pub fn clamp_percent(Double) -> Double pub fn clamp_percent(Double) -> Double
@@ -30,6 +32,10 @@ pub fn linear_to_percent(Double) -> Double
pub fn linked_percent(Array[Double]) -> Double pub fn linked_percent(Array[Double]) -> Double
pub fn meter_level(Double) -> Double
pub fn meter_step(Double, Double) -> Double
pub fn percent_to_linear(Double) -> Double pub fn percent_to_linear(Double) -> Double
pub fn rows(State, Tab) -> Array[Row] pub fn rows(State, Tab) -> Array[Row]
+15 -5
View File
@@ -78,16 +78,17 @@ wait_for() {
# can wedge its event queue, after which nothing gets linked. # can wedge its event queue, after which nothing gets linked.
wait_for '\[default' wait_for '\[default'
LOGS="$XDG_RUNTIME_DIR" LOGS="$XDG_RUNTIME_DIR"
# Two minutes of stereo s16 48 kHz silence as a WAV file (header written by # Two minutes of stereo s16 48 kHz noise as a WAV file (header written by
# hand: no python/sox needed). Reading raw audio from /dev/zero made older # hand: no python/sox needed), so the peak meters have a signal; it only
# pw-cat (PipeWire 1.4) exit without creating a stream. # plays into the private null sinks. Reading raw audio from a device made
# older pw-cat (PipeWire 1.4) exit without creating a stream, so it is a file.
le32() { printf "\\$(printf %03o $(($1 & 255)))\\$(printf %03o $(($1 >> 8 & 255)))\\$(printf %03o $(($1 >> 16 & 255)))\\$(printf %03o $(($1 >> 24 & 255)))"; } le32() { printf "\\$(printf %03o $(($1 & 255)))\\$(printf %03o $(($1 >> 8 & 255)))\\$(printf %03o $(($1 >> 16 & 255)))\\$(printf %03o $(($1 >> 24 & 255)))"; }
DATA=23040000 DATA=23040000
{ printf 'RIFF'; le32 $((DATA + 36)); printf 'WAVEfmt '; le32 16 { printf 'RIFF'; le32 $((DATA + 36)); printf 'WAVEfmt '; le32 16
printf '\001\000\002\000'; le32 48000; le32 192000; printf '\004\000\020\000' printf '\001\000\002\000'; le32 48000; le32 192000; printf '\004\000\020\000'
printf 'data'; le32 $DATA; head -c $DATA /dev/zero; } > "$LOGS/silence.wav" printf 'data'; le32 $DATA; head -c $DATA /dev/urandom; } > "$LOGS/noise.wav"
{ pw-play -P '{ application.name = "Test Player" media.name = "Smoke test tone" }' \ { pw-play -P '{ application.name = "Test Player" media.name = "Smoke test tone" }' \
"$LOGS/silence.wav"; echo "pw-play exited with $?"; } >"$LOGS/play.log" 2>&1 & PIDS="$PIDS $!" "$LOGS/noise.wav"; echo "pw-play exited with $?"; } >"$LOGS/play.log" 2>&1 & PIDS="$PIDS $!"
pw-cat --record --raw --rate 48000 --channels 1 --format s16 \ pw-cat --record --raw --rate 48000 --channels 1 --format s16 \
-P '{ application.name = "Test Recorder" media.name = "Mic capture" }' \ -P '{ application.name = "Test Recorder" media.name = "Mic capture" }' \
/dev/null >"$LOGS/record.log" 2>&1 & PIDS="$PIDS $!" /dev/null >"$LOGS/record.log" 2>&1 & PIDS="$PIDS $!"
@@ -118,6 +119,15 @@ step 'Test Headphones | .*\[default\]' default test_headphones
STREAM=$("$PROBE" | awk -F: '/Test Player/ {gsub(/ /,"",$1); print $1; exit}') STREAM=$("$PROBE" | awk -F: '/Test Player/ {gsub(/ /,"",$1); print $1; exit}')
step 'Test Player | .*-> Test Speakers' move "${STREAM:-0}" test_speakers step 'Test Player | .*-> Test Speakers' move "${STREAM:-0}" test_speakers
# meter <node>: a peak meter on it must see the noise.
meter() {
echo "### meter $1"
"$PROBE" meter "$1" >"$OUT" 2>&1 || { echo "FAIL: no signal on $1's meter"; fail=1; }
grep '^== meter' "$OUT"
}
meter "${STREAM:-0}"
meter test_speakers
if [ "$fail" != 0 ]; then if [ "$fail" != 0 ]; then
echo "### diagnostics" echo "### diagnostics"
echo "--- pw-play playback:"; cat "$LOGS/play.log" echo "--- pw-play playback:"; cat "$LOGS/play.log"
+8
View File
@@ -6,6 +6,14 @@ import {
} }
// Values // Values
pub fn meter_start(Int32, @model.NodeKind) -> Bool
pub fn meter_stop(Int32) -> Unit
pub fn meter_stop_all() -> Unit
pub fn meter_take(Int32) -> Double?
pub fn move_stream(Int32, Int32) -> Bool pub fn move_stream(Int32, Int32) -> Bool
pub fn node_ids() -> Array[Int32] pub fn node_ids() -> Array[Int32]
+50 -1
View File
@@ -103,6 +103,18 @@ extern "C" fn ffi_set_default(kind : Int32, id : Int32) -> Int32 = "mm_wp_set_de
///| ///|
extern "C" fn ffi_move_stream(stream : Int32, device : Int32) -> Int32 = "mm_wp_move_stream" extern "C" fn ffi_move_stream(stream : Int32, device : Int32) -> Int32 = "mm_wp_move_stream"
///|
extern "C" fn ffi_meter_start(id : Int32, kind : Int32) -> Int32 = "mm_wp_meter_start"
///|
extern "C" fn ffi_meter_stop(id : Int32) = "mm_wp_meter_stop"
///|
extern "C" fn ffi_meter_stop_all() = "mm_wp_meter_stop_all"
///|
extern "C" fn ffi_meter_take(id : Int32) -> Double = "mm_wp_meter_take"
///| ///|
/// NUL-terminated UTF-8 for C. /// NUL-terminated UTF-8 for C.
fn cstr(s : String) -> Bytes { fn cstr(s : String) -> Bytes {
@@ -158,7 +170,9 @@ pub fn node_prop(id : Int32, key : String) -> String {
///| ///|
/// Current state of a node as a model node, or None if it is gone. /// Current state of a node as a model node, or None if it is gone.
pub fn read_node(id : Int32) -> @model.Node? { pub fn read_node(id : Int32) -> @model.Node? {
if ffi_node_exists(id) == 0 { // Peak-meter streams (ours, pavucontrol's via pipewire-pulse) are not
// something to show or control.
if ffi_node_exists(id) == 0 || node_prop(id, "stream.monitor") == "true" {
return None return None
} }
let nch = ffi_query_volume(id) let nch = ffi_query_volume(id)
@@ -264,3 +278,38 @@ pub fn set_default_source(id : Int32) -> Bool {
pub fn move_stream(stream_id : Int32, device_id : Int32) -> Bool { pub fn move_stream(stream_id : Int32, device_id : Int32) -> Bool {
ffi_move_stream(stream_id, device_id) != 0 ffi_move_stream(stream_id, device_id) != 0
} }
///|
/// Start a live peak meter on a sink, source or playback stream (other
/// kinds have nothing to meter). True if one is running for `id`.
pub fn meter_start(id : Int32, kind : @model.NodeKind) -> Bool {
let k = match kind {
Sink => 0
Source => 1
PlaybackStream => 2
RecordStream | Other => return false
}
ffi_meter_start(id, k) != 0
}
///|
pub fn meter_stop(id : Int32) -> Unit {
ffi_meter_stop(id)
}
///|
pub fn meter_stop_all() -> Unit {
ffi_meter_stop_all()
}
///|
/// Linear peak (0..1, may exceed 1 when clipping) since the last call, or
/// None if `id` has no meter.
pub fn meter_take(id : Int32) -> Double? {
let p = ffi_meter_take(id)
if p < 0.0 {
None
} else {
Some(p)
}
}
+149 -1
View File
@@ -7,7 +7,10 @@
* - the "mixer-api" plugin for per-channel volume and mute (it handles * - the "mixer-api" plugin for per-channel volume and mute (it handles
* device routes for hardware sinks, so it is what pavucontrol's numbers * device routes for hardware sinks, so it is what pavucontrol's numbers
* correspond to); * correspond to);
* - the "default-nodes-api" plugin for the default sink/source. * - the "default-nodes-api" plugin for the default sink/source;
* - peak meters: a small capture pw_stream per monitored node, created on
* WirePlumber's own pw_core (the same connection), like the peak streams
* pipewire-pulse creates for pavucontrol.
* *
* MoonBit gets a single callback (kind, id) for every change and pulls the * MoonBit gets a single callback (kind, id) for every change and pulls the
* details it needs through small accessor functions. All calls happen on the * details it needs through small accessor functions. All calls happen on the
@@ -16,6 +19,8 @@
#include <string.h> #include <string.h>
#include <wp/wp.h> #include <wp/wp.h>
#include <pipewire/keys.h> #include <pipewire/keys.h>
#include <pipewire/stream.h>
#include <spa/param/audio/format-utils.h>
#include "moonbit.h" #include "moonbit.h"
enum { enum {
@@ -141,9 +146,12 @@ static void on_defaults_changed(WpPlugin *p, gpointer d) {
emit(MM_EV_DEFAULTS_CHANGED, 0); emit(MM_EV_DEFAULTS_CHANGED, 0);
} }
static void forget_meters(void);
static void on_disconnected(WpCore *core, gpointer d) { static void on_disconnected(WpCore *core, gpointer d) {
(void)core; (void)core;
(void)d; (void)d;
forget_meters();
emit(MM_EV_DISCONNECTED, 0); emit(MM_EV_DISCONNECTED, 0);
} }
@@ -460,3 +468,143 @@ MOONBIT_FFI_EXPORT int32_t mm_wp_move_stream(int32_t stream_id,
wp_metadata_set(m, (guint32)stream_id, "target.object", "Spa:Id", serial); wp_metadata_set(m, (guint32)stream_id, "target.object", "Spa:Id", serial);
return 1; return 1;
} }
/* ---- peak meters ---------------------------------------------------------- */
/* One capture stream per monitored node. Not RT_PROCESS, so `process` runs
* on the main loop; it only folds the buffer into `peak`, which the GUI reads
* (and resets) from a timer. */
typedef struct {
struct pw_stream *stream;
struct spa_hook listener;
float peak;
} MmMeter;
static GHashTable *g_meters; /* node id -> MmMeter* */
static void meter_process(void *data) {
MmMeter *m = data;
struct pw_buffer *b = pw_stream_dequeue_buffer(m->stream);
if (!b)
return;
struct spa_buffer *buf = b->buffer;
if (buf->n_datas > 0 && buf->datas[0].data) {
struct spa_data *d = &buf->datas[0];
uint32_t off = SPA_MIN(d->chunk->offset, d->maxsize);
uint32_t size = SPA_MIN(d->chunk->size, d->maxsize - off);
const float *f = SPA_PTROFF(d->data, off, const float);
float peak = m->peak;
for (uint32_t i = 0; i < size / sizeof(float); i++) {
float v = f[i] < 0 ? -f[i] : f[i];
if (v > peak)
peak = v;
}
m->peak = peak;
}
pw_stream_queue_buffer(m->stream, b);
}
static const struct pw_stream_events meter_events = {
PW_VERSION_STREAM_EVENTS,
.process = meter_process,
};
static void meter_free(gpointer p) {
MmMeter *m = p;
if (m->stream)
pw_stream_destroy(m->stream);
g_free(m);
}
/* Start a peak meter on node `id`. `kind`: 0 = sink (captures its monitor),
* 1 = source, 2 = playback stream. Returns 1 if a meter runs (or already
* ran) for it. */
MOONBIT_FFI_EXPORT int32_t mm_wp_meter_start(int32_t id, int32_t kind) {
if (!g_core || !wp_core_is_connected(g_core))
return 0;
if (!g_meters)
g_meters = g_hash_table_new_full(NULL, NULL, NULL, meter_free);
if (g_hash_table_contains(g_meters, GINT_TO_POINTER(id)))
return 1;
g_autoptr(WpNode) node = lookup_node((guint32)id);
if (!node)
return 0;
const char *serial = wp_pipewire_object_get_property(
WP_PIPEWIRE_OBJECT(node), PW_KEY_OBJECT_SERIAL);
struct pw_core *pwc = wp_core_get_pw_core(g_core);
if (!serial || !pwc)
return 0;
struct pw_properties *props = pw_properties_new(
PW_KEY_MEDIA_TYPE, "Audio", PW_KEY_MEDIA_CATEGORY, "Capture",
PW_KEY_MEDIA_ROLE, "DSP", PW_KEY_NODE_NAME, "moonmix-peak",
PW_KEY_APP_NAME, "moonmix", PW_KEY_STREAM_MONITOR, "true",
PW_KEY_TARGET_OBJECT, serial, PW_KEY_NODE_DONT_RECONNECT, "true",
NULL);
if (kind == 0)
pw_properties_set(props, PW_KEY_STREAM_CAPTURE_SINK, "true");
/* Don't keep outputs running just to meter them; a source is opened so
* its level shows, like pavucontrol does. */
if (kind != 1)
pw_properties_set(props, PW_KEY_NODE_PASSIVE, "true");
MmMeter *m = g_new0(MmMeter, 1);
m->stream = pw_stream_new(pwc, "moonmix peak meter", props);
if (!m->stream) {
g_free(m);
return 0;
}
pw_stream_add_listener(m->stream, &m->listener, &meter_events, m);
uint8_t buffer[512];
struct spa_pod_builder pb = SPA_POD_BUILDER_INIT(buffer, sizeof buffer);
struct spa_audio_info_raw info = {.format = SPA_AUDIO_FORMAT_F32,
.channels = 1};
const struct spa_pod *params[1] = {
spa_format_audio_raw_build(&pb, SPA_PARAM_EnumFormat, &info)};
if (pw_stream_connect(m->stream, PW_DIRECTION_INPUT, PW_ID_ANY,
PW_STREAM_FLAG_AUTOCONNECT |
PW_STREAM_FLAG_MAP_BUFFERS |
PW_STREAM_FLAG_DONT_RECONNECT,
params, 1) < 0) {
meter_free(m);
return 0;
}
g_hash_table_insert(g_meters, GINT_TO_POINTER(id), m);
return 1;
}
/* The streams belong to the pw_core, which libpipewire tears down (with
* them) on disconnect: drop our records without touching the streams. */
static void forget_meters(void) {
if (!g_meters)
return;
GHashTableIter it;
gpointer v;
g_hash_table_iter_init(&it, g_meters);
while (g_hash_table_iter_next(&it, NULL, &v))
((MmMeter *)v)->stream = NULL;
g_hash_table_remove_all(g_meters);
}
MOONBIT_FFI_EXPORT void mm_wp_meter_stop(int32_t id) {
if (g_meters)
g_hash_table_remove(g_meters, GINT_TO_POINTER(id));
}
MOONBIT_FFI_EXPORT void mm_wp_meter_stop_all(void) {
if (g_meters)
g_hash_table_remove_all(g_meters);
}
/* Highest absolute sample since the last call (linear, 0..1+), then resets;
* -1 if node `id` has no meter. */
MOONBIT_FFI_EXPORT double mm_wp_meter_take(int32_t id) {
MmMeter *m = g_meters ? g_hash_table_lookup(g_meters, GINT_TO_POINTER(id))
: NULL;
if (!m)
return -1.0;
double p = m->peak;
m->peak = 0;
return p;
}