Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Draw linear volume curves between keyframes

JonnyBurger7b075355e962
diff --git a/packages/studio/src/components/AudioWaveform.tsx b/packages/studio/src/components/AudioWaveform.tsx
index 8337454e4d..0fe56a77d8 100644
--- a/packages/studio/src/components/AudioWaveform.tsx
+++ b/packages/studio/src/components/AudioWaveform.tsx
@@ -3,7 +3,6 @@ import {
getVisibleWaveformVolume,
subscribeToWaveformPeaks,
type WaveformDrawRange,
- type WaveformVolume,
} from '@remotion/timeline-utils';
import React, {useLayoutEffect, useMemo, useRef, useState} from 'react';
import type {LoopDisplay} from 'remotion';
@@ -13,6 +12,7 @@ import {BLACK_ALPHA_60, WHITE_ALPHA_60} from '../helpers/colors';
import {TIMELINE_FRAME_WIDTH_AT_MAX_ZOOM} from '../helpers/get-timeline-max-zoom';
import {resolveStudioColor} from '../helpers/resolve-studio-color';
import {getStudioPixelRatio} from '../helpers/studio-pixel-ratio';
+import type {TimelineVolume} from './Timeline/get-timeline-volume';
const EMPTY_PEAKS = new Float32Array(0);
@@ -47,7 +47,7 @@ const AudioWaveformInner: React.FC<{
readonly durationInFrames: number;
readonly displayOffsetInFrames: number;
readonly displayDurationInFrames: number;
- readonly volume: WaveformVolume;
+ readonly volume: TimelineVolume;
readonly muted: boolean;
readonly playbackRate: number;
readonly loopDisplay: LoopDisplay | undefined;
@@ -85,23 +85,33 @@ const AudioWaveformInner: React.FC<{
return Math.max(1, volume);
}
+ if ('points' in volume) {
+ return volume.points.reduce(
+ (highest, point) => Math.max(highest, point.value),
+ 1,
+ );
+ }
+
return volume.reduce((highest, value) => {
return Number.isFinite(value) ? Math.max(highest, value) : highest;
}, 1);
}, [volume]);
- const visibleVolume = useMemo((): WaveformVolume => {
+ const visibleVolume = useMemo((): TimelineVolume => {
if (muted) {
return 0;
}
+ if (typeof volume !== 'number' && 'points' in volume) {
+ return volume;
+ }
+
return getVisibleWaveformVolume({
displayDurationInFrames,
displayOffsetInFrames,
volume,
});
}, [displayDurationInFrames, displayOffsetInFrames, muted, volume]);
- const waveformVolume =
- shouldRenderVolumeOverlay && !muted ? 1 : visibleVolume;
+ const waveformVolume = typeof visibleVolume === 'number' ? visibleVolume : 1;
// Layout effect so that a cache hit sets the peaks synchronously and the
// waveform is painted on the very first frame after mounting.
@@ -202,54 +212,62 @@ const AudioWaveformInner: React.FC<{
}
context.clearRect(0, 0, w, h);
- if (
- !Array.isArray(visibleVolume) ||
- visibleVolume.length === 0 ||
- drawingWidth <= 0 ||
- h <= 0
- ) {
+ if (typeof visibleVolume === 'number' || drawingWidth <= 0 || h <= 0) {
return;
}
context.setTransform(1, 0, 0, 1, horizontalOffset, 0);
context.beginPath();
context.moveTo(0, 0);
- // The canvas only spans the virtualized range. Sampling by its physical
- // width keeps drawing work bounded to the visible part of the timeline.
- const numberOfPoints = Math.min(
- visibleVolume.length,
- Math.max(1, Math.ceil(drawingWidth)),
- );
- for (let point = 0; point < numberOfPoints; point++) {
- const volumeIndex = Math.floor(
- (point / numberOfPoints) * visibleVolume.length,
- );
- const nextVolumeIndex = Math.floor(
- ((point + 1) / numberOfPoints) * visibleVolume.length,
- );
- const firstFrame = Math.max(0, Math.floor(displayOffsetInFrames));
- const x = Math.max(
- 0,
- ((firstFrame + volumeIndex - displayOffsetInFrames) /
- displayDurationInFrames) *
- drawingWidth,
+ if ('points' in visibleVolume) {
+ for (const point of visibleVolume.points) {
+ context.lineTo(
+ ((point.frame - displayOffsetInFrames) / displayDurationInFrames) *
+ drawingWidth,
+ Math.max(
+ 0,
+ Math.min(h, (1 - point.value / visualizationMaxVolume) * h),
+ ),
+ );
+ }
+ } else {
+ // The canvas only spans the virtualized range. Sampling by its physical
+ // width keeps drawing work bounded to the visible part of the timeline.
+ const numberOfPoints = Math.min(
+ visibleVolume.length,
+ Math.max(1, Math.ceil(drawingWidth)),
);
- const nextX =
- point === numberOfPoints - 1
- ? drawingWidth
- : Math.min(
- drawingWidth,
- ((firstFrame + nextVolumeIndex - displayOffsetInFrames) /
- displayDurationInFrames) *
+ for (let point = 0; point < numberOfPoints; point++) {
+ const volumeIndex = Math.floor(
+ (point / numberOfPoints) * visibleVolume.length,
+ );
+ const nextVolumeIndex = Math.floor(
+ ((point + 1) / numberOfPoints) * visibleVolume.length,
+ );
+ const firstFrame = Math.max(0, Math.floor(displayOffsetInFrames));
+ const x = Math.max(
+ 0,
+ ((firstFrame + volumeIndex - displayOffsetInFrames) /
+ displayDurationInFrames) *
+ drawingWidth,
+ );
+ const nextX =
+ point === numberOfPoints - 1
+ ? drawingWidth
+ : Math.min(
drawingWidth,
- );
- const unclampedY =
- (1 - (visibleVolume[volumeIndex] ?? 1) / visualizationMaxVolume) * h;
- const y = Math.max(0, Math.min(h, unclampedY));
- // Volume samples apply for one frame. Keep each value until the next
- // frame boundary instead of blending a hold into a diagonal ramp.
- context.lineTo(x, y);
- context.lineTo(nextX, y);
+ ((firstFrame + nextVolumeIndex - displayOffsetInFrames) /
+ displayDurationInFrames) *
+ drawingWidth,
+ );
+ const unclampedY =
+ (1 - (visibleVolume[volumeIndex] ?? 1) / visualizationMaxVolume) * h;
+ const y = Math.max(0, Math.min(h, unclampedY));
+ // Volume samples apply for one frame. Keep each value until the next
+ // frame boundary instead of blending a hold into a diagonal ramp.
+ context.lineTo(x, y);
+ context.lineTo(nextX, y);
+ }
}
context.lineTo(drawingWidth, 0);
diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsx
index 9b067ed9db..da91117ff0 100644
--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx
@@ -68,13 +68,10 @@ import {
} from './get-sequence-context-menu-items';
import {getSequenceSplitMenuItem} from './get-sequence-split-menu-item';
import {getSequencesContextForAgents} from './get-sequences-context-for-agents';
-import {
- getKeyframeDisplayOffset,
- getKeyframePlaybackRate,
-} from './get-timeline-keyframes';
import {getTimelineMediaStartFrame} from './get-timeline-media-start-frame';
import {getTimelineSceneMask} from './get-timeline-scene-mask';
import {getTimelineSequenceVisibleLayout} from './get-timeline-sequence-visible-layout';
+import {getTimelineVolume} from './get-timeline-volume';
import {getCurrentFrame} from './imperative-state';
import {LoopedTimelineIndicator} from './LoopedTimelineIndicators';
import {splitSelectedTimelineItems} from './split-selected-timeline-item';
@@ -1407,50 +1404,14 @@ const useTimelineSequenceState = (props: TimelineSequenceProps) => {
const displayDurationInFrames = s.loopDisplay
? s.loopDisplay.durationInFrames * s.loopDisplay.numberOfTimes
: s.duration;
- const keyframedTimelineVolume = useMemo((): readonly number[] | null => {
- if (volumeKeyframeStatus === null) {
- return null;
- }
-
- if (
- !Number.isFinite(displayDurationInFrames) ||
- displayDurationInFrames <= 0
- ) {
- return [];
- }
-
- const resolvedDisplayOffset = getKeyframeDisplayOffset({
- propStatus: volumeKeyframeStatus,
+ const timelineVolume = useMemo(() => {
+ return getTimelineVolume({
+ status: volumeKeyframeStatus,
+ displayDurationInFrames,
+ firstDisplayFrame: s.from + (s.loopDisplay?.startOffset ?? 0),
keyframeDisplayOffset,
keyframePlaybackRate,
});
- const resolvedPlaybackRate = getKeyframePlaybackRate(
- volumeKeyframeStatus,
- keyframePlaybackRate,
- );
- const firstDisplayFrame = s.from + (s.loopDisplay?.startOffset ?? 0);
- const evaluateVolume = Internals.prepareNumericKeyframedStatus({
- forceSpringAllowTail: null,
- status: volumeKeyframeStatus,
- });
- if (evaluateVolume === null) {
- return null;
- }
-
- const curve: number[] = [];
- for (let index = 0; index < Math.ceil(displayDurationInFrames); index++) {
- const value = evaluateVolume(
- (firstDisplayFrame + index - resolvedDisplayOffset) *
- resolvedPlaybackRate,
- );
- if (typeof value !== 'number' || !Number.isFinite(value)) {
- return null;
- }
-
- curve.push(Math.max(0, value));
- }
-
- return curve;
}, [
displayDurationInFrames,
keyframeDisplayOffset,
@@ -1459,7 +1420,6 @@ const useTimelineSequenceState = (props: TimelineSequenceProps) => {
s.loopDisplay?.startOffset,
volumeKeyframeStatus,
]);
- const timelineVolume = keyframedTimelineVolume ?? 1;
const isMedia = s.type === 'audio' || s.type === 'video';
const durationInFramesCodeValue =
diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
index 70259736fc..720c629668 100644
--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
@@ -13,7 +13,6 @@ import {
makeFrameDatabaseKey,
resizeVideoFrame,
snapCanvasPositionToDevicePixel,
- type WaveformVolume,
WEBCODECS_TIMESCALE,
} from '@remotion/timeline-utils';
import React, {useLayoutEffect, useMemo, useRef, useState} from 'react';
@@ -28,6 +27,7 @@ import {
} from '../../helpers/timeline-layout';
import {AudioWaveform} from '../AudioWaveform';
import {getTimelineMediaStartFrame} from './get-timeline-media-start-frame';
+import type {TimelineVolume} from './get-timeline-volume';
import {getTimelineVideoFilmstripTimes} from './timeline-video-filmstrip-times';
const outerStyle: React.CSSProperties = {
@@ -65,7 +65,7 @@ const TimelineVideoInfoSegment: React.FC<{
readonly loopWidth: number;
} | null;
readonly playbackRate: number;
- readonly volume: WaveformVolume;
+ readonly volume: TimelineVolume;
readonly muted: boolean;
readonly frozenMediaFrame: number | null;
readonly extendLastFrame: boolean;
@@ -563,7 +563,7 @@ const TimelineVideoInfoInner: React.FC<{
readonly mediaFrameAtSequenceZero: number | null;
readonly sequenceFrameOffset: number;
readonly playbackRate: number;
- readonly volume: WaveformVolume;
+ readonly volume: TimelineVolume;
readonly muted: boolean;
readonly marginLeft: number;
readonly loopDisplay: LoopDisplay | undefined;
@@ -640,6 +640,15 @@ const TimelineVideoInfoInner: React.FC<{
return volume;
}
+ if ('points' in volume) {
+ return {
+ points: volume.points.map((point) => ({
+ frame: point.frame - segmentDisplayOffsetInFrames,
+ value: point.value,
+ })),
+ };
+ }
+
return volume.slice(
Math.max(0, Math.floor(segmentDisplayOffsetInFrames)),
Math.min(
diff --git a/packages/studio/src/components/Timeline/get-timeline-volume.ts b/packages/studio/src/components/Timeline/get-timeline-volume.ts
new file mode 100644
index 0000000000..85c9c6d4a0
--- /dev/null
+++ b/packages/studio/src/components/Timeline/get-timeline-volume.ts
@@ -0,0 +1,128 @@
+import type {WaveformVolume} from '@remotion/timeline-utils';
+import type {CanUpdateSequencePropStatusKeyframed} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ getKeyframeDisplayOffset,
+ getKeyframePlaybackRate,
+} from './get-timeline-keyframes';
+
+export type TimelineVolume =
+ | WaveformVolume
+ | {
+ readonly points: readonly {
+ readonly frame: number;
+ readonly value: number;
+ }[];
+ };
+
+export const getTimelineVolume = ({
+ status,
+ displayDurationInFrames,
+ firstDisplayFrame,
+ keyframeDisplayOffset,
+ keyframePlaybackRate,
+}: {
+ readonly status: CanUpdateSequencePropStatusKeyframed | null;
+ readonly displayDurationInFrames: number;
+ readonly firstDisplayFrame: number;
+ readonly keyframeDisplayOffset: number;
+ readonly keyframePlaybackRate: number;
+}): TimelineVolume => {
+ if (status === null) {
+ return 1;
+ }
+
+ if (
+ !Number.isFinite(displayDurationInFrames) ||
+ displayDurationInFrames <= 0
+ ) {
+ return [];
+ }
+
+ const resolvedDisplayOffset = getKeyframeDisplayOffset({
+ propStatus: status,
+ keyframeDisplayOffset,
+ keyframePlaybackRate,
+ });
+ const resolvedPlaybackRate = getKeyframePlaybackRate(
+ status,
+ keyframePlaybackRate,
+ );
+ const evaluateVolume = Internals.prepareNumericKeyframedStatus({
+ forceSpringAllowTail: null,
+ status,
+ });
+ if (evaluateVolume === null) {
+ return 1;
+ }
+
+ if (
+ status.easing.every((easing) => easing.type === 'linear') &&
+ status.posterize === undefined &&
+ (status.output === undefined || status.output === 'linear') &&
+ status.clamping.left !== 'identity' &&
+ status.clamping.right !== 'identity' &&
+ status.clamping.left !== 'wrap' &&
+ status.clamping.right !== 'wrap' &&
+ Number.isFinite(resolvedPlaybackRate) &&
+ resolvedPlaybackRate > 0
+ ) {
+ // Include the clip boundaries for clamping/extrapolation, and keep exact
+ // keyframe positions even when playback rate puts them between frames.
+ const frames = [
+ 0,
+ ...status.keyframes
+ .map(
+ (keyframe) =>
+ keyframe.frame / resolvedPlaybackRate +
+ resolvedDisplayOffset -
+ firstDisplayFrame,
+ )
+ .filter((frame) => frame > 0 && frame < displayDurationInFrames),
+ displayDurationInFrames,
+ ].sort((a, b) => a - b);
+ const points: {frame: number; value: number}[] = [];
+ let previousValue = 0;
+ for (const frame of frames) {
+ const value = evaluateVolume(
+ (firstDisplayFrame + frame - resolvedDisplayOffset) *
+ resolvedPlaybackRate,
+ );
+ if (value === null || !Number.isFinite(value)) {
+ return 1;
+ }
+
+ const previousPoint = points.at(-1);
+ if (previousPoint && previousValue * value < 0) {
+ // Clamping negative volumes adds a corner where the line crosses zero.
+ points.push({
+ frame:
+ previousPoint.frame +
+ ((frame - previousPoint.frame) * -previousValue) /
+ (value - previousValue),
+ value: 0,
+ });
+ }
+
+ points.push({frame, value: Math.max(0, value)});
+ previousValue = value;
+ }
+
+ return {points};
+ }
+
+ const curve: number[] = [];
+ for (let index = 0; index < Math.ceil(displayDurationInFrames); index++) {
+ const value = evaluateVolume(
+ (firstDisplayFrame + index - resolvedDisplayOffset) *
+ resolvedPlaybackRate,
+ );
+ if (value === null || !Number.isFinite(value)) {
+ return 1;
+ }
+
+ curve.push(Math.max(0, value));
+ }
+
+ return curve;
+};