Skip to content

🎥 Make videos programmatically with React

also get 48khz audio

Jonny Burgerf39ac3124429
diff --git a/packages/video/src/convert-audiodata/combine-audiodata.ts b/packages/video/src/convert-audiodata/combine-audiodata.ts
new file mode 100644
index 0000000000..49411a8239
--- /dev/null
+++ b/packages/video/src/convert-audiodata/combine-audiodata.ts
@@ -0,0 +1,92 @@
+import {getDataTypeForAudioFormat} from './data-types';
+import {isPlanarFormat} from './is-planar-format';
+
+export const combineAudioDataAndClosePrevious = (
+ audioDataArray: AudioData[],
+) => {
+ let numberOfFrames = 0;
+ let format: AudioSampleFormat | null = null;
+ let numberOfChannels: number | null = null;
+ let sampleRate: number | null = null;
+ const {timestamp} = audioDataArray[0];
+
+ for (const audioData of audioDataArray) {
+ numberOfFrames += audioData.numberOfFrames;
+ if (!format) {
+ format = audioData.format;
+ } else if (format !== audioData.format) {
+ throw new Error('Formats do not match');
+ }
+
+ if (!numberOfChannels) {
+ numberOfChannels = audioData.numberOfChannels;
+ } else if (numberOfChannels !== audioData.numberOfChannels) {
+ throw new Error('Number of channels do not match');
+ }
+
+ if (!sampleRate) {
+ sampleRate = audioData.sampleRate;
+ } else if (sampleRate !== audioData.sampleRate) {
+ throw new Error('Sample rates do not match');
+ }
+ }
+
+ if (!format) {
+ throw new Error('Format is not set');
+ }
+
+ if (!numberOfChannels) {
+ throw new Error('Number of channels is not set');
+ }
+
+ if (!sampleRate) {
+ throw new Error('Sample rate is not set');
+ }
+
+ const DataType = getDataTypeForAudioFormat(format);
+ const isPlanar = isPlanarFormat(format);
+ if (isPlanar) {
+ throw new Error(
+ 'Planar formats are not supported for combining audio dats',
+ );
+ }
+
+ const channel = new DataType(numberOfFrames * numberOfChannels);
+
+ let framesWritten = 0;
+
+ for (
+ let audioDataIndex = 0;
+ audioDataIndex < audioDataArray.length;
+ audioDataIndex++
+ ) {
+ const audioData = audioDataArray[audioDataIndex];
+ if (audioDataIndex === 0) {
+ audioData.clone().copyTo(channel, {
+ planeIndex: 0,
+ });
+ } else {
+ const intermediateChannel = new DataType(
+ audioData.numberOfFrames * numberOfChannels,
+ );
+ audioData.clone().copyTo(intermediateChannel, {
+ planeIndex: 0,
+ });
+ channel.set(intermediateChannel, framesWritten);
+ }
+
+ framesWritten += audioData.numberOfFrames;
+ audioData.close();
+ }
+
+ const newAudioData = new AudioData({
+ numberOfFrames,
+ sampleRate,
+ timestamp,
+ data: channel,
+ format,
+ numberOfChannels,
+ });
+
+ return newAudioData;
+};
diff --git a/packages/video/src/convert-audiodata/convert-audiodata.ts b/packages/video/src/convert-audiodata/convert-audiodata.ts
new file mode 100644
index 0000000000..2d5a029849
--- /dev/null
+++ b/packages/video/src/convert-audiodata/convert-audiodata.ts
@@ -0,0 +1,147 @@
+import {getDataTypeForAudioFormat} from './data-types';
+import {isPlanarFormat} from './is-planar-format';
+
+const validateRange = (format: AudioSampleFormat, value: number) => {
+ if (format === 'f32' || format === 'f32-planar') {
+ if (value < -1 || value > 1) {
+ throw new Error('All values in a Float32 array must be between -1 and 1');
+ }
+ }
+};
+
+export type ConvertAudioDataOptions = {
+ audioData: AudioData;
+ newSampleRate: number;
+ format: AudioSampleFormat | null;
+ trimStartInSeconds: number;
+ trimEndInSeconds: number;
+};
+/**
+ * Converts an `AudioData` object to a new `AudioData` object with a different sample rate or format.
+ * @see [Documentation](https://remotion.dev/docs/webcodecs/convert-audiodata)
+ */
+export const convertAudioData = ({
+ audioData,
+ newSampleRate,
+ format,
+ trimStartInSeconds,
+ trimEndInSeconds,
+}: ConvertAudioDataOptions) => {
+ const {
+ numberOfChannels,
+ sampleRate: currentSampleRate,
+ numberOfFrames,
+ } = audioData;
+ const ratio = currentSampleRate / newSampleRate;
+
+ const frameOffset = Math.round(trimStartInSeconds * audioData.sampleRate);
+ const frameCount =
+ numberOfFrames -
+ Math.round((trimEndInSeconds + trimStartInSeconds) * audioData.sampleRate);
+
+ const newNumberOfFrames = Math.floor(frameCount / ratio);
+
+ if (newNumberOfFrames === 0) {
+ throw new Error(
+ 'Cannot resample - the given sample rate would result in less than 1 sample',
+ );
+ }
+
+ if (newSampleRate < 3000 || newSampleRate > 768000) {
+ throw new Error('newSampleRate must be between 3000 and 768000');
+ }
+
+ if (!format) {
+ throw new Error('AudioData format is not set');
+ }
+
+ if (
+ format === audioData.format &&
+ newNumberOfFrames === numberOfFrames &&
+ trimStartInSeconds === 0 &&
+ trimEndInSeconds === null
+ ) {
+ return audioData.clone();
+ }
+
+ const DataType = getDataTypeForAudioFormat(format);
+
+ const isPlanar = isPlanarFormat(format);
+ const planes = isPlanar ? numberOfChannels : 1;
+
+ const srcChannels = new Array(planes)
+ .fill(true)
+ .map(() => new DataType((isPlanar ? 1 : numberOfChannels) * frameCount));
+
+ for (let i = 0; i < planes; i++) {
+ audioData.clone().copyTo(srcChannels[i], {
+ planeIndex: i,
+ format,
+ frameOffset,
+ frameCount,
+ });
+ }
+
+ const data = new DataType(newNumberOfFrames * numberOfChannels);
+ const chunkSize = frameCount / newNumberOfFrames;
+
+ for (
+ let newFrameIndex = 0;
+ newFrameIndex < newNumberOfFrames;
+ newFrameIndex++
+ ) {
+ const start = Math.floor(newFrameIndex * chunkSize);
+ const end = Math.max(Math.floor(start + chunkSize), start + 1);
+
+ if (isPlanar) {
+ for (
+ let channelIndex = 0;
+ channelIndex < numberOfChannels;
+ channelIndex++
+ ) {
+ const chunk = srcChannels[channelIndex].slice(start, end);
+
+ const average =
+ (chunk as Int32Array<ArrayBuffer>).reduce((a, b) => {
+ return a + b;
+ }, 0) / chunk.length;
+
+ validateRange(format, average);
+
+ data[newFrameIndex + channelIndex * newNumberOfFrames] = average;
+ }
+ } else {
+ const sampleCountAvg = end - start;
+
+ for (
+ let channelIndex = 0;
+ channelIndex < numberOfChannels;
+ channelIndex++
+ ) {
+ const items = [];
+ for (let k = 0; k < sampleCountAvg; k++) {
+ const num =
+ srcChannels[0][(start + k) * numberOfChannels + channelIndex];
+ items.push(num);
+ }
+
+ const average = items.reduce((a, b) => a + b, 0) / items.length;
+
+ validateRange(format, average);
+
+ data[newFrameIndex * numberOfChannels + channelIndex] = average;
+ }
+ }
+ }
+
+ const newAudioData = new AudioData({
+ data,
+ format,
+ numberOfChannels,
+ numberOfFrames: newNumberOfFrames,
+ sampleRate: newSampleRate,
+ timestamp: audioData.timestamp,
+ });
+
+ return newAudioData;
+};
diff --git a/packages/video/src/convert-audiodata/data-types.ts b/packages/video/src/convert-audiodata/data-types.ts
new file mode 100644
index 0000000000..6592fd0355
--- /dev/null
+++ b/packages/video/src/convert-audiodata/data-types.ts
@@ -0,0 +1,22 @@
+export const getDataTypeForAudioFormat = (format: AudioSampleFormat) => {
+ switch (format) {
+ case 'f32':
+ return Float32Array;
+ case 'f32-planar':
+ return Float32Array;
+ case 's16':
+ return Int16Array;
+ case 's16-planar':
+ return Int16Array;
+ case 'u8':
+ return Uint8Array;
+ case 'u8-planar':
+ return Uint8Array;
+ case 's32':
+ return Int32Array;
+ case 's32-planar':
+ return Int32Array;
+ default:
+ throw new Error(`Unsupported audio format: ${format satisfies never}`);
+ }
+};
diff --git a/packages/video/src/convert-audiodata/is-planar-format.ts b/packages/video/src/convert-audiodata/is-planar-format.ts
new file mode 100644
index 0000000000..3ae59fce5c
--- /dev/null
+++ b/packages/video/src/convert-audiodata/is-planar-format.ts
@@ -0,0 +1,3 @@
+export const isPlanarFormat = (format: AudioSampleFormat) => {
+ return format.includes('-planar');
+};
diff --git a/packages/video/src/extract-frame-via-broadcast-channel.ts b/packages/video/src/extract-frame-via-broadcast-channel.ts
index d2b002f80e..f355c4355e 100644
--- a/packages/video/src/extract-frame-via-broadcast-channel.ts
+++ b/packages/video/src/extract-frame-via-broadcast-channel.ts
@@ -1,10 +1,11 @@
-import {extractFrame} from './extract-frame';
+import {extractFrameAndAudio} from './extract-frame';
import type {LogLevel} from './log';
type ExtractFrameRequest = {
type: 'request';
src: string;
timeInSeconds: number;
+ durationInSeconds: number;
id: string;
logLevel: LogLevel;
};
@@ -14,6 +15,7 @@ type ExtractFrameResponse =
type: 'response-success';
id: string;
frame: ImageBitmap | null;
+ audio: AudioData | null;
}
| {
type: 'response-error';
@@ -34,26 +36,30 @@ if (window.remotion_broadcastChannel) {
const data = event.data as ExtractFrameRequest;
if (data.type === 'request') {
try {
- const sample = await extractFrame({
+ const {frame, audio} = await extractFrameAndAudio({
src: data.src,
- timestamp: data.timeInSeconds,
+ timeInSeconds: data.timeInSeconds,
logLevel: data.logLevel,
+ durationInSeconds: data.durationInSeconds,
});
- const frame = sample?.toVideoFrame() ?? null;
- const imageBitmap = frame ? await createImageBitmap(frame) : null;
- if (frame) {
- frame.close();
+ const videoFrame = frame?.toVideoFrame() ?? null;
+ const imageBitmap = videoFrame
+ ? await createImageBitmap(videoFrame)
+ : null;
+ if (videoFrame) {
+ videoFrame.close();
}
const response: ExtractFrameResponse = {
type: 'response-success',
id: data.id,
frame: imageBitmap,
+ audio,
};
window.remotion_broadcastChannel!.postMessage(response);
- frame?.close();
+ videoFrame?.close();
} catch (error) {
const response: ExtractFrameResponse = {
type: 'response-error',
@@ -72,34 +78,42 @@ if (window.remotion_broadcastChannel) {
export const extractFrameViaBroadcastChannel = async ({
src,
- timestamp,
+ timeInSeconds,
logLevel,
+ durationInSeconds,
}: {
src: string;
- timestamp: number;
+ timeInSeconds: number;
+ durationInSeconds: number;
logLevel: LogLevel;
-}): Promise<ImageBitmap | VideoFrame | null> => {
+}): Promise<{
+ frame: ImageBitmap | VideoFrame | null;
+ audio: AudioData | null;
+}> => {
if (typeof window.remotion_isMainTab === 'undefined') {
throw new Error('This should be defined');
}
if (window.remotion_isMainTab) {
- const sample = await extractFrame({
+ const {frame: sample, audio} = await extractFrameAndAudio({
logLevel,
src,
- timestamp,
+ timeInSeconds,
+ durationInSeconds,
});
- if (!sample) {
- return null;
- }
-
- return sample.toVideoFrame();
+ return {
+ frame: sample?.toVideoFrame() ?? null,
+ audio,
+ };
}
const requestId = crypto.randomUUID();
- const resolvePromise = new Promise<ImageBitmap | null>((resolve, reject) => {
+ const resolvePromise = new Promise<{
+ frame: ImageBitmap | null;
+ audio: AudioData | null;
+ }>((resolve, reject) => {
const onMessage = (event: MessageEvent) => {
const data = event.data as ExtractFrameResponse;
@@ -108,7 +122,7 @@ export const extractFrameViaBroadcastChannel = async ({
}
if (data.type === 'response-success' && data.id === requestId) {
- resolve(data.frame ? data.frame : null);
+ resolve({frame: data.frame ? data.frame : null, audio: data.audio});
window.remotion_broadcastChannel!.removeEventListener(
'message',
onMessage,
@@ -128,9 +142,10 @@ export const extractFrameViaBroadcastChannel = async ({
const request: ExtractFrameRequest = {
type: 'request',
src,
- timeInSeconds: timestamp,
+ timeInSeconds,
id: requestId,
logLevel,
+ durationInSeconds,
};
window.remotion_broadcastChannel!.postMessage(request);
@@ -147,7 +162,7 @@ export const extractFrameViaBroadcastChannel = async ({
() => {
reject(
new Error(
- `Timeout while extracting frame ${timestamp} from ${src}`,
+ `Timeout while extracting frame ${timeInSeconds} from ${src}`,
),
);
},
diff --git a/packages/video/src/extract-frame.ts b/packages/video/src/extract-frame.ts
index 9ca580651f..01a6f72b08 100644
--- a/packages/video/src/extract-frame.ts
+++ b/packages/video/src/extract-frame.ts
@@ -1,4 +1,7 @@
-import {getVideoSink, type GetSink} from './get-frames-since-keyframe';
+import type {AudioSample} from 'mediabunny';
+import {combineAudioDataAndClosePrevious} from './convert-audiodata/combine-audiodata';
+import {convertAudioData} from './convert-audiodata/convert-audiodata';
+import {getSinks, type GetSink} from './get-frames-since-keyframe';
import {makeKeyframeManager} from './keyframe-manager';
import type {LogLevel} from './log';
@@ -7,28 +10,145 @@ const sinkPromise: Record<string, Promise<GetSink>> = {};
export const extractFrame = async ({
src,
- timestamp,
+ timeInSeconds,
logLevel,
}: {
src: string;
- timestamp: number;
+ timeInSeconds: number;
logLevel: LogLevel;
}) => {
if (!sinkPromise[src]) {
- sinkPromise[src] = getVideoSink(src);
+ sinkPromise[src] = getSinks(src);
}
- const {packetSink, videoSampleSink} = await sinkPromise[src];
+ const {video} = await sinkPromise[src];
const keyframeBank = await keyframeManager.requestKeyframeBank({
- packetSink,
- videoSampleSink,
- timestamp,
+ packetSink: video.packetSink,
+ videoSampleSink: video.sampleSink,
+ timestamp: timeInSeconds,
src,
logLevel,
});
- const frame = await keyframeBank.getFrameFromTimestamp(timestamp);
+ const frame = await keyframeBank.getFrameFromTimestamp(timeInSeconds);
return frame;
};
+
+export const extractAudio = async ({
+ src,
+ timeInSeconds,
+ durationInSeconds,
+}: {
+ src: string;
+ timeInSeconds: number;
+ logLevel: LogLevel;
+ durationInSeconds: number;
+}) => {
+ if (!sinkPromise[src]) {
+ sinkPromise[src] = getSinks(src);
+ }
+
+ const {audio} = await sinkPromise[src];
+
+ if (audio === null) {
+ return null;
+ }
+
+ const sampleIterator = audio.sampleSink.samples(
+ timeInSeconds,
+ timeInSeconds + durationInSeconds,
+ );
+ const samples: AudioSample[] = [];
+ for await (const sample of sampleIterator) {
+ samples.push(sample);
+ }
+
+ const audioDataArray: AudioData[] = [];
+ for (let i = 0; i < samples.length; i++) {
+ const sample = samples[i];
+
+ // Less than 1 sample would be included - we did not need it after all!
+ if (
+ Math.abs(sample.timestamp - (timeInSeconds + durationInSeconds)) *
+ sample.sampleRate <
+ 1
+ ) {
+ sample.close();
+ continue;
+ }
+
+ const isFirstSample = i === 0;
+ const isLastSample = i === samples.length - 1;
+
+ const audioDataRaw = sample.toAudioData();
+
+ // amount of samples to shave from start and end
+ let trimStartInSeconds = 0;
+ let trimEndInSeconds = 0;
+
+ // TODO: Apply volume
+ // TODO: Apply playback rate
+ // TODO: Apply tone frequency
+
+ if (isFirstSample) {
+ trimStartInSeconds = timeInSeconds - sample.timestamp;
+ }
+
+ if (isLastSample) {
+ trimEndInSeconds =
+ sample.timestamp +
+ sample.duration -
+ (timeInSeconds + durationInSeconds);
+ }
+
+ const audioData = convertAudioData({
+ audioData: audioDataRaw,
+ newSampleRate: 48000,
+ // todo: planar or not?
+ format: 's16',
+ trimStartInSeconds,
+ trimEndInSeconds,
+ });
+
+ audioDataArray.push(audioData);
+
+ sample.close();
+ }
+
+ const combined = combineAudioDataAndClosePrevious(audioDataArray);
+
+ return combined;
+};
+
+export const extractFrameAndAudio = async ({
+ src,
+ timeInSeconds,
+ logLevel,
+ durationInSeconds,
+}: {
+ src: string;
+ timeInSeconds: number;
+ logLevel: LogLevel;
+ durationInSeconds: number;
+}) => {
+ const [frame, audio] = await Promise.all([
+ extractFrame({
+ src,
+ timeInSeconds,
+ logLevel,
+ }),
+ extractAudio({
+ src,
+ timeInSeconds,
+ logLevel,
+ durationInSeconds,
+ }),
+ ]);
+
+ return {
+ frame,
+ audio,
+ };
+};
diff --git a/packages/video/src/get-frames-since-keyframe.ts b/packages/video/src/get-frames-since-keyframe.ts
index 6bca38382c..d433a81072 100644
--- a/packages/video/src/get-frames-since-keyframe.ts
+++ b/packages/video/src/get-frames-since-keyframe.ts
@@ -1,6 +1,7 @@
import type {EncodedPacket} from 'mediabunny';
import {
ALL_FORMATS,
+ AudioSampleSink,
EncodedPacketSink,
Input,
UrlSource,
@@ -8,24 +9,33 @@ import {
} from 'mediabunny';
import {makeKeyframeBank} from './keyframe-bank';
-export const getVideoSink = async (src: string) => {
+export const getSinks = async (src: string) => {
const input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src),
});
- const track = await input.getPrimaryVideoTrack();
- if (!track) {
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
throw new Error(`No video track found for ${src}`);
}
- const videoSampleSink = new VideoSampleSink(track);
- const packetSink = new EncodedPacketSink(track);
+ const audioTrack = await input.getPrimaryAudioTrack();
- return {videoSampleSink, packetSink};
+ return {
+ video: {
+ sampleSink: new VideoSampleSink(videoTrack),
+ packetSink: new EncodedPacketSink(videoTrack),
+ },
+ audio: audioTrack
+ ? {
+ sampleSink: new AudioSampleSink(audioTrack),
+ }
+ : null,
+ };
};
-export type GetSink = Awaited<ReturnType<typeof getVideoSink>>;
+export type GetSink = Awaited<ReturnType<typeof getSinks>>;
export const getFramesSinceKeyframe = async ({
packetSink,
diff --git a/packages/video/src/new-video-for-rendering.tsx b/packages/video/src/new-video-for-rendering.tsx
index b43ebcd59f..061f4b9ad1 100644
--- a/packages/video/src/new-video-for-rendering.tsx
+++ b/packages/video/src/new-video-for-rendering.tsx
@@ -133,6 +133,7 @@ export const NewVideoForRendering: React.FC<NewVideoProps> = ({
const actualFps = playbackRate ? fps / playbackRate : fps;
const timestamp = frame / actualFps;
+ const durationInSeconds = 1 / actualFps;
const newHandle = delayRender(`extracting frame number ${frame}`, {
retries: delayRenderRetries ?? undefined,
@@ -141,10 +142,11 @@ export const NewVideoForRendering: React.FC<NewVideoProps> = ({
extractFrameViaBroadcastChannel({
src,
- timestamp,
+ timeInSeconds: timestamp,
+ durationInSeconds,
logLevel: logLevel ?? 'info',
})
- .then((imageBitmap) => {
+ .then(({frame: imageBitmap, audio}) => {
if (!imageBitmap) {
cancelRender(new Error('No video frame found'));
}