android: the phone, on the real core — the mockup shell, playback, the media card, the catalog, the resolver, Save, the dev flavour

The same Tauri 2 project builds for Android: mobile.html as a third Vite
entry (src/mobile/, the mockup on real data), tauri.android.conf.json, the
mobile stubs (updater, lyric alignment, vocal separation), rustls reqwest
on Android, the AAudio buffer, and a hand-driven detour build
(src-tauri/android/{env,build,deploy,dev}.sh) while Developer Mode is off.
ANDROID.md is the recipe.

Playback: the media-session plugin crate (lock-screen card, MediaStyle
notification, audio focus, headset buttons, a foreground service that
promotes itself first — Android 14 kills the app otherwise), session
restore across reload and restart, solid chrome after measuring the
backdrop-filter lag.

The catalog: Search is the desktop's top bar (the top-result rule, artist
cards), the artist page and the record page are the desktop's, Home is the
desktop's landing page, Gaps per followed shelf. Playing goes through the
desktop's own source rules, moved verbatim from state.svelte.js into
src/lib/sources.js so both apps share one resolver; the phone readies the
next three tracks and crosses boundaries gapless. Save fetches a record or
a track into the library by the download rules; Transfers shows the
burst. The raw Soulseek search stays, offered on request, a peer's copy
streaming with the lane rising as the bytes arrive. Community is the
Soulseek side (rooms, chat, buddies); the private layer waits.

The opener and storage plugins (social links, the picked library folder,
all-files access), the volume normalization switch, and the harness:
tests/mobile/smoke.mjs walks the mock (a fake network behind
src/lib/events.js) and the real phone over CDP, perf.mjs measures frames.
This commit is contained in:
KeelrLeek committed 2026-09-13 09:30:06 -05:00
1 parent 972dd103cb
commit bb828ff2dc
102 files changed
+12258 -830

No files matched your search

+9 -1
View File
@@ -1,6 +1,6 @@
// Thin wrapper over Tauri IPC so components never import tauri directly.
import { invoke as tauriInvoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { listen } from "./events.js";
import { mockInvoke } from "./mockLibrary.js";
// mockInvoke is inert (returns undefined) unless localStorage.mockLibrary === "1".
@@ -327,6 +327,8 @@ export const lyricPrepRequest = (path, durationSecs, lines, stream = null) =>
});
// Local-library candidates for the unresolved-row repair panel.
export const libraryTrackSearch = (query) => invoke("library_track_search", { query });
// The whole index, for a list that filters on the device (the phone's Tracks tab).
export const libraryTrackIndex = () => invoke("library_track_index");
// ---- lyrics (see src-tauri/src/lyrics.rs) ----------------------------------
export const lyricsGet = (args) =>
@@ -489,6 +491,12 @@ export const importLocalArt = (sourceRoot, rel, parts) =>
invoke("import_local_art", { sourceRoot, rel, parts });
// Prune rows whose files are gone, then index anything new — the real rescan.
export const rescanLibrary = () => invoke("rescan_library");
// The phone's storage plugin (crates/tauri-plugin-storage): a picked folder
// as { uri, path } (path null when the tree has none), and Android's
// all-files access — { granted }, and the system screen that grants it.
export const pickLibraryFolder = () => invoke("plugin:storage|pick_folder");
export const allFilesAccess = () => invoke("plugin:storage|all_files_access");
export const requestAllFilesAccess = () => invoke("plugin:storage|request_all_files_access");
// Download a found album copy into (Cache)\_audition\<rel>\ for the version
// comparison. Called track 1 first, then the rest — `startIndex` keeps the
// second batch's indices continuing, since index 0 means "track 1".
+9
View File
@@ -0,0 +1,9 @@
/* Backend events, behind the same switch as the IPC: with the mock library
on (localStorage.mockLibrary === "1") a listener is registered with the
mock's own bus, which the mock and the harness can fire; otherwise it is
Tauri's. Stores import `listen` from here so the phone's screens can be
walked in a plain browser with a fake network behind them. */
import { listen as tauriListen } from "@tauri-apps/api/event";
import { mockListen } from "./mockLibrary.js";
export const listen = (event, cb) => mockListen(event, cb) ?? tauriListen(event, cb);
+251 -1
View File
@@ -97,7 +97,6 @@ export function mockInvoke(cmd, args) {
if (!enabled) return undefined;
if (cmd === "library_albums") return Promise.resolve(albums);
if (cmd === "library_album_stats") return Promise.resolve(albums.map(statsFor));
if (cmd === "followed_artists") return Promise.resolve([]);
if (cmd === "recent_albums") return Promise.resolve([]);
if (cmd === "album_tracks")
return new Promise((r) => setTimeout(() => r(tracksFor(args.albumId)), 60));
@@ -107,5 +106,256 @@ export function mockInvoke(cmd, args) {
return Promise.resolve(svgArt((num * 47) % 360, String.fromCharCode(65 + (num % 26))));
}
if (cmd === "list_playlists") return Promise.resolve([]);
// The track index, as the library crate shapes it (TrackIndexRow) — the
// phone's Tracks tab and its library search read these.
if (cmd === "library_track_index" || cmd === "library_track_search") {
const rows = albums.flatMap((a) =>
tracksFor(a.id).map((t) => ({
title: t.title, artist: a.artist, album: a.title,
duration_secs: t.duration_secs, path: t.path, art_path: a.art_path,
})));
if (cmd === "library_track_index") return Promise.resolve(rows);
const words = String(args?.query || "").toLowerCase().split(/\s+/).filter(Boolean);
return Promise.resolve(words.length
? rows.filter((r) => { const hay = (r.artist + r.title + r.album).toLowerCase(); return words.every((w) => hay.includes(w)); }).slice(0, 40)
: []);
}
return mockCatalog(cmd, args) ?? mockNet(cmd, args);
}
/* ── the fake network ───────────────────────────────────────────────────
A Soulseek behind the phone's screens: a stored account that signs in at
boot, a room list, rooms with a few lines in them, a search answered by
five peers, and a stream that arrives over twelve seconds with its
waveform growing — enough to walk Search, Community and the rising lane
in a plain browser. Events go out over the bus below; the harness can
fire its own through window.__ssMock.emit. */
const bus = new Map();
/** Returns a Promise<unlisten> for a mocked page, or undefined to pass through. */
export function mockListen(event, cb) {
if (!enabled) return undefined;
let set = bus.get(event);
if (!set) { set = new Set(); bus.set(event, set); }
set.add(cb);
return Promise.resolve(() => { set.delete(cb); });
}
export function mockEmit(event, payload) {
for (const cb of bus.get(event) || []) {
try { cb({ event, payload }); } catch (e) { console.error(e); }
}
}
const later = (ms, fn) => setTimeout(fn, ms);
if (enabled && typeof window !== "undefined") window.__ssMock = { emit: mockEmit };
const MOCK_USER = "mockuser";
const ROOMS = [["Lounge", 412], ["Electronic", 98], ["Vinyl Rips", 37], ["Jazz", 61], ["Lossless Only", 23]];
const PEOPLE = ["ada", "bo", "cy", "dee"];
const LINES = ["anyone got the 2024 remaster?", "the vinyl rip is warmer imo", "that folder is complete btw", "brb"];
const PEERS = [
{ username: "hifi_hank", slot: true, speed: 2400, queue: 0, ext: "flac", depth: 24, rate: 96000 },
{ username: "dusty_crates", slot: true, speed: 900, queue: 0, ext: "flac", depth: 16, rate: 44100 },
{ username: "bo", slot: false, speed: 1500, queue: 3, ext: "flac", depth: 16, rate: 44100 },
{ username: "mp3_marge", slot: true, speed: 500, queue: 0, ext: "mp3", bitrate: 320 },
{ username: "slowpoke", slot: false, speed: 60, queue: 12, ext: "mp3", bitrate: 192 },
];
const TITLES = ["One More Time", "Aerodynamic", "Digital Love", "Harder, Better, Faster, Stronger", "Crescendolls", "Nightvision", "Superheroes", "High Life", "Something About Us", "Voyager", "Veridis Quo", "Short Circuit", "Face to Face", "Too Long"];
function peerResponse(token, peer, query) {
const artist = /daft/i.test(query) ? "Daft Punk" : (query.split(/\s+/)[0] || "Various");
const album = /discovery/i.test(query) ? "Discovery" : "Homework";
const folder = "@@shared\\Music\\" + artist + "\\" + artist + " - 2001 - " + album + (peer.ext === "flac" ? " [FLAC]" : " [MP3 " + peer.bitrate + "]");
const files = TITLES.map((t, i) => {
const name = String(i + 1).padStart(2, "0") + " - " + t + "." + peer.ext;
const duration = 200 + ((i * 37) % 180);
const size = peer.ext === "flac" ? Math.round(duration * (peer.depth === 24 ? 320000 : 110000)) : Math.round(duration * peer.bitrate * 125);
return { path: folder + "\\" + name, name, folder, size, extension: peer.ext, bitrate: peer.bitrate ?? null, duration, sample_rate: peer.rate ?? 44100, bit_depth: peer.depth ?? null, vbr: false };
});
return { token, username: peer.username, has_free_upload_slot: peer.slot, upload_speed: peer.speed, queue_length: peer.queue, files };
}
/* the catalog: one artist, two records, the songs of one of them */
const CAT_ARTIST = { id: 27, name: "Daft Punk", picture: svgArt(210, "DP"), album_count: 4, fans: 4200000 };
const CAT_NAMESAKE = { id: 28, name: "Daft Punk", picture: "https://cdn-images.dzcdn.net/images/artist/d41d8cd98f00b204e9800998ecf8427e/1000x1000-000000-80-0-0.jpg", album_count: 1, fans: 120 };
const CAT_ALBUMS = [
{ id: 302127, title: "Discovery", artist: "Daft Punk", cover: null, release_date: "2001-03-12", record_type: "album", track_count: 14, edition_group: 302127, is_soundtrack: false },
{ id: 302128, title: "Homework", artist: "Daft Punk", cover: null, release_date: "1997-01-20", record_type: "album", track_count: 16, edition_group: null, is_soundtrack: false },
];
const CAT_TRACKS = TITLES.map((t, i) => ({
id: 3135550 + i, title: t, artist: "Daft Punk", artist_id: 27, rank: 900000 - i * 1000,
album: "Discovery", album_id: 302127, cover: null, duration_secs: 200 + ((i * 37) % 180), preview: null, track_no: i + 1,
}));
const CAT_DISCO = [
...CAT_ALBUMS,
{ id: 302129, title: "Discovery (Deluxe Edition)", artist: "Daft Punk", cover: null, release_date: "2001-03-12", record_type: "album", track_count: 16, edition_group: 302127, is_soundtrack: false },
{ id: 302130, title: "Alive 1997", artist: "Daft Punk", cover: null, release_date: "2001-10-01", record_type: "album", track_count: 1, edition_group: null, is_soundtrack: false },
{ id: 302131, title: "One More Time", artist: "Daft Punk", cover: null, release_date: "2000-11-13", record_type: "single", track_count: 2, edition_group: null, is_soundtrack: false },
{ id: 302132, title: "Musique Vol. 1 1993–2005", artist: "Daft Punk", cover: null, release_date: "2006-04-03", record_type: "compile", track_count: 15, edition_group: null, is_soundtrack: false },
{ id: 302133, title: "TRON: Legacy (Original Motion Picture Soundtrack)", artist: "Daft Punk", cover: null, release_date: "2010-12-03", record_type: "album", track_count: 22, edition_group: null, is_soundtrack: true },
{ id: 302134, title: "Human After All", artist: "Daft Punk", cover: null, release_date: "2005-03-14", record_type: "album", track_count: 10, edition_group: null, is_soundtrack: false },
{ id: 302135, title: "Random Access Memories", artist: "Daft Punk", cover: null, release_date: "2013-05-17", record_type: "album", track_count: 13, edition_group: null, is_soundtrack: false },
];
/* the follows feed needs covers and dates near today */
const dayIso = (offset) => new Date(Date.now() + offset * 86400000).toISOString().slice(0, 10);
for (const a of CAT_DISCO) a.cover = svgArt((a.id * 31) % 360, a.title[0]);
CAT_DISCO.push(
{ id: 302136, title: "Infinity Repeating", artist: "Daft Punk", cover: svgArt(300, "I"), release_date: dayIso(-9), record_type: "single", track_count: 2, edition_group: null, is_soundtrack: false },
{ id: 302137, title: "Alive 2027", artist: "Daft Punk", cover: svgArt(120, "A"), release_date: dayIso(21), record_type: "album", track_count: 12, edition_group: null, is_soundtrack: false },
);
const NEWS = [
{ title: "Daft Punk announce Alive 2027 — a live record from the reunion shows", url: "https://example.com/news/1", source: "Pitchfork", date: Math.floor(Date.now() / 1000) - 3600 * 5 },
{ title: "Infinity Repeating gets a video", url: "https://example.com/news/2", source: "NME", date: Math.floor(Date.now() / 1000) - 86400 * 2 },
];
const RELATED = [["Justice", 411], ["Air", 412], ["Kavinsky", 413], ["Chemical Brothers", 414]].map(([name, id], i) => ({ id, name, picture: i % 2 ? null : svgArt(40 + id, name[0]), album_count: 3, fans: 900000 - id * 100 }));
let follows = [];
function mockCatalog(cmd, args) {
if (cmd === "catalog_artist") {
const id = Number(args?.artistId);
const a = id === CAT_ARTIST.id ? CAT_ARTIST : RELATED.find((r) => r.id === id);
if (!a) return Promise.reject(new Error("catalog_artist: unknown artist"));
const own = a === CAT_ARTIST;
return new Promise((r) => setTimeout(() => r({
artist: a, banner: null, banners: [], banner_custom: false, logos: [],
popular_tracks: own ? CAT_TRACKS.slice(0, 7).map((t, i) => ({ ...t, listeners: 2_400_000 - i * 310_000 })) : [],
albums: own ? CAT_DISCO : [{ id: 900 + id, title: a.name + " Live", artist: a.name, cover: null, release_date: "2015-01-01", record_type: "album", track_count: 9, edition_group: null, is_soundtrack: false }],
top_genre: "Electronic", socials: [],
}), 220));
}
if (cmd === "catalog_artist_socials") {
const id = Number(args?.artistId);
return new Promise((r) => setTimeout(() => r(id === CAT_ARTIST.id ? [{ kind: "website", url: "https://example.com" }, { kind: "wikipedia", url: "https://en.wikipedia.org/wiki/Daft_Punk" }] : []), 300));
}
if (cmd === "home_warm") return Promise.resolve();
if (cmd === "home_artist_news") return new Promise((r) => setTimeout(() => r(Object.fromEntries((args?.artists || []).map((n) => [n, /daft/i.test(n) ? NEWS : []]))), 150));
if (cmd === "catalog_artist_identity") return Promise.resolve({ artist_id: Number(args?.artistId), albums: [], socials: [], type_hints: [], owned_album_ids: [] });
if (cmd === "catalog_artist_profile") return Promise.resolve({ listeners: 3_100_000, plays: 210_000_000, tags: ["electronic", "house", "french house", "dance"] });
if (cmd === "catalog_artist_bio") return Promise.resolve("Daft Punk were a French electronic music duo formed in Paris in 1993 by Guy-Manuel de Homem-Christo and Thomas Bangalter. They achieved popularity in the late 1990s as part of the French house movement.");
if (cmd === "catalog_related") return Promise.resolve(RELATED);
if (cmd === "followed_artists") return Promise.resolve(follows.slice());
if (cmd === "follow_artist") { follows.push({ artist_id: args?.artistId, name: args?.name, portrait: args?.portrait ?? null, followed_at: Date.now() / 1000 }); later(30, () => mockEmit("soulseek:follows-changed", {})); return Promise.resolve(); }
if (cmd === "unfollow_artist") { follows = follows.filter((f) => f.artist_id !== args?.artistId); later(30, () => mockEmit("soulseek:follows-changed", {})); return Promise.resolve(); }
if (cmd === "catalog_search") {
const q = String(args?.query || "").toLowerCase();
const hit = /daft|discovery|one more|punk/.test(q);
return new Promise((r) => setTimeout(() => r(hit
? { artists: [CAT_ARTIST, CAT_NAMESAKE], albums: CAT_ALBUMS, tracks: CAT_TRACKS.slice(0, 8) }
: { artists: [], albums: [], tracks: [] }), 120));
}
if (cmd === "catalog_album") {
const a = CAT_ALBUMS.find((x) => x.id === Number(args?.albumId));
if (!a) return Promise.reject(new Error("catalog_album: unknown album"));
return Promise.resolve({ album: a, tracks: a.id === 302127 ? CAT_TRACKS.map((t, i) => ({ ...t, listeners: 2_400_000 - i * 150_000 })) : [], album_plays: a.id === 302127 ? 310_000_000 : null, album_listeners: a.id === 302127 ? 4_100_000 : null, totals_summed: false });
}
if (cmd === "catalog_album_info") {
const t = String(args?.title || "");
return new Promise((r) => setTimeout(() => r(/discovery/i.test(t)
? { description: "Discovery is the second studio album by the French electronic music duo Daft Punk, released on 12 March 2001. It marks a shift from the Chicago house of their debut to a house style more heavily inspired by disco, post-disco, garage house and synth-pop. The album's singles included the worldwide hit One More Time.", genre: "Electronic", label: "Virgin", source: "wikipedia" }
: null), 150));
}
if (cmd === "download_file") {
const id = ++downloadSeq;
const total = args?.size || 20e6;
const name = String(args?.path || "").split("\\").pop();
const base = { id, username: args?.username, path: args?.path, name, queue_place: null, local_path: null, error: null };
later(200, () => mockEmit("soulseek:download", { ...base, state: "connecting", received: 0, total }));
let got = 0;
const step = setInterval(() => {
got = Math.min(total, got + total / 8);
mockEmit("soulseek:download", { ...base, state: got >= total ? "complete" : "transferring", received: Math.round(got), total, local_path: got >= total ? "C:\\mock\\library\\" + name : null });
if (got >= total) { clearInterval(step); mockEmit("soulseek:library-changed", {}); }
}, 400 + (id % 3) * 120);
return Promise.resolve(id);
}
if (cmd === "cancel_download") return Promise.resolve();
if (cmd === "rescan_library") return Promise.resolve();
if (cmd === "catalog_art") return Promise.resolve(svgArt(200, "D"));
if (cmd === "stream_cache_ready") return Promise.resolve(cacheReady.has(args?.path) || (xfer && xfer.path === args?.path && xfer.received >= xfer.total));
if (cmd === "preload_stream") {
const path = args?.path;
if (!cacheReady.has(path) && !preloading.has(path)) { preloading.add(path); later(4000, () => { preloading.delete(path); cacheReady.add(path); }); }
return Promise.resolve();
}
if (cmd === "preload_cached_stream") return Promise.resolve(cacheReady.has(args?.path));
if (cmd === "excluded_search_phrases") return Promise.resolve([]);
if (cmd === "get_settings") return Promise.resolve({ download_dir: "C:\\mock\\Library" });
if (cmd === "set_settings") return Promise.resolve();
if (cmd === "plugin:storage|pick_folder") return Promise.resolve({ uri: "content://mock/tree/primary%3AMusic", path: "C:\\mock\\Music" });
if (cmd === "plugin:storage|all_files_access") return Promise.resolve({ granted: true });
if (cmd === "plugin:storage|request_all_files_access") return Promise.resolve();
return undefined;
}
let token = 0;
let downloadSeq = 0;
const cacheReady = new Set(); // paths a preload has fully fetched
const preloading = new Set();
let xfer = null; // the one fake transfer: { received, total, timer }
let posTimer = null; // the fake engine's position ticks
function mockNet(cmd, args) {
if (cmd === "get_credentials") return Promise.resolve({ username: MOCK_USER, has_password: true });
if (cmd === "connect_stored" || cmd === "connect_and_login") {
later(400, () => mockEmit("soulseek:state", { kind: "connected", username: MOCK_USER }));
return Promise.resolve();
}
if (cmd === "disconnect") { later(50, () => mockEmit("soulseek:state", { kind: "disconnected" })); return Promise.resolve(); }
if (cmd === "forget_credentials") return Promise.resolve();
if (cmd === "buddy_list") return Promise.resolve(["ada", "cy"]);
if (cmd === "buddy_add") return Promise.resolve(["ada", "cy", args?.username].filter(Boolean));
if (cmd === "buddy_remove") return Promise.resolve(["ada", "cy"].filter((u) => u !== args?.username));
if (cmd === "slsk_room_list") {
later(200, () => mockEmit("soulseek:room-list", ROOMS.map(([name, users]) => ({ name, users }))));
return Promise.resolve();
}
if (cmd === "slsk_join_room") {
const room = args?.room;
later(250, () => mockEmit("soulseek:room-joined", { room, users: [...PEOPLE, MOCK_USER].map((username) => ({ username })) }));
LINES.forEach((message, i) => later(400 + i * 350, () => mockEmit("soulseek:room-message", { room, username: PEOPLE[i % PEOPLE.length], message, ts: Math.floor(Date.now() / 1000) })));
return Promise.resolve();
}
if (cmd === "slsk_leave_room") { later(50, () => mockEmit("soulseek:room-left", { room: args?.room })); return Promise.resolve(); }
if (cmd === "slsk_say_room") {
later(120, () => mockEmit("soulseek:room-message", { room: args?.room, username: MOCK_USER, message: args?.message, ts: Math.floor(Date.now() / 1000) }));
return Promise.resolve();
}
if (cmd === "slsk_message_user") {
later(900, () => mockEmit("soulseek:private-message", { username: args?.username, message: "sure, sending", timestamp: Math.floor(Date.now() / 1000) }));
return Promise.resolve();
}
if (cmd === "start_search") {
const t = ++token;
const q = String(args?.query || "");
later(300, () => mockEmit("soulseek:search-results", [peerResponse(t, PEERS[1], q)]));
later(700, () => mockEmit("soulseek:search-results", [peerResponse(t, PEERS[0], q), peerResponse(t, PEERS[3], q)]));
later(1300, () => mockEmit("soulseek:search-results", [peerResponse(t, PEERS[2], q), peerResponse(t, PEERS[4], q)]));
return Promise.resolve(t);
}
if (cmd === "stop_search") return Promise.resolve();
if (cmd === "play_stream") {
if (xfer) clearInterval(xfer.timer);
clearInterval(posTimer);
const total = args?.size || 30e6;
const duration = args?.duration || 240;
xfer = { received: 0, total, timer: null, path: args?.path };
xfer.timer = setInterval(() => {
xfer.received = Math.min(total, xfer.received + total / 30);
const done = xfer.received >= total;
mockEmit("soulseek:stream", { received: Math.round(xfer.received), total, done, failed: null });
if (done) clearInterval(xfer.timer);
}, 400);
let secs = 0;
later(1200, () => {
mockEmit("soulseek:player", { kind: "playing" });
posTimer = setInterval(() => { secs += 0.5; mockEmit("soulseek:player", { kind: "position", secs, duration }); }, 500);
});
return Promise.resolve();
}
if (cmd === "stream_waveform") {
const coverage = xfer ? xfer.received / xfer.total : 0;
const n = Math.round((args?.buckets || 900) * coverage);
const peaks = Array.from({ length: n }, (_, i) => 0.25 + 0.7 * Math.abs(Math.sin(i * 0.37) * Math.cos(i * 0.011)));
return Promise.resolve({ coverage, peaks });
}
if (cmd === "stream_cache_len") return Promise.resolve(xfer ? Math.round(xfer.received) : 0);
if (cmd === "stream_embedded_art") return Promise.resolve(xfer && xfer.received > 200000 ? svgArt(200, "D") : null);
if (cmd === "record_play") return Promise.resolve(1);
if (cmd === "add_play_seconds") return Promise.resolve();
return undefined;
}
+872
View File
@@ -0,0 +1,872 @@
/* The source rules — the code behind every play button that turns a catalog
track or record into a peer's copy: the query ladder and its poisoned-term
hygiene, the paced search with its early exit, the quality window, the
candidate scoring for songs and albums, the remembered stream sources, and
the small text helpers they all share.
ONE copy, for the desktop (state.svelte.js) and the phone (src/mobile):
the rules moved here verbatim from state.svelte.js on 2026-09-12 so the
phone could play through the same resolver instead of a fork of it.
Nothing in here touches a view or a store — the callers own the player. */
import * as api from "./api.js";
export const RESOLVER_AUDIO_QUALITY = {
flac: 4, ape: 4, aiff: 3.5, wav: 3.5,
m4a: 2.5, ogg: 2.5, opus: 2.5, aac: 2.2, mp3: 2, wma: 1.5,
};
// Formats that decode progressively while the file is still downloading.
// MP4-family files (m4a/aac) put their index at the end and only play once
// complete, so they're save-only.
//
// `opus` was here and must not be: this build has no Opus decoder, so the
// resolver would pick an Opus source to stream, download it, and fail at the
// moment of play. Streamable is a subset of PLAYABLE, never a superset —
// see crates/audio-formats.
const RESOLVER_STREAMABLE = new Set(["flac", "mp3", "ogg", "oga", "wav", "wave", "aiff", "aif"]);
// Lossless for LABELLING — what the file claims to be, which is a different
// question from whether we can decode it. `.ape` and `.wv` are genuinely
// lossless and genuinely unplayable here; a peer's file is still worth naming
// accurately in search results.
const LOSSLESS_EXTS = new Set(["flac", "ape", "wav", "wave", "aiff", "aif", "alac", "wv", "tta"]);
// User source-selection preferences, independent per mode. Loaded from
// settings at startup and refreshed by the Settings view after a commit;
// defaults reproduce the pre-feature behavior exactly.
const DEFAULT_SOURCE_PREFS = { max: "any", min: "any", priority: "quality" };
export const sourcePrefs = {
stream: { ...DEFAULT_SOURCE_PREFS },
download: { ...DEFAULT_SOURCE_PREFS },
};
export async function refreshSourcePrefs() {
try {
const s = await api.getSettings();
sourcePrefs.stream = { ...DEFAULT_SOURCE_PREFS, ...(s?.stream_source_prefs ?? {}) };
sourcePrefs.download = { ...DEFAULT_SOURCE_PREFS, ...(s?.download_source_prefs ?? {}) };
} catch {
// settings unavailable (fresh install / backend restart) → defaults
}
}
// ---- remembered stream sources ------------------------------------------
// The last source each catalog track streamed from, persisted so a track can
// play again WITHOUT a Soulseek search: its bytes are already in the stream
// cache, and the resolve would only rediscover the peer that put them there.
// The memory is a HINT, not a promise — before any search is skipped the
// backend confirms the exact file is byte-complete on disk, so eviction, a
// half-finished transfer, or a source that never delivered all fall back to
// the normal resolver on their own.
const STREAM_SOURCE_STORE = "soulstream.streamSources.v1";
const STREAM_SOURCE_CAP = 400;
let streamSources = null; // Map key → {username, path, size, duration, quality}
function streamSourceKeys(trackId, artist, title) {
const keys = [];
if (trackId != null) keys.push(`t:${trackId}`);
if (artist && title) keys.push(`n:${artist}|${title}`.toLowerCase());
return keys;
}
function loadStreamSources() {
if (streamSources) return streamSources;
streamSources = new Map();
try {
for (const [k, v] of JSON.parse(localStorage.getItem(STREAM_SOURCE_STORE) ?? "[]")) {
streamSources.set(k, v);
}
} catch {
// corrupt store — start over; losing it only costs one search per track
}
return streamSources;
}
function saveStreamSources() {
try {
const entries = [...streamSources.entries()];
localStorage.setItem(
STREAM_SOURCE_STORE,
JSON.stringify(entries.slice(-STREAM_SOURCE_CAP)),
);
} catch {
// quota — same story, the memory is only a shortcut
}
}
/** Called every time a stream item is queued to PLAY (not when it proves
* itself) — eager on purpose: a source that never delivers leaves no complete
* cache file, so the probe rejects it later and nothing was lost. Insertion
* order doubles as the LRU for the cap in saveStreamSources. */
function rememberStreamSource(item) {
if (!item?.stream?.username || !item.path || !(item.stream.size > 0)) return;
const map = loadStreamSources();
const record = {
username: item.stream.username,
path: item.path,
size: item.stream.size,
duration: item.duration ?? null,
quality: item.quality ?? null,
};
for (const key of streamSourceKeys(item.trackId ?? null, item.artist, item.title)) {
map.delete(key);
map.set(key, record);
}
saveStreamSources();
}
/** The remembered source for this track, but ONLY if its cache file is
* byte-complete right now. Anything else is null: resolve normally. */
async function cachedStreamSourceFor(trackId, artist, title) {
const map = loadStreamSources();
for (const key of streamSourceKeys(trackId, artist, title)) {
const src = map.get(key);
if (!src) continue;
// A remembered file whose NAME does not even contain the track's
// base title is a mis-paired memory (the 2026-08-20 incident:
// three unrelated rows each "remembered" the same Weezer FLAC and
// played it from the warm cache forever). Delete it and resolve
// normally — a wrongly-dropped legit source only costs one search.
const base = normText(asciiFold((title ?? "").split(/[([]/)[0]));
const fileName = normText(asciiFold((src.path ?? "").split("\\").pop() ?? ""));
if (base.length >= 4 && fileName && !fileName.includes(base)) {
map.delete(key);
saveStreamSources();
continue;
}
try {
if (await api.streamCacheReady(src.username, src.path, src.size)) return src;
} catch {
// backend unavailable — resolve normally
}
}
return null;
}
/** Whether a peer file satisfies the user's quality window for this mode.
* Lossless formats satisfy every kbps floor; a lossy file must carry a KNOWN
* bitrate at or above it — a peer that hides its bitrate does not get the
* benefit of the doubt when the user asked for a minimum. Thresholds sit
* slightly under nominal so VBR files reporting 317 kbps still count as 320. */
function passesSourcePrefs(f, prefs) {
const lossless = LOSSLESS_EXTS.has(f.extension);
if (prefs.max === "lossy_only" && lossless) return false;
switch (prefs.min) {
case "lossless":
if (!lossless) return false;
break;
case "kbps320":
if (!lossless && (f.bitrate ?? 0) < 315) return false;
break;
case "kbps256":
if (!lossless && (f.bitrate ?? 0) < 250) return false;
break;
case "kbps192":
if (!lossless && (f.bitrate ?? 0) < 186) return false;
break;
}
return true;
}
/** Diacritics folded to ASCII ("Jóga" → "Joga", "Björk" → "Bjork"). Peers
* overwhelmingly name files unaccented; without folding, normText simply
* DELETED accented letters ("Jóga" → "jga") and the request could never
* match the file. */
const asciiFold = (s) => (s ?? "").normalize("NFKD").replace(/\p{M}/gu, "");
const normText = (s) =>
asciiFold(s).toLowerCase().replace(/\(.*?\)|\[.*?\]/g, "").replace(/[^a-z0-9]/g, "");
/** Catalog titles are often verbose editions ("Album; or, The Long Subtitle…",
* "Album (Deluxe Edition)"). Peer searches AND-match every word, so query
* with just the primary segment, capped to a few words. */
function simplifyTitle(s) {
const first = (s ?? "").split(/[;:(\[]/)[0].trim();
const words = (first || s || "").split(/\s+/).slice(0, 6).join(" ");
return words || s || "";
}
// Words that mark an *edition* of a release, not a distinct release. Used to
// tell an edition suffix (noise, safe to drop) from a variant name that names
// a different album — critical for self-titled records where the base title
// alone can't tell "Weezer (Blue Album)" from "Weezer (Red Album)".
const ALBUM_EDITION_RE =
/\b(?:deluxe|expanded|remaster(?:ed)?|anniversary|edition|version|bonus|reissue|super|complete|definitive|legacy|special|collector'?s?|mono|stereo|redux|remix(?:es|ed)?)\b/i;
/** The disambiguating variant name inside a title's brackets — e.g. "Blue
* Album" from "Weezer (Blue Album)", or "Red Album" from "Weezer (Deluxe
* Edition / Red Album)" — skipping pure edition markers. "" when the brackets
* only hold edition noise (or there are none). */
export function albumDisambiguator(title) {
const groups = [...(title ?? "").matchAll(/[([]([^)\]]+)[)\]]/g)].map((m) => m[1]);
for (const inner of groups) {
for (const part of inner.split(/\s*[/|;]\s*/)) {
const p = part.trim();
if (p && !ALBUM_EDITION_RE.test(p)) return p;
}
}
return "";
}
/** Search-query title-part for a release: the simplified title, plus the
* disambiguating variant name when there is one, so distinct self-titled
* albums search for their own colour instead of colliding on the band name. */
function albumQueryTitle(album) {
const base = simplifyTitle(album.title);
// Fall back to a caller-supplied variant (the family's colour) when the
// title itself dropped it — e.g. "Weezer (Deluxe Edition)" is the Red Album
// but names no colour, so without this it searches bare "Weezer".
const d = albumDisambiguator(album.title) || album.variant || "";
return d ? `${base} ${d}` : base;
}
// Server-distributed excluded search phrases (Soulseek message 160). A query
// containing one is NEVER routed by the server — it returns zero responses
// network-wide with no error. Verified live: every query containing "mgmt"
// was silent while "little dark age" alone returned 738 responses. The list
// arrives by event after login and is also fetchable on demand (covers a
// WebView reload); the resolver strips these terms before they reach the wire.
let excludedSearchPhrases = [];
export function setExcludedSearchPhrases(list) {
excludedSearchPhrases = (Array.isArray(list) ? list : [])
.map((p) => String(p ?? "").toLowerCase().trim())
.filter(Boolean);
}
void api.excludedSearchPhrases?.().then(setExcludedSearchPhrases, () => {});
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/** Query with server-excluded phrases removed (whole-word, any position) and
* whitespace collapsed. Returns "" when nothing usable remains. */
export function sanitizeSearchQuery(query) {
let out = ` ${query ?? ""} `;
for (const phrase of [...excludedSearchPhrases, ...learnedPoisonedTerms]) {
out = out.replace(new RegExp(`(?<=^|[^\\p{L}\\p{N}])${escapeRegExp(phrase)}(?=$|[^\\p{L}\\p{N}])`, "giu"), " ");
}
return out.replace(/\s+/g, " ").trim();
}
/** Run a background source search (own token — the Search view is untouched)
* and collect responses. Ends early once `goodCount()` finds enough.
*
* The early exit is evaluated on a 250ms TICK, not only when a batch
* arrives: peers deliver most results within the first second and then go
* quiet, and the old on-batch-only check meant a plentiful-but-fast search
* still sat out the full window waiting for one more batch that never came
* (measured: 8.1s click-to-play on Discovery, ~7s of it idle waiting).
* Thresholds are adaptive — a flood of good candidates releases at 900ms,
* a workable set at 1800ms, and the full window only runs when results
* are genuinely sparse. */
/** Minimum gap between Soulseek searches, whoever asks. A search is SERVER
* traffic, and the server drops sessions that flood it — measured
* 2026-08-03: a fresh login was killed inside ~90 seconds while background
* album fills re-searched on every rapid track click, and the reconnect
* throttle then locked the account out. User-triggered resolves feel
* instant (the first search never waits); only bursts are spread. */
const SEARCH_MIN_GAP_MS = 1500;
let lastSearchStartedAt = 0;
// Exported for the import finder (import-audio.js): the pacing, poisoned-
// term hygiene and early-exit logic must exist ONCE, not be re-coded.
export async function collectSources(query, maxMs, goodCount) {
const gap = lastSearchStartedAt + SEARCH_MIN_GAP_MS - performance.now();
if (gap > 0) await new Promise((r) => setTimeout(r, gap));
lastSearchStartedAt = performance.now();
const token = await api.startSearch(query);
const responses = [];
let unlisten = null;
await new Promise((resolve) => {
const started = performance.now();
const timer = setTimeout(() => {
clearInterval(tick);
resolve();
}, maxMs);
const tick = setInterval(() => {
if (!goodCount) return;
const elapsed = performance.now() - started;
const good = goodCount(responses);
if ((elapsed >= 900 && good >= 12) || (elapsed >= 1800 && good >= 5)) {
clearTimeout(timer);
clearInterval(tick);
resolve();
}
}, 250);
unlisten = api.onEvent("soulseek:search-results", (batch) => {
for (const r of batch) if (r.token === token) responses.push(r);
});
});
unlisten?.();
api.stopSearch(token).catch(() => {});
return responses;
}
/** Queries measured silent (zero responses) recently — skipped for a while
* so a poisoned rung ("mgmt …") costs its discovery timeout once, not on
* every album/track of the same artist. */
const silentQueries = new Map();
const SILENT_QUERY_TTL_MS = 10 * 60 * 1000;
function querySilent(q) {
const at = silentQueries.get(q);
if (at == null) return false;
if (performance.now() - at > SILENT_QUERY_TTL_MS) {
silentQueries.delete(q);
return false;
}
return true;
}
// Terms PROVEN poisoned this session: a rung containing the term was silent
// while a term-less rung answered — the network is fine, the term is dead
// (the "mgmt" case; the server's own excluded list does not admit it).
// Applied exactly like server-excluded phrases, so the second album by the
// same artist never pays the discovery timeout again.
const learnedPoisonedTerms = new Set();
/** Estimated seconds until this peer's file has fully arrived: transfer time
* from the file's size and the peer's advertised upload speed (bytes/sec),
* plus a rough wait for a busy slot / queued transfers. Pessimistic where the
* peer hides its numbers — an unknown speed must not look like a fast one. */
function estimatedTransferSecs(r, file) {
const size = file.size > 0 ? file.size : 60_000_000; // unknown → assume large
const speed = (r.upload_speed ?? 0) > 0 ? r.upload_speed : 75_000; // unknown → slow
let secs = size / speed;
if (!r.has_free_upload_slot) secs += 90;
secs += Math.min(r.queue_length ?? 0, 50) * 45;
return secs;
}
function scoreSource(r, file, prefs = null) {
const q = RESOLVER_AUDIO_QUALITY[file.extension] ?? 0;
if (!q) return -1;
const bitrate = file.bitrate;
// Speed priority ranks by ESTIMATED ARRIVAL TIME — size ÷ peer speed plus
// queue wait — not by raw peer speed. A 40 MB FLAC from a 5 MB/s peer
// (~8s) legitimately beats a 7 MB MP3 from a 100 KB/s peer (~70s). This
// only reorders sources that already passed the user's min/max quality
// window (passesSourcePrefs runs before scoring), so "fastest" can never
// dip below the configured floor. Format/bitrate remain as tie-breakers.
if (prefs?.priority === "speed") {
// Positive baseline: callers treat score <= 0 as "reject this
// format", and a slow, deep-queued peer must rank last, not vanish.
const eta = Math.min(estimatedTransferSecs(r, file), 3_600);
let s = 100_000 - eta * 25;
s += q * 50;
if (bitrate) s += Math.min(bitrate, 1500) / 50;
return s;
}
let s = q * 1000;
if (bitrate) s += Math.min(bitrate, 1500) / 10;
if (r.has_free_upload_slot) s += 600;
s += Math.min(r.upload_speed ?? 0, 5_000_000) / 20_000;
s -= Math.min(r.queue_length ?? 0, 50) * 12;
return s;
}
// Markers that name a DIFFERENT RECORDING of the same song — live takes,
// remixes, demos, covers, radio edits… `normText` strips brackets, so
// "Island in the Sun (Live at X).mp3" matches the studio request perfectly;
// these are tested against the RAW filename + folder to catch that. Matching
// is symmetric: a candidate must carry exactly the markers the requested
// title carries — no live file for a studio request, no studio file for an
// explicitly "(Live)" catalog track.
const TRACK_VARIANT_MARKERS = [
/\blive\b/i,
/\bunplugged\b/i,
/\bacoustic\b/i,
/\bremix(?:es|ed)?\b/i,
/\brmx\b/i,
/\brework(?:ed)?\b/i,
/\bdemo(?:s)?\b/i,
/\binstrumental\b/i,
/\bkaraoke\b/i,
/\bcover(?:s|ed)?\b/i,
/\btribute\b/i,
/\b(?:radio|single)\s+edit\b/i,
/\b(?:club|extended|dub|dance)\s+mix\b/i,
/\bmedley\b/i,
/\bmashup\b/i,
/\bsession(?:s)?\b/i,
/\brehearsal\b/i,
/\bouttake(?:s)?\b/i,
/\balternate\b/i,
/\btake\s+\d+\b/i,
/\bre-?recorded\b/i,
// "<Name>'s Version" re-records (Taylor's Version and kin): a different
// recording of the song, matched symmetrically like every marker here —
// found live by the source audit when a request for "22" top-ranked
// "22 (Taylor's Version)".
/\b\w+['’]s\s+version\b/i,
/\bsped\s+up\b/i,
/\bslowed\b/i,
/\b8[\s-]?bit\b/i,
];
// Checked against the filename only: "Reprise" is also a record label
// (Weezer's!), so folder paths like "… (Reprise, 1996)" must not reject.
const TRACK_VARIANT_NAME_ONLY = [/\breprise\b/i];
/** True when the candidate names a different version of the song than the
* request asked for (either direction). */
function variantMismatch(wantedTitle, candidateName, candidateFolder) {
const cand = `${candidateFolder}\\${candidateName}`;
for (const re of TRACK_VARIANT_MARKERS) {
if (re.test(cand) !== re.test(wantedTitle)) return true;
}
for (const re of TRACK_VARIANT_NAME_ONLY) {
if (re.test(candidateName) !== re.test(wantedTitle)) return true;
}
return false;
}
/** A peer file's playtime is the wrong recording when it's far from the
* catalog's known length — most often a ripped 30-second streaming *preview*
* whose filename matches the real track (e.g. a 30s "Long Season" for a
* 41-minute live track). Only judges when BOTH durations are known; the band
* is generous (±20%, min 45s) so gapless trims and a few seconds of trailing
* silence never trip it. */
function durationMismatch(expectSecs, candSecs) {
if (!expectSecs || !candSecs || expectSecs <= 0 || candSecs <= 0) return false;
const tol = Math.max(45, expectSecs * 0.2);
return Math.abs(candSecs - expectSecs) > tol;
}
/** Ranked candidate files for a song across all responses (best first).
* `album` (title string, optional) biases toward folders of the release the
* user is actually looking at. `expectSecs` (optional) is the catalog track's
* known length, used to drop preview clips / wrong-length rips. */
function songCandidates(
responses,
title,
streamOnly = false,
album = null,
expectSecs = null,
artist = null,
requireIdentityEvidence = false,
) {
const want = normText(title);
const wantedRaw = title ?? "";
const wantAlbum = album ? normText(simplifyTitle(album)) : "";
const artistKey = artist ? normText(artist) : "";
const prefs = streamOnly ? sourcePrefs.stream : sourcePrefs.download;
const out = [];
for (const r of responses) {
for (const f of r.files) {
if (!normText(f.name).includes(want)) continue;
if (streamOnly && !RESOLVER_STREAMABLE.has(f.extension)) continue;
if (!passesSourcePrefs(f, prefs)) continue;
if (variantMismatch(wantedRaw, f.name, f.folder)) continue;
if (durationMismatch(expectSecs, f.duration)) continue;
let s = scoreSource(r, f, prefs);
if (s <= 0) continue;
const albumEvidence = wantAlbum && normText(f.folder).includes(wantAlbum);
const artistEvidence =
artistKey && normText(`${f.folder}\\${f.name}`).includes(artistKey);
// A rung that dropped the artist term (server-excluded phrase)
// matches by title alone, which happily returns other artists'
// covers of the song. The peer's PATH must then prove identity:
// the artist somewhere in the folder/filename, or the exact
// release folder.
if (requireIdentityEvidence && artistKey && !artistEvidence && !albumEvidence) {
continue;
}
// The requested release's own folder beats compilation/misc rips
// (below a format-tier jump, so quality still wins).
if (albumEvidence) s += 800;
if (artistEvidence) s += 400;
// Filename ends with the title → it IS this song, not a longer
// title containing it ("Holiday" vs "Holiday in Cambodia").
if (normText(f.name.replace(/\.[^.]+$/, "")).endsWith(want)) s += 250;
out.push({ username: r.username, file: f, score: s, slotFree: !!r.has_free_upload_slot });
}
}
out.sort((a, b) => b.score - a.score);
// STREAMING needs bytes now: a peer with no free upload slot usually
// queues the request and never starts inside the failover window, and the
// quality-first score let busy lossless peers occupy the whole failover
// list — "Da Funk", with hundreds of sources, spent over a minute walking
// dead candidates (2026-08-03). Stable partition: peers that can deliver
// immediately first, best quality within each half. Downloads keep the
// pure ranking — a save can afford to wait in a queue for the better file.
if (streamOnly) {
return [...out.filter((c) => c.slotFree), ...out.filter((c) => !c.slotFree)];
}
return out;
}
/** Ranked candidate folders for an album (best first). `trackCountOverride`
* is the authoritative track count from the catalog tracklist fetch; prefer it
* over `album.track_count`, which is routinely null when Play is pressed on the
* artist page (Deezer's artist-album LIST endpoint omits nb_tracks). */
function albumCandidates(
responses,
album,
streamOnly = false,
trackCountOverride = null,
requireIdentityEvidence = false,
) {
const artistKey = normText(album.artist ?? "");
const wantAlbum = normText(simplifyTitle(album.title));
const wanted = trackCountOverride ?? album.track_count ?? null;
const year = album.release_date?.slice(0, 4) || null;
// Self-titled disambiguation: the "(Blue Album)" variant, and its bare
// colour word, so we can prefer the right folder and reject a wrong-colour
// one that a fuzzy peer search returns anyway.
const variant = (albumDisambiguator(album.title) || album.variant || "").toLowerCase();
const wantColour = variant.match(/([a-z]+)\s+album\b/)?.[1] || null;
const folders = new Map();
for (const r of responses) {
for (const f of r.files) {
const key = `${r.username}|${f.folder}`;
let g = folders.get(key);
if (!g) {
g = { username: r.username, folder: f.folder, files: [], r };
folders.set(key, g);
}
g.files.push(f);
}
}
const prefs = streamOnly ? sourcePrefs.stream : sourcePrefs.download;
const out = [];
for (const g of folders.values()) {
const audio = g.files.filter(
(f) =>
(streamOnly
? RESOLVER_STREAMABLE.has(f.extension)
: RESOLVER_AUDIO_QUALITY[f.extension])
&& passesSourcePrefs(f, prefs),
);
// Require enough streamable files to plausibly be this release, but
// NEVER default an unknown count to 3 — that silently rejected every
// single/2-track release (whose peer folders hold 1–2 matching files)
// and is exactly why "No streamable album sources found" fired for
// real, obviously-streamable singles like ICARUS. Known count → at most
// 3, floor 1; unknown → just 1.
const minAudio = wanted ? Math.min(3, Math.max(1, wanted)) : 1;
if (audio.length < minAudio) continue;
const top = audio
.map((f) => scoreSource(g.r, f, prefs))
.reduce((a, b) => a + b, 0) / audio.length;
let s = top;
const folderNorm = normText(g.folder);
const albumEvidence = folderNorm.includes(wantAlbum);
const artistEvidence = artistKey && folderNorm.includes(artistKey);
// Artist-less query rung (server-excluded phrase): the folder path
// must prove the release's identity — see songCandidates.
if (requireIdentityEvidence && artistKey && !artistEvidence && !albumEvidence) {
continue;
}
if (albumEvidence) s += 400;
if (artistEvidence) s += 300;
// Prefer folders whose track count matches the release.
if (wanted) s -= Math.min(Math.abs(audio.length - wanted), 20) * 60;
// The release year in the folder path is a strong per-release signal
// (distinguishes reissues and same-named albums).
if (year && g.folder.includes(year)) s += 300;
// Self-titled colour disambiguation: reward the matching "(X Album)"
// folder, and strongly reject a folder that clearly names a different
// colour, so "Weezer (Blue Album)" can't stream from a Red folder.
if (wantColour) {
const folderColours = [
...g.folder.toLowerCase().matchAll(/\b([a-z]+)\s+album\b/g),
].map((m) => m[1]);
if (folderColours.includes(wantColour)) s += 500;
else if (folderColours.length) s -= 900;
}
audio.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
out.push({
username: g.username,
folder: g.folder,
files: g.files,
audio,
score: s,
slotFree: !!g.r.has_free_upload_slot,
});
}
out.sort((a, b) => b.score - a.score);
// Same availability partition as songCandidates, same reason: a streamed
// album must START; a busy peer's better folder is a save-time choice.
if (streamOnly) {
return [...out.filter((c) => c.slotFree), ...out.filter((c) => !c.slotFree)];
}
return out;
}
/** Distill a peer file's tags into the quality info the Now Playing panel
* shows (format/bitrate/sample-rate/bit-depth). All fields are optional —
* many clients only report some, so the panel hides what's missing. */
function qualityOf(f) {
if (!f) return null;
const ext = f.extension || (f.name || f.path || "").split(".").pop() || "";
return {
format: ext.toUpperCase(),
bitrate: f.bitrate ?? null,
sampleRate: f.sample_rate ?? null,
bitDepth: f.bit_depth ?? null,
vbr: !!f.vbr,
size: f.size ?? null,
};
}
/** Deezer's CDN renders the same cover at whatever size the URL's size
* segment asks for. Track objects carry the 250px list thumb
* (`cover_medium`), which looks terrible blown up in the player — rewrite it
* to the 1000px xl the album pages use. Non-Deezer URLs pass through
* untouched. */
function hqCover(url) {
if (!url) return url;
try {
if (!new URL(url).hostname.endsWith("dzcdn.net")) return url;
} catch {
return url;
}
return url.replace(
/\/\d{2,4}x\d{2,4}((?:-[0-9a-z]+)*)\.(jpg|png|webp)$/i,
"/1000x1000$1.$2",
);
}
/** Match a peer file to a catalog track, so queue items carry the tagged
* title instead of the filename.
*
* A track title contained in the filename normally identifies the track — but
* only if it's *specific* to this file. When peers embed the album name in
* every filename ("… - Eggbeater Jesus - 01 Happy Hour.flac"), and the album
* name is also a track title, that album name is a substring of every filename
* and — being long — used to out-rank each track's real, shorter title, so the
* whole album collapsed to one repeated title. So: ignore any title that
* appears in (roughly) every filename, take the longest *specific* match, and
* otherwise fall back to album order when the folder is a complete album. */
function catalogTrackFor(file, i, files, tracks) {
if (!tracks?.length) return null;
const fname = normText(file.name);
const base = (t) => normText(t.title);
const named = (t) => base(t).length >= 3 && fname.includes(base(t));
// PRIMARY: the catalog (Deezer) tracklist, in order. When the folder holds
// exactly the album's track count it's almost always the whole album in
// order, so file `i` is track `i`. That's the only reliable way to tell
// same-named variants apart — "My Name Is Jonas (2024 Remaster)",
// "(Live On BBC…)" and "(Kitchen Tape Demo)" all normalize to one base
// title, so filename matching alone can't say which belongs here (it used
// to pick the longest title, i.e. the verbose live/demo one). Only distrust
// the position if the filename clearly names a DIFFERENT song than the one
// sitting there (a reordered/mismatched folder — handled by the backup).
if (files.length === tracks.length) {
const at = tracks[i];
if (!fname || named(at) || !tracks.some(named)) return at;
}
// BACKUP: fuzzy filename→title matching for a partial/reordered folder.
// Drop any title that appears in ~every filename (that's the album name),
// then among the rest prefer the closest duration (disambiguates same-named
// variants), then the longest title.
const contained = tracks.filter(named);
const ubiquity = (t) => files.reduce((n, f) => n + (normText(f.name).includes(base(t)) ? 1 : 0), 0);
const ubiquitous = Math.max(2, Math.ceil(files.length * 0.5));
let pool = contained.filter((t) => ubiquity(t) < ubiquitous);
if (!pool.length) pool = contained;
if (pool.length) {
const dur = file.duration;
if (dur) {
const off = (t) => Math.abs((t.duration_secs ?? 1e9) - dur);
// Closest duration wins; on a tie prefer the shorter title, i.e. the
// plain studio version over a longer "(Live…)" / "(Demo…)" variant.
return pool.reduce((a, b) =>
off(b) < off(a) || (off(b) === off(a) && b.title.length < a.title.length) ? b : a,
);
}
return pool.reduce((a, b) => (b.title.length > a.title.length ? b : a));
}
return files.length === tracks.length ? tracks[i] : null;
}
/** Turn a peer filename into a readable title when no catalog track matches
* it (a genuine bonus/extra file on an expanded edition): drop the extension
* and a leading track-number prefix ("04. ", "1 - ", "07 ") so it reads as a
* title rather than "04. Dragon Ball Z…". Conservative — only strips a number
* that's clearly a track index (has a separator, or a leading zero), so a title
* like "99 Luftballons" is left intact. */
function cleanTrackName(name) {
const stem = (name ?? "").replace(/\.[^.]+$/, "");
const stripped = stem.replace(/^\s*(?:\d{1,2}\s*[.\-)]|0\d)\s+/, "").trim();
return stripped || stem;
}
/* ── the ladder ───────────────────────────────────────────────────────
The query shapes a caller hands over, each also ASCII-folded, each
sanitised of server-excluded and learned-poisoned terms; the rungs run in
order with short windows, a silent rung is remembered, and a whole silent
ladder gets one quiet retry for the post-login warm-up. `status` is the
caller's resolver state ({ active, label, error }) — the desktop's toast,
the phone's bar line. */
export async function resolveSources(label, queries, goodCount, artistTerm = null, status = null) {
if (status) { status.active = true; status.label = label; status.error = ""; }
try {
const artistKey = artistTerm ? normText(artistTerm) : "";
const seen = new Set();
const ladder = [];
for (const raw of [].concat(queries).filter(Boolean)) {
// Each shape also gets an ASCII-folded rung: peers name files
// unaccented, and the server AND-matches query tokens, so
// "Björk Jóga" finds nothing that "Bjork Joga" finds.
for (const variant of [raw, asciiFold(raw)]) {
const q = sanitizeSearchQuery(variant);
if (!q || seen.has(q)) continue;
seen.add(q);
ladder.push(q);
}
}
// Non-final rungs get a short window: a rung the network answers at
// all answers within ~2s, so a silent (poisoned/warm-up) rung should
// cost 3.5s, not the full budget. Recently-silent rungs are skipped
// outright. The post-login warm-up retry sits BEHIND the ladder: if
// ANY rung answered, connectivity is proven and no retry is owed.
let sawSilentArtistRung = false;
for (let index = 0; index < ladder.length; index++) {
const q = ladder[index];
if (querySilent(q)) continue;
const final = index === ladder.length - 1;
const hasArtist = artistKey && normText(q).includes(artistKey);
const responses = await collectSources(q, final ? 7000 : 3500, goodCount);
if (responses.length) {
// An answered term-less rung after a silent artist rung PROVES
// the artist term is what kills the query — learn it, so the
// artist's other releases skip the dead rung entirely.
if (sawSilentArtistRung && !hasArtist && artistTerm) {
learnedPoisonedTerms.add(artistTerm.toLowerCase().trim());
}
return {
responses,
artistIncluded: !artistKey || normText(q).includes(artistKey),
};
}
if (hasArtist) sawSilentArtistRung = true;
silentQueries.set(q, performance.now());
}
// Whole ladder silent: either the terms are all poisoned or we are in
// the post-login window where the server has not attached us to a
// search parent yet. One quiet retry of the primary rung covers the
// latter (and clears its silent mark on success).
if (ladder.length) {
const q = ladder[0];
const responses = await collectSources(q, 7000, goodCount);
if (responses.length) {
silentQueries.delete(q);
return {
responses,
artistIncluded: !artistKey || normText(q).includes(artistKey),
};
}
}
return { responses: [], artistIncluded: true };
} finally {
if (status) { status.active = false; status.label = ""; }
}
}
/* ── the library first ────────────────────────────────────────────────
Over whatever album list the caller holds (the desktop's library store,
the phone's). */
/** The library's copy of a catalog record, or null. */
export function libraryAlbumIn(albums, artist, title, releaseDate = null) {
const a = normText(artist);
const t1 = normText(title);
if (!a || !t1) return null;
// normText strips ALL bracket content, so base-title comparison alone
// cannot tell self-titled variants apart: "Weezer (Blue Album)" and
// "Weezer (Green Album)" both normalize to "weezer" and would exact-match
// a library copy saved under the bare provider title "Weezer". After the
// base titles agree, identity therefore needs the variant name
// (albumDisambiguator) to agree — or, when either side lacks one, the
// release YEAR to corroborate. A self-titled base carries no identity at
// all (the title is just the artist), so even a bare↔bare title match
// requires the year there. No usable evidence → no local match; streaming
// the right album beats instantly playing the wrong one.
const wantD = normText(albumDisambiguator(title));
// The simplified-title fallback lets a library copy saved under a terse
// name match a verbose catalog EDITION (library "Album" ↔ catalog "Album
// (Deluxe Edition)"); disambiguated variants never take it.
const t2 = wantD ? null : normText(simplifyTitle(title));
const wantYear = releaseDate ? Number(String(releaseDate).slice(0, 4)) || null : null;
const selfTitled = t1 === a;
return (
albums.find((al) => {
if (normText(al.artist) !== a) return false;
const lt = normText(al.title);
if (lt !== t1 && !(t2 && lt === t2)) return false;
const libD = normText(albumDisambiguator(al.title));
if (wantD && wantD === libD) return true;
if (wantD !== libD || selfTitled) {
const libYear = Number(al.year) || null;
return wantYear != null && libYear != null && libYear === wantYear;
}
return true;
}) ?? null
);
}
/** The library's copy of a song, as { album, tracks, index }, or null.
* `albumTracks(id)` fetches a record's rows. */
export async function libraryTrackIn(albums, albumTracks, artist, title) {
const a = normText(artist);
const t = normText(title);
if (!a || !t) return null;
for (const al of albums) {
if (normText(al.artist) !== a) continue;
try {
const tracks = await albumTracks(al.id);
const index = tracks.findIndex((tr) => normText(tr.title) === t);
if (index >= 0) return { album: al, tracks, index };
} catch {
// library unavailable — fall through to streaming
}
}
return null;
}
export {
RESOLVER_STREAMABLE,
LOSSLESS_EXTS,
DEFAULT_SOURCE_PREFS,
STREAM_SOURCE_STORE,
STREAM_SOURCE_CAP,
streamSources,
streamSourceKeys,
loadStreamSources,
saveStreamSources,
rememberStreamSource,
cachedStreamSourceFor,
passesSourcePrefs,
asciiFold,
normText,
simplifyTitle,
ALBUM_EDITION_RE,
albumQueryTitle,
excludedSearchPhrases,
escapeRegExp,
SEARCH_MIN_GAP_MS,
lastSearchStartedAt,
silentQueries,
SILENT_QUERY_TTL_MS,
querySilent,
learnedPoisonedTerms,
estimatedTransferSecs,
scoreSource,
TRACK_VARIANT_MARKERS,
TRACK_VARIANT_NAME_ONLY,
variantMismatch,
durationMismatch,
songCandidates,
albumCandidates,
qualityOf,
hqCover,
catalogTrackFor,
cleanTrackName,
};
+32 -784
View File
@@ -1,5 +1,34 @@
// Shared reactive app state (Svelte 5 runes module).
import * as api from "./api.js";
import {
sourcePrefs,
refreshSourcePrefs,
rememberStreamSource,
cachedStreamSourceFor,
asciiFold,
normText,
simplifyTitle,
albumDisambiguator,
albumQueryTitle,
setExcludedSearchPhrases,
sanitizeSearchQuery,
collectSources,
silentQueries,
querySilent,
learnedPoisonedTerms,
variantMismatch,
durationMismatch,
songCandidates,
albumCandidates,
qualityOf,
hqCover,
catalogTrackFor,
cleanTrackName,
resolveSources,
libraryAlbumIn,
libraryTrackIn,
} from "./sources.js";
export { RESOLVER_AUDIO_QUALITY, sourcePrefs, refreshSourcePrefs, albumDisambiguator, setExcludedSearchPhrases, sanitizeSearchQuery, collectSources } from "./sources.js";
import { nameNorm, pickCatalogMatch } from "./catalogMatch.js";
import { accentFromImage, hexToRgb, rgbToHex, lerpRgb } from "./color.js";
import {
@@ -4083,133 +4112,7 @@ export const resolver = $state({
error: "",
});
export const RESOLVER_AUDIO_QUALITY = {
flac: 4, ape: 4, aiff: 3.5, wav: 3.5,
m4a: 2.5, ogg: 2.5, opus: 2.5, aac: 2.2, mp3: 2, wma: 1.5,
};
// Formats that decode progressively while the file is still downloading.
// MP4-family files (m4a/aac) put their index at the end and only play once
// complete, so they're save-only.
//
// `opus` was here and must not be: this build has no Opus decoder, so the
// resolver would pick an Opus source to stream, download it, and fail at the
// moment of play. Streamable is a subset of PLAYABLE, never a superset —
// see crates/audio-formats.
const RESOLVER_STREAMABLE = new Set(["flac", "mp3", "ogg", "oga", "wav", "wave", "aiff", "aif"]);
// Lossless for LABELLING — what the file claims to be, which is a different
// question from whether we can decode it. `.ape` and `.wv` are genuinely
// lossless and genuinely unplayable here; a peer's file is still worth naming
// accurately in search results.
const LOSSLESS_EXTS = new Set(["flac", "ape", "wav", "wave", "aiff", "aif", "alac", "wv", "tta"]);
// User source-selection preferences, independent per mode. Loaded from
// settings at startup and refreshed by the Settings view after a commit;
// defaults reproduce the pre-feature behavior exactly.
const DEFAULT_SOURCE_PREFS = { max: "any", min: "any", priority: "quality" };
export const sourcePrefs = {
stream: { ...DEFAULT_SOURCE_PREFS },
download: { ...DEFAULT_SOURCE_PREFS },
};
export async function refreshSourcePrefs() {
try {
const s = await api.getSettings();
sourcePrefs.stream = { ...DEFAULT_SOURCE_PREFS, ...(s?.stream_source_prefs ?? {}) };
sourcePrefs.download = { ...DEFAULT_SOURCE_PREFS, ...(s?.download_source_prefs ?? {}) };
} catch {
// settings unavailable (fresh install / backend restart) → defaults
}
}
// ---- remembered stream sources ------------------------------------------
// The last source each catalog track streamed from, persisted so a track can
// play again WITHOUT a Soulseek search: its bytes are already in the stream
// cache, and the resolve would only rediscover the peer that put them there.
// The memory is a HINT, not a promise — before any search is skipped the
// backend confirms the exact file is byte-complete on disk, so eviction, a
// half-finished transfer, or a source that never delivered all fall back to
// the normal resolver on their own.
const STREAM_SOURCE_STORE = "soulstream.streamSources.v1";
const STREAM_SOURCE_CAP = 400;
let streamSources = null; // Map key → {username, path, size, duration, quality}
function streamSourceKeys(trackId, artist, title) {
const keys = [];
if (trackId != null) keys.push(`t:${trackId}`);
if (artist && title) keys.push(`n:${artist}|${title}`.toLowerCase());
return keys;
}
function loadStreamSources() {
if (streamSources) return streamSources;
streamSources = new Map();
try {
for (const [k, v] of JSON.parse(localStorage.getItem(STREAM_SOURCE_STORE) ?? "[]")) {
streamSources.set(k, v);
}
} catch {
// corrupt store — start over; losing it only costs one search per track
}
return streamSources;
}
function saveStreamSources() {
try {
const entries = [...streamSources.entries()];
localStorage.setItem(
STREAM_SOURCE_STORE,
JSON.stringify(entries.slice(-STREAM_SOURCE_CAP)),
);
} catch {
// quota — same story, the memory is only a shortcut
}
}
/** Called every time a stream item is queued to PLAY (not when it proves
* itself) — eager on purpose: a source that never delivers leaves no complete
* cache file, so the probe rejects it later and nothing was lost. Insertion
* order doubles as the LRU for the cap in saveStreamSources. */
function rememberStreamSource(item) {
if (!item?.stream?.username || !item.path || !(item.stream.size > 0)) return;
const map = loadStreamSources();
const record = {
username: item.stream.username,
path: item.path,
size: item.stream.size,
duration: item.duration ?? null,
quality: item.quality ?? null,
};
for (const key of streamSourceKeys(item.trackId ?? null, item.artist, item.title)) {
map.delete(key);
map.set(key, record);
}
saveStreamSources();
}
/** The remembered source for this track, but ONLY if its cache file is
* byte-complete right now. Anything else is null: resolve normally. */
async function cachedStreamSourceFor(trackId, artist, title) {
const map = loadStreamSources();
for (const key of streamSourceKeys(trackId, artist, title)) {
const src = map.get(key);
if (!src) continue;
// A remembered file whose NAME does not even contain the track's
// base title is a mis-paired memory (the 2026-08-20 incident:
// three unrelated rows each "remembered" the same Weezer FLAC and
// played it from the warm cache forever). Delete it and resolve
// normally — a wrongly-dropped legit source only costs one search.
const base = normText(asciiFold((title ?? "").split(/[([]/)[0]));
const fileName = normText(asciiFold((src.path ?? "").split("\\").pop() ?? ""));
if (base.length >= 4 && fileName && !fileName.includes(base)) {
map.delete(key);
saveStreamSources();
continue;
}
try {
if (await api.streamCacheReady(src.username, src.path, src.size)) return src;
} catch {
// backend unavailable — resolve normally
}
}
return null;
}
void refreshSourcePrefs();
// ---- artwork for a stream that arrived without any -----------------------
@@ -4301,225 +4204,6 @@ async function ensureStreamArt(item) {
}
/** Whether a peer file satisfies the user's quality window for this mode.
* Lossless formats satisfy every kbps floor; a lossy file must carry a KNOWN
* bitrate at or above it — a peer that hides its bitrate does not get the
* benefit of the doubt when the user asked for a minimum. Thresholds sit
* slightly under nominal so VBR files reporting 317 kbps still count as 320. */
function passesSourcePrefs(f, prefs) {
const lossless = LOSSLESS_EXTS.has(f.extension);
if (prefs.max === "lossy_only" && lossless) return false;
switch (prefs.min) {
case "lossless":
if (!lossless) return false;
break;
case "kbps320":
if (!lossless && (f.bitrate ?? 0) < 315) return false;
break;
case "kbps256":
if (!lossless && (f.bitrate ?? 0) < 250) return false;
break;
case "kbps192":
if (!lossless && (f.bitrate ?? 0) < 186) return false;
break;
}
return true;
}
/** Diacritics folded to ASCII ("Jóga" → "Joga", "Björk" → "Bjork"). Peers
* overwhelmingly name files unaccented; without folding, normText simply
* DELETED accented letters ("Jóga" → "jga") and the request could never
* match the file. */
const asciiFold = (s) => (s ?? "").normalize("NFKD").replace(/\p{M}/gu, "");
const normText = (s) =>
asciiFold(s).toLowerCase().replace(/\(.*?\)|\[.*?\]/g, "").replace(/[^a-z0-9]/g, "");
/** Catalog titles are often verbose editions ("Album; or, The Long Subtitle…",
* "Album (Deluxe Edition)"). Peer searches AND-match every word, so query
* with just the primary segment, capped to a few words. */
function simplifyTitle(s) {
const first = (s ?? "").split(/[;:(\[]/)[0].trim();
const words = (first || s || "").split(/\s+/).slice(0, 6).join(" ");
return words || s || "";
}
// Words that mark an *edition* of a release, not a distinct release. Used to
// tell an edition suffix (noise, safe to drop) from a variant name that names
// a different album — critical for self-titled records where the base title
// alone can't tell "Weezer (Blue Album)" from "Weezer (Red Album)".
const ALBUM_EDITION_RE =
/\b(?:deluxe|expanded|remaster(?:ed)?|anniversary|edition|version|bonus|reissue|super|complete|definitive|legacy|special|collector'?s?|mono|stereo|redux|remix(?:es|ed)?)\b/i;
/** The disambiguating variant name inside a title's brackets — e.g. "Blue
* Album" from "Weezer (Blue Album)", or "Red Album" from "Weezer (Deluxe
* Edition / Red Album)" — skipping pure edition markers. "" when the brackets
* only hold edition noise (or there are none). */
export function albumDisambiguator(title) {
const groups = [...(title ?? "").matchAll(/[([]([^)\]]+)[)\]]/g)].map((m) => m[1]);
for (const inner of groups) {
for (const part of inner.split(/\s*[/|;]\s*/)) {
const p = part.trim();
if (p && !ALBUM_EDITION_RE.test(p)) return p;
}
}
return "";
}
/** Search-query title-part for a release: the simplified title, plus the
* disambiguating variant name when there is one, so distinct self-titled
* albums search for their own colour instead of colliding on the band name. */
function albumQueryTitle(album) {
const base = simplifyTitle(album.title);
// Fall back to a caller-supplied variant (the family's colour) when the
// title itself dropped it — e.g. "Weezer (Deluxe Edition)" is the Red Album
// but names no colour, so without this it searches bare "Weezer".
const d = albumDisambiguator(album.title) || album.variant || "";
return d ? `${base} ${d}` : base;
}
// Server-distributed excluded search phrases (Soulseek message 160). A query
// containing one is NEVER routed by the server — it returns zero responses
// network-wide with no error. Verified live: every query containing "mgmt"
// was silent while "little dark age" alone returned 738 responses. The list
// arrives by event after login and is also fetchable on demand (covers a
// WebView reload); the resolver strips these terms before they reach the wire.
let excludedSearchPhrases = [];
export function setExcludedSearchPhrases(list) {
excludedSearchPhrases = (Array.isArray(list) ? list : [])
.map((p) => String(p ?? "").toLowerCase().trim())
.filter(Boolean);
}
void api.excludedSearchPhrases?.().then(setExcludedSearchPhrases, () => {});
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/** Query with server-excluded phrases removed (whole-word, any position) and
* whitespace collapsed. Returns "" when nothing usable remains. */
export function sanitizeSearchQuery(query) {
let out = ` ${query ?? ""} `;
for (const phrase of [...excludedSearchPhrases, ...learnedPoisonedTerms]) {
out = out.replace(new RegExp(`(?<=^|[^\\p{L}\\p{N}])${escapeRegExp(phrase)}(?=$|[^\\p{L}\\p{N}])`, "giu"), " ");
}
return out.replace(/\s+/g, " ").trim();
}
/** Run a background source search (own token — the Search view is untouched)
* and collect responses. Ends early once `goodCount()` finds enough.
*
* The early exit is evaluated on a 250ms TICK, not only when a batch
* arrives: peers deliver most results within the first second and then go
* quiet, and the old on-batch-only check meant a plentiful-but-fast search
* still sat out the full window waiting for one more batch that never came
* (measured: 8.1s click-to-play on Discovery, ~7s of it idle waiting).
* Thresholds are adaptive — a flood of good candidates releases at 900ms,
* a workable set at 1800ms, and the full window only runs when results
* are genuinely sparse. */
/** Minimum gap between Soulseek searches, whoever asks. A search is SERVER
* traffic, and the server drops sessions that flood it — measured
* 2026-08-03: a fresh login was killed inside ~90 seconds while background
* album fills re-searched on every rapid track click, and the reconnect
* throttle then locked the account out. User-triggered resolves feel
* instant (the first search never waits); only bursts are spread. */
const SEARCH_MIN_GAP_MS = 1500;
let lastSearchStartedAt = 0;
// Exported for the import finder (import-audio.js): the pacing, poisoned-
// term hygiene and early-exit logic must exist ONCE, not be re-coded.
export async function collectSources(query, maxMs, goodCount) {
const gap = lastSearchStartedAt + SEARCH_MIN_GAP_MS - performance.now();
if (gap > 0) await new Promise((r) => setTimeout(r, gap));
lastSearchStartedAt = performance.now();
const token = await api.startSearch(query);
const responses = [];
let unlisten = null;
await new Promise((resolve) => {
const started = performance.now();
const timer = setTimeout(() => {
clearInterval(tick);
resolve();
}, maxMs);
const tick = setInterval(() => {
if (!goodCount) return;
const elapsed = performance.now() - started;
const good = goodCount(responses);
if ((elapsed >= 900 && good >= 12) || (elapsed >= 1800 && good >= 5)) {
clearTimeout(timer);
clearInterval(tick);
resolve();
}
}, 250);
unlisten = api.onEvent("soulseek:search-results", (batch) => {
for (const r of batch) if (r.token === token) responses.push(r);
});
});
unlisten?.();
api.stopSearch(token).catch(() => {});
return responses;
}
/** Queries measured silent (zero responses) recently — skipped for a while
* so a poisoned rung ("mgmt …") costs its discovery timeout once, not on
* every album/track of the same artist. */
const silentQueries = new Map();
const SILENT_QUERY_TTL_MS = 10 * 60 * 1000;
function querySilent(q) {
const at = silentQueries.get(q);
if (at == null) return false;
if (performance.now() - at > SILENT_QUERY_TTL_MS) {
silentQueries.delete(q);
return false;
}
return true;
}
// Terms PROVEN poisoned this session: a rung containing the term was silent
// while a term-less rung answered — the network is fine, the term is dead
// (the "mgmt" case; the server's own excluded list does not admit it).
// Applied exactly like server-excluded phrases, so the second album by the
// same artist never pays the discovery timeout again.
const learnedPoisonedTerms = new Set();
/** Estimated seconds until this peer's file has fully arrived: transfer time
* from the file's size and the peer's advertised upload speed (bytes/sec),
* plus a rough wait for a busy slot / queued transfers. Pessimistic where the
* peer hides its numbers — an unknown speed must not look like a fast one. */
function estimatedTransferSecs(r, file) {
const size = file.size > 0 ? file.size : 60_000_000; // unknown → assume large
const speed = (r.upload_speed ?? 0) > 0 ? r.upload_speed : 75_000; // unknown → slow
let secs = size / speed;
if (!r.has_free_upload_slot) secs += 90;
secs += Math.min(r.queue_length ?? 0, 50) * 45;
return secs;
}
function scoreSource(r, file, prefs = null) {
const q = RESOLVER_AUDIO_QUALITY[file.extension] ?? 0;
if (!q) return -1;
const bitrate = file.bitrate;
// Speed priority ranks by ESTIMATED ARRIVAL TIME — size ÷ peer speed plus
// queue wait — not by raw peer speed. A 40 MB FLAC from a 5 MB/s peer
// (~8s) legitimately beats a 7 MB MP3 from a 100 KB/s peer (~70s). This
// only reorders sources that already passed the user's min/max quality
// window (passesSourcePrefs runs before scoring), so "fastest" can never
// dip below the configured floor. Format/bitrate remain as tie-breakers.
if (prefs?.priority === "speed") {
// Positive baseline: callers treat score <= 0 as "reject this
// format", and a slow, deep-queued peer must rank last, not vanish.
const eta = Math.min(estimatedTransferSecs(r, file), 3_600);
let s = 100_000 - eta * 25;
s += q * 50;
if (bitrate) s += Math.min(bitrate, 1500) / 50;
return s;
}
let s = q * 1000;
if (bitrate) s += Math.min(bitrate, 1500) / 10;
if (r.has_free_upload_slot) s += 600;
s += Math.min(r.upload_speed ?? 0, 5_000_000) / 20_000;
s -= Math.min(r.queue_length ?? 0, 50) * 12;
return s;
}
function requireOnline() {
if (app.connection !== "online") {
app.showLogin = true;
@@ -4528,135 +4212,6 @@ function requireOnline() {
return true;
}
// Markers that name a DIFFERENT RECORDING of the same song — live takes,
// remixes, demos, covers, radio edits… `normText` strips brackets, so
// "Island in the Sun (Live at X).mp3" matches the studio request perfectly;
// these are tested against the RAW filename + folder to catch that. Matching
// is symmetric: a candidate must carry exactly the markers the requested
// title carries — no live file for a studio request, no studio file for an
// explicitly "(Live)" catalog track.
const TRACK_VARIANT_MARKERS = [
/\blive\b/i,
/\bunplugged\b/i,
/\bacoustic\b/i,
/\bremix(?:es|ed)?\b/i,
/\brmx\b/i,
/\brework(?:ed)?\b/i,
/\bdemo(?:s)?\b/i,
/\binstrumental\b/i,
/\bkaraoke\b/i,
/\bcover(?:s|ed)?\b/i,
/\btribute\b/i,
/\b(?:radio|single)\s+edit\b/i,
/\b(?:club|extended|dub|dance)\s+mix\b/i,
/\bmedley\b/i,
/\bmashup\b/i,
/\bsession(?:s)?\b/i,
/\brehearsal\b/i,
/\bouttake(?:s)?\b/i,
/\balternate\b/i,
/\btake\s+\d+\b/i,
/\bre-?recorded\b/i,
// "<Name>'s Version" re-records (Taylor's Version and kin): a different
// recording of the song, matched symmetrically like every marker here —
// found live by the source audit when a request for "22" top-ranked
// "22 (Taylor's Version)".
/\b\w+['’]s\s+version\b/i,
/\bsped\s+up\b/i,
/\bslowed\b/i,
/\b8[\s-]?bit\b/i,
];
// Checked against the filename only: "Reprise" is also a record label
// (Weezer's!), so folder paths like "… (Reprise, 1996)" must not reject.
const TRACK_VARIANT_NAME_ONLY = [/\breprise\b/i];
/** True when the candidate names a different version of the song than the
* request asked for (either direction). */
function variantMismatch(wantedTitle, candidateName, candidateFolder) {
const cand = `${candidateFolder}\\${candidateName}`;
for (const re of TRACK_VARIANT_MARKERS) {
if (re.test(cand) !== re.test(wantedTitle)) return true;
}
for (const re of TRACK_VARIANT_NAME_ONLY) {
if (re.test(candidateName) !== re.test(wantedTitle)) return true;
}
return false;
}
/** A peer file's playtime is the wrong recording when it's far from the
* catalog's known length — most often a ripped 30-second streaming *preview*
* whose filename matches the real track (e.g. a 30s "Long Season" for a
* 41-minute live track). Only judges when BOTH durations are known; the band
* is generous (±20%, min 45s) so gapless trims and a few seconds of trailing
* silence never trip it. */
function durationMismatch(expectSecs, candSecs) {
if (!expectSecs || !candSecs || expectSecs <= 0 || candSecs <= 0) return false;
const tol = Math.max(45, expectSecs * 0.2);
return Math.abs(candSecs - expectSecs) > tol;
}
/** Ranked candidate files for a song across all responses (best first).
* `album` (title string, optional) biases toward folders of the release the
* user is actually looking at. `expectSecs` (optional) is the catalog track's
* known length, used to drop preview clips / wrong-length rips. */
function songCandidates(
responses,
title,
streamOnly = false,
album = null,
expectSecs = null,
artist = null,
requireIdentityEvidence = false,
) {
const want = normText(title);
const wantedRaw = title ?? "";
const wantAlbum = album ? normText(simplifyTitle(album)) : "";
const artistKey = artist ? normText(artist) : "";
const prefs = streamOnly ? sourcePrefs.stream : sourcePrefs.download;
const out = [];
for (const r of responses) {
for (const f of r.files) {
if (!normText(f.name).includes(want)) continue;
if (streamOnly && !RESOLVER_STREAMABLE.has(f.extension)) continue;
if (!passesSourcePrefs(f, prefs)) continue;
if (variantMismatch(wantedRaw, f.name, f.folder)) continue;
if (durationMismatch(expectSecs, f.duration)) continue;
let s = scoreSource(r, f, prefs);
if (s <= 0) continue;
const albumEvidence = wantAlbum && normText(f.folder).includes(wantAlbum);
const artistEvidence =
artistKey && normText(`${f.folder}\\${f.name}`).includes(artistKey);
// A rung that dropped the artist term (server-excluded phrase)
// matches by title alone, which happily returns other artists'
// covers of the song. The peer's PATH must then prove identity:
// the artist somewhere in the folder/filename, or the exact
// release folder.
if (requireIdentityEvidence && artistKey && !artistEvidence && !albumEvidence) {
continue;
}
// The requested release's own folder beats compilation/misc rips
// (below a format-tier jump, so quality still wins).
if (albumEvidence) s += 800;
if (artistEvidence) s += 400;
// Filename ends with the title → it IS this song, not a longer
// title containing it ("Holiday" vs "Holiday in Cambodia").
if (normText(f.name.replace(/\.[^.]+$/, "")).endsWith(want)) s += 250;
out.push({ username: r.username, file: f, score: s, slotFree: !!r.has_free_upload_slot });
}
}
out.sort((a, b) => b.score - a.score);
// STREAMING needs bytes now: a peer with no free upload slot usually
// queues the request and never starts inside the failover window, and the
// quality-first score let busy lossless peers occupy the whole failover
// list — "Da Funk", with hundreds of sources, spent over a minute walking
// dead candidates (2026-08-03). Stable partition: peers that can deliver
// immediately first, best quality within each half. Downloads keep the
// pure ranking — a save can afford to wait in a queue for the better file.
if (streamOnly) {
return [...out.filter((c) => c.slotFree), ...out.filter((c) => !c.slotFree)];
}
return out;
}
/** Exposed for the source-resolution audit harness (session-scratchpad CDP
* probes drive the REAL matching/scoring code against live search responses).
@@ -4691,103 +4246,6 @@ function waitForStreamStart(ms) {
});
}
/** Ranked candidate folders for an album (best first). `trackCountOverride`
* is the authoritative track count from the catalog tracklist fetch; prefer it
* over `album.track_count`, which is routinely null when Play is pressed on the
* artist page (Deezer's artist-album LIST endpoint omits nb_tracks). */
function albumCandidates(
responses,
album,
streamOnly = false,
trackCountOverride = null,
requireIdentityEvidence = false,
) {
const artistKey = normText(album.artist ?? "");
const wantAlbum = normText(simplifyTitle(album.title));
const wanted = trackCountOverride ?? album.track_count ?? null;
const year = album.release_date?.slice(0, 4) || null;
// Self-titled disambiguation: the "(Blue Album)" variant, and its bare
// colour word, so we can prefer the right folder and reject a wrong-colour
// one that a fuzzy peer search returns anyway.
const variant = (albumDisambiguator(album.title) || album.variant || "").toLowerCase();
const wantColour = variant.match(/([a-z]+)\s+album\b/)?.[1] || null;
const folders = new Map();
for (const r of responses) {
for (const f of r.files) {
const key = `${r.username}|${f.folder}`;
let g = folders.get(key);
if (!g) {
g = { username: r.username, folder: f.folder, files: [], r };
folders.set(key, g);
}
g.files.push(f);
}
}
const prefs = streamOnly ? sourcePrefs.stream : sourcePrefs.download;
const out = [];
for (const g of folders.values()) {
const audio = g.files.filter(
(f) =>
(streamOnly
? RESOLVER_STREAMABLE.has(f.extension)
: RESOLVER_AUDIO_QUALITY[f.extension])
&& passesSourcePrefs(f, prefs),
);
// Require enough streamable files to plausibly be this release, but
// NEVER default an unknown count to 3 — that silently rejected every
// single/2-track release (whose peer folders hold 1–2 matching files)
// and is exactly why "No streamable album sources found" fired for
// real, obviously-streamable singles like ICARUS. Known count → at most
// 3, floor 1; unknown → just 1.
const minAudio = wanted ? Math.min(3, Math.max(1, wanted)) : 1;
if (audio.length < minAudio) continue;
const top = audio
.map((f) => scoreSource(g.r, f, prefs))
.reduce((a, b) => a + b, 0) / audio.length;
let s = top;
const folderNorm = normText(g.folder);
const albumEvidence = folderNorm.includes(wantAlbum);
const artistEvidence = artistKey && folderNorm.includes(artistKey);
// Artist-less query rung (server-excluded phrase): the folder path
// must prove the release's identity — see songCandidates.
if (requireIdentityEvidence && artistKey && !artistEvidence && !albumEvidence) {
continue;
}
if (albumEvidence) s += 400;
if (artistEvidence) s += 300;
// Prefer folders whose track count matches the release.
if (wanted) s -= Math.min(Math.abs(audio.length - wanted), 20) * 60;
// The release year in the folder path is a strong per-release signal
// (distinguishes reissues and same-named albums).
if (year && g.folder.includes(year)) s += 300;
// Self-titled colour disambiguation: reward the matching "(X Album)"
// folder, and strongly reject a folder that clearly names a different
// colour, so "Weezer (Blue Album)" can't stream from a Red folder.
if (wantColour) {
const folderColours = [
...g.folder.toLowerCase().matchAll(/\b([a-z]+)\s+album\b/g),
].map((m) => m[1]);
if (folderColours.includes(wantColour)) s += 500;
else if (folderColours.length) s -= 900;
}
audio.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
out.push({
username: g.username,
folder: g.folder,
files: g.files,
audio,
score: s,
slotFree: !!g.r.has_free_upload_slot,
});
}
out.sort((a, b) => b.score - a.score);
// Same availability partition as songCandidates, same reason: a streamed
// album must START; a busy peer's better folder is a save-time choice.
if (streamOnly) {
return [...out.filter((c) => c.slotFree), ...out.filter((c) => !c.slotFree)];
}
return out;
}
/** Walk a LADDER of query shapes until one returns responses. Each rung is
* sanitized against the server's excluded-phrase list first (a poisoned term
@@ -4799,74 +4257,8 @@ function albumCandidates(
*
* `queries` may be a string (single rung) or an array, best-first. */
async function resolve(label, queries, goodCount, artistTerm = null) {
resolver.active = true;
resolver.label = label;
resolver.error = "";
player.error = "";
try {
const artistKey = artistTerm ? normText(artistTerm) : "";
const seen = new Set();
const ladder = [];
for (const raw of [].concat(queries).filter(Boolean)) {
// Each shape also gets an ASCII-folded rung: peers name files
// unaccented, and the server AND-matches query tokens, so
// "Björk Jóga" finds nothing that "Bjork Joga" finds.
for (const variant of [raw, asciiFold(raw)]) {
const q = sanitizeSearchQuery(variant);
if (!q || seen.has(q)) continue;
seen.add(q);
ladder.push(q);
}
}
// Non-final rungs get a short window: a rung the network answers at
// all answers within ~2s, so a silent (poisoned/warm-up) rung should
// cost 3.5s, not the full budget. Recently-silent rungs are skipped
// outright. The post-login warm-up retry moved BEHIND the ladder: if
// ANY rung answered, connectivity is proven and no retry is owed —
// the old first-rung retry burned 7 extra seconds on every poisoned
// artist query before the fallback rung even ran.
let sawSilentArtistRung = false;
for (let index = 0; index < ladder.length; index++) {
const q = ladder[index];
if (querySilent(q)) continue;
const final = index === ladder.length - 1;
const hasArtist = artistKey && normText(q).includes(artistKey);
const responses = await collectSources(q, final ? 7000 : 3500, goodCount);
if (responses.length) {
// An answered term-less rung after a silent artist rung PROVES
// the artist term is what kills the query — learn it, so the
// artist's other releases skip the dead rung entirely.
if (sawSilentArtistRung && !hasArtist && artistTerm) {
learnedPoisonedTerms.add(artistTerm.toLowerCase().trim());
}
return {
responses,
artistIncluded: !artistKey || normText(q).includes(artistKey),
};
}
if (hasArtist) sawSilentArtistRung = true;
silentQueries.set(q, performance.now());
}
// Whole ladder silent: either the terms are all poisoned or we are in
// the post-login window where the server has not attached us to a
// search parent yet. One quiet retry of the primary rung covers the
// latter (and clears its silent mark on success).
if (ladder.length) {
const q = ladder[0];
const responses = await collectSources(q, 7000, goodCount);
if (responses.length) {
silentQueries.delete(q);
return {
responses,
artistIncluded: !artistKey || normText(q).includes(artistKey),
};
}
}
return { responses: [], artistIncluded: true };
} finally {
resolver.active = false;
resolver.label = "";
}
return resolveSources(label, queries, goodCount, artistTerm, resolver);
}
// ---- library-first playback ----
@@ -4877,40 +4269,7 @@ async function resolve(label, queries, goodCount, artistTerm = null) {
* artist page's ✓ badges, plus the simplified-title variant so verbose
* catalog editions still match). */
function libraryAlbumFor(artist, title, releaseDate = null) {
const a = normText(artist);
const t1 = normText(title);
if (!a || !t1) return null;
// normText strips ALL bracket content, so base-title comparison alone
// cannot tell self-titled variants apart: "Weezer (Blue Album)" and
// "Weezer (Green Album)" both normalize to "weezer" and would exact-match
// a library copy saved under the bare provider title "Weezer". After the
// base titles agree, identity therefore needs the variant name
// (albumDisambiguator) to agree — or, when either side lacks one, the
// release YEAR to corroborate. A self-titled base carries no identity at
// all (the title is just the artist), so even a bare↔bare title match
// requires the year there. No usable evidence → no local match; streaming
// the right album beats instantly playing the wrong one.
const wantD = normText(albumDisambiguator(title));
// The simplified-title fallback lets a library copy saved under a terse
// name match a verbose catalog EDITION (library "Album" ↔ catalog "Album
// (Deluxe Edition)"); disambiguated variants never take it.
const t2 = wantD ? null : normText(simplifyTitle(title));
const wantYear = releaseDate ? Number(String(releaseDate).slice(0, 4)) || null : null;
const selfTitled = t1 === a;
return (
libraryStore.albums.find((al) => {
if (normText(al.artist) !== a) return false;
const lt = normText(al.title);
if (lt !== t1 && !(t2 && lt === t2)) return false;
const libD = normText(albumDisambiguator(al.title));
if (wantD && wantD === libD) return true;
if (wantD !== libD || selfTitled) {
const libYear = Number(al.year) || null;
return wantYear != null && libYear != null && libYear === wantYear;
}
return true;
}) ?? null
);
return libraryAlbumIn(libraryStore.albums, artist, title, releaseDate);
}
/** The library album matching a catalog release, or null — the same evidence
@@ -4930,37 +4289,9 @@ export function libraryHasAlbum(artist, album) {
/** Locate a track in the library by artist + title, searching only that
* artist's albums. Returns { album, tracks, index } or null. */
async function libraryTrackFor(artist, title) {
const a = normText(artist);
const t = normText(title);
if (!a || !t) return null;
for (const al of libraryStore.albums) {
if (normText(al.artist) !== a) continue;
try {
const tracks = await api.albumTracks(al.id);
const index = tracks.findIndex((tr) => normText(tr.title) === t);
if (index >= 0) return { album: al, tracks, index };
} catch {
// library unavailable — fall through to streaming
}
}
return null;
return libraryTrackIn(libraryStore.albums, (id) => api.albumTracks(id), artist, title);
}
/** Distill a peer file's tags into the quality info the Now Playing panel
* shows (format/bitrate/sample-rate/bit-depth). All fields are optional —
* many clients only report some, so the panel hides what's missing. */
function qualityOf(f) {
if (!f) return null;
const ext = f.extension || (f.name || f.path || "").split(".").pop() || "";
return {
format: ext.toUpperCase(),
bitrate: f.bitrate ?? null,
sampleRate: f.sample_rate ?? null,
bitDepth: f.bit_depth ?? null,
vbr: !!f.vbr,
size: f.size ?? null,
};
}
/** Quality info for a local library track: format from the path, the rest
* from the DB (sample-rate/bit-depth/size backfilled for older files at
@@ -4980,23 +4311,6 @@ function localQuality(t) {
};
}
/** Deezer's CDN renders the same cover at whatever size the URL's size
* segment asks for. Track objects carry the 250px list thumb
* (`cover_medium`), which looks terrible blown up in the player — rewrite it
* to the 1000px xl the album pages use. Non-Deezer URLs pass through
* untouched. */
function hqCover(url) {
if (!url) return url;
try {
if (!new URL(url).hostname.endsWith("dzcdn.net")) return url;
} catch {
return url;
}
return url.replace(
/\/\d{2,4}x\d{2,4}((?:-[0-9a-z]+)*)\.(jpg|png|webp)$/i,
"/1000x1000$1.$2",
);
}
/** The tier gridCover asks for, chosen by device pixel ratio.
*
@@ -5236,72 +4550,6 @@ export async function saveSong(artist, title) {
return true;
}
/** Match a peer file to a catalog track, so queue items carry the tagged
* title instead of the filename.
*
* A track title contained in the filename normally identifies the track — but
* only if it's *specific* to this file. When peers embed the album name in
* every filename ("… - Eggbeater Jesus - 01 Happy Hour.flac"), and the album
* name is also a track title, that album name is a substring of every filename
* and — being long — used to out-rank each track's real, shorter title, so the
* whole album collapsed to one repeated title. So: ignore any title that
* appears in (roughly) every filename, take the longest *specific* match, and
* otherwise fall back to album order when the folder is a complete album. */
function catalogTrackFor(file, i, files, tracks) {
if (!tracks?.length) return null;
const fname = normText(file.name);
const base = (t) => normText(t.title);
const named = (t) => base(t).length >= 3 && fname.includes(base(t));
// PRIMARY: the catalog (Deezer) tracklist, in order. When the folder holds
// exactly the album's track count it's almost always the whole album in
// order, so file `i` is track `i`. That's the only reliable way to tell
// same-named variants apart — "My Name Is Jonas (2024 Remaster)",
// "(Live On BBC…)" and "(Kitchen Tape Demo)" all normalize to one base
// title, so filename matching alone can't say which belongs here (it used
// to pick the longest title, i.e. the verbose live/demo one). Only distrust
// the position if the filename clearly names a DIFFERENT song than the one
// sitting there (a reordered/mismatched folder — handled by the backup).
if (files.length === tracks.length) {
const at = tracks[i];
if (!fname || named(at) || !tracks.some(named)) return at;
}
// BACKUP: fuzzy filename→title matching for a partial/reordered folder.
// Drop any title that appears in ~every filename (that's the album name),
// then among the rest prefer the closest duration (disambiguates same-named
// variants), then the longest title.
const contained = tracks.filter(named);
const ubiquity = (t) => files.reduce((n, f) => n + (normText(f.name).includes(base(t)) ? 1 : 0), 0);
const ubiquitous = Math.max(2, Math.ceil(files.length * 0.5));
let pool = contained.filter((t) => ubiquity(t) < ubiquitous);
if (!pool.length) pool = contained;
if (pool.length) {
const dur = file.duration;
if (dur) {
const off = (t) => Math.abs((t.duration_secs ?? 1e9) - dur);
// Closest duration wins; on a tie prefer the shorter title, i.e. the
// plain studio version over a longer "(Live…)" / "(Demo…)" variant.
return pool.reduce((a, b) =>
off(b) < off(a) || (off(b) === off(a) && b.title.length < a.title.length) ? b : a,
);
}
return pool.reduce((a, b) => (b.title.length > a.title.length ? b : a));
}
return files.length === tracks.length ? tracks[i] : null;
}
/** Turn a peer filename into a readable title when no catalog track matches
* it (a genuine bonus/extra file on an expanded edition): drop the extension
* and a leading track-number prefix ("04. ", "1 - ", "07 ") so it reads as a
* title rather than "04. Dragon Ball Z…". Conservative — only strips a number
* that's clearly a track index (has a separator, or a leading zero), so a title
* like "99 Luftballons" is left intact. */
function cleanTrackName(name) {
const stem = (name ?? "").replace(/\.[^.]+$/, "");
const stripped = stem.replace(/^\s*(?:\d{1,2}\s*[.\-)]|0\d)\s+/, "").trim();
return stripped || stem;
}
/** Find the best folder for an album; stream it as a queue, failing over to
* the next-best folder when a peer never starts sending. Albums already in