Revert "feat(web): gapless audio handoff to fix desktop media-tile flicker"

This reverts commit 98d7c84269.
This commit is contained in:
Honey committed 2026-06-26 17:45:40 +02:00
1 parent 98d7c84269
commit 420c84d191
4 files changed
+48 -92

No files matched your search

+35 -44
View File
@@ -122,9 +122,6 @@ window.addEventListener('load', () => {
// Wire up audio elements from DOM
S.audio = document.getElementById('audio-element');
const _audioB = document.getElementById('audio-element-b');
// Two fixed audio elements for gapless handoff — S.audio always points at the active one.
S._audioEls = _audioB ? [S.audio, _audioB] : [S.audio];
S.previewAudio = document.getElementById('preview-audio');
const saved = localStorage.getItem('ns_cfg');
@@ -137,50 +134,44 @@ window.addEventListener('load', () => {
if(window.NS_SERVER_URL?.trim()) { const el=document.getElementById('srv-url'); if(el&&!el.value) el.value=window.NS_SERVER_URL.trim(); }
document.getElementById('srv-pass').addEventListener('keydown', e => { if(e.key==='Enter') doConnect(); });
// Listeners are bound to BOTH audio elements so a gapless handoff needs no rebinding.
// Handlers that only make sense for the playing element guard with `el !== S.audio`.
let _errRetries = 0, _errTimer = null;
function bindAudioEl(el) {
el.addEventListener('timeupdate', updateProgress);
el.addEventListener('ended', onEnded);
el.addEventListener('play', () => {
S._trackChanging = false;
absInterrupt();
if (S.previewCurrent) stopPreview(false);
setPlayIcon(true);
document.getElementById('player-art').classList.add('spinning');
if(navigator.mediaSession) navigator.mediaSession.playbackState = 'playing';
});
el.addEventListener('pause', () => {
if (el !== S.audio) return; // ignore the idle standby element during a handoff
setPlayIcon(false);
document.getElementById('player-art').classList.remove('spinning');
// Suppress during track change — src swap fires pause before the new track starts
if(!S._trackChanging && navigator.mediaSession) navigator.mediaSession.playbackState = 'paused';
});
// stalled = browser buffer ran out briefly; let the browser retry naturally.
el.addEventListener('play', () => { _errRetries = 0; clearTimeout(_errTimer); }, { capture: true });
el.addEventListener('error', () => {
if (el !== S.audio) return; // standby/preload errors must not disrupt active playback
// Skip if playCurrent() is already handling recovery (_trackChanging = true means
// we're mid-transition or waiting for canplay — don't conflict with that)
if(!S.queue[S.qIdx] || S._trackChanging) return;
_errRetries++;
const delay = Math.min(1000 * Math.pow(2, _errRetries - 1), 8000); // 1s, 2s, 4s, 8s
clearTimeout(_errTimer);
_errTimer = setTimeout(() => {
if(!S.queue[S.qIdx] || S._trackChanging) return;
S._trackChanging = true;
S.audio.load();
S.audio.play().catch(() => { S._trackChanging = false; });
}, delay);
});
}
S._audioEls.forEach(bindAudioEl);
S.audio.addEventListener('timeupdate', updateProgress);
S.audio.addEventListener('ended', onEnded);
S.audio.addEventListener('play', () => {
S._trackChanging = false;
absInterrupt();
if (S.previewCurrent) stopPreview(false);
setPlayIcon(true);
document.getElementById('player-art').classList.add('spinning');
if(navigator.mediaSession) navigator.mediaSession.playbackState = 'playing';
});
S.audio.addEventListener('pause', () => {
setPlayIcon(false);
document.getElementById('player-art').classList.remove('spinning');
// Suppress during track change — src swap fires pause before the new track starts
if(!S._trackChanging && navigator.mediaSession) navigator.mediaSession.playbackState = 'paused';
});
S.previewAudio.addEventListener('timeupdate', updatePreviewProgress);
S.previewAudio.addEventListener('ended', stopPreview);
// stalled = browser buffer ran out briefly; let the browser retry naturally.
// The watchdog below catches genuine long freezes.
let _errRetries = 0, _errTimer = null;
S.audio.addEventListener('play', () => { _errRetries = 0; clearTimeout(_errTimer); }, { capture: true });
S.audio.addEventListener('error', () => {
// Skip if playCurrent() is already handling recovery (_trackChanging = true means
// we're mid-transition or waiting for canplay — don't conflict with that)
if(!S.queue[S.qIdx] || S._trackChanging) return;
_errRetries++;
const delay = Math.min(1000 * Math.pow(2, _errRetries - 1), 8000); // 1s, 2s, 4s, 8s
clearTimeout(_errTimer);
_errTimer = setTimeout(() => {
if(!S.queue[S.qIdx] || S._trackChanging) return;
S._trackChanging = true;
S.audio.load();
S.audio.play().catch(() => { S._trackChanging = false; });
}, delay);
});
const _savedVol = parseInt(localStorage.getItem('ns_volume') ?? '', 10);
setVolume(isNaN(_savedVol) ? 55 : _savedVol);
+12 -46
View File
@@ -276,19 +276,10 @@ function _setAudioSession() {
try { if(navigator.audioSession) navigator.audioSession.type = 'playback'; } catch {}
}
// ─── PRELOAD — the standby audio element buffers the next track ──────────────
// Buffering into the *standby* element (not a throwaway) lets playCurrent() hand
// playback over to it gaplessly: the active element never empties, so the OS media
// tile doesn't flicker on skip. Falls back to a source-swap when not preloaded.
// ─── PRELOAD — shadow Audio element actually buffers the next track ──────────
let _preUrl = '';
let _preId = '';
/** The audio element that is NOT currently active (or null if there's only one). */
function _standbyEl() {
const els = S._audioEls;
if (!els || els.length < 2) return null;
return els.find(e => e !== S.audio) || null;
}
let _preAudio = null;
function _nextIdx() {
if(S.repeat === 'one') return S.qIdx;
@@ -303,12 +294,13 @@ function _preloadNext() {
if(ni < 0) return;
const next = S.queue[ni];
if(!next || _preId === next.id) return;
const standby = _standbyEl();
if(!standby) return;
_preId = next.id;
_preUrl = streamUrl(next.id);
standby.src = _preUrl; // preload="auto" → the element buffers it for a gapless handoff
try { standby.load(); } catch {}
// Real Audio preload — actually buffers the stream so canplay fires instantly
if(_preAudio) { _preAudio.src = ''; _preAudio = null; }
_preAudio = new Audio();
_preAudio.preload = 'auto';
_preAudio.src = _preUrl;
if(next.coverArt) {
[256, 512, 1024].forEach(size => {
const img = new Image();
@@ -319,8 +311,7 @@ function _preloadNext() {
function _clearPreload() {
_preId = ''; _preUrl = '';
const standby = _standbyEl();
if(standby) { try { standby.pause(); standby.removeAttribute('src'); standby.load(); } catch {} }
if(_preAudio) { _preAudio.src = ''; _preAudio = null; }
}
// ─── PLAY HISTORY (for prev-in-shuffle) ──────────────────────────────────────
@@ -406,6 +397,10 @@ export function playCurrent() {
renderQueue();
_scheduleScrobble(s.id, s.duration);
const src = (_preId === s.id && _preUrl) ? _preUrl : streamUrl(s.id);
_clearPreload();
S.audio.src = src;
const _resetFlag = () => { if (_playGen === gen) S._trackChanging = false; };
const _applySession = () => {
@@ -414,35 +409,6 @@ export function playCurrent() {
setTimeout(_preloadNext, 2000);
};
// ── Gapless handoff: if the standby element already buffered THIS track, switch
// playback to it instead of reloading the source. The active element never empties,
// so the OS media tile stays put (and the skip is instant). ──
const standby = _standbyEl();
if (standby && _preId === s.id && standby.readyState >= 2) {
const old = S.audio;
standby.currentTime = 0;
standby.volume = old.volume; standby.muted = old.muted; standby.playbackRate = old.playbackRate || 1;
S.audio = standby; // the active element is now the preloaded one
_preId = ''; _preUrl = '';
try { old.pause(); } catch {} // 'pause' is ignored for the now-inactive element
_setAudioSession();
S.audio.play()
.then(() => { S._trackChanging = false; _applySession(); })
.catch(() => {
// Handoff playback failed — recover with a fresh source load on this element.
if (_playGen !== gen) return;
S.audio.src = streamUrl(s.id);
try { S.audio.load(); } catch {}
S.audio.play().then(() => { S._trackChanging = false; _applySession(); }).catch(_resetFlag);
});
return;
}
// ── Fallback: classic source swap on the current element (unchanged) ──
const src = (_preId === s.id && _preUrl) ? _preUrl : streamUrl(s.id);
_clearPreload();
S.audio.src = src;
let _guardTimer = null;
let _canplayFn = null;