Skip to content

🎥 Make videos programmatically with React

sequencing refactor

Jonny Burger25f12a73b6c1
diff --git a/packages/cli/src/editor/components/AudioWaveform.tsx b/packages/cli/src/editor/components/AudioWaveform.tsx
index 0de665e2e6..35ae06e376 100644
--- a/packages/cli/src/editor/components/AudioWaveform.tsx
+++ b/packages/cli/src/editor/components/AudioWaveform.tsx
@@ -1,15 +1,14 @@
-import React, {useEffect, useState} from 'react';
+import React, {useEffect, useMemo, useState} from 'react';
-const filterData = (audioBuffer: AudioBuffer) => {
- const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
+const filterData = (audioBuffer: Float32Array) => {
const samples = 200; // Number of samples we want to have in our final data set
- const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
+ const blockSize = Math.floor(audioBuffer.length / samples); // the number of samples in each subdivision
const filteredData = [];
for (let i = 0; i < samples; i++) {
const blockStart = blockSize * i; // the location of the first sample in the block
let sum = 0;
for (let j = 0; j < blockSize; j++) {
- sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
+ sum = sum + Math.abs(audioBuffer[blockStart + j]); // find the sum of all the samples in the block
}
filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
}
@@ -27,21 +26,27 @@ export const AudioWaveform: React.FC<{
}> = ({src}) => {
// TODO: Resize to timeline length so it aligns with cursor
- const [waveform, setWaveform] = useState<number[] | null>(null);
+ const [waveform, setWaveform] = useState<Float32Array | null>(null);
useEffect(() => {
const audioContext = new AudioContext();
fetch(src)
.then((response) => response.arrayBuffer())
.then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer))
- .then((audioBuffer) => filterData(audioBuffer))
- .then((filtered) => normalizeData(filtered))
- .then((wave) => setWaveform(wave))
+ .then((wave) => setWaveform(wave.getChannelData(0)))
.catch((err) => {
// TODO: Error handling
console.log(err);
});
}, [src]);
+
+ const normalized = useMemo(() => {
+ if (!waveform) {
+ return [];
+ }
+ return normalizeData(filterData(waveform));
+ }, [waveform]);
+
if (!waveform) {
return null;
}
@@ -55,7 +60,7 @@ export const AudioWaveform: React.FC<{
height: 60,
}}
>
- {waveform.map((w, i) => {
+ {normalized.map((w, i) => {
return (
<div
// eslint-disable-next-line react/no-array-index-key
diff --git a/packages/cli/src/editor/components/TimelineElements.tsx b/packages/cli/src/editor/components/TimelineElements.tsx
index e98bd8c193..922e5856f5 100644
--- a/packages/cli/src/editor/components/TimelineElements.tsx
+++ b/packages/cli/src/editor/components/TimelineElements.tsx
@@ -2,6 +2,7 @@ import React, {useContext, useMemo} from 'react';
import {Internals} from 'remotion';
import styled from 'styled-components';
import {calculateTimeline, Track} from '../helpers/calculate-timeline';
+import {AudioWaveform} from './AudioWaveform';
const Container = styled.div`
height: 100%;
@@ -60,12 +61,12 @@ export const TimelineElements: React.FC = () => {
key={s.sequence.id}
style={{
background:
- track.trackType === 'sequence'
+ s.sequence.type === 'sequence'
? SEQUENCE_GRADIENT
: AUDIO_GRADIENT,
border: '1px solid rgba(255, 255, 255, 0.2)',
borderRadius: 4,
- height: track.trackType === 'sequence' ? 80 : 60,
+ height: s.sequence.type === 'sequence' ? 80 : 60,
marginTop: 1,
marginLeft: `calc(${(s.sequence.from / lastFrame) * 100}%)`,
width:
@@ -77,6 +78,9 @@ export const TimelineElements: React.FC = () => {
}}
title={s.sequence.displayName}
>
+ {s.sequence.type === 'audio' ? (
+ <AudioWaveform src={s.sequence.src} />
+ ) : null}
<Pre>{s.sequence.displayName}</Pre>
</div>
);
diff --git a/packages/cli/src/editor/helpers/calculate-timeline.ts b/packages/cli/src/editor/helpers/calculate-timeline.ts
index 47c9ceadc1..ac7959e06b 100644
--- a/packages/cli/src/editor/helpers/calculate-timeline.ts
+++ b/packages/cli/src/editor/helpers/calculate-timeline.ts
@@ -5,20 +5,10 @@ export type SequenceWithOverlap = {
overlaps: TSequence[];
};
-type DynamicTrackAttributes =
- | {
- trackType: 'audio';
- audioForWaveform: string;
- }
- | {
- trackType: 'sequence';
- };
-
export type Track = {
trackId: string;
sequences: SequenceWithOverlap[];
- audioForWaveform: string | null;
-} & DynamicTrackAttributes;
+};
export const calculateOverlays = (
sequences: TSequence[]
@@ -75,12 +65,12 @@ const getAudioTracks = (
from: 0,
id: `audio-${i}`,
parent: null,
+ type: 'audio',
+ src: a.src,
},
},
],
trackId: `audio-${i}`,
- trackType: 'audio',
- audioForWaveform: a.src,
};
}
);
@@ -110,12 +100,11 @@ export const calculateTimeline = ({
from: 0,
id: 'seq',
parent: null,
+ type: 'sequence',
},
},
],
trackId: '0',
- trackType: 'sequence',
- audioForWaveform: null,
},
...getAudioTracks(assets, sequenceDuration),
];
@@ -132,8 +121,6 @@ export const calculateTimeline = ({
tracks[overlayCount] = {
sequences: [],
trackId: String(overlayCount),
- trackType: 'sequence',
- audioForWaveform: null,
};
}
tracks[overlayCount].sequences.push(sequence);
diff --git a/packages/core/src/CompositionManager.tsx b/packages/core/src/CompositionManager.tsx
index 2b26f095ac..3431a45b5d 100644
--- a/packages/core/src/CompositionManager.tsx
+++ b/packages/core/src/CompositionManager.tsx
@@ -15,13 +15,26 @@ export type TCompMetadata = Pick<
'id' | 'height' | 'width' | 'fps' | 'durationInFrames'
>;
+type EnhancedTSequenceData =
+ | {
+ type: 'sequence';
+ }
+ | {
+ type: 'audio';
+ src: string;
+ }
+ | {
+ type: 'video';
+ src: string;
+ };
+
export type TSequence = {
from: number;
duration: number;
id: string;
displayName: string;
parent: string | null;
-};
+} & EnhancedTSequenceData;
export type TAsset = {
type: 'audio' | 'video';
diff --git a/packages/core/src/audio/AudioForDevelopment.tsx b/packages/core/src/audio/AudioForDevelopment.tsx
index 4a9f9a0c17..bcdcb9d821 100644
--- a/packages/core/src/audio/AudioForDevelopment.tsx
+++ b/packages/core/src/audio/AudioForDevelopment.tsx
@@ -1,5 +1,6 @@
import React, {useContext, useEffect, useRef, useState} from 'react';
import {CompositionManager} from '../CompositionManager';
+import {getAssetFileName} from '../get-asset-file-name';
import {isApproximatelyTheSame} from '../is-approximately-the-same';
import {SequenceContext} from '../sequencing';
import {usePlayingState} from '../timeline-position-state';
@@ -17,8 +18,9 @@ export const AudioForDevelopment: React.FC<RemotionAudioProps> = (props) => {
const videoConfig = useUnsafeVideoConfig();
const [playing] = usePlayingState();
const parentSequence = useContext(SequenceContext);
+ const actualFrom = parentSequence?.from ?? 0;
- const {registerAsset, unregisterAsset} = useContext(CompositionManager);
+ const {registerSequence, unregisterSequence} = useContext(CompositionManager);
const [id] = useState(() => String(Math.random()));
@@ -72,32 +74,35 @@ export const AudioForDevelopment: React.FC<RemotionAudioProps> = (props) => {
if (!audioRef.current) {
return;
}
+ if (!videoConfig) {
+ return;
+ }
if (!props.src) {
throw new Error('No src passed');
}
- // Currently we only show audio in the timeline
- // that is **not inside a sequence**.
- if (parentSequence) {
- return;
- }
- registerAsset({
+ registerSequence({
type: 'audio',
src: props.src,
id,
- sequenceFrame: currentFrame,
- volume: userPreferredVolume,
+ // TODO: Cap to audio duration
+ duration: videoConfig.durationInFrames,
+ from: actualFrom,
+ parent: parentSequence?.id ?? null,
+ displayName: getAssetFileName(props.src),
});
- return () => unregisterAsset(id);
+ return () => unregisterSequence(id);
}, [
props.src,
- registerAsset,
id,
- unregisterAsset,
currentFrame,
parentSequence,
actualVolume,
userPreferredVolume,
+ registerSequence,
+ unregisterSequence,
+ videoConfig,
+ actualFrom,
]);
useEffect(() => {
@@ -105,7 +110,9 @@ export const AudioForDevelopment: React.FC<RemotionAudioProps> = (props) => {
throw new Error('No audio ref found');
}
if (!videoConfig) {
- throw new Error('No video config found');
+ throw new Error(
+ 'No video config found. <Audio> must be placed inside a composition.'
+ );
}
const shouldBeTime = currentFrame / videoConfig.fps;
diff --git a/packages/core/src/get-asset-file-name.ts b/packages/core/src/get-asset-file-name.ts
new file mode 100644
index 0000000000..64077d9413
--- /dev/null
+++ b/packages/core/src/get-asset-file-name.ts
@@ -0,0 +1,7 @@
+export const getAssetFileName = (filename: string): string => {
+ const splitted = filename
+ .split('/')
+ .map((s) => s.split('\\'))
+ .flat(1);
+ return splitted[splitted.length - 1];
+};
diff --git a/packages/core/src/sequencing/index.tsx b/packages/core/src/sequencing/index.tsx
index 452d4b975b..c94ef0c674 100644
--- a/packages/core/src/sequencing/index.tsx
+++ b/packages/core/src/sequencing/index.tsx
@@ -72,6 +72,7 @@ export const Sequence: React.FC<{
id,
displayName: timelineClipName,
parent: parentSequence?.id ?? null,
+ type: 'sequence',
});
return () => {
unregisterSequence(id);
diff --git a/packages/core/src/video/VideoForDevelopment.tsx b/packages/core/src/video/VideoForDevelopment.tsx
index d14c4d4b92..0e29663368 100644
--- a/packages/core/src/video/VideoForDevelopment.tsx
+++ b/packages/core/src/video/VideoForDevelopment.tsx
@@ -39,7 +39,9 @@ export const VideoForDevelopment: React.FC<RemotionVideoProps> = (props) => {
}
if (!videoConfig) {
- throw new Error('No video config found');
+ throw new Error(
+ 'No video config found. <Video> must be placed inside a composition.'
+ );
}
const currentTime = (() => {
if (FEATURE_FLAG_V2_BREAKING_CHANGES) {
diff --git a/packages/example/package-lock.json b/packages/example/package-lock.json
index 0d680b451f..acf2c7be9b 100644
--- a/packages/example/package-lock.json
+++ b/packages/example/package-lock.json
@@ -1886,6 +1886,14 @@
"csstype": "^3.0.2"
}
},
+ "@types/react-native": {
+ "version": "0.64.0",
+ "resolved": "https://registry.npmjs.org/@types/react-native/-/react-native-0.64.0.tgz",
+ "integrity": "sha512-yys0k6tNby1VxEVfuxpaJRUChMer7lvnxSQfK6EtpxV8rtNk8boo/nQJkUoXgIi0mdhC1pj72flztdkj6wOHPA==",
+ "requires": {
+ "@types/react": "*"
+ }
+ },
"@types/scheduler": {
"version": "0.16.1",
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.1.tgz",
diff --git a/packages/example/package.json b/packages/example/package.json
index a983f4da74..d7dc84c533 100644
--- a/packages/example/package.json
+++ b/packages/example/package.json
@@ -26,6 +26,7 @@
"@remotion/eslint-plugin": "^1.4.0",
"@types/node": "^14.0.13",
"@types/styled-components": "^5.1.1",
+ "@types/react-native": "^0.64.0",
"babel-loader": "^8.2.2",
"mdx-loader": "3.0.2",
"polished": "^4.0.5",
diff --git a/packages/example/src/AudioTestingMute/index.tsx b/packages/example/src/AudioTestingMute/index.tsx
index 7ff20eedc5..95cb011dfc 100644
--- a/packages/example/src/AudioTestingMute/index.tsx
+++ b/packages/example/src/AudioTestingMute/index.tsx
@@ -1,11 +1,5 @@
import React from 'react';
-import {
- Audio,
- Sequence,
- useCurrentFrame,
- useVideoConfig,
- Video,
-} from 'remotion';
+import {Audio, useCurrentFrame, useVideoConfig, Video} from 'remotion';
// FIXME: commit sample movie + music
import movie from '../resources/framer-music.mp4';
import music from '../resources/sound1.mp3';
@@ -33,10 +27,11 @@ const AudioTestingMute: React.FC = () => {
);
return (
- <Sequence from={0} durationInFrames={durationInFrames}>
+ <div>
<Video src={movie} muted={getMuteState('movie')} />
+
<Audio src={music} muted={getMuteState('music')} />
- </Sequence>
+ </div>
);
};