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 { 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([]); }); });