🎥 Make videos programmatically with React
intereseting
Jonny Burger4446814ef3c8
diff --git a/packages/media-parser/src/boxes/webm/make-header.ts b/packages/media-parser/src/boxes/webm/make-header.tsindex 5df4af9730..279d67e924 100644--- a/packages/media-parser/src/boxes/webm/make-header.ts+++ b/packages/media-parser/src/boxes/webm/make-header.ts@@ -1,15 +1,6 @@import {getVariableInt} from './ebml';-import type {Prettify} from './parse-ebml';-import type {- Ebml,- EbmlWithChildren,- EbmlWithHexString,- EbmlWithString,- EbmlWithUint8,- HeaderStructure,- matroskaElements,-} from './segments/all-segments';-import {getIdForName} from './segments/all-segments';+import type {PossibleEbml, matroskaElements} from './segments/all-segments';+import {ebmlMap, getIdForName} from './segments/all-segments';export const webmPattern = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]);@@ -26,25 +17,6 @@ const matroskaToHex = (return numbers;};-type Numbers = '0' | '1' | '2' | '3' | '4' | '5' | '6';--type ChildFields<StructArray extends HeaderStructure> = {- [key in keyof StructArray &- Numbers as StructArray[key]['name']]: SerializeValue<StructArray[key]>;-};--type SerializeValue<Struct extends Ebml> =- | Uint8Array- | (Struct extends EbmlWithChildren- ? Prettify<ChildFields<Struct['children']>>- : Struct extends EbmlWithString- ? string- : Struct extends EbmlWithUint8- ? number- : Struct extends EbmlWithHexString- ? string- : undefined);-function putUintDynamic(number: number) {if (number < 0) {throw new Error(@@ -64,36 +36,29 @@ function putUintDynamic(number: number) {return bytes;}-const makeFromHeaderStructure = <Struct extends Ebml>(- struct: Struct,- fields: SerializeValue<Struct>,-): Uint8Array => {+const makeFromHeaderStructure = (fields: PossibleEbml): Uint8Array => {const arrays: Uint8Array[] = [];+ const struct = ebmlMap[getIdForName(fields.type)];+if (struct.type === 'children') {- for (const item of struct.children) {- arrays.push(- makeMatroskaBytes(- item,- // @ts-expect-error- fields[item.name],- ),- );+ for (const item of fields.value as PossibleEbml[]) {+ arrays.push(makeMatroskaBytes(item));}return combineUint8Arrays(arrays);}if (struct.type === 'string') {- return new TextEncoder().encode(fields as string);+ return new TextEncoder().encode(fields.value as string);}if (struct.type === 'uint') {- return putUintDynamic(fields as number);+ return putUintDynamic(fields.value as number);}if (struct.type === 'hex-string') {- const hex = (fields as string).substring(2);+ const hex = (fields.value as string).substring(2);const arr = new Uint8Array(hex.length / 2);for (let i = 0; i < hex.length; i += 2) {const byte = parseInt(hex.substring(i, i + 2), 16);@@ -110,18 +75,15 @@ const makeFromHeaderStructure = <Struct extends Ebml>(throw new Error('Unexpected type');};-export const makeMatroskaBytes = <Struct extends Ebml>(- struct: Struct,- fields: SerializeValue<Struct>,-) => {+export const makeMatroskaBytes = (fields: PossibleEbml | Uint8Array) => {if (fields instanceof Uint8Array) {return fields;}- const value = makeFromHeaderStructure(struct, fields);+ const value = makeFromHeaderStructure(fields);return combineUint8Arrays([- matroskaToHex(getIdForName(struct.name)),+ matroskaToHex(getIdForName(fields.type)),getVariableInt(value.length),value,]);diff --git a/packages/media-parser/src/boxes/webm/segments/all-segments.ts b/packages/media-parser/src/boxes/webm/segments/all-segments.tsindex aafb712274..8cfc936a95 100644--- a/packages/media-parser/src/boxes/webm/segments/all-segments.ts+++ b/packages/media-parser/src/boxes/webm/segments/all-segments.ts@@ -292,7 +292,7 @@ export const getSegmentName = (id: string) => {)?.[0];};-export const getIdForName = (name: string) => {+export const getIdForName = (name: string): EbmlMapKey => {const value = Object.entries(matroskaElements).find(([key]) => key === name,)?.[1];@@ -300,7 +300,7 @@ export const getIdForName = (name: string) => {throw new Error(`Could not find id for name ${name}`);}- return value;+ return value as EbmlMapKey;};export type MatroskaKey = keyof typeof matroskaElements;@@ -312,7 +312,6 @@ type EbmlType = 'string';export type EbmlWithChildren = {name: MatroskaKey;type: 'children';- children: HeaderStructure;};export type EbmlWithUint8 = {@@ -398,14 +397,12 @@ export type EmblTypes = {uint: number;float: number;string: string;- children: HeaderStructure;+ children: Ebml[];void: undefined;'hex-string': string;uint8array: Uint8Array;};-export type HeaderStructure = Ebml[];-export const matroskaHeaderStructure = [ebmlVersion,ebmlReadVersion,@@ -414,12 +411,11 @@ export const matroskaHeaderStructure = [docType,docTypeVersion,docTypeReadVersion,-] as const satisfies HeaderStructure;+] as const satisfies Ebml[];export const matroskaHeader = {name: 'Header',type: 'children',- children: matroskaHeaderStructure,} as const satisfies Ebml;export const seekId = {@@ -435,13 +431,11 @@ export const seekPosition = {export const seek = {name: 'Seek',type: 'children',- children: [seekId, seekPosition],} as const satisfies Ebml;export const seekHead = {name: 'SeekHead',type: 'children',- children: [seek],} as const satisfies Ebml;export const voidHeader = {@@ -492,7 +486,6 @@ export const writingApp = {export const infoType = {name: 'Info',type: 'children',- children: [muxingApp, timestampScale, writingApp, duration],} as const satisfies Ebml;export const titleType = {@@ -548,7 +541,6 @@ export const tagSegment = {export const tags = {name: 'Tags',type: 'children',- children: [tagSegment],} as const satisfies Ebml;export const trackNumber = {@@ -594,13 +586,11 @@ export const maxBlockAdditionIdSegment = {export const audioSegment = {name: 'Audio',type: 'children',- children: [samplingFrequency, channels, bitDepth],} as const satisfies Ebml;export const videoSegment = {name: 'Video',type: 'children',- children: [heightType, displayHeight, displayWidth, widthType],} as const satisfies Ebml;export const flagDefault = {@@ -631,22 +621,11 @@ export const trackTimestampScale = {export const trackEntry = {name: 'TrackEntry',type: 'children',- children: [- trackNumber,- trackUID,- defaultDuration,- trackTimestampScale,- trackType,- flagDefault,- audioSegment,- videoSegment,- ],} as const satisfies Ebml;export const tracks = {name: 'Tracks',type: 'children',- children: [trackEntry],} as const satisfies Ebml;export const timestampEntry = {@@ -667,7 +646,6 @@ export const simpleBlock = {export const blockGroup = {name: 'BlockGroup',type: 'children',- children: [],} as const satisfies Ebml;export type CodecIdSegment = EbmlParsed<typeof codecID>;@@ -816,3 +794,5 @@ export type PossibleEbml = Prettify<[key in keyof typeof ebmlMap]: EbmlParsed<(typeof ebmlMap)[key]>;}[keyof typeof ebmlMap]>;++export type EbmlMapKey = keyof typeof ebmlMap;diff --git a/packages/media-parser/src/test/create-matroska.test.ts b/packages/media-parser/src/test/create-matroska.test.tsindex 4927ae0773..6e34ee0f42 100644--- a/packages/media-parser/src/test/create-matroska.test.ts+++ b/packages/media-parser/src/test/create-matroska.test.ts@@ -1,14 +1,6 @@import {expect, test} from 'bun:test';import {makeMatroskaBytes} from '../boxes/webm/make-header';import {parseEbml} from '../boxes/webm/parse-ebml';-import {- matroskaElements,- matroskaHeader,- seek,- seekHead,- seekId,- seekPosition,-} from '../boxes/webm/segments/all-segments';import {getArrayBufferIterator} from '../buffer-iterator';import type {ParserContext} from '../parser-context';import {makeParserState} from '../parser-state';@@ -28,14 +20,38 @@ const options: ParserContext = {};test('Should make Matroska header that is same as input', async () => {- const headerOutput = makeMatroskaBytes(matroskaHeader, {- EBMLVersion: 1,- DocTypeReadVersion: 2,- EBMLMaxIDLength: 4,- EBMLMaxSizeLength: 8,- DocType: 'webm',- DocTypeVersion: 4,- EBMLReadVersion: 1,+ const headerOutput = makeMatroskaBytes({+ type: 'Header',+ value: [+ {+ type: 'EBMLVersion',+ value: 1,+ },+ {+ type: 'EBMLReadVersion',+ value: 1,+ },+ {+ type: 'EBMLMaxIDLength',+ value: 4,+ },+ {+ type: 'EBMLMaxSizeLength',+ value: 8,+ },+ {+ type: 'DocType',+ value: 'webm',+ },+ {+ type: 'DocTypeVersion',+ value: 4,+ },+ {+ type: 'DocTypeReadVersion',+ value: 2,+ },+ ],});const iterator = getArrayBufferIterator(headerOutput, headerOutput.length);@@ -81,7 +97,10 @@ test('Should be able to create SeekIdBox', async () => {await Bun.file('vp8-segments/56-0x53ab').arrayBuffer(),);- const custom = makeMatroskaBytes(seekId, '0x1549a966');+ const custom = makeMatroskaBytes({+ type: 'SeekID',+ value: '0x1549a966',+ });expect(custom).toEqual(file);});@@ -89,13 +108,22 @@ test('Should be able to create Seek', async () => {const file = new Uint8Array(await Bun.file('vp8-segments/53-0x4dbb').arrayBuffer(),);-- const seekPositionBytes = makeMatroskaBytes(seekPosition, 0x40);-- const custom = makeMatroskaBytes(seek, {- SeekID: '0x1549a966',- SeekPosition: seekPositionBytes,+ const parsed = await parseEbml(getArrayBufferIterator(file, null), options);+ expect(parsed).toEqual({+ type: 'Seek',+ value: [+ {+ type: 'SeekID',+ value: '0x1549a966',+ },+ {+ type: 'SeekPosition',+ value: 0x40,+ },+ ],});++ const custom = makeMatroskaBytes(parsed);expect(custom).toEqual(file);});@@ -104,13 +132,23 @@ test('Should parse seekHead', async () => {await Bun.file('vp8-segments/2165155-0x114d9b74').arrayBuffer(),);- const seekPosBytes = makeMatroskaBytes(seekPosition, 3911);-- const custom = makeMatroskaBytes(seekHead, {- Seek: {- SeekID: matroskaElements.Cluster,- SeekPosition: seekPosBytes,- },+ const custom = makeMatroskaBytes({+ type: 'SeekHead',+ value: [+ {+ type: 'Seek',+ value: [+ {+ type: 'SeekID',+ value: '0x1f43b675',+ },+ {+ type: 'SeekPosition',+ value: 3911,+ },+ ],+ },+ ],});expect(custom).toEqual(file);