Skip to content

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

feat(quality): 新增来源画质探测与聚合展示 (#934)

0xEthan339222f32df1
diff --git a/src/app/api/quality/route.test.ts b/src/app/api/quality/route.test.ts
new file mode 100644
index 0000000..10f4cf7
--- /dev/null
+++ b/src/app/api/quality/route.test.ts
@@ -0,0 +1,101 @@
+/**
+ * 批量画质探测接口单测:同 URL + detail + 影片的并发请求要合并成一次上游探测,
+ * 但结果仍按各自条目的 sourceKey 返回(直接按 cacheKey 去重会把另一个源的徽章吞掉)。
+ * 上游与鉴权一律 mock,不产生网络请求。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { POST } from './route';
+import type { QualityProbeResult } from '@/lib/types';
+
+const state = vi.hoisted(() => ({
+ /** 模拟 probeQuality 调用次数:用来断言「合并成一次」 */
+ calls: 0,
+ /** 模拟 probeQuality 抛异常(客户端断开) */
+ abort: false,
+ /** 内存缓存,模拟 fetch-utils 内的 getCache/setCache */
+ cache: new Map<string, { value: unknown; expiresAt: number }>(),
+}));
+
+vi.mock('@/lib/api-guard', () => ({
+ // 接口鉴权在本测试范围内不关心,假装放行
+ guardRequest: vi.fn(() => null),
+}));
+
+vi.mock('@/lib/fetch-utils', () => ({
+ getCache: <T,>(key: string): T | undefined => {
+ const hit = state.cache.get(key);
+ return hit && hit.expiresAt > Date.now() ? (hit.value as T) : undefined;
+ },
+ setCache: (key: string, value: unknown, ttlMs: number) => {
+ state.cache.set(key, { value, expiresAt: Date.now() + ttlMs });
+ },
+}));
+
+vi.mock('@/lib/quality-probe', () => ({
+ probeQuality: vi.fn(async () => {
+ state.calls++;
+ if (state.abort) throw new DOMException('aborted', 'AbortError');
+ return { sourceKey: 'mock', vodId: 'mock', height: 1080 };
+ }),
+}));
+
+const item = (key: string, url: string, id = '1') => ({
+ source: { key, name: key, url },
+ id,
+});
+
+function post(items: unknown[]): Request {
+ return new Request('https://local.test/api/quality', {
+ method: 'POST',
+ body: JSON.stringify({ items }),
+ });
+}
+
+beforeEach(() => {
+ state.calls = 0;
+ state.abort = false;
+ state.cache.clear();
+});
+
+describe('POST /api/quality', () => {
+ it('同 URL + detail + 影片的多条请求合并成一次上游探测,但结果按各自 sourceKey 返回', async () => {
+ // 同一份资源挂了两个源(订阅 + 自定义常见),url 与 id 相同、sourceKey 不同
+ const res = await POST(post([item('a', 'https://s.test/api'), item('b', 'https://s.test/api')]));
+ const data = (await res.json()) as { results: QualityProbeResult[] };
+ expect(res.status).toBe(200);
+ expect(state.calls).toBe(1);
+ expect(data.results).toHaveLength(2);
+ expect(data.results.map((r) => r.sourceKey).sort()).toEqual(['a', 'b']);
+ expect(data.results.every((r) => r.height === 1080)).toBe(true);
+ });
+
+ it('探测完成后才写缓存;并发请求缓存未命中时也只会打一次源站', async () => {
+ // 一次性发 6 条且同 key —— 没有合并逻辑的话,cache 还没写入就会 6 次都 miss
+ const res = await POST(
+ post(['1', '2', '3', '4', '5', '6'].map((k) => item(k, 'https://s.test/api')))
+ );
+ const data = (await res.json()) as { results: QualityProbeResult[] };
+ expect(state.calls).toBe(1);
+ expect(data.results).toHaveLength(6);
+ });
+
+ it('第二次同 key 请求命中缓存:不再调 probeQuality', async () => {
+ await POST(post([item('a', 'https://s.test/api')]));
+ expect(state.calls).toBe(1);
+ await POST(post([item('a', 'https://s.test/api')]));
+ expect(state.calls).toBe(1);
+ });
+
+ it('客户端断开等中断:error 为「探测已取消」且不写缓存(下次仍会重试)', async () => {
+ state.abort = true;
+ const res = await POST(post([item('a', 'https://s.test/api')]));
+ const data = (await res.json()) as { results: QualityProbeResult[] };
+ expect(data.results[0]).toMatchObject({ sourceKey: 'a', error: '探测已取消' });
+ expect(state.cache.size).toBe(0);
+
+ state.abort = false;
+ await POST(post([item('a', 'https://s.test/api')]));
+ expect(state.calls).toBe(2);
+ });
+});
diff --git a/src/app/api/quality/route.ts b/src/app/api/quality/route.ts
new file mode 100644
index 0000000..76f23e0
--- /dev/null
+++ b/src/app/api/quality/route.ts
@@ -0,0 +1,159 @@
+import { NextResponse } from 'next/server';
+import { guardRequest } from '@/lib/api-guard';
+import { getCache, setCache } from '@/lib/fetch-utils';
+import { probeQuality } from '@/lib/quality-probe';
+import type { QualityProbeItem, QualityProbeResult } from '@/lib/types';
+
+export const runtime = 'nodejs';
+
+interface QualityBody {
+ items?: unknown;
+}
+
+/** 单次请求最多探测的条目数:一张卡片展开最多十几个源,留足余量且防止被刷 */
+const MAX_ITEMS = 50;
+
+/** 并发上限:一次打满十几个源容易触发源站限流,也会把服务端出站连接占满 */
+const CONCURRENCY = 6;
+
+/** 探测成功缓存 30 分钟:源站短期内不会给同一部剧换片源 */
+const OK_CACHE_TTL = 30 * 60 * 1000;
+
+/** 失败结果短缓存:避免每个用户每次展开都去白打一遍已经挂掉的源 */
+const FAIL_CACHE_TTL = 2 * 60 * 1000;
+
+interface CachedProbe {
+ height?: number;
+ error?: string;
+}
+
+function isProbeItem(v: unknown): v is QualityProbeItem {
+ if (!v || typeof v !== 'object') return false;
+ const item = v as { source?: unknown; id?: unknown };
+ if (!item.source || typeof item.source !== 'object') return false;
+ const source = item.source as Record<string, unknown>;
+ if (typeof source.key !== 'string' || typeof source.url !== 'string') return false;
+ return typeof item.id === 'string' && item.id.length > 0 && item.id.length <= 64;
+}
+
+function cacheKey(item: QualityProbeItem): string {
+ return `quality:${item.source.url.replace(/\/+$/, '')}|${item.source.detail ?? ''}|${item.id}`;
+}
+
+/** 定长并发池:逐个取任务,worker 内部自行兜住异常 */
+async function runWithConcurrency(
+ items: QualityProbeItem[],
+ limit: number,
+ worker: (item: QualityProbeItem) => Promise<void>
+): Promise<void> {
+ let cursor = 0;
+ const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
+ for (;;) {
+ const index = cursor++;
+ if (index >= items.length) return;
+ await worker(items[index]);
+ }
+ });
+ await Promise.all(lanes);
+}
+
+/**
+ * 批量画质探测:
+ * - 默认返回完整 JSON;
+ * - `?stream=1` 以 NDJSON 逐条推送——展开来源面板时先到的先亮,不必等最慢的源。
+ */
+export async function POST(req: Request) {
+ const guarded = guardRequest(req);
+ if (guarded) return guarded;
+
+ let body: QualityBody;
+ try {
+ body = (await req.json()) as QualityBody;
+ } catch {
+ return NextResponse.json({ error: '请求格式错误' }, { status: 400 });
+ }
+
+ if (!Array.isArray(body.items) || body.items.length === 0) {
+ return NextResponse.json({ error: '请提供待探测的条目' }, { status: 400 });
+ }
+ const items = body.items.filter(isProbeItem).slice(0, MAX_ITEMS);
+ if (items.length === 0) {
+ return NextResponse.json({ error: '条目格式无效' }, { status: 400 });
+ }
+
+ const isStream = new URL(req.url).searchParams.get('stream') === '1';
+
+ // 同一「源地址 + detail + 影片」的探测按进程内合并:缓存只在探测完成后才写入,
+ // 并发的重复条目会同时 miss、各打一遍源站,缓存本身挡不住。
+ // 结果仍按条目各自的 sourceKey 返回——直接按 cacheKey 去重会吞掉另一个源的结论,
+ // 那个源在前端就永远拿不到结果、徽章不亮
+ const inflight = new Map<string, Promise<CachedProbe>>();
+
+ const resolveItem = async (item: QualityProbeItem): Promise<QualityProbeResult> => {
+ const key = cacheKey(item);
+ const cached = getCache<CachedProbe>(key);
+ if (cached) {
+ return { sourceKey: item.source.key, vodId: item.id, height: cached.height, error: cached.error };
+ }
+ let pending = inflight.get(key);
+ if (!pending) {
+ pending = (async () => {
+ try {
+ const result = await probeQuality(item, req.signal);
+ const value: CachedProbe = { height: result.height, error: result.error };
+ // 「测不出」(height 缺失且无 error)同样是有效结论,也要缓存,
+ // 否则单码率源每次展开都会被重复探测一遍
+ setCache(key, value, result.error ? FAIL_CACHE_TTL : OK_CACHE_TTL);
+ return value;
+ } catch {
+ // 客户端断开等中断:不缓存、也不作为失败结果下发
+ return { error: '探测已取消' };
+ }
+ })();
+ inflight.set(key, pending);
+ }
+ const value = await pending;
+ return { sourceKey: item.source.key, vodId: item.id, height: value.height, error: value.error };
+ };
+
+ if (!isStream) {
+ const results: QualityProbeResult[] = [];
+ await runWithConcurrency(items, CONCURRENCY, async (item) => {
+ results.push(await resolveItem(item));
+ });
+ return NextResponse.json({ results });
+ }
+
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ let closed = false;
+ const send = (result: QualityProbeResult) => {
+ if (closed) return;
+ try {
+ controller.enqueue(encoder.encode(JSON.stringify(result) + '\n'));
+ } catch {
+ closed = true; // 客户端已断开
+ }
+ };
+ await runWithConcurrency(items, CONCURRENCY, async (item) => {
+ if (closed) return;
+ send(await resolveItem(item));
+ });
+ closed = true;
+ try {
+ controller.close();
+ } catch {
+ /* 已断开 */
+ }
+ },
+ });
+
+ return new Response(stream, {
+ headers: {
+ 'Content-Type': 'application/x-ndjson; charset=utf-8',
+ 'Cache-Control': 'no-store',
+ 'X-Accel-Buffering': 'no',
+ },
+ });
+}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index f9c6b78..cd461c3 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -335,6 +335,7 @@ function HomeContent() {
<AggregatedCard
key={group.key}
group={group}
+ sources={selectedSources}
onOpen={(item) => setDetailItem(item)}
/>
))}
diff --git a/src/app/watch/page.tsx b/src/app/watch/page.tsx
index eda2361..adb5fac 100644
--- a/src/app/watch/page.tsx
+++ b/src/app/watch/page.tsx
@@ -21,6 +21,7 @@ import { enqueueDownload } from '@/components/download-manager';
import { Icon } from '@/components/icon';
import { useAuth } from '@/components/auth';
import { resolveSource, useAppStore } from '@/lib/store';
+import { qualityKey } from '@/lib/quality';
import {
clearProgress,
progressKeyOf,
@@ -248,6 +249,13 @@ function WatchContent() {
onTimeUpdate={handleProgress}
onPause={handleProgress}
onEnded={handleEnded}
+ onQuality={(height) => {
+ // 播放实测是最权威的画质来源,回写后搜索列表里该「源 + 影片」直接显示
+ if (!sourceKey || !vodId) return;
+ useAppStore.getState().setQuality({
+ [qualityKey(sourceKey, vodId)]: { height, from: 'play', timestamp: Date.now() },
+ });
+ }}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
diff --git a/src/components/detail-modal.tsx b/src/components/detail-modal.tsx
index 637b81f..98a05b0 100644
--- a/src/components/detail-modal.tsx
+++ b/src/components/detail-modal.tsx
@@ -5,6 +5,7 @@ import { useRouter } from 'next/navigation';
import { api } from '@/lib/client-api';
import type { SearchResultItem, VideoDetail } from '@/lib/types';
import { buildWatchUrl } from '@/lib/utils';
+import { formatRemarks } from '@/lib/remarks';
import { SmartImage } from './smart-image';
import { useAppStore, resolveSource } from '@/lib/store';
import { useToast } from './toast';
@@ -113,13 +114,15 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;
else toast('复制失败,请检查浏览器权限', 'error');
};
+ // 备注与卡片同源,同样归一化,避免同一部剧在两处显示不同文案
+ const remarks = formatRemarks(info?.remarks);
const metaRows = [
info?.typeName && ['类型', info.typeName],
info?.year && ['年份', info.year],
info?.area && ['地区', info.area],
info?.director && ['导演', info.director],
info?.actor && ['主演', info.actor],
- info?.remarks && ['备注', info.remarks],
+ remarks && ['备注', remarks],
].filter(Boolean) as [string, string][];
return (
diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsx
index 8c0d786..cae50a7 100644
--- a/src/components/player-shell.tsx
+++ b/src/components/player-shell.tsx
@@ -38,6 +38,12 @@ interface PlayerShellProps {
onTimeUpdate?: (position: number, duration: number) => void;
onEnded?: () => void;
onPause?: (position: number, duration: number) => void;
+ /**
+ * 实测画质(视频高度,像素)。
+ * 单码率 m3u8 / 直链的分辨率只能等解码后才知道,播放一次后回写缓存,
+ * 下次搜索同一部剧就能直接显示画质,不必再探测。
+ */
+ onQuality?: (height: number) => void;
/** 恢复策略判源不可用(重试耗尽/格式硬失败)时回调:父级弹出换源面板 */
onRequestSwitchSource?: (reason: string) => void;
}
@@ -54,6 +60,7 @@ export function PlayerShell({
onTimeUpdate,
onEnded,
onPause,
+ onQuality,
onRequestSwitchSource,
}: PlayerShellProps) {
const containerRef = useRef<HTMLDivElement>(null);
@@ -69,11 +76,16 @@ export function PlayerShell({
// 始终持有最新 props/回调,避免重建播放器
const propsRef = useRef({
url, title, adFilter, autoplayNext, episodeKey, nextUrl, nextEpisodeKey,
- getRestorePosition, onTimeUpdate, onEnded, onPause, onRequestSwitchSource,
+ getRestorePosition, onTimeUpdate, onEnded, onPause, onQuality, onRequestSwitchSource,
});
propsRef.current = {
url, title, adFilter, autoplayNext, episodeKey, nextUrl, nextEpisodeKey,
- getRestorePosition, onTimeUpdate, onEnded, onPause, onRequestSwitchSource,
+ getRestorePosition, onTimeUpdate, onEnded, onPause, onQuality, onRequestSwitchSource,
+ };
+
+ /** 上报实测画质:多次上报取大值由调用方决定,这里只管把拿到的高度传出去 */
+ const reportQuality = (height: number) => {
+ if (height > 0) propsRef.current.onQuality?.(height);
};
// 跨集共享、每次换集重置的播放链路状态
@@ -164,6 +176,11 @@ export function PlayerShell({
hls.on(Hls.Events.MANIFEST_PARSED, async () => {
recoveryRef.current?.markHealthy();
+ // master playlist 的档位高度:多码率源在这里就能拿到上限
+ const heights = hls.levels
+ .map((level) => level.height)
+ .filter((h): h is number => typeof h === 'number' && h > 0);
+ if (heights.length > 0) reportQuality(Math.max(...heights));
// 预取锚点:恢复进度时直接取恢复目标。赋值后 video.currentTime 未必立刻反映
// (Safari 系),而 ensure 是以「锚点未变」为前提复用 parsing 中的运行的——
// 这里读到旧值会把窗口建在片头,且白等一次纠错重建。
@@ -187,6 +204,12 @@ export function PlayerShell({
});
// 播放链路恢复(FRAG_LOADED / MANIFEST_PARSED):静默窗外清零连续失败计数
hls.on(Hls.Events.FRAG_LOADED, () => recoveryRef.current?.markHealthy());
+ // 单码率源在 MANIFEST 阶段拿不到 height(清单尚未解析),这里补一次。
+ // 注意 data.level 是档位下标,分辨率在 levelInfo 上
+ hls.on(Hls.Events.LEVEL_LOADED, (_evt, data) => {
+ const height = data.levelInfo?.height;
+ if (typeof height === 'number') reportQuality(height);
+ });
// 分片真正进入 MSE buffer 才算媒体恢复:此时视频轨可渲染,错误态可解除
hls.on(Hls.Events.FRAG_BUFFERED, () => {
mediaHealthyRef.current = true;
@@ -301,6 +324,23 @@ export function PlayerShell({
},
});
artRef.current = art;
+
+ /**
+ * 读解码后的真实分辨率。
+ * 单码率 m3u8 / mp4 直链的清单里没有画质字段,服务端无论如何探测不到,
+ * 只有 video 元素的 videoHeight 是真的——这是「播放一次即记住画质」链路的唯一数据源。
+ * loadedmetadata 在部分浏览器上 videoHeight 仍为 0,因此 resize / canplay / playing
+ * 各补一次机会,不能只赌单一事件时机。
+ */
+ const reportVideoHeight = () => {
+ const height = art.video?.videoHeight;
+ if (typeof height === 'number' && height > 0) reportQuality(height);
+ };
+ art.on('video:loadedmetadata', reportVideoHeight);
+ art.on('video:canplay', reportVideoHeight);
+ // resize 不在 ArtPlayer 的视频事件转发表里,直接挂原生事件
+ art.video?.addEventListener('resize', reportVideoHeight);
+
art.on('video:loadedmetadata', () => {
// ArtPlayer 运行时支持 title 选项(类型定义未覆盖),用于界面标题展示
try {
@@ -315,6 +355,7 @@ export function PlayerShell({
// 仅在媒体真正恢复(有分片进入 buffer)后清错误遮罩:
// 否则「视频轨挂了、音频轨先播出来」时会清掉遮罩,留下黑屏假死态
if (mediaHealthyRef.current) setError('');
+ reportVideoHeight();
});
art.on('video:error', () => {
mediaHealthyRef.current = false;
@@ -461,6 +502,7 @@ export function PlayerShell({
el?.removeEventListener('touchcancel', onTouchEnd);
el?.removeEventListener('touchmove', onTouchMove);
el?.removeEventListener('contextmenu', onContextMenu);
+ art.video?.removeEventListener('resize', reportVideoHeight);
hlsRef.current?.destroy();
hlsRef.current = null;
recoveryRef.current?.dispose();
diff --git a/src/components/video-card.tsx b/src/components/video-card.tsx
index 6efdf48..b7170a6 100644
--- a/src/components/video-card.tsx
+++ b/src/components/video-card.tsx
@@ -1,8 +1,11 @@
'use client';
-import { useEffect, useMemo, useState } from 'react';
-import type { SearchResultItem } from '@/lib/types';
-import { useAppStore } from '@/lib/store';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import type { QualityEntry, SearchResultItem, SourceConfig } from '@/lib/types';
+import { api } from '@/lib/client-api';
+import { useAppStore, readQualities } from '@/lib/store';
+import { QUALITY_FAIL_TTL_MS, qualityKey, qualityLabel } from '@/lib/quality';
+import { formatRemarks, inferGroupRemarks } from '@/lib/remarks';
import { cn } from '@/lib/utils';
import { SmartImage } from './smart-image';
@@ -25,7 +28,9 @@ function buildGroup(name: string, year: string | undefined, items: SearchResultI
year,
typeName: items.find((i) => i.typeName)?.typeName,
pic: items.find((i) => i.pic)?.pic,
- remarks: items.find((i) => i.remarks)?.remarks,
+ // 同一部剧各源文案详略不同(「全34集」/「完结」/「更新至34集」),推到统一结论,
+ // 否则同一部剧的来源列表会看起来状态各异
+ remarks: inferGroupRemarks(items.map((i) => i.remarks)),
items,
};
}
@@ -59,6 +64,48 @@ export function aggregateResults(list: SearchResultItem[]): AggregatedGroup[] {
return groups;
}
+/**
+ * 画质徽章。
+ * 四态:探测中 → 「…」;源站没写画质信息 → 「未知」;探测本身失败 → 「未探到」;
+ * 尚未探测 → 不渲染(展开即发起探测,未探测态几乎不可见)。
+ *
+ * 后两种在数值上完全一样(都没有 height),但成因完全不同:前者是源站是单码率流、
+ * 服务端无论如何测不出;后者是请求被拒/超时。文案与 tooltip 分开,否则用户无法判断
+ * 是该等一等重试,还是只能播一次才知道。
+ */
+function QualityBadge({ entry, loading }: { entry?: QualityEntry; loading?: boolean }) {
+ if (loading) {
+ return <span className="tag bg-chip text-faint shrink-0 animate-pulse">…</span>;
+ }
+ if (!entry) return null;
+ const label = qualityLabel(entry.height);
+ if (!label) {
+ return (
+ <span
+ className="tag bg-chip text-faint shrink-0"
+ title={
+ entry.error
+ ? `画质探测失败:${entry.error}(可能是防盗链或源站超时)`
+ : '单码率或直链,播放列表里没有画质信息;播放一次后会记录实测分辨率'
+ }
+ >
+ {entry.error ? '未探到' : '未知'}
+ </span>
+ );
+ }
+ return (
+ <span
+ className={cn(
+ 'tag font-medium shrink-0',
+ (entry.height ?? 0) >= 1080 ? 'bg-accent/15 text-accent' : 'bg-chip text-muted'
+ )}
+ title={entry.from === 'play' ? '播放时实测的真实分辨率' : '解析播放列表得到的档位'}
+ >
+ {label}
+ </span>
+ );
+}
+
/**
* 聚合影片卡片:
* - 单源:点击直接打开该源详情(与旧体验一致);
@@ -67,9 +114,12 @@ export function aggregateResults(list: SearchResultItem[]): AggregatedGroup[] {
export function AggregatedCard({
group,
onOpen,
+ sources,
}: {
group: AggregatedGroup;
onOpen: (item: SearchResultItem) => void;
+ /** 完整源配置:探测画质需要 source.url / source.detail,搜索结果里只带 sourceUrl */
+ sources?: SourceConfig[];
}) {
const imageProxyMode = useAppStore((s) => s.imageProxyMode);
const customImageProxy = useAppStore((s) => s.customImageProxy);
@@ -77,12 +127,139 @@ export function AggregatedCard({
const [expanded, setExpanded] = useState(false);
const showImg = !!group.pic && !imgFailed;
+ // 画质状态:按 `sourceKey:vodId` 存放。探测完成后一定会有条目
+ // (height 缺失代表「测不出」),所以「无条目」= 尚未探测。
+ const [qualities, setQualities] = useState<Record<string, QualityEntry>>({});
+ const [probing, setProbing] = useState<Record<string, true>>({});
+ // 正在探测中的键:只用于防同一个键并发重复请求,拿到结果或被掐掉就移除
+ const inflightRef = useRef<Set<string>>(new Set());
+ // 拿到终态结果(有画质 / 测不出 / 失败)的键 → 时间。折叠再展开不重复打源站;
+ // 失败是瞬时的,永久锁死会让偶发失败的源再也拿不到画质,所以冷却满 QUALITY_FAIL_TTL_MS 才重试。
+ // 只记「拿到结果」的键:请求被掐掉时没有终态,记下来会让该源被锁到冷却结束
+ const settledRef = useRef<Map<string, number>>(new Map());
+ // 当前批次的键:被下一批掐掉时,靠它把未完成的键解锁
+ const batchRef = useRef<Set<string>>(new Set());
+ const abortRef = useRef<AbortController | null>(null);
+
+ useEffect(() => () => abortRef.current?.abort(), []);
+
+ /**
+ * 展开时懒探测各来源画质。
+ * 不做全页预探测:一次搜索可能几十部片 × 十几个源,全量打会把源站和服务端都压垮,
+ * 而用户真正关心的只有他点开的那一张卡片。
+ */
+ const startQualityProbe = () => {
+ const cached = readQualities(group.items.map((i) => ({ sourceKey: i.sourceKey, vodId: i.vodId })));
+ setQualities((prev) => ({ ...cached, ...prev }));
+
+ const now = Date.now();
+ const selectPending = () =>
+ group.items.filter((i) => {
+ const key = qualityKey(i.sourceKey, i.vodId);
+ const known = cached[key] ?? qualities[key];
+ // 已有结论就不再探:成功和「测不出」都是终态,重探也还是同一个结果
+ if (known && !known.error) return false;
+ // 已在飞:等这一批的结果,不重复打
+ if (inflightRef.current.has(key)) return false;
+ const last = settledRef.current.get(key);
+ if (last === undefined) return true;
+ // 探测失败过:冷却满 QUALITY_FAIL_TTL_MS 才重试,
+ // 否则每次展开都要重打一遍挂掉的源,白等一轮超时
+ return now - last > QUALITY_FAIL_TTL_MS;
+ });
+
+ // 没有新要探的键:让上一批跑完,不打断它(结果回来照样更新徽章)
+ if (selectPending().length === 0) return;
+
+ // 掐掉上一批:本轮要重发,留着只会互相打断。
+ // 同时把它未拿到结果的键解锁——否则这些键既不在飞、又因 inflight 选不进本批,
+ // 徽章会一直空着,直到冷却结束才有机会重探
+ for (const k of batchRef.current) inflightRef.current.delete(k);
+ batchRef.current.clear();
+ abortRef.current?.abort();
+
+ const items = selectPending()
+ .map((i) => {
+ const key = qualityKey(i.sourceKey, i.vodId);
+ const source =
+ sources?.find((s) => s.key === i.sourceKey) ??
+ // 源配置缺失时用搜索结果自带的地址兜底(缺 detail,走不了详情页降级)
+ (i.sourceUrl ? { key: i.sourceKey, name: i.sourceName, url: i.sourceUrl } : undefined);
+ return source ? { key, item: { source, id: i.vodId } } : undefined;
+ })
+ .filter((v): v is { key: string; item: { source: SourceConfig; id: string } } => Boolean(v));
+
+ if (items.length === 0) return;
+ const keys = items.map((i) => i.key);
+ // 探测结果先攒在这里,流结束时一次性写全局缓存:逐条写会让 persist
+ // 把整个状态(含最多 400 条画质记录)序列化十几遍
+ const collected: Record<string, QualityEntry> = {};
+ const batch = new Set(keys);
+ for (const k of keys) inflightRef.current.add(k);
+ batchRef.current = batch;
+ setProbing((prev) => {
+ const next = { ...prev };
+ for (const k of keys) next[k] = true;
+ return next;
+ });
+
+ const controller = new AbortController();
+ abortRef.current = controller;
+
+ const finish = (targets: string[]) => {
+ setProbing((prev) => {
+ const next = { ...prev };
+ for (const k of targets) delete next[k];
+ return next;
+ });
+ };
+
+ api
+ .qualityProbeStream(
+ items.map((i) => i.item),
+ (result) => {
+ const key = qualityKey(result.sourceKey, result.vodId);
+ const entry: QualityEntry = {
+ height: result.height,
+ from: 'probe',
+ error: result.error,
+ timestamp: Date.now(),
+ };
+ // 逐条更新本卡片的徽章(流式效果保留)
+ setQualities((prev) => ({ ...prev, [key]: entry }));
+ collected[key] = entry;
+ // 拿到终态:解锁并发标记,并记下冷却起点
+ inflightRef.current.delete(key);
+ settledRef.current.set(key, Date.now());
+ finish([key]);
+ },
+ controller.signal
+ )
+ .catch(() => {
+ // 探测整批失败(离线/未登录)或被新一轮掐掉:保持「未知」,不打断选源
+ })
+ .finally(() => {
+ // 一次性写入全局缓存:同一部剧在别处(换源面板、再次搜索)也能复用。
+ // 中断时也会走到这里,已拿到的结果不会丢
+ if (Object.keys(collected).length > 0) useAppStore.getState().setQuality(collected);
+ // 本批未拿到终态的键一律解锁,下次展开可以立刻重试
+ for (const k of batch) inflightRef.current.delete(k);
+ if (batchRef.current === batch) batchRef.current.clear();
+ finish(keys);
+ });
+ };
+
const multi = group.items.length > 1;
const adult = useMemo(() => group.items.some((i) => i.isAdult), [group.items]);
const activate = () => {
- if (multi) setExpanded((v) => !v);
- else onOpen(group.items[0]);
+ if (multi) {
+ const next = !expanded;
+ setExpanded(next);
+ if (next) startQualityProbe();
+ } else {
+ onOpen(group.items[0]);
+ }
};
return (
@@ -165,34 +342,67 @@ export function AggregatedCard({
{multi && expanded && (
<div className="border-t border-line p-2.5 animate-fade-in">
<p className="text-[10px] text-faint mb-1.5">选择来源播放</p>
- <div className="flex flex-wrap gap-1.5">
- {group.items.map((item) => (
- <button
- key={`${item.sourceKey}_${item.vodId}`}
- className={cn(
- 'group inline-flex items-center gap-1.5 max-w-full rounded-lg border px-2.5 py-1.5',
- 'text-xs transition-all cursor-pointer',
- 'border-line bg-chip hover:border-accent hover:bg-accent/10',
- item.isAdult && 'border-pink-500/30'
- )}
- onClick={(e) => {
- e.stopPropagation();
- onOpen(item);
- }}
- aria-label={`使用 ${item.sourceName} 播放`}
- >
- <span className="font-medium text-content truncate max-w-[9em]">{item.sourceName}</span>
- <span className="text-faint truncate max-w-[7em]">{item.remarks || '暂无介绍'}</span>
- <svg
- className="w-3.5 h-3.5 text-accent shrink-0 transition-transform group-hover:scale-110"
- fill="currentColor"
- viewBox="0 0 24 24"
- aria-hidden
+ {/*
+ 一行两个源:用 grid 而不是 flex-wrap —— flex 里为了撑满整行必须加 grow,
+ 而 grow 在源数为奇数时会把最后一行的那个按钮拉满整行,与上一行对不齐。
+ grid 的列宽是固定的两等分,落单的按钮自然停在左列。
+ 348px 是两列的下限(按钮摊不到约 148px 后源名会被截成「36…」),再窄退回单列整行。
+ */}
+ <div className="grid grid-cols-1 min-[348px]:grid-cols-2 gap-1.5">
+ {group.items.map((item) => {
+ const itemKey = qualityKey(item.sourceKey, item.vodId);
+ const remarks = formatRemarks(item.remarks);
+ const shownRemarks = (() => {
+ if (!remarks) return undefined;
+ const epMatch = /^(?:全|更新至)(\d+)集$/.exec(remarks);
+ if (epMatch) {
+ // 单集(1集)= 电影/单集影片,没有「更新到第几集」这回事,不显示;
+ // 多集电视剧/综艺才显示集数进度
+ return parseInt(epMatch[1], 10) > 1 ? remarks : undefined;
+ }
+ // 带「全」「更新至」「更新」「更至」前缀但后面不是集数(如「更新HD」):
+ // 前缀对单集影片没有意义,剥掉后保留实际内容(HD / 高清 这类)
+ const prefixMatch = /^(?:全|更(?:新至|新|至))\s*(.+)$/.exec(remarks);
+ if (prefixMatch) return prefixMatch[1].trim() || undefined;
+ // 非集数备注(电影的正片、HD国语 等)原样显示
+ return remarks;
+ })();
+ return (
+ // 两列下一行放不下「源名 + 画质 + 集数 + 图标」,拆成两行:
+ // 上行源名与播放图标,下行画质与集数。信息一项不减,按钮高度 +14px 左右
+ <button
+ key={`${item.sourceKey}_${item.vodId}`}
+ className={cn(
+ 'group flex w-full min-w-0 flex-col gap-1 rounded-lg border px-2.5 py-1.5',
+ 'text-xs transition-all cursor-pointer',
+ 'border-line bg-chip hover:border-accent hover:bg-accent/10',
+ item.isAdult && 'border-pink-500/30'
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpen(item);
+ }}
+ aria-label={`使用 ${item.sourceName} 播放`}
>
- <path d="M8 5v14l11-7z" />
- </svg>
- </button>
- ))}
+ <span className="flex items-center gap-1.5">
+ <span className="font-medium text-content truncate flex-1 min-w-0">{item.sourceName}</span>
+ <svg
+ className="w-3.5 h-3.5 text-accent shrink-0 transition-transform group-hover:scale-110"
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ aria-hidden
+ >
+ <path d="M8 5v14l11-7z" />
+ </svg>
+ </span>
+ <span className="flex min-w-0 items-center gap-1.5">
+ <QualityBadge entry={qualities[itemKey]} loading={probing[itemKey]} />
+ {/* 该源自己的备注:电视剧是它报的集数,电影是「HD国语」这类 */}
+ {shownRemarks && <span className="text-faint truncate flex-1 min-w-0">{shownRemarks}</span>}
+ </span>
+ </button>
+ );
+ })}
</div>
</div>
)}
@@ -251,7 +461,7 @@ export function VideoCard({ item, onClick }: { item: SearchResultItem; onClick:
{item.typeName && <span className="tag bg-accent/15 text-accent">{item.typeName}</span>}
{item.year && <span className="tag bg-purple-500/15 text-purple-600 dark:text-purple-300">{item.year}</span>}
</div>
- <p className="text-xs text-muted line-clamp-2 mb-2">{item.remarks || '暂无介绍'}</p>
+ <p className="text-xs text-muted line-clamp-2 mb-2">{formatRemarks(item.remarks) || '暂无介绍'}</p>
</div>
<div className="flex items-center justify-between mt-auto pt-1.5 border-t border-line">
<span className="tag bg-chip text-muted truncate max-w-[80%]">{item.sourceName}</span>
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index e57383c..9e41b6a 100644
--- a/src/lib/client-api.ts
+++ b/src/lib/client-api.ts
@@ -1,6 +1,6 @@
'use client';
-import type { SearchResponse, SearchStreamEvent, SourceSearchOutcome, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse, SourceListPayload } from './types';
+import type { SearchResponse, SearchStreamEvent, SourceSearchOutcome, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse, SourceListPayload, QualityProbeItem, QualityProbeResult } from './types';
/**
* 客户端 API 封装。401 时触发全局事件打开登录框,
@@ -146,6 +146,27 @@ export const api = {
return request<VideoDetail>(`/api/detail?${sp.toString()}`, { signal });
},
+ /**
+ * 批量画质探测(NDJSON 流式):展开来源面板时逐条回调,先到的源先显示画质。
+ * 结果里的 height 缺失代表「测不出」(单码率 m3u8 / 直链 / 防盗链),不是失败。
+ */
+ qualityProbeStream: async (
+ items: QualityProbeItem[],
+ onResult: (result: QualityProbeResult) => void,
+ signal?: AbortSignal
+ ): Promise<void> => {
+ const res = await fetch('/api/quality?stream=1', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ items }),
+ signal,
+ });
+ throwForAuthStatus(res);
+ if (!res.ok || !res.body) throw new ApiError(`请求失败 (${res.status})`, res.status);
+
+ await consumeNdjson<QualityProbeResult>(res, onResult);
+ },
+
douban: (type: 'movie' | 'tv', tag: string, pageStart: number, pageSize: number, signal?: AbortSignal) => {
const sp = new URLSearchParams({ type, tag, pageStart: String(pageStart), pageSize: String(pageSize) });
return request<DoubanResponse>(`/api/douban?${sp.toString()}`, { signal });
diff --git a/src/lib/codec-parse.test.ts b/src/lib/codec-parse.test.ts
new file mode 100644
index 0000000..86297b2
--- /dev/null
+++ b/src/lib/codec-parse.test.ts
@@ -0,0 +1,373 @@
+import { createCipheriv, randomBytes } from 'node:crypto';
+import { describe, expect, it } from 'vitest';
+import {
+ decryptAes128CbcPrefix,
+ findH264Sps,
+ looksLikeMp4,
+ parseH264Sps,
+ parseMp4VideoResolution,
+ parseTsVideoResolution,
+ unescapeRbsp,
+} from './codec-parse';
+
+/** 位写入器:手写 SPS 的二进制极易出错,用语法元素逐项构造 */
+class BitWriter {
+ private readonly bits: number[] = [];
+
+ writeBits(value: number, n: number): void {
+ for (let i = n - 1; i >= 0; i--) this.bits.push((value >> i) & 1);
+ }
+
+ writeUE(value: number): void {
+ const v = value + 1;
+ const width = v.toString(2).length;
+ for (let i = 0; i < width - 1; i++) this.bits.push(0);
+ this.writeBits(v, width);
+ }
+
+ toBytes(): Uint8Array {
+ const bytes: number[] = [];
+ for (let i = 0; i < this.bits.length; i += 8) {
+ let byte = 0;
+ for (let j = 0; j < 8; j++) byte = (byte << 1) | (this.bits[i + j] ?? 0);
+ bytes.push(byte);
+ }
+ return new Uint8Array(bytes);
+ }
+}
+
+interface SpsOptions {
+ profileIdc?: number;
+ widthInMbs: number;
+ heightInMapUnits: number;
+ frameMbsOnly?: boolean;
+ cropBottom?: number;
+ scalingLists?: boolean;
+}
+
+/** 构造一个最小可用的 H.264 SPS(写到 vui_parameters_present_flag 为止) */
+function buildSps(opts: SpsOptions): Uint8Array {
+ const profileIdc = opts.profileIdc ?? 100;
+ const frameMbsOnly = opts.frameMbsOnly ?? true;
+ const w = new BitWriter();
+ w.writeBits(profileIdc, 8);
+ w.writeBits(0, 8); // constraint flags + reserved
+ w.writeBits(40, 8); // level_idc
+ w.writeUE(0); // seq_parameter_set_id
+
+ if (profileIdc === 100) {
+ w.writeUE(1); // chroma_format_idc = 4:2:0
+ w.writeUE(0); // bit_depth_luma_minus8
+ w.writeUE(0); // bit_depth_chroma_minus8
+ w.writeBits(0, 1); // qpprime_y_zero_transform_bypass_flag
+ w.writeBits(opts.scalingLists ? 1 : 0, 1);
+ if (opts.scalingLists) {
+ // 8 组,前 6 组 16 项、后 2 组 64 项,全部 delta_scale = 0(等价于 ue(0))
+ for (let i = 0; i < 8; i++) {
+ w.writeBits(1, 1); // seq_scaling_list_present_flag
+ const size = i < 6 ? 16 : 64;
+ for (let j = 0; j < size; j++) w.writeUE(0);
+ }
+ }
+ }
+
+ w.writeUE(0); // log2_max_frame_num_minus4
+ w.writeUE(0); // pic_order_cnt_type
+ w.writeUE(2); // log2_max_pic_order_cnt_lsb_minus4
+ w.writeUE(2); // max_num_ref_frames
+ w.writeBits(0, 1); // gaps_in_frame_num_value_allowed_flag
+ w.writeUE(opts.widthInMbs - 1);
+ w.writeUE(opts.heightInMapUnits - 1);
+ w.writeBits(frameMbsOnly ? 1 : 0, 1);
+ if (!frameMbsOnly) w.writeBits(1, 1); // mb_adaptive_frame_field_flag
+ w.writeBits(1, 1); // direct_8x8_inference_flag
+ const cropping = (opts.cropBottom ?? 0) > 0;
+ w.writeBits(cropping ? 1 : 0, 1);
+ if (cropping) {
+ w.writeUE(0);
+ w.writeUE(0);
+ w.writeUE(0);
+ w.writeUE(opts.cropBottom!);
+ }
+ w.writeBits(1, 1); // vui_parameters_present_flag(之后的内容我们不再解析)
+ return w.toBytes();
+}
+
+function concat(parts: Uint8Array[]): Uint8Array {
+ const total = parts.reduce((n, p) => n + p.length, 0);
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const part of parts) {
+ out.set(part, offset);
+ offset += part.length;
+ }
+ return out;
+}
+
+// ——— H.264 SPS ———
+
+describe('parseH264Sps', () => {
+ it('1080P:宏块尺寸裁剪到 1920x1080(1088 减掉底部 4 个裁剪单位)', () => {
+ expect(parseH264Sps(buildSps({ widthInMbs: 120, heightInMapUnits: 68, cropBottom: 4 }))).toEqual({
+ width: 1920,
+ height: 1080,
+ });
+ });
+
+ it('720P:无需裁剪时直接是宏块尺寸', () => {
+ expect(parseH264Sps(buildSps({ widthInMbs: 80, heightInMapUnits: 45 }))).toEqual({
+ width: 1280,
+ height: 720,
+ });
+ });
+
+ it('隔行扫描时高度按两个 field 计算', () => {
+ expect(parseH264Sps(buildSps({ widthInMbs: 45, heightInMapUnits: 15, frameMbsOnly: false }))).toEqual({
+ width: 720,
+ height: 480,
+ });
+ });
+
+ it('带 scaling list 的 High profile 也能正确跳到尺寸字段', () => {
+ // scaling list 是变长的,跳过位数算错的话这里会拿到完全错误的值
+ expect(parseH264Sps(buildSps({ widthInMbs: 120, heightInMapUnits: 68, cropBottom: 4, scalingLists: true }))).toEqual({
+ width: 1920,
+ height: 1080,
+ });
+ });
+
+ it('Baseline profile(无 chroma 扩展字段)', () => {
+ expect(parseH264Sps(buildSps({ profileIdc: 66, widthInMbs: 80, heightInMapUnits: 45 }))).toEqual({
+ width: 1280,
+ height: 720,
+ });
+ });
+
+ it('数据被截断时返回 undefined,而不是给出错误分辨率', () => {
+ expect(parseH264Sps(new Uint8Array([0x64, 0x00]))).toBeUndefined();
+ expect(parseH264Sps(new Uint8Array([]))).toBeUndefined();
+ });
+});
+
+describe('unescapeRbsp', () => {
+ it('去掉防竞争字节 00 00 03 → 00 00', () => {
+ expect([...unescapeRbsp(new Uint8Array([0x00, 0x00, 0x03, 0x01, 0x02]))]).toEqual([0x00, 0x00, 0x01, 0x02]);
+ });
+
+ it('连续的 00 00 03 各自独立处理', () => {
+ expect([...unescapeRbsp(new Uint8Array([0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x05]))]).toEqual([
+ 0x00, 0x00, 0x00, 0x00, 0x05,
+ ]);
+ });
+
+ it('正常数据原样返回', () => {
+ expect([...unescapeRbsp(new Uint8Array([0x67, 0x42, 0x80, 0x1f]))]).toEqual([0x67, 0x42, 0x80, 0x1f]);
+ });
+});
+
+describe('findH264Sps', () => {
+ it('从 Annex-B 流里取出 SPS NAL(跳过 PPS)', () => {
+ const sps = buildSps({ widthInMbs: 120, heightInMapUnits: 68, cropBottom: 4 });
+ const es = concat([
+ new Uint8Array([0x00, 0x00, 0x00, 0x01]),
+ concat([new Uint8Array([0x67]), sps]),
+ new Uint8Array([0x00, 0x00, 0x00, 0x01]),
+ new Uint8Array([0x68, 0xeb, 0xe3, 0xcb]), // PPS
+ ]);
+ const found = findH264Sps(es);
+ expect(found).toBeDefined();
+ expect(parseH264Sps(found!)).toEqual({ width: 1920, height: 1080 });
+ });
+
+ it('没有 SPS 时返回 undefined', () => {
+ expect(findH264Sps(new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x68, 0xeb]))).toBeUndefined();
+ });
+});
+
+// ——— MPEG-TS ———
+
+const TS_SIZE = 188;
+
+function buildTsPacket(pid: number, payload: Uint8Array, payloadStart: boolean): Uint8Array {
+ const packet = new Uint8Array(TS_SIZE).fill(0xff);
+ packet[0] = 0x47;
+ packet[1] = (payloadStart ? 0x40 : 0x00) | ((pid >> 8) & 0x1f);
+ packet[2] = pid & 0xff;
+ packet[3] = 0x10; // 含载荷、无自适应字段
+ packet.set(payload.subarray(0, TS_SIZE - 4), 4);
+ return packet;
+}
+
+/** 把 PES 拆成多个 TS 包(超过单包容量时续包 payloadStart=0) */
+function packetize(pid: number, pes: Uint8Array): Uint8Array[] {
+ const packets: Uint8Array[] = [];
+ let offset = 0;
+ let first = true;
+ while (offset < pes.length) {
+ packets.push(buildTsPacket(pid, pes.subarray(offset, offset + TS_SIZE - 4), first));
+ offset += TS_SIZE - 4;
+ first = false;
+ }
+ return packets;
+}
+
+function buildSection(tableId: number, body: number[], sectionLength: number): Uint8Array {
+ return concat([new Uint8Array([0]), new Uint8Array([tableId, 0xb0, sectionLength]), new Uint8Array(body)]);
+}
+
+function buildPat(pmtPid: number): Uint8Array {
+ // program_number=1 + PMT PID + 4 字节 CRC,section_length = 13
+ return buildSection(0x00, [0x00, 0x01, 0xc1, 0x00, 0x00, 0x00, 0x01, 0xe0 | (pmtPid >> 8), pmtPid & 0xff, 0, 0, 0, 0], 0x0d);
+}
+
+function buildPmt(videoPid: number, streamType = 0x1b): Uint8Array {
+ const pidHigh = 0xe0 | ((videoPid >> 8) & 0x1f);
+ const pidLow = videoPid & 0xff;
+ // 2(program) + 1(version) + 2(section) + 2(PCR) + 2(prog_info_len) + 5(stream) + 4(CRC) = 18
+ return buildSection(0x02, [0x00, 0x01, 0xc1, 0x00, 0x00, pidHigh, pidLow, 0xf0, 0x00, streamType, pidHigh, pidLow, 0xf0, 0x00, 0, 0, 0, 0], 0x12);
+}
+
+function buildPes(es: Uint8Array): Uint8Array {
+ const headerLength = 0;
+ const pes = new Uint8Array(9 + headerLength + es.length);
+ pes.set([0x00, 0x00, 0x01, 0xe0], 0); // 起始码 + 视频 stream_id
+ const length = headerLength + es.length;
+ pes[4] = (length >> 8) & 0xff;
+ pes[5] = length & 0xff;
+ pes[6] = 0x80;
+ pes[7] = 0x00;
+ pes[8] = headerLength;
+ pes.set(es, 9 + headerLength);
+ return pes;
+}
+
+function buildTsWithSps(sps: Uint8Array): Uint8Array {
+ const es = concat([
+ new Uint8Array([0x00, 0x00, 0x00, 0x01]),
+ concat([new Uint8Array([0x67]), sps]),
+ new Uint8Array([0x00, 0x00, 0x00, 0x01]),
+ new Uint8Array([0x68, 0xeb, 0xe3, 0xcb]),
+ ]);
+ return concat([
+ buildTsPacket(0x0000, buildPat(0x1000), true),
+ buildTsPacket(0x1000, buildPmt(0x0100), true),
+ ...packetize(0x0100, buildPes(es)),
+ ]);
+}
+
+describe('parseTsVideoResolution', () => {
+ it('从 PAT → PMT → PES → SPS 链路拿到 1080P', () => {
+ const ts = buildTsWithSps(buildSps({ widthInMbs: 120, heightInMapUnits: 68, cropBottom: 4 }));
+ expect(parseTsVideoResolution(ts)).toEqual({ width: 1920, height: 1080 });
+ });
+
+ it('前面带 padding 时仍能定位同步字节', () => {
+ const ts = buildTsWithSps(buildSps({ widthInMbs: 80, heightInMapUnits: 45 }));
+ const padded = concat([new Uint8Array(37).fill(0xaa), ts]);
+ expect(parseTsVideoResolution(padded)).toEqual({ width: 1280, height: 720 });
+ });
+
+ it('HEVC 轨(stream_type 0x24)不支持,返回 undefined 而不是错误值', () => {
+ const es = concat([new Uint8Array([0x00, 0x00, 0x00, 0x01]), new Uint8Array([0x26, 0x01, 0x02])]);
+ const ts = concat([
+ buildTsPacket(0x0000, buildPat(0x1000), true),
+ buildTsPacket(0x1000, buildPmt(0x0100, 0x24), true),
+ ...packetize(0x0100, buildPes(es)),
+ ]);
+ expect(parseTsVideoResolution(ts)).toBeUndefined();
+ });
+
+ it('不是 TS 流时返回 undefined', () => {
+ expect(parseTsVideoResolution(new Uint8Array(600).fill(0x5a))).toBeUndefined();
+ expect(parseTsVideoResolution(new Uint8Array(0))).toBeUndefined();
+ });
+});
+
+// ——— MP4 / fMP4 ———
+
+function box(type: string, payload: Uint8Array): Uint8Array {
+ const buf = new Uint8Array(8 + payload.length);
+ const size = buf.length;
+ buf[0] = (size >>> 24) & 0xff;
+ buf[1] = (size >>> 16) & 0xff;
+ buf[2] = (size >>> 8) & 0xff;
+ buf[3] = size & 0xff;
+ buf.set([type.charCodeAt(0), type.charCodeAt(1), type.charCodeAt(2), type.charCodeAt(3)], 4);
+ buf.set(payload, 8);
+ return buf;
+}
+
+function buildVisualEntry(type: string, width: number, height: number): Uint8Array {
+ const payload = new Uint8Array(40);
+ payload[24] = (width >> 8) & 0xff;
+ payload[25] = width & 0xff;
+ payload[26] = (height >> 8) & 0xff;
+ payload[27] = height & 0xff;
+ return box(type, payload);
+}
+
+function buildMoov(width: number, height: number, entryType = 'avc1'): Uint8Array {
+ // stsd 是 full box:version/flags(4) + entry_count(4) 之后再放 sample entry
+ const stsdPayload = concat([new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]), buildVisualEntry(entryType, width, height)]);
+ return box('moov', box('trak', box('mdia', box('minf', box('stbl', box('stsd', stsdPayload))))));
+}
+
+describe('parseMp4VideoResolution', () => {
+ it('从 moov → trak → mdia → minf → stbl → stsd → avc1 取出宽高', () => {
+ expect(parseMp4VideoResolution(buildMoov(1920, 1080))).toEqual({ width: 1920, height: 1080 });
+ });
+
+ it('HEVC 的 hvc1 / Dolby 的 dvh1 同样识别', () => {
+ expect(parseMp4VideoResolution(buildMoov(3840, 2160, 'hvc1'))).toEqual({ width: 3840, height: 2160 });
+ expect(parseMp4VideoResolution(buildMoov(1920, 1080, 'dvh1'))).toEqual({ width: 1920, height: 1080 });
+ });
+
+ it('init segment 常见形态:ftyp + moov', () => {
+ const init = concat([box('ftyp', new Uint8Array([0x69, 0x73, 0x6f, 0x6d])), buildMoov(1280, 720)]);
+ expect(parseMp4VideoResolution(init)).toEqual({ width: 1280, height: 720 });
+ });
+
+ it('宽高为 0 的异常条目当作无效', () => {
+ expect(parseMp4VideoResolution(buildMoov(0, 0))).toBeUndefined();
+ });
+
+ it('非 MP4 数据返回 undefined', () => {
+ expect(parseMp4VideoResolution(new Uint8Array(64).fill(0x47))).toBeUndefined();
+ expect(parseMp4VideoResolution(new Uint8Array(0))).toBeUndefined();
+ });
+});
+
+describe('looksLikeMp4', () => {
+ it('按 box 类型判断,而不是看扩展名', () => {
+ expect(looksLikeMp4(box('ftyp', new Uint8Array(4)))).toBe(true);
+ expect(looksLikeMp4(box('styp', new Uint8Array(4)))).toBe(true);
+ expect(looksLikeMp4(concat([new Uint8Array([0x47]), new Uint8Array(60)]))).toBe(false);
+ });
+});
+
+// ——— 解密 ———
+
+describe('decryptAes128CbcPrefix', () => {
+ it('解密分片前缀(只读到不完整块为止,不按 PKCS7 去 padding)', () => {
+ const key = randomBytes(16);
+ const iv = randomBytes(16);
+ const plain = new Uint8Array(300).fill(0x7a);
+ const cipher = createCipheriv('aes-128-cbc', key, iv);
+ cipher.setAutoPadding(false);
+ const encrypted = new Uint8Array(
+ concat([new Uint8Array(cipher.update(Buffer.from(plain.subarray(0, 288)))), new Uint8Array(11).fill(0x11)])
+ );
+ const out = decryptAes128CbcPrefix(encrypted, key, iv);
+ expect(out.length).toBe(288); // 末尾 11 字节不构成整块,丢弃
+ expect([...out]).toEqual([...plain.subarray(0, 288)]);
+ });
+
+ it('密钥或 IV 长度不足时返回空,不抛错', () => {
+ expect(decryptAes128CbcPrefix(new Uint8Array(64), new Uint8Array(8), new Uint8Array(16)).length).toBe(0);
+ expect(decryptAes128CbcPrefix(new Uint8Array(64), new Uint8Array(16), new Uint8Array(4)).length).toBe(0);
+ });
+
+ it('数据不足一个块时返回空', () => {
+ expect(decryptAes128CbcPrefix(new Uint8Array(10), randomBytes(16), randomBytes(16)).length).toBe(0);
+ });
+});
diff --git a/src/lib/codec-parse.ts b/src/lib/codec-parse.ts
new file mode 100644
index 0000000..2b70816
--- /dev/null
+++ b/src/lib/codec-parse.ts
@@ -0,0 +1,432 @@
+import { createDecipheriv } from 'node:crypto';
+
+/**
+ * 直接从媒体分片里解析分辨率。
+ *
+ * 存在的理由:大量采集源给的是**单码率 m3u8**(甚至 mp4 直链),master playlist 里
+ * 没有 #EXT-X-STREAM-INF:RESOLUTION,服务端光靠读 m3u8 永远拿不到画质。
+ * 但分辨率其实就写在视频流的编码数据里——H.264 的 SPS NAL、MP4 的 VisualSampleEntry。
+ * 所以「测不出」时拉一小段分片前缀,从编码层把它挖出来。
+ *
+ * 只做够用的部分:读前缀(几十 KB,SPS 必然在分片开头)、只解析必要的头部字段。
+ * 不做完整 demux,也不解码像素。
+ */
+
+export interface MediaResolution {
+ width: number;
+ height: number;
+}
+
+/** H.264 里带 chroma_format_idc 等扩展字段的 profile(Baseline/Main 没有这些) */
+const H264_HIGH_PROFILES = new Set([100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135]);
+
+/** chroma_format_idc → [SubWidthC, SubHeightC],用于把裁剪偏移换算成像素 */
+function chromaSubsampling(chromaFormatIdc: number): [number, number] {
+ switch (chromaFormatIdc) {
+ case 1: // 4:2:0
+ return [2, 2];
+ case 2: // 4:2:2
+ return [2, 1];
+ default: // 0 单色 / 3 4:4:4
+ return [1, 1];
+ }
+}
+
+/** 按位读取器:SPS 是变长位流(exp-golomb),不能按字节读 */
+class BitReader {
+ private pos = 0;
+
+ constructor(private readonly data: Uint8Array) {}
+
+ readBits(n: number): number {
+ let value = 0;
+ for (let i = 0; i < n; i++) {
+ const byte = this.data[this.pos >> 3];
+ if (byte === undefined) throw new Error('位流已耗尽');
+ value = (value << 1) | ((byte >> (7 - (this.pos & 7))) & 1);
+ this.pos++;
+ }
+ return value;
+ }
+
+ /** 无符号 exp-golomb */
+ readUE(): number {
+ let zeros = 0;
+ while (this.readBits(1) === 0) {
+ zeros++;
+ if (zeros > 32) throw new Error('非法的 exp-golomb 编码');
+ }
+ if (zeros === 0) return 0;
+ return (1 << zeros) - 1 + this.readBits(zeros);
+ }
+
+ /** 有符号 exp-golomb(scaling list 与部分语法元素用) */
+ readSE(): number {
+ const k = this.readUE();
+ return k % 2 === 1 ? (k + 1) / 2 : -k / 2;
+ }
+}
+
+/**
+ * 去掉防竞争字节:编码时把 00 00 00 / 00 00 01 之类的序列插成 00 00 03 xx,
+ * 解析前必须还原,否则后续的 exp-golomb 会读到错误的值。
+ */
+export function unescapeRbsp(src: Uint8Array): Uint8Array {
+ const out: number[] = [];
+ let zeros = 0;
+ for (let i = 0; i < src.length; i++) {
+ const byte = src[i];
+ if (zeros === 2 && byte === 3) {
+ zeros = 0;
+ continue;
+ }
+ out.push(byte);
+ zeros = byte === 0 ? zeros + 1 : 0;
+ }
+ return new Uint8Array(out);
+}
+
+/** 跳过 scaling list:High profile 常见,跳错位数后面全乱 */
+function skipScalingLists(reader: BitReader, chromaFormatIdc: number): void {
+ const count = chromaFormatIdc !== 3 ? 8 : 12;
+ for (let i = 0; i < count; i++) {
+ if (reader.readBits(1) === 0) continue;
+ const size = i < 6 ? 16 : 64;
+ for (let j = 0; j < size; j++) reader.readSE();
+ }
+}
+
+/**
+ * 解析 H.264 SPS 得到画面尺寸。
+ * 读到 vui_parameters 就停——后面的字段对分辨率没有影响。
+ */
+export function parseH264Sps(rbsp: Uint8Array): MediaResolution | undefined {
+ try {
+ const reader = new BitReader(rbsp);
+ const profileIdc = reader.readBits(8);
+ reader.readBits(8); // constraint_set flags + reserved
+ reader.readBits(8); // level_idc
+ reader.readUE(); // seq_parameter_set_id
+
+ let chromaFormatIdc = 1;
+ if (H264_HIGH_PROFILES.has(profileIdc)) {
+ chromaFormatIdc = reader.readUE();
+ if (chromaFormatIdc === 3) reader.readBits(1); // separate_colour_plane_flag
+ reader.readUE(); // bit_depth_luma_minus8
+ reader.readUE(); // bit_depth_chroma_minus8
+ reader.readBits(1); // qpprime_y_zero_transform_bypass_flag
+ if (reader.readBits(1)) skipScalingLists(reader, chromaFormatIdc);
+ }
+
+ reader.readUE(); // log2_max_frame_num_minus4
+ const picOrderCntType = reader.readUE();
+ if (picOrderCntType === 0) {
+ reader.readUE(); // log2_max_pic_order_cnt_lsb_minus4
+ } else if (picOrderCntType === 1) {
+ reader.readBits(1); // delta_pic_order_always_zero_flag
+ reader.readSE(); // offset_for_non_ref_pic
+ reader.readSE(); // offset_for_top_to_bottom_field
+ const cycles = reader.readUE();
+ for (let i = 0; i < cycles; i++) reader.readSE();
+ }
+
+ reader.readUE(); // max_num_ref_frames
+ reader.readBits(1); // gaps_in_frame_num_value_allowed_flag
+ const widthInMbs = reader.readUE() + 1;
+ const heightInMapUnits = reader.readUE() + 1;
+ const frameMbsOnly = reader.readBits(1);
+ if (!frameMbsOnly) reader.readBits(1); // mb_adaptive_frame_field_flag
+ reader.readBits(1); // direct_8x8_inference_flag
+
+ const cropped = reader.readBits(1);
+ let cropLeft = 0;
+ let cropRight = 0;
+ let cropTop = 0;
+ let cropBottom = 0;
+ if (cropped) {
+ cropLeft = reader.readUE();
+ cropRight = reader.readUE();
+ cropTop = reader.readUE();
+ cropBottom = reader.readUE();
+ }
+
+ let width = widthInMbs * 16;
+ // 隔行扫描时每帧占两个 field,高度要翻倍
+ let height = (2 - frameMbsOnly) * heightInMapUnits * 16;
+ if (cropped) {
+ const [subWidthC, subHeightC] = chromaSubsampling(chromaFormatIdc);
+ width -= (cropLeft + cropRight) * subWidthC;
+ height -= (cropTop + cropBottom) * subHeightC * (2 - frameMbsOnly);
+ }
+ if (width <= 0 || height <= 0) return undefined;
+ return { width, height };
+ } catch {
+ // 位流不规则/被截断:宁可返回「未知」,也不要给出一个错的分辨率
+ return undefined;
+ }
+}
+
+/** Annex-B 流的起始码位置(00 00 01) */
+function findStartCodes(es: Uint8Array, limit = 64): number[] {
+ const positions: number[] = [];
+ for (let i = 2; i < es.length && positions.length < limit; i++) {
+ if (es[i] === 1 && es[i - 1] === 0 && es[i - 2] === 0) positions.push(i + 1);
+ }
+ return positions;
+}
+
+/** 在 Annex-B 基本流里找 SPS(NAL type 7)的 RBSP */
+export function findH264Sps(es: Uint8Array): Uint8Array | undefined {
+ const starts = findStartCodes(es);
+ for (let i = 0; i < starts.length; i++) {
+ const from = starts[i];
+ const to = i + 1 < starts.length ? starts[i + 1] - 3 : es.length;
+ if (to <= from) continue;
+ const nal = es.subarray(from, to);
+ if ((nal[0] & 0x1f) === 7) return unescapeRbsp(nal.subarray(1));
+ }
+ return undefined;
+}
+
+// ——— MPEG-TS ———
+
+const TS_PACKET_SIZE = 188;
+const MAX_ES_BYTES = 256 * 1024;
+
+interface TsPacket {
+ pid: number;
+ payloadStart: boolean;
+ payload: Uint8Array;
+}
+
+/** 定位 TS 同步位置:允许前面有 padding,靠连续 3 个包头的 0x47 判定 */
+function findTsOffset(buf: Uint8Array): number {
+ const max = Math.min(buf.length, TS_PACKET_SIZE * 4);
+ for (let i = 0; i < max; i++) {
+ if (
+ buf[i] === 0x47 &&
+ buf[i + TS_PACKET_SIZE] === 0x47 &&
+ buf[i + TS_PACKET_SIZE * 2] === 0x47
+ ) {
+ return i;
+ }
+ }
+ // 退化:只要第一个字节是 0x47 就试(有些分片起始处只有一两个包)
+ return buf[0] === 0x47 ? 0 : -1;
+}
+
+function* readTsPackets(buf: Uint8Array, start: number): Generator<TsPacket> {
+ for (let i = start; i + TS_PACKET_SIZE <= buf.length; i += TS_PACKET_SIZE) {
+ if (buf[i] !== 0x47) continue; // 同步丢失,跳过这个包
+ const pid = ((buf[i + 1] & 0x1f) << 8) | buf[i + 2];
+ const payloadStart = (buf[i + 1] & 0x40) !== 0;
+ const hasAdaptation = (buf[i + 3] & 0x20) !== 0;
+ const hasPayload = (buf[i + 3] & 0x10) !== 0;
+ if (!hasPayload) continue;
+ let payloadBegin = i + 4;
+ if (hasAdaptation) payloadBegin += 1 + buf[i + 4];
+ if (payloadBegin >= i + TS_PACKET_SIZE) continue;
+ yield { pid, payloadStart, payload: buf.subarray(payloadBegin, i + TS_PACKET_SIZE) };
+ }
+}
+
+/** PAT:返回第一个节目对应的 PMT PID */
+function parsePat(payload: Uint8Array): number {
+ const begin = 1 + payload[0]; // 跳过 pointer_field
+ if (begin + 8 > payload.length) return -1;
+ if (payload[begin] !== 0x00) return -1;
+ const sectionLength = ((payload[begin + 1] & 0x0f) << 8) | payload[begin + 2];
+ const end = begin + 3 + sectionLength - 4; // 末尾 4 字节是 CRC
+ for (let p = begin + 8; p + 4 <= end && p + 4 <= payload.length; p += 4) {
+ const programNumber = (payload[p] << 8) | payload[p + 1];
+ if (programNumber === 0) continue; // NIT,不是节目
+ return ((payload[p + 2] & 0x1f) << 8) | payload[p + 3];
+ }
+ return -1;
+}
+
+/** PMT:返回 H.264 视频轨的 PID(0x1b)。HEVC(0x24) 不解析——见文件末尾说明 */
+function parsePmt(payload: Uint8Array): number {
+ const begin = 1 + payload[0];
+ if (begin + 12 > payload.length) return -1;
+ if (payload[begin] !== 0x02) return -1;
+ const sectionLength = ((payload[begin + 1] & 0x0f) << 8) | payload[begin + 2];
+ const end = begin + 3 + sectionLength - 4;
+ const programInfoLength = ((payload[begin + 10] & 0x0f) << 8) | payload[begin + 11];
+ let p = begin + 12 + programInfoLength;
+ while (p + 5 <= end && p + 5 <= payload.length) {
+ const streamType = payload[p];
+ const pid = ((payload[p + 1] & 0x1f) << 8) | payload[p + 2];
+ const esInfoLength = ((payload[p + 3] & 0x0f) << 8) | payload[p + 4];
+ if (streamType === 0x1b) return pid;
+ p += 5 + esInfoLength;
+ }
+ return -1;
+}
+
+/** 把指定 PID(或全部 PID)的 PES 载荷拼成连续的基本流 */
+function collectElementaryStream(buf: Uint8Array, start: number, videoPid: number): Uint8Array {
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (const packet of readTsPackets(buf, start)) {
+ // videoPid < 0 表示 PMT 解析失败,退化为拼所有包——多数源只有一个视频轨
+ if (videoPid >= 0 && packet.pid !== videoPid) continue;
+ let payload = packet.payload;
+ if (packet.payloadStart) {
+ // PES 头:起始码 00 00 01 + stream_id + 长度 + 可选头
+ if (payload.length > 9 && payload[0] === 0 && payload[1] === 0 && payload[2] === 1) {
+ const esBegin = 9 + payload[8];
+ if (esBegin >= payload.length) continue;
+ payload = payload.subarray(esBegin);
+ }
+ }
+ chunks.push(payload);
+ total += payload.length;
+ if (total >= MAX_ES_BYTES) break;
+ }
+ const es = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ es.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return es;
+}
+
+/** 解析 TS 分片得到分辨率 */
+export function parseTsVideoResolution(buf: Uint8Array): MediaResolution | undefined {
+ const start = findTsOffset(buf);
+ if (start < 0) return undefined;
+
+ let pmtPid = -1;
+ let videoPid = -1;
+ for (const packet of readTsPackets(buf, start)) {
+ if (!packet.payloadStart) continue;
+ if (pmtPid < 0 && packet.pid === 0x0000) {
+ pmtPid = parsePat(packet.payload);
+ continue;
+ }
+ if (pmtPid >= 0 && packet.pid === pmtPid) {
+ videoPid = parsePmt(packet.payload);
+ break;
+ }
+ }
+
+ const es = collectElementaryStream(buf, start, videoPid);
+ if (es.length === 0) return undefined;
+ const sps = findH264Sps(es);
+ if (!sps) return undefined;
+ return parseH264Sps(sps);
+}
+
+// ——— MP4 / fMP4 ———
+
+/** 承载分辨率的 visual sample entry */
+const VISUAL_BOXES = new Set(['avc1', 'avc3', 'hvc1', 'hev1', 'mp4v', 'encv', 'dvh1', 'dvhe']);
+/** 需要继续下钻的容器 box,值为其头部长度(stsd 是 full box,多了 4 字节) */
+const CONTAINER_BOXES: Record<string, number> = {
+ moov: 8,
+ trak: 8,
+ mdia: 8,
+ minf: 8,
+ stbl: 8,
+ stsd: 16,
+};
+
+function readU32(buf: Uint8Array, offset: number): number {
+ return (
+ ((buf[offset] << 24) >>> 0) + (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3]
+ );
+}
+
+function boxType(buf: Uint8Array, offset: number): string {
+ return String.fromCharCode(buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3]);
+}
+
+/**
+ * VisualSampleEntry 的宽高:
+ * SampleEntry(6 保留 + 2 data_reference_index) + 2 pre_defined + 2 reserved + 12 pre_defined
+ * = 载荷偏移 24,宽高各 16 位固定点整数。
+ */
+function readVisualSampleEntry(buf: Uint8Array, boxStart: number): MediaResolution | undefined {
+ const offset = boxStart + 8 + 24;
+ if (offset + 4 > buf.length) return undefined;
+ const width = (buf[offset] << 8) | buf[offset + 1];
+ const height = (buf[offset + 2] << 8) | buf[offset + 3];
+ if (width <= 0 || height <= 0) return undefined;
+ return { width, height };
+}
+
+function isPrintableType(type: string): boolean {
+ for (let i = 0; i < type.length; i++) {
+ const code = type.charCodeAt(i);
+ if (code < 0x20 || code > 0x7e) return false;
+ }
+ return true;
+}
+
+function scanBoxes(buf: Uint8Array, from: number, to: number): MediaResolution | undefined {
+ let p = from;
+ while (p + 8 <= to) {
+ const type = boxType(buf, p + 4);
+ if (!isPrintableType(type)) return undefined;
+ let size = readU32(buf, p);
+ let header = 8;
+ if (size === 1) {
+ if (p + 16 > to) return undefined;
+ const high = readU32(buf, p + 8);
+ const low = readU32(buf, p + 12);
+ if (high !== 0) return undefined; // 超过 4GB,分片前缀里不可能
+ size = low;
+ header = 16;
+ }
+ if (size === 0) size = to - p;
+ if (size < header || p + size > to) return undefined;
+ if (VISUAL_BOXES.has(type)) {
+ const found = readVisualSampleEntry(buf, p);
+ if (found) return found;
+ }
+ const childHeader = CONTAINER_BOXES[type];
+ if (childHeader !== undefined) {
+ const found = scanBoxes(buf, p + childHeader, p + size);
+ if (found) return found;
+ }
+ p += size;
+ }
+ return undefined;
+}
+
+/** 解析 MP4 / fMP4(init segment)得到分辨率 */
+export function parseMp4VideoResolution(buf: Uint8Array): MediaResolution | undefined {
+ return scanBoxes(buf, 0, buf.length);
+}
+
+/** 是否以 MP4 box 开头:用来在拿不到扩展名时判断分片是 fMP4 还是 TS */
+export function looksLikeMp4(buf: Uint8Array): boolean {
+ if (buf.length < 12) return false;
+ const type = boxType(buf, 4);
+ return type === 'ftyp' || type === 'styp' || type === 'moov' || type === 'moof';
+}
+
+// ——— 解密 ———
+
+/**
+ * AES-128-CBC 解密分片前缀。
+ * 只处理完整的 16 字节块:我们只读了分片开头一小段,末尾必然是不完整块,
+ * 交给 update 而不调用 final,否则 Node 会按 PKCS7 去 padding 并报错。
+ */
+export function decryptAes128CbcPrefix(buf: Uint8Array, key: Uint8Array, iv: Uint8Array): Uint8Array {
+ const usable = Math.floor(buf.length / 16) * 16;
+ if (usable === 0 || key.length < 16 || iv.length < 16) return new Uint8Array(0);
+ const decipher = createDecipheriv('aes-128-cbc', key.subarray(0, 16), iv.subarray(0, 16));
+ decipher.setAutoPadding(false);
+ const out = decipher.update(buf.subarray(0, usable));
+ return new Uint8Array(out.buffer, out.byteOffset, out.byteLength);
+}
+
+/**
+ * 已知不支持:HEVC/H.265 的 SPS。
+ * TS 里能识别到它的 PID,但解析尺寸要正确跳过 profile_tier_level(含 33 位保留位与
+ * 子层循环),逻辑繁琐且缺少真实样本可验证,写错会静默给出错误分辨率——
+ * 那比「未知」更糟。这类源仍会显示「未知」,播放一次后由播放器实测补上。
+ */
diff --git a/src/lib/quality-probe.test.ts b/src/lib/quality-probe.test.ts
new file mode 100644
index 0000000..c1e6e81
--- /dev/null
+++ b/src/lib/quality-probe.test.ts
@@ -0,0 +1,328 @@
+import { describe, expect, it, vi } from 'vitest';
+import { probeEpisodeOrder, probeQuality } from './quality-probe';
+import type { SourceConfig } from './types';
+
+const mocks = vi.hoisted(() => ({ fetchUpstream: vi.fn() }));
+vi.mock('./fetch-utils', () => ({ fetchUpstream: mocks.fetchUpstream }));
+// 探测 대상由用例自己提供,跳过 SSRF 校验(那是 ssrf.test.ts 的职责)
+vi.mock('./ssrf', () => ({ checkUpstreamAllowed: () => Promise.resolve({ ok: true }) }));
+
+/**
+ * 集成测试:验证「m3u8 测不出 → 下沉到分片解析」这条降级链路真的接通。
+ * 解析器本身由 codec-parse.test.ts 覆盖,这里关心的是拼接环节:
+ * 什么时候该走分片、请求哪个 URL、失败时该返回什么。
+ */
+
+const SOURCE: SourceConfig = { key: 'demo', name: 'demo', url: 'https://api.test/api.php/provide/vod' };
+const PLAYLIST_URL = 'https://cdn.test/2024/01/abc/index.m3u8';
+
+const MASTER = `#EXTM3U
+#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080
+1080/index.m3u8
+#EXT-X-STREAM-INF:BANDWIDTH=2500000,RESOLUTION=1280x720
+720/index.m3u8
+`;
+
+const SINGLE_TS = `#EXTM3U
+#EXT-X-TARGETDURATION:10
+#EXT-X-MEDIA-SEQUENCE:0
+#EXTINF:10.0,
+seg0.ts
+#EXT-X-ENDLIST
+`;
+
+const FMP4 = `#EXTM3U
+#EXT-X-TARGETDURATION:10
+#EXT-X-MAP:URI="init.mp4"
+#EXTINF:10.0,
+seg0.m4s
+#EXT-X-ENDLIST
+`;
+
+// ——— 最小 TS/SPS 构造(只够解析出 1920x1080) ———
+
+class BitWriter {
+ private readonly bits: number[] = [];
+ writeBits(value: number, n: number): void {
+ for (let i = n - 1; i >= 0; i--) this.bits.push((value >> i) & 1);
+ }
+ writeUE(value: number): void {
+ const v = value + 1;
+ const width = v.toString(2).length;
+ for (let i = 0; i < width - 1; i++) this.bits.push(0);
+ this.writeBits(v, width);
+ }
+ toBytes(): Uint8Array {
+ const bytes: number[] = [];
+ for (let i = 0; i < this.bits.length; i += 8) {
+ let byte = 0;
+ for (let j = 0; j < 8; j++) byte = (byte << 1) | (this.bits[i + j] ?? 0);
+ bytes.push(byte);
+ }
+ return new Uint8Array(bytes);
+ }
+}
+
+function buildSps1080(): Uint8Array {
+ const w = new BitWriter();
+ w.writeBits(100, 8); // High profile
+ w.writeBits(0, 8);
+ w.writeBits(40, 8); // level
+ w.writeUE(0); // sps id
+ w.writeUE(1); // chroma 4:2:0
+ w.writeUE(0);
+ w.writeUE(0);
+ w.writeBits(0, 1);
+ w.writeBits(0, 1); // 无 scaling list
+ w.writeUE(0); // log2_max_frame_num
+ w.writeUE(0); // pic_order_cnt_type
+ w.writeUE(2);
+ w.writeUE(2); // max_num_ref_frames
+ w.writeBits(0, 1);
+ w.writeUE(119); // 120 MBs → 1920
+ w.writeUE(67); // 68 → 1088
+ w.writeBits(1, 1); // frame_mbs_only
+ w.writeBits(1, 1); // direct_8x8_inference
+ w.writeBits(1, 1); // frame_cropping
+ w.writeUE(0);
+ w.writeUE(0);
+ w.writeUE(0);
+ w.writeUE(4); // 1088 - 4*2 = 1080
+ w.writeBits(1, 1); // vui_present
+ return w.toBytes();
+}
+
+const TS_SIZE = 188;
+
+function tsPacket(pid: number, payload: Uint8Array, payloadStart: boolean): Uint8Array {
+ const packet = new Uint8Array(TS_SIZE).fill(0xff);
+ packet[0] = 0x47;
+ packet[1] = (payloadStart ? 0x40 : 0x00) | ((pid >> 8) & 0x1f);
+ packet[2] = pid & 0xff;
+ packet[3] = 0x10;
+ packet.set(payload.subarray(0, TS_SIZE - 4), 4);
+ return packet;
+}
+
+function concat(parts: Uint8Array[]): Uint8Array {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let offset = 0;
+ for (const part of parts) {
+ out.set(part, offset);
+ offset += part.length;
+ }
+ return out;
+}
+
+function section(tableId: number, body: number[], length: number): Uint8Array {
+ return concat([new Uint8Array([0, tableId, 0xb0, length]), new Uint8Array(body)]);
+}
+
+function buildTs(): Uint8Array {
+ const pmtPid = 0x1000;
+ const videoPid = 0x0100;
+ const pat = section(0x00, [0, 1, 0xc1, 0, 0, 0, 1, 0xe0 | (pmtPid >> 8), pmtPid & 0xff, 0, 0, 0, 0], 0x0d);
+ const pmt = section(
+ 0x02,
+ [0, 1, 0xc1, 0, 0, 0xe1, 0x00, 0xf0, 0x00, 0x1b, 0xe1, 0x00, 0xf0, 0x00, 0, 0, 0, 0],
+ 0x12
+ );
+ const es = concat([
+ new Uint8Array([0, 0, 0, 1]),
+ concat([new Uint8Array([0x67]), buildSps1080()]),
+ new Uint8Array([0, 0, 0, 1, 0x68, 0xeb]),
+ ]);
+ const pes = new Uint8Array(9 + es.length);
+ pes.set([0, 0, 1, 0xe0], 0);
+ pes[4] = (es.length >> 8) & 0xff;
+ pes[5] = es.length & 0xff;
+ pes[6] = 0x80;
+ pes[8] = 0;
+ pes.set(es, 9);
+ return concat([tsPacket(0, pat, true), tsPacket(pmtPid, pmt, true), tsPacket(videoPid, pes, true)]);
+}
+
+function box(type: string, payload: Uint8Array): Uint8Array {
+ const buf = new Uint8Array(8 + payload.length);
+ buf[0] = (buf.length >>> 24) & 0xff;
+ buf[1] = (buf.length >>> 16) & 0xff;
+ buf[2] = (buf.length >>> 8) & 0xff;
+ buf[3] = buf.length & 0xff;
+ buf.set([type.charCodeAt(0), type.charCodeAt(1), type.charCodeAt(2), type.charCodeAt(3)], 4);
+ buf.set(payload, 8);
+ return buf;
+}
+
+function buildInitMp4(): Uint8Array {
+ const entry = new Uint8Array(40);
+ entry[24] = (1920 >> 8) & 0xff;
+ entry[25] = 1920 & 0xff;
+ entry[26] = (1080 >> 8) & 0xff;
+ entry[27] = 1080 & 0xff;
+ const stsd = concat([new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]), box('avc1', entry)]);
+ return box('moov', box('trak', box('mdia', box('minf', box('stbl', box('stsd', stsd))))));
+}
+
+/** 二进制响应:Uint8Array 直接交给 Response 在 TS 下类型不匹配,取底层 ArrayBuffer */
+function bytesResponse(bytes: Uint8Array): Response {
+ return new Response(bytes.slice().buffer as ArrayBuffer, { status: 200 });
+}
+
+/** 按 URL 返回不同的上游响应;未匹配返回 404 */
+function route(url: string): Response {
+ if (url.includes('ac=videolist')) {
+ // CMS 的 vod_play_url 是「集名$地址」格式,裸 URL 会被解析成空
+ const body = JSON.stringify({ list: [{ vod_id: '123', vod_name: '测试影片', vod_play_url: `第1集$${PLAYLIST_URL}` }] });
+ return new Response(body, { status: 200 });
+ }
+ if (url === PLAYLIST_URL) return new Response(currentPlaylist, { status: 200 });
+ if (url.endsWith('.ts')) return bytesResponse(buildTs());
+ if (url.endsWith('init.mp4')) return bytesResponse(buildInitMp4());
+ return new Response('not found', { status: 404 });
+}
+
+let currentPlaylist = SINGLE_TS;
+
+function urls(): string[] {
+ return mocks.fetchUpstream.mock.calls.map((call) => call[0] as string);
+}
+
+describe('probeEpisodeOrder', () => {
+ it('多集:中间集优先,最后一集作为换集重试的对象', () => {
+ expect(probeEpisodeOrder(['a', 'b', 'c'])).toEqual(['b', 'c']);
+ expect(probeEpisodeOrder(['a', 'b', 'c', 'd', 'e'])).toEqual(['c', 'e']);
+ });
+
+ it('两集时不重复:中间集就是最后一集', () => {
+ expect(probeEpisodeOrder(['a', 'b'])).toEqual(['b']);
+ });
+
+ it('单集影片(电影)只有一集可探', () => {
+ expect(probeEpisodeOrder(['a'])).toEqual(['a']);
+ expect(probeEpisodeOrder([])).toEqual([]);
+ });
+});
+
+describe('probeQuality 降级到分片解析', () => {
+ it('多码率 master playlist 直接解析档位,不再下载分片', async () => {
+ currentPlaylist = MASTER;
+ mocks.fetchUpstream.mockImplementation((url: string) => Promise.resolve(route(url)));
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBe(1080);
+ // 详情接口 + m3u8,仅此两次:多码率源没有理由再拉分片
+ expect(urls()).toEqual([
+ 'https://api.test/api.php/provide/vod?ac=videolist&ids=123',
+ PLAYLIST_URL,
+ ]);
+ });
+
+ it('单码率 m3u8:下沉到 TS 分片,从 SPS 拿到 1080', async () => {
+ currentPlaylist = SINGLE_TS;
+ mocks.fetchUpstream.mockImplementation((url: string) => Promise.resolve(route(url)));
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBe(1080);
+ // 关键:m3u8 里的 seg0.ts 是相对路径,必须按播放列表地址拼对
+ expect(urls()).toContain('https://cdn.test/2024/01/abc/seg0.ts');
+ });
+
+ it('fMP4:优先取 init segment(moov 在里面),不去下载媒体分片', async () => {
+ currentPlaylist = FMP4;
+ mocks.fetchUpstream.mockImplementation((url: string) => Promise.resolve(route(url)));
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBe(1080);
+ expect(urls()).toContain('https://cdn.test/2024/01/abc/init.mp4');
+ expect(urls().some((u) => u.endsWith('.m4s'))).toBe(false);
+ });
+
+ it('SAMPLE-AES 加密:服务端解不开,放弃而不是给出错误分辨率', async () => {
+ currentPlaylist = `#EXTM3U
+#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://fairplay"
+#EXTINF:10.0,
+seg0.ts
+`;
+ mocks.fetchUpstream.mockImplementation((url: string) => Promise.resolve(route(url)));
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBeUndefined();
+ expect(result.error).toBeUndefined(); // 是「测不出」,不是探测失败
+ });
+
+ it('分片拿不到:仍算探到(m3u8 是通的),只当作画质未知', async () => {
+ currentPlaylist = SINGLE_TS;
+ mocks.fetchUpstream.mockImplementation((url: string) => {
+ if (url.endsWith('.ts')) return Promise.resolve(new Response('', { status: 404 }));
+ return Promise.resolve(route(url));
+ });
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBeUndefined();
+ // 不能因为分片下载失败就把一个可用源标成「未探到」
+ expect(result.error).toBeUndefined();
+ });
+
+ it('mp4 直链:直接解析 moov,不经过 m3u8', async () => {
+ mocks.fetchUpstream.mockImplementation((url: string) => {
+ if (url.includes('ac=videolist')) {
+ const body = JSON.stringify({
+ list: [{ vod_id: '123', vod_name: 'x', vod_play_url: '正片$https://cdn.test/movie.mp4' }],
+ });
+ return Promise.resolve(new Response(body, { status: 200 }));
+ }
+ if (url.endsWith('.mp4')) return Promise.resolve(bytesResponse(buildInitMp4()));
+ return Promise.resolve(new Response('', { status: 404 }));
+ });
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBe(1080);
+ });
+
+ it('电视剧单码率:中间集探不出时换最后一集再探', async () => {
+ // 中间集的分片缺失(采集站常见),最后一集正常 —— 不换集就永远「未知」
+ const EP2 = 'https://cdn.test/2024/01/abc/2/index.m3u8';
+ const EP3 = 'https://cdn.test/2024/01/abc/3/index.m3u8';
+ mocks.fetchUpstream.mockClear();
+ mocks.fetchUpstream.mockImplementation((url: string) => {
+ if (url.includes('ac=videolist')) {
+ const body = JSON.stringify({
+ list: [
+ {
+ vod_id: '123',
+ vod_name: '测试剧',
+ vod_play_url: `第1集$https://cdn.test/2024/01/abc/1/index.m3u8#第2集$${EP2}#第3集$${EP3}`,
+ },
+ ],
+ });
+ return Promise.resolve(new Response(body, { status: 200 }));
+ }
+ if (url === EP2 || url === EP3) return Promise.resolve(new Response(SINGLE_TS, { status: 200 }));
+ if (url.endsWith('/2/seg0.ts')) return Promise.resolve(new Response('', { status: 404 }));
+ if (url.endsWith('.ts')) return Promise.resolve(bytesResponse(buildTs()));
+ return Promise.resolve(new Response('not found', { status: 404 }));
+ });
+
+ const result = await probeQuality({ source: SOURCE, id: '123' });
+ expect(result.height).toBe(1080);
+ expect(result.error).toBeUndefined();
+ // 两集都请求过:中间集先探,探不到才轮到最后一集
+ expect(urls()).toContain(EP2);
+ expect(urls()).toContain(EP3);
+ });
+
+ it('单集影片不重复探测同一地址', async () => {
+ currentPlaylist = SINGLE_TS;
+ mocks.fetchUpstream.mockClear();
+ mocks.fetchUpstream.mockImplementation((url: string) => Promise.resolve(route(url)));
+
+ await probeQuality({ source: SOURCE, id: '123' });
+ expect(urls().filter((u) => u === PLAYLIST_URL)).toHaveLength(1);
+ });
+
+ it('无效的源地址:返回错误而不是静默「未知」', async () => {
+ const result = await probeQuality({ source: { ...SOURCE, url: 'not-a-url' }, id: '123' });
+ expect(result.error).toBeDefined();
+ expect(result.height).toBeUndefined();
+ });
+});
diff --git a/src/lib/quality-probe.ts b/src/lib/quality-probe.ts
new file mode 100644
index 0000000..ce35c56
--- /dev/null
+++ b/src/lib/quality-probe.ts
@@ -0,0 +1,413 @@
+import {
+ decryptAes128CbcPrefix,
+ looksLikeMp4,
+ parseMp4VideoResolution,
+ parseTsVideoResolution,
+} from './codec-parse';
+import { cmsRequestHeaders, parseDetail, parseDetailPageHtml } from './cms-parser';
+import { fetchUpstream } from './fetch-utils';
+import { inferHeightFromBitrate } from './quality';
+import { checkUpstreamAllowed } from './ssrf';
+import type { QualityProbeItem, QualityProbeResult, SourceConfig } from './types';
+
+/**
+ * 服务端画质探测。
+ *
+ * 画质不在 CMS 搜索接口里,只写在 m3u8 内部(#EXT-X-STREAM-INF 的 RESOLUTION),
+ * 所以「搜索阶段就知道哪个源是 1080P」只能靠真实拉取一次播放列表。
+ *
+ * 两级策略:
+ * 1. 多码率源:master playlist 里就有各档位分辨率,解析文本即可(最快);
+ * 2. 单码率源(大量采集站如此):m3u8 里什么都没有,下沉到分片本身,
+ * 从 H.264 的 SPS / MP4 的 VisualSampleEntry 里把分辨率挖出来。
+ *
+ * 剩下的盲区只有两种,前端按「未知」而非「标清」展示:
+ * - HEVC/H.265 的 TS 分片(SPS 跳过逻辑复杂,暂无可靠实现);
+ * - 有防盗链或要求特殊鉴权的源:请求被拒。
+ */
+
+/** m3u8 读取上限:master playlist 通常 < 1KB,媒体列表可能几百 KB,只读够解析的头部 */
+const M3U8_MAX_BYTES = 64 * 1024;
+
+/** 分片前缀:SPS / moov 必然在开头,96KB 足够,不必为几十 MB 的分片买单 */
+const SEGMENT_PREFIX_BYTES = 96 * 1024;
+
+/** fMP4 的 init segment 很小,moov 就在里面 */
+const INIT_PREFIX_BYTES = 64 * 1024;
+
+/** 单条探测总死线:与搜索的单源死线同量级,避免一个慢源拖住整批 */
+export const QUALITY_PROBE_TIMEOUT_MS = 8000;
+
+/**
+ * 分片解析的独立预算。
+ * 走这条路径意味着 m3u8 已经拿到了,此时源本身是好的;若分片下载慢而耗尽总死线,
+ * 会把「已探到但没探出画质」误报成「探测失败」,所以单独限一笔更短的预算。
+ */
+const SEGMENT_BUDGET_MS = 4000;
+
+/** 从 m3u8 文本解析最高档的短边高度;非 master playlist(无 STREAM-INF)返回 undefined */
+export function parseBestHeight(text: string): number | undefined {
+ if (!text.includes('#EXT-X-STREAM-INF')) return undefined;
+ let best: number | undefined;
+ 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+)/);
+ // 取短边而非第二个数字:档位本就按短边定义(720P = 1280×720 的 720),
+ // 采集站常把宽高写反(如把 1280×720 写成 720x1280),按 height 取会得到 1280 → 标成 2K
+ pending = {
+ bandwidth,
+ height: resolution
+ ? Math.min(parseInt(resolution[1], 10), parseInt(resolution[2], 10))
+ : undefined,
+ };
+ continue;
+ }
+ if (!line || line.startsWith('#') || !pending) continue;
+ // 只有 BANDWIDTH 的源站按常见转码参数反推高度,与播放器的档位命名口径一致
+ const height = pending.height ?? (pending.bandwidth > 0 ? inferHeightFromBitrate(pending.bandwidth) : undefined);
+ if (height && (best === undefined || height > best)) best = height;
+ pending = undefined;
+ }
+ return best;
+}
+
+/** 媒体列表里解析分片所需的片段信息 */
+export interface MediaPlaylistInfo {
+ initUri?: string;
+ firstSegment?: string;
+ keyMethod?: string;
+ keyUri?: string;
+ keyIv?: Uint8Array;
+ mediaSequence: number;
+}
+
+function hexToBytes(hex: string): Uint8Array | undefined {
+ if (hex.length % 2 !== 0) return undefined;
+ const out = new Uint8Array(hex.length / 2);
+ for (let i = 0; i < out.length; i++) {
+ const value = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
+ if (Number.isNaN(value)) return undefined;
+ out[i] = value;
+ }
+ return out;
+}
+
+/** 解析媒体列表:init segment、第一个分片、加密方式与 IV */
+export function parseMediaPlaylist(text: string): MediaPlaylistInfo {
+ const info: MediaPlaylistInfo = { mediaSequence: 0 };
+ for (const raw of text.split('\n')) {
+ const line = raw.trim();
+ if (!line) continue;
+ if (line.startsWith('#EXT-X-MAP:')) {
+ info.initUri = line.match(/URI="([^"]+)"/)?.[1];
+ continue;
+ }
+ if (line.startsWith('#EXT-X-KEY:')) {
+ info.keyMethod = line.match(/METHOD=([^,]+)/)?.[1]?.trim();
+ info.keyUri = line.match(/URI="([^"]+)"/)?.[1];
+ const iv = line.match(/IV=0x([0-9a-fA-F]+)/)?.[1];
+ info.keyIv = iv ? hexToBytes(iv) : undefined;
+ continue;
+ }
+ if (line.startsWith('#EXT-X-MEDIA-SEQUENCE:')) {
+ const seq = parseInt(line.slice(line.indexOf(':') + 1).trim(), 10);
+ info.mediaSequence = Number.isNaN(seq) ? 0 : seq;
+ continue;
+ }
+ // 第一个非注释行即首个分片(可能是相对路径)
+ if (!line.startsWith('#') && info.firstSegment === undefined) {
+ info.firstSegment = line;
+ }
+ }
+ return info;
+}
+
+/** HLS 规定未显式给 IV 时用媒体序列号作大端 128 位 IV */
+function defaultIv(sequence: number): Uint8Array {
+ const iv = new Uint8Array(16);
+ const seq = sequence >>> 0;
+ iv[12] = (seq >>> 24) & 0xff;
+ iv[13] = (seq >>> 16) & 0xff;
+ iv[14] = (seq >>> 8) & 0xff;
+ iv[15] = seq & 0xff;
+ return iv;
+}
+
+/** 只读取响应体前 maxBytes 字节:分片动辄几十 MB,全量拉取纯属浪费 */
+async function readBytesPrefix(res: Response, maxBytes: number): Promise<Uint8Array> {
+ if (!res.body) return new Uint8Array(await res.arrayBuffer());
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (total < maxBytes) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ total += value.byteLength;
+ }
+ } finally {
+ // 提前放弃剩余 body:不 cancel 会让连接挂着等上游写完
+ reader.cancel().catch(() => {});
+ }
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+}
+
+/** 只读取响应体前 maxBytes 字符(m3u8 用) */
+async function readTextPrefix(res: Response, maxBytes: number): Promise<string> {
+ if (!res.body) return res.text();
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let text = '';
+ let total = 0;
+ try {
+ while (total < maxBytes) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ text += decoder.decode(value, { stream: true });
+ }
+ } finally {
+ reader.cancel().catch(() => {});
+ }
+ return text + decoder.decode();
+}
+
+/** 源站根地址:探测时作为 Referer,绕过最常见的 Referer 防盗链 */
+function originOf(url: string): string {
+ try {
+ return new URL(url).origin;
+ } catch {
+ return '';
+ }
+}
+
+/** 探测阶段的请求头:与播放时的表现尽量一致,避免被防盗链拦下 */
+function probeHeaders(source: SourceConfig): Record<string, string> {
+ return {
+ 'User-Agent': cmsRequestHeaders()['User-Agent'],
+ Referer: `${originOf(source.url)}/`,
+ Accept: '*/*',
+ };
+}
+
+function resolveUrl(base: string, ref: string): string | undefined {
+ try {
+ return new URL(ref, base).toString();
+ } catch {
+ return undefined;
+ }
+}
+
+/** 拉取一段字节前缀;SSRF 拦截或请求失败都返回 undefined */
+async function fetchBytesPrefix(
+ url: string,
+ maxBytes: number,
+ source: SourceConfig,
+ signal: AbortSignal
+): Promise<Uint8Array | undefined> {
+ const verdict = await checkUpstreamAllowed(url);
+ if (!verdict.ok) return undefined;
+ const res = await fetchUpstream(url, {
+ timeoutMs: 6000,
+ headers: probeHeaders(source),
+ signal,
+ });
+ if (!res.ok) return undefined;
+ return readBytesPrefix(res, maxBytes);
+}
+
+/**
+ * 从分片本身解析分辨率(单码率源的兜底路径)。
+ * 返回 undefined 表示仍测不出——前端显示「未知」,待播放后由实测补上。
+ */
+async function probeSegmentResolution(
+ text: string,
+ playlistUrl: string,
+ source: SourceConfig,
+ signal: AbortSignal
+): Promise<number | undefined> {
+ const list = parseMediaPlaylist(text);
+ if (!list.firstSegment) return undefined;
+
+ // fMP4:moov 在 init segment 里,比媒体分片小得多且一定含分辨率,优先走这条
+ if (list.initUri) {
+ const initUrl = resolveUrl(playlistUrl, list.initUri);
+ if (initUrl) {
+ const buf = await fetchBytesPrefix(initUrl, INIT_PREFIX_BYTES, source, signal);
+ const found = buf ? parseMp4VideoResolution(buf) : undefined;
+ if (found) return found.height;
+ }
+ }
+
+ const segmentUrl = resolveUrl(playlistUrl, list.firstSegment);
+ if (!segmentUrl) return undefined;
+ let buf = await fetchBytesPrefix(segmentUrl, SEGMENT_PREFIX_BYTES, source, signal);
+ if (!buf || buf.length === 0) return undefined;
+
+ if (list.keyMethod && list.keyMethod !== 'NONE') {
+ // SAMPLE-AES 是按采样加密的,服务端拿不到分片级的解密上下文,直接放弃
+ if (list.keyMethod !== 'AES-128' || !list.keyUri) return undefined;
+ const keyUrl = resolveUrl(playlistUrl, list.keyUri);
+ if (!keyUrl) return undefined;
+ const key = await fetchBytesPrefix(keyUrl, 32, source, signal);
+ if (!key || key.length < 16) return undefined;
+ buf = decryptAes128CbcPrefix(buf, key, list.keyIv ?? defaultIv(list.mediaSequence));
+ }
+
+ // 按内容判断容器比按扩展名可靠:不少源的分片没有扩展名
+ if (looksLikeMp4(buf)) return parseMp4VideoResolution(buf)?.height;
+ return parseTsVideoResolution(buf)?.height;
+}
+
+/** 取影片的播放地址列表(与 /api/detail 同逻辑:列表接口优先,拿不到再爬详情页) */
+async function fetchEpisodes(source: SourceConfig, id: string, signal: AbortSignal): Promise<string[]> {
+ const api = `${source.url.replace(/\/+$/, '')}?ac=videolist&ids=${encodeURIComponent(id)}`;
+ const res = await fetchUpstream(api, { timeoutMs: 6000, headers: cmsRequestHeaders(), signal });
+ if (res.ok) {
+ try {
+ const detail = parseDetail(await res.json(), source);
+ if (detail.episodes.length > 0) return detail.episodes;
+ } catch {
+ // 列表接口无内容 → 继续尝试详情页
+ }
+ }
+
+ const detailRoot = (source.detail || '').replace(/\/+$/, '');
+ if (!/^https?:\/\//.test(detailRoot)) return [];
+ const verdict = await checkUpstreamAllowed(detailRoot);
+ if (!verdict.ok) return [];
+ const detailRes = await fetchUpstream(`${detailRoot}/index.php/vod/detail/id/${id}.html`, {
+ timeoutMs: 6000,
+ headers: { 'User-Agent': cmsRequestHeaders()['User-Agent'] },
+ signal,
+ });
+ if (!detailRes.ok) return [];
+ return parseDetailPageHtml(await detailRes.text(), source).episodes;
+}
+
+/**
+ * 探测顺序:中间集优先,探不出再退到最后一集。
+ *
+ * 取中间集是因为部分源第一集是预告/广告片;但采集站常有个别集的分片缺失、加密或换过编码,
+ * 中间集恰好命中这种集,整部剧就一直是「未知」——用户不点进播放器的话没有实测回填的机会,
+ * 一次探不出等于永久未知,所以电视剧(多集)补一次最后一集。
+ * 单集影片(电影)无集可换,直接返回唯一那一集。
+ */
+export function probeEpisodeOrder(episodes: string[]): string[] {
+ if (episodes.length < 2) return episodes.slice(0, 1);
+ const mid = episodes[Math.floor(episodes.length / 2)] ?? episodes[0];
+ const last = episodes[episodes.length - 1];
+ return mid === last ? [mid] : [mid, last];
+}
+
+/** 探测单集地址:m3u8 走清单 → 分片两级,mp4 直链直接读 moov */
+async function probeEpisode(
+ target: string,
+ source: SourceConfig,
+ merged: AbortSignal,
+ signal?: AbortSignal
+): Promise<{ height?: number; error?: string }> {
+ // 末尾允许 ?query / #fragment:不少源在 .m3u8 后挂鉴权参数或分片锚点
+ const isM3u8 = /\.m3u8([?#]|$)/i.test(target);
+
+ if (!isM3u8) {
+ // mp4 直链:moov 里有分辨率。未 faststart 的文件 moov 在尾部,前缀拿不到 → 仍未知
+ if (!/\.mp4([?#]|$)/i.test(target)) return {};
+ const buf = await fetchBytesPrefix(target, SEGMENT_PREFIX_BYTES, source, merged);
+ return { height: buf ? parseMp4VideoResolution(buf)?.height : undefined };
+ }
+
+ const res = await fetchUpstream(target, {
+ timeoutMs: 6000,
+ headers: probeHeaders(source),
+ signal: merged,
+ });
+ if (!res.ok) return { error: `HTTP ${res.status}` };
+ const text = await readTextPrefix(res, M3U8_MAX_BYTES);
+
+ const height = parseBestHeight(text);
+ if (height !== undefined) return { height };
+
+ // 单码率媒体列表:m3u8 里没有档位信息,下沉到分片挖分辨率
+ return { height: await withSegmentBudget(target, text, source, merged, signal) };
+}
+
+/**
+ * 探测单条「源 + 影片」的画质。
+ * 返回的 height 为 undefined 表示「测不出」(单码率 / 直链 / 被拒),而非请求失败——
+ * 失败时带 error,前端据此区分「未知」与「探测失败」两种状态。
+ */
+export async function probeQuality(item: QualityProbeItem, signal?: AbortSignal): Promise<QualityProbeResult> {
+ const { source, id } = item;
+ const base: QualityProbeResult = { sourceKey: source.key, vodId: id };
+
+ if (!/^https?:\/\//.test(source.url || '') || !/^[\w-]+$/.test(id)) {
+ return { ...base, error: '无效的源或影片 ID' };
+ }
+ const verdict = await checkUpstreamAllowed(source.url);
+ if (!verdict.ok) return { ...base, error: verdict.reason };
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(new DOMException('画质探测超时', 'TimeoutError')), QUALITY_PROBE_TIMEOUT_MS);
+ // 客户端断开(关闭面板/切页)与单条死线合并为一个 signal
+ const signals = signal ? [signal, controller.signal] : [controller.signal];
+ const merged = AbortSignal.any(signals);
+
+ try {
+ const episodes = await fetchEpisodes(source, id, merged);
+ if (episodes.length === 0) return { ...base, error: '未找到播放资源' };
+
+ const startedAt = Date.now();
+ let lastError: string | undefined;
+ for (const target of probeEpisodeOrder(episodes)) {
+ const r = await probeEpisode(target, source, merged, signal);
+ if (r.height !== undefined) return { ...base, height: r.height };
+ if (r.error) lastError = r.error;
+ // 源站级拒绝(401/403)换集也不会变,不必再耗一轮超时
+ if (lastError && /^HTTP (401|403)$/.test(lastError)) break;
+ // 慢源换集重试会把 8s 总死线打穿,反而把「未知」变成「探测失败」:时间过半就不再换集
+ if (Date.now() - startedAt > QUALITY_PROBE_TIMEOUT_MS / 2) break;
+ }
+ return lastError ? { ...base, error: lastError } : base;
+ } catch (err) {
+ // 客户端主动中止:不算失败,也不该污染缓存
+ if (signal?.aborted) throw err;
+ return { ...base, error: err instanceof Error ? err.message : '探测失败' };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * 分片解析阶段的独立预算。
+ * 走到这里说明 m3u8 已经拿到、源是通的,所以这一阶段的失败只当作「没探出画质」,
+ * 不能升级成探测失败——否则前端会把一个好源标成「未探到」。
+ */
+async function withSegmentBudget(
+ playlistUrl: string,
+ text: string,
+ source: SourceConfig,
+ merged: AbortSignal,
+ clientSignal?: AbortSignal
+): Promise<number | undefined> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(new DOMException('分片解析超时', 'TimeoutError')), SEGMENT_BUDGET_MS);
+ try {
+ return await probeSegmentResolution(text, playlistUrl, source, AbortSignal.any([merged, controller.signal]));
+ } catch {
+ if (clientSignal?.aborted) throw new DOMException('已取消', 'AbortError');
+ return undefined;
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/src/lib/quality.test.ts b/src/lib/quality.test.ts
new file mode 100644
index 0000000..3c282cc
--- /dev/null
+++ b/src/lib/quality.test.ts
@@ -0,0 +1,263 @@
+import { describe, expect, it } from 'vitest';
+import {
+ QUALITY_FAIL_TTL_MS,
+ QUALITY_TTL_MS,
+ inferHeightFromBitrate,
+ isQualityEntryFresh,
+ mergeQualityEntries,
+ qualityLabel,
+} from './quality';
+import { parseBestHeight, parseMediaPlaylist } from './quality-probe';
+import type { QualityEntry } from './types';
+
+/** master playlist 样例:三档,其中一个只有 BANDWIDTH 没有 RESOLUTION */
+const MASTER = `#EXTM3U
+#EXT-X-STREAM-INF:BANDWIDTH=1280000,RESOLUTION=1280x720
+720/index.m3u8
+#EXT-X-STREAM-INF:BANDWIDTH=2560000,RESOLUTION=1920x1080
+1080/index.m3u8
+#EXT-X-STREAM-INF:BANDWIDTH=800000
+480/index.m3u8
+`;
+
+describe('qualityLabel', () => {
+ it('按常见档位命名', () => {
+ expect(qualityLabel(2160)).toBe('4K');
+ expect(qualityLabel(1440)).toBe('2K');
+ expect(qualityLabel(1080)).toBe('1080P');
+ expect(qualityLabel(720)).toBe('720P');
+ expect(qualityLabel(540)).toBe('540P');
+ expect(qualityLabel(480)).toBe('480P');
+ expect(qualityLabel(360)).toBe('360P');
+ });
+
+ it('轻微裁切仍归原档:1080P 裁掉上下边还是 1080P', () => {
+ expect(qualityLabel(1040)).toBe('1080P'); // 1924×1040
+ expect(qualityLabel(1030)).toBe('1080P');
+ expect(qualityLabel(1110)).toBe('1080P');
+ });
+
+ it('1920×960 这类 2.0:1 裁切仍算 1080P(960 不是独立档位)', () => {
+ expect(qualityLabel(960)).toBe('1080P');
+ expect(qualityLabel(920)).toBe('1080P');
+ expect(qualityLabel(1000)).toBe('1080P');
+ expect(qualityLabel(700)).toBe('720P');
+ expect(qualityLabel(680)).toBe('720P');
+ });
+
+ it('偏差过大时不抬档:低分辨率不会被算成 360P', () => {
+ expect(qualityLabel(144)).toBe('144P');
+ expect(qualityLabel(240)).toBe('240P');
+ expect(qualityLabel(800)).toBe('720P');
+ });
+
+ it('缺失或非法高度返回 undefined(前端据此显示「未知」)', () => {
+ expect(qualityLabel(undefined)).toBeUndefined();
+ expect(qualityLabel(0)).toBeUndefined();
+ });
+});
+
+describe('parseBestHeight', () => {
+ it('取 master playlist 的最高档', () => {
+ expect(parseBestHeight(MASTER)).toBe(1080);
+ });
+
+ it('只有 BANDWIDTH 的档位按转码参数反推高度', () => {
+ const text = `#EXTM3U
+#EXT-X-STREAM-INF:BANDWIDTH=6000000
+only-bandwidth.m3u8
+`;
+ expect(parseBestHeight(text)).toBe(inferHeightFromBitrate(6_000_000));
+ });
+
+ it('单码率媒体列表没有 STREAM-INF,返回 undefined 而非猜一个档位', () => {
+ const text = `#EXTM3U
+#EXT-X-TARGETDURATION:10
+#EXTINF:10.0,
+seg0.ts
+`;
+ expect(parseBestHeight(text)).toBeUndefined();
+ });
+
+ it('空文本与纯注释返回 undefined', () => {
+ expect(parseBestHeight('')).toBeUndefined();
+ expect(parseBestHeight('#EXTM3U\n')).toBeUndefined();
+ });
+
+ it('变体行缺失时不被上一档的声明污染', () => {
+ // STREAM-INF 后紧跟另一条 STREAM-INF(异常清单):不产生高度,避免误判
+ const text = `#EXTM3U
+#EXT-X-STREAM-INF:BANDWIDTH=1280000,RESOLUTION=1280x720
+#EXT-X-STREAM-INF:BANDWIDTH=2560000,RESOLUTION=1920x1080
+1080/index.m3u8
+`;
+ expect(parseBestHeight(text)).toBe(1080);
+ });
+
+ it('取短边:源站把宽高写反(720x1280)时拿到 720 而非 1280', () => {
+ // 实际采集站常见 720P 源被标成 720x1280;之前按 height 取会得到 1280 → qualityLabel 成 2K
+ const text = `#EXTM3U
+#EXT-X-STREAM-INF:BANDWIDTH=1500000,RESOLUTION=720x1280
+720p/index.m3u8
+`;
+ expect(parseBestHeight(text)).toBe(720);
+ });
+
+ it('取短边:正常的 1280x720 不受影响', () => {
+ // 回归保护:取短边后档位判断与原本按 height 写在 16:9 视频上一致
+ const text = `#EXTM3U
+#EXT-X-STREAM-INF:BANDWIDTH=1500000,RESOLUTION=1280x720
+720p/index.m3u8
+`;
+ expect(parseBestHeight(text)).toBe(720);
+ });
+});
+
+describe('parseMediaPlaylist', () => {
+ const MEDIA = `#EXTM3U
+#EXT-X-TARGETDURATION:10
+#EXT-X-MEDIA-SEQUENCE:17
+#EXT-X-MAP:URI="init.mp4"
+#EXTINF:10.0,
+seg0.m4s
+#EXTINF:10.0,
+seg1.m4s
+`;
+
+ it('取到 init segment 与第一个分片(分片解析靠这两个)', () => {
+ const info = parseMediaPlaylist(MEDIA);
+ expect(info.initUri).toBe('init.mp4');
+ expect(info.firstSegment).toBe('seg0.m4s'); // 只取第一个,第二个不关心
+ });
+
+ it('解析媒体序列号:未显式给 IV 时它就是 IV', () => {
+ expect(parseMediaPlaylist(MEDIA).mediaSequence).toBe(17);
+ expect(parseMediaPlaylist('#EXTM3U\nseg.ts\n').mediaSequence).toBe(0);
+ });
+
+ it('解析 AES-128 的方法、密钥地址与十六进制 IV', () => {
+ const info = parseMediaPlaylist(`#EXTM3U
+#EXT-X-KEY:METHOD=AES-128,URI="https://cdn.example/key.bin",IV=0x1a2b3c4d5e6f708192a3b4c5d6e7f809
+seg0.ts
+`);
+ expect(info.keyMethod).toBe('AES-128');
+ expect(info.keyUri).toBe('https://cdn.example/key.bin');
+ expect(info.keyIv).toHaveLength(16);
+ expect(info.keyIv![0]).toBe(0x1a);
+ expect(info.keyIv![15]).toBe(0x09);
+ });
+
+ it('SAMPLE-AES 单独识别:服务端解不开,调用方据此放弃而不是解密出错', () => {
+ const info = parseMediaPlaylist('#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://x"\nseg.ts\n');
+ expect(info.keyMethod).toBe('SAMPLE-AES');
+ expect(info.keyUri).toBe('skd://x');
+ });
+
+ it('相对路径原样保留(拼接由调用方用 new URL 完成)', () => {
+ expect(parseMediaPlaylist('#EXTM3U\n/2024/01/abc/index.ts\n').firstSegment).toBe('/2024/01/abc/index.ts');
+ });
+
+ it('m3u8 里没有分片时返回空,调用方据此判定测不出', () => {
+ expect(parseMediaPlaylist('#EXTM3U\n#EXT-X-ENDLIST\n').firstSegment).toBeUndefined();
+ });
+});
+
+describe('isQualityEntryFresh', () => {
+ const T = 1_700_000_000_000;
+
+ it('成功与「测不出」按长 TTL 判定', () => {
+ const ok: QualityEntry = { height: 1080, from: 'probe', timestamp: T };
+ const unknown: QualityEntry = { from: 'probe', timestamp: T };
+ expect(isQualityEntryFresh(ok, T + QUALITY_TTL_MS - 1)).toBe(true);
+ expect(isQualityEntryFresh(unknown, T + QUALITY_TTL_MS - 1)).toBe(true);
+ expect(isQualityEntryFresh(ok, T + QUALITY_TTL_MS + 1)).toBe(false);
+ });
+
+ it('失败按短 TTL 判定:过期后允许重试', () => {
+ const failed: QualityEntry = { from: 'probe', error: 'HTTP 403', timestamp: T };
+ expect(isQualityEntryFresh(failed, T + QUALITY_FAIL_TTL_MS - 1)).toBe(true);
+ expect(isQualityEntryFresh(failed, T + QUALITY_FAIL_TTL_MS + 1)).toBe(false);
+ });
+
+ it('读取路径靠它挡住持久化回来的过期条目', () => {
+ // 刷新页面后旧条目直接从 localStorage 回到内存,写入时的清理没机会跑
+ const stale: QualityEntry = { height: 720, from: 'play', timestamp: T };
+ expect(isQualityEntryFresh(stale, T + QUALITY_TTL_MS * 2)).toBe(false);
+ });
+});
+
+describe('mergeQualityEntries', () => {
+ const T = 1_700_000_000_000;
+ const probe = (height?: number, error?: string): QualityEntry => ({ height, from: 'probe', error, timestamp: T });
+ const play = (height: number): QualityEntry => ({ height, from: 'play', timestamp: T });
+ const KEY = 'huang:123';
+
+ it('播放实测覆盖此前的「测不出」——单码率源的画质只能这样补上', () => {
+ // 先探测:单码率 m3u8,没有画质信息(无 error、无 height)
+ const afterProbe = mergeQualityEntries({}, { [KEY]: probe() }, T);
+ expect(afterProbe[KEY].height).toBeUndefined();
+
+ // 播放后拿到真实解码高度
+ const afterPlay = mergeQualityEntries(afterProbe, { [KEY]: play(1080) }, T + 1000);
+ expect(afterPlay[KEY]).toMatchObject({ height: 1080, from: 'play' });
+ });
+
+ it('实测值不被后续探测覆盖(m3u8 里写的是声明值,不如解码值可信)', () => {
+ const current = { [KEY]: play(1080) };
+ const next = mergeQualityEntries(current, { [KEY]: probe(720) }, T + 1000);
+ expect(next[KEY]).toMatchObject({ height: 1080, from: 'play' });
+ });
+
+ it('多次实测取较大值:ABR 起播先选低档再升档,不能被起播档位低估', () => {
+ const current = { [KEY]: play(720) };
+ const next = mergeQualityEntries(current, { [KEY]: play(1080) }, T + 1000);
+ expect(next[KEY].height).toBe(1080);
+
+ // 反向:后来的低档位不该把已知的高档位拉低
+ const back = mergeQualityEntries(next, { [KEY]: play(540) }, T + 2000);
+ expect(back[KEY].height).toBe(1080);
+ });
+
+ it('已有明确档位时,不被「测不出」的探测抹掉', () => {
+ const current = { [KEY]: probe(1080) };
+ const next = mergeQualityEntries(current, { [KEY]: probe() }, T + 1000);
+ expect(next[KEY].height).toBe(1080);
+ });
+
+ it('探测失败按短 TTL 淘汰,成功与「测不出」按长 TTL 保留', () => {
+ const now = T + QUALITY_FAIL_TTL_MS + 1000;
+ const merged = mergeQualityEntries(
+ {
+ failed: probe(undefined, 'HTTP 403'),
+ unknown: probe(),
+ ok: probe(1080),
+ },
+ {},
+ now
+ );
+ // 失败记录已过期 → 允许重试;另外两条是有效结论,不能反复重探
+ expect(merged.failed).toBeUndefined();
+ expect(merged.unknown).toBeDefined();
+ expect(merged.ok).toBeDefined();
+ // 长 TTL 到期后同样清掉
+ expect(mergeQualityEntries({ ok: probe(1080) }, {}, T + QUALITY_TTL_MS + 1000).ok).toBeUndefined();
+ });
+
+ it('保留未过期条目,避免每次写入都把已有缓存丢掉', () => {
+ const current = { other: probe(720) };
+ const next = mergeQualityEntries(current, { [KEY]: play(1080) }, T + 1000);
+ expect(next.other).toMatchObject({ height: 720 });
+ expect(next[KEY]).toMatchObject({ height: 1080 });
+ });
+
+ it('超过上限时淘汰最旧条目', () => {
+ const current: Record<string, QualityEntry> = {};
+ for (let i = 0; i < 400; i++) {
+ current[`k${i}`] = { height: 720, from: 'probe', timestamp: T + i };
+ }
+ const next = mergeQualityEntries(current, { fresh: { height: 1080, from: 'probe', timestamp: T + 9999 } }, T + 9999);
+ expect(Object.keys(next)).toHaveLength(400);
+ expect(next.k0).toBeUndefined(); // 最旧的一条被淘汰
+ expect(next.fresh).toBeDefined();
+ });
+});
diff --git a/src/lib/quality.ts b/src/lib/quality.ts
new file mode 100644
index 0000000..9fdfda7
--- /dev/null
+++ b/src/lib/quality.ts
@@ -0,0 +1,141 @@
+/**
+ * 画质工具:缓存键、展示标签、高度推断、缓存合并。
+ *
+ * 画质信息不在 CMS 搜索接口里,只存在于 m3u8 内部(#EXT-X-STREAM-INF 的 RESOLUTION),
+ * 因此只能「探测」(拉 m3u8 解析)或「实测」(播放器解码后读 videoHeight)。
+ * 本模块只负责这两个来源产出的高度值如何命名与存放,不负责获取。
+ */
+
+import type { QualityEntry } from './types';
+
+/** 画质缓存有效期:源站换片源的概率低,30 天内直接复用 */
+export const QUALITY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
+
+/**
+ * 探测失败结果的缓存有效期。
+ * 失败原因多为瞬时(超时/限流/防盗链偶发拒绝),不能像成功结果那样存 30 天,
+ * 否则偶发失败会被当成永久结论,用户再也看不到画质。
+ */
+export const QUALITY_FAIL_TTL_MS = 10 * 60 * 1000;
+
+/**
+ * 条目是否仍在有效期内(唯一判定入口,写入与读取都走这里)。
+ *
+ * 读取路径也必须过滤:qualityMap 是持久化的,刷新页面后旧条目直接从 localStorage
+ * 回到内存;而写入路径(mergeQualityEntries)只有在下次写入时才顺带清理。
+ * 只清理不过滤的话,过期条目会被当成终态显示,且因为「已有结论就不再探」而永不过期。
+ */
+export function isQualityEntryFresh(entry: QualityEntry, now = Date.now()): boolean {
+ const ttl = entry.error ? QUALITY_FAIL_TTL_MS : QUALITY_TTL_MS;
+ return now - entry.timestamp < ttl;
+}
+
+/** 缓存键:按「源 + 影片」,同一源的不同剧画质不同,不能按源整体记录 */
+export function qualityKey(sourceKey: string, vodId: string): string {
+ return `${sourceKey}:${vodId}`;
+}
+
+/**
+ * 档位容差:与档位值的偏差在此比例内才算同一档。
+ *
+ * 采集站普遍对片源做裁切(1920×1080 → 1924×1040、1920×960 这类),
+ * 严格「必须 ≥ 档位值」会把 1040、960 都打成 720P,与用户观感相反。
+ * 15% 覆盖常见的裁边与等比缩放(960 距 1080 差 11%),
+ * 又足以挡住反向误判:144 不会被抬成 360P。
+ */
+const TIER_TOLERANCE = 0.15;
+
+/** 档位表:高度 → 标签 */
+const TIERS: ReadonlyArray<readonly [number, string]> = [
+ [2160, '4K'],
+ [1440, '2K'],
+ [1080, '1080P'],
+ [720, '720P'],
+ [540, '540P'],
+ [480, '480P'],
+ [360, '360P'],
+];
+
+/**
+ * 高度 → 展示标签:就近取档。
+ * 2160 及以上统称 4K(2K/1440 单独一档,避免 1440 被误标成 1080P)。
+ * 偏差超过 15% 的按原样展示(如 144 → 144P、240 → 240P)。
+ */
+export function qualityLabel(height?: number): string | undefined {
+ if (!height || height <= 0) return undefined;
+ let best: readonly [number, string] | undefined;
+ for (const tier of TIERS) {
+ const [value] = tier;
+ if (Math.abs(value - height) > value * TIER_TOLERANCE) continue;
+ if (!best || Math.abs(value - height) < Math.abs(best[0] - height)) best = tier;
+ }
+ return best ? best[1] : `${height}P`;
+}
+
+/** 缓存条目上限(按「源 + 影片」计):每部剧 × 每个源一条,需防无上限膨胀 */
+export const QUALITY_MAX_ENTRIES = 400;
+
+/**
+ * 把新结果合并进画质缓存(纯函数,便于单测)。
+ *
+ * 三条优先级规则,缺一都会让用户看到错误结论:
+ * 1. 实测(play)压过探测(probe)——m3u8 里写的是源站「声明」的档位,解码出来的才是真的;
+ * 2. 实测之间取较大值——ABR 起播常先选低档再升档,取最大才不会被起播档位低估;
+ * 3. 探测之间,已有明确档位时不被「测不出」抹掉——否则一次偶发失败会毁掉已知的好结果。
+ */
+export function mergeQualityEntries(
+ current: Record<string, QualityEntry>,
+ incoming: Record<string, QualityEntry>,
+ now = Date.now()
+): Record<string, QualityEntry> {
+ const next: Record<string, QualityEntry> = {};
+ // 过期条目顺带清理。「测不出」(无 error)是有效结论,按长 TTL 保留,
+ // 否则每次展开来源面板都会白探测一遍同一个源;失败按短 TTL 淘汰,给重试留机会
+ for (const [key, entry] of Object.entries(current)) {
+ if (isQualityEntryFresh(entry, now)) next[key] = entry;
+ }
+
+ for (const [key, value] of Object.entries(incoming)) {
+ const prev = next[key];
+ if (prev?.from === 'play') {
+ if (value.from !== 'play') continue;
+ const best = Math.max(prev.height ?? 0, value.height ?? 0);
+ next[key] = { from: 'play', height: best || undefined, timestamp: now };
+ continue;
+ }
+ if (prev?.from === 'probe' && value.from === 'probe' && prev.height !== undefined && value.height === undefined) {
+ continue;
+ }
+ next[key] = value;
+ }
+
+ const overflow = Object.keys(next).length - QUALITY_MAX_ENTRIES;
+ if (overflow > 0) {
+ const oldest = Object.entries(next)
+ .sort((a, b) => a[1].timestamp - b[1].timestamp)
+ .slice(0, overflow)
+ .map(([key]) => key);
+ for (const key of oldest) delete next[key];
+ }
+ return next;
+}
+
+/**
+ * 码率 → 推断高度:部分源站的 master playlist 只给 BANDWIDTH 不给 RESOLUTION。
+ * 分层取自常见转码参数,仅供档位标识使用(与 m3u8-parse 的推断表保持一致)。
+ */
+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;
+}
diff --git a/src/lib/remarks.test.ts b/src/lib/remarks.test.ts
new file mode 100644
index 0000000..c19ba96
--- /dev/null
+++ b/src/lib/remarks.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+import { formatRemarks, inferGroupRemarks } from './remarks';
+
+describe('formatRemarks', () => {
+ it('截图里那五种写法归一成两种结果', () => {
+ // 360资源 / 暴风资源 / 电影天堂 / 非凡影视 / 光速资源 的实际取值
+ expect(formatRemarks('全34集')).toBe('全34集');
+ expect(formatRemarks('完结')).toBe('已完结');
+ expect(formatRemarks('已完结')).toBe('已完结');
+ expect(formatRemarks('第34集已完结')).toBe('全34集');
+ });
+
+ it('连载中保留进度', () => {
+ expect(formatRemarks('更新至12集')).toBe('更新至12集');
+ expect(formatRemarks('更新至第12集')).toBe('更新至12集');
+ expect(formatRemarks('第12集')).toBe('更新至12集');
+ });
+
+ it('「全」「共」「集全」都是完结信号', () => {
+ expect(formatRemarks('共24集')).toBe('全24集');
+ expect(formatRemarks('24集全')).toBe('全24集');
+ expect(formatRemarks('全集')).toBe('已完结');
+ expect(formatRemarks('大结局')).toBe('已完结');
+ });
+
+ it('非集数备注原样保留,不能把信息改丢', () => {
+ // 电影常用这类备注,跟集数无关
+ expect(formatRemarks('HD国语')).toBe('HD国语');
+ expect(formatRemarks('正片')).toBe('正片');
+ expect(formatRemarks('BD高清中字')).toBe('BD高清中字');
+ expect(formatRemarks('2026')).toBe('2026');
+ // 「终」只认「剧终」:终极版不是完结
+ expect(formatRemarks('终极版')).toBe('终极版');
+ });
+
+ it('空值与空白返回 undefined,交给调用方显示「暂无介绍」', () => {
+ expect(formatRemarks(undefined)).toBeUndefined();
+ expect(formatRemarks('')).toBeUndefined();
+ expect(formatRemarks(' ')).toBeUndefined();
+ });
+
+ it('幂等:已归一化的文案再跑一次不变', () => {
+ for (const raw of ['全34集', '更新至12集', '已完结', 'HD国语']) {
+ const once = formatRemarks(raw);
+ expect(formatRemarks(once)).toBe(once);
+ }
+ });
+
+ it('首尾空白不影响判定', () => {
+ expect(formatRemarks(' 全34集 ')).toBe('全34集');
+ });
+});
+
+describe('inferGroupRemarks', () => {
+ it('用组内已知的总集数补齐只标了「已完结」的源', () => {
+ // 截图里 13 个源的真实组合:8 个「全34集」、4 个「已完结」、1 个「更新至34集」
+ const group = [
+ '全34集', '完结', '已完结', '已完结', '第34集已完结',
+ '全34集', '全34集', '全34集', '全34集', '全34集',
+ '已完结', '全34集', '更新至34集',
+ ];
+ expect(inferGroupRemarks(group)).toBe('全34集');
+ });
+
+ it('组内没有任何总集数时,退回「已完结」而不是编一个数字', () => {
+ expect(inferGroupRemarks(['已完结', '完结', '已完结'])).toBe('已完结');
+ });
+
+ it('全是连载中的源:取最大进度', () => {
+ expect(inferGroupRemarks(['更新至12集', '更新至5集'])).toBe('更新至12集');
+ });
+
+ it('总集数优先于进度:不能拿进度当总集数', () => {
+ // 12 集的进度不代表这部只有 12 集;组内既然有源写「全24集」,总集数就是 24
+ expect(inferGroupRemarks(['全24集', '更新至12集'])).toBe('全24集');
+ // 反过来:只有进度时不能冒充总集数
+ expect(inferGroupRemarks(['更新至12集', '更新至5集'])).toBe('更新至12集');
+ });
+
+ it('总集数优先于完结:有集数就别退回没集数的「已完结」', () => {
+ expect(inferGroupRemarks(['已完结', '完结', '全24集'])).toBe('全24集');
+ });
+
+ it('非集数备注(电影)原样返回第一条', () => {
+ expect(inferGroupRemarks(['HD国语', '正片'])).toBe('HD国语');
+ });
+
+ it('多个源给不同总集数时取最大的', () => {
+ expect(inferGroupRemarks(['全24集', '全34集', '全12集'])).toBe('全34集');
+ });
+
+ it('什么都没给时返回 undefined', () => {
+ expect(inferGroupRemarks([undefined, '', ' '])).toBeUndefined();
+ expect(inferGroupRemarks([])).toBeUndefined();
+ });
+});
diff --git a/src/lib/remarks.ts b/src/lib/remarks.ts
new file mode 100644
index 0000000..6cb26fa
--- /dev/null
+++ b/src/lib/remarks.ts
@@ -0,0 +1,92 @@
+/**
+ * 播放备注(CMS 的 vod_remarks)归一化。
+ *
+ * 这个字段由各采集源自由填写,同一部剧的不同源常常各写各的:
+ * 「全34集」「完结」「已完结」「第34集已完结」说的是同一件事,
+ * 直接原样显示,会让用户以为这些源的状态不一样。
+ *
+ * 只归一「集数」与「完结状态」两类信息,其余(HD国语 / 正片 / 年份等)
+ * 原样返回——它们不是集数信息,强行改写只会把内容丢掉。
+ */
+
+/** 集数:「全34集」「第34集」「更新至12集」「共24集」都能取出数字 */
+const EPISODE_COUNT = /(\d+)\s*集/;
+/** 完结的明确表述。「剧终」而不单是「终」——否则「终极版」会被误判成已完结 */
+const FINISHED_WORD = /完结|大结局|全集|剧终/;
+/** 前置全称:「全34集」「共24集」 */
+const FINISHED_PREFIX = /(?:全|共)\s*\d+\s*集/;
+/** 后置全称:「34集全」 */
+const FINISHED_SUFFIX = /\d+\s*集\s*全/;
+
+function isFinished(text: string): boolean {
+ return FINISHED_WORD.test(text) || FINISHED_PREFIX.test(text) || FINISHED_SUFFIX.test(text);
+}
+
+function episodeCount(text: string): number {
+ return Number(EPISODE_COUNT.exec(text)?.[1] ?? 0);
+}
+
+/**
+ * 归一备注文案。输出只有三种形态:
+ * - `全N集`:已完结且知道总集数
+ * - `更新至N集`:连载中且知道当前集数
+ * - `已完结`:完结但没有集数信息
+ * 以及原样返回的非集数备注(如 `HD国语`、`正片`)。
+ *
+ * 幂等:已归一化的文案再跑一次结果不变,因此聚合阶段与渲染阶段都调它也不会变样。
+ */
+export function formatRemarks(raw?: string): string | undefined {
+ const text = raw?.trim();
+ if (!text) return undefined;
+
+ const finished = isFinished(text);
+ const count = episodeCount(text);
+ if (count > 0) return finished ? `全${count}集` : `更新至${count}集`;
+ // 没有集数时,只有「完结」类表述能归一,别的保持原样
+ if (finished) return '已完结';
+ return text;
+}
+
+/**
+ * 推断整组(同一部剧的所有来源)的统一备注。
+ *
+ * 单看一个源补不出集数:标「已完结」的源就是没写总集数。但同一部剧的总集数是客观的,
+ * 组内只要有源写了「全34集」,就能确定这部剧是 34 集,把成果推到同组其他源上。
+ * 这正是「有的是已完结、有的是全34集」的解法。
+ *
+ * 优先级:总集数 > 完结 > 进度。
+ * 反过来(完结 > 总集数)会丢掉集数;而拿「更新至N集」当总集数是错的——
+ * 那是进度,12 集的进度不代表这部只有 12 集。
+ *
+ * 注意这是**推断**:若某源实际只更到 20 集而组内已有源完结,它也会显示总集数。
+ * 该源自己的原始标注保留在按钮 tooltip 里,信息不丢。
+ */
+export function inferGroupRemarks(raws: Array<string | undefined>): string | undefined {
+ let total = 0;
+ let progress = 0;
+ let finished = false;
+ let fallback: string | undefined;
+
+ for (const raw of raws) {
+ const text = formatRemarks(raw);
+ if (!text) continue;
+ fallback ??= text;
+
+ const totalMatch = /^全(\d+)集$/.exec(text);
+ if (totalMatch) {
+ total = Math.max(total, Number(totalMatch[1]));
+ continue;
+ }
+ const progressMatch = /^更新至(\d+)集$/.exec(text);
+ if (progressMatch) {
+ progress = Math.max(progress, Number(progressMatch[1]));
+ continue;
+ }
+ if (text === '已完结') finished = true;
+ }
+
+ if (total > 0) return `全${total}集`;
+ if (finished) return '已完结';
+ if (progress > 0) return `更新至${progress}集`;
+ return fallback;
+}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index dd6a730..826e882 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -2,7 +2,8 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
-import type { SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';
+import type { QualityEntry, SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';
+import { isQualityEntryFresh, mergeQualityEntries, qualityKey } from './quality';
import { clearLiveProbeResultsDb, loadLiveProbeResults, saveLiveProbeResults } from './db';
import { PERSIST_KEY, createThrottledStorage } from './persist-storage';
@@ -197,6 +198,8 @@ interface AppState extends AppSettings {
liveProbeResults: Record<string, LiveProbeEntry>;
/** 点播源健康度(随搜索滚动更新,跨会话持久化) */
sourceHealth: Record<string, SourceHealthEntry>;
+ /** 画质缓存(按 `sourceKey:vodId`):播放实测与搜索时懒探测共用一份 */
+ qualityMap: Record<string, QualityEntry>;
/** 已出现过的 env 预置订阅 URL(持久化:用户删除后不再被自动加回) */
envSubsSeen: string[];
addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;
@@ -251,6 +254,12 @@ interface AppState extends AppSettings {
recordSourceHealth: (outcomes: SourceSearchOutcome[]) => SourceDisableEvent[];
/** 清除单个源的健康度记录(手动恢复入口) */
clearSourceHealth: (key: string) => void;
+ /**
+ * 写入画质记录(播放实测与懒探测共用同一份缓存)。
+ * 实测值优先级高于探测值:解析 m3u8 得到的只是源站声明的档位,
+ * 播放时的 videoHeight 才是真实分辨率,实测一旦拿到就覆盖探测结果。
+ */
+ setQuality: (entries: Record<string, QualityEntry>) => void;
markEnvSubsSeen: (urls: string[]) => void;
updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;
}
@@ -287,6 +296,7 @@ export const useAppStore = create<AppState>()(
liveRecent: [],
liveProbeResults: {},
sourceHealth: {},
+ qualityMap: {},
envSubsSeen: [],
selectedKeys: [],
yellowFilter: true,
@@ -708,6 +718,11 @@ export const useAppStore = create<AppState>()(
set({ envSubsSeen: [...seen] });
},
+ setQuality: (entries) => {
+ // 合并与淘汰规则见 mergeQualityEntries(纯函数,单独覆盖了优先级与 TTL 的单测)
+ set({ qualityMap: mergeQualityEntries(get().qualityMap, entries) });
+ },
+
updateSettings: (patch) => {
// 用户主动修改推荐数据源 / 封面图加载方式时打上「已选择」标记:此后部署者的
// DEFAULT_RECOMMEND_SOURCE / DEFAULT_IMAGE_MODE 默认值不再覆盖该用户的选择
@@ -780,6 +795,7 @@ export const useAppStore = create<AppState>()(
liveFavorites: s.liveFavorites,
liveRecent: s.liveRecent,
sourceHealth: s.sourceHealth,
+ qualityMap: s.qualityMap,
envSubsSeen: s.envSubsSeen,
yellowFilter: s.yellowFilter,
adFilter: s.adFilter,
@@ -862,6 +878,30 @@ export function isSourceDisabled(
* 与 isSourceDisabled 分开判断:一个是用户主动关的、一个是系统按连续失败关的,
* 提示文案与恢复方式都不同,混在一起用户就看不懂源为什么不生效了。
*/
+/**
+ * 读取某「源 + 影片」的画质记录(直接查内存态,不订阅 store)。
+ * 结果列表一次可能有十几张卡片 × 十几个来源,订阅整个 map 会让每次探测
+ * 结果都触发所有卡片重渲染,因此只在展开面板 / 探测回调时用 getState 读。
+ */
+export function readQuality(sourceKey: string, vodId: string): QualityEntry | undefined {
+ const entry = useAppStore.getState().qualityMap[qualityKey(sourceKey, vodId)];
+ // 过期条目按「没有结论」处理:持久化回来后 TTL 只在写入时清理过,
+ // 直接返回会让旧画质一直显示,且因为被认为已有结论而永远不重探
+ return entry && isQualityEntryFresh(entry) ? entry : undefined;
+}
+
+/** 批量读取:一次拿多个「源 + 影片」的画质,避免逐个 getState */
+export function readQualities(pairs: Array<{ sourceKey: string; vodId: string }>): Record<string, QualityEntry> {
+ const map = useAppStore.getState().qualityMap;
+ const out: Record<string, QualityEntry> = {};
+ for (const p of pairs) {
+ const key = qualityKey(p.sourceKey, p.vodId);
+ const entry = map[key];
+ if (entry && isQualityEntryFresh(entry)) out[key] = entry;
+ }
+ return out;
+}
+
export function isInDisabledSubscription(
state: Pick<AppState, 'subscriptions'>,
key: string
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 070dcda..3b16630 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -64,6 +64,40 @@ export interface SourceSearchOutcome {
ms?: number;
}
+// —— 画质(按「源 + 影片」记录) ——
+
+/**
+ * 画质记录条目。
+ * `height` 为视频高度(像素),undefined 表示探测过但测不出(单码率 m3u8 / 直链)。
+ * `from` 区分来源:play 是播放器实测的真实分辨率(权威),probe 是解析 m3u8 推断值。
+ */
+export interface QualityEntry {
+ height?: number;
+ from: 'play' | 'probe';
+ /**
+ * 探测失败原因(如 `HTTP 403`、`请求超时`)。
+ * 有值 = 这次压根没探到;无值而 height 也缺失 = 探到了但源站没写画质信息。
+ * 两者在 UI 上都显示「未知」,靠这个字段区分出「源站不给」和「我们没够着」。
+ */
+ error?: string;
+ /** 记录时间(epoch ms),用于 LRU 淘汰与失败重试 */
+ timestamp: number;
+}
+
+/** 画质探测请求条目:源配置 + 影片 ID */
+export interface QualityProbeItem {
+ source: SourceConfig;
+ id: string;
+}
+
+/** 画质探测结果;height 缺失代表「测不出」而非失败失败(error 有值时才是失败) */
+export interface QualityProbeResult {
+ sourceKey: string;
+ vodId: string;
+ height?: number;
+ error?: string;
+}
+
// —— API 响应结构 ——
export interface SearchResponse {