fader_master/architecture.md

38 KiB
Raw Blame History

fader_master architecture

Status: design researched 2026-10-05; foundation and the M1–M3 hardware-free domain, persistence, reducer, bounded dispatch, fake-adapter, and lifecycle milestones are implemented. The executable launches an interactive Ratatui mixer shell backed by explicitly labeled demo state. Native workers, live TUI state, and native adapters below are planned, not shipped.

Implemented boundary at M2 entry

Rust 1.88.0 is the pinned toolchain and tested MSRV. The workspace inherits package metadata, including the existing custom LICENSE through license-file. core contains typed IDs, finite gain/channel vectors, normalized selectors, stream identities, logical routing, device-scoped bindings, group gain planning, and serial mute intent planning. config contains strict version-1 profile, device-capability, and persisted-state schemas. Parsing validates stable IDs, selectors, references, duplicate IDs and physical bindings, audio/MIDI bounds, and feedback/output capabilities before returning a document. It serializes a canonical semantic round trip. XDG resolution, private directory/file modes, owner/symlink checks, same-directory atomic replacement with file and directory sync, recoverable state loads, comment-preserving application-label edits, and forward-migration backups are implemented. A pure monotonic checkpoint coordinator owns the 500 ms debounce, two-second maximum dirty interval, and shutdown flush. Restart views force cached observations stale and retain desired intent separately; adopt produces no audio write, while restore checks the profile write ceiling before yielding application-join intent. MIDI/audio crates are adapter boundaries without native handles or transport behavior yet.

Stable IDs contain 1–64 ASCII bytes, start with an alphanumeric character, and otherwise allow alphanumerics, _, and -. Selector patterns contain 1–256 bytes; regex compilation has a 1 MiB size limit. Missing normalized properties never fall back to raw metadata. Group references cannot nest. Logical routing validates references and returns ordered, deduplicated stream sets. Physical binding lookup includes surface, channel, message kind, and control number.

Group gain plans clip each stream at the explicit write ceiling, preserve channel ratios, and leave observations unchanged. Relative scaling divides a stream's maximum by the aggregate maximum before multiplication to avoid intermediate overflow. Partial confirmations and late members are represented by supplying updated observations to the next plan; asynchronous dispatch belongs to M3. Mute planning stores accepted per-stream intent so rapid toggles and overlapping targets compose. The future reducer must clear intent only after checking that an operation completion is current, or on removal/disconnect. Display state is always derived from observations.

Added dependencies were verified from their downloaded package manifests: thiserror 2.0.21 requires Rust 1.77, regex 1.13.1 requires 1.65, and the test-only proptest 1.11.0 requires 1.85. Each offers MIT OR Apache-2.0 and requires no audio/MIDI development library. All compile on the pinned 1.88.0 toolchain. Regex provides bounded compiled matching, thiserror implements typed library errors, and proptest exercises numerical invariants. Cargo.lock records the resolved versions; dependency versions are workspace-managed.

M2.1 adds serde 1.0.229 (Rust 1.56) and toml 0.8.23 / toml_edit 0.22.27 (Rust 1.66), each MIT OR Apache-2.0 with no native prerequisite. Serde defines strict data shapes and TOML supplies parsing and canonical serialization; the resolved toml_edit dependency will also underpin M2.2 comment-preserving edits. These versions compile on the pinned Rust 1.88.0.

M2.2 directly uses rustix 1.1.5 (Rust 1.65, Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT) for safe effective-user checks and tempfile 3.27.0 (Rust 1.63, MIT OR Apache-2.0) for collision-safe same-directory temporary files. Neither adds a native system-library prerequisite, and both compile on the pinned toolchain.

M4 begins with libpulse-binding 2.30.1 and libpulse-sys 1.23.0. Both declare Rust 1.63 and MIT OR Apache-2.0, compile on the pinned Rust 1.88.0, and require libpulse development files through pkg-config. The default compatibility feature targets PulseAudio 8 or newer. The adapter uses the asynchronous protocol API on an owned mainloop, deep-copies callback data, and converts software volumes through VolumeLinear; it does not parse pactl.

Purpose and scope

Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group/default-output targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output.

The MVP controls application playback streams and the selected backend's default output sink, not microphone capture, routing, DSP, or audio samples. An application may have zero, one, or many streams. The output target follows the server's current default sink and remains distinct from ALSA hardware mixer elements, which are an explicit extension rather than a substitute for application control.

Structure

flowchart LR
    HW[USB MIDI surfaces] <--> MIDI[MIDI transport and device profiles]
    MIDI <-->|commands and confirmed feedback| SERVER[Server: single state owner]
    TUI[TUI: mixer and editor] <-->|local IPC| SERVER
    SERVER <--> CONFIG[TOML profiles and state]
    SERVER --> OBJECTS[Virtual applications and groups]
    OBJECTS --> PORT[Audio adapter commands]
    PORT --> PULSE[PulseAudio protocol]
    PORT --> PW[Native PipeWire]
    PORT --> ALSA[ALSA mixer]
    PULSE --> EVENTS[Snapshots and observed changes]
    PW --> EVENTS
    ALSA --> EVENTS
    EVENTS --> SERVER

Only the server mutates domain state. Virtual objects resolve commands; they do not own native backend handles. Feedback follows observations, never a direct MIDI-to-audio shortcut.

Workspace location Planned responsibility
Existing core directory, package fader-core Pure domain types and target resolution; commands/events, reducer and adapter contract follow in M3
Existing config directory, package fader-config Empty boundary; TOML schemas, validation, migration, atomic persistence follow in M2
Existing sound, currently package volume_lib Audio workers; pulse, pipewire, alsa-mixer features; fake adapter
Existing midi MIDI transport, parsing, device identity, bindings, feedback, pickup
Existing tui Mixer/editor/devices/status tabs and IPC client; no native audio access
Existing fader_master CLI, server orchestration, IPC, worker lifecycle and logging

All outer crates depend inward on domain contracts; core depends on none of them. Start with modules inside these crates, splitting further only when warranted. An internal audio worker contract accepts typed commands and emits typed events; do not require native handles or callback objects to implement async traits or cross threads.

Domain model and matching

  • 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.
  • 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.

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.

The initial physical fader curve maps its normalized position linearly to gain in [0, 1]; future dB curves are explicit profile options. Above-unity writes require explicit configuration, with a finite maximum. External over-limit observations remain visible without being rewritten or silently clamped; feedback clips only the physical representation. Mute is an independent boolean: zero volume does not imply mute, and changing volume does not unmute.

For an application or group, display maximum member stream gain as the aggregate fader position plus a mixed indicator when gains differ. Display mute as all-muted, all-unmuted, mixed, or unavailable. A toggle mutes all when any member is unmuted; otherwise it unmutes all. Unmute leaves volumes untouched and clears mute on all members, including independently muted members; there is no hidden pre-group mute restore in v1.

Recognize two group volume models, but enable only sync groups in the current runtime:

  1. absolute (also called sync, current default and only accepted profile mode): a move to g sets each resolved stream's scalar gain to g, preserving each stream's channel balance. This is predictable for absolute USB faders.
  2. relative (reserved): each member remembers the channel vector from its last independent application-fader or external edit as that member's maximum. A normalized group position p scales the member between silence and that maximum (p * member_max), preserving channel balance. A group write or its confirmation never rebases the remembered maximum; a later independent/external edit rebases only that member. Moving to zero therefore remains reversible. Newly resolved members adopt their live state as their initial maximum, and removed members lose their anchor.

The pure domain planner for the reserved relative model exists and is tested, but profile validation rejects volume_mode = "relative" until the runtime can track write origin and lifecycle for those anchors. Examples and live routing use volume_mode = "absolute" only.

Group dispatch is best effort because audio APIs do not offer a transaction across arbitrary streams. Track results per stream, keep successful changes, show failures, and refresh observations. Do not pretend to roll back atomically. Backend workers preserve server write ordering per stream and per property; volume and mute can be tracked independently.

Default startup, reconnect, profile switching, and new-stream discovery adopt live state without writes. Live MIDI/TUI input against an offline or read-only target is a visible, nonfatal no-op and is never replayed when the target appears. A future explicit saved-intent workflow may retain a deliberate offline command for display, but only an explicit restore policy may apply saved object intents to newly matched streams after full discovery, with validated bounds and visible status; conflicting restored targets use documented profile order, last matching target wins. Persist that order and test it. Never resurrect backend handles or pending operation IDs from disk.

Server state transitions and concurrency

Use a Tokio event task as the single domain owner. MIDI, IPC, persistence, and audio workers send owned messages. A pure reducer produces state changes and effects, making the sequence testable without devices.

  1. Decode and validate a MIDI/TUI command with origin, surface, active profile revision, and sequence number.
  2. Resolve its fader/object and current stream membership. Record desired state and pending operation before emitting adapter effects. “Record” means immediate in-memory state; durable TOML checkpoints are debounced, not a disk write on every MIDI packet.
  3. Dispatch absolute per-stream volume/mute operations with operation ID, backend epoch, and config generation. Coalesce unsent volume updates to the latest value per stream/property. Resolve mute toggles to explicit booleans in accepted order, so two rapid presses toggle twice even before confirmation.
  4. Process acceptance/failure and observed events. Serialize in-flight writes per property and retain newer pending intent when an older observation arrives. Where the backend cannot correlate notifications to requests, treat notifications as observed state, use readback and finite timeout to settle pending operations, and do not invent correlation IDs from equal values.
  5. Recompute affected virtual objects, publish revisioned views, schedule checkpointing, and enqueue device feedback from observed values. External changes follow the same path but cause no audio write. Timeouts trigger readback; disconnects invalidate handles and pending operations.

PulseAudio and native PipeWire event loops run on their own owner threads. In particular, PipeWire Rust objects are not generally Send/Sync; transfer commands and copied data, not handles. PipeWire Rust threading documentation

Pulse subscription notifications caused by the server's own confirmed writes retain their originating operation when their copied volume/mute state matches the expected echo. They remain observations, but must not masquerade as external edits and repeatedly re-arm a non-motorized fader during motion. A different observed state clears the echo expectation and remains an external change that re-arms pickup.

Use bounded mpsc for ordered work and watch for latest display snapshots. Keep button edges and lifecycle events separate from coalescible fader motion. A MIDI callback only parses/copies bounded input and tries to enqueue; on overflow set an explicit fault/resync flag rather than silently losing mute edges. A dropped button edge cannot be reconstructed from an audio snapshot: report the fault and require a new user press, never guess a toggle. Dedicate output workers to rate-limited MIDI feedback. Tokio synchronization primitives

The production audio dispatcher retains a bounded server-owned queue in front of a one-slot native worker command lane. Its independent event lane remains large enough for a complete startup snapshot; command backpressure must never shrink snapshot capacity. Replace unsent volume commands for the same stream with their newest value and explicitly supersede the older operation; never coalesce mute edges. A full non-coalescible queue or event lane is a visible fault, not permission to drop an action. Drain copied worker events in batches so native round-trip latency cannot starve MIDI input or local clients.

On shutdown stop accepting commands, stop callbacks, drain with deadlines, checkpoint confirmed state, close native connections, and join workers. Reconnect with bounded exponential backoff and cancellation; resnapshot before accepting writes. Keep other surfaces working when one disconnects. Stale backend/config generations cannot update current state.

Audio adapter selection and contract

Each adapter provides probe/connect, capabilities, subscribe-and-snapshot, set-volume, set-mute, readback, and shutdown through a command/event worker boundary. Events include ready, snapshot begin/end, stream upsert/remove, operation result, observed state, and disconnected. Missing metadata/capabilities must be explicit.

Subscribe before enumeration, buffer intervening events, and reconcile using an adapter-specific barrier/readback so a stream created or changed during enumeration is not lost. Pulse notifications may require fetching fresh stream info; events are not necessarily complete state. Repeated full snapshots replace state, rather than accumulating phantom streams.

Adapter Scope and selection
pulse First implementation. Enumerate playback sink inputs plus the current default output sink; read channel volumes/mute, change them, and subscribe to both stream and default-output changes. Supports PulseAudio and PipeWire's PulseAudio-compatible service. Native PipeWire-only stream coverage needs explicit testing; do not claim completeness.
pipewire Native playback stream discovery and SPA parameter control/observation. Implement after a spike proves writable parameters, correct linear gain/mute handling, metadata, and reconnect behavior with the active session manager.
alsa-mixer Optional explicit hardware mixer targets only; report playback switch/mute support per element. Reject application/group targets requiring application discovery. Never silently fall back to system Master volume.

adapter = "auto" probes enabled candidates with timeouts in configured preference order (initially pulse, then pipewire). Pick the first reachable backend satisfying required capabilities; retain it until disconnect or explicit reload. Use API connection/capability probes, not process names. Manual selection fails visibly if unavailable, with no fallback. An unbuilt backend yields an actionable feature error. Auto mode never activates two adapters on the same graph and excludes ALSA unless the profile explicitly requests hardware-only targets. Expose selected protocol, reported server identity, missing capabilities, and probe failures.

PulseAudio compatibility is provided by pipewire-pulse; ALSA's mixer API exposes mixer controls. The restriction of ALSA to hardware targets here is a design conclusion from that API model. PipeWire PulseAudio service, Pulse introspection, ALSA mixer interface

Multiple MIDI surfaces and feedback

Use midir for input/output connections. A device profile maps CC/note/pitch-bend messages to controls and output messages; v1 supports 7-bit absolute CC and note/CC mute buttons, then 14-bit pairs, pitch bend, and declared relative encoder dialects. Channel values in TOML are 1–16 and translate once at the transport boundary. Note-on velocity zero is release. Toggle actions fire on press only; validate malformed lengths and data bytes. Ignore unrelated clock/active-sensing traffic; arbitrary SysEx protocols are deferred.

Persist a user surface ID plus matching hints: backend port identifier where usable, input/output port names, USB VID/PID, serial when available, and optional physical path. MIDI port indices and names alone are not durable identity. On Linux, bridge midir's ALSA client:port through the sequencer client's card number to the udev sound/cardN device; user/virtual clients legitimately have no card. Match USB devices by serial first, physical ID_PATH second, and unique VID/PID/port-name last. Identical serial-less devices without a retained path require explicit current-port assignment and remain unresolved when ambiguous after topology changes. See the identity spike.

Keep bindings for absent surfaces. Re-enumerate ports on hotplug notifications or a bounded periodic scan, reconnect matching input/output ports independently, and resynchronize output from current observed state. Missing output does not disable input. Two devices may send the same channel/CC without collision because the surface ID is part of the key. midir input/connection API, udev discovery/monitoring

Output capabilities are explicit: mute LED, value display, motorized fader, or none. Non-motorized devices may still receive supported LED/display feedback; never assume every surface has LEDs. Mixed mute uses a declared mixed indicator, otherwise LED on only for all-muted and the TUI shows mixed. Send full supported state on attach and incremental changes thereafter. Device feedback failures are separate from audio operation failures.

Non-motorized absolute controls default to pickup: after startup, external changes, another surface's move, or profile switch, wait until the physical value crosses or enters a configured tolerance around the observed target before sending volume commands. First input establishes position; an out-of-range external volume uses the nearest physical endpoint. Relative encoders do not need pickup. Reset pickup on disconnect/rebind. For motors, add touch-aware inhibition before enabling motor output; unsupported touch means no claimed touch protection.

Avoid feedback loops with direction/origin tracking, quantization-aware equality, rate limiting, and device-specific echo suppression. MIDI has no universal request IDs: generic time-window byte suppression can swallow real input, so only enable it for documented echoing device profiles and test it. Server observations never themselves generate audio commands.

TOML configuration, persistence, and switching

All durable application data is TOML: profiles, device profiles/bindings, active profile selection, and last observed state and saved desired object values. Runtime sockets and log streams are not configuration stores. Use XDG config/state/runtime directories with validated ownership, falling back only according to the applicable XDG rules; do not put sockets in a shared predictable /tmp path.

  • ~/.config/fader_master/config.toml: schema version and selected profile.
  • ~/.config/fader_master/profiles/<id>.toml: adapter policy, applications, groups, surfaces, faders and bindings.
  • ~/.config/fader_master/devices/<id>.toml: reusable MIDI output/input protocol profiles when needed.
  • ~/.local/state/fader_master/state.toml: schema version, per-profile confirmed object/channel state and separately validated desired object volume/mute, remembered assignments, last selected UI view. No ephemeral backend handles or pending operation IDs; cached observations are marked stale until refreshed. Desired values may include commands issued offline, but are applied after restart only under explicit restore policy.

The following profile is parsed and semantically validated by an automated test and mirrored at examples/profiles/desktop.toml. Sample application and MIDI names must still be selected from actual discovery. CLI overrides apply for the session; persist them only on explicit Save.

schema_version = 1
id = "desktop"
startup = "adopt"
new_stream = "adopt"

[runtime]
poll_interval_ms = 10

[audio]
adapter = "auto"
preference = ["pulse", "pipewire"]
max_gain = 1.0

[[applications]]
id = "music"
label = "Music"
selectors = [{ field = "application.name", exact = "Music Player" }]

[[applications]]
id = "browser"
label = "Browser"
selectors = [{ field = "application.process.binary", regex = '^(firefox|chromium)$' }]

[[groups]]
id = "media"
label = "Media"
members = ["music", "browser"]
volume_mode = "absolute"

[[surfaces]]
id = "desk-left"
label = "Left controller"
input_port = "Example Controller MIDI 1"
output_port = "Example Controller MIDI 1"
identity_policy = "require_unique"
motorized = false

[[faders]]
id = "media-fader"
target = { kind = "group", id = "media" }
pickup = true
pickup_tolerance = 0.02

[[bindings]]
surface = "desk-left"
fader = "media-fader"
action = "volume"
message = { kind = "cc", channel = 1, number = 0 }

[[bindings]]
surface = "desk-left"
fader = "media-fader"
action = "toggle_mute"
edge = "press"
message = { kind = "note", channel = 1, number = 32 }
feedback = { kind = "note", channel = 1, number = 32, on = 127, off = 0 }

runtime.poll_interval_ms controls how long both the server state owner and the native audio worker may wait between MIDI/IPC/command/notification polls. It defaults to 10 ms when omitted and is validated within 1..=100. Lower values can reduce worst-case control latency at the cost of more wake-ups; higher values reduce wake-ups but make physical control and external-state updates less responsive. It does not change the bounded coalescing policy or cause every intermediate fader sample to be written.

Reject unknown schema versions/fields, duplicate IDs/physical bindings, dangling references, invalid matchers/ranges, unsupported capability requirements, and unsafe profile paths. Use forward migrations with backups; never downgrade silently. Validate the whole candidate before changing live mappings or files.

Write same-directory temporary files, flush/fsync, rename atomically, then sync the directory. Debounce state writes (initial target: 500 ms after changes, maximum 2 s between dirty checkpoints), flush on orderly shutdown, and document the corresponding crash-loss window. Permission/disk-full errors leave the old file usable and show an unsaved state. Preserve user comments in profile edits with toml_edit. The server is the sole writer; TUI edits carry a base revision and conflict if stale. Detect out-of-process file edits before saving rather than overwriting them.

Editor mutations are first applied to a cloned, comment-preserving document and the complete candidate profile is semantically validated before the draft is replaced. Invalid matchers, duplicate IDs, and referenced deletes therefore leave the prior draft unchanged. The v1 editor creates absolute groups; relative group controls remain a reserved future mode.

The live mixer revision and configuration-draft revision are independent. Draft edits are serialized by the server, require the caller's expected draft revision, and never mutate live routing or audio as a side effect. Successful draft edits are explicitly marked unsaved until a later apply/save command.

MIDI learn is scoped to one configured surface, logical fader, and action. While armed, messages from that surface are withheld from normal routing; unrelated surfaces continue normally. The first compatible CC or note press becomes a validated draft binding, while cancellation restores routing immediately.

Apply and Save are separate editor actions. Apply rebuilds profile-derived matching, groups, faders, pickup, and MIDI routing while retaining confirmed audio observations and issuing no audio write. Save first compares the exact on-disk bytes with the server's load/save baseline, then uses the atomic writer; conflicts or persistence failures retain both the previous file and dirty draft.

The implemented atomic writer checks that its parent and any existing target are owned by the effective user and are not symlinks. It creates mode-0600 temporary files in the destination directory, streams and syncs their content, renames over the destination, and syncs the parent directory. Application directories are mode 0700. Missing state and malformed readable state are distinct recoverable load outcomes; malformed bytes are retained for diagnosis. Profile migration accepts only versions below the current schema, validates the replacement first, and durably backs up the original bytes before replacement. Checkpoint changes are written after 500 ms without another change and at least every two seconds during sustained input, then flushed once more on orderly shutdown. A process or machine crash can therefore lose up to the latest unflushed interval; atomic replacement protects the preceding checkpoint. Revision conflict handling belongs to the server/editor boundary in M9.3.

Profile switch: parse/validate candidate, prepare/probe required resources without writes, pause input briefly, drain old writes with a deadline, obtain fresh state, then commit a new config generation and publish bindings/feedback together. Abort on prepare failure and retain the old profile. If an old in-flight call cannot be safely drained, close/reconnect and reconcile before activation; generation tags alone do not cancel native writes. In-flight group membership is fixed at command acceptance. Re-arm pickup, invalidate stale queued commands, and adopt live volumes by default. Persist the active profile pointer only after successful activation; disk failure leaves the active runtime profile clearly marked unsaved. Durable crash-atomic multi-file transactions are not claimed.

CLI, IPC, and TUI

Plan fader_master serve, tui, validate --config PATH, devices, status, and profile switch ID. Run one server per user/runtime namespace with an owned Unix socket and lock; TUI disconnect must not stop MIDI control. No network listener. Bound IPC message size and queue sizes, enforce socket permissions/peer identity, negotiate protocol version, use request IDs and revisioned snapshots, and resnapshot after missed deltas. Length-prefixed UTF-8 TOML messages reuse Serde schemas initially; cap frames before allocation.

The TUI owns blocking IPC on a joined background thread. Its render/input thread reads a shared local snapshot only, applies optimistic volume/mute changes, and queues work without waiting for a socket response. Pending volume work is latest-value-per-object; mute presses remain a bounded FIFO. Confirmed snapshots replace the local base and retain optimistic overlays until observation settles them. Poll quickly while writes are pending, slowly while idle, and resnapshot then retry once after a stale edit. Start immediately with a disconnected placeholder when the socket is absent, retain the last confirmed items across transport failures, surface the connection error inside the terminal, and keep retrying so starting or restarting the server reconnects without restarting the TUI.

Mixer-object snapshots also aggregate pickup state across configured physical volume bindings. They expose unavailable, waiting, tracking, or mixed; controls are instantiated from the profile before discovery so the first live observation can arm them without waiting for an initial MIDI packet.

The same client snapshot retains configured MIDI-device placeholders and their backend IDs/errors. The compact mixer status line distinguishes connected, connecting, missing, ambiguous, and failed devices, adding a connect/select action where the user can resolve the state.

Terminal restoration is guarded around all fallible client/run work after terminal initialization. The restore action is injectable for failure-path tests; client and transport diagnostics stay in the rendered status area rather than being printed over the alternate screen.

Terminal colors come from semantic theme palettes rather than renderer-local literals. The built-ins are Default, Dracula, Nord, Gruvbox Dark, Catppuccin Mocha, and Solarized Dark. tui --theme NAME selects the initial palette and t cycles themes for the current session; theme selection is presentation-only and is not persisted in the audio profile. Each palette defines background, foreground, accent/selection, secondary meter, muted, warning, error, and meter track colors so status meaning remains consistent across themes.

TUI tabs:

  • Mixer: faders, resolved applications/streams, volume, mute, mixed/offline/pending/errors, pickup status.
  • Editor: create/edit/delete application selectors, groups, faders, surface bindings, and MIDI learn; preview matches and conflicts. Draft changes do not affect audio; Validate, Apply, Save, Cancel are distinct. Referenced deletion requires reassignment or explicit cascade confirmation in the UI.
  • Devices / status: MIDI assignments and ambiguity resolution, manual/auto backend choice, capability/probe errors, active profile and persistence errors.

MIDI learn reserves the selected control and suppresses its normal action while learning. Save sends a revisioned request to the server; it never writes files from the TUI. Restore terminal state on errors and exit. Use logs away from the active terminal display.

Library research and choices

These are fit-for-purpose recommendations based on primary documentation, not benchmark winners. Recheck maintenance, API compatibility, license compatibility with this repository, MSRV, and native dependencies when implementing; pin resolved dependencies in Cargo.lock. Avoid upgrading the existing Ratatui dependency just to write this plan.

Concern Recommendation and tradeoff Primary source
USB MIDI midir 0.11.1 (MIT); owns input/output connections and uses ALSA on Linux. Prefer this to hand-written ALSA MIDI FFI; supplement persistent identity separately. It declares no MSRV, so the locked release is compiled in the Rust 1.88 gate. midir
Pulse protocol libpulse-binding; exposes asynchronous introspection/control. Keep callbacks on an owned loop. Prefer this to parsing pactl output; simple playback APIs do not provide the control plane. libpulse-binding
Native PipeWire Official pipewire Rust bindings; full native object access, with more SPA/graph complexity. Keep behind a feature and capability spike. pipewire-rs
Hardware mixer alsa for mixer controls and optional MIDI identity enrichment; feature-gated. No promise of application volume control. alsa::mixer
Async orchestration tokio, limited features for runtime/sync/time/net/signal; native loops remain dedicated threads. Prefer over building timers/IPC/cancellation manually. Tokio sync
TUI / events Keep ratatui plus its compatible crossterm; in-process test backend and terminal event support. Ratatui, Crossterm
Typed config serde + toml; toml_edit for preserving profile formatting/comments. Custom semantic validation is still necessary. Serde, toml, toml_edit
Matching regex, compiled at load; predictable supported syntax, no need for lookaround/backreferences. regex
Device metadata Optional udev; enumerate/monitor Linux devices. Does not itself solve MIDI-port-to-USB association. udev
CLI clap derive for typed subcommands/help. clap
Errors thiserror in libraries; anyhow at executable boundaries. thiserror, anyhow
Diagnostics tracing with a compatible subscriber for structured operation/backend/surface context; rate-limit noisy events. tracing
Tests / temporary files Standard Rust tests, proptest for conversion/reducer invariants, tempfile for filesystem fixtures and same-directory temp files; atomic durability still requires explicit sync. proptest, tempfile

Avoid CPAL/Rodio for this task: the needed boundary is an existing sound server's control plane, not a new playback engine. Avoid shelling out on every fader movement. Avoid a database, plugin ABI, web service, or scripting engine until an actual requirement justifies one.

Native build prerequisites to verify in CI: pkg-config and C toolchain; ALSA development files for Linux MIDI/mixer; libpulse development files for Pulse; PipeWire/SPA headers and any bindgen/libclang requirements of the selected binding release; libudev development files if enabled. Feature-specific builds must work without unrelated native libraries.

Verification and remaining design risks

Use deterministic fake adapters with reorderable events, failures, a fake clock, and a recorder of dispatched commands. Contract tests run against each audio implementation; real-daemon fixtures run in isolated sessions and never assume a developer's desktop can be modified. MIDI tests inject bytes and capture output; physical-device tests verify LED protocols and identity behavior separately. TUI uses a test backend and synthetic input. Benchmark sustained multi-surface fader traffic with bounded memory, eventual final-value delivery, and no starved mute events; set measured latency targets after the first working vertical slice.

Highest-risk spikes are native PipeWire stream control, conversion/channel semantics, serial-less device identity, snapshot races, and MIDI echo/motor protocols. Their acceptance tests are explicit in task.md. Shipping the Pulse vertical slice first reduces risk while preserving all adapter boundaries.