Files
Shade/packages/shade-media/src/fmp4.ts
Sterister 75dbf530ce 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>
2026-10-18 21:27:50 +02:00

402 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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;
}
}