377 lines
13 KiB
TypeScript
377 lines
13 KiB
TypeScript
|
|
/**
|
||
|
|
* WebM → live frames.
|
||
|
|
*
|
||
|
|
* A live WebM stream (ffmpeg `-f webm`, the browser's `MediaRecorder`) is an
|
||
|
|
* EBML header and a Segment whose children are Info, Tracks and then an
|
||
|
|
* endless run of Clusters. For Media Source Extensions that splits cleanly:
|
||
|
|
*
|
||
|
|
* init = everything before the first Cluster → one sticky frame
|
||
|
|
* cluster = one Cluster element → one frame, a keyframe
|
||
|
|
* if the video track's first block in it is one
|
||
|
|
*
|
||
|
|
* A viewer who joins late appends the init, then starts at the next keyframe
|
||
|
|
* cluster — exactly the two flags the live format carries.
|
||
|
|
*
|
||
|
|
* Streaming parser: push bytes in any chunking, get whole pieces out. It
|
||
|
|
* handles Segments and Clusters of unknown size (what live muxers write),
|
||
|
|
* ending such a Cluster at the next element that cannot be its child.
|
||
|
|
*/
|
||
|
|
|
||
|
|
import { concat } from './bytes.js';
|
||
|
|
import { MediaFormatError } from './errors.js';
|
||
|
|
|
||
|
|
const ID_EBML = 0x1a45dfa3;
|
||
|
|
const ID_SEGMENT = 0x18538067;
|
||
|
|
const ID_CLUSTER = 0x1f43b675;
|
||
|
|
const ID_TRACKS = 0x1654ae6b;
|
||
|
|
const ID_TRACK_ENTRY = 0xae;
|
||
|
|
const ID_TRACK_NUMBER = 0xd7;
|
||
|
|
const ID_TRACK_TYPE = 0x83;
|
||
|
|
const ID_CODEC_ID = 0x86;
|
||
|
|
const ID_SIMPLE_BLOCK = 0xa3;
|
||
|
|
const ID_BLOCK_GROUP = 0xa0;
|
||
|
|
const ID_BLOCK = 0xa1;
|
||
|
|
const ID_REFERENCE_BLOCK = 0xfb;
|
||
|
|
|
||
|
|
/** Children a Cluster may hold; anything else ends an unknown-size Cluster. */
|
||
|
|
const CLUSTER_CHILDREN = new Set([0xe7, 0xa7, 0xab, ID_SIMPLE_BLOCK, ID_BLOCK_GROUP, 0x5854, 0xaf, 0xec, 0xbf]);
|
||
|
|
|
||
|
|
export type WebmPiece =
|
||
|
|
| { type: 'init'; mime: string; bytes: Uint8Array }
|
||
|
|
| { type: 'cluster'; keyframe: boolean; bytes: Uint8Array };
|
||
|
|
|
||
|
|
interface Vint {
|
||
|
|
value: number;
|
||
|
|
length: number;
|
||
|
|
unknown: boolean;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** EBML element ID: the VINT with its marker bit kept. */
|
||
|
|
function readId(b: Uint8Array, at: number): Vint | null {
|
||
|
|
const first = b[at];
|
||
|
|
if (first === undefined) return null;
|
||
|
|
let len = 1;
|
||
|
|
while (len <= 4 && (first & (0x80 >> (len - 1))) === 0) len++;
|
||
|
|
if (len > 4) throw new MediaFormatError('bad EBML id');
|
||
|
|
if (at + len > b.length) return null;
|
||
|
|
let v = 0;
|
||
|
|
for (let i = 0; i < len; i++) v = v * 256 + b[at + i]!;
|
||
|
|
return { value: v, length: len, unknown: false };
|
||
|
|
}
|
||
|
|
|
||
|
|
/** EBML size: the VINT with its marker removed; all ones means unknown. */
|
||
|
|
function readSize(b: Uint8Array, at: number): Vint | null {
|
||
|
|
const first = b[at];
|
||
|
|
if (first === undefined) return null;
|
||
|
|
let len = 1;
|
||
|
|
while (len <= 8 && (first & (0x80 >> (len - 1))) === 0) len++;
|
||
|
|
if (len > 8) throw new MediaFormatError('bad EBML size');
|
||
|
|
if (at + len > b.length) return null;
|
||
|
|
let v = first & (0xff >> len);
|
||
|
|
let allOnes = v === 0xff >> len;
|
||
|
|
for (let i = 1; i < len; i++) {
|
||
|
|
const x = b[at + i]!;
|
||
|
|
if (x !== 0xff) allOnes = false;
|
||
|
|
v = v * 256 + x;
|
||
|
|
}
|
||
|
|
return { value: v, length: len, unknown: allOnes };
|
||
|
|
}
|
||
|
|
|
||
|
|
interface TrackInfo {
|
||
|
|
number: number;
|
||
|
|
type: number;
|
||
|
|
codec: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
function parseTracks(body: Uint8Array): TrackInfo[] {
|
||
|
|
const tracks: TrackInfo[] = [];
|
||
|
|
let at = 0;
|
||
|
|
while (at < body.length) {
|
||
|
|
const id = readId(body, at);
|
||
|
|
const size = id && readSize(body, at + id.length);
|
||
|
|
if (!id || !size) break;
|
||
|
|
const start = at + id.length + size.length;
|
||
|
|
if (id.value === ID_TRACK_ENTRY) {
|
||
|
|
const t: TrackInfo = { number: 0, type: 0, codec: '' };
|
||
|
|
let p = start;
|
||
|
|
const end = Math.min(body.length, start + size.value);
|
||
|
|
while (p < end) {
|
||
|
|
const cid = readId(body, p);
|
||
|
|
const csz = cid && readSize(body, p + cid.length);
|
||
|
|
if (!cid || !csz) break;
|
||
|
|
const cs = p + cid.length + csz.length;
|
||
|
|
const val = body.subarray(cs, cs + csz.value);
|
||
|
|
if (cid.value === ID_TRACK_NUMBER || cid.value === ID_TRACK_TYPE) {
|
||
|
|
let n = 0;
|
||
|
|
for (const x of val) n = n * 256 + x;
|
||
|
|
if (cid.value === ID_TRACK_NUMBER) t.number = n;
|
||
|
|
else t.type = n;
|
||
|
|
} else if (cid.value === ID_CODEC_ID) {
|
||
|
|
t.codec = new TextDecoder().decode(val);
|
||
|
|
}
|
||
|
|
p = cs + csz.value;
|
||
|
|
}
|
||
|
|
tracks.push(t);
|
||
|
|
}
|
||
|
|
at = start + size.value;
|
||
|
|
}
|
||
|
|
return tracks;
|
||
|
|
}
|
||
|
|
|
||
|
|
const CODECS: Record<string, string> = {
|
||
|
|
V_VP8: 'vp8',
|
||
|
|
V_VP9: 'vp9',
|
||
|
|
V_AV1: 'av01.0.08M.08',
|
||
|
|
A_OPUS: 'opus',
|
||
|
|
A_VORBIS: 'vorbis',
|
||
|
|
};
|
||
|
|
|
||
|
|
/** The MSE type string for a set of tracks, e.g. `video/webm; codecs="vp8,opus"`. */
|
||
|
|
export function webmMime(tracks: readonly TrackInfo[]): string {
|
||
|
|
const codecs = tracks.map((t) => CODECS[t.codec]).filter((c): c is string => c !== undefined);
|
||
|
|
const video = tracks.some((t) => t.type === 1);
|
||
|
|
return `${video ? 'video' : 'audio'}/webm${codecs.length > 0 ? `; codecs="${codecs.join(',')}"` : ''}`;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Relative timecode (signed 16-bit) of a SimpleBlock or BlockGroup body, or null. */
|
||
|
|
function blockTimecode(b: Uint8Array, id: number, body: number, end: number): number | null {
|
||
|
|
let at = body;
|
||
|
|
if (id === ID_BLOCK_GROUP) {
|
||
|
|
// Find the Block inside the group.
|
||
|
|
let found = -1;
|
||
|
|
while (at < end) {
|
||
|
|
const g = readId(b, at);
|
||
|
|
const gs = g && readSize(b, at + g.length);
|
||
|
|
if (!g || !gs) return null;
|
||
|
|
if (g.value === ID_BLOCK) {
|
||
|
|
found = at + g.length + gs.length;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
at += g.length + gs.length + gs.value;
|
||
|
|
}
|
||
|
|
if (found < 0) return null;
|
||
|
|
at = found;
|
||
|
|
} else if (id !== ID_SIMPLE_BLOCK) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
const track = readSize(b, at);
|
||
|
|
if (track === null || at + track.length + 2 > end) return null;
|
||
|
|
const v = (b[at + track.length]! << 8) | b[at + track.length + 1]!;
|
||
|
|
return v >= 0x8000 ? v - 0x10000 : v;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Put a cluster's blocks in timecode order across tracks.
|
||
|
|
*
|
||
|
|
* Chrome's WebM parser rejects a cluster in which any block — of any track —
|
||
|
|
* has an earlier timecode than the block before it ("Got a block with a
|
||
|
|
* timecode before the previous block"). ffmpeg's live muxer writes exactly
|
||
|
|
* that when Opus timestamps round a millisecond below an interleaved video
|
||
|
|
* frame. Each track's own order is already right, so a stable sort over all
|
||
|
|
* blocks only fixes the interleaving; the cluster keeps its size and every
|
||
|
|
* block its bytes.
|
||
|
|
*/
|
||
|
|
export function orderBlocks(cluster: Uint8Array): Uint8Array {
|
||
|
|
const id = readId(cluster, 0);
|
||
|
|
const size = id && readSize(cluster, id.length);
|
||
|
|
if (!id || !size) return cluster;
|
||
|
|
const bodyStart = id.length + size.length;
|
||
|
|
const children: { start: number; end: number; tc: number | null }[] = [];
|
||
|
|
let at = bodyStart;
|
||
|
|
while (at < cluster.length) {
|
||
|
|
const cid = readId(cluster, at);
|
||
|
|
const cs = cid && readSize(cluster, at + cid.length);
|
||
|
|
if (!cid || !cs) return cluster;
|
||
|
|
const body = at + cid.length + cs.length;
|
||
|
|
const end = body + cs.value;
|
||
|
|
if (end > cluster.length) return cluster;
|
||
|
|
children.push({ start: at, end, tc: blockTimecode(cluster, cid.value, body, end) });
|
||
|
|
at = end;
|
||
|
|
}
|
||
|
|
const slots = children.map((c, i) => (c.tc !== null ? i : -1)).filter((i) => i >= 0);
|
||
|
|
let ordered = true;
|
||
|
|
for (let k = 1; k < slots.length; k++) {
|
||
|
|
if (children[slots[k]!]!.tc! < children[slots[k - 1]!]!.tc!) ordered = false;
|
||
|
|
}
|
||
|
|
if (ordered) return cluster;
|
||
|
|
const blocks = slots.map((i) => children[i]!).sort((a, b) => a.tc! - b.tc!); // stable
|
||
|
|
const placed = children.slice();
|
||
|
|
slots.forEach((slot, k) => {
|
||
|
|
placed[slot] = blocks[k]!;
|
||
|
|
});
|
||
|
|
const out = new Uint8Array(cluster.length);
|
||
|
|
out.set(cluster.subarray(0, bodyStart), 0);
|
||
|
|
let w = bodyStart;
|
||
|
|
for (const c of placed) {
|
||
|
|
out.set(cluster.subarray(c.start, c.end), w);
|
||
|
|
w += c.end - c.start;
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
export class WebmSplitter {
|
||
|
|
private buf: Uint8Array = new Uint8Array(0);
|
||
|
|
private initDone = false;
|
||
|
|
private tracks: TrackInfo[] = [];
|
||
|
|
private videoTracks = new Set<number>();
|
||
|
|
/** Offset in `buf` where the cluster being assembled started, or -1. */
|
||
|
|
private clusterStart = -1;
|
||
|
|
/** For a known-size cluster: its end offset in `buf`. */
|
||
|
|
private clusterEnd = -1;
|
||
|
|
/** Scan position inside an unknown-size cluster. */
|
||
|
|
private scan = 0;
|
||
|
|
|
||
|
|
push(chunk: Uint8Array): WebmPiece[] {
|
||
|
|
this.buf = this.buf.length === 0 ? chunk.slice() : concat([this.buf, chunk]);
|
||
|
|
const out: WebmPiece[] = [];
|
||
|
|
if (!this.initDone) {
|
||
|
|
const init = this.tryInit();
|
||
|
|
if (init === null) return out;
|
||
|
|
out.push(init);
|
||
|
|
}
|
||
|
|
for (;;) {
|
||
|
|
const c = this.tryCluster(false);
|
||
|
|
if (c === null) break;
|
||
|
|
out.push(c);
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** End of stream: the last unknown-size cluster ends here. */
|
||
|
|
finish(): WebmPiece[] {
|
||
|
|
const out: WebmPiece[] = [];
|
||
|
|
const c = this.tryCluster(true);
|
||
|
|
if (c !== null) out.push(c);
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
private tryInit(): WebmPiece | null {
|
||
|
|
// EBML header, then the Segment header, then children until a Cluster.
|
||
|
|
let at = 0;
|
||
|
|
const ebml = readId(this.buf, at);
|
||
|
|
if (ebml === null) return null;
|
||
|
|
if (ebml.value !== ID_EBML) throw new MediaFormatError('not a WebM stream (no EBML header)');
|
||
|
|
const ebmlSize = readSize(this.buf, at + ebml.length);
|
||
|
|
if (ebmlSize === null) return null;
|
||
|
|
at += ebml.length + ebmlSize.length + ebmlSize.value;
|
||
|
|
const seg = readId(this.buf, at);
|
||
|
|
const segSize = seg && readSize(this.buf, at + seg.length);
|
||
|
|
if (!seg || !segSize) return null;
|
||
|
|
if (seg.value !== ID_SEGMENT) throw new MediaFormatError('WebM: expected Segment');
|
||
|
|
at += seg.length + segSize.length;
|
||
|
|
for (;;) {
|
||
|
|
const id = readId(this.buf, at);
|
||
|
|
if (id === null) return null;
|
||
|
|
if (id.value === ID_CLUSTER) break;
|
||
|
|
const size = readSize(this.buf, at + id.length);
|
||
|
|
if (size === null) return null;
|
||
|
|
if (size.unknown) throw new MediaFormatError('WebM: unknown-size element before the first Cluster');
|
||
|
|
const bodyStart = at + id.length + size.length;
|
||
|
|
if (bodyStart + size.value > this.buf.length) return null;
|
||
|
|
if (id.value === ID_TRACKS) this.tracks = parseTracks(this.buf.subarray(bodyStart, bodyStart + size.value));
|
||
|
|
at = bodyStart + size.value;
|
||
|
|
}
|
||
|
|
this.initDone = true;
|
||
|
|
for (const t of this.tracks) if (t.type === 1) this.videoTracks.add(t.number);
|
||
|
|
const bytes = this.buf.slice(0, at);
|
||
|
|
this.buf = this.buf.slice(at);
|
||
|
|
return { type: 'init', mime: webmMime(this.tracks), bytes };
|
||
|
|
}
|
||
|
|
|
||
|
|
private tryCluster(final: boolean): WebmPiece | null {
|
||
|
|
if (this.clusterStart < 0) {
|
||
|
|
// Skip anything between clusters that is not one (Cues, Tags, Void).
|
||
|
|
for (;;) {
|
||
|
|
const id = readId(this.buf, 0);
|
||
|
|
if (id === null) return null;
|
||
|
|
const size = readSize(this.buf, id.length);
|
||
|
|
if (size === null) return null;
|
||
|
|
if (id.value === ID_CLUSTER) {
|
||
|
|
this.clusterStart = 0;
|
||
|
|
const body = id.length + size.length;
|
||
|
|
this.clusterEnd = size.unknown ? -1 : body + size.value;
|
||
|
|
this.scan = body;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
if (size.unknown) throw new MediaFormatError('WebM: unknown-size element between clusters');
|
||
|
|
const skip = id.length + size.length + size.value;
|
||
|
|
if (skip > this.buf.length) return null;
|
||
|
|
this.buf = this.buf.slice(skip);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
let end: number;
|
||
|
|
if (this.clusterEnd >= 0) {
|
||
|
|
if (this.buf.length < this.clusterEnd) return null;
|
||
|
|
end = this.clusterEnd;
|
||
|
|
} else {
|
||
|
|
// Walk children until one that cannot belong to a Cluster.
|
||
|
|
for (;;) {
|
||
|
|
const id = readId(this.buf, this.scan);
|
||
|
|
const size = id && readSize(this.buf, this.scan + id.length);
|
||
|
|
if (!id || !size) {
|
||
|
|
if (final) {
|
||
|
|
end = this.buf.length;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
if (!CLUSTER_CHILDREN.has(id.value)) {
|
||
|
|
end = this.scan;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
const next = this.scan + id.length + size.length + size.value;
|
||
|
|
if (next > this.buf.length) {
|
||
|
|
if (final) {
|
||
|
|
end = this.buf.length;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
this.scan = next;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (end <= 0) return null;
|
||
|
|
const bytes = orderBlocks(this.buf.slice(0, end));
|
||
|
|
this.buf = this.buf.slice(end);
|
||
|
|
this.clusterStart = -1;
|
||
|
|
this.clusterEnd = -1;
|
||
|
|
return { type: 'cluster', keyframe: this.isKeyframe(bytes), bytes };
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Does the first block of a video track in this cluster start a GOP? */
|
||
|
|
private isKeyframe(cluster: Uint8Array): boolean {
|
||
|
|
if (this.videoTracks.size === 0) return true; // audio only: every cluster is a start
|
||
|
|
const id = readId(cluster, 0)!;
|
||
|
|
const size = readSize(cluster, id.length)!;
|
||
|
|
let at = id.length + size.length;
|
||
|
|
while (at < cluster.length) {
|
||
|
|
const cid = readId(cluster, at);
|
||
|
|
const cs = cid && readSize(cluster, at + cid.length);
|
||
|
|
if (!cid || !cs) return false;
|
||
|
|
const body = at + cid.length + cs.length;
|
||
|
|
if (cid.value === ID_SIMPLE_BLOCK) {
|
||
|
|
const track = readSize(cluster, body);
|
||
|
|
if (track && this.videoTracks.has(track.value)) {
|
||
|
|
return (cluster[body + track.length + 2]! & 0x80) !== 0;
|
||
|
|
}
|
||
|
|
} else if (cid.value === ID_BLOCK_GROUP) {
|
||
|
|
// A BlockGroup is a keyframe iff it has no ReferenceBlock.
|
||
|
|
let p = body;
|
||
|
|
let track: Vint | null = null;
|
||
|
|
let referenced = false;
|
||
|
|
while (p < body + cs.value) {
|
||
|
|
const g = readId(cluster, p);
|
||
|
|
const gs = g && readSize(cluster, p + g.length);
|
||
|
|
if (!g || !gs) break;
|
||
|
|
if (g.value === ID_BLOCK) track = readSize(cluster, p + g.length + gs.length);
|
||
|
|
if (g.value === ID_REFERENCE_BLOCK) referenced = true;
|
||
|
|
p += g.length + gs.length + gs.value;
|
||
|
|
}
|
||
|
|
if (track && this.videoTracks.has(track.value)) return !referenced;
|
||
|
|
}
|
||
|
|
at = body + cs.value;
|
||
|
|
}
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|