Compare commits

...
15 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov 0ad3844d37 Bump 2026-11-16 00:17:50 +00:00
Aleksandr Bogomiakov 2253ec7d91 Added simple status visual 2026-11-15 23:48:33 +00:00
Aleksandr Bogomiakov 8dd3ededf6 Fixed queue bug 2026-10-10 00:19:10 +01:00
Aleksandr Bogomiakov 81fdcf13ae Fixed queue bug 2026-10-10 00:18:07 +01:00
Aleksandr Bogomiakov a6d502e319 Fix duplicate queue playback position 2026-10-09 23:54:07 +01:00
Aleksandr Bogomiakov 3298204f2e Bump lock 2026-10-09 15:42:17 +01:00
Aleksandr Bogomiakov 9155bb9e00 Fixed release fed search regression 2026-10-09 15:34:20 +01:00
ab b07bcd4ddd Added fix 2026-09-10 22:56:06 +03:00
ab 966cf4b437 Fix connected devices 2026-09-10 18:05:00 +03:00
ab 532d6ee1e9 Integrate shared playback coordination and release 0.3.1 2026-09-10 17:07:41 +03:00
ab 5a193d839f Reworked settings menu 2026-09-07 13:06:46 +03:00
ab 7d6af59e97 fix lock 2026-09-07 12:41:27 +03:00
ab 32c976beb8 Added self updater 2026-09-07 12:36:48 +03:00
Ultradesu 2607314da3 Fix lock 2026-09-02 15:50:41 +01:00
Ultradesu f901836929 fix federation recovery after sleep 2026-09-02 15:10:20 +01:00
32 changed files with 4745 additions and 687 deletions

No files matched your search

+6 -1
View File
@@ -98,7 +98,12 @@ jobs:
run: | run: |
set -euo pipefail set -euo pipefail
gh release create "$RELEASE_TAG" artifacts/*/* \ # Hash archive bytes; manifest entries use the release asset basenames.
for archive in artifacts/*/*; do
(cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")")
done > SHA256SUMS
gh release create "$RELEASE_TAG" artifacts/*/* SHA256SUMS \
--title "furumi ${RELEASE_TAG}" \ --title "furumi ${RELEASE_TAG}" \
--notes "Release ${RELEASE_TAG}" \ --notes "Release ${RELEASE_TAG}" \
--verify-tag --verify-tag
+46
View File
@@ -190,6 +190,13 @@ must propagate and converge, not an ephemeral server-side session flag.
## Playback across devices ## Playback across devices
A persisted device identity has exactly one live coordinator. The TUI holds
an OS file lock beside its device-sync database for the entire runtime; two
installations using the same user data directory cannot open it concurrently.
Network polling is independent per trusted peer, with one in-flight exchange
per peer and a bounded deadline. A stalled peer must not delay the next poll
of a healthy output. Poll tasks are cancelled when federation shuts down.
Playback has one logical state but remains physically local to the device Playback has one logical state but remains physically local to the device
producing audio. producing audio.
@@ -286,6 +293,17 @@ created or edited while Furumi is running without rebuilding or restarting the
application. Bundled scripts use the same path and contract as user scripts, application. Bundled scripts use the same path and contract as user scripts,
so built-in and custom visualizations exercise the same runtime. so built-in and custom visualizations exercise the same runtime.
The v2 primitives are sufficient for small perspective wireframes without a
native 3D engine. The bundled morphing cube transforms eight vertices in Rhai
and batches its twelve edges into trace/vertical-line commands. Perspective,
audio-driven deformation, and depth cues stay in the user-editable script;
Rust rasterizes the resulting 2D commands. This deliberately avoids per-cell
script command maps and does not provide filled meshes or a depth buffer.
The richer cube preset adds bounded particle, ring, inner-cage, and echo
layers. Echo poses are reconstructed from earlier times with current audio
features, rather than retaining previous frames; particles have deterministic
lifetimes. Small terminals omit expensive layers and reduce particle counts.
The Rhai engine is configured as a sandboxed computation environment. Module The Rhai engine is configured as a sandboxed computation environment. Module
loading through `import` and `export` is disabled, no filesystem or network API loading through `import` and `export` is disabled, no filesystem or network API
is exposed to scripts, and execution is bounded by limits on operations, call is exposed to scripts, and execution is bounded by limits on operations, call
@@ -298,6 +316,34 @@ intended role: transforming current audio features into drawing commands. It
is not a plugin mechanism for accessing the library, network, or player is not a plugin mechanism for accessing the library, network, or player
controls. controls.
Fullscreen execution currently happens synchronously during UI drawing, with a fresh
Rhai scope for each frame; scripts should derive motion from time and the
already-smoothed audio features rather than rely on retained mutable state.
The 50 ms animation timer gives a nominal 20 FPS cadence (other events can
also trigger redraws). Operation limits are not wall-clock deadlines. The
host also checks the script modification time during drawing, so slow script
storage or expensive custom scripts can still delay input. Benchmark script
evaluation and buffer drawing separately from real terminal throughput before
increasing scene complexity or the refresh rate.
The embedded status surface uses the same Rhai engine, input map, command
decoder, and clipped buffer rasterizer with a one-row viewport. It has an
independent AST cache and a fixed user-editable script in
`visualizations/status/braille.rhai`, installed if absent. Exact copies of the
previous bundled default can be atomically upgraded; edited files are preserved. It is not a
fullscreen preset. During local playback the visual timer samples the audio
analyzer without increasing trusted-device publication frequency. At most
one blocking render job is in flight; excess ticks are dropped. File access,
compilation, evaluation, and buffer preparation happen on that worker.
An `AppEvent` delivers a prepared row to `AppState`; UI drawing only copies
cells. Its audio input comes from the decoded-source analyzer before output
volume scaling; the volume field remains informational. Pause suspends jobs
and retains the last frame, even when the row needs resizing. Generation
checks discard results invalidated by track changes, resize, pause/resume,
or stop. Script errors are confined to the row and retried so
editing the file repairs the display. Status scripts have a smaller operation
budget, bounded source/output sizes, and cannot draw outside their viewport.
## Music-similarity indexing ## Music-similarity indexing
Similarity search is an optional local capability and is disabled by default. Similarity search is an optional local capability and is disabled by default.
+7 -2
View File
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
## [0.2.8] - 2026-09-02
### Added ### Added
- Optional offline music-similarity search for local tracks, backed by - Optional offline music-similarity search for local tracks, backed by
@@ -27,7 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed ### Changed
- Similarity wire types, bounds, validation, and stream framing now come from - Similarity wire types, bounds, validation, and stream framing now come from
the shared `music-dht 0.4.0` API so native, web, and future clients can the shared `music-dht 0.4` API so native, web, and future clients can
interoperate without sharing an embedding implementation. interoperate without sharing an embedding implementation.
- Existing SQLite embeddings are backfilled once with compact 256-bit routing - Existing SQLite embeddings are backfilled once with compact 256-bit routing
signatures; new embeddings store them immediately without changing exact signatures; new embeddings store them immediately without changing exact
@@ -41,6 +43,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Federation now recovers automatically after sleep, prolonged idle, or a
degraded rendezvous transport while preserving local playback and state.
- Current-track information (`Shift+I`) now uses the enriched queue entry, so - Current-track information (`Shift+I`) now uses the enriched queue entry, so
it shows the same complete metadata and similarity action as `I` on that it shows the same complete metadata and similarity action as `I` on that
track in the queue. track in the queue.
@@ -74,5 +78,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Music-directory validation and migration now reject overlapping changes, - Music-directory validation and migration now reject overlapping changes,
resolve canonical paths, and produce Windows-portable managed filenames. resolve canonical paths, and produce Windows-portable managed filenames.
[Unreleased]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.5...HEAD [Unreleased]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.8...HEAD
[0.2.8]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.7...v0.2.8
[0.2.5]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.4...v0.2.5 [0.2.5]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.4...v0.2.5
Generated
+426 -238
View File
File diff suppressed because it is too large. Load diff
+14 -4
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "furumi_tui" name = "furumi_tui"
version = "0.2.7" version = "0.3.4"
edition = "2024" edition = "2024"
rust-version = "1.97" rust-version = "1.97"
description = "A federated P2P player for personal music libraries" description = "A federated P2P player for personal music libraries"
@@ -11,20 +11,30 @@ name = "furumi"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
semver = "1"
self-replace = "1.5"
tempfile = "3"
fs2 = "0.4"
flate2 = "1"
tar = "0.4"
zip = { version = "4", default-features = false, features = ["deflate"] }
object = { version = "0.36", default-features = false, features = ["read", "std"] }
anyhow = "1.0.102" anyhow = "1.0.102"
blake3 = "1" blake3 = "1"
crokey = "1.4.0" crokey = "1.4.0"
crossterm = { version = "0.29.0", features = ["event-stream"] } crossterm = { version = "0.29.0", features = ["event-stream"] }
directories = "6.0.0" directories = "6.0.0"
futures-util = "0.3.32" futures-util = "0.3.32"
furumi-library = "0.1.0" furumi-library = "0.2.0"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] } image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
lofty = "0.22" lofty = "0.22"
# P2P federation: library index in a shared DHT + audio streaming between # P2P federation: library index in a shared DHT + audio streaming between
# peers (same protocol as furumi-fd). # peers (same protocol as furumi-fd).
music-dht = "0.4.0" music-dht = "0.5.0"
ratatui = "0.30.1" ratatui = "0.30.1"
reqwest = { version = "0.12.28", default-features = false, features = ["rustls-tls", "stream"] } reqwest = { version = "0.12.28", default-features = false, features = ["rustls-tls", "stream", "blocking"] }
rhai = { version = "1", features = ["sync"] } rhai = { version = "1", features = ["sync"] }
rodio = { version = "0.22.2", default-features = false, features = ["playback", "mp3", "flac", "vorbis", "wav", "symphonia-aac", "symphonia-isomp4", "symphonia-alac"] } rodio = { version = "0.22.2", default-features = false, features = ["playback", "mp3", "flac", "vorbis", "wav", "symphonia-aac", "symphonia-isomp4", "symphonia-alac"] }
rusty-opus = "0.9.1" rusty-opus = "0.9.1"
+74
View File
@@ -101,6 +101,9 @@ Download a prebuilt archive from the
[GitHub releases](https://github.com/house-of-vanity/furumi_tui/releases), or [GitHub releases](https://github.com/house-of-vanity/furumi_tui/releases), or
build Furumi from source with Rust 1.97 or newer: build Furumi from source with Rust 1.97 or newer:
The repository selects the stable Rust toolchain. With rustup, run
`rustup update stable` to install or update it before building.
```bash ```bash
cargo build --release --locked cargo build --release --locked
./target/release/furumi ./target/release/furumi
@@ -124,6 +127,28 @@ Import a music directory from Furumi's command line:
Federation, trusted-device pairing, and key bindings are configured directly Federation, trusted-device pairing, and key bindings are configured directly
inside the player. inside the player.
### Manual updates
In **Settings → Additional settings → Updates**, select **Check for updates**, then **Install update**
when a newer stable GitHub release is available. Downloads run in the background.
After installation, restart `furumi` to use the new version; playback is not
restarted automatically. Wait for an active update operation to finish before
quitting.
Updates replace the running executable in its installation directory, which
must be writable by your user. Release archives must include a matching entry
in the release's `SHA256SUMS` asset. Older releases without it cannot be installed
through this feature. The updater checks SHA-256 and the executable's format
and architecture before replacing it. Checksums provide integrity checking,
not publisher signatures. Settings and the local library are preserved.
There are no automatic startup checks. Only the existing release asset naming
scheme is supported; missing or incompatible platform builds are rejected.
The **Additional settings** window also contains the music save directory and
visualization controls. Use Up/Down (or j/k) to navigate, Enter to select, and
Esc to return to Settings. Long lists scroll with the selection.
### Now playing in tmux ### Now playing in tmux
While Furumi is running, a second invocation can print a cheap, single-line While Furumi is running, a second invocation can print a cheap, single-line
@@ -173,6 +198,55 @@ cargo check --all-targets
cargo test --all-targets cargo test --all-targets
``` ```
## Playback coordination
Connected Devices uses the shared `music_dht::playback` engine from frid.
Newly started players take an idle/paused output after discovery and become
controllers when another device is playing. Missing output reports trigger
automatic failover; concurrent claims converge to one owner. The web gateway
uses a passive server profile and reports actual browser activity.
Only one TUI process may use a device identity. Installed and locally built
binaries use the same user data directory: close the installed player before
starting a development build. An OS file lock prevents duplicate coordinators
and is released automatically on exit or a crash. Older builds do not take
this lock, so close those explicitly when upgrading.
Connected-device polling runs independently per peer, so an offline or stalled
device does not postpone updates to live players.
The existing device menu handles manual transfers. Advanced policy can be set
in `settings.toml` without changing the UI:
```toml
[playback]
claim_on_startup = true
automatic_failover = true
take_paused_on_startup = true
discovery_ms = 3000
owner_timeout_ms = 120000
```
All clients must support the new coordination envelope for eventual single
output ownership. frid's `PLAYBACK_PROTOCOL.md` describes the protocol, adapter
contract and rollout. Local Cargo patches are only for development; publish
frid and bump the client dependency versions before releasing these changes.
Run the local protocol checks from the TUI repository:
```bash
cargo test localhost_devices_exchange_state_and_handoff
python scripts/test_device_interop.py ../furumusic
```
The first test uses real iroh streams, isolated SQLite databases, ownership
handoff, and a stalled peer. The second builds both player test binaries and
exchanges their actual JSON messages over `127.0.0.1`: queue metadata,
bidirectional handoff, pause/seek and duplicate command fencing. It exercises
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.
## License ## License
Furumi is released under the Furumi is released under the
+1 -1
View File
@@ -1,4 +1,4 @@
[toolchain] [toolchain]
channel = "1.97.0" channel = "stable"
profile = "minimal" profile = "minimal"
components = ["clippy", "rust-src", "rustfmt"] components = ["clippy", "rust-src", "rustfmt"]
+65
View File
@@ -0,0 +1,65 @@
"""Build and run the real TUI and web protocol adapters against each other.
Usage: python scripts/test_device_interop.py [path/to/furumusic]
No user databases, accounts, audio outputs, or external servers are used.
"""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
def test_binary(repo):
result = subprocess.run(
["cargo", "test", "--locked", "--no-run", "--message-format=json"],
cwd=repo, text=True, encoding="utf-8", stdout=subprocess.PIPE,
)
result.check_returncode()
binaries = []
for line in result.stdout.splitlines():
event = json.loads(line)
if event.get("reason") == "compiler-artifact" and event.get("profile", {}).get("test") and event.get("executable"):
binaries.append(event["executable"])
if len(binaries) != 1:
raise RuntimeError(f"Expected one player test binary in {repo}, found {binaries}")
return binaries[0]
def main():
tui = Path(__file__).resolve().parents[1]
web = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else tui.parent / "furumusic"
tui_bin, web_bin = test_binary(tui), test_binary(web)
with tempfile.TemporaryDirectory(prefix="furumi-interop-") as directory:
env = dict(os.environ, FURUMI_INTEROP_DIR=directory)
processes = []
try:
for binary, test in [(web_bin, "federation::devices::interop_tests::localhost_tui_peer"),
(tui_bin, "devices::interop_tests::localhost_web_peer")]:
listing = subprocess.check_output([binary, "--list"], text=True, encoding="utf-8")
if f"{test}: test" not in listing:
raise RuntimeError(f"Required test {test} is missing from {binary}")
processes.append(subprocess.Popen(
[binary, "--ignored", "--exact", test, "--nocapture"], env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8",
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
))
codes = []
for process in processes:
output, _ = process.communicate(timeout=45)
print(output, end="")
codes.append(process.returncode)
if any(codes):
raise RuntimeError(f"Cross-player test failed: exit codes {codes}")
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait()
print("PASS: TUI <-> WEB state, bidirectional handoff, pause/seek, duplicate fencing")
if __name__ == "__main__":
main()
+14 -1
View File
@@ -10,7 +10,11 @@ use crate::library::models::{
/// the playback engine, imports). Tasks never touch AppState directly. /// the playback engine, imports). Tasks never touch AppState directly.
#[derive(Debug)] #[derive(Debug)]
pub enum AppEvent { pub enum AppEvent {
UpdateChecked(Result<Option<crate::updater::Update>, String>),
UpdateProgress(String),
UpdateInstalled(Result<(), String>),
StatusMessage(String), StatusMessage(String),
StatusVisualizationReady(crate::visualizer::status::Ready),
/// A page of the artists list arrived (or failed). /// A page of the artists list arrived (or failed).
ArtistsLoaded(Result<ArtistsPage, String>), ArtistsLoaded(Result<ArtistsPage, String>),
/// A full reload after a library change: replaces the loaded artist /// A full reload after a library change: replaces the loaded artist
@@ -27,6 +31,11 @@ pub enum AppEvent {
id: i64, id: i64,
result: Result<ReleaseDetail, String>, result: Result<ReleaseDetail, String>,
}, },
/// Federated tracks that complete an already-open local release view.
ReleaseFederationLoaded {
id: i64,
result: Result<Option<crate::federation::FedRelease>, String>,
},
/// Live search results; `seq` drops responses that are already stale. /// Live search results; `seq` drops responses that are already stale.
SearchLoaded { SearchLoaded {
seq: u64, seq: u64,
@@ -182,7 +191,11 @@ pub enum AppEvent {
/// Trusted device playback state, delivered by personal-device sync. /// Trusted device playback state, delivered by personal-device sync.
DevicePlayback(crate::devices::PlaybackSnapshot), DevicePlayback(crate::devices::PlaybackSnapshot),
/// Playback command addressed to this device. /// Playback command addressed to this device.
PlaybackCommand(crate::devices::PlaybackCommand), PlaybackCommand {
command: crate::devices::PlaybackCommand,
authority: music_dht::playback::CommandStamp,
origin: String,
},
/// Current lifecycle/status of the federation Jam. /// Current lifecycle/status of the federation Jam.
JamStatus(crate::jam::JamStatus), JamStatus(crate::jam::JamStatus),
/// Host playback snapshot received by a Jam participant. /// Host playback snapshot received by a Jam participant.
+461 -151
View File
@@ -32,7 +32,6 @@ use update::{Effect, update};
const TICK_INTERVAL: Duration = Duration::from_millis(250); const TICK_INTERVAL: Duration = Duration::from_millis(250);
const VISUALIZER_TICK_INTERVAL: Duration = Duration::from_millis(50); const VISUALIZER_TICK_INTERVAL: Duration = Duration::from_millis(50);
const ACTIVE_IDLE_LEASE_MS: i64 = 5 * 60 * 1000;
/// Handles shared by background tasks; AppState stays pure UI data. /// Handles shared by background tasks; AppState stays pure UI data.
pub struct Runtime { pub struct Runtime {
@@ -76,6 +75,7 @@ pub struct Runtime {
pub media_tx: std::sync::mpsc::Sender<crate::media::MediaUpdate>, pub media_tx: std::sync::mpsc::Sender<crate::media::MediaUpdate>,
pub last_media_push: Option<std::time::Instant>, pub last_media_push: Option<std::time::Instant>,
pub status_publisher: crate::status::Publisher, pub status_publisher: crate::status::Publisher,
pub status_visualizer: crate::visualizer::status::Renderer,
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -190,6 +190,126 @@ fn spawn_artist_federation_enrichment(runtime: &Runtime, id: i64, name: String)
}); });
} }
fn merge_release_federation_results(
title: &str,
releases: impl IntoIterator<Item = crate::federation::FedRelease>,
) -> Option<crate::federation::FedRelease> {
let key = music_dht::normalize_name(title);
let mut merged = None;
for release in releases {
if music_dht::normalize_name(&release.title) != key {
continue;
}
let target = merged.get_or_insert_with(|| crate::federation::FedRelease {
title: release.title.clone(),
release_type: release.release_type.clone(),
year: release.year,
owners: Vec::new(),
cover_path: release.cover_path.clone(),
tracks: Vec::new(),
});
if target.release_type.is_empty() {
target.release_type = release.release_type.clone();
}
if target.year.is_none() {
target.year = release.year;
}
if target.cover_path.is_none() {
target.cover_path = release.cover_path.clone();
}
for owner in release.owners {
if !target.owners.contains(&owner) {
target.owners.push(owner);
}
}
for track in release.tracks {
let existing = target.tracks.iter_mut().find(|existing| {
music_dht::normalize_name(&existing.title)
== music_dht::normalize_name(&track.title)
&& (existing.track_number == track.track_number
|| existing.track_number.is_none()
|| track.track_number.is_none())
});
match existing {
Some(existing) => {
if existing.artists.is_empty() {
existing.artists = track.artists;
}
if existing.featured_artists.is_empty() {
existing.featured_artists = track.featured_artists;
}
if existing.track_number.is_none() {
existing.track_number = track.track_number;
}
if existing.disc_number.is_none() {
existing.disc_number = track.disc_number;
}
if existing.duration_seconds.is_none() {
existing.duration_seconds = track.duration_seconds;
}
if existing.content_id.is_none() {
existing.content_id = track.content_id;
}
for source in track.sources {
if !existing.sources.contains(&source) {
existing.sources.push(source);
}
}
}
None => target.tracks.push(track),
}
}
}
merged
}
fn spawn_release_federation_enrichment(
runtime: &Runtime,
id: i64,
title: String,
artists: Vec<String>,
) {
let fed = Arc::clone(&runtime.federation);
let tx = runtime.event_tx.clone();
tokio::spawn(async move {
let requests = artists.into_iter().map(|artist| {
let fed = Arc::clone(&fed);
async move { fed.artist_card(&artist).await }
});
let mut cards = Vec::new();
let mut errors = Vec::new();
for result in futures_util::future::join_all(requests).await {
match result {
Ok(card) => {
let own_owner = card.own_owner.clone();
for mut release in card.releases {
// The local catalog is included in artist cards. This
// view only needs the missing network tracks; local
// rows are already supplied by the release query.
if let Some(own_owner) = own_owner.as_deref() {
release.owners.retain(|owner| owner != own_owner);
for track in &mut release.tracks {
track.sources.retain(|(owner, _)| owner != own_owner);
}
release.tracks.retain(|track| !track.sources.is_empty());
}
cards.push(release);
}
}
Err(error) => errors.push(format!("{error:#}")),
}
}
let result = if let Some(release) = merge_release_federation_results(&title, cards) {
Ok(Some(release))
} else if !errors.is_empty() {
Err(errors.join("; "))
} else {
Ok(None)
};
let _ = tx.send(AppEvent::ReleaseFederationLoaded { id, result });
});
}
fn maybe_enrich_open_artist(state: &mut AppState, runtime: &Runtime) { fn maybe_enrich_open_artist(state: &mut AppState, runtime: &Runtime) {
if !state.federation.settings.enabled || state.active_tab != state::Tab::Global { if !state.federation.settings.enabled || state.active_tab != state::Tab::Global {
return; return;
@@ -208,6 +328,38 @@ fn maybe_enrich_open_artist(state: &mut AppState, runtime: &Runtime) {
spawn_artist_federation_enrichment(runtime, id, name); spawn_artist_federation_enrichment(runtime, id, name);
} }
fn maybe_enrich_open_release(state: &mut AppState, runtime: &Runtime) {
if !state.federation.settings.enabled
|| !state.global.filters.source_mode.includes_network()
|| state.active_tab != state::Tab::Global
{
return;
}
let Some(state::GlobalView::Release { id, .. }) = state.global.stack.last().copied() else {
return;
};
if state.release_fed_views.contains_key(&id) {
return;
}
let Some(state::Loadable::Ready(detail)) = state.release_views.get(&id) else {
return;
};
let mut artists = Vec::new();
for artist in &detail.artists {
if !artists.iter().any(|name: &String| {
music_dht::normalize_name(name) == music_dht::normalize_name(&artist.name)
}) {
artists.push(artist.name.clone());
}
}
if artists.is_empty() {
return;
}
let title = detail.title.clone();
state.release_fed_views.insert(id, state::Loadable::Loading);
spawn_release_federation_enrichment(runtime, id, title, artists);
}
fn spawn_content_id_backfill(runtime: &Runtime) { fn spawn_content_id_backfill(runtime: &Runtime) {
let library = Arc::clone(&runtime.library); let library = Arc::clone(&runtime.library);
let federation = Arc::clone(&runtime.federation); let federation = Arc::clone(&runtime.federation);
@@ -297,6 +449,8 @@ pub async fn run(
} }
let devices = crate::devices::DeviceSync::new(Arc::clone(&library))?; let devices = crate::devices::DeviceSync::new(Arc::clone(&library))?;
devices.configure_playback(settings.playback.clone())?;
state.device_playback.config = settings.playback.clone();
devices.set_event_tx(event_tx.clone()); devices.set_event_tx(event_tx.clone());
let jam = crate::jam::JamManager::new(event_tx.clone()); let jam = crate::jam::JamManager::new(event_tx.clone());
let similarity = crate::similarity::Manager::new( let similarity = crate::similarity::Manager::new(
@@ -312,6 +466,7 @@ pub async fn run(
Arc::clone(&similarity), Arc::clone(&similarity),
settings.music_dir.clone(), settings.music_dir.clone(),
); );
federation.start_supervisor();
state.music_dir = federation.media_dir(); state.music_dir = federation.media_dir();
state.federation.settings = federation.settings(); state.federation.settings = federation.settings();
state.federation.devices = Some(devices.status()); state.federation.devices = Some(devices.status());
@@ -320,7 +475,6 @@ pub async fn run(
state.device_playback.self_device_name = device_name.clone(); state.device_playback.self_device_name = device_name.clone();
state.device_playback.active_device_id = Some(device_id); state.device_playback.active_device_id = Some(device_id);
state.device_playback.active_device_name = Some(device_name); state.device_playback.active_device_name = Some(device_name);
state.device_playback.startup_takeover_pending = true;
} }
let player_events = event_tx.clone(); let player_events = event_tx.clone();
let mut runtime = Runtime { let mut runtime = Runtime {
@@ -357,6 +511,7 @@ pub async fn run(
media_tx, media_tx,
last_media_push: None, last_media_push: None,
status_publisher: crate::status::Publisher::spawn(), status_publisher: crate::status::Publisher::spawn(),
status_visualizer: crate::visualizer::status::Renderer::default(),
}; };
spawn_content_id_backfill(&runtime); spawn_content_id_backfill(&runtime);
if state.similarity.settings.enabled { if state.similarity.settings.enabled {
@@ -380,6 +535,7 @@ pub async fn run(
tick.set_missed_tick_behavior(MissedTickBehavior::Skip); tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut visual_tick = tokio::time::interval(VISUALIZER_TICK_INTERVAL); let mut visual_tick = tokio::time::interval(VISUALIZER_TICK_INTERVAL);
visual_tick.set_missed_tick_behavior(MissedTickBehavior::Skip); visual_tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut redraw = true;
loop { loop {
let plain_text = match state.popup.as_ref() { let plain_text = match state.popup.as_ref() {
@@ -399,7 +555,8 @@ pub async fn run(
_ => {} _ => {}
} }
if !runtime.plain_text_mode { sync_status_visualizer_target(&mut state, terminal.get_frame().area());
if !runtime.plain_text_mode && (redraw || runtime.force_redraw) {
if runtime.force_redraw { if runtime.force_redraw {
terminal.clear()?; terminal.clear()?;
runtime.force_redraw = false; runtime.force_redraw = false;
@@ -407,6 +564,7 @@ pub async fn run(
terminal.draw(|frame| ui::draw(frame, &state, &keymap))?; terminal.draw(|frame| ui::draw(frame, &state, &keymap))?;
} }
redraw = true;
tokio::select! { tokio::select! {
maybe_event = input.next() => match maybe_event { maybe_event = input.next() => match maybe_event {
Some(Ok(event)) => handle_terminal_event(&mut state, &mut keymap, &mut runtime, event), Some(Ok(event)) => handle_terminal_event(&mut state, &mut keymap, &mut runtime, event),
@@ -415,6 +573,7 @@ pub async fn run(
}, },
Some(app_event) = event_rx.recv() => handle_app_event(&mut state, &mut runtime, app_event), Some(app_event) = event_rx.recv() => handle_app_event(&mut state, &mut runtime, app_event),
_ = tick.tick() => { _ = tick.tick() => {
reconcile_personal_playback(&mut state, &mut runtime);
state.advance_spinner(); state.advance_spinner();
expire_quit_confirmation(&mut state); expire_quit_confirmation(&mut state);
sync_player_shared(&mut state, &runtime); sync_player_shared(&mut state, &runtime);
@@ -424,12 +583,32 @@ pub async fn run(
maybe_prefetch_next(&mut state, &runtime); maybe_prefetch_next(&mut state, &runtime);
push_media_update(&state, &mut runtime, false); push_media_update(&state, &mut runtime, false);
} }
_ = visual_tick.tick(), if state.visualizer.active => { _ = visual_tick.tick(), if state.visualizer.active || crate::visualizer::status::playing(&state) => {
sync_player_shared(&mut state, &runtime); if state.visualizer.active {
sync_player_shared(&mut state, &runtime);
} else {
// The embedded meter only needs the atomic audio snapshot;
// keep device publication on the ordinary player tick.
state.player.audio_analysis = runtime.player.shared.audio_analysis();
// The ready event will repaint. Avoid rendering the old
// meter once here and the new meter again on completion.
redraw = false;
}
sync_status_visualizer_target(&mut state, terminal.get_frame().area());
if !runtime.plain_text_mode {
runtime.status_visualizer.request(&state, runtime.event_tx.clone());
}
} }
} }
if state.should_quit { if state.should_quit {
// A replacement must finish before the runtime/process is torn down.
if state.updater.busy {
state.should_quit = false;
state.status_message =
Some("Please wait for the update operation to finish".into());
continue;
}
if runtime.plain_text_mode { if runtime.plain_text_mode {
leave_plain_text_mode()?; leave_plain_text_mode()?;
runtime.plain_text_mode = false; runtime.plain_text_mode = false;
@@ -469,6 +648,21 @@ fn leave_plain_text_mode() -> Result<()> {
Ok(()) Ok(())
} }
fn sync_status_visualizer_target(state: &mut AppState, screen: ratatui::layout::Rect) {
let area = ui::status_visualizer_area(screen, state);
let target = if crate::visualizer::status::visible(state) && !area.is_empty() {
state
.player
.current
.as_ref()
.map(|track| (area.width, track_playback_key(track)))
} else {
None
};
state.status_visualizer.set_target(target);
state.status_visualizer.set_paused(state.player.paused);
}
fn sync_player_shared(state: &mut AppState, runtime: &Runtime) { fn sync_player_shared(state: &mut AppState, runtime: &Runtime) {
if state.device_playback.is_control() { if state.device_playback.is_control() {
extrapolate_control_position(state); extrapolate_control_position(state);
@@ -618,6 +812,7 @@ fn publish_playback_snapshot_with_active(state: &mut AppState, runtime: &Runtime
state.device_playback.active_device_name = Some(device_name.clone()); state.device_playback.active_device_name = Some(device_name.clone());
} }
let snapshot = crate::devices::PlaybackSnapshot { let snapshot = crate::devices::PlaybackSnapshot {
coordination: None,
device_id, device_id,
device_name, device_name,
active, active,
@@ -631,6 +826,7 @@ fn publish_playback_snapshot_with_active(state: &mut AppState, runtime: &Runtime
runtime runtime
.jam .jam
.publish_host_playback(crate::devices::PlaybackSnapshot { .publish_host_playback(crate::devices::PlaybackSnapshot {
coordination: None,
device_id: state.device_playback.self_device_id.clone(), device_id: state.device_playback.self_device_id.clone(),
device_name: state.device_playback.self_device_name.clone(), device_name: state.device_playback.self_device_name.clone(),
active: true, active: true,
@@ -650,36 +846,6 @@ fn update_local_idle_since(state: &mut AppState) {
} }
} }
fn active_snapshot_idle_since(snapshot: &crate::devices::PlaybackSnapshot) -> Option<i64> {
if snapshot.state.playing && !snapshot.state.paused {
None
} else {
snapshot
.state
.idle_since_ms
.or(Some(snapshot.updated_at_ms))
}
}
fn active_idle_lease_expired(snapshot: &crate::devices::PlaybackSnapshot, now: i64) -> bool {
active_snapshot_idle_since(snapshot)
.is_some_and(|idle_since| now.saturating_sub(idle_since) >= ACTIVE_IDLE_LEASE_MS)
}
fn local_active_lease_protected(state: &mut AppState, now: i64) -> bool {
if !state.device_playback.is_audio_owner() || !state.player.playing {
return false;
}
if !state.player.paused {
return true;
}
update_local_idle_since(state);
state
.device_playback
.local_idle_since_ms
.is_some_and(|idle_since| now.saturating_sub(idle_since) < ACTIVE_IDLE_LEASE_MS)
}
fn extrapolate_control_position(state: &mut AppState) { fn extrapolate_control_position(state: &mut AppState) {
let Some(snapshot) = state.device_playback.last_remote_snapshot.as_ref() else { let Some(snapshot) = state.device_playback.last_remote_snapshot.as_ref() else {
return; return;
@@ -711,6 +877,7 @@ pub(crate) fn become_control_device(
runtime: &Runtime, runtime: &Runtime,
snapshot: crate::devices::PlaybackSnapshot, snapshot: crate::devices::PlaybackSnapshot,
) { ) {
runtime.player.set_playback_allowed(false);
if state.device_playback.is_audio_owner() { if state.device_playback.is_audio_owner() {
runtime.player.stop(); runtime.player.stop();
publish_inactive_playback_snapshot(state, runtime); publish_inactive_playback_snapshot(state, runtime);
@@ -729,6 +896,7 @@ pub(crate) fn become_control_device(
} }
pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime, start_audio: bool) { pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime, start_audio: bool) {
runtime.player.set_playback_allowed(true);
let was_control = state.device_playback.role == state::DevicePlaybackRole::Control; let was_control = state.device_playback.role == state::DevicePlaybackRole::Control;
state.device_playback.role = state::DevicePlaybackRole::Active; state.device_playback.role = state::DevicePlaybackRole::Active;
state.device_playback.jam_host = false; state.device_playback.jam_host = false;
@@ -753,6 +921,13 @@ 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) { pub(crate) fn transfer_active_to_this_device(state: &mut AppState, runtime: &mut Runtime) {
if let Err(error) = runtime
.devices
.claim_playback(&state.device_playback.self_device_id)
{
state.status_message = Some(format!("device handoff: {error}"));
return;
}
if state.device_playback.is_audio_owner() { if state.device_playback.is_audio_owner() {
publish_playback_snapshot(state, runtime); publish_playback_snapshot(state, runtime);
request_urgent_device_sync(runtime); request_urgent_device_sync(runtime);
@@ -792,6 +967,10 @@ pub(crate) fn transfer_active_to_remote_device(
transfer_active_to_this_device(state, runtime); transfer_active_to_this_device(state, runtime);
return; return;
} }
if let Err(error) = runtime.devices.claim_playback(&target_device_id) {
state.status_message = Some(format!("device handoff: {error}"));
return;
}
extrapolate_control_position(state); extrapolate_control_position(state);
let previous_active_id = state.device_playback.active_device_id.clone(); let previous_active_id = state.device_playback.active_device_id.clone();
if state.player.current.is_none() && !state.player.queue.is_empty() { if state.player.current.is_none() && !state.player.queue.is_empty() {
@@ -816,6 +995,7 @@ pub(crate) fn transfer_active_to_remote_device(
record_playback_command_async(runtime, previous, command.clone(), "device handoff"); record_playback_command_async(runtime, previous, command.clone(), "device handoff");
} }
let snapshot = crate::devices::PlaybackSnapshot { let snapshot = crate::devices::PlaybackSnapshot {
coordination: None,
device_id: target_device_id.clone(), device_id: target_device_id.clone(),
device_name: target_device_name.clone(), device_name: target_device_name.clone(),
active: true, active: true,
@@ -1016,6 +1196,7 @@ fn maintenance(state: &mut AppState, runtime: &mut Runtime) {
maybe_refresh_network_library(state, runtime); maybe_refresh_network_library(state, runtime);
maybe_fetch_network_artist_images(state, runtime); maybe_fetch_network_artist_images(state, runtime);
maybe_enrich_open_artist(state, runtime); maybe_enrich_open_artist(state, runtime);
maybe_enrich_open_release(state, runtime);
// Liked ids load once per session — markers are shown everywhere. // Liked ids load once per session — markers are shown everywhere.
if !state.likes_loaded { if !state.likes_loaded {
@@ -1414,6 +1595,31 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
return; return;
} }
match effect { match effect {
Effect::CheckUpdate => {
let tx = runtime.event_tx.clone();
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(crate::updater::check)
.await
.map_err(|err| format!("update worker failed: {err}"))
.and_then(|result| result.map_err(|err| format!("{err:#}")));
let _ = tx.send(AppEvent::UpdateChecked(result));
});
}
Effect::InstallUpdate(update) => {
let tx = runtime.event_tx.clone();
tokio::spawn(async move {
let progress_tx = tx.clone();
let result = tokio::task::spawn_blocking(move || {
crate::updater::install(&update, |message| {
let _ = progress_tx.send(AppEvent::UpdateProgress(message));
})
})
.await
.map_err(|err| format!("update worker failed: {err}"))
.and_then(|result| result.map_err(|err| format!("{err:#}")));
let _ = tx.send(AppEvent::UpdateInstalled(result));
});
}
Effect::PlayCurrent => { Effect::PlayCurrent => {
play_current(state, runtime); play_current(state, runtime);
push_media_metadata(state, runtime); push_media_metadata(state, runtime);
@@ -1934,6 +2140,11 @@ fn perform_control_playback_effect(state: &mut AppState, runtime: &mut Runtime,
} }
fn clamp_settings_cursor(state: &mut AppState) { fn clamp_settings_cursor(state: &mut AppState) {
state.additional_settings_cursor = state.additional_settings_cursor.min(
state::additional_settings_rows(state)
.len()
.saturating_sub(1),
);
let last = state::settings_rows(state).len().saturating_sub(1); let last = state::settings_rows(state).len().saturating_sub(1);
state.settings_cursor = state.settings_cursor.min(last); state.settings_cursor = state.settings_cursor.min(last);
} }
@@ -2839,6 +3050,7 @@ fn refresh_artists(state: &mut AppState, runtime: &Runtime) {
fn save_app_settings(state: &AppState) { fn save_app_settings(state: &AppState) {
let settings = crate::config::settings::AppSettings { let settings = crate::config::settings::AppSettings {
playback: state.device_playback.config.clone(),
volume: state.player.volume, volume: state.player.volume,
library: state.global.filters, library: state.global.filters,
music_dir: state.music_dir.clone(), music_dir: state.music_dir.clone(),
@@ -2862,6 +3074,24 @@ fn reset_artist_pagination(state: &mut AppState) {
global.reloading = false; global.reloading = false;
} }
/// Preserve the queue position while refreshing library-backed entries.
///
/// A playback key identifies a track, not a queue occurrence: the same track
/// may intentionally appear more than once. Only entries removed before the
/// current position can therefore move the current occurrence.
fn queue_position_after_refresh(
queue: &[crate::library::models::TrackItem],
queue_pos: usize,
refreshed_ids: &std::collections::HashSet<i64>,
) -> usize {
let removed_before_current = queue
.iter()
.take(queue_pos)
.filter(|track| track.id >= 0 && !refreshed_ids.contains(&track.id))
.count();
queue_pos.saturating_sub(removed_before_current)
}
/// Swap queue entries for their fresh library copies; tracks that were /// Swap queue entries for their fresh library copies; tracks that were
/// deleted leave the queue. /// deleted leave the queue.
fn apply_queue_refresh( fn apply_queue_refresh(
@@ -2871,6 +3101,9 @@ fn apply_queue_refresh(
) { ) {
let by_id: std::collections::HashMap<i64, _> = let by_id: std::collections::HashMap<i64, _> =
tracks.into_iter().map(|track| (track.id, track)).collect(); tracks.into_iter().map(|track| (track.id, track)).collect();
let refreshed_ids: std::collections::HashSet<i64> = by_id.keys().copied().collect();
let refreshed_queue_pos =
queue_position_after_refresh(&state.player.queue, state.player.queue_pos, &refreshed_ids);
let by_key: std::collections::HashMap<String, _> = by_id let by_key: std::collections::HashMap<String, _> = by_id
.values() .values()
.cloned() .cloned()
@@ -2906,26 +3139,38 @@ fn apply_queue_refresh(
state.queue_tab.cursor = 0; state.queue_tab.cursor = 0;
return; return;
} }
state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
state.queue_tab.cursor = state.queue_tab.cursor.min(state.player.queue.len() - 1); state.queue_tab.cursor = state.queue_tab.cursor.min(state.player.queue.len() - 1);
match (current_id, current_key) { match (current_id, current_key) {
(Some(id), _) if id < 0 => { (Some(id), _) if id < 0 => {
// The current source can be an ephemeral federated stream while // The current source can be an ephemeral federated stream while
// the queue is refreshed after save-on-listen. It is not a // the queue is refreshed after save-on-listen. It is not a
// deleted library row, so keep playback untouched. // deleted library row, so keep playback untouched.
state.player.queue_pos = state.player.queue_pos.min(state.player.queue.len() - 1); state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
} }
(Some(id), Some(key)) if by_id.contains_key(&id) || by_key.contains_key(&key) => { (Some(id), Some(key)) if by_id.contains_key(&id) || by_key.contains_key(&key) => {
if let Some(position) = state // Keep the occurrence at the old position. Searching by key here
// would jump to the first copy when a track is queued repeatedly.
let position_matches_current = state
.player .player
.queue .queue
.iter() .get(state.player.queue_pos)
.position(|track| track_playback_key(track) == key) .is_some_and(|track| track.id == id || track_playback_key(track) == key);
if !position_matches_current
&& let Some(position) = state
.player
.queue
.iter()
.position(|track| track.id == id || track_playback_key(track) == key)
{ {
state.player.queue_pos = position; state.player.queue_pos = position;
} }
state.player.current = by_id state.player.current = state
.get(&id) .player
.queue
.get(state.player.queue_pos)
.cloned() .cloned()
.or_else(|| by_id.get(&id).cloned())
.or_else(|| by_key.get(&key).cloned()); .or_else(|| by_key.get(&key).cloned());
push_media_metadata(state, runtime); push_media_metadata(state, runtime);
} }
@@ -2933,93 +3178,79 @@ fn apply_queue_refresh(
// The playing track was deleted from the library. // The playing track was deleted from the library.
runtime.player_start_pending = false; runtime.player_start_pending = false;
runtime.player.stop(); runtime.player.stop();
state.player.queue_pos = state.player.queue_pos.min(state.player.queue.len() - 1); state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
state.player.current = None; state.player.current = None;
state.player.playing = false; state.player.playing = false;
state.player.paused = false; state.player.paused = false;
push_media_update(state, runtime, true); push_media_update(state, runtime, true);
} }
(None, _) => { (None, _) => {
state.player.queue_pos = state.player.queue_pos.min(state.player.queue.len() - 1); state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1);
} }
} }
} }
fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) {
if state.device_playback.role == state::DevicePlaybackRole::Jam {
runtime
.player
.set_playback_allowed(state.device_playback.is_audio_owner());
let _ = runtime.devices.playback_tick(false, false);
return;
}
let playing =
state.device_playback.is_audio_owner() && state.player.playing && !state.player.paused;
let owner = match runtime.devices.playback_tick(true, playing) {
Ok(owner) => owner,
Err(error) => {
runtime.player.set_playback_allowed(false);
runtime.player.stop();
state.status_message = Some(format!("playback coordination: {error}"));
return;
}
};
let Some(owner) = owner else {
runtime.player.set_playback_allowed(false);
runtime.player.stop();
runtime.player_start_pending = false;
state.device_playback.role = state::DevicePlaybackRole::Control;
state.device_playback.active_device_id = None;
return;
};
if owner == state.device_playback.self_device_id {
runtime.player.set_playback_allowed(true);
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()
{
become_control_device(state, runtime, snapshot);
}
} else {
runtime.player.set_playback_allowed(false);
runtime.player.stop();
runtime.player_start_pending = false;
state.device_playback.role = state::DevicePlaybackRole::Control;
state.device_playback.active_device_id = Some(owner);
}
publish_playback_snapshot_with_active(state, runtime, state.device_playback.is_audio_owner());
}
fn handle_device_playback_snapshot( fn handle_device_playback_snapshot(
state: &mut AppState, state: &mut AppState,
runtime: &mut Runtime, runtime: &mut Runtime,
snapshot: crate::devices::PlaybackSnapshot, snapshot: crate::devices::PlaybackSnapshot,
) { ) {
// Personal-device reconciliation must never change Jam ownership. Jam
// has its own authority and lifecycle even when the same TUI also belongs
// to a trusted-device group.
if state.device_playback.role == state::DevicePlaybackRole::Jam {
return;
}
if snapshot.device_id == state.device_playback.self_device_id { if snapshot.device_id == state.device_playback.self_device_id {
return; return;
} }
state state
.device_playback .device_playback
.remote .remote
.insert(snapshot.device_id.clone(), snapshot.clone()); .insert(snapshot.device_id.clone(), snapshot);
let now = unix_time_ms(); reconcile_personal_playback(state, runtime);
state.device_playback.online_devices = state
.device_playback
.remote
.values()
.filter(|snapshot| {
now.saturating_sub(snapshot.updated_at_ms) <= state::DEVICE_ONLINE_TTL_MS
})
.count()
+ 1;
if !snapshot.active {
return;
}
// Starting a player is an explicit claim of the active role. Import the
// current queue/position from the previously active peer, then announce a
// normal handoff so that the old owner becomes a control device. This is
// intentionally one-shot: subsequent snapshots use the regular lease and
// explicit-transfer rules.
if state.device_playback.startup_takeover_pending {
state.device_playback.startup_takeover_pending = false;
become_control_device(state, runtime, snapshot);
transfer_active_to_this_device(state, runtime);
state.status_message = Some("playback moved to this newly started player".to_string());
return;
}
if local_active_lease_protected(state, now) {
tracing::debug!(
remote = %snapshot.device_id,
"ignored remote active snapshot while local active playback is protected"
);
return;
}
let lease_expired = active_idle_lease_expired(&snapshot, now);
let already_controls_this_device = state.device_playback.is_personal_control()
&& state.device_playback.active_device_id.as_deref() == Some(snapshot.device_id.as_str());
if !lease_expired || already_controls_this_device {
let was_active = state.device_playback.is_audio_owner();
let was_paused = state.player.playing && state.player.paused;
become_control_device(state, runtime, snapshot.clone());
if was_active && was_paused {
state.popup = Some(state::Popup::FedText {
title: "Active device moved".to_string(),
text: format!("Playback is now controlled by {}.", snapshot.device_name),
});
}
return;
}
if state.device_playback.is_personal_control() {
return;
}
become_active_device(state, runtime, false);
state.status_message = Some(format!(
"active playback moved here; {} was idle for 5m",
snapshot.device_name
));
} }
fn handle_playback_command( fn handle_playback_command(
@@ -3074,10 +3305,19 @@ fn handle_playback_command(
state: wire, state: wire,
} => { } => {
if active_device_id == state.device_playback.self_device_id { if active_device_id == state.device_playback.self_device_id {
handle_playback_command(
state,
runtime,
crate::devices::PlaybackCommand::SetState {
state: wire,
seek: true,
},
);
return; return;
} }
let was_active = state.device_playback.is_audio_owner(); let was_active = state.device_playback.is_audio_owner();
let snapshot = crate::devices::PlaybackSnapshot { let snapshot = crate::devices::PlaybackSnapshot {
coordination: None,
device_id: active_device_id, device_id: active_device_id,
device_name: active_device_name, device_name: active_device_name,
active: true, active: true,
@@ -3097,6 +3337,41 @@ fn handle_playback_command(
fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent) { fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent) {
match event { match event {
AppEvent::StatusVisualizationReady(ready) => {
runtime.status_visualizer.busy = false;
state.status_visualizer.apply(ready);
}
AppEvent::UpdateChecked(result) => {
state.updater.busy = false;
state.updater.message = match result {
Ok(Some(update)) => {
let message = format!("v{} available", update.version);
state.updater.available = Some(update);
message
}
Ok(None) => "No newer stable release".into(),
Err(error) => format!("Check failed: {error}"),
};
state.status_message = Some(state.updater.message.clone());
}
AppEvent::UpdateProgress(message) => state.updater.message = message,
AppEvent::UpdateInstalled(result) => {
state.updater.busy = false;
state.updater.message = match result {
Ok(()) => {
state.updater.installed = true;
let version = state
.updater
.available
.as_ref()
.map(|u| u.version.as_str())
.unwrap_or("new version");
format!("Installed {version}; restart furumi")
}
Err(error) => format!("Update failed: {error}"),
};
state.status_message = Some(state.updater.message.clone());
}
AppEvent::StatusMessage(message) => state.status_message = Some(message), AppEvent::StatusMessage(message) => state.status_message = Some(message),
AppEvent::ListenHistoryLoaded(result) => { AppEvent::ListenHistoryLoaded(result) => {
state.listen_history = Some(match result { state.listen_history = Some(match result {
@@ -3168,47 +3443,6 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}) })
.unwrap_or(1) .unwrap_or(1)
.max(1); .max(1);
let active_revoked = state.device_playback.is_personal_control()
&& state
.device_playback
.active_device_id
.as_ref()
.is_some_and(|active| {
state
.federation
.devices
.as_ref()
.and_then(|status| {
status
.devices
.iter()
.find(|device| device.device_id == *active)
})
.is_some_and(|device| device.revoked)
});
let active_missing = state.device_playback.is_personal_control()
&& state
.device_playback
.active_device_id
.as_ref()
.is_some_and(|active| {
active != &state.device_playback.self_device_id
&& !state.federation.devices.as_ref().is_some_and(|status| {
status
.devices
.iter()
.any(|device| device.device_id == *active)
})
});
if active_revoked || active_missing {
runtime.player.stop();
state.player.playing = false;
state.player.current = None;
state.player.paused = false;
state.player.position_secs = 0.0;
become_active_device(state, runtime, false);
state.status_message = Some("active playback moved to this device".into());
}
clamp_settings_cursor(state); clamp_settings_cursor(state);
} }
AppEvent::FedSyncFinished(message) => { AppEvent::FedSyncFinished(message) => {
@@ -3249,18 +3483,28 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
AppEvent::DevicePlayback(snapshot) => { AppEvent::DevicePlayback(snapshot) => {
handle_device_playback_snapshot(state, runtime, snapshot); handle_device_playback_snapshot(state, runtime, snapshot);
} }
AppEvent::PlaybackCommand(_) AppEvent::PlaybackCommand { .. }
if state.device_playback.role == state::DevicePlaybackRole::Jam => if state.device_playback.role == state::DevicePlaybackRole::Jam =>
{ {
tracing::debug!("ignored personal-device playback command while Jam is active"); tracing::debug!("ignored personal-device playback command while Jam is active");
} }
AppEvent::PlaybackCommand(command) => { AppEvent::PlaybackCommand {
handle_playback_command(state, runtime, command); command,
authority,
origin,
} => {
if runtime
.devices
.playback_command_is_current(&origin, &authority)
{
handle_playback_command(state, runtime, command);
}
} }
AppEvent::JamStatus(status) => { AppEvent::JamStatus(status) => {
state.jam = status.clone(); state.jam = status.clone();
match status.role { match status.role {
crate::jam::JamRole::Host => { crate::jam::JamRole::Host => {
runtime.player.set_playback_allowed(true);
state.device_playback.role = state::DevicePlaybackRole::Jam; state.device_playback.role = state::DevicePlaybackRole::Jam;
state.device_playback.jam_host = true; state.device_playback.jam_host = true;
publish_playback_snapshot(state, runtime); publish_playback_snapshot(state, runtime);
@@ -3570,6 +3814,17 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
state.artist_fed_views.insert(id, entry); state.artist_fed_views.insert(id, entry);
state::restore_artist_cursor_anchor(state, id, cursor_anchor); state::restore_artist_cursor_anchor(state, id, cursor_anchor);
} }
AppEvent::ReleaseFederationLoaded { id, result } => {
let entry = match result {
Ok(Some(release)) => state::Loadable::Ready(release),
Ok(None) => state::Loadable::Ready(crate::federation::FedRelease::default()),
Err(message) => {
tracing::debug!(release = id, %message, "release federation enrichment failed");
state::Loadable::Failed(message)
}
};
state.release_fed_views.insert(id, entry);
}
AppEvent::NetworkArtistCacheUpdated { source_id, count } => { AppEvent::NetworkArtistCacheUpdated { source_id, count } => {
tracing::debug!(source = %source_id, count, "network artist cache updated"); tracing::debug!(source = %source_id, count, "network artist cache updated");
if state.active_tab == state::Tab::Global && state.global.stack.is_empty() { if state.active_tab == state::Tab::Global && state.global.stack.is_empty() {
@@ -3693,6 +3948,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
} }
}; };
state.release_views.insert(id, entry); state.release_views.insert(id, entry);
maybe_enrich_open_release(state, runtime);
// A Shift-J jump was waiting for this release: focus its track. // A Shift-J jump was waiting for this release: focus its track.
if let Some((release_id, track_id)) = state.pending_release_focus if let Some((release_id, track_id)) = state.pending_release_focus
&& release_id == id && release_id == id
@@ -3779,6 +4035,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
} }
AppEvent::Player(event) if state.device_playback.is_control() => { AppEvent::Player(event) if state.device_playback.is_control() => {
runtime.player_start_pending = false; runtime.player_start_pending = false;
// A background decoder may finish after ownership was handed off.
// Ignoring Started alone would leave its obsolete audio playing.
runtime.player.stop();
tracing::debug!( tracing::debug!(
?event, ?event,
"ignored local player event while controlling remote playback" "ignored local player event while controlling remote playback"
@@ -4182,6 +4441,57 @@ mod similarity_search_tests {
} }
} }
#[cfg(test)]
mod queue_refresh_tests {
use super::*;
use crate::library::models::TrackItem;
fn track(id: i64) -> TrackItem {
TrackItem {
id,
title: "duplicate".into(),
track_number: None,
disc_number: None,
duration_seconds: 1.0,
artists: vec![],
featured_artists: vec![],
release_id: 1,
release_title: "release".into(),
release_year: None,
cover_path: None,
file_path: format!("/music/{id}"),
content_id: None,
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
}
}
#[test]
fn queue_refresh_keeps_the_selected_duplicate_occurrence() {
let queue = vec![track(7), track(7), track(7)];
let refreshed_ids = std::collections::HashSet::from([7]);
assert_eq!(
queue_position_after_refresh(&queue, 2, &refreshed_ids),
2,
"refreshing duplicate queue entries must not select the first one"
);
}
#[test]
fn queue_refresh_shifts_position_only_for_removed_entries_before_it() {
let queue = vec![track(8), track(7), track(7)];
let refreshed_ids = std::collections::HashSet::from([7]);
assert_eq!(queue_position_after_refresh(&queue, 2, &refreshed_ids), 1);
}
}
/// Mirror the playback state to the OS now-playing surface. `force` skips /// Mirror the playback state to the OS now-playing surface. `force` skips
/// the position throttle (track switches, pauses). /// the position throttle (track switches, pauses).
fn push_media_update(state: &AppState, runtime: &mut Runtime, force: bool) { fn push_media_update(state: &AppState, runtime: &mut Runtime, force: bool) {
+177 -22
View File
@@ -303,6 +303,79 @@ mod tests {
assert_eq!(fed_release_display_order(&releases), vec![2, 0, 3, 1, 4]); assert_eq!(fed_release_display_order(&releases), vec![2, 0, 3, 1, 4]);
} }
#[test]
fn release_tracks_adds_remote_rows_without_duplicating_local_content() {
let local_content =
"b3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string();
let detail = ReleaseDetail {
id: 7,
title: "Album".to_string(),
release_type: "album".to_string(),
year: Some(2024),
cover_path: None,
artists: vec![crate::library::models::ArtistRef {
id: 3,
name: "Artist".to_string(),
}],
tracks: vec![TrackItem {
id: 1,
title: "Local".to_string(),
track_number: Some(1),
disc_number: None,
duration_seconds: 120.0,
artists: Vec::new(),
featured_artists: Vec::new(),
release_id: 7,
release_title: "Album".to_string(),
release_year: Some(2024),
file_path: "/music/local.mp3".to_string(),
content_id: Some(local_content.clone()),
cover_path: None,
audio_format: Some("mp3".to_string()),
audio_bitrate: Some(320),
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
}],
};
let mut state = AppState::default();
state.release_fed_views.insert(
detail.id,
Loadable::Ready(crate::federation::FedRelease {
title: "Album".to_string(),
tracks: vec![
crate::federation::FedCardTrack {
title: "Local".to_string(),
track_number: Some(1),
content_id: Some(local_content),
sources: vec![("peer".to_string(), "local-item".to_string())],
..Default::default()
},
crate::federation::FedCardTrack {
title: "Remote".to_string(),
track_number: Some(3),
sources: vec![("peer".to_string(), "remote-item".to_string())],
..Default::default()
},
],
..Default::default()
}),
);
let tracks = release_tracks(&state, detail.id, &detail);
assert_eq!(
tracks
.iter()
.map(|track| track.title.as_str())
.collect::<Vec<_>>(),
vec!["Local", "Remote"]
);
assert!(tracks[1].is_fed_pending());
}
#[test] #[test]
fn artist_merged_releases_marks_partially_local_federated_release() { fn artist_merged_releases_marks_partially_local_federated_release() {
let local_id = "b3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; let local_id = "b3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
@@ -926,6 +999,9 @@ impl FedRow {
/// the config directory. /// the config directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingsRow { pub enum SettingsRow {
AdditionalSettings,
CheckUpdate,
InstallUpdate,
MusicDirectory, MusicDirectory,
Similarity(SimilarityRow), Similarity(SimilarityRow),
Federation(FedRow), Federation(FedRow),
@@ -1064,20 +1140,13 @@ pub fn device_status_order(state: &AppState) -> Vec<usize> {
indices indices
} }
pub fn settings_rows(state: &AppState) -> Vec<SettingsRow> { /// Secondary settings share actions but have independent navigation.
let mut rows = vec![SettingsRow::MusicDirectory]; pub fn additional_settings_rows(state: &AppState) -> Vec<SettingsRow> {
rows.extend(SimilarityRow::ALL.into_iter().map(SettingsRow::Similarity)); let mut rows = vec![
rows.extend(FedRow::ALL.into_iter().map(SettingsRow::Federation)); SettingsRow::MusicDirectory,
rows.push(SettingsRow::DeviceName); SettingsRow::CheckUpdate,
rows.push(SettingsRow::DeviceInvite); SettingsRow::InstallUpdate,
rows.push(SettingsRow::DeviceConnect); ];
rows.push(SettingsRow::DeviceSyncNow);
rows.push(SettingsRow::DeviceLeaveGroup);
rows.extend(
device_status_order(state)
.into_iter()
.map(SettingsRow::Device),
);
rows.push(SettingsRow::VisualizationClock); rows.push(SettingsRow::VisualizationClock);
rows.extend( rows.extend(
state state
@@ -1091,7 +1160,23 @@ pub fn settings_rows(state: &AppState) -> Vec<SettingsRow> {
if !state.visualizer.scripts.is_empty() { if !state.visualizer.scripts.is_empty() {
rows.push(SettingsRow::VisualizationEdit); rows.push(SettingsRow::VisualizationEdit);
} }
rows.push(SettingsRow::StatusDetails); rows
}
pub fn settings_rows(state: &AppState) -> Vec<SettingsRow> {
let mut rows = vec![SettingsRow::AdditionalSettings, SettingsRow::StatusDetails];
rows.extend(FedRow::ALL.into_iter().map(SettingsRow::Federation));
rows.push(SettingsRow::DeviceName);
rows.push(SettingsRow::DeviceInvite);
rows.push(SettingsRow::DeviceConnect);
rows.push(SettingsRow::DeviceSyncNow);
rows.push(SettingsRow::DeviceLeaveGroup);
rows.extend(
device_status_order(state)
.into_iter()
.map(SettingsRow::Device),
);
rows.extend(SimilarityRow::ALL.into_iter().map(SettingsRow::Similarity));
rows rows
} }
@@ -1529,6 +1614,7 @@ impl DevicePlaybackRole {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct DevicePlaybackState { pub struct DevicePlaybackState {
pub config: music_dht::playback::Config,
pub role: DevicePlaybackRole, pub role: DevicePlaybackRole,
pub self_device_id: String, pub self_device_id: String,
pub self_device_name: String, pub self_device_name: String,
@@ -1539,9 +1625,6 @@ pub struct DevicePlaybackState {
pub remote: BTreeMap<String, crate::devices::PlaybackSnapshot>, pub remote: BTreeMap<String, crate::devices::PlaybackSnapshot>,
pub last_remote_snapshot: Option<crate::devices::PlaybackSnapshot>, pub last_remote_snapshot: Option<crate::devices::PlaybackSnapshot>,
pub jam_host: bool, pub jam_host: bool,
/// A freshly started TUI owns playback by protocol. The first active
/// snapshot discovered during startup is imported and handed off here.
pub startup_takeover_pending: bool,
} }
impl DevicePlaybackState { impl DevicePlaybackState {
@@ -1550,10 +1633,6 @@ impl DevicePlaybackState {
|| (self.role == DevicePlaybackRole::Jam && !self.jam_host) || (self.role == DevicePlaybackRole::Jam && !self.jam_host)
} }
pub fn is_personal_control(&self) -> bool {
self.role == DevicePlaybackRole::Control
}
pub fn is_audio_owner(&self) -> bool { pub fn is_audio_owner(&self) -> bool {
self.role == DevicePlaybackRole::Active self.role == DevicePlaybackRole::Active
|| (self.role == DevicePlaybackRole::Jam && self.jam_host) || (self.role == DevicePlaybackRole::Jam && self.jam_host)
@@ -1571,6 +1650,7 @@ impl DevicePlaybackState {
/// event handlers in the main loop; views render from `&AppState`. /// event handlers in the main loop; views render from `&AppState`.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct AppState { pub struct AppState {
pub updater: crate::updater::State,
pub active_tab: Tab, pub active_tab: Tab,
pub should_quit: bool, pub should_quit: bool,
pub shutting_down: bool, pub shutting_down: bool,
@@ -1582,6 +1662,9 @@ pub struct AppState {
pub status_message: Option<String>, pub status_message: Option<String>,
pub spinner_frame: usize, pub spinner_frame: usize,
pub settings_cursor: usize, pub settings_cursor: usize,
/// Kept open underneath child dialogs and asynchronous confirmations.
pub additional_settings_open: bool,
pub additional_settings_cursor: usize,
/// Root for music permanently downloaded from federation peers. /// Root for music permanently downloaded from federation peers.
pub music_dir: std::path::PathBuf, pub music_dir: std::path::PathBuf,
pub music_dir_changing: bool, pub music_dir_changing: bool,
@@ -1589,11 +1672,14 @@ pub struct AppState {
pub device_playback: DevicePlaybackState, pub device_playback: DevicePlaybackState,
pub jam: crate::jam::JamStatus, pub jam: crate::jam::JamStatus,
pub visualizer: crate::visualizer::VisualizerState, pub visualizer: crate::visualizer::VisualizerState,
pub status_visualizer: crate::visualizer::status::State,
pub global: GlobalTab, pub global: GlobalTab,
pub artist_views: HashMap<i64, Loadable<ArtistDetail>>, pub artist_views: HashMap<i64, Loadable<ArtistDetail>>,
/// Federated card data that enriches a local artist page in-place. /// Federated card data that enriches a local artist page in-place.
pub artist_fed_views: HashMap<i64, Loadable<crate::federation::FedArtistCard>>, pub artist_fed_views: HashMap<i64, Loadable<crate::federation::FedArtistCard>>,
pub release_views: HashMap<i64, Loadable<ReleaseDetail>>, pub release_views: HashMap<i64, Loadable<ReleaseDetail>>,
/// Federated tracks that enrich an already-open local release view.
pub release_fed_views: HashMap<i64, Loadable<crate::federation::FedRelease>>,
pub playlists: PlaylistsTab, pub playlists: PlaylistsTab,
pub playlist_views: HashMap<i64, Loadable<PlaylistDetail>>, pub playlist_views: HashMap<i64, Loadable<PlaylistDetail>>,
/// Liked local-library content ids, for the ♥ markers everywhere tracks are shown. /// Liked local-library content ids, for the ♥ markers everywhere tracks are shown.
@@ -1711,6 +1797,75 @@ pub fn artist_fed_card(state: &AppState, id: i64) -> Option<&crate::federation::
} }
} }
/// The tracklist rendered and played by an opened release. When federation
/// has supplied a matching release, local rows remain authoritative and only
/// tracks that are not already present locally are appended.
pub fn release_tracks(state: &AppState, id: i64, detail: &ReleaseDetail) -> Vec<TrackItem> {
let mut tracks = detail.tracks.clone();
if !state.global.filters.source_mode.includes_network() {
return tracks;
}
let Some(Loadable::Ready(fed_release)) = state.release_fed_views.get(&id) else {
return tracks;
};
for fed in &fed_release.tracks {
let Some((owner, item_id)) = fed.sources.first().cloned() else {
continue;
};
let fed_content_id = fed
.content_id
.as_deref()
.and_then(music_dht::normalize_content_id);
let already_local = tracks.iter().any(|local| {
let same_content = fed_content_id.is_some()
&& track_content_id(local).as_deref() == fed_content_id.as_deref();
let same_position = local.track_number == fed.track_number
|| local.track_number.is_none()
|| fed.track_number.is_none();
same_content
|| (music_dht::normalize_name(&local.title)
== music_dht::normalize_name(&fed.title)
&& same_position)
});
if already_local {
continue;
}
let names = if fed.artists.is_empty() {
detail
.artists
.iter()
.map(|artist| artist.name.clone())
.collect()
} else {
fed.artists.clone()
};
let featured_artists = fed.featured_artists.clone();
tracks.push(crate::federation::pending_track(
&crate::federation::FedTrack {
item_id,
owner,
own: false,
title: fed.title.clone(),
artist_names: names,
featured_artist_names: featured_artists,
year: fed_release.year.or(detail.year),
duration_seconds: fed.duration_seconds.map(|seconds| seconds.round() as i64),
content_id: fed.content_id.clone(),
release_title: Some(detail.title.clone()),
track_number: fed.track_number,
disc_number: fed.disc_number,
},
));
}
tracks.sort_by_key(|track| {
(
track.disc_number.unwrap_or(1),
track.track_number.unwrap_or(i32::MAX),
)
});
tracks
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtistCursorAnchor { pub enum ArtistCursorAnchor {
TopTrack(i64), TopTrack(i64),
+112 -25
View File
@@ -18,6 +18,8 @@ pub const QUIT_CONFIRM_HINT: &str = "press quit again to exit";
/// owns the Runtime (audio controller, API client). Keeps update() pure. /// owns the Runtime (audio controller, API client). Keeps update() pure.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect { pub enum Effect {
CheckUpdate,
InstallUpdate(crate::updater::Update),
/// (Re)start playback of `queue[queue_pos]`. /// (Re)start playback of `queue[queue_pos]`.
PlayCurrent, PlayCurrent,
TogglePause, TogglePause,
@@ -113,6 +115,22 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
.take() .take()
.is_some_and(|deadline| Instant::now() <= deadline); .is_some_and(|deadline| Instant::now() <= deadline);
state.status_message = None; state.status_message = None;
if state.additional_settings_open
&& !matches!(
action,
Action::PlayPause
| Action::NextTrack
| Action::PrevTrack
| Action::SeekForward { .. }
| Action::SeekBackward { .. }
| Action::VolumeUp
| Action::VolumeDown
| Action::ToggleShuffle
| Action::CycleRepeat
)
{
return update_additional_settings(state, action);
}
match action { match action {
// While the help window is open, quit/back just close it. // While the help window is open, quit/back just close it.
Action::Quit | Action::Back if state.help_visible => { Action::Quit | Action::Back if state.help_visible => {
@@ -947,11 +965,10 @@ fn current_track_list_context(state: &AppState) -> Option<(TrackSelectionScope,
_ => None, _ => None,
}, },
GlobalView::Release { id, cursor } => match state.release_views.get(id)? { GlobalView::Release { id, cursor } => match state.release_views.get(id)? {
Loadable::Ready(detail) => Some(( Loadable::Ready(detail) => {
TrackSelectionScope::Release(*id), let tracks = crate::app::state::release_tracks(state, *id, detail);
*cursor, Some((TrackSelectionScope::Release(*id), *cursor, tracks.len()))
detail.tracks.len(), }
)),
_ => None, _ => None,
}, },
GlobalView::Search { cursor } => { GlobalView::Search { cursor } => {
@@ -1003,7 +1020,7 @@ fn current_track_list_context(state: &AppState) -> Option<(TrackSelectionScope,
} }
} }
fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, Vec<&TrackItem>)> { fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, Vec<TrackItem>)> {
match state.active_tab { match state.active_tab {
Tab::Global => match state.global.stack.last()? { Tab::Global => match state.global.stack.last()? {
GlobalView::Artist { id, cursor } => match state.artist_views.get(id)? { GlobalView::Artist { id, cursor } => match state.artist_views.get(id)? {
@@ -1014,14 +1031,14 @@ fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, V
Some(( Some((
TrackSelectionScope::ArtistTop(*id), TrackSelectionScope::ArtistTop(*id),
*cursor, *cursor,
detail.top_tracks.iter().collect(), detail.top_tracks.clone(),
)) ))
} else { } else {
let featured = cursor.checked_sub(tracks + releases)?; let featured = cursor.checked_sub(tracks + releases)?;
(featured < detail.featured_tracks.len()).then_some(( (featured < detail.featured_tracks.len()).then_some((
TrackSelectionScope::ArtistFeatured(*id), TrackSelectionScope::ArtistFeatured(*id),
featured, featured,
detail.featured_tracks.iter().collect(), detail.featured_tracks.clone(),
)) ))
} }
} }
@@ -1031,7 +1048,7 @@ fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, V
Loadable::Ready(detail) => Some(( Loadable::Ready(detail) => Some((
TrackSelectionScope::Release(*id), TrackSelectionScope::Release(*id),
*cursor, *cursor,
detail.tracks.iter().collect(), crate::app::state::release_tracks(state, *id, detail),
)), )),
_ => None, _ => None,
}, },
@@ -1042,13 +1059,16 @@ fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, V
Some(( Some((
TrackSelectionScope::Playlist(opened.id), TrackSelectionScope::Playlist(opened.id),
opened.cursor, opened.cursor,
playlist_tracks(state, opened.id)?, playlist_tracks(state, opened.id)?
.into_iter()
.cloned()
.collect(),
)) ))
} }
Tab::Queue => Some(( Tab::Queue => Some((
TrackSelectionScope::Queue, TrackSelectionScope::Queue,
state.queue_tab.cursor, state.queue_tab.cursor,
state.player.queue.iter().collect(), state.player.queue.clone(),
)), )),
Tab::Federation | Tab::Logs => None, Tab::Federation | Tab::Logs => None,
} }
@@ -1086,7 +1106,7 @@ pub fn selected_tracks(state: &AppState) -> Vec<TrackItem> {
.unwrap_or_else(|| vec![cursor.min(tracks.len().saturating_sub(1))]); .unwrap_or_else(|| vec![cursor.min(tracks.len().saturating_sub(1))]);
indices indices
.into_iter() .into_iter()
.filter_map(|index| tracks.get(index).map(|track| (*track).clone())) .filter_map(|index| tracks.get(index).cloned())
.collect() .collect()
} }
@@ -1297,7 +1317,9 @@ pub fn selected_track(state: &AppState) -> Option<TrackItem> {
_ => None, _ => None,
}, },
GlobalView::Release { id, cursor } => match state.release_views.get(id)? { GlobalView::Release { id, cursor } => match state.release_views.get(id)? {
Loadable::Ready(detail) => detail.tracks.get(*cursor).cloned(), Loadable::Ready(detail) => crate::app::state::release_tracks(state, *id, detail)
.get(*cursor)
.cloned(),
_ => None, _ => None,
}, },
GlobalView::Search { cursor } => { GlobalView::Search { cursor } => {
@@ -1438,11 +1460,12 @@ fn open_release_for_track(state: &mut AppState, track: &TrackItem) {
} }
let release_id = track.release_id; let release_id = track.release_id;
let cursor = match state.release_views.get(&release_id) { let cursor = match state.release_views.get(&release_id) {
Some(Loadable::Ready(detail)) => detail Some(Loadable::Ready(detail)) => {
.tracks crate::app::state::release_tracks(state, release_id, detail)
.iter() .iter()
.position(|t| t.id == track.id) .position(|t| t.id == track.id)
.unwrap_or(0), .unwrap_or(0)
}
_ => { _ => {
state.pending_release_focus = Some((release_id, track.id)); state.pending_release_focus = Some((release_id, track.id));
0 0
@@ -1896,7 +1919,7 @@ fn move_selection(state: &mut AppState, dx: isize, dy: isize) {
let Some(Loadable::Ready(detail)) = state.release_views.get(&id) else { let Some(Loadable::Ready(detail)) = state.release_views.get(&id) else {
return; return;
}; };
let total = detail.tracks.len() as isize; let total = crate::app::state::release_tracks(state, id, detail).len() as isize;
if total == 0 { if total == 0 {
return; return;
} }
@@ -2027,7 +2050,7 @@ fn current_view_len(state: &AppState) -> usize {
_ => 0, _ => 0,
}, },
Some(GlobalView::Release { id, .. }) => match state.release_views.get(id) { Some(GlobalView::Release { id, .. }) => match state.release_views.get(id) {
Some(Loadable::Ready(d)) => d.tracks.len(), Some(Loadable::Ready(d)) => crate::app::state::release_tracks(state, *id, d).len(),
_ => 0, _ => 0,
}, },
Some(GlobalView::Search { .. }) => { Some(GlobalView::Search { .. }) => {
@@ -2321,10 +2344,17 @@ fn select_current(state: &mut AppState) -> Option<Effect> {
_ => Outcome::Nothing, _ => Outcome::Nothing,
}, },
Some(GlobalView::Release { id, cursor }) => match state.release_views.get(&id) { Some(GlobalView::Release { id, cursor }) => match state.release_views.get(&id) {
Some(Loadable::Ready(detail)) if !detail.tracks.is_empty() => Outcome::Play { Some(Loadable::Ready(detail)) => {
tracks: detail.tracks.clone(), let tracks = crate::app::state::release_tracks(state, id, detail);
start: cursor.min(detail.tracks.len() - 1), if tracks.is_empty() {
}, Outcome::Nothing
} else {
Outcome::Play {
start: cursor.min(tracks.len() - 1),
tracks,
}
}
}
_ => Outcome::Nothing, _ => Outcome::Nothing,
}, },
Some(GlobalView::Search { cursor }) => { Some(GlobalView::Search { cursor }) => {
@@ -2812,9 +2842,66 @@ fn fed_card_featured_artist_names(track: &crate::federation::FedCardTrack) -> Ve
/// Enter on Settings: toggle switches, open text inputs, run /// Enter on Settings: toggle switches, open text inputs, run
/// one-shot operations. The heavy lifting happens in perform_effect(). /// one-shot operations. The heavy lifting happens in perform_effect().
fn update_additional_settings(state: &mut AppState, action: Action) -> Option<Effect> {
if state.help_visible {
if matches!(action, Action::Back | Action::Quit | Action::ToggleHelp) {
state.help_visible = false;
}
return None;
}
let rows = super::state::additional_settings_rows(state);
let last = rows.len().saturating_sub(1);
let cursor = state.additional_settings_cursor.min(last);
state.additional_settings_cursor = match action {
Action::Back | Action::Quit => {
state.additional_settings_open = false;
return None;
}
Action::MoveUp | Action::PrevTab => cursor.saturating_sub(1),
Action::MoveDown | Action::NextTab => (cursor + 1).min(last),
Action::PageUp => cursor.saturating_sub(5),
Action::PageDown => (cursor + 5).min(last),
Action::SelectFirst => 0,
Action::SelectLast => last,
Action::Select => return select_settings_row(state, *rows.get(cursor)?),
Action::ToggleHelp => {
state.help_visible = true;
cursor
}
_ => cursor,
};
None
}
fn federation_select(state: &mut AppState) -> Option<Effect> { fn federation_select(state: &mut AppState) -> Option<Effect> {
select_settings_row(state, *settings_rows(state).get(state.settings_cursor)?)
}
fn select_settings_row(state: &mut AppState, row: super::state::SettingsRow) -> Option<Effect> {
use super::state::{FedInputField, FedRow, Popup, SettingsRow, SimilarityRow}; use super::state::{FedInputField, FedRow, Popup, SettingsRow, SimilarityRow};
match settings_rows(state).get(state.settings_cursor).copied()? { match row {
SettingsRow::AdditionalSettings => {
state.additional_settings_open = true;
None
}
SettingsRow::CheckUpdate => {
if state.updater.busy || state.updater.installed {
return None;
}
state.updater.busy = true;
state.updater.available = None;
state.updater.message = "Checking GitHub Releases...".into();
Some(Effect::CheckUpdate)
}
SettingsRow::InstallUpdate => {
if state.updater.busy || state.updater.installed {
return None;
}
let update = state.updater.available.clone()?;
state.updater.busy = true;
state.updater.message = "Downloading update...".into();
Some(Effect::InstallUpdate(update))
}
SettingsRow::MusicDirectory => { SettingsRow::MusicDirectory => {
if state.music_dir_changing { if state.music_dir_changing {
state.status_message = Some("music directory change is already running".into()); state.status_message = Some("music directory change is already running".into());
+73
View File
@@ -1,6 +1,79 @@
use super::*; use super::*;
use crate::library::models::{ArtistCard, ArtistDetail, TrackItem}; use crate::library::models::{ArtistCard, ArtistDetail, TrackItem};
#[test]
fn additional_settings_preserve_main_navigation_and_child_dialog_parent() {
use crate::app::state::{FedInputField, Popup, SettingsRow, additional_settings_rows};
let mut state = AppState {
active_tab: Tab::Federation,
..AppState::default()
};
let main_rows = settings_rows(&state);
assert!(!main_rows.contains(&SettingsRow::MusicDirectory));
assert!(!main_rows.contains(&SettingsRow::CheckUpdate));
assert!(!main_rows.contains(&SettingsRow::VisualizationClock));
state.settings_cursor = main_rows
.iter()
.position(|r| *r == SettingsRow::AdditionalSettings)
.unwrap();
let main_cursor = state.settings_cursor;
update(&mut state, Action::Select);
assert!(state.additional_settings_open);
update(&mut state, Action::Select);
assert!(matches!(
state.popup,
Some(Popup::FedInput {
field: FedInputField::MusicDirectory,
..
})
));
// Child dialogs own their input; closing one leaves the parent window intact.
state.popup = None;
assert!(state.additional_settings_open);
update(&mut state, Action::SelectLast);
assert_eq!(
state.additional_settings_cursor,
additional_settings_rows(&state).len() - 1
);
update(&mut state, Action::MoveDown);
assert_eq!(
state.additional_settings_cursor,
additional_settings_rows(&state).len() - 1
);
update(&mut state, Action::ToggleHelp);
update(&mut state, Action::Back);
assert!(!state.help_visible);
assert!(state.additional_settings_open);
update(&mut state, Action::Back);
assert!(!state.additional_settings_open);
assert!(!state.should_quit);
assert_eq!(state.settings_cursor, main_cursor);
}
#[test]
fn manual_update_check_is_single_flight_and_disabled_after_install() {
let mut state = AppState::default();
state.additional_settings_cursor = crate::app::state::additional_settings_rows(&state)
.iter()
.position(|row| *row == crate::app::state::SettingsRow::CheckUpdate)
.unwrap();
assert_eq!(
update_additional_settings(&mut state, Action::Select),
Some(Effect::CheckUpdate)
);
assert!(state.updater.busy);
assert_eq!(update_additional_settings(&mut state, Action::Select), None);
state.updater.busy = false;
state.updater.installed = true;
assert_eq!(update_additional_settings(&mut state, Action::Select), None);
state.updater.installed = false;
state.additional_settings_cursor = crate::app::state::additional_settings_rows(&state)
.iter()
.position(|row| *row == crate::app::state::SettingsRow::InstallUpdate)
.unwrap();
assert_eq!(update_additional_settings(&mut state, Action::Select), None);
}
fn with_artists(n: usize) -> AppState { fn with_artists(n: usize) -> AppState {
let mut state = AppState::default(); let mut state = AppState::default();
state.global.artists = (0..n) state.global.artists = (0..n)
+3
View File
@@ -50,6 +50,8 @@ impl Default for SimilaritySettings {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AppSettings { pub struct AppSettings {
#[serde(default)]
pub playback: music_dht::playback::Config,
#[serde(default = "default_volume")] #[serde(default = "default_volume")]
pub volume: u8, pub volume: u8,
#[serde(default)] #[serde(default)]
@@ -64,6 +66,7 @@ pub struct AppSettings {
impl Default for AppSettings { impl Default for AppSettings {
fn default() -> Self { fn default() -> Self {
Self { Self {
playback: music_dht::playback::Config::default(),
volume: default_volume(), volume: default_volume(),
library: LibraryFilters::default(), library: LibraryFilters::default(),
music_dir: default_music_dir(), music_dir: default_music_dir(),
+231 -45
View File
@@ -5,6 +5,7 @@
//! materialized tables, so offline clients can merge likes, playlists and //! materialized tables, so offline clients can merge likes, playlists and
//! membership changes deterministically. //! membership changes deterministically.
use music_dht::playback::{Checkpoint, CommandStamp, Config as PlaybackConfig, Engine};
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf; use std::path::PathBuf;
use std::str::FromStr; use std::str::FromStr;
@@ -24,7 +25,7 @@ use crate::library::models::{ArtistRef, TrackItem};
pub const SYNC_ALPN: &[u8] = b"furumi/sync/2"; pub const SYNC_ALPN: &[u8] = b"furumi/sync/2";
const CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION"); const CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const PROTOCOL_VERSION: u16 = 2; pub const PROTOCOL_VERSION: u16 = 3;
const INVITE_TTL_MS: i64 = 10 * 60 * 1000; const INVITE_TTL_MS: i64 = 10 * 60 * 1000;
const PAIRING_WAIT_MS: i64 = 5 * 60 * 1000; const PAIRING_WAIT_MS: i64 = 5 * 60 * 1000;
const PAIRING_RETRY_DELAY: Duration = Duration::from_secs(1); const PAIRING_RETRY_DELAY: Duration = Duration::from_secs(1);
@@ -81,6 +82,10 @@ pub struct DeviceSyncStatus {
#[derive(Clone)] #[derive(Clone)]
pub struct DeviceSync { pub struct DeviceSync {
// A device identity has exactly one coordinator, including across binaries
// launched from different installation directories. The OS releases this
// lock on crashes; the file itself is deliberately never removed.
_identity_lock: Option<Arc<std::fs::File>>,
conn: Arc<std::sync::Mutex<Connection>>, conn: Arc<std::sync::Mutex<Connection>>,
library: Arc<Library>, library: Arc<Library>,
event_tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<AppEvent>>>>, event_tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<AppEvent>>>>,
@@ -245,32 +250,13 @@ pub struct PlaybackStateWire {
pub repeat: PlaybackRepeat, pub repeat: PlaybackRepeat,
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub type PlaybackSnapshot = music_dht::playback::Snapshot<PlaybackStateWire>;
pub struct PlaybackSnapshot { pub type PlaybackCommand = music_dht::playback::Command<PlaybackStateWire>;
pub device_id: String,
pub device_name: String,
pub active: bool,
pub updated_at_ms: i64,
pub state: PlaybackStateWire,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PlaybackCommand {
SetState {
state: PlaybackStateWire,
#[serde(default)]
seek: bool,
},
ActiveChanged {
active_device_id: String,
active_device_name: String,
state: PlaybackStateWire,
},
}
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
struct PlaybackShared { struct PlaybackShared {
engine: Option<Engine>,
engine_group: String,
local: Option<PlaybackSnapshot>, local: Option<PlaybackSnapshot>,
remote: BTreeMap<String, PlaybackSnapshot>, remote: BTreeMap<String, PlaybackSnapshot>,
} }
@@ -369,6 +355,8 @@ pub enum SyncOpPayload {
PlaybackCommand { PlaybackCommand {
target_device_id: String, target_device_id: String,
command: PlaybackCommand, command: PlaybackCommand,
#[serde(default)]
authority: Option<CommandStamp>,
}, },
ListenRecorded { ListenRecorded {
event: ListenEvent, event: ListenEvent,
@@ -615,16 +603,33 @@ fn default_db_path() -> PathBuf {
.unwrap_or_else(|| PathBuf::from("devices").join("sync.sqlite3")) .unwrap_or_else(|| PathBuf::from("devices").join("sync.sqlite3"))
} }
fn acquire_identity_lock(database: &std::path::Path) -> Result<std::fs::File> {
let path = database.with_extension("lock");
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.with_context(|| format!("opening device identity lock {}", path.display()))?;
file.try_lock().with_context(|| format!(
"Cannot acquire device identity lock {}. Another Furumi instance may already be using this device. Close it before launching another binary; two players must not share one device identity.", path.display()
))?;
Ok(file)
}
impl DeviceSync { impl DeviceSync {
pub fn new(library: Arc<Library>) -> Result<Arc<Self>> { pub fn new(library: Arc<Library>) -> Result<Arc<Self>> {
let path = default_db_path(); let path = default_db_path();
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
} }
let identity_lock = acquire_identity_lock(&path)?;
let conn = let conn =
Connection::open(&path).with_context(|| format!("opening {}", path.display()))?; Connection::open(&path).with_context(|| format!("opening {}", path.display()))?;
init_schema(&conn)?; init_schema(&conn)?;
let sync = Arc::new(Self { let sync = Arc::new(Self {
_identity_lock: Some(Arc::new(identity_lock)),
conn: Arc::new(std::sync::Mutex::new(conn)), conn: Arc::new(std::sync::Mutex::new(conn)),
library, library,
event_tx: Arc::new(std::sync::Mutex::new(None)), event_tx: Arc::new(std::sync::Mutex::new(None)),
@@ -648,10 +653,92 @@ impl DeviceSync {
format!("{}-{}", now_ms(), random_hex(12)) format!("{}-{}", now_ms(), random_hex(12))
} }
pub fn configure_playback(&self, config: PlaybackConfig) -> Result<()> {
set_meta(
&lock(&self.conn),
"playback_config_v1",
&serde_json::to_string(&config)?,
)?;
lock(&self.playback).engine = None;
Ok(())
}
fn with_playback_engine<R>(&self, f: impl FnOnce(&mut Engine) -> R) -> Result<R> {
let identity = self.ensure_identity()?;
let mut shared = lock(&self.playback);
if shared.engine.is_none() || shared.engine_group != identity.group_id {
shared.engine_group = identity.group_id.clone();
let conn = lock(&self.conn);
let durable = get_meta(&conn, "playback_coordination_v1")?
.map(|json| serde_json::from_str::<Checkpoint>(&json))
.transpose()?
.filter(|checkpoint| checkpoint.scope == identity.group_id)
.map(|checkpoint| checkpoint.state)
.unwrap_or_default();
let config = get_meta(&conn, "playback_config_v1")?
.map(|json| serde_json::from_str::<PlaybackConfig>(&json))
.transpose()?
.unwrap_or_default();
shared.engine = Some(Engine::new(
identity.device_id,
config,
durable,
playback_clock(),
));
}
let engine = shared.engine.as_mut().expect("initialized playback engine");
let previous = engine.clone();
let result = f(engine);
if previous.durable() != engine.durable() {
let saved = set_meta(
&lock(&self.conn),
"playback_coordination_v1",
&serde_json::to_string(&Checkpoint {
scope: identity.group_id,
state: engine.durable().clone(),
})?,
);
if let Err(error) = saved {
*engine = previous;
return Err(error);
}
}
Ok(result)
}
/// Evaluate shared ownership independently of the UI's online-device list.
pub fn playback_tick(&self, available: bool, playing: bool) -> Result<Option<String>> {
self.with_playback_engine(|engine| {
engine.set_output(available, playing);
engine.heartbeat(playback_clock());
engine.tick(playback_clock());
engine.owner().map(str::to_string)
})
}
pub fn playback_command_is_current(&self, origin: &str, stamp: &CommandStamp) -> bool {
self.with_playback_engine(|engine| engine.command_is_current(origin, stamp))
.unwrap_or(false)
}
pub fn claim_playback(&self, target: &str) -> Result<()> {
self.with_playback_engine(|engine| engine.transfer(target, playback_clock()))?
.then_some(())
.context("cannot allocate playback ownership term")
}
pub fn publish_playback(&self, mut snapshot: PlaybackSnapshot) { pub fn publish_playback(&self, mut snapshot: PlaybackSnapshot) {
if snapshot.updated_at_ms <= 0 { if snapshot.updated_at_ms <= 0 {
snapshot.updated_at_ms = now_ms(); snapshot.updated_at_ms = now_ms();
} }
let Ok(coordination) = self.with_playback_engine(|engine| engine.announcement()) else {
return;
};
snapshot.active = coordination
.claim
.as_ref()
.is_some_and(|claim| claim.owner == snapshot.device_id);
snapshot.coordination = Some(coordination);
lock(&self.playback).local = Some(snapshot); lock(&self.playback).local = Some(snapshot);
} }
@@ -663,9 +750,22 @@ impl DeviceSync {
if target_device_id.trim().is_empty() { if target_device_id.trim().is_empty() {
return Ok(()); return Ok(());
} }
let authority = self
.with_playback_engine(|engine| {
if let PlaybackCommand::ActiveChanged {
active_device_id, ..
} = &command
&& engine.owner() != Some(active_device_id.as_str())
{
engine.transfer(active_device_id, playback_clock());
}
engine.stamp()
})?
.context("no playback owner; wait for discovery or select an output")?;
self.record_local_op(SyncOpPayload::PlaybackCommand { self.record_local_op(SyncOpPayload::PlaybackCommand {
target_device_id: target_device_id.to_string(), target_device_id: target_device_id.to_string(),
command, command,
authority: Some(authority),
}) })
} }
@@ -845,7 +945,7 @@ impl DeviceSync {
if let Some(profile) = profile { if let Some(profile) = profile {
self.apply_device_profile(&profile, true)?; self.apply_device_profile(&profile, true)?;
if let Some(playback) = playback { if let Some(playback) = playback {
self.apply_playback_snapshot(playback)?; self.apply_playback_snapshot(&profile.device_id, playback)?;
} }
} }
self.apply_device_profiles(&devices)?; self.apply_device_profiles(&devices)?;
@@ -1305,7 +1405,7 @@ impl DeviceSync {
} => { } => {
self.apply_device_profiles(&devices)?; self.apply_device_profiles(&devices)?;
if let Some(playback) = playback { if let Some(playback) = playback {
self.apply_playback_snapshot(playback)?; self.apply_playback_snapshot(&device.device_id, playback)?;
} }
self.apply_snapshot(snapshot)?; self.apply_snapshot(snapshot)?;
self.apply_ops(ops)?; self.apply_ops(ops)?;
@@ -1636,8 +1736,15 @@ impl DeviceSync {
SyncOpPayload::PlaybackCommand { SyncOpPayload::PlaybackCommand {
target_device_id, target_device_id,
command, command,
authority,
} => { } => {
self.apply_playback_command(target_device_id, command, &op.op_id)?; self.apply_playback_command(
target_device_id,
command,
authority.as_ref(),
&op.origin_device_id,
&op.op_id,
)?;
false false
} }
SyncOpPayload::ListenRecorded { event } => self SyncOpPayload::ListenRecorded { event } => self
@@ -1651,10 +1758,32 @@ impl DeviceSync {
&self, &self,
target_device_id: &str, target_device_id: &str,
command: &PlaybackCommand, command: &PlaybackCommand,
authority: Option<&CommandStamp>,
origin: &str,
op_id: &str, op_id: &str,
) -> Result<()> { ) -> Result<()> {
let identity = self.ensure_identity()?; let identity = self.ensure_identity()?;
if target_device_id != identity.device_id { // Legacy commands still replicate with the library log, but cannot
// override the versioned personal-playback protocol.
let Some(authority) = authority else {
return Ok(());
};
let handoff = matches!(command, PlaybackCommand::ActiveChanged { .. });
if !handoff && target_device_id != identity.device_id {
return Ok(());
}
if let PlaybackCommand::ActiveChanged {
active_device_id, ..
} = command
&& active_device_id != &authority.claim.owner
{
return Ok(());
}
let accepted = self.with_playback_engine(|engine| {
engine.accept_command(origin, authority, handoff, playback_clock())
&& (handoff || engine.is_owner())
})?;
if !accepted || target_device_id != identity.device_id {
return Ok(()); return Ok(());
} }
let inserted = { let inserted = {
@@ -1669,7 +1798,11 @@ impl DeviceSync {
return Ok(()); return Ok(());
} }
if let Some(tx) = lock(&self.event_tx).as_ref() { if let Some(tx) = lock(&self.event_tx).as_ref() {
let _ = tx.send(AppEvent::PlaybackCommand(command.clone())); let _ = tx.send(AppEvent::PlaybackCommand {
command: command.clone(),
authority: authority.clone(),
origin: origin.to_string(),
});
} }
Ok(()) Ok(())
} }
@@ -2595,19 +2728,29 @@ impl DeviceSync {
lock(&self.playback).local.clone() lock(&self.playback).local.clone()
} }
fn apply_playback_snapshot(&self, snapshot: PlaybackSnapshot) -> Result<()> { fn apply_playback_snapshot(&self, sender: &str, snapshot: PlaybackSnapshot) -> Result<()> {
let identity = self.ensure_identity()?; let identity = self.ensure_identity()?;
if snapshot.device_id == identity.device_id { if snapshot.device_id != sender || snapshot.device_id == identity.device_id {
return Ok(());
}
let Some(coordination) = &snapshot.coordination else {
return Ok(());
};
if !self.with_playback_engine(|engine| {
engine.observe(&snapshot.device_id, coordination, playback_clock())
})? {
return Ok(()); return Ok(());
} }
let should_send = { let should_send = {
let mut playback = lock(&self.playback); let mut shared = lock(&self.playback);
let changed = playback let changed = shared.remote.get(&snapshot.device_id).is_none_or(|old| {
.remote old.coordination.as_ref().is_none_or(|c| {
.get(&snapshot.device_id) coordination.claim > c.claim
.is_none_or(|current| snapshot.updated_at_ms > current.updated_at_ms); || (coordination.claim == c.claim && coordination.heartbeat > c.heartbeat)
})
});
if changed { if changed {
playback shared
.remote .remote
.insert(snapshot.device_id.clone(), snapshot.clone()); .insert(snapshot.device_id.clone(), snapshot.clone());
} }
@@ -2707,13 +2850,45 @@ pub async fn sync_loop(
transport_stats: Arc<crate::federation::TransportStats>, transport_stats: Arc<crate::federation::TransportStats>,
) { ) {
let mut interval = tokio::time::interval(SYNC_INTERVAL); let mut interval = tokio::time::interval(SYNC_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
// Independent polls: an offline device must not hold up live outputs.
// JoinSet aborts outstanding IO when federation stops or restarts.
let mut polls = tokio::task::JoinSet::new();
let mut active = std::collections::HashMap::new();
loop { loop {
interval.tick().await; tokio::select! {
if let Err(err) = sync _ = interval.tick() => {
.sync_once(Arc::clone(&service), Arc::clone(&transport_stats)) match sync.active_remote_devices() {
.await Ok(devices) => for device in devices {
{ if device.endpoint_ticket.trim().is_empty()
tracing::debug!("personal sync tick failed: {err:#}"); || active.values().any(|id| id == &device.device_id) { continue; }
let device_id = device.device_id.clone();
let sync = Arc::clone(&sync);
let service = Arc::clone(&service);
let stats = Arc::clone(&transport_stats);
let handle = polls.spawn(async move {
tokio::time::timeout(Duration::from_secs(30), sync.sync_device(service, &device, stats))
.await.context("device sync exchange timed out")?
});
active.insert(handle.id(), device_id);
},
Err(err) => { let _ = sync.set_last_error(Some(format!("{err:#}"))); }
}
if let Err(err) = sync.gc_tombstones() {
tracing::debug!("personal sync cleanup failed: {err:#}");
}
}
Some(completed) = polls.join_next_with_id(), if !polls.is_empty() => {
let (task, result) = match completed {
Ok((task, result)) => (task, result),
Err(error) => (error.id(), Err(anyhow::Error::from(error))),
};
if let Some(device_id) = active.remove(&task)
&& let Err(err) = result {
tracing::debug!(device = %device_id, "device sync failed: {err:#}");
let _ = sync.set_last_error(Some(format!("{}: {err:#}", short_id(&device_id))));
}
}
} }
if let Some(tx) = lock(&sync.event_tx).as_ref() { if let Some(tx) = lock(&sync.event_tx).as_ref() {
let _ = tx.send(AppEvent::DeviceSyncStatus(sync.status())); let _ = tx.send(AppEvent::DeviceSyncStatus(sync.status()));
@@ -2936,7 +3111,7 @@ async fn handle_pair_request(
} }
sync.apply_device_profile(&profile, true)?; sync.apply_device_profile(&profile, true)?;
if let Some(playback) = playback { if let Some(playback) = playback {
sync.apply_playback_snapshot(playback)?; sync.apply_playback_snapshot(&profile.device_id, playback)?;
} }
sync.apply_snapshot(snapshot)?; sync.apply_snapshot(snapshot)?;
sync.apply_ops(ops)?; sync.apply_ops(ops)?;
@@ -3026,7 +3201,7 @@ async fn handle_hello(
sync.apply_device_profile(&profile, false)?; sync.apply_device_profile(&profile, false)?;
sync.apply_device_profiles(&devices)?; sync.apply_device_profiles(&devices)?;
if let Some(playback) = playback { if let Some(playback) = playback {
sync.apply_playback_snapshot(playback)?; sync.apply_playback_snapshot(&profile.device_id, playback)?;
} }
sync.apply_snapshot(snapshot)?; sync.apply_snapshot(snapshot)?;
sync.apply_ops(ops)?; sync.apply_ops(ops)?;
@@ -3635,3 +3810,14 @@ fn base64url_decode(value: &str) -> Result<Vec<u8>> {
#[cfg(test)] #[cfg(test)]
#[path = "devices/tests.rs"] #[path = "devices/tests.rs"]
mod tests; mod tests;
#[cfg(test)]
mod interop_tests;
fn playback_clock() -> u64 {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
START
.get_or_init(std::time::Instant::now)
.elapsed()
.as_millis() as u64
}
+133
View File
@@ -0,0 +1,133 @@
//! Cross-binary wire test. Run with scripts/test_device_interop.py; the other
//! endpoint is compiled from furumusic's real protocol types and player hub.
use super::*;
use tokio::io::AsyncWriteExt;
#[tokio::test]
#[ignore = "run scripts/test_device_interop.py to start both player test binaries"]
async fn localhost_web_peer() {
tokio::time::timeout(Duration::from_secs(30), async {
let dir = PathBuf::from(std::env::var("FURUMI_INTEROP_DIR").expect("interop runner"));
let address = loop {
if let Ok(address) = std::fs::read_to_string(dir.join("web-address")) {
break address;
}
tokio::time::sleep(Duration::from_millis(20)).await;
};
let mut stream = tokio::net::TcpStream::connect(address.trim())
.await
.unwrap();
let conn = Connection::open_in_memory().unwrap();
init_schema(&conn).unwrap();
let sync = DeviceSync {
_identity_lock: None,
conn: Arc::new(std::sync::Mutex::new(conn)),
library: Arc::new(Library::open(&dir.join("interop-library.sqlite3")).unwrap()),
event_tx: Default::default(),
playback: Default::default(),
};
let id = sync.ensure_identity().unwrap();
let (tx, mut events) = tokio::sync::mpsc::unbounded_channel();
sync.set_event_tx(tx);
sync.claim_playback(&id.device_id).unwrap();
sync.playback_tick(true, true).unwrap();
let mut state: PlaybackStateWire = serde_json::from_value(serde_json::json!({
"queue": [{ "id": 7, "title": "Interop track", "duration_seconds": 123.5,
"release_id": 1, "release_title": "Interop album", "artist_names": ["Interop artist"],
"content_id": "b3:0000000000000000000000000000000000000000000000000000000000000000" }],
"queue_pos": 0, "playing": true, "paused": false,
"position_secs": 42.5, "volume": 73, "shuffle": true, "repeat": "all"
}))
.unwrap();
for phase in 0..3 {
sync.publish_playback(PlaybackSnapshot {
device_id: id.device_id.clone(),
device_name: "TUI interop".into(),
active: true,
updated_at_ms: now_ms(),
state: state.clone(),
coordination: None,
});
let hello = WireMessage::Hello {
group_id: id.group_id.clone(),
profile: sync.own_profile("").unwrap(),
devices: vec![],
vector: BTreeMap::new(),
ops: vec![],
snapshot: SyncSnapshot::default(),
playback: sync.local_playback_snapshot(),
};
let mut bytes = serde_json::to_vec(&hello).unwrap();
bytes.push(b'\n');
stream.write_all(&bytes).await.unwrap();
let response: WireMessage =
serde_json::from_slice(&read_line(&mut stream).await.unwrap()).unwrap();
let WireMessage::SyncResponse {
accepted: true,
playback: Some(snapshot),
ops,
..
} = response
else {
panic!("expected web response")
};
let web_id = snapshot.device_id.clone();
sync.apply_playback_snapshot(&web_id, snapshot).unwrap();
assert_eq!(ops.len(), 1);
let op = &ops[0];
// Production command adapter including durable fencing/deduplication.
sync.apply_op(op).unwrap();
sync.apply_op(op).unwrap();
let mut commands = Vec::new();
while let Ok(event) = events.try_recv() {
if let AppEvent::PlaybackCommand {
command,
authority,
origin,
} = event
{
assert!(sync.playback_command_is_current(&origin, &authority));
commands.push(command);
}
}
assert_eq!(commands.len(), 1, "one event even after duplicate delivery");
match commands.pop().unwrap() {
PlaybackCommand::ActiveChanged {
active_device_id,
state: next,
..
} => {
assert_eq!(
active_device_id,
if phase == 0 {
web_id.clone()
} else {
id.device_id.clone()
}
);
assert_eq!(next.position_secs, 42.5);
assert_eq!(next.queue, state.queue);
state = next;
}
PlaybackCommand::SetState { state: next, seek } => {
assert_eq!(phase, 2);
assert!(seek);
assert!(next.paused);
assert_eq!(next.position_secs, 87.0);
state = next;
}
}
assert_eq!(
sync.playback_tick(true, false).unwrap(),
Some(if phase == 0 {
web_id
} else {
id.device_id.clone()
})
);
}
stream.write_all(b"ok\n").await.unwrap();
})
.await
.expect("web/TUI exchange timed out");
}
+386 -6
View File
@@ -1,5 +1,329 @@
use super::*; use super::*;
/// Exercises the production stream handlers and SQLite adapter, not just the
/// ownership reducer. Each peer has a fresh identity and an isolated library.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn localhost_devices_exchange_state_and_handoff() {
tokio::time::timeout(Duration::from_secs(30), async {
let dirs = [tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()];
let network = NetworkId::from_name(&format!("device-test-{}", random_hex(16)));
let mut peers = Vec::new();
let mut servers = Vec::new();
let mut receivers = Vec::new();
for dir in &dirs {
std::fs::create_dir_all(dir.path().join("network")).unwrap();
let config = music_dht::MusicDhtConfig::builder()
.data_dir(dir.path().join("network"))
.network_id(network)
.stream_protocol(SYNC_ALPN)
.build()
.unwrap();
let (service, events) = MusicDhtService::start(config).await.unwrap();
let service = Arc::new(service);
let conn = Connection::open_in_memory().unwrap();
init_schema(&conn).unwrap();
let sync = Arc::new(DeviceSync {
_identity_lock: Some(Arc::new(
acquire_identity_lock(&dir.path().join("sync.sqlite3")).unwrap(),
)),
conn: Arc::new(std::sync::Mutex::new(conn)),
library: Arc::new(Library::open(&dir.path().join("library.sqlite3")).unwrap()),
event_tx: Default::default(),
playback: Default::default(),
});
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
sync.set_event_tx(tx);
let stats = Arc::new(crate::federation::TransportStats::default());
servers.push(tokio::spawn(serve_peers(
service.stream_acceptor(SYNC_ALPN).unwrap(),
sync.clone(),
service.clone(),
stats.clone(),
)));
receivers.push(rx);
peers.push((sync, service, stats, events));
}
let (a, service_a, stats_a, _) = &peers[0];
let (b, service_b, stats_b, _) = &peers[1];
b.ensure_identity().unwrap();
b.set_group_id(&a.ensure_identity().unwrap().group_id)
.unwrap();
let profile_a = a
.own_profile(&service_a.ticket().await.unwrap().to_string())
.unwrap();
let profile_b = b
.own_profile(&service_b.ticket().await.unwrap().to_string())
.unwrap();
a.apply_device_profile(&profile_b, true).unwrap();
b.apply_device_profile(&profile_a, true).unwrap();
a.claim_playback(&profile_a.device_id).unwrap();
a.playback_tick(true, true).unwrap();
let mut state = empty_playback_state();
state.playing = true;
state.position_secs = 42.5;
a.publish_playback(PlaybackSnapshot {
device_id: profile_a.device_id.clone(),
device_name: "TUI".into(),
active: true,
updated_at_ms: now_ms(),
state: state.clone(),
coordination: None,
});
a.sync_device(
service_a.clone(),
&a.active_remote_devices().unwrap()[0],
stats_a.clone(),
)
.await
.unwrap();
assert_eq!(
b.with_playback_engine(|e| e.owner().map(str::to_owned))
.unwrap(),
Some(profile_a.device_id.clone())
);
assert_eq!(lock(&b.playback).remote[&profile_a.device_id].state, state);
assert!(
b.status()
.devices
.iter()
.any(|d| d.device_id == profile_a.device_id && d.last_seen_ms.is_some())
);
a.record_playback_command(
&profile_b.device_id,
PlaybackCommand::ActiveChanged {
active_device_id: profile_b.device_id.clone(),
active_device_name: "Second player".into(),
state: state.clone(),
},
)
.unwrap();
a.sync_device(
service_a.clone(),
&a.active_remote_devices().unwrap()[0],
stats_a.clone(),
)
.await
.unwrap();
let mut transferred = false;
while let Ok(event) = receivers[1].try_recv() {
if let AppEvent::PlaybackCommand {
command:
PlaybackCommand::ActiveChanged {
state: received, ..
},
authority,
origin,
} = event
{
assert_eq!(received, state);
assert!(b.playback_command_is_current(&origin, &authority));
transferred = true;
}
}
assert!(transferred, "handoff must reach the player's event loop");
assert_eq!(
b.playback_tick(true, true).unwrap(),
Some(profile_b.device_id.clone())
);
b.publish_playback(PlaybackSnapshot {
device_id: profile_b.device_id.clone(),
device_name: "Second player".into(),
active: true,
updated_at_ms: now_ms(),
state,
coordination: None,
});
b.sync_device(
service_b.clone(),
&b.active_remote_devices().unwrap()[0],
stats_b.clone(),
)
.await
.unwrap();
assert_eq!(
a.playback_tick(true, false).unwrap(),
Some(profile_b.device_id)
);
// A paired peer that accepts a connection but never answers must not
// serialize or stop subsequent polls to the responsive peer.
let silent_dir = tempfile::tempdir().unwrap();
let (silent, _events) = MusicDhtService::start(
music_dht::MusicDhtConfig::builder()
.data_dir(silent_dir.path())
.network_id(network)
.stream_protocol(SYNC_ALPN)
.build()
.unwrap(),
)
.await
.unwrap();
let _silent_acceptor = silent.stream_acceptor(SYNC_ALPN).unwrap();
let mut silent_profile = profile_a.clone();
silent_profile.device_id = "silent-peer".into();
silent_profile.endpoint_id = silent.endpoint_id().to_string();
silent_profile.endpoint_ticket = silent.ticket().await.unwrap().to_string();
a.apply_device_profile(&silent_profile, true).unwrap();
lock(&a.conn)
.execute(
"UPDATE sync_devices SET last_seen_ms = ?1 WHERE device_id = 'silent-peer'",
[now_ms() + 1_000],
)
.unwrap();
assert_eq!(
a.active_remote_devices().unwrap()[0].device_id,
"silent-peer"
);
a.claim_playback(&profile_a.device_id).unwrap();
let poller = tokio::spawn(sync_loop(a.clone(), service_a.clone(), stats_a.clone()));
for position in [99.0, 100.0] {
a.playback_tick(true, true).unwrap();
let mut next = empty_playback_state();
next.playing = true;
next.position_secs = position;
a.publish_playback(PlaybackSnapshot {
device_id: profile_a.device_id.clone(),
device_name: "TUI".into(),
active: true,
updated_at_ms: now_ms(),
state: next,
coordination: None,
});
tokio::time::timeout(Duration::from_secs(6), async {
loop {
if lock(&b.playback)
.remote
.get(&profile_a.device_id)
.is_some_and(|snapshot| snapshot.state.position_secs == position)
{
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.expect("a stalled peer must not delay live playback polls");
}
poller.abort();
let _ = poller.await;
silent.shutdown().await.unwrap();
for server in servers {
server.abort();
}
for (_, service, _, _) in &peers {
service.shutdown().await.unwrap();
}
})
.await
.expect("localhost sync must complete within 30 seconds");
}
fn empty_playback_state() -> PlaybackStateWire {
PlaybackStateWire {
queue: vec![],
queue_pos: 0,
playing: false,
paused: false,
idle_since_ms: None,
position_secs: 0.0,
volume: 80,
shuffle: false,
repeat: PlaybackRepeat::Off,
}
}
#[test]
fn coordination_ignores_legacy_commands_and_wrong_snapshot_sender() {
let sync = test_sync();
let identity = sync.ensure_identity().unwrap();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
sync.set_event_tx(tx);
let command = PlaybackCommand::SetState {
state: empty_playback_state(),
seek: false,
};
sync.apply_playback_command(&identity.device_id, &command, None, "remote", "legacy")
.unwrap();
assert!(rx.try_recv().is_err());
let mut remote = Engine::new(
"remote".into(),
PlaybackConfig::default(),
Default::default(),
0,
);
remote.transfer("remote", 0);
remote.set_output(true, true);
remote.heartbeat(1);
let snapshot = PlaybackSnapshot {
device_id: "remote".into(),
device_name: "Remote".into(),
active: true,
updated_at_ms: now_ms(),
state: empty_playback_state(),
coordination: Some(remote.announcement()),
};
sync.apply_playback_snapshot("different-sender", snapshot.clone())
.unwrap();
assert!(
sync.with_playback_engine(|engine| engine.owner().is_none())
.unwrap()
);
sync.apply_playback_snapshot("remote", snapshot).unwrap();
assert_eq!(
sync.playback_tick(true, false).unwrap().as_deref(),
Some("remote")
);
sync.publish_playback(PlaybackSnapshot {
device_id: identity.device_id,
device_name: identity.name,
active: false,
updated_at_ms: now_ms(),
state: empty_playback_state(),
coordination: None,
});
let gossip = sync
.local_playback_snapshot()
.unwrap()
.coordination
.unwrap();
assert_eq!(gossip.claim.unwrap().owner, "remote");
}
#[test]
fn checkpoint_is_not_reused_after_changing_trusted_group() {
let sync = test_sync();
sync.claim_playback("old-group-owner").unwrap();
sync.set_group_id("new-test-group").unwrap();
assert!(
sync.with_playback_engine(|engine| engine.owner().is_none())
.unwrap()
);
}
#[test]
fn queued_command_loses_its_fence_when_another_owner_wins() {
let sync = test_sync();
let identity = sync.ensure_identity().unwrap();
sync.claim_playback(&identity.device_id).unwrap();
let stamp = sync
.with_playback_engine(|engine| engine.stamp().unwrap())
.unwrap();
sync.apply_playback_command(
&identity.device_id,
&PlaybackCommand::SetState {
state: empty_playback_state(),
seek: false,
},
Some(&stamp),
&identity.device_id,
"queued",
)
.unwrap();
assert!(sync.playback_command_is_current(&identity.device_id, &stamp));
sync.claim_playback("new-owner").unwrap();
assert!(!sync.playback_command_is_current(&identity.device_id, &stamp));
}
static NEXT_TEST_DB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); static NEXT_TEST_DB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn test_sync() -> DeviceSync { fn test_sync() -> DeviceSync {
@@ -13,6 +337,7 @@ fn test_sync() -> DeviceSync {
unique unique
)); ));
let sync = DeviceSync { let sync = DeviceSync {
_identity_lock: None,
conn: Arc::new(std::sync::Mutex::new(conn)), conn: Arc::new(std::sync::Mutex::new(conn)),
library: Arc::new(Library::open(&library_path).unwrap()), library: Arc::new(Library::open(&library_path).unwrap()),
event_tx: Arc::new(std::sync::Mutex::new(None)), event_tx: Arc::new(std::sync::Mutex::new(None)),
@@ -22,6 +347,38 @@ fn test_sync() -> DeviceSync {
sync sync
} }
#[test]
fn device_identity_has_one_coordinator_across_installation_paths() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sync.sqlite3");
let first = acquire_identity_lock(&path).unwrap();
assert!(acquire_identity_lock(&path).is_err());
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"devices::tests::identity_lock_child_process",
"--nocapture",
])
.env("FURUMI_IDENTITY_LOCK_TEST_PATH", &path)
.output()
.unwrap();
assert!(
child.status.success(),
"{}",
String::from_utf8_lossy(&child.stderr)
);
drop(first);
// Reopening a leftover lock file after shutdown must succeed.
assert!(acquire_identity_lock(&path).is_ok());
}
#[test]
fn identity_lock_child_process() {
if let Some(path) = std::env::var_os("FURUMI_IDENTITY_LOCK_TEST_PATH") {
assert!(acquire_identity_lock(std::path::Path::new(&path)).is_err());
}
}
fn device_revoked(sync: &DeviceSync, device_id: &str) -> bool { fn device_revoked(sync: &DeviceSync, device_id: &str) -> bool {
let conn = lock(&sync.conn); let conn = lock(&sync.conn);
conn.query_row( conn.query_row(
@@ -212,19 +569,41 @@ fn playback_command_is_targeted_and_deduplicated() {
seek: false, seek: false,
}; };
sync.apply_playback_command("dev_other", &command, "op_other") sync.claim_playback(&identity.device_id).unwrap();
let stamp = sync
.with_playback_engine(|engine| engine.stamp().unwrap())
.unwrap(); .unwrap();
sync.apply_playback_command(
"dev_other",
&command,
Some(&stamp),
&identity.device_id,
"op_other",
)
.unwrap();
assert!(rx.try_recv().is_err()); assert!(rx.try_recv().is_err());
sync.apply_playback_command(&identity.device_id, &command, "op_1") sync.apply_playback_command(
.unwrap(); &identity.device_id,
&command,
Some(&stamp),
&identity.device_id,
"op_1",
)
.unwrap();
assert!(matches!( assert!(matches!(
rx.try_recv().unwrap(), rx.try_recv().unwrap(),
crate::app::event::AppEvent::PlaybackCommand(_) crate::app::event::AppEvent::PlaybackCommand { .. }
)); ));
sync.apply_playback_command(&identity.device_id, &command, "op_1") sync.apply_playback_command(
.unwrap(); &identity.device_id,
&command,
Some(&stamp),
&identity.device_id,
"op_1",
)
.unwrap();
assert!(rx.try_recv().is_err()); assert!(rx.try_recv().is_err());
} }
@@ -245,6 +624,7 @@ fn playback_commands_are_caught_up_only_by_their_target_while_fresh() {
}, },
seek: false, seek: false,
}; };
sync.claim_playback("dev_target").unwrap();
sync.record_playback_command("dev_target", command.clone()) sync.record_playback_command("dev_target", command.clone())
.unwrap(); .unwrap();
sync.record_playback_command("dev_other", command).unwrap(); sync.record_playback_command("dev_other", command).unwrap();
+121 -4
View File
@@ -21,8 +21,8 @@ use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::time::Duration; use std::time::{Duration, Instant};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use music_dht::similarity_dht::SimilarityDht; use music_dht::similarity_dht::SimilarityDht;
@@ -46,6 +46,11 @@ pub use similarity::SIMILARITY_ALPN;
/// How often the published library is re-synchronized with the local index. /// How often the published library is re-synchronized with the local index.
const SYNC_INTERVAL: Duration = Duration::from_secs(60); const SYNC_INTERVAL: Duration = Duration::from_secs(60);
/// How often the application checks whether the shared transport needs a
/// full restart so all application-owned protocol acceptors are recreated.
const SUPERVISOR_INTERVAL: Duration = Duration::from_secs(15);
/// Prevents repeated restarts during a prolonged external network outage.
const RECOVERY_COOLDOWN: Duration = Duration::from_secs(5 * 60);
/// How many times a share-link content lookup is retried before the label /// How many times a share-link content lookup is retried before the label
/// fallback kicks in. /// fallback kicks in.
@@ -370,6 +375,12 @@ pub struct FedStatus {
pub endpoint_id: String, pub endpoint_id: String,
pub dht_node_id: String, pub dht_node_id: String,
pub connected_peers: Vec<String>, pub connected_peers: Vec<String>,
pub network_health: String,
pub rendezvous_failures: u32,
pub peer_dial_failures: u32,
pub rendezvous_restarts: u64,
pub recovery_count: u64,
pub last_rendezvous_error: Option<String>,
pub known_contacts: usize, pub known_contacts: usize,
pub stored_dht_records: Option<usize>, pub stored_dht_records: Option<usize>,
pub stored_dht_bytes: Option<u64>, pub stored_dht_bytes: Option<u64>,
@@ -419,6 +430,10 @@ pub struct Federation {
metadata_cache: std::sync::Mutex<std::collections::HashMap<String, CachedTrackMetadata>>, metadata_cache: std::sync::Mutex<std::collections::HashMap<String, CachedTrackMetadata>>,
settings: std::sync::Mutex<FedSettings>, settings: std::sync::Mutex<FedSettings>,
running: tokio::sync::Mutex<Option<Running>>, running: tokio::sync::Mutex<Option<Running>>,
supervisor_task: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
supervisor_shutdown: tokio::sync::Notify,
shutting_down: AtomicBool,
recovery_count: AtomicU64,
last_sync: std::sync::Mutex<Option<String>>, last_sync: std::sync::Mutex<Option<String>>,
last_error: std::sync::Mutex<Option<String>>, last_error: std::sync::Mutex<Option<String>>,
transport_stats: Arc<TransportStats>, transport_stats: Arc<TransportStats>,
@@ -549,6 +564,10 @@ impl Federation {
metadata_cache: std::sync::Mutex::new(Default::default()), metadata_cache: std::sync::Mutex::new(Default::default()),
settings: std::sync::Mutex::new(load_settings()), settings: std::sync::Mutex::new(load_settings()),
running: tokio::sync::Mutex::new(None), running: tokio::sync::Mutex::new(None),
supervisor_task: std::sync::Mutex::new(None),
supervisor_shutdown: tokio::sync::Notify::new(),
shutting_down: AtomicBool::new(false),
recovery_count: AtomicU64::new(0),
last_sync: std::sync::Mutex::new(None), last_sync: std::sync::Mutex::new(None),
last_error: std::sync::Mutex::new(initial_error), last_error: std::sync::Mutex::new(initial_error),
transport_stats: Arc::new(TransportStats::default()), transport_stats: Arc::new(TransportStats::default()),
@@ -560,6 +579,18 @@ impl Federation {
lock(&self.settings).clone() lock(&self.settings).clone()
} }
/// Starts the application-level federation supervisor once.
pub fn start_supervisor(self: &Arc<Self>) {
let mut task = lock(&self.supervisor_task);
if task.is_some() || self.shutting_down.load(Ordering::SeqCst) {
return;
}
let federation = Arc::clone(self);
*task = Some(tokio::spawn(async move {
federation.supervisor_loop().await;
}));
}
pub fn media_dir(&self) -> PathBuf { pub fn media_dir(&self) -> PathBuf {
lock(&self.media_dir).clone() lock(&self.media_dir).clone()
} }
@@ -665,12 +696,43 @@ impl Federation {
network_id: NetworkId, network_id: NetworkId,
network_name: String, network_name: String,
) -> Result<()> { ) -> Result<()> {
self.start_with_network_id_mode(network_id, network_name, false)
.await
.map(|_| ())
}
async fn start_with_network_id_mode(
self: &Arc<Self>,
network_id: NetworkId,
network_name: String,
recovery_only: bool,
) -> Result<bool> {
let mut guard = self.running.lock().await; let mut guard = self.running.lock().await;
if recovery_only {
let current = self.settings();
if !current.enabled
|| current.network_id.trim() != network_name
|| NetworkId::from_name(current.network_id.trim()) != network_id
{
return Ok(false);
}
}
if let Some(running) = guard.as_ref() { if let Some(running) = guard.as_ref() {
if running.network_id == network_id { if running.network_id == network_id {
return Ok(()); if !recovery_only || !running.service.network_health().restart_recommended {
return Ok(false);
}
tracing::warn!(
network = %network_name,
health = %running.service.network_health().state,
"restarting degraded federation service"
);
} else if recovery_only {
return Ok(false);
} }
stop_running(guard.take()).await; stop_running(guard.take()).await;
} else if recovery_only {
tracing::warn!(network = %network_name, "retrying stopped federation service");
} }
std::fs::create_dir_all(&self.data_dir) std::fs::create_dir_all(&self.data_dir)
.with_context(|| format!("creating {}", self.data_dir.display()))?; .with_context(|| format!("creating {}", self.data_dir.display()))?;
@@ -828,7 +890,7 @@ impl Federation {
], ],
}); });
self.set_error(None); self.set_error(None);
Ok(()) Ok(true)
} }
async fn stop(&self) { async fn stop(&self) {
@@ -837,9 +899,57 @@ impl Federation {
} }
pub async fn shutdown(&self) { pub async fn shutdown(&self) {
self.shutting_down.store(true, Ordering::SeqCst);
self.supervisor_shutdown.notify_one();
let supervisor = lock(&self.supervisor_task).take();
if let Some(supervisor) = supervisor {
let _ = supervisor.await;
}
self.stop().await; self.stop().await;
} }
async fn supervisor_loop(self: Arc<Self>) {
let mut interval = tokio::time::interval(SUPERVISOR_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
interval.tick().await;
let mut last_attempt = None;
loop {
tokio::select! {
_ = self.supervisor_shutdown.notified() => return,
_ = interval.tick() => {}
}
if self.shutting_down.load(Ordering::SeqCst) {
return;
}
if last_attempt.is_some_and(|attempt: Instant| attempt.elapsed() < RECOVERY_COOLDOWN) {
continue;
}
match self.recover_if_needed().await {
Ok(false) => {}
Ok(true) => {
last_attempt = Some(Instant::now());
self.recovery_count.fetch_add(1, Ordering::Relaxed);
self.spawn_sync_soon().await;
}
Err(err) => {
last_attempt = Some(Instant::now());
tracing::error!(error = %err, "federation recovery failed");
self.set_error(Some(format!("network recovery failed: {err}")));
}
}
}
}
async fn recover_if_needed(self: &Arc<Self>) -> Result<bool> {
let settings = self.settings();
if !settings.enabled || settings.network_id.trim().is_empty() {
return Ok(false);
}
let network_name = settings.network_id.trim().to_string();
self.start_with_network_id_mode(NetworkId::from_name(&network_name), network_name, true)
.await
}
async fn service(&self) -> Result<Arc<MusicDhtService>> { async fn service(&self) -> Result<Arc<MusicDhtService>> {
self.running self.running
.lock() .lock()
@@ -975,6 +1085,7 @@ impl Federation {
let guard = self.running.lock().await; let guard = self.running.lock().await;
let mut status = FedStatus { let mut status = FedStatus {
network: settings.network_id, network: settings.network_id,
recovery_count: self.recovery_count.load(Ordering::Relaxed),
last_sync: lock(&self.last_sync).clone(), last_sync: lock(&self.last_sync).clone(),
last_error: lock(&self.last_error).clone(), last_error: lock(&self.last_error).clone(),
protocols: ProtocolVersions::snapshot(&self.observed_protocols), protocols: ProtocolVersions::snapshot(&self.observed_protocols),
@@ -982,6 +1093,7 @@ impl Federation {
}; };
if let Some(running) = guard.as_ref() { if let Some(running) = guard.as_ref() {
let service = &running.service; let service = &running.service;
let health = service.network_health();
status.running = true; status.running = true;
status.network = running.network_name.clone(); status.network = running.network_name.clone();
status.endpoint_id = service.endpoint_id().to_string(); status.endpoint_id = service.endpoint_id().to_string();
@@ -991,6 +1103,11 @@ impl Federation {
.iter() .iter()
.map(|p| p.to_string()) .map(|p| p.to_string())
.collect(); .collect();
status.network_health = health.state.to_string();
status.rendezvous_failures = health.consecutive_rendezvous_failures;
status.peer_dial_failures = health.consecutive_peer_dial_failures;
status.rendezvous_restarts = health.rendezvous_restarts;
status.last_rendezvous_error = health.last_rendezvous_error;
status.known_contacts = service.known_peers().len(); status.known_contacts = service.known_peers().len();
status.stored_dht_records = service.dht_record_count().await.ok(); status.stored_dht_records = service.dht_record_count().await.ok();
status.stored_dht_bytes = status.stored_dht_bytes =
+1
View File
@@ -668,6 +668,7 @@ mod tests {
repeat: crate::devices::PlaybackRepeat::Off, repeat: crate::devices::PlaybackRepeat::Off,
}; };
host.publish_host_playback(PlaybackSnapshot { host.publish_host_playback(PlaybackSnapshot {
coordination: None,
device_id: "dev_host".into(), device_id: "dev_host".into(),
device_name: "Host".into(), device_name: "Host".into(),
active: true, active: true,
+108 -16
View File
@@ -12,6 +12,7 @@ mod similarity;
mod status; mod status;
mod streaming; mod streaming;
mod ui; mod ui;
mod updater;
mod visualizer; mod visualizer;
use std::io; use std::io;
@@ -60,7 +61,9 @@ fn main() -> Result<()> {
if let Err(err) = config::logging::init() { if let Err(err) = config::logging::init() {
startup_warning = Some(format!("logging disabled: {err:#}")); startup_warning = Some(format!("logging disabled: {err:#}"));
} }
capture_stderr(); // Restore stderr before main returns: Rust prints a returned error only
// after local guards have been dropped and the terminal has been restored.
let _stderr_capture = capture_stderr();
let (keymap, keymap_warning) = config::keymap::Keymap::load(); let (keymap, keymap_warning) = config::keymap::Keymap::load();
let startup_warning = keymap_warning.or(startup_warning); let startup_warning = keymap_warning.or(startup_warning);
@@ -131,25 +134,46 @@ fn run_app(
/// every line into tracing — it lands in the Logs tab and the log file /// every line into tracing — it lands in the Logs tab and the log file
/// instead of the screen. /// instead of the screen.
#[cfg(unix)] #[cfg(unix)]
fn capture_stderr() { struct StderrCapture {
original: std::os::fd::RawFd,
}
#[cfg(unix)]
impl Drop for StderrCapture {
fn drop(&mut self) {
// SAFETY: original is our owned duplicate, kept open for this scope.
unsafe {
libc::dup2(self.original, libc::STDERR_FILENO);
libc::close(self.original);
}
}
}
#[cfg(unix)]
fn capture_stderr() -> Option<StderrCapture> {
use std::io::BufRead as _; use std::io::BufRead as _;
use std::os::fd::FromRawFd as _; use std::os::fd::FromRawFd as _;
let mut fds = [0i32; 2]; let mut fds = [0i32; 2];
// SAFETY: plain pipe/dup2 syscalls on freshly created fds. // SAFETY: plain pipe/dup2 syscalls on freshly created fds.
unsafe { unsafe {
let original = libc::dup(libc::STDERR_FILENO);
if original == -1 {
return None;
}
let capture = StderrCapture { original };
if libc::pipe(fds.as_mut_ptr()) != 0 { if libc::pipe(fds.as_mut_ptr()) != 0 {
return; return None;
} }
let [read_fd, write_fd] = fds; let [read_fd, write_fd] = fds;
if libc::dup2(write_fd, libc::STDERR_FILENO) == -1 { if libc::dup2(write_fd, libc::STDERR_FILENO) == -1 {
libc::close(read_fd); libc::close(read_fd);
libc::close(write_fd); libc::close(write_fd);
return; return None;
} }
libc::close(write_fd); libc::close(write_fd);
let reader = std::fs::File::from_raw_fd(read_fd); let reader = std::fs::File::from_raw_fd(read_fd);
std::thread::Builder::new() let reader_thread = std::thread::Builder::new()
.name("stderr".to_string()) .name("stderr".to_string())
.spawn(move || { .spawn(move || {
for line in std::io::BufReader::new(reader).lines() { for line in std::io::BufReader::new(reader).lines() {
@@ -158,33 +182,65 @@ fn capture_stderr() {
tracing::warn!(target: "stderr", "{line}"); tracing::warn!(target: "stderr", "{line}");
} }
} }
}) });
.ok(); if reader_thread.is_err() {
return None;
}
Some(capture)
} }
} }
#[cfg(windows)] #[cfg(windows)]
fn capture_stderr() { struct StderrCapture {
original: windows_sys::Win32::Foundation::HANDLE,
writer: windows_sys::Win32::Foundation::HANDLE,
}
#[cfg(windows)]
impl Drop for StderrCapture {
fn drop(&mut self) {
// SAFETY: original is borrowed from the process; writer is owned by
// this guard. Restoring the original also preserves shell redirection.
unsafe {
windows_sys::Win32::System::Console::SetStdHandle(
windows_sys::Win32::System::Console::STD_ERROR_HANDLE,
self.original,
);
windows_sys::Win32::Foundation::CloseHandle(self.writer);
}
}
}
#[cfg(windows)]
fn capture_stderr() -> Option<StderrCapture> {
use std::io::BufRead as _; use std::io::BufRead as _;
use std::os::windows::io::FromRawHandle as _; use std::os::windows::io::FromRawHandle as _;
use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Console::{STD_ERROR_HANDLE, SetStdHandle}; use windows_sys::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, SetStdHandle};
use windows_sys::Win32::System::Pipes::CreatePipe; use windows_sys::Win32::System::Pipes::CreatePipe;
unsafe { unsafe {
let original = GetStdHandle(STD_ERROR_HANDLE);
if original.is_null() || original == INVALID_HANDLE_VALUE {
return None;
}
let mut read = core::ptr::null_mut(); let mut read = core::ptr::null_mut();
let mut write = core::ptr::null_mut(); let mut write = core::ptr::null_mut();
if CreatePipe(&mut read, &mut write, core::ptr::null(), 0) == 0 { if CreatePipe(&mut read, &mut write, core::ptr::null(), 0) == 0 {
return; return None;
} }
if SetStdHandle(STD_ERROR_HANDLE, write) == 0 { if SetStdHandle(STD_ERROR_HANDLE, write) == 0 {
CloseHandle(read); CloseHandle(read);
CloseHandle(write); CloseHandle(write);
return; return None;
} }
let capture = StderrCapture {
original,
writer: write,
};
let reader = std::fs::File::from_raw_handle(read); let reader = std::fs::File::from_raw_handle(read);
std::thread::Builder::new() let reader_thread = std::thread::Builder::new()
.name("stderr".to_string()) .name("stderr".to_string())
.spawn(move || { .spawn(move || {
for line in std::io::BufReader::new(reader).lines() { for line in std::io::BufReader::new(reader).lines() {
@@ -193,13 +249,49 @@ fn capture_stderr() {
tracing::warn!(target: "stderr", "{line}"); tracing::warn!(target: "stderr", "{line}");
} }
} }
}) });
.ok(); if reader_thread.is_err() {
return None;
}
Some(capture)
} }
} }
#[cfg(not(any(unix, windows)))] #[cfg(not(any(unix, windows)))]
fn capture_stderr() {} fn capture_stderr() -> Option<()> {
None
}
#[cfg(test)]
mod stderr_tests {
#[test]
fn error_output_is_restored_after_capture() {
const CHILD: &str = "FURUMI_STDERR_CAPTURE_TEST";
if std::env::var_os(CHILD).is_some() {
{
let _capture = super::capture_stderr().expect("capture stderr");
}
eprintln!("furumi-test: visible error after terminal shutdown");
return;
}
// Run in another process: redirecting global stderr inside a parallel
// test suite would interfere with unrelated tests and panic reporting.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"stderr_tests::error_output_is_restored_after_capture",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
assert!(output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr)
.contains("furumi-test: visible error after terminal shutdown")
);
}
}
/// Kitty keyboard protocol, where supported, disambiguates Esc from alt-keys /// Kitty keyboard protocol, where supported, disambiguates Esc from alt-keys
/// and modifier combos. The flags are popped on exit and on panic — leaving /// and modifier combos. The flags are popped on exit and on panic — leaving
+31 -3
View File
@@ -90,9 +90,18 @@ impl Shared {
pub struct Controller { pub struct Controller {
tx: Sender<Command>, tx: Sender<Command>,
pub shared: Arc<Shared>, pub shared: Arc<Shared>,
playback_allowed: Arc<AtomicBool>,
} }
impl Controller { impl Controller {
/// Revoke the output at the audio thread boundary, including work queued
/// by background decoders before an ownership transfer.
pub fn set_playback_allowed(&self, allowed: bool) {
if self.playback_allowed.swap(allowed, Ordering::AcqRel) && !allowed {
self.stop();
}
}
pub fn play(&self, reader: TrackReader, byte_len: Option<u64>, volume: f32) { pub fn play(&self, reader: TrackReader, byte_len: Option<u64>, volume: f32) {
let _ = self.tx.send(Command::Play { let _ = self.tx.send(Command::Play {
reader, reader,
@@ -142,11 +151,17 @@ pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Controller {
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
let shared = Arc::new(Shared::default()); let shared = Arc::new(Shared::default());
let thread_shared = Arc::clone(&shared); let thread_shared = Arc::clone(&shared);
let playback_allowed = Arc::new(AtomicBool::new(true));
let thread_allowed = Arc::clone(&playback_allowed);
std::thread::Builder::new() std::thread::Builder::new()
.name("audio".to_string()) .name("audio".to_string())
.spawn(move || run(rx, thread_shared, on_event)) .spawn(move || run(rx, thread_shared, thread_allowed, on_event))
.expect("spawning the audio thread cannot fail"); .expect("spawning the audio thread cannot fail");
Controller { tx, shared } Controller {
tx,
shared,
playback_allowed,
}
} }
struct Output { struct Output {
@@ -155,7 +170,12 @@ struct Output {
player: Player, player: Player,
} }
fn run(rx: Receiver<Command>, shared: Arc<Shared>, on_event: impl Fn(PlayerEvent)) { fn run(
rx: Receiver<Command>,
shared: Arc<Shared>,
playback_allowed: Arc<AtomicBool>,
on_event: impl Fn(PlayerEvent),
) {
let mut output: Option<Output> = None; let mut output: Option<Output> = None;
let mut track_loaded = false; let mut track_loaded = false;
let mut last_len = 0usize; let mut last_len = 0usize;
@@ -163,6 +183,14 @@ fn run(rx: Receiver<Command>, shared: Arc<Shared>, on_event: impl Fn(PlayerEvent
loop { loop {
match rx.recv_timeout(Duration::from_millis(100)) { match rx.recv_timeout(Duration::from_millis(100)) {
Ok(command) => { Ok(command) => {
if !playback_allowed.load(Ordering::Acquire)
&& matches!(
command,
Command::Play { .. } | Command::Enqueue { .. } | Command::Resume
)
{
continue;
}
// Commands change the source queue legitimately; resync the // Commands change the source queue legitimately; resync the
// length so the next tick doesn't read it as a track ending. // length so the next tick doesn't read it as a track ending.
handle(command, &shared, &mut output, &mut track_loaded, &on_event); handle(command, &shared, &mut output, &mut track_loaded, &on_event);
+191
View File
@@ -0,0 +1,191 @@
//! Secondary settings window; child dialogs are rendered above it.
use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
text::Line,
widgets::{Block, Clear, List, ListItem, ListState, Paragraph, Wrap},
};
use super::theme;
use crate::app::state::{AppState, SettingsRow, additional_settings_rows};
pub fn draw(frame: &mut Frame, state: &AppState) {
let screen = frame.area();
let width = screen.width.saturating_sub(2).min(90);
let height = screen.height.saturating_sub(2).min(26);
let area = Rect::new(
screen.x + (screen.width - width) / 2,
screen.y + (screen.height - height) / 2,
width,
height,
);
let block = Block::bordered()
.title(" Additional settings ")
.title_style(theme::header_for(state))
.border_style(theme::strong_border_for(state));
let inner = block.inner(area);
frame.render_widget(Clear, area);
frame.render_widget(block, area);
let [list_area, status_area, footer] = Layout::vertical([
Constraint::Min(1),
Constraint::Length(3),
Constraint::Length(1),
])
.areas(inner);
let rows = additional_settings_rows(state);
let mut items = Vec::new();
let mut selected = 0;
for (index, row) in rows.iter().enumerate() {
let section = match row {
SettingsRow::MusicDirectory => Some("Library"),
SettingsRow::CheckUpdate => Some("Updates"),
SettingsRow::VisualizationClock => Some("Visualizations"),
_ => None,
};
if let Some(section) = section {
items.push(ListItem::new(Line::styled(
section,
theme::header_for(state),
)));
}
if index
== state
.additional_settings_cursor
.min(rows.len().saturating_sub(1))
{
selected = items.len();
}
let (label, value, enabled) = match row {
SettingsRow::MusicDirectory => (
"Music save directory".into(),
if state.music_dir_changing {
"checking/changing...".into()
} else {
state.music_dir.to_string_lossy().into_owned()
},
!state.music_dir_changing,
),
SettingsRow::CheckUpdate => (
"Check for updates".into(),
format!("v{}", env!("CARGO_PKG_VERSION")),
!state.updater.busy && !state.updater.installed,
),
SettingsRow::InstallUpdate => (
"Install update".into(),
state
.updater
.available
.as_ref()
.map(|u| format!("v{}", u.version))
.unwrap_or_else(|| "check for updates first".into()),
state.updater.available.is_some()
&& !state.updater.busy
&& !state.updater.installed,
),
SettingsRow::VisualizationClock => (
"Show clock".into(),
if state.visualizer.config.show_clock {
"on"
} else {
"off"
}
.into(),
true,
),
SettingsRow::VisualizationScript(index) => {
let script = &state.visualizer.scripts[*index];
let mark = if state.visualizer.selected_script_index() == Some(*index) {
"* "
} else {
""
};
(
format!("{mark}{}", script.name),
script
.path
.file_name()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default(),
true,
)
}
SettingsRow::VisualizationNew => {
("+ New visualization script".into(), "enter".into(), true)
}
SettingsRow::VisualizationEdit => {
("Edit selected visualization".into(), "enter".into(), true)
}
_ => continue,
};
let item = ListItem::new(format!("{label}: {value}"));
items.push(if enabled {
item
} else {
item.style(theme::dim())
});
}
frame.render_stateful_widget(
List::new(items)
.highlight_symbol("> ")
.highlight_style(theme::selection_for(state)),
list_area,
&mut ListState::default().with_selected(Some(selected)),
);
let message = state
.status_message
.as_deref()
.filter(|message| !message.is_empty())
.unwrap_or(&state.updater.message);
frame.render_widget(
Paragraph::new(message)
.wrap(Wrap { trim: true })
.style(theme::dim()),
status_area,
);
frame.render_widget(
Paragraph::new("Up/Down: navigate | Enter: select | Esc: back").style(theme::dim()),
footer,
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn window_renders_controls_and_scrolls_to_last_row_in_small_terminal() {
for (width, height) in [(80, 30), (45, 14)] {
let mut terminal =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height)).unwrap();
let mut state = AppState::default();
state.updater.message = "No newer stable release".into();
terminal.draw(|frame| draw(frame, &state)).unwrap();
let text: String = terminal
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(text.contains("Additional settings"));
assert!(text.contains("Music save directory"));
if height >= 30 {
assert!(text.contains("Check for updates"));
assert!(text.contains("Install update"));
assert!(text.contains("Visualizations"));
}
state.additional_settings_cursor = additional_settings_rows(&state).len() - 1;
terminal.draw(|frame| draw(frame, &state)).unwrap();
let text: String = terminal
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(text.contains("New visualization script"));
assert!(text.contains("No newer stable release"));
}
}
}
+99 -121
View File
@@ -33,7 +33,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState) {
} }
let rows_height = let rows_height =
(settings_rows(state).len() + 10 + device_presence_sections(state).len()) as u16; (settings_rows(state).len() + 6 + device_presence_sections(state).len()) as u16;
let [rows_area, _, status_area] = Layout::vertical([ let [rows_area, _, status_area] = Layout::vertical([
Constraint::Length(rows_height.min(inner.height)), Constraint::Length(rows_height.min(inner.height)),
Constraint::Length(1), Constraint::Length(1),
@@ -69,7 +69,6 @@ fn draw_settings_rows(frame: &mut Frame, area: Rect, state: &AppState) {
let mut y = area.y; let mut y = area.y;
let mut cursor = 0usize; let mut cursor = 0usize;
draw_section(frame, area, state, &mut y, "Library");
draw_row( draw_row(
frame, frame,
area, area,
@@ -77,56 +76,22 @@ fn draw_settings_rows(frame: &mut Frame, area: Rect, state: &AppState) {
&mut y, &mut y,
cursor, cursor,
state.settings_cursor, state.settings_cursor,
"Music save directory", "Additional settings",
if state.music_dir_changing { "enter".into(),
format!("{} checking/changing…", state.spinner())
} else {
state.music_dir.to_string_lossy().into_owned()
},
); );
cursor += 1; cursor += 1;
draw_row(
frame,
area,
state,
&mut y,
cursor,
state.settings_cursor,
"Full status details",
"enter".to_string(),
);
y = y.saturating_add(1); cursor += 1;
draw_section(frame, area, state, &mut y, "Similarity Search");
let similarity = &state.similarity.settings;
for row in SimilarityRow::ALL {
let (label, value) = match row {
SimilarityRow::Toggle => ("Similarity search", on_off(similarity.enabled).to_string()),
SimilarityRow::Model => (
"Embedding model",
crate::similarity::model_by_id(&similarity.model)
.map(|model| format!("{} · {}", model.id, model.license))
.unwrap_or_else(|| similarity.model.clone()),
),
SimilarityRow::Profile => (
"Preprocessing profile",
format!("{} (enter for details)", similarity.profile),
),
SimilarityRow::MinimumScore => (
"Minimum similarity",
format!("{:.2}", similarity.minimum_score),
),
SimilarityRow::MaxTracksPerArtist => (
"Tracks per artist",
similarity.max_tracks_per_artist.to_string(),
),
SimilarityRow::Workers => ("Background workers", similarity.workers.to_string()),
SimilarityRow::Clear => ("Clear all stored embeddings", "↵".to_string()),
};
draw_row(
frame,
area,
state,
&mut y,
cursor,
state.settings_cursor,
label,
value,
);
cursor += 1;
}
y = y.saturating_add(1); y = y.saturating_add(1);
draw_section(frame, area, state, &mut y, "Federation"); draw_section(frame, area, state, &mut y, "Federation");
@@ -314,39 +279,32 @@ fn draw_settings_rows(frame: &mut Frame, area: Rect, state: &AppState) {
} }
y = y.saturating_add(1); y = y.saturating_add(1);
draw_section(frame, area, state, &mut y, "Visualizations"); draw_section(frame, area, state, &mut y, "Similarity Search");
draw_row( let similarity = &state.similarity.settings;
frame, for row in SimilarityRow::ALL {
area, let (label, value) = match row {
state, SimilarityRow::Toggle => ("Similarity search", on_off(similarity.enabled).to_string()),
&mut y, SimilarityRow::Model => (
cursor, "Embedding model",
state.settings_cursor, crate::similarity::model_by_id(&similarity.model)
"Show clock", .map(|model| format!("{} · {}", model.id, model.license))
if state.visualizer.config.show_clock { .unwrap_or_else(|| similarity.model.clone()),
"[x]".to_string() ),
} else { SimilarityRow::Profile => (
"[ ]".to_string() "Preprocessing profile",
}, format!("{} (enter for details)", similarity.profile),
); ),
cursor += 1; SimilarityRow::MinimumScore => (
"Minimum similarity",
for (index, script) in state.visualizer.scripts.iter().enumerate() { format!("{:.2}", similarity.minimum_score),
let selected_script = state ),
.visualizer SimilarityRow::MaxTracksPerArtist => (
.selected_script_index() "Tracks per artist",
.is_some_and(|selected| selected == index); similarity.max_tracks_per_artist.to_string(),
let label = if selected_script { ),
format!("* {}", script.name) SimilarityRow::Workers => ("Background workers", similarity.workers.to_string()),
} else { SimilarityRow::Clear => ("Clear all stored embeddings", "↵".to_string()),
format!(" {}", script.name)
}; };
let value = script
.path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("")
.to_string();
draw_row( draw_row(
frame, frame,
area, area,
@@ -354,49 +312,11 @@ fn draw_settings_rows(frame: &mut Frame, area: Rect, state: &AppState) {
&mut y, &mut y,
cursor, cursor,
state.settings_cursor, state.settings_cursor,
&label, label,
value, value,
); );
cursor += 1; cursor += 1;
} }
draw_row(
frame,
area,
state,
&mut y,
cursor,
state.settings_cursor,
"+ New visualization script",
"↵".to_string(),
);
cursor += 1;
if state.visualizer.selected_script().is_some() {
draw_row(
frame,
area,
state,
&mut y,
cursor,
state.settings_cursor,
"Edit selected visualization",
"↵".to_string(),
);
cursor += 1;
}
y = y.saturating_add(1);
draw_row(
frame,
area,
state,
&mut y,
cursor,
state.settings_cursor,
"Full status details",
"enter".to_string(),
);
} }
fn protocol_label(id: &str) -> &str { fn protocol_label(id: &str) -> &str {
@@ -961,7 +881,10 @@ fn node_summary_lines(state: &AppState) -> Vec<Line<'static>> {
] ]
} }
Some(status) => vec![ Some(status) => vec![
summary_line("Node", format!("running on {}", status.network)), summary_line(
"Node",
format!("running on {} · {}", status.network, status.network_health),
),
summary_line( summary_line(
"Peers", "Peers",
format!( format!(
@@ -1215,6 +1138,17 @@ fn status_detail_status_lines(state: &AppState, status_cursor: usize) -> Vec<Lin
status.known_contacts status.known_contacts
), ),
)); ));
lines.push(status_line(
"Discovery",
format!(
"{} · {} DHT / {} dial failures · {} rebuilds · {} full recoveries",
status.network_health,
status.rendezvous_failures,
status.peer_dial_failures,
status.rendezvous_restarts,
status.recovery_count
),
));
if !status.connected_peers.is_empty() { if !status.connected_peers.is_empty() {
let mut peers: Vec<String> = status let mut peers: Vec<String> = status
.connected_peers .connected_peers
@@ -1260,6 +1194,9 @@ fn status_detail_status_lines(state: &AppState, status_cursor: usize) -> Vec<Lin
if let Some(error) = &status.last_error { if let Some(error) = &status.last_error {
lines.push(status_line("Error", first_line(error))); lines.push(status_line("Error", first_line(error)));
} }
if let Some(error) = &status.last_rendezvous_error {
lines.push(status_line("Discovery error", first_line(error)));
}
push_transport_summary_status(&mut lines, state, status); push_transport_summary_status(&mut lines, state, status);
} }
} }
@@ -1561,3 +1498,44 @@ fn relative_time_label(value_ms: Option<i64>, now_ms: i64) -> String {
format!("{}d ago", seconds / 60 / 60 / 24) format!("{}d ago", seconds / 60 / 60 / 24)
} }
} }
#[cfg(test)]
mod update_ui_tests {
use super::*;
#[test]
fn update_controls_and_existing_sections_render_in_both_layouts() {
for width in [80, 160] {
let mut terminal =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, 55)).unwrap();
let mut state = AppState::default();
state.updater.message = "No newer stable release".into();
terminal
.draw(|frame| draw(frame, frame.area(), &state))
.unwrap();
let text: String = terminal
.backend()
.buffer()
.content
.iter()
.map(|cell| cell.symbol())
.collect();
let mut previous = 0;
for expected in [
"Additional settings",
"Full status details",
"Federation",
"Connected Devices",
"Similarity Search",
] {
assert!(
text.contains(expected),
"missing {expected} at width {width}"
);
let position = text.find(expected).unwrap();
assert!(position >= previous, "incorrect order for {expected}");
previous = position;
}
}
}
}
+26 -8
View File
@@ -837,29 +837,47 @@ fn draw_release(frame: &mut Frame, area: Rect, state: &AppState, id: i64, cursor
let artists: Vec<&str> = detail.artists.iter().map(|a| a.name.as_str()).collect(); let artists: Vec<&str> = detail.artists.iter().map(|a| a.name.as_str()).collect();
let year = detail.year.map(|y| format!(" · {y}")).unwrap_or_default(); let year = detail.year.map(|y| format!(" · {y}")).unwrap_or_default();
let info = vec![ let tracks = crate::app::state::release_tracks(state, id, detail);
let federation_line = match state.release_fed_views.get(&id) {
Some(Loadable::Loading) => Some(super::loading_line(state, "searching peers…")),
Some(Loadable::Ready(release)) if !release.tracks.is_empty() => Some(Line::styled(
format!("federation: +{} tracks", release.tracks.len()),
theme::dim(),
)),
Some(Loadable::Ready(_)) => Some(Line::styled(
"federation: no additional tracks",
theme::dim(),
)),
Some(Loadable::Failed(_)) => Some(Line::styled("federation: unavailable", theme::dim())),
_ if state.federation.settings.enabled
&& state.global.filters.source_mode.includes_network() =>
{
Some(Line::styled("federation: pending", theme::dim()))
}
_ => None,
};
let mut info = vec![
Line::default(), Line::default(),
Line::styled(detail.title.clone(), theme::header_for(state)), Line::styled(detail.title.clone(), theme::header_for(state)),
Line::raw(artists.join(", ")), Line::raw(artists.join(", ")),
Line::default(), Line::default(),
Line::styled( Line::styled(
format!( format!("{}{year} · {} tracks", detail.release_type, tracks.len()),
"{}{year} · {} tracks",
detail.release_type,
detail.tracks.len()
),
theme::dim(), theme::dim(),
), ),
]; ];
if let Some(line) = federation_line {
info.push(line);
}
frame.render_widget(Paragraph::new(info), info_area); frame.render_widget(Paragraph::new(info), info_area);
// Track list with centered scrolling. // Track list with centered scrolling.
let visible = usize::from(tracks_area.height.max(1)); let visible = usize::from(tracks_area.height.max(1));
let total = detail.tracks.len(); let total = tracks.len();
let first = cursor let first = cursor
.saturating_sub(visible / 2) .saturating_sub(visible / 2)
.min(total.saturating_sub(visible)); .min(total.saturating_sub(visible));
for (offset, track) in detail.tracks.iter().enumerate().skip(first).take(visible) { for (offset, track) in tracks.iter().enumerate().skip(first).take(visible) {
let rect = Rect { let rect = Rect {
x: tracks_area.x, x: tracks_area.x,
y: tracks_area.y + (offset - first) as u16, y: tracks_area.y + (offset - first) as u16,
+68 -7
View File
@@ -1,9 +1,12 @@
mod additional_settings;
pub mod art; pub mod art;
mod federation; mod federation;
mod global; mod global;
mod logs; mod logs;
mod playlists; mod playlists;
mod popup; mod popup;
#[cfg(test)]
mod status_tests;
pub mod theme; pub mod theme;
use ratatui::Frame; use ratatui::Frame;
@@ -75,6 +78,10 @@ pub fn draw(frame: &mut Frame, state: &AppState, keymap: &Keymap) {
} }
draw_status(frame, status_area, state); draw_status(frame, status_area, state);
if state.additional_settings_open {
additional_settings::draw(frame, state);
}
if state.help_visible { if state.help_visible {
draw_help(frame, keymap, state); draw_help(frame, keymap, state);
} }
@@ -329,7 +336,7 @@ fn format_secs(secs: f64) -> String {
/// Playback time, progress bar, queue position, volume and mode flags. /// Playback time, progress bar, queue position, volume and mode flags.
/// Wider consoles get a longer bar and full flags; narrow ones drop pieces. /// Wider consoles get a longer bar and full flags; narrow ones drop pieces.
fn player_right_line(state: &AppState, width: u16) -> Line<'static> { fn player_right_line(state: &AppState, width: u16) -> (Line<'static>, u16) {
let player = &state.player; let player = &state.player;
let mut spans: Vec<Span<'static>> = Vec::new(); let mut spans: Vec<Span<'static>> = Vec::new();
if let Some(track) = &player.current if let Some(track) = &player.current
@@ -359,6 +366,7 @@ fn player_right_line(state: &AppState, width: u16) -> Line<'static> {
)); ));
} }
} }
let volume_offset = spans.iter().map(Span::width).sum::<usize>() + 2;
if width >= 80 { if width >= 80 {
let volume_cells = usize::from(player.volume / 10); let volume_cells = usize::from(player.volume / 10);
spans.extend([ spans.extend([
@@ -399,18 +407,69 @@ fn player_right_line(state: &AppState, width: u16) -> Line<'static> {
} }
// Keep a gap between the flags and the username block to the right. // Keep a gap between the flags and the username block to the right.
spans.push(Span::raw(" ")); spans.push(Span::raw(" "));
Line::from(spans) (
Line::from(spans),
volume_offset.min(usize::from(u16::MAX)) as u16,
)
}
/// Shared geometry for rendering and background visualization requests.
fn footer_areas(area: Rect, state: &AppState) -> [Rect; 3] {
let [player_row, message_row] =
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area);
let (line, volume_offset) = player_right_line(state, area.width);
let right_width = line.width().min(usize::from(area.width)) as u16;
let [_, right] =
Layout::horizontal([Constraint::Min(8), Constraint::Length(right_width)]).areas(player_row);
let version_width = (env!("CARGO_PKG_VERSION").len() as u16 + 1).min(message_row.width);
let version = Rect::new(
message_row.x + message_row.width.saturating_sub(version_width) / 2,
message_row.y,
version_width,
message_row.height,
);
let message = Rect::new(
message_row.x,
message_row.y,
version.x.saturating_sub(message_row.x).saturating_sub(1),
message_row.height,
);
// On wide terminals align exactly with "vol". On narrow ones keep the
// centered version readable, shrinking the histogram into the remainder.
let start = right
.x
.saturating_add(volume_offset)
.max(version.right().saturating_add(1))
.min(message_row.right());
let visual = Rect::new(
start,
message_row.y,
message_row.right().saturating_sub(start),
message_row.height,
);
[message, version, visual]
}
pub(crate) fn status_visualizer_area(screen: Rect, state: &AppState) -> Rect {
let [_, _, status] = Layout::vertical([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(2),
])
.areas(screen);
footer_areas(status, state)[2]
} }
fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) { fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
let [player_row, message_row] = let [player_row, _] =
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area); Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area);
let [message_row, version_area, visual_area] = footer_areas(area, state);
let player = &state.player; let player = &state.player;
// Layout: track title left, time/progress/flags on the right. The // Layout: track title left, time/progress/flags on the right. The
// right block is built first and gets a fixed width; the title // right block is built first and gets a fixed width; the title
// truncates into whatever is left. // truncates into whatever is left.
let center = player_right_line(state, area.width); let (center, _) = player_right_line(state, area.width);
let center_width = (center.width() as u16).min(area.width); let center_width = (center.width() as u16).min(area.width);
let [title_area, right_area] = let [title_area, right_area] =
Layout::horizontal([Constraint::Min(8), Constraint::Length(center_width)]) Layout::horizontal([Constraint::Min(8), Constraint::Length(center_width)])
@@ -439,6 +498,10 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
} }
frame.render_widget(Paragraph::new(Line::from(spans)), title_area); frame.render_widget(Paragraph::new(Line::from(spans)), title_area);
frame.render_widget(Paragraph::new(center), right_area); frame.render_widget(Paragraph::new(center), right_area);
draw_version(frame, version_area);
if crate::visualizer::status::visible(state) {
state.status_visualizer.draw(frame, visual_area);
}
if state.cmdline.active { if state.cmdline.active {
// Vim-style command line takes over the message row. // Vim-style command line takes over the message row.
@@ -448,7 +511,6 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
usize::from(message_row.width.saturating_sub(2)), usize::from(message_row.width.saturating_sub(2)),
)); ));
frame.render_widget(Paragraph::new(Line::from(spans)), message_row); frame.render_widget(Paragraph::new(Line::from(spans)), message_row);
draw_version(frame, message_row);
return; return;
} }
@@ -470,7 +532,6 @@ fn draw_status(frame: &mut Frame, area: Rect, state: &AppState) {
}, },
}; };
frame.render_widget(Paragraph::new(message), message_row); frame.render_widget(Paragraph::new(message), message_row);
draw_version(frame, message_row);
if let Some(pending) = &state.pending_keys { if let Some(pending) = &state.pending_keys {
let pending = Paragraph::new(Line::styled( let pending = Paragraph::new(Line::styled(
@@ -502,7 +563,7 @@ fn active_artist_peer_search(state: &AppState) -> Option<String> {
fn draw_version(frame: &mut Frame, area: Rect) { fn draw_version(frame: &mut Frame, area: Rect) {
let version = format!("v{}", env!("CARGO_PKG_VERSION")); let version = format!("v{}", env!("CARGO_PKG_VERSION"));
frame.render_widget( frame.render_widget(
Paragraph::new(Line::styled(version, theme::dim())).alignment(Alignment::Right), Paragraph::new(Line::styled(version, theme::dim())).alignment(Alignment::Center),
area, area,
); );
} }
+110
View File
@@ -0,0 +1,110 @@
use super::*;
use ratatui::{Terminal, backend::TestBackend};
fn playing_state() -> AppState {
let mut state = AppState::default();
state.player.current = Some(crate::library::models::TrackItem {
id: 1,
title: "Песня 界".into(),
track_number: None,
disc_number: None,
duration_seconds: 240.0,
artists: vec![],
featured_artists: vec![],
release_id: 1,
release_title: "Release".into(),
release_year: None,
cover_path: None,
file_path: "/unused/test.flac".into(),
content_id: None,
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
});
state.player.playing = true;
state.player.position_secs = 12.0;
state
}
#[test]
fn footer_centers_version_and_aligns_visualization_under_volume() {
let mut state = playing_state();
for width in [160, 200] {
for shuffle in [false, true] {
state.player.shuffle = shuffle;
let mut terminal = Terminal::new(TestBackend::new(width, 2)).unwrap();
terminal
.draw(|frame| draw_status(frame, frame.area(), &state))
.unwrap();
let buffer = terminal.backend().buffer();
let version = format!("v{}", env!("CARGO_PKG_VERSION"));
// Count display cells, not UTF-8 bytes: the title is non-ASCII.
let volume_x = (0..width)
.find(|x| {
buffer[(*x, 0)].symbol() == "v"
&& *x + 2 < width
&& buffer[(*x + 1, 0)].symbol() == "o"
&& buffer[(*x + 2, 0)].symbol() == "l"
})
.unwrap();
let areas = footer_areas(Rect::new(0, 0, width, 2), &state);
assert_eq!(areas[2].x, volume_x);
assert_eq!(areas[2].y, 1);
assert_eq!(areas[2].right(), width);
let version_x = (width - version.len() as u16) / 2;
for (offset, ch) in version.chars().enumerate() {
assert_eq!(
buffer[(version_x + offset as u16, 1)].symbol(),
ch.to_string()
);
}
assert_eq!(
status_visualizer_area(Rect::new(0, 0, width, 24), &state).x,
volume_x
);
}
}
}
#[test]
fn footer_regions_do_not_overlap_on_narrow_terminals_or_command_input() {
let mut state = playing_state();
state.status_message = Some("long status message ".repeat(20));
for width in [1, 5, 8, 20, 40, 80, 120, 200] {
let areas = footer_areas(Rect::new(0, 0, width, 2), &state);
assert!(areas[0].right() <= areas[1].x);
assert!(areas[1].right() <= areas[2].x);
assert!(areas[2].right() <= width);
for command in [false, true] {
state.cmdline.active = command;
let mut terminal = Terminal::new(TestBackend::new(width, 2)).unwrap();
terminal
.draw(|frame| draw_status(frame, frame.area(), &state))
.unwrap();
// Neither messages nor the command prompt may paint the graph.
for x in areas[2].x..areas[2].right() {
assert_eq!(terminal.backend().buffer()[(x, 1)].symbol(), " ");
}
}
}
}
#[test]
fn status_animation_requires_local_unpaused_playback() {
let mut state = playing_state();
assert!(crate::visualizer::status::playing(&state));
state.player.paused = true;
assert!(!crate::visualizer::status::playing(&state));
assert!(crate::visualizer::status::visible(&state));
state.player.paused = false;
state.player.playing = false;
assert!(!crate::visualizer::status::playing(&state));
assert!(!crate::visualizer::status::visible(&state));
state.player.playing = true;
state.device_playback.role = crate::app::state::DevicePlaybackRole::Control;
assert!(!crate::visualizer::status::playing(&state));
}
+432
View File
@@ -0,0 +1,432 @@
//! Manual portable-binary updates. All network/disk work runs off the UI thread.
use std::{
fs::File,
io::{Read, Write},
path::Path,
time::Duration,
};
use anyhow::{Context, Result, bail, ensure};
use object::Object;
use reqwest::blocking::Client;
use semver::Version;
use serde::Deserialize;
use sha2::{Digest, Sha256};
const REPOSITORY: &str = "https://api.github.com/repos/house-of-vanity/furumi_tui";
const MAX_ARCHIVE: u64 = 512 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Update {
pub version: String,
asset: Asset,
checksums: Asset,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
#[derive(Deserialize)]
struct Release {
tag_name: String,
draft: bool,
prerelease: bool,
assets: Vec<Asset>,
}
#[derive(Debug, Default)]
pub struct State {
pub busy: bool,
pub installed: bool,
pub available: Option<Update>,
pub message: String,
}
fn client() -> Result<Client> {
// Reuse the ring backend already used by federation; respect an existing provider.
let _ = rustls::crypto::ring::default_provider().install_default();
Ok(Client::builder()
.user_agent(concat!("furumi/", env!("CARGO_PKG_VERSION")))
.https_only(true)
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(300))
.build()?)
}
fn read_limited(mut reader: impl Read, limit: u64) -> Result<Vec<u8>> {
let mut data = Vec::new();
reader.by_ref().take(limit + 1).read_to_end(&mut data)?;
ensure!(data.len() as u64 <= limit, "download exceeds size limit");
Ok(data)
}
fn select_release(release: Release, current: &str, os: &str, arch: &str) -> Result<Option<Update>> {
let version = release
.tag_name
.strip_prefix('v')
.unwrap_or(&release.tag_name);
let next = Version::parse(version).context("invalid release version")?;
if release.draft
|| release.prerelease
|| !next.pre.is_empty()
|| next <= Version::parse(current)?
{
return Ok(None);
}
let platform = match os {
"linux" => "linux",
"macos" => "macos",
"windows" => "windows",
_ => bail!("self-update is unsupported on {os}"),
};
let extension = if os == "windows" { "zip" } else { "tar.gz" };
let name = format!("furumi-{platform}-{arch}-{version}.{extension}");
let find = |name: &str| -> Result<Asset> {
let matches: Vec<_> = release
.assets
.iter()
.filter(|asset| asset.name == name)
.collect();
ensure!(matches.len() == 1, "release has no unique {name} asset");
Ok(matches[0].clone())
};
Ok(Some(Update {
version: version.to_owned(),
asset: find(&name)?,
checksums: find("SHA256SUMS")?,
}))
}
pub fn check() -> Result<Option<Update>> {
let response = client()?
.get(format!("{REPOSITORY}/releases/latest"))
.timeout(Duration::from_secs(20))
.send()?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
let release = serde_json::from_slice(&read_limited(
response.error_for_status()?,
2 * 1024 * 1024,
)?)?;
select_release(
release,
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH,
)
}
fn checksum(text: &str, name: &str) -> Result<String> {
let mut found = None;
for line in text.lines() {
let Some((hash, filename)) = line.split_once(' ') else {
continue;
};
if filename.trim_start().trim_start_matches('*') != name {
continue;
}
ensure!(found.is_none(), "duplicate checksum for {name}");
ensure!(
hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()),
"invalid SHA-256 for {name}"
);
found = Some(hash.to_ascii_lowercase());
}
found.context("release does not contain a checksum for the selected archive")
}
fn extract(archive: &Path, name: &str, output: &mut File) -> Result<()> {
let binary = if cfg!(windows) {
"furumi.exe"
} else {
"furumi"
};
let root = name
.strip_suffix(".tar.gz")
.or_else(|| name.strip_suffix(".zip"))
.context("unsupported archive")?;
// Existing release archives omit the version in their inner directory.
let root = root.rsplit_once('-').context("invalid archive name")?.0;
let expected = format!("{root}/{binary}");
let mut count = 0;
if name.ends_with(".zip") {
let mut archive = zip::ZipArchive::new(File::open(archive)?)?;
for index in 0..archive.len() {
let mut entry = archive.by_index(index)?;
if entry.name() != expected {
continue;
}
ensure!(
entry.is_file() && !entry.is_symlink(),
"binary is not a regular file"
);
count += 1;
ensure!(count == 1, "duplicate binary in archive");
output.write_all(&read_limited(&mut entry, MAX_ARCHIVE)?)?;
}
} else {
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(File::open(archive)?));
for entry in archive.entries()? {
let mut entry = entry?;
if entry.path()?.as_ref() != Path::new(&expected) {
continue;
}
ensure!(
entry.header().entry_type().is_file(),
"binary is not a regular file"
);
count += 1;
ensure!(count == 1, "duplicate binary in archive");
output.write_all(&read_limited(&mut entry, MAX_ARCHIVE)?)?;
}
}
ensure!(count == 1, "archive does not contain {expected}");
output.sync_all()?;
Ok(())
}
fn validate_binary(current: &[u8], candidate: &[u8]) -> Result<()> {
let current = object::File::parse(current).context("cannot inspect installed binary")?;
let candidate = object::File::parse(candidate).context("invalid downloaded binary")?;
ensure!(
candidate.kind() == object::ObjectKind::Executable
|| candidate.kind() == object::ObjectKind::Dynamic,
"download is not an executable"
);
ensure!(
candidate.format() == current.format()
&& candidate.architecture() == current.architecture()
&& candidate.is_64() == current.is_64()
&& candidate.is_little_endian() == current.is_little_endian(),
"downloaded binary has incompatible platform or architecture"
);
Ok(())
}
pub fn install(update: &Update, mut progress: impl FnMut(String)) -> Result<()> {
let exe = std::env::current_exe()?.canonicalize()?;
let parent = exe.parent().context("executable has no parent directory")?;
let lock = File::options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(parent.join(".furumi-update.lock"))
.context("cannot write to installation directory")?;
fs2::FileExt::try_lock_exclusive(&lock).context("another furumi instance is updating")?;
// Keep staging on the destination filesystem and never overwrite a running image.
let staging = tempfile::Builder::new()
.prefix(".furumi-update-")
.tempdir_in(parent)
.context("cannot create update staging directory")?;
let client = client()?;
let sums = read_limited(
client
.get(&update.checksums.browser_download_url)
.send()?
.error_for_status()?,
1024 * 1024,
)?;
let expected = checksum(std::str::from_utf8(&sums)?, &update.asset.name)?;
let mut response = client
.get(&update.asset.browser_download_url)
.send()?
.error_for_status()?;
let total = response.content_length();
ensure!(
total.is_none_or(|size| size <= MAX_ARCHIVE),
"archive exceeds size limit"
);
let archive = staging.path().join("download");
let mut file = File::create(&archive)?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
let mut downloaded = 0u64;
let mut reported = u64::MAX;
loop {
let count = response.read(&mut buffer)?;
if count == 0 {
break;
}
downloaded += count as u64;
ensure!(downloaded <= MAX_ARCHIVE, "archive exceeds size limit");
file.write_all(&buffer[..count])?;
hash.update(&buffer[..count]);
let mb = downloaded / (1024 * 1024);
if mb != reported {
progress(format!("Downloading: {mb} MiB"));
reported = mb;
}
}
file.sync_all()?;
drop(file);
ensure!(
format!("{:x}", hash.finalize()) == expected,
"SHA-256 mismatch; update was not installed"
);
progress("Verifying binary...".into());
let binary = staging.path().join(if cfg!(windows) {
"furumi.exe"
} else {
"furumi"
});
let mut output = File::create(&binary)?;
extract(&archive, &update.asset.name, &mut output)?;
drop(output);
validate_binary(&std::fs::read(&exe)?, &std::fs::read(&binary)?)?;
std::fs::set_permissions(&binary, std::fs::metadata(&exe)?.permissions())?;
progress("Installing...".into());
self_replace::self_replace(&binary).context("could not replace executable")?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn https_client_can_be_constructed() {
client().unwrap();
}
#[test]
fn extracts_only_expected_binary_from_release_archives() {
let temp = tempfile::tempdir().unwrap();
let binary = if cfg!(windows) {
"furumi.exe"
} else {
"furumi"
};
let expected = format!("furumi-windows-x86_64/{binary}");
let payload = b"test executable";
let zip_path = temp.path().join("test.zip");
let mut zip = zip::ZipWriter::new(File::create(&zip_path).unwrap());
zip.start_file("README.md", zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(b"readme").unwrap();
zip.start_file(&expected, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(payload).unwrap();
zip.finish().unwrap();
let output = temp.path().join("output");
extract(
&zip_path,
"furumi-windows-x86_64-0.1.6.zip",
&mut File::create(&output).unwrap(),
)
.unwrap();
assert_eq!(std::fs::read(&output).unwrap(), payload);
assert!(
extract(
&zip_path,
"furumi-linux-x86_64-0.1.6.zip",
&mut File::create(&output).unwrap()
)
.is_err()
);
let tar_path = temp.path().join("test.tar.gz");
let gzip = flate2::write::GzEncoder::new(
File::create(&tar_path).unwrap(),
flate2::Compression::default(),
);
let mut tar = tar::Builder::new(gzip);
let mut header = tar::Header::new_gnu();
header.set_size(payload.len() as u64);
header.set_mode(0o755);
header.set_cksum();
tar.append_data(&mut header, &expected, payload.as_slice())
.unwrap();
tar.into_inner().unwrap().finish().unwrap();
extract(
&tar_path,
"furumi-windows-x86_64-0.1.6.tar.gz",
&mut File::create(&output).unwrap(),
)
.unwrap();
assert_eq!(std::fs::read(&output).unwrap(), payload);
}
#[test]
fn binary_validation_rejects_wrong_architecture() {
let current = std::fs::read(std::env::current_exe().unwrap()).unwrap();
let mut other = current.clone();
// Change only the machine field, preserving an otherwise valid executable.
if current.starts_with(b"MZ") {
let pe = u32::from_le_bytes(current[0x3c..0x40].try_into().unwrap()) as usize;
let machine: u16 = if current[pe + 4..pe + 6] == [0x64, 0x86] {
0xaa64
} else {
0x8664
};
other[pe + 4..pe + 6].copy_from_slice(&machine.to_le_bytes());
} else if current.starts_with(b"\x7fELF") {
let machine: u16 = if current[18..20] == [62, 0] { 183 } else { 62 };
other[18..20].copy_from_slice(&machine.to_le_bytes());
} else if current.starts_with(&[0xcf, 0xfa, 0xed, 0xfe]) {
let cpu: u32 = if current[4] == 7 {
0x0100000c
} else {
0x01000007
};
other[4..8].copy_from_slice(&cpu.to_le_bytes());
} else {
panic!("unsupported test executable format");
}
assert!(validate_binary(&current, &other).is_err());
}
#[test]
fn checksums_require_exact_unique_valid_entry() {
let hash = "ab".repeat(32);
assert_eq!(
checksum(&format!("{hash} app.zip\n"), "app.zip").unwrap(),
hash
);
assert!(checksum(&format!("{hash} other.zip"), "app.zip").is_err());
assert!(checksum("broken app.zip", "app.zip").is_err());
assert!(checksum(&format!("{hash} app.zip\n{hash} app.zip"), "app.zip").is_err());
}
#[test]
fn release_selection_respects_semver_and_assets() {
let release = |version: &str| Release {
tag_name: version.into(),
draft: false,
prerelease: false,
assets: vec![
Asset {
name: "furumi-linux-x86_64-0.1.10.tar.gz".into(),
browser_download_url: String::new(),
},
Asset {
name: "SHA256SUMS".into(),
browser_download_url: String::new(),
},
],
};
assert!(
select_release(release("v0.1.10"), "0.1.9", "linux", "x86_64")
.unwrap()
.is_some()
);
assert!(
select_release(release("v0.1.8"), "0.1.9", "linux", "x86_64")
.unwrap()
.is_none()
);
assert!(
select_release(release("v0.2.0-beta.1"), "0.1.9", "linux", "x86_64")
.unwrap()
.is_none()
);
assert!(select_release(release("v0.1.10"), "0.1.9", "linux", "aarch64").is_err());
}
#[test]
fn binary_validation_rejects_corrupt_download() {
let current = std::fs::read(std::env::current_exe().unwrap()).unwrap();
validate_binary(&current, &current).unwrap();
assert!(validate_binary(&current, b"not a binary").is_err());
}
}
+279
View File
@@ -0,0 +1,279 @@
// name: Morphing cube
// protocol: furumi-visualizer-v2
// bundle-version: 6
//
// Audio-reactive neon wireframe, echo contours, core, shock rings, sparks
// and a bounded particle field. No native 3D API or retained state required.
// Echoes sample earlier rotation times with CURRENT audio; they are analytic
// trails, not stored frames. Particle lifetimes use time, rings also expand
// as the smoothed beat envelope decays. No beat history is available in v2.
//
// Fixed budgets: 8 mesh vertices, at most 48 particles + 24 short tails,
// 20 background stars, 3 rings, 2 echoes. Edges/rings use bulk trace commands.
// Smaller terminals omit echoes/rings and reduce particle counts.
fn clamp(v, lo, hi) {
if v < lo { lo } else if v > hi { hi } else { v }
}
fn min(a, b) { if a < b { a } else { b } }
fn rgb(r, g, b) {
to_int(clamp(r, 0.0, 255.0)) * 65536
+ to_int(clamp(g, 0.0, 255.0)) * 256
+ to_int(clamp(b, 0.0, 255.0))
}
// trace runs left-to-right. Swap endpoints for reversed edges and use
// vline for vertical ones (including an edge projected to a single cell).
fn edge(ax, ay, bx, by, fg, bg) {
if ax > bx {
let tx = ax; ax = bx; bx = tx;
let ty = ay; ay = by; by = ty;
}
if ax == bx {
return #{ op: "vline", x: ax, y: min(ay, by),
h: abs(to_float(by - ay)).to_int() + 1, ch: "|", fg: fg, bg: bg };
}
let dx = bx - ax;
let dy = by - ay;
let ch = if abs(to_float(dy)) * 3.0 < to_float(dx) { "-" }
else if abs(to_float(dy)) > to_float(dx) { "|" }
else if dy < 0 { "/" } else { "\\" };
let ys = [];
let slope = to_float(dy) / to_float(dx);
for x in 0..=dx {
ys.push(to_int(to_float(ay) + to_float(x) * slope + 0.5));
}
#{ op: "trace", x: ax, ys: ys, ch: ch, line_ch: ch,
fg: fg, line_fg: fg, bg: bg }
}
// Lift quieter passages without a hard gain/clipping threshold.
fn response(level) { 1.0 - pow(1.0 - clamp(level, 0.0, 1.0), 1.6) }
fn palette(t, heat, light) {
rgb((95.0 + 125.0 * heat + 35.0 * sin(t * 0.43)) * light,
(185.0 - 95.0 * heat + 55.0 * sin(t * 0.31 + 1.3)) * light,
255.0 * light)
}
// A single projected mesh, fitted uniformly: never clamp individual corners.
fn mesh(t, energy, bass, mid, treble, beat, width, height) {
let pulse = 0.70 + energy * 0.45 + beat * 0.85;
let sx = pulse * (1.0 + bass * 0.55);
let sy = pulse * (1.0 - bass * 0.42 + mid * 0.15);
let sz = pulse * (1.0 + treble * 0.22);
// A bounded beat kick, not time * instantaneous_energy (which jumps).
let ax = t * 0.47 + 0.35 + beat * 0.22 * sin(t * 1.3);
let ay = t * 0.63 + 0.55;
let az = t * 0.23 + beat * 0.16 * cos(t * 0.7);
let cx = cos(ax); let snx = sin(ax);
let cy = cos(ay); let sny = sin(ay);
let cz = cos(az); let snz = sin(az);
let twist = mid * 0.95 * sin(t * 0.83);
let ct = cos(twist); let st = sin(twist);
let vertices = [
[-1.0, -1.0, -1.0], [1.0, -1.0, -1.0],
[1.0, 1.0, -1.0], [-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0], [1.0, -1.0, 1.0],
[1.0, 1.0, 1.0], [-1.0, 1.0, 1.0]
];
let projected = [];
let extent = 0.01;
for i in 0..8 {
let v = vertices[i];
let pull = 1.0 + treble * 0.38 * sin(t * 2.3 + to_float(i) * 2.4)
+ beat * 0.14 * cos(to_float(i) * 1.7 + t);
let x = v[0] * sx * pull;
let y = v[1] * sy * pull;
let z = v[2] * sz * pull;
let xt = x * ct + z * st * v[1];
let zt = z * ct - x * st * v[1];
let y1 = y * cx - zt * snx;
let z1 = y * snx + zt * cx;
let x2 = xt * cy + z1 * sny;
let z2 = z1 * cy - xt * sny;
let x3 = x2 * cz - y1 * snz;
let y3 = x2 * snz + y1 * cz;
// Even the largest deformed vertex stays < 6.4 from the origin.
let perspective = 10.0 / (10.0 + z2);
let px = x3 * perspective;
let py = y3 * perspective;
if abs(px) > extent { extent = abs(px); }
if abs(py) > extent { extent = abs(py); }
projected.push([px, py, z2]);
}
// CELL_ASPECT is cell height / width; adjust for a different font.
let CELL_ASPECT = 2.0;
let span = min(to_float(width - 4) / CELL_ASPECT, to_float(height - 4));
let scale = span * min(0.23, 0.46 / extent);
let center_x = to_float(width - 1) * 0.5;
let center_y = to_float(height - 1) * 0.5;
let points = [];
for p in projected {
points.push([to_int(center_x + p[0] * scale * CELL_ASPECT + 0.5),
to_int(center_y + p[1] * scale + 0.5), p[2]]);
}
points
}
// Method calls mutate the command array in place; don't copy it into helpers.
fn dot(x, y, ch, fg, bg, width, height) {
let px = to_int(x + 0.5); let py = to_int(y + 0.5);
if x >= 0.0 && y >= 1.0 && px < width && py < height - 1 {
this.push(#{ op: "cell", x: px, y: py, ch: ch, fg: fg, bg: bg });
}
}
fn render(input) {
let bg = 0x020610;
let cmds = [#{ op: "clear", bg: bg }];
if input.width < 12 || input.height < 8 { return cmds; }
let w = input.width; let h = input.height;
let t = input.time;
let energy = response(input.energy);
let bass = response(input.bass);
let mid = response(input.mid);
let treble = response(input.treble);
let beat = response(input.beat);
let drive = clamp(energy * 0.4 + treble * 0.3 + beat * 0.8, 0.0, 1.0);
let small = w < 40 || h < 16;
let center_x = to_float(w - 1) * 0.5;
let center_y = to_float(h - 1) * 0.5;
let span = min(to_float(w - 4) * 0.5, to_float(h - 4));
let points = mesh(t, energy, bass, mid, treble, beat, w, h);
let edges = [[0,1], [1,2], [2,3], [3,0], [4,5], [5,6],
[6,7], [7,4], [0,4], [1,5], [2,6], [3,7]];
// Sparse drifting starfield; deterministic, independent of audio hardware.
let stars = if small { 8 } else { 20 };
for i in 0..stars {
let phase = to_float(i);
let x = (phase * 37.71 + t * (0.3 + to_float(i % 3) * 0.2)) % to_float(w - 1);
let y = 1.0 + (phase * 13.37) % to_float(h - 3);
let light = 0.12 + treble * 0.16 * (0.5 + 0.5 * sin(t * 2.0 + phase));
cmds.dot(x, y, ".", palette(t, 0.0, light), bg, w, h);
}
// Three elliptical shock fronts. On a transient they brighten and
// spread; release of the beat envelope carries them farther outward.
if !small && drive > 0.04 {
for ring in 0..3 {
let phase = (t * 0.45 + to_float(ring) / 3.0) % 1.0;
let radius = 0.22 + phase * 0.55 + (1.0 - beat) * 0.18;
let rx = span * radius;
let ry = span * radius * (0.22 + mid * 0.10);
let left = to_int(center_x - rx);
let right = to_int(center_x + rx);
let top = []; let bottom = [];
for x in left..=right {
let nx = clamp((to_float(x) - center_x) / rx, -1.0, 1.0);
let dy = sqrt(1.0 - nx * nx) * ry;
top.push(to_int(center_y - dy + 0.5));
bottom.push(to_int(center_y + dy + 0.5));
}
let fg = palette(t + to_float(ring), beat, (1.0 - phase) * (0.12 + beat * 0.45 + bass * 0.12));
for ys in [top, bottom] {
cmds.push(#{ op: "trace", x: left, ys: ys, ch: ".", line_ch: ".",
fg: fg, line_fg: fg, bg: bg });
}
}
}
// Particles launch from the eight corners with staggered lifetimes.
// Speed/age depend on time; audio changes reach and brightness instead
// of rescaling time and teleporting particles on each audio update.
if drive > 0.04 {
let particles = if small { 16 } else { 48 };
for i in 0..particles {
let fi = to_float(i);
let age = (t * (0.27 + to_float(i % 5) * 0.025) + fi * 0.618034) % 1.0;
let angle = fi * 2.39996 + t * 0.16;
let dx = cos(angle); let dy = sin(angle);
let origin = points[i % 8];
let travel = span * (0.35 + energy * 0.55 + beat * 0.8);
let distance = age * travel;
let light = sin(age * 3.14159) * (0.15 + drive * 0.85);
let fg = palette(t + fi * 0.13, beat, light);
let ch = if beat > 0.45 && i % 3 == 0 { "*" } else if treble > 0.35 { "+" } else { "." };
if !small && i % 2 == 0 {
let tail = distance - span * 0.04;
cmds.dot(to_float(origin[0]) + dx * tail * 2.0,
to_float(origin[1]) + dy * tail, ".", palette(t, beat, light * 0.3), bg, w, h);
}
cmds.dot(to_float(origin[0]) + dx * distance * 2.0,
to_float(origin[1]) + dy * distance, ch, fg, bg, w, h);
}
}
// Analytic motion echoes. These are recomputed poses, not frame history.
if !small && drive > 0.04 {
for echo in [2, 1] {
let lag = to_float(echo) * (0.14 + beat * 0.10);
let ghost = mesh(t - lag, energy, bass, mid, treble, beat, w, h);
let fg = palette(t + to_float(echo), 1.0 - beat, (0.08 + drive * 0.16) / to_float(echo));
for e in edges {
let a = ghost[e[0]]; let b = ghost[e[1]];
cmds.push(edge(a[0], a[1], b[0], b[1], fg, bg));
}
}
}
// A warm inner cage gives depth and a second pulse inside the main mesh.
if !small {
let inner = [];
let size = 0.35 + beat * 0.25;
for p in points {
inner.push([to_int(center_x + (to_float(p[0]) - center_x) * size + 0.5),
to_int(center_y + (to_float(p[1]) - center_y) * size + 0.5)]);
}
let fg = rgb(100.0 + beat * 155.0, 45.0 + energy * 75.0, 65.0 + treble * 70.0);
for e in edges {
let a = inner[e[0]]; let b = inner[e[1]];
cmds.push(edge(a[0], a[1], b[0], b[1], fg, bg));
}
}
let ordered = [];
for e in edges {
let depth = (points[e[0]][2] + points[e[1]][2]) * 0.5;
let at = 0;
while at < ordered.len() && ordered[at][2] > depth { at += 1; }
ordered.insert(at, [e[0], e[1], depth]);
}
for e in ordered {
let a = points[e[0]]; let b = points[e[1]];
let light = clamp(0.78 - e[2] * 0.14 + beat * 0.12, 0.3, 1.0);
cmds.push(edge(a[0], a[1], b[0], b[1], palette(t, beat, light), bg));
}
// Sparks travel along edges; no more than twelve extra cells.
if treble > 0.08 || beat > 0.08 {
for i in 0..12 {
let e = edges[i]; let a = points[e[0]]; let b = points[e[1]];
let phase = (t * 0.8 + to_float(i) * 0.137) % 1.0;
cmds.dot(to_float(a[0]) + to_float(b[0] - a[0]) * phase,
to_float(a[1]) + to_float(b[1] - a[1]) * phase,
"*", 0xffe8c0, bg, w, h);
}
}
for p in points {
if !small && beat > 0.45 {
let glow = palette(t, beat, beat * 0.45);
for offset in [[-1,0], [1,0], [0,-1], [0,1]] {
cmds.dot(to_float(p[0] + offset[0]), to_float(p[1] + offset[1]), "+", glow, bg, w, h);
}
}
cmds.push(#{ op: "cell", x: p[0], y: p[1], ch: "o", fg: 0xe8f6ff, bg: bg });
}
if input.show_clock {
cmds.push(#{ op: "text", x: 1, y: 0, text: input.clock, fg: 0xa6cde0, bg: bg });
}
if input.paused {
cmds.push(#{ op: "text", x: w - 7, y: 0, text: "paused", fg: 0xa6cde0, bg: bg });
}
if w >= 16 {
cmds.push(#{ op: "text", x: 1, y: h - 1, text: "MORPHING CUBE", fg: 0x527b98, bg: bg });
}
cmds
}
+57
View File
@@ -0,0 +1,57 @@
// name: Status braille histogram
// protocol: furumi-visualizer-v2
// surface: status
// revision: 2
//
// One-row waveform histogram. Input is decoded audio BEFORE output volume.
// The host freezes the last frame on pause, including custom scripts.
// Edit this file to customize it; only untouched bundled defaults upgrade.
// Each Braille character packs two independent four-dot vertical columns.
// "default" background retains the terminal's background color.
fn clamp(value, low, high) {
if value < low { low } else if value > high { high } else { value }
}
// Local RMS for one slice of the recent waveform. Method syntax avoids
// copying the complete sample array for every column.
fn level(index, columns, reference) {
let count = this.len();
if count == 0 { return 0; }
let start = index * count / columns;
let end = (index + 1) * count / columns;
let square = 0.0;
let total = 0;
for i in start..end {
square += this[i] * this[i];
total += 1;
}
let rms = if total > 0 { sqrt(square / to_float(total)) }
else { abs(this[start]) };
// Remove the near-silent baseline and spread useful levels over 0..4.
// No additive bass/energy/beat floor: quiet columns really become empty.
let normalized = clamp((rms / reference - 0.12) / 0.72, 0.0, 1.0);
to_int(normalized * 4.0 + 0.5)
}
fn render(input) {
let commands = [#{ op: "clear", bg: "default" }];
if input.width <= 0 || input.height <= 0 { return commands; }
let samples = input.samples;
let square = 0.0;
for sample in samples { square += sample * sample; }
let rms = if samples.len() > 0 { sqrt(square / to_float(samples.len())) } else { 0.0 };
// Adapt headroom to the current recording, with an absolute noise floor
// so silence/very quiet passages are never normalized into a full row.
let reference = if rms * 1.8 > 0.10 { rms * 1.8 } else { 0.10 };
let dots = ["⠀⢀⢠⢰⢸", "⡀⣀⣠⣰⣸", "⡄⣄⣤⣴⣼", "⡆⣆⣦⣶⣾", "⡇⣇⣧⣷⣿"];
let columns = input.width * 2;
for x in 0..input.width {
let left = samples.level(x * 2, columns, reference);
let right = samples.level(x * 2 + 1, columns, reference);
let glyph = dots[left].sub_string(right, 1);
commands.push(#{ op: "cell", x: x, y: 0, ch: glyph,
fg: 0x48c9c0, bg: "default" });
}
commands
}
+353 -32
View File
@@ -1,4 +1,4 @@
//! Script-backed fullscreen visualizers. //! Script-backed fullscreen and status-bar visualizers.
//! //!
//! Rust owns the audio tap, script loading, sandboxed execution limits and //! Rust owns the audio tap, script loading, sandboxed execution limits and
//! terminal drawing primitives. Visual math lives in `.rhai` files: every //! terminal drawing primitives. Visual math lives in `.rhai` files: every
@@ -11,6 +11,9 @@ use std::time::{Instant, SystemTime};
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use ratatui::Frame; use ratatui::Frame;
use ratatui::buffer::Buffer;
pub mod status;
use ratatui::layout::Rect; use ratatui::layout::Rect;
use ratatui::style::{Color, Style}; use ratatui::style::{Color, Style};
use ratatui::widgets::{Clear, Paragraph}; use ratatui::widgets::{Clear, Paragraph};
@@ -20,12 +23,12 @@ use serde::{Deserialize, Serialize};
use crate::app::state::AppState; use crate::app::state::AppState;
const PRIMARY_SCRIPT_ID: &str = "scope_spectrum"; const PRIMARY_SCRIPT_ID: &str = "scope_spectrum";
const BUNDLE_VERSION: u32 = 5;
struct BundledScript { struct BundledScript {
id: &'static str, id: &'static str,
file_name: &'static str, file_name: &'static str,
display_name: &'static str, display_name: &'static str,
version: u32,
source: &'static str, source: &'static str,
} }
@@ -34,14 +37,23 @@ const BUNDLED_SCRIPTS: &[BundledScript] = &[
id: PRIMARY_SCRIPT_ID, id: PRIMARY_SCRIPT_ID,
file_name: "scope_spectrum.rhai", file_name: "scope_spectrum.rhai",
display_name: "Scope spectrum", display_name: "Scope spectrum",
version: 5,
source: include_str!("visualizations/scope_spectrum.rhai"), source: include_str!("visualizations/scope_spectrum.rhai"),
}, },
BundledScript { BundledScript {
id: "pulsing_sphere", id: "pulsing_sphere",
file_name: "pulsing_sphere.rhai", file_name: "pulsing_sphere.rhai",
display_name: "Pulsing sphere", display_name: "Pulsing sphere",
version: 5,
source: include_str!("visualizations/pulsing_sphere.rhai"), source: include_str!("visualizations/pulsing_sphere.rhai"),
}, },
BundledScript {
id: "morphing_cube",
file_name: "morphing_cube.rhai",
display_name: "Morphing cube",
version: 6,
source: include_str!("visualizations/morphing_cube.rhai"),
},
]; ];
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -114,6 +126,9 @@ impl VisualizerState {
} }
pub fn load_library(&mut self) -> Result<()> { pub fn load_library(&mut self) -> Result<()> {
if let Err(err) = status::ensure_script() {
tracing::warn!(%err, "status visualization initialization failed");
}
ensure_bundled_scripts()?; ensure_bundled_scripts()?;
self.config = load_config().unwrap_or_else(|err| { self.config = load_config().unwrap_or_else(|err| {
tracing::warn!(%err, "visualization settings failed to load; using defaults"); tracing::warn!(%err, "visualization settings failed to load; using defaults");
@@ -284,7 +299,10 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
} }
fn input_map(area: Rect, state: &AppState) -> Map { fn input_map(area: Rect, state: &AppState) -> Map {
let features = features_from_state(state); input_map_with_features(area, state, features_from_state(state, true))
}
fn input_map_with_features(area: Rect, state: &AppState, features: AudioFeatures) -> Map {
let mut input = Map::new(); let mut input = Map::new();
insert_int(&mut input, "width", i64::from(area.width)); insert_int(&mut input, "width", i64::from(area.width));
insert_int(&mut input, "height", i64::from(area.height)); insert_int(&mut input, "height", i64::from(area.height));
@@ -329,7 +347,7 @@ fn input_map(area: Rect, state: &AppState) -> Map {
input input
} }
fn features_from_state(state: &AppState) -> AudioFeatures { fn features_from_state(state: &AppState, scale_output: bool) -> AudioFeatures {
let elapsed_secs = state let elapsed_secs = state
.visualizer .visualizer
.started_at .started_at
@@ -355,12 +373,18 @@ fn features_from_state(state: &AppState) -> AudioFeatures {
.unwrap_or(0.17); .unwrap_or(0.17);
let analysis = &state.player.audio_analysis; let analysis = &state.player.audio_analysis;
let volume = f64::from(state.player.volume.min(100)) / 100.0; let volume = f64::from(state.player.volume.min(100)) / 100.0;
let output_scale = if state.player.volume == 0 { let output_scale = if !scale_output {
1.0
} else if state.player.volume == 0 {
0.0 0.0
} else { } else {
0.35 + volume * 0.65 0.35 + volume * 0.65
}; };
let active_scale = if state.player.paused { 0.12 } else { 1.0 }; let active_scale = if scale_output && state.player.paused {
0.12
} else {
1.0
};
let scale = output_scale * active_scale; let scale = output_scale * active_scale;
AudioFeatures { AudioFeatures {
@@ -373,7 +397,7 @@ fn features_from_state(state: &AppState) -> AudioFeatures {
bass: (analysis.bass * scale).clamp(0.0, 1.0), bass: (analysis.bass * scale).clamp(0.0, 1.0),
mid: (analysis.mid * scale).clamp(0.0, 1.0), mid: (analysis.mid * scale).clamp(0.0, 1.0),
treble: (analysis.treble * scale).clamp(0.0, 1.0), treble: (analysis.treble * scale).clamp(0.0, 1.0),
beat: if state.player.paused { beat: if scale_output && state.player.paused {
0.0 0.0
} else { } else {
(analysis.beat * output_scale).clamp(0.0, 1.0) (analysis.beat * output_scale).clamp(0.0, 1.0)
@@ -423,6 +447,10 @@ impl Default for ScriptRuntime {
.set_max_string_size(1_000_000) .set_max_string_size(1_000_000)
.set_max_array_size(120_000) .set_max_array_size(120_000)
.set_max_map_size(1_000_000); .set_max_map_size(1_000_000);
engine.on_print(|message| tracing::debug!(message, "visualizer script"));
engine.on_debug(|message, source, position| {
tracing::debug!(message, ?source, ?position, "visualizer script")
});
engine.disable_symbol("import"); engine.disable_symbol("import");
engine.disable_symbol("export"); engine.disable_symbol("export");
engine.register_fn("sin", |value: FLOAT| value.sin()); engine.register_fn("sin", |value: FLOAT| value.sin());
@@ -606,11 +634,15 @@ impl DrawCommand {
} }
fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) { fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
render_commands_to_buffer(frame.buffer_mut(), area, commands);
}
fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCommand]) {
for command in commands { for command in commands {
match command { match command {
DrawCommand::Clear { bg } => fill_rect(frame, area, " ", Style::new().bg(*bg)), DrawCommand::Clear { bg } => fill_rect(buffer, area, " ", Style::new().bg(*bg)),
DrawCommand::Cell { x, y, ch, fg, bg } => { DrawCommand::Cell { x, y, ch, fg, bg } => {
write_cell(frame, area, *x, *y, ch, Style::new().fg(*fg).bg(*bg)); write_cell(buffer, area, *x, *y, ch, Style::new().fg(*fg).bg(*bg));
} }
DrawCommand::HLine { DrawCommand::HLine {
x, x,
@@ -621,8 +653,8 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
bg, bg,
} => { } => {
let style = Style::new().fg(*fg).bg(*bg); let style = Style::new().fg(*fg).bg(*bg);
for offset in 0..*w { for offset in 0..(*w).min(area.width.saturating_sub(*x)) {
write_cell(frame, area, x.saturating_add(offset), *y, ch, style); write_cell(buffer, area, x.saturating_add(offset), *y, ch, style);
} }
} }
DrawCommand::VLine { DrawCommand::VLine {
@@ -634,8 +666,8 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
bg, bg,
} => { } => {
let style = Style::new().fg(*fg).bg(*bg); let style = Style::new().fg(*fg).bg(*bg);
for offset in 0..*h { for offset in 0..(*h).min(area.height.saturating_sub(*y)) {
write_cell(frame, area, *x, y.saturating_add(offset), ch, style); write_cell(buffer, area, *x, y.saturating_add(offset), ch, style);
} }
} }
DrawCommand::Rect { DrawCommand::Rect {
@@ -648,10 +680,10 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
bg, bg,
} => { } => {
let style = Style::new().fg(*fg).bg(*bg); let style = Style::new().fg(*fg).bg(*bg);
for row in 0..*h { for row in 0..(*h).min(area.height.saturating_sub(*y)) {
for col in 0..*w { for col in 0..(*w).min(area.width.saturating_sub(*x)) {
write_cell( write_cell(
frame, buffer,
area, area,
x.saturating_add(col), x.saturating_add(col),
y.saturating_add(row), y.saturating_add(row),
@@ -673,7 +705,12 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
let line_style = Style::new().fg(*line_fg).bg(*bg); let line_style = Style::new().fg(*line_fg).bg(*bg);
let point_style = Style::new().fg(*fg).bg(*bg); let point_style = Style::new().fg(*fg).bg(*bg);
let mut previous_y: Option<u16> = None; let mut previous_y: Option<u16> = None;
for (index, y) in ys.iter().copied().enumerate() { for (index, y) in ys
.iter()
.copied()
.take(usize::from(area.width.saturating_sub(*x)))
.enumerate()
{
let Ok(offset) = u16::try_from(index) else { let Ok(offset) = u16::try_from(index) else {
break; break;
}; };
@@ -681,21 +718,25 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
if let Some(previous) = previous_y { if let Some(previous) = previous_y {
let from = previous.min(y); let from = previous.min(y);
let to = previous.max(y); let to = previous.max(y);
for y in from..=to { for y in from..=to.min(area.height.saturating_sub(1)) {
write_cell(frame, area, x, y, line_ch, line_style); write_cell(buffer, area, x, y, line_ch, line_style);
} }
} }
write_cell(frame, area, x, y, ch, point_style); write_cell(buffer, area, x, y, ch, point_style);
previous_y = Some(y); previous_y = Some(y);
} }
} }
DrawCommand::Text { x, y, text, fg, bg } => { DrawCommand::Text { x, y, text, fg, bg } => {
for (offset, ch) in text.chars().enumerate() { for (offset, ch) in text
.chars()
.take(usize::from(area.width.saturating_sub(*x)))
.enumerate()
{
let Ok(offset) = u16::try_from(offset) else { let Ok(offset) = u16::try_from(offset) else {
break; break;
}; };
write_cell( write_cell(
frame, buffer,
area, area,
x.saturating_add(offset), x.saturating_add(offset),
*y, *y,
@@ -708,24 +749,21 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
} }
} }
fn fill_rect(frame: &mut Frame, area: Rect, symbol: &'static str, style: Style) { fn fill_rect(buffer: &mut Buffer, area: Rect, symbol: &'static str, style: Style) {
for y in area.y..area.y + area.height { for y in area.y..area.y + area.height {
for x in area.x..area.x + area.width { for x in area.x..area.x + area.width {
if let Some(cell) = frame.buffer_mut().cell_mut((x, y)) { if let Some(cell) = buffer.cell_mut((x, y)) {
cell.set_symbol(symbol).set_style(style); cell.set_symbol(symbol).set_style(style);
} }
} }
} }
} }
fn write_cell(frame: &mut Frame, area: Rect, x: u16, y: u16, symbol: &str, style: Style) { fn write_cell(buffer: &mut Buffer, area: Rect, x: u16, y: u16, symbol: &str, style: Style) {
if x >= area.width || y >= area.height { if x >= area.width || y >= area.height {
return; return;
} }
if let Some(cell) = frame if let Some(cell) = buffer.cell_mut((area.x.saturating_add(x), area.y.saturating_add(y))) {
.buffer_mut()
.cell_mut((area.x.saturating_add(x), area.y.saturating_add(y)))
{
cell.set_symbol(symbol).set_style(style); cell.set_symbol(symbol).set_style(style);
} }
} }
@@ -774,6 +812,9 @@ fn rgb_color(value: INT) -> Color {
} }
fn parse_color(text: &str) -> Option<Color> { fn parse_color(text: &str) -> Option<Color> {
if text == "default" {
return Some(Color::Reset);
}
let hex = text.trim().trim_start_matches('#').trim_start_matches("0x"); let hex = text.trim().trim_start_matches('#').trim_start_matches("0x");
let value = u32::from_str_radix(hex, 16).ok()?; let value = u32::from_str_radix(hex, 16).ok()?;
Some(Color::Rgb( Some(Color::Rgb(
@@ -850,7 +891,7 @@ fn ensure_bundled_scripts() -> Result<()> {
fn should_replace_bundled_script(existing: &str, script: &BundledScript) -> bool { fn should_replace_bundled_script(existing: &str, script: &BundledScript) -> bool {
let name_marker = format!("// name: {}", script.display_name); let name_marker = format!("// name: {}", script.display_name);
let version_marker = format!("// bundle-version: {BUNDLE_VERSION}"); let version_marker = format!("// bundle-version: {}", script.version);
existing existing
.lines() .lines()
.take(3) .take(3)
@@ -918,9 +959,9 @@ mod tests {
insert_int(&mut input, "analysis_sequence", 1); insert_int(&mut input, "analysis_sequence", 1);
input.insert( input.insert(
"samples".into(), "samples".into(),
(0..128) (0..256)
.map(|index| { .map(|index| {
let sample = ((index as f64 / 128.0) * std::f64::consts::TAU).sin(); let sample = ((index as f64 / 256.0) * std::f64::consts::TAU).sin();
Dynamic::from_float(sample as FLOAT) Dynamic::from_float(sample as FLOAT)
}) })
.collect::<Array>() .collect::<Array>()
@@ -991,4 +1032,284 @@ mod tests {
scope, scope,
)); ));
} }
fn cube_file() -> tempfile::NamedTempFile {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
file.path(),
include_str!("visualizations/morphing_cube.rhai"),
)
.unwrap();
file
}
#[test]
fn cube_update_does_not_upgrade_other_presets() {
let cube = BUNDLED_SCRIPTS
.iter()
.find(|script| script.id == "morphing_cube")
.unwrap();
let old_cube = cube
.source
.replacen("// bundle-version: 6", "// bundle-version: 5", 1);
assert!(should_replace_bundled_script(&old_cube, cube));
for script in BUNDLED_SCRIPTS {
assert!(!should_replace_bundled_script(script.source, script));
}
let custom = old_cube.replacen("// name: Morphing cube", "// name: My cube", 1);
assert!(!should_replace_bundled_script(&custom, cube));
}
#[test]
fn cube_music_adds_particles_echoes_and_a_larger_pulse() {
let file = cube_file();
let mut runtime = ScriptRuntime::default();
let mut input = test_input();
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, 0.0);
}
let quiet = runtime.render(file.path(), input.clone()).unwrap();
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, 0.8);
}
let loud = runtime.render(file.path(), input).unwrap();
let effects = |commands: &[DrawCommand]| {
commands
.iter()
.filter(|command| matches!(command, DrawCommand::Cell { ch, .. } if ch != "o"))
.count()
};
assert!(
effects(&loud) > effects(&quiet) + 30,
"music should visibly populate the scene"
);
let lines = |commands: &[DrawCommand]| {
commands
.iter()
.filter(|command| {
matches!(
command,
DrawCommand::Trace { .. } | DrawCommand::VLine { .. }
)
})
.count()
};
assert_eq!(
lines(&loud),
lines(&quiet) + 30,
"two echoes and three rings"
);
let footprint = |commands: &[DrawCommand]| {
let vertices = cube_vertices(commands);
let xs: Vec<_> = vertices.iter().map(|p| p.0).collect();
let ys: Vec<_> = vertices.iter().map(|p| p.1).collect();
u32::from(xs.iter().max().unwrap() - xs.iter().min().unwrap())
* u32::from(ys.iter().max().unwrap() - ys.iter().min().unwrap())
};
assert!(
footprint(&loud) > footprint(&quiet) * 2,
"pulse should be substantially larger"
);
}
fn cube_vertices(commands: &[DrawCommand]) -> Vec<(u16, u16)> {
commands
.iter()
.filter_map(|command| match command {
DrawCommand::Cell { x, y, ch, .. } if ch == "o" => Some((*x, *y)),
_ => None,
})
.collect()
}
#[test]
fn cube_rotates_and_each_audio_control_deforms_geometry() {
let file = cube_file();
let mut runtime = ScriptRuntime::default();
let mut input = test_input();
insert_int(&mut input, "width", 160);
insert_int(&mut input, "height", 60);
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, 0.0);
}
let quiet = cube_vertices(&runtime.render(file.path(), input.clone()).unwrap());
assert_eq!(quiet.len(), 8);
for band in ["energy", "bass", "mid", "treble", "beat"] {
let mut loud = input.clone();
insert_float(&mut loud, band, 1.0);
let deformed = cube_vertices(&runtime.render(file.path(), loud).unwrap());
assert_ne!(
quiet, deformed,
"{band} should move vertices, not just colors"
);
}
insert_float(&mut input, "time", 3.0);
let rotated = cube_vertices(&runtime.render(file.path(), input).unwrap());
assert_ne!(quiet, rotated, "rotation should continue in silence");
}
#[test]
fn cube_stays_bounded_across_sizes_times_and_audio_extremes() {
let file = cube_file();
let mut runtime = ScriptRuntime::default();
// Much tighter than the production two-million-operation ceiling.
runtime.engine.set_max_operations(200_000);
for (width, height) in [
(1, 1),
(11, 7),
(12, 8),
(24, 80),
(80, 24),
(160, 50),
(320, 100),
] {
for level in [0.0, 0.5, 1.0] {
for tick in 0..12 {
let mut input = test_input();
insert_int(&mut input, "width", width);
insert_int(&mut input, "height", height);
insert_float(&mut input, "time", f64::from(tick) * 1.37);
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, level);
}
let commands = runtime.render(file.path(), input).unwrap();
assert!(commands.len() <= 220);
if width < 12 || height < 8 {
assert_eq!(commands.len(), 1);
continue;
}
assert_eq!(cube_vertices(&commands).len(), 8);
let mut edges = 0;
for command in &commands {
match command {
DrawCommand::Trace { x, ys, .. } => {
edges += 1;
assert!(usize::from(*x) + ys.len() <= width as usize);
assert!(ys.iter().all(|y| i64::from(*y) < height));
}
DrawCommand::VLine { x, y, h, .. } => {
edges += 1;
assert!(i64::from(*x) < width);
assert!(i64::from(*y) + i64::from(*h) <= height);
}
DrawCommand::Cell { x, y, .. } => {
assert!(i64::from(*x) < width && i64::from(*y) < height);
}
_ => {}
}
}
assert!((12..=54).contains(&edges));
}
}
}
}
#[test]
fn cube_edges_handle_reversed_vertical_and_collapsed_projections() {
let runtime = ScriptRuntime::default();
let ast = runtime
.engine
.compile(include_str!("visualizations/morphing_cube.rhai"))
.unwrap();
for (ax, ay, bx, by) in [
(2_i64, 3_i64, 8_i64, 9_i64),
(8, 9, 2, 3),
(2, 9, 8, 3),
(8, 3, 2, 9),
(4, 9, 4, 3),
(4, 3, 4, 3),
] {
let output = runtime
.engine
.call_fn::<Dynamic>(
&mut Scope::new(),
&ast,
"edge",
(ax, ay, bx, by, 0xffffff_i64, 0_i64),
)
.unwrap();
match DrawCommand::from_dynamic(output).unwrap() {
DrawCommand::Trace { x, ys, .. } => {
assert_eq!(i64::from(x), ax.min(bx));
assert_eq!(ys.len(), (ax - bx).unsigned_abs() as usize + 1);
let (left_y, right_y) = if ax < bx { (ay, by) } else { (by, ay) };
assert_eq!(i64::from(ys[0]), left_y);
assert_eq!(i64::from(*ys.last().unwrap()), right_y);
}
DrawCommand::VLine { x, y, h, .. } => {
assert_eq!(i64::from(x), ax);
assert_eq!(i64::from(y), ay.min(by));
assert_eq!(u64::from(h), (ay - by).unsigned_abs() + 1);
}
other => panic!("unexpected edge: {other:?}"),
}
}
}
/// Explicit, reproducible CPU measurement; no audio hardware or user config.
/// TestBackend includes buffer drawing/diff, but not terminal I/O/emulation.
#[test]
#[ignore = "manual benchmark: cargo test --release benchmark_visualizers -- --ignored --nocapture"]
fn benchmark_visualizers() {
use ratatui::{Terminal, backend::TestBackend};
for script in BUNDLED_SCRIPTS {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), script.source).unwrap();
let mut runtime = ScriptRuntime::default();
for (width, height) in [(80_u16, 24_u16), (160, 50), (240, 80)] {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
let mut script_times = Vec::new();
let mut frame_times = Vec::new();
let mut max_commands = 0;
for tick in 0..230 {
let mut input = test_input();
insert_int(&mut input, "width", i64::from(width));
insert_int(&mut input, "height", i64::from(height));
let time = f64::from(tick) * 0.05;
insert_float(&mut input, "time", time);
for (i, band) in ["energy", "bass", "mid", "treble", "beat"]
.iter()
.enumerate()
{
insert_float(&mut input, band, (time * (i + 1) as f64).sin() * 0.5 + 0.5);
}
let started = Instant::now();
let commands = runtime.render(file.path(), input).unwrap();
let script_elapsed = started.elapsed();
terminal
.draw(|frame| render_commands(frame, frame.area(), &commands))
.unwrap();
if tick >= 30 {
script_times.push(script_elapsed.as_secs_f64() * 1000.0);
frame_times.push(started.elapsed().as_secs_f64() * 1000.0);
max_commands = max_commands.max(commands.len());
}
}
script_times.sort_by(f64::total_cmp);
frame_times.sort_by(f64::total_cmp);
println!(
"{} {width}x{height}: script p95={:.3}ms; frame median={:.3}ms p95={:.3}ms max={:.3}ms; commands<={max_commands}",
script.id,
script_times[189],
frame_times[99],
frame_times[189],
frame_times[199]
);
if script.id == "morphing_cube" && width == 80 {
for row in terminal
.backend()
.buffer()
.content
.chunks(usize::from(width))
{
println!(
"{}",
row.iter().map(|cell| cell.symbol()).collect::<String>()
);
}
}
}
}
}
} }
@@ -0,0 +1,57 @@
// name: Status braille histogram
// protocol: furumi-visualizer-v2
// surface: status
//
// Always-on, one-row visualization. Edit this file to customize it; saved
// changes reload during playback. The host never overwrites an existing file.
// Same render(input) and draw commands as fullscreen scripts; height is 1.
// Audio bands and waveform amplitudes drive the bars (not a full FFT).
// Each Braille character packs two independent four-dot vertical columns.
// "default" background retains the terminal's background color.
// A method reads the waveform through `this`, avoiding an array copy for
// every column in this continuously running visualization.
fn level(index, columns, band, energy, beat) {
let wave = 0.0;
let count = this.len();
if count > 0 {
let start = index * count / columns;
let end = (index + 1) * count / columns;
let total = 0;
for i in start..end {
wave += abs(this[i]);
total += 1;
}
if total > 0 { wave /= to_float(total); }
else { wave = abs(this[start]); }
}
let value = band * 0.55 + wave * 0.8 + energy * 0.12 + beat * 0.18;
if value <= 0.01 { 0 }
else if value < 0.20 { 1 }
else if value < 0.40 { 2 }
else if value < 0.65 { 3 }
else { 4 }
}
fn render(input) {
let commands = [#{ op: "clear", bg: "default" }];
if input.width <= 0 || input.height <= 0 || input.paused { return commands; }
// Lookup table indexed by left/right bar heights, from the bottom up.
let dots = ["⠀⢀⢠⢰⢸", "⡀⣀⣠⣰⣸", "⡄⣄⣤⣴⣼", "⡆⣆⣦⣶⣾", "⡇⣇⣧⣷⣿"];
let columns = input.width * 2;
let samples = input.samples;
for x in 0..input.width {
let levels = [];
for side in 0..2 {
let index = x * 2 + side;
let phase = to_float(index) / to_float(columns);
let band = if phase < 0.33 { input.bass }
else if phase < 0.67 { input.mid } else { input.treble };
levels.push(samples.level(index, columns, band, input.energy, input.beat));
}
let glyph = dots[levels[0]].sub_string(levels[1], 1);
commands.push(#{ op: "cell", x: x, y: 0, ch: glyph,
fg: 0x48c9c0, bg: "default" });
}
commands
}
+583
View File
@@ -0,0 +1,583 @@
//! One-row surface: blocking preparation runs off the UI thread; views copy
//! only the prepared buffer. Uses the fullscreen engine and drawing commands.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use ratatui::{
Frame,
buffer::Buffer,
layout::Rect,
style::{Color, Style},
widgets::Paragraph,
};
use tokio::sync::mpsc;
use unicode_width::UnicodeWidthStr;
use super::{
ScriptRuntime, features_from_state, input_map_with_features, render_commands_to_buffer,
};
use crate::app::{event::AppEvent, state::AppState};
const SOURCE: &str = include_str!("../visualizations/status/braille.rhai");
const LEGACY_SOURCE: &str = include_str!("fixtures/status_braille_v1.rhai");
pub fn script_path() -> anyhow::Result<PathBuf> {
Ok(super::visualizations_dir()?
.join("status")
.join("braille.rhai"))
}
pub(super) fn ensure_script() -> anyhow::Result<()> {
install_script_at(&script_path()?)
}
fn install_script_at(path: &Path) -> anyhow::Result<()> {
ensure_script_at(path)?;
// Upgrade only a byte-for-byte stock script, never a user's edited one.
if std::fs::metadata(path)?.len() == LEGACY_SOURCE.len() as u64
&& std::fs::read(path)? == LEGACY_SOURCE.as_bytes()
{
let mut replacement =
tempfile::NamedTempFile::new_in(path.parent().unwrap_or(Path::new(".")))?;
replacement.write_all(SOURCE.as_bytes())?;
replacement.as_file().sync_all()?;
if std::fs::read(path)? == LEGACY_SOURCE.as_bytes() {
replacement.persist(path)?;
}
}
Ok(())
}
fn ensure_script_at(path: &Path) -> anyhow::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
{
Ok(mut file) => file.write_all(SOURCE.as_bytes())?,
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(err) => return Err(err.into()),
}
Ok(())
}
pub fn visible(state: &AppState) -> bool {
state.player.playing && state.player.current.is_some() && state.device_playback.is_audio_owner()
}
pub fn playing(state: &AppState) -> bool {
visible(state) && !state.player.paused
}
fn source_input(width: u16, state: &AppState, elapsed: f64) -> rhai::Map {
// AnalyzedSource taps decoded audio before rodio's output volume. Keep
// those source levels intact; input.volume remains available as metadata.
let mut features = features_from_state(state, false);
features.elapsed_secs = elapsed;
input_map_with_features(Rect::new(0, 0, width, 1), state, features)
}
#[derive(Debug, Default)]
pub struct State {
target: Option<(u16, String)>,
generation: u64,
frame: Option<Buffer>,
error: Option<String>,
paused: bool,
}
impl State {
/// Invalidates in-flight results. A resize keeps the last frame until a
/// replacement arrives, including when playback is paused.
pub fn set_target(&mut self, target: Option<(u16, String)>) {
if self.target != target {
let same_track = self
.target
.as_ref()
.zip(target.as_ref())
.is_some_and(|(old, new)| old.1 == new.1);
self.target = target;
self.generation = self.generation.wrapping_add(1);
if !same_track {
self.frame = None;
}
self.error = None;
}
}
pub fn set_paused(&mut self, paused: bool) {
if self.paused != paused {
self.paused = paused;
self.generation = self.generation.wrapping_add(1);
}
}
pub fn apply(&mut self, ready: Ready) {
if ready.generation != self.generation || self.target.is_none() || self.paused {
return;
}
match ready.result {
Ok(frame) => {
self.frame = Some(frame);
self.error = None;
}
Err(error) => {
if self.error.as_ref() != Some(&error) {
tracing::warn!(%error, "status visualization failed");
}
self.frame = None;
self.error = Some(error);
}
}
}
pub fn draw(&self, frame: &mut Frame, area: Rect) {
if area.is_empty() {
return;
}
if let Some(buffer) = &self.frame {
if buffer.area.width == 0 {
return;
}
for x in 0..area.width {
let source_x =
usize::from(x) * usize::from(buffer.area.width) / usize::from(area.width);
if let Some(target) = frame.buffer_mut().cell_mut((area.x + x, area.y)) {
*target = buffer.content[source_x].clone();
}
}
} else if let Some(error) = &self.error {
frame.render_widget(
Paragraph::new(format!("viz: {error}")).style(Style::new().fg(Color::Red)),
area,
);
}
}
}
#[derive(Debug)]
pub struct Ready {
generation: u64,
result: Result<Buffer, String>,
}
/// One in-flight job at most: slow custom scripts drop ticks, never queue
/// frames or block input. AST caches are independent of fullscreen selection.
pub struct Renderer {
runtime: Arc<Mutex<ScriptRuntime>>,
started: Instant,
pub busy: bool,
}
impl Default for Renderer {
fn default() -> Self {
let mut runtime = ScriptRuntime::default();
runtime
.engine
.set_max_operations(200_000)
.set_max_array_size(8192)
.set_max_map_size(4096)
.set_max_string_size(32_768);
Self {
runtime: Arc::new(Mutex::new(runtime)),
started: Instant::now(),
busy: false,
}
}
}
impl Renderer {
pub fn request(&mut self, state: &AppState, tx: mpsc::UnboundedSender<AppEvent>) {
let Some((width, _)) = &state.status_visualizer.target else {
return;
};
if self.busy || !playing(state) || state.visualizer.active {
return;
}
self.busy = true;
let width = *width;
let generation = state.status_visualizer.generation;
let input = source_input(width, state, self.started.elapsed().as_secs_f64());
let runtime = Arc::clone(&self.runtime);
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
let path = script_path().map_err(|e| e.to_string())?;
let mut runtime = runtime
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if runtime.cached_path.is_none() {
// Retry initialization after a transient startup error.
install_script_at(&path).map_err(|e| e.to_string())?;
}
prepare(&mut runtime, &path, input, width)
})
.await
.unwrap_or_else(|err| Err(err.to_string()));
let _ = tx.send(AppEvent::StatusVisualizationReady(Ready {
generation,
result,
}));
});
}
}
fn prepare(
runtime: &mut ScriptRuntime,
path: &Path,
input: rhai::Map,
width: u16,
) -> Result<Buffer, String> {
if std::fs::metadata(path).map_err(|e| e.to_string())?.len() > 65_536 {
return Err("status script exceeds 64 KiB".into());
}
let commands = runtime.render(path, input)?;
if commands.len() > 4096 {
return Err("too many status drawing commands".into());
}
let area = Rect::new(0, 0, width, 1);
let mut buffer = Buffer::empty(area);
render_commands_to_buffer(&mut buffer, area, &commands);
// A user-supplied cell string must never spill into neighboring UI areas.
for cell in &mut buffer.content {
if cell.symbol().width() != 1 || cell.symbol().chars().any(char::is_control) {
cell.set_symbol(" ");
}
}
Ok(buffer)
}
#[cfg(test)]
mod tests {
use super::super::insert_float;
use super::*;
use ratatui::{Terminal, backend::TestBackend};
use rhai::{Array, Dynamic};
fn input(width: u16, level: f64) -> rhai::Map {
let mut input = source_input(width, &AppState::default(), 0.0);
for band in ["energy", "bass", "mid", "treble", "beat"] {
insert_float(&mut input, band, level);
}
input.insert(
"samples".into(),
(0..256)
.map(|index| {
Dynamic::from_float(level * (index as f64 * std::f64::consts::TAU / 64.0).sin())
})
.collect::<Array>()
.into(),
);
input
}
#[test]
fn histogram_uses_braille_and_real_levels_in_one_row() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("status/braille.rhai");
ensure_script_at(&path).unwrap();
let renderer = Renderer::default();
let mut runtime = renderer.runtime.lock().unwrap();
for width in [0, 1, 8, 60, 200] {
let quiet = prepare(&mut runtime, &path, input(width, 0.0), width).unwrap();
let loud = prepare(&mut runtime, &path, input(width, 1.0), width).unwrap();
assert_eq!(loud.area, Rect::new(0, 0, width, 1));
assert!(quiet.content.iter().all(|cell| cell.symbol() == "⠀"));
assert!(loud.content.iter().all(|cell| {
cell.symbol()
.chars()
.all(|ch| ('\u{2800}'..='\u{28ff}').contains(&ch))
&& cell.bg == Color::Reset
}));
if width > 0 {
assert_ne!(loud, quiet);
}
let mut paused = input(width, 1.0);
paused.insert("paused".into(), true.into());
assert_eq!(prepare(&mut runtime, &path, paused, width).unwrap(), loud);
}
}
#[test]
fn existing_user_script_survives_and_hot_reload_recovers_from_errors() {
let file = tempfile::NamedTempFile::new().unwrap();
let path = file.path();
let mut runtime = ScriptRuntime::default();
for (revision, symbol) in [(1, "A"), (2, "B"), (3, "bad"), (4, "C")] {
let source = if symbol == "bad" {
"fn render(".into()
} else {
format!(
"fn render(input) {{ [#{{ op: \"text\", x: 0, y: 0, text: \"{symbol}\" }}] }}"
)
};
std::fs::write(path, &source).unwrap();
file.as_file()
.set_times(std::fs::FileTimes::new().set_modified(
std::time::UNIX_EPOCH
+ std::time::Duration::from_secs(1_700_000_000 + revision),
))
.unwrap();
install_script_at(path).unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), source);
let frame = prepare(&mut runtime, path, input(8, 0.0), 8);
if symbol == "bad" {
assert!(frame.is_err());
} else {
assert_eq!(frame.unwrap().content[0].symbol(), symbol);
}
}
}
#[test]
fn status_commands_are_clipped_and_cannot_spill_into_the_ui() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
file.path(),
r##"fn render(input) { [
#{ op: "rect", x: 0, y: 0, w: 65535, h: 65535, ch: "#" },
#{ op: "text", x: 0, y: 1, text: "outside" },
#{ op: "trace", x: 6, ys: [65535, 0, 65535], ch: "*" },
#{ op: "cell", x: 0, y: 0, ch: "界" },
#{ op: "cell", x: 1, y: 0, ch: "\n" },
#{ op: "cell", x: 2, y: 0, ch: "too long" }
] }"##,
)
.unwrap();
let buffer = prepare(&mut ScriptRuntime::default(), file.path(), input(8, 0.0), 8).unwrap();
assert!(buffer.content[..3].iter().all(|cell| cell.symbol() == " "));
let state = State {
frame: Some(buffer),
..State::default()
};
let mut terminal = Terminal::new(TestBackend::new(20, 4)).unwrap();
terminal
.draw(|frame| {
for cell in &mut frame.buffer_mut().content {
cell.set_symbol("x");
}
state.draw(frame, Rect::new(11, 3, 8, 1));
})
.unwrap();
let buffer = terminal.backend().buffer();
for y in 0..4 {
for x in 0..20 {
if y != 3 || !(11..19).contains(&x) {
assert_eq!(buffer[(x, y)].symbol(), "x");
}
}
}
}
#[test]
fn stale_frames_are_discarded_after_resize_track_change_or_stop() {
let mut state = State::default();
state.set_target(Some((8, "track-a".into())));
let generation = state.generation;
state.apply(Ready {
generation,
result: Ok(Buffer::empty(Rect::new(0, 0, 8, 1))),
});
assert!(state.frame.is_some());
for target in [
Some((12, "track-a".into())),
Some((12, "track-b".into())),
None,
] {
state.set_target(target);
let previous_frame = state.frame.clone();
state.apply(Ready {
generation,
result: Ok(Buffer::empty(Rect::new(0, 0, 8, 1))),
});
assert_eq!(state.frame, previous_frame);
}
assert!(state.frame.is_none());
}
#[test]
fn pause_freezes_the_last_frame_and_rejects_in_flight_work() {
let mut state = State::default();
state.set_target(Some((8, "track".into())));
let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 1));
for cell in &mut buffer.content {
cell.set_symbol("⣤");
}
let generation = state.generation;
state.apply(Ready {
generation,
result: Ok(buffer.clone()),
});
state.set_paused(true);
state.apply(Ready {
generation,
result: Err("late error".into()),
});
state.apply(Ready {
generation: state.generation,
result: Ok(Buffer::empty(buffer.area)),
});
assert_eq!(state.frame.as_ref(), Some(&buffer));
// A paused resize adapts the frozen row instead of erasing it.
state.set_target(Some((12, "track".into())));
let mut terminal = Terminal::new(TestBackend::new(12, 1)).unwrap();
terminal
.draw(|frame| state.draw(frame, frame.area()))
.unwrap();
assert!(
terminal
.backend()
.buffer()
.content
.iter()
.all(|cell| cell.symbol() == "⣤")
);
let paused_generation = state.generation;
state.set_paused(false);
state.apply(Ready {
generation: paused_generation,
result: Err("stale pause".into()),
});
assert_eq!(state.frame.as_ref(), Some(&buffer));
state.apply(Ready {
generation: state.generation,
result: Ok(Buffer::empty(Rect::new(0, 0, 12, 1))),
});
assert_ne!(state.frame.as_ref(), Some(&buffer));
state.set_target(None);
assert!(state.frame.is_none());
}
#[test]
fn source_audio_input_is_independent_of_output_volume_and_pause() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), SOURCE).unwrap();
let mut state = AppState::default();
state.player.audio_analysis = crate::player::AudioAnalysisSnapshot {
energy: 0.8,
bass: 0.9,
mid: 0.6,
treble: 0.3,
beat: 0.5,
scope: (0..256).map(|i| (i as f64 * 0.13).sin() * 0.7).collect(),
..Default::default()
};
let mut runtime = ScriptRuntime::default();
let expected =
prepare(&mut runtime, file.path(), source_input(64, &state, 1.0), 64).unwrap();
for volume in [0, 1, 25, 80, 100] {
for paused in [false, true] {
state.player.volume = volume;
state.player.paused = paused;
let map = source_input(64, &state, 1.0);
for (key, level) in [
("energy", 0.8),
("bass", 0.9),
("mid", 0.6),
("treble", 0.3),
("beat", 0.5),
] {
assert_eq!(map[key].as_float().unwrap(), level);
}
assert_eq!(map["volume"].as_float().unwrap(), f64::from(volume) / 100.0);
assert_eq!(
prepare(&mut runtime, file.path(), map, 64).unwrap(),
expected
);
}
}
}
#[test]
fn loud_recordings_use_multiple_heights_instead_of_a_solid_row() {
let file = tempfile::NamedTempFile::new().unwrap();
let mut runtime = ScriptRuntime::default();
std::fs::write(file.path(), LEGACY_SOURCE).unwrap();
let old = prepare(&mut runtime, file.path(), input(64, 1.0), 64).unwrap();
assert!(old.content.iter().all(|cell| cell.symbol() == "⣿"));
install_script_at(file.path()).unwrap();
// A fresh runtime also models a restart installing the new default.
let mut runtime = ScriptRuntime::default();
let new = prepare(&mut runtime, file.path(), input(64, 1.0), 64).unwrap();
let symbols: std::collections::HashSet<_> =
new.content.iter().map(|cell| cell.symbol()).collect();
assert!(symbols.len() >= 4, "{symbols:?}");
assert!(
new.content
.iter()
.filter(|cell| cell.symbol() == "⣿")
.count()
< 32
);
assert!(new.content.iter().any(|cell| cell.symbol() == "⠀"));
// Compressed band/beat values alone must not create a filled baseline.
let mut silence = input(64, 1.0);
silence.insert(
"samples".into(),
(0..256)
.map(|_| Dynamic::from_float(0.001))
.collect::<Array>()
.into(),
);
let silent = prepare(&mut runtime, file.path(), silence, 64).unwrap();
assert!(silent.content.iter().all(|cell| cell.symbol() == "⠀"));
}
#[test]
fn only_the_untouched_previous_default_is_upgraded() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), LEGACY_SOURCE).unwrap();
install_script_at(file.path()).unwrap();
assert_eq!(std::fs::read_to_string(file.path()).unwrap(), SOURCE);
install_script_at(file.path()).unwrap();
assert_eq!(std::fs::read_to_string(file.path()).unwrap(), SOURCE);
for stock in [LEGACY_SOURCE, SOURCE] {
let custom = format!("{stock}\n// user customization\n");
std::fs::write(file.path(), &custom).unwrap();
install_script_at(file.path()).unwrap();
assert_eq!(std::fs::read_to_string(file.path()).unwrap(), custom);
}
}
#[test]
fn status_script_infinite_loop_hits_the_operation_limit() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), "fn render(input) { loop {} [] }").unwrap();
let renderer = Renderer::default();
let mut runtime = renderer.runtime.lock().unwrap();
let err = prepare(&mut runtime, file.path(), input(8, 0.0), 8).unwrap_err();
assert!(err.contains("operations"), "{err}");
}
#[test]
#[ignore = "manual benchmark: cargo test --release benchmark_status_visualizer -- --ignored --nocapture"]
fn benchmark_status_visualizer() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), SOURCE).unwrap();
let renderer = Renderer::default();
let mut runtime = renderer.runtime.lock().unwrap();
for width in [32, 64, 128] {
let mut times = Vec::new();
for tick in 0..230 {
let level = (f64::from(tick) * 0.13).sin() * 0.5 + 0.5;
let input = input(width, level);
let start = Instant::now();
let frame = prepare(&mut runtime, file.path(), input, width).unwrap();
std::hint::black_box(frame);
if tick >= 30 {
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
}
times.sort_by(f64::total_cmp);
println!(
"status {width}x1: median={:.3}ms p95={:.3}ms max={:.3}ms",
times[99], times[189], times[199]
);
}
}
}