Compare commits

..
94 Commits
Author SHA1 Message Date
trav 5f6f01d91c v0.100.0: songs a playlist already has are skipped quietly — the status bar says so for ten seconds with an Add Anyway button, instead of a prompt every time (Preferences › General › Playlists brings the prompt back) 2026-11-21 02:15:27 -08:00
trav 6797910d76 v0.99.1: Boost Volume no longer re-encodes: it raises an MP3's own gain setting (mp3gain's method, 1.5 dB steps, bit-exact and reversible) toward a typical song's loudness, never clipping; Get Info only, and only for MP3s 2026-11-19 23:14:30 -08:00
trav a7d061b200 v0.99.0: Boost Volume amplifies a quiet song's file up to a typical song's loudness (says how many dB and whether it clips; Edit ▸ Undo puts the original back), replacing the per-song Volume Adjustment, which could never play past full volume 2026-11-19 22:51:16 -08:00
trav f52dd7f567 v0.98.1: a playlist's Imported from link can be typed in Get Info, for playlists imported before it was kept 2026-11-17 23:27:54 -08:00
trav 2964158281 v0.98.0: playlist Get Info (right-click): created, songs changed, last played on any machine, the link it was imported from, and a cover any playlist can have 2026-11-17 22:47:25 -08:00
trav f21c31940f v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
2026-11-17 22:41:48 -08:00
trav b78b6c5275 v0.96.1: songs are named in Unicode NFC in the music folder, since Syncthing renames anything else under the library (a Bengali YouTube title lost its file that way); a song already renamed so is followed 2026-11-17 22:21:29 -08:00
trav 9f2f9222dd v0.96.0: now-playing words grow to fill the panel side by side; Spotify/Apple imports untick songs already in the library and put those copies in their place, so the playlist comes out the same; the shown playlist's cover fills the art panel while nothing plays 2026-11-17 22:04:11 -08:00
trav cea9daa09f v0.95.0: the now-playing panel puts the title beside artist-over-album when it all fits, and keeps the stack (now with an ellipsis) when it doesn't 2026-11-17 19:22:10 -08:00
trav 81b6fa509f v0.94.0: a playlist made from a Spotify or Apple Music link keeps the link's cover image (stored, not shown yet) 2026-11-17 19:15:36 -08:00
trav 2069e1b1d0 v0.93.0: Import from URL takes Apple Music songs, albums and playlists, found on YouTube like Spotify's, with a playlist of the same name offered 2026-11-17 19:09:15 -08:00
trav 8afcd4433b v0.92.0: no black corners on windows shown before they were polished; Copy beside Shazams that couldn't be imported, to
search by hand
2026-11-08 20:54:26 -08:00
trav bf68e99b8d v0.91.3: no focus box round the clicked cell in lists; the row's highlight is enough 2026-11-08 19:40:05 -08:00
trav 8c4315fc48 v0.91.2: the window's emboss rims fade across their width, pixel by pixel, instead of two flat pixels and a fade 2026-11-08 01:28:39 -08:00
trav 38f300bca7 v0.91.1: now-playing panel debossed again; window rim 1 px heavier and kept when maximized; square corners when tiled 2026-11-08 01:09:02 -08:00
trav 435a082dc5 v0.91.0: rounded, softly embossed windows with no line under the title or menu bar; blank main title bar; seek times centred on the timeline 2026-11-08 00:35:24 -08:00
trav 15f1ed5c96 v0.90.1: the visualizer's sync delay is a box with 1 ms arrows instead of a slider 2026-11-06 02:55:16 -08:00
trav 95bbcf9601 v0.90.0: Lint Oontz can look left or right in three-quarter view (Preferences › Visualizer › Looking) 2026-11-06 02:48:52 -08:00
trav 0cf22773e7 v0.89.0: Lint Oontz in three-quarter view (or head on), nodding to the bass, ten dance moves by intensity
The moves come in three tiers picked by how full the music is now against
the last ~12 s, so a build or a drop changes the move; some use the legs.
It waits standing for 10 s before sitting and sleeps at 30 s, and skipping
songs no longer sits it down.
2026-11-06 02:41:45 -08:00
trav 2b59ea02da v0.88.1: Lint Oontz is one ball — it sits when nothing plays and falls asleep later; the wheel's modes for it are colour, gray, black
The visualizer keeps its clock with nothing playing for a style that idles
(fed silence), so the ball can sit, blink and fall asleep while paused.
2026-11-06 02:24:59 -08:00
trav f2c1de559e v0.88.0: Lint Oontz visualizer — three lint balls in headphones, 8 fps stop motion
They bob to the bass, dance when the music is fast and full, and lie down to
sleep after a few seconds of quiet. Gray, highlight and black lines on the
panel's gray; every frame re-wobbled, never tweened.
2026-11-06 02:14:51 -08:00
trav d93a265c33 v0.87.1: one app icon (lint.jpg, wave's corner radius) on desktop and andTunes 0.4.2; quitting no longer segfaults
The swap-a-PNG icon is gone: scripts/make_icons.py renders packaging/lint.jpg
into packaging/lintunes.png and the andTunes launcher. Quitting ends with
os._exit once aboutToQuit has saved everything — Python's teardown of the
QApplication wrapper segfaulted on every quit.
2026-11-06 02:01:06 -08:00
trav 39bbfaa5c0 v0.87.0: Connections › Full Rabbit Sync — the music sync, then Import Shazams into the current playlist; Sync to Rabbit is now Sync Music to Rabbit 2026-11-06 01:30:39 -08:00
trav 61955ef996 v0.86.0: Identify windows find the album art too — one song gets a cover picker beside its tags, a playlist batch a cover per album 2026-11-02 16:07:08 -08:00
trav 4911fc425f v0.85.1: andTunes 0.4.1 — a speaker's volume shows as a bar on the right edge instead of a toast 2026-10-31 02:42:40 -07:00
trav b1c8a704e7 v0.85.0: every slider tall and click-to-jump, Light | Dark as folder tabs, album art shows it's clickable (finger, tooltip, keyboard focus) 2026-10-30 16:41:04 -07:00
trav 4be4d60da2 CLAUDE.md: note toolbar column partners 2026-10-29 18:15:37 -07:00
trav b26b0da54b v0.84.1: automatic buttons ending the second toolbar row line up under the buttons ending the first 2026-10-29 18:15:27 -07:00
trav 2deacdadca v0.84.0: Preferences › Appearance can hide the menu bar until Alt is pressed 2026-10-28 02:04:44 -07:00
trav 5150a1d145 v0.83.0: Preferences › DJ shows the space saved vocal splits use and says what they are; README gets a DJ mode section 2026-10-27 08:59:52 -07:00
trav cd4edcf81f v0.82.0: Instant vocal splitting (Spleeter via sherpa-onnx, opt-in), a per-deck Instant/HQ swap, and stems cached as Opus 2026-10-26 17:25:33 -07:00
trav 1fd7dacf88 v0.81.0: Last Played and Last Skipped show the time, and every date column shows the local date 2026-10-25 23:40:12 -07:00
trav f410fb8ea1 v0.80.0: Speakers and Identify Track toolbar items (Customize Toolbar, not in the default bar) 2026-10-25 20:45:11 -07:00
trav eba27e7b8c v0.79.3: editing the playing song's tags or art no longer glitches playback 2026-10-25 20:09:55 -07:00
trav b8f2325f0b v0.80.0: visualizer settings sliders are twice as tall and jump where clicked; radial dot size reads as a share of the gap between dots 2026-10-25 19:11:12 -07:00
trav 1dbb4b81eb v0.79.2: the version button shows a button face on hover once an update is ready; both cancel ✕s are always buttons 2026-10-25 14:30:30 -07:00
trav e4ad527493 v0.79.1: no pointing-hand cursor anywhere 2026-10-25 14:24:52 -07:00
trav 1ad6956abe v0.79.0: the now-playing panel embosses on hover and a click goes to the current song 2026-10-25 14:02:33 -07:00
trav 4a32baac3a v0.78.0: importing a playlist link can make a new playlist of the same name
Once a YouTube, SoundCloud or Spotify link turns out to be a named list,
Import from URL offers "Make a new playlist of these songs, named …"
(off unless ticked, the name editable). yt-dlp's listing now prints each
entry's playlist_title; Spotify's probe hands over the album's or
playlist's name. The playlist is made when the first song lands, so a
link that downloads nothing leaves no empty playlist, and the songs go
in in the link's order. Undoing "New Playlist" takes it all back in one
step.
2026-10-23 01:47:41 -07:00
trav e368b8eb6e v0.76.0: Convert to MP3 for songs already in the library, and for Cassette arrivals
- right-click › Convert to MP3…: lossless songs become MP3s at a chosen
  bitrate; same tracks (plays, ratings, playlists kept), originals to the
  trash, one undo step brings them back; Cancel changes nothing
- Preferences › Importing › Convert songs from Cassette friends too
- the bitrate list is just the numbers
- conversions stage in ~/.cache, not /tmp
2026-10-23 01:21:52 -07:00
trav 3a3d518092 v0.77.1: a cassetted song shows a little blue down-arrow instead of going grey
Asked for and waiting to download now reads as that: the button stays
pressed in, in its own face, with the tape nudged up-left and a blue
arrow in the corner (paler for a partly asked-for artist or album, faded
on hover to say a click lets it go). The guide's icons and friend-mode
screenshot are repainted with the same code.
2026-10-23 01:13:20 -07:00
trav 5f41460cb6 v0.77.0: the laser visualizer is the Oscilloscope — screen sliders and rig diagram gone, a graticule dot size, and a sync delay per style 2026-10-23 00:21:32 -07:00
trav 5413263587 v0.76.0: opening DJ mode with empty decks hands the playing song to Deck A without a gap, and closing goes back to it 2026-10-22 12:43:34 -07:00
trav fc1cd80d35 v0.75.0: Preferences › General › Compress lossless imports to MP3
FLAC, WAV, AIFF and Apple Lossless files being imported are converted by
ffmpeg to an MP3 at 320/256/192/160/128 kbps (off by default) and the MP3
goes in the library, tags and cover art copied over. The original file is
only ever read. One song shows its progress in the status bar; more get a
window with a bar per song and Cancel / Done. Cancel takes back every song
the import added, finished ones included: the copies it made go to the
trash, and a file imported in place is never trashed.
2026-10-21 22:28:49 -07:00
trav a43f0be9d8 v0.74.1: the version in the status bar follows light/dark mode
It read its color from its own palette, which its stylesheet pins, so
the color it got at launch survived every theme switch — pale on pale
after going from dark to light.
2026-10-21 21:54:07 -07:00
trav 00c3ef7f66 v0.74.0: Sync Settings shares one selection with every friend by default, scrolls on a small screen, and searches playlists
- "Share the same selection with all friends" is on by default (a saved
  choice is kept)
- each page scrolls and the window opens no bigger than the screen; the
  General page with its selector held the window taller than a laptop
- a search box over the Playlists list (every word, case-folded, in the
  name, like the sidebar's); while either search is up, Select All /
  Select None reach only what it shows
2026-10-21 21:33:39 -07:00
trav 5f985929bf v0.73.2: Import Shazams' columns can be resized
The song column was Stretch beside the last column, so there was no edge
to drag and a long "Couldn't import: …" stayed cut off. Every edge now
drags and the last column (status / note) takes what's left.
2026-10-20 22:29:16 -07:00
trav b76a69f504 v0.73.1: opening DJ mode no longer crashes after enough openings
Each opening started a new audio thread, and Qt's PipeWire backend leaks
~24 file descriptors per thread that ends. At the desktop's 1024-fd limit
QAudioSink.start() failed ("Too many open files") and segfaulted in
pw_stream_connect. The thread now lives as long as the output: stop()
only silences the pump, shutdown() (window close / aboutToQuit) ends it.
2026-10-20 21:16:26 -07:00
trav a52542750c v0.73.0: Connections › Import Shazams… — the Rabbit's new Shazams, found on YouTube as the original song, tagged as they land
Reads Shazam's history over root adb (and unroots after), offers only
Shazams not dealt with yet (a synced list), picks the plain studio take
(no live/cover/karaoke/clean/vinyl/sped-up, Apple's length decides), and
shows every song's stage with the Identify panel for each one as soon as
it's imported, in the same window.
2026-10-20 00:00:20 -07:00
trav fb5f134045 v0.72.1: the visualizer gets its own Preferences page, sized to the style shown 2026-10-19 23:09:20 -07:00
trav 2c379c4229 v0.72.0: View › Dark Mode (Ctrl+Shift+D) 2026-10-19 23:07:20 -07:00
trav 481e6eec9d v0.71.0: a tiny ✕ cancels a deck's vocals split 2026-10-19 23:04:38 -07:00
trav aea8f82e74 v0.70.0: customize the toolbar — drag items in and out, resize, fill or exact size; a light/dark button 2026-10-19 22:50:40 -07:00
trav a5d4ab27c6 v0.69.0: dark mode, with its own grays and a tint per mode 2026-10-19 22:41:14 -07:00
trav d1174c6b35 v0.68.0: DJ vocal splits survive tag edits; a size limit for their cache 2026-10-19 22:16:39 -07:00
trav 1d215fd045 v0.67.3: the rating column is never narrower than five stars 2026-10-19 22:10:47 -07:00
trav 2e5ebf0b0b v0.67.2: the air horn is the classic rap horn
trav's recording from instantrapairhorn.com replaces the steady can. A
click plays the whole blast untouched; held, it laps the steady stretch
through a crossfade matched to the recording's own loudness; let go after
a lap, it jumps straight to the recording's own ending.
2026-10-19 00:25:53 -07:00
trav 8e39335988 v0.67.1: the air horn is one continuous tone
The old recording was a two-note phrase that wobbled 9% in pitch, so no
loop of it could hold a tone. A steady CC0 can (guitarguy1985, 359-361 Hz
for 7 s) replaces it: held, it plays on and laps a long crossfade; a click
is at least half a second; letting go bends the pitch down as it fades.
2026-10-17 22:57:26 -07:00
trav 056f794e86 CLAUDE.md: loops start on the nearest beat, not the next 2026-10-17 22:44:51 -07:00
trav 0f535a4ca3 v0.67.0: the air horn done properly; djay-style loops; a gentler grab zoom
Air horn: the recording's first blast wobbles on a ~0.15 s cycle, so the
old 0.30 s loop jumped every lap (the repeating beat). Held, it now loops
exactly one cycle (found by self-similarity), levelled and crossfaded;
a release crossfades into the recording's own ending, so a click is a
short blast that trails off; each press cuts a still-sounding blast in
25 ms, so taps stay separate. Exact at any block size.

Loops start on the nearest beat (djay's Quantize), and resizing a running
loop keeps its start and keeps looping. Grabbing a waveform zooms out
only a little, gently, and drags at the zoom it was grabbed at. The sync
button just says Sync.
2026-10-17 22:44:45 -07:00
trav 279f51fba9 v0.66.0: DJ mode's djay layout, loops, a sync that sets once, a real horn, a smooth slide
- Records in the top corners, each deck's controls beside them facing the
  middle, the zoomed A-over-B waveforms in the centre, and a whole-song
  overview per deck below (click to jump, drag to move) with the
  crossfader between them.
- Loops per deck: Loop plus a 1/32 to 8 beat stepper; a loop starts on
  the next beat and shows on both waveforms.
- Sync sets this deck to the other's tempo once, and stays lit only while
  that still holds.
- The air horn plays like a real one: every press a fresh blast, held it
  carries the note, let go it stops.
- Opening and closing DJ mode slides a picture over the final layout
  instead of re-laying-out the window every frame (the flicker).
- Tests: garbage is collected on the main thread after each test, which
  stops a rare segfault in the full run.
2026-10-17 22:19:59 -07:00
trav e00aafefba v0.65.0: DJ mode round three, and the small things
- The shelf is revealed in place: the decks don't stretch or squeeze as
  the window parts.
- The DJ button is the top row's last box (where bpm was), so it stays
  put; bpm moved under it.
- Tempo, vocals and the crossfader snap to their middle and show it. The
  vocals slider has icons, lined up with its ends and middle.
- Sync sticks: a synced deck follows the other's tempo, glows and says
  Synced until its own tempo fader moves. The ½×/1×/2× switch re-syncs,
  and the BPM line says when it's counted half or double.
- A back-to-the-start button per deck.
- The air horn is a real recording (CC0): tap for the phrase, hold to
  stretch the first blast.
- The zoomed waveforms ease out while a deck is paused or held.
- DJ audio follows a change of output device instead of going silent.
- A new playlist folder is named in place, scrolled into view.
- Visualizer bars: choose how many, 1 to 1024 (one per pixel at most).
- The volume slider is as tall as the scrubber.
2026-10-17 04:00:34 -07:00
trav 6d6a0c2385 v0.64.0: DJ mode round two — vocals models, Prepare for DJ, deck volumes, ½×/2×, scrubbing, air horn
- Preferences › DJ: vocals model (Best / Balanced / Fast) and gentle CPU
  use (a quarter of the cores, lowest priority — measured only ~20%
  slower). Splits are cached per model; a deck uses the best one.
- Prepare for DJ on a playlist or songs: BPM and vocals ahead of time.
- Each deck: a volume fader on the outer edge, labelled beside Tempo; a
  ½×/1×/2× switch for half/double-time counting.
- Drag a waveform to scrub (backwards too).
- Crossfader: a handle twice as tall, a middle line, a snap to centre;
  narrower. "calculated, saved" is gone from the BPM line.
- Keep pitch shows a checkmark. An air horn to hold.
- The visualizer draws the mix; the sidebar art hides in DJ mode.
- The Library button has the transport buttons' 8 px corners.
2026-10-17 03:13:59 -07:00
trav 8298450814 v0.63.1: nothing starts the main player in DJ mode; sync always clickable
Return or a double-click on a song started the regular player behind the
decks, with its controls greyed out and no way to stop it. DJ mode now
suspends the player. Sync to other track was only re-enabled when its own
deck changed, so loading the other deck afterwards left it grey; it's now
enabled whenever its deck has a song and explains what it can't do.
2026-10-17 02:19:02 -07:00
trav 57cc5d5289 v0.63.0: DJ mode — two decks, sync, keep-pitch speed, scratching, vocal stems
View > DJ Mode (or the turntable button under BPM) parts the window under
the transport boxes and opens a dark shelf: a record per deck (drag a song
on to load it; drag the record to scratch), play/pause and Sync to other
track beside it, a ±8% speed fader on each edge, Keep pitch, the two
waveforms stacked around one playhead, a vocals/instrumental slider and
the crossfader. Deck A is blue, Deck B orange; loaded songs are tagged in
the lists.

Its own engine (lintunes/dj): whole-song decode, tempo refined to 0.01
BPM plus the first beat (exact on synthetic kicks), WSOLA time-stretch or
varispeed, a QAudioSink on its own thread. Sync matches tempo and, while
both play, nudges the beats into line. A missing BPM is calculated and
saved. Vocals come from Demucs, run once per song in the background and
cached; Demucs lives in its own venv.
2026-10-17 02:06:45 -07:00
trav 7ad51ab4dc v0.62.0: andTunes 0.4.0 — speakers (AirPlay, Chromecast), a list for a menu, icon pills, full-screen art
Now Playing: tap the art for it full screen, the title or artist line
for its album; shuffle, repeat and a new speakers button are icon pills.
The main menu is a list (Now Playing on top, Settings at the bottom, six
rows to a screen). The speakers button lists this Rabbit plus every
AirPlay speaker and Chromecast on the Wi-Fi: AirPlayRemote is the
desktop's RAOP sender in Java (verified from the R1 against
shairport-sync), CastRemote speaks the Cast protocol directly to the
Default Media Receiver and serves the file over HTTP (not yet tried on a
real Chromecast).
2026-10-17 01:00:54 -07:00
trav 770a239138 v0.61.1: update the art-border test to the uniform grey line
v0.61.0 shipped with this test still pinning the old two-tone edge.
2026-10-17 00:42:58 -07:00
trav 42114f252b v0.61.0: buttons darken clearly while held; the play box is three touching buttons; taller scrubber; crisp art border
Held is now PRESSED_DARKER 125 (between Material 3 and GNOME), sunk, on
every button. Transport boxes no longer carry the face themselves (a
QFrame has no pressed state): each button does, so shuffle, repeat and
bpm sink while held and the play box's tiles act as separate buttons with
no grey hover patch. Scrollbar thumbs darken further while dragged. The
seek bar's groove and knob are twice as tall. The album art meets a 1 px
line in the lists' grey, without the pale blend that doubled it.
2026-10-17 00:39:46 -07:00
trav 293d253258 v0.60.0: cliairplay fallback; rounded playlist frame; empty art is a button on hover; no black in the art window
AirPlay: when LinTunes' own sender can't connect (or airplay_backend is
"cli"), Music Assistant's cliairplay is downloaded once, refused unless
its SHA-256 matches the pinned one, and streamed through.

The playlist list gets the panels' 8 px corners. The empty album-art panel
pops up as a plain button under the cursor and sinks darker while held.
The big art window keeps the art's shape after a resize and paints the
art to cover, so it never shows a background.
2026-10-16 23:45:55 -07:00
trav efbee5c465 v0.59.0: LinTunes' own AirPlay 1 sender for third-party speakers
pyatv's handshakes play nothing on a WiiM; Music Assistant's cliairplay
plays on it through libraop's RAOP client. airplay/raop.py reproduces that
client's behaviour on the wire: one RTSP session with auth-setup, an
AppleLossless ANNOUNCE and RECORD carrying RTP-Info, OPTIONS keepalives,
a 2 s buffer, NTP-locked timestamps, a start that sends the first two
seconds at once, the timing responder and resends. Non-Apple speakers
stream through it; pyatv only finds them. Verified against shairport-sync
(decoded tone, flush on pause/seek, volume, metadata). Round 88's pyatv
compat hooks are gone.
2026-10-16 23:12:38 -07:00
trav ab25a6381b v0.58.1: the track list's headings run over the scrollbar's column
The vertical scrollbar now starts under the headings instead of beside
them, so the last heading gets the scrollbar's width back.
2026-10-16 22:48:03 -07:00
trav d77a9fe7f9 v0.58.0: the library search filters the sidebar's playlists
- Typing in the library search now also narrows the playlist list to names
  containing every word; folders stay when they or something inside match,
  open while filtering, and clearing puts back the folders you had open.
- AirPlay: an unreadable /info reply no longer fails the stream (pyatv died
  on shairport-sync's).
2026-10-16 10:27:51 -07:00
trav bdeacd9793 v0.57.0: repeat button; AirPlay compatibility handshake for third-party speakers
- Transport: a repeat button (off / all / one) between shuffle and the
  visualizer. Repeat-all wraps the walk (a shuffled one is reshuffled per
  lap); repeat-one replays a song that finishes, Next/Previous still move.
  BPM button and the now-playing minimum shrink to make room.
- Clicking the streaming tile to stop casting/AirPlay no longer also opens
  the big visualizer (the release after the stop counted as a click).
- AirPlay: pyatv's AirPlay 2 session is silent on a WiiM, and its AirPlay 1
  pairs then talks plaintext, which the WiiM hangs up on. Non-Apple
  speakers now get cliraop's handshake: auth-setup, no pairing, ALAC
  (uncompressed frames). airplay_protocol "2" keeps pyatv's AirPlay 2.
2026-10-15 18:01:20 -07:00
trav c2a566bf57 v0.56.1: AirPlay diagnostics — log each stream, choose the protocol
tiat.place connects but stays silent; pyatv streams to it with its AirPlay 2
path, which the fake receiver never exercised. Log every stream's start,
first audio and outcome; config.json airplay_protocol (auto/1/2) forces a
version and airplay_debug turns on pyatv's own debug log.
2026-10-15 16:07:20 -07:00
trav c1aee48b8b v0.56.0: Connect to AirPlay — stream to AirPlay speakers via pyatv
Every song is decoded by the ffmpeg CLI and streamed over RAOP, so ALAC
and AIFF play too (only FairPlay is refused). pyatv has no pause or seek
for RAOP, so both restart the stream at the heard position. The picker
lists every AirPlay device on the network, greyed with the reason when
LinTunes can't stream to it (video-only TVs, PIN pairing). Casting and
AirPlay are mutually exclusive; the visualizer tile shows the AirPlay glyph
and a click there stops it. Needs: pip install -e . (adds pyatv).
2026-10-15 16:01:08 -07:00
trav 00aa5e7f2e v0.55.0: Kaleidostrobe smooth again; visualizer tile hover controls
The cones move only on the plugin's own 25 fps frames again: driving them
from fresh audio every refresh made bass-heavy songs twitch (a jump on 84%
of refreshes against 41%). The continuous turn, texture crossfade and the
GPU big window stay.

The tile: a click opens it big (and it stays blank while big); hovering
shows a colour wheel (colour / gray / off) and up/down arrows (previous /
next visualizer). No more double-click or click-to-cycle. The big album
art closes on a click or Esc, like the big visualizer.
2026-10-14 12:51:38 -07:00
trav 7ae55e757a v0.54.0: Kaleidostrobe at 60 fps, its big window on the GPU, two-tone gray mode, sync can go sooner
The plugin still steps at its own 25 fps, frame for frame; between frames
the turn continues, textures crossfade, and the cone follows a preview of
the newest audio, so beats land a refresh sooner. The big window replays
the original's GL calls through OpenGL (QPainter took ~40 ms a frame at
1080p); without GL it falls back. Gray mode is only the gray-mode colour on
the panel background. The sync slider goes to -50 ms (sooner).
2026-10-14 12:26:38 -07:00
trav e38c751e39 v0.53.0: Kaleidostrobe, the 2002 iTunes visualizer, as the fourth style
Reverse-engineered from its PowerPC binary and checked against the original
running under emulation: textures byte for byte and every triangle, over
3,600 frames. 25 fps like the plugin; its colour maps and wave images are
extracted from its own code; tests/kaleidostrobe_golden.npz was recorded
from the original.
2026-10-14 12:02:22 -07:00
trav 6178f5d0f7 v0.52.0: volume normalization — every song plays at one loudness
Measured once per file with ffmpeg's ebur128 (cached on this machine),
applied as a gain on the output volume; the next songs are measured
ahead and an unmeasured one glides to its level. Toggle in Controls and
Preferences → General.
2026-10-13 13:29:37 -07:00
trav 78338d84a7 tests never play the finish tink out loud 2026-10-13 10:22:06 -07:00
trav af92ff9b73 v0.51.2: album art sits in the empty art panel's own frame, below the list, instead of inside the list's frame 2026-10-13 10:20:26 -07:00
trav f48165080b v0.51.1: album art sits under the list frame's closing line, like the empty panel 2026-10-13 10:11:55 -07:00
trav 976d338574 v0.51.0: the web mix player has previous and next buttons 2026-10-10 23:54:57 -07:00
trav 96fac71075 v0.50.0: exports report the finished folder's size 2026-10-10 23:48:03 -07:00
trav 3dcd30eab6 v0.49.1: image pickers see uppercase suffixes like IMG_1897.JPG 2026-10-10 23:42:40 -07:00
trav 660740992a v0.49.0: a web mix can carry several images, one after another under the description 2026-10-10 23:39:06 -07:00
trav 9f390b6102 v0.48.2: the finished upload window hides Stop instead of greying it to blank 2026-10-10 23:29:58 -07:00
trav 4d7c17e41d v0.48.1: a web mix leaves a blank line between the description and the image 2026-10-10 23:29:46 -07:00
trav e9488c5289 v0.48.0: web mixes upload to a web server (rsync over ssh), and the player shuffles
Export Web Mix gets an 'Upload to web server' box: the mix is built in a
cache staging folder and mirrored with rsync --delete into <path>/<slug>/
on the host set in Preferences → Integrations → Web Server (config.json,
this machine only). An ssh check asks before replacing an existing mix;
a status window follows check, export and upload. The web player gains a
shuffle button (and the S key).
2026-10-10 23:23:56 -07:00
trav d4cf3f95c2 v0.47.1: the no-art panel sits on the window, shaded like the visualizer
With no art, the sidebar's art widget moves out of the playlist list's
frame onto the window below it, so the panel is set into the gray like the
visualizer rather than into a white box. A tall debossed panel is now
shaded along its top and bottom exactly as the 62 px visualizer is, flat
in the visualizer's color between, instead of one gradient stretched over
its whole height, which read as gray. The scrollbar thumb is shaded the
same way, like a button.
2026-10-10 23:03:47 -07:00
trav fbb439b7ee v0.47.0: no album art shows a debossed panel, not a flat square
The sidebar's art square, when a track has no art, is now the list's own
background with a rounded panel set into it, debossed like the visualizer
and the now-playing panel. paint_deboss takes its rims in pixels when
asked, so a panel as tall as the sidebar is recessed as much as a short
one rather than fading over 16 px.
2026-10-10 11:26:33 -07:00
trav 617402657f v0.46.0: scrollbars lose their arrows; the thumb is embossed like a button
The app style now paints the scrollbars itself: the trough runs the full
length with no arrow buttons, and the thumb gets the buttons' 4 px corners
and emboss, with rims as tall in pixels as a button's however long the
thumb. Bar thickness moved from QSS to the style's pixel metric, since any
QSS rule on a scrollbar part makes Qt draw the whole bar, arrows included.
2026-10-10 10:44:05 -07:00
trav c312751c86 v0.45.1: the laser's Afterimage is a number box, like Line width
Type the seconds, or step by 0.05 with the arrows or ↑/↓; it reads "Off"
at zero. Line width and Afterimage now share one number-box helper.
2026-10-10 02:24:17 -07:00
trav 43d2d21d9d v0.45.0: copying songs pastes into other apps as a song list
Ctrl+C (and Cut) on selected songs now also puts plain text on the
clipboard — one "Artist - Title" per line, in the order the table shows —
so a whole playlist pastes into a message or a document. Pasting back into
a playlist still reads the songs themselves, as before.
2026-10-10 02:17:00 -07:00
252 changed files with 38239 additions and 1663 deletions
+176
View File
@@ -0,0 +1,176 @@
# Build LinTunes.app for both kinds of Mac, and publish a release on tags.
#
# tag vX.Y.Z pushed -> test, build both .dmg files, smoke-test them,
# and attach them + SHA256SUMS to the GitHub Release
# manual dispatch -> the same; publishes only when run on a vX.Y.Z tag
# pull request, or a push to master touching the Mac packaging
# -> test and build, artifacts only, nothing published
#
# macOS minutes are expensive on a private repository (docs/mac-release.md),
# which is why an ordinary push to master doesn't build.
name: macOS
on:
push:
tags: ["v*"]
branches: [master]
paths:
- "packaging/mac/**"
- ".github/workflows/mac.yml"
pull_request:
paths:
- "packaging/mac/**"
- ".github/workflows/mac.yml"
- "setup.py"
- "requirements.txt"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: mac-${{ github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
env:
PYTHON_VERSION: "3.13"
jobs:
test:
name: Tests (${{ matrix.label }})
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15 # Apple Silicon (arm64)
label: AppleSilicon
- runner: macos-15-intel # Intel (x86_64)
label: Intel
runs-on: ${{ matrix.runner }}
# The suite grew up on Linux, and until the Linux-only tests carry a
# `linux_only` marker that conftest skips on macOS, some will fail
# here. Reported, not blocking: the build below doesn't wait on it.
continue-on-error: true
timeout-minutes: 45
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install
run: |
python -m pip install --upgrade pip
python -m pip install --prefer-binary \
--only-binary=PyQt6,PyQt6-Qt6,PyQt6-sip,numpy,cryptography,zeroconf,pydantic-core,aiohttp,miniaudio,protobuf \
-e . pytest
- name: ffmpeg and fpcalc (the pinned ones the app ships)
run: |
export SSL_CERT_FILE="$(python -m certifi)"
python -I packaging/mac/fetch_tools.py --out "$RUNNER_TEMP/tools"
echo "$RUNNER_TEMP/tools" >> "$GITHUB_PATH"
- name: Test suite (headless)
env:
QT_QPA_PLATFORM: offscreen
XDG_CONFIG_HOME: ${{ runner.temp }}/xdg/config
XDG_DATA_HOME: ${{ runner.temp }}/xdg/share
XDG_CACHE_HOME: ${{ runner.temp }}/xdg/cache
run: python -m pytest -q -m "not linux_only" -p no:cacheprovider
build:
name: Build (${{ matrix.label }})
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15
label: AppleSilicon
- runner: macos-15-intel
label: Intel
runs-on: ${{ matrix.runner }}
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Tag matches __version__
if: startsWith(github.ref, 'refs/tags/v')
run: |
version="$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' lintunes/__init__.py)"
if [ "v$version" != "$GITHUB_REF_NAME" ]; then
echo "::error::tag $GITHUB_REF_NAME but lintunes/__init__.py says $version"
exit 1
fi
- name: Build LinTunes.app and the .dmg
env:
PYTHON: python
# Developer ID signing + notarization: inactive until these
# secrets exist (docs/mac-release.md). Empty = ad-hoc signing.
MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }}
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
MACOS_NOTARY_APPLE_ID: ${{ secrets.MACOS_NOTARY_APPLE_ID }}
MACOS_NOTARY_TEAM_ID: ${{ secrets.MACOS_NOTARY_TEAM_ID }}
MACOS_NOTARY_PASSWORD: ${{ secrets.MACOS_NOTARY_PASSWORD }}
run: packaging/mac/build.sh
- name: Launch smoke test
run: packaging/mac/smoke_test.sh build/mac/dist/LinTunes.app 20
- name: Mount the .dmg and check what's inside
run: |
dmg="$(ls build/mac/LinTunes-*-${{ matrix.label }}.dmg)"
mnt="$(mktemp -d)"
hdiutil attach -nobrowse -readonly -mountpoint "$mnt" "$dmg"
test -d "$mnt/LinTunes.app"
test -L "$mnt/Applications"
codesign --verify --deep --strict "$mnt/LinTunes.app"
hdiutil detach "$mnt"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: LinTunes-${{ matrix.label }}
path: |
build/mac/LinTunes-*.dmg
build/mac/LinTunes-*.dmg.sha256
build/mac/pip-freeze-*.txt
if-no-files-found: error
retention-days: 14
release:
name: Publish the GitHub Release
needs: build
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write # create the release and upload its files
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: LinTunes-*
path: dist
merge-multiple: true
- name: SHA256SUMS
working-directory: dist
run: |
sha256sum LinTunes-*.dmg > SHA256SUMS
cat SHA256SUMS
- name: Create or update the release
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
TAG: ${{ github.ref_name }}
run: |
notes="LinTunes ${TAG#v} for macOS.
- Apple Silicon (M1 and later): LinTunes-${TAG#v}-AppleSilicon.dmg
- Intel: LinTunes-${TAG#v}-Intel.dmg
Not sure which Mac you have? Apple menu > About This Mac: \"Chip: Apple M…\" is Apple Silicon, \"Processor: … Intel …\" is Intel.
The app is not signed by Apple yet: the first time, macOS will refuse to open it. Open System Settings > Privacy & Security, scroll down, and click Open Anyway. Full instructions: docs/mac.md in the repository.
Check a download with: shasum -a 256 -c SHA256SUMS --ignore-missing"
if gh release view "$TAG" >/dev/null 2>&1; then
gh release upload "$TAG" dist/LinTunes-*.dmg dist/SHA256SUMS --clobber
else
gh release create "$TAG" dist/LinTunes-*.dmg dist/SHA256SUMS \
--title "LinTunes ${TAG#v}" --notes "$notes" --verify-tag
fi
+3
View File
@@ -25,3 +25,6 @@ itunes-test-library/
# andTunes build output (andtunes/build.py); the shipped APK lives in
# lintunes/android/ and *is* committed
/andtunes/build/
# Mac build output (packaging/mac/build.sh)
/build/
+657 -23
View File
@@ -115,7 +115,7 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
finish/skip/stop/quit; the artist/album snapshot outlives a delete or
retag. Under 5 s is noise and never written. Only while the synced pref
`wrapped.track_history` is on: `Player.listen_ended` → `MainWindow` (adds
`src` desktop/cast and `ctx`, which it latches at `track_changed` because
`src` desktop/cast/airplay and `ctx`, which it latches at `track_changed` because
`_now_playing_context` moves before the old listen closes) →
`LibraryManager.record_listen`, flushed with the journal. The Rabbit writes
the same lines (`History.java`) only when sync put `"history": true` in its
@@ -139,13 +139,34 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
without recursing. Widgets react to its signals (`playlists_changed`,
`playlist_content_changed(pid)`, `track_updated(id)`, `track_fields_edited`).
- **Per-track volume** (Round 79): `Track.volume_adjustment` is iTunes'
"Volume Adjustment", imported as-is (±255 = ±100%) and edited in Get Info.
`player.volume_with_adjustment` scales the slider's *perceptual* level by
it: −100% is silence, and a boost can't pass full. `Player` applies it
through `_output_volume()` everywhere it pushes volume to a sink, before
each load, and on `refresh_volume()` (MainWindow calls that when the
playing track is edited). `Player.volume()` stays the bare slider value.
- **Boost Volume** (Round 131, `boost.py`; Get Info's button, shown only
for an MP3 it can treat) replaced Round 79's per-track Volume Adjustment,
which scaled the slider and so could never play past full — with the
slider up it did nothing (normalization has the same ceiling for quiet
songs). **Never transcode** (trav's rule, after v0.99.0 re-encoded and
was pulled): it adds the same number of units to every granule's 8-bit
`global_gain` in the MP3 side info, mp3gain's method — 1.5 dB a unit,
decoded audio exactly × 2^(units/4), same length, nothing else changes.
Granules with `part2_3_length` 0 are silence (LAME parks them at 210/255)
and are skipped; CRC-protected frames make a file unsupported; the
Xing/Info frame is left alone (LAME's tag CRCs it). How much: whole units
toward a *typical* song (`LoudnessAnalyzer.typical_lufs`), never past −1
dBTP true peak — **no clipping, no options**, one Boost/Cancel. A boosted
copy is staged, then `replace_track_files(…, in_place=True)` trashes the
original and puts the copy at the same path — one undo step. Boosting the
playing song `Player.reopen_current()`s it where it was (no new listen).
`Track.volume_adjustment` is still imported and stored but nothing reads it.
- **Volume normalization** (Round 83, `loudness.py`, Controls → Normalize
Volume / Preferences → General): each file's EBU R128 integrated loudness
from the `ffmpeg` CLI's `ebur128` (~0.4 s a song), cached by path + size +
mtime in `$XDG_CACHE_HOME/lintunes/loudness.json` (machine-local, never
the synced dir). `Player` turns `TARGET_LUFS − measured` into a dB gain in
`_output_volume` (`volume_with_gain`, linear amplitude through Qt's own
volume curve, capped at full). The playing song is measured urgently and
the next `LOOKAHEAD` ahead; an unmeasured one starts at the cache's median
and **glides** (never jumps) to its own gain. No DSP, no tags: Qt's
pipeline has no insert point, and none is needed.
- **`lintunes/player.py`** — `Player(QObject)` walks a queue through a swappable
**`PlaybackSink`**. Player owns the queue, shuffle walk, per-track start/stop
@@ -158,6 +179,12 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
implementation. `set_sink()` carries the current track, position and
playing-state across a swap and deliberately does *not* re-emit
`track_changed` (that would double-scrobble the same song).
**Repeat** (Round 88, the transport's button, off → all → one) lives in
`Player`: repeat-all wraps `_step_index` both ways (a shuffled walk is
reshuffled for each lap, never starting with the song that ended the last),
repeat-one replays only a song that *finished* (`_after_finish`) — Next and
Previous still move — and `_load_current`'s unplayable-skip loop gives up
after one lap, since a wrapping walk would otherwise never end.
Player is also deliberately **context-agnostic**: playback *context*
("library" / "playlist:<pid>") is tracked in `MainWindow`, not the player.
@@ -175,9 +202,106 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
share of the width. Since the Library button left the
sidebar, `MainWindow` must hand it the first focus, or the playlist tree
takes it and opens its first playlist at startup.
**Both rows are a customizable toolbar** (Round 101, `gui/toolbar.py`,
View › Customize Toolbar… or a right-click on the bar): preferences'
`toolbar` is two rows of `{id, size: auto|fill|exact, width}`, and
`TransportBar.place_rows` lays them out by hand with the pure
`toolbar.lay_out` (fills share the leftover; an *anchored* slot sits at
its anchor unless the items before it need the room). "auto" is what
reproduces the old bar: the now-playing panel fills row 0, and in row 1
the Library button spans the sidebar, the view's header starts at the
view and seek/bpm sit under the now-playing panel/DJ box
(`ANCHORED_UNDER`) — the Round 69 geometry tests run against the
default. Automatic buttons ending row 1 also pair off, right to left,
with those ending row 0 (`column_partners`, Round 117), so speakers sits
exactly under the theme box. Widgets are measured once (`_natural`/`_least`) and then freed
of their fixed sizes, so a box can go in either row. Customize mode lays
a `CustomizeOverlay` over each row (it takes every click; edges are
resize handles → exact width; right-click → Automatic / Fill space /
Exact size) and a `CustomizePanel` under them (items not shown, both
spacers always; Restore Defaults). Moves are `QDrag`s with
`toolbar.MIME`; a toolbar item dropped anywhere that refuses it is
removed. Library and the view's header are row-1-only and can't be removed.
The light/dark button (`theme` item) is not in the default rows, nor
are (Round 112) `speakers` — a menu of Connections' Chromecast and
AirPlay actions, lit while either plays (`set_speakers_active`) — and
`identify` (a cassette with an "i"): Identify Track on the playing
song, or the shown list's selection when nothing is on.
The transport-bar visualizer tile (`gui/visualizer.py`, Round 86): a
click opens it big, and while big the tile stays blank; hovering paints
two controls over it — a colour wheel (left: colour / gray / off) and ▲/▼
(right: previous/next style, wrapping) — hit-tested on release. No
double-click. Both big windows (visualizer, album art) close on a click
or Esc.
**Buttons** (Round 92): every one darkens on hover (`HOVER_DARKER`)
and clearly more while held (`PRESSED_DARKER` 125, sunk) — between
Material 3's 8 %→10 % and GNOME's 15 %→30 %; a checked toggle uses
`CHECKED_DARKER`. A transport box draws nothing itself: its buttons
carry the face (QFrame has no `:pressed`, so a face on the box could
never sink), and the play box's three are separate touching buttons
(`tile` property: square where they meet, one shared line). The seek
slider has the `tall` property, which `ClickToJumpScrollStyle` reads to
draw its groove and knob twice Fusion's height. With art, the sidebar
panel draws the cover to the outline's centre and the 1 px line over it
in the lists' grey (`frame_color`); inset by half a pixel, the clip
left a pale blend that read as a 2 px border on vivid covers.
The now-playing panel (`transport.NowPlayingPanel`, Round 110) is a
Go to Current Song button while a song is on (not in DJ mode): raised
in the hover face under the cursor, sunk and darker while held. Its
face is a `face` property, since a QFrame has no `:pressed`.
Its words are `transport.NowPlayingText` (Round 130): the title on the
left with artist over album beside it when all of it fits the width,
else the old stack (title over "Artist — Album", elided with "…").
Side by side the words grow to fill the panel (title up to its full
height, the two lines up to half each, by one shared share as far as
the width allows); the stack keeps the normal sizes.
Decided from the text's widths on every resize and song; DJ mode's
lines (`set_lines`) always stack.
**The look is `~/Documents/shared-resources/design.html`** (canonical
since Round 118; read it before UI work). **No pointing-hand (finger)
cursor** (Round 110), with one exception (Round 118): a clickable
*picture* — the sidebar art — can't wear a button face without altering
the picture, so it gets the finger, a tooltip and Tab focus (Enter/Space,
a 2 px highlight ring). Everything else that's clickable must *look* it:
the version button is flat until an update is ready, then shows the
button face on hover; the status bar's cancel ✕ and the DJ deck's
cancel-split ✕ are always drawn as buttons. **Every slider is tall and
click-to-jump** (Round 118, app-wide in `ClickToJumpScrollStyle`: the
`tall` property defaults on, `SH_Slider_AbsoluteSetButtons`); a slider
with its own style sheet (the DJ shelf's) draws itself. A choice that
changes the page under it is **folder tabs** (`gui/mac_tabs.py`, shared
with wave) — Preferences › Colors' Light | Dark.
The playlist list's frame is a `sidebar.RoundedFrame` (Round 91): the
panels' 8 px corners, painted *over* the list by a mouse-transparent
overlay (window color outside the curve, then Fusion's own frame line,
`frame_color`), since a mask would be jagged. The empty art panel is a
button (click = download art) that only looks like one under the
cursor: embossed in the Library button's face on hover, sunk and darker
while held. The big art window has **no background**: it is snapped
back to the art's shape after a resize (`art_window.reshaped`, the
dimension the user dragged leads) and paints the art to *cover*, so a
shape it can't take (maximized) crops a sliver instead of showing a bar.
The library search box filters the sidebar too (Round 89):
`LibraryView.search_changed` → `PlaylistTree.set_filter`, same rule as
the songs (every word, case-folded, in the name); a folder shows when its
name matches (with all it holds) or something inside does, opened while
filtering, and clearing restores the folders the user had open — so
`rebuild` reads the pre-filter expansion while a filter is up.
**The menu bar can hide until Alt** (Round 116, `gui/menu_bar.py`,
Preferences › Appearance, pref `menu_bar`: `always` | `alt`): a tap of Alt
shows it until a menu closes, Esc, a click elsewhere or another tap;
Alt+<letter> opens that menu straight away. Qt disables a hidden menu
bar's shortcuts with it, so `register_shortcuts` adds every menu action
to the window too — an action added to a menu later must be as well.
`track_table.py` is the shared track grid (drag/drop, copy/paste, drop
indicator). `playlist_ops.py::add_tracks_with_dup_check` is the single funnel
for every add-to-playlist path. `theme.py` applies the palette (highlight
for every add-to-playlist path; since Round 132 it adds only the songs a
playlist doesn't have and says so in the status bar
(`gui/duplicate_notice.py`, found as `window().duplicate_notice`: 10 s,
then a fade; the cursor holds it) with **Add Anyway**, which makes the
playlist what adding everything would have (or appends the duplicates if
it changed since). Pref `ask_on_duplicates` brings the old modal back.
`theme.py` applies the palette (highlight
colors, UI scales) from prefs.
- **`lintunes/gui/visualizer.py`** + **`visualizer_styles.py`** — the
@@ -198,21 +322,28 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
drew as a flat arc. "Even out bass and treble" removes a *straight*,
loudness-weighted dB-vs-log-f tilt, clipped to ±24 dB, and never lifts a
band that isn't sounding (a curve fitted to a lone tone lit up silent
treble). **Laser** simulates a mirror on a speaker membrane: the
treble). **Oscilloscope** (`laser` in code and prefs — Round 108 renamed
only what the user sees) is an **X-Y scope of the bass**: nine resonators
(≈50–160 Hz) each push the trace along a fixed direction, and the sum is
X and Y. *Where* they sit and *which way* they push comes from modelling a
laser off a mirror on a speaker membrane (Tame Impala's rig): the
circular-membrane modes run as complex one-pole resonators, vectorized in
`CHUNK`s. Loops come from the split degenerate pairs, between whose
resonances x and y answer up to 90° apart, hence the slack 50 Hz membrane
with a wide split. The beam ray is intersected with a screen at
`distance`, turned by pitch/yaw/roll; the auto-gain holds the beam
*angle*, so distance is real, and `scale()` shrinks the drawing only when a
steep screen would push the loudest swing out of view. The path is drawn
with a wide split. Round 78's screen distance/pitch/yaw/roll sliders and
the live rig diagram are gone (Round 108): they only resized, stretched or
spun the same tangle, so trav found they "don't really do anything". The
screen is fixed square at `SCREEN_DISTANCE`; a still `gui/scope_drawing.py`
sits beside the look controls. The graticule's dots have a size
(`visualizer_laser_grid_dot`, × the automatic size). The path is drawn
brighter where it moves slower (dwell). The afterimage is a **phosphor**
(`_Phosphor`, one per painted size, half resolution past 400 px wide):
each sweep is burned in once and the buffer is dimmed per frame, so cost
doesn't grow with the fade time. The dimming is a numpy LUT that rounds
*down*, because Qt's own fade rounds to nearest and stalls faint pixels
forever. The numpy array must be a **view of the QImage's `bits()`**, since
building a QImage *from* an array copies it. A **speaker range** (low/high
building a QImage *from* an array copies it. A **frequency range** (the
"speaker" in code, low/high
Hz, `gui/range_slider.py`) filters what drives the membrane, with
`one_pole` stages done exactly via the cumsum trick, 36 dB/octave. That is
steeper than a real speaker on purpose: the membrane answers bass ~80 dB
@@ -227,26 +358,271 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
buffers arrive in a burst. So the widget keeps 1.5 s of *timestamped*
history (`QAudioBuffer.startTime()`) and each frame draws the stretch
ending at `Player.position_ms()`, carried forward by the clock between
Qt's buffer-sized steps, minus `visualizer_sync_delay_ms`. That delay is
output latency Qt can't see (Bluetooth), this machine's hardware, so it
lives in **`config.json`**; the dialog emits `prefs.changed` after writing
it so the widget re-reads. The laser takes every heard sample exactly once
Qt's buffer-sized steps, minus the sync delay. That delay is output
latency Qt can't see (Bluetooth), this machine's hardware, so it lives in
**`config.json`** — and since Round 108 **one per style**
(`visualizer_sync_delays: {style: ms}`, the slider right under each page's
preset), because each style adds its own lag (radial's FFT window, the
bars' fall, Kaleidostrobe's 25 fps, the scope's ringing). A style not yet
set starts from the old shared `visualizer_sync_delay_ms`. The dialog emits
`prefs.changed` after writing it so the widget re-reads. The laser takes every heard sample exactly once
(`_drawn` index), never the newest-decoded ones.
**Presets** (`gui/visualizer_presets.py`): per style, `STYLE_KEYS` under a
name, in `visualizer_presets` (synced; never the sync delay). `Default` is
built in and reserved. Applying one moves the dialog's *controls* (each
registers a setter in `_viz_setters`), and their own handlers save the
values, so controls and prefs can't disagree. The drop-down reads
"Custom" whenever the settings match no preset. A setting added later
"Custom" whenever the settings match no preset. The page's sliders
(Round 111) are `transport.ClickJumpSlider`s with the `tall` property:
twice Fusion's height, and a click puts the handle's centre where it
lands. Radial's dot size is shown as a share of the gap between dots
(100% = touching; the pref is × the automatic size, `RADIAL_DOT_SHARE`
of the gap) — never pixels, since the gap moves with the drawing's size. A setting added later
must join `STYLE_KEYS` and register a setter, or presets silently skip it
(`test_every_style_key_has_a_control` pins that).
The laser page draws the rig (`gui/laser_diagram.py`, textbook line art
through the renderer's own `_rotation`); it labels distance, angles and
dot size, so those sliders show no number.
**Dark mode** (Round 101, Preferences › Appearance): `theme.mode(prefs)`
picks a whole palette (`_dark_palette`, every role) in dark, or the
base palette plus overrides in light. Each mode has its own gray sliders
(dark's are `dark_<key>`, light keeps the original keys) and a tint
(`tint_color`/`tint_level`, `dark_…`): the gray's lightness with the
tint's hue at level × its saturation, on every surface but text. Paint
surfaces with `theme.surface(prefs, key)`, glyphs with
`theme.icon_gray()` and button text with `theme.text_color()` — a
hardcoded black/#4A4A4A vanishes in dark. The highlight is shared.
The highlight swatches can be repainted with a color picker:
`highlight_palette` overrides a slot, and `theme.highlight_color` reads
through `theme.highlight_palette`, so nothing else needs to know.
- **`lintunes/kaleidostrobe/`** + **`gui/visualizer_kaleido.py`** — the
fourth visualizer style (Round 84): Kaleidostrobe, the 2002 iTunes plugin
by Shehryar Lasi, **reverse-engineered from its PowerPC Mach-O** (symbols
intact) to be identical, not "inspired by". Method: capstone listings, and
the original running under a **Unicorn PPC emulator** through its own
VisualPluginHandler (imports answered in Python, GL calls recorded) as the
oracle. `engine.py` is the Qt-free port, routine by routine, with `f32` /
`math.fma` wherever the PPC rounded to single or fused a multiply-add
(a palette index on `x.5` depends on it), `ParkMiller` = Darwin 6's
`rand()` (RAND_MAX 2³¹−1). `tables.npz` holds what the original computes
deterministically, extracted by running *its* code: 22 colour maps and 23
base wave images (before their random `transform()`, which is ported, as
are the 16 live `calcDelta` warps — each with its **own** static counters
per layer). Quirks kept on purpose: `flipDiag`'s off-by-one. Facts that
shape the port: the plugin renders only after 39,999 µs, so it ran at
**25 fps** and counts frames for rotation and switching — the renderer
steps the engine on its own 25 Hz clock, never the widget's 60 Hz timer;
beat timing is in TickCount (1/60 s). The original's Color/Flash settings
were Apple SDK leftovers its code never read, so the style has none. It
reads only iTunes' **spectrum** bytes (never the waveform); iTunes' byte
scale was never published, so `itunes_spectrum` (√magnitude, 43 Hz bins)
is the one calibrated stand-in. **On screen it is 60 fps anyway**
(Round 85): between the 25 Hz frames `_compose` turns the cones by a
fraction of a frame and crossfades the textures — smoothing only. The
cones' height/depth change **only on the plugin's frames**: Round 85 also
drove them from the newest audio every refresh (snappier beats), and on
bass-heavy songs it twitched — a jump on 84% of refreshes against 41% —
so Round 86 took it out. The 25 fps cap was hiding that jitter; don't
reintroduce fresh-audio geometry between frames. Painting: the panel uses QPainter — each GL triangle is
planar, drawn in texture space through a projective **world** transform
(Qt mis-draws a strongly projective *brush* transform). The **big window
replays the original's GL calls** (`paint_gl` in a `gui/kaleido_gl.py`
QOpenGLWidget, GL 2.1 fixed-function via QOpenGLVersionFunctionsFactory):
QPainter cost ~40 ms a frame at 1920×1080, which is what stuttered. No GL
→ `unavailable` → the window paints with QPainter again. Gray mode is
strictly two-tone (gray-mode colour on the panel background, by HSV
value — luma calls the saturated palettes dark). The sync slider now goes
below 0 ("sooner"), borrowing audio decoded but not yet heard — only
~0–30 ms of it exists, hence the −50 ms floor. The top cone is always
nearer, so painter's order is the depth test.
`tests/kaleidostrobe_golden.npz` was recorded from the emulated original
and `test_round84` holds the port to it byte for byte.
- **`gui/visualizer_lint.py`** — Lint Oontz, the fifth style (Rounds
122–123, `lint`): one line-drawn lint ball in big headphones on the
panel's gray, in **three-quarter view** (default: face turned to our
right, the near cup seen whole, the far one clipped to what shows past
the ball) or **head on** (`visualizer_lint_head_on`, Preferences' View
combo; in `STYLE_KEYS`). `visualizer_lint_face_left` (Round 124, the
Looking combo, 3/4 only) mirrors the whole drawing about its centre; the
z's are only moved, so they still read as z's. The ball is filled with the panel colour so
what's behind it (legs' tops, the far arm in 3/4) is hidden.
**Stop motion**: the renderer steps at 8 fps on its own clock and
`advance` is True only on a step; every step re-rolls each line's wobble
(seeded by step) and nothing is ever tweened. A bass onset **nods** the
head (rotated about the neck in 3/4; head on, the face drops) — the legs
no longer crouch on the bass. Busy (onset tempo ≥ `BUSY_BPM` *and* a full
spectrum) → one of `MOVES`: ten arm+leg moves in three tiers; the tier is
`now` fullness (1.5 s) against `TIER_EDGES`, ±1 when `now` is `LIFT` over
or under `lately` (12 s) — a build or a drop. A tier change that holds 2
beats switches the move; every 16 beats it may switch within the tier.
Not busy: arms hang, it only nods. Quiet/nothing playing: stands, sits
at `SIT_AFTER_S` (10), sleeps at `SLEEP_AFTER_S` (30); `clear()` does
nothing, so skipping songs never sits it down. Two renderer flags the
widget reads: `idles` keeps the 60 Hz timer running with nothing playing
(fed silence, never the old song's tail), and `black_mode` adds
`MODE_BLACK` to the colour wheel (colour → gray → black → off) — for any
other style a saved black reads as colour.
- **`lintunes/dj/`** + **`gui/dj_shelf.py`** — DJ mode (Round 93; View ›
DJ Mode or the turntable button under BPM). The window parts **under the
row of transport boxes** (`TransportBar.insert_shelf`: the Library button's
header row slides down with the lists) and a dark shelf shows in the gap,
animated open and closed (`MainWindow.set_dj_mode`). Default height leaves
~15 songs below (at least the full 320 px layout), the grip resizes it
between ~28 and ~5 songs below (`height_bounds`), saved as config.json's
`dj_shelf_height`; under 200 px it's one compact strip. **Manual, like DJ
software**: a deck loads only by dragging a song onto its record (the
record darkens and gets the deck's rim; replacing a deck that's playing
above 50 % gain asks first), and a song that ends just stops — no queue,
so the main transport, seek bar, space and arrows are greyed/ignored, and
the main player is **suspended** while DJ mode is open
(`Player.set_suspended`: paused, and nothing — double-click, Return, a
media key — can start it; it played behind the decks, unstoppable, in
v0.63.0). **Except** (Round 107) when both decks are empty and a song
is on: then it keeps sounding (`set_suspended(True, pause=False)`) while
Deck A loads it (`DjShelf.load(…, handoff=)`), the deck starts a sink
latency ahead (`DjShelf.cue`), the main player pauses as that arrives
and its spot is `MainWindow._dj_pin`; closing seeks back there and plays
(`_back_to_pin`). The crossfader goes to all-A. Casting/AirPlay keep the
old pause. "Sync to other track" is enabled whenever its own deck has a
song; what it can't do yet it says in the status bar. Deck A is blue and Deck B
orange, every control included; loaded songs get a DECK A/B tag in every
track list (`track_table.deck_tag`). **Its own engine**, because Qt's
player can't change tempo without pitch or play backwards: `dj/loader.py`
decodes the whole song (ffmpeg CLI, int16 stereo 44.1 kHz, ~50 MB per 5
min) and analyses it — `bpm_detect`'s tempo, refined to 0.01 BPM by which
tempo folds the onsets sharpest (`analysis.beat_grid`; 0.1 BPM off smears
two minutes of beats by a fifth of a beat), and the first beat from a
~3 ms energy-rise onset (`onset_times`; bpm_detect's 1024-sample flux
smears *when* by tens of ms). Both measured exact on synthetic kicks. A
file with no BPM gets it saved (`set_tracks_bpm`). `dj/audio.py` is pure
numpy: keep pitch = WSOLA (1024/512, ±256 search), Keep pitch off =
varispeed, scratching = varispeed at the hand's angular rate (one turn =
1.8 s, a 33⅓ record; letting go is normal speed at once). The mixer is
constant-power crossfade × master (the volume slider through Qt's curve).
`dj/output.py` feeds a QAudioSink from **its own QThread** (100 ms
buffered), so GUI painting can't starve it; it must end before Qt quits
(`shutdown()`: `aboutToQuit`, `closeEvent`). Closing DJ mode is only
`stop()` — **the thread is started once and kept** (Round 104): Qt's
PipeWire backend leaks ~24 fds per thread that ends, so a thread per
opening hit the 1024-fd limit and segfaulted in `pw_stream_connect`.
**Tests stub it** (conftest
`_no_dj_sound`) — the decks would otherwise play out loud. Sync ("Sync to
other track", per deck): tempo to the other deck's (the nearest octave);
if both are playing, then the shortest beat nudge (`phase_shift`, never
more than half a beat). The waveforms are drawn in *heard* time around one
shared playhead, so synced beats sit exactly above each other. **Vocals**:
Demucs (htdemucs, two stems) splits each loaded song once in the
background into `$XDG_CACHE_HOME/lintunes/stems/<key>/` (path+size+mtime);
the slider blends vocals/instrumental live. Demucs + CPU PyTorch (~1 GB)
live in their own venv, `$XDG_DATA_HOME/lintunes/demucs`
(`stems.setup_command()`; it needs numpy installed explicitly), never a
pip dependency of LinTunes — without it the slider is disabled with that
command in its tooltip.
**Round 94**: Demucs is the CPU hog (htdemucs: 29 s per 40 s of audio on
8 cores, 35 s on 2 — so cores barely matter), so it always runs niced
and Preferences › DJ (its own page) picks the model (`stems.MODELS`:
Best = htdemucs_ft, Balanced = htdemucs, Fast = htdemucs at overlap 0.1,
~25 % quicker; hdemucs_mmi 42 s and mdx 156 s were slower, no "fast"
model exists) and "gentle" (default: a quarter of the cores, nice 19).
Splits are cached per model (`<key>/<model>/`; Round 93's sit in
`<key>/` and count as htdemucs) and a deck takes the best one cached.
**Round 100**: `<key>` is a hash of the *audio packets* (`ffmpeg -c copy
-f hash`), not path + size + mtime — loading a song with no BPM writes
its BPM tag, which orphaned every such split at once. `index.json`
memoizes path + size + mtime → key; old path-keyed folders are renamed
on sight. The cache is held to config.json's `dj_stem_cache_gb`
(Preferences › DJ, default 1): after each split the least recently used
songs go (`stems.prune`). **Round 102**: a tiny ✕ after a deck's
vocals note while it waits for or runs Demucs ("cancel vocals split")
calls `StemSplitter.cancel` — out of the queue, or Demucs killed by
`split`'s watcher thread at once (it can go seconds without a progress
line). The slider then stays enabled, and grabbing it (or loading the
song again) splits it over.
**Round 114 — Instant vocals** (`dj/instant.py`, opt-in): Spleeter's
2-stem weights as ONNX through **sherpa-onnx** — the real `spleeter`
package needs TensorFlow and Python ≤3.11 — in its own venv
(`$XDG_DATA_HOME/lintunes/spleeter`, ~160 MB, made by Preferences › DJ's
download button, `InstantSetup`; models pinned by SHA-256 — the
release's checksum.txt is stale for them). `_spleeter_run.py` runs in
that venv (`-I`, no LinTunes imports) in 30 s pieces crossfaded over 1 s
(sample-aligned across seams, measured): ~11–17 s for a 4-min song while
Demucs was running beside it. It is the lowest tier (`stems.TIERS`,
`"spleeter"`), so a cached Demucs split still wins. The decks keep **one
`StemSplitter` per engine** (`HQ`/`FAST`; Instant never queues behind
Demucs); `DeckView.engine` is what the deck wants, `using` the tier
playing. `dj_stem_default` (synced) picks the engine a deck starts with,
`stems.default_engine` falls back to whichever is installed *here*. Each
deck's **Instant ⇄ HQ** button (only when both are set up) swaps: to HQ
keeps the instant stems playing until Demucs lands; to Instant kills a
running Demucs. Every split is cached as **Opus 160k** (`to_opus`, ~1/7
of FLAC; decodes back sample-aligned); old FLAC splits still read.
conftest `_no_instant_split` pins `instant.available` off in tests.
**Prepare for DJ** (a playlist's or songs' right-click; `dj/prepare.py`)
does the BPM + split ahead of time with the status-bar progress/cancel.
Each deck also has a volume fader (outer edge, perceptual), a ½×/1×/2×
switch (half/double-time: the BPM shown, the beat ticks and what Sync
matches — `analysis.sync_speed` takes the straight ratio unless it's
implausible, then the nearest octave), and its waveform lane scrubs when
dragged (a scratch at the drag's rate). The crossfader is
`dj_shelf.Crossfader` (big handle, a middle line, snaps within 3 %). An
air-horn button (held = longer; `audio.Horn`, synthesised). The
transport's visualizer draws the mix in DJ mode (`Mixer.tap` →
`VisualizerWidget.set_dj_source/feed_dj`). The sidebar art hides.
**Round 95**: the shelf is laid out at its full height on a body
(`set_layout_height`) and only *revealed* by the opening — the decks
never squeeze. The DJ button is the top row's last box (it swapped with
bpm, which is under it in the header row), so it doesn't move when the
window parts. `dj_shelf.SnapSlider` is every DJ slider with a middle
(tempo, vocals — `VocalSlider`, icons over its ends and middle —
crossfader): a centre line and a snap. Sync is **sticky**: a synced deck
follows the other's tempo every tick (`_follow`), glows and says
"Synced", until its own tempo fader moves; only one deck follows; the
½×/1×/2× switch re-syncs a synced pair (`sync_ratio` folds any number of
octaves). |◀ per deck. The air horn is a real recording
(`sounds/airhorn.mp3`, see `sounds/CREDITS.md`; Round 99 below). The zoomed lanes ease out ×2
while a deck is paused or held. The sink reopens when the system's
default output changes (`output._Pump`: `audioOutputsChanged`, a device
id check, an error check) — it used to go silent until DJ mode reopened.
**Round 96**: the layout is djay's — records in the top corners, each
deck's controls beside its record facing the middle (title, tempo, |◀ ⏯
Sync, ½×/1×/2×, Keep pitch, Loop, vocals), the horn and the zoomed A-over-
B lanes in the centre, and below them each deck's **whole-song overview**
(`OverviewWave`: played part shaded, playhead, loop band; click jumps,
drag moves) with the crossfader between. **Loops**: Loop + a ‹ size ›
stepper (1/32 … 8 beats); the engine
renders up to the loop end in pieces and wraps (`Deck.loop`), shown on
both waveforms. **Sync sets once** (trav's call): it puts this deck at the
other's tempo and stays lit only while that holds (`_check_sync`: same
song on the other deck, tempos still equal) — nothing follows anything.
**The horn** (Round 99, the fifth go — trav chose the sound: the
classic rap horn from instantrapairhorn.com, `sounds/airhorn.mp3`). It is
one blast: a swoop ~420 → 305 Hz in its first 0.35 s, then 302 Hz steady
to 1.62 s, then its own short end. A click plays the whole recording
untouched, as that page does. Held, it laps `Horn.LOOP` (0.729–1.450 s)
through a 0.2 s crossfade baked into a copy (`_laps`); the steady part is
beating reeds, not a repeating wave (seams correlate ~0.3 at best), so
the crossfade is equal loudness *for the measured correlation*. Let go
before a lap, it plays out; after one, it jumps (40 ms, matched to the
nearest wave cycle) to the loop end, so the ending follows at once. A
press cuts a blast still sounding in 25 ms. test_round99 holds it to the
recording's own loudness range. **Before changing the recording, measure
its pitch and loudness track** — Rounds 93–98 failed on the recording,
not the code.
**Loops** (Round 97, djay's Quantize behaviour): a loop starts on the
*nearest* beat (it may be just behind — playback carries on inside it);
under a beat, it snaps to its own grid; resizing keeps the start and
folds a playhead left outside back in, so it never breaks out. The
zoomed lanes ease out only ×1.35 when grabbed, and a drag converts
pixels at the zoom it was grabbed at. **Opening/closing slides a picture** (`SlideOverlay`):
the window jumps to its final layout once and a grab of what was below
the transport boxes moves over it — animating the real shelf height
re-laid-out the window every frame, which flickered.
The suite collects garbage on the main thread after every test (conftest
`_collect_on_the_main_thread`): Python's GC runs on whatever thread
triggers it, and a Qt object a test left behind, collected on a worker,
segfaulted a later test (always test_round72's maximized window, only in
the full run).
- **`lintunes/importers/itunes_importer.py`** — parses the iTunes XML plist.
Remaps Mac `file:///Volumes/...` paths to the local `--music-root` with
case/Unicode-normalization fuzzy matching (macOS is case-insensitive + NFD vs
@@ -323,6 +699,39 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
and hand over nothing. Every paste attempt is logged at INFO
(`lintunes.gui.info_dialog`), so it shows up in the journal.
- **`lintunes/importers/lossless.py`** + **`gui/compress_import.py`** —
Preferences › General › Importing, "Compress lossless imports to MP3"
(Round 106, a friend's request; **off by default**, pref
`import_compress` + `import_compress_kbps` ∈ 320/256/192/160/128). With it
on and a lossless file (FLAC/WAV/AIFF by suffix, `.m4a` only when its
codec is ALAC) in an import, `MainWindow.import_files` hands the **whole**
batch to `CompressImport` and returns `[]`: `CompressWorker` walks it in
order on a daemon thread (lossy files pass straight through, so a
playlist drop keeps its order), the `ffmpeg` CLI converts into a private
temp dir, tags and art are copied with mutagen (`copy_tags`, not
ffmpeg's mapping), and `file_importer.import_converted` *moves* the MP3
into the tree under the source's stem. **The source is only ever read.**
One file → the status-bar progress; more → `CompressProgress` (a bar per
song, Cancel/Done; closing while working only hides it). **Cancel takes
back every song the batch added, finished ones too**
(`LibraryManager.discard_imports`: the copies it made go to the trash, a
file imported in place from the music folder is never trashed). So the
batch's playlist inserts use `add_tracks_to_playlist(undoable=False)` —
an undo step left behind would put back ids Cancel removed. A lossless
file already in the library isn't converted again.
**Round 107**: "Convert songs from Cassette friends too"
(`import_compress_cassette`, needs the main box; `lossless.cassette_kbps`
read by `DeliveryCoordinator` each pass) converts a lossless *library*
arrival inside `delivery.run_plans` before staging (followed-playlist
cache files are left as sent). Right-click › **Convert to MP3…**
(`ConvertLibrary`) does songs already in the library: everything is
converted first, *then* each MP3 is moved beside its original and
`LibraryManager.replace_track_files` swaps them as ONE undo step (same
track id, so plays/ratings/playlists stay; library tags written into the
MP3; originals to the trash, undo brings them back) — so its Cancel
changes nothing. Conversions stage in `$XDG_CACHE_HOME/lintunes/
converting/` (`lossless.staging_root`), never /tmp, which is often RAM.
- **`lintunes/fingerprint.py`** — "Identify Track…": Chromaprint's `fpcalc`
CLI (detected with `shutil.which`, the `ffmpeg_available()` pattern — a
runtime tool, never a pip dep) fingerprints the file, and AcoustID's web API
@@ -440,6 +849,13 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
get `gui/url_import_progress.py`, a non-modal per-song list (Hide keeps
downloading; clicking the status-bar line reopens it). `LTSTART` carries
the id, and `ERROR: [site] <id>: …` lines become `item_failed`.
**A named list can become a playlist** (Round 109): the probe also
prints `LTLIST %(playlist_title|)s` (Spotify's probe emits the album's
or playlist's name), and the dialog then offers "Make a new playlist of
these songs, named [it]", off unless ticked. `MainWindow` makes the
playlist when the *first* song lands (nothing downloaded → no empty
playlist) and adds each song with `undoable=False`, so undoing "New
Playlist" is the one step that takes it all back.
**A Spotify link** (Round 76, `spotify_link.py`, ported from trav's
`spotify-youtube` script) can't be downloaded, but Spotify's public
embed page (`open.spotify.com/embed/<kind>/<id>`, a `__NEXT_DATA__`
@@ -453,6 +869,39 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
track number into the mp3 **before** emitting `downloaded`, so the
import files it under the right artist and Identify ranks by that artist.
If the embed page changes shape, `parse_embed` raises `SpotifyError`.
**An Apple Music link** (Round 130, `apple_music_link.py`) is the same
path with another reader: `AppleMusicProbe` returns `SpotifyTrack`s
(kind `"apple"`, same `"spotify"` entry key, same worker). Albums and
songs (`/song/<id>`, `/album/…?i=<id>`) come from the keyless iTunes
Lookup API (track/disc numbers, `limit=200`); a playlist has no keyless
API, so its `music.apple.com` page's `serialized-server-data` JSON is read
— measured to hold every song (143 of 143), with album and length each.
Private `/library/` playlists can't be read and aren't matched.
**The cover is kept** (`playlist_art.py`): a playlist made from a
Spotify/Apple link gets the link's cover in `<data_dir>/playlist_art/
<pid>.jpg|png` (synced, never in the playlist JSON, so no merge or
"edited" stamp; downloaded on a daemon thread when the playlist is made).
The sidebar art panel shows the *shown* playlist's cover while nothing
is playing (`SidebarArt.set_playlist_art`, fed by
`MainWindow._update_playlist_art`); a song's art always wins.
**Playlist Get Info** (sidebar right-click › Get Info,
`gui/playlist_info_dialog.py`, passive; `MainWindow._playlist_info`
applies rename + cover): name, kind, songs/length, `Playlist.date_created`
(set by every create_* since Round 130; older/iTunes playlists show —),
`date_modified`, last played and `source_url` (the link a URL import made
it from; editable there, undoable, `set_playlist_source`). Last played is **never in the playlist JSON** (a write per song
from both machines = Round 42's conflict): `storage/playlist_plays.py`
keeps `playlist_plays/<machine id>.json` per machine (owner-only writer,
≤ one write a minute per playlist), stamped when a song starts in a
`playlist:<pid>` context; the newest stamp across machines wins. Any
playlist's cover can be set/removed there (non-JPEG/PNG re-encoded PNG).
**Songs already owned** (`library_match.LibraryMatcher`, Shazam's rule
plus a ±15 s length check) are listed "already in your library" and
unticked; `link_rows()` keeps them in the list's order as the library's
copy, and `MainWindow._place_url_rows` fills the playlists in the link's
order as downloads land (a pending download holds back what follows, a
failed one is skipped, the rest go in when the worker ends) — so the
playlist comes out the same and only new songs download.
**Several songs are identified as one batch** (Round 77,
`identify_batch.py` + `gui/identify_batch_dialog.py`): an import of more
than one song never pops a dialog mid-download. `IdentifyCollector` looks
@@ -472,6 +921,44 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
test that downloads several songs must stub `_show_batch_review` and
cancel `_url_batch` on teardown, or a late lookup opens a modal dialog
in the next test.
**Both Identify windows search the cover too** (Round 119,
`gui/art_picker.ArtPicker`, Download Album Art's search as a widget):
`IdentifyDialog(find_art=True)` (every MainWindow caller) searches the
album its grid proposes and re-searches on a candidate switch or after
typing rests; Embed ticks itself only when the file has no cover
(`MainWindow._has_artwork`). A playlist batch gets a picker per album —
searched one at a time, a Cover column, the selected song's album
beside the table; `selected_art()` is [(rows, image, mime)], embedded
in that album's rows whether ticked or not (the tick is about tags).
- **`lintunes/shazam.py`** + **`gui/shazam_import.py`** — Connections ›
Import Shazams… (Round 103), the `/shazam-import` skill inside the app.
Shazam's `library.db` is only reachable through **root adbd**
(`ShazamReader`: `adb root`, pull the db **and its -wal** — the newest
Shazams live there — then `adb unroot` if it was the one that rooted).
Which Shazams are dealt with is the synced pref `shazam_import.handled`
(request id → date; the skill's own state file counts too): imported,
unticked in the preview, or already in the library (`match_library`) —
never a failure, so that comes back next time. Picking the result:
`not_the_song` rejects live/cover/karaoke/instrumental/clean/vinyl/
turntable/sped-up/remix… unless Shazam's title says it too; then Apple's
length (iTunes Search, never a live album or a hits collection) rejects
anything >20 s off, and Topic > the artist's own channel > a stranger's
"(Official Audio)" (measured: the other order picked fan uploads over
Kendrick's and Outkast's own). `ShazamImportWorker` is a
`UrlImportWorker` (it owns `_url_worker`/`_url_progress`, so busy/cancel/
quit come free) narrating `stage` per song — the `LTPP` postprocess
marker is what says "Converting". `ShazamImportWindow` is the song list
*and* an embedded `identify_dialog.IdentifyPanel` per song as soon as it's
imported (a song that didn't make it gets a Copy button in the last
column — `search_text`, to search by hand, Round 128) (its own one-at-a-time `TrackIdentifier` queue; filename
candidates are dropped, since the file already wears Shazam's tags).
**Full Rabbit Sync** (Round 120, beside Sync Music to Rabbit) is the
music sync, then Import Shazams into the playlist current *at the
click* (`_full_sync_target`). `_then_shazams` runs at every end of the
music half — done, failed, nothing ticked, declined — except a cancel,
and retries until the sync worker's busy flag clears (it drops just
after the worker's last signal).
- **`lintunes/mpris.py`** — registers `org.mpris.MediaPlayer2.lintunes` over D-Bus
so the desktop's media keys / now-playing popup control playback. Spacebar and
@@ -577,6 +1064,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
`lintunes/android/andTunes.apk` with its version in `andTunes.json`;
**re-run `--ship` whenever the app changes**, since the committed APK is
what the self-updater carries and what `install.py` installs.
**App v0.4.0** (Round 92): the menu is a list, Now Playing has icon
pills and a full-screen art / album link, and a speakers pill plays the
queue on AirPlay (`AirPlayRemote`, raop.py in Java) or Chromecast
(`CastRemote`, the Cast protocol by hand) — see andtunes/README.md.
Test speakers only against shairport-sync in Docker published on this
machine's LAN address (its avahi stays on the Docker bridge, so it is
never advertised), listed in the device's `Music/andTunes/speakers.txt`
— **never** connect the Rabbit to a speaker that isn't trav's, and read
a screencap before every `input tap`: the picker lists the neighbours'.
`andtunes/andtunes.keystore` is committed on purpose (both machines must
sign identically or `adb install -r` refuses the update). `install.py` is
Connections → Install andTunes on Rabbit…: adb as a runtime tool, then the
@@ -644,6 +1140,27 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
untouched export still renders the original `#8c764a`. Templates are
registered in `setup.py` via `package_data`; loaded with
`importlib.resources` so an installed copy finds them.
**Upload to web server** (Round 81, `export/upload.py`): a ticked box in
the web-mix dialog builds the mix in `$XDG_CACHE_HOME/lintunes/webmix/
<slug>/` (no folder picker) and mirrors it with `rsync -a --checksum
--delete` over ssh to `<host>:<path>/<slug>/`. rsync, not scp: scp re-sends
everything and never deletes, so a song taken out of the playlist would
stay online forever. Host and path live in **`config.json`** only (the
host is usually this machine's `~/.ssh/config` alias, and trav's server
must never appear in the repo or the synced share — tests use
`example-host`). `--delete` only ever reaches the slug folder
(`remote_dir` validates the slug), staging is wiped first
(`reset_staging`, guarded to stay inside the staging root) so a removed
song can't survive the mirror, and ssh runs with `BatchMode=yes`, since
nobody can answer a prompt. Steps: `ServerCheckWorker` (`ssh test -d`; an
existing folder asks before replacing it), `ExportWorker`, then
`UploadWorker`, all shown in `gui/web_upload_progress.py`. The web
player has **previous/next** buttons (the arrow keys, wrapping at either
end, through the shuffle order when on) and a **shuffle** button (and the S key): a shuffled walk that starts at
the current song and plays every song once. A mix can carry several
images (`plan.images`): the dialog always keeps one empty row to add
another, and the page shows them in order under the description, a blank
line apart; none at all ships `placeholder.png`.
- **`lintunes/cassette/`** — friend library sharing (Round 63+; the spec is
`Cassette friend library.md`). LinTunes never talks to a friend: it drives
@@ -727,6 +1244,81 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
a 500 ms poll of `adjusted_current_time` (only trusted while PLAYING — it
creeps while paused).
- **`lintunes/airplay/`** — AirPlay playback (Connections → Connect to
AirPlay…, Round 87), via **pyatv**'s RAOP streaming and the opposite model
to `cast/`: an AirPlay speaker is *sent* PCM in real time, so every song is
decoded by the `ffmpeg` CLI (`stream.py`) and pyatv packetizes it — ALAC and
AIFF play here, only FairPlay is refused. pyatv's own sources don't fit
(its file path is miniaudio, no AAC/ALAC; its pipe path reports duration 0
and guesses the WAV header), so `stream.install_shim` patches the
`open_source` name in `pyatv.protocols.raop` to answer a `PcmRequest` with
an `FfmpegSource` at the negotiated rate. ffmpeg emits **big-endian**
(`s16be`): pyatv byteswaps its own little-endian samples, and the shim's
output is byte-identical to pyatv's `FileSource`. pyatv has **no pause or
seek** for RAOP (its pause *is* stop), so `AirPlaySink` runs one
`stream_file` per stretch of playback and pause/seek/resume start a new one
at `-ss`; each start bumps a generation, so a replaced stream can't report
"finished" and advance the queue. **A closed connection makes pyatv
*return*, not raise** — "the song ended" is only ffmpeg's EOF
(`outcome_of`), anything else is a lost speaker. Position is what's
*heard*: frames read minus the receiver's `22050 + rate` frames of latency
(~1.5 s, `support.heard_ms`). Volume: the slider's level through Qt's
log→linear curve, then that dB on pyatv's −30..0 scale
(`level_to_percent`), applied before each stream starts. Everything pyatv
runs on one `AsyncLoop` thread; results come back as Qt signals.
Discovery repeats `pyatv.scan` while the picker is open and lists *every*
AirPlay device, greyed with the reason when it can't be used (video-only
TVs/projectors have no RAOP; PIN pairing and passwords aren't built), in
`gui/cast_dialog.DevicePickerDialog`, which `ChromecastDialog` shares.
Connects go **RAOP-only** (`controller.raop_only`). Casting and AirPlay are
mutually exclusive (MainWindow disconnects the other first); the visualizer
tile shows the sink's `glyph`. Testing streams against **pyatv's own fake
receiver** (`tests/fake_device/raop.py` in its sdist, bound to 127.0.0.1) —
never a real speaker unless trav says so.
**pyatv's own handshakes play nothing on a WiiM** (Round 88): its AirPlay 2
session (picked for any receiver advertising AirPlay 2 features) gets 200
OK for everything, timing included, and stays silent; its AirPlay 1 runs a
transient pairing and then sends the ANNOUNCE unencrypted, and the WiiM
hangs up. Music Assistant's `cliairplay` plays on it through libraop's
RAOP client (its "RAOP-compat" route), so since Round 90 **`raop.py` is
LinTunes' own RAOP sender** reproducing that client's behaviour, and
pyatv only discovers those speakers: one RTSP session per connection
(auth-setup when `et` lists 4, ANNOUNCE AppleLossless, SETUP, RECORD with
`RTP-Info`, no FLUSH before audio; OPTIONS keepalive every 25 s; FLUSH +
restart for pause/seek/next), the iTunes User-Agent, a **2 s** buffer
(pyatv's is 1.5 s; cliairplay's notes say LinkPlay starves on shallow
ones), RTP timestamps on the NTP clock, a start 200 ms out so the first
~2 s go out at once, the timing responder, resends from a 512-packet
backlog. `NativeDevice` is the slice of a pyatv device `AirPlaySink`
drives, so the sink is shared. Audio is **uncompressed** ALAC
(`support.alac_verbatim`) where libraop compresses: ffmpeg's encoder only
writes 4096-sample frames (RAOP needs 352), and Rice coding in Python
would cost the GUI's interpreter a share of a core. Not yet confirmed on
the WiiM. `use_compat`: config.json's `airplay_protocol` "auto" = the
native sender for everything but Apple's own hardware (a HomePod is
AirPlay 2 only), "1" = native everywhere, "2" = pyatv's AirPlay 2;
`airplay_latency_ms` overrides the 2 s. **cliairplay is the fallback**
(Round 91, trav's go-ahead): when the native sender can't connect, or
config.json's `airplay_backend` is `"cli"` (`"native"` = never fall
back), `cli.ensure_binary` downloads Music Assistant's pinned release
into `$XDG_DATA_HOME/lintunes/bin/` once and **refuses it unless its
SHA-256 matches** the one pinned in `cli.py` — then `CliAirPlaySink`
runs ffmpeg → cliairplay per stretch of playback (commands on a fifo,
`[STATUS]` lines back on stderr; `started at_unix_ms` / `playing
elapsed_ms` give the position). Bumping its version means new pinned
hashes from that release's SHA256SUMS. `airplay_debug` puts pyatv's and
`lintunes.airplay.raop`'s loggers at DEBUG (every RTSP request); every
stream's start, first audio and outcome are logged at INFO under
`lintunes.airplay`, and the chosen sender in the control log.
**Testing without a speaker** (Round 89): shairport-sync in Docker
(`mikebrady/shairport-sync:5.5.2-classic`, its own dbus + avahi inside,
on the default bridge so nothing is advertised on the LAN, `-o stdout`
to a file) is a real third-party receiver whose decoded PCM can be
compared with what was sent — silent and bit-checkable (its output file
also holds the silence it writes while idle). pyatv also died on
shairport's `/info` (not a plist), so the shim treats an unreadable
`/info` as none.
## Conventions & gotchas
- **The Rabbit R1's screen is not what the internet says.** Measured:
@@ -775,6 +1367,30 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
into `contentsRect()` (`art_window.py`); one that needs the system frame
sets the `titlebar.OPT_OUT` property. The bar must never be an event filter
on its own window — that is called during the window's teardown and aborts.
**The window is the house tile** (Round 126, design.html#window, after
routine-widget): translucent with 10 px round corners (square when
maximized, fullscreen or `titlebar.tiled` — within 64 px of the screen's
height, since Qt hides Wayland's tiled state), its gray filled by the installer on the window's `Paint`, and
`titlebar._Frame` — a mouse-transparent overlay masked to the edge ring,
on top of everything — clears outside the curve and paints the soft
emboss and outline. A window shown before anything polished it gets
its native surface *before* `Polish`, so `make_frameless` sets an alpha
format and remakes the surface (Round 128) — without it the cleared
corners were black wedges. No line under the title bar, nor under the menu bar
(`ClickToJumpScrollStyle.drawControl` paints over Fusion's). The main
window sets `BLANK_TITLE` (the song is in the panel right under it);
`VisualizerWindow` sets `SQUARE` — Kaleidostrobe's GL clears to alpha 0,
which would show the desktop through a translucent window. A widget
polished while parentless looks like a window to the installer, so a
`ParentChange` takes the translucency back off — kept on, the now-playing
panel (style sheet set before it had a parent) painted no background.
- **Names in the music tree are NFC** (Round 130): Syncthing (except on a
Mac) renames a non-NFC name to its NFC spelling as it scans, so a YouTube
title with Bengali "ড়" (U+09DC → U+09A1 U+09BC) was renamed under the
library seconds after import and the next tag write hit ENOENT.
`file_importer.sanitize_component` and `_maybe_move_file` write NFC, and
`LibraryManager.repair_location` follows a missing file to its NFC twin
(before every tag write, and on `track_missing` before asking).
- **Music files are only touched deliberately:** tag edits via `tagging.py`,
and — since Round 18 — artist/album_artist/album edits relocate the file
inside `LibraryManager.organize_root()` (`<music_folder>/Music`) to keep the
@@ -785,6 +1401,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
the file to the desktop trash via `trash.py` — never `unlink`, so it stays
recoverable. Nothing else may move, rewrite or remove music files. The library
JSON is the source of truth for everything else.
**The playing song's tags are never saved in place** (Round 111):
mutagen shifts the audio inside the file when a tag outgrows its
padding, and the decoder, reading by offset, glitched (~1.3 M samples
wrong in a 20 s test). `tagging.in_use` (MainWindow: the player's
current track) names those files; `tagging._editable` saves them to a
copy beside them and `os.replace`s it over, so the open file keeps the
old inode, untouched (0 samples wrong). Everything else stays in place —
a full copy per file would make a big batch edit cost gigabytes. No room
for the copy falls back to in place.
- **Versioning & self-update:** `__version__` in `lintunes/__init__.py` is
the single source of truth (`setup.py` regex-reads it, never imports the
package). Claude bumps minor for feature rounds and patch for fix-only
@@ -811,6 +1436,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
When a feature needs a shape the fixture lacks, **add it to the generator**
rather than reaching for the real library.
- **One app icon** (Round 121): `packaging/lint.jpg`, corners rounded at
wave's radius (16 % of the side), rendered by `scripts/make_icons.py` into
`packaging/lintunes.png` (desktop, 512 px, installed by
`packaging/install-desktop.sh`) and andTunes' `ic_launcher.png` — the same
icon on both. There is no swap-a-PNG customization any more; after
remaking it, `andtunes/build.py --ship`.
- **Quitting ends with `main.leave`** (`os._exit` after `aboutToQuit` has
saved everything): a normal `sys.exit` let Python free the QApplication's
wrapper in random order and sip segfaulted on every quit.
- `scripts/` holds one-off maintenance tools (`audit_artwork.py`,
`recover_artwork.py`, `clear_computed_ratings.py`) run manually against a data
dir; most default to dry-run and need `--write` to mutate files.
+29 -1
View File
@@ -53,7 +53,7 @@ mkdir -p ~/Music/lintunes
python3 -m lintunes.main --data-dir ~/Music/lintunes --save-config
```
Now you can open LinTunes from your app menu like any other app. Now you're running LinTunes! You can drag music in and it'll copy it into the ~/Music/lintunes folder and keep it organize (make sure you have enough ssd space to store your music).
**Now you can open LinTunes from your app menu like any other app**. You can drag music in and it'll copy it into the ~/Music/lintunes folder and keep it organize (make sure you have enough ssd space to store your music).
If you see a little asterix in the bottom-left next to the version number it means there's a software update. Click that number and it'll do the update.
@@ -62,6 +62,18 @@ If you see a little asterix in the bottom-left next to the version number it mea
Fedora, enable [RPM Fusion](https://rpmfusion.org/Configuration), then run
`sudo dnf swap ffmpeg-free ffmpeg --allowerasing`.
## macOS
There's a Mac version: download `LinTunes-<version>-AppleSilicon.dmg`
or `-Intel.dmg` from the project's GitHub Releases page, then drag it to
Applications. It's unsigned, so the first launch needs **Open Anyway**
in System Settings › Privacy & Security. Everything except the Rabbit R1
features works there.
- [docs/mac.md](docs/mac.md): installing and using it on a Mac
- [docs/mac-release.md](docs/mac-release.md): how the Mac builds are made and released
- [docs/mac-testing.md](docs/mac-testing.md): the checklist for testing a build on a real Mac
## Keys
_(written by LLM, cleaned up by me)_
@@ -129,6 +141,22 @@ _(written by LLM and cleaned up a bit by me)_
- Theming: highlight color, UI scale, and custom colors
- A soft emboss on every button that follows your custom colors.
**DJ mode** (View ▸ DJ Mode, or the turntable button)
- Two decks open above your library: drag a song onto a record to load it.
Each deck has play/pause, back-to-start, a tempo fader, volume, loops (1/32 to 8 beats), a
½×/1×/2× switch and **Keep pitch** (change tempo without changing key).
- **Sync** matches one deck's tempo and beat to the other's. BPM is worked
out when a song loads (and saved to the song).
- Grab a record to **scratch**; drag the waveforms to scrub. A crossfader
mixes the two, and there's an **air horn**.
- **Vocals slider**: each song is split into vocals and instrumental so you
can fade either out. *Instant* (Spleeter, seconds a song) or *High quality*
(Demucs, minutes a song); both are optional downloads, set up in
Preferences ▸ DJ. Splits are saved so a song is only split once (the limit
is in Preferences ▸ DJ), and **Prepare for DJ** on a playlist's right-click
menu splits everything ahead of time.
- If a song is playing when you open DJ mode, it carries on from Deck A.
**Sending music elsewhere**
- **Chromecast**
- **Export a playlist** (File ▸ Export Playlist…) — either a folder of
+33 -7
View File
@@ -46,9 +46,9 @@ Density is overridden to 160, so an app sees a 480 × 640 **dp** canvas — but
the panel is 2.88", about 278 real ppi. **One dp is roughly half its usual
physical size here.** A stock 48 dp list row is 4.4 mm tall and unusable.
> **Rule: double every stock dp value.** Body text 28–32 sp, list rows ≥ 88 dp,
> menu tiles ~213 dp. A 2 × 3 grid gives six 240 × 213 dp buttons, ≈ 22 × 19 mm
> each.
> **Rule: double every stock dp value.** Body text 28–32 sp, list rows ≥ 88 dp.
> The main menu (a list since v0.4.0) sizes its rows so exactly six fill the
> space the status and navigation bars leave, ≈ 84 dp each.
Do **not** "fix" this by changing the device's density. trav has it where he
wants it and asked for it to be left alone.
@@ -160,9 +160,34 @@ Target: menu visible in **under 400 ms**.
`library.json`, which isn't media — that's the whole reason. Fallback if it
turns out to be blocked: a one-time SAF folder pick.
- **Screens are activities**, so "the last screen we were at" is Android's own
back stack with no bookkeeping. `MenuActivity` (six tiles, loads nothing),
one generic `ListActivity` parameterised for every list in the spec,
`NowPlayingActivity`, and a foreground `PlaybackService`.
back stack with no bookkeeping. `MenuActivity` (a list, loads nothing:
Now Playing / Shuffle All on top, Settings at the bottom), one generic
`ListActivity` parameterised for every list in the spec,
`NowPlayingActivity` (tap the art for it full screen, the title for its
album; shuffle · repeat · speakers as icon pills), `SettingsActivity`
(version and library so far), and a foreground `PlaybackService`.
- **Speakers** (v0.4.0, `SpeakersActivity`): the speakers pill lists this
Rabbit and every AirPlay speaker (`_raop._tcp`) and Chromecast
(`_googlecast._tcp`) NsdManager finds, resolved one at a time (Android 13
refuses a second concurrent resolve). Picking one hands the queue to a
`Remote`; `PlaybackService` keeps queue, shuffle, repeat and play counts
either way, holds a wake + Wi-Fi lock while one is connected, and going
back to the Rabbit leaves it *paused*. The wheel drives the speaker's
volume. No SDKs, by the same rule as everything else:
- `CastRemote` speaks the Cast protocol itself (TLS :8009, length-prefixed
protobuf `CastMessage` frames — encoded by hand, checked byte-identical
to pychromecast's — with JSON payloads), launches the Default Media
Receiver and hands it a URL on `MediaServer`, a token-only HTTP server
with Range, so the speaker fetches the original file (the desktop's
media-receiver model). **Untested on a real Chromecast so far.**
- `AirPlayRemote` is the desktop's `airplay/raop.py` in Java (libraop's
RAOP behaviour: auth-setup, AppleLossless, RECORD with RTP-Info, a 2 s
buffer, NTP-locked timestamps, timing responder, resends), decoding with
MediaExtractor + MediaCodec to 44.1 kHz stereo and sending uncompressed
ALAC (byte-identical to `support.alac_verbatim`). Verified from the R1
against shairport-sync: the receiver's output matched the song.
- `Music/andTunes/speakers.txt` lists speakers by address for when mDNS
can't see them: `airplay|cast <host> [port] [name]` per line.
- **No back button on the now-playing screen** — Android's own is always on
screen and the panel is tiny (trav's call).
- **End of a queue pauses.** It does not roll into shuffle-all. Repeat is
@@ -183,7 +208,8 @@ authority and `manifest.py` for the exact rows.
Media/<Artist>/<Album>/04 Song.mp3
Art/<8-hex album key>.jpg 480 px, one per album
Playlists/<Name>.m3u entries are ../Media/… relative paths
Buttons/*.png the user's own menu artwork — app reads only
Buttons/*.png the user's own button artwork — app reads only
speakers.txt optional: speakers by address (see Speakers)
plays/andtunes-<installid>.json the app writes counts back here (phase 3)
```
+10
View File
@@ -11,6 +11,12 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Speakers: finding them (mDNS), talking to them, staying awake while
a song streams from here to one. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<application
android:label="andTunes"
@@ -34,6 +40,10 @@
<activity android:name=".NowPlayingActivity" android:exported="false"
android:launchMode="singleTop" />
<activity android:name=".SettingsActivity" android:exported="false" />
<activity android:name=".SpeakersActivity" android:exported="false" />
<service android:name=".PlaybackService" android:exported="false"
android:foregroundServiceType="mediaPlayback" />
</application>
@@ -0,0 +1,765 @@
package me.teafry.andtunes;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* AirPlay 1 (RAOP) playback: the desktop's lintunes/airplay/raop.py in Java,
* which reproduces libraop's RAOP client — what Music Assistant's cliairplay
* plays third-party speakers (a WiiM) with:
*
* <ul>
* <li>one RTSP session: auth-setup when {@code et} lists 4, ANNOUNCE
* AppleLossless, SETUP, RECORD carrying RTP-Info, no FLUSH before audio;
* OPTIONS every 25 s; pause and seek are FLUSH + a fresh start;
* <li>a 2 s buffer ({@link #LATENCY_FRAMES} plus the 11025 every receiver
* adds), RTP timestamps on the NTP clock, a start {@link #LEAD_MS} out so
* the first two seconds go at once;
* <li>the NTP timing responder, resends from a 512-packet backlog, a sync
* packet a second.
* </ul>
*
* Audio is decoded here (MediaExtractor + MediaCodec, so whatever the Rabbit
* plays), made 44.1 kHz 16-bit stereo, and sent as uncompressed ALAC frames.
*/
final class AirPlayRemote implements Remote {
static final int FRAMES = 352, RATE = 44100;
static final int LATENCY_MIN = 11025, LATENCY_FRAMES = 88200;
static final int LEAD_MS = 200;
private static final int BACKLOG = 512;
private static final String UA = "iTunes/7.6.2 (Windows; N;)";
private static final long KEEPALIVE_MS = 25000;
private final String name, host;
private final int port;
private final Map<String, String> txt;
private final Handler main = new Handler(Looper.getMainLooper());
private final SecureRandom random = new SecureRandom();
private Events events;
// RTSP
private Socket rtsp;
private InputStream rtspIn;
private OutputStream rtspOut;
private String url, session, localIp;
private int cseq;
private final String clientInstance, dacpId, activeRemote;
private final Object rtspLock = new Object();
// UDP
private DatagramSocket timing, control, audioSock;
private InetAddress peer;
private int serverPort, controlPort;
// Stream state (guarded by this)
private int latency = LATENCY_FRAMES;
private long headTs;
private int seq;
private final int ssrc;
private boolean streaming, first;
private final byte[][] backlog = new byte[BACKLOG][];
private final int[] backlogSeq = new int[BACKLOG];
private volatile boolean closed;
private volatile float volume = 0.5f;
private long lastKeepalive;
// The current song (main thread owns these).
private Library.Track track;
private Streamer streamer;
private int startMs; // where the current stretch began
private long firstSentAt; // elapsedRealtime of its first packet, 0 = none
private int framesSent;
private int pausedAt = -1; // position while paused
AirPlayRemote(String name, String host, int port, Map<String, String> txt) {
this.name = name;
this.host = host;
this.port = port;
this.txt = txt != null ? txt : new HashMap<>();
byte[] b = new byte[8];
random.nextBytes(b);
clientInstance = hex(b);
random.nextBytes(b);
dacpId = hex(b).toUpperCase(Locale.ROOT);
activeRemote = String.valueOf(random.nextInt() & 0x7FFFFFFF);
ssrc = random.nextInt();
seq = random.nextInt(1 << 16);
}
@Override public String name() { return name; }
@Override public void setEvents(Events e) { events = e; }
// ---- clocks ----
static long ntpNow() {
long ms = System.currentTimeMillis();
long sec = ms / 1000, frac = ((ms % 1000) << 32) / 1000;
return (sec << 32) | frac;
}
static long ntp2ts(long ntp) { return ((ntp >>> 16) * RATE) >>> 16; }
static long ts2ntp(long ts) { return ((ts << 16) / RATE) << 16; }
int totalLatency() { return latency + LATENCY_MIN; }
// ---- connecting (blocking; off the main thread) ----
void connect() throws IOException {
peer = InetAddress.getByName(host);
rtsp = new Socket();
rtsp.connect(new InetSocketAddress(peer, port), 8000);
rtsp.setSoTimeout(10000);
rtspIn = new BufferedInputStream(rtsp.getInputStream());
rtspOut = rtsp.getOutputStream();
localIp = rtsp.getLocalAddress().getHostAddress();
String sid = String.format(Locale.ROOT, "%010d", (random.nextLong() >>> 1) % 10000000000L);
url = "rtsp://" + host + "/" + sid;
try {
String et = txt.getOrDefault("et", "");
if (et.contains("4")) {
// 0x01 + a 32-byte public key; libraop carries on whatever the
// answer, and so does this.
byte[] body = new byte[33];
random.nextBytes(body);
body[0] = 1;
request("POST", "/auth-setup", null, "application/octet-stream", body, false);
}
timing = new DatagramSocket(0, InetAddress.getByName(localIp));
daemon(this::timingLoop, "andTunes-raop-timing");
String sdp = "v=0\r\n"
+ "o=iTunes " + sid + " 0 IN IP4 " + localIp + "\r\n"
+ "s=iTunes\r\n"
+ "c=IN IP4 " + host + "\r\n"
+ "t=0 0\r\n"
+ "m=audio 0 RTP/AVP 96\r\n"
+ "a=rtpmap:96 AppleLossless\r\n"
+ "a=fmtp:96 " + FRAMES + " 0 16 40 10 14 2 255 0 0 " + RATE + "\r\n";
request("ANNOUNCE", null, null, "application/sdp",
sdp.getBytes(StandardCharsets.UTF_8), true);
control = new DatagramSocket(0, InetAddress.getByName(localIp));
audioSock = new DatagramSocket(0, InetAddress.getByName(localIp));
Map<String, String> h = request("SETUP", null, new String[] {"Transport",
"RTP/AVP/UDP;unicast;interleaved=0-1;mode=record;control_port="
+ control.getLocalPort() + ";timing_port=" + timing.getLocalPort()},
null, null, true);
session = h.get("session");
for (String part : h.getOrDefault("transport", "").split(";")) {
String[] kv = part.split("=", 2);
if (kv.length < 2) continue;
try {
if (kv[0].trim().equals("server_port")) serverPort = Integer.parseInt(kv[1].trim());
if (kv[0].trim().equals("control_port")) controlPort = Integer.parseInt(kv[1].trim());
} catch (NumberFormatException ignored) { }
}
if (session == null || serverPort == 0 || controlPort == 0) {
throw new IOException("the speaker's SETUP answer had no ports");
}
h = request("RECORD", null, new String[] {"Range", "npt=0-", "RTP-Info",
"seq=" + ((seq + 1) & 0xFFFF) + ";rtptime=" + (ntp2ts(ntpNow()) & 0xFFFFFFFFL)},
null, null, true);
try {
latency = Math.max(latency, Integer.parseInt(h.getOrDefault("audio-latency", "0")));
} catch (NumberFormatException ignored) { }
lastKeepalive = SystemClock.elapsedRealtime();
daemon(this::controlLoop, "andTunes-raop-control");
sendVolume();
} catch (IOException e) {
shutdown();
throw e;
}
}
private Map<String, String> request(String method, String path, String[] headers,
String type, byte[] body, boolean mustSucceed)
throws IOException {
synchronized (rtspLock) {
if (rtsp == null || rtsp.isClosed()) throw new IOException("not connected");
StringBuilder m = new StringBuilder();
m.append(method).append(' ').append(path != null ? path : url).append(" RTSP/1.0\r\n");
for (int i = 0; headers != null && i + 1 < headers.length; i += 2) {
m.append(headers[i]).append(": ").append(headers[i + 1]).append("\r\n");
}
if (type != null && body != null) {
m.append("Content-Type: ").append(type).append("\r\n");
m.append("Content-Length: ").append(body.length).append("\r\n");
}
m.append("CSeq: ").append(++cseq).append("\r\n");
m.append("User-Agent: ").append(UA).append("\r\n");
m.append("Client-Instance: ").append(clientInstance).append("\r\n");
m.append("DACP-ID: ").append(dacpId).append("\r\n");
m.append("Active-Remote: ").append(activeRemote).append("\r\n");
if (session != null) m.append("Session: ").append(session).append("\r\n");
m.append("\r\n");
rtspOut.write(m.toString().getBytes(StandardCharsets.ISO_8859_1));
if (body != null) rtspOut.write(body);
rtspOut.flush();
String status = readLine();
if (status == null) throw new IOException("the speaker closed the connection");
String[] parts = status.split(" ");
int code = parts.length > 1 ? parseInt(parts[1]) : 0;
Map<String, String> h = new HashMap<>();
String line;
while ((line = readLine()) != null && !line.isEmpty()) {
int colon = line.indexOf(':');
if (colon > 0) {
h.put(line.substring(0, colon).trim().toLowerCase(Locale.ROOT),
line.substring(colon + 1).trim());
}
}
int length = parseInt(h.getOrDefault("content-length", "0"));
for (int i = 0; i < length; i++) if (rtspIn.read() < 0) break;
if (mustSucceed && code != 200) {
throw new IOException("the speaker refused " + method + " (" + code + ")");
}
return h;
}
}
private String readLine() throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
int c;
while ((c = rtspIn.read()) >= 0) {
if (c == '\n') break;
if (c != '\r') b.write(c);
}
if (c < 0 && b.size() == 0) return null;
return b.toString("ISO-8859-1");
}
// ---- Remote ----
@Override public void load(Library.Track t, int startMs, boolean play) {
track = t;
pausedAt = startMs;
stopStreamer(true);
if (play) {
startStreamer(startMs, true);
} else {
// Nothing to fetch ahead: AirPlay has no "loaded but paused".
main.post(() -> { if (!closed && events != null) events.remoteReady(); });
}
}
@Override public void play() {
if (track == null || streamer != null) return;
startStreamer(Math.max(0, pausedAt), false);
}
@Override public void pause() {
pausedAt = position();
stopStreamer(true);
}
@Override public void seekTo(int ms) {
pausedAt = ms;
if (streamer != null) {
stopStreamer(true);
startStreamer(ms, false);
}
}
@Override public int position() {
if (streamer == null) return Math.max(0, pausedAt);
if (firstSentAt == 0) return startMs;
long heard = SystemClock.elapsedRealtime() - firstSentAt - LEAD_MS;
long sent = framesSent * 1000L / RATE;
return startMs + (int) Math.max(0, Math.min(heard, sent));
}
@Override public void setVolume(float level) {
volume = Math.max(0f, Math.min(1f, level));
new Thread(this::sendVolume, "andTunes-raop-volume").start();
}
@Override public float volume() { return volume; }
private void sendVolume() {
// 0..1 linear onto −30..0 dB, 0 muted: pyatv's and libraop's scale.
float v = volume;
double db = v <= 0 ? -144.0 : -30.0 + 30.0 * v;
try {
request("SET_PARAMETER", null, null, "text/parameters",
String.format(Locale.ROOT, "volume: %f\r\n", db)
.getBytes(StandardCharsets.US_ASCII), false);
} catch (IOException e) {
lost("the connection dropped");
}
}
@Override public void close() {
if (closed) return;
stopStreamer(false);
closed = true;
new Thread(() -> {
try {
long head;
int s;
synchronized (this) { head = headTs; s = seq; }
request("FLUSH", null, new String[] {"RTP-Info",
"seq=" + ((s + 1) & 0xFFFF) + ";rtptime=" + ((head + 1) & 0xFFFFFFFFL)},
null, null, false);
request("TEARDOWN", null, null, null, null, false);
} catch (IOException ignored) {
} finally {
shutdown();
}
}, "andTunes-raop-close").start();
}
private void shutdown() {
closed = true;
for (DatagramSocket d : new DatagramSocket[] {timing, control, audioSock}) {
if (d != null) d.close();
}
try { if (rtsp != null) rtsp.close(); } catch (IOException ignored) { }
}
private void lost(String why) {
if (closed) return;
main.post(() -> {
if (closed) return;
stopStreamer(false);
shutdown();
if (events != null) events.remoteLost(why);
});
}
// ---- one stretch of a song ----
private void startStreamer(int fromMs, boolean announceReady) {
startMs = fromMs;
firstSentAt = 0;
framesSent = 0;
streamer = new Streamer(track, fromMs, announceReady);
streamer.start();
}
/** Stop the stretch; {@code flush}: and drop what the speaker queued. */
private void stopStreamer(boolean flush) {
Streamer s = streamer;
streamer = null;
if (s == null) return;
s.cancel();
boolean wasStreaming;
long head;
int sq;
synchronized (this) {
wasStreaming = streaming;
streaming = false;
head = headTs;
sq = seq;
}
if (flush && wasStreaming && !closed) {
new Thread(() -> {
try {
request("FLUSH", null, new String[] {"RTP-Info",
"seq=" + ((sq + 1) & 0xFFFF) + ";rtptime=" + ((head + 1) & 0xFFFFFFFFL)},
null, null, false);
} catch (IOException e) {
lost("the connection dropped");
}
}, "andTunes-raop-flush").start();
}
}
private final class Streamer extends Thread {
private final Library.Track t;
private final int fromMs;
private final boolean announceReady;
private volatile boolean cancelled;
Streamer(Library.Track t, int fromMs, boolean announceReady) {
super("andTunes-raop-stream");
setDaemon(true);
this.t = t;
this.fromMs = fromMs;
this.announceReady = announceReady;
}
void cancel() { cancelled = true; interrupt(); }
@Override public void run() {
Pcm pcm;
try {
pcm = new Pcm(t.file().getPath(), fromMs);
} catch (IOException | RuntimeException e) {
post(() -> { if (events != null) events.remoteFailed("can't decode it"); });
return;
}
try {
byte[] packet = new byte[FRAMES * 4];
long lastTs = -1;
synchronized (AirPlayRemote.this) {
headTs = ntp2ts(ntpNow() + ts2ntp(LEAD_MS * (long) RATE / 1000)) - totalLatency();
first = true;
streaming = true;
}
sendSync(true);
if (announceReady) post(() -> { if (events != null) events.remoteReady(); });
while (!cancelled) {
int got = pcm.read(packet);
if (got <= 0) break;
for (int i = got; i < packet.length; i++) packet[i] = 0;
long due;
synchronized (AirPlayRemote.this) { due = headTs + FRAMES; }
long wait = (due - ntp2ts(ntpNow())) * 1000 / RATE;
if (wait > 0) Thread.sleep(wait);
if (cancelled) return;
synchronized (AirPlayRemote.this) {
lastTs = headTs;
sendAudio(packet);
}
final int frames = got / 4;
post(() -> {
if (streamer != this) return;
if (firstSentAt == 0) firstSentAt = SystemClock.elapsedRealtime();
framesSent += frames;
});
}
if (cancelled || lastTs < 0) return;
// Until the end has been heard, then the song is over.
// Timestamps are the wall clock counted in frames.
long endMs = ((lastTs + FRAMES + totalLatency()) * 1000L) / RATE;
while (!cancelled) {
long left = endMs - System.currentTimeMillis();
if (left <= 0) break;
Thread.sleep(Math.min(left, 250));
}
if (!cancelled) post(() -> {
if (streamer != this) return;
streamer = null;
pausedAt = 0;
if (events != null) events.remoteEnded();
});
} catch (InterruptedException ignored) {
} catch (IOException e) {
if (!cancelled) lost("the connection dropped");
} catch (RuntimeException e) {
// MediaCodec gave up mid-song
if (!cancelled) post(() -> {
if (streamer != this) return;
streamer = null;
if (events != null) events.remoteFailed("can't decode it");
});
} finally {
pcm.release();
}
}
private void post(Runnable r) { main.post(() -> { if (!closed) r.run(); }); }
}
/** Under the lock: one packet of 352 frames of s16be stereo. */
private void sendAudio(byte[] pcm) throws IOException {
seq = (seq + 1) & 0xFFFF;
byte[] payload = alacVerbatim(pcm);
byte[] p = new byte[12 + payload.length];
p[0] = (byte) 0x80;
p[1] = (byte) (first ? 0xE0 : 0x60);
first = false;
p[2] = (byte) (seq >>> 8); p[3] = (byte) seq;
putInt(p, 4, (int) headTs);
putInt(p, 8, ssrc);
System.arraycopy(payload, 0, p, 12, payload.length);
backlog[seq % BACKLOG] = p;
backlogSeq[seq % BACKLOG] = seq;
headTs += FRAMES;
audioSock.send(new DatagramPacket(p, p.length, peer, serverPort));
}
private void sendSync(boolean isFirst) {
byte[] p = new byte[20];
long head;
synchronized (this) {
if (!streaming) return;
head = headTs;
}
long ntp = ts2ntp(head);
p[0] = (byte) (isFirst ? 0x90 : 0x80);
p[1] = (byte) 0xD4;
p[2] = 0; p[3] = 7;
putInt(p, 4, (int) (head - latency));
putInt(p, 8, (int) (ntp >>> 32));
putInt(p, 12, (int) ntp);
putInt(p, 16, (int) head);
try {
control.send(new DatagramPacket(p, p.length, peer, controlPort));
} catch (IOException ignored) { }
}
/**
* 16-bit stereo big-endian PCM as one uncompressed ALAC frame: a 23-bit
* channel-pair header flagged "not compressed", the samples, the 3-bit
* end tag, zero padding (support.alac_verbatim on the desktop).
*/
static byte[] alacVerbatim(byte[] pcm) {
int n = pcm.length;
byte[] out = new byte[n + 4];
out[0] = 0x20;
out[1] = 0x00;
out[2] = (byte) (0x02 | ((pcm[0] >> 7) & 1));
for (int i = 0; i < n - 1; i++) {
out[3 + i] = (byte) ((pcm[i] << 1) | ((pcm[i + 1] >> 7) & 1));
}
out[2 + n] = (byte) ((pcm[n - 1] << 1) | 1);
out[3 + n] = (byte) 0xC0;
return out;
}
// ---- the background ----
private void timingLoop() {
byte[] buf = new byte[128];
while (!closed) {
try {
DatagramPacket in = new DatagramPacket(buf, buf.length);
timing.receive(in);
if (in.getLength() < 32) continue;
long now = ntpNow();
byte[] r = new byte[32];
r[0] = buf[0];
r[1] = (byte) (0x53 | 0x80);
r[2] = buf[2]; r[3] = buf[3];
System.arraycopy(buf, 24, r, 8, 8); // their send time = our reference
putInt(r, 16, (int) (now >>> 32)); putInt(r, 20, (int) now);
putInt(r, 24, (int) (now >>> 32)); putInt(r, 28, (int) now);
timing.send(new DatagramPacket(r, r.length, in.getSocketAddress()));
} catch (IOException e) {
if (closed) return;
}
}
}
private void controlLoop() {
byte[] buf = new byte[64];
long lastSync = 0;
try { control.setSoTimeout(250); } catch (IOException ignored) { }
while (!closed) {
long now = SystemClock.elapsedRealtime();
if (now - lastSync >= 1000) {
lastSync = now;
sendSync(false);
}
if (now - lastKeepalive >= KEEPALIVE_MS) {
lastKeepalive = now;
try {
request("OPTIONS", "*", null, null, null, false);
} catch (IOException e) {
lost("the connection dropped");
return;
}
}
try {
DatagramPacket in = new DatagramPacket(buf, buf.length);
control.receive(in);
if (in.getLength() != 8 || (buf[1] & 0x7F) != 0x55) continue;
int firstLost = ((buf[4] & 0xFF) << 8) | (buf[5] & 0xFF);
int count = ((buf[6] & 0xFF) << 8) | (buf[7] & 0xFF);
for (int i = 0; i < count; i++) {
int s = (firstLost + i) & 0xFFFF;
byte[] p;
synchronized (this) {
p = backlogSeq[s % BACKLOG] == s ? backlog[s % BACKLOG] : null;
}
if (p == null) continue;
byte[] r = new byte[4 + p.length];
r[0] = (byte) 0x80; r[1] = (byte) 0xD6; r[2] = 0; r[3] = 1;
System.arraycopy(p, 0, r, 4, p.length);
control.send(new DatagramPacket(r, r.length, peer, controlPort));
}
} catch (SocketTimeoutException ignored) {
} catch (IOException e) {
if (closed) return;
}
}
}
// ---- decoding ----
/** A song as 44.1 kHz 16-bit stereo big-endian PCM, from a position. */
static final class Pcm {
private final MediaExtractor extractor = new MediaExtractor();
private MediaCodec codec;
private final MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
private boolean inputDone, outputDone;
private int rate = RATE, channels = 2;
private long skipUntilUs;
private short[] carry = new short[0]; // decoded, not yet resampled
private double phase; // resampler position in carry
private final ByteArrayOutputStream ready = new ByteArrayOutputStream();
private byte[] readyBytes = new byte[0];
private int readyPos;
Pcm(String path, int fromMs) throws IOException {
extractor.setDataSource(path);
int track = -1;
MediaFormat format = null;
for (int i = 0; i < extractor.getTrackCount(); i++) {
MediaFormat f = extractor.getTrackFormat(i);
String mime = f.getString(MediaFormat.KEY_MIME);
if (mime != null && mime.startsWith("audio/")) { track = i; format = f; break; }
}
if (track < 0) throw new IOException("no audio");
extractor.selectTrack(track);
if (fromMs > 0) {
extractor.seekTo(fromMs * 1000L, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
skipUntilUs = fromMs * 1000L;
}
codec = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
codec.configure(format, null, null, 0);
codec.start();
rate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
channels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
}
/** Fill {@code out} (352 frames); returns bytes written, 0 at the end. */
int read(byte[] out) throws IOException {
while (readyBytes.length - readyPos < out.length && !outputDone) step();
int n = Math.min(out.length, readyBytes.length - readyPos);
System.arraycopy(readyBytes, readyPos, out, 0, n);
readyPos += n;
return n;
}
private void step() throws IOException {
if (!inputDone) {
int in = codec.dequeueInputBuffer(10000);
if (in >= 0) {
ByteBuffer b = codec.getInputBuffer(in);
int size = extractor.readSampleData(b, 0);
if (size < 0) {
codec.queueInputBuffer(in, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
inputDone = true;
} else {
codec.queueInputBuffer(in, 0, size, extractor.getSampleTime(), 0);
extractor.advance();
}
}
}
int outIndex = codec.dequeueOutputBuffer(info, 10000);
if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
MediaFormat f = codec.getOutputFormat();
rate = f.getInteger(MediaFormat.KEY_SAMPLE_RATE);
channels = f.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
return;
}
if (outIndex < 0) return;
ByteBuffer b = codec.getOutputBuffer(outIndex);
short[] samples = new short[info.size / 2];
b.position(info.offset);
b.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(samples);
long ptsUs = info.presentationTimeUs;
boolean end = (info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
codec.releaseOutputBuffer(outIndex, false);
if (end) outputDone = true;
int frames = samples.length / Math.max(1, channels);
int skip = 0;
if (skipUntilUs > 0 && frames > 0) {
long endUs = ptsUs + frames * 1_000_000L / rate;
if (endUs <= skipUntilUs) return;
if (ptsUs < skipUntilUs) skip = (int) ((skipUntilUs - ptsUs) * rate / 1_000_000L);
skipUntilUs = 0;
}
append(samples, skip, frames);
}
/** Decoded frames → stereo at 44.1 kHz → s16be into the ready buffer. */
private void append(short[] s, int skip, int frames) {
int ch = Math.max(1, channels);
short[] stereo = new short[(carry.length / 2 + frames - skip) * 2];
System.arraycopy(carry, 0, stereo, 0, carry.length);
int o = carry.length;
for (int f = skip; f < frames; f++) {
short l = s[f * ch], r = ch > 1 ? s[f * ch + 1] : l;
stereo[o++] = l;
stereo[o++] = r;
}
int total = stereo.length / 2;
if (rate == RATE) {
for (int f = 0; f < total; f++) put(stereo[2 * f], stereo[2 * f + 1]);
carry = new short[0];
} else {
// Linear interpolation; a rare 48 kHz file doesn't need better.
double step = (double) rate / RATE;
while (phase + 1 < total) {
int i = (int) phase;
double frac = phase - i;
put((short) (stereo[2 * i] * (1 - frac) + stereo[2 * i + 2] * frac),
(short) (stereo[2 * i + 1] * (1 - frac) + stereo[2 * i + 3] * frac));
phase += step;
}
int keep = (int) phase;
carry = new short[(total - keep) * 2];
System.arraycopy(stereo, keep * 2, carry, 0, carry.length);
phase -= keep;
}
byte[] fresh = ready.toByteArray();
ready.reset();
byte[] merged = new byte[readyBytes.length - readyPos + fresh.length];
System.arraycopy(readyBytes, readyPos, merged, 0, readyBytes.length - readyPos);
System.arraycopy(fresh, 0, merged, readyBytes.length - readyPos, fresh.length);
readyBytes = merged;
readyPos = 0;
}
private void put(short l, short r) {
ready.write(l >> 8); ready.write(l);
ready.write(r >> 8); ready.write(r);
}
void release() {
try { codec.stop(); } catch (Exception ignored) { }
try { codec.release(); } catch (Exception ignored) { }
extractor.release();
}
}
// ---- small things ----
private static void putInt(byte[] b, int at, int v) {
b[at] = (byte) (v >>> 24); b[at + 1] = (byte) (v >>> 16);
b[at + 2] = (byte) (v >>> 8); b[at + 3] = (byte) v;
}
private static int parseInt(String s) {
try { return Integer.parseInt(s.trim()); } catch (NumberFormatException e) { return 0; }
}
private static String hex(byte[] b) {
StringBuilder s = new StringBuilder();
for (byte x : b) s.append(String.format(Locale.ROOT, "%02x", x));
return s.toString();
}
private static void daemon(Runnable r, String name) {
Thread t = new Thread(r, name);
t.setDaemon(true);
t.start();
}
}
@@ -100,8 +100,17 @@ abstract class BaseActivity extends Activity implements PlaybackService.Listener
}
}
/** One wheel detent. Volume unless the screen has something to scroll. */
/** One wheel detent. Volume unless the screen has something to scroll —
* the speaker's own volume while playing through one. */
protected void onWheel(int dir) {
PlaybackService s = PlaybackService.get();
Remote r = s != null ? s.remote() : null;
if (r != null) {
float level = Math.max(0f, Math.min(1f, r.volume() + dir * 0.05f));
r.setVolume(level);
VolumeBar.show(this, level);
return;
}
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
dir > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER,
AudioManager.FLAG_SHOW_UI);
@@ -0,0 +1,479 @@
package me.teafry.andtunes;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* Chromecast playback, speaking the Cast protocol itself: TLS to port 8009,
* each message a length-prefixed protobuf {@code CastMessage} whose payload is
* JSON. No Google Cast SDK — it needs AndroidX and Play Services' cast
* framework, which andTunes' Gradle-free build doesn't link — and the
* protocol is small: connect, heartbeat, launch the Default Media Receiver,
* hand it a URL.
*
* <p>The desktop's media-receiver model (lintunes/cast): the speaker fetches
* the original file from {@link MediaServer} on the Rabbit, bit for bit.
* A Chromecast presents a self-signed certificate, so the TLS trusts any —
* the same as every Cast sender that isn't Google's.
*/
final class CastRemote implements Remote {
private static final String RECEIVER = "receiver-0", SENDER = "sender-0";
private static final String NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection";
private static final String NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat";
private static final String NS_RECEIVER = "urn:x-cast:com.google.cast.receiver";
private static final String NS_MEDIA = "urn:x-cast:com.google.cast.media";
/** Google's Default Media Receiver. */
private static final String APP_ID = "CC1AD845";
private static final int CONNECT_TIMEOUT_MS = 8000;
private static final long LAUNCH_TIMEOUT_MS = 12000;
private static final long PING_MS = 5000;
private final String name, host;
private final int port;
private final Handler main = new Handler(Looper.getMainLooper());
private Events events;
private SSLSocket socket;
private OutputStream out;
private MediaServer server;
private String localIp;
private volatile boolean closed;
private final Object lock = new Object();
// Receiver state (reader thread writes, under lock).
private String transportId, sessionId;
private int requestId = 1;
private float volume = 0.5f;
// Media state, main thread.
private Integer mediaSessionId;
private int loadRequest = -1;
private boolean awaitingReady, loaded;
private double reportedTime; // seconds, at reportedAt
private long reportedAt;
private boolean reportedPlaying;
private Library.Track track;
CastRemote(String name, String host, int port) {
this.name = name;
this.host = host;
this.port = port;
}
@Override public String name() { return name; }
@Override public void setEvents(Events e) { events = e; }
// ---- connecting (blocking; call off the main thread) ----
void connect() throws IOException {
try {
SSLContext tls = SSLContext.getInstance("TLS");
tls.init(null, new TrustManager[] {new X509TrustManager() {
@Override public void checkClientTrusted(X509Certificate[] c, String a) { }
@Override public void checkServerTrusted(X509Certificate[] c, String a) { }
@Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}}, null);
socket = (SSLSocket) tls.getSocketFactory().createSocket();
socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
socket.startHandshake();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e.getMessage());
}
out = socket.getOutputStream();
localIp = socket.getLocalAddress().getHostAddress();
server = new MediaServer();
Thread reader = new Thread(this::readLoop, "andTunes-cast");
reader.setDaemon(true);
reader.start();
send(NS_CONNECTION, RECEIVER, json("type", "CONNECT"));
Thread ping = new Thread(this::pingLoop, "andTunes-cast-ping");
ping.setDaemon(true);
ping.start();
JSONObject launch = json("type", "LAUNCH");
put(launch, "appId", APP_ID);
request(NS_RECEIVER, RECEIVER, launch);
long deadline = SystemClock.elapsedRealtime() + LAUNCH_TIMEOUT_MS;
synchronized (lock) {
while (transportId == null && !closed) {
long left = deadline - SystemClock.elapsedRealtime();
if (left <= 0) break;
try { lock.wait(left); } catch (InterruptedException e) { break; }
}
}
if (transportId == null) {
close();
throw new IOException("it didn't start the player");
}
send(NS_CONNECTION, transportId, json("type", "CONNECT"));
}
// ---- Remote ----
@Override public void load(Library.Track t, int startMs, boolean play) {
track = t;
loaded = false;
awaitingReady = true;
mediaSessionId = null;
reportedTime = startMs / 1000.0;
reportedAt = SystemClock.elapsedRealtime();
reportedPlaying = false;
File file = t.file();
String base = "http://" + localIp + ":" + server.port();
JSONObject meta = new JSONObject();
put(meta, "metadataType", 3); // MusicTrackMediaMetadata
put(meta, "title", t.title);
put(meta, "artist", t.artistLabel());
if (!t.album.isEmpty()) put(meta, "albumName", t.album);
if (!t.art.isEmpty()) {
File art = new File(Library.root(), t.art);
if (art.isFile()) {
JSONArray images = new JSONArray();
images.put(json("url", base + server.register(art)));
put(meta, "images", images);
}
}
JSONObject media = new JSONObject();
put(media, "contentId", base + server.register(file));
put(media, "streamType", "BUFFERED");
put(media, "contentType", MediaServer.mime(file.getName()));
put(media, "metadata", meta);
JSONObject msg = json("type", "LOAD");
put(msg, "media", media);
put(msg, "autoplay", play);
put(msg, "currentTime", startMs / 1000.0);
loadRequest = background(NS_MEDIA, msg);
}
@Override public void play() { mediaCommand("PLAY", null); }
@Override public void pause() {
reportedTime = position() / 1000.0;
reportedAt = SystemClock.elapsedRealtime();
reportedPlaying = false;
mediaCommand("PAUSE", null);
}
@Override public void seekTo(int ms) {
reportedTime = ms / 1000.0;
reportedAt = SystemClock.elapsedRealtime();
mediaCommand("SEEK", ms / 1000.0);
}
@Override public int position() {
double t = reportedTime;
if (reportedPlaying) t += (SystemClock.elapsedRealtime() - reportedAt) / 1000.0;
int ms = (int) Math.round(t * 1000);
return track != null && track.secs > 0 ? Math.min(ms, track.secs * 1000) : ms;
}
@Override public void setVolume(float level) {
volume = level;
JSONObject msg = json("type", "SET_VOLUME");
put(msg, "volume", json("level", (double) level));
background(NS_RECEIVER, msg);
}
@Override public float volume() { return volume; }
@Override public void close() {
if (closed) return;
String session;
synchronized (lock) { session = sessionId; }
Thread t = new Thread(() -> {
try {
if (session != null) {
JSONObject stop = json("type", "STOP");
put(stop, "sessionId", session);
request(NS_RECEIVER, RECEIVER, stop);
}
send(NS_CONNECTION, RECEIVER, json("type", "CLOSE"));
} catch (IOException ignored) {
} finally {
shutdown();
}
}, "andTunes-cast-close");
t.start();
closed = true;
synchronized (lock) { lock.notifyAll(); }
}
private void shutdown() {
closed = true;
try { if (socket != null) socket.close(); } catch (IOException ignored) { }
if (server != null) server.close();
}
// ---- sending ----
private void mediaCommand(String type, Double seekTo) {
if (mediaSessionId == null) return;
JSONObject msg = json("type", type);
put(msg, "mediaSessionId", mediaSessionId);
if (seekTo != null) put(msg, "currentTime", seekTo);
background(NS_MEDIA, msg);
}
/** Send from a worker (the main thread mustn't touch the network). */
private int background(String ns, JSONObject msg) {
int id;
synchronized (lock) { id = requestId++; }
put(msg, "requestId", id);
String dest;
synchronized (lock) { dest = NS_RECEIVER.equals(ns) ? RECEIVER : transportId; }
if (dest == null) return id;
new Thread(() -> {
try {
send(ns, dest, msg);
} catch (IOException e) {
lost("the connection dropped");
}
}, "andTunes-cast-send").start();
return id;
}
private void request(String ns, String dest, JSONObject msg) throws IOException {
synchronized (lock) { put(msg, "requestId", requestId++); }
send(ns, dest, msg);
}
private void send(String ns, String dest, JSONObject payload) throws IOException {
byte[] frame = encode(SENDER, dest, ns, payload.toString());
synchronized (this) {
if (out == null) throw new IOException("not connected");
out.write(new byte[] {(byte) (frame.length >>> 24), (byte) (frame.length >>> 16),
(byte) (frame.length >>> 8), (byte) frame.length});
out.write(frame);
out.flush();
}
}
private void pingLoop() {
while (!closed) {
try {
Thread.sleep(PING_MS);
if (!closed) send(NS_HEARTBEAT, RECEIVER, json("type", "PING"));
} catch (InterruptedException e) {
return;
} catch (IOException e) {
lost("the connection dropped");
return;
}
}
}
// ---- receiving ----
private void readLoop() {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
while (!closed) {
int length = in.readInt();
if (length <= 0 || length > 1 << 20) throw new IOException("bad frame");
byte[] frame = new byte[length];
in.readFully(frame);
String[] msg = decode(frame); // source, namespace, payload
if (msg[2] == null) continue;
JSONObject payload;
try { payload = new JSONObject(msg[2]); } catch (JSONException e) { continue; }
handle(msg[0], msg[1], payload);
}
} catch (IOException e) {
if (!closed) lost("the connection dropped");
}
}
private void handle(String source, String ns, JSONObject p) throws IOException {
String type = p.optString("type");
if (NS_HEARTBEAT.equals(ns)) {
if ("PING".equals(type)) send(NS_HEARTBEAT, source, json("type", "PONG"));
return;
}
if (NS_CONNECTION.equals(ns) && "CLOSE".equals(type)) {
lost("it closed the session");
return;
}
if (NS_RECEIVER.equals(ns) && "RECEIVER_STATUS".equals(type)) {
JSONObject status = p.optJSONObject("status");
if (status == null) return;
JSONObject vol = status.optJSONObject("volume");
if (vol != null && vol.has("level")) volume = (float) vol.optDouble("level", volume);
JSONArray apps = status.optJSONArray("applications");
JSONObject ours = null;
for (int i = 0; apps != null && i < apps.length(); i++) {
JSONObject a = apps.optJSONObject(i);
if (a != null && APP_ID.equals(a.optString("appId"))) ours = a;
}
synchronized (lock) {
if (ours != null) {
if (transportId == null) {
transportId = ours.optString("transportId", null);
sessionId = ours.optString("sessionId", null);
lock.notifyAll();
}
} else if (transportId != null) {
// Someone else's app took the speaker over.
main.post(() -> lost("something else is playing on it"));
}
}
return;
}
if (!NS_MEDIA.equals(ns)) return;
final JSONObject payload = p;
main.post(() -> onMedia(payload));
}
/** Media messages, on the main thread. */
private void onMedia(JSONObject p) {
if (closed) return;
String type = p.optString("type");
int forRequest = p.optInt("requestId", 0);
if ("LOAD_FAILED".equals(type) || "LOAD_CANCELLED".equals(type)
|| "INVALID_REQUEST".equals(type)) {
if (forRequest == loadRequest && awaitingReady) {
awaitingReady = false;
if (events != null) events.remoteFailed("it can't play this file");
}
return;
}
if (!"MEDIA_STATUS".equals(type)) return;
JSONArray list = p.optJSONArray("status");
if (list == null || list.length() == 0) return;
JSONObject s = list.optJSONObject(0);
if (s == null) return;
if (s.has("mediaSessionId")) mediaSessionId = s.optInt("mediaSessionId");
String state = s.optString("playerState");
if (s.has("currentTime")) {
reportedTime = s.optDouble("currentTime", reportedTime);
reportedAt = SystemClock.elapsedRealtime();
}
reportedPlaying = "PLAYING".equals(state);
if (awaitingReady && ("PLAYING".equals(state) || "PAUSED".equals(state)
|| "BUFFERING".equals(state))) {
awaitingReady = false;
loaded = true;
if (events != null) events.remoteReady();
return;
}
if ("IDLE".equals(state) && loaded) {
String why = s.optString("idleReason");
if ("FINISHED".equals(why)) {
loaded = false;
if (events != null) events.remoteEnded();
} else if ("ERROR".equals(why)) {
loaded = false;
if (events != null) events.remoteFailed("it couldn't play it");
} else if ("INTERRUPTED".equals(why) && !awaitingReady) {
lost("something else is playing on it");
}
}
}
private void lost(String why) {
if (closed) return;
main.post(() -> {
if (closed) return;
shutdown();
if (events != null) events.remoteLost(why);
});
}
// ---- CastMessage, by hand ----
// 1 protocol_version (0), 2 source_id, 3 destination_id, 4 namespace,
// 5 payload_type (0 = string), 6 payload_utf8.
static byte[] encode(String source, String dest, String ns, String payload) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(0x08); b.write(0x00);
field(b, 2, source);
field(b, 3, dest);
field(b, 4, ns);
b.write(0x28); b.write(0x00);
field(b, 6, payload);
return b.toByteArray();
}
private static void field(ByteArrayOutputStream b, int number, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
b.write((number << 3) | 2);
varint(b, bytes.length);
b.write(bytes, 0, bytes.length);
}
private static void varint(ByteArrayOutputStream b, long v) {
while ((v & ~0x7FL) != 0) {
b.write((int) ((v & 0x7F) | 0x80));
v >>>= 7;
}
b.write((int) v);
}
/** {source, namespace, payload_utf8} (nulls where absent). */
static String[] decode(byte[] f) {
String[] out = new String[3];
int i = 0;
while (i < f.length) {
long[] tag = readVarint(f, i);
i = (int) tag[1];
int number = (int) (tag[0] >>> 3), wire = (int) (tag[0] & 7);
if (wire == 0) {
i = (int) readVarint(f, i)[1];
} else if (wire == 2) {
long[] len = readVarint(f, i);
i = (int) len[1];
int n = (int) len[0];
if (i + n > f.length) break;
String s = new String(f, i, n, StandardCharsets.UTF_8);
if (number == 2) out[0] = s;
else if (number == 4) out[1] = s;
else if (number == 6) out[2] = s;
i += n;
} else {
break; // nothing else appears in a CastMessage
}
}
return out;
}
private static long[] readVarint(byte[] f, int i) {
long v = 0;
int shift = 0;
while (i < f.length) {
int b = f[i++] & 0xFF;
v |= (long) (b & 0x7F) << shift;
if ((b & 0x80) == 0) break;
shift += 7;
}
return new long[] {v, i};
}
private static JSONObject json(String key, Object value) {
JSONObject o = new JSONObject();
put(o, key, value);
return o;
}
private static void put(JSONObject o, String key, Object value) {
try { o.put(key, value); } catch (JSONException ignored) { }
}
}
@@ -0,0 +1,179 @@
package me.teafry.andtunes;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* The Rabbit's files over HTTP, for a Chromecast to fetch: the desktop's
* cast/server.py model, so the speaker gets the original file, bit for bit.
*
* <p>A URL carries an opaque random token, never a path, so nothing but what
* was registered can be read. Range and HEAD are supported because a
* Chromecast seeks by re-requesting ranges and won't report a duration
* without them. The last {@link #KEEP} registrations stay valid, so the
* previous song's tail and a cover can still be fetched after a skip.
*/
final class MediaServer {
private static final int KEEP = 8;
private final ServerSocket socket;
private final SecureRandom random = new SecureRandom();
private final Map<String, File> files = new LinkedHashMap<String, File>() {
@Override protected boolean removeEldestEntry(Map.Entry<String, File> e) {
return size() > KEEP;
}
};
private volatile boolean open = true;
MediaServer() throws IOException {
socket = new ServerSocket(0);
Thread accept = new Thread(this::acceptLoop, "andTunes-http");
accept.setDaemon(true);
accept.start();
}
int port() { return socket.getLocalPort(); }
/** The path (with leading slash) that serves {@code file}. */
synchronized String register(File file) {
byte[] b = new byte[12];
random.nextBytes(b);
StringBuilder token = new StringBuilder();
for (byte x : b) token.append(String.format(Locale.ROOT, "%02x", x));
String name = file.getName();
int dot = name.lastIndexOf('.');
String path = "/" + token + (dot >= 0 ? name.substring(dot).toLowerCase(Locale.ROOT) : "");
files.put(path, file);
return path;
}
void close() {
open = false;
try { socket.close(); } catch (IOException ignored) { }
}
static String mime(String name) {
String n = name.toLowerCase(Locale.ROOT);
if (n.endsWith(".mp3")) return "audio/mpeg";
if (n.endsWith(".m4a") || n.endsWith(".mp4") || n.endsWith(".aac")) return "audio/mp4";
if (n.endsWith(".flac")) return "audio/flac";
if (n.endsWith(".ogg") || n.endsWith(".oga") || n.endsWith(".opus")) return "audio/ogg";
if (n.endsWith(".wav")) return "audio/wav";
if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg";
if (n.endsWith(".png")) return "image/png";
return "application/octet-stream";
}
private void acceptLoop() {
while (open) {
try {
Socket client = socket.accept();
Thread t = new Thread(() -> serve(client), "andTunes-http-client");
t.setDaemon(true);
t.start();
} catch (IOException e) {
if (!open) return;
}
}
}
private synchronized File lookup(String path) { return files.get(path); }
private void serve(Socket client) {
try (Socket c = client) {
c.setSoTimeout(30000);
BufferedReader in = new BufferedReader(new InputStreamReader(
c.getInputStream(), StandardCharsets.ISO_8859_1));
OutputStream out = c.getOutputStream();
while (true) {
String request = in.readLine();
if (request == null || request.isEmpty()) return;
String[] parts = request.split(" ");
String range = null;
boolean keepAlive = true;
String line;
while ((line = in.readLine()) != null && !line.isEmpty()) {
int colon = line.indexOf(':');
if (colon < 0) continue;
String key = line.substring(0, colon).trim().toLowerCase(Locale.ROOT);
String value = line.substring(colon + 1).trim();
if (key.equals("range")) range = value;
if (key.equals("connection") && value.equalsIgnoreCase("close")) keepAlive = false;
}
if (parts.length < 2) return;
boolean head = parts[0].equals("HEAD");
File f = lookup(parts[1].split("\\?")[0]);
if ((!head && !parts[0].equals("GET")) || f == null || !f.isFile()) {
write(out, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
if (!keepAlive) return;
continue;
}
long size = f.length(), start = 0, end = size - 1;
boolean partial = false;
if (range != null && range.startsWith("bytes=")) {
String[] se = range.substring(6).split("-", 2);
try {
if (se[0].isEmpty()) {
start = Math.max(0, size - Long.parseLong(se[1]));
} else {
start = Long.parseLong(se[0]);
if (se.length > 1 && !se[1].isEmpty()) end = Math.min(end, Long.parseLong(se[1]));
}
partial = true;
} catch (NumberFormatException ignored) { }
if (start > end || start >= size) {
write(out, "HTTP/1.1 416 Range Not Satisfiable\r\nContent-Range: bytes */"
+ size + "\r\nContent-Length: 0\r\n\r\n");
if (!keepAlive) return;
continue;
}
}
long length = end - start + 1;
StringBuilder h = new StringBuilder();
h.append(partial ? "HTTP/1.1 206 Partial Content\r\n" : "HTTP/1.1 200 OK\r\n");
h.append("Content-Type: ").append(mime(f.getName())).append("\r\n");
h.append("Accept-Ranges: bytes\r\n");
h.append("Access-Control-Allow-Origin: *\r\n");
h.append("Content-Length: ").append(length).append("\r\n");
if (partial) {
h.append("Content-Range: bytes ").append(start).append('-').append(end)
.append('/').append(size).append("\r\n");
}
h.append("\r\n");
write(out, h.toString());
if (!head) {
try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
raf.seek(start);
byte[] buf = new byte[64 * 1024];
long left = length;
while (left > 0) {
int n = raf.read(buf, 0, (int) Math.min(buf.length, left));
if (n < 0) break;
out.write(buf, 0, n);
left -= n;
}
}
}
out.flush();
if (!keepAlive) return;
}
} catch (IOException ignored) {
// the speaker hung up mid-file: it does that on every seek
}
}
private static void write(OutputStream out, String s) throws IOException {
out.write(s.getBytes(StandardCharsets.ISO_8859_1));
}
}
@@ -11,29 +11,35 @@ import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.graphics.drawable.ColorDrawable;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* The first screen, and the number the project is judged on: six tiles,
* visible in well under 400 ms. It <b>loads nothing</b> — it only starts the
* library parse in the background, so the data is usually ready by the time a
* finger lands on a tile.
* The first screen, and the number the project is judged on: visible in well
* under 400 ms. It <b>loads nothing</b> — it only starts the library parse in
* the background, so the data is usually ready by the time a finger lands.
*
* <p>A list like every other menu (trav's call, replacing the six picture
* tiles): Now Playing on top (Shuffle All when nothing is loaded), the
* library's ways in, Settings at the bottom. Six rows fill the screen; the
* wheel scrolls to the seventh.
*/
public class MenuActivity extends BaseActivity {
private static final String[] MODES = {
ListActivity.PLAYLISTS, ListActivity.ARTISTS, ListActivity.ALBUMS,
ListActivity.SONGS, ListActivity.SEARCH};
private static final String[] NAMES = {"playlists", "artists", "albums", "songs", "search"};
private static final String[] LABELS = {"Playlists", "Artists", "Albums", "Songs", "Search"};
private static final int[] ART = {
R.drawable.playlists, R.drawable.artists, R.drawable.albums,
R.drawable.songs, R.drawable.search};
/** Rows: [0] Now Playing / Shuffle All, then LABELS, then Settings. */
private static final int ROWS = LABELS.length + 2;
private static final int ROW_DP = 84;
private ImageView sixth;
private Boolean builtWithAccess;
private boolean sixthShowsNowPlaying;
private BaseAdapter adapter;
private ListView list;
private WheelScroll wheel;
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
@@ -49,6 +55,16 @@ public class MenuActivity extends BaseActivity {
}
}
@Override protected void onDestroy() {
if (wheel != null) wheel.stop();
super.onDestroy();
}
@Override protected void onWheel(int dir) {
if (wheel != null) wheel.push(dir);
else super.onWheel(dir);
}
private void build() {
builtWithAccess = hasAccess();
if (!builtWithAccess) {
@@ -62,38 +78,68 @@ public class MenuActivity extends BaseActivity {
requestPermissions(new String[] {Manifest.permission.POST_NOTIFICATIONS}, 1);
}
LinearLayout grid = new LinearLayout(this);
grid.setOrientation(LinearLayout.VERTICAL);
int pad = Ui.dp(this, 4);
grid.setPadding(pad, pad, pad, pad);
LinearLayout row = null;
for (int i = 0; i < 6; i++) {
if (i % 2 == 0) {
row = new LinearLayout(this);
grid.addView(row, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
}
ImageView tile = new ImageView(this);
tile.setScaleType(ImageView.ScaleType.FIT_CENTER);
tile.setPadding(pad, pad, pad, pad);
if (i < 5) {
final int n = i;
tile.setImageDrawable(Ui.button(this, NAMES[i], ART[i]));
tile.setContentDescription(LABELS[i]);
tile.setOnClickListener(v -> startActivity(
new Intent(this, ListActivity.class).putExtra(ListActivity.MODE, MODES[n])));
LinearLayout column = new LinearLayout(this);
column.setOrientation(LinearLayout.VERTICAL);
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
titleBar.setBackgroundColor(Ui.BLACK);
titleBar.setGravity(Gravity.CENTER_VERTICAL);
int pad = Ui.dp(this, 20);
titleBar.setPadding(pad, 0, pad, 0);
titleBar.setText("andTunes");
column.addView(titleBar, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
list = new ListView(this);
list.setDivider(new ColorDrawable(Ui.BLACK));
list.setDividerHeight(Ui.dp(this, 1));
list.setBackgroundColor(Ui.WHITE);
adapter = new BaseAdapter() {
@Override public int getCount() { return ROWS; }
@Override public Object getItem(int i) { return i; }
@Override public long getItemId(int i) { return i; }
@Override public View getView(int i, View convert, ViewGroup parent) {
TextView row = convert != null ? (TextView) convert
: Ui.text(MenuActivity.this, Ui.TITLE_SP, false, Ui.BLACK);
row.setGravity(Gravity.CENTER_VERTICAL);
row.setPadding(pad, 0, pad, 0);
// Six rows fill the list exactly, whatever the bars leave.
int fit = parent.getHeight() > 0
? (parent.getHeight() - 5 * list.getDividerHeight()) / 6
: Ui.dp(MenuActivity.this, ROW_DP);
row.setMinHeight(fit);
row.setHeight(fit);
row.setTypeface(null, i == 0 ? android.graphics.Typeface.BOLD
: android.graphics.Typeface.NORMAL);
if (i == 0) {
row.setText(hasTrack() ? "Now Playing" : "Shuffle All");
} else if (i <= LABELS.length) {
row.setText(LABELS[i - 1]);
} else {
sixth = tile;
tile.setOnClickListener(v -> onSixth());
row.setText("Settings");
}
row.addView(tile, new LinearLayout.LayoutParams(0,
ViewGroup.LayoutParams.MATCH_PARENT, 1f));
return row;
}
sixthShowsNowPlaying = !hasTrack(); // force the first paint
setScreen(grid, false);
};
list.setAdapter(adapter);
list.setOnItemClickListener((parent, view, i, rowId) -> onRow(i));
wheel = new WheelScroll(list);
column.addView(list, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
setScreen(column, false);
onPlaybackChanged();
}
private void onRow(int i) {
if (i == 0) {
onFirst();
} else if (i <= LABELS.length) {
startActivity(new Intent(this, ListActivity.class)
.putExtra(ListActivity.MODE, MODES[i - 1]));
} else {
startActivity(new Intent(this, SettingsActivity.class));
}
}
private static boolean hasTrack() {
PlaybackService s = PlaybackService.get();
return s != null && s.current() != null;
@@ -101,17 +147,11 @@ public class MenuActivity extends BaseActivity {
@Override public void onPlaybackChanged() {
super.onPlaybackChanged();
if (sixth == null) return;
boolean now = hasTrack();
if (now == sixthShowsNowPlaying) return;
sixthShowsNowPlaying = now;
sixth.setImageDrawable(now ? Ui.button(this, "now_playing", R.drawable.now_playing)
: Ui.button(this, "shuffle_all", R.drawable.shuffle_all));
sixth.setContentDescription(now ? "Now Playing" : "Shuffle All");
if (adapter != null) adapter.notifyDataSetChanged(); // Now Playing / Shuffle All
}
/** "Now Playing" when there is something, else shuffle everything we know. */
private void onSixth() {
private void onFirst() {
if (hasTrack()) {
openNowPlaying();
return;
@@ -14,15 +14,20 @@ import android.widget.SeekBar;
import android.widget.TextView;
/**
* White background, square art, a slim scrubber, ◀ ⏯ ▶, then shuffle and
* repeat. <b>No back button</b> — Android's own is always on screen, and the
* panel is too small to spend on a second one (trav's call). The wheel stays
* volume here: this is the one screen where that's the useful thing.
* White background, square art, a slim scrubber, ◀ ⏯ ▶, then shuffle, repeat
* and speakers as icon pills. <b>No back button</b> — Android's own is always
* on screen, and the panel is too small to spend on a second one (trav's
* call). The wheel stays volume here: this is the one screen where that's the
* useful thing.
*
* <p>Tapping the art shows it full screen (tap again to come back); tapping
* the title or the artist line opens the song's album.
*/
public class NowPlayingActivity extends BaseActivity {
private final Handler main = new Handler(Looper.getMainLooper());
private ImageView art, playPause;
private TextView title, detail, elapsed, remaining, shuffleBtn, repeatBtn;
private ImageView art, playPause, shuffleBtn, repeatBtn, speakersBtn, bigArt;
private TextView title, detail, elapsed, remaining;
private Drawable shuffleD, repeatD, repeatOneD, speakersD;
private SeekBar scrubber;
private boolean dragging;
private Library.Track shown;
@@ -52,6 +57,7 @@ public class NowPlayingActivity extends BaseActivity {
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
alp.gravity = Gravity.CENTER_HORIZONTAL;
col.addView(art, alp);
art.setOnClickListener(v -> showBigArt(true));
title = Ui.text(this, 26, true, Ui.BLACK);
title.setGravity(Gravity.CENTER);
@@ -63,6 +69,8 @@ public class NowPlayingActivity extends BaseActivity {
LinearLayout.LayoutParams dlp = wrap();
dlp.topMargin = Ui.dp(this, 4);
col.addView(detail, dlp);
title.setOnClickListener(v -> openAlbum());
detail.setOnClickListener(v -> openAlbum());
scrubber = new SeekBar(this);
ColorStateList black = ColorStateList.valueOf(Ui.BLACK);
@@ -106,17 +114,53 @@ public class NowPlayingActivity extends BaseActivity {
col.addView(transport, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 96)));
shuffleD = Ui.button(this, "shuffle", R.drawable.shuffle);
repeatD = Ui.button(this, "repeat", R.drawable.repeat);
repeatOneD = Ui.button(this, "repeat_one", R.drawable.repeat_one);
speakersD = Ui.button(this, "speakers", R.drawable.speakers);
LinearLayout toggles = new LinearLayout(this);
shuffleBtn = toggle(toggles, "Shuffle");
repeatBtn = toggle(toggles, "Repeat");
shuffleBtn = toggle(toggles, shuffleD, "Shuffle");
repeatBtn = toggle(toggles, repeatD, "Repeat");
speakersBtn = toggle(toggles, speakersD, "Speakers");
shuffleBtn.setOnClickListener(v -> withService(s -> s.setShuffle(!s.shuffle())));
repeatBtn.setOnClickListener(v -> withService(PlaybackService::cycleRepeat));
speakersBtn.setOnClickListener(v -> startActivity(
new android.content.Intent(this, SpeakersActivity.class)));
LinearLayout.LayoutParams glp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64));
glp.topMargin = Ui.dp(this, 8);
col.addView(toggles, glp);
setScreen(col, false);
// The art, full screen, over everything; a tap anywhere puts it away.
android.widget.FrameLayout stack = new android.widget.FrameLayout(this);
stack.addView(col);
bigArt = new ImageView(this);
bigArt.setScaleType(ImageView.ScaleType.FIT_CENTER);
bigArt.setBackgroundColor(Ui.WHITE);
bigArt.setVisibility(android.view.View.GONE);
bigArt.setOnClickListener(v -> showBigArt(false));
stack.addView(bigArt);
setScreen(stack, false);
}
private void showBigArt(boolean show) {
if (show) {
if (shown == null || shown.art.isEmpty()) return;
bigArt.setImageDrawable(art.getDrawable());
}
bigArt.setVisibility(show ? android.view.View.VISIBLE : android.view.View.GONE);
}
@Override public void onBackPressed() {
if (bigArt.getVisibility() == android.view.View.VISIBLE) showBigArt(false);
else super.onBackPressed();
}
private void openAlbum() {
if (shown == null || shown.albumRef == null) return;
startActivity(new android.content.Intent(this, ListActivity.class)
.putExtra(ListActivity.MODE, ListActivity.ALBUM)
.putExtra(ListActivity.ID, shown.albumRef.key));
}
private LinearLayout.LayoutParams wrap() {
@@ -134,15 +178,20 @@ public class NowPlayingActivity extends BaseActivity {
return b;
}
private TextView toggle(LinearLayout row, String label) {
TextView t = Ui.text(this, 22, true, Ui.BLACK);
t.setText(label);
private ImageView toggle(LinearLayout row, Drawable icon, String label) {
ImageView b = new ImageView(this);
b.setImageDrawable(icon);
b.setScaleType(ImageView.ScaleType.FIT_CENTER);
int p = Ui.dp(this, 10);
b.setPadding(p, p, p, p);
b.setContentDescription(label);
Ui.toggleStyle(this, b, false);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
int m = Ui.dp(this, 6);
lp.setMargins(m, 0, m, 0);
row.addView(t, lp);
return t;
row.addView(b, lp);
return b;
}
private interface Action { void run(PlaybackService s); }
@@ -200,8 +249,10 @@ public class NowPlayingActivity extends BaseActivity {
playPause.setContentDescription(s.isPlaying() ? "Pause" : "Play");
Ui.toggleStyle(this, shuffleBtn, s.shuffle());
int r = s.repeat();
repeatBtn.setText(r == PlaybackService.REPEAT_ONE ? "Repeat one"
repeatBtn.setImageDrawable(r == PlaybackService.REPEAT_ONE ? repeatOneD : repeatD);
repeatBtn.setContentDescription(r == PlaybackService.REPEAT_ONE ? "Repeat one"
: r == PlaybackService.REPEAT_ALL ? "Repeat all" : "Repeat");
Ui.toggleStyle(this, repeatBtn, r != PlaybackService.REPEAT_OFF);
Ui.toggleStyle(this, speakersBtn, s.remoteName() != null);
}
}
@@ -41,7 +41,8 @@ import java.util.Random;
*/
public class PlaybackService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener, AudioManager.OnAudioFocusChangeListener {
MediaPlayer.OnErrorListener, AudioManager.OnAudioFocusChangeListener,
Remote.Events {
interface Listener { void onPlaybackChanged(); }
@@ -79,6 +80,11 @@ public class PlaybackService extends Service implements
private int failures;
private final History history = new History();
/** Playing through a speaker instead of the MediaPlayer (null: here). */
private Remote remote;
private PowerManager.WakeLock remoteWake;
private android.net.wifi.WifiManager.WifiLock remoteWifi;
// ---- the static front door ----
static PlaybackService get() { return sService; }
@@ -173,7 +179,7 @@ public class PlaybackService extends Service implements
}
@Override public void onTaskRemoved(Intent rootIntent) {
if (!playing) stopSelf();
if (!playing && remote == null) stopSelf();
}
@Override public void onDestroy() {
@@ -182,6 +188,8 @@ public class PlaybackService extends Service implements
abandonFocus();
unregisterNoisy();
main.removeCallbacksAndMessages(null);
if (remote != null) { remote.close(); remote = null; }
holdRemoteLocks(false);
session.release();
mp.release();
notifications.cancel(NOTIFICATION_ID);
@@ -204,13 +212,19 @@ public class PlaybackService extends Service implements
int repeat() { return repeat; }
/** The speaker being played through, or null for the Rabbit itself. */
String remoteName() { return remote != null ? remote.name() : null; }
Remote remote() { return remote; }
int position() {
if (!prepared) return pendingSeek;
if (remote != null) return remote.position();
try { return mp.getCurrentPosition(); } catch (IllegalStateException e) { return 0; }
}
int duration() {
if (prepared) {
if (prepared && remote == null) {
try { return mp.getDuration(); } catch (IllegalStateException ignored) { }
}
Library.Track t = current();
@@ -224,14 +238,18 @@ public class PlaybackService extends Service implements
void play() {
if (current() == null) return;
if (!prepared) { playWhenReady = true; return; }
if (remote != null) {
remote.play();
} else {
if (audio.requestAudioFocus(focusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
return;
}
mp.setVolume(1f, 1f);
mp.start();
}
playing = true;
history.playing(current());
registerNoisy();
if (remote == null) registerNoisy();
goForeground();
tick();
changed();
@@ -240,7 +258,8 @@ public class PlaybackService extends Service implements
void pause() {
playWhenReady = false;
if (playing) {
try { mp.pause(); } catch (IllegalStateException ignored) { }
if (remote != null) remote.pause();
else try { mp.pause(); } catch (IllegalStateException ignored) { }
}
playing = false;
history.paused();
@@ -256,7 +275,8 @@ public class PlaybackService extends Service implements
}
void seekTo(int ms) {
if (prepared) mp.seekTo(ms);
if (prepared && remote != null) remote.seekTo(ms);
else if (prepared) mp.seekTo(ms);
else pendingSeek = ms;
changed();
}
@@ -335,8 +355,9 @@ public class PlaybackService extends Service implements
// End of the queue pauses, parked at the top of the last song.
playing = false;
pendingSeek = 0;
if (prepared) mp.seekTo(0);
if (prepared && remote == null) mp.seekTo(0);
pause();
if (remote != null) { prepared = false; pendingSeek = 0; }
}
return;
}
@@ -354,6 +375,16 @@ public class PlaybackService extends Service implements
prepared = false;
playWhenReady = play;
pendingSeek = seekMs;
if (remote != null) {
if (!t.file().isFile()) {
skipBroken(t, "missing");
return;
}
remote.load(t, seekMs, play);
saveState();
changed();
return;
}
try {
mp.reset();
if (!t.file().isFile()) throw new java.io.FileNotFoundException(t.path);
@@ -408,9 +439,99 @@ public class PlaybackService extends Service implements
return true;
}
// ---- playing through a speaker ----
/**
* Hand playback to {@code r}, already connected: the song carries on
* there from where it is. The MediaPlayer is stopped, not released.
*/
void connectRemote(Remote r) {
boolean wasPlaying = playing;
int at = current() != null ? position() : 0;
if (playing) {
try { mp.pause(); } catch (IllegalStateException ignored) { }
playing = false;
}
abandonFocus();
unregisterNoisy();
if (remote != null) remote.close();
remote = r;
r.setEvents(this);
holdRemoteLocks(true);
if (current() != null) load(pos, wasPlaying, at);
else changed();
}
/** Back to the Rabbit, paused where the speaker was (never blaring out). */
void disconnectRemote() {
if (remote == null) return;
int at = current() != null && prepared ? remote.position() : pendingSeek;
Remote r = remote;
remote = null;
r.close();
holdRemoteLocks(false);
if (playing) history.paused();
playing = false;
if (current() != null) load(pos, false, at);
else changed();
}
/** Streaming runs on our threads, so the CPU and Wi-Fi must stay up. */
private void holdRemoteLocks(boolean hold) {
if (hold) {
if (remoteWake == null) {
remoteWake = getSystemService(PowerManager.class).newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "andTunes:speaker");
remoteWifi = getSystemService(android.net.wifi.WifiManager.class)
.createWifiLock(android.net.wifi.WifiManager.WIFI_MODE_FULL_HIGH_PERF,
"andTunes:speaker");
}
if (!remoteWake.isHeld()) remoteWake.acquire();
if (!remoteWifi.isHeld()) remoteWifi.acquire();
} else {
if (remoteWake != null && remoteWake.isHeld()) remoteWake.release();
if (remoteWifi != null && remoteWifi.isHeld()) remoteWifi.release();
}
}
@Override public void remoteReady() {
if (remote == null) return;
prepared = true;
failures = 0;
pendingSeek = 0;
if (playWhenReady) {
playing = true;
history.playing(current());
goForeground();
tick();
}
changed();
}
@Override public void remoteEnded() {
if (remote == null || !prepared) return;
Library.Track done = current();
if (done != null) Plays.record(this, done.id);
history.end(this, "finish");
advance(true);
}
@Override public void remoteFailed(String why) {
Library.Track t = current();
prepared = false;
if (t != null) skipBroken(t, why);
}
@Override public void remoteLost(String why) {
if (remote == null) return;
Ui.toast(this, "Lost " + remote.name() + (why.isEmpty() ? "" : " (" + why + ")"));
disconnectRemote();
}
// ---- audio focus, noisy ----
@Override public void onAudioFocusChange(int change) {
if (remote != null) return; // the speaker isn't ours to duck
switch (change) {
case AudioManager.AUDIOFOCUS_LOSS:
resumeOnFocus = false;
@@ -0,0 +1,46 @@
package me.teafry.andtunes;
/**
* A speaker the queue plays through instead of the Rabbit's own output: a
* Chromecast ({@link CastRemote}) or an AirPlay speaker ({@link AirPlayRemote}).
*
* <p>{@link PlaybackService} keeps the queue, shuffle, repeat and play counts
* either way; a remote only has to make one song come out of something and
* say where it's up to. Calls arrive on the main thread and return at once
* (the network happens on the remote's own threads); {@link Events} are
* delivered on the main thread too.
*/
interface Remote {
interface Events {
/** The song is loaded (and playing, if it was asked to). */
void remoteReady();
/** The song played to its end. */
void remoteEnded();
/** This song can't be played there; the queue moves on. */
void remoteFailed(String why);
/** The speaker went away; playback stops. */
void remoteLost(String why);
}
String name();
void setEvents(Events events);
void load(Library.Track track, int startMs, boolean play);
void play();
void pause();
void seekTo(int ms);
/** Where the listener is in the song, in ms. */
int position();
/** 0..1, the speaker's own volume. */
void setVolume(float level);
float volume();
void close();
}
@@ -0,0 +1,65 @@
package me.teafry.andtunes;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
/**
* The menu's last row. Nothing to set yet: what the app is, and what the last
* sync left on the Rabbit — the place future settings go.
*/
public class SettingsActivity extends BaseActivity {
private LinearLayout column;
private TextView library;
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
column = new LinearLayout(this);
column.setOrientation(LinearLayout.VERTICAL);
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
titleBar.setBackgroundColor(Ui.BLACK);
titleBar.setGravity(Gravity.CENTER_VERTICAL);
int pad = Ui.dp(this, 20);
titleBar.setPadding(pad, 0, pad, 0);
titleBar.setText("Settings");
column.addView(titleBar, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
String version = "";
try {
version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (Exception ignored) { }
line("andTunes " + version, true);
library = line("Loading the library…", false);
File manifest = Library.manifest();
if (manifest.isFile()) {
line("Last synced " + DateFormat.format("d MMM yyyy, h:mm a",
manifest.lastModified()), false);
}
setScreen(column, true);
Library.whenReady((lib, error) -> {
if (lib == null) {
library.setText(error != null ? error : "No library");
} else {
library.setText(lib.tracks.size() + " songs, "
+ lib.playlists.size() + " playlists");
}
});
}
private TextView line(String text, boolean bold) {
TextView t = Ui.text(this, Ui.SUB_SP + 3, bold, Ui.BLACK);
t.setSingleLine(false);
t.setText(text);
int pad = Ui.dp(this, 20);
t.setPadding(pad, Ui.dp(this, 16), pad, 0);
column.addView(t, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return t;
}
}
@@ -0,0 +1,142 @@
package me.teafry.andtunes;
import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.os.Handler;
import android.os.Looper;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Finds AirPlay (RAOP) speakers and Chromecasts on the Wi-Fi with Android's
* own mDNS (NsdManager), while the picker is open. Resolving is done one
* service at a time: on Android 13 a second resolve while one is running
* fails with FAILURE_ALREADY_ACTIVE.
*/
final class Speakers {
static final String AIRPLAY = "_raop._tcp", CAST = "_googlecast._tcp";
static final class Speaker {
final String kind, id, name, host;
final int port;
final Map<String, String> txt;
/** Why it can't be used ("" = it can). */
final String note;
Speaker(String kind, String id, String name, String host, int port,
Map<String, String> txt, String note) {
this.kind = kind; this.id = id; this.name = name; this.host = host;
this.port = port; this.txt = txt; this.note = note;
}
String kindLabel() { return CAST.equals(kind) ? "Chromecast" : "AirPlay"; }
}
interface Listener { void onSpeakers(ArrayList<Speaker> speakers); }
private final NsdManager nsd;
private final Handler main = new Handler(Looper.getMainLooper());
private final Listener listener;
private final LinkedHashMap<String, Speaker> found = new LinkedHashMap<>();
private final ArrayDeque<NsdServiceInfo> toResolve = new ArrayDeque<>();
private boolean resolving, running;
private final ArrayList<NsdManager.DiscoveryListener> browsers = new ArrayList<>();
Speakers(Context c, Listener listener) {
nsd = c.getSystemService(NsdManager.class);
this.listener = listener;
}
void start() {
if (running) return;
running = true;
for (String type : new String[] {AIRPLAY, CAST}) {
NsdManager.DiscoveryListener l = new NsdManager.DiscoveryListener() {
@Override public void onDiscoveryStarted(String t) { }
@Override public void onDiscoveryStopped(String t) { }
@Override public void onStartDiscoveryFailed(String t, int code) { }
@Override public void onStopDiscoveryFailed(String t, int code) { }
@Override public void onServiceFound(NsdServiceInfo info) {
main.post(() -> { toResolve.add(info); resolveNext(); });
}
@Override public void onServiceLost(NsdServiceInfo info) {
main.post(() -> {
String key = typeOf(info) + "/" + info.getServiceName();
if (found.remove(key) != null) publish();
});
}
};
browsers.add(l);
nsd.discoverServices(type, NsdManager.PROTOCOL_DNS_SD, l);
}
}
void stop() {
if (!running) return;
running = false;
for (NsdManager.DiscoveryListener l : browsers) {
try { nsd.stopServiceDiscovery(l); } catch (IllegalArgumentException ignored) { }
}
browsers.clear();
toResolve.clear();
}
private static String typeOf(NsdServiceInfo info) {
String t = info.getServiceType();
return t != null && t.contains("googlecast") ? CAST : AIRPLAY;
}
private void resolveNext() {
if (resolving || !running || toResolve.isEmpty()) return;
resolving = true;
NsdServiceInfo next = toResolve.poll();
nsd.resolveService(next, new NsdManager.ResolveListener() {
@Override public void onResolveFailed(NsdServiceInfo info, int code) {
main.post(() -> { resolving = false; resolveNext(); });
}
@Override public void onServiceResolved(NsdServiceInfo info) {
main.post(() -> {
resolving = false;
add(info);
resolveNext();
});
}
});
}
private void add(NsdServiceInfo info) {
if (info.getHost() == null) return;
String kind = typeOf(info);
Map<String, String> txt = new HashMap<>();
for (Map.Entry<String, byte[]> e : info.getAttributes().entrySet()) {
txt.put(e.getKey(), e.getValue() == null ? ""
: new String(e.getValue(), StandardCharsets.UTF_8));
}
String service = info.getServiceName();
String name;
String note = "";
if (CAST.equals(kind)) {
name = txt.containsKey("fn") ? txt.get("fn") : service;
} else {
// "AABBCCDDEEFF@Living Room"
int at = service.indexOf('@');
name = at >= 0 ? service.substring(at + 1) : service;
if ("true".equalsIgnoreCase(txt.get("pw"))) note = "needs a password";
}
found.put(kind + "/" + service, new Speaker(kind, kind + "/" + service, name,
info.getHost().getHostAddress(), info.getPort(), txt, note));
publish();
}
private void publish() {
ArrayList<Speaker> list = new ArrayList<>(found.values());
list.sort((a, b) -> a.name.compareToIgnoreCase(b.name));
listener.onSpeakers(list);
}
}
@@ -0,0 +1,231 @@
package me.teafry.andtunes;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.graphics.drawable.ColorDrawable;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
/**
* "Play on": this Rabbit, then every AirPlay speaker and Chromecast found on
* the Wi-Fi. Tapping one connects in the background and hands the queue to
* it; tapping "This Rabbit" (or the speaker already playing) comes back,
* paused.
*
* <p>Speakers mDNS can't find (another subnet, a receiver that doesn't
* advertise) can be listed in {@code Music/andTunes/speakers.txt}, one per
* line: {@code airplay|cast <host> [port] [name]}. They come first.
*/
public class SpeakersActivity extends BaseActivity implements Speakers.Listener {
private final Handler main = new Handler(Looper.getMainLooper());
private final ArrayList<Speakers.Speaker> speakers = new ArrayList<>();
private Speakers discovery;
private BaseAdapter adapter;
private ListView list;
private WheelScroll wheel;
private String connecting; // speaker id while a connect runs
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
LinearLayout column = new LinearLayout(this);
column.setOrientation(LinearLayout.VERTICAL);
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
titleBar.setBackgroundColor(Ui.BLACK);
titleBar.setGravity(Gravity.CENTER_VERTICAL);
int pad = Ui.dp(this, 20);
titleBar.setPadding(pad, 0, pad, 0);
titleBar.setText("Play on");
column.addView(titleBar, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
list = new ListView(this);
list.setDivider(new ColorDrawable(Ui.BLACK));
list.setDividerHeight(Ui.dp(this, 1));
list.setBackgroundColor(Ui.WHITE);
adapter = new Rows();
list.setAdapter(adapter);
list.setOnItemClickListener((parent, view, i, id) -> onRow(i));
wheel = new WheelScroll(list);
column.addView(list, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
setScreen(column, false);
discovery = new Speakers(this, this);
speakers.addAll(listed());
}
/** {@code speakers.txt}: the speakers named by address. */
private static ArrayList<Speakers.Speaker> listed() {
ArrayList<Speakers.Speaker> out = new ArrayList<>();
java.io.File f = new java.io.File(Library.root(), "speakers.txt");
if (!f.isFile()) return out;
try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.FileReader(f))) {
String line;
while ((line = r.readLine()) != null) {
String[] p = line.trim().split("\\s+", 4);
if (p.length < 2 || p[0].startsWith("#")) continue;
boolean cast = p[0].equalsIgnoreCase("cast");
if (!cast && !p[0].equalsIgnoreCase("airplay")) continue;
int port = cast ? 8009 : 7000;
if (p.length > 2) {
try { port = Integer.parseInt(p[2]); } catch (NumberFormatException ignored) { }
}
String name = p.length > 3 ? p[3] : p[1];
out.add(new Speakers.Speaker(cast ? Speakers.CAST : Speakers.AIRPLAY,
"direct/" + p[1] + ":" + port, name, p[1], port,
new HashMap<>(), ""));
}
} catch (java.io.IOException ignored) { }
return out;
}
@Override protected void onResume() {
super.onResume();
discovery.start();
}
@Override protected void onPause() {
discovery.stop();
super.onPause();
}
@Override protected void onDestroy() {
wheel.stop();
super.onDestroy();
}
@Override protected void onWheel(int dir) { wheel.push(dir); }
@Override public void onSpeakers(ArrayList<Speakers.Speaker> found) {
ArrayList<Speakers.Speaker> direct = new ArrayList<>();
for (Speakers.Speaker s : speakers) if (s.id.startsWith("direct/")) direct.add(s);
speakers.clear();
speakers.addAll(direct);
speakers.addAll(found);
adapter.notifyDataSetChanged();
}
@Override public void onPlaybackChanged() {
super.onPlaybackChanged();
if (adapter != null) adapter.notifyDataSetChanged();
}
private static String playingOn() {
PlaybackService s = PlaybackService.get();
return s != null ? s.remoteName() : null;
}
private void onRow(int i) {
PlaybackService service = PlaybackService.get();
if (service == null) {
Ui.toast(this, "Play something first");
return;
}
if (i == 0) {
service.disconnectRemote();
finish();
return;
}
Speakers.Speaker sp = speakers.get(i - 1);
if (!sp.note.isEmpty() || connecting != null) return;
if (sp.name.equals(playingOn())) {
service.disconnectRemote();
finish();
return;
}
connecting = sp.id;
adapter.notifyDataSetChanged();
new Thread(() -> {
Remote remote;
String error = null;
if (Speakers.CAST.equals(sp.kind)) {
CastRemote r = new CastRemote(sp.name, sp.host, sp.port);
try { r.connect(); } catch (Exception e) { error = e.getMessage(); }
remote = r;
} else {
AirPlayRemote r = new AirPlayRemote(sp.name, sp.host, sp.port, sp.txt);
try { r.connect(); } catch (Exception e) { error = e.getMessage(); }
remote = r;
}
final String why = error;
main.post(() -> {
connecting = null;
adapter.notifyDataSetChanged();
if (why != null) {
Ui.toast(this, "Couldn't connect to " + sp.name
+ (why.isEmpty() ? "" : ": " + why));
return;
}
PlaybackService s = PlaybackService.get();
if (s == null || isFinishing()) { remote.close(); return; }
s.connectRemote(remote);
finish();
});
}, "andTunes-connect").start();
}
private final class Rows extends BaseAdapter {
@Override public int getCount() { return speakers.size() + 1; }
@Override public Object getItem(int i) { return i; }
@Override public long getItemId(int i) { return i; }
@Override public boolean isEnabled(int i) {
return i == 0 || speakers.get(i - 1).note.isEmpty();
}
@Override public boolean areAllItemsEnabled() { return false; }
@Override public View getView(int i, View convert, ViewGroup parent) {
LinearLayout line;
TextView title, sub;
if (convert == null) {
line = new LinearLayout(SpeakersActivity.this);
line.setOrientation(LinearLayout.VERTICAL);
line.setGravity(Gravity.CENTER_VERTICAL);
int pad = Ui.dp(SpeakersActivity.this, 20);
line.setPadding(pad, Ui.dp(SpeakersActivity.this, 8), pad,
Ui.dp(SpeakersActivity.this, 8));
line.setMinimumHeight(Ui.dp(SpeakersActivity.this, Ui.ROW_DP));
title = Ui.text(SpeakersActivity.this, Ui.TITLE_SP, false, Ui.BLACK);
sub = Ui.text(SpeakersActivity.this, Ui.SUB_SP, false, Ui.DIM);
line.addView(title);
LinearLayout.LayoutParams slp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
slp.topMargin = Ui.dp(SpeakersActivity.this, 4);
line.addView(sub, slp);
} else {
line = (LinearLayout) convert;
title = (TextView) line.getChildAt(0);
sub = (TextView) line.getChildAt(1);
}
String on = playingOn();
boolean current;
boolean usable = true;
if (i == 0) {
title.setText("This Rabbit");
sub.setText(on == null ? "In use" : "Its own speaker");
current = on == null;
} else {
Speakers.Speaker sp = speakers.get(i - 1);
title.setText(sp.name);
current = sp.name.equals(on);
usable = sp.note.isEmpty();
String state = sp.id.equals(connecting) ? "Connecting…"
: current ? "In use" : !usable ? sp.note : "";
sub.setText(sp.kindLabel() + (state.isEmpty() ? "" : " · " + state));
}
// The output in use is drawn inverted, as the playing song is.
line.setBackgroundColor(current ? Ui.BLACK : Ui.WHITE);
title.setTextColor(current ? Ui.WHITE : usable ? Ui.BLACK : Ui.DIM);
sub.setTextColor(current ? Ui.WHITE : Ui.DIM);
return line;
}
}
}
@@ -73,6 +73,16 @@ final class Ui {
t.setGravity(Gravity.CENTER);
}
/** The same pill around an icon: the icon turns white when it's on. */
static void toggleStyle(Context c, ImageView b, boolean on) {
GradientDrawable d = new GradientDrawable();
d.setCornerRadius(dp(c, 12));
d.setStroke(dp(c, 3), BLACK);
d.setColor(on ? BLACK : WHITE);
b.setBackground(d);
b.setColorFilter(on ? WHITE : BLACK, android.graphics.PorterDuff.Mode.SRC_IN);
}
static void toast(Context c, String msg) {
Toast.makeText(c.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
@@ -0,0 +1,84 @@
package me.teafry.andtunes;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
* A speaker's volume while the wheel turns it: a pill along the right edge,
* black from the bottom up to the level and white above, with a black border.
* Full is all black, silent all white. It shows only while the volume is being
* adjusted and goes away a moment after the wheel stops.
*/
final class VolumeBar extends View {
private static final long HIDE_AFTER_MS = 1200;
private final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint border = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RectF pill = new RectF();
private final Path clip = new Path();
private final Runnable hide = () -> setVisibility(GONE);
private float level;
private VolumeBar(Context c) {
super(c);
border.setStyle(Paint.Style.STROKE);
border.setStrokeWidth(Ui.dp(c, 3));
border.setColor(Ui.BLACK);
fill.setStyle(Paint.Style.FILL);
setVisibility(GONE);
}
/** Show {@code level} (0..1) over {@code a}, adding the bar to it if needed. */
static void show(Activity a, float level) {
ViewGroup content = a.findViewById(android.R.id.content);
if (content == null) return;
VolumeBar bar = null;
for (int i = 0; i < content.getChildCount(); i++) {
if (content.getChildAt(i) instanceof VolumeBar) bar = (VolumeBar) content.getChildAt(i);
}
if (bar == null) {
bar = new VolumeBar(a);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
Ui.dp(a, 36), Ui.dp(a, 400), Gravity.END | Gravity.CENTER_VERTICAL);
lp.rightMargin = Ui.dp(a, 16);
content.addView(bar, lp);
}
bar.update(level);
}
private void update(float l) {
level = Math.max(0f, Math.min(1f, l));
bringToFront();
setVisibility(VISIBLE);
invalidate();
removeCallbacks(hide);
postDelayed(hide, HIDE_AFTER_MS);
}
@Override protected void onDraw(Canvas canvas) {
float inset = border.getStrokeWidth() / 2f;
pill.set(inset, inset, getWidth() - inset, getHeight() - inset);
float r = pill.width() / 2f;
clip.reset();
clip.addRoundRect(pill, r, r, Path.Direction.CW);
canvas.save();
canvas.clipPath(clip);
fill.setColor(Ui.WHITE);
canvas.drawRect(pill, fill);
float top = pill.bottom - pill.height() * level;
fill.setColor(Ui.BLACK);
canvas.drawRect(pill.left, top, pill.right, pill.bottom, fill);
canvas.restore();
canvas.drawRoundRect(pill, r, r, border);
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

+2 -2
View File
@@ -26,8 +26,8 @@ import sys
import zipfile
from pathlib import Path
VERSION_NAME = "0.3.0"
VERSION_CODE = 6
VERSION_NAME = "0.4.2"
VERSION_CODE = 9
PACKAGE = "me.teafry.andtunes"
MIN_SDK = 26
+72 -11
View File
@@ -42,6 +42,9 @@ MENU = {
}
ICON = 128
TRANSPORT = ("prev", "play", "pause", "next")
# Now Playing's bottom row: icons inside the toggle pills (drawn black; the
# app tints them white when the pill is on).
TOGGLES = ("shuffle", "repeat", "repeat_one", "speakers")
def _canvas(w, h):
@@ -97,17 +100,73 @@ def transport(name: str, color="black", size=ICON) -> QImage:
return image
def launcher() -> QImage:
size = 192
def toggle_icon(name: str, color="black", size=ICON) -> QImage:
from PyQt6.QtGui import QPen
image, p = _canvas(size, size)
path = QPainterPath()
path.addRoundedRect(QRectF(8, 8, size - 16, size - 16), 36, 36)
p.fillPath(path, QColor("black"))
s = size / 128
pen = QPen(QColor(color), 10 * s)
pen.setCapStyle(Qt.PenCapStyle.FlatCap)
pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
def head(x, y, right=True):
# a solid arrowhead whose point is at (x, y)
d = 1 if right else -1
p.save()
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor("white"))
p.drawPolygon(_tri(70, 50, 142, 96))
p.drawPolygon(QPolygonF([QPointF(70, 96), QPointF(142, 96),
QPointF(70, 142)]))
p.setBrush(QColor(color))
p.drawPolygon(QPolygonF([QPointF(x, y), QPointF(x - d * 22 * s, y - 16 * s),
QPointF(x - d * 22 * s, y + 16 * s)]))
p.restore()
if name == "shuffle":
# two strands that cross, each ending in an arrow on the right
a = QPainterPath(QPointF(14 * s, 38 * s))
a.cubicTo(QPointF(60 * s, 38 * s), QPointF(60 * s, 90 * s),
QPointF(96 * s, 90 * s))
b = QPainterPath(QPointF(14 * s, 90 * s))
b.cubicTo(QPointF(60 * s, 90 * s), QPointF(60 * s, 38 * s),
QPointF(96 * s, 38 * s))
p.drawPath(a)
p.drawPath(b)
head(116 * s, 38 * s)
head(116 * s, 90 * s)
elif name in ("repeat", "repeat_one"):
# a loop: top run left to right, bottom run back, rounded ends
loop = QPainterPath(QPointF(30 * s, 64 * s))
loop.lineTo(30 * s, 52 * s)
loop.arcTo(QRectF(30 * s, 32 * s, 40 * s, 40 * s), 180, -90)
loop.lineTo(92 * s, 32 * s)
p.drawPath(loop)
head(114 * s, 32 * s)
back = QPainterPath(QPointF(98 * s, 64 * s))
back.lineTo(98 * s, 76 * s)
back.arcTo(QRectF(58 * s, 56 * s, 40 * s, 40 * s), 0, -90)
back.lineTo(36 * s, 96 * s)
p.drawPath(back)
head(14 * s, 96 * s, right=False)
if name == "repeat_one":
font = QFont("DejaVu Sans")
font.setPixelSize(int(34 * s))
font.setBold(True)
p.setFont(font)
p.setPen(QColor(color))
p.drawText(QRectF(44 * s, 40 * s, 40 * s, 48 * s),
int(Qt.AlignmentFlag.AlignCenter), "1")
elif name == "speakers":
# broadcast: a dot with two arcs either side, (( • ))
p.save()
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(color))
p.drawEllipse(QPointF(64 * s, 64 * s), 11 * s, 11 * s)
p.restore()
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
for r in (30, 52):
box = QRectF((64 - r) * s, (64 - r) * s, 2 * r * s, 2 * r * s)
p.drawArc(box, -45 * 16, 90 * 16)
p.drawArc(box, 135 * 16, 90 * 16)
p.end()
return image
@@ -125,10 +184,12 @@ def main():
save(tile(label), name, RES, SHIP)
for name in TRANSPORT:
save(transport(name), name, RES, SHIP)
save(launcher(), "ic_launcher", RES)
for name in TOGGLES:
save(toggle_icon(name), name, RES, SHIP)
# The launcher icon is LinTunes' own: scripts/make_icons.py.
# Status-bar icons must be white-on-transparent; Android tints by alpha.
save(transport("play", "white", 96), "ic_notify", RES)
print(f"wrote {len(MENU) + len(TRANSPORT)} buttons to {RES} and {SHIP}")
print(f"wrote {len(MENU) + len(TRANSPORT) + len(TOGGLES)} buttons to {RES} and {SHIP}")
if __name__ == "__main__":
+2 -2
View File
@@ -90,8 +90,8 @@ your computer yet). Instead, every artist, album and song has a little
| Button | What it means |
|---|---|
| <img src="docs/cassette/cassette-off.png" width="28" alt="cassette button, not pressed"> | Not asked for. Click it to ask your friend for this. |
| <img src="docs/cassette/cassette-on.png" width="28" alt="cassette button, pressed"> | Asked for — this song is on its way to you. Click again to change your mind. |
| <img src="docs/cassette/cassette-partial.png" width="28" alt="cassette button, partly pressed"> | Some of this artist's or album's songs are asked for. Click to ask for all of them. |
| <img src="docs/cassette/cassette-on.png" width="28" alt="cassette button, pressed, with a blue down-arrow"> | Asked for — the blue arrow means this song is waiting to download to you. Click again to change your mind. |
| <img src="docs/cassette/cassette-partial.png" width="28" alt="cassette button, pressed, with a pale blue down-arrow"> | Some of this artist's or album's songs are asked for. Click to ask for all of them. |
Pressing the button on an **artist** or **album** asks for every song under it.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

After

Width:  |  Height:  |  Size: 158 KiB

+209
View File
@@ -0,0 +1,209 @@
# Releasing the Mac app
Notes for trav. The repo still lives on the Gitea/Forgejo host
(`origin`). GitHub gets a **read-only push mirror** of it, and GitHub
Actions' macOS runners build the two `.dmg` files and attach them to a
GitHub Release. Nothing about the Linux workflow changes: Linux machines
keep updating with `git pull` from `origin`.
```
your push ──> origin (Gitea/Forgejo) ──push mirror──> GitHub
└─ tag vX.Y.Z → .github/workflows/mac.yml
→ Release vX.Y.Z: two .dmg + SHA256SUMS
```
## One-time setup
### 1. Public or private?
Make the GitHub repo **public**, for three reasons:
- **Downloads.** Mac users download from the Releases page. A private
repo's releases are invisible to anyone you haven't invited, and the
app's update check asks GitHub's API without logging in, so it can't see
them either.
- **Cost.** Standard GitHub-hosted runners are **free on public repos**. On
a private repo, GitHub Free includes **$12 a month** of Actions usage.
macOS runners cost **$0.062 a minute** (Linux is $0.006, so a Mac minute
costs about ten Linux minutes). $12 buys about **190 macOS minutes** a
month. One release runs tests and a build on two Macs, roughly 60–80
minutes in all, so a private repo covers two or three releases a month.
(Prices are from GitHub's billing docs, November 2026.)
- **License.** The .dmg bundles PyQt6, which is GPL-3.0, so LinTunes as
shipped is a GPL combination. Before the first public .dmg, add a
`LICENSE` file (GPL-3.0-or-later fits) to the repo. See
`packaging/mac/THIRD-PARTY.md`.
A private repo still works for trying the pipeline out. Builds then show
up as workflow artifacts, which only you can download.
### 2. Create the GitHub repo
Create an **empty** repository: no README, no license, no .gitignore. The
mirror's first push fills it. Its `owner/name` is what goes into
`GITHUB_REPO` in step 5.
### 3. A token for the mirror
On GitHub, go to Settings › Developer settings › **Fine-grained personal
access tokens** › Generate new token:
- **Repository access:** only the new repo.
- **Permissions:** **Contents: Read and write**, and **Workflows: Read
and write**. GitHub refuses any push that changes a file under
`.github/workflows/` from a token without the Workflows permission.
Metadata: Read is added for you.
- **Expiration:** as long as you're comfortable with. When the token
expires, the mirror stops, so put the date in your calendar.
(A classic token works too, with the `repo` and `workflow` scopes.)
### 4. The push mirror on Gitea/Forgejo
In the repo on the Gitea/Forgejo host, open **Settings › Repository ›
Mirror settings** and add a **push mirror**:
- **Git remote repository URL:** `https://github.com/<owner>/<name>.git`
- **Username:** your GitHub username. **Password:** the token.
- Tick **Sync when commits are pushed**, and leave a periodic interval as
well (say 8h) as a backstop.
- Click **Synchronize now** once, and check that the code shows up on
GitHub.
Two things to know about push mirrors:
- **The mirror force-pushes and prunes.** Anything that exists only on
GitHub is deleted on the next sync: commits, branches **and tags**. Never
edit, commit, tag or merge pull requests on GitHub. In particular,
never let GitHub create a tag (the "create a new tag on publish" box in
the Releases UI, or a workflow that tags). The next sync removes that
tag, and the release on it turns back into a draft. This is why tags
are made where the code lives (below).
- If the Gitea/Forgejo host runs Actions of its own, it may pick up
`.github/workflows/mac.yml` too, and those jobs then sit queued forever
waiting for a macOS runner. If that happens, turn Actions off for this
repo there (Settings › Repository › untick Actions).
### 5. Name the repo in the app
In `lintunes/release_info.py`, set:
```python
GITHUB_REPO = "<owner>/<name>"
```
While this is empty, the Mac app never checks for updates. Commit and
release as usual. Every Mac build made after that checks.
## Making a release
Releasing is **bump, commit, tag, push**. The tag is the only new step:
```sh
# __version__ in lintunes/__init__.py is already bumped and committed
v="v$(python3 setup.py --version 2>/dev/null | tail -1)"
git tag -a "$v" -m "LinTunes $v"
git push origin master --follow-tags
```
Run `git config push.followTags true` once, and a plain `git push` takes
annotated tags along from then on. That keeps the existing habit (each
round ends with a commit and a push), and the round's final step only
gains the `git tag -a`.
The mirror carries the tag to GitHub, and the tag starts **macOS**
(`.github/workflows/mac.yml`). The workflow:
1. runs the test suite on both kinds of Mac (reported, not blocking, until
the Linux-only tests are marked);
2. builds both apps with `packaging/mac/build.sh`. It refuses to build if
the tag and `__version__` disagree;
3. starts each app against a throwaway library (`smoke_test.sh`), and
checks the disk image mounts and verifies;
4. creates the GitHub Release `vX.Y.Z` with
`LinTunes-X.Y.Z-AppleSilicon.dmg`, `LinTunes-X.Y.Z-Intel.dmg` and
`SHA256SUMS`.
It takes around half an hour. Mac apps that are running see the new
release at their next check (a few hours at most) and show the `*`.
Not every version has to be a Mac release. An untagged version simply
never gets a .dmg. To rebuild a release (say, after a failed run), go to
**Actions › macOS › Run workflow** and pick the tag as the ref. The files
on the existing release are replaced.
A push to master that touches `packaging/mac/` or the workflow builds
without publishing, so packaging changes get tested. A plain push to
master doesn't build at all, which keeps macOS minutes for releases.
**Why not tag automatically when `__version__` changes?** A workflow on
GitHub could do that, but the tag would exist only on GitHub, and the next
mirror sync would delete it (see above). Tagging at the source is the only
version that survives the mirror.
## Turning on Developer ID signing (later)
Unsigned builds make every Mac user go through **Open Anyway** once. To
stop that:
1. Join the Apple Developer Program ($99 a year).
2. In Xcode or on developer.apple.com, create a **Developer ID
Application** certificate, and export it with its private key as a
`.p12` with a password.
3. Create an **app-specific password** for your Apple ID at
account.apple.com › Sign-In and Security.
4. On GitHub, add these under Settings › Secrets and variables › Actions:
| Secret | Value |
|---|---|
| `MACOS_CERTIFICATE` | `base64 -i DeveloperID.p12` (the whole output) |
| `MACOS_CERTIFICATE_PASSWORD` | the .p12's password |
| `MACOS_SIGNING_IDENTITY` | `Developer ID Application: Your Name (TEAMID)` |
| `MACOS_NOTARY_APPLE_ID` | your Apple ID email |
| `MACOS_NOTARY_TEAM_ID` | the 10-character team ID |
| `MACOS_NOTARY_PASSWORD` | the app-specific password |
The next tagged build signs every binary inside out, with the hardened
runtime and `packaging/mac/entitlements.plist`. It then signs the .dmg,
notarizes it with `notarytool`, and staples the ticket. Without the
secrets, `build.sh` says "Developer ID signing skipped" and signs ad hoc,
as it does today. Once a signed build is confirmed, take the "Open
Anyway" section out of `docs/mac.md`. Also try removing
`disable-library-validation` from the entitlements.
The signing path has never been run. Expect the first signed build to
need fixes.
## Building on a Mac by hand
On any Mac with Python 3.11 or later for that Mac's architecture, plus
Xcode's command line tools (`xcode-select --install`):
```sh
git clone <origin> lintunes && cd lintunes
PYTHON=python3.13 packaging/mac/build.sh
packaging/mac/smoke_test.sh build/mac/dist/LinTunes.app 20
open build/mac/LinTunes-*.dmg
```
Everything goes in `build/mac/`: the venv, the downloaded tools, the
app, and the .dmg with its `.sha256`. A Mac builds only for itself: an
Apple Silicon Mac makes the AppleSilicon dmg, and an Intel Mac makes the
Intel one.
## Updating what's bundled
- **ffmpeg / fpcalc**: `packaging/mac/tools.json` pins each download's URL
and SHA-256. To bump one, download the new file, run
`shasum -a 256` on it yourself, compare the result with the publisher's
checksum, then change the URL and hash together. Also update the
versions in `THIRD-PARTY.md`. The ffmpeg builds' publisher stops making
**Intel** release builds from January 2027. Keep the pinned 9.0.2 for
Intel until a replacement is chosen.
- **PyInstaller**: pinned at the top of `build.sh`.
- **Python**: `PYTHON_VERSION` in the workflow.
- **Minimum macOS**: `MINIMUM_MACOS` in `packaging/mac/plist.py`. It
follows PyQt6's macOS wheel tag (14.0 for PyQt6 6.12).
- **The icon**: `python3 scripts/make_icons.py --only mac` rewrites
`packaging/mac/LinTunes.icns` from `packaging/lint.jpg`. Commit the
result.
+270
View File
@@ -0,0 +1,270 @@
# Mac test checklist
This is for a person with a real Mac, testing a LinTunes build from start
to finish. Use **test music only**: a few albums you don't mind being
retagged, moved or trashed. Don't point LinTunes at a music collection
you'd miss.
Mark every line **✓** (works), **✗** (broken, and say what happened), or
**–** (skipped, and say why). A screenshot helps whenever something looks
wrong (⇧⌘4 selects an area). Send back the whole file.
| | |
|---|---|
| Tester | |
| Date | |
| LinTunes version (bottom-left corner) | |
| Download (AppleSilicon / Intel .dmg) | |
| Mac model, chip | |
| macOS version | |
| Speakers / Chromecast / AirPlay devices available | |
To see the app's log, quit LinTunes and start it from Terminal instead:
`/Applications/LinTunes.app/Contents/MacOS/LinTunes`. Copy whatever it
prints around a failure into the notes.
---
## 1. Download and install
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 1.1 | Download the .dmg for this Mac, and `SHA256SUMS` | | |
| 1.2 | `shasum -a 256 -c SHA256SUMS --ignore-missing` in Downloads | `…dmg: OK` | |
| 1.3 | Open the .dmg | A window with LinTunes and an Applications shortcut | |
| 1.4 | Drag LinTunes to Applications, then eject | Copies, no errors | |
| 1.5 | Double-click LinTunes in Applications | macOS refuses: *"LinTunes" Not Opened*. Note the exact wording. | |
| 1.6 | System Settings › Privacy & Security › Security › **Open Anyway**, then your password | LinTunes opens | |
| 1.7 | Quit, and open it again from Launchpad/Spotlight | Opens with no warning | |
| 1.8 | Get Info on the app in Finder | Version matches, the lint-ball icon, size noted: ____ MB | |
| 1.9 | The Dock icon and the ⌘-Tab icon | The lint-ball icon, not a generic Python one | |
| 1.10 | The app menu (left of File) | Says **LinTunes**, not "Python" | |
## 2. First run and library setup
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 2.1 | First launch | The window appears. A library is created in `~/Music/LinTunes`. You're asked where the music should go. | |
| 2.2 | Choose a music folder | Accepted. Nothing is copied yet. | |
| 2.3 | Look in `~/Library/Application Support/LinTunes` | `config.json` exists | |
| 2.4 | Quit and relaunch | Same library, no questions this time | |
| 2.5 | Window: resize, minimize, full screen (green button), zoom | Behaves like a Mac window. Corners and title bar look right in light and dark. | |
| 2.6 | System Settings › Appearance › Dark, then Light | LinTunes follows, or keeps its own theme setting. Note which. | |
| 2.7 | Menu bar: File, Edit, Controls, View, Track, Connections | Present. **Preferences…/Settings…** is in the LinTunes menu (⌘,). **Quit LinTunes** is there too (⌘Q). | |
| 2.8 | Keyboard shortcuts use ⌘ (⌘O, ⌘I, ⌘Z, ⌘B, ⌘L, ⌘N) | Each one works | |
| 2.9 | Connections menu | No Rabbit / andTunes / Shazam entries | |
## 3. Importing
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 3.1 | Drag a folder of songs into the window | Copied into the music folder, filed as Artist/Album | |
| 3.2 | File › Add Files to Library… (⌘O) | The file picker opens, and the files are added | |
| 3.3 | Drop an audio file on LinTunes' **Dock icon** while it's running | Imported | |
| 3.4 | Right-click an mp3 in Finder › Open With › LinTunes | Imported (LinTunes may need to be running) | |
| 3.5 | Drag a song onto a playlist in the sidebar | Added at the drop point | |
| 3.6 | Importing an iTunes/Music library: `LinTunes --import-xml "Library.xml" --music-root … --data-dir …` from Terminal (optional) | Imports | |
| 3.7 | Preferences › Importing › compress lossless to MP3, then import a FLAC | Converted to MP3 | |
## 4. Playback, one format at a time
Play each one for a few seconds, seek in the middle, and let one play to
the end.
| # | Format | Plays | Seeks | Duration right | Notes |
|---|---|---|---|---|---|
| 4.1 | MP3 | | | | |
| 4.2 | AAC (.m4a) | | | | |
| 4.3 | Apple Lossless (.m4a) | | | | |
| 4.4 | FLAC | | | | |
| 4.5 | WAV | | | | |
| 4.6 | AIFF | | | | |
| 4.7 | A protected iTunes .m4p (if you have one) | Refused with a message, never a crash | | | |
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 4.8 | Space, ←/→ | Play/pause, previous/next | |
| 4.9 | Volume slider; per-track volume (Get Info) | Changes the volume | |
| 4.10 | Controls › Normalize Volume on, then play two very different songs | The loudness evens out. No error about ffmpeg. | |
| 4.11 | Shuffle and repeat (off/all/one) | As on Linux | |
| 4.12 | Change the output in System Settings › Sound (e.g. headphones) while playing | Audio follows, or note what happens | |
| 4.13 | Play counts go up after a song finishes | | |
## 5. Media keys and Now Playing
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 5.1 | Keyboard ⏯ ⏮ ⏭ keys (F7–F9) with LinTunes in the background | Control LinTunes, not Music.app | |
| 5.2 | Control Center › Now Playing | Shows title, artist, artwork and position | |
| 5.3 | Play/pause/next from Control Center | Works | |
| 5.4 | Seek using the Now Playing scrubber | Works | |
| 5.5 | AirPods/headphone controls (if any) | Work | |
| 5.6 | Lock screen Now Playing | Shows the song | |
## 6. Trash and Put Back
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 6.1 | Delete a song from the library (and its file) | Gone from the list. The file is in the **Trash**. | |
| 6.2 | In the Trash, right-click the file › **Put Back** | Returns to its folder | |
| 6.3 | Delete a song whose file is on an external drive | Goes to the Trash (that drive's), and Put Back works | |
| 6.4 | ⌘Z after a delete | The song comes back into the library | |
## 7. Get Info and tags
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 7.1 | ⌘I on a song, change title/artist/album/year, OK | Saved. Check the file in Finder's Get Info or another player. | |
| 7.2 | Rename an album | The file moves to the new Artist/Album folder | |
| 7.3 | Edit several songs at once | All changed | |
| 7.4 | Paste artwork (copy an image in Preview, paste in Get Info) | Embedded, shown in the sidebar | |
| 7.5 | Drag an image file onto the artwork square | Embedded | |
| 7.6 | Download Album Art… | Finds covers | |
| 7.7 | Edit the tags of the song that's **playing** | Playback doesn't glitch | |
| 7.8 | Right-click › Calculate BPM | A BPM appears | |
## 8. Visualizers
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 8.1 | The transport-bar visualizer during playback | Moves with the music | |
| 8.2 | Each style: bars, radial, oscilloscope, Kaleidostrobe, Lint Oontz | Each draws | |
| 8.3 | Click the visualizer for the **big window**, especially Kaleidostrobe (the OpenGL one) | Smooth, no black window. Note the fps feel. | |
| 8.4 | Big window on a Retina display | Sharp, not blurry or quarter-sized | |
| 8.5 | Preferences › visualizer sync slider | Changes the lag | |
## 9. Chromecast and AirPlay
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 9.1 | Connections › Connect to Chromecast… | macOS asks to **find devices on local networks**. Note the exact text. | |
| 9.2 | Allow | Your Chromecasts appear | |
| 9.3 | Cast a song | Plays on the TV/speaker. A firewall prompt about incoming connections may appear: allow it. | |
| 9.4 | Pause/seek/next while casting | Works | |
| 9.5 | Connections › Connect to AirPlay… | AirPlay speakers listed (Apple TV, HomePod, AirPlay speakers) | |
| 9.6 | Play to an AirPlay speaker | Sound comes out, within about 2 s | |
| 9.7 | If you denied the network prompt: System Settings › Privacy & Security › Local Network › LinTunes on | Devices appear after that | |
## 10. Import from URL
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 10.1 | Without yt-dlp: File › Import from URL… | A clear message saying yt-dlp is needed (`brew install yt-dlp`) | |
| 10.2 | `brew install yt-dlp`, restart LinTunes, then import a song link | Downloads, imports, and Identify proposes tags | |
| 10.3 | A playlist link | The checklist of songs appears | |
| 10.4 | A Spotify link | Each song is found on YouTube | |
## 11. Identify Track
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 11.1 | Preferences: set an AcoustID key, then right-click a song › Identify Track… | Candidates appear. No "fpcalc not found". | |
| 11.2 | Accept a candidate | Tags written | |
## 12. Export and web mix
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 12.1 | File › Export Playlist… › folder | Files and an .m3u | |
| 12.2 | Export as a web mix, then open `index.html` in Safari | Plays; previous/next/shuffle work | |
| 12.3 | A playlist with an ALAC song, as a web mix | Converted to FLAC | |
| 12.4 | Upload to web server (only if you have one in `~/.ssh/config`) | Uploads | |
| 12.5 | Right-click › Convert to MP3… on a FLAC | Replaced by an MP3, and the original goes to the Trash | |
## 13. DJ mode
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 13.1 | View › DJ Mode | The shelf slides open | |
| 13.2 | Drag a song onto each record | Loads, shows BPM, waveforms | |
| 13.3 | Play both, crossfader, tempo, Keep pitch, Sync, loops | Sound is clean (no crackles). Note any. | |
| 13.4 | Scratch a record; drag a waveform | Works | |
| 13.5 | Air horn, click and hold | Plays | |
| 13.6 | Preferences › DJ › set up **Instant** vocals (download) | Installs. Note how long, and any error. | |
| 13.7 | Vocals slider on a loaded song | Splits, then fades vocals | |
| 13.8 | Preferences › DJ › High quality (Demucs): follow the shown setup | Note what happens | |
| 13.9 | Close DJ mode with a song playing on deck A | The main player carries on | |
| 13.10 | Switch audio output while in DJ mode | Sound follows | |
## 14. Cassette (sharing with a friend)
Needs Syncthing (`brew install syncthing && brew services start syncthing`)
and a second person or computer.
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 14.1 | With Syncthing **not** running: open Cassette | A clear "Syncthing isn't running" message | |
| 14.2 | With Syncthing running: make this Mac the host, then create an invite | An invite code | |
| 14.3 | The friend accepts | Connected | |
| 14.4 | Browse the friend's library; request a song; Save and Close | The song arrives and is imported | |
| 14.5 | Follow a friend's playlist (the UFO) | Plays from the cache | |
| 14.6 | A sync conflict between two of your own computers (optional) | The merge summary shows | |
## 15. Sleep, quitting, updates
| # | Step | Expect | Result / notes |
|---|---|---|---|
| 15.1 | Play an album with the display set to sleep in 1–2 minutes | The **Mac** doesn't sleep while music plays (the display may). Check with `pmset -g assertions` in Terminal: a `caffeinate` assertion while playing. | |
| 15.2 | Pause for a while | The assertion goes away | |
| 15.3 | ⌘Q while playing | Quits at once, no "unexpectedly quit" report | |
| 15.4 | Close the window with the red button | Note: does it quit, or stay in the Dock like Music.app? | |
| 15.5 | Relaunch | Same library, playlists, play counts and column widths | |
| 15.6 | Version button in the bottom-left corner | `vX.Y.Z`. If a newer release exists, `*`, and a click opens the release page in your browser. | |
| 15.7 | Force-quit during an import (⌥⌘Esc), then relaunch | The library is intact | |
---
<!-- OTHER AGENTS' CHECKLISTS: the coordinator merges the OS-integration
and Cassette/DJ/AirPlay checklists here. Keep the table shape. -->
## 16. Additional checks (merged in)
### Desktop integration
- [ ] First launch from Finder with no settings: it starts, makes `~/Music/LinTunes`, and the app menu reads "LinTunes".
- [ ] Preferences (⌘,) and Quit (⌘Q) are in the LinTunes menu.
- [ ] Playing a song: Control Centre's Now Playing shows title, artist, album, cover and a moving progress bar; paused, the time stops.
- [ ] F8 pauses and resumes, F9 / F7 skip, the Now Playing scrubber seeks — also with another app in front.
- [ ] Embedding new art on the playing song updates the Now Playing cover.
- [ ] While playing, `pmset -g assertions` lists `caffeinate`; paused, it's gone. Force-quit while playing: `pgrep caffeinate` finds nothing.
- [ ] Right-click a song › Show in Finder selects the file.
- [ ] Delete a song (move to Trash): it's in the Trash and Put Back works; Edit › Undo brings it back into the library.
- [ ] The delete key (⌫) removes songs from a playlist; context menus show ⌘I / ⌘C / ⌫, never "Ctrl+".
- [ ] ⌘N, ⌘B, ⌘L, ⌘I, ⌘Z, ⌘⇧Z each fire once. Space and ← → play/pause and skip, but not while typing in the search box.
- [ ] Renaming an artist by capitals only ("Rjd2" → "RJD2") leaves the file where it is, with its own name.
- [ ] Connections has no Rabbit, Shazam or andTunes items; Preferences › Appearance has no "Hide the menu bar" row.
- [ ] The look is the Linux one (flat buttons, the app's own scrollbars), not native Mac controls.
- [ ] An mp3 dropped on the Dock icon is imported, with the app running and with it closed.
- [ ] Web-mix upload with only Apple's rsync says to `brew install rsync`; with Homebrew's it uploads.
- [ ] Import from URL after `brew install yt-dlp` downloads; on a YouTube bot check it retries with Firefox or Chrome cookies.
### Cassette
- [ ] With the Syncthing app running, Sync Settings shows its version (the key is read from `~/Library/Application Support/Syncthing/config.xml`). Same with Homebrew's `syncthing`.
- [ ] With Syncthing stopped, the status says how to open or get it.
- [ ] An invite and handshake between this Mac and a Linux friend completes. Syncthing accepts the folders under `~/Library/Application Support/LinTunes/cassette/` (the path has a space).
- [ ] Songs with accents in their names (é, ü) arrive and import, both ways.
- [ ] The disk-space verdict looks right; the host name shows without `.local`.
### DJ mode
- [ ] Decks play through speakers, headphones and AirPods; switching output while playing follows it.
- [ ] Activity Monitor: LinTunes' CPU with DJ mode open and nothing playing is low.
- [ ] Preferences › DJ › Download Instant Vocal Splitting finishes, and a split puts `.opus` files in `~/Library/Caches/LinTunes/stems`.
- [ ] Download High-Quality Vocal Splitting finishes; splitting an m4a and an mp3 works; the ✕ beside the vocals note stops it.
- [ ] A split is found again after editing the song's tags. BPM is detected on load.
### AirPlay and Chromecast
- [ ] The local-network prompt appears once; after Allow, speakers and Chromecasts are listed.
- [ ] AirPlay plays to a speaker of your own; pause, seek and next behave.
- [ ] With `"airplay_backend": "cli"` in config.json the helper downloads and plays. If macOS refuses to run it, note its exact words.
- [ ] Chromecast: the TV plays the song, seeking works, the cover shows. Note whether the firewall prompt blocked the first try.
---
## Anything else
Note anything that felt un-Mac-like, slow, ugly or confusing, even if it
"worked":
-
+142
View File
@@ -0,0 +1,142 @@
# LinTunes on a Mac
LinTunes started on Linux, and there is now a Mac version. You install it
the usual way, by dragging it to Applications. It needs **macOS 14 Sonoma
or later**.
## 1. Download the right one
Every release has two disk images:
| Your Mac | Download |
|---|---|
| Apple Silicon (M1, M2, M3, M4 and later) | `LinTunes-<version>-AppleSilicon.dmg` |
| Intel | `LinTunes-<version>-Intel.dmg` |
To find out which Mac you have, open the Apple menu › **About This
Mac**. If it says **Chip: Apple M…**, you have Apple Silicon. If it says
**Processor: … Intel …**, you have an Intel Mac.
Releases are on the project's GitHub **Releases** page. The newest one is
at the top.
## 2. (Optional) Check the download
Each release also has a file called `SHA256SUMS`. Download it to the same
folder as the .dmg, open Terminal, and run:
```sh
cd ~/Downloads
shasum -a 256 -c SHA256SUMS --ignore-missing
```
If the download is intact, you'll see `LinTunes-…dmg: OK`.
## 3. Install
1. Double-click the `.dmg`. A window opens with **LinTunes** and an
**Applications** folder.
2. Drag **LinTunes** onto **Applications**.
3. Eject the disk image (the ⏏ next to it in the Finder sidebar).
## 4. The first launch: "Open Anyway"
LinTunes isn't signed by Apple (that costs a yearly fee the project doesn't
pay yet), so macOS won't open it until you say so. You only have to do this
once:
1. Open **Applications** and double-click **LinTunes**. macOS says
*"LinTunes" Not Opened* (or *can't be opened*). Click **Done**. Don't
choose Move to Trash.
2. Open the Apple menu › **System Settings…** › **Privacy & Security**.
3. Scroll down to the **Security** section. It shows *"LinTunes" was
blocked to protect your Mac.* Click **Open Anyway**. (Some versions
label the button **Open**.) The button only appears for about an hour
after step 1. If it isn't there, do step 1 again.
4. Confirm with **Open Anyway**, then enter your login password.
From then on LinTunes opens like any other app.
On macOS 15 Sequoia and later, Control-click › **Open** **no longer** gets
you past this. Use System Settings as described above.
(If you're comfortable with Terminal, `xattr -dr com.apple.quarantine
/Applications/LinTunes.app` does the same thing.)
## 5. First run
When LinTunes opens for the first time, it creates a new library in
**~/Music/LinTunes** and asks where your music should go. To add songs,
drag them into the window, or use **File › Add Files to Library…** (⌘O). You can also
drop audio files onto LinTunes' Dock icon.
### "Allow LinTunes to find devices on local networks?"
The first time you open the Chromecast or AirPlay picker (the
**Connections** menu), macOS asks whether LinTunes may use your local
network. Click **Allow**. Without it LinTunes can't see your speakers.
If you said no, change it later under System Settings › **Privacy &
Security › Local Network**.
If your Mac's firewall is on, macOS may also ask whether LinTunes may
**accept incoming connections** when you cast. A Chromecast fetches the
song from LinTunes, so allow it.
## What's included, and what's optional
Included in the app, with nothing extra to install: playback (MP3, AAC/M4A,
Apple Lossless, FLAC, WAV, AIFF), the visualizers, DJ mode, Chromecast,
AirPlay, Identify Track, volume normalization, BPM detection, export, web
mixes, converting to MP3, Cassette, media keys and the Now Playing widget.
LinTunes ships with its own copies of `ffmpeg` and `fpcalc`.
Optional extras you install yourself (easiest with [Homebrew](https://brew.sh)):
- **Import from URL** (File menu) needs `yt-dlp`: `brew install yt-dlp`.
It isn't bundled, because YouTube changes often and yt-dlp has to keep
up. Run `brew upgrade yt-dlp` when downloads start failing.
- **Cassette** (sharing with friends) needs
[Syncthing](https://syncthing.net): `brew install syncthing`, then
`brew services start syncthing`. Syncthing is also how a library is kept
in step between computers.
- **DJ mode's vocal slider** needs Instant (Spleeter) or High quality
(Demucs). Set them up in Preferences › DJ, the same as on Linux.
- **Upload a web mix to your server** uses `ssh` and `rsync`, and macOS
already has both.
Not on the Mac: the **Rabbit R1** features (andTunes, Sync to Rabbit,
Import Shazams). They need the R1 plugged into a Linux machine.
## Where LinTunes keeps things
| What | Where |
|---|---|
| Your library (songs list, playlists, play counts, preferences) | `~/Music/LinTunes` unless you chose another folder |
| This Mac's settings (`config.json`), Cassette folders, the DJ vocal-splitter downloads | `~/Library/Application Support/LinTunes` |
| Things that can be rebuilt (loudness, vocal splits, album-art cache) | `~/Library/Caches/LinTunes` |
To remove LinTunes, drag it from Applications to the Trash. You can also
delete those two `~/Library` folders. Your library folder and your music
are never removed for you.
## Updates
LinTunes checks for a new release a little after it starts, and then every
few hours. When one is out, the version number in the bottom-left corner
gets a `*`. Click it and the release page opens in your browser. Download
the new `.dmg` and drag LinTunes to Applications again, replacing the old
one. Your library and settings are kept. If the new version is still
unsigned, macOS may ask for **Open Anyway** again.
The app never downloads or installs anything by itself.
## Something wrong?
[mac-testing.md](mac-testing.md) is the checklist a tester goes through.
When you report a problem, include the LinTunes version (bottom-left
corner), your macOS version, and Apple Silicon or Intel. To get the log,
start LinTunes from Terminal and send what it prints:
```sh
/Applications/LinTunes.app/Contents/MacOS/LinTunes
```
+3 -5
View File
@@ -106,12 +106,10 @@ dock icon, uses the synced library automatically.)
## App icon
_(written by LLM, cleaned up by me)_
You can change the app icon if you want.
`packaging/install-desktop.sh` installs the launcher entry and icon for your
user (lets you pin LinTunes to the GNOME dash). The icon is just a file —
replace `packaging/lintunes.png` (256×256 PNG) and re-run the script to use
your own. GNOME caches icons, so if the old one lingers, log out and back in.
user (lets you pin LinTunes to the GNOME dash). The icon is the same on the
desktop and the Rabbit; GNOME caches icons, so if an old one lingers after
re-running the script, log out and back in.
Unpinning from the dash does **not** uninstall LinTunes — it's still in the
GNOME app grid (open Activities and search "LinTunes"). Right-click it there →
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.44.1"
__version__ = "0.100.0"
+17
View File
@@ -0,0 +1,17 @@
"""AirPlay playback: discovery, the streaming session, and the Player sink.
The opposite model to Chromecast. A Chromecast fetches the original file over
HTTP and decodes it itself; an AirPlay speaker (RAOP) is *sent* PCM in real
time. So lintunes decodes every song with the ``ffmpeg`` CLI and pyatv
packetizes it. That makes every format the desktop plays castable here (ALAC
and AIFF included), at the cost of the stream being ours to keep running: a
suspended laptop is a silent speaker.
pyatv has neither pause nor seek for RAOP (its "pause" is stop), so both are
"tear the stream down and start a new one at that position" — ffmpeg's
``-ss`` makes the restart cheap.
Nothing here imports pyatv at module scope — like pychromecast, it is deferred
into the code that needs it, so lintunes still launches on a machine that has
pulled this round but not yet run ``pip install -e .``.
"""
+261
View File
@@ -0,0 +1,261 @@
"""cliairplay: Music Assistant's AirPlay sender, run as a helper process.
pyatv's own stream is accepted by a WiiM (Linkplay) speaker — every request
answered 200, timing exchanged, volume set — and nothing comes out, in AirPlay
1 and 2 alike (Round 88). cliairplay, the same speaker, plays. So it streams
for LinTunes wherever it runs, and pyatv stays for discovery (and as the
fallback where the helper can't be had).
The binary is never committed or pip-installed: it is downloaded once, from
the release pinned here, and checked against the release's SHA-256 before it
is ever run (the yt-dlp/fpcalc "runtime tool" rule, minus the package
manager, since no distribution ships it). GPL-3.0, and run as a separate
process — LinTunes only talks to it: audio as raw PCM on stdin, commands on a
named pipe, `[STATUS]` lines back on stderr.
Everything here is pure or plain file/network I/O, no Qt.
"""
import contextlib
import hashlib
import os
import platform
import re
import secrets
import tempfile
import urllib.request
from pathlib import Path
from lintunes import paths
VERSION = "0.5.4"
_RELEASE = ("https://github.com/music-assistant/airplay-cli/releases/download/"
f"v{VERSION}/")
# From the release's SHA256SUMS. Linux keys are the bare machine; the Mac
# builds (same release, same tag) are keyed by their asset suffix.
_SHA256 = {
"x86_64": "1ac56a15fb548f07a1dae94be16d4bea308420a0ec0cd04238023e44345fc1c9",
"aarch64": "1ce9160a8a9abb1b2263dfbf5ed59551dd1205b2336a024e9e33c903c201a310",
"macos-arm64": "5b99e3bf76d20cb31a2f6946e0c9d8bc12e0845d7d66a0ec22a49b5ebbac14b4",
"macos-x86_64": "09fd5925787db0cea530d380656b06fa6da89f0da11ef86e1cba1139b3c828fd",
}
_ARCH_ALIASES = {"amd64": "x86_64", "arm64": "aarch64"}
_MAC_ARCH_ALIASES = {"aarch64": "arm64", "amd64": "x86_64"}
DOWNLOAD_TIMEOUT_S = 60
class CliUnavailable(RuntimeError):
"""The helper can't be had here (platform, network, checksum)."""
def _arch() -> str | None:
"""The ``_SHA256`` key for this computer, or None."""
machine = platform.machine().lower()
if paths.IS_MAC:
# Under Rosetta this reads x86_64, and the x86_64 build runs there.
key = "macos-" + _MAC_ARCH_ALIASES.get(machine, machine)
return key if key in _SHA256 else None
if platform.system() != "Linux":
return None
machine = _ARCH_ALIASES.get(machine, machine)
return machine if machine in _SHA256 else None
def _asset(arch: str) -> str:
"""The release asset's file name for an ``_arch`` key."""
if arch.startswith("macos-"):
return f"cliairplay-{arch}"
return f"cliairplay-linux-{arch}"
def binary_dir() -> Path:
"""Machine-local: a binary for this CPU, never the synced data dir."""
return paths.data_dir() / "bin"
def binary_path() -> Path | None:
arch = _arch()
if arch is None:
return None
return binary_dir() / f"cliairplay-{VERSION}-{arch}"
def supported() -> bool:
return _arch() is not None
def installed() -> Path | None:
"""The verified binary, if it's already on disk."""
path = binary_path()
if path is not None and path.is_file() and os.access(path, os.X_OK):
return path
return None
def _sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def download_verified(url: str, sha256: str, path: Path, fetch=None,
what: str = "the helper", error=CliUnavailable,
unpack=None) -> Path:
"""Download ``url`` to ``path`` (mode 755), refusing it unless its
SHA-256 is ``sha256``. Nothing lands at ``path`` unless it matched.
``unpack(data) -> bytes`` (after the check) picks the binary out of an
archive. Raises ``error``. Shared by every pinned runtime download
(cliairplay here, ``uv`` in ``dj/venv_tool.py``)."""
fetch = fetch or _fetch
try:
data = fetch(url)
except Exception as e: # noqa: BLE001 — reported, not raised raw
raise error(f"couldn't download {what} ({e})")
if _sha256(data) != sha256:
raise error(f"the downloaded {what} failed its checksum")
if unpack is not None:
data = unpack(data)
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + "-")
try:
with os.fdopen(fd, "wb") as out:
out.write(data)
os.chmod(tmp, 0o755)
os.replace(tmp, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp)
raise
return path
def ensure_binary(fetch=None) -> Path:
"""The helper's path, downloading and verifying it first if needed.
Blocking (a few MB): callers run it off the GUI thread. `fetch(url)`
returns the bytes; it's injectable so tests never touch the network.
"""
path = installed()
if path is not None:
return path
arch = _arch()
if arch is None:
raise CliUnavailable(
f"no AirPlay helper for {platform.system()} {platform.machine()}")
return download_verified(_RELEASE + _asset(arch), _SHA256[arch],
binary_path(), fetch, "AirPlay helper")
def _fetch(url: str) -> bytes:
with urllib.request.urlopen(url, timeout=DOWNLOAD_TIMEOUT_S,
context=https_context()) as response:
return response.read()
def https_context():
"""None (urllib's default) on Linux. On a Mac, certifi's roots: the
Python inside a built LinTunes.app was compiled with an OpenSSL whose
certificate folder doesn't exist on the user's Mac, so the default
context trusts nothing and every HTTPS download fails."""
if not paths.IS_MAC:
return None
import ssl
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except Exception: # noqa: BLE001 — fall back to the system's default
return ssl.create_default_context()
# ---- the command line ----
# RAOP TXT keys the binary takes as their own flags (Music Assistant's set).
_RAOP_FLAGS = ("et", "md", "am", "pk", "pw", "cn")
def txt_blob(properties: dict) -> str:
"""The `_airplay._tcp` TXT as cliairplay's --txt: space-separated
key=value, skipping pairs with whitespace (the binary splits on spaces)."""
pairs = []
for key, value in (properties or {}).items():
if value is None:
continue
key, value = str(key), str(value)
if any(c.isspace() for c in key + value):
continue
pairs.append(f"{key}={value}")
return " ".join(pairs)
def protocol_arg(choice: str) -> str:
"""config.json's `airplay_protocol` → cliairplay's --protocol. "auto"
lets the binary pick from the TXT, as Music Assistant does."""
return {"1": "airplay2-compat", "2": "airplay2"}.get(choice, "auto")
def build_args(binary: str, host: str, port: int, raop: dict, airplay: dict,
pipe: str, volume: float, choice: str = "auto",
name: str = "") -> list[str]:
"""argv for one stream. `raop`/`airplay` are the TXT properties of the
device's _raop._tcp and _airplay._tcp services ({} when absent)."""
args = [binary, "--protocol", protocol_arg(choice),
"--dacp", secrets.token_hex(8).upper(),
"--activeremote", str(secrets.randbelow(2**32)),
"--cmdpipe", pipe,
"--samplerate", "44100", "--bitdepth", "16",
"--port", str(port),
"--volume", str(round(max(0.0, min(100.0, volume)))),
"--debug", "1"]
for key in _RAOP_FLAGS:
value = (raop or {}).get(key)
if value:
args += [f"--{key}", str(value)]
# Some receivers (the WiiM) advertise their AirPlay 2 feature bits only on
# _raop's `ft`; route selection reads them from --txt either way.
txt = dict(airplay or {})
if not (txt.get("features") or txt.get("ft")) and (raop or {}).get("ft"):
txt["ft"] = raop["ft"]
blob = txt_blob(txt)
if blob:
args += ["--txt", blob]
if name and airplay:
args += ["--name", name]
return args + [host]
# ---- what it says ----
_STATUS = re.compile(r"^\[STATUS\]\s+(\w+)\s*(.*)$")
_FIELD = re.compile(r'(\w+)=("([^"]*)"|\S+)')
def parse_status(line: str) -> tuple[str, dict] | None:
"""`[STATUS] playing elapsed_ms=1203` → ("playing", {"elapsed_ms": "1203"}).
Anything that isn't a status line is None."""
match = _STATUS.match(line.strip())
if match is None:
return None
fields = {}
for key, raw, quoted in _FIELD.findall(match.group(2)):
fields[key] = quoted if raw.startswith('"') else raw
return match.group(1), fields
def metadata_command(title: str, artist: str, album: str, duration_s: int,
artwork_file: str | None = None) -> str:
"""Now-playing for the receiver. Newlines would end a field early."""
def clean(value):
return " ".join(str(value or "").split())
lines = [f"TITLE={clean(title)}", f"ARTIST={clean(artist)}",
f"ALBUM={clean(album)}", f"DURATION={max(0, int(duration_s))}"]
if artwork_file:
lines.append(f"ARTWORKFILE={artwork_file}")
lines.append("ACTION=SENDMETA")
return "\n".join(lines) + "\n"
def start_command(at_unix_ms: int) -> str:
return f"START_UNIX_MS={int(at_unix_ms)}\nACTION=START\n"
def volume_command(percent: float) -> str:
return f"VOLUME={round(max(0.0, min(100.0, percent)))}\n"
+453
View File
@@ -0,0 +1,453 @@
"""The Player sink that plays through an AirPlay speaker via cliairplay.
Same contract as sink.AirPlaySink — one stream per stretch of playback, a
generation per stream so a replaced one can't advance the queue — but each
stream is two processes: ffmpeg decoding the song from the position (s16le
on its stdout) straight into cliairplay's stdin, and cliairplay talking to
the speaker. A daemon thread per stream owns both, writes the command pipe
and reads `[STATUS]` lines; what it learns comes back as Qt signals.
What the statuses mean (measured against shairport-sync, and the WiiM):
`connected` → send the now-playing and START; `started at_unix_ms=` is when
the first sample is *heard*, and `playing elapsed_ms=` (about once a second)
how far the listener is since then — so position needs no latency guess.
`eof` comes when the song has played out (stopping right then cut nothing),
and the binary then holds the session until told ACTION=STOP.
"""
import logging
import os
import shutil
import subprocess
import tempfile
import threading
import time
from PyQt6.QtCore import QTimer, pyqtSignal
from PyQt6.QtMultimedia import QAudio
from lintunes import tagging
from lintunes.airplay import cli
from lintunes.airplay.sink import (
DECODE_ERROR, DROPPED, FAILED, FINISHED, jpeg_artwork)
from lintunes.airplay.support import (
can_stream, ffmpeg_command, level_to_percent, unstreamable_reason)
from lintunes.player import PlaybackSink
log = logging.getLogger("lintunes.airplay")
CONNECT_TIMEOUT_S = 15.0
STOP_GRACE_S = 1.0
START_LEAD_MS = 300
def now_ms() -> int:
return int(time.time() * 1000)
class CliStream:
"""One song from one position, on its own thread. Never touches Qt:
`report(kind, fields)` and `ended(outcome, detail)` are called from the
thread and must be thread-safe (the sink passes signal emits)."""
def __init__(self, binary, target: dict, path: str, start_ms: int,
volume: float, metadata: str, report, ended, workdir: str):
self.binary = str(binary)
self.target = target
self.path = path
self.start_ms = start_ms
self.volume = volume
self.metadata = metadata
self._report = report
self._ended = ended
self._workdir = workdir
self._stop = threading.Event()
self._connected = threading.Event()
self._eof = threading.Event()
self._lock = threading.Lock()
self._pipe = None # the command pipe, once open
self._error = ""
self._last_line = ""
self.thread = threading.Thread(target=self._run, daemon=True,
name="airplay-stream")
def start(self):
self.thread.start()
def stop(self):
"""Ask the stream to end; returns at once (the thread tears down)."""
self._stop.set()
def send(self, command: str):
"""A command for the binary; dropped if the pipe isn't open yet."""
with self._lock:
if self._pipe is None:
return False
try:
os.write(self._pipe, command.encode())
return True
except OSError:
return False
# ---- the thread ----
def _run(self):
fifo = os.path.join(self._workdir, f"cmd-{id(self)}.pipe")
decoder = player = None
try:
os.mkfifo(fifo)
decoder = subprocess.Popen(
ffmpeg_command(self.path, self.start_ms, 44100, 2, 2,
big_endian=False),
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
t = self.target
player = subprocess.Popen(
cli.build_args(self.binary, t["host"], t["port"], t["raop"],
t["airplay"], fifo, self.volume,
t.get("choice", "auto"), t.get("name", "")),
stdin=decoder.stdout, stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE, text=True, errors="replace")
decoder.stdout.close() # the binary holds the only read end
reader = threading.Thread(target=self._read, args=(player,),
daemon=True)
reader.start()
outcome, detail = self._drive(player, decoder, fifo)
except Exception as e: # noqa: BLE001 — reported, never raised
outcome, detail = FAILED, str(e) or type(e).__name__
finally:
self._teardown(player, decoder, fifo)
self._ended(outcome, detail)
def _drive(self, player, decoder, fifo):
deadline = time.monotonic() + CONNECT_TIMEOUT_S
while not self._connected.wait(0.05):
if self._stop.is_set():
return None, ""
if player.poll() is not None:
return FAILED, self._error or self._last_line or "it closed"
if time.monotonic() > deadline:
return FAILED, "it didn't answer"
self._open_pipe(fifo, player)
if self.metadata:
self.send(self.metadata)
self.send(cli.start_command(now_ms() + START_LEAD_MS))
while not self._stop.is_set():
if self._eof.wait(0.1):
code = decoder.wait()
if code != 0 and not self._heard_any:
message = decoder.stderr.read().decode(
errors="replace").strip().splitlines()
return DECODE_ERROR, (message[-1] if message
else f"ffmpeg exited with {code}")
return FINISHED, ""
if player.poll() is not None:
return DROPPED, self._error or self._last_line
return None, ""
_heard_any = False
def _open_pipe(self, fifo, player):
"""The binary opens its end once connected; never block on it."""
while not self._stop.is_set() and player.poll() is None:
try:
fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)
except OSError:
time.sleep(0.02)
continue
os.set_blocking(fd, True)
with self._lock:
self._pipe = fd
return
def _read(self, player):
for line in player.stderr:
line = line.rstrip()
if not line:
continue
parsed = cli.parse_status(line)
if parsed is None:
if "rror" in line:
self._last_line = line
continue
kind, fields = parsed
if kind == "connected":
self._connected.set()
elif kind == "eof":
self._eof.set()
elif kind == "playing":
self._heard_any = True
elif kind == "error":
self._error = fields.get("detail") or fields.get("code", "")
if kind in ("started", "playing", "connected", "error"):
self._report(kind, fields)
def _teardown(self, player, decoder, fifo):
if player is not None and player.poll() is None:
self.send("ACTION=STOP\n")
try:
player.wait(STOP_GRACE_S)
except subprocess.TimeoutExpired:
player.terminate()
try:
player.wait(STOP_GRACE_S)
except subprocess.TimeoutExpired:
player.kill()
if decoder is not None and decoder.poll() is None:
decoder.kill()
with self._lock:
fd, self._pipe = self._pipe, None
if fd is not None:
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(fifo)
except OSError:
pass
class CliAirPlaySink(PlaybackSink):
"""Streams to an AirPlay receiver through cliairplay."""
provides_pcm = False
glyph = "airplay"
listen_src = "airplay"
POLL_MS = 250
VOLUME_COALESCE_MS = 120
STOP_TIMEOUT_S = 3.0
_status = pyqtSignal(int, str, object) # generation, kind, fields
_stream_ended = pyqtSignal(int, str, str) # generation, outcome, detail
stream_class = CliStream # tests swap in a fake
def __init__(self, binary, target: dict, name: str, parent=None):
super().__init__(parent)
self._binary = binary
self._target = dict(target, name=name)
self.name = name or "AirPlay"
self._workdir = tempfile.mkdtemp(prefix="lintunes-airplay-")
self._track = None
self._metadata = ""
self._stream: CliStream | None = None
self._generation = 0
self._playing = False
self._start_ms = 0
self._anchor_ms: int | None = None # unix ms when start_ms is heard
self._position_ms = 0
self._duration_ms = 0
self._percent = 0.0
self._first_logged = False
self._shutdown_done = False
self._dying = False
self._status.connect(self._on_status)
self._stream_ended.connect(self._on_stream_ended)
self._poll = QTimer(self)
self._poll.setInterval(self.POLL_MS)
self._poll.timeout.connect(self._on_poll)
self._volume_timer = QTimer(self)
self._volume_timer.setSingleShot(True)
self._volume_timer.setInterval(self.VOLUME_COALESCE_MS)
self._volume_timer.timeout.connect(self._flush_volume)
# ---- PlaybackSink ----
def can_play(self, track) -> bool:
return can_stream(track.location, track.kind)
def unplayable_reason(self, track) -> str:
return unstreamable_reason(track.location, track.kind)
def load(self, track, autoplay: bool, start_ms: int):
self._track = track
self._duration_ms = track.total_time or 0
self._metadata = cli.metadata_command(
track.name, track.artist, track.album, self._duration_ms // 1000,
self._artwork_file(track))
self.duration_changed.emit(self._duration_ms)
self._set_position(max(0, start_ms))
if autoplay:
self._start_stream(self._position_ms)
else:
self._halt_stream()
self._set_playing(False)
def _artwork_file(self, track) -> str | None:
try:
data = jpeg_artwork(tagging.read_embedded_artwork(track.location))
except Exception: # noqa: BLE001 — art is never worth a failure
return None
if not data:
return None
path = os.path.join(self._workdir, "cover.jpg")
try:
with open(path, "wb") as out:
out.write(data)
except OSError:
return None
return path
def play(self):
if self._track is None or self._playing:
return
self._start_stream(self._position_ms)
def pause(self):
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def stop(self):
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def seek(self, position_ms: int):
target = max(0, position_ms)
if self._playing:
self._start_stream(target)
else:
self._set_position(target)
def position_ms(self) -> int:
return self._position_ms
def duration_ms(self) -> int:
return self._duration_ms
def is_playing(self) -> bool:
return self._playing
def set_volume(self, level: float):
level = max(0.0, min(1.0, float(level)))
linear = QAudio.convertVolume(
level, QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
# cliairplay's 0–100 is pyatv's: linear across -30..0 dB.
self._percent = level_to_percent(linear)
self._volume_timer.start()
def shutdown(self):
if self._shutdown_done:
return
self._shutdown_done = True
self._poll.stop()
self._volume_timer.stop()
self._generation += 1
stream, self._stream = self._stream, None
if stream is not None:
stream.stop()
stream.thread.join(self.STOP_TIMEOUT_S)
shutil.rmtree(self._workdir, ignore_errors=True)
# ---- streams ----
def _start_stream(self, start_ms: int):
if self._shutdown_done or self._dying or self._track is None:
return
self._generation += 1
generation = self._generation
if self._stream is not None:
self._stream.stop()
log.info("stream %d: %s from %d ms (cliairplay)", generation,
self._track.name or self._track.location, start_ms)
self._start_ms = start_ms
self._anchor_ms = None
self._first_logged = False
self._stream = self.stream_class(
self._binary, self._target, self._track.location, start_ms,
self._percent, self._metadata,
lambda kind, fields: self._status.emit(generation, kind, fields),
lambda outcome, detail: self._stream_ended.emit(
generation, outcome or "", detail or ""),
self._workdir)
self._set_position(start_ms)
self._set_playing(True)
self._poll.start()
self._stream.start()
def _halt_stream(self):
self._generation += 1
self._poll.stop()
stream, self._stream = self._stream, None
if stream is not None:
stream.stop()
def _freeze_position(self):
if self._stream is not None:
self._set_position(self._heard())
def _heard(self) -> int:
if self._anchor_ms is None:
return self._start_ms
played = max(0, now_ms() - self._anchor_ms)
position = self._start_ms + played
if self._duration_ms:
position = min(position, self._duration_ms)
return position
def _on_status(self, generation: int, kind: str, fields: dict):
if generation != self._generation:
return
if kind == "started":
try:
self._anchor_ms = int(fields.get("at_unix_ms", 0)) or None
except ValueError:
self._anchor_ms = None
elif kind == "playing":
try:
self._anchor_ms = now_ms() - int(fields.get("elapsed_ms", 0))
except ValueError:
pass
if not self._first_logged:
self._first_logged = True
log.info("stream %d: playing", generation)
def _on_poll(self):
if self._stream is not None:
self._set_position(self._heard())
def _on_stream_ended(self, generation: int, outcome: str, detail: str):
if outcome:
log.info("stream %d ended: %s %s", generation, outcome, detail)
if (generation != self._generation or self._shutdown_done
or not outcome):
return
self._stream = None
self._poll.stop()
if outcome == FINISHED:
self._set_position(self._duration_ms or self._position_ms)
self._set_playing(False)
self.ended.emit()
elif outcome == DECODE_ERROR:
self._set_playing(False)
self.error.emit(f"it couldn't be decoded ({detail})")
elif outcome == DROPPED:
self._fail(f"{self.name} stopped playing — something else may "
"have taken it over.")
else:
self._fail(f"Lost {self.name} ({detail}).")
def _fail(self, reason: str):
if self._dying:
return
self._dying = True
self._poll.stop()
self.unavailable.emit(reason)
def _flush_volume(self):
if self._stream is not None:
self._stream.send(cli.volume_command(self._percent))
def _set_playing(self, playing: bool):
if playing != self._playing:
self._playing = playing
self.state_changed.emit(playing)
def _set_position(self, position_ms: int):
self._position_ms = position_ms
self.position_changed.emit(position_ms)
+242
View File
@@ -0,0 +1,242 @@
"""Owns an AirPlay session on MainWindow's behalf (CastController's shape).
Widget-free: it reports state as signals and MainWindow decides what to show.
"Connected" is mostly a promise here — RAOP holds no connection between
streams, so a speaker that vanishes while paused is only noticed when the
next stream can't reach it, and Player falls back then.
"""
import logging
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from lintunes.airplay.discovery import AirPlayDiscovery
from lintunes.airplay.loop import AsyncLoop
from lintunes.airplay.support import is_available, protocol_choice, use_compat
from lintunes.config import load_config
from lintunes.eventlog import log_control
from lintunes.inhibit import INHIBIT_LOGOUT, INHIBIT_SUSPEND, SleepInhibitor
CONNECT_TIMEOUT_S = 10.0
def raop_only(conf):
"""Connect over RAOP alone. The AirPlay service on a speaker is the video/
remote-control side; left enabled, pyatv may route volume through it
when no stream is running."""
from pyatv.const import Protocol
for service in conf.services:
if service.protocol != Protocol.RAOP:
service.enabled = False
return conf
class AirPlayController(QObject):
connecting = pyqtSignal(object) # AirPlayDevice
connected = pyqtSignal(str) # device name
disconnected = pyqtSignal(str) # reason; "" when the user asked
failed = pyqtSignal(str)
_connect_done = pyqtSignal(object, int) # {"atv"|"error"}, attempt
def __init__(self, player, parent=None):
super().__init__(parent)
self._player = player
self._loop = AsyncLoop()
self._sink = None
self._discovery: AirPlayDiscovery | None = None
self._attempt = 0
self._connect_done.connect(self._on_connect_result)
# This machine decodes every packet the speaker plays, so a suspend
# silences the room mid-song.
self._inhibitor = SleepInhibitor(
reason="Playing to an AirPlay speaker",
flags=INHIBIT_LOGOUT | INHIBIT_SUSPEND)
# ---- state ----
def is_available(self) -> tuple[bool, str]:
return is_available()
def is_connected(self) -> bool:
return self._sink is not None
def device_name(self) -> str:
return self._sink.name if self._sink is not None else ""
def discovery(self) -> AirPlayDiscovery:
if self._discovery is None:
self._discovery = AirPlayDiscovery(self._loop, self)
return self._discovery
# ---- connecting ----
def connect_to(self, device):
if self._sink is not None:
self.disconnect()
self._attempt += 1
attempt = self._attempt
self.connecting.emit(device)
log_control("airplay", "connect", f"{device.name} at {device.host}")
conf = self.discovery().config_for(device.uuid)
future = self._loop.submit(self._connect(conf, device))
def done(f):
try:
result = {"atv": f.result(), "name": device.name}
except Exception as e: # noqa: BLE001 — report, never crash
result = {"error": str(e) or type(e).__name__}
self._connect_done.emit(result, attempt)
future.add_done_callback(done)
async def _connect(self, conf, device):
import asyncio
import pyatv
from pyatv.const import Protocol
loop = asyncio.get_running_loop()
if conf is None:
# Not seen by this session's scans (or seen long ago): ask the
# address directly.
found = await pyatv.scan(loop, hosts=[device.host], timeout=5)
conf = next((c for c in found
if str(c.identifier) == device.uuid), None)
if conf is None:
raise ConnectionError(f"{device.name} didn't answer")
from pyatv.protocols.airplay.utils import get_protocol_version
from pyatv.settings import AirPlayVersion
from pyatv.storage.memory_storage import MemoryStorage
config = load_config()
choice = protocol_choice(config.get("airplay_protocol"))
if config.get("airplay_debug"):
# Every RTSP request and a line per second of audio, into the
# journal: what "connected but silent" needs to be diagnosed.
logging.getLogger("pyatv").setLevel(logging.DEBUG)
logging.getLogger("lintunes.airplay.raop").setLevel(logging.DEBUG)
storage = MemoryStorage()
settings = await storage.get_settings(conf)
raop = conf.get_service(Protocol.RAOP)
model = raop.properties.get("am", "") if raop is not None else ""
compat = use_compat(choice, model)
from lintunes.airplay.stream import install_shim
install_shim()
if compat and raop is not None:
backend = str(config.get("airplay_backend") or "auto").lower()
if backend != "cli":
try:
return await self._connect_native(conf, device, raop,
model, choice, config)
except (ConnectionError, OSError, asyncio.TimeoutError) as e:
native_error = str(e) or type(e).__name__
log_control("airplay", "native failed",
f"{device.name}: {native_error}")
if backend == "native":
raise
from lintunes.airplay import cli
if not cli.supported():
raise ConnectionError(
"LinTunes' AirPlay sender couldn't connect, and "
"cliairplay isn't available for this computer")
# Downloaded once, verified against its pinned SHA-256 before it
# ever runs (cli.ensure_binary); blocking, so off the loop.
binary = await loop.run_in_executor(None, cli.ensure_binary)
airplay = conf.get_service(Protocol.AirPlay)
log_control("airplay", "protocol",
f"{device.name} ({model}): cliairplay {cli.VERSION}")
return {"cli": binary, "target": {
"host": str(conf.address), "port": raop.port,
"raop": dict(raop.properties),
"airplay": dict(airplay.properties) if airplay else {},
"choice": "auto"}}
settings.protocols.raop.protocol_version = (
{"2": AirPlayVersion.V2}.get(choice, AirPlayVersion.Auto))
if raop is not None:
used = get_protocol_version(
raop, settings.protocols.raop.protocol_version)
log_control("airplay", "protocol",
f"{device.name} ({model}): pyatv {used.name} "
f"(airplay_protocol={choice})")
return await asyncio.wait_for(
pyatv.connect(raop_only(conf), loop, storage=storage),
CONNECT_TIMEOUT_S)
@staticmethod
async def _connect_native(conf, device, raop, model, choice, config):
"""LinTunes' own RAOP sender (raop.py): what third-party speakers
play. pyatv only found the device."""
import asyncio
from lintunes.airplay.raop import (
DEFAULT_LATENCY_MS, NativeDevice, RaopClient)
latency = config.get("airplay_latency_ms") or DEFAULT_LATENCY_MS
log_control("airplay", "protocol",
f"{device.name} ({model}): native RAOP, "
f"{latency} ms buffer (airplay_protocol={choice})")
native = NativeDevice(RaopClient(
str(conf.address), raop.port, dict(raop.properties),
latency_ms=int(latency)))
await asyncio.wait_for(native.connect(), CONNECT_TIMEOUT_S)
return native
def _on_connect_result(self, result: dict, attempt: int):
atv = result.get("atv")
via_cli = isinstance(atv, dict)
if attempt != self._attempt:
if atv is not None and not via_cli:
self._loop.submit(self._close(atv))
return
if "error" in result:
self.failed.emit(f"Couldn't connect: {result['error']}")
return
if via_cli:
from lintunes.airplay.cli_sink import CliAirPlaySink
self._sink = CliAirPlaySink(atv["cli"], atv["target"],
result["name"], self)
else:
from lintunes.airplay.sink import AirPlaySink
self._sink = AirPlaySink(atv, self._loop, result["name"], self)
# Deferred a turn, as in CastController: Player's own fallback slot
# disconnects this signal mid-emission.
self._sink.unavailable.connect(
lambda reason: QTimer.singleShot(
0, lambda: self._on_unavailable(reason)))
self._player.set_sink(self._sink)
self._inhibitor.inhibit()
self.connected.emit(self._sink.name)
@staticmethod
async def _close(atv):
import asyncio
await asyncio.gather(*atv.close(), return_exceptions=True)
# ---- disconnecting ----
def disconnect(self, reason: str = ""):
sink, self._sink = self._sink, None
if sink is None:
return
log_control("airplay", "disconnect",
f"{sink.name} reason={reason or 'user'}")
self._player.set_sink(None)
self._teardown(sink, reason)
def _on_unavailable(self, reason: str):
sink, self._sink = self._sink, None
if sink is None:
return
log_control("airplay", "lost", reason)
self._teardown(sink, reason)
def _teardown(self, sink, reason: str):
sink.shutdown()
self._inhibitor.release()
self.disconnected.emit(reason)
def shutdown(self):
"""Quitting: stop first so the swap back can't burst out of the
laptop's speakers (CastController.shutdown's rule)."""
if self._discovery is not None:
self._discovery.stop()
if self._sink is not None:
self._player.stop()
self.disconnect()
self._inhibitor.release()
+145
View File
@@ -0,0 +1,145 @@
"""Finding AirPlay speakers on the local network.
pyatv's `scan` is one-shot, so while the picker is open this repeats it and
reports differences — the same device_found / device_lost / failed shape as
CastDiscovery, which is what lets one picker dialog serve both. A device has
to miss two scans in a row to count as gone: one lost mDNS reply shouldn't
make a row blink out.
Every device with AirPlay is listed, including ones lintunes can't stream to
(a TV that wants a PIN, a video-only projector) — greyed, with the reason —
so "why isn't my speaker there?" has an answer on screen.
"""
import asyncio
import threading
from dataclasses import dataclass
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes.airplay.support import classify
SCAN_TIMEOUT_S = 3
SCAN_PAUSE_S = 2.0
MISSES_TO_LOSE = 2
@dataclass(frozen=True)
class AirPlayDevice:
uuid: str # pyatv's identifier (the device id for RAOP)
name: str
model: str
host: str
connectable: bool = True
note: str = "" # why it isn't connectable
def to_device(conf) -> AirPlayDevice:
"""Every pyatv config access in one place (discovery.py's _to_device
rule: a pyatv upgrade should be a fix here)."""
from pyatv.const import Protocol
raop = conf.get_service(Protocol.RAOP)
if raop is not None:
ok, note = classify(True, raop.pairing.name, raop.requires_password)
else:
ok, note = classify(False, "", False)
model = ""
info = getattr(conf, "device_info", None)
if info is not None:
model = getattr(info, "raw_model", "") or ""
if not model or model.startswith("Unknown"):
model = ""
if not model and raop is not None:
model = raop.properties.get("am", "") or ""
return AirPlayDevice(uuid=str(conf.identifier), name=conf.name or "AirPlay",
model=model, host=str(conf.address),
connectable=ok, note=note)
class AirPlayDiscovery(QObject):
"""Scans for AirPlay devices while running, reporting changes."""
device_found = pyqtSignal(object) # AirPlayDevice
device_lost = pyqtSignal(object) # AirPlayDevice
failed = pyqtSignal(str)
def __init__(self, loop, parent=None):
super().__init__(parent)
self._loop = loop
self._future = None
self._lock = threading.Lock()
self._devices: dict[str, AirPlayDevice] = {}
# pyatv configs by identifier, kept after stop(): the picker stops
# scanning as it closes, *before* the controller connects to the pick.
self._configs: dict[str, object] = {}
def is_running(self) -> bool:
return self._future is not None
def devices(self) -> list[AirPlayDevice]:
with self._lock:
return list(self._devices.values())
def config_for(self, uuid: str):
with self._lock:
return self._configs.get(uuid)
def start(self):
if self._future is not None:
return
try:
import pyatv # noqa: F401 — imported here, not at module scope
except ImportError as e:
self.failed.emit(f"AirPlay support isn't installed ({e}).")
return
self._future = self._loop.submit(self._scan_forever())
def stop(self):
"""Idempotent: safe from every dialog exit path."""
future, self._future = self._future, None
if future is not None:
future.cancel()
with self._lock:
self._devices.clear()
# ---- loop thread ----
async def _scan_forever(self):
import pyatv
from pyatv.const import Protocol
misses: dict[str, int] = {}
loop = asyncio.get_running_loop()
while True:
try:
confs = await pyatv.scan(
loop, timeout=SCAN_TIMEOUT_S,
protocol={Protocol.AirPlay, Protocol.RAOP})
except asyncio.CancelledError:
raise
except Exception as e: # noqa: BLE001 — report, never crash
self.failed.emit(f"Couldn't search for AirPlay devices: {e}")
return
seen = set()
for conf in confs:
device = to_device(conf)
seen.add(device.uuid)
misses.pop(device.uuid, None)
with self._lock:
known = self._devices.get(device.uuid)
self._devices[device.uuid] = device
self._configs[device.uuid] = conf
if known != device:
if known is not None:
self.device_lost.emit(known)
self.device_found.emit(device)
with self._lock:
gone = [uuid for uuid in self._devices if uuid not in seen]
for uuid in gone:
misses[uuid] = misses.get(uuid, 0) + 1
if misses[uuid] >= MISSES_TO_LOSE:
misses.pop(uuid)
with self._lock:
device = self._devices.pop(uuid, None)
if device is not None:
self.device_lost.emit(device)
await asyncio.sleep(SCAN_PAUSE_S)
+38
View File
@@ -0,0 +1,38 @@
"""The one asyncio loop pyatv runs on, on a daemon thread of its own.
pyatv is asyncio throughout; Qt owns the GUI thread's loop. Everything AirPlay
(discovery scans, connects, streams, volume) is submitted here and its results
come back as Qt signals, so no coroutine ever runs on the GUI thread and no
widget is touched from this one.
"""
import asyncio
import threading
class AsyncLoop:
"""Started on first use; lives as long as the process (it's one idle
thread when nothing is playing)."""
def __init__(self):
self._loop: asyncio.AbstractEventLoop | None = None
self._lock = threading.Lock()
def loop(self) -> asyncio.AbstractEventLoop:
with self._lock:
if self._loop is None:
loop = asyncio.new_event_loop()
threading.Thread(target=loop.run_forever, daemon=True,
name="airplay-loop").start()
self._loop = loop
return self._loop
def submit(self, coro):
"""Schedule `coro`; returns a concurrent.futures.Future. Coroutines
submitted in order start in that order."""
return asyncio.run_coroutine_threadsafe(coro, self.loop())
def run(self, coro, timeout: float):
"""Block for `coro`'s result — teardown only, where waiting a moment
for the speaker to stop is better than leaving it playing."""
return self.submit(coro).result(timeout)
+636
View File
@@ -0,0 +1,636 @@
"""LinTunes' own AirPlay 1 (RAOP) sender, for speakers pyatv can't play on.
pyatv's handshakes reach a WiiM (Linkplay) speaker and play nothing (Round
88); Music Assistant's cliairplay plays on it through libraop's RAOP client
(its "RAOP-compat" route: AirPlay 1 plus auth-setup, NTP timing). This is that
client's *behaviour* on the wire, written from the protocol rather than
translated, request for request:
- one RTSP session for the whole connection — ANNOUNCE (ALAC), SETUP,
RECORD carrying `RTP-Info`, no FLUSH before the first packet — kept alive
with OPTIONS every 25 s; songs, pauses and seeks are FLUSH + restart;
- auth-setup whenever the speaker's `et` lists 4, whatever its model;
- the iTunes User-Agent plus Client-Instance / DACP-ID / Active-Remote;
- a **2 s** buffer (`latency_frames` 88200, plus the 11025 every receiver
adds) against pyatv's 1.5 s — LinkPlay speakers go silent with a shallow
one — and RTP timestamps on the NTP clock itself, so the sync packet says
"frame `ts - latency` plays at NTP(`ts`)";
- a start `START_LEAD_MS` out: the first packets are already late when they
leave, so the first ~2 s go out at once and the speaker begins with a full
buffer;
- the NTP timing responder, resends from a 512-packet backlog, and a sync
packet every second.
One deliberate difference: audio is *uncompressed* ALAC (`alac_verbatim`).
libraop compresses with Apple's encoder; ffmpeg's encoder only writes
4096-sample frames (RAOP needs 352), and adaptive Rice coding in Python
would cost a share of a core on the GUI's interpreter. cliairplay's own
`--raw` is the same uncompressed form.
Pure asyncio, run on the AirPlay `AsyncLoop`; `NativeDevice` gives
`AirPlaySink` the slice of a pyatv device it uses.
"""
import asyncio
import contextlib
import logging
import os
import secrets
import socket
import struct
import time
from lintunes.airplay.support import alac_verbatim
log = logging.getLogger("lintunes.airplay.raop")
FRAMES_PER_PACKET = 352
SAMPLE_RATE = 44100
RAOP_LATENCY_MIN = 11025 # what every receiver adds to the sync's
DEFAULT_LATENCY_MS = 2000
START_LEAD_MS = 200 # libraop's minimum RAOP start lead
USER_AGENT = "iTunes/7.6.2 (Windows; N;)"
KEEPALIVE_S = 25.0
SYNC_INTERVAL_S = 1.0
BACKLOG = 512
RTSP_TIMEOUT_S = 10.0
VOLUME_MIN_DB = -30.0
VOLUME_MUTE_DB = -144.0
class RaopError(ConnectionError):
"""The speaker refused or dropped the session."""
# ---- clocks ----
# NTP here is a 32.32 fixed-point second count (on the Unix epoch, as
# libraop's gettimeofday-based clock is: only differences reach the speaker).
# A timestamp ("ts") is that clock counted in frames.
def ntp_now() -> int:
ns = time.time_ns()
seconds, rest = divmod(ns, 1_000_000_000)
return (seconds << 32) | ((rest << 32) // 1_000_000_000)
def ntp2ts(ntp: int, rate: int = SAMPLE_RATE) -> int:
return ((ntp >> 16) * rate) >> 16
def ts2ntp(ts: int, rate: int = SAMPLE_RATE) -> int:
return ((ts << 16) // rate) << 16
def ms2ts(ms: float, rate: int = SAMPLE_RATE) -> int:
return int(ms * rate // 1000)
def percent_to_db(percent: float) -> float:
"""pyatv's / libraop's volume: 0–100 linear onto −30..0 dB, 0 muted."""
percent = max(0.0, min(100.0, float(percent)))
if percent <= 0:
return VOLUME_MUTE_DB
return VOLUME_MIN_DB + (-VOLUME_MIN_DB) * percent / 100.0
# ---- packets ----
def audio_packet(first: bool, seq: int, ts: int, ssrc: int,
payload: bytes) -> bytes:
return struct.pack(">BBHII", 0x80, 0xE0 if first else 0x60,
seq & 0xFFFF, ts & 0xFFFFFFFF, ssrc) + payload
def sync_packet(first: bool, head_ts: int, latency_frames: int) -> bytes:
""""Frame `head - latency` plays at NTP(head)"; seq is always 7."""
ntp = ts2ntp(head_ts)
return struct.pack(">BBHIIII", 0x90 if first else 0x80, 0xD4, 7,
(head_ts - latency_frames) & 0xFFFFFFFF,
(ntp >> 32) & 0xFFFFFFFF, ntp & 0xFFFFFFFF,
head_ts & 0xFFFFFFFF)
def timing_reply(request: bytes, now_ntp: int) -> bytes | None:
"""Answer a timing request (type 0x52): its send time becomes our
reference, and we received and sent it 'now'."""
if len(request) < 32:
return None
send_time = request[24:32]
now = struct.pack(">II", (now_ntp >> 32) & 0xFFFFFFFF,
now_ntp & 0xFFFFFFFF)
return (bytes([request[0], 0x53 | 0x80]) + request[2:4] + b"\0\0\0\0"
+ send_time + now + now)
def parse_resend(data: bytes) -> tuple[int, int] | None:
"""A resend request (type 0x55): (first lost seq, count)."""
if len(data) != 8 or data[1] & 0x7F != 0x55:
return None
seq, count = struct.unpack(">HH", data[4:8])
return seq, count
def resend_packet(packet: bytes) -> bytes:
return b"\x80\xd6\x00\x01" + packet
def daap_item(title: str, artist: str, album: str) -> bytes:
"""Now-playing text as an `mlit` listing, libraop's layout."""
def tag(code: bytes, data: bytes) -> bytes:
return code + struct.pack(">I", len(data)) + data
body = tag(b"mikd", b"\x02")
for code, value in ((b"minm", title), (b"asar", artist),
(b"asal", album)):
if value:
body += tag(code, value.encode("utf-8"))
return tag(b"mlit", body)
def announce_sdp(sid: str, local_ip: str, peer_ip: str,
rate: int = SAMPLE_RATE) -> str:
return ("v=0\r\n"
f"o=iTunes {sid} 0 IN IP4 {local_ip}\r\n"
"s=iTunes\r\n"
f"c=IN IP4 {peer_ip}\r\n"
"t=0 0\r\n"
"m=audio 0 RTP/AVP 96\r\n"
"a=rtpmap:96 AppleLossless\r\n"
f"a=fmtp:96 {FRAMES_PER_PACKET} 0 16 40 10 14 2 255 0 0 {rate}\r\n")
def parse_transport(value: str) -> dict[str, int]:
ports = {}
for token in (value or "").split(";"):
key, _, number = token.partition("=")
if key.strip() in ("server_port", "control_port", "timing_port"):
with contextlib.suppress(ValueError):
ports[key.strip()] = int(number)
return ports
def metadata_caps(md: str) -> set[str]:
caps = set()
for digit, name in (("0", "text"), ("1", "artwork"), ("2", "progress")):
if digit in (md or ""):
caps.add(name)
return caps
def auth_setup_body() -> bytes:
"""0x01 (unencrypted) and a fresh X25519 public key, as libraop sends."""
from cryptography.hazmat.primitives.asymmetric.x25519 import (
X25519PrivateKey)
from cryptography.hazmat.primitives.serialization import (
Encoding, PublicFormat)
key = X25519PrivateKey.generate().public_key()
return b"\x01" + key.public_bytes(Encoding.Raw, PublicFormat.Raw)
# ---- RTSP ----
class _Rtsp:
"""Requests in libraop's header order, one at a time."""
def __init__(self, user_agent: str, extra: list[tuple[str, str]]):
self.user_agent = user_agent
self.extra = extra
self.url = ""
self.session: str | None = None
self.local_ip = ""
self._cseq = 0
self._reader = None
self._writer = None
self._lock = asyncio.Lock()
async def open(self, host: str, port: int, sid: str):
self._reader, self._writer = await asyncio.wait_for(
asyncio.open_connection(host, port), RTSP_TIMEOUT_S)
self.local_ip = self._writer.get_extra_info("sockname")[0]
self.url = f"rtsp://{host}/{sid}"
def closed(self) -> bool:
return (self._writer is None or self._writer.is_closing()
or self._reader.at_eof())
async def request(self, method: str, headers=(), body: bytes = b"",
content_type: str | None = None, url: str | None = None,
must_succeed: bool = True):
async with self._lock:
if self.closed():
raise RaopError("the speaker closed the connection")
self._cseq += 1
lines = [f"{method} {url or self.url} RTSP/1.0"]
lines += [f"{key}: {value}" for key, value in headers]
if content_type and body:
lines += [f"Content-Type: {content_type}",
f"Content-Length: {len(body)}"]
lines += [f"CSeq: {self._cseq}", f"User-Agent: {self.user_agent}"]
lines += [f"{key}: {value}" for key, value in self.extra]
if self.session is not None:
lines.append(f"Session: {self.session}")
message = ("\r\n".join(lines) + "\r\n\r\n").encode() + body
log.debug("> %s", message[:600])
self._writer.write(message)
try:
await self._writer.drain()
code, reply_headers, reply_body = await asyncio.wait_for(
self._response(), RTSP_TIMEOUT_S)
except (OSError, asyncio.IncompleteReadError,
asyncio.TimeoutError) as e:
raise RaopError(f"{method} got no answer ({e or type(e).__name__})")
log.debug("< %s %s %s", method, code, reply_headers)
if must_succeed and code != 200:
raise RaopError(f"the speaker refused {method} ({code})")
return code, reply_headers, reply_body
async def _response(self):
status = (await self._reader.readuntil(b"\r\n")).decode(
"latin-1").split()
code = int(status[1]) if len(status) > 1 and status[1].isdigit() else 0
headers = {}
while True:
line = (await self._reader.readuntil(b"\r\n")).decode("latin-1")
if line in ("\r\n", "\n"):
break
key, _, value = line.partition(":")
headers[key.strip().lower()] = value.strip()
length = int(headers.get("content-length", "0") or 0)
body = await self._reader.readexactly(length) if length else b""
return code, headers, body
def close(self):
if self._writer is not None:
self._writer.close()
self._writer = None
# ---- UDP ----
class _Udp(asyncio.DatagramProtocol):
def __init__(self, on_datagram=None):
self.transport = None
self._on_datagram = on_datagram
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
if self._on_datagram is not None:
self._on_datagram(data, addr)
def error_received(self, exc):
log.debug("udp error: %s", exc)
@property
def port(self) -> int:
return self.transport.get_extra_info("sockname")[1]
def close(self):
if self.transport is not None:
self.transport.close()
self.transport = None
async def _udp(local_ip: str, on_datagram=None) -> _Udp:
loop = asyncio.get_running_loop()
_, protocol = await loop.create_datagram_endpoint(
lambda: _Udp(on_datagram), local_addr=(local_ip, 0),
family=socket.AF_INET)
return protocol
# ---- the session ----
class RaopClient:
"""One speaker: connect once, then play stretch after stretch.
State mirrors libraop: DOWN → FLUSHED (connected, nothing playing) →
STREAMING; `flush()` goes back to FLUSHED.
"""
def __init__(self, host: str, port: int, properties: dict,
latency_ms: int = DEFAULT_LATENCY_MS):
self.host = host
self.port = port
self.properties = dict(properties or {})
self.latency_frames = max(ms2ts(latency_ms), RAOP_LATENCY_MIN)
self.caps = metadata_caps(self.properties.get("md", ""))
self.state = "down"
self.volume_db: float | None = None
self.head_ts = 0
self.seq = secrets.randbelow(1 << 16)
self.ssrc = int.from_bytes(os.urandom(4), "big")
self._first = False
self._backlog: dict[int, bytes] = {}
self._rtsp: _Rtsp | None = None
self._timing: _Udp | None = None
self._control: _Udp | None = None
self._audio: _Udp | None = None
self._ports: dict[str, int] = {}
self._tasks: list[asyncio.Task] = []
self._last_keepalive = 0.0
# -- connecting --
@property
def latency(self) -> int:
"""Frames from a packet's timestamp to its being heard."""
return self.latency_frames + RAOP_LATENCY_MIN
def connected(self) -> bool:
return self.state != "down" and self._rtsp is not None \
and not self._rtsp.closed()
async def connect(self):
await self._teardown_quietly()
sid = f"{secrets.randbelow(10**10):010d}"
extra = [("Client-Instance", secrets.token_hex(8)),
("DACP-ID", secrets.token_hex(8).upper()),
("Active-Remote", str(secrets.randbelow(1 << 32)))]
model = self.properties.get("am", "")
agent = ("AirPlay/999.0.0" if "AudioAccessory" in model
or "AppleTV" in model else USER_AGENT)
rtsp = _Rtsp(agent, extra)
self._rtsp = rtsp
try:
await rtsp.open(self.host, self.port, sid)
except (OSError, asyncio.TimeoutError) as e:
raise RaopError(f"couldn't reach the speaker ({e})")
try:
if "4" in self.properties.get("et", ""):
# libraop carries on whatever the answer.
await rtsp.request("POST", body=auth_setup_body(),
content_type="application/octet-stream",
url="/auth-setup", must_succeed=False)
local = rtsp.local_ip
# Timing before ANNOUNCE: some receivers query it straight away.
self._timing = await _udp(local, self._on_timing)
await rtsp.request(
"ANNOUNCE", content_type="application/sdp",
body=announce_sdp(sid, local, self.host).encode())
self._control = await _udp(local, self._on_control)
self._audio = await _udp(local)
transport = ("RTP/AVP/UDP;unicast;interleaved=0-1;mode=record;"
f"control_port={self._control.port};"
f"timing_port={self._timing.port}")
_, headers, _ = await rtsp.request(
"SETUP", headers=[("Transport", transport)])
rtsp.session = (headers.get("session") or "").strip() or None
self._ports = parse_transport(headers.get("transport", ""))
if (rtsp.session is None or not self._ports.get("server_port")
or not self._ports.get("control_port")):
raise RaopError("the speaker's SETUP answer had no ports")
_, headers, _ = await rtsp.request("RECORD", headers=[
("Range", "npt=0-"),
("RTP-Info", f"seq={(self.seq + 1) & 0xFFFF};"
f"rtptime={ntp2ts(ntp_now()) & 0xFFFFFFFF}")])
with contextlib.suppress(ValueError):
self.latency_frames = max(
int(headers.get("audio-latency", "0")), self.latency_frames)
self.state = "flushed"
self._last_keepalive = time.monotonic()
self._tasks = [asyncio.ensure_future(self._control_loop())]
if self.volume_db is not None and self.volume_db > VOLUME_MUTE_DB:
await self._send_volume()
log.info("connected to %s:%d (latency %d frames)", self.host,
self.port, self.latency)
except BaseException:
await self._teardown_quietly()
raise
async def ensure_connected(self):
if not self.connected():
await self.connect()
# -- playing --
def start(self, start_ntp: int | None = None):
"""Begin a stretch: its first frame is heard at `start_ntp` (default
START_LEAD_MS from now). Mirrors raopcl_start_at + accept_frames."""
if start_ntp is None:
start_ntp = ntp_now() + ts2ntp(ms2ts(START_LEAD_MS))
self.head_ts = ntp2ts(start_ntp) - self.latency
self._first = True
self.state = "streaming"
self._send_sync(first=True)
def ready_for(self) -> float:
"""Seconds until the next packet is due (≤ 0: send it now)."""
due = self.head_ts + FRAMES_PER_PACKET
return (due - ntp2ts(ntp_now())) / SAMPLE_RATE
def send(self, pcm: bytes):
"""One packet of 352 frames of s16be stereo PCM."""
if len(pcm) < FRAMES_PER_PACKET * 4:
pcm = pcm + bytes(FRAMES_PER_PACKET * 4 - len(pcm))
self.seq = (self.seq + 1) & 0xFFFF
packet = audio_packet(self._first, self.seq, self.head_ts, self.ssrc,
alac_verbatim(pcm))
self._first = False
self._backlog[self.seq % BACKLOG] = (self.seq, packet)
self.head_ts += FRAMES_PER_PACKET
if self._audio is not None and self._audio.transport is not None:
self._audio.transport.sendto(
packet, (self.host, self._ports["server_port"]))
def heard_at(self, ts: int) -> float:
"""time.time() at which frame `ts` comes out of the speaker."""
return (ts + self.latency) / SAMPLE_RATE
async def flush(self):
"""Stop what the speaker has queued (pause, seek, next song)."""
if self.state != "streaming":
return
self.state = "flushed"
await self._rtsp.request("FLUSH", headers=[(
"RTP-Info", f"seq={(self.seq + 1) & 0xFFFF};"
f"rtptime={(self.head_ts + 1) & 0xFFFFFFFF}")],
must_succeed=False)
async def set_volume(self, db: float):
self.volume_db = db
if self.connected():
await self._send_volume()
async def _send_volume(self):
await self._rtsp.request(
"SET_PARAMETER", content_type="text/parameters",
body=f"volume: {self.volume_db:f}\r\n".encode())
async def set_metadata(self, title="", artist="", album="",
artwork: bytes | None = None,
elapsed_ms: int = 0, duration_ms: int = 0):
"""Now playing, as far as the speaker said it takes each part
(`md`). Best effort: a refusal is never fatal (libraop's rule)."""
rtptime = (self.head_ts + self.latency_frames) & 0xFFFFFFFF
info = [("RTP-Info", f"rtptime={rtptime}")]
if "text" in self.caps:
await self._rtsp.request(
"SET_PARAMETER", headers=info,
content_type="application/x-dmap-tagged",
body=daap_item(title, artist, album), must_succeed=False)
if "artwork" in self.caps and artwork:
await self._rtsp.request(
"SET_PARAMETER", headers=info, content_type="image/jpeg",
body=artwork, must_succeed=False)
if "progress" in self.caps and self.state == "streaming":
now = ntp2ts(ntp_now())
started = now - ms2ts(elapsed_ms)
end = started + ms2ts(duration_ms) if duration_ms else now
await self._rtsp.request(
"SET_PARAMETER", content_type="text/parameters",
body=(f"progress: {started & 0xFFFFFFFF}/{now & 0xFFFFFFFF}/"
f"{end & 0xFFFFFFFF}\r\n").encode(),
must_succeed=False)
# -- the background --
def _send_sync(self, first: bool = False):
if self.state != "streaming" or self._control is None \
or self._control.transport is None:
return
self._control.transport.sendto(
sync_packet(first, self.head_ts, self.latency_frames),
(self.host, self._ports["control_port"]))
def _on_timing(self, data: bytes, addr):
reply = timing_reply(data, ntp_now())
if reply is not None and self._timing is not None \
and self._timing.transport is not None:
self._timing.transport.sendto(reply, addr)
def _on_control(self, data: bytes, addr):
lost = parse_resend(data)
if lost is None or self._control is None:
return
first, count = lost
for i in range(count):
seq = (first + i) & 0xFFFF
entry = self._backlog.get(seq % BACKLOG)
if entry is not None and entry[0] == seq \
and self._control.transport is not None:
self._control.transport.sendto(
resend_packet(entry[1]),
(self.host, self._ports["control_port"]))
async def _control_loop(self):
while self.state != "down":
await asyncio.sleep(SYNC_INTERVAL_S)
if self.state == "down":
break
self._send_sync()
if time.monotonic() - self._last_keepalive >= KEEPALIVE_S:
self._last_keepalive = time.monotonic()
try:
await self._rtsp.request("OPTIONS", url="*",
must_succeed=False)
except RaopError as e:
log.info("keepalive failed: %s", e)
self.state = "down"
# -- closing --
async def close(self):
"""FLUSH and TEARDOWN, as libraop's disconnect does."""
if self.connected():
with contextlib.suppress(RaopError):
await self._rtsp.request("FLUSH", headers=[(
"RTP-Info", f"seq={(self.seq + 1) & 0xFFFF};"
f"rtptime={(self.head_ts + 1) & 0xFFFFFFFF}")],
must_succeed=False)
with contextlib.suppress(RaopError):
await self._rtsp.request("TEARDOWN", must_succeed=False)
await self._teardown_quietly()
async def _teardown_quietly(self):
self.state = "down"
tasks, self._tasks = self._tasks, []
for task in tasks:
task.cancel()
for task in tasks:
with contextlib.suppress(BaseException):
await task
for udp in (self._timing, self._control, self._audio):
if udp is not None:
udp.close()
self._timing = self._control = self._audio = None
if self._rtsp is not None:
self._rtsp.close()
self._rtsp = None
self._backlog.clear()
# ---- what AirPlaySink drives ----
class NativeDevice:
"""The pieces of a pyatv device `AirPlaySink` uses — `stream.stream_file`,
`audio.set_volume`, `close()` — over a RaopClient."""
def __init__(self, client: RaopClient):
self.client = client
self.stream = self
self.audio = self
async def connect(self):
await self.client.connect()
async def stream_file(self, request, metadata=None):
"""Play one stretch of a song: ffmpeg's PCM, paced packet by packet,
then wait until the last of it has been heard. A cancel (pause,
seek, next) flushes what the speaker has queued."""
from lintunes.airplay.stream import _ffmpeg_source
client = self.client
request.latency_ms = START_LEAD_MS
await client.ensure_connected()
if client.state == "streaming":
await client.flush()
source = await _ffmpeg_source().open(request, SAMPLE_RATE, 2, 2)
try:
client.start()
meta_task = asyncio.ensure_future(self._metadata(request, metadata))
last_ts = None
while True:
pcm = await source.readframes(FRAMES_PER_PACKET)
if not pcm:
break
wait = client.ready_for()
if wait > 0:
await asyncio.sleep(wait)
if not client.connected():
return # dropped: the request isn't exhausted
last_ts = client.head_ts
client.send(pcm)
meta_task.cancel()
if last_ts is not None:
# Until the end has been heard, as pyatv's padding waits.
end = client.heard_at(last_ts + FRAMES_PER_PACKET)
while time.time() < end and client.connected():
await asyncio.sleep(min(0.25, end - time.time()))
except asyncio.CancelledError:
with contextlib.suppress(Exception):
await asyncio.wait_for(client.flush(), 2.0)
raise
finally:
await source.close()
async def _metadata(self, request, metadata):
if metadata is None:
return
try:
await self.client.set_metadata(
getattr(metadata, "title", "") or "",
getattr(metadata, "artist", "") or "",
getattr(metadata, "album", "") or "",
getattr(metadata, "artwork", None),
elapsed_ms=request.start_ms,
duration_ms=int((getattr(metadata, "duration", 0) or 0)
* 1000))
except RaopError as e:
log.info("metadata: %s", e)
async def set_volume(self, percent: float):
await self.client.set_volume(percent_to_db(percent))
def close(self):
return [self.client.close()]
+346
View File
@@ -0,0 +1,346 @@
"""The Player sink that plays through an AirPlay speaker.
One `stream_file` per stretch of continuous playback: a song from its start,
or from wherever a resume or a seek put it. Each start bumps a *generation*;
a stream's outcome only counts if it is still the current one, so the stream
a seek just replaced can't report "finished" and advance the queue.
Threading follows cast/sink.py: every pyatv call runs on the AsyncLoop, every
outcome comes back through a private signal (queued onto the GUI thread), and
the position is computed on the GUI thread from the frame count the source
keeps in its PcmRequest.
"""
import asyncio
import logging
from contextlib import suppress
from PyQt6.QtCore import QBuffer, QIODevice, QTimer, Qt, pyqtSignal
from PyQt6.QtGui import QImage
from PyQt6.QtMultimedia import QAudio
from lintunes import tagging
from lintunes.airplay.stream import PcmRequest, install_shim
from lintunes.airplay.support import (
can_stream, heard_ms, level_to_percent, unstreamable_reason)
from lintunes.player import PlaybackSink
# Outcomes a stream reports when it ends.
FINISHED = "finished" # ffmpeg reached the end of the song
DECODE_ERROR = "decode_error" # this song can't be read; Player skips it
DROPPED = "dropped" # the speaker closed on us mid-song
FAILED = "failed" # couldn't reach the speaker at all
ART_MAX_PX = 600
# Each stream's life in the journal: started, first audio, how it ended.
log = logging.getLogger("lintunes.airplay") # receivers show a small square; a 3000 px scan is waste
def jpeg_artwork(data: bytes | None) -> bytes | None:
"""The cover as a JPEG of at most ART_MAX_PX: RAOP sends artwork as
image/jpeg whatever it really is. Best-effort, like every art path."""
if not data:
return None
image = QImage()
if not image.loadFromData(data):
return None
if data[:3] == b"\xff\xd8\xff" and max(image.width(),
image.height()) <= ART_MAX_PX:
return data
if max(image.width(), image.height()) > ART_MAX_PX:
image = image.scaled(ART_MAX_PX, ART_MAX_PX,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
buffer = QBuffer()
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buffer, "JPEG", 90)
return bytes(buffer.data())
def outcome_of(request: PcmRequest, error: Exception | None) -> str:
"""Why a stream ended. A closed connection makes pyatv *return* rather
than raise, so "the song is over" is only ever ffmpeg's end of file."""
if request.decode_error:
return DECODE_ERROR
if error is not None:
return FAILED if request.frames_read == 0 else DROPPED
return FINISHED if request.exhausted else DROPPED
class AirPlaySink(PlaybackSink):
"""Streams decoded PCM to an AirPlay receiver."""
provides_pcm = False
glyph = "airplay"
listen_src = "airplay"
POLL_MS = 250
VOLUME_COALESCE_MS = 120
STOP_TIMEOUT_S = 3.0
_stream_ended = pyqtSignal(int, str, str) # generation, outcome, detail
def __init__(self, atv, loop, name: str, parent=None):
super().__init__(parent)
install_shim()
self._atv = atv
self._loop = loop
self.name = name or "AirPlay"
self._track = None
self._metadata: dict = {}
self._first_logged = False
self._request: PcmRequest | None = None
self._generation = 0
self._playing = False
self._position_ms = 0
self._duration_ms = 0
self._percent = 0.0
self._shutdown_done = False
self._dying = False
# Loop-thread state: the running stream task, and a lock so a new
# stream never starts before the last one has torn down (pyatv
# refuses a second stream while one holds the session).
self._task: asyncio.Task | None = None
self._lock: asyncio.Lock | None = None
self._stream_ended.connect(self._on_stream_ended)
self._poll = QTimer(self)
self._poll.setInterval(self.POLL_MS)
self._poll.timeout.connect(self._on_poll)
self._volume_timer = QTimer(self)
self._volume_timer.setSingleShot(True)
self._volume_timer.setInterval(self.VOLUME_COALESCE_MS)
self._volume_timer.timeout.connect(self._flush_volume)
# ---- PlaybackSink ----
def can_play(self, track) -> bool:
return can_stream(track.location, track.kind)
def unplayable_reason(self, track) -> str:
return unstreamable_reason(track.location, track.kind)
def load(self, track, autoplay: bool, start_ms: int):
self._track = track
self._metadata = {
"title": track.name or "",
"artist": track.artist or "",
"album": track.album or "",
"duration": (track.total_time or 0) / 1000.0,
"artwork": self._artwork(track),
}
self._duration_ms = track.total_time or 0
self.duration_changed.emit(self._duration_ms)
self._set_position(max(0, start_ms))
if autoplay:
self._start_stream(self._position_ms)
else:
self._halt_stream()
self._set_playing(False)
def _artwork(self, track):
try:
return jpeg_artwork(tagging.read_embedded_artwork(track.location))
except Exception: # noqa: BLE001 — art is never worth a failure
return None
def play(self):
if self._track is None or self._playing:
return
self._start_stream(self._position_ms)
def pause(self):
# AirPlay has no pause: stop the stream where the listener is, and
# resume() starts a new one from there.
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def stop(self):
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def seek(self, position_ms: int):
target = max(0, position_ms)
if self._playing:
self._start_stream(target)
else:
self._set_position(target)
def position_ms(self) -> int:
return self._position_ms
def duration_ms(self) -> int:
return self._duration_ms
def is_playing(self) -> bool:
return self._playing
def set_volume(self, level: float):
level = max(0.0, min(1.0, float(level)))
# The same perceptual→linear curve LocalSink uses, then dB on the
# speaker: one slider position, one loudness, either output.
linear = QAudio.convertVolume(
level, QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
self._percent = level_to_percent(linear)
self._volume_timer.start()
def shutdown(self):
"""Stop the speaker and close the session. Waits a moment for the
teardown, so quitting doesn't leave the speaker playing what it had
buffered, and never longer: a vanished speaker can't hold up quit."""
if self._shutdown_done:
return
self._shutdown_done = True
self._poll.stop()
self._volume_timer.stop()
self._generation += 1
with suppress(Exception):
self._loop.run(self._close_all(), self.STOP_TIMEOUT_S)
# ---- streams (GUI side) ----
def _start_stream(self, start_ms: int):
if self._shutdown_done or self._dying or self._track is None:
return
self._generation += 1
request = PcmRequest(self._track.location, start_ms,
self._duration_ms)
self._request = request
self._first_logged = False
log.info("stream %d: %s from %d ms", self._generation,
self._track.name or self._track.location, start_ms)
self._set_position(start_ms)
self._set_playing(True)
self._poll.start()
self._loop.submit(self._restart(self._generation, request,
dict(self._metadata), self._percent))
def _halt_stream(self):
self._generation += 1
self._request = None
self._poll.stop()
if not self._shutdown_done:
self._loop.submit(self._halt())
def _freeze_position(self):
if self._request is not None:
self._set_position(self._heard(self._request))
def _heard(self, request: PcmRequest) -> int:
return heard_ms(request.start_ms, request.frames_read,
request.elapsed_ms(), request.sample_rate,
request.latency_ms)
def _on_poll(self):
request = self._request
if request is not None:
if request.first_read_at is not None and not self._first_logged:
self._first_logged = True
log.info("stream %d: first audio sent %.1f s after play "
"(%d Hz)", self._generation,
request.first_read_at - request.created_at,
request.sample_rate)
self._set_position(self._heard(request))
def _on_stream_ended(self, generation: int, outcome: str, detail: str):
log.info("stream %d ended: %s %s", generation, outcome, detail)
if generation != self._generation or self._shutdown_done:
return
self._request = None
self._poll.stop()
if outcome == FINISHED:
self._set_position(self._duration_ms or self._position_ms)
self._set_playing(False)
self.ended.emit()
elif outcome == DECODE_ERROR:
self._set_playing(False)
self.error.emit(f"it couldn't be decoded ({detail})")
elif outcome == DROPPED:
self._fail(f"{self.name} stopped playing — something else may "
"have taken it over.")
else:
self._fail(f"Lost {self.name} ({detail}).")
def _fail(self, reason: str):
"""Let Player fall back to the local output, still playing — the
cast sink's rule: what lintunes last asked for, not what the dying
session said."""
if self._dying:
return
self._dying = True
self._poll.stop()
self.unavailable.emit(reason)
def _flush_volume(self):
if not self._shutdown_done:
self._loop.submit(self._apply_volume(self._percent))
def _set_playing(self, playing: bool):
if playing != self._playing:
self._playing = playing
self.state_changed.emit(playing)
def _set_position(self, position_ms: int):
self._position_ms = position_ms
self.position_changed.emit(position_ms)
# ---- streams (loop thread) ----
def _loop_lock(self) -> asyncio.Lock:
if self._lock is None:
self._lock = asyncio.Lock()
return self._lock
async def _restart(self, generation, request, metadata, percent):
async with self._loop_lock():
await self._cancel_task()
if generation != self._generation:
return # superseded while the last one tore down
# Before the stream, so its first packet is already at this level:
# with no stream running pyatv only stores it for the next one.
await self._apply_volume(percent)
self._task = asyncio.ensure_future(
self._stream(generation, request, metadata))
async def _halt(self):
async with self._loop_lock():
await self._cancel_task()
async def _cancel_task(self):
task, self._task = self._task, None
if task is not None and not task.done():
task.cancel()
with suppress(asyncio.CancelledError, Exception):
await task
async def _stream(self, generation, request, metadata):
from pyatv.interface import MediaMetadata
error = None
try:
await self._atv.stream.stream_file(
request, metadata=MediaMetadata(**metadata))
except asyncio.CancelledError:
request.kill()
raise
except Exception as e: # noqa: BLE001 — reported, never raised
error = e
finally:
request.kill()
self._stream_ended.emit(generation, outcome_of(request, error),
request.decode_error or str(error or ""))
async def _apply_volume(self, percent: float):
with suppress(Exception): # a volume write is never fatal
await self._atv.audio.set_volume(percent)
async def _close_all(self):
await self._halt()
await asyncio.gather(*self._atv.close(), return_exceptions=True)
+189
View File
@@ -0,0 +1,189 @@
"""The audio that goes to the speaker: ffmpeg's PCM, as a pyatv AudioSource.
pyatv's `stream_file` takes a path (decoded whole into memory by miniaudio,
which can't read AAC or ALAC) or a pipe (whose duration it reports as 0 and
whose WAV header it skips by assuming 44 bytes). Neither fits, so
`install_shim` teaches pyatv's `open_source` one more input: a `PcmRequest`,
answered with an `FfmpegSource` built at the sample rate, channel count and
sample size the receiver actually negotiated. Every other input still goes to
pyatv's own code.
A `PcmRequest` is also how the GUI thread watches the stream: the source counts
frames into it, and the sink turns that count into a position.
The compatibility sender (`raop.py`, Round 90) reads its PCM through the
same FfmpegSource; it replaced Round 88's hooks into pyatv's AirPlay 1.
"""
import asyncio
import time
from lintunes.airplay.support import ffmpeg_command
class PcmRequest:
"""One song from one position, plus what happened to it.
Written from the loop thread, read from the GUI thread; every field is a
plain int/float/bool/str, so a read is never torn.
"""
def __init__(self, path: str, start_ms: int, duration_ms: int):
self.path = path
self.start_ms = max(0, int(start_ms))
self.duration_ms = max(0, int(duration_ms))
self.sample_rate = 44100
self.frames_read = 0
self.created_at = time.monotonic()
self.first_read_at: float | None = None # time.monotonic()
self.exhausted = False # ffmpeg reached the end of the song
self.decode_error = "" # ffmpeg failed before producing any audio
# From the first frame read to its being heard; None = pyatv's.
self.latency_ms: float | None = None
self._process = None
def elapsed_ms(self) -> float | None:
if self.first_read_at is None:
return None
return (time.monotonic() - self.first_read_at) * 1000.0
def kill(self):
process, self._process = self._process, None
if process is not None and process.returncode is None:
try:
process.kill()
except ProcessLookupError:
pass
_source_class = None
def _ffmpeg_source():
"""FfmpegSource subclasses pyatv's AudioSource, so it is defined on first
use rather than at import (see the package docstring)."""
global _source_class
if _source_class is not None:
return _source_class
from pyatv.interface import MediaMetadata
from pyatv.protocols.raop.audio_source import AudioSource
class FfmpegSource(AudioSource):
def __init__(self, request, process, sample_rate, channels,
sample_size):
self._request = request
self._process = process
self._rate = sample_rate
self._channels = channels
self._size = sample_size
self._frame = channels * sample_size
@classmethod
async def open(cls, request, sample_rate, channels, sample_size):
process = await asyncio.create_subprocess_exec(
*ffmpeg_command(request.path, request.start_ms, sample_rate,
channels, sample_size),
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
request._process = process
request.sample_rate = sample_rate
return cls(request, process, sample_rate, channels, sample_size)
async def readframes(self, nframes: int) -> bytes:
request = self._request
if request.exhausted or request.decode_error:
return self.NO_FRAMES
try:
data = await self._process.stdout.readexactly(
nframes * self._frame)
except asyncio.IncompleteReadError as e:
data = e.partial
await self._finish(bool(data))
# A trailing partial frame would shift every sample after it.
data = data[:len(data) - len(data) % self._frame]
if data:
if request.first_read_at is None:
request.first_read_at = time.monotonic()
request.frames_read += len(data) // self._frame
return data
async def _finish(self, got_data: bool):
"""End of ffmpeg's output: the song's end, or a failure if it
never produced a frame (missing file, unreadable codec)."""
code = await self._process.wait()
request = self._request
if code != 0 and request.frames_read == 0 and not got_data:
stderr = await self._process.stderr.read()
lines = stderr.decode(errors="replace").strip().splitlines()
request.decode_error = (lines[-1] if lines
else f"ffmpeg exited with {code}")
else:
request.exhausted = True
async def close(self) -> None:
self._request.kill()
async def get_metadata(self):
return MediaMetadata()
@property
def sample_rate(self) -> int:
return self._rate
@property
def channels(self) -> int:
return self._channels
@property
def sample_size(self) -> int:
return self._size
@property
def duration(self) -> int:
# What's left from the start position: the receiver's progress
# bar runs over this stream, not over the whole song.
remaining = self._request.duration_ms - self._request.start_ms
return max(0, round(remaining / 1000))
_source_class = FfmpegSource
return FfmpegSource
def _install_info_fix():
from pyatv.support import rtsp
# GET /info is optional, and pyatv treats an unparseable answer as fatal:
# shairport-sync's classic build answers it with a body that isn't a
# plist, so every stream failed before it began.
real_info = rtsp.RtspSession.info
async def info(self):
try:
return await real_info(self)
except Exception: # noqa: BLE001 — /info is only a hint
return {}
rtsp.RtspSession.info = info
def install_shim():
"""Route a PcmRequest through `stream_file` to an FfmpegSource.
Patches the name the RAOP module looked up at import, which is what
`RaopStream.stream_file` calls. Idempotent.
"""
import pyatv.protocols.raop as raop
if getattr(raop.open_source, "_lintunes", False):
return
original = raop.open_source
async def open_source(source, sample_rate, channels, sample_size):
if isinstance(source, PcmRequest):
return await _ffmpeg_source().open(
source, sample_rate, channels, sample_size)
return await original(source, sample_rate, channels, sample_size)
open_source._lintunes = True
raop.open_source = open_source
_install_info_fix()
+190
View File
@@ -0,0 +1,190 @@
"""Pure helpers for AirPlay: availability, formats, volume, position.
Free of pyatv and the network, so the fiddly arithmetic is unit-tested
offline (the cast/support.py pattern).
"""
import math
import shutil
from pathlib import Path
# pyatv's own buffering: RAOP receivers are told to play each packet
# ``22050 + sample_rate`` frames after it is sent (stream_client's
# StreamContext.latency), so what is heard trails what was sent by ~1.5 s.
def latency_ms(sample_rate: int) -> float:
return (22050 + sample_rate) / sample_rate * 1000.0
# ffmpeg decodes everything the desktop plays; only FairPlay is out of reach.
_REFUSED_KINDS = {"Protected AAC audio file": "copy-protected AAC"}
_REFUSED_SUFFIXES = {".m4p": "copy-protected AAC"}
# AirPlay's volume is dB: 0 is full, -30 is pyatv's floor (its 0–100 % maps
# linearly onto -30..0 dB), -144 is mute.
DBFS_FLOOR = -30.0
def is_available() -> tuple[bool, str]:
"""(True, "") when pyatv is importable and ffmpeg is on PATH.
find_spec, not an import: the menu asks on every open, and pyatv pulls in
aiohttp, cryptography and protobuf.
"""
import importlib.util
try:
if importlib.util.find_spec("pyatv") is None:
return False, "pyatv isn't installed"
except (ImportError, ValueError):
return False, "pyatv isn't installed"
if shutil.which("ffmpeg") is None:
return False, "ffmpeg isn't installed (AirPlay decodes with it)"
return True, ""
def can_stream(location: str, kind: str = "") -> bool:
if not location:
return False
if kind in _REFUSED_KINDS:
return False
return Path(location).suffix.lower() not in _REFUSED_SUFFIXES
def unstreamable_reason(location: str, kind: str = "") -> str:
if not location:
return "it has no file"
if kind in _REFUSED_KINDS:
return f"AirPlay can't play {_REFUSED_KINDS[kind]}"
suffix = Path(location).suffix.lower()
return f"AirPlay can't play {_REFUSED_SUFFIXES.get(suffix, 'this file')}"
def classify(has_raop: bool, pairing: str, requires_password: bool
) -> tuple[bool, str]:
"""Can lintunes stream to this device? (yes, "") or (no, why not).
`pairing` is the name of pyatv's PairingRequirement for the RAOP service.
Only receivers that take a stream from anyone are offered: pairing (a PIN
on a TV) and passwords aren't built yet. A device with AirPlay but no RAOP
is a video/screen-mirroring target with no audio-only endpoint.
"""
if not has_raop:
return False, "video only"
if requires_password:
return False, "needs a password"
if pairing == "Mandatory":
return False, "needs pairing"
if pairing in ("Unsupported", "Disabled"):
return False, "doesn't accept LinTunes"
return True, ""
def level_to_percent(linear: float) -> float:
"""pyatv's volume percent for a *linear* amplitude 0..1.
Player hands sinks a perceptual slider level; the sink converts that to
linear the way LocalSink does (Qt's log→linear curve), and this turns the
linear gain into the same dB on the speaker, so the slider means one
loudness whichever output is playing. Anything under pyatv's -30 dB floor
is 0 % (silent) — the bottom of Qt's curve is that quiet locally too.
"""
if linear <= 0:
return 0.0
db = 20.0 * math.log10(min(1.0, linear))
return max(0.0, min(100.0, (db - DBFS_FLOOR) / -DBFS_FLOOR * 100.0))
def heard_ms(start_ms: int, frames_read: int, elapsed_ms: float | None,
sample_rate: int, lag_ms: float | None = None) -> int:
"""Where the listener is in the song.
`elapsed_ms` runs from the first frame handed to pyatv (None before
that). pyatv paces packets to real time, so elapsed minus the receiver's
latency is what has come out of the speaker — never more than what was
actually read, which is what holds the position at the end while pyatv
sends its trailing silence. `lag_ms` replaces pyatv's latency for a
sender whose first packet is heard sooner after it is read (raop.py).
"""
if elapsed_ms is None or sample_rate <= 0:
return start_ms
read_ms = frames_read / sample_rate * 1000.0
lag = latency_ms(sample_rate) if lag_ms is None else lag_ms
played = max(0.0, min(read_ms, elapsed_ms - lag))
return start_ms + int(played)
def protocol_choice(value) -> str:
"""config.json's `airplay_protocol`: "auto", "1" or "2". Machine-local on
purpose — it's about which speakers this machine meets — and anything
unrecognized is auto."""
value = str(value or "auto").strip().lower().lstrip("v")
return value if value in ("1", "2") else "auto"
# RAOP `am` (model) prefixes of Apple's own receivers. A HomePod takes only
# AirPlay 2, so Apple hardware keeps pyatv's own choice.
_APPLE_MODELS = ("AudioAccessory", "AppleTV", "AirPort", "Mac", "iMac")
def use_compat(choice: str, model: str) -> bool:
"""Stream with LinTunes' own RAOP sender (raop.py) rather than pyatv?
pyatv picks AirPlay 2 for any receiver advertising its features, and a
WiiM (Linkplay) takes that whole session — RECORD, volume, timing — and
plays nothing; its own AirPlay 1 refuses pyatv's transient pairing. What
third-party speakers accept is libraop's AirPlay 1 (cliairplay's
RAOP-compat route), which raop.py reproduces. So "auto" means that for
everything that isn't Apple's, "1" means it everywhere, and "2" is
pyatv's AirPlay 2.
"""
if choice == "1":
return True
if choice == "2":
return False
return not (model or "").startswith(_APPLE_MODELS)
_ALAC_HEAD = None
def alac_verbatim(pcm: bytes) -> bytes:
"""16-bit stereo big-endian PCM as one uncompressed ALAC frame.
ALAC's escape: a channel-pair element flagged "not compressed" carries
the samples as-is, so there's nothing to encode — a 23-bit header
(0x20 0x00 0x02 less its last bit), the samples, the 3-bit end tag, zero
padding. Byte-identical to ffmpeg's encoder on incompressible input.
"""
import numpy as np
global _ALAC_HEAD
if _ALAC_HEAD is None:
_ALAC_HEAD = np.unpackbits(np.frombuffer(b"\x20\x00\x02", np.uint8))[:23]
bits = np.unpackbits(np.frombuffer(pcm, np.uint8))
return np.packbits(np.concatenate(
[_ALAC_HEAD, bits, np.ones(3, np.uint8)])).tobytes()
_SAMPLE_FORMATS = {2: "s16be", 4: "s32be"}
_SAMPLE_FORMATS_LE = {2: "s16le", 4: "s32le"}
def ffmpeg_command(path: str, start_ms: int, sample_rate: int, channels: int,
sample_size: int, big_endian: bool = True) -> list[str]:
"""Decode `path` from `start_ms` to raw PCM on stdout, in the shape the
receiver asked for.
*Big*-endian: pyatv's own sources byteswap little-endian samples before
sending (audio_source._to_audio_samples), so asking ffmpeg for BE is the
same bytes on the wire. `-ss` before `-i` is an input seek, which is
sample-accurate for audio and instant even deep into a long file.
cliairplay (cli.py) reads little-endian, hence `big_endian=False`.
"""
fmt = (_SAMPLE_FORMATS if big_endian else _SAMPLE_FORMATS_LE).get(sample_size)
if fmt is None:
raise ValueError(f"unsupported sample size {sample_size}")
command = ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error"]
if start_ms > 0:
command += ["-ss", f"{start_ms / 1000.0:.3f}"]
command += ["-i", path, "-map", "0:a:0", "-vn",
"-f", fmt, "-ac", str(channels), "-ar", str(sample_rate),
"pipe:1"]
return command
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"version_name": "0.3.0", "version_code": 6}
{"version_name": "0.4.2", "version_code": 9}
+2 -3
View File
@@ -19,7 +19,7 @@ from pathlib import Path
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, Qt
from PyQt6.QtGui import QImage
from .. import tagging
from .. import paths, tagging
from .layout import album_key
# The panel is 480 px wide, so a cover never needs to be bigger than that;
@@ -29,8 +29,7 @@ JPEG_QUALITY = 85
def _cache_dir() -> Path:
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "andtunes-art"
return paths.cache_dir() / "andtunes-art"
def render_jpeg(data: bytes) -> bytes | None:
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

+2 -3
View File
@@ -28,7 +28,7 @@ from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from .. import __version__
from .. import __version__, paths
from ..device_sync import CHUNK, build_m3u, track_display
from ..export import web_support
from . import art as art_mod
@@ -129,8 +129,7 @@ def flac_cache(track) -> Path:
Keyed by track id, so a rename doesn't orphan it; stale once the source
is newer (a re-tag rewrites the file), exactly like the art cache.
"""
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "andtunes-flac" / f"{track.track_id}.flac"
return paths.cache_dir() / "andtunes-flac" / f"{track.track_id}.flac"
def _fresh(cache: Path, src: Path) -> bool:
+233
View File
@@ -0,0 +1,233 @@
"""Apple Music links for File ▸ Import from URL… (Round 130).
Spotify's twin (``spotify_link``): Apple won't hand over audio either, but
it will say what a link is, without a key or a login, and each song is then
found on YouTube by artist, title and length exactly as a Spotify song is.
The songs come back as ``spotify_link.SpotifyTrack``s, so the probe, the
checklist, the YouTube search and the tagging are all Spotify's own.
Where the list comes from depends on the link (measured November 2026):
- **An album or a song** — the public iTunes Lookup API
(``itunes.apple.com/lookup``), which is documented and stable: track and
disc numbers, the album's name, each song's length.
- **A playlist** — has no keyless API, but its ``music.apple.com`` page
carries every song as JSON in a ``serialized-server-data`` script: title,
artist, album and length per song, and the playlist's name. All of them,
not a first page: a 143-song playlist's page held all 143.
Shaped like ``spotify_link``: pure helpers first (tested against canned
JSON), then the network calls.
"""
import json
import re
from urllib.parse import parse_qs, urlsplit
import requests
from lintunes.spotify_link import USER_AGENT, SpotifyTrack
TIMEOUT = 20
LOOKUP_URL = "https://itunes.apple.com/lookup"
PLAYLIST_URL = "https://music.apple.com/{storefront}/playlist/{id}"
_HOSTS = ("music.apple.com", "geo.music.apple.com", "embed.music.apple.com",
"itunes.apple.com")
_SERVER_DATA = re.compile(
r'<script[^>]*id="serialized-server-data"[^>]*>\s*(.*?)\s*</script>',
re.DOTALL)
class AppleMusicError(Exception):
pass
def apple_source(text: str) -> tuple[str, str, str] | None:
"""(kind, id, storefront) for an Apple Music song, album or playlist
link, else None. kind is "song", "album" or "playlist"; an album link
with ``?i=<song id>`` (what Share Song copies) is that one song."""
text = (text or "").strip()
try:
parts = urlsplit(text)
except ValueError:
return None
if parts.scheme not in ("http", "https") or \
(parts.hostname or "").lower() not in _HOSTS:
return None
segments = [s for s in parts.path.split("/") if s]
storefront = "us"
if segments and re.fullmatch(r"[a-z]{2}", segments[0]):
storefront = segments.pop(0)
if len(segments) < 2:
return None
kind, source_id = segments[0], segments[-1]
song = (parse_qs(parts.query).get("i") or [""])[0]
if kind == "album":
if song.isdigit():
return "song", song, storefront
m = re.fullmatch(r"(?:id)?(\d+)", source_id)
return ("album", m.group(1), storefront) if m else None
if kind == "song":
m = re.fullmatch(r"(?:id)?(\d+)", source_id)
return ("song", m.group(1), storefront) if m else None
if kind == "playlist" and source_id.startswith("pl."):
return "playlist", source_id, storefront
return None
def _seconds(ms) -> int | None:
try:
return round(float(ms) / 1000) or None
except (TypeError, ValueError):
return None
def parse_lookup(data: dict, kind: str) -> tuple[str, list[SpotifyTrack]]:
"""An iTunes Lookup answer → (the album's or song's name, its songs).
An album's songs are numbered as on the album; a lone song too, since
the lookup knows where it sits."""
results = (data or {}).get("results") or []
songs = [r for r in results
if r.get("wrapperType") == "track" and r.get("trackName")]
if not songs:
raise AppleMusicError("Apple Music has no songs at that link (it may "
"be private, deleted, or not in that country)")
songs.sort(key=lambda r: (r.get("discNumber") or 0,
r.get("trackNumber") or 0))
collection = next((r for r in results
if r.get("wrapperType") == "collection"), None)
discs = max((r.get("discCount") or 0) for r in songs)
tracks = [SpotifyTrack(
id=str(r.get("trackId") or n), title=r["trackName"],
artist=r.get("artistName") or "",
album=r.get("collectionName") or "",
duration=_seconds(r.get("trackTimeMillis")),
track_number=r.get("trackNumber") or 0,
track_count=r.get("trackCount") or 0,
disc_number=(r.get("discNumber") or 0) if discs > 1 else 0,
disc_count=discs if discs > 1 else 0)
for n, r in enumerate(songs, 1)]
if kind == "song":
return tracks[0].title, tracks[:1]
name = (collection or {}).get("collectionName") or tracks[0].album
return name or "Apple Music", tracks
def _link_title(item: dict, key: str) -> str:
links = item.get(key) or []
return (links[0].get("title") or "") if links else ""
def parse_playlist_page(html: str) -> tuple[str, list[SpotifyTrack]]:
"""A ``music.apple.com`` playlist page → (its name, its songs in order).
Raises AppleMusicError when the page isn't shaped the way it was in
November 2026."""
m = _SERVER_DATA.search(html or "")
if not m:
raise AppleMusicError("Apple Music's page didn't have the song list "
"in it (Apple may have changed its page "
"format)")
try:
data = json.loads(m.group(1))
sections = data["data"][0]["data"]["sections"]
except (ValueError, KeyError, IndexError, TypeError) as e:
raise AppleMusicError(f"Apple Music's song list couldn't be read: "
f"{e}")
name = ""
tracks: list[SpotifyTrack] = []
for section in sections:
kind = section.get("itemKind")
items = section.get("items") or []
if kind == "containerDetailHeaderLockup" and items and not name:
name = items[0].get("title") or ""
elif kind == "trackLockup":
for n, item in enumerate(items, 1):
title = item.get("title")
if not title:
continue
ident = ((item.get("contentDescriptor") or {})
.get("identifiers") or {}).get("storeAdamID")
tracks.append(SpotifyTrack(
id=str(ident or n), title=title,
artist=(item.get("artistName")
or _link_title(item, "subtitleLinks")),
album=_link_title(item, "tertiaryLinks"),
duration=_seconds(item.get("duration"))))
if not tracks:
raise AppleMusicError("Apple Music's page had no songs in it")
return name or "Apple Music", tracks
# The size a cover is asked for. Apple's artwork URLs are templates and
# scale server-side to whatever is asked.
COVER_SIZE = 1200
def _artwork(template: str) -> str:
if not template:
return ""
return (template.replace("{w}", str(COVER_SIZE))
.replace("{h}", str(COVER_SIZE)).replace("{f}", "jpg"))
def playlist_cover_url(html: str) -> str:
"""A playlist page's cover image URL, or "" when it has none."""
m = _SERVER_DATA.search(html or "")
try:
sections = json.loads(m.group(1))["data"][0]["data"]["sections"]
except (AttributeError, ValueError, KeyError, IndexError, TypeError):
return ""
for section in sections:
if section.get("itemKind") == "containerDetailHeaderLockup":
for item in section.get("items") or []:
url = (((item.get("artwork") or {}).get("dictionary") or {})
.get("url"))
if url:
return _artwork(url)
return ""
def lookup_cover_url(data: dict) -> str:
"""An iTunes Lookup answer's cover, at ``COVER_SIZE``, or ""."""
for r in (data or {}).get("results") or []:
url = r.get("artworkUrl100") or ""
if url and "100x100" in url:
return url.replace("100x100", f"{COVER_SIZE}x{COVER_SIZE}")
return ""
# ---- network ----
def _get(url: str, **params) -> requests.Response:
try:
return requests.get(url, params=params or None, timeout=TIMEOUT,
headers={"User-Agent": USER_AGENT})
except requests.RequestException as e:
raise AppleMusicError(f"couldn't reach Apple Music: {e}")
def fetch(kind: str, source_id: str,
storefront: str = "us") -> tuple[str, list[SpotifyTrack], str]:
"""→ (the link's name, its songs, its cover image URL or "")."""
if kind == "playlist":
resp = _get(PLAYLIST_URL.format(storefront=storefront, id=source_id))
if resp.status_code == 404:
raise AppleMusicError("Apple Music has no playlist with that "
"link (it may be private or deleted)")
if not resp.ok:
raise AppleMusicError(f"Apple Music answered {resp.status_code}")
return (*parse_playlist_page(resp.text),
playlist_cover_url(resp.text))
params = {"id": source_id, "country": storefront}
if kind == "album":
params["entity"] = "song"
params["limit"] = 200 # the default 50 cuts a box set short
resp = _get(LOOKUP_URL, **params)
if not resp.ok:
raise AppleMusicError(f"Apple Music answered {resp.status_code}")
try:
data = resp.json()
except ValueError as e:
raise AppleMusicError(f"Apple Music's answer couldn't be read: {e}")
return (*parse_lookup(data, kind), lookup_cover_url(data))
+380
View File
@@ -0,0 +1,380 @@
"""Boost Volume (Round 131): make a too-quiet MP3 as loud as the rest
**without re-encoding it** — the way ``mp3gain`` does.
Why the file and not the player: the player can't play louder than the file
(Qt's output volume stops at 1.0), so neither iTunes' old per-song Volume
Adjustment nor volume normalization could lift a quiet song while the main
volume was up.
How, losslessly: every MP3 granule carries an 8-bit ``global_gain`` in its
side info, the scale the decoder multiplies the whole granule by — one unit
is 2^(1/4) in amplitude, **1.5 dB**. Adding the same number of units to every
granule makes the decoder play the same audio louder; the compressed audio
itself is untouched, so nothing is lost, and taking the units off again gives
back the original bytes. Hence boosts come in 1.5 dB steps, and only MP3s
(Layer III) get the button: AAC's equivalent sits behind each frame's Huffman
data, and re-encoding anything is ruled out (trav's call — never transcode).
How much: up to a *typical* song's loudness (the median of every song the
normalizer has measured, ``LoudnessAnalyzer.typical_lufs``, EBU R128 via
ffmpeg, which only *reads*), but never past ``CEILING_DBTP`` true peak — a
boost never clips. One choice, no options.
Frames whose side info is CRC-protected would need their CRC redone, so such
a file counts as unsupported. The Xing/Info frame is left alone: its side
info is all zeros anyway, and LAME's tag in it carries a CRC over those bytes.
The library swaps files through ``LibraryManager.replace_track_files``
(in place): the original goes to the trash, Edit ▸ Undo puts it back.
"""
from __future__ import annotations
import logging
import math
import re
import shutil
import tempfile
import threading
from dataclasses import dataclass
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import loudness
from lintunes.importers import lossless
log = logging.getLogger(__name__)
CEILING_DBTP = -1.0 # true-peak headroom a boost keeps: it never clips
STEP_DB = 1.5 # one global_gain unit
MAX_STEPS = 20 # 30 dB: past that it's a near-silent file, all hiss
_TRUE_PEAK = re.compile(r"True peak:\s*\n\s*Peak:\s*(-?[\d.]+|-inf)\s*dBFS")
# ---- measuring and planning ----
def parse_measurement(output: str) -> tuple[float | None, float | None]:
"""``(integrated LUFS, true peak dBTP)`` from ffmpeg's ebur128 summary
(run with ``peak=true``); either is None when absent or silent."""
lufs = loudness.parse_ebur128(output)
match = _TRUE_PEAK.search(output)
peak = None
if match and match.group(1) != "-inf":
peak = float(match.group(1))
return lufs, peak
@dataclass
class Plan:
"""What a boost of one song would do."""
lufs: float | None # how loud it is now
peak: float | None # its true peak now, dBTP
steps: int # global_gain units to add (1.5 dB each)
reaches_typical: bool # False when the peak stopped it short
@property
def gain_db(self) -> float:
return self.steps * STEP_DB
@property
def measurable(self) -> bool:
return self.lufs is not None and self.peak is not None
def plan(lufs: float | None, peak: float | None, typical_lufs: float) -> Plan:
"""As close to ``typical_lufs`` as whole steps get without passing the
ceiling (rounded down, so it never overshoots either)."""
if lufs is None or peak is None:
return Plan(lufs, peak, 0, False)
wanted = typical_lufs - lufs
room = CEILING_DBTP - peak
steps = max(0, min(MAX_STEPS, math.floor(min(wanted, room) / STEP_DB + 1e-9)))
# "Reaches" means within a step of where it was going.
return Plan(lufs, peak, steps, wanted - steps * STEP_DB < STEP_DB)
def measure(path: str) -> tuple[float | None, float | None]:
"""Decode the whole file once through ebur128 with true peak."""
import subprocess
try:
result = subprocess.run(
["ffmpeg", "-nostdin", "-nostats", "-hide_banner", "-i", path,
"-map", "0:a:0", "-af", "ebur128=peak=true:framelog=quiet",
"-f", "null", "-"],
capture_output=True, text=True, errors="replace", timeout=300)
except (OSError, subprocess.SubprocessError) as exc:
log.info("boost: couldn't measure %s: %s", path, exc)
return None, None
return parse_measurement(result.stderr)
# ---- MP3 frames ----
class Mp3Error(Exception):
"""Not an MP3 whose gain this can change."""
_BITRATES = { # Layer III, kbps by index
1: (0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320),
2: (0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160),
}
_RATES = {3: (44100, 48000, 32000), 2: (22050, 24000, 16000),
0: (11025, 12000, 8000)} # by the header's version bits
@dataclass
class _Frame:
offset: int
length: int
mpeg1: bool
channels: int
crc: bool
@property
def side_offset(self) -> int:
return self.offset + 4 + (2 if self.crc else 0)
@property
def side_length(self) -> int:
if self.mpeg1:
return 17 if self.channels == 1 else 32
return 9 if self.channels == 1 else 17
def _header(data, pos: int) -> _Frame | None:
"""The Layer III frame starting at ``pos``, or None if there isn't one."""
if pos + 4 > len(data) or data[pos] != 0xFF or (data[pos + 1] & 0xE0) != 0xE0:
return None
b1, b2, b3 = data[pos + 1], data[pos + 2], data[pos + 3]
version = (b1 >> 3) & 3 # 3 MPEG1, 2 MPEG2, 0 MPEG2.5, 1 reserved
layer = (b1 >> 1) & 3 # 1 = Layer III
if version == 1 or layer != 1:
return None
br_index, sr_index = b2 >> 4, (b2 >> 2) & 3
if br_index in (0, 15) or sr_index == 3:
return None # free format, bad, or reserved
mpeg1 = version == 3
bitrate = _BITRATES[1 if mpeg1 else 2][br_index] * 1000
rate = _RATES[version][sr_index]
padding = (b2 >> 1) & 1
length = (144 if mpeg1 else 72) * bitrate // rate + padding
channels = 1 if (b3 >> 6) == 3 else 2
return _Frame(pos, length, mpeg1, channels, crc=not (b1 & 1))
def _audio_start(data) -> int:
"""Past an ID3v2 tag (and its footer), if there is one."""
if data[:3] == b"ID3" and len(data) >= 10:
size = 0
for b in data[6:10]:
size = (size << 7) | (b & 0x7F)
return 10 + size + (10 if data[5] & 0x10 else 0)
return 0
def _frames(data):
"""Every Layer III frame, in order. A frame is trusted when the next
one starts where it ends (or it's the last); junk between frames is
skipped by resyncing on the next pair that chains."""
pos = _audio_start(data)
end = len(data)
if data[-128:-125] == b"TAG":
end -= 128
synced = False
while pos < end - 4:
frame = _header(data, pos)
if frame is not None and pos + frame.length <= end:
following = pos + frame.length
if synced or following >= end - 4 or _header(data, following):
synced = True
yield frame
pos = following
continue
synced = False
pos += 1
def _is_info_frame(data, frame: _Frame) -> bool:
tag = frame.side_offset + frame.side_length
return data[tag:tag + 4] in (b"Xing", b"Info")
def _gain_bits(frame: _Frame):
"""Bit offsets of every global_gain in the frame's side info."""
if frame.mpeg1:
head = 9 + (5 if frame.channels == 1 else 3) + 4 * frame.channels
granules, info = 2, 59
else:
head = 8 + (1 if frame.channels == 1 else 2)
granules, info = 1, 63
for g in range(granules):
for c in range(frame.channels):
yield head + (g * frame.channels + c) * info + 21
def _bits(buf, base: int, bit: int, count: int) -> int:
value = 0
for i in range(bit, bit + count):
value = (value << 1) | ((buf[base + i // 8] >> (7 - i % 8)) & 1)
return value
def _get8(buf, base: int, bit: int) -> int:
byte, shift = base + bit // 8, bit % 8
word = (buf[byte] << 8) | buf[byte + 1]
return (word >> (8 - shift)) & 0xFF
def _set8(buf, base: int, bit: int, value: int):
byte, shift = base + bit // 8, bit % 8
word = (buf[byte] << 8) | buf[byte + 1]
mask = 0xFF << (8 - shift)
word = (word & ~mask & 0xFFFF) | (value << (8 - shift))
buf[byte], buf[byte + 1] = word >> 8, word & 0xFF
def _gain_sites(data):
"""Every (frame, side-info base, bit offset) whose gain is ours to move.
Raises Mp3Error for a file this can't treat."""
sites, frames = [], 0
for frame in _frames(data):
frames += 1
if frame.crc:
raise Mp3Error("its frames have CRC checks")
if _is_info_frame(data, frame):
continue
for bit in _gain_bits(frame):
# A granule with no audio data (part2_3_length 0) is digital
# silence: LAME parks its gain at 210 or 255, and it means
# nothing — moving it would only hit the 255 ceiling.
if _bits(data, frame.side_offset, bit - 21, 12):
sites.append((frame.side_offset, bit))
if frames < 10 or not sites:
raise Mp3Error("no MP3 audio found")
return sites
def supported(path: str) -> bool:
"""Whether Boost Volume can work on this file: an MP3 (Layer III)
without CRC-protected frames. Reads the start of the file only."""
if Path(path).suffix.lower() != ".mp3":
return False
try:
with open(path, "rb") as f:
head = f.read(10)
start = _audio_start(head) if len(head) == 10 else 0
f.seek(start)
data = f.read(16384)
except OSError:
return False
for pos in range(min(len(data) - 4, 4096)):
frame = _header(data, pos)
if frame is not None and _header(data, pos + frame.length):
return not frame.crc
return False
def headroom_steps(data) -> int:
"""How many steps fit before some granule's gain would pass 255."""
return 255 - max(_get8(data, base, bit) for base, bit in _gain_sites(data))
def apply_gain(data: bytes, steps: int) -> bytes:
"""``data`` (a whole MP3 file) with ``steps`` added to every granule's
global_gain. Same length; only those bits differ. Raises Mp3Error."""
buf = bytearray(data)
sites = _gain_sites(buf)
if steps > 255 - max(_get8(buf, b, bit) for b, bit in sites):
raise Mp3Error("its gain is already near the top")
for base, bit in sites:
value = _get8(buf, base, bit)
_set8(buf, base, bit, max(0, value + steps))
return bytes(buf)
def boost_file(src: Path, dest: Path, steps: int):
"""Write ``src`` with ``steps`` more gain to ``dest``. ``src`` is only
read; ``dest`` is byte for byte the same file but for the gain bits."""
data = src.read_bytes()
steps = min(steps, headroom_steps(data))
if steps <= 0:
raise Mp3Error("its gain is already at the top")
dest.write_bytes(apply_gain(data, steps))
shutil.copystat(src, dest)
# ---- the worker ----
class BoostWorker(QObject):
"""Measures songs, then (once told how much) writes boosted copies, on
a daemon thread. Works from ``(track id, path, name)`` snapshots, never
the library.
``measured`` carries ``{track id: Plan}``; ``boosted`` carries
``[(track id, staged file)]`` plus ``[(track id, reason)]`` failures.
The caller removes ``tmp_dir`` when it's done with the staged files."""
measured = pyqtSignal(dict)
progress = pyqtSignal(str)
boosted = pyqtSignal(list, list)
def __init__(self, items: list[tuple[int, str, str]], typical_lufs: float,
parent=None, measure_fn=None):
super().__init__(parent)
self._items = list(items)
self._typical = typical_lufs
self._measure = measure_fn or measure
self.tmp_dir: Path | None = None
self._busy = False
def busy(self) -> bool:
return self._busy
def start_measuring(self):
self._start(self._run_measure)
def start_boosting(self, steps: dict[int, int]):
self._start(lambda: self._run_boost(steps))
def _start(self, target):
self._busy = True
def run():
try:
target()
finally:
self._busy = False
threading.Thread(target=run, daemon=True).start()
def _run_measure(self):
plans = {}
for n, (tid, path, name) in enumerate(self._items, 1):
self.progress.emit(f"Measuring {self._which(n, name)}")
plans[tid] = plan(*self._measure(path), self._typical)
self.measured.emit(plans)
def _run_boost(self, steps: dict[int, int]):
root = lossless.staging_root()
root.mkdir(parents=True, exist_ok=True)
self.tmp_dir = Path(tempfile.mkdtemp(prefix="boost-", dir=root))
done, failed = [], []
todo = [item for item in self._items if item[0] in steps]
for n, (tid, path, name) in enumerate(todo, 1):
self.progress.emit(f"Boosting {self._which(n, name, len(todo))}")
src = Path(path)
dest = self.tmp_dir / f"{tid}" / src.name
dest.parent.mkdir(parents=True, exist_ok=True)
try:
boost_file(src, dest, steps[tid])
except (OSError, Mp3Error) as e:
log.warning("boost: %s: %s", path, e)
failed.append((tid, str(e)))
continue
done.append((tid, dest))
self.boosted.emit(done, failed)
def _which(self, n: int, name: str, total: int | None = None) -> str:
total = total if total is not None else len(self._items)
name = name if len(name) <= 40 else name[:39] + "…"
return name if total == 1 else f"{n} of {total} · {name}"
+34 -5
View File
@@ -234,9 +234,30 @@ class DeliveryResult:
errors: list = field(default_factory=list) # (what, error text)
def _stage_compressed(source: Path, music_dir: Path, original: str,
kbps: int, cancel) -> tuple[Path, dict] | None:
"""A lossless arrival converted to MP3 (``importers.lossless``) and
staged under the name it was sent with; None when cancelled. The outbox
copy is only read — it's the friend's to delete."""
import tempfile
from lintunes.importers import lossless
from lintunes.importers.file_importer import stage_file
root = lossless.staging_root()
root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="cassette-", dir=root) as tmp:
mp3 = Path(tmp) / (Path(original).stem + ".mp3")
if not lossless.convert(source, mp3, kbps, cancel=cancel):
return None
return stage_file(mp3, music_dir, mp3.name)
def run_plans(send_plans, receive_plans, music_dir: Path | None,
cancel: threading.Event | None = None) -> DeliveryResult:
"""All the file work. Safe off the GUI thread: touches no library."""
cancel: threading.Event | None = None,
compress_kbps: int | None = None) -> DeliveryResult:
"""All the file work. Safe off the GUI thread: touches no library.
With ``compress_kbps``, a lossless song coming into the library is
converted to an MP3 at that bitrate first (Round 107)."""
from lintunes.importers import lossless
from lintunes.importers.file_importer import stage_file
result = DeliveryResult()
for plan in send_plans:
@@ -279,7 +300,14 @@ def run_plans(send_plans, receive_plans, music_dir: Path | None,
tmp.replace(dest)
result.cached.append((plan.token, arrival.track_id))
if arrival.to_library and music_dir is not None:
dest, fields = stage_file(arrival.path, music_dir, original)
staged = None
if compress_kbps and lossless.is_lossless(arrival.path):
staged = _stage_compressed(arrival.path, music_dir,
original, compress_kbps, cancel)
if staged is None:
return result
dest, fields = staged or stage_file(arrival.path, music_dir,
original)
result.staged.append(Staged(plan.token, arrival.track_id,
dest, fields,
Path(original).stem))
@@ -304,7 +332,8 @@ class DeliveryWorker(QObject):
def cancel(self):
self._cancel.set()
def start(self, send_plans, receive_plans, music_dir):
def start(self, send_plans, receive_plans, music_dir,
compress_kbps: int | None = None):
if self._busy:
return False
self._busy = True
@@ -313,7 +342,7 @@ class DeliveryWorker(QObject):
def run():
try:
result = run_plans(send_plans, receive_plans, music_dir,
self._cancel)
self._cancel, compress_kbps)
except Exception as exc: # never die silently
log.exception("cassette delivery")
result = DeliveryResult(errors=[("Delivering songs", str(exc))])
+6 -1
View File
@@ -16,6 +16,7 @@ from __future__ import annotations
import socket
from lintunes import paths
from lintunes.config import load_config, save_config
from lintunes.storage.play_journal import machine_id
@@ -29,9 +30,13 @@ UNCLAIMED = "unclaimed"
def hostname() -> str:
try:
return socket.gethostname() or "this computer"
name = socket.gethostname() or "this computer"
except OSError:
return "this computer"
# A Mac's hostname is its Bonjour name, "Travs-MacBook.local".
if paths.IS_MAC and name.lower().endswith(".local") and len(name) > 6:
name = name[:-6]
return name
def host_status(prefs) -> tuple[str, str]:
+24 -1
View File
@@ -14,6 +14,8 @@ from __future__ import annotations
import json
from pathlib import Path
from lintunes import paths
FORMAT_VERSION = 1
INFO_FILE = "cassette.json"
AVATAR_FILE = "avatar.png"
@@ -23,6 +25,17 @@ STIGNORE = ".stignore"
# own .syncthing.*.tmp already.)
STIGNORE_TEXT = "// written by LinTunes\n*.tmp\n*.part\n"
# Finder drops .DS_Store into any folder it shows (and ._* AppleDouble files
# on non-APFS disks). In a send-only folder they would travel to the friend;
# in a receive-only one they would read as "local additions". (?d) lets
# Syncthing delete them when the folder itself has to go.
MAC_IGNORES = "(?d).DS_Store\n(?d)._*\n"
def stignore_text() -> str:
"""The out folder's .stignore. On Linux exactly STIGNORE_TEXT."""
return STIGNORE_TEXT + (MAC_IGNORES if paths.IS_MAC else "")
def write_bytes_if_changed(path: Path, data: bytes) -> bool:
"""Atomically write ``data`` unless ``path`` already holds exactly it.
@@ -54,7 +67,17 @@ def read_json(path: Path, default=None):
def prepare_out_dir(out: Path):
out.mkdir(parents=True, exist_ok=True)
write_bytes_if_changed(out / STIGNORE, STIGNORE_TEXT.encode())
write_bytes_if_changed(out / STIGNORE, stignore_text().encode())
def prepare_in_dir(folder: Path):
"""Make a receive-only folder. On a Mac it also gets a .stignore for
Finder's litter; on Linux nothing is written but the directory."""
folder.mkdir(parents=True, exist_ok=True)
if paths.IS_MAC:
write_bytes_if_changed(folder / STIGNORE,
("// written by LinTunes\n"
+ MAC_IGNORES).encode())
def publish_intro(out: Path, display_name: str, avatar_source: Path | None):
+11 -3
View File
@@ -24,12 +24,14 @@ from __future__ import annotations
import logging
import shutil
import threading
import unicodedata
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
from lintunes.config import load_config
from lintunes.cassette import invite as inv
from lintunes.cassette import publish
@@ -315,6 +317,10 @@ class CassetteService(QObject):
try:
client = self.client()
relative = path.relative_to(in_dir(self.root, token)).as_posix()
if paths.IS_MAC:
# Syncthing names files in NFC; a name listed off APFS can be
# NFD (whatever wrote it), and the lookup would miss.
relative = unicodedata.normalize("NFC", relative)
info = client.file_info(friend.in_folder, relative)
except (st.SyncthingError, ValueError):
return True
@@ -480,7 +486,9 @@ class CassetteService(QObject):
"Syncthing's config.")
else:
status = Status(SYNCTHING_DOWN, "Syncthing isn't running",
"Start Syncthing, then press Retry in Sync "
st.not_running_hint(
"press Retry in Sync Settings ▸ General")
or "Start Syncthing, then press Retry in Sync "
"Settings ▸ General.")
with self._lock:
changed = self._api.code != status.code
@@ -541,7 +549,7 @@ class CassetteService(QObject):
and friend.device_id == device_id
and client.folder(folder_id) is None):
in_path = in_dir(self.root, token)
in_path.mkdir(parents=True, exist_ok=True)
publish.prepare_in_dir(in_path)
client.add_folder(
folder_id, f"LinTunes: from {friend.name}", in_path,
"receiveonly", [device_id],
@@ -561,7 +569,7 @@ class CassetteService(QObject):
client.share_folder(invite.folder_id, device_id,
step="Sharing your folder with your friend")
in_path = in_dir(self.root, token)
in_path.mkdir(parents=True, exist_ok=True)
publish.prepare_in_dir(in_path)
client.add_folder(inv.invitee_folder(token), "LinTunes: from a friend",
in_path, "receiveonly", [device_id],
step="Accepting your friend's folder")
+10 -9
View File
@@ -1,10 +1,10 @@
"""Cassette's own state: who my friends are, what I share with each, what I've
asked each of them for.
It lives in the machine-local cassette root (``~/.local/share/lintunes/
cassette/state.json``), **not** in the synced data dir: only the host machine
runs Cassette, the friend folders it describes exist only here, and a second
copy riding Syncthing would just be a conflict waiting to happen.
It lives in the machine-local cassette root (``paths.data_dir()/cassette/
state.json``; ``~/.local/share/lintunes/…`` on Linux), **not** in the synced
data dir: only the host machine runs Cassette, the friend folders it
describes exist only here, and a second copy riding Syncthing would just be a conflict waiting to happen.
Plain dataclasses with ``to_dict``/``from_dict``, like ``lintunes/models``;
``save`` is atomic (``json_storage.write_json``).
@@ -13,11 +13,11 @@ from __future__ import annotations
import copy
import getpass
import os
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from lintunes import paths
from lintunes.config import load_config
from lintunes.storage.json_storage import read_json, write_json
@@ -52,8 +52,7 @@ def cassette_root() -> Path:
override = (load_config().get(ROOT_KEY) or "").strip()
if override:
return Path(override).expanduser()
base = os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share"))
return Path(base) / "lintunes" / "cassette"
return paths.data_dir() / "cassette"
def default_display_name() -> str:
@@ -160,7 +159,9 @@ class Friend:
class CassetteState:
display_name: str = field(default_factory=default_display_name)
avatar: str = "" # filename inside the cassette root, "" = none
share_same_for_all: bool = False
# On by default (Round 105): one selection for everyone is what a first
# friend expects; per-friend pages are the exception.
share_same_for_all: bool = True
general: Selection = field(default_factory=Selection)
invites: dict = field(default_factory=dict) # token -> Invite
friends: dict = field(default_factory=dict) # token -> Friend
@@ -189,7 +190,7 @@ class CassetteState:
d = d or {}
state = cls(display_name=d.get("display_name") or default_display_name(),
avatar=d.get("avatar", ""),
share_same_for_all=bool(d.get("share_same_for_all", False)),
share_same_for_all=bool(d.get("share_same_for_all", True)),
general=Selection.from_dict(d.get("general")),
probing=dict(d.get("probing", {})),
rejected=dict(d.get("rejected", {})),
+22 -1
View File
@@ -20,7 +20,7 @@ from pathlib import Path
import requests
from lintunes import sync_identity
from lintunes import paths, sync_identity
log = logging.getLogger(__name__)
@@ -39,6 +39,27 @@ NO_KEY = "no_key" # we couldn't find a key to send at all
OTHER = "other" # it answered, and said no
# What to tell someone whose Syncthing isn't answering. Linux keeps the
# words it always had (the UI writes its own there); a Mac gets told where
# Syncthing comes from, since nothing on a Mac ships it.
MAC_START_HINT = ("Open the Syncthing app (or run: brew services start "
"syncthing)")
MAC_INSTALL_HINT = ("Don't have Syncthing? Get the Syncthing macOS app from "
"syncthing.net, or install it with Homebrew: brew install "
"--cask syncthing-app (the app) or brew install syncthing "
"(the command-line one).")
def not_running_hint(retry_where: str = "") -> str | None:
"""On a Mac, the next step for "Syncthing isn't running", ending with
``retry_where`` (e.g. "press Retry in Sync Settings ▸ General"). None on
Linux, where each caller keeps its own text."""
if not paths.IS_MAC:
return None
then = f", then {retry_where}." if retry_where else "."
return f"{MAC_START_HINT}{then} {MAC_INSTALL_HINT}"
class SyncthingError(Exception):
"""A step that failed, and what Syncthing (or the socket) said."""
+3 -3
View File
@@ -1,11 +1,11 @@
import json
import os
from pathlib import Path
from lintunes import paths
def config_path() -> Path:
base = os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))
return Path(base) / "lintunes" / "config.json"
return paths.config_dir() / "config.json"
def load_config() -> dict:
+8
View File
@@ -0,0 +1,8 @@
"""DJ mode (Round 93): two decks, a crossfader, tempo sync and vocal stems.
Its own little audio engine, separate from Player: Qt's player can neither
change tempo without changing pitch nor play backwards for a scratch, so a
deck holds its song decoded in memory and the mixer renders both decks into
one QAudioSink. Pure numpy in ``analysis`` and ``audio`` (tested offline);
Qt only in ``output`` (the sink's thread), ``loader`` and the GUI shelf.
"""
+81
View File
@@ -0,0 +1,81 @@
"""Split one song with Spleeter (sherpa-onnx), run inside the instant venv.
<venv>/bin/python -I _spleeter_run.py <model dir> <threads> <song> <out dir>
It can't import LinTunes (``-I``, and the venv doesn't have it), so it is
self-contained: ffmpeg decodes the song to 44.1 kHz float stereo, Spleeter
splits it in pieces (each overlapping the next by a second, crossfaded, so
the seams don't click), and ffmpeg encodes each stem to Opus. Progress goes
to stderr as ``LTPCT <n>`` lines.
"""
import subprocess
import sys
import numpy as np
import sherpa_onnx
RATE = 44100
PIECE = 30 * RATE # Spleeter's own window is ~12 s; 30 s pieces keep progress moving
OVERLAP = RATE # crossfaded between pieces
STEMS = ("vocals", "no_vocals") # sherpa-onnx returns vocals, then accompaniment
def decode(path: str) -> np.ndarray:
done = subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", path, "-map", "0:a:0",
"-vn", "-ac", "2", "-ar", str(RATE), "-f", "f32le", "-"],
capture_output=True)
if done.returncode != 0 or not done.stdout:
lines = done.stderr.decode(errors="replace").strip().splitlines()
raise SystemExit(lines[-1] if lines else "no audio")
data = np.frombuffer(done.stdout, np.float32)
return data[:len(data) - len(data) % 2].reshape(-1, 2).T.copy()
def encode(samples: np.ndarray, path: str):
pcm = np.ascontiguousarray(samples.T, dtype=np.float32).tobytes()
done = subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-f", "f32le",
"-ar", str(RATE), "-ac", "2", "-i", "-", "-c:a", "libopus",
"-b:a", "160k", path], input=pcm, capture_output=True)
if done.returncode != 0:
lines = done.stderr.decode(errors="replace").strip().splitlines()
raise SystemExit(lines[-1] if lines else "ffmpeg couldn't write the stem")
def main():
model_dir, threads, song, out_dir = sys.argv[1:5]
config = sherpa_onnx.OfflineSourceSeparationConfig(
model=sherpa_onnx.OfflineSourceSeparationModelConfig(
spleeter=sherpa_onnx.OfflineSourceSeparationSpleeterModelConfig(
vocals=f"{model_dir}/vocals.fp16.onnx",
accompaniment=f"{model_dir}/accompaniment.fp16.onnx"),
num_threads=int(threads)))
if not config.validate():
raise SystemExit("the Spleeter models are missing")
separator = sherpa_onnx.OfflineSourceSeparation(config)
audio = decode(song)
total = audio.shape[1]
out = [np.zeros_like(audio), np.zeros_like(audio)]
fade_in = np.linspace(0.0, 1.0, OVERLAP, dtype=np.float32)
start = 0
while start < total:
end = min(total, start + PIECE + OVERLAP)
parts = separator.process(sample_rate=RATE, samples=np.ascontiguousarray(audio[:, start:end])).stems
for stem, part in zip(out, parts):
data = np.asarray(part.data, np.float32)[:, :end - start]
if start > 0:
n = min(OVERLAP, data.shape[1])
stem[:, start:start + n] *= 1.0 - fade_in[:n]
data = data.copy()
data[:, :n] *= fade_in[:n]
stem[:, start:start + data.shape[1]] += data
print(f"LTPCT {min(100, round(100 * end / total))}", file=sys.stderr, flush=True)
if end >= total:
break
start = end - OVERLAP
for name, stem in zip(STEMS, out):
encode(stem, f"{out_dir}/{name}.opus")
if __name__ == "__main__":
main()
+172
View File
@@ -0,0 +1,172 @@
"""What a deck needs to know about its song: peaks to draw, its tempo to a
tenth of a BPM, where the beats fall, and how to sync to the other deck.
Tempo comes from ``bpm_detect`` (spectral flux + autocorrelation), but at its
full 0.1 BPM resolution rather than the whole number the library stores: an
integer can be 0.5 BPM out, which drifts a quarter beat in 30 seconds. The
file's own BPM, when there is one, only settles which octave the answer is
in (the detector can land on half or double).
"""
import numpy as np
from lintunes import bpm_detect
PEAKS_PER_SECOND = 200
def peaks(samples: np.ndarray, rate: int,
per_second: int = PEAKS_PER_SECOND) -> np.ndarray:
"""Loudest absolute sample (0..1) in each 1/per_second of a song.
``samples`` is (frames, channels) int16 or float."""
if len(samples) == 0:
return np.zeros(0, np.float32)
data = np.abs(samples.astype(np.float32)).max(axis=1)
if samples.dtype == np.int16:
data /= 32768.0
step = max(1, rate // per_second)
count = len(data) // step
if count == 0:
return np.array([data.max()], np.float32)
return data[:count * step].reshape(count, step).max(axis=1)
def mono_11k(samples: np.ndarray, rate: int = 44100) -> np.ndarray:
"""A mono float32 copy at ~11025 Hz (every 4th frame of a 4-frame
average), the rate bpm_detect works at."""
data = samples.astype(np.float32).mean(axis=1)
if samples.dtype == np.int16:
data /= 32768.0
factor = max(1, round(rate / bpm_detect.SAMPLE_RATE))
count = len(data) // factor
return data[:count * factor].reshape(count, factor).mean(axis=1)
def precise_bpm(mono: np.ndarray, file_bpm: int | None = None) -> float | None:
"""The tempo to 0.1 BPM, folded into the octave the file's BPM names
(when it has one) or into 70–180."""
bpm = bpm_detect.estimate_bpm(mono[:bpm_detect.SAMPLE_RATE
* bpm_detect.MAX_SECONDS])
if bpm is None:
return float(file_bpm) if file_bpm else None
target = float(file_bpm) if file_bpm else None
if target:
candidates = [bpm / 4, bpm / 2, bpm, bpm * 2, bpm * 4]
bpm = min(candidates, key=lambda b: abs(np.log2(b / target)))
else:
while bpm < 70:
bpm *= 2
while bpm > 180:
bpm /= 2
return round(bpm, 1)
def onset_times(mono: np.ndarray, sr: int = bpm_detect.SAMPLE_RATE,
window: int = 128, hop: int = 32) -> tuple[np.ndarray, np.ndarray]:
"""(strength, seconds): how sharply the log energy rises, every ~3 ms.
bpm_detect's spectral flux is right for *tempo* but its 1024-sample
window smears *when* a beat lands by tens of ms; this short energy
window places it within a few. A rise between two windows is timed at
the later window's middle, where an onset entering it peaks."""
data = np.asarray(mono, dtype=np.float64)
if len(data) <= window + hop:
return np.zeros(0), np.zeros(0)
total = np.concatenate([[0.0], np.cumsum(data * data)])
starts = np.arange(0, len(data) - window, hop)
energy = (total[starts + window] - total[starts]) / window
level = np.log1p(1e4 * energy)
rise = np.maximum(np.diff(level), 0.0)
times = (np.arange(len(rise)) + 1) * hop / sr + window / (2 * sr)
return rise, times
def _fold(rise, times, bpm: float, bins: int):
"""Onsets folded over one beat, smoothed around the circle."""
beat = 60.0 / bpm
phase = (times % beat) / beat
folded = np.bincount((phase * bins).astype(int) % bins, weights=rise,
minlength=bins)
kernel = np.array([0.25, 0.5, 1.0, 0.5, 0.25])
padded = np.concatenate([folded[-2:], folded, folded[:2]])
return np.convolve(padded, kernel, mode="valid")
def beat_grid(mono: np.ndarray, bpm: float, bins: int = 256,
search: float = 0.25, step: float = 0.01) -> tuple[float, float]:
"""(bpm, offset): the tempo refined to 0.01 BPM and the seconds from the
start to the first beat. A tempo 0.1 BPM out smears two minutes of beats
across a fifth of a beat, so of the tempos within ``search`` of the
estimate, the one whose folded onsets peak sharpest wins; the peak is
the first beat (within ~4 ms on a synthetic kick track)."""
if not bpm:
return bpm, 0.0
limit = bpm_detect.SAMPLE_RATE * bpm_detect.MAX_SECONDS
rise, times = onset_times(mono[:limit])
if len(rise) == 0 or not np.any(rise):
return bpm, 0.0
best = (-1.0, bpm, None)
for candidate in np.arange(bpm - search, bpm + search + step / 2, step):
smooth = _fold(rise, times, candidate, bins)
sharpness = smooth.max() / max(smooth.mean(), 1e-12)
if sharpness > best[0]:
best = (sharpness, float(candidate), smooth)
_, refined, smooth = best
offset = (int(np.argmax(smooth)) + 0.5) / bins * 60.0 / refined
return round(refined, 2), offset
def beat_offset(mono: np.ndarray, bpm: float) -> float:
"""Seconds to the first beat at exactly ``bpm`` (no refining)."""
if not bpm:
return 0.0
rise, times = onset_times(mono[:bpm_detect.SAMPLE_RATE * bpm_detect.MAX_SECONDS])
if len(rise) == 0:
return 0.0
smooth = _fold(rise, times, bpm, 256)
return (int(np.argmax(smooth)) + 0.5) / 256 * 60.0 / bpm
def sync_ratio(own_bpm: float, target_bpm: float) -> float:
"""The speed that makes ``own_bpm`` play at ``target_bpm``: of the
straight ratio and its half/double, the one nearest normal speed (a
70 BPM song syncs to a 140 BPM one at its own speed, beat on every
other beat)."""
if not own_bpm or not target_bpm:
return 1.0
ratio = target_bpm / own_bpm
# as many octaves as it takes (½× against 2× is two apart)
while ratio > 2 ** 0.5:
ratio /= 2
while ratio < 2 ** -0.5:
ratio *= 2
return ratio
def sync_speed(own_beat_bpm: float, target_beat_bpm: float,
plausible: tuple[float, float] = (0.75, 1.34)) -> float:
"""The speed that plays ``own`` at ``target``, both as the decks count
their beats (the ½×/1×/2× switch already applied). Taken straight when
it's a plausible change of speed; a ratio further out than that means
the two are counted an octave apart, so the nearest octave wins."""
if not own_beat_bpm or not target_beat_bpm:
return 1.0
ratio = target_beat_bpm / own_beat_bpm
if plausible[0] <= ratio <= plausible[1]:
return ratio
return sync_ratio(own_beat_bpm, target_beat_bpm)
def beat_phase(position_s: float, offset_s: float, bpm: float) -> float:
"""Where in its beat a song is, 0..1."""
if not bpm:
return 0.0
return ((position_s - offset_s) * bpm / 60.0) % 1.0
def phase_shift(own_phase: float, target_phase: float, own_bpm: float) -> float:
"""Seconds (of the song's own time) to move it so its beat lines up with
the target's, by the shortest way: never more than half a beat."""
if not own_bpm:
return 0.0
delta = (target_phase - own_phase + 0.5) % 1.0 - 0.5
return delta * 60.0 / own_bpm
+465
View File
@@ -0,0 +1,465 @@
"""The decks and the mix, as pure numpy: render N frames, get N frames.
A deck holds its song in memory as int16 stereo at 44.1 kHz (about 50 MB for
five minutes) — plus, once Demucs has split it, the vocals and the
instrumental, which the vocals slider blends. It plays three ways:
- **keep pitch** (the default): WSOLA time-stretch, so a sped-up song stays
in its key. 1024-frame windows, half overlapping; each next window is the
one within ±256 frames of where the tempo says to read that best continues
the last (normalised cross-correlation), so the seams don't click.
- **pitch follows tempo** (Keep pitch off): plain varispeed, read at the
speed with linear interpolation, like a turntable's pitch fader.
- **scratching**: varispeed at whatever rate the hand on the record gives,
backwards included; letting go goes straight back to normal speed.
The mixer adds both decks after the crossfader's constant-power curve and the
master volume, and clips. Everything here runs on the sink's thread; the GUI
only sets plain attributes (one assignment each, so never torn).
"""
from collections import deque
import numpy as np
RATE = 44100
CHANNELS = 2
WINDOW = 1024
HOP = WINDOW // 2
SEARCH = 256
SPEED_RANGE = 0.08 # the speed faders' ±8 %
_HANN = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(WINDOW) / WINDOW)).astype(np.float32)
class Source:
"""A song in memory: the original, and the stems once they exist."""
def __init__(self, original: np.ndarray, rate: int = RATE):
self.original = original # (frames, 2) int16
self.rate = rate
self.vocals: np.ndarray | None = None
self.instrumental: np.ndarray | None = None
@property
def frames(self) -> int:
return len(self.original)
@property
def seconds(self) -> float:
return self.frames / self.rate
def has_stems(self) -> bool:
return self.vocals is not None and self.instrumental is not None
def read(self, start: int, count: int, vocal_mix: float) -> np.ndarray:
"""``count`` frames from ``start`` as float32, silence past either
end. ``vocal_mix`` −1 vocals only, 0 both, +1 instrumental only."""
out = np.zeros((count, CHANNELS), np.float32)
lo, hi = max(0, start), min(self.frames, start + count)
if hi <= lo:
return out
dest = slice(lo - start, hi - start)
if self.has_stems() and abs(vocal_mix) > 1e-3:
v_gain = min(1.0, 1.0 - vocal_mix)
i_gain = min(1.0, 1.0 + vocal_mix)
n = min(hi, len(self.vocals), len(self.instrumental))
if n > lo:
d = slice(lo - start, n - start)
out[d] = (self.vocals[lo:n].astype(np.float32) * v_gain
+ self.instrumental[lo:n].astype(np.float32) * i_gain)
else:
out[dest] = self.original[lo:hi]
out *= 1.0 / 32768.0
return out
class Deck:
"""One turntable. Attributes the GUI sets: ``playing``, ``speed``,
``keep_pitch``, ``vocal_mix``, ``scratch_rate`` (None when no hand is on
the record). ``position`` is in source frames (float)."""
def __init__(self, name: str):
self.name = name
self.source: Source | None = None
self.position = 0.0
self.playing = False
self.speed = 1.0
self.keep_pitch = True
self.vocal_mix = 0.0
self.scratch_rate: float | None = None
self.volume = 1.0 # the deck's own fader, before the crossfader
self.loop: tuple[int, int] | None = None # (start, end) source frames
self.ended = False # reached the end by playing (GUI clears)
self._ola: np.ndarray | None = None # overlap-add tail
self._last: int | None = None # where the last window was read
self._pending: np.ndarray | None = None # stretched, not yet emitted
self._mode = None
def load(self, source: Source | None):
self.playing = False
self.loop = None
self.source = source
self.position = 0.0
self.ended = False
self.scratch_rate = None
self._reset()
def seek(self, frame: float):
if self.source is None:
return
self.position = float(max(0.0, min(frame, self.source.frames - 1)))
self._reset()
def _reset(self):
self._ola = None
self._last = None
self._pending = None
# ---- rendering ----
def render(self, count: int) -> np.ndarray:
"""``count`` frames out. With a loop set, playback that crosses its
end jumps back to its start — rendered in pieces that stop at the
end, so even a 1/32-beat loop lands where it should."""
loop = self.loop
if loop is None or self.scratch_rate is not None or not self.playing:
return self._render(count)
start, end = loop
pieces = []
left = count
while left > 0:
speed = max(self.speed, 1e-3)
n = left
if self.position < end:
to_end = int(np.ceil((end - self.position) / speed))
n = max(1, min(left, to_end))
before = self.position
pieces.append(self._render(n))
left -= n
if before < end <= self.position:
self.position -= (end - start)
if not self.playing:
break
out = np.concatenate(pieces) if pieces else np.zeros((0, CHANNELS), np.float32)
if len(out) < count:
out = np.concatenate([out, np.zeros((count - len(out), CHANNELS), np.float32)])
return out
def _render(self, count: int) -> np.ndarray:
src = self.source
if src is None:
return np.zeros((count, CHANNELS), np.float32)
if self.scratch_rate is not None:
return self._varispeed(count, self.scratch_rate, "scratch")
if not self.playing:
self._mode = None
return np.zeros((count, CHANNELS), np.float32)
if self.position >= src.frames:
self.playing = False
self.ended = True
return np.zeros((count, CHANNELS), np.float32)
if self.keep_pitch and abs(self.speed - 1.0) > 1e-4:
return self._stretch(count)
if abs(self.speed - 1.0) <= 1e-4:
return self._straight(count)
return self._varispeed(count, self.speed, "vari")
def _straight(self, count: int) -> np.ndarray:
if self._mode != "straight":
self._mode = "straight"
self._reset()
start = int(round(self.position))
out = self.source.read(start, count, self.vocal_mix)
self.position = start + count
return out
def _varispeed(self, count: int, rate: float, mode: str) -> np.ndarray:
if self._mode != mode:
self._mode = mode
self._reset()
src = self.source
steps = self.position + rate * np.arange(count, dtype=np.float64)
lo = int(np.floor(steps.min()))
hi = int(np.ceil(steps.max())) + 2
block = src.read(lo, hi - lo, self.vocal_mix)
idx = steps - lo
i0 = np.clip(np.floor(idx).astype(np.int64), 0, len(block) - 2)
frac = (idx - i0)[:, None].astype(np.float32)
out = block[i0] * (1 - frac) + block[i0 + 1] * frac
self.position = float(self.position + rate * count)
if self.position < 0:
self.position = 0.0
if mode == "vari" and self.position >= src.frames:
self.playing = False
self.ended = True
if mode == "scratch":
self.position = min(self.position, src.frames - 1.0)
return out
def _stretch(self, count: int) -> np.ndarray:
"""WSOLA: emit HOP frames per window until ``count`` are out."""
if self._mode != "stretch":
self._mode = "stretch"
self._reset()
src = self.source
pieces = []
made = 0
if self._pending is not None and len(self._pending):
pieces.append(self._pending)
made += len(self._pending)
while made < count:
nominal = int(round(self.position))
if self._last is None:
start = nominal
else:
natural = src.read(self._last + HOP, WINDOW, self.vocal_mix).mean(axis=1)
region = src.read(nominal - SEARCH, WINDOW + 2 * SEARCH,
self.vocal_mix).mean(axis=1)
start = nominal - SEARCH + _best_offset(region, natural)
frame = src.read(start, WINDOW, self.vocal_mix) * _HANN[:, None]
if self._ola is None:
self._ola = np.zeros((WINDOW, CHANNELS), np.float32)
self._ola += frame
pieces.append(self._ola[:HOP].copy())
made += HOP
self._ola = np.concatenate(
[self._ola[HOP:], np.zeros((HOP, CHANNELS), np.float32)])
self._last = start
self.position += HOP * self.speed
if self.position >= src.frames:
self.playing = False
self.ended = True
break
out = np.concatenate(pieces) if pieces else np.zeros((0, CHANNELS), np.float32)
if len(out) < count:
out = np.concatenate([out, np.zeros((count - len(out), CHANNELS), np.float32)])
self._pending = None
else:
self._pending = out[count:]
out = out[:count]
return out
def _best_offset(region: np.ndarray, natural: np.ndarray) -> int:
"""The offset into ``region`` where ``natural`` fits best (normalised
cross-correlation over the window's first half)."""
probe = natural[:HOP]
if not np.any(probe):
return SEARCH
corr = np.correlate(region[:len(region) - WINDOW + HOP], probe, mode="valid")
energy = np.convolve(region[:len(region) - WINDOW + HOP] ** 2,
np.ones(len(probe)), mode="valid")
score = corr / np.sqrt(np.maximum(energy, 1e-9))
return int(np.argmax(score))
def crossfade_gains(x: float) -> tuple[float, float]:
"""Constant power: 0 = all A, 1 = all B, the middle ~71 % each."""
x = min(1.0, max(0.0, x))
return float(np.cos(x * np.pi / 2)), float(np.sin(x * np.pi / 2))
class Horn:
"""The air horn: the classic rap horn, one continuous blast.
The recording (``sounds/airhorn.mp3``, trav's pick — see
lintunes/sounds/CREDITS.md) is one blast: a swoop from ~420 Hz down to
~305 Hz over its first 0.35 s ("BWAAA"), then one steady tone (302 Hz,
within 1 %) until 1.62 s and a short natural end.
- **click**: the whole recording, as on the web page it came from.
- **held**: past ``LOOP``'s end it laps back to its start through a
``XFADE`` crossfade. The steady part is reeds beating, not a
repeating wave (seams correlate ~0.3 at best), so the crossfade is
equal *loudness* for that correlation, measured in ``set_sample``.
- **release**: a blast that never lapped plays out naturally; one that
did jumps (``JUMP``, matched to the nearest wave cycle) to the loop
end, so the recording's own ending follows at once.
- **press** again: a fresh blast; one still sounding is cut in ``CUT``.
"""
ONSET = 0.14 # s: just before the blast starts in the file
LOOP = (0.729, 1.450) # s: the steady stretch it laps within
XFADE = 0.20 # s: the lap's crossfade
JUMP = 0.04 # s: release → the ending
CUT = 0.025
VOICES = 4
LEVEL = 1.0
def __init__(self, sample: np.ndarray | None = None):
self.on = False
self._src = None
self._voices: list[dict] = []
if sample is not None:
self.set_sample(sample)
def set_sample(self, sample: np.ndarray):
"""``sample``: (frames, 2) int16 or float."""
src = sample.astype(np.float32)
if sample.dtype == np.int16:
src /= 32768.0
src /= float(np.abs(src).max()) or 1.0
n = len(src)
a, b = (min(n - 1, int(t * RATE)) for t in self.LOOP)
if b - a < RATE // 4: # some other, shorter sound: lap its middle
a, b = n // 4, n - n // 20
xf = min(int(self.XFADE * RATE), (b - a) // 2, a)
# The lap's seam, baked into a copy: the stretch's last xf frames
# fade from themselves into what comes before its start, so b → a
# lands on a continuation. Scaled for the two sides' correlation,
# so the seam is neither a dip nor a swell.
laps = src.copy()
if xf > 0:
tail, head = src[b - xf:b], src[a - xf:a]
corr = float((tail * head).sum()
/ (np.sqrt((tail * tail).sum() * (head * head).sum()) or 1.0))
t = np.linspace(0, 1, xf, dtype=np.float32)[:, None]
fo, fi = np.cos(t * np.pi / 2), np.sin(t * np.pi / 2)
laps[b - xf:b] = (tail * fo + head * fi) / np.sqrt(1 + 2 * corr * fo * fi)
self._src, self._laps, self._loop = src, laps, (a, b)
self._onset = min(int(self.ONSET * RATE), a)
# ---- the button ----
def press(self):
self.on = True
for voice in self._voices:
if voice["state"] != "cut":
voice.update(state="cut", fade=0)
self._voices.append({"state": "held", "pos": self._onset,
"lapped": False, "fade": 0})
del self._voices[:-self.VOICES]
def release(self):
self.on = False
if self._src is None:
return
a, b = self._loop
xf = min(int(self.XFADE * RATE), (b - a) // 2, a)
for voice in self._voices:
if voice["state"] != "held":
continue
if voice["lapped"]:
voice.update(state="jump", fade=0, to=self._match(voice["pos"], b))
elif voice["pos"] >= b - xf: # mid-seam: back onto the original
voice.update(state="jump", fade=0, to=voice["pos"])
else:
voice["state"] = "free"
def _match(self, pos: int, near: int) -> int:
"""Where around ``near`` the original best continues what the
held voice is playing at ``pos`` (within one wave cycle)."""
win = int(self.JUMP * RATE)
here = self._laps[pos:pos + win, 0]
best, at = -2.0, near
for to in range(max(0, near - 160), min(len(self._src) - win, near + 160)):
there = self._src[to:to + win, 0]
c = float((here * there).sum())
if c > best:
best, at = c, to
return at
# ---- sound ----
def _read(self, voice: dict, n: int, source: np.ndarray) -> np.ndarray:
"""n frames from the voice's position; a held voice laps."""
pos = voice["pos"]
if voice["state"] == "held":
a, b = self._loop
out = np.empty((n, CHANNELS), np.float32)
done = 0
while done < n:
take = min(n - done, b - pos)
out[done:done + take] = source[pos:pos + take]
done += take
pos += take
if pos >= b:
pos = a
voice["lapped"] = True
voice["pos"] = pos
return out
frames = source[pos:pos + n]
voice["pos"] = pos + len(frames)
if len(frames) < n:
frames = np.concatenate([frames, np.zeros((n - len(frames), CHANNELS), np.float32)])
return frames
def render(self, count: int) -> np.ndarray | None:
if self._src is None or not self._voices:
return None
out = np.zeros((count, CHANNELS), np.float32)
cut = max(1, int(self.CUT * RATE))
jump = max(1, int(self.JUMP * RATE))
end = len(self._src)
kept = []
for voice in self._voices:
done = 0
alive = True
while done < count and alive:
room = count - done
state = voice["state"]
if state == "held":
n = room
out[done:] += self._read(voice, n, self._laps)
elif state == "free":
n = min(room, end - voice["pos"])
out[done:done + n] += self._read(voice, n, self._src)
alive = voice["pos"] < end
elif state == "jump": # held sound out, the ending in
n = min(room, jump - voice["fade"])
k = (voice["fade"] + np.arange(n)) / jump
old = self._laps[voice["pos"]:voice["pos"] + n]
new = self._src[voice["to"]:voice["to"] + n]
m = min(len(old), len(new))
out[done:done + m] += (old[:m] * np.cos(k[:m, None] * np.pi / 2)
+ new[:m] * np.sin(k[:m, None] * np.pi / 2))
voice["pos"] += n
voice["to"] += n
voice["fade"] += n
if voice["fade"] >= jump:
voice.update(state="free", pos=voice["to"])
if m < n:
alive = False
else: # cut
n = min(room, cut - voice["fade"])
pos = min(voice["pos"], end - n)
k = voice["fade"] + np.arange(1, n + 1)
out[done:done + n] += self._laps[pos:pos + n] * np.clip(1 - k / cut, 0, 1)[:, None]
voice["pos"] = pos + n
voice["fade"] += n
alive = voice["fade"] < cut
done += n
if alive:
kept.append(voice)
self._voices = kept
return out * self.LEVEL
class Mixer:
def __init__(self):
self.a = Deck("A")
self.b = Deck("B")
self.crossfader = 0.5
self.master = 1.0
self.horn = Horn()
# What was rendered, for the visualizer: (first frame, mono) blocks,
# appended here (the sink's thread), drained by the GUI.
self.tap = deque(maxlen=128)
self.rendered = 0
def deck_gain(self, deck: Deck) -> float:
a, b = crossfade_gains(self.crossfader)
return (a if deck is self.a else b) * deck.volume * self.master
def render(self, count: int) -> np.ndarray:
ga, gb = crossfade_gains(self.crossfader)
out = self.a.render(count) * (ga * self.a.volume * self.master)
out += self.b.render(count) * (gb * self.b.volume * self.master)
horn = self.horn.render(count)
if horn is not None:
out += horn * self.master
np.clip(out, -1.0, 1.0, out=out)
self.tap.append((self.rendered, out.mean(axis=1)))
self.rendered += count
return out
+185
View File
@@ -0,0 +1,185 @@
"""Instant vocals: Spleeter's 2-stem model, ~20× faster than Demucs here.
Demucs takes minutes a song on this laptop's CPU (Round 94); Spleeter took
11 s for a 4-minute song while Demucs was running beside it. It sounds
rougher (watery vocals, some bleed), so it's opt-in: Preferences › DJ has a
download button, and a deck can swap between the two splits of a song.
The original ``spleeter`` package needs TensorFlow and Python ≤3.11, so this
runs Spleeter's own weights as ONNX through **sherpa-onnx** (onnxruntime, a
~125 MB venv at ``paths.data_dir()/spleeter``, never a pip dependency
of LinTunes). The fp16 models (35 MB) come from sherpa-onnx's GitHub release
and are refused unless their SHA-256 is the one pinned here, the
``airplay/cli.py`` rule. The release's own checksum.txt is stale for this
file (it names a different hash), so this one was measured on download.
"""
import hashlib
import os
import shutil
import subprocess
import tarfile
import tempfile
import threading
import urllib.request
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
from lintunes.airplay import cli
from lintunes.dj import venv_tool
SHERPA_VERSION = "2.0.1"
MODEL_URL = ("https://github.com/k2-fsa/sherpa-onnx/releases/download/"
"source-separation-models/sherpa-onnx-spleeter-2stems-fp16.tar.bz2")
MODEL_SHA256 = "d54561979bd2e08a51e7dbd99ac36bb47564e089eefd403636dbca93e811bba2"
MODEL_FILES = ("vocals.fp16.onnx", "accompaniment.fp16.onnx")
DOWNLOAD_MB = 160 # the wheels (~125 MB installed) and the models
RUNNER = Path(__file__).with_name("_spleeter_run.py")
class Cancelled(Exception):
pass
def venv_dir() -> Path:
return paths.data_dir() / "spleeter"
def python() -> Path:
return venv_dir() / "bin" / "python"
def model_dir() -> Path:
return venv_dir() / "models"
def available() -> bool:
return python().is_file() and all((model_dir() / f).is_file() for f in MODEL_FILES)
def threads() -> int:
return os.cpu_count() or 4
def remove():
shutil.rmtree(venv_dir(), ignore_errors=True)
def _fetch(url: str) -> bytes:
with urllib.request.urlopen(url, timeout=120,
context=cli.https_context()) as response:
return response.read()
def install_models(fetch=None):
"""Download, check and unpack the models. Raises OSError."""
data = (fetch or _fetch)(MODEL_URL)
if hashlib.sha256(data).hexdigest() != MODEL_SHA256:
raise OSError("the downloaded Spleeter models didn't match their checksum")
target = model_dir()
target.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="lintunes-spleeter-") as tmp:
archive = Path(tmp) / "models.tar.bz2"
archive.write_bytes(data)
with tarfile.open(archive) as tar:
for member in tar.getmembers():
name = Path(member.name).name
if name in MODEL_FILES and member.isfile():
source = tar.extractfile(member)
(target / name).write_bytes(source.read())
missing = [f for f in MODEL_FILES if not (target / f).is_file()]
if missing:
raise OSError(f"the Spleeter download had no {missing[0]}")
class InstantSetup(QObject):
"""Preferences' download button: makes the venv, installs sherpa-onnx,
fetches the models, on a daemon thread."""
progress = pyqtSignal(str)
finished = pyqtSignal()
failed = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._thread = None
def busy(self) -> bool:
return self._thread is not None and self._thread.is_alive()
def start(self):
self._thread = threading.Thread(target=self._run, daemon=True,
name="lintunes-spleeter-setup")
self._thread.start()
def _run(self):
try:
venv = venv_dir()
if venv_tool.uses_uv():
# A Mac (or the built app) has no Python to make a venv
# with; uv brings one (venv_tool's docstring).
self.progress.emit("Downloading a Python for it…")
venv_tool.ensure_uv()
env = venv_tool.run_env()
if not python().is_file():
self.progress.emit("Making its own Python environment…")
venv.parent.mkdir(parents=True, exist_ok=True)
self._call(venv_tool.create_command(venv), env)
self.progress.emit("Downloading sherpa-onnx…")
self._call(venv_tool.install_command(
venv, [f"sherpa-onnx=={SHERPA_VERSION}", "numpy"]), env)
self.progress.emit("Downloading the Spleeter models…")
install_models()
except (OSError, subprocess.SubprocessError) as e:
self.failed.emit(str(e) or type(e).__name__)
return
self.finished.emit()
@staticmethod
def _call(cmd, env=None):
done = subprocess.run(cmd, capture_output=True, text=True, timeout=1800,
env=env)
if done.returncode != 0:
lines = (done.stderr or done.stdout).strip().splitlines()
raise OSError(lines[-1] if lines else f"{cmd[2]} failed")
def split(path: str, out_dir: Path, progress=None,
cancel: threading.Event | None = None):
"""Write ``vocals.opus`` and ``no_vocals.opus`` for ``path`` into
``out_dir`` (blocking). Raises OSError, or Cancelled."""
if not available():
raise OSError("instant vocal splitting isn't set up on this computer")
if not RUNNER.is_file(): # a built app that left the helper out
raise OSError(f"LinTunes is missing {RUNNER.name}")
cmd, preexec = venv_tool.niced(
[str(python()), "-I", str(RUNNER), str(model_dir()), str(threads()), path, str(out_dir)],
5)
process = subprocess.Popen(
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
env=venv_tool.child_env(), preexec_fn=preexec)
if cancel is not None:
def watch():
while process.poll() is None:
if cancel.wait(0.2):
process.kill()
return
threading.Thread(target=watch, daemon=True, name="lintunes-spleeter-watch").start()
tail = []
for line in process.stderr:
if line.startswith("LTPCT "):
if progress is not None:
try:
progress(int(line.split()[1]))
except ValueError:
pass
else:
tail = (tail + [line.strip()])[-20:]
code = process.wait()
if cancel is not None and cancel.is_set():
raise Cancelled()
if code != 0:
lines = [t for t in tail if t]
raise OSError(lines[-1] if lines else "Spleeter failed")
+82
View File
@@ -0,0 +1,82 @@
"""Getting a song onto a deck: decode, analyse, report — off the GUI thread.
ffmpeg (the CLI, as everywhere else) decodes the whole file to int16 stereo
at 44.1 kHz; then the waveform's peaks, the tempo to 0.1 BPM and the first
beat's offset are worked out from that copy (no second decode). A five-
minute song takes about a second. The result arrives as one Qt signal.
"""
import subprocess
import threading
from dataclasses import dataclass
import numpy as np
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes.dj import analysis
from lintunes.dj.audio import CHANNELS, RATE, Source
@dataclass
class Loaded:
track_id: int
source: Source
peaks: np.ndarray
bpm: float | None # precise, what the deck syncs with
offset: float # seconds to the first beat
detected: bool # bpm came from the audio, not the file
def decode(path: str) -> np.ndarray:
"""The whole file as (frames, 2) int16 at 44.1 kHz. Raises OSError."""
cmd = ["ffmpeg", "-nostdin", "-v", "error", "-i", str(path), "-map", "0:a:0",
"-vn", "-ac", str(CHANNELS), "-ar", str(RATE), "-f", "s16le", "-"]
try:
result = subprocess.run(cmd, capture_output=True, timeout=300)
except (OSError, subprocess.TimeoutExpired) as e:
raise OSError(f"ffmpeg could not run: {e}") from e
if result.returncode != 0 or not result.stdout:
detail = result.stderr.decode(errors="replace").strip().splitlines()
raise OSError(detail[-1] if detail else "no audio")
data = np.frombuffer(result.stdout, dtype=np.int16)
return data[:len(data) - len(data) % CHANNELS].reshape(-1, CHANNELS)
def load(track_id: int, path: str, file_bpm: int | None) -> Loaded:
samples = decode(path)
mono = analysis.mono_11k(samples, RATE)
bpm = analysis.precise_bpm(mono, file_bpm)
offset = 0.0
if bpm:
bpm, offset = analysis.beat_grid(mono, bpm)
return Loaded(track_id=track_id, source=Source(samples), peaks=analysis.peaks(samples, RATE),
bpm=bpm, offset=offset, detected=not file_bpm and bpm is not None)
class DeckLoader(QObject):
"""One load at a time per deck; a newer request makes an older result
stale (``ticket``), so a fast second drag wins."""
loaded = pyqtSignal(str, object) # deck name, Loaded
failed = pyqtSignal(str, int, str) # deck name, track id, why
def __init__(self, name: str, parent=None):
super().__init__(parent)
self.name = name
self._ticket = 0
def request(self, track_id: int, path: str, file_bpm: int | None):
self._ticket += 1
ticket = self._ticket
def work():
try:
result = load(track_id, path, file_bpm)
except Exception as e: # noqa: BLE001 — reported, not raised
if ticket == self._ticket:
self.failed.emit(self.name, track_id, str(e) or type(e).__name__)
return
if ticket == self._ticket:
self.loaded.emit(self.name, result)
threading.Thread(target=work, daemon=True, name="lintunes-dj-load").start()
+175
View File
@@ -0,0 +1,175 @@
"""The mixer, heard: a QAudioSink fed from its own thread.
The sink lives in a QThread with its own event loop; a 5 ms timer there tops
its buffer up with whatever the mixer renders, so the GUI thread painting
records and waveforms at 60 fps can't starve it. About 100 ms is buffered:
enough to ride out a busy GUI, short enough that the crossfader and a hand
on a record still feel immediate. Created only when DJ mode opens (a
QAudioOutput made before the main window deadlocks Qt 6.10, and nothing
here should exist for someone who never opens it).
"""
import numpy as np
from PyQt6.QtCore import QObject, QThread, QTimer, pyqtSignal, pyqtSlot
from PyQt6.QtMultimedia import QAudio, QAudioFormat, QAudioSink, QMediaDevices
from lintunes import paths
from lintunes.dj.audio import CHANNELS, RATE
BUFFER_MS = 100
TICK_MS = 5
BYTES_PER_FRAME = 2 * CHANNELS
def _converts_any_rate() -> bool:
"""CoreAudio's output unit converts rate and sample format itself, and
Qt's Mac sink goes through it; a device that reports only 48 kHz (or a
Bluetooth headset in call mode) still plays 44.1 kHz stereo there. So on
a Mac an unsupported-looking format is tried anyway. Linux keeps the
check it always had."""
return paths.IS_MAC
class _Pump(QObject):
failed = pyqtSignal(str)
def __init__(self, mixer):
super().__init__()
self.mixer = mixer
self.sink = None
self.io = None
self.timer = None
self.queued_frames = 0
self.device_id = b""
@pyqtSlot()
def start(self):
# Follow the system's output: a sink is opened on one device, and
# when that goes (headphones in, Bluetooth on) Qt doesn't move it —
# it just stops, and the decks went silent until DJ mode reopened.
if getattr(self, "devices", None) is None:
self.devices = QMediaDevices()
self.devices.audioOutputsChanged.connect(self._outputs_changed)
self.timer = QTimer()
self.timer.setInterval(TICK_MS)
self.timer.timeout.connect(self._fill)
self._open()
self.timer.start()
def _open(self) -> bool:
fmt = QAudioFormat()
fmt.setSampleRate(RATE)
fmt.setChannelCount(CHANNELS)
fmt.setSampleFormat(QAudioFormat.SampleFormat.Int16)
device = QMediaDevices.defaultAudioOutput()
if device.isNull() or not (device.isFormatSupported(fmt)
or _converts_any_rate()):
self.failed.emit("this computer's sound output can't play 44.1 kHz stereo")
return False
self.sink = QAudioSink(device, fmt)
self.sink.setBufferSize(int(RATE * BUFFER_MS / 1000) * BYTES_PER_FRAME)
self.io = self.sink.start()
self.device_id = bytes(device.id())
return True
def _close(self):
if self.sink is not None:
self.sink.stop()
self.sink = self.io = None
@pyqtSlot()
def _reopen(self):
"""The default output changed (or this one broke): reopen on it."""
self._close()
self._open()
@pyqtSlot()
def _outputs_changed(self):
if self.timer is not None: # stopped: nothing to move
self._reopen()
def _fill(self):
if self.sink is None or self.io is None:
# No device a moment ago; try again about once a second.
self._retry = getattr(self, "_retry", 0) + 1
if self._retry * TICK_MS >= 1000:
self._retry = 0
self._open()
return
if self.sink.error() != QAudio.Error.NoError:
self._reopen()
return
current = QMediaDevices.defaultAudioOutput()
if not current.isNull() and bytes(current.id()) != self.device_id:
self._reopen() # the default moved without telling us
return
free = self.sink.bytesFree() // BYTES_PER_FRAME
frames = free - free % 64
if frames > 0:
pcm = self.mixer.render(frames)
data = (pcm * 32767.0).astype(np.int16).tobytes()
self.io.write(data)
size = self.sink.bufferSize() // BYTES_PER_FRAME
self.queued_frames = max(0, size - self.sink.bytesFree() // BYTES_PER_FRAME)
@pyqtSlot()
def stop(self):
if self.timer is not None:
self.timer.stop()
self._close()
self.timer = None
class DjOutput(QObject):
"""Owns the thread; ``latency_frames`` is how far behind what has been
rendered the speakers are, for drawing what is *heard*."""
failed = pyqtSignal(str)
_go = pyqtSignal()
_halt = pyqtSignal()
def __init__(self, mixer, parent=None):
super().__init__(parent)
self._thread = QThread()
self._thread.setObjectName("lintunes-dj-audio")
self._pump = _Pump(mixer)
self._pump.moveToThread(self._thread)
self._go.connect(self._pump.start)
self._halt.connect(self._pump.stop)
self._pump.failed.connect(self.failed)
self._running = False
# However the app ends, the thread ends first (a QThread destroyed
# while running aborts the process).
from PyQt6.QtCore import QCoreApplication
app = QCoreApplication.instance()
if app is not None:
app.aboutToQuit.connect(self.shutdown)
@property
def latency_frames(self) -> int:
return self._pump.queued_frames
def start(self):
if self._running:
return
self._running = True
if not self._thread.isRunning():
self._thread.start()
self._go.emit()
def stop(self):
"""Silence: the sink closes, the thread stays for the next start.
Qt's PipeWire backend never frees what it set up in a thread that
ends — ~24 file descriptors a thread — so one per DJ-mode opening
ran the app out of them (limit 1024) and the sink's start crashed."""
if not self._running:
return
self._running = False
self._halt.emit()
def shutdown(self):
"""The app is ending: the thread ends too."""
self.stop()
if self._thread.isRunning():
self._thread.quit()
self._thread.wait(2000)
+74
View File
@@ -0,0 +1,74 @@
"""Prepare for DJ: the slow part of a deck load, done ahead for many songs.
For each song: its BPM, worked out and saved to the file when it has none
(the GUI applies it, as Calculate BPM does), and its vocals/instrumental
split with the engine and model set in Preferences › DJ (Instant, or
Demucs's model) — so a whole playlist
can be split with the slow, best model overnight and every deck load after
that is instant. One song at a time on a daemon thread, ExportWorker's
shape: ``progress``, ``bpm_found``, ``finished``; ``cancel`` stops between
songs and kills a split in progress.
"""
import threading
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import bpm_detect
from lintunes.dj import stems
class DjPrepWorker(QObject):
progress = pyqtSignal(int, int, str) # done, total, what's happening
bpm_found = pyqtSignal(int, int) # track id, bpm
finished = pyqtSignal(dict) # {"done", "split", "bpm", "failed", "cancelled"}
def __init__(self, items, model: str, gentle: bool, parent=None):
"""``items``: (track id, path, label, has bpm)."""
super().__init__(parent)
self._items = list(items)
self._model = model
self._gentle = gentle
self._cancel = threading.Event()
self._thread = None
def busy(self) -> bool:
return self._thread is not None and self._thread.is_alive()
def cancel(self):
self._cancel.set()
def start(self):
self._thread = threading.Thread(target=self._run, daemon=True,
name="lintunes-dj-prepare")
self._thread.start()
def _run(self):
summary = {"done": 0, "split": 0, "bpm": 0, "failed": 0, "cancelled": False}
total = len(self._items)
for i, (track_id, path, label, has_bpm) in enumerate(self._items):
if self._cancel.is_set():
summary["cancelled"] = True
break
try:
if not has_bpm:
self.progress.emit(i, total, f"BPM · {label}")
bpm = bpm_detect.detect_file(path)
if bpm is not None:
self.bpm_found.emit(track_id, bpm)
summary["bpm"] += 1
if (stems.engine_ready(stems.engine_of(self._model))
and stems.cached(path, self._model) is None):
def tick(percent, i=i, label=label):
self.progress.emit(i, total, f"Vocals {percent}% · {label}")
self.progress.emit(i, total, f"Vocals · {label}")
stems.split(path, self._model, self._gentle, tick, self._cancel)
summary["split"] += 1
summary["done"] += 1
except stems.Cancelled:
summary["cancelled"] = True
break
except Exception: # noqa: BLE001 — counted, the batch goes on
summary["failed"] += 1
self.progress.emit(total, total, "")
self.finished.emit(summary)
+615
View File
@@ -0,0 +1,615 @@
"""Vocals and instrumental, for the decks' vocals sliders: Demucs.
Nothing separates a voice from a mix in real time on a laptop, so a song is
split once, in the background, and kept:
``paths.cache_dir()/stems/<key>/<model>/{vocals,no_vocals}.opus``
(machine-local, never the synced data dir). A cached song's slider works the
moment it loads, and a deck uses the best split it finds whatever model made
it. (Round 93's first splits sit directly in ``<key>/``; they were htdemucs.)
The key is the song's **audio**, not its file (Round 100): a hash of the
audio packets (``ffmpeg -c copy -f hash``, ~0.2 s, no decoding), so a tag
edit or a move doesn't lose the split. It used to be path + size + mtime,
and loading a song with no BPM *writes* its BPM tag — so every such split
was orphaned the moment it was made. ``index.json`` remembers path + size +
mtime → key, so the hash runs once per version of a file; a folder still
under its old path key is renamed to the audio key when found.
The cache is held to ``config.json``'s ``dj_stem_cache_gb`` (1 GB unless
set; this machine's disk, so not a synced pref): after each split, the songs
used longest ago go first. Using a split (``cached``) counts as using it.
Demucs runs as a runtime tool, never a pip dependency of LinTunes: PyTorch is
~1 GB, so it lives in its own venv at ``paths.data_dir()/demucs``
(``setup_command`` makes it on Linux; on a Mac ``DemucsSetup``, with uv), and LinTunes runs ``<venv>/bin/python -m
demucs``. It is *the* CPU hog in LinTunes (Round 94: htdemucs took 29 s for
40 s of audio on all 8 cores — several hot minutes a song), so it always
runs niced, and "gentle" (Preferences › DJ, the default) caps it at a
quarter of the cores: measured only ~20 % slower, far cooler. Which model is
a Preferences choice too (``MODELS``). Progress is read off its tqdm bar.
One split at a time: two would only halve each other's speed.
Round 113: an **Instant** tier too (``instant.py``, Spleeter as ONNX), opt-in
from Preferences › DJ. It's the lowest tier, so a deck still takes a Demucs
split when one is cached, and it runs on its own ``StemSplitter`` so an
impatient swap never waits behind Demucs. Every split is cached as **Opus**
(160 kbps, ~1/7 of the FLAC Demucs writes; ffmpeg decodes it back
sample-aligned with the original); older FLAC splits still read.
"""
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
import tempfile
import threading
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
from lintunes.config import load_config
from lintunes.dj import instant, venv_tool
# id → (label, what it costs). Best first: a deck uses the best split it has.
# Measured on this laptop (Round 94, 40 s of audio, 2 threads): htdemucs
# 35 s, at overlap 0.1 27 s; hdemucs_mmi 42 s and mdx 156 s were slower,
# so no other Demucs model is a "fast" one — fewer overlapping windows is.
MODELS = {
"htdemucs_ft": ("Best", "4 fine-tuned models: cleanest, about 4× slower"),
"htdemucs": ("Balanced", "about as long as the song plays"),
"htdemucs_fast": ("Fast", "the same model, fewer overlapping windows: "
"~25 % quicker, very slightly rougher"),
}
# id → the demucs command-line arguments that make it
_ARGS = {
"htdemucs_ft": ["-n", "htdemucs_ft"],
"htdemucs": ["-n", "htdemucs"],
"htdemucs_fast": ["-n", "htdemucs", "--overlap", "0.1"],
}
DEFAULT_MODEL = "htdemucs"
INSTANT = "spleeter" # instant.py's tier, below every Demucs model
TIERS = list(MODELS) + [INSTANT] # best first
HQ, FAST = "hq", "instant" # the two engines, as StemSplitter and the decks name them
LEGACY_MODEL = "htdemucs" # Round 93's splits, made before models had folders
STEMS = ("vocals", "no_vocals")
_PERCENT = re.compile(r"(\d{1,3})%\|")
class Cancelled(Exception):
pass
def venv_dir() -> Path:
return paths.data_dir() / "demucs"
def python() -> Path:
return venv_dir() / "bin" / "python"
def available() -> bool:
return python().is_file()
def setup_command() -> str:
"""What makes the venv, for the "not set up" message."""
if setup_in_app():
return ("Preferences › DJ › Download High-Quality Vocal Splitting "
f"(Demucs, ~{DEMUCS_DOWNLOAD_GB} GB)")
v = venv_dir()
return (f"python3 -m venv {v} && {v}/bin/pip install torch --index-url "
f"https://download.pytorch.org/whl/cpu && {v}/bin/pip install numpy demucs")
# The Mac's Demucs, pinned (the Linux command above isn't). torchaudio 2.9
# hands load/save to torchcodec, which needs FFmpeg's shared libraries — a
# Mac running the built app has only the ffmpeg command — so 2.8 is the last
# that saves through soundfile (whose wheel carries libsndfile). Intel Macs
# stop at torch 2.2.2, the last x86_64 macOS wheel, built against numpy 1.
# Demucs itself stays on the CPU: its default device is CUDA-or-CPU, and
# its FFTs on MPS aren't reliable enough to make that a default.
DEMUCS_VERSION = "4.0.1"
DEMUCS_DOWNLOAD_GB = 1
_MAC_PACKAGES = {
"arm64": ["torch==2.8.0", "torchaudio==2.8.0", "numpy", "soundfile",
f"demucs=={DEMUCS_VERSION}"],
"x86_64": ["torch==2.2.2", "torchaudio==2.2.2", "numpy<2", "soundfile",
f"demucs=={DEMUCS_VERSION}"],
}
_CPU_INDEX = "https://download.pytorch.org/whl/cpu"
def setup_in_app() -> bool:
"""True where Demucs is set up by a button in Preferences (uv makes the
venv) rather than by a command typed into a terminal."""
return venv_tool.uses_uv()
def install_steps() -> list[tuple[str, list[str], str | None]]:
"""(what to say, packages, index URL) for each install, in order."""
if paths.IS_MAC:
machine = platform.machine().lower()
arch = "arm64" if machine in ("arm64", "aarch64") else "x86_64"
return [("Downloading PyTorch and Demucs…", _MAC_PACKAGES[arch], None)]
return [("Downloading PyTorch…", ["torch"], _CPU_INDEX),
("Downloading Demucs…", ["numpy", "demucs"], None)]
class DemucsSetup(QObject):
"""Preferences' Demucs download button (where ``setup_in_app``): makes
the venv with uv and installs PyTorch + Demucs, on a daemon thread."""
progress = pyqtSignal(str)
finished = pyqtSignal()
failed = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._thread = None
def busy(self) -> bool:
return self._thread is not None and self._thread.is_alive()
def start(self):
self._thread = threading.Thread(target=self._run, daemon=True,
name="lintunes-demucs-setup")
self._thread.start()
def _run(self):
try:
venv = venv_dir()
if venv_tool.uses_uv():
self.progress.emit("Downloading a Python for it…")
venv_tool.ensure_uv()
env = venv_tool.run_env()
if not python().is_file():
self.progress.emit("Making its own Python environment…")
venv.parent.mkdir(parents=True, exist_ok=True)
self._call(venv_tool.create_command(venv), env)
for text, packages, index in install_steps():
self.progress.emit(text)
self._call(venv_tool.install_command(venv, packages, index), env)
except (OSError, subprocess.SubprocessError) as e:
self.failed.emit(str(e) or type(e).__name__)
return
self.finished.emit()
@staticmethod
def _call(cmd, env=None):
done = subprocess.run(cmd, capture_output=True, text=True, timeout=3600,
env=env)
if done.returncode != 0:
lines = (done.stderr or done.stdout).strip().splitlines()
raise OSError(lines[-1] if lines else f"{cmd[0]} failed")
def instant_available() -> bool:
return instant.available()
def label(model: str) -> str:
return "Instant" if model == INSTANT else MODELS.get(model, MODELS[DEFAULT_MODEL])[0]
def engine_of(model: str) -> str:
return FAST if model == INSTANT else HQ
def engine_models(engine: str) -> list[str]:
return [INSTANT] if engine == FAST else list(MODELS)
def default_engine(prefs) -> str:
"""Which engine a deck starts with: Preferences › DJ's choice, unless
only the other one is installed here (the pref syncs, installs don't)."""
value = prefs.get("dj_stem_default", HQ) if prefs is not None else HQ
other = HQ if value == FAST else FAST
if not engine_ready(value) and engine_ready(other):
return other
return FAST if value == FAST else HQ
def engine_ready(engine: str) -> bool:
return instant.available() if engine == FAST else available()
def model_choice(prefs) -> str:
value = prefs.get("dj_stem_model", DEFAULT_MODEL) if prefs is not None else DEFAULT_MODEL
return value if value in MODELS else DEFAULT_MODEL
def gentle_choice(prefs) -> bool:
return bool(prefs.get("dj_stem_gentle", True)) if prefs is not None else True
def threads(gentle: bool) -> int:
cores = os.cpu_count() or 4
return max(1, cores // 4) if gentle else cores
def cache_root() -> Path:
return paths.cache_dir() / "stems"
CACHE_LIMIT_KEY = "dj_stem_cache_gb"
DEFAULT_CACHE_GB = 1.0
_INDEX = "index.json"
_index_lock = threading.Lock()
def cache_limit_gb(config: dict | None = None) -> float:
config = load_config() if config is None else config
try:
value = float(config.get(CACHE_LIMIT_KEY, DEFAULT_CACHE_GB))
except (TypeError, ValueError):
return DEFAULT_CACHE_GB
return value if value >= 0 else DEFAULT_CACHE_GB
def _file_id(path: str) -> str | None:
try:
st = os.stat(path)
except OSError:
return None
return f"{os.path.abspath(path)}|{st.st_size}|{int(st.st_mtime)}"
def _path_key(path: str) -> str | None:
"""The key before Round 100: path + size + mtime."""
raw = _file_id(path)
return hashlib.sha1(raw.encode()).hexdigest()[:20] if raw else None
def audio_hash(path: str) -> str | None:
"""A hash of the audio packets alone, so tags don't change it."""
try:
done = subprocess.run(
["ffmpeg", "-v", "error", "-nostdin", "-i", path, "-map", "0:a:0",
"-c", "copy", "-f", "hash", "-hash", "sha256", "-"],
capture_output=True, text=True, timeout=60)
except (OSError, subprocess.SubprocessError):
return None
out = done.stdout.strip()
if done.returncode != 0 or not out.startswith("SHA256="):
return None
return out[len("SHA256="):]
def _read_index() -> dict:
try:
with open(cache_root() / _INDEX, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def _write_index(index: dict):
root = cache_root()
try:
root.mkdir(parents=True, exist_ok=True)
tmp = root / (_INDEX + ".tmp")
tmp.write_text(json.dumps(index), encoding="utf-8")
tmp.replace(root / _INDEX)
except OSError:
pass
def cache_key(path: str) -> str | None:
"""The song's audio key (the path key when ffmpeg can't read it)."""
file_id = _file_id(path)
if file_id is None:
return None
with _index_lock:
known = _read_index().get(file_id)
if known:
return known
digest = audio_hash(path)
if digest is None:
return _path_key(path)
key = "a" + digest[:24]
with _index_lock:
index = _read_index()
prefix = os.path.abspath(path) + "|"
index = {k: v for k, v in index.items() if not k.startswith(prefix)}
index[file_id] = key
_write_index(index)
return key
def _files(folder: Path) -> dict[str, Path] | None:
for suffix in (".opus", ".flac"): # FLAC: splits made before Round 113
files = {name: folder / f"{name}{suffix}" for name in STEMS}
if all(f.is_file() for f in files.values()):
return files
return None
def model_of(files: dict[str, Path]) -> str:
"""Which tier a ``cached``/``split`` result came from."""
name = files["vocals"].parent.name
return name if name in TIERS else LEGACY_MODEL
def to_opus(source: Path, target: Path):
"""Encode one stem. Raises OSError."""
try:
done = subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", str(source),
"-c:a", "libopus", "-b:a", "160k", str(target)],
capture_output=True, text=True, timeout=300)
except (OSError, subprocess.SubprocessError) as e:
raise OSError(f"ffmpeg could not run: {e}") from e
if done.returncode != 0:
lines = done.stderr.strip().splitlines()
raise OSError(lines[-1] if lines else "ffmpeg couldn't write the stem")
def _touch(folder: Path):
try:
os.utime(folder)
except OSError:
pass
def cached(path: str, model: str | None = None,
models: list[str] | None = None) -> dict[str, Path] | None:
"""The stems of ``path``: ``model``'s when given, else the best there
are among ``models`` (default every tier, ``TIERS`` order). None when it
hasn't been split."""
key = cache_key(path)
if key is None:
return None
root = cache_root() / key
legacy = _path_key(path)
if legacy and legacy != key and not root.exists() and (cache_root() / legacy).is_dir():
try:
(cache_root() / legacy).rename(root)
except OSError:
root = cache_root() / legacy
order = [model] if model else (models or TIERS)
for name in order:
hit = _files(root / name)
if hit is None and name == LEGACY_MODEL:
hit = _files(root)
if hit is not None:
_touch(root)
return hit
return None
def _size(folder: Path) -> int:
total = 0
for f in folder.rglob("*"):
try:
if f.is_file():
total += f.stat().st_size
except OSError:
pass
return total
def cache_size() -> int:
"""Bytes the whole split cache takes on disk now (both engines)."""
root = cache_root()
return _size(root) if root.is_dir() else 0
def prune(limit_gb: float | None = None, keep: str | None = None) -> int:
"""Delete the songs used longest ago until the cache is under
``limit_gb`` (config.json's when None). ``keep`` (a key) is never
deleted. Returns how many songs went."""
limit = int((cache_limit_gb() if limit_gb is None else limit_gb) * 1024 ** 3)
root = cache_root()
try:
folders = [d for d in root.iterdir() if d.is_dir()]
except OSError:
return 0
entries = []
for d in folders:
try:
entries.append((d.stat().st_mtime, d, _size(d)))
except OSError:
pass
total = sum(size for _m, _d, size in entries)
removed = 0
for _mtime, folder, size in sorted(entries, key=lambda e: e[0]):
if total <= limit:
break
if folder.name == keep:
continue
shutil.rmtree(folder, ignore_errors=True)
total -= size
removed += 1
return removed
def parse_progress(text: str) -> int | None:
found = _PERCENT.findall(text)
return int(found[-1]) if found else None
def split(path: str, model: str, gentle: bool, progress=None,
cancel: threading.Event | None = None) -> dict[str, Path]:
"""Run Demucs on ``path`` (blocking) and cache the two stems. Raises
OSError on failure and Cancelled when ``cancel`` is set."""
if model == INSTANT:
return _split_instant(path, progress, cancel)
if not available():
raise OSError("Demucs isn't set up on this computer")
key = cache_key(path)
if key is None:
raise OSError("the file is missing")
model = model if model in MODELS else DEFAULT_MODEL
work = Path(tempfile.mkdtemp(prefix="lintunes-stems-"))
count = str(threads(gentle))
env = venv_tool.child_env(
dict(os.environ, OMP_NUM_THREADS=count, MKL_NUM_THREADS=count))
niceness = 19 if gentle else 10
try:
cmd, preexec = venv_tool.niced(
[str(python()), "-m", "demucs", "--two-stems=vocals"] + _ARGS[model]
+ ["--flac", "-o", str(work), path], niceness)
process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=env, preexec_fn=preexec)
if cancel is not None:
def watch():
# Demucs can go seconds without a progress line (loading the
# model), so a cancel kills it from here rather than waiting.
while process.poll() is None:
if cancel.wait(0.2):
process.kill()
return
threading.Thread(target=watch, daemon=True, name="lintunes-demucs-watch").start()
tail = b""
last = -1
while True:
chunk = process.stderr.read(256)
if cancel is not None and cancel.is_set():
process.kill()
process.wait()
raise Cancelled()
if not chunk:
break
tail = (tail + chunk)[-4096:]
percent = parse_progress(tail.decode(errors="replace"))
if percent is not None and percent != last and progress is not None:
last = percent
progress(percent)
if process.wait() != 0:
lines = tail.decode(errors="replace").strip().splitlines()
raise OSError(lines[-1] if lines else "Demucs failed")
made = list(work.rglob("vocals.flac"))
if not made:
raise OSError("Demucs wrote nothing")
for name in STEMS:
to_opus(made[0].parent / f"{name}.flac", work / f"{name}.opus")
return _keep(key, model, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _split_instant(path: str, progress, cancel) -> dict[str, Path]:
key = cache_key(path)
if key is None:
raise OSError("the file is missing")
work = Path(tempfile.mkdtemp(prefix="lintunes-stems-"))
try:
try:
instant.split(path, work, progress, cancel)
except instant.Cancelled:
raise Cancelled() from None
return _keep(key, INSTANT, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _keep(key: str, model: str, work: Path) -> dict[str, Path]:
"""Move the two ``.opus`` stems in ``work`` into the cache."""
folder = cache_root() / key / model
folder.mkdir(parents=True, exist_ok=True)
out = {}
for name in STEMS:
target = folder / f"{name}.opus"
shutil.move(str(work / f"{name}.opus"), target)
out[name] = target
_touch(cache_root() / key)
prune(keep=key)
return out
class StemSplitter(QObject):
"""A queue of songs to split for the decks, one run at a time, with one
engine: ``HQ`` (Demucs; ``settings`` returns (model, gentle) when each
split starts, so a change in Preferences applies to the next song) or
``FAST`` (Instant). The decks keep one of each."""
progress = pyqtSignal(str, int) # path, percent
finished = pyqtSignal(str, object) # path, {"vocals": Path, …}
failed = pyqtSignal(str, str) # path, why
cancelled = pyqtSignal(str) # path
def __init__(self, settings=None, parent=None, engine: str = HQ):
super().__init__(parent)
self.engine = engine
self._settings = settings or (lambda: (DEFAULT_MODEL, True))
self._queue: list[str] = []
self._busy = False
self._lock = threading.Lock()
self._running: str | None = None
self._stop = threading.Event()
self._called_off: set[str] = set()
def request(self, path: str, best: bool = False):
"""Split ``path`` unless this engine has a split of it cached (then
report it). ``best`` (Instant only): a cached Demucs split counts
too, and wins — what a deck wants when a song loads.
The lookup may hash the audio (~0.2 s), so it runs off this thread."""
with self._lock:
self._called_off.discard(path)
threading.Thread(target=self._look_up, args=(path, best), daemon=True,
name="lintunes-stems-lookup").start()
def cancel(self, path: str):
"""Stop splitting ``path``: out of the queue, or Demucs killed if it
is the one running. Emits ``cancelled``; a later ``request`` starts
it over."""
with self._lock:
self._called_off.add(path)
queued = path in self._queue
if queued:
self._queue.remove(path)
if self._running == path:
self._stop.set()
return # _run reports it once Demucs is gone
self.cancelled.emit(path)
def _look_up(self, path: str, best: bool = False):
models = TIERS if best and self.engine == FAST else engine_models(self.engine)
hit = cached(path, models=models)
if hit is not None:
self.finished.emit(path, hit)
return
self._enqueue(path)
def _enqueue(self, path: str):
with self._lock:
if path in self._called_off or path in self._queue:
return
self._queue.append(path)
start = not self._busy
self._busy = True
if start:
threading.Thread(target=self._run, daemon=True,
name=f"lintunes-stems-{self.engine}").start()
def _run(self):
while True:
with self._lock:
if not self._queue:
self._busy = False
return
path = self._queue.pop(0)
self._running = path
self._stop.clear()
model, gentle = self._settings() if self.engine == HQ else (INSTANT, False)
try:
result = split(path, model, gentle,
lambda percent, path=path: self.progress.emit(path, percent),
self._stop)
except Cancelled:
with self._lock:
still_off = path in self._called_off
if still_off: # not asked for again while Demucs died
self.cancelled.emit(path)
continue
except Exception as e: # noqa: BLE001 — reported, never raised
self.failed.emit(path, str(e) or type(e).__name__)
continue
finally:
with self._lock:
self._running = None
self.finished.emit(path, result)
+185
View File
@@ -0,0 +1,185 @@
"""Making the vocal splitters' private Python environments, on any computer.
Demucs and Spleeter each live in a venv of their own (``stems.py``,
``instant.py``), never in LinTunes' own Python. On Linux from a checkout that
venv is made by the Python running LinTunes (``python -m venv``), as it always
was. That can't work on a Mac: inside the built LinTunes.app ``sys.executable``
is the app, and a stock Mac has no usable ``python3`` (``/usr/bin/python3`` is
a stub that offers to install Xcode's tools).
So on a Mac, and in any frozen build, the venv is made by Astral's **uv**,
which brings its own Python: a pinned release is downloaded once into
``paths.data_dir()/bin`` and refused unless its SHA-256 is the one pinned here
(the ``airplay/cli.py`` rule, through its ``download_verified``). uv's Python
and its download cache go under LinTunes' own folders too, so removing a
splitter's venv leaves nothing of uv's lying around in the user's home.
Pure subprocess/file work, no Qt.
"""
from __future__ import annotations
import io
import os
import platform
import sys
import tarfile
from pathlib import Path
from lintunes import paths
UV_VERSION = "0.13.6"
_UV_RELEASE = ("https://github.com/astral-sh/uv/releases/download/"
f"{UV_VERSION}/")
# From each asset's .sha256 in that release (checked against sha256.sum).
_UV_SHA256 = {
"aarch64-apple-darwin":
"60fbd5c8a1ed681845eea28d9d622fcde03c51e91a43465b64a1e17db1ed3472",
"x86_64-apple-darwin":
"63ba17fdda55ad1a230d4b37fc6017ffa10c23688c83818bd3bfdf914c652a02",
"x86_64-unknown-linux-gnu":
"f29c3e94ffabd7e6f3ba521dba169a9b7ec12100bf3257087f0f24f6123f3645",
"aarch64-unknown-linux-gnu":
"229e194255c7958d86d56e8790d969a6f74736592133f0dfd0076f754c642c1d",
}
# The splitters' Python. Every wheel they need exists for it on both Mac
# CPUs (torch 2.2.2 is the last for Intel Macs and still has cp312).
PYTHON_VERSION = "3.12"
# The Python variables that would point a child Python at LinTunes' own
# (frozen) one instead of the venv's.
_LEAKY = ("PYTHONHOME", "PYTHONPATH", "PYTHONEXECUTABLE", "PYTHONSTARTUP",
"__PYVENV_LAUNCHER__")
class VenvError(OSError):
"""The environment couldn't be made (download, checksum, uv itself)."""
def uses_uv() -> bool:
"""True where the venv must be made by uv rather than ``python -m venv``."""
return paths.IS_MAC or paths.FROZEN
def uv_target() -> str | None:
"""uv's release target for this computer, or None."""
machine = platform.machine().lower()
machine = {"arm64": "aarch64", "amd64": "x86_64"}.get(machine, machine)
if paths.IS_MAC:
target = f"{machine}-apple-darwin"
elif sys.platform.startswith("linux"):
target = f"{machine}-unknown-linux-gnu"
else:
return None
return target if target in _UV_SHA256 else None
def uv_path() -> Path:
return paths.data_dir() / "bin" / f"uv-{UV_VERSION}"
def _unpack_uv(archive: bytes, target: str) -> bytes:
"""The ``uv`` binary out of a release tarball."""
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
for member in tar.getmembers():
if member.isfile() and member.name == f"uv-{target}/uv":
return tar.extractfile(member).read()
raise VenvError("the uv download had no uv in it")
def ensure_uv(fetch=None) -> Path:
"""uv's path, downloading and verifying it first if needed. Blocking.
``fetch(url) -> bytes`` is injectable so tests never touch the network."""
from lintunes.airplay import cli
path = uv_path()
if path.is_file() and os.access(path, os.X_OK):
return path
target = uv_target()
if target is None:
raise VenvError(f"no uv for {platform.system()} {platform.machine()}")
# The archive is checked exactly as published, then only its uv is kept.
return cli.download_verified(
_UV_RELEASE + f"uv-{target}.tar.gz", _UV_SHA256[target], path, fetch,
"Python installer (uv)", error=VenvError,
unpack=lambda data: _unpack_uv(data, target))
def uv_env(base: dict | None = None) -> dict:
"""The environment uv runs in: its Python and cache under our folders,
only Pythons uv manages (never Xcode's stub), no Python variables of
LinTunes' own leaking in."""
env = clean_env(base)
env["UV_PYTHON_INSTALL_DIR"] = str(paths.data_dir() / "python")
env["UV_CACHE_DIR"] = str(paths.cache_dir() / "uv")
env["UV_MANAGED_PYTHON"] = "1"
env.pop("VIRTUAL_ENV", None)
return env
def clean_env(base: dict | None = None) -> dict:
"""``base`` (default os.environ) without the variables that would point
a venv's Python back at LinTunes' own. On a Mac a Python downloaded by
uv may not find root certificates of its own, so it is handed certifi's
(which LinTunes ships, as a dependency of requests)."""
env = dict(os.environ if base is None else base)
for name in _LEAKY:
env.pop(name, None)
if paths.IS_MAC and "SSL_CERT_FILE" not in env:
bundle = certifi_bundle()
if bundle:
env["SSL_CERT_FILE"] = bundle
return env
def certifi_bundle() -> str | None:
try:
import certifi
where = certifi.where()
except Exception: # noqa: BLE001 — no certifi just means no override
return None
return where if where and os.path.isfile(where) else None
def child_env(base: dict | None = None) -> dict | None:
"""The environment for running a tool *inside* a splitter's venv:
``base`` untouched (None = inherit, as always) on Linux from a checkout,
``clean_env(base)`` elsewhere."""
return clean_env(base) if uses_uv() else base
def venv_python(venv: Path) -> Path:
return venv / "bin" / "python"
def create_command(venv: Path, uv: Path | None = None) -> list[str]:
"""The command that makes ``venv``."""
if not uses_uv():
return [sys.executable, "-m", "venv", str(venv)]
return [str(uv or uv_path()), "venv", "--quiet", "--python", PYTHON_VERSION,
str(venv)]
def install_command(venv: Path, packages: list[str], index_url: str | None = None,
uv: Path | None = None, quiet: bool = True) -> list[str]:
"""The command that installs ``packages`` into ``venv``."""
extra = ["--index-url", index_url] if index_url else []
if not uses_uv():
return ([str(venv_python(venv)), "-m", "pip", "install"]
+ (["--quiet"] if quiet else []) + extra + list(packages))
return ([str(uv or uv_path()), "pip", "install"]
+ (["--quiet"] if quiet else [])
+ ["--python", str(venv_python(venv))] + extra + list(packages))
def run_env() -> dict | None:
"""The environment ``create_command``/``install_command`` run in."""
return uv_env() if uses_uv() else None
def niced(cmd: list[str], niceness: int):
"""(command, preexec_fn) that run ``cmd`` at ``niceness``. Linux keeps
``os.nice`` in the child, as it always did; a Mac prefixes
``/usr/bin/nice``, since a ``preexec_fn`` in a threaded process (Qt's)
is unsafe there with the system's fork rules."""
if paths.IS_MAC:
return ["/usr/bin/nice", "-n", str(niceness)] + list(cmd), None
return list(cmd), (lambda: os.nice(niceness))
+8
View File
@@ -11,12 +11,20 @@ import logging
import time
from pathlib import Path
from lintunes import paths
log = logging.getLogger("lintunes.control")
_MAX_BYTES = 1_000_000
def _log_path() -> Path:
return default_log_path()
def default_log_path() -> Path:
if paths.IS_MAC:
return paths.cache_dir() / "control-events.log"
return Path.home() / ".cache" / "lintunes" / "control-events.log"
+47 -18
View File
@@ -107,7 +107,7 @@ class ExportPlan:
m3u_name: str # "" for a web mix, which writes no m3u
title: str = ""
description: str = ""
image: Path | None = None # None = ship the gray placeholder
images: list = field(default_factory=list) # [] = the gray placeholder
accent: str = DEFAULT_ACCENT # hover backgrounds + the progress fill
items: list = field(default_factory=list)
skipped: list = field(default_factory=list) # (display, reason)
@@ -123,13 +123,14 @@ class ExportPlan:
def plan_export(playlist_name: str, tracks: list, dest_parent: Path,
kind: str = FOLDER) -> ExportPlan:
kind: str = FOLDER, folder: str | None = None) -> ExportPlan:
"""Work out what an export would write. Pure — creates nothing.
`tracks` is the playlist's tracks in order; `dest_parent` is the folder
the user picked, inside which a folder named after the playlist is made.
the user picked, inside which a folder named after the playlist is made
(or `folder`, when given — an upload names it by its URL slug).
"""
folder = sanitize_name(playlist_name)
folder = folder or sanitize_name(playlist_name)
dest_dir = Path(dest_parent) / folder
plan = ExportPlan(
kind=kind,
@@ -207,18 +208,21 @@ def build_tracklist(items: list) -> str:
return "\n".join(rows)
def build_index_html(plan: ExportPlan, image_name: str | None) -> str:
def build_index_html(plan: ExportPlan, image_names) -> str:
"""Render index.html for `plan`.
The title and track names are escaped; the description deliberately is
**not**, because the hand-made mixes lean on inline links and <br> in
exactly that spot and the dialog says so.
`image_names` are the copied images, shown one after another with a
blank line between each (a single name still works).
"""
if image_name:
image_tag = (f' <img src="{html.escape(image_name, quote=True)}"'
f' width="400"><br>')
else:
image_tag = ""
if isinstance(image_names, str):
image_names = [image_names]
image_tag = "\n <br><br>\n".join(
f' <img src="{html.escape(name, quote=True)}" width="400"><br>'
for name in image_names or [])
accent = normalize_accent(plan.accent)
tmpl = string.Template((templates() / "index.html.tmpl").read_text(encoding="utf-8"))
return tmpl.substitute(
@@ -231,6 +235,19 @@ def build_index_html(plan: ExportPlan, image_name: str | None) -> str:
)
def folder_size(path: Path) -> int:
"""Bytes in every file under `path` — what the exported folder weighs,
conversions, page and images included."""
total = 0
for p in Path(path).rglob("*"):
try:
if p.is_file():
total += p.stat().st_size
except OSError:
pass
return total
class _Cancelled(Exception):
"""Internal: unwinds _run when cancel() was requested."""
@@ -348,6 +365,7 @@ class ExportWorker(QObject):
"converted": converted,
"skipped": len(plan.skipped),
"vanished": len(vanished),
"bytes": folder_size(plan.dest_dir),
})
except _Cancelled:
if dest is not None:
@@ -382,16 +400,27 @@ class ExportWorker(QObject):
if plan.kind == WEB:
for name in _WEB_ASSETS:
shutil.copyfile(templates() / name, plan.dest_dir / name)
if plan.image is not None and Path(plan.image).is_file():
image_name = sanitize_name(Path(plan.image).stem) \
+ Path(plan.image).suffix.lower()
shutil.copyfile(plan.image, plan.dest_dir / image_name)
else:
image_name = "placeholder.png"
image_names = []
for image in plan.images:
image = Path(image)
if not image.is_file():
continue
name = sanitize_name(image.stem) + image.suffix.lower()
# Two pictures called cover.jpg from different folders must
# not overwrite each other.
stem, ext = os.path.splitext(name)
n = 2
while name in image_names:
name = f"{stem} {n}{ext}"
n += 1
shutil.copyfile(image, plan.dest_dir / name)
image_names.append(name)
if not image_names:
image_names = ["placeholder.png"]
shutil.copyfile(templates() / "placeholder.png",
plan.dest_dir / image_name)
plan.dest_dir / "placeholder.png")
(plan.dest_dir / "index.html").write_text(
build_index_html(plan, image_name), encoding="utf-8")
build_index_html(plan, image_names), encoding="utf-8")
return
entries = [(item.dest_name, item.secs, item.display)
@@ -63,6 +63,7 @@ $tracklist
</p>
-->
<br><br>
$image_tag
</div>
</body>
+39 -3
View File
@@ -27,7 +27,7 @@
.audiojs audio { position: absolute; left: -1px; }
.audiojs {
width: 250px;
width: 334px;
height: 36px;
background: #eee;
color: #000;
@@ -40,9 +40,9 @@
}
.audiojs .play-pause {
width: 40px;
width: 36px;
height: 40px;
padding: 4px 6px;
padding: 4px 2px;
margin: 0px;
float: left;
overflow: hidden;
@@ -88,6 +88,42 @@
.audiojs .time em { padding: 0px 2px 0px 0px; color: #000; font-style: normal; }
.audiojs .time strong { padding: 0px 0px 0px 2px; font-weight: normal; }
/* Previous / next, either side of play-pause: plain black glyphs. */
.audiojs .skip {
float: left;
width: 24px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
color: #000;
cursor: pointer;
}
.audiojs .prev { margin-left: 4px; }
.audiojs .skip:hover { color: var(--accent, #8c764a); }
.audiojs .skip:focus-visible { outline: 1px dotted #000; }
/* Shuffle: black like the other glyphs while off, the accent while on
* (the same fill as the progress bar, with the text color picked for it). */
.audiojs .shuffle {
float: left;
width: 26px;
height: 26px;
margin: 5px 0px;
display: flex;
align-items: center;
justify-content: center;
color: #000;
cursor: pointer;
border-radius: 3px;
}
.audiojs .shuffle.on {
background: var(--accent, #8c764a);
color: var(--accent-text, #fff);
}
.audiojs .shuffle:focus-visible { outline: 1px dotted #000; }
.audiojs.error .shuffle { display: none; }
.audiojs .error-message {
float: left;
display: none;
+92 -8
View File
@@ -13,18 +13,41 @@
* Expected page markup:
* <audio preload></audio>
* <ol><li><a href="#" data-src="./audios/x.mp3">Title — Artist</a></li>…</ol>
*
* Shuffle (the button after the clock, or the S key) walks a shuffled copy of
* the tracklist that starts at the song playing when it was switched on, so
* every song plays once before the walk ends — like LinTunes' own shuffle,
* and unlike picking a random next song, which repeats. Off again, play
* carries on down the list from wherever it is.
*/
(function () {
"use strict";
var WRAPPER =
'<div class="skip prev" role="button" tabindex="0" title="Previous (←)">' +
'<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">' +
'<path d="M6 5h2.5v14H6zM20 5v14L9 12z" fill="currentColor"/>' +
'</svg>' +
'</div>' +
'<div class="play-pause">' +
'<p class="play"></p><p class="pause"></p>' +
'<p class="loading"></p><p class="error"></p>' +
'</div>' +
'<div class="skip next" role="button" tabindex="0" title="Next (→)">' +
'<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">' +
'<path d="M15.5 5H18v14h-2.5zM4 5v14l11-7z" fill="currentColor"/>' +
'</svg>' +
'</div>' +
'<div class="scrubber"><div class="progress"></div><div class="loaded"></div></div>' +
'<div class="time"><em class="played">00:00</em>/<strong class="duration">00:00</strong></div>' +
'<div class="error-message"></div>';
'<div class="error-message"></div>' +
'<div class="shuffle" role="button" tabindex="0" aria-pressed="false" title="Shuffle (S)">' +
'<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">' +
'<path d="M3 7h3.5c2.5 0 3.8 1.2 5.5 5s3 5 5.5 5H20M3 17h3.5c1.4 0 2.4-.4 3.3-1.3M14.2 8.3c.9-.9 1.9-1.3 3.3-1.3H20" ' +
'fill="none" stroke="currentColor" stroke-width="2"/>' +
'<path d="M18 4l3 3-3 3zM18 14l3 3-3 3z" fill="currentColor"/>' +
'</svg>' +
'</div>';
function clock(seconds) {
if (!isFinite(seconds) || seconds < 0) seconds = 0;
@@ -48,7 +71,10 @@
scrubber: wrap.querySelector(".scrubber"),
played: wrap.querySelector(".played"),
duration: wrap.querySelector(".duration"),
error: wrap.querySelector(".error-message")
error: wrap.querySelector(".error-message"),
shuffle: wrap.querySelector(".shuffle"),
prev: wrap.querySelector(".prev"),
next: wrap.querySelector(".next")
};
function state(name) {
@@ -112,6 +138,9 @@
return {
element: audio,
shuffleButton: ui.shuffle,
prevButton: ui.prev,
nextButton: ui.next,
load: function (src) {
ui.progress.style.width = "0%";
ui.loaded.style.width = "0%";
@@ -133,6 +162,58 @@
if (!audio || !items.length) return;
var player = build(audio);
var order = null; // the shuffled walk, or null for list order
function shuffledFrom(first) {
var rest = items.filter(function (li) { return li !== first; });
for (var i = rest.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var t = rest[i]; rest[i] = rest[j]; rest[j] = t;
}
return first ? [first].concat(rest) : rest;
}
function setShuffle(on) {
var current = document.querySelector("ol li.playing");
order = on ? shuffledFrom(current || items[0]) : null;
player.shuffleButton.classList.toggle("on", on);
player.shuffleButton.setAttribute("aria-pressed", on ? "true" : "false");
}
// The song after/before `current` in the walk; null past either end.
function step(current, delta) {
var list = order || items;
var i = list.indexOf(current);
return i < 0 ? null : list[i + delta] || null;
}
function first() { return (order || items)[0]; }
function last() { var list = order || items; return list[list.length - 1]; }
// The previous/next buttons and the arrow keys: wrap around at either
// end, through the shuffled walk when shuffle is on.
function goNext() {
var current = document.querySelector("ol li.playing");
select((current && step(current, 1)) || first(), true);
}
function goPrev() {
var current = document.querySelector("ol li.playing");
select((current && step(current, -1)) || last(), true);
}
function button(el, action) {
el.addEventListener("click", action);
el.addEventListener("keydown", function (e) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
e.stopPropagation();
action();
}
});
}
button(player.shuffleButton, function () { setShuffle(!order); });
button(player.prevButton, goPrev);
button(player.nextButton, goNext);
function select(li, autoplay) {
items.forEach(function (other) { other.classList.remove("playing"); });
@@ -148,11 +229,12 @@
});
});
// Advance to the next track, stopping at the end of the mix — the old
// page had the wrap-around commented out, so this matches it.
// Advance to the next track, stopping at the end of the mix (or of the
// shuffled walk) — the old page had the wrap-around commented out, so
// this matches it.
audio.addEventListener("ended", function () {
var current = document.querySelector("ol li.playing");
var next = current && current.nextElementSibling;
var next = current && step(current, 1);
if (next) select(next, true);
});
@@ -161,13 +243,15 @@
var tag = (target.tagName || "").toLowerCase();
if (tag === "input" || tag === "textarea" || target.isContentEditable) return;
var current = document.querySelector("ol li.playing");
if (e.key === "ArrowRight") {
e.preventDefault();
select((current && current.nextElementSibling) || items[0], true);
goNext();
} else if (e.key === "ArrowLeft") {
e.preventDefault();
select((current && current.previousElementSibling) || items[items.length - 1], true);
goPrev();
} else if ((e.key === "s" || e.key === "S") && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
setShuffle(!order);
} else if (e.key === " " || e.key === "Spacebar") {
e.preventDefault();
player.playPause();
+305
View File
@@ -0,0 +1,305 @@
"""Upload a web mix to a web server — rsync over ssh (Round 81).
The export dialog's "Upload to web server" box builds the mix in a staging
folder under the cache, then mirrors it to ``<host>:<path>/<slug>/``. Why
rsync and not scp: scp re-sends every file every time and never removes one,
so a song taken out of the playlist would stay on the server forever. rsync
sends only what changed, and ``--delete`` makes the mix's folder match the
export exactly.
Rules worth keeping:
* **The server lives in ``config.json``**, never preferences.json or the repo.
The host is usually an alias from this machine's ``~/.ssh/config``, which is
this machine's business.
* **``--delete`` only ever reaches one mix's folder.** The destination is
always ``<path>/<slug>/`` with a validated slug — never the configured root.
* **Staging is rebuilt from scratch** on every export (``reset_staging``), or a
song removed from the playlist would linger there and survive the mirror.
Hence ``--checksum``: rebuilt files may carry new mtimes, and checksums still
keep unchanged songs from being re-sent.
* **``BatchMode=yes``**: there is no terminal to answer a password or
host-key prompt, so ssh must fail fast rather than hang invisibly.
"""
import os
import re
import shlex
import shutil
import subprocess
import threading
import unicodedata
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
HOST_KEY = "webmix_host"
PATH_KEY = "webmix_path"
_SSH_OPTIONS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]
_ERROR_TAIL = 8 # lines of ssh/rsync output kept for a failure message
class UploadError(Exception):
pass
def server_settings(config: dict) -> tuple[str, str] | None:
"""(host, path) from config.json, or None if either is blank."""
host = (config.get(HOST_KEY) or "").strip()
path = (config.get(PATH_KEY) or "").strip()
if not host or not path:
return None
return host, path
def slugify(title: str) -> str:
"""'Summer Mix 2026!' → 'summer-mix-2026'. May return "" (all symbols)."""
text = unicodedata.normalize("NFKD", title or "")
text = text.encode("ascii", "ignore").decode("ascii").lower()
return re.sub(r"[^a-z0-9]+", "-", text).strip("-")
def valid_slug(slug: str) -> bool:
return bool(slug) and slug not in (".", "..") and "/" not in slug \
and "\0" not in slug
def remote_dir(path: str, slug: str) -> str:
"""The mix's folder on the server. A leading ``~/`` means the home
directory, which is where ssh and rsync resolve a relative path anyway —
quoting would otherwise stop the shell expanding it."""
if not valid_slug(slug):
raise UploadError(f"“{slug}” can't be a folder name on the server")
path = path.strip()
if path == "~":
path = ""
elif path.startswith("~/"):
path = path[2:]
path = path.rstrip("/")
if not path:
return slug
return path + "/" + slug
def staging_root() -> Path:
return paths.cache_dir() / "webmix"
def reset_staging(slug: str) -> Path:
"""Remove a previous build of this mix, and return its folder."""
root = Path(os.path.abspath(staging_root()))
target = Path(os.path.abspath(root / slug))
if not valid_slug(slug) or target == root \
or not target.is_relative_to(root):
raise UploadError(f"{target} is not inside {root}")
if target.exists():
shutil.rmtree(target)
return target
def exists_command(host: str, rdir: str) -> list[str]:
return ["ssh", *_SSH_OPTIONS, host, "test", "-d", shlex.quote(rdir)]
def rsync_command(host: str, local_dir: Path, rdir: str) -> list[str]:
# -s: the remote path is passed whole, never re-split by the remote
# shell (spaces in the configured folder).
return ["rsync", "-a", "-s", "--checksum", "--delete",
"--chmod=D755,F644", "--info=progress2",
"-e", shlex.join(["ssh", *_SSH_OPTIONS]),
str(local_dir).rstrip("/") + "/",
f"{host}:{rdir}/"]
# " 1,234,567 42% 1.23MB/s 0:00:03 (xfr#2, to-chk=5/9)"
_PERCENT = re.compile(r"^\s*[\d,.]+[KMGTP]?\s+(\d{1,3})%(?:\s|$)")
_XFR = re.compile(r"xfr#(\d+)")
def parse_progress2(line: str) -> int | None:
m = _PERCENT.match(line)
return min(int(m.group(1)), 100) if m else None
def _missing_tool(name: str) -> str:
return (f"The {name} command isn't installed, so LinTunes can't reach "
f"the server.")
_RSYNC_VERSION = re.compile(r"rsync\s+version\s+v?(\d+)\.")
def rsync_major(version_text: str) -> int | None:
"""rsync's major version from ``rsync --version`` (None if unreadable).
macOS's own is 2.6.9 or openrsync ("rsync version 2.6.9 compatible")."""
m = _RSYNC_VERSION.search(version_text or "")
return int(m.group(1)) if m else None
def mac_rsync_problem() -> str | None:
"""On a Mac, why the rsync on PATH can't do this upload, or None.
The command line needs rsync 3 (``-s``, ``--info=progress2``); Apple
ships 2.6.9 or openrsync, so Homebrew's is required there. Linux is
never asked."""
if not paths.IS_MAC:
return None
try:
out = subprocess.run(["rsync", "--version"], capture_output=True,
text=True, errors="replace", timeout=10).stdout
except (OSError, subprocess.SubprocessError):
return None # the run itself will report it
major = rsync_major(out)
if major is not None and major < 3:
return ("The rsync that comes with macOS is too old for uploading. "
"Install a current one with Homebrew (brew install rsync) "
"and try again.")
return None
class _ProcessWorker(QObject):
"""One subprocess on a daemon thread; cancel() kills it."""
failed = pyqtSignal(str)
cancelled = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self._busy = False
self._cancel = threading.Event()
self._proc = None
self._lock = threading.Lock()
def busy(self) -> bool:
return self._busy
def cancel(self):
self._cancel.set()
with self._lock:
if self._proc is not None and self._proc.poll() is None:
self._proc.kill()
def start(self):
if self._busy:
return
self._busy = True
threading.Thread(target=self._run_guarded, daemon=True).start()
def _run_guarded(self):
try:
self._run()
except OSError as e:
self.failed.emit(str(e))
finally:
self._busy = False
def _spawn(self, argv: list[str]):
with self._lock:
if self._cancel.is_set():
return None
self._proc = subprocess.Popen(
argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return self._proc
def _run(self):
raise NotImplementedError
class ServerCheckWorker(_ProcessWorker):
"""Does the mix's folder already exist on the server? Also the first
proof the connection works, before any export time is spent."""
result = pyqtSignal(bool)
def __init__(self, host: str, rdir: str, parent=None):
super().__init__(parent)
self._host = host
self._rdir = rdir
def _run(self):
if shutil.which("ssh") is None:
self.failed.emit(_missing_tool("ssh"))
return
proc = self._spawn(exists_command(self._host, self._rdir))
if proc is None:
self.cancelled.emit()
return
out = proc.communicate()[0].decode("utf-8", "replace")
if self._cancel.is_set():
self.cancelled.emit()
elif proc.returncode in (0, 1):
self.result.emit(proc.returncode == 0)
else:
tail = "\n".join(out.strip().splitlines()[-_ERROR_TAIL:])
self.failed.emit(
f"Couldn't connect to {self._host}"
+ (f":\n{tail}" if tail else "."))
class UploadWorker(_ProcessWorker):
"""rsync the staged mix to the server, reporting a percentage."""
progress = pyqtSignal(int, str) # percent, rsync's own progress line
finished = pyqtSignal(dict)
def __init__(self, host: str, local_dir: Path, rdir: str, parent=None):
super().__init__(parent)
self._host = host
self._local = Path(local_dir)
self._rdir = rdir
def _run(self):
if shutil.which("rsync") is None:
self.failed.emit(_missing_tool("rsync"))
return
problem = mac_rsync_problem()
if problem:
self.failed.emit(problem)
return
proc = self._spawn(rsync_command(self._host, self._local, self._rdir))
if proc is None:
self.cancelled.emit()
return
tail: list[str] = []
files = 0
buf = b""
while True:
chunk = proc.stdout.read1(4096)
if not chunk:
break
buf += chunk
# progress2 rewrites one line with \r; errors end with \n.
parts = re.split(rb"[\r\n]", buf)
buf = parts.pop()
for raw in parts:
self._line(raw, tail)
m = _XFR.search(raw.decode("utf-8", "replace"))
if m:
files = int(m.group(1))
if buf:
self._line(buf, tail)
proc.wait()
if self._cancel.is_set():
self.cancelled.emit()
elif proc.returncode == 0:
self.finished.emit({"host": self._host, "dest": self._rdir,
"files_sent": files})
else:
text = "\n".join(tail[-_ERROR_TAIL:])
self.failed.emit(
f"Upload to {self._host} failed (rsync exit "
f"{proc.returncode})" + (f":\n{text}" if text else "."))
def _line(self, raw: bytes, tail: list):
line = raw.decode("utf-8", "replace").strip()
if not line:
return
percent = parse_progress2(line)
if percent is not None:
self.progress.emit(percent, line)
else:
tail.append(line)
+191
View File
@@ -0,0 +1,191 @@
"""A cover-art search inside another window (Round 119).
Download Album Art's search (iTunes + Deezer, ``AlbumArtFetcher``) as a
widget: the picture, what it is, **Next Artwork** to cycle the results and
an **Embed** box. The Identify windows carry one, so an Import from URL
proposes tags and a cover in the same place.
Passive like the dialogs it sits in: nothing is written. The caller reads
``selected()`` after an accept and embeds through ``art_ops``.
"""
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import (
QCheckBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget,
)
from lintunes.art_search import AlbumArtFetcher
ART_PX = 180
class ArtPicker(QWidget):
# The picture or the Embed box changed (a table's thumbnail follows).
changed = pyqtSignal()
# A search has come to rest: no results, an error, or its first image
# (good or bad). A queue of pickers starts the next one on this.
settled = pyqtSignal()
def __init__(self, embed_text: str = "Embed this artwork",
size: int = ART_PX, parent=None):
super().__init__(parent)
self._candidates = []
self._index = 0
self._image: bytes | None = None
self._mime = "image/jpeg"
self._embed_default = True
self._generation = 0
self._fetchers = [] # kept alive while their threads run
self._settled = True
self.query: tuple | None = None
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._art = QLabel("No artwork search")
self._art.setFixedSize(size, size)
self._art.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._art.setStyleSheet("border: 1px solid palette(mid);")
self._art.setWordWrap(True)
layout.addWidget(self._art)
self._caption = QLabel()
self._caption.setWordWrap(True)
self._caption.setEnabled(False)
self._caption.setMaximumWidth(max(size, 220))
layout.addWidget(self._caption)
row = QHBoxLayout()
self._embed = QCheckBox(embed_text)
self._embed.setEnabled(False)
self._embed.toggled.connect(lambda _on: self.changed.emit())
self._next = QPushButton("Next Artwork")
self._next.setEnabled(False)
self._next.clicked.connect(self.next_artwork)
row.addWidget(self._embed)
row.addWidget(self._next)
row.addStretch(1)
layout.addLayout(row)
layout.addStretch(1)
# ---- searching ----
def search(self, artist: str, album: str, embed_by_default: bool = True):
"""Look up (artist, album), dropping whatever an earlier search was
still doing. The Embed box ticks itself when the first picture
arrives, if ``embed_by_default``."""
self.query = (artist, album)
self._embed_default = embed_by_default
self._reset("Searching…")
self._settled = False
fetcher = self._fetcher()
fetcher.search(artist, album)
def clear(self, text: str = "No album to search artwork by"):
self.query = None
self._reset(text)
self._settled = True
self.changed.emit()
def _reset(self, text: str):
self._generation += 1
self._candidates = []
self._index = 0
self._image = None
self._caption.setText("")
self._art.setPixmap(QPixmap())
self._art.setText(text)
self._next.setEnabled(False)
self._embed.blockSignals(True)
self._embed.setChecked(False)
self._embed.blockSignals(False)
self._embed.setEnabled(False)
def _fetcher(self):
"""A fetcher whose answers count only while its search is the
latest one."""
gen = self._generation
fetcher = AlbumArtFetcher()
fetcher.search_finished.connect(
lambda result: gen == self._generation
and self._on_search(result))
fetcher.image_finished.connect(
lambda result: gen == self._generation
and self._on_image(result))
self._fetchers = self._fetchers[-3:] + [fetcher]
return fetcher
def _on_search(self, result: dict):
self._candidates = result.get("candidates") or []
if not self._candidates:
self._art.setText("No artwork found" if "error" not in result
else "Artwork search failed")
self._caption.setText(result.get("error", ""))
self._settle()
return
self._next.setEnabled(len(self._candidates) > 1)
self._load()
def _load(self):
candidate = self._candidates[self._index]
n = len(self._candidates)
self._caption.setText(
f"{candidate.artist} — {candidate.album}, via {candidate.source}"
+ (f" ({self._index + 1}/{n})" if n > 1 else ""))
self._image = None
self._embed.setEnabled(False)
self._art.setPixmap(QPixmap())
self._art.setText("Loading…")
self._fetchers[-1].fetch(candidate)
self.changed.emit()
def next_artwork(self):
if len(self._candidates) < 2:
return
self._index = (self._index + 1) % len(self._candidates)
self._load()
def _on_image(self, result: dict):
if "candidate" in result and (
not self._candidates
or result["candidate"] is not self._candidates[self._index]):
return # a stale download after Next Artwork
if "error" in result:
self._art.setText("Couldn't load the image")
self._settle()
return
pixmap = QPixmap()
if not pixmap.loadFromData(result["image"]):
self._art.setText("Couldn't decode the image")
self._settle()
return
self._image = result["image"]
self._mime = result["mime"]
self._art.setPixmap(pixmap.scaled(
self._art.size(), Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation))
first = not self._settled
self._embed.setEnabled(True)
if first and self._embed_default:
self._embed.blockSignals(True)
self._embed.setChecked(True)
self._embed.blockSignals(False)
self.changed.emit()
self._settle()
def _settle(self):
if not self._settled:
self._settled = True
self.settled.emit()
# ---- what the caller reads ----
def set_embed_text(self, text: str):
self._embed.setText(text)
def image(self) -> bytes | None:
"""The picture on show, embedded or not."""
return self._image
def selected(self) -> tuple[bytes, str] | None:
"""(image, mime) when the Embed box is ticked over a picture."""
if self._image and self._embed.isChecked():
return self._image, self._mime
return None
+89 -8
View File
@@ -1,5 +1,5 @@
from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtCore import Qt, QSize, QTimer
from PyQt6.QtGui import QPainter, QPixmap
# Height left free for the window's own title bar. On Wayland the frame size
@@ -22,6 +22,31 @@ def fit_size(art: QSize, available: QSize,
return art.scaled(room, Qt.AspectRatioMode.KeepAspectRatio)
def reshaped(art: QSize, area: QSize, previous: QSize | None,
available: QSize | None = None) -> QSize:
"""The content size with the art's shape nearest ``area``.
The dimension that changed more since ``previous`` is the one the user
meant (dragging a side edge sets the width), and the other follows; the
result stays within ``available``.
"""
if art.isEmpty() or area.isEmpty():
return area
aspect = art.width() / art.height()
width_led = True
if previous is not None and not previous.isEmpty():
width_led = (abs(area.width() - previous.width()) / previous.width()
>= abs(area.height() - previous.height()) / previous.height())
if width_led:
size = QSize(area.width(), max(1, round(area.width() / aspect)))
else:
size = QSize(max(1, round(area.height() * aspect)), area.height())
if available is not None and not available.isEmpty() and (
size.width() > available.width() or size.height() > available.height()):
size = art.scaled(available, Qt.AspectRatioMode.KeepAspectRatio)
return size
def _aspect(pixmap: QPixmap | None) -> float | None:
if pixmap is None or pixmap.isNull() or pixmap.height() == 0:
return None
@@ -30,13 +55,28 @@ def _aspect(pixmap: QPixmap | None) -> float | None:
class ArtWindow(QWidget):
"""Non-modal window showing the current track's album art as large as
possible. Just an album art window — closing it has no side effects."""
possible. Just an album art window — closing it has no side effects.
A click anywhere on the art (or Esc) closes it, like the big
visualizer.
Never any background: the window keeps the art's shape (a resize is
snapped back to it once the drag pauses), and the art is painted to
*cover* the area, so even mid-drag or when the window can't be
reshaped (maximized) there is a sliver cropped, never a bar."""
RESHAPE_DELAY_MS = 150
def __init__(self, parent=None):
super().__init__(parent, Qt.WindowType.Window)
self._pixmap: QPixmap | None = None
self.setMinimumSize(120, 120)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.setToolTip("Click to close")
self._settled: QSize | None = None
self._reshape = QTimer(self)
self._reshape.setSingleShot(True)
self._reshape.setInterval(self.RESHAPE_DELAY_MS)
self._reshape.timeout.connect(self._snap_to_art)
def show_artwork(self, pixmap: QPixmap | None, title: str, screen=None):
"""Open (or re-raise) the window, sized to the art on ``screen``."""
@@ -54,7 +94,7 @@ class ArtWindow(QWidget):
self._pixmap = pixmap
if reshape:
# A track change brought a different shape of cover: re-fit, or
# the new art would sit between black bars.
# the new art would be cropped.
self.fit_to_screen()
self.update()
@@ -68,21 +108,62 @@ class ArtWindow(QWidget):
size = fit_size(self._pixmap.size(), geo.size())
# The app-drawn title bar (gui/titlebar.py) sits inside the window.
margins = self.contentsMargins()
self.resize(size.width(), size.height() + margins.top())
self._settled = size
self.resize(size.width() + margins.left() + margins.right(),
size.height() + margins.top() + margins.bottom())
# Wayland ignores move() (the compositor places the window); X11
# honors it.
self.move(geo.x() + (geo.width() - size.width()) // 2,
geo.y() + (geo.height() - size.height()) // 2)
def resizeEvent(self, event):
super().resizeEvent(event)
self._reshape.start()
def _snap_to_art(self):
if (self._pixmap is None or self._pixmap.isNull()
or self.isMaximized() or self.isFullScreen()):
return
area = self.contentsRect().size()
screen = self.screen() or QApplication.primaryScreen()
room = None
if screen is not None:
geo = screen.availableGeometry().size()
margins = self.contentsMargins()
room = QSize(geo.width() - margins.left() - margins.right(),
geo.height() - margins.top() - margins.bottom())
size = reshaped(self._pixmap.size(), area, self._settled, room)
self._settled = size
if abs(size.width() - area.width()) > 1 or abs(
size.height() - area.height()) > 1:
margins = self.contentsMargins()
self.resize(size.width() + margins.left() + margins.right(),
size.height() + margins.top() + margins.bottom())
def paintEvent(self, event):
painter = QPainter(self)
area = self.contentsRect()
painter.fillRect(area, Qt.GlobalColor.black)
if self._pixmap is None or self._pixmap.isNull():
return
painter = QPainter(self)
area = self.contentsRect()
painter.setClipRect(area)
# Cover, not fit: the window has the art's shape, so this crops at
# most a rounding pixel — and never leaves a bar.
scaled = self._pixmap.scaled(
area.size(), Qt.AspectRatioMode.KeepAspectRatio,
area.size(), Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation)
x = area.x() + (area.width() - scaled.width()) // 2
y = area.y() + (area.height() - scaled.height()) // 2
painter.drawPixmap(x, y, scaled)
def mouseReleaseEvent(self, event):
if (event.button() == Qt.MouseButton.LeftButton
and self.contentsRect().contains(event.position().toPoint())):
self.close()
return
super().mouseReleaseEvent(event)
def keyPressEvent(self, event):
if event.key() == Qt.Key.Key_Escape:
self.close()
return
super().keyPressEvent(event)
+48 -18
View File
@@ -1,9 +1,11 @@
"""Cassette's two little pictures, painted (no image files to ship or theme).
* The **cassette button**: a small embossed square with a tape glyph. Raised
when off; pressed in and grey when on ("I want this"); a medium grey on
hover over a pressed one, to say a click would let it go. Functionally
it's a checkbox — the tape is reserved for asking friends for songs.
when off; pressed in with a little blue down-arrow when on ("asked for,
on its way"); the arrow fades on hover over a pressed one, to say a click
would let it go. Partly asked for (an artist or album) is a paler
arrow. Functionally it's a checkbox — the tape is reserved for asking
friends for songs.
* The **UFO**: a friend's playlist. Light purple when followed, a grey
outline when not.
@@ -24,8 +26,7 @@ UFO_PURPLE = QColor("#b38ee8")
OFF, ON, PARTIAL = "off", "on", "partial"
ON_GREY = QColor("#9c9c9c")
ON_HOVER_GREY = QColor("#bdbdbd")
ASKED_BLUE = QColor("#2f7de1") # the "on its way" arrow
def friend_button_qss(selector: str = "QPushButton", padding: str = "3px 12px") -> str:
@@ -58,24 +59,56 @@ def paint_cassette_button(painter: QPainter, rect: QRectF, state: str,
gradient.setColorAt(0, top)
gradient.setColorAt(1, base.darker(106))
else:
fill = ON_HOVER_GREY if hovered else ON_GREY
if state == PARTIAL:
fill = QColor(fill).lighter(118)
gradient.setColorAt(0, fill.darker(108)) # pressed in: lit from below
gradient.setColorAt(1, fill.lighter(106))
gradient.setColorAt(0, base.darker(118)) # pressed in: lit from below
gradient.setColorAt(1, base.darker(104))
painter.setBrush(QBrush(gradient))
painter.setPen(QPen(mid, 1))
painter.drawRoundedRect(box, radius, radius)
ink = QColor(palette.text().color())
if state != OFF:
ink = QColor("#303030")
ink.setAlpha(200 if state != OFF else 150)
_paint_tape(painter, box, ink, half=(state == PARTIAL))
ink.setAlpha(150)
if state == OFF:
_paint_tape(painter, box, ink)
else:
# the tape moves up and left to make room for the arrow
_paint_tape(painter, box.translated(-box.width() * 0.06,
-box.height() * 0.08), ink)
blue = QColor(ASKED_BLUE)
blue.setAlpha((255 if state == ON else 130) // (2 if hovered else 1))
_paint_arrow(painter, box, blue, base.darker(110))
painter.restore()
def _paint_tape(painter: QPainter, box: QRectF, ink: QColor, half=False):
def _paint_arrow(painter: QPainter, box: QRectF, color: QColor,
halo: QColor):
"""A down-arrow in the bottom-right corner, ringed in the button's own
face so it stands off the tape behind it."""
w, h = box.width(), box.height()
cx = box.left() + w * 0.75
top, bottom = box.top() + h * 0.5, box.top() + h * 0.88
shaft, head = w * 0.08, w * 0.17
neck = bottom - h * 0.17
path = QPainterPath()
path.moveTo(cx - shaft, top)
path.lineTo(cx + shaft, top)
path.lineTo(cx + shaft, neck)
path.lineTo(cx + head, neck)
path.lineTo(cx, bottom)
path.lineTo(cx - head, neck)
path.lineTo(cx - shaft, neck)
path.closeSubpath()
line = max(1.0, w / 16)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.setPen(QPen(halo, line * 3, Qt.PenStyle.SolidLine,
Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin))
painter.drawPath(path)
painter.setPen(QPen(color, line, Qt.PenStyle.SolidLine,
Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin))
painter.setBrush(color)
painter.drawPath(path)
def _paint_tape(painter: QPainter, box: QRectF, ink: QColor):
"""A cassette: body, label window, two reels."""
w, h = box.width(), box.height()
body = QRectF(box.left() + w * 0.16, box.top() + h * 0.28,
@@ -96,9 +129,6 @@ def _paint_tape(painter: QPainter, box: QRectF, ink: QColor, half=False):
path.lineTo(body.left() + body.width() * 0.7, body.bottom() - body.height() * 0.22)
path.lineTo(body.left() + body.width() * 0.78, body.bottom())
painter.drawPath(path)
if half:
painter.drawLine(QPointF(body.left() + body.width() * 0.4, cy),
QPointF(body.left() + body.width() * 0.6, cy))
def paint_ufo(painter: QPainter, rect: QRectF, color: QColor,
+6 -2
View File
@@ -26,10 +26,13 @@ class DeliveryCoordinator(QObject):
library_grew = pyqtSignal(list) # new track ids
passed = pyqtSignal() # a pass finished (the cache may have moved)
def __init__(self, service, manager, parent=None):
def __init__(self, service, manager, parent=None, compress_kbps=None):
super().__init__(parent)
self._service = service
self._manager = manager
# () -> kbps to convert lossless arrivals to, or None (the
# "from Cassette friends too" preference, read at each pass).
self._compress_kbps = compress_kbps or (lambda: None)
self._worker = delivery.DeliveryWorker(self)
self._worker.finished.connect(self._on_finished)
self._again = False
@@ -102,7 +105,8 @@ class DeliveryCoordinator(QObject):
self._finish_receives(receives, set())
self.passed.emit()
return
self._worker.start(sends, receives, self._manager.organize_root())
self._worker.start(sends, receives, self._manager.organize_root(),
self._compress_kbps())
def _on_finished(self, result, receives):
added = []
+3
View File
@@ -21,6 +21,9 @@ def failure_text(exc: Exception) -> str:
return str(exc)
if isinstance(exc, st.SyncthingError):
if exc.kind == st.NOT_RUNNING:
hint = st.not_running_hint("try again")
if hint:
return f"{exc.step} failed: Syncthing isn't running. {hint}"
return (f"{exc.step} failed: Syncthing isn't running. Start "
f"Syncthing and try again.")
if exc.kind in (st.BAD_KEY, st.NO_KEY):
+4 -1
View File
@@ -84,7 +84,10 @@ class CassetteUi(QObject):
self._republish_timer.start()
if self._manager is not None:
from lintunes.gui.cassette_delivery import DeliveryCoordinator
self.delivery = DeliveryCoordinator(self.service, self._manager, self)
from lintunes.importers import lossless
self.delivery = DeliveryCoordinator(
self.service, self._manager, self,
compress_kbps=lambda: lossless.cassette_kbps(self._prefs))
self.delivery.notice.connect(self._on_notice)
self.delivery.step_failed.connect(self._on_step_failed)
self.delivery.library_grew.connect(self._on_library_grew)
+44 -13
View File
@@ -1,6 +1,6 @@
"""The "Connect to Chromecast…" picker.
"""The "Connect to Chromecast…" and "Connect to AirPlay…" pickers.
Searching starts when the dialog opens and stops when it closes, whichever way
One dialog over either discovery (they share a signal shape). Searching starts when the dialog opens and stops when it closes, whichever way
it closes. Connecting is not awaited here — the dialog's job ends at "which
device", and CastController reports the outcome on the status bar.
"""
@@ -17,22 +17,30 @@ from lintunes.gui.spinner import Spinner
EMPTY_AFTER_MS = 12_000
class ChromecastDialog(QDialog):
"""Lists Chromecasts as they're discovered; returns the one picked."""
class DevicePickerDialog(QDialog):
"""Lists devices as they're discovered; returns the one picked.
A device may carry `connectable=False` and a `note`: it is listed greyed
with the reason rather than hidden, so a speaker that can't be used
doesn't look like one that wasn't found.
"""
noun = "device" # "Searching for <noun>s…"
title = "Connect"
def __init__(self, discovery, parent=None):
super().__init__(parent)
self._discovery = discovery
self._selected = None
self.setWindowTitle("Connect to Chromecast")
self.setWindowTitle(self.title)
self.setMinimumWidth(340)
layout = QVBoxLayout(self)
header = QHBoxLayout()
self._spinner = Spinner()
header.addWidget(self._spinner)
self._status = QLabel("Searching for Chromecasts…")
self._status = QLabel(f"Searching for {self.noun}s…")
header.addWidget(self._status, stretch=1)
layout.addLayout(header)
@@ -81,12 +89,19 @@ class ChromecastDialog(QDialog):
label = device.name
if device.model:
label = f"{device.name} · {device.model}"
connectable = getattr(device, "connectable", True)
if not connectable:
label = f"{label} — {device.note}"
item = QListWidgetItem(label)
item.setData(Qt.ItemDataRole.UserRole, device)
if not connectable:
item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsEnabled
| Qt.ItemFlag.ItemIsSelectable))
self._list.addItem(item)
self._status.setText("Select a Chromecast to connect to.")
if self._list.count() == 1:
self._list.setCurrentRow(0)
if connectable:
self._status.setText(f"Select a {self.noun} to connect to.")
if self._list.currentItem() is None:
self._list.setCurrentItem(item)
def _on_lost(self, device):
for row in range(self._list.count()):
@@ -95,7 +110,7 @@ class ChromecastDialog(QDialog):
self._list.takeItem(row)
break
if self._list.count() == 0:
self._status.setText("Searching for Chromecasts…")
self._status.setText(f"Searching for {self.noun}s…")
def _on_failed(self, message: str):
self._spinner.hide()
@@ -106,16 +121,22 @@ class ChromecastDialog(QDialog):
if self._list.count() == 0:
# The spinner keeps turning: discovery is still running, and a
# device that comes online in a minute will still appear.
self._status.setText("No Chromecasts found on this network yet.")
self._status.setText(f"No {self.noun}s found on this network yet.")
elif not any(self._list.item(row).flags() & Qt.ItemFlag.ItemIsEnabled
for row in range(self._list.count())):
self._status.setText(
f"No {self.noun}s LinTunes can play to found yet.")
# ---- selection ----
def _on_selection_changed(self):
self._connect_button.setEnabled(self._list.currentItem() is not None)
item = self._list.currentItem()
self._connect_button.setEnabled(
item is not None and bool(item.flags() & Qt.ItemFlag.ItemIsEnabled))
def _on_connect(self):
item = self._list.currentItem()
if item is None:
if item is None or not item.flags() & Qt.ItemFlag.ItemIsEnabled:
return
self._selected = item.data(Qt.ItemDataRole.UserRole)
self.accept()
@@ -127,3 +148,13 @@ class ChromecastDialog(QDialog):
self._spinner.stop()
self._discovery.stop()
super().done(result)
class ChromecastDialog(DevicePickerDialog):
noun = "Chromecast"
title = "Connect to Chromecast"
class AirPlayDialog(DevicePickerDialog):
noun = "AirPlay speaker"
title = "Connect to AirPlay"
+506
View File
@@ -0,0 +1,506 @@
"""An import that compresses lossless files to MP3 (Round 106; the
converter is ``importers/lossless.py``).
``CompressImport`` runs one batch: hands the files to a ``CompressWorker``,
imports each one as it's ready (in order, so a playlist drop keeps its
order), and remembers every track it added — Cancel takes back *all* of
them, finished ones included, which is the point of the button. One file
shows its progress in the status bar (MainWindow's shared widgets); more
than one gets ``CompressProgress``, a non-modal window with a bar per song
and Cancel / Done. Closing that window while it works only hides it (the
status-bar line brings it back); closing it after is Done.
"""
from __future__ import annotations
import logging
import shutil
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from PyQt6.QtWidgets import (
QDialog, QHBoxLayout, QHeaderView, QLabel, QMessageBox, QProgressBar,
QPushButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout,
)
from lintunes import tagging
from lintunes.importers import file_importer, lossless
log = logging.getLogger(__name__)
WAITING = "Waiting"
IMPORTED = "Imported"
CONVERTED = "Converted and imported"
ALREADY = "Already in your library"
CANCELLED = "Cancelled"
READY = "Converted"
CONVERT_TITLE = "Converting to MP3"
NOT_IMPORTED = "Not imported"
def plan_items(files: list[Path], manager, music_dir: Path):
"""``(source, convert?, duration ms)`` for each file. A lossless file is
converted unless this very file is already in the library (then it
imports as it always did: as the existing track)."""
by_location = file_importer.location_index(manager)
items = []
for path in files:
source = Path(path).resolve()
convert = (source not in by_location and lossless.is_lossless(source))
duration = 0
if convert:
try:
duration = int(tagging.read_tags(source).get("total_time") or 0)
except Exception:
duration = 0
items.append((source, convert, duration))
return items
class CompressProgress(QDialog):
"""A row per song: name, a progress bar, and what happened."""
cancel_requested = pyqtSignal()
done_requested = pyqtSignal()
def __init__(self, items, kbps: int, parent=None, title: str = "Importing",
note: str = ""):
super().__init__(parent)
self.setWindowTitle(title)
self.setModal(False)
self.resize(640, 440)
self._finished = False
self._kbps = kbps
layout = QVBoxLayout(self)
self._summary = QLabel()
layout.addWidget(self._summary)
self._tree = QTreeWidget()
self._tree.setColumnCount(3)
self._tree.setHeaderLabels(["Song", "Progress", "Status"])
self._tree.setRootIsDecorated(False)
self._tree.setUniformRowHeights(True)
header = self._tree.header()
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
header.setStretchLastSection(False)
self._tree.setColumnWidth(1, 140)
self._bars: list[QProgressBar] = []
self._rows: list[QTreeWidgetItem] = []
for source, convert, _duration in items:
item = QTreeWidgetItem([source.name, "", WAITING])
item.setToolTip(0, str(source))
self._tree.addTopLevelItem(item)
bar = QProgressBar()
bar.setRange(0, 100)
bar.setValue(0)
bar.setTextVisible(convert)
bar.setMaximumHeight(16)
self._tree.setItemWidget(item, 1, bar)
self._rows.append(item)
self._bars.append(bar)
layout.addWidget(self._tree, 1)
buttons = QHBoxLayout()
self._note = QLabel(note or f"Lossless files become {kbps} kbps "
"MP3s; the originals aren't touched.")
self._note.setWordWrap(True)
buttons.addWidget(self._note, 1)
self.cancel_button = QPushButton("Cancel")
self.cancel_button.setToolTip(
"Stop, and take back every song this import added")
self.cancel_button.clicked.connect(self.cancel_requested)
self.done_button = QPushButton("Done")
self.done_button.setEnabled(False)
self.done_button.clicked.connect(self.done_requested)
buttons.addWidget(self.cancel_button)
buttons.addWidget(self.done_button)
layout.addLayout(buttons)
self._refresh_summary()
def status(self, index: int) -> str:
return self._rows[index].text(2)
def set_status(self, index: int, text: str, percent: int | None = None):
item = self._rows[index]
item.setText(2, text)
item.setToolTip(2, text)
if percent is not None:
self._bars[index].setValue(percent)
self._refresh_summary()
def started(self, index: int, converting: bool):
self.set_status(index, "Converting…" if converting else "Copying…")
self._tree.scrollToItem(self._rows[index])
def progress(self, index: int, percent: int):
self._bars[index].setValue(percent)
def finish(self, cancelled: bool):
self._finished = True
for index, item in enumerate(self._rows):
if item.text(2) in (WAITING, "Converting…", "Copying…"):
self.set_status(index, CANCELLED if cancelled else NOT_IMPORTED)
self.done_button.setEnabled(True)
self.done_button.setDefault(True)
self._refresh_summary()
def _refresh_summary(self):
statuses = [item.text(2) for item in self._rows]
landed = sum(1 for s in statuses
if s in (IMPORTED, CONVERTED, ALREADY, READY))
failed = sum(1 for s in statuses if s.startswith("Couldn't"))
verb = "converted" if self.windowTitle() == CONVERT_TITLE else "imported"
text = f"{landed} of {len(statuses)} songs {verb}"
if failed:
text += f" · {failed} couldn't be"
self._summary.setText(("Done: " if self._finished else "") + text)
def closeEvent(self, event):
# Working: just hide (the status bar brings it back). Finished: Done.
if self._finished:
self.done_requested.emit()
super().closeEvent(event)
class CompressImport(QObject):
"""One compressing import, from start to Done or Cancel."""
# (label, value, maximum) for the status bar while it works
status = pyqtSignal(str, int, int)
landed = pyqtSignal() # a song joined the library
worker_finished = pyqtSignal() # the status-bar widgets are free again
over = pyqtSignal(str) # the batch is closed; a closing message
def __init__(self, manager, music_dir: Path, items, kbps: int,
playlist_pid: str = "", position: int | None = None,
parent_widget=None, worker_factory=None):
super().__init__(parent_widget)
self._manager = manager
self._music_dir = music_dir
self._items = items
self._kbps = kbps
self._pid = playlist_pid
self._position = position
self._inserted = 0
self._by_location = file_importer.location_index(manager)
self.added: list[int] = [] # new tracks, in order
self._owned: set[int] = set() # ...whose file this import made
self._converted = 0
self._failures: list[str] = []
self._percent = {}
self._closed = False
factory = worker_factory or lossless.CompressWorker
self.worker = factory([(s, c, d) for s, c, d in items], kbps, self)
self.worker.started.connect(self._on_started)
self.worker.progress.connect(self._on_progress)
self.worker.ready.connect(self._on_ready)
self.worker.failed.connect(self._on_failed)
self.worker.finished.connect(self._on_finished)
self.window = None
if len(items) > 1:
self.window = CompressProgress(items, kbps, parent_widget)
self.window.cancel_requested.connect(self.request_cancel)
self.window.done_requested.connect(self.done)
def start(self):
self.worker.start()
if self.window is not None:
self.window.show()
def show_window(self):
if self.window is not None and not self._closed:
self.window.show()
self.window.raise_()
self.window.activateWindow()
# ---- the worker's reports ----
def _label(self, index: int) -> str:
return self._items[index][0].name
def _emit_status(self, index: int, percent: int):
total = len(self._items)
name = self._label(index)
name = name if len(name) <= 40 else name[:39] + "…"
if total == 1:
verb = "Converting" if self._items[index][1] else "Importing"
self.status.emit(f"{verb} {name}", percent, 100)
else:
self.status.emit(f"Importing {index + 1} of {total} · {name}",
index * 100 + percent, total * 100)
def _on_started(self, index: int):
if self.window is not None:
self.window.started(index, self._items[index][1])
self._emit_status(index, 0)
def _on_progress(self, index: int, percent: int):
if self.window is not None:
self.window.progress(index, percent)
self._emit_status(index, percent)
def _on_ready(self, index: int, path: str, converted: bool):
if self._closed:
return
source = self._items[index][0]
before = set(self._manager.library.tracks)
try:
if converted:
track = file_importer.import_converted(
Path(path), source, self._music_dir, self._manager,
self._by_location)
else:
track = file_importer.import_file(
source, self._music_dir, self._manager, self._by_location)
except Exception as e:
log.warning("Failed to import %s: %s", source, e)
self._on_failed(index, str(e))
return
if track is None:
self._on_failed(index, "not an audio file LinTunes can read")
return
new = track.track_id not in before
if new:
self.added.append(track.track_id)
# A file inside the music folder is imported where it is: not
# ours to trash on Cancel.
if Path(track.location) != source:
self._owned.add(track.track_id)
if converted:
self._converted += 1
if self._pid:
position = (None if self._position is None
else self._position + self._inserted)
self._manager.add_tracks_to_playlist(
self._pid, [track.track_id], position, undoable=False)
self._inserted += 1
if self.window is not None:
self.window.set_status(
index, (CONVERTED if converted else IMPORTED) if new else ALREADY,
100)
self.landed.emit()
def _on_failed(self, index: int, reason: str):
self._failures.append(f"{self._label(index)}: {reason}")
if self.window is not None:
self.window.set_status(index, f"Couldn't import: {reason}")
def _on_finished(self, summary: dict):
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
self.worker_finished.emit()
if self._closed:
return
if self.window is not None:
self.window.finish(summary.get("cancelled", False))
return
# One song: nothing more to decide.
self.done()
# ---- closing ----
def summary(self) -> str:
n = len(self.added)
text = f"Imported {n} song{'s' if n != 1 else ''}"
if self._converted:
text += f" ({self._converted} converted to {self._kbps} kbps MP3)"
if self._failures:
text += f" · {len(self._failures)} couldn't be"
return text
def done(self):
if self._closed:
return
self._closed = True
if self.window is not None:
self.window.hide()
self.over.emit(self.summary())
def request_cancel(self, confirm: bool = True):
"""Stop, and take back every song this batch added. Asks first when
that means removing songs already imported."""
if self._closed:
return
if confirm and self.added:
n = len(self.added)
box = QMessageBox(self.window or self.parent())
box.setWindowTitle("Cancel Import")
box.setText(f"Cancel the import and remove the {n} "
f"song{'s' if n != 1 else ''} it already added?")
box.setInformativeText(
"Their converted copies go to the trash. The files you "
"imported from aren't touched.")
go = box.addButton("Cancel Import", QMessageBox.ButtonRole.DestructiveRole)
keep = box.addButton("Keep Them", QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(keep)
box.exec()
if box.clickedButton() is not go:
return
self.worker.cancel()
self._closed = True
failures = self._manager.discard_imports(self.added, self._owned)
removed = len(self.added)
self.added = []
if self.window is not None:
self.window.hide()
self.landed.emit()
text = "Import cancelled"
if removed:
text += f" — removed {removed} song{'s' if removed != 1 else ''}"
if failures:
text += f" ({len(failures)} file(s) couldn't be trashed)"
self.over.emit(text)
def shutdown(self):
"""Quitting: stop converting, keep what landed."""
self.worker.cancel()
self._closed = True
if self.window is not None:
self.window.hide()
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
def convertible(tracks) -> list:
"""The tracks Convert to MP3 can do: a lossless file that's on disk."""
return [t for t in tracks if t.location and Path(t.location).is_file()
and lossless.is_lossless(Path(t.location))]
class ConvertLibrary(QObject):
"""Convert to MP3 on songs already in the library (Round 107).
Every song is converted into the staging folder first and nothing in
the library changes until the last one is done; then each MP3 is moved
beside its original and ``LibraryManager.replace_track_files`` swaps
them in one undo step (originals to the trash). So Cancel needs no
undoing: it stops and throws the MP3s away."""
status = pyqtSignal(str, int, int)
worker_finished = pyqtSignal()
over = pyqtSignal(str)
def __init__(self, manager, tracks, kbps: int, parent_widget=None,
worker_factory=None):
super().__init__(parent_widget)
self._manager = manager
self._tracks = list(tracks)
self._kbps = kbps
self._items = [(Path(t.location), True, int(t.total_time or 0))
for t in self._tracks]
self._ready: dict[int, Path] = {}
self._failures: list[str] = []
self._closed = False
factory = worker_factory or lossless.CompressWorker
self.worker = factory(self._items, kbps, self)
self.worker.started.connect(self._on_started)
self.worker.progress.connect(self._on_progress)
self.worker.ready.connect(self._on_ready)
self.worker.failed.connect(self._on_failed)
self.worker.finished.connect(self._on_finished)
self.window = None
if len(self._tracks) > 1:
self.window = CompressProgress(
self._items, kbps, parent_widget, title=CONVERT_TITLE,
note=f"Each song becomes a {kbps} kbps MP3 when all are done; "
"the originals go to the trash. Edit ▸ Undo puts them back.")
for item, track in zip(self.window._rows, self._tracks):
item.setText(0, f"{track.artist} — {track.name}"
if track.artist else track.name)
self.window.cancel_requested.connect(self.request_cancel)
self.window.done_requested.connect(self._close_window)
def start(self):
self.worker.start()
if self.window is not None:
self.window.show()
def show_window(self):
if self.window is not None:
self.window.show()
self.window.raise_()
self.window.activateWindow()
def _label(self, index: int) -> str:
track = self._tracks[index]
return track.name or Path(track.location).name
def _emit_status(self, index: int, percent: int):
total = len(self._items)
name = self._label(index)
name = name if len(name) <= 40 else name[:39] + "…"
if total == 1:
self.status.emit(f"Converting {name}", percent, 100)
else:
self.status.emit(f"Converting {index + 1} of {total} · {name}",
index * 100 + percent, total * 100)
def _on_started(self, index: int):
if self.window is not None:
self.window.started(index, True)
self._emit_status(index, 0)
def _on_progress(self, index: int, percent: int):
if self.window is not None:
self.window.progress(index, percent)
self._emit_status(index, percent)
def _on_ready(self, index: int, path: str, _converted: bool):
self._ready[index] = Path(path)
if self.window is not None:
self.window.set_status(index, READY, 100)
def _on_failed(self, index: int, reason: str):
self._failures.append(f"{self._label(index)}: {reason}")
if self.window is not None:
self.window.set_status(index, f"Couldn't convert: {reason}")
def _on_finished(self, summary: dict):
try:
if self._closed or summary.get("cancelled"):
return
changes, move_failures = [], []
for index, mp3 in sorted(self._ready.items()):
track = self._tracks[index]
original = Path(track.location)
try:
dest = file_importer.unique_path(original.with_suffix(".mp3"))
shutil.move(str(mp3), str(dest))
except OSError as e:
move_failures.append(f"{self._label(index)}: {e}")
continue
changes.append((track.track_id, dest))
failures = self._manager.replace_track_files(changes)
done = len(changes) - len(failures)
text = f"Converted {done} song{'s' if done != 1 else ''} to {self._kbps} kbps MP3"
problems = len(self._failures) + len(move_failures) + len(failures)
if problems:
text += f" · {problems} couldn't be"
for line in self._failures + move_failures:
log.warning("Convert to MP3: %s", line)
if self.window is not None:
self.window.finish(False)
self.window.cancel_button.setEnabled(False)
self._closed = True
self.over.emit(text)
finally:
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
self.worker_finished.emit()
def _close_window(self):
if self.window is not None:
self.window.hide()
def request_cancel(self, confirm: bool = True):
"""Nothing has changed yet, so there is nothing to ask about."""
if self._closed:
self._close_window()
return
self._closed = True
self.worker.cancel()
self._close_window()
self.over.emit("Convert to MP3 cancelled — nothing was changed")
def shutdown(self):
self.worker.cancel()
self._closed = True
self._close_window()
shutil.rmtree(self.worker.tmp_dir, ignore_errors=True)
File diff suppressed because it is too large Load Diff
+99
View File
@@ -0,0 +1,99 @@
"""The status bar's "already in the playlist" notice (Round 132).
Adding songs a playlist already has used to stop everything with a modal
prompt. Now (unless the ``ask_on_duplicates`` preference brings the prompt
back) playlist_ops adds only the new songs and this says so in the status
bar, with an Add Anyway button that adds the rest. It shows for ``SHOW_MS``
and then fades out; the cursor over it holds it, so it never vanishes from
under a click.
"""
from PyQt6.QtCore import QPropertyAnimation, QTimer
from PyQt6.QtWidgets import (
QGraphicsOpacityEffect, QHBoxLayout, QLabel, QPushButton, QWidget)
SHOW_MS = 10_000
FADE_MS = 600
# After the cursor leaves, a little longer to come back to it.
LINGER_MS = 3_000
def message(name: str, skipped: int, added: int) -> str:
songs = "1 song was" if skipped == 1 else f"{skipped} songs were"
if added:
return (f"{songs} already in “{name}” — "
"only the new ones were added")
return f"{songs} already in “{name}” — nothing was added"
class DuplicateNotice(QWidget):
def __init__(self, prefs, parent=None):
super().__init__(parent)
self._prefs = prefs
self._action = None
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 6, 0)
layout.setSpacing(6)
self.label = QLabel()
layout.addWidget(self.label)
self.button = QPushButton("Add Anyway")
# The shared button face, only shrunk to fit the status bar
# (main_window._CancelSyncButton's rule).
self.button.setStyleSheet("QPushButton { padding: 0 6px; "
"min-height: 0; }")
self.button.clicked.connect(self._add_anyway)
layout.addWidget(self.button)
self._effect = QGraphicsOpacityEffect(self)
self._effect.setOpacity(1.0)
self.setGraphicsEffect(self._effect)
self._fade = QPropertyAnimation(self._effect, b"opacity", self)
self._fade.setDuration(FADE_MS)
self._fade.setStartValue(1.0)
self._fade.setEndValue(0.0)
self._fade.finished.connect(self.dismiss)
self._timer = QTimer(self)
self._timer.setSingleShot(True)
self._timer.timeout.connect(self._fade.start)
self.hide()
def quiet(self) -> bool:
"""Whether duplicates are skipped quietly (vs. asked about)."""
return not bool(self._prefs.get("ask_on_duplicates", False))
def show_skipped(self, name: str, skipped: int, added: int, action):
"""Say ``skipped`` songs were left out of ``name``; ``action`` adds
them. A newer add replaces whatever was showing."""
self._fade.stop()
self._effect.setOpacity(1.0)
self._action = action
self.label.setText(message(name, skipped, added))
self.button.setEnabled(True)
self.show()
self._timer.start(SHOW_MS)
def dismiss(self):
self._timer.stop()
self._fade.stop()
self._action = None
self.hide()
self._effect.setOpacity(1.0)
def _add_anyway(self):
action = self._action
self.dismiss()
if action is not None:
action()
def enterEvent(self, event):
if self.isVisible():
self._timer.stop()
self._fade.stop()
self._effect.setOpacity(1.0)
super().enterEvent(event)
def leaveEvent(self, event):
if self.isVisible() and self._action is not None:
self._timer.start(LINGER_MS)
super().leaveEvent(event)
+133 -26
View File
@@ -1,7 +1,8 @@
"""The two dialogs behind File → Export Playlist…
`ExportKindDialog` asks folder-or-website; `WebMixDialog` collects the bits of
a web mix that can't be inferred — title, blurb, hero image, accent color.
a web mix that can't be inferred — title, blurb, images, accent color —
and whether to upload it to the web server set in Preferences (Round 81).
Per-track liner notes are deliberately absent: the hand-made mixes carry a numbered paragraph
per track, which is far too much to type into a form, so the generated
index.html leaves a commented-out block in the right place instead.
@@ -12,14 +13,13 @@ from pathlib import Path
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QColor
from PyQt6.QtWidgets import (
QColorDialog, QDialog, QDialogButtonBox, QFileDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QPlainTextEdit, QPushButton, QRadioButton,
QVBoxLayout)
QCheckBox, QColorDialog, QDialog, QDialogButtonBox, QFileDialog,
QFormLayout, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPlainTextEdit,
QPushButton, QRadioButton, QVBoxLayout, QWidget)
from lintunes import theme
from lintunes.export import exporter
_IMAGE_FILTER = "Images (*.png *.jpg *.jpeg *.gif *.webp)"
from lintunes.export import exporter, upload
from lintunes.gui.file_filters import WEB_IMAGE_FILTER as _IMAGE_FILTER
class ExportKindDialog(QDialog):
@@ -67,15 +67,20 @@ class ExportKindDialog(QDialog):
class WebMixDialog(QDialog):
"""Title, description, hero image and accent color for a web mix.
"""Title, description, images and accent color for a web mix.
The accent isn't remembered between exports: it opens on
``exporter.DEFAULT_ACCENT`` every time, so an export nobody touched comes
out looking exactly like the mixes already online.
`config` is config.json's contents, read for the web server. The upload
box is never ticked by default, and a ticked box with no server set up
keeps the dialog open rather than failing later.
"""
def __init__(self, playlist_name: str, parent=None):
def __init__(self, playlist_name: str, parent=None, config=None):
super().__init__(parent)
self._server = upload.server_settings(config or {})
self.setWindowTitle("Export Web Mix")
self.setMinimumWidth(520)
layout = QVBoxLayout(self)
@@ -91,18 +96,15 @@ class WebMixDialog(QDialog):
self._description.setMinimumHeight(140)
form.addRow("Description:", self._description)
image_row = QHBoxLayout()
self._image = QLineEdit()
self._image.setPlaceholderText("(a gray placeholder)")
self._image.setReadOnly(True)
image_row.addWidget(self._image, stretch=1)
browse = QPushButton("Browse…")
browse.clicked.connect(self._choose_image)
image_row.addWidget(browse)
clear = QPushButton("Clear")
clear.clicked.connect(lambda: self._image.clear())
image_row.addWidget(clear)
form.addRow("Image:", image_row)
# One row per image, always with an empty one at the end: choosing a
# file in the last row adds another below it, and clearing any other
# row removes it.
images = QWidget()
self._image_rows = QVBoxLayout(images)
self._image_rows.setContentsMargins(0, 0, 0, 0)
self._images: list[QLineEdit] = []
self._add_image_row()
form.addRow("Images:", images)
color_row = QHBoxLayout()
self._accent = exporter.DEFAULT_ACCENT
@@ -129,6 +131,29 @@ class WebMixDialog(QDialog):
note.setEnabled(False)
layout.addWidget(note)
layout.addSpacing(8)
self._upload = QCheckBox("Upload to web server")
layout.addWidget(self._upload)
upload_form = QFormLayout()
upload_form.setFieldGrowthPolicy(
QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
upload_form.setContentsMargins(24, 0, 0, 0)
# The slug follows the title until it is edited by hand.
self._slug = QLineEdit(upload.slugify(playlist_name))
self._slug_edited = False
self._slug.textEdited.connect(self._on_slug_edited)
self._slug.textChanged.connect(self._refresh_upload_note)
self._title.textEdited.connect(self._on_title_edited)
upload_form.addRow("Folder on server:", self._slug)
layout.addLayout(upload_form)
self._upload_note = QLabel()
self._upload_note.setWordWrap(True)
self._upload_note.setIndent(24)
self._upload_note.setEnabled(False)
layout.addWidget(self._upload_note)
self._upload.toggled.connect(self._refresh_upload_note)
self._refresh_upload_note()
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
| QDialogButtonBox.StandardButton.Cancel)
buttons.button(QDialogButtonBox.StandardButton.Ok).setText("Export")
@@ -136,12 +161,92 @@ class WebMixDialog(QDialog):
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def _choose_image(self):
start = str(Path(self._image.text()).parent) if self._image.text() else ""
def _on_title_edited(self, text: str):
if not self._slug_edited:
self._slug.setText(upload.slugify(text))
def _on_slug_edited(self, _text: str):
self._slug_edited = True
def _refresh_upload_note(self):
on = self._upload.isChecked()
self._slug.setEnabled(on)
if self._server is None:
text = ("Not set up yet — fill in the web server in Preferences → "
"Integrations → Web Server.")
else:
host, path = self._server
slug = self._slug.text().strip() or "…"
try:
where = f"{host}:{upload.remote_dir(path, slug)}"
except upload.UploadError:
where = f"{host}:{path.rstrip('/')}/{slug}"
text = (f"Uploads to {where} instead of a folder here. If a mix "
"with that folder name is already on the server, it is "
"replaced by this one.")
self._upload_note.setText(text)
def accept(self):
if self._upload.isChecked():
if self._server is None:
QMessageBox.warning(
self, "Web server not set up",
"Fill in the web server details in Preferences → "
"Integrations to upload this mix, or uncheck "
"“Upload to web server” to export it to a folder here.")
return
if not upload.valid_slug(self._slug.text().strip()):
QMessageBox.warning(
self, "Folder on server",
"Give the mix a folder name for the server — letters, "
"numbers and dashes work best, since it becomes part "
"of the web address.")
return
super().accept()
def _add_image_row(self):
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 0, 0, 0)
field = QLineEdit()
field.setReadOnly(True)
field.setPlaceholderText("(a gray placeholder)" if not self._images
else "(add another image)")
layout.addWidget(field, stretch=1)
browse = QPushButton("Browse…")
browse.clicked.connect(lambda: self._choose_image(field))
layout.addWidget(browse)
clear = QPushButton("Clear")
clear.clicked.connect(lambda: self._clear_image(field))
layout.addWidget(clear)
self._images.append(field)
self._image_rows.addWidget(row)
def _choose_image(self, field: QLineEdit):
# Start where this row's image is, or where the last one came from.
near = field.text() or next(
(f.text() for f in reversed(self._images) if f.text()), "")
start = str(Path(near).parent) if near else ""
name, _filter = QFileDialog.getOpenFileName(
self, "Choose Image", start, _IMAGE_FILTER)
if name:
self._image.setText(name)
self._set_image(field, name)
def _set_image(self, field: QLineEdit, path: str):
field.setText(path)
if field is self._images[-1]:
self._add_image_row()
def _clear_image(self, field: QLineEdit):
if field is self._images[-1]:
field.clear()
return
index = self._images.index(field)
self._images.pop(index)
row = self._image_rows.takeAt(index).widget()
row.deleteLater()
# The first row's placeholder says what an export with none gets.
self._images[0].setPlaceholderText("(a gray placeholder)")
def _set_accent(self, color_hex: str):
self._accent = exporter.normalize_accent(color_hex)
@@ -155,10 +260,12 @@ class WebMixDialog(QDialog):
self._set_accent(color.name())
def values(self) -> dict:
text = self._image.text().strip()
return {
"title": self._title.text().strip(),
"description": self._description.toPlainText().strip(),
"image": Path(text) if text else None,
"images": [Path(f.text().strip()) for f in self._images
if f.text().strip()],
"accent": self._accent,
"upload": self._upload.isChecked(),
"slug": self._slug.text().strip(),
}
+17
View File
@@ -0,0 +1,17 @@
"""File-dialog name filters.
Qt matches a filter's patterns case-sensitively on Linux, so "*.jpg" hides
a phone photo called IMG_1897.JPG. Every pattern is listed in both cases.
"""
_IMAGE_SUFFIXES = ("png", "jpg", "jpeg", "gif", "bmp", "webp")
def image_filter(suffixes=_IMAGE_SUFFIXES) -> str:
patterns = " ".join(f"*.{s} *.{s.upper()}" for s in suffixes)
return f"Images ({patterns})"
IMAGE_FILTER = image_filter()
# What a web page can show: no BMP.
WEB_IMAGE_FILTER = image_filter(("png", "jpg", "jpeg", "gif", "webp"))
+118 -1
View File
@@ -2,7 +2,8 @@
so buttons can flash the theme highlight while pressed."""
from PyQt6.QtCore import Qt, QPointF, QRectF
from PyQt6.QtGui import QIcon, QPixmap, QPainter, QPen, QColor, QPolygonF
from PyQt6.QtGui import (QIcon, QPixmap, QPainter, QPainterPath, QPen, QColor,
QPolygonF)
_cache: dict[tuple, QIcon] = {}
@@ -74,6 +75,41 @@ def _shuffle(p, color):
p.drawPolygon(QPolygonF([QPointF(15, 11), QPointF(19, 14), QPointF(15, 17)]))
def _repeat(p, color):
"""iTunes' repeat: a loop of two strands with rounded far corners, the
top one arrowed to the right, the bottom one back to the left."""
pen = QPen(color, 1.8)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
top = QPainterPath(QPointF(3, 11.5))
top.lineTo(3, 9)
top.quadTo(3, 6, 6, 6)
top.lineTo(14, 6)
bottom = QPainterPath(QPointF(17, 8.5))
bottom.lineTo(17, 11)
bottom.quadTo(17, 14, 14, 14)
bottom.lineTo(6, 14)
p.drawPath(top)
p.drawPath(bottom)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(color)
p.drawPolygon(QPolygonF([QPointF(13.5, 2.8), QPointF(18, 6), QPointF(13.5, 9.2)]))
p.drawPolygon(QPolygonF([QPointF(6.5, 10.8), QPointF(2, 14), QPointF(6.5, 17.2)]))
def _repeat_one(p, color):
"""Repeat with a "1" inside the loop."""
_repeat(p, color)
pen = QPen(color, 1.9)
pen.setCapStyle(Qt.PenCapStyle.FlatCap)
pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawPolyline(QPolygonF([QPointF(8.6, 8.9), QPointF(10.6, 7.4),
QPointF(10.6, 12.6)]))
def _cast(p, color):
"""The standard cast glyph: a screen with signal arcs at its lower left.
The screen is lit rather than empty — it is only ever drawn while a device
@@ -102,11 +138,92 @@ def _cast(p, color):
p.drawEllipse(QPointF(3.8, 15.2), 1.5, 1.5)
def _airplay(p, color):
"""The AirPlay glyph: a screen whose bottom edge opens around a solid
triangle rising into it."""
pen = QPen(color, 1.6)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawPolyline(QPolygonF([
QPointF(6.0, 14.0), QPointF(3.5, 14.0), QPointF(3.5, 3.5),
QPointF(16.5, 3.5), QPointF(16.5, 14.0), QPointF(14.0, 14.0),
]))
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(color)
p.drawPolygon(QPolygonF([
QPointF(10.0, 11.0), QPointF(14.5, 17.0), QPointF(5.5, 17.0),
]))
def _sun(p, color):
"""Light mode's glyph: a disc and eight rays."""
import math
p.drawEllipse(QPointF(10, 10), 3.6, 3.6)
pen = QPen(color, 1.8)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
for i in range(8):
a = i * math.pi / 4
p.drawLine(QPointF(10 + 6 * math.cos(a), 10 + 6 * math.sin(a)),
QPointF(10 + 8.4 * math.cos(a), 10 + 8.4 * math.sin(a)))
def _moon(p, _color):
"""Dark mode's glyph: a crescent."""
disc = QPainterPath()
disc.addEllipse(QPointF(10, 10), 7.5, 7.5)
bite = QPainterPath()
bite.addEllipse(QPointF(13.5, 7), 6.5, 6.5)
p.drawPath(disc.subtracted(bite))
def _speakers(p, color):
"""Choose a speaker: a loudspeaker with two sound waves."""
p.drawPolygon(QPolygonF([
QPointF(2.5, 7.5), QPointF(5.5, 7.5), QPointF(10.0, 3.5),
QPointF(10.0, 16.5), QPointF(5.5, 12.5), QPointF(2.5, 12.5),
]))
pen = QPen(color, 1.6)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
for radius in (3.2, 6.4): # arcs centred on the cone's mouth
p.drawArc(QRectF(10.0 - radius, 10.0 - radius, radius * 2, radius * 2),
-50 * 16, 100 * 16)
def _identify(p, color):
"""Identify Track: a cassette with a lowercase "i" between its reels."""
pen = QPen(color, 1.5)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRoundedRect(QRectF(1.5, 4.0, 17.0, 12.0), 1.8, 1.8)
for x in (5.6, 14.4):
p.drawEllipse(QPointF(x, 9.0), 1.9, 1.9)
# where the tape shows, along the bottom
p.drawPolyline(QPolygonF([QPointF(4.5, 16.0), QPointF(6.0, 13.6),
QPointF(14.0, 13.6), QPointF(15.5, 16.0)]))
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(color)
p.drawEllipse(QPointF(10.0, 6.4), 1.05, 1.05) # the i's dot
p.drawRoundedRect(QRectF(9.2, 8.2, 1.6, 4.0), 0.5, 0.5)
_DRAWERS = {
"play": _play,
"pause": _pause,
"next": _next,
"previous": _previous,
"shuffle": _shuffle,
"repeat": _repeat,
"repeat_one": _repeat_one,
"cast": _cast,
"airplay": _airplay,
"sun": _sun,
"moon": _moon,
"speakers": _speakers,
"identify": _identify,
}
+137 -90
View File
@@ -11,22 +11,28 @@ album-wide fields sit above the table, once. Editing them edits every row.
Beside them is the album's cover from the same search Download Album Art
uses, with Next Artwork to cycle through the results.
A playlist gets a cover per album (Round 119): a Cover column shows each
song's, and the panel beside the table is the selected song's album —
its picture, Next Artwork, and whether to embed it in that album's songs.
The searches run one at a time, so a long playlist doesn't fire dozens
at the art APIs at once.
Passive like IdentifyDialog: nothing is written until the caller reads
``edits()``, ``unchecked_rows()`` and ``selected_image`` after an accept.
``edits()``, ``unchecked_rows()`` and ``selected_art()`` after an accept.
"""
import re
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QPixmap
from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QFont, QIcon, QPixmap
from PyQt6.QtWidgets import (
QAbstractItemView, QCheckBox, QDialog, QDialogButtonBox, QFormLayout,
QAbstractItemView, QDialog, QDialogButtonBox, QFormLayout,
QHBoxLayout, QHeaderView, QLabel, QLineEdit, QPushButton, QSpinBox,
QTableWidget, QTableWidgetItem, QVBoxLayout,
QStackedWidget, QTableWidget, QTableWidgetItem, QVBoxLayout,
)
from lintunes.art_search import AlbumArtFetcher
from lintunes.gui.art_picker import ART_PX, ArtPicker
ART_PX = 180
THUMB_PX = 36
# (header, fields shown in the column)
COLUMNS = [
@@ -86,14 +92,15 @@ class IdentifyBatchDialog(QDialog):
r.proposal.get("track_number")
or 999))
self.outcome = 0
self.selected_image: bytes | None = None
self.selected_mime = "image/jpeg"
self._art_candidates = []
self._art_index = 0
self._art_image = None
self._art_mime = "image/jpeg"
self._fetcher = None
self._filling = False
# Playlist mode: one picker per album, the rows that album covers,
# and the searches still waiting their turn.
self._pickers: dict[tuple, ArtPicker] = {}
self._group_rows: dict[tuple, list[int]] = {}
self._row_group: dict[int, tuple] = {}
self._art_queue: list[ArtPicker] = []
self._art = None
self._cover_col = None
layout = QVBoxLayout(self)
n = len(self._rows)
@@ -106,13 +113,16 @@ class IdentifyBatchDialog(QDialog):
layout.addWidget(header)
self._album_edit = self._album_artist_edit = self._year_edit = None
self._embed = None
if analysis.is_album:
layout.addLayout(self._album_panel(art_query))
else:
self._cover_col = SOURCE_COL + 1
self._table = QTableWidget(n, SOURCE_COL + 1)
columns = SOURCE_COL + 1 + (self._cover_col is not None)
self._table = QTableWidget(n, columns)
self._table.setHorizontalHeaderLabels(
[""] + [h for h, _f in COLUMNS] + ["Found by"])
[""] + [h for h, _f in COLUMNS] + ["Found by"]
+ (["Cover"] if self._cover_col is not None else []))
self._table.verticalHeader().hide()
self._table.setSelectionBehavior(
QAbstractItemView.SelectionBehavior.SelectRows)
@@ -124,13 +134,29 @@ class IdentifyBatchDialog(QDialog):
head.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
head.setSectionResizeMode(CHECK_COL,
QHeaderView.ResizeMode.ResizeToContents)
if self._cover_col is None:
head.setStretchLastSection(True)
else:
head.setSectionResizeMode(SOURCE_COL,
QHeaderView.ResizeMode.Stretch)
head.setSectionResizeMode(self._cover_col,
QHeaderView.ResizeMode.Fixed)
self._table.setColumnWidth(self._cover_col, THUMB_PX + 16)
self._table.setIconSize(QSize(THUMB_PX, THUMB_PX))
self._table.verticalHeader().setDefaultSectionSize(THUMB_PX + 6)
self._fill_table()
self._table.itemChanged.connect(self._on_item_changed)
for col, width in zip(range(FIRST_FIELD_COL, SOURCE_COL),
(200, 150, 120, 170, 55, 70, 45)):
self._table.setColumnWidth(col, width)
if self._cover_col is None:
layout.addWidget(self._table, 1)
else:
middle = QHBoxLayout()
middle.addWidget(self._table, 1)
middle.addSpacing(8)
middle.addWidget(self._cover_panel())
layout.addLayout(middle, 1)
hint = QLabel("Bold is what changes (hover to see what it was). "
"Double-click to edit. Unticked songs are shown one "
@@ -157,20 +183,24 @@ class IdentifyBatchDialog(QDialog):
layout.addWidget(buttons)
self._update_apply()
self._table.setFocus() # not the Album box: nothing to type yet
self.resize(1000, min(260 + 30 * n + (ART_PX if analysis.is_album
else 0), 820))
if self._cover_col is None:
self.resize(1000, min(260 + 30 * n + ART_PX, 820))
else:
self.resize(1260, min(max(260 + (THUMB_PX + 6) * n,
ART_PX + 260), 820))
if n:
self._table.selectRow(0)
self._next_search()
# ---- the album panel ----
def _album_panel(self, art_query):
a = self._analysis
row = QHBoxLayout()
self._art = QLabel("Searching…" if art_query else "No artwork search")
self._art.setFixedSize(ART_PX, ART_PX)
self._art.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._art.setStyleSheet("border: 1px solid palette(mid);")
self._art.setWordWrap(True)
self._art = ArtPicker(f"Embed this artwork in all "
f"{len(self._rows)} songs", parent=self)
row.addWidget(self._art)
row.addSpacing(12)
side = QVBoxLayout()
form = QFormLayout()
@@ -191,79 +221,79 @@ class IdentifyBatchDialog(QDialog):
self._year_edit.valueChanged.connect(
lambda v: self._set_column(("year",), str(v) if v else ""))
side.addLayout(form)
self._art_caption = QLabel()
self._art_caption.setWordWrap(True)
self._art_caption.setEnabled(False)
side.addWidget(self._art_caption)
art_row = QHBoxLayout()
self._embed = QCheckBox(f"Embed this artwork in all "
f"{len(self._rows)} songs")
self._embed.setEnabled(False)
self._next_art = QPushButton("Next Artwork")
self._next_art.setEnabled(False)
self._next_art.clicked.connect(self._on_next_art)
art_row.addWidget(self._embed)
art_row.addWidget(self._next_art)
art_row.addStretch(1)
side.addLayout(art_row)
side.addStretch(1)
row.addLayout(side, 1)
if art_query:
self._fetcher = AlbumArtFetcher()
self._fetcher.search_finished.connect(self._on_art_search)
self._fetcher.image_finished.connect(self._on_art_image)
self._fetcher.search(*art_query)
self._art.search(*art_query)
return row
def _on_art_search(self, result: dict):
self._art_candidates = result.get("candidates") or []
if not self._art_candidates:
self._art.setText("No artwork found" if "error" not in result
else "Artwork search failed")
self._art_caption.setText(result.get("error", ""))
return
self._next_art.setEnabled(len(self._art_candidates) > 1)
self._load_art()
# ---- a playlist's covers, one per album ----
def _load_art(self):
candidate = self._art_candidates[self._art_index]
n = len(self._art_candidates)
self._art_caption.setText(
f"{candidate.artist} — {candidate.album}, via {candidate.source}"
+ (f" ({self._art_index + 1}/{n})" if n > 1 else ""))
self._art_image = None
self._embed.setEnabled(False)
self._art.setPixmap(QPixmap())
self._art.setText("Loading…")
self._fetcher.fetch(candidate)
def _cover_panel(self):
"""The selected song's album cover, with a picker per album held in
a stack: switching songs on one album keeps its choice."""
for r, row in enumerate(self._rows):
artist = (row.proposal.get("album_artist")
or row.current("album_artist")
or row.proposal.get("artist") or row.current("artist"))
album = row.proposal.get("album") or row.current("album")
if not (artist and album):
continue
key = (artist.casefold(), album.casefold())
self._row_group[r] = key
self._group_rows.setdefault(key, []).append(r)
if key not in self._pickers:
picker = ArtPicker(parent=self)
picker.query = (artist, album) # searched in turn
picker.changed.connect(
lambda k=key: self._refresh_thumbs(k))
picker.settled.connect(self._next_search)
self._pickers[key] = picker
self._art_queue.append(picker)
for key, picker in self._pickers.items():
n = len(self._group_rows[key])
picker.set_embed_text("Embed in this song" if n == 1 else
f"Embed in its {n} songs here")
self._cover_stack = QStackedWidget()
self._no_album = QLabel("This song has no album to search "
"artwork by.")
self._no_album.setWordWrap(True)
self._no_album.setEnabled(False)
self._no_album.setFixedWidth(ART_PX)
self._no_album.setAlignment(Qt.AlignmentFlag.AlignTop)
self._cover_stack.addWidget(self._no_album)
for picker in self._pickers.values():
picker._art.setText("Waiting to search…")
self._cover_stack.addWidget(picker)
self._table.itemSelectionChanged.connect(self._show_cover)
return self._cover_stack
def _on_next_art(self):
self._art_index = (self._art_index + 1) % len(self._art_candidates)
self._load_art()
def _next_search(self):
if self._art_queue:
picker = self._art_queue.pop(0)
picker.search(*picker.query)
def _on_art_image(self, result: dict):
if not self._art_candidates or result.get("candidate") is not \
self._art_candidates[self._art_index]:
if "candidate" in result:
return # a stale download after Next Artwork
if "error" in result:
self._art.setText("Couldn't load the image")
return
def _show_cover(self):
rows = {i.row() for i in self._table.selectedItems()}
key = self._row_group.get(min(rows)) if rows else None
self._cover_stack.setCurrentWidget(
self._pickers[key] if key else self._no_album)
def _refresh_thumbs(self, key):
picker = self._pickers[key]
chosen = picker.selected()
icon = QIcon()
if chosen:
pixmap = QPixmap()
if not pixmap.loadFromData(result["image"]):
self._art.setText("Couldn't decode the image")
return
self._art_image = result["image"]
self._art_mime = result["mime"]
self._art.setPixmap(pixmap.scaled(
self._art.size(), Qt.AspectRatioMode.KeepAspectRatio,
if pixmap.loadFromData(chosen[0]):
icon = QIcon(pixmap.scaled(
THUMB_PX, THUMB_PX, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation))
first = not self._embed.isEnabled() and self._art_index == 0
self._embed.setEnabled(True)
if first:
self._embed.setChecked(True)
self._table.blockSignals(True)
for r in self._group_rows[key]:
self._table.item(r, self._cover_col).setIcon(icon)
self._table.blockSignals(False)
# ---- the table ----
@@ -293,6 +323,12 @@ class IdentifyBatchDialog(QDialog):
source.setFlags(Qt.ItemFlag.ItemIsEnabled
| Qt.ItemFlag.ItemIsSelectable)
self._table.setItem(r, SOURCE_COL, source)
if self._cover_col is not None:
cover = QTableWidgetItem()
cover.setFlags(Qt.ItemFlag.ItemIsEnabled
| Qt.ItemFlag.ItemIsSelectable)
cover.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
self._table.setItem(r, self._cover_col, cover)
self._filling = False
def _mark(self, r: int, c: int):
@@ -371,12 +407,23 @@ class IdentifyBatchDialog(QDialog):
def all_rows(self) -> list:
return list(self._rows)
def selected_art(self) -> list:
"""[(rows, image, mime)] for every cover whose Embed box is ticked —
all the songs for an album, that album's songs for a playlist,
ticked or not (the tick is about the tags)."""
if self._art is not None:
chosen = self._art.selected()
return [(self.all_rows(), *chosen)] if chosen else []
out = []
for key, picker in self._pickers.items():
chosen = picker.selected()
if chosen:
out.append(([self._rows[r] for r in self._group_rows[key]],
*chosen))
return out
def _on_apply(self):
self.outcome = self.APPLY
if self._embed is not None and self._embed.isChecked() \
and self._art_image:
self.selected_image = self._art_image
self.selected_mime = self._art_mime
self.accept()
def _on_review_all(self):
+116 -25
View File
@@ -6,12 +6,22 @@ dropdown of alternate candidates (other albums/releases the recording appears
on). Passive like AlbumArtDialog: candidates arrive pre-parsed, nothing is
written until the user accepts, and the caller applies ``result_fields()``
through LibraryManager afterwards.
The proposal itself is ``IdentifyPanel``, a plain widget, so Import Shazams
can show it inside its own window while songs are still downloading.
With ``find_art`` the dialog also searches a cover for the album the grid
proposes (Round 119, ``art_picker``), re-searching when the candidate or
the artist/album boxes change; ``selected_image`` is set on accept.
"""
from PyQt6.QtCore import QTimer, pyqtSignal
from PyQt6.QtWidgets import (
QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QLabel,
QLineEdit, QPushButton, QSpinBox, QVBoxLayout,
QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QSpinBox, QVBoxLayout, QWidget,
)
from lintunes.gui.art_picker import ArtPicker
# (field, label, is_number, spinbox max)
_FIELDS = [
("name", "Name", False, 0),
@@ -25,16 +35,19 @@ _FIELDS = [
]
class IdentifyDialog(QDialog):
def __init__(self, track, candidates, remaining: int = 0, parent=None):
class IdentifyPanel(QWidget):
"""One track's proposals: the candidate drop-down and the field grid."""
# The candidate switched, or a box or tick was edited.
proposal_changed = pyqtSignal()
def __init__(self, track, candidates, parent=None):
super().__init__(parent)
self.setWindowTitle("Identify Track")
self._track = track
self._candidates = candidates
# True when the user pressed "Stop Identifying" on a queued batch.
self.cancel_all = False
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._header = QLabel()
self._header.setWordWrap(True)
layout.addWidget(self._header)
@@ -69,6 +82,13 @@ class IdentifyDialog(QDialog):
else:
editor = QLineEdit()
check.toggled.connect(editor.setEnabled)
check.toggled.connect(lambda _on: self.proposal_changed.emit())
if is_number:
editor.valueChanged.connect(
lambda _v: self.proposal_changed.emit())
else:
editor.textChanged.connect(
lambda _t: self.proposal_changed.emit())
self._checks[field] = check
self._current_labels[field] = current
self._editors[field] = editor
@@ -78,20 +98,6 @@ class IdentifyDialog(QDialog):
grid.addWidget(editor, row, 3)
layout.addLayout(grid)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
| QDialogButtonBox.StandardButton.Cancel)
buttons.button(QDialogButtonBox.StandardButton.Ok).setText(
"Apply Tags")
if remaining > 0:
noun = "track" if remaining == 1 else "tracks"
stop_btn = QPushButton(f"Stop Identifying ({remaining} {noun} left)")
buttons.addButton(stop_btn,
QDialogButtonBox.ButtonRole.ActionRole)
stop_btn.clicked.connect(self._stop_all)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
self._combo.currentIndexChanged.connect(self._fill_from_candidate)
self._fill_from_candidate(0)
@@ -134,12 +140,14 @@ class IdentifyDialog(QDialog):
check.setChecked(differs)
editor.setEnabled(differs)
def _stop_all(self):
self.cancel_all = True
self.reject()
# ---- result ----
def value(self, field):
"""What ``field`` will be after Apply: the box when its row is
ticked and filled, else the track's own value."""
proposed = self.result_fields().get(field)
return proposed if proposed else self._current_value(field)
def result_fields(self) -> dict:
"""Checked rows only, keyed by LinTunes field names — ready for
``LibraryManager.edit_track_fields``. Blank editors are dropped (a
@@ -153,3 +161,86 @@ class IdentifyDialog(QDialog):
if value:
fields[field] = value
return fields
class IdentifyDialog(QDialog):
"""``IdentifyPanel`` as its own window, with Apply / Cancel and, for a
queue, Stop Identifying."""
# How long typing in Artist/Album rests before the cover is searched.
ART_DELAY_MS = 700
def __init__(self, track, candidates, remaining: int = 0, parent=None,
find_art: bool = False, embed_art: bool = True):
super().__init__(parent)
self.setWindowTitle("Identify Track")
# True when the user pressed "Stop Identifying" on a queued batch.
self.cancel_all = False
self.selected_image: bytes | None = None
self.selected_mime = "image/jpeg"
layout = QVBoxLayout(self)
top = QHBoxLayout()
self.panel = IdentifyPanel(track, candidates, self)
top.addWidget(self.panel, 1)
self.art = None
if find_art:
self._embed_art = embed_art
self.art = ArtPicker("Embed this artwork", parent=self)
top.addSpacing(12)
top.addWidget(self.art)
self._art_timer = QTimer(self)
self._art_timer.setSingleShot(True)
self._art_timer.setInterval(self.ART_DELAY_MS)
self._art_timer.timeout.connect(self._search_art)
self.panel.proposal_changed.connect(self._art_timer.start)
self.panel._combo.currentIndexChanged.connect(
lambda _i: self._search_art())
self._search_art()
layout.addLayout(top)
# What the tests reach into.
self._header = self.panel._header
self._combo = self.panel._combo
self._checks = self.panel._checks
self._editors = self.panel._editors
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
| QDialogButtonBox.StandardButton.Cancel)
buttons.button(QDialogButtonBox.StandardButton.Ok).setText(
"Apply Tags")
if remaining > 0:
noun = "track" if remaining == 1 else "tracks"
stop_btn = QPushButton(f"Stop Identifying ({remaining} {noun} left)")
buttons.addButton(stop_btn,
QDialogButtonBox.ButtonRole.ActionRole)
stop_btn.clicked.connect(self._stop_all)
buttons.accepted.connect(self._on_accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def art_query(self) -> tuple[str, str] | None:
"""(artist, album) the proposal would leave the song with."""
artist = self.panel.value("album_artist") or self.panel.value("artist")
album = self.panel.value("album")
return (artist, album) if artist and album else None
def _search_art(self):
self._art_timer.stop()
query = self.art_query()
if query is None:
self.art.clear()
elif query != self.art.query:
self.art.search(*query, embed_by_default=self._embed_art)
def _on_accept(self):
chosen = self.art.selected() if self.art is not None else None
if chosen:
self.selected_image, self.selected_mime = chosen
self.accept()
def _stop_all(self):
self.cancel_all = True
self.reject()
def result_fields(self) -> dict:
return self.panel.result_fields()
+41 -54
View File
@@ -12,7 +12,8 @@ from PyQt6.QtGui import QPixmap, QImage, QKeySequence, QShortcut
from lintunes import tagging
from lintunes.gui.art_ops import embed_artwork
from lintunes.player import VOLUME_ADJUSTMENT_MAX
from lintunes.gui.file_filters import IMAGE_FILTER
from lintunes.gui.track_table import key_hint
log = logging.getLogger(__name__)
@@ -29,7 +30,7 @@ PASTE_RETRY_MS = 300
# compare covers; it just offers the paste.
MULTI_ART_READ_LIMIT = 100
HINT_IDLE = "Ctrl+V or Paste Artwork to add a cover"
HINT_IDLE = key_hint("Ctrl+V") + " or Paste Artwork to add a cover"
HINT_STAGED = "New artwork — saved when you click OK"
@@ -195,7 +196,7 @@ class ArtSquare(QLabel):
def _show_menu(self, pos):
menu = QMenu(self)
paste = menu.addAction("Paste Image\tCtrl+V")
paste = menu.addAction("Paste Image\t" + key_hint("Ctrl+V"))
choose = menu.addAction("Choose File…")
chosen = menu.exec(self.mapToGlobal(pos))
if chosen is paste:
@@ -206,7 +207,7 @@ class ArtSquare(QLabel):
def choose_file(self):
file_name, _filter = QFileDialog.getOpenFileName(
self, "Choose Artwork", "",
"Images (*.jpg *.jpeg *.png *.gif *.bmp *.webp)")
IMAGE_FILTER)
if file_name and not self._stage_file(Path(file_name)):
self.hint_changed.emit("That file isn't a readable image")
@@ -291,12 +292,14 @@ class InfoDialog(QDialog):
"""iTunes-style Get Info: edits library fields and the file's real tags.
Single track: custom start/stop times and the file's path, besides the
fields every mode has (incl. Volume, iTunes' per-song volume adjustment).
Multiple tracks: a combined
fields every mode has. Multiple tracks: a combined
editor where fields shared by every selection are editable and applied to
all, while fields that differ show "Mixed" and are only written if touched.
Boost Volume… acts at once rather than on OK: ``boost_requested``.
"""
boost_requested = pyqtSignal(list) # track ids
def __init__(self, manager, track_ids: list[int], parent=None):
super().__init__(parent)
self._manager = manager
@@ -375,26 +378,24 @@ class InfoDialog(QDialog):
form.addRow("", self._start_row)
form.addRow("", self._stop_row)
# Volume adjustment: iTunes' own (imported as-is), ±255 = ±100%.
volume_row = QHBoxLayout()
self._volume = QSlider(Qt.Orientation.Horizontal)
self._volume.setRange(-100, 100)
self._volume.setPageStep(10)
self._volume.setTickPosition(QSlider.TickPosition.TicksBelow)
self._volume.setTickInterval(50)
self._volume.setToolTip(
"Make this song quieter or louder than the rest. A boost can't "
"go past full volume, so it only helps while the main volume "
"isn't all the way up.")
self._volume_label = QLabel()
self._volume_label.setMinimumWidth(QLabel("Mixed").sizeHint().width() + 8)
self._volume.valueChanged.connect(self._on_volume_moved)
volume_row.addWidget(QLabel("−100%"))
volume_row.addWidget(self._volume, stretch=1)
volume_row.addWidget(QLabel("+100%"))
volume_row.addSpacing(6)
volume_row.addWidget(self._volume_label)
form.addRow("Volume:", volume_row)
# Boost Volume (Round 131) replaced iTunes' Volume Adjustment slider,
# which could never play past full volume. It raises an MP3's own
# gain (no re-encode), at once, as its own undo step; MainWindow
# does the work. Only shown when a selected song is an MP3 it can
# work on.
self._boost_row = QWidget()
volume_row = QHBoxLayout(self._boost_row)
volume_row.setContentsMargins(0, 0, 0, 0)
self._boost_button = QPushButton("Boost Volume…")
self._boost_button.setToolTip(
"Make a quiet MP3 about as loud as a typical song, without "
"re-encoding it or clipping. Edit ▸ Undo puts the original back.")
self._boost_button.setAutoDefault(False)
self._boost_button.clicked.connect(self._on_boost)
volume_row.addWidget(self._boost_button)
volume_row.addStretch(1)
form.addRow("Volume:", self._boost_row)
self._form = form
self._file_label = QLabel()
self._file_label.setStyleSheet("color: gray; font-size: 10px;")
@@ -416,6 +417,7 @@ class InfoDialog(QDialog):
self._load_multi()
else:
self._load_current()
self._show_boost()
def _make_time_row(self, title: str):
row = QWidget()
@@ -487,7 +489,6 @@ class InfoDialog(QDialog):
self._stop_time.setEnabled(track.stop_time > 0)
self._stop_time.set_ms(track.stop_time)
self._file_label.setText(track.location or "")
self._set_volume_slider(track.volume_adjustment or 0)
self._loading = False
def _load_multi(self):
@@ -520,9 +521,6 @@ class InfoDialog(QDialog):
self._comments.setPlainText("")
else:
self._comments.setPlainText(comments or "")
volume = self._common_value("volume_adjustment")
self._set_volume_slider(0 if volume is _MIXED else (volume or 0),
mixed=volume is _MIXED)
self._loading = False
def _collect_fields(self) -> dict:
@@ -537,7 +535,6 @@ class InfoDialog(QDialog):
if self._start_check.isChecked() else 0)
fields["stop_time"] = (self._stop_time.ms()
if self._stop_check.isChecked() else 0)
fields["volume_adjustment"] = self._volume_adjustment()
return fields
def _validate_times(self, track) -> str | None:
@@ -589,8 +586,6 @@ class InfoDialog(QDialog):
fields["compilation"] = self._compilation.isChecked()
if "comments" in self._touched:
fields["comments"] = self._comments.toPlainText().strip()
if "volume_adjustment" in self._touched:
fields["volume_adjustment"] = self._volume_adjustment()
if self._staged_art is not None:
tracks = [self._manager.library.tracks[tid]
for tid in self._track_ids]
@@ -614,29 +609,21 @@ class InfoDialog(QDialog):
# ---- volume ----
def _set_volume_slider(self, adjustment: int, mixed: bool = False):
self._volume.setValue(round(100 * adjustment / VOLUME_ADJUSTMENT_MAX))
self._show_volume(mixed)
def _boostable_ids(self) -> list[int]:
from lintunes import boost
ids = (list(self._track_ids) if self._multi
else [self._current_track().track_id])
tracks = self._manager.library.tracks
return [tid for tid in ids if tid in tracks and tracks[tid].location
and boost.supported(tracks[tid].location)]
def _volume_adjustment(self) -> int:
"""The slider in iTunes' unit. A value the slider shows unchanged
keeps its exact stored number (±1 % is 2–3 units)."""
position = self._volume.value()
if not self._multi:
stored = self._current_track().volume_adjustment or 0
if round(100 * stored / VOLUME_ADJUSTMENT_MAX) == position:
return stored
return round(position * VOLUME_ADJUSTMENT_MAX / 100)
def _show_boost(self):
self._form.setRowVisible(self._boost_row, bool(self._boostable_ids()))
def _on_volume_moved(self, _value):
if not self._loading:
self._mark_touched("volume_adjustment")
self._show_volume(mixed=False)
def _show_volume(self, mixed: bool):
value = self._volume.value()
self._volume_label.setText(
"Mixed" if mixed else "None" if value == 0 else f"{value:+d}%")
def _on_boost(self):
ids = self._boostable_ids()
if ids:
self.boost_requested.emit(ids)
def _on_ok(self):
saved = self._save_multi() if self._multi else self._save_current()
+71
View File
@@ -0,0 +1,71 @@
"""The big visualizer window's OpenGL canvas, for Kaleidostrobe.
Kaleidostrobe drew with fixed-function OpenGL; this replays those calls
(``KaleidostrobeRenderer.paint_gl``) through Qt's GL 2.x functions, so a
full-screen picture costs the GPU what it cost a 2002 Mac and the GUI
thread almost nothing. Painting the same picture with QPainter takes tens of
milliseconds a frame at 1920×1080 — the stutter this exists to remove.
If no usable OpenGL context turns up (no driver, a core-only context),
``failed`` is set and the window goes back to painting with QPainter.
"""
import logging
from PyQt6.QtOpenGLWidgets import QOpenGLWidget
from PyQt6.QtOpenGL import QOpenGLVersionFunctionsFactory, QOpenGLVersionProfile
from PyQt6.QtCore import pyqtSignal
from lintunes.gui import visualizer_kaleido as vk
log = logging.getLogger(__name__)
class KaleidoGLView(QOpenGLWidget):
"""Draws the visualizer's Kaleidostrobe renderer with OpenGL."""
unavailable = pyqtSignal()
def __init__(self, visualizer, parent=None):
super().__init__(parent)
self._visualizer = visualizer
self._gl = None
self._textures = None
self.failed = False
def initializeGL(self):
try:
profile = QOpenGLVersionProfile()
profile.setVersion(2, 1)
self._gl = QOpenGLVersionFunctionsFactory.get(profile, self.context())
except Exception: # pragma: no cover — depends on the driver
log.exception("kaleidostrobe: no OpenGL 2.1 functions")
self._gl = None
if self._gl is None:
self.failed = True
self.unavailable.emit()
return
gl = self._gl
gl.initializeOpenGLFunctions()
# InitGL(): smooth shading, depth test, blending, byte-aligned rows,
# and two 128×128 textures, GL_REPEAT + GL_LINEAR.
gl.glShadeModel(vk.GL_SMOOTH)
gl.glPixelStorei(vk.GL_UNPACK_ALIGNMENT, 1)
self._textures = list(gl.glGenTextures(2))
for name in self._textures:
gl.glBindTexture(vk.GL_TEXTURE_2D, name)
for pname, value in ((vk.GL_TEXTURE_WRAP_S, vk.GL_REPEAT),
(vk.GL_TEXTURE_WRAP_T, vk.GL_REPEAT),
(vk.GL_TEXTURE_MAG_FILTER, vk.GL_LINEAR),
(vk.GL_TEXTURE_MIN_FILTER, vk.GL_LINEAR)):
gl.glTexParameteri(vk.GL_TEXTURE_2D, pname, value)
def paintGL(self):
if self._gl is None:
return
renderer = self._visualizer.gl_renderer()
if renderer is None:
return
ratio = self.devicePixelRatioF()
renderer.paint_gl(self._gl, self._textures,
round(self.width() * ratio), round(self.height() * ratio),
self._visualizer.paint_color())
-222
View File
@@ -1,222 +0,0 @@
"""A small line drawing of the laser rig as the settings describe it — the
speaker with its mirror, the laser, the beam, and the screen at its distance
and angles — in the manner of an old electronics textbook: thin dark-gray
lines, a dimension line with arrowheads, small italic serif labels.
Schematic, not to scale: the distance moves the screen along the beam and
the angles turn it (through the same rotation the visualizer projects
with), but sizes are chosen to read, not measured.
"""
import math
import numpy as np
from PyQt6.QtWidgets import QWidget, QSizePolicy
from PyQt6.QtCore import Qt, QPointF, QRectF, QSize
from PyQt6.QtGui import QPainter, QPen, QColor, QFont, QPolygonF, QFontMetricsF
from lintunes.gui import visualizer_styles
# Oblique projection: the screen's width (across the beam) recedes up and to
# the right at this share of its true length — a cabinet drawing.
DEPTH = 0.5
DEPTH_ANGLE = math.radians(35)
INK = 0.72 # how far the line color is from the background to the text
class LaserDiagram(QWidget):
def __init__(self, config=None, parent=None):
super().__init__(parent)
self._config = config or visualizer_styles.settings(None)
self.setSizePolicy(QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding)
self.setMinimumSize(300, 150)
self.setToolTip("The rig your settings describe (not to scale)")
def sizeHint(self):
return QSize(420, 160)
def set_config(self, config: dict):
self._config = config
self.update()
# ---- drawing helpers ----
def _ink(self) -> QColor:
text = self.palette().windowText().color()
back = self.palette().window().color()
return QColor(*(round(b + (t - b) * INK) for t, b in (
(text.red(), back.red()), (text.green(), back.green()),
(text.blue(), back.blue()))))
def _label_font(self, caps=False) -> QFont:
font = QFont(self.font())
font.setFamilies(["Times New Roman", "Liberation Serif", "DejaVu Serif"])
font.setStyleHint(QFont.StyleHint.Serif)
font.setItalic(not caps)
font.setPointSizeF(max(7.0, font.pointSizeF() - (1.5 if caps else 0.5)))
if caps:
font.setLetterSpacing(QFont.SpacingType.PercentageSpacing, 112)
return font
@staticmethod
def _arrowhead(painter, tip: QPointF, toward: QPointF, size=6.0):
angle = math.atan2(tip.y() - toward.y(), tip.x() - toward.x())
wing = math.radians(18)
painter.drawPolygon(QPolygonF([
tip,
QPointF(tip.x() - size * math.cos(angle - wing),
tip.y() - size * math.sin(angle - wing)),
QPointF(tip.x() - size * math.cos(angle + wing),
tip.y() - size * math.sin(angle + wing))]))
def screen_corners(self, center: QPointF, half_height: float,
pitch=None, yaw=None, roll=None) -> list:
"""The screen's outline, projected: its own right/up axes turned by
the angles, then the across-the-beam axis drawn receding."""
c = self._config
rot = visualizer_styles._rotation(
c["visualizer_laser_pitch"] if pitch is None else pitch,
c["visualizer_laser_yaw"] if yaw is None else yaw,
c["visualizer_laser_roll"] if roll is None else roll)
half_width = half_height * 1.6
corners = []
for u, v in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
x, y, z = rot @ np.array([u * half_width, v * half_height, 0.0])
corners.append(QPointF(
center.x() + z + x * DEPTH * math.cos(DEPTH_ANGLE),
center.y() - y - x * DEPTH * math.sin(DEPTH_ANGLE)))
return corners
# ---- the drawing ----
def paintEvent(self, event):
c = self._config
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
ink = self._ink()
thin = QPen(ink, 1.0)
thin.setCapStyle(Qt.PenCapStyle.RoundCap)
thin.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
dashed = QPen(ink, 0.8, Qt.PenStyle.DashLine)
italic, caps = self._label_font(), self._label_font(caps=True)
w, h = self.width(), self.height()
axis_y = h * 0.42
mirror = QPointF(62, axis_y)
half = min(h * 0.24, 34) # the screen's half-height
angle_labels_w = QFontMetricsF(italic).horizontalAdvance("pitch −60°") + 14
near_x = mirror.x() + 105
far_x = max(near_x + 40, w - angle_labels_w - half * 1.0)
lo, hi = visualizer_styles.LIMITS["visualizer_laser_distance"]
distance = c["visualizer_laser_distance"]
screen = QPointF(near_x + (distance - lo) / (hi - lo) * (far_x - near_x),
axis_y)
# The laser, below and ahead of the speaker, aimed up at the mirror.
laser_at = QPointF(mirror.x() + 62, axis_y + 30)
incoming = math.atan2(laser_at.y() - mirror.y(), laser_at.x() - mirror.x())
painter.save()
painter.translate(laser_at)
painter.rotate(math.degrees(incoming))
painter.setPen(thin)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(QRectF(0, -5, 34, 10))
painter.drawLine(QPointF(34, -3), QPointF(38, -3)) # a cable stub
painter.restore()
painter.setFont(caps)
painter.drawText(QPointF(laser_at.x() + 2, laser_at.y() + 26), "LASER")
# The speaker: its axis halfway between the laser and the screen, so
# the mirror on its membrane sends the beam straight along the axis.
normal = incoming / 2
painter.save()
painter.translate(mirror)
painter.rotate(math.degrees(normal))
painter.setPen(thin)
cone = QPolygonF([QPointF(0, -26), QPointF(-22, -9), QPointF(-22, 9),
QPointF(0, 26)])
painter.drawPolyline(cone)
painter.drawLine(QPointF(0, -26), QPointF(0, 26)) # the membrane
painter.drawRect(QRectF(-34, -10, 12, 20)) # the magnet
painter.drawLine(QPointF(-3, -27), QPointF(-3, 27)) # the frame lip
mirror_pen = QPen(ink, 3.0)
painter.setPen(mirror_pen)
painter.drawLine(QPointF(1.5, -6), QPointF(1.5, 6)) # the mirror
painter.restore()
painter.setPen(thin)
painter.setFont(caps)
painter.drawText(QPointF(mirror.x() - 52, axis_y + 46), "SPEAKER")
# The beam: in from the laser, out to the screen.
painter.drawLine(laser_at, mirror)
painter.setBrush(ink)
self._arrowhead(painter, QPointF((laser_at.x() + mirror.x()) / 2,
(laser_at.y() + mirror.y()) / 2), laser_at)
corners = self.screen_corners(screen, half)
painter.drawLine(mirror, screen)
mid = QPointF((mirror.x() + screen.x()) / 2, axis_y)
self._arrowhead(painter, mid, mirror)
painter.setBrush(Qt.BrushStyle.NoBrush)
# Where a screen facing the beam squarely would be, if this one isn't.
turned = any(c[k] for k in ("visualizer_laser_pitch",
"visualizer_laser_yaw", "visualizer_laser_roll"))
if turned:
painter.setPen(dashed)
painter.drawPolygon(QPolygonF(self.screen_corners(screen, half, 0, 0, 0)))
painter.setPen(thin)
painter.drawPolygon(QPolygonF(corners))
painter.setFont(caps)
top = min(p.y() for p in corners)
painter.drawText(QPointF(screen.x() - 22, max(10.0, top - 6)), "SCREEN")
# The dot, where the beam lands, at its size.
radius = max(1.0, min(9.0, c["visualizer_laser_dot"] / 2))
painter.setBrush(ink)
painter.setPen(Qt.PenStyle.NoPen)
painter.drawEllipse(screen, radius, radius)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.setPen(thin)
right = max(p.x() for p in corners)
lead_from = QPointF(screen.x() + radius + 1, screen.y() + radius + 1)
lead_to = QPointF(right + 10, axis_y + half * 0.9)
painter.drawLine(lead_from, lead_to)
painter.setFont(italic)
dot = c["visualizer_laser_dot"]
dot_text = f"dot {dot:g} px" + ("" if c["visualizer_laser_head"] else
" (at rest)")
painter.drawText(QPointF(lead_to.x() + 3, lead_to.y() + 4), dot_text)
# The angles, beside the screen.
lines = [f"pitch {_deg(c['visualizer_laser_pitch'])}",
f"yaw {_deg(c['visualizer_laser_yaw'])}",
f"roll {_deg(c['visualizer_laser_roll'])}"]
metrics = QFontMetricsF(italic)
y = axis_y - half - 2
for line in lines:
painter.drawText(QPointF(right + 10, y), line)
y += metrics.height()
# The distance: a dimension line under it all, mirror to screen.
dim_y = h - 12
painter.setPen(thin)
for x in (mirror.x(), screen.x()):
painter.drawLine(QPointF(x, dim_y - 6), QPointF(x, dim_y + 4))
left, right_end = QPointF(mirror.x(), dim_y), QPointF(screen.x(), dim_y)
text = f"D = {distance:.1f} m"
text_w = metrics.horizontalAdvance(text) + 10
centre = (left.x() + right_end.x()) / 2
painter.drawLine(left, QPointF(centre - text_w / 2, dim_y))
painter.drawLine(QPointF(centre + text_w / 2, dim_y), right_end)
painter.setBrush(ink)
self._arrowhead(painter, left, right_end, 5)
self._arrowhead(painter, right_end, left, 5)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawText(QPointF(centre - text_w / 2 + 5, dim_y + 4), text)
painter.end()
def _deg(value) -> str:
value = round(value)
return f"{value:+d}°".replace("-", "−") if value else "0°"
+5
View File
@@ -179,6 +179,9 @@ class LibraryView(TableSettingsMixin, QWidget):
play_requested = pyqtSignal(list, int)
info_requested = pyqtSignal(list)
show_in_playlist_requested = pyqtSignal(int, str) # track_id, playlist pid
# The search box's text, case-folded, after the debounce ("" when cleared):
# MainWindow filters the sidebar's playlists by it too.
search_changed = pyqtSignal(str)
def __init__(self, manager, parent=None):
super().__init__(parent)
@@ -337,6 +340,7 @@ class LibraryView(TableSettingsMixin, QWidget):
self._search.blockSignals(False)
self._search_text = ""
self._search_tracks = self._all_tracks
self.search_changed.emit("")
for lst in (self._genre_list, self._artist_list, self._album_list):
lst.blockSignals(True)
lst.setCurrentRow(0) # "All"
@@ -370,6 +374,7 @@ class LibraryView(TableSettingsMixin, QWidget):
def _apply_search(self):
self._search_text = self._search.text().strip().casefold()
self._search_tracks = self._compute_search_tracks()
self.search_changed.emit(self._search_text)
# Rebuild the whole cascade so the genre/artist/album columns reflect
# only what the search matched.
self._populate_genres()
+167
View File
@@ -0,0 +1,167 @@
"""Folder tabs after classic Mac OS (the Platinum look of OS 8 and 9), in
the house style (shared-resources' design page, #tabs): slanted sides with
8 px top corners, the tabs behind are buttons (embossed in the button
gray, darker on hover, sunk while held), and the open tab in front is the
page's own color with only the top rim, open at the foot so it runs into
the page. All stand on one baseline, overlapping a little.
Each tab is a checkable QToolButton that paints itself, so the window's
QButtonGroup logic is unchanged; `TabStrip` holds them, overlapping a little
the way the real ones did, and draws the baseline they stand on. The tab
in front is raised above its neighbours, so its feet cover theirs."""
from __future__ import annotations
from PyQt6.QtCore import QPointF, QSize, Qt
from PyQt6.QtGui import QLinearGradient, QPainter, QPainterPath, QPalette, QPen
from PyQt6.QtWidgets import QToolButton, QWidget
from lintunes import theme
OVERLAP = 9 # px adjacent tabs overlap at their slanted feet
RADIUS = 8 # the top corners: the big buttons' radius
SLANT = 0.28 # each side's run, as a share of the height
OUTLINE = 135 # the buttons' outline, darker(135)
def _slant(h: int) -> float:
return h * SLANT
def baseline_color(palette):
return palette.color(QPalette.ColorRole.Window).darker(OUTLINE)
class MacTab(QToolButton):
def __init__(self, text: str, parent=None):
super().__init__(parent)
self.setText(text)
self.setCheckable(True)
self.toggled.connect(lambda on: on and self.raise_())
def sizeHint(self) -> QSize:
fm = self.fontMetrics()
h = fm.height() + 12
return QSize(int(fm.horizontalAdvance(self.text()) + 2 * _slant(h) + 18), h)
def minimumSizeHint(self) -> QSize:
return self.sizeHint()
def _outline(self) -> QPainterPath:
"""Up the left slope, round the top corners, down the right slope;
open along the foot."""
w, h, s = self.width(), self.height(), _slant(self.height())
top, foot = 0.5, float(h)
side = ((s - 0.5) ** 2 + (foot - top) ** 2) ** 0.5
r = min(RADIUS, side / 2)
# where the curve starts, back down each slope
dx, dy = (s - 0.5) * r / side, (foot - top) * r / side
p = QPainterPath()
p.moveTo(0.5, foot)
p.lineTo(s - dx, top + dy)
p.quadTo(s, top, s + r, top)
p.lineTo(w - s - r, top)
p.quadTo(w - s, top, w - s + dx, top + dy)
p.lineTo(w - 0.5, foot)
return p
def _fill(self, color, front: bool) -> QLinearGradient:
"""A button's emboss, or (front) only its top rim, then the page."""
g = QLinearGradient(QPointF(0, 0), QPointF(0, self.height()))
stops = theme.emboss_stops(color, pressed=self.isDown() and not front)
for pos, c in (stops[:3] if front else stops):
g.setColorAt(pos, c)
if front:
g.setColorAt(1, color)
return g
def paintEvent(self, _) -> None:
front = self.isChecked()
pal = self.palette()
if front:
color = pal.color(QPalette.ColorRole.Window)
else:
color = pal.color(QPalette.ColorRole.Button)
if self.isDown():
color = color.darker(theme.PRESSED_DARKER)
elif self.underMouse():
color = color.darker(theme.HOVER_DARKER)
w, h = self.width(), self.height()
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
shape = self._outline()
p.fillPath(shape, self._fill(color, front))
p.setPen(QPen(color.darker(OUTLINE), 1))
p.drawPath(shape)
if not front: # behind: the baseline runs across its foot
p.setPen(QPen(baseline_color(pal), 1))
p.drawLine(QPointF(0, h - 0.5), QPointF(w, h - 0.5))
p.setPen(pal.color(QPalette.ColorRole.WindowText if front
else QPalette.ColorRole.ButtonText))
f = self.font()
f.setBold(front)
p.setFont(f)
p.drawText(self.rect().adjusted(0, 2, 0, 0), Qt.AlignmentFlag.AlignCenter, self.text())
p.end()
def enterEvent(self, e) -> None:
self.update()
super().enterEvent(e)
def leaveEvent(self, e) -> None:
self.update()
super().leaveEvent(e)
class TabStrip(QWidget):
"""A row of MacTabs (None in `add` = a gap) on a baseline across the
width. Placed by hand: a layout can't overlap its widgets."""
def __init__(self, parent=None):
super().__init__(parent)
self._items: list[MacTab | int] = [] # a tab, or a gap's width
def add(self, tab: MacTab | None, gap: int = 24) -> None:
if tab is None:
self._items.append(gap)
else:
tab.setParent(self)
self._items.append(tab)
def finish(self) -> None:
for t in self._tabs():
if t.isChecked():
t.raise_()
self._place()
def _tabs(self) -> list[MacTab]:
return [t for t in self._items if isinstance(t, MacTab)]
def sizeHint(self) -> QSize:
tabs = self._tabs()
h = max((t.sizeHint().height() for t in tabs), default=24)
w = 4 + sum(t.sizeHint().width() - OVERLAP if isinstance(t, MacTab) else t
for t in self._items) + OVERLAP
return QSize(w, h)
def minimumSizeHint(self) -> QSize:
return self.sizeHint()
def _place(self) -> None:
x, h = 4, self.height()
for item in self._items:
if isinstance(item, MacTab):
hint = item.sizeHint()
item.setGeometry(x, h - hint.height(), hint.width(), hint.height())
x += hint.width() - OVERLAP
else:
x += item
def resizeEvent(self, e) -> None:
self._place()
super().resizeEvent(e)
def paintEvent(self, _) -> None:
p = QPainter(self)
p.setPen(QPen(baseline_color(self.palette()), 1))
p.drawLine(0, self.height() - 1, self.width(), self.height() - 1)
p.end()
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More