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

@@ -6,7 +6,7 @@
* shade media get <link> -o out.mkv download and decrypt
* shade media ls|rm --server URL
* tail -f app.log | shade live text --server URL --name "app logs"
* ffmpeg … -f webm - | shade live webm --server URL --name "Camera"
* ffmpeg … -f webm - | shade live video --server URL --name "Camera" (or fragmented MP4)
* shade live watch <link> a live text channel in the terminal
*
* The owner key (who may upload and delete) is created on first use under
@@ -26,7 +26,8 @@ import { LivePublishClient, LiveWatchClient } from './live/client.js';
import { sealFile } from './node.js';
import { OwnerKey } from './owner.js';
import type { MediaMeta } from './sealed.js';
import { WebmSplitter } from './webm.js';
import { MediaSplitter } from './splitter.js';
import type { LiveContainer } from './splitter.js';
type Flags = Record<string, string | true>;
@@ -297,25 +298,46 @@ async function liveText(flags: Flags): Promise<number> {
return 0;
}
async function liveWebm(flags: Flags): Promise<number> {
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? 'video/webm' };
/**
* A live WebM or fragmented-MP4 stream from stdin. `--format webm|fmp4` pins
* the container (the `webm` subcommand pins WebM); otherwise the first bytes
* decide.
*/
async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise<number> {
const format = pinned ?? str(flags, 'format');
if (format !== undefined && format !== 'webm' && format !== 'fmp4') throw new UsageError('--format must be webm or fmp4');
const splitter = new MediaSplitter(format);
const stdin = Bun.stdin.stream().getReader();
// Read until the container is known, so the meta can carry the right type.
let first: ReturnType<MediaSplitter['push']> = [];
while (splitter.container === null) {
const { value, done } = await stdin.read();
if (done) throw new UsageError('no input on stdin');
first = first.concat(splitter.push(value));
}
const fallbackMime = splitter.container === 'webm' ? 'video/webm' : 'video/mp4';
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? fallbackMime };
const { client } = await startPublishing(flags, meta);
const splitter = new WebmSplitter();
let clusters = 0;
const send = async (pieces: ReturnType<WebmSplitter['push']>) => {
for (const p of pieces) {
let pieces = 0;
const send = async (batch: ReturnType<MediaSplitter['push']>) => {
for (const p of batch) {
if (p.type === 'init') {
await client.send({ type: 'init', mime: p.mime, bytes: p.bytes }, { sticky: true });
err(`stream: ${p.mime}`);
} else {
await client.send({ type: 'chunk', bytes: p.bytes }, { keyframe: p.keyframe });
clusters++;
pieces++;
}
}
};
for await (const chunk of Bun.stdin.stream()) await send(splitter.push(chunk));
await send(first);
for (;;) {
const { value, done } = await stdin.read();
if (done) break;
await send(splitter.push(value));
}
await send(splitter.finish());
err(`${clusters} clusters sent`);
err(`${pieces} ${splitter.container === 'webm' ? 'clusters' : 'fragments'} sent`);
await client.end();
return 0;
}
@@ -357,8 +379,12 @@ export const MEDIA_HELP = `
media rm <link|id> --server URL
live text --server URL [--name N] [--channel file.json]
Publish stdin as a live log (tail -f app.log | shade live text …)
live webm --server URL [--name N] [--channel file.json]
Publish a WebM stream from stdin (ffmpeg … -f webm - | …)
live video --server URL [--name N] [--channel file.json] [--format webm|fmp4]
Publish a live WebM or fragmented MP4 from stdin:
ffmpeg … -f webm - | …
ffmpeg … -c:v libx264 -c:a aac -f mp4 \\
-movflags frag_keyframe+empty_moov+default_base_moof - | …
live webm … The same, pinned to WebM
live watch <link> Follow a live text channel in the terminal
`;
@@ -387,8 +413,10 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[]): Prom
switch (sub) {
case 'text':
return await liveText(flags);
case 'video':
return await liveVideo(flags);
case 'webm':
return await liveWebm(flags);
return await liveVideo(flags, 'webm');
case 'watch':
return await liveWatch(pos);
}

View File

@@ -0,0 +1,401 @@
/**
* Fragmented MP4 → live frames.
*
* A live fMP4 stream (ffmpeg `-movflags frag_keyframe+empty_moov+default_base_moof`,
* OBS, hardware encoders, CMAF) is a run of top-level boxes:
*
* ftyp moov → init, one sticky frame
* [styp] [sidx] [prft] [emsg] moof mdat → one fragment, one frame
*
* For Media Source Extensions that is the same split as WebM: the init makes
* the SourceBuffer, every fragment after it is appendable on its own. A
* fragment is a keyframe when the first sample of its video track is a sync
* sample, which is what a late joiner needs to start on.
*
* Streaming parser: push bytes in any chunking, get whole pieces out.
*/
import { concat } from './bytes.js';
import { MediaFormatError } from './errors.js';
export type Fmp4Piece =
| { type: 'init'; mime: string; bytes: Uint8Array }
| { type: 'fragment'; keyframe: boolean; bytes: Uint8Array };
/** Boxes that may come before a `moof` and belong to its fragment. */
const FRAGMENT_PREFIX = new Set(['styp', 'sidx', 'prft', 'emsg', 'free', 'skip']);
/** Index boxes a muxer writes at the end; a live viewer has no use for them. */
const TRAILING_INDEX = new Set(['mfra']);
/** Boxes that end the init. */
const FRAGMENT_START = new Set(['moof', ...FRAGMENT_PREFIX]);
/** Largest box accepted: a fragment of an 8K keyframe is tens of MiB, not GiBs. */
const MAX_BOX = 256 * 1024 * 1024;
interface Box {
type: string;
/** Offset of the box's payload (after size, type and any largesize). */
body: number;
/** Offset one past the box. */
end: number;
}
function fourcc(b: Uint8Array, at: number): string {
return String.fromCharCode(b[at]!, b[at + 1]!, b[at + 2]!, b[at + 3]!);
}
function u32(b: Uint8Array, at: number): number {
return ((b[at]! << 24) | (b[at + 1]! << 16) | (b[at + 2]! << 8) | b[at + 3]!) >>> 0;
}
/**
* The box header at `at`, or null if more bytes are needed. `limit` is where
* the enclosing container ends; a box running past it is malformed.
*/
function readBox(b: Uint8Array, at: number, limit: number): Box | null {
if (at + 8 > limit) return null;
let size = u32(b, at);
const type = fourcc(b, at + 4);
let body = at + 8;
if (size === 1) {
if (at + 16 > limit) return null;
const hi = u32(b, at + 8);
const lo = u32(b, at + 12);
if (hi > 0x1f_ffff) throw new MediaFormatError(`fMP4: ${type} box too large`);
size = hi * 2 ** 32 + lo;
body = at + 16;
} else if (size === 0) {
// "Extends to the end of the file": meaningless in a live stream.
throw new MediaFormatError(`fMP4: ${type} box of open size in a live stream`);
}
if (size < body - at) throw new MediaFormatError(`fMP4: ${type} box smaller than its header`);
if (size > MAX_BOX) throw new MediaFormatError(`fMP4: ${type} box of ${size} bytes`);
return { type, body, end: at + size };
}
/** The child boxes of a container, fully present in `b[from, to)`. */
function children(b: Uint8Array, from: number, to: number): Box[] {
const out: Box[] = [];
let at = from;
while (at + 8 <= to) {
const box = readBox(b, at, to);
if (box === null || box.end > to) throw new MediaFormatError('fMP4: truncated box');
out.push(box);
at = box.end;
}
return out;
}
function child(b: Uint8Array, parent: Box, type: string): Box | undefined {
return children(b, parent.body, parent.end).find((c) => c.type === type);
}
function hex(n: number, width = 2): string {
return n.toString(16).padStart(width, '0');
}
// ─── Codec strings (RFC 6381 and the codec-specific registrations) ───
/** `avc1.PPCCLL` from an avcC box. */
function avcCodec(entry: string, b: Uint8Array, avcC: Box): string {
return `${entry}.${hex(b[avcC.body + 1]!)}${hex(b[avcC.body + 2]!)}${hex(b[avcC.body + 3]!)}`;
}
/** `hvc1.P.C.TL.B…` from an hvcC box (ISO/IEC 14496-15 Annex E). */
function hevcCodec(entry: string, b: Uint8Array, hvcC: Box): string {
const p = hvcC.body;
const space = b[p + 1]! >> 6;
const tier = (b[p + 1]! >> 5) & 1;
const profile = b[p + 1]! & 0x1f;
// general_profile_compatibility_flags, bit-reversed.
let compat = u32(b, p + 2);
let rev = 0;
for (let i = 0; i < 32; i++) {
rev = (rev << 1) | (compat & 1);
compat >>>= 1;
}
const level = b[p + 12]!;
const constraints: string[] = [];
for (let i = 0; i < 6; i++) constraints.push(hex(b[p + 6 + i]!).toUpperCase());
while (constraints.length > 0 && constraints[constraints.length - 1] === '00') constraints.pop();
const spaceTag = ['', 'A', 'B', 'C'][space]!;
return [
entry,
`${spaceTag}${profile}`,
(rev >>> 0).toString(16).toUpperCase(),
`${tier ? 'H' : 'L'}${level}`,
...constraints,
].join('.');
}
/** `av01.P.LLT.DD` from an av1C box (AV1 ISOBMFF binding §5). */
function av1Codec(b: Uint8Array, av1C: Box): string {
const p = av1C.body;
const profile = b[p + 1]! >> 5;
const level = b[p + 1]! & 0x1f;
const tier = b[p + 2]! >> 7;
const high = (b[p + 2]! >> 6) & 1;
const twelve = (b[p + 2]! >> 5) & 1;
const depth = high ? (twelve ? 12 : 10) : 8;
return `av01.${profile}.${String(level).padStart(2, '0')}${tier ? 'H' : 'M'}.${String(depth).padStart(2, '0')}`;
}
/** `vp09.PP.LL.DD` from a vpcC box (VP Codec ISOBMFF binding). */
function vp9Codec(b: Uint8Array, vpcC: Box): string {
const p = vpcC.body + 4; // FullBox
const d2 = (n: number) => String(n).padStart(2, '0');
return `vp09.${d2(b[p]!)}.${d2(b[p + 1]!)}.${d2(b[p + 2]! >> 4)}`;
}
/** An MPEG-4 descriptor's tag and body, with its 1–4 byte length. */
function descriptor(b: Uint8Array, at: number, end: number): { tag: number; body: number; end: number } | null {
if (at >= end) return null;
const tag = b[at]!;
let len = 0;
let p = at + 1;
for (let i = 0; i < 4 && p < end; i++) {
const x = b[p++]!;
len = (len << 7) | (x & 0x7f);
if ((x & 0x80) === 0) break;
}
return { tag, body: p, end: Math.min(end, p + len) };
}
/** `mp4a.OO.A` from an esds box: objectTypeIndication and the audio object type. */
function aacCodec(b: Uint8Array, esds: Box): string {
const es = descriptor(b, esds.body + 4, esds.end);
if (es === null || es.tag !== 0x03) return 'mp4a.40.2';
let p = es.body + 2; // ES_ID
const flags = b[p++]!;
if (flags & 0x80) p += 2; // dependsOn_ES_ID
if (flags & 0x40) p += 1 + b[p]!; // URL
if (flags & 0x20) p += 2; // OCR_ES_ID
const dc = descriptor(b, p, es.end);
if (dc === null || dc.tag !== 0x04) return 'mp4a.40.2';
const oti = b[dc.body]!;
const dsi = descriptor(b, dc.body + 13, dc.end);
if (oti !== 0x40 || dsi === null || dsi.tag !== 0x05) return `mp4a.${hex(oti)}`;
let aot = b[dsi.body]! >> 3;
if (aot === 31) aot = 32 + (((b[dsi.body]! & 0x07) << 3) | (b[dsi.body + 1]! >> 5));
return `mp4a.40.${aot}`;
}
/** Size of a sample entry's fixed fields, before its child boxes. */
const VISUAL_ENTRY = 78;
const AUDIO_ENTRY = 28;
function sampleEntryCodec(b: Uint8Array, entry: Box): string | null {
const kind = entry.type;
const visual = ['avc1', 'avc3', 'hvc1', 'hev1', 'av01', 'vp09', 'encv'].includes(kind);
const audio = ['mp4a', 'Opus', 'fLaC', 'ac-3', 'ec-3', 'enca'].includes(kind);
if (!visual && !audio) return null;
const sub = children(b, entry.body + (visual ? VISUAL_ENTRY : AUDIO_ENTRY), entry.end);
const find = (t: string) => sub.find((c) => c.type === t);
switch (kind) {
case 'avc1':
case 'avc3': {
const c = find('avcC');
return c ? avcCodec(kind, b, c) : kind;
}
case 'hvc1':
case 'hev1': {
const c = find('hvcC');
return c ? hevcCodec(kind, b, c) : kind;
}
case 'av01': {
const c = find('av1C');
return c ? av1Codec(b, c) : 'av01';
}
case 'vp09': {
const c = find('vpcC');
return c ? vp9Codec(b, c) : 'vp09';
}
case 'mp4a': {
const c = find('esds');
return c ? aacCodec(b, c) : 'mp4a.40.2';
}
case 'Opus':
return 'opus';
case 'fLaC':
return 'flac';
case 'ac-3':
return 'ac-3';
case 'ec-3':
return 'ec-3';
default:
// encv / enca: CENC-encrypted tracks — Shade already encrypts; refuse
// rather than guess the original format from sinf.
throw new MediaFormatError(`fMP4: ${kind} (CENC-encrypted) tracks are not supported`);
}
}
interface Track {
id: number;
handler: string;
codec: string | null;
/** trex default_sample_flags, the fallback for fragments that state none. */
defaultFlags: number;
}
function parseMoov(b: Uint8Array, moov: Box): Track[] {
const tracks: Track[] = [];
const top = children(b, moov.body, moov.end);
for (const trak of top.filter((c) => c.type === 'trak')) {
const tkhd = child(b, trak, 'tkhd');
const mdia = child(b, trak, 'mdia');
if (!tkhd || !mdia) continue;
const version = b[tkhd.body]!;
const id = u32(b, tkhd.body + 4 + (version === 1 ? 16 : 8));
const hdlr = child(b, mdia, 'hdlr');
const handler = hdlr ? fourcc(b, hdlr.body + 8) : '';
const minf = child(b, mdia, 'minf');
const stbl = minf && child(b, minf, 'stbl');
const stsd = stbl && child(b, stbl, 'stsd');
let codec: string | null = null;
if (stsd) {
const entries = children(b, stsd.body + 8, stsd.end);
if (entries[0]) codec = sampleEntryCodec(b, entries[0]);
}
tracks.push({ id, handler, codec, defaultFlags: 0 });
}
const mvex = top.find((c) => c.type === 'mvex');
if (mvex) {
for (const trex of children(b, mvex.body, mvex.end).filter((c) => c.type === 'trex')) {
const t = tracks.find((x) => x.id === u32(b, trex.body + 4));
if (t) t.defaultFlags = u32(b, trex.body + 20);
}
}
return tracks;
}
/** The MSE type string, e.g. `video/mp4; codecs="avc1.64001f,mp4a.40.2"`. */
export function fmp4Mime(tracks: readonly { handler: string; codec: string | null }[]): string {
const media = tracks.filter((t) => t.handler === 'vide' || t.handler === 'soun');
const codecs = media.map((t) => t.codec).filter((c): c is string => c !== null);
const video = media.some((t) => t.handler === 'vide');
return `${video ? 'video' : 'audio'}/mp4${codecs.length > 0 ? `; codecs="${codecs.join(',')}"` : ''}`;
}
/** sample_is_non_sync_sample, ISO/IEC 14496-12 §8.8.3.1. */
const NON_SYNC = 0x0001_0000;
export class Fmp4Splitter {
private buf: Uint8Array = new Uint8Array(0);
private initDone = false;
private tracks: Track[] = [];
private videoTracks = new Set<number>();
push(chunk: Uint8Array): Fmp4Piece[] {
this.buf = this.buf.length === 0 ? chunk.slice() : concat([this.buf, chunk]);
const out: Fmp4Piece[] = [];
if (!this.initDone) {
const init = this.tryInit();
if (init === null) return out;
out.push(init);
}
for (;;) {
const f = this.tryFragment();
if (f === null) break;
out.push(f);
}
return out;
}
/** End of stream. A half-written last fragment is dropped, not sent. */
finish(): Fmp4Piece[] {
this.buf = new Uint8Array(0);
return [];
}
private tryInit(): Fmp4Piece | null {
let at = 0;
let moov: Box | null = null;
let first = true;
for (;;) {
const box = readBox(this.buf, at, this.buf.length);
if (box === null) return null;
if (first && box.type !== 'ftyp' && box.type !== 'moov') {
throw new MediaFormatError(`not a fragmented MP4 stream (starts with ${JSON.stringify(box.type)})`);
}
first = false;
if (box.type === 'moof' && moov === null) throw new MediaFormatError('fMP4: no moov before the first fragment');
// free/skip before the moov are padding in the init, after it a fragment's prefix.
if (moov !== null && FRAGMENT_START.has(box.type)) break;
if (box.type === 'mdat') throw new MediaFormatError('fMP4: mdat before moof — not a fragmented MP4 (use -movflags frag_keyframe+empty_moov)');
if (box.end > this.buf.length) return null;
if (box.type === 'moov') moov = box;
at = box.end;
}
this.tracks = parseMoov(this.buf, moov!);
if (!this.tracks.some((t) => t.codec !== null)) throw new MediaFormatError('fMP4: no audio or video track');
for (const t of this.tracks) if (t.handler === 'vide') this.videoTracks.add(t.id);
this.initDone = true;
const bytes = this.buf.slice(0, at);
this.buf = this.buf.slice(at);
return { type: 'init', mime: fmp4Mime(this.tracks), bytes };
}
/** `[prefix boxes] moof … mdat` once the mdat is complete. */
private tryFragment(): Fmp4Piece | null {
let at = 0;
let moof: Box | null = null;
for (;;) {
const box = readBox(this.buf, at, this.buf.length);
if (box === null) return null;
if (moof === null && at === 0 && TRAILING_INDEX.has(box.type)) {
if (box.end > this.buf.length) return null;
this.buf = this.buf.slice(box.end);
continue;
}
if (moof === null) {
if (box.type !== 'moof' && !FRAGMENT_PREFIX.has(box.type)) {
throw new MediaFormatError(`fMP4: unexpected ${JSON.stringify(box.type)} box between fragments`);
}
} else if (box.type !== 'mdat') {
throw new MediaFormatError(`fMP4: ${JSON.stringify(box.type)} between moof and mdat`);
}
if (box.end > this.buf.length) return null;
if (box.type === 'moof') moof = box;
at = box.end;
if (box.type === 'mdat') break;
}
const bytes = this.buf.slice(0, at);
this.buf = this.buf.slice(at);
return { type: 'fragment', keyframe: this.isKeyframe(bytes, moof!), bytes };
}
/** Is the first sample of the video track in this fragment a sync sample? */
private isKeyframe(b: Uint8Array, moof: Box): boolean {
if (this.videoTracks.size === 0) return true; // audio only: every fragment is a start
for (const traf of children(b, moof.body, moof.end).filter((c) => c.type === 'traf')) {
const tfhd = child(b, traf, 'tfhd');
if (!tfhd) continue;
const tfFlags = u32(b, tfhd.body) & 0xffffff;
const trackId = u32(b, tfhd.body + 4);
if (!this.videoTracks.has(trackId)) continue;
let defaultFlags = this.tracks.find((t) => t.id === trackId)?.defaultFlags ?? 0;
let p = tfhd.body + 8;
if (tfFlags & 0x01) p += 8; // base_data_offset
if (tfFlags & 0x02) p += 4; // sample_description_index
if (tfFlags & 0x08) p += 4; // default_sample_duration
if (tfFlags & 0x10) p += 4; // default_sample_size
if (tfFlags & 0x20) defaultFlags = u32(b, p);
const trun = child(b, traf, 'trun');
if (!trun) continue;
const trFlags = u32(b, trun.body) & 0xffffff;
const count = u32(b, trun.body + 4);
if (count === 0) continue;
let q = trun.body + 8;
if (trFlags & 0x001) q += 4; // data_offset
if (trFlags & 0x004) return (u32(b, q) & NON_SYNC) === 0; // first_sample_flags
if (trFlags & 0x400) {
// Per-sample flags: skip the first sample's duration and size.
if (trFlags & 0x100) q += 4;
if (trFlags & 0x200) q += 4;
return (u32(b, q) & NON_SYNC) === 0;
}
return (defaultFlags & NON_SYNC) === 0;
}
return false;
}
}

View File

@@ -28,3 +28,9 @@ export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME,
export type { LiveContent, FrameHeader } from './live/frame.js';
export { LivePublishClient, LiveWatchClient, liveUrl } from './live/client.js';
export type { LiveState, PublishOptions, WatchOptions } from './live/client.js';
export { MediaSplitter, sniffContainer } from './splitter.js';
export type { MediaPiece, LiveContainer } from './splitter.js';
export { WebmSplitter, webmMime } from './webm.js';
export type { WebmPiece } from './webm.js';
export { Fmp4Splitter, fmp4Mime } from './fmp4.js';
export type { Fmp4Piece } from './fmp4.js';

View File

@@ -18,6 +18,7 @@ const HTML = `<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
<link rel="icon" href="data:,">
<title>Shade</title>
<style>
:root { color-scheme: dark; --bg: #0d0f12; --panel: #15181d; --line: #262b33; --text: #e7e9ec; --dim: #8b929c; --ok: #6fcf97; --warn: #f2c94c; --bad: #eb5757; }

View File

@@ -0,0 +1,65 @@
/**
* Live container → live frames, whichever container it is.
*
* `MediaSplitter` sniffs the first bytes — an EBML header is WebM, an
* `ftyp`/`moov`/`styp` box is fragmented MP4 — and hands the rest to the
* matching splitter. Both give the same two pieces: one sticky `init` with
* the MSE type string, then media pieces that a SourceBuffer appends on
* their own, flagged where a late joiner may start.
*/
import { concat } from './bytes.js';
import { MediaFormatError } from './errors.js';
import { Fmp4Splitter } from './fmp4.js';
import { WebmSplitter } from './webm.js';
export type MediaPiece =
| { type: 'init'; mime: string; bytes: Uint8Array }
| { type: 'media'; keyframe: boolean; bytes: Uint8Array };
export type LiveContainer = 'webm' | 'fmp4';
/** The container of a live stream from its first bytes, or null if more are needed. */
export function sniffContainer(head: Uint8Array): LiveContainer | null {
if (head.length < 8) return null;
if (head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) return 'webm';
const box = String.fromCharCode(head[4]!, head[5]!, head[6]!, head[7]!);
if (box === 'ftyp' || box === 'moov' || box === 'styp') return 'fmp4';
throw new MediaFormatError('not a live WebM or fragmented MP4 stream');
}
export class MediaSplitter {
private inner: WebmSplitter | Fmp4Splitter | null = null;
private head: Uint8Array = new Uint8Array(0);
container: LiveContainer | null = null;
/** `container` pins the format; without it the first bytes decide. */
constructor(container?: LiveContainer) {
if (container !== undefined) this.start(container);
}
push(chunk: Uint8Array): MediaPiece[] {
if (this.inner === null) {
this.head = this.head.length === 0 ? chunk.slice() : concat([this.head, chunk]);
const kind = sniffContainer(this.head);
if (kind === null) return [];
this.start(kind);
chunk = this.head;
this.head = new Uint8Array(0);
}
return this.inner!.push(chunk).map(normalise);
}
finish(): MediaPiece[] {
return this.inner === null ? [] : this.inner.finish().map(normalise);
}
private start(kind: LiveContainer): void {
this.container = kind;
this.inner = kind === 'webm' ? new WebmSplitter() : new Fmp4Splitter();
}
}
function normalise(p: ReturnType<WebmSplitter['push']>[number] | ReturnType<Fmp4Splitter['push']>[number]): MediaPiece {
return p.type === 'init' ? p : { type: 'media', keyframe: p.keyframe, bytes: p.bytes };
}

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