Update css/player-base.js

This commit is contained in:
ashley 2025-10-22 21:38:02 +02:00
parent 4ca6bbf7e1
commit 1be26d2f1d

View File

@ -15,7 +15,7 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
* <https://github.com/mozilla/vtt.js/blob/main/LICENSE> * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
*/ */
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
const video = videojs('video', { const video = videojs('video', {
controls: true, controls: true,
autoplay: false, autoplay: false,
preload: 'auto', preload: 'auto',
@ -30,13 +30,12 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
const videoEl = document.getElementById('video'); const videoEl = document.getElementById('video');
const audio = document.getElementById('aud'); const audio = document.getElementById('aud');
// iOS/Safari inline hint
try { try {
videoEl.setAttribute('playsinline', ''); videoEl.setAttribute('playsinline', '');
videoEl.setAttribute('webkit-playsinline', ''); videoEl.setAttribute('webkit-playsinline', '');
} catch {} } catch {}
video.ready(() => { video.ready(() => {
const metaTitle = document.querySelector('meta[name="title"]')?.content || ""; const metaTitle = document.querySelector('meta[name="title"]')?.content || "";
const metaDesc = document.querySelector('meta[name="twitter:description"]')?.content || ""; const metaDesc = document.querySelector('meta[name="twitter:description"]')?.content || "";
const metaAuthor = document.querySelector('meta[name="twitter:author"]')?.content || ""; const metaAuthor = document.querySelector('meta[name="twitter:author"]')?.content || "";
@ -52,31 +51,27 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} }
const createTitleBar = () => { const createTitleBar = () => {
try { const existing = video.getChild("TitleBar");
const existing = video.getChild?.("TitleBar"); if (!existing) {
if (!existing) { const titleBar = video.addChild("TitleBar");
const titleBar = video.addChild?.("TitleBar"); titleBar.update({ title: metaTitle, description: stats });
titleBar?.update?.({ title: metaTitle, description: stats }); }
}
} catch {}
}; };
const removeTitleBar = () => { const removeTitleBar = () => {
try { const existing = video.getChild("TitleBar");
const existing = video.getChild?.("TitleBar"); if (existing) video.removeChild(existing);
if (existing) video.removeChild?.(existing);
} catch {}
}; };
const handleFullscreen = () => { const handleFullscreen = () => {
const fs = document.fullscreenElement || document.webkitFullscreenElement; const fs = document.fullscreenElement || document.webkitFullscreenElement;
if (fs) createTitleBar(); if (fs) createTitleBar();
else removeTitleBar(); else removeTitleBar();
}; };
document.addEventListener("fullscreenchange", handleFullscreen); document.addEventListener("fullscreenchange", handleFullscreen, { passive: true });
document.addEventListener("webkitfullscreenchange", handleFullscreen); document.addEventListener("webkitfullscreenchange", handleFullscreen, { passive: true });
handleFullscreen(); handleFullscreen();
}); });
let syncing = false; let syncing = false;
let restarting = false; let restarting = false;
let firstSeekDone = false; let firstSeekDone = false;
@ -93,36 +88,20 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
let userMutedAudio = false; let userMutedAudio = false;
let lastPlayKickTs = 0; let lastPlayKickTs = 0;
const STARTUP_GRACE_MS = 2200; // longer grace to ignore early stalls const STARTUP_GRACE_MS = 2200;
// anti-random-mute controls
let seekingActive = false; let seekingActive = false;
let squelchMuteEvents = 0; let squelchMuteEvents = 0;
let suppressMirrorUntil = 0; let suppressMirrorUntil = 0;
const MUTE_SQUELCH_MS = 500; const MUTE_SQUELCH_MS = 500;
// startup quiet phase to prevent play->pause jitter and audio pops
let startupPhase = true; let startupPhase = true;
let firstPlayCommitted = false; let firstPlayCommitted = false;
try { videoEl.loop = false; videoEl.removeAttribute?.('loop'); } catch {} try { videoEl.loop = false; videoEl.removeAttribute?.('loop'); } catch {}
try { audio.loop = false; audio.removeAttribute?.('loop'); } catch {} try { audio.loop = false; audio.removeAttribute?.('loop'); } catch {}
const abort = new AbortController(); const clamp01 = v => Math.max(0, Math.min(1, Number(v)));
const on = (t, type, fn, opts) => t?.addEventListener(type, fn, { signal: abort.signal, ...(opts||{}) });
const timeouts = new Set();
const intervals = new Set();
const rafs = new Set();
const setT = (fn, ms) => { const id = setTimeout(fn, ms); timeouts.add(id); return id; };
const setI = (fn, ms) => { const id = setInterval(fn, ms); intervals.add(id); return id; };
const rAF = (fn) => { const id = requestAnimationFrame(fn); rafs.add(id); return id; };
const clearAllTimers = () => {
intervals.forEach(clearInterval); intervals.clear();
timeouts.forEach(clearTimeout); timeouts.clear();
rafs.forEach(cancelAnimationFrame); rafs.clear();
};
const clamp01 = v => Math.max(0, Math.min(1, Number(v)));
const EPS = 0.15; const EPS = 0.15;
const MICRO_DRIFT = 0.05; const MICRO_DRIFT = 0.05;
const BIG_DRIFT = 0.5; const BIG_DRIFT = 0.5;
@ -132,41 +111,35 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
const PROGRESS_KEY = `progress-${vidKey}`; const PROGRESS_KEY = `progress-${vidKey}`;
const pickAudioSrc = () => { const pickAudioSrc = () => {
try { const s = audio?.getAttribute?.('src');
const s = audio?.getAttribute?.('src'); if (s) return s;
if (s) return s; const child = audio?.querySelector?.('source');
const child = audio?.querySelector?.('source'); if (child?.getAttribute?.('src')) return child.getAttribute('src');
if (child?.getAttribute?.('src')) return child.getAttribute('src'); if (audio?.currentSrc) return audio.currentSrc;
if (audio?.currentSrc) return audio.currentSrc;
} catch {}
return null; return null;
}; };
const srcObj = video.src?.(); const srcObj = video.src();
const videoSrc = Array.isArray(srcObj) ? (srcObj[0] && srcObj[0].src) : srcObj; const videoSrc = Array.isArray(srcObj) ? (srcObj[0] && srcObj[0].src) : srcObj;
const hasExternalAudio = !!audio && audio.tagName === 'AUDIO' && !!pickAudioSrc(); const hasExternalAudio = !!audio && audio.tagName === 'AUDIO' && !!pickAudioSrc();
let syncInterval = null; let syncInterval = null;
let lastAT = 0, lastATts = 0; // audio watchdog let lastAT = 0, lastATts = 0;
let aligning = false; // prevents overlapping soft-aligns let aligning = false;
let volAnim = null; let volAnim = null;
function setImmediateVolume(val) { function setImmediateVolume(val) {
try { if (audio) audio.volume = clamp01(val); } catch {} try { audio.volume = clamp01(val); } catch {}
} }
function getBaseTargetVol() { function getBaseTargetVol() {
// Prefer Video.js API if present; fall back to native const vVol = clamp01(typeof video.volume === 'function' ? video.volume() : videoEl.volume ?? 1);
let vVol = 1, vMuted = false; const vMuted = typeof video.muted === 'function' ? video.muted() : videoEl.muted;
try {
vVol = clamp01(typeof video.volume === 'function' ? video.volume() : (videoEl.volume ?? 1));
vMuted = typeof video.muted === 'function' ? video.muted() : !!videoEl.muted;
} catch {}
const hardMuted = vMuted || userMutedVideo || userMutedAudio; const hardMuted = vMuted || userMutedVideo || userMutedAudio;
return hardMuted ? 0 : vVol; return hardMuted ? 0 : vVol;
} }
function rampVolumeTo(target, ms = 60) { function rampVolumeTo(target, ms = 60) {
target = clamp01(target); target = clamp01(target);
const from = clamp01(audio?.volume ?? 0); const from = clamp01(audio.volume);
if (!isFinite(from)) { setImmediateVolume(target); return Promise.resolve(); } if (!isFinite(from)) { setImmediateVolume(target); return Promise.resolve(); }
if (ms <= 0 || Math.abs(target - from) < 0.001) { setImmediateVolume(target); return Promise.resolve(); } if (ms <= 0 || Math.abs(target - from) < 0.001) { setImmediateVolume(target); return Promise.resolve(); }
@ -181,10 +154,10 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
const t = Math.min(1, (performance.now() - start) / ms); const t = Math.min(1, (performance.now() - start) / ms);
const val = from + (target - from) * t; const val = from + (target - from) * t;
setImmediateVolume(val); setImmediateVolume(val);
if (t < 1) rafs.add(requestAnimationFrame(step)); if (t < 1) requestAnimationFrame(step);
else resolve(); else resolve();
}; };
rAF(step); requestAnimationFrame(step);
}); });
} }
async function softMuteAudio(ms = 40) { async function softMuteAudio(ms = 40) {
@ -198,7 +171,6 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} }
async function softAlignAudioTo(t, fadeDown = 40, fadeUp = 60) { async function softAlignAudioTo(t, fadeDown = 40, fadeUp = 60) {
if (!audio) return;
if (aligning) return; if (aligning) return;
aligning = true; aligning = true;
try { try {
@ -209,11 +181,10 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
aligning = false; aligning = false;
} }
} }
//
function timeInBuffered(media, t) { function timeInBuffered(media, t) {
try { try {
const br = media?.buffered; const br = media.buffered;
if (!br || br.length === 0 || !isFinite(t)) return false; if (!br || br.length === 0 || !isFinite(t)) return false;
for (let i = 0; i < br.length; i++) { for (let i = 0; i < br.length; i++) {
const s = br.start(i) - EPS, e = br.end(i) + EPS; const s = br.start(i) - EPS, e = br.end(i) + EPS;
@ -224,9 +195,9 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} }
function canPlayAt(media, t) { function canPlayAt(media, t) {
try { try {
const rs = Number(media?.readyState || 0); const rs = Number(media.readyState || 0);
if (!isFinite(t)) return false; if (!isFinite(t)) return false;
if (rs >= 3) return true; // HAVE_FUTURE_DATA if (rs >= 3) return true;
return timeInBuffered(media, t); return timeInBuffered(media, t);
} catch { return false; } } catch { return false; }
} }
@ -234,53 +205,77 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
return canPlayAt(videoEl, t) && canPlayAt(audio, t); return canPlayAt(videoEl, t) && canPlayAt(audio, t);
} }
function safeSetCT(media, t) { function safeSetCT(media, t) {
try { if (media && isFinite(t) && t >= 0) media.currentTime = t; } catch {} try { if (isFinite(t) && t >= 0) media.currentTime = t; } catch {}
} }
function clearSyncLoop() { function clearSyncLoop() {
if (syncInterval) { if (syncInterval) {
clearInterval(syncInterval); clearInterval(syncInterval);
intervals.delete(syncInterval);
syncInterval = null; syncInterval = null;
} }
try { if (audio) audio.playbackRate = 1; } catch {} try { audio.playbackRate = 1; } catch {}
if (rvfcHandle != null) {
try { videoEl.cancelVideoFrameCallback(rvfcHandle); } catch {}
rvfcHandle = null;
}
} }
function setVideoMuted(val) { function setVideoMuted(val) {
squelchMuteEvents++; squelchMuteEvents++;
try { video.muted?.(val); } catch {} try { video.muted(val); } catch {}
queueMicrotask(() => { squelchMuteEvents = Math.max(0, squelchMuteEvents - 1); }); queueMicrotask(() => { squelchMuteEvents = Math.max(0, squelchMuteEvents - 1); });
} }
function setAudioMuted(val) { function setAudioMuted(val) {
squelchMuteEvents++; squelchMuteEvents++;
try { if (audio) audio.muted = val; } catch {} try { audio.muted = val; } catch {}
queueMicrotask(() => { squelchMuteEvents = Math.max(0, Math.min(1000, squelchMuteEvents - 1)); }); queueMicrotask(() => { squelchMuteEvents = Math.max(0, squelchMuteEvents - 1); });
} }
async function ensureUnmutedIfNotUserMuted() { async function ensureUnmutedIfNotUserMuted() {
// During startup, don't change muted states — playTogether will fade-in safely
if (startupPhase) { updateAudioGainImmediate(); return; } if (startupPhase) { updateAudioGainImmediate(); return; }
if (!userMutedVideo) setVideoMuted(false); if (!userMutedVideo) setVideoMuted(false);
if (!userMutedAudio) setAudioMuted(false); if (!userMutedAudio) setAudioMuted(false);
await softUnmuteAudio(80); await softUnmuteAudio(80);
} }
let rvfcHandle = null;
const useRVFC = !!videoEl.requestVideoFrameCallback;
function startFrameSyncLoop() {
if (!useRVFC) return;
const step = (_now, meta) => {
if (!intendedPlaying) { rvfcHandle = videoEl.requestVideoFrameCallback(step); return; }
const vt = Number(video.currentTime());
const at = Number(audio.currentTime);
if (isFinite(vt) && isFinite(at)) {
const delta = vt - at;
if (Math.abs(delta) > BIG_DRIFT) {
softAlignAudioTo(vt, 20, 60);
} else if (Math.abs(delta) > MICRO_DRIFT) {
const targetRate = 1 + (delta * 0.12);
try { audio.playbackRate = Math.max(0.9, Math.min(1.1, targetRate)); } catch {}
} else {
try { audio.playbackRate = 1; } catch {}
}
}
rvfcHandle = videoEl.requestVideoFrameCallback(step);
};
rvfcHandle = videoEl.requestVideoFrameCallback(step);
}
function startSyncLoop() { function startSyncLoop() {
clearSyncLoop(); clearSyncLoop();
syncInterval = setI(() => { syncInterval = setInterval(() => {
const vt = Number(video.currentTime?.()); const vt = Number(video.currentTime());
const at = Number(audio?.currentTime); const at = Number(audio.currentTime);
if (!isFinite(vt) || !isFinite(at)) return; if (!isFinite(vt) || !isFinite(at)) return;
// strict co-play enforcement
if (intendedPlaying) { if (intendedPlaying) {
if (video.paused?.() && !audio?.paused) { try { video.play?.(); } catch {} } if (video.paused() && !audio.paused) { try { video.play(); } catch {} }
if (!video.paused?.() && audio?.paused) { if (!video.paused() && audio.paused) { try { audio.play().then(()=>softUnmuteAudio(80)).catch(()=>{}); } catch {} }
try { audio.play?.().then(()=>softUnmuteAudio(80)).catch(()=>{}); } catch {}
}
} else { } else {
if (!video.paused?.()) { try { video.pause?.(); } catch {} } if (!video.paused()) { try { video.pause(); } catch {} }
if (!audio?.paused) { try { audio.pause?.(); } catch {} } if (!audio.paused) { try { audio.pause(); } catch {} }
} }
const delta = vt - at; const delta = vt - at;
@ -288,35 +283,22 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
if (Math.abs(delta) > RESYNC_DRIFT_LIMIT) { if (Math.abs(delta) > RESYNC_DRIFT_LIMIT) {
intendedPlaying = true; intendedPlaying = true;
pauseHard(); pauseHard();
setT(() => playTogether({ allowMutedRetry: true }), 120); setTimeout(() => playTogether({ allowMutedRetry: true }), 120);
return; return;
} }
if (Math.abs(delta) > BIG_DRIFT) {
// clickless hard realign
softAlignAudioTo(vt, 30, 80);
} else if (Math.abs(delta) > MICRO_DRIFT) {
// gentle time-stretch
const targetRate = 1 + (delta * 0.12);
try { if (audio) audio.playbackRate = Math.max(0.9, Math.min(1.1, targetRate)); } catch {}
} else {
try { if (audio) audio.playbackRate = 1; } catch {}
}
// Media Session position state (guarded)
try { try {
if ('mediaSession' in navigator && navigator.mediaSession?.setPositionState) { if ('mediaSession' in navigator && navigator.mediaSession.setPositionState) {
navigator.mediaSession.setPositionState({ navigator.mediaSession.setPositionState({
duration: Number(video.duration?.()) || 0, duration: Number(video.duration()) || 0,
playbackRate: Number(video.playbackRate?.()) || 1, playbackRate: Number(video.playbackRate()) || 1,
position: vt position: vt
}); });
} }
} catch {} } catch {}
// audio progress watchdog (kick without clicks)
const now = performance.now(); const now = performance.now();
if (audio && !audio.paused && intendedPlaying) { if (!audio.paused && intendedPlaying) {
if (Math.abs(at - lastAT) < 0.001) { if (Math.abs(at - lastAT) < 0.001) {
if (now - lastATts > 1500) { if (now - lastATts > 1500) {
kickAudio(); kickAudio();
@ -331,77 +313,70 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
lastATts = now; lastATts = now;
} }
}, SYNC_INTERVAL_MS); }, SYNC_INTERVAL_MS);
if (useRVFC) startFrameSyncLoop();
} }
async function kickAudio() { async function kickAudio() {
if (!audio) return;
try { try {
const t = Number(audio.currentTime) || 0; const t = Number(audio.currentTime) || 0;
await softMuteAudio(25); await softMuteAudio(25);
audio.pause?.(); audio.pause();
safeSetCT(audio, t + 0.001); safeSetCT(audio, t + 0.001);
await audio.play?.().catch(()=>{}); await audio.play().catch(()=>{});
await softUnmuteAudio(60); await softUnmuteAudio(60);
} catch {} } catch {}
} }
async function tryPlay(el) { async function tryPlay(el) {
if (!el?.play) return false;
try { try {
const p = el.play(); const p = el.play();
if (p && p.then) await p; if (p && p.then) await p;
return true; return true;
} catch { } catch { return false; }
// Autoplay policy surfaces here; leave quiet. See MDN for play() promise. }
return false;
} function shouldAttemptLoudAutoplay() {
if (!('mediaSession' in navigator)) return false;
return document.visibilityState === 'visible';
} }
async function playTogether({ allowMutedRetry = true } = {}) { async function playTogether({ allowMutedRetry = true } = {}) {
if (!audio) { // no audio element present
try {
const p = video.play?.();
if (p && p.then) await p;
} catch {}
return;
}
if (syncing || restarting) return; if (syncing || restarting) return;
syncing = true; syncing = true;
intendedPlaying = true; intendedPlaying = true;
lastPlayKickTs = performance.now(); lastPlayKickTs = performance.now();
try { try {
const t = Number(video.currentTime?.()); const t = Number(video.currentTime());
if (isFinite(t) && Math.abs(Number(audio.currentTime) - t) > 0.05) { if (isFinite(t) && Math.abs(Number(audio.currentTime) - t) > 0.05) {
await softAlignAudioTo(t, 25, 70); await softAlignAudioTo(t, 25, 70);
} }
// QUIET START: avoid pops by starting with volume 0 (no mute flip needed)
setImmediateVolume(0); setImmediateVolume(0);
setAudioMuted(false); setAudioMuted(false);
let vOk = true, aOk = true; let vOk = true, aOk = true;
try { const p = video.play?.(); if (p && p.then) await p; } catch { vOk = false; } try { const p = video.play(); if (p && p.then) await p; } catch { vOk = false; }
aOk = await tryPlay(audio); aOk = await tryPlay(audio);
if (allowMutedRetry && (!vOk || !aOk)) { if ((allowMutedRetry && (!vOk || !aOk)) || !shouldAttemptLoudAutoplay()) {
const prevVideoMuted = !!video.muted?.(); const prevVideoMuted = !!video.muted();
const prevAudioMuted = !!audio.muted; const prevAudioMuted = !!audio.muted;
await softMuteAudio(40); await softMuteAudio(40);
setVideoMuted(true); setVideoMuted(true);
setAudioMuted(true); setAudioMuted(true);
try { const p = video.play?.(); if (p && p.then) await p; } catch {} try { const p = video.play(); if (p && p.then) await p; } catch {}
await tryPlay(audio); await tryPlay(audio);
setT(async () => { setTimeout(async () => {
if (!userMutedVideo) setVideoMuted(prevVideoMuted); if (!userMutedVideo) setVideoMuted(prevVideoMuted);
if (!userMutedAudio) setAudioMuted(prevAudioMuted); if (!userMutedAudio) setAudioMuted(prevAudioMuted);
await softUnmuteAudio(120); await softUnmuteAudio(120);
}, 160); }, 160);
suppressMirrorUntil = performance.now() + MUTE_SQUELCH_MS; suppressMirrorUntil = performance.now() + MUTE_SQUELCH_MS;
} else { } else {
// Smooth fade-in after both elements are actually playing
await softUnmuteAudio(140); await softUnmuteAudio(140);
} }
@ -409,8 +384,7 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
if (!firstPlayCommitted) { if (!firstPlayCommitted) {
firstPlayCommitted = true; firstPlayCommitted = true;
// end startup phase shortly after first stable play setTimeout(() => { startupPhase = false; }, 800);
setT(() => { startupPhase = false; }, 800);
} }
} finally { } finally {
syncing = false; syncing = false;
@ -418,8 +392,8 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} }
function pauseHard() { function pauseHard() {
try { video.pause?.(); } catch {} try { video.pause(); } catch {}
try { audio?.pause?.(); } catch {} try { audio.pause(); } catch {}
clearSyncLoop(); clearSyncLoop();
} }
@ -446,20 +420,20 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
artwork: vidKey ? [{ src: `https://i.ytimg.com/vi/${vidKey}/maxresdefault.jpg`, sizes: "1280x720", type: "image/jpeg" }] : [] artwork: vidKey ? [{ src: `https://i.ytimg.com/vi/${vidKey}/maxresdefault.jpg`, sizes: "1280x720", type: "image/jpeg" }] : []
}); });
} catch {} } catch {}
try { navigator.mediaSession.setActionHandler('play', () => playTogether()); } catch {}
try { navigator.mediaSession.setActionHandler('pause', () => pauseTogether()); } catch {}
try { try {
navigator.mediaSession.setActionHandler('play', () => playTogether());
navigator.mediaSession.setActionHandler('pause', () => pauseTogether());
navigator.mediaSession.setActionHandler('seekforward', (d) => { navigator.mediaSession.setActionHandler('seekforward', (d) => {
const inc = Number(d?.seekOffset) || 10; const inc = Number(d?.seekOffset) || 10;
video.currentTime?.(Math.min((video.currentTime?.() || 0) + inc, Number(video.duration?.()) || 0)); video.currentTime(Math.min((video.currentTime() || 0) + inc, Number(video.duration()) || 0));
}); });
navigator.mediaSession.setActionHandler('seekbackward', (d) => { navigator.mediaSession.setActionHandler('seekbackward', (d) => {
const dec = Number(d?.seekOffset) || 10; const dec = Number(d?.seekOffset) || 10;
video.currentTime?.(Math.max((video.currentTime?.() || 0) - dec, 0)); video.currentTime(Math.max((video.currentTime() || 0) - dec, 0));
}); });
navigator.mediaSession.setActionHandler('seekto', (d) => { navigator.mediaSession.setActionHandler('seekto', (d) => {
if (!d || typeof d.seekTime !== 'number') return; if (!d || typeof d.seekTime !== 'number') return;
video.currentTime?.(Math.max(0, Math.min(Number(video.duration?.()) || 0, d.seekTime))); video.currentTime(Math.max(0, Math.min(Number(video.duration()) || 0, d.seekTime)));
}); });
} catch {} } catch {}
} }
@ -467,9 +441,9 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
function restoreProgress() { function restoreProgress() {
try { try {
const saved = Number(localStorage.getItem(PROGRESS_KEY)); const saved = Number(localStorage.getItem(PROGRESS_KEY));
const dur = Number(video.duration?.()) || 0; const dur = Number(video.duration()) || 0;
if (isFinite(saved) && saved > 3 && dur && saved < (dur - 10)) { if (isFinite(saved) && saved > 3 && dur && saved < (dur - 10)) {
video.currentTime?.(saved); video.currentTime(saved);
safeSetCT(audio, saved); safeSetCT(audio, saved);
firstSeekDone = true; firstSeekDone = true;
updateAudioGainImmediate(); updateAudioGainImmediate();
@ -478,7 +452,7 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} }
function saveProgressThrottled() { function saveProgressThrottled() {
try { try {
const t = Math.floor(Number(video.currentTime?.()) || 0); const t = Math.floor(Number(video.currentTime()) || 0);
if ((t & 1) === 0) localStorage.setItem(PROGRESS_KEY, String(t)); if ((t & 1) === 0) localStorage.setItem(PROGRESS_KEY, String(t));
} catch {} } catch {}
} }
@ -486,138 +460,107 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
function wireResilience(el, label) { function wireResilience(el, label) {
const pauseIfRealStall = () => { const pauseIfRealStall = () => {
const now = performance.now(); const now = performance.now();
// Ignore early "waiting/stalled" during startup to prevent play->pause jitters
if (startupPhase) return; if (startupPhase) return;
if (now - lastPlayKickTs < STARTUP_GRACE_MS) return; // ignore startup jitters if (now - lastPlayKickTs < STARTUP_GRACE_MS) return;
if (!intendedPlaying) return; if (!intendedPlaying) return;
showError(`${label} buffering…`); showError(`${label} buffering…`);
pauseHard(); pauseHard();
}; };
on(el, 'waiting', pauseIfRealStall); el.addEventListener('waiting', pauseIfRealStall);
on(el, 'stalled', pauseIfRealStall); el.addEventListener('stalled', pauseIfRealStall);
on(el, 'emptied', pauseIfRealStall); el.addEventListener('emptied', pauseIfRealStall);
on(el, 'error', pauseIfRealStall); el.addEventListener('error', pauseIfRealStall);
const tryResume = async () => { const tryResume = async () => {
hideError(); hideError();
if (!intendedPlaying) return; if (!intendedPlaying) return;
const t = Number(video.currentTime?.()); const t = Number(video.currentTime());
if (bothPlayableAt(t)) { if (bothPlayableAt(t)) {
await ensureUnmutedIfNotUserMuted(); await ensureUnmutedIfNotUserMuted();
playTogether({ allowMutedRetry: true }); playTogether({ allowMutedRetry: true });
} }
}; };
on(el, 'canplay', tryResume); el.addEventListener('canplay', tryResume);
on(el, 'canplaythrough', tryResume); el.addEventListener('canplaythrough', tryResume);
} }
// requestVideoFrameCallback alignment assist (micro-drift smoother)
const hasRVFC = typeof videoEl?.requestVideoFrameCallback === 'function';
if (hasRVFC && hasExternalAudio) {
const rvfcLoop = (now, meta) => {
try {
if (!intendedPlaying || !audio || audio.paused) return;
const vt = Number(video.currentTime?.());
const at = Number(audio.currentTime);
const delta = vt - at;
// Fine-grain trim, less than MICRO_DRIFT so we don't fight the main loop
if (Math.abs(delta) > 0.02 && Math.abs(delta) < BIG_DRIFT) {
const targetRate = 1 + (delta * 0.2);
audio.playbackRate = Math.max(0.9, Math.min(1.1, targetRate));
}
} catch {}
if (!abort.signal.aborted) videoEl.requestVideoFrameCallback(rvfcLoop);
};
videoEl.requestVideoFrameCallback(rvfcLoop);
}
// ---------------- main path ----------------
if (qua !== "medium" && hasExternalAudio) { if (qua !== "medium" && hasExternalAudio) {
let audioReady = false, videoReady = false; let audioReady = false, videoReady = false;
const oneShotReady = (elm, markReady) => { const oneShotReady = (elm, markReady) => {
let done = false; let done = false;
const onLoaded = () => { if (done) return; done = true; markReady(); maybeStart(); }; const onLoaded = () => { if (done) return; done = true; markReady(); maybeStart(); };
on(elm, 'loadeddata', onLoaded, { once: true }); elm.addEventListener('loadeddata', onLoaded, { once: true });
on(elm, 'loadedmetadata', onLoaded, { once: true }); elm.addEventListener('loadedmetadata', onLoaded, { once: true });
on(elm, 'canplay', onLoaded, { once: true }); elm.addEventListener('canplay', onLoaded, { once: true });
}; };
const maybeStart = () => { const maybeStart = () => {
if (!audioReady || !videoReady || restarting) return; if (!audioReady || !videoReady || restarting) return;
restoreProgress(); restoreProgress();
const t = Number(video.currentTime?.()); const t = Number(video.currentTime());
if (isFinite(t) && Math.abs(Number(audio.currentTime) - t) > 0.1) { if (isFinite(t) && Math.abs(Number(audio.currentTime) - t) > 0.1) {
safeSetCT(audio, t); safeSetCT(audio, t);
} }
setupMediaSession(); setupMediaSession();
updateAudioGainImmediate(); updateAudioGainImmediate();
// end startup phase a bit after both are primed if play didn't already commit setTimeout(() => { if (!firstPlayCommitted) startupPhase = false; }, 2500);
setT(() => { if (!firstPlayCommitted) startupPhase = false; }, 2500);
}; };
oneShotReady(audio, () => { audioReady = true; }); oneShotReady(audio, () => { audioReady = true; });
oneShotReady(videoEl, () => { videoReady = true; }); oneShotReady(videoEl, () => { videoReady = true; });
// volume/mute coupling (no random mutes; fade around mute flips) video.on('volumechange', () => {
video.on?.('volumechange', () => {
if (squelchMuteEvents) return; if (squelchMuteEvents) return;
userMutedVideo = !!video.muted?.(); userMutedVideo = !!video.muted();
if (performance.now() < suppressMirrorUntil || seekingActive || restarting) { if (performance.now() < suppressMirrorUntil || seekingActive || restarting) {
// defer mirroring during squelch; just update gain target
rampVolumeTo(getBaseTargetVol(), 80); rampVolumeTo(getBaseTargetVol(), 80);
return; return;
} }
if (video.muted?.()) { if (video.muted()) {
softMuteAudio(80).then(() => setAudioMuted(true)); softMuteAudio(80).then(() => setAudioMuted(true));
} else { } else {
setAudioMuted(false); setAudioMuted(false);
softUnmuteAudio(100); softUnmuteAudio(100);
} }
// follow volume level smoothly if (!video.muted()) rampVolumeTo(getBaseTargetVol(), 120);
if (!video.muted?.()) rampVolumeTo(getBaseTargetVol(), 120);
}); });
on(audio, 'volumechange', () => { audio.addEventListener('volumechange', () => {
if (squelchMuteEvents) return; if (squelchMuteEvents) return;
userMutedAudio = !!audio.muted; userMutedAudio = !!audio.muted;
// audio->video mute isn't mirrored; video UI is the authority
}); });
// playback rate video.on('ratechange', () => { try { audio.playbackRate = video.playbackRate(); } catch {} });
video.on?.('ratechange', () => { try { if (audio) audio.playbackRate = video.playbackRate?.(); } catch {} });
// user play/pause drives both video.on('play', () => { intendedPlaying = true; ensureUnmutedIfNotUserMuted().then(()=>playTogether()); });
video.on?.('play', () => { intendedPlaying = true; ensureUnmutedIfNotUserMuted().then(()=>playTogether()); }); video.on('pause', () => { if (!restarting) pauseTogether(); });
video.on?.('pause', () => { if (!restarting) pauseTogether(); });
// seek auto-play policy with clickless alignment
let wasPlayingBeforeSeek = false; let wasPlayingBeforeSeek = false;
let seekStartTime = 0; let seekStartTime = 0;
function computeSeekThresholds() { function computeSeekThresholds() {
const dur = Number(video.duration?.()) || 300; const dur = Number(video.duration()) || 300;
const small = Math.max(0.4, Math.min(5, dur * 0.01)); // 0.4s..5s const small = Math.max(0.4, Math.min(5, dur * 0.01));
const large = Math.max(5, Math.min(45, dur * 0.12)); // 5s..45s const large = Math.max(5, Math.min(45, dur * 0.12));
const huge = Math.max(10, Math.min(60, dur * 0.33)); // 10s..60s const huge = Math.max(10, Math.min(60, dur * 0.33));
return { small, large, huge }; return { small, large, huge };
} }
video.on?.('seeking', () => { video.on('seeking', () => {
if (restarting) return; if (restarting) return;
seekingActive = true; seekingActive = true;
wasPlayingBeforeSeek = intendedPlaying && !video.paused?.(); wasPlayingBeforeSeek = intendedPlaying && !video.paused();
seekStartTime = Number(video.currentTime?.()); seekStartTime = Number(video.currentTime());
suppressMirrorUntil = performance.now() + MUTE_SQUELCH_MS; suppressMirrorUntil = performance.now() + MUTE_SQUELCH_MS;
}); });
video.on?.('seeked', async () => { video.on('seeked', async () => {
if (restarting) return; if (restarting) return;
const newTime = Number(video.currentTime?.()); const newTime = Number(video.currentTime());
const diff = Math.abs(newTime - seekStartTime); const diff = Math.abs(newTime - seekStartTime);
const { small, large, huge } = computeSeekThresholds(); const { small, large, huge } = computeSeekThresholds();
// clickless align for anything > ~120ms, straight set for tiny nudges
if (diff > 0.12) await softAlignAudioTo(newTime, 30, 80); if (diff > 0.12) await softAlignAudioTo(newTime, 30, 80);
else safeSetCT(audio, newTime); else safeSetCT(audio, newTime);
@ -644,7 +587,7 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} else { } else {
intendedPlaying = false; intendedPlaying = false;
pauseHard(); pauseHard();
setT(async () => { setTimeout(async () => {
if (wasPlayingBeforeSeek) { if (wasPlayingBeforeSeek) {
intendedPlaying = true; intendedPlaying = true;
await ensureUnmutedIfNotUserMuted(); await ensureUnmutedIfNotUserMuted();
@ -655,9 +598,8 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
seekingActive = false; seekingActive = false;
}); });
try { video.on?.('timeupdate', saveProgressThrottled); } catch {} try { video.on('timeupdate', saveProgressThrottled); } catch {}
// resilience
wireResilience(videoEl, 'Video'); wireResilience(videoEl, 'Video');
wireResilience(audio, 'Audio'); wireResilience(audio, 'Audio');
@ -676,72 +618,56 @@ var versionclient = "youtube.player.web_20250917_22_RC00"
} finally { restarting = false; } } finally { restarting = false; }
} }
video.on?.('ended', () => { video.on('ended', () => {
if (restarting) return; if (restarting) return;
if (performance.now() < suppressEndedUntil) return; if (performance.now() < suppressEndedUntil) return;
if (desiredLoop) restartLoop(); if (desiredLoop) restartLoop();
else pauseTogether(); else pauseTogether();
}); });
on(audio, 'ended', () => { audio.addEventListener('ended', () => {
if (restarting) return; if (restarting) return;
if (performance.now() < suppressEndedUntil) return; if (performance.now() < suppressEndedUntil) return;
if (desiredLoop) restartLoop(); if (desiredLoop) restartLoop();
else pauseTogether(); else pauseTogether();
}); });
// resume after either becomes ready again
const tryAutoResume = async () => { const tryAutoResume = async () => {
if (!intendedPlaying) return; if (!intendedPlaying) return;
const t = Number(video.currentTime?.()); const t = Number(video.currentTime());
if (bothPlayableAt(t)) { await ensureUnmutedIfNotUserMuted(); playTogether({ allowMutedRetry: true }); } if (bothPlayableAt(t)) { await ensureUnmutedIfNotUserMuted(); playTogether({ allowMutedRetry: true }); }
}; };
on(videoEl, 'canplay', tryAutoResume); videoEl.addEventListener('canplay', tryAutoResume);
on(audio, 'canplay', tryAutoResume); audio.addEventListener('canplay', tryAutoResume);
// persist progress on unload/visibility changes
try { try {
on(window, 'pagehide', () => { clearSyncLoop(); }); window.addEventListener('pagehide', () => { clearSyncLoop(); }, { passive: true });
on(window, 'beforeunload', () => { window.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
clearSyncLoop();
} else if (intendedPlaying) {
if (!syncInterval) startSyncLoop();
tryAutoResume();
}
}, { passive: true });
window.addEventListener('beforeunload', () => {
try { try {
localStorage.setItem(PROGRESS_KEY, String(Math.floor(Number(video.currentTime?.()) || 0))); localStorage.setItem(PROGRESS_KEY, String(Math.floor(Number(video.currentTime()) || 0)));
} catch {} } catch {}
}); });
on(document, 'visibilitychange', () => {
if (document.visibilityState === 'hidden') {
// reduce CPU while hidden; resume smoothly when visible
clearSyncLoop();
} else if (intendedPlaying && !syncInterval) {
startSyncLoop();
// quick gentle re-sync on return
const t = Number(video.currentTime?.());
if (isFinite(t)) softAlignAudioTo(t, 10, 80);
}
});
on(window, 'offline', () => showError('Network offline…'));
on(window, 'online', () => hideError());
} catch {} } catch {}
} else { } else {
// no external audio path (kept)
try { try {
video.on?.('timeupdate', () => { video.on('timeupdate', () => {
try { try {
localStorage.setItem(`progress-${vidKey}`, String(Math.floor(Number(video.currentTime?.()) || 0))); localStorage.setItem(`progress-${vidKey}`, String(Math.floor(Number(video.currentTime()) || 0)));
} catch {} } catch {}
}); });
} catch {} } catch {}
setupMediaSession(); setupMediaSession();
} }
// clean up on navigation
on(window, 'pagehide', () => {
abort.abort();
clearAllTimers();
clearSyncLoop();
});
}); });
// https://codeberg.org/ashley/poke/src/branch/main/src/libpoketube/libpoketube-youtubei-objects.json // https://codeberg.org/ashley/poke/src/branch/main/src/libpoketube/libpoketube-youtubei-objects.json