Skip to content

🎥 Make videos programmatically with React

av1 bitstreaming

Jonny Burger79b3366afb6e
diff --git a/packages/media-parser/av1.json b/packages/media-parser/av1.json
new file mode 100644
index 0000000000..16727bb557
--- /dev/null
+++ b/packages/media-parser/av1.json
@@ -0,0 +1,195 @@
+[
+ {
+ "type": "main-segment",
+ "children": [
+ {
+ "type": "seek-head-segment",
+ "length": 59,
+ "children": [
+ {
+ "type": "seek-segment",
+ "seekId": "0x1549a966",
+ "child": {
+ "type": "seek-position-segment",
+ "seekPosition": 161
+ }
+ },
+ {
+ "type": "seek-segment",
+ "seekId": "0x1654ae6b",
+ "child": {
+ "type": "seek-position-segment",
+ "seekPosition": 214
+ }
+ },
+ {
+ "type": "seek-segment",
+ "seekId": "0x1254c367",
+ "child": {
+ "type": "seek-position-segment",
+ "seekPosition": 322
+ }
+ },
+ {
+ "type": "seek-segment",
+ "seekId": "0x1c53bb6b",
+ "child": {
+ "type": "seek-position-segment",
+ "seekPosition": 347329
+ }
+ }
+ ]
+ },
+ {
+ "type": "void-segment",
+ "length": 88
+ },
+ {
+ "type": "info-segment",
+ "length": 48,
+ "children": [
+ {
+ "type": "timestamp-scale-segment",
+ "timestampScale": 1000000
+ },
+ {
+ "type": "muxing-app-segment",
+ "value": "Lavf60.3.100"
+ },
+ {
+ "type": "writing-app-segment",
+ "value": "Lavf60.3.100"
+ },
+ {
+ "type": "duration-segment",
+ "duration": 1000
+ }
+ ]
+ },
+ {
+ "type": "tracks-segment",
+ "children": [
+ {
+ "type": "track-entry-segment",
+ "children": [
+ {
+ "type": "track-number-segment",
+ "trackNumber": 1
+ },
+ {
+ "type": "track-uid-segment",
+ "trackUid": "ab2171012bb9020a"
+ },
+ {
+ "type": "flag-lacing-segment",
+ "lacing": false
+ },
+ {
+ "type": "language-segment",
+ "language": "und"
+ },
+ {
+ "type": "codec-segment",
+ "codec": "V_AV1"
+ },
+ {
+ "type": "track-type-segment",
+ "trackType": "video"
+ },
+ {
+ "type": "default-duration-segment",
+ "defaultDuration": 40000000
+ },
+ {
+ "type": "video-segment",
+ "children": [
+ {
+ "type": "width-segment",
+ "width": 1920
+ },
+ {
+ "type": "height-segment",
+ "height": 1080
+ },
+ {
+ "type": "color-segment",
+ "length": 16
+ }
+ ]
+ },
+ {
+ "type": "codec-private-segment",
+ "codecPrivateData": [
+ 129,
+ 8,
+ 12,
+ 0,
+ 10,
+ 14,
+ 0,
+ 0,
+ 0,
+ 66,
+ 171,
+ 191,
+ 195,
+ 118,
+ 0,
+ 8,
+ 8,
+ 8,
+ 8,
+ 32
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "type": "tags-segment",
+ "children": [
+ {
+ "type": "tag-segment",
+ "length": 31
+ },
+ {
+ "type": "tag-segment",
+ "length": 51
+ }
+ ]
+ },
+ {
+ "type": "cluster-segment",
+ "children": [
+ {
+ "type": "timestamp-segment",
+ "timestamp": 0
+ },
+ {
+ "type": "simple-block-segment",
+ "length": 279307,
+ "trackNumber": 1,
+ "timecode": 0,
+ "headerFlags": 128,
+ "keyframe": true,
+ "lacing": [
+ 0,
+ 0
+ ],
+ "invisible": false,
+ "children": null
+ },
+ {
+ "type": "unknown-segment",
+ "id": "0x"
+ }
+ ]
+ },
+ {
+ "type": "unknown-segment",
+ "id": "0x"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/packages/media-parser/src/av1-codec-string.ts b/packages/media-parser/src/av1-codec-string.ts
new file mode 100644
index 0000000000..e22cd09892
--- /dev/null
+++ b/packages/media-parser/src/av1-codec-string.ts
@@ -0,0 +1,19 @@
+// https://aomediacodec.github.io/av1-isobmff/#codecsparam
+
+import type {TrackEntrySegment} from './boxes/webm/segments/track-entry';
+
+export const av1CodecStringToString = (track: TrackEntrySegment): string => {
+ const codecSegment = track.children.find((b) => b.type === 'codec-segment');
+
+ if (!codecSegment || codecSegment.type !== 'codec-segment') {
+ throw new Error('Expected codec segment');
+ }
+
+ if (codecSegment.codec !== 'V_AV1') {
+ throw new Error(`Unknown codec: ${codecSegment.codec}`);
+ }
+
+ const str = 'av01.';
+
+ return str;
+};
diff --git a/packages/media-parser/src/bitstream/av1.ts b/packages/media-parser/src/bitstream/av1.ts
new file mode 100644
index 0000000000..b3a8c6fdb7
--- /dev/null
+++ b/packages/media-parser/src/bitstream/av1.ts
@@ -0,0 +1,10 @@
+import type {BufferIterator} from '../buffer-iterator';
+
+export const expectAv1Bitstream = (iterator: BufferIterator, size: number) => {
+ const offset = iterator.counter.getOffset();
+ const firstByte = iterator.getUint8();
+
+ const remaining = size - (iterator.counter.getOffset() - offset);
+ iterator.discard(remaining);
+ return null;
+};
diff --git a/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts b/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts
index 7feff8dbb0..032739d7d8 100644
--- a/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts
@@ -58,6 +58,10 @@ export const parseMdat = ({
const flatSamples = allTracks
.map((track) => {
+ if (!track.samplePositions) {
+ throw new Error('No sample positions');
+ }
+
return track.samplePositions.map((samplePosition) => {
return {
track,
diff --git a/packages/media-parser/src/boxes/webm/segments.ts b/packages/media-parser/src/boxes/webm/segments.ts
index 15778c2f34..17174835bd 100644
--- a/packages/media-parser/src/boxes/webm/segments.ts
+++ b/packages/media-parser/src/boxes/webm/segments.ts
@@ -123,7 +123,10 @@ export const expectSegment = (iterator: BufferIterator): MatroskaSegment => {
throw new Error('No bytes remaining');
}
+ const offset = iterator.counter.getOffset();
+ iterator.peek(10);
const segmentId = iterator.getMatroskaSegmentId();
+ console.log('offset', offset, segmentId);
if (segmentId === '0x') {
return {
diff --git a/packages/media-parser/src/boxes/webm/segments/track-entry.ts b/packages/media-parser/src/boxes/webm/segments/track-entry.ts
index 211dda989a..90d5b5db76 100644
--- a/packages/media-parser/src/boxes/webm/segments/track-entry.ts
+++ b/packages/media-parser/src/boxes/webm/segments/track-entry.ts
@@ -1,3 +1,4 @@
+import {expectAv1Bitstream} from '../../../bitstream/av1';
import type {BufferIterator} from '../../../buffer-iterator';
import type {MatroskaSegment} from '../segments';
import {expectChildren} from './parse-children';
@@ -127,9 +128,39 @@ export const parseCodecSegment = (iterator: BufferIterator): CodecSegment => {
};
};
+type TrackType =
+ | 'video'
+ | 'audio'
+ | 'complex'
+ | 'subtitle'
+ | 'button'
+ | 'control'
+ | 'metadata';
+
export type TrackTypeSegment = {
type: 'track-type-segment';
- trackType: number;
+ trackType: TrackType;
+};
+
+const trackTypeToString = (trackType: number): TrackType => {
+ switch (trackType) {
+ case 1:
+ return 'video';
+ case 2:
+ return 'audio';
+ case 3:
+ return 'complex';
+ case 4:
+ return 'subtitle';
+ case 5:
+ return 'button';
+ case 6:
+ return 'control';
+ case 7:
+ return 'metadata';
+ default:
+ throw new Error(`Unknown track type: ${trackType}`);
+ }
};
export const parseTrackTypeSegment = (
@@ -142,6 +173,8 @@ export const parseTrackTypeSegment = (
const trackType = iterator.getUint8();
+ const trackTypeString = trackTypeToString(trackType);
+
// Could make the return type nicer
/* 1 - video,
2 - audio,
@@ -154,7 +187,7 @@ export const parseTrackTypeSegment = (
*/
return {
type: 'track-type-segment',
- trackType,
+ trackType: trackTypeString,
};
};
@@ -468,14 +501,13 @@ export type SimpleBlockSegment = {
keyframe: boolean;
lacing: [number, number];
invisible: boolean;
- children: MatroskaSegment[];
+ children: null;
};
export const parseSimpleBlockSegment = (
iterator: BufferIterator,
): SimpleBlockSegment => {
const length = iterator.getVint();
- const offset = iterator.counter.getOffset();
const trackNumber = iterator.getVint();
const timecode = iterator.getUint16();
const headerFlags = iterator.getUint8();
@@ -485,9 +517,7 @@ export const parseSimpleBlockSegment = (
const pos7 = (headerFlags >> 6) & 1;
const keyframe = Boolean((headerFlags >> 7) & 1);
- const remaining = length - (iterator.counter.getOffset() - offset);
-
- const children = expectChildren(iterator, remaining);
+ const children = expectAv1Bitstream(iterator, length - 4);
return {
type: 'simple-block-segment',
@@ -498,6 +528,6 @@ export const parseSimpleBlockSegment = (
keyframe,
lacing: [pos6, pos7],
invisible,
- children,
+ children: null,
};
};
diff --git a/packages/media-parser/src/get-tracks.ts b/packages/media-parser/src/get-tracks.ts
index 9d752ab503..5cf95bca14 100644
--- a/packages/media-parser/src/get-tracks.ts
+++ b/packages/media-parser/src/get-tracks.ts
@@ -1,4 +1,7 @@
+import {av1CodecStringToString} from './av1-codec-string';
import type {MoovBox} from './boxes/iso-base-media/moov/moov';
+import type {MainSegment} from './boxes/webm/segments/main';
+import type {TrackEntrySegment} from './boxes/webm/segments/track-entry';
import {getAudioCodecStringFromTrak} from './get-audio-codec';
import {
getTimescaleAndDuration,
@@ -37,7 +40,7 @@ type SampleAspectRatio = {
export type VideoTrack = {
type: 'video';
- samplePositions: SamplePosition[];
+ samplePositions: SamplePosition[] | null;
trackId: number;
description: Uint8Array | null;
timescale: number;
@@ -51,7 +54,7 @@ export type VideoTrack = {
export type AudioTrack = {
type: 'audio';
- samplePositions: SamplePosition[];
+ samplePositions: SamplePosition[] | null;
trackId: number;
timescale: number;
codecString: string | null;
@@ -88,12 +91,157 @@ export const hasTracks = (segments: AnySegment[]): boolean => {
return tracks.length === numberOfTracks;
};
+const getMatroskaVideoCodecString = (track: TrackEntrySegment): string => {
+ const codec = track.children.find((b) => b.type === 'codec-segment');
+
+ if (!codec || codec.type !== 'codec-segment') {
+ throw new Error('Expected codec segment');
+ }
+
+ if (codec.codec === 'V_VP8') {
+ return 'vp8';
+ }
+
+ if (codec.codec === 'V_AV1') {
+ return av1CodecStringToString(track);
+ }
+
+ throw new Error(`Unknown codec: ${codec.codec}`);
+};
+
+const getMatroskaAudioCodecString = (track: TrackEntrySegment): string => {
+ const codec = track.children.find((b) => b.type === 'codec-segment');
+
+ if (!codec || codec.type !== 'codec-segment') {
+ throw new Error('Expected codec segment');
+ }
+
+ if (codec.codec === 'A_OPUS') {
+ return 'opus';
+ }
+
+ throw new Error(`Unknown codec: ${codec.codec}`);
+};
+
+const getTracksFromMatroska = (
+ segment: MainSegment,
+): {videoTracks: VideoTrack[]; audioTracks: AudioTrack[]} => {
+ const tracksSegment = segment.children.find(
+ (b) => b.type === 'tracks-segment',
+ );
+ if (!tracksSegment || tracksSegment.type !== 'tracks-segment') {
+ throw new Error('No tracks segment');
+ }
+
+ const infoSegment = segment.children.find((b) => b.type === 'info-segment');
+
+ if (!infoSegment || infoSegment.type !== 'info-segment') {
+ throw new Error('No info segment');
+ }
+
+ const timescale = infoSegment.children.find(
+ (b) => b.type === 'timestamp-scale-segment',
+ );
+
+ if (!timescale || timescale.type !== 'timestamp-scale-segment') {
+ throw new Error('No timescale segment');
+ }
+
+ const videoTracks: VideoTrack[] = [];
+ const audioTracks: AudioTrack[] = [];
+
+ for (const track of tracksSegment.children) {
+ if (track.type !== 'track-entry-segment') {
+ throw new Error('Expected track entry segment');
+ }
+
+ const trackType = track.children.find(
+ (b) => b.type === 'track-type-segment',
+ );
+
+ if (!trackType || trackType.type !== 'track-type-segment') {
+ throw new Error('Expected track type segment');
+ }
+
+ const trackId = track.children.find(
+ (b) => b.type === 'track-number-segment',
+ );
+
+ if (!trackId || trackId.type !== 'track-number-segment') {
+ throw new Error('Expected track id segment');
+ }
+
+ if (trackType.trackType === 'video') {
+ const videoSegment = track.children.find(
+ (b) => b.type === 'video-segment',
+ );
+
+ if (!videoSegment || videoSegment.type !== 'video-segment') {
+ throw new Error('Expected video segment');
+ }
+
+ const width = videoSegment.children.find(
+ (b) => b.type === 'width-segment',
+ );
+
+ if (!width || width.type !== 'width-segment') {
+ throw new Error('Expected width segment');
+ }
+
+ const height = videoSegment.children.find(
+ (b) => b.type === 'height-segment',
+ );
+
+ if (!height || height.type !== 'height-segment') {
+ throw new Error('Expected height segment');
+ }
+
+ videoTracks.push({
+ type: 'video',
+ trackId: trackId.trackNumber,
+ codecString: getMatroskaVideoCodecString(track),
+ description: null,
+ height: height.height,
+ width: width.width,
+ sampleAspectRatio: {
+ numerator: 1,
+ denominator: 1,
+ },
+ timescale: timescale.timestampScale,
+ samplePositions: [],
+ untransformedHeight: height.height,
+ untransformedWidth: width.width,
+ });
+ }
+
+ if (trackType.trackType === 'audio') {
+ audioTracks.push({
+ type: 'audio',
+ trackId: trackId.trackNumber,
+ codecString: getMatroskaAudioCodecString(track),
+ samplePositions: null,
+ timescale: timescale.timestampScale,
+ });
+ }
+ }
+
+ return {
+ videoTracks,
+ audioTracks,
+ };
+};
+
export const getTracks = (
segments: AnySegment[],
): {
videoTracks: VideoTrack[];
audioTracks: AudioTrack[];
} => {
+ const mainSegment = segments.find((s) => s.type === 'main-segment');
+ if (mainSegment && mainSegment.type === 'main-segment') {
+ return getTracksFromMatroska(mainSegment);
+ }
+
const moovBox = getMoovBox(segments);
if (!moovBox) {
return {
diff --git a/packages/media-parser/src/test/matroska.test.ts b/packages/media-parser/src/test/matroska.test.ts
index 5a2606d6c5..d39f3a6d7c 100644
--- a/packages/media-parser/src/test/matroska.test.ts
+++ b/packages/media-parser/src/test/matroska.test.ts
@@ -117,7 +117,7 @@ test('Should get duration of AV1 video', async () => {
},
{
type: 'track-type-segment',
- trackType: 1,
+ trackType: 'video',
},
{
type: 'default-duration-segment',
diff --git a/packages/media-parser/src/test/stream-local.test.ts b/packages/media-parser/src/test/stream-local.test.ts
index a704b06344..6a88a08675 100644
--- a/packages/media-parser/src/test/stream-local.test.ts
+++ b/packages/media-parser/src/test/stream-local.test.ts
@@ -70,12 +70,14 @@ test('Should stream AV1 with no duration', async () => {
videoCodec: true,
audioCodec: true,
rotation: true,
+ tracks: true,
boxes: true,
- // TODO: Return WebM tracks
},
reader: nodeReader,
});
+ await Bun.write('av1.json', JSON.stringify(parsed.boxes, null, 2));
+
expect(parsed.durationInSeconds).toBe(1);
expect(parsed.fps).toBe(null);
expect(parsed.dimensions).toEqual({
@@ -85,6 +87,27 @@ test('Should stream AV1 with no duration', async () => {
expect(parsed.videoCodec).toBe('av1');
expect(parsed.audioCodec).toBe(null);
expect(parsed.rotation).toBe(0);
+ expect(parsed.videoTracks.length).toBe(1);
+ expect(parsed.videoTracks[0]).toEqual({
+ type: 'video',
+ // TODO: it is the wrong one
+ // <sample entry 4CC>.<profile>.<level><tier>.<bitDepth>.<monochrome>.<chromaSubsampling>.
+ // <colorPrimaries>.<transferCharacteristics>.<matrixCoefficients>.<videoFullRangeFlag>
+ codecString: 'av01.',
+ description: null,
+ sampleAspectRatio: {
+ denominator: 1,
+ numerator: 1,
+ },
+ samplePositions: [],
+ timescale: 1000000,
+ trackId: 1,
+ untransformedHeight: 1080,
+ untransformedWidth: 1920,
+ height: 1080,
+ width: 1920,
+ });
+ expect(parsed.audioTracks.length).toBe(0);
});
test('Should stream corrupted video', async () => {
@@ -181,6 +204,8 @@ test('Should stream variable fps video', async () => {
audioCodec: true,
rotation: true,
unrotatedDimension: true,
+ tracks: true,
+ boxes: true,
},
reader: nodeReader,
});
@@ -193,6 +218,31 @@ test('Should stream variable fps video', async () => {
expect(parsed.videoCodec).toBe('vp8');
expect(parsed.audioCodec).toBe('opus');
expect(parsed.rotation).toBe(0);
+ expect(parsed.videoTracks.length).toBe(1);
+ expect(parsed.videoTracks[0]).toEqual({
+ type: 'video',
+ codecString: 'vp8',
+ description: null,
+ sampleAspectRatio: {
+ denominator: 1,
+ numerator: 1,
+ },
+ samplePositions: [],
+ timescale: 1000000,
+ trackId: 2,
+ untransformedHeight: 720,
+ untransformedWidth: 1280,
+ height: 720,
+ width: 1280,
+ });
+ expect(parsed.audioTracks.length).toBe(1);
+ expect(parsed.audioTracks[0]).toEqual({
+ type: 'audio',
+ codecString: 'opus',
+ samplePositions: null,
+ timescale: 1000000,
+ trackId: 1,
+ });
});
test('Should stream MKV video', async () => {
@@ -292,13 +342,10 @@ test('Custom DAR', async () => {
dimensions: true,
rotation: true,
unrotatedDimension: true,
- boxes: true,
},
reader: nodeReader,
});
- await Bun.write('dar.json', JSON.stringify(parsed.boxes, null, 2));
-
expect(parsed.videoTracks[0].sampleAspectRatio).toEqual({
numerator: 56,
denominator: 177,