Skip to content

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

feat(live): 测活三色状态语义与错误占位识别;播放器支持原生容器与回退

bestZwei8ce11014e946
diff --git a/package.json b/package.json
index 40fbf28..577b84f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv",
- "version": "2.7.2",
+ "version": "2.8.0",
"private": true,
"description": "免费在线视频搜索与观看平台(Next.js 重构版)",
"license": "AGPL-3.0-or-later",
diff --git a/src/app/api/live/probe/route.test.ts b/src/app/api/live/probe/route.test.ts
index 4f36b76..1af4161 100644
--- a/src/app/api/live/probe/route.test.ts
+++ b/src/app/api/live/probe/route.test.ts
@@ -125,6 +125,66 @@ describe('POST /api/live/probe', () => {
expect(fn.mock.calls.length).toBe(callsAfterFirst);
});
+ it('重定向到错误占位资源(令牌失效)时判为不可用', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes('/channel/expired')) {
+ return new Response(null, {
+ status: 302,
+ headers: { location: 'https://static.err.test/status/error_account_pirated.mp4' },
+ });
+ }
+ return new Response('mp4-bytes', {
+ status: 200,
+ headers: { 'content-type': 'video/mp4' },
+ });
+ })
+ );
+ const res = await POST(makeRequest(['https://tv.test/channel/expired?token=x'], true));
+ const [line] = await readNdjson(res);
+ expect(line.ok).toBe(false);
+ expect(String(line.error)).toContain('错误占位');
+ });
+
+ it('重定向到仍在 /status/ 下的正常 m3u8 时不误判为错误占位', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes('/entry')) {
+ return new Response(null, {
+ status: 302,
+ headers: { location: 'https://cdn.ok.test/status/live.m3u8' },
+ });
+ }
+ if (url.includes('/status/live.m3u8')) {
+ return jsonRes(MEDIA, 'application/vnd.apple.mpegurl');
+ }
+ return new Response('x', { status: 206, headers: { 'content-type': 'video/mp2t' } });
+ })
+ );
+ const res = await POST(makeRequest(['https://cdn.ok.test/entry?token=x'], true));
+ const [line] = await readNdjson(res);
+ expect(line.ok).toBe(true);
+ expect(line.level).toBe('segment');
+ });
+
+ it('直链 MP4 只标记为 head(可达但未验证可播性)', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('mp4-bytes', {
+ status: 200,
+ headers: { 'content-type': 'video/mp4' },
+ }))
+ );
+ const res = await POST(makeRequest(['https://direct.test/live/stream?id=1'], true));
+ const [line] = await readNdjson(res);
+ expect(line.ok).toBe(true);
+ expect(line.level).toBe('head');
+ });
+
it('探测窗口内最新分片(滑动窗口下最不易过期)', async () => {
const MEDIA3 = [
'#EXTM3U',
diff --git a/src/app/api/live/probe/route.ts b/src/app/api/live/probe/route.ts
index f25e8a5..fe52679 100644
--- a/src/app/api/live/probe/route.ts
+++ b/src/app/api/live/probe/route.ts
@@ -60,6 +60,8 @@ interface ProbeOutcome {
error?: string;
/** master playlist 的 CODECS 属性(如 hvc1.1.6.L93.B0,mp4a.40.2),用于前端提示编码兼容性 */
codec?: string;
+ /** 因超出时间预算而失败(源可能只是慢,不代表不可播),前端据此区分展示 */
+ timedOut?: boolean;
}
interface FetchHeadResult {
@@ -71,6 +73,15 @@ interface FetchHeadResult {
isM3u8: boolean;
}
+/**
+ * 错误占位资源:不少 IPTV 服务在令牌失效/账号异常时 302 到一段错误提示视频或图片
+ * (如 `https://static.xxx/status/error_account_pirated.mp4`)。
+ * 响应是 200 的合法媒体,单看可达性会误判为可用,这里按最终 URL 路径特征识别。
+ * 仅在发生重定向时判定,避免误伤正常路径。
+ */
+const ERROR_PLACEHOLDER_RE =
+ /(^|\/)(error|errors|status|denied|forbidden|expired|invalid|pirated|unauthorized)([_\-./]|$)/i;
+
/** 明显的网页/接口响应(200 的 HTML/JSON 错误页不能当成流) */
function isWebPageType(contentType: string): boolean {
const ct = contentType.toLowerCase();
@@ -203,7 +214,24 @@ async function probeOne(url: string): Promise<ProbeOutcome> {
return { url, ok: false, status: entry.status, ms: elapsed(start), error: `入口响应 ${entry.status}` };
}
- // 非 m3u8(FLV/TS 直链):拒绝明显的网页/接口响应,其余单级判定
+ // 令牌失效/账号异常时,源常重定向到错误提示资源:本质不可用,但 HTTP 层是 200。
+ // 仍以 m3u8 结尾的重定向视为正常播放列表(如 /status/live.m3u8),不按占位资源处理。
+ if (entry.finalUrl !== url) {
+ try {
+ const pathname = new URL(entry.finalUrl).pathname;
+ if (!/\.m3u8?$/i.test(pathname) && ERROR_PLACEHOLDER_RE.test(pathname)) {
+ return {
+ url,
+ ok: false,
+ status: entry.status,
+ ms: elapsed(start),
+ error: '源返回错误占位内容(令牌失效 / 账号异常)',
+ };
+ }
+ } catch { /* 忽略 URL 解析失败 */ }
+ }
+
+ // 非 m3u8(FLV/TS 直链):拒绝明显的网页/接口响应,其余仅标记"可达"(level=head,未验证可播性)
if (!entry.isM3u8) {
if (isWebPageType(entry.contentType)) {
return {
@@ -279,6 +307,7 @@ async function probeOne(url: string): Promise<ProbeOutcome> {
url,
ok: false,
ms: elapsed(start),
+ timedOut: timedOut || undefined,
error: timedOut ? `探测超时(${URL_BUDGET_MS}ms)` : err instanceof Error ? err.message : '探测失败',
};
}
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index 43398d8..0d94e3c 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -254,12 +254,22 @@ function ChannelRow({
// H.265/HEVC:国内 IPTV 常见,测活通过但 Chromium 内核通常无法软解
const isHevc = Boolean(probe?.codec && /hvc1|hev1|hevc/i.test(probe.codec));
+ // 状态点语义:绿=分片级验证通过;琥珀=仅弱验证(直链/清单级)或超时(源可能只是慢);红=不可达
+ const weakLevel = probe?.ok && probe.level !== 'segment';
+ const amber = Boolean(probe && (weakLevel || (!probe.ok && probe.timedOut)));
+ const dotClass = amber ? 'bg-amber-400' : probe?.ok ? 'bg-green-500' : 'bg-red-400';
const levelText =
- probe?.level === 'segment' ? '分片可用' : probe?.level === 'head' ? '直链可达' : 'manifest 可用';
+ probe?.level === 'segment'
+ ? '分片可用'
+ : probe?.level === 'head'
+ ? '直链可达(未验证可播性)'
+ : '播放列表可达(无分片,未验证可播)';
const probeTitle = probe
? probe.ok
- ? `${levelText}${probe.ms != null ? ` · 分片耗时 ${probe.ms}ms` : ''}${isHevc ? ' · H.265 编码,需 Edge/Safari' : ''}`
- : probe.error || '不可用'
+ ? `${levelText}${probe.ms != null && probe.level === 'segment' ? ` · 分片耗时 ${probe.ms}ms` : ''}${isHevc ? ' · H.265 编码,需 Edge/Safari' : ''}`
+ : probe.timedOut
+ ? `${probe.error || '探测超时'} · 源可能只是慢,可直接试播确认`
+ : probe.error || '不可用'
: undefined;
return (
@@ -307,10 +317,7 @@ function ChannelRow({
<div className="flex items-center gap-1.5 min-w-0">
{probe && (
<span
- className={cn(
- 'w-1.5 h-1.5 rounded-full shrink-0',
- probe.ok ? 'bg-green-500' : 'bg-red-400'
- )}
+ className={cn('w-1.5 h-1.5 rounded-full shrink-0', dotClass)}
title={probeTitle}
/>
)}
diff --git a/src/components/live-player.tsx b/src/components/live-player.tsx
index 5020416..b3a60a3 100644
--- a/src/components/live-player.tsx
+++ b/src/components/live-player.tsx
@@ -6,8 +6,11 @@ import Hls, { type HlsConfig } from 'hls.js';
/**
* 直播播放器:与点播 player-shell 完全独立。
- * - 协议分发:.m3u8 → hls.js(直播参数);.flv → mpegts.js(动态加载,按需 ~150KB);
- * - 直连失败自动切换到 /api/live/stream/ 代理通道重试一次;
+ * - 引擎分发:.m3u8 → hls.js(直播参数);.flv → mpegts.js(动态加载,按需 ~150KB);
+ * mp4/webm 等原生容器 → <video> 直接播放;
+ * - 无扩展名的地址(如 /channel/xxx?token=...)默认按 HLS 处理,
+ * HLS 直连与代理均失败后**回退原生播放**一次(覆盖"内容是 MP4 却无 .m3u8 后缀"的源);
+ * - 每级直连失败自动切换到 /api/live/stream/ 代理通道重试一次;
* - 直播态 UI:无进度条、无倍速、无截图、无连播。
*/
@@ -17,6 +20,17 @@ export function isFlvUrl(url: string): boolean {
return /\.flv(\?|$)/i.test(url);
}
+/** 浏览器原生可播的直链容器(非 HLS/FLV) */
+const NATIVE_MEDIA_RE = /\.(mp4|m4v|webm|ogv|ogg|mov)(\?|$)/i;
+
+type Engine = 'hls' | 'flv' | 'native';
+
+function engineOf(url: string): Engine {
+ if (isFlvUrl(url)) return 'flv';
+ if (NATIVE_MEDIA_RE.test(url)) return 'native';
+ return 'hls';
+}
+
function proxyUrl(url: string): string {
return STREAM_PROXY_PREFIX + encodeURIComponent(url);
}
@@ -58,6 +72,8 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
let playbackStarted = false;
let disposed = false;
let destroyed = false;
+ /** 原生播放注册的 error 监听清理函数(切台/销毁时调用) */
+ let nativeCleanup: (() => void) | null = null;
const cleanupEngines = () => {
hlsRef.current?.destroy();
@@ -67,10 +83,44 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
try { mpegtsRef.current.destroy(); } catch { /* 忽略 */ }
mpegtsRef.current = null;
}
+ if (nativeCleanup) {
+ try { nativeCleanup(); } catch { /* 忽略 */ }
+ nativeCleanup = null;
+ }
+ };
+
+ /**
+ * 原生播放:mp4/webm 等容器交给 <video> 直接播放。
+ * 也作为 HLS 两级都失败后的兜底——覆盖"地址没有 .m3u8 后缀但内容其实是 MP4"的源。
+ * 直连失败(CORS/混合内容)时再走一次代理。
+ */
+ const setupNative = (
+ video: HTMLVideoElement,
+ mediaUrl: string,
+ allowProxyFallback: boolean,
+ failMessage?: string
+ ) => {
+ cleanupEngines();
+ const onError = () => {
+ video.removeEventListener('error', onError);
+ nativeCleanup = null;
+ if (disposed || destroyed) return;
+ if (allowProxyFallback && !mediaUrl.startsWith(STREAM_PROXY_PREFIX)) {
+ showHint('直连失败,改用代理重试...');
+ setupNative(video, proxyUrl(url), false, failMessage);
+ return;
+ }
+ setError(failMessage || '该地址不是可播放的直播流(内容可能是文件或错误提示)');
+ };
+ video.addEventListener('error', onError);
+ nativeCleanup = () => video.removeEventListener('error', onError);
+ video.src = mediaUrl;
+ video.load();
+ video.play().catch(() => {});
};
/** HLS 直播参数:小缓冲、快速追帧;与点播(大缓冲、进度恢复)刻意区分 */
- const setupHls = (video: HTMLVideoElement, mediaUrl: string, allowProxyFallback: boolean) => {
+ const setupHls = (video: HTMLVideoElement, mediaUrl: string, stage: 'direct' | 'proxy') => {
cleanupEngines();
let liveNetRetryCount = 0;
let mediaRecoverCount = 0;
@@ -119,16 +169,18 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
}
if (!playbackStarted) {
if (
- allowProxyFallback &&
+ stage === 'direct' &&
!mediaUrl.startsWith(STREAM_PROXY_PREFIX) &&
(data.details === 'manifestLoadError' || data.type === Hls.ErrorTypes.NETWORK_ERROR)
) {
showHint('直连失败,改用代理重试...');
// 直播 manifest 重写需要本站前缀,交给代理通道
- setupHls(video, proxyUrl(url), false);
+ setupHls(video, proxyUrl(url), 'proxy');
return;
}
- setError(`直播流加载失败${codeHint},可能该频道已失效,请尝试其他频道`);
+ // HLS 直连与代理均失败:可能是"无 .m3u8 后缀但内容是 MP4"的源,回退原生播放
+ showHint('HLS 解析失败,尝试原生播放...');
+ setupNative(video, url, true, `直播流加载失败${codeHint},可能该频道已失效,请尝试其他频道`);
return;
}
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
@@ -191,10 +243,12 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
player.play().catch(() => {});
};
+ const engine = engineOf(url);
const art = new Artplayer({
container: containerRef.current,
url,
- type: isFlvUrl(url) ? 'flv' : 'm3u8',
+ // 原生容器统一用 'mp4'(仅用于选择处理函数,实际容器由浏览器嗅探)
+ type: engine === 'flv' ? 'flv' : engine === 'native' ? 'mp4' : 'm3u8',
volume: 0.9,
autoplay: true,
// —— 直播态:关闭点播专属能力 ——
@@ -216,11 +270,14 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
moreVideoAttr: { playsInline: true },
customType: {
m3u8: (video: HTMLVideoElement) => {
- setupHls(video, url, true);
+ setupHls(video, url, 'direct');
},
flv: (video: HTMLVideoElement) => {
void setupFlv(video, url, true);
},
+ mp4: (video: HTMLVideoElement) => {
+ setupNative(video, url, true);
+ },
},
});
artRef.current = art;
diff --git a/src/components/use-live-probe.ts b/src/components/use-live-probe.ts
index 3c0aaf8..33af226 100644
--- a/src/components/use-live-probe.ts
+++ b/src/components/use-live-probe.ts
@@ -19,6 +19,8 @@ export interface ProbeResult {
level?: 'segment' | 'manifest' | 'head';
error?: string;
codec?: string;
+ /** 因超时失败(源可能只是慢) */
+ timedOut?: boolean;
}
const CHUNK_SIZE = 50;
@@ -55,7 +57,14 @@ export function useLiveProbe() {
const map = new Map<string, ProbeResult>();
for (const [url, e] of Object.entries(cache)) {
if (now - e.timestamp < LIVE_PROBE_TTL_MS) {
- map.set(url, { ok: e.ok, ms: e.ms, level: e.level, error: e.error, codec: e.codec });
+ map.set(url, {
+ ok: e.ok,
+ ms: e.ms,
+ level: e.level,
+ error: e.error,
+ codec: e.codec,
+ timedOut: e.timedOut,
+ });
}
}
return map;
@@ -139,6 +148,7 @@ export function useLiveProbe() {
level: r.level,
error: r.error,
codec: r.codec,
+ timedOut: r.timedOut,
timestamp: Date.now(),
};
done++;
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index 81fe9fd..b630198 100644
--- a/src/lib/client-api.ts
+++ b/src/lib/client-api.ts
@@ -29,6 +29,8 @@ export interface LiveProbeResult {
error?: string;
/** master playlist 的 CODECS,用于前端提示 H.265 等不可解码情况 */
codec?: string;
+ /** 因超时失败:源可能只是慢,前端以琥珀色区分于真正的不可达 */
+ timedOut?: boolean;
}
export function onUnauthorized(handler: (event: CustomEvent) => void): () => void {
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 9d27e26..628ec2f 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -74,6 +74,8 @@ export interface LiveProbeEntry {
error?: string;
/** 流编码(master playlist 的 CODECS 属性),用于提示 H.265 等不可解码情况 */
codec?: string;
+ /** 因超时失败(源可能只是慢),前端以琥珀色区分展示 */
+ timedOut?: boolean;
/** 测活时间戳(epoch ms),配合 TTL 判断有效性 */
timestamp: number;
}