From c55883b8ad4002bb2f674966dcdcc687c6cccdef Mon Sep 17 00:00:00 2001 From: Sprite Date: Sun, 22 Nov 2026 22:28:50 +0000 Subject: [PATCH] feature: WirePlumber binding and headless probe Thin C layer over libwireplumber-0.5: an object manager for audio nodes, links and the default metadata, plus the mixer-api and default-nodes-api plugins (what wpctl uses internally) for volume, mute and defaults. Streams are moved by setting target.object in the default metadata, as pipewire-pulse does. No CLI tools are spawned. tools/pkg-cc wraps the C compiler to append pkg-config flags because moon does not expand $(pkg-config ...) in moon.pkg link options. moonmix-probe prints what each tab shows and can apply one action. Co-Authored-By: Claude Opus 5.5 --- cmd/moonmix-probe/main.mbt | 146 +++++++++ cmd/moonmix-probe/moon.pkg | 15 + cmd/moonmix-probe/pkg.generated.mbti | 12 + model/pkg.generated.mbti | 2 + tools/pkg-ar | 3 + tools/pkg-cc | 7 + wp/moon.pkg | 14 + wp/pkg.generated.mbti | 58 ++++ wp/wp.mbt | 266 +++++++++++++++ wp/wp_stub.c | 462 +++++++++++++++++++++++++++ 10 files changed, 985 insertions(+) create mode 100644 cmd/moonmix-probe/main.mbt create mode 100644 cmd/moonmix-probe/moon.pkg create mode 100644 cmd/moonmix-probe/pkg.generated.mbti create mode 100755 tools/pkg-ar create mode 100755 tools/pkg-cc create mode 100644 wp/moon.pkg create mode 100644 wp/pkg.generated.mbti create mode 100644 wp/wp.mbt create mode 100644 wp/wp_stub.c diff --git a/cmd/moonmix-probe/main.mbt b/cmd/moonmix-probe/main.mbt new file mode 100644 index 0000000..99a6d3c --- /dev/null +++ b/cmd/moonmix-probe/main.mbt @@ -0,0 +1,146 @@ +// moonmix-probe: headless companion to the GUI. Connects through the same +// WirePlumber binding and model, prints what each tab would show, and can +// apply one action. Used for smoke tests and debugging without a display. +// +// moonmix-probe print all tabs +// may be a numeric node id or a node.name. +// +// moonmix-probe volume set linked volume (cubic %) +// moonmix-probe mute <0|1> +// moonmix-probe default make sink/source the default +// moonmix-probe move route a stream to a device + +///| +extern "C" fn c_exit(code : Int32) = "exit" + +///| +fn print_state(state : @model.State) -> Unit { + for tab in @model.Tab::all() { + println("== \{tab.label()}") + let rows = @model.rows(state, tab) + if rows.length() == 0 { + println(" (none)") + } + for r in rows { + let flags = [] + if r.is_default { + flags.push("default") + } + if r.mute { + flags.push("muted") + } + if r.current_choice >= 0 { + flags.push("-> " + r.choices[r.current_choice].label) + } + let vol = if r.has_volume { r.volume_text } else { "(no volume)" } + let f = if flags.length() > 0 { + " [" + flags.join(", ") + "]" + } else { + "" + } + println(" \{r.id}: \{r.title} | \{vol} | ch=\{r.volumes.length()}\{f}") + } + } +} + +///| +fn parse(s : String) -> Double { + @string.parse_double(s) catch { + _ => { + println("moonmix-probe: not a number: \{s}") + c_exit(2) + 0.0 + } + } +} + +///| +/// Node id from a number or a node.name. +fn resolve(state : @model.State, s : String) -> Int32 { + for id, n in state.nodes { + if n.name == s { + return id + } + } + parse(s).to_int() +} + +///| +fn act(state : @model.State, args : Array[String]) -> Bool { + match args { + ["volume", id, pct] => { + let id = resolve(state, id) + let vols = match state.nodes.get(id) { + Some(n) => n.volumes + None => [] + } + @wp.set_volumes(id, @model.scale_linked(vols, parse(pct))) + } + ["mute", id, on] => @wp.set_mute(resolve(state, id), on == "1") + ["default", id] => { + let id = resolve(state, id) + match state.nodes.get(id).map(fn(n) { n.kind() }) { + Some(Sink) => @wp.set_default_sink(id) + Some(Source) => @wp.set_default_source(id) + _ => false + } + } + ["move", stream, dev] => + @wp.move_stream(resolve(state, stream), resolve(state, dev)) + _ => { + println("moonmix-probe: unknown command") + false + } + } +} + +///| +fn main { + let argv = @env.args() + let args = if argv.length() > 1 { argv[1:].to_owned() } else { [] } + let state = @model.State::new() + @wp.on_event(fn(ev) { + for e in @wp.to_model_events(ev) { + let _ = state.apply(e) + } + match ev { + // default-nodes-api reports defaults shortly after Ready: settle first. + Ready => @wp.timeout(300, 2) + Timeout(2) => { + print_state(state) + if args.length() > 0 { + let ok = act(state, args) + println( + "== action \{args.join(" ")}: \{if ok { "ok" } else { "FAILED" }}", + ) + @wp.timeout(800, 1) + } else { + @wp.quit() + } + } + Timeout(1) => { + print_state(state) + @wp.quit() + } + PluginError => { + println("moonmix-probe: WirePlumber API modules failed to load") + c_exit(3) + } + Disconnected => { + println("moonmix-probe: disconnected") + c_exit(4) + } + Timeout(99) => { + println("moonmix-probe: timed out waiting for WirePlumber") + c_exit(5) + } + _ => () + } + }) + if !@wp.start() { + println("moonmix-probe: cannot connect to PipeWire") + c_exit(1) + } + @wp.timeout(10000, 99) + @wp.run() +} diff --git a/cmd/moonmix-probe/moon.pkg b/cmd/moonmix-probe/moon.pkg new file mode 100644 index 0000000..5c56157 --- /dev/null +++ b/cmd/moonmix-probe/moon.pkg @@ -0,0 +1,15 @@ +// Headless probe: prints what each tab shows, can apply one action. +import { + "geordi/moonmix/model", + "geordi/moonmix/wp", + "moonbitlang/core/env", + "moonbitlang/core/string", +} + +supported_targets = "-all+native" + +pkgtype(kind: "executable") + +options( + link: { "native": { "cc": "tools/pkg-cc" } }, +) diff --git a/cmd/moonmix-probe/pkg.generated.mbti b/cmd/moonmix-probe/pkg.generated.mbti new file mode 100644 index 0000000..2dd55fb --- /dev/null +++ b/cmd/moonmix-probe/pkg.generated.mbti @@ -0,0 +1,12 @@ +// Generated using `moon info`, DON'T EDIT IT +package "geordi/moonmix/cmd/moonmix-probe" + +// Values + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/model/pkg.generated.mbti b/model/pkg.generated.mbti index 6120584..214fcde 100644 --- a/model/pkg.generated.mbti +++ b/model/pkg.generated.mbti @@ -12,6 +12,8 @@ pub const NORM_PERCENT : Double = 100.0 pub fn clamp_percent(Double) -> Double +pub fn compare_text(String, String) -> Int32 + pub fn diff_rows(Array[Row], Array[Row]) -> Diff pub fn display_title(Node) -> String diff --git a/tools/pkg-ar b/tools/pkg-ar new file mode 100755 index 0000000..f1bbc9d --- /dev/null +++ b/tools/pkg-ar @@ -0,0 +1,3 @@ +#!/bin/sh +# Archiver companion of tools/pkg-cc (moon derives its name from the cc name). +exec "${MOONMIX_AR:-ar}" "$@" diff --git a/tools/pkg-cc b/tools/pkg-cc new file mode 100755 index 0000000..8ab738d --- /dev/null +++ b/tools/pkg-cc @@ -0,0 +1,7 @@ +#!/bin/sh +# C compiler wrapper used by moon.pkg (link.native.stub-cc / cc): moon does +# not expand $(pkg-config ...) in flags, so append them here. Works for both +# compiling stubs and linking the final executable. +set -e +PKGS="${MOONMIX_PKGS:-libpipewire-0.3 wireplumber-0.5 gtk4}" +exec "${MOONMIX_CC:-cc}" "$@" $(pkg-config --cflags --libs $PKGS) diff --git a/wp/moon.pkg b/wp/moon.pkg new file mode 100644 index 0000000..36b8dde --- /dev/null +++ b/wp/moon.pkg @@ -0,0 +1,14 @@ +// WirePlumber/PipeWire binding (native only). See wp_stub.c. +import { + "geordi/moonmix/model", + "moonbitlang/core/encoding/utf8", +} + +supported_targets = "-all+native" + +options( + "native-stub": [ "wp_stub.c" ], + // moon does not expand $(pkg-config ...) in flags; tools/pkg-cc appends + // `pkg-config --cflags --libs` for PipeWire, WirePlumber and GTK4. + link: { "native": { "stub-cc": "tools/pkg-cc" } }, +) diff --git a/wp/pkg.generated.mbti b/wp/pkg.generated.mbti new file mode 100644 index 0000000..5935921 --- /dev/null +++ b/wp/pkg.generated.mbti @@ -0,0 +1,58 @@ +// Generated using `moon info`, DON'T EDIT IT +package "geordi/moonmix/wp" + +import { + "geordi/moonmix/model", +} + +// Values +pub fn move_stream(Int32, Int32) -> Bool + +pub fn node_ids() -> Array[Int32] + +pub fn node_prop(Int32, String) -> String + +pub fn on_event((Event) -> Unit) -> Unit + +pub fn quit() -> Unit + +pub fn read_defaults() -> @model.Event + +pub fn read_links() -> Array[@model.Link] + +pub fn read_node(Int32) -> @model.Node? + +pub fn run() -> Unit + +pub fn set_default_sink(Int32) -> Bool + +pub fn set_default_source(Int32) -> Bool + +pub fn set_mute(Int32, Bool) -> Bool + +pub fn set_volumes(Int32, Array[Double]) -> Bool + +pub fn start() -> Bool + +pub fn timeout(Int32, Int32) -> Unit + +pub fn to_model_events(Event) -> Array[@model.Event] + +// Errors + +// Types and methods +pub(all) enum Event { + NodeAdded(Int32) + NodeChanged(Int32) + NodeRemoved(Int32) + LinksChanged + DefaultsChanged + Ready + Disconnected + PluginError + Timeout(Int32) +} + +// Type aliases + +// Traits diff --git a/wp/wp.mbt b/wp/wp.mbt new file mode 100644 index 0000000..4f00618 --- /dev/null +++ b/wp/wp.mbt @@ -0,0 +1,266 @@ +// MoonBit side of the WirePlumber binding (see wp_stub.c). +// +// `start` connects to PipeWire through libwireplumber and loads the +// mixer-api and default-nodes-api plugins. Every change arrives as an +// `Event` through the handler; `read_node`, `read_links` and +// `read_defaults` turn the current WirePlumber state into @model events. + +///| +pub(all) enum Event { + NodeAdded(Int32) + NodeChanged(Int32) + NodeRemoved(Int32) + LinksChanged + DefaultsChanged + /// Plugins loaded and initial object set known: do a full sync. + Ready + Disconnected + /// A plugin failed to load (wireplumber modules missing?). + PluginError + /// One-shot timer from `timeout`, carrying its tag. + Timeout(Int32) +} + +///| +fn decode_event(kind : Int32, id : Int32) -> Event? { + match kind { + 1 => Some(NodeAdded(id)) + 2 => Some(NodeChanged(id)) + 3 => Some(NodeRemoved(id)) + 4 => Some(LinksChanged) + 5 => Some(DefaultsChanged) + 6 => Some(Ready) + 7 => Some(Disconnected) + 8 => Some(PluginError) + 9 => Some(Timeout(id)) + _ => None + } +} + +///| +extern "C" fn ffi_set_handler( + call : FuncRef[((Int32, Int32) -> Unit, Int32, Int32) -> Unit], + closure : (Int32, Int32) -> Unit, +) = "mm_wp_set_handler" + +///| +extern "C" fn ffi_start() -> Int32 = "mm_wp_start" + +///| +extern "C" fn ffi_timeout(ms : Int32, tag : Int32) = "mm_wp_timeout" + +///| +extern "C" fn ffi_run() = "mm_wp_run" + +///| +extern "C" fn ffi_quit() = "mm_wp_quit" + +///| +extern "C" fn ffi_node_count() -> Int32 = "mm_wp_node_count" + +///| +extern "C" fn ffi_node_id_at(i : Int32) -> Int32 = "mm_wp_node_id_at" + +///| +extern "C" fn ffi_node_exists(id : Int32) -> Int32 = "mm_wp_node_exists" + +///| +#borrow(key) +extern "C" fn ffi_node_prop(id : Int32, key : Bytes) -> Bytes = "mm_wp_node_prop" + +///| +extern "C" fn ffi_query_volume(id : Int32) -> Int32 = "mm_wp_query_volume" + +///| +extern "C" fn ffi_volume_at(ch : Int32) -> Double = "mm_wp_volume_at" + +///| +extern "C" fn ffi_mute() -> Int32 = "mm_wp_mute" + +///| +extern "C" fn ffi_link_count() -> Int32 = "mm_wp_link_count" + +///| +extern "C" fn ffi_link_end(i : Int32, input : Int32) -> Int32 = "mm_wp_link_end" + +///| +extern "C" fn ffi_default_node(kind : Int32) -> Int32 = "mm_wp_default_node" + +///| +#borrow(vols) +extern "C" fn ffi_set_volumes( + id : Int32, + vols : FixedArray[Double], + n : Int32, +) -> Int32 = "mm_wp_set_volumes" + +///| +extern "C" fn ffi_set_mute(id : Int32, mute : Int32) -> Int32 = "mm_wp_set_mute" + +///| +extern "C" fn ffi_set_default(kind : Int32, id : Int32) -> Int32 = "mm_wp_set_default" + +///| +extern "C" fn ffi_move_stream(stream : Int32, device : Int32) -> Int32 = "mm_wp_move_stream" + +///| +/// NUL-terminated UTF-8 for C. +fn cstr(s : String) -> Bytes { + let b = @utf8.encode(s) + let n = b.length() + Bytes::makei(n + 1, fn(i) { if i < n { b[i] } else { b'\x00' } }) +} + +///| +/// Register the single event handler. Call before `start`. +pub fn on_event(f : (Event) -> Unit) -> Unit { + ffi_set_handler(fn(g, kind, id) { g(kind, id) }, fn(kind, id) { + match decode_event(kind, id) { + Some(ev) => f(ev) + None => () + } + }) +} + +///| +/// Connect to PipeWire. False if the daemon is not reachable. +pub fn start() -> Bool { + ffi_start() == 0 +} + +///| +pub fn timeout(ms : Int32, tag : Int32) -> Unit { + ffi_timeout(ms, tag) +} + +///| +/// Run a plain GLib main loop (headless tools; the GUI runs GTK's loop). +pub fn run() -> Unit { + ffi_run() +} + +///| +pub fn quit() -> Unit { + ffi_quit() +} + +///| +pub fn node_ids() -> Array[Int32] { + let n = ffi_node_count() + Array::makei(n, fn(i) { ffi_node_id_at(i) }) +} + +///| +pub fn node_prop(id : Int32, key : String) -> String { + @utf8.decode_lossy(ffi_node_prop(id, cstr(key))) +} + +///| +/// Current state of a node as a model node, or None if it is gone. +pub fn read_node(id : Int32) -> @model.Node? { + if ffi_node_exists(id) == 0 { + return None + } + let nch = ffi_query_volume(id) + let volumes = Array::makei(nch, fn(ch) { ffi_volume_at(ch) }) + let mute = ffi_mute() != 0 + let description = { + let d = node_prop(id, "node.description") + if d != "" { + d + } else { + node_prop(id, "node.nick") + } + } + let icon = { + let a = node_prop(id, "application.icon-name") + if a != "" { + a + } else { + node_prop(id, "device.icon-name") + } + } + Some( + @model.Node::new( + id, + node_prop(id, "media.class"), + name=node_prop(id, "node.name"), + description~, + app_name=node_prop(id, "application.name"), + media_name=node_prop(id, "media.name"), + icon_name=icon, + volumes~, + mute~, + ), + ) +} + +///| +pub fn read_links() -> Array[@model.Link] { + let n = ffi_link_count() + Array::makei(n, fn(i) { + { output_node: ffi_link_end(i, 0), input_node: ffi_link_end(i, 1), } + }) +} + +///| +pub fn read_defaults() -> @model.Event { + Defaults(sink=ffi_default_node(0), source=ffi_default_node(1)) +} + +///| +/// Translate a WirePlumber event into model events (pulling fresh data). +pub fn to_model_events(ev : Event) -> Array[@model.Event] { + match ev { + NodeAdded(id) | NodeChanged(id) => + match read_node(id) { + Some(n) => [Upsert(n)] + None => [] + } + NodeRemoved(id) => [Remove(id)] + LinksChanged => [Links(read_links())] + DefaultsChanged => [read_defaults()] + Ready => { + let evs : Array[@model.Event] = [Reset] + for id in node_ids() { + match read_node(id) { + Some(n) => evs.push(Upsert(n)) + None => () + } + } + evs.push(Links(read_links())) + evs.push(read_defaults()) + evs + } + Disconnected => [Reset] + PluginError | Timeout(_) => [] + } +} + +///| +/// Set linear channel volumes. +pub fn set_volumes(id : Int32, volumes : Array[Double]) -> Bool { + let arr = FixedArray::makei(volumes.length(), fn(i) { volumes[i] }) + ffi_set_volumes(id, arr, arr.length()) != 0 +} + +///| +pub fn set_mute(id : Int32, mute : Bool) -> Bool { + ffi_set_mute(id, if mute { 1 } else { 0 }) != 0 +} + +///| +pub fn set_default_sink(id : Int32) -> Bool { + ffi_set_default(0, id) != 0 +} + +///| +pub fn set_default_source(id : Int32) -> Bool { + ffi_set_default(1, id) != 0 +} + +///| +/// Route a playback/record stream to another sink/source. +pub fn move_stream(stream_id : Int32, device_id : Int32) -> Bool { + ffi_move_stream(stream_id, device_id) != 0 +} diff --git a/wp/wp_stub.c b/wp/wp_stub.c new file mode 100644 index 0000000..fa3dc4e --- /dev/null +++ b/wp/wp_stub.c @@ -0,0 +1,462 @@ +/* + * moonmix: thin C layer over libwireplumber-0.5. + * + * Exactly what wpctl does internally, without spawning wpctl: + * - a WpObjectManager watching audio WpNodes, WpLinks and the "default" + * WpMetadata; + * - the "mixer-api" plugin for per-channel volume and mute (it handles + * device routes for hardware sinks, so it is what pavucontrol's numbers + * correspond to); + * - the "default-nodes-api" plugin for the default sink/source. + * + * 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 + * GLib default main context (shared with GTK), so no locking is needed. + */ +#include +#include +#include +#include "moonbit.h" + +enum { + MM_EV_NODE_ADDED = 1, + MM_EV_NODE_CHANGED = 2, + MM_EV_NODE_REMOVED = 3, + MM_EV_LINKS_CHANGED = 4, + MM_EV_DEFAULTS_CHANGED = 5, + MM_EV_READY = 6, + MM_EV_DISCONNECTED = 7, + MM_EV_ERROR = 8, + MM_EV_TIMEOUT = 9, +}; + +typedef void (*mm_call_t)(void *closure, int32_t kind, int32_t id); + +static mm_call_t g_call; +static void *g_closure; +static WpCore *g_core; +static WpObjectManager *g_om; +static WpPlugin *g_mixer; +static WpPlugin *g_defaults; +static GMainLoop *g_loop; +static int g_pending; +static gboolean g_om_installed; +static gboolean g_ready_sent; + +static void emit(int32_t kind, int32_t id) { + if (g_call) { + /* MoonBit functions take ownership of their arguments. */ + moonbit_incref(g_closure); + g_call(g_closure, kind, id); + } +} + +MOONBIT_FFI_EXPORT void mm_wp_set_handler(mm_call_t call, void *closure) { + if (g_closure) + moonbit_decref(g_closure); + g_call = call; + g_closure = closure; /* owned, kept for the program lifetime */ +} + +/* ---- helpers ------------------------------------------------------------ */ + +static moonbit_bytes_t to_bytes(const char *s) { + size_t n = s ? strlen(s) : 0; + moonbit_bytes_t b = moonbit_make_bytes((int32_t)n, 0); + if (n) + memcpy(b, s, n); + return b; +} + +static WpNode *lookup_node(guint32 id) { + if (!g_om) + return NULL; + return wp_object_manager_lookup(g_om, WP_TYPE_NODE, + WP_CONSTRAINT_TYPE_G_PROPERTY, "bound-id", + "=u", id, NULL); +} + +static WpMetadata *lookup_default_metadata(void) { + if (!g_om) + return NULL; + return wp_object_manager_lookup(g_om, WP_TYPE_METADATA, + WP_CONSTRAINT_TYPE_PW_GLOBAL_PROPERTY, + "metadata.name", "=s", "default", NULL); +} + +static void maybe_ready(void) { + if (!g_ready_sent && g_pending == 0 && g_om_installed) { + g_ready_sent = TRUE; + emit(MM_EV_READY, 0); + } +} + +/* ---- signal handlers ---------------------------------------------------- */ + +static void on_node_props(GObject *obj, GParamSpec *pspec, gpointer data) { + (void)pspec; + (void)data; + emit(MM_EV_NODE_CHANGED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj))); +} + +static void on_object_added(WpObjectManager *om, GObject *obj, gpointer d) { + (void)om; + (void)d; + if (WP_IS_NODE(obj)) { + g_signal_connect(obj, "notify::properties", G_CALLBACK(on_node_props), + NULL); + emit(MM_EV_NODE_ADDED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj))); + } else if (WP_IS_LINK(obj)) { + emit(MM_EV_LINKS_CHANGED, 0); + } +} + +static void on_object_removed(WpObjectManager *om, GObject *obj, gpointer d) { + (void)om; + (void)d; + if (WP_IS_NODE(obj)) { + g_signal_handlers_disconnect_by_func(obj, on_node_props, NULL); + emit(MM_EV_NODE_REMOVED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj))); + } else if (WP_IS_LINK(obj)) { + emit(MM_EV_LINKS_CHANGED, 0); + } +} + +static void on_installed(WpObjectManager *om, gpointer d) { + (void)om; + (void)d; + g_om_installed = TRUE; + maybe_ready(); +} + +static void on_mixer_changed(WpPlugin *p, guint id, gpointer d) { + (void)p; + (void)d; + emit(MM_EV_NODE_CHANGED, (int32_t)id); +} + +static void on_defaults_changed(WpPlugin *p, gpointer d) { + (void)p; + (void)d; + emit(MM_EV_DEFAULTS_CHANGED, 0); +} + +static void on_disconnected(WpCore *core, gpointer d) { + (void)core; + (void)d; + emit(MM_EV_DISCONNECTED, 0); +} + +static void on_plugin_loaded(GObject *src, GAsyncResult *res, gpointer d) { + const char *plugin_name = d; + g_autoptr(GError) error = NULL; + if (!wp_core_load_component_finish(WP_CORE(src), res, &error)) { + g_warning("moonmix: failed to load %s: %s", plugin_name, + error ? error->message : "?"); + emit(MM_EV_ERROR, 1); + return; + } + if (g_str_equal(plugin_name, "mixer-api")) { + g_mixer = wp_plugin_find(g_core, "mixer-api"); + if (g_mixer) { + /* 0 = linear: report raw channelVolumes, the MoonBit side does the + * cubic (pavucontrol) mapping. */ + g_object_set(g_mixer, "scale", 0, NULL); + g_signal_connect(g_mixer, "changed", G_CALLBACK(on_mixer_changed), + NULL); + } + } else { + g_defaults = wp_plugin_find(g_core, "default-nodes-api"); + if (g_defaults) + g_signal_connect(g_defaults, "changed", G_CALLBACK(on_defaults_changed), + NULL); + } + g_pending--; + if (g_pending == 0) { + /* Install the object manager only after the plugins are up, like wpctl + * does, so the first full sync already has volumes and defaults. */ + wp_core_install_object_manager(g_core, g_om); + } + maybe_ready(); +} + +/* ---- lifecycle ---------------------------------------------------------- */ + +/* Returns 0 on success, -1 if PipeWire is not reachable. Events follow on + * the main loop; MM_EV_READY once the initial state is known. */ +MOONBIT_FFI_EXPORT int32_t mm_wp_start(void) { + if (g_core) + return 0; + wp_init(WP_INIT_PIPEWIRE | WP_INIT_SPA_TYPES | WP_INIT_SET_GLIB_LOG); + + g_autoptr(WpProperties) props = + wp_properties_new(PW_KEY_APP_NAME, "moonmix", NULL); + g_core = wp_core_new(NULL, NULL, g_steal_pointer(&props)); + if (!wp_core_connect(g_core)) { + g_clear_object(&g_core); + return -1; + } + g_signal_connect(g_core, "disconnected", G_CALLBACK(on_disconnected), NULL); + + g_om = wp_object_manager_new(); + wp_object_manager_add_interest(g_om, WP_TYPE_NODE, + WP_CONSTRAINT_TYPE_PW_PROPERTY, "media.class", + "#s", "*Audio*", NULL); + wp_object_manager_add_interest(g_om, WP_TYPE_LINK, NULL); + wp_object_manager_add_interest(g_om, WP_TYPE_METADATA, + WP_CONSTRAINT_TYPE_PW_GLOBAL_PROPERTY, + "metadata.name", "=s", "default", NULL); + wp_object_manager_request_object_features( + g_om, WP_TYPE_GLOBAL_PROXY, WP_PIPEWIRE_OBJECT_FEATURES_MINIMAL); + wp_object_manager_request_object_features(g_om, WP_TYPE_METADATA, + WP_OBJECT_FEATURES_ALL); + g_signal_connect(g_om, "object-added", G_CALLBACK(on_object_added), NULL); + g_signal_connect(g_om, "object-removed", G_CALLBACK(on_object_removed), + NULL); + g_signal_connect(g_om, "installed", G_CALLBACK(on_installed), NULL); + + g_pending = 2; + wp_core_load_component(g_core, "libwireplumber-module-mixer-api", "module", + NULL, NULL, NULL, + (GAsyncReadyCallback)on_plugin_loaded, + (gpointer) "mixer-api"); + wp_core_load_component(g_core, "libwireplumber-module-default-nodes-api", + "module", NULL, NULL, NULL, + (GAsyncReadyCallback)on_plugin_loaded, + (gpointer) "default-nodes-api"); + return 0; +} + +static gboolean on_timeout(gpointer d) { + emit(MM_EV_TIMEOUT, GPOINTER_TO_INT(d)); + return G_SOURCE_REMOVE; +} + +/* One-shot timer delivering MM_EV_TIMEOUT with `tag` as id. */ +MOONBIT_FFI_EXPORT void mm_wp_timeout(int32_t ms, int32_t tag) { + g_timeout_add((guint)ms, on_timeout, GINT_TO_POINTER(tag)); +} + +/* Standalone main loop for the headless probe (the GUI uses GTK's). */ +MOONBIT_FFI_EXPORT void mm_wp_run(void) { + if (!g_loop) + g_loop = g_main_loop_new(NULL, FALSE); + g_main_loop_run(g_loop); +} + +MOONBIT_FFI_EXPORT void mm_wp_quit(void) { + if (g_loop) + g_main_loop_quit(g_loop); +} + +/* ---- queries ------------------------------------------------------------ */ + +static GArray *g_ids; /* snapshot for mm_wp_node_count/mm_wp_node_id_at */ + +MOONBIT_FFI_EXPORT int32_t mm_wp_node_count(void) { + if (!g_ids) + g_ids = g_array_new(FALSE, FALSE, sizeof(guint32)); + g_array_set_size(g_ids, 0); + if (!g_om) + return 0; + g_autoptr(WpIterator) it = wp_object_manager_new_filtered_iterator( + g_om, WP_TYPE_NODE, NULL); + g_auto(GValue) val = G_VALUE_INIT; + for (; wp_iterator_next(it, &val); g_value_unset(&val)) { + guint32 id = wp_proxy_get_bound_id(WP_PROXY(g_value_get_object(&val))); + g_array_append_val(g_ids, id); + } + return (int32_t)g_ids->len; +} + +MOONBIT_FFI_EXPORT int32_t mm_wp_node_id_at(int32_t i) { + if (!g_ids || i < 0 || (guint)i >= g_ids->len) + return -1; + return (int32_t)g_array_index(g_ids, guint32, i); +} + +MOONBIT_FFI_EXPORT int32_t mm_wp_node_exists(int32_t id) { + g_autoptr(WpNode) node = lookup_node((guint32)id); + return node != NULL; +} + +/* A PipeWire property of a node ("node.name", "media.class", ...), "" if + * unset. `key` is NUL-terminated UTF-8. */ +MOONBIT_FFI_EXPORT moonbit_bytes_t mm_wp_node_prop(int32_t id, + moonbit_bytes_t key) { + g_autoptr(WpNode) node = lookup_node((guint32)id); + const char *v = NULL; + if (node) + v = wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node), + (const char *)key); + return to_bytes(v); +} + +/* Volume of the last queried node. */ +#define MM_MAX_CH 64 +static double g_vol[MM_MAX_CH]; +static int g_nch; +static int g_mute; + +/* Asks mixer-api for a node's volume. Returns the channel count (0 if the + * node has no volume control yet), then read mm_wp_volume_at / mm_wp_mute. */ +MOONBIT_FFI_EXPORT int32_t mm_wp_query_volume(int32_t id) { + g_nch = 0; + g_mute = 0; + if (!g_mixer) + return 0; + GVariant *v = NULL; + g_signal_emit_by_name(g_mixer, "get-volume", (guint)id, &v); + if (!v) + return 0; + gboolean mute = FALSE; + g_variant_lookup(v, "mute", "b", &mute); + g_mute = mute; + g_autoptr(GVariant) chans = + g_variant_lookup_value(v, "channelVolumes", G_VARIANT_TYPE_VARDICT); + if (chans) { + GVariantIter iter; + const char *key; + GVariant *ch; + g_variant_iter_init(&iter, chans); + while (g_variant_iter_loop(&iter, "{&sv}", &key, &ch)) { + int idx = atoi(key); + double vol = 0; + if (idx >= 0 && idx < MM_MAX_CH && g_variant_lookup(ch, "volume", "d", &vol)) { + g_vol[idx] = vol; + if (idx + 1 > g_nch) + g_nch = idx + 1; + } + } + } else { + double vol; + if (g_variant_lookup(v, "volume", "d", &vol)) { + g_vol[0] = vol; + g_nch = 1; + } + } + g_variant_unref(v); + return g_nch; +} + +MOONBIT_FFI_EXPORT double mm_wp_volume_at(int32_t ch) { + return (ch >= 0 && ch < g_nch) ? g_vol[ch] : 0.0; +} + +MOONBIT_FFI_EXPORT int32_t mm_wp_mute(void) { return g_mute; } + +/* Links snapshot. */ +static GArray *g_links; + +MOONBIT_FFI_EXPORT int32_t mm_wp_link_count(void) { + if (!g_links) + g_links = g_array_new(FALSE, FALSE, sizeof(guint32) * 2); + g_array_set_size(g_links, 0); + if (!g_om) + return 0; + g_autoptr(WpIterator) it = wp_object_manager_new_filtered_iterator( + g_om, WP_TYPE_LINK, NULL); + g_auto(GValue) val = G_VALUE_INIT; + for (; wp_iterator_next(it, &val); g_value_unset(&val)) { + guint32 pair[2] = {0, 0}; + guint32 out_port, in_port; + wp_link_get_linked_object_ids(WP_LINK(g_value_get_object(&val)), &pair[0], + &out_port, &pair[1], &in_port); + g_array_append_val(g_links, pair); + } + return (int32_t)g_links->len; +} + +MOONBIT_FFI_EXPORT int32_t mm_wp_link_end(int32_t i, int32_t input) { + if (!g_links || i < 0 || (guint)i >= g_links->len) + return -1; + guint32 *pair = &g_array_index(g_links, guint32, i * 2); + return (int32_t)pair[input ? 1 : 0]; +} + +static const char *class_for(int32_t kind) { + return kind == 0 ? "Audio/Sink" : "Audio/Source"; +} + +/* Default node id for kind 0 = sink, 1 = source; -1 if none. */ +MOONBIT_FFI_EXPORT int32_t mm_wp_default_node(int32_t kind) { + if (!g_defaults) + return -1; + guint32 id = SPA_ID_INVALID; + g_signal_emit_by_name(g_defaults, "get-default-node", class_for(kind), &id); + return id == SPA_ID_INVALID ? -1 : (int32_t)id; +} + +/* ---- actions ------------------------------------------------------------ */ + +/* Set linear per-channel volumes. */ +MOONBIT_FFI_EXPORT int32_t mm_wp_set_volumes(int32_t id, double *vols, + int32_t n) { + if (!g_mixer || n <= 0) + return 0; + GVariantBuilder chans; + g_variant_builder_init(&chans, G_VARIANT_TYPE_VARDICT); + for (int i = 0; i < n; i++) { + GVariantBuilder ch; + g_variant_builder_init(&ch, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&ch, "{sv}", "volume", g_variant_new_double(vols[i])); + char key[16]; + g_snprintf(key, sizeof key, "%d", i); + g_variant_builder_add(&chans, "{sv}", key, g_variant_builder_end(&ch)); + } + GVariantBuilder b; + g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&b, "{sv}", "channelVolumes", + g_variant_builder_end(&chans)); + gboolean ok = FALSE; + g_signal_emit_by_name(g_mixer, "set-volume", (guint)id, + g_variant_builder_end(&b), &ok); + return ok; +} + +MOONBIT_FFI_EXPORT int32_t mm_wp_set_mute(int32_t id, int32_t mute) { + if (!g_mixer) + return 0; + GVariantBuilder b; + g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&b, "{sv}", "mute", g_variant_new_boolean(mute != 0)); + gboolean ok = FALSE; + g_signal_emit_by_name(g_mixer, "set-volume", (guint)id, + g_variant_builder_end(&b), &ok); + return ok; +} + +/* Make node `id` the configured default sink (kind 0) or source (kind 1). */ +MOONBIT_FFI_EXPORT int32_t mm_wp_set_default(int32_t kind, int32_t id) { + if (!g_defaults) + return 0; + g_autoptr(WpNode) node = lookup_node((guint32)id); + if (!node) + return 0; + const char *name = wp_pipewire_object_get_property(WP_PIPEWIRE_OBJECT(node), + PW_KEY_NODE_NAME); + if (!name) + return 0; + gboolean ok = FALSE; + g_signal_emit_by_name(g_defaults, "set-default-configured-node-name", + class_for(kind), name, &ok); + return ok; +} + +/* Route a stream to another device, the way pipewire-pulse implements + * pavucontrol's move: set "target.object" (the device's object.serial) on + * the stream in the "default" metadata; WirePlumber relinks it. */ +MOONBIT_FFI_EXPORT int32_t mm_wp_move_stream(int32_t stream_id, + int32_t device_id) { + g_autoptr(WpMetadata) m = lookup_default_metadata(); + g_autoptr(WpNode) dev = lookup_node((guint32)device_id); + if (!m || !dev) + return 0; + const char *serial = wp_pipewire_object_get_property( + WP_PIPEWIRE_OBJECT(dev), PW_KEY_OBJECT_SERIAL); + if (!serial) + return 0; + wp_metadata_set(m, (guint32)stream_id, "target.node", NULL, NULL); + wp_metadata_set(m, (guint32)stream_id, "target.object", "Spa:Id", serial); + return 1; +}