Compare commits

...

22 Commits

Author SHA1 Message Date
Dandaedre 814c87cc6e
docs: record completed M13 implementation and automated qualification
Rust CI fader_master passed its selected CI mode.
MadGobblins/fader_master/pipeline/head This commit looks good Details
Verify: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features all passed. Default/no-default workspace and portable/individual-backend tests and builds passed. Private D-Bus fixtures: 2 passed. scripts/test-ci.sh and git diff --check passed. Real QBZ/controller and provisioned Jenkins runs remain explicitly unverified.
2026-10-18 23:08:47 +02:00
Dandaedre 31a2fa338a
ci: include M13 media contracts and isolated MPRIS fixtures
Verify: scripts/test-ci.sh failed before the required fixture/prerequisite commands, then passed after updates; git diff --check passed. Linux runner needs provisioned libdbus-1 and dbus-run-session; no Jenkins run claimed.
2026-10-18 23:07:21 +02:00
Dandaedre e11e537e12
docs: document M13 media controls and add a validated QBZ profile
Verify: cargo test -p fader-config --quiet: 60 tests passed, including round-trip validation of all 14 example controls; git diff --check passed; documented UI keys and limits reviewed against implementation. Hardware checklist explicitly remains opt-in and unverified.
2026-10-18 23:06:58 +02:00
Dandaedre 0f59b25fc9
fix: retain M13 media availability when a player is unresponsive
Verify: private_bus_extended regression failed before native availability reporting; dbus-run-session -- cargo test -p fader_master --lib private_bus -- --ignored: 2 passed after fix; cargo fmt --all passed. Session-bus availability is independent of successful player discovery.
2026-10-18 23:05:12 +02:00
Dandaedre a31929ec08
fix: bound M13 playlist snapshots within expanded IPC frames
Verify: 256-playlist IPC regression failed at the former 64 KiB limit, then passed with the bounded 1 MiB limit. cargo test -p fader_master --test ipc_frames --quiet: 4 passed; config tests passed, including oversized media rejection; workspace clippy -D warnings and formatting passed.
2026-10-18 23:04:35 +02:00
Dandaedre 6ee082673b
test: qualify M13.3f extended MPRIS actions and persisted editing
Verify: dbus-run-session -- cargo test -p fader_master private_bus -- --ignored --nocapture: 2 isolated fake-bus tests passed, including wire units, playlists, capability changes, timeout recovery and unique-owner replacement. cargo test -p fader_master --lib --quiet: 40 passed, 2 opt-in ignored. Save/restart/unbind/delete covered. Clippy -D warnings and formatting passed.
2026-10-18 23:03:26 +02:00
Dandaedre f7acaf3ba4
test: qualify M13.3e media feedback state transitions
Extract the hardware-free media feedback plan for direct regression tests. Verify: cargo test -p fader_master media_feedback_is --quiet passed; cargo clippy -p fader_master --all-targets --all-features -- -D warnings passed; cargo fmt --all passed.
2026-10-18 23:01:30 +02:00
Dandaedre 195f3974c6
fix: reject incomplete M13 player matches and unsupported PlayPause
Verify: new regression tests failed before fixes; cargo test -p media --quiet: 4 passed; cargo test -p tui --quiet: 55 passed; cargo fmt --all passed. PlayPause capability checked against the MPRIS Player specification.
2026-10-18 23:00:42 +02:00
Dandaedre 431669c994
feat: implement M13.3d capability-aware media tab and guided editing
Verify: cargo test -p tui --quiet: 55 passed; cargo check --workspace --all-targets --all-features passed; workspace clippy -D warnings passed before final playlist-label addition; cargo fmt --all passed. Tests cover validation, discovery picker, advertised availability, gated commands and learn/unbind.
2026-10-18 22:59:50 +02:00
Dandaedre c7e33d45d2
feat: connect M13 media actions, MIDI learn and feedback to the server
Verify: cargo test -p fader_master --lib --quiet: 38 passed, 1 opt-in ignored (temporary Unix sockets require elevated sandbox permissions). cargo test -p fader_master media_triggers --quiet passed. cargo fmt --all passed. Live hardware not exercised.
2026-10-18 22:54:51 +02:00
Dandaedre 5d0126abff
feat: add bounded M13.3b MPRIS worker and native adapter
Use pinned dbus 0.9.12 on a joined worker with bounded command queue, expiry, finite method timeouts, unique-owner targeting and configuration fences. Discover playback capabilities, position, shuffle, repeat and playlists independently of audio.

Verification: Rust 1.88 build; media_runtime fake-adapter tests; dbus-run-session -- cargo test -p fader_master private_bus_discovers -- --ignored --nocapture passed; clippy all-targets/all-features and no-default-features check passed. License and native prerequisites documented.
2026-10-18 22:49:03 +02:00
Dandaedre fb937ef6ae
feat: define M13 media entries and confirmed-state contracts
Add hardware-free selector/action/feedback types and validated profile editing with MIDI collision checks. Retain media entries when a surface is removed. Includes seeking, shuffle, repeat and playlist actions.

Tests: new selector/feedback and schema regressions failed before implementation; cargo test -p media -p fader-config --quiet and targeted clippy passed. Formatting and staged diff checks passed.
2026-10-18 22:44:40 +02:00
Dandaedre 618c3d7b07
feat: add M13.3a global and per-fader feedback gates
Persist default-enabled feedback switches and expose them in Config and Edit fader. Both explicit and implicit output mappings are suppressed; reactivation recreates feedback state.

Tests: feedback_switches failed before implementation and now passes; cargo test -p tui --quiet (50 passed); cargo test -p fader_master disabled_feedback --quiet passed; workspace clippy all-targets/all-features, formatting and diff checks passed.
2026-10-18 22:41:03 +02:00
Dandaedre e0d17d735a
feat: expose M13.2 normalized process diagnostics
Expose scrollable per-stream normalized fields with explicit unavailable values and exclude raw secrets. Add native, Proton-like, restricted-read and exit fixtures.

Tests: stream_diagnostics regression failed before implementation, now passes; cargo test -p tui --quiet and cargo test -p volume_lib process_metadata --quiet passed. Workspace check and clippy all-targets/all-features passed; cargo fmt and git diff --check passed.
2026-10-18 22:39:03 +02:00
Dandaedre 0e224c664b
feat: add bounded M13.2 process metadata selectors
Enrich local Pulse streams outside native callbacks with executable, working directory and allowlisted Steam IDs. Preserve unavailable data, check start-time consistency and never infer Steam launch from paths. Add capture fields and document best-effort limitations; diagnostics qualification remains pending.

Verification passed: enriched_process schema regression (initially failed on unknown field); process_metadata tests; cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features --quiet; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default/no-default workspace builds; volume_lib without defaults and with pulse; midi midir build. Hardware fixtures remain opt-in.
2026-10-18 22:25:46 +02:00
Dandaedre 64f08e9db0
feat: expose M13.1 selector composition in fader editor
Add revisioned Any/OR and All/AND editing, optimistic display and persistence across a fresh editor instance. Preserve legacy IPC defaults.

Verification passed: cargo test -p tui --quiet; cargo test -p fader_master selector_mode --quiet; cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features --quiet; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default and no-default-features workspace builds; volume_lib pulse and midi midir builds. Hardware fixtures remain opt-in. Regression first failed on missing Match captures row.
2026-10-18 22:21:39 +02:00
Dandaedre 002570a848
feat: add M13.1 explicit AND selector composition
Preserve default OR behavior; validate all-mode matching and document schema. Include transactional editor API for the following TUI slice.

Tests: cargo test -p fader-core -p fader-config --quiet passed. Regression first failed because selector_mode was rejected. git diff --check passed.
2026-10-18 22:19:17 +02:00
Dandaedre 59fe7f9efc
docs: expand M13 media-control acceptance criteria
Record approved discovery, UI, MIDI feedback gates and extended playback controls. Validation: git diff --check; reviewed backlog ordering and architecture consistency. No runtime behavior changed.
2026-10-18 22:17:38 +02:00
Dandaedre 9b7ebb4bb1
feat: add Save and exit to M9.5 capture editor
Validate capture selectors before submitting either edit path; retain invalid input with an inline error. Document draft-save semantics.

Verification: cargo test -p tui (49 passed); cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features --quiet; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; cargo build --workspace; cargo build --workspace --no-default-features; cargo build -p volume_lib --no-default-features --features pulse; cargo build -p midi --no-default-features --features midir. All passed. Hardware fixtures remain opt-in.
2026-10-18 21:54:54 +02:00
Dandaedre 2b725ca82f
feat: fold MIDI unbind into the learn prompt
M9.5: Remove separate Unlearn rows. U in a locally opened Learn MIDI prompt cancels capture and removes only that fader action; Esc cancels unchanged. Retain the controller for relearning and document the compact workflow.

Tests: updated guided-editor regression fails before implementation; new volume/mute scope, cancel and relearn regression passes. cargo fmt --all -- --check, cargo check --workspace --all-targets --all-features, cargo test --workspace --all-targets --all-features --quiet (48 TUI tests, two opt-in hardware tests ignored), cargo test --workspace --doc --all-features, cargo clippy --workspace --all-targets --all-features -- -D warnings, and cargo build --workspace --release --all-features all pass.
2026-10-18 21:52:07 +02:00
Dandaedre dc27b764fc
docs: plan M13 matching and media control stretch goals
Document the existing media.name YouTube regex as sufficient. Order AND selectors and process/Steam metadata before targeted MPRIS controls, with dependencies and acceptance criteria; distinguish planned schema from current RC2 behavior.

Validation: git diff --cached --check passed; reviewed selector example against current supported fields and OR semantics, and checked M13 references across configuration guide, architecture and backlog. Documentation only; runtime tests not required.
2026-10-18 21:48:54 +02:00
Dandaedre 704bb3aeaa
docs: record verified RC2 publication
Rust CI fader_master passed its selected CI mode.
MadGobblins/fader_master/pipeline/head This commit looks good Details
Record tagged source, fixed publisher, Cross image, release assets and public installation verification. Validation: git diff --cached --check; rust_realease completed all download/checksum/archive and cargo-binstall checks; public Gitea API confirms five assets, prerelease=true and draft=false.
2026-10-18 14:01:27 +02:00
44 changed files with 5090 additions and 103 deletions

View File

@ -1,5 +1,18 @@
# Changelog
## Unreleased
- Add Any/All application selectors and bounded process/Steam metadata with
normalized diagnostics in Config.
- Add the optional MPRIS Media tab: exact/regex player selection, discovery
picker, persisted entry/control editing, MIDI learn/unbind, transport, seeking,
shuffle, repeat and playlist activation.
- Add confirmed media feedback, custom note/CC color mappings, and global,
per-fader and per-media-entry feedback switches.
- Bound media discovery and configuration; expand bounded IPC frames for playlist
snapshots. Rebuild and restart both server and client. Real-controller/player
checks remain opt-in; see the hands-on checklist.
## 0.1.0-rc.2 — 2026-10-18
- Fix persistent stale-revision failures from MIDI volume/mute after saving

34
Cargo.lock generated
View File

@ -360,6 +360,17 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "dbus"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
dependencies = [
"libc",
"libdbus-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "deranged"
version = "0.5.8"
@ -403,6 +414,7 @@ name = "fader-config"
version = "0.1.0-rc.2"
dependencies = [
"fader-core",
"media",
"rustix 1.1.5",
"serde",
"tempfile",
@ -426,8 +438,10 @@ version = "0.1.0-rc.2"
dependencies = [
"anyhow",
"clap",
"dbus",
"fader-config",
"fader-core",
"media",
"midi",
"rustix 1.1.5",
"serde",
@ -701,6 +715,15 @@ version = "0.2.190"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
[[package]]
name = "libdbus-sys"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
dependencies = [
"pkg-config",
]
[[package]]
name = "libloading"
version = "0.7.4"
@ -784,6 +807,16 @@ dependencies = [
"hashbrown 0.15.5",
]
[[package]]
name = "media"
version = "0.1.0-rc.2"
dependencies = [
"fader-core",
"regex",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "memchr"
version = "2.8.3"
@ -1451,6 +1484,7 @@ name = "tui"
version = "0.1.0-rc.2"
dependencies = [
"fader-core",
"media",
"ratatui",
]

View File

@ -1,5 +1,5 @@
[workspace]
members = ["config", "core", "fader_master", "midi", "sound", "tui"]
members = ["config", "core", "fader_master", "media", "midi", "sound", "tui"]
resolver = "3"
[workspace.package]
@ -11,6 +11,8 @@ repository = "https://proxy.dandaedre.com/gitea/MadGobblins/fader_master"
publish = false
[workspace.dependencies]
dbus = "=0.9.12"
media = { path = "media" }
alsa = "0.12.1"
anyhow = "1.0.104"
clap = { version = "4.6.7", features = ["derive"] }

View File

@ -3,4 +3,4 @@ passthrough = ["RUSTUP_TOOLCHAIN"]
[target.x86_64-unknown-linux-gnu]
image = "ghcr.io/cross-rs/x86_64-unknown-linux-gnu:0.2.5"
pre-build = ["apt-get update && apt-get install --assume-yes --no-install-recommends pkg-config libasound2-dev libpulse-dev libudev-dev"]
pre-build = ["apt-get update && apt-get install --assume-yes --no-install-recommends pkg-config libasound2-dev libpulse-dev libudev-dev libdbus-1-dev"]

15
Jenkinsfile vendored
View File

@ -119,6 +119,8 @@ pipeline {
steps {
sh '''
set -eu
pkg-config --exists alsa libpulse libudev dbus-1
command -v dbus-run-session
cargo check --workspace --all-targets --locked
cargo check --workspace --all-targets --no-default-features --locked
cargo check --workspace --all-targets --all-features --locked
@ -134,6 +136,7 @@ pipeline {
cargo test --workspace --all-targets --locked
cargo test --workspace --all-targets --no-default-features --locked
cargo test --workspace --all-targets --all-features --locked
dbus-run-session -- cargo test -p fader_master private_bus --locked -- --ignored
: >"coverage/.tests-passed-${BUILD_NUMBER}"
'''
}
@ -145,18 +148,18 @@ pipeline {
sh '''
set -eu
cargo check -p fader-core -p fader-config -p midi -p volume_lib -p tui \
cargo check -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
--all-targets --no-default-features --locked
cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui \
cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
--all-targets --no-default-features --locked
cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui \
cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
--doc --no-default-features --locked
RUSTDOCFLAGS='-D warnings' \
cargo doc -p fader-core -p fader-config -p midi -p volume_lib -p tui \
cargo doc -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
--no-deps --no-default-features --locked
cargo clippy -p fader-core -p fader-config -p midi -p volume_lib -p tui \
cargo clippy -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
--all-targets --no-default-features --locked -- -D warnings
cargo build -p fader-core -p fader-config -p midi -p volume_lib -p tui \
cargo build -p fader-core -p fader-config -p midi -p volume_lib -p tui -p media \
--release --no-default-features --locked
: >"coverage/.tests-passed-${BUILD_NUMBER}"

View File

@ -19,7 +19,11 @@ cards, including one-row Slim and Bordered slim faders:
## Features
- Match PulseAudio or `pipewire-pulse` streams by application metadata, with
exact and regular-expression capture rules.
exact and regular-expression capture rules, Any/All composition, and available
executable/working-directory and Steam IDs.
- Target MPRIS players directly from the Media tab or MIDI: transport, seeking,
shuffle, repeat and playlists, with confirmed-state feedback and global/local
feedback switches. See [media configuration](docs/configuration.md#media-controls-mpris).
- Control individual applications, non-nesting application groups, and the
default output without changing live audio during discovery.
- Learn volume and mute controls from MIDI, reflect confirmed mute state on

View File

@ -126,11 +126,102 @@ All outer crates depend inward on domain contracts; core depends on none of them
- `SurfaceId`, `FaderId`, `ApplicationId`, `GroupId`, and `ProfileId` are stable persisted user IDs. Renaming a display label preserves its ID.
- A physical binding is `(surface ID, MIDI channel, message kind, control number) -> fader ID + action`. A logical fader targets exactly one `Application`, `Group`, or the `default` output (later, an explicit `HardwareMixer`). Several faders/surfaces may target the same object.
- An application object has selectors on explicit normalized fields: `application.name`, `application.id`, `application.process.binary`, or `media.name`. Preserve raw backend metadata for inspection. Never silently substitute one field for another.
- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Multiple selectors for an application are ORed. Missing properties do not match. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor.
- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Application `selector_mode` defaults to `any` (OR); `all` requires every selector (AND). Missing properties do not match. Empty lists and unknown modes are rejected. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor.
- A matching application controls all its current playback streams. Stopped applications remain configured and display offline; new streams are discovered dynamically. Runtime handles include backend connection epoch plus object ID and an incarnation where needed to prevent ID-reuse bugs. PIDs, backend indices, and discovery order are never durable identity.
- Groups reference application IDs only in v1; no nested groups or cycles. Overlapping selectors/groups are allowed: deduplicate resolved streams within each command and show overlap in the editor. Separate commands are serialized by server arrival order; the last accepted command touching a stream wins. Overlap is shared control, not multiple multiplicative gain layers.
- Maintain requested state, observed per-stream/per-channel state, pending operation IDs, errors, and availability separately. A write acknowledgment means accepted by the adapter; success requires observation/readback. Derived objects can be `mixed`, `offline`, `pending`, or `partially failed`.
### Matching and media-control extensions
The agreed stretch-goal order is AND selectors and richer process metadata,
then targeted MPRIS media controls (M13 in `task.md`). Selector composition is
implemented in the domain/configuration layer and the fader editor's Match
captures toggle (Any/OR or All/AND). Process metadata uses bounded Pulse-worker
enrichment; MPRIS controls are implemented on the development branch after RC2.
The existing `media.name` regex `(?i) - YouTube$` is sufficient for YouTube
streams whose reported title has that suffix. Do not couple this use case to
browser identity, window-title concatenation, or the AND matcher.
AND composition must preserve the meaning of existing OR selector lists and
keep field matching explicit, validated, and visible in the editor. Process
enrichment belongs in an adapter, not the domain matcher: resolve available
executable/working-directory and Steam launch metadata from the reported PID,
with bounded reads, process-reuse checks, and unavailable values on failure.
Read only relevant environment keys; do not expose entire environments or
command lines in diagnostics. Steam IDs and launch context are evidence;
`steamapps` paths are a fallback installation hint, not proof of launch origin.
The implemented process fields are `application.process.executable`,
`application.process.working_directory`, `steam.app_id` and `steam.game_id`.
Pulse callbacks copy only reported PID/machine ID; enrichment runs afterward on
the adapter worker. Require the reported machine ID to equal the local one,
read start time before/after inspection, and discard values if the process
changes or disappears. Reads are bounded (stat 4 KiB, environment 64 KiB), and
only nonzero numeric SteamAppId/SteamGameId values leave the environment parser.
Missing/oversized/inaccessible values remain absent; paths are not launch proof.
Reported PIDs are best-effort hints, not authenticated identities; remote and
namespace-restricted applications may be unavailable. No command lines or full
environments enter diagnostics. The start-time check follows Linux
[/proc/pid/stat](https://man7.org/linux/man-pages/man5/proc_pid_stat.5.html).
MPRIS controls address matched player instances over D-Bus using identity,
desktop ID or bus-name selectors, with Play, Pause and PlayPause actions. Keep
media-player discovery independent of active audio streams so paused players
remain controllable. Extend MIDI learn, capability/state reporting and TUI
editing through the server owner; use confirmed playback state for feedback.
Resolve multiple matches explicitly rather than choosing an arbitrary player.
This controls players such as QBZ directly, without synthetic keyboard input.
The approved Media tab lists configured player/control sets with stable IDs,
labels, explicit exact/regex selectors and observed state. Discovery supplies a
picker without a builtin player catalogue; manual selectors remain available.
Multiple matches are ambiguous and block commands. The server advertises session
bus availability to the client: no running players is an empty list, not a reason
to hide the tab; a later disconnect retains the tab with an unavailable status.
The scope includes Stop/Next/Previous, relative and absolute seeking, shuffle,
repeat and playlist discovery/activation, gated by player capabilities. Playlist
content editing is not included. Learn/unbind, validated editing and persisted
configuration follow the mixer conventions.
Feedback uses confirmed state, with exclusive Play/Pause/Stop indicators and
explicit device-specific colour mappings; default note output is same-note 127/0.
Global and per-fader/per-media-entry switches gate MIDI output. Global off sends
no messages (even clearing messages), so existing lights may remain lit until
feedback is re-enabled and resynchronized. Save activates feedback-gate changes.
Global and per-fader gates now use `feedback_enabled` (default true) at root and
fader-table scope, applied on configuration Save, including explicit mappings.
The protocol boundary follows the
[MPRIS Player interface](https://specifications.freedesktop.org/mpris/latest/Player_Interface.html).
The hardware-free `media` crate defines player selectors, capability-aware
actions, observed playback state, configuration entries and MIDI feedback rules.
`[[media]]` entries have stable IDs, labels, a selector, a default-enabled feedback
gate, and controls with stable IDs/actions/optional bindings. Configuration
validates selectors, limits, references and input collisions with mixer bindings
before activation. Entry editing is transactional; removing a surface unbinds its
media controls without deleting entries. The live server routes media MIDI press
edges through the bounded worker and exposes discovery, capabilities and state
over IPC. The optional Media tab edits draft entries and controls; Save activates
them. Learn/unbind is scoped to a selected control and surface. Media commands
are not retried by the client after ambiguous transport failures.
IPC frames are limited to 1 MiB (oversized lengths are rejected before allocation).
Media configuration and discovery each have a 256 KiB serialized budget, so a
256-playlist response does not exceed the previous 64 KiB frame limit. Discovery
fails closed instead of publishing an incomplete set that could hide ambiguity.
The MPRIS adapter uses pinned `dbus` 0.9.12 (MIT/Apache-2.0) and system
libdbus-1; its upstream manifest does not declare an MSRV, so compatibility is
verified by building with the repository's Rust 1.88 toolchain. A dedicated
joined thread owns the blocking connection. Calls have 200 ms timeouts, polling
uses 250 ms intervals, and the command queue holds at most 32 requests. Discovery
limits player count to 32 and lists the first 256 playlist choices per player.
Exhausted player-discovery bounds fail closed rather than selecting from an
incomplete player set. Polling (rather than signal subscriptions) also observes
external playback/capability changes and replacement owners; it trades a bounded
delay and extra reads for a small, recoverable worker without a second event loop.
Commands resolve a fresh snapshot and address a unique bus owner, not a reusable
well-known name; feedback comes only from readback. Missing optional properties
remain unavailable. Connection failure triggers reconnect; configuration
activation fences queued and in-flight work before replacing the active profile.
## Volume and mute semantics
The core stores finite, non-negative linear amplitude gain; `1.0` is unity, `0.0` is silence. Adapters convert native representations explicitly; PulseAudio volume numbers and PipeWire linear gain must not be treated as interchangeable percentages. Preserve per-channel balance by scaling channel gains relative to their maximum. If all channels are zero, an explicit nonzero command initializes them equally. Tests cover silence, clipping, NaN/infinity rejection, and round trips.
@ -574,10 +665,16 @@ presents domain fields rather than a serialized command:
Home/End, accept, and cancel controls; group faders instead present a member
summary that opens a multi-select popup, plus the currently available group
mode.
- **Volume control:** separate controller selection, Learn MIDI, and Unlearn
MIDI actions.
- **Mute control:** separate controller selection, Learn MIDI, and Unlearn MIDI
actions.
Capture also has a Save and exit row to submit field/mode changes without
reopening Pattern. Both submission paths validate the current selector using
the domain's bounded exact/regex rules before queueing the draft edit; invalid
input retains the form and an inline error. Configuration Save remains the
separate persistence/activation operation.
- **Volume control:** controller selection and Learn MIDI. The learn prompt
offers `U` to unbind the current volume assignment and `Esc` to cancel.
- **Mute control:** controller selection and Learn MIDI, with the same prompt
shortcuts scoped to the mute assignment. Unbinding cancels capture first,
preserves the other action, and retains the selected controller for relearning.
- **Size:** Slim, Bordered slim, Standard, or Thick vertical presentation for
this fader.
- **Visibility:** Hide from mixer or Show in mixer without changing routing.

View File

@ -30,6 +30,36 @@ Known mappings: Music `CC48/Note64`, Browser `CC49/Note65`, Media sync
`CC50/Note66`, and Master `CC56/Note98`. The profile polling interval is 10 ms
and accepts 1–100 ms.
## MPRIS/QBZ opt-in checks (new, not yet hardware-qualified)
Use a disposable profile, build with default `mpris` support and restart both
processes. Start QBZ in the same user's desktop session; leave it paused and
start a second, different MPRIS player to check targeting. Configure the real
controller input/output ports (do not overwrite the checked-in examples).
- [ ] Media appears even with no audio stream; P discovers paused QBZ. A manual
exact bus-name selector reaches QBZ only. A broad regex matching both players
reports ambiguity and sends no command.
- [ ] A/E/D, rename, control action/parameter editing and Save/exit survive Save,
server restart and client reconnect. Unsupported controls show unsupported.
- [ ] Learn Play/Pause/Stop, release/hold buttons and U-unbind. Only presses act;
bindings persist after Save/restart. Removing the surface unbinds controls.
- [ ] Only the confirmed Play/Pause/Stop state lights. External player changes
update LEDs. Verify controller-specific on/off colors; reconnect resynchronizes.
- [ ] Global, per-fader and per-entry feedback switches send no output while off,
including no clearing messages. Re-enable/Save restores observed indicators.
- [ ] Seek forward/back and absolute position, shuffle, repeat and playlist
activation work where QBZ reports support. Unsupported properties stay disabled.
- [ ] Quit/restart QBZ, switch profiles and unplug/replug the controller. Errors
recover; expired commands are not replayed against a replacement player.
Hardware-free D-Bus qualification (creates its own bus and fake players, never
controls desktop applications):
```sh
dbus-run-session -- cargo test -p fader_master private_bus -- --ignored
```
## Mixer smoke test
- [x] TUI shows Music, Browser, Media, Master, and the APC backend ID; startup

View File

@ -8,6 +8,7 @@ repository.workspace = true
publish.workspace = true
[dependencies]
media.workspace = true
fader-core.workspace = true
rustix.workspace = true
serde.workspace = true

View File

@ -212,7 +212,29 @@ pickup_tolerance = 0.02
/// Removes a MIDI surface and all configuration that references it.
pub fn remove_surface(&mut self, id: &str) -> Result<(), ConfigError> {
let mut updates = Vec::new();
for mut entry in self.preview()?.media().iter().cloned() {
if entry
.controls
.iter()
.any(|c| c.binding.as_ref().is_some_and(|b| b.surface == id))
{
for control in &mut entry.controls {
if control.binding.as_ref().is_some_and(|b| b.surface == id) {
control.binding = None;
}
}
let mut table = DocumentMut::from_str(&toml::to_string(&entry)?)?
.as_table()
.clone();
clear_table_positions(&mut table);
updates.push((entry.id, table));
}
}
self.transaction(|document| {
for (entry, table) in updates {
*find_table_mut(document, "media", &entry)? = table;
}
remove_table_entry(document, "surfaces", id)?;
if let Some(bindings) = document
.get_mut("bindings")
@ -300,6 +322,66 @@ pickup_tolerance = 0.02
})
}
/// Creates or updates one validated media entry atomically.
pub fn set_media_entry(&mut self, entry: &media::Entry) -> Result<(), ConfigError> {
let serialized = toml::to_string(entry)?;
let mut replacement = DocumentMut::from_str(&serialized)?.as_table().clone();
clear_table_positions(&mut replacement);
self.transaction(|document| {
let entries = array_of_tables_mut(document, "media")?;
if let Some(existing) = entries
.iter_mut()
.find(|t| t.get("id").and_then(Item::as_str) == Some(entry.id.as_str()))
{
*existing = replacement;
} else {
entries.push(replacement);
}
Ok(())
})
}
pub fn remove_media_entry(&mut self, id: &str) -> Result<(), ConfigError> {
self.transaction(|document| {
let entries = array_of_tables_mut(document, "media")?;
let index = entries
.iter()
.position(|t| t.get("id").and_then(Item::as_str) == Some(id))
.ok_or_else(|| ConfigError::validation("media", "unknown media entry"))?;
entries.remove(index);
Ok(())
})
}
/// Sets the global or per-fader MIDI feedback gate transactionally.
pub fn set_feedback_enabled(
&mut self,
fader: Option<&str>,
enabled: bool,
) -> Result<(), ConfigError> {
self.transaction(|document| {
if let Some(id) = fader {
find_table_mut(document, "faders", id)?["feedback_enabled"] = value(enabled);
} else {
document["feedback_enabled"] = value(enabled);
}
Ok(())
})
}
/// Changes selector composition without replacing selectors or their comments.
pub fn set_application_selector_mode(
&mut self,
id: &str,
mode: crate::SelectorMode,
) -> Result<(), ConfigError> {
self.transaction(|document| {
let table = find_table_mut(document, "applications", id)?;
table["selector_mode"] = value(mode.as_str());
Ok(())
})
}
/// Replaces one capture selector while retaining every other selector.
pub fn set_application_selector(
&mut self,
@ -853,6 +935,24 @@ fn find_table_mut<'a>(
.ok_or_else(|| ConfigError::validation(section, format!("unknown {section} entry {id:?}")))
}
fn clear_table_positions(table: &mut Table) {
let mut unpositioned = Table::new();
for (key, item) in table.iter() {
unpositioned.insert(key, item.clone());
}
*table = unpositioned;
for (_, item) in table.iter_mut() {
if let Some(child) = item.as_table_mut() {
clear_table_positions(child);
}
if let Some(children) = item.as_array_of_tables_mut() {
for child in children.iter_mut() {
clear_table_positions(child);
}
}
}
}
fn array_of_tables_mut<'a>(
document: &'a mut DocumentMut,
section: &str,

View File

@ -29,8 +29,8 @@ pub use paths::{XdgEnvironment, XdgPaths};
pub use profile::{
Action, Adapter, Application, Audio, Binding, Fader, FaderDensity, Group, MessageKind,
MixerLayoutEntry, MixerOrientation, NewStreamPolicy, Profile, Selector, SelectorField,
SeparatorDecoration, SeparatorSize, StartupPolicy, StatusDisplayMode, Surface, TargetKind,
UiTheme,
SelectorMode, SeparatorDecoration, SeparatorSize, StartupPolicy, StatusDisplayMode, Surface,
TargetKind, UiTheme,
};
pub use state::{
CachedObservation, DesiredWrite, PersistedState, ProfileState, StartupState, UiView,

View File

@ -12,6 +12,9 @@ use serde::{Deserialize, Serialize};
use crate::{ConfigError, SCHEMA_VERSION};
const DEFAULT_POLL_INTERVAL_MS: u64 = 10;
const fn enabled() -> bool {
true
}
const MIN_POLL_INTERVAL_MS: u64 = 1;
const MAX_POLL_INTERVAL_MS: u64 = 100;
@ -127,6 +130,30 @@ pub struct Application {
id: String,
label: String,
selectors: Vec<Selector>,
#[serde(default)]
selector_mode: SelectorMode,
}
/// Composition of an application's nonempty capture selector list.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SelectorMode {
/// Legacy OR behavior.
#[default]
Any,
/// Require every selector to match.
All,
}
impl SelectorMode {
/// Stable TOML representation.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Any => "any",
Self::All => "all",
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
@ -149,6 +176,14 @@ pub enum SelectorField {
ProcessBinary,
#[serde(rename = "media.name")]
MediaName,
#[serde(rename = "application.process.executable")]
ProcessExecutable,
#[serde(rename = "application.process.working_directory")]
ProcessWorkingDirectory,
#[serde(rename = "steam.app_id")]
SteamAppId,
#[serde(rename = "steam.game_id")]
SteamGameId,
}
impl SelectorField {
@ -158,6 +193,10 @@ impl SelectorField {
Self::ApplicationId => "application.id",
Self::ProcessBinary => "application.process.binary",
Self::MediaName => "media.name",
Self::ProcessExecutable => "application.process.executable",
Self::ProcessWorkingDirectory => "application.process.working_directory",
Self::SteamAppId => "steam.app_id",
Self::SteamGameId => "steam.game_id",
}
}
}
@ -228,6 +267,8 @@ struct Target {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Fader {
#[serde(default = "enabled")]
feedback_enabled: bool,
id: String,
target: Target,
pickup: bool,
@ -349,6 +390,10 @@ pub struct Binding {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct RawProfile {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
media: Vec<media::Entry>,
#[serde(default = "enabled")]
feedback_enabled: bool,
schema_version: u16,
id: String,
startup: StartupPolicy,
@ -381,6 +426,13 @@ pub struct Profile {
}
impl Profile {
pub fn media(&self) -> &[media::Entry] {
&self.raw.media
}
/// Master gate for every MIDI output message generated as feedback.
pub const fn feedback_enabled(&self) -> bool {
self.raw.feedback_enabled
}
/// Parses strict TOML and validates all cross-document invariants.
pub fn parse(input: &str) -> Result<Self, ConfigError> {
let raw: RawProfile = toml::from_str(input)?;
@ -389,6 +441,7 @@ impl Profile {
validate_runtime(&raw.runtime)?;
validate_audio(&raw.audio)?;
validate_profile_members(&raw)?;
validate_media(&raw)?;
let mixer_layout = effective_mixer_layout(&raw);
Ok(Self {
raw,
@ -478,6 +531,15 @@ impl Profile {
/// off=0, whenever the surface has an output. Other protocols are explicit.
/// This does not rewrite the document or override an explicit mapping.
pub fn effective_feedback(&self, binding: &Binding) -> Option<Feedback> {
if !self.feedback_enabled()
|| !self
.faders()
.iter()
.find(|f| f.id() == binding.fader())?
.feedback_enabled()
{
return None;
}
if let Some(feedback) = binding.feedback() {
return Some(feedback.clone());
}
@ -513,6 +575,63 @@ impl Profile {
}
}
fn validate_media(raw: &RawProfile) -> Result<(), ConfigError> {
let invalid = |message: String| ConfigError::validation("media", message);
#[derive(Serialize)]
struct MediaSize<'a> {
media: &'a [media::Entry],
}
if toml::to_string(&MediaSize { media: &raw.media })
.map_err(|e| invalid(e.to_string()))?
.len()
> 256 * 1024
{
return Err(invalid("media configuration exceeds 256 KiB".into()));
}
if raw.media.len() > 128 {
return Err(invalid("at most 128 media entries".into()));
}
let mut ids = BTreeSet::new();
let mut inputs = BTreeSet::new();
for binding in &raw.bindings {
inputs.insert((
binding.surface.as_str(),
binding.message.kind == MessageKind::Note,
binding.message.channel,
binding.message.number,
));
}
for entry in &raw.media {
entry.validate().map_err(|e| invalid(e.to_string()))?;
if !ids.insert(&entry.id) {
return Err(invalid("duplicate media entry ID".into()));
}
for control in &entry.controls {
if let Some(binding) = &control.binding {
let surface = raw
.surfaces
.iter()
.find(|s| s.id == binding.surface)
.ok_or_else(|| invalid(format!("unknown surface {}", binding.surface)))?;
if binding.feedback.is_some() && surface.output_port.is_none() {
return Err(invalid("media feedback needs an output port".into()));
}
if !inputs.insert((
binding.surface.as_str(),
binding.message.kind == media::MessageKind::Note,
binding.message.channel,
binding.message.number,
)) {
return Err(invalid(
"MIDI input is already bound to another action".into(),
));
}
}
}
}
Ok(())
}
impl Audio {
/// Configured automatic or manual adapter choice.
#[must_use]
@ -552,6 +671,12 @@ impl Application {
&self.selectors
}
/// How this application's capture selectors are combined.
#[must_use]
pub const fn selector_mode(&self) -> SelectorMode {
self.selector_mode
}
/// Compiles this validated application's selectors for live stream matching.
pub fn matcher(&self) -> Result<ApplicationMatcher, ConfigError> {
let id = parse_id::<ApplicationId>(&self.id, "application.id")?;
@ -560,7 +685,11 @@ impl Application {
.iter()
.map(Selector::compile)
.collect::<Result<Vec<_>, _>>()?;
ApplicationMatcher::new(id, selectors)
let mode = match self.selector_mode {
SelectorMode::Any => fader_core::SelectorMode::Any,
SelectorMode::All => fader_core::SelectorMode::All,
};
ApplicationMatcher::with_mode(id, selectors, mode)
.map_err(|error| ConfigError::validation("application.selectors", error.to_string()))
}
}
@ -588,6 +717,10 @@ impl Selector {
SelectorField::ApplicationId => MetadataField::ApplicationId,
SelectorField::ProcessBinary => MetadataField::ProcessBinary,
SelectorField::MediaName => MetadataField::MediaName,
SelectorField::ProcessExecutable => MetadataField::ProcessExecutable,
SelectorField::ProcessWorkingDirectory => MetadataField::ProcessWorkingDirectory,
SelectorField::SteamAppId => MetadataField::SteamAppId,
SelectorField::SteamGameId => MetadataField::SteamGameId,
};
match (&self.exact, &self.regex) {
(Some(pattern), None) => DomainSelector::exact(field, pattern),
@ -685,6 +818,9 @@ impl Surface {
}
impl Fader {
pub const fn feedback_enabled(&self) -> bool {
self.feedback_enabled
}
pub fn id(&self) -> &str {
&self.id
}
@ -1012,6 +1148,10 @@ fn validate_selector(
SelectorField::ApplicationId => MetadataField::ApplicationId,
SelectorField::ProcessBinary => MetadataField::ProcessBinary,
SelectorField::MediaName => MetadataField::MediaName,
SelectorField::ProcessExecutable => MetadataField::ProcessExecutable,
SelectorField::ProcessWorkingDirectory => MetadataField::ProcessWorkingDirectory,
SelectorField::SteamAppId => MetadataField::SteamAppId,
SelectorField::SteamGameId => MetadataField::SteamGameId,
};
match (&selector.exact, &selector.regex) {
(Some(pattern), None) => DomainSelector::exact(field, pattern)

View File

@ -5,6 +5,30 @@ use fader_config::{
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn selector_mode_edit_survives_serialization_without_replacing_selectors() {
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
let original = draft.preview().unwrap().applications()[0]
.selectors()
.to_vec();
draft
.set_application_selector_mode("music", fader_config::SelectorMode::All)
.unwrap();
let saved = draft.source();
let restored = ProfileDocument::parse(&saved).unwrap().preview().unwrap();
assert_eq!(
restored.applications()[0].selector_mode(),
fader_config::SelectorMode::All
);
assert_eq!(restored.applications()[0].selectors(), original);
assert!(
draft
.set_application_selector_mode("missing", fader_config::SelectorMode::Any)
.is_err()
);
assert_eq!(draft.source(), saved);
}
#[test]
fn removing_a_surface_clears_its_bindings_and_default_controller_atomically() {
let mut draft = ProfileDocument::parse(PROFILE).unwrap();

View File

@ -6,6 +6,151 @@ const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml");
const ARCH_PIPEWIRE: &str = include_str!("../../examples/profiles/arch-pipewire.toml");
const ARCHITECTURE: &str = include_str!("../../architecture.md");
#[test]
fn documented_media_profile_validates_and_round_trips_all_action_kinds() {
let source = include_str!("../../examples/profiles/media-qbz.toml");
let profile = Profile::parse(source).unwrap();
assert_eq!(profile.media()[0].controls.len(), 14);
assert_eq!(
profile,
Profile::parse(&profile.to_toml().unwrap()).unwrap()
);
let mut document = fader_config::ProfileDocument::parse(source).unwrap();
document.set_media_entry(&profile.media()[0]).unwrap();
assert_eq!(document.preview().unwrap().media(), profile.media());
}
#[test]
fn media_configuration_has_a_bounded_ipc_budget() {
let mut source = EXAMPLE.to_owned();
for n in 0..8 {
source.push_str(&format!("\n[[media]]\nid = 'entry-{n}'\nlabel = 'Player'\nselector = {{ field = 'identity', pattern = 'Player' }}\n"));
for c in 0..64 {
source.push_str(&format!("[[media.controls]]\nid = 'control-{c}'\naction = {{ kind = 'playlist', id = '/{}' }}\n", "x".repeat(1000)));
}
}
assert!(
Profile::parse(&source)
.unwrap_err()
.to_string()
.contains("256 KiB")
);
}
#[test]
fn media_entries_round_trip_and_validate_selectors_and_midi_collisions() {
let extra = r#"
[[media]]
id = "qbz"
label = "QBZ"
feedback_enabled = false
selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz" }
controls = [{ id = "play", action = { kind = "play" }, binding = { surface = "desk-left", message = { kind = "note", channel = 1, number = 40 } } }]
"#;
let source = format!("{EXAMPLE}\n{extra}");
let profile = Profile::parse(&source).unwrap();
let mut document = fader_config::ProfileDocument::parse(&source).unwrap();
let mut entry = profile.media()[0].clone();
entry.label = "Renamed QBZ".into();
document.set_media_entry(&entry).unwrap();
assert_eq!(document.preview().unwrap().media()[0].label, "Renamed QBZ");
document.remove_surface("desk-left").unwrap();
assert!(
document.preview().unwrap().media()[0].controls[0]
.binding
.is_none()
);
document.remove_media_entry("qbz").unwrap();
assert!(document.preview().unwrap().media().is_empty());
assert_eq!(
profile,
Profile::parse(&profile.to_toml().unwrap()).unwrap()
);
assert!(Profile::parse(&source.replace("number = 40", "number = 32")).is_err());
assert!(
Profile::parse(&source.replace("field = \"bus_name\"", "field = \"unknown\"")).is_err()
);
}
#[test]
fn feedback_switches_override_explicit_and_default_output() {
for source in [
format!("feedback_enabled = false\n{EXAMPLE}"),
EXAMPLE.replace("pickup = true", "pickup = true\nfeedback_enabled = false"),
] {
let profile = Profile::parse(&source).unwrap();
assert!(
profile
.bindings()
.iter()
.all(|binding| profile.effective_feedback(binding).is_none())
);
}
let profile = Profile::parse(EXAMPLE).unwrap();
assert!(profile.effective_feedback(&profile.bindings()[1]).is_some());
}
#[test]
fn enriched_process_fields_match_only_available_values() {
let metadata = StreamMetadata::new().with_process_metadata(
Some("/games/Game/game.exe".into()),
Some("/games/Game".into()),
Some("123".into()),
Some("456".into()),
);
for (field, pattern) in [
("application.process.executable", "/games/Game/game.exe"),
("application.process.working_directory", "/games/Game"),
("steam.app_id", "123"),
("steam.game_id", "456"),
] {
let source = EXAMPLE.replace(
"field = \"application.name\", exact = \"Music Player\"",
&format!("field = {field:?}, exact = {pattern:?}"),
);
let profile = Profile::parse(&source).unwrap();
let matcher = profile.applications()[0].matcher().unwrap();
assert!(matcher.matches(&metadata));
assert!(!matcher.matches(&StreamMetadata::new()));
}
}
#[test]
fn selector_composition_defaults_to_any_and_all_requires_every_field() {
let source = EXAMPLE.replace(
"selectors = [{ field = \"application.name\", exact = \"Music Player\" }]",
"selectors = [{ field = \"application.name\", exact = \"Music Player\" }, { field = \"media.name\", regex = '(?i) - YouTube$' }]",
);
let partial = StreamMetadata::new().with_application_name("Music Player");
let complete = partial.clone().with_media_name("A song - YouTube");
let legacy = Profile::parse(&source).unwrap();
assert!(
legacy.applications()[0]
.matcher()
.unwrap()
.matches(&partial)
);
let source = source.replacen(
"label = \"Music\"",
"label = \"Music\"\nselector_mode = \"all\"",
1,
);
let profile = Profile::parse(&source).unwrap();
let matcher = profile.applications()[0].matcher().unwrap();
assert!(!matcher.matches(&partial));
assert!(matcher.matches(&complete));
assert!(!matcher.matches(&complete.with_application_name("Other Player")));
assert_eq!(
profile,
Profile::parse(&profile.to_toml().unwrap()).unwrap()
);
assert!(
Profile::parse(&source.replace("selector_mode = \"all\"", "selector_mode = \"xor\""))
.is_err()
);
assert!(Profile::parse(&source.replace("regex = '(?i) - YouTube$'", "regex = '['")).is_err());
}
#[test]
fn architecture_profile_parses_and_round_trips_semantically() {
let marker = "The following profile";

View File

@ -31,7 +31,7 @@ pub use group::{RelativeGroupState, VolumeMode, VolumeView, plan_volume, volume_
pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId};
pub use matching::{
ApplicationMatcher, ApplicationRuntime, ApplicationSelector, MetadataField, SelectorError,
SelectorKind, StreamHandle, StreamMetadata,
SelectorKind, SelectorMode, StreamHandle, StreamMetadata,
};
pub use mute::{MuteIntent, MutePlanner, mute_view};
pub use pickup::{Pickup, PickupError, PickupState};

View File

@ -19,6 +19,14 @@ pub enum MetadataField {
ProcessBinary,
/// Backend `media.name`.
MediaName,
/// Locally observed executable path, not merely a reported binary name.
ProcessExecutable,
/// Locally observed working directory.
ProcessWorkingDirectory,
/// SteamAppId launch-environment evidence (not proof of launch origin).
SteamAppId,
/// SteamGameId launch-environment evidence, including non-Steam shortcuts.
SteamGameId,
}
/// Normalized fields plus untouched backend metadata for diagnostics.
@ -28,6 +36,10 @@ pub struct StreamMetadata {
application_id: Option<String>,
process_binary: Option<String>,
media_name: Option<String>,
process_executable: Option<String>,
process_working_directory: Option<String>,
steam_app_id: Option<String>,
steam_game_id: Option<String>,
raw: BTreeMap<String, String>,
}
@ -66,6 +78,22 @@ impl StreamMetadata {
self
}
/// Attaches adapter-observed process metadata. Missing values stay unknown.
#[must_use]
pub fn with_process_metadata(
mut self,
executable: Option<String>,
working_directory: Option<String>,
steam_app_id: Option<String>,
steam_game_id: Option<String>,
) -> Self {
self.process_executable = executable;
self.process_working_directory = working_directory;
self.steam_app_id = steam_app_id;
self.steam_game_id = steam_game_id;
self
}
/// Adds an untouched backend property for inspection.
#[must_use]
pub fn with_raw_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
@ -81,6 +109,10 @@ impl StreamMetadata {
MetadataField::ApplicationId => self.application_id.as_deref(),
MetadataField::ProcessBinary => self.process_binary.as_deref(),
MetadataField::MediaName => self.media_name.as_deref(),
MetadataField::ProcessExecutable => self.process_executable.as_deref(),
MetadataField::ProcessWorkingDirectory => self.process_working_directory.as_deref(),
MetadataField::SteamAppId => self.steam_app_id.as_deref(),
MetadataField::SteamGameId => self.steam_game_id.as_deref(),
}
}
@ -230,11 +262,22 @@ fn validate_pattern(pattern: &str) -> Result<(), SelectorError> {
Ok(())
}
/// Immutable OR-combination of selectors for one virtual application.
/// How the nonempty selector list is combined.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum SelectorMode {
/// At least one selector must match (legacy behavior).
#[default]
Any,
/// Every selector must match; absent fields fail their selector.
All,
}
/// Immutable combination of selectors for one virtual application.
#[derive(Clone, Debug)]
pub struct ApplicationMatcher {
id: ApplicationId,
selectors: Vec<ApplicationSelector>,
mode: SelectorMode,
}
impl ApplicationMatcher {
@ -246,11 +289,28 @@ impl ApplicationMatcher {
pub fn new(
id: ApplicationId,
selectors: Vec<ApplicationSelector>,
) -> Result<Self, SelectorError> {
Self::with_mode(id, selectors, SelectorMode::Any)
}
/// Constructs an explicitly combined matcher.
///
/// # Errors
/// Returns [`SelectorError::NoSelectors`] for an empty selector list,
/// including All mode (an empty conjunction must not match everything).
pub fn with_mode(
id: ApplicationId,
selectors: Vec<ApplicationSelector>,
mode: SelectorMode,
) -> Result<Self, SelectorError> {
if selectors.is_empty() {
return Err(SelectorError::NoSelectors { application: id });
}
Ok(Self { id, selectors })
Ok(Self {
id,
selectors,
mode,
})
}
/// Returns the stable application identifier.
@ -259,12 +319,19 @@ impl ApplicationMatcher {
&self.id
}
/// Returns whether any configured selector matches.
/// Returns whether the configured selector combination matches.
#[must_use]
pub fn matches(&self, metadata: &StreamMetadata) -> bool {
self.selectors
.iter()
.any(|selector| selector.matches(metadata))
match self.mode {
SelectorMode::Any => self
.selectors
.iter()
.any(|selector| selector.matches(metadata)),
SelectorMode::All => self
.selectors
.iter()
.all(|selector| selector.matches(metadata)),
}
}
}
@ -413,6 +480,14 @@ mod tests {
assert!(matcher.matches(&StreamMetadata::new().with_process_binary("librewolf")));
}
#[test]
fn empty_conjunction_is_rejected_instead_of_matching_everything() {
assert!(matches!(
ApplicationMatcher::with_mode(application_id(), vec![], SelectorMode::All),
Err(SelectorError::NoSelectors { .. })
));
}
#[test]
fn malformed_and_unbounded_patterns_are_rejected() {
assert!(matches!(

View File

@ -8,6 +8,8 @@
profiles, TOML concepts, migration, validation, and operational commands.
- [Example PipeWire/APC MINI profile](../examples/profiles/arch-pipewire.toml)
- [Example desktop profile](../examples/profiles/desktop.toml)
- [MPRIS controls and editing](configuration.md#media-controls-mpris)
- [Example QBZ media profile](../examples/profiles/media-qbz.toml)
- [Hands-on functional checklist](../checklist.md)
For everyday layout editing: select a fader or separator and press `E`.

View File

@ -6,10 +6,10 @@ toolchain. `rustup` reads `rust-toolchain.toml` and installs the required
`rustfmt`, Clippy, and LLVM tools components.
The default build includes the PulseAudio protocol adapter and links to
libpulse. On a Debian-family Linux system, install:
libpulse. MPRIS is enabled by default and also links to libdbus-1. On a Debian-family Linux system, install:
```sh
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev libudev-dev
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev libudev-dev libdbus-1-dev dbus
rustup toolchain install 1.88.0 \
--profile minimal \
--component rustfmt \
@ -21,11 +21,21 @@ On Arch Linux with PipeWire, install the client library, build tools, and the
PulseAudio-compatible PipeWire service:
```sh
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse systemd-libs pipewire-audio pipewire-pulse wireplumber
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse systemd-libs dbus pipewire-audio pipewire-pulse wireplumber
pactl info
```
The `Server Name` reported by the last command should contain `PulseAudio (on
The executable's `mpris` feature can be omitted with
`cargo build -p fader_master --no-default-features`; this disables only MPRIS,
not the existing audio/MIDI backends. MPRIS runtime requires access to the user's
session bus, not playerctl. CI native runners need libdbus development files too.
The hardware-free protocol fixture runs with:
```sh
dbus-run-session -- cargo test -p fader_master private_bus -- --ignored
```
The `Server Name` reported by `pactl info` should contain `PulseAudio (on
PipeWire ...)`. Arch packages the headers with `libpulse`, rather than in a
separate development package. The application communicates with PipeWire
through `pipewire-pulse`; it does not require the standalone PulseAudio server.

View File

@ -110,7 +110,13 @@ before activating the profile unless a supported schema migration can upgrade it
### Application capture
Selectors are ORed. Each selector chooses exactly one supported metadata field
MIDI feedback defaults to enabled. Set root-level `feedback_enabled = false`
to disable all feedback, or put the same setting in a `[[faders]]` table to
disable only that fader. Config and Edit fader expose these switches. Save the
configuration to apply them. Disabled feedback sends nothing, even light-off
messages; lights may retain their previous state until re-enabled and refreshed.
Selectors are ORed by default. Each selector chooses exactly one supported metadata field
and exactly one matching mode:
```toml
@ -124,9 +130,162 @@ selectors = [
```
Supported fields are `application.name`, `application.id`,
`application.process.binary`, and `media.name`. Exact matches are whole-string
`application.process.binary`, `media.name`, `application.process.executable`,
`application.process.working_directory`, `steam.app_id`, and `steam.game_id`.
Exact matches are whole-string
and case-sensitive. Regexes use Rust's bounded `regex` syntax.
The last four fields are best-effort Linux process observations, currently
provided by the Pulse adapter (including PipeWire's Pulse compatibility server).
Enrichment requires a reported PID and a machine ID matching `/etc/machine-id`.
Executable and working-directory values come from `/proc`; Steam IDs come only
from numeric, nonzero `SteamAppId` / `SteamGameId` environment entries. These
are launch-context evidence, not authenticated proof that Steam launched the
process. A path containing `steamapps` never creates a Steam ID.
Unavailable fields do not match. Processes that exit or change start time during
inspection, restricted `/proc`, remote
servers, container/PID namespace differences, and large environments can prevent
enrichment. Environment reads are limited to 64 KiB; only the two allowlisted IDs
are retained, never complete environment contents or command lines. Proton may
report a Wine executable while its working directory identifies the game.
The Config tab lists normalized fields for each observed stream, including
`unavailable` values. Navigate down through Settings to inspect them; raw
environment contents and command lines are never included.
Applications may set `selector_mode = "all"` to require every selector to
match (AND). The default `"any"` preserves OR matching for existing profiles.
The fader editor's **Match captures** row toggles **Any (OR)** / **All (AND)**
for the application; save the configuration to activate the change. Individual
Capture rows continue to edit their respective selectors without replacing the
rest of the list.
Missing fields fail their selector; empty selector lists and unknown modes are
rejected. For example, requiring a particular application ID and media title:
```toml
[[applications]]
id = "music-video"
label = "Music video"
selector_mode = "all"
selectors = [
{ field = "application.id", exact = "example.player" },
{ field = "media.name", regex = '(?i) - YouTube$' },
]
```
For the original YouTube-only capture use case, the single `media.name` selector
below remains sufficient; no additional application condition is needed.
The capture editor's **Save and exit** row validates and saves the current
field, match mode and pattern to the draft without reopening the pattern popup.
Invalid patterns leave the editor open with an error. **Esc** cancels local
capture changes; use the configuration **Save** action to persist and activate
accepted draft changes.
To capture YouTube playback by its reported media title, use:
```toml
selectors = [
{ field = "media.name", regex = '(?i) - YouTube$' },
]
```
This already works when the browser exposes a title ending in ` - YouTube`
(as observed with Waterfox). The media-title selector alone is sufficient;
no browser-name condition or combined window-title matching is required.
Applications must expose this metadata for it to match.
AND selectors, richer process metadata and direct MPRIS controls are implemented
on the development branch after RC2; rebuild and restart both server and client.
They are not required for the YouTube selector above.
### Media controls (MPRIS)
The **Media** tab (`3`, or `Tab`) appears when the server has MPRIS support and
can connect to the user's session bus. No running players is a valid empty state.
A later disconnect keeps the tab and configured entries visible. Config reports
why support is unavailable. No keyboard emulation or `playerctl` is used; paused
players are discoverable without an audio stream.
In Media, `A` adds an entry, `E` edits its name/selector/feedback/controls, and
`D` asks before deleting the entry. Select a control and press `Enter` to send it.
Unsupported, offline or ambiguous targets cannot be invoked. Draft edits must be
saved with `S` before commands use them. Entries remain configured while offline.
In the entry editor, `P` lists discovered players. Selecting one prefers its
stable DesktopEntry, falling back to its bus name. You can manually choose
`bus_name`, `desktop_entry` or `identity`, and exact or regex matching. Regexes
use substring matching unless anchored; `(?i)` enables case-insensitivity.
Multiple matches block commands—narrow the selector to an exact instance when
necessary. Instance-specific bus-name suffixes may change across restarts.
Failed identity reads also block identity-based selection until discovery recovers.
`A` inside the editor adds a control, and `D` removes the selected control from
the local edit. Enter a control row to edit its action; use left/right to choose
the action. Seek offsets and positions are milliseconds, bounded to one day.
For playlists, left/right cycles observed playlist IDs and displays their names;
Enter permits manual object-path input. Absolute position uses the observed track
ID and requires a known track length. Shuffle and repeat require the player to
report those properties; playlists require the optional Playlists interface.
Playlist-content editing is not supported. Choose **Save and return to entry**,
then **Save and exit (draft)**, and `S` to persist/activate. Entry validation runs
again at Save and exit; Esc discards the entry edit.
Select a control in the list and press `L` to choose a MIDI device and learn its
input. `U` in that prompt unbinds the selected control; Esc cancels learning.
Save to activate the learned binding. Notes trigger on presses, CCs on zero to
nonzero transitions; releases and repeated held values do not repeat commands.
One physical input cannot also be bound to another media or mixer action.
See the validated [complete media profile](../examples/profiles/media-qbz.toml).
An entry uses this shape (append to a profile containing the `buttons` surface):
```toml
[[media]]
id = "qbz"
label = "QBZ"
feedback_enabled = true
selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz", regex = false }
controls = [
{ id = "play", action = { kind = "play" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 40 } } },
{ id = "pause", action = { kind = "pause" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 41 } } },
]
```
Actions are `play`, `pause`, `stop`, `play_pause`, `next`, `previous`,
`seek` (`offset_ms`), `set_position` (`position_ms`), `shuffle_toggle`,
`shuffle` (`enabled`), `repeat_cycle`, `repeat` (`mode = "None"`, `"Track"` or
`"Playlist"`) and `playlist` (`id`, a player-reported D-Bus object path).
All actions may have a MIDI binding. Unbound actions remain usable from the TUI.
Feedback defaults to the same learned note/channel, with 127 on and 0 off, when
the surface has an output port. CC inputs have no implicit feedback. Play, Pause
and Stop lights follow the mutually exclusive **observed** playback state, not
the last button pressed. PlayPause follows Playing; shuffle, repeat and playlist
lights follow the properties the player reports. Seek/next/previous have no
latched indicator. Polling picks up external changes; an accepted command is not
proof that a player changed state. Unavailable/ambiguous state clears enabled
indicators. Successful output is deduplicated and reconnects resynchronize it.
For device-specific colors or CC output, learn first, then edit the control's
Custom feedback fields. The equivalent binding field is:
```toml
feedback = { message = { kind = "note", channel = 1, number = 40 }, on = 3, off = 0 }
```
Color values depend on the controller. Root `feedback_enabled = false` overrides
both per-fader and per-media-entry switches, including explicit mappings. Disabled
feedback sends **nothing**, not even a clearing message; old LEDs may remain lit.
Re-enable and Save to resynchronize. Removing a MIDI device unbinds media controls
without deleting entries.
Limits: 128 entries, 64 controls per entry, 256-byte selectors, 256 KiB of media
configuration; discovery handles up to 32 players and lists the first 256 playlists
per player. Oversized/incomplete player discovery fails closed. Calls time out and
errors are reported; missing players are rediscovered automatically. Timed-out
commands are not replayed. Restart both processes after upgrading the IPC build.
### Groups and faders
Groups contain application IDs, never other groups. The TUI presents eligible
@ -272,6 +431,11 @@ lights an LED as if it succeeded. Reconnect sends the current state again;
unchanged states are deduplicated. Both note and CC feedback use 1-based
channels and values from 0–127.
In the fader editor, open **Learn volume MIDI** or **Learn mute MIDI** to change
that assignment. Press `U` in the learn prompt to unbind it, or `Esc` to cancel
without changing it. Unbinding leaves the other action intact and keeps the
controller selected for relearning. Save the draft to persist and activate it.
LED values are device-specific: a note velocity can mean a color or animation,
so 127 is not a universal “on” value. The APC MINI example uses its configured
green value. Relearning a mute binding moves its feedback assignment to the new

View File

@ -56,7 +56,8 @@ Rust toolchain and Cargo.lock constrain Rust builds. The container tag and apt
repositories are not digest/snapshot pinned, so bit-for-bit reproducibility
and the minimum supported runtime glibc version are not yet established.
Artifacts are dynamically linked: recipient systems need ALSA, libpulse and
libudev runtime libraries and a running Pulse-compatible audio service.
libudev runtime libraries and a running Pulse-compatible audio service. Builds
with the default MPRIS feature also require libdbus-1 and a user session bus.
## Credentials and invocation
@ -180,3 +181,26 @@ downloaded and verified every asset anonymously, checked archive layout, and
completed an isolated cargo-binstall installation for x86-64 GNU/Linux.
The API confirmed `prerelease = true`, `draft = false` and the five assets.
No existing assets were replaced. Real hardware qualification remains pending.
### Published RC2 build
Published on 2026-10-18: [v0.1.0-rc.2](https://proxy.dandaedre.com/gitea/MadGobblins/fader_master/releases/tag/v0.1.0-rc.2),
marked prerelease, not draft. Source commit:
`8ac222b501cb5bc4fbd5fc5ec52feb4a94301039`; main and the annotated tag were pushed
before packaging. The publisher was built temporarily from the same `ed2ce6e`
fix and used the same digest-pinned Ubuntu 24.04 Cross image documented above.
No globally installed publisher was replaced.
All workspace formatting/check/Clippy/doctest/release gates, default/no-default
tests and independent MIDI/Pulse feature tests passed on Rust 1.88.0. The four
old Arch fixture assertions were aligned with the committed example bindings.
All eight release-wrapper tests passed; ShellCheck was unavailable. Two hardware
tests remain opt-in, and the outstanding M12 qualifications remain open.
Authenticated preview and compile-only packaging passed. Local checks verified
all checksums, the three-binary archive, runtime dependencies and CLI smoke tests.
Publication reused that completed source build and uploaded three binaries,
the archive and `SHA256SUMS`, without replacing assets. The publisher verified
all public downloads/checksums, archive layout and an isolated cargo-binstall
installation. The public API confirmed all five assets, `prerelease = true` and
`draft = false`. Restart both server and client when upgrading.

View File

@ -0,0 +1,42 @@
# Replace port names with your controller's ports, or learn from the TUI.
schema_version = 1
id = "media-qbz"
startup = "adopt"
new_stream = "adopt"
feedback_enabled = true
bindings = []
[audio]
adapter = "auto"
max_gain = 1.0
[[surfaces]]
id = "buttons"
label = "Media buttons"
input_port = "Example Controller MIDI 1"
output_port = "Example Controller MIDI 1"
identity_policy = "require_unique"
motorized = false
[[media]]
id = "qbz"
label = "QBZ"
feedback_enabled = true
selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz", regex = false }
controls = [
{ id = "play", action = { kind = "play" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 40 } } },
{ id = "pause", action = { kind = "pause" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 41 } } },
{ id = "stop", action = { kind = "stop" }, binding = { surface = "buttons", message = { kind = "note", channel = 1, number = 42 } } },
{ id = "toggle", action = { kind = "play_pause" } },
{ id = "next", action = { kind = "next" } },
{ id = "previous", action = { kind = "previous" } },
{ id = "back", action = { kind = "seek", offset_ms = -10000 } },
{ id = "forward", action = { kind = "seek", offset_ms = 10000 } },
{ id = "beginning", action = { kind = "set_position", position_ms = 0 } },
{ id = "shuffle", action = { kind = "shuffle_toggle" } },
{ id = "shuffle-off", action = { kind = "shuffle", enabled = false } },
{ id = "repeat", action = { kind = "repeat_cycle" } },
{ id = "repeat-track", action = { kind = "repeat", mode = "Track" } },
# Select an actual playlist from the player in the editor; this is a placeholder.
{ id = "favorites", action = { kind = "playlist", id = "/playlist/favorites" } },
]

View File

@ -14,6 +14,8 @@ pkg-fmt = "tgz"
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
[dependencies]
media.workspace = true
dbus = { workspace = true, optional = true }
anyhow.workspace = true
clap.workspace = true
fader-config.workspace = true
@ -28,3 +30,7 @@ volume_lib.workspace = true
[dev-dependencies]
tempfile.workspace = true
[features]
default = ["mpris"]
mpris = ["dep:dbus"]

View File

@ -162,6 +162,47 @@ impl ConfigurationEditor {
self.document
.set_application(&id, &label, &[selector(&field, pattern, regex)?])?
}
ConfigurationEdit::SetMediaEntry { entry } => self.document.set_media_entry(&entry)?,
ConfigurationEdit::RemoveMediaEntry { id } => self.document.remove_media_entry(&id)?,
ConfigurationEdit::SetMediaBinding {
entry,
control,
binding,
} => {
let profile = self.document.preview()?;
let mut entry = profile
.media()
.iter()
.find(|e| e.id == entry)
.cloned()
.ok_or_else(|| ConfigError::Validation {
path: "media".into(),
message: "unknown entry".into(),
})?;
let target = entry
.controls
.iter_mut()
.find(|c| c.id == control)
.ok_or_else(|| ConfigError::Validation {
path: "media".into(),
message: "unknown control".into(),
})?;
target.binding = binding;
self.document.set_media_entry(&entry)?;
}
ConfigurationEdit::SetFeedbackEnabled { fader, enabled } => self
.document
.set_feedback_enabled(fader.as_deref(), enabled)?,
ConfigurationEdit::SetApplicationSelectorMode { id, match_all } => {
self.document.set_application_selector_mode(
&id,
if match_all {
fader_config::SelectorMode::All
} else {
fader_config::SelectorMode::Any
},
)?;
}
ConfigurationEdit::SetApplicationSelector {
id,
index,
@ -449,6 +490,10 @@ fn selector(field: &str, pattern: String, regex: bool) -> Result<SelectorDraft,
"application.id" => SelectorField::ApplicationId,
"application.process.binary" => SelectorField::ProcessBinary,
"media.name" => SelectorField::MediaName,
"application.process.executable" => SelectorField::ProcessExecutable,
"application.process.working_directory" => SelectorField::ProcessWorkingDirectory,
"steam.app_id" => SelectorField::SteamAppId,
"steam.game_id" => SelectorField::SteamGameId,
_ => {
return Err(ConfigError::Validation {
path: "application.selector.field".to_owned(),
@ -709,6 +754,44 @@ mod tests {
));
}
#[test]
fn selector_mode_is_saved_reloaded_and_published_to_clients() {
let root = tempdir().unwrap();
let path = root.path().join("desktop.toml");
fs::write(&path, PROFILE).unwrap();
let mut editor =
ConfigurationEditor::new(ProfileDocument::parse(PROFILE).unwrap(), path.clone());
editor
.apply(
0,
ConfigurationEdit::SetApplicationSelectorMode {
id: "music".into(),
match_all: true,
},
)
.unwrap();
editor.save(1).unwrap();
let document = ProfileDocument::parse(&fs::read_to_string(&path).unwrap()).unwrap();
let profile = document.preview().unwrap();
let snapshot = crate::live::configuration_snapshot(&profile, 0, false, 0);
assert!(snapshot.applications[0].match_all);
assert!(!snapshot.applications[1].match_all);
let mut restarted = ConfigurationEditor::new(document, path);
let profile = restarted
.apply(
0,
ConfigurationEdit::SetApplicationSelectorMode {
id: "music".into(),
match_all: false,
},
)
.unwrap();
assert_eq!(
profile.applications()[0].selector_mode(),
fader_config::SelectorMode::Any
);
}
#[test]
fn layout_edits_are_revisioned_without_changing_fader_routing() {
let root = tempdir().unwrap();

View File

@ -4,7 +4,8 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;
pub const PROTOCOL_VERSION: u16 = 24;
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
// Bounded playlist/discovery snapshots can legitimately exceed 64 KiB.
pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
/// Kind of mixer object addressed by a client.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
@ -42,6 +43,15 @@ pub struct ClientRequest {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RequestCommand {
MediaAction {
entry: String,
control: String,
},
StartMediaLearn {
surface: String,
entry: String,
control: String,
},
Snapshot,
EditConfiguration {
expected_revision: u64,
@ -77,6 +87,21 @@ pub enum RequestCommand {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "operation", rename_all = "snake_case")]
pub enum ConfigurationEdit {
SetMediaEntry {
entry: media::Entry,
},
RemoveMediaEntry {
id: String,
},
SetMediaBinding {
entry: String,
control: String,
binding: Option<media::Binding>,
},
SetFeedbackEnabled {
fader: Option<String>,
enabled: bool,
},
AddApplicationFader {
application_id: String,
label: String,
@ -127,6 +152,10 @@ pub enum ConfigurationEdit {
pattern: String,
regex: bool,
},
SetApplicationSelectorMode {
id: String,
match_all: bool,
},
SetApplicationSelector {
id: String,
index: usize,
@ -256,6 +285,16 @@ pub struct MixerSnapshot {
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ConfigurationSnapshot {
#[serde(default)]
pub media_entries: Vec<media::Entry>,
#[serde(default)]
pub media_state: media::Snapshot,
#[serde(default)]
pub feedback_disabled: bool,
#[serde(default)]
pub disabled_feedback_faders: Vec<String>,
#[serde(default)]
pub stream_metadata: Vec<String>,
pub revision: u64,
pub dirty: bool,
pub applied_revision: u64,
@ -356,6 +395,8 @@ pub enum FaderDensity {
pub struct ConfiguredApplication {
pub id: String,
pub label: String,
#[serde(default)]
pub match_all: bool,
pub selectors: Vec<ConfiguredSelector>,
}

View File

@ -8,6 +8,7 @@ mod editor;
pub mod ipc;
pub mod live;
pub mod local;
pub mod media_runtime;
pub mod midi_runtime;
pub mod tui_client;

View File

@ -110,6 +110,15 @@ pub(crate) fn configuration_snapshot(
applied_revision: u64,
) -> ConfigurationSnapshot {
ConfigurationSnapshot {
media_entries: profile.media().to_vec(),
media_state: media::Snapshot::default(),
feedback_disabled: !profile.feedback_enabled(),
disabled_feedback_faders: profile
.faders()
.iter()
.filter(|f| !f.feedback_enabled())
.map(|f| f.id().to_owned())
.collect(),
revision,
dirty,
applied_revision,
@ -118,6 +127,7 @@ pub(crate) fn configuration_snapshot(
error: None,
profile_id: profile.id().to_string(),
profile_path: None,
stream_metadata: Vec::new(),
available_profiles: vec![profile.id().to_string()],
mixer_orientation: match profile.mixer_orientation() {
fader_config::MixerOrientation::Vertical => crate::ipc::MixerOrientation::Vertical,
@ -154,6 +164,7 @@ pub(crate) fn configuration_snapshot(
.map(|application| IpcApplication {
id: application.id().to_owned(),
label: application.label().to_owned(),
match_all: application.selector_mode() == fader_config::SelectorMode::All,
selectors: application
.selectors()
.iter()
@ -289,6 +300,12 @@ const fn selector_field_name(field: fader_config::SelectorField) -> &'static str
fader_config::SelectorField::ApplicationId => "application.id",
fader_config::SelectorField::ProcessBinary => "application.process.binary",
fader_config::SelectorField::MediaName => "media.name",
fader_config::SelectorField::ProcessExecutable => "application.process.executable",
fader_config::SelectorField::ProcessWorkingDirectory => {
"application.process.working_directory"
}
fader_config::SelectorField::SteamAppId => "steam.app_id",
fader_config::SelectorField::SteamGameId => "steam.game_id",
}
}
@ -518,6 +535,48 @@ impl LiveMixerState {
.unwrap_or_else(|| "offline".to_owned());
objects.push(output);
}
let mut configuration = self.configuration.clone();
configuration.stream_metadata = self
.metadata
.iter()
.flat_map(|(handle, view)| {
[
(
"application.name",
fader_core::MetadataField::ApplicationName,
),
("application.id", fader_core::MetadataField::ApplicationId),
(
"application.process.binary",
fader_core::MetadataField::ProcessBinary,
),
("media.name", fader_core::MetadataField::MediaName),
(
"application.process.executable",
fader_core::MetadataField::ProcessExecutable,
),
(
"application.process.working_directory",
fader_core::MetadataField::ProcessWorkingDirectory,
),
("steam.app_id", fader_core::MetadataField::SteamAppId),
("steam.game_id", fader_core::MetadataField::SteamGameId),
]
.map(|(name, field)| {
format!(
"Stream {} · {name}={}",
handle.backend_id(),
view.metadata
.value(field)
.unwrap_or("unavailable")
.chars()
.filter(|c| !c.is_control())
.take(512)
.collect::<String>()
)
})
})
.collect();
MixerSnapshot {
revision: self.view_revision(),
backend: self.backend.clone(),
@ -525,7 +584,7 @@ impl LiveMixerState {
objects,
devices: self.devices.clone(),
discovered_midi_ports: self.discovered_midi_ports.clone(),
configuration: self.configuration.clone(),
configuration,
}
}
@ -554,10 +613,15 @@ impl LiveMixerState {
self.discovered_midi_ports = ports;
}
pub(crate) fn set_configuration(&mut self, configuration: ConfigurationSnapshot) {
pub(crate) fn set_configuration(&mut self, mut configuration: ConfigurationSnapshot) {
configuration.media_state = self.configuration.media_state.clone();
self.configuration = configuration;
}
pub(crate) fn set_media(&mut self, snapshot: media::Snapshot) {
self.configuration.media_state = snapshot;
}
/// Replaces profile-derived routing while retaining confirmed backend state.
pub(crate) fn reconfigure(
&mut self,
@ -817,7 +881,10 @@ impl LiveMixerState {
"configuration edits must be handled by the server owner".to_owned(),
));
}
RequestCommand::StartMidiLearn { .. } | RequestCommand::CancelMidiLearn => {
RequestCommand::StartMidiLearn { .. }
| RequestCommand::CancelMidiLearn
| RequestCommand::StartMediaLearn { .. }
| RequestCommand::MediaAction { .. } => {
return Err(LiveMixerError::Profile(
"MIDI learn commands must be handled by the server owner".to_owned(),
));
@ -1089,6 +1156,31 @@ impl LiveMixerState {
mod reconfigure_tests {
use super::*;
#[test]
fn stream_diagnostics_expose_only_normalized_fields_including_unknowns() {
let profile = Profile::parse(include_str!("../../examples/profiles/desktop.toml")).unwrap();
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
state
.worker_event(WorkerEvent::StreamMetadata {
stream: StreamHandle::new(fader_core::BackendEpoch::new(1), 7, 1),
metadata: StreamMetadata::new()
.with_application_name("Game")
.with_raw_property("SECRET", "never-publish")
.with_process_metadata(
Some("/games/game".into()),
None,
Some("123".into()),
None,
),
volume_writable: true,
})
.unwrap();
let text = format!("{:?}", state.snapshot().configuration);
assert!(text.contains("steam.app_id=123"));
assert!(text.contains("steam.game_id=unavailable"));
assert!(!text.contains("never-publish"));
}
#[test]
fn midi_controls_survive_repeated_reconfiguration() {
let source = include_str!("../../examples/profiles/desktop.toml");

View File

@ -174,6 +174,8 @@ pub fn client_request(
/// Persistent local server joining the Pulse owner thread on drop.
#[derive(Debug)]
pub struct LocalServer {
media: crate::media_runtime::MediaRuntime,
active_media: Vec<media::Entry>,
listener: OwnedListener,
worker: PulseWorker,
mixer: LiveMixerState,
@ -208,6 +210,9 @@ impl LocalServer {
})?
.to_owned();
let mut server = Self {
media: crate::media_runtime::MediaRuntime::start()
.map_err(|e| LocalError::MidiRuntime(format!("MPRIS worker: {e}")))?,
active_media: profile.media().to_vec(),
listener: OwnedListener::bind(socket)?,
// One waiting native command keeps round-trip backpressure at the
// state-owner boundary, where unsent volume motion can coalesce.
@ -254,7 +259,37 @@ impl LocalServer {
}
pub fn tick(&mut self) -> Result<(), LocalError> {
self.mixer.set_media(self.media.snapshot());
let midi_tick = self.midi.tick();
for (entry, control) in &midi_tick.media_actions {
if let Err(error) = self.execute_media(entry, control) {
let profile = self
.configuration
.profile()
.map_err(|e| crate::live::LiveMixerError::Profile(e.to_string()))?;
self.publish_configuration(&profile, Some(error));
}
}
if let Some((learn, binding)) = midi_tick.learned_media {
let edit = crate::ipc::ConfigurationEdit::SetMediaBinding {
entry: learn.entry,
control: learn.control,
binding: Some(binding),
};
match self
.configuration
.apply(self.configuration.revision(), edit)
{
Ok(profile) => self.publish_configuration(&profile, None),
Err(error) => {
let profile = self
.configuration
.profile()
.map_err(|e| crate::live::LiveMixerError::Profile(e.to_string()))?;
self.publish_configuration(&profile, Some(error.to_string()));
}
}
}
self.flush_dispatch();
let mut worker_events = Vec::new();
match self.worker.receive_timeout(self.poll_interval) {
@ -331,6 +366,49 @@ impl LocalServer {
let request_id = request.request_id;
let result = (|| -> Result<_, crate::live::LiveMixerError> {
match request.command {
crate::ipc::RequestCommand::StartMediaLearn {
surface,
entry,
control,
} if request.version == PROTOCOL_VERSION => {
let profile = self
.configuration
.profile()
.map_err(|e| crate::live::LiveMixerError::Profile(e.to_string()))?;
if !profile.surfaces().iter().any(|s| s.id() == surface)
|| !profile
.media()
.iter()
.any(|e| e.id == entry && e.controls.iter().any(|c| c.id == control))
{
return Err(crate::live::LiveMixerError::Profile(
"unknown media entry, control or MIDI surface".into(),
));
}
self.midi
.start_media_learn(crate::midi_runtime::MediaLearn {
surface,
entry,
control,
});
self.publish_configuration(&profile, None);
self.mixer.request(ClientRequest {
version: request.version,
request_id,
command: crate::ipc::RequestCommand::Snapshot,
})
}
crate::ipc::RequestCommand::MediaAction { entry, control }
if request.version == PROTOCOL_VERSION =>
{
self.execute_media(&entry, &control)
.map_err(crate::live::LiveMixerError::Profile)?;
self.mixer.request(ClientRequest {
version: request.version,
request_id,
command: crate::ipc::RequestCommand::Snapshot,
})
}
crate::ipc::RequestCommand::EditConfiguration {
expected_revision,
edit,
@ -441,11 +519,15 @@ impl LocalServer {
let midi = crate::midi_runtime::MidiRuntime::new(&profile)
.map_err(crate::live::LiveMixerError::Profile)?;
let max_gain = Gain::new(profile.max_gain())?;
self.media
.fence()
.map_err(crate::live::LiveMixerError::Profile)?;
self.configuration
.save(current_revision)
.map_err(|error| crate::live::LiveMixerError::Profile(error.to_string()))?;
self.mixer.reconfigure(&profile, max_gain)?;
self.midi = midi;
self.active_media = profile.media().to_vec();
self.applied_configuration_revision = self.configuration.revision();
self.publish_configuration(&profile, None);
self.mixer.request(ClientRequest {
@ -457,6 +539,9 @@ impl LocalServer {
crate::ipc::RequestCommand::ResetConfiguration { expected_revision }
if request.version == PROTOCOL_VERSION =>
{
self.media
.fence()
.map_err(crate::live::LiveMixerError::Profile)?;
let profile = self
.configuration
.reset(expected_revision)
@ -466,6 +551,7 @@ impl LocalServer {
self.mixer
.reconfigure(&profile, Gain::new(profile.max_gain())?)?;
self.midi = midi;
self.active_media = profile.media().to_vec();
self.applied_configuration_revision = self.configuration.revision();
self.publish_configuration(&profile, None);
self.mixer.request(ClientRequest {
@ -558,6 +644,9 @@ impl LocalServer {
};
let midi = crate::midi_runtime::MidiRuntime::new(&profile)
.map_err(crate::live::LiveMixerError::Profile)?;
self.media
.fence()
.map_err(crate::live::LiveMixerError::Profile)?;
self.mixer
.reconfigure(&profile, Gain::new(profile.max_gain())?)?;
let restore_commands = self.mixer.activate_restore(
@ -566,6 +655,7 @@ impl LocalServer {
&& profile.new_stream() == fader_config::NewStreamPolicy::Restore,
)?;
self.midi = midi;
self.active_media = profile.media().to_vec();
self.configuration = ConfigurationEditor::new(document, path);
self.applied_configuration_revision = 0;
let persistence_error = (|| {
@ -625,6 +715,21 @@ impl LocalServer {
Ok(())
}
fn execute_media(&self, entry: &str, control: &str) -> Result<(), String> {
let entry = self
.active_media
.iter()
.find(|e| e.id == entry)
.ok_or("media entry is not active; save configuration first")?;
let control = entry
.controls
.iter()
.find(|c| c.id == control)
.ok_or("unknown active media control")?;
self.media
.command(entry.selector.clone(), control.action.clone())
}
fn publish_configuration(&mut self, profile: &fader_config::Profile, error: Option<String>) {
let mut configuration = configuration_snapshot(
profile,
@ -636,6 +741,7 @@ impl LocalServer {
configuration.available_profiles =
available_profile_ids(&self.profile_directory, profile.id().as_str());
configuration.error = error;
configuration.learning = self.midi.learning_label();
self.mixer.set_configuration(configuration);
}
@ -791,6 +897,107 @@ mod tests {
use fader_core::{AdapterEvent, ChannelGains, Mute, StreamHandle, StreamMetadata};
use tempfile::tempdir;
#[test]
fn media_draft_save_restart_unbind_and_delete_preserve_active_boundaries() {
let root = tempdir().unwrap();
let source = include_str!("../../examples/profiles/desktop.toml");
let path = root.path().join("desktop.toml");
fs::write(&path, source).unwrap();
let open = || {
LocalServer::pulse(
root.path().join("control.sock"),
Gain::UNITY,
ProfileDocument::parse(&fs::read_to_string(&path).unwrap()).unwrap(),
path.clone(),
root.path().join("config.toml"),
root.path().join("state.toml"),
)
.unwrap()
};
let mut server = open();
let entry = media::Entry {
id: "qbz".into(),
label: "QBZ".into(),
selector: media::PlayerSelector {
field: media::PlayerField::BusName,
pattern: "org.mpris.MediaPlayer2.com.blitzfc.qbz".into(),
regex: false,
},
feedback_enabled: false,
controls: vec![media::Control {
id: "play".into(),
action: media::Action::Play,
binding: Some(media::Binding {
surface: "desk-left".into(),
message: media::Message {
kind: media::MessageKind::Note,
channel: 1,
number: 40,
},
feedback: None,
}),
}],
};
let edit = |server: &mut LocalServer, edit| {
let response = direct_request(
server,
RequestCommand::EditConfiguration {
expected_revision: server.configuration.revision(),
edit,
},
);
assert!(
matches!(response.result, ResponseResult::Snapshot { .. }),
"{response:?}"
);
};
let save = |server: &mut LocalServer| {
let response = direct_request(
server,
RequestCommand::SaveConfiguration {
expected_revision: server.configuration.revision(),
},
);
assert!(
matches!(response.result, ResponseResult::Snapshot { .. }),
"{response:?}"
);
};
edit(
&mut server,
crate::ipc::ConfigurationEdit::SetMediaEntry {
entry: entry.clone(),
},
);
assert!(server.active_media.is_empty());
save(&mut server);
assert_eq!(server.active_media, vec![entry.clone()]);
drop(server);
let mut server = open();
assert_eq!(server.active_media, vec![entry]);
edit(
&mut server,
crate::ipc::ConfigurationEdit::SetMediaBinding {
entry: "qbz".into(),
control: "play".into(),
binding: None,
},
);
assert!(server.active_media[0].controls[0].binding.is_some());
save(&mut server);
drop(server);
let mut server = open();
assert!(server.active_media[0].controls[0].binding.is_none());
edit(
&mut server,
crate::ipc::ConfigurationEdit::RemoveMediaEntry { id: "qbz".into() },
);
assert_eq!(server.active_media.len(), 1);
save(&mut server);
drop(server);
assert!(open().active_media.is_empty());
}
#[test]
fn startup_audio_snapshot_is_applied_before_queued_midi_motion() {
let profile = fader_config::Profile::parse(include_str!(

View File

@ -0,0 +1,239 @@
//! Bounded MPRIS worker. Native connection ownership never leaves its thread.
use media::{Action, Player, PlayerSelector, Snapshot};
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
mpsc::{self, SyncSender},
},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
trait Adapter {
fn available(&self) -> bool {
false
}
fn discover(&mut self) -> Result<Vec<Player>, String>;
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String>;
}
fn execute_selected(
adapter: &mut impl Adapter,
selector: &PlayerSelector,
action: &Action,
) -> Result<Vec<Player>, String> {
action.validate().map_err(|e| e.to_string())?;
let players = adapter.discover()?;
let matcher = selector.compile().map_err(|e| e.to_string())?;
let player = matcher.resolve(&players).map_err(|e| e.to_string())?;
if !action.supported(player) {
return Err(media::MediaError::Unsupported.to_string());
}
adapter.execute(player, action)?;
adapter.discover()
}
struct Command {
generation: u64,
selector: PlayerSelector,
action: Action,
expires: Instant,
}
enum Work {
Action(Command),
Fence(SyncSender<()>),
}
#[derive(Debug)]
pub struct MediaRuntime {
sender: SyncSender<Work>,
generation: Arc<AtomicU64>,
snapshot: Arc<Mutex<Snapshot>>,
stop: Arc<AtomicBool>,
worker: Option<JoinHandle<()>>,
}
impl MediaRuntime {
pub fn start() -> std::io::Result<Self> {
let (sender, receiver) = mpsc::sync_channel::<Work>(32);
let generation = Arc::new(AtomicU64::new(0));
let current_generation = Arc::clone(&generation);
let snapshot = Arc::new(Mutex::new(Snapshot {
error: Some("MPRIS initializing".into()),
..Snapshot::default()
}));
let stop = Arc::new(AtomicBool::new(false));
let latest = Arc::clone(&snapshot);
let cancelled = Arc::clone(&stop);
let worker = thread::Builder::new().name("mpris".into()).spawn(move || {
#[cfg(feature = "mpris")]
let mut adapter = native::DbusAdapter::default();
#[cfg(not(feature = "mpris"))]
let mut adapter = Disabled;
let mut command_error = None;
while !cancelled.load(Ordering::Acquire) {
let command = receiver.recv_timeout(Duration::from_millis(250));
let is_command = command.is_ok();
if cancelled.load(Ordering::Acquire) {
break;
}
let result = match command {
Ok(Work::Fence(done)) => {
let _ = done.try_send(());
continue;
}
Ok(Work::Action(command))
if command.generation != current_generation.load(Ordering::Acquire) =>
{
continue;
}
Ok(Work::Action(command)) if Instant::now() <= command.expires => {
execute_selected(&mut adapter, &command.selector, &command.action)
}
Ok(_) => Err("media command expired; press again".into()),
Err(mpsc::RecvTimeoutError::Timeout) => adapter.discover(),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
};
if let Ok(mut state) = latest.lock() {
state.available |= adapter.available();
match result {
Ok(players) => {
if is_command {
command_error = None;
}
state.available = true;
state.players = players;
state.error = command_error.clone();
}
Err(error) => {
if is_command {
command_error = Some(error.clone());
}
// Do not retain stale observed states after any failed read/write.
state.players.clear();
state.error = Some(error);
}
}
}
}
})?;
Ok(Self {
sender,
generation,
snapshot,
stop,
worker: Some(worker),
})
}
pub fn snapshot(&self) -> Snapshot {
self.snapshot
.lock()
.map(|s| s.clone())
.unwrap_or_else(|_| Snapshot {
error: Some("MPRIS state unavailable".into()),
..Snapshot::default()
})
}
pub fn command(&self, selector: PlayerSelector, action: Action) -> Result<(), String> {
self.sender
.try_send(Work::Action(Command {
generation: self.generation.load(Ordering::Acquire),
selector,
action,
expires: Instant::now() + Duration::from_secs(2),
}))
.map_err(|e| format!("MPRIS queue unavailable: {e}"))
}
/// Invalidate queued work and drain the one in-flight call before changing
/// profiles. A failed barrier must abort activation rather than race a write.
pub fn fence(&self) -> Result<(), String> {
self.generation.fetch_add(1, Ordering::AcqRel);
let (done, wait) = mpsc::sync_channel(1);
self.sender
.try_send(Work::Fence(done))
.map_err(|e| e.to_string())?;
wait.recv_timeout(Duration::from_secs(10))
.map_err(|e| format!("MPRIS drain failed: {e}"))
}
}
impl Drop for MediaRuntime {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
#[cfg(not(feature = "mpris"))]
struct Disabled;
#[cfg(not(feature = "mpris"))]
impl Adapter for Disabled {
fn discover(&mut self) -> Result<Vec<Player>, String> {
Err("MPRIS support not compiled in".into())
}
fn execute(&mut self, _: &Player, _: &Action) -> Result<(), String> {
Err("MPRIS support not compiled in".into())
}
}
#[cfg(feature = "mpris")]
mod native;
#[cfg(test)]
mod tests {
use super::*;
struct Fake {
players: Vec<Player>,
calls: Vec<(String, Action)>,
fail: bool,
}
impl Adapter for Fake {
fn discover(&mut self) -> Result<Vec<Player>, String> {
Ok(self.players.clone())
}
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String> {
self.calls.push((player.owner.clone(), action.clone()));
if self.fail {
Err("timed out".into())
} else {
Ok(())
}
}
}
#[test]
fn targeted_commands_never_select_ambiguous_or_unsupported_players() {
let selector = PlayerSelector {
field: media::PlayerField::Identity,
pattern: "QBZ".into(),
regex: false,
};
let p = Player {
identity: Some("QBZ".into()),
owner: ":1.42".into(),
can_control: true,
can_play: true,
..Player::default()
};
let mut adapter = Fake {
players: vec![p.clone(), p.clone()],
calls: vec![],
fail: false,
};
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
assert!(adapter.calls.is_empty());
adapter.players.pop();
assert!(execute_selected(&mut adapter, &selector, &Action::Pause).is_err());
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
assert_eq!(adapter.calls[0].0, ":1.42");
adapter.fail = true;
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
assert_eq!(adapter.players[0].playback, None);
}
}

View File

@ -0,0 +1,601 @@
use super::*;
use dbus::{
Path,
arg::{PropMap, RefArg},
blocking::{Connection, stdintf::org_freedesktop_dbus::Properties},
};
use media::{Playback, Playlist, Repeat};
const PLAYER: &str = "org.mpris.MediaPlayer2.Player";
const ROOT: &str = "org.mpris.MediaPlayer2";
const PLAYLISTS: &str = "org.mpris.MediaPlayer2.Playlists";
const PATH: &str = "/org/mpris/MediaPlayer2";
const TIMEOUT: Duration = Duration::from_millis(200);
type WirePlaylist = (Path<'static>, String, String);
#[derive(Default)]
pub(super) struct DbusAdapter {
connection: Option<Connection>,
}
fn text(properties: &PropMap, key: &str) -> Option<String> {
properties
.get(key)?
.0
.as_str()
.map(|s| s.chars().filter(|c| !c.is_control()).take(1024).collect())
}
fn flag(properties: &PropMap, key: &str) -> Option<bool> {
properties.get(key)?.0.as_u64().map(|value| value != 0)
}
impl DbusAdapter {
fn connection(&mut self) -> Result<&Connection, String> {
if self.connection.is_none() {
self.connection = Some(Connection::new_session().map_err(|e| e.to_string())?);
}
self.connection
.as_ref()
.ok_or_else(|| "session bus unavailable".into())
}
fn read_player(
connection: &Connection,
bus_name: String,
owner: String,
) -> Result<Player, String> {
let proxy = connection.with_proxy(owner.clone(), PATH, TIMEOUT);
let root = proxy.get_all(ROOT).map_err(|e| e.to_string())?;
let props = proxy.get_all(PLAYER).map_err(|e| e.to_string())?;
let playback = match text(&props, "PlaybackStatus").as_deref() {
Some("Playing") => Some(Playback::Playing),
Some("Paused") => Some(Playback::Paused),
Some("Stopped") => Some(Playback::Stopped),
_ => None,
};
let repeat = match text(&props, "LoopStatus").as_deref() {
Some("None") => Some(Repeat::None),
Some("Track") => Some(Repeat::Track),
Some("Playlist") => Some(Repeat::Playlist),
_ => None,
};
let metadata: PropMap = proxy.get(PLAYER, "Metadata").unwrap_or_default();
let duration_ms = metadata
.get("mpris:length")
.and_then(|v| v.0.as_i64())
.and_then(|n| u64::try_from(n).ok())
.map(|n| n / 1000);
let position_ms = props
.get("Position")
.and_then(|v| v.0.as_i64())
.and_then(|n| u64::try_from(n).ok())
.map(|n| n / 1000);
let track_id = text(&metadata, "mpris:trackid")
.filter(|id| id != "/org/mpris/MediaPlayer2/TrackList/NoTrack");
let mut playlists = Vec::new();
let mut active_playlist = None;
if let Ok(playlist_props) = proxy.get_all(PLAYLISTS) {
let count = playlist_props
.get("PlaylistCount")
.and_then(|v| v.0.as_u64())
.unwrap_or(0)
.min(256) as u32;
let orderings: Vec<String> = proxy.get(PLAYLISTS, "Orderings").unwrap_or_default();
if let Some(order) = orderings.first() {
let result: Result<(Vec<WirePlaylist>,), _> = proxy.method_call(
PLAYLISTS,
"GetPlaylists",
(0u32, count, order.as_str(), false),
);
if let Ok((items,)) = result {
playlists = items
.into_iter()
.take(256)
.map(|(id, name, _)| Playlist {
id: id.to_string(),
name: name.chars().filter(|c| !c.is_control()).take(256).collect(),
})
.collect();
}
}
let active: Result<(bool, WirePlaylist), _> = proxy.get(PLAYLISTS, "ActivePlaylist");
if let Ok((true, (id, _, _))) = active {
active_playlist = Some(id.to_string());
}
}
Ok(Player {
bus_name,
owner,
identity: text(&root, "Identity"),
desktop_entry: text(&root, "DesktopEntry"),
playback,
can_control: flag(&props, "CanControl").unwrap_or(false),
can_play: flag(&props, "CanPlay").unwrap_or(false),
can_pause: flag(&props, "CanPause").unwrap_or(false),
can_next: flag(&props, "CanGoNext").unwrap_or(false),
can_previous: flag(&props, "CanGoPrevious").unwrap_or(false),
can_seek: flag(&props, "CanSeek").unwrap_or(false),
position_ms,
duration_ms,
track_id,
shuffle: flag(&props, "Shuffle"),
repeat,
playlists,
active_playlist,
error: None,
})
}
}
impl Adapter for DbusAdapter {
fn available(&self) -> bool {
self.connection.is_some()
}
fn discover(&mut self) -> Result<Vec<Player>, String> {
let connection = self.connection()?;
let bus = connection.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", TIMEOUT);
let names: Result<(Vec<String>,), _> =
bus.method_call("org.freedesktop.DBus", "ListNames", ());
let (names,) = match names {
Ok(names) => names,
Err(error) => {
self.connection = None;
return Err(error.to_string());
}
};
let names = names
.into_iter()
.filter(|name| name.starts_with("org.mpris.MediaPlayer2."))
.collect::<Vec<_>>();
if names.len() > 32 {
return Err("more than 32 MPRIS players; refusing incomplete discovery".into());
}
let started = Instant::now();
let mut players = Vec::new();
for name in names {
if started.elapsed() > Duration::from_secs(2) {
return Err("MPRIS discovery timed out".into());
}
let owner: Result<(String,), _> =
bus.method_call("org.freedesktop.DBus", "GetNameOwner", (name.as_str(),));
let Ok((owner,)) = owner else {
continue;
};
match Self::read_player(connection, name.clone(), owner.clone()) {
Ok(player) => players.push(player),
Err(error) => players.push(Player {
bus_name: name,
owner,
error: Some(error),
..Player::default()
}),
}
}
#[derive(serde::Serialize)]
struct DiscoverySize<'a> {
players: &'a [Player],
}
if toml::to_string(&DiscoverySize { players: &players })
.map_err(|e| e.to_string())?
.len()
> 256 * 1024
{
return Err("MPRIS discovery exceeds 256 KiB; refusing incomplete state".into());
}
Ok(players)
}
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String> {
let proxy = self
.connection()?
.with_proxy(player.owner.clone(), PATH, TIMEOUT);
let result: Result<(), dbus::Error> = match action {
Action::Play => proxy.method_call(PLAYER, "Play", ()),
Action::Pause => proxy.method_call(PLAYER, "Pause", ()),
Action::Stop => proxy.method_call(PLAYER, "Stop", ()),
Action::PlayPause => proxy.method_call(PLAYER, "PlayPause", ()),
Action::Next => proxy.method_call(PLAYER, "Next", ()),
Action::Previous => proxy.method_call(PLAYER, "Previous", ()),
Action::Seek { offset_ms } => {
proxy.method_call(PLAYER, "Seek", (offset_ms.saturating_mul(1000),))
}
Action::SetPosition { position_ms } => {
let track = player
.track_id
.as_deref()
.ok_or("track identity unavailable")?;
let path = Path::new(track).map_err(|e| e.to_string())?;
let position = i64::try_from(*position_ms)
.map_err(|e| e.to_string())?
.saturating_mul(1000);
proxy.method_call(PLAYER, "SetPosition", (path, position))
}
Action::Shuffle { enabled } => proxy.set(PLAYER, "Shuffle", *enabled),
Action::ShuffleToggle => proxy.set(
PLAYER,
"Shuffle",
!player.shuffle.ok_or("shuffle unavailable")?,
),
Action::Repeat { mode } => proxy.set(PLAYER, "LoopStatus", format!("{mode:?}")),
Action::RepeatCycle => {
let next = match player.repeat.ok_or("repeat unavailable")? {
Repeat::None => "Track",
Repeat::Track => "Playlist",
Repeat::Playlist => "None",
};
proxy.set(PLAYER, "LoopStatus", next)
}
Action::Playlist { id } => proxy.method_call(
PLAYLISTS,
"ActivatePlaylist",
(Path::new(id.clone()).map_err(|e| e.to_string())?,),
),
};
result.map_err(|e| e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use dbus::{
arg::Variant,
channel::{MatchingReceiver, Sender},
message::MatchRule,
};
#[derive(Default)]
struct ExtendedState {
shuffle: bool,
repeat: String,
position: i64,
active: bool,
deny_seek: bool,
silent: bool,
calls: Vec<String>,
}
struct Fixture {
state: Arc<Mutex<ExtendedState>>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl Fixture {
fn start() -> Self {
let state = Arc::new(Mutex::new(ExtendedState {
repeat: "None".into(),
..ExtendedState::default()
}));
let owned = state.clone();
let stop = Arc::new(AtomicBool::new(false));
let cancelled = stop.clone();
let (ready, wait) = mpsc::sync_channel(1);
let thread = thread::spawn(move || {
let connection = Connection::new_session().unwrap();
connection
.request_name(
"org.mpris.MediaPlayer2.extended_fixture",
false,
true,
false,
)
.unwrap();
connection.start_receive(
MatchRule::new_method_call(),
Box::new(move |message, connection| {
let mut state = owned.lock().unwrap();
if state.silent {
return true;
}
let member = message.member().unwrap().to_string();
let mut reply = message.method_return();
let playlist = || {
(
Path::new("/playlist/one").unwrap(),
"Favorites".to_owned(),
String::new(),
)
};
match member.as_str() {
"GetAll" => {
let interface: String = message.read1().unwrap();
let mut props = PropMap::new();
if interface == ROOT {
props.insert(
"Identity".into(),
Variant(Box::new("Extended fixture".to_owned())),
);
props.insert(
"DesktopEntry".into(),
Variant(Box::new("extended_fixture".to_owned())),
);
} else if interface == PLAYER {
props.insert(
"PlaybackStatus".into(),
Variant(Box::new("Paused".to_owned())),
);
props
.insert("Shuffle".into(), Variant(Box::new(state.shuffle)));
props.insert(
"LoopStatus".into(),
Variant(Box::new(state.repeat.clone())),
);
props.insert(
"Position".into(),
Variant(Box::new(state.position)),
);
for key in [
"CanControl",
"CanPlay",
"CanPause",
"CanGoNext",
"CanGoPrevious",
] {
props.insert(key.into(), Variant(Box::new(true)));
}
props.insert(
"CanSeek".into(),
Variant(Box::new(!state.deny_seek)),
);
} else if interface == PLAYLISTS {
props.insert("PlaylistCount".into(), Variant(Box::new(1u32)));
}
reply = reply.append1(props);
}
"Get" => {
let (_, property): (String, String) = message.read2().unwrap();
reply = match property.as_str() {
"Metadata" => {
let mut metadata = PropMap::new();
metadata.insert(
"mpris:trackid".into(),
Variant(Box::new(Path::new("/track/one").unwrap())),
);
metadata.insert(
"mpris:length".into(),
Variant(Box::new(300_000_000i64)),
);
reply.append1(Variant(metadata))
}
"Orderings" => {
reply.append1(Variant(vec!["Alphabetical".to_owned()]))
}
"ActivePlaylist" => {
reply.append1(Variant((state.active, playlist())))
}
_ => panic!("unexpected property {property}"),
};
}
"GetPlaylists" => {
let (start, count, order, reverse): (u32, u32, String, bool) =
message.read4().unwrap();
assert_eq!(
(start, count, order.as_str(), reverse),
(0, 1, "Alphabetical", false)
);
reply = reply.append1(vec![playlist()]);
}
"Set" => {
let (_, property): (String, String) = message.read2().unwrap();
if property == "Shuffle" {
let (_, _, value): (String, String, Variant<bool>) =
message.read3().unwrap();
state.shuffle = value.0;
} else {
let (_, _, value): (String, String, Variant<String>) =
message.read3().unwrap();
state.repeat = value.0;
}
state.calls.push(property);
}
"Seek" => {
let offset: i64 = message.read1().unwrap();
state.position += offset;
state.calls.push(member);
}
"SetPosition" => {
let (track, position): (Path<'static>, i64) =
message.read2().unwrap();
assert_eq!(track.to_string(), "/track/one");
state.position = position;
state.calls.push(member);
}
"ActivatePlaylist" => {
let id: Path<'static> = message.read1().unwrap();
assert_eq!(id.to_string(), "/playlist/one");
state.active = true;
state.calls.push(member);
}
_ => state.calls.push(member),
}
connection.send(reply).unwrap();
true
}),
);
ready.send(()).unwrap();
while !cancelled.load(Ordering::Acquire) {
connection.process(Duration::from_millis(10)).unwrap();
}
});
wait.recv_timeout(Duration::from_secs(2)).unwrap();
Self {
state,
stop,
thread: Some(thread),
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
if let Some(thread) = self.thread.take() {
thread.join().unwrap();
}
}
}
#[test]
#[ignore = "run inside dbus-run-session; fake player only"]
fn private_bus_extended_controls_capabilities_timeouts_and_owner_changes() {
let fixture = Fixture::start();
let mut adapter = DbusAdapter::default();
let selector = PlayerSelector {
field: media::PlayerField::BusName,
pattern: "org.mpris.MediaPlayer2.extended_fixture".into(),
regex: false,
};
let matcher = selector.compile().unwrap();
let initial = adapter.discover().unwrap();
let player = matcher.resolve(&initial).unwrap().clone();
assert_eq!(player.duration_ms, Some(300_000));
assert_eq!(player.playlists[0].name, "Favorites");
for action in [
Action::Seek { offset_ms: 5000 },
Action::Seek { offset_ms: -2000 },
Action::SetPosition { position_ms: 12000 },
Action::ShuffleToggle,
Action::RepeatCycle,
Action::Playlist {
id: "/playlist/one".into(),
},
Action::Next,
Action::Previous,
] {
execute_selected(&mut adapter, &selector, &action).unwrap();
}
let observed = adapter.discover().unwrap();
let observed = matcher.resolve(&observed).unwrap();
assert_eq!(observed.position_ms, Some(12000));
assert_eq!(observed.shuffle, Some(true));
assert_eq!(observed.repeat, Some(Repeat::Track));
assert_eq!(observed.active_playlist.as_deref(), Some("/playlist/one"));
assert!(Action::ShuffleToggle.feedback(Some(observed)));
fixture.state.lock().unwrap().deny_seek = true;
let count = fixture.state.lock().unwrap().calls.len();
assert!(
execute_selected(&mut adapter, &selector, &Action::Seek { offset_ms: 10 }).is_err()
);
assert_eq!(fixture.state.lock().unwrap().calls.len(), count);
fixture.state.lock().unwrap().silent = true;
let started = Instant::now();
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
assert!(adapter.available()); // A broken player does not mean D-Bus support is absent.
assert!(started.elapsed() < Duration::from_secs(3));
fixture.state.lock().unwrap().silent = false;
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
drop(fixture);
assert!(matcher.resolve(&adapter.discover().unwrap()).is_err());
let replacement = Fixture::start();
let current = adapter.discover().unwrap();
assert_ne!(matcher.resolve(&current).unwrap().owner, player.owner);
assert!(adapter.execute(&player, &Action::Play).is_err()); // Never retarget an old owner.
assert!(replacement.state.lock().unwrap().calls.is_empty());
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
}
#[test]
#[ignore = "run inside dbus-run-session; uses only a fake player"]
fn private_bus_discovers_paused_player_and_confirms_play() {
let stop = Arc::new(AtomicBool::new(false));
let worker_stop = Arc::clone(&stop);
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
let worker = thread::spawn(move || {
let connection = Connection::new_session().unwrap();
connection
.request_name("org.mpris.MediaPlayer2.fader_fixture", false, true, false)
.unwrap();
let playing = Arc::new(AtomicBool::new(false));
connection.start_receive(
MatchRule::new_method_call(),
Box::new(move |message, connection| {
let reply = message.method_return();
let member = message.member().map(|m| m.to_string()).unwrap_or_default();
let interface = message
.interface()
.map(|m| m.to_string())
.unwrap_or_default();
let reply = if member == "GetAll" {
let requested: String = message.read1().unwrap();
let mut props: PropMap = PropMap::new();
if requested == ROOT {
props
.insert("Identity".into(), Variant(Box::new("Fixture".to_owned())));
}
if requested == PLAYER {
props.insert(
"PlaybackStatus".into(),
Variant(Box::new(
if playing.load(Ordering::Relaxed) {
"Playing"
} else {
"Paused"
}
.to_owned(),
)),
);
for name in ["CanControl", "CanPlay", "CanPause"] {
props.insert(name.into(), Variant(Box::new(true)));
}
}
reply.append1(props)
} else if member == "Get" {
let (_, name): (String, String) = message.read2().unwrap();
if name == "Metadata" {
reply.append1(Variant(PropMap::new()))
} else if name == "Orderings" {
reply.append1(Variant(Vec::<String>::new()))
} else {
reply.append1(Variant((
false,
(Path::new("/").unwrap(), String::new(), String::new()),
)))
}
} else {
if interface == PLAYER && member == "Play" {
playing.store(true, Ordering::Relaxed);
}
reply
};
connection.send(reply).unwrap();
true
}),
);
ready_tx.send(()).unwrap();
while !worker_stop.load(Ordering::Acquire) {
connection.process(Duration::from_millis(10)).unwrap();
}
});
ready_rx.recv_timeout(Duration::from_secs(2)).unwrap();
let mut adapter = DbusAdapter::default();
let selector = PlayerSelector {
field: media::PlayerField::BusName,
pattern: "org.mpris.MediaPlayer2.fader_fixture".into(),
regex: false,
};
let before = adapter.discover();
let after = execute_selected(&mut adapter, &selector, &Action::Play);
stop.store(true, Ordering::Release);
worker.join().unwrap();
assert_eq!(
selector
.compile()
.unwrap()
.resolve(&before.unwrap())
.unwrap()
.playback,
Some(Playback::Paused)
);
assert_eq!(
selector
.compile()
.unwrap()
.resolve(&after.unwrap())
.unwrap()
.playback,
Some(Playback::Playing)
);
}
}

View File

@ -22,6 +22,11 @@ const EVENT_CAPACITY: usize = 256;
/// Owns native MIDI input connections and periodically reconciles hotplug state.
pub struct MidiRuntime {
media_entries: Vec<(media::Entry, media::PlayerMatcher)>,
media_feedback_enabled: bool,
media_sent: BTreeMap<(String, String, String), [u8; 3]>,
media_down: BTreeSet<(String, bool, u16, u16)>,
media_learn: Option<MediaLearn>,
lifecycle: SurfaceLifecycle,
labels: BTreeMap<SurfaceId, String>,
connections: BTreeMap<SurfaceId, MidiInputConnection>,
@ -177,10 +182,25 @@ pub struct LearnedBinding {
#[derive(Debug, Default)]
pub struct MidiTick {
pub media_actions: Vec<(String, String)>,
pub learned_media: Option<(MediaLearn, media::Binding)>,
pub intents: Vec<MidiIntent>,
pub learned: Option<LearnedBinding>,
}
#[derive(Clone, Debug)]
pub struct MediaLearn {
pub surface: String,
pub entry: String,
pub control: String,
}
struct MediaFeedback {
key: (String, String, String),
bytes: [u8; 3],
on: bool,
}
impl std::fmt::Debug for MidiRuntime {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
@ -251,6 +271,21 @@ impl MidiRuntime {
let feedback = FeedbackEngine::new(profile)?;
let (sender, receiver) = sync_channel(EVENT_CAPACITY);
Ok(Self {
media_entries: profile
.media()
.iter()
.map(|entry| {
entry
.selector
.compile()
.map(|matcher| (entry.clone(), matcher))
.map_err(|e| e.to_string())
})
.collect::<Result<_, _>>()?,
media_feedback_enabled: profile.feedback_enabled(),
media_sent: BTreeMap::new(),
media_down: BTreeSet::new(),
media_learn: None,
lifecycle,
labels,
connections: BTreeMap::new(),
@ -302,19 +337,55 @@ impl MidiRuntime {
}
pub fn start_learn(&mut self, learn: MidiLearn) {
self.media_learn = None;
self.learn = Some(learn);
}
pub fn cancel_learn(&mut self) {
self.media_learn = None;
self.learn = None;
}
pub fn start_media_learn(&mut self, learn: MediaLearn) {
self.learn = None;
self.media_learn = Some(learn);
}
#[must_use]
pub fn learning(&self) -> Option<&MidiLearn> {
self.learn.as_ref()
}
pub fn learning_label(&self) -> Option<String> {
self.media_learn
.as_ref()
.map(|l| format!("{} -> {} / {}", l.surface, l.entry, l.control))
.or_else(|| {
self.learn
.as_ref()
.map(|l| format!("{} -> {} ({:?})", l.surface, l.fader, l.action))
})
}
fn handle_message(&mut self, surface: SurfaceId, message: MidiMessage, result: &mut MidiTick) {
let (input, pressed) = media_input(message);
if self
.media_learn
.as_ref()
.is_some_and(|learn| learn.surface == surface.as_str())
{
if pressed && let Some(learn) = self.media_learn.take() {
result.learned_media = Some((
learn,
media::Binding {
surface: surface.to_string(),
message: input,
feedback: None,
},
));
}
return;
}
if self
.learn
.as_ref()
@ -362,6 +433,32 @@ impl MidiRuntime {
}
return;
}
for (entry, _) in &self.media_entries {
for control in &entry.controls {
if control
.binding
.as_ref()
.is_some_and(|b| b.surface == surface.as_str() && b.message == input)
{
let key = (
surface.to_string(),
input.kind == media::MessageKind::Note,
input.channel,
input.number,
);
if pressed {
if self.media_down.insert(key) {
result
.media_actions
.push((entry.id.clone(), control.id.clone()));
}
} else {
self.media_down.remove(&key);
}
return;
}
}
}
if let Some(intent) = self.router.route(&surface, message) {
result.intents.push(intent);
}
@ -441,6 +538,7 @@ impl MidiRuntime {
match action {
SurfaceAction::Disconnect { surface, .. } => {
self.connections.remove(&surface);
self.media_down.retain(|(id, ..)| id != surface.as_str());
}
SurfaceAction::Connect {
surface,
@ -552,6 +650,7 @@ impl MidiRuntime {
}
fn disconnect_output(&mut self, surface: &SurfaceId) {
self.media_sent.retain(|(id, ..), _| id != surface.as_str());
if self.output_connections.remove(surface).is_some() {
self.feedback.invalidate_surface(surface);
}
@ -559,6 +658,7 @@ impl MidiRuntime {
}
pub fn sync_feedback(&mut self, snapshot: &MixerSnapshot) {
self.sync_media_feedback(&snapshot.configuration.media_state);
let confirmed = self
.feedback
.bindings
@ -590,6 +690,89 @@ impl MidiRuntime {
}
}
}
fn plan_media_feedback(&self, snapshot: &media::Snapshot) -> Vec<MediaFeedback> {
if !self.media_feedback_enabled {
return Vec::new();
}
let mut writes = Vec::new();
for (entry, matcher) in &self.media_entries {
if !entry.feedback_enabled {
continue;
}
let player = matcher.resolve(&snapshot.players).ok();
for control in &entry.controls {
let Some(binding) = &control.binding else {
continue;
};
let on = control.action.feedback(player);
let Some(bytes) = binding.feedback_bytes(on) else {
continue;
};
let key = (
binding.surface.clone(),
entry.id.clone(),
control.id.clone(),
);
if self.media_sent.get(&key) != Some(&bytes) {
writes.push(MediaFeedback { key, bytes, on });
}
}
}
// Turn old state lights off before turning a new state light on.
writes.sort_by_key(|write| write.on);
writes
}
fn sync_media_feedback(&mut self, snapshot: &media::Snapshot) {
for MediaFeedback { key, bytes, .. } in self.plan_media_feedback(snapshot) {
let Ok(surface) = SurfaceId::new(&key.0) else {
continue;
};
let Some(connection) = self.output_connections.get_mut(&surface) else {
continue;
};
match connection.send(&bytes) {
Ok(()) => {
self.media_sent.insert(key, bytes);
}
Err(error) => {
self.output_errors
.insert(surface.clone(), error.to_string());
self.disconnect_output(&surface);
}
}
}
}
}
fn media_input(message: MidiMessage) -> (media::Message, bool) {
let (kind, channel, number, pressed) = match message {
MidiMessage::Note {
channel,
number,
edge,
..
} => (
media::MessageKind::Note,
channel,
number,
edge == ButtonEdge::Press,
),
MidiMessage::ControlChange {
channel,
number,
value,
} => (media::MessageKind::Cc, channel, number, value.get() > 0),
};
(
media::Message {
kind,
channel: u16::from(channel.get()),
number: u16::from(number.get()),
},
pressed,
)
}
fn unclaimed_ports(visible: Vec<PortIdentity>, lifecycle: &SurfaceLifecycle) -> Vec<PortIdentity> {
@ -634,6 +817,161 @@ mod tests {
use fader_core::{MidiChannel, MidiData};
use midi::{ButtonEdge, MidiMessage};
#[test]
fn media_feedback_is_confirmed_deduplicated_gated_and_resynchronized() {
let profile =
Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap();
let mut runtime = MidiRuntime::new(&profile).unwrap();
let selector = media::PlayerSelector {
field: media::PlayerField::BusName,
pattern: "org.mpris.MediaPlayer2.fixture".into(),
regex: false,
};
let controls = [
media::Action::Play,
media::Action::Pause,
media::Action::Stop,
]
.into_iter()
.enumerate()
.map(|(i, action)| media::Control {
id: format!("button-{i}"),
action,
binding: Some(media::Binding {
surface: "buttons".into(),
message: media::Message {
kind: media::MessageKind::Note,
channel: 1,
number: i as u16,
},
feedback: None,
}),
})
.collect();
runtime.media_entries.push((
media::Entry {
id: "player".into(),
label: "Player".into(),
selector: selector.clone(),
feedback_enabled: true,
controls,
},
selector.compile().unwrap(),
));
let mut snapshot = media::Snapshot {
available: true,
error: None,
players: vec![media::Player {
bus_name: selector.pattern,
playback: Some(media::Playback::Playing),
..media::Player::default()
}],
};
let plan = runtime.plan_media_feedback(&snapshot);
assert_eq!(plan.iter().filter(|w| w.on).count(), 1);
assert_eq!(plan.last().unwrap().bytes, [0x90, 0, 127]);
for w in plan {
runtime.media_sent.insert(w.key, w.bytes);
}
assert!(runtime.plan_media_feedback(&snapshot).is_empty());
snapshot.players[0].playback = Some(media::Playback::Paused);
let plan = runtime.plan_media_feedback(&snapshot);
assert_eq!(
plan.iter().map(|w| w.bytes).collect::<Vec<_>>(),
[[0x90, 0, 0], [0x90, 1, 127]]
);
runtime.media_feedback_enabled = false;
snapshot.players.clear();
assert!(runtime.plan_media_feedback(&snapshot).is_empty()); // No clearing while disabled.
runtime.media_feedback_enabled = true;
assert_eq!(runtime.plan_media_feedback(&snapshot).len(), 1); // Clear confirmed old Playing.
runtime.media_entries[0].0.feedback_enabled = false;
assert!(runtime.plan_media_feedback(&snapshot).is_empty());
runtime.media_entries[0].0.feedback_enabled = true;
runtime.disconnect_output(&SurfaceId::new("buttons").unwrap());
assert_eq!(runtime.plan_media_feedback(&snapshot).len(), 3); // Full resync after reconnect.
let binding = runtime.media_entries[0].0.controls[0]
.binding
.as_mut()
.unwrap();
binding.feedback = Some(media::Feedback {
message: binding.message.clone(),
on: 1,
off: 7,
});
snapshot.players.push(media::Player {
bus_name: "org.mpris.MediaPlayer2.fixture".into(),
playback: Some(media::Playback::Paused),
..media::Player::default()
});
let plan = runtime.plan_media_feedback(&snapshot);
assert_eq!(plan.last().unwrap().bytes, [0x90, 1, 127]); // Logical off before on even if off is a color.
assert!(plan.iter().any(|w| !w.on && w.bytes == [0x90, 0, 7]));
}
#[test]
fn media_triggers_are_press_edges_and_learn_is_scoped() {
let profile =
Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap();
let mut runtime = MidiRuntime::new(&profile).unwrap();
let surface = SurfaceId::new("buttons").unwrap();
let selector = media::PlayerSelector {
field: media::PlayerField::BusName,
pattern: "org.mpris.MediaPlayer2.test".into(),
regex: false,
};
let binding = media::Binding {
surface: surface.to_string(),
message: media::Message {
kind: media::MessageKind::Cc,
channel: 1,
number: 12,
},
feedback: None,
};
runtime.media_entries.push((
media::Entry {
id: "player".into(),
label: "Player".into(),
selector: selector.clone(),
feedback_enabled: true,
controls: vec![media::Control {
id: "play".into(),
action: media::Action::Play,
binding: Some(binding.clone()),
}],
},
selector.compile().unwrap(),
));
let message = |value| MidiMessage::ControlChange {
channel: MidiChannel::new(1).unwrap(),
number: MidiData::new(12).unwrap(),
value: MidiData::new(value).unwrap(),
};
let mut result = MidiTick::default();
for value in [127, 127, 50, 0, 127] {
runtime.handle_message(surface.clone(), message(value), &mut result);
}
assert_eq!(
result.media_actions,
vec![("player".into(), "play".into()); 2]
);
assert!(result.intents.is_empty());
runtime.start_media_learn(MediaLearn {
surface: surface.to_string(),
entry: "player".into(),
control: "play".into(),
});
let mut learned = MidiTick::default();
runtime.handle_message(SurfaceId::new("other").unwrap(), message(127), &mut learned);
runtime.handle_message(surface.clone(), message(0), &mut learned);
assert!(learned.learned_media.is_none());
runtime.handle_message(surface, message(127), &mut learned);
assert_eq!(learned.learned_media.unwrap().1, binding);
assert!(learned.media_actions.is_empty());
assert!(runtime.learning_label().is_none());
}
#[test]
fn discovery_exposes_only_ports_not_claimed_by_configured_surfaces() {
let surface = SurfaceId::new("configured").unwrap();
@ -847,6 +1185,28 @@ mod tests {
}
}
#[test]
fn disabled_feedback_sends_nothing_and_reenable_resynchronizes() {
let source = include_str!("../../examples/profiles/desktop.toml");
let mut doc = fader_config::ProfileDocument::parse(source).unwrap();
for fader in [None, Some("media-fader")] {
doc.set_feedback_enabled(fader, false).unwrap();
assert!(
FeedbackEngine::new(&doc.preview().unwrap())
.unwrap()
.bindings
.is_empty()
);
doc.set_feedback_enabled(fader, true).unwrap();
let engine = FeedbackEngine::new(&doc.preview().unwrap()).unwrap();
assert_eq!(engine.bindings.len(), 1);
assert!(engine.sent.is_empty());
}
let reloaded = Profile::parse(&doc.source()).unwrap();
assert!(reloaded.feedback_enabled());
assert!(reloaded.faders()[0].feedback_enabled());
}
#[test]
fn confirmed_mute_feedback_is_surface_scoped_deduplicated_and_resynced() {
let profile = Profile::parse(include_str!("../../examples/profiles/desktop.toml")).unwrap();

View File

@ -102,6 +102,8 @@ impl IpcMixerClient {
})
.collect(),
configuration: tui::ConfigurationSnapshot {
feedback_disabled: snapshot.configuration.feedback_disabled,
disabled_feedback_faders: snapshot.configuration.disabled_feedback_faders,
revision: snapshot.configuration.revision,
dirty: snapshot.configuration.dirty,
applied_revision: snapshot.configuration.applied_revision,
@ -110,6 +112,9 @@ impl IpcMixerClient {
error: snapshot.configuration.error,
profile_id: snapshot.configuration.profile_id,
profile_path: snapshot.configuration.profile_path,
stream_metadata: snapshot.configuration.stream_metadata,
media_entries: snapshot.configuration.media_entries,
media_state: snapshot.configuration.media_state,
available_profiles: snapshot.configuration.available_profiles,
mixer_orientation: match snapshot.configuration.mixer_orientation {
crate::ipc::MixerOrientation::Vertical => tui::MixerOrientation::Vertical,
@ -151,6 +156,7 @@ impl IpcMixerClient {
.map(|application| tui::ConfiguredApplication {
id: application.id,
label: application.label,
match_all: application.match_all,
selectors: application
.selectors
.into_iter()
@ -324,6 +330,23 @@ impl MixerClient for IpcMixerClient {
})
}
fn media_action(&mut self, entry: String, control: String) -> io::Result<tui::MixerSnapshot> {
self.send(RequestCommand::MediaAction { entry, control })
}
fn start_media_learn(
&mut self,
surface: String,
entry: String,
control: String,
) -> io::Result<tui::MixerSnapshot> {
self.send(RequestCommand::StartMediaLearn {
surface,
entry,
control,
})
}
fn start_midi_learn(
&mut self,
surface: String,
@ -548,6 +571,23 @@ fn configuration_edit(edit: TuiConfigurationEdit) -> crate::ipc::ConfigurationEd
tui::SeparatorDecoration::Box => crate::ipc::SeparatorDecoration::Box,
},
},
TuiConfigurationEdit::SetFeedbackEnabled { fader, enabled } => {
IpcEdit::SetFeedbackEnabled { fader, enabled }
}
TuiConfigurationEdit::SetMediaEntry { entry } => IpcEdit::SetMediaEntry { entry },
TuiConfigurationEdit::RemoveMediaEntry { id } => IpcEdit::RemoveMediaEntry { id },
TuiConfigurationEdit::SetMediaBinding {
entry,
control,
binding,
} => IpcEdit::SetMediaBinding {
entry,
control,
binding,
},
TuiConfigurationEdit::SetApplicationSelectorMode { id, match_all } => {
IpcEdit::SetApplicationSelectorMode { id, match_all }
}
TuiConfigurationEdit::SetApplicationSelector {
id,
index,

View File

@ -32,6 +32,30 @@ fn bounded_toml_frame_round_trips_request_identity_and_revision() {
);
}
#[test]
fn bounded_media_playlist_snapshot_round_trips_over_ipc() {
let snapshot = media::Snapshot {
available: true,
error: None,
players: vec![media::Player {
bus_name: "org.mpris.MediaPlayer2.fixture".into(),
playlists: (0..256)
.map(|n| media::Playlist {
id: format!("/playlist/{n}"),
name: "X".repeat(256),
})
.collect(),
..media::Player::default()
}],
};
let mut bytes = Vec::new();
write_frame(&mut bytes, &snapshot).unwrap();
assert_eq!(
read_frame::<media::Snapshot>(&mut Cursor::new(bytes)).unwrap(),
snapshot
);
}
#[test]
fn oversized_length_is_rejected_before_payload_allocation_or_read() {
let length = u32::try_from(MAX_FRAME_BYTES + 1).unwrap().to_be_bytes();

14
media/Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "media"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license-file.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
fader-core.workspace = true
serde.workspace = true
regex.workspace = true
thiserror.workspace = true

446
media/src/lib.rs Normal file
View File

@ -0,0 +1,446 @@
//! Hardware-free MPRIS matching, action and feedback contracts.
#![forbid(unsafe_code)]
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum MediaError {
#[error("player offline")]
Offline,
#[error("selector matches multiple players; narrow the selector")]
Ambiguous,
#[error("unsupported player action")]
Unsupported,
#[error("player discovery incomplete: {0}")]
Unavailable(String),
#[error("invalid media configuration: {0}")]
Invalid(String),
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlayerField {
#[default]
BusName,
DesktopEntry,
Identity,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlayerSelector {
pub field: PlayerField,
pub pattern: String,
#[serde(default)]
pub regex: bool,
}
#[derive(Clone, Debug)]
pub struct PlayerMatcher {
selector: PlayerSelector,
regex: Option<regex::Regex>,
}
impl PlayerSelector {
pub fn compile(&self) -> Result<PlayerMatcher, MediaError> {
if self.pattern.is_empty() || self.pattern.len() > 256 {
return Err(MediaError::Invalid(
"selector must contain 1–256 bytes".into(),
));
}
let regex = if self.regex {
Some(
regex::RegexBuilder::new(&self.pattern)
.size_limit(1 << 20)
.build()
.map_err(|e| MediaError::Invalid(e.to_string()))?,
)
} else {
None
};
Ok(PlayerMatcher {
selector: self.clone(),
regex,
})
}
}
impl PlayerMatcher {
pub fn matches(&self, player: &Player) -> bool {
let value = match self.selector.field {
PlayerField::BusName => Some(player.bus_name.as_str()),
PlayerField::DesktopEntry => player.desktop_entry.as_deref(),
PlayerField::Identity => player.identity.as_deref(),
};
value.is_some_and(|value| {
self.regex
.as_ref()
.map_or_else(|| value == self.selector.pattern, |re| re.is_match(value))
})
}
pub fn resolve<'a>(&self, players: &'a [Player]) -> Result<&'a Player, MediaError> {
if self.selector.field != PlayerField::BusName
&& let Some(error) = players.iter().find_map(|p| p.error.as_ref())
{
return Err(MediaError::Unavailable(error.clone()));
}
let mut matches = players.iter().filter(|p| self.matches(p));
let first = matches.next().ok_or(MediaError::Offline)?;
if matches.next().is_some() {
return Err(MediaError::Ambiguous);
}
if let Some(error) = &first.error {
return Err(MediaError::Unavailable(error.clone()));
}
Ok(first)
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum Playback {
Playing,
Paused,
Stopped,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub enum Repeat {
#[default]
None,
Track,
Playlist,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Action {
Play,
Pause,
Stop,
PlayPause,
Next,
Previous,
Seek { offset_ms: i64 },
SetPosition { position_ms: u64 },
ShuffleToggle,
Shuffle { enabled: bool },
RepeatCycle,
Repeat { mode: Repeat },
Playlist { id: String },
}
impl Action {
pub fn validate(&self) -> Result<(), MediaError> {
match self {
Self::Seek { offset_ms } if offset_ms.unsigned_abs() > 86_400_000 => {
Err(MediaError::Invalid("seek offset exceeds one day".into()))
}
Self::SetPosition { position_ms } if *position_ms > 86_400_000 => {
Err(MediaError::Invalid("position exceeds one day".into()))
}
Self::Playlist { id } if !valid_object_path(id) => {
Err(MediaError::Invalid("invalid playlist object path".into()))
}
_ => Ok(()),
}
}
pub fn supported(&self, p: &Player) -> bool {
if !p.can_control {
return false;
}
match self {
Self::Play => p.can_play,
Self::Pause => p.can_pause,
Self::PlayPause => {
p.can_pause
&& match p.playback {
Some(Playback::Playing) => p.can_pause,
Some(_) => p.can_play,
None => false,
}
}
Self::Stop => true,
Self::Next => p.can_next,
Self::Previous => p.can_previous,
Self::Seek { .. } => p.can_seek,
Self::SetPosition { position_ms } => {
p.can_seek
&& p.track_id.is_some()
&& p.duration_ms.is_some_and(|length| *position_ms <= length)
}
Self::ShuffleToggle | Self::Shuffle { .. } => p.shuffle.is_some(),
Self::RepeatCycle | Self::Repeat { .. } => p.repeat.is_some(),
Self::Playlist { id } => p.playlists.iter().any(|playlist| &playlist.id == id),
}
}
/// State indicators are observations, never acknowledgements of a command.
pub fn feedback(&self, player: Option<&Player>) -> bool {
let Some(p) = player else {
return false;
};
match self {
Self::Play | Self::PlayPause => p.playback == Some(Playback::Playing),
Self::Pause => p.playback == Some(Playback::Paused),
Self::Stop => p.playback == Some(Playback::Stopped),
Self::ShuffleToggle => p.shuffle == Some(true),
Self::Shuffle { enabled } => p.shuffle == Some(*enabled),
Self::RepeatCycle => matches!(p.repeat, Some(Repeat::Track | Repeat::Playlist)),
Self::Repeat { mode } => p.repeat == Some(*mode),
Self::Playlist { id } => p.active_playlist.as_ref() == Some(id),
_ => false,
}
}
}
fn valid_object_path(value: &str) -> bool {
value == "/"
|| (value.len() <= 1024
&& value.starts_with('/')
&& value.split('/').skip(1).all(|part| {
!part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}))
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Player {
pub bus_name: String,
/// Unique D-Bus owner; commands must never jump to a replacement instance.
pub owner: String,
pub identity: Option<String>,
pub desktop_entry: Option<String>,
pub playback: Option<Playback>,
pub can_control: bool,
pub can_play: bool,
pub can_pause: bool,
pub can_next: bool,
pub can_previous: bool,
pub can_seek: bool,
pub position_ms: Option<u64>,
pub duration_ms: Option<u64>,
pub track_id: Option<String>,
pub shuffle: Option<bool>,
pub repeat: Option<Repeat>,
pub playlists: Vec<Playlist>,
pub active_playlist: Option<String>,
pub error: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Playlist {
pub id: String,
pub name: String,
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Snapshot {
pub available: bool,
pub error: Option<String>,
pub players: Vec<Player>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageKind {
Note,
Cc,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Message {
pub kind: MessageKind,
pub channel: u16,
pub number: u16,
}
impl Message {
pub fn validate(&self) -> Result<(), MediaError> {
fader_core::MidiChannel::new(self.channel)
.map_err(|e| MediaError::Invalid(e.to_string()))?;
fader_core::MidiData::new(self.number).map_err(|e| MediaError::Invalid(e.to_string()))?;
Ok(())
}
pub fn bytes(&self, value: u8) -> Option<[u8; 3]> {
self.validate().ok()?;
let status = match self.kind {
MessageKind::Note => 0x90,
MessageKind::Cc => 0xb0,
};
Some([
status | u8::try_from(self.channel - 1).ok()?,
u8::try_from(self.number).ok()?,
value,
])
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Feedback {
pub message: Message,
pub on: u8,
pub off: u8,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub surface: String,
pub message: Message,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub feedback: Option<Feedback>,
}
impl Binding {
pub fn feedback_bytes(&self, on: bool) -> Option<[u8; 3]> {
if let Some(feedback) = &self.feedback {
feedback
.message
.bytes(if on { feedback.on } else { feedback.off })
} else if self.message.kind == MessageKind::Note {
self.message.bytes(if on { 127 } else { 0 })
} else {
None
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Control {
pub id: String,
pub action: Action,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub binding: Option<Binding>,
}
const fn enabled() -> bool {
true
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Entry {
pub id: String,
pub label: String,
pub selector: PlayerSelector,
#[serde(default = "enabled")]
pub feedback_enabled: bool,
#[serde(default)]
pub controls: Vec<Control>,
}
impl Entry {
pub fn validate(&self) -> Result<(), MediaError> {
fader_core::ApplicationId::new(&self.id).map_err(|e| MediaError::Invalid(e.to_string()))?;
if self.label.trim().is_empty()
|| self.label.len() > 128
|| self.label.chars().any(char::is_control)
{
return Err(MediaError::Invalid("invalid media label".into()));
}
self.selector.compile()?;
if self.controls.len() > 64 {
return Err(MediaError::Invalid("at most 64 controls per entry".into()));
}
let mut ids = std::collections::BTreeSet::new();
for control in &self.controls {
fader_core::FaderId::new(&control.id)
.map_err(|e| MediaError::Invalid(e.to_string()))?;
if !ids.insert(&control.id) {
return Err(MediaError::Invalid("duplicate control ID".into()));
}
control.action.validate()?;
if let Some(binding) = &control.binding {
binding.message.validate()?;
if let Some(feedback) = &binding.feedback {
feedback.message.validate()?;
if feedback.on > 127 || feedback.off > 127 {
return Err(MediaError::Invalid("feedback values must be 0–127".into()));
}
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn failed_identity_reads_cannot_hide_an_ambiguous_target() {
let matcher = PlayerSelector {
field: PlayerField::Identity,
pattern: "QBZ".into(),
regex: false,
}
.compile()
.unwrap();
let players = [
Player {
identity: Some("QBZ".into()),
..Player::default()
},
Player {
error: Some("timed out".into()),
..Player::default()
},
];
assert!(matcher.resolve(&players).is_err());
}
#[test]
fn play_pause_requires_the_protocol_pause_capability() {
let player = Player {
playback: Some(Playback::Paused),
can_control: true,
can_play: true,
can_pause: false,
..Player::default()
};
assert!(!Action::PlayPause.supported(&player));
}
#[test]
fn matching_is_explicit_and_never_picks_an_ambiguous_player() {
let selector = PlayerSelector {
field: PlayerField::BusName,
pattern: "org.mpris.MediaPlayer2.com.blitzfc.qbz".into(),
regex: false,
};
let matcher = selector.compile().unwrap();
let qbz = Player {
bus_name: selector.pattern.clone(),
owner: ":1.4".into(),
..Player::default()
};
assert!(matches!(matcher.resolve(&[]), Err(MediaError::Offline)));
assert_eq!(
matcher.resolve(std::slice::from_ref(&qbz)).unwrap().owner,
":1.4"
);
assert!(matches!(
matcher.resolve(&[qbz.clone(), qbz]),
Err(MediaError::Ambiguous)
));
}
#[test]
fn feedback_tracks_observation_not_intent() {
for status in [Playback::Playing, Playback::Paused, Playback::Stopped] {
let player = Player {
playback: Some(status),
..Player::default()
};
let on = [Action::Play, Action::Pause, Action::Stop]
.iter()
.filter(|a| a.feedback(Some(&player)))
.count();
assert_eq!(on, 1);
}
assert!(!Action::Play.feedback(None));
}
}

View File

@ -13,7 +13,7 @@ fail() {
assert_contains() {
file=$1
expected=$2
grep -F "$expected" "$file" >/dev/null || fail "$file does not contain: $expected"
grep -F -- "$expected" "$file" >/dev/null || fail "$file does not contain: $expected"
}
assert_fails() {
@ -37,6 +37,9 @@ assert_contains "$repository/Jenkinsfile" "stage('Portable Rust Gates')"
assert_contains "$repository/Jenkinsfile" '!params.ENABLE_NATIVE_BACKENDS'
assert_contains "$repository/Jenkinsfile" 'params.ENABLE_NATIVE_BACKENDS'
assert_contains "$repository/Jenkinsfile" 'cargo test -p fader-core -p fader-config -p midi -p volume_lib -p tui'
assert_contains "$repository/Jenkinsfile" 'dbus-run-session -- cargo test -p fader_master private_bus --locked -- --ignored'
assert_contains "$repository/Jenkinsfile" 'pkg-config --exists alsa libpulse libudev dbus-1'
assert_contains "$repository/Jenkinsfile" '-p tui -p media'
svg_count() {
directory=$1

View File

@ -4,6 +4,8 @@
mod policy;
#[cfg(feature = "pulse")]
mod process_metadata;
#[cfg(feature = "pulse")]
mod pulse;
#[cfg(feature = "pulse")]
mod pulse_worker;

View File

@ -0,0 +1,319 @@
//! Bounded, best-effort Linux process enrichment outside native callbacks.
//!
//! Only explicitly local process IDs are inspected. Environment contents never
//! leave this module: only allowlisted numeric Steam IDs enter stream metadata.
use fader_core::StreamMetadata;
use std::{
fs,
io::{self, Read},
path::Path,
sync::OnceLock,
};
const MAX_ENV_BYTES: u64 = 64 * 1024;
const MAX_STAT_BYTES: u64 = 4096;
#[derive(Default)]
struct ProcessFields {
executable: Option<String>,
cwd: Option<String>,
steam_app_id: Option<String>,
steam_game_id: Option<String>,
}
trait ProcessSource {
fn start_time(&self, pid: u32) -> Option<u64>;
fn link(&self, pid: u32, name: &str) -> Option<String>;
fn environment(&self, pid: u32) -> Option<Vec<u8>>;
}
struct ProcFs;
fn bounded_read(path: &Path, maximum: u64) -> io::Result<Vec<u8>> {
read_limited(fs::File::open(path)?, maximum)
}
fn read_limited(reader: impl Read, maximum: u64) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
reader.take(maximum + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > maximum {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"process metadata exceeds limit",
));
}
Ok(bytes)
}
fn start_time(stat: &[u8]) -> Option<u64> {
// comm is parenthesized and may contain spaces or parentheses. Field 22 is
// the twentieth field after the closing comm delimiter (state is field 3).
std::str::from_utf8(stat)
.ok()?
.rsplit_once(") ")?
.1
.split_whitespace()
.nth(19)?
.parse()
.ok()
}
impl ProcessSource for ProcFs {
fn start_time(&self, pid: u32) -> Option<u64> {
start_time(&bounded_read(Path::new(&format!("/proc/{pid}/stat")), MAX_STAT_BYTES).ok()?)
}
fn link(&self, pid: u32, name: &str) -> Option<String> {
fs::read_link(format!("/proc/{pid}/{name}"))
.ok()?
.into_os_string()
.into_string()
.ok()
}
fn environment(&self, pid: u32) -> Option<Vec<u8>> {
bounded_read(Path::new(&format!("/proc/{pid}/environ")), MAX_ENV_BYTES).ok()
}
}
fn steam_id(environment: &[u8], key: &[u8]) -> Option<String> {
let mut matches = environment.split(|byte| *byte == 0).filter_map(|entry| {
let value = entry.strip_prefix(key)?.strip_prefix(b"=")?;
if value.is_empty() || value.len() > 20 || !value.iter().all(u8::is_ascii_digit) {
return None;
}
let value = std::str::from_utf8(value).ok()?.parse::<u64>().ok()?;
(value != 0).then(|| value.to_string())
});
let first = matches.next()?;
// Duplicate conflicting keys are not reliable evidence.
matches.all(|value| value == first).then_some(first)
}
fn inspect(source: &impl ProcessSource, pid: u32) -> ProcessFields {
let Some(before) = source.start_time(pid) else {
return ProcessFields::default();
};
let executable = source.link(pid, "exe");
let cwd = source.link(pid, "cwd");
let environment = source.environment(pid);
let fields = ProcessFields {
executable,
cwd,
steam_app_id: environment
.as_deref()
.and_then(|value| steam_id(value, b"SteamAppId")),
steam_game_id: environment
.as_deref()
.and_then(|value| steam_id(value, b"SteamGameId")),
};
if source.start_time(pid) == Some(before) {
fields
} else {
ProcessFields::default()
}
}
pub(crate) fn enrich(metadata: StreamMetadata) -> StreamMetadata {
static MACHINE_ID: OnceLock<Option<String>> = OnceLock::new();
let local = MACHINE_ID.get_or_init(|| {
let bytes = bounded_read(Path::new("/etc/machine-id"), 128).ok()?;
let value = String::from_utf8(bytes).ok()?.trim().to_owned();
(!value.is_empty()).then_some(value)
});
let reported_machine = metadata.raw().get("application.process.machine_id");
if local.is_none() || reported_machine != local.as_ref() {
return metadata;
}
let Some(pid) = metadata
.raw()
.get("application.process.id")
.and_then(|value| value.parse::<u32>().ok())
.filter(|pid| *pid > 0)
else {
return metadata;
};
let fields = inspect(&ProcFs, pid);
metadata.with_process_metadata(
fields.executable,
fields.cwd,
fields.steam_app_id,
fields.steam_game_id,
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
struct FakeProc {
reused: bool,
denied: bool,
steam: bool,
reads: Cell<u32>,
}
impl ProcessSource for FakeProc {
fn start_time(&self, _: u32) -> Option<u64> {
let count = self.reads.get();
self.reads.set(count + 1);
(!self.denied).then_some(if self.reused && count > 0 { 2 } else { 1 })
}
fn link(&self, _: u32, name: &str) -> Option<String> {
Some(
if name == "exe" {
"/games/steamapps/common/Game/game.exe"
} else {
"/games/steamapps/common/Game"
}
.into(),
)
}
fn environment(&self, _: u32) -> Option<Vec<u8>> {
self.steam
.then(|| b"SECRET=never-publish\0SteamAppId=123\0SteamGameId=123\0".to_vec())
}
}
#[test]
fn steam_launch_evidence_is_allowlisted_and_paths_are_not_launch_proof() {
for steam in [false, true] {
let fields = inspect(
&FakeProc {
reused: false,
denied: false,
steam,
reads: Cell::new(0),
},
42,
);
assert!(fields.executable.unwrap().contains("steamapps"));
assert_eq!(fields.steam_app_id.as_deref(), steam.then_some("123"));
assert_eq!(fields.steam_game_id.as_deref(), steam.then_some("123"));
}
}
#[test]
fn reused_or_unavailable_process_never_supplies_metadata() {
for (reused, denied) in [(true, false), (false, true)] {
let fields = inspect(
&FakeProc {
reused,
denied,
steam: true,
reads: Cell::new(0),
},
42,
);
assert!(fields.executable.is_none());
assert!(fields.cwd.is_none());
assert!(fields.steam_app_id.is_none());
}
}
#[test]
fn malformed_or_conflicting_steam_ids_are_unavailable() {
for value in [
b"SteamAppId=0\0".as_slice(),
b"SteamAppId=nope\0",
b"SteamAppId=1\0SteamAppId=2\0",
] {
assert!(steam_id(value, b"SteamAppId").is_none());
}
assert_eq!(
steam_id(b"SteamGameId=1234567890123\0", b"SteamGameId").as_deref(),
Some("1234567890123")
);
}
#[test]
fn stat_parsing_handles_spaces_and_parentheses_in_comm() {
let stat = format!("42 (a ) b) S {} 12345 999", "0 ".repeat(18));
assert_eq!(start_time(stat.as_bytes()), Some(12345));
assert_eq!(start_time(b"truncated"), None);
}
#[test]
fn bounded_reads_reject_truncation_and_stop_at_limit_plus_one() {
let mut reader = io::Cursor::new(vec![b'x'; 100]);
assert!(read_limited(&mut reader, 8).is_err());
assert_eq!(reader.position(), 9);
assert_eq!(
read_limited(io::Cursor::new(b"12345678"), 8).unwrap(),
b"12345678"
);
}
#[test]
fn foreign_or_unknown_machine_never_enriches_a_local_pid() {
for machine in ["", "not-the-local-machine-id"] {
let metadata = enrich(
StreamMetadata::new()
.with_raw_property("application.process.machine_id", machine)
.with_raw_property("application.process.id", std::process::id().to_string()),
);
assert!(
metadata
.value(fader_core::MetadataField::ProcessExecutable)
.is_none()
);
}
}
#[test]
fn native_proton_sandbox_and_exit_fixtures_preserve_partial_unknowns() {
struct Fixture {
executable: Option<&'static str>,
environment: Option<&'static [u8]>,
exits: bool,
reads: Cell<u32>,
}
impl ProcessSource for Fixture {
fn start_time(&self, _: u32) -> Option<u64> {
let n = self.reads.get();
self.reads.set(n + 1);
(!(self.exits && n > 0)).then_some(10)
}
fn link(&self, _: u32, _: &str) -> Option<String> {
self.executable.map(str::to_owned)
}
fn environment(&self, _: u32) -> Option<Vec<u8>> {
self.environment.map(<[u8]>::to_vec)
}
}
for executable in [
Some("/games/native/game"),
Some("/proton/files/bin/wine64"),
None,
] {
let fields = inspect(
&Fixture {
executable,
environment: Some(b"SteamAppId=123\0SteamGameId=123\0"),
exits: false,
reads: Cell::new(0),
},
1,
);
assert_eq!(fields.executable.as_deref(), executable);
assert_eq!(fields.steam_app_id.as_deref(), Some("123"));
}
for exits in [false, true] {
let fields = inspect(
&Fixture {
executable: Some("/bin/game"),
environment: None,
exits,
reads: Cell::new(0),
},
1,
);
assert_eq!(
fields.executable.as_deref(),
(!exits).then_some("/bin/game")
);
assert!(fields.steam_app_id.is_none());
}
}
}

View File

@ -504,6 +504,15 @@ fn copy_stream(
properties::MEDIA_NAME,
info.proplist.get_str(properties::MEDIA_NAME),
),
(
properties::APPLICATION_PROCESS_ID,
info.proplist.get_str(properties::APPLICATION_PROCESS_ID),
),
(
properties::APPLICATION_PROCESS_MACHINE_ID,
info.proplist
.get_str(properties::APPLICATION_PROCESS_MACHINE_ID),
),
]
.into_iter()
.fold(StreamMetadata::new(), |metadata, (key, value)| {
@ -515,7 +524,7 @@ fn copy_stream(
properties::APPLICATION_ID => metadata.with_application_id(value),
properties::APPLICATION_PROCESS_BINARY => metadata.with_process_binary(value),
properties::MEDIA_NAME => metadata.with_media_name(value),
_ => metadata,
_ => metadata.with_raw_property(key, value),
}
});
let gains = info

View File

@ -743,7 +743,7 @@ fn emit_stream(
) -> bool {
events.emit(WorkerEvent::StreamMetadata {
stream: handle,
metadata: stream.metadata,
metadata: crate::process_metadata::enrich(stream.metadata),
volume_writable: stream.volume_writable,
}) && events.emit(WorkerEvent::Adapter(AdapterEvent::Observed {
stream: handle,

102
task.md
View File

@ -442,8 +442,8 @@ Dependencies: M8, M2, M1.
- [x] **M9.5 Guided fader editor:** replace pipe-delimited table commands with a
selected-fader form. Application faders edit capture field/mode/pattern;
groups select eligible application faders and show the absolute group mode;
volume and mute assignments each expose controller selection, Learn MIDI, and
Unlearn MIDI as distinct actions. Tests: editing one field preserves unrelated
volume and mute assignments each expose controller selection and Learn MIDI;
`U` in the learn prompt unbinds that action. Tests: editing one field preserves unrelated
selectors/bindings, unlearn removes only the selected action, learn conflicts
preserve the draft, and group selection translates to deduplicated
application IDs.
@ -451,10 +451,14 @@ Dependencies: M8, M2, M1.
Field, Exact/Regex, and Pattern separately while preserving other selectors;
Pattern opens a cursor-aware modal for local insertion and deletion rather
than requiring the full value to be erased;
a Save and exit row validates and submits the current capture fields without
reopening Pattern. Invalid patterns retain the form and inline error; both
submission paths use domain validation before queueing the draft edit.
groups edit application-fader membership in a checked multi-select popup and
show the currently supported Absolute mode. Volume and Mute show separate
controller, Learn MIDI, and Unlearn MIDI
actions. Learning opens a modal prompt for a fader movement or button press;
controller and Learn MIDI actions. Learning opens a modal prompt for a fader
movement or button press, with `U` to unbind and `Esc` to cancel unchanged.
Unbinding cancels capture and keeps the controller available for relearning;
relearning atomically replaces only the chosen action, and validation
conflicts retain the draft. Visibility uses the same form.
The form also persists a per-fader Slim, Bordered slim, Standard, or Thick
@ -566,6 +570,96 @@ Dependencies: all required feature milestones; hardware-only ALSA remains an exp
feature tests pass on Rust 1.88.0; example assertions now match the committed
Arch profile. Release wrapper tests pass. Publication uses the same fixed
publisher and pinned Ubuntu 24.04 Cross image as RC1.
RC2 is published from `8ac222b`: all five assets, public checksums/archive and
isolated cargo-binstall verification passed. The release API confirms a
non-draft prerelease; build provenance is recorded in `docs/releasing.md`.
## M13 — Stretch goals: matching and targeted media controls
Agreed order: M13.1 and M13.2 first, then M13.3. These do not change RC2's
supported configuration or mark the remaining release qualifications complete.
The existing `media.name` selector `(?i) - YouTube$` already satisfies the
YouTube capture use case; no browser-name condition is needed.
- [x] **M13.1 AND selectors:** add explicit conjunction while preserving existing
OR-list behavior. Dependencies: M1.2, M9.5. Acceptance: configuration and TUI
express the composition clearly; exact/regex and missing-field behavior are
deterministic; existing profiles retain their matches; invalid composition
is rejected before activation; save/reload preserves the expression.
Domain/configuration slice: `selector_mode = "any"` (default OR) or `"all"`
(AND), preserving missing-field and bounded pattern validation. The fader
editor exposes Match captures Any/All, with revisioned IPC edits and a
save/reload/restart regression. Workspace formatting, check, tests, doc tests,
clippy and release build pass, as do default/no-default and individual backend
builds. Existing profile semantics remain unchanged.
- [x] **M13.2 Richer process metadata:** enrich stream metadata with available
process paths and Steam launch identity, then expose validated matcher fields
and useful diagnostics. Dependencies: M1.2, M4. Acceptance: bounded adapter
reads, PID-reuse protection, selective Steam environment keys, and explicit
unavailable state for exited/inaccessible/sandboxed processes. Tests cover
native and Proton-like fixtures, Steam IDs, non-Steam processes and path-only
hints; a `steamapps` path must not be treated as proof Steam launched a game.
Implemented: bounded Pulse-worker enrichment and four selectable fields
(executable, working_directory, steam.app_id, steam.game_id), local-machine
guard and start-time consistency check. Fixture coverage includes missing
process data, PID reuse, Steam/path-only cases, malformed IDs and bounded
reads. Config now includes per-stream normalized metadata diagnostics, including
explicit unavailable values; native/Proton-like, restricted-environment and
exit-during-read fixtures are covered. Real-process checks remain opt-in.
- [x] **M13.3 Targeted MPRIS controls:** add Play, Pause and PlayPause via matched
player identity/desktop ID/bus name, without keyboard simulation.
Dependencies: M13.1, M13.2, M5.2, M9.5. Acceptance: a QBZ-specific binding
affects only its resolved player; paused players with no audio stream remain
discoverable; ambiguous matches are surfaced; missing players, unsupported
capabilities, disconnects and timeouts are recoverable. Cover MIDI learn,
saved configuration, TUI controls and confirmed playback-state feedback with
a fake D-Bus adapter before opt-in player integration checks.
Approved implementation slices for M13.3 (each independently tested/committed):
- [x] **M13.3a Feedback switches:** persisted global MIDI-feedback gate and
per-fader/per-media-entry gates; global off overrides local settings and sends
no output, including clearing messages; re-enable resynchronizes observed state.
All three gates are implemented in configuration/runtime and TUI, applied on
Save. Tests cover no-clear suppression, observed-state resync and explicit maps.
- [x] **M13.3b MPRIS adapter:** session-bus discovery independent of audio streams,
bounded calls, capability reporting, owner-change handling and reconnects.
Verify dependency license, native prerequisites and Rust 1.88 compatibility.
Worker and native adapter implemented with pinned dbus 0.9.12; fake-adapter
tests and two isolated dbus-run-session fixtures pass: paused discovery,
transport/extended actions, readback, capability changes, timeouts/recovery and
owner replacement. Session-bus availability survives individual player errors.
- [x] **M13.3c Media entries:** stable IDs, labels, exact/regex selectors on bus
name, desktop entry or identity; live picker plus manual entry; reject ambiguous
targets rather than selecting arbitrarily. Persist MIDI action bindings.
Hardware-free contracts, bounded validated profiles, live picker/manual
selectors and MIDI press-edge routing are integrated. Save/restart/unbind/delete
regression exercises IPC and active-versus-draft boundaries.
- [x] **M13.3d Media tab:** server-advertised availability, A/E/D editing,
validated Save and exit, MIDI Learn with U to unbind; retain offline entries.
Support Play, Pause, Stop, PlayPause, Next and Previous with capability checks.
- [x] **M13.3e Playback feedback:** confirmed Playing/Paused/Stopped exclusively
lights the corresponding transport buttons; default same-note 127/0, explicit
device-specific colour values; clear unavailable targets only when enabled.
Deduplicate and resync after reconnect; failed commands never imply success.
- [x] **M13.3f Extended controls:** relative seeking with configurable steps and
absolute position where supported; shuffle toggle/set; repeat Off/Track/Playlist
set/cycle; discover/select/activate playlists with MIDI bindings and confirmed
feedback where reported. Playlist-content editing is outside this scope.
- [x] **M13.3g Qualification:** document schema/UI, save/reload/restart tests,
fake-bus failures and capability changes, workspace gates, opt-in QBZ/controller
integration checks. No keyboard simulation or playerctl dependency.
M13 automated qualification (2026-10-18, Rust 1.88.0): all six workspace gates
passed: fmt check, all-target/all-feature check and tests, doc tests, clippy with
warnings denied, and all-feature release build. Default/no-default workspace
tests, portable-library tests/builds and independent MIDI/Pulse/MPRIS feature
tests/builds passed. Both isolated private-bus fixtures passed; CI script tests
passed and Jenkins now includes the media crate plus the private-bus fixture.
The complete QBZ example validates and round-trips all action kinds. Documentation
and the opt-in real QBZ/controller checklist are updated. Real hardware/player
checks and a provisioned Jenkins execution are **not claimed**; their existing
release/manual qualification items remain open. M13 completion does not complete
native PipeWire, relative groups, M0.2 or the wider release backlog.
## User requirement coverage

View File

@ -9,4 +9,5 @@ publish.workspace = true
[dependencies]
fader-core.workspace = true
media.workspace = true
ratatui.workspace = true

View File

@ -137,6 +137,8 @@ fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot {
}],
discovered_midi_ports: Vec::new(),
configuration: ConfigurationSnapshot {
media_entries: Vec::new(),
media_state: media::Snapshot::default(),
revision: 7,
dirty: false,
applied_revision: 7,
@ -145,6 +147,9 @@ fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot {
error: None,
profile_id: "desktop".to_owned(),
profile_path: Some("/home/alex/.config/fader_master/profiles/desktop.toml".to_owned()),
feedback_disabled: false,
disabled_feedback_faders: Vec::new(),
stream_metadata: Vec::new(),
available_profiles: vec!["desktop".to_owned()],
mixer_orientation,
status_display: tui::StatusDisplayMode::Symbol,
@ -158,16 +163,19 @@ fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot {
ConfiguredApplication {
id: "music".to_owned(),
label: "Music".to_owned(),
match_all: false,
selectors: Vec::new(),
},
ConfiguredApplication {
id: "browser".to_owned(),
label: "Browser".to_owned(),
match_all: false,
selectors: Vec::new(),
},
ConfiguredApplication {
id: "voice".to_owned(),
label: "Voice chat".to_owned(),
match_all: false,
selectors: Vec::new(),
},
],

File diff suppressed because it is too large Load Diff

976
tui/src/media_ui.rs Normal file
View File

@ -0,0 +1,976 @@
use super::*;
pub(super) enum Intent {
Edit(ConfigurationEdit),
Action(String, String),
Learn(String, String, String),
CancelLearn,
Save,
}
enum Editor {
Entry {
entry: media::Entry,
row: usize,
text: Option<String>,
},
Control {
entry: media::Entry,
index: usize,
row: usize,
text: Option<String>,
},
Players {
entry: media::Entry,
selected: usize,
},
Delete(String),
Learn {
entry: String,
control: String,
selected: usize,
started: bool,
seen: bool,
revision: u64,
},
}
#[derive(Default)]
pub(super) struct MediaUi {
selected: usize,
editor: Option<Editor>,
error: Option<String>,
}
fn new_entry(cfg: &ConfigurationSnapshot) -> media::Entry {
let id = unique_id("media", cfg.media_entries.iter().map(|e| e.id.as_str()));
media::Entry {
label: "Media player".into(),
id,
selector: media::PlayerSelector {
field: media::PlayerField::BusName,
pattern: String::new(),
regex: false,
},
feedback_enabled: true,
controls: [
media::Action::Play,
media::Action::Pause,
media::Action::Stop,
media::Action::PlayPause,
media::Action::Next,
media::Action::Previous,
]
.into_iter()
.enumerate()
.map(|(i, action)| media::Control {
id: format!("control-{i}"),
action,
binding: None,
})
.collect(),
}
}
fn unique_id<'a>(prefix: &str, ids: impl Iterator<Item = &'a str>) -> String {
let ids: Vec<_> = ids.collect();
(1..)
.map(|n| format!("{prefix}-{n}"))
.find(|id| !ids.contains(&id.as_str()))
.unwrap_or_else(|| prefix.into())
}
fn entry_editor(entry: media::Entry) -> Editor {
Editor::Entry {
entry,
row: 0,
text: None,
}
}
fn actions() -> Vec<media::Action> {
vec![
media::Action::Play,
media::Action::Pause,
media::Action::Stop,
media::Action::PlayPause,
media::Action::Next,
media::Action::Previous,
media::Action::Seek { offset_ms: -10000 },
media::Action::Seek { offset_ms: 10000 },
media::Action::SetPosition { position_ms: 0 },
media::Action::ShuffleToggle,
media::Action::Shuffle { enabled: true },
media::Action::Shuffle { enabled: false },
media::Action::RepeatCycle,
media::Action::Repeat {
mode: media::Repeat::None,
},
media::Action::Repeat {
mode: media::Repeat::Track,
},
media::Action::Repeat {
mode: media::Repeat::Playlist,
},
media::Action::Playlist {
id: "/playlist".into(),
},
]
}
fn cycle_action(action: &mut media::Action, forward: bool) {
let choices = actions();
let index = choices
.iter()
.position(|a| match (a, &*action) {
(media::Action::Seek { offset_ms: a }, media::Action::Seek { offset_ms: b }) => {
a.signum() == b.signum()
}
(media::Action::SetPosition { .. }, media::Action::SetPosition { .. })
| (media::Action::Playlist { .. }, media::Action::Playlist { .. }) => true,
_ => a == action,
})
.unwrap_or(0);
let next = if forward {
(index + 1) % choices.len()
} else {
(index + choices.len() - 1) % choices.len()
};
if let Some(choice) = choices.get(next) {
*action = choice.clone();
}
}
fn parameter(action: &media::Action) -> String {
match action {
media::Action::Seek { offset_ms } => offset_ms.to_string(),
media::Action::SetPosition { position_ms } => position_ms.to_string(),
media::Action::Playlist { id } => id.clone(),
_ => "—".into(),
}
}
fn set_parameter(action: &mut media::Action, text: &str) -> Result<(), String> {
match action {
media::Action::Seek { offset_ms } => {
*offset_ms = text.parse().map_err(|_| "enter signed milliseconds")?
}
media::Action::SetPosition { position_ms } => {
*position_ms = text.parse().map_err(|_| "enter nonnegative milliseconds")?
}
media::Action::Playlist { id } => *id = text.into(),
_ => return Err("this action has no parameter".into()),
}
action.validate().map_err(|e| e.to_string())
}
impl MediaUi {
pub fn modal(&self) -> bool {
self.editor.is_some()
}
pub fn refresh(&mut self, cfg: &ConfigurationSnapshot) {
if let Some(Editor::Learn {
started: true,
seen,
revision,
entry,
control,
..
}) = &mut self.editor
{
if cfg.learning.is_some() {
*seen = true;
} else if *seen
|| (cfg.revision > *revision
&& cfg.media_entries.iter().any(|e| {
&e.id == entry
&& e.controls
.iter()
.any(|c| &c.id == control && c.binding.is_some())
}))
{
self.editor = None;
}
}
}
pub fn key(&mut self, key: KeyCode, cfg: &ConfigurationSnapshot) -> Vec<Intent> {
self.error = None;
if let Some(editor) = self.editor.take() {
return self.editor_key(editor, key, cfg);
}
let rows = media_rows(cfg);
self.selected = self.selected.min(rows.len().saturating_sub(1));
let target = rows.get(self.selected).copied();
match key {
KeyCode::Up => self.selected = self.selected.saturating_sub(1),
KeyCode::Down => self.selected = (self.selected + 1).min(rows.len().saturating_sub(1)),
KeyCode::Home => self.selected = 0,
KeyCode::End => self.selected = rows.len().saturating_sub(1),
KeyCode::Char('a' | 'A') => self.editor = Some(entry_editor(new_entry(cfg))),
KeyCode::Char('e' | 'E') => {
if let Some((entry, _)) = target {
self.editor = Some(entry_editor(entry.clone()));
}
}
KeyCode::Char('d' | 'D') => {
if let Some((entry, _)) = target {
self.editor = Some(Editor::Delete(entry.id.clone()));
}
}
KeyCode::Char('s' | 'S') => return vec![Intent::Save],
KeyCode::Char('l' | 'L') => {
if let Some((entry, Some(control))) = target {
if cfg.surfaces.is_empty() {
self.error = Some("Add a MIDI device in Configuration first".into());
} else {
self.editor = Some(Editor::Learn {
entry: entry.id.clone(),
control: control.id.clone(),
selected: 0,
started: false,
seen: false,
revision: cfg.revision,
});
}
}
}
KeyCode::Enter => {
if let Some((entry, Some(control))) = target {
if cfg.dirty {
self.error =
Some("Save configuration before sending media commands".into());
} else {
match entry
.selector
.compile()
.and_then(|m| m.resolve(&cfg.media_state.players))
{
Ok(player) if control.action.supported(player) => {
return vec![Intent::Action(entry.id.clone(), control.id.clone())];
}
Ok(_) => self.error = Some("Unsupported by this player".into()),
Err(e) => self.error = Some(e.to_string()),
}
}
}
}
_ => {}
}
vec![]
}
fn editor_key(
&mut self,
mut editor: Editor,
key: KeyCode,
cfg: &ConfigurationSnapshot,
) -> Vec<Intent> {
match &mut editor {
Editor::Delete(id) => {
if matches!(key, KeyCode::Char('y' | 'Y')) {
return vec![Intent::Edit(ConfigurationEdit::RemoveMediaEntry {
id: id.clone(),
})];
}
if matches!(key, KeyCode::Esc | KeyCode::Char('n' | 'N')) {
return vec![];
}
}
Editor::Players { entry, selected } => {
match key {
KeyCode::Esc => {
self.editor = Some(entry_editor(entry.clone()));
return vec![];
}
KeyCode::Up => *selected = selected.saturating_sub(1),
KeyCode::Down => {
*selected =
(*selected + 1).min(cfg.media_state.players.len().saturating_sub(1))
}
KeyCode::Enter => {
if let Some(player) = cfg.media_state.players.get(*selected) {
// DesktopEntry is stable across instance-specific bus names; ambiguity remains an error.
entry.selector = if let Some(desktop) =
player.desktop_entry.as_ref().filter(|s| !s.is_empty())
{
media::PlayerSelector {
field: media::PlayerField::DesktopEntry,
pattern: desktop.clone(),
regex: false,
}
} else {
media::PlayerSelector {
field: media::PlayerField::BusName,
pattern: player.bus_name.clone(),
regex: false,
}
};
self.editor = Some(entry_editor(entry.clone()));
return vec![];
}
}
_ => {}
}
}
Editor::Learn {
entry,
control,
selected,
started,
..
} => match key {
KeyCode::Esc => return vec![Intent::CancelLearn],
KeyCode::Char('u' | 'U') => {
return vec![
Intent::CancelLearn,
Intent::Edit(ConfigurationEdit::SetMediaBinding {
entry: entry.clone(),
control: control.clone(),
binding: None,
}),
];
}
KeyCode::Up if !*started => *selected = selected.saturating_sub(1),
KeyCode::Down if !*started => {
*selected = (*selected + 1).min(cfg.surfaces.len().saturating_sub(1))
}
KeyCode::Enter if !*started => {
if let Some(surface) = cfg.surfaces.get(*selected) {
let intent =
Intent::Learn(surface.id.clone(), entry.clone(), control.clone());
*started = true;
self.editor = Some(editor);
return vec![intent];
}
}
_ => {}
},
Editor::Entry { entry, row, text } => {
if let Some(value) = text {
match key {
KeyCode::Esc => *text = None,
KeyCode::Enter => {
if *row == 0 {
entry.label = value.clone();
} else {
entry.selector.pattern = value.clone();
}
*text = None;
}
KeyCode::Backspace => {
value.pop();
}
KeyCode::Char(ch) if !ch.is_control() && value.len() < 256 => {
value.push(ch)
}
_ => {}
}
} else {
match key {
KeyCode::Esc => return vec![],
KeyCode::Up => *row = row.saturating_sub(1),
KeyCode::Down => *row = (*row + 1).min(5 + entry.controls.len()),
KeyCode::Char('p' | 'P') => {
self.editor = Some(Editor::Players {
entry: entry.clone(),
selected: 0,
});
return vec![];
}
KeyCode::Char('a' | 'A') if entry.controls.len() < 64 => {
let id =
unique_id("control", entry.controls.iter().map(|c| c.id.as_str()));
entry.controls.push(media::Control {
id,
action: media::Action::PlayPause,
binding: None,
});
*row = 5 + entry.controls.len();
}
KeyCode::Char('d' | 'D') if *row >= 6 => {
let index = *row - 6;
if index < entry.controls.len() {
entry.controls.remove(index);
}
*row = (*row).min(5 + entry.controls.len());
}
KeyCode::Enter | KeyCode::Left | KeyCode::Right => match *row {
0 => *text = Some(entry.label.clone()),
1 => {
entry.selector.field = match entry.selector.field {
media::PlayerField::BusName => media::PlayerField::DesktopEntry,
media::PlayerField::DesktopEntry => {
media::PlayerField::Identity
}
media::PlayerField::Identity => media::PlayerField::BusName,
}
}
2 => *text = Some(entry.selector.pattern.clone()),
3 => entry.selector.regex = !entry.selector.regex,
4 => entry.feedback_enabled = !entry.feedback_enabled,
5 => match entry.validate() {
Ok(()) => {
return vec![Intent::Edit(ConfigurationEdit::SetMediaEntry {
entry: entry.clone(),
})];
}
Err(e) => self.error = Some(e.to_string()),
},
index => {
self.editor = Some(Editor::Control {
entry: entry.clone(),
index: index - 6,
row: 0,
text: None,
});
return vec![];
}
},
_ => {}
}
}
}
Editor::Control {
entry,
index,
row,
text,
} => {
let Some(control) = entry.controls.get_mut(*index) else {
return vec![];
};
if let Some(value) = text {
match key {
KeyCode::Esc => *text = None,
KeyCode::Backspace => {
value.pop();
}
KeyCode::Char(ch) if !ch.is_control() && value.len() < 256 => {
value.push(ch)
}
KeyCode::Enter => {
let result = if *row == 1 {
set_parameter(&mut control.action, value)
} else if let Some(feedback) =
control.binding.as_mut().and_then(|b| b.feedback.as_mut())
{
value
.parse::<u16>()
.map_err(|_| "enter a MIDI number".to_string())
.and_then(|n| {
if (*row == 4 && (1..=16).contains(&n))
|| (*row != 4 && n <= 127)
{
match *row {
4 => feedback.message.channel = n,
5 => feedback.message.number = n,
6 => feedback.on = n as u8,
7 => feedback.off = n as u8,
_ => {}
}
Ok(())
} else {
Err("channel must be 1–16, data 0–127".into())
}
})
} else {
Err("learn an input and enable custom feedback first".into())
};
match result {
Ok(()) => *text = None,
Err(e) => self.error = Some(e),
}
}
_ => {}
}
} else {
match key {
KeyCode::Esc => {
self.editor = Some(entry_editor(entry.clone()));
return vec![];
}
KeyCode::Up => *row = row.saturating_sub(1),
KeyCode::Down => *row = (*row + 1).min(8),
KeyCode::Enter | KeyCode::Left | KeyCode::Right => match *row {
0 => cycle_action(&mut control.action, key != KeyCode::Left),
1 => {
if let media::Action::Playlist { id } = &mut control.action {
if key != KeyCode::Enter {
if let Ok(player) = entry
.selector
.compile()
.and_then(|m| m.resolve(&cfg.media_state.players))
{
let i = player
.playlists
.iter()
.position(|p| &p.id == id)
.map_or(0, |i| {
(i + 1) % player.playlists.len().max(1)
});
if let Some(playlist) = player.playlists.get(i) {
*id = playlist.id.clone();
}
}
} else {
*text = Some(id.clone());
}
} else {
*text = Some(parameter(&control.action));
}
}
2 => {
if let Some(binding) = &mut control.binding {
binding.feedback = if binding.feedback.is_some() {
None
} else {
Some(media::Feedback {
message: binding.message.clone(),
on: 127,
off: 0,
})
};
} else {
self.error = Some(
"Save entry, then L to learn this control first".into(),
);
}
}
3 => {
if let Some(feedback) =
control.binding.as_mut().and_then(|b| b.feedback.as_mut())
{
feedback.message.kind = match feedback.message.kind {
media::MessageKind::Note => media::MessageKind::Cc,
media::MessageKind::Cc => media::MessageKind::Note,
};
}
}
4..=7 => {
if let Some(f) =
control.binding.as_ref().and_then(|b| b.feedback.as_ref())
{
*text = Some(match *row {
4 => f.message.channel.to_string(),
5 => f.message.number.to_string(),
6 => f.on.to_string(),
_ => f.off.to_string(),
});
}
}
8 => match entry.validate() {
Ok(()) => {
self.editor = Some(entry_editor(entry.clone()));
return vec![];
}
Err(e) => self.error = Some(e.to_string()),
},
_ => {}
},
_ => {}
}
}
}
}
self.editor = Some(editor);
vec![]
}
pub fn render(&self, area: Rect, buf: &mut Buffer, cfg: &ConfigurationSnapshot) {
let rows = media_rows(cfg);
let lines: Vec<String> = rows
.iter()
.map(|(entry, control)| {
let player = entry
.selector
.compile()
.and_then(|m| m.resolve(&cfg.media_state.players));
if let Some(control) = control {
let status = match &player {
Ok(p) if !control.action.supported(p) => "unsupported",
Ok(p) if control.action.feedback(Some(p)) => "active",
Ok(_) => "ready",
Err(_) => "offline/ambiguous",
};
let binding = control
.binding
.as_ref()
.map(|b| {
format!(
"{} {:?} ch{} #{}",
b.surface, b.message.kind, b.message.channel, b.message.number
)
})
.unwrap_or_else(|| "unbound".into());
format!(" {:?} [{status}] {binding}", control.action)
} else {
let status = player
.map(|p| {
format!(
"{:?} · {}",
p.playback,
p.identity.as_deref().unwrap_or(&p.bus_name)
)
})
.unwrap_or_else(|e| e.to_string());
format!(
"{} · {:?}: {} · {status} · feedback {}",
entry.label,
entry.selector.field,
entry.selector.pattern,
if cfg.feedback_disabled || !entry.feedback_enabled {
"off"
} else {
"on"
}
)
}
})
.collect();
let lines = if lines.is_empty() {
vec!["No media entries. A adds one; players may be offline.".into()]
} else {
lines
};
draw_rows(
area,
buf,
&lines,
self.selected,
"Media controls",
self.error
.as_deref()
.or(cfg.media_state.error.as_deref())
.unwrap_or("Enter send · L learn · A add · E edit · D delete · S save"),
);
}
pub fn render_modal(&self, area: Rect, buf: &mut Buffer, cfg: &ConfigurationSnapshot) {
let Some(editor) = &self.editor else {
return;
};
let (title, rows, selected, text, help) = match editor {
Editor::Entry { entry, row, text } => {
let mut rows = vec![
format!("Name: {}", entry.label),
format!("Target field: {:?}", entry.selector.field),
format!("Pattern: {}", entry.selector.pattern),
format!("Regex: {}", entry.selector.regex),
format!("Feedback: {}", entry.feedback_enabled),
"Save and exit (draft)".into(),
];
rows.extend(
entry
.controls
.iter()
.map(|c| format!("Edit {}: {:?}", c.id, c.action)),
);
(
"Edit media entry",
rows,
*row,
text.as_deref(),
"Enter edit · P discovered players · A add control · D remove control · Esc discard",
)
}
Editor::Control {
entry,
index,
row,
text,
} => {
let Some(c) = entry.controls.get(*index) else {
return;
};
let f = c.binding.as_ref().and_then(|b| b.feedback.as_ref());
let playlist_name = match &c.action {
media::Action::Playlist { id } => entry
.selector
.compile()
.ok()
.and_then(|m| m.resolve(&cfg.media_state.players).ok())
.and_then(|p| p.playlists.iter().find(|v| &v.id == id))
.map(|p| format!(" ({})", p.name))
.unwrap_or_default(),
_ => String::new(),
};
let rows = vec![
format!("Action: {:?}", c.action),
format!(
"Parameter (ms / playlist path): {}{}",
parameter(&c.action),
playlist_name
),
format!("Custom feedback: {}", f.is_some()),
format!("Output kind: {:?}", f.map(|f| f.message.kind)),
format!("Channel: {:?}", f.map(|f| f.message.channel)),
format!("Number: {:?}", f.map(|f| f.message.number)),
format!("On value/color: {:?}", f.map(|f| f.on)),
format!("Off value/color: {:?}", f.map(|f| f.off)),
"Save and return to entry".into(),
];
(
"Edit media control",
rows,
*row,
text.as_deref(),
"←→ action / playlist · Enter edit · Esc return · Save entry to retain changes",
)
}
Editor::Players { selected, .. } => (
"Discovered players",
cfg.media_state
.players
.iter()
.map(|p| {
format!(
"{} · {} · {}",
p.identity.as_deref().unwrap_or("unknown"),
p.desktop_entry.as_deref().unwrap_or("no desktop entry"),
p.bus_name
)
})
.collect(),
*selected,
None,
"Enter select stable desktop entry or bus name · Esc manual input",
),
Editor::Delete(id) => (
"Delete media entry?",
vec![format!(
"Delete {id} and all its controls? Y confirm / N cancel"
)],
0,
None,
"Change is a draft until configuration Save",
),
Editor::Learn {
selected, started, ..
} => (
"Learn media MIDI input",
if *started {
vec![
cfg.learning
.clone()
.unwrap_or_else(|| "Waiting for server / MIDI press…".into()),
]
} else {
cfg.surfaces
.iter()
.map(|s| format!("{} ({})", s.label, s.id))
.collect()
},
*selected,
None,
"Choose device, Enter learn · U unbind · Esc cancel · Save to activate",
),
};
let modal = Rect::new(
area.x + 1,
area.y + 1,
area.width.saturating_sub(2),
area.height.saturating_sub(2),
);
Clear.render(modal, buf);
let mut rows = rows;
if let Some(text) = text
&& let Some(row) = rows.get_mut(selected)
{
*row = format!("Editing: {text}▏ (Enter accept / Esc cancel)");
}
draw_rows(
modal,
buf,
&rows,
selected,
title,
self.error.as_deref().unwrap_or(help),
);
}
}
fn media_rows(cfg: &ConfigurationSnapshot) -> Vec<(&media::Entry, Option<&media::Control>)> {
cfg.media_entries
.iter()
.flat_map(|e| {
std::iter::once((e, None)).chain(e.controls.iter().map(move |c| (e, Some(c))))
})
.collect()
}
fn draw_rows(
area: Rect,
buf: &mut Buffer,
rows: &[String],
selected: usize,
title: &str,
help: &str,
) {
let block = Block::bordered().title(title).title_bottom(help);
let inner = block.inner(area);
block.render(area, buf);
let selected = selected.min(rows.len().saturating_sub(1));
let start = selected.saturating_sub(usize::from(inner.height).saturating_sub(1));
let lines: Vec<Line<'_>> = rows
.iter()
.enumerate()
.skip(start)
.map(|(i, row)| {
Line::from(format!("{} {row}", if i == selected { "›" } else { " " })).style(
if i == selected {
Style::default().reversed()
} else {
Style::default()
},
)
})
.collect();
Paragraph::new(lines).render(inner, buf);
}
#[cfg(test)]
mod tests {
use super::*;
fn configured() -> ConfigurationSnapshot {
let mut cfg = ConfigurationSnapshot::default();
let mut entry = new_entry(&cfg);
entry.selector.pattern = "org.mpris.MediaPlayer2.fixture".into();
cfg.media_entries.push(entry);
cfg.media_state.available = true;
cfg.media_state.players.push(media::Player {
bus_name: "org.mpris.MediaPlayer2.fixture".into(),
desktop_entry: Some("fixture".into()),
can_control: true,
can_play: true,
..media::Player::default()
});
cfg.surfaces.push(ConfiguredSurface {
id: "buttons".into(),
label: "Buttons".into(),
});
cfg
}
#[test]
fn media_tab_is_advertised_by_server_even_with_no_players() {
let client = DemoClient::default();
let mut app = LiveTui::new(client).unwrap();
app.handle_key_event(KeyEvent::from(KeyCode::Char('3')));
assert_eq!(app.tab, Tab::Mixer);
app.snapshot.configuration.media_state.available = true;
app.handle_key_event(KeyEvent::from(KeyCode::Char('3')));
assert_eq!(app.tab, Tab::Media);
let mut buf = Buffer::empty(Rect::new(0, 0, 100, 30));
(&app).render(buf.area, &mut buf);
assert!(
buf.content
.iter()
.map(|c| c.symbol())
.collect::<String>()
.contains("No media entries")
);
}
#[test]
fn commands_require_unique_capable_saved_target() {
let mut cfg = configured();
let mut ui = MediaUi::default();
ui.key(KeyCode::Down, &cfg);
assert!(matches!(
ui.key(KeyCode::Enter, &cfg).as_slice(),
[Intent::Action(_, _)]
));
cfg.dirty = true;
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
cfg.dirty = false;
cfg.media_state.players[0].can_play = false;
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
cfg.media_state
.players
.push(cfg.media_state.players[0].clone());
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
cfg.media_state.players.clear();
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
}
#[test]
fn picker_prefers_desktop_entry_and_learn_unbinds_selected_control() {
let cfg = configured();
let mut ui = MediaUi::default();
ui.key(KeyCode::Char('e'), &cfg);
ui.key(KeyCode::Char('p'), &cfg);
ui.key(KeyCode::Enter, &cfg);
let Some(Editor::Entry { entry, .. }) = &ui.editor else {
panic!("entry editor");
};
assert_eq!(entry.selector.field, media::PlayerField::DesktopEntry);
assert_eq!(entry.selector.pattern, "fixture");
ui.key(KeyCode::Esc, &cfg);
ui.key(KeyCode::Down, &cfg);
ui.key(KeyCode::Char('l'), &cfg);
assert!(
matches!(ui.key(KeyCode::Enter, &cfg).as_slice(), [Intent::Learn(surface, _, _)] if surface == "buttons")
);
assert!(matches!(
ui.key(KeyCode::Char('u'), &cfg).as_slice(),
[
Intent::CancelLearn,
Intent::Edit(ConfigurationEdit::SetMediaBinding { binding: None, .. })
]
));
assert!(!ui.modal());
ui.key(KeyCode::Char('d'), &cfg);
assert!(ui.modal());
assert!(matches!(
ui.key(KeyCode::Char('y'), &cfg).as_slice(),
[Intent::Edit(ConfigurationEdit::RemoveMediaEntry { .. })]
));
}
#[test]
fn learn_completion_can_arrive_before_learning_snapshot() {
let mut cfg = configured();
let mut ui = MediaUi::default();
ui.key(KeyCode::Down, &cfg);
ui.key(KeyCode::Char('l'), &cfg);
ui.key(KeyCode::Enter, &cfg);
cfg.media_entries[0].controls[0].binding = Some(media::Binding {
surface: "buttons".into(),
message: media::Message {
kind: media::MessageKind::Note,
channel: 1,
number: 1,
},
feedback: None,
});
cfg.revision += 1;
ui.refresh(&cfg);
assert!(!ui.modal());
}
#[test]
fn invalid_selector_cannot_leave_editor_and_save_is_explicit() {
let mut ui = MediaUi::default();
let cfg = ConfigurationSnapshot::default();
ui.key(KeyCode::Char('a'), &cfg);
assert!(ui.modal());
if let Some(Editor::Entry { entry, row, .. }) = &mut ui.editor {
entry.selector.pattern = "[".into();
entry.selector.regex = true;
*row = 5;
}
assert!(ui.key(KeyCode::Enter, &cfg).is_empty());
assert!(ui.modal());
assert!(ui.error.is_some());
if let Some(Editor::Entry { entry, .. }) = &mut ui.editor {
entry.selector.pattern = "qbz".into();
}
assert!(matches!(
ui.key(KeyCode::Enter, &cfg).as_slice(),
[Intent::Edit(ConfigurationEdit::SetMediaEntry { .. })]
));
assert!(!ui.modal());
}
}