// ==UserScript== // @name 视频缓冲增强 // @namespace https://scriptcat.org/ // @version 2026.12.3 // @description 网页视频智能缓冲增强:自动适配 Hls.js / dash.js / shaka-player / video.js / xgplayer / flv.js / mpegts.js / ArtPlayer 等播放器,按视频时长与网站实际缓冲能力动态调整缓冲目标并实时变动(无硬性封顶);HLS.js 并发预取、在途请求合并、内存缓存,显著减少播放卡顿;悬浮面板实时显示缓冲秒数 / 网速 / 引擎类型,缓冲条颜色可自定义,底部进度条自动跟随网站主题色;全屏与网页全屏时鼠标静止 3 秒自动接管控制栏与进度条;直播流智能保护不被误改,无视频页面不注入,SPA 换源安全重置 // @tag 视频 缓冲 美化 // @author zzz妄炁&AI // @match *://*/* // @grant unsafeWindow // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @compatible chrome // @compatible firefox // @icon https://haowallpaper.com/default-avatar.webp?v=322b8ddb // @run-at document-start // @inject-into page // @license MIT // ==/UserScript== (function () { 'use strict'; const PAGE = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; const IS_MOBILE = /android|iphone|ipad|ipod|mobile|harmony/i.test(navigator.userAgent) || ((navigator.maxTouchPoints || 0) > 1 && window.innerWidth < 1024); const POLL_INTERVAL = IS_MOBILE ? 2000 : 1200; const GUARD_INTERVAL = 5000; const REPOSITION_INTERVAL = 1500; const COLOR_KEY = 'vbp_buffer_color'; const POS_KEY = 'vbp_panel_pos'; const FLOAT_POS_KEY = 'vbp_float_pos'; const FS_HIDE_CTRL_KEY = 'vbp_fs_hide_ctrl'; const LIVE_BYPASS_KEY = 'vbp_live_bypass'; const DEFAULT_COLOR = '#4a90e2'; const BUFFER_COLOR_VAR = '--vbp-buffer-color'; const SITE_PLAYED_COLOR_VAR = '--vbp-site-played-color'; const DEFAULT_PLAYED_COLOR = DEFAULT_COLOR; const BASE_TARGET_DESKTOP = 60; const BASE_TARGET_MOBILE = 30; const BASE_TARGET_LIVE = 30; const MIN_SAFE_TARGET = 10; const CAPACITY_RECOVERY_TARGET = 20; const RECOVERY_STEP = 10; const RECOVERY_INTERVAL_MS = 15000; const STALL_DEGRADE_FACTOR = 0.5; /* ★ 缓冲上限动态化:目标跟随站点配置与实际缓冲能力,不设硬性封顶 */ const LONG_VIDEO_THRESHOLD = 600; const LONG_VIDEO_RATIO = 0.3; /* ★ 实际缓冲峰值采信门槛:只有实际缓冲"远超"当前目标时才视为站点真实能力, 避免贴身小幅超出形成"目标越多→缓冲越多→目标越大"的匀速爬升 */ const PEAK_RATIO_THRESHOLD = 1.5; const PEAK_MARGIN_SECONDS = 60; /* ★ 预取深度动态化 */ const PREFETCH_BASE_DEPTH = 90; const PREFETCH_DEPTH_BONUS = 30; const PREFETCH_MAX_DEPTH = 300; const PREFETCH_CONCURRENCY = IS_MOBILE ? 3 : 6; /* ★ 内存缓存限制(按平台区分) */ const MEMORY_CACHE_LIMIT = 80 * 1024 * 1024; const MEMORY_CACHE_HARD_CAP = IS_MOBILE ? 128 * 1024 * 1024 : 256 * 1024 * 1024; const MEMORY_CACHE_PER_SEC_MB = IS_MOBILE ? 0.4 : 0.7; /* 播放器引擎显示名 */ const ENGINE_LABELS = { dashjs: 'DASH', hls: 'HLS', shaka: 'SHAKA', videojs: 'VJS', xgplayer: 'XG', artplayer: 'ART', flv: 'FLV', native: '原生' }; const HIDE_DELAY_MS = IS_MOBILE ? 1500 : 3000; const SITE_COLOR_DETECT_INTERVAL = 5000; /* ★ 最小化面板自动隐藏 */ const MINI_HIDE_DELAY_MS = 7000; let bufferColor = String(GM_getValue(COLOR_KEY, DEFAULT_COLOR) || DEFAULT_COLOR).trim() || DEFAULT_COLOR; let hideCtrlInFs = GM_getValue(FS_HIDE_CTRL_KEY, true) !== false; let bypassLive = GM_getValue(LIVE_BYPASS_KEY, true) !== false; let videoHadControls = new WeakMap(); let lastUserActivityTime = Date.now(); let mouseInVideoArea = false; let mouseLeaveTimer = 0; let videoRectCache = null; let bottomBar = null; let bottomBarHideTimer = 0; let panel = null; let collapsed = true; let currentHost = null; let isEmbedded = false; let currentPos = null; let dragPaused = false; let progressDragging = false; /* ★ 最小化自动隐藏状态 */ let miniAutoHidden = false; let miniHideTimer = 0; let uiMounted = false; let oneTimeSetupDone = false; let settingsOverlay = null; let settingsModal = null; /* ★ 定时器句柄统一管理,便于清理 */ let panelUpdateTimer = null; let pollTimer = null; let guardTimer = null; let repositionTimer = null; let fsIdleTimer = null; let origArtHookTimer = null; let origArtHookAttempts = 0; /* ★ 实际缓冲峰值追踪(换源/换视频/重置时清零) */ let _peakBuffered = 0; let siteProgressColor = null; let lastColorDetectTime = 0; let currentEngine = 'native'; let dashPlayer = null; let shakaPlayer = null; let xgPlayer = null; let artPlayerInstance = null; let hlsInstances = new Set(); let videoJsApplied = false; let flvHooked = false; let mpegtsHooked = false; let dashHookDone = false; let hlsHookDone = false; let shakaHookDone = false; let xgHookDone = false; let artHookDone = false; let dashAppliedTarget = null; let xgAppliedTarget = null; const log = (...a) => console.log('%c[VBP]', 'color:#00bcd4;font-weight:bold', ...a); const ICON_PLAY = ''; const ICON_GEAR = ''; const ICON_X = ''; /* ============================================================ * 1. 工具 * ============================================================ */ /* 视频元素缓存:热点路径共用,元素脱离文档时自动重新查找, 避免同一时间片内数十次 querySelector */ let _activeVideo = null; function getActiveVideo() { if (_activeVideo && document.contains(_activeVideo)) return _activeVideo; _activeVideo = document.querySelector('video'); return _activeVideo; } function hexColor(c) { return /^#[0-9a-f]{6}$/i.test(String(c || '')) ? c : DEFAULT_COLOR; } function getForwardBuffer(video) { if (!video) return 0; try { if (video.buffered.length > 0) { return Math.max(0, video.buffered.end(video.buffered.length - 1) - video.currentTime); } } catch (_) {} return 0; } function fmtTime(sec) { if (!isFinite(sec) || sec < 0) return '00:00'; sec = Math.floor(sec); const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; const p = (n) => (n < 10 ? '0' + n : '' + n); return h > 0 ? `${h}:${p(m)}:${p(s)}` : `${p(m)}:${p(s)}`; } function fmtSpeed(bps) { if (!bps || bps <= 0) return '0'; if (bps < 1024) return Math.round(bps) + 'B'; if (bps < 1024 * 1024) return (bps / 1024).toFixed(1) + 'K'; return (bps / 1024 / 1024).toFixed(1) + 'M'; } function isMediaUrl(url) { if (!url) return false; return /\.(m3u8|ts|m4s|mp4|flv|mp3|aac|webm|m4a|fmp4|m4v|mov|mkv)(\?|#|$)/i.test(String(url)); } function dataSize(data) { if (!data) return 0; return data.byteLength || data.length || 0; } /* 深拷贝响应体:hls.js 会把 ArrayBuffer 以 Transferable 方式移交解复用 Worker, 原缓冲区随后被 detach;缓存必须只存/只发独立副本,否则 seek 回看命中缓存即崩溃 */ function cloneBuffer(data) { try { if (typeof data === 'string') return data; if (data && typeof data.slice === 'function') return data.slice(0); } catch (_) {} return data; } /* 缓存命中时构造合成 stats:传 null 会让 hls.js 内部读取 stats 字段时抛异常, 且带宽估算可能除零;用约 5Mbps 的中性估计,避免 ABR 被异常拉扯 */ function makeInstantStats(data) { const now = performance.now(); const size = dataSize(data); const durMs = Math.max(50, size / 625); return { aborted: false, loaded: size, retry: 0, total: size, loading: { start: now - durMs, first: now, end: now }, parsing: { start: now, end: now }, buffering: { start: now, end: now } }; } function isVideoFullscreen() { if (document.fullscreenElement) return true; if (document.webkitFullscreenElement) return true; if (document.mozFullScreenElement) return true; if (document.msFullscreenElement) return true; const v = getActiveVideo(); if (v) { try { if (v.webkitDisplayingFullscreen === true) return true; } catch (_) {} } return false; } function getFullscreenEl() { return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null; } function getVideoRect() { if (isVideoFullscreen()) { const fsEl = getFullscreenEl(); if (fsEl && fsEl.getBoundingClientRect) { const r = fsEl.getBoundingClientRect(); if (r.width > 0 && r.height > 0) return r; } if (artPlayerInstance && artPlayerInstance.template?.$player) { const r = artPlayerInstance.template.$player.getBoundingClientRect(); if (r.width > 0 && r.height > 0) return r; } } const v = getActiveVideo(); return v ? v.getBoundingClientRect() : null; } function getVideoRectCached() { if (!videoRectCache) videoRectCache = getVideoRect(); return videoRectCache; } let fakeFsCache = { result: false, at: 0 }; function invalidateVideoRectCache() { videoRectCache = null; fakeFsCache.at = 0; } /* 网页全屏(fake fullscreen)检测:站点未调用 Fullscreen API, 而是把播放器容器 position:fixed 铺满视口("网页全屏"的通用实现)。 要求容器 fixed/sticky 且自视口左上角起占满 95% 以上,避免误伤普通 100vh 视频流 */ function isFakeFullscreen() { const now = Date.now(); if (now - fakeFsCache.at < 1000) return fakeFsCache.result; let result = false; const v = getActiveVideo(); if (v) { try { const r = v.getBoundingClientRect(); if (r.width >= window.innerWidth * 0.95 && r.height >= window.innerHeight * 0.95) { let el = v.parentElement; for (let i = 0; i < 8 && el && el !== document.body && el !== document.documentElement; i++) { const cs = getComputedStyle(el); const er = el.getBoundingClientRect(); if ((cs.position === 'fixed' || cs.position === 'sticky') && er.width >= window.innerWidth * 0.95 && er.height >= window.innerHeight * 0.95 && er.top <= 5 && er.left <= 5) { result = true; break; } el = el.parentElement; } } } catch (_) {} } fakeFsCache = { result, at: now }; return result; } /* video 元素自身被原生全屏(video.requestFullscreen):浏览器只渲染 video 节点, 页面内任何 UI 均不可见,脚本必须放弃接管并保留原生控制栏 */ function isNativeVideoFullscreen(video) { const fsEl = getFullscreenEl(); return !!(fsEl && video && fsEl === video); } function isEffectivelyFullscreen() { return isVideoFullscreen() || isFakeFullscreen(); } /* ★ 修复 6:duration 有效时直接排除直播 */ function isLikelyLive(video) { if (!video) return false; try { const dur = video.duration; if (dur === Infinity) return true; if (typeof dur === 'number' && isFinite(dur) && dur > 0 && dur < 86400) { return false; // 明确的点播 } /* duration 为 NaN/0 表示元数据未就绪,不能武断判为直播,交给 seekable 辅助判断 */ if (video.seekable && video.seekable.length > 0) { const s = video.seekable.start(0); const e = video.seekable.end(video.seekable.length - 1); if (e - s < 120 && Math.abs(e - video.currentTime) < 15) return true; } } catch (_) {} return false; } function isLiveStream(video) { if (!bypassLive) return false; return isLikelyLive(video); } function toggleFullscreen() { const v = getActiveVideo(); if (!v) return; if (isVideoFullscreen()) { try { if (document.exitFullscreen) document.exitFullscreen(); else if (document.webkitExitFullscreen) document.webkitExitFullscreen(); else if (document.mozCancelFullScreen) document.mozCancelFullScreen(); else if (document.msExitFullscreen) document.msExitFullscreen(); } catch (_) {} } else { try { if (v.requestFullscreen) v.requestFullscreen(); else if (v.webkitRequestFullscreen) v.webkitRequestFullscreen(); else if (v.mozRequestFullScreen) v.mozRequestFullScreen(); else if (v.msRequestFullscreen) v.msRequestFullscreen(); } catch (_) {} } } function isFsIdle() { return Date.now() - lastUserActivityTime > HIDE_DELAY_MS; } /* ============================================================ * 1.5 网站进度条颜色检测 * ============================================================ */ function isVisibleColor(c) { if (!c) return false; if (c === 'transparent' || c === 'initial' || c === 'none') return false; if (/^rgba\([^)]+,\s*0(\.0+)?\)$/.test(c)) return false; if (/^rgba\(0,\s*0,\s*0,\s*0\)$/.test(c)) return false; return true; } function detectSiteProgressColor() { const selectors = [ '.vjs-play-progress', '.xgplayer-progress-played', '.dplayer-progress-played', '.art-progress-played', '.ytp-play-progress', '.bpx-player-progress-schedule-current', '.bpx-player-progress-current', '.prism-progress-played', '.prism-progress-loaded', '.txp-progress-played', '.txp-progress-main', '.iqp-progress-played', '.iqp-progress-current', '.youku-progress-played', '[class*="progress" i][class*="played" i]', '[class*="play-progress" i]', '[class*="progress" i][class*="current" i]', '[class*="progress" i][class*="active" i]', '[class*="progress" i][class*="bar" i][class*="played" i]' ]; for (const sel of selectors) { try { const el = document.querySelector(sel); if (!el) continue; const cs = getComputedStyle(el); const bg = cs.backgroundColor; if (isVisibleColor(bg)) return bg; const bgFull = cs.background; if (bgFull && bgFull.indexOf('rgb') >= 0) { const m = bgFull.match(/rgba?\([^)]+\)/); if (m && isVisibleColor(m[0])) return m[0]; } } catch (_) {} } try { const rootStyle = getComputedStyle(document.documentElement); const themeVars = [ '--theme-color', '--primary-color', '--brand-color', '--vjs-theme-color', '--bpx-primary-color', '--accent-color', '--accent', '--main-color', '--color-primary' ]; for (const v of themeVars) { const c = rootStyle.getPropertyValue(v).trim(); if (isVisibleColor(c)) return c; } } catch (_) {} return null; } function applySiteProgressColor(color) { const finalColor = color || DEFAULT_PLAYED_COLOR; try { document.documentElement.style.setProperty(SITE_PLAYED_COLOR_VAR, finalColor); } catch (_) {} } function updateSiteProgressColorIfNeeded() { const now = Date.now(); if (now - lastColorDetectTime < SITE_COLOR_DETECT_INTERVAL) return; lastColorDetectTime = now; const color = detectSiteProgressColor(); if (color !== siteProgressColor) { siteProgressColor = color; applySiteProgressColor(color); } } /* ============================================================ * 1.6 实时网速追踪 * ============================================================ */ const NetSpeed = { samples: [], addBytes(n) { if (!n || n <= 0) return; const now = performance.now(); this.samples.push({ t: now, b: n }); if (this.samples.length > 600) this.samples = this.samples.slice(-400); }, current() { const now = performance.now(); const cutoff = now - 2000; let i = 0; while (i < this.samples.length && this.samples[i].t < cutoff) i++; if (i > 0) this.samples = this.samples.slice(i); if (this.samples.length === 0) return 0; let sum = 0; for (const s of this.samples) sum += s.b; const span = Math.max(0.5, (now - this.samples[0].t) / 1000); return sum / span; } }; function installSpeedTracker() { try { const XHR = PAGE.XMLHttpRequest; if (XHR && XHR.prototype && !XHR.prototype._vbpSpeedHooked) { const proto = XHR.prototype; const origOpen = proto.open; const origSend = proto.send; proto.open = function (method, url) { try { this._vbpUrl = String(url || ''); } catch (_) {} return origOpen.apply(this, arguments); }; proto.send = function () { try { if (this._vbpTracked === undefined) { this._vbpTracked = true; const isMedia = this.responseType === 'arraybuffer' || this.responseType === 'blob' || isMediaUrl(this._vbpUrl); if (isMedia) { let lastLoaded = 0; this.addEventListener('progress', (e) => { const delta = e.loaded - lastLoaded; if (delta > 0) { NetSpeed.addBytes(delta); lastLoaded = e.loaded; } }); } } } catch (_) {} return origSend.apply(this, arguments); }; proto._vbpSpeedHooked = true; } } catch (_) {} try { const origFetch = PAGE.fetch; if (origFetch && !origFetch._vbpSpeedHooked) { const wrapped = function (input, init) { const url = typeof input === 'string' ? input : (input && input.url) || ''; const promise = origFetch.apply(this, arguments); if (isMediaUrl(url)) { promise.then((resp) => { try { const cloned = resp.clone(); const reader = cloned.body && cloned.body.getReader(); if (!reader) return; const pump = () => reader.read().then(({ done, value }) => { if (done) return; if (value && value.length) NetSpeed.addBytes(value.length); return pump(); }).catch(() => {}); pump(); } catch (_) {} }).catch(() => {}); } return promise; }; wrapped._vbpSpeedHooked = true; /* 保持 toString 原生特征,避免站点反检测破坏封装 */ try { wrapped.toString = origFetch.toString.bind(origFetch); } catch (_) {} try { PAGE.fetch = wrapped; } catch (_) {} } } catch (_) {} } /* ============================================================ * 1.7 网站缓冲能力探测 * ============================================================ */ function detectEngineConfigBuffer() { let detected = 0; /* --- HLS.js --- */ const hlsDefaultMax = (PAGE.Hls && PAGE.Hls.DefaultConfig && PAGE.Hls.DefaultConfig.maxBufferLength) || 30; const inspectHls = (h) => { if (!h || !h.config) return; const c = h.config; if (c.maxBufferLength && c.maxBufferLength > hlsDefaultMax + 10) { detected = Math.max(detected, c.maxBufferLength); } }; for (const h of hlsInstances) inspectHls(h); if (PAGE.hls) inspectHls(PAGE.hls); if (PAGE.Hls && PAGE.Hls.instances instanceof Map) { for (const h of PAGE.Hls.instances.values()) inspectHls(h); } for (const v of document.querySelectorAll('video')) { for (const k of ['__hls', 'hls', '_hls']) if (v[k]) inspectHls(v[k]); } /* ★ 修复 7:dash.js getSettings 安全检测 */ const DASH_DEFAULT = 12; const inspectDash = (p) => { if (!p || typeof p.getSettings !== 'function') return; let s = null; try { s = p.getSettings(); } catch (_) { return; } if (!s) return; const b = s.streaming && s.streaming.buffer; if (!b) return; if (typeof b.bufferTimeDefault === 'number' && b.bufferTimeDefault > DASH_DEFAULT + 5) { detected = Math.max(detected, b.bufferTimeDefault); } if (typeof b.stableBufferTime === 'number' && b.stableBufferTime > DASH_DEFAULT + 5) { detected = Math.max(detected, b.stableBufferTime); } }; if (dashPlayer) inspectDash(dashPlayer); for (const p of [PAGE.player, PAGE.dashPlayer]) inspectDash(p); if (PAGE.dashjs && PAGE.dashjs.MediaPlayer && PAGE.dashjs.MediaPlayer._instance) { inspectDash(PAGE.dashjs.MediaPlayer._instance); } for (const v of document.querySelectorAll('video')) { if (v._dashjs_player) inspectDash(v._dashjs_player); } /* --- shaka --- */ const SHAKA_DEFAULT = 10; const inspectShaka = (p) => { if (!p || typeof p.getConfiguration !== 'function') return; try { const c = p.getConfiguration(); if (c && c.streaming && c.streaming.bufferingGoal && c.streaming.bufferingGoal > SHAKA_DEFAULT + 5) { detected = Math.max(detected, c.streaming.bufferingGoal); } } catch (_) {} }; if (shakaPlayer) inspectShaka(shakaPlayer); if (PAGE.player) inspectShaka(PAGE.player); for (const v of document.querySelectorAll('video')) { if (v.shakaPlayer) inspectShaka(v.shakaPlayer); } /* --- video.js VHS --- */ if (PAGE.videojs && PAGE.videojs.Vhs) { const v = PAGE.videojs.Vhs; if (v.GOAL_BUFFER_LENGTH && v.GOAL_BUFFER_LENGTH > 40) { detected = Math.max(detected, v.GOAL_BUFFER_LENGTH); } if (v.MAX_GOAL_BUFFER_LENGTH && v.MAX_GOAL_BUFFER_LENGTH > 80) { detected = Math.max(detected, v.MAX_GOAL_BUFFER_LENGTH); } } /* --- xgplayer --- */ const inspectXg = (p) => { if (!p || typeof p.config !== 'object' || !p.config) return; const c = p.config; if (c.hls && c.hls.preloadTime && c.hls.preloadTime > 35) { detected = Math.max(detected, c.hls.preloadTime); } if (c.flv && c.flv.preloadTime && c.flv.preloadTime > 35) { detected = Math.max(detected, c.flv.preloadTime); } if (c.dash && c.dash.maxBufferLength && c.dash.maxBufferLength > 35) { detected = Math.max(detected, c.dash.maxBufferLength); } }; if (xgPlayer) inspectXg(xgPlayer); if (PAGE.player) inspectXg(PAGE.player); /* 仅探测各引擎的显式配置,语义为"站点开发者设定的缓冲能力"; 实际缓冲峰值的实时采信在 updateSiteCeiling 中每 tick 执行。 取整后返回,避免站点配置中的浮点值带出长小数 */ return Math.floor(detected); } /* 引擎配置探测节流:dash.js getSettings 等调用较重,无需每 tick 执行 */ let _engineConfigDetected = 0; let _lastEngineProbeTime = 0; const ENGINE_PROBE_INTERVAL = 8000; /* 换视频/换源/手动重置时清空探测缓存 */ function resetSiteProbeCache() { _peakBuffered = 0; _engineConfigDetected = 0; _lastEngineProbeTime = 0; } function updateSiteCeiling() { /* 峰值采信(轻量,每 tick 执行):实际缓冲大幅超过当前目标(>1.5倍且>+60s)时, 说明站点/网络实际支撑更大缓冲,目标如实跟随(无封顶); 贴身小幅超出不采信,避免"目标越多→缓冲越多→目标越大"的爬升; 降级/恢复期间冻结采信,保证降级保护有效 */ let detected = _engineConfigDetected; const video = getActiveVideo(); if (video && Governor.mode === 'normal') { try { const forward = getForwardBuffer(video); if (forward > _peakBuffered) _peakBuffered = forward; const scriptDefault = IS_MOBILE ? BASE_TARGET_MOBILE : BASE_TARGET_DESKTOP; if (_peakBuffered > scriptDefault * PEAK_RATIO_THRESHOLD && _peakBuffered > Governor.currentTarget * PEAK_RATIO_THRESHOLD && _peakBuffered > Governor.currentTarget + PEAK_MARGIN_SECONDS) { detected = Math.max(detected, _peakBuffered); } } catch (_) {} } /* 引擎配置探测(较重):按 ENGINE_PROBE_INTERVAL 节流 */ const now = Date.now(); if (now - _lastEngineProbeTime >= ENGINE_PROBE_INTERVAL) { _lastEngineProbeTime = now; try { const cfgDetected = detectEngineConfigBuffer(); if (cfgDetected > _engineConfigDetected) _engineConfigDetected = cfgDetected; } catch (_) {} } /* 取整后生效,避免浮点带出长小数 */ detected = Math.floor(detected); const prev = Governor.siteCeiling || 0; if (detected > prev) { Governor.siteCeiling = detected; log(`网站缓冲能力: ${prev}s → ${detected}s`); return true; } return false; } /* ★ 修复 1:预取深度动态化 */ function getPrefetchDepth() { return Math.min( PREFETCH_MAX_DEPTH, Math.max(PREFETCH_BASE_DEPTH, Governor.currentTarget + PREFETCH_DEPTH_BONUS) ); } /* ============================================================ * 2. 缓冲治理器 * ============================================================ */ const Governor = { baseTarget: BASE_TARGET_DESKTOP, currentTarget: BASE_TARGET_DESKTOP, ceilingTarget: BASE_TARGET_DESKTOP, siteCeiling: 0, mode: 'normal', lastDegradeTime: 0, lastRecoveryTime: 0, stallHistory: [], reset(video) { this.baseTarget = computeBaseTarget(video); this.currentTarget = this.baseTarget; this.ceilingTarget = this.baseTarget; this.mode = 'normal'; this.lastDegradeTime = 0; this.lastRecoveryTime = 0; this.stallHistory = []; }, recordStall() { const now = Date.now(); this.stallHistory.push(now); this.stallHistory = this.stallHistory.filter(t => now - t < 60000); if (this.stallHistory.length >= 2 && this.mode !== 'degraded') { this.degrade('frequent_stall'); } }, degrade(reason) { if (this.mode === 'degraded') return; const prev = this.currentTarget; this.currentTarget = Math.max(MIN_SAFE_TARGET, Math.floor(this.currentTarget * STALL_DEGRADE_FACTOR)); this.mode = 'degraded'; this.lastDegradeTime = Date.now(); this.lastRecoveryTime = 0; log(`缓冲降级 (${reason}): ${prev}s → ${this.currentTarget}s`); }, onCapacityError() { if (this.mode === 'degraded' && this.currentTarget <= CAPACITY_RECOVERY_TARGET) return; const prev = this.currentTarget; this.currentTarget = CAPACITY_RECOVERY_TARGET; this.mode = 'degraded'; this.lastDegradeTime = Date.now(); this.lastRecoveryTime = 0; log(`容量超限降级: ${prev}s → ${CAPACITY_RECOVERY_TARGET}s`); }, tryRecover(video) { if (this.mode !== 'degraded') return; const now = Date.now(); if (now - this.lastDegradeTime < RECOVERY_INTERVAL_MS) return; if (now - this.lastRecoveryTime < RECOVERY_INTERVAL_MS) return; const curBuf = getForwardBuffer(video); if (curBuf < this.currentTarget * 0.8) return; this.lastRecoveryTime = now; const prev = this.currentTarget; this.currentTarget = Math.floor(Math.min(this.ceilingTarget, this.currentTarget + RECOVERY_STEP)); this.mode = this.currentTarget >= this.ceilingTarget ? 'normal' : 'recovering'; log(`缓冲恢复: ${prev}s → ${this.currentTarget}s`); }, markHealthy() { if (this.mode === 'recovering' && this.currentTarget >= this.ceilingTarget) this.mode = 'normal'; } }; function computeBaseTarget(video) { const scriptDefault = IS_MOBILE ? BASE_TARGET_MOBILE : BASE_TARGET_DESKTOP; if (video) { try { const dur = video.duration; /* ★ 修复 8:直播分支直接返回,语义清晰 */ if (dur === Infinity || (typeof dur === 'number' && !isFinite(dur))) { return BASE_TARGET_LIVE; } if (dur > 0) { const effectiveMax = Math.max(scriptDefault, Governor.siteCeiling || 0); if (dur < 10) return Math.max(1, Math.floor(dur)); let durCap; if (dur < 300) durCap = Math.max(MIN_SAFE_TARGET, Math.floor(dur * 0.5)); else if (dur < LONG_VIDEO_THRESHOLD) durCap = Math.floor(dur * 0.4); else durCap = Math.floor(dur * LONG_VIDEO_RATIO); /* 默认受时长比例约束;但站点能力/实际缓冲超过比例上限时, 目标按实际的走(仅受视频总时长约束), 避免"缓冲已近全片而目标卡在比例上限" */ const base = effectiveMax > durCap ? Math.min(effectiveMax, Math.floor(dur)) : Math.min(effectiveMax, durCap); return Math.floor(Math.max(MIN_SAFE_TARGET, base)); } } catch (_) {} } return Math.floor(Math.max(scriptDefault, Governor.siteCeiling || 0)); } let cachedVideo = null; let cachedDuration = null; function updateSmartTarget() { const video = getActiveVideo(); if (!video) return; if (cachedVideo !== video) { cachedVideo = video; cachedDuration = null; resetSiteProbeCache(); Governor.siteCeiling = 0; Governor.reset(video); } const ceilingChanged = updateSiteCeiling(); let dur = null; try { dur = video.duration; } catch (_) {} if (dur !== cachedDuration || ceilingChanged) { cachedDuration = dur; const newBase = computeBaseTarget(video); if (newBase !== Governor.baseTarget) { const prev = Governor.baseTarget; Governor.baseTarget = newBase; Governor.ceilingTarget = newBase; if (Governor.mode === 'normal' || Governor.currentTarget < newBase) { Governor.currentTarget = newBase; } dashAppliedTarget = null; xgAppliedTarget = null; reapplyAll(); log(`缓冲目标: ${prev}s → ${newBase}s(网站上限 ${Governor.siteCeiling}s,预取深度 ${getPrefetchDepth()}s)`); } } Governor.tryRecover(video); Governor.markHealthy(); } /* ============================================================ * 3. Stall 检测 * ============================================================ */ const stallInfo = { startTime: 0, startBuffer: 0 }; function setupStallWatch(video) { if (!video || video._vbpStallSetup) return; video._vbpStallSetup = true; video.addEventListener('waiting', () => { stallInfo.startTime = Date.now(); stallInfo.startBuffer = getForwardBuffer(video); }); const clear = () => { stallInfo.startTime = 0; }; video.addEventListener('playing', clear); video.addEventListener('seeked', clear); } function checkStallHealth() { if (stallInfo.startTime === 0) return; if (Date.now() - stallInfo.startTime < 5000) return; const video = getActiveVideo(); if (!video) return; const curBuf = getForwardBuffer(video); if (curBuf - stallInfo.startBuffer < 2 && curBuf < 10) { Governor.recordStall(); stallInfo.startTime = 0; } } /* ============================================================ * 4. HLS.js 预取引擎 * ============================================================ */ const PrefetchEngine = { memoryCache: new Map(), memoryCacheSize: 0, inFlight: new Map(), hijackedSet: new WeakSet(), hijackLoader(hls) { if (!hls || this.hijackedSet.has(hls)) return; const cfg = hls.config; if (!cfg || !cfg.loader) return; const OriginalLoader = cfg.loader; const engine = this; cfg.loader = class extends OriginalLoader { load(context, config, callbacks) { const url = context.url; this._vbpUrl = url; if (!url || context.type !== 'fragment') { return super.load(context, config, callbacks); } const v = getActiveVideo(); if (v && isLiveStream(v)) { return super.load(context, config, callbacks); } if (engine.memoryCache.has(url)) { /* 命中缓存:分发独立副本并携带合成 stats, 防止 hls.js 因 null stats 崩溃或缓冲被 Worker transfer 后 detach */ const cached = engine.memoryCache.get(url); const stats = makeInstantStats(cached); const payload = cloneBuffer(cached); Promise.resolve().then(() => { try { callbacks.onSuccess({ data: payload, url }, stats, context); } catch (_) { try { callbacks.onError({ details: 'vbpCacheError' }, context, stats); } catch (_) {} } }); return; } const existing = engine.inFlight.get(url); if (existing) { existing.waiters.push({ callbacks, context, loader: this }); return; } const entry = { waiters: [{ callbacks, context, loader: this }], startedAt: Date.now(), prefetch: this._vbpIsPrefetch === true }; engine.inFlight.set(url, entry); const wrapped = { onSuccess: (response, stats, ctx, networkDetails) => { /* 写缓存必须存副本:原 ArrayBuffer 会随 hls.js 内部 transfer 被 detach */ try { if (response && dataSize(response.data) > 0) { engine.putCache(url, cloneBuffer(response.data)); } } catch (_) {} if (engine.inFlight.get(url) === entry) engine.inFlight.delete(url); for (const w of entry.waiters) { try { w.callbacks.onSuccess(response, w.context, stats, networkDetails); } catch (_) {} } }, onError: (err, ctx, stats, networkDetails) => { if (engine.inFlight.get(url) === entry) engine.inFlight.delete(url); for (const w of entry.waiters) { try { w.callbacks.onError(err, w.context, stats, networkDetails); } catch (_) {} } }, onTimeout: (stats, ctx) => { if (engine.inFlight.get(url) === entry) engine.inFlight.delete(url); for (const w of entry.waiters) { try { w.callbacks.onTimeout(stats); } catch (_) {} } }, onProgress: (stats, ctx, data, networkDetails) => { for (const w of entry.waiters) { if (w.callbacks.onProgress) { try { w.callbacks.onProgress(stats, w.context, data, networkDetails); } catch (_) {} } } } }; try { return super.load(context, config, wrapped); } catch (err) { /* 同步异常:清理在途条目并向所有等待者传播,避免永久悬挂 */ if (engine.inFlight.get(url) === entry) engine.inFlight.delete(url); for (const w of entry.waiters) { try { w.callbacks.onError(err, w.context, null); } catch (_) {} } } } abort() { const entry = this._vbpUrl ? engine.inFlight.get(this._vbpUrl) : null; if (entry) { const idx = entry.waiters.findIndex(w => w.loader === this); if (idx >= 0) entry.waiters.splice(idx, 1); if (entry.waiters.length === 0) { engine.inFlight.delete(this._vbpUrl); try { super.abort(); } catch (_) {} } /* 仍有其他等待者复用该请求:保留底层加载,结果会广播给它们 */ return; } try { super.abort(); } catch (_) {} } destroy() { try { this.abort(); } catch (_) {} try { super.destroy(); } catch (_) {} } }; this.hijackedSet.add(hls); this.startPrefetchLoop(hls); }, /* ★ 修复 5:内存限制按平台自适应,与预取深度挂钩 */ getMemLimit() { const depth = getPrefetchDepth(); const dynamic = depth * MEMORY_CACHE_PER_SEC_MB * 1024 * 1024; return Math.min(MEMORY_CACHE_HARD_CAP, Math.max(MEMORY_CACHE_LIMIT, dynamic)); }, putCache(url, data) { if (!data) return; const size = dataSize(data); if (size <= 0) return; /* 顺带拦截已被 detach 的 ArrayBuffer(byteLength 为 0) */ if (this.memoryCache.has(url)) { /* 同 URL 重复写入先扣除旧尺寸,避免计数虚增 */ const old = this.memoryCache.get(url); this.memoryCacheSize -= dataSize(old); this.memoryCache.delete(url); } const limit = this.getMemLimit(); if (size > limit) return; /* 单条目超限直接拒收,避免缓存失控 */ while (this.memoryCacheSize + size > limit && this.memoryCache.size > 0) { const firstKey = this.memoryCache.keys().next().value; if (!firstKey) break; const old = this.memoryCache.get(firstKey); this.memoryCacheSize -= dataSize(old); this.memoryCache.delete(firstKey); } this.memoryCache.set(url, data); this.memoryCacheSize += size; }, startPrefetchLoop(hls) { if (hls._vbpPrefetchLoop) return; hls._vbpPrefetchLoop = setInterval(() => { try { this.doPrefetchBatch(hls); } catch (_) {} }, 1000); }, doPrefetchBatch(hls) { const video = getActiveVideo(); if (!video || video.paused || !isFinite(video.duration)) return; const forwardBuf = getForwardBuffer(video); /* ★ 修复 1:跟随目标值 + 保底 + 上限 */ const targetDepth = getPrefetchDepth(); if (forwardBuf >= targetDepth) return; /* auto 档时 currentLevel 为 -1,依次回退 loadLevel / 末级 */ const level = hls.levels && (hls.levels[hls.currentLevel] || hls.levels[hls.loadLevel] || hls.levels[hls.levels.length - 1]); if (!level || !level.details || !level.details.fragments) return; /* 精确并发限额:只统计预取在途请求,避免慢网络下请求累积失控 */ let activePrefetch = 0; for (const e of this.inFlight.values()) if (e.prefetch) activePrefetch++; const slots = PREFETCH_CONCURRENCY - activePrefetch; if (slots <= 0) return; const fragments = level.details.fragments; const curTime = video.currentTime; const candidates = []; for (const frag of fragments) { if (!frag || !frag.url) continue; if (frag.start <= curTime + forwardBuf) continue; if (this.memoryCache.has(frag.url)) continue; if (this.inFlight.has(frag.url)) continue; candidates.push(frag); if (candidates.length >= slots) break; } if (candidates.length === 0) return; const LoaderCtor = hls.config.loader; if (!LoaderCtor) return; for (const frag of candidates) { try { const loader = new LoaderCtor(hls.config); loader._vbpIsPrefetch = true; const ctx = { url: frag.url, type: 'fragment', frag: frag, responseType: 'arraybuffer', rangeStart: frag.rangeStart || 0, rangeEnd: (frag.rangeEnd === undefined || frag.rangeEnd === null) ? -1 : frag.rangeEnd }; loader.load(ctx, hls.config, { /* 缓存写入已由合并层统一完成(写入副本),此处无需重复 putCache */ onSuccess: () => {}, onError: () => {}, onTimeout: () => {} }); } catch (_) {} } } }; /* ============================================================ * 5. ArtPlayer 适配 * ============================================================ */ function findArtPlayer() { if (!PAGE.Artplayer) return null; const instances = PAGE.Artplayer.instances; if (!instances) return null; const arr = Array.isArray(instances) ? instances : Array.from(instances); if (arr.length === 0) return null; for (const art of arr) { if (art && art.video && !art.video.paused) return art; } return arr[0]; } function attachArtPlayerCapacityWatch(art) { if (!art || art._vbpCapWatched) return; art._vbpCapWatched = true; const hls = art.hls || (art.option && art.option.customType && art.option.customType.hls); if (hls && typeof hls.on === 'function' && PAGE.Hls && PAGE.Hls.Events && PAGE.Hls.ErrorDetails) { try { hls.on(PAGE.Hls.Events.ERROR, (e, data) => { if (data && data.details === PAGE.Hls.ErrorDetails.BUFFER_APPEND_ERROR && data.error && /QuotaExceeded/i.test(data.error.message || '')) { Governor.onCapacityError(); dashAppliedTarget = null; xgAppliedTarget = null; reapplyAll(); } }); } catch (_) {} } } function pollArtPlayer() { const art = findArtPlayer(); if (!art) return; artPlayerInstance = art; currentEngine = 'artplayer'; attachArtPlayerCapacityWatch(art); artHookDone = true; } function getArtPlayerFullscreenHost() { if (!artPlayerInstance || !artPlayerInstance.template) return null; const $player = artPlayerInstance.template.$player; if (!$player) return null; if (!isEffectivelyFullscreen()) return null; try { const r = $player.getBoundingClientRect(); if (r.width > window.innerWidth * 0.9 && r.height > window.innerHeight * 0.9) { return $player; } } catch (_) {} return null; } /* ============================================================ * 6. 缓冲条着色 * ============================================================ */ function buildBufferColorCSS() { const sels = [ '.vjs-load-progress', '.vjs-load-progress div', '.xgplayer-progress-cache', '.dplayer-progress-loaded', '.art-progress-loaded', '.art-progress-loaded div', '[class*="buffer" i][class*="progress" i]', '[class*="progress" i][class*="cache" i]', '[class*="progress" i][class*="loaded" i]', '[class*="progress" i][class*="buffered" i]', '[class*="load-progress" i]' ]; return sels.join(',\n') + ' {\n' + ' background-color: var(' + BUFFER_COLOR_VAR + ', ' + DEFAULT_COLOR + ') !important;\n' + ' background-image: none !important;\n box-shadow: none !important;\n}'; } function applyBufferColorVar(color) { try { document.documentElement.style.setProperty(BUFFER_COLOR_VAR, color); } catch (_) {} } function injectBufferColorCSS() { let el = document.getElementById('vbp-buffer-color-style'); if (!el) { const host = document.head || document.documentElement; if (!host) return; el = document.createElement('style'); el.id = 'vbp-buffer-color-style'; el.textContent = buildBufferColorCSS(); host.appendChild(el); } applyBufferColorVar(bufferColor); } /* ============================================================ * 7. 全屏隐藏网站控制栏 * ============================================================ */ function buildFullscreenHideCSS() { const explicitSels = [ '.vjs-control-bar', '.vjs-control-bar *', '.xgplayer-controls', '.xgplayer-bottom', '.dplayer-controller', '.dplayer-controller-mask', '.shaka-controls-container', '.shaka-controls-button-panel', '.prism-controlbar', '.prism-progress', '.prism-ctrl-bottom', '.txp_controlbar', '.txp-progress', '.bpx-player-control-bottom', '.bpx-player-control-entity', '.bpx-player-control-wrap', '.bpx-player-control-progress', '.iqp-player-control-bottom', '.iqp-controlbar', '.ytp-chrome-bottom', '.ytp-chrome-controls', '.art-bottom', '.art-controls', '.art-progress' ]; const fuzzySels = [ '[class*="player-controls" i]', '[class*="video-controls" i]', '[class*="media-controls" i]', '[class*="player-control-bar" i]', '[class*="control-bar" i]', '[class*="controlbar" i]', '[class*="control-bottom" i]', '[class*="player-bottom" i]', '[class*="player-progress" i]', '[class*="video-progress" i]', '[class*="seek-bar" i]' ].map(s => `${s}:not(:has(video))`); const allSels = explicitSels.concat(fuzzySels); const hideCss = 'html.vbp-fs-hide-ctrl ' + allSels.join(',\nhtml.vbp-fs-hide-ctrl ') + ' {\n' + ' display: none !important; opacity: 0 !important;\n' + ' pointer-events: none !important; visibility: hidden !important;\n}'; const protectCss = [ 'html.vbp-fs-hide-ctrl video', 'html.vbp-fs-hide-ctrl video *', 'html.vbp-fs-hide-ctrl :has(> video)' ].join(',\n') + ' {\n' + ' display: block !important; opacity: 1 !important;\n' + ' visibility: visible !important; pointer-events: auto !important;\n}'; return hideCss + '\n' + protectCss; } function injectFullscreenCSS() { let el = document.getElementById('vbp-fullscreen-style'); if (!el) { const host = document.head || document.documentElement; if (!host) return; el = document.createElement('style'); el.id = 'vbp-fullscreen-style'; host.appendChild(el); } const css = buildFullscreenHideCSS(); if (el.textContent !== css) el.textContent = css; } function syncNativeControls(video, shouldHide) { if (!video) return; if (shouldHide) { if (video.controls) { videoHadControls.set(video, true); try { video.controls = false; } catch (_) {} } } else { if (videoHadControls.get(video)) { try { video.controls = true; } catch (_) {} videoHadControls.delete(video); } } } function tickFsIdle() { const fs = isEffectivelyFullscreen(); const v = getActiveVideo(); if (!fs) { if (document.documentElement.classList.contains('vbp-fs-hide-ctrl')) { document.documentElement.classList.remove('vbp-fs-hide-ctrl'); } syncNativeControls(v, false); return; } /* video 元素原生全屏:浏览器只渲染 video 节点,脚本 UI 无法显示, 必须保留原生控制栏,否则全屏 3 秒后画面上无任何可操作控件 */ if (isNativeVideoFullscreen(v)) { syncNativeControls(v, false); return; } if (v && isLikelyLive(v)) { if (document.documentElement.classList.contains('vbp-fs-hide-ctrl')) { document.documentElement.classList.remove('vbp-fs-hide-ctrl'); } /* 换源切到直播时必须恢复此前被隐藏的原生控制栏 */ syncNativeControls(v, false); updateBottomBarVisibility(); return; } const idle = isFsIdle(); const shouldHide = hideCtrlInFs && idle; const hasClass = document.documentElement.classList.contains('vbp-fs-hide-ctrl'); if (shouldHide !== hasClass) { document.documentElement.classList.toggle('vbp-fs-hide-ctrl', shouldHide); syncNativeControls(v, shouldHide); updateBottomBarVisibility(); } } function handleFsChange() { requestAnimationFrame(() => { if (settingsOverlay && settingsOverlay.style.display === 'flex') { reattachSettingsOverlay(); } invalidateVideoRectCache(); lastUserActivityTime = Date.now(); tickFsIdle(); if (!dragPaused) setTimeout(reposition, 100); updateBottomBarVisibility(); }); } /* ============================================================ * 8. 颜色 * ============================================================ */ let colorRafId = 0; let colorSaveTimer = 0; let pendingColor = null; function commitColor(color, immediate) { if (!color) color = DEFAULT_COLOR; bufferColor = color; pendingColor = color; if (immediate) { if (colorRafId) { cancelAnimationFrame(colorRafId); colorRafId = 0; } applyBufferColorVar(color); if (colorSaveTimer) { clearTimeout(colorSaveTimer); colorSaveTimer = 0; } try { GM_setValue(COLOR_KEY, color); } catch (_) {} } else { if (!colorRafId) { colorRafId = requestAnimationFrame(() => { colorRafId = 0; applyBufferColorVar(pendingColor); }); } clearTimeout(colorSaveTimer); colorSaveTimer = setTimeout(() => { try { GM_setValue(COLOR_KEY, bufferColor); } catch (_) {} }, 400); } if (shakaPlayer) { setTimeout(() => { if (shakaPlayer) applyShaka(shakaPlayer, true, false); }, 300); } syncColorDot(); } function syncColorDot() { if (panel) { const dot = panel.querySelector('.vbp-color-dot'); if (dot) dot.style.background = bufferColor; /* 面板内颜色选择器同步当前值,避免下次打开原生选择器时显示旧颜色 */ const pInput = panel.querySelector('#vbp-color'); if (pInput && /^#[0-9a-f]{6}$/i.test(bufferColor)) pInput.value = bufferColor; } if (settingsModal) { const sdot = settingsModal.querySelector('.vbp-color-dot'); if (sdot) sdot.style.background = bufferColor; const scolorInput = settingsModal.querySelector('#vbp-color-s'); if (scolorInput && /^#[0-9a-f]{6}$/i.test(bufferColor)) scolorInput.value = bufferColor; const scode = settingsModal.querySelector('#vbp-color-code'); if (scode) scode.textContent = bufferColor; } } /* ============================================================ * 9. 各引擎应用 * ============================================================ */ function applyDash(player, force) { if (!player || typeof player.updateSettings !== 'function') return false; const lv = getActiveVideo(); if (lv && isLiveStream(lv)) { dashPlayer = player; currentEngine = 'dashjs'; return true; } const t = Governor.currentTarget; if (!force && dashPlayer === player && dashAppliedTarget === t) { currentEngine = 'dashjs'; return true; } try { player.updateSettings({ streaming: { buffer: { bufferTimeDefault: t, stableBufferTime: t, bufferTimeAtTopQuality: Math.max(t, 30) }}}); dashPlayer = player; dashAppliedTarget = t; currentEngine = 'dashjs'; return true; } catch (_) { return false; } } function findDash() { if (!PAGE.dashjs) return null; for (const c of [PAGE.player, PAGE.dashPlayer]) { if (c && typeof c.updateSettings === 'function') return c; if (c?.dash && typeof c.dash.updateSettings === 'function') return c.dash; } for (const v of document.querySelectorAll('video')) { if (v._dashjs_player && typeof v._dashjs_player.updateSettings === 'function') return v._dashjs_player; } const mp = PAGE.dashjs.MediaPlayer; if (mp?._instance && typeof mp._instance.updateSettings === 'function') return mp._instance; return null; } function pollDash() { const i = findDash(); if (i && applyDash(i)) dashHookDone = true; } function applyHls(h, force) { if (!h || !h.config) return false; const lv = getActiveVideo(); if (lv && isLiveStream(lv)) { hlsInstances.add(h); if (!artHookDone) currentEngine = 'hls'; return true; } const t = Governor.currentTarget; if (force || !h.config.maxBufferLength || h.config.maxBufferLength < t) { h.config.maxBufferLength = t; } if (!h.config.maxMaxBufferLength || h.config.maxMaxBufferLength < t) { h.config.maxMaxBufferLength = t; } hlsInstances.add(h); PrefetchEngine.hijackLoader(h); if (!artHookDone) currentEngine = 'hls'; return true; } function pollHls() { const seen = new Set(); for (const v of document.querySelectorAll('video')) { for (const k of ['__hls', 'hls', '_hls']) { const i = v[k]; if (i && i.config && !seen.has(i)) { seen.add(i); applyHls(i); } } } if (PAGE.hls && PAGE.hls.config && !seen.has(PAGE.hls)) { seen.add(PAGE.hls); applyHls(PAGE.hls); } if (PAGE.Hls && PAGE.Hls.instances instanceof Map) { for (const i of PAGE.Hls.instances.values()) { if (i && i.config && !seen.has(i)) { seen.add(i); applyHls(i); } } } if (hlsInstances.size > 0) hlsHookDone = true; } function applyShaka(p, includeColor, force) { if (!p || typeof p.configure !== 'function') return false; const lv = getActiveVideo(); if (lv && isLiveStream(lv)) { shakaPlayer = p; currentEngine = 'shaka'; return true; } const t = Governor.currentTarget; let cur = null; try { cur = p.getConfiguration ? p.getConfiguration() : null; } catch (_) {} const curGoal = cur?.streaming?.bufferingGoal; const curColor = cur?.ui?.seekBarColors?.buffered; const needGoal = !!force || curGoal !== t; const needColor = !!includeColor && (!!force || curColor !== bufferColor); if (!needGoal && !needColor) { shakaPlayer = p; currentEngine = 'shaka'; return true; } const cfg = {}; if (needGoal) cfg.streaming = { bufferingGoal: t, rebufferingGoal: Math.min(t, 30) }; if (needColor) { cfg.ui = { seekBarColors: Object.assign({}, cur?.ui?.seekBarColors, { buffered: bufferColor }) }; } try { p.configure(cfg); shakaPlayer = p; currentEngine = 'shaka'; return true; } catch (_) { return false; } } function pollShaka() { if (!PAGE.shaka?.Player) return; let i = null; if (PAGE.player && typeof PAGE.player.configure === 'function' && typeof PAGE.player.getConfiguration === 'function') i = PAGE.player; if (!i) { for (const v of document.querySelectorAll('video')) { if (v.shakaPlayer && typeof v.shakaPlayer.configure === 'function') { i = v.shakaPlayer; break; } } } if (!i && PAGE.shaka.Player._instance && typeof PAGE.shaka.Player._instance.configure === 'function') i = PAGE.shaka.Player._instance; if (i && applyShaka(i, false)) shakaHookDone = true; } function pollVideoJs() { const vjs = PAGE.videojs; if (!vjs || typeof vjs !== 'function' || !vjs.Vhs) return; const lv = getActiveVideo(); if (lv && isLiveStream(lv)) { videoJsApplied = true; currentEngine = 'videojs'; return; } const t = Governor.currentTarget; try { /* 无条件同步为目标值:仅"只增"会保留站点更大的配置,导致实际缓冲超出上限 */ vjs.Vhs.GOAL_BUFFER_LENGTH = t; vjs.Vhs.MAX_GOAL_BUFFER_LENGTH = t; vjs.Vhs.OVERRIDE_NATIVE = true; videoJsApplied = true; currentEngine = 'videojs'; } catch (_) {} } function applyXg(p, force) { if (!p || typeof p.setConfig !== 'function') return false; const lv = getActiveVideo(); if (lv && isLiveStream(lv)) { xgPlayer = p; currentEngine = 'xgplayer'; return true; } const t = Governor.currentTarget; if (!force && xgPlayer === p && xgAppliedTarget === t) { currentEngine = 'xgplayer'; return true; } try { p.setConfig({ mp4plugin: { maxBufferLength: t } }); p.setConfig({ hls: { preloadTime: t } }); p.setConfig({ flv: { preloadTime: t } }); p.setConfig({ dash: { maxBufferLength: t } }); xgPlayer = p; xgAppliedTarget = t; currentEngine = 'xgplayer'; return true; } catch (_) { return false; } } function findXg() { if (PAGE.player && typeof PAGE.player.setConfig === 'function') return PAGE.player; for (const v of document.querySelectorAll('video')) { for (const k of ['_xgPlayer', 'xgPlayer', 'player']) { if (v[k] && typeof v[k].setConfig === 'function') return v[k]; } } if (PAGE.xgplayer?._instance && typeof PAGE.xgplayer._instance.setConfig === 'function') { return PAGE.xgplayer._instance; } return null; } function pollXg() { const i = findXg(); if (i && applyXg(i)) xgHookDone = true; } function hookFlvMpegts() { if (PAGE.flvjs && typeof PAGE.flvjs.createPlayer === 'function' && !flvHooked) { const orig = PAGE.flvjs.createPlayer; PAGE.flvjs.createPlayer = function (ds, cfg) { cfg = cfg || {}; const v = getActiveVideo(); const isLive = v && isLiveStream(v); if (cfg.enableStashBuffer === undefined && !isLive) cfg.enableStashBuffer = true; flvHooked = true; if (!artHookDone) currentEngine = 'flv'; return orig.call(this, ds, cfg); }; } if (PAGE.mpegts && typeof PAGE.mpegts.createPlayer === 'function' && !mpegtsHooked) { const orig = PAGE.mpegts.createPlayer; PAGE.mpegts.createPlayer = function (ds, cfg) { cfg = cfg || {}; const v = getActiveVideo(); const isLive = v && isLiveStream(v); if (cfg.enableStashBuffer === undefined && !isLive) cfg.enableStashBuffer = true; mpegtsHooked = true; if (!artHookDone) currentEngine = 'flv'; return orig.call(this, ds, cfg); }; } } const processed = new WeakSet(); function scanVideos() { document.querySelectorAll('video').forEach(v => { if (processed.has(v)) return; processed.add(v); try { v.preload = 'auto'; } catch (_) {} setupStallWatch(v); if (!v._vbpProgListen) { v._vbpProgListen = true; v.addEventListener('timeupdate', updateProgressBar); v.addEventListener('progress', updateProgressBar); v.addEventListener('durationchange', () => { invalidateVideoRectCache(); updateProgressBar(); }); /* ★ 修复 2:换源检测 */ v.addEventListener('loadstart', () => { invalidateVideoRectCache(); hideTimeTip(); updateProgressBar(); try { const cur = v.currentSrc || v.src; if (v._vbpLastSrc && cur && v._vbpLastSrc !== cur) { resetSiteProbeCache(); Governor.siteCeiling = 0; cachedDuration = null; Governor.reset(v); } v._vbpLastSrc = cur; } catch (_) {} }); } }); } function settleEngine() { if (artHookDone) return; if (dashHookDone || hlsHookDone || shakaHookDone || xgHookDone || videoJsApplied || flvHooked || mpegtsHooked) return; if (getActiveVideo()) currentEngine = 'native'; } function findPlayerContainer(video) { if (!video) return null; let el = video.parentElement; const vr = video.getBoundingClientRect(); for (let i = 0; i < 6 && el && el !== document.body; i++) { const cs = getComputedStyle(el); const er = el.getBoundingClientRect(); if (cs.position !== 'static' && er.width >= vr.width * 0.9 && er.height >= vr.height * 0.9) return el; el = el.parentElement; } return video.parentElement; } /* ============================================================ * 10. 位置记忆 * ============================================================ */ function loadSavedPos() { try { const raw = GM_getValue(POS_KEY, ''); if (!raw) return null; const p = typeof raw === 'string' ? JSON.parse(raw) : raw; if (p && typeof p.leftPct === 'number' && typeof p.bottomPct === 'number' && isFinite(p.leftPct) && isFinite(p.bottomPct)) { return { leftPct: Math.max(0, Math.min(95, p.leftPct)), bottomPct: Math.max(0, Math.min(95, p.bottomPct)) }; } } catch (_) {} return null; } function savePos(pos) { try { GM_setValue(POS_KEY, JSON.stringify(pos)); } catch (_) {} } function loadFloatPos() { try { const raw = GM_getValue(FLOAT_POS_KEY, ''); if (!raw) return null; const p = typeof raw === 'string' ? JSON.parse(raw) : raw; if (p && typeof p.left === 'number' && typeof p.top === 'number') return p; } catch (_) {} return null; } function saveFloatPos(left, top) { try { GM_setValue(FLOAT_POS_KEY, JSON.stringify({ left, top })); } catch (_) {} } /* ============================================================ * 11. 底部进度条 * ============================================================ */ function buildBottomBarDOM() { if (bottomBar) return; bottomBar = document.createElement('div'); bottomBar.id = 'vbp-bottom-bar'; bottomBar.style.cssText = ` position:absolute;left:0;right:0;bottom:0;height:26px; z-index:2147483646;display:none;cursor:pointer; opacity:0;transition:opacity .25s;pointer-events:none;touch-action:none;`; bottomBar.innerHTML = `