Skip to content

Migrating to Version 2 ​

Version 2.0.0 replaces the classes IsoBoxReadView and IsoBoxWriteView with two plain objects: the read cursor and the write cursor. A field function reads or writes one field at the position of a cursor. Every built-in reader and writer takes a cursor.

The guide uses two terms:

  • A box object is an object with a type field and the fields of the box, such as the result of readTfdt.
  • A raw box is the result of readIsoBoxes for a box with no reader and a type outside CONTAINERS: { type, bytes, headerSize }.

The compiler reports most changes. The tables in this guide list each change and its replacement.

The type declarations of version 2.0.0 need TypeScript 5.7 or later.

Reading boxes ​

readIsoBoxes keeps its arguments. Its result changes:

  • A box with no reader and a type outside CONTAINERS is a raw box. bytes is the complete box, with its header. The body is box.bytes.subarray(box.headerSize). The bytes share memory with the input.
  • A box object has only type and its fields. The fields view, size, largesize, and usertype do not exist.
  • A raw box has its four-character code in type, as a box object has. A test such as box.type === "mdat" matches a box object and a raw box.
  • The result type does not follow the readers map. Every box has the type ParsedIsoBox, also a child in a boxes field. A test of box.type does not exclude a raw box, so narrow a box with isIsoBoxType.
typescript
import { findIsoBox, isIsoBoxType, readIsoBoxes, readTfdt } from "@svta/cml-iso-bmff";

const boxes = readIsoBoxes(buffer, { readers: { tfdt: readTfdt } });

const tfdt = findIsoBox(boxes, (box) => isIsoBoxType("tfdt", box));

console.log(tfdt?.baseMediaDecodeTime);
Version 1Version 2.0.0
box.viewOmit the reader of the box, and use box.bytes of the raw box
box.sizebox.bytes.length of a raw box
box.largesizebox.bytes.length of a raw box
box.view or box.size of a box with a type in CONTAINERS, such as moofA custom reader for the box. The bytes of the box are from cursor.start to cursor.end. seekIsoBox returns a cursor with the same range.
box.usertype of a parsed uuid boxbox.userType of a parsed uuid box, as a UUID string. Declare the user type in IsoCustomUuidBoxMap and read the box with createUuidReader. A raw uuid box has box.userType as 16 bytes.
if (box.type === "tfdt") before a field readif (isIsoBoxType("tfdt", box))
readStsd<Avc1Box>readStsd, then isIsoBoxType for each entry
stsd.entries, dref.entriesstsd.boxes, dref.boxes
A malformed stsd or dref box returns fewer entriesThe read throws a RangeError
readVlab, readPayl, readIden, and readSttg stop at a null byteThe readers read to the end of the box. A box from release 1.0.7 or earlier gives a trailing U+0000.
A co64 or stz2 box with the default readers has no fieldsThe box has chunkOffset, or fieldSize and entrySize
A ludt, rinf, strd, or trgr box has view and no boxes fieldThe four types are in CONTAINERS. The box has its child boxes in boxes.
An error Truncated box from a custom readerThe error reaches the caller of readIsoBoxes. A truncated box stops the read with no error.

seekIsoBox reads one box without a read of the other boxes. Use it in place of a full read when your code needs one box, such as tfdt. See Reading one box.

seekIsoBoxes finds every box at a path, such as the tfdt box of every fragment, and returns a read cursor for each box. See Reading every box at a path.

Custom readers ​

A reader takes a read cursor and the box type, and returns the complete box object with its type field. The cursor of a reader starts at the first byte after the box header. For a uuid box, the cursor starts at the first byte of usertype.

typescript
import {
	readIsoBoxes,
	readUint24,
	readUint32,
	readUint8,
	type IsoBoxReadCursor,
	type IsoInt64,
} from "@svta/cml-iso-bmff";

const readMfhd = (cursor: IsoBoxReadCursor<IsoInt64>) => ({
	type: "mfhd" as const,
	version: readUint8(cursor),
	flags: readUint24(cursor),
	sequenceNumber: readUint32(cursor),
});

const boxes = readIsoBoxes(buffer, { readers: { mfhd: readMfhd } });

The readers map takes a reader under a key of IsoBoxMap, and the reader returns the box type of that key. For a box type that the package does not name, add the type to IsoCustomBoxMap. See Writing a custom reader.

The table shows the replacement for each member of IsoBoxReadView. A method with a size parameter becomes one function for each size.

IsoBoxReadView memberVersion 2.0.0
new IsoBoxReadView(raw, config)createIsoBoxReadCursor(raw, config)
view.readUint(1), view.readUint(2), view.readUint(3), view.readUint(4)readUint8(cursor), readUint16(cursor), readUint24(cursor), readUint32(cursor)
view.readUint(8)readWideUint(cursor, 8)
view.readInt(1), view.readInt(2), view.readInt(4)readInt8(cursor), readInt16(cursor), readInt32(cursor)
view.readInt(8)readWideInt(cursor, 8)
view.readTemplate(2), view.readTemplate(4)readTemplate16(cursor), readTemplate32(cursor)
view.readString(4) for a four-character codereadFourCc(cursor)
view.readUtf8(size)readUtf8(cursor, size)
view.readString(size) for other sizesreadUtf8(cursor, size). readString gave one character for each byte, so a byte above 0x7F now decodes as UTF-8.
view.readUtf8(-1), view.readString(-1)readTerminatedUtf8(cursor). For readString, a byte above 0x7F now decodes as UTF-8.
view.readUtf8()readUtf8(cursor, cursor.end - cursor.pos)
view.readData(size)readBytes(cursor, size)
view.readData(-1)readBytes(cursor, cursor.end - cursor.pos)
view.readFullBox()readUint8(cursor) for the version, then readUint24(cursor) for the flags
view.readArray(...), view.readEntries(...)A loop in the reader
view.readBoxes()readChildBoxes(cursor)
view.readBoxes(count)readChildBoxes(cursor, count)
view.readBoxes(-1)readChildBoxes(cursor). A negative count now throws a RangeError.
view.readBox()readChildBoxes(cursor, 1)[0]. To skip the box, nextIsoBox(cursor) returns its type and moves past it.
for (const box of view)for (const box of readChildBoxes(cursor))
view.jump(size)cursor.pos += size
view.bytesRemainingcursor.end - cursor.pos
view.donecursor.pos >= cursor.end. Before a truncated box, nextIsoBox(cursor) returns null.
view.cursorcursor.pos - cursor.start
view.slice(offset, size)readBytes, then createIsoBoxReadCursor
view.buffer, view.byteOffset, view.byteLengthcursor.view.buffer, cursor.view.byteOffset + cursor.start, cursor.end - cursor.start. cursor.view covers the complete input, not one box.

A read past cursor.end throws a RangeError, so a reader cannot read the bytes of the next box. A length below 0 and a length that is not an integer throw a RangeError too. No length value has a special meaning.

The int64 option of the configuration is new in version 2.0.0. The function of the option takes a read cursor. The package exports readInt64AsBigInt and createInt64OverflowReader for the option. See Reading 64-bit fields.

Writing boxes ​

writeIsoBoxes keeps its arguments and returns one Uint8Array with every box. Remove the code that joins the arrays of version 1:

typescript
import { createDefaultWriterConfig, readIsoBoxes, writeIsoBoxes } from "@svta/cml-iso-bmff";

const bytes = writeIsoBoxes(readIsoBoxes(buffer), createDefaultWriterConfig());
Version 1Version 2.0.0
writeIsoBoxes returns one Uint8Array for each boxwriteIsoBoxes returns one Uint8Array
A writer in the map comes before the bytes of a parsed boxThe bytes of a raw box come before a writer. To change a raw box, build a box object with no bytes field.
A box object with a reader and no writer writes the bytes of viewAdd the writer of the type, or remove the reader so that the box stays a raw box
writeIsoBox returns a view of the input for an ArrayBufferViewwriteIsoBox returns a new array
writeFtyp(box) and every other built-in writer returns an IsoBoxWriteViewwriteFtyp(cursor, box) writes to a write cursor and returns nothing. For the bytes of one box, call writeIsoBox(box, { writers: { ftyp: writeFtyp } }).
createIsoBoxReadableStream throws an error of the first boxThe error rejects the first read
new IsoBoxReadableStream(boxes, config)createIsoBoxReadableStream(boxes, config)
writeSidx writes the low 16 bits of a reference count above 65535writeSidx throws a RangeError
writeEmsg writes the text after a U+0000 in schemeIdUri or valuewriteEmsg throws a RangeError for a string with U+0000
writeSubs writes the low 16 bits of a subsample count above 65535writeSubs throws a RangeError
writeFtyp, writeStyp, and writeHdlr write a code that does not have 4 charactersThe writers throw a RangeError. A character above U+00FF throws too.
writeMdhd writes 0 or a wrong code for a language that is not 3 characters from U+0060 to U+007FwriteMdhd throws a RangeError
writeHdlr writes the text after a U+0000 in namewriteHdlr throws a RangeError
writeSchm writes the text after a U+0000 in schemeUriwriteSchm throws a RangeError
writePrsl, writeLabl, writeKind, and writeElng write the text after a U+0000Each writer throws a RangeError
A writer writes the low bits of a number that does not fit its field, and 0 for NaNThe writer throws a RangeError. version and flags follow the same rule.
A writer writes 0 for a field that a flag selects when the box has no value for it, such as sampleDuration of trunThe writer throws a RangeError
writePssh and writeTenc write 16 bytes for a systemId or a defaultKid of another lengthThe writers throw a RangeError
A byte field takes any valueA byte field takes a Uint8Array or an array of integers from 0 to 255. An ArrayBuffer throws a RangeError.

The stream writes one box for each read and writes no box before the first read.

Custom writers ​

A writer takes a write cursor and the box object, and returns nothing. The writer writes the header with beginIsoBox or beginIsoFullBox, then the fields, then the size with endIsoBox. A writer of a box with child boxes writes them with writeChildBoxes. The writers of the cursor then apply to the child boxes.

typescript
import {
	beginIsoFullBox,
	endIsoBox,
	writeIsoBox,
	writeUint32,
	type IsoBoxWriteCursor,
	type MovieFragmentHeaderBox,
} from "@svta/cml-iso-bmff";

const writeMfhd = (cursor: IsoBoxWriteCursor, box: MovieFragmentHeaderBox) => {
	const start = beginIsoFullBox(cursor, "mfhd", box.version, box.flags);
	writeUint32(cursor, box.sequenceNumber);
	endIsoBox(cursor, start);
};

const bytes = writeIsoBox(
	{ type: "mfhd", version: 0, flags: 0, sequenceNumber: 1 },
	{ writers: { mfhd: writeMfhd } },
);

The table shows the replacement for each member of IsoBoxWriteView:

IsoBoxWriteView memberVersion 2.0.0
new IsoBoxWriteView(type, size)const start = beginIsoBox(cursor, type) at the start, and endIsoBox(cursor, start) at the end
writer.writeFullBox(version, flags)beginIsoFullBox(cursor, type, version, flags) in place of beginIsoBox
writer.writeBoxHeader(type, size)beginIsoBox(cursor, type) and endIsoBox(cursor, start)
writer.writeUint(value, 1), 2, 3, 4writeUint8, writeUint16, writeUint24, writeUint32
writer.writeUint(value, 8)writeWideUint(cursor, value, 8)
writer.writeInt(value, 1), 2, 4writeInt8, writeInt16, writeInt32
writer.writeInt(value, 8)writeWideInt(cursor, value, 8)
writer.writeUint64(value)writeUint64(cursor, value)
writer.writeWideUint(value, size), writer.writeWideInt(value, size)writeWideUint(cursor, value, size), writeWideInt(cursor, value, size)
writer.writeTemplate(value, 2), writer.writeTemplate(value, 4)writeTemplate16(cursor, value), writeTemplate32(cursor, value)
writer.writeString(code) for a four-character codewriteFourCc(cursor, code)
writer.writeString(text) for ASCII textwriteUtf8(cursor, text)
writer.writeTerminatedString(text), writer.writeUtf8TerminatedString(text)writeTerminatedUtf8(cursor, text)
writer.writeBytes(data)writeBytes(cursor, data)
writer.writeBytes([a, b])writeBytes(cursor, a), then writeBytes(cursor, b)
writer.writeArray(...)A loop in the writer
writer.buffer, writer.byteOffset, writer.byteLengthcursor.bytes.subarray(0, cursor.pos)

A writer does not compute the size of its box. endIsoBox writes the size, and throws a RangeError for a box above 2^32 - 1 bytes. writeFourCc, beginIsoBox, and beginIsoFullBox throw a RangeError for a code that does not have 4 characters of 1 byte each.

The writers of the boxes with child boxes, such as writeStsd and writeMoov, have no config parameter. They write the child boxes with the writers of the cursor. To call a writer directly, create the cursor with createIsoBoxWriteCursor({ writers }).

Types ​

Renamed exports and fields ​

The names of the box types, entry types, and fields follow the names of the specification.

Version 1Version 2.0.0
HandlerReferenceBoxHandlerBox
DecodingTimeToSampleBoxTimeToSampleBox
CompositionTimeToSampleBoxCompositionOffsetBox
ProtectionSchemeInformationBoxProtectionSchemeInfoBox
TrackKindBoxKindBox
SubsampleInformationBoxSubSampleInformationBox
SubTrackBoxSubTrack
SampleEntryBox, AudioSampleEntryBox, VisualSampleEntryBoxSampleEntry, AudioSampleEntry, VisualSampleEntry
writeAudioSampleEntryBoxwriteAudioSampleEntry
writeVisualSampleEntryBoxwriteVisualSampleEntry
DecodingTimeSampleTimeToSampleEntry
CompositionTimeToSampleEntryCompositionOffsetEntry
SubsampleEntry, SubsampleSubSampleInformationEntry, SubSampleInformationSubsample
Subsegment, SubsegmentRangeSubsegmentIndexSubsegment, SubsegmentIndexRange
channelcount, samplesize, sampleratechannelCount, sampleSize, sampleRate
horizresolution, vertresolutionhorizResolution, vertResolution
graphicsmode, opcolorgraphicsMode, opColor
defaultIvSizedefaultPerSampleIvSize
IsoBoxReadViewConfig, IsoBoxWriteViewConfigIsoBoxReadConfig, IsoBoxWriteConfig
defaultReaderConfig, defaultWriterConfigcreateDefaultReaderConfig, createDefaultWriterConfig

A field rename changes the keys of a reader result. The compiler does not report code that reads a field with a string key.

Removed exports ​

Version 1Version 2.0.0
IsoBoxReadView, IsoBoxWriteViewThe read cursor and the write cursor. See Custom readers and Custom writers.
ParsedBox, IsoTypedParsedBoxParsedIsoBox
IsoBoxReaderReturnParsedIsoBox. The result type of readIsoBoxes does not follow the readers map.
IsoFieldTypeMap, UINT, INT, TEMPLATE, STRING, UTF8, DATA, IsoBoxFieldsThe field functions, such as readUint32
IsoBoxReadableStreamcreateIsoBoxReadableStream
fourCcToUint32A field with a four-character code is a string. To convert a code, compute new DataView(Uint8Array.from(code, char => char.charCodeAt(0)).buffer).getUint32(0).
readAudioSampleEntryBox(type, view), readVisualSampleEntryBox(type, view)readAudioSampleEntry(cursor, type) and readVisualSampleEntry(cursor, type). The cursor is the first argument.
createAudioSampleEntryReader(type), createVisualSampleEntryReader(type)readAudioSampleEntry and readVisualSampleEntry. Put each function in the readers map under the key of a sample entry type, such as { av01: readVisualSampleEntry }.
EventMessageBoxBase, EventMessageBoxV0, EventMessageBoxV1EventMessageBox. Read the field of the version, such as box.presentationTimeDelta ?? box.presentationTime.
isFullBoxisIsoBoxType, or a test such as 'version' in box && 'flags' in box
The child types, such as MovieBoxChild and VisualSampleEntryBoxChildParsedIsoBox
TrackReferenceTypeBoxA raw box. A child of a tref box is a raw box.
The aliases co64, stz2, url, and urnChunkLargeOffsetBox, CompactSampleSizeBox, DataEntryUrlBox, DataEntryUrnBox, or a key of IsoBoxMap such as IsoBoxMap['co64']
SyncSample, EntityA number in sampleNumber and entityId
The types of 16 boxes with no reader and no writer: HintMediaHeaderBox (hmhd), ItemInfoBox (iinf), ItemLocationBox (iloc), IpmpInfoBox (imif), ItemInfoEntry (infe), ItemProtectionBox (ipro), ItemReferenceBox (iref), NullMediaHeaderBox (nmhd), PrimaryItemBox (pitm), SampleAuxiliaryInformationOffsetsBox (saio), SampleAuxiliaryInformationSizesBox (saiz), SampleToGroupBox (sbgp), SampleEncryptionBox (senc), SampleGroupDescriptionBox (sgpd), DegradationPriorityBox (stdp), and ShadowSyncSampleBox (stsh)A type that your code declares and adds to IsoCustomBoxMap, with a custom reader
The types that those 16 boxes use: EncryptedSample, SubsampleEncryption, ItemExtent, ItemLocation, SampleToGroupEntry, ShadowSyncEntry, and SingleItemTypeReferenceBoxA type that your code declares

Changed fields ​

Version 1Version 2.0.0
stss.entries: { sampleNumber }[]stss.sampleNumber: number[]
prsl.entities: { entityId }[]prsl.entityId: number[]
reserved1, reserved2, reserved3 of mvhd, tkhd, and the sample entriesRemoved. The writers write 0.
reserved of smhd, sidx, and tfraRemoved. The writers write 0.
preDefined of hdlr, mdhd, mvhd, and the audio sample entries is required. preDefined1, preDefined2, and preDefined3 of the visual sample entries are required.The fields are optional. A writer writes 0 for a missing value, and -1 for a missing preDefined3.
reserved of hdlr is requiredThe field is optional. The writer writes 0 for a missing value.
defaultIsEncrypted of tencdefaultIsProtected, with the pattern in defaultCryptByteBlock and defaultSkipByteBlock
isGroupLabel of labl(box.flags & 0x1) !== 0
reference and sap of a sidx referenceThe decoded fields, such as referenceType and sapType
sampleCount of trunsamples.length. A box with none of the flags 0x000100 to 0x000800 keeps sampleCount and has no samples. The writer writes the length of samples, or sampleCount.
numberOfEntry of tfraentries.length
subsegmentCount of ssix, rangesCount of a subsegmentsubsegments.length, ranges.length
sampleDependencyTable: number[] of sdtpA Uint8Array, a view of the input. Wrap a list in new Uint8Array(...).
entryCount of stts, stsc, stco, stss, and subsThe length of the list: entries, chunkOffset, or sampleNumber
subsampleCount of a subs entrysubsamples.length
entryCount of a ctts box of version 0 or 1entries.length. A box of version 2 or above keeps entryCount.
sampleCount of a stsz box with a sampleSize of 0entrySize.length. A box with a sampleSize above 0 keeps sampleCount.
entryCount of co64, sampleCount of stz2chunkOffset.length, entrySize.length
entryCount of elstentries.length
entryCount of stsd and drefboxes.length
numEntitiesInGroup of prslentityId.length
compressorName: number[] of a visual sample entrycompressorName: string. The writer writes the length byte and the padding. A name above 31 bytes in UTF-8 throws a RangeError.
location: string of url and urn location?: string. A box with no bytes after the flags or after name has no location.
kidCount and kid: number[] of psshkid: Uint8Array[], one entry for each key ID. The count is kid.length.
dataSize and data: number[] of psshdata: Uint8Array. The size is data.length.
systemId: number[] of pssh, defaultKid: number[] of tencA Uint8Array of 16 bytes
dataFormat: number of frma, schemeType: number of schmA string, such as 'avc1' or 'cenc'
matrix: number[] of mvhd and tkhd, opColor: number[] of vmhdLabeled tuples of 9 and 3 numbers. Annotate an array that your code builds, such as matrix as MovieHeaderBox['matrix'].

Changed values ​

The compiler does not report these changes.

Version 1Version 2.0.0
The matrix entries u, v, and w (indexes 2, 5, and 8) of mvhd and tkhd are 16.16 values. The entry w of the identity matrix is 16384.The entries are 2.30 values, and w of the identity matrix is 1. Pass 1 for w. The value 16384 throws a RangeError.
balance of smhd is 256 for full right and 65280 for full left1 for full right and -1 for full left. The value 256 throws a RangeError.
A rate, volume, layer, alternateGroup, or matrix entry of -1 reads as 65535The value reads as -1
A fixed-point field with a fraction reads a wrong value, such as 8193 for 1.5The field reads 1.5
A reader omits the key of a field that the box does not have, such as sampleDuration of a trun sample or presentationTime of emsgEvery key is present, with undefined for an absent field. "presentationTime" in box is always true, so test the value for undefined. A spread of the box over default values sets each absent field to undefined.

Changed types ​

Version 1Version 2.0.0
The boxes field of a container has a list of child typesThe boxes field of every box type is ParsedIsoBox<V>[]. Narrow a child with isIsoBoxType.
A child of a sample entry can be a Uint8ArrayA child is a box object or a raw box, such as { type: "esds", bytes }
SampleEntry<T, C>SampleEntry<T, V>
SampleDescriptionBox<E>SampleDescriptionBox<V, E>
Box with no type argumentBox<"abcd"> for one box type, or IsoBox
The result type of readIsoBoxes has the return type of each readerThe result type is ParsedIsoBox<V>[]. isIsoBoxType narrows a box. Add the box type of a custom reader to IsoCustomBoxMap.
IsoBoxStreamable has ParsedBox and accepts a box object with missing fieldsIsoBoxStreamable is the union of the box types of IsoBoxMap, IsoRawBox, and ArrayBufferView. The write functions check a box object against its box type.
IsoBoxReader<B, T, V>, with the box type T as the second parameterIsoBoxReader<B, V>, with the type V of the 64-bit fields as the second parameter. Replace IsoBoxReader<MyBox, 'abcd', bigint> with IsoBoxReader<MyBox, bigint>. B has a type field.
IsoBoxWriter<B> returns an ArrayBufferViewIsoBoxWriter<B> takes the cursor and the box, and returns nothing
IsoBoxReaderMap and IsoBoxWriterMap accept a function under any keyThe maps take a key of IsoBoxMap only. A reader returns the box type of that key, and a writer takes that box type. Add another box type to IsoCustomBoxMap.
CONTAINERS is a string[], and code can add a type with pushCONTAINERS is a readonly string[]. To read another container box, add a reader that calls readChildBoxes.

A Streaming Video Technology Alliance project.