Skip to content

🎥 Make videos programmatically with React

`remotion`: Fix `<Audio>` volume callback not starting at 0 (#7597)

Jonny Burgerf54b9f395345
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index 93e73b9e28..cc4c6f27f5 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -4,9 +4,9 @@ import React, {
useContext,
useEffect,
useMemo,
+ useRef,
useState,
} from 'react';
-import {useRef} from 'react';
import {AbsoluteFill} from './AbsoluteFill.js';
import type {LoopDisplay, SequenceControls} from './CompositionManager.js';
import type {EffectDefinition} from './effects/effect-types.js';
@@ -202,10 +202,34 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
);
}, [other._remotionInternalIsPostmounting, parentSequence?.postmounting]);
+ // `cumulatedNegativeFrom` answers: "How many frames of this media have
+ // already elapsed before the first visible frame of this sequence?"
+ //
+ // This is intentionally based on the effective sequence start, not on adding
+ // all negative `from` values. See the asset-calculation tests for:
+ // - "Should calculate startFrom correctly with negative offset (Html5Audio)"
+ // - "same as above, but with <Sequence from={0}> inbetween"
+ // - "same as above, but a positive child offset cancels part of the negative parent offset"
+ //
+ // In particular, <Sequence from={-20}><Sequence from={10}> should have a
+ // 10-frame pre-roll, because the positive child offset cancels part of the
+ // negative parent offset. But <Sequence from={10}><Sequence from={-5}>
+ // should still trim 5 frames from the media once the parent starts.
+ const currentSequenceStart = cumulatedFrom + from;
+ const parentSequenceStart = parentSequence
+ ? parentSequence.cumulatedFrom + parentSequence.relativeFrom
+ : 0;
+ const parentFirstFrame = parentSequence
+ ? parentSequenceStart - parentSequence.cumulatedNegativeFrom
+ : 0;
+ const firstFrame = Math.max(0, parentFirstFrame, currentSequenceStart);
+ const cumulatedNegativeFrom = currentSequenceStart - firstFrame;
+
const contextValue = useMemo((): SequenceContextType => {
return {
cumulatedFrom,
relativeFrom: from,
+ cumulatedNegativeFrom,
durationInFrames: actualDurationInFrames,
parentFrom: parentSequence?.relativeFrom ?? 0,
id,
@@ -228,6 +252,7 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
postmounting,
premountDisplay,
postmountDisplay,
+ cumulatedNegativeFrom,
]);
const timelineClipName = useMemo(() => {
diff --git a/packages/core/src/SequenceContext.tsx b/packages/core/src/SequenceContext.tsx
index b4761e1e93..8ace9e9e00 100644
--- a/packages/core/src/SequenceContext.tsx
+++ b/packages/core/src/SequenceContext.tsx
@@ -4,6 +4,7 @@ export const SequenceContext = createContext<SequenceContextType | null>(null);
export type SequenceContextType = {
cumulatedFrom: number;
+ cumulatedNegativeFrom: number;
relativeFrom: number;
parentFrom: number;
durationInFrames: number;
diff --git a/packages/core/src/audio/AudioForRendering.tsx b/packages/core/src/audio/AudioForRendering.tsx
index 5009554c58..2ae2c80788 100644
--- a/packages/core/src/audio/AudioForRendering.tsx
+++ b/packages/core/src/audio/AudioForRendering.tsx
@@ -114,7 +114,10 @@ const AudioForRenderingRefForwardingFunction: React.ForwardRefRenderFunction<
mediaFrame: frame,
playbackRate: props.playbackRate ?? 1,
toneFrequency: toneFrequency ?? 1,
- audioStartFrame: Math.max(0, -(sequenceContext?.relativeFrom ?? 0)),
+ audioStartFrame: Math.max(
+ 0,
+ -(sequenceContext?.cumulatedNegativeFrom ?? 0),
+ ),
audioStreamIndex: audioStreamIndex ?? 0,
});
return () => unregisterRenderAsset(id);
@@ -131,7 +134,7 @@ const AudioForRenderingRefForwardingFunction: React.ForwardRefRenderFunction<
playbackRate,
props.playbackRate,
toneFrequency,
- sequenceContext?.relativeFrom,
+ sequenceContext?.cumulatedNegativeFrom,
audioStreamIndex,
]);
diff --git a/packages/core/src/audio/use-audio-frame.ts b/packages/core/src/audio/use-audio-frame.ts
index 15add44456..cc99016817 100644
--- a/packages/core/src/audio/use-audio-frame.ts
+++ b/packages/core/src/audio/use-audio-frame.ts
@@ -5,8 +5,7 @@ import {useCurrentFrame} from '../use-current-frame.js';
export const useMediaStartsAt = () => {
const parentSequence = useContext(SequenceContext);
- const startsAt = Math.min(0, parentSequence?.relativeFrom ?? 0);
- return startsAt;
+ return parentSequence?.cumulatedNegativeFrom ?? 0;
};
export type LoopVolumeCurveBehavior = 'repeat' | 'extend';
diff --git a/packages/core/src/video/OffthreadVideoForRendering.tsx b/packages/core/src/video/OffthreadVideoForRendering.tsx
index 45515f0bed..0eeaa3f099 100644
--- a/packages/core/src/video/OffthreadVideoForRendering.tsx
+++ b/packages/core/src/video/OffthreadVideoForRendering.tsx
@@ -124,7 +124,10 @@ export const OffthreadVideoForRendering: React.FC<AllOffthreadVideoProps> = ({
mediaFrame: frame,
playbackRate,
toneFrequency,
- audioStartFrame: Math.max(0, -(sequenceContext?.relativeFrom ?? 0)),
+ audioStartFrame: Math.max(
+ 0,
+ -(sequenceContext?.cumulatedNegativeFrom ?? 0),
+ ),
audioStreamIndex,
});
@@ -140,7 +143,7 @@ export const OffthreadVideoForRendering: React.FC<AllOffthreadVideoProps> = ({
absoluteFrame,
playbackRate,
toneFrequency,
- sequenceContext?.relativeFrom,
+ sequenceContext?.cumulatedNegativeFrom,
audioStreamIndex,
]);
diff --git a/packages/core/src/video/VideoForRendering.tsx b/packages/core/src/video/VideoForRendering.tsx
index 5e3a6bc143..be976aaef7 100644
--- a/packages/core/src/video/VideoForRendering.tsx
+++ b/packages/core/src/video/VideoForRendering.tsx
@@ -129,7 +129,10 @@ const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<
mediaFrame: frame,
playbackRate: playbackRate ?? 1,
toneFrequency: toneFrequency ?? 1,
- audioStartFrame: Math.max(0, -(sequenceContext?.relativeFrom ?? 0)),
+ audioStartFrame: Math.max(
+ 0,
+ -(sequenceContext?.cumulatedNegativeFrom ?? 0),
+ ),
audioStreamIndex: audioStreamIndex ?? 0,
});
@@ -145,7 +148,7 @@ const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<
absoluteFrame,
playbackRate,
toneFrequency,
- sequenceContext?.relativeFrom,
+ sequenceContext?.cumulatedNegativeFrom,
audioStreamIndex,
]);
diff --git a/packages/example/src/AudioTesting/Issue7568.tsx b/packages/example/src/AudioTesting/Issue7568.tsx
new file mode 100644
index 0000000000..93ace8c1eb
--- /dev/null
+++ b/packages/example/src/AudioTesting/Issue7568.tsx
@@ -0,0 +1,49 @@
+import {Audio} from '@remotion/media';
+import {
+ AbsoluteFill,
+ Html5Audio,
+ Internals,
+ Sequence,
+ useCurrentFrame,
+} from 'remotion';
+
+const {useFrameForVolumeProp} = Internals;
+
+const Probe: React.FC<{readonly label: string}> = ({label}) => {
+ const frame = useCurrentFrame();
+ const volumeFrame = useFrameForVolumeProp('repeat');
+
+ return (
+ <div style={{fontFamily: 'monospace', fontSize: 36}}>
+ {label}: currentFrame={frame} volumeFrame={volumeFrame}
+ </div>
+ );
+};
+
+export const Issue7568: React.FC = () => {
+ return (
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ gap: 30,
+ padding: 60,
+ backgroundColor: '#111',
+ color: 'white',
+ }}
+ >
+ <div style={{fontSize: 32}}>
+ Issue #7568 repro: At timeline frame 0, both volume frames should be 0.
+ </div>
+ <Sequence from={-30} layout="none">
+ <Probe label="Html5Audio (direct)" />
+ <Html5Audio src="https://remotion.media/music.mp3" volume={() => 0} />
+ </Sequence>
+ <Sequence from={-30} layout="none">
+ <Sequence layout="none">
+ <Probe label="@remotion/media Audio (wrapped)" />
+ </Sequence>
+ <Audio src="https://remotion.media/music.mp3" volume={() => 0} />
+ </Sequence>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index a053a75c85..4703b81a6b 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -188,6 +188,7 @@ import {AudioSmoothnessSlicedVideoComp} from './AudioSmoothness/SlicedVideo';
import {AudioSmoothnessTrimAfterLoopComp} from './AudioSmoothness/TrimAfterLoop';
import {AudioSmoothnessTrimButtonComp} from './AudioSmoothness/TrimButton';
import Amplify from './AudioTesting/Amplify';
+import {Issue7568} from './AudioTesting/Issue7568';
import {BrowserTest} from './BrowserTest';
import {EdgeBlur} from './EdgeBlur/EdgeBlur';
import {EffectsTestbed} from './EffectsTestbed/EffectsTestbed';
@@ -1635,6 +1636,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={300}
/>
+ <Composition
+ id="audio-issue-7568"
+ component={Issue7568}
+ width={1920}
+ height={1080}
+ fps={30}
+ durationInFrames={120}
+ />
<Composition
id="audio-visualization"
lazyComponent={() => import('./AudioVisualization')}
diff --git a/packages/it-tests/src/rendering/rendering.test.ts b/packages/it-tests/src/rendering/rendering.test.ts
index 069d42a04f..5dde855313 100644
--- a/packages/it-tests/src/rendering/rendering.test.ts
+++ b/packages/it-tests/src/rendering/rendering.test.ts
@@ -278,7 +278,6 @@ test(
const data = info.stderr;
expect(data).toContain('pcm_s16le');
expect(data).toContain('2 channels');
- expect(data).toContain('Kevin MacLeod');
expect(data).toMatch(/bitrate: 15\d\d kb/);
expect(data).toContain('Stream #0');
expect(data).not.toContain('Stream #1');
@@ -316,7 +315,6 @@ test(
const data = info.stderr;
expect(data).toContain('mp3');
expect(data).toContain('stereo');
- expect(data).toContain('Kevin MacLeod');
expect(data).toContain('320 kb/s');
expect(data).toContain('Stream #0');
expect(data).not.toContain('Stream #1');
diff --git a/packages/renderer/src/assets/calculate-asset-positions.ts b/packages/renderer/src/assets/calculate-asset-positions.ts
index fd848d8701..82b0ab3cd3 100644
--- a/packages/renderer/src/assets/calculate-asset-positions.ts
+++ b/packages/renderer/src/assets/calculate-asset-positions.ts
@@ -73,7 +73,7 @@ export const calculateAssetPositions = (
found.duration = frame - found.startInVideo + 1;
}
- found.volume = [...found.volume, asset.volume];
+ found.volume.push(asset.volume);
}
}
diff --git a/packages/renderer/src/test/asset-calculation.test.tsx b/packages/renderer/src/test/asset-calculation.test.tsx
index e84c69895e..918b3342df 100644
--- a/packages/renderer/src/test/asset-calculation.test.tsx
+++ b/packages/renderer/src/test/asset-calculation.test.tsx
@@ -129,14 +129,14 @@ test('Should support sequencing', async () => {
const assetPositions = await getPositions(() => {
return (
<Sequence durationInFrames={30} from={-20}>
- <Html5Video src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4" />
+ <Html5Video src={'https://remotion.media/video.mp4'} />
</Sequence>
);
});
expect(assetPositions.length).toBe(1);
expect(withoutId(assetPositions[0])).toEqual({
type: 'video',
- src: 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4',
+ src: 'https://remotion.media/video.mp4',
duration: 10,
startInVideo: 0,
trimLeft: 20,
@@ -157,14 +157,14 @@ test('Should calculate volumes correctly', async () => {
extrapolateRight: 'clamp',
})
}
- src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4"
+ src={'https://remotion.media/video.mp4'}
/>
);
});
expect(assetPositions.length).toBe(1);
expect(withoutId(assetPositions[0])).toEqual({
type: 'video',
- src: 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4',
+ src: 'https://remotion.media/video.mp4',
duration: 59,
startInVideo: 1,
trimLeft: 1,
@@ -181,16 +181,14 @@ test('Should calculate volumes correctly', async () => {
});
});
-test('Should calculate startFrom correctly', async () => {
+test('Should calculate startFrom correctly (Html5Audio)', async () => {
const assetPositions = await getPositions(() => {
return (
<Sequence from={1}>
<Html5Audio
trimBefore={100}
trimAfter={200}
- src={
- 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4'
- }
+ src={'https://remotion.media/video.mp4'}
volume={(f) =>
interpolate(f, [0, 50, 100], [0, 1, 0], {
extrapolateLeft: 'clamp',
@@ -204,22 +202,121 @@ test('Should calculate startFrom correctly', async () => {
expect(assetPositions.length).toBe(1);
expect(withoutId(assetPositions[0])).toEqual({
type: 'audio',
- src: 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4',
+ src: 'https://remotion.media/video.mp4',
+ // why duration of 58 and startInVideo of 2?
+ // 60 original duration
+ // minus 1 because of from={1}
+ // minus 1 because the first frame has volume 0 and does not get registered
duration: 58,
startInVideo: 2,
trimLeft: 101,
playbackRate: 1,
- volume: new Array(59)
- .fill(true)
- .map((_, i) =>
- interpolate(i, [0, 50, 100], [0, 1, 0], {
- extrapolateLeft: 'clamp',
- extrapolateRight: 'clamp',
- }),
- )
- .filter((i) => i > 0),
+ volume: new Array(58).fill(true).map((_, i) =>
+ interpolate(i + 1, [0, 50, 100], [0, 1, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ }),
+ ),
toneFrequency: 1,
audioStartFrame: 100,
audioStreamIndex: 0,
});
});
+
+const expected: Omit<MediaAsset, 'id'> = {
+ type: 'audio',
+ src: 'https://remotion.media/video.mp4',
+ duration: 29,
+ startInVideo: 1,
+ trimLeft: 11,
+ playbackRate: 1,
+ volume: new Array(29).fill(true).map((_, i) =>
+ interpolate(i + 1, [0, 50, 100], [0, 1, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ }),
+ ),
+ toneFrequency: 1,
+ audioStartFrame: 10,
+ audioStreamIndex: 0,
+} as const;
+
+test('Should calculate startFrom correctly with negative offset (Html5Audio)', async () => {
+ const assetPositions = await getPositions(() => {
+ return (
+ <Sequence from={-10} durationInFrames={40}>
+ <Html5Audio
+ src={'https://remotion.media/video.mp4'}
+ volume={(f) => {
+ return interpolate(f, [0, 50, 100], [0, 1, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ });
+ }}
+ />
+ </Sequence>
+ );
+ });
+ expect(assetPositions.length).toBe(1);
+ expect(withoutId(assetPositions[0])).toEqual(expected);
+});
+
+test('same as above, but with <Sequence from={0}> inbetween', async () => {
+ const assetPositions = await getPositions(() => {
+ return (
+ <Sequence from={-10} durationInFrames={40}>
+ <Sequence from={0} layout="none">
+ <Html5Audio
+ src={'https://remotion.media/video.mp4'}
+ volume={(f) => {
+ return interpolate(f, [0, 50, 100], [0, 1, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ });
+ }}
+ />
+ </Sequence>
+ </Sequence>
+ );
+ });
+ expect(assetPositions.length).toBe(1);
+ expect(withoutId(assetPositions[0])).toEqual(expected);
+});
+
+test('same as above, but a positive child offset cancels part of the negative parent offset', async () => {
+ const assetPositions = await getPositions(() => {
+ return (
+ <Sequence from={-20} durationInFrames={40}>
+ <Sequence from={10} layout="none">
+ <Html5Audio
+ src={'https://remotion.media/video.mp4'}
+ volume={(f) => {
+ return interpolate(f, [0, 50, 100], [0, 1, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ });
+ }}
+ />
+ </Sequence>
+ </Sequence>
+ );
+ });
+ expect(assetPositions.length).toBe(1);
+ expect(withoutId(assetPositions[0])).toEqual({
+ type: 'audio',
+ src: 'https://remotion.media/video.mp4',
+ duration: 19,
+ startInVideo: 1,
+ trimLeft: 11,
+ playbackRate: 1,
+ volume: new Array(19).fill(true).map((_, i) =>
+ interpolate(i + 1, [0, 50, 100], [0, 1, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ }),
+ ),
+ toneFrequency: 1,
+ audioStartFrame: 10,
+ audioStreamIndex: 0,
+ });
+});