Compare commits

...
20 Commits
Author SHA1 Message Date
ab cc1176a160 feat(opendeck): like the playing track and fade before removing a like 2026-11-29 05:51:43 +02:00
ab 79df5edd8c feat: ship the Furumi OpenDeck plugin for Windows, macOS and Linux 2026-11-28 18:09:48 +02:00
Aleksandr Bogomiakov 57e60a7fe3 ci: complete existing releases without replacing binaries 2026-11-23 18:31:54 +02:00
Aleksandr Bogomiakov 1f806fd44d ci: dispatch Homebrew update after publishing Furumi 2026-11-23 18:29:06 +02:00
Aleksandr Bogomiakov bb215790a7 fix readme 2026-11-23 18:12:59 +02:00
Aleksandr Bogomiakov df11d68382 fix: refresh displayed lyrics and preserve particle backgrounds 2026-11-23 17:41:38 +02:00
Aleksandr Bogomiakov a3782ed8a8 Improve kinetic typography in the TUI lyrics visualizer 2026-11-23 17:16:27 +02:00
Aleksandr Bogomiakov aa32dbb101 feat: add federated lyrics and recover audio output changes 2026-11-23 16:42:42 +02:00
ab ddcd523282 bumnp lock 2026-11-22 15:32:47 +02:00
ab 5aef2cb1e7 Add offline podcast downloads and release 0.5.3 2026-11-22 15:27:40 +02:00
ab 3cd6d94895 Merge pull request #5: VFD visualization platform v3 for 0.5.1 2026-11-22 13:44:44 +02:00
sanapachandClaude Opus 5.5 3e60195352 VFD panel: live signal path output row
The lower row of the signal path schematic was decoration (TONE, AMP,
SPEAKERS A). It now shows what leaves the player, read right to left
after the volume stage: the sample rate, STEREO or MONO, and the output
peak after the volume (the analyzer measures before rodio's gain, which
is volume cubed), refreshed four times a second and red near full scale.
The compact strip line and the transport STEREO lamp use the same values.

Comparing the L and R levels cannot tell stereo from mono: a wide mix
with balanced channels has equal levels. The analyzer therefore also
accumulates the side signal (L - R) / 2 per window, exposed as
level_side, and the meter decides stereo or mono on loud raw windows
(side within 30 dB of the louder channel), before any ballistics, and
keeps the decision through silence; scripts get it as channel_mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 22:12:41 +02:00
sanapachandClaude Opus 5.5 5a00a1c8e8 VFD panel: display modes with a hardware-style switch
DISPLAY_MODE() replaces LAYOUT() with "full", "spectrum", "minimal" and
"deck" ("auto" follows Shift+M; the old names still work). When the
layout on screen changes, the time and L/R meters stay lit while the
other sections go dark and light up one after another with a short
overshoot, like a display switching modes in hardware. A pinned mode or
a fallback to the same layout only flashes the mode lamps.

The analyzer's display range follows the music: its top rises with the
loudest band and falls 4 dB/s within -26..-6 dBFS, never reaching below
the analyzer floor, so silence stays dark. Spectrum mode caps the
analyzer at 18 rows and centres the panel; minimal mode is at most 132
columns wide and centred. Deck mode adds AMS, NR [B], AUTO REVERSE and
REW / FF lamps and a tape counter that races during a seek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:38:26 +02:00
sanapachandClaude Opus 5.5 d1c89511ed Finish the VFD panel: 14-segment transport word and display behaviour polish
PLAY / PAUSE / STOP are drawn as full 14-segment letters (box-drawing
diagonals, a split middle bar, centre strokes) with faint unlit segments,
so the word no longer mixes segment and dot-matrix styles. Unlit lamps are
brighter and keep their level at night; the balance marker is two thin
segments over a bright centre mark; analyzer peak marks hold, then fall with
growing speed; and the lower-right block is one digital module with captions
and equally tall digits for track and volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:14:12 +02:00
sanapachandClaude Opus 5.5 2288392825 Switch visualizer display modes with Shift+M and polish the VFD panel
A new CycleVisualizerMode action (Shift+M by default) steps the fullscreen
visualizer's display mode; the choice is saved in visualizations.toml and
reaches scripts as input.mode. The VFD panel uses it for its classic, focus,
minimal and tape modes, with a row of mode lamps after each change and a
step-down when a mode does not fit the window.

Polish: quieter signal-path lines with lit boxes and nodes, two-cell peak
marks and a mid-level red zone in the level meter, A and Y in a 14-segment
style with thin diagonals, an analyzer tint from warm amber in the bass to
light yellow in the treble, and bar inertia that is separate from peak hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:49:38 +02:00
sanapachandClaude Opus 5.5 204d17f14c Give the VFD panel glow levels, a measuring module and a signal schematic
The analyzer shows three levels of glow (a dimmer foot, the body, a nearly
white top segment), faint unlit segments and a light peak-hold mark, on a
nonlinear scale; loud columns glow brighter on their own instead of the
whole panel brightening. The peak frequency becomes one measuring module
(caption, held value, rule, sample rate) with a real hold. The signal path
is a schematic of framed boxes on a bus with nodes, a wire to the lower row,
a pulse that now and then runs along it and a SIGNAL PATH state label.
PLAY / PAUSE / STOP use segment letters with centre strokes, mode lamps get
indicator bars, paused colours fade into unlit phosphor, and a new source
goes dark and relights with its value. LAYOUT() chooses between the full
panel, a spectrum focus and a tape deck composition, or picks by size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:04:07 +02:00
sanapachandClaude Opus 5.5 73a8e94c78 Even out the VFD panel's thin lines and clean up its routing
Verticals of the segment digits now use quarter blocks, as thick as the
eighth-block horizontals, and the mesh behind them is gone; unlit segments
are fainter so lit digits read clearly. The routing display uses label
plates without sides, and its wire runs along cell edges from the volume
plate's corner straight down to the tone plate's corner, so it joins
cleanly. The bass / treble fans are single thin strokes instead of braille
lines, and the braille amplifier and speakers are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:48:48 +02:00
sanapachandClaude Opus 5.5 61027d22ca Add VFD panel effects and a local-time clock for visualizations
The VFD panel gains a dot-matrix title line (5x7 Latin and Cyrillic in
braille, smooth scrolling), palettes, optional needle VU meters, a night
dimmer, a filament "breath" and loudness brightening, uneven digit
brightness, a mesh behind the big digits, a tape counter, LOUDNESS / MUTE /
SEARCH lamps, a burst of static on track and source changes, and a standby
clock with a sweep at the top of every minute.

The visualization clock now shows local time (it showed UTC), and scripts
get clock_hour, clock_minute, clock_second and clock_millis from the same
reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:28:59 +02:00
sanapachandClaude Opus 5.5 8606f08a36 Add visualization protocol v3 and the VFD panel preset
Scripts now receive the spectrum, channel levels, sample rate and track,
queue and transport details; may return #{ commands, state } to keep state
between frames (with dt and frame, reset on reload and on opening); can draw
thin braille dots and lines (clipped to the area); and can set bold, dim,
italic, underline or reversed on any command. v2 scripts keep working.

The bundled "VFD panel" preset uses all of it for a vacuum-fluorescent hi-fi
front panel in a thin style: segment counter, peak level meter, 25-band
analyzer with peak hold, tone fans, routing diagram and transport lamps,
with a power-on segment test, a counter search on track changes and an
OVER lamp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:48:13 +02:00
sanapachandClaude Opus 5.5 aabca327b2 Measure a third-octave spectrum and channel levels for visualizations
The analyzer now keeps a full-rate mono PCM history and per-window left/right
RMS and peaks. The FFT and all ballistics run on the reader side when a
snapshot is taken, so the audio callback only appends samples: 31 bands with
exact base-2 edges that partition the FFT bins, an ~85 ms window that follows
the sample rate, time-based attack/fall/peak hold, and silence only after the
PCM counter has stalled for longer than a few device callbacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:48:13 +02:00
108 changed files with 17812 additions and 264 deletions

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
name: OpenDeck plugin
on:
workflow_call:
workflow_dispatch:
pull_request:
paths:
- 'integrations/opendeck/**'
- 'integrations/control-protocol/**'
- 'Cargo.toml'
- 'Cargo.lock'
- '.github/workflows/opendeck.yml'
- '.github/workflows/release.yml'
permissions:
contents: read
jobs:
build:
name: Plugin / ${{ matrix.target }}
strategy:
fail-fast: false
matrix:
include:
- os: windows-latest
target: x86_64-pc-windows-msvc
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
- os: ubuntu-24.04-arm
target: aarch64-unknown-linux-gnu
- os: macos-latest
target: aarch64-apple-darwin
- os: macos-15-intel
target: x86_64-apple-darwin
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
targets: ${{ matrix.target }}
- name: Check formatting
run: cargo fmt -p furumi-opendeck -- --check
- name: Test native renderer and simulated hosts
run: cargo test -p furumi-opendeck --all-targets --locked
- name: Test shared settings across action inspectors
run: node integrations/opendeck/tests/property-inspector.cjs
- name: Clippy
run: cargo clippy -p furumi-opendeck --all-targets --locked
- name: Build native plugin
run: cargo build -p furumi-opendeck --release --locked --target ${{ matrix.target }}
- name: Package
shell: pwsh
run: ./integrations/opendeck/package.ps1 -Target '${{ matrix.target }}'
- name: Upload native bundle
uses: actions/upload-artifact@v4
with:
name: opendeck-native-${{ matrix.target }}
path: integrations/opendeck/dist/*.zip
if-no-files-found: error
- name: Render previews with the shipped renderer
shell: pwsh
run: |
$extension = if ($IsWindows) { '.exe' } else { '' }
& "./target/${{ matrix.target }}/release/furumi-opendeck$extension" --preview integrations/opendeck/preview
if ($LASTEXITCODE) { exit $LASTEXITCODE }
- uses: actions/upload-artifact@v4
with:
name: opendeck-preview-${{ matrix.target }}
path: integrations/opendeck/preview/*.png
if-no-files-found: error
package:
name: Package OpenDeck / ${{ matrix.platform }}
needs: build
runs-on: ubuntu-latest
strategy:
matrix:
include:
- platform: windows
targets: '*-windows-msvc'
- platform: macos
targets: '*-apple-darwin'
- platform: linux
targets: '*-linux-gnu'
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
pattern: opendeck-native-${{ matrix.targets }}
path: native
merge-multiple: true
- name: Assemble installable plugin
env:
PLATFORM: ${{ matrix.platform }}
run: |
set -euo pipefail
suffix=""
if [[ "$GITHUB_REF_TYPE" == tag ]]; then suffix="-${GITHUB_REF_NAME#v}"; fi
python3 integrations/opendeck/package_release.py "$PLATFORM" native "dist/furumi-opendeck-$PLATFORM$suffix.zip"
- uses: actions/upload-artifact@v4
with:
name: furumi-opendeck-${{ matrix.platform }}
path: dist/*.zip
if-no-files-found: error
+84 -10
View File
@@ -13,6 +13,9 @@ env:
CARGO_NET_RETRY: 10
jobs:
build-opendeck:
uses: ./.github/workflows/opendeck.yml
build:
name: Build ${{ matrix.asset_name }}
runs-on: ${{ matrix.os }}
@@ -48,7 +51,7 @@ jobs:
run: cargo fetch --locked
- name: Build
run: cargo build --release --locked --offline
run: cargo build -p furumi_tui --release --locked --offline
- name: Package
shell: bash
@@ -78,7 +81,10 @@ jobs:
publish:
name: Publish release assets
needs: build
concurrency:
group: release-assets-${{ github.ref }}
cancel-in-progress: false
needs: [build, build-opendeck]
runs-on: ubuntu-latest
permissions:
contents: write
@@ -89,7 +95,9 @@ jobs:
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
pattern: furumi-*
path: artifacts
merge-multiple: true
- name: Create release and upload assets
env:
@@ -98,12 +106,78 @@ jobs:
run: |
set -euo pipefail
# Hash archive bytes; manifest entries use the release asset basenames.
for archive in artifacts/*/*; do
(cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")")
done > SHA256SUMS
version="${RELEASE_TAG#v}"
archives=(
"artifacts/furumi-linux-x86_64-$version.tar.gz"
"artifacts/furumi-macos-aarch64-$version.tar.gz"
"artifacts/furumi-windows-x86_64-$version.zip"
"artifacts/furumi-opendeck-windows-$version.zip"
"artifacts/furumi-opendeck-macos-$version.zip"
"artifacts/furumi-opendeck-linux-$version.zip"
)
for archive in "${archives[@]}"; do
[[ -s "$archive" ]] || { echo "::error::Missing release archive $archive"; exit 1; }
done
assets=$(mktemp)
if ! gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' > "$assets"; then
for archive in "${archives[@]}"; do
(cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")")
done > SHA256SUMS
gh release create "$RELEASE_TAG" "${archives[@]}" SHA256SUMS \
--title "furumi ${RELEASE_TAG}" \
--notes "Release ${RELEASE_TAG}" \
--verify-tag
exit 0
fi
gh release create "$RELEASE_TAG" artifacts/*/* SHA256SUMS \
--title "furumi ${RELEASE_TAG}" \
--notes "Release ${RELEASE_TAG}" \
--verify-tag
# Hash existing archives from the release itself. Rebuilt artifacts
# can have different bytes even if the tag and file names match.
published=$(mktemp -d)
missing=()
: > SHA256SUMS
for archive in "${archives[@]}"; do
name=$(basename "$archive")
if grep -Fxq -- "$name" "$assets"; then
gh release download "$RELEASE_TAG" --pattern "$name" --dir "$published"
(cd "$published" && sha256sum "$name") >> SHA256SUMS
else
missing+=("$archive")
(cd "$(dirname "$archive")" && sha256sum "$name") >> SHA256SUMS
fi
done
if (( ${#missing[@]} )); then
gh release upload "$RELEASE_TAG" "${missing[@]}"
fi
if grep -Fxq -- SHA256SUMS "$assets"; then
gh release download "$RELEASE_TAG" --pattern SHA256SUMS --dir "$published"
if ! cmp -s "$published/SHA256SUMS" SHA256SUMS; then
gh release upload "$RELEASE_TAG" SHA256SUMS --clobber
fi
else
gh release upload "$RELEASE_TAG" SHA256SUMS
fi
update-homebrew:
name: Dispatch Homebrew formula update
needs: publish
if: github.server_url == 'https://github.com' && github.repository == 'Furumi-stack/furumi-tui'
runs-on: ubuntu-latest
permissions: {}
steps:
- name: Trigger workflow in the Homebrew tap
env:
GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
RELEASE_TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
if [[ ! "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Skipping Homebrew for non-stable tag $RELEASE_TAG"
exit 0
fi
if [[ -z "$GH_TOKEN" ]]; then
echo "::error::Set the HOMEBREW_TAP_TOKEN repository secret to dispatch the Homebrew update."
exit 1
fi
gh workflow run update-furumi.yml \
--repo house-of-vanity/homebrew-tap --ref main --raw-field "tag=$RELEASE_TAG"
+92 -2
View File
@@ -261,6 +261,16 @@ Active-device leases and idle timing prevent stale snapshots from immediately
taking control after a device reconnects. This provides practical coordination
without introducing a central playback arbiter.
A personal controller keeps its confirmed playback view separate from a
pending SetState request. It sends one playback change at a time and resumes
from the active output's latest report. Completion requires a newer heartbeat
in the same ownership term with the requested effect. For a transport change
both the playback state and the owner's output-playing flag must agree.
Furumi obtains this flag from its audio worker. A write failure, change of
owner or timeout ends the wait. The TUI and local control API expose the same
pending state. The existing device-sync command and announcement carry all
information used for this comparison.
## Local application architecture
Inside one node, Furumi uses an event-driven state machine:
@@ -470,6 +480,21 @@ The TUI owns what the contract leaves to clients:
progress generation this device saw, so a handoff target starts its
session above it.
## Lyrics
Furumi loads saved lyrics from the library by canonical audio content ID.
The playback runtime queries the optional `furumi/lyrics/1` stream in the
background and adds distinct alternatives without changing the active version.
Only tracks with local audio can be served. Save on listen persists discovered
versions after the audio is imported. Track edits write directly to the local
library, which keeps exclusions for deleted alternatives.
A single parsed LRC timeline supplies both the reader and the Rhai
`input.lyrics` map. The map contains the current, previous and next line with
timing and availability information. The text sent to a script is bounded on
each frame. The bundled preset combines the `matrix_text` dot-matrix renderer
with Unicode text, sparse Braille particles and timestamp-driven transitions.
## Scripted visualizations
Visualizations are an extension boundary rather than hard-coded rendering
@@ -481,6 +506,9 @@ rodio source
│
v
audio analyzer ──> normalized features + scope samples
│ (PCM history, channel levels)
v
display meter ───> third-octave spectrum, L/R levels, peak hold
│
v
Rhai render(input)
@@ -499,6 +527,36 @@ script implements `render(input)` and returns declarative commands such as
clear, cell, line, rectangle, trace, and text. Scripts never receive the
ratatui frame or audio engine directly.
Protocol v3 adds what front-panel displays need: a third-octave spectrum
(31 bands, 20 Hz to 20 kHz, nominal ISO labels with exact base-2 edges that
partition the FFT bins) with per-band peak hold, left/right RMS and held
sample peaks, the RMS of the side signal (L - R) / 2 and a
stereo/mono decision made on loud windows, the analyzed sample rate, and track, queue and transport
details (format, bit depth, bitrate, track number, queue position, repeat,
shuffle, source), and the local wall-clock time. The audio thread only appends mono samples to a lock-free
ring and accumulates per-window channel levels; the FFT (an ~85 ms window
whose length follows the sample rate) and all ballistics run when the UI
takes a snapshot, under a mutex the audio thread never touches. Ballistics
are time-based (fast attack, steady fall, hold then fall): they advance with
the clock rather than per snapshot. Audio arrives in device-callback bursts,
so a snapshot that sees no new samples reuses the last measurement; only when
the PCM write counter stays still for longer than a few callbacks (pause,
stop) does the meter fall to the floor instead of freezing. In the control
role, and briefly when a track starts, the host passes an empty analysis, so
the meter reads zero. Meter values report the decoded signal on a fixed dBFS
scale and are therefore not scaled by the output volume, unlike the v2
energy features. Scripts choose their own display range within that scale.
v3 also lets a script keep state: `render` may return
`#{ commands, state }`, and the host passes `state` back with `dt` and a frame
counter on the next frame. State lives in the host's script runtime, is reset
whenever the script is recompiled or the visualizer is opened, and is subject
to the same sandbox size limits as any other value. Thin drawing comes from braille `dots` and `line`
commands in a 2 x 4 dot grid per cell (dots merge with braille already in the
cell; lines are clipped to the area first, so far endpoints cost nothing) and
from optional bold/dim/italic/underline/reversed attributes, which each
command sets for its cells rather than adding to what was drawn before.
This command boundary is intentional:
- scripts remain independent of Rust UI internals;
@@ -538,8 +596,8 @@ is not a plugin mechanism for accessing the library, network, or player
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.
Rhai scope for each frame; retained state is limited to the explicit `state`
value described above, and motion should still be derived from time and `dt`.
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
@@ -592,6 +650,27 @@ local storage or ranking.
## Persistence boundaries
### Device-local control surfaces
`control.rs` serves authenticated native clients on loopback only; its shared
contract is independent of device-sync wire types. The OpenDeck plugin is
one such client and owns presentation and navigation, never library or
playback authority. Commands enter `AppEvent` and the ordinary playback
transitions/effects. Trusted-device transfer and Jam restrictions remain
owned by the existing runtime.
The UI publishes in-memory snapshots through a latest-value channel; socket
I/O, endpoint discovery writes and image preparation happen outside the
interactive loop. Artwork references are opaque and restricted to the
current cover. The control endpoint is an optional local adapter, not a
coordinator or federation service, and losing it does not affect playback.
An authenticated local spectrum subscription shares the same 31 bands
sampled for the status visualizer. One bounded latest-value channel feeds
all subscribers at up to 10 Hz during local output. A new stream epoch
invalidates accumulated history across seeks, track changes and handoffs.
The plugin composes the Infobar image locally.
Furumi stores different kinds of state according to their lifetime:
| State | Storage | Role |
@@ -666,3 +745,14 @@ Future changes should preserve these rules:
5. Network and storage work must remain outside the interactive UI path.
6. More peers should improve availability; losing peers should only reduce
remote capabilities.
### Device-local podcast audio
Episode downloads are explicit local actions. Completed files live beside the
podcast database in `podcast-downloads`, keyed by a hash of the shared episode
id. Temporary files become visible only after a complete response is saved.
Playback checks this directory on the blocking pool before opening HTTP and
uses the same progress and queue model for local audio. Downloads and retention
settings never enter the podcast store registers or device-sync protocol.
A background maintenance pass removes downloads after the configured age
(default 30 days from completion); catalog, progress and subscriptions remain.
+50 -1
View File
@@ -7,6 +7,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.5.1] - 2026-11-22
### Added
- "VFD panel" visualization: a vacuum-fluorescent hi-fi front panel with
thin segment digits, a stereo peak level meter (bars or needle VU meters),
a 25-band analyzer with three levels of glow, a nonlinear scale and peak
hold, a peak frequency readout with hold, tone fans, a signal path
schematic with a travelling pulse (source, format, volume, sample rate,
stereo or mono, and the output level in dBFS), the transport word in segment letters,
mode lamps (REPEAT, SHUFFLE, source, LOUDNESS, MUTE, SEARCH, OVER), a tape
counter and a dot-matrix title line (Latin and Cyrillic). Effects: a
power-on segment test, a counter "search" on track changes, static on
track and source changes, a source block that relights with its new
value, colours that fade into unlit phosphor on pause, a night dimmer, a
slow filament "breath", slightly uneven digit brightness and a standby
clock when nothing is loaded. Display modes "full", "spectrum",
"minimal" and "deck" switch with Shift+M or can be pinned with
`DISPLAY_MODE()` at the top of the script, like the palettes ("classic",
"green", "amber", "ice"); a mode that does not fit the window steps down.
A switch looks like hardware: the time and L/R meters stay lit, the other
sections go dark and light up one by one, and a row of mode lamps shows
the choice for a moment. The analyzer's display range follows the
loudness of the music (the measurements stay absolute), and deck mode has
AMS, NR, AUTO REVERSE and REW/FF lamps with a counter that races during a
seek. Bars settle with a little inertia, the analyzer's
tint runs from warm amber in the bass to light yellow in the treble, peak
marks fall with a little gravity after their hold, and the transport word
uses 14-segment letters with faint unlit segments.
- `Shift+M` in the fullscreen visualizer switches its display mode; the
choice is saved in `visualizations.toml`.
- Visualization protocol v3: a real third-octave spectrum (31 bands) with
peak hold, left/right RMS and held peaks, the side-signal level
(`level_side`, the floor for mono) and `channel_mode` ("stereo" or
"mono"), the sample rate, and track,
queue and transport details in the script input; `render` may return
`#{ commands, state }` to keep state between frames (with `dt` and
`frame`); new braille `dots` and `line` commands for thin drawing; bold,
dim, italic, underline and reversed attributes on any command. v2 scripts
keep working unchanged. Scripts also get the local time as
`clock_hour`, `clock_minute`, `clock_second` and `clock_millis`, and the
display mode as `mode`, a counter each script takes modulo its own number
of modes.
### Fixed
- The visualization clock shows local time instead of UTC.
## [0.5.0] - 2026-11-20
### Added
@@ -212,6 +260,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Music-directory validation and migration now reject overlapping changes,
resolve canonical paths, and produce Windows-portable managed filenames.
[Unreleased]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.8...HEAD
[Unreleased]: https://gt.hexor.cy/Furumi/furumi-tui/compare/v0.5.1...HEAD
[0.5.1]: https://gt.hexor.cy/Furumi/furumi-tui/compare/v0.5.0...v0.5.1
[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
Generated
+127 -17
View File
@@ -817,6 +817,15 @@ dependencies = [
"libc",
]
[[package]]
name = "core_maths"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
dependencies = [
"libm",
]
[[package]]
name = "coreaudio-rs"
version = "0.14.2"
@@ -1143,7 +1152,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead"
dependencies = [
"data-encoding",
"syn 1.0.109",
"syn 3.0.4",
]
[[package]]
@@ -1269,7 +1278,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1455,7 +1464,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1656,12 +1665,28 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "fontdue"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca"
dependencies = [
"hashbrown 0.15.5",
"ttf-parser",
]
[[package]]
name = "foreign-types"
version = "0.3.2"
@@ -1696,11 +1721,20 @@ dependencies = [
"winapi",
]
[[package]]
name = "furumi-control-protocol"
version = "0.1.0"
dependencies = [
"directories",
"serde",
"serde_json",
]
[[package]]
name = "furumi-library"
version = "0.3.0"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e7eb785cc6ab5b59db8ef74ffa05d798afde45fbd86da08aecf356432a52d10"
checksum = "fc11f57b118c407380be2bc8c05c9cff4033c8e6c37f9ada450004002801c386"
dependencies = [
"anyhow",
"blake3",
@@ -1713,19 +1747,38 @@ dependencies = [
"tracing",
]
[[package]]
name = "furumi-opendeck"
version = "0.1.0"
dependencies = [
"anyhow",
"base64",
"fontdue",
"furumi-control-protocol",
"futures-util",
"image",
"serde",
"serde_json",
"tempfile",
"tokio",
"tokio-tungstenite",
]
[[package]]
name = "furumi_tui"
version = "0.5.0"
version = "0.6.1"
dependencies = [
"anyhow",
"base64",
"blake3",
"chrono",
"core-foundation 0.10.1",
"crokey",
"crossterm",
"directories",
"flate2",
"fs2",
"furumi-control-protocol",
"furumi-library",
"futures-util",
"image",
@@ -1733,6 +1786,7 @@ dependencies = [
"lofty",
"music-dht",
"object",
"rand 0.9.5",
"ratatui",
"reqwest 0.12.28",
"rhai",
@@ -1752,6 +1806,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.20",
"tokio",
"tokio-tungstenite",
"toml",
"tracing",
"tracing-subscriber",
@@ -2035,6 +2090,17 @@ dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash 0.1.5",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -2043,7 +2109,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
"serde",
"serde_core",
]
@@ -2056,7 +2122,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -3239,9 +3305,9 @@ dependencies = [
[[package]]
name = "music-dht"
version = "0.6.0"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce81f361952228654c28a46e41555f2c3d1520bf8c6c76562e7a53f70dd38e1"
checksum = "f66490c90836afebfd75394d527f47abf8f0675f1eeb4b41dadbd94c13836521"
dependencies = [
"async-trait",
"blake3",
@@ -3657,7 +3723,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3742,7 +3808,7 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
dependencies = [
"proc-macro-crate 1.3.1",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 2.0.119",
@@ -4540,7 +4606,7 @@ dependencies = [
"once_cell",
"socket2 0.6.5",
"tracing",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5056,7 +5122,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5114,7 +5180,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5928,7 +5994,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.4",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6178,6 +6244,18 @@ dependencies = [
"tokio-util",
]
[[package]]
name = "tokio-tungstenite"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
]
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -6614,6 +6692,32 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "ttf-parser"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
dependencies = [
"core_maths",
]
[[package]]
name = "tungstenite"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand 0.9.5",
"sha1",
"thiserror 2.0.20",
"utf-8",
]
[[package]]
name = "typeid"
version = "1.0.3"
@@ -6716,6 +6820,12 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -7032,7 +7142,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.48.0",
"windows-sys 0.61.2",
]
[[package]]
+16 -7
View File
@@ -1,16 +1,25 @@
[package]
name = "furumi_tui"
version = "0.5.0"
version = "0.6.1"
edition = "2024"
rust-version = "1.97"
description = "A federated P2P player for personal music libraries"
license = "WTFPL"
[workspace]
members = ["integrations/control-protocol", "integrations/opendeck"]
default-members = [".", "integrations/control-protocol", "integrations/opendeck"]
resolver = "3"
[[bin]]
name = "furumi"
path = "src/main.rs"
[dependencies]
furumi-control-protocol = { path = "integrations/control-protocol" }
base64 = "0.22.1"
rand = "0.9"
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
semver = "1"
self-replace = "1.5"
@@ -23,16 +32,19 @@ object = { version = "0.36", default-features = false, features = ["read", "std"
anyhow = "1.0.102"
blake3 = "1"
# Local wall-clock time for visualizations (the clock and its hour/minute).
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
crokey = "1.4.0"
crossterm = { version = "0.29.0", features = ["event-stream"] }
directories = "6.0.0"
futures-util = "0.3.32"
furumi-library = "0.3.0"
furumi-library = "0.4.0"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
lofty = "0.22"
# P2P federation: library index in a shared DHT + audio streaming between
# peers (same protocol as furumi-fd).
music-dht = { version = "0.6.0", features = ["podcast-feed"] }
# The library and player must share the same FRID podcast and lyrics types.
music-dht = { version = "0.7.0", features = ["podcast-feed"] }
ratatui = { version = "0.30.1", features = ["unstable-rendered-line-info"] }
reqwest = { version = "0.12.28", default-features = false, features = ["rustls-tls", "stream", "blocking"] }
rhai = { version = "1", features = ["sync"] }
@@ -46,7 +58,7 @@ sha2 = "0.10.9"
souvlaki = { version = "0.8.3", default-features = false, features = ["use_zbus"] }
symphonia = { version = "0.5.5", default-features = false, features = ["ogg"] }
thiserror = "2.0.18"
tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util"] }
tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util", "net"] }
toml = "1.1.2"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
@@ -66,6 +78,3 @@ windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_UI_Wi
[target."cfg(unix)".dependencies]
libc = "0.2.186"
[dev-dependencies]
base64 = "0.22.1"
+45 -5
View File
@@ -2,6 +2,8 @@
![furumi](furumi.png)
[![asciicast](https://asciinema.org/a/xSCEn090SS4gk8Hk.svg)](https://asciinema.org/a/xSCEn090SS4gk8Hk)
**Your music. Your devices. Your network.**
Furumi is a federated P2P player for your personal music library. Every
@@ -67,7 +69,10 @@ context-aware bindings, and user-defined rebinding through TOML. Built-in
audio visualizations, OS media controls, gapless queue playback, and local
library management are included. Visualizations are runtime-loadable Rhai
scripts executed in a resource-limited sandbox, so they can be added or edited
without rebuilding the player.
without rebuilding the player. The bundled "VFD panel" preset draws a hi-fi
front panel from a real third-octave spectrum and stereo level meter; scripts
can use the same spectrum, levels, track details, thin braille lines and
per-frame state.
Optional similarity search calculates versioned embeddings for local tracks
in the background and keeps them in SQLite. It works offline; after a separate
@@ -149,6 +154,19 @@ 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.
### Lyrics
Press **l** for the selected track's lyrics or **Ctrl+L** for the playing track. Saved text opens immediately while
Furumi looks for more versions on peers. Use **←/→** to select a version,
**↑/↓** or **Page Up/Down** to read, and **f** to resume following timed lines.
Federated lyrics are stored alongside local audio when **Save on listen** is
enabled. A saved version can be served to peers that request the same audio.
In a local track's metadata editor, **F3** opens its lyrics versions. Use **a**
to add a version, paste plain text or LRC, and save with **Ctrl+S** or **F2**.
Select **Lyrics in motion** in the visualization settings for animated timed
lyrics using the same selected alternative.
### Tabs and key bindings
The number keys open the tabs in the order they are shown, and Tab /
@@ -183,9 +201,16 @@ take them literally and silence the notice.
### Podcasts
The Podcasts tab (`4`) follows RSS and Atom podcast feeds. Furumi stores only
the feed's episode information; audio stays on the publisher's server and is
never imported into the music library or offered to other peers.
The Podcasts tab (`4`) follows RSS and Atom podcast feeds. Audio streams from
the publisher unless you download an episode. Downloads stay on this device,
are never imported into the music library or offered to other peers.
- Press `y` on an episode to download it; `[offline]` marks a complete local
copy. Playback uses that copy, including resume and seeking, without HTTP.
- Settings → Additional settings → Podcast downloads: keep days controls
automatic cleanup (default 30 days from download completion). Cleanup runs
while Furumi is open; expired files can be downloaded again. No episodes
are downloaded automatically.
- **Add podcast** (`o`, or the first row) takes a feed URL; `feed://`,
`podcast://` and URLs without a scheme are accepted. Nothing is stored unless
@@ -459,7 +484,7 @@ 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. This release uses the published FRID crates
`music-dht 0.6.0` and `furumi-library 0.3.0` from crates.io.
`music-dht 0.7.0` and `furumi-library 0.4.0` from crates.io.
Run the local protocol checks from the TUI repository:
@@ -481,6 +506,21 @@ the TUI command adapter and web player hub, but does not start a browser or
PostgreSQL and does not cover web database migrations. Both tests use temporary
identities and data; no running player or user library is used.
## Stream Deck Neo / OpenDeck
The native Rust [OpenDeck plugin](integrations/opendeck/README.md) provides
playback buttons, direct transfer to an online trusted device, a clean album
cover key opening Functions, similarity radio, role colors and a scrolling
Neo Infobar. Its shared settings offer a scrolling spectrogram or live frequency
bars for local audio, album art across four keys and role-colored icons on
black. It targets OpenDeck 2.14.2 on Windows, macOS and Linux. Download the
`furumi-opendeck` ZIP for your operating system alongside the player from
[GitHub Releases](https://github.com/Furumi-stack/furumi-tui/releases).
The running player also accepts local commands such as `furumi ctl status`,
`furumi ctl play-pause`, `furumi ctl seek -10` and `furumi ctl transfer DEVICE_ID`.
See [local control](docs/local-control.md) for the JSON API and authority boundary.
## License
Furumi is released under the
+186
View File
@@ -0,0 +1,186 @@
# Local player control
Furumi exposes a versioned, authenticated WebSocket API to programs on the
same computer. It controls the running TUI; it does not start another audio
engine or grant membership to a device group. It is independent of the DHT
and remains available when federation is disabled.
## Command line
```sh
furumi ctl status
furumi ctl devices
furumi ctl watch
furumi ctl play-pause
furumi ctl previous
furumi ctl next
furumi ctl seek -10
furumi ctl volume-up
furumi ctl volume-down
furumi ctl shuffle
furumi ctl repeat
furumi ctl radio
furumi ctl transfer DEVICE_ID
furumi ctl artwork --federation --output cover.png
```
Status, devices and command results are JSON. Watch emits one JSON snapshot
per line. Volume changes in five percentage-point steps. Seek is relative,
in seconds, bounded to one day per command. A missing or stopped player is an
error, not an instruction to start a second player. The existing
`--status` / `--status-json` exports remain unchanged.
## Connection and authority
The shared `furumi-control-protocol` crate defines the contract and
`discovery_path()`. The running player writes `control-endpoint.json` in
`directories::ProjectDirs::from("", "", "furumi").data_local_dir()`:
```json
{"api_version":1,"port":12345,"token":"RANDOM_PER_PROCESS_TOKEN"}
```
The endpoint binds only to `127.0.0.1`, on an ephemeral port. Connect to
`ws://127.0.0.1:PORT` and send authentication as the first message:
```json
{"type":"authenticate","api_version":1,"token":"RANDOM_PER_PROCESS_TOKEN"}
```
No metadata or commands are available before authentication. Browser Origin
headers are rejected. On Unix the discovery file has mode 0600; on Windows
it inherits the user's application-data directory permissions. Tokens must
never be included in logs or checked into a profile. A reconnect reads the
discovery file again; an old file after an abnormal exit grants no control
over a later process. Normal teardown removes the matching endpoint.
## Messages
The server sends `{"type":"snapshot","snapshot":{...}}` immediately after
authentication. It publishes playback updates at four Hz and sends a snapshot
immediately when a remote command changes state. Snapshots
include stopped/idle players, the local role, active output, online and
offline trusted devices, transfer eligibility, and optional current-track
metadata. Revoked devices are omitted. Item keys preserve episode identity;
numeric track IDs must not be used as episode identity.
Commands carry an opaque unique request ID:
```json
{"type":"command","id":"UNIQUE_REQUEST_ID","command":{"type":"seek","seconds":-10}}
{"type":"command","id":"ANOTHER_ID","command":{"type":"transfer","device_id":"TRUSTED_DEVICE_ID"}}
```
The result is `{"type":"result","id":"...","accepted":true,"error":null}`.
Accepted means dispatched by this player, **not** proof that a remote audio
engine started. Subsequent ownership snapshots report coordination state.
No audio-ready acknowledgement is invented. Local dispatch results are
deduplicated over the most recent 256 command IDs across client connections;
reusing an ID with another command is rejected. Clients should generate IDs
unique across restarts and avoid automatically replaying non-idempotent
commands after uncertain failures.
In the personal Control role the controller keeps displaying the last
confirmed playback while an operation is in flight. The optional local
`remote_command` field contains a monotonically increasing per-session
`id`, a `state` (`idle`, `pending`, `confirmed` or `failed`) and an optional
English `error`. Confirmation means a fresh heartbeat from the selected
owner reports the requested effect. For pause or resume the owner's output
flag must agree with its transport state. Concurrent transport requests are
rejected while waiting. A write failure, ownership change or 15-second
timeout releases the controls. Clients can still navigate or switch devices.
Older local API servers omit this field.
Transfers recheck trust, presence, Jam restrictions and podcast protocol
support. API transfers back to this computer preserve pause. Existing TUI
"play here" behavior is unchanged. Jam volume keeps its existing local
semantics. Commands use the same playback transitions/effects as media keys.
## Likes
`track.liked` is the current music track's state in the user's library.
Furumi omits the field while likes are loading and for items such as podcast
episodes. Older servers also omit it. Clients enable the heart when they
receive a boolean and send the exact `track.key` from that snapshot.
```json
{"type":"command","id":"deck-42","command":{"type":"set_liked","track_key":"lib:17","liked":true}}
```
Both `true` and `false` set the requested state. Furumi rejects a key for a
track that is no longer current and acknowledges a successful save after
reading the state back from the library. Control and Jam clients edit their
own personal library. Content-addressed likes use the normal trusted-device
replication path.
## Artwork
The optional track `artwork_id` is opaque. Request it with
`{"type":"command","id":"...","command":{"type":"artwork","artwork_id":"..."}}`.
The server returns an `artwork` message with the ID and optional `png_base64`.
The default lookup checks the current track and the local release library.
Passing `"federation":true` in the command, or `--federation` on the CLI,
also permits a lookup through the existing release-cover catalog request
when federation is enabled. Furumi tries the active output and known release
source first. Global library mode can additionally discover owners of the
release through the artist catalog. Private items and podcast metadata are
excluded from federated artwork lookup.
The CLI returns a JSON artwork response or writes a 384 × 384 PNG to a new
file with `--output`. A missing cover has a null `png_base64`. The server
coalesces simultaneous lookups and keeps sending snapshots and processing
playback commands during a fetch. OpenDeck requests the image when a player
key displaying the cover is visible. Its cover button shows a loading
indicator, then the image or a neutral framed music note. The service accepts only opaque
references for the current track.
## Local spectrum
A server that supports audio levels advertises `"spectrum_supported":true`
in its normal snapshot. After authentication, a client can send
`{"type":"subscribe_spectrum","enabled":true}` and unsubscribe with
`"enabled":false`. The subscription belongs to that connection and ends
on disconnect. Clients should wait for the advertised capability before
subscribing to an older installation.
A `spectrum` message contains `epoch`, `sequence` and `bands`. The 31 byte
values represent third-octave levels, ordered from 20 Hz to 20 kHz. Values
0–255 cover the analyzer's −60 to 0 dBFS display range. Subscribers receive
up to ten samples per second from local playback, including a local Jam host.
A pause freezes the history. A new epoch or null bands clears it after a
seek, track change, stop or handoff. Slow subscribers receive the latest
available sample. Normal playback snapshots retain their own cadence.
## Similarity radio
Radio uses the current music track as its seed and creates a temporary play
queue, without saving or editing a library playlist. Similarity must already
be enabled and the seed must have a local indexed embedding (a remote seed
is resolved by content ID against this computer's library). Podcast seeds
are rejected. Network queries respect the existing federation consent.
The `radio` snapshot field has an operation `id`, a `state`
(`idle`, `searching`, `starting`, `playing`, `failed`) and an optional English
error. Local and federated candidates are collected asynchronously before
the queue is replaced. A bounded peer search is awaited; if peers fail but
local matches exist, radio can still play offline. Candidate ranking,
deduplication and artist diversity reuse the TUI similarity policy.
Search failures, empty results, changed queues/outputs and stale operation
results leave the existing queue untouched. `starting` persists through
audio preparation; `playing` is emitted after a local audio Started event,
or an active output's matching playback report with advancing position.
The plugin animates the Radio key until that operation succeeds, then
returns to the main screen. Errors keep the Functions screen available.
## OpenDeck
The native Rust [OpenDeck integration](../integrations/opendeck/README.md)
targets Stream Deck Neo and OpenDeck 2.14.2 on Windows, macOS and Linux.
It renders eight 96 × 96 key images and a 248 × 58 Infobar, and maintains its
own player/device screens within one OpenDeck profile.
The API limits connections, command queues, request IDs, message sizes,
authentication time and slow writes. A slow plugin cannot hold up terminal
rendering: snapshots use a latest-value watch channel. It has no authority
to pair, revoke or otherwise change trusted-device membership.
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "furumi-control-protocol"
version = "0.1.0"
edition = "2024"
rust-version = "1.97"
license = "WTFPL"
[dependencies]
directories = "6"
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
serde_json = "1"
+203
View File
@@ -0,0 +1,203 @@
//! Versioned, device-local control API. This is not a device-sync wire protocol.
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
pub const API_VERSION: u16 = 1;
pub const MAX_MESSAGE_BYTES: usize = 2 * 1024 * 1024;
/// Third-octave levels, from 20 Hz to 20 kHz, quantized to 0..=255.
pub const SPECTRUM_BANDS: usize = 31;
pub fn discovery_path() -> Option<PathBuf> {
directories::ProjectDirs::from("", "", "furumi")
.map(|dirs| dirs.data_local_dir().join("control-endpoint.json"))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Discovery {
pub api_version: u16,
pub port: u16,
pub token: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Snapshot {
pub api_version: u16,
#[serde(default, skip_serializing_if = "is_false")]
pub spectrum_supported: bool,
pub revision: u64,
pub updated_at_ms: u64,
pub role: Role,
pub self_device_id: String,
pub active_device_id: Option<String>,
pub active_device_name: Option<String>,
pub playing: bool,
pub paused: bool,
pub position_secs: f64,
pub duration_secs: f64,
pub volume: u8,
pub shuffle: bool,
pub repeat: Repeat,
pub radio: Radio,
/// Optional for backward compatibility with local API servers predating
/// remote command acknowledgement. This is not a device-sync wire field.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_command: Option<RemoteCommand>,
pub track: Option<Track>,
pub devices: Vec<Device>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Role {
Active,
Control,
Jam,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Repeat {
#[default]
Off,
All,
One,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Radio {
pub id: u64,
pub state: RadioState,
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RadioState {
#[default]
Idle,
Searching,
Starting,
Playing,
Failed,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RemoteCommand {
pub id: u64,
pub state: RemoteCommandState,
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RemoteCommandState {
#[default]
Idle,
Pending,
Confirmed,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Track {
/// Stable playback identity, including podcast episodes (never a row ID).
pub key: String,
pub title: String,
pub artist: String,
pub album: String,
pub year: Option<i32>,
/// Personal library state for this track. Absent on older servers and
/// when the current item cannot be liked.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub liked: Option<bool>,
/// Opaque reference; clients cannot ask the server to read arbitrary paths.
pub artwork_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Device {
pub id: String,
pub name: String,
pub is_self: bool,
pub active: bool,
pub online: bool,
pub can_transfer: bool,
pub unavailable_reason: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientMessage {
Authenticate {
token: String,
api_version: u16,
},
Command {
id: String,
command: Command,
},
/// Local to this authenticated connection. Only request after the server
/// advertises spectrum_supported.
SubscribeSpectrum {
enabled: bool,
},
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Command {
PlayPause,
Next,
Previous,
Seek {
seconds: i64,
},
VolumeUp,
VolumeDown,
ToggleShuffle,
CycleRepeat,
StartRadio,
SetLiked {
track_key: String,
liked: bool,
},
Transfer {
device_id: String,
},
Artwork {
artwork_id: String,
#[serde(default, skip_serializing_if = "is_false")]
federation: bool,
},
}
fn is_false(value: &bool) -> bool {
!*value
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerMessage {
Snapshot {
snapshot: Box<Snapshot>,
},
/// A new epoch invalidates visual history. No bands means clear the display.
/// Only explicit subscribers receive this message.
Spectrum {
epoch: u64,
sequence: u64,
bands: Option<[u8; SPECTRUM_BANDS]>,
},
/// `accepted` means dispatched locally, not acknowledged by a remote engine.
Result {
id: String,
accepted: bool,
error: Option<String>,
},
Artwork {
id: String,
artwork_id: String,
png_base64: Option<String>,
},
}
+5
View File
@@ -0,0 +1,5 @@
/.research-opendeck/
/target/
/dist/
/dist-*/
/preview/
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "furumi-opendeck"
version = "0.1.0"
edition = "2024"
rust-version = "1.97"
license = "WTFPL"
description = "Native Rust Furumi control surface for OpenDeck and Stream Deck Neo"
[dependencies]
anyhow = "1"
base64 = "0.22"
fontdue = "0.9"
furumi-control-protocol = { path = "../control-protocol" }
futures-util = "0.3"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tempfile = "3"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "fs"] }
tokio-tungstenite = "0.28"
+233
View File
@@ -0,0 +1,233 @@
# Furumi for OpenDeck / Stream Deck Neo
A native Rust plugin for **OpenDeck 2.14.2** on Windows, Linux and macOS. It
uses OpenAction's WebSocket protocol directly; no Node.js or USB access is
needed. OpenDeck owns the hardware and hosts the local settings inspector.
## Install
1. Download Furumi and the plugin ZIP for your operating system from the
[same release](https://github.com/Furumi-stack/furumi-tui/releases).
2. Start Furumi. OpenDeck discovers the running player automatically.
3. In OpenDeck Settings, choose **Open config directory**. Extract the
`org.furumi.opendeck.sdPlugin` folder into the `plugins` subdirectory and
restart OpenDeck.
4. Create a **Furumi** profile. Place **Furumi cell** on each of the eight LCD
keys and **Furumi now playing** on the Infobar.
| Release asset | Included architectures |
| --- | --- |
| `furumi-opendeck-windows-<version>.zip` | x86_64 |
| `furumi-opendeck-macos-<version>.zip` | Intel and Apple Silicon |
| `furumi-opendeck-linux-<version>.zip` | x86_64 and ARM64 (GNU) |
OpenDeck selects the executable for the current architecture through
`CodePaths` in the bundled manifest. The release's `SHA256SUMS` includes all
three plugin archives.
To build a package for your own machine, run
`cargo build -p furumi-opendeck --release --locked` and then
`pwsh -File integrations/opendeck/package.ps1` from the repository root.
### Optional complete profile
Instead of dragging nine actions, close OpenDeck and generate a **new** profile:
```text
furumi-opendeck --write-profile sd-SERIAL /path/to/opendeck/config/profiles/sd-SERIAL/Furumi.json
```
Create the destination device directory first. Find the `sd-SERIAL` directory
in OpenDeck's existing `profiles` directory. The generator uses `create_new`
and refuses to overwrite an existing profile. It never edits your selected
profile or settings. Start OpenDeck and select Furumi. This is OpenDeck's JSON
profile format, not Elgato's `.streamDeckProfile` archive.
On Windows invoke the packaged target-specific `.exe` (or
`target/debug/furumi-opendeck.exe` while developing). On macOS/Linux use `./`
and the corresponding target-specific executable. Use a native OpenDeck
installation initially; sandboxed Flatpak distributions may require access to
Furumi's data directory and localhost, which is not configured by this plugin.
## Controls and screens
| Album cover / Functions | Previous track | Play / pause | Next track |
| --- | --- | --- | --- |
| Cycle repeat | Toggle shuffle | Seek −10 seconds | Seek +30 seconds |
All keys are authored at **96 × 96 px**. ACTIVE uses muted blue `#2b465a`,
CONTROL uses ochre `#524825` and JAM uses plum `#473451`. Phosphor Fill
icons use pale foregrounds on these dark backgrounds. The first key displays
the full release cover and opens Functions. A music-note icon appears when a cover
is unavailable. The Devices key inside Functions shows the role and current
audio owner.
The top row of Functions starts with **Like**, **Devices**, and **Radio**.
The back caret is at the bottom right. The Like key sits directly under the
album-cover key, so two taps on that physical key like the playing track.
A filled heart marks a liked track. To remove the like, tap the heart and let
the fill fade for three seconds, or tap again during the fade to remove it
immediately. Leaving Functions or changing tracks cancels a pending fade.
After Furumi saves the change, the heart shows the new state for half a second
and the deck returns to playback. The heart is dimmed for podcast episodes
and when the connected player does not supply a liked state.
Radio starts Furumi's similarity
radio; its key shows an animated spinner while local/federation results are
collected and the first track is prepared. It returns to the player only for a
new radio operation that Furumi reports as actually playing, never merely on
command acceptance. A failed operation leaves an English error notice. Back
remains available while radio starts. Repeat cycles Off → All → One. Enabled
Repeat and Shuffle keys have a **4 px rounded border**, inset 4 px from the
edge. Repeat One also shows a `1` inside the loop.
Devices opens a screen with six online trusted devices, a next-page key and a
back key. Each key shows the device's name at 16 px. Short names stay centered.
Long names scroll horizontally at 20 px/s and pause for two seconds at each
end. Opening a page starts each name at its beginning. The active output has
a blue background and check mark. An incompatible
target is dimmed; it cannot be selected. A press captures the device ID, so a
list update while the key is down cannot transfer to a different device.
Transfer is immediate, with no confirmation dialog. Pending transfer blocks
repeat commands, then returns to playback when Furumi reports the new owner.
That ownership report **does not prove that the remote audio engine has started**.
The local API currently acknowledges dispatch, not remote playback completion.
An explicit rejection or timeout appears temporarily in the Infobar.
Back from Devices returns to Functions. Navigation never changes the OpenDeck
profile or overwrites unrelated actions.
Each physical deck has its own navigation and pressed-key state. Leaving the
profile removes its contexts. If Furumi exits, keys turn grey and the Infobar
shows **Furumi offline**. The plugin reconnects automatically and never
replays old commands across a disconnect.
The Infobar is **248 × 58 px**, with content inset 8 px horizontally / 4 px
vertically. A 26 px metadata marquee runs on the left; elapsed time and duration
are fixed on the right, and a **6 px progress line** runs along the bottom.
Long podcast durations widen the time column instead of overlapping text.
The marquee pauses for two seconds and moves at 25 px/s. Metadata includes title,
artist, album and year. Updates are capped at 10 FPS, and unchanged key images
are not resent. Position is extrapolated only briefly between fresh snapshots.
## Preview and tests
```text
cargo run -p furumi-opendeck -- --preview integrations/opendeck/preview
cargo fmt -p furumi-opendeck -- --check
cargo check -p furumi-opendeck --all-targets
cargo test -p furumi-opendeck --all-targets
cargo clippy -p furumi-opendeck --all-targets
```
The preview command uses exactly the runtime renderer and writes native-size
buttons/Infobars, eight screen assemblies and sampled marquee frames. The synthetic
cover fixture is deliberately original and is not an included music album. Screen
assemblies are schematic; they do not claim measured millimetre positions for
the physical LCD windows. Tests include a temporary authenticated Furumi server
and a temporary OpenDeck WebSocket host, without audio, real profiles or peers.
Network sandboxes that block localhost connections must allow loopback for this
test. USB hardware and actual OpenDeck installation still require manual QA.
## Remote playback confirmation
In CONTROL mode, a pending remote playback command makes Play/Pause grey and
shows a small animated indicator in its bottom-right corner. The main glyph
continues to reflect the last confirmed playback state. Local API acceptance
means dispatch, not successful remote playback, and does not clear the indicator.
The authoritative pending state also covers commands issued through Furumi's
keyboard or another local client. While it is pending, playback commands,
including radio, are blocked on both key press and release. Navigation and
device transfer remain available. The local latch is shared by all attached
decks, preventing rapid repeated commands before the next state snapshot.
A new confirmed/failed operation, local rejection, owner change or disconnect
releases the corresponding local wait. A bounded 45-second fallback prevents a
broken acknowledgement stream from locking the plugin indefinitely. Failure
shows a short English notice. JAM behaviour is unchanged. Older local API
servers that omit `remote_command` retain their previous behaviour, without
waiting for an acknowledgement field they cannot publish. This optional field
belongs only to the local control API; no device-sync wire format was changed.
## Artwork on demand
The cover key has a neutral `#202a33` background, a thin rounded frame and an
original Phosphor Fill music-note icon when no cover is available. This is the
same in ACTIVE, CONTROL, JAM and offline mode. A separate animated loading badge
indicates an outstanding request. A successful cover is shown cleanly, without
icons, tint or labels. Pressing the key opens Functions even while artwork is
loading or missing; offline navigation is available too.
Artwork is requested only when key0 is attached to a visible Player screen,
or a visible Previous/Repeat/Shuffle key needs its part of enabled 2×2 artwork.
A background plugin, an Infobar alone and the Functions/Devices screens
do not trigger federation requests. Returning to Player or attaching the key
after a snapshot rechecks demand. Requests use the additive local API flag
`federation: true`; the existing local API request defaults to local-only when
the flag is omitted. No personal-device synchronization protocol was changed.
The request ID, artwork identity and playback generation must all match before
a reply is accepted, including A → B → A track changes. Missing artwork,
request rejection or a 35-second timeout restores the neutral key and does not
retry on each playback snapshot. Late artwork replies are ignored. Image loading
never blocks playback commands or clears a pending remote transport operation.
The preview command also writes `artwork-states.png`, showing the neutral,
loading and ready states at their native 96×96 resolution.
## Shared appearance settings
Select any Furumi action in OpenDeck to open the same three global options.
Defaults preserve the plain Infobar and single cover key:
- **Infobar background** offers **None**, **Spectrogram** and **Bars**. The
spectrogram scrolls behind the title. Bars displays 31 fixed frequency bands
with bass on the left and treble on the right. Both use blue and teal for the
middle of the audio level range and amber for peaks. They follow local output
at up to 10 Hz while the Infobar is visible. Control and Jam guests use the
plain background. A pause freezes the picture. Stop, seek, track changes and
output handoff clear it. Time and progress have a separate solid background.
Switching between the two visualizations keeps the current audio history.
- **2×2 album art:** spans the left four keys while retaining their bindings.
Previous sits at the upper right of its tile, Repeat at the lower left and
Shuffle at the lower right. Their 19 px glyphs have a thin contrasting
contour directly over the art. Enabled Repeat/Shuffle alone add a solid
role-accent corner triangle; Repeat One retains its numeral. The first tile
stays clean. Each 96 px crop starts at 0 or 130 in a 226 px square, skipping
34 px (about 5 mm) of art along each axis. Previews show the measured 6 mm
gaps between the 14 mm key screens. The plugin prepares both cover sizes once
per image.
- **Invert colors:** black button and Infobar bases with muted blue, amber or
purple role accents. Menus, device selection and disabled states remain
distinct; release artwork is unchanged.
Open inspectors stay synchronized. The Rust runtime serializes settings
patches, preserving unknown global fields rather than replacing the object.
Older saved OpenDeck profiles retain their old inspector path. With OpenDeck
closed, run `furumi-opendeck --upgrade-profile /path/to/Furumi.json` to add the
common inspector without changing bindings (a backup is made). Alternatively,
reassign one existing Furumi action to expose one settings entry point.
`infobar-backgrounds.png` compares Spectrogram and Bars at native resolution for
three simulated audio samples. `appearance-options.png` shows the complete
deck. `album-2x2-layout.png` and `album-overlay-controls.png` show the cover
with physical key spacing and the different Repeat and Shuffle states.
## Compatibility and license
Verified against OpenDeck tag `v2.14.2`, commit
`3ddecc1ce8952a423916cf066724356267b97410`: `elgato.rs` handles the **Infobar**
controller via `setImage` with 248 × 58 image data. This deliberately does not
use newer Elgato SDK 3's **Neo** layout controller. Official Elgato software is
not a supported host for this version of the plugin.
All interface labels and status messages are English. Track metadata and user
device names are displayed in their original language; the embedded font covers
Latin and Cyrillic without relying on OS-installed fonts.
The plugin uses the WTFPL v2 license. Its embedded DejaVu Sans font provides
Latin and Cyrillic text on all three platforms. [Font license](assets/FONT-LICENSE.txt)
The controls use Phosphor Fill under the MIT license. The plugin embeds masks
rasterized from the original SVGs. [Phosphor icons](https://github.com/phosphor-icons/core),
[icon license](assets/PHOSPHOR-LICENSE.txt)
Binary file not shown.
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Phosphor Icons
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96"><rect width="96" height="96" rx="12" fill="#2b465a"/><g color="#d0dce3"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="#d0dce3"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg></g></svg>

After

Width:  |  Height:  |  Size: 509 B

@@ -0,0 +1,49 @@
# Embedded Phosphor icon atlas
The Rust runtime decodes `phosphor-atlas.png` once and uses its alpha channel
as colourable masks. It does not require Node, an SVG parser, system icons or
network access.
- `phosphor-fill/`: unmodified original SVGs from the official
[Phosphor core repository](https://github.com/phosphor-icons/core/tree/main/assets/fill).
- `phosphor-regular/heart.svg`: the matching outline for the Like key. Its
silhouette aligns with the filled heart throughout the removal animation.
- `phosphor-atlas.svg`: editable named elements at their production placement.
- `phosphor-atlas.json`: tile names, offsets, source URLs and original SHA-256.
- `../PHOSPHOR-LICENSE.txt`: unmodified MIT license for the source icons.
- `build-atlas.cjs`: optional authoring script, using **`@resvg/resvg-js` 2.6.2**.
That package is required only to regenerate the assets, not to build or run
the Rust plugin.
Every tile is 96×96 pixels. Main glyph viewport: 56×56 centered at (48,48).
Seek viewport: 48×48 centered at (48,34). Radio/devices: 48×48 at (48,32).
Back: 36×36 caret-left at (48,48). Next page: 28×28 caret-right at (48,39).
Check/unavailable: 20×20 at (80,13). Spinner-gap: eight 45° rotations of the
original 48×48 Fill icon centered at (48,32).
The missing-cover `Album` mask uses the original **music-note-simple-fill**
glyph. Its neutral frame is a separate 2 px `CoverFrame` mask. The loading badge
uses the same authentic Phosphor spinner as the transport acknowledgement UI.
`EnabledFrame` is the only custom shape: a rounded 4px outline inset 4px from
every tile edge. Its outside corner radius is 10 px (centerline SVG radius 8 px).
The frame is an independent mask; the renderer chooses its colour and whether
it is shown. Phosphor glyph paths have not been redrawn or simplified.
## Regenerate
Install the pinned rasterizer in a separate authoring directory and make it
available through Node's standard `NODE_PATH`. From the repository root, using
PowerShell 7 on Windows, macOS or Linux:
```powershell
npm install --prefix ./output/icon-authoring --no-audit --no-fund @resvg/resvg-js@2.6.2
$env:NODE_PATH = (Resolve-Path ./output/icon-authoring/node_modules).Path
node ./integrations/opendeck/assets/icons/build-atlas.cjs
```
The script validates that every mask is nonempty, every spinner frame leaves
the label area clear, and the enabled frame retains its full four-pixel inset.
It writes the PNG, named SVG, JSON metadata and host launcher icon. Regeneration
with version 2.6.2 was checked to produce identical SHA-256 hashes for all four
outputs. Individual original SVG hashes are recorded in the generated JSON.
@@ -0,0 +1,173 @@
// Authoring tool only. The compiled Rust plugin has no SVG or Node dependency.
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { Resvg } = require('@resvg/resvg-js');
const tileSize = 96;
const columns = 8;
const atlasWidth = 768;
const atlasHeight = 384;
// Enum order in src/icons.rs and atlas order must remain identical.
// Columns: name, Phosphor source name, viewport size, centre x, centre y.
const specs = [
['Previous', 'skip-back', 56, 48, 48],
['Play', 'play', 56, 48, 48],
['Pause', 'pause', 56, 48, 48],
['Next', 'skip-forward', 56, 48, 48],
['Repeat', 'repeat', 56, 48, 48],
['RepeatOne', 'repeat-once', 56, 48, 48],
['Shuffle', 'shuffle', 56, 48, 48],
['Back', 'caret-left', 36, 48, 48],
['SeekBack', 'rewind', 48, 48, 34],
['SeekForward', 'fast-forward', 48, 48, 34],
['Radio', 'radio', 48, 48, 32],
['Devices', 'devices', 48, 48, 32],
['NextPage', 'caret-right', 28, 48, 39],
['Album', 'music-note-simple', 56, 48, 48],
['Check', 'check', 20, 80, 13],
['Unavailable', 'prohibit', 20, 80, 13],
['Heart', 'heart', 56, 48, 48, 'regular'],
['HeartFill', 'heart', 56, 48, 48],
['CoverFrame', null, 0, 0, 0],
['EnabledFrame', null, 0, 0, 0],
];
function glyph(name, size, centreX, centreY, weight = 'fill') {
const filename = path.join(__dirname, `phosphor-${weight}`, `${name}.svg`);
const original = fs.readFileSync(filename, 'utf8');
// Preserve the official paths. Only set viewport, placement and colour.
return original.replace(/<svg\b([^>]*)>/, (_, attributes) => {
const retained = attributes.replace(
/\s(?:width|height|x|y|color)="[^"]*"/g,
'',
);
const x = centreX - size / 2;
const y = centreY - size / 2;
return `<svg${retained} width="${size}" height="${size}" x="${x}" y="${y}" color="white">`;
});
}
const tiles = specs.map(([id, name, size, centreX, centreY, weight]) => ({
id,
// The frame is custom: 4 px outside inset, 4 px stroke, outside radius 10 px.
content: name
? glyph(name, size, centreX, centreY, weight)
: id === 'CoverFrame'
? '<rect x="5" y="5" width="86" height="86" rx="9" fill="none" stroke="white" stroke-width="2"/>'
: '<rect x="6" y="6" width="84" height="84" rx="8" fill="none" stroke="white" stroke-width="4"/>',
}));
for (let step = 0; step < 8; step++) {
tiles.push({
id: `Spinner${step}`,
content: `<g transform="rotate(${step * 45} 48 32)">${glyph('spinner-gap', 48, 48, 32)}</g>`,
});
}
let svg = [
'<svg xmlns="http://www.w3.org/2000/svg" width="768" height="384" viewBox="0 0 768 384">',
'<title>Furumi / Phosphor alpha atlas</title>',
'<desc>96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill and Regular SVG geometry. Custom frames.</desc>',
].join('');
const metadata = [];
tiles.forEach((tile, index) => {
const x = (index % columns) * tileSize;
const y = Math.floor(index / columns) * tileSize;
svg += `<svg id="${tile.id}" x="${x}" y="${y}" width="96" height="96" viewBox="0 0 96 96">${tile.content}</svg>`;
metadata.push({ name: tile.id, index, x, y, width: tileSize, height: tileSize });
});
svg += '</svg>';
const raster = new Resvg(svg).render();
if (raster.width !== atlasWidth || raster.height !== atlasHeight) {
throw new Error('Unexpected atlas dimensions');
}
// Cache pixels once: the renderer's getter creates a fresh buffer each time.
const pixels = raster.pixels;
const alpha = (x, y) => pixels[(y * raster.width + x) * 4 + 3];
for (const tile of metadata) {
let visible = 0;
for (let y = 0; y < tileSize; y++) {
for (let x = 0; x < tileSize; x++) {
if (alpha(tile.x + x, tile.y + y)) visible++;
}
}
if (!visible) throw new Error(`Empty mask: ${tile.name}`);
if (tile.name.startsWith('Spinner')) {
for (let y = 68; y < tileSize; y++) {
for (let x = 0; x < tileSize; x++) {
if (alpha(tile.x + x, tile.y + y)) {
throw new Error('Spinner overlaps label');
}
}
}
}
}
const frame = metadata.find(tile => tile.name === 'EnabledFrame');
for (let position = 0; position < tileSize; position++) {
for (let inset = 0; inset < 4; inset++) {
const top = alpha(frame.x + position, frame.y + inset);
const bottom = alpha(frame.x + position, frame.y + 95 - inset);
const left = alpha(frame.x + inset, frame.y + position);
const right = alpha(frame.x + 95 - inset, frame.y + position);
if (top || bottom || left || right) {
throw new Error('Enabled frame violates 4px full inset');
}
}
}
const sources = ['fill', 'regular'].flatMap(weight => {
const directory = `phosphor-${weight}`;
const files = fs.readdirSync(path.join(__dirname, directory))
.filter(name => name.endsWith('.svg'))
.sort();
return files.map(filename => {
const file = `${directory}/${filename}`;
const upstream = weight === 'regular' ? filename : filename.replace('.svg', '-fill.svg');
return {
file,
url: `https://raw.githubusercontent.com/phosphor-icons/core/main/assets/${weight}/${upstream}`,
sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(__dirname, file))).digest('hex'),
};
});
});
const atlasMetadata = {
width: atlasWidth,
height: atlasHeight,
tile_size: tileSize,
columns,
icons: metadata,
sources,
license: 'MIT',
license_file: '../PHOSPHOR-LICENSE.txt',
};
fs.writeFileSync(path.join(__dirname, 'phosphor-atlas.svg'), svg + '\n');
fs.writeFileSync(path.join(__dirname, 'phosphor-atlas.png'), raster.asPng());
fs.writeFileSync(
path.join(__dirname, 'phosphor-atlas.json'),
JSON.stringify(atlasMetadata, null, 2) + '\n',
);
// The host-side launcher icon uses the same genuine Phosphor Play glyph.
const launcherGlyph = glyph('play', 56, 48, 48).replace(
'color="white"',
'color="#d0dce3"',
);
const launcher = [
'<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">',
'<rect width="96" height="96" rx="12" fill="#2b465a"/>',
`<g color="#d0dce3">${launcherGlyph}</g></svg>\n`,
].join('');
fs.writeFileSync(path.join(__dirname, '../icon.svg'), launcher);
console.log(`Generated ${tiles.length} named masks, 768×384 transparent atlas and host icon.`);
@@ -0,0 +1,336 @@
{
"width": 768,
"height": 384,
"tile_size": 96,
"columns": 8,
"icons": [
{
"name": "Previous",
"index": 0,
"x": 0,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "Play",
"index": 1,
"x": 96,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "Pause",
"index": 2,
"x": 192,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "Next",
"index": 3,
"x": 288,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "Repeat",
"index": 4,
"x": 384,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "RepeatOne",
"index": 5,
"x": 480,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "Shuffle",
"index": 6,
"x": 576,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "Back",
"index": 7,
"x": 672,
"y": 0,
"width": 96,
"height": 96
},
{
"name": "SeekBack",
"index": 8,
"x": 0,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "SeekForward",
"index": 9,
"x": 96,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "Radio",
"index": 10,
"x": 192,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "Devices",
"index": 11,
"x": 288,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "NextPage",
"index": 12,
"x": 384,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "Album",
"index": 13,
"x": 480,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "Check",
"index": 14,
"x": 576,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "Unavailable",
"index": 15,
"x": 672,
"y": 96,
"width": 96,
"height": 96
},
{
"name": "Heart",
"index": 16,
"x": 0,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "HeartFill",
"index": 17,
"x": 96,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "CoverFrame",
"index": 18,
"x": 192,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "EnabledFrame",
"index": 19,
"x": 288,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner0",
"index": 20,
"x": 384,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner1",
"index": 21,
"x": 480,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner2",
"index": 22,
"x": 576,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner3",
"index": 23,
"x": 672,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner4",
"index": 24,
"x": 0,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner5",
"index": 25,
"x": 96,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner6",
"index": 26,
"x": 192,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner7",
"index": 27,
"x": 288,
"y": 288,
"width": 96,
"height": 96
}
],
"sources": [
{
"file": "phosphor-fill/caret-left.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/caret-left-fill.svg",
"sha256": "a6300d93ee3016043fe02af787421093bedd301a0da992337d07b16404e65fa5"
},
{
"file": "phosphor-fill/caret-right.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/caret-right-fill.svg",
"sha256": "c62278a701f1e4c08f424ce4b5cac69c8adb23b496dae489d5545ea7e6c019ef"
},
{
"file": "phosphor-fill/check.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/check-fill.svg",
"sha256": "d114007dc371976dc3e8f4ebc59c5aef429fae59ae58d56acdf231a52b4700be"
},
{
"file": "phosphor-fill/devices.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/devices-fill.svg",
"sha256": "9198a600c051f27d61947e0d4558eb680f10fd0ff21147ce719c1cb0180c007f"
},
{
"file": "phosphor-fill/fast-forward.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/fast-forward-fill.svg",
"sha256": "8be39d806d46384a635c53ffef51e9c19f91fcbb54901fc52c59ee290edbaf8b"
},
{
"file": "phosphor-fill/heart.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/heart-fill.svg",
"sha256": "d90560d4f762f1b345bd2322cd1ef696926ffa74b0c1396933b6d926faf8341e"
},
{
"file": "phosphor-fill/music-note-simple.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/music-note-simple-fill.svg",
"sha256": "929c4c4c0c3213c914e59e54d261f020310fc77cb19776626f199db26fd7d81a"
},
{
"file": "phosphor-fill/pause.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/pause-fill.svg",
"sha256": "156d3cdfa5cea803caec50b35f49bc635070c8bd84e7fe78df94b025017ccee1"
},
{
"file": "phosphor-fill/play.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/play-fill.svg",
"sha256": "6d2a75bc5700a68dec50516ebae121c307807e4e6fcca5c863e5b4af006df880"
},
{
"file": "phosphor-fill/prohibit.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/prohibit-fill.svg",
"sha256": "f4082e6bde36411618d4da65fe087cd3b746bb0e8070fec3d2e11b5aee059675"
},
{
"file": "phosphor-fill/radio.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/radio-fill.svg",
"sha256": "7dda166865035ef1b9f38e667b54ae65add809f0fba7791961290fd566b2c68c"
},
{
"file": "phosphor-fill/repeat-once.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/repeat-once-fill.svg",
"sha256": "6fe280758047324c9a7bc55b4b8291b5dca76082cc444351f52a650751d6a41c"
},
{
"file": "phosphor-fill/repeat.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/repeat-fill.svg",
"sha256": "0ccdc4397cd7c1e528c571d6ba3fb6764043d791b3de0ac86c6eaf5edb3a8ce6"
},
{
"file": "phosphor-fill/rewind.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/rewind-fill.svg",
"sha256": "beb5b9c00dcf99c2c7f0849ab17fe25ef4f1893aa02c71fb9876be0df743408d"
},
{
"file": "phosphor-fill/shuffle.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/shuffle-fill.svg",
"sha256": "4e3b3d19192ae67ae051e06767e42f69cfb1f33c90c1c39d6387fe3ca55aa164"
},
{
"file": "phosphor-fill/skip-back.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/skip-back-fill.svg",
"sha256": "65a2d664196ad28fff7288ed7a1870f508fdb922334ad1a49c54586dae7592d7"
},
{
"file": "phosphor-fill/skip-forward.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/skip-forward-fill.svg",
"sha256": "2f13f5cbeab47627d30782e7942001e7f80f7da993df053d3be2b8c6cb737ae2"
},
{
"file": "phosphor-fill/spinner-gap.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/spinner-gap-fill.svg",
"sha256": "6b13c6fe3926cfddf637e50ee92bc1d592369ee1d16e9e8b18e81fa3bc1ffbe8"
},
{
"file": "phosphor-fill/vinyl-record.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/vinyl-record-fill.svg",
"sha256": "92552f12cb4dd696977bd7fe04e2a7d35f57fb5e265de8091a817d45433e2296"
},
{
"file": "phosphor-regular/heart.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/regular/heart.svg",
"sha256": "312dee73d1d969631d5498012f619ccf4edbdf31e1be3e65af4f4f1b3ac1b2dd"
}
],
"license": "MIT",
"license_file": "../PHOSPHOR-LICENSE.txt"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="768" height="384" viewBox="0 0 768 384"><title>Furumi / Phosphor alpha atlas</title><desc>96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill and Regular SVG geometry. Custom frames.</desc><svg id="Previous" x="0" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M208,47.88V208.12a16,16,0,0,1-24.43,13.43L64,146.77V216a8,8,0,0,1-16,0V40a8,8,0,0,1,16,0v69.23L183.57,34.45A15.95,15.95,0,0,1,208,47.88Z"/></svg></svg><svg id="Play" x="96" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg></svg><svg id="Pause" x="192" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></svg></svg><svg id="Next" x="288" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M208,40V216a8,8,0,0,1-16,0V146.77L72.43,221.55A15.95,15.95,0,0,1,48,208.12V47.88A15.95,15.95,0,0,1,72.43,34.45L192,109.23V40a8,8,0,0,1,16,0Z"/></svg></svg><svg id="Repeat" x="384" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Z"/></svg></svg><svg id="RepeatOne" x="480" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Zm-88,40a8,8,0,0,0,8-8V104a8,8,0,0,0-11.58-7.16l-16,8a8,8,0,1,0,7.16,14.31l4.42-2.21V152A8,8,0,0,0,136,160Z"/></svg></svg><svg id="Shuffle" x="576" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="56" height="56" x="20" y="20" color="white"><path d="M237.66,178.34a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,200,208V192a72.15,72.15,0,0,1-57.65-30.14l-41.72-58.4A56.1,56.1,0,0,0,55.06,80H32a8,8,0,0,1,0-16H55.06a72.12,72.12,0,0,1,58.59,30.15l41.72,58.4A56.08,56.08,0,0,0,200,176V160a8,8,0,0,1,13.66-5.66ZM143,107a8,8,0,0,0,11.16-1.86l1.2-1.67A56.08,56.08,0,0,1,200,80V96a8,8,0,0,0,13.66,5.66l24-24a8,8,0,0,0,0-11.32l-24-24A8,8,0,0,0,200,48V64a72.15,72.15,0,0,0-57.65,30.14l-1.2,1.67A8,8,0,0,0,143,107Zm-30,42a8,8,0,0,0-11.16,1.86l-1.2,1.67A56.1,56.1,0,0,1,55.06,176H32a8,8,0,0,0,0,16H55.06a72.12,72.12,0,0,0,58.59-30.15l1.2-1.67A8,8,0,0,0,113,149Z"/></svg></svg><svg id="Back" x="672" y="0" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="36" height="36" x="30" y="30" color="white"><path d="M168,48V208a8,8,0,0,1-13.66,5.66l-80-80a8,8,0,0,1,0-11.32l80-80A8,8,0,0,1,168,48Z"/></svg></svg><svg id="SeekBack" x="0" y="96" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="48" height="48" x="24" y="10" color="white"><path d="M232,71.84V184.16a15.92,15.92,0,0,1-24.48,13.34L128,146.86v37.3a15.92,15.92,0,0,1-24.48,13.34L15.33,141.34a15.8,15.8,0,0,1,0-26.68L103.52,58.5A15.91,15.91,0,0,1,128,71.84v37.3L207.52,58.5A15.91,15.91,0,0,1,232,71.84Z"/></svg></svg><svg id="SeekForward" x="96" y="96" width="96" height="96" viewBox="0 0 96 96"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="48" height="48" x="24" y="10" color="white"><path d="M256,128a15.76,15.76,0,0,1-7.33,13.34L160.48,197.5A15.91,15.91,0,0,1,136,184.16v-37.3L56.48,197.5A15.91,15.91,0,0,1,32,184.16V71.Line truncated

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M168,48V208a8,8,0,0,1-13.66,5.66l-80-80a8,8,0,0,1,0-11.32l80-80A8,8,0,0,1,168,48Z"/></svg>

After

Width:  |  Height:  |  Size: 181 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M181.66,133.66l-80,80A8,8,0,0,1,88,208V48a8,8,0,0,1,13.66-5.66l80,80A8,8,0,0,1,181.66,133.66Z"/></svg>

After

Width:  |  Height:  |  Size: 193 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,40H40A16,16,0,0,0,24,56V200a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V56A16,16,0,0,0,216,40ZM205.66,85.66l-96,96a8,8,0,0,1-11.32,0l-40-40a8,8,0,0,1,11.32-11.32L104,164.69l90.34-90.35a8,8,0,0,1,11.32,11.32Z"/></svg>

After

Width:  |  Height:  |  Size: 308 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,72H208V64a24,24,0,0,0-24-24H40A24,24,0,0,0,16,64v96a24,24,0,0,0,24,24H152v8a24,24,0,0,0,24,24h48a24,24,0,0,0,24-24V96A24,24,0,0,0,224,72Zm8,120a8,8,0,0,1-8,8H176a8,8,0,0,1-8-8V96a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8Zm-96,16a8,8,0,0,1-8,8H88a8,8,0,0,1,0-16h40A8,8,0,0,1,136,208Zm80-96a8,8,0,0,1-8,8H192a8,8,0,0,1,0-16h16A8,8,0,0,1,216,112Z"/></svg>

After

Width:  |  Height:  |  Size: 437 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M256,128a15.76,15.76,0,0,1-7.33,13.34L160.48,197.5A15.91,15.91,0,0,1,136,184.16v-37.3L56.48,197.5A15.91,15.91,0,0,1,32,184.16V71.84A15.91,15.91,0,0,1,56.48,58.5L136,109.14V71.84A15.91,15.91,0,0,1,160.48,58.5l88.19,56.16A15.76,15.76,0,0,1,256,128Z"/></svg>

After

Width:  |  Height:  |  Size: 346 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M240,102c0,70-103.79,126.66-108.21,129a8,8,0,0,1-7.58,0C119.79,228.66,16,172,16,102A62.07,62.07,0,0,1,78,40c20.65,0,38.73,8.88,50,23.89C139.27,48.88,157.35,40,178,40A62.07,62.07,0,0,1,240,102Z"/></svg>

After

Width:  |  Height:  |  Size: 292 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M210.3,56.34l-80-24A8,8,0,0,0,120,40V148.26A48,48,0,1,0,136,184V50.75l69.7,20.91a8,8,0,1,0,4.6-15.32Z"/></svg>

After

Width:  |  Height:  |  Size: 201 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></svg>

After

Width:  |  Height:  |  Size: 287 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></svg>

After

Width:  |  Height:  |  Size: 290 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M200,128a71.69,71.69,0,0,1-15.78,44.91L83.09,71.78A71.95,71.95,0,0,1,200,128ZM56,128a71.95,71.95,0,0,0,116.91,56.22L71.78,83.09A71.69,71.69,0,0,0,56,128Zm180,0A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-20,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z"/></svg>

After

Width:  |  Height:  |  Size: 358 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M216,64H86.51L194.3,31.67a8,8,0,0,0-4.6-15.33l-160,48h0A8,8,0,0,0,24,72V192a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V80A16,16,0,0,0,216,64ZM104,176H64a8,8,0,0,1,0-16h40a8,8,0,0,1,0,16Zm0-32H64a8,8,0,0,1,0-16h40a8,8,0,0,1,0,16Zm0-32H64a8,8,0,0,1,0-16h40a8,8,0,0,1,0,16Zm64,56a32,32,0,1,1,32-32A32,32,0,0,1,168,168Z"/></svg>

After

Width:  |  Height:  |  Size: 412 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Zm-88,40a8,8,0,0,0,8-8V104a8,8,0,0,0-11.58-7.16l-16,8a8,8,0,1,0,7.16,14.31l4.42-2.21V152A8,8,0,0,0,136,160Z"/></svg>

After

Width:  |  Height:  |  Size: 528 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M24,128A72.08,72.08,0,0,1,96,56h96V40a8,8,0,0,1,13.66-5.66l24,24a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,192,88V72H96a56.06,56.06,0,0,0-56,56,8,8,0,0,1-16,0Zm200-8a8,8,0,0,0-8,8,56.06,56.06,0,0,1-56,56H64V168a8,8,0,0,0-13.66-5.66l-24,24a8,8,0,0,0,0,11.32l24,24A8,8,0,0,0,64,216V200h96a72.08,72.08,0,0,0,72-72A8,8,0,0,0,224,120Z"/></svg>

After

Width:  |  Height:  |  Size: 422 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M232,71.84V184.16a15.92,15.92,0,0,1-24.48,13.34L128,146.86v37.3a15.92,15.92,0,0,1-24.48,13.34L15.33,141.34a15.8,15.8,0,0,1,0-26.68L103.52,58.5A15.91,15.91,0,0,1,128,71.84v37.3L207.52,58.5A15.91,15.91,0,0,1,232,71.84Z"/></svg>

After

Width:  |  Height:  |  Size: 316 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M237.66,178.34a8,8,0,0,1,0,11.32l-24,24A8,8,0,0,1,200,208V192a72.15,72.15,0,0,1-57.65-30.14l-41.72-58.4A56.1,56.1,0,0,0,55.06,80H32a8,8,0,0,1,0-16H55.06a72.12,72.12,0,0,1,58.59,30.15l41.72,58.4A56.08,56.08,0,0,0,200,176V160a8,8,0,0,1,13.66-5.66ZM143,107a8,8,0,0,0,11.16-1.86l1.2-1.67A56.08,56.08,0,0,1,200,80V96a8,8,0,0,0,13.66,5.66l24-24a8,8,0,0,0,0-11.32l-24-24A8,8,0,0,0,200,48V64a72.15,72.15,0,0,0-57.65,30.14l-1.2,1.67A8,8,0,0,0,143,107Zm-30,42a8,8,0,0,0-11.16,1.86l-1.2,1.67A56.1,56.1,0,0,1,55.06,176H32a8,8,0,0,0,0,16H55.06a72.12,72.12,0,0,0,58.59-30.15l1.2-1.67A8,8,0,0,0,113,149Z"/></svg>

After

Width:  |  Height:  |  Size: 688 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M208,47.88V208.12a16,16,0,0,1-24.43,13.43L64,146.77V216a8,8,0,0,1-16,0V40a8,8,0,0,1,16,0v69.23L183.57,34.45A15.95,15.95,0,0,1,208,47.88Z"/></svg>

After

Width:  |  Height:  |  Size: 236 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M208,40V216a8,8,0,0,1-16,0V146.77L72.43,221.55A15.95,15.95,0,0,1,48,208.12V47.88A15.95,15.95,0,0,1,72.43,34.45L192,109.23V40a8,8,0,0,1,16,0Z"/></svg>

After

Width:  |  Height:  |  Size: 240 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z"/></svg>

After

Width:  |  Height:  |  Size: 571 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24ZM72,128a8,8,0,0,1-16,0,72.08,72.08,0,0,1,72-72,8,8,0,0,1,0,16A56.06,56.06,0,0,0,72,128Zm32,0a24,24,0,1,1,24,24A24,24,0,0,1,104,128Zm24,72a8,8,0,0,1,0-16,56.06,56.06,0,0,0,56-56,8,8,0,0,1,16,0A72.08,72.08,0,0,1,128,200Z"/></svg>

After

Width:  |  Height:  |  Size: 375 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M178,40c-20.65,0-38.73,8.88-50,23.89C116.73,48.88,98.65,40,78,40a62.07,62.07,0,0,0-62,62c0,70,103.79,126.66,108.21,129a8,8,0,0,0,7.58,0C136.21,228.66,240,172,240,102A62.07,62.07,0,0,0,178,40ZM128,214.8C109.74,204.16,32,155.69,32,102A46.06,46.06,0,0,1,78,56c19.45,0,35.78,10.36,42.6,27a8,8,0,0,0,14.8,0c6.82-16.67,23.15-27,42.6-27a46.06,46.06,0,0,1,46,46C224,155.61,146.24,204.15,128,214.8Z"/></svg>

After

Width:  |  Height:  |  Size: 489 B

@@ -0,0 +1,42 @@
{
"Name": "Furumi",
"Author": "Furumi contributors",
"Version": "0.1.0",
"Icon": "icon",
"Category": "Furumi",
"PropertyInspectorPath": "property-inspector.html",
"OS": [{ "Platform": "windows" }, { "Platform": "mac" }, { "Platform": "linux" }],
"CodePaths": {
"x86_64-pc-windows-msvc": "furumi-opendeck-x86_64-pc-windows-msvc.exe",
"x86_64-apple-darwin": "furumi-opendeck-x86_64-apple-darwin",
"aarch64-apple-darwin": "furumi-opendeck-aarch64-apple-darwin",
"x86_64-unknown-linux-gnu": "furumi-opendeck-x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu": "furumi-opendeck-aarch64-unknown-linux-gnu"
},
"CodePathWin": "furumi-opendeck-x86_64-pc-windows-msvc.exe",
"CodePathMac": "furumi-opendeck-aarch64-apple-darwin",
"CodePathLin": "furumi-opendeck-x86_64-unknown-linux-gnu",
"Actions": [
{
"UUID": "org.furumi.opendeck.cell",
"Name": "Furumi cell — fill the 8 Neo keys",
"Tooltip": "Place this action on all eight Neo keys. Position determines the function; the plugin switches player and device screens.",
"Icon": "icon",
"Controllers": ["Keypad"],
"PropertyInspectorPath": "property-inspector.html",
"SupportedInMultiActions": false,
"DisableAutomaticStates": true,
"States": [{ "Image": "icon", "ShowTitle": false }]
},
{
"UUID": "org.furumi.opendeck.infobar",
"Name": "Furumi now playing — Neo Infobar",
"Tooltip": "248×58 now playing, scrolling metadata, fixed time and a 6-pixel progress line. OpenDeck 2.14.2 Infobar controller.",
"Icon": "icon",
"Controllers": ["Infobar"],
"PropertyInspectorPath": "property-inspector.html",
"SupportedInMultiActions": false,
"States": [{ "Image": "icon", "ShowTitle": false }]
}
]
}
@@ -0,0 +1,35 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Furumi settings</title>
<style>
:root { color-scheme: dark; font: 13px system-ui,sans-serif; background:#24282e; color:#d0dce3; }
body { margin:16px; max-width:420px; }
h1 { font-size:16px; margin:0 0 18px; }
label { display:block; margin:0 0 16px; }
select { display:block; box-sizing:border-box; width:100%; margin-top:7px; padding:7px 9px; border:1px solid #536472; border-radius:5px; background:#202a33; color:inherit; }
.check { display:flex; align-items:center; gap:9px; }
input { accent-color:#81a8be; width:16px; height:16px; margin:0; }
small { display:block; line-height:1.5; color:#99acba; }
#status { margin-top:14px; min-height:20px; }
:disabled { opacity:.55; }
</style>
<script src="property-inspector.js" defer></script>
</head>
<body>
<h1>Furumi</h1>
<label>Infobar background
<select id="infobar-background" disabled>
<option value="none">None</option>
<option value="spectrogram">Spectrogram</option>
<option value="bars">Bars</option>
</select>
</label>
<label class="check"><input id="album-art-2x2" type="checkbox" disabled>2×2 album art</label>
<label class="check"><input id="invert-colors" type="checkbox" disabled>Invert colors</label>
<small>Applies to all Furumi keys and Infobars. Spectrogram and Bars use only audio playing on this computer.</small>
<small id="status" role="status">Connecting to OpenDeck…</small>
</body>
</html>
@@ -0,0 +1,65 @@
/* OpenDeck supplies this callback inside its local Property Inspector WebView. */
/* No remote scripts, Node runtime, filesystem reads or player credentials. */
'use strict';
let socket;
let inspectorContext;
let settings = {};
function send(event, payload) {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
socket.send(JSON.stringify({ event, context: inspectorContext, ...(payload === undefined ? {} : { payload }) }));
}
function elements() {
return {
background: document.getElementById('infobar-background'),
mosaic: document.getElementById('album-art-2x2'),
invert: document.getElementById('invert-colors'),
status: document.getElementById('status'),
};
}
function showSettings() {
const ui = elements();
ui.background.value = ['none', 'spectrogram', 'bars'].includes(settings.infobar_background) ? settings.infobar_background : 'none';
ui.mosaic.checked = settings.album_art_2x2 === true;
ui.invert.checked = settings.invert_colors === true;
for (const control of [ui.background, ui.mosaic, ui.invert]) control.disabled = false;
}
function change(field, value) {
if (field === 'infobar_background' && !['none', 'spectrogram', 'bars'].includes(value)) return;
// The native runtime is the single writer. A patch cannot clobber another
// inspector's fields or settings owned by a newer version of the plugin.
send('sendToPlugin', { event: 'preferencesPatch', patch: { [field]: value } });
elements().status.textContent = 'Saving…';
}
function connectElgatoStreamDeckSocket(port, uuid, registerEvent) {
inspectorContext = uuid;
socket = new WebSocket('ws://127.0.0.1:' + port);
socket.onopen = () => {
socket.send(JSON.stringify({ event: registerEvent, uuid }));
send('getGlobalSettings');
};
socket.onmessage = message => {
let event;
try { event = JSON.parse(message.data); } catch { return; }
if (event.event !== 'didReceiveGlobalSettings' &&
!(event.event === 'sendToPropertyInspector' && event.payload?.event === 'preferencesState')) return;
const received = event.payload && event.payload.settings;
settings = received && typeof received === 'object' && !Array.isArray(received) ? { ...received } : {};
elements().status.textContent = '';
showSettings();
};
socket.onclose = () => {
const ui = elements();
for (const control of [ui.background, ui.mosaic, ui.invert]) control.disabled = true;
ui.status.textContent = 'OpenDeck disconnected';
};
const ui = elements();
ui.background.onchange = () => change('infobar_background', ui.background.value);
ui.mosaic.onchange = () => change('album_art_2x2', ui.mosaic.checked);
ui.invert.onchange = () => change('invert_colors', ui.invert.checked);
}
+37
View File
@@ -0,0 +1,37 @@
param(
[string]$Target = '',
[string]$BuildProfile = 'release',
[string]$OutputDirectory = "$PSScriptRoot/dist"
)
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path "$PSScriptRoot/../..").Path
if (!$Target) {
$hostLine = & rustc -vV | Select-String '^host: '
$Target = $hostLine.ToString().Substring(6).Trim()
$binaryDirectory = Join-Path $repo "target/$BuildProfile"
} else {
$binaryDirectory = Join-Path $repo "target/$Target/$BuildProfile"
}
$extension = if ($Target -like '*windows*') { '.exe' } else { '' }
$binary = Join-Path $binaryDirectory "furumi-opendeck$extension"
if (!(Test-Path -LiteralPath $binary)) { throw "Build the plugin first; missing $binary" }
$bundle = Join-Path $OutputDirectory 'org.furumi.opendeck.sdPlugin'
$binaryName = "furumi-opendeck-$Target$extension"
if (Test-Path -LiteralPath $bundle) {
$packageFiles = @($binaryName, 'manifest.json', 'icon.svg', 'property-inspector.html', 'property-inspector.js', 'FONT-LICENSE.txt', 'PHOSPHOR-LICENSE.txt', 'README.md', 'LICENSE')
$extra = Get-ChildItem -LiteralPath $bundle -Force | Where-Object { $_.PSIsContainer -or $_.Name -notin $packageFiles }
if ($extra) { throw "The output bundle contains additional files. Choose a separate OutputDirectory: $bundle" }
}
New-Item -ItemType Directory -Force -Path $bundle | Out-Null
Copy-Item -LiteralPath $binary -Destination (Join-Path $bundle $binaryName)
Copy-Item -LiteralPath "$PSScriptRoot/assets/manifest.json" -Destination $bundle
Copy-Item -LiteralPath "$PSScriptRoot/assets/icon.svg" -Destination $bundle
Copy-Item -LiteralPath "$PSScriptRoot/assets/property-inspector.html" -Destination $bundle
Copy-Item -LiteralPath "$PSScriptRoot/assets/property-inspector.js" -Destination $bundle
Copy-Item -LiteralPath "$PSScriptRoot/assets/FONT-LICENSE.txt" -Destination $bundle
Copy-Item -LiteralPath "$PSScriptRoot/assets/PHOSPHOR-LICENSE.txt" -Destination $bundle
Copy-Item -LiteralPath "$PSScriptRoot/README.md" -Destination $bundle
Copy-Item -LiteralPath "$repo/LICENSE" -Destination $bundle
$archive = Join-Path $OutputDirectory "furumi-opendeck-$Target.zip"
Compress-Archive -LiteralPath $bundle -DestinationPath $archive -Force
Write-Output $archive
+65
View File
@@ -0,0 +1,65 @@
"""Combine the native OpenDeck bundles for one OS into an installable ZIP."""
import argparse
import json
import stat
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
BUNDLE = "org.furumi.opendeck.sdPlugin/"
TARGET_SUFFIX = {
"windows": "-windows-msvc",
"macos": "-apple-darwin",
"linux": "-linux-gnu",
}
def assemble(platform: str, inputs: Path, output: Path) -> None:
manifest = json.loads((Path(__file__).parent / "assets/manifest.json").read_bytes())
programs = {}
resources = None
for target, executable in manifest["CodePaths"].items():
if not target.endswith(TARGET_SUFFIX[platform]):
continue
source = inputs / f"furumi-opendeck-{target}.zip"
with ZipFile(source) as archive:
files = {
entry.filename: archive.read(entry)
for entry in archive.infolist()
if not entry.is_dir()
}
if json.loads(files[BUNDLE + "manifest.json"]) != manifest:
raise ValueError(f"{source} was built with a different plugin manifest")
program = BUNDLE + executable
programs[program] = files.pop(program)
if not programs[program]:
raise ValueError(f"Empty executable in {source}: {executable}")
if resources is None:
resources = files
elif files != resources:
raise ValueError(f"Shared plugin resources differ in {source}")
if resources is None:
raise ValueError(f"No {platform} executables in the plugin manifest")
output.parent.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(dir=output.parent) as staging:
staged = Path(staging) / output.name
with ZipFile(staged, "w") as archive:
for name, data in sorted((resources | programs).items()):
entry = ZipInfo(name)
entry.create_system = 3 # Record Unix permissions regardless of the build host.
mode = 0o755 if name in programs else 0o644
entry.external_attr = (stat.S_IFREG | mode) << 16
archive.writestr(entry, data, compress_type=ZIP_DEFLATED)
staged.replace(output)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("platform", choices=TARGET_SUFFIX)
parser.add_argument("inputs", type=Path, help="Directory containing native plugin ZIPs")
parser.add_argument("output", type=Path, help="Path of the resulting platform ZIP")
args = parser.parse_args()
assemble(args.platform, args.inputs, args.output)
+268
View File
@@ -0,0 +1,268 @@
//! Demand-driven cover state. A request is scoped to a playback generation,
//! including A → B → A, and can never revive an image from an older request.
use std::time::{Duration, Instant};
use base64::Engine as _;
use furumi_control_protocol::Snapshot;
use image::RgbImage;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(35);
pub const KEY_PIXELS: u32 = 96;
// A 6 mm gap corresponds to 41 pixels on a 14 mm, 96-pixel key.
pub const GAP_PX: u32 = 41;
pub const KEY_STRIDE: u32 = KEY_PIXELS + GAP_PX;
pub const PHYSICAL_MOSAIC_SIZE: u32 = KEY_PIXELS * 2 + GAP_PX;
// Trim slightly less art than the physical 6 mm spacers: about 5 mm per axis.
pub const ART_GAP_PX: u32 = 34;
pub const ART_STRIDE: u32 = KEY_PIXELS + ART_GAP_PX;
pub const MOSAIC_SIZE: u32 = KEY_PIXELS * 2 + ART_GAP_PX;
/// Both cover sizes share the lifetime of a single artwork response.
pub struct PreparedArt {
small: RgbImage,
square: RgbImage,
}
pub struct CoverReply<T> {
pub request_id: String,
pub artwork_id: String,
pub image: T,
}
impl CoverReply<String> {
/// Decode and resize on the image worker while the keys continue to accept input.
pub fn prepare(self) -> CoverReply<Option<PreparedArt>> {
let image = decode_png(&self.image).map(PreparedArt::new);
CoverReply {
request_id: self.request_id,
artwork_id: self.artwork_id,
image,
}
}
}
fn decode_png(encoded: &str) -> Option<RgbImage> {
let bytes = base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()?;
let mut reader =
image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(2048);
limits.max_image_height = Some(2048);
limits.max_alloc = Some(32 * 1024 * 1024);
reader.limits(limits);
reader.decode().ok().map(|image| image.into_rgb8())
}
impl PreparedArt {
pub fn new(image: RgbImage) -> Self {
let side = image.width().min(image.height());
let square = image::imageops::crop_imm(
&image,
(image.width() - side) / 2,
(image.height() - side) / 2,
side,
side,
);
Self {
small: image::imageops::resize(
&*square,
KEY_PIXELS,
KEY_PIXELS,
image::imageops::FilterType::Lanczos3,
),
square: image::imageops::resize(
&*square,
MOSAIC_SIZE,
MOSAIC_SIZE,
image::imageops::FilterType::Lanczos3,
),
}
}
pub fn small(&self) -> &RgbImage {
&self.small
}
pub fn square(&self) -> &RgbImage {
&self.square
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Identity {
track_key: String,
artwork_id: Option<String>,
}
#[derive(Debug)]
struct Pending {
request_id: String,
artwork_id: String,
generation: u64,
started: Instant,
}
#[derive(Default)]
pub struct Artwork {
identity: Option<Identity>,
generation: u64,
pending: Option<Pending>,
terminal: bool,
image: Option<PreparedArt>,
}
impl Artwork {
pub fn observe(&mut self, snapshot: Option<&Snapshot>) {
let identity = snapshot
.and_then(|s| s.track.as_ref())
.map(|track| Identity {
track_key: track.key.clone(),
artwork_id: track.artwork_id.clone(),
});
if identity != self.identity {
self.identity = identity;
self.generation = self.generation.wrapping_add(1);
self.pending = None;
self.terminal = false;
self.image = None;
}
}
pub fn needed(&self, visible: bool) -> Option<String> {
if !visible || self.terminal || self.pending.is_some() {
return None;
}
self.identity.as_ref()?.artwork_id.clone()
}
pub fn begin(&mut self, request_id: String, artwork_id: String, now: Instant) {
self.pending = Some(Pending {
request_id,
artwork_id,
generation: self.generation,
started: now,
});
}
pub fn matches(&self, id: &str, artwork_id: &str) -> bool {
self.pending.as_ref().is_some_and(|p| {
p.request_id == id && p.artwork_id == artwork_id && p.generation == self.generation
})
}
pub fn complete(&mut self, id: &str, artwork_id: &str, image: Option<PreparedArt>) {
if !self.matches(id, artwork_id) {
return;
}
self.pending = None;
self.terminal = true;
self.image = image;
}
pub fn reject(&mut self, id: &str) {
if self.pending.as_ref().is_some_and(|p| p.request_id == id) {
self.pending = None;
self.terminal = true;
self.image = None;
}
}
pub fn expire(&mut self, now: Instant) {
if self
.pending
.as_ref()
.is_some_and(|p| now.saturating_duration_since(p.started) >= REQUEST_TIMEOUT)
{
self.pending = None;
self.terminal = true;
self.image = None;
}
}
pub fn loading(&self) -> Option<Instant> {
self.pending.as_ref().map(|p| p.started)
}
#[cfg(test)]
pub fn image(&self) -> Option<&RgbImage> {
self.image.as_ref().map(PreparedArt::small)
}
pub fn prepared(&self) -> Option<&PreparedArt> {
self.image.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::preview::fixture;
#[test]
fn no_request_without_visible_cover_and_missing_is_terminal_for_this_generation() {
let mut s = fixture();
s.track.as_mut().unwrap().artwork_id = Some("art-A".into());
let mut art = Artwork::default();
art.observe(Some(&s));
assert_eq!(art.needed(false), None);
assert_eq!(art.needed(true), Some("art-A".into()));
art.begin("request-A".into(), "art-A".into(), Instant::now());
assert!(art.loading().is_some());
art.complete("request-A", "art-A", None);
assert!(art.image().is_none());
assert!(art.loading().is_none());
assert_eq!(art.needed(true), None);
art.observe(Some(&s));
assert_eq!(art.needed(true), None);
}
#[test]
fn returning_to_same_artwork_rejects_the_first_a_response_by_request_id() {
let now = Instant::now();
let mut s = fixture();
s.track.as_mut().unwrap().artwork_id = Some("same-cover".into());
let mut art = Artwork::default();
art.observe(Some(&s));
art.begin("A-first".into(), "same-cover".into(), now);
let original_key = s.track.as_ref().unwrap().key.clone();
s.track.as_mut().unwrap().key = "B".into();
art.observe(Some(&s));
s.track.as_mut().unwrap().key = original_key;
art.observe(Some(&s));
art.begin("A-new".into(), "same-cover".into(), now);
let image = RgbImage::new(96, 96);
art.complete(
"A-first",
"same-cover",
Some(PreparedArt::new(image.clone())),
);
assert!(art.image().is_none());
assert!(art.loading().is_some());
art.complete("A-new", "same-cover", Some(PreparedArt::new(image.clone())));
assert_eq!(art.image(), Some(&image));
}
#[test]
fn timeout_and_reject_clear_loading_without_retry_or_late_image() {
let now = Instant::now();
let mut s = fixture();
s.track.as_mut().unwrap().artwork_id = Some("art".into());
let mut art = Artwork::default();
art.observe(Some(&s));
art.begin("timeout".into(), "art".into(), now);
art.expire(now + REQUEST_TIMEOUT);
art.complete(
"timeout",
"art",
Some(PreparedArt::new(RgbImage::new(96, 96))),
);
assert!(art.image().is_none());
assert_eq!(art.needed(true), None);
s.track.as_mut().unwrap().key = "next".into();
art.observe(Some(&s));
art.begin("rejected".into(), "art".into(), now);
art.reject("other");
assert!(art.loading().is_some());
art.reject("rejected");
assert!(art.loading().is_none());
assert_eq!(art.needed(true), None);
}
}
+166
View File
@@ -0,0 +1,166 @@
//! Reconnecting authenticated local client. Commands are never replayed across
//! disconnects: a non-idempotent PlayPause must not become a second toggle.
use std::path::PathBuf;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use furumi_control_protocol::{
API_VERSION, ClientMessage, Discovery, MAX_MESSAGE_BYTES, ServerMessage, discovery_path,
};
use futures_util::{SinkExt, StreamExt};
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::tungstenite::{Message, protocol::WebSocketConfig};
#[derive(Debug)]
pub enum Update {
Message(Box<ServerMessage>),
Disconnected,
}
pub async fn run(
mut commands: mpsc::Receiver<ClientMessage>,
updates: mpsc::Sender<Update>,
endpoint_path: Option<PathBuf>,
spectrum: watch::Sender<Option<crate::spectrum::Frame>>,
) {
loop {
while commands.try_recv().is_ok() {}
if updates.is_closed() {
return;
}
let _ = session(&mut commands, &updates, endpoint_path.clone(), &spectrum).await;
spectrum.send_replace(None);
if updates.send(Update::Disconnected).await.is_err() {
return;
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
async fn session(
commands: &mut mpsc::Receiver<ClientMessage>,
updates: &mpsc::Sender<Update>,
endpoint_path: Option<PathBuf>,
spectrum: &watch::Sender<Option<crate::spectrum::Frame>>,
) -> Result<()> {
let path = endpoint_path
.or_else(discovery_path)
.context("Furumi data directory unavailable")?;
let bytes = tokio::fs::read(path).await?;
if bytes.len() > 4096 {
bail!("invalid discovery size");
}
let endpoint: Discovery = serde_json::from_slice(&bytes)?;
if endpoint.api_version != API_VERSION || endpoint.port == 0 {
bail!("unsupported local API version");
}
let config = WebSocketConfig::default()
.max_message_size(Some(MAX_MESSAGE_BYTES))
.max_frame_size(Some(MAX_MESSAGE_BYTES));
let (mut socket, _) = tokio::time::timeout(
Duration::from_secs(3),
tokio_tungstenite::connect_async_with_config(
format!("ws://127.0.0.1:{}", endpoint.port),
Some(config),
false,
),
)
.await??;
socket
.send(Message::text(serde_json::to_string(
&ClientMessage::Authenticate {
token: endpoint.token,
api_version: API_VERSION,
},
)?))
.await?;
// Only a valid snapshot establishes the authenticated session.
let first = tokio::time::timeout(Duration::from_secs(3), socket.next())
.await?
.context("Furumi disconnected")??;
let message: ServerMessage = serde_json::from_slice(&first.into_data())?;
if !matches!(&message,ServerMessage::Snapshot{snapshot} if snapshot.api_version==API_VERSION) {
bail!("missing initial snapshot");
}
updates.send(Update::Message(Box::new(message))).await?;
loop {
tokio::select! {
item=tokio::time::timeout(Duration::from_secs(4),socket.next()) => {
let message=item?.context("Furumi disconnected")??;
match message {
Message::Text(text)=> {
let message=serde_json::from_str(&text)?;
forward(message,updates,spectrum).await?;
},
Message::Close(_)=>return Ok(()),
Message::Ping(data)=> {socket.send(Message::Pong(data)).await?;},
_=>{}
}
}
command=commands.recv()=> {
let Some(command)=command else{return Ok(())};
tokio::time::timeout(Duration::from_secs(2),socket.send(Message::text(serde_json::to_string(&command)?))).await??;
}
}
}
}
async fn forward(
message: ServerMessage,
updates: &mpsc::Sender<Update>,
spectrum: &watch::Sender<Option<crate::spectrum::Frame>>,
) -> Result<()> {
match message {
ServerMessage::Spectrum {
epoch,
sequence,
bands,
} => {
spectrum.send_replace(Some(crate::spectrum::Frame {
epoch,
sequence,
bands,
}));
}
message => updates.send(Update::Message(Box::new(message))).await?,
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn spectrum_bursts_replace_latest_instead_of_queuing_before_command_results() {
let (updates, mut receiver) = mpsc::channel(1);
let (spectrum, latest) = watch::channel(None);
for sequence in 1..=1000 {
forward(
ServerMessage::Spectrum {
epoch: 1,
sequence,
bands: Some([99; 31]),
},
&updates,
&spectrum,
)
.await
.unwrap();
}
forward(
ServerMessage::Result {
id: "transport".into(),
accepted: true,
error: None,
},
&updates,
&spectrum,
)
.await
.unwrap();
assert!(
matches!(receiver.recv().await,Some(Update::Message(message)) if matches!(*message,ServerMessage::Result{..}))
);
assert_eq!(latest.borrow().as_ref().unwrap().sequence, 1000);
}
}
+86
View File
@@ -0,0 +1,86 @@
use furumi_control_protocol::Command;
use std::time::{Duration, Instant};
pub const REMOVE_DELAY: Duration = Duration::from_secs(3);
pub const SAVED_DISPLAY: Duration = Duration::from_millis(500);
pub const RESULT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub enum Phase {
Fading(Instant),
Sending,
Waiting(String, Instant),
Confirmed(Instant),
}
#[derive(Clone)]
pub struct Heart {
pub key: String,
pub liked: bool,
pub phase: Phase,
}
impl Heart {
pub fn press(&mut self) -> Option<Command> {
if matches!(self.phase, Phase::Fading(_)) {
self.phase = Phase::Sending;
Some(self.command())
} else {
None
}
}
pub fn command(&self) -> Command {
Command::SetLiked {
track_key: self.key.clone(),
liked: self.liked,
}
}
pub fn due(&mut self, now: Instant) -> Option<Command> {
if let Phase::Fading(start) = self.phase
&& now.saturating_duration_since(start) >= REMOVE_DELAY
{
return self.press();
}
None
}
pub fn fill(&self, now: Instant) -> f32 {
match self.phase {
Phase::Fading(start) => {
1.0 - (now.saturating_duration_since(start).as_secs_f32()
/ REMOVE_DELAY.as_secs_f32())
.clamp(0.0, 1.0)
}
Phase::Confirmed(_) if self.liked => 1.0,
_ => 0.0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn removal_waits_three_seconds_and_repeat_press_sends_once() {
let now = Instant::now();
let mut h = Heart {
key: "a".into(),
liked: false,
phase: Phase::Fading(now),
};
assert!(h.due(now + Duration::from_millis(2999)).is_none());
assert!((h.fill(now + Duration::from_millis(1500)) - 0.5).abs() < 0.001);
assert!(h.due(now + Duration::from_secs(3)).is_some());
assert_eq!(h.fill(now + REMOVE_DELAY), 0.0);
assert!(h.press().is_none());
h.phase = Phase::Fading(now);
assert!(h.press().is_some());
assert_eq!(h.fill(now), 0.0);
h.phase = Phase::Waiting("request".into(), now);
assert_eq!(h.fill(now), 0.0);
h.phase = Phase::Confirmed(now);
assert_eq!(h.fill(now), 0.0);
assert!(h.press().is_none());
}
}
+141
View File
@@ -0,0 +1,141 @@
//! Minimal OpenAction WebSocket adapter, checked against OpenDeck v2.14.2.
//! In that version the Neo controller is "Infobar", not Elgato SDK 3's "Neo".
use std::collections::BTreeMap;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use serde_json::{Value, json};
pub const PLUGIN: &str = "org.furumi.opendeck.sdPlugin";
pub const CELL: &str = "org.furumi.opendeck.cell";
pub const INFOBAR: &str = "org.furumi.opendeck.infobar";
pub const PROFILE_INSPECTOR: &str = "plugins/org.furumi.opendeck.sdPlugin/property-inspector.html";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Instance {
pub context: String,
pub device: String,
pub slot: Option<usize>,
}
#[derive(Debug, Deserialize)]
pub struct Event {
pub event: String,
#[serde(default)]
pub action: String,
#[serde(default)]
pub context: String,
#[serde(default)]
pub device: String,
#[serde(default)]
pub payload: Value,
}
impl Event {
pub fn instance(&self) -> Option<Instance> {
if self.payload["isInMultiAction"].as_bool() == Some(true) {
return None;
}
let controller = self.payload["controller"].as_str()?;
let slot = match (self.action.as_str(), controller) {
(CELL, "Keypad") => {
let row = self.payload["coordinates"]["row"].as_u64()?;
let column = self.payload["coordinates"]["column"].as_u64()?;
if row > 1 || column > 3 {
return None;
}
Some((row * 4 + column) as usize)
}
(INFOBAR, "Infobar") => None,
_ => return None,
};
if self.context.is_empty() || self.device.is_empty() {
return None;
}
Some(Instance {
context: self.context.clone(),
device: self.device.clone(),
slot,
})
}
}
pub fn image(context: &str, image: String) -> Value {
json!({"event":"setImage","context":context,"payload":{"image":image,"target":0}})
}
pub fn registration(args: &[String]) -> Result<(u16, Value)> {
let flag = |name: &str| -> Result<String> {
let index = args
.iter()
.position(|a| a.eq_ignore_ascii_case(name))
.with_context(|| format!("missing OpenDeck launch argument {name}"))?;
args.get(index + 1)
.cloned()
.context("missing argument value")
};
let port = flag("-port")?.parse()?;
let event = flag("-registerEvent")?;
let uuid = flag("-pluginUUID")?;
if event != "registerPlugin" || uuid != PLUGIN {
bail!("unexpected OpenDeck plugin registration");
}
Ok((port, json!({"event":event,"uuid":uuid})))
}
/// Profile format is OpenDeck's own JSON (not an Elgato .streamDeckProfile).
/// Generate it offline; never mutate a profile underneath a running host.
pub fn profile(device: &str) -> Result<Value> {
if !device.starts_with("sd-")
|| !device
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-')
{
bail!("expected a Stream Deck device ID such as sd-SERIAL");
}
let manifest: Value = serde_json::from_str(include_str!("../assets/manifest.json"))?;
let instance = |slot: usize, infobar: bool| {
let mut action = manifest["Actions"][usize::from(infobar)].clone();
action["plugin"] = PLUGIN.into();
action["PropertyInspectorPath"] = PROFILE_INSPECTOR.into();
let icon = format!("plugins/{PLUGIN}/icon.svg");
action["Icon"] = icon.clone().into();
action["States"][0]["Image"] = icon.clone().into();
let controller = if infobar { "Infobar" } else { "Keypad" };
json!({"action":action,"context":format!("{controller}.{slot}.0"),"states":[{"Image":icon,"ShowTitle":false}],"current_state":0,"settings":{},"children":null})
};
let mut keys: Vec<Value> = (0..8).map(|slot| instance(slot, false)).collect();
keys.extend([Value::Null, Value::Null]);
Ok(json!({"id":"Furumi","keys":keys,"sliders":[],"infobars":[instance(0,true)]}))
}
pub type Instances = BTreeMap<String, Instance>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_actual_opendeck_2142_infobar_event_and_emits_set_image() {
let event:Event=serde_json::from_value(json!({"event":"willAppear","action":INFOBAR,"context":"sd-TEST.Furumi.Infobar.0.0","device":"sd-TEST","payload":{"settings":{},"coordinates":{"row":0,"column":0},"controller":"Infobar","state":0,"isInMultiAction":false}})).unwrap();
let instance = event.instance().unwrap();
assert_eq!(instance.slot, None);
let out = image(&instance.context, "data:image/png;base64,abc".into());
assert_eq!(out["context"], event.context);
assert_eq!(out["event"], "setImage");
}
#[test]
fn profile_contains_eight_cells_and_the_correct_infobar_controller() {
let p = profile("sd-TEST").unwrap();
assert_eq!(
p["keys"]
.as_array()
.unwrap()
.iter()
.filter(|v| !v.is_null())
.count(),
8
);
assert_eq!(p["infobars"][0]["action"]["Controllers"][0], "Infobar");
assert!(profile("../../other").is_err());
}
}
+229
View File
@@ -0,0 +1,229 @@
//! Phosphor masks, rasterised at authoring time from the bundled
//! source SVGs. No SVG/Node dependency or OS-specific font is needed at runtime.
use std::sync::LazyLock;
use image::{GrayImage, Luma, Rgb, RgbImage, RgbaImage};
const TILE: u32 = 96;
const COLUMNS: u32 = 8;
static ATLAS: LazyLock<RgbaImage> = LazyLock::new(|| {
let image = image::load_from_memory(include_bytes!("../assets/icons/phosphor-atlas.png"))
.expect("bundled Phosphor alpha atlas must decode")
.into_rgba8();
assert_eq!(
image.dimensions(),
(768, 384),
"bundled icon atlas dimensions"
);
image
});
/// Order matches the named tiles in assets/icons/phosphor-atlas.json.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Icon {
Previous,
Play,
Pause,
Next,
Repeat,
RepeatOne,
Shuffle,
Back,
SeekBack,
SeekForward,
Radio,
Devices,
NextPage,
Album,
Check,
Unavailable,
Heart,
HeartFill,
CoverFrame,
EnabledFrame,
}
fn blend(im: &mut RgbImage, index: usize, color: [u8; 3]) {
let x = (index as u32 % COLUMNS) * TILE;
let y = (index as u32 / COLUMNS) * TILE;
for dy in 0..im.height().min(TILE) {
for dx in 0..im.width().min(TILE) {
let alpha = ATLAS.get_pixel(x + dx, y + dy)[3] as u32;
if alpha == 0 {
continue;
}
let background = im.get_pixel(dx, dy).0;
let pixel = std::array::from_fn(|channel| {
((background[channel] as u32 * (255 - alpha) + color[channel] as u32 * alpha + 127)
/ 255) as u8
});
im.put_pixel(dx, dy, Rgb(pixel));
}
}
}
/// Paint a mask at its fixed native 96×96 production position. Existing pixels
/// outside its alpha coverage are preserved, including album artwork.
pub fn draw(im: &mut RgbImage, icon: Icon, color: [u8; 3]) {
blend(im, icon as usize, color);
}
/// Eight genuine spinner-gap-fill frames. Choose e.g. elapsed_ms/100 as step.
/// The spinner occupies the Radio glyph area; it leaves the label area free.
pub fn spinner(im: &mut RgbImage, step: usize, color: [u8; 3]) {
blend(im, Icon::EnabledFrame as usize + 1 + step % 8, color);
}
static CORNER_SPINNERS: LazyLock<Vec<GrayImage>> = LazyLock::new(|| {
(0..8)
.map(|step| {
let index = Icon::EnabledFrame as usize + 1 + step;
let x = (index as u32 % COLUMNS) * TILE + 24;
let y = (index as u32 / COLUMNS) * TILE + 8;
let alpha =
GrayImage::from_fn(48, 48, |dx, dy| Luma([ATLAS.get_pixel(x + dx, y + dy)[3]]));
image::imageops::resize(&alpha, 20, 20, image::imageops::FilterType::Triangle)
})
.collect()
});
/// The same genuine Phosphor spinner, scaled to a 20px bottom-right badge.
pub fn corner_spinner(im: &mut RgbImage, step: usize, color: [u8; 3]) {
paint_mask(im, &CORNER_SPINNERS[step % 8], 72, 72, color);
}
fn paint_mask(im: &mut RgbImage, mask: &GrayImage, x: u32, y: u32, color: [u8; 3]) {
for (dx, dy, pixel) in mask.enumerate_pixels() {
if pixel[0] == 0 || x + dx >= im.width() || y + dy >= im.height() {
continue;
}
let a = u32::from(pixel[0]);
let old = im.get_pixel(x + dx, y + dy).0;
let pixel = std::array::from_fn(|channel| {
((u32::from(old[channel]) * (255 - a) + u32::from(color[channel]) * a + 127) / 255)
as u8
});
im.put_pixel(x + dx, y + dy, Rgb(pixel));
}
}
pub const COVER_GLYPH_SIZE: u32 = 19;
static COVER_GLYPHS: LazyLock<[(Icon, GrayImage); 4]> = LazyLock::new(|| {
[Icon::Previous, Icon::Repeat, Icon::RepeatOne, Icon::Shuffle].map(|icon| {
let index = icon as u32;
let sx = index % COLUMNS * TILE + 20;
let sy = index / COLUMNS * TILE + 20;
let alpha = GrayImage::from_fn(56, 56, |x, y| Luma([ATLAS.get_pixel(sx + x, sy + y)[3]]));
let glyph = image::imageops::resize(
&alpha,
COVER_GLYPH_SIZE,
COVER_GLYPH_SIZE,
image::imageops::FilterType::Triangle,
);
(icon, glyph)
})
});
pub fn cover_glyph(
im: &mut RgbImage,
icon: Icon,
x: u32,
y: u32,
color: [u8; 3],
contour: [u8; 3],
) {
let Some((_, mask)) = COVER_GLYPHS.iter().find(|(kind, _)| *kind == icon) else {
return;
};
for py in y.saturating_sub(1)..=y + 1 {
for px in x.saturating_sub(1)..=x + 1 {
if (px, py) != (x, y) {
paint_mask(im, mask, px, py, contour);
}
}
}
paint_mask(im, mask, x, y, color);
}
#[cfg(test)]
mod tests {
use super::*;
const ALL: [Icon; 20] = [
Icon::Previous,
Icon::Play,
Icon::Pause,
Icon::Next,
Icon::Repeat,
Icon::RepeatOne,
Icon::Shuffle,
Icon::Back,
Icon::SeekBack,
Icon::SeekForward,
Icon::Radio,
Icon::Devices,
Icon::NextPage,
Icon::Album,
Icon::Check,
Icon::Unavailable,
Icon::Heart,
Icon::HeartFill,
Icon::CoverFrame,
Icon::EnabledFrame,
];
#[test]
fn enum_order_matches_named_svg_atlas_elements() {
let metadata: serde_json::Value =
serde_json::from_str(include_str!("../assets/icons/phosphor-atlas.json")).unwrap();
for (index, icon) in ALL.into_iter().enumerate() {
assert_eq!(metadata["icons"][index]["name"], format!("{icon:?}"));
assert_eq!(metadata["icons"][index]["index"], index);
}
}
#[test]
fn every_named_production_mask_has_visible_pixels_and_stays_inside_the_key() {
for icon in ALL {
let mut im = RgbImage::from_pixel(TILE, TILE, Rgb([43, 70, 90]));
draw(&mut im, icon, [208, 220, 227]);
assert!(im.pixels().any(|p| p.0 != [43, 70, 90]), "empty {icon:?}");
assert_eq!(im.get_pixel(0, 0).0, [43, 70, 90]);
assert_eq!(im.get_pixel(95, 95).0, [43, 70, 90]);
}
}
#[test]
fn frame_has_full_four_pixel_inset_and_does_not_fill_the_middle() {
let mut im = RgbImage::from_pixel(96, 96, Rgb([0, 0, 0]));
draw(&mut im, Icon::EnabledFrame, [255, 255, 255]);
assert_eq!(im.get_pixel(48, 48).0, [0, 0, 0]);
for inset in 0..4 {
for p in 0..96 {
assert_eq!(im.get_pixel(p, inset).0, [0, 0, 0]);
assert_eq!(im.get_pixel(p, 95 - inset).0, [0, 0, 0]);
assert_eq!(im.get_pixel(inset, p).0, [0, 0, 0]);
assert_eq!(im.get_pixel(95 - inset, p).0, [0, 0, 0]);
}
}
assert_eq!(im.get_pixel(48, 4).0, [255, 255, 255]);
}
#[test]
fn spinner_rotates_and_wraps_without_painting_over_the_label() {
let make = |step| {
let mut im = RgbImage::new(96, 96);
spinner(&mut im, step, [208, 220, 227]);
im
};
assert_ne!(make(0), make(1));
assert_eq!(make(0), make(8));
let frame = make(3);
for y in 68..96 {
for x in 0..96 {
assert_eq!(frame.get_pixel(x, y).0, [0, 0, 0]);
}
}
}
}
File diff suppressed because it is too large. Load diff
+794
View File
@@ -0,0 +1,794 @@
//! One navigation state per physical deck. A press captures the visible target,
//! so device arrivals/reordering between keyDown and keyUp cannot redirect it.
use std::collections::BTreeMap;
use std::time::{Duration, Instant};
use furumi_control_protocol::{Command, Device, RadioState, RemoteCommandState, Role, Snapshot};
pub const DEVICES_PER_PAGE: usize = 6;
const REMOTE_FALLBACK: Duration = Duration::from_secs(45);
pub fn conflicts_with_remote_playback(command: &Command) -> bool {
!matches!(
command,
Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. }
)
}
#[derive(Clone, Debug)]
struct RemoteLatch {
request_id: Option<String>,
baseline: u64,
observed: Option<u64>,
started: Instant,
}
/// One canonical instance belongs to Surface; each deck receives a clone for
/// rendering/routing. This also blocks a second physical deck between snapshots.
#[derive(Clone, Debug, Default)]
pub struct RemoteGate {
initialized: bool,
owner: Option<String>,
last_id: Option<u64>,
latch: Option<RemoteLatch>,
abandoned: Option<u64>,
}
impl RemoteGate {
pub fn waiting(&self, snapshot: Option<&Snapshot>) -> bool {
snapshot.is_some_and(|s| s.role == Role::Control && s.active_device_id == self.owner)
&& self.latch.is_some()
}
pub fn started(&self) -> Option<Instant> {
self.latch.as_ref().map(|latch| latch.started)
}
/// Legacy local servers advertise no acknowledgement capability. Preserve
/// their existing command behaviour rather than wait for an absent field.
pub fn begin(&mut self, snapshot: &Snapshot, request_id: String, now: Instant) {
if snapshot.role != Role::Control {
return;
}
let Some(status) = &snapshot.remote_command else {
return;
};
self.owner = snapshot.active_device_id.clone();
self.initialized = true;
self.latch = Some(RemoteLatch {
request_id: Some(request_id),
baseline: status.id,
observed: None,
started: now,
});
}
pub fn reject(&mut self, id: &str) -> bool {
if self
.latch
.as_ref()
.is_some_and(|latch| latch.request_id.as_deref() == Some(id))
{
if let Some(mut latch) = self.latch.take() {
if let Some(observed) = latch.observed {
// Another input may have reached the TUI first. Rejecting
// this local request does not cancel an authoritative
// pending command already seen in a snapshot.
latch.request_id = None;
latch.baseline = observed;
self.latch = Some(latch);
} else {
self.abandoned = Some(latch.baseline);
}
}
return true;
}
false
}
pub fn observe(&mut self, snapshot: &Snapshot, now: Instant) -> Option<String> {
if snapshot.role != Role::Control {
*self = Self::default();
return None;
}
if self.initialized && snapshot.active_device_id != self.owner {
*self = Self {
initialized: true,
owner: snapshot.active_device_id.clone(),
last_id: snapshot.remote_command.as_ref().map(|status| status.id),
abandoned: snapshot.remote_command.as_ref().map(|status| status.id),
..Self::default()
};
return None;
}
self.initialized = true;
self.owner = snapshot.active_device_id.clone();
let Some(status) = &snapshot.remote_command else {
self.latch = None;
self.last_id = None;
self.abandoned = None;
return None;
};
let mut error = None;
if let Some(latch) = &mut self.latch {
let newer = latch
.observed
.map_or(status.id > latch.baseline, |id| status.id >= id);
if newer {
match status.state {
RemoteCommandState::Pending => latch.observed = Some(status.id),
RemoteCommandState::Confirmed => {
self.latch = None;
self.abandoned = Some(status.id);
}
RemoteCommandState::Failed => {
self.latch = None;
self.abandoned = Some(status.id);
error = Some(remote_error(status.error.as_deref()));
}
// An idle snapshot may have been queued before dispatch.
RemoteCommandState::Idle => {}
}
}
} else if status.state == RemoteCommandState::Pending
&& self.abandoned.is_none_or(|id| status.id > id)
&& self.last_id.is_none_or(|id| status.id >= id)
{
self.latch = Some(RemoteLatch {
request_id: None,
baseline: status.id,
observed: Some(status.id),
started: now,
});
} else if status.state == RemoteCommandState::Failed
&& self.last_id.is_some_and(|id| status.id > id)
{
error = Some(remote_error(status.error.as_deref()));
}
self.last_id = Some(self.last_id.map_or(status.id, |id| id.max(status.id)));
if self.latch.is_none()
&& matches!(
status.state,
RemoteCommandState::Confirmed | RemoteCommandState::Failed
)
{
self.abandoned = Some(self.abandoned.map_or(status.id, |id| id.max(status.id)));
}
error.or_else(|| self.expire(now))
}
pub fn expire(&mut self, now: Instant) -> Option<String> {
if self
.latch
.as_ref()
.is_some_and(|latch| now.saturating_duration_since(latch.started) >= REMOTE_FALLBACK)
{
if let Some(latch) = self.latch.take() {
self.abandoned = Some(latch.observed.unwrap_or(latch.baseline));
}
return Some("Remote command timed out".into());
}
None
}
}
fn remote_error(error: Option<&str>) -> String {
let value = error
.and_then(|value| value.lines().next())
.filter(|value| !value.trim().is_empty())
.unwrap_or("Remote command failed");
let mut short: String = value.chars().take(72).collect();
if value.chars().count() > 72 {
short.push('…');
}
short
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Binding {
Heart { key: String, liked: bool },
Command(Command),
Functions,
Devices,
NextPage,
Back,
Disabled,
}
#[derive(Clone, Debug)]
pub enum Screen {
Player,
Functions,
Devices {
page: usize,
targets: Vec<Device>,
name_since: [Instant; DEVICES_PER_PAGE],
},
}
#[derive(Clone, Debug)]
pub struct PendingTransfer {
pub request_id: String,
pub device_id: String,
pub started: Instant,
}
pub struct PendingRadio {
pub request_id: String,
pub baseline: u64,
pub started: Instant,
}
pub struct Deck {
pub heart: Option<crate::heart::Heart>,
pub screen: Screen,
pub presses: BTreeMap<String, Binding>,
pub pending: Option<PendingTransfer>,
pub radio: Option<PendingRadio>,
pub notice: Option<(String, Instant)>,
pub remote: RemoteGate,
pub artwork_loading: Option<Instant>,
pub preferences: crate::settings::Preferences,
}
impl Default for Deck {
fn default() -> Self {
Self {
heart: None,
screen: Screen::Player,
presses: BTreeMap::new(),
pending: None,
radio: None,
notice: None,
remote: RemoteGate::default(),
artwork_loading: None,
preferences: crate::settings::Preferences::default(),
}
}
}
impl Deck {
pub fn targets(snapshot: &Snapshot) -> Vec<Device> {
let mut devices: Vec<_> = snapshot
.devices
.iter()
.filter(|d| d.online || d.is_self)
.cloned()
.collect();
devices.sort_by(|a, b| {
b.is_self
.cmp(&a.is_self)
.then_with(|| a.name.cmp(&b.name))
.then_with(|| a.id.cmp(&b.id))
});
devices
}
pub fn binding(&self, slot: usize, snapshot: Option<&Snapshot>) -> Binding {
if self.pending.is_some() {
return Binding::Disabled;
}
let binding = match &self.screen {
Screen::Player => match slot {
0 => Binding::Functions,
1 => Binding::Command(Command::Previous),
2 => Binding::Command(Command::PlayPause),
3 => Binding::Command(Command::Next),
4 => Binding::Command(Command::CycleRepeat),
5 => Binding::Command(Command::ToggleShuffle),
6 => Binding::Command(Command::Seek { seconds: -10 }),
7 => Binding::Command(Command::Seek { seconds: 30 }),
_ => Binding::Disabled,
},
Screen::Functions => match slot {
0 => snapshot
.and_then(|s| s.track.as_ref())
.and_then(|t| {
t.liked.map(|liked| Binding::Heart {
key: t.key.clone(),
liked,
})
})
.unwrap_or(Binding::Disabled),
2 if self.radio.is_none() => Binding::Command(Command::StartRadio),
1 => Binding::Devices,
7 => Binding::Back,
_ => Binding::Disabled,
},
Screen::Devices { page, targets, .. } => match slot {
7 => Binding::Back,
6 if targets.len() > DEVICES_PER_PAGE => Binding::NextPage,
0..=5 => targets
.get(page * DEVICES_PER_PAGE + slot)
.filter(|d| d.can_transfer && !d.active)
.map_or(Binding::Disabled, |d| {
Binding::Command(Command::Transfer {
device_id: d.id.clone(),
})
}),
_ => Binding::Disabled,
},
};
if snapshot.is_none() && matches!(&binding, Binding::Command(_)) {
return Binding::Disabled;
}
if self.remote.waiting(snapshot)
&& matches!(&binding,Binding::Command(command) if conflicts_with_remote_playback(command))
{
Binding::Disabled
} else {
binding
}
}
pub fn release(&mut self, binding: Binding, snapshot: Option<&Snapshot>) -> Option<Command> {
// Recheck liveness and capability; the captured ID is never replaced by
// the device that happens to occupy that cell in a newer snapshot.
let Some(snapshot) = snapshot else {
match binding {
Binding::Functions => self.screen = Screen::Functions,
Binding::Devices => {
self.screen = Screen::Devices {
page: 0,
targets: Vec::new(),
name_since: [Instant::now(); DEVICES_PER_PAGE],
}
}
Binding::Back => {
self.screen = if matches!(self.screen, Screen::Devices { .. }) {
Screen::Functions
} else {
Screen::Player
}
}
_ => {}
}
return None;
};
if self.remote.waiting(Some(snapshot))
&& matches!(&binding,Binding::Command(command) if conflicts_with_remote_playback(command))
{
return None;
}
if self.pending.is_some() {
return None;
}
if self.radio.is_some() && binding == Binding::Command(Command::StartRadio) {
return None;
}
if binding != Binding::Disabled {
self.notice = None;
}
if !matches!(binding, Binding::Heart { .. } | Binding::Disabled) {
self.heart = None;
}
match binding {
Binding::Heart { key, liked } => {
if !matches!(self.screen, Screen::Functions)
|| snapshot
.track
.as_ref()
.is_none_or(|t| t.key != key || t.liked != Some(liked))
{
return None;
}
if let Some(heart) = &mut self.heart {
return heart.press();
}
let heart = crate::heart::Heart {
key,
liked: !liked,
phase: if liked {
crate::heart::Phase::Fading(Instant::now())
} else {
crate::heart::Phase::Sending
},
};
let command = (!liked).then(|| heart.command());
self.heart = Some(heart);
command
}
Binding::Functions => {
self.screen = Screen::Functions;
None
}
Binding::Devices => {
self.screen = Screen::Devices {
page: 0,
targets: Self::targets(snapshot),
name_since: [Instant::now(); DEVICES_PER_PAGE],
};
None
}
Binding::NextPage => {
if let Screen::Devices {
page,
targets,
name_since,
} = &mut self.screen
{
*targets = Self::targets(snapshot);
*page = (*page + 1) % targets.len().div_ceil(DEVICES_PER_PAGE).max(1);
name_since.fill(Instant::now());
}
None
}
Binding::Back => {
self.screen = if matches!(self.screen, Screen::Devices { .. }) {
Screen::Functions
} else {
Screen::Player
};
None
}
Binding::Command(Command::Transfer { device_id }) => {
if snapshot.devices.iter().any(|d| {
d.id == device_id && (d.online || d.is_self) && d.can_transfer && !d.active
}) {
Some(Command::Transfer { device_id })
} else {
self.notice = Some(("Device unavailable".into(), Instant::now()));
None
}
}
Binding::Command(command) => Some(command),
Binding::Disabled => None,
}
}
pub fn update(&mut self, snapshot: &Snapshot) {
if let Some(pending) = &self.pending {
// Accepted only means local dispatch; do not show confirmed remote
// playback before the deadline or invent an acknowledgement.
if pending.started.elapsed() > Duration::from_secs(10) {
self.pending = None;
self.notice = Some(("Transfer not confirmed".into(), Instant::now()));
} else if snapshot.active_device_id.as_deref() == Some(&pending.device_id) {
self.screen = Screen::Player;
// Ownership snapshot is useful feedback, but not an audio ACK.
self.pending = None;
}
}
if let Some(radio) = &self.radio {
if snapshot.radio.id > radio.baseline && snapshot.radio.state == RadioState::Playing {
self.screen = Screen::Player;
self.radio = None;
} else if snapshot.radio.id > radio.baseline
&& snapshot.radio.state == RadioState::Failed
{
self.notice = Some((
snapshot
.radio
.error
.clone()
.unwrap_or_else(|| "Radio failed".into()),
Instant::now(),
));
self.radio = None;
} else if radio.started.elapsed() > Duration::from_secs(240) {
self.notice = Some(("Radio timed out".into(), Instant::now()));
self.radio = None;
}
}
if self.presses.is_empty()
&& let Screen::Devices {
page,
targets,
name_since,
} = &mut self.screen
{
let next = Self::targets(snapshot);
let next_page = (*page).min(next.len().saturating_sub(1) / DEVICES_PER_PAGE);
let now = Instant::now();
for (slot, since) in name_since.iter_mut().enumerate() {
let old = targets.get(*page * DEVICES_PER_PAGE + slot);
let new = next.get(next_page * DEVICES_PER_PAGE + slot);
if old.map(|d| (&d.id, &d.name)) != new.map(|d| (&d.id, &d.name)) {
*since = now;
}
}
*targets = next;
*page = next_page;
}
if self.notice.as_ref().is_some_and(|(message, at)| {
at.elapsed()
> Duration::from_secs((message.chars().count() as u64 / 2 + 5).clamp(6, 45))
}) {
self.notice = None;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::preview::fixture;
use furumi_control_protocol::RemoteCommand;
fn controlled() -> Snapshot {
let mut snapshot = fixture();
snapshot.role = Role::Control;
snapshot.active_device_id = Some("laptop".into());
snapshot.remote_command = Some(RemoteCommand::default());
snapshot
}
#[test]
fn remote_latch_ignores_idle_and_old_confirmation_until_new_command_finishes() {
let now = Instant::now();
let mut snapshot = controlled();
snapshot.remote_command.as_mut().unwrap().id = 4;
let mut gate = RemoteGate::default();
gate.observe(&snapshot, now);
gate.begin(&snapshot, "request-5".into(), now);
assert!(gate.waiting(Some(&snapshot)));
gate.observe(&snapshot, now);
assert!(gate.waiting(Some(&snapshot)));
snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Confirmed;
gate.observe(&snapshot, now);
assert!(gate.waiting(Some(&snapshot)));
snapshot.remote_command = Some(RemoteCommand {
id: 5,
state: RemoteCommandState::Pending,
error: None,
});
gate.observe(&snapshot, now);
assert!(gate.waiting(Some(&snapshot)));
snapshot.remote_command = Some(RemoteCommand {
id: 4,
state: RemoteCommandState::Idle,
error: None,
});
gate.observe(&snapshot, now);
assert!(gate.waiting(Some(&snapshot)));
snapshot.remote_command = Some(RemoteCommand {
id: 5,
state: RemoteCommandState::Confirmed,
error: None,
});
gate.observe(&snapshot, now);
assert!(!gate.waiting(Some(&snapshot)));
snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Pending;
gate.observe(&snapshot, now);
assert!(
!gate.waiting(Some(&snapshot)),
"stale pending cannot restart a completed command"
);
}
#[test]
fn authoritative_pending_blocks_keyboard_and_radio_conflicts_but_not_navigation_or_transfer() {
let now = Instant::now();
let mut snapshot = controlled();
snapshot.remote_command = Some(RemoteCommand {
id: 8,
state: RemoteCommandState::Pending,
error: None,
});
let mut deck = Deck::default();
deck.remote.observe(&snapshot, now);
for slot in 1..8 {
assert_eq!(deck.binding(slot, Some(&snapshot)), Binding::Disabled);
}
assert_eq!(deck.binding(0, Some(&snapshot)), Binding::Functions);
// A command captured before the authoritative snapshot is rechecked.
assert!(
deck.release(Binding::Command(Command::Next), Some(&snapshot))
.is_none()
);
deck.release(Binding::Functions, Some(&snapshot));
assert_eq!(deck.binding(2, Some(&snapshot)), Binding::Disabled);
assert_eq!(deck.binding(1, Some(&snapshot)), Binding::Devices);
deck.release(Binding::Devices, Some(&snapshot));
assert!(matches!(
deck.binding(1, Some(&snapshot)),
Binding::Command(Command::Transfer { .. })
));
}
#[test]
fn remote_failure_reject_owner_change_and_legacy_servers_release_local_wait() {
let now = Instant::now();
let mut snapshot = controlled();
let mut gate = RemoteGate::default();
gate.begin(&snapshot, "rejected".into(), now);
assert!(gate.reject("rejected"));
assert!(!gate.waiting(Some(&snapshot)));
gate.begin(&snapshot, "failed".into(), now);
snapshot.remote_command = Some(RemoteCommand {
id: 1,
state: RemoteCommandState::Failed,
error: Some("Output unavailable".into()),
});
assert_eq!(
gate.observe(&snapshot, now),
Some("Output unavailable".into())
);
assert!(!gate.waiting(Some(&snapshot)));
gate.begin(&snapshot, "changed-owner".into(), now);
snapshot.active_device_id = Some("studio".into());
gate.observe(&snapshot, now);
assert!(!gate.waiting(Some(&snapshot)));
snapshot.remote_command = None;
gate.begin(&snapshot, "legacy".into(), now);
assert!(!gate.waiting(Some(&snapshot)));
snapshot.remote_command = Some(RemoteCommand {
id: 2,
state: RemoteCommandState::Pending,
error: None,
});
snapshot.role = Role::Jam;
gate.observe(&snapshot, now);
assert!(!gate.waiting(Some(&snapshot)));
}
#[test]
fn remote_timeout_is_bounded_and_same_pending_snapshot_cannot_relock() {
let now = Instant::now();
let mut snapshot = controlled();
let mut gate = RemoteGate::default();
gate.begin(&snapshot, "slow".into(), now);
snapshot.remote_command = Some(RemoteCommand {
id: 1,
state: RemoteCommandState::Pending,
error: None,
});
gate.observe(&snapshot, now);
assert_eq!(
gate.expire(now + REMOTE_FALLBACK),
Some("Remote command timed out".into())
);
assert!(!gate.waiting(Some(&snapshot)));
gate.observe(&snapshot, now + REMOTE_FALLBACK);
assert!(!gate.waiting(Some(&snapshot)));
snapshot.remote_command.as_mut().unwrap().id = 2;
gate.observe(&snapshot, now + REMOTE_FALLBACK);
assert!(gate.waiting(Some(&snapshot)));
}
#[test]
fn rejecting_our_racing_request_preserves_another_authoritative_pending_command() {
let now = Instant::now();
let mut snapshot = controlled();
let mut gate = RemoteGate::default();
gate.begin(&snapshot, "ours".into(), now);
snapshot.remote_command = Some(RemoteCommand {
id: 1,
state: RemoteCommandState::Pending,
error: None,
});
gate.observe(&snapshot, now);
gate.reject("ours");
assert!(gate.waiting(Some(&snapshot)));
snapshot.remote_command.as_mut().unwrap().state = RemoteCommandState::Confirmed;
gate.observe(&snapshot, now);
assert!(!gate.waiting(Some(&snapshot)));
}
#[test]
fn press_keeps_identity_when_devices_reorder_or_disappear() {
let mut snapshot = fixture();
let mut deck = Deck::default();
deck.release(Binding::Devices, Some(&snapshot));
let binding = deck.binding(1, Some(&snapshot));
let Binding::Command(Command::Transfer { device_id }) = &binding else {
panic!("target")
};
snapshot.devices.retain(|d| &d.id != device_id);
assert_eq!(deck.release(binding, Some(&snapshot)), None);
}
#[test]
fn navigation_does_not_reuse_release_as_new_screen_command() {
let snapshot = fixture();
let mut deck = Deck::default();
let press = deck.binding(0, Some(&snapshot));
assert_eq!(deck.release(press, Some(&snapshot)), None);
assert!(matches!(deck.screen, Screen::Functions));
let press = deck.binding(1, Some(&snapshot));
assert_eq!(deck.release(press, Some(&snapshot)), None);
assert!(matches!(deck.screen, Screen::Devices { .. }));
assert_eq!(deck.binding(7, Some(&snapshot)), Binding::Back);
}
#[test]
fn a_renamed_device_restarts_only_its_own_marquee() {
let mut s = fixture();
let mut deck = Deck::default();
deck.release(Binding::Devices, Some(&s));
let earlier = Instant::now() - Duration::from_secs(4);
let Screen::Devices { name_since, .. } = &mut deck.screen else {
unreachable!()
};
name_since.fill(earlier);
s.position_secs += 1.0;
s.devices[0].active = false;
deck.update(&s);
let Screen::Devices { name_since, .. } = &deck.screen else {
unreachable!()
};
assert_eq!(name_since, &[earlier; DEVICES_PER_PAGE]);
s.devices[0].name = "New local name".into();
deck.update(&s);
let Screen::Devices { name_since, .. } = &deck.screen else {
unreachable!()
};
assert!(name_since[0] > earlier);
assert!(name_since[1..].iter().all(|since| *since == earlier));
}
#[test]
fn pagination_wraps_and_devices_are_independent() {
let mut snapshot = fixture();
for n in 0..9 {
let mut d = snapshot.devices[1].clone();
d.id = format!("extra-{n}");
d.name = d.id.clone();
snapshot.devices.push(d);
}
let mut a = Deck::default();
let b = Deck::default();
a.release(Binding::Devices, Some(&snapshot));
a.release(Binding::NextPage, Some(&snapshot));
assert!(matches!(a.screen, Screen::Devices { page: 1, .. }));
assert!(matches!(b.screen, Screen::Player));
assert_eq!(a.binding(7, Some(&snapshot)), Binding::Back);
a.release(Binding::NextPage, Some(&snapshot));
a.release(Binding::NextPage, Some(&snapshot));
assert!(matches!(a.screen, Screen::Devices { page: 0, .. }));
}
#[test]
fn radio_waits_for_new_operation_and_actual_playback() {
let mut snapshot = fixture();
snapshot.radio.id = 10;
snapshot.radio.state = RadioState::Playing;
let mut deck = Deck {
screen: Screen::Functions,
radio: Some(PendingRadio {
request_id: "radio-11".into(),
baseline: 10,
started: Instant::now(),
}),
..Deck::default()
};
deck.update(&snapshot);
assert!(deck.radio.is_some());
snapshot.radio.id = 11;
snapshot.radio.state = RadioState::Searching;
deck.update(&snapshot);
assert!(deck.radio.is_some());
snapshot.radio.state = RadioState::Starting;
deck.update(&snapshot);
assert!(deck.radio.is_some());
snapshot.radio.state = RadioState::Playing;
snapshot.paused = true;
deck.update(&snapshot);
// Started is an explicit acknowledged state. A pause before the next
// snapshot must not leave an already-started radio spinning forever.
assert!(deck.radio.is_none());
assert!(matches!(deck.screen, Screen::Player));
}
#[test]
fn device_back_returns_to_functions_and_new_main_layout_routes_repeat_shuffle() {
let snapshot = fixture();
let mut deck = Deck::default();
assert_eq!(
deck.binding(4, Some(&snapshot)),
Binding::Command(Command::CycleRepeat)
);
assert_eq!(
deck.binding(5, Some(&snapshot)),
Binding::Command(Command::ToggleShuffle)
);
deck.release(Binding::Functions, Some(&snapshot));
assert_eq!(
deck.binding(2, Some(&snapshot)),
Binding::Command(Command::StartRadio)
);
deck.release(Binding::Devices, Some(&snapshot));
deck.release(Binding::Back, Some(&snapshot));
assert!(matches!(deck.screen, Screen::Functions));
}
}
+494
View File
@@ -0,0 +1,494 @@
use std::path::Path;
use std::time::{Duration, Instant};
use anyhow::Result;
use furumi_control_protocol::{
API_VERSION, Device, Radio, RemoteCommand, RemoteCommandState, Repeat, Role, Snapshot, Track,
};
use image::{Rgb, RgbImage};
use crate::model::{Binding, Deck, Screen};
use crate::render;
const PANEL_WIDTH: u32 = 64 + crate::artwork::KEY_PIXELS * 4 + crate::artwork::GAP_PX * 3;
const PANEL_HEIGHT: u32 = 343;
const BAR_Y: i64 = 273;
pub fn fixture() -> Snapshot {
let devices = [
("self", "This PC"),
("laptop", "Laptop"),
("studio", "Studio"),
("lounge", "Living room speakers"),
("mac", "MacBook"),
]
.into_iter()
.map(|(id, name)| Device {
id: id.into(),
name: name.into(),
is_self: id == "self",
active: id == "self",
online: true,
can_transfer: true,
unavailable_reason: None,
})
.collect();
Snapshot {
api_version: API_VERSION,
revision: 1,
updated_at_ms: 0,
role: Role::Active,
self_device_id: "self".into(),
active_device_id: Some("self".into()),
active_device_name: Some("This PC".into()),
playing: true,
paused: false,
position_secs: 83.0,
duration_secs: 245.0,
volume: 70,
shuffle: false,
repeat: Repeat::Off,
radio: Radio::default(),
remote_command: Some(Default::default()),
spectrum_supported: false,
track: Some(Track {
key: "preview-track".into(),
title: "Midnight City".into(),
artist: "M83".into(),
album: "Hurry Up, We're Dreaming".into(),
year: Some(2011),
artwork_id: None,
liked: Some(false),
}),
devices,
}
}
/// Offline examples at device resolution. Each pair receives identical band frames.
fn infobar_backgrounds(directory: &Path) -> Result<()> {
use crate::settings::InfobarBackground;
use crate::spectrum::{Frame, History};
let snapshot = fixture();
let mut deck = Deck::default();
let modes = [
("Spectrogram", InfobarBackground::Spectrogram),
("Bars", InfobarBackground::Bars),
];
let cases = [
("Quiet passage", 14usize, 85.0),
("Bass hit", 6, 242.0),
("Treble hit", 24, 242.0),
];
let mut sheet = RgbImage::from_pixel(2 * render::BAR_WIDTH + 36, 296, Rgb([24, 27, 32]));
for (column, (label, _)) in modes.iter().enumerate() {
let x = 12 + column as i32 * (render::BAR_WIDTH as i32 + 12);
render::preview_label(&mut sheet, label, x, 8, render::BAR_WIDTH as i32);
}
for (row, (label, center, amplitude)) in cases.into_iter().enumerate() {
let mut history = History::default();
for sequence in 1..=232 {
let phase = ((sequence + 8) % 12) as f32;
let pulse = (-phase / 4.5).exp();
let bands = std::array::from_fn(|band: usize| {
let distance = band.abs_diff(center) as f32 / 3.1;
let emphasis = (-0.5 * distance.powi(2)).exp();
let texture = ((band as f32 * 0.94 + sequence as f32 * 0.12).sin() + 1.0) * 0.09;
(amplitude * (0.09 + texture + emphasis * (0.2 + 0.64 * pulse))).min(255.0) as u8
});
history.ingest(Frame {
epoch: 1,
sequence,
bands: Some(bands),
});
}
let y = 32 + row as i32 * 88;
render::preview_label(&mut sheet, label, 12, y, 240);
for (column, (_, mode)) in modes.iter().enumerate() {
deck.preferences.infobar_background = *mode;
let frame = render::bar_with_spectrum(
&deck,
Some(&snapshot),
Duration::ZERO,
Duration::ZERO,
Some(&history),
);
let x = 12 + column as i64 * (i64::from(render::BAR_WIDTH) + 12);
image::imageops::overlay(&mut sheet, &frame, x, i64::from(y + 20));
}
}
sheet.save(directory.join("infobar-backgrounds.png"))?;
Ok(())
}
fn appearance(directory: &Path, artwork: &crate::artwork::PreparedArt) -> Result<()> {
use crate::settings::InfobarBackground;
let mut history = crate::spectrum::History::default();
for sequence in 1..=232 {
let bands = std::array::from_fn(|band| {
let t = sequence as f32 * 0.075;
let frequency = band as f32 * 0.31;
((t.sin() * frequency.cos() * 0.5 + 0.5) * 210.0) as u8
});
history.ingest(crate::spectrum::Frame {
epoch: 1,
sequence,
bands: Some(bands),
});
}
let mut sheet = RgbImage::from_pixel(
PANEL_WIDTH * 2 + 48,
(PANEL_HEIGHT + 44) * 4 + 10,
Rgb([24, 27, 32]),
);
let labels = [
"Default / plain Infobar",
"2x2 art / 41px physical gaps",
"Inverted Active / fixture spectrum",
"Inverted 2x2 / fixture bars",
"Inverted Control / no local spectrum",
"Inverted Jam host / fixture spectrum",
"Inverted Functions",
"Inverted Devices",
];
let now = Instant::now();
for (index, label) in labels.into_iter().enumerate() {
let mut snapshot = fixture();
snapshot.spectrum_supported = true;
snapshot.repeat = Repeat::One;
snapshot.shuffle = true;
let mut deck = Deck::default();
deck.preferences.album_art_2x2 = matches!(index, 1 | 3);
deck.preferences.invert_colors = index >= 2;
if matches!(index, 2 | 5) {
deck.preferences.infobar_background = InfobarBackground::Spectrogram;
} else if index == 3 {
deck.preferences.infobar_background = InfobarBackground::Bars;
}
if index == 4 {
snapshot.role = Role::Control;
snapshot.active_device_id = Some("laptop".into());
snapshot.active_device_name = Some("Laptop".into());
}
if index == 5 {
snapshot.role = Role::Jam;
}
if index == 6 {
deck.screen = Screen::Functions;
}
if index == 7 {
deck.release(Binding::Devices, Some(&snapshot));
}
let mut panel = RgbImage::from_pixel(PANEL_WIDTH, PANEL_HEIGHT, Rgb([218, 221, 224]));
for slot in 0..8 {
let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(artwork), now);
image::imageops::overlay(
&mut panel,
&key,
32 + (slot % 4) as i64 * i64::from(crate::artwork::KEY_STRIDE),
16 + (slot / 4) as i64 * i64::from(crate::artwork::KEY_STRIDE),
);
key.save(directory.join(format!("appearance-{index}-key-{slot}.png")))?;
}
let bar = render::bar_with_spectrum(
&deck,
Some(&snapshot),
Duration::ZERO,
Duration::ZERO,
Some(&history),
);
bar.save(directory.join(format!("appearance-{index}-infobar.png")))?;
image::imageops::overlay(&mut panel, &bar, i64::from((PANEL_WIDTH - 248) / 2), BAR_Y);
let x = 16 + (index % 2) as i64 * i64::from(PANEL_WIDTH + 16);
let y = 10 + (index / 2) as i64 * i64::from(PANEL_HEIGHT + 44);
render::preview_label(&mut sheet, label, x as i32, y as i32, PANEL_WIDTH as i32);
image::imageops::overlay(&mut sheet, &panel, x, y + 24);
}
sheet.save(directory.join("appearance-options.png"))?;
let mut mosaic = RgbImage::from_pixel(
crate::artwork::PHYSICAL_MOSAIC_SIZE,
crate::artwork::PHYSICAL_MOSAIC_SIZE,
Rgb([218, 221, 224]),
);
let mut deck = Deck::default();
deck.preferences.album_art_2x2 = true;
let snapshot = fixture();
for (slot, x, y) in [
(0, 0, 0),
(1, crate::artwork::KEY_STRIDE, 0),
(4, 0, crate::artwork::KEY_STRIDE),
(5, crate::artwork::KEY_STRIDE, crate::artwork::KEY_STRIDE),
] {
let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(artwork), now);
image::imageops::overlay(&mut mosaic, &key, i64::from(x), i64::from(y));
}
mosaic.save(directory.join("album-2x2-layout.png"))?;
let mut comparison = RgbImage::from_pixel(233 * 3 + 64, 273, Rgb([24, 27, 32]));
for (index, label) in ["Both off", "Repeat One enabled", "Shuffle enabled"]
.into_iter()
.enumerate()
{
let mut snapshot = fixture();
snapshot.repeat = if index == 1 { Repeat::One } else { Repeat::Off };
snapshot.shuffle = index == 2;
let mut mosaic = RgbImage::from_pixel(233, 233, Rgb([218, 221, 224]));
for (slot, x, y) in [(0, 0, 0), (1, 137, 0), (4, 0, 137), (5, 137, 137)] {
let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(artwork), now);
image::imageops::overlay(&mut mosaic, &key, x, y);
}
let x = 16 + index as i64 * 249;
render::preview_label(&mut comparison, label, x as i32, 8, 233);
image::imageops::overlay(&mut comparison, &mosaic, x, 32);
}
comparison.save(directory.join("album-overlay-controls.png"))?;
Ok(())
}
pub fn write(directory: &Path) -> Result<()> {
std::fs::create_dir_all(directory)?;
let mut sheet = RgbImage::from_pixel(
PANEL_WIDTH * 2 + 48,
(PANEL_HEIGHT + 15) * 4 + 10,
Rgb([24, 27, 32]),
);
// Deliberately synthetic cover fixture; no copyrighted album artwork is
// bundled. It demonstrates an untinted full-bleed artwork key.
let mut artwork = RgbImage::new(384, 384);
for (x, y, p) in artwork.enumerate_pixels_mut() {
let (sx, sy) = (x / 4, y / 4);
let horizon = 52;
*p = if sy < horizon {
Rgb([
20 + (sx / 3) as u8,
35 + (sy / 2) as u8,
90 + (sx / 2) as u8,
])
} else {
Rgb([100 + (sx / 2) as u8, 35 + (sy / 3) as u8, 65])
};
if (sx as i32 - 62).pow(2) + (sy as i32 - 28).pow(2) < 100 {
*p = Rgb([244, 169, 81]);
}
}
artwork.save(directory.join("cover-fixture.png"))?;
let prepared = crate::artwork::PreparedArt::new(artwork.clone());
for (index, name) in [
"active",
"control",
"jam",
"functions",
"devices",
"radio-starting",
"control-pending",
"control-confirmed",
]
.iter()
.enumerate()
{
let mut snapshot = fixture();
let mut deck = Deck::default();
if *name == "active" {
snapshot.repeat = Repeat::All;
snapshot.shuffle = true;
}
if name.starts_with("control") {
snapshot.role = Role::Control;
snapshot.paused = true;
snapshot.active_device_id = Some("laptop".into());
snapshot.active_device_name = Some("Laptop".into());
snapshot.shuffle = true;
}
if *name == "control-pending" {
snapshot.remote_command = Some(RemoteCommand {
id: 7,
state: RemoteCommandState::Pending,
error: None,
});
deck.remote.observe(&snapshot, Instant::now());
}
if *name == "control-confirmed" {
snapshot.paused = false;
snapshot.remote_command = Some(RemoteCommand {
id: 7,
state: RemoteCommandState::Confirmed,
error: None,
});
}
if *name == "jam" {
snapshot.role = Role::Jam;
snapshot.active_device_name = Some("Studio".into());
snapshot.repeat = Repeat::One;
}
if *name == "functions" || *name == "radio-starting" {
deck.screen = Screen::Functions;
}
if *name == "radio-starting" {
deck.radio = Some(crate::model::PendingRadio {
request_id: "preview".into(),
baseline: 0,
started: std::time::Instant::now(),
});
}
if *name == "devices" {
deck.release(Binding::Devices, Some(&snapshot));
}
let now = Instant::now();
if let Screen::Devices { targets, .. } = &deck.screen
&& let Some(slot) = targets.iter().position(|d| d.id == "lounge")
{
for seconds in [0, 4, 7] {
render::key(
slot,
&deck,
Some(&snapshot),
None,
now + Duration::from_secs(seconds),
)
.save(directory.join(format!("device-name-{seconds}s.png")))?;
}
}
let mut panel = RgbImage::from_pixel(PANEL_WIDTH, PANEL_HEIGHT, Rgb([218, 221, 224]));
for slot in 0..8 {
let key = render::key_prepared(slot, &deck, Some(&snapshot), Some(&prepared), now);
key.save(directory.join(format!("{name}-key-{slot}.png")))?;
image::imageops::overlay(
&mut panel,
&key,
32 + (slot % 4) as i64 * i64::from(crate::artwork::KEY_STRIDE),
16 + (slot / 4) as i64 * i64::from(crate::artwork::KEY_STRIDE),
);
}
let bar = render::bar(&deck, Some(&snapshot), Duration::ZERO, Duration::ZERO);
bar.save(directory.join(format!("{name}-infobar.png")))?;
image::imageops::overlay(&mut panel, &bar, i64::from((PANEL_WIDTH - 248) / 2), BAR_Y);
panel.save(directory.join(format!("{name}-screen.png")))?;
image::imageops::overlay(
&mut sheet,
&panel,
16 + (index % 2) as i64 * i64::from(PANEL_WIDTH + 16),
10 + (index / 2) as i64 * i64::from(PANEL_HEIGHT + 15),
);
}
sheet.save(directory.join("all-screens.png"))?;
appearance(directory, &prepared)?;
let now = Instant::now();
let mut hearts = RgbImage::from_pixel(4 * 112 + 16, 132, Rgb([24, 27, 32]));
for (index, label) in ["Not liked", "Liked", "Unlike fade", "Saved"]
.into_iter()
.enumerate()
{
let mut snapshot = fixture();
snapshot.track.as_mut().unwrap().liked = Some(index > 0);
let mut deck = Deck {
screen: Screen::Functions,
..Default::default()
};
if index >= 2 {
deck.heart = Some(crate::heart::Heart {
key: "preview-track".into(),
liked: false,
phase: if index == 2 {
crate::heart::Phase::Fading(now - Duration::from_millis(1500))
} else {
crate::heart::Phase::Confirmed(now)
},
});
}
let key = render::key_prepared(0, &deck, Some(&snapshot), Some(&prepared), now);
render::preview_label(&mut hearts, label, 16 + index as i32 * 112, 5, 104);
image::imageops::overlay(&mut hearts, &key, 16 + index as i64 * 112, 28);
}
hearts.save(directory.join("heart-states.png"))?;
infobar_backgrounds(directory)?;
let mut covers = RgbImage::from_pixel(856, 168, Rgb([24, 27, 32]));
render::preview_label(
&mut covers,
"Cover: missing (first four), loading (next two), ready",
16,
6,
824,
);
let now = Instant::now();
for (index, name) in [
"Active",
"Control",
"Jam",
"Offline",
"Loading 1",
"Loading 2",
"Ready",
]
.into_iter()
.enumerate()
{
let mut snapshot = fixture();
snapshot.role = match index {
1 => Role::Control,
2 => Role::Jam,
_ => Role::Active,
};
let mut deck = Deck::default();
if index == 4 || index == 5 {
deck.artwork_loading = Some(now);
}
let snapshot = if index == 3 { None } else { Some(&snapshot) };
let art = if index == 6 { Some(&artwork) } else { None };
let at = if index == 5 {
now + Duration::from_millis(100)
} else {
now
};
let key = render::key(0, &deck, snapshot, art, at);
key.save(directory.join(format!("cover-state-{index}.png")))?;
let x = 16 + index as i64 * 120;
image::imageops::overlay(&mut covers, &key, x, 34);
render::preview_label(&mut covers, name, x as i32, 140, 112);
}
covers.save(directory.join("artwork-states.png"))?;
let offline = Deck::default();
render::bar(&offline, None, Duration::ZERO, Duration::ZERO)
.save(directory.join("offline-infobar.png"))?;
let snapshot = fixture();
let frames: Vec<_> = (0..100)
.map(|i| {
let bar = render::bar(
&Deck::default(),
Some(&snapshot),
Duration::from_millis(i * 100),
Duration::ZERO,
);
image::Frame::from_parts(
image::DynamicImage::ImageRgb8(bar).into_rgba8(),
0,
0,
image::Delay::from_numer_denom_ms(100, 1),
)
})
.collect();
// Individual PNG frames are sufficient to inspect the real renderer without
// introducing an animation encoder dependency into the runtime.
for (i, frame) in frames.into_iter().enumerate().step_by(10) {
frame
.buffer()
.save(directory.join(format!("marquee-{i:03}.png")))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preview_uses_runtime_renderer_and_preserves_native_dimensions() {
let dir = tempfile::tempdir().unwrap();
write(dir.path()).unwrap();
assert_eq!(
image::image_dimensions(dir.path().join("active-key-0.png")).unwrap(),
(96, 96)
);
assert_eq!(
image::image_dimensions(dir.path().join("control-infobar.png")).unwrap(),
(248, 58)
);
assert!(dir.path().join("all-screens.png").exists());
}
}
@@ -0,0 +1,121 @@
//! OpenDeck 2.14.2 saves the inspector path on each action in the profile.
//! Upgrade an explicitly selected, offline profile from the first plugin release.
use std::fs;
use std::io::Write as _;
use std::path::Path;
use anyhow::{Context, Result, ensure};
use serde_json::Value;
use crate::host::{CELL, INFOBAR, PLUGIN, PROFILE_INSPECTOR};
fn upgrade_instance(instance: &mut Value) -> usize {
let mut changed = 0;
if let Some(action) = instance.get_mut("action").and_then(Value::as_object_mut)
&& action.get("plugin").and_then(Value::as_str) == Some(PLUGIN)
&& matches!(
action
.get("uuid")
.or_else(|| action.get("UUID"))
.and_then(Value::as_str),
Some(CELL | INFOBAR)
)
{
// Loaded profiles use snake_case; profiles exported by the Furumi
// generator can still contain the original manifest spelling.
let field = if action.contains_key("PropertyInspectorPath") {
"PropertyInspectorPath"
} else {
"property_inspector"
};
if action.get(field).and_then(Value::as_str) != Some(PROFILE_INSPECTOR) {
action.insert(field.into(), PROFILE_INSPECTOR.into());
changed = 1;
}
}
if let Some(children) = instance.get_mut("children").and_then(Value::as_array_mut) {
changed += children.iter_mut().map(upgrade_instance).sum::<usize>();
}
changed
}
pub(super) fn upgrade(path: &Path) -> Result<()> {
let path = fs::canonicalize(path).context("OpenDeck profile not found")?;
let original = fs::read(&path)?;
let json = original.strip_prefix(b"\xef\xbb\xbf").unwrap_or(&original);
let mut profile: Value = serde_json::from_slice(json).context("invalid profile JSON")?;
ensure!(
profile["keys"].is_array(),
"expected an OpenDeck profile with a keys array"
);
let mut changed = 0;
for field in ["keys", "sliders", "infobars"] {
if let Some(instances) = profile.get_mut(field).and_then(Value::as_array_mut) {
changed += instances.iter_mut().map(upgrade_instance).sum::<usize>();
}
}
if changed == 0 {
println!("No Furumi actions need a settings update.");
return Ok(());
}
let directory = path.parent().context("profile has no parent directory")?;
let mut replacement = tempfile::NamedTempFile::new_in(directory)?;
fs::set_permissions(replacement.path(), fs::metadata(&path)?.permissions())?;
serde_json::to_writer_pretty(&mut replacement, &profile)?;
replacement.write_all(b"\n")?;
replacement.as_file().sync_all()?;
let mut backup = tempfile::Builder::new()
.prefix("furumi-profile-")
.suffix(".bak")
.tempfile_in(directory)?;
backup.write_all(&original)?;
backup.as_file().sync_all()?;
ensure!(
fs::read(&path)? == original,
"profile changed during upgrade; close OpenDeck and retry"
);
let (_, backup_path) = backup.keep()?;
replacement.persist(&path)?;
println!(
"Updated {changed} Furumi actions. Original profile saved to {}",
backup_path.display()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn upgrades_only_furumi_inspector_fields_and_keeps_one_original_on_retry() {
let other = json!({"action":{"plugin":"other","uuid":"other.cell","property_inspector":"custom.html"}});
let settings = json!({"my_saved_title": "keep me"});
let mut profile = json!({
"keys":[null,{"action":{"plugin":PLUGIN,"uuid":CELL,"property_inspector":""},"settings":settings},other],
"infobars":[{"action":{"plugin":PLUGIN,"UUID":INFOBAR,"PropertyInspectorPath":""}}],
"sliders":[], "extra":"keep"
});
let original = serde_json::to_vec(&profile).unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("Personal.json");
fs::write(&path, &original).unwrap();
upgrade(&path).unwrap();
profile["keys"][1]["action"]["property_inspector"] = PROFILE_INSPECTOR.into();
profile["infobars"][0]["action"]["PropertyInspectorPath"] = PROFILE_INSPECTOR.into();
assert_eq!(
serde_json::from_slice::<Value>(&fs::read(&path).unwrap()).unwrap(),
profile
);
upgrade(&path).unwrap();
let backups: Vec<_> = fs::read_dir(dir.path())
.unwrap()
.flatten()
.filter(|e| e.path().extension().is_some_and(|ext| ext == "bak"))
.collect();
assert_eq!(backups.len(), 1);
assert_eq!(fs::read(backups[0].path()).unwrap(), original);
}
}
File diff suppressed because it is too large. Load diff
+159
View File
@@ -0,0 +1,159 @@
//! Preferences are global to the OpenDeck plugin, not to an action instance.
//! The native runtime is the sole writer, merging validated inspector patches
//! into the canonical object while preserving unknown fields.
use serde_json::{Map, Value};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InfobarBackground {
#[default]
None,
Spectrogram,
Bars,
}
impl InfobarBackground {
pub fn uses_spectrum(self) -> bool {
matches!(self, Self::Spectrogram | Self::Bars)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Preferences {
pub infobar_background: InfobarBackground,
pub album_art_2x2: bool,
pub invert_colors: bool,
}
impl Preferences {
pub fn read(value: &Value) -> Self {
Self {
infobar_background: match value["infobar_background"].as_str() {
Some("spectrogram") => InfobarBackground::Spectrogram,
Some("bars") => InfobarBackground::Bars,
_ => InfobarBackground::None,
},
album_art_2x2: value["album_art_2x2"].as_bool().unwrap_or(false),
invert_colors: value["invert_colors"].as_bool().unwrap_or(false),
}
}
}
#[derive(Default)]
pub struct Store {
raw: Map<String, Value>,
ready: bool,
queued: Map<String, Value>,
}
impl Store {
pub fn raw_value(&self) -> Option<Value> {
self.ready.then(|| Value::Object(self.raw.clone()))
}
pub fn preferences(&self) -> Preferences {
Preferences::read(&Value::Object(self.raw.clone()))
}
pub fn receive(&mut self, value: &Value) -> Option<Value> {
self.raw = value.as_object().cloned().unwrap_or_default();
self.ready = true;
let changed = !self.queued.is_empty();
self.raw.extend(std::mem::take(&mut self.queued));
changed.then(|| Value::Object(self.raw.clone()))
}
pub fn patch(&mut self, value: &Value) -> Option<Value> {
let patch = value.as_object()?;
if patch.is_empty()
|| patch.len() > 3
|| !patch.iter().all(|(key, value)| match key.as_str() {
"infobar_background" => {
matches!(value.as_str(), Some("none" | "spectrogram" | "bars"))
}
"album_art_2x2" | "invert_colors" => value.is_boolean(),
_ => false,
})
{
return None;
}
if !self.ready {
self.queued.extend(patch.clone());
return None;
}
self.raw.extend(patch.clone());
Some(Value::Object(self.raw.clone()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn bars_round_trips_and_old_or_unknown_modes_keep_safe_defaults() {
let mut store = Store::default();
store.receive(&json!({"future":42}));
let value = store.patch(&json!({"infobar_background":"bars"})).unwrap();
assert_eq!(value["future"], 42);
assert_eq!(
store.preferences().infobar_background,
InfobarBackground::Bars
);
assert!(InfobarBackground::Bars.uses_spectrum());
assert!(InfobarBackground::Spectrogram.uses_spectrum());
assert!(!InfobarBackground::None.uses_spectrum());
assert!(
store
.patch(&json!({"infobar_background":"invalid"}))
.is_none()
);
assert_eq!(
Preferences::read(&json!({})).infobar_background,
InfobarBackground::None
);
}
#[test]
fn defaults_and_unknown_preferences_are_safe_and_nondestructive() {
assert_eq!(Preferences::read(&json!({})), Preferences::default());
let source = json!({"infobar_background":"spectrogram","album_art_2x2":true,"invert_colors":true,"future":{"keep":42}});
let before = source.clone();
let preferences = Preferences::read(&source);
assert_eq!(
preferences.infobar_background,
InfobarBackground::Spectrogram
);
assert!(preferences.album_art_2x2 && preferences.invert_colors);
assert_eq!(source, before);
assert_eq!(
Preferences::read(
&json!({"album_art_2x2":"yes","invert_colors":1,"infobar_background":"future"})
),
Preferences::default()
);
}
#[test]
fn two_inspectors_merge_different_fields_without_discarding_unknown_settings() {
let mut store = Store::default();
store.receive(&json!({"future":{"keep":42}}));
let a = store.patch(&json!({"album_art_2x2":true})).unwrap();
let b = store.patch(&json!({"invert_colors":true})).unwrap();
assert_eq!(a["album_art_2x2"], true);
assert_eq!(b["album_art_2x2"], true);
assert_eq!(b["invert_colors"], true);
assert_eq!(b["future"]["keep"], 42);
assert!(store.patch(&json!({"future":false})).is_none());
assert!(store.patch(&json!({"invert_colors":"yes"})).is_none());
}
#[test]
fn patches_before_initial_host_read_are_queued_then_merged_with_unknown_fields() {
let mut store = Store::default();
assert!(store.patch(&json!({"album_art_2x2":true})).is_none());
assert!(store.patch(&json!({"invert_colors":true})).is_none());
let merged = store.receive(&json!({"future":"preserve"})).unwrap();
assert_eq!(merged["future"], "preserve");
assert_eq!(merged["album_art_2x2"], true);
assert_eq!(merged["invert_colors"], true);
}
}
+246
View File
@@ -0,0 +1,246 @@
//! Ephemeral local-output visual history. It never derives synthetic audio
//! from track metadata, and epoch/sequence checks discard stale frames.
use std::collections::VecDeque;
use std::sync::LazyLock;
use furumi_control_protocol::SPECTRUM_BANDS;
use image::{Rgb, RgbImage};
use crate::settings::InfobarBackground;
// The input is already in dB (−60..0 dBFS). Give the commonly occupied
// middle of that range most of the blue-to-teal transition. White 26 px
// marquee text retains over 3:1 contrast even against the warmest peaks.
static COLORS: LazyLock<[Rgb<u8>; 256]> = LazyLock::new(|| {
const STOPS: [(u8, [u8; 3]); 8] = [
(0, [8, 10, 13]),
(24, [46, 42, 107]),
(64, [63, 66, 166]),
(96, [34, 96, 193]),
(132, [6, 132, 159]),
(160, [44, 148, 129]),
(192, [147, 140, 72]),
(255, [202, 126, 47]),
];
let mut colors = [Rgb([0; 3]); 256];
for (&(low, from), &(high, to)) in STOPS.iter().zip(&STOPS[1..]) {
let span = u16::from(high - low);
for level in low..=high {
let step = u16::from(level - low);
colors[usize::from(level)] = Rgb(std::array::from_fn(|channel| {
((u16::from(from[channel]) * (span - step)
+ u16::from(to[channel]) * step
+ span / 2)
/ span) as u8
}));
}
}
colors
});
#[derive(Clone, Debug)]
pub struct Frame {
pub epoch: u64,
pub sequence: u64,
pub bands: Option<[u8; SPECTRUM_BANDS]>,
}
#[derive(Default)]
pub struct History {
epoch: Option<u64>,
sequence: Option<u64>,
columns: VecDeque<[u8; SPECTRUM_BANDS]>,
}
impl History {
pub fn clear(&mut self) {
self.columns.clear();
}
pub fn ingest(&mut self, frame: Frame) {
if self.epoch.is_some_and(|epoch| frame.epoch < epoch) {
return;
}
if self.epoch != Some(frame.epoch) {
self.columns.clear();
self.sequence = None;
self.epoch = Some(frame.epoch);
}
if self
.sequence
.is_some_and(|sequence| frame.sequence <= sequence)
{
return;
}
self.sequence = Some(frame.sequence);
match frame.bands {
Some(bands) => {
self.columns.push_back(bands);
if self.columns.len() > 232 {
self.columns.pop_front();
}
}
None => self.columns.clear(),
}
}
pub fn paint(
&self,
im: &mut RgbImage,
(x, y, width, height): (u32, u32, u32, u32),
mode: InfobarBackground,
) {
let Some(latest) = self.columns.back() else {
return;
};
let width = width.min(im.width().saturating_sub(x));
let height = height.min(im.height().saturating_sub(y));
if width == 0 || height == 0 {
return;
}
match mode {
InfobarBackground::None => {}
InfobarBackground::Spectrogram => {
for (age, bands) in self.columns.iter().rev().take(width as usize).enumerate() {
let px = x + width - 1 - age as u32;
for dy in 0..height {
let band = ((height - 1 - dy) * SPECTRUM_BANDS as u32 / height) as usize;
let level = bands[band];
if level != 0 {
im.put_pixel(px, y + dy, COLORS[usize::from(level)]);
}
}
}
}
InfobarBackground::Bars => {
let count = width.min(SPECTRUM_BANDS as u32);
for column in 0..count {
// A very wide time field can leave fewer pixels than bands.
let first = (column * SPECTRUM_BANDS as u32 / count) as usize;
let end = ((column + 1) * SPECTRUM_BANDS as u32 / count) as usize;
let level = *latest[first..end].iter().max().unwrap();
let rows = (u32::from(level) * height).div_ceil(255);
let left = x + column * width / count;
let right = x + (column + 1) * width / count;
let gutter = u32::from(right - left >= 3);
for py in y + height - rows..y + height {
for px in left..right - gutter {
im.put_pixel(px, py, COLORS[usize::from(level)]);
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quiet_and_midrange_levels_are_visible_and_white_titles_keep_contrast() {
fn luminance(rgb: Rgb<u8>) -> f64 {
let [r, g, b] = rgb.0.map(|value| {
let value = f64::from(value) / 255.0;
if value <= 0.04045 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
});
0.2126 * r + 0.7152 * g + 0.0722 * b
}
let background = luminance(Rgb([8, 10, 13])) + 0.05;
// −48 and −30 dBFS, respectively. The previous linear ramp was nearly black here.
assert!((luminance(COLORS[51]) + 0.05) / background >= 2.0);
assert!((luminance(COLORS[128]) + 0.05) / background >= 4.0);
assert!(COLORS.iter().all(|&c| 1.05 / (luminance(c) + 0.05) >= 3.0));
}
#[test]
fn bars_use_only_the_latest_frame_at_fixed_frequency_positions() {
let mut history = History::default();
let mut bands = [0; SPECTRUM_BANDS];
bands[0] = 255;
bands[15] = 128;
history.ingest(Frame {
epoch: 1,
sequence: 1,
bands: Some(bands),
});
let paint = |history: &History| {
let mut frame = RgbImage::new(124, 32);
history.paint(&mut frame, (0, 0, 124, 32), InfobarBackground::Bars);
frame
};
let low = paint(&history);
assert_eq!(*low.get_pixel(0, 0), COLORS[255]);
assert_eq!(*low.get_pixel(3, 31), Rgb([0; 3])); // gutter
assert_eq!(*low.get_pixel(60, 14), Rgb([0; 3]));
assert_eq!(*low.get_pixel(60, 15), COLORS[128]);
assert_eq!(*low.get_pixel(120, 31), Rgb([0; 3]));
let mut treble = [0; SPECTRUM_BANDS];
treble[30] = 255;
history.ingest(Frame {
epoch: 1,
sequence: 2,
bands: Some(treble),
});
let high = paint(&history);
assert_eq!(*high.get_pixel(0, 31), Rgb([0; 3]));
assert_eq!(*high.get_pixel(120, 0), COLORS[255]);
}
#[test]
fn silence_preserves_the_selected_background_in_both_audio_modes() {
let mut history = History::default();
history.ingest(Frame {
epoch: 1,
sequence: 1,
bands: Some([0; SPECTRUM_BANDS]),
});
for color in [Rgb([0; 3]), Rgb([8, 10, 13])] {
for mode in [InfobarBackground::Spectrogram, InfobarBackground::Bars] {
let mut frame = RgbImage::from_pixel(124, 32, color);
history.paint(&mut frame, (0, 0, 124, 32), mode);
assert!(frame.pixels().all(|&pixel| pixel == color));
}
}
}
#[test]
fn epoch_and_sequence_prevent_old_audio_from_reappearing() {
let mut history = History::default();
history.ingest(Frame {
epoch: 1,
sequence: 1,
bands: Some([100; 31]),
});
history.ingest(Frame {
epoch: 1,
sequence: 1,
bands: Some([250; 31]),
});
assert_eq!(history.columns.len(), 1);
history.ingest(Frame {
epoch: 2,
sequence: 1,
bands: None,
});
assert!(history.columns.is_empty());
history.ingest(Frame {
epoch: 1,
sequence: 10,
bands: Some([255; 31]),
});
assert!(history.columns.is_empty());
history.ingest(Frame {
epoch: 2,
sequence: 2,
bands: Some([50; 31]),
});
assert_eq!(history.columns.len(), 1);
}
}
@@ -0,0 +1,70 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '../assets/property-inspector.js'), 'utf8');
function inspector(uuid) {
const controls = Object.fromEntries(['infobar-background', 'album-art-2x2', 'invert-colors', 'status'].map(id => [id, { disabled: true, checked: false, value: '', textContent: '' }]));
const sent = [];
class Socket {
static OPEN = 1;
constructor(url) { this.url = url; this.readyState = 1; Socket.instance = this; }
send(value) { sent.push(JSON.parse(value)); }
}
const context = vm.createContext({ WebSocket: Socket, document: { getElementById: id => controls[id] } });
vm.runInContext(source, context);
context.connectElgatoStreamDeckSocket(12345, uuid, 'registerPropertyInspector');
const socket = Socket.instance;
socket.onopen();
assert.deepEqual(sent.shift(), { event: 'registerPropertyInspector', uuid });
assert.deepEqual(sent.shift(), { event: 'getGlobalSettings', context: uuid });
return { uuid, controls, sent, socket, receive: settings => socket.onmessage({ data: JSON.stringify({ event: 'didReceiveGlobalSettings', payload: { settings } }) }) };
}
const a = inspector('sd-TEST.Furumi.Keypad.0.0');
const b = inspector('sd-TEST.Furumi.Infobar.0.0');
let canonical = { future: { keep: 42 }, infobar_background: 'none' };
for (const pi of [a, b]) pi.receive(canonical);
assert.equal(a.controls['album-art-2x2'].disabled, false);
a.controls['album-art-2x2'].checked = true;
a.controls['album-art-2x2'].onchange();
b.controls['invert-colors'].checked = true;
b.controls['invert-colors'].onchange();
for (const pi of [a, b]) {
const message = pi.sent.shift();
assert.equal(message.event, 'sendToPlugin');
assert.equal(message.context, pi.uuid);
assert.equal(message.payload.event, 'preferencesPatch');
assert.equal(Object.keys(message.payload.patch).length, 1);
canonical = { ...canonical, ...message.payload.patch };
// OpenDeck broadcasts runtime setGlobalSettings to every mounted inspector.
for (const inspector of [a, b]) inspector.receive(canonical);
}
assert.equal(canonical.album_art_2x2, true);
assert.equal(canonical.invert_colors, true);
assert.equal(canonical.future.keep, 42);
for (const mode of ['bars', 'spectrogram', 'none']) {
a.controls['infobar-background'].value = mode;
a.controls['infobar-background'].onchange();
const message = a.sent.shift();
assert.deepEqual(message.payload.patch, { infobar_background: mode });
canonical = { ...canonical, ...message.payload.patch };
for (const pi of [a, b]) {
pi.receive(canonical);
assert.equal(pi.controls['infobar-background'].value, mode);
}
}
a.controls['infobar-background'].value = 'invalid';
a.controls['infobar-background'].onchange();
assert.equal(a.sent.length, 0, 'invalid modes must not emit patches');
for (const pi of [a, b]) {
assert.equal(pi.controls['album-art-2x2'].checked, true);
assert.equal(pi.controls['invert-colors'].checked, true);
assert.equal(pi.controls.status.textContent, '');
assert.equal(pi.sent.length, 0, 'inspectors must never rewrite global objects');
pi.socket.onclose();
assert.equal(pi.controls['invert-colors'].disabled, true);
}
console.log('Property Inspector: real script registered both contexts, emitted validated patches, and synchronized two mounted inspectors without losing unknown settings.');
+11 -2
View File
@@ -32,6 +32,9 @@ pub enum Action {
ToggleShuffle,
CycleRepeat,
ToggleVisualizer,
OpenLyrics,
OpenCurrentLyrics,
CycleVisualizerMode,
ToggleLike,
ToggleTrackSelection,
OpenTrackInfo,
@@ -40,7 +43,7 @@ pub enum Action {
QueueAddLast,
MoveQueueUp,
MoveQueueDown,
/// Download the selected federated track(s) into the local library.
/// Download selected federated tracks, or a podcast episode for offline playback.
DownloadSelected,
RemoveFromQueue,
ClearQueue,
@@ -128,7 +131,10 @@ impl Action {
| Action::VolumeDown
| Action::ToggleShuffle
| Action::CycleRepeat
| Action::OpenLyrics
| Action::OpenCurrentLyrics
| Action::ToggleVisualizer
| Action::CycleVisualizerMode
| Action::OpenConnectedDevices
| Action::OpenListenHistory => Category::Playback,
Action::QueueAddNext
@@ -227,7 +233,10 @@ impl Action {
Action::VolumeDown => "Volume down".into(),
Action::ToggleShuffle => "Toggle shuffle".into(),
Action::CycleRepeat => "Cycle repeat mode".into(),
Action::OpenLyrics => "Show selected track lyrics".into(),
Action::OpenCurrentLyrics => "Show now-playing lyrics".into(),
Action::ToggleVisualizer => "Toggle fullscreen visualizer".into(),
Action::CycleVisualizerMode => "Next visualizer display mode".into(),
Action::ToggleLike => "Like / unlike".into(),
Action::ToggleTrackSelection => "Track line selection".into(),
Action::OpenTrackInfo => "Track info".into(),
@@ -236,7 +245,7 @@ impl Action {
Action::QueueAddLast => "Queue: add to end".into(),
Action::MoveQueueUp => "Queue: move track/selection up".into(),
Action::MoveQueueDown => "Queue: move track/selection down".into(),
Action::DownloadSelected => "Federation: download to library".into(),
Action::DownloadSelected => "Download selected music / podcast episode".into(),
Action::RemoveFromQueue => "Queue: remove selected".into(),
Action::ClearQueue => "Queue: clear".into(),
Action::OpenConnectedDevices => "Connected devices…".into(),
+266
View File
@@ -0,0 +1,266 @@
//! Pure control snapshots and routing into the ordinary playback runtime.
use furumi_control_protocol::{API_VERSION, Command, Device, Repeat, Role, Snapshot, Track};
use super::action::Action;
use super::state::{self, AppState, DevicePlaybackRole};
use super::{Runtime, perform_effect, update};
pub(crate) fn published(state: &AppState, revision: u64) -> crate::control::Published {
let now = state::unix_time_ms();
let current = state.player.current.as_ref();
let artwork = crate::control::art::Source::current(state);
let track = current.map(|track| Track {
key: track.key().to_string(),
title: track.title.clone(),
artist: track.artist_line(),
album: track.release_title.clone(),
year: track.release_year,
liked: super::likes::status(state, track),
artwork_id: artwork.id(&track.key().to_string()),
});
let has_episodes = state.player.queue.iter().any(|track| track.is_podcast())
|| current.is_some_and(|track| track.is_podcast());
let mut devices = Vec::new();
if let Some(status) = &state.federation.devices {
for device in status.devices.iter().filter(|device| !device.revoked) {
let is_self =
device.is_self || device.device_id == state.device_playback.self_device_id;
let online = state::device_status_online(state, device, now);
let reason = if state.device_playback.role == DevicePlaybackRole::Jam {
Some("leave the current Jam before switching personal devices")
} else if !online {
Some("device is offline")
} else if !is_self
&& has_episodes
&& !music_dht::device_sync::supports_podcasts(device.protocol_version)
{
Some("this device does not support podcast queues")
} else {
None
};
devices.push(Device {
id: device.device_id.clone(),
name: state::device_display_name(device),
is_self,
active: state.device_playback.active_device_id.as_deref()
== Some(&device.device_id),
online,
can_transfer: reason.is_none(),
unavailable_reason: reason.map(str::to_owned),
});
}
}
if !devices.iter().any(|device| device.is_self) {
let jam = state.device_playback.role == DevicePlaybackRole::Jam;
devices.push(Device {
id: state.device_playback.self_device_id.clone(),
name: state.device_playback.self_device_name.clone(),
is_self: true,
active: state.device_playback.is_audio_owner(),
online: true,
can_transfer: !jam,
unavailable_reason: jam
.then(|| "leave the current Jam before switching personal devices".into()),
});
}
devices.sort_by(|a, b| {
b.is_self
.cmp(&a.is_self)
.then_with(|| a.name.cmp(&b.name))
.then_with(|| a.id.cmp(&b.id))
});
crate::control::Published {
snapshot: Snapshot {
api_version: API_VERSION,
spectrum_supported: true,
revision,
updated_at_ms: now.max(0) as u64,
role: match state.device_playback.role {
DevicePlaybackRole::Active => Role::Active,
DevicePlaybackRole::Control => Role::Control,
DevicePlaybackRole::Jam => Role::Jam,
},
self_device_id: state.device_playback.self_device_id.clone(),
active_device_id: state.device_playback.active_device_id.clone(),
active_device_name: state.device_playback.active_device_name.clone(),
playing: state.player.playing,
paused: state.player.paused,
position_secs: finite(state.player.position_secs),
duration_secs: current
.map(|track| finite(track.duration_seconds))
.unwrap_or(0.0),
volume: state.player.volume,
shuffle: state.player.shuffle,
repeat: match state.player.repeat {
state::RepeatMode::Off => Repeat::Off,
state::RepeatMode::All => Repeat::All,
state::RepeatMode::One => Repeat::One,
},
remote_command: Some(state.device_playback.control.status.clone()),
radio: state.radio.status.clone(),
track,
devices,
},
artwork,
}
}
fn finite(value: f64) -> f64 {
if value.is_finite() {
value.max(0.0)
} else {
0.0
}
}
/// Share the visualizer's existing sample, even when the fullscreen view is
/// closed. A pause freezes the waterfall. Losing the local output clears it.
pub(crate) fn publish_spectrum(
spectrum: &mut crate::control::Spectrum,
state: &AppState,
sampled_at: Option<std::time::Instant>,
preparing: bool,
output_playing: bool,
) {
if preparing || !crate::visualizer::status::visible(state) {
spectrum.clear();
} else if let Some(at) = sampled_at
&& !state.player.paused
&& output_playing
{
spectrum.sample(at, &state.player.audio_analysis.spectrum);
}
}
pub(super) enum Intent {
Action(Action),
Transfer(Device),
Radio,
SetLiked {
track: Box<crate::federation::FedTrack>,
liked: bool,
},
}
pub(super) fn intent(state: &AppState, command: Command) -> Result<Intent, String> {
if !matches!(
command,
Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. }
) {
super::remote_playback::available(state)?;
}
Ok(match command {
Command::PlayPause => {
if state.player.current.is_none() && state.player.queue.is_empty() {
return Err("nothing queued".into());
}
Intent::Action(Action::PlayPause)
}
Command::Next => Intent::Action(Action::NextTrack),
Command::Previous => Intent::Action(Action::PrevTrack),
Command::VolumeUp => Intent::Action(Action::VolumeUp),
Command::VolumeDown => Intent::Action(Action::VolumeDown),
Command::ToggleShuffle => Intent::Action(Action::ToggleShuffle),
Command::CycleRepeat => Intent::Action(Action::CycleRepeat),
Command::StartRadio => Intent::Radio,
Command::SetLiked { track_key, liked } => Intent::SetLiked {
track: Box::new(super::likes::target(state, &track_key)?),
liked,
},
Command::Seek { seconds } => {
if state.player.current.is_none() {
return Err("nothing playing".into());
}
if seconds.unsigned_abs() > 86_400 {
return Err("seek exceeds one day".into());
}
if seconds >= 0 {
Intent::Action(Action::SeekForward {
seconds: seconds as u32,
})
} else {
Intent::Action(Action::SeekBackward {
seconds: seconds.unsigned_abs() as u32,
})
}
}
Command::Transfer { device_id } => {
let device = published(state, 0)
.snapshot
.devices
.into_iter()
.find(|device| device.id == device_id)
.ok_or_else(|| "unknown or revoked device".to_owned())?;
if !device.can_transfer {
return Err(device
.unavailable_reason
.unwrap_or_else(|| "device unavailable".into()));
}
Intent::Transfer(device)
}
Command::Artwork { .. } => {
return Err("artwork requests belong to the control service".into());
}
})
}
pub(super) fn dispatch(
state: &mut AppState,
runtime: &mut Runtime,
request: crate::control::Request,
) {
if matches!(request.command, Command::Seek { .. })
&& !state.device_playback.is_control()
&& let Some(reason) = super::podcast_runtime::seek_refusal(state, runtime)
{
let _ = request.reply.send(Err(reason));
return;
}
let result = match intent(state, request.command) {
Err(error) => Err(error),
Ok(Intent::SetLiked { track, liked }) => {
super::likes::set(runtime, *track, liked, request.reply);
return;
}
Ok(Intent::Radio) => super::radio::start(state, runtime),
Ok(Intent::Action(action)) => {
// Same state transitions, remote targeting and podcast checks as media keys.
let id = state.device_playback.control.status.id;
if let Some(effect) = update(state, action) {
perform_effect(state, runtime, effect);
}
if state.device_playback.role == DevicePlaybackRole::Control
&& state.device_playback.control.status.id == id
{
Err(state
.status_message
.clone()
.unwrap_or_else(|| "No playback change to send".into()))
} else {
Ok(())
}
}
Ok(Intent::Transfer(device)) if device.active => Ok(()),
Ok(Intent::Transfer(device)) => {
if device.is_self {
super::transfer_active_to_this_device_inner(state, runtime, true);
} else {
super::transfer_active_to_remote_device(
state,
runtime,
device.id.clone(),
device.name,
);
}
if state.device_playback.active_device_id.as_ref() == Some(&device.id) {
Ok(())
} else {
Err(state
.status_message
.clone()
.unwrap_or_else(|| "handoff failed".into()))
}
}
};
let _ = request.reply.send(result);
}
+19 -4
View File
@@ -10,10 +10,22 @@ use crate::library::models::{
/// the playback engine, imports). Tasks never touch AppState directly.
#[derive(Debug)]
pub enum AppEvent {
Control(crate::control::Request),
RadioReady {
id: u64,
result: Result<Vec<super::state::SimilaritySearchHit>, String>,
},
Lyrics(super::lyrics::Event),
UpdateChecked(Result<Option<crate::updater::Update>, String>),
UpdateProgress(String),
UpdateInstalled(Result<(), String>),
StatusMessage(String),
/// The local operation was recorded. Output confirmation arrives in a
/// separate DevicePlayback report from the owner.
RemoteCommandRecorded {
id: u64,
result: Result<(), String>,
},
StatusVisualizationReady(crate::visualizer::status::Ready),
/// A page of the artists list arrived (or failed).
ArtistsLoaded(Result<ArtistsPage, String>),
@@ -74,8 +86,8 @@ pub enum AppEvent {
id: i64,
result: Result<PlaylistDetail, String>,
},
/// Liked local content ids for the ♥ markers.
LikesLoaded(Result<Vec<String>, String>),
/// Local and federated identities from a completed library like refresh.
LikesLoaded(Result<super::likes::LikeIds, String>),
/// Local-library content ids for availability markers.
LocalContentIdsLoaded(Result<Vec<String>, String>),
/// Counts and storage footprint of the local library/database.
@@ -91,8 +103,6 @@ pub enum AppEvent {
content_id: String,
liked: bool,
},
/// Liked federated item ids and content ids for the ♥ markers.
FedLikesLoaded(Result<Vec<String>, String>),
FedLikeToggled {
item_id: String,
content_id: Option<String>,
@@ -273,6 +283,11 @@ pub enum AppEvent {
},
/// Scheduler timer: ask the store which feeds are due.
PodcastRefreshTick,
PodcastDownloads(Result<std::collections::HashSet<String>, String>),
PodcastDownloaded {
id: String,
result: Result<(), String>,
},
/// Feeds due for a background refresh.
PodcastsDue(Result<Vec<(music_dht::podcast::PodcastId, music_dht::podcast::FeedUrl)>, String>),
/// What sharing a podcast would publish (`Effect::PodcastPrepareShare`).
+41
View File
@@ -36,6 +36,47 @@ impl LineEdit {
.unwrap_or(self.value.len())
}
pub fn line_cursor(&self) -> (usize, usize) {
let before = &self.value[..self.byte_index(self.cursor)];
(
before.bytes().filter(|&byte| byte == b'\n').count(),
before
.rsplit('\n')
.next()
.unwrap_or_default()
.chars()
.count(),
)
}
pub fn move_line(&mut self, direction: isize) {
let (row, column) = self.line_cursor();
self.move_to_line(row.saturating_add_signed(direction), column);
}
pub fn line_edge(&mut self, end: bool) {
let (row, _) = self.line_cursor();
self.move_to_line(row, if end { usize::MAX } else { 0 });
}
fn move_to_line(&mut self, row: usize, column: usize) {
let mut start = 0;
for (index, line) in self.value.split('\n').enumerate() {
let len = line.chars().count();
if index == row {
self.cursor = start + column.min(len);
return;
}
start += len + 1;
}
}
pub fn with_cursor(value: impl Into<String>, cursor: usize) -> Self {
let mut edit = Self::new(value);
edit.cursor = edit.cursor.min(cursor);
edit
}
pub fn clear(&mut self) {
self.value.clear();
self.cursor = 0;
+247
View File
@@ -0,0 +1,247 @@
//! Personal library likes shared by the TUI and local control surfaces.
use std::collections::HashSet;
use anyhow::{Result, ensure};
use tokio::sync::{mpsc, oneshot};
use super::event::AppEvent;
use super::state::{self, AppState};
use super::{Runtime, err_string, update};
use crate::devices::DeviceSync;
use crate::federation::FedTrack;
use crate::library::{Library, models::TrackItem};
#[derive(Debug)]
pub(crate) struct LikeIds {
pub local: HashSet<String>,
pub federated: HashSet<String>,
}
impl LikeIds {
fn load(library: &Library) -> Result<Self> {
Ok(Self {
local: library.liked_content_ids()?.into_iter().collect(),
federated: library.fed_like_ids()?.into_iter().collect(),
})
}
fn contains(&self, track: &FedTrack) -> bool {
self.federated.contains(&track.item_id)
|| track
.content_id
.as_ref()
.is_some_and(|id| self.local.contains(id) || self.federated.contains(id))
}
}
// Serialize library reads and edits from the keyboard and control clients.
// In particular, old federated entries without a content ID have only a local
// toggle operation and cannot be changed by a trusted-device sync.
pub(super) fn in_background(
runtime: &Runtime,
work: impl FnOnce(&Library, &DeviceSync, &mpsc::UnboundedSender<AppEvent>) + Send + 'static,
) {
let (library, devices, tx, gate) = (
runtime.library.clone(),
runtime.devices.clone(),
runtime.event_tx.clone(),
runtime.like_io.clone(),
);
tokio::task::spawn_blocking(move || {
let _guard = gate.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
work(&library, &devices, &tx);
});
}
pub(super) fn reload(library: &Library, tx: &mpsc::UnboundedSender<AppEvent>) {
let _ = tx.send(AppEvent::LikesLoaded(
LikeIds::load(library).map_err(err_string),
));
}
pub(super) fn status(state: &AppState, track: &TrackItem) -> Option<bool> {
let identifiable = state::track_content_id(track).is_some()
|| track
.fed
.as_ref()
.is_some_and(|fed| !fed.item_id.is_empty());
(state.likes_ready && !track.is_podcast() && identifiable).then(|| state.track_liked(track))
}
pub(super) fn target(state: &AppState, key: &str) -> Result<FedTrack, String> {
let track = state
.player
.current
.as_ref()
.filter(|track| track.key().to_string() == key)
.ok_or("Track is no longer current")?;
status(state, track).ok_or("Likes are unavailable for this track")?;
let mut fed = update::fed_track_for_download(track).ok_or("Track has no music identity")?;
fed.content_id = state::track_content_id(track);
if fed.item_id.is_empty() {
// A controller may only know the content hash and the owner's playback
// metadata. Keep distinct playlist entries and resolve by hash on play.
fed.item_id = fed
.content_id
.clone()
.ok_or("Track has no music identity")?;
}
Ok(fed)
}
pub(super) fn set(
runtime: &Runtime,
track: FedTrack,
liked: bool,
reply: oneshot::Sender<Result<(), String>>,
) {
in_background(runtime, move |library, devices, tx| {
let write = set_in_library(library, devices, &track, liked, tx).map_err(err_string);
// Refresh both kinds of markers even after a partial storage failure.
// Only confirm a state that the library can actually read back.
let ids = LikeIds::load(library).map_err(err_string);
let saved = match &ids {
Ok(ids) if ids.contains(&track) == liked => Ok(()),
Ok(_) => Err("Liked state changed during the update".into()),
Err(error) => Err(error.clone()),
};
let _ = tx.send(AppEvent::LikesLoaded(ids));
let _ = reply.send(write.and(saved));
});
}
fn set_in_library(
library: &Library,
devices: &DeviceSync,
track: &FedTrack,
liked: bool,
tx: &mpsc::UnboundedSender<AppEvent>,
) -> Result<()> {
let previous = LikeIds::load(library)?;
if previous.contains(track) == liked {
return Ok(());
}
let event = if let Some(id) = &track.content_id
&& library.track_id_by_content_id(id)?.is_some()
{
// This absolute sync operation also updates the local library offline.
devices.record_content_like(id, liked)?;
if !liked && previous.federated.contains(id) {
library.remove_fed_like_by_content_id(id)?;
}
AppEvent::LikeToggled {
content_id: id.clone(),
liked,
}
} else {
if track.content_id.is_some() {
devices.record_fed_like(track, liked)?;
} else {
// Keyboard and control requests share the library's item-ID-only toggle.
ensure!(
library.toggle_fed_like(track)? == liked,
"Liked state changed during the update"
);
}
AppEvent::FedLikeToggled {
item_id: track.item_id.clone(),
content_id: track.content_id.clone(),
liked,
}
};
// A federated like saved before its hash was known can still have a
// separate item-ID-only row. Remove that old identity as well.
if !liked
&& let Some(id) = &track.content_id
&& previous.federated.contains(&track.item_id)
&& !previous.federated.contains(id)
&& library.fed_like_ids()?.contains(&track.item_id)
{
ensure!(
!library.toggle_fed_like(track)?,
"Liked state changed during the update"
);
}
let _ = tx.send(event);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn explicit_sets_are_idempotent_in_local_federated_and_legacy_libraries() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("library.sqlite3");
let library = Arc::new(Library::open(&path).unwrap());
let devices = DeviceSync::with_test_library(library.clone());
let (tx, mut events) = mpsc::unbounded_channel();
let local_id = format!("b3:{:064x}", 1);
let remote_id = format!("b3:{:064x}", 2);
let db = rusqlite::Connection::open(&path).unwrap();
db.execute("INSERT INTO releases (id, title) VALUES (1, 'Test')", [])
.unwrap();
db.execute("INSERT INTO tracks (title, release_id, file_path, content_id) VALUES ('One', 1, 'one.wav', ?1)", [&local_id]).unwrap();
drop(db);
for (key, content_id) in [
(local_id.clone(), Some(local_id.clone())),
(remote_id.clone(), Some(remote_id.clone())),
("legacy-item".into(), None),
] {
let track = FedTrack {
item_id: key,
content_id,
owner: String::new(),
own: false,
title: "Track".into(),
artist_names: vec!["Artist".into()],
featured_artist_names: vec![],
release_title: None,
year: None,
duration_seconds: None,
track_number: None,
disc_number: None,
};
for liked in [true, false] {
set_in_library(&library, &devices, &track, liked, &tx).unwrap();
let event = events.try_recv().unwrap();
if track.content_id.as_ref() == Some(&local_id) {
assert!(
matches!(event, AppEvent::LikeToggled { liked: actual, .. } if actual == liked)
);
} else {
assert!(
matches!(event, AppEvent::FedLikeToggled { liked: actual, .. } if actual == liked)
);
}
set_in_library(&library, &devices, &track, liked, &tx).unwrap();
assert!(
events.try_recv().is_err(),
"a retry must not toggle the like again"
);
let reopened = Library::open(&path).unwrap();
assert_eq!(LikeIds::load(&reopened).unwrap().contains(&track), liked);
assert_eq!(
reopened
.playlist(furumi_library::LIKES_PLAYLIST_ID)
.unwrap()
.tracks
.len(),
usize::from(liked)
);
}
if track.content_id.is_none() {
set_in_library(&library, &devices, &track, true, &tx).unwrap();
let identified = FedTrack {
content_id: Some(remote_id.clone()),
..track
};
set_in_library(&library, &devices, &identified, false, &tx).unwrap();
assert!(!LikeIds::load(&library).unwrap().contains(&identified));
}
}
}
}
+788
View File
@@ -0,0 +1,788 @@
//! Lyrics effects, playback selection, and the track editor.
use super::Runtime;
use super::event::AppEvent;
use super::input::LineEdit;
use super::state::{AppState, Popup, track_content_id};
use crate::library::models::TrackItem;
use crate::lyrics::{self, Document, SavedLyrics};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use music_dht::lyrics::{LyricsVersion, MAX_LYRICS_TEXT_BYTES};
use std::{
collections::HashSet,
sync::Arc,
time::{Duration, Instant},
};
#[derive(Debug, Default)]
pub(crate) struct Playback {
pub title: String,
pub content_id: Option<String>,
pub versions: Vec<LyricsVersion>,
pub selected: usize,
pub document: Document,
pub document_revision: u64,
pub loading: bool,
track: Option<(i64, Option<String>)>,
local_at: Option<Instant>,
local_reading: bool,
serial: u64,
hidden: HashSet<String>,
retry_at: Option<Instant>,
task: Option<tokio::task::AbortHandle>,
}
impl Playback {
pub(super) fn refresh_local(&mut self) {
self.local_at = Some(Instant::now());
}
fn local_changed(&mut self, content_id: &str) {
if self.content_id.as_deref() == Some(content_id)
|| self.track.as_ref().and_then(|(_, id)| id.as_deref()) == Some(content_id)
{
self.refresh_local();
}
}
fn select(&mut self, index: usize) {
self.document_revision = self.document_revision.wrapping_add(1);
self.selected = index.min(self.versions.len().saturating_sub(1));
self.document = self
.versions
.get(self.selected)
.map(Document::new)
.unwrap_or_default();
}
fn add(&mut self, versions: Vec<LyricsVersion>) {
let first = self.versions.is_empty();
lyrics::merge(&mut self.versions, versions, &self.hidden);
if first && !self.versions.is_empty() {
self.select(0);
}
}
fn saved(&mut self, saved: SavedLyrics) {
if self.hidden == saved.hidden && self.versions.starts_with(&saved.versions) {
return;
}
let selected = self
.versions
.get(self.selected)
.map(|entry| entry.id.clone());
self.hidden = saved.hidden;
let existing = std::mem::replace(&mut self.versions, saved.versions);
self.add(existing);
self.select(
selected
.and_then(|id| self.versions.iter().position(|v| v.id == id))
.unwrap_or(0),
);
}
}
#[derive(Debug, Default)]
pub(crate) struct Reader {
pub top: Option<usize>,
pub viewport_height: usize,
pub preview: Option<Box<(TrackItem, Playback)>>,
pub rows: Vec<(usize, String)>,
pub layout_key: Option<(u64, usize)>,
}
impl Reader {
pub fn preview(track: TrackItem) -> Self {
Self {
preview: Some(Box::new((track, Playback::default()))),
..Self::default()
}
}
pub fn lyrics<'a>(&'a self, playback: &'a Playback) -> &'a Playback {
self.preview.as_ref().map_or(playback, |preview| &preview.1)
}
pub fn active_line(
&self,
playback: &Playback,
player: &super::state::PlayerBar,
) -> Option<usize> {
if let Some(preview) = &self.preview
&& !player.current.as_ref().is_some_and(|track| {
super::state::track_key(track) == super::state::track_key(&preview.0)
})
{
return None;
}
self.lyrics(playback).document.line_at(player.position_secs)
}
fn cancel_preview(&mut self) {
if let Some(task) = self
.preview
.as_mut()
.and_then(|preview| preview.1.task.take())
{
task.abort();
}
}
pub fn follow_top(&self, active: Option<usize>) -> usize {
active
.map(|active| self.rows.partition_point(|(index, _)| *index < active))
.unwrap_or_default()
.saturating_sub(self.viewport_height / 2)
.min(self.rows.len().saturating_sub(self.viewport_height))
}
}
#[derive(Debug)]
pub(crate) struct Editor {
pub parent: Box<Popup>,
pub track_id: i64,
pub query: u64,
pub content_id: Option<String>,
pub versions: Vec<LyricsVersion>,
pub cursor: usize,
pub draft: Option<Draft>,
pub busy: bool,
pub confirm_delete: bool,
pub error: Option<String>,
}
#[derive(Debug)]
pub(crate) struct Draft {
pub replaced: Option<String>,
pub label: LineEdit,
pub text: LineEdit,
pub label_focused: bool,
}
#[derive(Debug)]
pub(crate) enum Event {
Local {
serial: u64,
content_id: Option<String>,
saved: SavedLyrics,
},
Saved(String),
Polled {
serial: u64,
saved: Option<SavedLyrics>,
},
Found {
serial: u64,
versions: Vec<LyricsVersion>,
},
Done {
serial: u64,
},
Editor {
query: u64,
result: Result<(String, SavedLyrics), String>,
},
Edited {
query: u64,
result: Result<(String, SavedLyrics), String>,
},
}
fn send(tx: &tokio::sync::mpsc::UnboundedSender<AppEvent>, event: Event) {
let _ = tx.send(AppEvent::Lyrics(event));
}
pub(super) fn refresh(state: &mut AppState, runtime: &Runtime) {
let changed = refresh_one(&mut state.lyrics, state.player.current.as_ref(), runtime);
if let Some(Popup::Lyrics(reader)) = state.popup.as_mut() {
let changed = match reader.preview.as_deref_mut() {
Some((track, lyrics)) => refresh_one(lyrics, Some(track), runtime),
None => changed,
};
if changed {
reader.top = None;
reader.layout_key = None;
}
}
}
fn refresh_one(playback: &mut Playback, track: Option<&TrackItem>, runtime: &Runtime) -> bool {
let track = track.filter(|track| !track.is_podcast());
let key = track.map(|track| (track.id, track_content_id(track)));
let same = playback.track == key
|| matches!((&playback.track, &key),
(Some((_, Some(old))), Some((_, Some(new)))) if old == new);
if !same {
if let Some(task) = playback.task.take() {
task.abort();
}
*playback = Playback {
title: track.map(|track| track.title.clone()).unwrap_or_default(),
..Playback::default()
};
}
playback.track = key;
let Some(track) = track else { return !same };
let now = Instant::now();
if same && (playback.loading || playback.retry_at.is_none_or(|at| at > now)) {
if !playback.local_reading
&& playback.local_at.is_some_and(|at| at <= now)
&& let Some(content_id) = playback.content_id.clone()
{
playback.local_reading = true;
playback.local_at = None;
let serial = playback.serial;
let library = Arc::clone(&runtime.library);
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
let saved = library
.lyrics(&content_id)
.map_err(|error| {
tracing::warn!(%error, "could not refresh local lyrics");
})
.ok();
send(&tx, Event::Polled { serial, saved });
});
}
return false;
}
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
playback.serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
playback.loading = true;
playback.retry_at = None;
playback.local_reading = false;
playback.local_at = None;
let serial = playback.serial;
let id = track.id;
let content_id = playback
.content_id
.clone()
.or_else(|| track_content_id(track));
let owner = track.fed.as_ref().map(|fed| fed.owner.clone());
let library = Arc::clone(&runtime.library);
let federation = Arc::clone(&runtime.federation);
let tx = runtime.event_tx.clone();
let task = tokio::spawn(async move {
let local = tokio::task::spawn_blocking({
let library = Arc::clone(&library);
move || -> anyhow::Result<_> {
let content_id = match content_id {
Some(content_id) => Some(content_id),
None if id > 0 => library.track_content_id_by_id(id)?,
None => None,
};
let saved = content_id
.as_deref()
.map(|id| library.lyrics(id))
.transpose();
Ok((content_id, saved))
}
})
.await;
if let Ok(Ok((content_id, saved))) = local {
let saved = saved
.unwrap_or_else(|error| {
tracing::warn!(%error, "could not read local lyrics");
None
})
.unwrap_or_default();
let hidden = saved.hidden.clone();
send(
&tx,
Event::Local {
serial,
content_id: content_id.clone(),
saved,
},
);
if let Some(content_id) = content_id {
let mut found = Vec::new();
let _ = federation
.find_lyrics(&content_id, owner.as_deref(), |versions| {
let previous = found.len();
lyrics::merge(&mut found, versions, &hidden);
if found.len() > previous {
let versions = found[previous..].to_vec();
if federation.settings().save_on_listen {
store_found(
Arc::clone(&library),
content_id.clone(),
versions.clone(),
tx.clone(),
);
}
send(&tx, Event::Found { serial, versions });
}
})
.await;
}
} else {
tracing::warn!("lyrics library lookup failed");
}
send(&tx, Event::Done { serial });
});
playback.task = Some(task.abort_handle());
!same
}
fn store_found(
library: Arc<crate::library::Library>,
content_id: String,
versions: Vec<LyricsVersion>,
tx: tokio::sync::mpsc::UnboundedSender<AppEvent>,
) {
if !versions.is_empty() {
tokio::task::spawn_blocking(move || match library.merge_lyrics(&content_id, versions) {
Ok(()) => send(&tx, Event::Saved(content_id)),
Err(error) => tracing::warn!(%error, %content_id, "could not save peer lyrics"),
});
}
}
/// Audio can become permanent after the lyrics request already completed.
pub(super) fn on_import(state: &AppState, runtime: &Runtime, track: &TrackItem) {
let Some(content_id) = track_content_id(track) else {
return;
};
if state.lyrics.content_id.as_deref() == Some(content_id.as_str()) {
store_found(
Arc::clone(&runtime.library),
content_id,
state.lyrics.versions.clone(),
runtime.event_tx.clone(),
);
} else if runtime.federation.settings().save_on_listen {
// The queue could have advanced while the audio was still downloading.
let federation = Arc::clone(&runtime.federation);
let library = Arc::clone(&runtime.library);
let tx = runtime.event_tx.clone();
tokio::spawn(async move {
let mut versions = Vec::new();
let _ = federation
.find_lyrics(&content_id, None, |incoming| {
lyrics::merge(&mut versions, incoming, &HashSet::new());
})
.await;
store_found(library, content_id, versions, tx);
});
}
}
pub(super) fn handle_event(state: &mut AppState, event: Event) {
let preview = match &mut state.popup {
Some(Popup::Lyrics(reader)) => reader.preview.as_deref_mut().map(|preview| &mut preview.1),
_ => None,
};
if let Event::Saved(content_id) = &event {
state.lyrics.local_changed(content_id);
if let Some(preview) = preview {
preview.local_changed(content_id);
}
return;
}
let serial = match &event {
Event::Local { serial, .. }
| Event::Polled { serial, .. }
| Event::Found { serial, .. }
| Event::Done { serial } => Some(*serial),
_ => None,
};
let playback = match serial {
Some(serial) if state.lyrics.serial != serial => {
let Some(preview) = preview.filter(|preview| preview.serial == serial) else {
return;
};
preview
}
_ => &mut state.lyrics,
};
match event {
Event::Local {
content_id, saved, ..
} => {
playback.content_id = content_id;
playback
.local_at
.get_or_insert_with(|| Instant::now() + Duration::from_secs(1));
playback.saved(saved);
}
Event::Polled { saved, .. } => {
playback.local_reading = false;
// A write notification may have arrived while this read was in flight.
playback
.local_at
.get_or_insert_with(|| Instant::now() + Duration::from_secs(1));
if let Some(saved) = saved {
playback.saved(saved);
}
}
Event::Found { versions, .. } => playback.add(versions),
Event::Done { .. } => {
playback.task = None;
playback.loading = false;
playback.retry_at = Some(Instant::now() + Duration::from_secs(60));
}
Event::Editor { query, result } | Event::Edited { query, result } => {
if let Ok((content_id, saved)) = &result
&& playback.content_id.as_deref() == Some(content_id)
{
playback.saved(SavedLyrics {
versions: saved.versions.clone(),
hidden: saved.hidden.clone(),
});
}
if let Some(Popup::LyricsEditor(editor)) = &mut state.popup
&& editor.query == query
{
editor.busy = false;
match result {
Ok((content_id, saved)) => {
editor.content_id = Some(content_id);
editor.versions = saved.versions;
editor.cursor = editor.cursor.min(editor.versions.len().saturating_sub(1));
editor.draft = None;
editor.error = None;
}
Err(error) => editor.error = Some(error),
}
}
}
Event::Saved(_) => {}
}
}
pub(super) fn reader_key(state: &mut AppState, mut reader: Reader, key: KeyEvent) {
if key.code == KeyCode::Char('l') {
match key.modifiers {
KeyModifiers::CONTROL if reader.preview.is_some() => {
reader.cancel_preview();
let _ = super::update::update(state, super::action::Action::OpenCurrentLyrics);
return;
}
KeyModifiers::NONE if reader.preview.is_none() => {
let _ = super::update::update(state, super::action::Action::OpenLyrics);
return;
}
_ => {}
}
}
let last = reader.rows.len().saturating_sub(reader.viewport_height);
let top = reader
.top
.unwrap_or_else(|| reader.follow_top(reader.active_line(&state.lyrics, &state.player)));
let playback = reader
.preview
.as_deref_mut()
.map_or(&mut state.lyrics, |preview| &mut preview.1);
let page = reader.viewport_height.saturating_sub(1).max(1);
match key.code {
KeyCode::Esc | KeyCode::Char('l' | 'q') => {
reader.cancel_preview();
return;
}
KeyCode::Up | KeyCode::Char('k') => reader.top = Some(top.saturating_sub(1)),
KeyCode::Down | KeyCode::Char('j') => reader.top = Some((top + 1).min(last)),
KeyCode::PageUp => reader.top = Some(top.saturating_sub(page)),
KeyCode::PageDown => reader.top = Some((top + page).min(last)),
KeyCode::Home => reader.top = Some(0),
KeyCode::End => reader.top = Some(last),
KeyCode::Char('f') => reader.top = None,
KeyCode::Right | KeyCode::Tab if !playback.versions.is_empty() => {
playback.select((playback.selected + 1) % playback.versions.len());
reader.top = None;
}
KeyCode::Left | KeyCode::BackTab if !playback.versions.is_empty() => {
playback.select(
(playback.selected + playback.versions.len() - 1) % playback.versions.len(),
);
reader.top = None;
}
_ => {}
}
state.popup = Some(Popup::Lyrics(reader));
}
pub(super) fn open_editor(state: &mut AppState, runtime: &Runtime, parent: Popup, track_id: i64) {
static NEXT_QUERY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let query = NEXT_QUERY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
state.popup = Some(Popup::LyricsEditor(Box::new(Editor {
parent: Box::new(parent),
track_id,
query,
content_id: None,
versions: Vec::new(),
cursor: 0,
draft: None,
busy: true,
confirm_delete: false,
error: None,
})));
let tx = runtime.event_tx.clone();
let library = Arc::clone(&runtime.library);
tokio::task::spawn_blocking(move || {
let result = (|| -> anyhow::Result<_> {
let content_id = match library.track_content_id_by_id(track_id)? {
Some(id) => Some(id),
None => library
.tracks_by_ids(&[track_id])?
.first()
.and_then(|track| crate::library::audio_content_id(&track.file_path)),
}
.ok_or_else(|| anyhow::anyhow!("Could not identify the local audio file"))?;
let saved = library.lyrics(&content_id)?;
Ok((content_id, saved))
})()
.map_err(|error| format!("{error:#}"));
send(&tx, Event::Editor { query, result });
});
}
pub(super) fn editor_key(
state: &mut AppState,
runtime: &Runtime,
mut editor: Box<Editor>,
key: KeyEvent,
) {
if !editor.busy {
if let Some(draft) = &mut editor.draft {
match key.code {
KeyCode::Esc => {
editor.draft = None;
editor.error = None;
}
KeyCode::F(2) => save_draft(runtime, &mut editor),
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
save_draft(runtime, &mut editor)
}
KeyCode::Tab | KeyCode::BackTab => draft.label_focused = !draft.label_focused,
_ if draft.label_focused => {
if draft.label.len() < 512 || !matches!(key.code, KeyCode::Char(_)) {
draft.label.handle_key(key);
}
}
KeyCode::Enter if draft.text.len() < MAX_LYRICS_TEXT_BYTES => {
draft.text.insert('\n')
}
KeyCode::Up => draft.text.move_line(-1),
KeyCode::Down => draft.text.move_line(1),
KeyCode::Home => draft.text.line_edge(false),
KeyCode::End => draft.text.line_edge(true),
_ => {
if draft.text.len() < MAX_LYRICS_TEXT_BYTES
|| !matches!(key.code, KeyCode::Char(_))
{
draft.text.handle_key(key);
}
}
}
} else if editor.confirm_delete {
editor.confirm_delete = false;
if matches!(key.code, KeyCode::Char('y') | KeyCode::Enter) {
let id = editor
.versions
.get(editor.cursor)
.map(|entry| entry.id.clone());
submit(runtime, &mut editor, id, None);
}
} else {
match key.code {
KeyCode::Esc => {
state.popup = Some(*editor.parent);
return;
}
KeyCode::Up => editor.cursor = editor.cursor.saturating_sub(1),
KeyCode::Down => {
editor.cursor = (editor.cursor + 1).min(editor.versions.len().saturating_sub(1))
}
KeyCode::Char('a') if editor.content_id.is_some() => {
editor.error = None;
editor.draft = Some(Draft {
replaced: None,
label: LineEdit::default(),
text: LineEdit::default(),
label_focused: false,
});
}
KeyCode::Enter if editor.content_id.is_some() => {
if let Some(entry) = editor.versions.get(editor.cursor) {
editor.error = None;
editor.draft = Some(Draft {
replaced: Some(entry.id.clone()),
label: LineEdit::new(
lyrics::clean_text(&entry.label).replace('\n', " "),
),
text: LineEdit::new(lyrics::clean_text(
entry
.synced_lrc
.as_deref()
.or(entry.plain_text.as_deref())
.unwrap_or_default(),
)),
label_focused: false,
});
}
}
KeyCode::Delete | KeyCode::Char('d') if !editor.versions.is_empty() => {
editor.confirm_delete = true
}
_ => {}
}
}
}
state.popup = Some(Popup::LyricsEditor(editor));
}
fn save_draft(runtime: &Runtime, editor: &mut Editor) {
if let Some(draft) = editor.draft.as_ref() {
match lyrics::manual_version(&draft.label, &draft.text) {
Ok(version) => submit(runtime, editor, draft.replaced.clone(), Some(version)),
Err(error) => editor.error = Some(format!("{error:#}")),
}
}
}
fn submit(
runtime: &Runtime,
editor: &mut Editor,
replaced: Option<String>,
version: Option<LyricsVersion>,
) {
let Some(content_id) = editor.content_id.clone() else {
return;
};
let library = Arc::clone(&runtime.library);
let track_id = editor.track_id;
let tx = runtime.event_tx.clone();
let query = editor.query;
editor.busy = true;
editor.error = None;
tokio::task::spawn_blocking(move || {
let result = (|| -> anyhow::Result<_> {
let track = library
.tracks_by_ids(&[track_id])?
.into_iter()
.next()
.ok_or_else(|| anyhow::anyhow!("The local track has been removed"))?;
let current_id = track_content_id(&track)
.or_else(|| crate::library::audio_content_id(&track.file_path));
anyhow::ensure!(
current_id.as_deref() == Some(&content_id),
"The local audio has changed"
);
let saved = library.edit_lyrics(track_id, &content_id, replaced.as_deref(), version)?;
Ok((content_id, saved))
})()
.map_err(|error| format!("{error:#}"));
send(&tx, Event::Edited { query, result });
});
}
pub(super) fn paste(editor: &mut Editor, pasted: &str) {
if editor.busy {
return;
}
let Some(draft) = &mut editor.draft else {
return;
};
let cleaned = lyrics::clean_text(pasted);
let (input, text, limit): (_, _, usize) = if draft.label_focused {
(&mut draft.label, cleaned.replace('\n', " "), 512)
} else {
(&mut draft.text, cleaned, MAX_LYRICS_TEXT_BYTES)
};
if text.len() <= limit.saturating_sub(input.len()) {
input.insert_str(&text);
editor.error = None;
} else {
editor.error = Some("Pasted text exceeds the field size limit".into());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn late_peer_results_cannot_replace_the_current_track_or_selected_version() {
let mut state = AppState::default();
state.lyrics.serial = 2;
let local = lyrics::manual_version("Local", "Current song").unwrap();
state.lyrics.saved(SavedLyrics {
versions: vec![local.clone()],
..Default::default()
});
handle_event(
&mut state,
Event::Found {
serial: 1,
versions: vec![lyrics::manual_version("Old", "Previous song").unwrap()],
},
);
assert_eq!(state.lyrics.versions, [local]);
handle_event(
&mut state,
Event::Found {
serial: 2,
versions: vec![lyrics::manual_version("Peer", "[00:01]Timed song").unwrap()],
},
);
assert_eq!(state.lyrics.versions.len(), 2);
assert_eq!(state.lyrics.document.lines, ["Current song"]);
reader_key(
&mut state,
Reader::default(),
KeyEvent::new(KeyCode::Right, KeyModifiers::NONE),
);
assert_eq!(state.lyrics.document.line_at(1.0), Some(0));
assert_eq!(state.lyrics.document.lines, ["Timed song"]);
}
#[test]
fn saved_lyrics_refresh_playback_even_after_network_lookup_ended() {
let mut state = AppState::default();
let content_id = format!("b3:{}", "a".repeat(64));
state.lyrics.content_id = Some(content_id.clone());
state.lyrics.serial = 2;
handle_event(&mut state, Event::Done { serial: 2 });
let retry_at = state.lyrics.retry_at;
handle_event(&mut state, Event::Saved(content_id));
assert!(state.lyrics.local_at.unwrap() <= Instant::now());
// The local read is independent of the pending network retry.
let version = lyrics::manual_version("Saved", "[00:01]Received words").unwrap();
handle_event(
&mut state,
Event::Polled {
serial: 2,
saved: Some(SavedLyrics {
versions: vec![version],
..Default::default()
}),
},
);
assert_eq!(state.lyrics.document.lines, ["Received words"]);
assert_eq!(state.lyrics.document.line_at(1.0), Some(0));
assert_eq!(state.lyrics.retry_at, retry_at);
}
#[test]
fn reader_scrolls_plain_text_one_row_per_keypress() {
let mut state = AppState::default();
let reader = Reader {
viewport_height: 4,
rows: (0..8)
.map(|index| (index, format!("Line {index}")))
.collect(),
..Default::default()
};
reader_key(
&mut state,
reader,
KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
);
assert!(matches!(
state.popup,
Some(Popup::Lyrics(Reader { top: Some(1), .. }))
));
}
}
+220 -72
View File
@@ -1,13 +1,18 @@
pub mod action;
mod cmdline;
pub mod command;
pub(crate) mod control;
mod enrichment;
pub mod event;
pub mod input;
mod likes;
pub(crate) mod lyrics;
#[cfg(test)]
pub(crate) mod podcast_fixtures;
pub(crate) mod podcast_runtime;
pub(crate) mod popup;
mod radio;
mod remote_playback;
pub mod state;
pub mod update;
@@ -43,10 +48,12 @@ const VISUALIZER_TICK_INTERVAL: Duration = Duration::from_millis(50);
pub struct Runtime {
pub event_tx: mpsc::UnboundedSender<AppEvent>,
pub library: Arc<Library>,
like_io: Arc<std::sync::Mutex<()>>,
pub devices: Arc<crate::devices::DeviceSync>,
pub jam: Arc<crate::jam::JamManager>,
pub federation: Arc<crate::federation::Federation>,
pub similarity: Arc<crate::similarity::Manager>,
pub radio_task: Option<tokio::task::JoinHandle<()>>,
/// When the last Federation-tab status snapshot was requested.
pub fed_status_at: Option<std::time::Instant>,
/// Keeps the last successful local-data snapshot visible while a newer
@@ -422,6 +429,7 @@ pub async fn run(
status_message,
..AppState::default()
};
state.podcast_retention_days = settings.podcast_retention_days;
state.player.volume = settings.volume;
state.global.filters = settings.library;
state.music_dir = settings.music_dir.clone();
@@ -462,10 +470,12 @@ pub async fn run(
let mut runtime = Runtime {
event_tx,
library,
like_io: Arc::default(),
devices,
jam,
federation,
similarity,
radio_task: None,
fed_status_at: None,
local_library_stats_refreshing: Arc::new(std::sync::atomic::AtomicBool::new(false)),
local_library_stats_refresh_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
@@ -521,6 +531,24 @@ pub async fn run(
let mut visual_tick = tokio::time::interval(VISUALIZER_TICK_INTERVAL);
visual_tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut redraw = true;
let mut control_service = match crate::control::Service::start(
control::published(&state, 0),
runtime.event_tx.clone(),
runtime.library.clone(),
runtime.federation.clone(),
)
.await
{
Ok(service) => Some(service),
Err(error) => {
tracing::warn!(%error, "local control unavailable");
state.status_message = Some(format!("local control unavailable: {error}"));
None
}
};
let mut control_revision = 0u64;
let mut published_command = state.device_playback.control.status.clone();
let mut control_published_at = std::time::Instant::now();
loop {
let plain_text = match state.popup.as_ref() {
@@ -546,22 +574,40 @@ pub async fn run(
terminal.clear()?;
runtime.force_redraw = false;
}
ui::lyrics::prepare_reader(&mut state, terminal.get_frame().area());
terminal.draw(|frame| ui::draw(frame, &state, &keymap))?;
}
redraw = true;
let mut spectrum_sample_at = None;
tokio::select! {
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);
lyrics::refresh(&mut state, &runtime);
},
Some(Err(err)) => return Err(err.into()),
None => state.should_quit = true,
},
Some(app_event) = event_rx.recv() => handle_app_event(&mut state, &mut runtime, app_event),
Some(app_event) = event_rx.recv() => {
if matches!(&app_event, AppEvent::Player(
player::PlayerEvent::Started
| player::PlayerEvent::TrackFinished { .. }
| player::PlayerEvent::Seeked { result: Ok(()), .. }
)) && let Some(service) = &mut control_service {
service.spectrum.clear();
}
handle_app_event(&mut state, &mut runtime, app_event);
lyrics::refresh(&mut state, &runtime);
},
_ = tick.tick() => {
radio::tick(&mut state, &mut runtime);
remote_playback::tick(&mut state, std::time::Instant::now());
reconcile_personal_playback(&mut state, &mut runtime);
state.advance_spinner();
expire_quit_confirmation(&mut state);
sync_player_shared(&mut state, &runtime);
lyrics::refresh(&mut state, &runtime);
podcast_runtime::tick(&state, &mut runtime);
runtime
.status_publisher
@@ -569,7 +615,7 @@ pub async fn run(
maybe_prefetch_next(&mut state, &runtime);
push_media_update(&state, &mut runtime, false);
}
_ = visual_tick.tick(), if state.visualizer.active || crate::visualizer::status::playing(&state) => {
at = visual_tick.tick(), if state.visualizer.active || crate::visualizer::status::playing(&state) => {
if state.visualizer.active {
sync_player_shared(&mut state, &runtime);
} else {
@@ -580,6 +626,7 @@ pub async fn run(
// meter once here and the new meter again on completion.
redraw = false;
}
spectrum_sample_at = Some(at.into_std());
sync_status_visualizer_target(&mut state, terminal.get_frame().area());
if !runtime.plain_text_mode {
runtime.status_visualizer.request(&state, runtime.event_tx.clone());
@@ -587,6 +634,24 @@ pub async fn run(
}
}
remote_playback::tick(&mut state, std::time::Instant::now());
if let Some(service) = &mut control_service {
control::publish_spectrum(
&mut service.spectrum,
&state,
spectrum_sample_at,
runtime.player_start_pending,
runtime.player.shared.output_playing(),
);
if control_published_at.elapsed() >= TICK_INTERVAL
|| published_command != state.device_playback.control.status
{
control_revision = control_revision.wrapping_add(1);
published_command = state.device_playback.control.status.clone();
service.publish(control::published(&state, control_revision));
control_published_at = std::time::Instant::now();
}
}
if state.should_quit {
// A replacement must finish before the runtime/process is torn down.
if state.updater.busy {
@@ -601,6 +666,12 @@ pub async fn run(
}
state.shutting_down = true;
terminal.draw(|frame| ui::draw(frame, &state, &keymap))?;
if let Some(service) = control_service {
service.shutdown().await;
}
if let Some(task) = runtime.radio_task.take() {
task.abort();
}
podcast_runtime::shutdown(&mut runtime).await;
runtime.federation.shutdown().await;
return Ok(());
@@ -875,14 +946,23 @@ pub(crate) fn become_control_device(
state.device_playback.role = state::DevicePlaybackRole::Control;
state.device_playback.active_device_id = Some(snapshot.device_id.clone());
state.device_playback.active_device_name = Some(snapshot.device_name.clone());
state.device_playback.last_remote_snapshot = Some(snapshot.clone());
state
.device_playback
.remote
.insert(snapshot.device_id.clone(), snapshot.clone());
apply_playback_state_to_ui(state, &snapshot.state, Some(runtime.library.as_ref()));
remote_playback::remember(state, &snapshot);
let name = snapshot.device_name.clone();
state.device_playback.last_remote_snapshot = Some(snapshot);
extrapolate_control_position(state);
state.status_message = Some(format!("controlling {}", snapshot.device_name));
if state.status_message.is_none()
|| state
.status_message
.as_ref()
.is_some_and(|s| s.starts_with("controlling ") || s == remote_playback::WAITING)
{
state.status_message = Some(format!("controlling {name}"));
}
}
pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime, start_audio: bool) {
@@ -906,6 +986,15 @@ pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime,
}
pub(crate) fn transfer_active_to_this_device(state: &mut AppState, runtime: &mut Runtime) {
transfer_active_to_this_device_inner(state, runtime, false);
}
fn transfer_active_to_this_device_inner(
state: &mut AppState,
runtime: &mut Runtime,
preserve_pause: bool,
) {
let paused = preserve_pause && state.player.paused;
if let Err(error) = runtime
.devices
.claim_playback(&state.device_playback.self_device_id)
@@ -927,11 +1016,11 @@ pub(crate) fn transfer_active_to_this_device(state: &mut AppState, runtime: &mut
}
if state.player.current.is_some() {
state.player.playing = true;
state.player.paused = false;
state.player.paused = paused;
}
become_active_device(state, runtime, false);
if should_start && state.player.current.is_some() {
start_current_audio_from(state, runtime, remote_start(state), false);
start_current_audio_from(state, runtime, remote_start(state), paused);
push_media_metadata(state, runtime);
push_media_update(state, runtime, true);
}
@@ -981,12 +1070,13 @@ pub(crate) fn transfer_active_to_remote_device(
target_device_id.clone(),
command.clone(),
"device handoff",
None,
);
if let Some(previous) = previous_active_id
&& previous != target_device_id
&& previous != state.device_playback.self_device_id
{
record_playback_command_async(runtime, previous, command.clone(), "device handoff");
record_playback_command_async(runtime, previous, command.clone(), "device handoff", None);
}
let snapshot = crate::devices::PlaybackSnapshot {
coordination: None,
@@ -1017,10 +1107,15 @@ fn record_active_handoff(
active_device_name: state.device_playback.self_device_name.clone(),
state: playback_state_from_ui(state),
};
record_playback_command_async(runtime, target, command, "device handoff");
record_playback_command_async(runtime, target, command, "device handoff", None);
}
fn record_control_playback_state(state: &mut AppState, runtime: &Runtime, seek: bool) {
fn record_control_playback_state(
state: &mut AppState,
runtime: &Runtime,
seek: bool,
change: remote_playback::Change,
) {
if !state.device_playback.is_control() {
return;
}
@@ -1028,17 +1123,30 @@ fn record_control_playback_state(state: &mut AppState, runtime: &Runtime, seek:
let Some(target) = state.device_playback.active_device_id.clone() else {
return;
};
let command = crate::devices::PlaybackCommand::SetState {
state: playback_state_from_ui(state),
seek,
};
let desired = playback_state_from_ui(state);
if state.device_playback.role == state::DevicePlaybackRole::Jam {
let command = crate::devices::PlaybackCommand::SetState {
state: desired,
seek,
};
if let Err(err) = runtime.jam.submit_command(command) {
state.status_message = Some(format!("Jam command failed: {err:#}"));
}
return;
}
record_playback_command_async(runtime, target, command, "device command");
match remote_playback::begin(state, change, desired.clone(), std::time::Instant::now()) {
Ok(id) => record_playback_command_async(
runtime,
target,
crate::devices::PlaybackCommand::SetState {
state: desired,
seek,
},
"device command",
Some(id),
),
Err(message) => state.status_message = Some(message.into()),
}
}
fn record_playback_command_async(
@@ -1046,6 +1154,7 @@ fn record_playback_command_async(
target: String,
command: crate::devices::PlaybackCommand,
label: &'static str,
request_id: Option<u64>,
) {
let devices = Arc::clone(&runtime.devices);
let sync_devices = Arc::clone(&runtime.devices);
@@ -1060,8 +1169,17 @@ fn record_playback_command_async(
devices.record_playback_command(&target_for_write, command)
})
.await;
let result = result
.map_err(|err| format!("{label} failed: {err}"))
.and_then(|result| result.map_err(|err| format!("{label} failed: {err:#}")));
if let Some(id) = request_id {
let _ = tx.send(AppEvent::RemoteCommandRecorded {
id,
result: result.clone(),
});
}
match result {
Ok(Ok(())) => {
Ok(()) => {
request_urgent_device_sync_parts(
federation,
sync_devices,
@@ -1070,13 +1188,11 @@ fn record_playback_command_async(
requested,
);
}
Ok(Err(err)) => {
tracing::warn!(%err, target, "recording playback command failed");
let _ = tx.send(AppEvent::StatusMessage(format!("{label} failed: {err:#}")));
}
Err(err) => {
tracing::warn!(%err, target, "recording playback command task failed");
let _ = tx.send(AppEvent::StatusMessage(format!("{label} failed: {err}")));
tracing::warn!(%err, target, "recording playback command failed");
if request_id.is_none() {
let _ = tx.send(AppEvent::StatusMessage(err));
}
}
}
});
@@ -1194,14 +1310,7 @@ fn maintenance(state: &mut AppState, runtime: &mut Runtime) {
// Liked ids load once per session — markers are shown everywhere.
if !state.likes_loaded {
state.likes_loaded = true;
let library = Arc::clone(&runtime.library);
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
let result = library.liked_content_ids().map_err(err_string);
let _ = tx.send(AppEvent::LikesLoaded(result));
let result = library.fed_like_ids().map_err(err_string);
let _ = tx.send(AppEvent::FedLikesLoaded(result));
});
likes::in_background(runtime, |library, _, tx| likes::reload(library, tx));
}
if !state.local_content_ids_loaded {
state.local_content_ids_loaded = true;
@@ -1728,7 +1837,9 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
});
}
// Executed by podcast_runtime::perform above.
Effect::PodcastsReload
Effect::SavePodcastSettings
| Effect::PodcastDownload(_)
| Effect::PodcastsReload
| Effect::PodcastLoadSeasons(_)
| Effect::PodcastLoadEpisodes { .. }
| Effect::PodcastSubscribe(_)
@@ -1760,10 +1871,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
if track_ids.is_empty() && fed_tracks.is_empty() {
return;
}
let library = Arc::clone(&runtime.library);
let devices = Arc::clone(&runtime.devices);
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
likes::in_background(runtime, move |library, devices, tx| {
for track_id in track_ids {
let content_id = match library.track_content_id_by_id(track_id) {
Ok(Some(content_id)) => content_id,
@@ -1816,12 +1924,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
}
}
}
let _ = tx.send(AppEvent::LikesLoaded(
library.liked_content_ids().map_err(err_string),
));
let _ = tx.send(AppEvent::FedLikesLoaded(
library.fed_like_ids().map_err(err_string),
));
likes::reload(library, tx);
});
}
Effect::RemoveFromPlaylist {
@@ -2124,44 +2227,61 @@ fn is_controlled_playback_effect(effect: &Effect) -> bool {
}
fn perform_control_playback_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
use remote_playback::Change;
if state.device_playback.role == state::DevicePlaybackRole::Control
&& let Err(reason) = remote_playback::available(state)
{
remote_playback::restore(state);
state.status_message = Some(reason.into());
return;
}
let mut seek = false;
let local_only_volume = state.device_playback.role == state::DevicePlaybackRole::Jam
&& matches!(effect, Effect::SetVolume(_));
match effect {
let change = match effect {
Effect::PlayCurrent | Effect::PlayCurrentFromStart => {
state.player.current = state.player.queue.get(state.player.queue_pos).cloned();
state.player.playing = state.player.current.is_some();
state.player.paused = false;
state.player.position_secs = 0.0;
seek = true;
Change::Start
}
Effect::TogglePause => {}
Effect::TogglePause => Change::Transport,
Effect::StopPlayback => {
state.player.playing = false;
state.player.current = None;
state.player.paused = false;
state.player.position_secs = 0.0;
Change::Transport
}
Effect::SeekBy(delta) => {
state.player.position_secs = (state.player.position_secs + delta as f64).max(0.0);
if let Some(track) = &state.player.current
&& track.duration_seconds > 0.0
{
state.player.position_secs = state.player.position_secs.min(track.duration_seconds);
}
seek = true;
Change::Seek
}
Effect::SetVolume(volume) => {
state.player.volume = volume.min(100);
save_app_settings(state);
if local_only_volume {
save_app_settings(state);
}
Change::Volume
}
Effect::SetOptions
| Effect::RemoveQueueIndices { .. }
Effect::SetOptions => Change::Options,
Effect::RemoveQueueIndices { .. }
| Effect::PlaybackQueueChanged
| Effect::QueueOrderChanged { .. }
| Effect::LoadListenHistory
| Effect::ChangeMusicDirectory { .. } => {}
_ => {}
}
| Effect::QueueOrderChanged { .. } => Change::Queue,
_ => return,
};
if local_only_volume {
return;
}
record_control_playback_state(state, runtime, seek);
record_control_playback_state(state, runtime, seek, change);
}
fn clamp_settings_cursor(state: &mut AppState) {
@@ -3133,14 +3253,19 @@ fn refresh_artists(state: &mut AppState, runtime: &Runtime) {
});
}
fn save_app_settings(state: &AppState) {
let settings = crate::config::settings::AppSettings {
fn app_settings(state: &AppState) -> crate::config::settings::AppSettings {
crate::config::settings::AppSettings {
podcast_retention_days: state.podcast_retention_days,
playback: state.device_playback.config.clone(),
volume: state.player.volume,
library: state.global.filters,
music_dir: state.music_dir.clone(),
similarity: state.similarity.settings.clone(),
};
}
}
fn save_app_settings(state: &AppState) {
let settings = app_settings(state);
if let Err(err) = crate::config::settings::save(&settings) {
tracing::warn!(%err, "saving app settings failed");
}
@@ -3302,8 +3427,7 @@ fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) {
let _ = runtime.devices.playback_tick(false, false);
return;
}
let playing =
state.device_playback.is_audio_owner() && state.player.playing && !state.player.paused;
let playing = state.device_playback.is_audio_owner() && runtime.player.shared.output_playing();
let owner = match runtime.devices.playback_tick(true, playing) {
Ok(owner) => owner,
Err(error) => {
@@ -3326,11 +3450,14 @@ fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) {
if !state.device_playback.is_audio_owner() {
become_active_device(state, runtime, true);
}
} else if let Some(snapshot) = state.device_playback.remote.get(&owner).cloned() {
if state.device_playback.last_remote_snapshot.as_ref() != Some(&snapshot)
|| state.device_playback.is_audio_owner()
} else if let Some(snapshot) = state.device_playback.remote.get(&owner) {
let waiting = state.device_playback.control.busy()
&& state.device_playback.active_device_id.as_ref() == Some(&owner);
if !waiting
&& (state.device_playback.last_remote_snapshot.as_ref() != Some(snapshot)
|| state.device_playback.is_audio_owner())
{
become_control_device(state, runtime, snapshot);
become_control_device(state, runtime, snapshot.clone());
}
} else {
runtime.player.set_playback_allowed(false);
@@ -3350,6 +3477,15 @@ fn handle_device_playback_snapshot(
if snapshot.device_id == state.device_playback.self_device_id {
return;
}
// Concurrent sync workers can enqueue reports in a different order
// from the one in which DeviceSync accepted their heartbeats.
if let Some(previous) = state.device_playback.remote.get(&snapshot.device_id)
&& let (Some(old), Some(new)) = (&previous.coordination, &snapshot.coordination)
&& (&new.claim, new.heartbeat) <= (&old.claim, old.heartbeat)
{
return;
}
remote_playback::observe(state, &snapshot, std::time::Instant::now());
state
.device_playback
.remote
@@ -3523,6 +3659,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
return;
};
match event {
AppEvent::Control(request) => control::dispatch(state, runtime, request),
AppEvent::RadioReady { id, result } => radio::ready(state, runtime, id, result),
AppEvent::Lyrics(event) => lyrics::handle_event(state, event),
// Folded in by podcast_runtime::handle_event above.
AppEvent::PodcastStoreOpened(_)
| AppEvent::PodcastsSynced { .. }
@@ -3535,6 +3674,8 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
| AppEvent::PodcastProgress(_)
| AppEvent::PodcastEpisodeStarted { .. }
| AppEvent::PodcastEpisodeFailed { .. }
| AppEvent::PodcastDownloads(_)
| AppEvent::PodcastDownloaded { .. }
| AppEvent::PodcastRefreshTick
| AppEvent::PodcastsDue(_)
| AppEvent::PodcastSharePrepared { .. }
@@ -3577,6 +3718,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
state.status_message = Some(state.updater.message.clone());
}
AppEvent::StatusMessage(message) => state.status_message = Some(message),
AppEvent::RemoteCommandRecorded { id, result } => {
remote_playback::recorded(state, id, result)
}
AppEvent::ListenHistoryLoaded(result) => {
state.listen_history = Some(match result {
Ok(entries) => state::Loadable::Ready(entries),
@@ -3685,6 +3829,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
state.federation.devices = Some(runtime.devices.status());
}
AppEvent::DevicePlayback(snapshot) => {
radio::remote_started(state, &snapshot);
handle_device_playback_snapshot(state, runtime, snapshot);
}
AppEvent::PlaybackCommand { .. }
@@ -3735,6 +3880,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}
}
AppEvent::JamPlayback(snapshot) => {
radio::remote_started(state, &snapshot);
let local_volume = state.player.volume;
become_control_device(state, runtime, snapshot);
state.device_playback.role = state::DevicePlaybackRole::Jam;
@@ -3913,6 +4059,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
match result {
Ok(playable) => {
if playable.imported {
lyrics::on_import(state, runtime, &playable.track);
if let Some(content_id) = state::track_content_id(&playable.track) {
state.local_content_ids.insert(content_id.clone());
let _ = runtime
@@ -4275,6 +4422,8 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}
AppEvent::Player(player::PlayerEvent::Started) => {
runtime.player_start_pending = false;
radio::started(state);
state.lyrics.refresh_local();
}
AppEvent::Player(player::PlayerEvent::TrackFinished { has_next }) => {
// An episode that played to the end is complete; one whose
@@ -4322,6 +4471,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}
}
AppEvent::Player(player::PlayerEvent::Failed(message)) => {
radio::failed(state, &message);
podcast_runtime::player_failed(runtime);
runtime.player_start_pending = false;
tracing::error!(%message, "playback failed");
@@ -4359,7 +4509,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}
AppEvent::LikesLoaded(result) => match result {
Ok(ids) => {
state.likes = ids.into_iter().collect();
state.likes = ids.local;
state.fed_likes = ids.federated;
state.likes_ready = true;
}
Err(message) => tracing::warn!(%message, "likes load failed"),
},
@@ -4388,10 +4540,6 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
state.local_content_ids.insert(content_id);
}
}
AppEvent::FedLikesLoaded(result) => match result {
Ok(ids) => state.fed_likes = ids.into_iter().collect(),
Err(message) => tracing::warn!(%message, "federated likes load failed"),
},
AppEvent::FedLikeToggled {
item_id,
content_id,
@@ -4532,16 +4680,16 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
MediaCommand::Next => action::Action::NextTrack,
MediaCommand::Previous => action::Action::PrevTrack,
MediaCommand::Stop => {
if state.device_playback.is_control() {
perform_effect(state, runtime, Effect::StopPlayback);
return;
}
runtime.player_start_pending = false;
state.player.playing = false;
state.player.paused = false;
state.player.current = None;
if state.device_playback.is_control() {
record_control_playback_state(state, runtime, false);
} else {
runtime.player.stop();
push_media_update(state, runtime, true);
}
runtime.player.stop();
push_media_update(state, runtime, true);
return;
}
};
+76 -1
View File
@@ -41,6 +41,8 @@ const PUBLICATION_FLUSH_TIMEOUT: Duration = Duration::from_secs(4);
pub struct PodcastRuntime {
pub services: Services,
refresh_slots: Arc<tokio::sync::Semaphore>,
download_slots: Arc<tokio::sync::Semaphore>,
downloads_cancelled: Arc<std::sync::atomic::AtomicBool>,
/// Writes progress in order on its own thread; `None` if it could not
/// start (episodes then play without saving progress).
progress: Option<ProgressWriter>,
@@ -187,6 +189,18 @@ fn services(runtime: &Runtime) -> Option<Services> {
/// Executes a podcast [`Effect`]; any other effect is handed back.
pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> Option<Effect> {
if matches!(effect, Effect::SavePodcastSettings) {
let settings = super::app_settings(state);
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
let message = match crate::config::settings::save(&settings) {
Ok(()) => "podcasts: download retention saved".to_string(),
Err(_) => "podcasts: could not save download retention".to_string(),
};
let _ = tx.send(AppEvent::StatusMessage(message));
});
return None;
}
let Some(services) = services(runtime) else {
if is_podcast_effect(&effect) {
if let Effect::PodcastRefresh { targets, .. } = &effect {
@@ -219,6 +233,30 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
};
let tx = runtime.event_tx.clone();
match effect {
Effect::SavePodcastSettings => unreachable!("handled before store lookup"),
Effect::PodcastDownload(episode) => {
let slots = Arc::clone(&runtime.podcasts.as_ref().unwrap().download_slots);
let cancelled = Arc::clone(&runtime.podcasts.as_ref().unwrap().downloads_cancelled);
tokio::spawn(async move {
let Ok(permit) = slots.acquire_owned().await else {
return;
};
let _ = tokio::task::spawn_blocking(move || {
let _permit = permit;
let id = episode.episode_id.as_str().to_owned();
let result = crate::podcasts::offline::download_with_cancel(
&services.downloads_dir,
&episode,
CancelToken::new(move || {
cancelled.load(std::sync::atomic::Ordering::Relaxed)
}),
)
.map_err(|_| "could not download episode audio".to_string());
let _ = tx.send(AppEvent::PodcastDownloaded { id, result });
})
.await;
});
}
Effect::PodcastsReload => {
tokio::task::spawn_blocking(move || {
let result = load_rows(&services.store).map_err(err_string);
@@ -411,7 +449,9 @@ fn set_shared(
fn is_podcast_effect(effect: &Effect) -> bool {
matches!(
effect,
Effect::PodcastsReload
Effect::SavePodcastSettings
| Effect::PodcastDownload(_)
| Effect::PodcastsReload
| Effect::PodcastLoadSeasons(_)
| Effect::PodcastLoadEpisodes { .. }
| Effect::PodcastSubscribe(_)
@@ -477,6 +517,8 @@ pub fn handle_event(
runtime.podcasts = Some(PodcastRuntime {
services,
refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)),
download_slots: Arc::new(tokio::sync::Semaphore::new(2)),
downloads_cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
progress,
publication,
});
@@ -599,7 +641,34 @@ pub fn handle_event(
episode_failed(state, runtime, generation, message);
Vec::new()
}
AppEvent::PodcastDownloaded { id, result } => {
state.podcast_downloading.remove(&id);
state.status_message = Some(match result {
Ok(()) => "podcasts: episode downloaded".into(),
Err(e) => e,
});
let _ = runtime.event_tx.send(AppEvent::PodcastRefreshTick);
Vec::new()
}
AppEvent::PodcastDownloads(result) => {
if let Ok(downloads) = result {
state.podcast_downloads = downloads;
}
Vec::new()
}
AppEvent::PodcastRefreshTick => {
let offline_services = services(runtime)?;
let days = state.podcast_retention_days.max(1);
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
let result = crate::podcasts::offline::cleanup(
&offline_services.downloads_dir,
days,
std::time::SystemTime::now(),
)
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastDownloads(result));
});
if let Some(services) = services(runtime) {
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
@@ -1148,6 +1217,12 @@ fn progress_event(
/// also one still being written) reach the overlay. Logs a warning when a
/// card of a private podcast may still be live.
pub(crate) async fn shutdown(runtime: &mut Runtime) {
if let Some(podcasts) = &runtime.podcasts {
podcasts
.downloads_cancelled
.store(true, std::sync::atomic::Ordering::Relaxed);
podcasts.download_slots.close();
}
end_playback(runtime);
let Some(podcasts) = runtime.podcasts.as_mut() else {
return;
+31
View File
@@ -97,6 +97,8 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
return;
};
match popup {
Popup::Lyrics(reader) => super::lyrics::reader_key(state, reader, key),
Popup::LyricsEditor(editor) => super::lyrics::editor_key(state, runtime, editor, key),
Popup::AddToPlaylist { target, cursor } => {
handle_picker(state, runtime, target, cursor, key);
}
@@ -614,6 +616,20 @@ fn handle_fed_input(
!state.federation.settings.network_id.is_empty();
super::fed_apply_settings(state, runtime);
}
FedInputField::PodcastRetention => match value.parse::<u32>() {
Ok(days) if (1..=36500).contains(&days) => {
state.podcast_retention_days = days;
super::perform_effect(
state,
runtime,
crate::app::update::Effect::SavePodcastSettings,
);
}
_ => {
state.status_message =
Some("enter a retention period from 1 to 36500 days".into())
}
},
FedInputField::MusicDirectory => {
if value.is_empty() {
state.status_message = Some("music directory is empty".into());
@@ -836,6 +852,10 @@ fn handle_device_leave(state: &mut AppState, runtime: &mut Runtime, key: KeyEven
/// Pasted text goes into the focused text field when one is open.
pub fn handle_paste(state: &mut AppState, runtime: &mut Runtime, pasted: &str) {
if let Some(Popup::LyricsEditor(editor)) = &mut state.popup {
super::lyrics::paste(editor, pasted);
return;
}
let cleaned: String = pasted.chars().filter(|c| !c.is_control()).collect();
let mut search = None;
match &mut state.popup {
@@ -880,6 +900,17 @@ fn handle_edit(
) {
match key.code {
KeyCode::Esc => return,
KeyCode::F(3) if let EditTarget::Track(id) = target => {
let parent = Popup::Edit {
target,
title,
fields,
focus,
error,
};
super::lyrics::open_editor(state, runtime, parent, id);
return;
}
KeyCode::Enter => {
match save_edit(runtime, target, &fields) {
Ok(message) => {
+286
View File
@@ -0,0 +1,286 @@
//! One-shot similarity radio: collect the whole candidate set before replacing
//! the queue. It is independent of the user's search page and request sequence.
use std::sync::Arc;
use std::time::{Duration, Instant};
use furumi_control_protocol::{Radio as Status, RadioState};
use super::event::AppEvent;
use super::state::{AppState, SimilaritySearchHit};
use super::{Runtime, update};
use crate::library::models::TrackItem;
#[derive(Debug, Default)]
pub(super) struct Radio {
pub status: Status,
seed: String,
owner: Option<String>,
queue: Vec<String>,
expected: Option<String>,
expected_queue: Vec<String>,
remote_baseline: Option<i64>,
deadline: Option<Instant>,
}
fn identity(track: &TrackItem) -> String {
track
.content_id
.clone()
.unwrap_or_else(|| track.key().to_string())
}
fn queue_identity(state: &AppState) -> Vec<String> {
state.player.queue.iter().map(identity).collect()
}
fn busy(state: &AppState) -> bool {
matches!(
state.radio.status.state,
RadioState::Searching | RadioState::Starting
)
}
pub(super) fn begin(state: &mut AppState) -> Result<TrackItem, String> {
if busy(state) {
return Err("Radio is already being prepared".into());
}
if !state.similarity.settings.enabled {
return Err("Enable similarity search in Furumi Settings first".into());
}
let seed = state
.player
.current
.clone()
.ok_or("Play a music track before starting radio")?;
if seed.is_podcast() {
return Err("Similarity radio is available for music tracks only".into());
}
state.radio = Radio {
status: Status {
id: state.radio.status.id.wrapping_add(1),
state: RadioState::Searching,
error: None,
},
seed: identity(&seed),
owner: state.device_playback.active_device_id.clone(),
queue: queue_identity(state),
expected: None,
expected_queue: Vec::new(),
remote_baseline: None,
deadline: Some(Instant::now() + Duration::from_secs(95)),
};
Ok(seed)
}
pub(super) fn start(state: &mut AppState, runtime: &mut Runtime) -> Result<(), String> {
let seed = begin(state)?;
if let Some(previous) = runtime.radio_task.take() {
previous.abort();
}
let id = state.radio.status.id;
let (similarity, federation, library, tx) = (
Arc::clone(&runtime.similarity),
Arc::clone(&runtime.federation),
Arc::clone(&runtime.library),
runtime.event_tx.clone(),
);
let network = state.federation.settings.enabled && runtime.similarity.network_allowed();
runtime.radio_task = Some(tokio::spawn(async move {
let work = async move {
let (local, query) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
// A controller's numeric row IDs are not the output's IDs.
let local_seed = if seed.id >= 0 && seed.fed.is_none() { seed.id } else {
let content_id = seed.content_id.as_deref().ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?;
library.track_by_content_id(content_id)?.ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?.id
};
similarity.search_track(local_seed, 49)
}).await.map_err(|error| format!("Radio search worker failed: {error}"))?
.map_err(|error| format!("Radio search failed: {error:#}"))?;
let mut hits: Vec<_> = local
.into_iter()
.map(|hit| SimilaritySearchHit::Local {
track: hit.track,
score: hit.score,
embedding_signature: hit.embedding_signature,
})
.collect();
if network {
// Await the full existing bounded fan-out, not its first answer.
let remote = tokio::time::timeout(
Duration::from_secs(75),
federation.search_similar(query, 50),
)
.await;
match remote {
Ok(Ok(remote)) => hits.extend(remote.tracks.into_iter().map(|hit| {
SimilaritySearchHit::Federated {
track: hit.track,
score: hit.score,
embedding_signature: hit.embedding_signature,
}
})),
_ if !hits.is_empty() => {
tracing::debug!("radio peer search unavailable; using local matches")
}
_ => {
return Err(
"No radio matches available; peer search failed or timed out".into(),
);
}
}
}
Ok(hits)
};
let result = tokio::time::timeout(Duration::from_secs(90), work)
.await
.unwrap_or_else(|_| Err("Radio search timed out; existing queue was kept".into()));
let _ = tx.send(AppEvent::RadioReady { id, result });
}));
Ok(())
}
/// Pure commit boundary: errors, stale generations and changed playback never
/// replace the user's queue. Ranking is shared with the TUI's similarity view.
pub(super) fn prepare(
state: &mut AppState,
id: u64,
result: Result<Vec<SimilaritySearchHit>, String>,
) -> bool {
if id != state.radio.status.id || state.radio.status.state != RadioState::Searching {
return false;
}
if !seed_current(state) {
fail(state, "Playback changed while radio was being prepared");
return false;
}
if let Err(reason) = super::remote_playback::available(state) {
fail(state, reason);
return false;
}
let mut hits = match result {
Ok(hits) => hits,
Err(error) => {
fail(state, &error);
return false;
}
};
super::rank_similarity_search_tracks(
&mut hits,
state.similarity.settings.max_tracks_per_artist,
);
let tracks: Vec<_> = hits
.into_iter()
.map(|hit| hit.track_item())
.filter(|track| !track.is_podcast() && identity(track) != state.radio.seed)
.collect();
if tracks.is_empty() {
fail(state, "No similar tracks found; existing queue was kept");
return false;
}
state.radio.expected = Some(identity(&tracks[0]));
state.radio.remote_baseline = state
.radio
.owner
.as_ref()
.and_then(|owner| state.device_playback.remote.get(owner))
.map(|snapshot| snapshot.updated_at_ms);
state.radio.status.state = RadioState::Starting;
state.radio.deadline = Some(Instant::now() + Duration::from_secs(120));
state.player.queue = tracks;
state.player.queue_pos = 0;
state.player.prefetched_pos = None;
state.queue_tab.cursor = 0;
update::on_new_queue(state);
state.radio.expected_queue = queue_identity(state);
true
}
pub(super) fn ready(
state: &mut AppState,
runtime: &mut Runtime,
id: u64,
result: Result<Vec<SimilaritySearchHit>, String>,
) {
if prepare(state, id, result) {
super::perform_effect(state, runtime, update::Effect::PlayCurrent);
}
}
fn seed_current(state: &AppState) -> bool {
state.player.current.as_ref().map(identity).as_ref() == Some(&state.radio.seed)
&& state.device_playback.active_device_id == state.radio.owner
&& queue_identity(state) == state.radio.queue
}
fn fail(state: &mut AppState, error: &str) {
state.radio.status.state = RadioState::Failed;
state.radio.status.error = Some(error.into());
state.radio.deadline = None;
state.status_message = Some(error.into());
}
pub(super) fn failed(state: &mut AppState, error: &str) {
if state.radio.status.state == RadioState::Starting {
fail(state, error);
}
}
pub(super) fn started(state: &mut AppState) {
if state.radio.status.state == RadioState::Starting
&& state.player.current.as_ref().map(identity) == state.radio.expected
&& state.player.playing
&& !state.player.paused
{
state.radio.status.state = RadioState::Playing;
state.radio.deadline = None;
}
}
pub(super) fn remote_started(state: &mut AppState, snapshot: &crate::devices::PlaybackSnapshot) {
use crate::devices::PlaybackTrackExt as _;
if state.radio.status.state == RadioState::Starting
&& snapshot.active
&& snapshot.state.playing
&& !snapshot.state.paused
// The wire's playing flag is intent; advancing position confirms the
// output passed source preparation, rather than merely accepting it.
&& snapshot.state.position_secs > 0.0
&& state.radio.remote_baseline.is_none_or(|baseline| snapshot.updated_at_ms > baseline)
&& Some(&snapshot.device_id) == state.radio.owner.as_ref()
&& snapshot.state.queue.iter().map(|track| identity(&track.to_track_item())).collect::<Vec<_>>() == state.radio.expected_queue
&& snapshot
.state
.queue
.get(snapshot.state.queue_pos)
.map(|track| identity(&track.to_track_item()))
== state.radio.expected
{
state.radio.status.state = RadioState::Playing;
state.radio.deadline = None;
}
}
pub(super) fn tick(state: &mut AppState, runtime: &mut Runtime) {
if !busy(state) {
return;
}
if state.radio.status.state == RadioState::Searching && !seed_current(state) {
fail(state, "Playback changed while radio was being prepared");
} else if state.device_playback.active_device_id != state.radio.owner {
fail(
state,
"Playback device changed while radio was being prepared",
);
} else if state
.radio
.deadline
.is_some_and(|deadline| Instant::now() > deadline)
{
fail(state, "Radio preparation timed out");
}
if !busy(state)
&& let Some(task) = runtime.radio_task.take()
{
task.abort();
}
}
+324
View File
@@ -0,0 +1,324 @@
//! Client-side completion of personal-device controls. Only a fresh output
//! report can finish a request. Nothing here is serialized to another device.
use std::time::{Duration, Instant};
use furumi_control_protocol::{RemoteCommand, RemoteCommandState};
use music_dht::playback::Claim;
use super::state::{AppState, DevicePlaybackRole, PlayerBar};
use crate::config::settings::LibrarySourceMode;
use crate::devices::{PlaybackSnapshot, PlaybackStateWire, PlaybackTrack};
pub(super) const WAITING: &str = "Waiting for the active device";
const TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, Clone, Copy)]
pub(super) enum Change {
Transport,
Start,
Seek,
Volume,
Options,
Queue,
}
#[derive(Debug)]
struct Pending {
owner: String,
claim: Option<Claim>,
heartbeat: u64,
written: bool,
started: Instant,
change: Change,
desired: PlaybackStateWire,
same_item: bool,
}
#[derive(Debug, Default)]
pub(crate) struct RemotePlayback {
pub(crate) status: RemoteCommand,
pending: Option<Pending>,
// The resolved UI projection preserves local cover paths and podcast
// identities when discarding a speculative edit. No DB access on input.
confirmed: Option<PlayerBar>,
source_mode: Option<LibrarySourceMode>,
}
impl RemotePlayback {
pub(crate) fn busy(&self) -> bool {
self.pending.is_some()
}
fn finish(&mut self, error: Option<String>) {
self.pending = None;
self.status.state = if error.is_some() {
RemoteCommandState::Failed
} else {
RemoteCommandState::Confirmed
};
self.status.error = error;
}
}
// A heartbeat normally changes only the position. Keep the resolved queue
// across those reports instead of copying every track on every heartbeat.
pub(super) fn remember(state: &mut AppState, report: &PlaybackSnapshot) {
let device = &mut state.device_playback;
let remote = &mut device.control;
let unchanged = device.last_remote_snapshot.as_ref().is_some_and(|old| {
let (a, b) = (&old.state, &report.state);
old.device_id == report.device_id
&& a.queue == b.queue
&& a.queue_pos == b.queue_pos
&& a.playing == b.playing
&& a.paused == b.paused
&& a.volume == b.volume
&& a.shuffle == b.shuffle
&& a.repeat == b.repeat
});
if unchanged
&& remote.source_mode == Some(state.global.filters.source_mode)
&& let Some(confirmed) = &mut remote.confirmed
{
confirmed.position_secs = state.player.position_secs;
} else {
remote.confirmed = Some(state.player.clone());
remote.source_mode = Some(state.global.filters.source_mode);
}
}
pub(super) fn restore(state: &mut AppState) {
if let Some(last) = &state.device_playback.last_remote_snapshot
&& state.device_playback.active_device_id.as_ref() == Some(&last.device_id)
&& let Some(confirmed) = &state.device_playback.control.confirmed
{
state.player.clone_from(confirmed);
state.device_playback.local_idle_since_ms = last.state.idle_since_ms;
state.queue_tab.cursor = state
.queue_tab
.cursor
.min(state.player.queue.len().saturating_sub(1));
super::extrapolate_control_position(state);
}
}
pub(super) fn available(state: &AppState) -> Result<(), &'static str> {
let device = &state.device_playback;
if device.role != DevicePlaybackRole::Control {
return Ok(());
}
if device.control.busy() {
return Err(WAITING);
}
device
.active_device_id
.as_ref()
.map(|_| ())
.ok_or("No active playback device")
}
pub(super) fn begin(
state: &mut AppState,
change: Change,
desired: PlaybackStateWire,
now: Instant,
) -> Result<u64, &'static str> {
// update() may already have edited the queue, modes or pause flag to
// build the outgoing SetState. Restore the screen before it can repaint.
restore(state);
let device = &mut state.device_playback;
if device.control.busy() {
return Err(WAITING);
}
let owner = device
.active_device_id
.as_ref()
.ok_or("No active playback device")?;
let last = device
.last_remote_snapshot
.as_ref()
.filter(|s| s.device_id == *owner);
let same_item = last.is_some_and(|s| same_current(&s.state, &desired));
let announcement = last.and_then(|s| s.coordination.as_ref());
let generation = device.control.status.id.wrapping_add(1);
device.control.pending = Some(Pending {
owner: owner.clone(),
claim: announcement.and_then(|a| a.claim.clone()),
heartbeat: announcement.map_or(0, |a| a.heartbeat),
written: false,
started: now,
change,
desired,
same_item,
});
device.control.status = RemoteCommand {
id: generation,
state: RemoteCommandState::Pending,
error: None,
};
Ok(generation)
}
pub(super) fn recorded(state: &mut AppState, id: u64, result: Result<(), String>) {
let control = &mut state.device_playback.control;
if id != control.status.id {
return;
}
let Some(pending) = &mut control.pending else {
return;
};
match result {
Ok(()) => pending.written = true,
Err(error) => {
state.status_message = Some(error.clone());
control.finish(Some(error));
}
}
}
// IDs and file paths belong to the originating library. Older music entries
// without a content ID can still be compared by portable display metadata.
fn same_item(a: &PlaybackTrack, b: &PlaybackTrack) -> bool {
use music_dht::device_sync::PlaybackSource;
match (&a.source, &b.source) {
(Some(PlaybackSource::PodcastEpisode(a)), Some(PlaybackSource::PodcastEpisode(b))) => {
return a.episode_id == b.episode_id;
}
(Some(PlaybackSource::Private), Some(PlaybackSource::Private)) => return true,
(None | Some(PlaybackSource::Music), None | Some(PlaybackSource::Music)) => {}
_ => return false,
}
let content = |t: &PlaybackTrack| {
t.content_id
.as_deref()
.or_else(|| t.fed.as_ref().map(|f| f.content_id.as_str()))
.and_then(music_dht::normalize_content_id)
};
if let (Some(a), Some(b)) = (content(a), content(b)) {
return a == b;
}
if let (Some(a), Some(b)) = (&a.fed, &b.fed) {
return a.owner == b.owner && a.item_id == b.item_id;
}
a.title == b.title
&& a.release_title == b.release_title
&& a.artist_names == b.artist_names
&& a.track_number == b.track_number
&& a.disc_number == b.disc_number
}
fn same_current(a: &PlaybackStateWire, b: &PlaybackStateWire) -> bool {
a.queue_pos == b.queue_pos
&& match (a.queue.get(a.queue_pos), b.queue.get(b.queue_pos)) {
(Some(a), Some(b)) => same_item(a, b),
(None, None) => true,
_ => false,
}
}
impl Pending {
fn matches(&self, actual: &PlaybackStateWire, output_playing: bool, age: Duration) -> bool {
let want = &self.desired;
let transport = actual.playing == want.playing
&& actual.paused == want.paused
&& output_playing == (want.playing && !want.paused);
let position_matches = || {
let elapsed = if output_playing {
age.as_secs_f64()
} else {
0.0
};
actual.position_secs >= want.position_secs - 0.75
&& actual.position_secs <= want.position_secs + elapsed + 0.75
};
let queue_matches = || {
want.queue.len() == actual.queue.len()
&& want
.queue
.iter()
.zip(&actual.queue)
.all(|(a, b)| same_item(a, b))
};
match self.change {
Change::Transport => transport && (!want.playing || same_current(want, actual)),
Change::Start => {
transport
&& same_current(want, actual)
&& queue_matches()
&& (!self.same_item || position_matches())
}
Change::Seek => transport && same_current(want, actual) && position_matches(),
Change::Volume => actual.volume == want.volume,
Change::Options => actual.repeat == want.repeat && actual.shuffle == want.shuffle,
Change::Queue => same_current(want, actual) && queue_matches(),
}
}
}
pub(super) fn observe(state: &mut AppState, report: &PlaybackSnapshot, now: Instant) {
tick(state, now);
let device = &mut state.device_playback;
let Some(pending) = &mut device.control.pending else {
return;
};
if device.role != DevicePlaybackRole::Control || pending.owner != report.device_id {
return;
}
let Some(announcement) = &report.coordination else {
return;
};
let Some(claim) = &announcement.claim else {
return;
};
if let Some(baseline) = &pending.claim {
if claim < baseline {
return;
}
if claim > baseline {
device
.control
.finish(Some("Playback ownership changed".into()));
state.status_message = device.control.status.error.clone();
return;
}
}
if !report.active
|| !announcement.available
|| claim.owner != pending.owner
|| announcement.heartbeat <= pending.heartbeat
{
return;
}
pending.heartbeat = announcement.heartbeat;
pending.claim.get_or_insert_with(|| claim.clone());
if pending.written
&& pending.matches(
&report.state,
announcement.playing,
now.saturating_duration_since(pending.started),
)
{
device.control.finish(None);
}
}
pub(super) fn tick(state: &mut AppState, now: Instant) {
let device = &mut state.device_playback;
if device.role != DevicePlaybackRole::Control {
device.control.confirmed = None;
}
let Some(pending) = &device.control.pending else {
return;
};
let reason = if device.role != DevicePlaybackRole::Control
|| device.active_device_id.as_ref() != Some(&pending.owner)
{
"Playback ownership changed"
} else if now.saturating_duration_since(pending.started) >= TIMEOUT {
"Active device did not confirm the command"
} else {
return;
};
state.status_message = Some(reason.into());
device.control.finish(Some(reason.into()));
}
+54 -17
View File
@@ -740,6 +740,8 @@ impl PlaylistAddTarget {
/// Modal dialog over the main screen.
#[derive(Debug)]
pub enum Popup {
Lyrics(super::lyrics::Reader),
LyricsEditor(Box<super::lyrics::Editor>),
/// Pick one of the playlists (last row = "create new"); the target is
/// added on Enter (federated tracks are downloaded first).
AddToPlaylist {
@@ -762,7 +764,10 @@ pub enum Popup {
error: Option<String>,
},
/// Delete confirmation; Enter/y deletes, Esc/n cancels.
ConfirmDelete { target: DeleteTarget, label: String },
ConfirmDelete {
target: DeleteTarget,
label: String,
},
/// Unsubscribe confirmation; progress and history are kept.
ConfirmPodcastUnsubscribe {
podcast_id: music_dht::podcast::PodcastId,
@@ -795,11 +800,15 @@ pub enum Popup {
max_scroll: std::cell::Cell<u16>,
},
/// Enabling network similarity reveals an embedding query to peers.
SimilarityPrivacyConsent { enable_federation: bool },
SimilarityPrivacyConsent {
enable_federation: bool,
},
/// Derived data is safe to recreate but potentially expensive.
ConfirmClearEmbeddings,
/// Library-home filters. Cursor is kept for the next filters added here.
LibraryFilters { cursor: usize },
LibraryFilters {
cursor: usize,
},
/// Track metadata viewer; left/right switch between selected tracks.
TrackInfo {
tracks: Vec<TrackItem>,
@@ -822,7 +831,10 @@ pub enum Popup {
input: LineEdit,
},
/// Wrapped read-only text (this peer's connection ticket).
FedText { title: String, text: String },
FedText {
title: String,
text: String,
},
/// Wrapped text that can be copied to the system clipboard.
FedCopyText {
title: String,
@@ -834,10 +846,14 @@ pub enum Popup {
/// The app loop temporarily leaves the alternate screen while this is
/// active so terminal selection does not acquire TUI borders or hard
/// line breaks.
PlainText { text: String },
PlainText {
text: String,
},
/// The destination is already write-tested; Enter/y migrates managed
/// files, while n changes only the destination for future downloads.
ConfirmMusicDirectory { path: std::path::PathBuf },
ConfirmMusicDirectory {
path: std::path::PathBuf,
},
/// Incoming trusted-device pairing request.
DevicePairing {
request_id: String,
@@ -848,13 +864,20 @@ pub enum Popup {
requester_group_active_devices: usize,
},
/// Confirmation before revoking a trusted device.
ConfirmDeviceRevoke { device_id: String, name: String },
ConfirmDeviceRevoke {
device_id: String,
name: String,
},
/// Confirmation before this device leaves the trusted-device group.
ConfirmDeviceLeave,
/// Connected playback devices and their current role/status.
ConnectedDevices { cursor: usize },
ConnectedDevices {
cursor: usize,
},
/// Qualified listening history from every trusted device.
ListenHistory { cursor: usize },
ListenHistory {
cursor: usize,
},
/// Full federation, transport and device status details.
FederationStatusDetails {
focus: StatusDetailFocus,
@@ -923,6 +946,7 @@ impl StatusDetailFocus {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FedInputField {
MusicDirectory,
PodcastRetention,
SimilarityWorkers,
SimilarityMinimumScore,
SimilarityMaxTracksPerArtist,
@@ -940,6 +964,7 @@ pub enum FedInputField {
impl FedInputField {
pub fn title(self) -> &'static str {
match self {
FedInputField::PodcastRetention => "Keep podcast downloads (days)",
FedInputField::MusicDirectory => "Music save directory",
FedInputField::SimilarityWorkers => "Similarity background workers",
FedInputField::SimilarityMinimumScore => "Minimum similarity score",
@@ -956,6 +981,9 @@ impl FedInputField {
pub fn help(self) -> &'static str {
match self {
FedInputField::PodcastRetention => {
"Enter 1–36500 days. Downloads expire from the time they finish. Default: 30 days. Only this device is affected."
}
FedInputField::MusicDirectory => {
"Federated tracks saved to your library use this directory. The directory is checked for write access before anything changes."
}
@@ -1047,6 +1075,7 @@ pub enum SettingsRow {
CheckUpdate,
InstallUpdate,
MusicDirectory,
PodcastRetention,
Similarity(SimilarityRow),
Federation(FedRow),
StatusDetails,
@@ -1188,6 +1217,7 @@ pub fn device_status_order(state: &AppState) -> Vec<usize> {
pub fn additional_settings_rows(state: &AppState) -> Vec<SettingsRow> {
let mut rows = vec![
SettingsRow::MusicDirectory,
SettingsRow::PodcastRetention,
SettingsRow::CheckUpdate,
SettingsRow::InstallUpdate,
];
@@ -1633,7 +1663,7 @@ impl RepeatMode {
/// Playback state mirrored for the UI: the queue, the loaded track and the
/// position polled from the audio thread on every tick.
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct PlayerBar {
pub queue: Vec<TrackItem>,
pub queue_pos: usize,
@@ -1702,6 +1732,7 @@ impl DevicePlaybackRole {
#[derive(Debug, Default)]
pub struct DevicePlaybackState {
pub(crate) control: super::remote_playback::RemotePlayback,
pub config: music_dht::playback::Config,
pub role: DevicePlaybackRole,
pub self_device_id: String,
@@ -1958,7 +1989,11 @@ pub struct AppState {
/// Root for music permanently downloaded from federation peers.
pub music_dir: std::path::PathBuf,
pub music_dir_changing: bool,
pub podcast_retention_days: u32,
pub podcast_downloads: std::collections::HashSet<String>,
pub podcast_downloading: std::collections::HashSet<String>,
pub player: PlayerBar,
pub(crate) lyrics: super::lyrics::Playback,
pub device_playback: DevicePlaybackState,
pub jam: crate::jam::JamStatus,
pub visualizer: crate::visualizer::VisualizerState,
@@ -1981,6 +2016,8 @@ pub struct AppState {
/// Content ids that currently have a local playable file.
pub local_content_ids: HashSet<String>,
pub likes_loaded: bool,
/// The local and federated markers have both loaded successfully at least once.
pub(super) likes_ready: bool,
pub local_content_ids_loaded: bool,
pub local_library_stats: Option<Loadable<crate::library::LocalLibraryStats>>,
pub listen_history: Option<Loadable<Vec<crate::library::ListenHistoryEntry>>>,
@@ -1988,6 +2025,7 @@ pub struct AppState {
pub queue_tab: QueueTab,
pub federation: FederationTab,
pub similarity: SimilarityTab,
pub(super) radio: super::radio::Radio,
pub podcasts: PodcastsTab,
/// The one federated artist card being viewed (name + loading state);
/// opening another card replaces it.
@@ -2084,13 +2122,12 @@ impl AppState {
}
pub fn track_liked(&self, track: &TrackItem) -> bool {
if let Some(content_id) = track_content_id(track) {
return self.likes.contains(&content_id) || self.fed_likes.contains(&content_id);
}
track
.fed
.as_ref()
.is_some_and(|fed| self.fed_track_liked(fed))
track_content_id(track)
.is_some_and(|id| self.likes.contains(&id) || self.fed_likes.contains(&id))
|| track
.fed
.as_ref()
.is_some_and(|fed| self.fed_likes.contains(&fed.item_id))
}
}
+60 -1
View File
@@ -112,6 +112,8 @@ pub enum Effect {
LoadListenHistory,
/// Reload the subscribed podcasts with their fetch state.
PodcastsReload,
PodcastDownload(music_dht::podcast::PodcastEpisodeRef),
SavePodcastSettings,
/// Load the season groups of a podcast.
PodcastLoadSeasons(music_dht::podcast::PodcastId),
/// Load one page of episodes; `seq` drops stale results.
@@ -165,6 +167,29 @@ pub enum Effect {
}
pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
if matches!(
action,
Action::PlayPause
| Action::NextTrack
| Action::PrevTrack
| Action::SeekForward { .. }
| Action::SeekBackward { .. }
| Action::VolumeUp
| Action::VolumeDown
| Action::CycleRepeat
| Action::ToggleShuffle
| Action::ClearQueue
| Action::RemoveFromQueue
| Action::MoveQueueUp
| Action::MoveQueueDown
| Action::QueueAddNext
| Action::QueueAddLast
| Action::RestartEpisode
) && let Err(reason) = super::remote_playback::available(state)
{
state.status_message = Some(reason.into());
return None;
}
// Any action other than a second Quit press disarms the confirmation.
let quit_armed = state
.quit_armed_until
@@ -389,6 +414,33 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
}
None
}
Action::OpenLyrics => {
if let Some(track) = selected_track(state).filter(|track| !track.is_podcast()) {
state.popup = Some(super::state::Popup::Lyrics(super::lyrics::Reader::preview(
track,
)));
} else {
state.status_message = Some("Select a music track to view its lyrics".into());
}
None
}
Action::OpenCurrentLyrics => {
state.lyrics.refresh_local();
state.popup = Some(super::state::Popup::Lyrics(super::lyrics::Reader::default()));
None
}
Action::CycleVisualizerMode => {
if state.visualizer.active {
if let Err(err) = state.visualizer.cycle_mode() {
// the fullscreen visualizer hides the status line
tracing::warn!(error = %format!("{err:#}"), "saving the visualizer mode failed");
state.status_message = Some(format!("visualization settings: {err:#}"));
}
} else {
state.status_message = Some("open the visualizer first (Shift+L)".into());
}
None
}
Action::Select => select_current(state),
Action::Back if state.visualizer.active => {
state.visualizer.close();
@@ -2819,7 +2871,7 @@ fn selected_downloadable_fed_tracks(state: &AppState) -> Vec<crate::federation::
tracks
}
fn fed_track_for_download(track: &TrackItem) -> Option<crate::federation::FedTrack> {
pub(super) fn fed_track_for_download(track: &TrackItem) -> Option<crate::federation::FedTrack> {
if let Some(fed) = &track.fed {
return Some(fed.clone());
}
@@ -3055,6 +3107,13 @@ fn select_settings_row(state: &mut AppState, row: super::state::SettingsRow) ->
state.updater.message = "Downloading update...".into();
Some(Effect::InstallUpdate(update))
}
SettingsRow::PodcastRetention => {
state.popup = Some(Popup::FedInput {
field: FedInputField::PodcastRetention,
input: crate::app::input::LineEdit::new(state.podcast_retention_days.to_string()),
});
None
}
SettingsRow::MusicDirectory => {
if state.music_dir_changing {
state.status_message = Some("music directory change is already running".into());
+25
View File
@@ -54,6 +54,31 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option<Option<Eff
open_add(state);
None
}
Action::DownloadSelected => {
if !store_ready(state) {
return Some(None);
}
let Some(track) = state.podcasts.selected_episode_track() else {
return Some(None);
};
let episode = track.podcast_episode_ref().unwrap().clone();
if state
.podcast_downloads
.contains(&crate::podcasts::offline::key(episode.episode_id.as_str()))
{
state.status_message =
Some("podcasts: episode is already available offline".into());
return Some(None);
}
if !state
.podcast_downloading
.insert(episode.episode_id.as_str().to_owned())
{
return Some(None);
}
state.status_message = Some("podcasts: downloading episode…".into());
Some(Effect::PodcastDownload(episode))
}
Action::RefreshPodcast => refresh_current(state),
Action::RefreshAllPodcasts => refresh_all(state),
Action::CycleEpisodeSort => cycle_sort(state),
+563
View File
@@ -132,6 +132,482 @@ fn test_track(id: i64) -> TrackItem {
}
}
#[test]
fn control_heart_follows_the_playing_music_track_and_uses_personal_likes_in_all_roles() {
use crate::app::{control, state::DevicePlaybackRole};
use furumi_control_protocol::Command;
let mut state = AppState::default();
let a = test_track(7);
let b = test_track(8);
let key = a.key().to_string();
let heart = |state: &AppState| control::published(state, 1).snapshot.track.unwrap().liked;
let set = || Command::SetLiked {
track_key: key.clone(),
liked: true,
};
state.player.current = Some(a.clone());
assert_eq!(heart(&state), None);
assert!(control::intent(&state, set()).is_err());
state.likes_ready = true;
state.player.queue = vec![b.clone(), a.clone()];
for role in [
DevicePlaybackRole::Active,
DevicePlaybackRole::Control,
DevicePlaybackRole::Jam,
] {
state.device_playback.role = role;
assert_eq!(heart(&state), Some(false));
let control::Intent::SetLiked { track, liked: true } =
control::intent(&state, set()).unwrap()
else {
panic!("expected a personal library edit")
};
assert_eq!(track.content_id, a.content_id);
}
state.likes.insert(a.content_id.unwrap());
assert_eq!(heart(&state), Some(true));
state.player.current = Some(b);
assert_eq!(heart(&state), Some(false));
assert!(control::intent(&state, set()).is_err());
for unavailable in [
crate::app::podcast_fixtures::episode_track(1),
crate::devices::private_track_item(0),
] {
let key = unavailable.key().to_string();
state.player.current = Some(unavailable);
assert_eq!(heart(&state), None);
assert!(
control::intent(
&state,
Command::SetLiked {
track_key: key,
liked: true
}
)
.is_err()
);
}
}
#[test]
fn control_snapshot_keeps_idle_devices_and_hides_revoked_members() {
let mut state = AppState::default();
state.device_playback.self_device_id = "self".into();
state.device_playback.self_device_name = "Local".into();
state.federation.devices = Some(crate::devices::DeviceSyncStatus {
devices: vec![crate::devices::DeviceStatusRow {
device_id: "revoked".into(),
revoked: true,
..Default::default()
}],
..Default::default()
});
let snapshot = crate::app::control::published(&state, 9).snapshot;
assert_eq!(snapshot.revision, 9);
assert!(snapshot.track.is_none());
assert_eq!(snapshot.devices.len(), 1);
assert!(snapshot.devices[0].online && snapshot.devices[0].can_transfer);
assert!(
crate::app::control::intent(
&state,
furumi_control_protocol::Command::Transfer {
device_id: "revoked".into()
}
)
.is_err()
);
}
#[test]
fn control_handoff_checks_liveness_jam_and_episode_protocol() {
use furumi_control_protocol::Command;
let mut state = AppState::default();
state.device_playback.self_device_id = "self".into();
state.player.queue = vec![crate::app::podcast_fixtures::episode_track(1)];
state.federation.devices = Some(crate::devices::DeviceSyncStatus {
devices: vec![crate::devices::DeviceStatusRow {
device_id: "old".into(),
name: "Old".into(),
protocol_version: 3,
last_seen_ms: Some(crate::app::state::unix_time_ms()),
..Default::default()
}],
..Default::default()
});
let command = Command::Transfer {
device_id: "old".into(),
};
assert!(crate::app::control::intent(&state, command.clone()).is_err());
state.federation.devices.as_mut().unwrap().devices[0].protocol_version = 4;
assert!(crate::app::control::intent(&state, command.clone()).is_ok());
state.device_playback.role = crate::app::state::DevicePlaybackRole::Jam;
assert!(crate::app::control::intent(&state, command.clone()).is_err());
state.device_playback.role = crate::app::state::DevicePlaybackRole::Active;
state.federation.devices.as_mut().unwrap().devices[0].last_seen_ms = None;
assert!(crate::app::control::intent(&state, command).is_err());
}
#[test]
fn control_uses_episode_identity_and_validates_relative_seek() {
use furumi_control_protocol::Command;
let mut state = AppState::default();
state.player.current = Some(crate::app::podcast_fixtures::episode_track(1));
let first = crate::app::control::published(&state, 0)
.snapshot
.track
.unwrap()
.key;
state.player.current = Some(crate::app::podcast_fixtures::episode_track(2));
let second = crate::app::control::published(&state, 0)
.snapshot
.track
.unwrap()
.key;
assert_ne!(first, second);
assert!(crate::app::control::intent(&state, Command::Seek { seconds: i64::MIN }).is_err());
assert!(matches!(
crate::app::control::intent(&state, Command::Seek { seconds: -10 }),
Ok(crate::app::control::Intent::Action(Action::SeekBackward {
seconds: 10
}))
));
}
#[test]
fn ctl_can_request_a_remote_release_cover_without_exposing_podcast_metadata() {
use crate::app::control::published;
use crate::library::models::ArtistRef;
let mut s = AppState::default();
let mut remote = test_track(1);
remote.artists.push(ArtistRef {
id: 4,
name: "Artist".into(),
});
s.player.current = Some(remote);
s.federation.settings.enabled = true;
let view = published(&s, 1);
assert!(view.artwork.path.is_none());
assert_eq!(view.artwork.release.as_ref().unwrap().artist, "Artist");
assert!(view.snapshot.track.unwrap().artwork_id.is_some());
s.player.current = Some(crate::app::podcast_fixtures::episode_track(1));
assert!(published(&s, 2).artwork.release.is_none());
s.player.current = None;
assert!(published(&s, 3).artwork.release.is_none());
}
fn radio_state() -> AppState {
let mut state = AppState::default();
state.similarity.settings.enabled = true;
state.similarity.settings.max_tracks_per_artist = 5;
state.device_playback.active_device_id = Some("self".into());
state.player.current = Some(test_track(1));
state.player.queue = vec![test_track(1), test_track(2)];
state.player.playing = true;
state
}
fn radio_hit(id: i64, score: f32) -> crate::app::state::SimilaritySearchHit {
crate::app::state::SimilaritySearchHit::Local {
track: test_track(id),
score,
embedding_signature: [id as u8; music_dht::similarity::SIMILARITY_SIGNATURE_BYTES],
}
}
fn controlling_player() -> (AppState, crate::devices::PlaybackSnapshot) {
use crate::app::{playback_state_from_ui, remote_playback, state::DevicePlaybackRole};
use music_dht::playback::{Announcement, Claim};
let mut s = radio_state();
s.device_playback.role = DevicePlaybackRole::Control;
s.device_playback.active_device_id = Some("web".into());
let report = crate::devices::PlaybackSnapshot {
device_id: "web".into(),
device_name: "WEB".into(),
active: true,
updated_at_ms: crate::app::state::unix_time_ms(),
state: playback_state_from_ui(&s),
coordination: Some(Announcement {
version: 1,
heartbeat: 10,
available: true,
playing: true,
claim: Some(Claim {
counter: 8,
issuer: "self".into(),
owner: "web".into(),
}),
}),
};
remote_playback::remember(&mut s, &report);
s.device_playback.last_remote_snapshot = Some(report.clone());
(s, report)
}
#[test]
fn a_control_pause_waits_for_the_owners_fresh_output_report() {
use crate::app::{control, playback_state_from_ui, remote_playback as remote};
use furumi_control_protocol::{Command, RemoteCommandState};
let (mut s, mut report) = controlling_player();
let start = std::time::Instant::now();
assert!(matches!(
update(&mut s, Action::PlayPause),
Some(Effect::TogglePause)
));
let desired = playback_state_from_ui(&s);
let id = remote::begin(&mut s, remote::Change::Transport, desired, start).unwrap();
let snapshot = control::published(&s, 1).snapshot;
assert!(!snapshot.paused);
assert_eq!(
snapshot.remote_command.unwrap().state,
RemoteCommandState::Pending
);
assert!(update(&mut s, Action::PlayPause).is_none());
assert!(control::intent(&s, Command::PlayPause).is_err());
assert!(control::intent(&s, Command::StartRadio).is_err());
// Existing media/keyboard bindings and the local API share the lock.
assert!(!s.player.paused);
report.state.paused = true;
report.coordination.as_mut().unwrap().playing = false;
report.coordination.as_mut().unwrap().heartbeat = 11;
remote::observe(&mut s, &report, start);
assert!(s.device_playback.control.busy()); // Write still in flight.
remote::recorded(&mut s, id, Ok(()));
for (device, heartbeat, paused, playing) in [
("laptop", 30, true, false),
("web", 10, true, false),
("web", 11, false, true),
("web", 12, true, true),
] {
report.device_id = device.into();
report.state.paused = paused;
let a = report.coordination.as_mut().unwrap();
a.heartbeat = heartbeat;
a.playing = playing;
remote::observe(&mut s, &report, start);
assert!(s.device_playback.control.busy());
assert!(!control::published(&s, 2).snapshot.paused);
}
report.coordination.as_mut().unwrap().heartbeat = 13;
report.coordination.as_mut().unwrap().playing = false;
remote::observe(&mut s, &report, start);
assert_eq!(
s.device_playback.control.status.state,
RemoteCommandState::Confirmed
);
crate::app::apply_playback_state_to_ui(&mut s, &report.state, None);
assert!(control::published(&s, 3).snapshot.paused);
assert!(control::intent(&s, Command::PlayPause).is_ok());
}
#[test]
fn controller_unlocks_on_timeout_write_failure_or_change_of_owner() {
use crate::app::remote_playback as remote;
use furumi_control_protocol::RemoteCommandState;
let (mut s, report) = controlling_player();
let start = std::time::Instant::now();
let mut desired = report.state.clone();
desired.volume = 55;
let first = remote::begin(&mut s, remote::Change::Volume, desired.clone(), start).unwrap();
remote::recorded(&mut s, first, Err("Device command failed".into()));
assert_eq!(
s.device_playback.control.status.state,
RemoteCommandState::Failed
);
let second = remote::begin(&mut s, remote::Change::Volume, desired.clone(), start).unwrap();
remote::recorded(&mut s, first, Err("Late failure".into()));
assert!(s.device_playback.control.busy());
remote::recorded(&mut s, second, Ok(()));
remote::tick(&mut s, start + std::time::Duration::from_secs(16));
assert_eq!(
s.device_playback.control.status.state,
RemoteCommandState::Failed
);
assert_eq!(s.player.volume, report.state.volume);
remote::begin(&mut s, remote::Change::Volume, desired, start).unwrap();
s.device_playback.active_device_id = Some("new owner".into());
remote::tick(&mut s, start);
assert!(!s.device_playback.control.busy());
assert_eq!(
s.device_playback.control.status.error.as_deref(),
Some("Playback ownership changed")
);
}
#[test]
fn remote_seek_modes_and_tracks_wait_for_the_requested_change() {
use crate::app::remote_playback as remote;
for change in [
remote::Change::Seek,
remote::Change::Options,
remote::Change::Start,
remote::Change::Queue,
remote::Change::Volume,
] {
let (mut s, mut report) = controlling_player();
let start = std::time::Instant::now();
let mut desired = report.state.clone();
match change {
remote::Change::Seek => desired.position_secs = 30.0,
remote::Change::Options => desired.shuffle = true,
remote::Change::Start => desired.queue_pos = 1,
remote::Change::Queue => desired.queue.reverse(),
remote::Change::Volume => desired.volume = 55,
remote::Change::Transport => unreachable!(),
}
let id = remote::begin(&mut s, change, desired.clone(), start).unwrap();
remote::recorded(&mut s, id, Ok(()));
report.coordination.as_mut().unwrap().heartbeat += 1;
remote::observe(&mut s, &report, start);
assert!(s.device_playback.control.busy(), "{change:?}");
report.state = desired;
// Numeric IDs belong to the owner, even when content is the same.
report.state.queue[0].id = 5432;
report.coordination.as_mut().unwrap().heartbeat += 1;
remote::observe(&mut s, &report, start);
assert!(!s.device_playback.control.busy(), "{change:?}");
}
}
#[test]
fn radio_keeps_queue_until_collection_finishes_and_waits_for_audio_start() {
use furumi_control_protocol::RadioState;
let mut state = radio_state();
let before: Vec<_> = state.player.queue.iter().map(|track| track.id).collect();
crate::app::radio::begin(&mut state).unwrap();
let id = state.radio.status.id;
assert_eq!(state.radio.status.state, RadioState::Searching);
assert_eq!(
state
.player
.queue
.iter()
.map(|track| track.id)
.collect::<Vec<_>>(),
before
);
assert!(crate::app::radio::prepare(
&mut state,
id,
Ok(vec![radio_hit(3, 0.8), radio_hit(4, 0.9)])
));
assert_eq!(state.player.queue[0].id, 4);
assert_eq!(state.radio.status.state, RadioState::Starting);
crate::app::radio::started(&mut state); // Old source still playing.
assert_eq!(state.radio.status.state, RadioState::Starting);
state.player.current = Some(state.player.queue[0].clone());
state.player.paused = false;
crate::app::radio::started(&mut state);
assert_eq!(state.radio.status.state, RadioState::Playing);
}
#[test]
fn radio_errors_empty_matches_and_stale_results_preserve_the_existing_queue() {
use furumi_control_protocol::RadioState;
for result in [Err("peer error".into()), Ok(vec![])] {
let mut state = radio_state();
crate::app::radio::begin(&mut state).unwrap();
let id = state.radio.status.id;
assert!(!crate::app::radio::prepare(&mut state, id, result));
assert_eq!(state.player.queue[0].id, 1);
assert_eq!(state.radio.status.state, RadioState::Failed);
}
let mut state = radio_state();
crate::app::radio::begin(&mut state).unwrap();
let id = state.radio.status.id;
assert!(!crate::app::radio::prepare(
&mut state,
id + 1,
Ok(vec![radio_hit(3, 0.9)])
));
assert_eq!(state.radio.status.state, RadioState::Searching);
state.player.queue.push(test_track(9)); // A newer user queue must win.
assert!(!crate::app::radio::prepare(
&mut state,
id,
Ok(vec![radio_hit(3, 0.9)])
));
assert_eq!(state.player.queue.last().unwrap().id, 9);
assert_eq!(state.radio.status.state, RadioState::Failed);
}
#[test]
fn radio_rechecks_owner_and_requires_music_and_enabled_similarity() {
let mut state = radio_state();
state.similarity.settings.enabled = false;
assert!(crate::app::radio::begin(&mut state).is_err());
state.similarity.settings.enabled = true;
state.player.current = Some(crate::app::podcast_fixtures::episode_track(1));
assert!(crate::app::radio::begin(&mut state).is_err());
state.player.current = Some(test_track(1));
crate::app::radio::begin(&mut state).unwrap();
let id = state.radio.status.id;
assert!(crate::app::radio::begin(&mut state).is_err());
state.device_playback.active_device_id = Some("another".into());
assert!(!crate::app::radio::prepare(
&mut state,
id,
Ok(vec![radio_hit(3, 0.9)])
));
assert_eq!(state.player.queue[0].id, 1);
}
#[test]
fn radio_remote_start_requires_the_output_report_and_advancing_position() {
use crate::devices::PlaybackTrackExt as _;
use furumi_control_protocol::RadioState;
let mut state = radio_state();
crate::app::radio::begin(&mut state).unwrap();
let id = state.radio.status.id;
let mut snapshot = crate::devices::PlaybackSnapshot {
coordination: None,
device_id: "self".into(),
device_name: "Output".into(),
active: true,
updated_at_ms: 10,
state: crate::devices::PlaybackStateWire {
queue: vec![crate::devices::PlaybackTrack::from_track(&test_track(3))],
playing: true,
paused: false,
queue_pos: 0,
idle_since_ms: None,
position_secs: 0.0,
volume: 80,
shuffle: false,
repeat: crate::devices::PlaybackRepeat::Off,
playback_rate: None,
},
};
state
.device_playback
.remote
.insert("self".into(), snapshot.clone());
assert!(crate::app::radio::prepare(
&mut state,
id,
Ok(vec![radio_hit(3, 0.9)])
));
crate::app::radio::remote_started(&mut state, &snapshot);
assert_eq!(state.radio.status.state, RadioState::Starting);
snapshot.state.position_secs = 0.1;
crate::app::radio::remote_started(&mut state, &snapshot);
assert_eq!(state.radio.status.state, RadioState::Starting); // Cached report.
snapshot.updated_at_ms = 11;
snapshot.device_id = "other".into();
crate::app::radio::remote_started(&mut state, &snapshot);
assert_eq!(state.radio.status.state, RadioState::Starting);
snapshot.device_id = "self".into();
snapshot
.state
.queue
.push(crate::devices::PlaybackTrack::from_track(&test_track(4)));
crate::app::radio::remote_started(&mut state, &snapshot);
assert_eq!(state.radio.status.state, RadioState::Starting); // Another queue.
snapshot.state.queue.pop();
crate::app::radio::remote_started(&mut state, &snapshot);
assert_eq!(state.radio.status.state, RadioState::Playing);
}
fn pending_fed_track(id: i64) -> TrackItem {
crate::federation::pending_track(&crate::federation::FedTrack {
item_id: format!("fed-{id}"),
@@ -776,6 +1252,20 @@ fn visualizer_requires_current_track() {
);
}
#[test]
fn visualizer_mode_needs_an_open_visualizer() {
let mut state = AppState::default();
let mode = state.visualizer.config.mode;
assert_eq!(update(&mut state, Action::CycleVisualizerMode), None);
assert_eq!(state.visualizer.config.mode, mode);
assert_eq!(
state.status_message.as_deref(),
Some("open the visualizer first (Shift+L)")
);
}
#[test]
fn visualizer_toggles_and_back_closes_it() {
let mut state = AppState::default();
@@ -2813,3 +3303,76 @@ mod podcast_discovery {
));
}
}
#[test]
fn episode_download_requires_explicit_action_and_deduplicates_requests() {
use crate::app::podcast_fixtures as fx;
let mut state = fx::with_episodes(
fx::ready_state(vec![fx::row("Show", 1, 1, 0)]),
vec![fx::episode(1, "Episode", None)],
);
assert!(state.podcast_downloading.is_empty());
let expected = state
.podcasts
.selected_episode_track()
.unwrap()
.podcast_episode_ref()
.unwrap()
.clone();
assert_eq!(
update(&mut state, Action::DownloadSelected),
Some(Effect::PodcastDownload(expected.clone()))
);
assert_eq!(update(&mut state, Action::DownloadSelected), None);
assert_eq!(state.podcast_downloading.len(), 1);
state.podcast_downloading.clear();
state
.podcast_downloads
.insert(crate::podcasts::offline::key(expected.episode_id.as_str()));
assert_eq!(update(&mut state, Action::DownloadSelected), None);
assert!(state.podcast_downloading.is_empty());
}
#[test]
fn podcast_retention_opens_a_numeric_editor_in_additional_settings() {
use crate::app::state::{FedInputField, Popup, SettingsRow, additional_settings_rows};
let mut state = AppState {
additional_settings_open: true,
podcast_retention_days: 30,
..Default::default()
};
state.additional_settings_cursor = additional_settings_rows(&state)
.iter()
.position(|row| *row == SettingsRow::PodcastRetention)
.unwrap();
assert_eq!(update(&mut state, Action::Select), None);
assert!(matches!(
state.popup,
Some(Popup::FedInput {
field: FedInputField::PodcastRetention,
..
})
));
}
#[test]
fn lyrics_preview_uses_queue_cursor_and_current_action_follows_playback() {
let mut state = AppState {
active_tab: Tab::Queue,
..Default::default()
};
state.player.current = Some(test_track(1));
state.player.queue = vec![test_track(1), test_track(2)];
state.queue_tab.cursor = 1;
update(&mut state, Action::OpenLyrics);
let Some(crate::app::state::Popup::Lyrics(reader)) = &state.popup else {
panic!("expected lyrics preview")
};
assert_eq!(reader.preview.as_ref().unwrap().0.id, 2);
update(&mut state, Action::OpenCurrentLyrics);
let Some(crate::app::state::Popup::Lyrics(reader)) = &state.popup else {
panic!("expected now-playing lyrics")
};
assert!(reader.preview.is_none());
assert_eq!(state.player.current.as_ref().unwrap().id, 1);
}
+9 -1
View File
@@ -137,7 +137,11 @@ command = "MoveLeft"
[[keymaps]]
key_sequence = "l"
command = "MoveRight"
command = "OpenLyrics"
[[keymaps]]
key_sequence = "ctrl-l"
command = "OpenCurrentLyrics"
[[keymaps]]
key_sequence = "right"
@@ -223,6 +227,10 @@ command = "CycleRepeat"
key_sequence = "shift-l"
command = "ToggleVisualizer"
[[keymaps]]
key_sequence = "shift-m"
command = "CycleVisualizerMode"
[[keymaps]]
key_sequence = "shift-h"
command = "OpenListenHistory"
+18
View File
@@ -456,6 +456,19 @@ mod tests {
);
}
#[test]
fn lyrics_keys_distinguish_selected_and_playing_track() {
let mut km = keymap_from(DEFAULT_KEYMAP);
assert_eq!(
km.resolve(key!(l), KeyContext::Library),
KeyResolution::Action(Action::OpenLyrics)
);
assert_eq!(
km.resolve(key!(ctrl - l), KeyContext::Library),
KeyResolution::Action(Action::OpenCurrentLyrics)
);
}
#[test]
fn chord_sequence_resolves() {
let mut km = keymap_from(DEFAULT_KEYMAP);
@@ -584,6 +597,11 @@ mod tests {
km.resolve(shift_l, KeyContext::Library),
KeyResolution::Action(Action::ToggleVisualizer)
);
let shift_m = KeyCombination::new(KeyCode::Char('M'), KeyModifiers::SHIFT);
assert_eq!(
km.resolve(shift_m, KeyContext::Library),
KeyResolution::Action(Action::CycleVisualizerMode)
);
}
#[test]
+9
View File
@@ -50,6 +50,8 @@ impl Default for SimilaritySettings {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AppSettings {
#[serde(default = "default_podcast_retention_days")]
pub podcast_retention_days: u32,
#[serde(default)]
pub playback: music_dht::playback::Config,
#[serde(default = "default_volume")]
@@ -66,6 +68,7 @@ pub struct AppSettings {
impl Default for AppSettings {
fn default() -> Self {
Self {
podcast_retention_days: 30,
playback: music_dht::playback::Config::default(),
volume: default_volume(),
library: LibraryFilters::default(),
@@ -77,6 +80,7 @@ impl Default for AppSettings {
impl AppSettings {
pub fn normalized(mut self) -> Self {
self.podcast_retention_days = self.podcast_retention_days.clamp(1, 36500);
self.volume = self.volume.min(100);
if self.music_dir.as_os_str().is_empty() {
self.music_dir = default_music_dir();
@@ -97,6 +101,10 @@ impl AppSettings {
}
}
fn default_podcast_retention_days() -> u32 {
30
}
fn default_volume() -> u8 {
80
}
@@ -186,6 +194,7 @@ hide_featured_only = true
let settings = settings.normalized();
assert_eq!(settings.volume, 100);
assert_eq!(settings.podcast_retention_days, 30);
assert!(settings.library.hide_featured_only);
assert_eq!(settings.library.source_mode, LibrarySourceMode::Global);
assert_eq!(settings.music_dir, default_music_dir());
+557
View File
@@ -0,0 +1,557 @@
//! Authenticated, loopback-only control of this running player. No LAN authority.
use std::collections::VecDeque;
use std::io::{Cursor, Read as _};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context as _, Result, bail, ensure};
use base64::Engine as _;
use furumi_control_protocol::{
API_VERSION, ClientMessage, Command, Discovery, MAX_MESSAGE_BYTES, ServerMessage, Snapshot,
};
use futures_util::{SinkExt, StreamExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::{JoinHandle, JoinSet};
use tokio_tungstenite::tungstenite::{Message, protocol::WebSocketConfig};
#[path = "control_art.rs"]
pub(crate) mod art;
#[path = "control_spectrum.rs"]
mod spectrum;
pub(crate) use spectrum::Spectrum;
#[cfg(test)]
#[path = "control_tests.rs"]
mod tests;
#[derive(Debug)]
pub struct Request {
pub command: Command,
pub reply: oneshot::Sender<std::result::Result<(), String>>,
}
#[derive(Clone)]
pub struct Published {
pub snapshot: Snapshot,
/// Local-only, never serialized. Artwork requests must match the current ID.
pub(crate) artwork: art::Source,
}
struct Queued {
id: String,
command: Command,
reply: oneshot::Sender<ServerMessage>,
}
pub struct Service {
state: watch::Sender<Published>,
pub(crate) spectrum: Spectrum,
task: JoinHandle<()>,
discovery: PathBuf,
token: String,
}
impl Service {
pub async fn start(
initial: Published,
events: mpsc::UnboundedSender<crate::app::event::AppEvent>,
library: Arc<crate::library::Library>,
federation: Arc<crate::federation::Federation>,
) -> Result<Self> {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?;
let port = listener.local_addr()?.port();
let (discovery, token) = tokio::task::spawn_blocking(move || -> Result<_> {
let path = furumi_control_protocol::discovery_path()
.context("no application data directory")?;
let token = rand::random::<[u8; 32]>()
.map(|byte| format!("{byte:02x}"))
.concat();
write_discovery(
&path,
&Discovery {
api_version: API_VERSION,
port,
token: token.clone(),
},
)?;
Ok((path, token))
})
.await??;
let (state, receiver) = watch::channel(initial);
let (commands, queue) = mpsc::channel(32);
let secret = token.clone();
let covers = art::Covers::new(library, federation);
let spectrum = Spectrum::default();
let frames = spectrum.frames.clone();
let task = tokio::spawn(async move {
let mut tasks = JoinSet::new();
tasks.spawn(broker(queue, events));
let clients = Arc::new(tokio::sync::Semaphore::new(8));
loop {
tokio::select! {
connection = listener.accept() => {
let Ok((socket, _)) = connection else { break };
let Ok(permit) = clients.clone().try_acquire_owned() else { continue };
let (state, token, commands, covers) = (receiver.clone(), secret.clone(), commands.clone(), covers.clone());
let frames = frames.clone();
tasks.spawn(async move {
let _permit = permit;
// Connection errors are deliberately not logged with private metadata.
let _ = session(socket, &token, state, commands, covers, frames).await;
});
}
_ = tasks.join_next(), if !tasks.is_empty() => {}
}
}
});
Ok(Self {
state,
spectrum,
task,
discovery,
token,
})
}
pub fn publish(&self, value: Published) {
self.state.send_replace(value);
}
pub async fn shutdown(mut self) {
self.task.abort();
let _ = (&mut self.task).await;
let (path, token) = (self.discovery.clone(), std::mem::take(&mut self.token));
let _ = tokio::task::spawn_blocking(move || remove_discovery(&path, &token)).await;
}
}
impl Drop for Service {
fn drop(&mut self) {
self.task.abort();
if self.token.is_empty() {
return;
}
let (path, token) = (self.discovery.clone(), self.token.clone());
// Avoid filesystem work during terminal teardown and never remove a successor's endpoint.
let _ = std::thread::Builder::new()
.name("control-cleanup".into())
.spawn(move || remove_discovery(&path, &token));
}
}
fn remove_discovery(path: &std::path::Path, token: &str) {
if std::fs::read(path)
.ok()
.and_then(|bytes| serde_json::from_slice::<Discovery>(&bytes).ok())
.is_some_and(|current| current.token == token)
{
let _ = std::fs::remove_file(path);
}
}
fn write_discovery(path: &std::path::Path, value: &Discovery) -> Result<()> {
let parent = path.parent().context("invalid control endpoint path")?;
std::fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.as_file()
.set_permissions(std::fs::Permissions::from_mode(0o600))?;
}
use std::io::Write as _;
file.write_all(&serde_json::to_vec(value)?)?;
file.persist(path).map_err(|error| error.error)?;
Ok(())
}
async fn broker(
mut queue: mpsc::Receiver<Queued>,
events: mpsc::UnboundedSender<crate::app::event::AppEvent>,
) {
// A reconnect/retry with the same ID never toggles pause or seeks twice.
let mut recent: VecDeque<(String, Command, ServerMessage)> = VecDeque::new();
while let Some(request) = queue.recv().await {
if let Some((_, command, result)) = recent.iter().find(|(id, _, _)| id == &request.id) {
let result = if command == &request.command {
result.clone()
} else {
failure(
request.id.clone(),
"request ID already used for another command",
)
};
let _ = request.reply.send(result);
continue;
}
let (tx, rx) = oneshot::channel();
let result = if events
.send(crate::app::event::AppEvent::Control(Request {
command: request.command.clone(),
reply: tx,
}))
.is_err()
{
Err("player unavailable".into())
} else {
tokio::time::timeout(Duration::from_secs(5), rx)
.await
.map_err(|_| "command timed out; result unknown".to_string())
.and_then(|reply| reply.map_err(|_| "player unavailable".to_string()))
.and_then(|result| result)
};
let result = ServerMessage::Result {
id: request.id.clone(),
accepted: result.is_ok(),
error: result.err(),
};
if recent.len() == 256 {
recent.pop_front();
}
recent.push_back((request.id, request.command, result.clone()));
let _ = request.reply.send(result);
}
}
fn failure(id: String, message: &str) -> ServerMessage {
ServerMessage::Result {
id,
accepted: false,
error: Some(message.into()),
}
}
#[expect(
clippy::result_large_err,
reason = "tungstenite fixes the handshake callback error to an HTTP response"
)]
fn native_handshake(
request: &tokio_tungstenite::tungstenite::handshake::server::Request,
response: tokio_tungstenite::tungstenite::handshake::server::Response,
) -> std::result::Result<
tokio_tungstenite::tungstenite::handshake::server::Response,
tokio_tungstenite::tungstenite::handshake::server::ErrorResponse,
> {
// Browser pages cannot use localhost as an ambient control channel.
if request.headers().contains_key("origin") {
let mut denied = tokio_tungstenite::tungstenite::handshake::server::ErrorResponse::new(
Some("native clients only".into()),
);
*denied.status_mut() = tokio_tungstenite::tungstenite::http::StatusCode::FORBIDDEN;
Err(denied)
} else {
Ok(response)
}
}
async fn session(
socket: TcpStream,
token: &str,
mut state: watch::Receiver<Published>,
commands: mpsc::Sender<Queued>,
covers: Arc<art::Covers>,
frames: watch::Sender<spectrum::Frame>,
) -> Result<()> {
let config = WebSocketConfig::default()
.max_message_size(Some(16 * 1024))
.max_frame_size(Some(16 * 1024));
let mut socket = tokio::time::timeout(
Duration::from_secs(5),
tokio_tungstenite::accept_hdr_async_with_config(socket, native_handshake, Some(config)),
)
.await??;
let auth = tokio::time::timeout(Duration::from_secs(5), socket.next())
.await?
.context("missing authentication")??;
let authenticated = matches!(auth, Message::Text(ref data) if matches!(serde_json::from_str::<ClientMessage>(data), Ok(ClientMessage::Authenticate {token: supplied, api_version}) if api_version == API_VERSION && supplied == token));
ensure!(authenticated, "authentication failed");
let mut jobs = JoinSet::new();
let mut pending_cover: Option<(String, String)> = None;
let mut spectrum_subscription = None;
let initial = state.borrow_and_update().snapshot.clone();
send(
&mut socket,
ServerMessage::Snapshot {
snapshot: Box::new(initial),
},
)
.await?;
loop {
tokio::select! {
Some(frame) = spectrum::next_frame(&mut spectrum_subscription) => {
send(&mut socket, frame).await?;
}
Some(done) = jobs.join_next(), if !jobs.is_empty() => {
if let Ok((id, artwork_id, png_base64)) = done
&& pending_cover.as_ref().is_some_and(|(i, key)| i == &id && key == &artwork_id)
{
pending_cover = None;
let current = state.borrow().snapshot.track.as_ref().and_then(|t| t.artwork_id.as_ref()) == Some(&artwork_id);
let reply = if current { ServerMessage::Artwork { id, artwork_id, png_base64 } } else { failure(id, "artwork is no longer current") };
send(&mut socket, reply).await?;
}
}
changed = state.changed() => {
if changed.is_err() { break; }
let snapshot = state.borrow_and_update().snapshot.clone();
if pending_cover.as_ref().is_some_and(|(_, key)| snapshot.track.as_ref().and_then(|t| t.artwork_id.as_ref()) != Some(key)) {
jobs.abort_all();
if let Some((id, _)) = pending_cover.take() {
send(&mut socket, failure(id, "artwork is no longer current")).await?;
}
}
send(&mut socket, ServerMessage::Snapshot { snapshot: Box::new(snapshot) }).await?;
}
message = socket.next() => {
let Some(message) = message else { break };
let data = match message? {
Message::Text(data) => data,
Message::Ping(data) => { socket.send(Message::Pong(data)).await?; continue; }
Message::Close(_) => break,
_ => continue,
};
let (id, command) = match serde_json::from_str(&data)? {
ClientMessage::Command { id, command } => (id, command),
ClientMessage::SubscribeSpectrum { enabled } => {
if enabled {
spectrum_subscription.get_or_insert_with(|| frames.subscribe());
} else {
spectrum_subscription = None;
}
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
}
ClientMessage::Authenticate { .. } => bail!("already authenticated"),
};
ensure!(!id.is_empty() && id.len() <= 128, "invalid request ID");
let result = if let Command::Artwork { artwork_id, federation } = command {
let source = {
let current = state.borrow();
current.snapshot.track.as_ref().is_some_and(|t| t.artwork_id.as_ref() == Some(&artwork_id)).then(|| current.artwork.clone())
};
if let Some(source) = source {
if let Some((previous, _)) = pending_cover.take() {
jobs.abort_all();
send(&mut socket, failure(previous, "artwork request superseded")).await?;
}
pending_cover = Some((id.clone(), artwork_id.clone()));
let covers = covers.clone();
jobs.spawn(async move {
let data = covers.get(&artwork_id, source, federation).await;
(id, artwork_id, data)
});
None
} else {
Some(failure(id, "artwork is no longer current"))
}
} else {
let (reply, result) = oneshot::channel();
if commands.try_send(Queued { id: id.clone(), command, reply }).is_err() {
Some(failure(id, "control queue busy"))
} else {
Some(result.await?)
}
};
if let Some(result) = result { send(&mut socket, result).await?; }
// Bound a malfunctioning client's event and artwork request rate.
tokio::time::sleep(Duration::from_millis(25)).await;
}
}
}
Ok(())
}
async fn send(
socket: &mut tokio_tungstenite::WebSocketStream<TcpStream>,
message: ServerMessage,
) -> Result<()> {
let encoded = serde_json::to_string(&message)?;
ensure!(encoded.len() <= MAX_MESSAGE_BYTES, "snapshot too large");
tokio::time::timeout(
Duration::from_secs(3),
socket.send(Message::Text(encoded.into())),
)
.await??;
Ok(())
}
fn artwork(path: &std::path::Path) -> Result<String> {
let mut bytes = Vec::new();
std::fs::File::open(path)?
.take(10 * 1024 * 1024 + 1)
.read_to_end(&mut bytes)?;
ensure!(bytes.len() <= 10 * 1024 * 1024, "artwork too large");
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format()?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(64 * 1024 * 1024);
reader.limits(limits);
let image = reader
.decode()?
.resize_to_fill(384, 384, image::imageops::FilterType::Triangle);
let mut png = Cursor::new(Vec::new());
image.write_to(&mut png, image::ImageFormat::Png)?;
Ok(base64::engine::general_purpose::STANDARD.encode(png.into_inner()))
}
pub async fn cli(args: &[String]) -> Result<()> {
const USAGE: &str = "usage: furumi ctl status|devices|watch|play-pause|next|previous|seek SECONDS|volume-up|volume-down|transfer DEVICE_ID|shuffle|repeat|radio\n furumi ctl artwork [--federation] [--output FILE.png]";
if args.is_empty() || args.iter().any(|arg| arg == "--help" || arg == "-h") {
println!("{USAGE}");
return Ok(());
}
let mode = args.first().map(String::as_str).context(USAGE)?;
let argument = || args.get(1).cloned().context("missing command argument");
let command = match mode {
"status" | "devices" | "watch" | "artwork" => None,
"shuffle" => Some(Command::ToggleShuffle),
"repeat" => Some(Command::CycleRepeat),
"radio" => Some(Command::StartRadio),
"play-pause" => Some(Command::PlayPause),
"next" => Some(Command::Next),
"previous" => Some(Command::Previous),
"seek" => Some(Command::Seek {
seconds: argument()?.parse()?,
}),
"volume-up" => Some(Command::VolumeUp),
"volume-down" => Some(Command::VolumeDown),
"transfer" => Some(Command::Transfer {
device_id: argument()?,
}),
_ => bail!("unknown control command: {mode}"),
};
let mut federated_art = false;
let mut art_output = None;
if mode == "artwork" {
let mut options = args[1..].iter();
while let Some(option) = options.next() {
match option.as_str() {
"--federation" => federated_art = true,
"--output" if art_output.is_none() => {
art_output = Some(PathBuf::from(
options.next().context("missing output file")?,
))
}
other => bail!("unknown or duplicate artwork option: {other}"),
}
}
}
let path =
furumi_control_protocol::discovery_path().context("no application data directory")?;
let endpoint: Discovery = serde_json::from_slice(
&tokio::fs::read(path)
.await
.context("Furumi is not running (no control endpoint)")?,
)?;
ensure!(
endpoint.api_version == API_VERSION,
"incompatible control API"
);
let (mut socket, _) = tokio::time::timeout(
Duration::from_secs(3),
tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{}", endpoint.port)),
)
.await??;
socket
.send(Message::Text(
serde_json::to_string(&ClientMessage::Authenticate {
token: endpoint.token,
api_version: API_VERSION,
})?
.into(),
))
.await?;
let mut has_command = command.is_some();
let request_id = format!("cli-{:032x}", rand::random::<u128>());
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
if let Some(command) = command {
let request = ClientMessage::Command {
id: request_id.clone(),
command,
};
socket
.send(Message::Text(serde_json::to_string(&request)?.into()))
.await?;
}
loop {
let read_until = if mode == "artwork" {
deadline
} else {
tokio::time::Instant::now() + Duration::from_secs(10)
};
let message = tokio::time::timeout_at(read_until, socket.next())
.await?
.context("player disconnected")??;
let Message::Text(text) = message else {
continue;
};
let message: ServerMessage = serde_json::from_str(&text)?;
match message {
ServerMessage::Snapshot { snapshot } if mode == "artwork" && !has_command => {
let artwork_id = snapshot
.track
.and_then(|t| t.artwork_id)
.context("no artwork available for the current track")?;
let request = ClientMessage::Command {
id: request_id.clone(),
command: Command::Artwork {
artwork_id,
federation: federated_art,
},
};
socket
.send(Message::text(serde_json::to_string(&request)?))
.await?;
has_command = true;
}
ServerMessage::Artwork { id, png_base64, .. } if id == request_id => {
if let Some(path) = art_output {
let bytes = base64::engine::general_purpose::STANDARD
.decode(png_base64.context("artwork not found")?)?;
tokio::task::spawn_blocking(move || -> Result<()> {
use std::io::Write as _;
let directory = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(std::path::Path::new("."));
let mut file = tempfile::NamedTempFile::new_in(directory)?;
file.write_all(&bytes)?;
file.persist_noclobber(&path)
.map_err(|e| e.error)
.context("could not create artwork output file")?;
Ok(())
})
.await??;
} else {
println!("{text}");
}
return Ok(());
}
ServerMessage::Snapshot { snapshot } if !has_command => {
if mode == "devices" {
println!("{}", serde_json::to_string(&snapshot.devices)?);
} else {
println!("{}", serde_json::to_string(&snapshot)?);
}
if mode != "watch" {
return Ok(());
}
}
ServerMessage::Result {
accepted, error, ..
} => {
println!("{text}");
ensure!(
accepted,
"{}",
error.unwrap_or_else(|| "command rejected".into())
);
return Ok(());
}
_ => {}
}
}
}
+237
View File
@@ -0,0 +1,237 @@
//! On-demand cover resolution for local control clients. A snapshot carries
//! lookup metadata only. The first explicit request starts the work.
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use futures_util::future::BoxFuture;
use tokio::sync::OnceCell;
use crate::config::settings::LibrarySourceMode;
use crate::federation::Federation;
use crate::library::Library;
#[derive(Clone, Debug, Default)]
pub(crate) struct Source {
pub path: Option<PathBuf>,
pub release: Option<Release>,
}
#[derive(Clone, Debug)]
pub(crate) struct Release {
pub artist: String,
pub title: String,
pub owners: Vec<String>,
pub global: bool,
pub network_enabled: bool,
}
impl Source {
pub fn current(state: &crate::app::state::AppState) -> Self {
let Some(track) = &state.player.current else {
return Self::default();
};
let path = track.cover_path.as_ref().map(PathBuf::from);
let release = if track.is_podcast() || crate::devices::is_private_track_item(track) {
None
} else {
let artist = track
.artists
.iter()
.map(|a| a.name.trim())
.find(|a| !a.is_empty())
.or_else(|| track.fed.as_ref()?.artist_names.first().map(|s| s.trim()));
let title = track.release_title.trim();
artist
.filter(|a| !a.is_empty() && !title.is_empty())
.map(|artist| {
let global = state.global.filters.source_mode == LibrarySourceMode::Global;
let trusted = state
.federation
.devices
.as_ref()
.map_or(&[][..], |s| s.devices.as_slice());
let mut owners = Vec::new();
if let Some(output) = trusted.iter().find(|d| {
!d.revoked
&& !d.is_self
&& Some(&d.device_id) == state.device_playback.active_device_id.as_ref()
}) && !output.endpoint_id.is_empty()
{
owners.push(output.endpoint_id.clone());
}
if let Some(fed) = &track.fed
&& !fed.owner.is_empty()
&& !owners.contains(&fed.owner)
&& (global
|| trusted
.iter()
.any(|d| !d.revoked && d.endpoint_id == fed.owner))
{
owners.push(fed.owner.clone());
}
Release {
artist: artist.to_owned(),
title: title.to_owned(),
owners,
global,
network_enabled: state.federation.settings.enabled,
}
})
};
Self { path, release }
}
pub fn id(&self, track_key: &str) -> Option<String> {
if self.path.is_none() && self.release.is_none() {
return None;
}
let mut hash = blake3::Hasher::new();
let mut field = |value: &[u8]| {
hash.update(&value.len().to_le_bytes());
hash.update(value);
};
field(track_key.as_bytes());
if let Some(path) = &self.path {
field(path.as_os_str().as_encoded_bytes());
}
if let Some(r) = &self.release {
field(r.artist.as_bytes());
field(r.title.as_bytes());
field(&[r.global as u8, r.network_enabled as u8]);
for owner in &r.owners {
field(owner.as_bytes());
}
}
Some(hash.finalize().to_hex().to_string())
}
}
type Resolver = dyn Fn(Source, bool) -> BoxFuture<'static, Option<String>> + Send + Sync;
struct Cached {
id: String,
federated: bool,
result: Arc<OnceCell<(Instant, Option<String>)>>,
}
pub(super) struct Covers {
resolve: Box<Resolver>,
entries: Mutex<VecDeque<Cached>>,
}
impl Covers {
pub(super) fn new(library: Arc<Library>, federation: Arc<Federation>) -> Arc<Self> {
Self::with(move |source, allow| {
let library = library.clone();
let federation = federation.clone();
Box::pin(async move {
let release = source.release;
let local = release
.as_ref()
.map(|r| (r.artist.clone(), r.title.clone()));
let encoded = tokio::task::spawn_blocking(move || {
if let Some(data) = source.path.and_then(|p| super::artwork(&p).ok()) {
return Some(data);
}
let (artist, title) = local?;
let path = library.release_cover_by_names(&artist, &title).ok()??;
super::artwork(std::path::Path::new(&path)).ok()
})
.await
.ok()
.flatten();
if encoded.is_some() || !allow {
return encoded;
}
let release = release.filter(|r| r.network_enabled)?;
let path = release.fetch(&federation).await?;
tokio::task::spawn_blocking(move || {
super::artwork(std::path::Path::new(&path)).ok()
})
.await
.ok()
.flatten()
})
})
}
pub(super) fn with(
resolve: impl Fn(Source, bool) -> BoxFuture<'static, Option<String>> + Send + Sync + 'static,
) -> Arc<Self> {
Arc::new(Self {
resolve: Box::new(resolve),
entries: Mutex::new(VecDeque::new()),
})
}
pub(super) async fn get(&self, id: &str, source: Source, federated: bool) -> Option<String> {
let cell = {
let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
entries.retain(|e| {
!e.result.get().is_some_and(|(at, value)| {
value.is_none() && at.elapsed() >= Duration::from_secs(30)
})
});
if let Some(entry) = entries
.iter()
.find(|e| e.id == id && e.federated == federated)
{
entry.result.clone()
} else {
if entries.len() == 8 {
entries.pop_front();
}
let cell = Arc::new(OnceCell::new());
entries.push_back(Cached {
id: id.to_owned(),
federated,
result: cell.clone(),
});
cell
}
};
cell.get_or_init(|| async {
let reply =
tokio::time::timeout(Duration::from_secs(25), (self.resolve)(source, federated))
.await
.ok()
.flatten();
(Instant::now(), reply)
})
.await
.1
.clone()
}
}
impl Release {
async fn fetch(&self, federation: &Federation) -> Option<String> {
if let Some(path) = federation
.card_image(&self.owners, &self.artist, Some(&self.title))
.await
{
return Some(path);
}
// Only global library mode uses wider artist discovery. Request art
// from owners of this release, rather than sending its title to all peers.
if !self.global {
return None;
}
let card = federation.artist_card(&self.artist).await.ok()?;
let title = music_dht::normalize_name(&self.title);
let release = card
.releases
.iter()
.find(|r| music_dht::normalize_name(&r.title) == title)?;
let owners: Vec<_> = release
.owners
.iter()
.filter(|o| !self.owners.contains(o) && Some(*o) != card.own_owner.as_ref())
.take(6)
.cloned()
.collect();
federation
.card_image(&owners, &self.artist, Some(&release.title))
.await
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Latest local audio levels. A connection owns a receiver only for the
//! lifetime of its subscription, so multiple decks share one sampled frame.
use std::time::{Duration, Instant};
use furumi_control_protocol::{SPECTRUM_BANDS, ServerMessage};
use tokio::sync::watch;
const FRAME_INTERVAL: Duration = Duration::from_millis(100);
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct Frame {
epoch: u64,
sequence: u64,
bands: Option<[u8; SPECTRUM_BANDS]>,
}
pub(crate) struct Spectrum {
pub(super) frames: watch::Sender<Frame>,
last_frame: Option<Instant>,
}
impl Default for Spectrum {
fn default() -> Self {
Self {
frames: watch::Sender::new(Frame::default()),
last_frame: None,
}
}
}
impl Spectrum {
pub(crate) fn sample(&mut self, at: Instant, levels: &[f64]) {
if self.frames.receiver_count() == 0
|| self
.last_frame
.is_some_and(|last| at.saturating_duration_since(last) < FRAME_INTERVAL)
{
return;
}
let Ok(levels) = <&[f64; SPECTRUM_BANDS]>::try_from(levels) else {
return;
};
self.last_frame = Some(at);
let bands = levels.map(|level| (level.clamp(0.0, 1.0) * 255.0).round() as u8);
self.frames.send_modify(|frame| {
frame.sequence = frame.sequence.wrapping_add(1);
frame.bands = Some(bands);
});
}
pub(crate) fn clear(&mut self) {
if self.last_frame.take().is_some() {
self.frames.send_modify(|frame| {
frame.epoch = frame.epoch.wrapping_add(1);
frame.sequence = frame.sequence.wrapping_add(1);
frame.bands = None;
});
}
}
}
pub(super) async fn next_frame(
subscription: &mut Option<watch::Receiver<Frame>>,
) -> Option<ServerMessage> {
let Some(receiver) = subscription else {
return std::future::pending().await;
};
receiver.changed().await.ok()?;
let frame = *receiver.borrow_and_update();
Some(ServerMessage::Spectrum {
epoch: frame.epoch,
sequence: frame.sequence,
bands: frame.bands,
})
}
+519
View File
@@ -0,0 +1,519 @@
use super::*;
#[test]
fn browser_handshakes_are_rejected_and_discovery_replaces_only_its_file() {
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
let request = Request::builder()
.header("Origin", "https://example.invalid")
.body(())
.unwrap();
assert!(native_handshake(&request, Response::new(())).is_err());
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("endpoint.json");
for port in [1234, 4567] {
write_discovery(
&path,
&Discovery {
api_version: API_VERSION,
port,
token: "private".into(),
},
)
.unwrap();
let read: Discovery = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(read.port, port);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
}
type TestConnection = (
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<TcpStream>>,
mpsc::Receiver<Queued>,
watch::Sender<Published>,
JoinHandle<()>,
);
async fn connect() -> TestConnection {
connect_with(art::Covers::with(|_, _| Box::pin(async { None }))).await
}
async fn connect_with(covers: Arc<art::Covers>) -> TestConnection {
connect_with_spectrum(covers, Spectrum::default().frames).await
}
async fn connect_with_spectrum(
covers: Arc<art::Covers>,
frames: watch::Sender<spectrum::Frame>,
) -> TestConnection {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
.await
.unwrap();
let port = listener.local_addr().unwrap().port();
let (state, receiver) = watch::channel(crate::app::control::published(
&crate::app::state::AppState::default(),
1,
));
let (commands, queue) = mpsc::channel(8);
let task = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
let _ = session(socket, "secret", receiver, commands, covers, frames).await;
});
let socket = tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{port}"))
.await
.unwrap()
.0;
(socket, queue, state, task)
}
#[tokio::test]
async fn authentication_required_and_wrong_tokens_cannot_dispatch() {
for token in ["wrong", ""] {
let (mut socket, mut queue, _state, task) = connect().await;
socket
.send(Message::Text(
serde_json::to_string(&ClientMessage::Authenticate {
token: token.into(),
api_version: API_VERSION,
})
.unwrap()
.into(),
))
.await
.unwrap();
task.await.unwrap();
assert!(queue.recv().await.is_none());
assert!(!matches!(socket.next().await, Some(Ok(Message::Text(_)))));
}
}
#[tokio::test]
async fn authenticated_session_streams_idle_state_and_routes_commands() {
let (mut socket, mut queue, state, task) = connect().await;
socket
.send(Message::Text(
serde_json::to_string(&ClientMessage::Authenticate {
token: "secret".into(),
api_version: API_VERSION,
})
.unwrap()
.into(),
))
.await
.unwrap();
let Message::Text(initial) = socket.next().await.unwrap().unwrap() else {
panic!()
};
let ServerMessage::Snapshot { snapshot } = serde_json::from_str(&initial).unwrap() else {
panic!()
};
assert!(!snapshot.playing);
assert_eq!(snapshot.devices.len(), 1);
let mut changed = state.borrow().clone();
changed.snapshot.revision = 2;
state.send_replace(changed);
let Message::Text(next) = socket.next().await.unwrap().unwrap() else {
panic!()
};
assert!(
matches!(serde_json::from_str::<ServerMessage>(&next).unwrap(), ServerMessage::Snapshot { snapshot } if snapshot.revision == 2)
);
socket
.send(Message::Text(
serde_json::to_string(&ClientMessage::Command {
id: "press-1".into(),
command: Command::VolumeUp,
})
.unwrap()
.into(),
))
.await
.unwrap();
let command = queue.recv().await.unwrap();
assert_eq!(command.command, Command::VolumeUp);
command
.reply
.send(ServerMessage::Result {
id: command.id,
accepted: true,
error: None,
})
.unwrap();
assert!(matches!(socket.next().await, Some(Ok(Message::Text(_)))));
task.abort();
}
#[tokio::test]
async fn repeated_ids_are_deduplicated_across_clients_and_payload_changes_rejected() {
let (commands, queue) = mpsc::channel(8);
let (events, mut event_rx) = mpsc::unbounded_channel();
let task = tokio::spawn(broker(queue, events));
let (tx, rx) = oneshot::channel();
commands
.send(Queued {
id: "one".into(),
command: Command::PlayPause,
reply: tx,
})
.await
.unwrap();
let crate::app::event::AppEvent::Control(event) = event_rx.recv().await.unwrap() else {
panic!()
};
event.reply.send(Ok(())).unwrap();
assert!(matches!(
rx.await.unwrap(),
ServerMessage::Result { accepted: true, .. }
));
for command in [Command::PlayPause, Command::Next] {
let expected = command == Command::PlayPause;
let (tx, rx) = oneshot::channel();
commands
.send(Queued {
id: "one".into(),
command,
reply: tx,
})
.await
.unwrap();
assert!(
matches!(rx.await.unwrap(), ServerMessage::Result { accepted, .. } if accepted == expected)
);
assert!(event_rx.try_recv().is_err());
}
task.abort();
}
#[tokio::test]
async fn artwork_references_never_accept_paths_from_clients() {
let (mut socket, _queue, _state, task) = connect().await;
for message in [
ClientMessage::Authenticate {
token: "secret".into(),
api_version: API_VERSION,
},
ClientMessage::Command {
id: "art".into(),
command: Command::Artwork {
artwork_id: "../../private-file".into(),
federation: true,
},
},
] {
socket
.send(Message::Text(
serde_json::to_string(&message).unwrap().into(),
))
.await
.unwrap();
}
socket.next().await.unwrap().unwrap();
let Message::Text(reply) = socket.next().await.unwrap().unwrap() else {
panic!()
};
assert!(matches!(
serde_json::from_str::<ServerMessage>(&reply).unwrap(),
ServerMessage::Result {
accepted: false,
..
}
));
task.abort();
}
#[test]
fn artwork_is_bounded_and_scaled_without_audio_or_user_files() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("cover.png");
image::RgbImage::from_pixel(4, 4, image::Rgb([10, 20, 30]))
.save(&path)
.unwrap();
let data = base64::engine::general_purpose::STANDARD
.decode(artwork(&path).unwrap())
.unwrap();
let decoded = image::load_from_memory(&data).unwrap();
assert_eq!((decoded.width(), decoded.height()), (384, 384));
}
#[tokio::test]
async fn slow_federated_art_is_opt_in_and_playback_commands_still_work() {
use furumi_control_protocol::Track;
let (lookup_tx, mut lookups) = mpsc::unbounded_channel();
let ready = Arc::new(tokio::sync::Notify::new());
let ready_worker = ready.clone();
let covers = art::Covers::with(move |_, federation| {
lookup_tx.send(federation).unwrap();
let ready = ready_worker.clone();
Box::pin(async move {
if !federation {
return None;
}
ready.notified().await;
Some("cG5n".into())
})
});
let (mut socket, mut commands, state, task) = connect_with(covers).await;
state.send_modify(|p| {
p.snapshot.track = Some(Track {
key: "song".into(),
title: "Song".into(),
artist: "Artist".into(),
album: "Album".into(),
year: None,
liked: None,
artwork_id: Some("cover".into()),
})
});
let auth = ClientMessage::Authenticate {
token: "secret".into(),
api_version: API_VERSION,
};
socket
.send(Message::text(serde_json::to_string(&auth).unwrap()))
.await
.unwrap();
socket.next().await.unwrap().unwrap();
assert!(lookups.try_recv().is_err());
let command = |id: &str, command| {
Message::text(
serde_json::to_string(&ClientMessage::Command {
id: id.into(),
command,
})
.unwrap(),
)
};
for allow in [false, true] {
socket
.send(command(
"art",
Command::Artwork {
artwork_id: "cover".into(),
federation: allow,
},
))
.await
.unwrap();
assert_eq!(lookups.recv().await, Some(allow));
if !allow {
let reply = socket.next().await.unwrap().unwrap().into_data();
assert!(matches!(
serde_json::from_slice(&reply).unwrap(),
ServerMessage::Artwork {
png_base64: None,
..
}
));
}
}
socket
.send(command("pause", Command::PlayPause))
.await
.unwrap();
let pending = tokio::time::timeout(Duration::from_secs(2), commands.recv())
.await
.unwrap()
.unwrap();
assert_eq!(pending.command, Command::PlayPause);
pending
.reply
.send(ServerMessage::Result {
id: pending.id,
accepted: true,
error: None,
})
.unwrap();
let reply = socket.next().await.unwrap().unwrap().into_data();
assert!(matches!(
serde_json::from_slice(&reply).unwrap(),
ServerMessage::Result { accepted: true, .. }
));
ready.notify_one();
let reply = socket.next().await.unwrap().unwrap().into_data();
assert!(matches!(
serde_json::from_slice(&reply).unwrap(),
ServerMessage::Artwork {
png_base64: Some(_),
..
}
));
task.abort();
}
#[tokio::test]
async fn simultaneous_cover_requests_share_the_fetch() {
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = Arc::new(AtomicUsize::new(0));
let count = calls.clone();
let covers = art::Covers::with(move |_, _| {
count.fetch_add(1, Ordering::Relaxed);
Box::pin(async {
tokio::task::yield_now().await;
Some("cover".into())
})
});
let fetch = || covers.get("album", art::Source::default(), true);
let (a, b) = tokio::join!(fetch(), fetch());
assert_eq!(a.as_deref(), Some("cover"));
assert_eq!(a, b);
assert_eq!(calls.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn spectrum_subscriptions_are_advertised_idempotent_and_connection_scoped() {
let mut spectrum = Spectrum::default();
let covers = art::Covers::with(|_, _| Box::pin(async { None }));
let (mut socket, _commands, _state, task) =
connect_with_spectrum(covers, spectrum.frames.clone()).await;
let auth = ClientMessage::Authenticate {
token: "secret".into(),
api_version: API_VERSION,
};
socket
.send(Message::text(serde_json::to_string(&auth).unwrap()))
.await
.unwrap();
let initial = socket.next().await.unwrap().unwrap().into_data();
let mut old_message: serde_json::Value = serde_json::from_slice(&initial).unwrap();
assert_eq!(
old_message["snapshot"]
.as_object_mut()
.unwrap()
.remove("spectrum_supported"),
Some(true.into())
);
assert!(
matches!(serde_json::from_value(old_message).unwrap(), ServerMessage::Snapshot { snapshot } if !snapshot.spectrum_supported)
);
let at = std::time::Instant::now();
spectrum.sample(at, &[1.0; 31]);
assert_eq!(spectrum.frames.receiver_count(), 0);
for (index, enabled) in [true, true, false, true].into_iter().enumerate() {
let subscribe = ClientMessage::SubscribeSpectrum { enabled };
socket
.send(Message::text(serde_json::to_string(&subscribe).unwrap()))
.await
.unwrap();
// A pong is a barrier on the socket following this subscription change.
socket
.send(Message::Ping(vec![index as u8].into()))
.await
.unwrap();
assert!(matches!(
socket.next().await.unwrap().unwrap(),
Message::Pong(_)
));
assert_eq!(spectrum.frames.receiver_count(), usize::from(enabled));
spectrum.sample(at + Duration::from_secs(index as u64), &[0.5; 31]);
if enabled {
let message = tokio::time::timeout(Duration::from_secs(2), socket.next())
.await
.unwrap()
.unwrap()
.unwrap()
.into_data();
assert!(matches!(serde_json::from_slice(&message).unwrap(),
ServerMessage::Spectrum { bands: Some(bands), .. } if bands == [128; 31]));
}
}
socket.close(None).await.unwrap();
task.await.unwrap();
assert_eq!(spectrum.frames.receiver_count(), 0);
}
#[tokio::test]
async fn waterfall_uses_fresh_local_audio_and_clears_history_across_discontinuities() {
use crate::app::{
control::publish_spectrum,
state::{AppState, DevicePlaybackRole},
};
use std::time::Instant;
let mut spectrum = Spectrum::default();
let mut subscription = Some(spectrum.frames.subscribe());
let mut state = AppState::default();
state.player.current = Some(crate::app::podcast_fixtures::episode_track(1));
state.player.playing = true;
state.player.audio_analysis.spectrum = (0..31).map(|i| f64::from(i) / 30.0).collect();
let at = Instant::now();
publish_spectrum(&mut spectrum, &state, Some(at), false, true);
let Some(ServerMessage::Spectrum {
epoch,
sequence: 1,
bands: Some(first),
}) = spectrum::next_frame(&mut subscription).await
else {
panic!()
};
assert_eq!((first[0], first[15], first[30]), (0, 128, 255));
publish_spectrum(
&mut spectrum,
&state,
Some(at + Duration::from_millis(50)),
false,
true,
);
assert!(!subscription.as_ref().unwrap().has_changed().unwrap());
state.player.paused = true;
publish_spectrum(
&mut spectrum,
&state,
Some(at + Duration::from_secs(1)),
false,
false,
);
assert!(!subscription.as_ref().unwrap().has_changed().unwrap());
state.player.paused = false;
publish_spectrum(
&mut spectrum,
&state,
Some(at + Duration::from_secs(2)),
false,
false,
);
assert!(!subscription.as_ref().unwrap().has_changed().unwrap());
state.device_playback.role = DevicePlaybackRole::Control;
publish_spectrum(&mut spectrum, &state, None, false, true);
assert!(
matches!(spectrum::next_frame(&mut subscription).await, Some(ServerMessage::Spectrum { epoch: next, bands: None, .. }) if next != epoch)
);
state.device_playback.role = DevicePlaybackRole::Jam;
publish_spectrum(
&mut spectrum,
&state,
Some(at + Duration::from_secs(3)),
false,
true,
);
assert!(!subscription.as_ref().unwrap().has_changed().unwrap());
state.device_playback.jam_host = true;
publish_spectrum(
&mut spectrum,
&state,
Some(at + Duration::from_secs(4)),
false,
true,
);
// A slow reader that misses the clear still sees the new epoch on the next sample.
spectrum.clear();
publish_spectrum(
&mut spectrum,
&state,
Some(at + Duration::from_secs(5)),
false,
true,
);
assert!(
matches!(spectrum::next_frame(&mut subscription).await, Some(ServerMessage::Spectrum { epoch: next, bands: Some(_), .. }) if next == epoch + 2)
);
publish_spectrum(&mut spectrum, &state, None, true, true);
assert!(matches!(
spectrum::next_frame(&mut subscription).await,
Some(ServerMessage::Spectrum { bands: None, .. })
));
}
+18 -12
View File
@@ -459,8 +459,6 @@ fn queued_command_loses_its_fence_when_another_owner_wins() {
static NEXT_TEST_DB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn test_sync() -> DeviceSync {
let conn = Connection::open_in_memory().unwrap();
init_schema(&conn).unwrap();
let unique = NEXT_TEST_DB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let library_path = std::env::temp_dir().join(format!(
"furumi-devices-test-{}-{}-{}.sqlite3",
@@ -468,16 +466,24 @@ fn test_sync() -> DeviceSync {
now_ms(),
unique
));
let sync = DeviceSync {
_identity_lock: None,
conn: Arc::new(std::sync::Mutex::new(conn)),
library: Arc::new(Library::open(&library_path).unwrap()),
event_tx: Arc::new(std::sync::Mutex::new(None)),
playback: Arc::new(std::sync::Mutex::new(PlaybackShared::default())),
podcasts: Default::default(),
};
sync.ensure_identity().unwrap();
sync
DeviceSync::with_test_library(Arc::new(Library::open(&library_path).unwrap()))
}
impl DeviceSync {
pub(crate) fn with_test_library(library: Arc<Library>) -> Self {
let conn = Connection::open_in_memory().unwrap();
init_schema(&conn).unwrap();
let sync = Self {
_identity_lock: None,
conn: Arc::new(std::sync::Mutex::new(conn)),
library,
event_tx: Default::default(),
playback: Default::default(),
podcasts: Default::default(),
};
sync.ensure_identity().unwrap();
sync
}
}
#[test]
+5 -1
View File
@@ -67,7 +67,11 @@ pub struct ObservedVersions {
/// peers never dial an overlay that failed to open here.
fn local_manifest(podcast_dht: bool) -> CapabilityManifest {
let manifest = CapabilityManifest::frid("furumi", env!("CARGO_PKG_VERSION"))
.with_protocol("audio", super::audio::AUDIO_PROTOCOL_VERSION);
.with_protocol("audio", super::audio::AUDIO_PROTOCOL_VERSION)
.with_protocol(
music_dht::lyrics::LYRICS_ID,
music_dht::lyrics::LYRICS_PROTOCOL_VERSION,
);
if podcast_dht {
manifest.with_podcast_dht()
} else {
+281
View File
@@ -0,0 +1,281 @@
//! Optional lyrics streams use audio content identities, independent of the catalog schema.
use super::Federation;
use crate::library::Library;
use anyhow::{Context, Result};
use futures_util::{StreamExt, stream};
use music_dht::lyrics::{self, LyricsRequest, LyricsResponse, LyricsVersion};
use music_dht::{ByteStream, EndpointId, MusicDhtService, StreamAcceptor};
use std::{collections::HashSet, sync::Arc, time::Duration};
const PEER_TIMEOUT: Duration = Duration::from_secs(6);
impl Federation {
pub(crate) async fn find_lyrics(
&self,
content_id: &str,
preferred: Option<&str>,
mut on_versions: impl FnMut(Vec<LyricsVersion>),
) -> Result<()> {
let request = LyricsRequest::new(content_id)?;
let service = self.service().await?;
let own = service.endpoint_id();
// Start with the audio source while content discovery looks for other copies.
let preferred = preferred
.and_then(|id| id.parse::<EndpointId>().ok())
.filter(|id| *id != own);
let direct = async {
if let Some(peer) = preferred {
fetch(&service, peer, &request).await.ok()
} else {
None
}
};
let discovery = tokio::time::timeout(PEER_TIMEOUT, service.search_content_id(content_id));
tokio::pin!(direct, discovery);
let found = tokio::select! {
result = &mut direct => {
if let Some(versions) = result {
on_versions(versions);
}
discovery.await
}
result = &mut discovery => {
if let Some(versions) = direct.await {
on_versions(versions);
}
result
}
};
let mut seen = HashSet::from([own]);
seen.extend(preferred);
let owners = found
.ok()
.and_then(Result::ok)
.into_iter()
.flat_map(|outcome| {
outcome
.local_results
.into_iter()
.chain(outcome.network_results)
})
.filter(|item| {
item.kind == music_dht::ItemKind::Track
&& item.content_id.as_deref() == Some(content_id)
})
.map(|item| item.owner);
// Connected peers can also have newly stored copies that aren't indexed yet.
let candidates = owners
.chain(service.connected_peers())
.filter(|peer| seen.insert(*peer))
.take(16);
let mut responses = stream::iter(candidates)
.map(|peer| fetch(&service, peer, &request))
.buffer_unordered(6);
while let Some(result) = responses.next().await {
match result {
Ok(versions) => on_versions(versions),
Err(error) => {
tracing::trace!(error = %format!("{error:#}"), "peer lyrics unavailable")
}
}
}
Ok(())
}
}
async fn fetch(
service: &MusicDhtService,
peer: EndpointId,
request: &LyricsRequest,
) -> Result<Vec<LyricsVersion>> {
tokio::time::timeout(PEER_TIMEOUT, async {
let mut retried = false;
loop {
let mut stream = service
.open_stream(peer, lyrics::LYRICS_ALPN)
.await
.context("opening peer lyrics stream")?;
lyrics::write_request(&mut stream, request).await?;
stream.send.finish()?;
match lyrics::read_response_from(&mut stream.recv).await {
Ok(response) => {
anyhow::ensure!(
response.content_id == request.content_id,
"lyrics response content identity mismatch"
);
return Ok(response.versions);
}
Err(music_dht::MusicDhtError::Network(_)) if !retried => retried = true,
Err(error) => return Err(error).context("reading peer lyrics response"),
}
}
})
.await?
}
pub(super) async fn serve(mut acceptor: StreamAcceptor, library: Arc<Library>) {
let limit = Arc::new(tokio::sync::Semaphore::new(16));
while let Some(stream) = acceptor.accept().await {
let Ok(permit) = Arc::clone(&limit).try_acquire_owned() else {
continue;
};
let library = Arc::clone(&library);
tokio::spawn(async move {
let _permit = permit;
match tokio::time::timeout(Duration::from_secs(12), serve_one(stream, library)).await {
Ok(Ok(())) => {}
Ok(Err(error)) => tracing::debug!(%error, "could not serve lyrics"),
Err(_) => tracing::debug!("lyrics stream timed out"),
}
});
}
}
async fn serve_one(mut stream: ByteStream, library: Arc<Library>) -> Result<()> {
let request = lyrics::read_request_from(&mut stream.recv).await?;
let content_id = request.content_id.clone();
let versions = tokio::task::spawn_blocking(move || -> Result<_> {
let local = library.track_by_content_id(&content_id)?;
if local.is_some_and(|track| std::path::Path::new(&track.file_path).is_file()) {
Ok(library.lyrics(&content_id)?.versions)
} else {
Ok(Vec::new())
}
})
.await??;
// JSON can be larger than the stored UTF-8 text because of escapes.
let mut response = LyricsResponse {
version: lyrics::LYRICS_PROTOCOL_VERSION,
content_id: request.content_id,
versions,
};
// Leave space for the bounded envelope and the comma before each entry.
let mut remaining = lyrics::MAX_LYRICS_RESPONSE_BYTES - 256;
response.versions.retain(|version| {
let Ok(encoded) = serde_json::to_vec(version) else {
return false;
};
let Some(rest) = remaining.checked_sub(encoded.len() + 1) else {
return false;
};
remaining = rest;
true
});
lyrics::write_response(&mut stream, &response).await?;
stream.send.finish()?;
// ByteStream also owns its connection. Keep it alive through FIN delivery.
let _ = tokio::time::timeout(Duration::from_secs(2), stream.send.stopped()).await;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::library::import::{TrackImport, upsert_track};
use music_dht::{MusicDhtConfig, NetworkId};
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn localhost_lyrics_stream_serves_only_saved_content_and_all_versions() {
let temp = tempfile::tempdir().unwrap();
let network = NetworkId::from_name(&format!("lyrics-test-{}", temp.path().display()));
let start = |name| {
let dir = temp.path().join(name);
async move {
std::fs::create_dir_all(&dir).unwrap();
let (service, mut events) = MusicDhtService::start(
MusicDhtConfig::builder()
.data_dir(dir)
.network_id(network)
.schema_independent_stream_protocol(lyrics::LYRICS_ALPN)
.build()
.unwrap(),
)
.await
.unwrap();
tokio::spawn(async move { while events.recv().await.is_some() {} });
service
}
};
let (server, client) = tokio::join!(start("server"), start("client"));
let library = Arc::new(Library::open(&temp.path().join("library.db")).unwrap());
let path = temp.path().join("track.flac");
std::fs::write(&path, b"immutable music bytes").unwrap();
let track_id = upsert_track(
&library,
&TrackImport {
file_path: path.to_string_lossy().into_owned(),
title: "Track".into(),
artists: vec!["Artist".into()],
album_artists: vec!["Artist".into()],
featured_artists: vec![],
release_title: "Release".into(),
release_type: None,
year: None,
track_number: None,
disc_number: None,
duration_seconds: 5.0,
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
cover: None,
},
)
.unwrap()
.0;
let id = library.track_content_id_by_id(track_id).unwrap().unwrap();
library
.edit_lyrics(
track_id,
&id,
None,
Some(crate::lyrics::manual_version("Plain", "Words").unwrap()),
)
.unwrap();
library
.edit_lyrics(
track_id,
&id,
None,
Some(crate::lyrics::manual_version("Timed", "[00:01]Words").unwrap()),
)
.unwrap();
let task = tokio::spawn(serve(
server.stream_acceptor(lyrics::LYRICS_ALPN).unwrap(),
library,
));
client
.connect(server.ticket().await.unwrap())
.await
.unwrap();
let versions = fetch(
&client,
server.endpoint_id(),
&LyricsRequest::new(&id).unwrap(),
)
.await
.unwrap();
assert_eq!(versions.len(), 2);
assert_eq!(versions[0].synced_lrc.as_deref(), Some("[00:01]Words"));
assert_eq!(versions[1].plain_text.as_deref(), Some("Words"));
std::fs::remove_file(path).unwrap();
assert!(
fetch(
&client,
server.endpoint_id(),
&LyricsRequest::new(id).unwrap()
)
.await
.unwrap()
.is_empty()
);
task.abort();
server.shutdown().await.unwrap();
client.shutdown().await.unwrap();
}
}
+19 -2
View File
@@ -15,6 +15,7 @@
mod audio;
mod capabilities;
pub mod catalog;
mod lyrics;
mod similarity;
use std::collections::{HashMap, VecDeque};
@@ -780,6 +781,7 @@ impl Federation {
.schema_independent_stream_protocol(PODCAST_DHT_ALPN)
// Informational application/protocol versions.
.schema_independent_stream_protocol(capabilities::CAPABILITIES_ALPN)
.schema_independent_stream_protocol(music_dht::lyrics::LYRICS_ALPN)
.build()
.map_err(|err| anyhow::anyhow!("invalid federation config: {err}"))?;
let (service, mut events) = MusicDhtService::start(config)
@@ -905,11 +907,15 @@ impl Federation {
podcast_dht.clone(),
));
let lyrics_acceptor = service.stream_acceptor(music_dht::lyrics::LYRICS_ALPN)?;
let lyrics_task = tokio::spawn(lyrics::serve(lyrics_acceptor, Arc::clone(&self.library)));
let mut tasks = podcast_dht_tasks;
tasks.extend([
event_task,
sync_task,
audio_task,
lyrics_task,
catalog_task,
similarity_task,
device_sync_task,
@@ -1725,7 +1731,6 @@ impl Federation {
}
}
let service = self.service().await.ok()?;
tokio::fs::create_dir_all(&dir).await.ok()?;
for owner in owners {
let Ok(owner) = EndpointId::from_str(owner) else {
continue;
@@ -1738,7 +1743,19 @@ impl Federation {
match fetched {
Ok(Ok(Some((bytes, extension)))) => {
let path = dir.join(format!("{stem}.{extension}"));
if tokio::fs::write(&path, &bytes).await.is_ok() {
// A cancelled on-demand lookup must never leave a partial
// file that the next lookup would accept as cached art.
let stored = tokio::task::spawn_blocking(move || -> std::io::Result<_> {
use std::io::Write as _;
let parent = path.parent().expect("cover has a directory");
std::fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
file.write_all(&bytes)?;
file.persist(&path).map_err(|e| e.error)?;
Ok(path)
})
.await;
if let Ok(Ok(path)) = stored {
return Some(path.to_string_lossy().into_owned());
}
}
+183
View File
@@ -0,0 +1,183 @@
//! Content-addressed lyrics and the playback timeline shared by the UI and scripts.
pub(crate) use crate::library::lyrics::{SavedLyrics, identity, merge};
use music_dht::lyrics::LyricsVersion;
pub(crate) fn clean_text(text: &str) -> String {
text.replace("\r\n", "\n")
.replace('\r', "\n")
.chars()
.filter_map(|c| match c {
'\t' => Some(' '),
'\n' => Some('\n'),
c if !c.is_control() => Some(c),
_ => None,
})
.collect()
}
#[derive(Debug, Default)]
pub(crate) struct Document {
pub lines: Vec<String>,
times: Vec<u64>,
pub instrumental: bool,
}
impl Document {
pub fn new(version: &LyricsVersion) -> Self {
let timed = version
.synced_lrc
.as_deref()
.map(parse_lrc)
.unwrap_or_default();
let (mut times, lines): (Vec<_>, Vec<_>) = timed.into_iter().unzip();
let lines = if times.is_empty() {
let text = version
.plain_text
.as_deref()
.or(version.synced_lrc.as_deref());
text.map(clean_text)
.map(|text| text.lines().map(str::to_owned).collect())
.unwrap_or_default()
} else {
// Some LRC releases split a duet over two lines with the same timestamp.
let mut combined: Vec<String> = Vec::new();
let mut previous = None;
let mut keep = Vec::new();
for (time, line) in times.into_iter().zip(lines) {
if previous == Some(time) {
if let Some(last) = combined.last_mut() {
last.push_str(" / ");
last.push_str(&line);
}
} else {
keep.push(time);
combined.push(line);
previous = Some(time);
}
}
times = keep;
combined
};
Self {
lines,
times,
instrumental: version.instrumental,
}
}
pub fn timed(&self) -> bool {
!self.times.is_empty()
}
pub fn line_at(&self, position: f64) -> Option<usize> {
let millis = (position * 1000.0) as u64;
self.times
.partition_point(|&time| time <= millis)
.checked_sub(1)
}
pub fn time(&self, index: usize) -> Option<f64> {
self.times.get(index).map(|&time| time as f64 / 1000.0)
}
}
fn parse_lrc(value: &str) -> Vec<(u64, String)> {
let offset = value
.lines()
.find_map(|line| {
line.trim()
.trim_start_matches('\u{feff}')
.strip_prefix("[offset:")?
.strip_suffix(']')?
.trim()
.parse::<i64>()
.ok()
})
.unwrap_or_default()
.clamp(-3_600_000, 3_600_000);
let mut lines = Vec::new();
for line in value.lines() {
let mut rest = line.trim().trim_start_matches('\u{feff}');
let mut times = Vec::new();
while let Some((tag, tail)) = rest.strip_prefix('[').and_then(|s| s.split_once(']')) {
let Some((minutes, seconds)) = tag.split_once(':') else {
break;
};
let (Ok(minutes), Ok(seconds)) = (minutes.parse::<u32>(), seconds.parse::<f64>())
else {
break;
};
if minutes > 1440 || !(0.0..60.0).contains(&seconds) {
break;
}
let ms = ((f64::from(minutes) * 60.0 + seconds) * 1000.0).round() as i64;
times.push((ms + offset).max(0) as u64);
rest = tail;
}
if !times.is_empty() {
let line = clean_text(rest.trim());
lines.extend(times.into_iter().map(|time| (time, line.clone())));
}
}
lines.sort_by_key(|(time, _)| *time);
lines
}
pub(crate) fn manual_version(label: &str, text: &str) -> anyhow::Result<LyricsVersion> {
let label = clean_text(label);
let text = clean_text(text);
anyhow::ensure!(
!text.trim().is_empty() && text.len() <= music_dht::lyrics::MAX_LYRICS_TEXT_BYTES,
"Enter lyrics up to 256 KiB"
);
let timed = !parse_lrc(&text).is_empty();
let mut version = LyricsVersion {
id: "manual".into(),
label: if label.trim().is_empty() {
"Manual".into()
} else {
label.trim().into()
},
source: "manual".into(),
source_id: None,
language: None,
plain_text: (!timed).then(|| text.clone()),
synced_lrc: timed.then_some(text),
instrumental: false,
};
version.id = identity(&version);
version.validate()?;
Ok(version)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn lrc_handles_offsets_repeated_timestamps_and_seeks() {
let version = manual_version(
"Duet",
"[offset:-500]\n[00:02][00:08]Hello\n[00:02]Hi\n[00:04.25]\n[00:05]Bye",
)
.unwrap();
let doc = Document::new(&version);
assert_eq!(doc.lines, ["Hello / Hi", "", "Bye", "Hello"]);
assert_eq!(doc.line_at(1.49), None);
assert_eq!(doc.line_at(1.5), Some(0));
assert_eq!(doc.line_at(8.0), Some(3));
assert_eq!(doc.line_at(3.8), Some(1));
}
#[test]
fn versions_are_deduplicated_by_representations() {
let first = manual_version("One", "Words").unwrap();
let second = manual_version("Another label", "Words").unwrap();
let timed = manual_version("Timed", "[00:01]Words").unwrap();
let mut versions = vec![first.clone()];
merge(&mut versions, [second, timed], &HashSet::new());
assert_eq!(versions.len(), 2);
assert_eq!(versions[0], first);
}
}
+15
View File
@@ -1,10 +1,12 @@
mod app;
mod art;
mod config;
mod control;
mod devices;
mod federation;
mod jam;
mod library;
mod lyrics;
mod media;
mod player;
mod podcasts;
@@ -29,6 +31,8 @@ Furumi — federated terminal music player
Usage:
furumi [OPTION]
furumi ctl <status|devices|watch|play-pause|next|previous|seek|volume-up|volume-down|transfer|shuffle|repeat|radio> [ARG]
furumi ctl artwork [--federation] [--output FILE.png]
Options:
-h, --help Show this help
@@ -43,6 +47,17 @@ tmux:
fn main() -> Result<()> {
let args: Vec<_> = std::env::args_os().collect();
if args.get(1).is_some_and(|arg| arg == "ctl") {
let args: Vec<_> = args
.iter()
.skip(2)
.map(|arg| arg.to_string_lossy().into_owned())
.collect();
return tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(control::cli(&args));
}
if args.iter().any(|arg| arg == "--help" || arg == "-h") {
print!("{HELP}");
return Ok(());
+265 -15
View File
@@ -1,10 +1,12 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicI16, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use rodio::source::SeekError;
use rodio::{ChannelCount, Sample, SampleRate, Source};
use super::spectrum::{Meter, PCM_SAMPLES, StereoReading};
const LEVEL_SCALE: f32 = 1_000_000.0;
const SCOPE_SAMPLES: usize = 256;
const SCOPE_SAMPLE_SCALE: f32 = i16::MAX as f32;
@@ -20,6 +22,26 @@ pub struct AudioAnalysisSnapshot {
pub treble: f64,
pub beat: f64,
pub scope: Vec<f64>,
/// Third-octave band levels (see `spectrum::BAND_CENTERS_HZ`), 0.0..1.0
/// over `spectrum::FLOOR_DB`..0 dBFS, with analyzer ballistics.
pub spectrum: Vec<f64>,
/// Per-band peak-hold markers on the same scale as `spectrum`.
pub spectrum_peaks: Vec<f64>,
/// Left/right RMS levels and held sample peaks on the same dB scale.
/// Mono sources report the same value for both channels.
pub level_l: f64,
pub level_r: f64,
pub peak_l: f64,
pub peak_r: f64,
/// RMS of the side signal (L - R) / 2 on the same scale: the floor for
/// mono sources and for stereo files that carry the same signal twice.
pub level_side: f64,
/// Whether the channels carry different signals: decided on loud windows
/// only (side within 30 dB of the louder channel), `None` until then.
pub stereo: Option<bool>,
/// Sample rate of the analyzed stream in Hz (0 when nothing has played
/// since the player last stopped).
pub sample_rate: u32,
}
#[derive(Debug)]
@@ -32,6 +54,20 @@ pub struct AnalyzerShared {
beat: AtomicU32,
scope_write: AtomicUsize,
scope: Box<[AtomicI16]>,
/// Full-rate mono history for the spectrum; written by the audio thread.
pcm_write: AtomicUsize,
pcm: Box<[AtomicI16]>,
sample_rate: AtomicU32,
/// Per-window channel levels (linear, `LEVEL_SCALE`). Peaks accumulate
/// with `fetch_max` until the meter consumes them.
rms_l: AtomicU32,
rms_r: AtomicU32,
rms_side: AtomicU32,
peak_l: AtomicU32,
peak_r: AtomicU32,
/// Ballistics and FFT state. Only snapshot readers (the UI side) lock it;
/// the audio thread never does.
meter: Mutex<Meter>,
}
impl Default for AnalyzerShared {
@@ -44,14 +80,27 @@ impl Default for AnalyzerShared {
treble: AtomicU32::new(0),
beat: AtomicU32::new(0),
scope_write: AtomicUsize::new(0),
scope: (0..SCOPE_SAMPLES)
.map(|_| AtomicI16::new(0))
.collect::<Vec<_>>()
.into_boxed_slice(),
scope: atomic_ring(SCOPE_SAMPLES),
pcm_write: AtomicUsize::new(0),
pcm: atomic_ring(PCM_SAMPLES),
sample_rate: AtomicU32::new(0),
rms_l: AtomicU32::new(0),
rms_r: AtomicU32::new(0),
rms_side: AtomicU32::new(0),
peak_l: AtomicU32::new(0),
peak_r: AtomicU32::new(0),
meter: Mutex::new(Meter::default()),
}
}
}
fn atomic_ring(len: usize) -> Box<[AtomicI16]> {
(0..len)
.map(|_| AtomicI16::new(0))
.collect::<Vec<_>>()
.into_boxed_slice()
}
impl AnalyzerShared {
pub fn clear(&self) {
self.energy.store(0, Ordering::Relaxed);
@@ -63,10 +112,37 @@ impl AnalyzerShared {
for sample in self.scope.iter() {
sample.store(0, Ordering::Relaxed);
}
self.pcm_write.store(0, Ordering::Relaxed);
for sample in self.pcm.iter() {
sample.store(0, Ordering::Relaxed);
}
for level in [
&self.rms_l,
&self.rms_r,
&self.rms_side,
&self.peak_l,
&self.peak_r,
] {
level.store(0, Ordering::Relaxed);
}
self.sequence.store(0, Ordering::Relaxed);
}
/// Like [`Self::clear`], and also forgets the sample rate: nothing is
/// loaded any more.
pub fn reset(&self) {
self.clear();
self.sample_rate.store(0, Ordering::Relaxed);
}
pub fn snapshot(&self) -> AudioAnalysisSnapshot {
self.snapshot_at(Instant::now())
}
/// Like [`Self::snapshot`] with an explicit clock, so meter ballistics are
/// deterministic in tests. Ballistics are time-based: how often callers
/// read does not change how fast bars rise or fall.
pub fn snapshot_at(&self, now: Instant) -> AudioAnalysisSnapshot {
let write = self.scope_write.load(Ordering::Relaxed);
let len = self.scope.len().max(1);
let scope = (0..self.scope.len())
@@ -76,6 +152,25 @@ impl AnalyzerShared {
})
.collect();
let sample_rate = self.sample_rate.load(Ordering::Relaxed);
let pcm_write = self.pcm_write.load(Ordering::Relaxed);
let stereo = StereoReading {
rms_l: load_norm(&self.rms_l) as f32,
rms_r: load_norm(&self.rms_r) as f32,
rms_side: load_norm(&self.rms_side) as f32,
peak_l: f64::from(self.peak_l.swap(0, Ordering::Relaxed)) as f32 / LEVEL_SCALE,
peak_r: f64::from(self.peak_r.swap(0, Ordering::Relaxed)) as f32 / LEVEL_SCALE,
};
let reading = {
let mut meter = self
.meter
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
meter.update(now, pcm_write, sample_rate, stereo, |out| {
self.copy_pcm(pcm_write, out)
})
};
AudioAnalysisSnapshot {
sequence: self.sequence.load(Ordering::Relaxed),
energy: load_norm(&self.energy),
@@ -84,6 +179,31 @@ impl AnalyzerShared {
treble: load_norm(&self.treble),
beat: load_norm(&self.beat),
scope,
spectrum: reading.spectrum,
spectrum_peaks: reading.spectrum_peaks,
level_l: reading.level_l,
level_r: reading.level_r,
peak_l: reading.peak_l,
peak_r: reading.peak_r,
level_side: reading.level_side,
stereo: reading.stereo,
sample_rate,
}
}
/// Copies the newest `out.len()` mono samples, oldest first. Slots not
/// written since the last clear read as silence.
fn copy_pcm(&self, write: usize, out: &mut [f32]) {
let len = self.pcm.len();
let count = out.len().min(len);
let start = write.wrapping_sub(count);
for (offset, slot) in out.iter_mut().enumerate() {
*slot = if offset < count && write >= count - offset {
let index = start.wrapping_add(offset) % len;
f32::from(self.pcm[index].load(Ordering::Relaxed)) / SCOPE_SAMPLE_SCALE
} else {
0.0
};
}
}
@@ -96,6 +216,22 @@ impl AnalyzerShared {
self.sequence.fetch_add(1, Ordering::Relaxed);
}
fn push_pcm(&self, sample: f32) {
let index = self.pcm_write.fetch_add(1, Ordering::Relaxed) % self.pcm.len();
let value = (sample.clamp(-1.0, 1.0) * SCOPE_SAMPLE_SCALE).round() as i16;
self.pcm[index].store(value, Ordering::Relaxed);
}
fn store_channels(&self, sample_rate: f32, rms: [f32; 3], peak: [f32; 2]) {
self.sample_rate
.store(sample_rate.round() as u32, Ordering::Relaxed);
store_norm(&self.rms_l, rms[0]);
store_norm(&self.rms_r, rms[1]);
store_norm(&self.rms_side, rms[2]);
self.peak_l.fetch_max(norm_bits(peak[0]), Ordering::Relaxed);
self.peak_r.fetch_max(norm_bits(peak[1]), Ordering::Relaxed);
}
fn push_scope(&self, sample: f32) {
let index = self.scope_write.fetch_add(1, Ordering::Relaxed) % self.scope.len();
let value = (sample.clamp(-1.0, 1.0) * SCOPE_SAMPLE_SCALE).round() as i16;
@@ -181,6 +317,12 @@ struct AnalyzerState {
mid_alpha: f32,
channel_index: usize,
frame_sum: f32,
/// Left/right of the current frame (mono feeds both).
frame_lr: [f32; 2],
channel_sq: [f32; 2],
/// Sum of squared side samples (L - R) / 2 in the current window.
side_sq: f32,
channel_peak: [f32; 2],
frame_count: usize,
window_frames: usize,
scope_counter: usize,
@@ -208,6 +350,10 @@ impl AnalyzerState {
mid_alpha: 0.0,
channel_index: 0,
frame_sum: 0.0,
frame_lr: [0.0; 2],
channel_sq: [0.0; 2],
side_sq: 0.0,
channel_peak: [0.0; 2],
frame_count: 0,
window_frames: 0,
scope_counter: 0,
@@ -252,6 +398,10 @@ impl AnalyzerState {
fn reset_filters(&mut self) {
self.channel_index = 0;
self.frame_sum = 0.0;
self.frame_lr = [0.0; 2];
self.channel_sq = [0.0; 2];
self.side_sq = 0.0;
self.channel_peak = [0.0; 2];
self.frame_count = 0;
self.scope_counter = 0;
self.low_bass = 0.0;
@@ -275,10 +425,23 @@ impl AnalyzerState {
0.0
};
self.frame_sum += sample;
// First channel is left, second right; extra channels only feed mono.
if self.channel_index < 2 {
self.frame_lr[self.channel_index] = sample;
}
self.channel_index += 1;
if self.channel_index < self.channels {
return;
}
if self.channels == 1 {
self.frame_lr[1] = self.frame_lr[0];
}
for (channel, value) in self.frame_lr.iter().enumerate() {
self.channel_sq[channel] += value * value;
self.channel_peak[channel] = self.channel_peak[channel].max(value.abs());
}
let side = (self.frame_lr[0] - self.frame_lr[1]) * 0.5;
self.side_sq += side * side;
let mono = self.frame_sum / self.channels as f32;
self.channel_index = 0;
@@ -299,6 +462,7 @@ impl AnalyzerState {
self.mid_sq += mid * mid;
self.treble_sq += treble * treble;
self.frame_count += 1;
shared.push_pcm(sample);
self.scope_counter += 1;
if self.scope_counter >= self.scope_stride {
@@ -339,10 +503,23 @@ impl AnalyzerState {
self.smooth_beat,
);
shared.store_channels(
self.sample_rate,
[
(self.channel_sq[0] / frames).sqrt(),
(self.channel_sq[1] / frames).sqrt(),
(self.side_sq / frames).sqrt(),
],
self.channel_peak,
);
self.full_sq = 0.0;
self.bass_sq = 0.0;
self.mid_sq = 0.0;
self.treble_sq = 0.0;
self.channel_sq = [0.0; 2];
self.side_sq = 0.0;
self.channel_peak = [0.0; 2];
self.frame_count = 0;
}
}
@@ -361,10 +538,11 @@ fn smooth_level(previous: f32, next: f32, attack: f32, release: f32) -> f32 {
}
fn store_norm(target: &AtomicU32, value: f32) {
target.store(
(value.clamp(0.0, 1.0) * LEVEL_SCALE).round() as u32,
Ordering::Relaxed,
);
target.store(norm_bits(value), Ordering::Relaxed);
}
fn norm_bits(value: f32) -> u32 {
(value.clamp(0.0, 1.0) * LEVEL_SCALE).round() as u32
}
fn load_norm(source: &AtomicU32) -> f64 {
@@ -384,19 +562,24 @@ mod tests {
impl TestSource {
fn sine(frames: usize, channels: u16, sample_rate: u32, frequency: f32) -> Self {
let channels_count = channels.max(1);
let mut samples = Vec::with_capacity(frames * usize::from(channels_count));
let gains = vec![1.0; usize::from(channels.max(1))];
Self::sine_gains(frames, sample_rate, frequency, &gains)
}
/// A sine with a gain per channel (one entry per channel).
fn sine_gains(frames: usize, sample_rate: u32, frequency: f32, gains: &[f32]) -> Self {
let mut samples = Vec::with_capacity(frames * gains.len());
for frame in 0..frames {
let time = frame as f32 / sample_rate as f32;
let sample = (std::f32::consts::TAU * frequency * time).sin() * 0.5;
for _ in 0..channels_count {
samples.push(sample as Sample);
for gain in gains {
samples.push((sample * gain) as Sample);
}
}
Self {
samples,
cursor: 0,
channels: ChannelCount::new(channels_count).unwrap(),
channels: ChannelCount::new(u16::try_from(gains.len()).unwrap()).unwrap(),
sample_rate: SampleRate::new(sample_rate).unwrap(),
}
}
@@ -452,4 +635,71 @@ mod tests {
assert!(snapshot.bass > 0.0);
assert!(snapshot.scope.iter().any(|sample| sample.abs() > 0.001));
}
#[test]
fn analyzed_source_feeds_the_spectrum_and_channel_meters() {
let shared = Arc::new(AnalyzerShared::default());
let source = TestSource::sine(48_000, 2, 48_000, 1_000.0);
let analyzed = AnalyzedSource::new(source, Arc::clone(&shared));
for _ in analyzed {}
let snapshot = shared.snapshot();
assert_eq!(snapshot.sample_rate, 48_000);
let bands = crate::player::BAND_CENTERS_HZ;
let at_1k = bands.iter().position(|hz| *hz == 1_000.0).unwrap();
let loudest = snapshot
.spectrum
.iter()
.enumerate()
.max_by(|left, right| left.1.total_cmp(right.1))
.map(|(index, _)| index);
assert_eq!(loudest, Some(at_1k));
assert!(snapshot.level_l > 0.5 && (snapshot.level_l - snapshot.level_r).abs() < 1e-6);
// the same signal in both channels has no side component
assert_eq!(snapshot.level_side, 0.0);
assert_eq!(snapshot.stereo, Some(false));
assert!(snapshot.peak_l >= snapshot.level_l);
}
#[test]
fn analyzed_source_measures_the_side_signal() {
let measure = |gains: &[f32]| {
let shared = Arc::new(AnalyzerShared::default());
let source = TestSource::sine_gains(48_000, 48_000, 1_000.0, gains);
for _ in AnalyzedSource::new(source, Arc::clone(&shared)) {}
shared.snapshot()
};
// R = -L: the side signal (L - R) / 2 equals L
let opposite = measure(&[1.0, -1.0]);
assert!(opposite.level_side > 0.5);
assert!((opposite.level_side - opposite.level_l).abs() < 1e-3);
assert_eq!(opposite.stereo, Some(true));
// mono duplicates L into R
let mono = measure(&[1.0]);
assert_eq!(mono.level_side, 0.0);
assert_eq!(mono.stereo, Some(false));
// a third channel only feeds the mono sum
let surround = measure(&[1.0, 0.0, 1.0]);
assert!(surround.level_side > 0.0 && surround.level_side < surround.level_l);
}
#[test]
fn pcm_history_reads_newest_samples_and_silence_before_the_first() {
let shared = AnalyzerShared::default();
for value in [0.25_f32, 0.5, -0.5] {
shared.push_pcm(value);
}
let mut out = [1.0_f32; 5];
shared.copy_pcm(shared.pcm_write.load(Ordering::Relaxed), &mut out);
let rounded: Vec<f32> = out
.iter()
.map(|value| (value * 4.0).round() / 4.0)
.collect();
assert_eq!(rounded, [0.0, 0.0, 0.25, 0.5, -0.5]);
shared.clear();
shared.copy_pcm(shared.pcm_write.load(Ordering::Relaxed), &mut out);
assert!(out.iter().all(|value| *value == 0.0));
}
}
+27 -44
View File
@@ -6,15 +6,19 @@
mod analyzer;
mod opus;
mod output;
mod spectrum;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::Duration;
use rodio::{Decoder, DeviceSinkBuilder, Player, Source, stream::MixerDeviceSink};
use output::Output;
use rodio::{Decoder, Source};
pub use analyzer::AudioAnalysisSnapshot;
pub use spectrum::{BAND_CENTERS_HZ, FLOOR_DB};
pub trait TrackReadSeek: std::io::Read + std::io::Seek + Send + Sync {}
@@ -89,10 +93,16 @@ enum Command {
pub struct Shared {
position_ms: AtomicU64,
paused: AtomicBool,
output_playing: AtomicBool,
analysis: Arc<analyzer::AnalyzerShared>,
}
impl Shared {
/// Whether the audio worker currently has an unpaused source in its sink.
pub fn output_playing(&self) -> bool {
self.output_playing.load(Ordering::Relaxed)
}
pub fn position(&self) -> Duration {
Duration::from_millis(self.position_ms.load(Ordering::Relaxed))
}
@@ -264,12 +274,6 @@ struct Generations {
start_paused: Arc<AtomicBool>,
}
struct Output {
/// Keeps the audio device open; dropping it stops the mixer.
_device: MixerDeviceSink,
player: Player,
}
/// Audio-thread state besides the output device.
struct Playing {
track_loaded: bool,
@@ -351,9 +355,6 @@ fn run(
shared
.position_ms
.store(position.as_millis() as u64, Ordering::Relaxed);
shared
.paused
.store(out.player.is_paused(), Ordering::Relaxed);
let len = out.player.len();
if playing.track_loaded && len < last_len {
// The next (gapless) source starts at zero.
@@ -374,6 +375,16 @@ fn run(
}
Err(RecvTimeoutError::Disconnected) => return,
}
// Publish the sink's state after applying the operation, including a
// stop or a gapless queue ending. The device heartbeat reads this.
let paused = output.as_ref().is_some_and(|out| out.player.is_paused());
shared.paused.store(paused, Ordering::Relaxed);
shared.output_playing.store(
playing.track_loaded
&& !paused
&& output.as_ref().is_some_and(|out| !out.player.empty()),
Ordering::Relaxed,
);
}
}
@@ -393,9 +404,7 @@ fn handle(
seekable,
volume,
} => {
let Some(out) = ensure_output(output, on_event) else {
return;
};
let out = output.get_or_insert_with(Output::new);
match decode_source(reader, byte_len, mime_type.as_deref(), seekable) {
Ok(source) => start_source(out, source, volume, false, shared, on_event),
Err(err) => {
@@ -412,9 +421,7 @@ fn handle(
start,
generation: _,
} => {
let Some(out) = ensure_output(output, on_event) else {
return;
};
let out = output.get_or_insert_with(Output::new);
let paused = start_paused.load(Ordering::SeqCst);
start_source(out, source, volume, paused, shared, on_event);
playing.track_loaded = true;
@@ -453,13 +460,13 @@ fn handle(
if let Some(out) = output.take() {
out.player.stop();
}
shared.analysis.clear();
shared.analysis.reset();
playing.track_loaded = false;
playing.base = Duration::ZERO;
}
Command::Seek(position) => {
let result = match output {
Some(out) => out.player.try_seek(position).map_err(|err| err.to_string()),
Some(out) => out.seek(position),
None => Err("nothing is playing".to_string()),
};
match &result {
@@ -482,33 +489,9 @@ fn handle(
}
}
/// The device is opened lazily on first playback so the app works on
/// machines with no audio output until you actually press play.
fn ensure_output<'a>(
output: &'a mut Option<Output>,
on_event: &impl Fn(PlayerEvent),
) -> Option<&'a Output> {
if output.is_none() {
match DeviceSinkBuilder::open_default_sink() {
Ok(device) => {
let player = Player::connect_new(device.mixer());
*output = Some(Output {
_device: device,
player,
});
}
Err(err) => {
on_event(PlayerEvent::Failed(format!("no audio device: {err}")));
return None;
}
}
}
output.as_ref()
}
/// Replace whatever is playing with `source`.
fn start_source(
out: &Output,
out: &mut Output,
source: DecodedSource,
volume: f32,
paused: bool,
@@ -516,7 +499,7 @@ fn start_source(
on_event: &impl Fn(PlayerEvent),
) {
shared.analysis.clear();
out.player.stop();
out.reset_player();
out.player.set_volume(volume);
out.player.append(analyzer::AnalyzedSource::new(
source,
+326
View File
@@ -0,0 +1,326 @@
//! Hardware output is replaceable. Rodio's source queue and playback controls
//! outlive the hardware sink, so unplugging never finishes or reopens a track.
use std::num::{NonZeroU16, NonZeroU32};
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
mpsc::{self, RecvTimeoutError},
};
use std::time::{Duration, Instant};
use rodio::{
DeviceSinkBuilder, Player, Source,
cpal::{
self,
traits::{DeviceTrait, HostTrait},
},
queue::SourcesQueueOutput,
source::UniformSourceIterator,
stream::MixerDeviceSink,
};
#[derive(Clone, Copy)]
struct AudioFormat {
channels: NonZeroU16,
sample_rate: NonZeroU32,
}
impl AudioFormat {
const FALLBACK: Self = Self {
channels: NonZeroU16::new(2).unwrap(),
sample_rate: NonZeroU32::new(48_000).unwrap(),
};
fn current_default() -> Self {
let config = cpal::default_host()
.default_output_device()
.and_then(|device| device.default_output_config().ok());
config
.and_then(|config| {
Some(Self {
channels: NonZeroU16::new(config.channels())?,
sample_rate: NonZeroU32::new(config.sample_rate())?,
})
})
.unwrap_or(Self::FALLBACK)
}
fn queue(self, input: SourcesQueueOutput) -> UniformSourceIterator<SourcesQueueOutput> {
UniformSourceIterator::new(input, self.channels, self.sample_rate)
}
fn aligned_samples(self, suggested: usize) -> usize {
let channels = usize::from(self.channels.get());
(suggested / channels).max(1) * channels
}
}
const CHUNK: usize = 64;
const PROBE_INTERVAL: Duration = Duration::from_millis(500);
const STALL_TIME: Duration = Duration::from_secs(2);
struct Audio {
format: AudioFormat,
queue: Mutex<UniformSourceIterator<SourcesQueueOutput>>,
// Rodio services synchronous seek orders when the source is consumed.
// Without hardware, the monitor can advance a muted buffer to service one.
seeking: AtomicBool,
samples: AtomicU64,
generation: AtomicU64,
}
pub(super) struct Output {
// Keeping the sender alive keeps the monitor active.
_monitor: mpsc::Sender<()>,
audio: Arc<Audio>,
pub(super) player: Player,
}
impl Output {
pub fn new() -> Self {
let (player, queue) = Player::new();
// Keep the starting device's native format in steady state. A
// replacement sink resamples only when its format differs.
let format = AudioFormat::current_default();
let audio = Arc::new(Audio {
format,
queue: Mutex::new(format.queue(queue)),
seeking: AtomicBool::new(false),
samples: AtomicU64::new(0),
generation: AtomicU64::new(0),
});
let (monitor, rx) = mpsc::channel();
let monitor_audio = Arc::clone(&audio);
std::thread::Builder::new()
.name("audio-output".into())
.spawn(move || watch_outputs(rx, monitor_audio))
.expect("spawning the audio output monitor cannot fail");
Self {
_monitor: monitor,
audio,
player,
}
}
pub fn reset_player(&mut self) {
// Rodio waits for the previous callback when appending after stop.
// Replace the queue instead, so starting another track can never wait
// for a callback from a disconnected device.
let (player, queue) = Player::new();
*self
.audio
.queue
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = self.audio.format.queue(queue);
self.audio.generation.fetch_add(1, Relaxed);
self.player = player;
}
pub fn seek(&self, position: Duration) -> Result<(), String> {
self.audio.seeking.store(true, Relaxed);
let result = self
.player
.try_seek(position)
.map_err(|error| error.to_string());
self.audio.seeking.store(false, Relaxed);
result
}
}
struct DeviceOutput {
id: Option<cpal::DeviceId>,
_sink: MixerDeviceSink,
failed: Arc<AtomicBool>,
last_samples: u64,
last_callback: Instant,
}
impl DeviceOutput {
fn open(
device: cpal::Device,
id: Option<cpal::DeviceId>,
audio: &Arc<Audio>,
) -> Result<Self, rodio::stream::DeviceSinkError> {
let failed = Arc::new(AtomicBool::new(false));
let signal = Arc::clone(&failed);
let mut sink = DeviceSinkBuilder::from_device(device)?
.with_error_callback(move |_| signal.store(true, Relaxed))
.open_sink_or_fallback()?;
sink.log_on_drop(false);
sink.mixer().add(RoutedSource::new(Arc::clone(audio)));
Ok(Self {
id,
_sink: sink,
failed,
last_samples: audio.samples.load(Relaxed),
last_callback: Instant::now(),
})
}
}
fn watch_outputs(rx: mpsc::Receiver<()>, audio: Arc<Audio>) {
let host = cpal::default_host();
let mut active: Option<DeviceOutput> = None;
let mut unavailable = false;
loop {
let device = host.default_output_device();
let id = device.as_ref().and_then(|device| device.id().ok());
let now = Instant::now();
if let Some(output) = &mut active {
let samples = audio.samples.load(Relaxed);
if samples != output.last_samples {
output.last_samples = samples;
output.last_callback = now;
}
if output.failed.load(Relaxed)
|| now.duration_since(output.last_callback) >= STALL_TIME
|| device.is_none()
|| matches!((&output.id, &id), (Some(old), Some(new)) if old != new)
{
// Drop the old callback first: only one sink may draw samples.
active = None;
}
}
if active.is_none() {
if let Some(device) = device {
match DeviceOutput::open(device, id, &audio) {
Ok(output) => {
if unavailable {
tracing::info!("audio output restored");
}
active = Some(output);
}
Err(error) if !unavailable => {
tracing::debug!(%error, "could not open audio output")
}
Err(_) => {}
}
}
if active.is_none() && !unavailable {
tracing::warn!("waiting for a usable default audio output");
}
unavailable = active.is_none();
}
if active.is_none() && audio.seeking.load(Relaxed) {
let mut queue = audio
.queue
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let channels = usize::from(audio.format.channels.get());
for _ in 0..(1024 / channels).max(1) {
if !audio.seeking.load(Relaxed) {
break;
}
for _ in 0..channels {
queue.next();
}
}
}
match rx.recv_timeout(PROBE_INTERVAL) {
Err(RecvTimeoutError::Disconnected) => break,
Err(RecvTimeoutError::Timeout) | Ok(()) => {}
}
}
}
struct RoutedSource {
audio: Arc<Audio>,
chunk: Vec<f32>,
index: usize,
generation: u64,
}
impl RoutedSource {
fn new(audio: Arc<Audio>) -> Self {
let size = audio.format.aligned_samples(CHUNK);
Self {
audio,
chunk: vec![0.0; size],
index: size,
generation: 0,
}
}
}
impl Iterator for RoutedSource {
type Item = f32;
fn next(&mut self) -> Option<f32> {
let generation = self.audio.generation.load(Relaxed);
if self.index == self.chunk.len() || self.generation != generation {
let mut queue = self
.audio
.queue
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for sample in &mut self.chunk {
*sample = queue.next().unwrap_or(0.0);
}
self.audio
.samples
.fetch_add(self.chunk.len() as u64, Relaxed);
self.index = 0;
self.generation = generation;
}
let sample = self.chunk[self.index];
self.index += 1;
Some(sample)
}
}
impl Source for RoutedSource {
fn current_span_len(&self) -> Option<usize> {
None
}
fn channels(&self) -> NonZeroU16 {
self.audio.format.channels
}
fn sample_rate(&self) -> NonZeroU32 {
self.audio.format.sample_rate
}
fn total_duration(&self) -> Option<Duration> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replacing_the_sink_preserves_the_rodio_queue_and_position() {
let (player, queue) = Player::new();
let format = AudioFormat::FALLBACK;
let audio = Arc::new(Audio {
format,
queue: Mutex::new(format.queue(queue)),
seeking: AtomicBool::new(false),
samples: AtomicU64::new(0),
generation: AtomicU64::new(0),
});
player.append(rodio::buffer::SamplesBuffer::new(
format.channels,
format.sample_rate,
vec![0.5; 96_000],
));
player.append(rodio::buffer::SamplesBuffer::new(
format.channels,
format.sample_rate,
vec![0.8; 96_000],
));
let mut first = RoutedSource::new(Arc::clone(&audio));
first.by_ref().take(9_600).for_each(|_| {});
let previous = player.get_pos();
drop(first);
assert_eq!(player.len(), 2);
player.pause();
let mut reconnected = RoutedSource::new(audio);
reconnected.by_ref().take(9_600).for_each(|_| {});
assert!(player.is_paused());
assert!(player.get_pos() - previous < Duration::from_millis(10));
player.play();
reconnected.take(9_600).for_each(|_| {});
assert!(player.get_pos() > previous + Duration::from_millis(50));
assert_eq!(player.len(), 2);
}
}
+650
View File
@@ -0,0 +1,650 @@
//! Display meter for visualizations: a third-octave spectrum and stereo levels
//! with analyzer ballistics (fast attack, steady fall, peak hold).
//!
//! The audio thread only writes samples and per-window channel levels into
//! `AnalyzerShared`; the FFT and all smoothing run here, on the reader side,
//! when a snapshot is taken. Ballistics are time-based: rises and falls
//! advance with the clock, not with the number of snapshots.
use std::sync::Arc;
use std::time::Instant;
use rustfft::num_complex::Complex;
use rustfft::{Fft, FftPlanner};
/// Mono samples kept for the spectrum: enough for an ~85 ms window at
/// 192 kHz. The FFT uses the newest `fft_len(rate)` of them.
pub const PCM_SAMPLES: usize = 16_384;
/// Bottom of the display scale: values are normalized from `FLOOR_DB`..0 dBFS
/// to 0.0..1.0, so a full-scale sine reads 1.0.
pub const FLOOR_DB: f32 = -60.0;
/// Nominal ISO third-octave band centres (Hz), 20 Hz .. 20 kHz. These are
/// labels; band edges come from the exact base-2 centres (see `exact_center`)
/// so neighbouring bands meet without gaps or overlaps.
pub const BAND_CENTERS_HZ: [f32; 31] = [
20.0, 25.0, 31.5, 40.0, 50.0, 63.0, 80.0, 100.0, 125.0, 160.0, 200.0, 250.0, 315.0, 400.0,
500.0, 630.0, 800.0, 1_000.0, 1_250.0, 1_600.0, 2_000.0, 2_500.0, 3_150.0, 4_000.0, 5_000.0,
6_300.0, 8_000.0, 10_000.0, 12_500.0, 16_000.0, 20_000.0,
];
const BANDS: usize = BAND_CENTERS_HZ.len();
/// Index of the 1 kHz band.
const KHZ_BAND: i32 = 17;
const MIN_FFT: usize = 4096;
const BAND_ATTACK_SECS: f32 = 0.025;
const BAND_FALL_DB_PER_SEC: f32 = 36.0;
const PEAK_HOLD_SECS: f32 = 1.2;
const PEAK_FALL_DB_PER_SEC: f32 = 18.0;
const LEVEL_ATTACK_SECS: f32 = 0.05;
const LEVEL_RELEASE_SECS: f32 = 0.3;
/// A window counts as stereo when its side signal (L - R) / 2 is no more
/// than this far below the louder channel: lossy coding of a mono recording
/// leaves a side signal far below that, real stereo mixes sit well above it.
const STEREO_SIDE_DB: f32 = -30.0;
/// Only windows this far above the floor decide; quieter ones keep the last
/// decision, since their side signal is lost in the floor.
const STEREO_DECIDE_ABOVE_FLOOR_DB: f32 = 30.0;
/// Longest step applied at once; a stalled reader must not fast-forward a
/// whole second of decay in one frame.
const MAX_STEP_SECS: f32 = 0.25;
/// Audio arrives in device-callback bursts (rodio uses ~46 ms buffers), so a
/// snapshot may see no new samples while playback runs. Only a longer stall
/// (pause, stop) counts as silence.
const STALL_SECS: f32 = 0.15;
/// FFT length for a sample rate: ~85 ms of audio, a power of two.
fn fft_len(sample_rate: u32) -> usize {
(sample_rate as usize * MIN_FFT / 48_000)
.next_power_of_two()
.clamp(MIN_FFT, PCM_SAMPLES)
}
/// Exact base-2 third-octave centre of band `index` (1 kHz at index 17).
fn exact_center(index: usize) -> f32 {
1_000.0 * 2f32.powf((index as i32 - KHZ_BAND) as f32 / 3.0)
}
/// Linear channel levels of the latest analysis window.
#[derive(Debug, Clone, Copy, Default)]
pub struct StereoReading {
pub rms_l: f32,
pub rms_r: f32,
/// RMS of the side signal (L - R) / 2.
pub rms_side: f32,
/// Highest sample peaks since the previous reading.
pub peak_l: f32,
pub peak_r: f32,
}
#[derive(Debug, Clone, Default)]
pub struct MeterReading {
pub spectrum: Vec<f64>,
pub spectrum_peaks: Vec<f64>,
pub level_l: f64,
pub level_r: f64,
pub peak_l: f64,
pub peak_r: f64,
pub level_side: f64,
/// Whether the two channels carry different signals (see
/// `STEREO_SIDE_DB`); `None` until a loud enough window was measured.
pub stereo: Option<bool>,
}
struct Hold {
db: f32,
age: f32,
}
impl Hold {
fn new() -> Self {
Self {
db: FLOOR_DB,
age: 0.0,
}
}
fn update(&mut self, value_db: f32, dt: f32) {
if value_db >= self.db {
self.db = value_db;
self.age = 0.0;
return;
}
self.age += dt;
if self.age > PEAK_HOLD_SECS {
self.db = (self.db - PEAK_FALL_DB_PER_SEC * dt).max(value_db);
}
}
}
/// FFT plan, window and band bin ranges for one sample rate.
struct Analysis {
sample_rate: u32,
fft: Arc<dyn Fft<f32>>,
window: Vec<f32>,
/// Sum of squared window weights, for power normalization.
window_power: f32,
pcm: Vec<f32>,
buffer: Vec<Complex<f32>>,
scratch: Vec<Complex<f32>>,
/// Inclusive bin range per band; `None` above Nyquist.
bins: [Option<(usize, usize)>; BANDS],
}
impl Analysis {
fn new(sample_rate: u32) -> Self {
let len = fft_len(sample_rate);
let fft = FftPlanner::<f32>::new().plan_fft_forward(len);
let scratch = vec![Complex::default(); fft.get_inplace_scratch_len()];
let window: Vec<f32> = (0..len)
.map(|index| {
let phase = std::f32::consts::TAU * index as f32 / len as f32;
0.5 - 0.5 * phase.cos()
})
.collect();
let window_power = window.iter().map(|weight| weight * weight).sum();
Self {
sample_rate,
fft,
window,
window_power,
pcm: vec![0.0; len],
buffer: vec![Complex::default(); len],
scratch,
bins: band_bins(sample_rate, len),
}
}
/// Band power in dBFS (a full-scale sine reads 0 dB in its band). The
/// caller has filled `pcm`.
fn band_targets(&mut self) -> [f32; BANDS] {
for ((slot, sample), weight) in self.buffer.iter_mut().zip(&self.pcm).zip(&self.window) {
*slot = Complex::new(sample * weight, 0.0);
}
self.fft
.process_with_scratch(&mut self.buffer, &mut self.scratch);
// One-sided power per bin, normalized so the bins of a sine sum to
// its mean square (A^2 / 2); doubled below so the sine reads 0 dB.
let scale = 2.0 / (self.buffer.len() as f32 * self.window_power);
let mut out = [FLOOR_DB; BANDS];
for (slot, range) in out.iter_mut().zip(self.bins) {
if let Some((first, last)) = range {
let power: f32 = self.buffer[first..=last]
.iter()
.map(|bin| bin.norm_sqr() * scale)
.sum();
*slot = to_db_power(2.0 * power);
}
}
out
}
}
/// Partitions the FFT bins between the bands: each bin belongs to exactly one
/// band, from the first bin at or above the band's lower edge up to the bin
/// before the next band starts. A band narrower than one bin (deep bass at
/// short windows) reads the bin that contains its centre, which it then shares
/// with its neighbour.
fn band_bins(sample_rate: u32, len: usize) -> [Option<(usize, usize)>; BANDS] {
let bin_hz = sample_rate as f32 / len as f32;
let last_bin = len / 2 - 1;
let nyquist = sample_rate as f32 / 2.0;
let edge = 2f32.powf(1.0 / 6.0);
let first_bin = |index: usize| ((exact_center(index) / edge / bin_hz).ceil() as usize).max(1);
std::array::from_fn(|index| {
let low = exact_center(index) / edge;
if low >= nyquist {
return None;
}
let first = first_bin(index);
let last = if index + 1 < BANDS {
first_bin(index + 1).saturating_sub(1)
} else {
((exact_center(index) * edge / bin_hz).floor() as usize).max(first)
}
.min(last_bin);
if first <= last {
Some((first, last))
} else {
let center = ((exact_center(index) / bin_hz).round() as usize).clamp(1, last_bin);
Some((center, center))
}
})
}
pub struct Meter {
analysis: Option<Analysis>,
bands_db: [f32; BANDS],
band_peaks: [Hold; BANDS],
/// Left, right and side RMS levels.
level_db: [f32; 3],
level_peaks: [Hold; 2],
last_update: Option<Instant>,
last_write: usize,
/// When the PCM counter last moved, and what that audio measured; reused
/// between device callbacks until `STALL_SECS` pass.
last_fresh: Option<Instant>,
held_targets: [f32; BANDS],
held_rms: [f32; 3],
/// Last stereo decision; kept through silence, pauses and stalls.
stereo: Option<bool>,
}
impl std::fmt::Debug for Meter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Meter")
.field("bands_db", &self.bands_db)
.field("level_db", &self.level_db)
.finish_non_exhaustive()
}
}
impl Default for Meter {
fn default() -> Self {
Self {
analysis: None,
bands_db: [FLOOR_DB; BANDS],
band_peaks: std::array::from_fn(|_| Hold::new()),
level_db: [FLOOR_DB; 3],
level_peaks: std::array::from_fn(|_| Hold::new()),
last_update: None,
last_write: 0,
last_fresh: None,
held_targets: [FLOOR_DB; BANDS],
held_rms: [0.0; 3],
stereo: None,
}
}
}
impl Meter {
/// Advances the meter to `now`. `write` is the analyzer's PCM write
/// counter: while it keeps moving the newest audio is measured; once it
/// has not moved for `STALL_SECS` (paused, stopped) the meter is fed
/// silence and falls instead of freezing. `fill_pcm` copies the newest
/// `out.len()` mono samples, oldest first.
pub fn update(
&mut self,
now: Instant,
write: usize,
sample_rate: u32,
stereo: StereoReading,
fill_pcm: impl FnOnce(&mut [f32]),
) -> MeterReading {
let dt = self
.last_update
.map(|last| now.saturating_duration_since(last).as_secs_f32())
.unwrap_or(MAX_STEP_SECS)
.min(MAX_STEP_SECS);
self.last_update = Some(now);
let fresh = write != self.last_write;
self.last_write = write;
let (targets, rms, peaks) = if fresh && sample_rate > 0 {
if self
.analysis
.as_ref()
.is_none_or(|analysis| analysis.sample_rate != sample_rate)
{
self.analysis = Some(Analysis::new(sample_rate));
}
let analysis = self.analysis.as_mut().expect("analysis was just set");
fill_pcm(&mut analysis.pcm);
self.held_targets = analysis.band_targets();
self.held_rms = [stereo.rms_l, stereo.rms_r, stereo.rms_side];
// decided on the raw window, before ballistics: smoothed levels
// converge on the floor together and would read as stereo
let loud = stereo.rms_l.max(stereo.rms_r);
if to_db(loud) > FLOOR_DB + STEREO_DECIDE_ABOVE_FLOOR_DB {
self.stereo = Some(to_db(stereo.rms_side) > to_db(loud) + STEREO_SIDE_DB);
}
self.last_fresh = Some(now);
(
self.held_targets,
self.held_rms,
[stereo.peak_l, stereo.peak_r],
)
} else if self
.last_fresh
.is_some_and(|last| now.saturating_duration_since(last).as_secs_f32() <= STALL_SECS)
{
(self.held_targets, self.held_rms, [0.0; 2])
} else {
([FLOOR_DB; BANDS], [0.0; 3], [0.0; 2])
};
for ((current, target), peak) in self
.bands_db
.iter_mut()
.zip(targets)
.zip(self.band_peaks.iter_mut())
{
*current = follow_band(*current, target, dt);
peak.update(*current, dt);
}
for (level, value) in self.level_db.iter_mut().zip(rms) {
*level = follow_level(*level, to_db(value), dt);
}
for (hold, value) in self.level_peaks.iter_mut().zip(peaks) {
hold.update(to_db(value), dt);
}
MeterReading {
spectrum: self.bands_db.iter().map(|db| normalize(*db)).collect(),
spectrum_peaks: self
.band_peaks
.iter()
.map(|hold| normalize(hold.db))
.collect(),
level_l: normalize(self.level_db[0]),
level_r: normalize(self.level_db[1]),
peak_l: normalize(self.level_peaks[0].db),
peak_r: normalize(self.level_peaks[1].db),
level_side: normalize(self.level_db[2]),
stereo: self.stereo,
}
}
}
fn follow_band(current: f32, target: f32, dt: f32) -> f32 {
if target > current {
current + (target - current) * (1.0 - (-dt / BAND_ATTACK_SECS).exp())
} else {
(current - BAND_FALL_DB_PER_SEC * dt).max(target)
}
}
fn follow_level(current: f32, target: f32, dt: f32) -> f32 {
let tau = if target > current {
LEVEL_ATTACK_SECS
} else {
LEVEL_RELEASE_SECS
};
current + (target - current) * (1.0 - (-dt / tau).exp())
}
fn to_db(amplitude: f32) -> f32 {
if amplitude <= 0.0 || !amplitude.is_finite() {
FLOOR_DB
} else {
(20.0 * amplitude.log10()).max(FLOOR_DB)
}
}
fn to_db_power(power: f32) -> f32 {
if power <= 0.0 || !power.is_finite() {
FLOOR_DB
} else {
(10.0 * power.log10()).max(FLOOR_DB)
}
}
fn normalize(db: f32) -> f64 {
f64::from(((db - FLOOR_DB) / -FLOOR_DB).clamp(0.0, 1.0))
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
fn sine(frequency: f32, amplitude: f32, sample_rate: u32, len: usize) -> Vec<f32> {
(0..len)
.map(|index| {
let time = index as f32 / sample_rate as f32;
amplitude * (std::f32::consts::TAU * frequency * time).sin()
})
.collect()
}
fn band(center: f32) -> usize {
BAND_CENTERS_HZ
.iter()
.position(|value| *value == center)
.unwrap()
}
/// Feeds a steady tone for `steps` snapshots 50 ms apart.
fn settle(meter: &mut Meter, frequency: f32, sample_rate: u32, steps: u64) -> MeterReading {
let samples = sine(frequency, 0.5, sample_rate, PCM_SAMPLES);
let start = Instant::now();
let mut reading = MeterReading::default();
for step in 1..=steps {
reading = meter.update(
start + Duration::from_millis(50 * step),
step as usize,
sample_rate,
StereoReading::default(),
|out| out.copy_from_slice(&samples[..out.len()]),
);
}
reading
}
fn band_powers_db(frequency: f32, sample_rate: u32) -> [f32; BANDS] {
let mut analysis = Analysis::new(sample_rate);
let len = analysis.pcm.len();
analysis
.pcm
.copy_from_slice(&sine(frequency, 1.0, sample_rate, len));
analysis.band_targets()
}
#[test]
fn a_sine_lights_its_own_third_octave_band() {
let reading = settle(&mut Meter::default(), 1_000.0, 48_000, 10);
let at_1k = reading.spectrum[band(1_000.0)];
// -6 dBFS on a 60 dB scale reads 0.9.
assert!((at_1k - 0.9).abs() < 0.03, "1 kHz band read {at_1k}");
assert!(reading.spectrum[band(250.0)] < 0.2);
assert!(reading.spectrum[band(4_000.0)] < 0.2);
assert!(reading.spectrum_peaks[band(1_000.0)] >= at_1k);
}
#[test]
fn bands_cover_the_axis_without_gaps_or_double_counting() {
for sample_rate in [44_100, 48_000, 96_000] {
// Up to just below the top band's upper edge (~22.4 kHz) or
// Nyquist; 1/24-octave steps also land right on band edges.
let top = (sample_rate as f32 / 2.0 * 0.85).min(exact_center(BANDS - 1) * 1.1);
let mut frequency = 80.0_f32;
while frequency < top {
let powers = band_powers_db(frequency, sample_rate);
let loudest = powers.iter().copied().fold(FLOOR_DB, f32::max);
let total: f32 = powers
.iter()
.filter(|db| **db > FLOOR_DB)
.map(|db| 10f32.powf(db / 10.0))
.sum();
assert!(
(-3.5..=0.5).contains(&loudest),
"{frequency} Hz at {sample_rate}: loudest band {loudest} dB"
);
let total_db = 10.0 * total.log10();
assert!(
total_db.abs() < 0.5,
"{frequency} Hz at {sample_rate}: bands sum to {total_db} dB"
);
frequency *= 2f32.powf(1.0 / 24.0);
}
}
}
#[test]
fn deep_bass_reads_at_every_sample_rate() {
for sample_rate in [44_100, 48_000, 96_000, 192_000] {
let powers = band_powers_db(31.5, sample_rate);
assert!(
powers[band(31.5)] > -3.0,
"31.5 Hz at {sample_rate}: {} dB",
powers[band(31.5)]
);
assert!(powers[band(1_000.0)] < -40.0);
}
// Bands above Nyquist stay at the floor.
assert_eq!(band_powers_db(1_000.0, 32_000)[band(20_000.0)], FLOOR_DB);
}
#[test]
fn callback_gaps_keep_the_meter_steady_but_a_stall_falls() {
let mut meter = Meter::default();
let samples = sine(1_000.0, 0.5, 48_000, PCM_SAMPLES);
let tone = StereoReading {
rms_l: 0.35,
rms_r: 0.35,
rms_side: 0.0,
peak_l: 0.5,
peak_r: 0.5,
};
let start = Instant::now();
let mut write = 0;
let mut steady = MeterReading::default();
for step in 1..=40u64 {
// Every third snapshot lands between two device callbacks.
if step % 3 != 0 {
write += 1;
}
let reading = meter.update(
start + Duration::from_millis(50 * step),
write,
48_000,
tone,
|out| out.copy_from_slice(&samples[..out.len()]),
);
if step > 20 {
assert!(
(reading.level_l - steady.level_l).abs() < 0.02 || step == 21,
"level jumped at step {step}"
);
assert!(
(reading.spectrum[band(1_000.0)] - 0.9).abs() < 0.03,
"band jumped at step {step}"
);
}
steady = reading;
}
// The counter stops for longer than a callback gap: paused.
let index = band(1_000.0);
let paused_at = start + Duration::from_millis(2_000);
let first = meter.update(paused_at, write, 48_000, tone, |_| {});
let later = meter.update(
paused_at + Duration::from_millis(500),
write,
48_000,
tone,
|_| {},
);
assert!(later.spectrum[index] < first.spectrum[index]);
assert!(later.level_l < first.level_l);
// The peak marker holds for 1.2 s before it falls too.
assert!((later.spectrum_peaks[index] - 0.9).abs() < 0.03);
let mut reading = later;
for step in 1..=20u64 {
reading = meter.update(
paused_at + Duration::from_millis(500 + 250 * step),
write,
48_000,
tone,
|_| {},
);
}
assert_eq!(reading.spectrum[index], 0.0);
assert!(reading.spectrum_peaks[index] < 0.5);
}
#[test]
fn channel_levels_follow_rms_and_hold_peaks() {
let mut meter = Meter::default();
let start = Instant::now();
let loud_left = StereoReading {
rms_l: 0.5,
rms_r: 0.05,
rms_side: 0.2,
peak_l: 0.9,
peak_r: 0.1,
};
let mut reading = MeterReading::default();
for step in 1..=20 {
reading = meter.update(
start + Duration::from_millis(50 * step),
step as usize,
48_000,
loud_left,
|out| out.fill(0.0),
);
}
assert!(reading.level_l > reading.level_r);
assert!((reading.level_l - normalize(to_db(0.5))).abs() < 0.02);
assert!((reading.peak_l - normalize(to_db(0.9))).abs() < 0.01);
assert!(reading.peak_l >= reading.level_l);
assert!((reading.level_side - normalize(to_db(0.2))).abs() < 0.02);
assert_eq!(reading.stereo, Some(true));
}
#[test]
fn stereo_is_decided_on_loud_windows_and_kept_through_silence() {
let mut meter = Meter::default();
let start = Instant::now();
let mut read = |step: u64, stereo: StereoReading| {
meter.update(
start + Duration::from_millis(50 * step),
step as usize,
48_000,
stereo,
|out| out.fill(0.0),
)
};
let quiet = StereoReading {
rms_l: 0.0005,
rms_r: 0.0001,
rms_side: 0.0002,
..StereoReading::default()
};
assert_eq!(read(1, quiet).stereo, None);
let near_mono = StereoReading {
rms_l: 0.3,
rms_r: 0.3,
rms_side: 0.003,
..StereoReading::default()
};
assert_eq!(read(2, near_mono).stereo, Some(false));
// silence and then a stall keep the decision
assert_eq!(read(3, StereoReading::default()).stereo, Some(false));
let wide = StereoReading {
rms_side: 0.1,
..near_mono
};
assert_eq!(read(4, wide).stereo, Some(true));
let later = meter.update(
start + Duration::from_secs(5),
4,
48_000,
StereoReading::default(),
|out| out.fill(0.0),
);
assert_eq!(later.stereo, Some(true));
}
#[test]
fn silence_and_unknown_rate_read_the_floor() {
let mut meter = Meter::default();
let reading = meter.update(Instant::now(), 1, 0, StereoReading::default(), |_| {});
assert!(reading.spectrum.iter().all(|value| *value == 0.0));
assert_eq!(reading.level_l, 0.0);
assert_eq!(reading.level_side, 0.0);
assert_eq!(reading.spectrum.len(), BAND_CENTERS_HZ.len());
}
#[test]
fn fft_length_tracks_the_sample_rate() {
assert_eq!(fft_len(44_100), 4096);
assert_eq!(fft_len(48_000), 4096);
assert_eq!(fft_len(96_000), 8192);
assert_eq!(fft_len(192_000), 16_384);
assert_eq!(fft_len(0), 4096);
}
}
+3 -1
View File
@@ -25,10 +25,11 @@
//! "already subscribed" mark, an episode preview read from the feed and
//! subscribing from a card.
//!
//! Only RSS metadata is stored. Audio stays on the publisher's server.
//! Audio is streamed unless the user explicitly downloads an episode.
pub mod discovery;
pub mod fetch;
pub mod offline;
pub mod playback;
pub mod progress;
pub mod publication;
@@ -125,6 +126,7 @@ pub fn open_services(db_path: &Path, covers_dir: PathBuf, log: Arc<dyn OpLog>) -
let confirmations =
publication::ShareConfirmations::open(publication::confirmations_path(db_path));
Ok(Services {
downloads_dir: db_path.with_file_name("podcast-downloads"),
store: Arc::new(store),
fetcher: Arc::new(Fetcher::new(covers_dir)?),
log,
+99
View File
@@ -0,0 +1,99 @@
//! Explicit device-local downloads, outside the podcast sync store.
use anyhow::{Result, bail};
use music_dht::podcast::PodcastEpisodeRef;
use std::{
fs::{self, File},
io::{Read, Write},
path::{Path, PathBuf},
time::{Duration, SystemTime},
};
pub fn key(id: &str) -> String {
blake3::hash(id.as_bytes()).to_hex().to_string()
}
pub fn path(dir: &Path, ep: &PodcastEpisodeRef) -> PathBuf {
dir.join(key(ep.episode_id.as_str()))
}
pub fn available(dir: &Path) -> Result<std::collections::HashSet<String>> {
if !dir.exists() {
return Ok(Default::default());
}
Ok(fs::read_dir(dir)?
.filter_map(Result::ok)
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.filter_map(|e| {
let n = e.file_name().to_str()?.to_owned();
(n.len() == 64 && n.bytes().all(|b| b.is_ascii_hexdigit())).then_some(n)
})
.collect())
}
pub fn cleanup(
dir: &Path,
days: u32,
now: SystemTime,
) -> Result<std::collections::HashSet<String>> {
for name in available(dir)? {
let p = dir.join(name);
if now
.duration_since(fs::metadata(&p)?.modified()?)
.unwrap_or_default()
>= Duration::from_secs(u64::from(days.max(1)) * 86400)
{
let _ = fs::remove_file(p);
}
}
available(dir)
}
pub fn open(dir: &Path, ep: &PodcastEpisodeRef) -> Result<Option<File>> {
match File::open(path(dir, ep)) {
Ok(f) => Ok(Some(f)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
#[cfg(test)]
pub fn download(dir: &Path, ep: &PodcastEpisodeRef) -> Result<()> {
download_with_cancel(dir, ep, super::stream::CancelToken::never())
}
pub fn download_with_cancel(
dir: &Path,
ep: &PodcastEpisodeRef,
cancel: super::stream::CancelToken,
) -> Result<()> {
let target = path(dir, ep);
let dir = target.parent().unwrap();
fs::create_dir_all(dir)?;
if target.is_file() {
return Ok(());
}
let started = std::time::Instant::now();
let mut stream = super::stream::open_with(
&ep.audio_url,
super::stream::CancelToken::new(move || {
cancel.is_cancelled() || started.elapsed() > Duration::from_secs(7200)
}),
)?;
let mut temp = tempfile::NamedTempFile::new_in(dir)?;
let mut buf = [0; 65536];
let mut total = 0u64;
loop {
let n = stream.reader.read(&mut buf)?;
if n == 0 {
break;
}
total += n as u64;
if total > 4 * 1024 * 1024 * 1024 {
bail!("episode exceeds 4 GiB");
}
temp.write_all(&buf[..n])?;
}
if total == 0
|| stream.probe.end() == super::stream::StreamEnd::Failed
|| stream.byte_len.is_some_and(|len| len != total)
{
bail!("incomplete episode download");
}
temp.as_file().sync_all()?;
temp.persist(target)
.map_err(|_| anyhow::anyhow!("cannot save episode"))?;
Ok(())
}
+58 -1
View File
@@ -163,6 +163,9 @@ pub fn open_at(
start_ms: i64,
cancel: &CancelToken,
) -> Result<PreparedEpisode> {
if cancel.is_cancelled() {
return Err(Cancelled.into());
}
let opened = stream::open_with(&episode.audio_url, cancel.clone())?;
let seekable = opened.seekable;
let probe = opened.probe.clone();
@@ -218,6 +221,43 @@ pub fn open_at(
})
}
/// Decode a completed local download. Blocking; no HTTP requests.
pub fn open_local(
episode: &PodcastEpisodeRef,
start_ms: i64,
file: std::fs::File,
) -> Result<PreparedEpisode> {
let len = file.metadata()?.len();
let mut source = decode_source_with(
Box::new(file),
Some(len),
episode.mime.as_deref(),
true,
true,
)
.map_err(|e| anyhow!(e))?;
if start_ms > 0 {
source
.try_seek(Duration::from_millis(start_ms as u64))
.map_err(|_| CannotResume {
position_ms: start_ms,
})?;
}
let measured = source
.total_duration()
.and_then(|d| i64::try_from(d.as_millis()).ok())
.filter(|ms| *ms > 0);
Ok(PreparedEpisode {
episode: episode.clone(),
source,
start_ms,
duration_ms: measured.or(episode.duration_ms),
duration_measured: measured.is_some(),
seekable: true,
probe: StreamProbe::local(),
})
}
/// [`resolve`] + [`open_at`], refreshing the feed once when the audio URL
/// answers with a client error (moved or expired file).
pub async fn prepare(
@@ -233,8 +273,25 @@ pub async fn prepare(
let lookup = queued.clone();
let (episode, start_ms) = blocking(move || resolve(store.as_deref(), &lookup, start)).await?;
let attempt = episode.clone();
let downloads_dir = services.as_ref().map(|s| s.downloads_dir.clone());
let attempt_cancel = cancel.clone();
let error = match blocking(move || open_at(&attempt, start_ms, &attempt_cancel)).await {
let error = match blocking(move || {
if attempt_cancel.is_cancelled() {
return Err(Cancelled.into());
}
let local = downloads_dir
.as_ref()
.map(|dir| super::offline::open(dir, &attempt))
.transpose()?
.flatten();
if let Some(file) = local {
open_local(&attempt, start_ms, file)
} else {
open_at(&attempt, start_ms, &attempt_cancel)
}
})
.await
{
Ok(prepared) => return Ok(prepared),
Err(error) => error,
};
+95
View File
@@ -834,3 +834,98 @@ fn a_superseded_resume_stops_reading_up_to_its_offset() {
started.elapsed()
);
}
#[tokio::test]
async fn downloaded_episode_plays_and_seeks_without_publisher() {
let f = fixture();
let (_, mut episode) = subscribed(&f).await;
f.server
.set("/offline.wav", Route::new(wav(8), "audio/wav"));
episode.audio_url = f.server.url("/offline.wav");
let download_dir = f.services.downloads_dir.clone();
let download_episode = episode.clone();
tokio::task::spawn_blocking(move || super::offline::download(&download_dir, &download_episode))
.await
.unwrap()
.unwrap();
assert!(
super::offline::available(&f.services.downloads_dir)
.unwrap()
.contains(&super::offline::key(episode.episode_id.as_str()))
);
// No store lookup can replace this reference with the fixture's old URL.
episode.audio_url = "http://127.0.0.1:1/unavailable".into();
let file = super::offline::open(&f.services.downloads_dir, &episode)
.unwrap()
.unwrap();
let prepared = playback::open_local(&episode, 2000, file).unwrap();
assert_eq!(prepared.start_ms, 2000);
assert!(prepared.seekable);
assert_eq!(prepared.probe.end(), StreamEnd::Complete);
assert!(prepared.source.take(100).count() > 0);
// Prepare must prefer the same local file even though resolve finds the old HTTP URL.
let prepared = playback::prepare(
Some(f.services.clone()),
episode,
StartAt::Position { ms: 2000 },
NOW,
CancelToken::never(),
)
.await
.unwrap();
assert_eq!(prepared.start_ms, 2000);
}
#[test]
fn download_cleanup_expires_only_completed_files_at_the_boundary() {
use std::fs::{File, FileTimes};
use std::time::SystemTime;
let dir = tempfile::tempdir().unwrap();
let now = SystemTime::now();
let expired = dir.path().join(super::offline::key("old"));
let fresh = dir.path().join(super::offline::key("new"));
File::create(&expired)
.unwrap()
.set_times(FileTimes::new().set_modified(now - Duration::from_secs(30 * 86400)))
.unwrap();
File::create(&fresh)
.unwrap()
.set_times(FileTimes::new().set_modified(now - Duration::from_secs(29 * 86400)))
.unwrap();
let unrelated = dir.path().join("notes.txt");
std::fs::write(&unrelated, b"keep").unwrap();
let remaining = super::offline::cleanup(dir.path(), 30, now).unwrap();
assert!(!expired.exists());
assert!(fresh.exists());
assert!(unrelated.exists());
assert_eq!(remaining.len(), 1);
assert_eq!(
super::offline::cleanup(dir.path(), 30, now).unwrap(),
remaining
);
}
#[tokio::test]
async fn failed_download_never_becomes_available_offline() {
let f = fixture();
let (_, mut episode) = subscribed(&f).await;
episode.audio_url = f.server.url("/missing-audio");
let download_dir = f.services.downloads_dir.clone();
assert!(
tokio::task::spawn_blocking(move || super::offline::download(&download_dir, &episode))
.await
.unwrap()
.is_err()
);
assert!(
super::offline::available(&f.services.downloads_dir)
.unwrap()
.is_empty()
);
assert_eq!(
std::fs::read_dir(&f.services.downloads_dir)
.unwrap()
.count(),
0
);
}
+1
View File
@@ -28,6 +28,7 @@ pub const FAILURE_BACKOFF_MAX: Duration = Duration::from_secs(24 * 60 * 60);
#[derive(Clone)]
pub struct Services {
pub store: Arc<PodcastStore>,
pub downloads_dir: std::path::PathBuf,
pub fetcher: Arc<Fetcher>,
pub log: Arc<dyn OpLog>,
/// Device-local privacy confirmations for sharing (never synced).
+9 -3
View File
@@ -162,7 +162,7 @@ pub enum StreamEnd {
/// Read-only view of a stream's state that outlives handing the reader to
/// the decoder.
#[derive(Clone)]
pub struct StreamProbe(Arc<Shared>);
pub struct StreamProbe(Option<Arc<Shared>>);
impl std::fmt::Debug for StreamProbe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -171,8 +171,14 @@ impl std::fmt::Debug for StreamProbe {
}
impl StreamProbe {
pub fn local() -> Self {
Self(None)
}
pub fn end(&self) -> StreamEnd {
let state = self.0.lock();
let Some(shared) = &self.0 else {
return StreamEnd::Complete;
};
let state = shared.lock();
if state.read_failed {
StreamEnd::Failed
} else if state.declared_total {
@@ -385,7 +391,7 @@ pub fn open_with(url: &str, cancel: CancelToken) -> Result<OpenedStream> {
.spawn(move || downloader.run(response))
.context("spawning the podcast stream thread")?;
Ok(OpenedStream {
probe: StreamProbe(Arc::clone(&shared)),
probe: StreamProbe(Some(Arc::clone(&shared))),
reader: HttpStream { pos: 0, shared },
byte_len: opened.total,
mime_type,
+5
View File
@@ -57,6 +57,11 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
selected = items.len();
}
let (label, value, enabled) = match row {
SettingsRow::PodcastRetention => (
"Podcast downloads: keep days".into(),
state.podcast_retention_days.to_string(),
true,
),
SettingsRow::MusicDirectory => (
"Music save directory".into(),
if state.music_dir_changing {
+256
View File
@@ -0,0 +1,256 @@
use crate::app::{
lyrics::{Editor, Reader},
state::{AppState, Popup},
};
use ratatui::{
Frame,
layout::{Alignment, Rect},
text::{Line, Span},
widgets::{Block, Clear, Paragraph, Wrap},
};
use unicode_width::UnicodeWidthChar;
use super::theme;
fn popup_area(screen: Rect) -> Rect {
let width = screen.width.saturating_sub(4).min(96);
let height = screen.height.saturating_sub(4).min(30);
Rect::new(
screen.x + (screen.width - width) / 2,
screen.y + (screen.height - height) / 2,
width,
height,
)
}
pub(crate) fn prepare_reader(state: &mut AppState, screen: Rect) {
if let Some(Popup::Lyrics(reader)) = &mut state.popup {
let area = popup_area(screen);
reader.viewport_height = usize::from(area.height.saturating_sub(4));
let width = usize::from(area.width.saturating_sub(4)).max(1);
let key = (reader.lyrics(&state.lyrics).document_revision, width);
if reader.layout_key != Some(key) {
reader.layout_key = Some(key);
reader.rows.clear();
let document = &reader
.preview
.as_ref()
.map_or(&state.lyrics, |preview| &preview.1)
.document;
for (index, line) in document.lines.iter().enumerate() {
let mut row = String::new();
let mut columns = 0;
for ch in line.chars() {
let char_width = ch.width().unwrap_or_default();
if columns + char_width > width && !row.is_empty() {
reader.rows.push((index, std::mem::take(&mut row)));
columns = 0;
}
row.push(ch);
columns += char_width;
}
reader.rows.push((index, row));
}
}
}
}
fn shell(frame: &mut Frame, state: &AppState, title: String) -> Rect {
let area = popup_area(frame.area());
let block = Block::bordered()
.title(title)
.border_style(theme::strong_border_for(state))
.title_style(theme::header_for(state));
let inner = block.inner(area);
frame.render_widget(Clear, area);
frame.render_widget(block, area);
inner
}
fn row(area: Rect, index: u16) -> Rect {
Rect::new(
area.x,
area.y.saturating_add(index),
area.width,
u16::from(index < area.height),
)
}
pub(super) fn draw_reader(frame: &mut Frame, state: &AppState, reader: &Reader) {
let playback = reader.lyrics(&state.lyrics);
let title = if playback.title.is_empty() {
" Lyrics ".into()
} else {
format!(" Lyrics · {} ", playback.title)
};
let inner = shell(frame, state, title);
if inner.height < 3 || inner.width < 4 {
return;
}
let body = Rect::new(inner.x + 1, inner.y + 1, inner.width - 2, inner.height - 2);
let active = reader.active_line(&state.lyrics, &state.player);
let version = playback.versions.get(playback.selected);
if let Some(version) = version {
let label = crate::lyrics::clean_text(&version.label).replace('\n', " ");
let loading = if playback.loading {
" · Looking for versions…"
} else {
""
};
frame.render_widget(
Paragraph::new(format!(
"{} / {} · {label}{loading}",
playback.selected + 1,
playback.versions.len()
))
.alignment(Alignment::Center)
.style(theme::dim()),
row(inner, 0),
);
}
if reader.rows.is_empty() {
let message = if playback.title.is_empty() {
"No music track selected".into()
} else if playback.document.instrumental {
"Instrumental".into()
} else if playback.loading {
format!("{} Looking for lyrics…", state.spinner())
} else {
"Could not find lyrics".into()
};
frame.render_widget(
Paragraph::new(message)
.alignment(Alignment::Center)
.style(theme::accent_for(state)),
row(body, body.height / 2),
);
} else {
let visible = usize::from(body.height);
let start = reader
.top
.unwrap_or_else(|| reader.follow_top(active))
.min(reader.rows.len().saturating_sub(visible));
for (offset, (index, text)) in reader.rows.iter().skip(start).take(visible).enumerate() {
let style = if Some(*index) == active {
theme::header_for(state)
} else if playback.document.timed() {
theme::dim()
} else {
ratatui::style::Style::default()
};
frame.render_widget(
Paragraph::new(text.as_str())
.alignment(Alignment::Center)
.style(style),
row(body, offset as u16),
);
}
}
let footer = if playback.document.timed() {
"↑↓ / PgUp PgDn scroll · f follow · ←→ version · esc close"
} else {
"↑↓ / PgUp PgDn scroll · ←→ version · esc close"
};
frame.render_widget(
Paragraph::new(footer)
.alignment(Alignment::Center)
.style(theme::dim()),
row(inner, inner.height - 1),
);
}
pub(super) fn draw_editor(frame: &mut Frame, state: &AppState, editor: &Editor) {
let inner = shell(frame, state, " Track lyrics ".into());
if inner.height < 4 || inner.width < 4 {
return;
}
let body = Rect::new(inner.x + 1, inner.y, inner.width - 2, inner.height - 1);
let mut footer = if editor.busy {
"Working…"
} else {
"↑↓ select · a add · enter edit · d delete · esc back"
};
if let Some(draft) = &editor.draft {
if !editor.busy {
footer =
"Tab label/text · paste plain text or LRC · Ctrl+S / F2 save · esc cancel";
}
let label = if draft.label_focused {
super::line_edit_spans(&draft.label, usize::from(body.width.saturating_sub(7)))
} else {
vec![Span::raw(draft.label.as_str())]
};
let mut label_line = vec![Span::styled("Label ", theme::accent_for(state))];
label_line.extend(label);
frame.render_widget(Paragraph::new(Line::from(label_line)), row(body, 0));
let (cursor_row, cursor_col) = draft.text.line_cursor();
let height = usize::from(body.height - 1);
let start = cursor_row.saturating_sub(height.saturating_sub(1));
for (offset, text) in draft.text.split('\n').skip(start).take(height).enumerate() {
let line = if !draft.label_focused && start + offset == cursor_row {
let edit = crate::app::input::LineEdit::with_cursor(text, cursor_col);
Line::from(super::line_edit_spans(&edit, usize::from(body.width)))
} else {
Line::from(text)
};
frame.render_widget(Paragraph::new(line), row(body, offset as u16 + 1));
}
} else if editor.confirm_delete {
footer = "Enter / y delete · any other key cancels";
let label = editor
.versions
.get(editor.cursor)
.map(|version| version.label.as_str())
.unwrap_or_default();
frame.render_widget(
Paragraph::new(format!("Delete {}?", crate::lyrics::clean_text(label)))
.alignment(Alignment::Center)
.wrap(Wrap { trim: true }),
body,
);
} else if editor.versions.is_empty() {
let message = if editor.busy {
format!("{} Loading lyrics…", state.spinner())
} else {
"No saved lyrics. Press a to add a version.".into()
};
frame.render_widget(
Paragraph::new(message).alignment(Alignment::Center),
row(body, body.height / 2),
);
} else {
let start = editor
.cursor
.saturating_sub(usize::from(body.height).saturating_sub(1));
for (offset, version) in editor
.versions
.iter()
.skip(start)
.take(usize::from(body.height))
.enumerate()
{
let synced = if version.synced_lrc.is_some() {
"Timed"
} else if version.instrumental {
"Instrumental"
} else {
"Plain"
};
let label = crate::lyrics::clean_text(&version.label).replace('\n', " ");
let style = if start + offset == editor.cursor {
theme::header_for(state)
} else {
theme::dim()
};
frame.render_widget(
Paragraph::new(format!("{label} · {synced}")).style(style),
row(body, offset as u16),
);
}
}
frame.render_widget(
Paragraph::new(editor.error.as_deref().unwrap_or(footer)).style(theme::accent_for(state)),
row(inner, inner.height - 1),
);
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more