Skip to content

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

修复 mux.js 导出的 MP4 moov 时长为真实值

bestZweiebe5c751acd4
diff --git a/src/lib/m3u8-downloader.ts b/src/lib/m3u8-downloader.ts
index 3475e42..c4af7b4 100644
--- a/src/lib/m3u8-downloader.ts
+++ b/src/lib/m3u8-downloader.ts
@@ -225,7 +225,9 @@ export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
// —— 顺序写出(转封装 / 拼接) ——
report(total, total, 'processing');
if (format === 'MP4') {
- const transmuxer = new StreamingTransmuxer(target);
+ // 传入整集时长:mux.js 恒把 moov 时长写成 0xFFFFFFFF(timescale 90000
+ // → 播放器显示 13:15:21),必须在写出 initSegment 前回填真实值
+ const transmuxer = new StreamingTransmuxer(target, { durationSeconds: parsed.totalDuration });
for (let i = 1; i <= total; i++) {
if (signal.aborted) return;
await pause.waitIfPaused();
diff --git a/src/lib/mp4-transmuxer.test.ts b/src/lib/mp4-transmuxer.test.ts
new file mode 100644
index 0000000..3c7badf
--- /dev/null
+++ b/src/lib/mp4-transmuxer.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import { patchInitSegmentDuration } from './mp4-transmuxer';
+
+const u32 = (v: number) =>
+ new Uint8Array([(v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff]);
+
+const readU32 = (b: Uint8Array, o: number) =>
+ ((b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
+
+function box(type: string, ...payloads: Uint8Array[]): Uint8Array {
+ const payloadLen = payloads.reduce((n, p) => n + p.length, 0);
+ const out = new Uint8Array(8 + payloadLen);
+ out.set(u32(out.length), 0);
+ for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
+ let off = 8;
+ for (const p of payloads) {
+ out.set(p, off);
+ off += p.length;
+ }
+ return out;
+}
+
+/** version 0 full box:version(1)+flags(3)=0,其后是若干 u32 字段 */
+function fullBox(fields: number[]): Uint8Array {
+ const out = new Uint8Array(4 + fields.length * 4);
+ fields.forEach((v, i) => out.set(u32(v), 4 + i * 4));
+ return out;
+}
+
+/** 按 mux.js 的实际布局搭最小 initSegment:ftyp + moov(mvhd + trak(tkhd)) */
+function initSegment(mvhdDuration: number, tkhdDuration: number): Uint8Array {
+ const ftyp = box('ftyp', new Uint8Array([0x69, 0x73, 0x6f, 0x6d]));
+ const mvhdBox = box('mvhd', fullBox([0, 0, 90_000, mvhdDuration])); // timescale 90000
+ const tkhdBox = box('tkhd', fullBox([0, 0, 1, 0, tkhdDuration]));
+ const moov = box('moov', mvhdBox, box('trak', tkhdBox));
+ const out = new Uint8Array(ftyp.length + moov.length);
+ out.set(ftyp, 0);
+ out.set(moov, ftyp.length);
+ return out;
+}
+
+// ftyp(12) + moov 头(8) → mvhd 头(8) → mvhd payload 起点 28
+const MVHD_PAYLOAD = 12 + 8 + 8;
+// + mvhd payload(20) + trak 头(8) + tkhd 头(8) → tkhd payload 起点 64
+const TKHD_PAYLOAD = MVHD_PAYLOAD + 20 + 8 + 8;
+
+describe('patchInitSegmentDuration', () => {
+ it('把 mvhd/tkhd 的 0xFFFFFFFF 哨兵值替换为真实时长(90000 时基)', () => {
+ const patched = patchInitSegmentDuration(initSegment(0xffffffff, 0xffffffff), 2730);
+ expect(readU32(patched, MVHD_PAYLOAD + 16)).toBe(2730 * 90_000);
+ expect(readU32(patched, TKHD_PAYLOAD + 20)).toBe(2730 * 90_000);
+ });
+
+ it('0xFFFFFFFF/90000 ≈ 47721.86s ≈ 13:15:21 —— 未修补时播放器看到的时长', () => {
+ expect(0xffffffff / 90_000).toBeCloseTo(47721.86, 1);
+ });
+
+ it('时长非正数 / 非有限值时原样返回', () => {
+ const init = initSegment(0xffffffff, 0xffffffff);
+ expect(patchInitSegmentDuration(init, 0)).toEqual(init);
+ expect(patchInitSegmentDuration(init, Number.NaN)).toEqual(init);
+ });
+
+ it('不修改入参缓冲', () => {
+ const init = initSegment(0xffffffff, 0xffffffff);
+ patchInitSegmentDuration(init, 60);
+ expect(readU32(init, MVHD_PAYLOAD + 16)).toBe(0xffffffff);
+ });
+});
diff --git a/src/lib/mp4-transmuxer.ts b/src/lib/mp4-transmuxer.ts
index 74cfe66..6b6532d 100644
--- a/src/lib/mp4-transmuxer.ts
+++ b/src/lib/mp4-transmuxer.ts
@@ -10,6 +10,85 @@ import muxjs from 'mux.js';
* 因此可以边下载边流式写入文件,不需要把整集聚合在内存里。
*/
+/** mux.js 写 mvhd 时用的 movie timescale(90kHz) */
+const MOVIE_TIMESCALE = 90_000;
+/** ISO BMFF 的「时长未知」哨兵值 */
+const UNKNOWN_DURATION = 0xffffffff;
+
+function readU32(buf: Uint8Array, off: number): number {
+ return ((buf[off] << 24) | (buf[off + 1] << 16) | (buf[off + 2] << 8) | buf[off + 3]) >>> 0;
+}
+
+function writeU32(buf: Uint8Array, off: number, value: number): void {
+ buf[off] = (value >>> 24) & 0xff;
+ buf[off + 1] = (value >>> 16) & 0xff;
+ buf[off + 2] = (value >>> 8) & 0xff;
+ buf[off + 3] = value & 0xff;
+}
+
+function boxType(buf: Uint8Array, off: number): string {
+ return String.fromCharCode(buf[off], buf[off + 1], buf[off + 2], buf[off + 3]);
+}
+
+/** 遍历 [start, end) 内的同级 box;遇到 size===1(64 位 largesize)或越界即放弃,避免误改 */
+function walkBoxes(
+ buf: Uint8Array,
+ start: number,
+ end: number,
+ visit: (type: string, payload: number, boxEnd: number) => void
+): void {
+ let off = start;
+ while (off + 8 <= end) {
+ const size = readU32(buf, off);
+ if (size < 8 || off + size > end) return;
+ visit(boxType(buf, off + 4), off + 8, off + size);
+ off += size;
+ }
+}
+
+/**
+ * 把 mux.js 初始化段里的「未知时长」哨兵值替换成真实时长。
+ *
+ * mux.js 的 `moov` 恒为 `mvhd(0xffffffff)`(`trak` 里 `tkhd` 同样),而它的 mvhd
+ * timescale 是 90000 —— 于是任何按 mvhd 读时长的播放器/资源管理器都会得到
+ * 0xFFFFFFFF / 90000 ≈ 47721.86s ≈ 13:15:21,即「每集下载出来都是 13 小时多」。
+ * 与片源无关,是封装层问题,只能在写出 initSegment 前就地回填。
+ *
+ * 只处理 version 0(mux.js 实际产物);version 1 的 8 字节 duration 不改写。
+ */
+export function patchInitSegmentDuration(init: Uint8Array, seconds: number): Uint8Array {
+ if (!Number.isFinite(seconds) || seconds <= 0) return init;
+ const ticks = Math.min(Math.round(seconds * MOVIE_TIMESCALE), UNKNOWN_DURATION - 1);
+ // 复制一份:initSegment 由 mux.js 内部生成,直接改可能污染其复用缓冲
+ const out = init.slice();
+ walkBoxes(out, 0, out.length, (type, payload, boxEnd) => {
+ if (type !== 'moov') return;
+ walkBoxes(out, payload, boxEnd, (childType, childPayload, childEnd) => {
+ if (childType === 'mvhd') {
+ // payload: version(1) flags(3) creation(4) modification(4) timescale(4) duration(4)
+ if (out[childPayload] === 0 && childPayload + 20 <= childEnd) {
+ writeU32(out, childPayload + 16, ticks);
+ }
+ return;
+ }
+ if (childType !== 'trak') return;
+ walkBoxes(out, childPayload, childEnd, (leafType, leafPayload, leafEnd) => {
+ if (leafType !== 'tkhd') return;
+ // payload: version(1) flags(3) creation(4) modification(4) track_ID(4) reserved(4) duration(4)
+ if (out[leafPayload] === 0 && leafPayload + 24 <= leafEnd) {
+ writeU32(out, leafPayload + 20, ticks);
+ }
+ });
+ });
+ });
+ return out;
+}
+
+export interface StreamingTransmuxerOptions {
+ /** 整集真实时长(秒);用于回填 moov 时长,缺省则保留「未知时长」哨兵值 */
+ durationSeconds?: number;
+}
+
export class StreamingTransmuxer {
private transmuxer: any;
private writer?: { write(data: Uint8Array): Promise<void>; close?(): Promise<void>; abort?(): Promise<void> };
@@ -17,14 +96,25 @@ export class StreamingTransmuxer {
private segmentCount = 0;
private writeChain: Promise<void> = Promise.resolve();
private writeError: Error | undefined;
+ private durationSeconds: number | undefined;
- constructor(writer?: { write(data: Uint8Array): Promise<void> }) {
+ constructor(
+ writer?: { write(data: Uint8Array): Promise<void> },
+ options?: StreamingTransmuxerOptions
+ ) {
this.writer = writer;
+ this.durationSeconds = options?.durationSeconds;
this.transmuxer = new muxjs.mp4.Transmuxer({ keepOriginalTimestamps: true });
this.transmuxer.on('data', (segment: any) => {
+ const media = new Uint8Array(segment.data);
const data: Uint8Array = this.initWritten
- ? new Uint8Array(segment.data)
- : concatInitAndData(segment);
+ ? media
+ : concat(
+ this.durationSeconds
+ ? patchInitSegmentDuration(new Uint8Array(segment.initSegment), this.durationSeconds)
+ : new Uint8Array(segment.initSegment),
+ media
+ );
this.initWritten = true;
this.segmentCount += 1;
// 写入串行化:写失败暂存,下一次 pushAndTransmux 时抛出
@@ -69,26 +159,22 @@ export class StreamingTransmuxer {
}
}
-function concatInitAndData(segment: { initSegment: ArrayBuffer; data: ArrayBuffer }): Uint8Array {
- const init = new Uint8Array(segment.initSegment);
- const data = new Uint8Array(segment.data);
- const out = new Uint8Array(init.length + data.length);
- out.set(init, 0);
- out.set(data, init.length);
+function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
+ const out = new Uint8Array(a.length + b.length);
+ out.set(a, 0);
+ out.set(b, a.length);
return out;
}
/** 批量转封装:push 全部分片后一次 flush,聚合为 MP4 Blob(内存型,适合小体量) */
export function transmuxTSToMP4(tsSegments: Uint8Array[], duration?: number): Blob {
- const transmuxer = new muxjs.mp4.Transmuxer({
- keepOriginalTimestamps: true,
- ...(duration ? { duration } : {}),
- });
+ const transmuxer = new muxjs.mp4.Transmuxer({ keepOriginalTimestamps: true });
const chunks: Uint8Array[] = [];
let initWritten = false;
transmuxer.on('data', (segment: any) => {
if (!initWritten) {
- chunks.push(new Uint8Array(segment.initSegment));
+ const init = new Uint8Array(segment.initSegment);
+ chunks.push(duration ? patchInitSegmentDuration(init, duration) : init);
initWritten = true;
}
chunks.push(new Uint8Array(segment.data));