Compare commits

...
112 Commits
Author SHA1 Message Date
ab c911cb63e3 feat(opendeck): preview and reroll radio from liked tracks 2026-11-29 17:00:17 +02:00
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
Aleksandr Bogomiakov 038f0979af Release Furumi 0.5.0 with published FRID podcast crates 2026-11-20 14:17:49 +00:00
ab 81f422b244 Merge pull request 'Публичные подкасты в TUI: «Поделиться», поиск с типом podcast и «Подписаться» из карточки (MR-T3)' (#4) from sanapach/furumi-tui:podcasts/discovery into federation 2026-11-20 14:11:11 +00:00
ab 7659313dc2 Merge pull request 'Подкасты в TUI на контракте FRID: подписки, воспроизведение, прогресс, синхронизация устройств v4 (MR-T2)' (#3) from sanapach/furumi-tui:podcasts/tui into federation 2026-11-20 14:11:09 +00:00
ab 44d0bb5abe Merge pull request 'Порядок вкладок 1–6 с Podcasts на 4 и миграция keymap (MR-T1)' (#2) from sanapach/furumi-tui:podcasts/tab-order into federation 2026-11-20 14:11:00 +00:00
sanapachandClaude Opus 5.5 59d6a1fe24 Point frid deps at the fork branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:15 +02:00
sanapachandClaude Opus 5.5 409188b9a9 Publish podcast cards only after the first device sync
A device restarted with a "share" decision that another device of its
group revoked meanwhile sent that card again: the first reconciler pass
called sync_shares from the stale registers before device sync ran.
Until DeviceSync says the registers are current (a sync exchange with a
v4 device of the group after the store was attached, or no such device
to wait for), passes now only unpublish cards the local registers no
longer share and never call sync_shares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 ce5697ce1d Document held-back revocation and quitting during a revocation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 adfe809a40 Wait for in-flight revocations and track them with federation off
Share-off and unsubscribe now take a revocation ticket on the UI thread
before the write starts and ask for the immediate pass from the blocking
task once the write succeeded, so quitting right after Shift+F (before the
write's event was handled) still waits for the tombstone. With the
federation off or not started yet, a podcast that was shared counts as
possibly not revoked: the reconciler keeps it in the Off reports until the
overlay runs, the side panel says the card may not be revoked yet, and the
quit-time flush logs a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 d6962eba47 Keep public artwork whose path only looks random
Public podcast hosts and CDNs name artwork and pages by UUIDs and
content hashes, so the random-looking path rule dropped the artwork of
most public podcasts. Artwork and links now follow the query and host
rules only; a member feed's artwork is still left out with its feed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 43e0696531 Drop share confirmations whose decision was not written
A confirmation is recorded as pending before the share decision is
written and covers the next newer decision. When the write failed (the
podcast was unsubscribed by a sync meanwhile, a database error), the
pending entry stayed and later covered a decision taken on another
device that this user never saw. Put the previous entry back on failure,
and drop pending entries left in the file by a call that never finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 405f8ae6d3 Hold back unconfirmed private-looking cards before syncing
FRID's sync_shares keeps publishing a card whose feed URLs this device
already publishes, even without the privacy confirmation. A device that
missed an intermediate share-off would go on publishing a private-looking
URL nobody confirmed for the new decision. share_plan now leaves such a
podcast out of the states, so sync_shares revokes the old card, and
reports it as held back itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 3ddf7995e8 Document prompt revocation and moved-feed subscriptions
README, ARCHITECTURE, CHANGELOG and AGENTS describe the immediate
revocation and quit-time wait, decision-bound confirmations, the card
URL filter, devices that left the group, the separate bounded podcast
search, and which direction of a moved feed the search mark covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 17ed8bfcd4 Scroll the podcast card exactly to its end
The card and the share dialog measure their word-wrapped height the
way it is rendered (ratatui's rendered-line-info), and scroll keys stop
at the last line instead of running past it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 fd6827126f Recognize subscriptions under a feed's newer address
Subscribing to an older address whose feed announces a newer one this
device already follows (itunes:new-feed-url without a redirect) reports
the existing subscription instead of adding a second one, and a card
whose feed moved to a followed address reads «Уже подписан» once its
episodes were read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 744d56e06b Leave private-looking artwork and links out of cards
The share dialog shows the feed URLs only, so a card no longer carries
an artwork or web page URL that looks like it holds an access key, and
a member feed's card carries neither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 7add66920d Bind share confirmations to the share decision
A privacy confirmation now covers the share decision it was given for,
not only the URLs: sharing turned off, or turned on again after a
revocation, on any trusted device drops it, so this device asks again
before it publishes a feed URL that looks private.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 1137670229 Revoke podcast cards promptly and report unrevoked ones
Turning sharing off or unsubscribing runs a reconciler pass right away,
and quitting waits up to 4 s for it. The Podcasts tab tells a private
podcast whose card from this device is still live, failed revocations
are reported without ids, the overlay peer count stays current, and the
reconciler loop is tested against a loopback overlay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 a51f5552e3 Search public podcasts apart from the music search
Federated music results no longer wait for the discovery overlay: the
podcast search runs as its own task, bounded at 15 s including the
overlay's bootstrap, and arrives as its own event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 d38144fe45 Document finding public podcasts and bump to 0.5.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 160237b5a5 Test subscribing from a public podcast card
Cover the merge order of podcast hits, alias resolution, the feed
preview, subscribing from a card (same podcast id as by URL, never a
claimed URL, forged ids refused) and an end-to-end run: a stranger's
node finds a shared card over loopback overlay nodes, subscribes
privately, refreshes from a local feed server and keeps the
subscription after the publisher stops sharing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 e038f282c2 Find public podcasts in search and subscribe from their cards
Federated search also queries the podcast discovery overlay and lists
the podcast entries of merge_search_results after the music results,
marked [podcast], with the publishing devices or "subscribed" (also
through a feed alias resolved off the UI thread). Enter opens the card:
the publishers' claims, the origin feed URL, unverified moved-feed
claims, an optional episode preview read from the feed itself, and
«Подписаться», which subscribes privately with the origin URL only.
«Уже подписан» opens the podcast in the Podcasts tab instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 25a9f2b0ec Subscribe to a parsed feed URL
Split refresh::subscribe into input parsing and subscribe_url, so a
public card's origin URL can be subscribed to exactly as given, and let
the feed parser be reused for previews.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 6d225531a5 Document sharing podcasts in the federation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 8f4e58d8af Add a share toggle to the Podcasts tab
Shift+F in the podcasts context shares the selected or opened podcast
through PodcastStore::set_shared (a synced decision) or makes it private
again. A feed URL that looks private is confirmed first in a dialog that
lists the warnings in Russian. The reconciler runs after share and
unsubscribe actions, received podcast operations, feed refreshes, overlay
restarts and periodically; the list and side panel show the shared and
published state and publication errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 8c90035fa2 Reconcile own podcast publications with the share registers
podcasts::publication builds one PodcastShareState per subscription (cards
from the catalog for shared podcasts only, the device-local privacy
confirmation) and hands them to PodcastDht::sync_shares, which publishes
what is shared and tombstones the rest. Without a readable store every own
card is revoked. Privacy confirmations live in a 0600 JSON file next to
podcasts.sqlite3 and cover exactly the confirmed URLs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 c453b0a52f Run the podcast discovery overlay in the federation node
The node serves FRID's podcast_dht overlay next to the similarity overlay
(cache federation/podcast-dht.sqlite3), runs its maintenance, hands peer
capability manifests to note_peer_capabilities and advertises podcast_dht
only while the overlay runs. A cache that cannot be opened is logged and
only turns discovery off. The running overlay is exposed through a watch
channel for the publication reconciler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:13:07 +02:00
sanapachandClaude Opus 5.5 ea7cdc4b7f Point frid deps at the fork branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:12:14 +02:00
sanapachandClaude Opus 5.5 c7e6a3672d Test that an older Jam guest cannot drop the host's episodes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 01:51:02 +02:00
sanapachandClaude Opus 5.5 e0624ab7f4 Document what an older device's takeover does to a podcast queue
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:15:09 +02:00
sanapachandClaude Opus 5.5 2806e679ac Leave out placeholders an older device echoes back as music
A device below sync v4 mirrors the redacted queue it gets with its own
types, which drop PlaybackTrack::source, so each "Private item" becomes
a bare music item. When it takes playback over (Play on it, a
paused-startup claim, automatic failover) or sends a command, it
announces those items, and this device adopted unplayable fake tracks
and passed them on to every v4 peer. States from such devices are now
cleaned on receipt, with a status message once per change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:15:09 +02:00
sanapachandClaude Opus 5.5 d03a3300f1 Resume dropping prototype feed validators after an interrupted start
The prototype import commits inside PodcastStore::open and the imported
validators were dropped afterwards, once. A start that stopped in
between left them for good. A marker next to the store, written before
the import and removed once every podcast was handled, makes the step
run again at the next start. The imported failure count is recorded
again as it was, so the back-off is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:12:24 +02:00
sanapachandClaude Opus 5.5 42ecc310fc End a sizeless episode stream where it ends when only the feed knew its length
A stream without a file size whose decoder cannot measure its duration
only has the feed's itunes:duration, which is often longer than the
audio. Treat that duration as a hint: a clean close past 80 % of it is
the end. A duration the decoder measured keeps the strict completion
window. The interrupted message for a stream that cannot seek now says
to start over or mark the episode played instead of "press play".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:11:33 +02:00
sanapachandClaude Opus 5.5 96e615bf1d Refuse an episode seek without leaving the effect early
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:56:12 +02:00
sanapachandClaude Opus 5.5 34c096a36b Bound a whole feed fetch and test the fetch limits
A slow server could hold one of the four refresh slots for 60 s per
redirect hop. A feed or cover fetch now has an overall deadline (120 s).
Tests cover feeds over the size cap with and without Content-Length
(error recorded with back-off, catalog kept), the redirect cap, a
redirect loop, a non-http redirect, a hanging server, and covers (not an
image, over the cap, written atomically). The test server can stall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:53:44 +02:00
sanapachandClaude Opus 5.5 268ea915da Keep podcast store work in sync handlers off Tokio workers
The device-sync stream handlers exported and merged podcast snapshot
sections and operations synchronously on a Tokio worker. While a large
feed refresh held the store (up to about half a second), the worker's
other tasks (feed checks, streams, art) waited. Run that work in
block_in_place on the multi-thread runtime, and say so in ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:52:05 +02:00
sanapachandClaude Opus 5.5 e0da2ddf2b Move a feed to its permanent address behind a temporary redirect
A 301 to a new host followed by a 302 (CDN, tracker) never moved the
feed, because only all-permanent chains counted; every check then went
through the old address without validators and re-applied the whole
feed. The target of the leading permanent hops is now recorded as the
new fetch URL (the old one becomes an alias); the document is still
parsed against the URL that served it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:50:44 +02:00
sanapachandClaude Opus 5.5 fe373e4169 Parse imported prototype feeds on their first check
The prototype import keeps the prototype's ETag and Last-Modified, but
the prototype stored no seasons, episode numbers or types, and GUID-less
episodes stay provisional until the feed is parsed again. The first check
was answered 304 and a feed that no longer changes was never parsed.
Drop the imported validators right after the migration so the first
check downloads and applies the feed. Contract gap for the FRID import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:49:16 +02:00
sanapachandClaude Opus 5.5 42f22f0fea Document lost connections, cancellation and seeks of episodes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:47:41 +02:00
sanapachandClaude Opus 5.5 2989747162 Stop broken episode streams instead of completing them
- The stream reader records whether the decoder stopped on a read error
  and whether the server announced the file size. An episode whose
  connection was lost (stall, expired URL) or whose sizeless stream
  closed early is no longer completed at its full duration: the last
  position is saved, playback stops on the episode and the queue does
  not move on (playback::played_to_the_end).
- Streams are cancelled by the player's source generation: a superseded
  start stops connecting or reading up to its resume offset, and a read
  blocked inside the audio callback returns within 100 ms instead of up
  to 30 s. The player no longer reports the end of a superseded source.
- A pause or resume pressed while an episode connects is applied when
  its source arrives (Controller::expect_source).
- Seeks report their result (PlayerEvent::Seeked); an episode's seek is
  saved only when the audio moved, and seeks while connecting or in a
  stream without Range support are refused with a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:47:41 +02:00
sanapachandClaude Opus 5.5 8d87fe3959 Keep older devices hearing from a podcast queue owner
A device below sync v4 got no playback snapshot while the queue held an
episode, so its engine never heard the owner's heartbeat and took
playback over by automatic failover after two minutes; this device then
adopted its queue and the episodes were gone. Send such peers the
coordination envelope with the queue redacted like for Jam: every
episode becomes an opaque "Private item", nothing is stripped, and their
commands stay refused while the queue has episodes.

This departs from FRID PLAYBACK_PROTOCOL.md rule 1 ("send None") and is
reported as a contract gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:40:07 +02:00
sanapachandClaude Opus 5.5 70df945ada Keep podcast URLs out of the personal-sync debug log
Podcast operations and playback commands with episodes carry feed and
audio URLs that may hold private tokens; the Logs tab shows this crate's
debug output. Log only their kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:39:19 +02:00
sanapachandClaude Opus 5.5 a79f0a0e95 Save a seek from a controlling device as an explicit episode action
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:03:55 +02:00
sanapachandClaude Opus 5.5 c6d7848ba4 Document podcast sync between devices and release 0.4.0
README explains that podcast state is private by default, syncs only
between trusted devices and streams audio from the publisher, plus
handoff, Jam and older devices. ARCHITECTURE, AGENTS and the changelog
describe protocol v4, version gating, the podcast store bridge and the
invariants (no numeric ids for episodes, versions only from the device
itself).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:02:45 +02:00
sanapachandClaude Opus 5.5 a92e12f322 Hand off podcast queues to v4 devices and keep episodes private in Jam
Queue items now cross the wire with their explicit source: episodes as
PlaybackSource::PodcastEpisode, received ones as TrackItem episodes, and
the source mode filter never drops them. A handoff carries the episode,
position and pause; an episode that becomes current at position 0
resumes from its saved position. A podcast queue is not handed to a
device below v4 (it needs an update), and playback commands from such a
device are ignored while the queue has episodes. Controlling a v4 device
may queue episodes.

Jam hosts publish redacted snapshots, so guests see numbered private
placeholders. Guest commands that add episodes are dropped; their
placeholders are mapped back to the host's episodes, and changes that
drop or duplicate them, or seek in them, are refused. A guest leaving a
Jam drops the placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:00:39 +02:00
sanapachandClaude Opus 5.5 79372e00fc Sync podcast state with devices on protocol v4
This client now announces device-sync protocol 4. Podcast operations
are applied to the podcast store, kept in the log and relayed; those
that arrive before the store opens wait in sync_podcast_pending.
Snapshots carry the podcast sections, bounded by the shared limits and
by the line budget of each message, and are merged after the operations.
Operations, snapshot sections and playback state that need v4 are only
sent to peers that reported v4. Periodic progress checkpoints are
coalesced in the log, and the Podcasts tab reloads after changes from
other devices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:54:16 +02:00
sanapachandClaude Opus 5.5 4c3edbcd12 Store peer protocol versions as the peers report them
A device_profile_set and the pending pairing row used to store this
build's own protocol constant for another device, which would defeat
version gating. Self-reports (hello, pairing, the sender's own entry of a
devices list, its own profile announcement) now replace the stored
version and relayed profiles only raise it. Invites and profile
announcements carry the version, and the first start of a new version
announces it in the log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:44:14 +02:00
sanapachandClaude Opus 5.5 e7713269f2 Use the shared device-sync wire types
The private copies of the device-sync wire types are replaced by
music_dht::device_sync. Golden tests keep the furumi-tui 0.3.x types
verbatim and check that v3 messages serialize byte for byte the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:41:11 +02:00
sanapachandClaude Opus 5.5 253583b139 Complete episodes after a seek into their last seconds
The progress tracker's observation step is now a pure method with tests
for listening time (jumps and pauses do not count), pause saves, the
checkpoint interval and one-time completion. A seek no longer marks the
playback completed by itself, so seeking into the last seconds still
sends complete_session on the next tick. The episode list render test
covers the live position of the playing episode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:30:11 +02:00
sanapachandClaude Opus 5.5 54db2978e0 Document episode playback, queue identity and progress saving
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:28:36 +02:00
sanapachandClaude Opus 5.5 9321e82335 Play podcast episodes from the queue and save their progress
Episodes stream from the publisher through the prototype's bounded HTTP
Range reader (ported, URL queries redacted from errors). The audio URL and
resume position come from the store at play time; a 4xx on the audio URL
refreshes the feed once and retries with the address it now lists, and a
stream that cannot seek refuses to start at a saved position instead of
playing from the wrong place. Prepared sources reach the audio thread
with the player's source generation, so a slow stream never replaces a
newer start or stop, and with their start offset for position reporting.

Progress follows the FRID contract through one ordered writer thread:
start_session or restart on start, checkpoints every 20 s and on pause,
explicit seeks, complete_session near the end or at end of stream, and a
final save with the last seen position on stop, track change, handoff
and exit. A superseded session stops checkpointing until the next
explicit action; listening sessions are recorded at pause, completion
and end. Enter on an episode plays it after the current item, b starts
it over, a/A queue it, and mark played goes through the same writer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:28:36 +02:00
sanapachandClaude Opus 5.5 3567f5f395 Key queue items by source and keep episodes out of music-only paths
Podcast episodes share the sentinel id -1, so the queue key now checks
the episode id first (ep:...) and falls back to TrackItem::key instead of
local:{id}. Likes, playlists, metadata edits, music history, content-id
lookups, share links, similarity and artist/release jumps skip episodes;
Shift-J and the info popup open the podcast instead. Sync protocol 3
cannot carry episodes, so peers and Jam guests get the private-item
placeholder, handoff of a queue with episodes is refused and remote
SetState commands do not replace such a queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:12:01 +02:00
sanapachandClaude Opus 5.5 7583afaeba Box large AppEvent payloads after TrackItem grew
furumi-library 0.3.0 adds TrackItem.podcast, which makes TrackItem a few
hundred bytes larger. Box the track-info result and the federation status
in AppEvent so the event enum stays small (and clippy's
large_enum_variant does not fire on it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:00:36 +02:00
sanapachandClaude Opus 5.5 043caf1aaf Document podcast subscriptions and their runtime boundaries
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:58:37 +02:00
sanapachandClaude Opus 5.5 99c4d05dec Replace the Podcasts placeholder with subscriptions, seasons and episodes
The tab opens the FRID podcast store (podcasts.sqlite3, migrating a
prototype database in place; newer or foreign files are reported and left
unchanged) off the UI thread and shows subscriptions with unplayed counts
and check status, podcast -> seasons -> episodes navigation, and episodes
with saved position, played state, duration and date. Episode search,
played filter and order run as paged store queries with request sequence
numbers. Adding a feed, checking one or all feeds, marking played and
unsubscribing (with a confirmation that progress is kept) go through
Effect/AppEvent; a scheduler refreshes due feeds in the background.

New actions are bound in the podcasts keymap context and listed in a
Podcasts help section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:58:37 +02:00
sanapachandClaude Opus 5.5 07dcd0587c Fetch podcast feeds and stamp store actions from the sync log
Add src/podcasts: an HTTP client with conditional requests, hand-followed
redirects (permanent ones become feed aliases via PodcastStore::apply_feed),
size and time limits and a furumi user agent; subscribe and refresh flows
that parse feeds with the shared music-dht parser and keep the store's
local fetch state with exponential back-off and Retry-After.

DeviceSync::run_podcast_action hands PodcastStore actions stamps reserved
in the device-sync log and appends the operations they return with exactly
those stamps. Podcast operations stay out of outgoing sync batches until
this client speaks sync protocol v4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:54:48 +02:00
sanapachandClaude Opus 5.5 bc04587252 Bump music-dht to 0.6.0 and furumi-library to 0.3.0
TrackItem gained a podcast field; music literals set it to None. The
music-dht podcast-feed feature provides the shared RSS/Atom parser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:37:28 +02:00
sanapachandClaude Opus 5.5 595c886303 Show both keymap notice and logging warning at startup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:30 +02:00
sanapachandClaude Opus 5.5 78bf2cf583 Keep all tabs visible on narrow terminals and wrap the podcasts placeholder
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:30 +02:00
sanapachandClaude Opus 5.5 df7ad3c8b7 Reject a keymap version nested in a binding; fix macOS keymap path in docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:30 +02:00
sanapachandClaude Opus 5.5 df171208eb Document the new tab order and keymap version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:18:00 +02:00
sanapachandClaude Opus 5.5 e78f1627da Reorder tabs and migrate legacy keymap tab indices
Tabs are now 1 Library, 2 Playlists, 3 Queue, 4 Podcasts, 5 Settings,
6 Logs. The Podcasts tab is a placeholder that states podcasts are not
available in this build yet; it gets its own "podcasts" key context.

Keymap files gain an optional top-level `version`. The default keymap
declares `version = 2` and binds "6" to the Logs tab. Files without a
version (or with version 1) have their GoToTab indices remapped in
memory (3 -> 4, 4 -> 5, and 5 -> 3 for the prototype podcast build) with
a startup notice; the user's file is never rewritten. The help window
names the target tab instead of "Go to tab N".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:17:59 +02:00
Aleksandr Bogomiakov 292f17fee1 Added MODE status 2026-11-18 16:18:56 +00:00
Aleksandr Bogomiakov 3e46f21804 Fixed artist card fed update 2026-11-18 15:43:43 +00:00
Aleksandr Bogomiakov 7f0ca2984f Fixed artist card fed update 2026-11-18 15:41:54 +00:00
Aleksandr Bogomiakov 0ad3844d37 Bump 2026-11-16 00:17:50 +00:00
Aleksandr Bogomiakov 2253ec7d91 Added simple status visual 2026-11-15 23:48:33 +00:00
Aleksandr Bogomiakov 8dd3ededf6 Fixed queue bug 2026-10-10 00:19:10 +01:00
Aleksandr Bogomiakov 81fdcf13ae Fixed queue bug 2026-10-10 00:18:07 +01:00
Aleksandr Bogomiakov a6d502e319 Fix duplicate queue playback position 2026-10-09 23:54:07 +01:00
Aleksandr Bogomiakov 3298204f2e Bump lock 2026-10-09 15:42:17 +01:00
Aleksandr Bogomiakov 9155bb9e00 Fixed release fed search regression 2026-10-09 15:34:20 +01:00
ab b07bcd4ddd Added fix 2026-09-10 22:56:06 +03:00
ab 966cf4b437 Fix connected devices 2026-09-10 18:05:00 +03:00
ab 532d6ee1e9 Integrate shared playback coordination and release 0.3.1 2026-09-10 17:07:41 +03:00
ab 5a193d839f Reworked settings menu 2026-09-07 13:06:46 +03:00
ab 7d6af59e97 fix lock 2026-09-07 12:41:27 +03:00
ab 32c976beb8 Added self updater 2026-09-07 12:36:48 +03:00
Ultradesu 2607314da3 Fix lock 2026-09-02 15:50:41 +01:00
Ultradesu f901836929 fix federation recovery after sleep 2026-09-02 15:10:20 +01:00
Ultradesu 0c30cdfcc6 Added ogg opus support 2026-08-14 11:42:54 +01:00
Ultradesu cfc0bfa0e5 Moved library to FRID 2026-08-11 18:13:02 +01:00
Aleksandr Bogomiakov 079d87a831 Merge local and federated similarity results 2026-08-10 20:51:21 +01:00
Aleksandr Bogomiakov add764e51d Stabilize similarity and library status cards 2026-08-10 20:18:51 +01:00
Aleksandr Bogomiakov 87cb7fe74c Route similarity search through the DHT 2026-08-10 19:40:37 +01:00
Aleksandr Bogomiakov e95d2e7fe1 Added similarity search feature 2026-08-10 00:37:50 +01:00
Aleksandr Bogomiakov 03f74cc91e Add federated music similarity search 2026-08-10 00:22:20 +01:00
Aleksandr Bogomiakov c971e81eed Many UI changes 2026-08-02 03:04:16 +01:00
Aleksandr Bogomiakov f73e3e7b95 Added nix files. revorked queue append, added library migration. 2026-08-02 00:40:50 +01:00
Ultradesu cced546cd5 Fixed invite logic to be lightweight 2026-07-29 14:24:22 +01:00
Ultradesu 52c2f7f7fe Fixed invite logic to be lightweight 2026-07-29 14:21:01 +01:00
Ultradesu 9b9f5d9ce5 Global is default mode 2026-07-29 10:52:57 +01:00
155 changed files with 51576 additions and 6090 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
+82 -3
View File
@@ -13,6 +13,9 @@ env:
CARGO_NET_RETRY: 10 CARGO_NET_RETRY: 10
jobs: jobs:
build-opendeck:
uses: ./.github/workflows/opendeck.yml
build: build:
name: Build ${{ matrix.asset_name }} name: Build ${{ matrix.asset_name }}
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
@@ -48,7 +51,7 @@ jobs:
run: cargo fetch --locked run: cargo fetch --locked
- name: Build - name: Build
run: cargo build --release --locked --offline run: cargo build -p furumi_tui --release --locked --offline
- name: Package - name: Package
shell: bash shell: bash
@@ -78,7 +81,10 @@ jobs:
publish: publish:
name: Publish release assets name: Publish release assets
needs: build concurrency:
group: release-assets-${{ github.ref }}
cancel-in-progress: false
needs: [build, build-opendeck]
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: write contents: write
@@ -89,7 +95,9 @@ jobs:
- name: Download build artifacts - name: Download build artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
pattern: furumi-*
path: artifacts path: artifacts
merge-multiple: true
- name: Create release and upload assets - name: Create release and upload assets
env: env:
@@ -98,7 +106,78 @@ jobs:
run: | run: |
set -euo pipefail set -euo pipefail
gh release create "$RELEASE_TAG" artifacts/*/* \ version="${RELEASE_TAG#v}"
archives=(
"artifacts/furumi-linux-x86_64-$version.tar.gz"
"artifacts/furumi-macos-aarch64-$version.tar.gz"
"artifacts/furumi-windows-x86_64-$version.zip"
"artifacts/furumi-opendeck-windows-$version.zip"
"artifacts/furumi-opendeck-macos-$version.zip"
"artifacts/furumi-opendeck-linux-$version.zip"
)
for archive in "${archives[@]}"; do
[[ -s "$archive" ]] || { echo "::error::Missing release archive $archive"; exit 1; }
done
assets=$(mktemp)
if ! gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' > "$assets"; then
for archive in "${archives[@]}"; do
(cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")")
done > SHA256SUMS
gh release create "$RELEASE_TAG" "${archives[@]}" SHA256SUMS \
--title "furumi ${RELEASE_TAG}" \ --title "furumi ${RELEASE_TAG}" \
--notes "Release ${RELEASE_TAG}" \ --notes "Release ${RELEASE_TAG}" \
--verify-tag --verify-tag
exit 0
fi
# 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"
+50 -3
View File
@@ -61,8 +61,30 @@ update it only when dependencies change.
- `src/player/` owns rodio playback and audio analysis. - `src/player/` owns rodio playback and audio analysis.
- `src/federation/` owns DHT discovery, peer catalogs, audio exchange, and - `src/federation/` owns DHT discovery, peer catalogs, audio exchange, and
federation caches. federation caches.
- `src/podcasts/` owns podcast feed HTTP and refresh policy, the episode
stream reader (HTTP Range, bounded buffer) and the ordered progress writer;
podcast identity, merge rules and the SQLite store come from FRID
(`music_dht::podcast`, `furumi_library::podcasts`) and must not be
re-derived here. Public podcast cards are published only through
`podcasts::publication` (`PodcastDht::sync_shares` over the merged
registers): never publish a podcast directly, never log feed URLs or ids of
podcasts that are not shared, never put progress, history, counters or
device names into a card. A local share-off or unsubscribe asks for an
immediate pass (`Reconciler::revoke_now`), which quitting waits for, and
privacy confirmations change only through `publication::set_shared` /
`ShareConfirmations` (bound to the share decision, never synced). Nothing
is published before `DeviceSync::podcast_registers_current` (a restarted
device may hold a revoked share decision); passes before it only revoke.
Public cards found by search are publisher claims:
subscribe and preview only through `podcasts::discovery`, which uses the
card's origin URL (`PodcastSearchHit::feed_url`), never a claimed URL, and
never stores card metadata. Queue items are identified by `state::track_key`
/ `TrackItem::key`, never by numeric id (every episode has the same sentinel
id); music-only code must skip `TrackItem::is_podcast()` items.
- `src/devices.rs` owns trusted-device replication, membership, and playback - `src/devices.rs` owns trusted-device replication, membership, and playback
coordination. coordination. Its wire types are the shared `music_dht::device_sync`
definitions; do not add local copies (golden tests in
`devices/wire_compat_tests.rs` keep the v3 JSON).
- `src/ui/` renders `AppState`; rendering code must not start background work - `src/ui/` renders `AppState`; rendering code must not start background work
or mutate persistence. or mutate persistence.
- `src/media.rs` owns OS media controls. - `src/media.rs` owns OS media controls.
@@ -155,7 +177,25 @@ When changing it:
- keep snapshots able to repair peers that missed older operations; - keep snapshots able to repair peers that missed older operations;
- treat membership and revocation as replicated durable state; - treat membership and revocation as replicated durable state;
- keep playback commands targeted and deduplicated; - keep playback commands targeted and deduplicated;
- test merge behavior from at least two operation orders. - test merge behavior from at least two operation orders;
- never store this build's protocol version for another device: use the
device's own report (`profile_protocol_version`) and only raise a stored
version from relayed profiles (`relayed_protocol_version`);
- gate everything a peer cannot parse by the version it reported: podcast
operations, podcast snapshot sections and playback state with podcast items
go only to v4 peers (`op_allowed_for_peer`, `SyncSnapshot::for_peer`,
`playback_allowed_for_peer`), a podcast queue is never handed to an older
device and its playback commands are ignored while the queue has episodes;
never strip episodes from a queue to make it fit an old peer; an older
peer still gets the playback coordination, with the queue redacted
(`redact_for_jam`), so its engine does not fail over, and the
"Private item" music entries it echoes back in its own states are left
out (`drop_echoed_private_items`), never adopted;
- apply podcast operations and snapshot sections only through
`PodcastStore` (`apply_remote_op`, `apply_snapshot`); never call the
podcast store while holding the sync-log connection;
- keep Jam snapshots redacted (`redact_for_jam`) and map guest placeholders
back with `restore_jam_private_items`.
Do not replace eventual reconciliation with assumptions about a continuously Do not replace eventual reconciliation with assumptions about a continuously
connected leader. connected leader.
@@ -186,6 +226,11 @@ The TUI is keyboard-first and cross-platform.
- Use semantic `Action` values rather than checking raw keys inside views. - Use semantic `Action` values rather than checking raw keys inside views.
- Add default bindings in `src/config/default_keymap.toml`. - Add default bindings in `src/config/default_keymap.toml`.
- Preserve user overrides and context-specific bindings. - Preserve user overrides and context-specific bindings.
- Tabs are ordered Library, Playlists, Queue, Podcasts, Settings, Logs
(`1`–`6`). `Tab::ALL` defines that order for the tab bar, Tab/Shift+Tab,
and `GoToTab` indices. Changing it, or the meaning of any other
positional action argument, requires a new `KEYMAP_VERSION` and an
in-memory migration of older keymap files; never rewrite the user's file.
- Account for narrow terminals, Unicode display width, and empty/loading/error - Account for narrow terminals, Unicode display width, and empty/loading/error
states. states.
- Restore raw mode, alternate screen, bracketed paste, and keyboard - Restore raw mode, alternate screen, bracketed paste, and keyboard
@@ -216,7 +261,9 @@ Add tests at the closest stable boundary:
- pure state transitions in `app/update_tests.rs`; - pure state transitions in `app/update_tests.rs`;
- SQLite behavior and migrations in `library/tests.rs`; - SQLite behavior and migrations in `library/tests.rs`;
- operation merge, tombstone, membership, and playback sync behavior in - operation merge, tombstone, membership, and playback sync behavior in
`devices/tests.rs`; `devices/tests.rs`; podcast sync between device stores and simulated v3
peers in `devices/podcast_sync_tests.rs`; wire shapes in
`devices/wire_compat_tests.rs`;
- search/ranking/federation conversion in `federation/tests.rs`; - search/ranking/federation conversion in `federation/tests.rs`;
- protocol-specific tests beside `federation/audio.rs` or - protocol-specific tests beside `federation/audio.rs` or
`federation/catalog.rs` when appropriate. `federation/catalog.rs` when appropriate.
+414 -4
View File
@@ -66,12 +66,27 @@ This layer connects devices owned or trusted by the same user. It carries
personal state such as: personal state such as:
- likes and playlist operations; - likes and playlist operations;
- podcast subscriptions, episode progress and listening sessions;
- device membership and revocation; - device membership and revocation;
- acknowledgements and synchronization progress; - acknowledgements and synchronization progress;
- playback state, commands, and handoff information. - playback state, commands, and handoff information.
Pairing establishes the trust relationship. After that, changes are replicated Pairing establishes the trust relationship. After that, changes are replicated
through an append-only operation log and applied to materialized local tables. through an append-only operation log and applied to materialized local tables.
The wire types are the shared `music_dht::device_sync` definitions (protocol
v4); golden tests keep the v3 JSON of furumi-tui 0.3.x byte for byte.
Each device stores the protocol version that the other devices report
themselves (their hello and pairing profiles, the sender's own entry of a
`devices` list, their own profile announcements). A relayed profile only
raises a stored version, because older relays list every device with their
own constant; this build never stores its own version for another device.
Everything a peer cannot parse is gated by that version: podcast operations,
podcast snapshot sections and playback state that contains podcast items
reach only v4 peers (`op_allowed_for_peer`, `SyncSnapshot::for_peer`,
`playback_allowed_for_peer`). An older client would reject a whole message
over one unknown operation kind, or silently drop an episode it does not
understand.
### Music federation ### Music federation
@@ -97,8 +112,12 @@ audio. Other TUI peers use a dedicated Jam ALPN to submit the same portable
playback commands used by connected-device control and receive the host's playback commands used by connected-device control and receive the host's
playback snapshot. They receive queue metadata, not audio. playback snapshot. They receive queue metadata, not audio.
Jam never exchanges trusted membership, likes, playlists, or listening Jam never exchanges trusted membership, likes, playlists, listening history
history. Volume remains local. Commands carry unique IDs and are retried until or podcast state. The host's podcast episodes are private: the published
snapshot replaces them with opaque placeholders (`redact_for_jam`), guest
commands that add episodes are dropped, and a guest's placeholders are mapped
back to the host's episodes (`restore_jam_private_items`); a change that
drops, duplicates or seeks in them is refused. Volume remains local. Commands carry unique IDs and are retried until
the host acknowledges them, while inactive participants expire from the the host acknowledges them, while inactive participants expire from the
runtime session. Regenerating the capability or restarting the host invalidates runtime session. Regenerating the capability or restarting the host invalidates
the previous link. the previous link.
@@ -123,6 +142,30 @@ The DHT is the distributed index. Nodes publish compact searchable
descriptions of their local library and query the network without contacting a descriptions of their local library and query the network without contacting a
central search service. central search service.
Opening a local artist or release card in a network-enabled library view
enriches it asynchronously. DHT matches identify likely catalog owners, while
a bounded set of known peers can also answer directly when the index is
incomplete. Card results are replaceable snapshots: reopening a card or
periodic maintenance retries discovery, with at most one request per card in
flight. A failed refresh keeps the last usable snapshot, and never prevents
browsing the local tracks.
Similarity discovery uses a separate schema-independent DHT overlay. A node
derives a deterministic 256-bit routing signature from every local embedding,
groups them into fixed two-level LSH buckets, and publishes compact summaries
containing only fine-bucket representatives, its peer identity, and the ticket
needed to dial a previously unknown owner. The owner signs every summary with
its existing transport key, so storage peers can relay and cache it but cannot
impersonate or modify it. Summaries expire with the ordinary library-record TTL
and are replaceable federation cache, never local library authority.
A similarity search first performs bounded multi-probe LSH lookups to rank
likely owners, then sends the existing normalized-vector request directly to
at most 16 peers initially and 48 on fallback. Known peers remain a rollout
fallback. The model, preprocessing, durable embeddings, exact cosine search,
and consent policy remain client-owned; `music-dht` owns only compatible
routing math, signed records, replication, and wire bounds.
Once a peer is known, communication moves to direct P2P streams provided by Once a peer is known, communication moves to direct P2P streams provided by
iroh through `music-dht`. Furumi defines separate application protocols for iroh through `music-dht`. Furumi defines separate application protocols for
catalog requests, audio transfer, and trusted-device synchronization. This catalog requests, audio transfer, and trusted-device synchronization. This
@@ -165,6 +208,12 @@ The synchronization model combines:
- per-peer acknowledgements to determine when old tombstones can be compacted; - per-peer acknowledgements to determine when old tombstones can be compacted;
- snapshots to repair a peer that missed older operations. - snapshots to repair a peer that missed older operations.
Vectors only grow, so operations hidden from a peer while it ran an older
protocol are never sent again after it upgrades. Snapshots are the recovery
path for that case; the podcast sections carry the subscription, share and
progress registers and the most recent listening sessions, bounded by the
shared FRID limits and by the line budget of each message.
This is eventual consistency scoped to a trusted device group. A temporarily This is eventual consistency scoped to a trusted device group. A temporarily
offline laptop can modify playlists, another device can continue playback, and offline laptop can modify playlists, another device can continue playback, and
both can later converge without a permanently available coordinator. both can later converge without a permanently available coordinator.
@@ -174,6 +223,13 @@ must propagate and converge, not an ephemeral server-side session flag.
## Playback across devices ## Playback across devices
A persisted device identity has exactly one live coordinator. The TUI holds
an OS file lock beside its device-sync database for the entire runtime; two
installations using the same user data directory cannot open it concurrently.
Network polling is independent per trusted peer, with one in-flight exchange
per peer and a bounded deadline. A stalled peer must not delay the next poll
of a healthy output. Poll tasks are cancelled when federation shuts down.
Playback has one logical state but remains physically local to the device Playback has one logical state but remains physically local to the device
producing audio. producing audio.
@@ -181,12 +237,40 @@ The synchronized state describes the queue, current item, position, pause
state, volume, shuffle/repeat mode, and the active playback owner. Commands are state, volume, shuffle/repeat mode, and the active playback owner. Commands are
targeted and deduplicated. Handoff transfers intent and position; the receiving targeted and deduplicated. Handoff transfers intent and position; the receiving
device resolves the track against its own library or federation sources before device resolves the track against its own library or federation sources before
starting its audio engine. starting its audio engine. Each queue item names its source: a podcast episode
travels as `PlaybackSource::PodcastEpisode` with the reference needed to play
it (the receiving device streams it from the publisher at the handed-off
position, with or without a subscription). A queue with episodes is not handed
to a device below protocol v4, and playback commands from such a device are
ignored while the local queue has episodes. Such a device still gets the
playback snapshot with its coordination envelope, but with every episode
replaced by an opaque "Private item" (`redact_for_jam`): an engine renews the
owner's liveness only from the owner's own announcements, so an old device
that heard nothing would take over by automatic failover after
`owner_timeout_ms` and replace the queue. This departs from FRID's
`PLAYBACK_PROTOCOL.md` rule 1 ("otherwise send `None`") and is reported to
FRID as a contract gap. An old device that mirrors such a queue drops the
`source` its types do not know, so each placeholder becomes a music item
titled "Private item"; when it later takes over (Play on it, a paused-startup
claim, failover while this device is gone) or sends a command, it announces
those. States from devices below v4 are therefore cleaned on receipt
(`drop_echoed_private_items`: bare music items with that title and no content
id, federated source, artist, release or duration), with a status message.
Active-device leases and idle timing prevent stale snapshots from immediately Active-device leases and idle timing prevent stale snapshots from immediately
taking control after a device reconnects. This provides practical coordination taking control after a device reconnects. This provides practical coordination
without introducing a central playback arbiter. 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 ## Local application architecture
Inside one node, Furumi uses an event-driven state machine: Inside one node, Furumi uses an event-driven state machine:
@@ -226,6 +310,191 @@ The audio engine is similarly isolated. The application owns the logical
queue, while `player::Controller` owns rodio playback and receives explicit queue, while `player::Controller` owns rodio playback and receives explicit
commands. Prefetching prepares the next source before the current item ends. commands. Prefetching prepares the next source before the current item ends.
### Versioned key bindings
Key bindings are semantic `Action` values loaded from the bundled defaults and
merged with the user's `keymap.toml`. Some actions carry positional meaning
(`GoToTab(index)` follows the displayed tab order), so changing the tab order
changes what an existing user file means. The keymap file therefore carries a
format `version`. Files from an older format are adapted in memory when they
are loaded and the user is told once per start; Furumi never rewrites a
user's configuration. The current format, version 2, orders tabs as Library,
Playlists, Queue, Podcasts, Settings, Logs; unversioned files use the earlier
order and have their tab indices remapped. A `version` key that TOML attached
to a binding (written after a `[[keymaps]]` header) is rejected, so a versioned
file is never silently mistaken for a legacy one.
## Podcasts
Podcasts are a separate content type, not library tracks. The shared contract
lives in FRID: `music_dht::podcast` defines podcast and episode identity, feed
URL canonicalization, the RSS/Atom parser and the merge rules, and
`furumi_library::podcasts::PodcastStore` persists the catalog, the personal
registers (subscription, share, progress) and listening sessions in
`podcasts.sqlite3`. The TUI does not re-derive ids or merge rules.
The TUI owns what the contract leaves to clients:
- **Fetching.** Feeds are fetched with conditional requests (ETag,
Last-Modified), bounded size (32 MiB per feed, 10 MiB per cover) and time
(15 s to connect, 60 s per request, 120 s for a whole fetch with its
redirects), and at most 10 redirects (http and https only) followed by
hand. The
address that the leading permanent hops (301/308) lead to becomes a feed
alias and the fetch URL, even when a temporary hop (CDN, tracker) follows
it; a chain that starts with a temporary hop never moves the feed.
Validators are dropped after a permanent redirect because they belong to
the old address. The prototype database's validators are dropped once at
import, so the first check parses the feed (seasons and episode numbers
were not stored by the prototype).
- **Scheduling.** The store keeps each feed's local fetch state (validators,
last error, consecutive failures, next check). A timer asks it which
subscriptions are due; feeds are checked at most a few at a time, a success
waits an hour, and failures back off exponentially (honouring
`Retry-After`). Errors never clear the stored catalog.
- **Runtime boundary.** Every store call, fetch and parse of the app runs on
the blocking pool or as a task and reports back through `AppEvent`s;
`update::podcasts` holds the pure state transitions. The device-sync
stream handlers call the store (snapshot export and merges) inside
`block_in_place`, so a store busy with a large feed refresh does not hold
a Tokio worker's other tasks; they are never called on the UI thread. Store open failures (newer schema,
foreign file) disable only the Podcasts tab and leave the file untouched.
- **Sync log.** Local actions (subscribe, unsubscribe, mark played, progress)
draw their operation stamps from the device-sync log through
`DeviceSync::run_podcast_action`, and the operations are appended with
exactly those stamps, so the store's registers and the log agree. The lock
order is podcast store, then sync log; device sync never calls the store
while it holds the log. Only the newest progress operation of an origin per
episode stays in the log (later operations of one origin always win the
register comparison).
- **Device sync.** Received podcast operations are kept in the log (and
relayed) and merged into the store with `PodcastStore::apply_remote_op`;
invalid ones are skipped but acknowledged. Operations that arrive before
the store opens wait in `sync_podcast_pending` and are applied when it is
attached. Snapshot sections are exported with `fill_snapshot` and merged
with `apply_snapshot` after the operations of the same message. The UI
reloads what it shows after such changes and checks the feed of a
subscription that came from another device.
- **Queue identity.** An episode is a `TrackItem` with an explicit
`podcast` reference (`TrackItem::podcast_episode`); its numeric id is a
shared sentinel and never identifies it. Queue keys check the episode id
first (`ep:…`), then music content ids, federated sources and library rows.
Music-only paths (likes, playlists, history, content-id resolution,
federation download, similarity, share links, metadata edits, release and
artist jumps) check `is_podcast()` and skip episodes. On the wire an
episode is `PlaybackSource::PodcastEpisode`; received ones become episodes
again (`TrackItem::from_playback_track`) and the library source mode never
drops them. Jam private placeholders are numbered queue entries that go
back on the wire as `PlaybackSource::Private`.
- **Playback.** Starting an episode resolves its current audio URL and
resume position from the store, opens `podcasts::stream` (a bounded
Range-request reader on its own thread), decodes and positions it with
coarse seeking, all off the UI and audio threads, then hands the source to
the audio thread with the player's source generation. Any later start or
stop bumps that generation, so a slow stream never replaces what the user
chose since. A stale audio URL (4xx) triggers one feed refresh and a retry
with the address the feed lists for the same episode id. A stream that
cannot seek does not start at a saved position it cannot reach, and seeks
in it (or in an episode still connecting) are refused. The stream is
cancelled by the same generation: a superseded start stops connecting or
reading up to its resume offset, and a read blocked on a stalled server
inside the audio callback returns within 100 ms, so it cannot hold the
audio thread past the next stop or start. The player does not report the
end of a superseded source. Pause and resume pressed while a source is
prepared update the intent it starts with.
- **End of a stream.** The reader records whether the decoder stopped on a
read error (lost connection, expired URL, cancellation) and whether the
server announced the file size. Only an end that the server described, or
one within the completion window, completes the episode and moves the
queue on; otherwise the last seen position is saved and playback stops on
the episode (`playback::played_to_the_end`).
- **Public discovery.** The federation node runs FRID's signed podcast
overlay (`music_dht::podcast_dht`, ALPN `furumi-fd/podcast-dht/1`, cache
`federation/podcast-dht.sqlite3`) next to the similarity overlay: it
serves the overlay, bootstraps, republishes and expires records, hands
every peer capability manifest to `note_peer_capabilities`, and advertises
`podcast_dht` in its own manifest only while the overlay runs. A cache
that cannot be opened is logged and only turns discovery off. What this
device publishes is decided by `podcasts::publication`: after local share
and unsubscribe actions (at once: `Reconciler::revoke_now`), received
podcast operations and feed refreshes (debounced 1 s), every overlay
(re)start and every 5 minutes it builds one
`PodcastShareState` per subscription (merged registers, a card from the
catalog for shared podcasts only, the local privacy confirmation) and
calls the declarative `PodcastDht::sync_shares`, which publishes what is
shared and tombstones every other own card. The share decision is the
synced `podcast_share_set` register, so share-off or unsubscribe on any
trusted device revokes every device's card and a stale device cannot
republish: until `DeviceSync::podcast_registers_current` turns true (a
sync exchange applied with a v4 device of the group after the podcast
store was attached, or no reachable v4 device in the group) a pass only
unpublishes the own cards its registers no longer share
(`publication::revoke_unshared`) and never calls `sync_shares`, whose
first call would re-send the cards FRID withholds from an earlier
session. Publication runs from each device's own identity. Privacy
confirmations of feed URLs that look private are device-local
(`podcast-share-confirmations.json`, mode 0600) and bound to the exact
URLs and to the share decision (the share register's operation): a newer
decision on any device drops them. Cards leave out artwork and web links
that look private, and both for a private-looking feed. Without a
readable podcast store this device revokes all its own cards. The report
of each pass lists the private podcasts whose own card is still live
(`unrevoked`: pending, failed or federation off) for the side panel; the
overlay peer count is refreshed every 10 s between passes. Before the
node stops on quit, `Reconciler::flush` waits up to 4 s for a revocation
requested just before. Logs carry counts only.
- **Finding and subscribing.** `Federation::search_podcasts`
(`podcasts::discovery::search`) runs `PodcastDht::search` as its own task,
bounded at 15 s including the overlay's bootstrap, apart from the music
search (`Federation::search`, unchanged), and delivers
`AppEvent::FedPodcastsLoaded` for the same search sequence, so music
results never wait for the overlay. The hits keep the podcast entries of
`merge_search_results` (exact titles first) as
`podcasts::discovery::PodcastHit`s. Off the UI thread each hit's origin
URL is resolved with
`PodcastStore::resolve_podcast_id`, and the "subscribed" mark compares
that id and the card's id with the subscribed podcasts, so a feed alias
counts. A card is a publisher's claim: only `PodcastSearchHit::feed_url`
(the origin URL the id is hashed from) is ever fetched, both for the
episode preview (`discovery::preview`, nothing stored) and for
«Подписаться» (`discovery::subscribe_from_hit` → `refresh::subscribe_url`),
which refuses a hit whose id does not match its URL and stores only what
the feed says. Claimed moved-feed URLs are displayed, never fetched or
recorded as aliases. The new subscription is private. Subscribing to an
address whose feed announces (`itunes:new-feed-url`) a newer one this
device already follows reports that subscription instead of adding a
second one, and the preview (`discovery::preview_for`) resolves the
address the feed moved to, so the card reads «Уже подписан» then.
- **Progress.** `podcasts::progress` runs one writer thread so every
progress write of this device is ordered. The app tick follows the
position and actual listening time and sends: an explicit start (or
"start over"), checkpoints every 20 s and on pause, explicit seeks (saved
once the audio thread reports that the seek worked,
`PlayerEvent::Seeked`), completion (`reaches_completion` or the real end
of the stream) and an end with the last
seen position on stop, track change, handoff and exit. When the store
reports a newer generation (another device started over, for example), the
playback stops checkpointing until the user's next explicit action.
Listening sessions are recorded at pause, completion and end; the store
keeps those that pass the shared threshold. Queue items carry the latest
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 ## Scripted visualizations
Visualizations are an extension boundary rather than hard-coded rendering Visualizations are an extension boundary rather than hard-coded rendering
@@ -237,6 +506,9 @@ rodio source
│ │
v v
audio analyzer ──> normalized features + scope samples audio analyzer ──> normalized features + scope samples
│ (PCM history, channel levels)
v
display meter ───> third-octave spectrum, L/R levels, peak hold
│ │
v v
Rhai render(input) Rhai render(input)
@@ -255,6 +527,36 @@ script implements `render(input)` and returns declarative commands such as
clear, cell, line, rectangle, trace, and text. Scripts never receive the clear, cell, line, rectangle, trace, and text. Scripts never receive the
ratatui frame or audio engine directly. 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: This command boundary is intentional:
- scripts remain independent of Rust UI internals; - scripts remain independent of Rust UI internals;
@@ -270,6 +572,17 @@ created or edited while Furumi is running without rebuilding or restarting the
application. Bundled scripts use the same path and contract as user scripts, application. Bundled scripts use the same path and contract as user scripts,
so built-in and custom visualizations exercise the same runtime. so built-in and custom visualizations exercise the same runtime.
The v2 primitives are sufficient for small perspective wireframes without a
native 3D engine. The bundled morphing cube transforms eight vertices in Rhai
and batches its twelve edges into trace/vertical-line commands. Perspective,
audio-driven deformation, and depth cues stay in the user-editable script;
Rust rasterizes the resulting 2D commands. This deliberately avoids per-cell
script command maps and does not provide filled meshes or a depth buffer.
The richer cube preset adds bounded particle, ring, inner-cage, and echo
layers. Echo poses are reconstructed from earlier times with current audio
features, rather than retaining previous frames; particles have deterministic
lifetimes. Small terminals omit expensive layers and reduce particle counts.
The Rhai engine is configured as a sandboxed computation environment. Module The Rhai engine is configured as a sandboxed computation environment. Module
loading through `import` and `export` is disabled, no filesystem or network API loading through `import` and `export` is disabled, no filesystem or network API
is exposed to scripts, and execution is bounded by limits on operations, call is exposed to scripts, and execution is bounded by limits on operations, call
@@ -282,20 +595,99 @@ intended role: transforming current audio features into drawing commands. It
is not a plugin mechanism for accessing the library, network, or player is not a plugin mechanism for accessing the library, network, or player
controls. controls.
Fullscreen execution currently happens synchronously during UI drawing, with a fresh
Rhai scope for each frame; 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
storage or expensive custom scripts can still delay input. Benchmark script
evaluation and buffer drawing separately from real terminal throughput before
increasing scene complexity or the refresh rate.
The embedded status surface uses the same Rhai engine, input map, command
decoder, and clipped buffer rasterizer with a one-row viewport. It has an
independent AST cache and a fixed user-editable script in
`visualizations/status/braille.rhai`, installed if absent. Exact copies of the
previous bundled default can be atomically upgraded; edited files are preserved. It is not a
fullscreen preset. During local playback the visual timer samples the audio
analyzer without increasing trusted-device publication frequency. At most
one blocking render job is in flight; excess ticks are dropped. File access,
compilation, evaluation, and buffer preparation happen on that worker.
An `AppEvent` delivers a prepared row to `AppState`; UI drawing only copies
cells. Its audio input comes from the decoded-source analyzer before output
volume scaling; the volume field remains informational. Pause suspends jobs
and retains the last frame, even when the row needs resizing. Generation
checks discard results invalidated by track changes, resize, pause/resume,
or stop. Script errors are confined to the row and retried so
editing the file repairs the display. Status scripts have a smaller operation
budget, bounded source/output sizes, and cannot draw outside their viewport.
## Music-similarity indexing
Similarity search is an optional local capability and is disabled by default.
When enabled, a background pipeline downloads a selected ONNX model, verifies
its pinned SHA-256 digest, decodes durable local tracks, and stores normalized
embeddings in the library SQLite database. Embeddings are keyed by an exact
fingerprint of the model artifact and preprocessing profile. Old profile rows
remain available while a new profile is calculated, and the in-memory exact
cosine index switches only after the replacement profile is usable.
The SQLite rows are the canonical derived store. The in-memory index can be
discarded and rebuilt, and neither is required for import, browsing, or
playback. Remote/cache-only tracks are never scheduled for local embedding.
Federated similarity uses a separate versioned direct-stream protocol. With
explicit privacy consent, the requester sends only a normalized embedding and
its profile fingerprint to a bounded set of known peers. It does not publish
queries to the DHT. Each peer searches its own active local index and returns a
bounded metadata result with a compact embedding SimHash. The requester uses
that signature to suppress near-duplicate recordings across peers without
receiving every result vector. Fan-out, concurrency, message sizes, and
timeouts are bounded; incompatible profiles are rejected. This direct
peer-selection layer can later be replaced by DHT routing without changing
local storage or ranking.
## Persistence boundaries ## 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: Furumi stores different kinds of state according to their lifetime:
| State | Storage | Role | | State | Storage | Role |
| --- | --- | --- | | --- | --- | --- |
| Library, playlists, likes, history | SQLite | Durable local source of truth | | Library, playlists, likes, history | SQLite | Durable local source of truth |
| Podcast subscriptions, episodes, progress | SQLite (`podcasts.sqlite3`, FRID store) | Durable personal state (synced with trusted devices) and a refreshable episode catalog |
| Podcast share confirmations | JSON next to `podcasts.sqlite3` | Device-local consent to publish feed URLs that look private |
| Public podcast cards (own and replicas) | SQLite (`federation/podcast-dht.sqlite3`) | Discovery overlay cache; replaceable |
| Device operation log and replicas | SQLite | Offline synchronization | | Device operation log and replicas | SQLite | Offline synchronization |
| Versioned track embeddings | SQLite | Durable, locally rebuildable similarity data |
| Federation catalog cache | SQLite/cache | Faster network browsing | | Federation catalog cache | SQLite/cache | Faster network browsing |
| Audio and artwork cache | Filesystem cache | Reusable fetched data | | Audio and artwork cache | Filesystem cache | Reusable fetched data |
| Settings, keymap, identity | Platform config/data dirs | Node configuration | | Settings, keymap, identity | Platform config/data dirs | Node configuration |
| Queue and playback snapshots | Application/device sync state | Continuity and handoff | | Queue and playback snapshots | Application/device sync state | Continuity and handoff |
Caches are replaceable. The local library and device operation log are durable. Caches are replaceable. The local library, the podcast store's personal state
and the device operation log are durable.
This distinction lets maintenance and recovery code discard derived network This distinction lets maintenance and recovery code discard derived network
data without risking the user's collection. data without risking the user's collection.
@@ -321,7 +713,14 @@ The source tree follows the architectural responsibilities:
- `library/` owns the local catalog and import pipeline; - `library/` owns the local catalog and import pipeline;
- `player/` owns audio playback and analysis; - `player/` owns audio playback and analysis;
- `similarity.rs` owns model acquisition, preprocessing, background indexing,
and the replaceable exact in-memory index;
- `federation/` owns DHT-facing search, peer catalogs, and audio exchange; - `federation/` owns DHT-facing search, peer catalogs, and audio exchange;
- `podcasts/` owns feed HTTP (conditional requests, redirects, limits),
refresh scheduling policy, the episode stream reader and the progress
writer, the publication of shared podcasts and subscribing from public
cards; the podcast model,
identity, merge rules, SQLite store and discovery overlay come from FRID;
- `devices.rs` owns trusted-device replication and playback coordination; - `devices.rs` owns trusted-device replication and playback coordination;
- `app/` owns state transitions and runtime orchestration; - `app/` owns state transitions and runtime orchestration;
- `ui/` renders the TUI; - `ui/` renders the TUI;
@@ -346,3 +745,14 @@ Future changes should preserve these rules:
5. Network and storage work must remain outside the interactive UI path. 5. Network and storage work must remain outside the interactive UI path.
6. More peers should improve availability; losing peers should only reduce 6. More peers should improve availability; losing peers should only reduce
remote capabilities. 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.
+266
View File
@@ -0,0 +1,266 @@
# Changelog
All notable changes to Furumi are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [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
- Sharing a podcast in the federation (`Shift+F` in the `podcasts` context,
off by default): the synced share decision makes each device publish a
signed public card of the podcast in the FRID discovery overlay
(`podcast_dht`, advertised in the capability manifest); share-off and
unsubscribe revoke it with a tombstone. Feed URLs that look private are
published only after a confirmation on that device. The list and side
panel show whether a podcast is shared and whether this device publishes
it.
- Turning sharing off or unsubscribing revokes this device's card at once,
and quitting waits up to 4 s for that (also for a change still being
saved); the side panel says when a private podcast's card is not revoked
yet (pending or failed) or may not be (federation off: a card of an
earlier session cannot be ruled out). A privacy confirmation covers one
share decision: turning sharing off (or on again after that) on any
trusted device asks again, and until then this device holds the podcast
back and revokes the card it published for the earlier decision. A
confirmation whose decision could not be saved is dropped. Cards leave out
artwork and web links with an access key in the query or a member-feed
host (random-looking path parts of public CDNs are fine), and both for a
feed whose URL looks private.
- A device with other devices in its group publishes its cards only after
it synced with one of them since it started (or once none is left that
syncs podcasts), so a device that was closed while sharing was turned off
elsewhere does not send that card again; until then it only revokes, and
the side panel says it waits for a sync.
- Search (`/`, with the federation running) also finds public podcast cards.
They are listed after the music results under "Podcasts · public cards" with
a `[podcast]` marker, the number of publishing devices, and "✓ subscribed"
when this device is subscribed (also through a feed alias). The podcast
search runs apart from the federated music search (bounded at 15 s), so
music results never wait for it; local-only search is unchanged.
- Enter on a podcast hit opens its card: title, author, categories,
description, episode count, newest episode, publishing devices, feed URL
and unverified moved-feed claims. `e` reads the seasons and episodes from
the feed without subscribing. «Подписаться» (Enter) subscribes privately
with the card's origin feed URL, so the podcast id is the card's, and
reads everything from the feed itself; «Уже подписан» opens the podcast
in the Podcasts tab instead, also when this device follows the feed under
the newer address it moved to (known once the feed was read), and
subscribing to such an older address adds no second subscription.
- A Podcasts tab on `4`: subscribe to RSS/Atom feeds by URL, browse
podcast → seasons → episodes with saved position, played state, duration and
date, search episodes, filter by listening state, change the order, mark
episodes played or unplayed, check one or all feeds, and unsubscribe (progress
and history are kept). Feeds are checked in the background with conditional
requests and back-off; permanent redirects become feed aliases.
- Podcast data uses the shared FRID store (`furumi_library::podcasts`) in
`podcasts.sqlite3`; a database of the earlier podcast test build is migrated
in place, and a newer or foreign file is refused without changes.
- Podcasts sync between trusted devices (device-sync protocol 4):
subscriptions, unsubscribing, feed addresses, episode progress ("played",
position, "start over") and listening sessions. A podcast subscribed on one
device appears on the others without its URL; each device checks the feed
itself. Podcast operations are applied to the podcast store, kept in the
sync log and relayed; snapshots carry the podcast state (bounded) so new
devices and devices that upgrade from an older version catch up. Periodic
progress saves are coalesced in the log.
- A queue with podcast episodes is handed to other devices with the episode,
its position and pause; the receiving device does not need the
subscription.
- Podcast episodes play from the Podcasts tab and the shared queue (mixed
with music): audio streams from the publisher through a bounded HTTP Range
buffer, Play continues from the saved position, `b` starts over, and the
position is saved every 20 s and on pause, seek, stop, track change and
exit. Completion and listening sessions follow the shared FRID rules. A
stale audio URL triggers one feed check for the episode's new address. A
lost connection stops playback at the saved position (the episode is not
completed and the queue does not move on). Without a file size from the
server, a closed stream counts as the end within the completion window of
the duration the audio file states, or past 80 % of a duration only the
feed announced; a superseded or stalled stream
is cancelled at the next start or stop; pause pressed while an episode
connects is kept; seeks that do not move the audio are not saved.
- Podcast key bindings in the `podcasts` context: `o`, `/`, `Shift+R`,
`Ctrl+R`, `Shift+S`, `f`, `m`, `Shift+U`, `b`.
- An optional top-level `version` in `keymap.toml`; the current format is
`version = 2`, and a `podcasts` binding context.
### Changed
- `furumi-tui` 0.5.0.
- Use published `music-dht` 0.6.0 and `furumi-library` 0.3.0 from crates.io;
remove the temporary FRID fork patches.
- Self-update and release download links use the canonical
`Furumi-stack/furumi-tui` GitHub repository.
- Queue items are keyed by their source: podcast episodes by episode id,
library rows as `lib:<id>` instead of `local:<id>`. Likes, playlists,
music history, similarity, share links and metadata edits skip episodes.
- Device sync speaks protocol 4 and uses the shared `music_dht::device_sync`
wire types instead of private copies; v3 messages are unchanged byte for
byte (golden tests). Devices below protocol 4 never receive podcast
operations, podcast snapshot sections or a queue with episodes: handing
such a queue to them is refused ("needs a Furumi update"), and their
playback commands are ignored while the queue has episodes. They still get
the playback coordination, with each episode shown as "Private item", so
they do not take playback over after two minutes of silence. When such a
device does take over, the "Private item" entries it echoes back as music
are left out of the queue here, with a status message.
- Jam guests see the host's podcast episodes as "Private item" (no title,
feed or address). Guest changes that add, drop or duplicate them, or seek
in them, are refused; a guest leaving a Jam drops the placeholders.
- Controlling another v4 device may queue and play episodes there; an
episode started by another device's command at position 0 resumes from its
saved position.
- Tab order is now `1` Library, `2` Playlists, `3` Queue, `4` Podcasts,
`5` Settings, `6` Logs, for the tab bar, Tab/Shift+Tab, and the default
number keys.
- Keymap files without `version` keep their tab shortcuts: `GoToTab` indices
are remapped in memory (3 → 4 Settings, 4 → 5 Logs, and 5 → 3 Podcasts
from the prototype podcast build) with a non-blocking startup notice. The
file is not rewritten; `version = 2` files are used as written. A `version`
key placed inside a `[[keymaps]]` entry is reported as an error instead of
being ignored.
- The tab bar shortens titles, then shows only numbers (keeping the active
tab's full title) on terminals too narrow for all six tabs.
- A keymap notice no longer hides a "logging disabled" startup warning; both
are shown.
- The help window names the target tab for number-key shortcuts
("Go to Settings") instead of "Go to tab N".
### Fixed
- Isolate log privacy and identity-lock lifecycle tests from process-wide
state and descriptor inheritance in parallel tests.
- The protocol version stored for another device came from this build's own
constant (on profile announcements and accepted pairings), not from the
device. Versions now come from the device's own reports; relayed profiles
only raise them. Invites and profile announcements carry the version, and
the first start of a new version announces it.
## [0.2.8] - 2026-09-02
### Added
- Optional offline music-similarity search for local tracks, backed by
versioned SQLite embeddings and a replaceable exact in-memory cosine index.
- Automatic SHA-256-verified download and local inference for the first ONNX
embedding model, with retained model/profile generations and background
backfilling of existing library tracks.
- Similarity settings for enablement, model/profile information, numeric worker
count, derived-data cleanup, processing progress, and federation privacy
consent.
- Track-seeded similarity search from the track-information popup, including
bounded federated queries to compatible known peers.
- The `furumi-fd/similarity/1` protocol in the visible protocol-version status.
- Decentralized `similarity_dht` routing with signed anonymous two-level LSH
summaries, multi-probe lookup beyond the locally known peer set, and known-
peer fallback during gradual network upgrades.
### Changed
- Similarity wire types, bounds, validation, and stream framing now come from
the shared `music-dht 0.4` API so native, web, and future clients can
interoperate without sharing an embedding implementation.
- Existing SQLite embeddings are backfilled once with compact 256-bit routing
signatures; new embeddings store them immediately without changing exact
local cosine search.
- A similarity result page keeps the source track first as query context while
excluding it from the actual nearest-neighbor ranking, labels the mode as
`Search similar to`, and suppresses near-identical embeddings across releases
and federated peer responses.
- Preprocessing profiles now open a read-only details window describing their
audio selection, resampling, spectrogram, patching, and aggregation contract.
### Fixed
- Federation now recovers automatically after sleep, prolonged idle, or a
degraded rendezvous transport while preserving local playback and state.
- Current-track information (`Shift+I`) now uses the enriched queue entry, so
it shows the same complete metadata and similarity action as `I` on that
track in the queue.
## [0.2.5] - 2026-08-02
### Added
- Command history navigation with the Up and Down arrow keys.
- A copy-friendly plain terminal view for connection tickets, device and Jam
invites, and track-sharing links.
- A configurable permanent music directory with write validation and an
optional safe migration of existing Furumi-managed files.
- Queue reordering for one track or a `Shift+V` selection with `Alt+K` and
`Alt+J`.
- Reproducible Nix/devenv tooling with Rust 1.97 and ALSA development files.
### Changed
- Sequential `a` actions now build one ordered play-next block instead of
reversing independently inserted tracks.
- Federated artist images and release covers are stored beside permanent music
in an `Artist/Release` directory tree.
### Fixed
- Running a development build next to another Furumi instance no longer lets
an MPRIS name collision disable terminal raw mode and freeze keyboard input.
- `nix develop` now keeps devenv state outside the read-only Nix store and
isolates Rust 1.97 build artifacts from other toolchains.
- Music-directory validation and migration now reject overlapping changes,
resolve canonical paths, and produce Windows-portable managed filenames.
[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
+1336 -308
View File
File diff suppressed because it is too large. Load diff
+33 -4
View File
@@ -1,39 +1,68 @@
[package] [package]
name = "furumi_tui" name = "furumi_tui"
version = "0.2.3" version = "0.6.1"
edition = "2024" edition = "2024"
rust-version = "1.97" rust-version = "1.97"
description = "A federated P2P player for personal music libraries" description = "A federated P2P player for personal music libraries"
license = "WTFPL" license = "WTFPL"
[workspace]
members = ["integrations/control-protocol", "integrations/opendeck"]
default-members = [".", "integrations/control-protocol", "integrations/opendeck"]
resolver = "3"
[[bin]] [[bin]]
name = "furumi" name = "furumi"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [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"
tempfile = "3"
fs2 = "0.4"
flate2 = "1"
tar = "0.4"
zip = { version = "4", default-features = false, features = ["deflate"] }
object = { version = "0.36", default-features = false, features = ["read", "std"] }
anyhow = "1.0.102" anyhow = "1.0.102"
blake3 = "1" blake3 = "1"
# 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" crokey = "1.4.0"
crossterm = { version = "0.29.0", features = ["event-stream"] } crossterm = { version = "0.29.0", features = ["event-stream"] }
directories = "6.0.0" directories = "6.0.0"
futures-util = "0.3.32" futures-util = "0.3.32"
furumi-library = "0.4.0"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] } image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
lofty = "0.22" lofty = "0.22"
# P2P federation: library index in a shared DHT + audio streaming between # P2P federation: library index in a shared DHT + audio streaming between
# peers (same protocol as furumi-fd). # peers (same protocol as furumi-fd).
music-dht = "0.3" # The library and player must share the same FRID podcast and lyrics types.
ratatui = "0.30.1" 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"] } rhai = { version = "1", features = ["sync"] }
rodio = { version = "0.22.2", default-features = false, features = ["playback", "mp3", "flac", "vorbis", "wav", "symphonia-aac", "symphonia-isomp4", "symphonia-alac"] } rodio = { version = "0.22.2", default-features = false, features = ["playback", "mp3", "flac", "vorbis", "wav", "symphonia-aac", "symphonia-isomp4", "symphonia-alac"] }
rusty-opus = "0.9.1"
rustfft = "6.4.1"
rusqlite = { version = "0.32", features = ["bundled", "functions"] } rusqlite = { version = "0.32", features = ["bundled", "functions"] }
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.150" serde_json = "1.0.150"
sha2 = "0.10.9"
souvlaki = { version = "0.8.3", default-features = false, features = ["use_zbus"] } 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" 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" toml = "1.1.2"
tracing = "0.1.44" tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
tract-onnx = "0.23.4"
unicode-width = "0.2.2" unicode-width = "0.2.2"
[patch.crates-io] [patch.crates-io]
+363 -2
View File
@@ -2,6 +2,8 @@
![furumi](furumi.png) ![furumi](furumi.png)
[![asciicast](https://asciinema.org/a/xSCEn090SS4gk8Hk.svg)](https://asciinema.org/a/xSCEn090SS4gk8Hk)
**Your music. Your devices. Your network.** **Your music. Your devices. Your network.**
Furumi is a federated P2P player for your personal music library. Every Furumi is a federated P2P player for your personal music library. Every
@@ -67,7 +69,20 @@ context-aware bindings, and user-defined rebinding through TOML. Built-in
audio visualizations, OS media controls, gapless queue playback, and local audio visualizations, OS media controls, gapless queue playback, and local
library management are included. Visualizations are runtime-loadable Rhai library management are included. Visualizations are runtime-loadable Rhai
scripts executed in a resource-limited sandbox, so they can be added or edited 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
privacy consent it can also ask a bounded set of federation peers for matches.
Compatible peers are selected through signed, anonymous LSH summaries in a
decentralized DHT; no central recommendation index or shared calibration file
is required.
The first selectable model is downloaded on demand and is licensed separately
by MTG under CC BY-NC-SA 4.0 (a proprietary license is also available from
MTG); Furumi itself remains WTFPL.
## Install ## Install
@@ -88,9 +103,12 @@ furumi
### Linux, Windows, and other platforms ### Linux, Windows, and other platforms
Download a prebuilt archive from the Download a prebuilt archive from the
[GitHub releases](https://github.com/house-of-vanity/furumi_tui/releases), or [GitHub releases](https://github.com/Furumi-stack/furumi-tui/releases), or
build Furumi from source with Rust 1.97 or newer: build Furumi from source with Rust 1.97 or newer:
The repository selects the stable Rust toolchain. With rustup, run
`rustup update stable` to install or update it before building.
```bash ```bash
cargo build --release --locked cargo build --release --locked
./target/release/furumi ./target/release/furumi
@@ -114,6 +132,277 @@ Import a music directory from Furumi's command line:
Federation, trusted-device pairing, and key bindings are configured directly Federation, trusted-device pairing, and key bindings are configured directly
inside the player. inside the player.
### Manual updates
In **Settings → Additional settings → Updates**, select **Check for updates**, then **Install update**
when a newer stable GitHub release is available. Downloads run in the background.
After installation, restart `furumi` to use the new version; playback is not
restarted automatically. Wait for an active update operation to finish before
quitting.
Updates replace the running executable in its installation directory, which
must be writable by your user. Release archives must include a matching entry
in the release's `SHA256SUMS` asset. Older releases without it cannot be installed
through this feature. The updater checks SHA-256 and the executable's format
and architecture before replacing it. Checksums provide integrity checking,
not publisher signatures. Settings and the local library are preserved.
There are no automatic startup checks. Only the existing release asset naming
scheme is supported; missing or incompatible platform builds are rejected.
The **Additional settings** window also contains the music save directory and
visualization controls. Use Up/Down (or j/k) to navigate, Enter to select, and
Esc to return to Settings. Long lists scroll with the selection.
### 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 /
Shift+Tab cycle through them:
| Key | Tab |
| --- | --- |
| `1` | Library |
| `2` | Playlists |
| `3` | Queue |
| `4` | Podcasts |
| `5` | Settings |
| `6` | Logs |
On narrow terminals the tab bar shortens titles and then shows only the
numbers, keeping the active tab's full name. Press `?` for the full list of
bindings and commands.
Bindings can be overridden in `keymap.toml` in the platform config directory
(`~/.config/furumi/keymap.toml` on Linux,
`~/Library/Application Support/furumi/keymap.toml` on macOS); the bundled
`src/config/default_keymap.toml` documents the format. Start the file with
`version = 2`, the current format: its `GoToTab` indices are used exactly as
written (`0` Library … `5` Logs). `version` must come before the first
`[[keymaps]]` entry; written after one, TOML would attach it to that entry, so
Furumi rejects such a file with an error instead of guessing. Files without `version` were written for the
older tab order (Settings and Logs on `4`/`5`, Podcasts on `6` in the
prototype podcast build); Furumi adapts their tab shortcuts in memory so they
keep opening the same tabs, shows a short notice at startup, and never
rewrites the file. Add `version = 2` once the indices match the new order to
take them literally and silence the notice.
### Podcasts
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
the URL serves a feed. New subscriptions are private.
- The list shows each podcast's unplayed and total episode counts and its
check status; `!` marks a podcast whose last check failed, with the error in
the side panel (or below the list on narrow terminals).
- `Enter` opens a podcast. Podcasts with seasons show their seasons first
(plus "All episodes" and "Without a season"); `Esc` goes back.
- Episodes show the date, season/episode number, duration and listening
state: `●` not started, `◐` in progress with the saved position, `✓` played.
`/` searches titles and descriptions, `f` cycles all / unplayed / in
progress / played, `Shift+S` changes the order, `m` marks the selected
episode played or unplayed.
- `Shift+R` checks the selected podcast for new episodes, `Ctrl+R` checks all
of them. Feeds are also checked in the background about once an hour with
conditional requests; a failing feed is retried with growing pauses and its
known episodes stay available. A permanent redirect moves the subscription
to the new address.
- `Shift+U` (or `Shift+D`) unsubscribes after a confirmation. Listening
progress and history are kept, so subscribing again continues where you
left off.
- `Shift+F` shares the selected (or opened) podcast in the federation, or
makes it private again. The list marks shared podcasts with `shared`, and
the side panel says whether this device publishes the card (see
"Sharing a podcast" below).
Episodes play in the same queue as music:
- `Enter` on an episode plays it right after the current item and continues
from the saved position; a played episode starts from the beginning. `b`
("start over") plays it from the beginning even when it is in progress.
`a` / `Shift+A` queue episodes like tracks, and the queue can mix music and
episodes.
- Audio streams from the publisher's server through a bounded buffer (about
9 MB) and seeks with HTTP range requests. Nothing is downloaded ahead of
time and nothing is kept after playback. If the server cannot seek (no
file length), Furumi says that it cannot continue at the saved position
instead of starting from the wrong place; "start over" still works, and
seeking in such an episode is refused with a message. If the episode's
address no longer works, the feed is checked once for a new one.
- If the connection is lost during an episode (no data for 30 seconds, or
the address stops working), playback stops there: the position is saved,
the episode is not marked played and the queue does not move on; play
continues from that position. A pause pressed while an episode is still
connecting is kept when the audio arrives.
- Some servers send episodes without a file size. There a closed connection
looks like the end of the file, so Furumi compares the position with the
episode's duration: the one the audio file states, or else the
`itunes:duration` of the feed. Feed durations are often a little off, so
reaching 80 % of one is enough; an episode that stops earlier is treated as
a lost connection. Such servers do not allow seeking either, so play cannot
continue in the middle: start the episode over (`b`) or mark it played
(`m`).
- The position is saved every 20 seconds while playing and on pause, seek,
stop, track change and exit. An episode counts as played within the last
30 seconds (or 5 %) or when its stream reaches its end; a listen enters the episode's
history when it completed or lasted at least 30 seconds. Seeking back and
"start over" are real changes: an older save never moves the position
forward again.
- Likes, playlists, music history, similarity search and share links are for
music only and skip episodes; `Shift+J` on an episode opens its podcast.
Podcasts and your connected devices:
- **Private by default.** Subscriptions, episode progress and listening
history are personal. They are synchronized only between your trusted
devices (Connected Devices), never published to the federation: no DHT
record, public catalog or search result contains them. Publishing a
podcast for discovery is a separate, explicit choice (`Shift+F`, below).
- **Synchronized between trusted devices.** A podcast you subscribe to on
one device appears on the others without typing its URL again; each
device then checks the feed itself. Unsubscribing, "played", the saved
position and "start over" follow the same way, also through a device
that relays them and after a device was offline for a while. When two
devices played the same episode offline, they agree on one position and
keep both listening sessions.
- **Handoff.** A queue with episodes moves to another device like music:
the episode continues there at the handed-off position, paused or
playing, even if that device is not subscribed. Devices that run an older
Furumi (device sync before v4) cannot keep episodes: handing such a queue
to them is refused with "needs a Furumi update", their remote control is
ignored while the queue has episodes, and they get no podcast data: they
see such a queue with "Private item" in place of each episode, so they
keep seeing this device as the playing one. An older device still takes
over when you choose it as the output (Play on it), when it starts while
this device is paused (`take_paused_on_startup`), or by itself once this
device has been closed, asleep or offline for about two minutes. Its queue
then has an unplayable "Private item" music entry for each episode; this
device shows that queue without them (with a status message), and the
episodes' saved positions stay.
- **Audio from the publisher.** Every device streams the episode from the
publisher's server itself. Furumi peers never pass podcast audio to each
other, and nothing is kept after playback.
- **Jam.** Guests see the host's episodes as "Private item" (no title, feed
or address), cannot add episodes to the host's queue and cannot seek in a
private item. They can still reorder the queue and skip.
Sharing a podcast (public discovery):
- `Shift+F` turns "share in the federation" on for one podcast. The choice is
synchronized to your trusted devices like a subscription; each of your
devices that runs the federation then publishes a small public card of the
podcast under its own device key: the feed URL, title, author,
description, artwork and web links, the number of episodes and the date of
the newest one. The card never contains your progress, history, play
counts, device names or anything from podcasts you did not share. Artwork
and web links that look like they carry an access key (a token, key or
signature in the query, a member-feed host) are left out, and so are both
for a feed whose own URL looks private. Random-looking parts of their
path alone do not count: public podcast hosts name artwork that way.
- If the feed URL looks private (a token, key or signature in its query, a
member-feed host such as Patreon, a long random-looking part), Furumi asks
first and lists why (in Russian). Anyone who finds the card can read the
feed at that URL. The confirmation is stored only on this device
(`podcast-share-confirmations.json` next to `podcasts.sqlite3`) and covers
exactly the URLs shown and this one decision to share: another device of
yours asks again before it publishes, and so does this one if the feed
moves or if sharing is turned off (or turned on again after that) on any
of your devices. Until then the side panel says the publication is held
back, and a card this device published for the earlier decision is
revoked; press `Shift+F` there to confirm (or `x` in the dialog to stop
sharing). A confirmation whose decision could not be saved is dropped.
- `Shift+F` on a shared podcast, or unsubscribing, makes it private again on
every device in your group: each device replaces its card with a signed
removal record. This device sends its removal right away, and quitting
waits for it (up to 4 seconds, also when you quit before the change is
saved) and logs a warning when a card may still be live. While the
removal is not sent yet (or could not be sent), the side panel says the
public card is not revoked yet instead of just "private". With the
federation off this device cannot tell whether a card of an earlier
session is still live, so for a podcast that was shared the panel says
the card may not be revoked yet; the removal is sent the next time the
federation runs. Until then, and for a copy that missed the removal, the
card can still be found until it expires (at most 12 hours). Removing your card never touches other
people's subscriptions. An older device that comes back with the earlier
"share" decision does not publish it again: after starting, a device with
other devices in its group publishes nothing until it has synced with one
of them (the side panel says "waiting for a sync with your other
devices"); it still revokes at once what its own decisions no longer
share. Devices of your group that still run Furumi 0.3 (they do not sync
podcasts) and devices without an address are not waited for; remove a
device you no longer use under Connected Devices so this one stops
waiting for it.
- A device that left your device group, or was removed from it, no longer
receives your share decisions: it keeps publishing the podcasts it shares
until you turn sharing off (or unsubscribe) on that device itself.
- The card is signed with this device's federation key, which is also the
key of its public music library, so a shared podcast can be linked to
that library and to the device's network address.
- Publishing needs the federation to be running; the side panel shows
"not published" with the reason otherwise.
Finding public podcasts:
- The search (`/` outside the Podcasts tab, with the federation
running) also looks for public podcast cards. They are listed after the
music results under "Podcasts · public cards", each marked `[podcast]`,
with the number of devices that publish the card (devices, not
subscribers; anyone can create devices, so it is not a sign of trust) or
"✓ subscribed" when this device already follows the podcast, also when
you subscribed under an older address of the same feed that moved to the
card's address. When you follow the feed under a newer address than the
card's, the list cannot tell yet; the card can once its episodes are read
(`e`), and «Подписаться» never adds a second subscription for it. Your
query words go to the discovery peers, as they do for music search. The
podcast search runs apart from the music search (music results never wait
for it) and gives up after 15 seconds. With the federation off, search
stays local and shows no podcasts.
- Enter opens the card (in Russian): what its publishers claim (title,
author, categories, description, number of episodes and date of the
newest one), the feed URL, and addresses some publishers claim the feed
moved to, shown as unverified and never used. `e` reads the feed itself
and lists its seasons and episodes without subscribing; this is a request
to the podcast's own server, not to the publisher.
- «Подписаться» (Enter) subscribes with the card's feed URL, the address
the podcast's id is derived from, so the podcast is the same one the
publisher shares. Furumi then reads the feed from its own server and
stores only what the feed says; the publisher does not need to stay
online, and nothing from the card is kept. The new subscription is
private like any other: it is not shared until you press `Shift+F`, and
your progress is your own. «Уже подписан» means this device is already
subscribed (under the card's address, an older one, or — once the feed
was read — the newer address the feed moved to); Enter then opens the
podcast in the Podcasts tab.
Podcast data lives in `podcasts.sqlite3` in the platform data directory (the
same file the earlier podcast test build used; it is upgraded in place). If
that file was written by a newer Furumi or is not a podcast database, the tab
explains why it is unavailable and the file is left unchanged; podcast
changes from other devices then wait in the device-sync log until it opens.
### Now playing in tmux ### Now playing in tmux
While Furumi is running, a second invocation can print a cheap, single-line While Furumi is running, a second invocation can print a cheap, single-line
@@ -144,6 +433,7 @@ Furumi is a Rust application built with:
- `ratatui` and `crossterm` for the cross-platform TUI; - `ratatui` and `crossterm` for the cross-platform TUI;
- `rodio` for local audio playback; - `rodio` for local audio playback;
- SQLite for the personal library and synchronization state; - SQLite for the personal library and synchronization state;
- tract ONNX inference for optional local music embeddings;
- a dedicated DHT for decentralized discovery; - a dedicated DHT for decentralized discovery;
- iroh-based P2P streams for client-to-client communication; - iroh-based P2P streams for client-to-client communication;
- an offline-tolerant operation log for trusted-device synchronization; - an offline-tolerant operation log for trusted-device synchronization;
@@ -162,6 +452,77 @@ cargo check --all-targets
cargo test --all-targets cargo test --all-targets
``` ```
## Playback coordination
Connected Devices uses the shared `music_dht::playback` engine from frid.
Newly started players take an idle/paused output after discovery and become
controllers when another device is playing. Missing output reports trigger
automatic failover; concurrent claims converge to one owner. The web gateway
uses a passive server profile and reports actual browser activity.
Only one TUI process may use a device identity. Installed and locally built
binaries use the same user data directory: close the installed player before
starting a development build. An OS file lock prevents duplicate coordinators
and is released automatically on exit or a crash. Older builds do not take
this lock, so close those explicitly when upgrading.
Connected-device polling runs independently per peer, so an offline or stalled
device does not postpone updates to live players.
The existing device menu handles manual transfers. Advanced policy can be set
in `settings.toml` without changing the UI:
```toml
[playback]
claim_on_startup = true
automatic_failover = true
take_paused_on_startup = true
discovery_ms = 3000
owner_timeout_ms = 120000
```
All clients must support the new coordination envelope for eventual single
output ownership. frid's `PLAYBACK_PROTOCOL.md` describes the protocol, adapter
contract and rollout. This release uses the published FRID crates
`music-dht 0.7.0` and `furumi-library 0.4.0` from crates.io.
Run the local protocol checks from the TUI repository:
```bash
cargo test localhost_devices_exchange_state_and_handoff
cargo test localhost_devices_sync_podcasts
cargo test devices::podcast_sync_tests
python scripts/test_device_interop.py ../furumusic
```
The first test uses real iroh streams, isolated SQLite databases, ownership
handoff, and a stalled peer. The podcast tests sync subscriptions, progress
and "start over" between TUI device stores (over iroh streams and through
the JSON messages), check a handoff with an episode and simulate a device
sync v3 peer with the exact JSON types of furumi-tui 0.3.x. The second builds both player test binaries and
exchanges their actual JSON messages over `127.0.0.1`: queue metadata,
bidirectional handoff, pause/seek and duplicate command fencing. It exercises
the TUI command adapter and web player hub, but does not start a browser or
PostgreSQL and does not cover web database migrations. Both tests use temporary
identities and data; no running player or user library is used.
## 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, role colors and a scrolling Neo Infobar.
Start similarity radio from the playing track, or tap the sparkles to preview
a random liked track for two seconds. Tap again to choose a different wave.
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 ## License
Furumi is released under the Furumi is released under the
+40
View File
@@ -0,0 +1,40 @@
{ config, lib, pkgs, ... }:
let
sourceRoot = builtins.toString ./.;
sourceKey = builtins.substring 0 12 (builtins.hashString "sha256" sourceRoot);
transientDotfile = "/tmp/furumi-tui-devenv-${sourceKey}";
rustToolchain = builtins.fromTOML (builtins.readFile ./rust-toolchain.toml);
rustVersion = rustToolchain.toolchain.channel;
in
{
# Pure flakes only expose their read-only store source. Keep devenv's own
# task/profile state writable, then restore the real checkout path in-shell.
devenv.root = sourceRoot;
devenv.dotfile = transientDotfile;
devenv.state = "${transientDotfile}/state";
languages.rust = {
enable = true;
toolchainFile = ./rust-toolchain.toml;
};
packages = [
pkgs.pkg-config
] ++ pkgs.lib.optionals pkgs.stdenv.isLinux [
pkgs.alsa-lib
];
env.RUST_BACKTRACE = "1";
enterShell = lib.mkAfter ''
export DEVENV_ROOT="$PWD"
# Keep Nix builds separate from artifacts produced by rustup or another
# devenv generation. Cargo metadata is not compatible across compilers.
export CARGO_TARGET_DIR="$PWD/target/devenv-rust-${rustVersion}"
export PATH="${config.languages.rust.toolchainPackage}/bin:$PATH"
export RUSTC="${config.languages.rust.toolchainPackage}/bin/rustc"
export RUSTDOC="${config.languages.rust.toolchainPackage}/bin/rustdoc"
hash -r
'';
}
+214
View File
@@ -0,0 +1,214 @@
# 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
The `start_radio` command 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`, an optional `request_id` matching the start command, 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.
### Radio from a liked track
When a snapshot advertises `liked_radio_supported: true`, a control surface
can preview a random liked music track, including while playback is idle.
Choosing reads the personal library and the active local similarity index.
The response goes to the requesting client. For example,
```json
{"type":"command","id":"pick-1","command":{"type":"pick_liked_radio_seed"}}
{"type":"liked_radio_seed","id":"pick-1","seed":{"key":"lib:7","title":"Nightfall","artist":"Northline"}}
```
On a reroll, pass the previous `seed.key` as `exclude`. Furumi picks a different
eligible track whenever possible. Replaying the same request ID returns the
cached choice. The preview has no playback or network side effects.
After displaying the chosen track, send its exact opaque key to start radio.
```json
{"type":"command","id":"start-1","command":{"type":"start_liked_radio","seed_key":"lib:7"}}
```
Furumi checks that the selected track is still liked and uses its embedding
for the same local and federated search as regular radio. Follow snapshots
where `radio.request_id` matches this start. To reroll a search already in
progress, send a fresh pick with `replace_request_id` set to that start ID.
It can supersede that liked-radio search until its queue is committed.
Selection errors use the usual rejected command result.
## 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.
Generated
+399
View File
@@ -0,0 +1,399 @@
{
"nodes": {
"cachix": {
"inputs": {
"devenv": [
"devenv"
],
"flake-compat": [
"devenv",
"flake-compat"
],
"git-hooks": [
"devenv",
"git-hooks"
],
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1777487137,
"narHash": "sha256-TuvKVBX60mqyMT6OB5JqVEh1YIWtFMR/igLCaCdC9tw=",
"owner": "cachix",
"repo": "cachix",
"rev": "a66a440c321d35f7193472c317f42a55ccd1cb93",
"type": "github"
},
"original": {
"owner": "cachix",
"ref": "latest",
"repo": "cachix",
"type": "github"
}
},
"crate2nix": {
"flake": false,
"locked": {
"lastModified": 1772186516,
"narHash": "sha256-8s28pzmQ6TOIUzznwFibtW1CMieMUl1rYJIxoQYor58=",
"owner": "rossng",
"repo": "crate2nix",
"rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e",
"type": "github"
},
"original": {
"owner": "rossng",
"repo": "crate2nix",
"rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e",
"type": "github"
}
},
"devenv": {
"inputs": {
"cachix": "cachix",
"crate2nix": "crate2nix",
"flake-compat": "flake-compat",
"flake-parts": "flake-parts",
"ghostty": "ghostty",
"git-hooks": "git-hooks",
"nix": "nix",
"nixd": "nixd",
"nixpkgs": [
"nixpkgs"
],
"rust-overlay": "rust-overlay"
},
"locked": {
"lastModified": 1785616853,
"narHash": "sha256-WKA53CfbSwXh/QuGHc3gsWoLNHYaKw4xgvkc9ceRgUA=",
"owner": "cachix",
"repo": "devenv",
"rev": "a3feed9ca96c66548496e8af2804d2a3a045d22e",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "devenv",
"type": "github"
}
},
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1767039857,
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-parts": {
"inputs": {
"nixpkgs-lib": [
"devenv",
"nixpkgs"
]
},
"locked": {
"lastModified": 1778716662,
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"flake-parts_2": {
"inputs": {
"nixpkgs-lib": "nixpkgs-lib"
},
"locked": {
"lastModified": 1782949081,
"narHash": "sha256-vp6Y/Grm98ESt6ceOkWiHWyZRDV3J1RID4w+6NWK9yA=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "17c9d6cdfc60c64f4ee8d306f9bc0b4ccb51481e",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"ghostty": {
"flake": false,
"locked": {
"lastModified": 1784602798,
"narHash": "sha256-298x90knBUWX5GHGXh2SKsAKvStjU2ri9UgOGoF79/8=",
"owner": "ghostty-org",
"repo": "ghostty",
"rev": "88b4cd047fa627cdca6781bc7e7dc8b75a2cecb9",
"type": "github"
},
"original": {
"owner": "ghostty-org",
"repo": "ghostty",
"type": "github"
}
},
"git-hooks": {
"inputs": {
"flake-compat": [
"devenv",
"flake-compat"
],
"nixpkgs": [
"devenv",
"nixpkgs"
]
},
"locked": {
"lastModified": 1782908218,
"narHash": "sha256-wLMOrPgVyeF3XmP+qfYcLqnVdTxikdcSvbIY7rA9jTA=",
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "9f7e99119ece7705299595299f3b031f39356de1",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "git-hooks.nix",
"type": "github"
}
},
"mk-shell-bin": {
"locked": {
"lastModified": 1677004959,
"narHash": "sha256-/uEkr1UkJrh11vD02aqufCxtbF5YnhRTIKlx5kyvf+I=",
"owner": "rrbutani",
"repo": "nix-mk-shell-bin",
"rev": "ff5d8bd4d68a347be5042e2f16caee391cd75887",
"type": "github"
},
"original": {
"owner": "rrbutani",
"repo": "nix-mk-shell-bin",
"type": "github"
}
},
"nix": {
"inputs": {
"flake-compat": [
"devenv",
"flake-compat"
],
"flake-parts": [
"devenv",
"flake-parts"
],
"git-hooks-nix": [
"devenv",
"git-hooks"
],
"nixpkgs": [
"devenv",
"nixpkgs"
],
"nixpkgs-23-11": [
"devenv"
],
"nixpkgs-regression": [
"devenv"
]
},
"locked": {
"lastModified": 1785349663,
"narHash": "sha256-JSD8lPe5kalvPKx5X+inX8ZZdGLeXkAbd3Jiv7UDf+I=",
"owner": "cachix",
"repo": "nix",
"rev": "f33db89fd6db6edc337d93212f6628ab6d25f407",
"type": "github"
},
"original": {
"owner": "cachix",
"ref": "devenv-2.34",
"repo": "nix",
"type": "github"
}
},
"nix2container": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1775487831,
"narHash": "sha256-2lguQpLPQaxpQCJjXhmEEAfabwsAhkP29Z7fgLzHARA=",
"owner": "nlewo",
"repo": "nix2container",
"rev": "76be9608a7f4d6c985d28b0e7be903ae2547df3e",
"type": "github"
},
"original": {
"owner": "nlewo",
"repo": "nix2container",
"type": "github"
}
},
"nixd": {
"inputs": {
"flake-parts": [
"devenv",
"flake-parts"
],
"nixpkgs": [
"devenv",
"nixpkgs"
],
"treefmt-nix": "treefmt-nix"
},
"locked": {
"lastModified": 1783935112,
"narHash": "sha256-IAQ14nteIKXAz4cd75UcZrsHGEVJ7QNrkUwX9rmeZ/Y=",
"owner": "nix-community",
"repo": "nixd",
"rev": "a64cd33e53b316b6b092ea0a966640cd2309bf3d",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nixd",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1772624091,
"narHash": "sha256-QKyJ0QGWBn6r0invrMAK8dmJoBYWoOWy7lN+UHzW1jc=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "80bdc1e5ce51f56b19791b52b2901187931f5353",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-lib": {
"locked": {
"lastModified": 1782614948,
"narHash": "sha256-ePjCwr1sNm9NYUqywL7QfK3JnlS015msC+eBu2zKlp8=",
"owner": "nix-community",
"repo": "nixpkgs.lib",
"rev": "db3f255737b94216eb71cce308e2912cf6bc2d7c",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nixpkgs.lib",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1785571196,
"narHash": "sha256-KoTsyMQqnXQZq8deCEnu4QkyldkwH/bpMMhUcfMdGIw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "148bab9c1c3c53136ecb44a6ea356a0ed5b39b06",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"devenv": "devenv",
"flake-parts": "flake-parts_2",
"mk-shell-bin": "mk-shell-bin",
"nix2container": "nix2container",
"nixpkgs": "nixpkgs_2",
"rust-overlay": "rust-overlay_2"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"devenv",
"nixpkgs"
]
},
"locked": {
"lastModified": 1782875958,
"narHash": "sha256-5eqDcnBjb1424HRQdnhuhNOBZguq1Z2tqSa2OMF/m2c=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "13139aefa973f3d96c60c0fbab801de058ae25ca",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"rust-overlay_2": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1785562362,
"narHash": "sha256-J15aBa3d6B1SUUAQydQ06wFjPzrrcVceb6jkdfwfGls=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "5f29c219a7655519f8a9f8c6968064b82c17cc93",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"treefmt-nix": {
"inputs": {
"nixpkgs": [
"devenv",
"nixd",
"nixpkgs"
]
},
"locked": {
"lastModified": 1780220602,
"narHash": "sha256-eynAfOmbmxJnkp7YewvCEbShNnnYJ9gLLqkzsYtBPeM=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "db947814a175b7ca6ded66e21383d938df01c227",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "treefmt-nix",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+33
View File
@@ -0,0 +1,33 @@
{
description = "Furumi TUI development environment";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-parts.url = "github:hercules-ci/flake-parts";
devenv.url = "github:cachix/devenv";
devenv.inputs.nixpkgs.follows = "nixpkgs";
rust-overlay.url = "github:oxalica/rust-overlay";
rust-overlay.inputs.nixpkgs.follows = "nixpkgs";
nix2container.url = "github:nlewo/nix2container";
nix2container.inputs.nixpkgs.follows = "nixpkgs";
mk-shell-bin.url = "github:rrbutani/nix-mk-shell-bin";
};
outputs = inputs@{ flake-parts, ... }:
flake-parts.lib.mkFlake { inherit inputs; } {
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
imports = [ inputs.devenv.flakeModule ];
perSystem = { ... }: {
devenv.shells.default = {
imports = [ ./devenv.nix ];
};
};
};
}
+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"
+227
View File
@@ -0,0 +1,227 @@
//! 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,
#[serde(default, skip_serializing_if = "is_false")]
pub liked_radio_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,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
pub state: RadioState,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LikedRadioSeed {
pub key: String,
pub title: String,
pub artist: 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,
PickLikedRadioSeed {
#[serde(default, skip_serializing_if = "Option::is_none")]
exclude: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
replace_request_id: Option<String>,
},
StartLikedRadio {
seed_key: String,
},
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>,
},
LikedRadioSeed {
id: String,
seed: LikedRadioSeed,
},
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"
+243
View File
@@ -0,0 +1,243 @@
# 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 contains **Like**, **Devices**, **Radio**, and a
**sparkles** key for radio from a random liked track.
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.
Tap the sparkles to choose a liked track, even when the player is idle.
The Infobar switches to a single message line with the track title and artist.
The bar underneath shrinks from right to left for two seconds. Tap again to
draw another track and reset the countdown, or leave Functions to cancel the
preview. When the bar runs out, Furumi searches for music similar to the
displayed track. You can reroll while the search is still collecting matches.
Playback resumes on the main screen once the new radio is playing. This uses
liked tracks present in the local similarity index.
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,174 @@
// 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],
['Sparkle', 'sparkle', 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,349 @@
{
"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": "Sparkle",
"index": 18,
"x": 192,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "CoverFrame",
"index": 19,
"x": 288,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "EnabledFrame",
"index": 20,
"x": 384,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner0",
"index": 21,
"x": 480,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner1",
"index": 22,
"x": 576,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner2",
"index": 23,
"x": 672,
"y": 192,
"width": 96,
"height": 96
},
{
"name": "Spinner3",
"index": 24,
"x": 0,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner4",
"index": 25,
"x": 96,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner5",
"index": 26,
"x": 192,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner6",
"index": 27,
"x": 288,
"y": 288,
"width": 96,
"height": 96
},
{
"name": "Spinner7",
"index": 28,
"x": 384,
"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/sparkle.svg",
"url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/sparkle-fill.svg",
"sha256": "9872a9255717f4ecc0f01b028b9436042e0f49391e4ce7a57f61aa466684fad1"
},
{
"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: 22 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="M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z"/></svg>

After

Width:  |  Height:  |  Size: 492 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());
}
}
+231
View File
@@ -0,0 +1,231 @@
//! 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,
Sparkle,
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; 21] = [
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::Sparkle,
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]);
}
}
}
}
+130
View File
@@ -0,0 +1,130 @@
use furumi_control_protocol::{LikedRadioSeed, RadioState, Snapshot};
use std::time::{Duration, Instant};
pub const PREVIEW_TIME: Duration = Duration::from_secs(2);
pub const PICK_TIMEOUT: Duration = Duration::from_secs(10);
pub const START_TIMEOUT: Duration = Duration::from_secs(240);
pub enum Phase {
Picking {
id: String,
since: Instant,
},
Preview {
seed: LikedRadioSeed,
since: Instant,
},
Starting {
id: String,
since: Instant,
},
Failed(String),
}
pub struct Attempt {
pub shown: bool,
pub widget_since: Instant,
pub phase: Phase,
pub last_key: Option<String>,
pub owner: Option<String>,
}
pub fn can_pick(snapshot: &Snapshot, attempt: Option<&Attempt>) -> bool {
snapshot.liked_radio_supported
&& match snapshot.radio.state {
RadioState::Starting => false,
RadioState::Searching => matches!(
attempt.map(|attempt| &attempt.phase),
Some(Phase::Starting { id, .. }) if snapshot.radio.request_id.as_ref() == Some(id)
),
_ => true,
}
}
impl Attempt {
pub fn request_id(&self) -> Option<&str> {
match &self.phase {
Phase::Picking { id, .. } | Phase::Starting { id, .. } => Some(id),
_ => None,
}
}
pub fn preview_due(&self, now: Instant) -> Option<&LikedRadioSeed> {
match &self.phase {
Phase::Preview { seed, since }
if self.shown && now.saturating_duration_since(*since) >= PREVIEW_TIME =>
{
Some(seed)
}
_ => None,
}
}
pub fn timed_out(&self, now: Instant) -> bool {
let (since, limit) = match &self.phase {
Phase::Picking { since, .. } => (*since, PICK_TIMEOUT),
Phase::Starting { since, .. } => (*since, START_TIMEOUT),
_ => return false,
};
now.saturating_duration_since(since) >= limit
}
pub fn message(&self, now: Instant) -> (String, Option<f32>) {
match &self.phase {
Phase::Picking { .. } => ("Choosing track…".into(), None),
Phase::Preview { seed, since } => {
let elapsed = if self.shown {
now.saturating_duration_since(*since)
} else {
Duration::ZERO
};
let remaining =
PREVIEW_TIME.saturating_sub(elapsed).as_secs_f32() / PREVIEW_TIME.as_secs_f32();
let text = match (seed.title.trim(), seed.artist.trim()) {
("", "") => "Unknown track".into(),
("", artist) => artist.to_owned(),
(title, "") => title.to_owned(),
(title, artist) => format!("{title} · {artist}"),
};
(text, Some(remaining))
}
Phase::Starting { .. } => ("Starting radio…".into(), None),
Phase::Failed(error) => (error.clone(), None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preview_waits_exactly_two_seconds_and_countdown_keeps_left_anchor() {
let now = Instant::now();
let a = Attempt {
shown: true,
widget_since: now,
phase: Phase::Preview {
seed: LikedRadioSeed {
key: "a".into(),
title: "Title".into(),
artist: "Artist".into(),
},
since: now,
},
last_key: Some("a".into()),
owner: Some("self".into()),
};
assert!(a.preview_due(now + Duration::from_millis(1999)).is_none());
assert_eq!(a.preview_due(now + PREVIEW_TIME).unwrap().key, "a");
assert_eq!(a.message(now).1, Some(1.0));
assert_eq!(a.message(now + Duration::from_secs(1)).1, Some(0.5));
assert_eq!(a.message(now + PREVIEW_TIME).1, Some(0.0));
let mut a = a;
if let Phase::Preview { seed, .. } = &mut a.phase {
seed.artist.clear();
}
assert_eq!(a.message(now).0, "Title");
if let Phase::Preview { seed, .. } = &mut a.phase {
seed.artist = "Artist".into();
seed.title.clear();
}
assert_eq!(a.message(now).0, "Artist");
}
}
File diff suppressed because it is too large. Load diff
+854
View File
@@ -0,0 +1,854 @@
//! 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 { .. }
| Command::PickLikedRadioSeed { .. }
)
}
#[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 {
LikedRadio,
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 liked_radio: Option<crate::liked_radio::Attempt>,
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 {
liked_radio: None,
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()
&& self.liked_radio.as_ref().is_none_or(|a| {
matches!(a.phase, crate::liked_radio::Phase::Failed(_))
})
&& self.heart.as_ref().is_none_or(|h| {
!matches!(
h.phase,
crate::heart::Phase::Waiting(..) | crate::heart::Phase::Sending
)
}) =>
{
Binding::Command(Command::StartRadio)
}
3 if snapshot.is_some_and(|s| {
crate::liked_radio::can_pick(s, self.liked_radio.as_ref())
}) && self.radio.is_none()
&& self.heart.as_ref().is_none_or(|h| {
!matches!(
h.phase,
crate::heart::Phase::Waiting(..) | crate::heart::Phase::Sending
)
}) =>
{
Binding::LikedRadio
}
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::LikedRadio => None,
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 {
let matches_request =
if snapshot.liked_radio_supported || snapshot.radio.request_id.is_some() {
snapshot.radio.request_id.as_deref() == Some(radio.request_id.as_str())
} else {
snapshot.radio.id > radio.baseline
};
if matches_request && snapshot.radio.state == RadioState::Playing {
self.screen = Screen::Player;
self.radio = None;
} else if matches_request && 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 old_radio_servers_without_request_ids_keep_generation_fallback() {
let mut snapshot = fixture();
snapshot.liked_radio_supported = false;
snapshot.radio.request_id = None;
snapshot.radio.id = 2;
snapshot.radio.state = RadioState::Playing;
let mut deck = Deck {
screen: Screen::Functions,
radio: Some(PendingRadio {
request_id: "legacy".into(),
baseline: 1,
started: Instant::now(),
}),
..Default::default()
};
deck.update(&snapshot);
assert!(matches!(deck.screen, Screen::Player));
assert!(deck.radio.is_none());
}
#[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.request_id = Some("another-deck".into());
deck.update(&snapshot);
assert!(deck.radio.is_some());
snapshot.radio.request_id = Some("radio-11".into());
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));
}
}
+517
View File
@@ -0,0 +1,517 @@
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,
liked_radio_supported: true,
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"))?;
let mut widgets = RgbImage::from_pixel(280, 6 * 98 + 8, Rgb([24, 27, 32]));
for (index, (label, message, countdown)) in [
("Functions", "Choose a function", None),
("Choosing", "Choosing track…", None),
("Preview / 2 seconds", "Midnight City · M83", Some(1.0)),
("Preview / 1 second", "Midnight City · M83", Some(0.5)),
("Searching", "Finding similar…", None),
("Error", "Like a track first", None),
]
.into_iter()
.enumerate()
{
let y = 8 + index as i32 * 98;
render::preview_label(&mut widgets, label, 16, y, 248);
let age = countdown.map_or(Duration::ZERO, |remaining| {
crate::liked_radio::PREVIEW_TIME.mul_f32(1.0 - remaining)
});
let bar = render::message_bar(message, countdown, Role::Active, false, age);
bar.save(directory.join(format!("liked-radio-widget-{index}.png")))?;
image::imageops::overlay(&mut widgets, &bar, 16, i64::from(y + 24));
}
widgets.save(directory.join("liked-radio-widgets.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.');
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "stable"
profile = "minimal"
components = ["clippy", "rust-src", "rustfmt"]
+65
View File
@@ -0,0 +1,65 @@
"""Build and run the real TUI and web protocol adapters against each other.
Usage: python scripts/test_device_interop.py [path/to/furumusic]
No user databases, accounts, audio outputs, or external servers are used.
"""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
def test_binary(repo):
result = subprocess.run(
["cargo", "test", "--locked", "--no-run", "--message-format=json"],
cwd=repo, text=True, encoding="utf-8", stdout=subprocess.PIPE,
)
result.check_returncode()
binaries = []
for line in result.stdout.splitlines():
event = json.loads(line)
if event.get("reason") == "compiler-artifact" and event.get("profile", {}).get("test") and event.get("executable"):
binaries.append(event["executable"])
if len(binaries) != 1:
raise RuntimeError(f"Expected one player test binary in {repo}, found {binaries}")
return binaries[0]
def main():
tui = Path(__file__).resolve().parents[1]
web = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else tui.parent / "furumusic"
tui_bin, web_bin = test_binary(tui), test_binary(web)
with tempfile.TemporaryDirectory(prefix="furumi-interop-") as directory:
env = dict(os.environ, FURUMI_INTEROP_DIR=directory)
processes = []
try:
for binary, test in [(web_bin, "federation::devices::interop_tests::localhost_tui_peer"),
(tui_bin, "devices::interop_tests::localhost_web_peer")]:
listing = subprocess.check_output([binary, "--list"], text=True, encoding="utf-8")
if f"{test}: test" not in listing:
raise RuntimeError(f"Required test {test} is missing from {binary}")
processes.append(subprocess.Popen(
[binary, "--ignored", "--exact", test, "--nocapture"], env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8",
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
))
codes = []
for process in processes:
output, _ = process.communicate(timeout=45)
print(output, end="")
codes.append(process.returncode)
if any(codes):
raise RuntimeError(f"Cross-player test failed: exit codes {codes}")
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait()
print("PASS: TUI <-> WEB state, bidirectional handoff, pause/seek, duplicate fencing")
if __name__ == "__main__":
main()
+67 -5
View File
@@ -32,13 +32,18 @@ pub enum Action {
ToggleShuffle, ToggleShuffle,
CycleRepeat, CycleRepeat,
ToggleVisualizer, ToggleVisualizer,
OpenLyrics,
OpenCurrentLyrics,
CycleVisualizerMode,
ToggleLike, ToggleLike,
ToggleTrackSelection, ToggleTrackSelection,
OpenTrackInfo, OpenTrackInfo,
OpenCurrentTrackInfo, OpenCurrentTrackInfo,
QueueAddNext, QueueAddNext,
QueueAddLast, QueueAddLast,
/// Download the selected federated track(s) into the local library. MoveQueueUp,
MoveQueueDown,
/// Download selected federated tracks, or a podcast episode for offline playback.
DownloadSelected, DownloadSelected,
RemoveFromQueue, RemoveFromQueue,
ClearQueue, ClearQueue,
@@ -55,6 +60,27 @@ pub enum Action {
OpenSearch, OpenSearch,
EditSelected, EditSelected,
DeleteSelected, DeleteSelected,
/// Podcasts: subscribe to an RSS feed URL.
AddPodcast,
/// Podcasts: search the episodes of the opened podcast.
SearchEpisodes,
/// Podcasts: check the selected or opened podcast for new episodes.
RefreshPodcast,
/// Podcasts: check every subscription for new episodes.
RefreshAllPodcasts,
/// Podcasts: cycle the episode order.
CycleEpisodeSort,
/// Podcasts: cycle the played-state filter.
CycleEpisodeFilter,
/// Podcasts: mark the selected episode played / unplayed.
ToggleEpisodePlayed,
/// Podcasts: unsubscribe (progress and history are kept).
UnsubscribePodcast,
/// Podcasts: play the selected (or playing) episode from the beginning.
RestartEpisode,
/// Podcasts: turn "share in the federation" on or off for the selected
/// or opened podcast (asks first when its feed URL looks private).
TogglePodcastShare,
} }
/// Help-window sections, in display order. /// Help-window sections, in display order.
@@ -64,16 +90,18 @@ pub enum Category {
Queue, Queue,
Library, Library,
Navigation, Navigation,
Podcasts,
Search, Search,
System, System,
} }
impl Category { impl Category {
pub const ALL: [Category; 6] = [ pub const ALL: [Category; 7] = [
Category::Playback, Category::Playback,
Category::Queue, Category::Queue,
Category::Library, Category::Library,
Category::Navigation, Category::Navigation,
Category::Podcasts,
Category::Search, Category::Search,
Category::System, Category::System,
]; ];
@@ -84,6 +112,7 @@ impl Category {
Category::Queue => "Queue & playlists", Category::Queue => "Queue & playlists",
Category::Library => "Library", Category::Library => "Library",
Category::Navigation => "Navigation", Category::Navigation => "Navigation",
Category::Podcasts => "Podcasts",
Category::Search => "Search & commands", Category::Search => "Search & commands",
Category::System => "System", Category::System => "System",
} }
@@ -102,11 +131,16 @@ impl Action {
| Action::VolumeDown | Action::VolumeDown
| Action::ToggleShuffle | Action::ToggleShuffle
| Action::CycleRepeat | Action::CycleRepeat
| Action::OpenLyrics
| Action::OpenCurrentLyrics
| Action::ToggleVisualizer | Action::ToggleVisualizer
| Action::CycleVisualizerMode
| Action::OpenConnectedDevices | Action::OpenConnectedDevices
| Action::OpenListenHistory => Category::Playback, | Action::OpenListenHistory => Category::Playback,
Action::QueueAddNext Action::QueueAddNext
| Action::QueueAddLast | Action::QueueAddLast
| Action::MoveQueueUp
| Action::MoveQueueDown
| Action::DownloadSelected | Action::DownloadSelected
| Action::RemoveFromQueue | Action::RemoveFromQueue
| Action::ClearQueue | Action::ClearQueue
@@ -135,6 +169,16 @@ impl Action {
| Action::DeleteSelected | Action::DeleteSelected
| Action::CycleSourceMode | Action::CycleSourceMode
| Action::OpenLibraryFilters => Category::Library, | Action::OpenLibraryFilters => Category::Library,
Action::AddPodcast
| Action::SearchEpisodes
| Action::RefreshPodcast
| Action::RefreshAllPodcasts
| Action::CycleEpisodeSort
| Action::CycleEpisodeFilter
| Action::ToggleEpisodePlayed
| Action::UnsubscribePodcast
| Action::RestartEpisode
| Action::TogglePodcastShare => Category::Podcasts,
Action::OpenSearch | Action::OpenCommandLine => Category::Search, Action::OpenSearch | Action::OpenCommandLine => Category::Search,
Action::ToggleHelp | Action::Quit => Category::System, Action::ToggleHelp | Action::Quit => Category::System,
} }
@@ -166,7 +210,10 @@ impl Action {
Action::Quit => "Quit".into(), Action::Quit => "Quit".into(),
Action::NextTab => "Next tab".into(), Action::NextTab => "Next tab".into(),
Action::PrevTab => "Previous tab".into(), Action::PrevTab => "Previous tab".into(),
Action::GoToTab(i) => format!("Go to tab {}", i + 1), Action::GoToTab(i) => match crate::app::state::Tab::from_index(*i) {
Some(tab) => format!("Go to {}", tab.title()),
None => format!("Go to tab {}", i + 1),
},
Action::MoveUp => "Move up".into(), Action::MoveUp => "Move up".into(),
Action::MoveDown => "Move down".into(), Action::MoveDown => "Move down".into(),
Action::MoveLeft => "Move left".into(), Action::MoveLeft => "Move left".into(),
@@ -186,14 +233,19 @@ impl Action {
Action::VolumeDown => "Volume down".into(), Action::VolumeDown => "Volume down".into(),
Action::ToggleShuffle => "Toggle shuffle".into(), Action::ToggleShuffle => "Toggle shuffle".into(),
Action::CycleRepeat => "Cycle repeat mode".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::ToggleVisualizer => "Toggle fullscreen visualizer".into(),
Action::CycleVisualizerMode => "Next visualizer display mode".into(),
Action::ToggleLike => "Like / unlike".into(), Action::ToggleLike => "Like / unlike".into(),
Action::ToggleTrackSelection => "Track line selection".into(), Action::ToggleTrackSelection => "Track line selection".into(),
Action::OpenTrackInfo => "Track info".into(), Action::OpenTrackInfo => "Track info".into(),
Action::OpenCurrentTrackInfo => "Current track info".into(), Action::OpenCurrentTrackInfo => "Current track info".into(),
Action::QueueAddNext => "Queue: add next".into(), Action::QueueAddNext => "Queue: add next".into(),
Action::QueueAddLast => "Queue: add to end".into(), Action::QueueAddLast => "Queue: add to end".into(),
Action::DownloadSelected => "Federation: download to library".into(), Action::MoveQueueUp => "Queue: move track/selection up".into(),
Action::MoveQueueDown => "Queue: move track/selection down".into(),
Action::DownloadSelected => "Download selected music / podcast episode".into(),
Action::RemoveFromQueue => "Queue: remove selected".into(), Action::RemoveFromQueue => "Queue: remove selected".into(),
Action::ClearQueue => "Queue: clear".into(), Action::ClearQueue => "Queue: clear".into(),
Action::OpenConnectedDevices => "Connected devices…".into(), Action::OpenConnectedDevices => "Connected devices…".into(),
@@ -206,9 +258,19 @@ impl Action {
Action::CycleSourceMode => "Cycle source mode: Local / My / Global".into(), Action::CycleSourceMode => "Cycle source mode: Local / My / Global".into(),
Action::OpenLibraryFilters => "Library filters…".into(), Action::OpenLibraryFilters => "Library filters…".into(),
Action::OpenCommandLine => "Command line (:help for commands)".into(), Action::OpenCommandLine => "Command line (:help for commands)".into(),
Action::OpenSearch => "Search artists, releases, tracks".into(), Action::OpenSearch => "Search artists, releases, tracks, public podcasts".into(),
Action::EditSelected => "Edit the selected item".into(), Action::EditSelected => "Edit the selected item".into(),
Action::DeleteSelected => "Delete the selected item".into(), Action::DeleteSelected => "Delete the selected item".into(),
Action::AddPodcast => "Add podcast (RSS URL)".into(),
Action::SearchEpisodes => "Search episodes".into(),
Action::RefreshPodcast => "Check podcast for new episodes".into(),
Action::RefreshAllPodcasts => "Check all podcasts".into(),
Action::CycleEpisodeSort => "Episode order".into(),
Action::CycleEpisodeFilter => "Filter: all/unplayed/played".into(),
Action::ToggleEpisodePlayed => "Mark played / unplayed".into(),
Action::UnsubscribePodcast => "Unsubscribe (keeps progress)".into(),
Action::RestartEpisode => "Play episode from the start".into(),
Action::TogglePodcastShare => "Share podcast in the federation on/off".into(),
} }
} }
} }
+112
View File
@@ -17,6 +17,16 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
match key.code { match key.code {
KeyCode::Esc => cancel(state), KeyCode::Esc => cancel(state),
KeyCode::Enter => commit(state, runtime), KeyCode::Enter => commit(state, runtime),
KeyCode::Up => {
if state.cmdline.history_previous() {
after_change(state, runtime);
}
}
KeyCode::Down => {
if state.cmdline.history_next() {
after_change(state, runtime);
}
}
// Backspace on an empty line closes it, like vim. // Backspace on an empty line closes it, like vim.
KeyCode::Backspace if state.cmdline.input.is_empty() => cancel(state), KeyCode::Backspace if state.cmdline.input.is_empty() => cancel(state),
_ => { _ => {
@@ -87,6 +97,11 @@ fn set_view_cursor_zero(state: &mut AppState) {
/// spawned task only queries if it is still the latest after the debounce, /// spawned task only queries if it is still the latest after the debounce,
/// and the receiver drops responses that arrive out of date. /// and the receiver drops responses that arrive out of date.
pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) { pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
state.search.similarity_source = None;
state.search.similarity_source_track = None;
state.search.similarity_tracks.clear();
state.search.similarity_stats = None;
state.search.similarity_error = None;
let seq = runtime.search_seq.fetch_add(1, Ordering::SeqCst) + 1; let seq = runtime.search_seq.fetch_add(1, Ordering::SeqCst) + 1;
let query = state.search.query.clone(); let query = state.search.query.clone();
if query.is_empty() { if query.is_empty() {
@@ -94,7 +109,9 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
state.search.results = None; state.search.results = None;
state.search.fed_tracks.clear(); state.search.fed_tracks.clear();
state.search.fed_artists.clear(); state.search.fed_artists.clear();
state.search.fed_podcasts.clear();
state.search.fed_loading = false; state.search.fed_loading = false;
state.search.fed_podcasts_loading = false;
return; return;
} }
let library = Arc::clone(&runtime.library); let library = Arc::clone(&runtime.library);
@@ -117,7 +134,9 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
// node is up); its results render as a separate, marked section. // node is up); its results render as a separate, marked section.
state.search.fed_tracks.clear(); state.search.fed_tracks.clear();
state.search.fed_artists.clear(); state.search.fed_artists.clear();
state.search.fed_podcasts.clear();
state.search.fed_loading = false; state.search.fed_loading = false;
state.search.fed_podcasts_loading = false;
if runtime.federation.settings().enabled { if runtime.federation.settings().enabled {
state.search.fed_loading = true; state.search.fed_loading = true;
let fed = Arc::clone(&runtime.federation); let fed = Arc::clone(&runtime.federation);
@@ -132,9 +151,96 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
let result = fed.search(&query).await.map_err(|err| format!("{err:#}")); let result = fed.search(&query).await.map_err(|err| format!("{err:#}"));
let _ = tx.send(AppEvent::FedSearchLoaded { seq, result }); let _ = tx.send(AppEvent::FedSearchLoaded { seq, result });
}); });
schedule_podcast_search(state, runtime, seq);
} }
} }
/// Public podcast cards for the live search `seq`, as their own task and
/// event: the overlay search (bounded, bootstrap included) never holds back
/// the music results.
fn schedule_podcast_search(state: &mut AppState, runtime: &Runtime, seq: u64) {
state.search.fed_podcasts_loading = true;
let fed = Arc::clone(&runtime.federation);
let query = state.search.query.clone();
let tx = runtime.event_tx.clone();
let latest = Arc::clone(&runtime.search_seq);
let podcast_store = runtime
.podcasts
.as_ref()
.map(|podcasts| Arc::clone(&podcasts.services.store));
tokio::spawn(async move {
tokio::time::sleep(SEARCH_DEBOUNCE).await;
if latest.load(Ordering::SeqCst) != seq {
return;
}
let mut hits = fed.search_podcasts(&query).await;
// Which public podcasts this device already knows (feed aliases
// included), for the "subscribed" mark.
if let Some(store) = podcast_store
&& !hits.is_empty()
{
hits = tokio::task::spawn_blocking(move || {
if let Err(err) = crate::podcasts::discovery::resolve_local_ids(&store, &mut hits) {
tracing::warn!("podcast search: feed aliases not resolved: {err:#}");
}
hits
})
.await
.unwrap_or_default();
}
let _ = tx.send(AppEvent::FedPodcastsLoaded { seq, hits });
});
}
pub(super) fn schedule_similarity_search(
state: &mut AppState,
runtime: &Runtime,
track: &crate::library::models::TrackItem,
) {
let seq = runtime.search_seq.fetch_add(1, Ordering::SeqCst) + 1;
let artist = track.artist_line();
state.search.query = if artist.is_empty() {
track.title.clone()
} else {
format!("{} — {artist}", track.title)
};
state.search.similarity_source = Some(track.id);
state.search.similarity_source_track = Some(track.clone());
state.search.similarity_tracks.clear();
state.search.similarity_stats = None;
state.search.similarity_error = None;
state.search.loading = true;
state.search.results = None;
state.search.fed_tracks.clear();
state.search.fed_artists.clear();
state.search.fed_podcasts.clear();
state.search.fed_loading = false;
state.search.fed_podcasts_loading = false;
state.active_tab = crate::app::state::Tab::Global;
if let Some(crate::app::state::GlobalView::Search { cursor }) = state.global.stack.last_mut() {
*cursor = 0;
} else {
state
.global
.stack
.push(crate::app::state::GlobalView::Search { cursor: 0 });
}
let similarity = Arc::clone(&runtime.similarity);
let tx = runtime.event_tx.clone();
let track_id = track.id;
tokio::task::spawn_blocking(move || {
let result = similarity
.search_track(track_id, 49)
.map(|(matches, query)| (matches, query));
let (result, query) = match result {
Ok((results, query)) => (Ok(results), Some(query)),
Err(err) => (Err(format!("{err:#}")), None),
};
let _ = tx.send(AppEvent::SimilaritySearchLoaded { seq, result, query });
});
}
/// Refresh only the local-library half of an already open search. /// Refresh only the local-library half of an already open search.
/// ///
/// Library/device sync notifications can arrive while federated search /// Library/device sync notifications can arrive while federated search
@@ -142,6 +248,9 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) {
/// federation rows and bump the shared sequence, causing valid network /// federation rows and bump the shared sequence, causing valid network
/// responses to be dropped or flicker away. /// responses to be dropped or flicker away.
pub(super) fn refresh_local_search(state: &mut AppState, runtime: &Runtime) { pub(super) fn refresh_local_search(state: &mut AppState, runtime: &Runtime) {
if state.search.similarity_source.is_some() {
return;
}
let query = state.search.query.clone(); let query = state.search.query.clone();
if query.is_empty() { if query.is_empty() {
return; return;
@@ -162,7 +271,9 @@ pub(super) fn refresh_local_search(state: &mut AppState, runtime: &Runtime) {
/// Enter: close the line. Live commands already took effect (their view /// Enter: close the line. Live commands already took effect (their view
/// stays open); one-shot commands execute here. /// stays open); one-shot commands execute here.
fn commit(state: &mut AppState, runtime: &mut Runtime) { fn commit(state: &mut AppState, runtime: &mut Runtime) {
let remembered = state.cmdline.input.as_str().to_string();
let parsed = command::parse(&state.cmdline.input); let parsed = command::parse(&state.cmdline.input);
state.cmdline.remember(&remembered);
close(state); close(state);
match parsed { match parsed {
Parsed::Empty => {} Parsed::Empty => {}
@@ -272,6 +383,7 @@ fn close(state: &mut AppState) {
state.cmdline.active = false; state.cmdline.active = false;
state.cmdline.input.clear(); state.cmdline.input.clear();
state.cmdline.live = false; state.cmdline.live = false;
state.cmdline.begin_history_navigation();
} }
/// Pop the live search view if this command-line session opened it. /// Pop the live search view if this command-line session opened it.
+297
View File
@@ -0,0 +1,297 @@
//! 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,
liked_radio_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,
PickLikedRadioSeed {
exclude: Option<String>,
replace_request_id: Option<String>,
},
StartLikedRadio {
seed_key: String,
},
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 { .. }
| Command::PickLikedRadioSeed { .. }
) {
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::PickLikedRadioSeed {
exclude,
replace_request_id,
} => Intent::PickLikedRadioSeed {
exclude,
replace_request_id,
},
Command::StartLikedRadio { seed_key } => Intent::StartLikedRadio { seed_key },
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, None, request.id),
Ok(Intent::PickLikedRadioSeed {
exclude,
replace_request_id,
}) => {
super::radio::pick_liked(state, runtime, exclude, replace_request_id, request.reply);
return;
}
Ok(Intent::StartLikedRadio { seed_key }) => {
super::radio::start(state, runtime, Some(seed_key), request.id)
}
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.map(|()| crate::control::Reply::Done));
}
+141
View File
@@ -0,0 +1,141 @@
//! Scheduling for local cards enriched by replaceable federation data.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use super::state::{AppState, GlobalView, Loadable, Tab};
const REFRESH_INTERVAL: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum Card {
Artist(i64),
Release(i64),
}
#[derive(Debug, Default)]
pub(super) struct RefreshState {
visible: Option<Card>,
/// None means a request is in flight; Some is its completion time.
requests: HashMap<Card, Option<Instant>>,
}
impl RefreshState {
pub(super) fn is_loading(&self, card: Card) -> bool {
matches!(self.requests.get(&card), Some(None))
}
fn begin(&mut self, visible: Option<Card>, now: Instant) -> bool {
let reopened = self.visible != visible;
self.visible = visible;
let Some(card) = visible else { return false };
match self.requests.get(&card) {
Some(None) => return false,
Some(Some(completed))
if !reopened && now.duration_since(*completed) < REFRESH_INTERVAL =>
{
return false;
}
_ => {}
}
self.requests.insert(card, None);
true
}
pub(super) fn complete(&mut self, card: Card, now: Instant) {
self.requests.insert(card, Some(now));
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Request {
Artist {
id: i64,
name: String,
},
Release {
id: i64,
title: String,
artists: Vec<String>,
},
}
/// Called on navigation and maintenance ticks. A cached success or failure
/// must not suppress discovery for the rest of the session.
pub(super) fn prepare(state: &mut AppState, now: Instant) -> Option<Request> {
let visible = if state.federation.settings.enabled
&& state.global.filters.source_mode.includes_network()
&& state.active_tab == Tab::Global
{
match state.global.stack.last() {
Some(GlobalView::Artist { id, .. }) => Some(Card::Artist(*id)),
Some(GlobalView::Release { id, .. }) => Some(Card::Release(*id)),
_ => None,
}
} else {
None
};
let request = match visible {
Some(Card::Artist(id)) => match state.artist_views.get(&id) {
Some(Loadable::Ready(detail)) => Some(Request::Artist {
id,
name: detail.name.clone(),
}),
_ => None,
},
Some(Card::Release(id)) => match state.release_views.get(&id) {
Some(Loadable::Ready(detail)) => {
let mut artists = Vec::new();
for artist in &detail.artists {
if !artists.iter().any(|name: &String| {
music_dht::normalize_name(name) == music_dht::normalize_name(&artist.name)
}) {
artists.push(artist.name.clone());
}
}
(!artists.is_empty()).then(|| Request::Release {
id,
title: detail.title.clone(),
artists,
})
}
_ => None,
},
None => None,
};
if !state
.card_enrichment
.begin(visible.filter(|_| request.is_some()), now)
{
return None;
}
match &request {
Some(Request::Artist { id, .. }) => mark_loading(&mut state.artist_fed_views, *id),
Some(Request::Release { id, .. }) => mark_loading(&mut state.release_fed_views, *id),
None => {}
}
request
}
fn mark_loading<T>(views: &mut HashMap<i64, Loadable<T>>, id: i64) {
if !matches!(views.get(&id), Some(Loadable::Ready(_))) {
views.insert(id, Loadable::Loading);
}
}
/// Keep the last usable snapshot if a refresh fails while peers are offline.
pub(super) fn store_result<T>(
views: &mut HashMap<i64, Loadable<T>>,
id: i64,
result: Result<T, String>,
) {
match result {
Ok(value) => {
views.insert(id, Loadable::Ready(value));
}
Err(message) if !matches!(views.get(&id), Some(Loadable::Ready(_))) => {
views.insert(id, Loadable::Failed(message));
}
Err(_) => {}
}
}
+141 -7
View File
@@ -10,7 +10,23 @@ use crate::library::models::{
/// the playback engine, imports). Tasks never touch AppState directly. /// the playback engine, imports). Tasks never touch AppState directly.
#[derive(Debug)] #[derive(Debug)]
pub enum AppEvent { pub enum AppEvent {
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), 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). /// A page of the artists list arrived (or failed).
ArtistsLoaded(Result<ArtistsPage, String>), ArtistsLoaded(Result<ArtistsPage, String>),
/// A full reload after a library change: replaces the loaded artist /// A full reload after a library change: replaces the loaded artist
@@ -27,11 +43,31 @@ pub enum AppEvent {
id: i64, id: i64,
result: Result<ReleaseDetail, String>, result: Result<ReleaseDetail, String>,
}, },
/// Federated tracks that complete an already-open local release view.
ReleaseFederationLoaded {
id: i64,
result: Result<Option<crate::federation::FedRelease>, String>,
},
/// Live search results; `seq` drops responses that are already stale. /// Live search results; `seq` drops responses that are already stale.
SearchLoaded { SearchLoaded {
seq: u64, seq: u64,
result: Result<SearchResults, String>, result: Result<SearchResults, String>,
}, },
/// Local similar-track search completed. It uses the same sequence as
/// text search so stale pages cannot overwrite a newer request.
SimilaritySearchLoaded {
seq: u64,
result: Result<Vec<crate::similarity::SimilarTrack>, String>,
query: Option<crate::similarity::QueryVector>,
},
/// Federated candidates and diagnostics for a track-seeded search.
FedSimilaritySearchLoaded {
seq: u64,
result: Result<crate::federation::FedSimilaritySearchResults, String>,
},
SimilarityStatus(crate::similarity::SimilarityStatus),
/// `None` is emitted after clearing every stored embedding.
SimilarityProfileActivated(Option<String>),
/// Artwork loaded and decoded for the shared art cache. /// Artwork loaded and decoded for the shared art cache.
ArtLoaded { ArtLoaded {
key: String, key: String,
@@ -50,12 +86,14 @@ pub enum AppEvent {
id: i64, id: i64,
result: Result<PlaylistDetail, String>, result: Result<PlaylistDetail, String>,
}, },
/// Liked local content ids for the ♥ markers. /// Local and federated identities from a completed library like refresh.
LikesLoaded(Result<Vec<String>, String>), LikesLoaded(Result<super::likes::LikeIds, String>),
/// Local-library content ids for availability markers. /// Local-library content ids for availability markers.
LocalContentIdsLoaded(Result<Vec<String>, String>), LocalContentIdsLoaded(Result<Vec<String>, String>),
/// Counts and storage footprint of the local library/database. /// Counts and storage footprint of the local library/database.
LocalLibraryStatsLoaded(Result<crate::library::LocalLibraryStats, String>), LocalLibraryStatsLoaded(Result<crate::library::LocalLibraryStats, String>),
MusicDirectoryValidated(Result<std::path::PathBuf, String>),
MusicDirectoryChanged(Result<crate::library::MusicRelocationStats, String>),
ListenHistoryLoaded(Result<Vec<crate::library::ListenHistoryEntry>, String>), ListenHistoryLoaded(Result<Vec<crate::library::ListenHistoryEntry>, String>),
/// One content id became available locally while the UI is open. /// One content id became available locally while the UI is open.
LocalContentAvailable { LocalContentAvailable {
@@ -65,8 +103,6 @@ pub enum AppEvent {
content_id: String, content_id: String,
liked: bool, liked: bool,
}, },
/// Liked federated item ids and content ids for the ♥ markers.
FedLikesLoaded(Result<Vec<String>, String>),
FedLikeToggled { FedLikeToggled {
item_id: String, item_id: String,
content_id: Option<String>, content_id: Option<String>,
@@ -104,13 +140,21 @@ pub enum AppEvent {
tracks: Vec<TrackItem>, tracks: Vec<TrackItem>,
}, },
/// A status snapshot for the Federation tab. /// A status snapshot for the Federation tab.
FederationStatus(crate::federation::FedStatus), /// Boxed to keep `AppEvent` small; the status is large and rare.
FederationStatus(Box<crate::federation::FedStatus>),
/// Federated live-search results (artists a card can be opened for, /// Federated live-search results (artists a card can be opened for,
/// plus matching tracks). /// plus matching tracks).
FedSearchLoaded { FedSearchLoaded {
seq: u64, seq: u64,
result: Result<crate::federation::FedSearchResults, String>, result: Result<crate::federation::FedSearchResults, String>,
}, },
/// Public podcast cards for the same live search (`seq`), delivered on
/// their own so the music results never wait for the overlay. Already
/// resolved against the podcast store.
FedPodcastsLoaded {
seq: u64,
hits: Vec<crate::podcasts::discovery::PodcastHit>,
},
/// A federated artist card finished assembling. /// A federated artist card finished assembling.
FedArtistLoaded { FedArtistLoaded {
name: String, name: String,
@@ -146,7 +190,8 @@ pub enum AppEvent {
FedTrackInfoLoaded { FedTrackInfoLoaded {
placeholder_id: i64, placeholder_id: i64,
item_id: String, item_id: String,
result: Result<TrackItem, String>, /// Boxed: `TrackItem` is large since it can carry a podcast episode.
result: Result<Box<TrackItem>, String>,
}, },
/// This peer's connection ticket, requested from the Federation tab. /// This peer's connection ticket, requested from the Federation tab.
FedTicket(Result<String, String>), FedTicket(Result<String, String>),
@@ -165,7 +210,11 @@ pub enum AppEvent {
/// Trusted device playback state, delivered by personal-device sync. /// Trusted device playback state, delivered by personal-device sync.
DevicePlayback(crate::devices::PlaybackSnapshot), DevicePlayback(crate::devices::PlaybackSnapshot),
/// Playback command addressed to this device. /// Playback command addressed to this device.
PlaybackCommand(crate::devices::PlaybackCommand), PlaybackCommand {
command: crate::devices::PlaybackCommand,
authority: music_dht::playback::CommandStamp,
origin: String,
},
/// Current lifecycle/status of the federation Jam. /// Current lifecycle/status of the federation Jam.
JamStatus(crate::jam::JamStatus), JamStatus(crate::jam::JamStatus),
/// Host playback snapshot received by a Jam participant. /// Host playback snapshot received by a Jam participant.
@@ -176,4 +225,89 @@ pub enum AppEvent {
JamInvite(Result<String, String>), JamInvite(Result<String, String>),
/// Result of joining a Jam capability. /// Result of joining a Jam capability.
JamJoined(Result<String, String>), JamJoined(Result<String, String>),
/// Received podcast operations or snapshot sections changed the podcast
/// store: `progress` lists changed progress registers, `changed` means
/// anything else (subscriptions, feeds, sessions).
PodcastsSynced {
progress: Vec<music_dht::podcast::ProgressRecord>,
changed: bool,
},
/// The podcast store opened (with the feed client), or why it did not.
PodcastStoreOpened(Result<crate::podcasts::refresh::Services, String>),
/// Subscribed podcasts reloaded from the podcast store.
PodcastsLoaded(Result<Vec<crate::app::state::PodcastRow>, String>),
PodcastSeasonsLoaded {
podcast_id: music_dht::podcast::PodcastId,
result: Result<Vec<furumi_library::podcasts::SeasonSummary>, String>,
},
/// One page of episodes; `seq` drops results of older requests.
PodcastEpisodesLoaded {
seq: u64,
offset: usize,
result: Result<Vec<furumi_library::podcasts::EpisodeListItem>, String>,
},
PodcastSubscribed(Result<crate::podcasts::refresh::SubscribeReport, String>),
/// One feed check finished.
PodcastRefreshed {
podcast_id: music_dht::podcast::PodcastId,
result: Result<crate::podcasts::refresh::RefreshReport, String>,
/// Asked by the user (status bar), not the background scheduler.
manual: bool,
},
PodcastUnsubscribed {
podcast_id: music_dht::podcast::PodcastId,
title: String,
result: Result<(), String>,
},
/// Result of the progress writer (saves, supersedes, mark played).
PodcastProgress(crate::podcasts::progress::ProgressEvent),
/// An episode stream is playing; `generation` is the player source
/// generation of the start that requested it.
PodcastEpisodeStarted {
generation: u64,
episode: Box<music_dht::podcast::PodcastEpisodeRef>,
start_ms: i64,
duration_ms: Option<i64>,
/// The decoder measured `duration_ms` (else the feed announced it).
duration_measured: bool,
restart: bool,
/// The server allows seeking in the stream.
seekable: bool,
/// How the stream ended, once it does.
probe: crate::podcasts::stream::StreamProbe,
},
/// Starting an episode failed (network, decoding, cannot resume).
PodcastEpisodeFailed {
generation: u64,
message: String,
},
/// 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`).
PodcastSharePrepared {
podcast_id: music_dht::podcast::PodcastId,
title: String,
result: Result<crate::podcasts::publication::ShareCheck, String>,
},
/// The share decision was written (`Effect::PodcastSetShared`).
PodcastShareSet {
podcast_id: music_dht::podcast::PodcastId,
title: String,
shared: bool,
result: Result<(), String>,
},
/// The publication reconciler finished a pass.
PodcastPublication(crate::podcasts::publication::PublicationReport),
/// A public card's feed was read for a preview (`Effect::PodcastPreview`).
PodcastPreviewLoaded {
podcast_id: music_dht::podcast::PodcastId,
result: Result<Box<crate::podcasts::discovery::FeedPreview>, String>,
},
} }
+41
View File
@@ -36,6 +36,47 @@ impl LineEdit {
.unwrap_or(self.value.len()) .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) { pub fn clear(&mut self) {
self.value.clear(); self.value.clear();
self.cursor = 0; 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;
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: crate::control::ReplySender,
) {
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).map(|()| crate::control::Reply::Done));
});
}
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), .. }))
));
}
}
+1630 -284
View File
File diff suppressed because it is too large. Load diff
+138
View File
@@ -0,0 +1,138 @@
//! Podcast state fixtures shared by update and rendering tests.
use furumi_library::podcasts::{
EpisodeListItem, EpisodeQuery, FetchState, PodcastSummary, SeasonSummary,
};
use music_dht::podcast::{
EpisodeId, EpisodeMeta, EpisodeType, FeedUrl, PodcastId, PodcastMeta, ProgressRecord,
ProgressStatus,
};
use crate::app::state::{
AppState, EpisodeList, Loadable, OpenedPodcast, PodcastRow, PodcastStoreStatus, Tab,
};
pub fn podcast_id() -> PodcastId {
PodcastId::from_feed_url(&FeedUrl::parse("https://example.test/feed.xml").unwrap())
}
pub fn row(title: &str, unplayed: u64, episodes: u64, seasons: u64) -> PodcastRow {
PodcastRow {
summary: PodcastSummary {
podcast_id: podcast_id(),
meta: PodcastMeta {
feed_url: FeedUrl::parse("https://example.test/feed.xml").unwrap(),
title: title.into(),
author: Some("Host".into()),
description: Some("A show about tests.".into()),
link: None,
image_url: None,
},
subscribed: true,
shared: false,
episode_count: episodes,
unplayed_count: unplayed,
in_progress_count: 0,
latest_published_at_ms: None,
season_count: seasons,
},
fetch: FetchState::default(),
}
}
pub fn episode(n: u32, title: &str, status: Option<(ProgressStatus, i64)>) -> EpisodeListItem {
let podcast = podcast_id();
let episode_id = EpisodeId::from_guid(&podcast, &format!("ep-{n}")).unwrap();
EpisodeListItem {
episode: EpisodeMeta {
episode_id: episode_id.clone(),
podcast_id: podcast.clone(),
guid: Some(format!("ep-{n}")),
title: title.into(),
description: Some(format!("Notes for {title}.")),
season: Some(1),
episode_number: Some(n),
episode_type: EpisodeType::Full,
published_at_ms: Some(1_718_409_600_000),
duration_ms: Some(2_700_000),
audio_url: format!("https://example.test/{n}.mp3"),
mime: Some("audio/mpeg".into()),
byte_len: None,
image_url: None,
link: None,
},
progress: status.map(|(status, position_ms)| ProgressRecord {
episode_id,
podcast_id: podcast,
position_ms,
status,
generation: 1,
session_id: "s".into(),
hlc_ms: 1,
device_id: "dev".into(),
op_id: "dev:1".into(),
}),
completed_count: 0,
in_feed: true,
}
}
pub fn ready_state(rows: Vec<PodcastRow>) -> AppState {
let mut state = AppState {
active_tab: Tab::Podcasts,
..AppState::default()
};
state.podcasts.store = PodcastStoreStatus::Ready;
state.podcasts.list = Some(Loadable::Ready(rows));
state
}
pub fn with_episodes(mut state: AppState, items: Vec<EpisodeListItem>) -> AppState {
let season = furumi_library::podcasts::SeasonFilter::Any;
state.podcasts.opened = Some(OpenedPodcast {
podcast_id: podcast_id(),
season_cursor: None,
season: Some(season),
episode_cursor: 0,
});
state.podcasts.episodes = Some(EpisodeList {
seq: 1,
query: EpisodeQuery::new(podcast_id()),
items,
loading: false,
loading_more: false,
complete: true,
error: None,
focus: None,
});
state
}
pub fn seasons() -> Vec<SeasonSummary> {
vec![
SeasonSummary {
season: Some(1),
episode_count: 3,
unplayed_count: 1,
first_published_at_ms: Some(1_609_459_200_000),
last_published_at_ms: Some(1_640_995_200_000),
},
SeasonSummary {
season: None,
episode_count: 2,
unplayed_count: 0,
first_published_at_ms: None,
last_published_at_ms: None,
},
]
}
/// Queue item for episode `n` of the fixture podcast ("Show").
pub fn episode_track(n: u32) -> crate::library::models::TrackItem {
let meta = row("Show", 0, 0, 0).summary.meta;
crate::library::models::TrackItem::podcast_episode(
episode(n, &format!("Episode {n}"), None)
.episode
.to_ref(&meta),
)
}
File diff suppressed because it is too large. Load diff
+293 -10
View File
@@ -97,6 +97,8 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
return; return;
}; };
match popup { 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 } => { Popup::AddToPlaylist { target, cursor } => {
handle_picker(state, runtime, target, cursor, key); handle_picker(state, runtime, target, cursor, key);
} }
@@ -115,6 +117,62 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
Popup::ConfirmDelete { target, label } => { Popup::ConfirmDelete { target, label } => {
handle_confirm_delete(state, runtime, target, label, key); handle_confirm_delete(state, runtime, target, label, key);
} }
Popup::ConfirmPodcastUnsubscribe { podcast_id, title } => match key.code {
KeyCode::Enter | KeyCode::Char('y') => super::perform_effect(
state,
runtime,
crate::app::update::Effect::PodcastUnsubscribe { podcast_id, title },
),
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {}
_ => state.popup = Some(Popup::ConfirmPodcastUnsubscribe { podcast_id, title }),
},
popup @ Popup::PodcastCard { .. } => {
if let Some(effect) =
crate::app::update::podcast_discovery::card_key(state, popup, key.code)
{
super::perform_effect(state, runtime, effect);
}
}
popup @ Popup::ConfirmPodcastShare { .. } => {
if let Some(effect) =
crate::app::update::podcasts::share_confirmation_key(state, popup, key.code)
{
super::perform_effect(state, runtime, effect);
}
}
Popup::SimilarityPrivacyConsent { enable_federation } => match key.code {
KeyCode::Enter | KeyCode::Char('y') => {
state.similarity.settings.federation_consent = true;
state.similarity.settings.enabled = true;
super::perform_effect(
state,
runtime,
crate::app::update::Effect::SimilarityApplySettings,
);
if enable_federation {
super::perform_effect(
state,
runtime,
crate::app::update::Effect::FedApplySettings,
);
}
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {
if enable_federation {
state.federation.settings.enabled = false;
}
}
_ => {
state.popup = Some(Popup::SimilarityPrivacyConsent { enable_federation });
}
},
Popup::ConfirmClearEmbeddings => match key.code {
KeyCode::Enter | KeyCode::Char('y') => {
super::perform_effect(state, runtime, crate::app::update::Effect::SimilarityClear)
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {}
_ => state.popup = Some(Popup::ConfirmClearEmbeddings),
},
Popup::LibraryFilters { cursor } => handle_library_filters(state, runtime, cursor, key), Popup::LibraryFilters { cursor } => handle_library_filters(state, runtime, cursor, key),
Popup::TrackInfo { Popup::TrackInfo {
tracks, tracks,
@@ -136,17 +194,52 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {} KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {}
_ => state.popup = Some(Popup::FedText { title, text }), _ => state.popup = Some(Popup::FedText { title, text }),
}, },
Popup::FedCopyText { title, text, help } => match key.code { Popup::FedCopyText {
title,
text,
help,
mut cursor,
} => match key.code {
KeyCode::Esc | KeyCode::Char('q') => {} KeyCode::Esc | KeyCode::Char('q') => {}
KeyCode::Left | KeyCode::Right | KeyCode::Tab | KeyCode::BackTab => {
cursor = usize::from(cursor == 0);
state.popup = Some(Popup::FedCopyText {
title,
text,
help,
cursor,
});
}
KeyCode::Enter if cursor == 1 => state.popup = Some(Popup::PlainText { text }),
KeyCode::Char('p') => state.popup = Some(Popup::PlainText { text }),
KeyCode::Enter | KeyCode::Char('c') => match copy_to_clipboard(&text) { KeyCode::Enter | KeyCode::Char('c') => match copy_to_clipboard(&text) {
Ok(()) => state.status_message = Some("copied to clipboard".to_string()), Ok(()) => state.status_message = Some("copied to clipboard".to_string()),
Err(err) => { Err(err) => {
state.status_message = Some(format!("copy failed: {err}")); state.status_message = Some(format!("copy failed: {err}"));
state.popup = Some(Popup::FedCopyText { title, text, help }); state.popup = Some(Popup::FedCopyText {
title,
text,
help,
cursor,
});
} }
}, },
_ => state.popup = Some(Popup::FedCopyText { title, text, help }), _ => {
state.popup = Some(Popup::FedCopyText {
title,
text,
help,
cursor,
})
}
}, },
Popup::PlainText { text } => match key.code {
KeyCode::Esc => {}
_ => state.popup = Some(Popup::PlainText { text }),
},
Popup::ConfirmMusicDirectory { path } => {
handle_music_directory_confirmation(state, runtime, path, key)
}
Popup::FederationStatusDetails { Popup::FederationStatusDetails {
focus, focus,
status_cursor, status_cursor,
@@ -489,10 +582,31 @@ fn handle_fed_input(
key: KeyEvent, key: KeyEvent,
) { ) {
match key.code { match key.code {
KeyCode::Esc => {} KeyCode::Esc => {
// Esc in the episode search clears it.
if field == FedInputField::PodcastSearch
&& let Some(effect) = crate::app::update::podcasts::set_search(state, String::new())
{
super::perform_effect(state, runtime, effect);
}
}
KeyCode::Enter => { KeyCode::Enter => {
let value = input.trim().to_string(); let value = input.trim().to_string();
match field { match field {
FedInputField::PodcastFeedUrl => {
if let Some(effect) =
crate::app::update::podcasts::submit_feed_url(state, &value)
{
super::perform_effect(state, runtime, effect);
}
}
// The search is applied while typing; Enter keeps it.
FedInputField::PodcastSearch => {
let search = input.to_string();
if let Some(effect) = crate::app::update::podcasts::set_search(state, search) {
super::perform_effect(state, runtime, effect);
}
}
FedInputField::NetworkId => { FedInputField::NetworkId => {
state.federation.settings.network_id = value; state.federation.settings.network_id = value;
// An empty id turns federation off rather than leaving a // An empty id turns federation off rather than leaving a
@@ -502,6 +616,72 @@ fn handle_fed_input(
!state.federation.settings.network_id.is_empty(); !state.federation.settings.network_id.is_empty();
super::fed_apply_settings(state, runtime); 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());
} else {
super::validate_music_directory(state, runtime, value.into());
}
}
FedInputField::SimilarityWorkers => match value.parse::<usize>() {
Ok(workers @ 1..=16) => {
state.similarity.settings.workers = workers;
super::perform_effect(
state,
runtime,
crate::app::update::Effect::SimilarityApplySettings,
);
}
_ => {
state.status_message =
Some("similarity workers must be a number from 1 to 16".into());
state.popup = Some(Popup::FedInput { field, input });
}
},
FedInputField::SimilarityMinimumScore => match value.parse::<f32>() {
Ok(score) if score.is_finite() && (0.0..=1.0).contains(&score) => {
state.similarity.settings.minimum_score = score;
super::perform_effect(
state,
runtime,
crate::app::update::Effect::SimilarityApplySettings,
);
}
_ => {
state.status_message =
Some("minimum similarity must be a number from 0.00 to 1.00".into());
state.popup = Some(Popup::FedInput { field, input });
}
},
FedInputField::SimilarityMaxTracksPerArtist => match value.parse::<usize>() {
Ok(limit @ 1..=50) => {
state.similarity.settings.max_tracks_per_artist = limit;
super::perform_effect(
state,
runtime,
crate::app::update::Effect::SimilarityApplySettings,
);
}
_ => {
state.status_message =
Some("tracks per artist must be a number from 1 to 50".into());
state.popup = Some(Popup::FedInput { field, input });
}
},
FedInputField::ConnectTicket => { FedInputField::ConnectTicket => {
if value.is_empty() { if value.is_empty() {
state.status_message = Some("ticket is empty".into()); state.status_message = Some("ticket is empty".into());
@@ -546,10 +726,41 @@ fn handle_fed_input(
} }
_ => { _ => {
input.handle_key(key); input.handle_key(key);
let search = (field == FedInputField::PodcastSearch).then(|| input.to_string());
state.popup = Some(Popup::FedInput { field, input }); state.popup = Some(Popup::FedInput { field, input });
if let Some(search) = search
&& let Some(effect) = crate::app::update::podcasts::set_search(state, search)
{
super::perform_effect(state, runtime, effect);
} }
} }
} }
}
fn handle_music_directory_confirmation(
state: &mut AppState,
runtime: &mut Runtime,
path: std::path::PathBuf,
key: KeyEvent,
) {
let move_existing = match key.code {
KeyCode::Esc | KeyCode::Char('q') => return,
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => true,
KeyCode::Char('n') | KeyCode::Char('N') => false,
_ => {
state.popup = Some(Popup::ConfirmMusicDirectory { path });
return;
}
};
super::perform_effect(
state,
runtime,
crate::app::update::Effect::ChangeMusicDirectory {
path,
move_existing,
},
);
}
fn handle_device_pairing( fn handle_device_pairing(
state: &mut AppState, state: &mut AppState,
@@ -640,11 +851,21 @@ fn handle_device_leave(state: &mut AppState, runtime: &mut Runtime, key: KeyEven
} }
/// Pasted text goes into the focused text field when one is open. /// Pasted text goes into the focused text field when one is open.
pub fn handle_paste(state: &mut AppState, pasted: &str) { 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 cleaned: String = pasted.chars().filter(|c| !c.is_control()).collect();
let mut search = None;
match &mut state.popup { match &mut state.popup {
Some(Popup::NewPlaylist { input, busy, .. }) if !*busy => input.insert_str(&cleaned), Some(Popup::NewPlaylist { input, busy, .. }) if !*busy => input.insert_str(&cleaned),
Some(Popup::FedInput { input, .. }) => input.insert_str(&cleaned), Some(Popup::FedInput { field, input }) => {
input.insert_str(&cleaned);
if *field == FedInputField::PodcastSearch {
search = Some(input.to_string());
}
}
Some(Popup::Edit { fields, focus, .. }) => { Some(Popup::Edit { fields, focus, .. }) => {
if let Some(field) = fields.get_mut(*focus) { if let Some(field) = fields.get_mut(*focus) {
field.value.insert_str(&cleaned); field.value.insert_str(&cleaned);
@@ -652,6 +873,11 @@ pub fn handle_paste(state: &mut AppState, pasted: &str) {
} }
_ => {} _ => {}
} }
if let Some(search) = search
&& let Some(effect) = crate::app::update::podcasts::set_search(state, search)
{
super::perform_effect(state, runtime, effect);
}
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -674,6 +900,17 @@ fn handle_edit(
) { ) {
match key.code { match key.code {
KeyCode::Esc => return, 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 => { KeyCode::Enter => {
match save_edit(runtime, target, &fields) { match save_edit(runtime, target, &fields) {
Ok(message) => { Ok(message) => {
@@ -873,6 +1110,21 @@ fn handle_track_info(
let len = tracks.len(); let len = tracks.len();
match key.code { match key.code {
KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {} KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {}
// An episode's "artist" is its podcast title: never look it up as a
// federated artist (that would send a private title to the
// network); open the podcast instead.
KeyCode::Char('a')
if tracks
.get(cursor.min(len.saturating_sub(1)))
.is_some_and(TrackItem::is_podcast) =>
{
let track = tracks[cursor.min(len.saturating_sub(1))].clone();
if let Some(effect) =
crate::app::update::podcasts::reveal_episode_podcast(state, &track)
{
super::perform_effect(state, runtime, effect);
}
}
KeyCode::Char('a') => { KeyCode::Char('a') => {
let artists = tracks let artists = tracks
.get(cursor.min(len.saturating_sub(1))) .get(cursor.min(len.saturating_sub(1)))
@@ -934,10 +1186,19 @@ fn handle_track_info(
KeyCode::Char('c') => { KeyCode::Char('c') => {
if let Some(track) = tracks.get(cursor.min(len.saturating_sub(1))) { if let Some(track) = tracks.get(cursor.min(len.saturating_sub(1))) {
match crate::share::track_share_link(track) { match crate::share::track_share_link(track) {
Some(link) => match copy_to_clipboard(&link) { None if track.is_podcast() => {
Ok(()) => state.status_message = Some("frid link copied".into()), state.status_message =
Err(err) => state.status_message = Some(format!("copy failed: {err}")), Some("podcast episodes have no track share link".into())
}, }
Some(link) => {
state.popup = Some(Popup::FedCopyText {
title: "Track share link".into(),
text: link,
help: "Copy the link with a clipboard helper, or show it as one clean terminal line for mouse selection.".into(),
cursor: 0,
});
return;
}
None => state.status_message = Some("no content id for this track yet".into()), None => state.status_message = Some("no content id for this track yet".into()),
} }
} }
@@ -947,6 +1208,28 @@ fn handle_track_info(
scroll, scroll,
}); });
} }
KeyCode::Char('s') => {
let Some(track) = tracks.get(cursor.min(len.saturating_sub(1))) else {
return;
};
if !state.similarity.settings.enabled {
state.status_message = Some("enable Similarity search in Settings first".into());
state.popup = Some(Popup::TrackInfo {
tracks,
cursor,
scroll,
});
} else if track.is_podcast() || track.id < 0 || track.file_path.is_empty() {
state.status_message = Some("similarity search starts from a local track".into());
state.popup = Some(Popup::TrackInfo {
tracks,
cursor,
scroll,
});
} else {
super::cmdline::schedule_similarity_search(state, runtime, track);
}
}
_ => { _ => {
state.popup = Some(Popup::TrackInfo { state.popup = Some(Popup::TrackInfo {
tracks, tracks,
+488
View File
@@ -0,0 +1,488 @@
//! 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 anyhow::Context as _;
use furumi_control_protocol::{LikedRadioSeed, Radio as Status, RadioState};
use rand::seq::SliceRandom;
use super::event::AppEvent;
use super::state::{AppState, SimilaritySearchHit};
use super::{Runtime, update};
use crate::library::{LIKES_PLAYLIST_ID, Library, models::TrackItem};
#[derive(Debug, Default)]
pub(super) struct Radio {
pub status: Status,
seed: String,
from_likes: bool,
original_track: Option<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) enum Seed {
Current(Box<TrackItem>),
Liked(String),
}
pub(super) fn begin(
state: &mut AppState,
liked_key: Option<String>,
request_id: String,
) -> Result<Seed, 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_key, seed) = if let Some(key) = liked_key {
(key.clone(), Seed::Liked(key))
} else {
let track = state
.player
.current
.as_ref()
.ok_or("Play a music track before starting radio")?;
if track.is_podcast() {
return Err("Similarity radio is available for music tracks only".into());
}
(identity(track), Seed::Current(Box::new(track.clone())))
};
state.radio = Radio {
status: Status {
id: state.radio.status.id.wrapping_add(1),
state: RadioState::Searching,
error: None,
request_id: Some(request_id),
},
seed: seed_key,
from_likes: matches!(seed, Seed::Liked(_)),
original_track: state.player.current.as_ref().map(identity),
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)
}
// A controller's numeric row IDs are not the output's IDs.
fn local_id(library: &Library, track: &TrackItem) -> anyhow::Result<Option<i64>> {
if track.id >= 0 && track.fed.is_none() && !track.is_podcast() {
return Ok(Some(track.id));
}
match super::state::track_content_id(track) {
Some(content_id) => library.track_id_by_content_id(&content_id),
None => Ok(None),
}
}
fn choose_liked(
library: &Library,
profile: Option<&str>,
exclude: Option<&str>,
) -> anyhow::Result<LikedRadioSeed> {
let mut tracks = library.playlist(LIKES_PLAYLIST_ID)?.tracks;
anyhow::ensure!(!tracks.is_empty(), "Like a track first");
let profile = profile.context("No similarity index is ready yet")?;
tracks.shuffle(&mut rand::rng());
// A shuffled traversal gives every eligible choice a chance. Keep the
// previous one only as a fallback for libraries with one eligible like.
let mut previous = None;
for track in tracks {
let Some(id) = local_id(library, &track)? else {
continue;
};
if library.similarity_embedding(id, profile)?.is_none() {
continue;
}
let seed = LikedRadioSeed {
key: identity(&track),
artist: track.artist_line(),
title: track.title,
};
if exclude != Some(seed.key.as_str()) {
return Ok(seed);
}
previous = Some(seed);
}
previous.context("No liked tracks in the local similarity index")
}
// Rerolls may supersede only their own unfinished liked-radio search. Once
// the queue has committed, ordinary playback owns it.
pub(super) fn supersede(state: &mut AppState, request_id: &str) -> bool {
if state.radio.from_likes
&& state.radio.status.state == RadioState::Searching
&& state.radio.status.request_id.as_deref() == Some(request_id)
{
state.radio.status.state = RadioState::Idle;
state.radio.deadline = None;
return true;
}
false
}
pub(super) fn pick_liked(
state: &mut AppState,
runtime: &mut Runtime,
exclude: Option<String>,
replace_request_id: Option<String>,
reply: crate::control::ReplySender,
) {
if replace_request_id
.as_deref()
.is_some_and(|id| supersede(state, id))
&& let Some(previous) = runtime.radio_task.take()
{
previous.abort();
}
if busy(state) {
let _ = reply.send(Err("Radio is already being prepared".into()));
return;
}
if !state.similarity.settings.enabled {
let _ = reply.send(Err(
"Enable similarity search in Furumi Settings first".into()
));
return;
}
let library = Arc::clone(&runtime.library);
let profile = runtime.similarity.status().active_profile;
tokio::task::spawn_blocking(move || {
let result = choose_liked(&library, profile.as_deref(), exclude.as_deref())
.map(crate::control::Reply::LikedRadioSeed)
.map_err(super::err_string);
let _ = reply.send(result);
});
}
fn liked_track_id(library: &Library, key: &str) -> anyhow::Result<i64> {
let track = library
.playlist(LIKES_PLAYLIST_ID)?
.tracks
.into_iter()
.find(|track| identity(track) == key)
.context("This track is no longer liked")?;
local_id(library, &track)?.context("This liked track is no longer available locally")
}
pub(super) fn start(
state: &mut AppState,
runtime: &mut Runtime,
liked_key: Option<String>,
request_id: String,
) -> Result<(), String> {
let seed = begin(state, liked_key, request_id)?;
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<_> {
let local_seed = match seed {
Seed::Current(track) => local_id(&library, &track)?.context(
"Import and index this track locally before starting similarity radio",
)?,
Seed::Liked(key) => liked_track_id(&library, &key)?,
};
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 !playback_unchanged(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 playback_unchanged(state: &AppState) -> bool {
state.player.current.as_ref().map(identity) == state.radio.original_track
&& 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 && !playback_unchanged(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();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn picks_only_indexed_likes_and_rechecks_the_exact_choice_on_start() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("library.sqlite3");
let library = Library::open(&path).unwrap();
assert!(choose_liked(&library, None, None).is_err());
let db = rusqlite::Connection::open(&path).unwrap();
db.execute("INSERT INTO releases (id, title) VALUES (1, 'Album')", [])
.unwrap();
for id in 1..=4 {
db.execute("INSERT INTO tracks (id, title, release_id, file_path, content_id) VALUES (?1, ?2, 1, ?2, ?3)",
rusqlite::params![id, format!("Song {id}"), format!("b3:{id:064x}")]).unwrap();
}
drop(db);
library.set_synced_like(1, true, 1).unwrap();
library.set_synced_like(3, true, 2).unwrap(); // No embedding for this track.
let profile = "test-profile";
library
.ensure_similarity_profile(profile, "model", "1", "hash", "test", 1280)
.unwrap();
assert!(choose_liked(&library, Some(profile), None).is_err());
let mut vector = vec![0.0; 1280];
vector[0] = 1.0;
for track in library.pending_similarity_tracks(profile).unwrap() {
if track.id != 3 {
library
.store_similarity_embedding(&track, profile, &vector)
.unwrap();
}
}
let first = choose_liked(&library, Some(profile), None).unwrap();
assert_eq!(first.title, "Song 1");
assert_eq!(
choose_liked(&library, Some(profile), Some(&first.key)).unwrap(),
first
);
// A liked entry learned from another device can use a local embedding
// by content ID even before the library has reconciled the like rows.
let remote_like = crate::federation::FedTrack {
item_id: "peer-track".into(),
owner: "peer".into(),
own: false,
title: "Remote title".into(),
artist_names: vec!["Artist".into()],
featured_artist_names: vec![],
content_id: Some(format!("b3:{:064x}", 2)),
release_title: None,
year: None,
duration_seconds: None,
track_number: None,
disc_number: None,
};
library.upsert_synced_fed_like(&remote_like, 3).unwrap();
let second = choose_liked(&library, Some(profile), Some(&first.key)).unwrap();
assert_eq!(second.title, remote_like.title);
assert_eq!(second.artist, "Artist");
assert_eq!(liked_track_id(&library, &second.key).unwrap(), 2);
assert_eq!(
choose_liked(&library, Some(profile), Some(&second.key)).unwrap(),
first
);
library.remove_fed_like_by_content_id(&second.key).unwrap();
assert!(liked_track_id(&library, &second.key).is_err());
assert_eq!(liked_track_id(&library, &first.key).unwrap(), 1);
}
}
+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()));
}
+852 -35
View File
File diff suppressed because it is too large. Load diff
+647 -56
View File
File diff suppressed because it is too large. Load diff
+135
View File
@@ -0,0 +1,135 @@
//! Public podcast cards opened from the search results.
//!
//! The card shows what its publishers claim. "Подписаться" subscribes with
//! the card's origin feed URL only (`Effect::PodcastSubscribeFromCard`); the
//! subscription is private and its metadata comes from the feed. When this
//! device is already subscribed (under the card's id or a feed alias), the
//! action reads «Уже подписан» and Enter opens the podcast instead.
use crossterm::event::KeyCode;
use music_dht::podcast::PodcastId;
use super::Effect;
use super::podcasts::{display_title, reveal_podcast, store_ready};
use crate::app::state::{AppState, Loadable, Popup};
use crate::podcasts::discovery::{FeedPreview, PodcastHit};
/// Lines a page key scrolls the card by.
const PAGE: u16 = 10;
/// Enter on a podcast hit of the search results.
pub fn open_card(state: &mut AppState, index: usize) {
let Some(hit) = state.search.fed_podcasts.get(index) else {
return;
};
state.popup = Some(Popup::PodcastCard {
hit: Box::new(hit.clone()),
preview: None,
scroll: 0,
max_scroll: std::cell::Cell::new(u16::MAX),
});
}
/// A key in [`Popup::PodcastCard`] (the popup was taken out of the state):
/// Enter/s subscribes (or opens the subscribed podcast), `e` reads the
/// episodes from the feed, arrows and page keys scroll, Esc/q closes.
pub fn card_key(state: &mut AppState, popup: Popup, key: KeyCode) -> Option<Effect> {
let Popup::PodcastCard {
hit,
mut preview,
mut scroll,
max_scroll,
} = popup
else {
state.popup = Some(popup);
return None;
};
let mut effect = None;
match key {
KeyCode::Esc | KeyCode::Char('q') => return None,
KeyCode::Enter | KeyCode::Char('s') => {
if let Some(id) = subscribed_id(state, &hit, preview.as_ref()) {
// «Уже подписан»: show the subscription instead.
return reveal_podcast(state, id, hit.title());
}
effect = subscribe(state, &hit);
}
KeyCode::Char('e') => {
if !matches!(preview, Some(Loadable::Loading | Loadable::Ready(_))) {
preview = Some(Loadable::Loading);
effect = Some(Effect::PodcastPreview {
podcast_id: hit.hit.podcast_id.clone(),
feed_url: hit.hit.feed_url.clone(),
});
}
}
KeyCode::Up | KeyCode::Char('k') => scroll = scroll.saturating_sub(1),
KeyCode::Down | KeyCode::Char('j') => scroll = scroll.saturating_add(1),
KeyCode::PageUp => scroll = scroll.saturating_sub(PAGE),
KeyCode::PageDown => scroll = scroll.saturating_add(PAGE),
KeyCode::Home | KeyCode::Char('g') => scroll = 0,
_ => {}
}
// Never past the end the last draw measured, so scrolling back moves
// the view at once.
scroll = scroll.min(max_scroll.get());
state.popup = Some(Popup::PodcastCard {
hit,
preview,
scroll,
max_scroll,
});
effect
}
/// The id under which this device is subscribed to the card's podcast: the
/// card's id, the id its origin URL resolves to here (a feed alias), or —
/// once the feed was read — the podcast followed under the newer address
/// the feed moved to.
pub fn subscribed_id(
state: &AppState,
hit: &PodcastHit,
preview: Option<&Loadable<FeedPreview>>,
) -> Option<PodcastId> {
let moved = match preview {
Some(Loadable::Ready(preview)) => preview.subscribed_as.as_ref(),
_ => None,
};
hit.ids()
.into_iter()
.chain(moved)
.find(|id| state.podcasts.podcast(id).is_some())
.cloned()
}
fn subscribe(state: &mut AppState, hit: &PodcastHit) -> Option<Effect> {
if !store_ready(state) {
return None;
}
if state.podcasts.subscribing {
state.status_message = Some("podcasts: a subscription is already being added".into());
return None;
}
state.podcasts.subscribing = true;
state.status_message = Some(format!(
"podcasts: reading the feed of {}…",
display_title(hit.title())
));
Some(Effect::PodcastSubscribeFromCard(Box::new(hit.hit.clone())))
}
/// The preview of an open card arrived (ignored when another card is open).
pub fn preview_loaded(
state: &mut AppState,
podcast_id: PodcastId,
result: Result<Box<FeedPreview>, String>,
) {
if let Some(Popup::PodcastCard { hit, preview, .. }) = &mut state.popup
&& hit.hit.podcast_id == podcast_id
{
*preview = Some(match result {
Ok(feed) => Loadable::Ready(*feed),
Err(err) => Loadable::Failed(err),
});
}
}
File diff suppressed because it is too large. Load diff
+2531 -7
View File
File diff suppressed because it is too large. Load diff
+92 -5
View File
@@ -1,15 +1,27 @@
# Default keybindings for furumi. # Default keybindings for furumi.
# #
# To customize, copy entries into <config dir>/furumi/keymap.toml # To customize, copy entries into keymap.toml in the platform config dir
# (~/.config/furumi/keymap.toml on Linux/macOS). A user binding replaces the # (~/.config/furumi/keymap.toml on Linux,
# default binding with the same key sequence and context. # ~/Library/Application Support/furumi/keymap.toml on macOS). A user binding
# replaces the default binding with the same key sequence and context.
#
# version: keymap format version; put `version = 2` at the top of your file,
# before the first [[keymaps]] entry (after one, TOML attaches it to that
# entry and the file is rejected). Version 2 numbers tabs in this order:
# GoToTab = 0 Library, 1 Playlists, 2 Queue, 3 Podcasts, 4 Settings, 5 Logs.
# A file without `version` is treated as the older layout and its GoToTab
# indices are adapted in memory (3 -> 4 Settings, 4 -> 5 Logs, and 5 -> 3
# Podcasts from the prototype podcast build); the file itself is never
# rewritten. With `version = 2` indices are used exactly as written.
# #
# key_sequence: space-separated chords, e.g. "g g" or "ctrl-a x". # key_sequence: space-separated chords, e.g. "g g" or "ctrl-a x".
# Modifiers: ctrl-, alt-, shift-, cmd-. Uppercase letters: "shift-g". # Modifiers: ctrl-, alt-, shift-, cmd-. Uppercase letters: "shift-g".
# command: an Action name, optionally with parameters: # command: an Action name, optionally with parameters:
# command = { SeekForward = { seconds = 30 } } # command = { SeekForward = { seconds = 30 } }
# context: optional view filter — global (default), library, search, # context: optional view filter — global (default), library, search,
# playlists, queue, logs. # playlists, queue, podcasts, settings, logs.
version = 2
[[keymaps]] [[keymaps]]
key_sequence = "q" key_sequence = "q"
@@ -51,6 +63,10 @@ command = { GoToTab = 3 }
key_sequence = "5" key_sequence = "5"
command = { GoToTab = 4 } command = { GoToTab = 4 }
[[keymaps]]
key_sequence = "6"
command = { GoToTab = 5 }
[[keymaps]] [[keymaps]]
key_sequence = "y" key_sequence = "y"
command = "DownloadSelected" command = "DownloadSelected"
@@ -63,6 +79,16 @@ command = "QueueAddNext"
key_sequence = "shift-a" key_sequence = "shift-a"
command = "QueueAddLast" command = "QueueAddLast"
[[keymaps]]
key_sequence = "alt-k"
command = "MoveQueueUp"
context = "queue"
[[keymaps]]
key_sequence = "alt-j"
command = "MoveQueueDown"
context = "queue"
[[keymaps]] [[keymaps]]
key_sequence = "shift-c" key_sequence = "shift-c"
command = "OpenConnectedDevices" command = "OpenConnectedDevices"
@@ -111,7 +137,11 @@ command = "MoveLeft"
[[keymaps]] [[keymaps]]
key_sequence = "l" key_sequence = "l"
command = "MoveRight" command = "OpenLyrics"
[[keymaps]]
key_sequence = "ctrl-l"
command = "OpenCurrentLyrics"
[[keymaps]] [[keymaps]]
key_sequence = "right" key_sequence = "right"
@@ -197,6 +227,10 @@ command = "CycleRepeat"
key_sequence = "shift-l" key_sequence = "shift-l"
command = "ToggleVisualizer" command = "ToggleVisualizer"
[[keymaps]]
key_sequence = "shift-m"
command = "CycleVisualizerMode"
[[keymaps]] [[keymaps]]
key_sequence = "shift-h" key_sequence = "shift-h"
command = "OpenListenHistory" command = "OpenListenHistory"
@@ -245,3 +279,56 @@ command = "OpenCommandLine"
[[keymaps]] [[keymaps]]
key_sequence = "/" key_sequence = "/"
command = "OpenSearch" command = "OpenSearch"
# Podcasts tab. Enter opens a podcast, its seasons and episodes, and plays
# an episode (continuing where you stopped); Esc goes back. a / shift-a queue
# the episode; Shift-D also unsubscribes here.
[[keymaps]]
key_sequence = "o"
command = "AddPodcast"
context = "podcasts"
[[keymaps]]
key_sequence = "/"
command = "SearchEpisodes"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-r"
command = "RefreshPodcast"
context = "podcasts"
[[keymaps]]
key_sequence = "ctrl-r"
command = "RefreshAllPodcasts"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-s"
command = "CycleEpisodeSort"
context = "podcasts"
[[keymaps]]
key_sequence = "f"
command = "CycleEpisodeFilter"
context = "podcasts"
[[keymaps]]
key_sequence = "m"
command = "ToggleEpisodePlayed"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-u"
command = "UnsubscribePodcast"
context = "podcasts"
[[keymaps]]
key_sequence = "b"
command = "RestartEpisode"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-f"
command = "TogglePodcastShare"
context = "podcasts"
+354 -4
View File
@@ -9,6 +9,14 @@ use crate::app::action::Action;
const DEFAULT_KEYMAP: &str = include_str!("default_keymap.toml"); const DEFAULT_KEYMAP: &str = include_str!("default_keymap.toml");
/// Current keymap file format, declared as a top-level `version = 2`.
///
/// Version 2 introduced the tab order Library, Playlists, Queue, Podcasts,
/// Settings, Logs. Files without a version (or with `version = 1`) were
/// written for the older order and have their `GoToTab` indices remapped in
/// memory; the user's file itself is never rewritten.
pub const KEYMAP_VERSION: u32 = 2;
/// Input context a binding applies to. `Global` bindings work everywhere; /// Input context a binding applies to. `Global` bindings work everywhere;
/// view-specific bindings shadow global ones for the same key sequence. /// view-specific bindings shadow global ones for the same key sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
@@ -20,6 +28,7 @@ pub enum KeyContext {
Search, Search,
Playlists, Playlists,
Queue, Queue,
Podcasts,
#[serde(rename = "settings", alias = "federation")] #[serde(rename = "settings", alias = "federation")]
Federation, Federation,
Logs, Logs,
@@ -33,6 +42,7 @@ impl KeyContext {
KeyContext::Search => "search", KeyContext::Search => "search",
KeyContext::Playlists => "playlists", KeyContext::Playlists => "playlists",
KeyContext::Queue => "queue", KeyContext::Queue => "queue",
KeyContext::Podcasts => "podcasts",
KeyContext::Federation => "settings", KeyContext::Federation => "settings",
KeyContext::Logs => "logs", KeyContext::Logs => "logs",
} }
@@ -52,10 +62,18 @@ struct RawBinding {
command: Action, command: Action,
#[serde(default)] #[serde(default)]
context: KeyContext, context: KeyContext,
/// Never valid here: a `version = N` line written after a `[[keymaps]]`
/// header lands inside that entry. Caught so the file is not silently
/// treated as legacy (and its tab indices remapped) despite the version.
#[serde(default)]
version: Option<toml::Value>,
} }
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize)]
struct KeymapFile { struct KeymapFile {
/// Format version; `None` means a legacy (pre-version-2) file.
#[serde(default)]
version: Option<u32>,
#[serde(default)] #[serde(default)]
keymaps: Vec<RawBinding>, keymaps: Vec<RawBinding>,
} }
@@ -87,9 +105,15 @@ impl Keymap {
{ {
match fs::read_to_string(&path) match fs::read_to_string(&path)
.map_err(anyhow::Error::from) .map_err(anyhow::Error::from)
.and_then(|text| parse_bindings(&text)) .and_then(|text| parse_user_keymap(&text))
{ {
Ok(user) => merge(&mut bindings, user), Ok(user) => {
if let Some(notice) = user.notice {
tracing::info!(path = %path.display(), "{notice}");
warning = Some(format!("{}: {notice}", path.display()));
}
merge(&mut bindings, user.bindings);
}
Err(err) => { Err(err) => {
warning = Some(format!( warning = Some(format!(
"{} ignored: {err:#}; using default keybindings", "{} ignored: {err:#}; using default keybindings",
@@ -106,6 +130,16 @@ impl Keymap {
(keymap, warning) (keymap, warning)
} }
/// The embedded defaults only, without reading the user's file.
#[cfg(test)]
pub(crate) fn defaults() -> Self {
Self {
bindings: parse_bindings(DEFAULT_KEYMAP).expect("embedded default keymap must parse"),
pending: Vec::new(),
format: KeyCombinationFormat::default(),
}
}
/// Feed one key combination; returns an action, a pending-chord state, or /// Feed one key combination; returns an action, a pending-chord state, or
/// nothing. Esc clears a pending chord instead of resolving. /// nothing. Esc clears a pending chord instead of resolving.
pub fn resolve(&mut self, key: KeyCombination, context: KeyContext) -> KeyResolution { pub fn resolve(&mut self, key: KeyCombination, context: KeyContext) -> KeyResolution {
@@ -275,10 +309,76 @@ pub fn user_keymap_path() -> Option<PathBuf> {
} }
fn parse_bindings(text: &str) -> Result<Vec<Binding>> { fn parse_bindings(text: &str) -> Result<Vec<Binding>> {
parse_file(text).map(|(_, bindings)| bindings)
}
/// A user keymap after version handling, plus a one-time, non-blocking
/// notice for the status bar and log when its meaning was adapted.
struct UserKeymap {
bindings: Vec<Binding>,
notice: Option<String>,
}
fn parse_user_keymap(text: &str) -> Result<UserKeymap> {
let (version, mut bindings) = parse_file(text)?;
let notice = match version {
None | Some(1) => {
let remapped = remap_legacy_tab_indices(&mut bindings);
(remapped > 0).then(|| {
format!(
"{remapped} tab shortcut(s) adapted to the new tab order \
(4 Podcasts, 5 Settings, 6 Logs); \
add `version = {KEYMAP_VERSION}` to use indices as written"
)
})
}
Some(KEYMAP_VERSION) => None,
Some(0) => bail!("unsupported keymap version 0"),
Some(newer) => Some(format!(
"keymap version {newer} is newer than this build supports \
({KEYMAP_VERSION}); bindings are used as written"
)),
};
Ok(UserKeymap { bindings, notice })
}
/// Pre-version-2 `GoToTab` index → current index. Index 5 only existed in the
/// prototype podcast build, where it opened Podcasts.
fn legacy_tab_index(index: usize) -> usize {
match index {
3 => 4, // Settings
4 => 5, // Logs
5 => 3, // Podcasts (prototype)
other => other,
}
}
/// Rewrites legacy `GoToTab` indices in memory; returns how many changed.
fn remap_legacy_tab_indices(bindings: &mut [Binding]) -> usize {
let mut remapped = 0;
for binding in bindings {
if let Action::GoToTab(index) = &mut binding.action {
let current = legacy_tab_index(*index);
if current != *index {
*index = current;
remapped += 1;
}
}
}
remapped
}
fn parse_file(text: &str) -> Result<(Option<u32>, Vec<Binding>)> {
let file: KeymapFile = toml::from_str(text).context("invalid TOML")?; let file: KeymapFile = toml::from_str(text).context("invalid TOML")?;
file.keymaps let bindings = file
.keymaps
.into_iter() .into_iter()
.map(|raw| { .map(|raw| {
if raw.version.is_some() {
bail!(
"`version` must be a top-level key placed before the first [[keymaps]] entry"
);
}
let keys = parse_sequence(&raw.key_sequence) let keys = parse_sequence(&raw.key_sequence)
.with_context(|| format!("bad key_sequence {:?}", raw.key_sequence))?; .with_context(|| format!("bad key_sequence {:?}", raw.key_sequence))?;
Ok(Binding { Ok(Binding {
@@ -287,7 +387,8 @@ fn parse_bindings(text: &str) -> Result<Vec<Binding>> {
context: raw.context, context: raw.context,
}) })
}) })
.collect() .collect::<Result<_>>()?;
Ok((file.version, bindings))
} }
fn parse_sequence(s: &str) -> Result<Vec<KeyCombination>> { fn parse_sequence(s: &str) -> Result<Vec<KeyCombination>> {
@@ -355,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] #[test]
fn chord_sequence_resolves() { fn chord_sequence_resolves() {
let mut km = keymap_from(DEFAULT_KEYMAP); let mut km = keymap_from(DEFAULT_KEYMAP);
@@ -483,6 +597,11 @@ mod tests {
km.resolve(shift_l, KeyContext::Library), km.resolve(shift_l, KeyContext::Library),
KeyResolution::Action(Action::ToggleVisualizer) 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] #[test]
@@ -597,6 +716,237 @@ mod tests {
); );
} }
#[test]
fn default_keymap_declares_current_version() {
let (version, _) = parse_file(DEFAULT_KEYMAP).unwrap();
assert_eq!(version, Some(KEYMAP_VERSION));
assert!(parse_user_keymap(DEFAULT_KEYMAP).unwrap().notice.is_none());
}
#[test]
fn default_digit_keys_follow_tab_order() {
let mut km = keymap_from(DEFAULT_KEYMAP);
for (index, key) in ['1', '2', '3', '4', '5', '6'].into_iter().enumerate() {
let combo = KeyCombination::new(KeyCode::Char(key), KeyModifiers::NONE);
assert_eq!(
km.resolve(combo, KeyContext::Library),
KeyResolution::Action(Action::GoToTab(index))
);
}
}
fn go_to_tab_indices(bindings: &[Binding]) -> Vec<usize> {
bindings
.iter()
.filter_map(|b| match b.action {
Action::GoToTab(index) => Some(index),
_ => None,
})
.collect()
}
const LEGACY_TABS: &str = r#"
[[keymaps]]
key_sequence = "1"
command = { GoToTab = 0 }
[[keymaps]]
key_sequence = "f2"
command = { GoToTab = 2 }
[[keymaps]]
key_sequence = "f4"
command = { GoToTab = 3 }
[[keymaps]]
key_sequence = "f5"
command = { GoToTab = 4 }
[[keymaps]]
key_sequence = "f6"
command = { GoToTab = 5 }
context = "logs"
[[keymaps]]
key_sequence = "x"
command = "ToggleHelp"
"#;
#[test]
fn legacy_keymap_tab_indices_are_remapped_in_memory() {
let user = parse_user_keymap(LEGACY_TABS).unwrap();
// Settings 3 -> 4, Logs 4 -> 5, prototype Podcasts 5 -> 3.
assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 4, 5, 3]);
assert_eq!(user.bindings[4].context, KeyContext::Logs);
assert_eq!(user.bindings[5].action, Action::ToggleHelp);
let notice = user.notice.expect("remap must be reported");
assert!(notice.starts_with("3 tab shortcut(s)"), "{notice}");
assert!(notice.contains("version = 2"), "{notice}");
}
#[test]
fn explicit_version_one_is_treated_as_legacy() {
let user = parse_user_keymap(&format!("version = 1\n{LEGACY_TABS}")).unwrap();
assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 4, 5, 3]);
assert!(user.notice.is_some());
}
#[test]
fn legacy_keymap_without_changed_tab_indices_has_no_notice() {
let user = parse_user_keymap(
r#"
[[keymaps]]
key_sequence = "1"
command = { GoToTab = 0 }
[[keymaps]]
key_sequence = "q"
command = "Back"
"#,
)
.unwrap();
assert_eq!(go_to_tab_indices(&user.bindings), [0]);
assert!(user.notice.is_none());
}
#[test]
fn versioned_keymap_is_taken_literally() {
let user = parse_user_keymap(&format!("version = 2\n{LEGACY_TABS}")).unwrap();
assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 3, 4, 5]);
assert!(user.notice.is_none());
}
#[test]
fn newer_keymap_version_is_used_as_written_with_a_notice() {
let user = parse_user_keymap(&format!("version = 3\n{LEGACY_TABS}")).unwrap();
assert_eq!(go_to_tab_indices(&user.bindings), [0, 2, 3, 4, 5]);
assert!(user.notice.unwrap().contains("newer"));
}
#[test]
fn version_inside_a_keymaps_entry_is_rejected() {
// Appended at the end, TOML puts `version` into the last entry; the
// file must not silently fall back to the legacy remap.
let err = parse_user_keymap(
"[[keymaps]]\nkey_sequence = \"4\"\ncommand = { GoToTab = 3 }\nversion = 2\n",
)
.err()
.expect("misplaced version must be rejected");
assert!(
format!("{err:#}").contains("before the first [[keymaps]]"),
"{err:#}"
);
}
#[test]
fn unknown_keys_in_keymaps_entries_are_still_ignored() {
let user = parse_user_keymap(
"version = 2\n[[keymaps]]\nkey_sequence = \"4\"\ncommand = { GoToTab = 3 }\nnote = \"mine\"\n",
)
.unwrap();
assert_eq!(go_to_tab_indices(&user.bindings), [3]);
}
#[test]
fn keymap_version_zero_is_rejected() {
assert!(parse_user_keymap("version = 0").is_err());
}
#[test]
fn legacy_user_digit_override_keeps_its_old_target() {
let mut bindings = parse_bindings(DEFAULT_KEYMAP).unwrap();
// An old file that swapped "4" and "5" (Settings / Logs).
let user = parse_user_keymap(
r#"
[[keymaps]]
key_sequence = "4"
command = { GoToTab = 4 }
[[keymaps]]
key_sequence = "5"
command = { GoToTab = 3 }
"#,
)
.unwrap();
merge(&mut bindings, user.bindings);
let mut km = Keymap {
bindings,
pending: Vec::new(),
format: KeyCombinationFormat::default(),
};
let four = KeyCombination::new(KeyCode::Char('4'), KeyModifiers::NONE);
let five = KeyCombination::new(KeyCode::Char('5'), KeyModifiers::NONE);
let six = KeyCombination::new(KeyCode::Char('6'), KeyModifiers::NONE);
// Still Logs and Settings, now at their new indices.
assert_eq!(
km.resolve(four, KeyContext::Library),
KeyResolution::Action(Action::GoToTab(5))
);
assert_eq!(
km.resolve(five, KeyContext::Library),
KeyResolution::Action(Action::GoToTab(4))
);
// The new default "6" is untouched by the user's file.
assert_eq!(
km.resolve(six, KeyContext::Library),
KeyResolution::Action(Action::GoToTab(5))
);
}
#[test]
fn podcasts_context_parses() {
let bindings = parse_bindings(
r#"
[[keymaps]]
key_sequence = "z"
command = "ToggleHelp"
context = "podcasts"
"#,
)
.unwrap();
assert_eq!(bindings[0].context, KeyContext::Podcasts);
assert_eq!(KeyContext::Podcasts.label(), "podcasts");
}
#[test]
fn default_podcast_keys_resolve_only_in_the_podcasts_context() {
let mut km = keymap_from(DEFAULT_KEYMAP);
let shift = |c| KeyCombination::new(KeyCode::Char(c), KeyModifiers::SHIFT);
let cases = [
(key!(o), Action::AddPodcast),
(key!('/'), Action::SearchEpisodes),
(shift('R'), Action::RefreshPodcast),
(key!(ctrl - r), Action::RefreshAllPodcasts),
(shift('S'), Action::CycleEpisodeSort),
(key!(f), Action::CycleEpisodeFilter),
(key!(m), Action::ToggleEpisodePlayed),
(shift('U'), Action::UnsubscribePodcast),
(key!(b), Action::RestartEpisode),
(shift('F'), Action::TogglePodcastShare),
];
for (key, action) in cases {
assert_eq!(
km.resolve(key, KeyContext::Podcasts),
KeyResolution::Action(action.clone()),
"{action:?}"
);
assert_ne!(
km.resolve(key, KeyContext::Library),
KeyResolution::Action(action.clone()),
"{action:?} leaks into the library"
);
}
// Playback keys keep working on the Podcasts tab.
assert_eq!(
km.resolve(key!(space), KeyContext::Podcasts),
KeyResolution::Action(Action::PlayPause)
);
assert_eq!(
km.resolve(key!(n), KeyContext::Podcasts),
KeyResolution::Action(Action::NextTrack)
);
}
#[test] #[test]
fn default_listening_history_key_resolves() { fn default_listening_history_key_resolves() {
let mut km = keymap_from(DEFAULT_KEYMAP); let mut km = keymap_from(DEFAULT_KEYMAP);
+125 -40
View File
@@ -1,77 +1,144 @@
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub use furumi_library::{LibraryFilters, LibrarySourceMode};
#[serde(rename_all = "snake_case")]
pub enum LibrarySourceMode {
#[default]
Local,
My,
Global,
}
impl LibrarySourceMode { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub fn label(self) -> &'static str { pub struct SimilaritySettings {
match self { /// Local embedding/search master switch. Network participation follows
LibrarySourceMode::Local => "Local", /// federation and additionally requires the explicit privacy consent.
LibrarySourceMode::My => "My",
LibrarySourceMode::Global => "Global",
}
}
pub fn includes_network(self) -> bool {
!matches!(self, LibrarySourceMode::Local)
}
pub fn includes_global_peers(self) -> bool {
matches!(self, LibrarySourceMode::Global)
}
pub fn next(self) -> Self {
match self {
LibrarySourceMode::Local => LibrarySourceMode::My,
LibrarySourceMode::My => LibrarySourceMode::Global,
LibrarySourceMode::Global => LibrarySourceMode::Local,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LibraryFilters {
#[serde(default)] #[serde(default)]
pub hide_featured_only: bool, pub enabled: bool,
#[serde(default = "default_similarity_model")]
pub model: String,
#[serde(default = "default_similarity_profile")]
pub profile: String,
#[serde(default = "default_similarity_workers")]
pub workers: usize,
/// Requester-side cosine score floor. This is search policy, not part of
/// the embedding profile, so changing it never invalidates vectors.
#[serde(default = "default_similarity_minimum_score")]
pub minimum_score: f32,
/// Requester-side diversity cap applied independently to local and
/// federated candidates.
#[serde(default = "default_similarity_max_tracks_per_artist")]
pub max_tracks_per_artist: usize,
#[serde(default)] #[serde(default)]
pub source_mode: LibrarySourceMode, pub federation_consent: bool,
/// Exact fingerprint of the last fully usable profile. Keeping this
/// separate from the selected target lets an old index serve searches
/// while a newly selected model/profile is being calculated.
#[serde(default)]
pub active_profile: Option<String>,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] impl Default for SimilaritySettings {
fn default() -> Self {
Self {
enabled: false,
model: default_similarity_model(),
profile: default_similarity_profile(),
workers: default_similarity_workers(),
minimum_score: default_similarity_minimum_score(),
max_tracks_per_artist: default_similarity_max_tracks_per_artist(),
federation_consent: false,
active_profile: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AppSettings { 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")] #[serde(default = "default_volume")]
pub volume: u8, pub volume: u8,
#[serde(default)] #[serde(default)]
pub library: LibraryFilters, pub library: LibraryFilters,
/// Root used for music materialized from federation peers.
#[serde(default = "default_music_dir")]
pub music_dir: PathBuf,
#[serde(default)]
pub similarity: SimilaritySettings,
} }
impl Default for AppSettings { impl Default for AppSettings {
fn default() -> Self { fn default() -> Self {
Self { Self {
podcast_retention_days: 30,
playback: music_dht::playback::Config::default(),
volume: default_volume(), volume: default_volume(),
library: LibraryFilters::default(), library: LibraryFilters::default(),
music_dir: default_music_dir(),
similarity: SimilaritySettings::default(),
} }
} }
} }
impl AppSettings { impl AppSettings {
pub fn normalized(mut self) -> Self { pub fn normalized(mut self) -> Self {
self.podcast_retention_days = self.podcast_retention_days.clamp(1, 36500);
self.volume = self.volume.min(100); self.volume = self.volume.min(100);
if self.music_dir.as_os_str().is_empty() {
self.music_dir = default_music_dir();
}
if self.similarity.model.trim().is_empty() {
self.similarity.model = default_similarity_model();
}
if self.similarity.profile.trim().is_empty() {
self.similarity.profile = default_similarity_profile();
}
self.similarity.workers = self.similarity.workers.clamp(1, 16);
if !self.similarity.minimum_score.is_finite() {
self.similarity.minimum_score = default_similarity_minimum_score();
}
self.similarity.minimum_score = self.similarity.minimum_score.clamp(0.0, 1.0);
self.similarity.max_tracks_per_artist = self.similarity.max_tracks_per_artist.clamp(1, 50);
self self
} }
} }
fn default_podcast_retention_days() -> u32 {
30
}
fn default_volume() -> u8 { fn default_volume() -> u8 {
80 80
} }
fn default_similarity_model() -> String {
"discogs-effnet-bsdynamic-1".to_string()
}
fn default_similarity_profile() -> String {
"furumi-full-track-v1".to_string()
}
fn default_similarity_workers() -> usize {
std::thread::available_parallelism()
.map(|count| (count.get() / 2).clamp(1, 4))
.unwrap_or(1)
}
fn default_similarity_minimum_score() -> f32 {
0.70
}
fn default_similarity_max_tracks_per_artist() -> usize {
5
}
/// The historical permanent-download location, kept as the default for
/// backward compatibility with existing installations.
pub fn default_music_dir() -> PathBuf {
crate::config::project_dirs()
.map(|dirs| dirs.data_dir().join("federation-media"))
.unwrap_or_else(|| PathBuf::from("federation-media"))
}
pub fn load() -> (AppSettings, Option<String>) { pub fn load() -> (AppSettings, Option<String>) {
let Some(path) = settings_path() else { let Some(path) = settings_path() else {
return (AppSettings::default(), None); return (AppSettings::default(), None);
@@ -127,7 +194,25 @@ hide_featured_only = true
let settings = settings.normalized(); let settings = settings.normalized();
assert_eq!(settings.volume, 100); assert_eq!(settings.volume, 100);
assert_eq!(settings.podcast_retention_days, 30);
assert!(settings.library.hide_featured_only); assert!(settings.library.hide_featured_only);
assert_eq!(settings.library.source_mode, LibrarySourceMode::Local); assert_eq!(settings.library.source_mode, LibrarySourceMode::Global);
assert_eq!(settings.music_dir, default_music_dir());
assert_eq!(settings.similarity.minimum_score, 0.70);
assert_eq!(settings.similarity.max_tracks_per_artist, 5);
}
#[test]
fn similarity_search_policy_is_normalized_without_changing_the_profile() {
let mut settings = AppSettings::default();
let profile = settings.similarity.profile.clone();
settings.similarity.minimum_score = f32::NAN;
settings.similarity.max_tracks_per_artist = 0;
let settings = settings.normalized();
assert_eq!(settings.similarity.minimum_score, 0.70);
assert_eq!(settings.similarity.max_tracks_per_artist, 1);
assert_eq!(settings.similarity.profile, profile);
} }
} }
+575
View File
@@ -0,0 +1,575 @@
//! 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, LikedRadioSeed, 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 id: String,
pub command: Command,
pub reply: ReplySender,
}
pub type ReplySender = oneshot::Sender<std::result::Result<Reply, String>>;
#[derive(Debug)]
pub enum Reply {
Done,
LikedRadioSeed(LikedRadioSeed),
}
#[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 {
id: request.id.clone(),
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 = match result {
Ok(Reply::Done) => ServerMessage::Result {
id: request.id.clone(),
accepted: true,
error: None,
},
Ok(Reply::LikedRadioSeed(seed)) => ServerMessage::LikedRadioSeed {
id: request.id.clone(),
seed,
},
Err(error) => failure(request.id.clone(), &error),
};
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,
})
}
+577
View File
@@ -0,0 +1,577 @@
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<()>,
);
#[test]
fn older_local_snapshots_do_not_advertise_liked_radio() {
let snapshot =
crate::app::control::published(&crate::app::state::AppState::default(), 1).snapshot;
let mut legacy = serde_json::to_value(snapshot).unwrap();
assert_eq!(
legacy
.as_object_mut()
.unwrap()
.remove("liked_radio_supported"),
Some(true.into())
);
let decoded: Snapshot = serde_json::from_value(legacy).unwrap();
assert!(!decoded.liked_radio_supported);
assert!(decoded.radio.request_id.is_none());
}
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 retrying_a_liked_radio_pick_returns_the_same_preview_without_a_second_draw() {
let (commands, queue) = mpsc::channel(8);
let (events, mut event_rx) = mpsc::unbounded_channel();
let task = tokio::spawn(broker(queue, events));
let seed = LikedRadioSeed {
key: "lib:7".into(),
title: "One".into(),
artist: "Two".into(),
};
for attempt in 0..2 {
let (tx, rx) = oneshot::channel();
commands
.send(Queued {
id: "pick".into(),
command: Command::PickLikedRadioSeed {
exclude: None,
replace_request_id: None,
},
reply: tx,
})
.await
.unwrap();
if attempt == 0 {
let Some(crate::app::event::AppEvent::Control(request)) = event_rx.recv().await else {
panic!()
};
assert_eq!(request.id, "pick");
request
.reply
.send(Ok(Reply::LikedRadioSeed(seed.clone())))
.unwrap();
}
assert!(
matches!(rx.await.unwrap(), ServerMessage::LikedRadioSeed { id, seed: picked } if id == "pick" && picked == seed)
);
}
assert!(event_rx.try_recv().is_err());
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(Reply::Done)).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, .. })
));
}
+1381 -570
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
{"type":"hello","group_id":"grp_1","profile":{"device_id":"tui_a","name":"TUI","client_version":"0.3.4","protocol_version":3,"endpoint_id":"e","endpoint_ticket":"t","revoked":false,"revoke_cutoff_seq":null,"updated_at_ms":5},"devices":[{"device_id":"tui_a","name":"TUI","client_version":"0.3.4","protocol_version":3,"endpoint_id":"e","endpoint_ticket":"t","revoked":false,"revoke_cutoff_seq":null,"updated_at_ms":5},{"device_id":"web_b","name":"TUI","client_version":"0.3.4","protocol_version":3,"endpoint_id":"e","endpoint_ticket":"t","revoked":false,"revoke_cutoff_seq":null,"updated_at_ms":5}],"vector":{"tui_a":12,"web_b":4},"ops":[{"op_id":"tui_a:1","origin_device_id":"tui_a","seq":1,"hlc_ms":1700000000001,"payload":{"kind":"track_like_set","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","liked":true,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}}},{"op_id":"tui_a:2","origin_device_id":"tui_a","seq":2,"hlc_ms":1700000000002,"payload":{"kind":"playlist_created","playlist_id":"pl","title":"Mix"}},{"op_id":"tui_a:3","origin_device_id":"tui_a","seq":3,"hlc_ms":1700000000003,"payload":{"kind":"playlist_renamed","playlist_id":"pl","title":"Mix 2"}},{"op_id":"tui_a:4","origin_device_id":"tui_a","seq":4,"hlc_ms":1700000000004,"payload":{"kind":"playlist_track_added","playlist_id":"pl","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","position":0,"fed":null}},{"op_id":"tui_a:5","origin_device_id":"tui_a","seq":5,"hlc_ms":1700000000005,"payload":{"kind":"playlist_track_removed","playlist_id":"pl","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111"}},{"op_id":"tui_a:6","origin_device_id":"tui_a","seq":6,"hlc_ms":1700000000006,"payload":{"kind":"playlist_deleted","playlist_id":"pl"}},{"op_id":"tui_a:7","origin_device_id":"tui_a","seq":7,"hlc_ms":1700000000007,"payload":{"kind":"device_profile_set","name":"TUI","client_version":"0.3.4","endpoint_ticket":"t","endpoint_id":"e"}},{"op_id":"tui_a:8","origin_device_id":"tui_a","seq":8,"hlc_ms":1700000000008,"payload":{"kind":"device_trusted","target_device_id":"web_b"}},{"op_id":"tui_a:9","origin_device_id":"tui_a","seq":9,"hlc_ms":1700000000009,"payload":{"kind":"device_revoked","target_device_id":"old","target_max_seq_seen":3}},{"op_id":"tui_a:10","origin_device_id":"tui_a","seq":10,"hlc_ms":1700000000010,"payload":{"kind":"playback_command","target_device_id":"web_b","command":{"kind":"set_state","state":{"queue":[{"id":7,"title":"Song","track_number":1,"disc_number":null,"duration_seconds":180.5,"artist_names":["A"],"featured_artist_names":["B"],"release_id":3,"release_title":"Album","release_year":2001,"file_path":"","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","audio_format":"flac","audio_bitrate":900,"audio_sample_rate":44100,"audio_bit_depth":16,"file_size_bytes":12345,"play_count":2,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}},{"id":0,"title":"Remote","track_number":null,"disc_number":null,"duration_seconds":0.0,"artist_names":[],"featured_artist_names":[],"release_id":0,"release_title":"","release_year":null,"file_path":"","content_id":null,"audio_format":null,"audio_bitrate":null,"audio_sample_rate":null,"audio_bit_depth":null,"file_size_bytes":null,"play_count":0,"fed":null}],"queue_pos":1,"playing":true,"paused":false,"idle_since_ms":null,"position_secs":42.5,"volume":73,"shuffle":true,"repeat":"all"},"seek":true},"authority":{"version":1,"claim":{"counter":3,"issuer":"tui_a","owner":"tui_a"},"sequence":9}}},{"op_id":"tui_a:11","origin_device_id":"tui_a","seq":11,"hlc_ms":1700000000011,"payload":{"kind":"playback_command","target_device_id":"web_b","command":{"kind":"active_changed","active_device_id":"web_b","active_device_name":"WEB","state":{"queue":[{"id":7,"title":"Song","track_number":1,"disc_number":null,"duration_seconds":180.5,"artist_names":["A"],"featured_artist_names":["B"],"release_id":3,"release_title":"Album","release_year":2001,"file_path":"","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","audio_format":"flac","audio_bitrate":900,"audio_sample_rate":44100,"audio_bit_depth":16,"file_size_bytes":12345,"play_count":2,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}},{"id":0,"title":"Remote","trackLine truncated
+137
View File
@@ -0,0 +1,137 @@
//! Cross-binary wire test. Run with scripts/test_device_interop.py; the other
//! endpoint is compiled from furumusic's real protocol types and player hub.
use super::*;
use tokio::io::AsyncWriteExt;
#[tokio::test]
#[ignore = "run scripts/test_device_interop.py to start both player test binaries"]
async fn localhost_web_peer() {
tokio::time::timeout(Duration::from_secs(30), async {
let dir = PathBuf::from(std::env::var("FURUMI_INTEROP_DIR").expect("interop runner"));
let address = loop {
if let Ok(address) = std::fs::read_to_string(dir.join("web-address")) {
break address;
}
tokio::time::sleep(Duration::from_millis(20)).await;
};
let mut stream = tokio::net::TcpStream::connect(address.trim())
.await
.unwrap();
let conn = Connection::open_in_memory().unwrap();
init_schema(&conn).unwrap();
let sync = DeviceSync {
_identity_lock: None,
conn: Arc::new(std::sync::Mutex::new(conn)),
library: Arc::new(Library::open(&dir.join("interop-library.sqlite3")).unwrap()),
event_tx: Default::default(),
playback: Default::default(),
podcasts: Default::default(),
};
let id = sync.ensure_identity().unwrap();
let (tx, mut events) = tokio::sync::mpsc::unbounded_channel();
sync.set_event_tx(tx);
sync.claim_playback(&id.device_id).unwrap();
sync.playback_tick(true, true).unwrap();
let mut state: PlaybackStateWire = serde_json::from_value(serde_json::json!({
"queue": [{ "id": 7, "title": "Interop track", "duration_seconds": 123.5,
"release_id": 1, "release_title": "Interop album", "artist_names": ["Interop artist"],
"content_id": "b3:0000000000000000000000000000000000000000000000000000000000000000" }],
"queue_pos": 0, "playing": true, "paused": false,
"position_secs": 42.5, "volume": 73, "shuffle": true, "repeat": "all"
}))
.unwrap();
for phase in 0..3 {
sync.publish_playback(PlaybackSnapshot {
device_id: id.device_id.clone(),
device_name: "TUI interop".into(),
active: true,
updated_at_ms: now_ms(),
state: state.clone(),
coordination: None,
});
let hello = WireMessage::Hello {
group_id: id.group_id.clone(),
profile: sync.own_profile("").unwrap(),
devices: vec![],
vector: BTreeMap::new(),
ops: vec![],
snapshot: SyncSnapshot::default(),
playback: sync.local_playback_snapshot_for(PROTOCOL_VERSION),
};
let mut bytes = serde_json::to_vec(&hello).unwrap();
bytes.push(b'\n');
stream.write_all(&bytes).await.unwrap();
let response: WireMessage =
serde_json::from_slice(
&music_dht::device_sync::read_line(&mut stream).await.unwrap(),
)
.unwrap();
let WireMessage::SyncResponse {
accepted: true,
playback: Some(snapshot),
ops,
..
} = response
else {
panic!("expected web response")
};
let web_id = snapshot.device_id.clone();
sync.apply_playback_snapshot(&web_id, snapshot).unwrap();
assert_eq!(ops.len(), 1);
let op = &ops[0];
// Production command adapter including durable fencing/deduplication.
sync.apply_op(op).unwrap();
sync.apply_op(op).unwrap();
let mut commands = Vec::new();
while let Ok(event) = events.try_recv() {
if let AppEvent::PlaybackCommand {
command,
authority,
origin,
} = event
{
assert!(sync.playback_command_is_current(&origin, &authority));
commands.push(command);
}
}
assert_eq!(commands.len(), 1, "one event even after duplicate delivery");
match commands.pop().unwrap() {
PlaybackCommand::ActiveChanged {
active_device_id,
state: next,
..
} => {
assert_eq!(
active_device_id,
if phase == 0 {
web_id.clone()
} else {
id.device_id.clone()
}
);
assert_eq!(next.position_secs, 42.5);
assert_eq!(next.queue, state.queue);
state = next;
}
PlaybackCommand::SetState { state: next, seek } => {
assert_eq!(phase, 2);
assert!(seek);
assert!(next.paused);
assert_eq!(next.position_secs, 87.0);
state = next;
}
}
assert_eq!(
sync.playback_tick(true, false).unwrap(),
Some(if phase == 0 {
web_id
} else {
id.device_id.clone()
})
);
}
stream.write_all(b"ok\n").await.unwrap();
})
.await
.expect("web/TUI exchange timed out");
}
File diff suppressed because it is too large. Load diff
+965 -16
View File
File diff suppressed because it is too large. Load diff
+576
View File
@@ -0,0 +1,576 @@
//! Golden wire-compatibility tests: the shared `music_dht::device_sync`
//! types this client now uses must serialize v3 content byte-for-byte like
//! the private copies of furumi-tui 0.3.x (kept verbatim in `legacy`
//! below), so 0.3.x clients and furumi-web 0.12.x keep interoperating.
use super::*;
/// Private wire types of furumi-tui 0.3.x (`src/devices.rs` before sync
/// v4), copied verbatim apart from visibility, `PartialEq` and doc comments.
#[allow(dead_code)]
pub(super) mod legacy {
use music_dht::device_sync::ListenEvent;
use music_dht::playback::CommandStamp;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InviteWire {
pub v: u16,
#[serde(rename = "t")]
pub ticket: String,
#[serde(rename = "d")]
pub device_id: String,
#[serde(rename = "i")]
pub invite_id: String,
#[serde(rename = "s")]
pub secret: String,
#[serde(rename = "e")]
pub expires_at_ms: i64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeviceProfileWire {
pub device_id: String,
pub name: String,
pub client_version: String,
pub protocol_version: u16,
pub endpoint_id: String,
pub endpoint_ticket: String,
#[serde(default)]
pub revoked: bool,
#[serde(default)]
pub revoke_cutoff_seq: Option<i64>,
#[serde(default)]
pub updated_at_ms: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncedFedTrack {
pub item_id: String,
pub owner: String,
pub title: String,
#[serde(default)]
pub artist_names: Vec<String>,
#[serde(default)]
pub featured_artist_names: Vec<String>,
pub year: Option<i32>,
pub duration_seconds: Option<i64>,
pub content_id: String,
pub release_title: Option<String>,
pub track_number: Option<i32>,
pub disc_number: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlaybackTrack {
pub id: i64,
pub title: String,
pub track_number: Option<i32>,
pub disc_number: Option<i32>,
pub duration_seconds: f64,
#[serde(default)]
pub artist_names: Vec<String>,
#[serde(default)]
pub featured_artist_names: Vec<String>,
pub release_id: i64,
pub release_title: String,
pub release_year: Option<i32>,
#[serde(default)]
pub file_path: String,
pub content_id: Option<String>,
pub audio_format: Option<String>,
pub audio_bitrate: Option<i32>,
pub audio_sample_rate: Option<i32>,
pub audio_bit_depth: Option<i32>,
pub file_size_bytes: Option<i64>,
#[serde(default)]
pub play_count: i64,
#[serde(default)]
pub fed: Option<SyncedFedTrack>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PlaybackRepeat {
#[default]
Off,
One,
All,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlaybackStateWire {
#[serde(default)]
pub queue: Vec<PlaybackTrack>,
#[serde(default)]
pub queue_pos: usize,
pub playing: bool,
pub paused: bool,
#[serde(default)]
pub idle_since_ms: Option<i64>,
pub position_secs: f64,
#[serde(default)]
pub volume: u8,
pub shuffle: bool,
pub repeat: PlaybackRepeat,
}
pub type PlaybackSnapshot = music_dht::playback::Snapshot<PlaybackStateWire>;
pub type PlaybackCommand = music_dht::playback::Command<PlaybackStateWire>;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncOpWire {
pub op_id: String,
pub origin_device_id: String,
pub seq: i64,
pub hlc_ms: i64,
pub payload: SyncOpPayload,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SyncOpPayload {
TrackLikeSet {
content_id: String,
liked: bool,
#[serde(default)]
fed: Option<SyncedFedTrack>,
},
PlaylistCreated {
playlist_id: String,
title: String,
},
PlaylistRenamed {
playlist_id: String,
title: String,
},
PlaylistDeleted {
playlist_id: String,
},
PlaylistTrackAdded {
playlist_id: String,
content_id: String,
position: i64,
#[serde(default)]
fed: Option<SyncedFedTrack>,
},
PlaylistTrackRemoved {
playlist_id: String,
content_id: String,
},
DeviceProfileSet {
name: String,
client_version: String,
endpoint_ticket: String,
endpoint_id: String,
},
DeviceTrusted {
target_device_id: String,
},
DeviceRevoked {
target_device_id: String,
target_max_seq_seen: i64,
},
PlaybackCommand {
target_device_id: String,
command: PlaybackCommand,
#[serde(default)]
authority: Option<CommandStamp>,
},
ListenRecorded {
event: ListenEvent,
},
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SyncSnapshot {
#[serde(default)]
pub likes: Vec<SnapshotLike>,
#[serde(default)]
pub unlikes: Vec<SnapshotLikeTombstone>,
#[serde(default)]
pub playlists: Vec<SnapshotPlaylist>,
#[serde(default)]
pub deleted_playlists: Vec<SnapshotPlaylistTombstone>,
#[serde(default)]
pub removed_playlist_items: Vec<SnapshotPlaylistItemTombstone>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotLike {
pub content_id: String,
pub hlc_ms: i64,
pub op_id: String,
#[serde(default)]
pub fed: Option<SyncedFedTrack>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotLikeTombstone {
pub content_id: String,
pub hlc_ms: i64,
pub op_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotPlaylist {
pub playlist_id: String,
pub title: String,
pub hlc_ms: i64,
pub op_id: String,
#[serde(default)]
pub items: Vec<SnapshotPlaylistItem>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotPlaylistTombstone {
pub playlist_id: String,
pub hlc_ms: i64,
pub op_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotPlaylistItem {
pub content_id: String,
pub position: i64,
pub hlc_ms: i64,
pub op_id: String,
#[serde(default)]
pub fed: Option<SyncedFedTrack>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotPlaylistItemTombstone {
pub playlist_id: String,
pub content_id: String,
pub hlc_ms: i64,
pub op_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum WireMessage {
PairRequest {
invite_id: String,
secret: String,
profile: DeviceProfileWire,
#[serde(default)]
group_id: Option<String>,
#[serde(default)]
group_active_devices: usize,
#[serde(default)]
devices: Vec<DeviceProfileWire>,
vector: BTreeMap<String, i64>,
ops: Vec<SyncOpWire>,
snapshot: SyncSnapshot,
#[serde(default)]
playback: Option<PlaybackSnapshot>,
},
PairResponse {
accepted: bool,
#[serde(default)]
pending: bool,
#[serde(default)]
error: Option<String>,
#[serde(default)]
group_id: Option<String>,
#[serde(default)]
profile: Option<DeviceProfileWire>,
#[serde(default)]
devices: Vec<DeviceProfileWire>,
#[serde(default)]
vector: BTreeMap<String, i64>,
#[serde(default)]
ops: Vec<SyncOpWire>,
#[serde(default)]
snapshot: SyncSnapshot,
#[serde(default)]
playback: Option<PlaybackSnapshot>,
},
Hello {
group_id: String,
profile: DeviceProfileWire,
devices: Vec<DeviceProfileWire>,
vector: BTreeMap<String, i64>,
ops: Vec<SyncOpWire>,
snapshot: SyncSnapshot,
#[serde(default)]
playback: Option<PlaybackSnapshot>,
},
SyncResponse {
accepted: bool,
#[serde(default)]
error: Option<String>,
#[serde(default)]
devices: Vec<DeviceProfileWire>,
#[serde(default)]
vector: BTreeMap<String, i64>,
#[serde(default)]
ops: Vec<SyncOpWire>,
#[serde(default)]
snapshot: SyncSnapshot,
#[serde(default)]
playback: Option<PlaybackSnapshot>,
},
}
}
const CONTENT_ID: &str = "b3:1111111111111111111111111111111111111111111111111111111111111111";
/// A v3 `hello` exercising every v3 operation kind, every snapshot section
/// and a coordinated playback snapshot (input order is irrelevant).
fn v3_hello_input() -> String {
let fed = serde_json::json!({
"item_id": "item", "owner": "owner", "title": "Song", "artist_names": ["A"],
"featured_artist_names": [], "year": 2001, "duration_seconds": 180,
"content_id": CONTENT_ID, "release_title": "Album", "track_number": 1, "disc_number": 1,
});
let track = serde_json::json!({
"id": 7, "title": "Song", "track_number": 1, "disc_number": null,
"duration_seconds": 180.5, "artist_names": ["A"], "featured_artist_names": ["B"],
"release_id": 3, "release_title": "Album", "release_year": 2001, "file_path": "",
"content_id": CONTENT_ID, "audio_format": "flac", "audio_bitrate": 900,
"audio_sample_rate": 44100, "audio_bit_depth": 16, "file_size_bytes": 12345,
"play_count": 2, "fed": fed,
});
let state = serde_json::json!({
"queue": [track, {"id": 0, "title": "Remote", "track_number": null, "disc_number": null,
"duration_seconds": 0.0, "release_id": 0, "release_title": "", "release_year": null,
"content_id": null, "audio_format": null, "audio_bitrate": null,
"audio_sample_rate": null, "audio_bit_depth": null, "file_size_bytes": null}],
"queue_pos": 1, "playing": true, "paused": false, "idle_since_ms": null,
"position_secs": 42.5, "volume": 73, "shuffle": true, "repeat": "all",
});
let claim = serde_json::json!({"counter": 3, "issuer": "tui_a", "owner": "tui_a"});
let stamp = serde_json::json!({"version": 1, "claim": claim, "sequence": 9});
let op = |seq: i64, payload: serde_json::Value| {
serde_json::json!({"op_id": format!("tui_a:{seq}"), "origin_device_id": "tui_a",
"seq": seq, "hlc_ms": 1_700_000_000_000i64 + seq, "payload": payload})
};
let profile = |id: &str| {
serde_json::json!({"device_id": id, "name": "TUI", "client_version": "0.3.4",
"protocol_version": 3, "endpoint_id": "e", "endpoint_ticket": "t",
"revoked": false, "revoke_cutoff_seq": null, "updated_at_ms": 5})
};
serde_json::json!({
"type": "hello",
"group_id": "grp_1",
"profile": profile("tui_a"),
"devices": [profile("tui_a"), profile("web_b")],
"vector": {"tui_a": 12, "web_b": 4},
"ops": [
op(1, serde_json::json!({"kind": "track_like_set", "content_id": CONTENT_ID, "liked": true, "fed": fed})),
op(2, serde_json::json!({"kind": "playlist_created", "playlist_id": "pl", "title": "Mix"})),
op(3, serde_json::json!({"kind": "playlist_renamed", "playlist_id": "pl", "title": "Mix 2"})),
op(4, serde_json::json!({"kind": "playlist_track_added", "playlist_id": "pl", "content_id": CONTENT_ID, "position": 0, "fed": null})),
op(5, serde_json::json!({"kind": "playlist_track_removed", "playlist_id": "pl", "content_id": CONTENT_ID})),
op(6, serde_json::json!({"kind": "playlist_deleted", "playlist_id": "pl"})),
op(7, serde_json::json!({"kind": "device_profile_set", "name": "TUI", "client_version": "0.3.4", "endpoint_ticket": "t", "endpoint_id": "e"})),
op(8, serde_json::json!({"kind": "device_trusted", "target_device_id": "web_b"})),
op(9, serde_json::json!({"kind": "device_revoked", "target_device_id": "old", "target_max_seq_seen": 3})),
op(10, serde_json::json!({"kind": "playback_command", "target_device_id": "web_b",
"command": {"kind": "set_state", "state": state, "seek": true}, "authority": stamp})),
op(11, serde_json::json!({"kind": "playback_command", "target_device_id": "web_b",
"command": {"kind": "active_changed", "active_device_id": "web_b", "active_device_name": "WEB", "state": state}})),
op(12, serde_json::json!({"kind": "listen_recorded", "event": {"listen_id": "l1",
"content_id": CONTENT_ID, "started_at_ms": 1, "listened_ms": 60000, "track_duration_ms": 180000,
"ended_reason": "finished", "track": {"title": "Song", "artist_names": ["A"], "featured_artist_names": [], "release_title": null}}})),
],
"snapshot": {
"likes": [{"content_id": CONTENT_ID, "hlc_ms": 1, "op_id": "tui_a:1", "fed": fed}],
"unlikes": [{"content_id": CONTENT_ID, "hlc_ms": 2, "op_id": "tui_a:2"}],
"playlists": [{"playlist_id": "pl", "title": "Mix", "hlc_ms": 3, "op_id": "tui_a:3",
"items": [{"content_id": CONTENT_ID, "position": 0, "hlc_ms": 4, "op_id": "tui_a:4", "fed": null}]}],
"deleted_playlists": [{"playlist_id": "gone", "hlc_ms": 5, "op_id": "tui_a:5"}],
"removed_playlist_items": [{"playlist_id": "pl", "content_id": CONTENT_ID, "hlc_ms": 6, "op_id": "tui_a:6"}],
},
"playback": {"device_id": "tui_a", "device_name": "TUI", "active": true, "updated_at_ms": 9,
"state": state, "coordination": {"version": 1, "claim": claim, "heartbeat": 4, "available": true, "playing": true}},
})
.to_string()
}
fn v3_other_inputs() -> Vec<String> {
vec![
r#"{"type":"sync_response","accepted":false,"error":"device is not trusted"}"#.into(),
r#"{"type":"pair_response","accepted":false,"pending":true,"error":"pairing pending"}"#
.into(),
serde_json::json!({"type": "pair_request", "invite_id": "i", "secret": "s",
"profile": {"device_id": "tui_a", "name": "TUI", "client_version": "0.3.4",
"protocol_version": 3, "endpoint_id": "e", "endpoint_ticket": "t"},
"vector": {}, "ops": [], "snapshot": {}})
.to_string(),
]
}
/// Parses `input` with the 0.3.x types and the shared types and checks
/// that both serialize to the same bytes, and that each side parses the
/// other's output.
fn assert_identical(input: &str) -> String {
let old: legacy::WireMessage = serde_json::from_str(input).unwrap();
let new: WireMessage = serde_json::from_str(input).unwrap();
let old_json = serde_json::to_string(&old).unwrap();
let new_json = serde_json::to_string(&new).unwrap();
assert_eq!(old_json, new_json);
assert_eq!(
serde_json::from_str::<legacy::WireMessage>(&new_json).unwrap(),
old
);
assert_eq!(serde_json::from_str::<WireMessage>(&old_json).unwrap(), new);
new_json
}
#[test]
fn v3_messages_serialize_like_furumi_tui_0_3() {
let hello = assert_identical(&v3_hello_input());
let golden = concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/devices/fixtures/v3_hello.golden.json"
);
if std::env::var_os("FURUMI_BLESS_GOLDEN").is_some() {
// Only for a deliberate change of the v3 shape.
std::fs::write(golden, format!("{hello}\n")).unwrap();
}
assert_eq!(hello, std::fs::read_to_string(golden).unwrap().trim_end());
for input in v3_other_inputs() {
assert_identical(&input);
}
}
#[test]
fn music_queue_items_keep_their_v3_shape() {
let track = TrackItem {
id: 7,
title: "Song".into(),
track_number: Some(1),
disc_number: None,
duration_seconds: 180.5,
artists: vec![ArtistRef {
id: 1,
name: "A".into(),
}],
featured_artists: Vec::new(),
release_id: 3,
release_title: "Album".into(),
release_year: Some(2001),
file_path: "/Users/me/Music/song.flac".into(),
content_id: Some(CONTENT_ID.into()),
cover_path: None,
audio_format: Some("flac".into()),
audio_bitrate: Some(900),
audio_sample_rate: Some(44_100),
audio_bit_depth: Some(16),
file_size_bytes: Some(12_345),
play_count: 2,
fed: None,
podcast: None,
};
let wire = PlaybackTrack::from_track(&track);
let json = serde_json::to_string(&wire).unwrap();
assert!(
!json.contains("source"),
"music items carry no source: {json}"
);
let old: legacy::PlaybackTrack = serde_json::from_str(&json).unwrap();
assert_eq!(serde_json::to_string(&old).unwrap(), json);
}
#[test]
fn invites_from_older_clients_stay_readable() {
let old = legacy::InviteWire {
v: 1,
ticket: "ticket".into(),
device_id: "tui_a".into(),
invite_id: "inv".into(),
secret: "s3cr3t".into(),
expires_at_ms: 10,
};
let old_json = serde_json::to_string(&old).unwrap();
assert_eq!(
old_json,
r#"{"v":1,"t":"ticket","d":"tui_a","i":"inv","s":"s3cr3t","e":10}"#
);
let shared: InviteWire = serde_json::from_str(&old_json).unwrap();
assert_eq!(
shared.inviter_protocol_version(),
music_dht::device_sync::UNREPORTED_PROTOCOL_VERSION
);
assert_eq!(serde_json::to_string(&shared).unwrap(), old_json);
}
#[test]
fn v3_peers_cannot_parse_podcast_operations() {
// Why podcast operations must be gated: an unknown `kind` breaks the
// whole message for a 0.3.x peer, not one operation.
let mut hello: serde_json::Value = serde_json::from_str(&v3_hello_input()).unwrap();
hello["ops"].as_array_mut().unwrap().push(serde_json::json!({
"op_id": "tui_a:13", "origin_device_id": "tui_a", "seq": 13, "hlc_ms": 13,
"payload": {"kind": "podcast_share_set",
"podcast_id": music_dht::podcast::PodcastId::from_feed_url(
&music_dht::podcast::FeedUrl::parse("https://podcasts.example/feed.xml").unwrap()),
"shared": false, "generation": 1},
}));
assert!(serde_json::from_value::<legacy::WireMessage>(hello.clone()).is_err());
assert!(serde_json::from_value::<WireMessage>(hello).is_ok());
}
#[test]
fn v3_peers_would_drop_the_source_of_podcast_items() {
// Why podcast playback must be gated: older types ignore `source` and
// forward the episode as a broken music item.
let episode = crate::app::podcast_fixtures::episode_track(1)
.podcast
.unwrap();
let wire = PlaybackTrack::podcast_episode(episode);
let json = serde_json::to_string(&wire).unwrap();
assert!(json.contains(r#""source":{"kind":"podcast_episode""#));
let old: legacy::PlaybackTrack = serde_json::from_str(&json).unwrap();
let forwarded: PlaybackTrack =
serde_json::from_str(&serde_json::to_string(&old).unwrap()).unwrap();
assert_eq!(forwarded.source, None);
assert_eq!(forwarded.id, 0);
}
#[test]
fn version_reports_stay_readable_by_older_clients() {
let link = encode_invite(&InviteWire {
v: 1,
ticket: "ticket".into(),
device_id: "tui_a".into(),
invite_id: "inv".into(),
secret: "s3cr3t".into(),
expires_at_ms: 10,
protocol_version: Some(PROTOCOL_VERSION),
})
.unwrap();
let invite = parse_invite(&link).unwrap();
assert_eq!(invite.inviter_protocol_version(), PROTOCOL_VERSION);
let json = serde_json::to_string(&invite).unwrap();
assert!(
json.ends_with(&format!(r#","p":{PROTOCOL_VERSION}}}"#)),
"{json}"
);
// `p` is an unknown field for 0.3.x and is ignored there.
assert_eq!(
serde_json::from_str::<legacy::InviteWire>(&json)
.unwrap()
.invite_id,
"inv"
);
let announcement = SyncOpPayload::DeviceProfileSet {
name: "TUI".into(),
client_version: CLIENT_VERSION.into(),
endpoint_ticket: "t".into(),
endpoint_id: "e".into(),
protocol_version: Some(PROTOCOL_VERSION),
};
let json = serde_json::to_string(&announcement).unwrap();
assert!(json.ends_with(&format!(r#","protocol_version":{PROTOCOL_VERSION}}}"#)));
let old: legacy::SyncOpPayload = serde_json::from_str(&json).unwrap();
assert!(matches!(
old,
legacy::SyncOpPayload::DeviceProfileSet { .. }
));
}
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more