99 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
What this is
LinTunes is an iTunes-replacement music library manager and player for Linux,
built with PyQt6 / Qt Multimedia. It imports an iTunes 12 library, stores the
library as plain JSON (syncable via Syncthing), and reproduces the iTunes UI
(left sidebar + right playlist view, column browser, customizable per-playlist
columns). spec.md is the original design brief. Tasks live on the kanban board at
~/Documents/projtracker/projects/lintunes/ (use the tasks skill); the old
TASKS.md/tasks-done.md are archived there — don't recreate them.
Commands
pip install -e . # install deps (PyQt6, mutagen, numpy, requests)
python3 -m lintunes.main # run the app straight from the checkout
python3 -m pytest # run the whole test suite
python3 -m pytest tests/test_round9.py # one test file
python3 -m pytest tests/test_round9.py::test_name # one test
The app needs a --data-dir; config persists to ~/.config/lintunes/config.json.
One-time iTunes import:
lintunes --import-xml "iTunes Library.xml" \
--music-root "/path/to/iTunes Media" \
--data-dir /path/to/library-data --save-config
Runtime needs FFmpeg codecs for Qt Multimedia (qt6-qtmultimedia w/ ffmpeg).
Tests run headless via the qapp fixture in tests/conftest.py
(QT_QPA_PLATFORM=offscreen).
Architecture
Data flows in one direction through three layers: storage (JSON on disk) →
model (Library/Track/Playlist dataclasses) → LibraryManager (mutations +
persistence) → GUI (Qt widgets that read the manager and connect to its signals).
-
lintunes/main.py— CLI entry.--import-xmlruns a headless import and exits; otherwiserun_gui()resolves Syncthing conflicts, loads the library, buildsPreferences/LibraryManager/LastFm/MainWindow, wires MPRIS, and installs the window as a global event filter (for media keys). -
lintunes/models/— pure dataclasses (track.py,playlist.py,library.py) withto_dict/from_dictround-tripping.PlaylistTypeisREGULAR | FOLDER | SMART | SYSTEM. Per-playlistPlaylistSettingsholds visible columns / sort column / widths. Playlists are identified by an 8-char hexpersistent_id(folder containment viaparent_persistent_id). -
lintunes/storage/json_storage.py— the library is multiple files in the data dir:library.json(all tracks),library_metadata.json, oneplaylists/<persistent_id>.jsonper playlist, and oneplays/<machine-id>.jsonper machine. Writes are atomic (*.json.tmp→ rename).storage/conflict_resolver.pymerges Syncthing*.sync-conflict-*files on startup: play counts take the max, edited fields take the newest, playlist membership takes the union except where a removal was recorded (Round 44, seetombstones.py). Since Round 39 that union is anchor-based (merge_track_order): a track only one copy has is re-inserted after the nearest track both share, not appended at the tail, so a middle insert stays in the middle. Whose order wins is decided byPlaylist.date_modified, not by the file's mtime, which moves for cosmetic reasons. Since Round 43 a stamped copy also beats an unstamped one (a stamp exists only once LinTunes recorded an edit, so that is real evidence); mtime is the fallback only when neither side has ever been edited. Two rules follow: a merge that changes nothing writes nothing (an unconditional write reset the kept file's mtime and biased that fallback a little more every round), and a merge whose result is a union neither copy had stampsdate_modified— that content is newer than both, and saying so is what stops two machines trading the same tracks back and forth.library_manager._reconcile_playlistis the same decision on the live-reload path and must read the stamps too; it is reached only for playlists in_dirty_playlist_content(real content edits), never for one that is merely cosmetically dirty from a column drag. Since Round 42 everyConflictSummarycarries alevel(WARNING/CHANGE/INFO): a merge that only reconciled column widths, or a smart playlist whose rules are byte-identical on both sides, isINFOand must never read as an edit the user made. The dialog (gui/conflict_dialog.py) shows one level and above and opens at the highest level in the batch, so a routine merge never steals focus but a blank window is impossible either. Round 43 made the summaries say something actionable: which copy won and when it was edited, who wrote the copy Syncthing set aside (the 7-char device token in the conflict filename, named viasync_identity.py), and every re-inserted track byArtist — Titleand position — six in the window, all of them inwhat-changed.txtat the top of the backup snapshot. Never label a copy "this machine" from which file holds the plain name: that is Syncthing's choice, and it sets the local copy aside as readily as a remote one. -
lintunes/storage/play_journal.py— why play counts can't conflict. Since Round 38library.jsonholds only a base count and each machine ownsplays/<machine-id>.jsonwith its own per-track totals; effective count = base + the sum of every journal. Only the owner ever writes its journal, so two machines never touch the same file — and finishing a track no longer rewrites 15 MB, which is what handed Syncthing a conflict once per song. Totals, not an append log, so there is no compaction step to double-count in.PlayJournal.load()must be handed a library whose tracks still carry base counts (the fresh load at startup, thediskcopy insidereload_from_disk) — folding an already-folded library promotes the effective count to base. Mirror-image rule injson_storage.save_tracks(): it writesjournal.base_fields(tid), never theTrack's effective count. Those two places are the whole hazard;tests/test_round38.pypins both. -
lintunes/storage/listen_history.py— the yearly Wrapped's raw data (Round 74). The journals keep totals, which can't say "top songs of 2026", minutes listened, month or time of day; this keeps one line per listen in<data_dir>/history/<machine id>/<YYYY-MM>.jsonl— the journals' owner-only-writer rule, append-only, a finished month never changes.tis local time with its offset (time-of-day is the listener's clock);msis time actually heard —Player._account_heardadds position steps of 0–1.5 s, so seeks and pauses don't count;endis 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 prefwrapped.track_historyis on:Player.listen_ended→MainWindow(addssrcdesktop/cast/airplay andctx, which it latches attrack_changedbecause_now_playing_contextmoves 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": truein itslibrary.json;andtunes/plays.bring_back_historycopies a month home when the device's copy is longer (two desktops can both do that, hence the union merge inconflict_resolver._merge_listen_history).cassette/wrapped.pyputs this year's trimmed log (trim_for_sharing: no id/ctx/src/shuf) in every friend'sout/aswrapped-<year>.jsonwhenwrapped.share_with_friendsis also on — checked hourly byCassetteUi, written daily in Nov–Dec and monthly otherwise, never rewritten when the plays didn't change. No Wrapped page yet: that's built after Spotify's 2026 one drops, plus a Last.fm backfill for Jan–Sep (scrobbling is on; the R1 never scrobbled). -
lintunes/library_manager.py—LibraryManager(QObject)owns theLibrary, is the single funnel for all mutations, and persists them debounced (3 s) with per-area dirty tracking (a play-count bump rewrites onlylibrary.json; a playlist edit rewrites only that playlist file). User edits go throughundo_stack(Ctrl+Z); the internal_apply_*/_set_*helpers do the real mutation + dirty-mark + signal and are reused by undo/redo without recursing. Widgets react to its signals (playlists_changed,playlist_content_changed(pid),track_updated(id),track_fields_edited). -
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-bitglobal_gainin the MP3 side info, mp3gain's method — 1.5 dB a unit, decoded audio exactly × 2^(units/4), same length, nothing else changes. Granules withpart2_3_length0 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, thenreplace_track_files(…, in_place=True)trashes the original and puts the copy at the same path — one undo step. Boosting the playing songPlayer.reopen_current()s it where it was (no new listen).Track.volume_adjustmentis 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 theffmpegCLI'sebur128(~0.4 s a song), cached by path + size + mtime in$XDG_CACHE_HOME/lintunes/loudness.json(machine-local, never the synced dir).PlayerturnsTARGET_LUFS − measuredinto 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 nextLOOKAHEADahead; 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 swappablePlaybackSink. Player owns the queue, shuffle walk, per-track start/stop times and the play-count/scrobble bookkeeping; a sink owns only "make this file come out of something, and report where it's up to".LocalSink(theQMediaPlayer/QAudioOutputpipeline, with theQAudioBufferOutputPCM tee that feeds the visualizer) stays inplayer.py— the Player tests stub Qt Multimedia withpatch.multiple(player_module, QMediaPlayer=..., …), so those names must resolve in this module.cast/sink.py::CastSinkis the other implementation.set_sink()carries the current track, position and playing-state across a swap and deliberately does not re-emittrack_changed(that would double-scrobble the same song). Repeat (Round 88, the transport's button, off → all → one) lives inPlayer: repeat-all wraps_step_indexboth 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:") is tracked inMainWindow, not the player. -
lintunes/gui/—main_window.pyassembles a topTransportBarover a horizontalQSplitter(SidebarPanel| stackedLibraryView/PlaylistView). The bar's second row (transport.HeaderRow, placed by hand) holds three things owned elsewhere: the sidebar's Library button (SidebarPanel.header, kept edge to edge with the playlist list —list_area, scrollbar included — viatrack_split), the shown view'sheader(search box, playlist name — mounted on the content stack'scurrentChanged, returned to its view when it goes), and the seek row, exactly under the now-playing panel. Everything in it stands on one floor (HeaderRow.BOTTOMabove the lists): boxes by their bottom edge, text by its baseline. The row of boxes above floats — equal space before, between and after the controls, with the panel a fixed share of the width. Since the Library button left the sidebar,MainWindowmust 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'toolbaris two rows of{id, size: auto|fill|exact, width}, andTransportBar.place_rowslays them out by hand with the puretoolbar.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 aCustomizeOverlayover each row (it takes every click; edges are resize handles → exact width; right-click → Automatic / Fill space / Exact size) and aCustomizePanelunder them (items not shown, both spacers always; Restore Defaults). Moves areQDrags withtoolbar.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 (themeitem) 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) — andidentify(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_DARKER125, sunk) — between Material 3's 8 %→10 % and GNOME's 15 %→30 %; a checked toggle usesCHECKED_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 (tileproperty: square where they meet, one shared line). The seek slider has thetallproperty, whichClickToJumpScrollStylereads 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 afaceproperty, since a QFrame has no:pressed. Its words aretransport.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 inClickToJumpScrollStyle: thetallproperty 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 asidebar.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 — sorebuildreads the pre-filter expansion while a filter is up. The menu bar can hide until Alt (Round 116,gui/menu_bar.py, Preferences › Appearance, prefmenu_bar:always|alt): a tap of Alt shows it until a menu closes, Esc, a click elsewhere or another tap; Alt+ opens that menu straight away. Qt disables a hidden menu bar's shortcuts with it, soregister_shortcutsadds every menu action to the window too — an action added to a menu later must be as well.track_table.pyis the shared track grid (drag/drop, copy/paste, drop indicator).playlist_ops.py::add_tracks_with_dup_checkis the single funnel for every add-to-playlist path.theme.pyapplies the palette (highlight colors, UI scales) from prefs. -
lintunes/gui/visualizer.py+visualizer_styles.py— the transport-bar visualizer (Round 78). The widget owns PCM intake, the timer, on/dim/off and the color; a renderer (visualizer_stylepref:bars,radial,laser) owns the animation state and paints it into any rect, so the double-clickVisualizerWindowpaints the same renderer bigger rather than a copy. Since the first press of a double-click already cycled the brightness,mouseDoubleClickEventputs it back. Every tunable is avisualizer_*pref, read throughvisualizer_styles.settings()(clamped toLIMITS, which the Preferences sliders share) and applied live throughconfigure(). Radial is the EQ as polar dots (angle = log bands, radius = level in rings; both counts are settings). A moving dot leaves ghosts in its own color fading into the background, kept as a birth time per (spoke, ring) so a spoke never holds more than its ring count. It reads a 4096-point FFT and interpolates bands narrower than a bin: with 2048 points, every degree under ~1.3 kHz shared a bin with its neighbours and 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). Oscilloscope (laserin 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 inCHUNKs. 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. 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 atSCREEN_DISTANCE; a stillgui/scope_drawing.pysits 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'sbits(), since 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, withone_polestages done exactly via the cumsum trick, 36 dB/octave. That is steeper than a real speaker on purpose: the membrane answers bass ~80 dB more than treble, so a gentler slope lets bass drown a treble-only setting. For the same reason the auto-gain floor is measured per range (reference hiss through that speaker and membrane), and the membrane is simulated at full rate only once the bass is cut. Treble alone draws a shimmer along one line: far above every resonance, all modes move in phase. Every style's fade is one seconds slider, 0 = off. Sync (Round 78): decoding runs ahead of the speakers, by a buffer or two normally but by up to ~0.8 s when the GUI thread stalls and buffers arrive in a burst. So the widget keeps 1.5 s of timestamped history (QAudioBuffer.startTime()) and each frame draws the stretch ending atPlayer.position_ms(), carried forward by the clock between 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 inconfig.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 sharedvisualizer_sync_delay_ms. The dialog emitsprefs.changedafter writing it so the widget re-reads. The laser takes every heard sample exactly once (_drawnindex), never the newest-decoded ones. Presets (gui/visualizer_presets.py): per style,STYLE_KEYSunder a name, invisualizer_presets(synced; never the sync delay).Defaultis 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. The page's sliders (Round 111) aretransport.ClickJumpSliders with thetallproperty: 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_SHAREof the gap) — never pixels, since the gap moves with the drawing's size. A setting added later must joinSTYLE_KEYSand register a setter, or presets silently skip it (test_every_style_key_has_a_controlpins that). 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 aredark_<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 withtheme.surface(prefs, key), glyphs withtheme.icon_gray()and button text withtheme.text_color()— a hardcoded black/#4A4A4A vanishes in dark. The highlight is shared. The highlight swatches can be repainted with a color picker:highlight_paletteoverrides a slot, andtheme.highlight_colorreads throughtheme.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.pyis the Qt-free port, routine by routine, withf32/math.fmawherever the PPC rounded to single or fused a multiply-add (a palette index onx.5depends on it),ParkMiller= Darwin 6'srand()(RAND_MAX 2³¹−1).tables.npzholds what the original computes deterministically, extracted by running its code: 22 colour maps and 23 base wave images (before their randomtransform(), which is ported, as are the 16 livecalcDeltawarps — 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, soitunes_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_composeturns 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_glin agui/kaleido_gl.pyQOpenGLWidget, 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.npzwas recorded from the emulated original andtest_round84holds 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; inSTYLE_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 andadvanceis 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_BPMand a full spectrum) → one ofMOVES: ten arm+leg moves in three tiers; the tier isnowfullness (1.5 s) againstTIER_EDGES, ±1 whennowisLIFTover or underlately(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 atSIT_AFTER_S(10), sleeps atSLEEP_AFTER_S(30);clear()does nothing, so skipping songs never sits it down. Two renderer flags the widget reads:idleskeeps the 60 Hz timer running with nothing playing (fed silence, never the old song's tail), andblack_modeaddsMODE_BLACKto 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'sdj_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 isMainWindow._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.pydecodes 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.pyis 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.pyfeeds 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 onlystop()— 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 inpw_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.jsonmemoizes path + size + mtime → key; old path-keyed folders are renamed on sight. The cache is held to config.json'sdj_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") callsStemSplitter.cancel— out of the queue, or Demucs killed bysplit'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 realspleeterpackage 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.pyruns 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 oneStemSplitterper engine (HQ/FAST; Instant never queues behind Demucs);DeckView.engineis what the deck wants,usingthe tier playing.dj_stem_default(synced) picks the engine a deck starts with,stems.default_enginefalls 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_splitpinsinstant.availableoff 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_speedtakes 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 isdj_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.SnapSlideris 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_ratiofolds any number of octaves). |◀ per deck. The air horn is a real recording (sounds/airhorn.mp3, seesounds/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 lapsHorn.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 Macfile:///Volumes/...paths to the local--music-rootwith case/Unicode-normalization fuzzy matching (macOS is case-insensitive + NFD vs ext4). Imports user playlists, folders and smart playlists (criteria parsed bysmart.parse_itunes_smart; criteria it can't model are kept as a static snapshot —report.smart_unsupported). System playlists are skipped (report.skipped_system). Album art is read live from embedded ID3 tags (tagging.py), never stored in the library JSON. -
lintunes/preferences.py— app settings in<data_dir>/preferences.json(rides the same Syncthing share).Preferences.set(key, value)saves and emitschanged;MainWindow._on_prefs_changedre-applies theme/metrics live. Because it is synced, anything machine-specific belongs inconfig.py'sconfig.jsoninstead (seemusic_folder.py).now_playing_fonthas three states —Noneautomatic (best available fromtheme.NOW_PLAYING_FALLBACKS),""the app font, or an explicit family. Startup never prompts for it; the row in Preferences is the only place it's chosen. -
lintunes/music_folder.py— where the organized tree lives on this machine. The library stores it three ways (models/library.py):music_folderabsolute (what pre-0.10 code reads — kept forever as the shared floor between versions),music_folder_relrelative to the data dir (the portable one, same trick asTrack.location), andmusic_folder_set_at, a stamp so a merge prefers the newest setting rather than the newest file.resolve()tries rel → legacy → the per-machine override inconfig.json(bothmusic_folder_overrideand the oldermusic_rootthat--music-root … --save-configwrites — an imported library already knows where its music is on this machine, so don't ask), and every candidate must exist — the override is consulted last so a machine that once needed one isn't pinned to it forever. Two rules that bite:LibraryManager.set_music_foldermust callmark_library_settings_dirty()(without itreload_from_diskreverts the change on the next sync tick), andorganize_root()can returnNone, which every caller must handle rather than inventing a relative path —MainWindow._music_import_dirused to fall back toPath("Music"), which resolved against a working directory GNOME's dash doesn't set predictably. -
lintunes/tombstones.py— why a deletion sticks. Two copies with no common ancestor cannot tell "A added this" from "B removed it", which is why every merge was a union — and why a song removed on one machine came back from the other forever. So removals are recorded:Playlist.track_events({track id: [when, "add"|"remove"]}) andLibrary.deleted_tracks({track id: when}, inlibrary_metadata.json). A merge takes the newest event per track across both copies and applies it, so a removal beats a copy that merely still had the song and a later re-add beats the removal; a track with no event still merges as a union. Events are recorded in the same single funnels as everything else —_set_track_idsfor playlists,_remove_tracksfor the library — and pruned afterRETENTION_DAYS(30) at the save boundary, so a machine offline longer than that can resurrect something. Three rules: track ids are never reused (_highest_track_idcounts deletions, or a new track would be dropped on sight by the dead id's own tombstone),library_metadata.jsonis merged beforelibrary.json(it carries the record the library merge is filtered against —resolve_conflictssorts for it), and a merge applying a deletion never touches a music file; it only drops the library entry, and reports at WARNING. -
lintunes/sync_identity.py— turns a conflict filename's 7-char device token into a device name, by reading Syncthing'sconfig.xmland deriving our own device ID fromcert.pem(base32 of the SHA-256 of the DER cert). Stdlib only, cached, and every failure path returnsNone— a machine with no Syncthing must still merge, just without naming anyone. -
lintunes/art_search.py— Download Album Art. Queries both the iTunes Search API and Deezer's public album search (neither needs a key) and merges them throughrank_candidates: album match beats artist match, so a right-artist, wrong-album hit never wins. Two sources because neither catalog is complete: iTunes has no copy at all of Digable Planets' Reachin', which Deezer finds on the first query (Round 60). One source failing is not an error while the other answers. Embedding, whether from there or from Get Info, goes throughgui/art_ops.embed_artwork: write,mpris.invalidate_artwork, size refresh. Get Info'sArtSquarenever stages bytes that don't decode (clipboard_imagechecks every candidate withQImage.loadFromData), because a clipboard can advertiseimage/pngand 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, prefimport_compress+import_compress_kbps∈ 320/256/192/160/128). With it on and a lossless file (FLAC/WAV/AIFF by suffix,.m4aonly when its codec is ALAC) in an import,MainWindow.import_fileshands the whole batch toCompressImportand returns[]:CompressWorkerwalks it in order on a daemon thread (lossy files pass straight through, so a playlist drop keeps its order), theffmpegCLI converts into a private temp dir, tags and art are copied with mutagen (copy_tags, not ffmpeg's mapping), andfile_importer.import_convertedmoves 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 useadd_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_kbpsread byDeliveryCoordinatoreach pass) converts a lossless library arrival insidedelivery.run_plansbefore 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 andLibraryManager.replace_track_filesswaps 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'sfpcalcCLI (detected withshutil.which, theffmpeg_available()pattern — a runtime tool, never a pip dep) fingerprints the file, and AcoustID's web API says what it is. Shaped likeart_search.py: pure parse/rank helpers first (tested offline against canned JSON), then subprocess/network, thenTrackIdentifier(QObject)on a daemon thread emitting a dict carrying eithercandidatesorerror. The year rule is the point of the feature: every candidate carries the recording's original year — the earliest release across all its release groups — even the candidate proposing a later compilation as the album, because a 60s song must not sort by the year its CD reissue came out._releasegroup_sort_keyseparately ranks a plain studio Album above EP/Single above anything with a Compilation/Live secondary type, so the default proposal is the real album. An AcoustID result's score belongs to the audio, not to any one recording: every recording linked to it carries that score, mis-tags included, and a song whose title another artist also used collects them (Round 52: trav's Dionne Farris "I Know" is linked to Jay-Z's, Marisela's, David Essex's and New Atlantic's). What tells a real link from a stray issources, the submission count — 475 against 6 and three 1s — so the lookup asks for it and_link_tiersinks anything under a tenth of the strongest link in that result. Hence the key order who, then which take, then which release: stray tier, agreement with the artist the file's own tags name (artist_hint_for), duration bucket, hint overlap, release rank. Artist before duration is the point — Jay-Z's take was 1.5 s closer to the file than Dionne's own, and that used to decide it.gui/identify_dialog.pyis passive (theAlbumArtDialogcontract — nothing written until accepted); the caller appliesresult_fields()throughLibraryManager.edit_track_fields, which is what buys tag writes, undo and artist/album file relocation for free. A row is pre-checked only where the proposal differs from the current value, so an unchecked field can never quietly blank a tag. The API key is the user's own, inpreferences.acoustid(the Last.fm precedent — preferences.json syncs, so it never belongs in git). Audio under ~3 s has no fingerprint at all ("Empty fingerprint"), which is a reported failure, not a crash. -
lintunes/bpm_detect.py— right-click → Calculate BPM (Round 73). Spectral-flux onset envelope → autocorrelation → every tempo 60–200 scored over four beat multiples, times a log-Gaussian prior at 120 BPM (the half/double-tempo tiebreak), thenfold_bpminto 70–180. Plain numpy plus theffmpegCLI (decodes the first 120 s to mono 11 kHz) — no librosa, which would drag numba/scipy/scikit-learn in for one function.BpmWorkeris ExportWorker's shape on the shared status-bar widgets (_busy_worker), reports each result as it lands so a cancel keeps them, and the batch is applied byLibraryManager.set_tracks_bpmas one undoable command, overwriting existing BPMs (trav's call). The transport's tap button stays for the songs it gets wrong. -
lintunes/filename_tags.py— the offline half of Identify Track, and the answer to its biggest limitation: AcoustID only knows music somebody submitted, so an underground/SoundCloud rip fingerprints perfectly and matches nothing (verified: "B. Clem — Zuuso" returns zero results from AcoustID, zero from a MusicBrainz text search, zero from iTunes). Its filename, though, says exactly what it is. Pure string work, no network, no Qt: strips yt-dlp's trailing id ([1025657891],-WC7gK2kgyTQ— an 11-char token is only treated as a YouTube id if it carries a digit, an underscore, or repeatedly flipping case, or "Underground" would be eaten), drops(Official Video)-style noise, splitsArtist - Titleon a spaced hyphen only (so "Jay-Z" and "350-440-DialTone" survive), collapses a doubled uploader, reads a leading1-04, restores_s→'s, and falls back to the iTunes tree (<root>/Artist/Album/NN Title.ext), ignoring placeholder dirs like "Unknown Artist".fingerprint.candidate_from_filenamewraps it as a candidate withsource="filename", appended to every lookup and standing alone when there are no matches — the dialog then says where the guess came from instead of quoting a fabricated confidence. The same filename also feedshint_for(track), which ranks real lookup results: token overlap (words worth double, bare numbers single — "alhambra" identifies a release, "1961" appears in every compilation spanning it), a coarse duration bucket off the recording lengths AcoustID returns (which is what separates a 150 s studio take from a 155 s live one), and a year named in the filename that predates anything the database knows. That last one is not a nicety: MusicBrainz's ownfirst-release-datefor "Ahmad Jamal's Alhambra" is 2002, because its three original 1961 pressings are in the database undated — so a second MusicBrainz call would return the same wrong year, and the file's own name is the only place 1961 exists. -
lintunes/url_import.py—File → Import from URL…(Round 49): trav'ssongshell helper (yt-dlp --extract-audio --audio-format mp3 "$@") run from inside the app. Those flags are passed verbatim; everything else on the command line is plumbing:-P <tempdir>,--print before_dl:LTSTART …,--print after_move:LTFILE %(filepath)sand anLTPROGprogress template, so output is read from markers rather than scraped. yt-dlp is a runtime CLI tool (shutil.which, the fpcalc pattern), never a pip dep, and needs ffmpeg for the mp3. No-o: yt-dlp's defaultTitle [id].mp3is whatfilename_tagsparses.UrlImportWorker(daemon thread,ExportWorker's shape, shares the status-bar progress widgets and so_busy_worker()) downloads into a privatemkdtemp, emitsdownloaded(path)per song, and the GUI imports each one as it lands, through the normalimport_files(a copy into the organized tree) and straight into the Identify queue, so song 1's dialog can be up while song 5 downloads. The GUI deletes the temp dir only onfinished/failed, which are queued after everydownloaded.resolve_targetis the rule for "and add to current playlist?": above the selected song in the shown playlist, else the end of the playing playlist, else the end of the shown one, else the checkbox is grayed. Smart/folder/system playlists are never targets. A batch keeps the link's order (position + songs already inserted). With no AcoustID key,TrackIdentifierproposes from the filename alone and never touches fpcalc or the network. Only a URL import reaches that path, since the menu route still insists on setup first. YouTube's "Sign in to confirm you're not a bot" is about the network (songhits it too), and yt-dlp's cure is the browser's cookies: a run that downloads nothing for that reason is retried once with--cookies-from-browser(default_cookies_browser, Firefox first), and a browser that worked is saved asytdlp_cookies_browserinconfig.json, not preferences — which browser holds a YouTube login is this machine's business (Round 59). A link is listed before it downloads (Round 75): trav pasted a song from a YouTube Mix (watch?v=…&list=RD…), yt-dlp took the whole list, and songs kept arriving with no word why.link_kind(URL alone) lets only a plain song link skip the listing; everything else goes throughPlaylistProbe(--flat-playlist, oneLTENTRYline per song, streamed into the dialog's checklist). A song-in-a-list ticks only its song (plus a Just This Song button that doesn't wait), a playlist link ticks all. Measured on the real Mix: ~36 s to the first row, 2,967 rows, the linked song 8 times (a Mix loops), so rows are de-duplicated by id. Chosen songs download by their own page URLs, never the list link or--playlist-items, since a Mix reshuffles on every listing. Several songs getgui/url_import_progress.py, a non-modal per-song list (Hide keeps downloading; clicking the status-bar line reopens it).LTSTARTcarries the id, andERROR: [site] <id>: …lines becomeitem_failed. A named list can become a playlist (Round 109): the probe also printsLTLIST %(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.MainWindowmakes the playlist when the first song lands (nothing downloaded → no empty playlist) and adds each song withundoable=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'sspotify-youtubescript) can't be downloaded, but Spotify's public embed page (open.spotify.com/embed/<kind>/<id>, a__NEXT_DATA__JSON block, no key) names every song with its length.SpotifyProbefeeds those to the same checklist;SpotifyImportWorker(aUrlImportWorkerwith the same signals, rows keyed by Spotify id) runs aytsearch5:listing per song, takes the result closest to Spotify's length (rank_candidates: within 10 s, then no "live"/"cover" the Spotify title doesn't have — the shazam-import lesson), falls back to the next result if a download fails, and writes Spotify's title/artist/album/ track number into the mp3 before emittingdownloaded, so the import files it under the right artist and Identify ranks by that artist. If the embed page changes shape,parse_embedraisesSpotifyError. An Apple Music link (Round 130,apple_music_link.py) is the same path with another reader:AppleMusicProbereturnsSpotifyTracks (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 itsmusic.apple.compage'sserialized-server-dataJSON 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 byMainWindow._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_infoapplies rename + cover): name, kind, songs/length,Playlist.date_created(set by every create_* since Round 130; older/iTunes playlists show —),date_modified, last played andsource_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.pykeepsplaylist_plays/<machine id>.jsonper machine (owner-only writer, ≤ one write a minute per playlist), stamped when a song starts in aplaylist:<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, andMainWindow._place_url_rowsfills 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.IdentifyCollectorlooks each up quietly as it lands, and only afterfinished/failedand the last lookup does one review window open, with all the songs as rows in the app's columns.find_common_albummakes it "one album" when every song naming an album can be on the same one (its own tags vote too, which is what carries a Spotify album through AcoustID's compilations). Then the album-wide fields are unified to the most common value, shown once above the table, and the cover comes from the sameAlbumArtFetchersearch. Ticked rows go throughLibraryManager.edit_many_track_fieldsas one undo step. Unticked rows get the ordinaryIdentifyDialogafterwards, from the lookups already made. No popup may land on top of another app:MainWindow._when_app_activeshows it at once only while LinTunes is the active application, and otherwise asks for attention (QApplication.alert) and waits forapplicationStateChanged. A window test that downloads several songs must stub_show_batch_reviewand cancel_url_batchon 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-importskill inside the app. Shazam'slibrary.dbis only reachable through root adbd (ShazamReader:adb root, pull the db and its -wal — the newest Shazams live there — thenadb unrootif it was the one that rooted). Which Shazams are dealt with is the synced prefshazam_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_songrejects 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).ShazamImportWorkeris aUrlImportWorker(it owns_url_worker/_url_progress, so busy/cancel/ quit come free) narratingstageper song — theLTPPpostprocess marker is what says "Converting".ShazamImportWindowis the song list and an embeddedidentify_dialog.IdentifyPanelper 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-timeTrackIdentifierqueue; 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_shazamsruns 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— registersorg.mpris.MediaPlayer2.lintunesover D-Bus so the desktop's media keys / now-playing popup control playback. Spacebar and arrow keys are handled locally viaMainWindow.eventFilter, which ignores auto-repeat: on Wayland repeats are generated client-side until the compositor delivers the release, and a busy gnome-shell turned one held arrow into 1,676 track skips (Round 56). Every list sent over D-Bus must be a typedQDBusArgument(mpris.string_array) — a plain Python list goes out asav, which GDBus rejects. That wasxesam:artist, and the error flood it caused is what kept gnome-shell busy. -
lintunes/trash.py— freedesktop.org Trash spec 1.0, hand-rolled (no new dep). The trash is per-filesystem: music usually lives on a mounted volume, so the file belongs in<topdir>/.Trash-<uid>with a topdir-relative, percent-encodedPath=, not in~/.local/share/Trash(which would be a cross-device copy the file manager can't "Restore"). The.trashinfois created withO_EXCLfirst to claim the name atomically, then the file is renamed in; a failed rename unlinks the info file so there's never a half-trashed pair. RaisesTrashErrorwithout touching the file, so a caller can treat failure as "not deleted". OnlyLibraryManagercalls it. -
lintunes/device_sync.py— one-way playlist sync to the Rabbit R1 (Device menu). The Rabbit mounts via MTP/gvfs (a FUSE path under/run/user/<uid>/gvfs), not mass storage — so plain file I/O, but never copystat and never trust mtimes (diff by name+size). Sync owns exactlyMusic/<Playlist Name>/on the device (creates/overwrites/deletes there, plus an Auxio-importable.m3u); it never deletes outside that folder and only ever reads local library files. Its menu item ("Sync Playlist to Rabbit (Auxio)") was retired in Round 51, once andTunes could play what it syncs; the module stays becausefind_deviceand itssanitize_name/track_display/track_filename/build_m3u/CHUNKare imported by bothexport/exporter.pyandandtunes/, so their signatures are load-bearing. -
lintunes/andtunes/— the desktop half of andTunes, a music player for the Rabbit R1 (Round 47; the app itself lives inandtunes/at the repo root, R1 measurements inandtunes/DEVICE.md, tasks taggedandtuneson the board). The premise: the app never scans anything. Auxio re-reads Android's MediaStore on every launch, which is the "your songs will show up here" hang — but LinTunes already knows the artist, album and year of every file it just copied, so it writes them intoMusic/andTunes/library.jsonand the app parses one file instead of indexing a filesystem.layout.pyis the on-device shape (Media/<Artist>/ <Album>/04 Song.mp3— one copy per song however many playlists hold it — plusArt/,Playlists/,library.json);manifest.pyis pure and Qt-free;art.pyrenders one 480 px JPEG per album (not per track) via QImage — safe off the GUI thread, unlike QPixmap — cached under$XDG_CACHE_HOME/lintunes/andtunes-artand invalidated by the audio file being newer, which is exactly what embedding new art does.sync.pyis a third sibling ofplan_export/ExportWorker: pure planner, then a daemon thread with KiB progress. Three rules that bite: planning must not render art (a mutagen open per album, and planning runs on the GUI thread — the worker does it, and those bytes are absent from the progress total); the index (m3us thenlibrary.json) is written last and after a cancel is rewritten to list only tracks whose files actually landed, so the app never opens a manifest with holes in it; and every delete goes throughlayout.assert_inside, which refuses anything not strictly inside the andTunes root. That guard is why the oldMusic/<Playlist>/folders are structurally unreachable rather than merely un-referenced, andButtons/(the user's own menu artwork) andplays/(written by the app) are skipped by the device scan entirely — sync reads those, it doesn't own them. Which playlists go on the device lives inpreferences.jsonunderdevice_sync(so it rides the Syncthing share and both machines agree); keeping it off thePlaylistkeeps it out of the conflict-merge machinery, and unticking is the only way a playlist comes off the device. A fully ticked folder is stored asdevice_sync.folder_idsand follows the folder — playlists added to it later sync too (device_sync_dialog.resolve_sync_playlistsis what both the dialog and the sync read). The device's filesystem is case-insensitive, so "RJD2" and "Rjd2" are one folder there and one artist here: since Round 54 the app'sLibrary.group()keys bothalbumsByKeyandartistsByNamecase-folded (and fetches the artist before the album block, holding it — the raw-case lookup afterwards is what NPE'd on the second track of a two-spelling album and blanked the whole library), andplan_andtunes_syncfolds both the collision rule and the device diff, which had been re-copying every such file over MTP every sync.plan.stalestill carries the device's own spelling — that is what_delete_staleunlinks by. A gvfs-MTP mount can hold a phantom directory — one it lists happily while the device has no such folder — and every write into it failsEIOforever, becausemkdir(exist_ok=True)sees the phantom and does nothing. Only remounting clears it (gio mount -u mtp://…thengio mount). Two rules came out of it (Round 55): a copy that raisesOSErrorcosts that song, not the sync (it lands in theunwritablesummary list), and the song is then left out of the m3u andlibrary.json— a manifest naming a file that isn't there is worse than a short one, because the app skips to the next track and the user sees the wrong song play. Planning is a worker too (AndTunesPlanWorker):plan_andtunes_syncis pure, but it walks every file on the device, and over MTP that froze the window long enough for GNOME to offer to kill LinTunes mid-sync. Anything after the last album (_write_index, buttons, pruning) must keep emitting progress — it was minutes of silence with the line stuck onAlbum art 501/501, and_write_indexreadsArt/in one listing, never a stat per album. The art pass is held to the same rule (Round 70): it compares each cover againstplan.art_sizes, the sizes the planner's scan already read, never a stat per album, andart.album_art_jpegcaches "this album has no art" as a<key>.nonemarker, so an unchanged library costs the art pass no device I/O and no mutagen opens. Since Round 50 the app exists:andtunes/app/is plain Java against the Android framework, built byandtunes/build.py(aapt2 → javac → R8 → zipalign → apksigner) — no Gradle, no Kotlin, because platform 33 + build-tools 34 were already on disk and trav didn't want a 1 GB download over cell for tools that make the same APK.--shipcopies it tolintunes/android/andTunes.apkwith its version inandTunes.json; re-run--shipwhenever the app changes, since the committed APK is what the self-updater carries and whatinstall.pyinstalls. 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'sMusic/andTunes/speakers.txt— never connect the Rabbit to a speaker that isn't trav's, and read a screencap before everyinput tap: the picker lists the neighbours'.andtunes/andtunes.keystoreis committed on purpose (both machines must sign identically oradb install -rrefuses the update).install.pyis Connections → Install andTunes on Rabbit…: adb as a runtime tool, then the all-files + notification grants (a refused grant is not a failed install — the app's first-run screen covers it), or an MTP copy toDownload/with no adb. Sync copiesbuttons/*.png(rendered byandtunes/tools/make_buttons.py) into the device'sButtons/only where the file is missing — those names are a contract with the app'sUi.button(), which prefers the device copy.proguard.prokeeps no debug attributes because R8 8.2 NPEs on javac 21's. Round 51 closed the loop. The planner runs every track throughexport/web_support.conversion_for(Android decodes the browser set), so FairPlay is refused and ALAC/AIFF land as.flac— converted once into$XDG_CACHE_HOME/lintunes/andtunes-flac/<track id>.flacand size-diffed from there on, so a converted song isn't re-copied every sync. And the app keepsplays/andtunes-<install id>.jsonin the play-journal shape, counted on a natural finish likePlayer;plays.bring_backfolds it into<data_dir>/plays/withplay_journal.merge_totals(per-track max — that file has two homes and both desktops may bring it back) before anything is copied, writing nothing when nothing moved.PlayJournal.loadthen treats the R1 as one more machine. A wedged gvfs-MTP mount blocks in uninterruptible FUSE waits:timeoutcan't kill a process stuck on it. USB re-enumeration (lock/unlock withmtp,adb, anadb install) is what wedged it in Round 51. Recovery:killthegvfsd-mtpprocess, thengio mount mtp://<device>/—device_sync.reset_mtp_connection, offered as Reset Connection when the menu item reads "Rabbit isn't responding…". Since Round 71 the GUI thread never callsfind_device(): it froze the window every time the Connections menu opened on a wedged mount.MainWindow._devices(device_sync.DeviceWatcher) probes on a daemon thread, one at a time, and declaresSTUCKafter 3 s; click handlers go throughwhen_ready(callback). A stuck probe thread can't be killed, so quitting then may still hang until the reset.tests/conftest.pypatchesfind_devicetoNonefor every test, and nothing — test or tool call — may list/run/user/*/gvfs; askgio mount -linstead, which goes over D-Bus. -
lintunes/export/—File → Export Playlist…(also on a playlist's right-click menu). A sibling ofdevice_sync, reusing its filename helpers andbuild_m3u: pureplan_export()first, thenExportWorkeron a daemon thread. Two destinations — a folder (files asArtist - Title.extplus an.m3u) or a web mix (index.html+audios/+ hero image, fromtemplates/; no m3u — it's a folder you upload, not one you open in a player, soplan.m3u_nameis""there). The manifest is written last, so an interrupted export never leaves a page or m3u naming files that aren't there.web_support.pyis the format gate, shaped likecast/support.py: deny-by-default on the suffix with the iTuneskindbreaking the.m4atie. Bitrate never triggers a conversion — only unplayability does — and every conversion targets FLAC, so it can't cost a bit; DRM'd tracks are reported, never attempted. ffmpeg is the CLI binary here (not Qt's ffmpeg backend), so it's detected at runtime and its absence is offered as "export without them". The templates ship a ~180-line dependency-freeplayer.js/player.cssthat replaced audio.js + jQuery (abandoned since 2012; jQuery was only ever glue — audio.js never used it).player-graphics.gifmust ship byte-identical: it's an animated GIF whose loading frame is a spinner, not a flat sprite sheet — which is why Round 41 recolors its pale glyphs to black withfilter: brightness(0)in CSS rather than editing the file. The one user-chosen color (link/row hover backgrounds + the progress fill) travels as a:root { --accent }custom property declared inindex.html, soplayer.csscan read it while staying a verbatimshutil.copyfile— the page is still the only rendered template.exporter.normalize_accentis a hard gate, not politeness: the value lands raw inside a<style>block andstring.Templateescapes nothing. The accent is not persisted, so an untouched export still renders the original#8c764a. Templates are registered insetup.pyviapackage_data; loaded withimportlib.resourcesso 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 withrsync -a --checksum --deleteover 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 inconfig.jsononly (the host is usually this machine's~/.ssh/configalias, and trav's server must never appear in the repo or the synced share — tests useexample-host).--deleteonly ever reaches the slug folder (remote_dirvalidates 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 withBatchMode=yes, since nobody can answer a prompt. Steps:ServerCheckWorker(ssh test -d; an existing folder asks before replacing it),ExportWorker, thenUploadWorker, all shown ingui/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 shipsplaceholder.png. -
lintunes/cassette/— friend library sharing (Round 63+; the spec isCassette friend library.md). LinTunes never talks to a friend: it drives the local Syncthing's REST API (syncthing_api.py, key/address from Syncthing'sconfig.xml, overridable inconfig.json) and Syncthing moves the bytes. Every failure is aSyncthingError(step, detail, kind), because the UI promises never to fail silently. One of trav's machines is the host (host.py:config.jsonflag + a syncedpreferences.jsonrecord naming it); everything lives in the machine-local~/.local/share/lintunes/cassette/(state.json+friends/<token>/ {out,in,cache}), never the synced data dir — Syncthing folders must not nest. A friendship is two folders,lintunes-cassette-<token>-a(inviter → invitee) and-b, each send-only for its writer and receive-only for the reader. Syncthing hides an unknown device's folders (verified on 1.30: a stranger is only a pending device), so while an invite is open the inviter'sCassetteServiceprobes a new knock — adds it with nothing shared, reads which folder it offers, completes on the right-btoken or removes and remembers it (state.rejected). With no open invite nothing is probed and knocks stay pending, untouched. The paste side can't tell "their computer is off" from "their LinTunes is closed" (Syncthing briefly reports a stranger's connection as up), so it shows one combined status.scripts/cassette_pair.pystarts throwaway Syncthings on loopback (no discovery there, henceCassetteService(addresses_for=…)); tests markedsyncthingrun a real handshake withpytest --syncthing. The service starts fromrun_gui, never from constructingMainWindow— tests build windows by the dozen and must not reach a real Syncthing. Friend mode (gui/friend_mode.py, entered from the ▾ beside Library) shows a friend'slibrary.jsonthrough a secondLibraryViewovercassette/friend_library.FriendSource— the slice ofLibraryManagerthat view reads, read-only. Their track ids are theirs: the table isset_read_only(True)(no play, no drag, no copy into my playlists, only "lookup on youtube"), and the cassette column istrack_table.CASSETTE_FIELD(registered inCOLUMN_MAP, deliberately notALL_COLUMNS), live only wherecassette_hooksis set. Nothing is written until Save and Close (service.save_requests→requests.json); any other exit with changes asks "Save changes?".cassette/matching.pyis best effort (exact vs fuzzy);cassette/space.pyjudges the music disk (red) and Syncthing'sminDiskFreefloor on the cassette disk (orange) separately. Delivery (cassette/delivery.py+gui/cassette_delivery.py) is rebuilt from the folders on every pass, both directions: sender = theirrequests.json∩ what I offer now →outbox/<id> ~ <name>(copied to a.partthe.stignorehides, then renamed), and anything no longer requested is deleted — a request vanishing is the delivery receipt. Receiver: planning on the GUI thread (it reads the library), copying onDeliveryWorker's thread (file_importer.stage_file— the import split so the copy is off the GUI thread),manager.add_trackback on the GUI thread (track_from_file: date added now, no listening history). An exact match already in my library is never imported twice, which is what makes a crash between import and requests-rewrite harmless; a missinglibrary.jsonprunes nothing. Followed playlists (a UFO in friend mode) are neverPlaylists of mine:PlaylistTree.followed_providerinjects them (mixed alphabetically or in a friend folder, perFriend.layout), andgui/followed_view.pyplays them fromfriends/<token>/cache/. Player queue entries may be string keys (cassette:<token>:<their id>) resolved byPlayer.track_resolver; a key scrobbles (track_finished) but never callsrecord_play. Requests are always computed byservice._write_requests(cassetted ∪ followed songs not yet cached), so a save never re-asks for what's already in the cache, and a pass prunes cache files no followed playlist uses. -
lintunes/cast/— Chromecast playback (Connections menu), using the media-receiver model:server.pyruns aThreadingHTTPServeron an ephemeral port for the life of a session and the device fetches the original file itself (bit-exact, no transcode). URLs carry an opaque random token, never a path, so traversal is structurally impossible; Range + HEAD are mandatory (the device seeks by re-requesting ranges and won't report a duration without them). A token resolves to an_Assetthat is either a file on disk (audio) or an in-memory blob (album art, which lives in tags rather than as its own file); the two have separate eviction rings so a cover can't push out the previous track's audio. Art is passed asplay_media(thumb=…), which pychromecast folds intometadata["images"]— that's what a TV paints full-screen.support.pyis the format gate — ALAC, AIFF and protected AAC are refused and Player skips them with a status-bar message.discovery.pywrapsCastBrowser;sink.pyis thePlaybackSink;controller.pyowns the session and its ownSleepInhibitor. pychromecast is imported lazily, never at module scope, so the app still launches where the dep isn't installed yet. While casting there is no local PCM, so the visualizer panel doubles as the cast indicator: it shows the cast glyph instead of bars and a click there stops casting (the brightness cycle is suppressed — it means nothing with no bars). That is the only cast control in the transport bar. Position comes from a 500 ms poll ofadjusted_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 tocast/: an AirPlay speaker is sent PCM in real time, so every song is decoded by theffmpegCLI (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), sostream.install_shimpatches theopen_sourcename inpyatv.protocols.raopto answer aPcmRequestwith anFfmpegSourceat 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'sFileSource. pyatv has no pause or seek for RAOP (its pause is stop), soAirPlaySinkruns onestream_fileper 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's22050 + rateframes 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 oneAsyncLoopthread; results come back as Qt signals. Discovery repeatspyatv.scanwhile 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), ingui/cast_dialog.DevicePickerDialog, whichChromecastDialogshares. Connects go RAOP-only (controller.raop_only). Casting and AirPlay are mutually exclusive (MainWindow disconnects the other first); the visualizer tile shows the sink'sglyph. Testing streams against pyatv's own fake receiver (tests/fake_device/raop.pyin 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'scliairplayplays on it through libraop's RAOP client (its "RAOP-compat" route), so since Round 90raop.pyis LinTunes' own RAOP sender reproducing that client's behaviour, and pyatv only discovers those speakers: one RTSP session per connection (auth-setup whenetlists 4, ANNOUNCE AppleLossless, SETUP, RECORD withRTP-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.NativeDeviceis the slice of a pyatv deviceAirPlaySinkdrives, 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'sairplay_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_msoverrides the 2 s. cliairplay is the fallback (Round 91, trav's go-ahead): when the native sender can't connect, or config.json'sairplay_backendis"cli"("native"= never fall back),cli.ensure_binarydownloads Music Assistant's pinned release into$XDG_DATA_HOME/lintunes/bin/once and refuses it unless its SHA-256 matches the one pinned incli.py— thenCliAirPlaySinkruns ffmpeg → cliairplay per stretch of playback (commands on a fifo,[STATUS]lines back on stderr;started at_unix_ms/playing elapsed_msgive the position). Bumping its version means new pinned hashes from that release's SHA256SUMS.airplay_debugputs pyatv's andlintunes.airplay.raop's loggers at DEBUG (every RTSP request); every stream's start, first audio and outcome are logged at INFO underlintunes.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 stdoutto 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/infoas none.
Conventions & gotchas
-
The Rabbit R1's screen is not what the internet says. Measured: 480 × 640 px, physical density 320, override density 160 — so an app sees a 480 × 640 dp canvas on a 2.88" panel (~278 real ppi). One dp is about half its usual physical size, so andTunes doubles every stock value (rows ≥ 88 dp, text 28–32 sp). Don't "fix" it by changing the device density; trav has it where he wants it. Android 13 / API 33, arm64-v8a. The scroll wheel emits KEY_UP/KEY_DOWN (
KEYCODE_DPAD_UP/DOWN). -
Tests are organized as
tests/test_roundN.py— each development round adds a newtest_roundN.pyalongside the topical files (test_models.py,test_itunes_importer.py, etc.). New feature work follows the same pattern. -
Keep
Playerandtrack_tablemanager-free where they already are — cross-cutting data is injected via callbacks/signals (e.g.track_tabletakes aplaylists_for_trackcallback rather than importing the manager). -
Cosmetic table settings must not look like edits. The last column is stretch-sized, so Qt re-fires
sectionResizedfor it on every viewport width change;track_table._on_section_resizedignores that section, or resizing the window would rewrite the open playlist's JSON (and hand Syncthing a conflict) purely for a widthapply_settingsoverrides on load anyway. Round 42 is the same rule one level down: a live smart playlist's membership is never persisted (Playlist.has_derived_membershipgates it injson_storage.save_playlist, which writestrack_ids: []+derived_membership: true) andrecompute_smart_playlistpassestouch=Falseto_set_track_idsso it marks nothing dirty and moves no timestamp. Membership is rebuilt from the criteria on every load (recompute_all_smart), so storing it only bought a conflict per song — one per finished track, on the same file, from both machines. The exceptions arelive_update=Falseandunsupportedcriteria: theirtrack_idsare the content (a snapshot), so they still persist and still count as edits. -
Qt/Wayland gotchas (GNOME/Mutter):
QDrag.setPixmap/setDragCursor/QCursor.pos()are unreliable during a drag —gui/drag_ghost.pypaints its own child-widget overlay instead.QAudioOutputmust not be constructed before aQMainWindowexists (Qt 6.10 deadlock). Some PyQt signal relays need explicit types/lambdas. Title bars are ours (Round 72): Mutter draws none for Wayland clients, and Qt'sadwaitadecoration plugin paints them pure white from hardcoded constants, deaf to the palette. So on Waylandgui/titlebar.install(an app event filter) makes everyWindow/Dialogframeless atPolishand adds aTitleBarat its firstShow, in the palette'sWindowcolor, room made through the window's top contents margin and the window grown by that much so its contents keep their size. Buttons follow GNOME'sbutton-layout; move/resize go throughstartSystemMove/startSystemResize. A window with no layout must paint intocontentsRect()(art_window.py); one that needs the system frame sets thetitlebar.OPT_OUTproperty. 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 ortitlebar.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'sPaint, andtitlebar._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 beforePolish, somake_framelesssets 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.drawControlpaints over Fusion's). The main window setsBLANK_TITLE(the song is in the panel right under it);VisualizerWindowsetsSQUARE— 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 aParentChangetakes 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_componentand_maybe_move_filewrite NFC, andLibraryManager.repair_locationfollows a missing file to its NFC twin (before every tag write, and ontrack_missingbefore asking). -
Music files are only touched deliberately: tag edits via
tagging.py, and — since Round 18 — artist/album_artist/album edits relocate the file insideLibraryManager.organize_root()(<music_folder>/Music) to keep the tree organized iTunes-style (_maybe_move_file; undoable; files outside the root are never moved; the new path syncs cross-machine via thelocationnewest-wins merge inconflict_resolver). Since Round 33 the only other path is an explicit user delete (LibraryManager.delete_tracks), which moves the file to the desktop trash viatrash.py— neverunlink, 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._editablesaves them to a copy beside them andos.replaces 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__inlintunes/__init__.pyis the single source of truth (setup.pyregex-reads it, never imports the package). Claude bumps minor for feature rounds and patch for fix-only rounds as part of each round's final commit; trav decides major bumps. The status-bar version button (gui/version_button.py+lintunes/updater.py) checksoriginshortly after launch and every 4 h, and a click runsgit pull --ff-onlythen re-execs the app — pushingmasteris effectively releasing to the other machines (a new pip dependency still needs a manualpip install -e .there). Every round ends with commit AND push (trav's standing request, 2026-07-03: both machines ride the bleeding edge, sync as often as possible) — so never leave master in a half-working state between commits you push. -
Never develop or verify against trav's real library. It is 21,531 tracks of irreplaceable music and no amount of read-only care makes it the right thing to point a half-finished feature at.
scripts/make_dev_library.pybuilds a synthetic one that has the same shapes — every playlist type (regular, folder, live/non-live/unsupported smart, system, empty, duplicates), six container formats, art on some albums and not others, a play journal, a tombstone, and a deliberate pile of naming edge cases (a collision pair differing only by id, an emoji album, a 208-character title, forbidden characters, a dangling location). Build it withpython3 scripts/make_dev_library.py --out dev-libraryand run against it with--data-dir dev-library/data; it's gitignored, the generator isn't. 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 byscripts/make_icons.pyintopackaging/lintunes.png(desktop, 512 px, installed bypackaging/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._exitafteraboutToQuithas saved everything): a normalsys.exitlet 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--writeto mutate files. -
Not under version control until recently — the
*~files are editor backups (gitignored).data/anditunes-test-library/are gitignored (the user's real library + large import fixture).