Skip to content

🎥 Make videos programmatically with React

progress

Jonny Burgerd0d49ccc27af
diff --git a/packages/renderer/src/assets/get-asset-audio-details.ts b/packages/renderer/src/assets/get-asset-audio-details.ts
deleted file mode 100644
index 8c0e695d68..0000000000
--- a/packages/renderer/src/assets/get-asset-audio-details.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import {pLimit} from '../p-limit';
-import {getAudioChannels} from './get-audio-channels';
-import {AssetAudioDetails} from './types';
-
-export async function getAssetAudioDetails(options: {
- assetPaths: string[];
-}): Promise<Map<string, AssetAudioDetails>> {
- const uniqueAssets = [...new Set(options.assetPaths)];
- const actualParallelism = 2;
- const parallelLimit = pLimit(actualParallelism);
- const audioChannelTasks = uniqueAssets.map((path) =>
- parallelLimit(() => getAudioChannels(path))
- );
- const result = await Promise.all(audioChannelTasks);
-
- const mappedResults: [string, AssetAudioDetails][] = result.map(
- (channels, index) => {
- return [uniqueAssets[index], {channels}];
- }
- );
-
- return new Map<string, AssetAudioDetails>(mappedResults);
-}
diff --git a/packages/renderer/src/calculate-ffmpeg-filters.ts b/packages/renderer/src/calculate-ffmpeg-filters.ts
index ca82515230..98f638315f 100644
--- a/packages/renderer/src/calculate-ffmpeg-filters.ts
+++ b/packages/renderer/src/calculate-ffmpeg-filters.ts
@@ -1,31 +1,39 @@
import {flattenVolumeArray} from './assets/flatten-volume-array';
-import {AssetAudioDetails, MediaAsset} from './assets/types';
+import {getAudioChannels} from './assets/get-audio-channels';
+import {MediaAsset} from './assets/types';
import {makeFfmpegFilterFile} from './ffmpeg-filter-file';
import {resolveAssetSrc} from './resolve-asset-src';
import {stringifyFfmpegFilter} from './stringify-ffmpeg-filter';
+type ReturnValue = {
+ cleanup: () => void;
+ src: string;
+ filter: string;
+};
+
export const calculateFfmpegFilter = async ({
asset,
fps,
- assetAudioDetails,
durationInFrames,
}: {
asset: MediaAsset;
fps: number;
- assetAudioDetails: Map<string, AssetAudioDetails>;
durationInFrames: number;
-}) => {
+}): Promise<ReturnValue | null> => {
+ const channels = await getAudioChannels(resolveAssetSrc(asset.src));
+
+ if (channels === 0) {
+ null;
+ }
+
const assetTrimLeft = (asset.trimLeft / fps).toFixed(3);
const assetTrimRight = (
(asset.trimLeft + asset.duration * asset.playbackRate) /
fps
).toFixed(3);
- const audioDetails = assetAudioDetails.get(
- resolveAssetSrc(asset.src)
- ) as AssetAudioDetails;
const filter = stringifyFfmpegFilter({
- channels: audioDetails.channels,
+ channels,
startInVideo: asset.startInVideo,
trimLeft: assetTrimLeft,
trimRight: assetTrimRight,
diff --git a/packages/renderer/src/preprocess-audio-track.ts b/packages/renderer/src/preprocess-audio-track.ts
index e617d34832..a753f34276 100644
--- a/packages/renderer/src/preprocess-audio-track.ts
+++ b/packages/renderer/src/preprocess-audio-track.ts
@@ -1,26 +1,43 @@
import execa from 'execa';
import {FfmpegExecutable} from 'remotion';
+import {MediaAsset} from './assets/types';
+import {calculateFfmpegFilter} from './calculate-ffmpeg-filters';
+import {pLimit} from './p-limit';
import {parseFfmpegProgress} from './parse-ffmpeg-progress';
import {DEFAULT_SAMPLE_RATE} from './sample-rate';
type Options = {
ffmpegExecutable: FfmpegExecutable;
- audioFile: string;
- filter: string;
outName: string;
onProgress: (progress: number) => void;
+ asset: MediaAsset;
+ expectedFrames: number;
+ fps: number;
};
-// TODO: Limit concurrency
-export const preprocessAudioTrack = async ({
+const preprocessAudioTrackUnlimited = async ({
ffmpegExecutable,
- audioFile,
- filter,
outName,
onProgress,
+ asset,
+ expectedFrames,
+ fps,
}: Options) => {
+ const data = await calculateFfmpegFilter({
+ asset,
+ durationInFrames: expectedFrames,
+ fps,
+ });
+
+ if (data === null) {
+ onProgress(1);
+ return;
+ }
+
+ const {filter, src, cleanup} = data;
+
const args = [
- ['-i', audioFile],
+ ['-i', src],
['-ac', '2'],
['-filter_script:a', filter],
['-ar', String(DEFAULT_SAMPLE_RATE)],
@@ -39,4 +56,11 @@ export const preprocessAudioTrack = async ({
});
await task;
+ cleanup();
+};
+
+const limit = pLimit(2);
+
+export const preprocessAudioTrack = (options: Options) => {
+ return limit(preprocessAudioTrackUnlimited, options);
};
diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.ts
index f40ebaaaa4..10c1ec7e4d 100644
--- a/packages/renderer/src/stitch-frames-to-video.ts
+++ b/packages/renderer/src/stitch-frames-to-video.ts
@@ -1,4 +1,5 @@
import execa from 'execa';
+import fs from 'fs';
import path from 'path';
import {
Codec,
@@ -17,9 +18,7 @@ import {
markAllAssetsAsDownloaded,
RenderMediaOnDownload,
} from './assets/download-and-map-assets-to-file';
-import {getAssetAudioDetails} from './assets/get-asset-audio-details';
-import {AssetAudioDetails, Assets} from './assets/types';
-import {calculateFfmpegFilter} from './calculate-ffmpeg-filters';
+import {Assets} from './assets/types';
import {deleteDirectory} from './delete-directory';
import {getAudioCodecName} from './get-audio-codec-name';
import {getCodecName} from './get-codec-name';
@@ -27,7 +26,6 @@ import {getProResProfileName} from './get-prores-profile-name';
import {mergeAudioTrack} from './merge-audio-track';
import {parseFfmpegProgress} from './parse-ffmpeg-progress';
import {preprocessAudioTrack} from './preprocess-audio-track';
-import {resolveAssetSrc} from './resolve-asset-src';
import {tmpDir} from './tmp-dir';
import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';
import {validateFfmpeg} from './validate-ffmpeg';
@@ -54,6 +52,11 @@ export type StitcherOptions = {
};
};
+type ReturnType = {
+ task: Promise<unknown>;
+ getLogs: () => string;
+};
+
const getAssetsData = async ({
assets,
downloadDir,
@@ -62,6 +65,7 @@ const getAssetsData = async ({
expectedFrames,
verbose,
ffmpegExecutable,
+ onProgress,
}: {
assets: TAsset[][];
downloadDir: string;
@@ -70,6 +74,7 @@ const getAssetsData = async ({
expectedFrames: number;
verbose: boolean;
ffmpegExecutable: FfmpegExecutable | null;
+ onProgress: (progress: number) => void;
}): Promise<string | null> => {
const fileUrlAssets = await convertAssetsToFileUrls({
assets: assets,
@@ -80,44 +85,30 @@ const getAssetsData = async ({
markAllAssetsAsDownloaded();
const assetPositions: Assets = calculateAssetPositions(fileUrlAssets);
- const assetAudioDetails = await getAssetAudioDetails({
- assetPaths: assetPositions.map((a) => a.src),
- });
-
- const withAtLeast1Channel = assetPositions.filter((pos) => {
- return (
- (assetAudioDetails.get(resolveAssetSrc(pos.src)) as AssetAudioDetails)
- .channels > 0
- );
- });
-
if (verbose) {
console.log('asset positions', assetPositions);
}
const tempPath = tmpDir('remotion-audio-mixing');
+ let totalProgress = new Array(assetPositions.length).fill(0);
+
const preprocessed = await Promise.all(
- withAtLeast1Channel.map(async (asset, index) => {
+ assetPositions.map(async (asset, index) => {
const filterFile = path.join(tempPath, `${index}.aac`);
- const {filter, src, cleanup} = await calculateFfmpegFilter({
- assetAudioDetails,
- asset: asset,
- durationInFrames: expectedFrames,
- fps,
- });
- if (verbose) {
- console.log('filter for ' + src, filter);
- }
-
await preprocessAudioTrack({
ffmpegExecutable: ffmpegExecutable ?? null,
- audioFile: src,
- filter,
- onProgress: (prog) => console.log(prog),
+ onProgress: (prog) => {
+ totalProgress[index] = prog;
+ onProgress(
+ totalProgress.reduce((a, b) => a + b, 0) / assetPositions.length
+ );
+ },
outName: filterFile,
+ asset,
+ expectedFrames,
+ fps,
});
- cleanup();
return filterFile;
})
);
@@ -139,7 +130,9 @@ const getAssetsData = async ({
return outName;
};
-export const spawnFfmpeg = async (options: StitcherOptions) => {
+export const spawnFfmpeg = async (
+ options: StitcherOptions
+): Promise<ReturnType> => {
Internals.validateDimension(
options.height,
'height',
@@ -199,11 +192,23 @@ export const spawnFfmpeg = async (options: StitcherOptions) => {
expectedFrames,
verbose: options.verbose ?? false,
ffmpegExecutable: options.ffmpegExecutable ?? null,
+ onProgress: (prog) => options.onProgress?.(prog),
});
- // TODO: If only audio should be output, finish now
if (isAudioOnly) {
- throw new Error('audio only not implemented');
+ if (!audio) {
+ // TODO: Just return an empty audio
+ throw new TypeError(
+ 'Audio output was selected but the composition contained no audio.'
+ );
+ }
+
+ await fs.promises.copyFile(audio, options.outputLocation);
+ options.onProgress?.(1);
+ return {
+ getLogs: () => '',
+ task: Promise.resolve(),
+ };
}
const ffmpegArgs = [
diff --git a/packages/renderer/src/test/ffmpeg-filters.test.ts b/packages/renderer/src/test/ffmpeg-filters.test.ts
index 490851b463..739870b1e6 100644
--- a/packages/renderer/src/test/ffmpeg-filters.test.ts
+++ b/packages/renderer/src/test/ffmpeg-filters.test.ts
@@ -1,13 +1,13 @@
import fs from 'fs';
-import {AssetAudioDetails, MediaAsset} from '../assets/types';
-import {calculateFfmpegFilters} from '../calculate-ffmpeg-filters';
+import {MediaAsset} from '../assets/types';
+import {calculateFfmpegFilter} from '../calculate-ffmpeg-filters';
const src =
'/var/folders/hl/p8pg9kw15dbg3l7dbpn0scc80000gn/T/react-motion-graphicsh871Pk/1fe4a495500e1658167982183be07231.mp4';
const asset: MediaAsset = {
type: 'video',
- src: '/var/folders/hl/p8pg9kw15dbg3l7dbpn0scc80000gn/T/react-motion-graphicsh871Pk/1fe4a495500e1658167982183be07231.mp4',
+ src,
duration: 20,
startInVideo: 0,
trimLeft: 0,
@@ -17,20 +17,15 @@ const asset: MediaAsset = {
};
test('Should create a basic filter correctly', async () => {
- const assetAudioDetails = new Map<string, AssetAudioDetails>();
- assetAudioDetails.set(src, {
- channels: 1,
- });
expect(
await fs.promises.readFile(
(
- await calculateFfmpegFilters({
+ await calculateFfmpegFilter({
fps: 30,
- assetPositions: [asset],
- assetAudioDetails,
+ asset,
durationInFrames: 100,
})
- )[0].filter,
+ ).filter,
'utf8'
)
).toBe(
@@ -39,25 +34,18 @@ test('Should create a basic filter correctly', async () => {
});
test('Should handle trim correctly', async () => {
- const assetAudioDetails = new Map<string, AssetAudioDetails>();
- assetAudioDetails.set(src, {
- channels: 1,
- });
expect(
await fs.promises.readFile(
(
- await calculateFfmpegFilters({
+ await calculateFfmpegFilter({
fps: 30,
- assetPositions: [
- {
- ...asset,
- trimLeft: 10,
- },
- ],
- assetAudioDetails,
+ asset: {
+ ...asset,
+ trimLeft: 10,
+ },
durationInFrames: 100,
})
- )[0].filter,
+ ).filter,
'utf8'
)
).toBe(
@@ -66,26 +54,20 @@ test('Should handle trim correctly', async () => {
});
test('Should handle delay correctly', async () => {
- const assetAudioDetails = new Map<string, AssetAudioDetails>();
- assetAudioDetails.set(src, {
- channels: 1,
- });
expect(
await fs.promises.readFile(
(
- await calculateFfmpegFilters({
+ await calculateFfmpegFilter({
fps: 30,
- assetPositions: [
- {
- ...asset,
- trimLeft: 10,
- startInVideo: 80,
- },
- ],
- assetAudioDetails,
+ asset: {
+ ...asset,
+ trimLeft: 10,
+ startInVideo: 80,
+ },
+
durationInFrames: 100,
})
- )[0].filter,
+ ).filter,
'utf8'
)
).toBe(
@@ -94,83 +76,22 @@ test('Should handle delay correctly', async () => {
});
test('Should offset multiple channels', async () => {
- const assetAudioDetails = new Map<string, AssetAudioDetails>();
- assetAudioDetails.set(src, {
- channels: 3,
- });
+ // TODO: 3 channels
expect(
await fs.promises.readFile(
(
- await calculateFfmpegFilters({
+ await calculateFfmpegFilter({
fps: 30,
- assetPositions: [
- {
- ...asset,
- trimLeft: 10,
- startInVideo: 80,
- },
- ],
- assetAudioDetails,
+ asset: {
+ ...asset,
+ trimLeft: 10,
+ startInVideo: 80,
+ },
durationInFrames: 100,
})
- )[0].filter
+ ).filter
)
).toBe(
'[0:a]apad,atrim=0.333:1.000,adelay=2667|2667|2667|2667,atempo=1.00000,volume=1:eval=once[a0]'
);
});
-
-test('Should calculate correct indices even if some muted channels are removed before', async () => {
- const assetAudioDetails = new Map<string, AssetAudioDetails>();
- const mutedSrc = 'music.mp3';
- assetAudioDetails.set(mutedSrc, {
- channels: 0,
- });
- assetAudioDetails.set(src, {
- channels: 3,
- });
- const makeFilters = () =>
- calculateFfmpegFilters({
- fps: 30,
- assetPositions: [
- {
- trimLeft: 10,
- startInVideo: 80,
- duration: 100,
- id: 'any',
- src: mutedSrc,
- type: 'video',
- volume: 1,
- playbackRate: 1,
- },
- {
- ...asset,
- trimLeft: 10,
- startInVideo: 80,
- },
- ],
- assetAudioDetails,
- durationInFrames: 100,
- });
- expect(
- await fs.promises.readFile((await makeFilters())[0].filter, 'utf8')
- ).toBe(
- // Should be index 2 - make sure that index 1 is not current, because it is muted
- '[0:a]apad,atrim=0.333:1.000,adelay=2667|2667|2667|2667,atempo=1.00000,volume=1:eval=once[a0]'
- );
-
- // Also test basic case: if first one is unmuted, both channels are there again
- assetAudioDetails.set(mutedSrc, {
- channels: 1,
- });
- expect(
- await fs.promises.readFile((await makeFilters())[0].filter, 'utf8')
- ).toBe(
- '[0:a]apad,atrim=0.333:3.667,adelay=2667|2667,atempo=1.00000,volume=1:eval=once[a0]'
- );
- expect(
- await fs.promises.readFile((await makeFilters())[1].filter, 'utf8')
- ).toBe(
- '[0:a]apad,atrim=0.333:1.000,adelay=2667|2667|2667|2667,atempo=1.00000,volume=1:eval=once[a0]'
- );
-});