aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
diff options
context:
space:
mode:
authorChristophe Besson <cbesson@gmail.com>2026-08-26 14:43:16 +0200
committerChristophe Besson <cbesson@gmail.com>2026-08-26 14:43:16 +0200
commit59d9f50bf41b2b38b7c95f8da52b698dff923c2d (patch)
tree14b308686860eea0a9c12c47c39f8a68a1bba376 /packages/meshbay-hub/src/meshbay_hub/static/music-player.js
parenta31b26df45860af16061fb43ccc3443381ed3df2 (diff)
downloadmeshbay-59d9f50bf41b2b38b7c95f8da52b698dff923c2d.tar.gz
feat(music): network-adaptive prefetch depth, opt-in keep-screen-on toggle
Prefetch depth (music-player.js): 5 tracks ahead on Wi-Fi, 3 on cellular — more runway through a screen-lock network gap when the connection is cheap and fast, less when it's metered. navigator.connection is Chromium-only; Firefox/Safari (where it's undefined) get the same conservative tier as an unrecognized connection type, never assumed fast. MAX_CACHED_BLOBS raised to 6 to hold the largest case (current + 5). Keep-screen-on-during-audio (new user preference, off by default): a Settings toggle, backed by a new whitelisted key on /v1/users/me/preferences (music_keep_screen_on). music-player.js holds a Screen Wake Lock only while a track is playing and only when the user has opted in — unlike the video player's unconditional lock, this must not fight the ordinary expectation (matching Spotify/Deezer) that the phone locks on its own while listening.
Diffstat (limited to 'packages/meshbay-hub/src/meshbay_hub/static/music-player.js')
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/music-player.js91
1 files changed, 78 insertions, 13 deletions
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/music-player.js b/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
index 7fdc74e..ffe092d 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
@@ -65,10 +65,36 @@ function shuffledOrder(n, keepFirst) {
return order;
}
-// Bounded: only the currently playing track plus a one-track read-ahead are
+// Bounded: only the currently playing track plus the read-ahead window are
// ever worth holding in memory. Older blob URLs are revoked, not merely
// dropped — otherwise every track played in a session leaks its object URL.
-const MAX_CACHED_BLOBS = 3;
+// Sized for the largest read-ahead prefetchDepth() can return (currently
+// playing + 5 on Wi-Fi) — a smaller run on cellular just evicts sooner.
+const MAX_CACHED_BLOBS = 6;
+
+/**
+ * How many tracks to warm the cache for, ahead of the one playing.
+ *
+ * A prefetched track needs no live connection to play — it is exactly what
+ * buys time through a screen-lock network gap (see transport.js's
+ * auto-reconnect) — so the more of a mobile-data budget it is safe to spend
+ * on tracks that might not even get listened to, the better the odds a lock
+ * of ordinary length is fully covered by tracks already sitting in
+ * blobCacheRef. Wi-Fi is effectively free and usually fast, so 5; a metered
+ * connection (or one this API cannot see at all) gets 3 — enough to matter,
+ * not so much it burns a noticeable chunk of a data plan on an album that
+ * might get abandoned after track one.
+ *
+ * `navigator.connection` is Chromium-only (Chrome, Edge, Electron) — plain
+ * `undefined` on Firefox and Safari, where this must fall through to the
+ * conservative tier exactly as it would for a cellular connection it could
+ * name. Never assume "fast" from the absence of a signal that says so.
+ */
+function prefetchDepth() {
+ const conn = navigator.connection;
+ if (conn && conn.type === 'wifi') return 5;
+ return 3;
+}
function loadVolume() {
try {
@@ -151,7 +177,7 @@ function QueuePanel({ tracks, order, pos, onSelect, onClose }) {
`;
}
-function MusicPlayerBar({ transportRef, gekRef, queue, onClose }) {
+function MusicPlayerBar({ transportRef, gekRef, queue, onClose, userPrefs }) {
const audioRef = useRef(null);
const blobCacheRef = useRef(new Map()); // file id -> { url, order: insertion index }
const blobInsertRef = useRef(0);
@@ -201,6 +227,47 @@ function MusicPlayerBar({ transportRef, gekRef, queue, onClose }) {
for (const { url } of blobCacheRef.current.values()) URL.revokeObjectURL(url);
}, []);
+ // Screen Wake Lock, opt-in only (Settings → music_keep_screen_on) and only
+ // while a track is actually playing — off by default because the ordinary
+ // expectation, matching Spotify/Deezer, is that the phone locks on its own
+ // idle timer while listening (docs/musicbay.md §2.2). Unlike the video
+ // player's unconditional lock, this must not fight that default for
+ // everyone who never asked for it; it exists for whoever explicitly wants
+ // to trade battery for riding out the WebRTC screen-lock reconnect gap
+ // without waiting on it at all.
+ useEffect(() => {
+ if (!playing) return;
+ if (!(userPrefs && userPrefs.music_keep_screen_on === 'true')) return;
+ if (!('wakeLock' in navigator)) return;
+ let sentinel = null;
+ let cancelled = false;
+ const acquire = async () => {
+ try {
+ const wl = await navigator.wakeLock.request('screen');
+ if (cancelled) { try { wl.release(); } catch { /* ignore */ } return; }
+ sentinel = wl;
+ wl.addEventListener('release', () => { sentinel = null; });
+ } catch (e) {
+ // Battery saver, no permission, an insecure context — playback has
+ // never depended on this, so there is nothing to fall back to.
+ console.warn('[MeshBay] Wake lock request failed:', e.message);
+ }
+ };
+ acquire();
+ // Released automatically the moment the page goes hidden (spec
+ // behaviour) — re-requested here so it holds again once foregrounded,
+ // same as the video player's handling of the same event.
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible' && !sentinel) acquire();
+ };
+ document.addEventListener('visibilitychange', onVisibility);
+ return () => {
+ cancelled = true;
+ document.removeEventListener('visibilitychange', onVisibility);
+ if (sentinel) { try { sentinel.release(); } catch { /* already released */ } }
+ };
+ }, [playing, userPrefs && userPrefs.music_keep_screen_on]);
+
const evictOldBlobs = useCallback(() => {
const cache = blobCacheRef.current;
while (cache.size > MAX_CACHED_BLOBS) {
@@ -258,18 +325,16 @@ function MusicPlayerBar({ transportRef, gekRef, queue, onClose }) {
// Silently warms the cache for the next tracks so pressing "next" doesn't
// visibly wait (musicbay.md §2.2) — best-effort, never surfaces an error.
//
- // Two ahead, not one: a screen lock can cost the transport several minutes
- // (see the WebRTC auto-reconnect in transport.js — this is the other half
- // of the same fix). A track already sitting in blobCacheRef needs no
+ // More than one: a screen lock can cost the transport several minutes (see
+ // the WebRTC auto-reconnect in transport.js — this is the other half of
+ // the same fix). A track already sitting in blobCacheRef needs no
// connection at all to play, so whatever got fetched *before* the lock
- // started plays through it regardless of what the connection is doing —
- // it just buys more of that runway than fetching only one track ahead did.
- // MAX_CACHED_BLOBS is sized for exactly this: the one playing plus these two.
- const PREFETCH_AHEAD = 2;
-
+ // started plays through it regardless of what the connection is doing
+ // afterward — see prefetchDepth() for how far ahead that runway goes.
const prefetchNext = useCallback((fromPos) => {
- for (let ahead = 1; ahead <= PREFETCH_AHEAD; ahead++) {
- const nextEntry = tracks[order[fromPos + ahead]];
+ const ahead = prefetchDepth();
+ for (let i = 1; i <= ahead; i++) {
+ const nextEntry = tracks[order[fromPos + i]];
if (!nextEntry || blobCacheRef.current.has(nextEntry.id)) continue;
fetchTrackBlob(nextEntry).catch(() => {});
}