Skip to content

一分钟搭建影视站,支持Docker等部署方式

feat: 片段本地缓存、播放错误恢复策略与整集离线下载

bestZwei8872f00ad2ad
diff --git a/README.md b/README.md
index b9ccd3b..b7108be 100644
--- a/README.md
+++ b/README.md
@@ -105,7 +105,7 @@ PASSWORD=your-password npm start # 监听 8080
1. **添加点播源**:设置 → 源管理 → 点播源 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。
2. **搜索**:勾选点播源后输入片名;搜索通过服务端聚合,个别源失败不影响整体结果。
-3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。
+3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。观看/暂停时后续分片自动缓存到本地(设置可关),播放页可「下载本集」(TS/MP4)离线观看。
4. **进度与历史**:自动保存在本设备 IndexedDB,仅定位信息入库,播放时自动同步最新剧集。
5. **配置迁移**:设置 → 数据 → 配置导入导出(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。
diff --git a/package-lock.json b/package-lock.json
index 2cb9d72..9c0bb56 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,6 +16,7 @@
"dexie-react-hooks": "^1.1.7",
"hls.js": "^1.5.17",
"mpegts.js": "^1.8.2",
+ "mux.js": "^6.3.0",
"next": "^15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
@@ -47,6 +48,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/@babel/runtime": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.29.7.tgz",
+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
@@ -3561,6 +3571,11 @@
"node": ">=0.10.0"
}
},
+ "node_modules/dom-walk": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmmirror.com/dom-walk/-/dom-walk-0.1.2.tgz",
+ "integrity": "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w=="
+ },
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -4608,6 +4623,16 @@
"node": ">=10.13.0"
}
},
+ "node_modules/global": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmmirror.com/global/-/global-4.4.0.tgz",
+ "integrity": "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==",
+ "license": "MIT",
+ "dependencies": {
+ "min-document": "^2.19.0",
+ "process": "^0.11.10"
+ }
+ },
"node_modules/globals": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
@@ -5516,6 +5541,15 @@
"node": ">=8.6"
}
},
+ "node_modules/min-document": {
+ "version": "2.19.2",
+ "resolved": "https://registry.npmmirror.com/min-document/-/min-document-2.19.2.tgz",
+ "integrity": "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A==",
+ "license": "MIT",
+ "dependencies": {
+ "dom-walk": "^0.1.0"
+ }
+ },
"node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
@@ -5559,6 +5593,23 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/mux.js": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmmirror.com/mux.js/-/mux.js-6.3.0.tgz",
+ "integrity": "sha512-/QTkbSAP2+w1nxV+qTcumSDN5PA98P0tjrADijIzQHe85oBK3Akhy9AHlH0ne/GombLMz1rLyvVsmrgRxoPDrQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime": "^7.11.2",
+ "global": "^4.4.0"
+ },
+ "bin": {
+ "muxjs-transmux": "bin/transmux.js"
+ },
+ "engines": {
+ "node": ">=8",
+ "npm": ">=5"
+ }
+ },
"node_modules/mz": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
@@ -6243,6 +6294,15 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/process": {
+ "version": "0.11.10",
+ "resolved": "https://registry.npmmirror.com/process/-/process-0.11.10.tgz",
+ "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
diff --git a/package.json b/package.json
index ecd66f2..062f837 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"dexie-react-hooks": "^1.1.7",
"hls.js": "^1.5.17",
"mpegts.js": "^1.8.2",
+ "mux.js": "^6.3.0",
"next": "^15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
diff --git a/src/app/watch/page.tsx b/src/app/watch/page.tsx
index b6260a2..06dbb69 100644
--- a/src/app/watch/page.tsx
+++ b/src/app/watch/page.tsx
@@ -17,6 +17,8 @@ const PlayerShell = dynamic(() => import('@/components/player-shell').then((m) =
});
import { EmptyState, LoadingState, Spinner } from '@/components/states';
import { SwitchSourceModal } from '@/components/switch-source';
+import { useToast } from '@/components/toast';
+import { enqueueDownload } from '@/components/download-manager';
import { Icon } from '@/components/icon';
import { useAuth } from '@/components/auth';
import { resolveSource, useAppStore } from '@/lib/store';
@@ -73,6 +75,7 @@ function WatchContent() {
const episodes = useMemo(() => detailQuery.data?.episodes ?? [], [detailQuery.data]);
const videoTitle = titleParam || detailQuery.data?.videoInfo?.title || '未知视频';
+ const { toast } = useToast();
// 当前播放地址:优先取剧集列表中的当前集,其次直连 URL 参数
const currentUrl = useMemo(() => {
@@ -206,6 +209,20 @@ function WatchContent() {
</p>
</div>
<div className="ml-auto flex items-center gap-2">
+ <button
+ className="btn-ghost btn-sm"
+ onClick={() => {
+ if (!currentUrl) return;
+ enqueueDownload({
+ url: currentUrl,
+ title: `${videoTitle}${episodes.length > 0 ? ` 第${currentIndex + 1}集` : ''}`,
+ format: 'MP4',
+ });
+ toast('已加入下载队列', 'success');
+ }}
+ >
+ 下载本集
+ </button>
<button className="btn-ghost btn-sm" onClick={() => setSwitchOpen(true)}>
切换资源
</button>
@@ -223,6 +240,9 @@ function WatchContent() {
title={videoTitle}
adFilter={store.adFilter}
autoplayNext={store.autoplayNext}
+ episodeKey={`${sourceKey}:${vodId}:${currentIndex}`}
+ nextUrl={currentIndex + 1 < episodes.length ? episodes[currentIndex + 1] : undefined}
+ nextEpisodeKey={currentIndex + 1 < episodes.length ? `${sourceKey}:${vodId}:${currentIndex + 1}` : undefined}
getRestorePosition={getRestorePosition}
onTimeUpdate={handleProgress}
onPause={handleProgress}
diff --git a/src/components/download-manager.tsx b/src/components/download-manager.tsx
new file mode 100644
index 0000000..ef26d07
--- /dev/null
+++ b/src/components/download-manager.tsx
@@ -0,0 +1,319 @@
+'use client';
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { Drawer } from './drawer';
+import { Icon } from './icon';
+import { useToast } from './toast';
+import { db, type DownloadTaskEntry } from '@/lib/db';
+import {
+ PauseResumeController,
+ clearDownloadChunks,
+ runDownloadJob,
+ type DownloadProgress,
+} from '@/lib/m3u8-downloader';
+import { detectSavingCapability, pickSaveTarget } from '@/lib/download-saver';
+
+/**
+ * 全局下载管理器(借鉴 MoonTV DownloadManager,UI 采用本站 Drawer 模式):
+ * - 入口:header 下载图标 + 播放页「下载本集」(均派发 window 事件);
+ * - 并发:全局最多同时进行 3 个任务,其余排队(waiting);
+ * - 断点:已下载分片写入 Cache Storage(网络层断点);
+ * 保存目标(FS Access / 内存)活不过页面刷新,恢复时由用户点击「继续」重新选择。
+ */
+
+const MAX_CONCURRENT_DOWNLOADS = 3;
+const ADD_TASK_EVENT = 'libretv:add-download';
+const SHOW_MANAGER_EVENT = 'libretv:show-download-manager';
+export const DOWNLOADS_UPDATED_EVENT = 'libretv:downloads-updated';
+
+export interface AddDownloadPayload {
+ url: string;
+ title: string;
+ format?: 'TS' | 'MP4';
+}
+
+/** 运行中的任务句柄(不进持久化) */
+interface RunningHandle {
+ abort: AbortController;
+ pause: PauseResumeController;
+ /** 恢复后需要用户重选保存位置时置 false */
+ hasTarget: boolean;
+}
+
+export function DownloadManager({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
+ const { toast } = useToast();
+ const [tasks, setTasks] = useState<DownloadTaskEntry[]>([]);
+ const [capability, setCapability] = useState<'fs-access' | 'memory'>('memory');
+ const running = useRef(new Map<string, RunningHandle>());
+
+ const refresh = useCallback(() => {
+ void db.downloads.orderBy('createdAt').reverse().toArray().then(setTasks);
+ }, []);
+
+ const updateEntry = useCallback(async (id: string, patch: Partial<DownloadTaskEntry>) => {
+ await db.downloads.update(id, { ...patch, updatedAt: Date.now() });
+ refresh();
+ }, [refresh]);
+
+ // —— 任务启动:选目标 → runDownloadJob ——
+ const startTask = useCallback(
+ async (entry: DownloadTaskEntry, hasTarget: boolean) => {
+ if (running.current.has(entry.id)) return;
+ const abort = new AbortController();
+ const pause = new PauseResumeController();
+ running.current.set(entry.id, { abort, pause, hasTarget });
+ await updateEntry(entry.id, { status: 'downloading' });
+
+ const onProgress = (p: DownloadProgress) => {
+ void updateEntry(entry.id, {
+ finished: p.current,
+ total: p.total,
+ status: p.status === 'done' ? 'completed' : p.status === 'error' ? 'error' : 'downloading',
+ });
+ };
+
+ const job = runDownloadJob({
+ taskId: entry.id,
+ url: entry.url,
+ title: entry.title,
+ format: entry.format,
+ signal: abort.signal,
+ pause,
+ onProgress,
+ // hasTarget=false(刷新恢复/排队恢复)时目标已在手势内由「继续」按钮选好
+ target: (globalThis as unknown as { __dlSaveTarget?: { id: string; target: import('@/lib/download-saver').SaveTarget } }).__dlSaveTarget?.id === entry.id
+ ? (globalThis as unknown as { __dlSaveTarget: { target: import('@/lib/download-saver').SaveTarget } }).__dlSaveTarget.target
+ : {
+ // 目标已失效(页面刷新后句柄消亡):显式报错引导用户点「继续」重选,
+ // 绝不能静默空写——否则任务会显示完成却产出空文件
+ kind: 'memory',
+ write: async () => {
+ throw new Error('保存位置已失效,请点击「继续」重新选择');
+ },
+ close: async () => {},
+ abort: async () => {},
+ },
+ });
+
+ void job
+ .then(async () => {
+ await updateEntry(entry.id, { status: 'completed' });
+ void clearDownloadChunks(entry.id);
+ toast(`《${entry.title}》下载完成`, 'success');
+ })
+ .catch(async (err: Error) => {
+ if (abort.signal.aborted) return; // 用户取消:状态已在取消处理里写好
+ await updateEntry(entry.id, { status: 'error' });
+ toast(`《${entry.title}》下载失败:${err.message}`, 'error');
+ })
+ .finally(() => {
+ running.current.delete(entry.id);
+ scheduleNext();
+ });
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [toast, updateEntry]
+ );
+
+ // —— 全局并发调度 ——
+ const scheduleNext = useCallback(() => {
+ void (async () => {
+ const runningCount = running.current.size;
+ if (runningCount >= MAX_CONCURRENT_DOWNLOADS) return;
+ const all = await db.downloads.orderBy('createdAt').toArray();
+ const waiting = all.filter((t) => t.status === 'waiting' && !running.current.has(t.id));
+ for (const t of waiting.slice(0, MAX_CONCURRENT_DOWNLOADS - runningCount)) {
+ const entry = t;
+ // 队列恢复的任务没有保存目标:以内存目标启动(分片已在本地,写出快)
+ void startTask(
+ { ...entry, format: entry.format },
+ (globalThis as { __dlSaveTarget?: { id: string } }).__dlSaveTarget?.id === entry.id
+ );
+ }
+ })();
+ }, [startTask]);
+
+ // —— 事件:新增任务(用户手势内触发,可安全弹文件选择器) ——
+ useEffect(() => {
+ if (!isOpen) return;
+ setCapability(detectSavingCapability());
+ refresh();
+
+ const onAdd = (e: Event) => {
+ const detail = (e as CustomEvent<AddDownloadPayload>).detail;
+ if (!detail?.url || !detail?.title) return;
+ void (async () => {
+ const format = detail.format ?? 'MP4';
+ const id = `dl_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
+ const entry: DownloadTaskEntry = {
+ id,
+ url: detail.url,
+ title: detail.title,
+ format,
+ status: 'waiting',
+ finished: 0,
+ total: 0,
+ errorNum: 0,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+ // 用户手势内预选保存目标(FS Access 弹窗必须在手势内)
+ try {
+ const target = await pickSaveTarget(`${detail.title}.${format.toLowerCase()}`);
+ (globalThis as unknown as { __dlSaveTarget?: { id: string; target: import('@/lib/download-saver').SaveTarget } }).__dlSaveTarget = {
+ id,
+ target,
+ };
+ } catch (err) {
+ if (err instanceof Error && err.message.includes('取消')) {
+ toast('已取消下载', 'info');
+ return;
+ }
+ }
+ await db.downloads.put(entry);
+ refresh();
+ scheduleNext();
+ })();
+ };
+
+ window.addEventListener(ADD_TASK_EVENT, onAdd);
+ return () => {
+ window.removeEventListener(ADD_TASK_EVENT, onAdd);
+ };
+ }, [isOpen, refresh, scheduleNext, toast]);
+
+ // 打开时启动排队中的任务
+ useEffect(() => {
+ if (isOpen) scheduleNext();
+ }, [isOpen, scheduleNext]);
+
+ const onPauseResume = async (entry: DownloadTaskEntry) => {
+ const handle = running.current.get(entry.id);
+ if (handle && entry.status === 'downloading') {
+ handle.pause.pause();
+ await updateEntry(entry.id, { status: 'paused' });
+ return;
+ }
+ if (entry.status === 'paused' || entry.status === 'waiting' || entry.status === 'error') {
+ // 恢复:需要用户手势内重选保存目标(浏览器限制)
+ try {
+ const target = await pickSaveTarget(`${entry.title}.${entry.format.toLowerCase()}`);
+ (globalThis as unknown as { __dlSaveTarget?: { id: string; target: import('@/lib/download-saver').SaveTarget } }).__dlSaveTarget = {
+ id: entry.id,
+ target,
+ };
+ if (running.current.has(entry.id)) return;
+ await updateEntry(entry.id, { status: 'waiting' });
+ scheduleNext();
+ } catch (err) {
+ if (err instanceof Error && err.message.includes('取消')) toast('已取消', 'info');
+ }
+ return;
+ }
+ void handle; // downloading 且无 handle:状态漂移,等待调度器自愈
+ };
+
+ const onCancel = async (entry: DownloadTaskEntry) => {
+ running.current.get(entry.id)?.abort.abort();
+ running.current.delete(entry.id);
+ await clearDownloadChunks(entry.id);
+ await db.downloads.delete(entry.id);
+ refresh();
+ toast(`《${entry.title}》已取消下载`, 'info');
+ };
+
+ const statusLabel: Record<DownloadTaskEntry['status'], string> = {
+ waiting: '排队中',
+ downloading: '下载中',
+ paused: '已暂停',
+ completed: '已完成',
+ error: '失败',
+ };
+
+ return (
+ <Drawer open={isOpen} onClose={onClose} title="下载管理" width="max-w-lg">
+ <div className="space-y-3">
+ <p className="text-xs text-faint">
+ 保存能力:{capability === 'fs-access' ? '磁盘直写(边下边存)' : '内存聚合(完成后浏览器下载)'} ·
+ 同时进行 {Math.min(running.current.size, MAX_CONCURRENT_DOWNLOADS)}/{MAX_CONCURRENT_DOWNLOADS} 个任务
+ </p>
+ {tasks.length === 0 && (
+ <div className="py-10 text-center text-sm text-faint">
+ 暂无下载任务。在播放页点击「下载本集」开始。
+ </div>
+ )}
+ {tasks.map((t) => (
+ <div key={t.id} className="card p-3 space-y-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <p className="text-sm text-content truncate">{t.title}</p>
+ <p className="text-xs text-faint">
+ {t.format.toUpperCase()} · {statusLabel[t.status]}
+ {t.status === 'downloading' && t.total > 0 ? ` · ${t.finished}/${t.total} 分片` : ''}
+ </p>
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ {t.status === 'downloading' && (
+ <button
+ type="button"
+ className="px-2 py-1 rounded bg-chip hover:bg-hover text-xs text-content transition-colors"
+ onClick={() => void onPauseResume(t)}
+ >
+ 暂停
+ </button>
+ )}
+ {(t.status === 'paused' || t.status === 'waiting' || t.status === 'error') && (
+ <button
+ type="button"
+ className="px-2 py-1 rounded bg-chip hover:bg-hover text-xs text-content transition-colors"
+ onClick={() => void onPauseResume(t)}
+ >
+ 继续
+ </button>
+ )}
+ <button
+ type="button"
+ aria-label="取消并删除任务"
+ className="p-1.5 rounded bg-chip hover:bg-hover text-content transition-colors"
+ onClick={() => void onCancel(t)}
+ >
+ <Icon name="close" className="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+ {(t.status === 'downloading' || t.status === 'paused' || t.status === 'completed') && t.total > 0 && (
+ <div className="h-1.5 rounded-full bg-chip overflow-hidden">
+ <div
+ className="h-full bg-accent transition-all"
+ style={{ width: `${t.total > 0 ? Math.round((t.finished / t.total) * 100) : 0}%` }}
+ />
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </Drawer>
+ );
+}
+
+/** 播放页等处调用:把一集加入下载队列(必须在用户手势内调用) */
+export function enqueueDownload(payload: AddDownloadPayload): void {
+ window.dispatchEvent(new CustomEvent(ADD_TASK_EVENT, { detail: payload }));
+}
+
+/** header 等处调用:打开下载管理器 */
+export function requestShowDownloadManager(): void {
+ window.dispatchEvent(new CustomEvent(SHOW_MANAGER_EVENT));
+}
+
+/** 全局挂载点:根布局渲染一次,监听打开事件 */
+export function GlobalDownloadManager() {
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ const onShow = () => setOpen(true);
+ window.addEventListener(SHOW_MANAGER_EVENT, onShow);
+ return () => window.removeEventListener(SHOW_MANAGER_EVENT, onShow);
+ }, []);
+ return <DownloadManager isOpen={open} onClose={() => setOpen(false)} />;
+}
+
diff --git a/src/components/header.tsx b/src/components/header.tsx
index 3d9a2a9..972240e 100644
--- a/src/components/header.tsx
+++ b/src/components/header.tsx
@@ -6,6 +6,7 @@ import { usePathname, useRouter } from 'next/navigation';
import { ThemeToggle } from './theme';
import { SourceManagerDrawer } from './source-manager';
import { HistoryPanel } from './history-panel';
+import { GlobalDownloadManager, requestShowDownloadManager } from './download-manager';
import { Icon } from './icon';
import { SearchHistoryDropdown, useSearchHistory } from './search-history';
import { cn } from '@/lib/utils';
@@ -106,6 +107,9 @@ export function Header({ showSearch = false }: { showSearch?: boolean }) {
<IconButton label="观看历史" onClick={() => setHistoryOpen(true)}>
<Icon name="clock" />
</IconButton>
+ <IconButton label="下载管理" onClick={requestShowDownloadManager}>
+ <Icon name="download" />
+ </IconButton>
<IconButton label="设置" onClick={() => setSettingsOpen(true)}>
<Icon name="gear" />
</IconButton>
@@ -115,6 +119,7 @@ export function Header({ showSearch = false }: { showSearch?: boolean }) {
<SourceManagerDrawer open={settingsOpen} onClose={() => setSettingsOpen(false)} />
<HistoryPanel open={historyOpen} onClose={() => setHistoryOpen(false)} />
+ <GlobalDownloadManager />
</>
);
}
diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsx
index c05e4e9..57bfc44 100644
--- a/src/components/player-shell.tsx
+++ b/src/components/player-shell.tsx
@@ -3,7 +3,14 @@
import { useEffect, useRef, useState } from 'react';
import Artplayer from 'artplayer';
import Hls, { type HlsConfig } from 'hls.js';
-import { filterAdsFromM3u8 } from '@/lib/m3u8';
+
+import { PlaybackRecovery, describeHlsError } from '@/lib/playback-recovery';
+import { createHlsLoader } from '@/lib/hls-loader';
+import {
+ getVideoPrefetcher,
+ getNextEpisodePrefetcher,
+} from '@/lib/video-prefetcher';
+import { loadCacheSettings } from '@/lib/video-cache';
import { formatTime } from '@/lib/utils';
/**
@@ -12,39 +19,23 @@ import { formatTime } from '@/lib/utils';
* 移除:DOM 手工操作、watch.html 跳转链、localStorage 状态总线。
*/
-// 广告过滤 loader:拦截 manifest/level 响应文本,剔除 DISCONTINUITY 广告片段
-class CustomHlsJsLoader extends Hls.DefaultConfig.loader {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- constructor(config: any) {
- super(config);
- const load = this.load.bind(this);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- hls.js loader 回调签名未导出精确类型
- this.load = function (context: any, config: any, callbacks: any) {
- if (context.type === 'manifest' || context.type === 'level') {
- const onSuccess = callbacks.onSuccess;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- callbacks.onSuccess = function (response: any, stats: any, ctx: any, networkDetails: any) {
- if (response.data && typeof response.data === 'string') {
- response.data = filterAdsFromM3u8(response.data);
- }
- return onSuccess(response, stats, ctx, networkDetails);
- };
- }
- load(context, config, callbacks);
- };
- }
-}
-
interface PlayerShellProps {
url: string;
title: string;
adFilter: boolean;
autoplayNext: boolean;
+ /** 剧集标识 `${source}:${vodId}:${episodeIndex}`(片段缓存按集淘汰的分组键) */
+ episodeKey?: string;
+ /** 下一集 m3u8 地址:当前集预取完成后预热下一集前 7 分钟 */
+ nextUrl?: string;
+ nextEpisodeKey?: string;
/** 进度恢复:优先 URL position,其次查询该回调(返回 0 表示无记录) */
getRestorePosition?: () => number | Promise<number>;
onTimeUpdate?: (position: number, duration: number) => void;
onEnded?: () => void;
onPause?: (position: number, duration: number) => void;
+ /** 恢复策略判源不可用(重试耗尽/格式硬失败)时回调:父级弹出换源面板 */
+ onRequestSwitchSource?: (reason: string) => void;
}
export function PlayerShell({
@@ -52,10 +43,14 @@ export function PlayerShell({
title,
adFilter,
autoplayNext,
+ episodeKey,
+ nextUrl,
+ nextEpisodeKey,
getRestorePosition,
onTimeUpdate,
onEnded,
onPause,
+ onRequestSwitchSource,
}: PlayerShellProps) {
const containerRef = useRef<HTMLDivElement>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -67,8 +62,8 @@ export function PlayerShell({
const [showPoster, setShowPoster] = useState(true);
const hintTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// 用 ref 持有最新回调,避免重建播放器
- const cbs = useRef({ onTimeUpdate, onEnded, onPause, getRestorePosition });
- cbs.current = { onTimeUpdate, onEnded, onPause, getRestorePosition };
+ const cbs = useRef({ onTimeUpdate, onEnded, onPause, getRestorePosition, onRequestSwitchSource });
+ cbs.current = { onTimeUpdate, onEnded, onPause, getRestorePosition, onRequestSwitchSource };
const autoplayRef = useRef(autoplayNext);
autoplayRef.current = autoplayNext;
@@ -83,9 +78,11 @@ export function PlayerShell({
const mountCbs = { onTimeUpdate, onEnded, onPause, getRestorePosition };
let lastSave = 0;
+ let lastPrefetchEnsure = 0;
let playbackStarted = false;
- let errorCount = 0;
let ended = false;
+ // 本集的恢复策略实例:跨直连/代理两级重建共享计数,换集随 effect 重建
+ const recovery = new PlaybackRecovery();
const showHint = (text: string) => {
setHint(text);
@@ -93,13 +90,16 @@ export function PlayerShell({
hintTimerRef.current = setTimeout(() => setHint(''), 2500);
};
+ // 片段缓存开启时调大 hls.js 自身缓冲,缓冲之外的空窗由预取器补齐
+ const cacheSettings = loadCacheSettings();
+ const cacheEnabled = cacheSettings.enabled && !!episodeKey;
const hlsConfig: Partial<HlsConfig> = {
debug: false,
enableWorker: true,
backBufferLength: 90,
- maxBufferLength: 30,
- maxMaxBufferLength: 60,
- maxBufferSize: 30 * 1000 * 1000,
+ maxBufferLength: cacheEnabled ? 120 : 30,
+ maxMaxBufferLength: cacheEnabled ? 600 : 60,
+ maxBufferSize: (cacheEnabled ? 90 : 30) * 1000 * 1000,
maxBufferHole: 0.5,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 1000,
@@ -108,13 +108,36 @@ export function PlayerShell({
startLevel: -1,
abrEwmaDefaultEstimate: 500_000,
appendErrorMaxRetry: 5,
+ // 组合 loader:广告过滤(blockAd 随设置)+ 片段缓存命中(cacheEnabled)
+ loader: createHlsLoader(Hls, { blockAd: adFilter }) as unknown as HlsConfig['loader'],
};
- if (adFilter) hlsConfig.loader = CustomHlsJsLoader as unknown as HlsConfig['loader'];
/**
* 初始化 HLS。allowProxyFallback:直连致命网络错误(CORS/防盗链/分片被拒)时,
* 自动改走同源 cookie 鉴权的 /api/proxy 重试一次。
*/
+ // 当前集预取(episodeKey 缺省 = 关闭,见 ensure 内部 settings.enabled 判断)
+ const ensurePrefetch = (mediaUrl: string, currentTime: number, horizonSeconds?: number) => {
+ if (!episodeKey) return;
+ getVideoPrefetcher().ensure({
+ m3u8Url: mediaUrl,
+ currentTime,
+ episodeKey,
+ horizonSeconds,
+ onProgress: (stats) => {
+ // 当前集预取完成且存在下一集:用独立预取器预热下一集前 7 分钟
+ if (stats.state === 'done' && nextUrl && nextEpisodeKey) {
+ getNextEpisodePrefetcher().ensure({
+ m3u8Url: nextUrl,
+ currentTime: 0,
+ episodeKey: nextEpisodeKey,
+ horizonSeconds: 420,
+ });
+ }
+ },
+ });
+ };
+
const setupHls = (video: HTMLVideoElement, mediaUrl: string, allowProxyFallback: boolean) => {
hlsRef.current?.destroy();
const hls = new Hls(hlsConfig);
@@ -124,31 +147,51 @@ export function PlayerShell({
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
+ recovery.markHealthy();
video.play().catch(() => {});
});
+ // 播放链路恢复(FRAG_LOADED / MANIFEST_PARSED):静默窗外清零连续失败计数
+ hls.on(Hls.Events.FRAG_LOADED, () => recovery.markHealthy());
+
hls.on(Hls.Events.ERROR, (_evt, data) => {
- errorCount++;
- if (data.fatal && !playbackStarted) {
- switch (data.type) {
- case Hls.ErrorTypes.NETWORK_ERROR:
- if (
- allowProxyFallback &&
- !mediaUrl.startsWith('/api/proxy') &&
- (errorCount >= 2 || data.details === 'manifestLoadError')
- ) {
- showHint('直连失败,改用代理重试...');
- setupHls(video, `/api/proxy?url=${encodeURIComponent(mediaUrl)}`, false);
- return;
- }
- hls.startLoad();
- break;
- case Hls.ErrorTypes.MEDIA_ERROR:
- hls.recoverMediaError();
- break;
- default:
- if (errorCount > 3) {
- setError('视频加载失败,可能是格式不兼容或源不可用,请尝试其他视频源');
- }
+ if (!data.fatal) return;
+ const decision = recovery.onFatal(data.type, data.details);
+ switch (decision.action) {
+ case 'ignore':
+ break;
+ case 'retry': {
+ // 前两次重试保留直连;达到退避阈值或清单级错误时升级为代理形式
+ // (同源 cookie 鉴权,规避 CORS/防盗链/分片被拒)
+ if (
+ allowProxyFallback &&
+ !mediaUrl.startsWith('/api/proxy') &&
+ (decision.attempt >= 2 || data.details === 'manifestLoadError')
+ ) {
+ showHint('直连失败,改用代理重试...');
+ setupHls(video, `/api/proxy?url=${encodeURIComponent(mediaUrl)}`, false);
+ return;
+ }
+ showHint(`${decision.reason}(第 ${decision.attempt} 次)...`);
+ recovery.schedule(decision.delayMs, () => hls.startLoad());
+ break;
+ }
+ case 'recover-media': {
+ showHint(`${decision.reason}(第 ${decision.attempt} 次)...`);
+ if (decision.swapAudio) hls.swapAudioCodec?.();
+ hls.recoverMediaError();
+ break;
+ }
+ case 'switch-source': {
+ // 覆盖播放开始后的场景:起播失败走 setError 遮罩;
+ // 播放中失败走回调弹换源面板(父级未提供回调时同样 setError)
+ const message = `${describeHlsError(data.type, data.details)}:${decision.reason}`;
+ if (playbackStarted) {
+ showHint(message);
+ cbs.current.onRequestSwitchSource?.(decision.reason);
+ } else {
+ setError(`视频加载失败,${message},请尝试其他视频源`);
+ }
+ break;
}
}
});
@@ -219,9 +262,26 @@ export function PlayerShell({
lastSave = now;
cbs.current.onTimeUpdate?.(art.currentTime, art.duration);
}
+ // 每 30s 续跑一次前向预取窗口(ensure 幂等,窗口未覆盖足够余量才会重建)
+ if (now - lastPrefetchEnsure > 30_000) {
+ lastPrefetchEnsure = now;
+ ensurePrefetch(url, art.currentTime);
+ }
+ });
+ art.on('video:seeked', () => {
+ ensurePrefetch(url, art.currentTime);
});
art.on('video:pause', () => {
cbs.current.onPause?.(art.currentTime, art.duration);
+ // 暂停 = 预取黄金窗口:解除限速并无限铺满整集(用户主动行为,带宽占用可接受)
+ ensurePrefetch(url, art.currentTime, 0);
+ });
+ art.on('video:waiting', () => {
+ // 卡顿:预取临时让出带宽给播放
+ getVideoPrefetcher().setThrottled(true);
+ });
+ art.on('video:playing', () => {
+ getVideoPrefetcher().setThrottled(false);
});
art.on('video:ended', () => {
ended = true;
@@ -321,6 +381,8 @@ export function PlayerShell({
el?.removeEventListener('touchmove', onTouchMove);
hlsRef.current?.destroy();
hlsRef.current = null;
+ recovery.dispose();
+ getVideoPrefetcher().stop();
art.destroy();
artRef.current = null;
};
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index b1452c8..ea34214 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { Drawer } from './drawer';
import { ConfirmDialog } from './confirm-dialog';
import { Icon, type IconName } from './icon';
@@ -16,6 +16,7 @@ import {
useSourceTests,
type TestState,
} from './settings-shared';
+import { loadCacheSettings, saveCacheSettings, getCacheSummary, clearVideoCache, type CacheSummary } from '@/lib/video-cache';
import { EmptyState, Spinner } from './states';
import { useSourceProbe } from './use-source-probe';
import { allLiveSources, isSourceDisabled, keyBelongsToSubscription, resolveSource, subKeyPrefix, useAppStore } from '@/lib/store';
@@ -574,10 +575,64 @@ function PlaybackPanel() {
onChange={(v) => store.updateSettings({ autoplayNext: v })}
/>
</div>
+ <VideoCachePanel />
</section>
);
}
+/** 片段缓存:开启/关闭 + 用量展示 + 清理(数据在浏览器本地,独立于配置导出) */
+function VideoCachePanel() {
+ const [enabled, setEnabled] = useState(() => loadCacheSettings().enabled);
+ const [summary, setSummary] = useState<CacheSummary>({ segments: 0, bytes: 0, episodes: 0 });
+ const [clearing, setClearing] = useState(false);
+
+ const refresh = useCallback(() => {
+ void getCacheSummary().then(setSummary);
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const formatBytes = (bytes: number): string => {
+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`;
+ return `${(bytes / 1024).toFixed(0)} KB`;
+ };
+
+ return (
+ <div className="space-y-3 pt-3 mt-3 border-t border-line">
+ <ToggleRow
+ label="片段本地缓存"
+ description="暂停或观看时把后续分片缓存到浏览器本地,二次播放与断网卡顿时直接命中(存储于本机,不计入配置导出)"
+ checked={enabled}
+ onChange={(v) => {
+ const next = saveCacheSettings({ enabled: v });
+ setEnabled(next.enabled);
+ }}
+ />
+ <div className="flex items-center justify-between text-xs text-faint">
+ <span>
+ 已缓存 {summary.segments} 个分片 · {formatBytes(summary.bytes)} · {summary.episodes} 集
+ </span>
+ <button
+ type="button"
+ className="px-2 py-1 rounded bg-chip text-content hover:bg-hover transition-colors disabled:opacity-50"
+ disabled={clearing || summary.segments === 0}
+ onClick={async () => {
+ setClearing(true);
+ await clearVideoCache();
+ refresh();
+ setClearing(false);
+ }}
+ >
+ 清理缓存
+ </button>
+ </div>
+ </div>
+ );
+}
+
function ImagePanel() {
const store = useAppStore();
const mode = store.imageProxyMode;
diff --git a/src/lib/db.ts b/src/lib/db.ts
index 115c23c..40fecd8 100644
--- a/src/lib/db.ts
+++ b/src/lib/db.ts
@@ -40,11 +40,43 @@ export interface SearchHistoryEntry {
timestamp: number;
}
+export interface SegmentMetaEntry {
+ /** Cache Storage 中的 key(归一化的分片绝对地址,或同源代理地址) */
+ key: string;
+ /** 所属剧集:`${source}:${vodId}:${episodeIndex}`,用于按集淘汰 */
+ episodeKey: string;
+ /** 片段序号(1 基,便于排查) */
+ index: number;
+ bytes: number;
+ /** 预取时记录的真实耗时(毫秒),loader 命中缓存时合成进 hls.js stats 防 ABR 误判 */
+ costMs: number;
+ lastAccess: number;
+}
+
+export type DownloadStatus = 'waiting' | 'downloading' | 'paused' | 'completed' | 'error';
+
+export interface DownloadTaskEntry {
+ id: string;
+ /** 播放页 m3u8 地址(直连或代理形式,入队时的原样) */
+ url: string;
+ title: string;
+ /** 输出格式 */
+ format: 'TS' | 'MP4';
+ status: DownloadStatus;
+ finished: number;
+ total: number;
+ errorNum: number;
+ createdAt: number;
+ updatedAt: number;
+}
+
export const db = new Dexie('libretv') as Dexie & {
history: EntityTable<HistoryEntry, 'id'>;
progress: EntityTable<ProgressEntry, 'key'>;
searchHistory: EntityTable<SearchHistoryEntry, 'text'>;
liveProbe: EntityTable<LiveProbeEntry & { url: string }, 'url'>;
+ segmentMeta: EntityTable<SegmentMetaEntry, 'key'>;
+ downloads: EntityTable<DownloadTaskEntry, 'id'>;
};
db.version(1).stores({
@@ -58,6 +90,12 @@ db.version(2).stores({
liveProbe: 'url',
});
+// v3:视频片段缓存元数据(Cache Storage 存字节、这里存 LRU 索引)与离线下载任务
+db.version(3).stores({
+ segmentMeta: 'key, episodeKey, lastAccess',
+ downloads: 'id, createdAt',
+});
+
export const MAX_HISTORY = 100;
export const MAX_SEARCH_HISTORY = 10;
diff --git a/src/lib/download-saver.ts b/src/lib/download-saver.ts
new file mode 100644
index 0000000..5656d36
--- /dev/null
+++ b/src/lib/download-saver.ts
@@ -0,0 +1,118 @@
+/**
+ * 下载文件的保存目标(借鉴 MoonTV download-saver,按项目约束裁剪):
+ * - Chromium(Edge/Chrome):showSaveFilePicker 边下边写盘(FS Access API),
+ * 必须在**用户手势内**调用(点击处理器的同步栈中);
+ * - 其余环境:内存聚合为 Blob 后触发浏览器下载(>500MB 时让用户确认)。
+ *
+ * 有意不做 StreamSaver(mitm.html + SW 中转):云平台域名下 SW 注册受限,
+ * 复杂度高、收益边际——大文件场景建议直接使用 FS Access 浏览器。
+ */
+
+export interface SaveTarget {
+ /** 'fs' = 磁盘直写;'memory' = 内存聚合 */
+ kind: 'fs' | 'memory';
+ write(data: Uint8Array): Promise<void>;
+ close(): Promise<void>;
+ abort(): Promise<void>;
+}
+
+export function supportsFileSystemAccess(): boolean {
+ return typeof window !== 'undefined' && 'showSaveFilePicker' in window;
+}
+
+export function detectSavingCapability(): 'fs-access' | 'memory' {
+ return supportsFileSystemAccess() ? 'fs-access' : 'memory';
+}
+
+export class UserCancelledError extends Error {
+ constructor() {
+ super('用户取消了保存');
+ }
+}
+
+function memoryTarget(filename: string, confirmOverBytes = 500 * 1024 * 1024): SaveTarget {
+ const chunks: Uint8Array[] = [];
+ let bytes = 0;
+ let done = false;
+ const flush = () => {
+ if (done) return;
+ done = true;
+ const blob = new Blob(chunks.map((c) => c.buffer as ArrayBuffer));
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
+ };
+ return {
+ kind: 'memory',
+ async write(data) {
+ if (done) return;
+ bytes += data.byteLength;
+ if (bytes > confirmOverBytes && bytes - data.byteLength <= confirmOverBytes) {
+ if (!window.confirm(`下载体积已超过 ${Math.round(confirmOverBytes / 1024 / 1024)}MB,继续将暂存在内存中,可能导致页面卡顿。是否继续?`)) {
+ throw new Error('用户取消了下载(内存超限)');
+ }
+ }
+ chunks.push(data);
+ },
+ async close() {
+ flush();
+ },
+ async abort() {
+ done = true;
+ chunks.length = 0;
+ },
+ };
+}
+
+/**
+ * 选择保存目标并打开写入流。showSaveFilePicker 必须在用户手势内调用,
+ * 因此本函数应在点击处理器里被 await(调用方负责)。
+ * 用户取消文件选择器时抛出 UserCancelledError。
+ */
+export async function pickSaveTarget(filename: string, estimatedBytes?: number): Promise<SaveTarget> {
+ if (supportsFileSystemAccess()) {
+ try {
+ // Safari 会暴露 showSaveFilePicker 之外的旧实现;直接 try/catch 兜底
+ const picker = (
+ window as unknown as {
+ showSaveFilePicker: (opts: {
+ suggestedName: string;
+ }) => Promise<{ createWritable: () => Promise<WritableStream> }>;
+ }
+ ).showSaveFilePicker;
+ const handle = await picker({ suggestedName: filename });
+ const writable = await handle.createWritable();
+ const writer = writable.getWriter();
+ return {
+ kind: 'fs',
+ async write(data) {
+ await writer.write(data);
+ },
+ async close() {
+ await writer.close();
+ },
+ async abort() {
+ try {
+ await writer.abort();
+ } catch { /* 已关闭则忽略 */ }
+ },
+ };
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ throw new UserCancelledError();
+ }
+ // 文件选择失败(权限/环境)→ 落到内存聚合
+ }
+ }
+ if (estimatedBytes && estimatedBytes > 500 * 1024 * 1024) {
+ if (!window.confirm('该视频体积较大(未提供磁盘直写能力的环境),将暂存在内存中,可能导致页面卡顿。是否继续?')) {
+ throw new UserCancelledError();
+ }
+ }
+ return memoryTarget(filename);
+}
diff --git a/src/lib/hls-loader.ts b/src/lib/hls-loader.ts
new file mode 100644
index 0000000..4eb53fc
--- /dev/null
+++ b/src/lib/hls-loader.ts
@@ -0,0 +1,108 @@
+import type HlsType from 'hls.js';
+import { filterAdsFromM3u8 } from './m3u8';
+import { buildSegmentCacheKey, readCachedSegment, touchMeta } from './video-cache';
+
+/**
+ * hls.js loader 工厂:在同一个 loader 里组合「广告过滤」与「片段缓存命中」。
+ *
+ * - manifest / level:走基类网络加载;blockAd 开启时在 onSuccess 里清洗
+ * DISCONTINUITY 广告片段(与旧 CustomHlsJsLoader 行为一致);
+ * - fragment:cache-first——本地缓存命中直接合成响应(不回源),未命中走基类。
+ * BYTERANGE 分片(原文件切片)不缓存、直接回源。
+ *
+ * 关键细节:缓存命中时用预取阶段记录的**真实耗时**(costMs)合成 hls.js 的
+ * loader stats——如果让加载时长为 0,ABR 会把它当成无限带宽,错误地拉高码率。
+ *
+ * hls.js 对每次请求都会 new 一个 loader 实例,因此实例上的 destroyed 标记
+ * 生命周期安全(abort/destroy 后不再回调,防孤儿 onSuccess)。
+ */
+interface LoaderOptions {
+ blockAd?: boolean;
+ /** 缓存命中探针(设置面板展示命中率用),可缺省 */
+ onProbe?: (hit: boolean) => void;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type HlsLoaderCtor = new (config: any) => any;
+
+export function createHlsLoader(
+ HlsCtor: typeof HlsType,
+ options: LoaderOptions = {}
+): HlsLoaderCtor {
+ const { blockAd = false, onProbe } = options;
+
+ return class CacheFirstHlsLoader extends (HlsCtor.DefaultConfig.loader as HlsLoaderCtor) {
+ private destroyed = false;
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ constructor(config: any) {
+ super(config);
+ const load = this.load.bind(this);
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ this.load = (context: any, config: any, callbacks: any) => {
+ const isPlaylist = context.type === 'manifest' || context.type === 'level';
+
+ // —— 播放列表:网络加载 + 可选广告过滤 ——
+ if (isPlaylist) {
+
+ if (blockAd) {
+
+ const onSuccess = callbacks.onSuccess;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ callbacks.onSuccess = function (response: any, stats: any, ctx: any, networkDetails: any) {
+ if (response.data && typeof response.data === 'string') {
+ response.data = filterAdsFromM3u8(response.data);
+ }
+ onSuccess(response, stats, ctx, networkDetails);
+ };
+ }
+ load(context, config, callbacks);
+ return;
+ }
+
+ // —— BYTERANGE 分片:整文件切片,无法独立缓存,直接回源 ——
+ if (context.rangeStart || context.rangeEnd) {
+ load(context, config, callbacks);
+ return;
+ }
+
+ // —— 片段:cache-first ——
+ const key = buildSegmentCacheKey(context.url);
+ readCachedSegment(key).then((hit) => {
+ if (this.destroyed) return;
+ if (hit) {
+ void touchMeta(key);
+ onProbe?.(true);
+ const now = performance.now();
+ Object.assign(this.stats, {
+ loading: { start: now - hit.costMs, first: now - hit.costMs + 1, end: now },
+ total: hit.data.byteLength,
+ loaded: hit.data.byteLength,
+ });
+ callbacks.onSuccess({ url: context.url, data: hit.data }, this.stats, context, undefined);
+ return;
+ }
+ onProbe?.(false);
+
+ const onSuccess = callbacks.onSuccess;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ callbacks.onSuccess = (response: any, stats: any, ctx: any, networkDetails: any) => {
+ if (!this.destroyed) onSuccess(response, stats, ctx, networkDetails);
+ };
+ load(context, config, callbacks);
+ });
+ };
+ }
+
+ abort(): void {
+ this.destroyed = true;
+ super.abort();
+ }
+
+ destroy(): void {
+ this.destroyed = true;
+ super.destroy?.();
+ }
+ };
+}
diff --git a/src/lib/m3u8-downloader.ts b/src/lib/m3u8-downloader.ts
new file mode 100644
index 0000000..f0cd6c8
--- /dev/null
+++ b/src/lib/m3u8-downloader.ts
@@ -0,0 +1,228 @@
+import { parseM3u8Playlist, type ParsedPlaylist } from './m3u8-parse';
+import { StreamingTransmuxer } from './mp4-transmuxer';
+
+/**
+ * 整集离线下载(借鉴 MoonTV m3u8-downloader,按 LibreTV-Next 约束裁剪):
+ * - 分片并发下载(默认 8),单分片 3 次重试,已下载分片写入 Cache Storage
+ * (`libretv-dl-v1` 桶)实现网络层断点——中断后续传不再耗流量;
+ * - AES-128 解密用 WebCrypto AES-CBC(HLS 标准),不引入 CryptoJS;
+ * - 输出:TS 直接顺序拼接;MP4 经 mux.js 流式转封装(边下边写,不聚整集);
+ * - 保存目标(FS Access / 内存)由调用方在用户手势内选好传入,本模块只管写。
+ *
+ * 文件层断点的现实约束:FS Access 句柄与内存 Blob 都活不过页面刷新,
+ * 因此「断点续传」指网络层——刷新后重试同一任务会跳过已下载的分片,
+ * 但需要用户重新选择保存位置。
+ */
+
+const DL_CACHE_NAME = 'libretv-dl-v1';
+const SEGMENT_TIMEOUT_MS = 20_000;
+const MAX_SEGMENT_RETRIES = 3;
+
+export class PauseResumeController {
+ private paused = false;
+ private waiters: Array<() => void> = [];
+
+ pause(): void {
+ this.paused = true;
+ }
+
+ resume(): void {
+ this.paused = false;
+ const waiters = this.waiters.splice(0);
+ for (const w of waiters) w();
+ }
+
+ getPaused(): boolean {
+ return this.paused;
+ }
+
+ async waitIfPaused(): Promise<void> {
+ if (!this.paused) return;
+ await new Promise<void>((resolve) => this.waiters.push(resolve));
+ }
+
+ destroy(): void {
+ this.resume();
+ }
+}
+
+export interface DownloadProgress {
+ current: number;
+ total: number;
+ percentage: number;
+ status: 'downloading' | 'processing' | 'done' | 'error';
+ message?: string;
+}
+
+function dlChunkKey(taskId: string, index: number): string {
+ return `${DL_CACHE_NAME}:dl:${taskId}:${index}`;
+}
+
+export async function clearDownloadChunks(taskId: string): Promise<void> {
+ try {
+ if (typeof caches === 'undefined') return;
+ const cache = await caches.open(DL_CACHE_NAME);
+ const keys = await cache.keys();
+ // Request 会把相对 key 解析成带 origin 的绝对 URL,按任务标记子串匹配
+ await Promise.all(
+ keys.filter((r) => r.url.includes(`:dl:${taskId}:`)).map((r) => cache.delete(r))
+ );
+ } catch { /* 忽略 */ }
+}
+
+async function fetchSegment(url: string, signal: AbortSignal): Promise<ArrayBuffer> {
+ const res = await fetch(url, { signal: AbortSignal.any([AbortSignal.timeout(SEGMENT_TIMEOUT_MS), signal]), headers: { Accept: '*/*' } });
+ if (!res.ok) throw new Error(`分片 HTTP ${res.status}`);
+ return res.arrayBuffer();
+}
+
+async function decryptAes128Cbc(data: ArrayBuffer, key: ArrayBuffer, ivHex?: string): Promise<ArrayBuffer> {
+ const iv = ivHex
+ ? Uint8Array.from(ivHex.padStart(32, '0').slice(0, 32).match(/.{2}/g)!.map((h) => parseInt(h, 16)))
+ : new Uint8Array(16);
+ const cryptoKey = await crypto.subtle.importKey('raw', key, 'AES-CBC', false, ['decrypt']);
+ return crypto.subtle.decrypt({ name: 'AES-CBC', iv }, cryptoKey, data);
+}
+
+export interface DownloadJobOptions {
+ taskId: string;
+ url: string;
+ title: string;
+ format: 'TS' | 'MP4';
+ concurrency?: number;
+ signal: AbortSignal;
+ pause: PauseResumeController;
+ onProgress: (p: DownloadProgress) => void;
+ /** 在用户手势内选好的保存目标 */
+ target: import('./download-saver').SaveTarget;
+}
+
+/**
+ * 执行一次整集下载。调用方(DownloadManager)负责:
+ * 在用户手势内 pickSaveTarget、构造 AbortSignal/PauseResumeController、
+ * 更新 Dexie 任务状态;本函数只负责解析 → 并发下载 → 顺序写出。
+ */
+export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
+ const { taskId, url, format, signal, pause, onProgress, target } = opts;
+ const concurrency = Math.min(Math.max(opts.concurrency ?? 8, 1), 16);
+
+ const report = (current: number, total: number, status: DownloadProgress['status'], message?: string) => {
+ onProgress({
+ current,
+ total,
+ percentage: total > 0 ? Math.round((current / total) * 100) : 0,
+ status,
+ message,
+ });
+ };
+
+ // —— 解析(重试 2 次) ——
+ let parsed: ParsedPlaylist;
+ let lastErr: unknown;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ parsed = await parseM3u8Playlist(url);
+ lastErr = undefined;
+ break;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ if (lastErr || !parsed!) {
+ throw new Error(`播放列表解析失败:${lastErr instanceof Error ? lastErr.message : '未知错误'}`);
+ }
+ if (parsed.byterange) throw new Error('该集使用 BYTERANGE 分片,暂不支持下载');
+
+ const total = parsed.segments.length;
+ report(0, total, 'downloading');
+
+ // —— AES key 预取 ——
+ let aesKey: ArrayBuffer | undefined;
+ if (parsed.aesConf) {
+ const res = await fetch(parsed.aesConf.uri, { signal });
+ if (!res.ok) throw new Error(`解密密钥加载失败:HTTP ${res.status}`);
+ aesKey = await res.arrayBuffer();
+ }
+
+ // —— 并发下载分片(Cache Storage 断点) ——
+ const cache = await caches.open(DL_CACHE_NAME);
+ const chunkKey = (index: number) => dlChunkKey(taskId, index);
+ let cursor = 0;
+ // 恢复:统计已有分片数作为起点
+ let current = 0;
+ for (let i = 1; i <= total; i++) {
+ if (await cache.match(new Request(chunkKey(i)))) current += 1;
+ }
+ report(current, total, 'downloading');
+
+ const worker = async (): Promise<void> => {
+ while (cursor < total) {
+ if (signal.aborted) return;
+ await pause.waitIfPaused();
+ const index = ++cursor; // 1 基
+ if (signal.aborted) return;
+ await pause.waitIfPaused();
+ const cached = await cache.match(new Request(chunkKey(index)));
+ if (cached) {
+ current += 1;
+ report(current, total, 'downloading');
+ continue;
+ }
+ const seg = parsed.segments[index - 1];
+ let buffer: ArrayBuffer | undefined;
+ for (let retry = 0; retry < MAX_SEGMENT_RETRIES; retry++) {
+ if (signal.aborted) return;
+ try {
+ buffer = await fetchSegment(seg.url, signal);
+ break;
+ } catch {
+ if (signal.aborted) return;
+ await new Promise((r) => setTimeout(r, 1000 * (retry + 1)));
+ }
+ }
+ if (!buffer) {
+ throw new Error(`分片 ${index} 下载失败(已重试 ${MAX_SEGMENT_RETRIES} 次)`);
+ }
+ await cache.put(
+ new Request(chunkKey(index)),
+ new Response(buffer.slice(0), { headers: { 'Content-Type': 'video/mp2t' } })
+ );
+ current += 1;
+ report(current, total, 'downloading');
+ }
+ };
+ await Promise.all(Array.from({ length: concurrency }, worker));
+ if (signal.aborted) return;
+
+ // —— 顺序写出(转封装 / 拼接) ——
+ report(total, total, 'processing');
+ if (format === 'MP4') {
+ const transmuxer = new StreamingTransmuxer(target);
+ for (let i = 1; i <= total; i++) {
+ if (signal.aborted) return;
+ await pause.waitIfPaused();
+ const resp = await cache.match(new Request(chunkKey(i)));
+ if (!resp) throw new Error(`分片 ${i} 缓存丢失,请重试`);
+ let data = await resp.arrayBuffer();
+ if (aesKey && parsed.aesConf) {
+ data = await decryptAes128Cbc(data, aesKey, parsed.aesConf.iv);
+ }
+ await transmuxer.pushAndTransmux(new Uint8Array(data));
+ }
+ await transmuxer.finish();
+ } else {
+ for (let i = 1; i <= total; i++) {
+ if (signal.aborted) return;
+ await pause.waitIfPaused();
+ const resp = await cache.match(new Request(chunkKey(i)));
+ if (!resp) throw new Error(`分片 ${i} 缓存丢失,请重试`);
+ let data = await resp.arrayBuffer();
+ if (aesKey && parsed.aesConf) {
+ data = await decryptAes128Cbc(data, aesKey, parsed.aesConf.iv);
+ }
+ await target.write(new Uint8Array(data));
+ }
+ await target.close();
+ }
+ report(total, total, 'done');
+}
diff --git a/src/lib/m3u8-parse.ts b/src/lib/m3u8-parse.ts
new file mode 100644
index 0000000..8baea72
--- /dev/null
+++ b/src/lib/m3u8-parse.ts
@@ -0,0 +1,171 @@
+import { makeAbsolute } from './m3u8';
+
+/**
+ * m3u8 播放列表解析(预取器与离线下载共用)。
+ *
+ * 与 hls.js loader 侧的一致性是本地缓存命中的前提:
+ * 两侧都通过 `new URL()` 绝对化地址(见 video-cache.buildSegmentCacheKey),
+ * 因此这里对分片地址也必须用同一构造器抹平默认端口 / 百分号编码差异。
+ */
+
+export interface ParsedSegment {
+ /** 绝对地址 */
+ url: string;
+ /** EXTINF 时长(秒);缺失时为 0 */
+ duration: number;
+}
+
+export interface ParsedVariant {
+ url: string;
+ /** RESOLUTION 的高度;缺失时按码率推断 */
+ height: number;
+ bandwidth: number;
+}
+
+export interface AesConf {
+ method: string;
+ uri: string;
+ iv?: string;
+}
+
+export interface ParsedPlaylist {
+ /** master 播放列表时非空(已按 preferredHeight 选档) */
+ variants?: ParsedVariant[];
+ segments: ParsedSegment[];
+ /** AES-128 解密参数;method=NONE 时为 undefined */
+ aesConf?: AesConf;
+ /** 出现 EXT-X-BYTERANGE:分片为原文件切片,无法独立缓存,该集禁用缓存 */
+ byterange: boolean;
+ totalDuration: number;
+}
+
+/** 解析深度上限(master → variant → media,正常不超过 2 层,防御异常源) */
+const MAX_DEPTH = 5;
+
+/**
+ * 码率 → 推断高度:很多源站的 master playlist 只给 BANDWIDTH 不给 RESOLUTION,
+ * hls.js 的 level.height 会是 undefined,任何「按分辨率命名」的实现都会退化。
+ * 分层取自常见转码参数(1080p≈5Mbps、720p≈3Mbps…),仅供档位标识使用。
+ */
+export function inferHeightFromBitrate(bandwidth: number): number {
+ const tiers: Array<[number, number]> = [
+ [20_000_000, 4320],
+ [10_000_000, 2160],
+ [5_000_000, 1080],
+ [3_000_000, 720],
+ [1_500_000, 540],
+ [800_000, 480],
+ [400_000, 360],
+ ];
+ for (const [bps, height] of tiers) {
+ if (bandwidth >= bps) return height;
+ }
+ return 240;
+}
+
+/**
+ * 档位选择:传 preferredHeight 时「同高度优先 → 更高档中最低 → 更低档中最高」;
+ * 未传时取最高带宽。与 hls-quality 的匹配思路一致,保证预取/下载选中的
+ * 档位就是用户正在观看的那一档。
+ */
+export function pickVariant(variants: ParsedVariant[], preferredHeight?: number): ParsedVariant {
+ if (!preferredHeight) {
+ return variants.reduce((best, v) => (v.bandwidth > best.bandwidth ? v : best), variants[0]);
+ }
+ const same = variants.filter((v) => v.height === preferredHeight);
+ if (same.length) return same.reduce((best, v) => (v.bandwidth < best.bandwidth ? v : best), same[0]);
+ const higher = variants.filter((v) => v.height > preferredHeight);
+ if (higher.length) return higher.reduce((best, v) => (v.height < best.height ? v : best), higher[0]);
+ return variants.reduce((best, v) => (v.height > best.height ? v : best), variants[0]);
+}
+
+function parseExtInf(line: string): number {
+ const m = line.match(/^#EXTINF:([\d.]+)/);
+ return m ? parseFloat(m[1]) || 0 : 0;
+}
+
+function parseAesConf(line: string): AesConf | undefined {
+ const method = line.match(/METHOD=([^,]+)/)?.[1];
+ if (!method || method === 'NONE') return undefined;
+ const uri = line.match(/URI="([^"]+)"/)?.[1];
+ if (!uri) return undefined;
+ const iv = line.match(/IV=0[xX]([0-9a-fA-F]+)/)?.[1];
+ return { method, uri, iv };
+}
+
+/** 解析播放列表:master 递归选档,media 输出分片清单。fetch 失败 / 超限直接抛错由调用方降级 */
+export async function parseM3u8Playlist(
+ url: string,
+ depth = 0,
+ preferredHeight?: number
+): Promise<ParsedPlaylist> {
+ if (depth > MAX_DEPTH) throw new Error(`m3u8 嵌套超过 ${MAX_DEPTH} 层`);
+ const res = await fetch(url, { headers: { Accept: '*/*' } });
+ if (!res.ok) throw new Error(`m3u8 拉取失败:HTTP ${res.status}`);
+ const text = await res.text();
+
+ // —— master:收集变体,选档后递归 ——
+ if (text.includes('#EXT-X-STREAM-INF')) {
+ const variants: ParsedVariant[] = [];
+ let pending: { bandwidth: number; height?: number } | undefined;
+ for (const raw of text.split('\n')) {
+ const line = raw.trim();
+ if (line.startsWith('#EXT-X-STREAM-INF')) {
+ const bandwidth = parseInt(line.match(/BANDWIDTH=(\d+)/)?.[1] || '0', 10);
+ const resolution = line.match(/RESOLUTION=(\d+)x(\d+)/);
+ pending = {
+ bandwidth,
+ height: resolution ? parseInt(resolution[2], 10) : undefined,
+ };
+ continue;
+ }
+ if (!line || line.startsWith('#')) continue;
+ if (pending) {
+ const abs = makeAbsolute(line, url);
+ variants.push({
+ url: abs,
+ bandwidth: pending.bandwidth,
+ height: pending.height ?? inferHeightFromBitrate(pending.bandwidth),
+ });
+ pending = undefined;
+ }
+ }
+ if (!variants.length) throw new Error('master m3u8 未解析到可用档位');
+ const chosen = pickVariant(variants, preferredHeight);
+ const inner = await parseM3u8Playlist(chosen.url, depth + 1, preferredHeight);
+ return { ...inner, variants };
+ }
+
+ // —— media:分片 / 时长 / AES / BYTERANGE ——
+ const segments: ParsedSegment[] = [];
+ let aesConf: AesConf | undefined;
+ let byterange = false;
+ let pendingDuration = 0;
+ for (const raw of text.split('\n')) {
+ const line = raw.trim();
+ if (line.startsWith('#EXT-X-KEY')) {
+ // 取最后一次出现的 KEY(逐段换 key 的源不在支持范围,与 MoonTV 一致)
+ const conf = parseAesConf(line);
+ if (conf) aesConf = { ...conf, uri: makeAbsolute(conf.uri, url) };
+ continue;
+ }
+ if (line.startsWith('#EXT-X-BYTERANGE')) {
+ byterange = true;
+ continue;
+ }
+ if (line.startsWith('#EXTINF:')) {
+ pendingDuration = parseExtInf(line);
+ continue;
+ }
+ if (!line || line.startsWith('#')) continue;
+ segments.push({ url: makeAbsolute(line, url), duration: pendingDuration });
+ pendingDuration = 0;
+ }
+ if (!segments.length) throw new Error('m3u8 未解析到分片');
+ return {
+ segments,
+ aesConf,
+ byterange,
+ totalDuration: segments.reduce((sum, s) => sum + s.duration, 0),
+ };
+}
diff --git a/src/lib/mp4-transmuxer.ts b/src/lib/mp4-transmuxer.ts
new file mode 100644
index 0000000..74cfe66
--- /dev/null
+++ b/src/lib/mp4-transmuxer.ts
@@ -0,0 +1,99 @@
+/* eslint-disable @typescript-eslint/no-explicit-any -- mux.js 无完整类型定义 */
+// @ts-expect-error - mux.js 没有完整的 TypeScript 类型定义
+import muxjs from 'mux.js';
+
+/**
+ * MP4 转封装(基于 mux.js,借鉴 MoonTV mp4-transmuxer)。
+ *
+ * HLS 的 TS 分片对浏览器不可直接播放,下载产物要做 TS→fMP4 转封装:
+ * mux.js 的 Transmuxer 每次 flush 产出一段 fMP4(首次含 initSegment),
+ * 因此可以边下载边流式写入文件,不需要把整集聚合在内存里。
+ */
+
+export class StreamingTransmuxer {
+ private transmuxer: any;
+ private writer?: { write(data: Uint8Array): Promise<void>; close?(): Promise<void>; abort?(): Promise<void> };
+ private initWritten = false;
+ private segmentCount = 0;
+ private writeChain: Promise<void> = Promise.resolve();
+ private writeError: Error | undefined;
+
+ constructor(writer?: { write(data: Uint8Array): Promise<void> }) {
+ this.writer = writer;
+ this.transmuxer = new muxjs.mp4.Transmuxer({ keepOriginalTimestamps: true });
+ this.transmuxer.on('data', (segment: any) => {
+ const data: Uint8Array = this.initWritten
+ ? new Uint8Array(segment.data)
+ : concatInitAndData(segment);
+ this.initWritten = true;
+ this.segmentCount += 1;
+ // 写入串行化:写失败暂存,下一次 pushAndTransmux 时抛出
+ this.writeChain = this.writeChain.then(() => this.writer?.write(data));
+ this.writeChain.catch((err) => {
+ this.writeError = err instanceof Error ? err : new Error(String(err));
+ });
+ });
+ }
+
+ setWriter(writer: { write(data: Uint8Array): Promise<void>; close?(): Promise<void>; abort?(): Promise<void> }): void {
+ this.writer = writer;
+ }
+
+ getSegmentCount(): number {
+ return this.segmentCount;
+ }
+
+ /** push 一个 TS 分片并立刻 flush 出 fMP4 片段 */
+ async pushAndTransmux(tsData: Uint8Array): Promise<void> {
+ this.transmuxer.push(tsData);
+ this.transmuxer.flush();
+ await this.writeChain;
+ if (this.writeError) {
+ const err = this.writeError;
+ this.writeError = undefined;
+ throw err;
+ }
+ }
+
+ /** 收尾:最后一次 flush 并关闭写入流 */
+ async finish(): Promise<void> {
+ this.transmuxer.flush();
+ await this.writeChain;
+ await this.writer?.close?.();
+ }
+
+ async abort(): Promise<void> {
+ try {
+ await this.writer?.abort?.();
+ } catch { /* 忽略 */ }
+ }
+}
+
+function concatInitAndData(segment: { initSegment: ArrayBuffer; data: ArrayBuffer }): Uint8Array {
+ const init = new Uint8Array(segment.initSegment);
+ const data = new Uint8Array(segment.data);
+ const out = new Uint8Array(init.length + data.length);
+ out.set(init, 0);
+ out.set(data, init.length);
+ return out;
+}
+
+/** 批量转封装:push 全部分片后一次 flush,聚合为 MP4 Blob(内存型,适合小体量) */
+export function transmuxTSToMP4(tsSegments: Uint8Array[], duration?: number): Blob {
+ const transmuxer = new muxjs.mp4.Transmuxer({
+ keepOriginalTimestamps: true,
+ ...(duration ? { duration } : {}),
+ });
+ const chunks: Uint8Array[] = [];
+ let initWritten = false;
+ transmuxer.on('data', (segment: any) => {
+ if (!initWritten) {
+ chunks.push(new Uint8Array(segment.initSegment));
+ initWritten = true;
+ }
+ chunks.push(new Uint8Array(segment.data));
+ });
+ for (const ts of tsSegments) transmuxer.push(ts);
+ transmuxer.flush();
+ return new Blob(chunks.map((c) => c.buffer as ArrayBuffer), { type: 'video/mp4' });
+}
diff --git a/src/lib/playback-recovery.test.ts b/src/lib/playback-recovery.test.ts
new file mode 100644
index 0000000..2f066ca
--- /dev/null
+++ b/src/lib/playback-recovery.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { PlaybackRecovery, describeHlsError } from './playback-recovery';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('PlaybackRecovery 决策表', () => {
+ it('格式硬失败直接换源,重试无意义', () => {
+ const r = new PlaybackRecovery();
+ for (const details of [
+ 'manifestParsingError',
+ 'manifestIncompatibleCodecsError',
+ 'levelEmptyError',
+ ]) {
+ expect(r.onFatal('networkError', details).action).toBe('switch-source');
+ }
+ });
+
+ it('networkError:指数退避,超过上限换源', () => {
+ const r = new PlaybackRecovery();
+ const delays: number[] = [];
+ for (let i = 0; i < 4; i++) {
+ const d = r.onFatal('networkError', 'fragLoadError');
+ if (d.action === 'retry') {
+ delays.push(d.delayMs);
+ expect(d.attempt).toBe(i + 1);
+ } else {
+ expect(d).toMatchObject({ action: 'switch-source' });
+ expect(d.action === 'switch-source' && d.reason).toContain('3 次');
+ }
+ }
+ expect(delays).toEqual([800, 1600, 3200]);
+ });
+
+ it('mediaError:先 recoverMediaError,第 2 次追加 swapAudio,再失败换源', () => {
+ const r = new PlaybackRecovery();
+ expect(r.onFatal('mediaError', 'bufferAppendError')).toMatchObject({
+ action: 'recover-media',
+ swapAudio: false,
+ attempt: 1,
+ });
+ expect(r.onFatal('mediaError', 'bufferAppendError')).toMatchObject({
+ action: 'recover-media',
+ swapAudio: true,
+ attempt: 2,
+ });
+ expect(r.onFatal('mediaError', 'bufferAppendError').action).toBe('switch-source');
+ });
+
+ it('未知致命类型换源', () => {
+ const r = new PlaybackRecovery();
+ expect(r.onFatal('someWeirdError', 'whatever').action).toBe('switch-source');
+ });
+
+ it('dispose 后一律忽略', () => {
+ const r = new PlaybackRecovery();
+ r.dispose();
+ expect(r.onFatal('networkError', 'fragLoadError').action).toBe('ignore');
+ });
+});
+
+describe('markHealthy 静默窗', () => {
+ it('静默窗外的成功清零计数,重新开始退避', () => {
+ const r = new PlaybackRecovery();
+ r.onFatal('networkError', 'fragLoadError'); // attempt 1
+ r.onFatal('networkError', 'fragLoadError'); // attempt 2
+ vi.advanceTimersByTime(3001); // 出静默窗
+ r.markHealthy();
+ const d = r.onFatal('networkError', 'fragLoadError');
+ expect(d.action === 'retry' && d.attempt).toBe(1);
+ });
+
+ it('静默窗内的成功不清零(防重试成功瞬间的噪声),计数继续累积', () => {
+ const r = new PlaybackRecovery();
+ r.onFatal('networkError', 'fragLoadError'); // attempt 1
+ r.markHealthy(); // 动作后 3s 内:忽略
+ const d = r.onFatal('networkError', 'fragLoadError');
+ expect(d.action === 'retry' && d.attempt).toBe(2);
+ });
+});
+
+describe('schedule', () => {
+ it('按延迟执行任务', () => {
+ const r = new PlaybackRecovery();
+ const task = vi.fn();
+ r.schedule(1000, task);
+ expect(task).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1000);
+ expect(task).toHaveBeenCalledTimes(1);
+ });
+
+ it('dispose 取消未执行的任务', () => {
+ const r = new PlaybackRecovery();
+ const task = vi.fn();
+ r.schedule(1000, task);
+ r.dispose();
+ vi.advanceTimersByTime(2000);
+ expect(task).not.toHaveBeenCalled();
+ });
+});
+
+describe('describeHlsError', () => {
+ it('常见 details 映射中文文案', () => {
+ expect(describeHlsError('networkError', 'manifestLoadError')).toBe('播放列表加载失败');
+ expect(describeHlsError('networkError', 'fragLoadError')).toBe('视频分片加载失败');
+ expect(describeHlsError('mediaError', '')).toBe('媒体解码错误');
+ expect(describeHlsError('otherError', 'xyz')).toBe('播放错误(xyz)');
+ });
+});
diff --git a/src/lib/playback-recovery.ts b/src/lib/playback-recovery.ts
new file mode 100644
index 0000000..057fbf3
--- /dev/null
+++ b/src/lib/playback-recovery.ts
@@ -0,0 +1,155 @@
+/**
+ * HLS 播放错误恢复策略(借鉴 MoonTV playback-recovery)。
+ *
+ * 解决的问题:player-shell 原实现遇致命错误就无条件 `hls.startLoad()`,
+ * errorCount 只增不减:源站挂掉时会形成无限重试风暴,而且永远不会换源;
+ * 播放开始(playbackStarted)之后的致命错误甚至完全没有任何处理。
+ *
+ * 本模块**只做决策,不碰 hls 实例**。调用方拿到 {@link RecoveryDecision}
+ * 后自行执行(含延时),这样策略可以独立单测,也便于在 UI 上给出提示。
+ *
+ * 计数语义:「连续失败次数」——收到 FRAG_LOADED(无论来自网络还是本地片段
+ * 缓存)即视为播放链路已恢复,计数归零。动作后设 3s 静默窗,窗内的成功
+ * 不清零(防重试成功瞬间的噪声),因此偶发抖动不会被误判为「源已死」,
+ * 而源站彻底挂掉时计数会持续累积并最终触发换源。
+ */
+
+/** hls.js 的 ErrorTypes 常量值,这里用字面量避免静态引入 hls.js */
+export const HLS_ERROR_NETWORK = 'networkError';
+export const HLS_ERROR_MEDIA = 'mediaError';
+
+/**
+ * 这些致命错误重试没有意义(格式/编码层面的硬失败),直接换源。
+ * manifestLoadError / manifestLoadTimeOut **不在其中**——网络抖动值得退避重试。
+ */
+const HARD_FAIL_DETAILS = new Set([
+ 'manifestParsingError',
+ 'manifestIncompatibleCodecsError',
+ 'levelEmptyError',
+]);
+
+export interface RecoveryPolicy {
+ /** 连续网络错误的最大退避重试次数,超出后换源 */
+ maxNetworkRetries: number;
+ /** mediaError 的最大恢复次数,超出后换源 */
+ maxMediaRecoveries: number;
+ /** 退避基值(毫秒),按 2^(n-1) 指数递增 */
+ baseDelayMs: number;
+ /** 退避上限(毫秒) */
+ maxDelayMs: number;
+}
+
+export const DEFAULT_RECOVERY_POLICY: RecoveryPolicy = {
+ maxNetworkRetries: 3,
+ maxMediaRecoveries: 2,
+ baseDelayMs: 800,
+ maxDelayMs: 8000,
+};
+
+export type RecoveryDecision =
+ | { action: 'retry'; delayMs: number; attempt: number; reason: string }
+ | { action: 'recover-media'; swapAudio: boolean; attempt: number; reason: string }
+ | { action: 'switch-source'; reason: string }
+ | { action: 'ignore'; reason: string };
+
+/** 动作后 3s 内的 FRAG_LOADED 视为重试噪声,不用于清零计数 */
+const HEALTHY_QUIET_MS = 3000;
+
+export class PlaybackRecovery {
+ private policy: RecoveryPolicy;
+ private networkRetries = 0;
+ private mediaRecoveries = 0;
+ private lastActionAt = 0;
+ private disposed = false;
+ private timers = new Set<ReturnType<typeof setTimeout>>();
+
+ constructor(policy: Partial<RecoveryPolicy> = {}) {
+ this.policy = { ...DEFAULT_RECOVERY_POLICY, ...policy };
+ }
+
+ /** 播放链路恢复(FRAG_LOADED / MANIFEST_PARSED):静默窗外的成功清零计数 */
+ markHealthy(): void {
+ if (this.disposed) return;
+ if (this.lastActionAt && Date.now() - this.lastActionAt < HEALTHY_QUIET_MS) return;
+ this.networkRetries = 0;
+ this.mediaRecoveries = 0;
+ }
+
+ /** 致命错误 → 恢复决策 */
+ onFatal(type: string, details: string): RecoveryDecision {
+ if (this.disposed) return { action: 'ignore', reason: '已销毁' };
+ this.lastActionAt = Date.now();
+
+ if (HARD_FAIL_DETAILS.has(details)) {
+ return { action: 'switch-source', reason: '播放列表格式无法解析,重试无意义' };
+ }
+
+ if (type === HLS_ERROR_MEDIA) {
+ this.mediaRecoveries += 1;
+ if (this.mediaRecoveries > this.policy.maxMediaRecoveries) {
+ return { action: 'switch-source', reason: '媒体解码错误多次恢复无效' };
+ }
+ return {
+ action: 'recover-media',
+ // 第 1 次仅 recoverMediaError;第 2 次追加 swapAudioCodec(hls.js 官方推荐链)
+ swapAudio: this.mediaRecoveries >= 2,
+ attempt: this.mediaRecoveries,
+ reason: '媒体解码错误,尝试恢复',
+ };
+ }
+
+ if (type === HLS_ERROR_NETWORK) {
+ this.networkRetries += 1;
+ if (this.networkRetries > this.policy.maxNetworkRetries) {
+ return { action: 'switch-source', reason: `网络错误已重试 ${this.policy.maxNetworkRetries} 次仍未恢复` };
+ }
+ return {
+ action: 'retry',
+ attempt: this.networkRetries,
+ delayMs: Math.min(
+ this.policy.baseDelayMs * 2 ** (this.networkRetries - 1),
+ this.policy.maxDelayMs
+ ),
+ reason: '网络错误,退避重试',
+ };
+ }
+
+ return { action: 'switch-source', reason: `未知的致命错误类型:${type}` };
+ }
+
+ /** 决策为 retry 时由调用方调用:统一管理定时器,dispose 时全部取消 */
+ schedule(delayMs: number, task: () => void): void {
+ const timer = setTimeout(() => {
+ this.timers.delete(timer);
+ if (!this.disposed) task();
+ }, delayMs);
+ this.timers.add(timer);
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ for (const timer of this.timers) clearTimeout(timer);
+ this.timers.clear();
+ }
+}
+
+/** hls 错误 → 中文提示(用于 hint 浮层 / toast) */
+export function describeHlsError(type: string, details: string): string {
+ if (HARD_FAIL_DETAILS.has(details)) return '播放列表格式无法解析';
+ switch (details) {
+ case 'manifestLoadError':
+ case 'manifestLoadTimeOut':
+ return '播放列表加载失败';
+ case 'manifestParsingError':
+ return '播放列表解析失败';
+ case 'fragLoadError':
+ case 'fragLoadTimeOut':
+ return '视频分片加载失败';
+ case 'keyLoadError':
+ return '解密密钥加载失败';
+ case 'bufferStalledError':
+ return '缓冲不足';
+ default:
+ return type === HLS_ERROR_MEDIA ? '媒体解码错误' : `播放错误(${details || type})`;
+ }
+}
diff --git a/src/lib/video-cache.ts b/src/lib/video-cache.ts
new file mode 100644
index 0000000..c5f6746
--- /dev/null
+++ b/src/lib/video-cache.ts
@@ -0,0 +1,267 @@
+import { db } from './db';
+
+/**
+ * 视频片段本地缓存层(借鉴 MoonTV video-cache)。
+ *
+ * 职责边界:Cache Storage 读写 + IndexedDB(Dexie segmentMeta 表)元数据 + 两轮 LRU 淘汰。
+ * 不做任何与播放器状态相关的判断,因此预取循环可以在视频暂停、页面切到后台时继续工作。
+ *
+ * 为什么不用 Service Worker:
+ * 1. 播放器本来就在替换 hls.js 的 loader(广告过滤 + 缓存命中),叠加 cache-first 零注册成本;
+ * 2. 跨域片段经 SW 拦截拿到的是 opaque response,cache.put 存不了内容;
+ * 3. 无 SW 也无跨域 opaque 问题:预取侧与 loader 侧对同一分片生成字节一致的 key(见下)。
+ *
+ * key 一致性是缓存命中的前提:hls.js loader 请求分片时的 context.url 与预取器
+ * 解析出的分片地址,都必须经 `new URL()` 归一化(抹平默认端口/百分号编码差异)。
+ * 播放列表是代理改写形式(/api/proxy?url=…)时分片也是同源地址,两种形式天然一致。
+ */
+
+export const VIDEO_CACHE_NAME = 'libretv-video-v1';
+const META_FLUSH_DEBOUNCE_MS = 30_000;
+
+export interface CacheSettings {
+ enabled: boolean;
+ /** 前向预取窗口(秒):从当前播放位置铺到多远;0 = 无限铺满到片尾 */
+ horizonSeconds: number;
+ /** 单集缓存上限(字节) */
+ maxBytesPerEpisode: number;
+ /** 全局缓存上限(字节) */
+ maxTotalBytes: number;
+}
+
+export const DEFAULT_CACHE_SETTINGS: CacheSettings = {
+ enabled: true,
+ horizonSeconds: 300,
+ maxBytesPerEpisode: 800 * 1024 * 1024,
+ maxTotalBytes: 2 * 1024 * 1024 * 1024,
+};
+
+const SETTINGS_KEY = 'libretv-video-cache-settings';
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), max);
+}
+
+export function normalizeCacheSettings(input: unknown): CacheSettings {
+ const raw = (input ?? {}) as Partial<CacheSettings>;
+ return {
+ enabled: raw.enabled !== false,
+ // 0 = 无限(铺满到片尾);否则 60s ~ 7200s
+ horizonSeconds: raw.horizonSeconds === 0 ? 0 : clamp(raw.horizonSeconds ?? DEFAULT_CACHE_SETTINGS.horizonSeconds, 60, 7200),
+ maxBytesPerEpisode: clamp(raw.maxBytesPerEpisode ?? DEFAULT_CACHE_SETTINGS.maxBytesPerEpisode, 50 * 1024 * 1024, 8 * 1024 * 1024 * 1024),
+ maxTotalBytes: clamp(raw.maxTotalBytes ?? DEFAULT_CACHE_SETTINGS.maxTotalBytes, 100 * 1024 * 1024, 20 * 1024 * 1024 * 1024),
+ };
+}
+
+export function loadCacheSettings(): CacheSettings {
+ try {
+ const raw = localStorage.getItem(SETTINGS_KEY);
+ return normalizeCacheSettings(raw ? JSON.parse(raw) : undefined);
+ } catch {
+ return { ...DEFAULT_CACHE_SETTINGS };
+ }
+}
+
+export function saveCacheSettings(next: Partial<CacheSettings>): CacheSettings {
+ const merged = normalizeCacheSettings({ ...loadCacheSettings(), ...next });
+ try {
+ localStorage.setItem(SETTINGS_KEY, JSON.stringify(merged));
+ } catch { /* 隐私模式等场景忽略 */ }
+ return merged;
+}
+
+/** 分片缓存 key:`new URL()` 归一化(与 hls.js loader 侧一致,缓存命中的前提) */
+export function buildSegmentCacheKey(segmentUrl: string): string {
+ try {
+ return new URL(segmentUrl).href;
+ } catch {
+ return segmentUrl;
+ }
+}
+
+function cacheStore(): CacheStorage | undefined {
+ return typeof caches !== 'undefined' ? caches : undefined;
+}
+
+/** 请求持久化存储(避免浏览器在磁盘压力下清掉缓存;失败静默,不影响功能) */
+export async function ensurePersistentStorage(): Promise<void> {
+ try {
+ if (navigator.storage?.persist) await navigator.storage.persist();
+ } catch { /* 忽略 */ }
+}
+
+export async function hasCachedSegment(key: string): Promise<boolean> {
+ const store = cacheStore();
+ if (!store) return false;
+ try {
+ const cache = await store.open(VIDEO_CACHE_NAME);
+ const hit = await cache.match(key);
+ return !!hit;
+ } catch {
+ return false;
+ }
+}
+
+export interface CachedFragment {
+ data: ArrayBuffer;
+ /** 预取时记录的真实耗时(毫秒),供 loader 合成 hls.js stats */
+ costMs: number;
+}
+
+export async function readCachedSegment(key: string): Promise<CachedFragment | null> {
+ const store = cacheStore();
+ if (!store) return null;
+ try {
+ const cache = await store.open(VIDEO_CACHE_NAME);
+ const hit = await cache.match(key);
+ if (!hit) return null;
+ const data = await hit.arrayBuffer();
+ const meta = await db.segmentMeta.get(key);
+ return { data, costMs: meta?.costMs ?? 150 };
+ } catch {
+ return null;
+ }
+}
+
+export type CachePutResult = 'ok' | 'quota' | 'failed';
+
+/** 写入分片:QuotaExceeded 时先触发两轮 LRU 淘汰再重试一次 */
+export async function putCachedSegmentResilient(
+ key: string,
+ buffer: ArrayBuffer,
+ opts: { episodeKey: string; index: number; costMs: number; settings: CacheSettings }
+): Promise<CachePutResult> {
+ const store = cacheStore();
+ if (!store) return 'failed';
+ const bytes = buffer.byteLength;
+ const put = async (): Promise<CachePutResult> => {
+ try {
+ const cache = await store.open(VIDEO_CACHE_NAME);
+ const headers = new Headers({ 'Content-Type': 'video/mp2t', 'Content-Length': String(bytes) });
+ await cache.put(key, new Response(buffer.slice(0), { headers }));
+ await db.segmentMeta.put({
+ key,
+ episodeKey: opts.episodeKey,
+ index: opts.index,
+ bytes,
+ costMs: Math.max(1, Math.round(opts.costMs)),
+ lastAccess: Date.now(),
+ });
+ return 'ok';
+ } catch (err) {
+ return err instanceof DOMException && err.name === 'QuotaExceededError' ? 'quota' : 'failed';
+ }
+ };
+
+ const first = await put();
+ if (first !== 'quota') return first;
+ await enforceQuota(opts.settings);
+ return put();
+}
+
+/**
+ * 两轮 LRU 淘汰:
+ * ① 按剧集分组,组内按 lastAccess 升序淘汰到单集上限以内;
+ * ② 全局按 lastAccess 升序淘汰到总量上限以内。
+ * 返回删除的分片数。Cache 条目与元数据并行删除,孤儿元数据顺带清理。
+ */
+export async function enforceQuota(settings?: CacheSettings): Promise<number> {
+ const conf = settings ?? loadCacheSettings();
+ const store = cacheStore();
+ if (!store) return 0;
+ try {
+ const cache = await store.open(VIDEO_CACHE_NAME);
+ const metas = await db.segmentMeta.toArray();
+ let removed = 0;
+
+ const remove = async (key: string) => {
+ await cache.delete(key);
+ await db.segmentMeta.delete(key);
+ removed += 1;
+ };
+
+ // ① 单集上限
+ const byEpisode = new Map<string, typeof metas>();
+ for (const m of metas) {
+ const list = byEpisode.get(m.episodeKey) ?? [];
+ list.push(m);
+ byEpisode.set(m.episodeKey, list);
+ }
+ for (const list of byEpisode.values()) {
+ let bytes = list.reduce((sum, m) => sum + m.bytes, 0);
+ if (bytes <= conf.maxBytesPerEpisode) continue;
+ const sorted = [...list].sort((a, b) => a.lastAccess - b.lastAccess);
+ for (const m of sorted) {
+ if (bytes <= conf.maxBytesPerEpisode) break;
+ bytes -= m.bytes;
+ await remove(m.key);
+ }
+ }
+
+ // ② 全局上限
+ let total = (await db.segmentMeta.toArray()).reduce((sum, m) => sum + m.bytes, 0);
+ if (total > conf.maxTotalBytes) {
+ const sorted = (await db.segmentMeta.toArray()).sort((a, b) => a.lastAccess - b.lastAccess);
+ for (const m of sorted) {
+ if (total <= conf.maxTotalBytes) break;
+ total -= m.bytes;
+ await remove(m.key);
+ }
+ }
+ return removed;
+ } catch {
+ return 0;
+ }
+}
+
+/** 命中/读取时刷新 lastAccess;30s 内同 key 只写一次,避免高频写放大 */
+const touchTimers = new Map<string, number>();
+export async function touchMeta(key: string): Promise<void> {
+ const now = Date.now();
+ const last = touchTimers.get(key) ?? 0;
+ if (now - last < META_FLUSH_DEBOUNCE_MS) return;
+ touchTimers.set(key, now);
+ try {
+ const meta = await db.segmentMeta.get(key);
+ if (meta) await db.segmentMeta.update(key, { lastAccess: now });
+ } catch { /* 忽略 */ }
+}
+
+export interface CacheSummary {
+ segments: number;
+ bytes: number;
+ episodes: number;
+}
+
+export async function getCacheSummary(): Promise<CacheSummary> {
+ try {
+ const metas = await db.segmentMeta.toArray();
+ return {
+ segments: metas.length,
+ bytes: metas.reduce((sum, m) => sum + m.bytes, 0),
+ episodes: new Set(metas.map((m) => m.episodeKey)).size,
+ };
+ } catch {
+ return { segments: 0, bytes: 0, episodes: 0 };
+ }
+}
+
+export async function clearVideoCache(): Promise<void> {
+ const store = cacheStore();
+ try {
+ if (store) await store.delete(VIDEO_CACHE_NAME);
+ await db.segmentMeta.clear();
+ } catch { /* 忽略 */ }
+}
+
+export async function deleteEpisodeCache(episodeKey: string): Promise<void> {
+ const store = cacheStore();
+ try {
+ const metas = await db.segmentMeta.where('episodeKey').equals(episodeKey).toArray();
+ if (store) {
+ const cache = await store.open(VIDEO_CACHE_NAME);
+ await Promise.all(metas.map((m) => cache.delete(m.key)));
+ }
+ await db.segmentMeta.bulkDelete(metas.map((m) => m.key));
+ } catch { /* 忽略 */ }
+}
diff --git a/src/lib/video-prefetcher.ts b/src/lib/video-prefetcher.ts
new file mode 100644
index 0000000..ee70761
--- /dev/null
+++ b/src/lib/video-prefetcher.ts
@@ -0,0 +1,313 @@
+import { parseM3u8Playlist, type ParsedPlaylist } from './m3u8-parse';
+import {
+ buildSegmentCacheKey,
+ loadCacheSettings,
+ putCachedSegmentResilient,
+ enforceQuota,
+ ensurePersistentStorage,
+ type CacheSettings,
+} from './video-cache';
+
+/**
+ * 前向片段预取器(借鉴 MoonTV video-prefetcher)。
+ *
+ * 设计要点(这是「视频暂停也继续缓存」的全部秘密):
+ * 预取循环体内**不读取任何播放状态**——不判断 paused、不判断 document.hidden、
+ * 不听播放器事件。循环体只有 fetch 与 cache 写入,因此视频暂停、页面切到
+ * 后台标签页时,队列仍会继续推进。
+ *
+ * `setThrottled()` 是「临时让出带宽」(播放卡顿时由调用方触发),与
+ * 「暂停视频就停缓存」是两件事,不要混用。
+ *
+ * 窗口语义:
+ * - horizonSeconds > 0:从当前播放位置向前铺 horizonSeconds 秒,另回看 30s;
+ * - horizonSeconds = 0:无限模式,铺满到片尾(配额交给字节上限 + LRU)。
+ */
+
+export type PrefetchState = 'idle' | 'parsing' | 'running' | 'done' | 'error' | 'disabled';
+
+export interface PrefetchStats {
+ state: PrefetchState;
+ cached: number;
+ total: number;
+ bytes: number;
+ message?: string;
+}
+
+export interface PrefetchOptions {
+ /** 当前集 m3u8 地址(与播放器 loadSource 一致,直接直连或代理改写形式均可) */
+ m3u8Url: string;
+ currentTime: number;
+ /** 剧集标识 `${source}:${vodId}:${episodeIndex}`(LRU 按集淘汰的分组键) */
+ episodeKey: string;
+ /** 覆盖 CacheSettings.horizonSeconds;0 = 无限铺满(暂停黄金窗口使用) */
+ horizonSeconds?: number;
+ lookBehindSeconds?: number;
+ concurrency?: number;
+ onProgress?: (stats: PrefetchStats) => void;
+}
+
+interface RunDescriptor {
+ m3u8Url: string;
+ episodeKey: string;
+ horizonSeconds: number;
+}
+
+/** 前向余量:正在跑的窗口距播放位置还有 60s 以上时,ensure 不重建 */
+const FORWARD_MARGIN_SECONDS = 60;
+const LOOK_BEHIND_SECONDS_DEFAULT = 30;
+/** 时长缺失时的兜底窗口(分片数) */
+const FALLBACK_MAX_SEGMENTS = 200;
+const PROGRESS_EMIT_INTERVAL_MS = 250;
+const EVICT_INTERVAL_MS = 15_000;
+
+/** 纯函数:按累计时长定位时间点对应的分片下标(第一个「累计结束 ≥ t」的分片) */
+export function indexAtTime(durations: number[], time: number): number {
+ let acc = 0;
+ for (let i = 0; i < durations.length; i++) {
+ acc += durations[i];
+ if (acc >= time) return i;
+ }
+ return Math.max(0, durations.length - 1);
+}
+
+/**
+ * 纯函数:计算预取窗口 [fromIdx, toIdx)(左闭右开)。
+ * horizonSeconds = 0 表示无限(铺到片尾);时长全缺失时按 FALLBACK_MAX_SEGMENTS 兜底。
+ */
+export function computeWindow(
+ durations: number[],
+ currentTime: number,
+ horizonSeconds: number,
+ lookBehindSeconds = LOOK_BEHIND_SECONDS_DEFAULT
+): { fromIdx: number; toIdx: number } {
+ 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 };
+ }
+ 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 };
+}
+
+export function shouldPrefetch(): boolean {
+ const conn = (navigator as { connection?: { saveData?: boolean; effectiveType?: string } }).connection;
+ if (!conn) return true;
+ if (conn.saveData) return false;
+ if (conn.effectiveType && /^(slow-)?2g$/.test(conn.effectiveType)) return false;
+ return true;
+}
+
+export class VideoPrefetcher {
+ private generation = 0;
+ private abort = new AbortController();
+ private throttled = false;
+ private waiters: Array<() => void> = [];
+ private stats: PrefetchStats = { state: 'idle', cached: 0, total: 0, bytes: 0 };
+ private onProgress?: (stats: PrefetchStats) => void;
+ private lastEmit = 0;
+
+ /** 幂等入口:窗口已覆盖请求时不重建,否则中止当前运行并重开 */
+ ensure(options: PrefetchOptions): void {
+ const settings = loadCacheSettings();
+ if (!settings.enabled || !shouldPrefetch()) {
+ this.setState({ state: 'disabled', cached: 0, total: 0, bytes: 0 });
+ return;
+ }
+ const horizon = options.horizonSeconds ?? settings.horizonSeconds;
+ const descriptor: RunDescriptor = { m3u8Url: options.m3u8Url, episodeKey: options.episodeKey, horizonSeconds: horizon };
+
+ // 幂等判断:同一集、同一窗口覆盖足够 → 不打断
+ if (
+ this.stats.state === 'running' &&
+ 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;
+ }
+
+ void this.run(options, settings, descriptor);
+ }
+
+ stop(): void {
+ this.generation += 1;
+ this.abort.abort();
+ this.setState({ state: 'idle', cached: 0, total: 0, bytes: 0 });
+ }
+
+ /** 播放卡顿(video:waiting)时临时让出带宽;playing / 暂停黄金窗口时解除 */
+ setThrottled(value: boolean): void {
+ this.throttled = value;
+ if (!value) {
+ const waiters = this.waiters.splice(0);
+ for (const w of waiters) w();
+ }
+ }
+
+ getStats(): PrefetchStats {
+ return this.stats;
+ }
+
+ // —— 内部运行时状态 ——
+ private descriptor?: RunDescriptor;
+ private currentTime = 0;
+ private windowFromTime = 0;
+ private windowToTime = 0;
+
+ private setState(next: PrefetchStats): void {
+ this.stats = next;
+ const now = Date.now();
+ if (now - this.lastEmit >= PROGRESS_EMIT_INTERVAL_MS || next.state !== 'running') {
+ this.lastEmit = now;
+ this.onProgress?.(next);
+ }
+ }
+
+ private waitForResume(generation: number): Promise<void> {
+ if (!this.throttled || generation !== this.generation) return Promise.resolve();
+ return new Promise((resolve) => {
+ const check = setInterval(() => {
+ if (!this.throttled || generation !== this.generation) {
+ clearInterval(check);
+ resolve();
+ }
+ }, 500);
+ });
+ }
+
+ private async run(options: PrefetchOptions, settings: CacheSettings, descriptor: RunDescriptor): Promise<void> {
+ const generation = ++this.generation;
+ this.abort.abort();
+ this.abort = new AbortController();
+ this.onProgress = options.onProgress;
+ this.descriptor = descriptor;
+ this.currentTime = options.currentTime;
+ this.setState({ state: 'parsing', cached: 0, total: 0, bytes: 0 });
+
+ void ensurePersistentStorage();
+
+ let parsed: ParsedPlaylist;
+ try {
+ parsed = await parseM3u8Playlist(options.m3u8Url);
+ } catch (err) {
+ if (generation !== this.generation) return;
+ this.setState({
+ state: 'error',
+ cached: 0,
+ total: 0,
+ bytes: 0,
+ message: err instanceof Error ? err.message : 'm3u8 解析失败',
+ });
+ return;
+ }
+ if (generation !== this.generation) return;
+ if (parsed.byterange) {
+ this.setState({ state: 'error', cached: 0, total: 0, bytes: 0, message: '该集使用 BYTERANGE 分片,不支持本地缓存' });
+ return;
+ }
+
+ const durations = parsed.segments.map((s) => s.duration);
+ const horizon = descriptor.horizonSeconds;
+ const { fromIdx, toIdx } = computeWindow(durations, options.currentTime, horizon, options.lookBehindSeconds);
+ this.windowFromTime = durations.slice(0, fromIdx).reduce((s, d) => s + d, 0);
+ this.windowToTime = durations.slice(0, toIdx).reduce((s, d) => s + d, 0);
+ this.currentTime = options.currentTime;
+
+ // 队列:先前向,再回看(已在窗口内的跳过)
+ const queue: Array<{ url: string; index: number }> = [];
+ for (let i = fromIdx; i < toIdx; i++) queue.push({ url: parsed.segments[i].url, index: i + 1 });
+ for (let i = Math.max(0, fromIdx - 1); i >= 0; i--) {
+ const behindStart = durations.slice(0, i).reduce((s, d) => s + d, 0);
+ if (options.currentTime - behindStart > (options.lookBehindSeconds ?? 30)) break;
+ queue.push({ url: parsed.segments[i].url, index: i + 1 });
+ }
+ // 去重(回看与前向窗口重叠的片段)
+ const seen = new Set<string>();
+ const taskQueue = queue.filter((t) => {
+ const key = buildSegmentCacheKey(t.url);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+
+ this.setState({ state: 'running', cached: 0, total: taskQueue.length, bytes: 0 });
+ let cursor = 0;
+ let cached = 0;
+ let bytes = 0;
+ let lastEvict = Date.now();
+ const concurrency = Math.min(options.concurrency ?? 3, 4);
+
+ const worker = async (): Promise<void> => {
+ while (cursor < taskQueue.length) {
+ if (generation !== this.generation) return;
+ await this.waitForResume(generation);
+ const task = taskQueue[cursor++];
+ if (!task) return;
+ const key = buildSegmentCacheKey(task.url);
+ const started = performance.now();
+ try {
+ const res = await fetch(task.url, { signal: this.abort.signal, headers: { Accept: '*/*' } });
+ if (!res.ok) continue;
+ const buffer = await res.arrayBuffer();
+ if (generation !== this.generation) return;
+ const costMs = performance.now() - started;
+ const result = await putCachedSegmentResilient(key, buffer, {
+ episodeKey: options.episodeKey,
+ index: task.index,
+ costMs,
+ settings,
+ });
+ if (result === 'ok') {
+ cached += 1;
+ bytes += buffer.byteLength;
+ this.setState({ state: 'running', cached, total: taskQueue.length, bytes });
+ } else if (result === 'quota') {
+ this.setState({ state: 'done', cached, total: taskQueue.length, bytes, message: '存储空间已满,已停止预取' });
+ this.generation += 1; // 终止其他 worker
+ return;
+ }
+ } catch {
+ // 单分片失败不中断队列(网络抖动/源限流),播放侧有自己的重试
+ if (generation !== this.generation) return;
+ }
+ // 周期性触发 LRU 淘汰(写放大与配额的双保险)
+ if (Date.now() - lastEvict > EVICT_INTERVAL_MS) {
+ lastEvict = Date.now();
+ void enforceQuota(settings);
+ }
+ }
+ };
+
+ await Promise.all(Array.from({ length: concurrency }, worker));
+ if (generation !== this.generation) return;
+ this.setState({
+ state: 'done',
+ cached,
+ total: taskQueue.length,
+ bytes,
+ message: cached < taskQueue.length ? '部分分片未缓存(源不可达或存储受限)' : undefined,
+ });
+ }
+}
+
+/** 全站单例:当前集的预取器 */
+let currentPrefetcher: VideoPrefetcher | undefined;
+export function getVideoPrefetcher(): VideoPrefetcher {
+ currentPrefetcher ??= new VideoPrefetcher();
+ return currentPrefetcher;
+}
+
+/** 独立单例:下一集预热(避免打断当前集的预取队列) */
+let nextEpisodePrefetcher: VideoPrefetcher | undefined;
+export function getNextEpisodePrefetcher(): VideoPrefetcher {
+ nextEpisodePrefetcher ??= new VideoPrefetcher();
+ return nextEpisodePrefetcher;
+}