diff --git a/plugin.json b/plugin.json index cd1478c..3e84166 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "stem_mixer", "name": "Stem Mixer", - "version": "1.4.0", + "version": "1.4.1", "private": false, "nav": { "label": "Stem Mixer", diff --git a/screen.js b/screen.js index 6e07f9e..8d829ca 100644 --- a/screen.js +++ b/screen.js @@ -106,6 +106,15 @@ // only — levels, aliases and persistence all stay keyed by id. let stemMeta = Object.create(null); let onStemsStateEvent = null; + // Write-behind persistence for slider drags. localStorage is synchronous + // main-thread work, and the old per-`input`-tick save chain (our state + // write + the stems plugin's saveVolume/saveMuted + owner-status + // snapshots) starved the highway's requestAnimationFrame loop and + // stuttered playback. Drags stage their state here and flush once, + // shortly after the last tick. + let pendingState = null; + let pendingDragLevels = Object.create(null); + let pendingFlushTimer = null; function invalidateAudioCaches() { stemAudioMapCache = null; @@ -176,13 +185,67 @@ } function saveState(state) { + // A direct save supersedes the drag write-behind. Callers either + // build `state` from getCurrentState() (staged values folded in) or + // pass a deliberate wholesale replacement (applyProfile) — in both + // cases this write is the newer truth, so drop the staging: a later + // flush must not overwrite it with older data. The staged stems-API + // application still runs — those levels were audible, and the stems + // plugin's own per-song persistence isn't covered by our store. + if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; } + pendingState = null; + applyPendingDragLevels(); + const sanitized = sanitizeState(state); try { - localStorage.setItem(STATE_KEY, JSON.stringify(sanitizeState(state))); + localStorage.setItem(STATE_KEY, JSON.stringify(sanitized)); } catch (_) { - // Ignore storage errors (private mode, quota, etc). + // Storage failed (private mode, quota, etc). Keep this state as + // the in-memory truth: getCurrentState() readers must not fall + // back to the stale stored copy, or a UI sweep would snap live + // values back for the rest of the session. Any later save either + // carries this forward (getCurrentState-based callers) or + // replaces it on purpose — both retry the write. + pendingState = sanitized; } } + // Apply staged drag levels through the FULL stems API — the per-song + // persistence, button-UI updates and owner-status snapshot that + // previewStemVolume() deliberately skips on every `input` tick. + function applyPendingDragLevels() { + const staged = pendingDragLevels; + pendingDragLevels = Object.create(null); + Object.keys(staged).forEach((stem) => { + try { + setStemVolumeViaStemsApi(stem, staged[stem]); + } catch (e) { + // The stems plugin can throw mid-rebuild (stemsReachable() + // expects the same). Don't let one stem abort the caller's + // save or drop the rest — re-stage it (unless a newer level + // arrived meanwhile) so the next flush/save retries. The + // audible gain already landed via previewStemVolume(). + if (!(stem in pendingDragLevels)) pendingDragLevels[stem] = staged[stem]; + } + }); + } + + function flushPending() { + if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; } + applyPendingDragLevels(); + if (!pendingState) return; + const state = pendingState; + pendingState = null; + saveState(state); + } + + function schedulePendingFlush() { + // Trailing debounce: one flush shortly after the last slider tick. + // 250 ms is long enough that a continuous drag never flushes mid-drag + // and short enough that the final value lands effectively instantly. + if (pendingFlushTimer) clearTimeout(pendingFlushTimer); + pendingFlushTimer = setTimeout(flushPending, 250); + } + function loadProfiles() { try { const raw = localStorage.getItem(PROFILES_KEY); @@ -209,7 +272,15 @@ } function getCurrentState() { - return sanitizeState(loadState()); + // While a drag's write-behind save is pending, the staged state — not + // localStorage — is the truth. Every reader (applyStoredState's + // re-push, profile capture, autolevel) must see it, or a mid-drag UI + // sweep would read the stale stored level and snap the volume back. + // The sanitize here doubles as a CLONE: callers mutate the returned + // state, and none of that may alias into pendingState. loadState() + // already returns a fresh sanitized object, so no second pass there. + if (pendingState) return sanitizeState(pendingState); + return loadState(); } function isStemsPluginActive() { @@ -559,10 +630,71 @@ appliedLevels[canonical] = clamped; if (!skipSave) { - const state = getCurrentState(); - state.levels[canonical] = clamped; - saveState(state); + if (!pendingState) pendingState = getCurrentState(); + pendingState.levels[canonical] = clamped; + schedulePendingFlush(); + } + } + + // Per-tick path for slider drags. `input` fires at pointer-move rate, so + // this does only the work that must track the pointer: the audible gain + // and the staged state. Everything heavy — our localStorage write, the + // stems plugin's saveVolume/saveMuted/button updates/owner-status + // snapshots — waits for flushPending(). Deliberately does NOT write + // item.vol: the flush's stems.setVolume() only persists when it sees the + // value change from the one it last saved. + function previewStemVolume(stem, level) { + const clamped = Math.max(0, Math.min(1, Number(level) || 0)); + const canonical = canonicalStemId(stem); + if (!window.stems) { + const map = getStemAudioMap(); + if (map[canonical]) { + map[canonical].volume = clamped; + map[canonical].muted = false; + } + ensureStemNodes(); + if (stemNodes[canonical]) { + stemNodes[canonical].gain.value = clamped; + } + } else { + // stemState is the live internal array (no allocation, unlike + // getState()); the API docs bless writing gain.gain.value + // directly as the caller-side fast path. + const raw = Array.isArray(window.stems.stemState) + ? window.stems.stemState + : (typeof window.stems.getState === 'function' ? window.stems.getState() : null); + const applyItem = (item, fallbackId) => { + if (!item || typeof item !== 'object') return; + if (canonicalStemId(item.id != null ? item.id : fallbackId) !== canonical) return; + if (item.gain && item.gain.gain) item.gain.gain.value = clamped; + if ('on' in item) item.on = true; + if (item.audio) item.audio.muted = false; + }; + // Array (newer) or keyed object (older) — the same two getState() + // shapes stemsReachable() accepts. Without the object arm, a host + // whose only surface is object-form getState() would hear nothing + // until the flush. + if (Array.isArray(raw)) { + raw.forEach((item) => applyItem(item, null)); + } else if (raw && typeof raw === 'object') { + Object.keys(raw).forEach((key) => applyItem(raw[key], key)); + } + } + + const bridged = stemsBridgeByStem[canonical]; + if (bridged) { + if (bridged.gain && bridged.gain.gain) bridged.gain.gain.value = clamped; + if (bridged.audio) { + bridged.audio.muted = false; + bridged.audio.volume = 1; + } } + + appliedLevels[canonical] = clamped; + if (!pendingState) pendingState = getCurrentState(); + pendingState.levels[canonical] = clamped; + pendingDragLevels[canonical] = clamped; + schedulePendingFlush(); } function clearStemBootstrapTimers() { @@ -695,7 +827,6 @@ const clamped = Math.max(-12, Math.min(12, Number(value) || 0)); const state = getCurrentState(); state.eq[index] = clamped; - saveState(state); ensureAudioContext(); applyEqToGraph(state.eq); @@ -709,6 +840,12 @@ } if (skipSave) return; + // Write-behind, same as the volume path — EQ `input` fires just as + // fast as the stem sliders. (The save used to run unconditionally + // above this guard, so skipSave never actually skipped it.) + if (!pendingState) pendingState = state; + pendingState.eq[index] = clamped; + schedulePendingFlush(); } function updateAutolevelButtonState(enabled) { @@ -1000,7 +1137,7 @@ input.addEventListener('input', () => { const level = parseInt(input.value, 10) / 100; pct.textContent = `${input.value}%`; - setStemVolume(stem, level); + previewStemVolume(stem, level); }); input._pctTag = pct; (registry || stemInputs)[stem] = input; @@ -1675,7 +1812,7 @@ module.exports = { STEM_KEYS, EQ_BANDS, DEFAULT_STATE, STEM_ALIASES, sanitizeState, cloneState, canonicalStemId, safeDecodeUrl, stemIdFromUrl, - loadState, saveState, loadProfiles, saveProfiles, + loadState, saveState, getCurrentState, loadProfiles, saveProfiles, normalizeAvailableStems, levelFor, extractStemMeta, stemDisplayName, sameStemSet, STEM_LABELS, }; @@ -1697,6 +1834,9 @@ else if (Number(d.stemCount) === 0) setAvailableStems([]); }; window.addEventListener('stems:state', onStemsStateEvent); + // A drag's write-behind save is only ~250 ms behind, but a close/refresh + // inside that window must not lose the final slider value. + window.addEventListener('pagehide', flushPending); const originalPlaySong = window.playSong; if (typeof originalPlaySong === 'function') { @@ -1767,6 +1907,10 @@ onStemsStateEvent = null; } try { clearStemBootstrapTimers(); } catch (e) { /* ignore */ } + // Land any staged drag state before this instance dies — the + // replacement instance reads localStorage on boot. + try { flushPending(); } catch (e) { /* ignore */ } + try { window.removeEventListener('pagehide', flushPending); } catch (e) { /* ignore */ } clearTimeout(uiUpdateTimer); if (autolevelTimer) { clearInterval(autolevelTimer); autolevelTimer = null; } diff --git a/tests/state.test.js b/tests/state.test.js index feb0456..35203ee 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -265,3 +265,34 @@ test('loadProfiles tolerates corrupt storage and non-object payloads', () => { global.localStorage.setItem('stem_mixer:profiles', '"a string"'); assert.deepEqual(loadProfiles(), {}); }); + +test('saveState keeps in-memory truth when the storage write fails', () => { + const { saveState, getCurrentState } = freshPlugin(); + // Seed a persisted baseline. + saveState({ levels: { vocals: 0.2 } }); + assert.equal(getCurrentState().levels.vocals, 0.2); + + // Break the store the way quota/private mode does. finally-restore so a + // failing assertion can't leave the broken setItem behind (freshPlugin() + // would rebuild localStorage anyway, but keep the teardown airtight). + const originalSetItem = global.localStorage.setItem; + try { + global.localStorage.setItem = () => { throw new Error('quota'); }; + saveState({ levels: { vocals: 0.9 } }); + // Reads must see the failed write, not regress to the stale stored + // 0.2 — otherwise a UI sweep would snap the live value back + // mid-session. + assert.equal(getCurrentState().levels.vocals, 0.9); + } finally { + global.localStorage.setItem = originalSetItem; + } + + // Once storage recovers, the next save (built from getCurrentState, as + // every caller does) lands the in-memory truth on disk. + const next = getCurrentState(); + next.levels.bass = 0.5; + saveState(next); + assert.equal(getCurrentState().levels.vocals, 0.9); + assert.equal(getCurrentState().levels.bass, 0.5); + assert.equal(JSON.parse(global.localStorage.getItem('stem_mixer:state')).levels.vocals, 0.9); +});