diff --git a/.github/workflows/opendeck.yml b/.github/workflows/opendeck.yml new file mode 100644 index 0000000..e84cad1 --- /dev/null +++ b/.github/workflows/opendeck.yml @@ -0,0 +1,105 @@ +name: OpenDeck plugin + +on: + workflow_call: + workflow_dispatch: + pull_request: + paths: + - 'integrations/opendeck/**' + - 'integrations/control-protocol/**' + - 'Cargo.toml' + - 'Cargo.lock' + - '.github/workflows/opendeck.yml' + - '.github/workflows/release.yml' + +permissions: + contents: read + +jobs: + build: + name: Plugin / ${{ matrix.target }} + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + target: x86_64-pc-windows-msvc + - os: ubuntu-latest + target: x86_64-unknown-linux-gnu + - os: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu + - os: macos-latest + target: aarch64-apple-darwin + - os: macos-15-intel + target: x86_64-apple-darwin + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + targets: ${{ matrix.target }} + - name: Check formatting + run: cargo fmt -p furumi-opendeck -- --check + - name: Test native renderer and simulated hosts + run: cargo test -p furumi-opendeck --all-targets --locked + - name: Test shared settings across action inspectors + run: node integrations/opendeck/tests/property-inspector.cjs + - name: Clippy + run: cargo clippy -p furumi-opendeck --all-targets --locked + - name: Build native plugin + run: cargo build -p furumi-opendeck --release --locked --target ${{ matrix.target }} + - name: Package + shell: pwsh + run: ./integrations/opendeck/package.ps1 -Target '${{ matrix.target }}' + - name: Upload native bundle + uses: actions/upload-artifact@v4 + with: + name: opendeck-native-${{ matrix.target }} + path: integrations/opendeck/dist/*.zip + if-no-files-found: error + - name: Render previews with the shipped renderer + shell: pwsh + run: | + $extension = if ($IsWindows) { '.exe' } else { '' } + & "./target/${{ matrix.target }}/release/furumi-opendeck$extension" --preview integrations/opendeck/preview + if ($LASTEXITCODE) { exit $LASTEXITCODE } + - uses: actions/upload-artifact@v4 + with: + name: opendeck-preview-${{ matrix.target }} + path: integrations/opendeck/preview/*.png + if-no-files-found: error + + package: + name: Package OpenDeck / ${{ matrix.platform }} + needs: build + runs-on: ubuntu-latest + strategy: + matrix: + include: + - platform: windows + targets: '*-windows-msvc' + - platform: macos + targets: '*-apple-darwin' + - platform: linux + targets: '*-linux-gnu' + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + pattern: opendeck-native-${{ matrix.targets }} + path: native + merge-multiple: true + - name: Assemble installable plugin + env: + PLATFORM: ${{ matrix.platform }} + run: | + set -euo pipefail + suffix="" + if [[ "$GITHUB_REF_TYPE" == tag ]]; then suffix="-${GITHUB_REF_NAME#v}"; fi + python3 integrations/opendeck/package_release.py "$PLATFORM" native "dist/furumi-opendeck-$PLATFORM$suffix.zip" + - uses: actions/upload-artifact@v4 + with: + name: furumi-opendeck-${{ matrix.platform }} + path: dist/*.zip + if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 220a8c6..c036260 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,9 @@ env: CARGO_NET_RETRY: 10 jobs: + build-opendeck: + uses: ./.github/workflows/opendeck.yml + build: name: Build ${{ matrix.asset_name }} runs-on: ${{ matrix.os }} @@ -48,7 +51,7 @@ jobs: run: cargo fetch --locked - name: Build - run: cargo build --release --locked --offline + run: cargo build -p furumi_tui --release --locked --offline - name: Package shell: bash @@ -81,7 +84,7 @@ jobs: concurrency: group: release-assets-${{ github.ref }} cancel-in-progress: false - needs: build + needs: [build, build-opendeck] runs-on: ubuntu-latest permissions: contents: write @@ -92,7 +95,9 @@ jobs: - name: Download build artifacts uses: actions/download-artifact@v4 with: + pattern: furumi-* path: artifacts + merge-multiple: true - name: Create release and upload assets env: @@ -101,7 +106,18 @@ jobs: run: | set -euo pipefail - archives=(artifacts/*/*) + version="${RELEASE_TAG#v}" + archives=( + "artifacts/furumi-linux-x86_64-$version.tar.gz" + "artifacts/furumi-macos-aarch64-$version.tar.gz" + "artifacts/furumi-windows-x86_64-$version.zip" + "artifacts/furumi-opendeck-windows-$version.zip" + "artifacts/furumi-opendeck-macos-$version.zip" + "artifacts/furumi-opendeck-linux-$version.zip" + ) + for archive in "${archives[@]}"; do + [[ -s "$archive" ]] || { echo "::error::Missing release archive $archive"; exit 1; } + done assets=$(mktemp) if ! gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' > "$assets"; then for archive in "${archives[@]}"; do diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index fdddab2..d1022e2 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -261,6 +261,16 @@ Active-device leases and idle timing prevent stale snapshots from immediately taking control after a device reconnects. This provides practical coordination without introducing a central playback arbiter. +A personal controller keeps its confirmed playback view separate from a +pending SetState request. It sends one playback change at a time and resumes +from the active output's latest report. Completion requires a newer heartbeat +in the same ownership term with the requested effect. For a transport change +both the playback state and the owner's output-playing flag must agree. +Furumi obtains this flag from its audio worker. A write failure, change of +owner or timeout ends the wait. The TUI and local control API expose the same +pending state. The existing device-sync command and announcement carry all +information used for this comparison. + ## Local application architecture Inside one node, Furumi uses an event-driven state machine: @@ -640,6 +650,27 @@ local storage or ranking. ## Persistence boundaries +### Device-local control surfaces + +`control.rs` serves authenticated native clients on loopback only; its shared +contract is independent of device-sync wire types. The OpenDeck plugin is +one such client and owns presentation and navigation, never library or +playback authority. Commands enter `AppEvent` and the ordinary playback +transitions/effects. Trusted-device transfer and Jam restrictions remain +owned by the existing runtime. + +The UI publishes in-memory snapshots through a latest-value channel; socket +I/O, endpoint discovery writes and image preparation happen outside the +interactive loop. Artwork references are opaque and restricted to the +current cover. The control endpoint is an optional local adapter, not a +coordinator or federation service, and losing it does not affect playback. + +An authenticated local spectrum subscription shares the same 31 bands +sampled for the status visualizer. One bounded latest-value channel feeds +all subscribers at up to 10 Hz during local output. A new stream epoch +invalidates accumulated history across seeks, track changes and handoffs. +The plugin composes the Infobar image locally. + Furumi stores different kinds of state according to their lifetime: | State | Storage | Role | diff --git a/Cargo.lock b/Cargo.lock index d1f6754..e353a73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -817,6 +817,15 @@ dependencies = [ "libc", ] +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "coreaudio-rs" version = "0.14.2" @@ -1143,7 +1152,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead" dependencies = [ "data-encoding", - "syn 1.0.109", + "syn 3.0.4", ] [[package]] @@ -1269,7 +1278,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1455,7 +1464,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1656,12 +1665,28 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "fontdue" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca" +dependencies = [ + "hashbrown 0.15.5", + "ttf-parser", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -1696,6 +1721,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "furumi-control-protocol" +version = "0.1.0" +dependencies = [ + "directories", + "serde", + "serde_json", +] + [[package]] name = "furumi-library" version = "0.4.0" @@ -1713,9 +1747,26 @@ dependencies = [ "tracing", ] +[[package]] +name = "furumi-opendeck" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64", + "fontdue", + "furumi-control-protocol", + "futures-util", + "image", + "serde", + "serde_json", + "tempfile", + "tokio", + "tokio-tungstenite", +] + [[package]] name = "furumi_tui" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "base64", @@ -1727,6 +1778,7 @@ dependencies = [ "directories", "flate2", "fs2", + "furumi-control-protocol", "furumi-library", "futures-util", "image", @@ -1734,6 +1786,7 @@ dependencies = [ "lofty", "music-dht", "object", + "rand 0.9.5", "ratatui", "reqwest 0.12.28", "rhai", @@ -1753,6 +1806,7 @@ dependencies = [ "tempfile", "thiserror 2.0.20", "tokio", + "tokio-tungstenite", "toml", "tracing", "tracing-subscriber", @@ -2036,6 +2090,17 @@ dependencies = [ "ahash", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -2044,7 +2109,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] @@ -2057,7 +2122,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", ] [[package]] @@ -3658,7 +3723,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3743,7 +3808,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -4541,7 +4606,7 @@ dependencies = [ "once_cell", "socket2 0.6.5", "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5057,7 +5122,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5115,7 +5180,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5929,7 +5994,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.4", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6179,6 +6244,18 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "tokio-tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -6615,6 +6692,32 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.20", + "utf-8", +] + [[package]] name = "typeid" version = "1.0.3" @@ -6717,6 +6820,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -7033,7 +7142,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9472bd4..22f9f49 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,16 +1,25 @@ [package] name = "furumi_tui" -version = "0.6.0" +version = "0.6.1" edition = "2024" rust-version = "1.97" description = "A federated P2P player for personal music libraries" license = "WTFPL" +[workspace] +members = ["integrations/control-protocol", "integrations/opendeck"] +default-members = [".", "integrations/control-protocol", "integrations/opendeck"] +resolver = "3" + [[bin]] name = "furumi" path = "src/main.rs" [dependencies] +furumi-control-protocol = { path = "integrations/control-protocol" } +base64 = "0.22.1" +rand = "0.9" +tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } semver = "1" self-replace = "1.5" @@ -49,7 +58,7 @@ sha2 = "0.10.9" souvlaki = { version = "0.8.3", default-features = false, features = ["use_zbus"] } symphonia = { version = "0.5.5", default-features = false, features = ["ogg"] } thiserror = "2.0.18" -tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util"] } +tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util", "net"] } toml = "1.1.2" tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } @@ -69,6 +78,3 @@ windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_UI_Wi [target."cfg(unix)".dependencies] libc = "0.2.186" - -[dev-dependencies] -base64 = "0.22.1" diff --git a/README.md b/README.md index 3300238..8770486 100644 --- a/README.md +++ b/README.md @@ -506,6 +506,21 @@ the TUI command adapter and web player hub, but does not start a browser or PostgreSQL and does not cover web database migrations. Both tests use temporary identities and data; no running player or user library is used. +## Stream Deck Neo / OpenDeck + +The native Rust [OpenDeck plugin](integrations/opendeck/README.md) provides +playback buttons, direct transfer to an online trusted device, a clean album +cover key opening Functions, similarity radio, role colors and a scrolling +Neo Infobar. Its shared settings offer a scrolling spectrogram or live frequency +bars for local audio, album art across four keys and role-colored icons on +black. It targets OpenDeck 2.14.2 on Windows, macOS and Linux. Download the +`furumi-opendeck` ZIP for your operating system alongside the player from +[GitHub Releases](https://github.com/Furumi-stack/furumi-tui/releases). + +The running player also accepts local commands such as `furumi ctl status`, +`furumi ctl play-pause`, `furumi ctl seek -10` and `furumi ctl transfer DEVICE_ID`. +See [local control](docs/local-control.md) for the JSON API and authority boundary. + ## License Furumi is released under the diff --git a/docs/local-control.md b/docs/local-control.md new file mode 100644 index 0000000..838ab9c --- /dev/null +++ b/docs/local-control.md @@ -0,0 +1,169 @@ +# Local player control + +Furumi exposes a versioned, authenticated WebSocket API to programs on the +same computer. It controls the running TUI; it does not start another audio +engine or grant membership to a device group. It is independent of the DHT +and remains available when federation is disabled. + +## Command line + +```sh +furumi ctl status +furumi ctl devices +furumi ctl watch +furumi ctl play-pause +furumi ctl previous +furumi ctl next +furumi ctl seek -10 +furumi ctl volume-up +furumi ctl volume-down +furumi ctl shuffle +furumi ctl repeat +furumi ctl radio +furumi ctl transfer DEVICE_ID +furumi ctl artwork --federation --output cover.png +``` + +Status, devices and command results are JSON. Watch emits one JSON snapshot +per line. Volume changes in five percentage-point steps. Seek is relative, +in seconds, bounded to one day per command. A missing or stopped player is an +error, not an instruction to start a second player. The existing +`--status` / `--status-json` exports remain unchanged. + +## Connection and authority + +The shared `furumi-control-protocol` crate defines the contract and +`discovery_path()`. The running player writes `control-endpoint.json` in +`directories::ProjectDirs::from("", "", "furumi").data_local_dir()`: + +```json +{"api_version":1,"port":12345,"token":"RANDOM_PER_PROCESS_TOKEN"} +``` + +The endpoint binds only to `127.0.0.1`, on an ephemeral port. Connect to +`ws://127.0.0.1:PORT` and send authentication as the first message: + +```json +{"type":"authenticate","api_version":1,"token":"RANDOM_PER_PROCESS_TOKEN"} +``` + +No metadata or commands are available before authentication. Browser Origin +headers are rejected. On Unix the discovery file has mode 0600; on Windows +it inherits the user's application-data directory permissions. Tokens must +never be included in logs or checked into a profile. A reconnect reads the +discovery file again; an old file after an abnormal exit grants no control +over a later process. Normal teardown removes the matching endpoint. + +## Messages + +The server sends `{"type":"snapshot","snapshot":{...}}` immediately after +authentication. It publishes playback updates at four Hz and sends a snapshot +immediately when a remote command changes state. Snapshots +include stopped/idle players, the local role, active output, online and +offline trusted devices, transfer eligibility, and optional current-track +metadata. Revoked devices are omitted. Item keys preserve episode identity; +numeric track IDs must not be used as episode identity. + +Commands carry an opaque unique request ID: + +```json +{"type":"command","id":"UNIQUE_REQUEST_ID","command":{"type":"seek","seconds":-10}} +{"type":"command","id":"ANOTHER_ID","command":{"type":"transfer","device_id":"TRUSTED_DEVICE_ID"}} +``` + +The result is `{"type":"result","id":"...","accepted":true,"error":null}`. +Accepted means dispatched by this player, **not** proof that a remote audio +engine started. Subsequent ownership snapshots report coordination state. +No audio-ready acknowledgement is invented. Local dispatch results are +deduplicated over the most recent 256 command IDs across client connections; +reusing an ID with another command is rejected. Clients should generate IDs +unique across restarts and avoid automatically replaying non-idempotent +commands after uncertain failures. + +In the personal Control role the controller keeps displaying the last +confirmed playback while an operation is in flight. The optional local +`remote_command` field contains a monotonically increasing per-session +`id`, a `state` (`idle`, `pending`, `confirmed` or `failed`) and an optional +English `error`. Confirmation means a fresh heartbeat from the selected +owner reports the requested effect. For pause or resume the owner's output +flag must agree with its transport state. Concurrent transport requests are +rejected while waiting. A write failure, ownership change or 15-second +timeout releases the controls. Clients can still navigate or switch devices. +Older local API servers omit this field. + +Transfers recheck trust, presence, Jam restrictions and podcast protocol +support. API transfers back to this computer preserve pause. Existing TUI +"play here" behavior is unchanged. Jam volume keeps its existing local +semantics. Commands use the same playback transitions/effects as media keys. + +## Artwork + +The optional track `artwork_id` is opaque. Request it with +`{"type":"command","id":"...","command":{"type":"artwork","artwork_id":"..."}}`. +The server returns an `artwork` message with the ID and optional `png_base64`. +The default lookup checks the current track and the local release library. +Passing `"federation":true` in the command, or `--federation` on the CLI, +also permits a lookup through the existing release-cover catalog request +when federation is enabled. Furumi tries the active output and known release +source first. Global library mode can additionally discover owners of the +release through the artist catalog. Private items and podcast metadata are +excluded from federated artwork lookup. + +The CLI returns a JSON artwork response or writes a 384 × 384 PNG to a new +file with `--output`. A missing cover has a null `png_base64`. The server +coalesces simultaneous lookups and keeps sending snapshots and processing +playback commands during a fetch. OpenDeck requests the image when a player +key displaying the cover is visible. Its cover button shows a loading +indicator, then the image or a neutral framed music note. The service accepts only opaque +references for the current track. + +## Local spectrum + +A server that supports audio levels advertises `"spectrum_supported":true` +in its normal snapshot. After authentication, a client can send +`{"type":"subscribe_spectrum","enabled":true}` and unsubscribe with +`"enabled":false`. The subscription belongs to that connection and ends +on disconnect. Clients should wait for the advertised capability before +subscribing to an older installation. + +A `spectrum` message contains `epoch`, `sequence` and `bands`. The 31 byte +values represent third-octave levels, ordered from 20 Hz to 20 kHz. Values +0–255 cover the analyzer's −60 to 0 dBFS display range. Subscribers receive +up to ten samples per second from local playback, including a local Jam host. +A pause freezes the history. A new epoch or null bands clears it after a +seek, track change, stop or handoff. Slow subscribers receive the latest +available sample. Normal playback snapshots retain their own cadence. + +## Similarity radio + +Radio uses the current music track as its seed and creates a temporary play +queue, without saving or editing a library playlist. Similarity must already +be enabled and the seed must have a local indexed embedding (a remote seed +is resolved by content ID against this computer's library). Podcast seeds +are rejected. Network queries respect the existing federation consent. + +The `radio` snapshot field has an operation `id`, a `state` +(`idle`, `searching`, `starting`, `playing`, `failed`) and an optional English +error. Local and federated candidates are collected asynchronously before +the queue is replaced. A bounded peer search is awaited; if peers fail but +local matches exist, radio can still play offline. Candidate ranking, +deduplication and artist diversity reuse the TUI similarity policy. + +Search failures, empty results, changed queues/outputs and stale operation +results leave the existing queue untouched. `starting` persists through +audio preparation; `playing` is emitted after a local audio Started event, +or an active output's matching playback report with advancing position. +The plugin animates the Radio key until that operation succeeds, then +returns to the main screen. Errors keep the Functions screen available. + +## OpenDeck + +The native Rust [OpenDeck integration](../integrations/opendeck/README.md) +targets Stream Deck Neo and OpenDeck 2.14.2 on Windows, macOS and Linux. +It renders eight 96 × 96 key images and a 248 × 58 Infobar, and maintains its +own player/device screens within one OpenDeck profile. + +The API limits connections, command queues, request IDs, message sizes, +authentication time and slow writes. A slow plugin cannot hold up terminal +rendering: snapshots use a latest-value watch channel. It has no authority +to pair, revoke or otherwise change trusted-device membership. diff --git a/integrations/control-protocol/Cargo.toml b/integrations/control-protocol/Cargo.toml new file mode 100644 index 0000000..7f85cc3 --- /dev/null +++ b/integrations/control-protocol/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "furumi-control-protocol" +version = "0.1.0" +edition = "2024" +rust-version = "1.97" +license = "WTFPL" + +[dependencies] +directories = "6" +serde = { version = "1", features = ["derive"] } + +[dev-dependencies] +serde_json = "1" diff --git a/integrations/control-protocol/src/lib.rs b/integrations/control-protocol/src/lib.rs new file mode 100644 index 0000000..4a33fa5 --- /dev/null +++ b/integrations/control-protocol/src/lib.rs @@ -0,0 +1,195 @@ +//! Versioned, device-local control API. This is not a device-sync wire protocol. +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +pub const API_VERSION: u16 = 1; +pub const MAX_MESSAGE_BYTES: usize = 2 * 1024 * 1024; +/// Third-octave levels, from 20 Hz to 20 kHz, quantized to 0..=255. +pub const SPECTRUM_BANDS: usize = 31; + +pub fn discovery_path() -> Option { + directories::ProjectDirs::from("", "", "furumi") + .map(|dirs| dirs.data_local_dir().join("control-endpoint.json")) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Discovery { + pub api_version: u16, + pub port: u16, + pub token: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Snapshot { + pub api_version: u16, + #[serde(default, skip_serializing_if = "is_false")] + pub spectrum_supported: bool, + pub revision: u64, + pub updated_at_ms: u64, + pub role: Role, + pub self_device_id: String, + pub active_device_id: Option, + pub active_device_name: Option, + pub playing: bool, + pub paused: bool, + pub position_secs: f64, + pub duration_secs: f64, + pub volume: u8, + pub shuffle: bool, + pub repeat: Repeat, + pub radio: Radio, + /// Optional for backward compatibility with local API servers predating + /// remote command acknowledgement. This is not a device-sync wire field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_command: Option, + pub track: Option, + pub devices: Vec, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Role { + Active, + Control, + Jam, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Repeat { + #[default] + Off, + All, + One, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct Radio { + pub id: u64, + pub state: RadioState, + pub error: Option, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum RadioState { + #[default] + Idle, + Searching, + Starting, + Playing, + Failed, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct RemoteCommand { + pub id: u64, + pub state: RemoteCommandState, + pub error: Option, +} + +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum RemoteCommandState { + #[default] + Idle, + Pending, + Confirmed, + Failed, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Track { + /// Stable playback identity, including podcast episodes (never a row ID). + pub key: String, + pub title: String, + pub artist: String, + pub album: String, + pub year: Option, + /// Opaque reference; clients cannot ask the server to read arbitrary paths. + pub artwork_id: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Device { + pub id: String, + pub name: String, + pub is_self: bool, + pub active: bool, + pub online: bool, + pub can_transfer: bool, + pub unavailable_reason: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ClientMessage { + Authenticate { + token: String, + api_version: u16, + }, + Command { + id: String, + command: Command, + }, + /// Local to this authenticated connection. Only request after the server + /// advertises spectrum_supported. + SubscribeSpectrum { + enabled: bool, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Command { + PlayPause, + Next, + Previous, + Seek { + seconds: i64, + }, + VolumeUp, + VolumeDown, + ToggleShuffle, + CycleRepeat, + StartRadio, + Transfer { + device_id: String, + }, + Artwork { + artwork_id: String, + #[serde(default, skip_serializing_if = "is_false")] + federation: bool, + }, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ServerMessage { + Snapshot { + snapshot: Box, + }, + /// A new epoch invalidates visual history. No bands means clear the display. + /// Only explicit subscribers receive this message. + Spectrum { + epoch: u64, + sequence: u64, + bands: Option<[u8; SPECTRUM_BANDS]>, + }, + /// `accepted` means dispatched locally, not acknowledged by a remote engine. + Result { + id: String, + accepted: bool, + error: Option, + }, + Artwork { + id: String, + artwork_id: String, + png_base64: Option, + }, +} diff --git a/integrations/opendeck/.gitignore b/integrations/opendeck/.gitignore new file mode 100644 index 0000000..a244039 --- /dev/null +++ b/integrations/opendeck/.gitignore @@ -0,0 +1,5 @@ +/.research-opendeck/ +/target/ +/dist/ +/dist-*/ +/preview/ diff --git a/integrations/opendeck/Cargo.toml b/integrations/opendeck/Cargo.toml new file mode 100644 index 0000000..6948cb3 --- /dev/null +++ b/integrations/opendeck/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "furumi-opendeck" +version = "0.1.0" +edition = "2024" +rust-version = "1.97" +license = "WTFPL" +description = "Native Rust Furumi control surface for OpenDeck and Stream Deck Neo" + +[dependencies] +anyhow = "1" +base64 = "0.22" +fontdue = "0.9" +furumi-control-protocol = { path = "../control-protocol" } +futures-util = "0.3" +image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tempfile = "3" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "fs"] } +tokio-tungstenite = "0.28" diff --git a/integrations/opendeck/README.md b/integrations/opendeck/README.md new file mode 100644 index 0000000..98aba40 --- /dev/null +++ b/integrations/opendeck/README.md @@ -0,0 +1,224 @@ +# Furumi for OpenDeck / Stream Deck Neo + +A native Rust plugin for **OpenDeck 2.14.2** on Windows, Linux and macOS. It +uses OpenAction's WebSocket protocol directly; no Node.js or USB access is +needed. OpenDeck owns the hardware and hosts the local settings inspector. + +## Install + +1. Download Furumi and the plugin ZIP for your operating system from the + [same release](https://github.com/Furumi-stack/furumi-tui/releases). +2. Start Furumi. OpenDeck discovers the running player automatically. +3. In OpenDeck Settings, choose **Open config directory**. Extract the + `org.furumi.opendeck.sdPlugin` folder into the `plugins` subdirectory and + restart OpenDeck. +4. Create a **Furumi** profile. Place **Furumi cell** on each of the eight LCD + keys and **Furumi now playing** on the Infobar. + +| Release asset | Included architectures | +| --- | --- | +| `furumi-opendeck-windows-.zip` | x86_64 | +| `furumi-opendeck-macos-.zip` | Intel and Apple Silicon | +| `furumi-opendeck-linux-.zip` | x86_64 and ARM64 (GNU) | + +OpenDeck selects the executable for the current architecture through +`CodePaths` in the bundled manifest. The release's `SHA256SUMS` includes all +three plugin archives. + +To build a package for your own machine, run +`cargo build -p furumi-opendeck --release --locked` and then +`pwsh -File integrations/opendeck/package.ps1` from the repository root. + +### Optional complete profile + +Instead of dragging nine actions, close OpenDeck and generate a **new** profile: + +```text +furumi-opendeck --write-profile sd-SERIAL /path/to/opendeck/config/profiles/sd-SERIAL/Furumi.json +``` + +Create the destination device directory first. Find the `sd-SERIAL` directory +in OpenDeck's existing `profiles` directory. The generator uses `create_new` +and refuses to overwrite an existing profile. It never edits your selected +profile or settings. Start OpenDeck and select Furumi. This is OpenDeck's JSON +profile format, not Elgato's `.streamDeckProfile` archive. + +On Windows invoke the packaged target-specific `.exe` (or +`target/debug/furumi-opendeck.exe` while developing). On macOS/Linux use `./` +and the corresponding target-specific executable. Use a native OpenDeck +installation initially; sandboxed Flatpak distributions may require access to +Furumi's data directory and localhost, which is not configured by this plugin. + +## Controls and screens + +| Album cover / Functions | Previous track | Play / pause | Next track | +| --- | --- | --- | --- | +| Cycle repeat | Toggle shuffle | Seek −10 seconds | Seek +30 seconds | + +All keys are authored at **96 × 96 px**. ACTIVE uses muted blue `#2b465a`, +CONTROL uses ochre `#524825` and JAM uses plum `#473451`. Phosphor Fill +icons use pale foregrounds on these dark backgrounds. The first key displays +the full release cover and opens Functions. A music-note icon appears when a cover +is unavailable. The Devices key inside Functions shows the role and current +audio owner. + +Functions has **Radio** at the top left, **Devices** beside it, and a compact back caret +at the bottom right. Other cells are blank. Radio starts Furumi's similarity +radio; its key shows an animated spinner while local/federation results are +collected and the first track is prepared. It returns to the player only for a +new radio operation that Furumi reports as actually playing, never merely on +command acceptance. A failed operation leaves an English error notice. Back +remains available while radio starts. Repeat cycles Off → All → One. Enabled +Repeat and Shuffle keys have a **4 px rounded border**, inset 4 px from the +edge. Repeat One also shows a `1` inside the loop. + +Devices opens a screen with six online trusted devices, a next-page key and a +back key. Each key shows the device's name at 16 px. Short names stay centered. +Long names scroll horizontally at 20 px/s and pause for two seconds at each +end. Opening a page starts each name at its beginning. The active output has +a blue background and check mark. An incompatible +target is dimmed; it cannot be selected. A press captures the device ID, so a +list update while the key is down cannot transfer to a different device. +Transfer is immediate, with no confirmation dialog. Pending transfer blocks +repeat commands, then returns to playback when Furumi reports the new owner. +That ownership report **does not prove that the remote audio engine has started**. +The local API currently acknowledges dispatch, not remote playback completion. +An explicit rejection or timeout appears temporarily in the Infobar. +Back from Devices returns to Functions. Navigation never changes the OpenDeck +profile or overwrites unrelated actions. + +Each physical deck has its own navigation and pressed-key state. Leaving the +profile removes its contexts. If Furumi exits, keys turn grey and the Infobar +shows **Furumi offline**. The plugin reconnects automatically and never +replays old commands across a disconnect. + +The Infobar is **248 × 58 px**, with content inset 8 px horizontally / 4 px +vertically. A 26 px metadata marquee runs on the left; elapsed time and duration +are fixed on the right, and a **6 px progress line** runs along the bottom. +Long podcast durations widen the time column instead of overlapping text. +The marquee pauses for two seconds and moves at 25 px/s. Metadata includes title, +artist, album and year. Updates are capped at 10 FPS, and unchanged key images +are not resent. Position is extrapolated only briefly between fresh snapshots. + +## Preview and tests + +```text +cargo run -p furumi-opendeck -- --preview integrations/opendeck/preview +cargo fmt -p furumi-opendeck -- --check +cargo check -p furumi-opendeck --all-targets +cargo test -p furumi-opendeck --all-targets +cargo clippy -p furumi-opendeck --all-targets +``` + +The preview command uses exactly the runtime renderer and writes native-size +buttons/Infobars, eight screen assemblies and sampled marquee frames. The synthetic +cover fixture is deliberately original and is not an included music album. Screen +assemblies are schematic; they do not claim measured millimetre positions for +the physical LCD windows. Tests include a temporary authenticated Furumi server +and a temporary OpenDeck WebSocket host, without audio, real profiles or peers. +Network sandboxes that block localhost connections must allow loopback for this +test. USB hardware and actual OpenDeck installation still require manual QA. + +## Remote playback confirmation + +In CONTROL mode, a pending remote playback command makes Play/Pause grey and +shows a small animated indicator in its bottom-right corner. The main glyph +continues to reflect the last confirmed playback state. Local API acceptance +means dispatch, not successful remote playback, and does not clear the indicator. + +The authoritative pending state also covers commands issued through Furumi's +keyboard or another local client. While it is pending, playback commands, +including radio, are blocked on both key press and release. Navigation and +device transfer remain available. The local latch is shared by all attached +decks, preventing rapid repeated commands before the next state snapshot. + +A new confirmed/failed operation, local rejection, owner change or disconnect +releases the corresponding local wait. A bounded 45-second fallback prevents a +broken acknowledgement stream from locking the plugin indefinitely. Failure +shows a short English notice. JAM behaviour is unchanged. Older local API +servers that omit `remote_command` retain their previous behaviour, without +waiting for an acknowledgement field they cannot publish. This optional field +belongs only to the local control API; no device-sync wire format was changed. + +## Artwork on demand + +The cover key has a neutral `#202a33` background, a thin rounded frame and an +original Phosphor Fill music-note icon when no cover is available. This is the +same in ACTIVE, CONTROL, JAM and offline mode. A separate animated loading badge +indicates an outstanding request. A successful cover is shown cleanly, without +icons, tint or labels. Pressing the key opens Functions even while artwork is +loading or missing; offline navigation is available too. + +Artwork is requested only when key0 is attached to a visible Player screen, +or a visible Previous/Repeat/Shuffle key needs its part of enabled 2×2 artwork. +A background plugin, an Infobar alone and the Functions/Devices screens +do not trigger federation requests. Returning to Player or attaching the key +after a snapshot rechecks demand. Requests use the additive local API flag +`federation: true`; the existing local API request defaults to local-only when +the flag is omitted. No personal-device synchronization protocol was changed. + +The request ID, artwork identity and playback generation must all match before +a reply is accepted, including A → B → A track changes. Missing artwork, +request rejection or a 35-second timeout restores the neutral key and does not +retry on each playback snapshot. Late artwork replies are ignored. Image loading +never blocks playback commands or clears a pending remote transport operation. + +The preview command also writes `artwork-states.png`, showing the neutral, +loading and ready states at their native 96×96 resolution. + +## Shared appearance settings + +Select any Furumi action in OpenDeck to open the same three global options. +Defaults preserve the plain Infobar and single cover key: + +- **Infobar background** offers **None**, **Spectrogram** and **Bars**. The + spectrogram scrolls behind the title. Bars displays 31 fixed frequency bands + with bass on the left and treble on the right. Both use blue and teal for the + middle of the audio level range and amber for peaks. They follow local output + at up to 10 Hz while the Infobar is visible. Control and Jam guests use the + plain background. A pause freezes the picture. Stop, seek, track changes and + output handoff clear it. Time and progress have a separate solid background. + Switching between the two visualizations keeps the current audio history. +- **2×2 album art:** spans the left four keys while retaining their bindings. + Previous sits at the upper right of its tile, Repeat at the lower left and + Shuffle at the lower right. Their 19 px glyphs have a thin contrasting + contour directly over the art. Enabled Repeat/Shuffle alone add a solid + role-accent corner triangle; Repeat One retains its numeral. The first tile + stays clean. Each 96 px crop starts at 0 or 130 in a 226 px square, skipping + 34 px (about 5 mm) of art along each axis. Previews show the measured 6 mm + gaps between the 14 mm key screens. The plugin prepares both cover sizes once + per image. +- **Invert colors:** black button and Infobar bases with muted blue, amber or + purple role accents. Menus, device selection and disabled states remain + distinct; release artwork is unchanged. + +Open inspectors stay synchronized. The Rust runtime serializes settings +patches, preserving unknown global fields rather than replacing the object. +Older saved OpenDeck profiles retain their old inspector path. With OpenDeck +closed, run `furumi-opendeck --upgrade-profile /path/to/Furumi.json` to add the +common inspector without changing bindings (a backup is made). Alternatively, +reassign one existing Furumi action to expose one settings entry point. + +`infobar-backgrounds.png` compares Spectrogram and Bars at native resolution for +three simulated audio samples. `appearance-options.png` shows the complete +deck. `album-2x2-layout.png` and `album-overlay-controls.png` show the cover +with physical key spacing and the different Repeat and Shuffle states. + +## Compatibility and license + +Verified against OpenDeck tag `v2.14.2`, commit +`3ddecc1ce8952a423916cf066724356267b97410`: `elgato.rs` handles the **Infobar** +controller via `setImage` with 248 × 58 image data. This deliberately does not +use newer Elgato SDK 3's **Neo** layout controller. Official Elgato software is +not a supported host for this version of the plugin. + +All interface labels and status messages are English. Track metadata and user +device names are displayed in their original language; the embedded font covers +Latin and Cyrillic without relying on OS-installed fonts. + +The plugin uses the WTFPL v2 license. Its embedded DejaVu Sans font provides +Latin and Cyrillic text on all three platforms. [Font license](assets/FONT-LICENSE.txt) + +The controls use Phosphor Fill under the MIT license. The plugin embeds masks +rasterized from the original SVGs. [Phosphor icons](https://github.com/phosphor-icons/core), +[icon license](assets/PHOSPHOR-LICENSE.txt) diff --git a/integrations/opendeck/assets/DejaVuSans.ttf b/integrations/opendeck/assets/DejaVuSans.ttf new file mode 100644 index 0000000..e5f7eec Binary files /dev/null and b/integrations/opendeck/assets/DejaVuSans.ttf differ diff --git a/integrations/opendeck/assets/FONT-LICENSE.txt b/integrations/opendeck/assets/FONT-LICENSE.txt new file mode 100644 index 0000000..8d71958 --- /dev/null +++ b/integrations/opendeck/assets/FONT-LICENSE.txt @@ -0,0 +1,187 @@ +Fonts are (c) Bitstream (see below). DejaVu changes are in public domain. +Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below) + + +Bitstream Vera Fonts Copyright +------------------------------ + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is +a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of the fonts accompanying this license ("Fonts") and associated +documentation files (the "Font Software"), to reproduce and distribute the +Font Software, including without limitation the rights to use, copy, merge, +publish, distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to the +following conditions: + +The above copyright and trademark notices and this permission notice shall +be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular +the designs of glyphs or characters in the Fonts may be modified and +additional glyphs or characters may be added to the Fonts, only if the fonts +are renamed to names not containing either the words "Bitstream" or the word +"Vera". + +This License becomes null and void to the extent applicable to Fonts or Font +Software that has been modified and is distributed under the "Bitstream +Vera" names. + +The Font Software may be sold as part of a larger software package but no +copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME +FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING +ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE +FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font Software +without prior written authorization from the Gnome Foundation or Bitstream +Inc., respectively. For further information, contact: fonts at gnome dot +org. + +Arev Fonts Copyright +------------------------------ + +Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the fonts accompanying this license ("Fonts") and +associated documentation files (the "Font Software"), to reproduce +and distribute the modifications to the Bitstream Vera Font Software, +including without limitation the rights to use, copy, merge, publish, +distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to +the following conditions: + +The above copyright and trademark notices and this permission notice +shall be included in all copies of one or more of the Font Software +typefaces. + +The Font Software may be modified, altered, or added to, and in +particular the designs of glyphs or characters in the Fonts may be +modified and additional glyphs or characters may be added to the +Fonts, only if the fonts are renamed to names not containing either +the words "Tavmjong Bah" or the word "Arev". + +This License becomes null and void to the extent applicable to Fonts +or Font Software that has been modified and is distributed under the +"Tavmjong Bah Arev" names. + +The Font Software may be sold as part of a larger software package but +no copy of one or more of the Font Software typefaces may be sold by +itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL +TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the name of Tavmjong Bah shall not +be used in advertising or otherwise to promote the sale, use or other +dealings in this Font Software without prior written authorization +from Tavmjong Bah. For further information, contact: tavmjong @ free +. fr. + +TeX Gyre DJV Math +----------------- +Fonts are (c) Bitstream (see below). DejaVu changes are in public domain. + +Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski +(on behalf of TeX users groups) are in public domain. + +Letters imported from Euler Fraktur from AMSfonts are (c) American +Mathematical Society (see below). +Bitstream Vera Fonts Copyright +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera +is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of the fonts accompanying this license (“Fonts”) and associated +documentation +files (the “Font Software”), to reproduce and distribute the Font Software, +including without limitation the rights to use, copy, merge, publish, +distribute, +and/or sell copies of the Font Software, and to permit persons to whom +the Font Software is furnished to do so, subject to the following +conditions: + +The above copyright and trademark notices and this permission notice +shall be +included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular +the designs of glyphs or characters in the Fonts may be modified and +additional +glyphs or characters may be added to the Fonts, only if the fonts are +renamed +to names not containing either the words “Bitstream” or the word “Vera”. + +This License becomes null and void to the extent applicable to Fonts or +Font Software +that has been modified and is distributed under the “Bitstream Vera” +names. + +The Font Software may be sold as part of a larger software package but +no copy +of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME +FOUNDATION +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, +SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN +ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR +INABILITY TO USE +THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. +Except as contained in this notice, the names of GNOME, the GNOME +Foundation, +and Bitstream Inc., shall not be used in advertising or otherwise to promote +the sale, use or other dealings in this Font Software without prior written +authorization from the GNOME Foundation or Bitstream Inc., respectively. +For further information, contact: fonts at gnome dot org. + +AMSFonts (v. 2.2) copyright + +The PostScript Type 1 implementation of the AMSFonts produced by and +previously distributed by Blue Sky Research and Y&Y, Inc. are now freely +available for general use. This has been accomplished through the +cooperation +of a consortium of scientific publishers with Blue Sky Research and Y&Y. +Members of this consortium include: + +Elsevier Science IBM Corporation Society for Industrial and Applied +Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS) + +In order to assure the authenticity of these fonts, copyright will be +held by +the American Mathematical Society. This is not meant to restrict in any way +the legitimate use of the fonts, such as (but not limited to) electronic +distribution of documents containing these fonts, inclusion of these fonts +into other public domain or commercial font collections or computer +applications, use of the outline data to create derivative fonts and/or +faces, etc. However, the AMS does require that the AMS copyright notice be +removed from any derivative versions of the fonts which have been altered in +any way. In addition, to ensure the fidelity of TeX documents using Computer +Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces, +has requested that any alterations which yield different font metrics be +given a different name. + +$Id$ diff --git a/integrations/opendeck/assets/PHOSPHOR-LICENSE.txt b/integrations/opendeck/assets/PHOSPHOR-LICENSE.txt new file mode 100644 index 0000000..78c9810 --- /dev/null +++ b/integrations/opendeck/assets/PHOSPHOR-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Phosphor Icons + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/integrations/opendeck/assets/icon.svg b/integrations/opendeck/assets/icon.svg new file mode 100644 index 0000000..161d151 --- /dev/null +++ b/integrations/opendeck/assets/icon.svg @@ -0,0 +1 @@ + diff --git a/integrations/opendeck/assets/icons/README.md b/integrations/opendeck/assets/icons/README.md new file mode 100644 index 0000000..e8587f0 --- /dev/null +++ b/integrations/opendeck/assets/icons/README.md @@ -0,0 +1,47 @@ +# Embedded Phosphor Fill icon atlas + +The Rust runtime decodes `phosphor-atlas.png` once and uses its alpha channel +as colourable masks. It does not require Node, an SVG parser, system icons or +network access. + +- `phosphor-fill/`: unmodified original SVGs from the official + [Phosphor core repository](https://github.com/phosphor-icons/core/tree/main/assets/fill). +- `phosphor-atlas.svg`: editable named elements at their production placement. +- `phosphor-atlas.json`: tile names, offsets, source URLs and original SHA-256. +- `../PHOSPHOR-LICENSE.txt`: unmodified MIT license for the source icons. +- `build-atlas.cjs`: optional authoring script, using **`@resvg/resvg-js` 2.6.2**. + That package is required only to regenerate the assets, not to build or run + the Rust plugin. + +Every tile is 96×96 pixels. Main glyph viewport: 56×56 centered at (48,48). +Seek viewport: 48×48 centered at (48,34). Radio/devices: 48×48 at (48,32). +Back: 36×36 caret-left at (48,48). Next page: 28×28 caret-right at (48,39). +Check/unavailable: 20×20 at (80,13). Spinner-gap: eight 45° rotations of the +original 48×48 Fill icon centered at (48,32). + +The missing-cover `Album` mask uses the original **music-note-simple-fill** +glyph. Its neutral frame is a separate 2 px `CoverFrame` mask. The loading badge +uses the same authentic Phosphor spinner as the transport acknowledgement UI. + +`EnabledFrame` is the only custom shape: a rounded 4px outline inset 4px from +every tile edge. Its outside corner radius is 10 px (centerline SVG radius 8 px). +The frame is an independent mask; the renderer chooses its colour and whether +it is shown. Phosphor glyph paths have not been redrawn or simplified. + +## Regenerate + +Install the pinned rasterizer in a separate authoring directory and make it +available through Node's standard `NODE_PATH`. From the repository root, using +PowerShell 7 on Windows, macOS or Linux: + +```powershell +npm install --prefix ./output/icon-authoring --no-audit --no-fund @resvg/resvg-js@2.6.2 +$env:NODE_PATH = (Resolve-Path ./output/icon-authoring/node_modules).Path +node ./integrations/opendeck/assets/icons/build-atlas.cjs +``` + +The script validates that every mask is nonempty, every spinner frame leaves +the label area clear, and the enabled frame retains its full four-pixel inset. +It writes the PNG, named SVG, JSON metadata and host launcher icon. Regeneration +with version 2.6.2 was checked to produce identical SHA-256 hashes for all four +outputs. Individual original SVG hashes are recorded in the generated JSON. diff --git a/integrations/opendeck/assets/icons/build-atlas.cjs b/integrations/opendeck/assets/icons/build-atlas.cjs new file mode 100644 index 0000000..332f33a --- /dev/null +++ b/integrations/opendeck/assets/icons/build-atlas.cjs @@ -0,0 +1,169 @@ +// Authoring tool only. The compiled Rust plugin has no SVG or Node dependency. +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { Resvg } = require('@resvg/resvg-js'); + +const tileSize = 96; +const columns = 8; +const atlasWidth = 768; +const atlasHeight = 384; + +// Enum order in src/icons.rs and atlas order must remain identical. +// Columns: name, Phosphor source name, viewport size, centre x, centre y. +const specs = [ + ['Previous', 'skip-back', 56, 48, 48], + ['Play', 'play', 56, 48, 48], + ['Pause', 'pause', 56, 48, 48], + ['Next', 'skip-forward', 56, 48, 48], + ['Repeat', 'repeat', 56, 48, 48], + ['RepeatOne', 'repeat-once', 56, 48, 48], + ['Shuffle', 'shuffle', 56, 48, 48], + ['Back', 'caret-left', 36, 48, 48], + ['SeekBack', 'rewind', 48, 48, 34], + ['SeekForward', 'fast-forward', 48, 48, 34], + ['Radio', 'radio', 48, 48, 32], + ['Devices', 'devices', 48, 48, 32], + ['NextPage', 'caret-right', 28, 48, 39], + ['Album', 'music-note-simple', 56, 48, 48], + ['Check', 'check', 20, 80, 13], + ['Unavailable', 'prohibit', 20, 80, 13], + ['CoverFrame', null, 0, 0, 0], + ['EnabledFrame', null, 0, 0, 0], +]; + +function glyph(name, size, centreX, centreY) { + const filename = path.join(__dirname, 'phosphor-fill', `${name}.svg`); + const original = fs.readFileSync(filename, 'utf8'); + + // Preserve the official paths. Only set viewport, placement and colour. + return original.replace(/]*)>/, (_, attributes) => { + const retained = attributes.replace( + /\s(?:width|height|x|y|color)="[^"]*"/g, + '', + ); + const x = centreX - size / 2; + const y = centreY - size / 2; + return ``; + }); +} + +const tiles = specs.map(([id, name, size, centreX, centreY]) => ({ + id, + // The frame is custom: 4 px outside inset, 4 px stroke, outside radius 10 px. + content: name + ? glyph(name, size, centreX, centreY) + : id === 'CoverFrame' + ? '' + : '', +})); + +for (let step = 0; step < 8; step++) { + tiles.push({ + id: `Spinner${step}`, + content: `${glyph('spinner-gap', 48, 48, 32)}`, + }); +} + +let svg = [ + '', + 'Furumi / Phosphor Fill alpha atlas', + '96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill SVG geometry. Custom enabled frame.', +].join(''); +const metadata = []; + +tiles.forEach((tile, index) => { + const x = (index % columns) * tileSize; + const y = Math.floor(index / columns) * tileSize; + svg += `${tile.content}`; + metadata.push({ name: tile.id, index, x, y, width: tileSize, height: tileSize }); +}); +svg += ''; + +const raster = new Resvg(svg).render(); +if (raster.width !== atlasWidth || raster.height !== atlasHeight) { + throw new Error('Unexpected atlas dimensions'); +} + +// Cache pixels once: the renderer's getter creates a fresh buffer each time. +const pixels = raster.pixels; +const alpha = (x, y) => pixels[(y * raster.width + x) * 4 + 3]; + +for (const tile of metadata) { + let visible = 0; + for (let y = 0; y < tileSize; y++) { + for (let x = 0; x < tileSize; x++) { + if (alpha(tile.x + x, tile.y + y)) visible++; + } + } + if (!visible) throw new Error(`Empty mask: ${tile.name}`); + + if (tile.name.startsWith('Spinner')) { + for (let y = 68; y < tileSize; y++) { + for (let x = 0; x < tileSize; x++) { + if (alpha(tile.x + x, tile.y + y)) { + throw new Error('Spinner overlaps label'); + } + } + } + } +} + +const frame = metadata.find(tile => tile.name === 'EnabledFrame'); +for (let position = 0; position < tileSize; position++) { + for (let inset = 0; inset < 4; inset++) { + const top = alpha(frame.x + position, frame.y + inset); + const bottom = alpha(frame.x + position, frame.y + 95 - inset); + const left = alpha(frame.x + inset, frame.y + position); + const right = alpha(frame.x + 95 - inset, frame.y + position); + if (top || bottom || left || right) { + throw new Error('Enabled frame violates 4px full inset'); + } + } +} + +const sourceDirectory = path.join(__dirname, 'phosphor-fill'); +const filenames = fs.readdirSync(sourceDirectory) + .filter(name => name.endsWith('.svg')) + .sort(); +const sources = filenames.map(filename => { + const data = fs.readFileSync(path.join(sourceDirectory, filename)); + const name = filename.slice(0, -4); + return { + file: `phosphor-fill/${filename}`, + url: `https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/${name}-fill.svg`, + sha256: crypto.createHash('sha256').update(data).digest('hex'), + }; +}); + +const atlasMetadata = { + width: atlasWidth, + height: atlasHeight, + tile_size: tileSize, + columns, + icons: metadata, + sources, + license: 'MIT', + license_file: '../PHOSPHOR-LICENSE.txt', +}; + +fs.writeFileSync(path.join(__dirname, 'phosphor-atlas.svg'), svg + '\n'); +fs.writeFileSync(path.join(__dirname, 'phosphor-atlas.png'), raster.asPng()); +fs.writeFileSync( + path.join(__dirname, 'phosphor-atlas.json'), + JSON.stringify(atlasMetadata, null, 2) + '\n', +); + +// The host-side launcher icon uses the same genuine Phosphor Play glyph. +const launcherGlyph = glyph('play', 56, 48, 48).replace( + 'color="white"', + 'color="#d0dce3"', +); +const launcher = [ + '', + '', + `${launcherGlyph}\n`, +].join(''); +fs.writeFileSync(path.join(__dirname, '../icon.svg'), launcher); + +console.log(`Generated ${tiles.length} named masks, 768×384 transparent atlas and host icon.`); diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.json b/integrations/opendeck/assets/icons/phosphor-atlas.json new file mode 100644 index 0000000..d9ece71 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-atlas.json @@ -0,0 +1,310 @@ +{ + "width": 768, + "height": 384, + "tile_size": 96, + "columns": 8, + "icons": [ + { + "name": "Previous", + "index": 0, + "x": 0, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "Play", + "index": 1, + "x": 96, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "Pause", + "index": 2, + "x": 192, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "Next", + "index": 3, + "x": 288, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "Repeat", + "index": 4, + "x": 384, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "RepeatOne", + "index": 5, + "x": 480, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "Shuffle", + "index": 6, + "x": 576, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "Back", + "index": 7, + "x": 672, + "y": 0, + "width": 96, + "height": 96 + }, + { + "name": "SeekBack", + "index": 8, + "x": 0, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "SeekForward", + "index": 9, + "x": 96, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "Radio", + "index": 10, + "x": 192, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "Devices", + "index": 11, + "x": 288, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "NextPage", + "index": 12, + "x": 384, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "Album", + "index": 13, + "x": 480, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "Check", + "index": 14, + "x": 576, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "Unavailable", + "index": 15, + "x": 672, + "y": 96, + "width": 96, + "height": 96 + }, + { + "name": "CoverFrame", + "index": 16, + "x": 0, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "EnabledFrame", + "index": 17, + "x": 96, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner0", + "index": 18, + "x": 192, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner1", + "index": 19, + "x": 288, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner2", + "index": 20, + "x": 384, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner3", + "index": 21, + "x": 480, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner4", + "index": 22, + "x": 576, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner5", + "index": 23, + "x": 672, + "y": 192, + "width": 96, + "height": 96 + }, + { + "name": "Spinner6", + "index": 24, + "x": 0, + "y": 288, + "width": 96, + "height": 96 + }, + { + "name": "Spinner7", + "index": 25, + "x": 96, + "y": 288, + "width": 96, + "height": 96 + } + ], + "sources": [ + { + "file": "phosphor-fill/caret-left.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/caret-left-fill.svg", + "sha256": "a6300d93ee3016043fe02af787421093bedd301a0da992337d07b16404e65fa5" + }, + { + "file": "phosphor-fill/caret-right.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/caret-right-fill.svg", + "sha256": "c62278a701f1e4c08f424ce4b5cac69c8adb23b496dae489d5545ea7e6c019ef" + }, + { + "file": "phosphor-fill/check.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/check-fill.svg", + "sha256": "d114007dc371976dc3e8f4ebc59c5aef429fae59ae58d56acdf231a52b4700be" + }, + { + "file": "phosphor-fill/devices.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/devices-fill.svg", + "sha256": "9198a600c051f27d61947e0d4558eb680f10fd0ff21147ce719c1cb0180c007f" + }, + { + "file": "phosphor-fill/fast-forward.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/fast-forward-fill.svg", + "sha256": "8be39d806d46384a635c53ffef51e9c19f91fcbb54901fc52c59ee290edbaf8b" + }, + { + "file": "phosphor-fill/music-note-simple.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/music-note-simple-fill.svg", + "sha256": "929c4c4c0c3213c914e59e54d261f020310fc77cb19776626f199db26fd7d81a" + }, + { + "file": "phosphor-fill/pause.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/pause-fill.svg", + "sha256": "156d3cdfa5cea803caec50b35f49bc635070c8bd84e7fe78df94b025017ccee1" + }, + { + "file": "phosphor-fill/play.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/play-fill.svg", + "sha256": "6d2a75bc5700a68dec50516ebae121c307807e4e6fcca5c863e5b4af006df880" + }, + { + "file": "phosphor-fill/prohibit.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/prohibit-fill.svg", + "sha256": "f4082e6bde36411618d4da65fe087cd3b746bb0e8070fec3d2e11b5aee059675" + }, + { + "file": "phosphor-fill/radio.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/radio-fill.svg", + "sha256": "7dda166865035ef1b9f38e667b54ae65add809f0fba7791961290fd566b2c68c" + }, + { + "file": "phosphor-fill/repeat-once.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/repeat-once-fill.svg", + "sha256": "6fe280758047324c9a7bc55b4b8291b5dca76082cc444351f52a650751d6a41c" + }, + { + "file": "phosphor-fill/repeat.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/repeat-fill.svg", + "sha256": "0ccdc4397cd7c1e528c571d6ba3fb6764043d791b3de0ac86c6eaf5edb3a8ce6" + }, + { + "file": "phosphor-fill/rewind.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/rewind-fill.svg", + "sha256": "beb5b9c00dcf99c2c7f0849ab17fe25ef4f1893aa02c71fb9876be0df743408d" + }, + { + "file": "phosphor-fill/shuffle.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/shuffle-fill.svg", + "sha256": "4e3b3d19192ae67ae051e06767e42f69cfb1f33c90c1c39d6387fe3ca55aa164" + }, + { + "file": "phosphor-fill/skip-back.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/skip-back-fill.svg", + "sha256": "65a2d664196ad28fff7288ed7a1870f508fdb922334ad1a49c54586dae7592d7" + }, + { + "file": "phosphor-fill/skip-forward.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/skip-forward-fill.svg", + "sha256": "2f13f5cbeab47627d30782e7942001e7f80f7da993df053d3be2b8c6cb737ae2" + }, + { + "file": "phosphor-fill/spinner-gap.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/spinner-gap-fill.svg", + "sha256": "6b13c6fe3926cfddf637e50ee92bc1d592369ee1d16e9e8b18e81fa3bc1ffbe8" + }, + { + "file": "phosphor-fill/vinyl-record.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/vinyl-record-fill.svg", + "sha256": "92552f12cb4dd696977bd7fe04e2a7d35f57fb5e265de8091a817d45433e2296" + } + ], + "license": "MIT", + "license_file": "../PHOSPHOR-LICENSE.txt" +} diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.png b/integrations/opendeck/assets/icons/phosphor-atlas.png new file mode 100644 index 0000000..602c81b Binary files /dev/null and b/integrations/opendeck/assets/icons/phosphor-atlas.png differ diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.svg b/integrations/opendeck/assets/icons/phosphor-atlas.svg new file mode 100644 index 0000000..78bff5f --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-atlas.svg @@ -0,0 +1 @@ +Furumi / Phosphor Fill alpha atlas96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill SVG geometry. Custom enabled frame. diff --git a/integrations/opendeck/assets/icons/phosphor-fill/caret-left.svg b/integrations/opendeck/assets/icons/phosphor-fill/caret-left.svg new file mode 100644 index 0000000..8fccd75 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/caret-left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/caret-right.svg b/integrations/opendeck/assets/icons/phosphor-fill/caret-right.svg new file mode 100644 index 0000000..41eaa04 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/caret-right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/check.svg b/integrations/opendeck/assets/icons/phosphor-fill/check.svg new file mode 100644 index 0000000..e5ec744 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/check.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/devices.svg b/integrations/opendeck/assets/icons/phosphor-fill/devices.svg new file mode 100644 index 0000000..461503a --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/devices.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/fast-forward.svg b/integrations/opendeck/assets/icons/phosphor-fill/fast-forward.svg new file mode 100644 index 0000000..bd8d593 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/fast-forward.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/music-note-simple.svg b/integrations/opendeck/assets/icons/phosphor-fill/music-note-simple.svg new file mode 100644 index 0000000..925333b --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/music-note-simple.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/pause.svg b/integrations/opendeck/assets/icons/phosphor-fill/pause.svg new file mode 100644 index 0000000..76bf51d --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/pause.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/play.svg b/integrations/opendeck/assets/icons/phosphor-fill/play.svg new file mode 100644 index 0000000..bf2bfb3 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/play.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/prohibit.svg b/integrations/opendeck/assets/icons/phosphor-fill/prohibit.svg new file mode 100644 index 0000000..b87a40c --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/prohibit.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/radio.svg b/integrations/opendeck/assets/icons/phosphor-fill/radio.svg new file mode 100644 index 0000000..9377fee --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/radio.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/repeat-once.svg b/integrations/opendeck/assets/icons/phosphor-fill/repeat-once.svg new file mode 100644 index 0000000..b86176b --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/repeat-once.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/repeat.svg b/integrations/opendeck/assets/icons/phosphor-fill/repeat.svg new file mode 100644 index 0000000..5c7996f --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/repeat.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/rewind.svg b/integrations/opendeck/assets/icons/phosphor-fill/rewind.svg new file mode 100644 index 0000000..7885f4d --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/rewind.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/shuffle.svg b/integrations/opendeck/assets/icons/phosphor-fill/shuffle.svg new file mode 100644 index 0000000..c2b17bc --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/shuffle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/skip-back.svg b/integrations/opendeck/assets/icons/phosphor-fill/skip-back.svg new file mode 100644 index 0000000..5dbd762 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/skip-back.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/skip-forward.svg b/integrations/opendeck/assets/icons/phosphor-fill/skip-forward.svg new file mode 100644 index 0000000..75f5f4d --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/skip-forward.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/spinner-gap.svg b/integrations/opendeck/assets/icons/phosphor-fill/spinner-gap.svg new file mode 100644 index 0000000..7ca5934 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/spinner-gap.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-fill/vinyl-record.svg b/integrations/opendeck/assets/icons/phosphor-fill/vinyl-record.svg new file mode 100644 index 0000000..e98b778 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/vinyl-record.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/manifest.json b/integrations/opendeck/assets/manifest.json new file mode 100644 index 0000000..3b25ca2 --- /dev/null +++ b/integrations/opendeck/assets/manifest.json @@ -0,0 +1,42 @@ +{ + "Name": "Furumi", + "Author": "Furumi contributors", + "Version": "0.1.0", + "Icon": "icon", + "Category": "Furumi", + "PropertyInspectorPath": "property-inspector.html", + "OS": [{ "Platform": "windows" }, { "Platform": "mac" }, { "Platform": "linux" }], + "CodePaths": { + "x86_64-pc-windows-msvc": "furumi-opendeck-x86_64-pc-windows-msvc.exe", + "x86_64-apple-darwin": "furumi-opendeck-x86_64-apple-darwin", + "aarch64-apple-darwin": "furumi-opendeck-aarch64-apple-darwin", + "x86_64-unknown-linux-gnu": "furumi-opendeck-x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu": "furumi-opendeck-aarch64-unknown-linux-gnu" + }, + "CodePathWin": "furumi-opendeck-x86_64-pc-windows-msvc.exe", + "CodePathMac": "furumi-opendeck-aarch64-apple-darwin", + "CodePathLin": "furumi-opendeck-x86_64-unknown-linux-gnu", + "Actions": [ + { + "UUID": "org.furumi.opendeck.cell", + "Name": "Furumi cell — fill the 8 Neo keys", + "Tooltip": "Place this action on all eight Neo keys. Position determines the function; the plugin switches player and device screens.", + "Icon": "icon", + "Controllers": ["Keypad"], + "PropertyInspectorPath": "property-inspector.html", + "SupportedInMultiActions": false, + "DisableAutomaticStates": true, + "States": [{ "Image": "icon", "ShowTitle": false }] + }, + { + "UUID": "org.furumi.opendeck.infobar", + "Name": "Furumi now playing — Neo Infobar", + "Tooltip": "248×58 now playing, scrolling metadata, fixed time and a 6-pixel progress line. OpenDeck 2.14.2 Infobar controller.", + "Icon": "icon", + "Controllers": ["Infobar"], + "PropertyInspectorPath": "property-inspector.html", + "SupportedInMultiActions": false, + "States": [{ "Image": "icon", "ShowTitle": false }] + } + ] +} diff --git a/integrations/opendeck/assets/property-inspector.html b/integrations/opendeck/assets/property-inspector.html new file mode 100644 index 0000000..4673529 --- /dev/null +++ b/integrations/opendeck/assets/property-inspector.html @@ -0,0 +1,35 @@ + + + + + + Furumi settings + + + + +

Furumi

+ + + + Applies to all Furumi keys and Infobars. Spectrogram and Bars use only audio playing on this computer. + Connecting to OpenDeck… + + diff --git a/integrations/opendeck/assets/property-inspector.js b/integrations/opendeck/assets/property-inspector.js new file mode 100644 index 0000000..92ea554 --- /dev/null +++ b/integrations/opendeck/assets/property-inspector.js @@ -0,0 +1,65 @@ +/* OpenDeck supplies this callback inside its local Property Inspector WebView. */ +/* No remote scripts, Node runtime, filesystem reads or player credentials. */ +'use strict'; + +let socket; +let inspectorContext; +let settings = {}; + +function send(event, payload) { + if (!socket || socket.readyState !== WebSocket.OPEN) return; + socket.send(JSON.stringify({ event, context: inspectorContext, ...(payload === undefined ? {} : { payload }) })); +} + +function elements() { + return { + background: document.getElementById('infobar-background'), + mosaic: document.getElementById('album-art-2x2'), + invert: document.getElementById('invert-colors'), + status: document.getElementById('status'), + }; +} + +function showSettings() { + const ui = elements(); + ui.background.value = ['none', 'spectrogram', 'bars'].includes(settings.infobar_background) ? settings.infobar_background : 'none'; + ui.mosaic.checked = settings.album_art_2x2 === true; + ui.invert.checked = settings.invert_colors === true; + for (const control of [ui.background, ui.mosaic, ui.invert]) control.disabled = false; +} + +function change(field, value) { + if (field === 'infobar_background' && !['none', 'spectrogram', 'bars'].includes(value)) return; + // The native runtime is the single writer. A patch cannot clobber another + // inspector's fields or settings owned by a newer version of the plugin. + send('sendToPlugin', { event: 'preferencesPatch', patch: { [field]: value } }); + elements().status.textContent = 'Saving…'; +} + +function connectElgatoStreamDeckSocket(port, uuid, registerEvent) { + inspectorContext = uuid; + socket = new WebSocket('ws://127.0.0.1:' + port); + socket.onopen = () => { + socket.send(JSON.stringify({ event: registerEvent, uuid })); + send('getGlobalSettings'); + }; + socket.onmessage = message => { + let event; + try { event = JSON.parse(message.data); } catch { return; } + if (event.event !== 'didReceiveGlobalSettings' && + !(event.event === 'sendToPropertyInspector' && event.payload?.event === 'preferencesState')) return; + const received = event.payload && event.payload.settings; + settings = received && typeof received === 'object' && !Array.isArray(received) ? { ...received } : {}; + elements().status.textContent = ''; + showSettings(); + }; + socket.onclose = () => { + const ui = elements(); + for (const control of [ui.background, ui.mosaic, ui.invert]) control.disabled = true; + ui.status.textContent = 'OpenDeck disconnected'; + }; + const ui = elements(); + ui.background.onchange = () => change('infobar_background', ui.background.value); + ui.mosaic.onchange = () => change('album_art_2x2', ui.mosaic.checked); + ui.invert.onchange = () => change('invert_colors', ui.invert.checked); +} diff --git a/integrations/opendeck/package.ps1 b/integrations/opendeck/package.ps1 new file mode 100644 index 0000000..1c84fd9 --- /dev/null +++ b/integrations/opendeck/package.ps1 @@ -0,0 +1,37 @@ +param( + [string]$Target = '', + [string]$BuildProfile = 'release', + [string]$OutputDirectory = "$PSScriptRoot/dist" +) +$ErrorActionPreference = 'Stop' +$repo = (Resolve-Path "$PSScriptRoot/../..").Path +if (!$Target) { + $hostLine = & rustc -vV | Select-String '^host: ' + $Target = $hostLine.ToString().Substring(6).Trim() + $binaryDirectory = Join-Path $repo "target/$BuildProfile" +} else { + $binaryDirectory = Join-Path $repo "target/$Target/$BuildProfile" +} +$extension = if ($Target -like '*windows*') { '.exe' } else { '' } +$binary = Join-Path $binaryDirectory "furumi-opendeck$extension" +if (!(Test-Path -LiteralPath $binary)) { throw "Build the plugin first; missing $binary" } +$bundle = Join-Path $OutputDirectory 'org.furumi.opendeck.sdPlugin' +$binaryName = "furumi-opendeck-$Target$extension" +if (Test-Path -LiteralPath $bundle) { + $packageFiles = @($binaryName, 'manifest.json', 'icon.svg', 'property-inspector.html', 'property-inspector.js', 'FONT-LICENSE.txt', 'PHOSPHOR-LICENSE.txt', 'README.md', 'LICENSE') + $extra = Get-ChildItem -LiteralPath $bundle -Force | Where-Object { $_.PSIsContainer -or $_.Name -notin $packageFiles } + if ($extra) { throw "The output bundle contains additional files. Choose a separate OutputDirectory: $bundle" } +} +New-Item -ItemType Directory -Force -Path $bundle | Out-Null +Copy-Item -LiteralPath $binary -Destination (Join-Path $bundle $binaryName) +Copy-Item -LiteralPath "$PSScriptRoot/assets/manifest.json" -Destination $bundle +Copy-Item -LiteralPath "$PSScriptRoot/assets/icon.svg" -Destination $bundle +Copy-Item -LiteralPath "$PSScriptRoot/assets/property-inspector.html" -Destination $bundle +Copy-Item -LiteralPath "$PSScriptRoot/assets/property-inspector.js" -Destination $bundle +Copy-Item -LiteralPath "$PSScriptRoot/assets/FONT-LICENSE.txt" -Destination $bundle +Copy-Item -LiteralPath "$PSScriptRoot/assets/PHOSPHOR-LICENSE.txt" -Destination $bundle +Copy-Item -LiteralPath "$PSScriptRoot/README.md" -Destination $bundle +Copy-Item -LiteralPath "$repo/LICENSE" -Destination $bundle +$archive = Join-Path $OutputDirectory "furumi-opendeck-$Target.zip" +Compress-Archive -LiteralPath $bundle -DestinationPath $archive -Force +Write-Output $archive diff --git a/integrations/opendeck/package_release.py b/integrations/opendeck/package_release.py new file mode 100644 index 0000000..88dcc98 --- /dev/null +++ b/integrations/opendeck/package_release.py @@ -0,0 +1,65 @@ +"""Combine the native OpenDeck bundles for one OS into an installable ZIP.""" + +import argparse +import json +import stat +from pathlib import Path +from tempfile import TemporaryDirectory +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + + +BUNDLE = "org.furumi.opendeck.sdPlugin/" +TARGET_SUFFIX = { + "windows": "-windows-msvc", + "macos": "-apple-darwin", + "linux": "-linux-gnu", +} + + +def assemble(platform: str, inputs: Path, output: Path) -> None: + manifest = json.loads((Path(__file__).parent / "assets/manifest.json").read_bytes()) + programs = {} + resources = None + for target, executable in manifest["CodePaths"].items(): + if not target.endswith(TARGET_SUFFIX[platform]): + continue + source = inputs / f"furumi-opendeck-{target}.zip" + with ZipFile(source) as archive: + files = { + entry.filename: archive.read(entry) + for entry in archive.infolist() + if not entry.is_dir() + } + if json.loads(files[BUNDLE + "manifest.json"]) != manifest: + raise ValueError(f"{source} was built with a different plugin manifest") + program = BUNDLE + executable + programs[program] = files.pop(program) + if not programs[program]: + raise ValueError(f"Empty executable in {source}: {executable}") + if resources is None: + resources = files + elif files != resources: + raise ValueError(f"Shared plugin resources differ in {source}") + + if resources is None: + raise ValueError(f"No {platform} executables in the plugin manifest") + output.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=output.parent) as staging: + staged = Path(staging) / output.name + with ZipFile(staged, "w") as archive: + for name, data in sorted((resources | programs).items()): + entry = ZipInfo(name) + entry.create_system = 3 # Record Unix permissions regardless of the build host. + mode = 0o755 if name in programs else 0o644 + entry.external_attr = (stat.S_IFREG | mode) << 16 + archive.writestr(entry, data, compress_type=ZIP_DEFLATED) + staged.replace(output) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("platform", choices=TARGET_SUFFIX) + parser.add_argument("inputs", type=Path, help="Directory containing native plugin ZIPs") + parser.add_argument("output", type=Path, help="Path of the resulting platform ZIP") + args = parser.parse_args() + assemble(args.platform, args.inputs, args.output) diff --git a/integrations/opendeck/src/artwork.rs b/integrations/opendeck/src/artwork.rs new file mode 100644 index 0000000..e91218e --- /dev/null +++ b/integrations/opendeck/src/artwork.rs @@ -0,0 +1,268 @@ +//! Demand-driven cover state. A request is scoped to a playback generation, +//! including A → B → A, and can never revive an image from an older request. +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use furumi_control_protocol::Snapshot; +use image::RgbImage; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(35); +pub const KEY_PIXELS: u32 = 96; +// A 6 mm gap corresponds to 41 pixels on a 14 mm, 96-pixel key. +pub const GAP_PX: u32 = 41; +pub const KEY_STRIDE: u32 = KEY_PIXELS + GAP_PX; +pub const PHYSICAL_MOSAIC_SIZE: u32 = KEY_PIXELS * 2 + GAP_PX; +// Trim slightly less art than the physical 6 mm spacers: about 5 mm per axis. +pub const ART_GAP_PX: u32 = 34; +pub const ART_STRIDE: u32 = KEY_PIXELS + ART_GAP_PX; +pub const MOSAIC_SIZE: u32 = KEY_PIXELS * 2 + ART_GAP_PX; + +/// Both cover sizes share the lifetime of a single artwork response. +pub struct PreparedArt { + small: RgbImage, + square: RgbImage, +} + +pub struct CoverReply { + pub request_id: String, + pub artwork_id: String, + pub image: T, +} + +impl CoverReply { + /// Decode and resize on the image worker while the keys continue to accept input. + pub fn prepare(self) -> CoverReply> { + let image = decode_png(&self.image).map(PreparedArt::new); + CoverReply { + request_id: self.request_id, + artwork_id: self.artwork_id, + image, + } + } +} + +fn decode_png(encoded: &str) -> Option { + let bytes = base64::engine::general_purpose::STANDARD + .decode(encoded) + .ok()?; + let mut reader = + image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(2048); + limits.max_image_height = Some(2048); + limits.max_alloc = Some(32 * 1024 * 1024); + reader.limits(limits); + reader.decode().ok().map(|image| image.into_rgb8()) +} + +impl PreparedArt { + pub fn new(image: RgbImage) -> Self { + let side = image.width().min(image.height()); + let square = image::imageops::crop_imm( + &image, + (image.width() - side) / 2, + (image.height() - side) / 2, + side, + side, + ); + Self { + small: image::imageops::resize( + &*square, + KEY_PIXELS, + KEY_PIXELS, + image::imageops::FilterType::Lanczos3, + ), + square: image::imageops::resize( + &*square, + MOSAIC_SIZE, + MOSAIC_SIZE, + image::imageops::FilterType::Lanczos3, + ), + } + } + pub fn small(&self) -> &RgbImage { + &self.small + } + pub fn square(&self) -> &RgbImage { + &self.square + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Identity { + track_key: String, + artwork_id: Option, +} + +#[derive(Debug)] +struct Pending { + request_id: String, + artwork_id: String, + generation: u64, + started: Instant, +} + +#[derive(Default)] +pub struct Artwork { + identity: Option, + generation: u64, + pending: Option, + terminal: bool, + image: Option, +} + +impl Artwork { + pub fn observe(&mut self, snapshot: Option<&Snapshot>) { + let identity = snapshot + .and_then(|s| s.track.as_ref()) + .map(|track| Identity { + track_key: track.key.clone(), + artwork_id: track.artwork_id.clone(), + }); + if identity != self.identity { + self.identity = identity; + self.generation = self.generation.wrapping_add(1); + self.pending = None; + self.terminal = false; + self.image = None; + } + } + + pub fn needed(&self, visible: bool) -> Option { + if !visible || self.terminal || self.pending.is_some() { + return None; + } + self.identity.as_ref()?.artwork_id.clone() + } + + pub fn begin(&mut self, request_id: String, artwork_id: String, now: Instant) { + self.pending = Some(Pending { + request_id, + artwork_id, + generation: self.generation, + started: now, + }); + } + + pub fn matches(&self, id: &str, artwork_id: &str) -> bool { + self.pending.as_ref().is_some_and(|p| { + p.request_id == id && p.artwork_id == artwork_id && p.generation == self.generation + }) + } + + pub fn complete(&mut self, id: &str, artwork_id: &str, image: Option) { + if !self.matches(id, artwork_id) { + return; + } + self.pending = None; + self.terminal = true; + self.image = image; + } + + pub fn reject(&mut self, id: &str) { + if self.pending.as_ref().is_some_and(|p| p.request_id == id) { + self.pending = None; + self.terminal = true; + self.image = None; + } + } + + pub fn expire(&mut self, now: Instant) { + if self + .pending + .as_ref() + .is_some_and(|p| now.saturating_duration_since(p.started) >= REQUEST_TIMEOUT) + { + self.pending = None; + self.terminal = true; + self.image = None; + } + } + + pub fn loading(&self) -> Option { + self.pending.as_ref().map(|p| p.started) + } + #[cfg(test)] + pub fn image(&self) -> Option<&RgbImage> { + self.image.as_ref().map(PreparedArt::small) + } + pub fn prepared(&self) -> Option<&PreparedArt> { + self.image.as_ref() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::preview::fixture; + + #[test] + fn no_request_without_visible_cover_and_missing_is_terminal_for_this_generation() { + let mut s = fixture(); + s.track.as_mut().unwrap().artwork_id = Some("art-A".into()); + let mut art = Artwork::default(); + art.observe(Some(&s)); + assert_eq!(art.needed(false), None); + assert_eq!(art.needed(true), Some("art-A".into())); + art.begin("request-A".into(), "art-A".into(), Instant::now()); + assert!(art.loading().is_some()); + art.complete("request-A", "art-A", None); + assert!(art.image().is_none()); + assert!(art.loading().is_none()); + assert_eq!(art.needed(true), None); + art.observe(Some(&s)); + assert_eq!(art.needed(true), None); + } + + #[test] + fn returning_to_same_artwork_rejects_the_first_a_response_by_request_id() { + let now = Instant::now(); + let mut s = fixture(); + s.track.as_mut().unwrap().artwork_id = Some("same-cover".into()); + let mut art = Artwork::default(); + art.observe(Some(&s)); + art.begin("A-first".into(), "same-cover".into(), now); + let original_key = s.track.as_ref().unwrap().key.clone(); + s.track.as_mut().unwrap().key = "B".into(); + art.observe(Some(&s)); + s.track.as_mut().unwrap().key = original_key; + art.observe(Some(&s)); + art.begin("A-new".into(), "same-cover".into(), now); + let image = RgbImage::new(96, 96); + art.complete( + "A-first", + "same-cover", + Some(PreparedArt::new(image.clone())), + ); + assert!(art.image().is_none()); + assert!(art.loading().is_some()); + art.complete("A-new", "same-cover", Some(PreparedArt::new(image.clone()))); + assert_eq!(art.image(), Some(&image)); + } + + #[test] + fn timeout_and_reject_clear_loading_without_retry_or_late_image() { + let now = Instant::now(); + let mut s = fixture(); + s.track.as_mut().unwrap().artwork_id = Some("art".into()); + let mut art = Artwork::default(); + art.observe(Some(&s)); + art.begin("timeout".into(), "art".into(), now); + art.expire(now + REQUEST_TIMEOUT); + art.complete( + "timeout", + "art", + Some(PreparedArt::new(RgbImage::new(96, 96))), + ); + assert!(art.image().is_none()); + assert_eq!(art.needed(true), None); + s.track.as_mut().unwrap().key = "next".into(); + art.observe(Some(&s)); + art.begin("rejected".into(), "art".into(), now); + art.reject("other"); + assert!(art.loading().is_some()); + art.reject("rejected"); + assert!(art.loading().is_none()); + assert_eq!(art.needed(true), None); + } +} diff --git a/integrations/opendeck/src/client.rs b/integrations/opendeck/src/client.rs new file mode 100644 index 0000000..26edda1 --- /dev/null +++ b/integrations/opendeck/src/client.rs @@ -0,0 +1,166 @@ +//! Reconnecting authenticated local client. Commands are never replayed across +//! disconnects: a non-idempotent PlayPause must not become a second toggle. +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use furumi_control_protocol::{ + API_VERSION, ClientMessage, Discovery, MAX_MESSAGE_BYTES, ServerMessage, discovery_path, +}; +use futures_util::{SinkExt, StreamExt}; +use tokio::sync::{mpsc, watch}; +use tokio_tungstenite::tungstenite::{Message, protocol::WebSocketConfig}; + +#[derive(Debug)] +pub enum Update { + Message(Box), + Disconnected, +} + +pub async fn run( + mut commands: mpsc::Receiver, + updates: mpsc::Sender, + endpoint_path: Option, + spectrum: watch::Sender>, +) { + loop { + while commands.try_recv().is_ok() {} + if updates.is_closed() { + return; + } + let _ = session(&mut commands, &updates, endpoint_path.clone(), &spectrum).await; + spectrum.send_replace(None); + if updates.send(Update::Disconnected).await.is_err() { + return; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + +async fn session( + commands: &mut mpsc::Receiver, + updates: &mpsc::Sender, + endpoint_path: Option, + spectrum: &watch::Sender>, +) -> Result<()> { + let path = endpoint_path + .or_else(discovery_path) + .context("Furumi data directory unavailable")?; + let bytes = tokio::fs::read(path).await?; + if bytes.len() > 4096 { + bail!("invalid discovery size"); + } + let endpoint: Discovery = serde_json::from_slice(&bytes)?; + if endpoint.api_version != API_VERSION || endpoint.port == 0 { + bail!("unsupported local API version"); + } + let config = WebSocketConfig::default() + .max_message_size(Some(MAX_MESSAGE_BYTES)) + .max_frame_size(Some(MAX_MESSAGE_BYTES)); + let (mut socket, _) = tokio::time::timeout( + Duration::from_secs(3), + tokio_tungstenite::connect_async_with_config( + format!("ws://127.0.0.1:{}", endpoint.port), + Some(config), + false, + ), + ) + .await??; + socket + .send(Message::text(serde_json::to_string( + &ClientMessage::Authenticate { + token: endpoint.token, + api_version: API_VERSION, + }, + )?)) + .await?; + // Only a valid snapshot establishes the authenticated session. + let first = tokio::time::timeout(Duration::from_secs(3), socket.next()) + .await? + .context("Furumi disconnected")??; + let message: ServerMessage = serde_json::from_slice(&first.into_data())?; + if !matches!(&message,ServerMessage::Snapshot{snapshot} if snapshot.api_version==API_VERSION) { + bail!("missing initial snapshot"); + } + updates.send(Update::Message(Box::new(message))).await?; + loop { + tokio::select! { + item=tokio::time::timeout(Duration::from_secs(4),socket.next()) => { + let message=item?.context("Furumi disconnected")??; + match message { + Message::Text(text)=> { + let message=serde_json::from_str(&text)?; + forward(message,updates,spectrum).await?; + }, + Message::Close(_)=>return Ok(()), + Message::Ping(data)=> {socket.send(Message::Pong(data)).await?;}, + _=>{} + } + } + command=commands.recv()=> { + let Some(command)=command else{return Ok(())}; + tokio::time::timeout(Duration::from_secs(2),socket.send(Message::text(serde_json::to_string(&command)?))).await??; + } + } + } +} + +async fn forward( + message: ServerMessage, + updates: &mpsc::Sender, + spectrum: &watch::Sender>, +) -> Result<()> { + match message { + ServerMessage::Spectrum { + epoch, + sequence, + bands, + } => { + spectrum.send_replace(Some(crate::spectrum::Frame { + epoch, + sequence, + bands, + })); + } + message => updates.send(Update::Message(Box::new(message))).await?, + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn spectrum_bursts_replace_latest_instead_of_queuing_before_command_results() { + let (updates, mut receiver) = mpsc::channel(1); + let (spectrum, latest) = watch::channel(None); + for sequence in 1..=1000 { + forward( + ServerMessage::Spectrum { + epoch: 1, + sequence, + bands: Some([99; 31]), + }, + &updates, + &spectrum, + ) + .await + .unwrap(); + } + forward( + ServerMessage::Result { + id: "transport".into(), + accepted: true, + error: None, + }, + &updates, + &spectrum, + ) + .await + .unwrap(); + assert!( + matches!(receiver.recv().await,Some(Update::Message(message)) if matches!(*message,ServerMessage::Result{..})) + ); + assert_eq!(latest.borrow().as_ref().unwrap().sequence, 1000); + } +} diff --git a/integrations/opendeck/src/host.rs b/integrations/opendeck/src/host.rs new file mode 100644 index 0000000..ecf2a6f --- /dev/null +++ b/integrations/opendeck/src/host.rs @@ -0,0 +1,141 @@ +//! Minimal OpenAction WebSocket adapter, checked against OpenDeck v2.14.2. +//! In that version the Neo controller is "Infobar", not Elgato SDK 3's "Neo". +use std::collections::BTreeMap; + +use anyhow::{Context, Result, bail}; +use serde::Deserialize; +use serde_json::{Value, json}; + +pub const PLUGIN: &str = "org.furumi.opendeck.sdPlugin"; +pub const CELL: &str = "org.furumi.opendeck.cell"; +pub const INFOBAR: &str = "org.furumi.opendeck.infobar"; +pub const PROFILE_INSPECTOR: &str = "plugins/org.furumi.opendeck.sdPlugin/property-inspector.html"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Instance { + pub context: String, + pub device: String, + pub slot: Option, +} + +#[derive(Debug, Deserialize)] +pub struct Event { + pub event: String, + #[serde(default)] + pub action: String, + #[serde(default)] + pub context: String, + #[serde(default)] + pub device: String, + #[serde(default)] + pub payload: Value, +} + +impl Event { + pub fn instance(&self) -> Option { + if self.payload["isInMultiAction"].as_bool() == Some(true) { + return None; + } + let controller = self.payload["controller"].as_str()?; + let slot = match (self.action.as_str(), controller) { + (CELL, "Keypad") => { + let row = self.payload["coordinates"]["row"].as_u64()?; + let column = self.payload["coordinates"]["column"].as_u64()?; + if row > 1 || column > 3 { + return None; + } + Some((row * 4 + column) as usize) + } + (INFOBAR, "Infobar") => None, + _ => return None, + }; + if self.context.is_empty() || self.device.is_empty() { + return None; + } + Some(Instance { + context: self.context.clone(), + device: self.device.clone(), + slot, + }) + } +} + +pub fn image(context: &str, image: String) -> Value { + json!({"event":"setImage","context":context,"payload":{"image":image,"target":0}}) +} + +pub fn registration(args: &[String]) -> Result<(u16, Value)> { + let flag = |name: &str| -> Result { + let index = args + .iter() + .position(|a| a.eq_ignore_ascii_case(name)) + .with_context(|| format!("missing OpenDeck launch argument {name}"))?; + args.get(index + 1) + .cloned() + .context("missing argument value") + }; + let port = flag("-port")?.parse()?; + let event = flag("-registerEvent")?; + let uuid = flag("-pluginUUID")?; + if event != "registerPlugin" || uuid != PLUGIN { + bail!("unexpected OpenDeck plugin registration"); + } + Ok((port, json!({"event":event,"uuid":uuid}))) +} + +/// Profile format is OpenDeck's own JSON (not an Elgato .streamDeckProfile). +/// Generate it offline; never mutate a profile underneath a running host. +pub fn profile(device: &str) -> Result { + if !device.starts_with("sd-") + || !device + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-') + { + bail!("expected a Stream Deck device ID such as sd-SERIAL"); + } + let manifest: Value = serde_json::from_str(include_str!("../assets/manifest.json"))?; + let instance = |slot: usize, infobar: bool| { + let mut action = manifest["Actions"][usize::from(infobar)].clone(); + action["plugin"] = PLUGIN.into(); + action["PropertyInspectorPath"] = PROFILE_INSPECTOR.into(); + let icon = format!("plugins/{PLUGIN}/icon.svg"); + action["Icon"] = icon.clone().into(); + action["States"][0]["Image"] = icon.clone().into(); + let controller = if infobar { "Infobar" } else { "Keypad" }; + json!({"action":action,"context":format!("{controller}.{slot}.0"),"states":[{"Image":icon,"ShowTitle":false}],"current_state":0,"settings":{},"children":null}) + }; + let mut keys: Vec = (0..8).map(|slot| instance(slot, false)).collect(); + keys.extend([Value::Null, Value::Null]); + Ok(json!({"id":"Furumi","keys":keys,"sliders":[],"infobars":[instance(0,true)]})) +} + +pub type Instances = BTreeMap; + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn parses_actual_opendeck_2142_infobar_event_and_emits_set_image() { + let event:Event=serde_json::from_value(json!({"event":"willAppear","action":INFOBAR,"context":"sd-TEST.Furumi.Infobar.0.0","device":"sd-TEST","payload":{"settings":{},"coordinates":{"row":0,"column":0},"controller":"Infobar","state":0,"isInMultiAction":false}})).unwrap(); + let instance = event.instance().unwrap(); + assert_eq!(instance.slot, None); + let out = image(&instance.context, "data:image/png;base64,abc".into()); + assert_eq!(out["context"], event.context); + assert_eq!(out["event"], "setImage"); + } + #[test] + fn profile_contains_eight_cells_and_the_correct_infobar_controller() { + let p = profile("sd-TEST").unwrap(); + assert_eq!( + p["keys"] + .as_array() + .unwrap() + .iter() + .filter(|v| !v.is_null()) + .count(), + 8 + ); + assert_eq!(p["infobars"][0]["action"]["Controllers"][0], "Infobar"); + assert!(profile("../../other").is_err()); + } +} diff --git a/integrations/opendeck/src/icons.rs b/integrations/opendeck/src/icons.rs new file mode 100644 index 0000000..8cad269 --- /dev/null +++ b/integrations/opendeck/src/icons.rs @@ -0,0 +1,225 @@ +//! Genuine Phosphor Fill masks, rasterised at authoring time from the bundled +//! source SVGs. No SVG/Node dependency or OS-specific font is needed at runtime. +use std::sync::LazyLock; + +use image::{GrayImage, Luma, Rgb, RgbImage, RgbaImage}; + +const TILE: u32 = 96; +const COLUMNS: u32 = 8; + +static ATLAS: LazyLock = LazyLock::new(|| { + let image = image::load_from_memory(include_bytes!("../assets/icons/phosphor-atlas.png")) + .expect("bundled Phosphor Fill alpha atlas must decode") + .into_rgba8(); + assert_eq!( + image.dimensions(), + (768, 384), + "bundled icon atlas dimensions" + ); + image +}); + +/// Order matches the named tiles in assets/icons/phosphor-atlas.json. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Icon { + Previous, + Play, + Pause, + Next, + Repeat, + RepeatOne, + Shuffle, + Back, + SeekBack, + SeekForward, + Radio, + Devices, + NextPage, + Album, + Check, + Unavailable, + CoverFrame, + EnabledFrame, +} + +fn blend(im: &mut RgbImage, index: usize, color: [u8; 3]) { + let x = (index as u32 % COLUMNS) * TILE; + let y = (index as u32 / COLUMNS) * TILE; + for dy in 0..im.height().min(TILE) { + for dx in 0..im.width().min(TILE) { + let alpha = ATLAS.get_pixel(x + dx, y + dy)[3] as u32; + if alpha == 0 { + continue; + } + let background = im.get_pixel(dx, dy).0; + let pixel = std::array::from_fn(|channel| { + ((background[channel] as u32 * (255 - alpha) + color[channel] as u32 * alpha + 127) + / 255) as u8 + }); + im.put_pixel(dx, dy, Rgb(pixel)); + } + } +} + +/// Paint a mask at its fixed native 96×96 production position. Existing pixels +/// outside its alpha coverage are preserved, including album artwork. +pub fn draw(im: &mut RgbImage, icon: Icon, color: [u8; 3]) { + blend(im, icon as usize, color); +} + +/// Eight genuine spinner-gap-fill frames. Choose e.g. elapsed_ms/100 as step. +/// The spinner occupies the Radio glyph area; it leaves the label area free. +pub fn spinner(im: &mut RgbImage, step: usize, color: [u8; 3]) { + blend(im, Icon::EnabledFrame as usize + 1 + step % 8, color); +} + +static CORNER_SPINNERS: LazyLock> = LazyLock::new(|| { + (0..8) + .map(|step| { + let index = Icon::EnabledFrame as usize + 1 + step; + let x = (index as u32 % COLUMNS) * TILE + 24; + let y = (index as u32 / COLUMNS) * TILE + 8; + let alpha = + GrayImage::from_fn(48, 48, |dx, dy| Luma([ATLAS.get_pixel(x + dx, y + dy)[3]])); + image::imageops::resize(&alpha, 20, 20, image::imageops::FilterType::Triangle) + }) + .collect() +}); + +/// The same genuine Phosphor spinner, scaled to a 20px bottom-right badge. +pub fn corner_spinner(im: &mut RgbImage, step: usize, color: [u8; 3]) { + paint_mask(im, &CORNER_SPINNERS[step % 8], 72, 72, color); +} + +fn paint_mask(im: &mut RgbImage, mask: &GrayImage, x: u32, y: u32, color: [u8; 3]) { + for (dx, dy, pixel) in mask.enumerate_pixels() { + if pixel[0] == 0 || x + dx >= im.width() || y + dy >= im.height() { + continue; + } + let a = u32::from(pixel[0]); + let old = im.get_pixel(x + dx, y + dy).0; + let pixel = std::array::from_fn(|channel| { + ((u32::from(old[channel]) * (255 - a) + u32::from(color[channel]) * a + 127) / 255) + as u8 + }); + im.put_pixel(x + dx, y + dy, Rgb(pixel)); + } +} + +pub const COVER_GLYPH_SIZE: u32 = 19; +static COVER_GLYPHS: LazyLock<[(Icon, GrayImage); 4]> = LazyLock::new(|| { + [Icon::Previous, Icon::Repeat, Icon::RepeatOne, Icon::Shuffle].map(|icon| { + let index = icon as u32; + let sx = index % COLUMNS * TILE + 20; + let sy = index / COLUMNS * TILE + 20; + let alpha = GrayImage::from_fn(56, 56, |x, y| Luma([ATLAS.get_pixel(sx + x, sy + y)[3]])); + let glyph = image::imageops::resize( + &alpha, + COVER_GLYPH_SIZE, + COVER_GLYPH_SIZE, + image::imageops::FilterType::Triangle, + ); + (icon, glyph) + }) +}); + +pub fn cover_glyph( + im: &mut RgbImage, + icon: Icon, + x: u32, + y: u32, + color: [u8; 3], + contour: [u8; 3], +) { + let Some((_, mask)) = COVER_GLYPHS.iter().find(|(kind, _)| *kind == icon) else { + return; + }; + for py in y.saturating_sub(1)..=y + 1 { + for px in x.saturating_sub(1)..=x + 1 { + if (px, py) != (x, y) { + paint_mask(im, mask, px, py, contour); + } + } + } + paint_mask(im, mask, x, y, color); +} + +#[cfg(test)] +mod tests { + use super::*; + const ALL: [Icon; 18] = [ + Icon::Previous, + Icon::Play, + Icon::Pause, + Icon::Next, + Icon::Repeat, + Icon::RepeatOne, + Icon::Shuffle, + Icon::Back, + Icon::SeekBack, + Icon::SeekForward, + Icon::Radio, + Icon::Devices, + Icon::NextPage, + Icon::Album, + Icon::Check, + Icon::Unavailable, + Icon::CoverFrame, + Icon::EnabledFrame, + ]; + + #[test] + fn enum_order_matches_named_svg_atlas_elements() { + let metadata: serde_json::Value = + serde_json::from_str(include_str!("../assets/icons/phosphor-atlas.json")).unwrap(); + for (index, icon) in ALL.into_iter().enumerate() { + assert_eq!(metadata["icons"][index]["name"], format!("{icon:?}")); + assert_eq!(metadata["icons"][index]["index"], index); + } + } + + #[test] + fn every_named_production_mask_has_visible_pixels_and_stays_inside_the_key() { + for icon in ALL { + let mut im = RgbImage::from_pixel(TILE, TILE, Rgb([43, 70, 90])); + draw(&mut im, icon, [208, 220, 227]); + assert!(im.pixels().any(|p| p.0 != [43, 70, 90]), "empty {icon:?}"); + assert_eq!(im.get_pixel(0, 0).0, [43, 70, 90]); + assert_eq!(im.get_pixel(95, 95).0, [43, 70, 90]); + } + } + + #[test] + fn frame_has_full_four_pixel_inset_and_does_not_fill_the_middle() { + let mut im = RgbImage::from_pixel(96, 96, Rgb([0, 0, 0])); + draw(&mut im, Icon::EnabledFrame, [255, 255, 255]); + assert_eq!(im.get_pixel(48, 48).0, [0, 0, 0]); + for inset in 0..4 { + for p in 0..96 { + assert_eq!(im.get_pixel(p, inset).0, [0, 0, 0]); + assert_eq!(im.get_pixel(p, 95 - inset).0, [0, 0, 0]); + assert_eq!(im.get_pixel(inset, p).0, [0, 0, 0]); + assert_eq!(im.get_pixel(95 - inset, p).0, [0, 0, 0]); + } + } + assert_eq!(im.get_pixel(48, 4).0, [255, 255, 255]); + } + + #[test] + fn spinner_rotates_and_wraps_without_painting_over_the_label() { + let make = |step| { + let mut im = RgbImage::new(96, 96); + spinner(&mut im, step, [208, 220, 227]); + im + }; + assert_ne!(make(0), make(1)); + assert_eq!(make(0), make(8)); + let frame = make(3); + for y in 68..96 { + for x in 0..96 { + assert_eq!(frame.get_pixel(x, y).0, [0, 0, 0]); + } + } + } +} diff --git a/integrations/opendeck/src/main.rs b/integrations/opendeck/src/main.rs new file mode 100644 index 0000000..232f5ff --- /dev/null +++ b/integrations/opendeck/src/main.rs @@ -0,0 +1,1206 @@ +#![cfg_attr(target_os = "windows", windows_subsystem = "windows")] +mod artwork; +mod client; +mod host; +mod icons; +mod model; +mod preview; +mod profile_upgrade; +mod render; +mod settings; +mod spectrum; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, bail}; +use furumi_control_protocol::{ + API_VERSION, ClientMessage, Command, MAX_MESSAGE_BYTES, ServerMessage, Snapshot, +}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::Value; +use tokio::sync::mpsc; +use tokio_tungstenite::tungstenite::{Message, protocol::WebSocketConfig}; + +use model::{Deck, PendingRadio, PendingTransfer, RemoteGate, conflicts_with_remote_playback}; + +struct Surface { + instances: host::Instances, + decks: BTreeMap, + snapshot: Option, + snapshot_at: Instant, + track_at: Instant, + artwork: artwork::Artwork, + sent: BTreeMap>, + sequence: u64, + session_id: String, + remote: RemoteGate, + preferences: settings::Preferences, + settings: settings::Store, + host_outbox: Vec, + spectrum: spectrum::History, + spectrum_subscribed: bool, + keys_dirty: bool, +} + +impl Surface { + fn new() -> Self { + Self { + instances: BTreeMap::new(), + decks: BTreeMap::new(), + snapshot: None, + snapshot_at: Instant::now(), + track_at: Instant::now(), + artwork: artwork::Artwork::default(), + sent: BTreeMap::new(), + sequence: 0, + session_id: format!( + "deck-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + ), + remote: RemoteGate::default(), + preferences: settings::Preferences::default(), + settings: settings::Store::default(), + host_outbox: Vec::new(), + spectrum: spectrum::History::default(), + spectrum_subscribed: false, + keys_dirty: true, + } + } + fn request(&mut self, command: Command) -> (String, ClientMessage) { + self.sequence += 1; + let kind = if matches!(command, Command::Artwork { .. }) { + "art" + } else { + "command" + }; + let id = format!("{}-{kind}-{}", self.session_id, self.sequence); + (id.clone(), ClientMessage::Command { id, command }) + } + fn disconnect(&mut self) { + let was_connected = self.snapshot.take().is_some(); + self.artwork = artwork::Artwork::default(); + self.remote = RemoteGate::default(); + self.spectrum = spectrum::History::default(); + self.spectrum_subscribed = false; + self.keys_dirty = true; + for deck in self.decks.values_mut() { + deck.presses.clear(); + deck.pending = None; + deck.radio = None; + deck.remote = RemoteGate::default(); + deck.artwork_loading = None; + if was_connected { + deck.screen = model::Screen::Player; + } + } + } + + fn artwork_request(&mut self, now: Instant) -> Option { + let previous_loading = self.artwork.loading(); + self.artwork.expire(now); + let online = self.snapshot.is_some() + && now.saturating_duration_since(self.snapshot_at) <= Duration::from_secs(3); + let visible = online + && self.instances.values().any(|instance| { + (instance.slot == Some(0) + || (self.preferences.album_art_2x2 && matches!(instance.slot, Some(1 | 4 | 5)))) + && self + .decks + .get(&instance.device) + .is_some_and(|deck| matches!(deck.screen, model::Screen::Player)) + }); + let command = self.artwork.needed(visible).map(|artwork_id| { + let (id, command) = self.request(Command::Artwork { + artwork_id: artwork_id.clone(), + federation: true, + }); + self.artwork.begin(id, artwork_id, now); + command + }); + let loading = self.artwork.loading(); + if previous_loading != loading { + self.keys_dirty = true; + } + for deck in self.decks.values_mut() { + deck.artwork_loading = loading; + } + command + } + + fn artwork_request_id(&self, id: &str) -> bool { + id.starts_with(&format!("{}-art-", self.session_id)) + } + + fn host_event(&mut self, event: host::Event) -> Option { + self.keys_dirty = true; + match event.event.as_str() { + "didReceiveGlobalSettings" => { + if let Some(value) = self.settings.receive(&event.payload["settings"]) { + self.write_settings(value); + } + self.apply_preferences(); + None + } + "sendToPlugin" + if matches!(event.action.as_str(), host::CELL | host::INFOBAR) + && event.payload["event"] == "preferencesPatch" => + { + if let Some(value) = self.settings.patch(&event.payload["patch"]) { + self.write_settings(value); + self.apply_preferences(); + } + None + } + "propertyInspectorDidAppear" => { + if let Some(settings) = self.settings.raw_value() { + self.host_outbox.push(serde_json::json!({"event":"sendToPropertyInspector","context":event.context,"payload":{"event":"preferencesState","settings":settings}})); + } + None + } + "willAppear" => { + if let Some(instance) = event.instance() { + self.decks + .entry(instance.device.clone()) + .or_default() + .remote = self.remote.clone(); + self.decks.get_mut(&instance.device).unwrap().preferences = self.preferences; + self.sent.remove(&instance.context); + self.instances.insert(instance.context.clone(), instance); + } + None + } + "willDisappear" => { + if let Some(instance) = self.instances.remove(&event.context) { + if let Some(deck) = self.decks.get_mut(&instance.device) { + deck.presses.remove(&event.context); + } + self.sent.remove(&event.context); + if !self.instances.values().any(|i| i.device == instance.device) { + self.decks.remove(&instance.device); + } + } + None + } + "deviceDidDisconnect" => { + self.instances.retain(|_, i| i.device != event.device); + self.sent + .retain(|context, _| self.instances.contains_key(context)); + self.decks.remove(&event.device); + None + } + "keyDown" => { + let instance = self.instances.get(&event.context)?; + let slot = instance.slot?; + let deck = self.decks.get_mut(&instance.device)?; + if !deck.presses.contains_key(&event.context) { + let binding = deck.binding(slot, self.snapshot.as_ref()); + deck.presses.insert(event.context, binding); + } + None + } + "keyUp" => { + let instance = self.instances.get(&event.context)?.clone(); + let deck = self.decks.get_mut(&instance.device)?; + let binding = deck.presses.remove(&event.context)?; + let command = deck.release(binding, self.snapshot.as_ref())?; + let transfer = if let Command::Transfer { device_id } = &command { + Some(device_id.clone()) + } else { + None + }; + let radio = command == Command::StartRadio; + if matches!(command, Command::Seek { .. }) { + self.spectrum.clear(); + } + let wait_remote = conflicts_with_remote_playback(&command) && !radio; + let radio_baseline = self.snapshot.as_ref().map_or(0, |s| s.radio.id); + let (id, message) = self.request(command); + if wait_remote && let Some(snapshot) = &self.snapshot { + self.remote.begin(snapshot, id.clone(), Instant::now()); + for deck in self.decks.values_mut() { + deck.remote = self.remote.clone(); + } + } + if radio { + self.decks.get_mut(&instance.device)?.radio = Some(PendingRadio { + request_id: id.clone(), + baseline: radio_baseline, + started: Instant::now(), + }); + } + if let Some(device_id) = transfer { + self.decks.get_mut(&instance.device)?.pending = Some(PendingTransfer { + request_id: id, + device_id, + started: Instant::now(), + }); + } + Some(message) + } + _ => None, + } + } + + fn write_settings(&mut self, value: Value) { + self.host_outbox.push( + serde_json::json!({"event":"setGlobalSettings","context":host::PLUGIN,"payload":value}), + ); + } + fn apply_preferences(&mut self) { + self.preferences = self.settings.preferences(); + for deck in self.decks.values_mut() { + deck.preferences = self.preferences; + } + self.keys_dirty = true; + if self.preferences.infobar_background == settings::InfobarBackground::None { + self.spectrum.clear(); + } + } + + fn update(&mut self, update: client::Update) -> Option> { + let message = match update { + client::Update::Disconnected => { + self.disconnect(); + return None; + } + client::Update::Message(message) => *message, + }; + match message { + ServerMessage::Snapshot { snapshot } => { + let snapshot = *snapshot; + if snapshot.api_version != API_VERSION { + self.disconnect(); + return None; + } + if self + .snapshot + .as_ref() + .is_some_and(|previous| snapshot.revision < previous.revision) + { + return None; + } + if self + .snapshot + .as_ref() + .is_none_or(|previous| key_state_changed(previous, &snapshot)) + { + self.keys_dirty = true; + } + let changed = self + .snapshot + .as_ref() + .and_then(|s| s.track.as_ref()) + .map(|t| &t.key) + != snapshot.track.as_ref().map(|t| &t.key); + if changed { + self.track_at = Instant::now(); + self.spectrum.clear(); + } + if self.snapshot.as_ref().is_some_and(|old| { + old.active_device_id != snapshot.active_device_id + || (old.playing && !snapshot.playing) + || old.role != snapshot.role + }) { + self.spectrum.clear(); + } + self.artwork.observe(Some(&snapshot)); + let remote_error = self.remote.observe(&snapshot, Instant::now()); + for deck in self.decks.values_mut() { + deck.remote = self.remote.clone(); + deck.update(&snapshot); + if let Some(error) = &remote_error { + deck.notice = Some((error.clone(), Instant::now())); + } + } + self.snapshot = Some(snapshot); + self.snapshot_at = Instant::now(); + } + ServerMessage::Result { + id, + accepted, + error, + } => { + if self.artwork_request_id(&id) { + if !accepted { + self.artwork.reject(&id); + self.keys_dirty = true; + } + return None; + } + if !accepted { + self.keys_dirty = true; + self.remote.reject(&id); + for deck in self.decks.values_mut() { + deck.remote = self.remote.clone(); + if deck.pending.as_ref().is_some_and(|p| p.request_id == id) { + deck.pending = None; + } + if deck.radio.as_ref().is_some_and(|p| p.request_id == id) { + deck.radio = None; + } + deck.notice = Some(( + error.clone().unwrap_or_else(|| "Command rejected".into()), + Instant::now(), + )); + } + } + } + ServerMessage::Artwork { + id, + artwork_id, + png_base64, + } => { + if !self.artwork.matches(&id, &artwork_id) { + return None; + } + if let Some(image) = png_base64 { + return Some(artwork::CoverReply { + request_id: id, + artwork_id, + image, + }); + } + self.artwork.complete(&id, &artwork_id, None); + self.keys_dirty = true; + } + ServerMessage::Spectrum { + epoch, + sequence, + bands, + } => self.spectrum_frame(spectrum::Frame { + epoch, + sequence, + bands, + }), + } + None + } + + fn cover_ready(&mut self, reply: artwork::CoverReply>) { + self.artwork + .complete(&reply.request_id, &reply.artwork_id, reply.image); + self.keys_dirty = true; + } + + fn wants_spectrum(&self) -> bool { + self.preferences.infobar_background.uses_spectrum() + && self.snapshot.as_ref().is_some_and(|s| { + s.spectrum_supported + && s.playing + && (s.role == furumi_control_protocol::Role::Active + || (s.role == furumi_control_protocol::Role::Jam + && s.active_device_id.as_deref() == Some(s.self_device_id.as_str()))) + }) + && self + .instances + .values() + .any(|instance| instance.slot.is_none()) + } + + fn spectrum_request(&mut self) -> Option { + let desired = self.wants_spectrum(); + if !desired { + self.spectrum.clear(); + } + if desired == self.spectrum_subscribed { + return None; + } + // Older servers cannot parse this additive client message. Never send + // it until the corresponding snapshot capability is advertised. + if !self.snapshot.as_ref().is_some_and(|s| s.spectrum_supported) { + self.spectrum_subscribed = false; + return None; + } + self.spectrum_subscribed = desired; + Some(ClientMessage::SubscribeSpectrum { enabled: desired }) + } + + fn spectrum_frame(&mut self, frame: spectrum::Frame) { + if self.wants_spectrum() { + if self.snapshot.as_ref().is_some_and(|s| s.paused) && frame.bands.is_some() { + return; + } + self.spectrum.ingest(frame); + } else { + self.spectrum.clear(); + } + } + + fn images(&mut self) -> Result> { + if self.snapshot.is_some() && self.snapshot_at.elapsed() > Duration::from_secs(3) { + self.disconnect(); + } + self.artwork.expire(Instant::now()); + for deck in self.decks.values_mut() { + if deck.artwork_loading != self.artwork.loading() { + self.keys_dirty = true; + } + deck.artwork_loading = self.artwork.loading(); + } + if let Some(error) = self.remote.expire(Instant::now()) { + self.keys_dirty = true; + for deck in self.decks.values_mut() { + deck.remote = self.remote.clone(); + deck.notice = Some((error.clone(), Instant::now())); + } + } + let mut messages = Vec::new(); + let now = Instant::now(); + for instance in self.instances.values() { + let Some(deck) = self.decks.get(&instance.device) else { + continue; + }; + let image = match instance.slot { + Some(slot) => { + let animated = match &deck.screen { + model::Screen::Player => { + (slot == 0 && deck.artwork_loading.is_some()) + || (slot == 2 && deck.remote.waiting(self.snapshot.as_ref())) + } + model::Screen::Functions => slot == 0 && deck.radio.is_some(), + model::Screen::Devices { .. } => slot < 6, + }; + if !self.keys_dirty && !animated { + continue; + } + render::key_prepared( + slot, + deck, + self.snapshot.as_ref(), + self.artwork.prepared(), + now, + ) + } + None => render::bar_with_spectrum( + deck, + self.snapshot.as_ref(), + self.track_at.elapsed(), + self.snapshot_at.elapsed(), + Some(&self.spectrum), + ), + }; + let raw = image.as_raw(); + if self.sent.get(&instance.context) == Some(raw) { + continue; + } + self.sent.insert(instance.context.clone(), raw.clone()); + messages.push(host::image(&instance.context, render::data_uri(&image)?)); + } + self.keys_dirty = false; + Ok(messages) + } +} + +fn key_state_changed(a: &Snapshot, b: &Snapshot) -> bool { + a.role != b.role + || a.active_device_id != b.active_device_id + || a.active_device_name != b.active_device_name + || a.playing != b.playing + || a.paused != b.paused + || a.shuffle != b.shuffle + || a.repeat != b.repeat + || a.radio != b.radio + || a.remote_command != b.remote_command + || a.track != b.track + || a.devices != b.devices +} + +#[tokio::main] +async fn main() -> Result<()> { + let os_args: Vec<_> = std::env::args_os().collect(); + if os_args.get(1).is_some_and(|a| a == "--upgrade-profile") { + return profile_upgrade::upgrade(Path::new( + os_args.get(2).context("usage: --upgrade-profile PATH")?, + )); + } + let args: Vec = os_args + .into_iter() + .map(|arg| { + arg.into_string() + .map_err(|_| anyhow::anyhow!("OpenDeck launch arguments must be UTF-8")) + }) + .collect::>()?; + if args.get(1).is_some_and(|a| a == "--preview") { + return preview::write(Path::new( + args.get(2).map(String::as_str).unwrap_or("preview"), + )); + } + if args.get(1).is_some_and(|a| a == "--write-profile") { + let device = args + .get(2) + .context("usage: --write-profile sd-SERIAL OUTPUT.json")?; + let output = args.get(3).context("missing output path")?; + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(output) + .context("profile output already exists or cannot be created")?; + serde_json::to_writer_pretty(file, &host::profile(device)?)?; + return Ok(()); + } + if args.len() == 1 || args.iter().any(|a| a == "--help") { + eprintln!( + "Furumi OpenDeck plugin: launched by OpenDeck, or --preview DIR, --write-profile sd-SERIAL OUTPUT.json, --upgrade-profile PATH (with OpenDeck closed)" + ); + return Ok(()); + } + run_host(&args, None).await +} + +async fn run_host(args: &[String], endpoint_path: Option) -> Result<()> { + let (port, registration) = host::registration(args)?; + let config = WebSocketConfig::default() + .max_message_size(Some(MAX_MESSAGE_BYTES)) + .max_frame_size(Some(MAX_MESSAGE_BYTES)); + let (mut host, _) = tokio_tungstenite::connect_async_with_config( + format!("ws://127.0.0.1:{port}"), + Some(config), + false, + ) + .await?; + host.send(Message::text(serde_json::to_string(®istration)?)) + .await?; + host.send(Message::text( + serde_json::json!({"event":"getGlobalSettings","context":host::PLUGIN}).to_string(), + )) + .await?; + let (command_tx, command_rx) = mpsc::channel(32); + let (update_tx, mut update_rx) = mpsc::channel(16); + let (spectrum_tx, mut spectrum_rx) = tokio::sync::watch::channel(None); + let client = tokio::spawn(client::run( + command_rx, + update_tx, + endpoint_path, + spectrum_tx, + )); + let mut surface = Surface::new(); + let mut cover_worker = tokio::task::JoinSet::new(); + let mut next_cover = None; + let mut clock = tokio::time::interval(Duration::from_millis(100)); + clock.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let result: Result<()> = async { + loop { + let command = tokio::select! { + incoming = host.next() => { + match incoming { + Some(Ok(Message::Text(text))) => { + surface.host_event(serde_json::from_str(&text)?) + } + Some(Ok(Message::Ping(bytes))) => { + host.send(Message::Pong(bytes)).await?; + None + } + Some(Ok(Message::Close(_))) | None => break, + Some(Err(error)) => return Err(error.into()), + _ => None, + } + } + update = update_rx.recv() => { + let Some(update) = update else { bail!("control client ended") }; + if let Some(cover) = surface.update(update) { + next_cover = Some(cover); + } + None + } + Some(completed) = cover_worker.join_next(), if !cover_worker.is_empty() => { + if let Ok(cover) = completed { + surface.cover_ready(cover); + } + None + } + _ = clock.tick() => { + if spectrum_rx.has_changed().unwrap_or(false) { + let frame = spectrum_rx.borrow_and_update().clone(); + match frame { + Some(frame) => surface.spectrum_frame(frame), + None => surface.spectrum.clear(), + } + } + None + } + }; + // A quick track change replaces queued work. An in-flight result is + // checked against the current request again when the worker returns. + if cover_worker.is_empty() + && let Some(cover) = next_cover.take() + && surface + .artwork + .matches(&cover.request_id, &cover.artwork_id) + { + cover_worker.spawn_blocking(move || cover.prepare()); + } + let artwork = surface.artwork_request(Instant::now()); + let spectrum = surface.spectrum_request(); + for command in command.into_iter().chain(artwork).chain(spectrum) { + if let Err(error) = command_tx.try_send(command) { + match error.into_inner() { + ClientMessage::SubscribeSpectrum { enabled } => { + surface.spectrum_subscribed = !enabled; + continue; + } + ClientMessage::Command { id, .. } => { + if surface.artwork_request_id(&id) { + surface.artwork.reject(&id); + surface.keys_dirty = true; + continue; + } + surface.remote.reject(&id); + } + _ => {} + } + for deck in surface.decks.values_mut() { + deck.remote = surface.remote.clone(); + deck.pending = None; + deck.radio = None; + deck.notice = Some(("Command not sent".into(), Instant::now())); + } + } + } + for message in surface.host_outbox.drain(..) { + tokio::time::timeout( + Duration::from_secs(3), + host.send(Message::text(message.to_string())), + ) + .await??; + } + for message in surface.images()? { + tokio::time::timeout( + Duration::from_secs(3), + host.send(Message::text(serde_json::to_string(&message)?)), + ) + .await??; + } + } + Ok(()) + } + .await; + client.abort(); + result +} + +#[cfg(test)] +mod tests { + use super::*; + use base64::Engine as _; + use image::RgbImage; + use serde_json::json; + fn event(kind: &str, slot: usize) -> host::Event { + serde_json::from_value(json!({"event":kind,"action":host::CELL,"context":format!("test-{slot}"),"device":"deck-1","payload":{"controller":"Keypad","coordinates":{"row":slot/4,"column":slot%4},"isInMultiAction":false}})).unwrap() + } + + fn spectrum_surface() -> Surface { + let mut surface = Surface::new(); + surface.host_event(serde_json::from_value(json!({"event":"didReceiveGlobalSettings","payload":{"settings":{"infobar_background":"spectrogram"}}})).unwrap()); + let mut snapshot = preview::fixture(); + snapshot.spectrum_supported = true; + surface.update(snapshot_update(snapshot)); + surface.host_event(serde_json::from_value(json!({"event":"willAppear","action":host::INFOBAR,"context":"infobar","device":"deck-1","payload":{"controller":"Infobar","coordinates":{"row":0,"column":0}}})).unwrap()); + surface + } + + #[test] + fn switching_spectrum_modes_preserves_history_and_existing_subscription() { + let mut surface = spectrum_surface(); + assert!(matches!( + surface.spectrum_request(), + Some(ClientMessage::SubscribeSpectrum { enabled: true }) + )); + surface.spectrum_frame(spectrum::Frame { + epoch: 1, + sequence: 1, + bands: Some([170; 31]), + }); + let paint = |surface: &Surface| { + let mut im = RgbImage::new(31, 30); + surface.spectrum.paint( + &mut im, + (0, 0, 31, 30), + settings::InfobarBackground::Spectrogram, + ); + im + }; + let before = paint(&surface); + for mode in ["bars", "spectrogram", "bars"] { + surface.host_event(serde_json::from_value(json!({"event":"didReceiveGlobalSettings","payload":{"settings":{"infobar_background":mode}}})).unwrap()); + assert!( + surface.spectrum_request().is_none(), + "hot switching must not resubscribe" + ); + assert_eq!( + paint(&surface), + before, + "hot switching retains source history" + ); + } + surface.host_event( + serde_json::from_value(json!({"event":"willDisappear","context":"infobar"})).unwrap(), + ); + assert!(matches!( + surface.spectrum_request(), + Some(ClientMessage::SubscribeSpectrum { enabled: false }) + )); + } + + #[test] + fn spectrum_subscription_is_capability_and_visibility_gated_and_pause_freezes_history() { + let mut surface = spectrum_surface(); + assert!(matches!( + surface.spectrum_request(), + Some(ClientMessage::SubscribeSpectrum { enabled: true }) + )); + assert!(surface.spectrum_request().is_none()); + surface.spectrum_frame(spectrum::Frame { + epoch: 1, + sequence: 1, + bands: Some([100; 31]), + }); + let paint = |surface: &Surface| { + let mut im = RgbImage::new(10, 10); + surface.spectrum.paint( + &mut im, + (0, 0, 10, 10), + settings::InfobarBackground::Spectrogram, + ); + im + }; + let before = paint(&surface); + let mut snapshot = surface.snapshot.clone().unwrap(); + snapshot.paused = true; + snapshot.revision += 1; + surface.update(snapshot_update(snapshot.clone())); + assert!(surface.spectrum_request().is_none()); + surface.spectrum_frame(spectrum::Frame { + epoch: 1, + sequence: 2, + bands: Some([255; 31]), + }); + assert_eq!(paint(&surface), before); + snapshot.role = furumi_control_protocol::Role::Control; + snapshot.revision += 1; + surface.update(snapshot_update(snapshot.clone())); + assert!(matches!( + surface.spectrum_request(), + Some(ClientMessage::SubscribeSpectrum { enabled: false }) + )); + assert_eq!(paint(&surface), RgbImage::new(10, 10)); + snapshot.role = furumi_control_protocol::Role::Active; + snapshot.paused = false; + snapshot.spectrum_supported = false; + snapshot.revision += 1; + surface.update(snapshot_update(snapshot)); + assert!( + surface.spectrum_request().is_none(), + "legacy servers must receive no unknown subscription variant" + ); + surface.disconnect(); + assert!(!surface.spectrum_subscribed); + } + + #[test] + fn spectrum_frames_only_update_infobar_not_key_images() { + let mut surface = spectrum_surface(); + for slot in 0..8 { + surface.host_event(event("willAppear", slot)); + } + surface.images().unwrap(); + assert!(!surface.keys_dirty); + surface.spectrum_frame(spectrum::Frame { + epoch: 1, + sequence: 1, + bands: Some([255; 31]), + }); + let images = surface.images().unwrap(); + assert!(!images.is_empty()); + assert!(images.iter().all(|message| message["context"] == "infobar")); + assert!(!surface.keys_dirty); + } + + fn snapshot_update(snapshot: Snapshot) -> client::Update { + client::Update::Message(Box::new(ServerMessage::Snapshot { + snapshot: Box::new(snapshot), + })) + } + + fn cover_snapshot(key: &str, artwork_id: &str, revision: u64) -> Snapshot { + let mut s = preview::fixture(); + s.revision = revision; + let track = s.track.as_mut().unwrap(); + track.key = key.into(); + track.artwork_id = Some(artwork_id.into()); + s + } + + fn art_request(surface: &mut Surface) -> (String, String) { + let Some(ClientMessage::Command { + id, + command: + Command::Artwork { + artwork_id, + federation: true, + }, + }) = surface.artwork_request(Instant::now()) + else { + panic!("visible cover should issue one federation-enabled request") + }; + (id, artwork_id) + } + + #[test] + fn mosaic_cover_demand_includes_visible_previous_repeat_and_shuffle_keys() { + for slot in [1, 4, 5] { + let mut surface = Surface::new(); + surface.update(snapshot_update(cover_snapshot("A", "art-A", 1))); + surface.host_event(event("willAppear", slot)); + assert!(surface.artwork_request(Instant::now()).is_none()); + surface.preferences.album_art_2x2 = true; + assert_eq!(art_request(&mut surface).1, "art-A"); + } + } + + #[test] + fn artwork_fetch_requires_attached_player_cover_and_navigation_rechecks_after_snapshot() { + let mut surface = Surface::new(); + surface.update(snapshot_update(cover_snapshot("A", "art-A", 1))); + assert!( + surface.artwork_request(Instant::now()).is_none(), + "background plugin does not fetch" + ); + surface.host_event(event("willAppear", 1)); + assert!( + surface.artwork_request(Instant::now()).is_none(), + "only key0 can demand a cover" + ); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("willAppear", 7)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + assert!( + surface.artwork_request(Instant::now()).is_none(), + "Functions does not fetch covers" + ); + surface.host_event(event("keyDown", 7)); + surface.host_event(event("keyUp", 7)); + let (_, artwork_id) = art_request(&mut surface); + assert_eq!(artwork_id, "art-A"); + assert!( + surface.artwork_request(Instant::now()).is_none(), + "one request per generation" + ); + surface.host_event(event("willDisappear", 0)); + surface.update(snapshot_update(cover_snapshot("B", "art-B", 2))); + assert!( + surface.artwork_request(Instant::now()).is_none(), + "hidden profile cannot request a new cover" + ); + surface.host_event(event("willAppear", 0)); + let (_, artwork_id) = art_request(&mut surface); + assert_eq!(artwork_id, "art-B"); + } + + #[test] + fn late_a_reply_and_rejection_cannot_replace_new_a_after_a_b_a_navigation() { + let mut surface = Surface::new(); + surface.host_event(event("willAppear", 0)); + surface.update(snapshot_update(cover_snapshot("A", "art-A", 1))); + let (old_id, _) = art_request(&mut surface); + let image = RgbImage::from_pixel(96, 96, image::Rgb([180, 30, 70])); + let data = base64::engine::general_purpose::STANDARD.encode(render::png(&image).unwrap()); + let in_flight = surface + .update(client::Update::Message(Box::new(ServerMessage::Artwork { + id: old_id.clone(), + artwork_id: "art-A".into(), + png_base64: Some(data.clone()), + }))) + .unwrap(); + surface.update(snapshot_update(cover_snapshot("B", "art-B", 2))); + art_request(&mut surface); + surface.update(snapshot_update(cover_snapshot("A", "art-A", 3))); + let (new_id, _) = art_request(&mut surface); + surface.cover_ready(in_flight.prepare()); + assert!(surface.artwork.image().is_none()); + let stale = surface.update(client::Update::Message(Box::new(ServerMessage::Artwork { + id: old_id.clone(), + artwork_id: "art-A".into(), + png_base64: Some(data.clone()), + }))); + assert!(stale.is_none()); + assert!(surface.artwork.image().is_none()); + assert!(surface.artwork.loading().is_some()); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id: old_id, + accepted: false, + error: Some("Old art expired".into()), + }))); + assert!(surface.artwork.loading().is_some()); + assert!(surface.decks["deck-1"].notice.is_none()); + let cover = surface + .update(client::Update::Message(Box::new(ServerMessage::Artwork { + id: new_id, + artwork_id: "art-A".into(), + png_base64: Some(data), + }))) + .unwrap(); + assert!(surface.artwork.image().is_none()); + surface.cover_ready(cover.prepare()); + assert_eq!(surface.artwork.image(), Some(&image)); + } + + #[test] + fn artwork_rejection_is_terminal_and_never_cancels_pending_transport() { + use furumi_control_protocol::Role; + let mut surface = Surface::new(); + let mut s = cover_snapshot("A", "art-A", 1); + s.role = Role::Control; + surface.update(snapshot_update(s)); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("willAppear", 2)); + let (id, _) = art_request(&mut surface); + surface.host_event(event("keyDown", 2)); + assert!( + surface.host_event(event("keyUp", 2)).is_some(), + "transport remains usable during art loading" + ); + assert!(surface.remote.waiting(surface.snapshot.as_ref())); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id, + accepted: false, + error: Some("Art unavailable".into()), + }))); + assert!(surface.remote.waiting(surface.snapshot.as_ref())); + assert!(surface.decks["deck-1"].notice.is_none()); + assert!(surface.artwork_request(Instant::now()).is_none()); + assert!(surface.artwork.loading().is_none()); + } + + #[test] + fn terminal_missing_cover_does_not_retry_on_each_playback_snapshot() { + let mut surface = Surface::new(); + surface.host_event(event("willAppear", 0)); + surface.update(snapshot_update(cover_snapshot("A", "art-A", 1))); + let (id, artwork_id) = art_request(&mut surface); + surface.update(client::Update::Message(Box::new(ServerMessage::Artwork { + id, + artwork_id, + png_base64: None, + }))); + for revision in 2..8 { + surface.update(snapshot_update(cover_snapshot("A", "art-A", revision))); + assert!(surface.artwork_request(Instant::now()).is_none()); + } + assert!(surface.artwork.image().is_none()); + assert!(surface.artwork.loading().is_none()); + } + + #[test] + fn artwork_federation_flag_is_additive_and_defaults_to_local_only() { + let old: Command = + serde_json::from_value(json!({"type":"artwork","artwork_id":"art"})).unwrap(); + assert_eq!( + old, + Command::Artwork { + artwork_id: "art".into(), + federation: false + } + ); + assert!( + serde_json::to_value(old) + .unwrap() + .get("federation") + .is_none() + ); + assert_eq!( + serde_json::to_value(Command::Artwork { + artwork_id: "art".into(), + federation: true + }) + .unwrap()["federation"], + true + ); + } + + #[test] + fn offline_reconnect_attempts_do_not_close_functions() { + let mut surface = Surface::new(); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface.update(client::Update::Disconnected); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Functions + )); + assert!(surface.artwork_request(Instant::now()).is_none()); + } + + #[test] + fn remote_pending_is_global_across_decks_and_accepted_dispatch_does_not_release_it() { + use furumi_control_protocol::{RemoteCommand, RemoteCommandState, Role}; + let mut surface = Surface::new(); + let mut snapshot = preview::fixture(); + snapshot.role = Role::Control; + snapshot.active_device_id = Some("laptop".into()); + surface.update(snapshot_update(snapshot.clone())); + for slot in 0..8 { + surface.host_event(event("willAppear", slot)); + } + let other = |kind: &str| { + let mut e = event(kind, 2); + e.device = "deck-2".into(); + e.context = "other-play".into(); + e + }; + surface.host_event(other("willAppear")); + // Capture a conflicting key before the first command is dispatched. + surface.host_event(event("keyDown", 3)); + surface.host_event(other("keyDown")); + let Some(ClientMessage::Command { id, .. }) = surface.host_event(other("keyUp")) else { + panic!("first control command") + }; + assert!(surface.host_event(event("keyUp", 3)).is_none()); + assert!( + surface + .decks + .values() + .all(|d| d.remote.waiting(surface.snapshot.as_ref())) + ); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id, + accepted: true, + error: None, + }))); + assert!(surface.remote.waiting(surface.snapshot.as_ref())); + snapshot.revision = 2; + surface.update(snapshot_update(snapshot.clone())); + assert!( + surface.remote.waiting(surface.snapshot.as_ref()), + "idle snapshot queued before dispatch must not unlock" + ); + snapshot.revision = 3; + snapshot.remote_command = Some(RemoteCommand { + id: 1, + state: RemoteCommandState::Pending, + error: None, + }); + surface.update(snapshot_update(snapshot.clone())); + surface.host_event(event("keyDown", 1)); + assert!(surface.host_event(event("keyUp", 1)).is_none()); + snapshot.revision = 4; + snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Confirmed; + surface.update(snapshot_update(snapshot)); + assert!(!surface.remote.waiting(surface.snapshot.as_ref())); + surface.host_event(event("keyDown", 1)); + assert!(surface.host_event(event("keyUp", 1)).is_some()); + surface.disconnect(); + assert!(!surface.remote.waiting(surface.snapshot.as_ref())); + } + + #[test] + fn additive_remote_status_field_keeps_legacy_local_snapshots_readable() { + let mut value = serde_json::to_value(preview::fixture()).unwrap(); + value.as_object_mut().unwrap().remove("remote_command"); + let snapshot: Snapshot = serde_json::from_value(value).unwrap(); + assert!(snapshot.remote_command.is_none()); + assert!( + serde_json::to_value(snapshot) + .unwrap() + .get("remote_command") + .is_none() + ); + assert_eq!( + serde_json::to_value(preview::fixture()).unwrap()["remote_command"]["state"], + "idle" + ); + } + #[test] + fn host_screen_switch_and_paired_press_dispatch_a_single_command() { + let mut surface = Surface::new(); + surface.update(client::Update::Message(Box::new(ServerMessage::Snapshot { + snapshot: Box::new(preview::fixture()), + }))); + for i in 0..8 { + surface.host_event(event("willAppear", i)); + } + surface.host_event(event("keyDown", 0)); + assert!(surface.host_event(event("keyUp", 0)).is_none()); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Functions + )); + surface.host_event(event("keyDown", 1)); + assert!(surface.host_event(event("keyUp", 1)).is_none()); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Devices { .. } + )); + surface.host_event(event("keyDown", 1)); + let message = surface.host_event(event("keyUp", 1)); + assert!(matches!( + message, + Some(ClientMessage::Command { + command: Command::Transfer { .. }, + .. + }) + )); + assert!(surface.host_event(event("keyUp", 1)).is_none()); + surface.update(client::Update::Disconnected); + assert!(surface.snapshot.is_none()); + assert!(surface.host_event(event("keyDown", 0)).is_none()); + assert!(surface.host_event(event("keyUp", 0)).is_none()); + } + + #[tokio::test] + async fn websocket_host_authenticates_draws_native_images_and_controls_furumi() { + use furumi_control_protocol::Discovery; + use image::GenericImageView as _; + use tokio::net::TcpListener; + use tokio_tungstenite::accept_async; + + tokio::time::timeout(Duration::from_secs(10), async { + let host_listener=TcpListener::bind("127.0.0.1:0").await.unwrap(); + let api_listener=TcpListener::bind("127.0.0.1:0").await.unwrap(); + let directory=tempfile::tempdir().unwrap();let discovery=directory.path().join("endpoint.json"); + let endpoint=Discovery{api_version:API_VERSION,port:api_listener.local_addr().unwrap().port(),token:"test-only-secret".into()}; + std::fs::write(&discovery,serde_json::to_vec(&endpoint).unwrap()).unwrap(); + let args=vec!["plugin".into(),"-port".into(),host_listener.local_addr().unwrap().port().to_string(),"-pluginUUID".into(),host::PLUGIN.into(),"-registerEvent".into(),"registerPlugin".into()]; + let plugin=tokio::spawn(async move{run_host(&args,Some(discovery)).await}); + let mut host=accept_async(host_listener.accept().await.unwrap().0).await.unwrap(); + let registration:Value=serde_json::from_slice(&host.next().await.unwrap().unwrap().into_data()).unwrap(); + assert_eq!(registration["event"],"registerPlugin");assert_eq!(registration["uuid"],host::PLUGIN); + let mut api=accept_async(api_listener.accept().await.unwrap().0).await.unwrap(); + let auth:ClientMessage=serde_json::from_slice(&api.next().await.unwrap().unwrap().into_data()).unwrap(); + assert!(matches!(auth,ClientMessage::Authenticate{token,..} if token=="test-only-secret")); + let mut snapshot=preview::fixture();snapshot.paused=true; + api.send(Message::text(serde_json::to_string(&ServerMessage::Snapshot{snapshot:Box::new(snapshot.clone())}).unwrap())).await.unwrap(); + let key_context="fake-profile.cell.2"; + host.send(Message::text(json!({"event":"willAppear","action":host::CELL,"context":key_context,"device":"sd-FAKE","payload":{"controller":"Keypad","coordinates":{"row":0,"column":2}}}).to_string())).await.unwrap(); + host.send(Message::text(json!({"event":"willAppear","action":host::INFOBAR,"context":"fake-profile.infobar","device":"sd-FAKE","payload":{"controller":"Infobar","coordinates":{"row":0,"column":0}}}).to_string())).await.unwrap(); + let expected=render::data_uri(&render::bar(&Deck::default(),Some(&snapshot),Duration::ZERO,Duration::ZERO)).unwrap(); + let mut saw_key=false; + loop { + let message=host.next().await.unwrap().unwrap(); + if let Message::Text(text)=message {let event:Value=serde_json::from_str(&text).unwrap(); + if event["context"]==key_context {let data=event["payload"]["image"].as_str().unwrap().split_once(',').unwrap().1;let bytes=base64::engine::general_purpose::STANDARD.decode(data).unwrap();assert_eq!(image::load_from_memory(&bytes).unwrap().dimensions(),(96,96));saw_key=true;} + if event["payload"]["image"]==expected {break;} + } + } + assert!(saw_key); + for kind in ["keyDown","keyUp"] {host.send(Message::text(json!({"event":kind,"context":key_context,"device":"sd-FAKE"}).to_string())).await.unwrap();} + let command:ClientMessage=serde_json::from_slice(&api.next().await.unwrap().unwrap().into_data()).unwrap(); + assert!(matches!(command,ClientMessage::Command{command:Command::PlayPause,..})); + host.send(Message::text(json!({"event":"didReceiveGlobalSettings","payload":{"settings":{"future":{"keep":42}}}}).to_string())).await.unwrap(); + for (action,context,patch) in [(host::CELL,key_context,json!({"album_art_2x2":true})),(host::INFOBAR,"fake-profile.infobar",json!({"invert_colors":true}))] { + host.send(Message::text(json!({"event":"sendToPlugin","action":action,"context":context,"payload":{"event":"preferencesPatch","patch":patch}}).to_string())).await.unwrap(); + } + let mut writes=Vec::new();while writes.len()<2 {let item=host.next().await.unwrap().unwrap();if let Message::Text(text)=item {let event:Value=serde_json::from_str(&text).unwrap();if event["event"]=="setGlobalSettings" {assert_eq!(event["context"],host::PLUGIN);writes.push(event["payload"].clone());}}} + assert_eq!(writes[1]["album_art_2x2"],true);assert_eq!(writes[1]["invert_colors"],true);assert_eq!(writes[1]["future"]["keep"],42); + host.close(None).await.unwrap(); + plugin.await.unwrap().unwrap(); + }).await.expect("mock host/API must finish without real configuration, peers or hardware"); + } +} diff --git a/integrations/opendeck/src/model.rs b/integrations/opendeck/src/model.rs new file mode 100644 index 0000000..446cb30 --- /dev/null +++ b/integrations/opendeck/src/model.rs @@ -0,0 +1,751 @@ +//! One navigation state per physical deck. A press captures the visible target, +//! so device arrivals/reordering between keyDown and keyUp cannot redirect it. +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +use furumi_control_protocol::{Command, Device, RadioState, RemoteCommandState, Role, Snapshot}; + +pub const DEVICES_PER_PAGE: usize = 6; +const REMOTE_FALLBACK: Duration = Duration::from_secs(45); + +pub fn conflicts_with_remote_playback(command: &Command) -> bool { + !matches!(command, Command::Transfer { .. } | Command::Artwork { .. }) +} + +#[derive(Clone, Debug)] +struct RemoteLatch { + request_id: Option, + baseline: u64, + observed: Option, + started: Instant, +} + +/// One canonical instance belongs to Surface; each deck receives a clone for +/// rendering/routing. This also blocks a second physical deck between snapshots. +#[derive(Clone, Debug, Default)] +pub struct RemoteGate { + initialized: bool, + owner: Option, + last_id: Option, + latch: Option, + abandoned: Option, +} + +impl RemoteGate { + pub fn waiting(&self, snapshot: Option<&Snapshot>) -> bool { + snapshot.is_some_and(|s| s.role == Role::Control && s.active_device_id == self.owner) + && self.latch.is_some() + } + + pub fn started(&self) -> Option { + self.latch.as_ref().map(|latch| latch.started) + } + + /// Legacy local servers advertise no acknowledgement capability. Preserve + /// their existing command behaviour rather than wait for an absent field. + pub fn begin(&mut self, snapshot: &Snapshot, request_id: String, now: Instant) { + if snapshot.role != Role::Control { + return; + } + let Some(status) = &snapshot.remote_command else { + return; + }; + self.owner = snapshot.active_device_id.clone(); + self.initialized = true; + self.latch = Some(RemoteLatch { + request_id: Some(request_id), + baseline: status.id, + observed: None, + started: now, + }); + } + + pub fn reject(&mut self, id: &str) -> bool { + if self + .latch + .as_ref() + .is_some_and(|latch| latch.request_id.as_deref() == Some(id)) + { + if let Some(mut latch) = self.latch.take() { + if let Some(observed) = latch.observed { + // Another input may have reached the TUI first. Rejecting + // this local request does not cancel an authoritative + // pending command already seen in a snapshot. + latch.request_id = None; + latch.baseline = observed; + self.latch = Some(latch); + } else { + self.abandoned = Some(latch.baseline); + } + } + return true; + } + false + } + + pub fn observe(&mut self, snapshot: &Snapshot, now: Instant) -> Option { + if snapshot.role != Role::Control { + *self = Self::default(); + return None; + } + if self.initialized && snapshot.active_device_id != self.owner { + *self = Self { + initialized: true, + owner: snapshot.active_device_id.clone(), + last_id: snapshot.remote_command.as_ref().map(|status| status.id), + abandoned: snapshot.remote_command.as_ref().map(|status| status.id), + ..Self::default() + }; + return None; + } + self.initialized = true; + self.owner = snapshot.active_device_id.clone(); + let Some(status) = &snapshot.remote_command else { + self.latch = None; + self.last_id = None; + self.abandoned = None; + return None; + }; + let mut error = None; + if let Some(latch) = &mut self.latch { + let newer = latch + .observed + .map_or(status.id > latch.baseline, |id| status.id >= id); + if newer { + match status.state { + RemoteCommandState::Pending => latch.observed = Some(status.id), + RemoteCommandState::Confirmed => { + self.latch = None; + self.abandoned = Some(status.id); + } + RemoteCommandState::Failed => { + self.latch = None; + self.abandoned = Some(status.id); + error = Some(remote_error(status.error.as_deref())); + } + // An idle snapshot may have been queued before dispatch. + RemoteCommandState::Idle => {} + } + } + } else if status.state == RemoteCommandState::Pending + && self.abandoned.is_none_or(|id| status.id > id) + && self.last_id.is_none_or(|id| status.id >= id) + { + self.latch = Some(RemoteLatch { + request_id: None, + baseline: status.id, + observed: Some(status.id), + started: now, + }); + } else if status.state == RemoteCommandState::Failed + && self.last_id.is_some_and(|id| status.id > id) + { + error = Some(remote_error(status.error.as_deref())); + } + self.last_id = Some(self.last_id.map_or(status.id, |id| id.max(status.id))); + if self.latch.is_none() + && matches!( + status.state, + RemoteCommandState::Confirmed | RemoteCommandState::Failed + ) + { + self.abandoned = Some(self.abandoned.map_or(status.id, |id| id.max(status.id))); + } + error.or_else(|| self.expire(now)) + } + + pub fn expire(&mut self, now: Instant) -> Option { + if self + .latch + .as_ref() + .is_some_and(|latch| now.saturating_duration_since(latch.started) >= REMOTE_FALLBACK) + { + if let Some(latch) = self.latch.take() { + self.abandoned = Some(latch.observed.unwrap_or(latch.baseline)); + } + return Some("Remote command timed out".into()); + } + None + } +} + +fn remote_error(error: Option<&str>) -> String { + let value = error + .and_then(|value| value.lines().next()) + .filter(|value| !value.trim().is_empty()) + .unwrap_or("Remote command failed"); + let mut short: String = value.chars().take(72).collect(); + if value.chars().count() > 72 { + short.push('…'); + } + short +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Binding { + Command(Command), + Functions, + Devices, + NextPage, + Back, + Disabled, +} + +#[derive(Clone, Debug)] +pub enum Screen { + Player, + Functions, + Devices { + page: usize, + targets: Vec, + name_since: [Instant; DEVICES_PER_PAGE], + }, +} + +#[derive(Clone, Debug)] +pub struct PendingTransfer { + pub request_id: String, + pub device_id: String, + pub started: Instant, +} + +pub struct PendingRadio { + pub request_id: String, + pub baseline: u64, + pub started: Instant, +} + +pub struct Deck { + pub screen: Screen, + pub presses: BTreeMap, + pub pending: Option, + pub radio: Option, + pub notice: Option<(String, Instant)>, + pub remote: RemoteGate, + pub artwork_loading: Option, + pub preferences: crate::settings::Preferences, +} + +impl Default for Deck { + fn default() -> Self { + Self { + screen: Screen::Player, + presses: BTreeMap::new(), + pending: None, + radio: None, + notice: None, + remote: RemoteGate::default(), + artwork_loading: None, + preferences: crate::settings::Preferences::default(), + } + } +} + +impl Deck { + pub fn targets(snapshot: &Snapshot) -> Vec { + let mut devices: Vec<_> = snapshot + .devices + .iter() + .filter(|d| d.online || d.is_self) + .cloned() + .collect(); + devices.sort_by(|a, b| { + b.is_self + .cmp(&a.is_self) + .then_with(|| a.name.cmp(&b.name)) + .then_with(|| a.id.cmp(&b.id)) + }); + devices + } + + pub fn binding(&self, slot: usize, snapshot: Option<&Snapshot>) -> Binding { + if self.pending.is_some() { + return Binding::Disabled; + } + let binding = match &self.screen { + Screen::Player => match slot { + 0 => Binding::Functions, + 1 => Binding::Command(Command::Previous), + 2 => Binding::Command(Command::PlayPause), + 3 => Binding::Command(Command::Next), + 4 => Binding::Command(Command::CycleRepeat), + 5 => Binding::Command(Command::ToggleShuffle), + 6 => Binding::Command(Command::Seek { seconds: -10 }), + 7 => Binding::Command(Command::Seek { seconds: 30 }), + _ => Binding::Disabled, + }, + Screen::Functions => match slot { + 0 if self.radio.is_none() => Binding::Command(Command::StartRadio), + 1 => Binding::Devices, + 7 => Binding::Back, + _ => Binding::Disabled, + }, + Screen::Devices { page, targets, .. } => match slot { + 7 => Binding::Back, + 6 if targets.len() > DEVICES_PER_PAGE => Binding::NextPage, + 0..=5 => targets + .get(page * DEVICES_PER_PAGE + slot) + .filter(|d| d.can_transfer && !d.active) + .map_or(Binding::Disabled, |d| { + Binding::Command(Command::Transfer { + device_id: d.id.clone(), + }) + }), + _ => Binding::Disabled, + }, + }; + if snapshot.is_none() && matches!(&binding, Binding::Command(_)) { + return Binding::Disabled; + } + if self.remote.waiting(snapshot) + && matches!(&binding,Binding::Command(command) if conflicts_with_remote_playback(command)) + { + Binding::Disabled + } else { + binding + } + } + + pub fn release(&mut self, binding: Binding, snapshot: Option<&Snapshot>) -> Option { + // Recheck liveness and capability; the captured ID is never replaced by + // the device that happens to occupy that cell in a newer snapshot. + let Some(snapshot) = snapshot else { + match binding { + Binding::Functions => self.screen = Screen::Functions, + Binding::Devices => { + self.screen = Screen::Devices { + page: 0, + targets: Vec::new(), + name_since: [Instant::now(); DEVICES_PER_PAGE], + } + } + Binding::Back => { + self.screen = if matches!(self.screen, Screen::Devices { .. }) { + Screen::Functions + } else { + Screen::Player + } + } + _ => {} + } + return None; + }; + if self.remote.waiting(Some(snapshot)) + && matches!(&binding,Binding::Command(command) if conflicts_with_remote_playback(command)) + { + return None; + } + if self.pending.is_some() { + return None; + } + if self.radio.is_some() && binding == Binding::Command(Command::StartRadio) { + return None; + } + if binding != Binding::Disabled { + self.notice = None; + } + match binding { + Binding::Functions => { + self.screen = Screen::Functions; + None + } + Binding::Devices => { + self.screen = Screen::Devices { + page: 0, + targets: Self::targets(snapshot), + name_since: [Instant::now(); DEVICES_PER_PAGE], + }; + None + } + Binding::NextPage => { + if let Screen::Devices { + page, + targets, + name_since, + } = &mut self.screen + { + *targets = Self::targets(snapshot); + *page = (*page + 1) % targets.len().div_ceil(DEVICES_PER_PAGE).max(1); + name_since.fill(Instant::now()); + } + None + } + Binding::Back => { + self.screen = if matches!(self.screen, Screen::Devices { .. }) { + Screen::Functions + } else { + Screen::Player + }; + None + } + Binding::Command(Command::Transfer { device_id }) => { + if snapshot.devices.iter().any(|d| { + d.id == device_id && (d.online || d.is_self) && d.can_transfer && !d.active + }) { + Some(Command::Transfer { device_id }) + } else { + self.notice = Some(("Device unavailable".into(), Instant::now())); + None + } + } + Binding::Command(command) => Some(command), + Binding::Disabled => None, + } + } + + pub fn update(&mut self, snapshot: &Snapshot) { + if let Some(pending) = &self.pending { + // Accepted only means local dispatch; do not show confirmed remote + // playback before the deadline or invent an acknowledgement. + if pending.started.elapsed() > Duration::from_secs(10) { + self.pending = None; + self.notice = Some(("Transfer not confirmed".into(), Instant::now())); + } else if snapshot.active_device_id.as_deref() == Some(&pending.device_id) { + self.screen = Screen::Player; + // Ownership snapshot is useful feedback, but not an audio ACK. + self.pending = None; + } + } + if let Some(radio) = &self.radio { + if snapshot.radio.id > radio.baseline && snapshot.radio.state == RadioState::Playing { + self.screen = Screen::Player; + self.radio = None; + } else if snapshot.radio.id > radio.baseline + && snapshot.radio.state == RadioState::Failed + { + self.notice = Some(( + snapshot + .radio + .error + .clone() + .unwrap_or_else(|| "Radio failed".into()), + Instant::now(), + )); + self.radio = None; + } else if radio.started.elapsed() > Duration::from_secs(240) { + self.notice = Some(("Radio timed out".into(), Instant::now())); + self.radio = None; + } + } + if self.presses.is_empty() + && let Screen::Devices { + page, + targets, + name_since, + } = &mut self.screen + { + let next = Self::targets(snapshot); + let next_page = (*page).min(next.len().saturating_sub(1) / DEVICES_PER_PAGE); + let now = Instant::now(); + for (slot, since) in name_since.iter_mut().enumerate() { + let old = targets.get(*page * DEVICES_PER_PAGE + slot); + let new = next.get(next_page * DEVICES_PER_PAGE + slot); + if old.map(|d| (&d.id, &d.name)) != new.map(|d| (&d.id, &d.name)) { + *since = now; + } + } + *targets = next; + *page = next_page; + } + if self.notice.as_ref().is_some_and(|(message, at)| { + at.elapsed() + > Duration::from_secs((message.chars().count() as u64 / 2 + 5).clamp(6, 45)) + }) { + self.notice = None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::preview::fixture; + use furumi_control_protocol::RemoteCommand; + + fn controlled() -> Snapshot { + let mut snapshot = fixture(); + snapshot.role = Role::Control; + snapshot.active_device_id = Some("laptop".into()); + snapshot.remote_command = Some(RemoteCommand::default()); + snapshot + } + + #[test] + fn remote_latch_ignores_idle_and_old_confirmation_until_new_command_finishes() { + let now = Instant::now(); + let mut snapshot = controlled(); + snapshot.remote_command.as_mut().unwrap().id = 4; + let mut gate = RemoteGate::default(); + gate.observe(&snapshot, now); + gate.begin(&snapshot, "request-5".into(), now); + assert!(gate.waiting(Some(&snapshot))); + gate.observe(&snapshot, now); + assert!(gate.waiting(Some(&snapshot))); + snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Confirmed; + gate.observe(&snapshot, now); + assert!(gate.waiting(Some(&snapshot))); + snapshot.remote_command = Some(RemoteCommand { + id: 5, + state: RemoteCommandState::Pending, + error: None, + }); + gate.observe(&snapshot, now); + assert!(gate.waiting(Some(&snapshot))); + snapshot.remote_command = Some(RemoteCommand { + id: 4, + state: RemoteCommandState::Idle, + error: None, + }); + gate.observe(&snapshot, now); + assert!(gate.waiting(Some(&snapshot))); + snapshot.remote_command = Some(RemoteCommand { + id: 5, + state: RemoteCommandState::Confirmed, + error: None, + }); + gate.observe(&snapshot, now); + assert!(!gate.waiting(Some(&snapshot))); + snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Pending; + gate.observe(&snapshot, now); + assert!( + !gate.waiting(Some(&snapshot)), + "stale pending cannot restart a completed command" + ); + } + + #[test] + fn authoritative_pending_blocks_keyboard_and_radio_conflicts_but_not_navigation_or_transfer() { + let now = Instant::now(); + let mut snapshot = controlled(); + snapshot.remote_command = Some(RemoteCommand { + id: 8, + state: RemoteCommandState::Pending, + error: None, + }); + let mut deck = Deck::default(); + deck.remote.observe(&snapshot, now); + for slot in 1..8 { + assert_eq!(deck.binding(slot, Some(&snapshot)), Binding::Disabled); + } + assert_eq!(deck.binding(0, Some(&snapshot)), Binding::Functions); + // A command captured before the authoritative snapshot is rechecked. + assert!( + deck.release(Binding::Command(Command::Next), Some(&snapshot)) + .is_none() + ); + deck.release(Binding::Functions, Some(&snapshot)); + assert_eq!(deck.binding(0, Some(&snapshot)), Binding::Disabled); + assert_eq!(deck.binding(1, Some(&snapshot)), Binding::Devices); + deck.release(Binding::Devices, Some(&snapshot)); + assert!(matches!( + deck.binding(1, Some(&snapshot)), + Binding::Command(Command::Transfer { .. }) + )); + } + + #[test] + fn remote_failure_reject_owner_change_and_legacy_servers_release_local_wait() { + let now = Instant::now(); + let mut snapshot = controlled(); + let mut gate = RemoteGate::default(); + gate.begin(&snapshot, "rejected".into(), now); + assert!(gate.reject("rejected")); + assert!(!gate.waiting(Some(&snapshot))); + gate.begin(&snapshot, "failed".into(), now); + snapshot.remote_command = Some(RemoteCommand { + id: 1, + state: RemoteCommandState::Failed, + error: Some("Output unavailable".into()), + }); + assert_eq!( + gate.observe(&snapshot, now), + Some("Output unavailable".into()) + ); + assert!(!gate.waiting(Some(&snapshot))); + gate.begin(&snapshot, "changed-owner".into(), now); + snapshot.active_device_id = Some("studio".into()); + gate.observe(&snapshot, now); + assert!(!gate.waiting(Some(&snapshot))); + snapshot.remote_command = None; + gate.begin(&snapshot, "legacy".into(), now); + assert!(!gate.waiting(Some(&snapshot))); + snapshot.remote_command = Some(RemoteCommand { + id: 2, + state: RemoteCommandState::Pending, + error: None, + }); + snapshot.role = Role::Jam; + gate.observe(&snapshot, now); + assert!(!gate.waiting(Some(&snapshot))); + } + + #[test] + fn remote_timeout_is_bounded_and_same_pending_snapshot_cannot_relock() { + let now = Instant::now(); + let mut snapshot = controlled(); + let mut gate = RemoteGate::default(); + gate.begin(&snapshot, "slow".into(), now); + snapshot.remote_command = Some(RemoteCommand { + id: 1, + state: RemoteCommandState::Pending, + error: None, + }); + gate.observe(&snapshot, now); + assert_eq!( + gate.expire(now + REMOTE_FALLBACK), + Some("Remote command timed out".into()) + ); + assert!(!gate.waiting(Some(&snapshot))); + gate.observe(&snapshot, now + REMOTE_FALLBACK); + assert!(!gate.waiting(Some(&snapshot))); + snapshot.remote_command.as_mut().unwrap().id = 2; + gate.observe(&snapshot, now + REMOTE_FALLBACK); + assert!(gate.waiting(Some(&snapshot))); + } + + #[test] + fn rejecting_our_racing_request_preserves_another_authoritative_pending_command() { + let now = Instant::now(); + let mut snapshot = controlled(); + let mut gate = RemoteGate::default(); + gate.begin(&snapshot, "ours".into(), now); + snapshot.remote_command = Some(RemoteCommand { + id: 1, + state: RemoteCommandState::Pending, + error: None, + }); + gate.observe(&snapshot, now); + gate.reject("ours"); + assert!(gate.waiting(Some(&snapshot))); + snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Confirmed; + gate.observe(&snapshot, now); + assert!(!gate.waiting(Some(&snapshot))); + } + + #[test] + fn press_keeps_identity_when_devices_reorder_or_disappear() { + let mut snapshot = fixture(); + let mut deck = Deck::default(); + deck.release(Binding::Devices, Some(&snapshot)); + let binding = deck.binding(1, Some(&snapshot)); + let Binding::Command(Command::Transfer { device_id }) = &binding else { + panic!("target") + }; + snapshot.devices.retain(|d| &d.id != device_id); + assert_eq!(deck.release(binding, Some(&snapshot)), None); + } + + #[test] + fn navigation_does_not_reuse_release_as_new_screen_command() { + let snapshot = fixture(); + let mut deck = Deck::default(); + let press = deck.binding(0, Some(&snapshot)); + assert_eq!(deck.release(press, Some(&snapshot)), None); + assert!(matches!(deck.screen, Screen::Functions)); + let press = deck.binding(1, Some(&snapshot)); + assert_eq!(deck.release(press, Some(&snapshot)), None); + assert!(matches!(deck.screen, Screen::Devices { .. })); + assert_eq!(deck.binding(7, Some(&snapshot)), Binding::Back); + } + + #[test] + fn a_renamed_device_restarts_only_its_own_marquee() { + let mut s = fixture(); + let mut deck = Deck::default(); + deck.release(Binding::Devices, Some(&s)); + let earlier = Instant::now() - Duration::from_secs(4); + let Screen::Devices { name_since, .. } = &mut deck.screen else { + unreachable!() + }; + name_since.fill(earlier); + s.position_secs += 1.0; + s.devices[0].active = false; + deck.update(&s); + let Screen::Devices { name_since, .. } = &deck.screen else { + unreachable!() + }; + assert_eq!(name_since, &[earlier; DEVICES_PER_PAGE]); + s.devices[0].name = "New local name".into(); + deck.update(&s); + let Screen::Devices { name_since, .. } = &deck.screen else { + unreachable!() + }; + assert!(name_since[0] > earlier); + assert!(name_since[1..].iter().all(|since| *since == earlier)); + } + + #[test] + fn pagination_wraps_and_devices_are_independent() { + let mut snapshot = fixture(); + for n in 0..9 { + let mut d = snapshot.devices[1].clone(); + d.id = format!("extra-{n}"); + d.name = d.id.clone(); + snapshot.devices.push(d); + } + let mut a = Deck::default(); + let b = Deck::default(); + a.release(Binding::Devices, Some(&snapshot)); + a.release(Binding::NextPage, Some(&snapshot)); + assert!(matches!(a.screen, Screen::Devices { page: 1, .. })); + assert!(matches!(b.screen, Screen::Player)); + assert_eq!(a.binding(7, Some(&snapshot)), Binding::Back); + a.release(Binding::NextPage, Some(&snapshot)); + a.release(Binding::NextPage, Some(&snapshot)); + assert!(matches!(a.screen, Screen::Devices { page: 0, .. })); + } + + #[test] + fn radio_waits_for_new_operation_and_actual_playback() { + let mut snapshot = fixture(); + snapshot.radio.id = 10; + snapshot.radio.state = RadioState::Playing; + let mut deck = Deck { + screen: Screen::Functions, + radio: Some(PendingRadio { + request_id: "radio-11".into(), + baseline: 10, + started: Instant::now(), + }), + ..Deck::default() + }; + deck.update(&snapshot); + assert!(deck.radio.is_some()); + snapshot.radio.id = 11; + snapshot.radio.state = RadioState::Searching; + deck.update(&snapshot); + assert!(deck.radio.is_some()); + snapshot.radio.state = RadioState::Starting; + deck.update(&snapshot); + assert!(deck.radio.is_some()); + snapshot.radio.state = RadioState::Playing; + snapshot.paused = true; + deck.update(&snapshot); + // Started is an explicit acknowledged state. A pause before the next + // snapshot must not leave an already-started radio spinning forever. + assert!(deck.radio.is_none()); + assert!(matches!(deck.screen, Screen::Player)); + } + + #[test] + fn device_back_returns_to_functions_and_new_main_layout_routes_repeat_shuffle() { + let snapshot = fixture(); + let mut deck = Deck::default(); + assert_eq!( + deck.binding(4, Some(&snapshot)), + Binding::Command(Command::CycleRepeat) + ); + assert_eq!( + deck.binding(5, Some(&snapshot)), + Binding::Command(Command::ToggleShuffle) + ); + deck.release(Binding::Functions, Some(&snapshot)); + assert_eq!( + deck.binding(0, Some(&snapshot)), + Binding::Command(Command::StartRadio) + ); + deck.release(Binding::Devices, Some(&snapshot)); + deck.release(Binding::Back, Some(&snapshot)); + assert!(matches!(deck.screen, Screen::Functions)); + } +} diff --git a/integrations/opendeck/src/preview.rs b/integrations/opendeck/src/preview.rs new file mode 100644 index 0000000..460abd9 --- /dev/null +++ b/integrations/opendeck/src/preview.rs @@ -0,0 +1,465 @@ +use std::path::Path; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use furumi_control_protocol::{ + API_VERSION, Device, Radio, RemoteCommand, RemoteCommandState, Repeat, Role, Snapshot, Track, +}; +use image::{Rgb, RgbImage}; + +use crate::model::{Binding, Deck, Screen}; +use crate::render; + +const PANEL_WIDTH: u32 = 64 + crate::artwork::KEY_PIXELS * 4 + crate::artwork::GAP_PX * 3; +const PANEL_HEIGHT: u32 = 343; +const BAR_Y: i64 = 273; + +pub fn fixture() -> Snapshot { + let devices = [ + ("self", "This PC"), + ("laptop", "Laptop"), + ("studio", "Studio"), + ("lounge", "Living room speakers"), + ("mac", "MacBook"), + ] + .into_iter() + .map(|(id, name)| Device { + id: id.into(), + name: name.into(), + is_self: id == "self", + active: id == "self", + online: true, + can_transfer: true, + unavailable_reason: None, + }) + .collect(); + Snapshot { + api_version: API_VERSION, + revision: 1, + updated_at_ms: 0, + role: Role::Active, + self_device_id: "self".into(), + active_device_id: Some("self".into()), + active_device_name: Some("This PC".into()), + playing: true, + paused: false, + position_secs: 83.0, + duration_secs: 245.0, + volume: 70, + shuffle: false, + repeat: Repeat::Off, + radio: Radio::default(), + remote_command: Some(Default::default()), + spectrum_supported: false, + track: Some(Track { + key: "preview-track".into(), + title: "Midnight City".into(), + artist: "M83".into(), + album: "Hurry Up, We're Dreaming".into(), + year: Some(2011), + artwork_id: None, + }), + devices, + } +} + +/// Offline examples at device resolution. Each pair receives identical band frames. +fn infobar_backgrounds(directory: &Path) -> Result<()> { + use crate::settings::InfobarBackground; + use crate::spectrum::{Frame, History}; + let snapshot = fixture(); + let mut deck = Deck::default(); + let modes = [ + ("Spectrogram", InfobarBackground::Spectrogram), + ("Bars", InfobarBackground::Bars), + ]; + let cases = [ + ("Quiet passage", 14usize, 85.0), + ("Bass hit", 6, 242.0), + ("Treble hit", 24, 242.0), + ]; + let mut sheet = RgbImage::from_pixel(2 * render::BAR_WIDTH + 36, 296, Rgb([24, 27, 32])); + for (column, (label, _)) in modes.iter().enumerate() { + let x = 12 + column as i32 * (render::BAR_WIDTH as i32 + 12); + render::preview_label(&mut sheet, label, x, 8, render::BAR_WIDTH as i32); + } + for (row, (label, center, amplitude)) in cases.into_iter().enumerate() { + let mut history = History::default(); + for sequence in 1..=232 { + let phase = ((sequence + 8) % 12) as f32; + let pulse = (-phase / 4.5).exp(); + let bands = std::array::from_fn(|band: usize| { + let distance = band.abs_diff(center) as f32 / 3.1; + let emphasis = (-0.5 * distance.powi(2)).exp(); + let texture = ((band as f32 * 0.94 + sequence as f32 * 0.12).sin() + 1.0) * 0.09; + (amplitude * (0.09 + texture + emphasis * (0.2 + 0.64 * pulse))).min(255.0) as u8 + }); + history.ingest(Frame { + epoch: 1, + sequence, + bands: Some(bands), + }); + } + let y = 32 + row as i32 * 88; + render::preview_label(&mut sheet, label, 12, y, 240); + for (column, (_, mode)) in modes.iter().enumerate() { + deck.preferences.infobar_background = *mode; + let frame = render::bar_with_spectrum( + &deck, + Some(&snapshot), + Duration::ZERO, + Duration::ZERO, + Some(&history), + ); + let x = 12 + column as i64 * (i64::from(render::BAR_WIDTH) + 12); + image::imageops::overlay(&mut sheet, &frame, x, i64::from(y + 20)); + } + } + sheet.save(directory.join("infobar-backgrounds.png"))?; + Ok(()) +} + +fn appearance(directory: &Path, artwork: &crate::artwork::PreparedArt) -> Result<()> { + use crate::settings::InfobarBackground; + let mut history = crate::spectrum::History::default(); + for sequence in 1..=232 { + let bands = std::array::from_fn(|band| { + let t = sequence as f32 * 0.075; + let frequency = band as f32 * 0.31; + ((t.sin() * frequency.cos() * 0.5 + 0.5) * 210.0) as u8 + }); + history.ingest(crate::spectrum::Frame { + epoch: 1, + sequence, + bands: Some(bands), + }); + } + let mut sheet = RgbImage::from_pixel( + PANEL_WIDTH * 2 + 48, + (PANEL_HEIGHT + 44) * 4 + 10, + Rgb([24, 27, 32]), + ); + let labels = [ + "Default / plain Infobar", + "2x2 art / 41px physical gaps", + "Inverted Active / fixture spectrum", + "Inverted 2x2 / fixture bars", + "Inverted Control / no local spectrum", + "Inverted Jam host / fixture spectrum", + "Inverted Functions", + "Inverted Devices", + ]; + let now = Instant::now(); + for (index, label) in labels.into_iter().enumerate() { + let mut snapshot = fixture(); + snapshot.spectrum_supported = true; + snapshot.repeat = Repeat::One; + snapshot.shuffle = true; + let mut deck = Deck::default(); + deck.preferences.album_art_2x2 = matches!(index, 1 | 3); + deck.preferences.invert_colors = index >= 2; + if matches!(index, 2 | 5) { + deck.preferences.infobar_background = InfobarBackground::Spectrogram; + } else if index == 3 { + deck.preferences.infobar_background = InfobarBackground::Bars; + } + if index == 4 { + snapshot.role = Role::Control; + snapshot.active_device_id = Some("laptop".into()); + snapshot.active_device_name = Some("Laptop".into()); + } + if index == 5 { + snapshot.role = Role::Jam; + } + if index == 6 { + deck.screen = Screen::Functions; + } + if index == 7 { + deck.release(Binding::Devices, Some(&snapshot)); + } + let mut panel = RgbImage::from_pixel(PANEL_WIDTH, PANEL_HEIGHT, Rgb([218, 221, 224])); + for slot in 0..8 { + let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(artwork), now); + image::imageops::overlay( + &mut panel, + &key, + 32 + (slot % 4) as i64 * i64::from(crate::artwork::KEY_STRIDE), + 16 + (slot / 4) as i64 * i64::from(crate::artwork::KEY_STRIDE), + ); + key.save(directory.join(format!("appearance-{index}-key-{slot}.png")))?; + } + let bar = render::bar_with_spectrum( + &deck, + Some(&snapshot), + Duration::ZERO, + Duration::ZERO, + Some(&history), + ); + bar.save(directory.join(format!("appearance-{index}-infobar.png")))?; + image::imageops::overlay(&mut panel, &bar, i64::from((PANEL_WIDTH - 248) / 2), BAR_Y); + let x = 16 + (index % 2) as i64 * i64::from(PANEL_WIDTH + 16); + let y = 10 + (index / 2) as i64 * i64::from(PANEL_HEIGHT + 44); + render::preview_label(&mut sheet, label, x as i32, y as i32, PANEL_WIDTH as i32); + image::imageops::overlay(&mut sheet, &panel, x, y + 24); + } + sheet.save(directory.join("appearance-options.png"))?; + let mut mosaic = RgbImage::from_pixel( + crate::artwork::PHYSICAL_MOSAIC_SIZE, + crate::artwork::PHYSICAL_MOSAIC_SIZE, + Rgb([218, 221, 224]), + ); + let mut deck = Deck::default(); + deck.preferences.album_art_2x2 = true; + let snapshot = fixture(); + for (slot, x, y) in [ + (0, 0, 0), + (1, crate::artwork::KEY_STRIDE, 0), + (4, 0, crate::artwork::KEY_STRIDE), + (5, crate::artwork::KEY_STRIDE, crate::artwork::KEY_STRIDE), + ] { + let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(artwork), now); + image::imageops::overlay(&mut mosaic, &key, i64::from(x), i64::from(y)); + } + mosaic.save(directory.join("album-2x2-layout.png"))?; + let mut comparison = RgbImage::from_pixel(233 * 3 + 64, 273, Rgb([24, 27, 32])); + for (index, label) in ["Both off", "Repeat One enabled", "Shuffle enabled"] + .into_iter() + .enumerate() + { + let mut snapshot = fixture(); + snapshot.repeat = if index == 1 { Repeat::One } else { Repeat::Off }; + snapshot.shuffle = index == 2; + let mut mosaic = RgbImage::from_pixel(233, 233, Rgb([218, 221, 224])); + for (slot, x, y) in [(0, 0, 0), (1, 137, 0), (4, 0, 137), (5, 137, 137)] { + let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(artwork), now); + image::imageops::overlay(&mut mosaic, &key, x, y); + } + let x = 16 + index as i64 * 249; + render::preview_label(&mut comparison, label, x as i32, 8, 233); + image::imageops::overlay(&mut comparison, &mosaic, x, 32); + } + comparison.save(directory.join("album-overlay-controls.png"))?; + Ok(()) +} + +pub fn write(directory: &Path) -> Result<()> { + std::fs::create_dir_all(directory)?; + let mut sheet = RgbImage::from_pixel( + PANEL_WIDTH * 2 + 48, + (PANEL_HEIGHT + 15) * 4 + 10, + Rgb([24, 27, 32]), + ); + // Deliberately synthetic cover fixture; no copyrighted album artwork is + // bundled. It demonstrates an untinted full-bleed artwork key. + let mut artwork = RgbImage::new(384, 384); + for (x, y, p) in artwork.enumerate_pixels_mut() { + let (sx, sy) = (x / 4, y / 4); + let horizon = 52; + *p = if sy < horizon { + Rgb([ + 20 + (sx / 3) as u8, + 35 + (sy / 2) as u8, + 90 + (sx / 2) as u8, + ]) + } else { + Rgb([100 + (sx / 2) as u8, 35 + (sy / 3) as u8, 65]) + }; + if (sx as i32 - 62).pow(2) + (sy as i32 - 28).pow(2) < 100 { + *p = Rgb([244, 169, 81]); + } + } + artwork.save(directory.join("cover-fixture.png"))?; + let prepared = crate::artwork::PreparedArt::new(artwork.clone()); + for (index, name) in [ + "active", + "control", + "jam", + "functions", + "devices", + "radio-starting", + "control-pending", + "control-confirmed", + ] + .iter() + .enumerate() + { + let mut snapshot = fixture(); + let mut deck = Deck::default(); + if *name == "active" { + snapshot.repeat = Repeat::All; + snapshot.shuffle = true; + } + if name.starts_with("control") { + snapshot.role = Role::Control; + snapshot.paused = true; + snapshot.active_device_id = Some("laptop".into()); + snapshot.active_device_name = Some("Laptop".into()); + snapshot.shuffle = true; + } + if *name == "control-pending" { + snapshot.remote_command = Some(RemoteCommand { + id: 7, + state: RemoteCommandState::Pending, + error: None, + }); + deck.remote.observe(&snapshot, Instant::now()); + } + if *name == "control-confirmed" { + snapshot.paused = false; + snapshot.remote_command = Some(RemoteCommand { + id: 7, + state: RemoteCommandState::Confirmed, + error: None, + }); + } + if *name == "jam" { + snapshot.role = Role::Jam; + snapshot.active_device_name = Some("Studio".into()); + snapshot.repeat = Repeat::One; + } + if *name == "functions" || *name == "radio-starting" { + deck.screen = Screen::Functions; + } + if *name == "radio-starting" { + deck.radio = Some(crate::model::PendingRadio { + request_id: "preview".into(), + baseline: 0, + started: std::time::Instant::now(), + }); + } + if *name == "devices" { + deck.release(Binding::Devices, Some(&snapshot)); + } + let now = Instant::now(); + if let Screen::Devices { targets, .. } = &deck.screen + && let Some(slot) = targets.iter().position(|d| d.id == "lounge") + { + for seconds in [0, 4, 7] { + render::key( + slot, + &deck, + Some(&snapshot), + None, + now + Duration::from_secs(seconds), + ) + .save(directory.join(format!("device-name-{seconds}s.png")))?; + } + } + let mut panel = RgbImage::from_pixel(PANEL_WIDTH, PANEL_HEIGHT, Rgb([218, 221, 224])); + for slot in 0..8 { + let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(&prepared), now); + key.save(directory.join(format!("{name}-key-{slot}.png")))?; + image::imageops::overlay( + &mut panel, + &key, + 32 + (slot % 4) as i64 * i64::from(crate::artwork::KEY_STRIDE), + 16 + (slot / 4) as i64 * i64::from(crate::artwork::KEY_STRIDE), + ); + } + let bar = render::bar(&deck, Some(&snapshot), Duration::ZERO, Duration::ZERO); + bar.save(directory.join(format!("{name}-infobar.png")))?; + image::imageops::overlay(&mut panel, &bar, i64::from((PANEL_WIDTH - 248) / 2), BAR_Y); + panel.save(directory.join(format!("{name}-screen.png")))?; + image::imageops::overlay( + &mut sheet, + &panel, + 16 + (index % 2) as i64 * i64::from(PANEL_WIDTH + 16), + 10 + (index / 2) as i64 * i64::from(PANEL_HEIGHT + 15), + ); + } + sheet.save(directory.join("all-screens.png"))?; + appearance(directory, &prepared)?; + infobar_backgrounds(directory)?; + let mut covers = RgbImage::from_pixel(856, 168, Rgb([24, 27, 32])); + render::preview_label( + &mut covers, + "Cover: missing (first four), loading (next two), ready", + 16, + 6, + 824, + ); + let now = Instant::now(); + for (index, name) in [ + "Active", + "Control", + "Jam", + "Offline", + "Loading 1", + "Loading 2", + "Ready", + ] + .into_iter() + .enumerate() + { + let mut snapshot = fixture(); + snapshot.role = match index { + 1 => Role::Control, + 2 => Role::Jam, + _ => Role::Active, + }; + let mut deck = Deck::default(); + if index == 4 || index == 5 { + deck.artwork_loading = Some(now); + } + let snapshot = if index == 3 { None } else { Some(&snapshot) }; + let art = if index == 6 { Some(&artwork) } else { None }; + let at = if index == 5 { + now + Duration::from_millis(100) + } else { + now + }; + let key = render::key(0, &deck, snapshot, art, at); + key.save(directory.join(format!("cover-state-{index}.png")))?; + let x = 16 + index as i64 * 120; + image::imageops::overlay(&mut covers, &key, x, 34); + render::preview_label(&mut covers, name, x as i32, 140, 112); + } + covers.save(directory.join("artwork-states.png"))?; + let offline = Deck::default(); + render::bar(&offline, None, Duration::ZERO, Duration::ZERO) + .save(directory.join("offline-infobar.png"))?; + let snapshot = fixture(); + let frames: Vec<_> = (0..100) + .map(|i| { + let bar = render::bar( + &Deck::default(), + Some(&snapshot), + Duration::from_millis(i * 100), + Duration::ZERO, + ); + image::Frame::from_parts( + image::DynamicImage::ImageRgb8(bar).into_rgba8(), + 0, + 0, + image::Delay::from_numer_denom_ms(100, 1), + ) + }) + .collect(); + // Individual PNG frames are sufficient to inspect the real renderer without + // introducing an animation encoder dependency into the runtime. + for (i, frame) in frames.into_iter().enumerate().step_by(10) { + frame + .buffer() + .save(directory.join(format!("marquee-{i:03}.png")))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn preview_uses_runtime_renderer_and_preserves_native_dimensions() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path()).unwrap(); + assert_eq!( + image::image_dimensions(dir.path().join("active-key-0.png")).unwrap(), + (96, 96) + ); + assert_eq!( + image::image_dimensions(dir.path().join("control-infobar.png")).unwrap(), + (248, 58) + ); + assert!(dir.path().join("all-screens.png").exists()); + } +} diff --git a/integrations/opendeck/src/profile_upgrade.rs b/integrations/opendeck/src/profile_upgrade.rs new file mode 100644 index 0000000..971b073 --- /dev/null +++ b/integrations/opendeck/src/profile_upgrade.rs @@ -0,0 +1,121 @@ +//! OpenDeck 2.14.2 saves the inspector path on each action in the profile. +//! Upgrade an explicitly selected, offline profile from the first plugin release. +use std::fs; +use std::io::Write as _; +use std::path::Path; + +use anyhow::{Context, Result, ensure}; +use serde_json::Value; + +use crate::host::{CELL, INFOBAR, PLUGIN, PROFILE_INSPECTOR}; + +fn upgrade_instance(instance: &mut Value) -> usize { + let mut changed = 0; + if let Some(action) = instance.get_mut("action").and_then(Value::as_object_mut) + && action.get("plugin").and_then(Value::as_str) == Some(PLUGIN) + && matches!( + action + .get("uuid") + .or_else(|| action.get("UUID")) + .and_then(Value::as_str), + Some(CELL | INFOBAR) + ) + { + // Loaded profiles use snake_case; profiles exported by the Furumi + // generator can still contain the original manifest spelling. + let field = if action.contains_key("PropertyInspectorPath") { + "PropertyInspectorPath" + } else { + "property_inspector" + }; + if action.get(field).and_then(Value::as_str) != Some(PROFILE_INSPECTOR) { + action.insert(field.into(), PROFILE_INSPECTOR.into()); + changed = 1; + } + } + if let Some(children) = instance.get_mut("children").and_then(Value::as_array_mut) { + changed += children.iter_mut().map(upgrade_instance).sum::(); + } + changed +} + +pub(super) fn upgrade(path: &Path) -> Result<()> { + let path = fs::canonicalize(path).context("OpenDeck profile not found")?; + let original = fs::read(&path)?; + let json = original.strip_prefix(b"\xef\xbb\xbf").unwrap_or(&original); + let mut profile: Value = serde_json::from_slice(json).context("invalid profile JSON")?; + ensure!( + profile["keys"].is_array(), + "expected an OpenDeck profile with a keys array" + ); + let mut changed = 0; + for field in ["keys", "sliders", "infobars"] { + if let Some(instances) = profile.get_mut(field).and_then(Value::as_array_mut) { + changed += instances.iter_mut().map(upgrade_instance).sum::(); + } + } + if changed == 0 { + println!("No Furumi actions need a settings update."); + return Ok(()); + } + let directory = path.parent().context("profile has no parent directory")?; + let mut replacement = tempfile::NamedTempFile::new_in(directory)?; + fs::set_permissions(replacement.path(), fs::metadata(&path)?.permissions())?; + serde_json::to_writer_pretty(&mut replacement, &profile)?; + replacement.write_all(b"\n")?; + replacement.as_file().sync_all()?; + + let mut backup = tempfile::Builder::new() + .prefix("furumi-profile-") + .suffix(".bak") + .tempfile_in(directory)?; + backup.write_all(&original)?; + backup.as_file().sync_all()?; + ensure!( + fs::read(&path)? == original, + "profile changed during upgrade; close OpenDeck and retry" + ); + let (_, backup_path) = backup.keep()?; + replacement.persist(&path)?; + println!( + "Updated {changed} Furumi actions. Original profile saved to {}", + backup_path.display() + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn upgrades_only_furumi_inspector_fields_and_keeps_one_original_on_retry() { + let other = json!({"action":{"plugin":"other","uuid":"other.cell","property_inspector":"custom.html"}}); + let settings = json!({"my_saved_title": "keep me"}); + let mut profile = json!({ + "keys":[null,{"action":{"plugin":PLUGIN,"uuid":CELL,"property_inspector":""},"settings":settings},other], + "infobars":[{"action":{"plugin":PLUGIN,"UUID":INFOBAR,"PropertyInspectorPath":""}}], + "sliders":[], "extra":"keep" + }); + let original = serde_json::to_vec(&profile).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("Personal.json"); + fs::write(&path, &original).unwrap(); + upgrade(&path).unwrap(); + profile["keys"][1]["action"]["property_inspector"] = PROFILE_INSPECTOR.into(); + profile["infobars"][0]["action"]["PropertyInspectorPath"] = PROFILE_INSPECTOR.into(); + assert_eq!( + serde_json::from_slice::(&fs::read(&path).unwrap()).unwrap(), + profile + ); + upgrade(&path).unwrap(); + let backups: Vec<_> = fs::read_dir(dir.path()) + .unwrap() + .flatten() + .filter(|e| e.path().extension().is_some_and(|ext| ext == "bak")) + .collect(); + assert_eq!(backups.len(), 1); + assert_eq!(fs::read(backups[0].path()).unwrap(), original); + } +} diff --git a/integrations/opendeck/src/render.rs b/integrations/opendeck/src/render.rs new file mode 100644 index 0000000..6e532ef --- /dev/null +++ b/integrations/opendeck/src/render.rs @@ -0,0 +1,1091 @@ +//! Raster renderer shared by the plugin and its offline preview command. +//! Every image is authored at hardware resolution, never enlarged to fit text. +use std::io::Cursor; +use std::sync::LazyLock; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use base64::Engine as _; +use fontdue::Font; +use furumi_control_protocol::{Repeat, Role, Snapshot}; +use image::{ImageFormat, Rgb, RgbImage}; + +use crate::icons::{self, Icon}; +use crate::model::{DEVICES_PER_PAGE, Deck, Screen}; +use crate::settings::InfobarBackground; + +pub const KEY_SIZE: u32 = crate::artwork::KEY_PIXELS; +pub const BAR_WIDTH: u32 = 248; +pub const BAR_HEIGHT: u32 = 58; +const PROGRESS_HEIGHT: i32 = 6; +const PROGRESS_Y: i32 = BAR_HEIGHT as i32 - 4 - PROGRESS_HEIGHT; +static FONT: LazyLock = LazyLock::new(|| { + Font::from_bytes( + include_bytes!("../assets/DejaVuSans.ttf") as &[u8], + fontdue::FontSettings::default(), + ) + .expect("bundled DejaVu font") +}); + +struct Palette { + background: [u8; 3], + foreground: [u8; 3], + accent: [u8; 3], +} + +fn palette(role: Role) -> Palette { + match role { + Role::Active => Palette { + background: [43, 70, 90], + foreground: [208, 220, 227], + accent: [129, 168, 190], + }, + Role::Control => Palette { + background: [82, 72, 37], + foreground: [228, 217, 180], + accent: [186, 167, 99], + }, + Role::Jam => Palette { + background: [71, 52, 81], + foreground: [222, 208, 228], + accent: [169, 141, 182], + }, + } +} + +fn themed_palette(role: Role, invert: bool) -> Palette { + let mut palette = palette(role); + if invert { + palette.background = [0, 0, 0]; + palette.foreground = palette.accent; + } + palette +} + +fn art_control( + im: &mut RgbImage, + icon: Icon, + slot: usize, + accent: [u8; 3], + enabled: bool, + invert: bool, +) { + let near = 3; + let far = KEY_SIZE - near - icons::COVER_GLYPH_SIZE; + let (x, y) = match slot { + 1 => (far, near), + 4 => (near, far), + 5 => (far, far), + _ => return, + }; + if enabled { + // One right triangle flush with both physical edges of this corner. + for py in 0..40 { + for px in 0..40 - py { + let cx = if slot == 4 { px } else { KEY_SIZE - 1 - px }; + im.put_pixel(cx, KEY_SIZE - 1 - py, Rgb(accent)); + } + } + } + let pale = [222, 229, 232]; + let dark = [20, 25, 29]; + let color = if enabled { + dark + } else if invert { + accent + } else { + pale + }; + let contour = if enabled { pale } else { dark }; + icons::cover_glyph(im, icon, x, y, color, contour); +} + +fn art_tile(artwork: &crate::artwork::PreparedArt, slot: usize) -> RgbImage { + let stride = crate::artwork::ART_STRIDE; + let (x, y) = match slot { + 0 => (0, 0), + 1 => (stride, 0), + 4 => (0, stride), + 5 => (stride, stride), + _ => (0, 0), + }; + image::imageops::crop_imm(artwork.square(), x, y, KEY_SIZE, KEY_SIZE).to_image() +} + +fn rect(im: &mut RgbImage, x: i32, y: i32, w: i32, h: i32, color: [u8; 3]) { + for py in y.max(0)..(y + h).min(im.height() as i32) { + for px in x.max(0)..(x + w).min(im.width() as i32) { + im.put_pixel(px as u32, py as u32, Rgb(color)); + } + } +} + +fn measure(text: &str, size: f32) -> f32 { + text.chars() + .map(|c| FONT.metrics(c, size).advance_width) + .sum() +} + +fn text( + im: &mut RgbImage, + value: &str, + size: f32, + x: i32, + top: i32, + clip: (i32, i32, i32, i32), + color: [u8; 3], +) { + let mut pen = x as f32; + let baseline = top as f32 + size * 0.82; + for ch in value.chars() { + let glyph = FONT.lookup_glyph_index(ch); + let m = FONT.metrics_indexed(glyph, size); + let gx = pen.round() as i32 + m.xmin; + pen += m.advance_width; + if gx + m.width as i32 <= clip.0 { + continue; + } + if gx >= clip.0 + clip.2 { + break; + } + let (_, pixels) = FONT.rasterize_indexed(glyph, size); + let gy = baseline.round() as i32 - m.ymin - m.height as i32; + for yy in 0..m.height { + for xx in 0..m.width { + let px = gx + xx as i32; + let py = gy + yy as i32; + if px < clip.0 + || py < clip.1 + || px >= clip.0 + clip.2 + || py >= clip.1 + clip.3 + || px < 0 + || py < 0 + || px >= im.width() as i32 + || py >= im.height() as i32 + { + continue; + } + let alpha = pixels[yy * m.width + xx] as u32; + if alpha > 0 { + let old = im.get_pixel(px as u32, py as u32).0; + let c = std::array::from_fn(|i| { + ((old[i] as u32 * (255 - alpha) + color[i] as u32 * alpha) / 255) as u8 + }); + im.put_pixel(px as u32, py as u32, Rgb(c)); + } + } + } + } +} + +fn label(im: &mut RgbImage, value: &str, size: f32, top: i32, color: [u8; 3]) { + let mut value = value.to_owned(); + if measure(&value, size) > 88.0 { + while !value.is_empty() && measure(&(value.clone() + "…"), size) > 88.0 { + value.pop(); + } + value.push('…'); + } + let x = ((96.0 - measure(&value, size)) / 2.0).round() as i32; + text(im, &value, size, x, top, (4, 0, 88, 96), color); +} + +fn device_name(im: &mut RgbImage, value: &str, age: Duration, color: [u8; 3], inset: i32) { + const SIZE: f32 = 16.0; + let width_limit = 96 - inset * 2; + let width = measure(value, SIZE).ceil() as i32; + let overflow = width - width_limit; + let x = if overflow > 0 { + // Hold at each end long enough to read both halves of similar names. + let speed = 20.0; + let pause = 2.0; + let leg = pause + f64::from(overflow) / speed; + let phase = age.as_secs_f64() % (2.0 * leg); + let distance = ((phase % leg - pause).max(0.0) * speed).round() as i32; + let offset = if phase < leg { + distance + } else { + overflow - distance + }; + inset - offset + } else { + inset + (width_limit - width) / 2 + }; + text(im, value, SIZE, x, 68, (inset, 64, width_limit, 26), color); +} + +pub fn key( + slot: usize, + deck: &Deck, + snapshot: Option<&Snapshot>, + artwork: Option<&RgbImage>, + now: Instant, +) -> RgbImage { + let prepared = artwork.map(|image| crate::artwork::PreparedArt::new(image.clone())); + key_prepared(slot, deck, snapshot, prepared.as_ref(), now) +} + +pub fn key_prepared( + slot: usize, + deck: &Deck, + snapshot: Option<&Snapshot>, + artwork: Option<&crate::artwork::PreparedArt>, + now: Instant, +) -> RgbImage { + let invert = deck.preferences.invert_colors; + let role = themed_palette(snapshot.map_or(Role::Active, |s| s.role), invert); + if matches!(deck.screen, Screen::Player) + && deck.preferences.album_art_2x2 + && matches!(slot, 0 | 1 | 4 | 5) + && snapshot.is_some() + && let Some(art) = artwork + { + let mut im = art_tile(art, slot); + match slot { + 1 => art_control(&mut im, Icon::Previous, 1, role.accent, false, invert), + 4 => { + let mode = snapshot.map_or(Repeat::Off, |s| s.repeat); + let icon = if mode == Repeat::One { + Icon::RepeatOne + } else { + Icon::Repeat + }; + art_control(&mut im, icon, 4, role.accent, mode != Repeat::Off, invert); + } + 5 => art_control( + &mut im, + Icon::Shuffle, + 5, + role.accent, + snapshot.is_some_and(|s| s.shuffle), + invert, + ), + _ => {} + } + return im; + } + if matches!(deck.screen, Screen::Player) && slot == 0 { + if snapshot.is_some() + && let Some(art) = artwork + { + return art.small().clone(); + } + let mut im = RgbImage::from_pixel( + KEY_SIZE, + KEY_SIZE, + Rgb(if invert { [0, 0, 0] } else { [32, 42, 51] }), + ); + icons::draw(&mut im, Icon::CoverFrame, [83, 100, 114]); + let note = if deck.artwork_loading.is_some() { + [103, 119, 132] + } else { + [169, 185, 198] + }; + icons::draw(&mut im, Icon::Album, note); + if let Some(started) = deck.artwork_loading { + let step = (now.saturating_duration_since(started).as_millis() / 100 % 8) as usize; + icons::corner_spinner(&mut im, step, [199, 213, 224]); + } + return im; + } + let remote_wait = deck.remote.waiting(snapshot); + let (bg, fg) = match (&deck.screen, snapshot) { + (Screen::Player, Some(_)) if slot == 2 && remote_wait => ( + if invert { [0, 0, 0] } else { [43, 48, 55] }, + [157, 169, 180], + ), + (Screen::Devices { .. }, _) => ( + if invert { [0, 0, 0] } else { [21, 34, 49] }, + if invert { + role.foreground + } else { + [201, 213, 223] + }, + ), + (_, None) => ( + if invert { [0, 0, 0] } else { [32, 39, 48] }, + [125, 136, 148], + ), + _ => (role.background, role.foreground), + }; + let mut im = RgbImage::from_pixel(KEY_SIZE, KEY_SIZE, Rgb(bg)); + match &deck.screen { + Screen::Player => match slot { + 1 => icons::draw(&mut im, Icon::Previous, fg), + 2 => { + let icon = if snapshot.is_some_and(|s| s.playing && !s.paused) { + Icon::Pause + } else { + Icon::Play + }; + icons::draw(&mut im, icon, fg); + if remote_wait { + let started = deck.remote.started().unwrap_or(now); + let step = + (now.saturating_duration_since(started).as_millis() / 100 % 8) as usize; + icons::corner_spinner(&mut im, step, role.foreground); + } + } + 3 => icons::draw(&mut im, Icon::Next, fg), + 4 => { + let mode = snapshot.map_or(Repeat::Off, |s| s.repeat); + let icon = if mode == Repeat::One { + Icon::RepeatOne + } else { + Icon::Repeat + }; + icons::draw(&mut im, icon, fg); + if mode != Repeat::Off { + icons::draw(&mut im, Icon::EnabledFrame, role.accent); + } + } + 5 => { + icons::draw(&mut im, Icon::Shuffle, fg); + if snapshot.is_some_and(|s| s.shuffle) { + icons::draw(&mut im, Icon::EnabledFrame, role.accent); + } + } + 6 | 7 => { + let (icon, caption) = if slot == 6 { + (Icon::SeekBack, "−10 s") + } else { + (Icon::SeekForward, "+30 s") + }; + icons::draw(&mut im, icon, fg); + label(&mut im, caption, 19.0, 65, fg); + } + _ => {} + }, + Screen::Functions => match slot { + 0 => { + if let Some(radio) = &deck.radio { + let step = (now.saturating_duration_since(radio.started).as_millis() / 100 % 8) + as usize; + icons::spinner(&mut im, step, fg); + label(&mut im, "Starting", 14.0, 73, fg); + } else { + icons::draw(&mut im, Icon::Radio, fg); + label(&mut im, "Radio", 16.0, 73, fg); + } + } + 1 => { + icons::draw(&mut im, Icon::Devices, fg); + let role_label = match snapshot.map(|s| s.role) { + Some(Role::Active) => "ACTIVE", + Some(Role::Control) => "CONTROL", + Some(Role::Jam) => "JAM", + None => "OFFLINE", + }; + label(&mut im, role_label, 14.0, 57, fg); + label( + &mut im, + snapshot + .and_then(|s| s.active_device_name.as_deref()) + .unwrap_or("Furumi"), + 14.0, + 77, + fg, + ); + } + 7 => icons::draw(&mut im, Icon::Back, fg), + _ => { + im = RgbImage::from_pixel( + KEY_SIZE, + KEY_SIZE, + Rgb(if invert { [0, 0, 0] } else { [13, 19, 26] }), + ) + } + }, + Screen::Devices { + page, + targets, + name_since, + } => match slot { + 0..=5 => { + if let Some(device) = targets.get(page * DEVICES_PER_PAGE + slot) { + let active = themed_palette(Role::Active, invert); + let color = if device.active { + im = RgbImage::from_pixel(KEY_SIZE, KEY_SIZE, Rgb(active.background)); + icons::draw(&mut im, Icon::Check, active.foreground); + if invert { + icons::draw(&mut im, Icon::EnabledFrame, active.accent); + } + active.foreground + } else if device.can_transfer { + fg + } else { + let disabled = [125, 138, 151]; + icons::draw(&mut im, Icon::Unavailable, disabled); + disabled + }; + icons::draw(&mut im, Icon::Devices, color); + let name = match (device.name.trim(), device.is_self) { + ("", true) => "This PC", + ("", false) => "Device", + (name, _) => name, + }; + if device.is_self && name != "This PC" { + label(&mut im, "This PC", 12.0, 53, color); + } + device_name( + &mut im, + name, + now.saturating_duration_since(name_since[slot]), + color, + if invert && device.active { 8 } else { 4 }, + ); + } else { + im = RgbImage::from_pixel( + KEY_SIZE, + KEY_SIZE, + Rgb(if invert { [0, 0, 0] } else { [13, 19, 26] }), + ); + } + } + 6 => { + let pages = targets.len().div_ceil(DEVICES_PER_PAGE).max(1); + let color = if pages > 1 { fg } else { [90, 103, 117] }; + icons::draw(&mut im, Icon::NextPage, color); + label(&mut im, &format!("{}/{}", page + 1, pages), 14.0, 74, color); + } + 7 => icons::draw(&mut im, Icon::Back, fg), + _ => {} + }, + } + if deck.pending.is_some() { + rect(&mut im, 0, 92, 96, 4, [80, 67, 23]); + } + im +} + +fn duration(seconds: f64) -> String { + let total = if seconds.is_finite() { + seconds.max(0.0) as u64 + } else { + 0 + }; + if total >= 3600 { + format!( + "{}:{:02}:{:02}", + total / 3600, + (total / 60) % 60, + total % 60 + ) + } else { + format!("{}:{:02}", total / 60, total % 60) + } +} + +pub fn metadata(snapshot: &Snapshot) -> String { + let Some(track) = &snapshot.track else { + return "No track".into(); + }; + let mut parts = vec![ + track.title.clone(), + track.artist.clone(), + track.album.clone(), + ]; + if let Some(year) = track.year { + parts.push(year.to_string()); + } + parts.retain(|s| !s.trim().is_empty()); + parts.join(" · ").chars().take(1024).collect() +} + +pub fn bar( + deck: &Deck, + snapshot: Option<&Snapshot>, + since_track: Duration, + since_snapshot: Duration, +) -> RgbImage { + bar_with_spectrum(deck, snapshot, since_track, since_snapshot, None) +} + +pub fn bar_with_spectrum( + deck: &Deck, + snapshot: Option<&Snapshot>, + since_track: Duration, + since_snapshot: Duration, + spectrum: Option<&crate::spectrum::History>, +) -> RgbImage { + let mut im = RgbImage::from_pixel( + BAR_WIDTH, + BAR_HEIGHT, + Rgb(if deck.preferences.invert_colors { + [0, 0, 0] + } else { + [8, 10, 13] + }), + ); + let Some(s) = snapshot else { + text( + &mut im, + "Furumi offline", + 22.0, + 8, + 16, + (8, 4, 232, 50), + [166, 176, 190], + ); + return im; + }; + let mut position = s.position_secs; + if s.playing && !s.paused { + position += since_snapshot.as_secs_f64().min(2.0); + } + if s.duration_secs > 0.0 { + position = position.min(s.duration_secs); + } + let elapsed = duration(position); + let total = if s.duration_secs > 0.0 { + duration(s.duration_secs) + } else { + "–:–".into() + }; + let time_width = measure(&elapsed, 17.0).max(measure(&total, 17.0)).ceil() as i32; + let time_x = 240 - time_width; + let clip_width = time_x - 16; + if let Some(spectrum) = spectrum { + let mode = deck.preferences.infobar_background; + // A two-pixel gap separates the base of the bars from track progress. + let bottom = if mode == InfobarBackground::Bars { + PROGRESS_Y - 2 + } else { + PROGRESS_Y + }; + spectrum.paint( + &mut im, + (8, 4, clip_width.max(0) as u32, (bottom - 4) as u32), + mode, + ); + } + let value = if deck.pending.is_some() { + "Transferring…".into() + } else if let Some((notice, _)) = &deck.notice { + notice.clone() + } else { + metadata(s) + }; + let width = measure(&value, 26.0); + let moving = width > clip_width as f32; + let travel = width + 35.0; + let cycle = 2.0 + travel as f64 / 25.0; + let marquee_age = deck + .pending + .as_ref() + .map(|pending| pending.started.elapsed()) + .or_else(|| deck.notice.as_ref().map(|(_, at)| at.elapsed())) + .unwrap_or(since_track); + let t = marquee_age.as_secs_f64() % cycle; + let offset = if moving { + ((t - 2.0).max(0.0) * 25.0) as i32 + } else { + 0 + }; + text( + &mut im, + &value, + 26.0, + 8 - offset, + 15, + (8, 4, clip_width, 43), + [255, 255, 255], + ); + if moving && offset > 0 { + text( + &mut im, + &value, + 26.0, + 8 - offset + travel as i32, + 15, + (8, 4, clip_width, 43), + [255, 255, 255], + ); + } + text( + &mut im, + &elapsed, + 17.0, + time_x, + 6, + (time_x, 4, time_width, 23), + [255, 255, 255], + ); + text( + &mut im, + &total, + 17.0, + time_x, + 28, + (time_x, 27, time_width, PROGRESS_Y - 27), + [174, 185, 199], + ); + rect(&mut im, 8, PROGRESS_Y, 232, PROGRESS_HEIGHT, [39, 48, 60]); + if s.duration_secs > 0.0 { + let width = (position / s.duration_secs).clamp(0.0, 1.0) * 232.0; + rect( + &mut im, + 8, + PROGRESS_Y, + width as i32, + PROGRESS_HEIGHT, + palette(s.role).accent, + ); + } + im +} + +pub fn png(image: &RgbImage) -> Result> { + let mut bytes = Cursor::new(Vec::new()); + image.write_to(&mut bytes, ImageFormat::Png)?; + Ok(bytes.into_inner()) +} +pub fn data_uri(image: &RgbImage) -> Result { + Ok(format!( + "data:image/png;base64,{}", + base64::engine::general_purpose::STANDARD.encode(png(image)?) + )) +} + +pub fn preview_label(im: &mut RgbImage, value: &str, x: i32, y: i32, width: i32) { + text(im, value, 14.0, x, y, (x, y, width, 24), [201, 213, 223]); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::preview::fixture; + + #[test] + fn two_by_two_cover_preserves_real_gap_and_original_bindings() { + use crate::model::Binding; + use furumi_control_protocol::Command; + let source = RgbImage::from_fn(226, 226, |x, y| Rgb([x as u8, y as u8, 77])); + let prepared = crate::artwork::PreparedArt::new(source); + let mut deck = Deck::default(); + deck.preferences.album_art_2x2 = true; + let mut snapshot = fixture(); + snapshot.repeat = Repeat::One; + snapshot.shuffle = true; + let now = Instant::now(); + assert_eq!(prepared.square().dimensions(), (226, 226)); + assert_eq!(crate::artwork::ART_GAP_PX, 34); + assert_eq!(crate::artwork::GAP_PX, 41); + for (slot, x, y) in [(0, 0, 0), (1, 130, 0), (4, 0, 130), (5, 130, 130)] { + let tile = key_prepared(slot, &deck, Some(&snapshot), Some(&prepared), now); + assert_eq!(tile.dimensions(), (96, 96)); + assert_eq!(tile.get_pixel(0, 0).0, [x as u8, y as u8, 77]); + assert_eq!( + tile.get_pixel(40, 40).0, + [(x + 40) as u8, (y + 40) as u8, 77] + ); + } + assert_eq!( + deck.binding(1, Some(&snapshot)), + Binding::Command(Command::Previous) + ); + assert_eq!( + deck.binding(4, Some(&snapshot)), + Binding::Command(Command::CycleRepeat) + ); + assert_eq!( + deck.binding(5, Some(&snapshot)), + Binding::Command(Command::ToggleShuffle) + ); + let left = key_prepared(0, &deck, Some(&snapshot), Some(&prepared), now); + let right = key_prepared(1, &deck, Some(&snapshot), Some(&prepared), now); + assert_eq!(left.get_pixel(95, 0)[0], 95); + assert_eq!(right.get_pixel(0, 0)[0], 130); + assert_eq!(right.get_pixel(0, 0)[0] - left.get_pixel(95, 0)[0] - 1, 34); + assert_ne!( + key_prepared(4, &deck, Some(&snapshot), Some(&prepared), now), + image::imageops::crop_imm(prepared.square(), 0, 130, 96, 96).to_image(), + "repeat-one corner glyph remains visible" + ); + } + + #[test] + fn mosaic_controls_use_glyph_contours_and_only_enabled_corner_triangles() { + for background in [[245, 245, 245], [8, 8, 8]] { + for invert in [false, true] { + let mut im = RgbImage::from_pixel(96, 96, Rgb(background)); + art_control( + &mut im, + Icon::Previous, + 1, + palette(Role::Active).accent, + false, + invert, + ); + assert!( + im.pixels().any(|p| p[0] < 65 && p[1] < 65 && p[2] < 65), + "dark contour survives light and dark covers" + ); + let foreground = if invert { + palette(Role::Active).accent + } else { + [222, 229, 232] + }; + assert!( + im.pixels().any(|p| p + .0 + .iter() + .zip(foreground) + .all(|(a, b)| a.abs_diff(b) < 20)) + ); + } + } + let source = RgbImage::from_pixel(384, 384, Rgb([70, 90, 110])); + let art = crate::artwork::PreparedArt::new(source); + let mut deck = Deck::default(); + deck.preferences.album_art_2x2 = true; + let mut snapshot = fixture(); + snapshot.repeat = Repeat::Off; + snapshot.shuffle = false; + let now = Instant::now(); + for (slot, bounds) in [ + (1, (73, 2, 93, 22)), + (4, (2, 73, 22, 93)), + (5, (73, 73, 93, 93)), + ] { + let off = key_prepared(slot, &deck, Some(&snapshot), Some(&art), now); + let mut changed = 0; + for (x, y, pixel) in off.enumerate_pixels() { + if pixel.0 != [70, 90, 110] { + changed += 1; + assert!(x >= bounds.0 && y >= bounds.1 && x <= bounds.2 && y <= bounds.3); + } + } + assert!(changed > 20); + assert_eq!(off.get_pixel(0, 95).0, [70, 90, 110]); + assert_eq!(off.get_pixel(95, 95).0, [70, 90, 110]); + } + for role in [Role::Active, Role::Control, Role::Jam] { + snapshot.role = role; + snapshot.repeat = Repeat::One; + snapshot.shuffle = true; + let accent = palette(role).accent; + let left = key_prepared(4, &deck, Some(&snapshot), Some(&art), now); + let right = key_prepared(5, &deck, Some(&snapshot), Some(&art), now); + for (x, y) in [(0, 95), (39, 95), (0, 56)] { + assert_eq!(left.get_pixel(x, y).0, accent); + assert_eq!(right.get_pixel(95 - x, y).0, accent); + } + assert_eq!(left.get_pixel(39, 75).0, [70, 90, 110]); + assert_eq!(right.get_pixel(56, 75).0, [70, 90, 110]); + let clean = key_prepared(0, &deck, Some(&snapshot), Some(&art), now); + assert!(clean.pixels().all(|p| p.0 == [70, 90, 110])); + let previous = key_prepared(1, &deck, Some(&snapshot), Some(&art), now); + assert_eq!(previous.get_pixel(0, 0).0, [70, 90, 110]); + } + } + + #[test] + fn inverted_theme_keeps_black_bases_role_icons_and_intact_artwork() { + let now = Instant::now(); + let mut deck = Deck::default(); + deck.preferences.invert_colors = true; + let mut snapshot = fixture(); + for role in [Role::Active, Role::Control, Role::Jam] { + snapshot.role = role; + for slot in 1..8 { + let im = key(slot, &deck, Some(&snapshot), None, now); + assert_eq!(im.get_pixel(0, 0).0, [0, 0, 0]); + assert!(im.pixels().any(|p| p.0 == palette(role).accent)); + } + } + let art = RgbImage::from_pixel(96, 96, Rgb([120, 40, 190])); + assert_eq!(key(0, &deck, Some(&snapshot), Some(&art), now), art); + assert_eq!(key(0, &deck, None, None, now).get_pixel(0, 0).0, [0, 0, 0]); + deck.screen = Screen::Functions; + assert_eq!( + key(1, &deck, Some(&snapshot), None, now).get_pixel(0, 0).0, + [0, 0, 0] + ); + deck.release(crate::model::Binding::Devices, Some(&snapshot)); + assert_eq!( + key(0, &deck, Some(&snapshot), None, now).get_pixel(0, 0).0, + [0, 0, 0] + ); + } + + #[test] + fn both_audio_backgrounds_are_confined_to_the_marquee() { + let mut history = crate::spectrum::History::default(); + for sequence in 1..=232 { + history.ingest(crate::spectrum::Frame { + epoch: 1, + sequence, + bands: Some([220; 31]), + }); + } + let mut deck = Deck::default(); + let snapshot = fixture(); + let plain = bar(&deck, Some(&snapshot), Duration::ZERO, Duration::ZERO); + let time_x = 240 - measure("1:23", 17.0).max(measure("4:05", 17.0)).ceil() as u32; + for mode in [InfobarBackground::Spectrogram, InfobarBackground::Bars] { + deck.preferences.infobar_background = mode; + let drawn = bar_with_spectrum( + &deck, + Some(&snapshot), + Duration::ZERO, + Duration::ZERO, + Some(&history), + ); + assert_ne!(plain, drawn); + for (x, y, pixel) in drawn.enumerate_pixels() { + if x >= time_x || y >= PROGRESS_Y as u32 { + assert_eq!(plain.get_pixel(x, y), pixel); + } + } + } + deck.preferences.invert_colors = true; + assert_eq!( + bar_with_spectrum( + &deck, + Some(&snapshot), + Duration::ZERO, + Duration::ZERO, + Some(&history) + ) + .get_pixel(0, 0) + .0, + [0, 0, 0] + ); + } + + #[test] + fn missing_cover_is_identical_and_neutral_for_all_roles_and_offline() { + let deck = Deck::default(); + let now = Instant::now(); + let mut snapshot = fixture(); + let neutral = key(0, &deck, None, None, now); + assert_eq!(neutral.get_pixel(0, 0).0, [32, 42, 51]); + for role in [Role::Active, Role::Control, Role::Jam] { + snapshot.role = role; + assert_eq!(key(0, &deck, Some(&snapshot), None, now), neutral); + } + assert!( + neutral.pixels().any(|p| p.0 != [32, 42, 51]), + "genuine note and thin frame remain visible" + ); + } + + #[test] + fn cover_loading_has_its_own_animation_without_disabling_functions_or_transport() { + use crate::model::Binding; + use furumi_control_protocol::Command; + let now = Instant::now(); + let snapshot = fixture(); + let mut deck = Deck { + artwork_loading: Some(now), + ..Deck::default() + }; + let a = key(0, &deck, Some(&snapshot), None, now); + let b = key( + 0, + &deck, + Some(&snapshot), + None, + now + Duration::from_millis(100), + ); + assert_ne!(a, b); + assert_eq!(a.get_pixel(0, 0).0, [32, 42, 51]); + assert_eq!( + deck.binding(2, Some(&snapshot)), + Binding::Command(Command::PlayPause) + ); + assert_eq!(deck.binding(0, Some(&snapshot)), Binding::Functions); + assert_eq!(deck.binding(0, None), Binding::Functions); + deck.release(Binding::Functions, None); + assert!(matches!(deck.screen, Screen::Functions)); + } + + #[test] + fn control_pending_key_is_grey_and_only_corner_badge_animates() { + use furumi_control_protocol::{RemoteCommand, RemoteCommandState}; + let now = Instant::now(); + let mut snapshot = fixture(); + snapshot.role = Role::Control; + snapshot.paused = true; + let mut deck = Deck::default(); + deck.remote.begin(&snapshot, "play".into(), now); + let a = key(2, &deck, Some(&snapshot), None, now); + let b = key( + 2, + &deck, + Some(&snapshot), + None, + now + Duration::from_millis(100), + ); + assert_eq!(a.get_pixel(0, 0).0, [43, 48, 55]); + assert_ne!(a, b); + for y in 0..96 { + for x in 0..96 { + if x < 72 || y < 72 { + assert_eq!(a.get_pixel(x, y), b.get_pixel(x, y)); + } + } + } + snapshot.remote_command = Some(RemoteCommand { + id: 1, + state: RemoteCommandState::Confirmed, + error: None, + }); + deck.remote.observe(&snapshot, now); + let confirmed = key(2, &deck, Some(&snapshot), None, now); + assert_eq!( + confirmed.get_pixel(0, 0).0, + palette(Role::Control).background + ); + // Jam preserves its normal button, even if an unrelated gate exists. + snapshot.role = Role::Jam; + assert_eq!( + key(2, &deck, Some(&snapshot), None, now).get_pixel(0, 0).0, + palette(Role::Jam).background + ); + } + #[test] + fn hardware_dimensions_and_reserved_time_region_are_stable_during_marquee() { + let s = fixture(); + let d = Deck::default(); + let a = bar(&d, Some(&s), Duration::ZERO, Duration::ZERO); + let b = bar(&d, Some(&s), Duration::from_secs(9), Duration::ZERO); + assert_eq!(a.dimensions(), (248, 58)); + assert_eq!( + key(0, &d, Some(&s), None, Instant::now()).dimensions(), + (96, 96) + ); + let time_x = 240 - measure("1:23", 17.0).max(measure("4:05", 17.0)).ceil() as u32; + for y in 0..50 { + for x in time_x..248 { + assert_eq!(a.get_pixel(x, y), b.get_pixel(x, y)); + } + } + assert_ne!(a, b); + for y in 48..54 { + assert_eq!(a.get_pixel(8, y).0, palette(s.role).accent); + assert_eq!(a.get_pixel(239, y).0, [39, 48, 60]); + } + assert_eq!(a.get_pixel(8, 47).0, [8, 10, 13]); + assert_eq!(a.get_pixel(8, 54).0, [8, 10, 13]); + } + #[test] + fn hour_long_podcast_keeps_time_inside_safe_bounds() { + let mut s = fixture(); + s.position_secs = 5000.0; + s.duration_secs = 10000.0; + let a = bar(&Deck::default(), Some(&s), Duration::ZERO, Duration::ZERO); + assert_eq!(a.dimensions(), (248, 58)); + assert_eq!(duration(5000.0), "1:23:20"); + for y in 0..58 { + for x in 240..248 { + assert_eq!(a.get_pixel(x, y).0, [8, 10, 13]); + } + } + } + + #[test] + fn cover_key_is_clean_and_other_keys_never_use_artwork() { + let snapshot = fixture(); + let deck = Deck::default(); + let now = Instant::now(); + let art = RgbImage::from_fn(96, 96, |x, y| Rgb([x as u8, y as u8, 88])); + assert_eq!(key(0, &deck, Some(&snapshot), Some(&art), now), art); + for slot in 1..8 { + assert_eq!( + key(slot, &deck, Some(&snapshot), Some(&art), now), + key(slot, &deck, Some(&snapshot), None, now) + ); + } + } + + #[test] + fn enabled_frames_follow_repeat_and_shuffle_independently_in_every_role() { + let now = Instant::now(); + let d = Deck::default(); + let mut s = fixture(); + for role in [Role::Active, Role::Control, Role::Jam] { + s.role = role; + let colors = palette(role); + for repeat in [Repeat::Off, Repeat::All, Repeat::One] { + s.repeat = repeat; + for shuffle in [false, true] { + s.shuffle = shuffle; + for (slot, selected) in [(4, repeat != Repeat::Off), (5, shuffle)] { + let tile = key(slot, &d, Some(&s), None, now); + for inset in 0..9 { + let expected = if selected && (4..8).contains(&inset) { + colors.accent + } else { + colors.background + }; + assert_eq!(tile.get_pixel(inset, 48).0, expected); + } + } + } + } + } + s.repeat = Repeat::All; + let all = key(4, &d, Some(&s), None, now); + s.repeat = Repeat::One; + let one = key(4, &d, Some(&s), None, now); + assert_ne!( + image::imageops::crop_imm(&all, 38, 38, 20, 20).to_image(), + image::imageops::crop_imm(&one, 38, 38, 20, 20).to_image() + ); + } + + #[test] + fn only_long_device_names_scroll_and_pause_at_both_ends() { + let mut s = fixture(); + let name = "Студийный компьютер A"; + s.devices[0].name = name.into(); + let mut d = Deck::default(); + d.release(crate::model::Binding::Devices, Some(&s)); + let Screen::Devices { name_since, .. } = &d.screen else { + unreachable!() + }; + let start = name_since[0]; + let frame = |slot, age| { + key( + slot, + &d, + Some(&s), + None, + start + Duration::from_secs_f64(age), + ) + }; + let leg = 2.0 + (measure(name, 16.0).ceil() as f64 - 88.0) / 20.0; + let first = frame(0, 0.0); + let last = frame(0, leg); + assert_eq!(first, frame(0, 1.9)); + assert_ne!(first, last); + assert_eq!(last, frame(0, leg + 1.9)); + assert_eq!(first, frame(0, 2.0 * leg)); + assert_eq!(frame(1, 0.0), frame(1, leg)); + for (x, y, p) in first.enumerate_pixels() { + if !(4..92).contains(&x) || !(64..90).contains(&y) { + assert_eq!(p, last.get_pixel(x, y)); + } + } + let mut renamed = s.clone(); + renamed.devices[0].name = name.replace('A', "B"); + let mut d2 = Deck::default(); + d2.release(crate::model::Binding::Devices, Some(&renamed)); + let Screen::Devices { name_since, .. } = &d2.screen else { + unreachable!() + }; + let renamed_frame = |age| { + key( + 0, + &d2, + Some(&renamed), + None, + name_since[0] + Duration::from_secs_f64(age), + ) + }; + assert_eq!(first, renamed_frame(0.0)); + assert_ne!(last, renamed_frame(leg + 1.0)); + } +} diff --git a/integrations/opendeck/src/settings.rs b/integrations/opendeck/src/settings.rs new file mode 100644 index 0000000..622d8bf --- /dev/null +++ b/integrations/opendeck/src/settings.rs @@ -0,0 +1,159 @@ +//! Preferences are global to the OpenDeck plugin, not to an action instance. +//! The native runtime is the sole writer, merging validated inspector patches +//! into the canonical object while preserving unknown fields. +use serde_json::{Map, Value}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum InfobarBackground { + #[default] + None, + Spectrogram, + Bars, +} + +impl InfobarBackground { + pub fn uses_spectrum(self) -> bool { + matches!(self, Self::Spectrogram | Self::Bars) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Preferences { + pub infobar_background: InfobarBackground, + pub album_art_2x2: bool, + pub invert_colors: bool, +} + +impl Preferences { + pub fn read(value: &Value) -> Self { + Self { + infobar_background: match value["infobar_background"].as_str() { + Some("spectrogram") => InfobarBackground::Spectrogram, + Some("bars") => InfobarBackground::Bars, + _ => InfobarBackground::None, + }, + album_art_2x2: value["album_art_2x2"].as_bool().unwrap_or(false), + invert_colors: value["invert_colors"].as_bool().unwrap_or(false), + } + } +} + +#[derive(Default)] +pub struct Store { + raw: Map, + ready: bool, + queued: Map, +} + +impl Store { + pub fn raw_value(&self) -> Option { + self.ready.then(|| Value::Object(self.raw.clone())) + } + pub fn preferences(&self) -> Preferences { + Preferences::read(&Value::Object(self.raw.clone())) + } + + pub fn receive(&mut self, value: &Value) -> Option { + self.raw = value.as_object().cloned().unwrap_or_default(); + self.ready = true; + let changed = !self.queued.is_empty(); + self.raw.extend(std::mem::take(&mut self.queued)); + changed.then(|| Value::Object(self.raw.clone())) + } + + pub fn patch(&mut self, value: &Value) -> Option { + let patch = value.as_object()?; + if patch.is_empty() + || patch.len() > 3 + || !patch.iter().all(|(key, value)| match key.as_str() { + "infobar_background" => { + matches!(value.as_str(), Some("none" | "spectrogram" | "bars")) + } + "album_art_2x2" | "invert_colors" => value.is_boolean(), + _ => false, + }) + { + return None; + } + if !self.ready { + self.queued.extend(patch.clone()); + return None; + } + self.raw.extend(patch.clone()); + Some(Value::Object(self.raw.clone())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn bars_round_trips_and_old_or_unknown_modes_keep_safe_defaults() { + let mut store = Store::default(); + store.receive(&json!({"future":42})); + let value = store.patch(&json!({"infobar_background":"bars"})).unwrap(); + assert_eq!(value["future"], 42); + assert_eq!( + store.preferences().infobar_background, + InfobarBackground::Bars + ); + assert!(InfobarBackground::Bars.uses_spectrum()); + assert!(InfobarBackground::Spectrogram.uses_spectrum()); + assert!(!InfobarBackground::None.uses_spectrum()); + assert!( + store + .patch(&json!({"infobar_background":"invalid"})) + .is_none() + ); + assert_eq!( + Preferences::read(&json!({})).infobar_background, + InfobarBackground::None + ); + } + + #[test] + fn defaults_and_unknown_preferences_are_safe_and_nondestructive() { + assert_eq!(Preferences::read(&json!({})), Preferences::default()); + let source = json!({"infobar_background":"spectrogram","album_art_2x2":true,"invert_colors":true,"future":{"keep":42}}); + let before = source.clone(); + let preferences = Preferences::read(&source); + assert_eq!( + preferences.infobar_background, + InfobarBackground::Spectrogram + ); + assert!(preferences.album_art_2x2 && preferences.invert_colors); + assert_eq!(source, before); + assert_eq!( + Preferences::read( + &json!({"album_art_2x2":"yes","invert_colors":1,"infobar_background":"future"}) + ), + Preferences::default() + ); + } + + #[test] + fn two_inspectors_merge_different_fields_without_discarding_unknown_settings() { + let mut store = Store::default(); + store.receive(&json!({"future":{"keep":42}})); + let a = store.patch(&json!({"album_art_2x2":true})).unwrap(); + let b = store.patch(&json!({"invert_colors":true})).unwrap(); + assert_eq!(a["album_art_2x2"], true); + assert_eq!(b["album_art_2x2"], true); + assert_eq!(b["invert_colors"], true); + assert_eq!(b["future"]["keep"], 42); + assert!(store.patch(&json!({"future":false})).is_none()); + assert!(store.patch(&json!({"invert_colors":"yes"})).is_none()); + } + + #[test] + fn patches_before_initial_host_read_are_queued_then_merged_with_unknown_fields() { + let mut store = Store::default(); + assert!(store.patch(&json!({"album_art_2x2":true})).is_none()); + assert!(store.patch(&json!({"invert_colors":true})).is_none()); + let merged = store.receive(&json!({"future":"preserve"})).unwrap(); + assert_eq!(merged["future"], "preserve"); + assert_eq!(merged["album_art_2x2"], true); + assert_eq!(merged["invert_colors"], true); + } +} diff --git a/integrations/opendeck/src/spectrum.rs b/integrations/opendeck/src/spectrum.rs new file mode 100644 index 0000000..c4b32b3 --- /dev/null +++ b/integrations/opendeck/src/spectrum.rs @@ -0,0 +1,246 @@ +//! Ephemeral local-output visual history. It never derives synthetic audio +//! from track metadata, and epoch/sequence checks discard stale frames. +use std::collections::VecDeque; +use std::sync::LazyLock; + +use furumi_control_protocol::SPECTRUM_BANDS; +use image::{Rgb, RgbImage}; + +use crate::settings::InfobarBackground; + +// The input is already in dB (−60..0 dBFS). Give the commonly occupied +// middle of that range most of the blue-to-teal transition. White 26 px +// marquee text retains over 3:1 contrast even against the warmest peaks. +static COLORS: LazyLock<[Rgb; 256]> = LazyLock::new(|| { + const STOPS: [(u8, [u8; 3]); 8] = [ + (0, [8, 10, 13]), + (24, [46, 42, 107]), + (64, [63, 66, 166]), + (96, [34, 96, 193]), + (132, [6, 132, 159]), + (160, [44, 148, 129]), + (192, [147, 140, 72]), + (255, [202, 126, 47]), + ]; + let mut colors = [Rgb([0; 3]); 256]; + for (&(low, from), &(high, to)) in STOPS.iter().zip(&STOPS[1..]) { + let span = u16::from(high - low); + for level in low..=high { + let step = u16::from(level - low); + colors[usize::from(level)] = Rgb(std::array::from_fn(|channel| { + ((u16::from(from[channel]) * (span - step) + + u16::from(to[channel]) * step + + span / 2) + / span) as u8 + })); + } + } + colors +}); + +#[derive(Clone, Debug)] +pub struct Frame { + pub epoch: u64, + pub sequence: u64, + pub bands: Option<[u8; SPECTRUM_BANDS]>, +} + +#[derive(Default)] +pub struct History { + epoch: Option, + sequence: Option, + columns: VecDeque<[u8; SPECTRUM_BANDS]>, +} + +impl History { + pub fn clear(&mut self) { + self.columns.clear(); + } + + pub fn ingest(&mut self, frame: Frame) { + if self.epoch.is_some_and(|epoch| frame.epoch < epoch) { + return; + } + if self.epoch != Some(frame.epoch) { + self.columns.clear(); + self.sequence = None; + self.epoch = Some(frame.epoch); + } + if self + .sequence + .is_some_and(|sequence| frame.sequence <= sequence) + { + return; + } + self.sequence = Some(frame.sequence); + match frame.bands { + Some(bands) => { + self.columns.push_back(bands); + if self.columns.len() > 232 { + self.columns.pop_front(); + } + } + None => self.columns.clear(), + } + } + + pub fn paint( + &self, + im: &mut RgbImage, + (x, y, width, height): (u32, u32, u32, u32), + mode: InfobarBackground, + ) { + let Some(latest) = self.columns.back() else { + return; + }; + let width = width.min(im.width().saturating_sub(x)); + let height = height.min(im.height().saturating_sub(y)); + if width == 0 || height == 0 { + return; + } + match mode { + InfobarBackground::None => {} + InfobarBackground::Spectrogram => { + for (age, bands) in self.columns.iter().rev().take(width as usize).enumerate() { + let px = x + width - 1 - age as u32; + for dy in 0..height { + let band = ((height - 1 - dy) * SPECTRUM_BANDS as u32 / height) as usize; + let level = bands[band]; + if level != 0 { + im.put_pixel(px, y + dy, COLORS[usize::from(level)]); + } + } + } + } + InfobarBackground::Bars => { + let count = width.min(SPECTRUM_BANDS as u32); + for column in 0..count { + // A very wide time field can leave fewer pixels than bands. + let first = (column * SPECTRUM_BANDS as u32 / count) as usize; + let end = ((column + 1) * SPECTRUM_BANDS as u32 / count) as usize; + let level = *latest[first..end].iter().max().unwrap(); + let rows = (u32::from(level) * height).div_ceil(255); + let left = x + column * width / count; + let right = x + (column + 1) * width / count; + let gutter = u32::from(right - left >= 3); + for py in y + height - rows..y + height { + for px in left..right - gutter { + im.put_pixel(px, py, COLORS[usize::from(level)]); + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quiet_and_midrange_levels_are_visible_and_white_titles_keep_contrast() { + fn luminance(rgb: Rgb) -> f64 { + let [r, g, b] = rgb.0.map(|value| { + let value = f64::from(value) / 255.0; + if value <= 0.04045 { + value / 12.92 + } else { + ((value + 0.055) / 1.055).powf(2.4) + } + }); + 0.2126 * r + 0.7152 * g + 0.0722 * b + } + let background = luminance(Rgb([8, 10, 13])) + 0.05; + // −48 and −30 dBFS, respectively. The previous linear ramp was nearly black here. + assert!((luminance(COLORS[51]) + 0.05) / background >= 2.0); + assert!((luminance(COLORS[128]) + 0.05) / background >= 4.0); + assert!(COLORS.iter().all(|&c| 1.05 / (luminance(c) + 0.05) >= 3.0)); + } + + #[test] + fn bars_use_only_the_latest_frame_at_fixed_frequency_positions() { + let mut history = History::default(); + let mut bands = [0; SPECTRUM_BANDS]; + bands[0] = 255; + bands[15] = 128; + history.ingest(Frame { + epoch: 1, + sequence: 1, + bands: Some(bands), + }); + let paint = |history: &History| { + let mut frame = RgbImage::new(124, 32); + history.paint(&mut frame, (0, 0, 124, 32), InfobarBackground::Bars); + frame + }; + let low = paint(&history); + assert_eq!(*low.get_pixel(0, 0), COLORS[255]); + assert_eq!(*low.get_pixel(3, 31), Rgb([0; 3])); // gutter + assert_eq!(*low.get_pixel(60, 14), Rgb([0; 3])); + assert_eq!(*low.get_pixel(60, 15), COLORS[128]); + assert_eq!(*low.get_pixel(120, 31), Rgb([0; 3])); + + let mut treble = [0; SPECTRUM_BANDS]; + treble[30] = 255; + history.ingest(Frame { + epoch: 1, + sequence: 2, + bands: Some(treble), + }); + let high = paint(&history); + assert_eq!(*high.get_pixel(0, 31), Rgb([0; 3])); + assert_eq!(*high.get_pixel(120, 0), COLORS[255]); + } + + #[test] + fn silence_preserves_the_selected_background_in_both_audio_modes() { + let mut history = History::default(); + history.ingest(Frame { + epoch: 1, + sequence: 1, + bands: Some([0; SPECTRUM_BANDS]), + }); + for color in [Rgb([0; 3]), Rgb([8, 10, 13])] { + for mode in [InfobarBackground::Spectrogram, InfobarBackground::Bars] { + let mut frame = RgbImage::from_pixel(124, 32, color); + history.paint(&mut frame, (0, 0, 124, 32), mode); + assert!(frame.pixels().all(|&pixel| pixel == color)); + } + } + } + + #[test] + fn epoch_and_sequence_prevent_old_audio_from_reappearing() { + let mut history = History::default(); + history.ingest(Frame { + epoch: 1, + sequence: 1, + bands: Some([100; 31]), + }); + history.ingest(Frame { + epoch: 1, + sequence: 1, + bands: Some([250; 31]), + }); + assert_eq!(history.columns.len(), 1); + history.ingest(Frame { + epoch: 2, + sequence: 1, + bands: None, + }); + assert!(history.columns.is_empty()); + history.ingest(Frame { + epoch: 1, + sequence: 10, + bands: Some([255; 31]), + }); + assert!(history.columns.is_empty()); + history.ingest(Frame { + epoch: 2, + sequence: 2, + bands: Some([50; 31]), + }); + assert_eq!(history.columns.len(), 1); + } +} diff --git a/integrations/opendeck/tests/property-inspector.cjs b/integrations/opendeck/tests/property-inspector.cjs new file mode 100644 index 0000000..cc9c4e8 --- /dev/null +++ b/integrations/opendeck/tests/property-inspector.cjs @@ -0,0 +1,70 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const source = fs.readFileSync(path.join(__dirname, '../assets/property-inspector.js'), 'utf8'); +function inspector(uuid) { + const controls = Object.fromEntries(['infobar-background', 'album-art-2x2', 'invert-colors', 'status'].map(id => [id, { disabled: true, checked: false, value: '', textContent: '' }])); + const sent = []; + class Socket { + static OPEN = 1; + constructor(url) { this.url = url; this.readyState = 1; Socket.instance = this; } + send(value) { sent.push(JSON.parse(value)); } + } + const context = vm.createContext({ WebSocket: Socket, document: { getElementById: id => controls[id] } }); + vm.runInContext(source, context); + context.connectElgatoStreamDeckSocket(12345, uuid, 'registerPropertyInspector'); + const socket = Socket.instance; + socket.onopen(); + assert.deepEqual(sent.shift(), { event: 'registerPropertyInspector', uuid }); + assert.deepEqual(sent.shift(), { event: 'getGlobalSettings', context: uuid }); + return { uuid, controls, sent, socket, receive: settings => socket.onmessage({ data: JSON.stringify({ event: 'didReceiveGlobalSettings', payload: { settings } }) }) }; +} + +const a = inspector('sd-TEST.Furumi.Keypad.0.0'); +const b = inspector('sd-TEST.Furumi.Infobar.0.0'); +let canonical = { future: { keep: 42 }, infobar_background: 'none' }; +for (const pi of [a, b]) pi.receive(canonical); +assert.equal(a.controls['album-art-2x2'].disabled, false); + +a.controls['album-art-2x2'].checked = true; +a.controls['album-art-2x2'].onchange(); +b.controls['invert-colors'].checked = true; +b.controls['invert-colors'].onchange(); +for (const pi of [a, b]) { + const message = pi.sent.shift(); + assert.equal(message.event, 'sendToPlugin'); + assert.equal(message.context, pi.uuid); + assert.equal(message.payload.event, 'preferencesPatch'); + assert.equal(Object.keys(message.payload.patch).length, 1); + canonical = { ...canonical, ...message.payload.patch }; + // OpenDeck broadcasts runtime setGlobalSettings to every mounted inspector. + for (const inspector of [a, b]) inspector.receive(canonical); +} +assert.equal(canonical.album_art_2x2, true); +assert.equal(canonical.invert_colors, true); +assert.equal(canonical.future.keep, 42); +for (const mode of ['bars', 'spectrogram', 'none']) { + a.controls['infobar-background'].value = mode; + a.controls['infobar-background'].onchange(); + const message = a.sent.shift(); + assert.deepEqual(message.payload.patch, { infobar_background: mode }); + canonical = { ...canonical, ...message.payload.patch }; + for (const pi of [a, b]) { + pi.receive(canonical); + assert.equal(pi.controls['infobar-background'].value, mode); + } +} +a.controls['infobar-background'].value = 'invalid'; +a.controls['infobar-background'].onchange(); +assert.equal(a.sent.length, 0, 'invalid modes must not emit patches'); +for (const pi of [a, b]) { + assert.equal(pi.controls['album-art-2x2'].checked, true); + assert.equal(pi.controls['invert-colors'].checked, true); + assert.equal(pi.controls.status.textContent, ''); + assert.equal(pi.sent.length, 0, 'inspectors must never rewrite global objects'); + pi.socket.onclose(); + assert.equal(pi.controls['invert-colors'].disabled, true); +} +console.log('Property Inspector: real script registered both contexts, emitted validated patches, and synchronized two mounted inspectors without losing unknown settings.'); diff --git a/src/app/control.rs b/src/app/control.rs new file mode 100644 index 0000000..75aef30 --- /dev/null +++ b/src/app/control.rs @@ -0,0 +1,250 @@ +//! Pure control snapshots and routing into the ordinary playback runtime. +use furumi_control_protocol::{API_VERSION, Command, Device, Repeat, Role, Snapshot, Track}; + +use super::action::Action; +use super::state::{self, AppState, DevicePlaybackRole}; +use super::{Runtime, perform_effect, update}; + +pub(crate) fn published(state: &AppState, revision: u64) -> crate::control::Published { + let now = state::unix_time_ms(); + let current = state.player.current.as_ref(); + let artwork = crate::control::art::Source::current(state); + let track = current.map(|track| Track { + key: track.key().to_string(), + title: track.title.clone(), + artist: track.artist_line(), + album: track.release_title.clone(), + year: track.release_year, + artwork_id: artwork.id(&track.key().to_string()), + }); + let has_episodes = state.player.queue.iter().any(|track| track.is_podcast()) + || current.is_some_and(|track| track.is_podcast()); + let mut devices = Vec::new(); + if let Some(status) = &state.federation.devices { + for device in status.devices.iter().filter(|device| !device.revoked) { + let is_self = + device.is_self || device.device_id == state.device_playback.self_device_id; + let online = state::device_status_online(state, device, now); + let reason = if state.device_playback.role == DevicePlaybackRole::Jam { + Some("leave the current Jam before switching personal devices") + } else if !online { + Some("device is offline") + } else if !is_self + && has_episodes + && !music_dht::device_sync::supports_podcasts(device.protocol_version) + { + Some("this device does not support podcast queues") + } else { + None + }; + devices.push(Device { + id: device.device_id.clone(), + name: state::device_display_name(device), + is_self, + active: state.device_playback.active_device_id.as_deref() + == Some(&device.device_id), + online, + can_transfer: reason.is_none(), + unavailable_reason: reason.map(str::to_owned), + }); + } + } + if !devices.iter().any(|device| device.is_self) { + let jam = state.device_playback.role == DevicePlaybackRole::Jam; + devices.push(Device { + id: state.device_playback.self_device_id.clone(), + name: state.device_playback.self_device_name.clone(), + is_self: true, + active: state.device_playback.is_audio_owner(), + online: true, + can_transfer: !jam, + unavailable_reason: jam + .then(|| "leave the current Jam before switching personal devices".into()), + }); + } + devices.sort_by(|a, b| { + b.is_self + .cmp(&a.is_self) + .then_with(|| a.name.cmp(&b.name)) + .then_with(|| a.id.cmp(&b.id)) + }); + crate::control::Published { + snapshot: Snapshot { + api_version: API_VERSION, + spectrum_supported: true, + revision, + updated_at_ms: now.max(0) as u64, + role: match state.device_playback.role { + DevicePlaybackRole::Active => Role::Active, + DevicePlaybackRole::Control => Role::Control, + DevicePlaybackRole::Jam => Role::Jam, + }, + self_device_id: state.device_playback.self_device_id.clone(), + active_device_id: state.device_playback.active_device_id.clone(), + active_device_name: state.device_playback.active_device_name.clone(), + playing: state.player.playing, + paused: state.player.paused, + position_secs: finite(state.player.position_secs), + duration_secs: current + .map(|track| finite(track.duration_seconds)) + .unwrap_or(0.0), + volume: state.player.volume, + shuffle: state.player.shuffle, + repeat: match state.player.repeat { + state::RepeatMode::Off => Repeat::Off, + state::RepeatMode::All => Repeat::All, + state::RepeatMode::One => Repeat::One, + }, + remote_command: Some(state.device_playback.control.status.clone()), + radio: state.radio.status.clone(), + track, + devices, + }, + artwork, + } +} + +fn finite(value: f64) -> f64 { + if value.is_finite() { + value.max(0.0) + } else { + 0.0 + } +} + +/// Share the visualizer's existing sample, even when the fullscreen view is +/// closed. A pause freezes the waterfall. Losing the local output clears it. +pub(crate) fn publish_spectrum( + spectrum: &mut crate::control::Spectrum, + state: &AppState, + sampled_at: Option, + preparing: bool, + output_playing: bool, +) { + if preparing || !crate::visualizer::status::visible(state) { + spectrum.clear(); + } else if let Some(at) = sampled_at + && !state.player.paused + && output_playing + { + spectrum.sample(at, &state.player.audio_analysis.spectrum); + } +} + +pub(super) enum Intent { + Action(Action), + Transfer(Device), + Radio, +} + +pub(super) fn intent(state: &AppState, command: Command) -> Result { + if !matches!(command, Command::Transfer { .. } | Command::Artwork { .. }) { + super::remote_playback::available(state)?; + } + Ok(match command { + Command::PlayPause => { + if state.player.current.is_none() && state.player.queue.is_empty() { + return Err("nothing queued".into()); + } + Intent::Action(Action::PlayPause) + } + Command::Next => Intent::Action(Action::NextTrack), + Command::Previous => Intent::Action(Action::PrevTrack), + Command::VolumeUp => Intent::Action(Action::VolumeUp), + Command::VolumeDown => Intent::Action(Action::VolumeDown), + Command::ToggleShuffle => Intent::Action(Action::ToggleShuffle), + Command::CycleRepeat => Intent::Action(Action::CycleRepeat), + Command::StartRadio => Intent::Radio, + Command::Seek { seconds } => { + if state.player.current.is_none() { + return Err("nothing playing".into()); + } + if seconds.unsigned_abs() > 86_400 { + return Err("seek exceeds one day".into()); + } + if seconds >= 0 { + Intent::Action(Action::SeekForward { + seconds: seconds as u32, + }) + } else { + Intent::Action(Action::SeekBackward { + seconds: seconds.unsigned_abs() as u32, + }) + } + } + Command::Transfer { device_id } => { + let device = published(state, 0) + .snapshot + .devices + .into_iter() + .find(|device| device.id == device_id) + .ok_or_else(|| "unknown or revoked device".to_owned())?; + if !device.can_transfer { + return Err(device + .unavailable_reason + .unwrap_or_else(|| "device unavailable".into())); + } + Intent::Transfer(device) + } + Command::Artwork { .. } => { + return Err("artwork requests belong to the control service".into()); + } + }) +} + +pub(super) fn dispatch( + state: &mut AppState, + runtime: &mut Runtime, + request: crate::control::Request, +) { + if matches!(request.command, Command::Seek { .. }) + && !state.device_playback.is_control() + && let Some(reason) = super::podcast_runtime::seek_refusal(state, runtime) + { + let _ = request.reply.send(Err(reason)); + return; + } + let result = intent(state, request.command).and_then(|intent| { + match intent { + Intent::Radio => return super::radio::start(state, runtime), + Intent::Action(action) => { + // Same state transitions, remote targeting and podcast checks as media keys. + let id = state.device_playback.control.status.id; + if let Some(effect) = update(state, action) { + perform_effect(state, runtime, effect); + } + if state.device_playback.role == DevicePlaybackRole::Control + && state.device_playback.control.status.id == id + { + return Err(state + .status_message + .clone() + .unwrap_or_else(|| "No playback change to send".into())); + } + } + Intent::Transfer(device) => { + if device.active { + return Ok(()); + } + if device.is_self { + super::transfer_active_to_this_device_inner(state, runtime, true); + } else { + super::transfer_active_to_remote_device( + state, + runtime, + device.id.clone(), + device.name, + ); + } + if state.device_playback.active_device_id.as_ref() != Some(&device.id) { + return Err(state + .status_message + .clone() + .unwrap_or_else(|| "handoff failed".into())); + } + } + } + Ok(()) + }); + let _ = request.reply.send(result); +} diff --git a/src/app/event.rs b/src/app/event.rs index f35e882..770ab73 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -10,11 +10,22 @@ use crate::library::models::{ /// the playback engine, imports). Tasks never touch AppState directly. #[derive(Debug)] pub enum AppEvent { + Control(crate::control::Request), + RadioReady { + id: u64, + result: Result, String>, + }, Lyrics(super::lyrics::Event), UpdateChecked(Result, String>), UpdateProgress(String), UpdateInstalled(Result<(), String>), StatusMessage(String), + /// The local operation was recorded. Output confirmation arrives in a + /// separate DevicePlayback report from the owner. + RemoteCommandRecorded { + id: u64, + result: Result<(), String>, + }, StatusVisualizationReady(crate::visualizer::status::Ready), /// A page of the artists list arrived (or failed). ArtistsLoaded(Result), diff --git a/src/app/mod.rs b/src/app/mod.rs index 13196ed..df70952 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1,6 +1,7 @@ pub mod action; mod cmdline; pub mod command; +pub(crate) mod control; mod enrichment; pub mod event; pub mod input; @@ -9,6 +10,8 @@ pub(crate) mod lyrics; pub(crate) mod podcast_fixtures; pub(crate) mod podcast_runtime; pub(crate) mod popup; +mod radio; +mod remote_playback; pub mod state; pub mod update; @@ -48,6 +51,7 @@ pub struct Runtime { pub jam: Arc, pub federation: Arc, pub similarity: Arc, + pub radio_task: Option>, /// When the last Federation-tab status snapshot was requested. pub fed_status_at: Option, /// Keeps the last successful local-data snapshot visible while a newer @@ -468,6 +472,7 @@ pub async fn run( jam, federation, similarity, + radio_task: None, fed_status_at: None, local_library_stats_refreshing: Arc::new(std::sync::atomic::AtomicBool::new(false)), local_library_stats_refresh_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)), @@ -523,6 +528,24 @@ pub async fn run( let mut visual_tick = tokio::time::interval(VISUALIZER_TICK_INTERVAL); visual_tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut redraw = true; + let mut control_service = match crate::control::Service::start( + control::published(&state, 0), + runtime.event_tx.clone(), + runtime.library.clone(), + runtime.federation.clone(), + ) + .await + { + Ok(service) => Some(service), + Err(error) => { + tracing::warn!(%error, "local control unavailable"); + state.status_message = Some(format!("local control unavailable: {error}")); + None + } + }; + let mut control_revision = 0u64; + let mut published_command = state.device_playback.control.status.clone(); + let mut control_published_at = std::time::Instant::now(); loop { let plain_text = match state.popup.as_ref() { @@ -553,6 +576,7 @@ pub async fn run( } redraw = true; + let mut spectrum_sample_at = None; tokio::select! { maybe_event = input.next() => match maybe_event { Some(Ok(event)) => { @@ -563,10 +587,19 @@ pub async fn run( None => state.should_quit = true, }, Some(app_event) = event_rx.recv() => { + if matches!(&app_event, AppEvent::Player( + player::PlayerEvent::Started + | player::PlayerEvent::TrackFinished { .. } + | player::PlayerEvent::Seeked { result: Ok(()), .. } + )) && let Some(service) = &mut control_service { + service.spectrum.clear(); + } handle_app_event(&mut state, &mut runtime, app_event); lyrics::refresh(&mut state, &runtime); }, _ = tick.tick() => { + radio::tick(&mut state, &mut runtime); + remote_playback::tick(&mut state, std::time::Instant::now()); reconcile_personal_playback(&mut state, &mut runtime); state.advance_spinner(); expire_quit_confirmation(&mut state); @@ -579,7 +612,7 @@ pub async fn run( maybe_prefetch_next(&mut state, &runtime); push_media_update(&state, &mut runtime, false); } - _ = visual_tick.tick(), if state.visualizer.active || crate::visualizer::status::playing(&state) => { + at = visual_tick.tick(), if state.visualizer.active || crate::visualizer::status::playing(&state) => { if state.visualizer.active { sync_player_shared(&mut state, &runtime); } else { @@ -590,6 +623,7 @@ pub async fn run( // meter once here and the new meter again on completion. redraw = false; } + spectrum_sample_at = Some(at.into_std()); sync_status_visualizer_target(&mut state, terminal.get_frame().area()); if !runtime.plain_text_mode { runtime.status_visualizer.request(&state, runtime.event_tx.clone()); @@ -597,6 +631,24 @@ pub async fn run( } } + remote_playback::tick(&mut state, std::time::Instant::now()); + if let Some(service) = &mut control_service { + control::publish_spectrum( + &mut service.spectrum, + &state, + spectrum_sample_at, + runtime.player_start_pending, + runtime.player.shared.output_playing(), + ); + if control_published_at.elapsed() >= TICK_INTERVAL + || published_command != state.device_playback.control.status + { + control_revision = control_revision.wrapping_add(1); + published_command = state.device_playback.control.status.clone(); + service.publish(control::published(&state, control_revision)); + control_published_at = std::time::Instant::now(); + } + } if state.should_quit { // A replacement must finish before the runtime/process is torn down. if state.updater.busy { @@ -611,6 +663,12 @@ pub async fn run( } state.shutting_down = true; terminal.draw(|frame| ui::draw(frame, &state, &keymap))?; + if let Some(service) = control_service { + service.shutdown().await; + } + if let Some(task) = runtime.radio_task.take() { + task.abort(); + } podcast_runtime::shutdown(&mut runtime).await; runtime.federation.shutdown().await; return Ok(()); @@ -885,14 +943,23 @@ pub(crate) fn become_control_device( state.device_playback.role = state::DevicePlaybackRole::Control; state.device_playback.active_device_id = Some(snapshot.device_id.clone()); state.device_playback.active_device_name = Some(snapshot.device_name.clone()); - state.device_playback.last_remote_snapshot = Some(snapshot.clone()); state .device_playback .remote .insert(snapshot.device_id.clone(), snapshot.clone()); apply_playback_state_to_ui(state, &snapshot.state, Some(runtime.library.as_ref())); + remote_playback::remember(state, &snapshot); + let name = snapshot.device_name.clone(); + state.device_playback.last_remote_snapshot = Some(snapshot); extrapolate_control_position(state); - state.status_message = Some(format!("controlling {}", snapshot.device_name)); + if state.status_message.is_none() + || state + .status_message + .as_ref() + .is_some_and(|s| s.starts_with("controlling ") || s == remote_playback::WAITING) + { + state.status_message = Some(format!("controlling {name}")); + } } pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime, start_audio: bool) { @@ -916,6 +983,15 @@ pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime, } pub(crate) fn transfer_active_to_this_device(state: &mut AppState, runtime: &mut Runtime) { + transfer_active_to_this_device_inner(state, runtime, false); +} + +fn transfer_active_to_this_device_inner( + state: &mut AppState, + runtime: &mut Runtime, + preserve_pause: bool, +) { + let paused = preserve_pause && state.player.paused; if let Err(error) = runtime .devices .claim_playback(&state.device_playback.self_device_id) @@ -937,11 +1013,11 @@ pub(crate) fn transfer_active_to_this_device(state: &mut AppState, runtime: &mut } if state.player.current.is_some() { state.player.playing = true; - state.player.paused = false; + state.player.paused = paused; } become_active_device(state, runtime, false); if should_start && state.player.current.is_some() { - start_current_audio_from(state, runtime, remote_start(state), false); + start_current_audio_from(state, runtime, remote_start(state), paused); push_media_metadata(state, runtime); push_media_update(state, runtime, true); } @@ -991,12 +1067,13 @@ pub(crate) fn transfer_active_to_remote_device( target_device_id.clone(), command.clone(), "device handoff", + None, ); if let Some(previous) = previous_active_id && previous != target_device_id && previous != state.device_playback.self_device_id { - record_playback_command_async(runtime, previous, command.clone(), "device handoff"); + record_playback_command_async(runtime, previous, command.clone(), "device handoff", None); } let snapshot = crate::devices::PlaybackSnapshot { coordination: None, @@ -1027,10 +1104,15 @@ fn record_active_handoff( active_device_name: state.device_playback.self_device_name.clone(), state: playback_state_from_ui(state), }; - record_playback_command_async(runtime, target, command, "device handoff"); + record_playback_command_async(runtime, target, command, "device handoff", None); } -fn record_control_playback_state(state: &mut AppState, runtime: &Runtime, seek: bool) { +fn record_control_playback_state( + state: &mut AppState, + runtime: &Runtime, + seek: bool, + change: remote_playback::Change, +) { if !state.device_playback.is_control() { return; } @@ -1038,17 +1120,30 @@ fn record_control_playback_state(state: &mut AppState, runtime: &Runtime, seek: let Some(target) = state.device_playback.active_device_id.clone() else { return; }; - let command = crate::devices::PlaybackCommand::SetState { - state: playback_state_from_ui(state), - seek, - }; + let desired = playback_state_from_ui(state); if state.device_playback.role == state::DevicePlaybackRole::Jam { + let command = crate::devices::PlaybackCommand::SetState { + state: desired, + seek, + }; if let Err(err) = runtime.jam.submit_command(command) { state.status_message = Some(format!("Jam command failed: {err:#}")); } return; } - record_playback_command_async(runtime, target, command, "device command"); + match remote_playback::begin(state, change, desired.clone(), std::time::Instant::now()) { + Ok(id) => record_playback_command_async( + runtime, + target, + crate::devices::PlaybackCommand::SetState { + state: desired, + seek, + }, + "device command", + Some(id), + ), + Err(message) => state.status_message = Some(message.into()), + } } fn record_playback_command_async( @@ -1056,6 +1151,7 @@ fn record_playback_command_async( target: String, command: crate::devices::PlaybackCommand, label: &'static str, + request_id: Option, ) { let devices = Arc::clone(&runtime.devices); let sync_devices = Arc::clone(&runtime.devices); @@ -1070,8 +1166,17 @@ fn record_playback_command_async( devices.record_playback_command(&target_for_write, command) }) .await; + let result = result + .map_err(|err| format!("{label} failed: {err}")) + .and_then(|result| result.map_err(|err| format!("{label} failed: {err:#}"))); + if let Some(id) = request_id { + let _ = tx.send(AppEvent::RemoteCommandRecorded { + id, + result: result.clone(), + }); + } match result { - Ok(Ok(())) => { + Ok(()) => { request_urgent_device_sync_parts( federation, sync_devices, @@ -1080,13 +1185,11 @@ fn record_playback_command_async( requested, ); } - Ok(Err(err)) => { - tracing::warn!(%err, target, "recording playback command failed"); - let _ = tx.send(AppEvent::StatusMessage(format!("{label} failed: {err:#}"))); - } Err(err) => { - tracing::warn!(%err, target, "recording playback command task failed"); - let _ = tx.send(AppEvent::StatusMessage(format!("{label} failed: {err}"))); + tracing::warn!(%err, target, "recording playback command failed"); + if request_id.is_none() { + let _ = tx.send(AppEvent::StatusMessage(err)); + } } } }); @@ -2136,44 +2239,61 @@ fn is_controlled_playback_effect(effect: &Effect) -> bool { } fn perform_control_playback_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { + use remote_playback::Change; + if state.device_playback.role == state::DevicePlaybackRole::Control + && let Err(reason) = remote_playback::available(state) + { + remote_playback::restore(state); + state.status_message = Some(reason.into()); + return; + } let mut seek = false; let local_only_volume = state.device_playback.role == state::DevicePlaybackRole::Jam && matches!(effect, Effect::SetVolume(_)); - match effect { + let change = match effect { Effect::PlayCurrent | Effect::PlayCurrentFromStart => { state.player.current = state.player.queue.get(state.player.queue_pos).cloned(); state.player.playing = state.player.current.is_some(); state.player.paused = false; state.player.position_secs = 0.0; seek = true; + Change::Start } - Effect::TogglePause => {} + Effect::TogglePause => Change::Transport, Effect::StopPlayback => { state.player.playing = false; state.player.current = None; state.player.paused = false; state.player.position_secs = 0.0; + Change::Transport } Effect::SeekBy(delta) => { state.player.position_secs = (state.player.position_secs + delta as f64).max(0.0); + if let Some(track) = &state.player.current + && track.duration_seconds > 0.0 + { + state.player.position_secs = state.player.position_secs.min(track.duration_seconds); + } seek = true; + Change::Seek } Effect::SetVolume(volume) => { state.player.volume = volume.min(100); - save_app_settings(state); + if local_only_volume { + save_app_settings(state); + } + Change::Volume } - Effect::SetOptions - | Effect::RemoveQueueIndices { .. } + Effect::SetOptions => Change::Options, + Effect::RemoveQueueIndices { .. } | Effect::PlaybackQueueChanged - | Effect::QueueOrderChanged { .. } - | Effect::LoadListenHistory - | Effect::ChangeMusicDirectory { .. } => {} - _ => {} - } + | Effect::QueueOrderChanged { .. } => Change::Queue, + _ => return, + }; if local_only_volume { return; } - record_control_playback_state(state, runtime, seek); + record_control_playback_state(state, runtime, seek, change); } fn clamp_settings_cursor(state: &mut AppState) { @@ -3319,8 +3439,7 @@ fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) { let _ = runtime.devices.playback_tick(false, false); return; } - let playing = - state.device_playback.is_audio_owner() && state.player.playing && !state.player.paused; + let playing = state.device_playback.is_audio_owner() && runtime.player.shared.output_playing(); let owner = match runtime.devices.playback_tick(true, playing) { Ok(owner) => owner, Err(error) => { @@ -3343,11 +3462,14 @@ fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) { if !state.device_playback.is_audio_owner() { become_active_device(state, runtime, true); } - } else if let Some(snapshot) = state.device_playback.remote.get(&owner).cloned() { - if state.device_playback.last_remote_snapshot.as_ref() != Some(&snapshot) - || state.device_playback.is_audio_owner() + } else if let Some(snapshot) = state.device_playback.remote.get(&owner) { + let waiting = state.device_playback.control.busy() + && state.device_playback.active_device_id.as_ref() == Some(&owner); + if !waiting + && (state.device_playback.last_remote_snapshot.as_ref() != Some(snapshot) + || state.device_playback.is_audio_owner()) { - become_control_device(state, runtime, snapshot); + become_control_device(state, runtime, snapshot.clone()); } } else { runtime.player.set_playback_allowed(false); @@ -3367,6 +3489,15 @@ fn handle_device_playback_snapshot( if snapshot.device_id == state.device_playback.self_device_id { return; } + // Concurrent sync workers can enqueue reports in a different order + // from the one in which DeviceSync accepted their heartbeats. + if let Some(previous) = state.device_playback.remote.get(&snapshot.device_id) + && let (Some(old), Some(new)) = (&previous.coordination, &snapshot.coordination) + && (&new.claim, new.heartbeat) <= (&old.claim, old.heartbeat) + { + return; + } + remote_playback::observe(state, &snapshot, std::time::Instant::now()); state .device_playback .remote @@ -3540,6 +3671,8 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent return; }; match event { + AppEvent::Control(request) => control::dispatch(state, runtime, request), + AppEvent::RadioReady { id, result } => radio::ready(state, runtime, id, result), AppEvent::Lyrics(event) => lyrics::handle_event(state, event), // Folded in by podcast_runtime::handle_event above. AppEvent::PodcastStoreOpened(_) @@ -3597,6 +3730,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent state.status_message = Some(state.updater.message.clone()); } AppEvent::StatusMessage(message) => state.status_message = Some(message), + AppEvent::RemoteCommandRecorded { id, result } => { + remote_playback::recorded(state, id, result) + } AppEvent::ListenHistoryLoaded(result) => { state.listen_history = Some(match result { Ok(entries) => state::Loadable::Ready(entries), @@ -3705,6 +3841,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent state.federation.devices = Some(runtime.devices.status()); } AppEvent::DevicePlayback(snapshot) => { + radio::remote_started(state, &snapshot); handle_device_playback_snapshot(state, runtime, snapshot); } AppEvent::PlaybackCommand { .. } @@ -3755,6 +3892,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } } AppEvent::JamPlayback(snapshot) => { + radio::remote_started(state, &snapshot); let local_volume = state.player.volume; become_control_device(state, runtime, snapshot); state.device_playback.role = state::DevicePlaybackRole::Jam; @@ -4296,6 +4434,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } AppEvent::Player(player::PlayerEvent::Started) => { runtime.player_start_pending = false; + radio::started(state); state.lyrics.refresh_local(); } AppEvent::Player(player::PlayerEvent::TrackFinished { has_next }) => { @@ -4344,6 +4483,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } } AppEvent::Player(player::PlayerEvent::Failed(message)) => { + radio::failed(state, &message); podcast_runtime::player_failed(runtime); runtime.player_start_pending = false; tracing::error!(%message, "playback failed"); @@ -4554,16 +4694,16 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent MediaCommand::Next => action::Action::NextTrack, MediaCommand::Previous => action::Action::PrevTrack, MediaCommand::Stop => { + if state.device_playback.is_control() { + perform_effect(state, runtime, Effect::StopPlayback); + return; + } runtime.player_start_pending = false; state.player.playing = false; state.player.paused = false; state.player.current = None; - if state.device_playback.is_control() { - record_control_playback_state(state, runtime, false); - } else { - runtime.player.stop(); - push_media_update(state, runtime, true); - } + runtime.player.stop(); + push_media_update(state, runtime, true); return; } }; diff --git a/src/app/radio.rs b/src/app/radio.rs new file mode 100644 index 0000000..26c8b8b --- /dev/null +++ b/src/app/radio.rs @@ -0,0 +1,286 @@ +//! One-shot similarity radio: collect the whole candidate set before replacing +//! the queue. It is independent of the user's search page and request sequence. +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use furumi_control_protocol::{Radio as Status, RadioState}; + +use super::event::AppEvent; +use super::state::{AppState, SimilaritySearchHit}; +use super::{Runtime, update}; +use crate::library::models::TrackItem; + +#[derive(Debug, Default)] +pub(super) struct Radio { + pub status: Status, + seed: String, + owner: Option, + queue: Vec, + expected: Option, + expected_queue: Vec, + remote_baseline: Option, + deadline: Option, +} + +fn identity(track: &TrackItem) -> String { + track + .content_id + .clone() + .unwrap_or_else(|| track.key().to_string()) +} + +fn queue_identity(state: &AppState) -> Vec { + state.player.queue.iter().map(identity).collect() +} + +fn busy(state: &AppState) -> bool { + matches!( + state.radio.status.state, + RadioState::Searching | RadioState::Starting + ) +} + +pub(super) fn begin(state: &mut AppState) -> Result { + if busy(state) { + return Err("Radio is already being prepared".into()); + } + if !state.similarity.settings.enabled { + return Err("Enable similarity search in Furumi Settings first".into()); + } + let seed = state + .player + .current + .clone() + .ok_or("Play a music track before starting radio")?; + if seed.is_podcast() { + return Err("Similarity radio is available for music tracks only".into()); + } + state.radio = Radio { + status: Status { + id: state.radio.status.id.wrapping_add(1), + state: RadioState::Searching, + error: None, + }, + seed: identity(&seed), + owner: state.device_playback.active_device_id.clone(), + queue: queue_identity(state), + expected: None, + expected_queue: Vec::new(), + remote_baseline: None, + deadline: Some(Instant::now() + Duration::from_secs(95)), + }; + Ok(seed) +} + +pub(super) fn start(state: &mut AppState, runtime: &mut Runtime) -> Result<(), String> { + let seed = begin(state)?; + if let Some(previous) = runtime.radio_task.take() { + previous.abort(); + } + let id = state.radio.status.id; + let (similarity, federation, library, tx) = ( + Arc::clone(&runtime.similarity), + Arc::clone(&runtime.federation), + Arc::clone(&runtime.library), + runtime.event_tx.clone(), + ); + let network = state.federation.settings.enabled && runtime.similarity.network_allowed(); + runtime.radio_task = Some(tokio::spawn(async move { + let work = async move { + let (local, query) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { + // A controller's numeric row IDs are not the output's IDs. + let local_seed = if seed.id >= 0 && seed.fed.is_none() { seed.id } else { + let content_id = seed.content_id.as_deref().ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?; + library.track_by_content_id(content_id)?.ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?.id + }; + similarity.search_track(local_seed, 49) + }).await.map_err(|error| format!("Radio search worker failed: {error}"))? + .map_err(|error| format!("Radio search failed: {error:#}"))?; + let mut hits: Vec<_> = local + .into_iter() + .map(|hit| SimilaritySearchHit::Local { + track: hit.track, + score: hit.score, + embedding_signature: hit.embedding_signature, + }) + .collect(); + if network { + // Await the full existing bounded fan-out, not its first answer. + let remote = tokio::time::timeout( + Duration::from_secs(75), + federation.search_similar(query, 50), + ) + .await; + match remote { + Ok(Ok(remote)) => hits.extend(remote.tracks.into_iter().map(|hit| { + SimilaritySearchHit::Federated { + track: hit.track, + score: hit.score, + embedding_signature: hit.embedding_signature, + } + })), + _ if !hits.is_empty() => { + tracing::debug!("radio peer search unavailable; using local matches") + } + _ => { + return Err( + "No radio matches available; peer search failed or timed out".into(), + ); + } + } + } + Ok(hits) + }; + let result = tokio::time::timeout(Duration::from_secs(90), work) + .await + .unwrap_or_else(|_| Err("Radio search timed out; existing queue was kept".into())); + let _ = tx.send(AppEvent::RadioReady { id, result }); + })); + Ok(()) +} + +/// Pure commit boundary: errors, stale generations and changed playback never +/// replace the user's queue. Ranking is shared with the TUI's similarity view. +pub(super) fn prepare( + state: &mut AppState, + id: u64, + result: Result, String>, +) -> bool { + if id != state.radio.status.id || state.radio.status.state != RadioState::Searching { + return false; + } + if !seed_current(state) { + fail(state, "Playback changed while radio was being prepared"); + return false; + } + if let Err(reason) = super::remote_playback::available(state) { + fail(state, reason); + return false; + } + let mut hits = match result { + Ok(hits) => hits, + Err(error) => { + fail(state, &error); + return false; + } + }; + super::rank_similarity_search_tracks( + &mut hits, + state.similarity.settings.max_tracks_per_artist, + ); + let tracks: Vec<_> = hits + .into_iter() + .map(|hit| hit.track_item()) + .filter(|track| !track.is_podcast() && identity(track) != state.radio.seed) + .collect(); + if tracks.is_empty() { + fail(state, "No similar tracks found; existing queue was kept"); + return false; + } + state.radio.expected = Some(identity(&tracks[0])); + state.radio.remote_baseline = state + .radio + .owner + .as_ref() + .and_then(|owner| state.device_playback.remote.get(owner)) + .map(|snapshot| snapshot.updated_at_ms); + state.radio.status.state = RadioState::Starting; + state.radio.deadline = Some(Instant::now() + Duration::from_secs(120)); + state.player.queue = tracks; + state.player.queue_pos = 0; + state.player.prefetched_pos = None; + state.queue_tab.cursor = 0; + update::on_new_queue(state); + state.radio.expected_queue = queue_identity(state); + true +} + +pub(super) fn ready( + state: &mut AppState, + runtime: &mut Runtime, + id: u64, + result: Result, String>, +) { + if prepare(state, id, result) { + super::perform_effect(state, runtime, update::Effect::PlayCurrent); + } +} + +fn seed_current(state: &AppState) -> bool { + state.player.current.as_ref().map(identity).as_ref() == Some(&state.radio.seed) + && state.device_playback.active_device_id == state.radio.owner + && queue_identity(state) == state.radio.queue +} + +fn fail(state: &mut AppState, error: &str) { + state.radio.status.state = RadioState::Failed; + state.radio.status.error = Some(error.into()); + state.radio.deadline = None; + state.status_message = Some(error.into()); +} + +pub(super) fn failed(state: &mut AppState, error: &str) { + if state.radio.status.state == RadioState::Starting { + fail(state, error); + } +} + +pub(super) fn started(state: &mut AppState) { + if state.radio.status.state == RadioState::Starting + && state.player.current.as_ref().map(identity) == state.radio.expected + && state.player.playing + && !state.player.paused + { + state.radio.status.state = RadioState::Playing; + state.radio.deadline = None; + } +} + +pub(super) fn remote_started(state: &mut AppState, snapshot: &crate::devices::PlaybackSnapshot) { + use crate::devices::PlaybackTrackExt as _; + if state.radio.status.state == RadioState::Starting + && snapshot.active + && snapshot.state.playing + && !snapshot.state.paused + // The wire's playing flag is intent; advancing position confirms the + // output passed source preparation, rather than merely accepting it. + && snapshot.state.position_secs > 0.0 + && state.radio.remote_baseline.is_none_or(|baseline| snapshot.updated_at_ms > baseline) + && Some(&snapshot.device_id) == state.radio.owner.as_ref() + && snapshot.state.queue.iter().map(|track| identity(&track.to_track_item())).collect::>() == state.radio.expected_queue + && snapshot + .state + .queue + .get(snapshot.state.queue_pos) + .map(|track| identity(&track.to_track_item())) + == state.radio.expected + { + state.radio.status.state = RadioState::Playing; + state.radio.deadline = None; + } +} + +pub(super) fn tick(state: &mut AppState, runtime: &mut Runtime) { + if !busy(state) { + return; + } + if state.radio.status.state == RadioState::Searching && !seed_current(state) { + fail(state, "Playback changed while radio was being prepared"); + } else if state.device_playback.active_device_id != state.radio.owner { + fail( + state, + "Playback device changed while radio was being prepared", + ); + } else if state + .radio + .deadline + .is_some_and(|deadline| Instant::now() > deadline) + { + fail(state, "Radio preparation timed out"); + } + if !busy(state) + && let Some(task) = runtime.radio_task.take() + { + task.abort(); + } +} diff --git a/src/app/remote_playback.rs b/src/app/remote_playback.rs new file mode 100644 index 0000000..0216f50 --- /dev/null +++ b/src/app/remote_playback.rs @@ -0,0 +1,324 @@ +//! Client-side completion of personal-device controls. Only a fresh output +//! report can finish a request. Nothing here is serialized to another device. +use std::time::{Duration, Instant}; + +use furumi_control_protocol::{RemoteCommand, RemoteCommandState}; +use music_dht::playback::Claim; + +use super::state::{AppState, DevicePlaybackRole, PlayerBar}; +use crate::config::settings::LibrarySourceMode; +use crate::devices::{PlaybackSnapshot, PlaybackStateWire, PlaybackTrack}; + +pub(super) const WAITING: &str = "Waiting for the active device"; +const TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Debug, Clone, Copy)] +pub(super) enum Change { + Transport, + Start, + Seek, + Volume, + Options, + Queue, +} + +#[derive(Debug)] +struct Pending { + owner: String, + claim: Option, + heartbeat: u64, + written: bool, + started: Instant, + change: Change, + desired: PlaybackStateWire, + same_item: bool, +} + +#[derive(Debug, Default)] +pub(crate) struct RemotePlayback { + pub(crate) status: RemoteCommand, + pending: Option, + // The resolved UI projection preserves local cover paths and podcast + // identities when discarding a speculative edit. No DB access on input. + confirmed: Option, + source_mode: Option, +} + +impl RemotePlayback { + pub(crate) fn busy(&self) -> bool { + self.pending.is_some() + } + + fn finish(&mut self, error: Option) { + self.pending = None; + self.status.state = if error.is_some() { + RemoteCommandState::Failed + } else { + RemoteCommandState::Confirmed + }; + self.status.error = error; + } +} + +// A heartbeat normally changes only the position. Keep the resolved queue +// across those reports instead of copying every track on every heartbeat. +pub(super) fn remember(state: &mut AppState, report: &PlaybackSnapshot) { + let device = &mut state.device_playback; + let remote = &mut device.control; + let unchanged = device.last_remote_snapshot.as_ref().is_some_and(|old| { + let (a, b) = (&old.state, &report.state); + old.device_id == report.device_id + && a.queue == b.queue + && a.queue_pos == b.queue_pos + && a.playing == b.playing + && a.paused == b.paused + && a.volume == b.volume + && a.shuffle == b.shuffle + && a.repeat == b.repeat + }); + if unchanged + && remote.source_mode == Some(state.global.filters.source_mode) + && let Some(confirmed) = &mut remote.confirmed + { + confirmed.position_secs = state.player.position_secs; + } else { + remote.confirmed = Some(state.player.clone()); + remote.source_mode = Some(state.global.filters.source_mode); + } +} + +pub(super) fn restore(state: &mut AppState) { + if let Some(last) = &state.device_playback.last_remote_snapshot + && state.device_playback.active_device_id.as_ref() == Some(&last.device_id) + && let Some(confirmed) = &state.device_playback.control.confirmed + { + state.player.clone_from(confirmed); + state.device_playback.local_idle_since_ms = last.state.idle_since_ms; + state.queue_tab.cursor = state + .queue_tab + .cursor + .min(state.player.queue.len().saturating_sub(1)); + super::extrapolate_control_position(state); + } +} + +pub(super) fn available(state: &AppState) -> Result<(), &'static str> { + let device = &state.device_playback; + if device.role != DevicePlaybackRole::Control { + return Ok(()); + } + if device.control.busy() { + return Err(WAITING); + } + device + .active_device_id + .as_ref() + .map(|_| ()) + .ok_or("No active playback device") +} + +pub(super) fn begin( + state: &mut AppState, + change: Change, + desired: PlaybackStateWire, + now: Instant, +) -> Result { + // update() may already have edited the queue, modes or pause flag to + // build the outgoing SetState. Restore the screen before it can repaint. + restore(state); + let device = &mut state.device_playback; + if device.control.busy() { + return Err(WAITING); + } + let owner = device + .active_device_id + .as_ref() + .ok_or("No active playback device")?; + let last = device + .last_remote_snapshot + .as_ref() + .filter(|s| s.device_id == *owner); + let same_item = last.is_some_and(|s| same_current(&s.state, &desired)); + let announcement = last.and_then(|s| s.coordination.as_ref()); + let generation = device.control.status.id.wrapping_add(1); + device.control.pending = Some(Pending { + owner: owner.clone(), + claim: announcement.and_then(|a| a.claim.clone()), + heartbeat: announcement.map_or(0, |a| a.heartbeat), + written: false, + started: now, + change, + desired, + same_item, + }); + device.control.status = RemoteCommand { + id: generation, + state: RemoteCommandState::Pending, + error: None, + }; + Ok(generation) +} + +pub(super) fn recorded(state: &mut AppState, id: u64, result: Result<(), String>) { + let control = &mut state.device_playback.control; + if id != control.status.id { + return; + } + let Some(pending) = &mut control.pending else { + return; + }; + match result { + Ok(()) => pending.written = true, + Err(error) => { + state.status_message = Some(error.clone()); + control.finish(Some(error)); + } + } +} + +// IDs and file paths belong to the originating library. Older music entries +// without a content ID can still be compared by portable display metadata. +fn same_item(a: &PlaybackTrack, b: &PlaybackTrack) -> bool { + use music_dht::device_sync::PlaybackSource; + match (&a.source, &b.source) { + (Some(PlaybackSource::PodcastEpisode(a)), Some(PlaybackSource::PodcastEpisode(b))) => { + return a.episode_id == b.episode_id; + } + (Some(PlaybackSource::Private), Some(PlaybackSource::Private)) => return true, + (None | Some(PlaybackSource::Music), None | Some(PlaybackSource::Music)) => {} + _ => return false, + } + let content = |t: &PlaybackTrack| { + t.content_id + .as_deref() + .or_else(|| t.fed.as_ref().map(|f| f.content_id.as_str())) + .and_then(music_dht::normalize_content_id) + }; + if let (Some(a), Some(b)) = (content(a), content(b)) { + return a == b; + } + if let (Some(a), Some(b)) = (&a.fed, &b.fed) { + return a.owner == b.owner && a.item_id == b.item_id; + } + a.title == b.title + && a.release_title == b.release_title + && a.artist_names == b.artist_names + && a.track_number == b.track_number + && a.disc_number == b.disc_number +} + +fn same_current(a: &PlaybackStateWire, b: &PlaybackStateWire) -> bool { + a.queue_pos == b.queue_pos + && match (a.queue.get(a.queue_pos), b.queue.get(b.queue_pos)) { + (Some(a), Some(b)) => same_item(a, b), + (None, None) => true, + _ => false, + } +} + +impl Pending { + fn matches(&self, actual: &PlaybackStateWire, output_playing: bool, age: Duration) -> bool { + let want = &self.desired; + let transport = actual.playing == want.playing + && actual.paused == want.paused + && output_playing == (want.playing && !want.paused); + let position_matches = || { + let elapsed = if output_playing { + age.as_secs_f64() + } else { + 0.0 + }; + actual.position_secs >= want.position_secs - 0.75 + && actual.position_secs <= want.position_secs + elapsed + 0.75 + }; + let queue_matches = || { + want.queue.len() == actual.queue.len() + && want + .queue + .iter() + .zip(&actual.queue) + .all(|(a, b)| same_item(a, b)) + }; + match self.change { + Change::Transport => transport && (!want.playing || same_current(want, actual)), + Change::Start => { + transport + && same_current(want, actual) + && queue_matches() + && (!self.same_item || position_matches()) + } + Change::Seek => transport && same_current(want, actual) && position_matches(), + Change::Volume => actual.volume == want.volume, + Change::Options => actual.repeat == want.repeat && actual.shuffle == want.shuffle, + Change::Queue => same_current(want, actual) && queue_matches(), + } + } +} + +pub(super) fn observe(state: &mut AppState, report: &PlaybackSnapshot, now: Instant) { + tick(state, now); + let device = &mut state.device_playback; + let Some(pending) = &mut device.control.pending else { + return; + }; + if device.role != DevicePlaybackRole::Control || pending.owner != report.device_id { + return; + } + let Some(announcement) = &report.coordination else { + return; + }; + let Some(claim) = &announcement.claim else { + return; + }; + if let Some(baseline) = &pending.claim { + if claim < baseline { + return; + } + if claim > baseline { + device + .control + .finish(Some("Playback ownership changed".into())); + state.status_message = device.control.status.error.clone(); + return; + } + } + if !report.active + || !announcement.available + || claim.owner != pending.owner + || announcement.heartbeat <= pending.heartbeat + { + return; + } + pending.heartbeat = announcement.heartbeat; + pending.claim.get_or_insert_with(|| claim.clone()); + if pending.written + && pending.matches( + &report.state, + announcement.playing, + now.saturating_duration_since(pending.started), + ) + { + device.control.finish(None); + } +} + +pub(super) fn tick(state: &mut AppState, now: Instant) { + let device = &mut state.device_playback; + if device.role != DevicePlaybackRole::Control { + device.control.confirmed = None; + } + let Some(pending) = &device.control.pending else { + return; + }; + let reason = if device.role != DevicePlaybackRole::Control + || device.active_device_id.as_ref() != Some(&pending.owner) + { + "Playback ownership changed" + } else if now.saturating_duration_since(pending.started) >= TIMEOUT { + "Active device did not confirm the command" + } else { + return; + }; + state.status_message = Some(reason.into()); + device.control.finish(Some(reason.into())); +} diff --git a/src/app/state.rs b/src/app/state.rs index 38b024c..1dc03ad 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -1663,7 +1663,7 @@ impl RepeatMode { /// Playback state mirrored for the UI: the queue, the loaded track and the /// position polled from the audio thread on every tick. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct PlayerBar { pub queue: Vec, pub queue_pos: usize, @@ -1732,6 +1732,7 @@ impl DevicePlaybackRole { #[derive(Debug, Default)] pub struct DevicePlaybackState { + pub(crate) control: super::remote_playback::RemotePlayback, pub config: music_dht::playback::Config, pub role: DevicePlaybackRole, pub self_device_id: String, @@ -2022,6 +2023,7 @@ pub struct AppState { pub queue_tab: QueueTab, pub federation: FederationTab, pub similarity: SimilarityTab, + pub(super) radio: super::radio::Radio, pub podcasts: PodcastsTab, /// The one federated artist card being viewed (name + loading state); /// opening another card replaces it. diff --git a/src/app/update.rs b/src/app/update.rs index df5a6fd..2e17070 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -167,6 +167,29 @@ pub enum Effect { } pub fn update(state: &mut AppState, action: Action) -> Option { + if matches!( + action, + Action::PlayPause + | Action::NextTrack + | Action::PrevTrack + | Action::SeekForward { .. } + | Action::SeekBackward { .. } + | Action::VolumeUp + | Action::VolumeDown + | Action::CycleRepeat + | Action::ToggleShuffle + | Action::ClearQueue + | Action::RemoveFromQueue + | Action::MoveQueueUp + | Action::MoveQueueDown + | Action::QueueAddNext + | Action::QueueAddLast + | Action::RestartEpisode + ) && let Err(reason) = super::remote_playback::available(state) + { + state.status_message = Some(reason.into()); + return None; + } // Any action other than a second Quit press disarms the confirmation. let quit_armed = state .quit_armed_until diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index ba2ad2d..479e34e 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -132,6 +132,424 @@ fn test_track(id: i64) -> TrackItem { } } +#[test] +fn control_snapshot_keeps_idle_devices_and_hides_revoked_members() { + let mut state = AppState::default(); + state.device_playback.self_device_id = "self".into(); + state.device_playback.self_device_name = "Local".into(); + state.federation.devices = Some(crate::devices::DeviceSyncStatus { + devices: vec![crate::devices::DeviceStatusRow { + device_id: "revoked".into(), + revoked: true, + ..Default::default() + }], + ..Default::default() + }); + let snapshot = crate::app::control::published(&state, 9).snapshot; + assert_eq!(snapshot.revision, 9); + assert!(snapshot.track.is_none()); + assert_eq!(snapshot.devices.len(), 1); + assert!(snapshot.devices[0].online && snapshot.devices[0].can_transfer); + assert!( + crate::app::control::intent( + &state, + furumi_control_protocol::Command::Transfer { + device_id: "revoked".into() + } + ) + .is_err() + ); +} + +#[test] +fn control_handoff_checks_liveness_jam_and_episode_protocol() { + use furumi_control_protocol::Command; + let mut state = AppState::default(); + state.device_playback.self_device_id = "self".into(); + state.player.queue = vec![crate::app::podcast_fixtures::episode_track(1)]; + state.federation.devices = Some(crate::devices::DeviceSyncStatus { + devices: vec![crate::devices::DeviceStatusRow { + device_id: "old".into(), + name: "Old".into(), + protocol_version: 3, + last_seen_ms: Some(crate::app::state::unix_time_ms()), + ..Default::default() + }], + ..Default::default() + }); + let command = Command::Transfer { + device_id: "old".into(), + }; + assert!(crate::app::control::intent(&state, command.clone()).is_err()); + state.federation.devices.as_mut().unwrap().devices[0].protocol_version = 4; + assert!(crate::app::control::intent(&state, command.clone()).is_ok()); + state.device_playback.role = crate::app::state::DevicePlaybackRole::Jam; + assert!(crate::app::control::intent(&state, command.clone()).is_err()); + state.device_playback.role = crate::app::state::DevicePlaybackRole::Active; + state.federation.devices.as_mut().unwrap().devices[0].last_seen_ms = None; + assert!(crate::app::control::intent(&state, command).is_err()); +} + +#[test] +fn control_uses_episode_identity_and_validates_relative_seek() { + use furumi_control_protocol::Command; + let mut state = AppState::default(); + state.player.current = Some(crate::app::podcast_fixtures::episode_track(1)); + let first = crate::app::control::published(&state, 0) + .snapshot + .track + .unwrap() + .key; + state.player.current = Some(crate::app::podcast_fixtures::episode_track(2)); + let second = crate::app::control::published(&state, 0) + .snapshot + .track + .unwrap() + .key; + assert_ne!(first, second); + assert!(crate::app::control::intent(&state, Command::Seek { seconds: i64::MIN }).is_err()); + assert!(matches!( + crate::app::control::intent(&state, Command::Seek { seconds: -10 }), + Ok(crate::app::control::Intent::Action(Action::SeekBackward { + seconds: 10 + })) + )); +} + +#[test] +fn ctl_can_request_a_remote_release_cover_without_exposing_podcast_metadata() { + use crate::app::control::published; + use crate::library::models::ArtistRef; + let mut s = AppState::default(); + let mut remote = test_track(1); + remote.artists.push(ArtistRef { + id: 4, + name: "Artist".into(), + }); + s.player.current = Some(remote); + s.federation.settings.enabled = true; + let view = published(&s, 1); + assert!(view.artwork.path.is_none()); + assert_eq!(view.artwork.release.as_ref().unwrap().artist, "Artist"); + assert!(view.snapshot.track.unwrap().artwork_id.is_some()); + s.player.current = Some(crate::app::podcast_fixtures::episode_track(1)); + assert!(published(&s, 2).artwork.release.is_none()); + s.player.current = None; + assert!(published(&s, 3).artwork.release.is_none()); +} + +fn radio_state() -> AppState { + let mut state = AppState::default(); + state.similarity.settings.enabled = true; + state.similarity.settings.max_tracks_per_artist = 5; + state.device_playback.active_device_id = Some("self".into()); + state.player.current = Some(test_track(1)); + state.player.queue = vec![test_track(1), test_track(2)]; + state.player.playing = true; + state +} + +fn radio_hit(id: i64, score: f32) -> crate::app::state::SimilaritySearchHit { + crate::app::state::SimilaritySearchHit::Local { + track: test_track(id), + score, + embedding_signature: [id as u8; music_dht::similarity::SIMILARITY_SIGNATURE_BYTES], + } +} + +fn controlling_player() -> (AppState, crate::devices::PlaybackSnapshot) { + use crate::app::{playback_state_from_ui, remote_playback, state::DevicePlaybackRole}; + use music_dht::playback::{Announcement, Claim}; + let mut s = radio_state(); + s.device_playback.role = DevicePlaybackRole::Control; + s.device_playback.active_device_id = Some("web".into()); + let report = crate::devices::PlaybackSnapshot { + device_id: "web".into(), + device_name: "WEB".into(), + active: true, + updated_at_ms: crate::app::state::unix_time_ms(), + state: playback_state_from_ui(&s), + coordination: Some(Announcement { + version: 1, + heartbeat: 10, + available: true, + playing: true, + claim: Some(Claim { + counter: 8, + issuer: "self".into(), + owner: "web".into(), + }), + }), + }; + remote_playback::remember(&mut s, &report); + s.device_playback.last_remote_snapshot = Some(report.clone()); + (s, report) +} + +#[test] +fn a_control_pause_waits_for_the_owners_fresh_output_report() { + use crate::app::{control, playback_state_from_ui, remote_playback as remote}; + use furumi_control_protocol::{Command, RemoteCommandState}; + let (mut s, mut report) = controlling_player(); + let start = std::time::Instant::now(); + assert!(matches!( + update(&mut s, Action::PlayPause), + Some(Effect::TogglePause) + )); + let desired = playback_state_from_ui(&s); + let id = remote::begin(&mut s, remote::Change::Transport, desired, start).unwrap(); + let snapshot = control::published(&s, 1).snapshot; + assert!(!snapshot.paused); + assert_eq!( + snapshot.remote_command.unwrap().state, + RemoteCommandState::Pending + ); + assert!(update(&mut s, Action::PlayPause).is_none()); + assert!(control::intent(&s, Command::PlayPause).is_err()); + assert!(control::intent(&s, Command::StartRadio).is_err()); + // Existing media/keyboard bindings and the local API share the lock. + assert!(!s.player.paused); + report.state.paused = true; + report.coordination.as_mut().unwrap().playing = false; + report.coordination.as_mut().unwrap().heartbeat = 11; + remote::observe(&mut s, &report, start); + assert!(s.device_playback.control.busy()); // Write still in flight. + remote::recorded(&mut s, id, Ok(())); + for (device, heartbeat, paused, playing) in [ + ("laptop", 30, true, false), + ("web", 10, true, false), + ("web", 11, false, true), + ("web", 12, true, true), + ] { + report.device_id = device.into(); + report.state.paused = paused; + let a = report.coordination.as_mut().unwrap(); + a.heartbeat = heartbeat; + a.playing = playing; + remote::observe(&mut s, &report, start); + assert!(s.device_playback.control.busy()); + assert!(!control::published(&s, 2).snapshot.paused); + } + report.coordination.as_mut().unwrap().heartbeat = 13; + report.coordination.as_mut().unwrap().playing = false; + remote::observe(&mut s, &report, start); + assert_eq!( + s.device_playback.control.status.state, + RemoteCommandState::Confirmed + ); + crate::app::apply_playback_state_to_ui(&mut s, &report.state, None); + assert!(control::published(&s, 3).snapshot.paused); + assert!(control::intent(&s, Command::PlayPause).is_ok()); +} + +#[test] +fn controller_unlocks_on_timeout_write_failure_or_change_of_owner() { + use crate::app::remote_playback as remote; + use furumi_control_protocol::RemoteCommandState; + let (mut s, report) = controlling_player(); + let start = std::time::Instant::now(); + let mut desired = report.state.clone(); + desired.volume = 55; + let first = remote::begin(&mut s, remote::Change::Volume, desired.clone(), start).unwrap(); + remote::recorded(&mut s, first, Err("Device command failed".into())); + assert_eq!( + s.device_playback.control.status.state, + RemoteCommandState::Failed + ); + let second = remote::begin(&mut s, remote::Change::Volume, desired.clone(), start).unwrap(); + remote::recorded(&mut s, first, Err("Late failure".into())); + assert!(s.device_playback.control.busy()); + remote::recorded(&mut s, second, Ok(())); + remote::tick(&mut s, start + std::time::Duration::from_secs(16)); + assert_eq!( + s.device_playback.control.status.state, + RemoteCommandState::Failed + ); + assert_eq!(s.player.volume, report.state.volume); + remote::begin(&mut s, remote::Change::Volume, desired, start).unwrap(); + s.device_playback.active_device_id = Some("new owner".into()); + remote::tick(&mut s, start); + assert!(!s.device_playback.control.busy()); + assert_eq!( + s.device_playback.control.status.error.as_deref(), + Some("Playback ownership changed") + ); +} + +#[test] +fn remote_seek_modes_and_tracks_wait_for_the_requested_change() { + use crate::app::remote_playback as remote; + for change in [ + remote::Change::Seek, + remote::Change::Options, + remote::Change::Start, + remote::Change::Queue, + remote::Change::Volume, + ] { + let (mut s, mut report) = controlling_player(); + let start = std::time::Instant::now(); + let mut desired = report.state.clone(); + match change { + remote::Change::Seek => desired.position_secs = 30.0, + remote::Change::Options => desired.shuffle = true, + remote::Change::Start => desired.queue_pos = 1, + remote::Change::Queue => desired.queue.reverse(), + remote::Change::Volume => desired.volume = 55, + remote::Change::Transport => unreachable!(), + } + let id = remote::begin(&mut s, change, desired.clone(), start).unwrap(); + remote::recorded(&mut s, id, Ok(())); + report.coordination.as_mut().unwrap().heartbeat += 1; + remote::observe(&mut s, &report, start); + assert!(s.device_playback.control.busy(), "{change:?}"); + report.state = desired; + // Numeric IDs belong to the owner, even when content is the same. + report.state.queue[0].id = 5432; + report.coordination.as_mut().unwrap().heartbeat += 1; + remote::observe(&mut s, &report, start); + assert!(!s.device_playback.control.busy(), "{change:?}"); + } +} + +#[test] +fn radio_keeps_queue_until_collection_finishes_and_waits_for_audio_start() { + use furumi_control_protocol::RadioState; + let mut state = radio_state(); + let before: Vec<_> = state.player.queue.iter().map(|track| track.id).collect(); + crate::app::radio::begin(&mut state).unwrap(); + let id = state.radio.status.id; + assert_eq!(state.radio.status.state, RadioState::Searching); + assert_eq!( + state + .player + .queue + .iter() + .map(|track| track.id) + .collect::>(), + before + ); + assert!(crate::app::radio::prepare( + &mut state, + id, + Ok(vec![radio_hit(3, 0.8), radio_hit(4, 0.9)]) + )); + assert_eq!(state.player.queue[0].id, 4); + assert_eq!(state.radio.status.state, RadioState::Starting); + crate::app::radio::started(&mut state); // Old source still playing. + assert_eq!(state.radio.status.state, RadioState::Starting); + state.player.current = Some(state.player.queue[0].clone()); + state.player.paused = false; + crate::app::radio::started(&mut state); + assert_eq!(state.radio.status.state, RadioState::Playing); +} + +#[test] +fn radio_errors_empty_matches_and_stale_results_preserve_the_existing_queue() { + use furumi_control_protocol::RadioState; + for result in [Err("peer error".into()), Ok(vec![])] { + let mut state = radio_state(); + crate::app::radio::begin(&mut state).unwrap(); + let id = state.radio.status.id; + assert!(!crate::app::radio::prepare(&mut state, id, result)); + assert_eq!(state.player.queue[0].id, 1); + assert_eq!(state.radio.status.state, RadioState::Failed); + } + let mut state = radio_state(); + crate::app::radio::begin(&mut state).unwrap(); + let id = state.radio.status.id; + assert!(!crate::app::radio::prepare( + &mut state, + id + 1, + Ok(vec![radio_hit(3, 0.9)]) + )); + assert_eq!(state.radio.status.state, RadioState::Searching); + state.player.queue.push(test_track(9)); // A newer user queue must win. + assert!(!crate::app::radio::prepare( + &mut state, + id, + Ok(vec![radio_hit(3, 0.9)]) + )); + assert_eq!(state.player.queue.last().unwrap().id, 9); + assert_eq!(state.radio.status.state, RadioState::Failed); +} + +#[test] +fn radio_rechecks_owner_and_requires_music_and_enabled_similarity() { + let mut state = radio_state(); + state.similarity.settings.enabled = false; + assert!(crate::app::radio::begin(&mut state).is_err()); + state.similarity.settings.enabled = true; + state.player.current = Some(crate::app::podcast_fixtures::episode_track(1)); + assert!(crate::app::radio::begin(&mut state).is_err()); + state.player.current = Some(test_track(1)); + crate::app::radio::begin(&mut state).unwrap(); + let id = state.radio.status.id; + assert!(crate::app::radio::begin(&mut state).is_err()); + state.device_playback.active_device_id = Some("another".into()); + assert!(!crate::app::radio::prepare( + &mut state, + id, + Ok(vec![radio_hit(3, 0.9)]) + )); + assert_eq!(state.player.queue[0].id, 1); +} + +#[test] +fn radio_remote_start_requires_the_output_report_and_advancing_position() { + use crate::devices::PlaybackTrackExt as _; + use furumi_control_protocol::RadioState; + let mut state = radio_state(); + crate::app::radio::begin(&mut state).unwrap(); + let id = state.radio.status.id; + let mut snapshot = crate::devices::PlaybackSnapshot { + coordination: None, + device_id: "self".into(), + device_name: "Output".into(), + active: true, + updated_at_ms: 10, + state: crate::devices::PlaybackStateWire { + queue: vec![crate::devices::PlaybackTrack::from_track(&test_track(3))], + playing: true, + paused: false, + queue_pos: 0, + idle_since_ms: None, + position_secs: 0.0, + volume: 80, + shuffle: false, + repeat: crate::devices::PlaybackRepeat::Off, + playback_rate: None, + }, + }; + state + .device_playback + .remote + .insert("self".into(), snapshot.clone()); + assert!(crate::app::radio::prepare( + &mut state, + id, + Ok(vec![radio_hit(3, 0.9)]) + )); + crate::app::radio::remote_started(&mut state, &snapshot); + assert_eq!(state.radio.status.state, RadioState::Starting); + snapshot.state.position_secs = 0.1; + crate::app::radio::remote_started(&mut state, &snapshot); + assert_eq!(state.radio.status.state, RadioState::Starting); // Cached report. + snapshot.updated_at_ms = 11; + snapshot.device_id = "other".into(); + crate::app::radio::remote_started(&mut state, &snapshot); + assert_eq!(state.radio.status.state, RadioState::Starting); + snapshot.device_id = "self".into(); + snapshot + .state + .queue + .push(crate::devices::PlaybackTrack::from_track(&test_track(4))); + crate::app::radio::remote_started(&mut state, &snapshot); + assert_eq!(state.radio.status.state, RadioState::Starting); // Another queue. + snapshot.state.queue.pop(); + crate::app::radio::remote_started(&mut state, &snapshot); + assert_eq!(state.radio.status.state, RadioState::Playing); +} + fn pending_fed_track(id: i64) -> TrackItem { crate::federation::pending_track(&crate::federation::FedTrack { item_id: format!("fed-{id}"), diff --git a/src/control.rs b/src/control.rs new file mode 100644 index 0000000..85c2f84 --- /dev/null +++ b/src/control.rs @@ -0,0 +1,557 @@ +//! Authenticated, loopback-only control of this running player. No LAN authority. +use std::collections::VecDeque; +use std::io::{Cursor, Read as _}; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context as _, Result, bail, ensure}; +use base64::Engine as _; +use furumi_control_protocol::{ + API_VERSION, ClientMessage, Command, Discovery, MAX_MESSAGE_BYTES, ServerMessage, Snapshot, +}; +use futures_util::{SinkExt, StreamExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::{JoinHandle, JoinSet}; +use tokio_tungstenite::tungstenite::{Message, protocol::WebSocketConfig}; + +#[path = "control_art.rs"] +pub(crate) mod art; +#[path = "control_spectrum.rs"] +mod spectrum; +pub(crate) use spectrum::Spectrum; + +#[cfg(test)] +#[path = "control_tests.rs"] +mod tests; + +#[derive(Debug)] +pub struct Request { + pub command: Command, + pub reply: oneshot::Sender>, +} + +#[derive(Clone)] +pub struct Published { + pub snapshot: Snapshot, + /// Local-only, never serialized. Artwork requests must match the current ID. + pub(crate) artwork: art::Source, +} + +struct Queued { + id: String, + command: Command, + reply: oneshot::Sender, +} + +pub struct Service { + state: watch::Sender, + pub(crate) spectrum: Spectrum, + task: JoinHandle<()>, + discovery: PathBuf, + token: String, +} + +impl Service { + pub async fn start( + initial: Published, + events: mpsc::UnboundedSender, + library: Arc, + federation: Arc, + ) -> Result { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?; + let port = listener.local_addr()?.port(); + let (discovery, token) = tokio::task::spawn_blocking(move || -> Result<_> { + let path = furumi_control_protocol::discovery_path() + .context("no application data directory")?; + let token = rand::random::<[u8; 32]>() + .map(|byte| format!("{byte:02x}")) + .concat(); + write_discovery( + &path, + &Discovery { + api_version: API_VERSION, + port, + token: token.clone(), + }, + )?; + Ok((path, token)) + }) + .await??; + let (state, receiver) = watch::channel(initial); + let (commands, queue) = mpsc::channel(32); + let secret = token.clone(); + let covers = art::Covers::new(library, federation); + let spectrum = Spectrum::default(); + let frames = spectrum.frames.clone(); + let task = tokio::spawn(async move { + let mut tasks = JoinSet::new(); + tasks.spawn(broker(queue, events)); + let clients = Arc::new(tokio::sync::Semaphore::new(8)); + loop { + tokio::select! { + connection = listener.accept() => { + let Ok((socket, _)) = connection else { break }; + let Ok(permit) = clients.clone().try_acquire_owned() else { continue }; + let (state, token, commands, covers) = (receiver.clone(), secret.clone(), commands.clone(), covers.clone()); + let frames = frames.clone(); + tasks.spawn(async move { + let _permit = permit; + // Connection errors are deliberately not logged with private metadata. + let _ = session(socket, &token, state, commands, covers, frames).await; + }); + } + _ = tasks.join_next(), if !tasks.is_empty() => {} + } + } + }); + Ok(Self { + state, + spectrum, + task, + discovery, + token, + }) + } + + pub fn publish(&self, value: Published) { + self.state.send_replace(value); + } + + pub async fn shutdown(mut self) { + self.task.abort(); + let _ = (&mut self.task).await; + let (path, token) = (self.discovery.clone(), std::mem::take(&mut self.token)); + let _ = tokio::task::spawn_blocking(move || remove_discovery(&path, &token)).await; + } +} + +impl Drop for Service { + fn drop(&mut self) { + self.task.abort(); + if self.token.is_empty() { + return; + } + let (path, token) = (self.discovery.clone(), self.token.clone()); + // Avoid filesystem work during terminal teardown and never remove a successor's endpoint. + let _ = std::thread::Builder::new() + .name("control-cleanup".into()) + .spawn(move || remove_discovery(&path, &token)); + } +} + +fn remove_discovery(path: &std::path::Path, token: &str) { + if std::fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .is_some_and(|current| current.token == token) + { + let _ = std::fs::remove_file(path); + } +} + +fn write_discovery(path: &std::path::Path, value: &Discovery) -> Result<()> { + let parent = path.parent().context("invalid control endpoint path")?; + std::fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.as_file() + .set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + use std::io::Write as _; + file.write_all(&serde_json::to_vec(value)?)?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +async fn broker( + mut queue: mpsc::Receiver, + events: mpsc::UnboundedSender, +) { + // A reconnect/retry with the same ID never toggles pause or seeks twice. + let mut recent: VecDeque<(String, Command, ServerMessage)> = VecDeque::new(); + while let Some(request) = queue.recv().await { + if let Some((_, command, result)) = recent.iter().find(|(id, _, _)| id == &request.id) { + let result = if command == &request.command { + result.clone() + } else { + failure( + request.id.clone(), + "request ID already used for another command", + ) + }; + let _ = request.reply.send(result); + continue; + } + let (tx, rx) = oneshot::channel(); + let result = if events + .send(crate::app::event::AppEvent::Control(Request { + command: request.command.clone(), + reply: tx, + })) + .is_err() + { + Err("player unavailable".into()) + } else { + tokio::time::timeout(Duration::from_secs(5), rx) + .await + .map_err(|_| "command timed out; result unknown".to_string()) + .and_then(|reply| reply.map_err(|_| "player unavailable".to_string())) + .and_then(|result| result) + }; + let result = ServerMessage::Result { + id: request.id.clone(), + accepted: result.is_ok(), + error: result.err(), + }; + if recent.len() == 256 { + recent.pop_front(); + } + recent.push_back((request.id, request.command, result.clone())); + let _ = request.reply.send(result); + } +} + +fn failure(id: String, message: &str) -> ServerMessage { + ServerMessage::Result { + id, + accepted: false, + error: Some(message.into()), + } +} + +#[expect( + clippy::result_large_err, + reason = "tungstenite fixes the handshake callback error to an HTTP response" +)] +fn native_handshake( + request: &tokio_tungstenite::tungstenite::handshake::server::Request, + response: tokio_tungstenite::tungstenite::handshake::server::Response, +) -> std::result::Result< + tokio_tungstenite::tungstenite::handshake::server::Response, + tokio_tungstenite::tungstenite::handshake::server::ErrorResponse, +> { + // Browser pages cannot use localhost as an ambient control channel. + if request.headers().contains_key("origin") { + let mut denied = tokio_tungstenite::tungstenite::handshake::server::ErrorResponse::new( + Some("native clients only".into()), + ); + *denied.status_mut() = tokio_tungstenite::tungstenite::http::StatusCode::FORBIDDEN; + Err(denied) + } else { + Ok(response) + } +} + +async fn session( + socket: TcpStream, + token: &str, + mut state: watch::Receiver, + commands: mpsc::Sender, + covers: Arc, + frames: watch::Sender, +) -> Result<()> { + let config = WebSocketConfig::default() + .max_message_size(Some(16 * 1024)) + .max_frame_size(Some(16 * 1024)); + let mut socket = tokio::time::timeout( + Duration::from_secs(5), + tokio_tungstenite::accept_hdr_async_with_config(socket, native_handshake, Some(config)), + ) + .await??; + let auth = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await? + .context("missing authentication")??; + let authenticated = matches!(auth, Message::Text(ref data) if matches!(serde_json::from_str::(data), Ok(ClientMessage::Authenticate {token: supplied, api_version}) if api_version == API_VERSION && supplied == token)); + ensure!(authenticated, "authentication failed"); + let mut jobs = JoinSet::new(); + let mut pending_cover: Option<(String, String)> = None; + let mut spectrum_subscription = None; + let initial = state.borrow_and_update().snapshot.clone(); + send( + &mut socket, + ServerMessage::Snapshot { + snapshot: Box::new(initial), + }, + ) + .await?; + loop { + tokio::select! { + Some(frame) = spectrum::next_frame(&mut spectrum_subscription) => { + send(&mut socket, frame).await?; + } + Some(done) = jobs.join_next(), if !jobs.is_empty() => { + if let Ok((id, artwork_id, png_base64)) = done + && pending_cover.as_ref().is_some_and(|(i, key)| i == &id && key == &artwork_id) + { + pending_cover = None; + let current = state.borrow().snapshot.track.as_ref().and_then(|t| t.artwork_id.as_ref()) == Some(&artwork_id); + let reply = if current { ServerMessage::Artwork { id, artwork_id, png_base64 } } else { failure(id, "artwork is no longer current") }; + send(&mut socket, reply).await?; + } + } + changed = state.changed() => { + if changed.is_err() { break; } + let snapshot = state.borrow_and_update().snapshot.clone(); + if pending_cover.as_ref().is_some_and(|(_, key)| snapshot.track.as_ref().and_then(|t| t.artwork_id.as_ref()) != Some(key)) { + jobs.abort_all(); + if let Some((id, _)) = pending_cover.take() { + send(&mut socket, failure(id, "artwork is no longer current")).await?; + } + } + send(&mut socket, ServerMessage::Snapshot { snapshot: Box::new(snapshot) }).await?; + } + message = socket.next() => { + let Some(message) = message else { break }; + let data = match message? { + Message::Text(data) => data, + Message::Ping(data) => { socket.send(Message::Pong(data)).await?; continue; } + Message::Close(_) => break, + _ => continue, + }; + let (id, command) = match serde_json::from_str(&data)? { + ClientMessage::Command { id, command } => (id, command), + ClientMessage::SubscribeSpectrum { enabled } => { + if enabled { + spectrum_subscription.get_or_insert_with(|| frames.subscribe()); + } else { + spectrum_subscription = None; + } + tokio::time::sleep(Duration::from_millis(25)).await; + continue; + } + ClientMessage::Authenticate { .. } => bail!("already authenticated"), + }; + ensure!(!id.is_empty() && id.len() <= 128, "invalid request ID"); + let result = if let Command::Artwork { artwork_id, federation } = command { + let source = { + let current = state.borrow(); + current.snapshot.track.as_ref().is_some_and(|t| t.artwork_id.as_ref() == Some(&artwork_id)).then(|| current.artwork.clone()) + }; + if let Some(source) = source { + if let Some((previous, _)) = pending_cover.take() { + jobs.abort_all(); + send(&mut socket, failure(previous, "artwork request superseded")).await?; + } + pending_cover = Some((id.clone(), artwork_id.clone())); + let covers = covers.clone(); + jobs.spawn(async move { + let data = covers.get(&artwork_id, source, federation).await; + (id, artwork_id, data) + }); + None + } else { + Some(failure(id, "artwork is no longer current")) + } + } else { + let (reply, result) = oneshot::channel(); + if commands.try_send(Queued { id: id.clone(), command, reply }).is_err() { + Some(failure(id, "control queue busy")) + } else { + Some(result.await?) + } + }; + if let Some(result) = result { send(&mut socket, result).await?; } + // Bound a malfunctioning client's event and artwork request rate. + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + } + Ok(()) +} + +async fn send( + socket: &mut tokio_tungstenite::WebSocketStream, + message: ServerMessage, +) -> Result<()> { + let encoded = serde_json::to_string(&message)?; + ensure!(encoded.len() <= MAX_MESSAGE_BYTES, "snapshot too large"); + tokio::time::timeout( + Duration::from_secs(3), + socket.send(Message::Text(encoded.into())), + ) + .await??; + Ok(()) +} + +fn artwork(path: &std::path::Path) -> Result { + let mut bytes = Vec::new(); + std::fs::File::open(path)? + .take(10 * 1024 * 1024 + 1) + .read_to_end(&mut bytes)?; + ensure!(bytes.len() <= 10 * 1024 * 1024, "artwork too large"); + let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format()?; + let mut limits = image::Limits::default(); + limits.max_image_width = Some(8192); + limits.max_image_height = Some(8192); + limits.max_alloc = Some(64 * 1024 * 1024); + reader.limits(limits); + let image = reader + .decode()? + .resize_to_fill(384, 384, image::imageops::FilterType::Triangle); + let mut png = Cursor::new(Vec::new()); + image.write_to(&mut png, image::ImageFormat::Png)?; + Ok(base64::engine::general_purpose::STANDARD.encode(png.into_inner())) +} + +pub async fn cli(args: &[String]) -> Result<()> { + const USAGE: &str = "usage: furumi ctl status|devices|watch|play-pause|next|previous|seek SECONDS|volume-up|volume-down|transfer DEVICE_ID|shuffle|repeat|radio\n furumi ctl artwork [--federation] [--output FILE.png]"; + if args.is_empty() || args.iter().any(|arg| arg == "--help" || arg == "-h") { + println!("{USAGE}"); + return Ok(()); + } + let mode = args.first().map(String::as_str).context(USAGE)?; + let argument = || args.get(1).cloned().context("missing command argument"); + let command = match mode { + "status" | "devices" | "watch" | "artwork" => None, + "shuffle" => Some(Command::ToggleShuffle), + "repeat" => Some(Command::CycleRepeat), + "radio" => Some(Command::StartRadio), + "play-pause" => Some(Command::PlayPause), + "next" => Some(Command::Next), + "previous" => Some(Command::Previous), + "seek" => Some(Command::Seek { + seconds: argument()?.parse()?, + }), + "volume-up" => Some(Command::VolumeUp), + "volume-down" => Some(Command::VolumeDown), + "transfer" => Some(Command::Transfer { + device_id: argument()?, + }), + _ => bail!("unknown control command: {mode}"), + }; + let mut federated_art = false; + let mut art_output = None; + if mode == "artwork" { + let mut options = args[1..].iter(); + while let Some(option) = options.next() { + match option.as_str() { + "--federation" => federated_art = true, + "--output" if art_output.is_none() => { + art_output = Some(PathBuf::from( + options.next().context("missing output file")?, + )) + } + other => bail!("unknown or duplicate artwork option: {other}"), + } + } + } + let path = + furumi_control_protocol::discovery_path().context("no application data directory")?; + let endpoint: Discovery = serde_json::from_slice( + &tokio::fs::read(path) + .await + .context("Furumi is not running (no control endpoint)")?, + )?; + ensure!( + endpoint.api_version == API_VERSION, + "incompatible control API" + ); + let (mut socket, _) = tokio::time::timeout( + Duration::from_secs(3), + tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{}", endpoint.port)), + ) + .await??; + socket + .send(Message::Text( + serde_json::to_string(&ClientMessage::Authenticate { + token: endpoint.token, + api_version: API_VERSION, + })? + .into(), + )) + .await?; + let mut has_command = command.is_some(); + let request_id = format!("cli-{:032x}", rand::random::()); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + if let Some(command) = command { + let request = ClientMessage::Command { + id: request_id.clone(), + command, + }; + socket + .send(Message::Text(serde_json::to_string(&request)?.into())) + .await?; + } + loop { + let read_until = if mode == "artwork" { + deadline + } else { + tokio::time::Instant::now() + Duration::from_secs(10) + }; + let message = tokio::time::timeout_at(read_until, socket.next()) + .await? + .context("player disconnected")??; + let Message::Text(text) = message else { + continue; + }; + let message: ServerMessage = serde_json::from_str(&text)?; + match message { + ServerMessage::Snapshot { snapshot } if mode == "artwork" && !has_command => { + let artwork_id = snapshot + .track + .and_then(|t| t.artwork_id) + .context("no artwork available for the current track")?; + let request = ClientMessage::Command { + id: request_id.clone(), + command: Command::Artwork { + artwork_id, + federation: federated_art, + }, + }; + socket + .send(Message::text(serde_json::to_string(&request)?)) + .await?; + has_command = true; + } + ServerMessage::Artwork { id, png_base64, .. } if id == request_id => { + if let Some(path) = art_output { + let bytes = base64::engine::general_purpose::STANDARD + .decode(png_base64.context("artwork not found")?)?; + tokio::task::spawn_blocking(move || -> Result<()> { + use std::io::Write as _; + let directory = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(std::path::Path::new(".")); + let mut file = tempfile::NamedTempFile::new_in(directory)?; + file.write_all(&bytes)?; + file.persist_noclobber(&path) + .map_err(|e| e.error) + .context("could not create artwork output file")?; + Ok(()) + }) + .await??; + } else { + println!("{text}"); + } + return Ok(()); + } + ServerMessage::Snapshot { snapshot } if !has_command => { + if mode == "devices" { + println!("{}", serde_json::to_string(&snapshot.devices)?); + } else { + println!("{}", serde_json::to_string(&snapshot)?); + } + if mode != "watch" { + return Ok(()); + } + } + ServerMessage::Result { + accepted, error, .. + } => { + println!("{text}"); + ensure!( + accepted, + "{}", + error.unwrap_or_else(|| "command rejected".into()) + ); + return Ok(()); + } + _ => {} + } + } +} diff --git a/src/control_art.rs b/src/control_art.rs new file mode 100644 index 0000000..7d581ef --- /dev/null +++ b/src/control_art.rs @@ -0,0 +1,237 @@ +//! On-demand cover resolution for local control clients. A snapshot carries +//! lookup metadata only. The first explicit request starts the work. +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use futures_util::future::BoxFuture; +use tokio::sync::OnceCell; + +use crate::config::settings::LibrarySourceMode; +use crate::federation::Federation; +use crate::library::Library; + +#[derive(Clone, Debug, Default)] +pub(crate) struct Source { + pub path: Option, + pub release: Option, +} + +#[derive(Clone, Debug)] +pub(crate) struct Release { + pub artist: String, + pub title: String, + pub owners: Vec, + pub global: bool, + pub network_enabled: bool, +} + +impl Source { + pub fn current(state: &crate::app::state::AppState) -> Self { + let Some(track) = &state.player.current else { + return Self::default(); + }; + let path = track.cover_path.as_ref().map(PathBuf::from); + let release = if track.is_podcast() || crate::devices::is_private_track_item(track) { + None + } else { + let artist = track + .artists + .iter() + .map(|a| a.name.trim()) + .find(|a| !a.is_empty()) + .or_else(|| track.fed.as_ref()?.artist_names.first().map(|s| s.trim())); + let title = track.release_title.trim(); + artist + .filter(|a| !a.is_empty() && !title.is_empty()) + .map(|artist| { + let global = state.global.filters.source_mode == LibrarySourceMode::Global; + let trusted = state + .federation + .devices + .as_ref() + .map_or(&[][..], |s| s.devices.as_slice()); + let mut owners = Vec::new(); + if let Some(output) = trusted.iter().find(|d| { + !d.revoked + && !d.is_self + && Some(&d.device_id) == state.device_playback.active_device_id.as_ref() + }) && !output.endpoint_id.is_empty() + { + owners.push(output.endpoint_id.clone()); + } + if let Some(fed) = &track.fed + && !fed.owner.is_empty() + && !owners.contains(&fed.owner) + && (global + || trusted + .iter() + .any(|d| !d.revoked && d.endpoint_id == fed.owner)) + { + owners.push(fed.owner.clone()); + } + Release { + artist: artist.to_owned(), + title: title.to_owned(), + owners, + global, + network_enabled: state.federation.settings.enabled, + } + }) + }; + Self { path, release } + } + + pub fn id(&self, track_key: &str) -> Option { + if self.path.is_none() && self.release.is_none() { + return None; + } + let mut hash = blake3::Hasher::new(); + let mut field = |value: &[u8]| { + hash.update(&value.len().to_le_bytes()); + hash.update(value); + }; + field(track_key.as_bytes()); + if let Some(path) = &self.path { + field(path.as_os_str().as_encoded_bytes()); + } + if let Some(r) = &self.release { + field(r.artist.as_bytes()); + field(r.title.as_bytes()); + field(&[r.global as u8, r.network_enabled as u8]); + for owner in &r.owners { + field(owner.as_bytes()); + } + } + Some(hash.finalize().to_hex().to_string()) + } +} + +type Resolver = dyn Fn(Source, bool) -> BoxFuture<'static, Option> + Send + Sync; +struct Cached { + id: String, + federated: bool, + result: Arc)>>, +} +pub(super) struct Covers { + resolve: Box, + entries: Mutex>, +} + +impl Covers { + pub(super) fn new(library: Arc, federation: Arc) -> Arc { + Self::with(move |source, allow| { + let library = library.clone(); + let federation = federation.clone(); + Box::pin(async move { + let release = source.release; + let local = release + .as_ref() + .map(|r| (r.artist.clone(), r.title.clone())); + let encoded = tokio::task::spawn_blocking(move || { + if let Some(data) = source.path.and_then(|p| super::artwork(&p).ok()) { + return Some(data); + } + let (artist, title) = local?; + let path = library.release_cover_by_names(&artist, &title).ok()??; + super::artwork(std::path::Path::new(&path)).ok() + }) + .await + .ok() + .flatten(); + if encoded.is_some() || !allow { + return encoded; + } + let release = release.filter(|r| r.network_enabled)?; + let path = release.fetch(&federation).await?; + tokio::task::spawn_blocking(move || { + super::artwork(std::path::Path::new(&path)).ok() + }) + .await + .ok() + .flatten() + }) + }) + } + + pub(super) fn with( + resolve: impl Fn(Source, bool) -> BoxFuture<'static, Option> + Send + Sync + 'static, + ) -> Arc { + Arc::new(Self { + resolve: Box::new(resolve), + entries: Mutex::new(VecDeque::new()), + }) + } + + pub(super) async fn get(&self, id: &str, source: Source, federated: bool) -> Option { + let cell = { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + entries.retain(|e| { + !e.result.get().is_some_and(|(at, value)| { + value.is_none() && at.elapsed() >= Duration::from_secs(30) + }) + }); + if let Some(entry) = entries + .iter() + .find(|e| e.id == id && e.federated == federated) + { + entry.result.clone() + } else { + if entries.len() == 8 { + entries.pop_front(); + } + let cell = Arc::new(OnceCell::new()); + entries.push_back(Cached { + id: id.to_owned(), + federated, + result: cell.clone(), + }); + cell + } + }; + cell.get_or_init(|| async { + let reply = + tokio::time::timeout(Duration::from_secs(25), (self.resolve)(source, federated)) + .await + .ok() + .flatten(); + (Instant::now(), reply) + }) + .await + .1 + .clone() + } +} + +impl Release { + async fn fetch(&self, federation: &Federation) -> Option { + if let Some(path) = federation + .card_image(&self.owners, &self.artist, Some(&self.title)) + .await + { + return Some(path); + } + // Only global library mode uses wider artist discovery. Request art + // from owners of this release, rather than sending its title to all peers. + if !self.global { + return None; + } + let card = federation.artist_card(&self.artist).await.ok()?; + let title = music_dht::normalize_name(&self.title); + let release = card + .releases + .iter() + .find(|r| music_dht::normalize_name(&r.title) == title)?; + let owners: Vec<_> = release + .owners + .iter() + .filter(|o| !self.owners.contains(o) && Some(*o) != card.own_owner.as_ref()) + .take(6) + .cloned() + .collect(); + federation + .card_image(&owners, &self.artist, Some(&release.title)) + .await + } +} diff --git a/src/control_spectrum.rs b/src/control_spectrum.rs new file mode 100644 index 0000000..2e54fa3 --- /dev/null +++ b/src/control_spectrum.rs @@ -0,0 +1,75 @@ +//! Latest local audio levels. A connection owns a receiver only for the +//! lifetime of its subscription, so multiple decks share one sampled frame. +use std::time::{Duration, Instant}; + +use furumi_control_protocol::{SPECTRUM_BANDS, ServerMessage}; +use tokio::sync::watch; + +const FRAME_INTERVAL: Duration = Duration::from_millis(100); + +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Frame { + epoch: u64, + sequence: u64, + bands: Option<[u8; SPECTRUM_BANDS]>, +} + +pub(crate) struct Spectrum { + pub(super) frames: watch::Sender, + last_frame: Option, +} + +impl Default for Spectrum { + fn default() -> Self { + Self { + frames: watch::Sender::new(Frame::default()), + last_frame: None, + } + } +} + +impl Spectrum { + pub(crate) fn sample(&mut self, at: Instant, levels: &[f64]) { + if self.frames.receiver_count() == 0 + || self + .last_frame + .is_some_and(|last| at.saturating_duration_since(last) < FRAME_INTERVAL) + { + return; + } + let Ok(levels) = <&[f64; SPECTRUM_BANDS]>::try_from(levels) else { + return; + }; + self.last_frame = Some(at); + let bands = levels.map(|level| (level.clamp(0.0, 1.0) * 255.0).round() as u8); + self.frames.send_modify(|frame| { + frame.sequence = frame.sequence.wrapping_add(1); + frame.bands = Some(bands); + }); + } + + pub(crate) fn clear(&mut self) { + if self.last_frame.take().is_some() { + self.frames.send_modify(|frame| { + frame.epoch = frame.epoch.wrapping_add(1); + frame.sequence = frame.sequence.wrapping_add(1); + frame.bands = None; + }); + } + } +} + +pub(super) async fn next_frame( + subscription: &mut Option>, +) -> Option { + let Some(receiver) = subscription else { + return std::future::pending().await; + }; + receiver.changed().await.ok()?; + let frame = *receiver.borrow_and_update(); + Some(ServerMessage::Spectrum { + epoch: frame.epoch, + sequence: frame.sequence, + bands: frame.bands, + }) +} diff --git a/src/control_tests.rs b/src/control_tests.rs new file mode 100644 index 0000000..cdf2a57 --- /dev/null +++ b/src/control_tests.rs @@ -0,0 +1,518 @@ +use super::*; + +#[test] +fn browser_handshakes_are_rejected_and_discovery_replaces_only_its_file() { + use tokio_tungstenite::tungstenite::handshake::server::{Request, Response}; + let request = Request::builder() + .header("Origin", "https://example.invalid") + .body(()) + .unwrap(); + assert!(native_handshake(&request, Response::new(())).is_err()); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("endpoint.json"); + for port in [1234, 4567] { + write_discovery( + &path, + &Discovery { + api_version: API_VERSION, + port, + token: "private".into(), + }, + ) + .unwrap(); + let read: Discovery = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(read.port, port); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } +} + +type TestConnection = ( + tokio_tungstenite::WebSocketStream>, + mpsc::Receiver, + watch::Sender, + JoinHandle<()>, +); + +async fn connect() -> TestConnection { + connect_with(art::Covers::with(|_, _| Box::pin(async { None }))).await +} + +async fn connect_with(covers: Arc) -> TestConnection { + connect_with_spectrum(covers, Spectrum::default().frames).await +} + +async fn connect_with_spectrum( + covers: Arc, + frames: watch::Sender, +) -> TestConnection { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) + .await + .unwrap(); + let port = listener.local_addr().unwrap().port(); + let (state, receiver) = watch::channel(crate::app::control::published( + &crate::app::state::AppState::default(), + 1, + )); + let (commands, queue) = mpsc::channel(8); + let task = tokio::spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + let _ = session(socket, "secret", receiver, commands, covers, frames).await; + }); + let socket = tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{port}")) + .await + .unwrap() + .0; + (socket, queue, state, task) +} + +#[tokio::test] +async fn authentication_required_and_wrong_tokens_cannot_dispatch() { + for token in ["wrong", ""] { + let (mut socket, mut queue, _state, task) = connect().await; + socket + .send(Message::Text( + serde_json::to_string(&ClientMessage::Authenticate { + token: token.into(), + api_version: API_VERSION, + }) + .unwrap() + .into(), + )) + .await + .unwrap(); + task.await.unwrap(); + assert!(queue.recv().await.is_none()); + assert!(!matches!(socket.next().await, Some(Ok(Message::Text(_))))); + } +} + +#[tokio::test] +async fn authenticated_session_streams_idle_state_and_routes_commands() { + let (mut socket, mut queue, state, task) = connect().await; + socket + .send(Message::Text( + serde_json::to_string(&ClientMessage::Authenticate { + token: "secret".into(), + api_version: API_VERSION, + }) + .unwrap() + .into(), + )) + .await + .unwrap(); + let Message::Text(initial) = socket.next().await.unwrap().unwrap() else { + panic!() + }; + let ServerMessage::Snapshot { snapshot } = serde_json::from_str(&initial).unwrap() else { + panic!() + }; + assert!(!snapshot.playing); + assert_eq!(snapshot.devices.len(), 1); + let mut changed = state.borrow().clone(); + changed.snapshot.revision = 2; + state.send_replace(changed); + let Message::Text(next) = socket.next().await.unwrap().unwrap() else { + panic!() + }; + assert!( + matches!(serde_json::from_str::(&next).unwrap(), ServerMessage::Snapshot { snapshot } if snapshot.revision == 2) + ); + socket + .send(Message::Text( + serde_json::to_string(&ClientMessage::Command { + id: "press-1".into(), + command: Command::VolumeUp, + }) + .unwrap() + .into(), + )) + .await + .unwrap(); + let command = queue.recv().await.unwrap(); + assert_eq!(command.command, Command::VolumeUp); + command + .reply + .send(ServerMessage::Result { + id: command.id, + accepted: true, + error: None, + }) + .unwrap(); + assert!(matches!(socket.next().await, Some(Ok(Message::Text(_))))); + task.abort(); +} + +#[tokio::test] +async fn repeated_ids_are_deduplicated_across_clients_and_payload_changes_rejected() { + let (commands, queue) = mpsc::channel(8); + let (events, mut event_rx) = mpsc::unbounded_channel(); + let task = tokio::spawn(broker(queue, events)); + let (tx, rx) = oneshot::channel(); + commands + .send(Queued { + id: "one".into(), + command: Command::PlayPause, + reply: tx, + }) + .await + .unwrap(); + let crate::app::event::AppEvent::Control(event) = event_rx.recv().await.unwrap() else { + panic!() + }; + event.reply.send(Ok(())).unwrap(); + assert!(matches!( + rx.await.unwrap(), + ServerMessage::Result { accepted: true, .. } + )); + for command in [Command::PlayPause, Command::Next] { + let expected = command == Command::PlayPause; + let (tx, rx) = oneshot::channel(); + commands + .send(Queued { + id: "one".into(), + command, + reply: tx, + }) + .await + .unwrap(); + assert!( + matches!(rx.await.unwrap(), ServerMessage::Result { accepted, .. } if accepted == expected) + ); + assert!(event_rx.try_recv().is_err()); + } + task.abort(); +} + +#[tokio::test] +async fn artwork_references_never_accept_paths_from_clients() { + let (mut socket, _queue, _state, task) = connect().await; + for message in [ + ClientMessage::Authenticate { + token: "secret".into(), + api_version: API_VERSION, + }, + ClientMessage::Command { + id: "art".into(), + command: Command::Artwork { + artwork_id: "../../private-file".into(), + federation: true, + }, + }, + ] { + socket + .send(Message::Text( + serde_json::to_string(&message).unwrap().into(), + )) + .await + .unwrap(); + } + socket.next().await.unwrap().unwrap(); + let Message::Text(reply) = socket.next().await.unwrap().unwrap() else { + panic!() + }; + assert!(matches!( + serde_json::from_str::(&reply).unwrap(), + ServerMessage::Result { + accepted: false, + .. + } + )); + task.abort(); +} + +#[test] +fn artwork_is_bounded_and_scaled_without_audio_or_user_files() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cover.png"); + image::RgbImage::from_pixel(4, 4, image::Rgb([10, 20, 30])) + .save(&path) + .unwrap(); + let data = base64::engine::general_purpose::STANDARD + .decode(artwork(&path).unwrap()) + .unwrap(); + let decoded = image::load_from_memory(&data).unwrap(); + assert_eq!((decoded.width(), decoded.height()), (384, 384)); +} + +#[tokio::test] +async fn slow_federated_art_is_opt_in_and_playback_commands_still_work() { + use furumi_control_protocol::Track; + let (lookup_tx, mut lookups) = mpsc::unbounded_channel(); + let ready = Arc::new(tokio::sync::Notify::new()); + let ready_worker = ready.clone(); + let covers = art::Covers::with(move |_, federation| { + lookup_tx.send(federation).unwrap(); + let ready = ready_worker.clone(); + Box::pin(async move { + if !federation { + return None; + } + ready.notified().await; + Some("cG5n".into()) + }) + }); + let (mut socket, mut commands, state, task) = connect_with(covers).await; + state.send_modify(|p| { + p.snapshot.track = Some(Track { + key: "song".into(), + title: "Song".into(), + artist: "Artist".into(), + album: "Album".into(), + year: None, + artwork_id: Some("cover".into()), + }) + }); + let auth = ClientMessage::Authenticate { + token: "secret".into(), + api_version: API_VERSION, + }; + socket + .send(Message::text(serde_json::to_string(&auth).unwrap())) + .await + .unwrap(); + socket.next().await.unwrap().unwrap(); + assert!(lookups.try_recv().is_err()); + let command = |id: &str, command| { + Message::text( + serde_json::to_string(&ClientMessage::Command { + id: id.into(), + command, + }) + .unwrap(), + ) + }; + for allow in [false, true] { + socket + .send(command( + "art", + Command::Artwork { + artwork_id: "cover".into(), + federation: allow, + }, + )) + .await + .unwrap(); + assert_eq!(lookups.recv().await, Some(allow)); + if !allow { + let reply = socket.next().await.unwrap().unwrap().into_data(); + assert!(matches!( + serde_json::from_slice(&reply).unwrap(), + ServerMessage::Artwork { + png_base64: None, + .. + } + )); + } + } + socket + .send(command("pause", Command::PlayPause)) + .await + .unwrap(); + let pending = tokio::time::timeout(Duration::from_secs(2), commands.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(pending.command, Command::PlayPause); + pending + .reply + .send(ServerMessage::Result { + id: pending.id, + accepted: true, + error: None, + }) + .unwrap(); + let reply = socket.next().await.unwrap().unwrap().into_data(); + assert!(matches!( + serde_json::from_slice(&reply).unwrap(), + ServerMessage::Result { accepted: true, .. } + )); + ready.notify_one(); + let reply = socket.next().await.unwrap().unwrap().into_data(); + assert!(matches!( + serde_json::from_slice(&reply).unwrap(), + ServerMessage::Artwork { + png_base64: Some(_), + .. + } + )); + task.abort(); +} + +#[tokio::test] +async fn simultaneous_cover_requests_share_the_fetch() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let covers = art::Covers::with(move |_, _| { + count.fetch_add(1, Ordering::Relaxed); + Box::pin(async { + tokio::task::yield_now().await; + Some("cover".into()) + }) + }); + let fetch = || covers.get("album", art::Source::default(), true); + let (a, b) = tokio::join!(fetch(), fetch()); + assert_eq!(a.as_deref(), Some("cover")); + assert_eq!(a, b); + assert_eq!(calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn spectrum_subscriptions_are_advertised_idempotent_and_connection_scoped() { + let mut spectrum = Spectrum::default(); + let covers = art::Covers::with(|_, _| Box::pin(async { None })); + let (mut socket, _commands, _state, task) = + connect_with_spectrum(covers, spectrum.frames.clone()).await; + let auth = ClientMessage::Authenticate { + token: "secret".into(), + api_version: API_VERSION, + }; + socket + .send(Message::text(serde_json::to_string(&auth).unwrap())) + .await + .unwrap(); + let initial = socket.next().await.unwrap().unwrap().into_data(); + let mut old_message: serde_json::Value = serde_json::from_slice(&initial).unwrap(); + assert_eq!( + old_message["snapshot"] + .as_object_mut() + .unwrap() + .remove("spectrum_supported"), + Some(true.into()) + ); + assert!( + matches!(serde_json::from_value(old_message).unwrap(), ServerMessage::Snapshot { snapshot } if !snapshot.spectrum_supported) + ); + let at = std::time::Instant::now(); + spectrum.sample(at, &[1.0; 31]); + assert_eq!(spectrum.frames.receiver_count(), 0); + for (index, enabled) in [true, true, false, true].into_iter().enumerate() { + let subscribe = ClientMessage::SubscribeSpectrum { enabled }; + socket + .send(Message::text(serde_json::to_string(&subscribe).unwrap())) + .await + .unwrap(); + // A pong is a barrier on the socket following this subscription change. + socket + .send(Message::Ping(vec![index as u8].into())) + .await + .unwrap(); + assert!(matches!( + socket.next().await.unwrap().unwrap(), + Message::Pong(_) + )); + assert_eq!(spectrum.frames.receiver_count(), usize::from(enabled)); + spectrum.sample(at + Duration::from_secs(index as u64), &[0.5; 31]); + if enabled { + let message = tokio::time::timeout(Duration::from_secs(2), socket.next()) + .await + .unwrap() + .unwrap() + .unwrap() + .into_data(); + assert!(matches!(serde_json::from_slice(&message).unwrap(), + ServerMessage::Spectrum { bands: Some(bands), .. } if bands == [128; 31])); + } + } + socket.close(None).await.unwrap(); + task.await.unwrap(); + assert_eq!(spectrum.frames.receiver_count(), 0); +} + +#[tokio::test] +async fn waterfall_uses_fresh_local_audio_and_clears_history_across_discontinuities() { + use crate::app::{ + control::publish_spectrum, + state::{AppState, DevicePlaybackRole}, + }; + use std::time::Instant; + let mut spectrum = Spectrum::default(); + let mut subscription = Some(spectrum.frames.subscribe()); + let mut state = AppState::default(); + state.player.current = Some(crate::app::podcast_fixtures::episode_track(1)); + state.player.playing = true; + state.player.audio_analysis.spectrum = (0..31).map(|i| f64::from(i) / 30.0).collect(); + let at = Instant::now(); + publish_spectrum(&mut spectrum, &state, Some(at), false, true); + let Some(ServerMessage::Spectrum { + epoch, + sequence: 1, + bands: Some(first), + }) = spectrum::next_frame(&mut subscription).await + else { + panic!() + }; + assert_eq!((first[0], first[15], first[30]), (0, 128, 255)); + publish_spectrum( + &mut spectrum, + &state, + Some(at + Duration::from_millis(50)), + false, + true, + ); + assert!(!subscription.as_ref().unwrap().has_changed().unwrap()); + state.player.paused = true; + publish_spectrum( + &mut spectrum, + &state, + Some(at + Duration::from_secs(1)), + false, + false, + ); + assert!(!subscription.as_ref().unwrap().has_changed().unwrap()); + state.player.paused = false; + publish_spectrum( + &mut spectrum, + &state, + Some(at + Duration::from_secs(2)), + false, + false, + ); + assert!(!subscription.as_ref().unwrap().has_changed().unwrap()); + state.device_playback.role = DevicePlaybackRole::Control; + publish_spectrum(&mut spectrum, &state, None, false, true); + assert!( + matches!(spectrum::next_frame(&mut subscription).await, Some(ServerMessage::Spectrum { epoch: next, bands: None, .. }) if next != epoch) + ); + state.device_playback.role = DevicePlaybackRole::Jam; + publish_spectrum( + &mut spectrum, + &state, + Some(at + Duration::from_secs(3)), + false, + true, + ); + assert!(!subscription.as_ref().unwrap().has_changed().unwrap()); + state.device_playback.jam_host = true; + publish_spectrum( + &mut spectrum, + &state, + Some(at + Duration::from_secs(4)), + false, + true, + ); + // A slow reader that misses the clear still sees the new epoch on the next sample. + spectrum.clear(); + publish_spectrum( + &mut spectrum, + &state, + Some(at + Duration::from_secs(5)), + false, + true, + ); + assert!( + matches!(spectrum::next_frame(&mut subscription).await, Some(ServerMessage::Spectrum { epoch: next, bands: Some(_), .. }) if next == epoch + 2) + ); + publish_spectrum(&mut spectrum, &state, None, true, true); + assert!(matches!( + spectrum::next_frame(&mut subscription).await, + Some(ServerMessage::Spectrum { bands: None, .. }) + )); +} diff --git a/src/federation/mod.rs b/src/federation/mod.rs index 6b719d9..b3c5857 100644 --- a/src/federation/mod.rs +++ b/src/federation/mod.rs @@ -1731,7 +1731,6 @@ impl Federation { } } let service = self.service().await.ok()?; - tokio::fs::create_dir_all(&dir).await.ok()?; for owner in owners { let Ok(owner) = EndpointId::from_str(owner) else { continue; @@ -1744,7 +1743,19 @@ impl Federation { match fetched { Ok(Ok(Some((bytes, extension)))) => { let path = dir.join(format!("{stem}.{extension}")); - if tokio::fs::write(&path, &bytes).await.is_ok() { + // A cancelled on-demand lookup must never leave a partial + // file that the next lookup would accept as cached art. + let stored = tokio::task::spawn_blocking(move || -> std::io::Result<_> { + use std::io::Write as _; + let parent = path.parent().expect("cover has a directory"); + std::fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + file.write_all(&bytes)?; + file.persist(&path).map_err(|e| e.error)?; + Ok(path) + }) + .await; + if let Ok(Ok(path)) = stored { return Some(path.to_string_lossy().into_owned()); } } diff --git a/src/main.rs b/src/main.rs index 5afbcba..9b4ac9c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod app; mod art; mod config; +mod control; mod devices; mod federation; mod jam; @@ -30,6 +31,8 @@ Furumi — federated terminal music player Usage: furumi [OPTION] + furumi ctl [ARG] + furumi ctl artwork [--federation] [--output FILE.png] Options: -h, --help Show this help @@ -44,6 +47,17 @@ tmux: fn main() -> Result<()> { let args: Vec<_> = std::env::args_os().collect(); + if args.get(1).is_some_and(|arg| arg == "ctl") { + let args: Vec<_> = args + .iter() + .skip(2) + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + return tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(control::cli(&args)); + } if args.iter().any(|arg| arg == "--help" || arg == "-h") { print!("{HELP}"); return Ok(()); diff --git a/src/player/mod.rs b/src/player/mod.rs index 259b0a8..90622e9 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -93,10 +93,16 @@ enum Command { pub struct Shared { position_ms: AtomicU64, paused: AtomicBool, + output_playing: AtomicBool, analysis: Arc, } impl Shared { + /// Whether the audio worker currently has an unpaused source in its sink. + pub fn output_playing(&self) -> bool { + self.output_playing.load(Ordering::Relaxed) + } + pub fn position(&self) -> Duration { Duration::from_millis(self.position_ms.load(Ordering::Relaxed)) } @@ -349,9 +355,6 @@ fn run( shared .position_ms .store(position.as_millis() as u64, Ordering::Relaxed); - shared - .paused - .store(out.player.is_paused(), Ordering::Relaxed); let len = out.player.len(); if playing.track_loaded && len < last_len { // The next (gapless) source starts at zero. @@ -372,6 +375,16 @@ fn run( } Err(RecvTimeoutError::Disconnected) => return, } + // Publish the sink's state after applying the operation, including a + // stop or a gapless queue ending. The device heartbeat reads this. + let paused = output.as_ref().is_some_and(|out| out.player.is_paused()); + shared.paused.store(paused, Ordering::Relaxed); + shared.output_playing.store( + playing.track_loaded + && !paused + && output.as_ref().is_some_and(|out| !out.player.empty()), + Ordering::Relaxed, + ); } } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 2a4fe2c..1967210 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -1037,9 +1037,15 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) { let (center, _) = player_right_line(state, area.width.saturating_sub(mode_area.width)); let mut spans = Vec::new(); + let command_pending = state.device_playback.control.busy(); match &player.current { Some(track) if player.playing => { - if player.paused { + if command_pending { + spans.push(Span::styled( + format!("{} ", state.spinner()), + theme::accent_for(state), + )); + } else if player.paused { spans.push(Span::styled("⏸ ", theme::dim())); } else { spans.push(Span::styled("▶ ", theme::accent_for(state))); @@ -1053,6 +1059,12 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) { theme::dim(), )); } + _ if command_pending => { + spans.push(Span::styled( + format!("{} stopped", state.spinner()), + theme::accent_for(state), + )); + } _ => { spans.push(Span::styled("■ stopped", theme::dim())); } @@ -1082,6 +1094,14 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) { } let message = match &state.status_message { + _ if command_pending => Line::styled( + format!( + "{} controlling {}", + state.spinner(), + state.device_playback.active_label() + ), + theme::accent_for(state), + ), Some(message) if is_waiting_message(message) => Line::from(vec![ Span::styled(format!("{} ", state.spinner()), theme::accent_for(state)), Span::styled(message.clone(), theme::accent_for(state)),