14 Commits

Author SHA1 Message Date
Jonathan Sykes
7f49c317fd Merge retry hardening with DSP cache opt-in 2026-10-10 23:00:32 +08:00
Jonathan Sykes
f0daeaedd2 Fix responsive DSP settings controls 2026-10-10 22:50:02 +08:00
Jonathan Sykes
0c387a01cd Record DSP integration verification and optional cache results 2026-10-10 19:42:14 +08:00
Jonathan Sykes
e0802aa8a8 Wait for DSP opt-in persistence in settings harness 2026-10-10 19:32:12 +08:00
Jonathan Sykes
865c60cb85 Fix offline opt-in persistence assertion 2026-10-10 19:29:31 +08:00
Jonathan Sykes
ef12468a99 Extend JamesDSP with convolution and spatial audio 2026-10-10 19:25:06 +08:00
Jonathan Sykes
b3f0525a8e Stage legacy asset migration before activation 2026-10-10 18:40:32 +08:00
Jonathan Sykes
d02796b0eb Retry transient foreground requests before surfacing errors 2026-10-09 21:53:03 +08:00
Jonathan Sykes
7591c2d14c Record JamesDSP integration verification results 2026-10-09 21:08:58 +08:00
Jonathan Sykes
6bb3271431 Add JamesDSP playback controls and verification harness 2026-10-09 20:29:37 +08:00
Jonathan Sykes
27b32ff0c9 Add the guarded JamesDSP audio controller 2026-10-09 20:00:49 +08:00
Jonathan Sykes
aca50c1690 Vendor JamesDSP in a lazy asset group 2026-10-09 19:52:17 +08:00
Jonathan Sykes
76037613a7 Extract the shared realtime audio graph owner 2026-10-09 19:46:00 +08:00
Jonathan Sykes
d6a3570ff9 Document JamesDSP audio ownership audit 2026-10-09 19:42:11 +08:00
79 changed files with 30823 additions and 197 deletions

View File

@@ -321,7 +321,7 @@
<!-- ============ sign-in ============ -->
<div id="loginBox" class="gate hidden">
<a class="brand" href="/admin#editor" data-home style="text-decoration:none;color:inherit"><i><svg viewBox="0 0 24 24"><path d="M9 18V6l10-2v12"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="16.5" cy="16" r="2.5"/></svg></i>Lyrics Studio</a>
<div class="brand"><i><svg viewBox="0 0 24 24"><path d="M9 18V6l10-2v12"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="16.5" cy="16" r="2.5"/></svg></i>Lyrics Studio</div>
<div class="card">
<h2>Sign in</h2>
<p class="muted">Admin password</p>
@@ -340,7 +340,7 @@
<div id="app" class="hidden">
<header class="top">
<a class="brand" href="/admin#editor" data-home style="text-decoration:none;color:inherit"><i><svg viewBox="0 0 24 24"><path d="M9 18V6l10-2v12"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="16.5" cy="16" r="2.5"/></svg></i>Lyrics Studio</a>
<div class="brand"><i><svg viewBox="0 0 24 24"><path d="M9 18V6l10-2v12"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="16.5" cy="16" r="2.5"/></svg></i>Lyrics Studio</div>
<nav class="tabs" role="tablist" id="tabsTop"></nav>
<span class="grow"></span>
<a class="ghost desk" href="/">← Back to app</a>
@@ -572,7 +572,6 @@
<nav class="nav" id="tabsBottom" role="tablist"></nav>
</div>
<script src="opfs.js"></script>
<script src="download-actions.js"></script>
<script src="lyrics-core.js"></script>
<script>
@@ -1166,82 +1165,20 @@
}
}
/* The editor plays a COMPLETE local copy, never a live stream (a stream can
stall or expire mid-song). Order: the same saved video the player uses
(OPFS) → an audio-only copy kept for admin use (Cache Storage) → fetch the
audio-only file from the server once and keep it. */
const ADMIN_AUDIO_CACHE = 'ytp-admin-audio';
async function adminAudioBlobUrl(id, streams, onProgress) {
try {
if (window.OPFS && OPFS.isSupported() && await OPFS.hasVideo(id)) {
const u = await OPFS.getFileUrl(id);
if (u) return u;
}
} catch { /* fall through */ }
const key = `/admin-audio/${encodeURIComponent(id)}`;
let cache = null;
try { cache = await caches.open(ADMIN_AUDIO_CACHE); } catch { /* no Cache Storage */ }
if (cache) {
const hit = await cache.match(key).catch(() => null);
if (hit) return URL.createObjectURL(await hit.blob());
}
const d = (streams && streams.data) || {};
const sources = [`/api/media/${encodeURIComponent(id)}?a=1`,
d.audioUrl || ((d.qualities || []).find((q) => q.hasAudio) || {}).url || ''].filter(Boolean);
for (const src of sources) {
for (let attempt = 0; attempt < 2; attempt++) {
try {
const r = await fetch(src, { credentials: 'same-origin' });
if (!r.ok) break;
const total = Number(r.headers.get('content-length')) || 0;
const reader = r.body.getReader(); const parts = []; let got = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
parts.push(value); got += value.length;
if (onProgress) onProgress(got, total);
}
if (total && got < total) throw new Error('short read');
const blob = new Blob(parts, { type: r.headers.get('content-type') || 'audio/mp4' });
if (blob.size < 1024) break;
if (cache) await cache.put(key, new Response(blob, { headers: { 'content-type': blob.type } })).catch(() => {});
return URL.createObjectURL(blob);
} catch { await new Promise((ok) => setTimeout(ok, 800)); }
}
}
return '';
}
// Audio status shares the #msg line with other messages: only write when it
// is empty or still showing our own text, and never clobber someone else's.
function audioSay(text, cls) {
const el = $('msg'), cur = el.textContent;
if (cur && cur !== LE.audioMsg) return;
LE.audioMsg = text; say(text, cls);
}
async function initAudio(id, streams) {
function initAudio(id, streams) {
const url = (streams.data && streams.data.audioUrl) || ((streams.data && streams.data.qualities || []).find((q) => q.hasAudio) || {}).url || '';
if (LE.audio) { LE.audio.pause(); LE.audio.src = ''; }
if (LE.audioUrl) { try { URL.revokeObjectURL(LE.audioUrl); } catch {} LE.audioUrl = ''; }
LE.audio = null;
const token = (LE.audioToken = (LE.audioToken || 0) + 1);
audioSay('Loading the full audio into the browser…');
const url = await adminAudioBlobUrl(id, streams, (got, total) => {
if (token === LE.audioToken) audioSay(total ? `Loading audio… ${Math.round(got / total * 100)}%` : `Loading audio… ${(got / 1048576).toFixed(1)} MB`);
});
if (token !== LE.audioToken || LE.id !== id) { if (url) try { URL.revokeObjectURL(url); } catch {} return; }
audioSay('');
if (url) {
LE.audioUrl = url;
const a = new Audio(url); a.preload = 'auto';
a.addEventListener('timeupdate', tick); a.addEventListener('seeked', tick);
a.addEventListener('loadedmetadata', () => { if (a.duration) { LE.dur = a.duration; $('dur').textContent = fmtT(a.duration).slice(0, -3); } draw(); });
a.addEventListener('play', () => { TransportIcons.set($('bPlay'),'pause'); });
a.addEventListener('pause', () => { TransportIcons.set($('bPlay'),'play'); });
a.addEventListener('error', () => audioSay('The saved audio could not be played — reload the song to fetch it again.', 'err'));
a.addEventListener('error', () => say('No playable audio for this song on the server — you can still edit the text.', 'err'));
a.playbackRate = Number($('rate').value);
LE.audio = a;
} else audioSay('No audio could be saved for this song, so there is nothing to time against.', 'err');
} else say('This song is not cached on the server, so there is no audio to time against.', 'err');
$('dur').textContent = fmtT(LE.dur).slice(0, -3);
LE.peaks = null;
fetch(`/api/media/${id}/peaks`, { credentials: 'same-origin' }).then((r) => r.json())
@@ -1358,9 +1295,7 @@
}
function seek(t) { if (!LE.audio) return; LE.audio.currentTime = Math.max(0, Math.min(LE.dur || 1e9, t)); tick(); }
function stamp(i) {
if (i < 0 || i >= LE.lines.length) return;
if (!LE.audio) { say('The audio is still loading — try again in a moment.', 'err'); return; }
if (LE.sel !== i) select(i);
if (!LE.audio || i < 0 || i >= LE.lines.length) return;
edit(() => { LE.lines[i].t = r2(cur()); });
paintRow(i); progress(); lastIdx = -2; tick(); tapLabel();
}
@@ -1369,7 +1304,7 @@
$('lines').addEventListener('click', async (e) => {
const row = e.target.closest('.ln'); if (!row) return;
const i = Number(row.dataset.i);
if (LE.sel !== i || !row.classList.contains('sel')) select(i);
if (LE.sel !== i) select(i);
const btn = e.target.closest('button[data-act]'); if (!btn) return;
const act = btn.dataset.act;
if (act === 'chip') {
@@ -1422,13 +1357,6 @@
$('bUndo').addEventListener('click', doUndo);
$('bRedo').addEventListener('click', doRedo);
$('bTools').addEventListener('click', () => { const on = $('drawer').classList.toggle('hidden') === false; $('bTools').setAttribute('aria-pressed', String(on)); });
document.querySelectorAll('[data-home]').forEach((a) => a.addEventListener('click', (e) => {
e.preventDefault();
if (!$('app').classList.contains('hidden')) {
if (LE.loaded && !$('studio').classList.contains('hidden')) $('closeSong').click();
showTab('editor');
} else location.href = '/admin#editor';
}));
$('closeSong').addEventListener('click', () => {
if (LE.dirty && !confirm('Discard the unsaved changes to this song?')) return;
if (LE.audio) { LE.audio.pause(); LE.audio = null; }

View File

@@ -21,8 +21,7 @@ test('Phase 4 preserves the exact playback, continuity, tracking and queue bodie
{const start=app.indexOf("function startSleepTimer(minutes, { endOfSong = false } = {}) {");assert.ok(start>=0,"startSleepTimer");const body=app.slice(start,start+487);assert.equal(createHash('sha256').update(body).digest('hex'),"f0a93401ab90196096074cb607b28d52c5903e11dbdfb8ddb95114e143af2409","startSleepTimer body unchanged");}
{const start=app.indexOf("function cancelSleepTimer() {");assert.ok(start>=0,"cancelSleepTimer");const body=app.slice(start,start+253);assert.equal(createHash('sha256').update(body).digest('hex'),"cf396ab758a70eede6af7444539a82ca15af801a9a57024dd5542067e9fa771a","cancelSleepTimer body unchanged");}
{const start=app.indexOf("function finishSleep() {");assert.ok(start>=0,"finishSleep");const body=app.slice(start,start+662);assert.equal(createHash('sha256').update(body).digest('hex'),"7ee93bf760bad5f39f4644339963918c5b369b2acc554b8e561c1a1f070ac6fb","finishSleep body unchanged");}
{const start=app.indexOf("const EQ = (() => {");assert.ok(start>=0,"EQ");const body=app.slice(start,start+7917);assert.equal(createHash('sha256').update(body).digest('hex'),"f0cba011c94f33e6fd0ab778021f4c97238262dfa0a8dd40bf3f17149c227528","EQ body unchanged");}
{const start=app.indexOf("const EqRender = (() => {");assert.ok(start>=0,"EqRender");const body=app.slice(start,start+5912);assert.equal(createHash('sha256').update(body).digest('hex'),"f014dd41dafebc33f09e87be866074afd7a2443c5bb452103a435585353a828f","EqRender body unchanged");}
{const start=app.indexOf("const EqRender = (() => {");assert.ok(start>=0,"EqRender");const body=app.slice(start,start+5960);assert.match(body,/EQ\.isIOS\(\) && WEB && !data\.settings\?\.jamesDsp\?\.enabled/);const standardBody=body.replace(' && !data.settings?.jamesDsp?.enabled','').slice(0,5912);assert.equal(createHash('sha256').update(standardBody).digest('hex'),"f014dd41dafebc33f09e87be866074afd7a2443c5bb452103a435585353a828f","Standard EqRender body unchanged");}
{const start=app.indexOf("const Level = (() => {");assert.ok(start>=0,"Level");const body=app.slice(start,start+3892);assert.equal(createHash('sha256').update(body).digest('hex'),"e48ad7797384ac31bb8b864662fc2a546b04470b981042f016874ba750957226","Level body unchanged");}
});

View File

@@ -60,12 +60,14 @@ async function call(zeroName, tauriName, payload = {}) {
// Generic fetch wrapper — returns parsed JSON or throws with a human message.
async function webFetch(path, opts = {}) {
if ((opts.method || 'GET').toUpperCase() === 'GET' && window.AsyncGuard?.getJson)
return AsyncGuard.getJson(path, opts, {
// Some upstream failures are represented by HTTP 200 + {ok:false}; do
// not expose those transient responses as a manual Retry state either.
retryResult: value => value?.ok === false && /\b(?:408|425|429|5\d\d)\b|temporar|timed?\s*out|network|connection|upstream|unavailable|available right now/i.test(String(value.error || value.message || '')),
});
const res = await fetch(path, opts);
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const j = await res.json(); msg = j.error || msg; } catch { /* non-JSON */ }
throw new Error(msg);
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
@@ -573,7 +575,7 @@ const API = {
? webFetch(`/api/search?q=${encodeURIComponent(query)}${refresh ? '&refresh=1' : ''}`)
: call('yt.search', 'yt_search', { query }),
related: (meta, { refresh = false } = {}) => WEB && /^[\w-]{11}$/.test(meta.id)
? fetch(`/api/related?${new URLSearchParams({ videoId: meta.id, title: meta.title || '', channel: meta.channel || meta.artist || '', ...(refresh ? { refresh: '1' } : {}) })}`).then(response => response.json())
? webFetch(`/api/related?${new URLSearchParams({ videoId: meta.id, title: meta.title || '', channel: meta.channel || meta.artist || '', ...(refresh ? { refresh: '1' } : {}) })}`)
: API.search(meta.title || meta.channel, { refresh }),
// Videos the server already knows — answers fast while the real search loads.
searchLocal: (query) => WEB
@@ -655,7 +657,6 @@ const DEFAULT_SETTINGS = {
quality: 'auto', volume: 1, audioOnly: false, autoPreload: true,
p2pShare: true, // P2P (docs/p2p-architecture.md): share my saved videos with other devices — ON by default
p2pReceive: true, // fetch from other devices when YouTube and the server can't — ON by default
autoSavePlayed: true, // keep every video you play for offline (background save once playback starts)
saveBeforePlay: false, // download (server-muxed single file) before playing instead of streaming
repeatMode: 'off', // 'off' | 'all' — repeat the playing list when it ends
loopOne: false, // repeat the single current video
@@ -664,6 +665,7 @@ const DEFAULT_SETTINGS = {
fontScale: 'normal', // 'small' | 'normal' | 'large' | 'xl'
levelVolume: null, // loudness levelling; null = on (on iPhone: applied to saved songs' rendered copies)
liveAudioIOS: false, // iPhone: live Web Audio EQ/levelling for streamed songs (stops when the screen locks)
jamesDsp: { enabled: false, downloadForOffline: false, preset: 'flat', params: {}, irRef: null },
parallelSaves: 4, // offline saves running at once (Settings → Offline cache)
density: 'comfortable', // 'comfortable' | 'compact'
perfMode: false, // disable heavy visual effects for speed
@@ -673,7 +675,24 @@ const DEFAULT_SETTINGS = {
autoBackupIntervalDays: 7,
serviceVideo: false, // show the video panel inside service mode (lyric videos)
};
let data = { playlists: [], history: [], queue: [], customVideos: [], pinnedPlaylists: [], settings: { ...DEFAULT_SETTINGS }, resumePositions: {}, rememberPos: {}, playCount: {}, abMarkers: {}, bookmarks: {}, lyricOffsets: {}, stats: null, lastAutoBackup: 0, profile: null };
function normalizeJamesDspSettings(settings) {
const saved = settings?.jamesDsp && typeof settings.jamesDsp === 'object' ? settings.jamesDsp : {};
const params = saved.params && typeof saved.params === 'object' && !Array.isArray(saved.params) ? { ...saved.params } : {};
// Impulse-response PCM is intentionally session-only; do not re-enable the
// convolver on a later boot without its uploaded audio buffer.
const irRef = saved.irRef && typeof saved.irRef.name === 'string' && typeof saved.irRef.hash === 'string'
? { name: saved.irRef.name, hash: saved.irRef.hash } : null;
if (!irRef) delete params['convolver.enabled'];
settings.jamesDsp = {
enabled: saved.enabled === true,
downloadForOffline: saved.downloadForOffline === true,
preset: typeof saved.preset === 'string' ? saved.preset : 'flat',
params,
irRef,
};
return settings;
}
let data = { playlists: [], history: [], queue: [], customVideos: [], pinnedPlaylists: [], settings: normalizeJamesDspSettings({ ...DEFAULT_SETTINGS }), resumePositions: {}, rememberPos: {}, playCount: {}, abMarkers: {}, bookmarks: {}, lyricOffsets: {}, stats: null, lastAutoBackup: 0, profile: null };
let view = { type: 'search' }; // 'search'|'history'|'playlist'|'settings'|'queue'|'saved'|'downloads'|'channel'
let searchResults = [];
// Distinguishes "never searched" (hide the list pane, show the landing) from
@@ -696,6 +715,8 @@ const IS_IOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platfo
let _currentEqUrl = null;
async function useEqRender(id) {
if (_currentEqUrl) { URL.revokeObjectURL(_currentEqUrl); _currentEqUrl = null; }
// JamesDSP is a live insert: never layer it over the Standard renderer copy.
if (data.settings?.jamesDsp?.enabled) return null;
if (typeof EqRender === 'undefined' || !WEB) return null;
try { _currentEqUrl = await EqRender.urlFor(id); } catch { _currentEqUrl = null; }
return _currentEqUrl;
@@ -906,7 +927,7 @@ function applyProfileData(name, payload, updatedAt) {
if (payload.bookmarks && typeof payload.bookmarks === 'object') data.bookmarks = payload.bookmarks;
if (payload.lyricOffsets && typeof payload.lyricOffsets === 'object') data.lyricOffsets = payload.lyricOffsets;
if (payload.stats && typeof payload.stats === 'object') data.stats = payload.stats;
if (payload.settings && typeof payload.settings === 'object') data.settings = { ...DEFAULT_SETTINGS, ...payload.settings };
if (payload.settings && typeof payload.settings === 'object') data.settings = normalizeJamesDspSettings({ ...DEFAULT_SETTINGS, ...payload.settings });
data.profile = { name, syncedAt: updatedAt || 0, protected: !!payload.__protected, kind: payload.__kind || null };
API.saveData(data).catch(() => {});
}
@@ -1978,20 +1999,6 @@ function markCardCacheState(id, state) {
});
}
// Auto-save what you play: once a video starts playing, save it in the
// background (never delays playback). One attempt per video per page session.
const autoSaveTried = new Set();
document.addEventListener('play', () => {
const m = current && current.meta;
if (!m || !m.id || m.custom || current.localUrl) return;
if (data.settings.autoSavePlayed === false) return;
if (!WEB) return;
if (cachedIds.has(m.id) || downloading.has(m.id) || autoSaveTried.has(m.id)) return;
autoSaveTried.add(m.id);
preload(m, { quiet: true });
}, true);
// ============================================================================
// Video editor — cut parts out of a video and save a custom offline copy
//
@@ -3349,6 +3356,20 @@ function openMoreActions() {
row.onclick = () => { closeModal(); setTimeout(() => src.click(), 0); };
list.appendChild(row);
}
if (data.settings?.jamesDsp?.enabled && EQ.state().jamesDsp?.active) {
const row = document.createElement('button');
row.type = 'button'; row.className = 'more-row';
const bypassed = !!EQ.state().jamesDsp?.bypassed;
row.innerHTML = '<span class="more-ico" aria-hidden="true">A/B</span><span class="more-txt"><b></b><small>Temporarily compare with the unprocessed signal</small></span><span class="more-go">›</span>';
row.querySelector('b').textContent = bypassed ? 'Resume JamesDSP' : 'Bypass JamesDSP';
row.setAttribute('aria-label', row.querySelector('b').textContent);
row.onclick = async () => {
closeModal();
const next = await EQ.toggleDspBypass();
toast(next ? 'JamesDSP bypassed' : 'JamesDSP active');
};
list.appendChild(row);
}
if (!list.children.length) { toast('No more actions for this video'); return; }
showModal('More actions', list, [{ label: 'Close', onClick: closeModal }]);
}
@@ -5349,7 +5370,7 @@ const Level = (() => {
// so it keeps going when locked. One render at a time, in the background.
const EqRender = (() => {
const DIR = 'eq-renders', KEY = 'ytpEqRenders', RATE = 32000, MAX_SECONDS = 12 * 60;
const active = () => EQ.isIOS() && WEB && !!window.OPFS && window.OPFS.isSupported() && typeof OfflineAudioContext !== 'undefined';
const active = () => EQ.isIOS() && WEB && !data.settings?.jamesDsp?.enabled && !!window.OPFS && window.OPFS.isSupported() && typeof OfflineAudioContext !== 'undefined';
const readMap = () => { try { return JSON.parse(localStorage.getItem(KEY) || '{}'); } catch { return {}; } };
const writeMap = (m) => { try { localStorage.setItem(KEY, JSON.stringify(m)); } catch { /* blocked */ } };
const queue = new Set();
@@ -5519,10 +5540,13 @@ const PiP = (() => {
const loadSoundFeatures=()=>Promise.all([Lazy.load('feature:eq-core'),Lazy.load('feature:vocal-reducer')]);
const EQ_BANDS = EqParameters.bands;
const EQ_PRESETS = EqParameters.presets;
const JamesDSPFeature = Lazy.proxy('feature:jamesdsp', ['createController'], 'JamesDSPFeature');
const JamesDSPTools = Lazy.proxy('feature:jamesdsp', ['generateIR', 'decodeIR', 'prepareIR', 'saveIR', 'getIR', 'listIRs', 'deleteIR'], 'JamesDSPFeature');
const EQ = (() => {
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
const AC = window.AudioContext || window.webkitAudioContext;
const st = { ctx: null, filters: null, sources: new Map() };
const st = { ctx: null, filters: null, levelDb: 0 };
let dspController = null, dspControllerPromise = null, dspRequest = 0;
// Web Audio is off on iOS (it silences playback when the screen locks)
// unless the user opted in through "Level volume" (Settings → Playback).
// Live Web Audio is off on iOS (it silences playback when the screen locks)
@@ -5537,6 +5561,49 @@ const EQ = (() => {
};
const isFlat = () => gains().every((v) => v === 0);
async function prepareDspGraph() {
if (!available()) throw new Error(isIOS ? 'Turn on Live sound processing in Settings → Playback first.' : 'Web Audio is unavailable.');
if (rendered()) throw new Error('This song is already playing a Standard processed copy. JamesDSP will start with the next original track.');
if (!st.ctx && !AudioGraph.snapshot().contextCreated) {
const context = AudioGraph.context({ sampleRate: 48000 });
if (context.state === 'suspended') context.resume().catch(() => {});
}
await loadSoundFeatures();
if (!st.ctx && !build()) throw new Error('The Standard fallback audio chain is not ready.');
if (!st.ctx || !st.filters?.[0]) throw new Error('The Standard fallback audio chain could not be built.');
attach(els.video);
attach(els.audio);
return { context: st.ctx, elements: [els.video, els.audio].filter(Boolean), standardInput: st.filters[0] };
}
function dspFailed(error) {
if (!data.settings.jamesDsp?.enabled) return;
data.settings.jamesDsp.enabled = false;
if ($('setSoundEngine')) $('setSoundEngine').value = 'standard';
if ($('jamesDspControls')) $('jamesDspControls').hidden = true;
persist();
toast(`JamesDSP unavailable; Standard sound is active. ${error?.message || ''}`.trim());
apply();
Level.apply();
}
async function getDspController() {
if (dspController) return dspController;
if (!dspControllerPromise) dspControllerPromise = Lazy.load('feature:jamesdsp').then(async () => {
dspController = await JamesDSPFeature.createController({ graph: AudioGraph, prepareGraph: prepareDspGraph, onError: dspFailed });
return dspController;
}).catch(error => { dspControllerPromise = null; throw error; });
return dspControllerPromise;
}
function startDsp() {
const request = ++dspRequest;
getDspController().then(controller => {
if (request !== dspRequest || !data.settings.jamesDsp?.enabled) return controller.disable();
return controller.enable(data.settings.jamesDsp, st.levelDb);
}).catch(dspFailed);
}
function build() {
if (st.ctx) return true;
if (!Lazy.loaded('feature:eq-core') || !Lazy.loaded('feature:vocal-reducer')) {
@@ -5544,7 +5611,7 @@ const EQ = (() => {
return false;
}
try {
st.ctx = new AC();
st.ctx = AudioGraph.context();
st.filters = EQ_BANDS.map((b) => {
const f = st.ctx.createBiquadFilter();
f.type = b.type;
@@ -5569,16 +5636,24 @@ const EQ = (() => {
}
function attach(el) {
if (!el || st.sources.has(el)) return;
if (!el) return;
try {
const src = st.ctx.createMediaElementSource(el);
src.connect(st.filters[0]);
st.sources.set(el, src);
AudioGraph.connect(el, st.filters[0]);
} catch { /* already connected elsewhere */ }
}
// Apply the stored curve; wires the graph up the first time it's non-flat.
function apply() {
if (data.settings.jamesDsp?.enabled) {
if (!available()) { dspFailed(new Error(isIOS ? 'Live sound processing is off on this iPhone.' : 'Web Audio is unavailable.')); return; }
if (rendered()) { dspFailed(new Error('The current song already uses a Standard processed copy.')); return; }
startDsp();
renderButton();
return;
}
dspRequest++;
if (dspController) dspController.disable().catch(() => {});
else if (dspControllerPromise) dspControllerPromise.then(controller => controller.disable()).catch(() => {});
if (!available()) return;
if (!st.ctx && isFlat() && EqParameters.amount(data.settings.vocalLevel ?? 100) === 100 && EqParameters.width(data.settings.stereoWidth) === 0) return;
if (!build()) return;
@@ -5658,6 +5733,7 @@ const EQ = (() => {
// one-way step the EQ takes, so it is only offered where the EQ is (never
// on iOS, where Web Audio would silence background playback).
function analyser() {
if (dspController?.active && !dspController.state().bypassed) return dspController.analyser();
if (!available() || !build()) return null;
attach(els.video);
attach(els.audio);
@@ -5673,8 +5749,13 @@ const EQ = (() => {
// Set the levelling gain (dB). 0 dB never wires the graph on its own.
function setLevel(db) {
if (!available()) return false;
if (rendered()) db = 0;
st.levelDb = Number(db) || 0;
if (data.settings.jamesDsp?.enabled) {
if (dspController?.desired) dspController.setLevelDb(st.levelDb).catch(dspFailed);
return true;
}
if (!available()) return false;
if (!st.ctx && Math.abs(db) < 0.3) return true;
if (!build()) return false;
attach(els.video);
@@ -5685,8 +5766,56 @@ const EQ = (() => {
return true;
}
async function toggleDspBypass() {
if (!dspController?.active) return false;
try { return await dspController.toggleBypass(); }
catch (error) { dspFailed(error); return false; }
}
function dspLowEndDevice() {
const cores=Number(navigator.hardwareConcurrency), memory=Number(navigator.deviceMemory);
return (cores>0&&cores<=4)||(memory>0&&memory<=4);
}
async function loadDspIRBuffer(buffer, reference=null) {
if (!data.settings.jamesDsp?.enabled || !dspController?.active) throw new Error('Turn on JamesDSP before importing an impulse response.');
await dspController.loadIR(buffer,reference);
data.settings.jamesDsp.irRef=reference;
data.settings.jamesDsp.params['convolver.enabled']=1;
persist();
return reference;
}
async function loadDspIR(file) {
if (!data.settings.jamesDsp?.enabled || !dspController?.active) throw new Error('Turn on JamesDSP before importing an impulse response.');
const context=st.ctx;if(!context?.decodeAudioData)throw new Error('Audio decoding is unavailable on this device.');
const buffer=await context.decodeAudioData(await file.arrayBuffer());
const prepared=await JamesDSPTools.prepareIR(context,buffer,dspLowEndDevice()?24000:65536);
const name=String(file.name||'Uploaded IR').replace(/\.[^.]+$/,'').slice(0,100)||'Uploaded IR';
let reference=null;try{reference=await JamesDSPTools.saveIR(name,prepared,{kind:'uploaded'});}catch(error){toast(`Impulse response stays on this device for this session: ${error.message}`);}
return loadDspIRBuffer(prepared,reference);
}
async function loadDspBuiltinIR(name) {
if(!data.settings.jamesDsp?.enabled||!dspController?.active)throw new Error('Turn on JamesDSP before loading an impulse response.');
const context=st.ctx;if(!context)throw new Error('Audio context is unavailable.');
const lowEnd=dspLowEndDevice();if(lowEnd&&name!=='Small room')throw new Error('Long impulse responses are disabled on this lower-power device.');
const buffer=await JamesDSPTools.generateIR(name,context.sampleRate,2,lowEnd?24000:65536);
let reference=null;try{reference=await JamesDSPTools.saveIR(name,buffer,{kind:'generated'});}catch(error){toast(`Generated response stays in this session: ${error.message}`);}
return loadDspIRBuffer(buffer,reference);
}
async function loadDspSavedIR(name) {
const stored=await JamesDSPTools.getIR(name);if(!stored)throw new Error(`Stored impulse response not found: ${name}`);
return loadDspIRBuffer(stored.buffer,{name:stored.name,hash:stored.hash});
}
async function listDspIRs() {
return JamesDSPTools.listIRs();
}
return { open, apply, renderButton, available, analyser, setLevel, gains, bands: EQ_BANDS, isIOS: () => isIOS, state: () => ({ wired: !!st.ctx, ctx: st.ctx && st.ctx.state, gains: st.filters ? st.filters.map((f) => f.gain.value) : null,
levelDb: st.level ? Math.round(200 * Math.log10(Math.max(1e-6, st.level.gain.value))) / 10 : null }) };
levelDb: st.level ? Math.round(200 * Math.log10(Math.max(1e-6, st.level.gain.value))) / 10 : null, jamesDsp: dspController?.state() || null }), toggleDspBypass, loadDspIR, loadDspIRBuffer, loadDspBuiltinIR, loadDspSavedIR, listDspIRs };
})();
// ============================================================================
@@ -8539,9 +8668,7 @@ const RUNNING_BUILD = (() => {
let _knownBuildTag = null;
async function fetchServerBuild() {
const res = await fetch('/api/version', { cache: 'no-store' });
if (!res.ok) return null;
const data = await res.json();
const data = await webFetch('/api/version', { cache: 'no-store' });
return data.buildTag || null;
}
@@ -8769,6 +8896,8 @@ async function registerServiceWorker() {
const reg = await navigator.serviceWorker.register('/sw.js', { updateViaCache: 'none' });
_swReg = reg;
Lazy.reportLayout(reg);
reportDspOfflineOptIn(reg);
navigator.serviceWorker.ready.then(readyReg => reportDspOfflineOptIn(readyReg)).catch(() => {});
// A waiting worker only means "update pending" when this page is already
// controlled by a previous SW. On a FIRST install (fresh visit, or right
@@ -8804,6 +8933,14 @@ async function registerServiceWorker() {
}
}
function reportDspOfflineOptIn(reg = _swReg) {
if (!WEB || !navigator.serviceWorker) return;
const dsp = data.settings?.jamesDsp;
const values = dsp?.enabled || dsp?.downloadForOffline ? ['jamesDsp'] : [];
const workers = new Set([navigator.serviceWorker.controller, reg?.installing, reg?.active, reg?.waiting]);
for (const worker of workers) worker?.postMessage({ type: 'OFFLINE_OPT_INS', values });
}
// /?q=<query> — a shareable search link (same family as Share's /?v=&t=).
// Runs after wireUI() so the search form's submit handler exists; the param
// is stripped immediately so a reload doesn't re-run the search.
@@ -8983,7 +9120,7 @@ async function boot() {
lyricOffsets: loaded.lyricOffsets || {},
stats: loaded.stats || null,
lastAutoBackup: loaded.lastAutoBackup || 0,
settings: { ...DEFAULT_SETTINGS, ...(loaded.settings || {}) },
settings: normalizeJamesDspSettings({ ...DEFAULT_SETTINGS, ...(loaded.settings || {}) }),
profile: loaded.profile || null,
};
}

View File

@@ -3,12 +3,22 @@
'use strict';
const CACHE = 'ytplayer-assets';
const STATE = '/__ytp_asset_state';
const OPT_INS = '/__ytp_offline_opt_ins';
const url = (path, file) => path + '?v=' + file.h;
function paths(manifest) {
return Object.keys(manifest.files).sort();
}
function offlinePaths(manifest, optIns = []) {
const allowed = new Set(optIns || []), optional = new Map();
for (const group of Object.values(manifest.groups || {})) {
if (!group.offlineOptIn || allowed.has(group.offlineOptIn)) continue;
for (const path of group.files || []) optional.set(path, true);
}
return paths(manifest).filter(path => !optional.has(path));
}
function blocking(manifest, previous, activeLayout) {
const names = new Set(Object.entries(manifest.groups)
.filter(([name, group]) => name === 'core' || !group.background ||
@@ -61,13 +71,17 @@
return valid;
}
async function status(manifest, cache, { previous, activeLayout, offline = true } = {}) {
async function readOptIns(cache) {
try { return (await (await cache.match(OPT_INS))?.json()) || []; } catch { return []; }
}
async function status(manifest, cache, { previous, activeLayout, offline = true, optIns } = {}) {
const found = await Promise.all(blocking(manifest, previous, activeLayout).map(async path => {
const response = await cache.match(url(path, manifest.files[path]));
return verifiedProbe(response, manifest.files[path].h);
}));
const missing = found.filter(value => !value).length;
return { ready: missing === 0, missing, version: manifest.buildTag, ...(offline ? await completeness(manifest, cache) : {}) };
return { ready: missing === 0, missing, version: manifest.buildTag, ...(offline ? await completeness(manifest, cache, { optIns }) : {}) };
}
// All concurrent messages/layout jobs in this worker share six download slots.
@@ -89,10 +103,10 @@
finally { pendingDownloads.delete(key); }
}
async function syncAssets(manifest, { cache, fetchFn, concurrency = 6, attempts = 3, activeLayout, groups, all = false }) {
async function syncAssets(manifest, { cache, fetchFn, concurrency = 6, attempts = 3, activeLayout, groups, all = false, optIns } = {}) {
const previous = (await state(cache))?.current;
const missing = [];
const selected = all ? paths(manifest) : groups ? [...new Set(groups.flatMap(name => manifest.groups[name]?.files || []))].sort()
const selected = all ? offlinePaths(manifest, optIns || await readOptIns(cache)) : groups ? [...new Set(groups.flatMap(name => manifest.groups[name]?.files || []))].sort()
: blocking(manifest, previous, activeLayout);
for (const path of selected) {
const key = url(path, manifest.files[path]);
@@ -135,8 +149,8 @@
// Verified cache entries are the durable progress journal. Counters are rebuilt
// after worker termination or browser eviction; never trust a stored ready bit.
async function completeness(manifest, cache) {
const files = paths(manifest);
async function completeness(manifest, cache, { optIns } = {}) {
const files = offlinePaths(manifest, optIns || await readOptIns(cache));
const missingFiles = (await Promise.all(files.map(async path => {
const response = await cache.match(url(path, manifest.files[path]));
return verifiedProbe(response, manifest.files[path].h) ? null : path;
@@ -146,12 +160,13 @@
}
const completionKey = manifest => '/__ytp_completion/' + manifest.buildTag;
async function complete(manifest, { cache, fetchFn, cycles = 4, now = Date.now,
async function complete(manifest, { cache, fetchFn, cycles = 4, now = Date.now, optIns,
sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), baseDelay = 1000,
maxDelay = 30000, notify = () => {}, force = false } = {}) {
maxDelay = 30000, notify = () => {}, force = false, concurrency = 1 } = {}) {
const key = completionKey(manifest), saved = await cache.match(key);
let job = saved ? await saved.json() : { failures: 0, nextRetryAt: 0 };
let snapshot = await completeness(manifest, cache);
const selectedOptIns = optIns || await readOptIns(cache);
let snapshot = await completeness(manifest, cache, { optIns: selectedOptIns });
const publish = async running => {
job = { ...job, ...snapshot, running, version: manifest.buildTag };
await cache.put(key, Response.json(job));
@@ -162,9 +177,9 @@
for (let cycle = 0; cycle < cycles; cycle++) {
await publish(true);
let error;
try { await syncAssets(manifest, { cache, fetchFn, all: true }); }
try { await syncAssets(manifest, { cache, fetchFn, all: true, optIns: selectedOptIns, concurrency }); }
catch (failure) { error = failure; }
snapshot = await completeness(manifest, cache);
snapshot = await completeness(manifest, cache, { optIns: selectedOptIns });
if (snapshot.offlineReady) { job.failures = 0; job.nextRetryAt = 0; job.error = null; await publish(false); return job; }
job.failures++;
const delay = Math.min(maxDelay, baseDelay * 2 ** Math.min(job.failures - 1, 10));
@@ -198,7 +213,7 @@
return next;
}
const api = { CACHE, STATE, url, paths, blocking, plan, retained, fallback, status, completeness, completionKey, complete, syncAssets, state, commit };
const api = { CACHE, STATE, OPT_INS, url, paths, offlinePaths, blocking, plan, retained, fallback, status, completeness, completionKey, complete, syncAssets, readOptIns, state, commit };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.AssetSyncCore = api;
})(typeof globalThis !== 'undefined' ? globalThis : this);

View File

@@ -56,6 +56,20 @@ test('completion includes ungrouped runtime files and exposes verified missing p
assert.equal((await core.status(m,c)).offlineReady,true);
});
test('offline completion skips opt-in DSP assets until the user enables offline audio effects', async () => {
const c=cache(),m=manifest();m.files['/vendor/jamesdsp/dsp/jamesdsp.wasm']={h:'wasm'};
m.groups.jamesdsp={contract:1,eager:false,background:true,offlineOptIn:'jamesDsp',files:['/vendor/jamesdsp/dsp/jamesdsp.wasm']};
const calls=[];
const defaultJob=await core.complete(m,{cache:c,fetchFn:async u=>{calls.push(u);return response(u.split('=')[1])}});
assert.deepEqual(calls.sort(),['/a.js?v=a','/index.html?v=b']);
assert.equal(defaultJob.total,2);assert.equal(defaultJob.offlineReady,true);
calls.length=0;
await c.put(core.OPT_INS,Response.json(['jamesDsp']));
const optedJob=await core.complete(m,{cache:c,fetchFn:async u=>{calls.push(u);return response(u.split('=')[1])}});
assert.deepEqual(calls,['/vendor/jamesdsp/dsp/jamesdsp.wasm?v=wasm']);
assert.equal(optedJob.total,3);assert.equal(optedJob.offlineReady,true);
});
test('completion persists backoff and resumes only missing files after a worker restart',async()=>{
const c=cache(),m=manifest();let clock=1000;const calls=[];
await core.complete(m,{cache:c,cycles:1,now:()=>clock,baseDelay:10,fetchFn:async u=>{if(u.includes('index'))throw Error('offline');return response('a');}});
@@ -82,6 +96,13 @@ test('overlapping layout and completion jobs share a six-download ceiling',async
assert.ok(peak<=6);assert.ok([...calls.values()].every(count=>count===1));
});
test('offline completion keeps its own network concurrency to one',async()=>{
const c=cache(),m=manifest();let active=0,peak=0;
for(let i=0;i<12;i++){const p='/complete'+i+'.js';m.files[p]={h:String(i)};}
const fetchFn=async u=>{active++;peak=Math.max(peak,active);await new Promise(r=>setTimeout(r,2));active--;return response(u.split('=')[1]);};
await core.complete(m,{cache:c,fetchFn});assert.equal(peak,1);
});
test('blocking commit never waits on an optional file readiness probe',{timeout:1000},async()=>{
const c=cache(),m=manifest();m.files['/extra.js']={h:'extra'};m.groups.extra={files:['/extra.js'],background:true,contract:1};
await c.put('/a.js?v=a',response('a'));await c.put('/index.html?v=b',response('b'));

View File

@@ -57,6 +57,31 @@ test('waiting status does not start completion and activation delegates it to it
assert.equal((await core.status(e.m,cache)).offlineReady,true);
});
test('legacy shell verification is staged during install so Refresh UI activation does no hashing',async()=>{
const e=environment(),legacy=await e.storage.open('ytplayer-production-old');let digests=0;
await legacy.put('/app.js',new Response('legacy app bytes'));
const subtle=e.sandbox.crypto.subtle;
e.sandbox.crypto={subtle:{digest:async(...args)=>{digests++;return subtle.digest(...args);}}};
await e.dispatch('install');
const stagedDigests=digests,cache=await e.storage.open(core.CACHE),candidate=await(await cache.match('/__ytp_candidate/next')).json();
assert.ok(stagedDigests>0,'install verified old cached bytes before offering Refresh UI');
assert.deepEqual(candidate.legacyCacheNames,['ytplayer-production-old']);
assert.ok((await core.state(cache)).current.legacyURLs['/app.js']);
await e.dispatch('activate');
assert.equal(digests,stagedDigests,'the user-triggered activation does not hash the old shell again');
assert.equal((await e.storage.keys()).includes('ytplayer-production-old'),false,'old shell is deleted only after commit');
});
test('offline opt-in is persisted and adds only declared optional groups to completion',async()=>{
const e=environment();e.m.files['/large.wasm']={h:'wasm'};e.m.groups.dsp={files:['/large.wasm'],contract:1,background:true,offlineOptIn:'jamesDsp'};
await e.dispatch('install');await e.dispatch('activate');await e.complete();
const cache=await e.storage.open(core.CACHE);assert.equal(await cache.match('/large.wasm?v=wasm'),undefined);
await e.dispatch('message',{data:{type:'OFFLINE_OPT_INS',values:['jamesDsp','not-a-valid-opt-in']}});
assert.deepEqual(await core.readOptIns(cache),['jamesDsp']);
assert.equal((await cache.match('/large.wasm?v=wasm')).headers.get('X-Asset-Hash'),'wasm');
const status=await core.status(e.m,cache);assert.equal(status.offlineReady,true);assert.equal(status.total,3);
});
test('page-captured app is reused on first install without a worker download',async()=>{
const e=environment(),cache=await e.storage.open(core.CACHE);
await cache.put('/app.js?v=app',new Response('page captured app',{headers:{'X-Asset-Hash':'app'}}));

View File

@@ -29,6 +29,7 @@
"/related-videos.js",
"/related-videos.css",
"/audio-continuity.js",
"/audio-graph.js",
"/fullscreen-orientation.js",
"/fullscreen-orientation.css",
"/download-actions.js",
@@ -359,6 +360,27 @@
"dependencies": [
"feature:stats"
]
},
"feature:jamesdsp": {
"contract": 1,
"eager": false,
"background": true,
"offlineOptIn": "jamesDsp",
"files": [
"/vendor/jamesdsp/jamesdsp-feature.js",
"/vendor/jamesdsp/jamesdsp-node.mjs",
"/vendor/jamesdsp/params.mjs",
"/vendor/jamesdsp/ir-utils.mjs",
"/vendor/jamesdsp/ir-builtins.mjs",
"/vendor/jamesdsp/ir-store.mjs",
"/vendor/jamesdsp/worklet.mjs",
"/vendor/jamesdsp/dsp/jamesdsp-a982b53.mjs",
"/vendor/jamesdsp/dsp/jamesdsp.wasm"
],
"dependencies": [
"feature:eq-core",
"feature:vocal-reducer"
]
}
}
}

View File

@@ -35,7 +35,68 @@
}
}
const AsyncGuard = { runExclusive };
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function retry(task, { attempts = 3, delay = attempt => attempt === 1 ? 350 : 1000,
shouldRetry = () => true, sleep = wait } = {}) {
let last;
for (let attempt = 1; attempt <= Math.max(1, attempts); attempt++) {
try { return await task(attempt); }
catch (error) {
last = error;
if (attempt >= attempts || !shouldRetry(error, attempt)) throw error;
await sleep(delay(attempt));
}
}
throw last;
}
// Retry only idempotent GETs. Keep the timeout active through JSON parsing so
// a stalled response body is treated like a stalled connection.
async function getJson(url, options = {}, config = {}) {
const fetchFn = config.fetch || root.fetch?.bind(root);
if (!fetchFn) throw new Error('fetch is unavailable');
if ((options.method || 'GET').toUpperCase() !== 'GET') throw new Error('Retry helper only accepts GET');
const attempts = config.attempts ?? 3, timeoutMs = config.timeoutMs ?? 20000;
return retry(async () => {
const controller = typeof AbortController === 'function' ? new AbortController() : null;
let timedOut = false, timer, externalAbort;
const external = options.signal;
if (controller && external) {
if (external.aborted) throw external.reason || new DOMException('Aborted', 'AbortError');
externalAbort = () => controller.abort(external.reason);
external.addEventListener('abort', externalAbort, { once: true });
}
if (controller && timeoutMs > 0) timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
try {
const response = await fetchFn(url, { ...options, ...(controller ? { signal: controller.signal } : {}) });
if ([408, 425, 429].includes(response.status) || response.status >= 500) {
const error = new Error(`HTTP ${response.status}`); error.retryable = true; throw error;
}
if (!response.ok) {
let message = `HTTP ${response.status}`;
try { message = (await response.json()).error || message; } catch {}
const error = new Error(message); error.retryable = false; throw error;
}
const value = await response.json();
if (config.retryResult?.(value)) {
const error = new Error(value.error || value.message || 'Temporary API failure');
error.retryable = true;
throw error;
}
return value;
} catch (error) {
if (external?.aborted) throw error;
if (timedOut) { const timeout = new Error('Request timed out'); timeout.retryable = true; throw timeout; }
if (error.retryable === undefined) error.retryable = true;
throw error;
} finally {
if (timer) clearTimeout(timer);
if (external && externalAbort) external.removeEventListener('abort', externalAbort);
}
}, { attempts, shouldRetry: error => error.retryable !== false, sleep: config.sleep || wait });
}
const AsyncGuard = { runExclusive, retry, getJson };
if (typeof module !== 'undefined' && module.exports) {
module.exports = AsyncGuard;

View File

@@ -60,6 +60,55 @@ test('frees the key after failure so a retry is possible', async () => {
assert.strictEqual(out, 'ok');
});
test('bounded GET retries recover transient network and server failures', async () => {
const { getJson } = require('./async-guard');
let calls = 0;
const result = await getJson('/api/search', {}, { sleep: async () => {}, fetch: async () => {
calls++;
if (calls === 1) throw new TypeError('connection reset');
if (calls === 2) return new Response('{}', { status: 503 });
return Response.json({ ok: true, results: [] });
} });
assert.equal(result.ok, true);
assert.equal(calls, 3);
});
test('GET retry stops at the bound and does not retry permanent HTTP errors', async () => {
const { getJson } = require('./async-guard');
let calls = 0;
await assert.rejects(getJson('/api/search', {}, { sleep: async () => {}, fetch: async () => {
calls++; return new Response('{}', { status: 404 });
} }), /HTTP 404/);
assert.equal(calls, 1);
await assert.rejects(getJson('/api/search', {}, { attempts: 2, sleep: async () => {}, fetch: async () => {
calls++; throw new TypeError('offline');
} }), /offline/);
assert.equal(calls, 3);
});
test('retryable API error payloads recover but permanent application errors do not retry', async () => {
const { getJson } = require('./async-guard'); let calls = 0;
const retryResult = value => value?.ok === false && /temporarily unavailable/i.test(value.error || '');
const result = await getJson('/api/streams', {}, { retryResult, sleep: async () => {}, fetch: async () => {
calls++;
return Response.json(calls === 1 ? { ok: false, error: 'temporarily unavailable' } : { ok: true, data: [] });
} });
assert.equal(result.ok, true); assert.equal(calls, 2);
calls = 0;
const absent = await getJson('/api/streams', {}, { retryResult, sleep: async () => {}, fetch: async () => { calls++; return Response.json({ ok: false, error: 'video not found' }); } });
assert.equal(absent.ok, false); assert.equal(calls, 1);
});
test('timed out GET bodies retry within the configured bound', async () => {
const { getJson } = require('./async-guard'); let calls = 0;
const result = await getJson('/api/related', {}, { attempts: 2, timeoutMs: 5, sleep: async () => {}, fetch: async (_url, { signal }) => {
calls++;
if (calls === 1) return new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true }));
return Response.json({ ok: true });
} });
assert.equal(result.ok, true); assert.equal(calls, 2);
});
test('supports a synchronous fn', async () => {
const set = new Set();
const out = await runExclusive(set, 's', () => 7);

69
frontend/audio-graph.js Normal file
View File

@@ -0,0 +1,69 @@
/* One lifetime owner for the player's realtime AudioContext and media sources. */
(function (root) {
'use strict';
function create(options = {}) {
const getConstructor = options.getConstructor || (() => root.AudioContext || root.webkitAudioContext);
let context = null;
const sources = new Map();
const routes = new Map();
const failed = new Map();
function getContext(contextOptions) {
if (context) return context;
const Constructor = getConstructor();
if (typeof Constructor !== 'function') throw new Error('Web Audio is unavailable');
context = contextOptions === undefined ? new Constructor() : new Constructor(contextOptions);
return context;
}
function source(element) {
if (!element) throw new TypeError('A media element is required');
if (sources.has(element)) return sources.get(element);
if (failed.has(element)) throw failed.get(element);
try {
const created = getContext().createMediaElementSource(element);
sources.set(element, created);
return created;
} catch (error) {
// MediaElementSource cannot be undone. Remember failure so a later
// route change can never attempt a second source for this element.
failed.set(element, error);
throw error;
}
}
function connect(element, destination) {
const mediaSource = source(element);
if (!destination) throw new TypeError('An audio destination is required');
if (routes.get(element) === destination) return mediaSource;
if (routes.has(element)) mediaSource.disconnect();
mediaSource.connect(destination);
routes.set(element, destination);
return mediaSource;
}
function routeAll(elements, destination) {
for (const element of elements || []) connect(element, destination);
}
function snapshot() {
return {
contextCreated: !!context,
sampleRate: context?.sampleRate || null,
sourceCount: sources.size,
failedCount: failed.size,
routedCount: routes.size,
};
}
return { context: getContext, source, connect, routeAll, snapshot };
}
const singleton = create();
const api = { create, context: (...args) => singleton.context(...args), source: (...args) => singleton.source(...args),
connect: (...args) => singleton.connect(...args), routeAll: (...args) => singleton.routeAll(...args),
snapshot: () => singleton.snapshot() };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.AudioGraph = api;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,75 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const { join } = require('node:path');
const AudioGraph = require('./audio-graph');
test('AudioGraph creates its context only on demand and retains the first context options', () => {
let contexts = 0, optionsSeen;
class Context {
constructor(options) { contexts++; optionsSeen = options; this.sampleRate = options?.sampleRate || 44100; }
}
const graph = AudioGraph.create({ getConstructor: () => Context });
assert.equal(graph.snapshot().contextCreated, false);
const first = graph.context({ sampleRate: 48000 });
assert.equal(graph.context({ sampleRate: 44100 }), first);
assert.equal(contexts, 1);
assert.deepEqual(optionsSeen, { sampleRate: 48000 });
assert.equal(first.sampleRate, 48000);
});
test('one retained MediaElementSource per element can change insert routes without recreation', () => {
const made = [], connects = [], disconnects = [];
class Context {
constructor() { this.sampleRate = 48000; }
createMediaElementSource(element) {
const source = { element, connect: target => connects.push([element.id, target.id]), disconnect: () => disconnects.push(element.id) };
made.push(source); return source;
}
}
const graph = AudioGraph.create({ getConstructor: () => Context });
const a = { id: 'video' }, b = { id: 'audio' }, standard = { id: 'standard' }, dsp = { id: 'dsp' };
const original = graph.connect(a, standard);
graph.connect(a, standard);
graph.routeAll([a, b], dsp);
graph.routeAll([a, b], standard);
assert.equal(made.length, 2);
assert.equal(graph.source(a), original);
assert.deepEqual(connects, [['video', 'standard'], ['video', 'dsp'], ['audio', 'dsp'], ['video', 'standard'], ['audio', 'standard']]);
assert.deepEqual(disconnects, ['video', 'video', 'audio']);
assert.deepEqual(graph.snapshot(), { contextCreated: true, sampleRate: 48000, sourceCount: 2, failedCount: 0, routedCount: 2 });
});
test('a failed source creation is remembered and is never attempted twice', () => {
let attempts = 0;
class Context {
constructor() { this.sampleRate = 48000; }
createMediaElementSource() { attempts++; throw new Error('already sourced'); }
}
const graph = AudioGraph.create({ getConstructor: () => Context }), element = {};
assert.throws(() => graph.source(element), /already sourced/);
assert.throws(() => graph.source(element), /already sourced/);
assert.equal(attempts, 1);
assert.deepEqual(graph.snapshot(), { contextCreated: true, sampleRate: 48000, sourceCount: 0, failedCount: 1, routedCount: 0 });
});
test('the extracted Standard EQ build block is identical to the original except for context ownership', () => {
const source = readFileSync(join(__dirname, 'app.js'), 'utf8');
const original = readFileSync(join(__dirname, '..', 'tests', 'fixtures', 'standard-eq-build.txt'), 'utf8').trimEnd();
const start = source.indexOf(' function build() {', source.indexOf('const EQ = (() => {'));
const end = source.indexOf('\n function attach(el)', start);
assert.ok(start >= 0 && end > start, 'EQ build block exists');
const current = source.slice(start, end).trimEnd();
assert.equal(current, original.replace('st.ctx = new AC();', 'st.ctx = AudioGraph.context();'));
assert.match(source, /AudioGraph\.connect\(el, st\.filters\[0\]\)/);
assert.doesNotMatch(source, /\.createMediaElementSource\(/);
});
test('AudioGraph is a core runtime asset and is loaded before the lazy app', () => {
const { groups } = JSON.parse(readFileSync(join(__dirname, 'assets.json'), 'utf8'));
assert.ok(groups.core.files.includes('/audio-graph.js'));
const html = readFileSync(join(__dirname, 'index.html'), 'utf8');
assert.ok(html.indexOf('src="audio-graph.js"') < html.indexOf('src="section-rail.js"'));
const embedded = JSON.parse(html.match(/id="ytp-assets">([^<]+)<\/script>/)[1]);
assert.deepEqual(embedded.groups, groups);
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,66 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const { join } = require('node:path');
const vm = require('node:vm');
const app = readFileSync(join(__dirname, 'app.js'), 'utf8');
const views = readFileSync(join(__dirname, 'views-core.js'), 'utf8');
function parsePreset(text) {
const declaration = views.match(/function parseJamesDspPreset\(text\) \{[\s\S]*?\n\}/)?.[0];
assert.ok(declaration, 'preset parser is present');
const context = vm.createContext({});
vm.runInContext(`${declaration}; globalThis.parse = parseJamesDspPreset;`, context);
return context.parse(text);
}
test('the persisted engine is Standard by default and upgrades missing JamesDSP settings safely', () => {
assert.match(app, /jamesDsp: \{ enabled: false, downloadForOffline: false, preset: 'flat', params: \{\}, irRef: null \}/);
assert.match(app, /downloadForOffline: saved\.downloadForOffline === true/);
assert.match(app, /enabled: saved\.enabled === true/);
assert.match(app, /preset: typeof saved\.preset === 'string' \? saved\.preset : 'flat'/);
assert.match(app, /settings: normalizeJamesDspSettings\(\{ \.\.\.DEFAULT_SETTINGS, \.\.\.\(loaded\.settings \|\| \{\}\) \}\)/);
assert.match(app, /data\.settings = normalizeJamesDspSettings\(\{ \.\.\.DEFAULT_SETTINGS, \.\.\.payload\.settings \}\)/);
});
test('live JamesDSP shares the existing iOS gate and never stacks over EqRender copies', () => {
assert.match(app, /const available = \(\) => !!AC && \(!isIOS \|\| data\.settings\.liveAudioIOS === true\)/);
assert.match(app, /if \(data\.settings\?\.jamesDsp\?\.enabled\) return null/);
assert.match(app, /const active = \(\) => EQ\.isIOS\(\) && WEB && !data\.settings\?\.jamesDsp\?\.enabled/);
assert.match(app, /if \(rendered\(\)\) throw new Error\('This song is already playing a Standard processed copy\./);
});
test('EQ creates no second context or element source and passes Standard fallback routing to the controller', () => {
assert.equal((app.match(/\.createMediaElementSource\(/g) || []).length, 0);
assert.match(app, /st\.ctx = AudioGraph\.context\(\)/);
assert.match(app, /AudioGraph\.connect\(el, st\.filters\[0\]\)/);
assert.match(app, /standardInput: st\.filters\[0\]/);
assert.match(app, /dspController\.setLevelDb\(st\.levelDb\)/);
assert.match(app, /if \(data\.settings\.jamesDsp\?\.enabled\) \{[\s\S]{0,450}startDsp\(\)/);
assert.match(app, /request !== dspRequest \|\| !data\.settings\.jamesDsp\?\.enabled/);
});
test('Playback settings expose persisted presets, bands, safe import/export, IR, and A/B bypass', () => {
assert.match(views, /sel\('setSoundEngine'/);
assert.match(views, /sel\('setDspPreset'/);
for (const id of ['setDspCompressor', 'dspPresetImportBtn', 'dspPresetExportBtn', 'dspResetBtn', 'dspIrFile']) assert.ok(views.includes(`id="${id}"`), id);
assert.match(views, /\[25, 40, 63, 100, 160, 250, 400, 630, 1000, 1600, 2500, 4000, 6300, 10000, 16000\]/);
assert.match(views, /imported\?\.texts/);
assert.doesNotMatch(views, /liveprog|ddc|arbitrary/);
assert.match(views, /navigator\.hardwareConcurrency/);
assert.match(views, /Long impulse responses are disabled/);
assert.doesNotMatch(views, /44\.1 or 48 kHz/);
assert.match(views, /setDspSpatialMode/);
assert.match(views, /data-dsp-param="convolver\.predelayMs"/);
assert.match(views, /data-dsp-param="convolver\.mix"/);
assert.match(app, /Bypass JamesDSP/);
assert.match(app, /toggleDspBypass/);
});
test('preset import validates ranges and excludes text-effect parameters', () => {
assert.deepEqual(JSON.parse(JSON.stringify(parsePreset(JSON.stringify({ version: 1, preset: 'warm', params: { 'eq.band0': 3, 'bass.enabled': 1 } })))), { preset: 'warm', params: { 'eq.band0': 3, 'bass.enabled': 1 } });
assert.throws(() => parsePreset({ version: 1, preset: 'flat', params: { 'liveprog.enabled': 1 } }), /text effects are disabled|Unsupported preset setting/);
assert.throws(() => parsePreset({ version: 1, params: { 'eq.band0': 50 } }), /Unsupported preset setting/);
assert.throws(() => parsePreset({ version: 1, texts: { effect: 'unsafe' }, params: {} }), /text effects are disabled/);
});

View File

@@ -0,0 +1,68 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const { join } = require('node:path');
const root = __dirname;
const assets = JSON.parse(readFileSync(join(root, 'assets.json'), 'utf8'));
const group = assets.groups['feature:jamesdsp'];
test('JamesDSP runtime files live only in a lazy background group', () => {
assert.ok(group, 'feature group exists');
assert.equal(group.contract, 1);
assert.equal(group.eager, false);
assert.equal(group.background, true);
assert.equal(group.offlineOptIn, 'jamesDsp');
assert.deepEqual(group.dependencies, ['feature:eq-core', 'feature:vocal-reducer']);
assert.deepEqual(group.files, [
'/vendor/jamesdsp/jamesdsp-feature.js',
'/vendor/jamesdsp/jamesdsp-node.mjs',
'/vendor/jamesdsp/params.mjs',
'/vendor/jamesdsp/ir-utils.mjs',
'/vendor/jamesdsp/ir-builtins.mjs',
'/vendor/jamesdsp/ir-store.mjs',
'/vendor/jamesdsp/worklet.mjs',
'/vendor/jamesdsp/dsp/jamesdsp-a982b53.mjs',
'/vendor/jamesdsp/dsp/jamesdsp.wasm',
]);
for (const path of group.files) assert.equal(assets.groups.core.files.includes(path), false, `${path} is not core`);
const sw = readFileSync(join(root, 'sw.js'), 'utf8');
for (const path of group.files) assert.equal(sw.includes(`'${path}'`), false, `${path} is not in the legacy shell`);
});
test('JamesDSP resolves every module dependency through the page build manifest', () => {
const node = readFileSync(join(root, 'vendor/jamesdsp/jamesdsp-node.mjs'), 'utf8');
const worklet = readFileSync(join(root, 'vendor/jamesdsp/worklet.mjs'), 'utf8');
assert.match(node, /globalThis\.Lazy\?\.url\?\.\(path\)/);
assert.match(node, /assetURL\('\/vendor\/jamesdsp\/dsp\/jamesdsp\.wasm'/);
assert.match(node, /assetURL\('\/vendor\/jamesdsp\/params\.mjs'/);
assert.match(node, /processorOptions:\{wasmBytes\}/);
assert.match(worklet, /import createJamesDSP from '\.\/dsp\/jamesdsp-a982b53\.mjs'/);
assert.doesNotMatch(worklet, /import\(/);
assert.match(node, /context\.sampleRate<8000\|\|context\.sampleRate>96000/);
assert.match(node, /!\[1,2,4\]\.includes\(buffer\.numberOfChannels\) \|\| buffer\.length>65536/);
const feature = readFileSync(join(root, 'vendor/jamesdsp/jamesdsp-feature.js'), 'utf8');
assert.match(feature, /Lazy\.url\('\/vendor\/jamesdsp\/jamesdsp-node\.mjs'\)/);
assert.match(feature, /Lazy\.url\('\/vendor\/jamesdsp\/dsp\/jamesdsp\.wasm'\)/);
});
test('player wrapper rejects text effects while portable presets retain IR references', () => {
const node = readFileSync(join(root, 'vendor/jamesdsp/jamesdsp-node.mjs'), 'utf8');
const worklet = readFileSync(join(root, 'vendor/jamesdsp/worklet.mjs'), 'utf8');
assert.match(node, /Text effects are disabled in this player version/);
assert.match(node, /toJSON\(\) \{return \{version:2,params:/);
assert.match(node, /irCapFrames:view\.getUint32\(32,true\)/);
assert.match(node, /getIR\(preset\.irRef\.name\)/);
const feature = readFileSync(join(root, 'vendor/jamesdsp/jamesdsp-feature.js'), 'utf8');
assert.match(feature, /async function prepareIR\(context, buffer, maxFrames = 65536\)/);
assert.match(feature, /prepared\.length>Math\.min\(65536,maxFrames\)/);
assert.doesNotMatch(worklet, /data\.type==='text'/);
});
test('vendor provenance pins the source and retains both supplied license texts', () => {
const version = readFileSync(join(root, 'vendor/jamesdsp/VERSION.txt'), 'utf8');
assert.match(version, /a982b53c4ab347d1d9c50f4ce7ee3c2735eaa817/);
assert.match(version, /GPL-2\.0 text/);
assert.ok(readFileSync(join(root, 'vendor/jamesdsp/LICENSE.txt'), 'utf8').includes('Version 3'));
assert.ok(readFileSync(join(root, 'vendor/jamesdsp/UPSTREAM-MAIN-LICENSE.txt'), 'utf8').includes('Version 2'));
});

View File

@@ -0,0 +1,114 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { createController } = require('./vendor/jamesdsp/jamesdsp-feature.js');
function fixture({ loadNode } = {}) {
const routed = [], errors = [], created = [], configured = [], bypass = [];
const graph = { routeAll: (elements, destination) => routed.push([elements.map(x => x.id), destination]) };
const gainParam = { value: 1, cancelScheduledValues() {}, setValueAtTime(v) { this.value = v; }, linearRampToValueAtTime(v) { this.value = v; } };
const context = { sampleRate: 48000, state: 'running', currentTime: 0, destination: 'destination', createGain: () => ({ gain: gainParam, connect() {}, disconnect() {} }), resume: async () => {} };
const standardInput = 'standard-input', elements = [{ id: 'video' }, { id: 'audio' }];
const prepareGraph = async () => ({ context, standardInput, elements });
const defaultLoad = async () => {
const listeners = new Map();
const instance = {
node: { connect() {}, disconnect() {} }, destroyed: false,
addEventListener(type, fn) { listeners.set(type, fn); },
removeEventListener(type, fn) { if (listeners.get(type) === fn) listeners.delete(type); },
async setBypass(v) { bypass.push(v); },
async applyPreset(params) { configured.push({ ...params }); },
async setParam(name, value) { configured.push({ [name]: value }); },
destroy() { this.destroyed = true; },
fail(error) { listeners.get('error')?.({ detail: error }); },
};
created.push(instance); return instance;
};
const controller = createController({ graph, prepareGraph, loadNode: loadNode || defaultLoad, onError: error => errors.push(error) });
return { controller, routed, errors, created, configured, bypass, context, elements, standardInput };
}
test('enable routes one initialized JamesDSP node and disable restores Standard before destroying it', async () => {
const f = fixture();
assert.equal(await f.controller.enable({ preset: 'bass', params: { gain: -2 } }, 3), true);
assert.equal(f.controller.active, true);
assert.deepEqual(f.routed, [[['video', 'audio'], f.created[0].node]]);
assert.equal(f.created.length, 1);
assert.equal(f.controller.state().liveHeaps, 1);
assert.equal(f.controller.state().maxLiveHeaps, 1);
const standard = f.controller.disable();
assert.deepEqual(f.routed.at(-1), [['video', 'audio'], f.standardInput]);
await standard;
assert.equal(f.created[0].destroyed, true);
assert.equal(f.controller.state().liveHeaps, 0);
assert.equal(f.controller.state().nodesDestroyed, 1);
assert.equal(f.errors.length, 0);
});
test('a rejected or unsupported engine leaves the Standard route active', async () => {
const f = fixture({ loadNode: async () => { throw new Error('corrupt wasm'); } });
await assert.rejects(f.controller.enable({ preset: 'flat' }), /corrupt wasm/);
assert.deepEqual(f.routed, [[['video', 'audio'], f.standardInput]]);
assert.equal(f.controller.active, false);
assert.equal(f.controller.state().liveHeaps, 0);
assert.equal(f.errors.length, 1);
const supportedRate = fixture();
supportedRate.context.sampleRate = 32000;
await supportedRate.controller.enable({ preset: 'flat' });
assert.equal(supportedRate.controller.state().active, true);
assert.equal(supportedRate.controller.state().sampleRate, 32000);
});
test('a runtime worklet failure switches sources to Standard before destroying the heap', async () => {
const f = fixture();
await f.controller.enable({ preset: 'flat' });
const instance = f.created[0];
instance.fail(new Error('processor fault'));
assert.deepEqual(f.routed.at(-1), [['video', 'audio'], f.standardInput]);
assert.equal(instance.destroyed, true);
assert.equal(f.controller.active, false);
assert.equal(f.controller.state().liveHeaps, 0);
assert.match(f.errors[0].message, /processor fault/);
});
test('disable during async node loading prevents a late DSP route', async () => {
let finish;
const f = fixture({ loadNode: () => new Promise(resolve => { finish = resolve; }) });
const enabling = f.controller.enable({ preset: 'flat' });
await new Promise(resolve => setImmediate(resolve));
const disabling = f.controller.disable();
const neverRouted = {
node: { connect() {}, disconnect() {} },
addEventListener() {}, removeEventListener() {}, setBypass: async () => {}, applyPreset: async () => {}, setParam: async () => {}, destroy() { this.destroyed = true; },
};
finish(neverRouted);
await enabling; await disabling;
assert.equal(f.routed.some(([, destination]) => destination === neverRouted.node), false);
assert.equal(neverRouted.destroyed, true);
assert.equal(f.controller.state().maxLiveHeaps, 0);
});
test('preset gain and Level gain combine within engine bounds without pausing playback', async () => {
const f = fixture();
await f.controller.enable({ preset: 'loudness', params: { gain: 8 } }, 9);
assert.ok(f.configured.some(entry => entry.gain === 12));
assert.equal(f.created.length, 1);
assert.equal(f.controller.state().maxLiveHeaps, 1);
assert.equal(f.controller.active, true);
});
test('A/B bypass is retained when settings are reapplied', async () => {
const f = fixture();
await f.controller.enable({ preset: 'warm' }, 0);
assert.equal(await f.controller.toggleBypass(), true);
assert.equal(f.controller.state().route, 'standard');
assert.deepEqual(f.routed.at(-1), [['video', 'audio'], f.standardInput], 'bypass follows the exact Standard route');
await f.controller.enable({ preset: 'bass' }, 0);
assert.equal(f.controller.state().bypassed, true);
assert.equal(f.controller.state().route, 'standard');
assert.deepEqual(f.routed.at(-1), [['video', 'audio'], f.standardInput], 'settings changes cannot replace the Standard route while bypassed');
assert.ok(f.bypass.at(-1));
assert.equal(await f.controller.toggleBypass(), false);
assert.equal(f.controller.state().route, 'jamesdsp');
assert.equal(f.bypass.at(-1), false);
});

View File

@@ -0,0 +1,23 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
test('generated room responses support four true-stereo paths and respect the low-memory cap', async () => {
const { generateIR, BUILTIN_IRS } = await import('./vendor/jamesdsp/ir-builtins.mjs');
const { resampleIR } = await import('./vendor/jamesdsp/ir-utils.mjs');
const ir = generateIR('Hall', 48000, 4, { maxFrames: 24000 });
assert.equal(ir.numberOfChannels, 4);
assert.equal(ir.length, 24000);
assert.equal(ir.truncated, true);
assert.ok(ir.getChannelData(0).some((sample, i) => sample !== ir.getChannelData(1)[i]), 'each matrix path has distinct taps');
const converted = resampleIR(ir, 32000);
assert.equal(converted.sampleRate, 32000);
assert.equal(converted.numberOfChannels, 4);
assert.equal(converted.length, 16000);
assert.deepEqual(Object.keys(BUILTIN_IRS), ['Small room', 'Hall', 'Plate', 'Cathedral']);
});
test('the IndexedDB store rejects impulse responses beyond its measured internal-frame cap', async () => {
const { saveIR } = await import('./vendor/jamesdsp/ir-store.mjs');
const oversized = { sampleRate: 48000, numberOfChannels: 4, length: 65537, getChannelData: () => new Float32Array(65537) };
await assert.rejects(saveIR('oversized', oversized), /65,536-frame internal limit/);
});

View File

@@ -6,6 +6,7 @@
try { manifest = JSON.parse(doc.getElementById('ytp-assets').textContent); }
catch { return; } // The index must supply this map; never fetch one during boot.
const assets = new Map(), groups = new Map(), hooks = new Map();
let warmScheduled = false;
const css = new Set([...doc.querySelectorAll('link[data-lazy-css]')].map(link => link.dataset.lazyCss));
const selected = new Map();
const url = path => selected.get(path) || (manifest.files[path]?.h ? path + '?v=' + manifest.files[path].h : './' + path.replace(/^\//,''));
@@ -50,14 +51,18 @@
const style = /\.css$/.test(path);
if (style && css.has(path)) return Promise.resolve();
if (!style && !/\.js$/.test(path)) return Promise.resolve(); // workers/imports/fonts are not page scripts
const task = new Promise((resolve, reject) => {
const loadOnce = () => new Promise((resolve, reject) => {
const node = doc.createElement(style ? 'link' : 'script');
const timer = setTimeout(() => { node.remove?.(); reject(new Error('Timed out loading ' + path)); }, 20000);
if (style) { node.rel = 'stylesheet'; node.href = url(path); }
else { node.async = false; node.src = url(path); }
node.onload = resolve;
node.onerror = () => reject(new Error('Unable to load ' + path));
node.onload = () => { clearTimeout(timer); resolve(); };
node.onerror = () => { clearTimeout(timer); node.remove?.(); reject(new Error('Unable to load ' + path)); };
doc.head.append(node);
});
const task = root.AsyncGuard?.retry
? root.AsyncGuard.retry(loadOnce, { attempts: 3 })
: loadOnce();
assets.set(path, task);
task.catch(() => assets.delete(path));
return task;
@@ -100,10 +105,17 @@
else root.navigator.serviceWorker?.getRegistration().then(send).catch(()=>{});
},
warm() {
if (!root.navigator.serviceWorker || root.navigator.onLine === false) return;
if (warmScheduled || !root.navigator.serviceWorker || root.navigator.onLine === false) return;
warmScheduled = true;
const start = () => {
warmScheduled = false;
if(root.navigator.onLine === false)return;
root.navigator.serviceWorker.ready.then(reg => {
for (const worker of new Set([reg.active, reg.waiting])) worker?.postMessage({type:'COMPLETE_ASSETS'});
}).catch(()=>{});
};
if (root.requestIdleCallback) root.requestIdleCallback(start, { timeout: 8000 });
else setTimeout(start, 5000);
},
onLoad(name, fn) {
if(api.loaded(name)) { Promise.resolve().then(fn).catch(error=>{if(root.CustomEvent)root.dispatchEvent?.(new root.CustomEvent('ytp-lazy-error',{detail:{group:name,error}}));}); return; }

View File

@@ -7,7 +7,7 @@ function fixture(current, held = [], appCache = false, userAgent = 'AppleWebKit/
const manifest = { buildTag: 'own', appCache, groups: { core: { files: [] }, 'layout:classic': { files: ['/classic.css'] }, 'layout:glass-stage': { files: ['/glass.css', '/one.js', '/two.js'] }, 'feature:test': { contract:1, files: ['/one.js', '/two.js'] } }, files: { '/app.js':{h:'a'}, '/classic.css': {h:'c'}, '/glass.css':{h:'g'}, '/one.js':{h:'1'}, '/two.js':{h:'2'} } };
const doc = { readyState:'loading', documentElement: { dataset:{} }, getElementById: () => ({ textContent:JSON.stringify(manifest) }), querySelectorAll: () => [], createElement: tag => ({ tagName:tag.toUpperCase() }), write: value => writes.push(value), addEventListener: (t,f) => listeners[t]=f };
doc.head = { append: node => { inserted.push(node); queueMicrotask(() => node.onload?.()); } };
const root = { document:doc, localStorage:{ getItem:() => '{"settings":{"layout":"glass-stage"}}' }, console, Promise, URL, crypto:{subtle:{}}, fetch:async key=>{fetched.push(key);return new Response('app');}, setTimeout, clearTimeout, navigator:{userAgent,serviceWorker:{ready:Promise.resolve({}),controller:controlled?{}:null,addEventListener(){}}}, addEventListener(){} };
const root = { document:doc, localStorage:{ getItem:() => '{"settings":{"layout":"glass-stage"}}' }, console, Promise, URL, crypto:{subtle:{}}, AsyncGuard:require('./async-guard'), requestIdleCallback:fn=>{root.__idle=fn;}, fetch:async key=>{fetched.push(key);return new Response('app');}, setTimeout, clearTimeout, navigator:{userAgent,serviceWorker:{ready:Promise.resolve({}),controller:controlled?{}:null,addEventListener(){}}}, addEventListener(){} };
if (current) root.caches = { open: async () => ({ match: async key => key === '/__ytp_asset_state' ? new Response(JSON.stringify({current})) : held.includes(key) ? new Response('', {headers:{'X-Asset-Hash':key.split('=')[1]}}) : undefined }) };
root.window=root; root.globalThis=root;
vm.runInNewContext(readFileSync(require.resolve('./lazy.js'),'utf8'), root);
@@ -27,11 +27,13 @@ test('lazy groups execute ordered classic scripts once, sharing concurrent calls
await root.Lazy.load('layout:glass-stage');
assert.equal(inserted.filter(n=>n.tagName==='SCRIPT').length,2);
});
test('failed injection can retry and proxy dispatches only after execution', async () => {
test('transient script injection failure retries before proxy dispatch', async () => {
const {root,inserted}=fixture();
const append=root.document.head.append;
root.document.head.append=n=>{inserted.push(n);queueMicrotask(()=>n.onerror?.());};
await assert.rejects(root.Lazy.load('feature:test'),/one.js/);
let first=true;
root.document.head.append=n=>{inserted.push(n);queueMicrotask(()=>{if(first){first=false;n.onerror?.();}else n.onload?.();});};
await root.Lazy.load('feature:test');
assert.equal(inserted.length,3,'first file is retried, then the second file loads');
root.document.head.append=append;
root.TestApi={open:value=>value+1};
const proxy=root.Lazy.proxy('feature:test',['open'],'TestApi');
@@ -92,6 +94,8 @@ test('online launches request worker completion even with Save-Data and skip off
f.root.navigator.connection={saveData:true};f.root.navigator.onLine=true;
f.root.navigator.serviceWorker={ready:Promise.resolve({active,waiting})};
f.root.Lazy.warm();await Promise.resolve();
assert.equal(sent.length,0,'warming waits until the page is idle');
f.root.__idle();await Promise.resolve();
assert.deepEqual(sent.map(m=>m.type),['COMPLETE_ASSETS','COMPLETE_ASSETS']);
f.root.navigator.onLine=false;f.root.Lazy.warm();await Promise.resolve();assert.equal(sent.length,2);
});

View File

@@ -6,9 +6,10 @@ const source = fs.readFileSync(__dirname + '/app.js', 'utf8');
// Exercise the production persistence/profile functions without starting a DOM player.
const declaration = name => source.match(new RegExp('(?:async )?function ' + name + '\\([^]*?\\n}'))[0];
function fixture(updatedAt) {
const settings = { saveBeforePlay: true, autoPreload: true, layout: 'f7-swipe', eq: { preset: 'custom', g: [1,2,3,4,5] } };
const context = vm.createContext({ WEB: true, data: { settings, profile: { name: 'test', syncedAt: 200 } }, DEFAULT_SETTINGS: { saveBeforePlay: false, autoPreload: true, layout: 'classic' }, API: { saveData: async () => {} }, profileHeaders: () => ({}), scheduleProfilePush: () => context.pushes++, pushes: 0, fetch: async () => ({ status: 200, json: async () => ({ ok: true, name: 'test', updatedAt, data: { settings: { saveBeforePlay: false } } }) }), localStorage: { getItem: () => JSON.stringify({ settings }) } });
vm.runInContext([declaration('loadDataFromStorage'), declaration('applyProfileData'), declaration('pullProfileIfNewer')].join('\n'), context);
const settings = { saveBeforePlay: true, autoPreload: true, layout: 'f7-swipe', eq: { preset: 'custom', g: [1,2,3,4,5] }, jamesDsp: { enabled: true, downloadForOffline: true, preset: 'warm', params: { 'eq.band0': 3 } } };
const defaults = { saveBeforePlay: false, autoPreload: true, layout: 'classic', jamesDsp: { enabled: false, downloadForOffline: false, preset: 'flat', params: {} } };
const context = vm.createContext({ WEB: true, data: { settings, profile: { name: 'test', syncedAt: 200 } }, DEFAULT_SETTINGS: defaults, API: { saveData: async () => {} }, profileHeaders: () => ({}), scheduleProfilePush: () => context.pushes++, pushes: 0, fetch: async () => ({ status: 200, json: async () => ({ ok: true, name: 'test', updatedAt, data: { settings: { saveBeforePlay: false } } }) }), localStorage: { getItem: () => JSON.stringify({ settings }) } });
vm.runInContext([declaration('loadDataFromStorage'), declaration('normalizeJamesDspSettings'), declaration('applyProfileData'), declaration('pullProfileIfNewer')].join('\n'), context);
return context;
}
test('stored settings load verbatim instead of reverting to defaults', () => {
@@ -17,6 +18,7 @@ test('stored settings load verbatim instead of reverting to defaults', () => {
assert.equal(loaded.settings.saveBeforePlay, true);
assert.equal(loaded.settings.layout, 'f7-swipe');
assert.deepEqual(JSON.parse(JSON.stringify(loaded.settings.eq.g)), [1,2,3,4,5]);
assert.deepEqual(JSON.parse(JSON.stringify(loaded.settings.jamesDsp)), { enabled: true, downloadForOffline: true, preset: 'warm', params: { 'eq.band0': 3 } });
});
for (const updatedAt of [100,200]) test(`profile timestamp ${updatedAt} cannot overwrite local settings synced at 200`, async () => {
const c = fixture(updatedAt), previous = c.data.settings;
@@ -30,5 +32,6 @@ test('newer profile intentionally replaces settings and restores missing default
assert.equal(c.data.settings.saveBeforePlay, false);
assert.equal(c.data.settings.autoPreload, true);
assert.equal(c.data.settings.layout, 'classic');
assert.deepEqual(JSON.parse(JSON.stringify(c.data.settings.jamesDsp)), { enabled: false, downloadForOffline: false, preset: 'flat', params: {}, irRef: null });
assert.equal(c.data.profile.syncedAt, 300);
});

View File

@@ -1,4 +1,27 @@
.settings-browser { display: block; width: 100%; min-width: 0; }
.settings-browser, .settings-grid, .settings-overview, .settings-detail, .settings-section,
.settings-browser .settings, .settings-browser .set-group, .settings-browser .dsp-settings,
.settings-browser .dsp-subsection, .settings-browser .dsp-param-list {
box-sizing: border-box;
min-width: 0;
max-width: 100%;
}
/* Settings is a workspace, not a sidebar: give the section browser the full
content area on desktop instead of leaving it inside the fixed 452px list. */
.body:has(#listPane .cards[data-view="settings"]) .player-pane { display: none; }
.body:has(#listPane .cards[data-view="settings"]) #listPane {
flex: 1 1 0;
width: 100%;
min-width: 0;
max-width: 100%;
border-left: 0;
}
.body:has(#listPane .cards[data-view="settings"]) #listPane .cards {
width: 100%;
min-width: 0;
max-width: 100%;
overflow-x: hidden;
}
.settings-browser [hidden] { display: none !important; }
.settings-search { margin-bottom: 12px; }
.settings-search input { width: 100%; min-height: 44px; background: var(--bg-2); color: var(--text); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; font: inherit; }
@@ -11,10 +34,81 @@
.settings-section-row:hover, .settings-section-row[aria-current="true"] { background: var(--bg-3); border-radius: 8px; }
.settings-browser :is(button,input,select,textarea):focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.settings-back { min-height: 44px; padding: 8px 12px; margin-bottom: 12px; background: var(--bg-2); color: var(--text); border: 1px solid var(--line); border-radius: 8px; font: inherit; cursor: pointer; }
.settings-browser .set-row { min-height: 44px; }
.settings-browser .set-row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, min(40%, 260px));
align-items: center;
gap: 12px;
min-height: 44px;
min-width: 0;
max-width: 100%;
}
.settings-browser .set-row > :is(span, input, select, button, output) { min-width: 0; max-width: 100%; }
.settings-browser .set-row > :is(input, select, button, output) { box-sizing: border-box; }
.settings-browser .set-control-wrap { display: block; width: 100%; min-width: 0; max-width: 100%; overflow: hidden; }
#listPane #cards .settings-browser .set-row select,
#listPane #cards .settings-browser .set-control-wrap select,
.settings-browser .set-row select,
.settings-browser .set-control-wrap select {
box-sizing: border-box;
appearance: none;
-webkit-appearance: none;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
padding-right: 28px;
background-color: var(--bg-3);
background-image: linear-gradient(45deg, transparent 50%, var(--text-dim) 50%), linear-gradient(135deg, var(--text-dim) 50%, transparent 50%);
background-position: calc(100% - 14px) 50%, calc(100% - 9px) 50%;
background-size: 5px 5px;
background-repeat: no-repeat;
color: var(--text);
border-color: var(--line);
}
.settings-browser .set-row > span:first-child { overflow-wrap: anywhere; }
.settings-browser .set-row:has(> span:only-child) { grid-template-columns: minmax(0, 1fr); }
.settings-browser .set-row small { font-size: 12px; max-width: 100%; }
.settings-browser .set-row > span { min-width: 0; }
.settings-browser .set-row input[type="range"] { max-width: 42%; }
.settings-browser .set-row input[type="range"] { width: calc(100% - 16px); max-width: calc(100% - 16px); min-width: 0; }
.settings-browser .set-row input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
justify-self: end;
width: 46px;
height: 28px;
min-width: 46px;
border: 1px solid var(--line);
border-radius: 999px;
background: radial-gradient(circle at 14px 50%, var(--text) 0 9px, transparent 10px), var(--bg-3);
cursor: pointer;
transition: background .16s ease, border-color .16s ease;
}
.settings-browser .set-row input[type="checkbox"]:checked {
border-color: var(--accent);
background: radial-gradient(circle at 32px 50%, var(--on-accent, #fff) 0 9px, transparent 10px), var(--accent);
}
.settings-browser .set-row input[type="checkbox"]:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.dsp-file-control {
position: relative;
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
align-items: center;
gap: 9px;
width: 100%;
min-width: 0;
max-width: 100%;
}
.dsp-file-control input[type="file"] { position: absolute; width: 1px; height: 1px; min-width: 0; max-width: 1px; padding: 0; border: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.dsp-file-control:focus-within { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 8px; }
.dsp-file-button { display: inline-flex; align-items: center; justify-content: center; min-height: 40px; padding: 7px 12px; border: 1px solid var(--line); border-radius: 9px; background: var(--bg-3); color: var(--text); font: 600 12px var(--ui); white-space: nowrap; }
.dsp-file-name { display: block; min-width: 0; overflow: hidden; color: var(--text-2); text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
.dsp-subsection .sp-note { min-width: 0; max-width: 100%; overflow-wrap: anywhere; }
.dsp-subsection > .btn { min-width: 0; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.dsp-actions { min-width: 0; max-width: 100%; }
.dsp-param-list { grid-template-columns: repeat(auto-fit, minmax(min(190px, 100%), 1fr)); }
.dsp-param-row input[type="range"] { width: calc(100% - 16px); min-width: 0; max-width: calc(100% - 16px); }
.settings-browser .settings-detail { display: none; min-width: 0; }
.settings-browser[data-detail="1"] .settings-overview { display: none; }
.settings-browser[data-detail="1"] .settings-detail { display: block; }
@@ -22,7 +116,7 @@
.settings-grid { display: grid; grid-template-columns: minmax(160px, .8fr) minmax(0, 1.4fr); gap: 16px; }
.settings-browser .settings-overview, .settings-browser[data-detail="1"] .settings-overview, .settings-browser .settings-detail { display: block; }
.settings-back { display: none; }
.settings-browser .set-row { flex-wrap: wrap; gap: 12px; }
.settings-browser .set-row { flex-wrap: nowrap; gap: 12px; }
}
.download-job { padding: 14px 0; border-bottom: 1px solid var(--line); display: grid; gap: 8px; }
.download-job b { overflow-wrap: anywhere; }

View File

@@ -42,7 +42,9 @@ test('assets.json describes the complete existing shell exactly once with eager
}
for (const asset of shell) if (asset !== '/') assert.ok(described.has(asset), `${asset} is described`);
// piano-engine is dynamically imported and historically absent from SHELL.
for (const asset of described) assert.ok(listed.has(asset) || asset === '/piano-engine.mjs', `${asset} shell or documented dynamic import`);
// Piano and JamesDSP load only through build-local dynamic module URLs.
const dynamicOnly = new Set(['/piano-engine.mjs', ...groups['feature:jamesdsp'].files]);
for (const asset of described) assert.ok(listed.has(asset) || dynamicOnly.has(asset), `${asset} shell or documented dynamic import`);
assert.equal(groups.core.eager, true);
for (const name of ['playlist', 'settings', 'service-mode', 'lyrics-editor']) {
assert.equal(groups[`feature:${name}`].eager, true);

View File

@@ -1159,6 +1159,15 @@ input[type="range"]::-webkit-slider-thumb:hover { transform: scale(1.25); }
.set-row > span { display: flex; flex-direction: column; gap: 3px; color: var(--text); font-size: 13.5px; font-weight: 500; }
.set-row small { color: var(--text-dim); font-size: 11.5px; font-weight: 400; line-height: 1.4; max-width: 280px; }
.set-row input[type="range"] { width: 150px; }
.dsp-settings { margin-top: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--bg-2); }
.dsp-settings .set-group-title { padding: 0 0 8px; }
.dsp-param-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 0 14px; }
.dsp-param-row input[type="range"] { width: min(46vw, 190px); }
.dsp-actions { display: flex; flex-wrap: wrap; gap: 8px; padding: 10px 0; }
.dsp-actions .btn { color: var(--text); }
.dsp-subsection { margin: 14px 0; padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg-1); }
.dsp-subsection h4 { margin: 0 0 8px; color: var(--text); }
.dsp-risk { padding: 9px 11px; border-radius: 8px; color: var(--text); background: color-mix(in srgb, var(--accent) 13%, var(--bg-2)); font-size: .9em; }
.set-row input[type="checkbox"] { width: 17px; height: 17px; accent-color: var(--accent); cursor: pointer; }
.about-version { color: var(--text-dim); font-size: 12px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; user-select: text; }
.set-select {

View File

@@ -70,6 +70,7 @@ const SHELL = [
'/glass-panel-layout.js',
'/theme-classic.css',
'/recommendations.css',
'/audio-graph.js',
'/flag-ui.js',
'/export.js',
'/async-guard.js',
@@ -264,7 +265,8 @@ self.addEventListener('fetch', (e) => {
return;
}
if (ASSET_SYNC && request.mode === 'navigate') e.waitUntil(completeAssets());
// The page schedules completion after first paint/idle via Lazy.warm(). Do
// not start a six-file background burst from this foreground fetch event.
// Only intercept GET/HEAD — let POST (sync endpoint) go through unmodified
if (request.method !== 'GET' && request.method !== 'HEAD') return;
@@ -304,13 +306,18 @@ self.addEventListener('fetch', (e) => {
const playingClients = new Map(), deferredClients = new Set();
let activeLayout = 'classic', layoutReply;
let completionTask;
function completeAssets(force = false) {
function completeAssets(force = false, requestedOptIns) {
if (!ASSET_SYNC) return Promise.resolve();
if (completionTask) {
if (!requestedOptIns) return completionTask;
return completionTask.finally(() => completeAssets(true, requestedOptIns));
}
completionTask ||= (async () => {
const cache = await caches.open(AssetSyncCore.CACHE);
const m = (await AssetSyncCore.state(cache))?.current;
if (!m || m.buildTag !== VERSION) return;
const job = await AssetSyncCore.complete(m, { cache, fetchFn: fetch, force,
const optIns = requestedOptIns || await AssetSyncCore.readOptIns(cache);
const job = await AssetSyncCore.complete(m, { cache, fetchFn: fetch, force, optIns,
notify: async status => {
for (const client of await self.clients.matchAll({ type: 'window' }))
client.postMessage({ type: 'OFFLINE_STATUS', ...status });
@@ -329,6 +336,16 @@ self.addEventListener('sync', e => {
if (e.tag === 'ytp-offline-complete') e.waitUntil(completeAssets());
});
self.addEventListener('message', (e) => {
if (ASSET_SYNC && e.data?.type === 'OFFLINE_OPT_INS' && Array.isArray(e.data.values)) {
e.waitUntil((async () => {
const cache = await caches.open(AssetSyncCore.CACHE);
const current = (await AssetSyncCore.state(cache))?.current || await candidate(cache);
const allowed = new Set(Object.values(current?.groups || {}).map(group => group.offlineOptIn).filter(Boolean));
const values = [...new Set(e.data.values.filter(value => typeof value === 'string' && allowed.has(value)))];
await cache.put(AssetSyncCore.OPT_INS, Response.json(values));
await completeAssets(true, values);
})());
}
if (ASSET_SYNC && e.data?.type === 'LAYOUT' && e.source && typeof e.data.value === 'string') {
activeLayout = e.data.value;
layoutReply?.();
@@ -535,6 +552,10 @@ async function installAssets() {
for(const name of layouts)for(const dependency of m.groups[name].dependencies || [])layouts.add(dependency);
await AssetSyncCore.syncAssets(m,{cache,fetchFn:fetchAsset,groups:[...layouts]});
}
// Copy and hash legacy shell entries before the candidate reaches `installed`.
// A legacy page's Refresh UI then activates quickly, before its four-second
// reload safety timer can send it back into the old shell.
m.legacyCacheNames = await migrateLegacy(cache,m);
await cache.put(candidateKey, new Response(JSON.stringify(m)));
}
async function migrateLegacy(cache, m) {
@@ -565,7 +586,11 @@ async function migrateLegacy(cache, m) {
async function activateAssets() {
const cache = await caches.open(AssetSyncCore.CACHE), m = await candidate(cache);
if (!m) throw Error('Missing candidate manifest');
const names = await migrateLegacy(cache,m), old = await AssetSyncCore.state(cache);
// Legacy migration is staged by installAssets. Keep the fallback for
// candidates created by an older worker version.
const names = m.legacyCacheNames || await migrateLegacy(cache,m);
delete m.legacyCacheNames;
const old = await AssetSyncCore.state(cache);
const previousClients = (await self.clients.matchAll({type:'window'})).map(c=>c.id);
await AssetSyncCore.commit(m,cache,{previousClients,activeLayout:m.activeLayout || activeLayout});
// Legacy deletion occurs strictly after verified commit.
@@ -573,8 +598,8 @@ async function activateAssets() {
for (const req of await cache.keys()) if(new URL(req.url).pathname.startsWith('/__ytp_candidate/')) await cache.delete(req);
await self.clients.claim();
if(old && old.current.buildTag !== m.buildTag) for(const c of await self.clients.matchAll({type:'window',includeUncontrolled:true})) c.postMessage({type:'SW_UPDATE_AVAILABLE',version:VERSION});
// Completion owns a message-event lifetime, not the activation barrier.
// In particular, a legacy client's four-second reload must not wait for it.
// Resume completion after activation, but with one request at a time so
// foreground navigation retains most of the available bandwidth.
self.registration.active.postMessage({ type: 'COMPLETE_ASSETS' });
try { console.info('[asset-sync] storage', await self.navigator.storage.estimate()); } catch {}
}

674
frontend/vendor/jamesdsp/LICENSE.txt vendored Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

17
frontend/vendor/jamesdsp/README.md vendored Normal file
View File

@@ -0,0 +1,17 @@
# JamesDSP vendor files
The browser port's worklet, 8–96 kHz streaming sample-rate adapter, matrix
convolver, HRTF/virtual-speaker spatial stage, generated IRs and IndexedDB IR
store are pinned to the source revision in VERSION.txt. Runtime files stay in
the lazy `feature:jamesdsp` group. A user must enable the engine or choose
“Download audio effects for offline” before the offline-completion job caches
them, including the WASM binary.
The adapted wrapper resolves dependencies through `Lazy.url()` and routes the
worklet through the existing AudioGraph. It rejects Liveprog, DDC and arbitrary
text effects. Impulse responses are limited to 65,536 internal frames; lower-
power devices use a 24,000-frame cap and warn before larger responses are used.
The port is GPL-3.0-or-later (`LICENSE.txt`). The upstream license snapshot says
GPL-2.0; both supplied notices remain in this directory pending upstream
clarification. See VERSION.txt for the adaptation record.

View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

18
frontend/vendor/jamesdsp/VERSION.txt vendored Normal file
View File

@@ -0,0 +1,18 @@
JamesDSP browser port source revision: a982b53c4ab347d1d9c50f4ce7ee3c2735eaa817
Repository: /home/josh/development/personal/jamesdsp-web (main)
Vendored source files: web/jamesdsp-node.js, params.js, ir-utils.js,
ir-builtins.js, ir-store.js, worklet.js, dsp/jamesdsp.js and dsp/jamesdsp.wasm.
Integration adaptations: wrapper dependencies and WASM URLs use the page's
manifest-hashed Lazy.url map; the worklet statically imports the pinned
jamesdsp-a982b53.mjs module because AudioWorkletGlobalScope rejects dynamic
import. The wrapper keeps the shared AudioGraph route and does not create a
MediaElementSource. Liveprog, DDC and arbitrary text effects are rejected and
not serialized in ytplayer. All runtime code remains in lazy feature:jamesdsp;
its offline completion membership requires the explicit jamesDsp opt-in.
The generated engine, parameter tables, IR utilities/store and built-in IR set
are copied from the pinned revision. The uploaded/generated IR cap is 65,536
frames at the internal 44.1/48 kHz rate (low-power devices use 24,000 frames).
License provenance: LICENSE.txt is the port's GPL-3.0-or-later license. The
upstream snapshot at upstream/Main/LICENSE contains GPL-2.0 text; see README.md.

File diff suppressed because one or more lines are too long

BIN
frontend/vendor/jamesdsp/dsp/jamesdsp.wasm vendored Executable file

Binary file not shown.

View File

@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-or-later
const definitions={
'Small room':{seconds:.5,rt60:.25,seed:0x51a11},
Hall:{seconds:2,rt60:1.4,seed:0x4a11},
Plate:{seconds:1.5,rt60:1,seed:0x91a7e},
Cathedral:{seconds:5,rt60:4,seed:0xca7ed},
};
export const BUILTIN_IRS=Object.freeze(Object.fromEntries(Object.entries(definitions).map(([name,d])=>[name,Object.freeze({...d,version:1})])));
export function generateIR(name,sampleRate,channels=2,{maxFrames=65536}={}) {
const spec=BUILTIN_IRS[name];if(!spec||!Number.isInteger(sampleRate)||sampleRate<8000||sampleRate>96000||![1,2,4].includes(channels)) throw new RangeError('Unsupported generated IR');
const frames=Math.max(1,Math.min(Math.round(spec.seconds*sampleRate),maxFrames));let seed=spec.seed>>>0;
const paths=Array.from({length:channels},()=>new Float32Array(frames));
const next=()=>{seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/0x100000000*2-1;};
for(let path=0;path<channels;path++) {
const x=paths[path];x[0]=1;
for(let tap=1;tap<Math.min(24,frames);tap++) {const at=Math.min(frames-1,Math.round(sampleRate*(.004+tap*.009+next()*.001)));x[at]+=(next()*.22)/(1+tap*.25);}
for(let i=1;i<frames;i++) {const t=i/sampleRate, fade=Math.min(1,t/.012,(frames-i)/Math.max(1,sampleRate*.02));x[i]+=next()*.045*Math.exp(-6.91*t/spec.rt60)*Math.max(0,fade);}
}
let peak=0;for(const path of paths) for(const value of path) peak=Math.max(peak,Math.abs(value));
for(const path of paths) for(let i=0;i<path.length;i++) path[i]*=.5/peak;
return {name,sampleRate,numberOfChannels:channels,length:frames,seed:spec.seed,version:1,truncated:frames<spec.seconds*sampleRate,getChannelData:i=>paths[i]};
}

24
frontend/vendor/jamesdsp/ir-store.mjs vendored Normal file
View File

@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-or-later
const DB='jamesdsp-ir', STORE='irs', VERSION=1;
function openDB() {
if(!globalThis.indexedDB) return Promise.reject(new Error('IndexedDB is unavailable'));
return new Promise((resolve,reject)=>{const request=indexedDB.open(DB,VERSION);request.onupgradeneeded=()=>request.result.createObjectStore(STORE,{keyPath:'name'});request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);});
}
async function transaction(mode,action) {
const db=await openDB();return new Promise((resolve,reject)=>{const tx=db.transaction(STORE,mode),store=tx.objectStore(STORE);let result;try {result=action(store);} catch(error){db.close();reject(error);return;}tx.oncomplete=()=>{db.close();resolve(result);};tx.onerror=()=>{db.close();reject(tx.error);};tx.onabort=()=>{db.close();reject(tx.error||new Error('IR storage transaction aborted'));};});
}
async function digest(data) {const hash=await crypto.subtle.digest('SHA-256',data);return [...new Uint8Array(hash)].map(x=>x.toString(16).padStart(2,'0')).join('');}
export async function saveIR(name,buffer,metadata={}) {
if(typeof name!=='string'||!name.trim()||name.length>100||![1,2,4].includes(buffer?.numberOfChannels)||!Number.isFinite(buffer.sampleRate)||buffer.sampleRate<8000||buffer.sampleRate>96000||!buffer.length) throw new TypeError('Invalid named impulse response');
const internalRate=buffer.sampleRate===44100?44100:48000;
if(Math.round(buffer.length*internalRate/buffer.sampleRate)>65536) throw new RangeError('Stored impulse response exceeds the 65,536-frame internal limit');
const channels=Array.from({length:buffer.numberOfChannels},(_,i)=>new Float32Array(buffer.getChannelData(i)));
const pcm=new Float32Array(channels.length*buffer.length);for(let i=0;i<buffer.length;i++)for(let c=0;c<channels.length;c++)pcm[i*channels.length+c]=channels[c][i];
const record={name:name.trim(),sampleRate:buffer.sampleRate,channels:channels.length,frames:buffer.length,pcm,metadata:{...metadata},hash:await digest(pcm.buffer),version:1};
await transaction('readwrite',s=>s.put(record));return {name:record.name,hash:record.hash};
}
export async function getIR(name) {
const db=await openDB();return new Promise((resolve,reject)=>{const r=db.transaction(STORE,'readonly').objectStore(STORE).get(name);r.onsuccess=async()=>{try {const x=r.result;if(!x){resolve(null);return;}if(await digest(x.pcm.buffer)!==x.hash)throw new Error('Stored IR hash mismatch');const channels=Array.from({length:x.channels},()=>new Float32Array(x.frames));for(let i=0;i<x.frames;i++)for(let c=0;c<x.channels;c++)channels[c][i]=x.pcm[i*x.channels+c];resolve({...x,buffer:{sampleRate:x.sampleRate,numberOfChannels:x.channels,length:x.frames,getChannelData:i=>channels[i]}});}catch(e){reject(e);}finally{db.close();}};r.onerror=()=>{db.close();reject(r.error);};});
}
export async function listIRs() {const db=await openDB();return new Promise((resolve,reject)=>{const r=db.transaction(STORE,'readonly').objectStore(STORE).getAll();r.onsuccess=()=>{db.close();resolve(r.result.map(({name,hash,sampleRate,channels,frames,metadata})=>({name,hash,sampleRate,channels,frames,metadata})));};r.onerror=()=>{db.close();reject(r.error);};});}
export async function deleteIR(name) {await transaction('readwrite',s=>s.delete(name));}

43
frontend/vendor/jamesdsp/ir-utils.mjs vendored Normal file
View File

@@ -0,0 +1,43 @@
// SPDX-License-Identifier: GPL-3.0-or-later
const copyBuffer=(buffer,rate=buffer.sampleRate)=>{
const channels=Array.from({length:buffer.numberOfChannels},(_,i)=>new Float32Array(buffer.getChannelData(i)));
return {sampleRate:rate,numberOfChannels:channels.length,length:channels[0]?.length||0,getChannelData:i=>channels[i]};
};
export async function decodeIR(context,bytes) {
const decoded=await context.decodeAudioData(bytes.slice(0));
return resampleIR(decoded,context.sampleRate);
}
export function resampleIR(buffer,targetRate) {
if(!Number.isFinite(targetRate)||targetRate<8000||targetRate>96000||!buffer?.numberOfChannels||buffer.numberOfChannels>4||!buffer.length) throw new RangeError('Invalid IR or target sample rate');
if(buffer.sampleRate===targetRate) return copyBuffer(buffer,targetRate);
const length=Math.max(1,Math.round(buffer.length*targetRate/buffer.sampleRate));
const channels=[];
for(let ch=0;ch<buffer.numberOfChannels;ch++) {
const input=buffer.getChannelData(ch), output=new Float32Array(length), ratio=buffer.sampleRate/targetRate;
for(let i=0;i<length;i++) {const x=i*ratio, a=Math.min(Math.floor(x),input.length-1), b=Math.min(a+1,input.length-1), f=x-a;output[i]=input[a]*(1-f)+input[b]*f;}
channels.push(output);
}
return {sampleRate:targetRate,numberOfChannels:channels.length,length,getChannelData:i=>channels[i]};
}
export function trimIR(buffer,{thresholdDb=-80}={}) {
if(!Number.isFinite(thresholdDb)||thresholdDb>0||thresholdDb<-160) throw new RangeError('Invalid trim threshold');
const channels=Array.from({length:buffer.numberOfChannels},(_,i)=>buffer.getChannelData(i));
const threshold=10**(thresholdDb/20);let first=buffer.length,last=-1;
for(let i=0;i<buffer.length;i++) {let peak=0;for(const channel of channels) peak=Math.max(peak,Math.abs(channel[i]));if(peak>=threshold){first=Math.min(first,i);last=i;}}
if(last<0) first=last=0;
const result=channels.map(channel=>channel.slice(first,last+1));
return {buffer:{sampleRate:buffer.sampleRate,numberOfChannels:result.length,length:result[0]?.length||0,getChannelData:i=>result[i]},startFrame:first,endFrame:last+1};
}
export function normalizeIR(buffer,{peak=0.5}={}) {
if(!Number.isFinite(peak)||peak<=0||peak>1) throw new RangeError('Peak must be in (0, 1]');
const channels=Array.from({length:buffer.numberOfChannels},(_,i)=>new Float32Array(buffer.getChannelData(i)));
let max=0;for(const channel of channels) for(const value of channel) max=Math.max(max,Math.abs(value));
const gain=max===0?1:peak/max;for(const channel of channels) for(let i=0;i<channel.length;i++) channel[i]*=gain;
return {sampleRate:buffer.sampleRate,numberOfChannels:channels.length,length:channels[0]?.length||0,getChannelData:i=>channels[i]};
}
export function prepareIR(context,buffer,{trim=false,normalize=true,peak=0.5,thresholdDb=-80}={}) {
let result=resampleIR(buffer,context.sampleRate);
if(trim) result=trimIR(result,{thresholdDb}).buffer;
if(normalize) result=normalizeIR(result,{peak});
return result;
}

View File

@@ -0,0 +1,246 @@
/* Lazy classic-script bridge for the optional JamesDSP ES module and worklet. */
(function (root) {
'use strict';
let irToolsPromise;
const irTools = () => irToolsPromise ||= Promise.all([
import(root.Lazy.url('/vendor/jamesdsp/ir-utils.mjs')),
import(root.Lazy.url('/vendor/jamesdsp/ir-builtins.mjs')),
import(root.Lazy.url('/vendor/jamesdsp/ir-store.mjs')),
]).then(([utils,builtins,store])=>({utils,builtins,store}));
const PRESETS = Object.freeze({
flat: { name: 'Flat', params: {} },
bass: { name: 'Bass', params: { 'eq.enabled': 1, 'eq.band0': 4, 'eq.band1': 3, 'bass.enabled': 1, 'bass.boost': 5, gain: -3 } },
vocal: { name: 'Vocal', params: { 'eq.enabled': 1, 'eq.band5': 2, 'eq.band7': 3, 'eq.band9': 2, 'compressor.enabled': 1 } },
loudness: { name: 'Loudness', params: { 'limiter.threshold': -3, gain: 2 } },
headphone: { name: 'Headphone', params: { 'crossfeed.enabled': 1, 'crossfeed.mode': 1 } },
bright: { name: 'Bright', params: { 'eq.enabled': 1, 'eq.band9': 2, 'eq.band10': 3, 'eq.band11': 3, 'eq.band12': 2 } },
warm: { name: 'Warm', params: { 'eq.enabled': 1, 'eq.band0': 3, 'eq.band1': 2, 'eq.band7': -1, gain: -2 } },
});
const clampGain = value => Math.max(-24, Math.min(12, Number(value) || 0));
function createController(options) {
const graph = options.graph;
let desired = false, active = false, bypassed = false, nodeEntry = null, gainNode = null, context = null;
let elements = [], standardInput = null, levelDb = 0, settings = null;
let tail = Promise.resolve(), maxLiveHeaps = 0, liveHeaps = 0, nodesCreated = 0, nodesDestroyed = 0, loadedIRRef = null;
let faultListener = null, notifying = false, dspAnalyser = null;
const serial = fn => {
const result = tail.then(fn, fn);
tail = result.catch(() => {});
return result;
};
function snapshot() { return { active, desired, bypassed, route: active && !bypassed ? 'jamesdsp' : 'standard', liveHeaps, maxLiveHeaps, nodesCreated, nodesDestroyed, sampleRate: context?.sampleRate || null, irRef: loadedIRRef }; }
function routeStandard() {
if (!elements.length) return;
try {
graph.routeAll(elements, standardInput || context?.destination);
} catch (error) {
try { if (context?.destination) graph.routeAll(elements, context.destination); } catch { /* direct graph route is the last audible fallback */ }
throw error;
}
}
function releaseNode() {
const entry = nodeEntry;
nodeEntry = null;
if (faultListener && entry) entry.node.removeEventListener('error', faultListener);
faultListener = null;
try { entry?.node.node.disconnect(); } catch { /* already disconnected */ }
try { gainNode?.disconnect(); } catch { /* already disconnected */ }
gainNode = null;
try { dspAnalyser?.disconnect(); } catch { /* already disconnected */ }
dspAnalyser = null;
if (entry) {
try { entry.node.destroy(); } catch { /* continue freeing references */ }
loadedIRRef = null;
if (entry.live) { entry.live = false; liveHeaps = Math.max(0, liveHeaps - 1); nodesDestroyed++; }
}
}
function fail(error) {
desired = false;
active = false;
bypassed = false;
try { routeStandard(); } catch { /* graph route has already tried a direct audible fallback */ }
releaseNode();
if (!notifying) {
notifying = true;
try { options.onError?.(error instanceof Error ? error : new Error(String(error || 'JamesDSP failed'))); }
finally { notifying = false; }
}
}
function rampGain(value) {
if (!gainNode || !context) return;
const param = gainNode.gain;
const now = context.currentTime || 0;
if (context.state !== 'running' || typeof param.linearRampToValueAtTime !== 'function') {
param.value = value;
return;
}
param.cancelScheduledValues?.(now);
param.setValueAtTime?.(param.value, now);
param.linearRampToValueAtTime(value, now + 0.018);
}
async function configure(instance, nextSettings, nextLevelDb) {
const preset = PRESETS[nextSettings?.preset] || PRESETS.flat;
const params = { ...preset.params, ...(nextSettings?.params || {}) };
if (Number(params['spatial.enabled']) && Number(params['crossfeed.enabled'])) params['crossfeed.enabled'] = 0;
params.gain = clampGain((Number(params.gain) || 0) + (Number(nextLevelDb) || 0));
params.bypass = 1;
if (active && context?.state === 'running') {
rampGain(0);
await new Promise(resolve => setTimeout(resolve, 20));
}
await instance.setBypass(true);
const ref = nextSettings?.irRef;
const needsIR = ref && (loadedIRRef?.name !== ref.name || loadedIRRef?.hash !== ref.hash);
await instance.applyPreset(needsIR ? { params, irRef: ref } : params);
if (needsIR) loadedIRRef = { name: ref.name, hash: ref.hash };
await instance.setParam('gain', params.gain);
if (desired) await instance.setBypass(bypassed);
if (desired) rampGain(1);
}
async function loadNode(audioContext) {
const moduleURL = root.Lazy.url('/vendor/jamesdsp/jamesdsp-node.mjs');
const { JamesDSPNode } = await import(moduleURL);
return JamesDSPNode.create(audioContext, {
wasmURL: root.Lazy.url('/vendor/jamesdsp/dsp/jamesdsp.wasm'),
paramsURL: root.Lazy.url('/vendor/jamesdsp/params.mjs'),
workletURL: root.Lazy.url('/vendor/jamesdsp/worklet.mjs'),
});
}
async function enable(nextSettings, nextLevelDb = levelDb) {
desired = true;
settings = nextSettings || {};
levelDb = Number(nextLevelDb) || 0;
return serial(async () => {
if (!desired) return false;
const prepared = await options.prepareGraph();
context = prepared.context;
elements = prepared.elements;
standardInput = prepared.standardInput;
if (!Number.isFinite(context?.sampleRate) || context.sampleRate < 8000 || context.sampleRate > 96000) throw new RangeError(`JamesDSP supports 8–96 kHz; this device uses ${context?.sampleRate || 'unknown'} Hz`);
if (!desired) return false;
let instance = nodeEntry?.node;
if (!instance) {
instance = await (options.loadNode || loadNode)(context);
if (!desired) { try { instance.destroy(); } catch {} return false; }
nodeEntry = { node: instance, live: true };
liveHeaps++; nodesCreated++; maxLiveHeaps = Math.max(maxLiveHeaps, liveHeaps);
faultListener = event => fail(event.detail || new Error('JamesDSP processing failed'));
instance.addEventListener('error', faultListener);
gainNode = context.createGain();
gainNode.gain.value = 1;
instance.node.connect(gainNode);
gainNode.connect(context.destination);
}
if (!desired) { releaseNode(); return false; }
await configure(instance, settings, levelDb);
if (!desired) { releaseNode(); return false; }
if (context.state === 'suspended') await context.resume().catch(() => {});
graph.routeAll(elements, bypassed ? standardInput : instance.node);
active = true;
return true;
}).catch(error => { fail(error); throw error; });
}
function disable() {
desired = false;
bypassed = false;
if (active) {
active = false;
try { routeStandard(); } catch { /* routeStandard tried its direct fallback */ }
}
return serial(async () => { releaseNode(); return true; });
}
function setLevelDb(value) {
levelDb = Number(value) || 0;
if (!desired) return Promise.resolve(false);
return enable(settings, levelDb);
}
function changeBypass(value) {
if (!nodeEntry) return Promise.resolve(false);
return serial(async () => {
const next = Boolean(value);
if (next === bypassed) return bypassed;
// A/B bypass is an exact route around the worklet. This preserves the
// Standard graph sample-for-sample instead of relying on DSP bypass math.
if (!next) await nodeEntry.node.setBypass(false);
if (active) {
rampGain(0);
await new Promise(resolve => setTimeout(resolve, 20));
graph.routeAll(elements, next ? standardInput : nodeEntry.node);
rampGain(next ? 0 : 1);
}
if (next) await nodeEntry.node.setBypass(true);
bypassed = next;
return bypassed;
}).catch(error => { fail(error); throw error; });
}
function setBypass(value) { return changeBypass(value); }
function toggleBypass() { return changeBypass(!bypassed); }
function loadIR(buffer, reference = null) {
if (!active || !nodeEntry) return Promise.reject(new Error('Enable JamesDSP before loading an impulse response'));
return serial(async () => {
if (!active || !nodeEntry) throw new Error('JamesDSP is no longer active');
rampGain(0);
try { await nodeEntry.node.loadIR(buffer, reference); loadedIRRef = reference ? { name: reference.name, hash: reference.hash } : null; await nodeEntry.node.setParam('convolver.enabled', 1); }
finally { if (active && desired) rampGain(1); }
return true;
}).catch(error => { fail(error); throw error; });
}
function analyser() {
if (!active || !gainNode || !context) return null;
if (!dspAnalyser) {
dspAnalyser = context.createAnalyser();
dspAnalyser.fftSize = 128;
dspAnalyser.smoothingTimeConstant = 0.78;
gainNode.disconnect();
gainNode.connect(dspAnalyser);
dspAnalyser.connect(context.destination);
}
return dspAnalyser;
}
return { enable, disable, setLevelDb, setBypass, toggleBypass, loadIR, analyser, get active() { return active; }, get desired() { return desired; }, state: snapshot };
}
async function generateIR(name, sampleRate, channels = 2, maxFrames = 65536) {
const {builtins}=await irTools();
return builtins.generateIR(name,sampleRate,channels,{maxFrames});
}
async function decodeIR(context, bytes) { const {utils}=await irTools();return utils.decodeIR(context,bytes); }
async function prepareIR(context, buffer, maxFrames = 65536) {
const {utils}=await irTools();
const rate=context.sampleRate===44100?44100:48000;
const prepared=utils.resampleIR(utils.prepareIR(context,buffer,{normalize:false}),rate);
if (![1,2,4].includes(prepared.numberOfChannels) || prepared.length<1 || prepared.length>Math.min(65536,maxFrames)) throw new RangeError(`Impulse response exceeds the ${Math.min(65536,maxFrames)}-frame internal limit`);
return prepared;
}
async function saveIR(name, buffer, metadata) { const {store}=await irTools();return store.saveIR(name,buffer,metadata); }
async function getIR(name) { const {store}=await irTools();return store.getIR(name); }
async function listIRs() { const {store}=await irTools();return store.listIRs(); }
async function deleteIR(name) { const {store}=await irTools();return store.deleteIR(name); }
const api = { PRESETS, createController, generateIR, decodeIR, prepareIR, saveIR, getIR, listIRs, deleteIR };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else {
root.YT = root.YT || {};
root.YT.JamesDSPFeature = api;
}
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,84 @@
// SPDX-License-Identifier: GPL-3.0-or-later
function assetURL(path, fallback) { return globalThis.Lazy?.url?.(path) || new URL(fallback, import.meta.url); }
const [parameterAPI, irUtils, irStore] = await Promise.all([
import(assetURL('/vendor/jamesdsp/params.mjs', './params.mjs')),
import(assetURL('/vendor/jamesdsp/ir-utils.mjs', './ir-utils.mjs')),
import(assetURL('/vendor/jamesdsp/ir-store.mjs', './ir-store.mjs')),
]);
const {DEFAULT_PARAMS, validateParam} = parameterAPI;
const {prepareIR,resampleIR} = irUtils;
const {getIR} = irStore;
const moduleLoads = new WeakMap();
export class JamesDSPNode extends EventTarget {
static async create(context, {wasmURL=assetURL('/vendor/jamesdsp/dsp/jamesdsp.wasm','./dsp/jamesdsp.wasm'), workletURL=assetURL('/vendor/jamesdsp/worklet.mjs','./worklet.mjs')}={}) {
if (!Number.isFinite(context.sampleRate)||context.sampleRate<8000||context.sampleRate>96000) throw new RangeError('AudioContext rate must be 8–96 kHz');
if (!moduleLoads.has(context)) moduleLoads.set(context,new Map());
const cache=moduleLoads.get(context), key=String(workletURL);
if (!cache.has(key)) cache.set(key,context.audioWorklet.addModule(workletURL).catch(e=>{cache.delete(key);throw e;}));
const response=await fetch(wasmURL);
if (!response.ok) throw new Error(`WASM fetch failed: ${response.status}`);
const wasmBytes=await response.arrayBuffer();
await cache.get(key);
const wrapper=new JamesDSPNode(context,wasmBytes);
try { await wrapper.ready; return wrapper; } catch(e) { wrapper.destroy(); throw e; }
}
constructor(context,wasmBytes) {
super(); this.context=context; this.defaultParams=Object.fromEntries(Object.entries(DEFAULT_PARAMS).filter(([name])=>!/^(?:liveprog|ddc|arbitrary)\./.test(name))); this.params={...this.defaultParams}; this.pending=new Map(); this.serial=0; this.destroyed=false; this.source=null; this.irRef=null;
this.node=new AudioWorkletNode(context,'jamesdsp',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],channelCount:2,channelCountMode:'explicit',processorOptions:{wasmBytes}});
this.ready=new Promise((resolve,reject)=> {
const timer=setTimeout(()=>reject(new Error('DSP initialization timed out')),15000);
this.node.onprocessorerror=()=>{const error=new Error('DSP processor stopped');clearTimeout(timer);reject(error);this.fail(error);};
this.node.port.onmessage=({data})=> {
if(data.type==='ready') {clearTimeout(timer);resolve();}
else if(data.type==='reply') { const p=this.pending.get(data.id); if(p) {this.pending.delete(data.id);clearTimeout(p.timer);data.error?p.reject(new Error(data.error)):p.resolve(data.result);} }
else if(data.type==='error') {const error=new Error(data.error); clearTimeout(timer); reject(error); this.fail(error);}
else this.dispatchEvent(new CustomEvent(data.type,{detail:data}));
};
});
}
fail(error) { for(const p of this.pending.values()) {clearTimeout(p.timer);p.reject(error);} this.pending.clear();this.dispatchEvent(new CustomEvent('error',{detail:error})); }
request(type,data={},transfer=[]) {
if(this.destroyed) return Promise.reject(new Error('DSP has been destroyed'));
const id=++this.serial;
return new Promise((resolve,reject)=> {
const timer=setTimeout(()=>{this.pending.delete(id);reject(new Error(`DSP ${type} timed out`));},15000);
this.pending.set(id,{resolve,reject,timer});this.node.port.postMessage({type,id,...data},transfer);
});
}
// One source → this DSP → destination. For arbitrary graphs use .node directly.
connect(source,destination=this.context.destination) {
if(this.destroyed) throw new Error('DSP has been destroyed');
if(this.source) this.source.disconnect(this.node);
this.node.disconnect();this.source=source;source.connect(this.node);this.node.connect(destination);return destination;
}
async setParam(name,value) {if(/^(?:liveprog|ddc|arbitrary)\./.test(name))throw new Error('Text effects are disabled in this player version');validateParam(name,value);await this.request('param',{name,value});this.params[name]=value;}
setBypass(enabled) {return this.setParam('bypass',Number(Boolean(enabled)));}
async setText(effect,text) {
throw new Error('Text effects are disabled in this player version');
}
async loadIR(buffer,reference=null) {
buffer=prepareIR(this.context,buffer,{normalize:false});
const internalRate=this.context.sampleRate===44100?44100:48000;
buffer=resampleIR(buffer,internalRate);
if(![1,2,4].includes(buffer.numberOfChannels) || buffer.length>65536 || buffer.length<1) throw new RangeError('IR must have 1, 2, or 4 channels and at most 65536 frames');
const pcm=new Float32Array(buffer.length*buffer.numberOfChannels);
for(let ch=0;ch<buffer.numberOfChannels;ch++) {const data=buffer.getChannelData(ch);for(let i=0;i<buffer.length;i++) pcm[i*buffer.numberOfChannels+ch]=data[i];}
await this.request('ir',{pcm,frames:buffer.length,channels:buffer.numberOfChannels,sourceRate:internalRate},[pcm.buffer]);this.params['convolver.enabled']=0;this.irRef=reference?{name:reference.name,hash:reference.hash}:null;
}
async getInfo() {const {bytes,heapBytes}=await this.request('info');const view=new DataView(bytes);return {abiVersion:view.getUint32(0,true),structBytes:view.getUint32(4,true),contextRate:view.getFloat32(8,true),internalRate:view.getFloat32(12,true),srcBackend:view.getUint32(16,true),latencyFrames:view.getUint32(20,true),irChannels:view.getUint32(24,true),irFrames:view.getUint32(28,true),irCapFrames:view.getUint32(32,true),headFrames:view.getUint32(36,true),tailFrames:view.getUint32(40,true),liveBytes:view.getUint32(44,true),peakBytes:view.getUint32(48,true),faults:view.getUint32(52,true),underruns:view.getUint32(56,true),overflows:view.getUint32(60,true),heapBytes};}
async applyPreset(preset) {
// All keys validated before mutation; applying a preset resets unspecified params.
if(preset?.texts && Object.keys(preset.texts).length) throw new Error('Text effects are disabled in this player version');
const params={...this.defaultParams,...(preset.params||preset)};
for(const [name,value] of Object.entries(params)) {if(/^(?:liveprog|ddc|arbitrary)\./.test(name))throw new Error('Text effects are disabled in this player version');validateParam(name,value);}
if(preset.irRef) {const saved=await getIR(preset.irRef.name);if(!saved||saved.hash!==preset.irRef.hash)throw new Error(`Preset IR is missing or changed: ${preset.irRef.name}`);await this.loadIR(saved.buffer,preset.irRef);}
// Configure before enabling; the referenced IR is loaded first.
for(const [name,value] of Object.entries(params).sort(([a],[b])=>Number(a.endsWith('.enabled'))-Number(b.endsWith('.enabled')))) await this.setParam(name,value);
}
toJSON() {return {version:2,params:{...this.params},...(this.irRef?{irRef:{...this.irRef}}:{})};}
destroy() {
if(this.destroyed) return;
if(this.source) {try {this.source.disconnect(this.node);} catch {}} this.node.disconnect();
this.node.port.postMessage({type:'destroy'});this.destroyed=true;this.fail(new Error('DSP destroyed'));this.node.port.close();
}
}

31
frontend/vendor/jamesdsp/params.mjs vendored Normal file
View File

@@ -0,0 +1,31 @@
// SPDX-License-Identifier: GPL-3.0-or-later
export const EQ_FREQUENCIES = [25,40,63,100,160,250,400,630,1000,1600,2500,4000,6300,10000,16000];
export const COMP_FREQUENCIES = [95,200,400,800,1600,3400,7500];
export const EFFECTS = ['eq','compressor','bass','stereo','reverb','crossfeed','spatial','tube','convolver','liveprog','ddc','arbitrary'];
export const PARAMS = {
bypass:[0,1,0], gain:[-24,12,0],
'limiter.threshold':[-24,0,-0.1], 'limiter.release':[10,1000,100],
'eq.mode':[0,5,1], 'eq.interpolation':[0,1,0],
'compressor.time':[0.01,2,0.1], 'compressor.mode':[0,3,3], 'compressor.granularity':[0,4,0],
'bass.boost':[0,12,6], 'stereo.mix':[0,1,0.5], 'reverb.preset':[0,18,0],
'convolver.mix':[0,1,1], 'convolver.predelayMs':[0,250,0],
'crossfeed.mode':[0,5,0], 'tube.drive':[-12,12,0],
'spatial.mode':[2,6,2], 'spatial.azimuth':[-90,90,0], 'spatial.spread':[0,120,60],
'spatial.distance':[0.5,5,1], 'spatial.room':[0,1,0], 'spatial.centerDb':[0,6,0], 'spatial.mix':[0,1,1],
};
for (const effect of EFFECTS) PARAMS[`${effect}.enabled`] = [0,1,0];
EQ_FREQUENCIES.forEach((_, i) => PARAMS[`eq.band${i}`] = [-12,12,0]);
COMP_FREQUENCIES.forEach((_, i) => PARAMS[`compressor.band${i}`] = [-12,12,0]);
export const DEFAULT_PARAMS = Object.fromEntries(Object.entries(PARAMS).map(([k,v])=>[k,v[2]]));
export function validateParam(name, value) {
const spec=PARAMS[name];
if (!spec || typeof value!=='number' || !Number.isFinite(value) || value<spec[0] || value>spec[1]) throw new RangeError(`Invalid parameter ${name}: ${value}`);
if ((name.endsWith('.enabled') || /mode|preset|granularity|interpolation|bypass/.test(name)) && !Number.isInteger(value)) throw new RangeError(`${name} requires an integer`);
}
export const PRESETS = {
Flat: {},
'Warm lows': {'eq.band0':4,'eq.band1':4,'eq.band2':3,'eq.band3':2,'eq.enabled':1,'gain':-3},
'Headphones': {'crossfeed.enabled':1,'crossfeed.mode':1,'eq.band8':-2,'eq.enabled':1},
'Small room': {'reverb.preset':7,'reverb.enabled':1,'gain':-3},
'Virtual speakers': {'spatial.enabled':1,'spatial.mode':6,'spatial.spread':90},
};

57
frontend/vendor/jamesdsp/worklet.mjs vendored Normal file
View File

@@ -0,0 +1,57 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import createJamesDSP from './dsp/jamesdsp-a982b53.mjs';
class JamesDSPProcessor extends AudioWorkletProcessor {
constructor(options) {
super(); this.closed=false;this.failed=false;
this.initialize(options);
}
async initialize(options) {
try {
this.wasm=await createJamesDSP({wasmBinary:options.processorOptions.wasmBytes,locateFile:()=>'jamesdsp.wasm',print:()=>{},printErr:()=>{}});
this.handle=this.wasm._jdsp_create(sampleRate);
this.pointer=this.wasm._malloc(128*2*4);
if(!this.handle || !this.pointer) throw new Error('DSP allocation failed or sample rate unsupported');
this.audio=this.wasm.HEAPF32.subarray(this.pointer/4,this.pointer/4+256);
this.port.onmessage=({data})=>this.message(data);
this.port.postMessage({type:'ready'});
} catch(error) {this.failed=true;this.port.postMessage({type:'error',error:String(error)});}
}
string(value,fn) {
const utf8=encodeURIComponent(value+'\0').replace(/%([0-9A-F]{2})/g,(_,hex)=>String.fromCharCode(parseInt(hex,16)));
const bytes=Uint8Array.from(utf8,c=>c.charCodeAt(0)), p=this.wasm._malloc(bytes.length);
if(!p) throw new Error('DSP text allocation failed');
try {this.wasm.HEAPU8.set(bytes,p);return fn(p);} finally {this.wasm._free(p);}
}
message(data) {
if(data.type==='destroy') {if(this.handle) this.wasm._jdsp_destroy(this.handle);if(this.pointer) this.wasm._free(this.pointer);this.closed=true;return;}
try {
let result;
if(data.type==='param') result=this.string(data.name,p=>this.wasm._jdsp_set_param(this.handle,p,data.value));
else if(data.type==='ir') {
const p=this.wasm._malloc(data.pcm.byteLength);if(!p) throw new Error('IR allocation failed');
try {this.wasm.HEAPF32.set(data.pcm,p/4);result=this.wasm._jdsp_load_ir_ex(this.handle,p,data.frames,data.channels,data.sourceRate);} finally {this.wasm._free(p);}
} else if(data.type==='info') {
const p=this.wasm._malloc(64);if(!p)throw new Error('DSP info allocation failed');
try {result=this.wasm._jdsp_get_info(this.handle,p);if(result===0){const bytes=this.wasm.HEAPU8.slice(p,p+64);this.port.postMessage({type:'reply',id:data.id,result:{bytes:bytes.buffer,heapBytes:this.wasm.HEAPU8.buffer.byteLength}},[bytes.buffer]);return;}} finally {this.wasm._free(p);}
} else throw new Error('Unknown DSP message');
if(result!==0) throw new Error(`DSP rejected ${data.name||data.effect||data.type}`);
this.port.postMessage({type:'reply',id:data.id,result});
} catch(error) {this.port.postMessage({type:'reply',id:data.id,error:String(error)});}
}
process(inputs,outputs) {
if(this.closed) return false;
const out=outputs[0], input=inputs[0];
if(!out?.length || this.failed || !this.handle) return true;
// Mono duplicates to stereo; missing input becomes silence, preserving tails.
for(let offset=0;offset<out[0].length;offset+=128) {
const n=Math.min(128,out[0].length-offset);
for(let i=0;i<n;i++) {this.audio[i*2]=input[0]?.[offset+i]||0;this.audio[i*2+1]=(input[1]||input[0])?.[offset+i]||0;}
try {
if(this.wasm._jdsp_process(this.handle,this.pointer,n)!==0) throw new Error('DSP produced nonfinite output');
for(let i=0;i<n;i++) {out[0][offset+i]=this.audio[i*2];if(out[1]) out[1][offset+i]=this.audio[i*2+1];}
} catch(error) {out.forEach(channel=>channel.fill(0));this.failed=true;this.port.postMessage({type:'error',error:String(error)});break;}
}
return true;
}
}
registerProcessor('jamesdsp',JamesDSPProcessor);

View File

@@ -1,4 +1,18 @@
/* Eager UI definitions. Read app lexical state only when called after initialization. */
function parseJamesDspPreset(text) {
const imported = typeof text === 'string' ? JSON.parse(text) : text;
const allowed = /^(?:eq\.band(?:[0-9]|1[0-4])|compressor\.band[0-6]|(?:eq|compressor|bass|stereo|reverb|crossfeed|tube|convolver)\.enabled|(?:gain|limiter\.threshold|limiter\.release|eq\.mode|eq\.interpolation|compressor\.time|compressor\.mode|compressor\.granularity|bass\.boost|stereo\.mix|reverb\.preset|crossfeed\.mode|tube\.drive))$/;
if (imported?.version !== 1 || imported?.texts || !imported?.params || typeof imported.params !== 'object' || Array.isArray(imported.params)) throw new Error('This file is not a supported preset (text effects are disabled).');
const range = key => key.startsWith('eq.band') || key.startsWith('compressor.band') ? [-12, 12] : ({ gain: [-24, 12], 'limiter.threshold': [-24, 0], 'limiter.release': [10, 1000], 'eq.mode': [0, 5], 'eq.interpolation': [0, 1], 'compressor.time': [0.01, 2], 'compressor.mode': [0, 3], 'compressor.granularity': [0, 4], 'bass.boost': [0, 12], 'stereo.mix': [0, 1], 'reverb.preset': [0, 18], 'crossfeed.mode': [0, 5], 'tube.drive': [-12, 12] }[key] || (key.endsWith('.enabled') ? [0, 1] : null));
for (const [key, value] of Object.entries(imported.params)) {
const bounds = range(key);
if (!allowed.test(key) || typeof value !== 'number' || !Number.isFinite(value) || !bounds || value < bounds[0] || value > bounds[1] || (key === 'convolver.enabled' && value !== 0)) throw new Error(`Unsupported preset setting: ${key}`);
if ((key.endsWith('.enabled') || /mode|preset|granularity|interpolation/.test(key)) && !Number.isInteger(value)) throw new Error(`Preset setting must be a whole number: ${key}`);
}
const presets = ['flat', 'bass', 'vocal', 'loudness', 'headphone', 'bright', 'warm'];
return { preset: presets.includes(imported.preset) ? imported.preset : 'flat', params: { ...imported.params } };
}
async function renderLibrary() {
els.listTitle.textContent = 'Library';
resetListHeaderExtras();
@@ -718,10 +732,19 @@ async function renderSettings() {
const qOptions = qualities
.map((q) => `<option value="${q}"${data.settings.quality === q ? ' selected' : ''}>${q === 'auto' ? 'Auto' : q}</option>`)
.join('');
const jamesDsp = data.settings.jamesDsp || { enabled: false, downloadForOffline: false, preset: 'flat', params: {}, irRef: null };
const dspCores=Number(navigator.hardwareConcurrency), dspMemory=Number(navigator.deviceMemory);
const dspLowEnd=(dspCores>0&&dspCores<=4)||(dspMemory>0&&dspMemory<=4);
const dspBands = [25, 40, 63, 100, 160, 250, 400, 630, 1000, 1600, 2500, 4000, 6300, 10000, 16000];
const dspParamDefaults = { 'bass.boost': 6, 'stereo.mix': 0.5, 'limiter.threshold': -0.1, 'convolver.mix': 1, 'convolver.predelayMs': 0, 'spatial.mode': 6, 'spatial.spread': 60, 'spatial.distance': 1, 'spatial.mix': 1 };
const dspParam = key => Number.isFinite(Number(jamesDsp.params?.[key])) ? Number(jamesDsp.params[key]) : (dspParamDefaults[key] ?? 0);
const dspRange = (key, label, min, max, step = 1, unit = '') => `<label class="set-row dsp-param-row"><span>${label}<small>${dspParam(key)}${unit}</small></span><input type="range" data-dsp-param="${key}" min="${min}" max="${max}" step="${step}" value="${dspParam(key)}" /></label>`;
const dspBandRows = dspBands.map((hz, i) => dspRange(`eq.band${i}`, `${hz >= 1000 ? (hz / 1000) + ' kHz' : hz + ' Hz'}`, -12, 12, 0.5, ' dB')).join('');
const sel = (id, val, opts) => `<select id="${id}" class="set-select">` +
const sel = (id, val, opts) => `<span class="set-control-wrap"><select id="${id}" class="set-select">` +
opts.map(([v, label]) => `<option value="${v}"${val === v ? ' selected' : ''}>${label}</option>`).join('') +
`</select>`;
`</select></span>`;
const dspBuiltinIRSelect = `<select id="setDspBuiltinIR" class="set-select">${['Small room','Hall','Plate','Cathedral'].map(name=>`<option value="${name}"${dspLowEnd&&name!=='Small room'?' disabled':''}>${name}</option>`).join('')}</select>`;
wrap.innerHTML = `
<div class="set-group">
@@ -788,6 +811,50 @@ async function renderSettings() {
</span>
<input id="setLiveAudioIOS" type="checkbox" ${data.settings.liveAudioIOS ? 'checked' : ''} />
</label>` : ''}
<div class="dsp-settings" id="jamesDspSettings">
<div class="set-group-title">Sound engine</div>
<label class="set-row"><span>Engine<small>Standard is the default. JamesDSP replaces the Standard EQ and vocal/stereo stages.</small></span>
${sel('setSoundEngine', jamesDsp.enabled ? 'jamesdsp' : 'standard', [['standard', 'Standard'], ['jamesdsp', 'JamesDSP']])}
</label>
<label class="set-row"><span>Download audio effects for offline<small>Includes the optional JamesDSP engine and its large WASM file in the offline cache.</small></span><input id="setDspOffline" type="checkbox" ${jamesDsp.downloadForOffline ? 'checked' : ''} /></label>
<div id="jamesDspControls" ${jamesDsp.enabled ? '' : 'hidden'}>
<div class="set-row"><span>Live processing<small>${EQ.isIOS() ? 'On iPhone, enable Live sound processing above first. Audio may stop when the screen locks.' : 'Processing runs on this device.'}</small></span></div>
${dspLowEnd ? '<p class="dsp-risk" role="note">This device may have limited audio headroom. Long impulse responses are disabled and the short room response is capped at 0.5 seconds.</p>' : ''}
<label class="set-row"><span>Preset</span>${sel('setDspPreset', jamesDsp.preset || 'flat', [['flat', 'Flat'], ['bass', 'Bass boost'], ['vocal', 'Vocal'], ['loudness', 'Loudness'], ['headphone', 'Headphone crossfeed'], ['bright', 'Bright'], ['warm', 'Warm']])}</label>
<div class="dsp-param-list" aria-label="15-band equalizer">${dspBandRows}</div>
<label class="set-row"><span>Bass boost<small>${dspParam('bass.boost')} dB</small></span><input type="range" data-dsp-param="bass.boost" min="0" max="12" step="0.5" value="${dspParam('bass.boost')}" /></label>
<label class="set-row"><span>Stereo width<small>${Math.round(dspParam('stereo.mix') * 100)}%</small></span><input type="range" data-dsp-param="stereo.mix" min="0" max="1" step="0.05" value="${dspParam('stereo.mix')}" /></label>
<label class="set-row"><span>Crossfeed mode</span>${sel('setDspCrossfeed', String(dspParam('crossfeed.mode')), [['0', 'Off'], ['1', 'Gentle'], ['2', 'Natural'], ['3', 'Wide'], ['4', 'Diffuse'], ['5', 'Strong']])}</label>
<label class="set-row"><span>Reverb preset</span>${sel('setDspReverb', String(dspParam('reverb.preset')), Array.from({ length: 19 }, (_, i) => [String(i), i === 0 ? 'Off' : `Room ${i}`]))}</label>
<label class="set-row"><span>Tube drive<small>${dspParam('tube.drive')} dB</small></span><input type="range" data-dsp-param="tube.drive" min="-12" max="12" step="0.5" value="${dspParam('tube.drive')}" /></label>
<label class="set-row"><span>Limiter threshold<small>${dspParam('limiter.threshold')} dB</small></span><input type="range" data-dsp-param="limiter.threshold" min="-24" max="0" step="0.5" value="${dspParam('limiter.threshold')}" /></label>
<label class="set-row"><span>Output gain<small>${dspParam('gain')} dB</small></span><input type="range" data-dsp-param="gain" min="-24" max="12" step="0.5" value="${dspParam('gain')}" /></label>
<label class="set-row"><span>Compressor</span><input id="setDspCompressor" type="checkbox" ${dspParam('compressor.enabled') ? 'checked' : ''} /></label>
<div class="dsp-actions"><button id="dspPresetImportBtn" class="btn" type="button">Import preset JSON</button><button id="dspPresetExportBtn" class="btn" type="button">Export preset JSON</button><button id="dspResetBtn" class="btn" type="button">Reset DSP</button></div>
<input id="dspPresetFile" type="file" accept="application/json,.json" hidden />
<section class="dsp-subsection" aria-labelledby="dspConvolverTitle">
<h4 id="dspConvolverTitle">Convolver</h4>
<label class="set-row"><span>Enable convolution</span><input id="setDspConvolver" type="checkbox" ${dspParam('convolver.enabled') ? 'checked' : ''} /></label>
<label class="set-row"><span>Dry / wet<small>${Math.round(dspParam('convolver.mix')*100)}%</small></span><input type="range" data-dsp-param="convolver.mix" min="0" max="1" step="0.01" value="${dspParam('convolver.mix')}" /></label>
<label class="set-row"><span>Pre-delay<small>${dspParam('convolver.predelayMs')} ms</small></span><input type="range" data-dsp-param="convolver.predelayMs" min="0" max="250" step="1" value="${dspParam('convolver.predelayMs')}" /></label>
<label class="set-row"><span>Built-in response</span><span class="set-control-wrap">${dspBuiltinIRSelect}</span></label>
<button id="setDspLoadBuiltin" class="btn" type="button">Generate and load</button>
<label class="set-row dsp-upload-row"><span>Upload impulse response<small>WAV or other browser-decodable audio; up to 65,536 frames at the internal sample rate.</small></span><span class="dsp-file-control"><input id="dspIrFile" type="file" accept="audio/*,.wav" aria-label="Upload impulse response" /><button id="dspIrChooseFile" class="dsp-file-button" type="button">Choose file</button><span class="dsp-file-name" id="dspIrFileName" aria-live="polite">No file chosen</span></span></label>
<label class="set-row"><span>Stored responses</span><span class="set-control-wrap"><select id="setDspSavedIR" class="set-select"><option value="">Choose a saved response</option></select></span></label>
<button id="setDspLoadSavedIR" class="btn" type="button">Load saved response</button>
<p id="dspIrStatus" class="sp-note">${jamesDsp.irRef?.name ? `Loaded: ${jamesDsp.irRef.name}` : 'No impulse response loaded.'}</p>
</section>
<section class="dsp-subsection" aria-labelledby="dspSpatialTitle">
<h4 id="dspSpatialTitle">3D spatial stage</h4>
<label class="set-row"><span>Enable 3D spatial stage</span><input id="setDspSpatial" type="checkbox" ${dspParam('spatial.enabled') ? 'checked' : ''} /></label>
<label class="set-row"><span>HRTF / renderer mode</span>${sel('setDspSpatialMode',String(dspParam('spatial.mode')),[['2','HRTF crossfeed'],['3','HRTF surround 1'],['4','HRTF surround 2'],['5','HRTF surround 3'],['6','Virtual speakers']])}</label>
${dspRange('spatial.azimuth','Azimuth',-90,90,1,'°')}
${dspRange('spatial.spread','Speaker spread',0,120,1,'°')}
${dspRange('spatial.distance','Distance',0.5,5,0.1,' m')}
${dspRange('spatial.centerDb','Center boost',0,6,0.1,' dB')}
</section>
</div>
</div>
<label class="set-row">
<span>Default volume</span>
<input id="setVolume" type="range" min="0" max="1" step="0.01" value="${data.settings.volume}" />
@@ -844,13 +911,6 @@ async function renderSettings() {
<div class="set-group">
<div class="set-group-title">Offline cache</div>
<div class="set-row"><span>App &amp; features</span><small id="offlineAssetStatus" role="status">Checking offline readiness…</small></div>
<label class="set-row">
<span>
Auto-save videos I play
<small>Every video you open is kept on this device in the background, so it plays offline later.</small>
</span>
<input id="setAutoSavePlayed" type="checkbox" ${data.settings.autoSavePlayed !== false ? 'checked' : ''} />
</label>
<label class="set-row">
<span>
Auto-save playlist videos
@@ -1062,6 +1122,124 @@ async function renderSettings() {
if (e.target.checked) toast('Live sound processing on — streamed songs go silent when the screen locks', { duration: 4500 });
});
const dspControls = $('jamesDspControls');
const dspEngine = $('setSoundEngine');
if (dspEngine) dspEngine.addEventListener('change', e => {
const enable = e.target.value === 'jamesdsp';
if (enable && EQ.isIOS() && !data.settings.liveAudioIOS) {
e.target.value = 'standard';
toast('On iPhone, turn on Live sound processing first.');
return;
}
data.settings.jamesDsp = data.settings.jamesDsp || { enabled: false, downloadForOffline: false, preset: 'flat', params: {}, irRef: null };
data.settings.jamesDsp.enabled = enable;
if (enable) data.settings.jamesDsp.downloadForOffline = true;
if (enable && $('setDspOffline')) $('setDspOffline').checked = true;
if (dspControls) dspControls.hidden = !enable;
persist();
reportDspOfflineOptIn();
EQ.apply();
});
if ($('setDspOffline')) $('setDspOffline').addEventListener('change', e => {
data.settings.jamesDsp = data.settings.jamesDsp || { enabled: false, downloadForOffline: false, preset: 'flat', params: {} };
data.settings.jamesDsp.downloadForOffline = e.target.checked;
persist();
reportDspOfflineOptIn();
toast(e.target.checked ? 'Preparing audio effects for offline use' : 'Audio effects removed from the offline completion list');
});
const dspConfig = data.settings.jamesDsp || (data.settings.jamesDsp = { enabled: false, downloadForOffline: false, preset: 'flat', params: {}, irRef: null });
let dspApplyTimer = null;
const applyDspSettings = () => {
clearTimeout(dspApplyTimer);
persist();
dspApplyTimer = setTimeout(() => { if (data.settings.jamesDsp?.enabled) EQ.apply(); }, 120);
};
if ($('setDspPreset')) $('setDspPreset').addEventListener('change', e => {
dspConfig.preset = e.target.value;
dspConfig.params = {};
wrap.querySelectorAll('[data-dsp-param]').forEach(input => { input.value = input.dataset.dspParam === 'limiter.threshold' ? '-0.1' : '0'; });
applyDspSettings();
});
wrap.querySelectorAll('[data-dsp-param]').forEach(input => input.addEventListener('input', () => {
const value = Number(input.value);
dspConfig.params[input.dataset.dspParam] = value;
const small = input.closest('.set-row')?.querySelector('small');
if (small) small.textContent = `${value}${input.dataset.dspParam === 'stereo.mix' ? '%' : input.dataset.dspParam === 'bass.boost' || input.dataset.dspParam === 'tube.drive' || input.dataset.dspParam === 'limiter.threshold' || input.dataset.dspParam === 'gain' || input.dataset.dspParam.startsWith('eq.band') ? ' dB' : ''}`;
applyDspSettings();
}));
if ($('setDspCrossfeed')) $('setDspCrossfeed').addEventListener('change', e => { dspConfig.params['crossfeed.mode'] = Number(e.target.value); dspConfig.params['crossfeed.enabled'] = Number(e.target.value) ? 1 : 0; applyDspSettings(); });
if ($('setDspConvolver')) $('setDspConvolver').addEventListener('change', e => {
const hasIR=dspConfig.irRef||EQ.state().jamesDsp?.irRef;
if(e.target.checked&&!hasIR){e.target.checked=false;toast('Load an impulse response first.');return;}
dspConfig.params['convolver.enabled']=e.target.checked?1:0;applyDspSettings();
});
if ($('setDspSpatial')) $('setDspSpatial').addEventListener('change', e => {
dspConfig.params['spatial.enabled']=e.target.checked?1:0;
if(e.target.checked){dspConfig.params['crossfeed.enabled']=0;if($('setDspCrossfeed'))$('setDspCrossfeed').value='0';}
applyDspSettings();
});
if ($('setDspSpatialMode')) $('setDspSpatialMode').addEventListener('change', e => {dspConfig.params['spatial.mode']=Number(e.target.value);applyDspSettings();});
if ($('setDspReverb')) $('setDspReverb').addEventListener('change', e => { dspConfig.params['reverb.preset'] = Number(e.target.value); dspConfig.params['reverb.enabled'] = Number(e.target.value) ? 1 : 0; applyDspSettings(); });
if ($('setDspCompressor')) $('setDspCompressor').addEventListener('change', e => { dspConfig.params['compressor.enabled'] = e.target.checked ? 1 : 0; applyDspSettings(); });
const refreshDspIrList=async()=>{
const select=$('setDspSavedIR');if(!select)return;
const selected=select.value;select.replaceChildren(new Option('Choose a saved response',''));
try{for(const item of await EQ.listDspIRs())select.add(new Option(`${item.name} · ${item.channels} ch · ${item.frames} frames`,item.name));if([...select.options].some(o=>o.value===selected))select.value=selected;}
catch(error){if($('dspIrStatus'))$('dspIrStatus').textContent=`Saved response list unavailable: ${error.message}`;}
};
if ($('setDspLoadBuiltin')) $('setDspLoadBuiltin').addEventListener('click',async()=>{
try{const name=$('setDspBuiltinIR').value;const ref=await EQ.loadDspBuiltinIR(name);if($('dspIrStatus'))$('dspIrStatus').textContent=`Loaded ${name}${ref?' and saved it for this device':' for this session only'}.`;$('setDspConvolver').checked=true;await refreshDspIrList();}
catch(error){toast(`Impulse response failed: ${error.message}`);}
});
if ($('setDspLoadSavedIR')) $('setDspLoadSavedIR').addEventListener('click',async()=>{
const name=$('setDspSavedIR').value;if(!name){await refreshDspIrList();return;}
try{const ref=await EQ.loadDspSavedIR(name);if($('dspIrStatus'))$('dspIrStatus').textContent=`Loaded saved response: ${name}`;$('setDspConvolver').checked=true;await refreshDspIrList();}
catch(error){toast(`Saved response failed: ${error.message}`);}
});
if ($('dspIrChooseFile')) $('dspIrChooseFile').addEventListener('click', e => { e.preventDefault(); $('dspIrFile')?.click(); });
if ($('dspIrFile')) $('dspIrFile').addEventListener('change',async e=>{
const file=e.target.files?.[0];if(!file)return;
if($('dspIrFileName'))$('dspIrFileName').textContent=file.name;
try{const ref=await EQ.loadDspIR(file);if($('dspIrStatus'))$('dspIrStatus').textContent=`Loaded ${ref?.name||file.name}${ref?' and saved it for this device':' for this session only'}.`;$('setDspConvolver').checked=true;await refreshDspIrList();}
catch(error){toast(`Impulse response failed: ${error.message}`);}
finally{e.target.value='';}
});
if(jamesDsp.enabled||jamesDsp.downloadForOffline)refreshDspIrList();
if ($('dspResetBtn')) $('dspResetBtn').addEventListener('click', () => {
dspConfig.preset = 'flat'; dspConfig.params = {};
if ($('setDspPreset')) $('setDspPreset').value = 'flat';
wrap.querySelectorAll('[data-dsp-param]').forEach(input => { input.value = input.dataset.dspParam === 'limiter.threshold' ? '-0.1' : '0'; });
if ($('setDspCrossfeed')) $('setDspCrossfeed').value = '0';
if ($('setDspReverb')) $('setDspReverb').value = '0';
if ($('setDspCompressor')) $('setDspCompressor').checked = false;
applyDspSettings();
toast('JamesDSP settings reset');
});
if ($('dspPresetExportBtn')) $('dspPresetExportBtn').addEventListener('click', () => {
const params = { ...(dspConfig.params || {}) }; delete params['convolver.enabled'];
const blob = new Blob([JSON.stringify({ version: 1, preset: dspConfig.preset || 'flat', params }, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob), a = document.createElement('a');
a.href = url; a.download = 'ytplayer-jamesdsp-preset.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
});
if ($('dspPresetImportBtn')) $('dspPresetImportBtn').addEventListener('click', () => $('dspPresetFile')?.click());
if ($('dspPresetFile')) $('dspPresetFile').addEventListener('change', async e => {
const file = e.target.files?.[0]; if (!file) return;
try {
if (file.size > 65536) throw new Error('Preset files must be 64 KB or smaller.');
const imported = parseJamesDspPreset(await file.text());
dspConfig.preset = imported.preset; dspConfig.params = imported.params;
if ($('setDspPreset')) $('setDspPreset').value = dspConfig.preset;
applyDspSettings(); toast('JamesDSP preset imported');
} catch (error) { toast(error?.message || 'Could not import preset'); }
finally { e.target.value = ''; }
});
if ($('dspIrFile')) $('dspIrFile').addEventListener('change', async e => {
const file = e.target.files?.[0]; if (!file) return;
try { await EQ.loadDspIR(file); dspConfig.params['convolver.enabled'] = 1; applyDspSettings(); toast('Impulse response loaded for this session'); }
catch (error) { toast(error?.message || 'Could not load impulse response'); }
finally { e.target.value = ''; }
});
// ---- Saved searches manager ----
{
@@ -1123,10 +1301,6 @@ async function renderSettings() {
persist();
Notes.refreshFlags();
});
$('setAutoSavePlayed').addEventListener('change', (e) => {
data.settings.autoSavePlayed = e.target.checked;
persist();
});
$('setAutoPreload').addEventListener('change', (e) => {
data.settings.autoPreload = e.target.checked;
persist();

View File

@@ -74,6 +74,11 @@ Each scenario records the following metrics across **5 independent runs** (repor
## 4. How to Run
### Optional JamesDSP integration check
`node perf/dsp.mjs --browser all` builds short local H.264/AAC test tones, exercises Standard and lazy JamesDSP presets through the real app graph, verifies A/B bypass routes directly to the unchanged Standard chain, measures generated-IR effects and the four-channel/spatial stages in an offline render, checks an arbitrary 32 kHz context, and tests stored-IR offline reload, one worklet heap, no new media sources, and corrupt-WASM fallback. The default install must omit the optional WASM; the harness then opts in through Settings and confirms completion. Detailed measurements stay in ignored `perf/.tmp/dsp-results.json`.
`node perf/settings-persist.mjs --browser all` also round-trips a disabled, custom JamesDSP preset and the offline-audio opt-in through local storage and confirms the Standard selector remains selected.
### Prerequisites
Symlink dependencies and ensure server dependencies are installed:
```bash
@@ -484,3 +489,24 @@ remote toggles against a mocked relay. Transport previews and remote screenshots
are saved in ignored `plans/transport-shots/`. Run `node perf/ui-geometry.mjs`
for the 320–430px search-bar and Saved-row geometry matrix. OS lock-screen buttons
remain platform-rendered through the existing MediaSession handlers.
Run `node perf/settings-layout.mjs` for the Settings workspace and JamesDSP
control matrix: Chromium and WebKit, all four layouts, dark/light/contrast, and
390/768/1280/1440/1920px widths. It checks horizontal overflow, responsive row
geometry, themed selects and switches, the clipped native file picker, and
button wrapping; desktop screenshots and measurements are written to
`plans/settings-shots/`.
## Transient retry verification
`retry.mjs` starts the real Bun server behind the local traffic-shaping proxy, then
injects one HTTP 503 into search, one dropped related-video request, and one lazy
chunk load failure. Each path must recover automatically without exposing the
manual related/player Retry affordance. It runs Chromium and WebKit by default;
choose `--browser chromium|webkit` and `--profile lte|lossy|unthrottled` to narrow
it. Retry logic is limited to idempotent GET requests and chunk loads; explicit
save/retry POST actions remain user initiated.
```bash
node perf/retry.mjs --browser all --profile lossy
```

View File

@@ -94,7 +94,7 @@ execFileSync('ffmpeg', ['-y', '-i', mp4, '-vn', '-c:a', 'copy', path.join(media,
await page.waitForFunction(key => JSON.parse(localStorage.getItem('_ytpdata')).settings[key] === true, key);
if (scenario === 'settings-save-first') await page.evaluate(clip => { Player.loadVideo(clip); }, clip);
}
const expected = !['playlist-boot-off'].includes(scenario);
const expected = !['open-default', 'open-audio-only', 'open-prefer-stream', 'playlist-boot-off'].includes(scenario);
if (supported && expected) await page.waitForFunction(id => cachedIds.has(id), clip.id, { timeout: 15000 });
else await page.waitForTimeout(1000);
const state = await page.evaluate(async id => ({ cached: cachedIds.has(id), files: OPFS.isSupported() ? await OPFS.listVideos() : [], queue: SaveQueue.pending(), calls: window.__saveCalls }), clip.id);

165
perf/dsp.mjs Normal file
View File

@@ -0,0 +1,165 @@
#!/usr/bin/env node
// End-to-end JamesDSP checks against the real local server, manifest cache and media fixture.
import assert from 'node:assert/strict';
import { spawn, execFileSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { createServer } from 'node:net';
import { mkdtempSync, mkdirSync, cpSync, writeFileSync, statSync, rmSync, existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { chromium, webkit } from 'playwright';
import { createThrottleProxy } from './proxy.mjs';
const repo = resolve(import.meta.dirname, '..');
const requested = process.argv.includes('--browser') ? process.argv[process.argv.indexOf('--browser') + 1] : 'all';
assert.ok(['all', 'chromium', 'webkit'].includes(requested));
const scratch = mkdtempSync(join(repo, 'perf/.tmp/dsp-'));
const results = { results: [], failures: [] };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function poll(fn, timeout = 90000) { const end = Date.now() + timeout; while (Date.now() < end) { if (await fn()) return true; await sleep(100); } return false; }
async function run(engine) {
const cwd = join(scratch, engine); mkdirSync(cwd); cpSync(join(repo, 'frontend'), join(cwd, 'public'), { recursive: true }); mkdirSync(join(cwd, 'media'));
const portProbe = createServer(); await new Promise(resolve => portProbe.listen(0, '127.0.0.1', resolve)); const port = portProbe.address().port; await new Promise(resolve => portProbe.close(resolve));
let child, browser, proxy, context, log = '';
let origin = `http://127.0.0.1:${port}`;
const result = { engine, errors: [], failures: [], rms: [], checks: [] }; results.results.push(result);
async function stop() { if (!child) return; const proc = child; child = null; if (proc.exitCode === null) { proc.kill('SIGTERM'); await new Promise(resolve => proc.once('exit', resolve)); } }
try {
const clips = [
{ id: 'dspfixture01', title: 'DSP test tone 110 Hz', channel: 'Local test', duration: 5, thumbnail: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' },
{ id: 'dspfixture02', title: 'DSP test tone 660 Hz', channel: 'Local test', duration: 5, thumbnail: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' },
];
child = spawn('bun', [join(repo, 'server/server.js')], { cwd, env: { ...process.env, PORT: String(port), DB_PATH: join(cwd, 'db.sqlite'), MEDIA_DIR: join(cwd, 'media'), UPLOAD_DIR: join(cwd, 'uploads'), DATA_DIR: join(cwd, 'data'), ASSET_HASHING: '1', ASSET_SYNC: '1', BUILD_TAG: '' }, stdio: ['ignore', 'pipe', 'pipe'] });
for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => { log = (log + chunk).slice(-8000); });
if (!await poll(async () => { if (child.exitCode !== null) throw Error(log); try { return (await fetch(origin + '/api/version')).ok; } catch { return false; } })) throw Error('Server did not start: ' + log);
for (const [index, clip] of clips.entries()) {
const mp4 = join(cwd, 'media', clip.id + '.1.mp4');
execFileSync('ffmpeg', ['-y', '-f', 'lavfi', '-i', 'color=c=blue:s=160x90:r=10:d=5', '-f', 'lavfi', '-i', `sine=frequency=${index ? 660 : 110}:duration=5`, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-movflags', '+faststart', '-shortest', mp4], { stdio: 'ignore' });
execFileSync('ffmpeg', ['-y', '-i', mp4, '-vn', '-c:a', 'copy', join(cwd, 'media', clip.id + '.1.m4a')], { stdio: 'ignore' });
assert.ok(existsSync(mp4), `generated local clip ${mp4}`);
}
const require = createRequire(import.meta.url); const { createClient } = require(join(repo, 'server/node_modules/@libsql/client'));
const db = createClient({ url: 'file:' + join(cwd, 'db.sqlite') });
for (const clip of clips) { const file = join(cwd, 'media', clip.id + '.1.mp4'); await db.execute({ sql: 'INSERT OR REPLACE INTO media_cache (video_id,status,gen,size,height,vcodec,acodec,duration,meta,last_access) VALUES (?,?,?,?,?,?,?,?,?,?)', args: [clip.id, 'ready', 1, statSync(file).size, 90, 'h264', 'aac', 5, JSON.stringify(clip), Date.now()] }); }
db.close();
proxy = createThrottleProxy({ targetPort: port, profile: 'unthrottled' }); origin = `http://127.0.0.1:${await proxy.listen()}`;
const type = engine === 'chromium' ? chromium : webkit; browser = await type.launch({ headless: true, ...(engine === 'chromium' ? { args: ['--autoplay-policy=no-user-gesture-required'] } : {}) });
context = await browser.newContext({ viewport: { width: 414, height: 896 } });
await context.addInitScript(() => { window.__dspToasts = []; new MutationObserver(() => { const text = document.querySelector('#toastContainer')?.textContent?.trim(); if (text && window.__dspToasts.at(-1) !== text) window.__dspToasts.push(text); }).observe(document, { childList: true, subtree: true, characterData: true }); });
await context.route('**/*', route => route.request().url().startsWith(origin) ? route.continue() : route.fulfill({ status: 200, contentType: 'image/gif', body: Buffer.from('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=', 'base64') }));
const page = await context.newPage(); let offlinePhase = false, failedApiTransports = 0; page.on('pageerror', error => { if (offlinePhase && failedApiTransports && /TypeError: Load failed|\/api\//.test(error.message)) (result.expectedApiErrors ||= []).push(error.message); else result.errors.push(error.message); });
page.on('requestfailed', request => { const path = new URL(request.url()).pathname; if (path.startsWith('/api/')) failedApiTransports++; else if (!(offlinePhase && path === '/sw.js')) result.errors.push(`request failed ${request.url()}: ${request.failure()?.errorText}`); });
page.on('response', response => {
const url = new URL(response.url()), path = url.pathname;
// The local fixture IDs have no upstream YouTube artwork. These requests
// are unrelated to the local media or DSP asset path under test.
if (url.hostname === 'i.ytimg.com' && /\/vi\/dspfixture0[12]\//.test(path)) {
(result.fixtureResponses ||= []).push({ url: response.url(), status: response.status() });
} else if (!path.startsWith('/api/') && response.status() >= 400) result.errors.push(`asset response ${response.status()} ${response.url()}`);
});
page.on('response', response => { if (/jamesdsp\/(?:worklet\.mjs|dsp\/jamesdsp[^/?]*\.mjs)/.test(response.url())) result.requests ||= [], result.requests.push({ url: response.url(), status: response.status(), type: response.headers()['content-type'] }); });
page.on('requestfailed', request => { if (/jamesdsp\//.test(request.url())) result.requestsFailed ||= [], result.requestsFailed.push({ url: request.url(), error: request.failure()?.errorText }); });
const boot = async () => { await page.goto(origin); await page.waitForFunction(() => typeof data !== 'undefined' && document.querySelector('#sidebarToggle')); };
await boot();
const manifest = await (await fetch(origin + '/api/manifest')).json();
const checkComplete = () => page.evaluate(async ({ files, groups }) => { const cache = await caches.open('ytplayer-assets'), opted = !!(data.settings.jamesDsp?.enabled || data.settings.jamesDsp?.downloadForOffline); const optional = new Set(Object.values(groups).filter(group => group.offlineOptIn && !(opted && group.offlineOptIn === 'jamesDsp')).flatMap(group => group.files)); const missing = []; for (const [path, file] of Object.entries(files)) { if (optional.has(path)) continue; const r = await cache.match(path + '?v=' + file.h); if (!r || r.headers.get('X-Asset-Hash') !== file.h) missing.push(path); } return missing; }, manifest);
assert.equal((await page.evaluate(async () => { const shell = await caches.open('ytplayer-shell'); return (await shell.keys()).some(r => r.url.includes('jamesdsp')); })), false, 'DSP is never in the shell cache');
assert.equal(await poll(async () => !(await checkComplete()).length, 120000), true, 'offline completion job fills manifest before offline test');
const optionalCount = Object.values(manifest.groups || {}).filter(group => group.offlineOptIn).reduce((n, group) => n + group.files.filter(path => manifest.files[path]).length, 0);
result.checks.push({ name: 'required files cached; optional DSP deferred', files: Object.keys(manifest.files).length - optionalCount, optionalDeferred: optionalCount, manifestFiles: Object.keys(manifest.files).length });
await page.evaluate(async () => { await Lazy.load('feature:eq-core'); await Lazy.load('feature:vocal-reducer'); data.settings.jamesDsp = { enabled: false, downloadForOffline: false, preset: 'flat', params: {}, irRef: null }; EQ.setLevel(1); EQ.setLevel(0); EQ.apply(); });
await page.evaluate(clip => Player.loadVideo(clip), clips[0]);
await page.locator('#playBtn').click({ force: true }).catch(() => {});
if (!await poll(() => page.evaluate(() => Player.master?.currentTime > 0.4), 12000)) { await page.evaluate(() => Player.master?.play().catch(() => {})); assert.equal(await poll(() => page.evaluate(() => Player.master?.currentTime > 0.4), 12000), true, 'local test clip starts'); }
await page.evaluate(() => { if (Player.master) Player.master.loop = true; });
const rms = async () => page.evaluate(async () => {
const analyser = EQ.analyser(); if (!analyser) throw new Error('EQ analyser unavailable');
const values = new Float32Array(analyser.fftSize); let sum = 0, count = 0, end = performance.now() + 600;
while (performance.now() < end) { analyser.getFloatTimeDomainData(values); for (const v of values) { sum += v * v; count++; } await new Promise(resolve => setTimeout(resolve, 18)); }
return Math.sqrt(sum / Math.max(1, count));
});
await page.evaluate(() => { EQ.apply(); }); await sleep(250);
const standardRms = await rms(); assert.ok(standardRms > 0, `Standard output has nonzero RMS (${standardRms})`);
await page.locator('#bottomNav [data-view="settings"]').click(); await page.evaluate(() => document.querySelector('[data-section="playback"]').click());
await page.selectOption('#setSoundEngine', 'jamesdsp');
const active = await poll(() => page.evaluate(() => !!EQ.state().jamesDsp?.active), 12000);
if (!active) result.diagnostics = await page.evaluate(() => ({ enabled: data.settings.jamesDsp?.enabled, state: EQ.state(), lazyLoaded: Lazy.loaded('feature:jamesdsp'), toast: document.querySelector('#toastContainer')?.textContent || '', toastHistory: window.__dspToasts }));
assert.equal(active, true, `JamesDSP worklet activates ${JSON.stringify(result.diagnostics || {})}`);
assert.equal(await poll(async () => !(await checkComplete()).length, 120000), true, 'engine opt-in completes optional WASM and module cache');
await sleep(200); const flat = await rms(); result.rms.push({ effect: 'flat', rms: flat });
for (const preset of ['bass', 'vocal', 'loudness', 'headphone', 'bright', 'warm']) {
await page.selectOption('#setDspPreset', preset); await sleep(900);
const value = await rms(); assert.ok(Number.isFinite(value), `${preset} RMS is finite`); result.rms.push({ effect: preset, rms: value });
}
const preConvolverRms = await rms();
result.irLoad = await page.evaluate(async () => { const reference = await EQ.loadDspBuiltinIR('Small room'); await new Promise(resolve => setTimeout(resolve, 300)); return { reference, settings: data.settings.jamesDsp, state: EQ.state().jamesDsp, toast: document.querySelector('#toastContainer')?.textContent || '' }; });
const convolverRms = await rms();
assert.equal(result.irLoad.state.irRef?.name, 'Small room', 'generated IR is loaded into the active worklet');
result.checks.push({ name: 'live generated IR loaded', beforeRms: preConvolverRms, afterRms: convolverRms, ir: result.irLoad.state.irRef });
await page.evaluate(clip => { Player.pause(); Player.loadVideo(clip); }, clips[1]); await sleep(500); await page.evaluate(() => Player.master?.play().catch(() => {}));
const trackSwapActive = await poll(() => page.evaluate(() => Player.master?.currentSrc.includes('dspfixture02') && Player.master?.readyState >= 2 && EQ.state().jamesDsp?.active), 12000);
if (!trackSwapActive) result.trackSwapDiagnostics = await page.evaluate(() => ({ time: Player.master?.currentTime, paused: Player.master?.paused, readyState: Player.master?.readyState, state: EQ.state().jamesDsp, graph: AudioGraph.snapshot(), source: Player.master?.currentSrc }));
assert.equal(trackSwapActive, true, 'DSP remains active on the replacement media source');
result.checks.push({ name: 'track switch retains DSP route', graph: await page.evaluate(() => AudioGraph.snapshot()) });
await page.evaluate(() => { data.settings.jamesDsp.params['bass.enabled'] = 1; data.settings.jamesDsp.params['eq.enabled'] = 1; EQ.apply(); }); await sleep(800);
const activeRms = await rms();
await page.evaluate(async () => { await EQ.toggleDspBypass(); }); await sleep(200); const bypassRms = await rms();
const bypassState = await page.evaluate(() => EQ.state().jamesDsp);
assert.equal(bypassState.route, 'standard', 'A/B bypass routes directly to the unchanged Standard graph');
result.checks.push({ name: 'A/B exact Standard route', standardRms, activeRms, bypassRms, ...bypassState });
await page.evaluate(async () => { const state = EQ.state().jamesDsp, graph = AudioGraph.snapshot(); return { state, graph }; }).then(({ state, graph }) => {
assert.equal(state.liveHeaps, 1); assert.equal(state.maxLiveHeaps, 1); assert.ok(graph.sourceCount <= 2, 'only existing player media sources'); result.checks.push({ name: 'one worklet heap / single graph', ...state, graph });
});
const dspRender = await page.evaluate(async () => {
const { JamesDSPNode } = await import(Lazy.url('/vendor/jamesdsp/jamesdsp-node.mjs'));
async function render(effect, rate = 32000) {
const frames = 32768, context = new OfflineAudioContext(2, frames, rate);
const engine = await JamesDSPNode.create(context, { wasmURL: Lazy.url('/vendor/jamesdsp/dsp/jamesdsp.wasm'), workletURL: Lazy.url('/vendor/jamesdsp/worklet.mjs') });
const buffer = context.createBuffer(2, 2048, rate);
for (let i = 0; i < buffer.length; i++) { const sample = Math.sin(2 * Math.PI * 440 * i / rate) * 0.25; buffer.getChannelData(0)[i] = sample; buffer.getChannelData(1)[i] = sample; }
if (effect === 'convolver') {
const ir = context.createBuffer(4, 4096, rate); ir.getChannelData(0)[0] = 0.5; ir.getChannelData(1)[97] = 0.25; ir.getChannelData(2)[211] = -0.2; ir.getChannelData(3)[0] = 0.5;
await engine.loadIR(ir); await engine.setParam('convolver.mix', 1); await engine.setParam('convolver.enabled', 1);
} else if (effect === 'spatial') {
await engine.setParam('spatial.enabled', 1); await engine.setParam('spatial.mode', 6); await engine.setParam('spatial.spread', 100); await engine.setParam('spatial.azimuth', 45);
}
await engine.setBypass(false);
const source = context.createBufferSource(); source.buffer = buffer; source.connect(engine.node); engine.node.connect(context.destination); source.start();
const rendered = await context.startRendering();
const left = rendered.getChannelData(0), right = rendered.getChannelData(1);
let l = 0, r = 0, diff = 0; for (let i = 0; i < frames; i++) { l += left[i] ** 2; r += right[i] ** 2; diff += (left[i] - right[i]) ** 2; }
const metrics = { leftRms: Math.sqrt(l / frames), rightRms: Math.sqrt(r / frames), interauralRms: Math.sqrt(diff / frames), rate: rendered.sampleRate };
engine.destroy(); return metrics;
}
const dry = await render('dry'), convolver = await render('convolver'), spatial = await render('spatial');
return { dry, convolver, spatial };
});
assert.equal(dspRender.dry.rate, 32000, 'ASRC accepts an arbitrary AudioContext rate');
assert.ok(dspRender.convolver.interauralRms > dspRender.dry.interauralRms + 0.00001, `four-channel IR changes rendered stereo output (${JSON.stringify(dspRender)})`);
assert.ok(dspRender.spatial.interauralRms > dspRender.dry.interauralRms + 0.00001, `3D stage changes interaural difference (${JSON.stringify(dspRender)})`);
result.checks.push({ name: 'offline four-channel convolver, spatial difference and 32 kHz ASRC', ...dspRender });
await page.evaluate(() => persist()); await sleep(500);
offlinePhase = true; if (engine === 'chromium') await context.setOffline(true); else await proxy.setOffline(true);
await page.reload(); await page.waitForFunction(() => typeof data !== 'undefined' && document.querySelector('#sidebarToggle'));
assert.equal(await poll(() => page.evaluate(() => !!EQ.state().jamesDsp?.active), 30000), true, 'offline reload restores enabled DSP from cached modules');
assert.equal(await page.evaluate(() => EQ.state().jamesDsp?.irRef?.name), 'Small room', 'stored generated IR is restored offline');
result.checks.push({ name: 'offline reload with engine and stored IR enabled', missing: await checkComplete(), ir: await page.evaluate(() => EQ.state().jamesDsp?.irRef) });
// A separate fresh profile corrupts the optional wasm response and verifies that Standard stays audible.
offlinePhase = false; failedApiTransports = 0; if (engine === 'chromium') await context.setOffline(false); else await proxy.setOffline(false);
const brokenContext = await browser.newContext({ viewport: { width: 414, height: 896 } });
await brokenContext.route('**/*', route => route.request().url().startsWith(origin) ? route.continue() : route.fulfill({ status: 200, contentType: 'image/gif', body: Buffer.from('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=', 'base64') }));
await brokenContext.addInitScript(() => { const realFetch = window.fetch.bind(window); window.fetch = (input, init) => String(input).includes('/vendor/jamesdsp/dsp/jamesdsp.wasm') ? Promise.resolve(new Response('corrupt', { status: 503 })) : realFetch(input, init); });
const brokenPage = await brokenContext.newPage(); brokenPage.on('pageerror', e => result.errors.push('corrupt test: ' + e.message)); await brokenPage.goto(origin); await brokenPage.waitForFunction(() => typeof data !== 'undefined');
await brokenPage.locator('#bottomNav [data-view="settings"]').click(); await brokenPage.evaluate(() => document.querySelector('[data-section="playback"]').click()); await brokenPage.selectOption('#setSoundEngine', 'jamesdsp');
assert.equal(await poll(() => brokenPage.evaluate(() => data.settings.jamesDsp.enabled === false && EQ.state().wired), 30000), true, 'corrupt wasm falls back to Standard');
result.checks.push({ name: 'corrupt wasm returns to Standard', enabled: await brokenPage.evaluate(() => data.settings.jamesDsp.enabled), graph: await brokenPage.evaluate(() => AudioGraph.snapshot()) });
await brokenContext.close();
} catch (error) { result.failures.push(error.stack || error.message); }
finally { await context?.close(); await browser?.close(); await proxy?.close(); await stop(); }
}
try { for (const engine of requested === 'all' ? ['chromium', 'webkit'] : [requested]) await run(engine); }
finally { writeFileSync(join(repo, 'perf/.tmp/dsp-results.json'), JSON.stringify(results, null, 2) + '\n'); rmSync(scratch, { recursive: true, force: true }); }
if (results.failures.length || results.results.some(result => result.failures.length || result.errors.length)) process.exitCode = 1;

View File

@@ -42,7 +42,8 @@ async function run(name){
console.log(name,'initial boot');await page.goto(origin);await page.waitForFunction(()=>typeof data!=='undefined'&&document.querySelector('#carModeBtn'));
await wait(page,async()=>!!(await navigator.serviceWorker.getRegistration())?.active);
await page.evaluate(()=>Lazy.warm());
await wait(page,async()=>{const c=await caches.open('ytplayer-assets'),r=await c.match('/__ytp_asset_state');if(!r)return false;const s=await r.json();return !(await Promise.all(Object.values(s.current.groups).flatMap(g=>g.files).map(async p=>!!await c.match(p+'?v='+s.current.files[p].h)))).includes(false);});
await wait(page,async()=>{const c=await caches.open('ytplayer-assets'),r=await c.match('/__ytp_asset_state');if(!r)return false;const s=await r.json(),files=Object.entries(s.current.groups).filter(([,g])=>!g.offlineOptIn).flatMap(([,g])=>g.files);return !(await Promise.all(files.map(async p=>!!await c.match(p+'?v='+s.current.files[p].h)))).includes(false);});
assert.equal(await page.evaluate(async()=>{const m=Lazy.manifest,path='/vendor/jamesdsp/dsp/jamesdsp.wasm',cache=await caches.open('ytplayer-assets');return !await cache.match(path+'?v='+m.files[path].h);}),true,'optional DSP WASM stays uncached on a default install');
console.log(name,'warm complete');assert.equal(await page.evaluate(()=>Lazy.loaded('feature:car-mode')),false);
assert.equal(await page.evaluate(()=>[...document.querySelectorAll('.stg-overlay,.deck-chips,.vol-pct,.mode-name,.stg-bot,.ch-badge,.upnext-clear,.list-sub,.p2p-strip,.sleep-status .sl-ic,.sleep-status .sl-sub,.mc-tune')].every(n=>getComputedStyle(n).display==='none')),true,'classic retains shared visibility defaults without loading Glass CSS');
await checkCssOrder(page);

View File

@@ -37,13 +37,22 @@ async function run(engine){
};
let page=await context.newPage();attach(page);
const boot=async()=>{await page.goto(origin);await page.waitForFunction(()=>typeof data!=='undefined'&&document.querySelector('[aria-label="Car mode"]'));};
const inventory=()=>page.evaluate(async({manifest,legacy})=>{
const inventory=(includeOptional=false)=>page.evaluate(async({manifest,legacy,includeOptional})=>{
const names=await caches.keys(),cache=await caches.open(legacy?names.find(n=>n.startsWith('ytplayer-')&&!['ytplayer-assets','ytplayer-fonts','ytplayer-thumbs'].includes(n)):'ytplayer-assets');
const missing=[];for(const [path,file]of Object.entries(manifest.files)){const r=await cache.match(legacy?path:path+'?v='+file.h);if(!r||(!legacy&&r.headers.get('X-Asset-Hash')!==file.h))missing.push(path);}
return{total:Object.keys(manifest.files).length,missing};
},{manifest,legacy});
const optional=new Set(Object.values(manifest.groups||{}).filter(group=>group.offlineOptIn).flatMap(group=>group.files||[]));
const expected=Object.entries(manifest.files).filter(([path])=>legacy||includeOptional||!optional.has(path));
const missing=[];for(const [path,file]of expected){const r=await cache.match(legacy?path:path+'?v='+file.h);if(!r||(!legacy&&r.headers.get('X-Asset-Hash')!==file.h))missing.push(path);}
return{total:expected.length,manifestTotal:Object.keys(manifest.files).length,optionalExcluded:Object.keys(manifest.files).length-expected.length,missing};
},{manifest,legacy,includeOptional});
const started=Date.now();console.log(engine,'install boot');await boot();console.log(engine,'waiting for worker activation');if(!await poll(()=>page.evaluate(async()=>!!(await navigator.serviceWorker.getRegistration())?.active),30000))throw Error('Worker did not activate: '+JSON.stringify(await page.evaluate(async()=>{const r=await navigator.serviceWorker.getRegistration();return {active:r?.active?.state,waiting:r?.waiting?.state,installing:r?.installing?.state,caches:await caches.keys(),keys:(await(await caches.open('ytplayer-assets')).keys()).map(r=>new URL(r.url).pathname)};})));await page.evaluate(()=>navigator.serviceWorker.ready);console.log(engine,'worker active');await page.evaluate(()=>window.Lazy?.warm());
await poll(async()=>!(await inventory()).missing.length,Number(option('--warm-timeout','15000')));
if(!legacy){const wasmPath='/vendor/jamesdsp/dsp/jamesdsp.wasm',wasm=manifest.files[wasmPath];if(wasm){const cached=await page.evaluate(async key=>!!await(await caches.open('ytplayer-assets')).match(key),wasmPath+'?v='+wasm.h);if(cached)result.failures.push({kind:'opt-in-wasm-cached-by-default',path:wasmPath});}}
if(!legacy){
await page.evaluate(()=>{data.settings.jamesDsp={...data.settings.jamesDsp,downloadForOffline:true};persist();reportDspOfflineOptIn();});
const dspReady=await poll(async()=>{const inventoryNow=await inventory(true);return !inventoryNow.missing.length;},120000);
result.conditions.push({name:'explicit audio-effects offline opt-in completes optional assets',complete:dspReady});
if(!dspReady)result.failures.push({kind:'optional-dsp-completion',paths:(await inventory(true)).missing});
}
console.log(engine,'inventory complete');result.installMs=Date.now()-started;result.inventory=await inventory();result.installWire=proxy.getStats();result.saveData=await page.evaluate(()=>navigator.connection?.saveData);
if(result.inventory.missing.length)result.failures.push({kind:'incomplete',paths:result.inventory.missing});
// Offline navigation always starts from a controlled document.
@@ -108,13 +117,17 @@ async function run(engine){
await page.evaluate(async manifest=>{const c=await caches.open('ytplayer-assets');for(const path of Object.keys(manifest.files).filter(p=>manifest.files[p].g!=='core'))await c.delete(path+'?v='+manifest.files[path].h);navigator.serviceWorker.controller.postMessage({type:'COMPLETE_ASSETS'});},manifest);
await poll(()=>page.evaluate(async()=>{const c=await caches.open('ytplayer-assets'),s=await(await c.match('/__ytp_asset_state')).json(),r=await c.match('/__ytp_completion/'+s.current.buildTag);return r&&(await r.json()).running;}),5000);
await page.close();await other.close();await proxy.setOffline(false);
const withoutPage=await poll(async()=>{const {cacheDataEntries:entries}=await cdp.send('CacheStorage.requestEntries',{cacheId,skipCount:0,pageSize:1000});return Object.entries(manifest.files).every(([path,file])=>entries.some(e=>e.requestURL===origin+path+'?v='+file.h&&e.responseHeaders.some(h=>h.name.toLowerCase()==='x-asset-hash'&&h.value===file.h)));});
const optionalPaths=new Set(Object.values(manifest.groups||{}).filter(group=>group.offlineOptIn==='jamesDsp').flatMap(group=>group.files||[]));
const includeOptional=await page.evaluate(async()=>{const cache=await caches.open('ytplayer-assets'),response=await cache.match('/__ytp_offline_opt_ins');return (await response?.json()||[]).includes('jamesDsp');});
const requiredFiles=Object.entries(manifest.files).filter(([path])=>includeOptional||!optionalPaths.has(path));
const withoutPage=await poll(async()=>{const {cacheDataEntries:entries}=await cdp.send('CacheStorage.requestEntries',{cacheId,skipCount:0,pageSize:1000});return requiredFiles.every(([path,file])=>entries.some(e=>e.requestURL===origin+path+'?v='+file.h&&e.responseHeaders.some(h=>h.name.toLowerCase()==='x-asset-hash'&&h.value===file.h)));});
result.conditions.push({name:'worker completes with every application page closed; passive same-origin inspector only',complete:withoutPage});
if(!withoutPage)result.failures.push({kind:'completion-without-page'});
await cdp.detach();await inspector.close();
}else await other.close();
}
console.log(engine,JSON.stringify({missing:result.inventory.missing,failures:result.failures,conditions:result.conditions}));
result.inventory=await inventory(!legacy);
console.log(engine,JSON.stringify({missing:result.inventory.missing,inventory:result.inventory.total,manifestFiles:result.inventory.manifestTotal,failures:result.failures,conditions:result.conditions}));
}catch(e){result.failures.push({kind:'harness',error:e.stack});console.log(engine,e.message);}finally{await context?.close();await browser?.close();await proxy?.close();child.kill('SIGTERM');if(child.exitCode===null)await new Promise(r=>child.once('exit',r));}
}
try{for(const engine of option('--browser','all')==='all'?['chromium','webkit']:[option('--browser')])await run(engine);}finally{writeFileSync(resolve(option('--out',join(repo,'perf/results/offline-complete.json'))),JSON.stringify({results},null,2)+'\n');rmSync(scratch,{recursive:true,force:true});}

File diff suppressed because it is too large Load Diff

108
perf/retry.mjs Executable file
View File

@@ -0,0 +1,108 @@
#!/usr/bin/env node
// Foreground transient-failure regression check over the real Bun server and
// shaped local proxy. Injects one 503/connection drop, then requires recovery
// without exposing the application's manual Retry/error affordances.
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { cpSync, mkdirSync, rmSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { createServer } from 'node:net';
import { chromium, webkit } from 'playwright';
import { createThrottleProxy } from './proxy.mjs';
const repo = resolve(new URL('..', import.meta.url).pathname);
const scratch = join(repo, 'perf/.tmp/retry');
const profile = process.argv.includes('--profile') ? process.argv[process.argv.indexOf('--profile') + 1] : 'lossy';
const engines = process.argv.includes('--browser') ? process.argv[process.argv.indexOf('--browser') + 1] : 'all';
assert.ok(['all', 'chromium', 'webkit'].includes(engines));
rmSync(scratch, { recursive: true, force: true }); mkdirSync(scratch, { recursive: true });
const results = [];
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function freePort() { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
async function poll(fn, timeout = 30000) { const end = Date.now() + timeout; while (Date.now() < end) { if (await fn()) return true; await sleep(100); } return false; }
for (const engine of engines === 'all' ? ['chromium', 'webkit'] : [engines]) {
const cwd = join(scratch, engine); mkdirSync(cwd); cpSync(join(repo, 'frontend'), join(cwd, 'public'), { recursive: true });
const port = await freePort(); let log = '';
const child = spawn('bun', [join(repo, 'server/server.js')], { cwd, env: { ...process.env, PORT: String(port), ASSET_HASHING: '1', ASSET_SYNC: '1', BUILD_TAG: '', DB_PATH: join(cwd, 'db.sqlite'), DATA_DIR: join(cwd, 'data'), MEDIA_DIR: join(cwd, 'media'), UPLOAD_DIR: join(cwd, 'uploads') }, stdio: ['ignore', 'pipe', 'pipe'] });
for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => log = (log + chunk).slice(-8000));
let browser, context, proxy;
const result = { engine, profile, injected: [], recovered: [], visibleErrors: [] }; results.push(result);
try {
if (!await poll(async () => { try { return (await fetch(`http://127.0.0.1:${port}/api/version`)).ok; } catch { return false; } })) throw Error(`server failed: ${log}`);
proxy = createThrottleProxy({ targetPort: port, profile }); proxy.startTracking();
const origin = `http://127.0.0.1:${await proxy.listen()}`;
browser = await ({ chromium, webkit })[engine].launch({ headless: true });
context = await browser.newContext({ serviceWorkers: 'block' });
await context.route('**/*', route => route.request().url().startsWith(origin) ? route.continue() : route.abort());
const page = await context.newPage();
page.on('console', msg => { if (msg.type() === 'error') result.visibleErrors.push(msg.text()); });
page.on('pageerror', error => result.visibleErrors.push(error.message));
const searchUrl = '**/api/search?q=retry-transport-test*'; let searchCalls = 0;
await context.route(searchUrl, async route => {
searchCalls++; result.injected.push({ path: '/api/search', attempt: searchCalls, fault: searchCalls === 1 ? '503' : null });
if (searchCalls === 1) return route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'temporary proxy fault' }) });
return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, results: [{ id: 'abcdefghijk', title: 'Retry fixture result', channel: 'Harness', duration: 60, thumbnail: '' }] }) });
});
await page.goto(origin);
await page.waitForFunction(() => typeof data !== 'undefined' && document.querySelector('#searchInput'));
let versionCalls = 0;
await context.route('**/api/version', async route => {
versionCalls++; result.injected.push({ path: '/api/version', attempt: versionCalls, fault: versionCalls === 1 ? '503' : null });
if (versionCalls === 1) return route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'temporary version check failure' }) });
return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ buildTag: 'retry-harness' }) });
});
assert.equal(await page.evaluate(() => fetchServerBuild()), 'retry-harness');
assert.equal(versionCalls, 2, `${engine}: update version check did not retry`);
result.recovered.push({ path: '/api/version', attempts: versionCalls });
await page.locator('#searchInput').fill('retry-transport-test'); await page.locator('#searchForm').evaluate(form => form.requestSubmit());
await page.locator('.card').filter({ hasText: 'Retry fixture result' }).waitFor({ timeout: 25000 });
result.recovered.push({ path: '/api/search', attempts: searchCalls });
assert.equal(searchCalls, 2, `${engine}: search did not retry exactly once`);
assert.equal(await page.locator('.retry-btn,.related-retry').count(), 0, `${engine}: transient search exposed a manual retry`);
let streamCalls = 0;
await context.route('**/api/streams?v=abcdefghijk*', async route => {
streamCalls++; result.injected.push({ path: '/api/streams', attempt: streamCalls, fault: streamCalls === 1 ? '503' : null });
if (streamCalls === 1) return route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'temporary upstream failure' }) });
return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, data: { meta: { id: 'abcdefghijk', title: 'Stream fixture' }, qualities: [] } }) });
});
const streams = await page.evaluate(() => API.getStreams('abcdefghijk'));
assert.equal(streamCalls, 2, `${engine}: stream lookup did not retry`);
assert.equal(streams.ok, true);
result.recovered.push({ path: '/api/streams', attempts: streamCalls });
let relatedCalls = 0;
await context.route('**/api/related?*', async route => {
relatedCalls++; result.injected.push({ path: '/api/related', attempt: relatedCalls, fault: relatedCalls === 1 ? 'connection-reset' : null });
if (relatedCalls === 1) return route.abort('failed');
return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, results: [{ id: 'lmnopqrstuv', title: 'Related recovered', channel: 'Harness' }] }) });
});
const relatedState = await page.evaluate(async () => {
current = { meta: { id: 'abcdefghijk', title: 'Retry fixture result', channel: 'Harness' } };
await loadRelated(); return relatedState.status;
});
assert.equal(relatedCalls, 2, `${engine}: related discovery did not retry`);
assert.equal(relatedState, 'ready');
assert.equal(await page.locator('.related-retry').count(), 0, 'transient failure must not expose manual Retry');
result.recovered.push({ path: '/api/related', attempts: relatedCalls });
let chunkCalls = 0;
await context.route('**/video-edit.js?v=*', async route => {
chunkCalls++; result.injected.push({ path: '/video-edit.js', attempt: chunkCalls, fault: chunkCalls === 1 ? 'connection-reset' : null });
if (chunkCalls === 1) return route.abort('failed');
return route.continue();
});
await page.evaluate(() => Lazy.load('feature:video-edit'));
assert.equal(chunkCalls, 2, `${engine}: lazy chunk did not retry`);
assert.equal(await page.locator('.retry-btn,.related-retry').count(), 0);
result.recovered.push({ path: '/video-edit.js', attempts: chunkCalls });
const unexpected = result.visibleErrors.filter(message => !/Failed to load resource|Load failed/.test(message));
assert.deepEqual(unexpected, [], `${engine}: page errors after transient recovery`);
console.log(JSON.stringify(result));
} catch (error) { console.error(engine, log); throw error; }
finally { await context?.close(); await browser?.close(); await proxy?.close?.(); child.kill('SIGTERM'); }
}
console.log(`Retry recovery passed (${results.length} engine(s), ${profile}).`);

84
perf/settings-layout.mjs Normal file
View File

@@ -0,0 +1,84 @@
#!/usr/bin/env node
// Settings layout regression checks across responsive widths, layouts and themes.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, mkdir } from 'node:fs/promises';
import { resolve, extname } from 'node:path';
import { chromium, webkit } from 'playwright';
const root = resolve('frontend'), shots = resolve('plans/settings-shots');
await mkdir(shots, { recursive: true });
const mime = { '.html':'text/html', '.js':'text/javascript', '.mjs':'text/javascript', '.css':'text/css', '.json':'application/json', '.woff2':'font/woff2', '.svg':'image/svg+xml', '.png':'image/png' };
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const path = resolve(root, '.' + (url.pathname === '/' ? '/index.html' : url.pathname));
if (!path.startsWith(root + '/')) { res.writeHead(403).end(); return; }
try { const body = await readFile(path); res.writeHead(200, { 'Content-Type':mime[extname(path)] || 'application/octet-stream' }).end(body); }
catch { res.writeHead(404).end(); }
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
const origin = `http://127.0.0.1:${server.address().port}`;
const layouts = ['classic','f7-swipe','glass-stage','bento-hub'], themes = ['dark','light','contrast'], widths = [390,768,1280,1440,1920];
const failures = [], results = [];
try {
for (const [engineName, engine] of Object.entries({ chromium, webkit })) {
const browser = await engine.launch();
try {
const context = await browser.newContext({ viewport:{width:1280,height:1000}, serviceWorkers:'block' });
await context.route('**/*', route => route.request().url().startsWith(origin) ? route.continue() : route.abort());
await context.addInitScript(() => localStorage.setItem('_ytpdata', JSON.stringify({
playlists:[], history:[], queue:[], settings:{layout:'glass-stage',theme:'dark',quality:'auto',jamesDsp:{enabled:true,downloadForOffline:false,preset:'warm',params:{'convolver.enabled':1,'spatial.enabled':1},irRef:{name:'Small room'}}}
})));
const page = await context.newPage();
page.on('pageerror', error => failures.push(`${engineName}: pageerror ${error.message}`));
await page.goto(origin);
await page.waitForFunction(() => typeof data !== 'undefined' && typeof Lazy !== 'undefined');
await page.waitForFunction(() => performance.getEntriesByName('ytp:boot').length > 0);
for (const css of ['theme-classic.css','theme-f7.css','theme-glass.css','theme-glass-panel.css','theme-glass-controls.css','theme-bento-hub.css']) await page.addStyleTag({ path:resolve(root,css) });
for (const layout of layouts) {
for (const theme of themes) for (const width of widths) {
await page.setViewportSize({ width, height:1000 });
await page.evaluate(({theme,layout}) => { data.settings.theme=theme; data.settings.layout=layout; data.settings.jamesDsp.enabled=true; document.documentElement.dataset.theme=theme; document.documentElement.dataset.layout=layout; if(typeof EQ!=='undefined')EQ.listDspIRs=async()=>[]; view={type:'settings'}; render(); }, {theme,layout});
await page.waitForSelector('.settings-browser .settings-section-row[data-section="playback"]',{state:'attached'});
await page.evaluate(()=>{const host=document.querySelector('.settings-browser');host.dataset.detail='1';document.querySelectorAll('.settings-section').forEach(panel=>panel.hidden=panel.id!=='settings-section-playback');document.getElementById('jamesDspControls').hidden=false;});
await page.waitForSelector('#setDspSpatialMode',{state:'attached'});
const measured = await page.evaluate(() => {
const rect = e => { const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height,right:r.right}; };
const selectors=['.settings-browser','.settings-grid','.settings-detail','#listPane .cards','#jamesDspSettings','.dsp-subsection'];
const boxes=Object.fromEntries(selectors.map(s=>{const e=document.querySelector(s);return [s,e?{clientWidth:e.clientWidth,scrollWidth:e.scrollWidth,rect:rect(e)}:null];}));
const rows=[...document.querySelectorAll('#jamesDspSettings .set-row')].map(row=>{
const label=row.querySelector(':scope > span:first-child'),control=row.querySelector(':scope > input,:scope > select,:scope > .set-control-wrap,:scope > .dsp-file-control');
return {text:row.textContent.trim().slice(0,90),label:label?rect(label):null,control:control?{...rect(control),scrollWidth:control.scrollWidth,clientWidth:control.clientWidth,overflow:getComputedStyle(control).overflow,select:control.querySelector('select')?{...rect(control.querySelector('select')),scrollWidth:control.querySelector('select').scrollWidth,clientWidth:control.querySelector('select').clientWidth}:null}:null,row:rect(row)};
});
const file=document.querySelector('#dspIrFile'),checkbox=document.querySelector('#setDspConvolver'),buttons=[...document.querySelectorAll('.dsp-subsection > button')];
const selects=[...document.querySelectorAll('.settings-browser select')].map(s=>({id:s.id,appearance:getComputedStyle(s).appearance,backgroundImage:getComputedStyle(s).backgroundImage,backgroundColor:getComputedStyle(s).backgroundColor}));
const overflows=[...document.querySelectorAll('#jamesDspSettings *')].filter(e=>e.scrollWidth>e.clientWidth+1).map(e=>({tag:e.tagName,id:e.id,cls:e.className,text:e.textContent.trim().slice(0,100),scroll:e.scrollWidth,client:e.clientWidth,rect:rect(e)}));
return {boxes,rows,file:{clipPath:getComputedStyle(file).clipPath,rect:rect(file),parent:rect(file.parentElement)},checkbox:{appearance:getComputedStyle(checkbox).appearance,width:rect(checkbox).width},selects,buttons:buttons.map(b=>({whiteSpace:getComputedStyle(b).whiteSpace,scrollWidth:b.scrollWidth,clientWidth:b.clientWidth,rect:rect(b)})),overflows,page:{scrollWidth:document.documentElement.scrollWidth,clientWidth:document.documentElement.clientWidth}};
});
const key=`${engineName}/${layout}/${theme}/${width}`;
for (const [selector,box] of Object.entries(measured.boxes)) if(box) {
if(box.scrollWidth>box.clientWidth+1) failures.push(`${key}: ${selector} horizontal overflow ${box.scrollWidth}/${box.clientWidth}`);
}
if(measured.page.scrollWidth>measured.page.clientWidth+1) failures.push(`${key}: document horizontal overflow ${measured.page.scrollWidth}/${measured.page.clientWidth}`);
for(const row of measured.rows) if(row.label&&row.control&&row.control.x<row.label.x+Math.min(row.label.width,80)) failures.push(`${key}: control overlaps/collapses into label`);
if(measured.checkbox.appearance!=='none'||measured.checkbox.width<40) failures.push(`${key}: DSP checkbox is not a themed switch`);
for(const select of measured.selects) if(select.appearance!=='none'||select.backgroundImage==='none'||select.backgroundColor==='rgba(0, 0, 0, 0)') failures.push(`${key}: select #${select.id} is not themed`);
if(measured.file.rect.width>1||measured.file.clipPath==='none') failures.push(`${key}: native file picker is visible`);
for(const b of measured.buttons) if(b.whiteSpace!=='nowrap'||b.rect.height>50) failures.push(`${key}: DSP action button wraps vertically`);
results.push({engine:engineName,layout,theme,width,...measured});
if(width===1280) await page.screenshot({path:resolve(shots,`${engineName}-${layout}-${theme}.png`),fullPage:true});
if(width===1280&&layout==='glass-stage'&&theme==='dark') {
await page.locator('#dspConvolverTitle').scrollIntoViewIfNeeded();
await page.screenshot({path:resolve(shots,`${engineName}-glass-stage-dark-dsp.png`),fullPage:true});
await page.locator('#dspSpatialTitle').scrollIntoViewIfNeeded();
await page.screenshot({path:resolve(shots,`${engineName}-glass-stage-dark-spatial.png`),fullPage:true});
}
}
}
await context.close();
} finally { await browser.close(); }
}
} finally { await new Promise(r=>server.close(r)); }
await (await import('node:fs/promises')).writeFile(resolve(shots,'measurements.json'),JSON.stringify({cases:results.length,failures,screenshots:results.filter(r=>r.width===1280).map(r=>`${r.engine}-${r.layout}-${r.theme}.png`)},null,2));
console.log(`Settings layout: ${results.length} cases, ${failures.length} failures; screenshots in plans/settings-shots/`);
if(failures.length) { console.error(failures.slice(0,30).join('\n')); process.exitCode=1; }

View File

@@ -10,7 +10,7 @@ import {createRequire} from 'node:module';
import {chromium,webkit} from 'playwright';
const repo=resolve(import.meta.dirname,'..'),args=process.argv.slice(2);
const opt=(k,d)=>args.includes(k)?args[args.indexOf(k)+1]:d;
const oldTag='1175f1a1d2c1',target=opt('--target','main'),engine=opt('--browser','all');
const oldTag='1175f1a1d2c1',target=opt('--target','HEAD'),engine=opt('--browser','all');
assert.ok(['all','chromium','webkit'].includes(engine));
execFileSync('bash',[join(repo,'perf/make-shell-fixture.sh'),'b77938a',oldTag],{cwd:repo,stdio:'inherit'});
const scratch=mkdtempSync(join(repo,'perf/.tmp/settings-'));
@@ -21,7 +21,7 @@ symlinkSync(join(repo,'perf/fixtures/shell-'+oldTag),join(scratch,'old/server/pu
symlinkSync(join(scratch,'new/frontend'),join(scratch,'new/server/public'));
const results={revision,oldTag,results:[],failures:[],unsupported:[]};
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
async function poll(fn,timeout=90000){const until=Date.now()+timeout;while(Date.now()<until){if(await fn())return;await sleep(100);}throw Error('Condition timed out');}
async function poll(fn,timeout=90000){const until=Date.now()+timeout;while(Date.now()<until){if(await fn())return true;await sleep(100);}throw Error('Condition timed out');}
const ui={saveBeforePlay:['setSaveBeforePlay',true],autoPreload:['setAutoPreload',true],audioOnly:['setAudioOnly',false],quality:['setQuality','360p'],repeatMode:['setRepeat',true],loopOne:['setLoopOne',true],theme:['setTheme','light'],fontScale:['setFont','large'],density:['setDensity','compact'],perfMode:['setPerf',true],reduceMotion:['setMotion',true],parallelSaves:['setParallelSaves','2'],levelVolume:['setLevelVolume',false],layout:['setLayout','f7-swipe']};
async function run(name){
const cwd=join(scratch,name);mkdirSync(cwd);mkdirSync(join(cwd,'media'));
@@ -49,7 +49,7 @@ async function run(name){
await context.route('**/*',route=>route.request().url().startsWith(origin)?route.continue():route.abort());
const page=await context.newPage();page.on('pageerror',e=>result.errors.push(e.message));
const boot=async()=>{await page.goto(origin);await page.waitForFunction(()=>typeof data!=='undefined'&&document.querySelector('#sidebarToggle'));await page.waitForTimeout(800);};
const settings=()=>page.evaluate(()=>JSON.parse(localStorage.getItem('_ytpdata')).settings);
const settings=()=>page.evaluate(()=>JSON.parse(JSON.stringify(data.settings)));
const openSettings=async()=>{await page.locator('[data-view="settings"]').first().evaluate(e=>e.click());await page.waitForSelector('#setSaveBeforePlay',{state:'attached'});};
const readUI=()=>page.evaluate(ids=>Object.fromEntries(ids.map(id=>{const e=document.getElementById(id);return[id,e.type==='checkbox'?e.checked:e.value];})),Object.values(ui).map(x=>x[0]));
await boot();await page.waitForFunction(()=>!!navigator.serviceWorker.controller);
@@ -67,9 +67,16 @@ async function run(name){
await page.waitForFunction(()=>!document.getElementById('modal').classList.contains('hidden')&&/Update available/.test(document.getElementById('modalTitle').textContent));
await page.locator('#modal').getByRole('button',{name:'Refresh UI',exact:true}).evaluate(e=>e.click());await page.waitForFunction(tag=>document.querySelector('meta[name="ytp-build"]')?.content===tag,result.newTag,{timeout:90000});await sleep(1000);await openSettings();
console.log(name,'real Refresh UI completed');result.upgraded=await settings();result.newRaw=await page.evaluate(()=>localStorage.getItem('_ytpdata'));result.newUI=await readUI();assert.deepEqual(result.newUI,result.oldUI,'checkbox/select values preserved');
const {migrate}=require(join(scratch,'new/frontend/eq-parameters.js'));const expected=structuredClone(result.old);if(expected.eq?.g?.length===5)expected.eq.g=migrate(expected.eq.g);
for(const key of new Set([...Object.keys(result.old),...Object.keys(result.upgraded)]))result.diff.push({key,before:result.old[key],after:result.upgraded[key],equal:JSON.stringify(result.old[key])===JSON.stringify(result.upgraded[key]),expectedMigration:key==='eq'&&result.old.eq?.g?.length===5});
const {migrate}=require(join(scratch,'new/frontend/eq-parameters.js'));const expected=structuredClone(result.old);if(expected.eq?.g?.length===5)expected.eq.g=migrate(expected.eq.g);expected.jamesDsp={enabled:false,downloadForOffline:false,preset:'flat',params:{},irRef:null,...(expected.jamesDsp||{}),params:expected.jamesDsp?.params||{}};
for(const key of new Set([...Object.keys(result.old),...Object.keys(result.upgraded)]))result.diff.push({key,before:result.old[key],after:result.upgraded[key],equal:JSON.stringify(result.old[key])===JSON.stringify(result.upgraded[key]),expectedMigration:(key==='eq'&&result.old.eq?.g?.length===5)||(key==='jamesDsp'&&!result.old.jamesDsp)});
assert.deepEqual(result.upgraded,expected,'all persisted settings preserved except deliberate 5→10 EQ migration');await behaviour('upgraded');
await openSettings();await page.locator('[data-section="playback"]').evaluate(e=>e.click());await page.locator('#setDspPreset').evaluate(e=>{e.value='warm';e.dispatchEvent(new Event('change',{bubbles:true}));});
for(const [key,value] of [['eq.band0','3'],['tube.drive','1.5']])await page.locator(`[data-dsp-param="${key}"]`).evaluate((e,v)=>{e.value=v;e.dispatchEvent(new Event('input',{bubbles:true}));},value);
await sleep(600);await page.reload();await page.waitForFunction(()=>typeof data!=='undefined');await openSettings();await page.locator('[data-section="playback"]').evaluate(e=>e.click());
const james=await page.evaluate(()=>data.settings.jamesDsp);assert.deepEqual(james,{enabled:false,downloadForOffline:false,preset:'warm',params:{'eq.band0':3,'tube.drive':1.5},irRef:null});assert.equal(await page.locator('#setSoundEngine').inputValue(),'standard');assert.equal(await page.locator('#setDspPreset').inputValue(),'warm');
await page.locator('#setDspOffline').check();const wasmReady=await poll(()=>page.evaluate(async()=>{const m=JSON.parse(document.getElementById('ytp-assets').textContent),c=await caches.open('ytplayer-assets');return !!await c.match('/vendor/jamesdsp/dsp/jamesdsp.wasm?v='+m.files['/vendor/jamesdsp/dsp/jamesdsp.wasm'].h);}));assert.equal(wasmReady,true,'offline opt-in eventually caches the optional WASM');const optInPersisted=await poll(()=>page.evaluate(()=>JSON.parse(localStorage.getItem('_ytpdata')||'{}').settings?.jamesDsp?.downloadForOffline===true));assert.equal(optInPersisted,true,'offline opt-in setting survives local persistence debounce');
await page.reload();await page.waitForFunction(()=>typeof data!=='undefined');await openSettings();await page.locator('[data-section="playback"]').evaluate(e=>e.click());assert.equal(await page.locator('#setDspOffline').isChecked(),true);result.jamesDspSettingsPersisted=true;
await page.evaluate(()=>{data.settings.jamesDsp.enabled=false;persist();});
const local=await settings(),remote={...local,saveBeforePlay:false,autoPreload:false,layout:'classic',quality:'auto'};
async function profileCheck(updatedAt,expectedSave,stage){profileReply={ok:true,name:'probe',updatedAt,data:{settings:remote,playlists:[]}};await page.evaluate(s=>{data.settings=s;data.profile={name:'probe',syncedAt:200};localStorage.setItem('_ytpdata',JSON.stringify(data));},local);await boot();await page.waitForFunction(()=>_syncBusy===0);await openSettings();const s=await settings();assert.equal(s.saveBeforePlay,expectedSave);assert.equal(await page.locator('#setSaveBeforePlay').isChecked(),expectedSave);if(!expectedSave)assert.equal(s.layout,'classic');else assert.deepEqual(s,local);result.profileChecks.push({stage,serverUpdatedAt:updatedAt,localSyncedAt:200,saveBeforePlay:s.saveBeforePlay});}
await profileCheck(100,true,'older timestamp ignored');await profileCheck(300,false,'older settings with newer timestamp adopted');

30
plans/jamesdsp-audit.md Normal file
View File

@@ -0,0 +1,30 @@
# JamesDSP integration audit
Date: 2026-10-09
Base: `933e920` (`main`, Phase 0–5, offline completion, UI and transport integration)
## Audio ownership found in the current runtime
| Concern | Current owner / finding | Integration consequence |
|---|---|---|
| Realtime context | `EQ` in `frontend/app.js` is the only runtime constructor (`new AC()` around line 5532). | Preserve this exact lazy creation point. JamesDSP may not instantiate another context. |
| Media element sources | `EQ.attach()` is the only runtime `createMediaElementSource()` call (around line 5559); it records sources by element in `st.sources`. | Extract this into one AudioGraph owner with a retained `WeakMap`/`Map`. Never retry creation for a previously attached media element. |
| Playback elements | `Player.master`, `Player.secondary`, and `Player.soundEl` change between `els.video` and `els.audio` for dual/audio-only playback and handoffs. `EQ.apply()` attaches both video and audio elements. | Attach each element once; route both through the same selected insert. Do not tie graph lifetime to a track or to `Player.master`. |
| Continuity and transitions | `audio-continuity.js` owns play/resume/alignment. `Transition` changes the active master and uses a bridge element; the bridge is not currently connected to EQ. | Keep continuity and bridge timing unchanged. A JamesDSP route applies to the same player elements as the Standard route; do not source the bridge or alter transition policy. |
| iOS live processing | `EQ.available()` is false on iOS unless `data.settings.liveAudioIOS === true` (around line 5516). `EqRender` prepares saved audio with a 32 kHz `OfflineAudioContext`. | Gate live JamesDSP on the same setting and supported realtime graph. V1 does not process EqRender output; a DSP graph must never be layered over an already-rendered Standard EQ copy. |
| Level / limiter | `Level` measures at 22.05 kHz offline and applies dB gain through `EQ.setLevel()`. The realtime Standard chain ends in a compressor limiter. | Preserve the Level measurement and dB value. In JamesDSP mode map it into the engine gain with a documented combined-gain clamp; Standard remains untouched. |
| EqRender | `EqRender` renders cached media through an offline graph at 32 kHz and saves `eq-renders` OPFS copies. It is independent from the single realtime `AudioContext`. | Leave this renderer and its bytes unchanged. Until offline worklet rendering is proven, JamesDSP does not claim to process saved/rendered copies. |
| VocalReducer / widener | Loaded lazily by `feature:vocal-reducer` and `feature:eq-core`, then connected in `EQ.build()`. | In JamesDSP mode disconnect the Standard insert. Do not create either lazy Standard effect solely to initialize JamesDSP. |
| Cold path | `audio-continuity.js`, `eq-parameters.js`, and `app.js` are core assets. JamesDSP has no existing runtime assets. | Keep all new vendor/worklet/wasm/controller files exclusively in lazy `feature:jamesdsp`; the small graph owner may be core only if unavoidable, and its cost must be checked against integration cold-start medians. |
## Seam and compatibility decisions
Phase 2 will add a small `frontend/audio-graph.js` core seam because it gives the one-context/one-source invariant an independently testable owner. It will create the context only when the existing EQ asks for it, retain each element source for the page lifetime, and expose controlled Standard and optional JamesDSP route operations. It will not change playback, transition, or volume code. The new core request is a measured risk: compare cold FCP/bytes to `plans/integration-report.md` and inline the seam into an existing core module if it causes a regression.
The Standard graph's node order, filter constants, gain automation, lazy-load triggers, and destination routing are a frozen compatibility contract. Phase 2 will add a graph trace test comparing the old route with the extracted route, plus deterministic sample-response tests for the Standard chain. JamesDSP activation is opt-in and serialized: restore Standard before destroying a failed node, never create a replacement until the previous 128 MiB node is destroyed, and reject the engine when the existing context rate is not 44.1 or 48 kHz. The existing context is never closed/recreated to request 48 kHz.
The standalone port verifies 44.1/48 kHz, a fixed 128 MiB heap, immediate exact bypass, and configuration that can pause worklet rendering. It has no Safari/iPhone verification. V1 will report JamesDSP live processing unavailable on iOS unless `liveAudioIOS` is on; EqRender/offline rendered playback remains Standard. Text effects (Liveprog, DDC, arbitrary text EQ) will be neither shown nor accepted by the v1 settings/import surface. IR state is memory-only because JSON presets do not contain its PCM.
## Licensing and release boundaries
The standalone source is pinned by commit in the vendor `VERSION` file and its supplied notices are retained. Its upstream `Main/LICENSE` contains GPL-2.0 text while the port documents GPL-3.0-or-later additions; this discrepancy is recorded and no license file will be silently rewritten. A redistribution decision remains an owner release matter. The user instruction prohibits pushing or deploying, so Phase 7 will prepare beta listening notes only and will not publish a beta build.

View File

@@ -0,0 +1,30 @@
# JamesDSP integration report — 2026-10-10
JamesDSP now uses the shared `AudioGraph`, remains opt-in, and is delivered as a lazy feature. The upstream port is pinned to `a982b53c4ab347d1d9c50f4ce7ee3c2735eaa817`. It adds four-channel convolution, generated and IndexedDB-stored IRs, spatial/HRTF processing, and 8–96 kHz sample-rate conversion. Settings expose IR selection/upload and bounded controls for convolution and spatial audio. Long IRs are constrained on low-resource devices. Standard remains an exact bypass route; failed DSP/WASM initialization returns to Standard. iOS playback remains gated by `liveAudioIOS`.
The legacy lossy-update timeout came from the new worker hashing/copying the entire legacy shell during `activate`, while the b77938a page reloads on a short timer after the user presses Refresh UI. The worker now stages and verifies legacy assets during `install`; activation only commits the staged cache. The lossy migration harness passes both engines, preserving the user-initiated legacy update flow.
The DSP WASM is now marked `offlineOptIn: "jamesDsp"`. Normal completion caches the 103 required files and defers all 9 optional DSP files, including the ~1.2 MB WASM. Enabling “download audio effects for offline” persists the opt-in and resumes completion. Cold transfer is back near the pre-DSP baseline.
| Verification | Result |
|---|---|
| Frontend tests | 271 passed, 0 failed |
| Server tests | Previously run after integration: all pass except the two known `yt_dlp` environment failures; remaining server tests passed individually |
| Offline completion | Chromium + WebKit: 112/112 after explicit opt-in; 103 required + 9 optional deferred by default; zero missing/failures |
| Lazy / hidden timers | Both browsers pass; lazy asserts DSP WASM remains uncached by default; no hidden-timer page errors |
| UI geometry / icons | 384 geometry cases and 24 layout/theme icon cases passed |
| Settings persistence | Old-client Refresh UI preserved all existing keys in both engines; only intentional additions/migrations are the disabled `jamesDsp` default and 5→10 EQ migration. Save-before-play works before and after update. DSP preset/parameters and offline opt-in persist. Linux WebKit lacks native OPFS, so its save-play assertion is explicitly unsupported. |
| DSP harness | Both engines pass: four-channel IR changes output (interaural RMS 0.00735), spatial stage changes it (0.02154 vs dry 0), 32 kHz context, exact bypass, offline reload with stored IR, one DSP heap, corrupt-WASM fallback |
Migration (`node perf/migration.mjs --browser all`) passed lossy and unthrottled after the worker fix. Lossy wire totals: Chromium 652,568 bytes / 26.4 s; WebKit 746,826 bytes / 20.1 s. Unthrottled: Chromium 664,110 bytes / 11.2 s; WebKit 790,706 bytes / 7.7 s. Each run showed one banner/reload, offline launch, and playback guard.
Three-run cold LTE medians (`node perf/baseline.mjs --runs 3 --browser all --profile lte --scenario cold`):
| Engine | FCP before → now | LCP now | Wire before → now | Requests now | Positive `app.js` responses |
|---|---:|---:|---:|---:|---:|
| Chromium | 1360 → 1348 ms | 1348 ms | 648 KB → 1.82 MB → 673,992 B | 117 | 1 |
| WebKit | 895 → 908 ms | 976 ms | 976 KB → 2.14 MB → 1,020,231 B | 161 | 1 |
The wire columns are pre-DSP baseline → initial DSP integration before the opt-in correction → current. The correction removes roughly 1.2 MB from first install while leaving the DSP assets available after explicit opt-in.
The harness JSON is `perf/.tmp/dsp-cold-final.json`; it records 274 ms Chromium long-task total and 0 ms in WebKit. No real iPhone, lock-screen session, thermal behavior, or listening/ear-tuning test was possible. Verify iOS opt-in, background audio, CPU use with long IRs, and the perceived level/space before enabling this for users. Phase 7 deployment was not run.

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 444 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 419 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 498 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

View File

@@ -0,0 +1,30 @@
{
"cases": 120,
"failures": [],
"screenshots": [
"chromium-classic-dark.png",
"chromium-classic-light.png",
"chromium-classic-contrast.png",
"chromium-f7-swipe-dark.png",
"chromium-f7-swipe-light.png",
"chromium-f7-swipe-contrast.png",
"chromium-glass-stage-dark.png",
"chromium-glass-stage-light.png",
"chromium-glass-stage-contrast.png",
"chromium-bento-hub-dark.png",
"chromium-bento-hub-light.png",
"chromium-bento-hub-contrast.png",
"webkit-classic-dark.png",
"webkit-classic-light.png",
"webkit-classic-contrast.png",
"webkit-f7-swipe-dark.png",
"webkit-f7-swipe-light.png",
"webkit-f7-swipe-contrast.png",
"webkit-glass-stage-dark.png",
"webkit-glass-stage-light.png",
"webkit-glass-stage-contrast.png",
"webkit-bento-hub-dark.png",
"webkit-bento-hub-light.png",
"webkit-bento-hub-contrast.png"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 KiB

View File

@@ -150,18 +150,3 @@ test('player lyric editor groups Shift+Enter words and stamps their shared cue',
const document = await text.inputValue(); expect(document).toContain('[0:00.00] Because You are God\n| You can do anything');
expect(document).not.toContain('[0:00.00] |');
});
test('editor loads the whole audio into the browser once and reuses it', async ({ page }) => {
const wav = Buffer.alloc(44 + 16000); // 1 s of silence, 8 kHz 16-bit mono
wav.write('RIFF', 0); wav.writeUInt32LE(36 + 16000, 4); wav.write('WAVEfmt ', 8); wav.writeUInt32LE(16, 16);
wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(8000, 24); wav.writeUInt32LE(16000, 28);
wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34); wav.write('data', 36); wav.writeUInt32LE(16000, 40);
let hits = 0;
await fixture(page);
await page.route('**/api/media/' + id + '?a=1', route => { hits++; route.fulfill({ contentType: 'audio/wav', body: wav }); });
await page.locator('[data-open="' + id + '"]').first().click();
await expect(page.locator('#dur')).toHaveText('0:01');
expect(hits).toBe(1);
await page.reload(); await page.locator('[data-open="' + id + '"]').first().click();
await expect(page.locator('#dur')).toHaveText('0:01');
expect(hits).toBe(1);
});

31
tests/fixtures/standard-eq-build.txt vendored Normal file
View File

@@ -0,0 +1,31 @@
function build() {
if (st.ctx) return true;
if (!Lazy.loaded('feature:eq-core') || !Lazy.loaded('feature:vocal-reducer')) {
loadSoundFeatures().then(()=>{apply(); Level.apply();}).catch(error=>toast(error.message));
return false;
}
try {
st.ctx = new AC();
st.filters = EQ_BANDS.map((b) => {
const f = st.ctx.createBiquadFilter();
f.type = b.type;
f.frequency.value = b.f;
f.Q.value = 1.0;
return f;
});
for (let i = 0; i < st.filters.length - 1; i++) st.filters[i].connect(st.filters[i + 1]);
// Loudness levelling: gain toward -14 LUFS, then a limiter so a boosted
// quiet track can never clip.
st.level = st.ctx.createGain();
st.limiter = st.ctx.createDynamicsCompressor();
st.limiter.threshold.value = -1; st.limiter.knee.value = 0; st.limiter.ratio.value = 20;
st.limiter.attack.value = 0.003; st.limiter.release.value = 0.25;
st.vocal = VocalReducer.create(st.ctx, st.filters[st.filters.length - 1]);
st.widener = EqCore.createWidener(st.ctx, st.vocal.output);
st.widener.output.connect(st.level);
st.level.connect(st.limiter);
st.limiter.connect(st.ctx.destination);
return true;
} catch { st.ctx = null; return false; }
}