Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Draw timeline waveforms progressively

Igor Samokhovets31af6c91fec6
diff --git a/packages/studio/src/components/AudioWaveform.tsx b/packages/studio/src/components/AudioWaveform.tsx
index bcf487efe3..7c1cf1c4f0 100644
--- a/packages/studio/src/components/AudioWaveform.tsx
+++ b/packages/studio/src/components/AudioWaveform.tsx
@@ -13,6 +13,12 @@ import {sliceWaveformPeaks} from './slice-waveform-peaks';
const EMPTY_PEAKS = new Float32Array(0);
+// Recreate the canvas after Fast Refresh because an already transferred canvas
+// cannot be handed to OffscreenCanvas again.
+const canRetryCanvasTransfer = (err: unknown) => {
+ return err instanceof DOMException && err.name === 'InvalidStateError';
+};
+
const canUseAudioWaveformWorker = () => {
if (
typeof Worker === 'undefined' ||
@@ -73,6 +79,7 @@ export const AudioWaveform: React.FC<{
}) => {
const [peaks, setPeaks] = useState<Float32Array | null>(null);
const [error, setError] = useState<Error | null>(null);
+ const [waveformCanvasKey, setWaveformCanvasKey] = useState(0);
const canUseWorkerPath = useMemo(() => canUseAudioWaveformWorker(), []);
const vidConf = Internals.useUnsafeVideoConfig();
if (vidConf === null) {
@@ -135,7 +142,20 @@ export const AudioWaveform: React.FC<{
},
);
- const offscreen = canvasElement.transferControlToOffscreen();
+ let offscreen: OffscreenCanvas;
+ try {
+ offscreen = canvasElement.transferControlToOffscreen();
+ } catch (err) {
+ worker.terminate();
+ waveformWorker.current = null;
+ if (canRetryCanvasTransfer(err)) {
+ setWaveformCanvasKey((key) => key + 1);
+ return;
+ }
+
+ throw err;
+ }
+
hasTransferredCanvas.current = true;
worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
@@ -145,7 +165,7 @@ export const AudioWaveform: React.FC<{
waveformWorker.current = null;
hasTransferredCanvas.current = false;
};
- }, [canUseWorkerPath]);
+ }, [canUseWorkerPath, waveformCanvasKey]);
const portionPeaks = useMemo(() => {
if (canUseWorkerPath || !peaks) {
@@ -223,6 +243,7 @@ export const AudioWaveform: React.FC<{
vidConf.fps,
visualizationWidth,
volume,
+ waveformCanvasKey,
]);
useEffect(() => {
@@ -278,7 +299,11 @@ export const AudioWaveform: React.FC<{
return (
<div ref={containerRef} style={container}>
- <canvas ref={waveformCanvas} style={waveformCanvasStyle} />
+ <canvas
+ key={waveformCanvasKey}
+ ref={waveformCanvas}
+ style={waveformCanvasStyle}
+ />
<canvas ref={volumeCanvas} style={volumeCanvasStyle} />
</div>
);
diff --git a/packages/studio/src/components/audio-waveform.worker.ts b/packages/studio/src/components/audio-waveform.worker.ts
index 386ae30cb4..49920e4285 100644
--- a/packages/studio/src/components/audio-waveform.worker.ts
+++ b/packages/studio/src/components/audio-waveform.worker.ts
@@ -27,6 +27,31 @@ const postError = (requestId: number, error: unknown) => {
self.postMessage(payload);
};
+const drawPartialWaveform = (
+ message: AudioWaveformWorkerRenderMessage,
+ peaks: Float32Array,
+) => {
+ if (!canvas) {
+ return;
+ }
+
+ const portionPeaks = sliceWaveformPeaks({
+ durationInFrames: message.durationInFrames,
+ fps: message.fps,
+ peaks,
+ playbackRate: message.playbackRate,
+ startFrom: message.startFrom,
+ });
+
+ drawBars(
+ canvas,
+ portionPeaks,
+ 'rgba(255, 255, 255, 0.6)',
+ message.volume,
+ message.width,
+ );
+};
+
const renderWaveform = async (message: AudioWaveformWorkerRenderMessage) => {
if (!canvas) {
postError(message.requestId, new Error('Waveform canvas not initialized'));
@@ -42,26 +67,23 @@ const renderWaveform = async (message: AudioWaveformWorkerRenderMessage) => {
canvas.width = message.width;
canvas.height = message.height;
- const peaks = await loadWaveformPeaks(message.src, controller.signal);
+ const peaks = await loadWaveformPeaks(message.src, controller.signal, {
+ onProgress: ({peaks: nextPeaks}) => {
+ if (
+ controller.signal.aborted ||
+ latestRequestId !== message.requestId
+ ) {
+ return;
+ }
+
+ drawPartialWaveform(message, nextPeaks);
+ },
+ });
if (controller.signal.aborted || latestRequestId !== message.requestId) {
return;
}
- const portionPeaks = sliceWaveformPeaks({
- durationInFrames: message.durationInFrames,
- fps: message.fps,
- peaks,
- playbackRate: message.playbackRate,
- startFrom: message.startFrom,
- });
-
- drawBars(
- canvas,
- portionPeaks,
- 'rgba(255, 255, 255, 0.6)',
- message.volume,
- message.width,
- );
+ drawPartialWaveform(message, peaks);
} catch (error) {
if (controller.signal.aborted || latestRequestId !== message.requestId) {
return;
diff --git a/packages/studio/src/components/load-waveform-peaks.ts b/packages/studio/src/components/load-waveform-peaks.ts
index 57c1561675..e51e862e8d 100644
--- a/packages/studio/src/components/load-waveform-peaks.ts
+++ b/packages/studio/src/components/load-waveform-peaks.ts
@@ -1,17 +1,44 @@
import {ALL_FORMATS, AudioSampleSink, Input, UrlSource} from 'mediabunny';
+import {
+ createWaveformPeakProcessor,
+ emitWaveformProgress,
+} from './waveform-peak-processor';
const TARGET_SAMPLE_RATE = 100;
+const DEFAULT_PROGRESS_INTERVAL_IN_MS = 50;
const peaksCache = new Map<string, Float32Array>();
export {TARGET_SAMPLE_RATE};
+type Progress = {
+ readonly peaks: Float32Array;
+ readonly completedPeaks: number;
+ readonly totalPeaks: number;
+ readonly final: boolean;
+};
+
+type LoadWaveformPeaksOptions = {
+ readonly onProgress?: (progress: Progress) => void;
+ readonly progressIntervalInMs?: number;
+};
+
export async function loadWaveformPeaks(
url: string,
signal: AbortSignal,
+ options?: LoadWaveformPeaksOptions,
): Promise<Float32Array> {
const cached = peaksCache.get(url);
- if (cached) return cached;
+ if (cached) {
+ emitWaveformProgress({
+ peaks: cached,
+ completedPeaks: cached.length,
+ totalPeaks: cached.length,
+ final: true,
+ onProgress: options?.onProgress,
+ });
+ return cached;
+ }
const input = new Input({
formats: ALL_FORMATS,
@@ -32,12 +59,15 @@ export async function loadWaveformPeaks(
Math.floor(sampleRate / TARGET_SAMPLE_RATE),
);
- const peaks = new Float32Array(totalPeaks);
- let peakIndex = 0;
- let peakMax = 0;
- let sampleInPeak = 0;
-
const sink = new AudioSampleSink(audioTrack);
+ const processor = createWaveformPeakProcessor({
+ totalPeaks,
+ samplesPerPeak,
+ onProgress: options?.onProgress,
+ progressIntervalInMs:
+ options?.progressIntervalInMs ?? DEFAULT_PROGRESS_INTERVAL_IN_MS,
+ now: () => Date.now(),
+ });
for await (const sample of sink.samples()) {
if (signal.aborted) {
@@ -52,42 +82,13 @@ export async function loadWaveformPeaks(
const floats = new Float32Array(bytesNeeded / 4);
sample.copyTo(floats, {format: 'f32', planeIndex: 0});
const channels = Math.max(1, sample.numberOfChannels);
- const frames = sample.numberOfFrames;
sample.close();
- for (let frame = 0; frame < frames; frame++) {
- // `f32` copies are interleaved, so timing must advance per frame, not per float.
- let framePeak = 0;
- for (let channel = 0; channel < channels; channel++) {
- const sampleIndex = frame * channels + channel;
- const abs = Math.abs(floats[sampleIndex] ?? 0);
- if (abs > framePeak) {
- framePeak = abs;
- }
- }
-
- if (framePeak > peakMax) {
- peakMax = framePeak;
- }
-
- sampleInPeak++;
-
- if (sampleInPeak >= samplesPerPeak) {
- if (peakIndex < totalPeaks) {
- peaks[peakIndex] = peakMax;
- }
-
- peakIndex++;
- peakMax = 0;
- sampleInPeak = 0;
- }
- }
- }
-
- if (sampleInPeak > 0 && peakIndex < totalPeaks) {
- peaks[peakIndex] = peakMax;
+ processor.processSampleChunk(floats, channels);
}
+ processor.finalize();
+ const {peaks} = processor;
peaksCache.set(url, peaks);
return peaks;
} finally {
diff --git a/packages/studio/src/components/slice-waveform-peaks.ts b/packages/studio/src/components/slice-waveform-peaks.ts
index 7827301cde..e758bd1bbc 100644
--- a/packages/studio/src/components/slice-waveform-peaks.ts
+++ b/packages/studio/src/components/slice-waveform-peaks.ts
@@ -25,7 +25,7 @@ export const sliceWaveformPeaks = ({
(startTimeInSeconds + durationInSeconds) * TARGET_SAMPLE_RATE,
);
- return peaks.slice(
+ return peaks.subarray(
Math.max(0, startPeakIndex),
Math.min(peaks.length, endPeakIndex),
);
diff --git a/packages/studio/src/components/waveform-peak-processor.ts b/packages/studio/src/components/waveform-peak-processor.ts
new file mode 100644
index 0000000000..b13950314b
--- /dev/null
+++ b/packages/studio/src/components/waveform-peak-processor.ts
@@ -0,0 +1,118 @@
+type Progress = {
+ readonly peaks: Float32Array;
+ readonly completedPeaks: number;
+ readonly totalPeaks: number;
+ readonly final: boolean;
+};
+
+type WaveformPeakProcessorOptions = {
+ readonly totalPeaks: number;
+ readonly samplesPerPeak: number;
+ readonly onProgress?: (progress: Progress) => void;
+ readonly progressIntervalInMs: number;
+ readonly now: () => number;
+};
+
+type WaveformPeakProcessor = {
+ readonly peaks: Float32Array;
+ processSampleChunk: (floats: Float32Array, channels: number) => void;
+ finalize: () => void;
+};
+
+export const emitWaveformProgress = ({
+ completedPeaks,
+ final,
+ onProgress,
+ peaks,
+ totalPeaks,
+}: Progress & {
+ readonly onProgress?: (progress: Progress) => void;
+}) => {
+ onProgress?.({
+ peaks,
+ completedPeaks,
+ totalPeaks,
+ final,
+ });
+};
+
+export const createWaveformPeakProcessor = ({
+ totalPeaks,
+ samplesPerPeak,
+ onProgress,
+ progressIntervalInMs,
+ now,
+}: WaveformPeakProcessorOptions): WaveformPeakProcessor => {
+ const peaks = new Float32Array(totalPeaks);
+ let peakIndex = 0;
+ let peakMax = 0;
+ let sampleInPeak = 0;
+ let lastProgressAt = 0;
+ let lastProgressPeak = 0;
+
+ const emitProgress = (force: boolean) => {
+ const timestamp = now();
+ if (!force && peakIndex === lastProgressPeak && sampleInPeak === 0) {
+ return;
+ }
+
+ if (!force && timestamp - lastProgressAt < progressIntervalInMs) {
+ return;
+ }
+
+ lastProgressAt = timestamp;
+ lastProgressPeak = peakIndex;
+ emitWaveformProgress({
+ peaks,
+ completedPeaks: peakIndex,
+ totalPeaks,
+ final: force,
+ onProgress,
+ });
+ };
+
+ return {
+ peaks,
+ processSampleChunk: (floats, channels) => {
+ const frameCount = Math.floor(floats.length / Math.max(1, channels));
+
+ for (let frame = 0; frame < frameCount; frame++) {
+ // `f32` copies are interleaved, so timing advances per frame.
+ let framePeak = 0;
+ for (let channel = 0; channel < channels; channel++) {
+ const sampleIndex = frame * channels + channel;
+ const abs = Math.abs(floats[sampleIndex] ?? 0);
+ if (abs > framePeak) {
+ framePeak = abs;
+ }
+ }
+
+ if (framePeak > peakMax) {
+ peakMax = framePeak;
+ }
+
+ sampleInPeak++;
+
+ if (sampleInPeak >= samplesPerPeak) {
+ if (peakIndex < totalPeaks) {
+ peaks[peakIndex] = peakMax;
+ }
+
+ peakIndex++;
+ peakMax = 0;
+ sampleInPeak = 0;
+ }
+ }
+
+ emitProgress(false);
+ },
+ finalize: () => {
+ if (sampleInPeak > 0 && peakIndex < totalPeaks) {
+ peaks[peakIndex] = peakMax;
+ peakIndex++;
+ }
+
+ emitProgress(true);
+ },
+ };
+};
diff --git a/packages/studio/src/test/waveform-peak-processor.test.ts b/packages/studio/src/test/waveform-peak-processor.test.ts
new file mode 100644
index 0000000000..927fccd871
--- /dev/null
+++ b/packages/studio/src/test/waveform-peak-processor.test.ts
@@ -0,0 +1,107 @@
+import {expect, test} from 'bun:test';
+import {createWaveformPeakProcessor} from '../components/waveform-peak-processor';
+
+const expectPeaksToBeClose = (actual: number[], expected: number[]) => {
+ expect(actual).toHaveLength(expected.length);
+ for (const [index, value] of expected.entries()) {
+ expect(actual[index]).toBeCloseTo(value);
+ }
+};
+
+test('Should emit incremental progress for completed peaks', () => {
+ const progressCalls: Array<{
+ completedPeaks: number;
+ final: boolean;
+ peaks: number[];
+ }> = [];
+
+ const processor = createWaveformPeakProcessor({
+ totalPeaks: 3,
+ samplesPerPeak: 2,
+ progressIntervalInMs: 0,
+ now: () => 100,
+ onProgress: ({completedPeaks, final, peaks}) => {
+ progressCalls.push({
+ completedPeaks,
+ final,
+ peaks: Array.from(peaks),
+ });
+ },
+ });
+
+ processor.processSampleChunk(
+ new Float32Array([0.1, 0.7, 0.5, 0.2, 0.3, 0.8, 0.4, 0.1]),
+ 2,
+ );
+
+ expect(progressCalls).toHaveLength(1);
+ expect(progressCalls[0]).toMatchObject({
+ completedPeaks: 2,
+ final: false,
+ });
+ expectPeaksToBeClose(progressCalls[0].peaks, [0.7, 0.8, 0]);
+});
+
+test('Should flush the last partial peak during finalize', () => {
+ const progressCalls: Array<{
+ completedPeaks: number;
+ final: boolean;
+ peaks: number[];
+ }> = [];
+
+ const processor = createWaveformPeakProcessor({
+ totalPeaks: 2,
+ samplesPerPeak: 2,
+ progressIntervalInMs: 0,
+ now: () => 100,
+ onProgress: ({completedPeaks, final, peaks}) => {
+ progressCalls.push({
+ completedPeaks,
+ final,
+ peaks: Array.from(peaks),
+ });
+ },
+ });
+
+ processor.processSampleChunk(new Float32Array([0.2, 0.6, 0.4]), 1);
+ processor.finalize();
+
+ expect(progressCalls).toHaveLength(2);
+ expect(progressCalls[0]).toMatchObject({
+ completedPeaks: 1,
+ final: false,
+ });
+ expectPeaksToBeClose(progressCalls[0].peaks, [0.6, 0]);
+ expect(progressCalls[1]).toMatchObject({
+ completedPeaks: 2,
+ final: true,
+ });
+ expectPeaksToBeClose(progressCalls[1].peaks, [0.6, 0.4]);
+});
+
+test('Should throttle intermediate progress but always emit the final update', () => {
+ let now = 0;
+ const progressCalls: Array<{completedPeaks: number; final: boolean}> = [];
+
+ const processor = createWaveformPeakProcessor({
+ totalPeaks: 3,
+ samplesPerPeak: 1,
+ progressIntervalInMs: 50,
+ now: () => now,
+ onProgress: ({completedPeaks, final}) => {
+ progressCalls.push({completedPeaks, final});
+ },
+ });
+
+ now = 100;
+ processor.processSampleChunk(new Float32Array([0.2]), 1);
+ now = 120;
+ processor.processSampleChunk(new Float32Array([0.4]), 1);
+ now = 130;
+ processor.finalize();
+
+ expect(progressCalls).toEqual([
+ {completedPeaks: 1, final: false},
+ {completedPeaks: 2, final: true},
+ ]);
+});