feat(media): live fragmented MP4 (H.264/HEVC/AV1 + AAC/Opus), shade live video

Fmp4Splitter cuts ftyp+moov into the sticky init and moof+mdat into frames,
reading sync samples from trun/tfhd/trex flags so fragments shorter than a
GOP still mark where late joiners may start. Codec strings come from the
sample entries. MediaSplitter sniffs WebM vs fMP4; the CLI's new
`live video` uses it (`live webm` stays as the pinned form).

Verified: 9 new tests on real ffmpeg output; H.264/AAC live in headless
Chromium (49/49 fragments appended, late join, 3.2 s latency) and a sealed
H.264 film seeking to 24 s.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:27:50 +02:00
parent c5b897b924
commit 75dbf530ce
12 changed files with 710 additions and 26 deletions

View File

@@ -0,0 +1,160 @@
import { describe, test, expect } from 'bun:test';
import { Fmp4Splitter } from '../src/fmp4.js';
import type { Fmp4Piece } from '../src/fmp4.js';
import { MediaSplitter, sniffContainer } from '../src/splitter.js';
import { MediaFormatError } from '../src/errors.js';
const hasFfmpeg = Bun.which('ffmpeg') !== null;
const FRAG = ['-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov+default_base_moof'];
async function ffmpeg(args: string[], format = FRAG): Promise<Uint8Array> {
const p = Bun.spawn(['ffmpeg', '-hide_banner', '-loglevel', 'error', ...args, ...format, 'pipe:1'], {
stdout: 'pipe',
stderr: 'inherit',
});
const out = new Uint8Array(await new Response(p.stdout).arrayBuffer());
await p.exited;
return out;
}
function split(bytes: Uint8Array, chunk: number): Fmp4Piece[] {
const s = new Fmp4Splitter();
const out: Fmp4Piece[] = [];
for (let i = 0; i < bytes.length; i += chunk) out.push(...s.push(bytes.subarray(i, i + chunk)));
out.push(...s.finish());
return out;
}
/** Top-level box types of a piece, in order. */
function boxes(b: Uint8Array): string[] {
const out: string[] = [];
const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
for (let at = 0; at < b.length; at += dv.getUint32(at)) out.push(String.fromCharCode(...b.subarray(at + 4, at + 8)));
return out;
}
/** The stream without the mfra index ffmpeg appends at the end. */
function withoutMfra(b: Uint8Array): Uint8Array {
const types = boxes(b);
if (types[types.length - 1] !== 'mfra') return b;
const size = new DataView(b.buffer, b.byteOffset).getUint32(b.length - 4); // mfro: size of the mfra
return b.subarray(0, b.length - size);
}
const VIDEO = ['-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=30,format=yuv420p'];
const AUDIO = ['-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000'];
describe.skipIf(!hasFfmpeg)('fMP4 splitter on real ffmpeg output', () => {
test('H.264 + AAC: init, then fragments; keyframes found inside a GOP', async () => {
// 200 ms fragments, a keyframe a second: four of every five fragments
// start mid-GOP, so the flag has to come from the sample flags.
const mp4 = await ffmpeg([
...VIDEO, ...AUDIO, '-t', '4',
'-c:v', 'libx264', '-profile:v', 'high', '-level', '3.1', '-preset', 'veryfast',
'-g', '30', '-keyint_min', '30', '-sc_threshold', '0',
'-c:a', 'aac', '-b:a', '96k', '-frag_duration', '200000',
]);
for (const chunk of [1, 999, 65536, mp4.length]) {
const pieces = split(mp4, chunk);
const init = pieces[0]!;
expect(init.type).toBe('init');
expect((init as { mime: string }).mime).toBe('video/mp4; codecs="avc1.64001f,mp4a.40.2"');
expect(boxes(init.bytes)).toEqual(['ftyp', 'moov']);
const frags = pieces.slice(1);
expect(frags.every((p) => p.type === 'fragment')).toBe(true);
for (const f of frags) expect(boxes(f.bytes).slice(-2)).toEqual(['moof', 'mdat']);
const keys = frags.filter((p) => p.type === 'fragment' && p.keyframe).length;
expect(frags.length).toBeGreaterThan(12);
expect(keys).toBe(4);
expect(frags[0]!.type === 'fragment' && frags[0]!.keyframe).toBe(true);
// Nothing reordered, nothing lost — but the trailing mfra index.
expect(Buffer.concat(pieces.map((p) => p.bytes)).equals(Buffer.from(withoutMfra(mp4)))).toBe(true);
}
}, 30_000);
test('codec strings: HEVC, AV1, VP9, Opus, audio-only AAC', async () => {
const mime = async (args: string[]) => {
const p = split(await ffmpeg(args), 4096);
return (p[0] as { mime: string }).mime;
};
const short = ['-t', '1'];
expect(await mime([...VIDEO, ...short, '-c:v', 'libx265', '-preset', 'ultrafast', '-tag:v', 'hvc1', '-x265-params', 'log-level=none'])).toMatch(
/^video\/mp4; codecs="hvc1\.1\.6\.L\d+\.[0-9A-F]+"$/,
);
expect(await mime([...VIDEO, ...short, '-c:v', 'libsvtav1', '-preset', '12'])).toMatch(/^video\/mp4; codecs="av01\.0\.\d\dM\.08"$/);
expect(await mime([...VIDEO, ...short, '-c:v', 'libvpx-vp9', '-deadline', 'realtime', '-cpu-used', '8'])).toMatch(
/^video\/mp4; codecs="vp09\.00\.\d\d\.08"$/,
);
expect(await mime([...AUDIO, ...short, '-c:a', 'libopus'])).toBe('audio/mp4; codecs="opus"');
expect(await mime([...AUDIO, ...short, '-c:a', 'aac'])).toBe('audio/mp4; codecs="mp4a.40.2"');
}, 60_000);
test('audio-only: every fragment is a starting point', async () => {
const pieces = split(await ffmpeg([...AUDIO, '-t', '2', '-c:a', 'aac', '-frag_duration', '250000']), 1000);
expect(pieces.length).toBeGreaterThan(4);
expect(pieces.slice(1).every((p) => p.type === 'fragment' && p.keyframe)).toBe(true);
}, 30_000);
test('CMAF-style styp before each moof stays with its fragment', async () => {
const mp4 = await ffmpeg([...VIDEO, '-t', '2', '-c:v', 'libx264', '-preset', 'ultrafast', '-g', '15'], [
'-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov+default_base_moof+cmaf', '-write_prft', 'wallclock',
]);
const pieces = split(mp4, 3000);
expect(boxes(pieces[0]!.bytes)).toEqual(['ftyp', 'moov']);
for (const f of pieces.slice(1)) {
const b = boxes(f.bytes);
expect(b.slice(-2)).toEqual(['moof', 'mdat']);
expect(f.type === 'fragment' && f.keyframe).toBe(true);
}
expect(Buffer.concat(pieces.map((p) => p.bytes)).equals(Buffer.from(withoutMfra(mp4)))).toBe(true);
}, 30_000);
test('MediaSplitter sniffs WebM and fMP4 and gives the same pieces', async () => {
const mp4 = await ffmpeg([...VIDEO, '-t', '2', '-c:v', 'libx264', '-preset', 'ultrafast', '-g', '30']);
const webm = await ffmpeg([...VIDEO, '-t', '2', '-c:v', 'libvpx', '-deadline', 'realtime', '-g', '30'], ['-f', 'webm', '-live', '1']);
for (const [bytes, kind, mime] of [
[mp4, 'fmp4', 'video/mp4; codecs="avc1.'],
[webm, 'webm', 'video/webm; codecs="vp8"'],
] as const) {
const s = new MediaSplitter();
const out = [];
for (let i = 0; i < bytes.length; i += 3) out.push(...s.push(bytes.subarray(i, i + 3)));
out.push(...s.finish());
expect(s.container).toBe(kind);
expect(out[0]!.type).toBe('init');
expect((out[0] as { mime: string }).mime.startsWith(mime)).toBe(true);
expect(out.slice(1).every((p) => p.type === 'media')).toBe(true);
expect(out[1]!.type === 'media' && out[1]!.keyframe).toBe(true);
}
}, 30_000);
});
describe('fMP4 splitter: refusals', () => {
const box = (type: string, body: Uint8Array = new Uint8Array(0)) => {
const b = new Uint8Array(8 + body.length);
new DataView(b.buffer).setUint32(0, b.length);
b.set(new TextEncoder().encode(type), 4);
b.set(body, 8);
return b;
};
test('a progressive MP4 (mdat before moov) is refused with a hint', () => {
expect(() => new Fmp4Splitter().push(Buffer.concat([box('ftyp'), box('mdat', new Uint8Array(16))]))).toThrow(/frag_keyframe/);
});
test('a fragment without a moov is refused', () => {
expect(() => new Fmp4Splitter().push(Buffer.concat([box('ftyp'), box('moof')]))).toThrow(MediaFormatError);
});
test('garbage is neither WebM nor fMP4', () => {
expect(() => sniffContainer(new TextEncoder().encode('hello, world'))).toThrow(MediaFormatError);
expect(sniffContainer(new Uint8Array(4))).toBeNull();
});
test('a half-written last fragment is not emitted', () => {
const s = new Fmp4Splitter();
// No moov yet: nothing to emit, nothing thrown while bytes are missing.
expect(s.push(box('ftyp').subarray(0, 5))).toEqual([]);
expect(s.finish()).toEqual([]);
});
});