Skip to content

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

feat(live): 测活吞吐测速识别限速源,换台 OSD 与一键切回,版本 2.9.3

bestZwei08a5505abd64
diff --git a/package-lock.json b/package-lock.json
index 5b05f3c..644e9dd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "libretv",
- "version": "2.9.2",
+ "version": "2.9.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "libretv",
- "version": "2.9.2",
+ "version": "2.9.3",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@tanstack/react-query": "^5.59.0",
diff --git a/package.json b/package.json
index 2da44f9..8faa8fa 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv",
- "version": "2.9.2",
+ "version": "2.9.3",
"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 1af4161..eb682ac 100644
--- a/src/app/api/live/probe/route.test.ts
+++ b/src/app/api/live/probe/route.test.ts
@@ -260,7 +260,9 @@ describe('POST /api/live/probe', () => {
const segmentCalls = seen.filter((s) => s.url.includes('seg1.ts'));
expect(segmentCalls.length).toBeGreaterThan(0);
- expect(segmentCalls.every((c) => c.range === 'bytes=0-1')).toBe(true);
+ // 可达性检查 bytes=0-1(收到响应头即 cancel)+ 吞吐采样 bytes=0-131071
+ expect(segmentCalls.some((c) => c.range === 'bytes=0-1')).toBe(true);
+ expect(segmentCalls.every((c) => c.range === 'bytes=0-1' || c.range === 'bytes=0-131071')).toBe(true);
});
it('未开启 LIVE_ALLOW_PRIVATE 时拒绝内网地址', async () => {
diff --git a/src/app/api/live/probe/route.ts b/src/app/api/live/probe/route.ts
index fe52679..01a0d3e 100644
--- a/src/app/api/live/probe/route.ts
+++ b/src/app/api/live/probe/route.ts
@@ -26,6 +26,7 @@ export const dynamic = 'force-dynamic';
* - 请求带源站 Referer,消除「源校验 Referer 导致的可播却测不通」假阴性;
* - 校验 m3u8 的 #EXTM3U 前缀与直链的 content-type,剔除 200 的 HTML/JSON 错误页;
* - master playlist 解析 CODECS 一并返回,前端据此提示 H.265 等浏览器无法解码的情况;
+ * - 分片级通过后额外采样 128KB 实际吞吐(kbps),识别「可达但限速」的源;
* - 走直播侧 SSRF 口径(allowPrivate):LIVE_ALLOW_PRIVATE=1 时自建内网 IPTV 同样能测通;
* - `?stream=1` 以 NDJSON 逐条推送结果(命中缓存的立即返回),前端状态点可边测边亮;
* 不带该参数时仍返回整批 JSON,保持向后兼容。
@@ -43,6 +44,15 @@ const URL_BUDGET_MS = 10_000;
const LEVEL_TIMEOUT_MS = 5000;
/** 分片级最长等待:分片只需响应头;部分服务器忽略 Range 会整段返回,留足余量 */
const SEGMENT_TIMEOUT_MS = 4000;
+/**
+ * 分片吞吐采样:Range 拉 128KB(或 2.5s 截止)估算实际带宽。
+ * Range: bytes=0-1 只能验证「分片可达」,覆盖不了「限速源」——
+ * 实测存在 206 秒回但整段下载仅 ~58kbps 的源,永远缓冲不起来(绿点却播不了)。
+ */
+const THROUGHPUT_BYTES = 128 * 1024;
+const THROUGHPUT_BUDGET_MS = 2500;
+/** 吞吐采样所需的最低剩余预算:预算不足时跳过采样,避免拖长探测长尾 */
+const THROUGHPUT_MIN_REMAINING_MS = 1500;
/** 结果缓存:成功结果稳定,失败可能是瞬断,分开设置 */
const CACHE_TTL_OK_MS = 10 * 60 * 1000;
const CACHE_TTL_FAIL_MS = 2 * 60 * 1000;
@@ -62,6 +72,8 @@ interface ProbeOutcome {
codec?: string;
/** 因超出时间预算而失败(源可能只是慢,不代表不可播),前端据此区分展示 */
timedOut?: boolean;
+ /** 分片吞吐估算(kbps):低于阈值的源前端标记为「源限速」琥珀色 */
+ kbps?: number;
}
interface FetchHeadResult {
@@ -198,6 +210,49 @@ function elapsed(start: number): number {
return Math.round(performance.now() - start);
}
+/**
+ * 分片吞吐采样:Range 拉 128KB(或 2.5s 截止),按实际收到的字节数估算 kbps。
+ * 与分片可达性检查是两次独立请求(前者只取响应头即 cancel)。
+ * 服务器忽略 Range 时按整段返回,读到 THROUGHPUT_BYTES 即停,不影响估算。
+ */
+async function measureThroughput(segmentUrl: string, referer?: string): Promise<number | undefined> {
+ const start = performance.now();
+ try {
+ const { res } = await fetchUpstreamWithMeta(segmentUrl, {
+ timeoutMs: 3000,
+ retries: 0,
+ headers: {
+ 'User-Agent': UA,
+ Accept: '*/*',
+ Range: `bytes=0-${THROUGHPUT_BYTES - 1}`,
+ ...(referer ? { Referer: referer } : {}),
+ },
+ allowPrivate: true,
+ });
+ if (!res.ok || !res.body) return undefined;
+ const reader = res.body.getReader();
+ let bytes = 0;
+ for (;;) {
+ const remaining = THROUGHPUT_BUDGET_MS - (performance.now() - start);
+ if (remaining <= 0) break;
+ const chunk = await Promise.race([
+ reader.read(),
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), remaining)),
+ ]);
+ if (!chunk || chunk.done) break;
+ bytes += chunk.value?.length ?? 0;
+ if (bytes >= THROUGHPUT_BYTES) break;
+ }
+ try { await reader.cancel(); } catch { /* 忽略 */ }
+ try { await res.body.cancel(); } catch { /* 忽略 */ }
+ const secs = (performance.now() - start) / 1000;
+ if (bytes <= 0 || secs < 0.05) return undefined;
+ return Math.round((bytes * 8) / secs / 1000);
+ } catch {
+ return undefined;
+ }
+}
+
/** 两级探测:manifest →(master 时穿透 variant)→ 分片 */
async function probeOne(url: string): Promise<ProbeOutcome> {
const start = performance.now();
@@ -292,14 +347,30 @@ async function probeOne(url: string): Promise<ProbeOutcome> {
);
// ms 只统计分片往返:三级累计耗时当作「延迟」对用户没有参考意义
const segmentMs = elapsed(segmentStart);
+ if (!segment.ok) {
+ return {
+ url,
+ ok: false,
+ status: segment.status,
+ ms: segmentMs,
+ level: 'segment',
+ codec,
+ error: `分片响应 ${segment.status}`,
+ };
+ }
+ // 分片可达:采样实际吞吐,识别「可达但限速」的源(绿点却播不了的主因)
+ const kbps =
+ remaining() > THROUGHPUT_MIN_REMAINING_MS
+ ? await measureThroughput(segmentUrl, referer)
+ : undefined;
return {
url,
- ok: segment.ok,
+ ok: true,
status: segment.status,
ms: segmentMs,
level: 'segment',
codec,
- error: segment.ok ? undefined : `分片响应 ${segment.status}`,
+ kbps,
};
} catch (err) {
const timedOut = performance.now() >= deadline;
diff --git a/src/app/live/page.tsx b/src/app/live/page.tsx
index 47ed342..dd0b1d7 100644
--- a/src/app/live/page.tsx
+++ b/src/app/live/page.tsx
@@ -64,6 +64,10 @@ function LiveContent() {
const [listOpen, setListOpen] = useState(false);
/** 侧栏上报的筛选排序结果(键盘换台沿此列表顺序);ref 存储,不触发重渲染 */
const filteredRef = useRef<LiveChannelItem[]>([]);
+ /** 当前频道镜像:selectChannel 内读取最近一次播放的频道,用于记录"上一个频道" */
+ const currentChannelRef = useRef<LiveChannelItem | undefined>(undefined);
+ /** 上一个频道:退格键/按钮一键切回(电视遥控器 back 键习惯) */
+ const lastChannelRef = useRef<LiveChannelItem | null>(null);
// 仅聚合已启用的直播源(设置 → 直播源中的勾选状态)
const sources = useMemo(() => {
@@ -119,8 +123,14 @@ function LiveContent() {
} as LiveChannelItem;
}, [channels, currentUrl, searchParams]);
+ useEffect(() => {
+ currentChannelRef.current = currentChannel;
+ }, [currentChannel]);
+
const selectChannel = useCallback(
(c: LiveChannelItem) => {
+ const cur = currentChannelRef.current;
+ if (cur && cur.url !== c.url) lastChannelRef.current = cur;
const sp = new URLSearchParams({ url: c.url, name: c.name });
if (c.group) sp.set('group', c.group);
if (c.tvgId) sp.set('tvgId', c.tvgId);
@@ -160,10 +170,20 @@ function LiveContent() {
const goPrevChannel = useCallback(() => switchChannelByOffset(-1), [switchChannelByOffset]);
const goNextChannel = useCallback(() => switchChannelByOffset(1), [switchChannelByOffset]);
- // 全局键盘换台:↑↓ 直接切台。输入框/列表光标导航场景让位(列表聚焦时由列表内 ↑↓ 管理光标)
+ /** 切回上一个频道(Backspace / 信息条按钮) */
+ const backToPrevChannel = useCallback(() => {
+ const prev = lastChannelRef.current;
+ if (!prev) return;
+ lastChannelRef.current = null;
+ selectChannel(prev);
+ }, [selectChannel]);
+
+ // 全局键盘:↑↓ 直接切台,Backspace 切回上一个频道。
+ // 输入框/列表光标导航场景让位(列表聚焦时由列表内 ↑↓ 管理光标)
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
- if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
+ const isChannelKey = e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Backspace';
+ if (!isChannelKey) return;
if (e.repeat || e.altKey || e.ctrlKey || e.metaKey) return;
const target = e.target as HTMLElement | null;
if (target) {
@@ -173,11 +193,12 @@ function LiveContent() {
if (target.closest('[data-channel-list]')) return;
}
e.preventDefault();
- switchChannelByOffset(e.key === 'ArrowDown' ? 1 : -1);
+ if (e.key === 'Backspace') backToPrevChannel();
+ else switchChannelByOffset(e.key === 'ArrowDown' ? 1 : -1);
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, [switchChannelByOffset]);
+ }, [switchChannelByOffset, backToPrevChannel]);
const handleSelect = useCallback(
(c: LiveChannelItem) => {
@@ -255,6 +276,26 @@ function LiveContent() {
<p className="text-xs text-faint truncate mt-0.5">{currentChannel.url}</p>
</div>
<div className="flex items-center gap-1 shrink-0">
+ <button
+ className={cn(
+ 'rounded-md p-2 transition-colors',
+ lastChannelRef.current
+ ? 'text-muted hover:text-accent hover:bg-hover'
+ : 'text-faint/40 cursor-default'
+ )}
+ aria-label="上一个频道"
+ title={lastChannelRef.current ? `上一个频道:${lastChannelRef.current.name}(Backspace)` : '暂无上一个频道'}
+ onClick={backToPrevChannel}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M9 15L4 10l5-5m-5 5h10.5a5.5 5.5 0 015.5 5.5V17"
+ />
+ </svg>
+ </button>
<button
className="rounded-md p-2 text-muted hover:text-accent hover:bg-hover transition-colors"
aria-label="上一台"
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index f878d70..d79ccda 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -4,6 +4,7 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { buildImageUrl, cn } from '@/lib/utils';
import { useAppStore } from '@/lib/store';
import {
+ isSlowSource,
matchesAlive,
matchesKeyword,
normalizeForSearch,
@@ -403,9 +404,11 @@ const ChannelRow = memo(function ChannelRow({
// H.265/HEVC:国内 IPTV 常见,测活通过但 Chromium 内核通常无法软解
const isHevc = Boolean(probe?.codec && /hvc1|hev1|hevc/i.test(probe.codec));
- // 状态点语义:绿=分片级验证通过;琥珀=弱验证(直链/清单级)或超时(源可能只是慢);红=不可达
+ // 源限速:分片可达但吞吐不足,绿点却播不了的主因
+ const slow = isSlowSource(probe);
+ // 状态点语义:绿=分片级验证且吞吐达标;琥珀=限速/弱验证(直链/清单级)或超时;红=不可达
const weakLevel = probe?.ok && probe.level !== 'segment';
- const amber = Boolean(probe && (weakLevel || (!probe.ok && probe.timedOut)));
+ const amber = Boolean(probe && (weakLevel || (!probe.ok && probe.timedOut) || slow));
const dotClass = amber ? 'bg-amber-400' : probe?.ok ? 'bg-green-500' : 'bg-red-400';
const levelText =
probe?.level === 'segment'
@@ -413,9 +416,15 @@ const ChannelRow = memo(function ChannelRow({
: probe?.level === 'head'
? '直链可达(未验证可播性)'
: '播放列表可达(无分片,未验证可播)';
+ const speedText =
+ probe?.kbps != null && probe.level === 'segment'
+ ? ` · ≈${probe.kbps >= 1000 ? `${(probe.kbps / 1000).toFixed(1)}Mbps` : `${probe.kbps}kbps`}`
+ : '';
const probeTitle = probe
? probe.ok
- ? `${levelText}${probe.ms != null && probe.level === 'segment' ? ` · 分片耗时 ${probe.ms}ms` : ''}${isHevc ? ' · H.265 编码,需 Edge/Safari' : ''}`
+ ? slow
+ ? `源限速${speedText.replace(' · ', ' ')},缓冲跟不上,可能无法流畅播放`
+ : `${levelText}${speedText}${probe.ms != null && probe.level === 'segment' ? ` · 延迟 ${probe.ms}ms` : ''}${isHevc ? ' · H.265 编码,需 Edge/Safari' : ''}`
: probe.timedOut
? `${probe.error || '探测超时'} · 源可能只是慢,可直接试播确认`
: probe.error || '不可用'
diff --git a/src/components/live-player.tsx b/src/components/live-player.tsx
index ed052c4..6295706 100644
--- a/src/components/live-player.tsx
+++ b/src/components/live-player.tsx
@@ -58,8 +58,22 @@ export function LivePlayer({ url, title, onPrevChannel, onNextChannel }: LivePla
const [retryNonce, setRetryNonce] = useState(0);
// 起播前的品牌占位图(与点播 player-shell 共用 /player-poster.png),实际开始播放后隐藏
const [showPoster, setShowPoster] = useState(true);
+ // 换台 OSD:切台后短暂显示频道名(键盘换台/控制条换台时的视觉反馈,全屏内同样可见)
+ const [osdTitle, setOsdTitle] = useState('');
+ const osdTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hintTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // url 变化即换台:显示频道名 2.5s
+ useEffect(() => {
+ if (!url) return;
+ setOsdTitle(title);
+ if (osdTimerRef.current) clearTimeout(osdTimerRef.current);
+ osdTimerRef.current = setTimeout(() => setOsdTitle(''), 2500);
+ return () => {
+ if (osdTimerRef.current) clearTimeout(osdTimerRef.current);
+ };
+ }, [url, title]);
+
const showHint = (text: string) => {
setHint(text);
if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
@@ -375,6 +389,12 @@ export function LivePlayer({ url, title, onPrevChannel, onNextChannel }: LivePla
<span className="text-[10px] font-semibold text-white tracking-wider">LIVE</span>
</div>
)}
+ {/* 换台 OSD:频道名(全屏内同样可见) */}
+ {osdTitle && !error && (
+ <div className="absolute top-3 left-3 flex items-center max-w-[70%] bg-black/60 px-3 py-1.5 rounded-full pointer-events-none animate-fade-in">
+ <span className="text-sm font-medium text-white truncate">{osdTitle}</span>
+ </div>
+ )}
{loading && !error && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 pointer-events-none">
<div className="h-9 w-9 rounded-full border-4 border-white/20 border-t-white animate-spin" />
diff --git a/src/components/use-live-probe.ts b/src/components/use-live-probe.ts
index 9ce7d7c..47945c9 100644
--- a/src/components/use-live-probe.ts
+++ b/src/components/use-live-probe.ts
@@ -21,6 +21,8 @@ export interface ProbeResult {
codec?: string;
/** 因超时失败(源可能只是慢) */
timedOut?: boolean;
+ /** 分片吞吐估算(kbps),低于阈值为「源限速」 */
+ kbps?: number;
}
const CHUNK_SIZE = 50;
@@ -72,6 +74,7 @@ export function useLiveProbe() {
error: e.error,
codec: e.codec,
timedOut: e.timedOut,
+ kbps: e.kbps,
};
if (!known || known.timestamp !== e.timestamp) identities.set(url, { timestamp: e.timestamp, result });
map.set(url, result);
@@ -164,6 +167,7 @@ export function useLiveProbe() {
error: r.error,
codec: r.codec,
timedOut: r.timedOut,
+ kbps: r.kbps,
timestamp: Date.now(),
};
done++;
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index b630198..cd35a0a 100644
--- a/src/lib/client-api.ts
+++ b/src/lib/client-api.ts
@@ -31,6 +31,8 @@ export interface LiveProbeResult {
codec?: string;
/** 因超时失败:源可能只是慢,前端以琥珀色区分于真正的不可达 */
timedOut?: boolean;
+ /** 分片吞吐估算(kbps):低于阈值的源前端标记为「源限速」 */
+ kbps?: number;
}
export function onUnauthorized(handler: (event: CustomEvent) => void): () => void {
diff --git a/src/lib/live-channel-filter.test.ts b/src/lib/live-channel-filter.test.ts
index 0365dc4..0f85349 100644
--- a/src/lib/live-channel-filter.test.ts
+++ b/src/lib/live-channel-filter.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
+ isSlowSource,
matchesAlive,
matchesKeyword,
normalizeForSearch,
@@ -47,6 +48,8 @@ describe('matchesKeyword', () => {
describe('matchesAlive', () => {
const green: ProbeLike = { ok: true, level: 'segment' };
+ const fast: ProbeLike = { ok: true, level: 'segment', kbps: 3000 };
+ const slow: ProbeLike = { ok: true, level: 'segment', kbps: 60 };
const weak: ProbeLike = { ok: true, level: 'head' };
const timeout: ProbeLike = { ok: false, timedOut: true };
const dead: ProbeLike = { ok: false };
@@ -56,23 +59,40 @@ describe('matchesAlive', () => {
expect(matchesAlive(dead, 'off')).toBe(true);
});
- it('ok 档:任何验证级别通过', () => {
- expect(matchesAlive(green, 'ok')).toBe(true);
+ it('ok 档:任何验证级别通过(含限速源)', () => {
+ expect(matchesAlive(fast, 'ok')).toBe(true);
+ expect(matchesAlive(slow, 'ok')).toBe(true);
expect(matchesAlive(weak, 'ok')).toBe(true);
expect(matchesAlive(timeout, 'ok')).toBe(false);
expect(matchesAlive(dead, 'ok')).toBe(false);
expect(matchesAlive(undefined, 'ok')).toBe(false);
});
- it('green 档:仅分片级验证', () => {
- expect(matchesAlive(green, 'green')).toBe(true);
+ it('green 档:仅分片级验证且吞吐达标', () => {
+ expect(matchesAlive(fast, 'green')).toBe(true);
+ expect(matchesAlive(green, 'green')).toBe(true); // 无吞吐数据不排除
+ expect(matchesAlive(slow, 'green')).toBe(false);
expect(matchesAlive(weak, 'green')).toBe(false);
});
});
+describe('isSlowSource', () => {
+ it('分片级 + kbps 低于阈值判为限速', () => {
+ expect(isSlowSource({ ok: true, level: 'segment', kbps: 58 })).toBe(true);
+ expect(isSlowSource({ ok: true, level: 'segment', kbps: 5000 })).toBe(false);
+ expect(isSlowSource({ ok: true, level: 'segment' })).toBe(false); // 未采样
+ expect(isSlowSource({ ok: true, level: 'head', kbps: 58 })).toBe(false);
+ expect(isSlowSource({ ok: false, level: 'segment', kbps: 58 })).toBe(false);
+ expect(isSlowSource(undefined)).toBe(false);
+ });
+});
+
describe('probeRank', () => {
- it('绿点 < 弱验证 < 超时 < 失败 < 未测', () => {
- expect(probeRank({ ok: true, level: 'segment' })).toBeLessThan(probeRank({ ok: true, level: 'head' }));
+ it('绿点 < 限速分片 < 弱验证 < 超时 < 失败 < 未测', () => {
+ expect(probeRank({ ok: true, level: 'segment', kbps: 3000 })).toBeLessThan(
+ probeRank({ ok: true, level: 'segment', kbps: 60 })
+ );
+ expect(probeRank({ ok: true, level: 'segment', kbps: 60 })).toBeLessThan(probeRank({ ok: true, level: 'head' }));
expect(probeRank({ ok: true, level: 'head' })).toBeLessThan(probeRank({ ok: false, timedOut: true }));
expect(probeRank({ ok: false, timedOut: true })).toBeLessThan(probeRank({ ok: false }));
expect(probeRank({ ok: false })).toBeLessThan(probeRank(undefined));
@@ -104,13 +124,26 @@ describe('sortChannels', () => {
expect(order.map((c) => c.url)).toEqual(['u2', 'u3']);
});
- it('probe 可用优先、同级按耗时升序', () => {
+ it('probe 可用优先、同级按带宽降序', () => {
const probeOf = (url: string): ProbeLike | undefined =>
- url === 'u3' ? { ok: true, level: 'head' } : url === 'u1' ? { ok: true, level: 'segment', ms: 200 } : { ok: false };
- // u1 绿点最快 → u3 弱验证 → u2 失败
+ url === 'u3' ? { ok: true, level: 'head' } : url === 'u1' ? { ok: true, level: 'segment', ms: 200, kbps: 3000 } : { ok: false };
+ // u1 绿点(带宽达标)→ u3 弱验证 → u2 失败
expect(sortChannels(list, 'probe', { probeOf }).map((c) => c.url)).toEqual(['u1', 'u3', 'u2']);
});
+ it('probe 同级绿点按带宽降序', () => {
+ const probeOf = (url: string): ProbeLike | undefined =>
+ url === 'u1' ? { ok: true, level: 'segment', kbps: 2000 } : url === 'u2' ? { ok: true, level: 'segment', kbps: 6000 } : { ok: true, level: 'segment', kbps: 4000 };
+ expect(sortChannels(list, 'probe', { probeOf }).map((c) => c.url)).toEqual(['u2', 'u3', 'u1']);
+ });
+
+ it('probe 限速源排在正常绿点之后', () => {
+ const probeOf = (url: string): ProbeLike | undefined =>
+ url === 'u1' ? { ok: true, level: 'segment', kbps: 60, ms: 10 } : url === 'u2' ? { ok: true, level: 'segment', kbps: 3000, ms: 500 } : { ok: false };
+ // u1 延迟更低但限速 → 排在 u2 之后
+ expect(sortChannels(list, 'probe', { probeOf }).map((c) => c.url)).toEqual(['u2', 'u1', 'u3']);
+ });
+
it('probe 未测频道排在已测之后', () => {
const probeOf = (url: string): ProbeLike | undefined => (url === 'u1' ? { ok: false } : undefined);
expect(sortChannels(list, 'probe', { probeOf }).map((c) => c.url)).toEqual(['u1', 'u2', 'u3']);
diff --git a/src/lib/live-channel-filter.ts b/src/lib/live-channel-filter.ts
index ae89547..8cf379b 100644
--- a/src/lib/live-channel-filter.ts
+++ b/src/lib/live-channel-filter.ts
@@ -12,11 +12,28 @@ export interface ProbeLike {
ms?: number;
level?: 'segment' | 'manifest' | 'head';
timedOut?: boolean;
+ kbps?: number;
}
export type LiveSortMode = 'default' | 'name' | 'group' | 'probe' | 'recent';
export type AliveFilter = 'off' | 'ok' | 'green';
+/**
+ * 「源限速」阈值(kbps):分片可达但吞吐低于该值的源无法流畅缓冲。
+ * 低于 1Mbps 的直播流基本必然卡顿,标记为琥珀色(介于绿点与不可达之间)。
+ */
+export const SLOW_SOURCE_KBPS = 1000;
+
+/** 分片可达但吞吐不足(测活绿点却播不了的主因) */
+export function isSlowSource(probe: ProbeLike | undefined): boolean {
+ return Boolean(
+ probe?.ok &&
+ probe.level === 'segment' &&
+ probe.kbps != null &&
+ probe.kbps < SLOW_SOURCE_KBPS
+ );
+}
+
/** 常见台名分隔符(空格、连字符、下划线、点、竖线、括号等),搜索时忽略 */
const SEPARATOR_RE = /[\s\-_./·|+()()[\]【】]/g;
@@ -41,20 +58,24 @@ export function matchesKeyword(channel: KeywordMatchable, normalizedKeyword: str
/**
* 可用性筛选:
- * - 'ok':任何验证级别通过(绿点或琥珀中的弱验证)
- * - 'green':仅分片级验证通过(真实可播置信度最高)
+ * - 'ok':任何验证级别通过(绿点、限速源或琥珀中的弱验证)
+ * - 'green':仅「分片级验证通过且吞吐达标」(真实可流畅播放置信度最高)
*/
export function matchesAlive(probe: ProbeLike | undefined, mode: AliveFilter): boolean {
if (mode === 'off') return true;
if (!probe?.ok) return false;
- return mode === 'ok' || probe.level === 'segment';
+ if (mode === 'green') return probe.level === 'segment' && !isSlowSource(probe);
+ return true;
}
-/** 探测状态排序权重:绿点 → 弱验证 → 超时 → 失败 → 未测 */
+/** 探测状态排序权重:绿点 → 限速分片 → 弱验证 → 超时 → 失败 → 未测 */
export function probeRank(probe: ProbeLike | undefined): number {
- if (!probe) return 4;
- if (probe.ok) return probe.level === 'segment' ? 0 : 1;
- return probe.timedOut ? 2 : 3;
+ if (!probe) return 5;
+ if (probe.ok) {
+ if (probe.level !== 'segment') return 2;
+ return isSlowSource(probe) ? 1 : 0;
+ }
+ return probe.timedOut ? 3 : 4;
}
export interface SortContext {
@@ -87,6 +108,8 @@ export function sortChannels<T extends KeywordMatchable & { url: string }>(
const pb = probeOf?.(b.url);
const rank = probeRank(pa) - probeRank(pb);
if (rank !== 0) return rank;
+ // 同级内:有吞吐数据的按带宽降序,否则按分片延迟升序
+ if (pa?.kbps != null && pb?.kbps != null && pa.kbps !== pb.kbps) return pb.kbps - pa.kbps;
return (pa?.ms ?? Number.POSITIVE_INFINITY) - (pb?.ms ?? Number.POSITIVE_INFINITY);
});
break;
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 2bfb1cd..d015475 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -76,6 +76,8 @@ export interface LiveProbeEntry {
codec?: string;
/** 因超时失败(源可能只是慢),前端以琥珀色区分展示 */
timedOut?: boolean;
+ /** 分片吞吐估算(kbps):低于阈值的源前端标记为「源限速」琥珀色 */
+ kbps?: number;
/** 测活时间戳(epoch ms),配合 TTL 判断有效性 */
timestamp: number;
}