// Fragmented MP4, as HLS plays it (RFC 8216 ยง3.3) and Media Source Extensions append it (W3C's ISO BMFF byte stream // format): an init segment (`ftyp`, `moov` with each track's sample description and `mvex`), then media segments, each // one `moof` (a `traf` per track: its decode time and its samples' durations, sizes, flags and composition offsets) and // one `mdat`. Video is track 1 at 90 kHz with the publisher's avcC as is; audio is track 2 at its sample rate with its // AudioSpecificConfig in an `esds`. Boxes per ISO/IEC 14496-12 and -14 and -15. import type { AacConfig, AvcConfig } from './flv.ts'; export const VIDEO_TRACK = 1; export const AUDIO_TRACK = 2; export const VIDEO_TIMESCALE = 90_000; const ascii = (s: string): number[] => Array.from(s, (c) => c.charCodeAt(0)); const u16 = (n: number): number[] => [(n >> 8) & 0xff, n & 0xff]; const u32 = (n: number): number[] => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]; const u64 = (n: number): number[] => [...u32(Math.floor(n / 2 ** 32)), ...u32(n % 2 ** 32)]; const zeros = (n: number): number[] => new Array(n).fill(0); type Part = number[] | Uint8Array; function box(type: string, ...parts: Part[]): Uint8Array { const size = 8 + parts.reduce((n, p) => n + p.length, 0); const out = new Uint8Array(size); out.set(u32(size), 0); out.set(ascii(type), 4); let at = 8; for (const p of parts) { out.set(p, at); at += p.length; } return out; } const full = (type: string, version: number, flags: number, ...parts: Part[]): Uint8Array => box(type, [version, (flags >> 16) & 0xff, (flags >> 8) & 0xff, flags & 0xff], ...parts); const MATRIX = [...u32(0x00010000), ...u32(0), ...u32(0), ...u32(0), ...u32(0x00010000), ...u32(0), ...u32(0), ...u32(0), ...u32(0x40000000)]; function descriptor(tag: number, ...parts: Part[]): number[] { const body = parts.flatMap((p) => Array.from(p)); // the size as four bytes of seven bits, as MP4 writers write it const n = body.length; return [tag, 0x80 | ((n >> 21) & 0x7f), 0x80 | ((n >> 14) & 0x7f), 0x80 | ((n >> 7) & 0x7f), n & 0x7f, ...body]; } function trak(id: number, kind: 'video' | 'audio', timescale: number, width: number, height: number, entry: Uint8Array): Uint8Array { const tkhd = full('tkhd', 0, 3, u32(0), u32(0), u32(id), u32(0), u32(0), zeros(8), u16(0), u16(0), u16(kind === 'audio' ? 0x0100 : 0), u16(0), MATRIX, u32(width * 65536), u32(height * 65536)); const mdhd = full('mdhd', 0, 0, u32(0), u32(0), u32(timescale), u32(0), u16(0x55c4), u16(0)); const hdlr = full('hdlr', 0, 0, u32(0), ascii(kind === 'video' ? 'vide' : 'soun'), zeros(12), [...ascii(kind === 'video' ? 'VideoHandler' : 'SoundHandler'), 0]); const header = kind === 'video' ? full('vmhd', 0, 1, u16(0), zeros(6)) : full('smhd', 0, 0, u16(0), u16(0)); const dinf = box('dinf', full('dref', 0, 0, u32(1), full('url ', 0, 1))); const stbl = box('stbl', full('stsd', 0, 0, u32(1), entry), full('stts', 0, 0, u32(0)), full('stsc', 0, 0, u32(0)), full('stsz', 0, 0, u32(0), u32(0)), full('stco', 0, 0, u32(0))); return box('trak', tkhd, box('mdia', mdhd, hdlr, box('minf', header, dinf, stbl))); } /** The init segment for the tracks a publish carries. */ export function initSegment(tracks: { video?: AvcConfig & { width: number; height: number }; audio?: AacConfig }): Uint8Array { const traks: Uint8Array[] = []; const trex: Uint8Array[] = []; const brands = ['isom', 'iso6', ...(tracks.video ? ['avc1'] : []), 'mp41']; if (tracks.video) { const v = tracks.video; const avc1 = box('avc1', zeros(6), u16(1), u16(0), u16(0), zeros(12), u16(v.width), u16(v.height), u32(0x00480000), u32(0x00480000), u32(0), u16(1), zeros(32), u16(0x0018), u16(0xffff), box('avcC', v.record)); traks.push(trak(VIDEO_TRACK, 'video', VIDEO_TIMESCALE, v.width, v.height, avc1)); trex.push(full('trex', 0, 0, u32(VIDEO_TRACK), u32(1), u32(0), u32(0), u32(0))); } if (tracks.audio) { const a = tracks.audio; const esds = full('esds', 0, 0, descriptor(3, u16(0), [0], descriptor(4, [0x40, 0x15], zeros(3), u32(0), u32(0), descriptor(5, a.asc)), descriptor(6, [0x02]))); const mp4a = box('mp4a', zeros(6), u16(1), zeros(8), u16(Math.max(1, a.channels)), u16(16), u16(0), u16(0), u32((a.sampleRate > 0xffff ? 0 : a.sampleRate) * 65536), esds); traks.push(trak(AUDIO_TRACK, 'audio', a.sampleRate, 0, 0, mp4a)); trex.push(full('trex', 0, 0, u32(AUDIO_TRACK), u32(1), u32(0), u32(0), u32(0))); } const mvhd = full('mvhd', 0, 0, u32(0), u32(0), u32(1000), u32(0), u32(0x00010000), u16(0x0100), u16(0), zeros(8), MATRIX, zeros(24), u32(3)); const ftyp = box('ftyp', ascii('isom'), u32(0x200), ...brands.map(ascii)); const moov = box('moov', mvhd, ...traks, box('mvex', ...trex)); const out = new Uint8Array(ftyp.length + moov.length); out.set(ftyp, 0); out.set(moov, ftyp.length); return out; } export type Sample = { duration: number; data: Uint8Array; key: boolean; cts?: number }; export type Fragment = { track: number; baseTime: number; samples: Sample[] }; /** A media segment: one `moof` over the fragments, then their samples in one `mdat`, video's first. */ export function mediaSegment(sequence: number, fragments: Fragment[]): Uint8Array { const present = fragments.filter((f) => f.samples.length > 0); const moofOf = (offsets: number[]): Uint8Array => box('moof', full('mfhd', 0, 0, u32(sequence)), ...present.map((f, i) => { const video = f.track === VIDEO_TRACK; // data offset, duration, size, flags and (video) composition offset per sample; version 1 for signed offsets const flags = video ? 0x000f01 : 0x000301; const rows = f.samples.flatMap((s) => [ ...u32(s.duration), ...u32(s.data.length), ...(video ? [...u32(s.key ? 0x02000000 : 0x01010000), ...u32((s.cts ?? 0) | 0)] : []), ]); return box('traf', full('tfhd', 0, 0x020000, u32(f.track)), full('tfdt', 1, 0, u64(f.baseTime)), full('trun', video ? 1 : 0, flags, u32(f.samples.length), u32(offsets[i]! | 0), rows)); })); const sized = moofOf(present.map(() => 0)).length; const offsets: number[] = []; let at = sized + 8; for (const f of present) { offsets.push(at); at += f.samples.reduce((n, s) => n + s.data.length, 0); } const moof = moofOf(offsets); // one buffer for the whole segment, the samples written straight into its mdat: a segment's bytes are copied once const out = new Uint8Array(at); out.set(moof, 0); out.set([...u32(at - moof.length), ...ascii('mdat')], moof.length); let to = moof.length + 8; for (const f of present) for (const s of f.samples) { out.set(s.data, to); to += s.data.length; } return out; }