// ==UserScript== // @name 全功能智能视频倍速控制器 (全局键盘生效版) // @namespace http://tampermonkey.net/ // @version 4.6.2 // @description 全网通用(自动在YouTube上屏蔽),全局键盘生效无需点击视频 | 跨iframe同步控制 | 支持直播时移 | 常驻系统时间 // @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(); } // ========================================== // ✅ 核心新增:跨iframe全局控制 // ========================================== const MSG_TYPE = 'TS_GLOBAL_SPEED_CONTROL_CMD'; // 顶层窗口向所有子iframe广播控制指令 function broadcastCommand(cmd) { if (window.top !== window.self) return; const iframes = document.querySelectorAll('iframe'); iframes.forEach(iframe => { try { iframe.contentWindow.postMessage({ type: MSG_TYPE, cmd: cmd }, '*'); } catch (e) {} }); } // 统一执行命令(本地按键 + 消息触发共用) function executeCommand(cmd) { const video = getActiveVideo(true); if (!video) return; switch (cmd) { case 'speedUp': if (!isLiveStream(video)) { changeSpeed((parseFloat(video.playbackRate) || 1) + CONFIG.STEP); } break; case 'speedDown': if (!isLiveStream(video)) { changeSpeed((parseFloat(video.playbackRate) || 1) - CONFIG.STEP); } break; case 'seekLeft': seekVideo(-CONFIG.SEEK_STEP); break; case 'seekRight': seekVideo(CONFIG.SEEK_STEP); break; case 'toggleNormal': toggleNormalSpeed(); break; case 'resetSpeed': if (!isLiveStream(video)) { changeSpeed(CONFIG.PREFERRED_SPEED); } break; } } // 监听来自主页面的控制消息 window.addEventListener('message', (e) => { const data = e.data; if (!data || data.type !== MSG_TYPE) return; executeCommand(data.cmd); }, false); // ========================================== // 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 = `