// ==UserScript== // @name 全功能智能视频倍速控制器 // @namespace http://tampermonkey.net/ // @version 4.6.1 // @description 全网通用(自动在YouTube上屏蔽),统一悬浮UI与快捷键操控 | 支持直播缓冲区快进/快退 | 常驻显示系统实时时间 | 智能刷新优化 // @author You // @match http://*/* // @match https://*/* // @allFrames true // @grant GM_setValue // @grant GM_getValue // @run-at document-idle // ==/UserScript== (function () { 'use strict'; // ========================================== // YouTube 自动禁用 // ========================================== if (window.location.hostname.includes('youtube.com')) { return; } // ========================================== // 防止重复注入 // ========================================== if (window.__TS_SPEED_CONTROLLER_INJECTED__) return; window.__TS_SPEED_CONTROLLER_INJECTED__ = true; // ========================================== // 配置 // ========================================== const CONFIG = { STEP: 0.25, // 倍速调整步长 SEEK_STEP: 3, // 快进/快退秒数 SEEK_INTERVAL: 500, // 按住左右键时的重复间隔 PREFERRED_SPEED: 2.25, // 第一次使用时的默认倍速 REMEMBER_SPEED: true, // 是否记忆倍速 // 刷新策略 NORMAL_UPDATE_INTERVAL: 1000, // 正常状态:1秒 FAST_UPDATE_INTERVAL: 50, // 滚轮操作时:50ms FAST_UPDATE_KEEP_MS: 400, // 最后一次滚轮后继续高频刷新时间 // 直播安全边界 LIVE_EDGE_PADDING: 0.5, // 视频激活最小尺寸(小于该尺寸的预览/缩略图视频自动忽略) MIN_VIDEO_WIDTH: 320, MIN_VIDEO_HEIGHT: 180 }; // ========================================== // 性能 / Hotkey // ========================================== try { ProcessSetPriority?.("High"); } catch (e) {} try { A_MaxHotkeysPerInterval = 2000; } catch (e) {} // ========================================== // 倍速状态 // ========================================== let savedSpeed = null; try { if (typeof GM_getValue !== 'undefined') { savedSpeed = GM_getValue('saved_video_speed', null); } } catch (e) { savedSpeed = null; } const initialSpeed = typeof savedSpeed === 'number' && isFinite(savedSpeed) && savedSpeed >= 0.25 && savedSpeed <= 16 ? savedSpeed : CONFIG.PREFERRED_SPEED; let globalSavedSpeed = savedSpeed; let globalDesiredSpeed = initialSpeed; let globalLastSpeed = initialSpeed; let isSettingRate = false; // ========================================== // 视频状态缓存 // ========================================== let activeVideoCache = null; let activeVideoCacheTime = 0; const ACTIVE_VIDEO_CACHE_MS = 150; // ========================================== // 键盘连续 Seek // ========================================== let keySeekTimer = null; let activeKeyCode = null; function stopKeySeek() { if (keySeekTimer) { clearInterval(keySeekTimer); keySeekTimer = null; } activeKeyCode = null; } // ========================================== // UI / Toast // ========================================== let UI_DIV = null; let TOAST_DIV = null; let toastTimer = null; // ========================================== // 刷新系统 // ========================================== let normalUpdateTimer = null; let fastUpdateTimer = null; let fastUpdateStopTimer = null; function startNormalUpdateLoop() { if (normalUpdateTimer) return; normalUpdateTimer = setInterval(() => { updateSingleUI(); }, CONFIG.NORMAL_UPDATE_INTERVAL); } function stopNormalUpdateLoop() { if (normalUpdateTimer) { clearInterval(normalUpdateTimer); normalUpdateTimer = null; } } function startFastUpdate() { stopNormalUpdateLoop(); if (!fastUpdateTimer) { fastUpdateTimer = setInterval(() => { updateSingleUI(); }, CONFIG.FAST_UPDATE_INTERVAL); } if (fastUpdateStopTimer) { clearTimeout(fastUpdateStopTimer); } fastUpdateStopTimer = setTimeout(() => { stopFastUpdate(); }, CONFIG.FAST_UPDATE_KEEP_MS); } function stopFastUpdate() { if (fastUpdateTimer) { clearInterval(fastUpdateTimer); fastUpdateTimer = null; } if (fastUpdateStopTimer) { clearTimeout(fastUpdateStopTimer); fastUpdateStopTimer = null; } updateSingleUI(); startNormalUpdateLoop(); } function requestImmediateUIUpdate() { updateSingleUI(); } // ========================================== // 系统时间 // ========================================== let cachedSystemTime = ''; function getFormattedSystemTime() { const now = new Date(); const hour = now.getHours(); const minutes = now.getMinutes().toString().padStart(2, '0'); const seconds = now.getSeconds().toString().padStart(2, '0'); let time_of_day = ''; if (hour < 5) time_of_day = '午夜'; else if (hour < 11) time_of_day = '早上'; else if (hour < 14) time_of_day = '中午'; else if (hour < 17) time_of_day = '下午'; else if (hour < 19) time_of_day = '傍晚'; else time_of_day = '晚上'; let hour12 = hour % 12; if (hour12 === 0) hour12 = 12; return `${time_of_day} ${hour12}:${minutes}:${seconds}`; } function refreshSystemTime() { cachedSystemTime = getFormattedSystemTime(); } refreshSystemTime(); setInterval(() => { refreshSystemTime(); // 即使 UI 正好处于正常 1 秒刷新,也确保系统时间实时更新 if (!fastUpdateTimer) { updateSingleUI(); } }, 1000); // ========================================== // Fullscreen // ========================================== function getFullscreenElement() { let fs = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; while ( fs && fs.shadowRoot && fs.shadowRoot.fullscreenElement ) { fs = fs.shadowRoot.fullscreenElement; } return fs; } function getMountContainer() { const fsElement = getFullscreenElement(); if ( fsElement && fsElement.tagName !== 'VIDEO' && fsElement.tagName !== 'IFRAME' ) { return fsElement; } return document.body; } function isVideoFullscreen(video) { if (!video) return false; const fsElement = getFullscreenElement(); if (fsElement) { return ( fsElement === video || fsElement.contains(video) || video.contains(fsElement) ); } const txpContainer = video.closest('.txp_player') || video.closest('.txp_video_container') || video.closest('.bpx-player-container') || video.closest('#bilibili-player') || video.closest('[data-player]'); if (txpContainer) { if ( txpContainer.classList.contains('txp_state_fullscreen') || txpContainer.classList.contains('txp_state_page_fullscreen') || txpContainer.classList.contains('mode-webscreen') || txpContainer.classList.contains('mode-fullscreen') || txpContainer.getAttribute('data-fullscreen') === 'true' ) { return true; } } const rect = video.getBoundingClientRect(); return ( Math.abs(rect.width - window.innerWidth) < 15 && Math.abs(rect.height - window.innerHeight) < 15 ); } // ========================================== // 直播判断 // ========================================== function isLiveStream(video) { if (!video) return false; const dur = video.duration; if (dur === Infinity) { return true; } if ( video.seekable && video.seekable.length > 0 && !isFinite(dur) ) { return true; } return false; } // ========================================== // 时间格式化 // ========================================== function formatTime(seconds) { if ( typeof seconds !== 'number' || isNaN(seconds) || seconds < 0 ) { return '--:--'; } const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); return `${mins}:${secs.toString().padStart(2, '0')}`; } // ========================================== // playbackRate setter 缓存 // ========================================== let cachedPlaybackRateSetter = null; let playbackRateSetterInitialized = false; function getPlaybackRateSetter() { if (playbackRateSetterInitialized) { return cachedPlaybackRateSetter; } playbackRateSetterInitialized = true; try { const descriptor = Object.getOwnPropertyDescriptor( HTMLMediaElement.prototype, 'playbackRate' ); if (descriptor && descriptor.set) { cachedPlaybackRateSetter = descriptor.set; } } catch (e) { cachedPlaybackRateSetter = null; } return cachedPlaybackRateSetter; } // ========================================== // 设置倍速 // ========================================== function forceSetPlaybackRate(video, speed) { if (!video) return; // 直播固定 1x if (isLiveStream(video)) { speed = 1.0; } else { speed = Math.max(0.25, Math.min(16, speed)); } isSettingRate = true; try { video.playbackRate = speed; } catch (e) {} if ( Math.abs( (parseFloat(video.playbackRate) || 1) - speed ) > 0.01 ) { const setter = getPlaybackRateSetter(); if (setter) { try { setter.call(video, speed); } catch (e) {} } } setTimeout(() => { isSettingRate = false; }, 50); } // ========================================== // 安全初始化倍速 // ========================================== function safeInitSpeed(video) { if (!video || isLiveStream(video)) return; if (video.__speed_init_timer__) { clearTimeout(video.__speed_init_timer__); } video.__speed_init_timer__ = setTimeout(() => { const targetInitSpeed = globalDesiredSpeed || CONFIG.PREFERRED_SPEED; if ( Math.abs( (parseFloat(video.playbackRate) || 1) - targetInitSpeed ) > 0.01 ) { forceSetPlaybackRate( video, targetInitSpeed ); } }, 100); } // ========================================== // 视频可见性 + 尺寸过滤 // ========================================== function isVisibleVideo(v) { if (!v) return false; const rect = v.getBoundingClientRect(); const style = window.getComputedStyle(v); // 尺寸过滤:小于阈值的预览/缩略图视频直接忽略 const isLargeEnough = rect.width > CONFIG.MIN_VIDEO_WIDTH && rect.height > CONFIG.MIN_VIDEO_HEIGHT; return ( isLargeEnough && style.visibility !== 'hidden' && style.display !== 'none' && style.opacity !== '0' ); } // ========================================== // 最大视频 // ========================================== function getLargestVideo(videos) { return videos.reduce( (largest, current) => { const largestArea = largest ? largest.getBoundingClientRect().width * largest.getBoundingClientRect().height : 0; const currentArea = current.getBoundingClientRect().width * current.getBoundingClientRect().height; return currentArea > largestArea ? current : largest; }, null ); } // ========================================== // Active Video // ========================================== function getActiveVideo(forceRefresh = false) { const now = performance.now(); if ( !forceRefresh && activeVideoCache && now - activeVideoCacheTime < ACTIVE_VIDEO_CACHE_MS ) { if (document.contains(activeVideoCache)) { return activeVideoCache; } } const fsElement = getFullscreenElement(); if (fsElement) { if (fsElement.tagName === 'VIDEO') { activeVideoCache = fsElement; activeVideoCacheTime = now; return fsElement; } const fsVideos = Array.from( fsElement.querySelectorAll('video') ).filter(isVisibleVideo); if (fsVideos.length > 0) { const result = fsVideos.find(v => !v.paused) || getLargestVideo(fsVideos); activeVideoCache = result; activeVideoCacheTime = now; return result; } } const allVideos = Array.from( document.querySelectorAll('video') ).filter(isVisibleVideo); if (allVideos.length === 0) { activeVideoCache = null; activeVideoCacheTime = now; return null; } const playingVideos = allVideos.filter( v => !v.paused && v.readyState >= 2 ); if (playingVideos.length > 0) { const result = getLargestVideo(playingVideos); activeVideoCache = result; activeVideoCacheTime = now; return result; } const viewportCenterY = window.innerHeight / 2; let closestVideo = null; let minDistance = Infinity; allVideos.forEach(video => { const rect = video.getBoundingClientRect(); const videoCenterY = rect.top + rect.height / 2; const distance = Math.abs( videoCenterY - viewportCenterY ); if (distance < minDistance) { minDistance = distance; closestVideo = video; } }); activeVideoCache = closestVideo; activeVideoCacheTime = now; return closestVideo; } function invalidateActiveVideoCache() { activeVideoCache = null; activeVideoCacheTime = 0; } // ========================================== // Toast // ========================================== function showToast(text, video = null) { video = video || getActiveVideo(); if (!video) return; if (!TOAST_DIV) { TOAST_DIV = document.createElement('div'); TOAST_DIV.className = '__speed_toast_single__'; TOAST_DIV.style.cssText = ` position: fixed !important; margin: 0 !important; padding: 10px 24px !important; background: rgba(0, 0, 0, 0.85) !important; color: #ffffff !important; border-radius: 9px !important; font-size: 32px !important; font-weight: 900 !important; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important; z-index: 2147483647 !important; pointer-events: none !important; user-select: none !important; white-space: nowrap !important; opacity: 0 !important; transition: opacity 0.15s ease-in-out !important; box-shadow: 0 6px 24px rgba(0, 0, 0, 0.6) !important; line-height: 1.2 !important; transform: translate(-50%, -50%) !important; letter-spacing: 1px !important; text-shadow: 0 2px 8px rgba(0,0,0,0.5) !important; border: 1px solid rgba(255,255,255,0.12) !important; `; } const targetContainer = getMountContainer(); if (TOAST_DIV.parentNode !== targetContainer) { targetContainer.appendChild( TOAST_DIV ); } const rect = video.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const centerY = rect.top + rect.height / 2; TOAST_DIV.style.left = `${Math.max( 60, Math.min( window.innerWidth - 60, centerX ) )}px`; TOAST_DIV.style.top = `${Math.max( 60, Math.min( window.innerHeight - 60, centerY ) )}px`; TOAST_DIV.textContent = text; TOAST_DIV.style.opacity = '0.95'; if (toastTimer) { clearTimeout(toastTimer); } toastTimer = setTimeout(() => { if (TOAST_DIV) { TOAST_DIV.style.opacity = '0'; } }, 260); } // ========================================== // 改变倍速 // ========================================== function changeSpeed( newSpeed, showPrompt = true ) { const video = getActiveVideo(true); if (!video || isLiveStream(video)) { return; } newSpeed = Math.max( 0.25, Math.min(16, newSpeed) ); newSpeed = Math.round( newSpeed * 100 ) / 100; globalDesiredSpeed = newSpeed; forceSetPlaybackRate( video, newSpeed ); if (CONFIG.REMEMBER_SPEED) { globalSavedSpeed = newSpeed; if ( typeof GM_setValue !== 'undefined' ) { try { GM_setValue( 'saved_video_speed', newSpeed ); } catch (e) {} } } if (showPrompt) { showToast( `${newSpeed}x`, video ); } requestImmediateUIUpdate(); } // ========================================== // 1x / 恢复倍速 // ========================================== function toggleNormalSpeed() { const video = getActiveVideo(true); if ( !video || isLiveStream(video) ) { return; } const current = parseFloat(video.playbackRate) || 1; if (Math.abs(current - 1) > 0.01) { globalLastSpeed = current; changeSpeed(1); } else { const target = globalLastSpeed || globalDesiredSpeed || CONFIG.PREFERRED_SPEED; changeSpeed(target); } } // ========================================== // Seek // ========================================== function seekVideo(seconds) { const video = getActiveVideo(true); if (!video) return; let target = video.currentTime + seconds; if ( video.seekable && video.seekable.length > 0 ) { const minTime = video.seekable.start(0); const maxTime = video.seekable.end( video.seekable.length - 1 ); target = Math.max( minTime, Math.min( maxTime - CONFIG.LIVE_EDGE_PADDING, target ) ); } else if ( video.duration && isFinite(video.duration) ) { target = Math.max( 0, Math.min( video.duration, target ) ); } else { target = Math.max( 0, target ); } try { video.currentTime = target; } catch (e) {} requestImmediateUIUpdate(); } // ========================================== // UI 初始化 // ========================================== function initSingleUI() { if (UI_DIV) return; UI_DIV = document.createElement('div'); UI_DIV.className = '__speed_time_display_single__'; UI_DIV.style.cssText = ` position: fixed !important; background: transparent !important; color: #ffffff !important; padding: 0 !important; font-size: 18px !important; font-weight: 700 !important; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important; z-index: 2147483647 !important; pointer-events: auto !important; user-select: none !important; white-space: nowrap !important; display: none; flex-direction: column !important; align-items: flex-end !important; opacity: 1 !important; line-height: 1.4 !important; margin: 0 !important; box-sizing: border-box !important; letter-spacing: 0.5px !important; text-shadow: 2px 2px 3px #000000, -2px -2px 3px #000000, 2px -2px 3px #000000, -2px 2px 3px #000000, 0px 0px 6px #000000, 0px 0px 10px #000000 !important; transition: opacity 0.2s ease !important; `; const svgRewind = ` `; const svgForward = ` `; UI_DIV.innerHTML = `
${svgRewind} ${svgForward}
`; // ========================================== // 防止播放器抢事件 // ========================================== UI_DIV.addEventListener( 'dblclick', e => { e.preventDefault(); e.stopPropagation(); }, true ); UI_DIV.addEventListener( 'mousedown', e => { e.stopPropagation(); }, true ); // ========================================== // 倍速文字 // ========================================== const textArea = UI_DIV.querySelector( '.__speed_text_area__' ); textArea.addEventListener( 'click', e => { e.preventDefault(); e.stopPropagation(); toggleNormalSpeed(); }, true ); // ========================================== // 后退按钮 // ========================================== const btnRewind = UI_DIV.querySelector( '.__btn_rewind__' ); btnRewind.addEventListener( 'click', e => { e.preventDefault(); e.stopPropagation(); seekVideo( -CONFIG.SEEK_STEP ); }, true ); // ========================================== // 前进按钮 // ========================================== const btnForward = UI_DIV.querySelector( '.__btn_forward__' ); btnForward.addEventListener( 'click', e => { e.preventDefault(); e.stopPropagation(); seekVideo( CONFIG.SEEK_STEP ); }, true ); // ========================================== // 按钮 Hover // ========================================== [btnRewind, btnForward].forEach( btn => { btn.style.opacity = '0.9'; btn.style.transform = 'scale(1)'; btn.addEventListener( 'mouseenter', () => { btn.style.opacity = '1'; btn.style.transform = 'scale(1.2)'; } ); btn.addEventListener( 'mouseleave', () => { btn.style.opacity = '0.9'; btn.style.transform = 'scale(1)'; } ); } ); } // ========================================== // UI 更新 // ========================================== let lastVideoTimeText = ''; let lastSystemTimeText = ''; let lastUIVideo = null; function updateSingleUI() { initSingleUI(); const video = getActiveVideo(); if ( !video || video.readyState === 0 || video.ended ) { if (UI_DIV) { UI_DIV.style.display = 'none'; } lastUIVideo = null; return; } const rect = video.getBoundingClientRect(); const isOutOfViewport = rect.bottom < 0 || rect.top > window.innerHeight || rect.right < 0 || rect.left > window.innerWidth; if (isOutOfViewport) { UI_DIV.style.display = 'none'; lastUIVideo = null; return; } const targetContainer = getMountContainer(); if ( UI_DIV.parentNode !== targetContainer ) { targetContainer.appendChild( UI_DIV ); } const full = isVideoFullscreen(video); if (full) { UI_DIV.style.top = `${Math.max( 10, rect.top + 10 )}px`; UI_DIV.style.right = `${Math.max( 15, window.innerWidth - rect.right + 15 )}px`; } else { UI_DIV.style.top = `${Math.max( 6, rect.top + 6 )}px`; UI_DIV.style.right = `${Math.max( 6, window.innerWidth - rect.right + 6 )}px`; } UI_DIV.style.display = 'flex'; let videoTimeText = ''; // ========================================== // 直播(仅显示基础状态,不显示缓存时长) // ========================================== if (isLiveStream(video)) { videoTimeText = '1x | 直播中'; } // ========================================== // 普通视频 // ========================================== else { const ct = parseFloat( video.currentTime ) || 0; const dur = video.duration; const rate = parseFloat( video.playbackRate ) || 1; const safeRate = rate === 0 ? 1 : rate; const rateStr = safeRate .toFixed(2) .replace( /\.?0+$/, '' ); if ( !isFinite(dur) || dur <= 0 || isNaN(dur) ) { videoTimeText = `${rateStr}x | ${formatTime(ct)}`; } else { const remainingStr = formatTime( Math.max( 0, dur - ct ) / safeRate ); const totalStr = formatTime( dur / safeRate ); videoTimeText = `${rateStr}x | ${remainingStr} / ${totalStr}`; } } const textArea = UI_DIV.querySelector( '.__speed_text_area__' ); const sysTimeArea = UI_DIV.querySelector( '.__system_time_area__' ); const btnGroup = UI_DIV.querySelector( '.__seek_btn_group__' ); // ========================================== // 只有发生变化才写 DOM // ========================================== if ( lastUIVideo !== video || lastVideoTimeText !== videoTimeText ) { textArea.textContent = videoTimeText; lastVideoTimeText = videoTimeText; } if ( lastSystemTimeText !== cachedSystemTime ) { sysTimeArea.textContent = cachedSystemTime; lastSystemTimeText = cachedSystemTime; } btnGroup.style.display = 'flex'; lastUIVideo = video; } // ========================================== // 判断鼠标是否在视频区域 // ========================================== function isEventInVideoArea( e, video ) { if (!video) return false; const rect = video.getBoundingClientRect(); return ( e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom ); } // ========================================== // Video 事件 // ========================================== document.addEventListener( 'play', e => { if ( e.target && e.target.tagName === 'VIDEO' ) { invalidateActiveVideoCache(); safeInitSpeed( e.target ); requestImmediateUIUpdate(); } }, true ); document.addEventListener( 'loadedmetadata', e => { if ( e.target && e.target.tagName === 'VIDEO' ) { invalidateActiveVideoCache(); safeInitSpeed( e.target ); requestImmediateUIUpdate(); } }, true ); document.addEventListener( 'pause', e => { if ( e.target && e.target.tagName === 'VIDEO' ) { invalidateActiveVideoCache(); requestImmediateUIUpdate(); } }, true ); document.addEventListener( 'emptied', e => { if ( e.target && e.target.tagName === 'VIDEO' ) { invalidateActiveVideoCache(); requestImmediateUIUpdate(); } }, true ); // ========================================== // Fullscreen 状态变化 // ========================================== [ 'fullscreenchange', 'webkitfullscreenchange' ].forEach(eventName => { document.addEventListener( eventName, () => { invalidateActiveVideoCache(); requestImmediateUIUpdate(); }, true ); }); // ========================================== // 滚轮调整倍速 // ========================================== window.addEventListener( 'wheel', e => { const video = getActiveVideo(true); if ( !video || isLiveStream(video) ) { return; } if ( video.paused && !isVideoFullscreen(video) ) { return; } if ( isEventInVideoArea( e, video ) || ( UI_DIV && UI_DIV.contains( e.target ) ) ) { e.preventDefault(); e.stopPropagation(); const direction = e.deltaY < 0 ? CONFIG.STEP : -CONFIG.STEP; const currentSpeed = (parseFloat( video.playbackRate ) || 1) + direction; changeSpeed( currentSpeed ); // ★ 滚轮期间进入高频刷新 startFastUpdate(); } }, { passive: false, capture: true } ); // ========================================== // 鼠标中键切换 1x / 恢复 // ========================================== window.addEventListener( 'auxclick', e => { if (e.button !== 1) return; const video = getActiveVideo(true); if ( !video || isLiveStream(video) ) { return; } if ( isEventInVideoArea( e, video ) || ( UI_DIV && UI_DIV.contains( e.target ) ) ) { e.preventDefault(); e.stopPropagation(); toggleNormalSpeed(); } }, true ); window.addEventListener( 'mousedown', e => { if (e.button !== 1) return; const video = getActiveVideo(); if ( video && ( isEventInVideoArea( e, video ) || ( UI_DIV && UI_DIV.contains( e.target ) ) ) ) { e.preventDefault(); } }, true ); // ========================================== // 键盘控制 // ========================================== window.addEventListener( 'keydown', e => { const activeTag = document.activeElement ? document.activeElement.tagName : ''; if ( ['INPUT', 'TEXTAREA'] .includes(activeTag) || document.activeElement ?.isContentEditable ) { return; } const code = e.code; const isTargetKey = [ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Numpad5', 'Numpad2' ].includes(code); if (!isTargetKey) { return; } const video = getActiveVideo(true); if (!video) { return; } // ========================================== // 左右方向键:连续快退 / 快进 // ========================================== if ( code === 'ArrowLeft' || code === 'ArrowRight' ) { e.preventDefault(); e.stopPropagation(); if (e.repeat) return; if ( activeKeyCode === code ) { return; } stopKeySeek(); activeKeyCode = code; const step = code === 'ArrowLeft' ? -CONFIG.SEEK_STEP : CONFIG.SEEK_STEP; seekVideo(step); keySeekTimer = setInterval(() => { seekVideo(step); }, CONFIG.SEEK_INTERVAL); return; } // ========================================== // 上下方向键:倍速 // ========================================== if (isLiveStream(video)) { return; } e.preventDefault(); e.stopPropagation(); if ( code === 'ArrowUp' ) { changeSpeed( (parseFloat( video.playbackRate ) || 1) + CONFIG.STEP ); } else if ( code === 'ArrowDown' ) { changeSpeed( (parseFloat( video.playbackRate ) || 1) - CONFIG.STEP ); } else if ( code === 'Numpad5' ) { toggleNormalSpeed(); } else if ( code === 'Numpad2' ) { changeSpeed( CONFIG.PREFERRED_SPEED ); } }, true ); // ========================================== // Keyup // ========================================== window.addEventListener( 'keyup', e => { if ( e.code === activeKeyCode ) { stopKeySeek(); } }, true ); window.addEventListener( 'blur', () => { stopKeySeek(); } ); // ========================================== // DOM 变化监听 // ========================================== let mutationTimer = null; function scheduleVideoRefresh() { if (mutationTimer) return; mutationTimer = setTimeout(() => { mutationTimer = null; invalidateActiveVideoCache(); requestImmediateUIUpdate(); }, 100); } try { const observer = new MutationObserver(() => { scheduleVideoRefresh(); }); if (document.documentElement) { observer.observe( document.documentElement, { childList: true, subtree: true } ); } } catch (e) {} // ========================================== // 页面滚动 / resize // ========================================== let layoutTimer = null; function scheduleLayoutUpdate() { if (layoutTimer) return; layoutTimer = requestAnimationFrame(() => { layoutTimer = null; requestImmediateUIUpdate(); }); } window.addEventListener( 'resize', scheduleLayoutUpdate, { passive: true } ); window.addEventListener( 'scroll', scheduleLayoutUpdate, { passive: true, capture: true } ); // ========================================== // 页面离开 // ========================================== window.addEventListener( 'beforeunload', () => { stopKeySeek(); stopFastUpdate(); stopNormalUpdateLoop(); if (mutationTimer) { clearTimeout( mutationTimer ); mutationTimer = null; } } ); // ========================================== // 初始启动 // ========================================== requestImmediateUIUpdate(); startNormalUpdateLoop(); })();