一分钟搭建影视站,支持Docker等部署方式
fix(player): 恢复 seek 不再 abort 刚起跑的预取;computeWindow 死分支修正
bestZweia7eda2d367b5
diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsxindex a851256..b6ea6c9 100644--- a/src/components/player-shell.tsx+++ b/src/components/player-shell.tsx@@ -163,6 +163,7 @@ export function PlayerShell({hls.on(Hls.Events.MANIFEST_PARSED, async () => {recoveryRef.current?.markHealthy();// 进度恢复(每集一次):优先 URL position,其次 IndexedDB 记录+ let restoreSeekPending = false;if (!restoredRef.current) {restoredRef.current = true;try {@@ -170,12 +171,17 @@ export function PlayerShell({const duration = artRef.current?.duration || 0;if (saved > 10 && duration > 0 && saved < duration - 2) {if (artRef.current) artRef.current.currentTime = saved;+ // Safari 系此刻 video.currentTime 未必已反映赋值,预取锚点会短暂+ // 落在 0——交给紧随的 video:seeked 事件以恢复后的锚点触发预取+ restoreSeekPending = true;showHint(`已从 ${formatTime(saved)} 继续播放`);}} catch { /* 忽略恢复失败 */ }}- // 新集立即预取(否则要等 timeupdate 的 30s 节流,起播初期无缓存)- ensurePrefetch(mediaUrl, video.currentTime);+ // 新集立即预取(否则要等 timeupdate 的 30s 节流,起播初期无缓存);+ // 有恢复 seek 待执行时跳过:seeked 事件带着恢复后的锚点触发预取,+ // 避免 parsing 中被第二次 ensure abort 白扔一次拉取与解析+ if (!restoreSeekPending) ensurePrefetch(mediaUrl, video.currentTime);video.play().catch(() => {});});// 播放链路恢复(FRAG_LOADED / MANIFEST_PARSED):静默窗外清零连续失败计数diff --git a/src/lib/video-prefetcher.test.ts b/src/lib/video-prefetcher.test.tsnew file mode 100644index 0000000..66577ad--- /dev/null+++ b/src/lib/video-prefetcher.test.ts@@ -0,0 +1,106 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { computeWindow, indexAtTime, VideoPrefetcher } from './video-prefetcher';+import { clearVideoCache } from './video-cache';++afterEach(async () => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ await clearVideoCache();+});++describe('computeWindow', () => {+ const durations = [4, 4, 4, 4, 4]; // 总长 20s++ it('indexAtTime:累计时长定位分片', () => {+ expect(indexAtTime(durations, 0)).toBe(0);+ expect(indexAtTime(durations, 4.5)).toBe(1);+ expect(indexAtTime(durations, 100)).toBe(4);+ });++ it('有限窗口:从回看点到当前 + horizon', () => {+ // 当前 10s,回看 5s → from 覆盖 5s 处;horizon 6s → to 覆盖 16s 处+ const { fromIdx, toIdx } = computeWindow(durations, 10, 6, 5);+ expect(fromIdx).toBe(1); // 5s 落在第 2 片+ expect(toIdx).toBe(4); // 16s 落在第 4 片末+ });++ it('horizon = 0:无限铺满到片尾', () => {+ const { fromIdx, toIdx } = computeWindow(durations, 10, 0, 5);+ expect(fromIdx).toBe(1);+ expect(toIdx).toBe(5);+ });++ it('锚点接近片尾时钳制', () => {+ const { fromIdx, toIdx } = computeWindow(durations, 19, 6, 5);+ expect(toIdx).toBe(5);+ });++ it('时长全缺失时按数量兜底', () => {+ const { toIdx } = computeWindow([0, 0, 0, 0, 0, 0], 0, 6, 5);+ expect(toIdx).toBeLessThanOrEqual(6);+ });+});++describe('VideoPrefetcher.ensure 幂等', () => {+ const PLAYLIST = [+ '#EXTM3U',+ '#EXTINF:5,',+ 'https://cdn.example.com/seg1.ts',+ '#EXTINF:5,',+ 'https://cdn.example.com/seg2.ts',+ ].join('\n');++ const M3U8_URL = 'https://cdn.example.com/index.m3u8';++ function makePrefetcher() {+ const m3u8Fetches = vi.fn();+ // 首次 m3u8 拉取可挂起(模拟 parsing 中途的第二次 ensure),其余立即返回+ let gated = true;+ const fetchMock = vi.fn((input: RequestInfo | URL) => {+ const url = typeof input === 'string' ? input : (input as Request).url;+ if (url.includes('index.m3u8')) {+ m3u8Fetches();+ if (gated) {+ gated = false;+ return new Promise<Response>((r) => setTimeout(() => r(new Response(PLAYLIST, { status: 200 })), 50));+ }+ return Promise.resolve(new Response(PLAYLIST, { status: 200 }));+ }+ return Promise.resolve(new Response(new ArrayBuffer(1000), { status: 200 }));+ });+ vi.stubGlobal('fetch', fetchMock);+ return { m3u8Fetches };+ }++ it('parsing 期间同 descriptor 的第二次 ensure 不 abort 刚起跑的运行', async () => {+ const { m3u8Fetches } = makePrefetcher();+ const p = new VideoPrefetcher();++ p.ensure({ m3u8Url: M3U8_URL, currentTime: 0, episodeKey: 's:v:0', horizonSeconds: 10 });+ // 解析尚未完成(fetch 挂起)时的第二次 ensure:同 descriptor,不得重建+ p.ensure({ m3u8Url: M3U8_URL, currentTime: 0, episodeKey: 's:v:0', horizonSeconds: 10 });+ expect(m3u8Fetches).toHaveBeenCalledTimes(1);++ await vi.waitFor(() => expect(p.getStats().state).toBe('done'));+ expect(m3u8Fetches).toHaveBeenCalledTimes(1);+ });++ it('done 状态的重复 ensure 按设计重建;换集必重建', async () => {+ const { m3u8Fetches } = makePrefetcher();+ const p = new VideoPrefetcher();++ p.ensure({ m3u8Url: M3U8_URL, currentTime: 0, episodeKey: 's:v:0', horizonSeconds: 10 });+ await vi.waitFor(() => expect(p.getStats().state).toBe('done'));+ expect(m3u8Fetches).toHaveBeenCalledTimes(1);++ // done 后的 ensure 会重查覆盖并重建(分片已缓存的拉取在 loader 侧命中)+ p.ensure({ m3u8Url: M3U8_URL, currentTime: 0, episodeKey: 's:v:0', horizonSeconds: 10 });+ await vi.waitFor(() => expect(p.getStats().state).toBe('done'));+ expect(m3u8Fetches).toHaveBeenCalledTimes(2);++ // 换集:descriptor 不同 → 必须重建+ p.ensure({ m3u8Url: M3U8_URL, currentTime: 0, episodeKey: 's:v:1', horizonSeconds: 10 });+ await vi.waitFor(() => expect(p.getStats().state).toBe('done'));+ expect(m3u8Fetches).toHaveBeenCalledTimes(3);+ });+});diff --git a/src/lib/video-prefetcher.ts b/src/lib/video-prefetcher.tsindex 7c33748..13406bc 100644--- a/src/lib/video-prefetcher.ts+++ b/src/lib/video-prefetcher.ts@@ -84,13 +84,13 @@ export function computeWindow(const total = durations.reduce((s, d) => s + d, 0);const cur = Math.max(0, Math.min(currentTime, total));const fromIdx = indexAtTime(durations, Math.max(0, cur - lookBehindSeconds));- if (horizonSeconds <= 0 || total === 0) {- return { fromIdx, toIdx: durations.length };+ // 时长数据不可信(全 0,累计时长恒为 0)时按数量兜底,避免无限窗口+ if (total === 0) {+ return { fromIdx, toIdx: Math.min(durations.length, fromIdx + FALLBACK_MAX_SEGMENTS) };}+ if (horizonSeconds <= 0) return { fromIdx, toIdx: durations.length };const toTime = Math.min(total, cur + horizonSeconds);const toIdx = Math.min(durations.length, indexAtTime(durations, toTime) + 1);- // 时长数据不可信(全 0)时退化为按数量兜底- if (total === 0) return { fromIdx, toIdx: Math.min(durations.length, fromIdx + FALLBACK_MAX_SEGMENTS) };return { fromIdx, toIdx };}@@ -121,17 +121,25 @@ export class VideoPrefetcher {const horizon = options.horizonSeconds ?? settings.horizonSeconds;const descriptor: RunDescriptor = { m3u8Url: options.m3u8Url, episodeKey: options.episodeKey, horizonSeconds: horizon };- // 幂等判断:同一集、同一窗口覆盖足够 → 不打断- if (- this.stats.state === 'running' &&+ // 幂等判断:+ // - running:同一集且窗口覆盖足够 → 不打断;+ // - parsing:窗口尚未可知,同 descriptor 直接复用——否则「MANIFEST_PARSED+ // 起跑 + 恢复 seek 立即第二次 ensure」会 abort 刚起跑的运行,白扔一次+ // m3u8 拉取与解析(窗口若未覆盖新锚点,由后续触发按 running 规则重建)。+ const reusable =+ (this.stats.state === 'running' || this.stats.state === 'parsing') &&this.descriptor &&this.descriptor.m3u8Url === descriptor.m3u8Url &&this.descriptor.episodeKey === descriptor.episodeKey &&- this.descriptor.horizonSeconds === descriptor.horizonSeconds &&- this.currentTime + FORWARD_MARGIN_SECONDS < this.windowToTime &&- options.currentTime >= this.windowFromTime- ) {- return;+ this.descriptor.horizonSeconds === descriptor.horizonSeconds;+ if (reusable) {+ if (this.stats.state === 'parsing') return;+ if (+ this.currentTime + FORWARD_MARGIN_SECONDS < this.windowToTime &&+ options.currentTime >= this.windowFromTime+ ) {+ return;+ }}void this.run(options, settings, descriptor);