Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/lib/m3u8.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,24 @@ describe('rewriteM3u8', () => {
expect(out).toContain('#EXT-X-ENDLIST');
});

it('主播放列表里 EXT-X-MEDIA 音轨/字幕与 I 帧播放列表的 URI 也改写为代理地址', () => {
const input = [
'#EXTM3U',
'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="English",DEFAULT=YES,URI="audio/en.m3u8"',
'#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="sub",NAME="中文",URI="/subs/zh.m3u8"',
'#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=86000,URI="iframe.m3u8"',
'#EXT-X-STREAM-INF:BANDWIDTH=1280000,AUDIO="aud",SUBTITLES="sub"',
'720p.m3u8',
].join('\n');

const out = rewriteM3u8(input, BASE);

expect(out).toContain('URI="/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/live/audio/en.m3u8') + '"');
expect(out).toContain('URI="/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/subs/zh.m3u8') + '"');
expect(out).toContain('URI="/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/live/iframe.m3u8') + '"');
expect(out).toContain('GROUP-ID="aud",NAME="English",DEFAULT=YES,');
});

it('直播前缀改写为 /api/live/stream?url= 形式', () => {
const out = rewriteM3u8('https://cdn.example.com/live/seg1.ts', BASE, 0, '/api/live/stream?url=');
expect(out).toBe('/api/live/stream?url=' + encodeURIComponent('https://cdn.example.com/live/seg1.ts'));
Expand Down
5 changes: 4 additions & 1 deletion src/lib/m3u8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ export function makeAbsolute(url: string, base: string | undefined): string {
}
}

/** 通过 URI 属性引用资源的标签:key/map,以及主播放列表里的备用音轨/字幕(EXT-X-MEDIA)和 I 帧播放列表 */
const URI_ATTR_TAGS = ['#EXT-X-KEY', '#EXT-X-MAP', '#EXT-X-MEDIA:', '#EXT-X-I-FRAME-STREAM-INF', '#EXT-X-SESSION-KEY'];

/** 将 m3u8 中的地址改写为经过本站代理的地址(分片/key/map 同样改写)。
* prefix 可指定代理地址基座(直播流走 /api/live/stream?url=,点播默认 /api/proxy?url=) */
export function rewriteM3u8(
Expand All @@ -46,7 +49,7 @@ export function rewriteM3u8(
if (depth > 5) return content;
const lines = content.split('\n');
const out = lines.map((line) => {
if (line.startsWith('#EXT-X-KEY') || line.startsWith('#EXT-X-MAP')) {
if (URI_ATTR_TAGS.some((tag) => line.startsWith(tag))) {
return line.replace(/(URI=")([^"]+)(")/g, (m, p1: string, uri: string, p2: string) => {
if (isProxiedUri(uri)) return m;
return p1 + prefix + encodeURIComponent(makeAbsolute(uri, baseUrl)) + p2;
Expand Down
Loading