feat: ship the Furumi OpenDeck plugin for Windows, macOS and Linux
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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]]
|
||||
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
@@ -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<PathBuf> {
|
||||
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<String>,
|
||||
pub active_device_name: Option<String>,
|
||||
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<RemoteCommand>,
|
||||
pub track: Option<Track>,
|
||||
pub devices: Vec<Device>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<i32>,
|
||||
/// Opaque reference; clients cannot ask the server to read arbitrary paths.
|
||||
pub artwork_id: Option<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<Snapshot>,
|
||||
},
|
||||
/// 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<String>,
|
||||
},
|
||||
Artwork {
|
||||
id: String,
|
||||
artwork_id: String,
|
||||
png_base64: Option<String>,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/.research-opendeck/
|
||||
/target/
|
||||
/dist/
|
||||
/dist-*/
|
||||
/preview/
|
||||
@@ -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"
|
||||
@@ -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-<version>.zip` | x86_64 |
|
||||
| `furumi-opendeck-macos-<version>.zip` | Intel and Apple Silicon |
|
||||
| `furumi-opendeck-linux-<version>.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)
|
||||
@@ -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$
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96"><rect width="96" height="96" rx="12" fill="#2b465a"/><g color="#d0dce3"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="#d0dce3"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg></g></svg>
|
||||
|
After Width: | Height: | Size: 509 B |
@@ -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.
|
||||
@@ -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(/<svg\b([^>]*)>/, (_, attributes) => {
|
||||
const retained = attributes.replace(
|
||||
/\s(?:width|height|x|y|color)="[^"]*"/g,
|
||||
'',
|
||||
);
|
||||
const x = centreX - size / 2;
|
||||
const y = centreY - size / 2;
|
||||
return `<svg${retained} width="${size}" height="${size}" x="${x}" y="${y}" color="white">`;
|
||||
});
|
||||
}
|
||||
|
||||
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'
|
||||
? '<rect x="5" y="5" width="86" height="86" rx="9" fill="none" stroke="white" stroke-width="2"/>'
|
||||
: '<rect x="6" y="6" width="84" height="84" rx="8" fill="none" stroke="white" stroke-width="4"/>',
|
||||
}));
|
||||
|
||||
for (let step = 0; step < 8; step++) {
|
||||
tiles.push({
|
||||
id: `Spinner${step}`,
|
||||
content: `<g transform="rotate(${step * 45} 48 32)">${glyph('spinner-gap', 48, 48, 32)}</g>`,
|
||||
});
|
||||
}
|
||||
|
||||
let svg = [
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="768" height="384" viewBox="0 0 768 384">',
|
||||
'<title>Furumi / Phosphor Fill alpha atlas</title>',
|
||||
'<desc>96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill SVG geometry. Custom enabled frame.</desc>',
|
||||
].join('');
|
||||
const metadata = [];
|
||||
|
||||
tiles.forEach((tile, index) => {
|
||||
const x = (index % columns) * tileSize;
|
||||
const y = Math.floor(index / columns) * tileSize;
|
||||
svg += `<svg id="${tile.id}" x="${x}" y="${y}" width="96" height="96" viewBox="0 0 96 96">${tile.content}</svg>`;
|
||||
metadata.push({ name: tile.id, index, x, y, width: tileSize, height: tileSize });
|
||||
});
|
||||
svg += '</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 = [
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">',
|
||||
'<rect width="96" height="96" rx="12" fill="#2b465a"/>',
|
||||
`<g color="#d0dce3">${launcherGlyph}</g></svg>\n`,
|
||||
].join('');
|
||||
fs.writeFileSync(path.join(__dirname, '../icon.svg'), launcher);
|
||||
|
||||
console.log(`Generated ${tiles.length} named masks, 768×384 transparent atlas and host icon.`);
|
||||
@@ -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"
|
||||
}
|
||||
|
After Width: | Height: | Size: 19 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="768" height="384" viewBox="0 0 768 384"><title>Furumi / Phosphor Fill alpha atlas</title><desc>96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill SVG geometry. Custom enabled frame.</desc><svg id="Previous" x="0" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M208,47.88V208.12a16,16,0,0,1-24.43,13.43L64,146.77V216a8,8,0,0,1-16,0V40a8,8,0,0,1,16,0v69.23L183.57,34.45A15.95,15.95,0,0,1,208,47.88Z"/></svg></svg><svg id="Play" x="96" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg></svg><svg id="Pause" x="192" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></svg></svg><svg id="Next" x="288" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M208,40V216a8,8,0,0,1-16,0V146.77L72.43,221.55A15.95,15.95,0,0,1,48,208.12V47.88A15.95,15.95,0,0,1,72.43,34.45L192,109.23V40a8,8,0,0,1,16,0Z"/></svg></svg><svg id="Repeat" x="384" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Z"/></svg></svg><svg id="RepeatOne" x="480" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Zm-88,40a8,8,0,0,0,8-8V104a8,8,0,0,0-11.58-7.16l-16,8a8,8,0,1,0,7.16,14.31l4.42-2.21V152A8,8,0,0,0,136,160Z"/></svg></svg><svg id="Shuffle" x="576" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M237.66,178.34a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,200,208V192a72.15,72.15,0,0,1-57.65-30.14l-41.72-58.4A56.1,56.1,0,0,0,55.06,80H32a8,8,0,0,1,0-16H55.06a72.12,72.12,0,0,1,58.59,30.15l41.72,58.4A56.08,56.08,0,0,0,200,176V160a8,8,0,0,1,13.66-5.66ZM143,107a8,8,0,0,0,11.16-1.86l1.2-1.67A56.08,56.08,0,0,1,200,80V96a8,8,0,0,0,13.66,5.66l24-24a8,8,0,0,0,0-11.32l-24-24A8,8,0,0,0,200,48V64a72.15,72.15,0,0,0-57.65,30.14l-1.2,1.67A8,8,0,0,0,143,107Zm-30,42a8,8,0,0,0-11.16,1.86l-1.2,1.67A56.1,56.1,0,0,1,55.06,176H32a8,8,0,0,0,0,16H55.06a72.12,72.12,0,0,0,58.59-30.15l1.2-1.67A8,8,0,0,0,113,149Z"/></svg></svg><svg id="Back" x="672" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="36" height="36" x="30" y="30" color="white"><path d="M168,48V208a8,8,0,0,1-13.66,5.66l-80-80a8,8,0,0,1,0-11.32l80-80A8,8,0,0,1,168,48Z"/></svg></svg><svg id="SeekBack" x="0" y="96" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="48" height="48" x="24" y="10" color="white"><path d="M232,71.84V184.16a15.92,15.92,0,0,1-24.48,13.34L128,146.86v37.3a15.92,15.92,0,0,1-24.48,13.34L15.33,141.34a15.8,15.8,0,0,1,0-26.68L103.52,58.5A15.91,15.91,0,0,1,128,71.84v37.3L207.52,58.5A15.91,15.91,0,0,1,232,71.84Z"/></svg></svg><svg id="SeekForward" x="96" y="96" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="48" height="48" x="24" y="10" color="white"><path d="M256,128a15.76,15.76,0,0,1-7.33,13.34L160.48,197.5A15.91,15.91,0,0,1,136,184.16v-37.3L56.48,197.5A15.91,15.91,0,0,1,32,184.16V71.Line truncated
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M168,48V208a8,8,0,0,1-13.66,5.66l-80-80a8,8,0,0,1,0-11.32l80-80A8,8,0,0,1,168,48Z"/></svg>
|
||||
|
After Width: | Height: | Size: 181 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M181.66,133.66l-80,80A8,8,0,0,1,88,208V48a8,8,0,0,1,13.66-5.66l80,80A8,8,0,0,1,181.66,133.66Z"/></svg>
|
||||
|
After Width: | Height: | Size: 193 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,40H40A16,16,0,0,0,24,56V200a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V56A16,16,0,0,0,216,40ZM205.66,85.66l-96,96a8,8,0,0,1-11.32,0l-40-40a8,8,0,0,1,11.32-11.32L104,164.69l90.34-90.35a8,8,0,0,1,11.32,11.32Z"/></svg>
|
||||
|
After Width: | Height: | Size: 308 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,72H208V64a24,24,0,0,0-24-24H40A24,24,0,0,0,16,64v96a24,24,0,0,0,24,24H152v8a24,24,0,0,0,24,24h48a24,24,0,0,0,24-24V96A24,24,0,0,0,224,72Zm8,120a8,8,0,0,1-8,8H176a8,8,0,0,1-8-8V96a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8Zm-96,16a8,8,0,0,1-8,8H88a8,8,0,0,1,0-16h40A8,8,0,0,1,136,208Zm80-96a8,8,0,0,1-8,8H192a8,8,0,0,1,0-16h16A8,8,0,0,1,216,112Z"/></svg>
|
||||
|
After Width: | Height: | Size: 437 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M256,128a15.76,15.76,0,0,1-7.33,13.34L160.48,197.5A15.91,15.91,0,0,1,136,184.16v-37.3L56.48,197.5A15.91,15.91,0,0,1,32,184.16V71.84A15.91,15.91,0,0,1,56.48,58.5L136,109.14V71.84A15.91,15.91,0,0,1,160.48,58.5l88.19,56.16A15.76,15.76,0,0,1,256,128Z"/></svg>
|
||||
|
After Width: | Height: | Size: 346 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M210.3,56.34l-80-24A8,8,0,0,0,120,40V148.26A48,48,0,1,0,136,184V50.75l69.7,20.91a8,8,0,1,0,4.6-15.32Z"/></svg>
|
||||
|
After Width: | Height: | Size: 201 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></svg>
|
||||
|
After Width: | Height: | Size: 287 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg>
|
||||
|
After Width: | Height: | Size: 290 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M200,128a71.69,71.69,0,0,1-15.78,44.91L83.09,71.78A71.95,71.95,0,0,1,200,128ZM56,128a71.95,71.95,0,0,0,116.91,56.22L71.78,83.09A71.69,71.69,0,0,0,56,128Zm180,0A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-20,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z"/></svg>
|
||||
|
After Width: | Height: | Size: 358 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,64H86.51L194.3,31.67a8,8,0,0,0-4.6-15.33l-160,48h0A8,8,0,0,0,24,72V192a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V80A16,16,0,0,0,216,64ZM104,176H64a8,8,0,0,1,0-16h40a8,8,0,0,1,0,16Zm0-32H64a8,8,0,0,1,0-16h40a8,8,0,0,1,0,16Zm0-32H64a8,8,0,0,1,0-16h40a8,8,0,0,1,0,16Zm64,56a32,32,0,1,1,32-32A32,32,0,0,1,168,168Z"/></svg>
|
||||
|
After Width: | Height: | Size: 412 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Zm-88,40a8,8,0,0,0,8-8V104a8,8,0,0,0-11.58-7.16l-16,8a8,8,0,1,0,7.16,14.31l4.42-2.21V152A8,8,0,0,0,136,160Z"/></svg>
|
||||
|
After Width: | Height: | Size: 528 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Z"/></svg>
|
||||
|
After Width: | Height: | Size: 422 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M232,71.84V184.16a15.92,15.92,0,0,1-24.48,13.34L128,146.86v37.3a15.92,15.92,0,0,1-24.48,13.34L15.33,141.34a15.8,15.8,0,0,1,0-26.68L103.52,58.5A15.91,15.91,0,0,1,128,71.84v37.3L207.52,58.5A15.91,15.91,0,0,1,232,71.84Z"/></svg>
|
||||
|
After Width: | Height: | Size: 316 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M237.66,178.34a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,200,208V192a72.15,72.15,0,0,1-57.65-30.14l-41.72-58.4A56.1,56.1,0,0,0,55.06,80H32a8,8,0,0,1,0-16H55.06a72.12,72.12,0,0,1,58.59,30.15l41.72,58.4A56.08,56.08,0,0,0,200,176V160a8,8,0,0,1,13.66-5.66ZM143,107a8,8,0,0,0,11.16-1.86l1.2-1.67A56.08,56.08,0,0,1,200,80V96a8,8,0,0,0,13.66,5.66l24-24a8,8,0,0,0,0-11.32l-24-24A8,8,0,0,0,200,48V64a72.15,72.15,0,0,0-57.65,30.14l-1.2,1.67A8,8,0,0,0,143,107Zm-30,42a8,8,0,0,0-11.16,1.86l-1.2,1.67A56.1,56.1,0,0,1,55.06,176H32a8,8,0,0,0,0,16H55.06a72.12,72.12,0,0,0,58.59-30.15l1.2-1.67A8,8,0,0,0,113,149Z"/></svg>
|
||||
|
After Width: | Height: | Size: 688 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M208,47.88V208.12a16,16,0,0,1-24.43,13.43L64,146.77V216a8,8,0,0,1-16,0V40a8,8,0,0,1,16,0v69.23L183.57,34.45A15.95,15.95,0,0,1,208,47.88Z"/></svg>
|
||||
|
After Width: | Height: | Size: 236 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M208,40V216a8,8,0,0,1-16,0V146.77L72.43,221.55A15.95,15.95,0,0,1,48,208.12V47.88A15.95,15.95,0,0,1,72.43,34.45L192,109.23V40a8,8,0,0,1,16,0Z"/></svg>
|
||||
|
After Width: | Height: | Size: 240 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z"/></svg>
|
||||
|
After Width: | Height: | Size: 571 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24ZM72,128a8,8,0,0,1-16,0,72.08,72.08,0,0,1,72-72,8,8,0,0,1,0,16A56.06,56.06,0,0,0,72,128Zm32,0a24,24,0,1,1,24,24A24,24,0,0,1,104,128Zm24,72a8,8,0,0,1,0-16,56.06,56.06,0,0,0,56-56,8,8,0,0,1,16,0A72.08,72.08,0,0,1,128,200Z"/></svg>
|
||||
|
After Width: | Height: | Size: 375 B |
@@ -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 }]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Furumi settings</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; font: 13px system-ui,sans-serif; background:#24282e; color:#d0dce3; }
|
||||
body { margin:16px; max-width:420px; }
|
||||
h1 { font-size:16px; margin:0 0 18px; }
|
||||
label { display:block; margin:0 0 16px; }
|
||||
select { display:block; box-sizing:border-box; width:100%; margin-top:7px; padding:7px 9px; border:1px solid #536472; border-radius:5px; background:#202a33; color:inherit; }
|
||||
.check { display:flex; align-items:center; gap:9px; }
|
||||
input { accent-color:#81a8be; width:16px; height:16px; margin:0; }
|
||||
small { display:block; line-height:1.5; color:#99acba; }
|
||||
#status { margin-top:14px; min-height:20px; }
|
||||
:disabled { opacity:.55; }
|
||||
</style>
|
||||
<script src="property-inspector.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Furumi</h1>
|
||||
<label>Infobar background
|
||||
<select id="infobar-background" disabled>
|
||||
<option value="none">None</option>
|
||||
<option value="spectrogram">Spectrogram</option>
|
||||
<option value="bars">Bars</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="check"><input id="album-art-2x2" type="checkbox" disabled>2×2 album art</label>
|
||||
<label class="check"><input id="invert-colors" type="checkbox" disabled>Invert colors</label>
|
||||
<small>Applies to all Furumi keys and Infobars. Spectrogram and Bars use only audio playing on this computer.</small>
|
||||
<small id="status" role="status">Connecting to OpenDeck…</small>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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<T> {
|
||||
pub request_id: String,
|
||||
pub artwork_id: String,
|
||||
pub image: T,
|
||||
}
|
||||
|
||||
impl CoverReply<String> {
|
||||
/// Decode and resize on the image worker while the keys continue to accept input.
|
||||
pub fn prepare(self) -> CoverReply<Option<PreparedArt>> {
|
||||
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<RgbImage> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Pending {
|
||||
request_id: String,
|
||||
artwork_id: String,
|
||||
generation: u64,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Artwork {
|
||||
identity: Option<Identity>,
|
||||
generation: u64,
|
||||
pending: Option<Pending>,
|
||||
terminal: bool,
|
||||
image: Option<PreparedArt>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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<PreparedArt>) {
|
||||
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<Instant> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<ServerMessage>),
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
mut commands: mpsc::Receiver<ClientMessage>,
|
||||
updates: mpsc::Sender<Update>,
|
||||
endpoint_path: Option<PathBuf>,
|
||||
spectrum: watch::Sender<Option<crate::spectrum::Frame>>,
|
||||
) {
|
||||
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<ClientMessage>,
|
||||
updates: &mpsc::Sender<Update>,
|
||||
endpoint_path: Option<PathBuf>,
|
||||
spectrum: &watch::Sender<Option<crate::spectrum::Frame>>,
|
||||
) -> 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<Update>,
|
||||
spectrum: &watch::Sender<Option<crate::spectrum::Frame>>,
|
||||
) -> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<usize>,
|
||||
}
|
||||
|
||||
#[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<Instance> {
|
||||
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<String> {
|
||||
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<Value> {
|
||||
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<Value> = (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<String, Instance>;
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
@@ -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<RgbaImage> = 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<Vec<GrayImage>> = 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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
baseline: u64,
|
||||
observed: Option<u64>,
|
||||
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<String>,
|
||||
last_id: Option<u64>,
|
||||
latch: Option<RemoteLatch>,
|
||||
abandoned: Option<u64>,
|
||||
}
|
||||
|
||||
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<Instant> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<Device>,
|
||||
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<String, Binding>,
|
||||
pub pending: Option<PendingTransfer>,
|
||||
pub radio: Option<PendingRadio>,
|
||||
pub notice: Option<(String, Instant)>,
|
||||
pub remote: RemoteGate,
|
||||
pub artwork_loading: Option<Instant>,
|
||||
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<Device> {
|
||||
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<Command> {
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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::<usize>();
|
||||
}
|
||||
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::<usize>();
|
||||
}
|
||||
}
|
||||
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::<Value>(&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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, Value>,
|
||||
ready: bool,
|
||||
queued: Map<String, Value>,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn raw_value(&self) -> Option<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<u8>; 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<u64>,
|
||||
sequence: Option<u64>,
|
||||
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<u8>) -> 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);
|
||||
}
|
||||
}
|
||||
@@ -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.');
|
||||
@@ -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<std::time::Instant>,
|
||||
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<Intent, String> {
|
||||
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);
|
||||
}
|
||||
@@ -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<Vec<super::state::SimilaritySearchHit>, String>,
|
||||
},
|
||||
Lyrics(super::lyrics::Event),
|
||||
UpdateChecked(Result<Option<crate::updater::Update>, 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<ArtistsPage, String>),
|
||||
|
||||
@@ -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<crate::jam::JamManager>,
|
||||
pub federation: Arc<crate::federation::Federation>,
|
||||
pub similarity: Arc<crate::similarity::Manager>,
|
||||
pub radio_task: Option<tokio::task::JoinHandle<()>>,
|
||||
/// When the last Federation-tab status snapshot was requested.
|
||||
pub fed_status_at: Option<std::time::Instant>,
|
||||
/// 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<u64>,
|
||||
) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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<String>,
|
||||
queue: Vec<String>,
|
||||
expected: Option<String>,
|
||||
expected_queue: Vec<String>,
|
||||
remote_baseline: Option<i64>,
|
||||
deadline: Option<Instant>,
|
||||
}
|
||||
|
||||
fn identity(track: &TrackItem) -> String {
|
||||
track
|
||||
.content_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| track.key().to_string())
|
||||
}
|
||||
|
||||
fn queue_identity(state: &AppState) -> Vec<String> {
|
||||
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<TrackItem, String> {
|
||||
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<Vec<SimilaritySearchHit>, 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<Vec<SimilaritySearchHit>, 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::<Vec<_>>() == 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();
|
||||
}
|
||||
}
|
||||
@@ -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<Claim>,
|
||||
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<Pending>,
|
||||
// The resolved UI projection preserves local cover paths and podcast
|
||||
// identities when discarding a speculative edit. No DB access on input.
|
||||
confirmed: Option<PlayerBar>,
|
||||
source_mode: Option<LibrarySourceMode>,
|
||||
}
|
||||
|
||||
impl RemotePlayback {
|
||||
pub(crate) fn busy(&self) -> bool {
|
||||
self.pending.is_some()
|
||||
}
|
||||
|
||||
fn finish(&mut self, error: Option<String>) {
|
||||
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<u64, &'static str> {
|
||||
// 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()));
|
||||
}
|
||||
@@ -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<TrackItem>,
|
||||
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.
|
||||
|
||||
@@ -167,6 +167,29 @@ pub enum Effect {
|
||||
}
|
||||
|
||||
pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
|
||||
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
|
||||
|
||||
@@ -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::<Vec<_>>(),
|
||||
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}"),
|
||||
|
||||
@@ -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<std::result::Result<(), String>>,
|
||||
}
|
||||
|
||||
#[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<ServerMessage>,
|
||||
}
|
||||
|
||||
pub struct Service {
|
||||
state: watch::Sender<Published>,
|
||||
pub(crate) spectrum: Spectrum,
|
||||
task: JoinHandle<()>,
|
||||
discovery: PathBuf,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl Service {
|
||||
pub async fn start(
|
||||
initial: Published,
|
||||
events: mpsc::UnboundedSender<crate::app::event::AppEvent>,
|
||||
library: Arc<crate::library::Library>,
|
||||
federation: Arc<crate::federation::Federation>,
|
||||
) -> Result<Self> {
|
||||
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::<Discovery>(&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<Queued>,
|
||||
events: mpsc::UnboundedSender<crate::app::event::AppEvent>,
|
||||
) {
|
||||
// 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<Published>,
|
||||
commands: mpsc::Sender<Queued>,
|
||||
covers: Arc<art::Covers>,
|
||||
frames: watch::Sender<spectrum::Frame>,
|
||||
) -> 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::<ClientMessage>(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<TcpStream>,
|
||||
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<String> {
|
||||
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::<u128>());
|
||||
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(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<PathBuf>,
|
||||
pub release: Option<Release>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Release {
|
||||
pub artist: String,
|
||||
pub title: String,
|
||||
pub owners: Vec<String>,
|
||||
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<String> {
|
||||
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<String>> + Send + Sync;
|
||||
struct Cached {
|
||||
id: String,
|
||||
federated: bool,
|
||||
result: Arc<OnceCell<(Instant, Option<String>)>>,
|
||||
}
|
||||
pub(super) struct Covers {
|
||||
resolve: Box<Resolver>,
|
||||
entries: Mutex<VecDeque<Cached>>,
|
||||
}
|
||||
|
||||
impl Covers {
|
||||
pub(super) fn new(library: Arc<Library>, federation: Arc<Federation>) -> Arc<Self> {
|
||||
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<String>> + Send + Sync + 'static,
|
||||
) -> Arc<Self> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<Frame>,
|
||||
last_frame: Option<Instant>,
|
||||
}
|
||||
|
||||
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<watch::Receiver<Frame>>,
|
||||
) -> Option<ServerMessage> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -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<tokio_tungstenite::MaybeTlsStream<TcpStream>>,
|
||||
mpsc::Receiver<Queued>,
|
||||
watch::Sender<Published>,
|
||||
JoinHandle<()>,
|
||||
);
|
||||
|
||||
async fn connect() -> TestConnection {
|
||||
connect_with(art::Covers::with(|_, _| Box::pin(async { None }))).await
|
||||
}
|
||||
|
||||
async fn connect_with(covers: Arc<art::Covers>) -> TestConnection {
|
||||
connect_with_spectrum(covers, Spectrum::default().frames).await
|
||||
}
|
||||
|
||||
async fn connect_with_spectrum(
|
||||
covers: Arc<art::Covers>,
|
||||
frames: watch::Sender<spectrum::Frame>,
|
||||
) -> 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::<ServerMessage>(&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::<ServerMessage>(&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, .. })
|
||||
));
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 <status|devices|watch|play-pause|next|previous|seek|volume-up|volume-down|transfer|shuffle|repeat|radio> [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(());
|
||||
|
||||
@@ -93,10 +93,16 @@ enum Command {
|
||||
pub struct Shared {
|
||||
position_ms: AtomicU64,
|
||||
paused: AtomicBool,
|
||||
output_playing: AtomicBool,
|
||||
analysis: Arc<analyzer::AnalyzerShared>,
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)),
|
||||
|
||||