From e16cc1b2ad4cfebfc0d9baf35776143a46ae4397 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sun, 29 Nov 2026 19:26:29 -0800 Subject: [PATCH] Name Chrome streams after their browser tabs A browser extension reports audible tabs to moonmix-tabs-host, which matches them to PipeWire streams by time and publishes the names for the mixer; streams of one tab share a row. Ambiguous streams keep the browser's name. Without the extension, a browser's only running stream shows its MPRIS title. The smoke test no longer claims real audio hardware. Co-Authored-By: Claude Opus 5.5 --- .sweet/quiet-named-tab.md | 5 + Containerfile | 1 + README.md | 50 ++- cmd/moonmix-probe/main.mbt | 5 + cmd/moonmix-probe/moon.pkg | 1 + cmd/moonmix-tabs-host/main.mbt | 118 +++++++ cmd/moonmix-tabs-host/moon.pkg | 14 + cmd/moonmix-tabs-host/pkg.generated.mbti | 13 + cmd/moonmix/main.mbt | 68 +++- cmd/moonmix/moon.pkg | 1 + extension/background.js | 68 ++++ extension/manifest.json | 10 + justfile | 4 + model/moon.pkg | 2 + model/pkg.generated.mbti | 60 +++- model/state.mbt | 62 +++- model/tabs.mbt | 394 +++++++++++++++++++++++ model/tabs_test.mbt | 191 +++++++++++ model/view.mbt | 43 ++- tabs/moon.pkg | 13 + tabs/pkg.generated.mbti | 43 +++ tabs/tabs.mbt | 134 ++++++++ tabs/tabs_stub.c | 336 +++++++++++++++++++ tools/fake-browser.py | 44 +++ tools/install-browser-tabs.py | 79 +++++ tools/moonmix-container | 8 + tools/smoke-test.sh | 23 ++ tools/test-container.py | 8 + wp/moon.pkg | 1 + wp/wp.mbt | 12 + wp/wp_stub.c | 34 ++ 31 files changed, 1830 insertions(+), 15 deletions(-) create mode 100644 .sweet/quiet-named-tab.md create mode 100644 cmd/moonmix-tabs-host/main.mbt create mode 100644 cmd/moonmix-tabs-host/moon.pkg create mode 100644 cmd/moonmix-tabs-host/pkg.generated.mbti create mode 100644 extension/background.js create mode 100644 extension/manifest.json create mode 100644 model/tabs.mbt create mode 100644 model/tabs_test.mbt create mode 100644 tabs/moon.pkg create mode 100644 tabs/pkg.generated.mbti create mode 100644 tabs/tabs.mbt create mode 100644 tabs/tabs_stub.c create mode 100644 tools/fake-browser.py create mode 100755 tools/install-browser-tabs.py diff --git a/.sweet/quiet-named-tab.md b/.sweet/quiet-named-tab.md new file mode 100644 index 0000000..ab632ef --- /dev/null +++ b/.sweet/quiet-named-tab.md @@ -0,0 +1,5 @@ +--- +type: feature +--- + +Name Chrome's audio streams after their browser tabs, one row per tab, with an optional browser extension and native-messaging host; without it, a browser's only running stream shows its MPRIS title. diff --git a/Containerfile b/Containerfile index 9a659f1..d3630f6 100644 --- a/Containerfile +++ b/Containerfile @@ -19,6 +19,7 @@ COPY cmd/ cmd/ COPY model/ model/ COPY wp/ wp/ COPY gtk/ gtk/ +COPY tabs/ tabs/ COPY tools/pkg-cc tools/pkg-ar tools/ RUN moon build --target native --release \ && install -Dm755 _build/native/release/build/cmd/moonmix/moonmix.exe /out/usr/local/bin/moonmix \ diff --git a/README.md b/README.md index a16cd96..8e888df 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ on top of libpipewire-0.3. It never runs `wpctl`, `pactl`, `pw-cli`, - **Playback**: every application stream, with a volume slider, mute and the output device it plays to (choose another to move it). +- **Browser tabs**: with the [browser extension](#browser-tabs), Chrome's + streams are named after their tabs, one row per tab. - **Recording**: capture streams, same controls, input device selector. - **Output Devices** / **Input Devices**: sinks and sources with volume, mute and a *Default* toggle that shows and sets the default device. @@ -55,6 +57,9 @@ sliders, monitor sources in Input Devices, meters for recording streams. ``` cmd/moonmix GUI: builds tabs, reconciles widgets with view rows cmd/moonmix-probe headless CLI over the same stack (smoke tests, debugging) +cmd/moonmix-tabs-host native-messaging host: names browser streams by tab +extension/ the browser extension it talks to +tabs/ tab name files and MPRIS: tabs_stub.c + tabs.mbt model/ pure MoonBit: volume curve, state reducer, view model wp/ WirePlumber binding: wp_stub.c + wp.mbt gtk/ minimal hand-written GTK4 binding: gtk_stub.c + gtk.mbt @@ -103,6 +108,45 @@ flowchart LR scroll handling (10% per detent, swallowing every scroll) with one that asks MoonBit synchronously whether the slider or the list gets the event. +## Browser tabs + +Chrome opens separate audio streams for each tab (one for the media elements +of the page and its frames, others for Web Audio), so each tab already has its +own volume, mute, output and meter. But every stream is called "Google +Chrome / Playback". To name them: + +```sh +just install-browser-tabs +``` + +then open `chrome://extensions`, turn on *Developer mode*, choose *Load +unpacked* and select `~/.local/share/moonmix/extension`. This works for +Chrome, Chromium, Brave, Edge and Vivaldi installed natively (a Flatpak or +Snap browser cannot start the host). `tools/install-browser-tabs.py +--uninstall` removes it again. + +- The **extension** tells **moonmix-tabs-host** (native messaging, started by + the browser) which tabs are audible, with their titles. It sends no page + addresses and nothing about silent or incognito tabs, and nothing leaves + the machine. Its `tabs` permission does allow it to see titles and + addresses of all tabs. +- The browser does not say which stream is which tab's. The host sees streams + start and tabs become audible, and **matches them by time** + (`model/tabs.mbt`), or by elimination when only one tab can be meant. It + runs as long as the browser, so the mixer need not be open. It publishes + the matches in `$XDG_RUNTIME_DIR/moonmix/` (mode 0700). +- **Ambiguous streams keep the browser's name**: tabs that start within the + same moment, or several that were already playing when the host started. + Pausing one and playing it again resolves it. +- Streams of one tab share a row, which controls all of them. + +Without the extension, a browser's only running stream shows the title the +browser publishes over **MPRIS**. WirePlumber remembers volumes per +application, so a new tab starts at the volume last set for any tab. + +The container image only reads the published names: the host and extension +are installed natively. + ## Appearance moonmix reads the desktop's **accent colour** and **colour scheme** from the @@ -223,7 +267,8 @@ set `MOONMIX_IMAGE` to run a different local tag. The runner maps your user ID and mounts only the Wayland and PipeWire sockets (including `PIPEWIRE_RUNTIME_DIR` / `PIPEWIRE_REMOTE` overrides), -`$XDG_RUNTIME_DIR/bus` when present for desktop appearance settings, and +`$XDG_RUNTIME_DIR/bus` when present for desktop appearance settings, +`$XDG_RUNTIME_DIR/moonmix` (browser tab names) read-only, and whichever standard host icon, pixmap and `.desktop` directories exist (`/usr/share/{icons,pixmaps,applications}`, Flatpak exports and `$XDG_DATA_HOME/{icons,applications}`) read-only under `/run/moonmix/host/`. @@ -308,7 +353,8 @@ tools/smoke-test.sh /tmp/shot # needs pipewire, wireplumber, pw-cat, gtk4- `XDG_RUNTIME_DIR`. The instance has two null sinks, a loopback virtual 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, checks that peak -meters on the stream and its sink see the signal, +meters on the stream and its sink see the signal, checks tab naming with a +fake browser (`tools/fake-browser.py`), then starts the GUI under GTK's broadway backend. With `MOONMIX_SCREENSHOT` set, the GUI renders each tab offscreen to a PNG and exits. If `python3` with PyGObject and `dbus-daemon` are available, it then starts a private diff --git a/cmd/moonmix-probe/main.mbt b/cmd/moonmix-probe/main.mbt index 8abe698..ed167b5 100644 --- a/cmd/moonmix-probe/main.mbt +++ b/cmd/moonmix-probe/main.mbt @@ -35,6 +35,9 @@ fn print_state(state : @model.State) -> Unit { flags.push("-> " + r.choices[r.current_choice].label) } let vol = if r.has_volume { r.volume_text } else { "(no volume)" } + if r.members.length() > 1 { + flags.push("\{r.members.length()} streams") + } let f = if flags.length() > 0 { " [" + flags.join(", ") + "]" } else { @@ -110,6 +113,8 @@ fn main { // default-nodes-api reports defaults shortly after Ready: settle first. Ready => @wp.timeout(300, 2) Timeout(2) => { + let names = @model.merge_tab_files(@tabs.files()) + let _ = state.apply(TabNames(names)) print_state(state) if args is ["meter", id] { let id = resolve(state, id) diff --git a/cmd/moonmix-probe/moon.pkg b/cmd/moonmix-probe/moon.pkg index 5c56157..34a9ab7 100644 --- a/cmd/moonmix-probe/moon.pkg +++ b/cmd/moonmix-probe/moon.pkg @@ -1,6 +1,7 @@ // Headless probe: prints what each tab shows, can apply one action. import { "geordi/moonmix/model", + "geordi/moonmix/tabs", "geordi/moonmix/wp", "moonbitlang/core/env", "moonbitlang/core/string", diff --git a/cmd/moonmix-tabs-host/main.mbt b/cmd/moonmix-tabs-host/main.mbt new file mode 100644 index 0000000..2778dcb --- /dev/null +++ b/cmd/moonmix-tabs-host/main.mbt @@ -0,0 +1,118 @@ +// moonmix-tabs-host: started by the browser for the moonmix extension +// (native messaging). It sees tabs become audible and the browser's PipeWire +// streams start, matches the two (@model.TabTracker) and publishes the +// result for the mixer. It runs as long as the browser, so streams that +// started before the mixer was opened have names too. +// +// stdout belongs to the native-messaging protocol: never print. + +///| +extern "C" fn c_exit(code : Int32) = "exit" + +///| +const TICK_MS : Int32 = 500 + +///| +struct Host { + browser : Int32 + state : @model.State + tracker : @model.TabTracker + mut ready : Bool + mut published : @model.TabFile? +} + +///| +fn Host::stop(_ : Host) -> Unit { + @tabs.unpublish() + c_exit(0) +} + +///| +/// Serials of the browser's running playback streams. Its audio service, +/// which owns them, is a child of the browser process. +fn Host::running(self : Host) -> Array[String] { + let out = [] + for _, n in self.state.nodes { + if n.kind() is PlaybackStream && + n.running && + n.parent_pid == self.browser && + n.serial != "" { + out.push(n.serial) + } + } + out +} + +///| +fn Host::update(self : Host) -> Unit { + if !self.ready { + return + } + let now = @tabs.now_ms() + // Another profile of this browser runs its own host with its own tabs. + let others = @tabs.files().filter(fn(f) { f.browser == self.browser }) + self.tracker.settle(now, eliminate=others.length() <= 1) + let file : @model.TabFile = { + browser: self.browser, + streams: self.tracker.matches(), + } + if self.published != Some(file) && @tabs.publish(file) { + self.published = Some(file) + } +} + +///| +fn main { + let host : Host = { + browser: @tabs.browser_pid(), + state: @model.State::new(), + tracker: @model.TabTracker::new(), + ready: false, + published: None, + } + @tabs.prune() + @tabs.on_event(fn(ev) { + match ev { + Message => + match @model.parse_tabs(@tabs.message()) { + Some(tabs) => { + host.tracker.set_tabs(tabs, @tabs.now_ms()) + host.update() + } + None => () + } + Eof => host.stop() + _ => () + } + }) + @wp.on_event(fn(ev) { + for e in @wp.to_model_events(ev) { + let _ = host.state.apply(e) + } + match ev { + Ready => { + host.ready = true + host.tracker.set_streams(host.running(), @tabs.now_ms(), initial=true) + host.update() + @wp.timeout(TICK_MS, 1) + } + Timeout(1) => { + host.update() + @wp.timeout(TICK_MS, 1) + } + // The extension starts a new host, which reconnects. + Disconnected | PluginError => host.stop() + NodeAdded(_) | NodeChanged(_) | NodeRemoved(_) => + if host.ready { + host.tracker.set_streams(host.running(), @tabs.now_ms()) + host.update() + } + _ => () + } + }) + if !@wp.start() { + c_exit(1) + } + @tabs.listen() + @wp.run() +} diff --git a/cmd/moonmix-tabs-host/moon.pkg b/cmd/moonmix-tabs-host/moon.pkg new file mode 100644 index 0000000..15b2378 --- /dev/null +++ b/cmd/moonmix-tabs-host/moon.pkg @@ -0,0 +1,14 @@ +// Native-messaging host: matches browser tabs to PipeWire streams. +import { + "geordi/moonmix/model", + "geordi/moonmix/tabs", + "geordi/moonmix/wp", +} + +supported_targets = "-all+native" + +pkgtype(kind: "executable") + +options( + link: { "native": { "cc": "tools/pkg-cc" } }, +) diff --git a/cmd/moonmix-tabs-host/pkg.generated.mbti b/cmd/moonmix-tabs-host/pkg.generated.mbti new file mode 100644 index 0000000..373df6b --- /dev/null +++ b/cmd/moonmix-tabs-host/pkg.generated.mbti @@ -0,0 +1,13 @@ +// Generated using `moon info`, DON'T EDIT IT +package "geordi/moonmix/cmd/moonmix-tabs-host" + +// Values + +// Errors + +// Types and methods +type Host + +// Type aliases + +// Traits diff --git a/cmd/moonmix/main.mbt b/cmd/moonmix/main.mbt index efdcfa8..585003b 100644 --- a/cmd/moonmix/main.mbt +++ b/cmd/moonmix/main.mbt @@ -152,7 +152,9 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView { match app.find_view(tab, id) { Some(v) => if idx >= 0 && idx < v.row.choices.length() { - let _ = @wp.move_stream(id, v.row.choices[idx].id) + for m in v.row.members { + let _ = @wp.move_stream(m, v.row.choices[idx].id) + } } None => () } @@ -199,7 +201,11 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView { let (mute, mute_tag) = @gtk.toggle( @gtk.resolve_icon(@model.volume_icon_chain(row.percent, row.mute)), "", - fn(on) { let _ = @wp.set_mute(id, on) }, + fn(on) { + for m in app.members(tab, id) { + let _ = @wp.set_mute(m, on) + } + }, ) tags.push(mute_tag) mute.set_tooltip("Mute") @@ -220,6 +226,14 @@ fn new_row_view(app : App, tab : @model.Tab, row : @model.Row) -> RowView { v.last_local_us = @gtk.now_us() v.volume_label.set_text(@model.format_volume(vols)) let _ = @wp.set_volumes(id, vols) + for m in v.row.members { + match app.state.nodes.get(m) { + Some(n) if m != id => + @wp.set_volumes(m, @model.scale_linked(n.volumes, percent)) + |> ignore + _ => () + } + } } None => () } @@ -339,6 +353,15 @@ fn App::find_view(self : App, tab : @model.Tab, id : Int32) -> RowView? { None } +///| +/// Nodes a row controls. +fn App::members(self : App, tab : @model.Tab, id : Int32) -> Array[Int32] { + match self.find_view(tab, id) { + Some(v) => v.row.members + None => [id] + } +} + ///| fn App::sync_default_button(self : App, tab : @model.Tab, id : Int32) -> Unit { match self.find_view(tab, id) { @@ -411,7 +434,9 @@ fn App::sync_meters(self : App) -> Unit { Some(t) => if t.tab.has_meter() { for row in t.rows { - want.set(row.id, t.tab.node_kind()) + for m in row.members { + want.set(m, t.tab.node_kind()) + } } } None => () @@ -450,8 +475,16 @@ fn App::tick_meters(self : App) -> Unit { } match self.tabs.get(self.current.val) { Some(t) => - for id, v in t.views { - match @wp.meter_take(id) { + for _, v in t.views { + let mut loudest : Double? = None + for m in v.row.members { + match (@wp.meter_take(m), loudest) { + (Some(p), Some(l)) => if p > l { loudest = Some(p) } + (Some(p), None) => loudest = Some(p) + (None, _) => () + } + } + match loudest { Some(peak) => { let next = @model.meter_step( v.shown_level, @@ -513,6 +546,30 @@ fn App::on_wp_event(self : App, ev : @wp.Event) -> Unit { } } +///| +/// Follow browser tab names (moonmix-tabs-host) and MPRIS titles. +fn App::follow_tabs(self : App) -> Unit { + fn apply(ev : @model.Event) { + if self.state.apply(ev) { + self.render() + } + } + + fn names() { + apply(TabNames(@model.merge_tab_files(@tabs.files()))) + } + + @tabs.on_event(fn(ev) { + match ev { + Files => names() + Media => apply(MediaTitles(@tabs.media_titles())) + _ => () + } + }) + @tabs.watch() + names() +} + ///| fn build_ui() -> App { @gtk.load_css(CSS) @@ -670,6 +727,7 @@ fn main { if !@wp.start() { app.set_status("Cannot connect to PipeWire. Is pipewire running?") } + app.follow_tabs() app.window.present() app.start_meter_timer() if screenshot is Some(prefix) { diff --git a/cmd/moonmix/moon.pkg b/cmd/moonmix/moon.pkg index d61bdeb..13f857a 100644 --- a/cmd/moonmix/moon.pkg +++ b/cmd/moonmix/moon.pkg @@ -1,6 +1,7 @@ // The GUI. import { "geordi/moonmix/model", + "geordi/moonmix/tabs", "geordi/moonmix/wp", "geordi/moonmix/gtk", "moonbitlang/core/env", diff --git a/extension/background.js b/extension/background.js new file mode 100644 index 0000000..90a9a71 --- /dev/null +++ b/extension/background.js @@ -0,0 +1,68 @@ +// Reports tabs that play audio to moonmix-tabs-host: id, title and whether +// they are audible now. Tabs that never made a sound, page addresses and +// incognito tabs are never sent. + +const HOST = "org.latha.moonmix.tabs"; +const RETRY_MS = 5000; + +// Tabs heard since the host connected. An open native port keeps this worker +// alive, so nothing needs to be stored. +const heard = new Map(); +let port = null; +let retry = null; + +function send() { + port?.postMessage({ tabs: [...heard.values()] }); +} + +// True if what we would send changed. +function note(tab) { + if (tab.id === undefined || tab.incognito) return false; + const old = heard.get(tab.id); + if (!old && !tab.audible) return false; + const now = { id: tab.id, title: tab.title ?? "", audible: !!tab.audible }; + if (old && old.title === now.title && old.audible === now.audible) return false; + heard.set(tab.id, now); + return true; +} + +async function connect() { + if (port) return; + clearTimeout(retry); + const opened = chrome.runtime.connectNative(HOST); + port = opened; + opened.onDisconnect.addListener(() => { + // Not installed, or PipeWire went away. lastError must be read. + void chrome.runtime.lastError; + if (port !== opened) return; + port = null; + retry = setTimeout(connect, RETRY_MS); + }); + heard.clear(); + for (const tab of await chrome.tabs.query({ audible: true })) note(tab); + send(); +} + +chrome.tabs.onUpdated.addListener((_id, change, tab) => { + if (!port) connect(); + else if (("audible" in change || "title" in change) && note(tab)) send(); +}); + +chrome.tabs.onRemoved.addListener((id) => { + if (heard.delete(id)) send(); +}); + +// Prerendered or discarded tabs can come back with another id. +chrome.tabs.onReplaced.addListener(async (added, removed) => { + let changed = heard.delete(removed); + try { + changed = note(await chrome.tabs.get(added)) || changed; + } catch { + // Already closed. + } + if (changed) send(); +}); + +chrome.runtime.onStartup.addListener(connect); +chrome.runtime.onInstalled.addListener(connect); +connect(); diff --git a/extension/manifest.json b/extension/manifest.json new file mode 100644 index 0000000..5bcff89 --- /dev/null +++ b/extension/manifest.json @@ -0,0 +1,10 @@ +{ + "manifest_version": 3, + "name": "moonmix tab names", + "version": "0.1.0", + "description": "Tells the moonmix volume control which tabs are playing audio.", + "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnwEsdryrEXsxfemPcrhQ0YTkIRqp0paRuD0RDKvQMWibZPHD7+Sx418+ytnaCAcS7AA0YNk97pq89PvmzWbsmXRFyDl0uAFLLsb/ibjdpr28rQ05Usb2Iu7/Lvaz5v7VEaF4qu8kcBhIzGJrheoxTnr0XUDn2/d+uJplpIKoDELgZ4c1qTrXz2kzyNuakr95JT35p/CJNY0vrd7LaauVsJnHwGgqB9FG91hJJgo6wZ27tObIS18yADa26looQJ5ObbXCLtOu6G7i8/ngxQhkfypRlDhKUj0xwYzak4iBMc9Qb1icSpNUjcS/NskUS0prhsQ2gZwPfGPjchaDX+C5WwIDAQAB", + "minimum_chrome_version": "116", + "permissions": ["tabs", "nativeMessaging"], + "background": { "service_worker": "background.js" } +} diff --git a/justfile b/justfile index 359b0f0..9c5ea79 100644 --- a/justfile +++ b/justfile @@ -30,6 +30,10 @@ install: build update-desktop-database "$data_home/applications" fi +# Build and install the browser tab host and extension for your user. +install-browser-tabs: build + python3 tools/install-browser-tabs.py + # Type-check all native packages and check MoonBit formatting. check: moon check --target native diff --git a/model/moon.pkg b/model/moon.pkg index 74586a6..77108b6 100644 --- a/model/moon.pkg +++ b/model/moon.pkg @@ -1,5 +1,7 @@ // Pure logic: volume curves, the audio-graph state reducer and the view // model the GUI renders. No FFI, so `moon test` runs it on any target. import { + "moonbitlang/core/json", "moonbitlang/core/math", + "moonbitlang/core/string", } diff --git a/model/pkg.generated.mbti b/model/pkg.generated.mbti index 007e933..e8fe554 100644 --- a/model/pkg.generated.mbti +++ b/model/pkg.generated.mbti @@ -24,6 +24,12 @@ pub const MIN_UI_CONTRAST : Double = 3.0 pub const NORM_PERCENT : Double = 100.0 +pub const TAB_SETTLE_MS : Int64 = 3000 + +pub const TAB_SLOP_MS : Int64 = 400 + +pub const TAB_WINDOW_MS : Int64 = 1500 + pub const WHEEL_STEP_PERCENT : Double = 2.0 pub fn accent_css(Rgb, Bool) -> String @@ -70,10 +76,16 @@ pub fn linear_to_percent(Double) -> Double pub fn linked_percent(Array[Double]) -> Double +pub fn merge_tab_files(Array[TabFile]) -> Map[String, TabName] + pub fn meter_level(Double) -> Double pub fn meter_step(Double, Double) -> Double +pub fn parse_media_titles(String) -> Map[Int32, String] + +pub fn parse_tabs(String) -> Array[BrowserTab]? + pub fn percent_to_linear(Double) -> Double pub fn readable_fg(Rgb) -> Rgb @@ -110,6 +122,13 @@ pub(all) struct AccentColors { } pub fn AccentColors::new(Rgb, Bool) -> Self +#derive(Eq, @debug.Debug) +pub(all) struct BrowserTab { + id : Int32 + title : String + audible : Bool +} + #derive(Eq, @debug.Debug) pub(all) enum ColorScheme { NoPreference @@ -138,6 +157,8 @@ pub(all) enum Event { Remove(Int32) Links(Array[Link]) Defaults(sink~ : Int32, source~ : Int32) + TabNames(Map[String, TabName]) + MediaTitles(Map[Int32, String]) Reset } @@ -160,11 +181,14 @@ pub(all) struct Node { bus : String app_binary : String app_id : String + serial : String + parent_pid : Int32 + running : Bool volumes : Array[Double] mute : Bool } pub fn Node::kind(Self) -> NodeKind -pub fn Node::new(Int32, String, name? : String, description? : String, app_name? : String, media_name? : String, icon_hints? : Array[String], form_factor? : String, bus? : String, app_binary? : String, app_id? : String, volumes? : Array[Double], mute? : Bool) -> Self +pub fn Node::new(Int32, String, name? : String, description? : String, app_name? : String, media_name? : String, icon_hints? : Array[String], form_factor? : String, bus? : String, app_binary? : String, app_id? : String, serial? : String, parent_pid? : Int32, running? : Bool, volumes? : Array[Double], mute? : Bool) -> Self #derive(Eq, @debug.Debug) pub(all) enum NodeKind { @@ -191,6 +215,7 @@ pub fn Rgb::to_hex(Self) -> String #derive(Eq, @debug.Debug) pub(all) struct Row { id : Int32 + members : Array[Int32] title : String subtitle : String icons : Array[String] @@ -224,11 +249,15 @@ pub(all) struct State { mut links : Array[Link] mut default_sink : Int32 mut default_source : Int32 + mut tab_names : Map[String, TabName] + mut media_titles : Map[Int32, String] } pub fn State::apply(Self, Event) -> Bool +pub fn State::media_title(Self, Node) -> String? pub fn State::new() -> Self pub fn State::nodes_of(Self, NodeKind) -> Array[Node] pub fn State::stream_device(Self, Int32) -> Int32? +pub fn State::tab_of(Self, Node) -> TabName? #derive(Eq, @debug.Debug) pub(all) enum Tab { @@ -244,6 +273,35 @@ pub fn Tab::icon_chain(Self) -> Array[String] pub fn Tab::label(Self) -> String pub fn Tab::node_kind(Self) -> NodeKind +#derive(Eq, @debug.Debug) +pub(all) struct TabFile { + browser : Int32 + streams : Array[(String, Int32, String)] +} +pub fn TabFile::parse(String) -> Self? +pub fn TabFile::to_text(Self) -> String + +#derive(Eq, @debug.Debug) +pub(all) struct TabName { + key : String + title : String +} + +pub struct TabTracker { + streams : Map[String, TrackedStream] + tabs : Map[Int32, TrackedTab] + mut got_tabs : Bool +} +pub fn TabTracker::matches(Self) -> Array[(String, Int32, String)] +pub fn TabTracker::new() -> Self +pub fn TabTracker::set_streams(Self, Array[String], Int64, initial? : Bool) -> Unit +pub fn TabTracker::set_tabs(Self, Array[BrowserTab], Int64) -> Unit +pub fn TabTracker::settle(Self, Int64, eliminate? : Bool) -> Unit + +type TrackedStream + +type TrackedTab + #derive(Eq, @debug.Debug) pub(all) enum WheelRoute { Slider diff --git a/model/state.mbt b/model/state.mbt index 9f12dce..2045ae6 100644 --- a/model/state.mbt +++ b/model/state.mbt @@ -40,6 +40,9 @@ pub(all) struct Node { bus : String // device.bus: "usb", "bluetooth", "pci", ... app_binary : String // application.process.binary app_id : String // pipewire.access.portal.app_id / application.id + serial : String // object.serial, never reused (ids are) + parent_pid : Int32 // parent of application.process.id; 0 if unknown + running : Bool // streams: node state is "running" volumes : Array[Double] // linear, one per channel; empty = no volume mute : Bool } @@ -62,6 +65,9 @@ pub fn Node::new( bus~ : String = "", app_binary~ : String = "", app_id~ : String = "", + serial~ : String = "", + parent_pid~ : Int32 = 0, + running~ : Bool = true, volumes~ : Array[Double] = [], mute~ : Bool = false, ) -> Node { @@ -77,6 +83,9 @@ pub fn Node::new( bus, app_binary, app_id, + serial, + parent_pid, + running, volumes, mute, } @@ -101,6 +110,10 @@ pub(all) enum Event { Links(Array[Link]) /// Current default sink / source node ids (-1 = none). Defaults(sink~ : Int32, source~ : Int32) + /// Streams matched to browser tabs, by object.serial. + TabNames(Map[String, TabName]) + /// Title a browser is playing (MPRIS), by browser pid. + MediaTitles(Map[Int32, String]) /// Connection to PipeWire lost: forget everything. Reset } @@ -111,11 +124,20 @@ pub(all) struct State { mut links : Array[Link] mut default_sink : Int32 mut default_source : Int32 + mut tab_names : Map[String, TabName] + mut media_titles : Map[Int32, String] } ///| pub fn State::new() -> State { - { nodes: {}, links: [], default_sink: -1, default_source: -1, } + { + nodes: {}, + links: [], + default_sink: -1, + default_source: -1, + tab_names: Map([]), + media_titles: Map([]), + } } ///| @@ -152,6 +174,16 @@ pub fn State::apply(self : State, ev : Event) -> Bool { self.default_source = source changed } + TabNames(names) => { + let changed = names != self.tab_names + self.tab_names = names + changed + } + MediaTitles(titles) => { + let changed = titles != self.media_titles + self.media_titles = titles + changed + } Reset => { let changed = self.nodes.length() > 0 || self.links.length() > 0 self.nodes.clear() @@ -226,6 +258,34 @@ pub fn display_title(n : Node) -> String { } } +///| +/// The browser tab a playback stream was matched to. +pub fn State::tab_of(self : State, n : Node) -> TabName? { + if n.kind() is PlaybackStream && n.serial != "" { + self.tab_names.get(n.serial) + } else { + None + } +} + +///| +/// What the stream's browser says it is playing (MPRIS): only when that can +/// only mean this stream, i.e. it is the browser's one running stream. +pub fn State::media_title(self : State, n : Node) -> String? { + if !(n.kind() is PlaybackStream) || n.parent_pid == 0 || !n.running { + return None + } + for _, other in self.nodes { + if other.id != n.id && + other.kind() is PlaybackStream && + other.running && + other.parent_pid == n.parent_pid { + return None + } + } + self.media_titles.get(n.parent_pid) +} + ///| /// Case-insensitive lexicographic comparison for display ordering. /// (MoonBit's built-in String compare orders by length first.) diff --git a/model/tabs.mbt b/model/tabs.mbt new file mode 100644 index 0000000..2851e63 --- /dev/null +++ b/model/tabs.mbt @@ -0,0 +1,394 @@ +// Which browser tab does a playback stream belong to? +// +// Chrome opens its audio streams per tab but gives them all the same +// properties, and its extension API knows which tabs are audible but not +// which stream they use. TabTracker links the two by time: a tab becomes +// audible just after its stream starts running. Whatever stays ambiguous is +// left unnamed; a wrong name is worse than none. + +///| +/// A tab reported by the browser extension. +#derive(Eq, Debug) +pub(all) struct BrowserTab { + id : Int32 + title : String + audible : Bool +} + +///| +/// A tab a stream was matched to, as the mixer shows it. `key` is unique +/// across browsers; streams with the same key share one row. +#derive(Eq, Debug) +pub(all) struct TabName { + key : String + title : String +} + +///| +/// A tab turns audible at most this long after its stream starts. +pub const TAB_WINDOW_MS : Int64 = 1500L + +///| +/// ... and, since the two reports take different paths, at most this long +/// before we see the stream. +pub const TAB_SLOP_MS : Int64 = 400L + +///| +/// Streams older than this may be matched by elimination. +pub const TAB_SETTLE_MS : Int64 = 3000L + +///| +struct TrackedStream { + since : Int64 + /// False when it was already running when tracking began. + seen_start : Bool + mut tab : Int32? + /// Matched by elimination, not by time. + mut weak : Bool + /// Elimination was contradicted: do not try it again. + mut doubt : Bool +} + +///| +struct TrackedTab { + mut title : String + mut audible : Bool + mut since : Int64 + mut seen_start : Bool +} + +///| +pub struct TabTracker { + streams : Map[String, TrackedStream] // by object.serial + tabs : Map[Int32, TrackedTab] + mut got_tabs : Bool +} + +///| +pub fn TabTracker::new() -> TabTracker { + { streams: Map([]), tabs: Map([]), got_tabs: false, } +} + +///| +/// The set of running streams. `initial` for the first, already running set. +/// A stream that stops loses its tab: Chrome reuses idle streams. +pub fn TabTracker::set_streams( + self : TabTracker, + serials : Array[String], + now : Int64, + initial~ : Bool = false, +) -> Unit { + for s in self.streams.keys().to_array() { + if !serials.contains(s) { + self.streams.remove(s) + } + } + for s in serials { + if !self.streams.contains(s) { + self.streams.set(s, { + since: now, + seen_start: !initial, + tab: None, + weak: false, + doubt: false, + }) + } + } +} + +///| +/// All tabs that are or have been audible and are still open. +pub fn TabTracker::set_tabs( + self : TabTracker, + tabs : Array[BrowserTab], + now : Int64, +) -> Unit { + let initial = !self.got_tabs + self.got_tabs = true + for id in self.tabs.keys().to_array() { + if !tabs.any(fn(t) { t.id == id }) { + self.tabs.remove(id) + for _, s in self.streams { + if s.tab == Some(id) { + s.tab = None + } + } + } + } + for t in tabs { + match self.tabs.get(t.id) { + Some(old) => { + old.title = t.title + if t.audible && !old.audible { + old.since = now + old.seen_start = true + } + old.audible = t.audible + } + None => + self.tabs.set(t.id, { + title: t.title, + audible: t.audible, + since: now, + seen_start: !initial, + }) + } + } +} + +///| +fn TabTracker::has_stream(self : TabTracker, tab : Int32) -> Bool { + for _, s in self.streams { + if s.tab == Some(tab) { + return true + } + } + false +} + +///| +fn in_window(s : TrackedStream, t : TrackedTab) -> Bool { + let d = t.since - s.since + s.seen_start && t.seen_start && d >= -TAB_SLOP_MS && d <= TAB_WINDOW_MS +} + +///| +/// Match what can be matched at `now`. `eliminate` must be false when tabs +/// of the same browser may be missing (another profile has its own list). +pub fn TabTracker::settle( + self : TabTracker, + now : Int64, + eliminate~ : Bool = true, +) -> Unit { + if !self.got_tabs { + return + } + if !eliminate { + for _, s in self.streams { + if s.weak { + s.tab = None + s.weak = false + } + } + } + let audible : Array[Int32] = [] + let free_tabs : Array[Int32] = [] + for id, t in self.tabs { + if t.audible { + audible.push(id) + if !self.has_stream(id) { + free_tabs.push(id) + } + } + } + // By time: the stream's only candidate is this tab. Several streams may + // start with one tab (media plus Web Audio), never the reverse. + let found : Array[(TrackedStream, Int32)] = [] + for _, s in self.streams { + if s.tab is None && now - s.since >= TAB_WINDOW_MS { + let near = audible.filter(fn(id) { + match self.tabs.get(id) { + Some(t) => in_window(s, t) + None => false + } + }) + // A tab that already has a stream comes second. + let free = near.filter(fn(id) { free_tabs.contains(id) }) + let cands = if free.length() > 0 { free } else { near } + if cands is [id] { + found.push((s, id)) + } + } + } + for f in found { + f.0.tab = Some(f.1) + f.0.weak = false + } + // A tab has been audible for a while with no stream left for it: one of + // the eliminated matches must be wrong, so drop them all. + let left = free_tabs.filter(fn(id) { !self.has_stream(id) }) + let free_streams : Array[TrackedStream] = [] + let mut pending = false + for _, s in self.streams { + if s.tab is None { + free_streams.push(s) + if now - s.since < TAB_SETTLE_MS { + pending = true + } + } + } + let overdue = left.any(fn(id) { + match self.tabs.get(id) { + Some(t) => now - t.since >= TAB_SETTLE_MS + None => false + } + }) + if overdue && free_streams.length() == 0 { + for _, s in self.streams { + if s.weak { + s.tab = None + s.weak = false + s.doubt = true + } + } + return + } + if !eliminate || pending { + return + } + let settled = left.all(fn(id) { + match self.tabs.get(id) { + Some(t) => now - t.since >= TAB_SETTLE_MS + None => false + } + }) + if !settled { + return + } + let target = if audible is [only] { + // A single tab makes sound: every stream left is its own. + Some(only) + } else if left is [only] && free_streams.length() == 1 { + Some(only) + } else { + None + } + match target { + Some(id) => + for s in free_streams { + if !s.doubt { + s.tab = Some(id) + s.weak = true + } + } + None => () + } +} + +///| +/// Matched streams: (object.serial, tab id, tab title). +pub fn TabTracker::matches(self : TabTracker) -> Array[(String, Int32, String)] { + let out = [] + for serial, s in self.streams { + match s.tab { + Some(id) => + match self.tabs.get(id) { + Some(t) => out.push((serial, id, t.title)) + None => () + } + None => () + } + } + out +} + +///| +/// Parse a message from the extension: +/// `{"tabs":[{"id":1,"title":"...","audible":true}]}`. None if malformed. +pub fn parse_tabs(text : String) -> Array[BrowserTab]? { + let json = @json.parse(text) catch { _ => return None } + guard json is Object({ "tabs": Array(items), .. }) else { return None } + let out = [] + for item in items { + guard item + is Object( + { + "id": Number(id, ..), + "title": String(title), + "audible": True + | False as audible, + .. + } + ) else { + return None + } + out.push({ id: id.to_int(), title, audible: audible is True, }) + } + Some(out) +} + +///| +/// What one tab host publishes: its browser's pid and its matches. +#derive(Eq, Debug) +pub(all) struct TabFile { + browser : Int32 + streams : Array[(String, Int32, String)] // serial, tab id, title +} + +///| +pub fn TabFile::to_text(self : TabFile) -> String { + let streams : Array[Json] = self.streams.map(fn(s) { + let o : Json = { + "serial": Json::string(s.0), + "tab": Json::number(s.1.to_double()), + "title": Json::string(s.2), + } + o + }) + let o : Json = { + "browser": Json::number(self.browser.to_double()), + "streams": Json::array(streams), + } + o.stringify() +} + +///| +pub fn TabFile::parse(text : String) -> TabFile? { + let json = @json.parse(text) catch { _ => return None } + guard json + is Object({ "browser": Number(pid, ..), "streams": Array(items), .. }) else { + return None + } + let streams = [] + for item in items { + guard item + is Object( + { + "serial": String(serial), + "tab": Number(tab, ..), + "title": String(title), + .. + } + ) else { + return None + } + streams.push((serial, tab.to_int(), title)) + } + Some({ browser: pid.to_int(), streams, }) +} + +///| +/// Names for the mixer from every host's file. A stream that two hosts +/// claim (two profiles of one browser) is ambiguous and stays unnamed. +pub fn merge_tab_files(files : Array[TabFile]) -> Map[String, TabName] { + let out : Map[String, TabName] = Map([]) + let clash : Map[String, Bool] = Map([]) + for f in files { + for s in f.streams { + if out.contains(s.0) { + clash.set(s.0, true) + } + out.set(s.0, { key: "\{f.browser}:\{s.1}", title: s.2, }) + } + } + for s, _ in clash { + out.remove(s) + } + out +} + +///| +/// Parse "pid\ttitle" lines. +pub fn parse_media_titles(text : String) -> Map[Int32, String] { + let out : Map[Int32, String] = Map([]) + for line in text.split("\n") { + match line.find("\t") { + Some(i) => { + let pid = @string.parse_int(line[:i]) catch { _ => continue } + out.set(pid, line[i + 1:].to_owned()) + } + None => () + } + } + out +} diff --git a/model/tabs_test.mbt b/model/tabs_test.mbt new file mode 100644 index 0000000..891b0d6 --- /dev/null +++ b/model/tabs_test.mbt @@ -0,0 +1,191 @@ +///| +fn tab(id : Int32, title : String, audible~ : Bool = true) -> @model.BrowserTab { + { id, title, audible, } +} + +///| +/// Names by serial, sorted for comparison. +fn names(t : @model.TabTracker) -> String { + let out = t.matches().map(fn(m) { "\{m.0}=\{m.2}" }) + out.sort_by(@model.compare_text) + out.join(" ") +} + +///| +fn fresh() -> @model.TabTracker { + let t = @model.TabTracker::new() + t.set_streams([], 0L, initial=true) + t.set_tabs([], 0L) + t +} + +///| +test "tabs: matched by when they start, also long afterwards" { + let t = fresh() + t.set_streams(["1"], 1000L) + t.set_tabs([tab(10, "A")], 1300L) + t.settle(1500L) + inspect(names(t), content="") + t.set_streams(["1", "2"], 5000L) + t.set_tabs([tab(10, "A"), tab(11, "B")], 5400L) + t.settle(9000L) + inspect(names(t), content="1=A 2=B") + // A quiet passage and a new title do not lose the match. + t.set_tabs([tab(10, "A2", audible=false), tab(11, "B")], 10000L) + t.settle(20000L) + inspect(names(t), content="1=A2 2=B") +} + +///| +test "tabs: starting together is ambiguous" { + let t = fresh() + t.set_streams(["1", "2"], 1000L) + t.set_tabs([tab(10, "A"), tab(11, "B")], 1300L) + t.settle(20000L) + inspect(names(t), content="") +} + +///| +test "tabs: already playing at start" { + let t = @model.TabTracker::new() + t.set_streams(["1", "2"], 0L, initial=true) + t.set_tabs([tab(10, "A"), tab(11, "B")], 0L) + t.settle(20000L) + inspect(names(t), content="") + // With a single tab there is no doubt. + let t = @model.TabTracker::new() + t.set_streams(["1", "2"], 0L, initial=true) + t.set_tabs([tab(10, "A")], 0L) + t.settle(20000L) + inspect(names(t), content="1=A 2=A") +} + +///| +test "tabs: a second stream of the only tab joins it" { + let t = fresh() + t.set_streams(["1"], 1000L) + t.set_tabs([tab(10, "A")], 1300L) + t.settle(4000L) + t.set_streams(["1", "2"], 5000L) + t.settle(6000L) + inspect(names(t), content="1=A") + t.settle(9000L) + inspect(names(t), content="1=A 2=A") +} + +///| +test "tabs: media and Web Audio of one tab, next to another tab" { + let t = fresh() + t.set_streams(["1"], 1000L) + t.set_tabs([tab(10, "A")], 1300L) + t.settle(4000L) + t.set_streams(["1", "2"], 9000L) + t.set_streams(["1", "2", "3"], 9100L) + t.set_tabs([tab(10, "A"), tab(11, "B")], 9300L) + t.settle(10550L) + t.settle(11000L) + inspect(names(t), content="1=A 2=B 3=B") +} + +///| +test "tabs: a contradicted elimination is dropped for good" { + let t = fresh() + t.set_streams(["1"], 1000L) + t.set_tabs([tab(10, "A")], 1300L) + t.settle(4000L) + // Stream 2 is a silent tab's; B is heard only much later. + t.set_streams(["1", "2"], 5000L) + t.settle(9000L) + inspect(names(t), content="1=A 2=A") + t.set_tabs([tab(10, "A"), tab(11, "B")], 20000L) + t.settle(24000L) + inspect(names(t), content="1=A") + t.settle(30000L) + inspect(names(t), content="1=A") +} + +///| +test "tabs: a stopped stream is forgotten, a closed tab too" { + let t = fresh() + t.set_streams(["1"], 1000L) + t.set_tabs([tab(10, "A")], 1300L) + t.settle(4000L) + t.set_streams([], 5000L) + inspect(names(t), content="") + t.set_streams(["1"], 6000L) + t.set_tabs([tab(11, "B")], 6300L) + t.settle(9000L) + inspect(names(t), content="1=B") + t.set_tabs([], 10000L) + inspect(names(t), content="") +} + +///| +test "tabs: no elimination next to another profile" { + let t = @model.TabTracker::new() + t.set_streams(["1"], 0L, initial=true) + t.set_tabs([tab(10, "A")], 0L) + t.settle(9000L) + inspect(names(t), content="1=A") + t.settle(9500L, eliminate=false) + inspect(names(t), content="") +} + +///| +test "tabs: messages and files" { + let parsed = @model.parse_tabs( + "{\"tabs\":[{\"id\":7,\"title\":\"a \\\"b\\\" é\",\"audible\":true}]}", + ) + assert_true(parsed == Some([tab(7, "a \"b\" é")])) + assert_true(@model.parse_tabs("nope") is None) + assert_true(@model.parse_tabs("{\"tabs\":[{\"id\":\"7\"}]}") is None) + let file : @model.TabFile = { + browser: 5, + streams: [("84", 7, "x\n\"y\""), ("85", 8, "z")], + } + assert_true(@model.TabFile::parse(file.to_text()) == Some(file)) + assert_false(file.to_text().contains("\n")) + assert_true(@model.TabFile::parse("{}") is None) + let other : @model.TabFile = { browser: 5, streams: [("85", 9, "w")], } + let merged = @model.merge_tab_files([file, other]) + inspect(merged.length(), content="1") + inspect(merged.get("84").unwrap().key, content="5:7") + let titles = @model.parse_media_titles("12\tSong\nbad\n") + assert_true(titles.get(12) == Some("Song")) + inspect(titles.length(), content="1") +} + +///| +test "tabs: rows are named and grouped" { + let s = @model.State::new() + for id in [60, 61, 62] { + let _ = s.apply( + Upsert( + @model.Node::new( + id, + "Stream/Output/Audio", + app_name="Google Chrome", + media_name="Playback", + serial="\{id + 100}", + parent_pid=5, + volumes=[1.0], + ), + ), + ) + } + let name : @model.TabName = { key: "5:1", title: "Music", } + assert_true(s.apply(TabNames({ "160": name, "162": name }))) + assert_false(s.apply(TabNames({ "160": name, "162": name }))) + // Three running streams: a browser-wide title says nothing about one. + let _ = s.apply(MediaTitles({ 5: "Song" })) + let rows = @model.rows(s, Playback) + inspect( + rows + .map(fn(r) { "\{r.title}/\{r.subtitle}/\{r.members.length()}" }) + .join(", "), + content="Music/Google Chrome/2, Google Chrome/Playback/1", + ) + let _ = s.apply(Remove(60)) + let _ = s.apply(Remove(62)) + inspect(@model.rows(s, Playback)[0].subtitle, content="Song") +} diff --git a/model/view.mbt b/model/view.mbt index e362990..588b909 100644 --- a/model/view.mbt +++ b/model/view.mbt @@ -58,6 +58,9 @@ pub(all) struct DeviceChoice { #derive(Eq, Debug) pub(all) struct Row { id : Int32 + /// Nodes this row controls: its own id first, then, for a browser tab, the + /// tab's other streams. + members : Array[Int32] title : String subtitle : String /// Icon-theme names to try in order (see icons.mbt). @@ -91,12 +94,33 @@ pub fn rows(state : State, tab : Tab) -> Array[Row] { .map(fn(d) { { id: d.id, name: d.name, label: display_title(d), } }) None => [] } - state - .nodes_of(kind) - .map(fn(n) { + // Streams of one browser tab share a row. + let groups : Map[String, Array[Int32]] = Map([]) + let nodes = state + .nodes_of(kind) + .filter(fn(n) { + match state.tab_of(n) { + Some(t) => + match groups.get(t.key) { + Some(g) => { + g.push(n.id) + false + } + None => { + groups.set(t.key, [n.id]) + true + } + } + None => true + } + }) + nodes.map(fn(n) { let is_stream = device_kind is Some(_) - let subtitle = if is_stream { - n.media_name + let tab = state.tab_of(n) + let subtitle = if tab is Some(_) { + display_title(n) + } else if is_stream { + state.media_title(n).unwrap_or(n.media_name) } else if n.name != display_title(n) { n.name } else { @@ -125,7 +149,14 @@ pub fn rows(state : State, tab : Tab) -> Array[Row] { } { id: n.id, - title: display_title(n), + members: match tab { + Some(t) => groups.get(t.key).unwrap_or([n.id]) + None => [n.id] + }, + title: match tab { + Some(t) if t.title != "" => t.title + _ => display_title(n) + }, subtitle, icons: if is_stream { stream_icon_chain(n) diff --git a/tabs/moon.pkg b/tabs/moon.pkg new file mode 100644 index 0000000..459a95d --- /dev/null +++ b/tabs/moon.pkg @@ -0,0 +1,13 @@ +// Browser tab names: native messaging (host side), the published files and +// MPRIS titles (mixer side). Native only. See tabs_stub.c. +import { + "geordi/moonmix/model", + "moonbitlang/core/encoding/utf8", +} + +supported_targets = "-all+native" + +options( + "native-stub": [ "tabs_stub.c" ], + link: { "native": { "stub-cc": "tools/pkg-cc" } }, +) diff --git a/tabs/pkg.generated.mbti b/tabs/pkg.generated.mbti new file mode 100644 index 0000000..08dcd6c --- /dev/null +++ b/tabs/pkg.generated.mbti @@ -0,0 +1,43 @@ +// Generated using `moon info`, DON'T EDIT IT +package "geordi/moonmix/tabs" + +import { + "geordi/moonmix/model", +} + +// Values +pub fn browser_pid() -> Int32 + +pub fn files() -> Array[@model.TabFile] + +pub fn listen() -> Unit + +pub fn media_titles() -> Map[Int32, String] + +pub fn message() -> String + +pub fn now_ms() -> Int64 + +pub fn on_event((Event) -> Unit) -> Unit + +pub fn prune() -> Unit + +pub fn publish(@model.TabFile) -> Bool + +pub fn unpublish() -> Unit + +pub fn watch() -> Unit + +// Errors + +// Types and methods +pub(all) enum Event { + Message + Eof + Files + Media +} + +// Type aliases + +// Traits diff --git a/tabs/tabs.mbt b/tabs/tabs.mbt new file mode 100644 index 0000000..dfde0eb --- /dev/null +++ b/tabs/tabs.mbt @@ -0,0 +1,134 @@ +// MoonBit side of tabs_stub.c. + +///| +pub(all) enum Event { + /// A native-messaging message arrived: `message`. + Message + /// The browser closed the connection, or asked us to stop. + Eof + /// The published files changed: `names`. + Files + /// What browsers play changed: `media_titles`. + Media +} + +///| +extern "C" fn ffi_set_handler( + call : FuncRef[((Int32) -> Unit, Int32) -> Unit], + closure : (Int32) -> Unit, +) = "mm_tabs_set_handler" + +///| +extern "C" fn ffi_now_ms() -> Int64 = "mm_tabs_now_ms" + +///| +extern "C" fn ffi_getppid() -> Int32 = "mm_tabs_getppid" + +///| +extern "C" fn ffi_listen() = "mm_tabs_listen" + +///| +extern "C" fn ffi_message() -> Bytes = "mm_tabs_message" + +///| +#borrow(text) +extern "C" fn ffi_publish(text : Bytes) -> Int32 = "mm_tabs_publish" + +///| +extern "C" fn ffi_unpublish() = "mm_tabs_unpublish" + +///| +extern "C" fn ffi_prune() = "mm_tabs_prune" + +///| +extern "C" fn ffi_read() -> Bytes = "mm_tabs_read" + +///| +extern "C" fn ffi_watch() = "mm_tabs_watch" + +///| +extern "C" fn ffi_watch_media() = "mm_tabs_watch_media" + +///| +extern "C" fn ffi_media() -> Bytes = "mm_tabs_media" + +///| +/// Register the single event handler. Call before `listen` or `watch`. +pub fn on_event(f : (Event) -> Unit) -> Unit { + ffi_set_handler(fn(g, kind) { g(kind) }, fn(kind) { + match kind { + 1 => f(Message) + 2 => f(Eof) + 3 => f(Files) + 4 => f(Media) + _ => () + } + }) +} + +///| +pub fn now_ms() -> Int64 { + ffi_now_ms() +} + +///| +/// The browser: it starts native-messaging hosts itself. +pub fn browser_pid() -> Int32 { + ffi_getppid() +} + +///| +/// Read native messages from stdin. +pub fn listen() -> Unit { + ffi_listen() +} + +///| +pub fn message() -> String { + @utf8.decode_lossy(ffi_message()) +} + +///| +/// Publish this host's matches for running mixers. +pub fn publish(file : @model.TabFile) -> Bool { + let b = @utf8.encode(file.to_text()) + let n = b.length() + ffi_publish(Bytes::makei(n + 1, fn(i) { if i < n { b[i] } else { b'\x00' } })) == + 0 +} + +///| +pub fn unpublish() -> Unit { + ffi_unpublish() +} + +///| +/// Remove files left by hosts that died. +pub fn prune() -> Unit { + ffi_prune() +} + +///| +/// Everything published by hosts right now. +pub fn files() -> Array[@model.TabFile] { + let out = [] + for line in @utf8.decode_lossy(ffi_read()).split("\n") { + match @model.TabFile::parse(line.to_owned()) { + Some(f) => out.push(f) + None => () + } + } + out +} + +///| +/// Report changes of the published files and of browsers' MPRIS titles. +pub fn watch() -> Unit { + ffi_watch() + ffi_watch_media() +} + +///| +pub fn media_titles() -> Map[Int32, String] { + @model.parse_media_titles(@utf8.decode_lossy(ffi_media())) +} diff --git a/tabs/tabs_stub.c b/tabs/tabs_stub.c new file mode 100644 index 0000000..491d4ad --- /dev/null +++ b/tabs/tabs_stub.c @@ -0,0 +1,336 @@ +/* + * moonmix: browser tab names. + * + * Host side: Chrome native messaging on stdin, and one published file per + * host in $XDG_RUNTIME_DIR/moonmix (private, gone at logout). + * Mixer side: watching that directory, and the titles Chromium-family + * browsers publish over MPRIS. + * + * Everything runs on the GLib default main context (shared with WirePlumber + * and GTK). MoonBit gets one callback with the kind of event. + */ +#include +#include +#include +#include +#include +#include +#include +#include "moonbit.h" + +enum { + MM_TABS_MESSAGE = 1, + MM_TABS_EOF = 2, + MM_TABS_FILES = 3, + MM_TABS_MEDIA = 4, +}; + +/* Native messaging allows far more; a list of tabs never needs it. */ +#define MAX_MESSAGE (1024 * 1024) + +typedef void (*mm_tcall_t)(void *closure, int32_t kind); +static mm_tcall_t g_call; +static void *g_closure; + +static void emit(int32_t kind) { + if (g_call) { + moonbit_incref(g_closure); + g_call(g_closure, kind); + } +} + +MOONBIT_FFI_EXPORT void mm_tabs_set_handler(mm_tcall_t call, void *closure) { + if (g_closure) + moonbit_decref(g_closure); + g_call = call; + g_closure = closure; +} + +static moonbit_bytes_t to_bytes(const char *s, size_t n) { + moonbit_bytes_t b = moonbit_make_bytes((int32_t)n, 0); + if (n) + memcpy(b, s, n); + return b; +} + +MOONBIT_FFI_EXPORT int64_t mm_tabs_now_ms(void) { + return g_get_monotonic_time() / 1000; +} + +MOONBIT_FFI_EXPORT int32_t mm_tabs_getppid(void) { return getppid(); } + +/* ---- native messaging --------------------------------------------------- */ + +static GByteArray *g_in; +static GString *g_message; + +static gboolean end_of_input(void) { + emit(MM_TABS_EOF); + return G_SOURCE_REMOVE; +} + +static gboolean on_stdin(gint fd, GIOCondition cond, gpointer d) { + (void)cond; + (void)d; + guint8 buf[65536]; + ssize_t n = read(fd, buf, sizeof buf); + if (n < 0 && (errno == EINTR || errno == EAGAIN)) + return G_SOURCE_CONTINUE; + if (n <= 0) + return end_of_input(); + g_byte_array_append(g_in, buf, (guint)n); + while (g_in->len >= 4) { + guint32 len; /* native byte order, per the protocol */ + memcpy(&len, g_in->data, 4); + if (len > MAX_MESSAGE) + return end_of_input(); + if (g_in->len < 4 + len) + break; + g_string_truncate(g_message, 0); + g_string_append_len(g_message, (const char *)g_in->data + 4, len); + g_byte_array_remove_range(g_in, 0, 4 + len); + emit(MM_TABS_MESSAGE); + } + return G_SOURCE_CONTINUE; +} + +static gboolean on_term(gpointer d) { + (void)d; + return end_of_input(); +} + +MOONBIT_FFI_EXPORT void mm_tabs_listen(void) { + g_in = g_byte_array_new(); + g_message = g_string_new(NULL); + g_unix_fd_add(STDIN_FILENO, G_IO_IN | G_IO_HUP | G_IO_ERR, on_stdin, NULL); + g_unix_signal_add(SIGTERM, on_term, NULL); + g_unix_signal_add(SIGINT, on_term, NULL); +} + +MOONBIT_FFI_EXPORT moonbit_bytes_t mm_tabs_message(void) { + return to_bytes(g_message->str, g_message->len); +} + +/* ---- published files ---------------------------------------------------- */ + +static char *tabs_dir(void) { + const char *dir = g_getenv("MOONMIX_TABS_DIR"); + if (dir && *dir) + return g_strdup(dir); + /* No fallback to a shared directory: titles are private. */ + dir = g_getenv("XDG_RUNTIME_DIR"); + return dir && *dir ? g_build_filename(dir, "moonmix", NULL) : NULL; +} + +static char *own_file(const char *dir) { + char name[32]; + g_snprintf(name, sizeof name, "%d.json", (int)getpid()); + return g_build_filename(dir, name, NULL); +} + +MOONBIT_FFI_EXPORT int32_t mm_tabs_publish(moonbit_bytes_t text) { + g_autofree char *dir = tabs_dir(); + if (!dir || g_mkdir_with_parents(dir, 0700) != 0) + return -1; + g_autofree char *path = own_file(dir); + return g_file_set_contents_full(path, (const char *)text, -1, + G_FILE_SET_CONTENTS_CONSISTENT, 0600, NULL) + ? 0 + : -1; +} + +MOONBIT_FFI_EXPORT void mm_tabs_unpublish(void) { + g_autofree char *dir = tabs_dir(); + if (dir) { + g_autofree char *path = own_file(dir); + g_unlink(path); + } +} + +/* Remove files whose host was killed before it could. */ +MOONBIT_FFI_EXPORT void mm_tabs_prune(void) { + g_autofree char *dir = tabs_dir(); + g_autoptr(GDir) d = dir ? g_dir_open(dir, 0, NULL) : NULL; + const char *name; + while (d && (name = g_dir_read_name(d))) { + char *end; + long pid = strtol(name, &end, 10); + if (pid <= 0 || strcmp(end, ".json") != 0) + continue; + g_autofree char *proc = g_strdup_printf("/proc/%ld", pid); + if (!g_file_test(proc, G_FILE_TEST_EXISTS)) { + g_autofree char *path = g_build_filename(dir, name, NULL); + g_unlink(path); + } + } +} + +/* Every published file (each is one line of JSON), newline separated. */ +MOONBIT_FFI_EXPORT moonbit_bytes_t mm_tabs_read(void) { + g_autofree char *dir = tabs_dir(); + g_autoptr(GDir) d = dir ? g_dir_open(dir, 0, NULL) : NULL; + g_autoptr(GString) out = g_string_new(NULL); + const char *name; + while (d && (name = g_dir_read_name(d))) { + if (!g_str_has_suffix(name, ".json")) + continue; + g_autofree char *path = g_build_filename(dir, name, NULL); + g_autofree char *text = NULL; + gsize len; + if (g_file_get_contents(path, &text, &len, NULL) && len <= MAX_MESSAGE) { + g_string_append_len(out, text, (gssize)len); + g_string_append_c(out, '\n'); + } + } + return to_bytes(out->str, out->len); +} + +static void on_dir_changed(GFileMonitor *m, GFile *f, GFile *other, + GFileMonitorEvent ev, gpointer d) { + (void)m; (void)f; (void)other; (void)ev; (void)d; + emit(MM_TABS_FILES); +} + +MOONBIT_FFI_EXPORT void mm_tabs_watch(void) { + static GFileMonitor *monitor; + g_autofree char *dir = tabs_dir(); + if (monitor || !dir) + return; + /* May fail on the container's read-only mount, where it already exists. */ + g_mkdir_with_parents(dir, 0700); + g_autoptr(GFile) file = g_file_new_for_path(dir); + monitor = g_file_monitor_directory(file, G_FILE_MONITOR_WATCH_MOVES, NULL, + NULL); + if (monitor) + g_signal_connect(monitor, "changed", G_CALLBACK(on_dir_changed), NULL); +} + +/* ---- MPRIS -------------------------------------------------------------- */ + +#define MPRIS "org.mpris.MediaPlayer2" +#define MPRIS_CHROMIUM MPRIS ".chromium.instance" + +static GDBusConnection *g_bus; +static GHashTable *g_titles; /* browser pid -> char *title, while playing */ +static guint g_rescan; + +typedef struct { + GHashTable *titles; + int pending; +} Scan; + +static void scan_done(Scan *scan) { + if (--scan->pending > 0) + return; + if (g_titles) + g_hash_table_unref(g_titles); + g_titles = scan->titles; + g_free(scan); + emit(MM_TABS_MEDIA); +} + +typedef struct { + Scan *scan; + int pid; +} Query; + +static void on_player(GObject *src, GAsyncResult *res, gpointer d) { + Query *q = d; + g_autoptr(GVariant) ret = + g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res, NULL); + if (ret) { + g_autoptr(GVariant) props = g_variant_get_child_value(ret, 0); + g_autoptr(GVariant) meta = + g_variant_lookup_value(props, "Metadata", G_VARIANT_TYPE_VARDICT); + const char *status = NULL, *title = NULL; + if (g_variant_lookup(props, "PlaybackStatus", "&s", &status) && + strcmp(status, "Playing") == 0 && meta && + g_variant_lookup(meta, "xesam:title", "&s", &title) && *title) + g_hash_table_insert(q->scan->titles, GINT_TO_POINTER(q->pid), + g_strdelimit(g_strdup(title), "\t\r\n", ' ')); + } + scan_done(q->scan); + g_free(q); +} + +static void on_names(GObject *src, GAsyncResult *res, gpointer d) { + (void)d; + g_autoptr(GVariant) ret = + g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res, NULL); + if (!ret) + return; + Scan *scan = g_new0(Scan, 1); + scan->titles = g_hash_table_new_full(NULL, NULL, NULL, g_free); + scan->pending = 1; + g_autoptr(GVariantIter) it = NULL; + const char *name; + g_variant_get(ret, "(as)", &it); + while (g_variant_iter_next(it, "&s", &name)) { + if (!g_str_has_prefix(name, MPRIS_CHROMIUM)) + continue; + int pid = atoi(name + strlen(MPRIS_CHROMIUM)); + if (pid <= 0) + continue; + Query *q = g_new0(Query, 1); + q->scan = scan; + q->pid = pid; + scan->pending++; + g_dbus_connection_call( + G_DBUS_CONNECTION(src), name, "/org/mpris/MediaPlayer2", + "org.freedesktop.DBus.Properties", "GetAll", + g_variant_new("(s)", MPRIS ".Player"), G_VARIANT_TYPE("(a{sv})"), + G_DBUS_CALL_FLAGS_NO_AUTO_START, 2000, NULL, on_player, q); + } + scan_done(scan); +} + +static gboolean rescan(gpointer d) { + (void)d; + g_rescan = 0; + g_dbus_connection_call(g_bus, "org.freedesktop.DBus", + "/org/freedesktop/DBus", "org.freedesktop.DBus", + "ListNames", NULL, G_VARIANT_TYPE("(as)"), + G_DBUS_CALL_FLAGS_NO_AUTO_START, 2000, NULL, on_names, + NULL); + return G_SOURCE_REMOVE; +} + +static void on_mpris_signal(GDBusConnection *c, const char *sender, + const char *path, const char *iface, + const char *signal, GVariant *params, gpointer d) { + (void)c; (void)sender; (void)path; (void)iface; (void)signal; (void)params; + (void)d; + if (!g_rescan) + g_rescan = g_timeout_add(100, rescan, NULL); +} + +MOONBIT_FFI_EXPORT void mm_tabs_watch_media(void) { + if (g_bus) + return; + g_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL); + if (!g_bus) + return; + g_dbus_connection_signal_subscribe( + g_bus, "org.freedesktop.DBus", "org.freedesktop.DBus", + "NameOwnerChanged", "/org/freedesktop/DBus", MPRIS, + G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE, on_mpris_signal, NULL, NULL); + g_dbus_connection_signal_subscribe( + g_bus, NULL, "org.freedesktop.DBus.Properties", "PropertiesChanged", + "/org/mpris/MediaPlayer2", MPRIS ".Player", G_DBUS_SIGNAL_FLAGS_NONE, + on_mpris_signal, NULL, NULL); + rescan(NULL); +} + +/* "pid\ttitle\n" for every browser that is playing. */ +MOONBIT_FFI_EXPORT moonbit_bytes_t mm_tabs_media(void) { + g_autoptr(GString) out = g_string_new(NULL); + GHashTableIter it; + gpointer pid, title; + if (g_titles) { + g_hash_table_iter_init(&it, g_titles); + while (g_hash_table_iter_next(&it, &pid, &title)) + g_string_append_printf(out, "%d\t%s\n", GPOINTER_TO_INT(pid), + (char *)title); + } + return to_bytes(out->str, out->len); +} diff --git a/tools/fake-browser.py b/tools/fake-browser.py new file mode 100644 index 0000000..f581bd0 --- /dev/null +++ b/tools/fake-browser.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Smoke-test stand-in for a browser: plays a stream and reports it as a tab. + +fake-browser.py : starts the host as its child, like a +browser does, then pw-play (its "audio service") and a moment later one audible +tab. Exits when stdin closes. +""" + +import json +import os +import struct +import subprocess +import sys +import time + + +def message(tabs): + body = json.dumps({"tabs": tabs}).encode() + return struct.pack("=I", len(body)) + body + + +def play(): + # exec keeps the pid the stream announces. + os.execvp("pw-play", ["pw-play", "-P", json.dumps({ + "application.name": "Fake Browser", + "application.process.id": str(os.getpid()), + "media.name": "Playback", + }), sys.argv[2]]) + + +host = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE) +host.stdin.write(message([])) +host.stdin.flush() +time.sleep(3) # let it connect to PipeWire +audio = os.fork() +if audio == 0: + play() +time.sleep(0.5) +host.stdin.write(message([{"id": 7, "title": "Smoke test tab", "audible": True}])) +host.stdin.flush() +sys.stdin.read() +os.kill(audio, 15) +host.stdin.close() +host.wait(5) diff --git a/tools/install-browser-tabs.py b/tools/install-browser-tabs.py new file mode 100755 index 0000000..d9e1c18 --- /dev/null +++ b/tools/install-browser-tabs.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Install the browser tab host and extension for the current user. + +Copies moonmix-tabs-host and the extension, and registers the host with every +Chromium-family browser that has a profile. Loading the extension is up to the +user. --uninstall removes everything again. +""" + +import base64 +import hashlib +import json +import os +from pathlib import Path +import shutil +import sys + +NAME = "org.latha.moonmix.tabs" +BROWSERS = ( + "google-chrome", "google-chrome-beta", "google-chrome-unstable", "chromium", + "BraveSoftware/Brave-Browser", "microsoft-edge", "vivaldi", +) + + +def extension_id(manifest): + digest = hashlib.sha256(base64.b64decode(manifest["key"])).hexdigest()[:32] + return "".join(chr(ord("a") + int(c, 16)) for c in digest) + + +def main(): + root = Path(__file__).resolve().parent.parent + config = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") + data = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share") + host = Path.home() / ".local/bin/moonmix-tabs-host" + extension = data / "moonmix/extension" + registered = [config / b / "NativeMessagingHosts" / f"{NAME}.json" for b in BROWSERS] + + if sys.argv[1:] == ["--uninstall"]: + for path in [*registered, host]: + path.unlink(missing_ok=True) + shutil.rmtree(extension, ignore_errors=True) + print("Removed. Also remove the extension in the browser.") + return + + built = root / "_build/native/release/build/cmd/moonmix-tabs-host/moonmix-tabs-host.exe" + if not built.exists(): + sys.exit("Build first: moon build --target native --release") + host.parent.mkdir(parents=True, exist_ok=True) + # Replace, not overwrite: the old one may be running. + temporary = host.with_name(host.name + ".new") + shutil.copyfile(built, temporary) + temporary.chmod(0o755) + temporary.replace(host) + shutil.copytree(root / "extension", extension, dirs_exist_ok=True) + + origin = extension_id(json.loads((extension / "manifest.json").read_text())) + manifest = json.dumps({ + "name": NAME, + "description": "moonmix browser tab names", + "path": str(host), + "type": "stdio", + "allowed_origins": [f"chrome-extension://{origin}/"], + }, indent=2) + found = False + for path in registered: + # Only browsers that are in use here. + if path.parent.parent.is_dir(): + path.parent.mkdir(exist_ok=True) + path.write_text(manifest + "\n") + print(f"Registered: {path}") + found = True + if not found: + print("No supported browser profile found; nothing registered.") + print(f"Installed host: {host}") + print("Now open the browser's extensions page (chrome://extensions), turn on") + print(f"Developer mode, choose 'Load unpacked' and select:\n {extension}") + + +if __name__ == "__main__": + main() diff --git a/tools/moonmix-container b/tools/moonmix-container index ca88cbd..6cf155d 100755 --- a/tools/moonmix-container +++ b/tools/moonmix-container @@ -35,6 +35,14 @@ set -- podman run --rm --pull=never \ --mount "type=bind,src=$wayland_socket,dst=/run/moonmix/wayland-0,ro" \ --mount "type=bind,src=$pipewire_socket,dst=/run/moonmix/pipewire-0,ro" +# Browser tab names published by the host's moonmix-tabs-host. Created here so +# that names also appear when the browser starts after the mixer. +tabs_dir=$XDG_RUNTIME_DIR/moonmix +mkdir -p -m 700 "$tabs_dir" +set -- "$@" \ + --mount "type=bind,src=$tabs_dir,dst=/run/moonmix/tabs,ro" \ + --env MOONMIX_TABS_DIR=/run/moonmix/tabs + # The portal supplies desktop appearance settings. Do not expose the rest of # XDG_RUNTIME_DIR (which can contain credentials and unrelated service sockets). if [ -S "$XDG_RUNTIME_DIR/bus" ]; then diff --git a/tools/smoke-test.sh b/tools/smoke-test.sh index db13e15..4925c9c 100755 --- a/tools/smoke-test.sh +++ b/tools/smoke-test.sh @@ -13,6 +13,7 @@ set -eu ROOT=$(cd "$(dirname "$0")/.." && pwd) BUILD="$ROOT/_build/native/debug/build/cmd" PROBE="$BUILD/moonmix-probe/moonmix-probe.exe" +TABS_HOST="$BUILD/moonmix-tabs-host/moonmix-tabs-host.exe" GUI="$BUILD/moonmix/moonmix.exe" SHOTS="${1:-}" @@ -49,12 +50,19 @@ CONF # Ubuntu's WirePlumber asks snapd before granting clients access; there is # no snapd in a sandbox/CI container, so turn that off for the test session. +# No hardware either: the test noise must not reach the real speakers. mkdir -p "$XDG_CONFIG_HOME/wireplumber/wireplumber.conf.d" cat > "$XDG_CONFIG_HOME/wireplumber/wireplumber.conf.d/moonmix-test.conf" <<'CONF' wireplumber.profiles = { main = { support.snapd-permission-prompting = disabled script.client.access-snap = disabled + monitor.alsa = disabled + monitor.alsa-midi = disabled + monitor.bluez = disabled + monitor.bluez-midi = disabled + monitor.libcamera = disabled + monitor.v4l2 = disabled } } CONF @@ -160,6 +168,21 @@ meter() { meter "${STREAM:-0}" meter test_speakers +# Browser tab names: a fake browser with a real tab host. +if command -v python3 >/dev/null; then + echo "### browser tab names" + mkfifo "$LOGS/browser.in" + python3 "$ROOT/tools/fake-browser.py" "$TABS_HOST" "$LOGS/noise.wav" \ + <"$LOGS/browser.in" >"$LOGS/browser.log" 2>&1 & BROWSER=$!; PIDS="$PIDS $BROWSER" + exec 5>"$LOGS/browser.in" + wait_for 'Smoke test tab | ' || { fail=1; cat "$LOGS/browser.log" "$XDG_RUNTIME_DIR"/moonmix/* || true; "$PROBE" || true; } + exec 5>&- + wait "$BROWSER" || { echo "FAIL: fake browser"; cat "$LOGS/browser.log"; fail=1; } + if [ -n "$(ls "$XDG_RUNTIME_DIR/moonmix")" ]; then echo "FAIL: tab host left its file"; fail=1; fi +else + echo "python3 not found; skipping browser tab names" +fi + if [ "$fail" != 0 ]; then echo "### diagnostics" echo "--- pw-play playback:"; cat "$LOGS/play.log" diff --git a/tools/test-container.py b/tools/test-container.py index f2069cb..1d7fdc0 100755 --- a/tools/test-container.py +++ b/tools/test-container.py @@ -92,9 +92,15 @@ class ContainerTests(unittest.TestCase): self.assertEqual(self.mounts(), [ f"type=bind,src={self.runtime}/wayland-test,dst=/run/moonmix/wayland-0,ro", f"type=bind,src={self.runtime}/pipewire-0,dst=/run/moonmix/pipewire-0,ro", + f"type=bind,src={self.runtime}/moonmix,dst=/run/moonmix/tabs,ro", ]) self.assertIn("DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/no-bus", arguments) + def test_tab_names_directory_is_private_and_read_only(self): + self.assertEqual(self.launch().returncode, 0) + self.assertEqual((self.runtime / "moonmix").stat().st_mode & 0o777, 0o700) + self.assertIn("MOONMIX_TABS_DIR=/run/moonmix/tabs", self.podman_arguments()) + def test_session_bus_is_optional_and_mounted_individually(self): self.bind_socket(self.runtime / "bus") self.assertEqual(self.launch().returncode, 0) @@ -117,6 +123,7 @@ class ContainerTests(unittest.TestCase): self.assertEqual(self.mounts(), [ f"type=bind,src={wayland},dst=/run/moonmix/wayland-0,ro", f"type=bind,src={pipewire},dst=/run/moonmix/pipewire-0,ro", + f"type=bind,src={self.runtime}/moonmix,dst=/run/moonmix/tabs,ro", ]) def test_pipewire_runtime_remote_and_image_overrides(self): @@ -270,6 +277,7 @@ class ContainerTests(unittest.TestCase): self.assertEqual(mounts, [ f"type=bind,src={self.runtime}/wayland-test,dst=/run/moonmix/wayland-0,ro", f"type=bind,src={self.runtime}/pipewire-0,dst=/run/moonmix/pipewire-0,ro", + f"type=bind,src={self.runtime}/moonmix,dst=/run/moonmix/tabs,ro", f"type=bind,src={user_icons},dst=/run/moonmix/host/user/icons,ro", f"type=bind,src={sys_pixmaps},dst=/run/moonmix/host/usr/pixmaps,ro", f"type=bind,src={sys_apps},dst=/run/moonmix/host/usr/applications,ro", diff --git a/wp/moon.pkg b/wp/moon.pkg index 36b8dde..11925c1 100644 --- a/wp/moon.pkg +++ b/wp/moon.pkg @@ -2,6 +2,7 @@ import { "geordi/moonmix/model", "moonbitlang/core/encoding/utf8", + "moonbitlang/core/string", } supported_targets = "-all+native" diff --git a/wp/wp.mbt b/wp/wp.mbt index 2644590..49d797f 100644 --- a/wp/wp.mbt +++ b/wp/wp.mbt @@ -68,6 +68,12 @@ 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_node_running(id : Int32) -> Int32 = "mm_wp_node_running" + +///| +extern "C" fn ffi_parent_pid(pid : Int32) -> Int32 = "mm_wp_parent_pid" + ///| extern "C" fn ffi_query_volume(id : Int32) -> Int32 = "mm_wp_query_volume" @@ -204,6 +210,9 @@ pub fn read_node(id : Int32) -> @model.Node? { node_prop(id, "application.id") } } + let pid = @string.parse_int(node_prop(id, "application.process.id")) catch { + _ => 0 + } Some( @model.Node::new( id, @@ -217,6 +226,9 @@ pub fn read_node(id : Int32) -> @model.Node? { bus=node_prop(id, "device.bus"), app_binary=node_prop(id, "application.process.binary"), app_id~, + serial=node_prop(id, "object.serial"), + parent_pid=ffi_parent_pid(pid), + running=ffi_node_running(id) != 0, volumes~, mute~, ), diff --git a/wp/wp_stub.c b/wp/wp_stub.c index 683cf87..b3f1ce4 100644 --- a/wp/wp_stub.c +++ b/wp/wp_stub.c @@ -16,6 +16,7 @@ * 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 @@ -104,12 +105,21 @@ static void on_node_props(GObject *obj, GParamSpec *pspec, gpointer data) { emit(MM_EV_NODE_CHANGED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(obj))); } +static void on_node_state(WpNode *node, WpNodeState old, WpNodeState now, + gpointer data) { + (void)data; + /* Only running / not running matters. */ + if ((old == WP_NODE_STATE_RUNNING) != (now == WP_NODE_STATE_RUNNING)) + emit(MM_EV_NODE_CHANGED, (int32_t)wp_proxy_get_bound_id(WP_PROXY(node))); +} + 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); + g_signal_connect(obj, "state-changed", G_CALLBACK(on_node_state), 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); @@ -121,6 +131,7 @@ static void on_object_removed(WpObjectManager *om, GObject *obj, gpointer d) { (void)d; if (WP_IS_NODE(obj)) { g_signal_handlers_disconnect_by_func(obj, on_node_props, NULL); + g_signal_handlers_disconnect_by_func(obj, on_node_state, 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); @@ -300,6 +311,29 @@ MOONBIT_FFI_EXPORT moonbit_bytes_t mm_wp_node_prop(int32_t id, return to_bytes(v); } +MOONBIT_FFI_EXPORT int32_t mm_wp_node_running(int32_t id) { + g_autoptr(WpNode) node = lookup_node((guint32)id); + return node && wp_node_get_state(node, NULL) == WP_NODE_STATE_RUNNING; +} + +/* Parent of a process (Chrome's audio service -> the browser); 0 if unknown, + * e.g. in a container with its own pid namespace. */ +MOONBIT_FFI_EXPORT int32_t mm_wp_parent_pid(int32_t pid) { + char path[64]; + g_autofree char *stat = NULL; + int ppid = 0; + if (pid <= 0) + return 0; + g_snprintf(path, sizeof path, "/proc/%d/stat", pid); + if (!g_file_get_contents(path, &stat, NULL, NULL)) + return 0; + /* "pid (comm) state ppid ...": comm may itself contain ") ". */ + const char *p = strrchr(stat, ')'); + if (!p || sscanf(p + 1, " %*c %d", &ppid) != 1) + return 0; + return ppid; +} + /* Volume of the last queried node. */ #define MM_MAX_CH 64 static double g_vol[MM_MAX_CH];