Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Use streaming audio waveform in timeline (#6931)

Jonny Burger25dd2c32a606
diff --git a/packages/studio/src/components/AudioWaveform.tsx b/packages/studio/src/components/AudioWaveform.tsx
index 980353dc47..9c8e394cbc 100644
--- a/packages/studio/src/components/AudioWaveform.tsx
+++ b/packages/studio/src/components/AudioWaveform.tsx
@@ -1,25 +1,18 @@
-import type {MediaUtilsAudioData} from '@remotion/media-utils';
-import {getAudioData, getWaveformPortion} from '@remotion/media-utils';
import React, {useEffect, useMemo, useRef, useState} from 'react';
import {Internals} from 'remotion';
import {LIGHT_TRANSPARENT} from '../helpers/colors';
-import {
- getTimelineLayerHeight,
- TIMELINE_BORDER,
-} from '../helpers/timeline-layout';
-import {
- AudioWaveformBar,
- WAVEFORM_BAR_LENGTH,
- WAVEFORM_BAR_MARGIN,
-} from './AudioWaveformBar';
+import {TIMELINE_BORDER} from '../helpers/timeline-layout';
+import {drawBars} from './draw-peaks';
+import {loadWaveformPeaks, TARGET_SAMPLE_RATE} from './load-waveform-peaks';
const container: React.CSSProperties = {
display: 'flex',
flexDirection: 'row',
- alignItems: 'flex-end',
+ alignItems: 'center',
position: 'absolute',
- height: getTimelineLayerHeight('other'),
+ inset: 0,
};
+
const errorMessage: React.CSSProperties = {
fontSize: 13,
paddingTop: 6,
@@ -31,7 +24,11 @@ const errorMessage: React.CSSProperties = {
opacity: 0.75,
};
-const canvasStyle: React.CSSProperties = {
+const waveformCanvasStyle: React.CSSProperties = {
+ pointerEvents: 'none',
+};
+
+const volumeCanvasStyle: React.CSSProperties = {
position: 'absolute',
};
@@ -52,54 +49,103 @@ export const AudioWaveform: React.FC<{
doesVolumeChange,
playbackRate,
}) => {
- const [metadata, setMetadata] = useState<MediaUtilsAudioData | null>(null);
+ const [peaks, setPeaks] = useState<Float32Array | null>(null);
const [error, setError] = useState<Error | null>(null);
- const mountState = useRef({isMounted: true});
const vidConf = Internals.useUnsafeVideoConfig();
if (vidConf === null) {
throw new Error('Expected video config');
}
- const canvas = useRef<HTMLCanvasElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const waveformCanvas = useRef<HTMLCanvasElement>(null);
+ const volumeCanvas = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+
+ setError(null);
+ loadWaveformPeaks(src, controller.signal)
+ .then((p) => {
+ if (!controller.signal.aborted) {
+ setPeaks(p);
+ }
+ })
+ .catch((err) => {
+ if (!controller.signal.aborted) {
+ setError(err);
+ }
+ });
+
+ return () => controller.abort();
+ }, [src]);
+
+ const portionPeaks = useMemo(() => {
+ if (!peaks || peaks.length === 0) {
+ return null;
+ }
+
+ const startTimeInSeconds = startFrom / vidConf.fps;
+ const durationInSeconds = (durationInFrames / vidConf.fps) * playbackRate;
+
+ const startPeakIndex = Math.floor(startTimeInSeconds * TARGET_SAMPLE_RATE);
+ const endPeakIndex = Math.ceil(
+ (startTimeInSeconds + durationInSeconds) * TARGET_SAMPLE_RATE,
+ );
+
+ return peaks.slice(
+ Math.max(0, startPeakIndex),
+ Math.min(peaks.length, endPeakIndex),
+ );
+ }, [peaks, startFrom, durationInFrames, vidConf.fps, playbackRate]);
useEffect(() => {
- const {current} = mountState;
- current.isMounted = true;
- return () => {
- current.isMounted = false;
- };
- }, []);
+ const {current: canvasElement} = waveformCanvas;
+ const {current: containerElement} = containerRef;
+ if (
+ !canvasElement ||
+ !containerElement ||
+ !portionPeaks ||
+ portionPeaks.length === 0
+ ) {
+ return;
+ }
+
+ const h = containerElement.clientHeight;
+ const w = Math.ceil(visualizationWidth);
+ canvasElement.width = w;
+ canvasElement.height = h;
+
+ const vol = typeof volume === 'number' ? volume : 1;
+ drawBars(canvasElement, portionPeaks, 'rgba(255, 255, 255, 0.6)', vol, w);
+ }, [portionPeaks, visualizationWidth, volume]);
useEffect(() => {
- if (!canvas.current) {
+ const {current: volumeCanvasElement} = volumeCanvas;
+ const {current: containerElement} = containerRef;
+ if (!volumeCanvasElement || !containerElement) {
return;
}
- const context = canvas.current.getContext('2d');
+ const h = containerElement.clientHeight;
+ const context = volumeCanvasElement.getContext('2d');
if (!context) {
return;
}
- context.clearRect(
- 0,
- 0,
- visualizationWidth,
- getTimelineLayerHeight('other'),
- );
+ volumeCanvasElement.width = Math.ceil(visualizationWidth);
+ volumeCanvasElement.height = h;
+
+ context.clearRect(0, 0, visualizationWidth, h);
if (!doesVolumeChange || typeof volume === 'number') {
- // The volume is a number, meaning it could change on each frame-
- // User did not use the (f: number) => number syntax, so we can't draw
- // a visualization.
return;
}
const volumes = volume.split(',').map((v) => Number(v));
context.beginPath();
- context.moveTo(0, getTimelineLayerHeight('other'));
+ context.moveTo(0, h);
volumes.forEach((v, index) => {
const x = (index / (volumes.length - 1)) * visualizationWidth;
- const y =
- (1 - v) * (getTimelineLayerHeight('other') - TIMELINE_BORDER * 2) + 1;
+ const y = (1 - v) * (h - TIMELINE_BORDER * 2) + 1;
if (index === 0) {
context.moveTo(x, y);
} else {
@@ -108,50 +154,7 @@ export const AudioWaveform: React.FC<{
});
context.strokeStyle = LIGHT_TRANSPARENT;
context.stroke();
- }, [visualizationWidth, metadata, startFrom, volume, doesVolumeChange]);
-
- useEffect(() => {
- setError(null);
- getAudioData(src)
- .then((data) => {
- if (mountState.current.isMounted) {
- setMetadata(data);
- }
- })
- .catch((err) => {
- if (mountState.current.isMounted) {
- setError(err);
- }
- });
- }, [src, vidConf.fps]);
-
- const normalized = useMemo(() => {
- if (!metadata || metadata.numberOfChannels === 0) {
- return [];
- }
-
- const numberOfSamples = Math.floor(
- visualizationWidth / (WAVEFORM_BAR_LENGTH + WAVEFORM_BAR_MARGIN),
- );
-
- return getWaveformPortion({
- audioData: metadata,
- startTimeInSeconds: startFrom / vidConf.fps,
- durationInSeconds: Math.min(
- (durationInFrames / vidConf.fps) * playbackRate,
- metadata.durationInSeconds,
- ),
- numberOfSamples,
- normalize: false,
- });
- }, [
- durationInFrames,
- vidConf.fps,
- metadata,
- playbackRate,
- startFrom,
- visualizationWidth,
- ]);
+ }, [visualizationWidth, volume, doesVolumeChange]);
if (error) {
return (
@@ -163,27 +166,14 @@ export const AudioWaveform: React.FC<{
);
}
- if (!metadata) {
+ if (!peaks) {
return null;
}
return (
- <div style={container}>
- {normalized.map((w) => {
- return (
- <AudioWaveformBar
- key={w.index}
- amplitude={w.amplitude * (typeof volume === 'number' ? volume : 1)}
- />
- );
- })}
-
- <canvas
- ref={canvas}
- style={canvasStyle}
- width={visualizationWidth}
- height={getTimelineLayerHeight('other')}
- />
+ <div ref={containerRef} style={container}>
+ <canvas ref={waveformCanvas} style={waveformCanvasStyle} />
+ <canvas ref={volumeCanvas} style={volumeCanvasStyle} />
</div>
);
};
diff --git a/packages/studio/src/components/AudioWaveformBar.tsx b/packages/studio/src/components/AudioWaveformBar.tsx
deleted file mode 100644
index ba6b083813..0000000000
--- a/packages/studio/src/components/AudioWaveformBar.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import React, {useMemo} from 'react';
-import {getTimelineLayerHeight} from '../helpers/timeline-layout';
-
-export const WAVEFORM_BAR_LENGTH = 2;
-export const WAVEFORM_BAR_MARGIN = 1;
-
-const container: React.CSSProperties = {
- width: WAVEFORM_BAR_LENGTH,
- backgroundColor: 'rgba(255, 255, 255, 0.6)',
- marginLeft: WAVEFORM_BAR_MARGIN,
- borderRadius: 2,
-};
-
-// Sonnet:
-/**
- *
- * consider a sinus wave with an amplitude going from [-1, 1].
- * if we sample it infinitely, and convert all negative samples from negative to positive
- * what is the average of all samples?
- *
- * Answer: 2 / Math.PI = 0.6366
- */
-
-export const AudioWaveformBar: React.FC<{
- readonly amplitude: number;
-}> = ({amplitude}) => {
- const style = useMemo(() => {
- return {
- ...container,
- height: getTimelineLayerHeight('other') * amplitude * (1 / 0.6366),
- };
- }, [amplitude]);
- return <div style={style} />;
-};
diff --git a/packages/studio/src/components/draw-peaks.ts b/packages/studio/src/components/draw-peaks.ts
new file mode 100644
index 0000000000..ec793f9ffc
--- /dev/null
+++ b/packages/studio/src/components/draw-peaks.ts
@@ -0,0 +1,79 @@
+import {parseColor} from './parse-color';
+
+const CLIPPING_COLOR = '#FF7F50';
+
+export const drawBars = (
+ canvas: HTMLCanvasElement,
+ peaks: Float32Array,
+ color: string,
+ volume: number,
+ width: number,
+) => {
+ const ctx = canvas.getContext('2d');
+
+ if (!ctx) {
+ throw new Error('Failed to get canvas context');
+ }
+
+ const {height} = canvas;
+ const w = canvas.width;
+
+ ctx.clearRect(0, 0, w, height);
+
+ if (volume === 0) return;
+
+ const [r, g, b, a] = parseColor(color);
+ const [cr, cg, cb, ca] = parseColor(CLIPPING_COLOR);
+
+ const imageData = ctx.createImageData(w, height);
+ const {data} = imageData;
+ const numBars = width;
+
+ for (let barIndex = 0; barIndex < numBars; barIndex++) {
+ const x = barIndex;
+ if (x >= w) break;
+
+ const peakIndex = Math.floor((barIndex / numBars) * peaks.length);
+ const peak = peaks[peakIndex] || 0;
+
+ const scaledPeak = peak * volume;
+ const halfBar = Math.max(
+ 0,
+ Math.min(height / 2, (scaledPeak * height) / 2),
+ );
+ if (halfBar === 0) continue;
+
+ const mid = height / 2;
+ const barY = Math.round(mid - halfBar);
+ const barEnd = Math.round(mid + halfBar);
+ const isClipping = scaledPeak > 1;
+ const clipTopEnd = isClipping ? Math.min(barY + 2, barEnd) : barY;
+ const clipBotStart = isClipping ? Math.max(barEnd - 2, barY) : barEnd;
+
+ for (let y = barY; y < clipTopEnd; y++) {
+ const idx = (y * w + x) * 4;
+ data[idx] = cr;
+ data[idx + 1] = cg;
+ data[idx + 2] = cb;
+ data[idx + 3] = ca;
+ }
+
+ for (let y = clipTopEnd; y < clipBotStart; y++) {
+ const idx = (y * w + x) * 4;
+ data[idx] = r;
+ data[idx + 1] = g;
+ data[idx + 2] = b;
+ data[idx + 3] = a;
+ }
+
+ for (let y = clipBotStart; y < barEnd; y++) {
+ const idx = (y * w + x) * 4;
+ data[idx] = cr;
+ data[idx + 1] = cg;
+ data[idx + 2] = cb;
+ data[idx + 3] = ca;
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+};
diff --git a/packages/studio/src/components/load-waveform-peaks.ts b/packages/studio/src/components/load-waveform-peaks.ts
new file mode 100644
index 0000000000..0796507f52
--- /dev/null
+++ b/packages/studio/src/components/load-waveform-peaks.ts
@@ -0,0 +1,79 @@
+import {ALL_FORMATS, AudioSampleSink, Input, UrlSource} from 'mediabunny';
+
+const TARGET_SAMPLE_RATE = 100;
+
+const peaksCache = new Map<string, Float32Array>();
+
+export {TARGET_SAMPLE_RATE};
+
+export async function loadWaveformPeaks(
+ url: string,
+ signal: AbortSignal,
+): Promise<Float32Array> {
+ const cached = peaksCache.get(url);
+ if (cached) return cached;
+
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(url),
+ });
+
+ try {
+ const audioTrack = await input.getPrimaryAudioTrack();
+ if (!audioTrack) {
+ return new Float32Array(0);
+ }
+
+ const {sampleRate} = audioTrack;
+ const durationInSeconds = await audioTrack.computeDuration();
+ const totalPeaks = Math.ceil(durationInSeconds * TARGET_SAMPLE_RATE);
+ const samplesPerPeak = 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);
+
+ for await (const sample of sink.samples()) {
+ if (signal.aborted) {
+ sample.close();
+ return new Float32Array(0);
+ }
+
+ const bytesNeeded = sample.allocationSize({
+ format: 'f32',
+ planeIndex: 0,
+ });
+ const floats = new Float32Array(bytesNeeded / 4);
+ sample.copyTo(floats, {format: 'f32', planeIndex: 0});
+ sample.close();
+
+ for (let i = 0; i < floats.length; i++) {
+ const abs = Math.abs(floats[i]);
+ if (abs > peakMax) peakMax = abs;
+ sampleInPeak++;
+
+ if (sampleInPeak >= samplesPerPeak) {
+ if (peakIndex < totalPeaks) {
+ peaks[peakIndex] = peakMax;
+ }
+
+ peakIndex++;
+ peakMax = 0;
+ sampleInPeak = 0;
+ }
+ }
+ }
+
+ if (sampleInPeak > 0 && peakIndex < totalPeaks) {
+ peaks[peakIndex] = peakMax;
+ }
+
+ peaksCache.set(url, peaks);
+ return peaks;
+ } finally {
+ input.dispose();
+ }
+}
diff --git a/packages/studio/src/components/parse-color.ts b/packages/studio/src/components/parse-color.ts
new file mode 100644
index 0000000000..122aef2550
--- /dev/null
+++ b/packages/studio/src/components/parse-color.ts
@@ -0,0 +1,13 @@
+const colorCache = new Map<string, [number, number, number, number]>();
+
+export const parseColor = (color: string): [number, number, number, number] => {
+ const cached = colorCache.get(color);
+ if (cached) return cached;
+ const ctx = new OffscreenCanvas(1, 1).getContext('2d')!;
+ ctx.fillStyle = color;
+ ctx.fillRect(0, 0, 1, 1);
+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
+ const result: [number, number, number, number] = [r, g, b, a];
+ colorCache.set(color, result);
+ return result;
+};