Reading Boxes
The readIsoBoxes function reads boxes from a buffer and returns an array of boxes. To read the fields of a box, provide a reader function for that box type. The result has two kinds of boxes:
- A box object has a
typefield and the fields of the box. A reader returns a box object. - A raw box is a box with no reader:
{ type, bytes, headerSize }.typeis the four-character code of the box.bytesis the complete box, with its header. The body of the box isbox.bytes.subarray(box.headerSize). A rawuuidbox also hasuserType, the 16 bytes of theusertypefield. No other raw box has that field.
The bytes of a raw box share memory with the input.
Every box has its four-character code in type. A test such as box.type === "tfdt" matches a box object and a raw box, so the test does not narrow the box. Narrow a box with isIsoBoxType, which returns false for a raw box. A box with no reader is a raw box, so add the reader of a box type before you narrow to that type. The test "bytes" in box narrows a box to a raw box.
NOTE
The function reads container boxes automatically, so they do not need a reader function. The CONTAINERS constant lists the container box types that the function reads automatically. Each container type also has a named reader, such as readMoov and readMoof. A container reader in the readers map is optional and does not change the result.
Using default config
If tree shaking is not a concern, use createDefaultReaderConfig(). It returns a configuration with every available reader except the container readers:
import { createDefaultReaderConfig, readIsoBoxes } from "@svta/cml-iso-bmff";
const buffer = await fetch("https://example.com/bbb.mp4").then((r) =>
r.arrayBuffer(),
);
const boxes = readIsoBoxes(buffer, createDefaultReaderConfig());Each call of createDefaultReaderConfig() returns a new configuration object. A player can create the configuration once and pass it to every read.
A minor release can add a reader to the default configuration. See Changes in a minor release.
readIsoBoxes accepts an ArrayBuffer and any view, such as a Uint8Array, a DataView, or a Node.js Buffer. The function does not copy the data. Pass the view itself. Do not pass the buffer property of a view, because that buffer can contain other data.
Using specific readers
For optimal bundle size with tree shaking, import only the readers you need:
import { readFtyp, readIsoBoxes } from "@svta/cml-iso-bmff";
const buffer = await fetch("https://example.com/bbb.mp4").then((r) =>
r.arrayBuffer(),
);
const boxes = readIsoBoxes(buffer, {
readers: {
ftyp: readFtyp,
},
});Optional fields
A box object from a built-in reader has every key of its type. A field that the flags, the version, or the size of the box excludes is undefined. To check for a field, test its value for undefined, or test the flags or the version. Do not test the key with in or Object.keys. The key is always present.
Reading one box
seekIsoBox finds a box by its path and returns a read cursor for that box. The function reads no other box. Pass the cursor to the reader of the box:
import { readTfdt, seekIsoBox } from "@svta/cml-iso-bmff";
const cursor = seekIsoBox(buffer, ["moof", "traf", "tfdt"]);
const time = cursor ? readTfdt(cursor).baseMediaDecodeTime : null;The function returns null for a missing box. By default, the function also returns null for a truncated box. If your code reads partial data, a null result means that the box can be in the next bytes. The third argument takes the int64 option and the truncated option, as readIsoBoxes does. See Throwing for an incomplete box.
If a box of a type has no box at the rest of the path, seekIsoBox searches the next box of that type. So the path ["moov", "trak", "edts"] finds the edts box of the second track if the first track has none. For a missing box, the function searches every box of each type in the path.
seekIsoBox treats the body of each box in the path as a list of boxes. Some boxes have fields before their child boxes, such as meta, stsd, and the sample entries. For such a box, move the position of the cursor past the fields, then call seekIsoBox again with the cursor. The second call does not move the first cursor:
import { seekIsoBox } from "@svta/cml-iso-bmff";
const stsd = seekIsoBox(buffer, ["moov", "trak", "mdia", "minf", "stbl", "stsd"]);
if (stsd) {
stsd.pos += 8; // version, flags, and entry_count
const avc1 = seekIsoBox(stsd, ["avc1"]);
console.log(avc1 && avc1.end - avc1.start);
}Reading every box at a path
seekIsoBoxes finds every box at a path and returns an array with a read cursor for each box. The array has the boxes in the order of the data. The function decodes no box. Use it for a list of boxes, such as the tfdt box of every fragment:
import { readTfdt, seekIsoBoxes } from "@svta/cml-iso-bmff";
const times = seekIsoBoxes(buffer, ["moof", "traf", "tfdt"]).map(
(cursor) => readTfdt(cursor).baseMediaDecodeTime,
);The function searches every box of each type in the path. So the path ["moov", "trak"] returns a cursor for each track. The first cursor of the array is the box that seekIsoBox returns. Pass one of the cursors to seekIsoBox or to seekIsoBoxes to search inside that track:
import { readMdhd, readTkhd, seekIsoBox, seekIsoBoxes } from "@svta/cml-iso-bmff";
for (const trak of seekIsoBoxes(initSegment, ["moov", "trak"])) {
const tkhd = seekIsoBox(trak, ["tkhd"]);
const mdhd = seekIsoBox(trak, ["mdia", "mdhd"]);
if (tkhd && mdhd) {
console.log(readTkhd(tkhd).trackId, readMdhd(mdhd).timescale);
}
}The result is an empty array if the data has no box at the path. seekIsoBoxes also accepts a read cursor in place of the data. The search then starts at the position of that cursor, and the function does not move that cursor. The third argument takes the int64 option. For a box with fields before its child boxes, move the position of a cursor past the fields first, as for seekIsoBox.
The search of a list of boxes stops before a truncated box. If that list is the body of a box, the search continues after that box. By default, a truncated box gives a shorter array and no error. If your code reads partial data, a missing cursor means that the box can be in the next bytes. To detect a truncated box, pass truncated: 'throw'. See Throwing for an incomplete box.
seekIsoBoxes creates no object for a box that is not at the path. To read boxes of more than one type from one list, use iterateChildBoxes.
Stepping over boxes
nextIsoBox returns the type of the box at the position of a cursor and moves the position past that box. The function reads no field of the box. The bytes from the old position to the new position are the complete box:
import { createIsoBoxReadCursor, nextIsoBox } from "@svta/cml-iso-bmff";
const cursor = createIsoBoxReadCursor(buffer);
let start = cursor.pos;
let type = nextIsoBox(cursor);
while (type) {
console.log(type, cursor.pos - start); // the type and the size of each box
start = cursor.pos;
type = nextIsoBox(cursor);
}The function returns null at the end of the cursor. By default, the function also returns null before a truncated box. The position then stays at the first byte of that box.
readIsoBoxSize returns the size of the box at a position of a DataView. Use it for a loop that has no read cursor:
import { readIsoBoxSize } from "@svta/cml-iso-bmff";
const view = new DataView(buffer);
let at = 0;
let size = readIsoBoxSize(view, at, view.byteLength);
while (size) {
console.log(at, size); // the position and the size of each box
at += size;
size = readIsoBoxSize(view, at, view.byteLength);
}The function returns 0 at the end of the data and for a truncated box. By default, the header of a uuid box includes the 16 bytes of usertype, as in readIsoBoxes. A uuid box with a size below that header is truncated. To get the size of that box, pass true as the fourth argument.
Reading some boxes of a list
iterateChildBoxes yields the type and a read cursor for each box from the position of a cursor to its end. The function reads no field of a box and does not move the input cursor. Each cursor of the result is a new object, with start at the box header, pos after the header, and end after the box. Use the function to read some boxes of a list, or to read the position of a box with its content. The function also reaches a box that seekIsoBox does not find, such as the second traf box of a moof box:
import {
iterateChildBoxes,
readTfhd,
readTrun,
seekIsoBox,
} from "@svta/cml-iso-bmff";
const moof = seekIsoBox(buffer, ["moof"]);
if (moof) {
for (const [type, traf] of iterateChildBoxes(moof)) {
if (type !== "traf") {
continue;
}
for (const [childType, child] of iterateChildBoxes(traf)) {
if (childType === "tfhd") {
console.log(readTfhd(child).trackId);
} else if (childType === "trun") {
// The position of the trun box, and its number of samples.
const trun = readTrun(child);
console.log(child.start, child.end, trun.samples ? trun.samples.length : trun.sampleCount);
}
}
}
}By default, the iteration stops before a truncated box. The cursors have the readers map, the int64 option, and the truncated option of the input. So readChildBoxes(child) reads the child boxes of a container with the same configuration. The function creates a cursor for each box. In a loop that reads no content, nextIsoBox steps over the boxes and creates no cursor.
Extending a built-in reader
A custom reader can call a built-in reader and add fields to the result. In the result of readIsoBoxes, the box has the built-in type. The loop narrows the box with isIsoBoxType, then casts the box to the result type of the reader.
HLS and DASH streams contain ID3 timed metadata in emsg boxes with the scheme https://aomedia.org/emsg/ID3. The built-in reader returns messageData as bytes. This reader decodes the frames once, when the box is read:
import { ID3_SCHEME_ID_URI, getId3Frames, type Id3Frame } from "@svta/cml-id3";
import {
isIsoBoxType,
readEmsg,
readIsoBoxes,
type IsoBoxReadCursor,
} from "@svta/cml-iso-bmff";
const readEmsgWithId3 = (cursor: IsoBoxReadCursor) => {
const emsg = readEmsg(cursor);
const frames: Id3Frame[] =
emsg.schemeIdUri === ID3_SCHEME_ID_URI
? getId3Frames(emsg.messageData)
: [];
return { ...emsg, frames };
};
const segment = await fetch("https://example.com/segment.m4s").then((r) =>
r.arrayBuffer(),
);
const boxes = readIsoBoxes(segment, {
readers: {
emsg: readEmsgWithId3,
},
});
type EmsgWithId3 = ReturnType<typeof readEmsgWithId3>;
for (const box of boxes) {
if (isIsoBoxType("emsg", box)) {
console.log((box as EmsgWithId3).frames);
}
}A byte field such as messageData is a view over the input data. The field shares memory with that data and is not a copy. To keep the bytes after your code releases or changes the input, call slice() on the field.
Writing a custom reader
The package parses no codec configuration box, such as avcC, hvcC, or esds. The boxes field of a sample entry, such as avc1, holds such a box as a raw box with its bytes. To read the fields of the box, write a custom reader for its box type.
The readers map takes a reader under a key of IsoBoxMap. For a box type that the package does not name, add the type to IsoCustomBoxMap first. readIsoBoxes and the write functions then have that box type.
A reader takes a read cursor and the box type, and returns the box object with its type field. A field function reads one field at cursor.pos and moves the position past the field, such as readUint32 or readFourCc:
import {
findIsoBox,
isIsoBoxType,
readFourCc,
readIsoBoxes,
readUint16,
readUint32,
type IsoBoxReadCursor,
type IsoInt64,
} from "@svta/cml-iso-bmff";
// A box type that the package does not name.
type AbcdBox = { type: "abcd"; brand: string; count: number; flags: number };
// Add the box type to the map of custom box types.
declare module "@svta/cml-iso-bmff" {
interface IsoCustomBoxMap {
abcd: AbcdBox;
}
}
const readAbcd = (cursor: IsoBoxReadCursor<IsoInt64>): AbcdBox => ({
type: "abcd",
brand: readFourCc(cursor),
count: readUint32(cursor),
flags: readUint16(cursor),
});
const boxes = readIsoBoxes(buffer, { readers: { abcd: readAbcd } });
// The guard narrows the box to `AbcdBox`.
console.log(findIsoBox(boxes, (box) => isIsoBoxType("abcd", box))?.brand);The cursor follows these rules:
cursor.startis the first byte of the box header, andcursor.endis the first byte after the box. The cursor of a reader starts at the first byte after the header. For auuidbox, the cursor starts at the first byte ofusertype. Readinguuidboxes shows the reader of that box.- A read past
cursor.endthrows aRangeError, so a reader cannot read the bytes of the next box. A reader can stop before the end of its box. - A length is an integer of 0 or more. Another length throws a
RangeError. - The bytes that remain are
cursor.end - cursor.pos. To skip bytes, add tocursor.pos. - A reader of a box with child boxes reads them with
readChildBoxes(cursor). The readers of the configuration then apply to the child boxes. readIsoBoxesuses one cursor for every box. A reader must not keep the cursor after it returns. A reader that needs bytes later keeps the result ofreadBytes.- The declaration of
IsoCustomBoxMapapplies to every file of the program. Two declarations of one box type need the same type. - Do not declare
uuidinIsoCustomBoxMap. Declare the box types ofuuidinIsoCustomUuidBoxMap. - A minor release can add a box type to
IsoBoxMap. See Changes in a minor release. - A reader under a key returns the box type of that key. The reader can add fields. A reader with another result type is a compile error.
An error of a reader reaches the caller of readIsoBoxes. See Incomplete boxes.
readIsoBoxes finds a reader by the exact type and by the trimmed type. A reader under the key url reads the "url " box. The box type has a trailing space.
IsoBoxMap names the sample entry types of these codecs: ac-3, ac-4, av01, dav1, dva1, dvav, dvh1, dvhe, ec-3, fLaC, Opus, and vp09. The default configuration reads these types with readAudioSampleEntry and readVisualSampleEntry. In a readers map of your own, add the function under the key of the sample entry type, such as { "ec-3": readAudioSampleEntry }.
Reading uuid boxes
Every uuid box has the box type uuid. The 16 bytes of usertype select the format of the body. The readers map has one key for all uuid boxes. createUuidReader creates the reader of that key from a map of user types.
Declare each user type in IsoCustomUuidBoxMap. A key is a UUID in lowercase hexadecimal digits with hyphens. The box type has type: "uuid" and the key as its userType field. The reader of a user type starts after the 16 bytes of usertype:
import {
createUuidReader,
isIsoBoxType,
readIsoBoxes,
readTfdt,
readUint24,
readUint8,
readWideUint,
type IsoBoxReadCursor,
} from "@svta/cml-iso-bmff";
// The tfxd box of Smooth Streaming.
const TFXD = "6d1d9b05-42d5-44e6-80e2-141daff757b2";
type TfxdBox = {
type: "uuid";
userType: typeof TFXD;
version: number;
flags: number;
fragmentAbsoluteTime: number;
fragmentDuration: number;
};
// Add the user type to the map of uuid box types.
declare module "@svta/cml-iso-bmff" {
interface IsoCustomUuidBoxMap {
[TFXD]: TfxdBox;
}
}
const readTfxd = (cursor: IsoBoxReadCursor, userType: typeof TFXD): TfxdBox => {
const version = readUint8(cursor);
const flags = readUint24(cursor);
const size = version === 1 ? 8 : 4;
return {
type: "uuid",
userType,
version,
flags,
fragmentAbsoluteTime: readWideUint(cursor, size),
fragmentDuration: readWideUint(cursor, size),
};
};
const boxes = readIsoBoxes(buffer, {
readers: { tfdt: readTfdt, uuid: createUuidReader({ [TFXD]: readTfxd }) },
});
for (const box of boxes) {
// The guard excludes a raw box, and the test of `userType` narrows the box to `TfxdBox`.
if (isIsoBoxType("uuid", box) && box.userType === TFXD) {
console.log(box.fragmentDuration);
}
}The reader follows these rules:
- For a user type with no reader, the reader returns
undefined.readIsoBoxesthen returns a raw box with theuserTypefield. createUuidReaderthrows aRangeErrorfor a key that is not a UUID in lowercase hexadecimal digits with hyphens.- The declaration of
IsoCustomUuidBoxMapapplies to every file of the program. Two declarations of one user type need the same type. - A package that reads its own
uuidboxes can export its map of user types. A caller then joins the maps of several packages in one call, as increateUuidReader({ ...readersA, ...readersB }). Do not callcreateUuidReaderonce for each package. The readers map has oneuuidkey, so one reader replaces the other.
Incomplete boxes
A box is incomplete when the data ends inside the header or inside the body of the box. A box is also incomplete when its size is below the size of its header. readIsoBoxes stops before the first incomplete box and returns the boxes before that box. The function does not throw for an incomplete box.
readIsoBoxes returns no position. To continue a read with more data, read with a cursor. After readChildBoxes or nextIsoBox stops before an incomplete box, the position of the cursor is the first byte of that box. Keep the bytes from that position, add the new bytes, and read again:
import { createIsoBoxReadCursor, readChildBoxes } from "@svta/cml-iso-bmff";
const cursor = createIsoBoxReadCursor(buffer);
const boxes = readChildBoxes(cursor);
// The first incomplete box starts at the first byte of `rest`.
const rest = buffer.slice(cursor.pos);The position has two limits:
- The position applies to the boxes of one level. If a child box of a complete box is incomplete, the reader of the parent box stops before the child box. The read then continues after the parent box, and the position does not show the child box.
- The position does not separate an incomplete box from a box with a bad size. A wrong
sizevalue above the remaining data stops the read at the same position. More data then does not complete the box.
A box with a reader in the configuration and a body shorter than its fields is not an incomplete box. readIsoBoxes then throws a RangeError and returns no boxes. A box that is deeper than 128 levels also throws a RangeError. If the data comes from the network, call readIsoBoxes inside a try block.
The size of a box includes its header. The header has 8 bytes, or 16 bytes when size is 1 and a largesize field follows (ISO/IEC 14496-12, clause 4.2). The header of a uuid box has 16 more bytes for the usertype field. A size of 0 is valid and means that the box extends to the end of the data.
The same rule applies to the child boxes of a container and of a sample entry. Some QuickTime files have 4 zero bytes after the last child box of a udta box. Other QuickTime files have those bytes at the end of an avc1 or hvc1 sample entry. A box header has at least 8 bytes, so the reader stops before those bytes. The box object has the child boxes and no field for those bytes.
A writer builds a container or a sample entry from the child boxes of the box object. A write therefore omits those bytes. The written box is shorter than the source box by those bytes. If the moov box precedes the mdat box, the chunk offsets of the written file then address other bytes. The mfraSize field of an mfro box has the same limit. See Writing a changed mfra box.
Throwing for an incomplete box
A validator has complete data, so an incomplete box means that the data is malformed. Pass truncated: 'throw' in the configuration. The read functions then throw a RangeError before an incomplete box. The read functions are readIsoBoxes, readChildBoxes, nextIsoBox, iterateChildBoxes, seekIsoBox, and seekIsoBoxes. Each cursor that these functions create has the option of its input:
import { createIsoBoxReadCursor, seekIsoBoxes } from "@svta/cml-iso-bmff";
const cursor = createIsoBoxReadCursor(buffer, { truncated: "throw" });
try {
const truns = seekIsoBoxes(cursor, ["moof", "traf", "trun"]);
console.log(truns.length);
} catch (error) {
if (!(error instanceof RangeError)) throw error;
console.log(error.message); // "Truncated box at 112: size 4 is below the header size"
}The message has the position of the box and one of two causes. Either the size is below the header size, or the data ends inside the box. The default value of the option is 'stop', the behavior of the sections above.
The option has four limits:
- Do not use the option for partial data. A box that the download has not finished is an incomplete box, so the read throws for that box.
seekIsoBoxstops at the first box at the path. The function does not throw for an incomplete box after that box. To check every box of each list in the path, useseekIsoBoxes.readChildBoxeswith a count does not read the bytes after the last box of the count. The readers ofstsdanddrefread their entries with a count.- The 4 zero bytes after the last child box of a QuickTime
udtabox or sample entry are an incomplete box. So the read throws for those bytes.
Resolving the samples of a trun box
The trun box omits a sample field that the tfhd box or the trex box supplies as a default. resolveTrunSamples returns one object for each sample with the resolved duration, size, flags, and composition time offset. A field of the trun box has priority, then the default of the tfhd box, then the default of the trex box. firstSampleFlags replaces the default flags of the first sample only. A missing composition time offset is 0. A trun box with none of the flags 0x000100 to 0x000800 has sampleCount and no samples. For that box, every sample takes the defaults:
import {
findIsoBox,
isIsoBoxType,
readIsoBoxes,
readTfhd,
readTrex,
readTrun,
resolveTrunSamples,
} from "@svta/cml-iso-bmff";
const readers = { tfhd: readTfhd, trex: readTrex, trun: readTrun };
const init = readIsoBoxes(initSegment, { readers });
const segment = readIsoBoxes(buffer, { readers });
const trex = findIsoBox(init, (box) => isIsoBoxType("trex", box));
const tfhd = findIsoBox(segment, (box) => isIsoBoxType("tfhd", box));
const trun = findIsoBox(segment, (box) => isIsoBoxType("trun", box));
if (trun && trex) {
const samples = resolveTrunSamples(trun, tfhd, trex);
const duration = samples.reduce((sum, sample) => sum + sample.sampleDuration, 0);
console.log(duration);
}The trex box is the one of the track of the fragment, with tfhd.trackId === trex.trackId. The function does not check the track. With a trex box, every field of the result is a number. With no trex box, a field is undefined when no box has a value for it.
The function reads only defaultSampleDuration, defaultSampleSize, and defaultSampleFlags of the two boxes. Each parameter also accepts an object with only those fields. The type of such an object is TrackRunSampleDefaults. For a number in every field of the result, the trex object needs all three fields. Use such an object for defaults that your code stores without the boxes:
import {
findIsoBox,
isIsoBoxType,
readIsoBoxes,
readTfhd,
readTrun,
resolveTrunSamples,
type TrackRunSampleDefaults,
} from "@svta/cml-iso-bmff";
const trackDefaults: Required<TrackRunSampleDefaults> = {
defaultSampleDuration: 3000,
defaultSampleSize: 0,
defaultSampleFlags: 0x01010000,
};
const segment = readIsoBoxes(buffer, { readers: { tfhd: readTfhd, trun: readTrun } });
const tfhd = findIsoBox(segment, (box) => isIsoBoxType("tfhd", box));
const trun = findIsoBox(segment, (box) => isIsoBoxType("trun", box));
if (trun) {
const samples = resolveTrunSamples(trun, tfhd, trackDefaults);
const duration = samples.reduce((sum, sample) => sum + sample.sampleDuration, 0);
console.log(duration);
}Reading the totals of a trun box
A player often needs the number of samples and the duration of a track fragment, and no field of one sample. readTrunTotals reads the number of samples of a trun box and the sum of the sample durations. The function creates no object for each sample. Find each trun box with seekIsoBoxes, then pass the cursor to the function:
import { readTfhd, readTrex, readTrunTotals, seekIsoBox, seekIsoBoxes } from "@svta/cml-iso-bmff";
const trex = seekIsoBox(initSegment, ["moov", "mvex", "trex"]);
const trexDuration = trex ? readTrex(trex).defaultSampleDuration : 0;
const traf = seekIsoBox(buffer, ["moof", "traf"]);
if (traf) {
const tfhd = seekIsoBox(traf, ["tfhd"]);
const defaultDuration = (tfhd ? readTfhd(tfhd).defaultSampleDuration : undefined) ?? trexDuration;
let duration = 0;
for (const cursor of seekIsoBoxes(traf, ["trun"])) {
const totals = readTrunTotals(cursor);
// A box with no sample durations takes the default for each sample.
duration += totals.totalSampleDuration ?? totals.sampleCount * defaultDuration;
}
console.log(duration);
}The total uses only the values of the sample records. totalSampleDuration is undefined for a box with no flag 0x000100. In that case, your code applies the default of the tfhd box. If the tfhd box has no default, your code applies the default of the trex box. The trex box is the one with the trackId of the tfhd box. The result is not a box object, so the function is not a reader of the readers map. To read a field of one sample, use readTrun and resolveTrunSamples.
Reading 64-bit fields
The built-in readers return every integer field as a number. A number holds integers up to 2^53 - 1 exactly. A 64-bit field can exceed that limit, and the reader then returns a rounded value. One example is baseMediaDecodeTime in a version 1 tfdt box with a 10 MHz timescale and a wall-clock origin.
The int64 option of the configuration takes a function that reads every 64-bit field of the built-in readers. The package exports two functions for the option. readInt64AsBigInt returns the exact value as a bigint. createInt64OverflowReader keeps the number and reports a rounded value.
The option applies to these fields:
| Box | Fields |
|---|---|
tfdt | baseMediaDecodeTime |
sidx | earliestPresentationTime, firstOffset |
tfra | time and moofOffset of each entry |
prft | mediaTime |
emsg | presentationTime |
mehd | fragmentDuration |
mvhd, mdhd, tkhd | creationTime, modificationTime, duration |
elst | segmentDuration and mediaTime of each entry |
tfhd | baseDataOffset |
co64 | each entry of chunkOffset |
Exact values as bigint
Pass readInt64AsBigInt as the int64 option. The built-in readers then return each field of the table as a bigint. The result type of readIsoBoxes follows the option:
import {
createDefaultReaderConfig,
isIsoBoxType,
readInt64AsBigInt,
readIsoBoxes,
} from "@svta/cml-iso-bmff";
const boxes = readIsoBoxes(
buffer,
createDefaultReaderConfig({ int64: readInt64AsBigInt }),
);
for (const box of boxes) {
if (isIsoBoxType("sidx", box)) {
// earliestPresentationTime is a bigint. The division of two bigints
// drops the fraction, so add the remainder as a number.
const scale = BigInt(box.timescale);
const seconds =
Number(box.earliestPresentationTime / scale) +
Number(box.earliestPresentationTime % scale) / box.timescale;
console.log(seconds);
}
}Pass the option as the argument of createDefaultReaderConfig. The readers of the returned configuration have the types of that option. If you add readInt64AsBigInt to the result of createDefaultReaderConfig() afterward, the code does not compile.
The option works the same way with specific readers:
import {
findIsoBox,
isIsoBoxType,
readInt64AsBigInt,
readIsoBoxes,
readTfdt,
} from "@svta/cml-iso-bmff";
const boxes = readIsoBoxes(buffer, {
int64: readInt64AsBigInt,
readers: {
tfdt: readTfdt,
},
});
// A tfdt box is inside a traf box, inside a moof box.
const tfdt = findIsoBox(boxes, (box) => isIsoBoxType("tfdt", box));
// baseMediaDecodeTime is a bigint.
console.log(tfdt?.baseMediaDecodeTime);Each field has one type for every version of its box. A version 0 tfdt box stores baseMediaDecodeTime in 32 bits. The reader returns that field as a bigint too, so your code does not test version. The option also applies to the child boxes of a container.
readInt64AsBigInt needs BigInt and the getBigUint64 method of DataView, and does not test for them. On a runtime without them, a read fails with the error of the runtime. If your code supports such a runtime, test typeof DataView.prototype.getBigUint64 === "function" before you pass the function. The test is false on a runtime without BigInt too.
JSON.stringify throws a TypeError for a bigint. To serialize a box with bigint fields, pass a replacer function that converts each bigint to a string.
Reporting a rounded value
If your code keeps number fields, use createInt64OverflowReader. The function takes a callback and returns a function for the int64 option. When a 64-bit value is outside the safe integer range, the callback receives a RangeError. If the callback returns, the read continues with the rounded value. If the callback throws, the read stops with that error.
A version 1 mvhd, tkhd, or mdhd box can have a duration with all bits set. ISO/IEC 14496-12 uses that value for a duration that cannot be determined. The callback receives a RangeError for that value too, and the field reads as 2 ** 64. That report does not mean that the file is damaged. If your code reads such boxes, do not throw from the callback.
import {
createInt64OverflowReader,
readIsoBoxes,
readTfdt,
} from "@svta/cml-iso-bmff";
const boxes = readIsoBoxes(buffer, {
int64: createInt64OverflowReader((error) => console.warn(error.message)),
readers: {
tfdt: readTfdt,
},
});The types of the result do not change, and the function does not need BigInt. The function checks the fields of the table above. The function does not check a field that a custom reader reads with readUint32 and no readWideUint. A configuration takes one function for the option. The configuration selects bigint fields or the report, not both.
Custom readers and the option
A custom reader of the type (cursor: IsoBoxReadCursor) => ... works with no option and with createInt64OverflowReader. With readInt64AsBigInt, that reader is a compile error, because the cursor then has bigint fields. Use one of two forms:
- A reader that reads no 64-bit field takes
IsoBoxReadCursor<IsoInt64>. That type accepts the cursor of every configuration. - A reader that follows the option is generic. That reader reads each 64-bit field with
readWideUintorreadWideInt.
readWideUint and readWideInt take the size of the field in bytes, 4 or 8. With no option, they return a number. With the option, they return the result of the int64 function:
import {
readInt64AsBigInt,
readIsoBoxes,
readUint24,
readUint8,
readWideUint,
type IsoBoxReadCursor,
type IsoInt64,
} from "@svta/cml-iso-bmff";
const readTfdtWide = <V extends IsoInt64>(cursor: IsoBoxReadCursor<V>) => {
const version = readUint8(cursor);
const flags = readUint24(cursor);
const baseMediaDecodeTime = readWideUint(cursor, version === 1 ? 8 : 4);
return {
type: "tfdt" as const,
version,
flags,
baseMediaDecodeTime,
source: "custom",
};
};
// baseMediaDecodeTime is a bigint in this result.
const boxes = readIsoBoxes(buffer, {
int64: readInt64AsBigInt,
readers: {
tfdt: readTfdtWide,
},
});
// A readers map in a variable works the same way.
const readers = { tfdt: readTfdtWide };
const stored = readIsoBoxes(buffer, { int64: readInt64AsBigInt, readers });The result type follows the int64 option, not the readers map. With isIsoBoxType("tfdt", box), the box has the built-in type with bigint fields. To read the source field, cast the box to ReturnType<typeof readTfdtWide<bigint>>.
TypeScript reads the type of the int64 function to select the type of the fields. Pass a named function, such as readInt64AsBigInt. For a function that you write inside the configuration object, give the cursor parameter the type IsoBoxReadCursor<IsoInt64>. Without that type, a function after a readers map with a generic reader can fail to compile.
The type of the fields also follows a type that your code writes, such as readIsoBoxes<bigint>(buffer) or a variable of the type ParsedIsoBox<bigint>[]. TypeScript does not check such a type against the int64 option. Let TypeScript infer the type from the option.
A function that forwards the option
Your code can have a function that takes a configuration and passes that configuration to readIsoBoxes. Give the function a type parameter for the type of the 64-bit fields. The result type then follows the configuration of each call:
import {
createDefaultReaderConfig,
readInt64AsBigInt,
readIsoBoxes,
type IsoBoxData,
type IsoBoxReadConfig,
type IsoInt64,
type ParsedIsoBox,
} from "@svta/cml-iso-bmff";
function readSegment<V extends IsoInt64 = number>(
data: IsoBoxData,
config: IsoBoxReadConfig<V>,
): ParsedIsoBox<V>[] {
return readIsoBoxes(data, config);
}
// The 64-bit fields are numbers in this result.
const plain = readSegment(buffer, createDefaultReaderConfig());
// The 64-bit fields are bigints in this result.
const exact = readSegment(
buffer,
createDefaultReaderConfig({ int64: readInt64AsBigInt }),
);Do not type the parameter as IsoBoxReadConfig<IsoInt64>. That type does not accept the result of createDefaultReaderConfig({ int64: readInt64AsBigInt }).
A custom reader for one field
If your code needs the exact value of one field only, a custom reader can call readUint64. The function returns a bigint and needs no option. A reader under the key tfdt returns the tfdt box type, so the reader adds the exact value as a new field:
import {
isIsoBoxType,
readIsoBoxes,
readUint24,
readUint32,
readUint64,
readUint8,
type IsoBoxReadCursor,
} from "@svta/cml-iso-bmff";
const readTfdtExact = (cursor: IsoBoxReadCursor) => {
const version = readUint8(cursor);
const flags = readUint24(cursor);
const exactTime =
version === 1 ? readUint64(cursor) : BigInt(readUint32(cursor));
return {
type: "tfdt" as const,
version,
flags,
baseMediaDecodeTime: Number(exactTime),
exactTime,
};
};
const boxes = readIsoBoxes(buffer, {
readers: {
tfdt: readTfdtExact,
},
});
type TfdtExact = ReturnType<typeof readTfdtExact>;
for (const box of boxes) {
if (isIsoBoxType("tfdt", box)) {
console.log((box as TfdtExact).exactTime);
}
}The built-in writers write a bigint field with the exact value. See Writing 64-bit fields.
Changes in a minor release
A minor release of the package can make two changes that affect existing code:
- A new default reader or writer.
createDefaultReaderConfigcan get a reader for a box type that had none. A box of that type was a raw box before, and it is a parsed box after.createDefaultWriterConfiggets the writer in the same release. If your code needs a fixed set of readers, pass areadersmap of your own. See Using specific readers. - A new box type in
IsoBoxMap. If your program declares that box type inIsoCustomBoxMap, the program no longer compiles. Delete your declaration. Your reader and your writer can remain under the key if they use the box type of the package.
The changelog of each release lists the new readers, writers, and box types.