/** * 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[number] | ReturnType[number]): MediaPiece { return p.type === 'init' ? p : { type: 'media', keyframe: p.keyframe, bytes: p.bytes }; }