// ==UserScript==
// @name 视频缓冲增强
// @namespace https://scriptcat.org/
// @version 2026.12.4
// @description 网页视频智能缓冲增强:自动适配 Hls.js / dash.js / shaka-player / video.js / xgplayer / flv.js / mpegts.js / ArtPlayer 等播放器,按视频时长与网站实际缓冲能力动态调整缓冲目标并实时变动(无硬性封顶);HLS.js 并发预取、在途请求合并、内存缓存,显著减少播放卡顿;悬浮面板实时显示缓冲秒数 / 网速 / 引擎类型,缓冲条颜色可自定义,底部进度条自动跟随网站主题色;全屏与网页全屏时鼠标静止 3 秒自动接管控制栏与进度条;直播流智能保护不被误改,无视频页面不注入,SPA 换源安全重置;检测到站点自带底部进度条时自动美化原条、不再叠加双进度条;网速测量覆盖无扩展名媒体分片并支持码率估算,修复网速长期显示为 0
// @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);
/* ★ 标记是否成功识别到站点主题色:未识别时不强制覆盖原条"已播放"层颜色 */
document.documentElement.classList.toggle('vbp-has-site-color', !!color);
} 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 实时网速追踪
* ★ 修复"网速一直显示 0":
* 1) XHR / fetch 捕获范围扩大 —— 无扩展名的媒体分片按 Content-Type 识别;
* 2) 显示平滑 —— 2s 窗口无样本时回退 10s 平滑窗口,突发式下载不再频繁归零;
* 3) 码率估算兜底 —— 长期统计"下载字节 / 缓冲新增媒体秒数"得到视频码率,
* 测量盲区(Worker 加载、原生直链等)以 ≈估值 或 —(无法测量)呈现,
* 不再显示误导性的 0
* ============================================================ */
const MEDIA_CT_RE = /(video\/|audio\/|mpegurl|octet-stream|mp2t|mp4|matroska|dash\+xml|segment)/i;
const NetSpeed = {
samples: [],
total: 0,
addBytes(n) {
if (!n || n <= 0) return;
const now = performance.now();
this.samples.push({ t: now, b: n });
this.total += n;
if (this.samples.length > 600) this.samples = this.samples.slice(-400);
},
/* 按窗口统计平均速率;不在查询中剪裁样本(统一由 prune 处理,
避免 2s 窗口查询破坏 10s 平滑窗口的数据) */
avgSince(maxAgeMs) {
const now = performance.now();
const cutoff = now - maxAgeMs;
let sum = 0, count = 0, firstT = 0;
for (const s of this.samples) {
if (s.t < cutoff) continue;
if (count === 0) firstT = s.t;
sum += s.b; count++;
}
if (count === 0) return 0;
const span = Math.max(0.5, (now - firstT) / 1000);
return sum / span;
},
prune() {
const cutoff = performance.now() - 12000;
let i = 0;
while (i < this.samples.length && this.samples[i].t < cutoff) i++;
if (i > 0) this.samples = this.samples.slice(i);
},
current() {
this.prune();
return this.avgSince(2000);
}
};
/* 码率估算器:下载字节 / 缓冲新增媒体秒 的长期比值(EMA,单位 bytes/媒体秒)。
稳态播放时下载速率≈码率,可在无网络样本时给出 ≈估值;
seek / 换源会使字节与媒体秒错位对应,立即重置防污染 */
const SpeedEstimator = {
bitrate: 0,
accBytes: 0,
accMedia: 0,
lastBufEnd: -1,
lastTotal: 0,
lastVideo: null,
reset(video) {
this.bitrate = 0; this.accBytes = 0; this.accMedia = 0;
this.lastBufEnd = -1;
this.lastTotal = NetSpeed.total;
this.lastVideo = video || null;
},
onSeek() {
this.accBytes = 0; this.accMedia = 0;
this.lastBufEnd = -1;
this.lastTotal = NetSpeed.total;
},
tick(video) {
if (!video) return this.bitrate;
if (this.lastVideo !== video) this.reset(video);
const total = NetSpeed.total;
const dBytes = total - this.lastTotal;
this.lastTotal = total;
let bufEnd = -1;
try {
if (video.buffered.length > 0) {
bufEnd = video.buffered.end(video.buffered.length - 1);
}
} catch (_) {}
if (bufEnd < 0) { this.lastBufEnd = -1; return this.bitrate; }
if (this.lastBufEnd >= 0) {
const dMedia = bufEnd - this.lastBufEnd;
if (dMedia > 0.01 && dMedia < 45 && dBytes > 0 && dBytes < 64 * 1024 * 1024) {
this.accBytes += dBytes;
this.accMedia += dMedia;
if (this.accMedia >= 8 && this.accBytes > 0) {
const inst = this.accBytes / this.accMedia;
if (isFinite(inst) && inst > 0) {
this.bitrate = this.bitrate > 0
? this.bitrate * 0.6 + inst * 0.4 : inst;
}
this.accBytes = 0; this.accMedia = 0;
}
} else if (dMedia < -0.01) {
/* 缓冲回退(seek / 换源):丢弃累计窗口防污染 */
this.accBytes = 0; this.accMedia = 0;
}
}
this.lastBufEnd = bufEnd;
return this.bitrate;
}
};
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;
let lastLoaded = 0;
let decided = false;
let isMedia = false;
/* ★ 修复:除 arraybuffer / blob / 媒体扩展名外,
按 Content-Type 识别无扩展名媒体分片(裸地址 CDN 常见),
首个 progress 事件时决定一次,后续事件零开销 */
const decide = () => {
if (decided) return isMedia;
try {
if (this.responseType === 'arraybuffer' ||
this.responseType === 'blob') {
decided = true; isMedia = true;
return true;
}
if (isMediaUrl(this._vbpUrl)) {
decided = true; isMedia = true;
return true;
}
if (this.readyState >= 2) {
const ct = String(this.getResponseHeader('Content-Type') || '');
decided = true;
isMedia = MEDIA_CT_RE.test(ct);
return isMedia;
}
} catch (_) {}
return false;
};
this.addEventListener('progress', (e) => {
try {
if (!decide()) return;
const delta = e.loaded - lastLoaded;
if (delta > 0) {
NetSpeed.addBytes(delta);
lastLoaded = e.loaded;
}
} catch (_) {}
});
}
} 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);
/* 本回调先于站点回调注册:站点开始消费 body 前完成判定与 clone;
★ 修复:非媒体扩展名的响应按 Content-Type 复核,
覆盖无扩展名分片等测量盲区 */
promise.then((resp) => {
try {
if (!resp) return;
let media = isMediaUrl(url);
if (!media && resp.headers && typeof resp.headers.get === 'function') {
try {
media = MEDIA_CT_RE.test(String(resp.headers.get('content-type') || ''));
} catch (_) {}
}
if (!media) return;
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',
'.bpx-player-control-top', '.bpx-player-ctrl-progress',
'.bpx-player-progress', '.bpx-player-progress-area',
'.bpx-player-progress-wrap', '.bpx-player-shadow-progress-area',
'.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*="ctrl-progress" i]',
'[class*="shadow-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(); });
/* ★ 码率估算:seek 会使下载字节与缓冲增长错位,重置估算窗口 */
v.addEventListener('seeking', () => { SpeedEstimator.onSeek(); });
/* ★ 修复 2:换源检测 */
v.addEventListener('loadstart', () => {
invalidateVideoRectCache();
hideTimeTip();
updateProgressBar();
SpeedEstimator.onSeek();
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 = `
`;
let pid = null;
let lastClick = 0;
let lastClickX = -1, lastClickY = -1;
const calcPct = (cx) => {
const r = bottomBar.getBoundingClientRect();
return r.width > 0 ? Math.max(0, Math.min(1, (cx - r.left) / r.width)) : 0;
};
const seekTo = (pct) => {
const v = getActiveVideo();
if (!v || !isFinite(v.duration) || v.duration <= 0) return;
try { v.currentTime = pct * v.duration; } catch (_) {}
};
bottomBar.addEventListener('pointerenter', (e) => {
if (e.pointerType === 'touch') return;
const inner = bottomBar.querySelector('.vbp-bb-track-inner');
if (inner) inner.style.height = '6px';
updateTimeTip(e.clientX, false);
});
bottomBar.addEventListener('pointerleave', () => {
if (pid !== null) return;
const inner = bottomBar.querySelector('.vbp-bb-track-inner');
if (inner) inner.style.height = '4px';
hideTimeTip();
});
bottomBar.addEventListener('pointermove', (e) => {
lastUserActivityTime = Date.now();
if (pid !== null && e.pointerId === pid) {
seekTo(calcPct(e.clientX));
updateTimeTip(e.clientX, true);
e.stopPropagation();
} else if (e.pointerType !== 'touch') {
updateTimeTip(e.clientX, false);
}
});
bottomBar.addEventListener('pointerdown', (e) => {
e.stopPropagation();
lastUserActivityTime = Date.now();
const now = Date.now();
/* 双击进全屏要求两次点击位置接近,避免连续 seek 不同位置被误判为双击 */
const nearLast = lastClickX >= 0 &&
Math.hypot(e.clientX - lastClickX, e.clientY - lastClickY) < 24;
if (now - lastClick < 300 && pid === null && nearLast) {
lastClick = 0; lastClickX = -1; lastClickY = -1;
toggleFullscreen(); e.preventDefault(); return;
}
lastClick = now;
lastClickX = e.clientX; lastClickY = e.clientY;
pid = e.pointerId; progressDragging = true;
try { bottomBar.setPointerCapture(e.pointerId); } catch (_) {}
seekTo(calcPct(e.clientX));
updateTimeTip(e.clientX, true);
e.preventDefault();
});
bottomBar.addEventListener('pointerup', (e) => {
if (e.pointerId !== pid) return;
pid = null; progressDragging = false;
try { bottomBar.releasePointerCapture(e.pointerId); } catch (_) {}
lastUserActivityTime = Date.now();
updateBottomBarVisibility();
if (e.pointerType === 'touch') hideTimeTip();
e.stopPropagation();
});
bottomBar.addEventListener('pointercancel', (e) => {
if (e.pointerId !== pid) return;
pid = null; progressDragging = false;
try { bottomBar.releasePointerCapture(e.pointerId); } catch (_) {}
hideTimeTip();
});
['click', 'dblclick', 'contextmenu', 'touchstart', 'touchend', 'touchmove']
.forEach(t => bottomBar.addEventListener(t, (e) => e.stopPropagation(), false));
}
function updateTimeTip(clientX, isDragging) {
if (!bottomBar) return;
const tip = bottomBar.querySelector('.vbp-bb-tip');
const v = getActiveVideo();
if (!tip || !v) return;
let dur = 0;
try { dur = v.duration; } catch (_) {}
if (!isFinite(dur) || dur <= 0) { tip.style.display = 'none'; return; }
const r = bottomBar.getBoundingClientRect();
if (r.width <= 0) return;
const pct = Math.max(0, Math.min(1, (clientX - r.left) / r.width));
const t = pct * dur;
tip.textContent = `${fmtTime(t)} / ${fmtTime(dur)}` + (isDragging ? '' : ` · 当前 ${fmtTime(v.currentTime)}`);
tip.style.left = Math.max(15, Math.min(85, pct * 100)) + '%';
tip.style.display = 'block';
tip.style.opacity = '1';
}
function hideTimeTip() {
if (!bottomBar) return;
const tip = bottomBar.querySelector('.vbp-bb-tip');
if (!tip) return;
tip.style.opacity = '0';
setTimeout(() => { if (tip.style.opacity === '0') tip.style.display = 'none'; }, 150);
}
function shouldShowBottomBar() {
const v = getActiveVideo();
if (!v || dragPaused) return false;
if (progressDragging) return true;
if (!v.currentSrc && !v.src) return false;
let dur = 0;
try { dur = v.duration; } catch (_) {}
if (!isFinite(dur) || dur <= 0) return false;
if (isEffectivelyFullscreen()) {
if (isNativeVideoFullscreen(v)) return false;
if (!hideCtrlInFs) return false;
if (isLikelyLive(v)) return false;
return isFsIdle();
}
if (v.paused) return false;
/* ★ 站点自带进度条当前可见时不再叠加自制条,避免双进度条(原条已美化);
原条淡出 / 滑出(hover 显隐条)时自制条照常接管 */
if (isSiteBarVisibleNow()) return false;
/* ★ 双保险:站点条可能刚出现 / 刚恢复显示而周期扫描尚未覆盖,
显示自制条前强制即时复扫一次,消除短暂的双条窗口 */
forceSiteBarScan();
if (isSiteBarVisibleNow()) return false;
return !mouseInVideoArea;
}
function updateBottomBarVisibility() {
if (!bottomBar || !bottomBar.parentElement) return;
if (shouldShowBottomBar()) {
if (bottomBarHideTimer) { clearTimeout(bottomBarHideTimer); bottomBarHideTimer = 0; }
if (bottomBar.style.display === 'none') {
updateSiteProgressColorIfNeeded();
updateProgressBar();
bottomBar.style.display = 'block';
bottomBar.style.pointerEvents = 'auto';
requestAnimationFrame(() => { if (bottomBar) bottomBar.style.opacity = '1'; });
} else if (bottomBar.style.opacity !== '1') {
bottomBar.style.opacity = '1'; bottomBar.style.pointerEvents = 'auto';
}
} else {
bottomBar.style.opacity = '0'; bottomBar.style.pointerEvents = 'none';
if (bottomBarHideTimer) clearTimeout(bottomBarHideTimer);
bottomBarHideTimer = setTimeout(() => {
bottomBarHideTimer = 0;
if (bottomBar && !shouldShowBottomBar()) bottomBar.style.display = 'none';
}, 300);
}
}
/* 底部条百分比缓存:仅在变化时写入样式,减少高频无谓重绘 */
let lastPlayedPct = -1;
let lastBufPct = -1;
let cachedPlayedEl = null;
let cachedBufEl = null;
function updateProgressBar() {
if (!bottomBar) return;
if (bottomBar.style.display === 'none' && bottomBar.style.opacity === '0') return;
const v = getActiveVideo();
if (!v) return;
let dur = 0, cur = 0, maxBuf = 0;
try {
dur = v.duration; cur = v.currentTime;
if (v.buffered.length > 0) maxBuf = v.buffered.end(v.buffered.length - 1);
} catch (_) {}
if (!isFinite(dur) || dur <= 0) return;
if (progressDragging) return;
const curPct = Math.min(100, cur / dur * 100);
const bufPct = Math.min(100, maxBuf / dur * 100);
const played = cachedPlayedEl || (cachedPlayedEl = bottomBar.querySelector('.vbp-bb-played'));
const buf = cachedBufEl || (cachedBufEl = bottomBar.querySelector('.vbp-bb-buffer'));
if (played && Math.abs(curPct - lastPlayedPct) > 0.1) {
played.style.width = curPct + '%';
lastPlayedPct = curPct;
}
if (buf && Math.abs(bufPct - lastBufPct) > 0.1) {
buf.style.width = bufPct + '%';
lastBufPct = bufPct;
}
}
/* ============================================================
* 11.5 站点自带进度条检测与美化
* ★ 修复"双进度条":播放器自带底部进度条时不再叠加自制进度条,
* 改为在原条上做圆角 / 主题色渐变 / 柔光等美化;
* 全屏闲置时仍按原逻辑隐藏站点控制栏并由自制条接管,行为不变;
* hover 显隐的原条淡出/滑出时自制条可正常接管,不会"无条可看"
* ============================================================ */
const SITE_BAR_SELECTORS = [
/* 主流播放器精确选择器(命中后取最外层候选,避免美化到内部分层) */
'.vjs-progress-control', '.vjs-progress-holder',
'.xgplayer-progress', '.xgplayer-progress-slider',
'.dplayer-bar-wrap',
'.art-progress', '.art-control-progress',
'.ytp-progress-bar-container', '.ytp-progress-bar',
/* B站 bpx 播放器:控制栏内交互条 + 控制栏隐藏后仍常驻的"阴影细条",
两层都要命中,否则鼠标移开后常驻细条会与自制条形成双进度条 */
'.bpx-player-progress', '.bpx-player-progress-wrap',
'.bpx-player-progress-area', '.bpx-player-progress-bar',
'.bpx-player-progress-schedule-wrap',
'.bpx-player-ctrl-progress', '.bpx-player-shadow-progress-area',
'.prism-progress', '.prism-progress-control',
'.txp-progress', '.txp-progress-bar',
'.iqp-progressbar', '.iqp-progress',
'.shaka-range-container', '.shaka-seek-bar',
'.jw-slider-time', '.jw-progress',
'.plyr__progress', '.plyr__progress__container',
'.fp-progress', '.fp-slider',
/* 通用模糊(配合几何校验排除页面级误匹配) */
'[class*="player-progress" i]', '[class*="video-progress" i]',
'[class*="ctrl-progress" i]', '[class*="shadow-progress" i]',
'[class*="progress" i][class*="bar" i]',
'[class*="progress" i][class*="slider" i]',
'[class*="progress" i][class*="wrap" i]',
'[class*="progress" i][class*="track" i]',
'[class*="seek" i][class*="bar" i]',
'[class*="seekbar" i]', '[class*="scrubber" i]',
'[class*="time-bar" i]', '[class*="timebar" i]',
'[class*="timeline" i]'
];
const SITE_BAR_CHECK_INTERVAL = 2000;
let siteBarEls = []; /* 命中的站点进度条:可能多层(常驻阴影细条 + 控制栏内交互条) */
let siteBarCheckAt = 0; /* 上次周期扫描时间 */
let siteBarForceAt = 0; /* 上次强制即时扫描时间(显示自制条前的兜底) */
let siteBarHadAny = false;
function injectSiteBarCSS() {
let el = document.getElementById('vbp-site-bar-style');
if (el) return;
const host = document.head || document.documentElement;
if (!host) return;
el = document.createElement('style');
el.id = 'vbp-site-bar-style';
el.textContent = `
/* ★ 站点自带进度条美化:仅作用于脚本识别并标记的原生进度条 */
.vbp-bar-beautify { border-radius: 999px !important; }
.vbp-bar-beautify > * { border-radius: inherit !important; }
.vbp-bar-beautify [class*="played" i],
.vbp-bar-beautify [class*="play-progress" i],
.vbp-bar-beautify [class*="loaded" i],
.vbp-bar-beautify [class*="load-progress" i],
.vbp-bar-beautify [class*="buffer" i],
.vbp-bar-beautify [class*="cache" i],
.vbp-bar-beautify [class*="current" i],
.vbp-bar-beautify [class*="schedule" i] { border-radius: 999px !important; }
/* 已播放层:站点主题色渐变 + 柔光(仅在成功识别到主题色时启用,避免覆盖站点原色) */
html.vbp-has-site-color .vbp-bar-beautify [class*="played" i],
html.vbp-has-site-color .vbp-bar-beautify [class*="play-progress" i],
html.vbp-has-site-color .vbp-bar-beautify [class*="current" i] {
background-image: linear-gradient(90deg,
color-mix(in srgb, var(--vbp-site-played-color, #4a90e2) 78%, #ffffff),
var(--vbp-site-played-color, #4a90e2) 85%) !important;
box-shadow: 0 0 6px -1px var(--vbp-site-played-color, #4a90e2) !important;
}
/* 拖动滑块:立体感描边 */
.vbp-bar-beautify [class*="knob" i],
.vbp-bar-beautify [class*="handle" i],
.vbp-bar-beautify [class*="cursor" i],
.vbp-bar-beautify [class*="dot" i] {
border-radius: 50% !important;
box-shadow: 0 1px 4px rgba(0,0,0,.35), 0 0 0 1px rgba(255,255,255,.25) !important;
}`;
host.appendChild(el);
}
/* 元素自身及可见祖先链是否处于渲染状态(display:none / 全透明 / 自身 visibility)。
祖先 visibility:hidden 不算隐藏 —— 子元素可用 visibility:visible 刻意保持显示
(典型:YouTube 控制栏淡出后底部细进度线仍然保留) */
function isElRendered(el) {
try {
let node = el;
for (let i = 0; node && i < 6; i++) {
const cs = getComputedStyle(node);
if (cs.display === 'none') return false;
const o = parseFloat(cs.opacity);
if (!isNaN(o) && o <= 0.05) return false;
if (node === el && cs.visibility === 'hidden') return false;
if (node === document.body || node === document.documentElement) break;
node = node.parentElement;
}
} catch (_) { return false; }
return true;
}
/* 候选校验:位于播放器容器内 + 紧贴视频底部 + 宽度占视频一半以上。
注意:不做 display/visibility 判定 —— rect>0 已排除 display:none 链;
纯透明/visibility 隐藏的元素保留 rect,照样标记,
显隐状态统一交给 isSiteBarVisibleNow 动态判断,避免显隐切换期漏标 */
function isSiteBarCandidate(el, scopeRoot, vr) {
if (!el || el.id === 'vbp-bottom-bar') return false;
if (bottomBar && bottomBar.contains(el)) return false;
if (panel && panel.contains(el)) return false;
if (!scopeRoot || !scopeRoot.contains(el)) return false;
if (el.contains(scopeRoot)) return false;
let r;
try { r = el.getBoundingClientRect(); } catch (_) { return false; }
if (r.width <= 0 || r.height <= 0) return false;
if (r.height > 44) return false; /* 过高多为控制栏容器而非进度条 */
if (r.width < vr.width * 0.5) return false; /* 宽度应占视频一半以上 */
if (r.right < vr.left + vr.width * 0.1) return false;
if (r.left > vr.right - vr.width * 0.1) return false;
/* 位于视频下半区、紧贴视频底部(进度条可略低于视频下缘) */
const midY = r.top + r.height / 2;
if (midY < vr.top + vr.height * 0.55) return false;
if (midY > vr.bottom + 70) return false;
return true;
}
function applySiteBarBeautify(el) {
try {
if (el && !el.classList.contains('vbp-bar-beautify')) el.classList.add('vbp-bar-beautify');
} catch (_) {}
}
function setSiteBars(els) {
const list = (els || []).filter(Boolean);
const same = siteBarEls.length === list.length &&
siteBarEls.every((el, i) => el === list[i]);
if (same) return;
for (const el of siteBarEls) {
try { el.classList.remove('vbp-bar-beautify'); } catch (_) {}
}
siteBarEls = list;
if (siteBarEls.length) {
for (const el of siteBarEls) applySiteBarBeautify(el);
if (!siteBarHadAny) {
siteBarHadAny = true;
log('检测到站点自带底部进度条:停用自制进度条,改为原条美化');
}
} else {
siteBarHadAny = false;
}
}
/* 站点条当前是否实际可见(控制栏淡出 / 滑出时按隐藏处理,
任一命中层可见即视为可见) */
function isSiteBarVisibleNow() {
if (!siteBarEls.length) return false;
let vr = null;
let vrReady = false;
for (const el of siteBarEls) {
if (!document.contains(el)) continue;
if (!isElRendered(el)) continue;
let r;
try { r = el.getBoundingClientRect(); } catch (_) { continue; }
if (r.width <= 0 || r.height <= 0) continue;
if (!vrReady) {
const v = getActiveVideo();
if (!v) return false;
try { vr = v.getBoundingClientRect(); } catch (_) { return false; }
vrReady = true;
}
if (r.top > vr.bottom + 110) continue; /* 随控制栏整体滑出视频区域 */
return true;
}
return false;
}
/* 全量扫描一次站点进度条(无节流,供周期刷新与显示前兜底共用) */
function scanSiteBars() {
const v = getActiveVideo();
if (!v) { setSiteBars([]); return; }
let scopeRoot = null;
let vr = null;
try {
const container = findPlayerContainer(v);
if (container) {
scopeRoot = container;
/* 搜索范围上浮两级:兼容控制栏 / 进度条位于播放器根节点之外的结构 */
for (let i = 0; i < 2; i++) {
const p = scopeRoot.parentElement;
if (!p || p === document.body || p === document.documentElement) break;
scopeRoot = p;
}
}
vr = v.getBoundingClientRect();
} catch (_) {}
if (!scopeRoot || !vr || vr.width <= 0 || vr.height <= 0) { setSiteBars([]); return; }
const candidates = [];
for (const sel of SITE_BAR_SELECTORS) {
let els = null;
try { els = scopeRoot.querySelectorAll(sel); } catch (_) { continue; }
for (const el of els) {
if (isSiteBarCandidate(el, scopeRoot, vr)) {
candidates.push(el);
if (candidates.length >= 16) break;
}
}
if (candidates.length >= 16) break;
}
if (candidates.length === 0) { setSiteBars([]); return; }
/* 取最外层候选(不被其它候选包含):
B站等双层结构会得到"常驻阴影细条 + 控制栏内交互条"多个根,全部标记 */
const roots = [];
for (const el of candidates) {
if (candidates.some(o => o !== el && o.contains(el))) continue;
roots.push(el);
if (roots.length >= 4) break;
}
setSiteBars(roots);
}
/* 周期刷新(2s 节流) */
function refreshSiteProgressBar() {
const now = Date.now();
const v = getActiveVideo();
if (!v) { setSiteBars([]); siteBarCheckAt = now; return; }
if (now - siteBarCheckAt < SITE_BAR_CHECK_INTERVAL) return;
siteBarCheckAt = now;
scanSiteBars();
}
/* 显示自制条前的兜底复扫:站点条可能刚出现 / 刚恢复显示而周期扫描未覆盖,
彻底消除短暂的双条窗口。已有命中时更积极(状态切换期),从未命中时低频兜底 */
function forceSiteBarScan() {
const now = Date.now();
const gap = siteBarEls.length > 0 ? 600 : 5000;
if (now - siteBarForceAt < gap) return;
siteBarForceAt = now;
scanSiteBars();
}
/* ============================================================
* 12. 用户活动追踪
* ============================================================ */
function setupUserActivityTracking() {
let lastThrottle = 0;
document.addEventListener('mousemove', (e) => {
lastUserActivityTime = Date.now();
const v = getActiveVideo();
if (!(v && isLikelyLive(v)) &&
isEffectivelyFullscreen() &&
document.documentElement.classList.contains('vbp-fs-hide-ctrl')) {
document.documentElement.classList.remove('vbp-fs-hide-ctrl');
syncNativeControls(getActiveVideo(), false);
updateBottomBarVisibility();
}
const now = Date.now();
if (now - lastThrottle < 50) return;
lastThrottle = now;
revealMini();
/* ★ 全屏 / 网页全屏:鼠标活动立即隐藏自制进度条,
消除站点控制栏重新出现后的短暂双条 */
if (isEffectivelyFullscreen()) updateBottomBarVisibility();
const rect = getVideoRectCached();
if (!rect || rect.width <= 0) return;
const inVideo = e.clientX >= rect.left && e.clientX <= rect.right &&
e.clientY >= rect.top && e.clientY <= rect.bottom;
if (inVideo) {
if (mouseLeaveTimer) { clearTimeout(mouseLeaveTimer); mouseLeaveTimer = 0; }
if (!mouseInVideoArea) {
mouseInVideoArea = true;
updateBottomBarVisibility();
}
} else if (mouseInVideoArea && !mouseLeaveTimer) {
mouseLeaveTimer = setTimeout(() => {
mouseLeaveTimer = 0; mouseInVideoArea = false; updateBottomBarVisibility();
}, 1500);
}
}, { passive: true });
document.addEventListener('touchstart', () => {
lastUserActivityTime = Date.now();
revealMini();
if (isEffectivelyFullscreen()) updateBottomBarVisibility();
const v = getActiveVideo();
if (!(v && isLikelyLive(v)) &&
isEffectivelyFullscreen() &&
document.documentElement.classList.contains('vbp-fs-hide-ctrl')) {
document.documentElement.classList.remove('vbp-fs-hide-ctrl');
syncNativeControls(getActiveVideo(), false);
updateBottomBarVisibility();
}
}, { passive: true });
document.addEventListener('keydown', () => {
lastUserActivityTime = Date.now();
revealMini();
}, { passive: true });
document.addEventListener('wheel', () => {
lastUserActivityTime = Date.now();
revealMini();
}, { passive: true });
/* 点击屏幕:capture 阶段先于面板自身的 stopPropagation,确保任何位置点击都能唤回最小化面板 */
document.addEventListener('pointerdown', () => {
lastUserActivityTime = Date.now();
revealMini();
}, { passive: true, capture: true });
document.addEventListener('mouseleave', () => {
mouseInVideoArea = false;
updateBottomBarVisibility();
});
window.addEventListener('scroll', invalidateVideoRectCache, { passive: true, capture: true });
window.addEventListener('resize', () => {
invalidateVideoRectCache();
if (!dragPaused) reposition();
updateBottomBarVisibility();
});
}
/* ============================================================
* 13. 全局 UI 样式
* ============================================================ */
function injectUIStyles() {
let el = document.getElementById('vbp-ui-styles');
if (el) return;
const host = document.head || document.documentElement;
if (!host) return;
el = document.createElement('style');
el.id = 'vbp-ui-styles';
el.textContent = `
#vbp-panel {
--vbp-bg: rgba(22,24,30,.82);
--vbp-bg-hover: rgba(28,31,38,.92);
--vbp-border: rgba(255,255,255,.09);
--vbp-text: #e5e7eb;
--vbp-text-dim: #9ca3af;
--vbp-text-mute: #6b7280;
--vbp-accent: #60a5fa;
--vbp-green: #4ade80;
--vbp-amber: #fbbf24;
--vbp-red: #f87171;
--vbp-cyan: #22d3ee;
z-index: 2147483647;
display: flex; flex-direction: column;
padding: 8px 10px 6px;
min-width: 148px; max-width: 168px;
background: var(--vbp-bg);
backdrop-filter: blur(18px) saturate(180%);
-webkit-backdrop-filter: blur(18px) saturate(180%);
border: 1px solid var(--vbp-border);
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,.4), 0 2px 6px rgba(0,0,0,.25),
inset 0 1px 0 rgba(255,255,255,.05);
font: 500 12px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif;
color: var(--vbp-text);
user-select: none;
cursor: grab;
touch-action: none;
opacity: .82;
transition: opacity .22s ease, background .22s ease;
box-sizing: border-box;
flex-shrink: 0;
letter-spacing: .01em;
}
#vbp-panel:hover { opacity: 1; background: var(--vbp-bg-hover); }
#vbp-panel:active { cursor: grabbing; }
#vbp-panel.is-collapsed { padding: 6px; min-width: 0; max-width: none; }
#vbp-panel.is-mini-hidden {
opacity: 0 !important;
pointer-events: none !important;
}
.vbp-toggle {
display: inline-flex; align-items: center; justify-content: center;
width: 24px; height: 24px; padding: 0;
background: transparent; border: 1px solid transparent; border-radius: 6px;
color: var(--vbp-accent); cursor: pointer; flex-shrink: 0;
font-family: inherit;
}
.vbp-toggle:hover { background: rgba(255,255,255,.06); border-color: rgba(255,255,255,.08); }
.vbp-inner { display: flex; flex-direction: column; gap: 5px; width: 100%; }
.vbp-stat-row {
display: flex; align-items: center; justify-content: space-between;
gap: 10px; min-width: 0;
}
.vbp-stat-label {
font-size: 10px; font-weight: 600; letter-spacing: .06em;
color: var(--vbp-text-mute); text-transform: uppercase;
flex-shrink: 0;
}
.vbp-stat-value {
font-size: 13px; font-weight: 600;
color: var(--vbp-text);
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#vbp-buf { color: var(--vbp-green); }
#vbp-target { color: var(--vbp-amber); }
#vbp-target.is-degraded { color: var(--vbp-red); }
#vbp-target.is-recovering { color: #fb923c; }
#vbp-speed { color: var(--vbp-cyan); }
#vbp-panel .vbp-footer {
display: flex; align-items: center; justify-content: space-between;
gap: 6px;
padding-top: 6px;
margin-top: 2px;
border-top: 1px solid rgba(255,255,255,.06);
}
.vbp-engine-badge {
font-size: 9px; font-weight: 700;
letter-spacing: .05em; text-transform: uppercase;
padding: 2px 5px; border-radius: 4px;
background: rgba(96,165,250,.15);
color: #93c5fd;
border: 1px solid rgba(96,165,250,.22);
white-space: nowrap;
}
.vbp-btns { display: flex; align-items: center; gap: 2px; }
.vbp-btn {
display: inline-flex; align-items: center; justify-content: center;
width: 22px; height: 22px; padding: 0;
border: 1px solid transparent; border-radius: 5px;
background: transparent; color: var(--vbp-text-dim);
cursor: pointer; flex-shrink: 0;
transition: background .15s, color .15s, border-color .15s;
font-family: inherit;
}
.vbp-btn:hover {
background: rgba(255,255,255,.06);
color: var(--vbp-text);
border-color: rgba(255,255,255,.08);
}
.vbp-btn:active { background: rgba(255,255,255,.09); }
.vbp-color-btn {
position: relative !important; display: inline-flex;
width: 22px !important; height: 22px !important; border-radius: 5px;
cursor: pointer; flex-shrink: 0 !important;
align-items: center; justify-content: center;
transition: background .15s;
overflow: hidden !important;
-webkit-tap-highlight-color: transparent;
}
.vbp-color-btn:hover,
.vbp-color-btn:focus-within { background: rgba(255,255,255,.06); }
/* ★ 修复:隐形取色 input 只有普通 opacity:0,站点全局 input 样式
(典型如 input:focus —— 取色确认后 input 恰好获得焦点)会把它强制
变成可见的原生色块;面板按钮内被 overflow 裁成竖条、设置行内则
铺满整行形成"长条色块遮盖文字"。
对策:ID 提升优先级 + 关键隐藏属性加 !important,保证任何情况下不可见 */
#vbp-panel .vbp-btns .vbp-color-btn input[type=color] {
position: absolute !important; inset: 0 !important;
opacity: 0 !important;
width: 100% !important; height: 100% !important;
max-width: 100% !important; max-height: 100% !important;
cursor: pointer;
border: 0 !important; padding: 0 !important; margin: 0 !important;
pointer-events: auto !important;
outline: none !important;
box-shadow: none !important;
-webkit-appearance: none !important;
appearance: none !important;
border-radius: inherit;
background: transparent !important;
-webkit-tap-highlight-color: transparent;
}
#vbp-panel .vbp-btns .vbp-color-btn input[type=color]:focus,
#vbp-panel .vbp-btns .vbp-color-btn input[type=color]:active,
#vbp-panel .vbp-btns .vbp-color-btn input[type=color]:focus-visible {
opacity: 0 !important;
outline: none !important;
box-shadow: none !important;
background: transparent !important;
}
/* 原生取色器内部色板兜底:即便极端站点样式穿透 opacity,也不显示色板边框 */
#vbp-panel .vbp-btns .vbp-color-btn input[type=color]::-webkit-color-swatch-wrapper { padding: 0 !important; margin: 0 !important; }
#vbp-panel .vbp-btns .vbp-color-btn input[type=color]::-webkit-color-swatch { border: none !important; }
#vbp-panel .vbp-btns .vbp-color-btn input[type=color]::-moz-color-swatch { border: none !important; }
.vbp-color-dot {
width: 12px; height: 12px; border-radius: 50%;
background: var(--vbp-buffer-color, #4a90e2);
border: 1.5px solid rgba(255,255,255,.3);
box-shadow: 0 0 0 2px rgba(74,144,226,.18);
transition: background .2s, box-shadow .2s;
pointer-events: none;
flex-shrink: 0;
box-sizing: border-box;
}
.vbp-color-btn:hover .vbp-color-dot {
box-shadow: 0 0 0 3px rgba(74,144,226,.28);
}
#vbp-settings-overlay {
position: fixed; inset: 0;
z-index: 2147483647;
background: rgba(8,10,14,.72);
display: none; align-items: center; justify-content: center;
padding: 20px;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
animation: vbp-fade-in .2s ease;
box-sizing: border-box;
}
#vbp-settings-overlay.vbp-fs-overlay {
position: absolute;
inset: 0; width: 100%; height: 100%;
}
@keyframes vbp-fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes vbp-slide-up {
from { opacity: 0; transform: translateY(12px) scale(.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
#vbp-settings-modal {
width: 100%; max-width: 440px; max-height: 82vh;
background: rgba(22,24,30,.98);
backdrop-filter: blur(24px) saturate(180%);
-webkit-backdrop-filter: blur(24px) saturate(180%);
border: 1px solid rgba(255,255,255,.08);
border-radius: 16px;
box-shadow: 0 24px 64px rgba(0,0,0,.6), 0 8px 20px rgba(0,0,0,.4),
inset 0 1px 0 rgba(255,255,255,.06);
color: #e5e7eb;
font-size: 13px;
display: flex; flex-direction: column;
overflow: hidden;
animation: vbp-slide-up .22s ease;
}
.vbp-modal-header {
display: flex; align-items: center; justify-content: space-between;
padding: 14px 18px;
border-bottom: 1px solid rgba(255,255,255,.06);
background: linear-gradient(180deg, rgba(255,255,255,.02), transparent);
}
.vbp-modal-title {
font-size: 15px; font-weight: 600; letter-spacing: -.01em;
display: flex; align-items: center; gap: 8px;
}
.vbp-modal-title svg { color: #60a5fa; }
.vbp-modal-body {
padding: 14px 18px 18px;
overflow-y: auto;
flex: 1;
}
.vbp-modal-body::-webkit-scrollbar { width: 6px; }
.vbp-modal-body::-webkit-scrollbar-thumb {
background: rgba(255,255,255,.15); border-radius: 3px;
}
.vbp-modal-body::-webkit-scrollbar-thumb:hover {
background: rgba(255,255,255,.25);
}
.vbp-status-card {
display: flex; align-items: center;
padding: 12px 10px;
background: linear-gradient(135deg, rgba(96,165,250,.1), rgba(96,165,250,.03));
border: 1px solid rgba(96,165,250,.18);
border-radius: 11px;
margin-bottom: 6px;
box-shadow: inset 0 1px 0 rgba(255,255,255,.04);
}
.vbp-status-item {
flex: 1;
display: flex; flex-direction: column; align-items: center;
gap: 3px; min-width: 0;
}
.vbp-status-label {
font-size: 9px; font-weight: 700; letter-spacing: .06em;
color: #6b7280; text-transform: uppercase;
}
.vbp-status-val {
font-size: 14px; font-weight: 600;
color: #e5e7eb;
font-variant-numeric: tabular-nums;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
#vbp-s-buf { color: #4ade80; }
#vbp-s-target { color: #fbbf24; }
#vbp-s-target.is-degraded { color: #f87171; }
#vbp-s-target.is-recovering { color: #fb923c; }
#vbp-s-engine { color: #60a5fa; }
.vbp-status-div {
width: 1px; height: 26px;
background: rgba(255,255,255,.08);
flex-shrink: 0;
}
.vbp-group { margin-top: 14px; }
.vbp-group:first-of-type { margin-top: 10px; }
.vbp-group-label {
font-size: 10px; font-weight: 700; letter-spacing: .08em;
color: #6b7280; text-transform: uppercase;
margin-bottom: 7px; padding-left: 2px;
}
.vbp-row {
display: flex; align-items: center;
gap: 10px;
padding: 10px 12px;
background: rgba(255,255,255,.025);
border: 1px solid rgba(255,255,255,.04);
border-radius: 10px;
margin-bottom: 6px;
transition: background .15s, border-color .15s;
position: relative;
}
.vbp-row:hover {
background: rgba(255,255,255,.045);
border-color: rgba(255,255,255,.07);
}
.vbp-row-icon {
width: 28px; height: 28px; flex-shrink: 0;
display: flex; align-items: center; justify-content: center;
font-size: 14px;
background: rgba(255,255,255,.045);
border: 1px solid rgba(255,255,255,.06);
border-radius: 7px;
}
.vbp-row-info {
display: flex; flex-direction: column; gap: 2px;
flex: 1; min-width: 0;
}
.vbp-row-title { font-weight: 500; color: #e5e7eb; font-size: 13px; line-height: 1.3; }
.vbp-row-desc { font-size: 11px; color: #6b7280; line-height: 1.4; }
.vbp-color-row-clickable { cursor: pointer; }
.vbp-color-row-clickable:focus-within {
background: rgba(255,255,255,.045);
border-color: rgba(255,255,255,.07);
}
/* ★ 修复:设置行取色 input 原先 inset:0 铺满整行(约 400×70 的隐形长条),
仅靠普通 opacity:0 隐藏;站点全局 input 样式(尤其 input:focus——取色确认
后 input 恰好获得焦点)会使其变成可见长条色块,遮盖行内"缓冲条颜色"等文字。
对策 1:input 改为锚定在右侧预览胶囊内(胶囊 position:relative)并裁剪,
整行可点不再依赖大覆盖面——外层