🎥 Make videos programmatically with React
New system for parsing boxes
Jonny Burgeree6c06c0237a
diff --git a/packages/media-parser/src/boxes/webm/make-header.ts b/packages/media-parser/src/boxes/webm/make-header.tsindex b73b74b93b..c7a030b85c 100644--- a/packages/media-parser/src/boxes/webm/make-header.ts+++ b/packages/media-parser/src/boxes/webm/make-header.ts@@ -5,7 +5,7 @@ import type {HeaderStructure,matroskaElements,} from './segments/all-segments';-import {matroskaHeaderStructure} from './segments/all-segments';+import {getIdForName, matroskaHeaderStructure} from './segments/all-segments';export const webmPattern = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]);@@ -33,7 +33,7 @@ const makeField = <T extends Ebml>(element: T, value: EmblTypes[T['type']]) => {}return combineUint8Arrays([- matroskaToHex(element.value),+ matroskaToHex(getIdForName(element.name)),getVariableInt(val.byteLength),val,]);diff --git a/packages/media-parser/src/boxes/webm/parse-ebml.ts b/packages/media-parser/src/boxes/webm/parse-ebml.tsindex 00954f2c5f..e1e73940bb 100644--- a/packages/media-parser/src/boxes/webm/parse-ebml.ts+++ b/packages/media-parser/src/boxes/webm/parse-ebml.ts@@ -1,36 +1,79 @@import type {BufferIterator} from '../../buffer-iterator';-import type {Ebml, EbmlParsed} from './segments/all-segments';+import type {+ EbmlWithString,+ EbmlWithUint8,+ EbmlWithVoid,+} from './segments/all-segments';+import {ebmlMap, type Ebml, type EbmlParsed} from './segments/all-segments';type Prettify<T> = {[K in keyof T]: T[K];} & {};-export const parseEbml = <T extends Ebml>(- segment: T,+export const parseEbml = (iterator: BufferIterator,-): Prettify<EbmlParsed<T>> => {+): Prettify<EbmlParsed<Ebml>> => {const hex = iterator.getMatroskaSegmentId();++ const hasInMap = ebmlMap[hex as keyof typeof ebmlMap];+ if (!hasInMap) {+ throw new Error(+ `Don't know how to parse EBML hex ID ${JSON.stringify(hex)}`,+ );+ }+const size = iterator.getVint();- if (segment.type === 'uint-8') {+ if (hasInMap.type === 'uint-8') {const value = iterator.getUint8();- console.log(hex, size, value);++ return {type: hasInMap.name, value, hex} as EbmlParsed<EbmlWithUint8>;}- if (segment.type === 'string') {+ if (hasInMap.type === 'string') {const value = iterator.getByteString(size);- console.log(hex, size, value);++ return {+ type: hasInMap.name,+ value,+ hex,+ } as EbmlParsed<EbmlWithString>;}- if (segment.type === 'children') {- const children = [];- for (const child of segment.children) {- const value = parseEbml(child, iterator);+ if (hasInMap.type === 'void') {+ iterator.discard(size);++ return {+ type: hasInMap.name,+ value: undefined,+ hex,+ } as EbmlParsed<EbmlWithVoid>;+ }++ if (hasInMap.type === 'children') {+ const children: EbmlParsed<Ebml>[] = [];+ const startOffset = iterator.counter.getOffset();++ // eslint-disable-next-line no-constant-condition+ while (true) {+ const value = parseEbml(iterator);children.push(value);+ const offsetNow = iterator.counter.getOffset();++ if (offsetNow - startOffset > size) {+ throw new Error(+ `Offset ${offsetNow - startOffset} is larger than the length of the hex ${size}`,+ );+ }++ if (offsetNow - startOffset === size) {+ break;+ }}- console.log(children);+ return {type: hasInMap.name, value: children as EbmlParsed<Ebml>[], hex};}- return {segment};+ // @ts-expect-error+ throw new Error(`Unknown segment type ${hasInMap.type}`);};diff --git a/packages/media-parser/src/boxes/webm/parse-webm-header.ts b/packages/media-parser/src/boxes/webm/parse-webm-header.tsindex 2f8b9dc55d..9a11c79b12 100644--- a/packages/media-parser/src/boxes/webm/parse-webm-header.ts+++ b/packages/media-parser/src/boxes/webm/parse-webm-header.ts@@ -1,24 +1,18 @@import type {BufferIterator} from '../../buffer-iterator';import type {ParseResult} from '../../parse-result';import type {ParserContext} from '../../parser-context';-import {parseEbml} from './parse-ebml';-import {expectSegment} from './segments';-import {matroskaHeader} from './segments/all-segments';+import {expectChildren} from './segments/parse-children';// Parsing according to https://darkcoding.net/software/reading-mediarecorders-webm-opus-output/export const parseWebm = (counter: BufferIterator,parserContext: ParserContext,): Promise<ParseResult> => {- const ret = parseEbml(matroskaHeader, counter);- const length = counter.getVint();-- if (length !== 31) {- throw new Error(`Expected header length 31 or 35, got ${length}`);- }-- // Discard header for now- counter.discard(length);-- return expectSegment(counter, parserContext);+ return expectChildren({+ iterator: counter,+ length: Infinity,+ initialChildren: [],+ wrap: null,+ parserContext,+ });};diff --git a/packages/media-parser/src/boxes/webm/segments.ts b/packages/media-parser/src/boxes/webm/segments.tsindex 074fd581b3..b7c1d65b04 100644--- a/packages/media-parser/src/boxes/webm/segments.ts+++ b/packages/media-parser/src/boxes/webm/segments.ts@@ -4,6 +4,8 @@ import type {ParseResult} from '../../parse-result';import type {ParserContext} from '../../parser-context';import type {VideoSample} from '../../webcodec-sample-types';import {getTrack} from './get-track';+import {parseEbml} from './parse-ebml';+import type {Ebml, EbmlParsed} from './segments/all-segments';import {matroskaElements} from './segments/all-segments';import type {DurationSegment} from './segments/duration';import {parseDurationSegment} from './segments/duration';@@ -101,8 +103,6 @@ import {} from './segments/track-entry';import type {TracksSegment} from './segments/tracks';import {parseTracksSegment} from './segments/tracks';-import type {UnknownSegment} from './segments/unknown';-import {parseUnknownSegment} from './segments/unknown';import type {VoidSegment} from './segments/void';import {parseVoidSegment} from './segments/void';import type {WritingAppSegment} from './segments/writing';@@ -110,7 +110,6 @@ import {parseWritingSegment} from './segments/writing';export type MatroskaSegment =| MainSegment- | UnknownSegment| SeekHeadSegment| SeekSegment| SeekPositionSegment@@ -156,7 +155,8 @@ export type MatroskaSegment =| ChannelsSegment| BitDepthSegment| ReferenceBlockSegment- | BlockAdditionsSegment;+ | BlockAdditionsSegment+ | EbmlParsed<Ebml>;export type OnTrackEntrySegment = (trackEntry: TrackEntrySegment) => void;@@ -165,33 +165,18 @@ const parseSegment = async ({iterator,length,parserContext,+ headerReadSoFar,}: {segmentId: string;iterator: BufferIterator;length: number;parserContext: ParserContext;+ headerReadSoFar: number;}): Promise<Promise<MatroskaSegment> | MatroskaSegment> => {if (length === 0) {throw new Error(`Expected length of ${segmentId} to be greater than 0`);}- if (segmentId === '0x') {- return {- type: 'unknown-segment',- id: segmentId,- };- }-- // Log this to debug- /*- console.log(- 'segmentId',- segmentId,- getSegmentName(segmentId),- iterator.counter.getOffset(),- );- */-if (segmentId === '0x114d9b74') {return parseSeekHeadSegment(iterator, length, parserContext);}@@ -442,14 +427,9 @@ const parseSegment = async ({return parseBlockElementSegment(iterator, length);}- const bytesRemaining = iterator.byteLength() - iterator.counter.getOffset();- const toDiscard = Math.min(- bytesRemaining,- length > 0 ? length : bytesRemaining,- );+ iterator.counter.decrement(headerReadSoFar);- const child = parseUnknownSegment(iterator, segmentId, toDiscard);- return child;+ return parseEbml(iterator);};export const expectSegment = async (@@ -457,7 +437,7 @@ export const expectSegment = async (parserContext: ParserContext,): Promise<ParseResult> => {const bytesRemaining_ = iterator.bytesRemaining();- if (bytesRemaining_ === 0) {+ if (bytesRemaining_ < 4) {return {status: 'incomplete',segments: [],@@ -525,6 +505,7 @@ export const expectSegment = async (iterator,length,parserContext,+ headerReadSoFar: iterator.counter.getOffset() - offset,});return {diff --git a/packages/media-parser/src/boxes/webm/segments/all-segments.ts b/packages/media-parser/src/boxes/webm/segments/all-segments.tsindex d8329c1723..a3c0ce82df 100644--- a/packages/media-parser/src/boxes/webm/segments/all-segments.ts+++ b/packages/media-parser/src/boxes/webm/segments/all-segments.ts@@ -290,78 +290,95 @@ export const getSegmentName = (id: string) => {)?.[0];};-export type MatroskaElement =- (typeof matroskaElements)[keyof typeof matroskaElements];+export const getIdForName = (name: string) => {+ const value = Object.entries(matroskaElements).find(+ ([key]) => key === name,+ )?.[1];+ if (!value) {+ throw new Error(`Could not find id for name ${name}`);+ }++ return value;+};++export type MatroskaKey = keyof typeof matroskaElements;++export type MatroskaElement = (typeof matroskaElements)[MatroskaKey];type EbmlType = 'string';-type EbmlWithChildren = {- name: string;- value: MatroskaElement;+export type EbmlWithChildren = {+ name: MatroskaKey;type: 'children';children: HeaderStructure;};-type EbmlWithUint8 = {- name: string;- value: MatroskaElement;+export type EbmlWithUint8 = {+ name: MatroskaKey;type: 'uint-8';};-type EbmlWithString = {- name: string;- value: MatroskaElement;+export type EbmlWithString = {+ name: MatroskaKey;type: EbmlType;};-export type Ebml = EbmlWithString | EbmlWithUint8 | EbmlWithChildren;+export type EbmlWithVoid = {+ name: MatroskaKey;+ type: 'void';+};++export type Ebml =+ | EbmlWithString+ | EbmlWithUint8+ | EbmlWithChildren+ | EbmlWithVoid;export const ebmlVersion = {- name: 'EBMLVersion' as const,- value: matroskaElements.EBMLVersion,+ name: 'EBMLVersion',type: 'uint-8',} satisfies Ebml;export const ebmlReadVersion = {- name: 'EBMLReadVersion' as const,- value: matroskaElements.EBMLReadVersion,+ name: 'EBMLReadVersion',type: 'uint-8',} satisfies Ebml;export const ebmlMaxIdLength = {- name: 'EBMLMaxIDLength' as const,- value: matroskaElements.EBMLMaxIDLength,+ name: 'EBMLMaxIDLength',type: 'uint-8',} satisfies Ebml;export const ebmlMaxSizeLength = {- name: 'EBMLMaxSizeLength' as const,- value: matroskaElements.EBMLMaxSizeLength,+ name: 'EBMLMaxSizeLength',type: 'uint-8',} satisfies Ebml;export const docType = {- name: 'DocType' as const,- value: matroskaElements.DocType,+ name: 'DocType',type: 'string',} satisfies Ebml;export const docTypeVersion = {- name: 'DocTypeVersion' as const,- value: matroskaElements.DocTypeVersion,+ name: 'DocTypeVersion',type: 'uint-8',} satisfies Ebml;export const docTypeReadVersion = {- name: 'DocTypeReadVersion' as const,- value: matroskaElements.DocTypeReadVersion,+ name: 'DocTypeReadVersion',type: 'uint-8',} satisfies Ebml;+export const voidEbml = {+ name: 'Void',+ type: 'void',+} satisfies Ebml;+export type EmblTypes = {'uint-8': number;string: string;children: HeaderStructure;+ void: undefined;};export type HeaderStructure = Ebml[];@@ -377,29 +394,75 @@ export const matroskaHeaderStructure = [] as const satisfies HeaderStructure;export const matroskaHeader = {- name: 'Header' as const,- value: matroskaElements.Header,+ name: 'Header',type: 'children',children: matroskaHeaderStructure,} as const satisfies Ebml;-type Numbers = '0' | '1' | '2' | '3' | '4' | '5' | '6';--type Prettify<T> = {- [K in keyof T]: T[K];-} & {};+export const voidHeader = {+ name: 'Void',+ type: 'void',+} as const satisfies Ebml;-type EbmlValue<T extends Ebml> = T extends EbmlWithUint8+export type EbmlValue<T extends Ebml> = T extends EbmlWithUint8? number- : T extends EbmlWithChildren- ? {- [key in keyof T['children'] & Numbers]: Prettify<- EbmlParsed<T['children'][key]>- >;- }- : string;+ : T extends EbmlWithVoid+ ? undefined+ : T extends EbmlWithString+ ? string+ : EbmlParsed<Ebml>[];export type EbmlParsed<T extends Ebml> = {type: T['name'];value: EbmlValue<T>;+ hex: string;+};++export const ebmlMap: Partial<Record<MatroskaElement, Ebml>> = {+ [matroskaElements.Header]: matroskaHeader,+ [matroskaElements.DocType]: docType,+ [matroskaElements.DocTypeVersion]: docTypeVersion,+ [matroskaElements.DocTypeReadVersion]: docTypeReadVersion,+ [matroskaElements.EBMLVersion]: ebmlVersion,+ [matroskaElements.EBMLReadVersion]: ebmlReadVersion,+ [matroskaElements.EBMLMaxIDLength]: ebmlMaxIdLength,+ [matroskaElements.EBMLMaxSizeLength]: ebmlMaxSizeLength,+ [matroskaElements.Void]: voidEbml,+ [matroskaElements.Cues]: {+ name: 'Cues' as const,+ type: 'void',+ },+ [matroskaElements.DateUTC]: {+ name: 'DateUTC' as const,+ type: 'void',+ },+ // TODO: Handle this better+ [matroskaElements.TrackTimestampScale]: {+ name: 'TrackTimestampScale' as const,+ type: 'void',+ },+ [matroskaElements.CodecDelay]: {+ name: 'CodecDelay' as const,+ type: 'void',+ },+ [matroskaElements.SeekPreRoll]: {+ name: 'SeekPreRoll' as const,+ type: 'void',+ },+ [matroskaElements.DiscardPadding]: {+ name: 'DiscardPadding' as const,+ type: 'void',+ },+ [matroskaElements.OutputSamplingFrequency]: {+ name: 'OutputSamplingFrequency' as const,+ type: 'void',+ },+ [matroskaElements.CodecName]: {+ name: 'CodecName' as const,+ type: 'void',+ },+ [matroskaElements.Position]: {+ name: 'Position' as const,+ type: 'void',+ },};diff --git a/packages/media-parser/src/boxes/webm/segments/unknown.ts b/packages/media-parser/src/boxes/webm/segments/unknown.tsdeleted file mode 100644index b9718ceede..0000000000--- a/packages/media-parser/src/boxes/webm/segments/unknown.ts+++ /dev/null@@ -1,19 +0,0 @@-import type {BufferIterator} from '../../../buffer-iterator';--export type UnknownSegment = {- id: string;- type: 'unknown-segment';-};--export const parseUnknownSegment = (- iterator: BufferIterator,- id: string,- length: number,-): UnknownSegment => {- iterator.discard(length);-- return {- id,- type: 'unknown-segment',- };-};diff --git a/packages/media-parser/src/test/matroska.test.ts b/packages/media-parser/src/test/matroska.test.tsindex 1573a8106c..4be42fe01c 100644--- a/packages/media-parser/src/test/matroska.test.ts+++ b/packages/media-parser/src/test/matroska.test.ts@@ -23,6 +23,47 @@ test('Should get duration of AV1 video', async () => {});expect(parsed.boxes).toEqual([+ {+ hex: '0x1a45dfa3',+ type: 'Header',+ value: [+ {+ hex: '0x4286',+ type: 'EBMLVersion',+ value: 1,+ },+ {+ hex: '0x42f7',+ type: 'EBMLReadVersion',+ value: 1,+ },+ {+ hex: '0x42f2',+ type: 'EBMLMaxIDLength',+ value: 4,+ },+ {+ hex: '0x42f3',+ type: 'EBMLMaxSizeLength',+ value: 8,+ },+ {+ hex: '0x4282',+ type: 'DocType',+ value: 'webm',+ },+ {+ hex: '0x4287',+ type: 'DocTypeVersion',+ value: 2,+ },+ {+ hex: '0x4285',+ type: 'DocTypeReadVersion',+ value: 2,+ },+ ],+ },{type: 'main-segment',children: [@@ -445,8 +486,9 @@ test('Should get duration of AV1 video', async () => {],},{- id: '0x1c53bb6b',- type: 'unknown-segment',+ hex: '0x1c53bb6b',+ type: 'Cues',+ value: undefined,},],},