Skip to content

🎥 Make videos programmatically with React

`@remotion/renderer`: Simplify video parser

Jonny Burger5e81aa43216c
diff --git a/packages/video-parser/src/boxes/iso-base-media/mvhd.ts b/packages/video-parser/src/boxes/iso-base-media/mvhd.ts
index 344b0400a2..83a8fb97ab 100644
--- a/packages/video-parser/src/boxes/iso-base-media/mvhd.ts
+++ b/packages/video-parser/src/boxes/iso-base-media/mvhd.ts
@@ -1,3 +1,4 @@
+import {getArrayBufferIterator} from '../../read-and-increment-offset';
import type {BaseBox} from './base-type';
import {toUnixTimestamp} from './to-date';
@@ -27,79 +28,65 @@ export interface MvhdBox extends BaseBox {
}
export const parseMvhd = (data: ArrayBuffer, offset: number): MvhdBox => {
- let chunkOffset = 0;
-
- const view = new DataView(data);
- const size = view.getUint32(chunkOffset);
- chunkOffset += 4;
- const atom = data.slice(chunkOffset, chunkOffset + 4);
- const atomString = new TextDecoder().decode(atom);
- if (atomString !== 'mvhd') {
- throw new Error(`Expected mvhd atom, got ${atomString}`);
+ const iterator = getArrayBufferIterator(data, 0);
+ const size = iterator.getUint32();
+ const atom = iterator.getAtom();
+ if (atom !== 'mvhd') {
+ throw new Error(`Expected mvhd atom, got ${atom}`);
}
- chunkOffset += 4;
- const version = view.getUint8(chunkOffset);
+ const version = iterator.getUint8();
if (version !== 0) {
throw new Error(`Unsupported MVHD version ${version}`);
}
- chunkOffset += 1;
-
if (size !== 108) {
throw new Error(`Expected mvhd size of version 0 to be 108, got ${size}`);
}
// Flags, we discard them
- data.slice(chunkOffset, chunkOffset + 3);
- chunkOffset += 3;
+ iterator.discard(3);
- const creationTime = view.getUint32(chunkOffset);
- chunkOffset += 4;
+ const creationTime = iterator.getUint32();
- const modificationTime = view.getUint32(chunkOffset);
- chunkOffset += 4;
+ const modificationTime = iterator.getUint32();
- const timeScale = view.getUint32(chunkOffset);
- chunkOffset += 4;
+ const timeScale = iterator.getUint32();
- const durationInUnits = view.getUint32(chunkOffset);
+ const durationInUnits = iterator.getUint32();
const durationInSeconds = durationInUnits / timeScale;
- chunkOffset += 4;
- const rateArray = data.slice(chunkOffset, chunkOffset + 4);
- const rateView = new DataView(rateArray);
+ const rateArray = iterator.getSlice(4);
+ const rateView = getArrayBufferIterator(rateArray, 0);
const rate =
- rateView.getInt8(0) * 10 +
- rateView.getInt8(1) +
- rateView.getInt8(2) * 0.1 +
- rateView.getInt8(3) * 0.01;
- chunkOffset += 4;
+ rateView.getInt8() * 10 +
+ rateView.getInt8() +
+ rateView.getInt8() * 0.1 +
+ rateView.getInt8() * 0.01;
+
+ const volumeArray = iterator.getSlice(2);
+ const volumeView = getArrayBufferIterator(volumeArray, 0);
- const volumeArray = data.slice(chunkOffset, chunkOffset + 2);
- const volumeView = new DataView(volumeArray);
- chunkOffset += 2;
- const volume = volumeView.getInt8(0) + volumeView.getInt8(1) * 0.1;
+ const volume = volumeView.getInt8() + volumeView.getInt8() * 0.1;
// reserved 16bit
- chunkOffset += 2;
+ iterator.discard(2);
// reserved 32bit x2
- chunkOffset += 4 * 2;
+ iterator.discard(4);
+ iterator.discard(4);
// matrix
const matrix: number[] = [];
for (let i = 0; i < 9; i++) {
- matrix.push(view.getUint32(chunkOffset));
- chunkOffset += 4;
+ matrix.push(iterator.getUint32());
}
// pre-defined
- chunkOffset += 4 * 6;
+ iterator.discard(4 * 6);
// next track id
- const nextTrackId = view.getUint32(chunkOffset);
- chunkOffset += 4;
+ const nextTrackId = iterator.getUint32();
return {
creationTime: toUnixTimestamp(creationTime),
diff --git a/packages/video-parser/src/boxes/webm/parse-webm-header.ts b/packages/video-parser/src/boxes/webm/parse-webm-header.ts
new file mode 100644
index 0000000000..9137d2eaa5
--- /dev/null
+++ b/packages/video-parser/src/boxes/webm/parse-webm-header.ts
@@ -0,0 +1,10 @@
+import {getArrayBufferIterator} from '../../read-and-increment-offset';
+
+export const parseWebmHeader = (data: ArrayBuffer) => {
+ const counter = getArrayBufferIterator(data, 4);
+ const length = counter.getEBML();
+
+ if (length !== 31) {
+ throw new Error(`Expected header length 31, got ${length}`);
+ }
+};
diff --git a/packages/video-parser/src/parse-video.ts b/packages/video-parser/src/parse-video.ts
index 6f14243d1a..fcac5a1b35 100644
--- a/packages/video-parser/src/parse-video.ts
+++ b/packages/video-parser/src/parse-video.ts
@@ -9,6 +9,7 @@ import type {MebxBox} from './boxes/iso-base-media/stsd/mebx';
import type {StsdBox} from './boxes/iso-base-media/stsd/stsd';
import type {TkhdBox} from './boxes/iso-base-media/tkhd';
import type {TrakBox} from './boxes/iso-base-media/trak/trak';
+import {parseWebmHeader} from './boxes/webm/parse-webm-header';
interface RegularBox extends BaseBox {
boxType: string;
@@ -36,6 +37,7 @@ export type BoxAndNext = {
};
const isoBaseMediaMp4Pattern = Buffer.from('ftyp');
+const webmPattern = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
const matchesPattern = (pattern: Buffer) => {
return (data: Buffer) => {
@@ -71,5 +73,9 @@ export const parseVideo = async (
return parseBoxes(new Uint8Array(data).buffer as unknown as ArrayBuffer, 0);
}
+ if (matchesPattern(webmPattern)(data.subarray(0, 4))) {
+ parseWebmHeader(new Uint8Array(data).buffer as unknown as ArrayBuffer);
+ }
+
return [];
};
diff --git a/packages/video-parser/src/read-and-increment-offset.ts b/packages/video-parser/src/read-and-increment-offset.ts
new file mode 100644
index 0000000000..533ebfad03
--- /dev/null
+++ b/packages/video-parser/src/read-and-increment-offset.ts
@@ -0,0 +1,72 @@
+export class OffsetCounter {
+ #offset: number;
+ constructor(initial: number) {
+ this.#offset = initial;
+ }
+
+ increment(amount: number) {
+ this.#offset += amount;
+ }
+
+ getOffset(): number {
+ return this.#offset;
+ }
+}
+
+const makeOffsetCounter = (initial: number): OffsetCounter => {
+ return new OffsetCounter(initial);
+};
+
+export const getArrayBufferIterator = (
+ data: ArrayBuffer,
+ initialOffset: number,
+) => {
+ const view = new DataView(data);
+ const counter = makeOffsetCounter(initialOffset);
+
+ const getSlice = (amount: number) => {
+ const value = data.slice(counter.getOffset(), counter.getOffset() + amount);
+ counter.increment(amount);
+ return value;
+ };
+
+ const getUint8 = () => {
+ const val = view.getUint8(counter.getOffset());
+ counter.increment(1);
+ return val;
+ };
+
+ return {
+ view,
+ counter,
+ data,
+ discard: (length: number) => {
+ counter.increment(length);
+ },
+ getSlice,
+ getAtom: () => {
+ const atom = getSlice(4);
+ return new TextDecoder().decode(atom);
+ },
+ getUint8,
+ getEBML: () => {
+ const val = getUint8();
+
+ // https://darkcoding.net/software/reading-mediarecorders-webm-opus-output/#:~:text=The%20first%20four%20bytes%20(%201A,%E2%80%93%20read%20on%20for%20why).
+ // You drop the initial 0 bits and the first 1 bit to get the value. 0x81 is 0b10000001, so there are zero inital 0 bits, meaning length one byte, and the value is 1. The 0x9F value for length of the EBML header we saw earlier is 0b10011111, still one byte, value is 0b0011111, which is 31 (the python repl is very helpful for these conversions).
+ const actualValue = val & 0x7f; // 0x7F is binary 01111111, which masks out the first bit
+
+ return actualValue;
+ },
+ getInt8: () => {
+ const val = view.getInt8(counter.getOffset());
+ counter.increment(1);
+ return val;
+ },
+ getUint32: () => {
+ const val = view.getUint32(counter.getOffset());
+ counter.increment(4);
+ return val;
+ },
+ };
+};
diff --git a/packages/video-parser/src/test/dimensions.test.ts b/packages/video-parser/src/test/dimensions.test.ts
deleted file mode 100644
index 7f4f7cd558..0000000000
--- a/packages/video-parser/src/test/dimensions.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import {test} from 'bun:test';
-
-test('Get dimensions of a video', () => {});
diff --git a/packages/video-parser/src/test/duration.test.ts b/packages/video-parser/src/test/duration.test.ts
index a6ceaa7eb2..ff65957f7c 100644
--- a/packages/video-parser/src/test/duration.test.ts
+++ b/packages/video-parser/src/test/duration.test.ts
@@ -6,31 +6,20 @@ import {exampleVideos} from './example-videos';
test('Should get duration of video', async () => {
const parsed = await parseVideo(exampleVideos.framer24fps, 128 * 1024);
- if (!parsed) {
- throw new Error('No parsed data');
- }
- const duration = getDuration(parsed);
- expect(duration).toBe(4.167);
-
- const dimensions = getDimensions(parsed);
- expect(dimensions).toEqual([1080, 1080]);
+ expect(getDuration(parsed)).toBe(4.167);
+ expect(getDimensions(parsed)).toEqual([1080, 1080]);
});
test('Should get duration of HEVC video', async () => {
const parsed = await parseVideo(exampleVideos.iphonehevc, Infinity);
- if (!parsed) {
- throw new Error('No parsed data');
- }
-
- const moovBox = parsed[3];
- if (moovBox.type !== 'moov-box') {
- throw new Error('Expected regular box');
- }
- const duration = getDuration(parsed);
- expect(duration).toBe(3.4);
+ expect(getDuration(parsed)).toBe(3.4);
+ expect(getDimensions(parsed)).toEqual([1920, 1080]);
+});
- const dimensions = getDimensions(parsed);
- expect(dimensions).toEqual([1920, 1080]);
+test('Should get duration of AV1 video', async () => {
+ const parsed = await parseVideo(exampleVideos.av1, Infinity);
+ // TODO: AV1 duration is not yet supported
+ expect(getDuration(parsed)).toBe(null);
});