Skip to content

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

fix(ad): 周期性 DISCONTINUITY 封装源不误杀正常片头(如 rycjapi 每30s一组)

bestZweic8033001da6b
diff --git a/src/lib/m3u8.test.ts b/src/lib/m3u8.test.ts
index f49fb9b..a494aba 100644
--- a/src/lib/m3u8.test.ts
+++ b/src/lib/m3u8.test.ts
@@ -110,6 +110,22 @@ describe('stripLeadAdGroup', () => {
it('空内容返回空串', () => {
expect(stripLeadAdGroup('')).toBe('');
});
+
+ it('周期性 DISCONTINUITY 封装(每 N 片一个标记):不误杀片头正常分组', () => {
+ // 模拟 rycjapi 类源:多分组、每组 5 片、相邻 DISCONTINUITY 间隙均匀(非广告)
+ const lines = ['#EXTM3U', '#EXT-X-PLAYLIST-TYPE:VOD', '#EXT-X-VERSION:3'];
+ const groups = 12;
+ for (let g = 0; g < groups; g++) {
+ lines.push('#EXT-X-DISCONTINUITY');
+ for (let s = 0; s < 5; s++) lines.push('#EXTINF:6,', `g${g}_s${s}.ts`);
+ }
+ lines.push('#EXT-X-ENDLIST');
+ const input = lines.join('\n');
+ const out = stripLeadAdGroup(input);
+ // 片头第一组(g0_s0.ts)必须保留,整体原样返回
+ expect(out).toBe(input);
+ expect(out).toContain('g0_s0.ts');
+ });
});
describe('stripAdGroups', () => {
diff --git a/src/lib/m3u8.ts b/src/lib/m3u8.ts
index 3fb25c8..0ff0bd7 100644
--- a/src/lib/m3u8.ts
+++ b/src/lib/m3u8.ts
@@ -62,6 +62,7 @@ const LEAD_AD_MAX_SEGMENTS = 20;
* hls.js 把整条流当连续时间轴,视频丢帧、音频错位,出现「只闻广告声不见其画面」)。
*
* 保守判定(全部满足才剔除):
+ * 0. 整片不是「周期性 DISCONTINUITY 封装」(否则片头与正片分组结构一致,跳过以免误杀);
* 1. 首个分片之前存在 DISCONTINUITY(存在「片头插入段」结构);
* 2. 该段以下一个 DISCONTINUITY 结束,且其后仍有分段(否则无法与正片区分);
* 3. 段时长 ≤ 90s 且分片数 ≤ 20。
@@ -79,12 +80,31 @@ export function stripLeadAdGroup(m3u8Content: string): string {
return t !== '' && !t.startsWith('#');
};
- const firstDisc = lines.findIndex(isDisc);
- if (firstDisc === -1) return m3u8Content;
+ // 周期性 DISCONTINUITY(部分采集站把每 ~N 个分片衔接处都打标记)不是广告:
+ // 这种封装下每个分组都被 DISCONTINUITY 框住,片头分组与正片分组结构一致、无法区分,
+ // 强行剔除会把正常片头当广告误杀。故先判断整片是否为「周期性封装」——
+ // 间隙(相邻 DISCONTINUITY 间的分片数)均匀且数量较多时,整段跳过片头剔除。
+ const discIdx: number[] = [];
+ for (let i = 0; i < lines.length; i++) if (isDisc(lines[i])) discIdx.push(i);
+ if (discIdx.length >= 4) {
+ const gaps: number[] = [];
+ for (let g = 0; g < discIdx.length - 1; g++) {
+ let seg = 0;
+ for (let k = discIdx[g] + 1; k < discIdx[g + 1]; k++) if (isSegment(lines[k])) seg += 1;
+ gaps.push(seg);
+ }
+ const mean = gaps.reduce((a, b) => a + b, 0) / gaps.length;
+ const variance = gaps.reduce((a, b) => a + (b - mean) ** 2, 0) / gaps.length;
+ const cv = mean > 0 ? Math.sqrt(variance) / mean : 0;
+ if (cv < 0.5) return m3u8Content; // 间隙均匀 ⇒ 周期性封装,跳过片头剔除
+ }
+
+ const firstDisc = discIdx[0];
+ if (firstDisc === undefined) return m3u8Content;
if (lines.slice(0, firstDisc).some(isSegment)) return m3u8Content;
- const nextDisc = lines.findIndex((l, i) => i > firstDisc && isDisc(l));
- if (nextDisc === -1) return m3u8Content;
+ const nextDisc = discIdx.slice(1).find((i) => i > firstDisc);
+ if (nextDisc === undefined) return m3u8Content;
let seconds = 0;
let count = 0;