Matroska Header
Read a Matroska or WebM file's header — running time, every track with its codec and language, the forced, default, original, hearing-impaired, visual-impaired and audio-description flags, and editions of ordered chapters — with no dependencies, in Node or the browser. readMatroskaHeader(bytes) walks the EBML tree over the bytes you hand it (the whole file, or just its head and tail), never decodes a frame, and names any header element it could not reach rather than guessing. Like its exif-parser sibling it checks the structure before it trusts it, throwing on anything malformed.
The honest edge
It reads the container's header, never the media: no frame is decoded, nothing checks that a stream matches what its header says, and Tags (titles, artists, ratings) and Attachments (cover art, fonts) are not read. It reads only the windows it is handed and names every header element it could not reach whole, never guessing. The running time is the header's Duration, which a muxer can write wrong: it is read, not measured.
Run it
node matroska-header.js film.mkv
test_matroska-header.js (30/30: hand-built EBML vectors, bounded windows and the SeekHead, six refusal cases, 64-bit UIDs; ffprobe as the oracle when installed; kill sheet 22/22)
Node / browser, no dependencies
The code — every file that ships
matroska-header.js281 lineson GitHub →
#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// matroska-header.js — read a Matroska or WebM file's header (running time, tracks with codec, language and the six
// flags, editions with ordered chapters) without decoding a frame. No dependencies; Node or the browser.
//
// readMatroskaHeader(bytes) one window at offset 0 (a Uint8Array or Buffer)
// readMatroskaHeader([{offset, bytes}, ...]) several windows of one file (say its head and its tail)
//
// It walks the EBML tree over the windows it is handed and nothing else. A header element it cannot read whole from
// those windows is named in `unreached`, never guessed. Untrusted bytes are checked before they are trusted: the EBML
// magic, the doc type, every variable-length integer, every child against its parent, and a nesting bound. Anything
// malformed throws MatroskaError. Clusters (the frames) are skipped by their size and never read.
// Element IDs: RFC 9559 (Matroska), witnessed against ffprobe in test_matroska-header.js.
'use strict';
class MatroskaError extends Error {
constructor(message) { super(message); this.name = 'MatroskaError'; }
}
const ID = {
EBML: 0x1A45DFA3, DocType: 0x4282, DocTypeVersion: 0x4287, Segment: 0x18538067,
SeekHead: 0x114D9B74, Seek: 0x4DBB, SeekID: 0x53AB, SeekPosition: 0x53AC,
Info: 0x1549A966, TimestampScale: 0x2AD7B1, Duration: 0x4489, Title: 0x7BA9,
Tracks: 0x1654AE6B, TrackEntry: 0xAE, TrackNumber: 0xD7, TrackUID: 0x73C5, TrackType: 0x83,
FlagDefault: 0x88, FlagForced: 0x55AA, FlagHearingImpaired: 0x55AB, FlagVisualImpaired: 0x55AC,
FlagTextDescriptions: 0x55AD, FlagOriginal: 0x55AE, Name: 0x536E, Language: 0x22B59C, LanguageBCP47: 0x22B59D,
CodecID: 0x86, Video: 0xE0, PixelWidth: 0xB0, PixelHeight: 0xBA, Audio: 0xE1, SamplingFrequency: 0xB5, Channels: 0x9F,
Chapters: 0x1043A770, EditionEntry: 0x45B9, EditionUID: 0x45BC, EditionFlagHidden: 0x45BD,
EditionFlagDefault: 0x45DB, EditionFlagOrdered: 0x45DD, ChapterAtom: 0xB6, ChapterUID: 0x73C4,
ChapterTimeStart: 0x91, ChapterTimeEnd: 0x92, ChapterFlagHidden: 0x98, ChapterFlagEnabled: 0x4598,
ChapterDisplay: 0x80, ChapString: 0x85, ChapLanguage: 0x437C, ChapLanguageBCP47: 0x437D,
Cluster: 0x1F43B675, Cues: 0x1C53BB6B, Tags: 0x1254C367, Attachments: 0x1941A469,
};
const HEADER_PARTS = { [ID.Info]: 'Info', [ID.Tracks]: 'Tracks', [ID.Chapters]: 'Chapters' };
const TRACK_KIND = { 1: 'video', 2: 'audio', 3: 'complex', 0x10: 'logo', 0x11: 'subtitle', 0x12: 'buttons', 0x20: 'control', 0x21: 'metadata' };
const MAX_DEPTH = 32; // the deepest real header (chapters within chapters) is far shallower
const MAX_STRING = 65536; // a codec id, a language, a title: never this long in a real file
const MAX_ELEMENTS = 200000; // a bound on work for one call
const UNKNOWN = -1; // an element of unknown size (only a Segment or a Cluster may be one)
// ---- windows: the bytes of one file at known offsets ----
function toWindows(input) {
const list = Array.isArray(input) ? input : [{ offset: 0, bytes: input }];
return list.map((w) => {
if (!w || !(w.bytes instanceof Uint8Array) || !Number.isSafeInteger(w.offset) || w.offset < 0) {
throw new MatroskaError('each window needs a whole-number offset and a Uint8Array of bytes');
}
return { start: w.offset, end: w.offset + w.bytes.length, bytes: w.bytes };
}).sort((a, b) => a.start - b.start);
}
function windowAt(ws, pos) { for (const w of ws) if (pos >= w.start && pos < w.end) return w; return null; }
function have(ws, start, end) { const w = windowAt(ws, start); return w !== null && end <= w.end; }
function byteAt(ws, pos) { const w = windowAt(ws, pos); return w === null ? null : w.bytes[pos - w.start]; }
// ---- variable-length integers ----
function readVint(ws, pos, isId) {
const first = byteAt(ws, pos);
if (first === null) return null; // out of every window: not readable here
if (first === 0) throw new MatroskaError(`invalid variable-length integer at byte ${pos}`);
let len = 1; while (!(first & (0x80 >> (len - 1)))) len++;
if (len > (isId ? 4 : 8)) throw new MatroskaError(`variable-length integer too long at byte ${pos}`);
if (!have(ws, pos, pos + len)) return null;
let value = isId ? first : first & (0xFF >> len); let allOnes = value === (0xFF >> len);
for (let i = 1; i < len; i++) {
const b = byteAt(ws, pos + i); value = value * 256 + b; if (b !== 0xFF) allOnes = false;
}
if (!isId && allOnes) return { value: UNKNOWN, len };
if (!Number.isSafeInteger(value)) throw new MatroskaError(`size too large at byte ${pos}`);
return { value, len };
}
function readHeader(ws, pos) {
const id = readVint(ws, pos, true); if (id === null) return null;
const size = readVint(ws, pos + id.len, false); if (size === null) return null;
return { id: id.value, start: pos, data: pos + id.len + size.len, size: size.value };
}
// ---- leaf values ----
function bytesOf(ws, e) {
const w = windowAt(ws, e.data);
return w.bytes.subarray(e.data - w.start, e.data - w.start + e.size);
}
function uint(ws, e) {
if (e.size > 8) throw new MatroskaError(`unsigned integer of ${e.size} bytes at byte ${e.start}`);
let v = 0; for (const b of bytesOf(ws, e)) v = v * 256 + b;
if (!Number.isSafeInteger(v)) throw new MatroskaError(`unsigned integer too large at byte ${e.start}`);
return v;
}
function float(ws, e) {
if (e.size === 0) return 0;
if (e.size !== 4 && e.size !== 8) throw new MatroskaError(`float of ${e.size} bytes at byte ${e.start}`);
const b = bytesOf(ws, e); const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
return e.size === 4 ? dv.getFloat32(0) : dv.getFloat64(0);
}
function text(ws, e) {
if (e.size > MAX_STRING) throw new MatroskaError(`string of ${e.size} bytes at byte ${e.start}`);
let b = bytesOf(ws, e); const nul = b.indexOf(0); if (nul >= 0) b = b.subarray(0, nul);
return new TextDecoder('utf-8').decode(b);
}
const flag = (ws, e) => uint(ws, e) !== 0;
function uid(ws, e) { // a UID is any 64-bit value: kept whole, as a decimal string
if (e.size > 8) throw new MatroskaError(`UID of ${e.size} bytes at byte ${e.start}`);
let v = BigInt(0); for (const b of bytesOf(ws, e)) v = v * BigInt(256) + BigInt(b);
return v.toString();
}
// ---- the walk ----
function children(ws, parent, depth, budget) {
if (depth > MAX_DEPTH) throw new MatroskaError(`nesting deeper than ${MAX_DEPTH} at byte ${parent.start}`);
const out = []; let pos = parent.data; const end = parent.data + parent.size;
while (pos < end) {
if (++budget.n > MAX_ELEMENTS) throw new MatroskaError('too many elements');
const e = readHeader(ws, pos);
if (e === null) throw new MatroskaError(`element at byte ${pos} is not in the window that holds its parent`);
if (e.size === UNKNOWN) throw new MatroskaError(`unknown size inside a header element at byte ${pos}`);
if (e.data + e.size > end) throw new MatroskaError(`element at byte ${pos} runs past its parent`);
if (!have(ws, e.data, e.data + e.size)) throw new MatroskaError(`element at byte ${pos} is not in the window that holds its parent`);
out.push(e); pos = e.data + e.size;
}
return out;
}
const kid = (list, id) => list.find((e) => e.id === id);
const kids = (list, id) => list.filter((e) => e.id === id);
function parseInfo(ws, e, budget, out) {
const c = children(ws, e, 2, budget);
const ts = kid(c, ID.TimestampScale); out.timestamp_scale = ts ? uint(ws, ts) : 1000000;
const d = kid(c, ID.Duration); out.duration_raw = d ? float(ws, d) : null;
const t = kid(c, ID.Title); out.title = t ? text(ws, t) : null;
}
function language(ws, list, isoId, bcpId, isoDefault) {
const iso = kid(list, isoId); const bcp = kid(list, bcpId);
const isoValue = iso ? text(ws, iso) : isoDefault; const bcpValue = bcp ? text(ws, bcp) : null;
return { language: bcpValue !== null ? bcpValue : isoValue, language_iso639_2: isoValue, language_bcp47: bcpValue, defaulted: !iso && !bcp };
}
function parseTracks(ws, e, budget) {
return kids(children(ws, e, 2, budget), ID.TrackEntry).map((te) => {
const c = children(ws, te, 3, budget);
const num = kid(c, ID.TrackNumber); const type = kid(c, ID.TrackType); const codec = kid(c, ID.CodecID); const name = kid(c, ID.Name);
const uidEl = kid(c, ID.TrackUID);
const optFlag = (id) => { const f = kid(c, id); return f ? flag(ws, f) : null; };
const lang = language(ws, c, ID.Language, ID.LanguageBCP47, 'eng');
const typeNum = type ? uint(ws, type) : null;
const track = {
number: num ? uint(ws, num) : null, uid: uidEl ? uid(ws, uidEl) : null, type: typeNum,
kind: typeNum === null ? null : (TRACK_KIND[typeNum] || 'unknown'),
codec_id: codec ? text(ws, codec) : null, name: name ? text(ws, name) : null,
language: lang.language, language_iso639_2: lang.language_iso639_2, language_bcp47: lang.language_bcp47,
language_defaulted: lang.defaulted,
flags: {
default: kid(c, ID.FlagDefault) ? flag(ws, kid(c, ID.FlagDefault)) : true,
forced: kid(c, ID.FlagForced) ? flag(ws, kid(c, ID.FlagForced)) : false,
hearing_impaired: optFlag(ID.FlagHearingImpaired), visual_impaired: optFlag(ID.FlagVisualImpaired),
descriptions: optFlag(ID.FlagTextDescriptions), original: optFlag(ID.FlagOriginal),
},
};
const v = kid(c, ID.Video);
if (v) { const vc = children(ws, v, 4, budget); const w = kid(vc, ID.PixelWidth); const h = kid(vc, ID.PixelHeight);
track.video = { width: w ? uint(ws, w) : null, height: h ? uint(ws, h) : null }; }
const a = kid(c, ID.Audio);
if (a) { const ac = children(ws, a, 4, budget); const sf = kid(ac, ID.SamplingFrequency); const ch = kid(ac, ID.Channels);
track.audio = { sampling_frequency: sf ? float(ws, sf) : 8000, channels: ch ? uint(ws, ch) : 1 }; }
return track;
});
}
function parseChapter(ws, e, depth, budget) {
const c = children(ws, e, depth, budget);
const g = (id) => kid(c, id);
return {
uid: g(ID.ChapterUID) ? uid(ws, g(ID.ChapterUID)) : null,
start_ns: g(ID.ChapterTimeStart) ? uint(ws, g(ID.ChapterTimeStart)) : null,
end_ns: g(ID.ChapterTimeEnd) ? uint(ws, g(ID.ChapterTimeEnd)) : null,
hidden: g(ID.ChapterFlagHidden) ? flag(ws, g(ID.ChapterFlagHidden)) : false,
enabled: g(ID.ChapterFlagEnabled) ? flag(ws, g(ID.ChapterFlagEnabled)) : true,
titles: kids(c, ID.ChapterDisplay).map((d) => {
const dc = children(ws, d, depth + 1, budget); const str = kid(dc, ID.ChapString);
const lang = language(ws, dc, ID.ChapLanguage, ID.ChapLanguageBCP47, 'eng');
return { title: str ? text(ws, str) : null, language: lang.language, language_iso639_2: lang.language_iso639_2, language_bcp47: lang.language_bcp47 };
}),
chapters: kids(c, ID.ChapterAtom).map((sub) => parseChapter(ws, sub, depth + 1, budget)),
};
}
function parseChapters(ws, e, budget) {
return kids(children(ws, e, 2, budget), ID.EditionEntry).map((ed) => {
const c = children(ws, ed, 3, budget); const g = (id) => kid(c, id);
return {
uid: g(ID.EditionUID) ? uid(ws, g(ID.EditionUID)) : null,
default: g(ID.EditionFlagDefault) ? flag(ws, g(ID.EditionFlagDefault)) : false,
ordered: g(ID.EditionFlagOrdered) ? flag(ws, g(ID.EditionFlagOrdered)) : false,
hidden: g(ID.EditionFlagHidden) ? flag(ws, g(ID.EditionFlagHidden)) : false,
chapters: kids(c, ID.ChapterAtom).map((a) => parseChapter(ws, a, 4, budget)),
};
});
}
function readMatroskaHeader(input) {
const ws = toWindows(input); const budget = { n: 0 };
const head = readHeader(ws, 0);
if (head === null || head.id !== ID.EBML) throw new MatroskaError('not an EBML file (no EBML header at byte 0)');
if (head.size === UNKNOWN || !have(ws, head.data, head.data + head.size)) throw new MatroskaError('the EBML header is not whole in the first window');
const hc = children(ws, head, 1, budget);
const dt = kid(hc, ID.DocType); const docType = dt ? text(ws, dt) : 'matroska';
if (docType !== 'matroska' && docType !== 'webm') throw new MatroskaError(`doc type "${docType}" is not matroska or webm`);
const dtv = kid(hc, ID.DocTypeVersion);
const seg = readHeader(ws, head.data + head.size);
if (seg === null || seg.id !== ID.Segment) throw new MatroskaError('no Segment after the EBML header');
const segEnd = seg.size === UNKNOWN ? Infinity : seg.data + seg.size;
const out = { doc_type: docType, doc_type_version: dtv ? uint(ws, dtv) : 1, timestamp_scale: 1000000, duration_raw: null, title: null };
let tracks = []; let editions = [];
const found = {}; const seekTo = {};
const take = (e) => {
const part = HEADER_PARTS[e.id]; if (!part || found[part]) return;
found[part] = true;
if (e.id === ID.Info) parseInfo(ws, e, budget, out);
else if (e.id === ID.Tracks) tracks = parseTracks(ws, e, budget);
else editions = parseChapters(ws, e, budget);
};
// The linear walk: top-level children of the Segment, in order, until the window ends or a Cluster begins.
let pos = seg.data;
while (pos < segEnd) {
if (++budget.n > MAX_ELEMENTS) throw new MatroskaError('too many elements');
const e = readHeader(ws, pos);
if (e === null) break; // the window ended
if (e.id === ID.Cluster) break; // frames begin: never read them
if (e.size === UNKNOWN) throw new MatroskaError(`unknown size on a non-Cluster element at byte ${pos}`);
if (e.data + e.size > segEnd) throw new MatroskaError(`element at byte ${pos} runs past its parent`);
if (HEADER_PARTS[e.id] || e.id === ID.SeekHead) {
if (!have(ws, e.data, e.data + e.size)) { if (HEADER_PARTS[e.id]) seekTo[HEADER_PARTS[e.id]] = { at: e.start, cut: true }; break; }
if (e.id === ID.SeekHead) {
for (const s of kids(children(ws, e, 2, budget), ID.Seek)) {
const sc = children(ws, s, 3, budget); const sid = kid(sc, ID.SeekID); const sp = kid(sc, ID.SeekPosition);
if (!sid || !sp) continue;
let idv = 0; for (const b of bytesOf(ws, sid)) idv = idv * 256 + b;
const part = HEADER_PARTS[idv]; if (part && !seekTo[part]) seekTo[part] = { at: seg.data + uint(ws, sp) };
}
} else take(e);
}
pos = e.data + e.size;
}
// The SeekHead's pointers: any header part not met on the walk is read wherever a window holds it whole.
const unreached = [];
for (const part of ['Info', 'Tracks', 'Chapters']) {
if (found[part] || !seekTo[part]) continue;
const e = readHeader(ws, seekTo[part].at);
if (e !== null && HEADER_PARTS[e.id] === part && e.size !== UNKNOWN && e.data + e.size <= segEnd && have(ws, e.data, e.data + e.size)) take(e);
else unreached.push(part);
}
return {
doc_type: out.doc_type, doc_type_version: out.doc_type_version, timestamp_scale: out.timestamp_scale,
duration_ns: out.duration_raw === null ? null : out.duration_raw * out.timestamp_scale, title: out.title,
tracks, editions, unreached,
};
}
// ---- the command line: bounded windows from a file, JSON out ----
const HEAD_BYTES = 4 * 1024 * 1024;
const TAIL_BYTES = 1024 * 1024;
function readFileWindows(fs, file) {
const fd = fs.openSync(file, 'r');
try {
const size = fs.fstatSync(fd).size; const windows = [];
const headLen = Math.min(size, HEAD_BYTES); const head = Buffer.alloc(headLen); fs.readSync(fd, head, 0, headLen, 0);
windows.push({ offset: 0, bytes: head });
if (size > headLen) {
const tailStart = Math.max(headLen, size - TAIL_BYTES); const tail = Buffer.alloc(size - tailStart);
fs.readSync(fd, tail, 0, tail.length, tailStart); windows.push({ offset: tailStart, bytes: tail });
}
return windows;
} finally { fs.closeSync(fd); }
}
if (typeof module !== 'undefined' && module.exports) module.exports = { readMatroskaHeader, readFileWindows, MatroskaError, HEAD_BYTES, TAIL_BYTES };
if (typeof require !== 'undefined' && typeof module !== 'undefined' && require.main === module) {
const fs = require('fs'); const file = process.argv[2];
const usage = 'usage: node matroska-header.js FILE.mkv (prints the header facts as JSON; reads the first 4 MiB and the last 1 MiB)\n';
if (file === '--help' || file === '-h') { process.stdout.write(usage); process.exit(0); }
if (!file) { process.stderr.write(usage); process.exit(2); }
try { process.stdout.write(JSON.stringify(readMatroskaHeader(readFileWindows(fs, file)), null, 2) + '\n'); }
catch (e) { process.stderr.write(`${e.name}: ${e.message}\n`); process.exit(e instanceof MatroskaError ? 3 : 1); }
}
test_matroska-header.js305 lineson GitHub →
#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// test_matroska-header.js — the Matroska header reader's tests (Gift; the-library AV4, Blueprint B3.34, D266).
// Hand-built EBML vectors (every element ID written once, in E below) plus, when ffmpeg and ffprobe are present,
// real files written by ffmpeg and read back by ffprobe as the oracle. Absent tools are SKIPPED and said so.
// Run: node test_matroska-header.js
'use strict';
const assert = require('assert');
const path = require('path');
const { readMatroskaHeader, MatroskaError } = require(path.join(__dirname, 'matroska-header.js'));
// ---- a tiny EBML writer (tests only) ----
const E = {
EBML: '1A45DFA3', DocType: '4282', DocTypeVersion: '4287', Segment: '18538067', SeekHead: '114D9B74',
Seek: '4DBB', SeekID: '53AB', SeekPosition: '53AC', Info: '1549A966', TimestampScale: '2AD7B1',
Duration: '4489', Title: '7BA9', Tracks: '1654AE6B', TrackEntry: 'AE', TrackNumber: 'D7', TrackUID: '73C5',
TrackType: '83', FlagEnabled: 'B9', FlagDefault: '88', FlagForced: '55AA', FlagHearingImpaired: '55AB',
FlagVisualImpaired: '55AC', FlagTextDescriptions: '55AD', FlagOriginal: '55AE', Name: '536E',
Language: '22B59C', LanguageBCP47: '22B59D', CodecID: '86', Video: 'E0', PixelWidth: 'B0', PixelHeight: 'BA',
Audio: 'E1', SamplingFrequency: 'B5', Channels: '9F', Chapters: '1043A770', EditionEntry: '45B9',
EditionUID: '45BC', EditionFlagHidden: '45BD', EditionFlagDefault: '45DB', EditionFlagOrdered: '45DD',
ChapterAtom: 'B6', ChapterUID: '73C4', ChapterTimeStart: '91', ChapterTimeEnd: '92', ChapterFlagHidden: '98',
ChapterFlagEnabled: '4598', ChapterDisplay: '80', ChapString: '85', ChapLanguage: '437C',
ChapLanguageBCP47: '437D', Cluster: '1F43B675', Void: 'EC', Tags: '1254C367',
};
const hex = (h) => Buffer.from(h, 'hex');
function vsize(n) { // smallest EBML size vint for n
for (let len = 1; len <= 8; len++) {
if (n < Math.pow(2, 7 * len) - 1) {
const out = Buffer.alloc(len); let v = n;
for (let i = len - 1; i >= 0; i--) { out[i] = v % 256; v = Math.floor(v / 256); }
out[0] |= 1 << (8 - len); return out;
}
}
throw new Error('too big');
}
const el = (name, ...kids) => { const body = Buffer.concat(kids); return Buffer.concat([hex(E[name]), vsize(body.length), body]); };
const unknownSize = (name, ...kids) => Buffer.concat([hex(E[name]), hex('01FFFFFFFFFFFFFF'), ...kids]);
const u = (n) => { if (n === 0) return Buffer.from([0]); const b = []; let v = n; while (v > 0) { b.unshift(v % 256); v = Math.floor(v / 256); } return Buffer.from(b); };
const s = (t) => Buffer.from(t, 'utf8');
const f64 = (x) => { const b = Buffer.alloc(8); b.writeDoubleBE(x); return b; };
const f32 = (x) => { const b = Buffer.alloc(4); b.writeFloatBE(x); return b; };
const ebmlHead = (doc = 'matroska') => el('EBML', el('DocType', s(doc)), el('DocTypeVersion', u(4)));
function film() { // a two-cut film: video, French audio (ISO only), pt-BR audio (both codes), forced subtitle
return Buffer.concat([ebmlHead(), el('Segment',
el('Info', el('TimestampScale', u(1000000)), el('Duration', f64(5400000.0)), el('Title', s('The Lantern Coast'))),
el('Tracks',
el('TrackEntry', el('TrackNumber', u(1)), el('TrackUID', u(11)), el('TrackType', u(1)), el('CodecID', s('V_MPEGH/ISO/HEVC')),
el('Video', el('PixelWidth', u(3840)), el('PixelHeight', u(1600)))),
el('TrackEntry', el('TrackNumber', u(2)), el('TrackType', u(2)), el('CodecID', s('A_PCM/INT/LIT')), el('Language', s('fre')),
el('FlagHearingImpaired', u(0)), el('FlagOriginal', u(1)), el('Name', s('Original')),
el('Audio', el('SamplingFrequency', f64(48000)), el('Channels', u(6)))),
el('TrackEntry', el('TrackNumber', u(3)), el('TrackType', u(2)), el('CodecID', s('A_AAC')), el('Language', s('por')),
el('LanguageBCP47', s('pt-BR')), el('FlagDefault', u(0)), el('FlagTextDescriptions', u(1)), el('FlagVisualImpaired', u(1)),
el('Audio', el('SamplingFrequency', f32(44100)), el('Channels', u(2)))),
el('TrackEntry', el('TrackNumber', u(4)), el('TrackType', u(0x11)), el('CodecID', s('S_TEXT/UTF8')), el('Language', s('eng')),
el('FlagForced', u(1)), el('FlagDefault', u(0)))),
el('Chapters',
el('EditionEntry', el('EditionUID', u(100)), el('EditionFlagDefault', u(1)), el('EditionFlagOrdered', u(0)),
el('ChapterAtom', el('ChapterUID', u(1)), el('ChapterTimeStart', u(0)), el('ChapterTimeEnd', u(60e9)),
el('ChapterDisplay', el('ChapString', s('Opening')), el('ChapLanguage', s('eng'))))),
el('EditionEntry', el('EditionUID', u(200)), el('EditionFlagOrdered', u(1)),
el('ChapterAtom', el('ChapterUID', u(2)), el('ChapterTimeStart', u(120e9)), el('ChapterTimeEnd', u(180e9)),
el('ChapterDisplay', el('ChapString', s('Extended scene')), el('ChapLanguageBCP47', s('en-GB')), el('ChapLanguage', s('eng')))),
el('ChapterAtom', el('ChapterUID', u(3)), el('ChapterTimeStart', u(0)), el('ChapterTimeEnd', u(60e9)), el('ChapterFlagHidden', u(1))))),
el('Cluster', hex('E7'), vsize(1), u(0), hex('A3'), vsize(4), hex('81000080')))]);
}
let passed = 0, failed = 0, skipped = 0;
function t(name, fn) {
try { fn(); passed++; } catch (e) { failed++; console.log(`FAIL ${name}\n ${e && e.message}`); }
}
function skip(name, why) { skipped++; console.log(`SKIP ${name} — ${why}`); }
// ---- the header ----
t('reads the doc type and running time from the header (duration x timestamp scale, in nanoseconds)', () => {
const r = readMatroskaHeader(film());
assert.strictEqual(r.doc_type, 'matroska');
assert.strictEqual(r.doc_type_version, 4);
assert.strictEqual(r.timestamp_scale, 1000000);
assert.strictEqual(r.duration_ns, 5400000.0 * 1000000);
assert.strictEqual(r.title, 'The Lantern Coast');
});
t('webm is a Matroska doc type and is read the same way', () => {
const b = Buffer.concat([ebmlHead('webm'), el('Segment', el('Info', el('Duration', f64(1000))))]);
const r = readMatroskaHeader(b);
assert.strictEqual(r.doc_type, 'webm');
assert.strictEqual(r.timestamp_scale, 1000000, 'the spec default when absent');
assert.strictEqual(r.duration_ns, 1000 * 1000000);
});
t('an absent Duration is null, never zero', () => {
const b = Buffer.concat([ebmlHead(), el('Segment', el('Info', el('TimestampScale', u(1000000))))]);
assert.strictEqual(readMatroskaHeader(b).duration_ns, null);
});
// ---- tracks ----
t('reads every track with its number, kind and codec id', () => {
const r = readMatroskaHeader(film());
assert.deepStrictEqual(r.tracks.map((x) => [x.number, x.kind, x.codec_id]),
[[1, 'video', 'V_MPEGH/ISO/HEVC'], [2, 'audio', 'A_PCM/INT/LIT'], [3, 'audio', 'A_AAC'], [4, 'subtitle', 'S_TEXT/UTF8']]);
assert.deepStrictEqual(r.tracks[0].video, { width: 3840, height: 1600 });
assert.deepStrictEqual(r.tracks[1].audio, { sampling_frequency: 48000, channels: 6 });
assert.deepStrictEqual(r.tracks[2].audio, { sampling_frequency: 44100, channels: 2 });
assert.strictEqual(r.tracks[1].name, 'Original');
});
t('the BCP 47 tag wins over the three-letter code when both are present', () => {
const r = readMatroskaHeader(film());
assert.strictEqual(r.tracks[2].language, 'pt-BR');
assert.strictEqual(r.tracks[2].language_iso639_2, 'por');
assert.strictEqual(r.tracks[2].language_bcp47, 'pt-BR');
assert.strictEqual(r.tracks[1].language, 'fre');
assert.strictEqual(r.tracks[1].language_bcp47, null);
});
t('an absent Language reads the spec default eng, marked as defaulted', () => {
const r = readMatroskaHeader(film());
assert.strictEqual(r.tracks[0].language, 'eng');
assert.strictEqual(r.tracks[0].language_defaulted, true);
assert.strictEqual(r.tracks[1].language_defaulted, false);
});
t('the six flags: default and forced take their spec defaults; the four accessibility flags are null when absent', () => {
const [v, fr, pt, sub] = readMatroskaHeader(film()).tracks;
assert.deepStrictEqual(v.flags, { default: true, forced: false, hearing_impaired: null, visual_impaired: null, descriptions: null, original: null });
assert.deepStrictEqual(fr.flags, { default: true, forced: false, hearing_impaired: false, visual_impaired: null, descriptions: null, original: true });
assert.deepStrictEqual(pt.flags, { default: false, forced: false, hearing_impaired: null, visual_impaired: true, descriptions: true, original: null });
assert.deepStrictEqual(sub.flags, { default: false, forced: true, hearing_impaired: null, visual_impaired: null, descriptions: null, original: null });
});
// ---- editions and chapters ----
t('reads editions with their default and ordered flags', () => {
const ed = readMatroskaHeader(film()).editions;
assert.deepStrictEqual(ed.map((e) => [e.uid, e.default, e.ordered, e.hidden]), [['100', true, false, false], ['200', false, true, false]]);
});
t('an ordered edition keeps its chapters in stored order, with times in nanoseconds and titles with languages', () => {
const ch = readMatroskaHeader(film()).editions[1].chapters;
assert.deepStrictEqual(ch.map((c) => [c.uid, c.start_ns, c.end_ns, c.hidden]), [['2', 120e9, 180e9, false], ['3', 0, 60e9, true]]);
assert.deepStrictEqual(ch[0].titles, [{ title: 'Extended scene', language: 'en-GB', language_iso639_2: 'eng', language_bcp47: 'en-GB' }]);
assert.strictEqual(ch[0].enabled, true);
});
// ---- never decode; bounded windows ----
t('never reads inside a Cluster: frames are skipped, not decoded', () => {
const r = readMatroskaHeader(film());
assert.ok(!('clusters' in r));
assert.deepStrictEqual(r.unreached, []);
});
t('stops at an unknown-size Cluster and still reports the header before it', () => {
const b = Buffer.concat([ebmlHead(), unknownSize('Segment',
el('Info', el('Duration', f64(2000))), el('Tracks', el('TrackEntry', el('TrackNumber', u(1)), el('TrackType', u(2)), el('CodecID', s('A_FLAC')))),
unknownSize('Cluster', hex('E781'), u(0)))]);
const r = readMatroskaHeader(b);
assert.strictEqual(r.tracks.length, 1);
assert.strictEqual(r.duration_ns, 2000 * 1000000);
});
t('a header element cut off by the window is named unreached, never guessed', () => {
const whole = film();
const cut = whole.subarray(0, whole.indexOf(hex(E.Chapters)) + 12);
const r = readMatroskaHeader(cut);
assert.strictEqual(r.tracks.length, 4, 'Tracks sat wholly inside the window');
assert.deepStrictEqual(r.editions, []);
assert.deepStrictEqual(r.unreached, ['Chapters']);
});
t('reads a top-level element from a later window found through the SeekHead', () => {
// Segment: SeekHead -> Chapters at a far offset; the head window ends in a Cluster; the tail window holds Chapters.
const chapters = el('Chapters', el('EditionEntry', el('EditionUID', u(9)), el('ChapterAtom', el('ChapterUID', u(5)), el('ChapterTimeStart', u(0)))));
const info = el('Info', el('Duration', f64(10)));
const tracks = el('Tracks', el('TrackEntry', el('TrackNumber', u(1)), el('TrackType', u(1)), el('CodecID', s('V_AV1'))));
const filler = el('Cluster', hex('E7'), vsize(1), u(0), el('Void', Buffer.alloc(5000))); // frames: the walk stops here
const seekLen = 30; // SeekHead is padded to a fixed length so positions are known before it is built
const body = (seek) => Buffer.concat([seek, info, tracks, filler, chapters]);
const chapPos = seekLen + info.length + tracks.length + filler.length;
let seek = el('SeekHead', el('Seek', el('SeekID', hex(E.Chapters)), el('SeekPosition', u(chapPos))));
seek = Buffer.concat([seek, el('Void', Buffer.alloc(seekLen - seek.length - 2))]);
assert.strictEqual(seek.length, seekLen);
const segment = el('Segment', body(seek));
const file = Buffer.concat([ebmlHead(), segment]);
const headEnd = file.length - chapters.length - 2000;
const r = readMatroskaHeader([{ offset: 0, bytes: file.subarray(0, headEnd) }, { offset: file.length - chapters.length - 10, bytes: file.subarray(file.length - chapters.length - 10) }]);
assert.strictEqual(r.editions.length, 1);
assert.strictEqual(r.editions[0].chapters[0].uid, '5');
assert.deepStrictEqual(r.unreached, []);
const linearOnly = readMatroskaHeader([{ offset: 0, bytes: file.subarray(0, headEnd) }, { offset: file.length - chapters.length - 10, bytes: file.subarray(file.length - chapters.length - 10) }]);
assert.strictEqual(linearOnly.editions[0].uid, '9', 'found through the SeekHead, past the Cluster');
const headOnly = readMatroskaHeader([{ offset: 0, bytes: file.subarray(0, headEnd) }]);
assert.deepStrictEqual(headOnly.unreached, ['Chapters']);
});
// ---- the ratchet: untrusted bytes refused, never read past ----
t('refuses bytes that are not EBML', () => {
assert.throws(() => readMatroskaHeader(Buffer.from('RIFF....WAVEfmt ')), MatroskaError);
});
t('refuses an EBML doc type that is not matroska or webm', () => {
assert.throws(() => readMatroskaHeader(Buffer.concat([ebmlHead('mide'), el('Segment')])), /doc type/);
});
t('refuses a child whose size runs past its parent', () => {
const bad = Buffer.concat([ebmlHead(), hex(E.Segment), vsize(8), hex(E.Info), vsize(200), Buffer.alloc(5)]);
assert.throws(() => readMatroskaHeader(bad), /past its parent/);
});
t('refuses a child that runs past its parent inside a header element', () => {
const info = Buffer.concat([hex(E.Info), vsize(6), hex(E.Duration), vsize(8), f64(1).subarray(0, 3), Buffer.alloc(20)]);
assert.throws(() => readMatroskaHeader(Buffer.concat([ebmlHead(), el('Segment', info)])), /runs past its parent/);
});
t('refuses an unknown size inside a header element', () => {
const info = el('Info', hex(E.Title), hex('01FFFFFFFFFFFFFF'), s('x'));
assert.throws(() => readMatroskaHeader(Buffer.concat([ebmlHead(), el('Segment', info)])), /unknown size inside/);
});
t('refuses an invalid variable-length integer (a zero first byte)', () => {
assert.throws(() => readMatroskaHeader(Buffer.concat([ebmlHead(), hex(E.Segment), Buffer.from([0x00, 0x01])])), MatroskaError);
});
t('refuses nesting deeper than the bound', () => {
let x = el('ChapterDisplay', el('ChapString', s('x')));
for (let i = 0; i < 40; i++) x = el('ChapterAtom', x);
const b = Buffer.concat([ebmlHead(), el('Segment', el('Chapters', el('EditionEntry', x)))]);
assert.throws(() => readMatroskaHeader(b), /nesting deeper/);
});
t('the same bytes read twice give the same facts (a pure function)', () => {
assert.deepStrictEqual(readMatroskaHeader(film()), readMatroskaHeader(film()));
});
t('a 64-bit UID is kept whole, digit for digit', () => {
const big = Buffer.from('8000000000000001', 'hex'); // 2^63 + 1: not representable as a JS number
const b = Buffer.concat([ebmlHead(), el('Segment', el('Tracks', el('TrackEntry', el('TrackNumber', u(1)), el('TrackUID', big), el('TrackType', u(2)))))]);
assert.strictEqual(readMatroskaHeader(b).tracks[0].uid, '9223372036854775809');
});
t('a string padded with NUL bytes reads up to the first NUL', () => {
const b = Buffer.concat([ebmlHead(), el('Segment', el('Tracks', el('TrackEntry', el('TrackNumber', u(1)), el('TrackType', u(2)), el('CodecID', Buffer.from('A_AAC\0\0\0', 'latin1')))))]);
assert.strictEqual(readMatroskaHeader(b).tracks[0].codec_id, 'A_AAC');
});
t('Void and CRC-32 padding is skipped', () => {
const b = Buffer.concat([ebmlHead(), el('Segment', el('Void', Buffer.alloc(3)), el('Info', el('Void', Buffer.alloc(1)), el('Duration', f64(5))))]);
assert.strictEqual(readMatroskaHeader(b).duration_ns, 5 * 1000000);
});
// ---- the oracle: ffmpeg writes, ffprobe reads, the reader must agree (skipped and said so when absent) ----
const { spawnSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const have = (bin) => spawnSync(bin, ['-version'], { encoding: 'utf8' }).status === 0;
function probe(file) {
const p = spawnSync('ffprobe', ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', '-show_chapters', file], { encoding: 'utf8' });
if (!p.stdout || !p.stdout.trim()) throw new Error(p.stderr);
return JSON.parse(p.stdout);
}
if (have('ffmpeg') && have('ffprobe')) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mkvh-'));
const meta = path.join(dir, 'ch.txt');
fs.writeFileSync(meta, ';FFMETADATA1\n[CHAPTER]\nTIMEBASE=1/1000\nSTART=0\nEND=1000\ntitle=Opening\n[CHAPTER]\nTIMEBASE=1/1000\nSTART=1000\nEND=2000\ntitle=Close\n');
const out = path.join(dir, 'oracle.mkv');
const mk = spawnSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-f', 'lavfi', '-i', 'color=c=black:s=64x48:d=2:r=10',
'-i', meta, '-map', '1:v', '-map', '0:a', '-map_chapters', '2', '-c:v', 'mpeg4', '-c:a', 'pcm_s16le', '-metadata:s:a:0', 'language=fre',
'-disposition:a:0', 'default+hearing_impaired+original', '-disposition:v:0', '0', out], { encoding: 'utf8' });
if (mk.status !== 0) { skip('ffprobe oracle', `ffmpeg could not write the fixture: ${mk.stderr.trim()}`); }
else {
const p = probe(out); let r = null;
t('oracle: reads the ffmpeg-written file (64-bit UIDs kept whole as strings)', () => {
r = readMatroskaHeader(fs.readFileSync(out));
assert.ok(/^[0-9]+$/.test(r.tracks[0].uid));
});
if (r === null) r = { duration_ns: NaN, tracks: [{ flags: {} }, { flags: {} }], editions: [] };
t('oracle: running time agrees with ffprobe to the millisecond', () => {
assert.ok(Math.abs(r.duration_ns / 1e9 - Number(p.format.duration)) < 0.001, `${r.duration_ns / 1e9} vs ${p.format.duration}`);
});
t('oracle: the track list and codec kinds agree with ffprobe', () => {
assert.deepStrictEqual(r.tracks.map((x) => x.kind), p.streams.map((x) => x.codec_type));
});
t('oracle: languages and the six flags agree with ffprobe', () => {
const a = r.tracks[1]; const ps = p.streams[1];
assert.strictEqual(a.language, ps.tags.language);
assert.strictEqual(a.flags.default, ps.disposition.default === 1);
assert.strictEqual(a.flags.hearing_impaired, ps.disposition.hearing_impaired === 1);
assert.strictEqual(a.flags.original, ps.disposition.original === 1);
assert.strictEqual(r.tracks[0].flags.default, p.streams[0].disposition.default === 1);
});
t('oracle: chapters agree with ffprobe (start, end, title)', () => {
const mine = r.editions.flatMap((e) => e.chapters).map((c) => [c.start_ns / 1e9, c.end_ns / 1e9, c.titles[0] && c.titles[0].title]);
const theirs = p.chapters.map((c) => [Number(c.start_time), Number(c.end_time), c.tags && c.tags.title]);
assert.deepStrictEqual(mine, theirs);
});
// The hand-built film carries IDs ffmpeg 6.1 never writes. ffprobe 6.1 reads back FlagOriginal, FlagVisualImpaired,
// FlagForced, ChapterTimeStart/End and ChapString, so those IDs are witnessed. It does NOT read LanguageBCP47
// (0x22B59D), FlagTextDescriptions (0x55AD) or ChapLanguageBCP47 (0x437D): it reports the ISO code and no
// descriptions disposition. Those three rest on RFC 9559 and on their witnessed neighbours (0x22B59C; 0x55AA-AC, AE),
// and the run below says so instead of claiming the oracle covered them.
const fpath = path.join(dir, 'film.mkv'); fs.writeFileSync(fpath, film());
const fp = probe(fpath); const fr = readMatroskaHeader(film());
t('oracle: ffprobe reads the hand-built film the same way where it reads at all (original, visual-impaired, forced, chapters)', () => {
assert.strictEqual(fp.streams[2].tags.language, fr.tracks[2].language_iso639_2, 'ffprobe 6.1 reports the ISO code');
assert.strictEqual(fp.streams[2].disposition.visual_impaired, 1);
assert.strictEqual(fp.streams[3].disposition.forced, 1);
assert.strictEqual(fp.streams[1].disposition.original, 1);
assert.strictEqual(fp.streams[1].disposition.default, 1);
assert.strictEqual(fp.streams[2].disposition.default, 0);
const visible = fr.editions.flatMap((e) => e.chapters).filter((c) => !c.hidden).map((c) => [c.start_ns / 1e9, c.titles[0].title]);
assert.deepStrictEqual(fp.chapters.map((c) => [Number(c.start_time), c.tags.title]), visible);
});
const wit = fp.streams[2].tags.language === 'pt-BR' && fp.streams[2].disposition.descriptions === 1;
console.log(wit ? 'WITNESS LanguageBCP47 + FlagTextDescriptions read back by this ffprobe' :
'UNWITNESSED by this ffprobe: LanguageBCP47 0x22B59D, FlagTextDescriptions 0x55AD, ChapLanguageBCP47 0x437D (RFC 9559; neighbours witnessed)');
fs.rmSync(dir, { recursive: true, force: true });
}
} else {
skip('ffprobe oracle (5 checks)', 'ffmpeg or ffprobe is not on this machine; the hand-built vectors still ran');
}
console.log(`matroska-header: ${passed} passed, ${failed} failed, ${skipped} skipped`);
process.exit(failed ? 1 : 0);