Skip to content

🎥 Make videos programmatically with React

not bad!

Jonny Burger5d1fa14edf88
diff --git a/packages/media-parser/src/containers/m3u/after-manifest-fetch.ts b/packages/media-parser/src/containers/m3u/after-manifest-fetch.ts
new file mode 100644
index 0000000000..e47200a368
--- /dev/null
+++ b/packages/media-parser/src/containers/m3u/after-manifest-fetch.ts
@@ -0,0 +1,85 @@
+import {registerTrack} from '../../register-track';
+import type {M3uState} from '../../state/m3u-state';
+import type {ParserState} from '../../state/parser-state';
+import {fetchM3u8Stream} from './fetch-m3u8-stream';
+import {getStreams} from './get-streams';
+import {iteratorOverTsFiles} from './return-packets';
+import {selectStream} from './select-stream';
+import type {M3uStructure} from './types';
+
+export const afterManifestFetch = async ({
+ structure,
+ m3uState,
+ state,
+ src,
+}: {
+ structure: M3uStructure;
+ m3uState: M3uState;
+ state: ParserState;
+ src: string | null;
+}) => {
+ const streams = getStreams(structure, src);
+
+ const selectedStream = await selectStream(streams);
+ m3uState.setSelectedStream(selectedStream);
+
+ if (!selectedStream.box.resolution) {
+ throw new Error('Stream does not have a resolution');
+ }
+
+ const boxes = await fetchM3u8Stream(selectedStream);
+ structure.boxes.push({type: 'm3u-playlist', boxes});
+ await iteratorOverTsFiles({
+ playlistUrl: selectedStream.url,
+ structure,
+ onDoneWithTracks() {
+ state.callbacks.tracks.setIsDone(state.logLevel);
+ },
+ onAudioTrack: async (track) => {
+ await registerTrack({
+ container: 'm3u8',
+ state,
+ track: {
+ type: 'audio',
+ codec: track.codec,
+ codecPrivate: track.codecPrivate,
+ codecWithoutConfig: track.codecWithoutConfig,
+ description: track.description,
+ numberOfChannels: track.numberOfChannels,
+ sampleRate: track.sampleRate,
+ timescale: track.timescale,
+ trackId: track.trackId,
+ trakBox: track.trakBox,
+ },
+ });
+ },
+ onVideoTrack: async (track) => {
+ await registerTrack({
+ container: 'm3u8',
+ state,
+ track: {
+ type: 'video',
+ // Explicitly copying everything over so we don't forget to change anything if necessary
+ codec: track.codec,
+ codecPrivate: track.codecPrivate,
+ codecWithoutConfig: track.codecWithoutConfig,
+ codedHeight: track.codedHeight,
+ codedWidth: track.codedWidth,
+ color: track.color,
+ description: track.description,
+ displayAspectHeight: track.displayAspectHeight,
+ displayAspectWidth: track.displayAspectWidth,
+ fps: track.fps,
+ height: track.height,
+ rotation: track.rotation,
+ sampleAspectRatio: track.sampleAspectRatio,
+ timescale: track.timescale,
+ trackId: track.trackId,
+ trakBox: track.trakBox,
+ width: track.width,
+ },
+ });
+ },
+ m3uState,
+ });
+};
diff --git a/packages/media-parser/src/containers/m3u/fetch-m3u8-stream.ts b/packages/media-parser/src/containers/m3u/fetch-m3u8-stream.ts
index 3093a25919..10fc0ef1c6 100644
--- a/packages/media-parser/src/containers/m3u/fetch-m3u8-stream.ts
+++ b/packages/media-parser/src/containers/m3u/fetch-m3u8-stream.ts
@@ -2,7 +2,7 @@ import type {M3uStream} from './get-streams';
import {parseM3u8Text} from './parse-m3u8-text';
import type {M3uBox} from './types';
-export const fetchM3u8Stream = async (stream: M3uStream) => {
+export const fetchM3u8Stream = async (stream: M3uStream): Promise<M3uBox[]> => {
const res = await fetch(stream.url);
const text = await res.text();
const lines = text.split('\n');
@@ -11,5 +11,5 @@ export const fetchM3u8Stream = async (stream: M3uStream) => {
parseM3u8Text(line, boxes);
}
- console.log({boxes});
+ return boxes;
};
diff --git a/packages/media-parser/src/containers/m3u/get-chunks.ts b/packages/media-parser/src/containers/m3u/get-chunks.ts
new file mode 100644
index 0000000000..7a81c801bc
--- /dev/null
+++ b/packages/media-parser/src/containers/m3u/get-chunks.ts
@@ -0,0 +1,26 @@
+import type {M3uPlaylist} from './types';
+
+export type M3uChunk = {
+ duration: number;
+ url: string;
+};
+
+export const getChunks = (playlist: M3uPlaylist) => {
+ const chunks: M3uChunk[] = [];
+ for (let i = 0; i < playlist.boxes.length; i++) {
+ const box = playlist.boxes[i];
+ if (box.type === 'm3u-extinf') {
+ const nextBox = playlist.boxes[i + 1];
+ i++;
+ if (nextBox.type !== 'm3u-text-value') {
+ throw new Error('Expected m3u-text-value');
+ }
+
+ chunks.push({duration: box.value, url: nextBox.value});
+ }
+
+ continue;
+ }
+
+ return chunks;
+};
diff --git a/packages/media-parser/src/containers/m3u/get-duration-from-m3u.ts b/packages/media-parser/src/containers/m3u/get-duration-from-m3u.ts
new file mode 100644
index 0000000000..4d04703050
--- /dev/null
+++ b/packages/media-parser/src/containers/m3u/get-duration-from-m3u.ts
@@ -0,0 +1,8 @@
+import {getDurationFromPlaylist, getPlaylist} from './get-playlist';
+import type {M3uStructure} from './types';
+
+export const getDurationFromM3u = (structure: M3uStructure): number | null => {
+ const playlist = getPlaylist(structure);
+
+ return getDurationFromPlaylist(playlist);
+};
diff --git a/packages/media-parser/src/containers/m3u/get-playlist.ts b/packages/media-parser/src/containers/m3u/get-playlist.ts
new file mode 100644
index 0000000000..4ba388f275
--- /dev/null
+++ b/packages/media-parser/src/containers/m3u/get-playlist.ts
@@ -0,0 +1,23 @@
+import type {M3uPlaylist, M3uStructure} from './types';
+
+export const getPlaylist = (structure: M3uStructure) => {
+ const playlists = structure.boxes.filter(
+ (box) => box.type === 'm3u-playlist',
+ );
+ if (playlists.length !== 1) {
+ throw new Error('Expected one playlist');
+ }
+
+ return playlists[0];
+};
+
+export const getDurationFromPlaylist = (playlist: M3uPlaylist): number => {
+ const duration = playlist.boxes.find(
+ (box) => box.type === 'm3u-target-duration',
+ );
+ if (!duration) {
+ throw new Error('Expected duration in m3u playlist');
+ }
+
+ return duration.duration;
+};
diff --git a/packages/media-parser/src/containers/m3u/get-streams.ts b/packages/media-parser/src/containers/m3u/get-streams.ts
index aa5c9d3352..02f9e49abd 100644
--- a/packages/media-parser/src/containers/m3u/get-streams.ts
+++ b/packages/media-parser/src/containers/m3u/get-streams.ts
@@ -5,7 +5,10 @@ export type M3uStream = {
box: M3uStreamInfo;
};
-export const getStreams = (structure: M3uStructure): M3uStream[] => {
+export const getStreams = (
+ structure: M3uStructure,
+ originalSrc: string | null,
+): M3uStream[] => {
const boxes: M3uStream[] = [];
for (let i = 0; i < structure.boxes.length; i++) {
@@ -17,7 +20,7 @@ export const getStreams = (structure: M3uStructure): M3uStream[] => {
}
boxes.push({
- url: next.value,
+ url: originalSrc ? new URL(next.value, originalSrc).href : next.value,
box: str,
});
}
diff --git a/packages/media-parser/src/containers/m3u/return-packets.ts b/packages/media-parser/src/containers/m3u/return-packets.ts
new file mode 100644
index 0000000000..31ddd3955e
--- /dev/null
+++ b/packages/media-parser/src/containers/m3u/return-packets.ts
@@ -0,0 +1,57 @@
+import type {AudioTrack, VideoTrack} from '../../get-tracks';
+import {parseMedia} from '../../parse-media';
+import type {M3uState} from '../../state/m3u-state';
+import {getChunks} from './get-chunks';
+import {getPlaylist} from './get-playlist';
+import type {M3uStructure} from './types';
+
+export const iteratorOverTsFiles = async ({
+ structure,
+ onVideoTrack,
+ m3uState,
+ onAudioTrack,
+ onDoneWithTracks,
+ playlistUrl,
+}: {
+ structure: M3uStructure;
+ onVideoTrack: (track: VideoTrack) => Promise<void>;
+ onAudioTrack: (track: AudioTrack) => Promise<void>;
+ onDoneWithTracks: () => void;
+ m3uState: M3uState;
+ playlistUrl: string;
+}) => {
+ const playlist = getPlaylist(structure);
+ const chunks = getChunks(playlist);
+
+ // TODO: Be able to pause / resume / cancel / seek
+ for (const chunk of chunks) {
+ const src = new URL(chunk.url, playlistUrl).toString();
+ await parseMedia({
+ src,
+ acknowledgeRemotionLicense: true,
+ onTracks: () => {
+ if (!m3uState.hasEmittedDoneWithTracks()) {
+ m3uState.setHasEmittedDoneWithTracks();
+ onDoneWithTracks();
+ return null;
+ }
+ },
+ onAudioTrack: async ({track}) => {
+ if (m3uState.hasEmittedAudioTrack()) {
+ m3uState.setHasEmittedAudioTrack();
+ await onAudioTrack(track);
+ }
+
+ return null;
+ },
+ onVideoTrack: async ({track}) => {
+ if (!m3uState.hasEmittedVideoTrack()) {
+ m3uState.setHasEmittedVideoTrack();
+ await onVideoTrack(track);
+ }
+
+ return null;
+ },
+ });
+ }
+};
diff --git a/packages/media-parser/src/containers/m3u/select-stream.ts b/packages/media-parser/src/containers/m3u/select-stream.ts
new file mode 100644
index 0000000000..85393f8b30
--- /dev/null
+++ b/packages/media-parser/src/containers/m3u/select-stream.ts
@@ -0,0 +1,11 @@
+import type {M3uStream} from './get-streams';
+
+export const selectStream = (streams: M3uStream[]) => {
+ if (!streams.length) {
+ throw new Error('No streams found');
+ }
+
+ // TODO: Select the first stream for now
+ const selectedStream = streams[0];
+ return Promise.resolve(selectedStream);
+};
diff --git a/packages/media-parser/src/containers/m3u/types.ts b/packages/media-parser/src/containers/m3u/types.ts
index 30b54ac94e..52a40aff8f 100644
--- a/packages/media-parser/src/containers/m3u/types.ts
+++ b/packages/media-parser/src/containers/m3u/types.ts
@@ -21,6 +21,11 @@ export type M3uPlaylistType = {
playlistType: string;
};
+export type M3uPlaylist = {
+ type: 'm3u-playlist';
+ boxes: M3uBox[];
+};
+
export type M3uExtInf = {
type: 'm3u-extinf';
value: number;
@@ -48,6 +53,7 @@ export type M3uTextValue = {
export type M3uBox =
| M3uHeader
+ | M3uPlaylist
| M3uVersion
| M3uIndependentSegments
| M3uStreamInfo
diff --git a/packages/media-parser/src/get-duration.ts b/packages/media-parser/src/get-duration.ts
index cc2877c8f1..54fd4f3984 100644
--- a/packages/media-parser/src/get-duration.ts
+++ b/packages/media-parser/src/get-duration.ts
@@ -6,6 +6,7 @@ import {
getMoovBox,
getMvhdBox,
} from './containers/iso-base-media/traversal';
+import {getDurationFromM3u} from './containers/m3u/get-duration-from-m3u';
import {getDurationFromMp3} from './containers/mp3/get-duration';
import {getDurationFromAvi} from './containers/riff/get-duration';
import {getDurationFromWav} from './containers/wav/get-duration-from-wav';
@@ -132,7 +133,7 @@ export const getDuration = (parserState: ParserState): number | null => {
}
if (structure.type === 'm3u') {
- throw new Error('No duration for m3u');
+ return getDurationFromM3u(parserState.getM3uStructure());
}
throw new Error('Has no duration ' + (structure satisfies never));
diff --git a/packages/media-parser/src/get-fps.ts b/packages/media-parser/src/get-fps.ts
index 74b9c19090..1263f41ac5 100644
--- a/packages/media-parser/src/get-fps.ts
+++ b/packages/media-parser/src/get-fps.ts
@@ -155,8 +155,9 @@ export const getFps = (state: ParserState) => {
return null;
}
+ // Same as
if (segments.type === 'm3u') {
- throw new Error('Cannot get fps from m3u');
+ return null;
}
if (
diff --git a/packages/media-parser/src/get-tracks.ts b/packages/media-parser/src/get-tracks.ts
index 1c49e4aa8b..8cf52cbdd3 100644
--- a/packages/media-parser/src/get-tracks.ts
+++ b/packages/media-parser/src/get-tracks.ts
@@ -243,7 +243,7 @@ export const defaultGetTracks = (parserState: ParserState): AllTracks => {
return {
audioTracks: tracks.filter((t) => t.type === 'audio'),
otherTracks: [],
- videoTracks: [],
+ videoTracks: tracks.filter((t) => t.type === 'video'),
};
};
@@ -278,14 +278,11 @@ export const getTracks = (state: ParserState): AllTracks => {
structure.type === 'mp3' ||
structure.type === 'wav' ||
structure.type === 'flac' ||
- structure.type === 'aac'
+ structure.type === 'aac' ||
+ structure.type === 'm3u'
) {
return defaultGetTracks(state);
}
- if (structure.type === 'm3u') {
- return defaultGetTracks(state);
- }
-
throw new Error(`Unknown container${structure satisfies never}`);
};
diff --git a/packages/media-parser/src/is-audio-structure.ts b/packages/media-parser/src/is-audio-structure.ts
index 2abc6666c6..e4a6a234d6 100644
--- a/packages/media-parser/src/is-audio-structure.ts
+++ b/packages/media-parser/src/is-audio-structure.ts
@@ -34,7 +34,7 @@ export const isAudioStructure = (structure: Structure) => {
}
if (structure.type === 'm3u') {
- return true;
+ return false;
}
throw new Error(`Unhandled structure type: ${structure satisfies never}`);
diff --git a/packages/media-parser/src/metadata/get-metadata.ts b/packages/media-parser/src/metadata/get-metadata.ts
index 9916c4885c..8a4b0fa3a1 100644
--- a/packages/media-parser/src/metadata/get-metadata.ts
+++ b/packages/media-parser/src/metadata/get-metadata.ts
@@ -23,7 +23,7 @@ export const getMetadata = (state: ParserState): MetadataEntry[] => {
return getMetadataFromRiff(structure);
}
- if (structure.type === 'transport-stream') {
+ if (structure.type === 'transport-stream' || structure.type === 'm3u') {
return [];
}
@@ -48,7 +48,11 @@ export const getMetadata = (state: ParserState): MetadataEntry[] => {
return getMetadataFromFlac(structure) ?? [];
}
- return getMetadataFromIsoBase(state);
+ if (structure.type === 'iso-base-media') {
+ return getMetadataFromIsoBase(state);
+ }
+
+ throw new Error('Unknown container ' + (structure as never));
};
export const hasMetadata = (structure: Structure): boolean => {
diff --git a/packages/media-parser/src/run-parse-iteration.ts b/packages/media-parser/src/run-parse-iteration.ts
index 9ed27970bf..579f3ec292 100644
--- a/packages/media-parser/src/run-parse-iteration.ts
+++ b/packages/media-parser/src/run-parse-iteration.ts
@@ -1,8 +1,7 @@
import {parseAac} from './containers/aac/parse-aac';
import {parseFlac} from './containers/flac/parse-flac';
import {parseIsoBaseMedia} from './containers/iso-base-media/parse-boxes';
-import {fetchM3u8Stream} from './containers/m3u/fetch-m3u8-stream';
-import {getStreams} from './containers/m3u/get-streams';
+import {afterManifestFetch} from './containers/m3u/after-manifest-fetch';
import {parseM3u} from './containers/m3u/parse-m3u';
import {parseMp3} from './containers/mp3/parse-mp3';
import {parseRiff} from './containers/riff/parse-riff';
@@ -68,18 +67,19 @@ export const runParseIteration = async ({
}
if (structure.type === 'm3u') {
- const box = parseM3u({
+ const box = await parseM3u({
iterator: state.iterator,
structure,
contentLength: state.contentLength,
});
const isDoneNow = state.iterator.counter.getOffset() === contentLength;
if (isDoneNow) {
- const streams = getStreams(structure);
-
- // TODO: Select the first stream for now
- const selectedStream = streams[0];
- await fetchM3u8Stream(selectedStream);
+ await afterManifestFetch({
+ structure,
+ m3uState: state.m3u,
+ state,
+ src: typeof state.src === 'string' ? state.src : null,
+ });
}
return box;
diff --git a/packages/media-parser/src/state/m3u-state.ts b/packages/media-parser/src/state/m3u-state.ts
new file mode 100644
index 0000000000..32f25a485c
--- /dev/null
+++ b/packages/media-parser/src/state/m3u-state.ts
@@ -0,0 +1,29 @@
+import type {M3uStream} from '../containers/m3u/get-streams';
+
+export const m3uState = () => {
+ let selectedStream: M3uStream | null = null;
+ let hasEmittedVideoTrack = false;
+ let hasEmittedAudioTrack = false;
+ let hasEmittedDoneWithTracks = false;
+
+ return {
+ setSelectedStream: (stream: M3uStream) => {
+ selectedStream = stream;
+ },
+ getSelectedStream: () => selectedStream,
+ setHasEmittedVideoTrack: () => {
+ hasEmittedVideoTrack = true;
+ },
+ hasEmittedVideoTrack: () => hasEmittedVideoTrack,
+ setHasEmittedAudioTrack: () => {
+ hasEmittedAudioTrack = true;
+ },
+ hasEmittedAudioTrack: () => hasEmittedAudioTrack,
+ setHasEmittedDoneWithTracks: () => {
+ hasEmittedDoneWithTracks = true;
+ },
+ hasEmittedDoneWithTracks: () => hasEmittedDoneWithTracks,
+ };
+};
+
+export type M3uState = ReturnType<typeof m3uState>;
diff --git a/packages/media-parser/src/state/parser-state.ts b/packages/media-parser/src/state/parser-state.ts
index 9db92b434a..ed4611495e 100644
--- a/packages/media-parser/src/state/parser-state.ts
+++ b/packages/media-parser/src/state/parser-state.ts
@@ -18,6 +18,7 @@ import {imagesState} from './images';
import {isoBaseMediaState} from './iso-base-media/iso-state';
import {keyframesState} from './keyframes';
import {eventLoopState} from './last-eventloop-break';
+import {m3uState} from './m3u-state';
import {makeMp3State} from './mp3';
import {riffSpecificState} from './riff';
import {sampleCallback} from './sample-callbacks';
@@ -101,6 +102,7 @@ export const makeParserState = ({
mp3Info,
aac: aacState(),
flac: flacState(),
+ m3u: m3uState(),
callbacks: sampleCallback({
controller,
hasAudioTrackHandlers,
diff --git a/packages/media-parser/src/state/structure.ts b/packages/media-parser/src/state/structure.ts
index 0d01048a79..7bb7a174f7 100644
--- a/packages/media-parser/src/state/structure.ts
+++ b/packages/media-parser/src/state/structure.ts
@@ -43,6 +43,14 @@ export const structureState = () => {
return struc;
},
+ getM3uStructure: () => {
+ const struc = getStructure();
+ if (struc.type !== 'm3u') {
+ throw new Error('Invalid structure type');
+ }
+
+ return struc;
+ },
getRiffStructure: () => {
const struc = getStructure();
if (struc.type !== 'riff') {
diff --git a/packages/media-parser/src/test/m3u8-with-audio.test.ts b/packages/media-parser/src/test/m3u8-with-audio.test.ts
new file mode 100644
index 0000000000..a866405e3a
--- /dev/null
+++ b/packages/media-parser/src/test/m3u8-with-audio.test.ts
@@ -0,0 +1,14 @@
+import {expect, test} from 'bun:test';
+import {parseMedia} from '../parse-media';
+
+test('parse m3u8', async () => {
+ const {audioCodec} = await parseMedia({
+ src: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
+ acknowledgeRemotionLicense: true,
+ fields: {
+ audioCodec: true,
+ },
+ });
+
+ expect(audioCodec).toBe('mp4a.40.2');
+});
diff --git a/packages/media-parser/src/test/parse-m3u8.test.ts b/packages/media-parser/src/test/parse-m3u8.test.ts
index f3ed8d71ec..b97868ce00 100644
--- a/packages/media-parser/src/test/parse-m3u8.test.ts
+++ b/packages/media-parser/src/test/parse-m3u8.test.ts
@@ -1,16 +1,105 @@
import {exampleVideos} from '@remotion/example-videos';
-import {test} from 'bun:test';
+import {expect, test} from 'bun:test';
import {parseMedia} from '../parse-media';
import {nodeReader} from '../readers/from-node';
test('parse m3u8', async () => {
- const fields = await parseMedia({
+ const {
+ dimensions,
+ durationInSeconds,
+ tracks,
+ audioCodec,
+ container,
+ fps,
+ images,
+ internalStats,
+ isHdr,
+ keyframes,
+ location,
+ metadata,
+ mimeType,
+ name,
+ } = await parseMedia({
src: exampleVideos.m3u8,
reader: nodeReader,
fields: {
structure: true,
+ durationInSeconds: true,
+ dimensions: true,
+ tracks: true,
+ audioCodec: true,
+ container: true,
+ fps: true,
+ images: true,
+ internalStats: true,
+ isHdr: true,
+ keyframes: true,
+ location: true,
+ metadata: true,
+ mimeType: true,
+ name: true,
+ rotation: true,
+ sampleRate: true,
+ videoCodec: true,
+ size: true,
+ numberOfAudioChannels: true,
},
acknowledgeRemotionLicense: true,
});
- console.log(fields);
+
+ expect(durationInSeconds).toBe(6);
+ expect(dimensions).toEqual({
+ // TODO: Why not 1000x1000?
+ width: 1008,
+ height: 1008,
+ });
+ expect(tracks.videoTracks).toEqual([
+ {
+ type: 'video',
+ codec: 'avc1.640028',
+ codecPrivate: new Uint8Array([
+ 1, 100, 0, 40, 255, 225, 0, 30, 103, 100, 0, 40, 172, 217, 0, 252, 31,
+ 249, 101, 192, 91, 129, 1, 2, 160, 0, 0, 3, 0, 42, 131, 166, 128, 1,
+ 227, 6, 50, 192, 1, 0, 4, 104, 234, 239, 44,
+ ]),
+ codecWithoutConfig: 'h264',
+ codedHeight: 1008,
+ codedWidth: 1008,
+ color: {
+ matrixCoefficients: 'bt470bg',
+ transferCharacteristics: null,
+ primaries: null,
+ fullRange: true,
+ },
+ description: undefined,
+ displayAspectHeight: 1008,
+ displayAspectWidth: 1008,
+ fps: null,
+ height: 1008,
+ rotation: 0,
+ sampleAspectRatio: {
+ denominator: 1,
+ numerator: 1,
+ },
+ timescale: 90000,
+ trackId: 256,
+ trakBox: null,
+ width: 1008,
+ },
+ ]);
+ expect(tracks.audioTracks).toEqual([]);
+ expect(audioCodec).toBe(null);
+ expect(container).toBe('m3u8');
+ expect(fps).toBe(null);
+ expect(images).toEqual([]);
+ expect(internalStats).toEqual({
+ finalCursorOffset: 2223,
+ skippedBytes: 0,
+ });
+ expect(isHdr).toBe(false);
+ expect(keyframes).toEqual(null);
+ expect(location).toBe(null);
+ expect(metadata).toEqual([]);
+ expect(mimeType).toBe(null);
+ expect(name).toBe('video.m3u8');
});