Skip to content

🎥 Make videos programmatically with React

progress

Jonny Burger26ded4b3ce19
diff --git a/packages/renderer/src/calculate-ffmpeg-filters.ts b/packages/renderer/src/calculate-ffmpeg-filters.ts
index 7752ffa990..c31b94a04e 100644
--- a/packages/renderer/src/calculate-ffmpeg-filters.ts
+++ b/packages/renderer/src/calculate-ffmpeg-filters.ts
@@ -8,10 +8,12 @@ export const calculateFfmpegFilters = ({
assetPositions,
assetAudioDetails,
fps,
+ durationInFrames,
}: {
assetPositions: Assets;
assetAudioDetails: Map<string, AssetAudioDetails>;
fps: number;
+ durationInFrames: number;
}): Promise<{filter: string; src: string; cleanup: () => void}[]> => {
const withAtLeast1Channel = assetPositions.filter((pos) => {
return (
@@ -38,6 +40,7 @@ export const calculateFfmpegFilters = ({
volume: flattenVolumeArray(asset.volume),
fps,
playbackRate: asset.playbackRate,
+ durationInFrames,
});
const {cleanup, file: filterFile} = await makeFfmpegFilterFile(filter);
diff --git a/packages/renderer/src/merge-audio-track.ts b/packages/renderer/src/merge-audio-track.ts
index f4947464d6..01f9120bdc 100644
--- a/packages/renderer/src/merge-audio-track.ts
+++ b/packages/renderer/src/merge-audio-track.ts
@@ -1,4 +1,5 @@
import execa from 'execa';
+import fs from 'fs';
import {FfmpegExecutable, Internals} from 'remotion';
import {createFfmpegComplexFilter} from './create-ffmpeg-complex-filter';
import {parseFfmpegProgress} from './parse-ffmpeg-progress';
@@ -10,7 +11,6 @@ type Options = {
onProgress: (progress: number) => void;
};
-// TODO: Limit concurrency
export const mergeAudioTrack = async ({
ffmpegExecutable,
outName,
@@ -19,6 +19,13 @@ export const mergeAudioTrack = async ({
}: Options) => {
const {complexFilterFlag: mergeFilter, cleanup} =
await createFfmpegComplexFilter(files.length);
+
+ if (files.length === 1) {
+ await fs.promises.copyFile(files[0], outName);
+ onProgress(1);
+ return;
+ }
+
const args = [
...files.map((f) => ['-i', f]),
mergeFilter,
diff --git a/packages/renderer/src/preprocess-audio-track.ts b/packages/renderer/src/preprocess-audio-track.ts
index 0368e92363..e617d34832 100644
--- a/packages/renderer/src/preprocess-audio-track.ts
+++ b/packages/renderer/src/preprocess-audio-track.ts
@@ -11,6 +11,7 @@ type Options = {
onProgress: (progress: number) => void;
};
+// TODO: Limit concurrency
export const preprocessAudioTrack = async ({
ffmpegExecutable,
audioFile,
diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.ts
index 4826688d43..1db2644bbb 100644
--- a/packages/renderer/src/stitch-frames-to-video.ts
+++ b/packages/renderer/src/stitch-frames-to-video.ts
@@ -8,6 +8,7 @@ import {
PixelFormat,
ProResProfile,
RenderAssetInfo,
+ TAsset,
} from 'remotion';
import {assetsToFfmpegInputs} from './assets-to-ffmpeg-inputs';
import {calculateAssetPositions} from './assets/calculate-asset-positions';
@@ -52,13 +53,27 @@ export type StitcherOptions = {
};
};
-const getAssetsData = async (
- options: StitcherOptions
-): Promise<string | null> => {
+const getAssetsData = async ({
+ assets,
+ downloadDir,
+ onDownload,
+ fps,
+ expectedFrames,
+ verbose,
+ ffmpegExecutable,
+}: {
+ assets: TAsset[][];
+ downloadDir: string;
+ onDownload: RenderMediaOnDownload | undefined;
+ fps: number;
+ expectedFrames: number;
+ verbose: boolean;
+ ffmpegExecutable: FfmpegExecutable | null;
+}): Promise<string | null> => {
const fileUrlAssets = await convertAssetsToFileUrls({
- assets: options.assetsInfo.assets,
- downloadDir: options.assetsInfo.downloadDir,
- onDownload: options.onDownload ?? (() => () => undefined),
+ assets: assets,
+ downloadDir: downloadDir,
+ onDownload: onDownload ?? (() => () => undefined),
});
markAllAssetsAsDownloaded();
@@ -71,13 +86,14 @@ const getAssetsData = async (
const filters = await calculateFfmpegFilters({
assetAudioDetails,
assetPositions,
- fps: options.fps,
+ fps: fps,
+ durationInFrames: expectedFrames,
});
- if (options.verbose) {
+ if (verbose) {
console.log('asset positions', assetPositions);
}
- if (options.verbose) {
+ if (verbose) {
console.log('filters', filters);
}
@@ -87,7 +103,7 @@ const getAssetsData = async (
filters.map(async ({filter, src, cleanup}, index) => {
const filterFile = path.join(tempPath, `${index}.aac`);
await preprocessAudioTrack({
- ffmpegExecutable: options.ffmpegExecutable ?? null,
+ ffmpegExecutable: ffmpegExecutable ?? null,
audioFile: src,
filter,
onProgress: (prog) => console.log(prog),
@@ -101,8 +117,9 @@ const getAssetsData = async (
const outName = path.join(tempPath, `audio.aac`);
await mergeAudioTrack({
- ffmpegExecutable: options.ffmpegExecutable ?? null,
+ ffmpegExecutable: ffmpegExecutable ?? null,
files: preprocessed,
+ // TODO: Handle progress better
onProgress: (prog) => console.log('merge', prog),
outName,
});
@@ -164,15 +181,23 @@ export const spawnFfmpeg = async (options: StitcherOptions) => {
Internals.validateSelectedCrfAndCodecCombination(crf, codec);
Internals.validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);
- const audio = await getAssetsData(options);
+ const expectedFrames = options.assetsInfo.assets.length;
+
+ const audio = await getAssetsData({
+ assets: options.assetsInfo.assets,
+ downloadDir: options.assetsInfo.downloadDir,
+ onDownload: options.onDownload,
+ fps: options.fps,
+ expectedFrames,
+ verbose: options.verbose ?? false,
+ ffmpegExecutable: options.ffmpegExecutable ?? null,
+ });
// TODO: If only audio should be output, finish now
if (isAudioOnly) {
throw new Error('audio only not implemented');
}
- const expectedFrames = options.assetsInfo.assets.length;
-
const ffmpegArgs = [
['-r', String(options.fps)],
...(options.internalOptions?.preEncodedFileLocation
@@ -187,7 +212,7 @@ export const spawnFfmpeg = async (options: StitcherOptions) => {
asset: audio,
isAudioOnly,
fps: options.fps,
- frameCount: options.assetsInfo.assets.length,
+ frameCount: expectedFrames,
}),
// -c:v is the same as -vcodec as -codec:video
diff --git a/packages/renderer/src/stringify-ffmpeg-filter.ts b/packages/renderer/src/stringify-ffmpeg-filter.ts
index 6acbfafb0a..7ff16cee31 100644
--- a/packages/renderer/src/stringify-ffmpeg-filter.ts
+++ b/packages/renderer/src/stringify-ffmpeg-filter.ts
@@ -11,6 +11,7 @@ export const stringifyFfmpegFilter = ({
volume,
fps,
playbackRate,
+ durationInFrames,
}: {
trimLeft: string;
trimRight: string;
@@ -18,6 +19,7 @@ export const stringifyFfmpegFilter = ({
startInVideo: number;
volume: AssetVolume;
fps: number;
+ durationInFrames: number;
playbackRate: number;
}) => {
const startInVideoSeconds = ((startInVideo / fps) * 1000).toFixed(); // in milliseconds
@@ -30,7 +32,6 @@ export const stringifyFfmpegFilter = ({
return (
`[0:a]` +
[
- 'apad',
`atrim=${trimLeft}:${trimRight}`,
// For n channels, we delay n + 1 channels.
// This is because `ffprobe` for some audio files reports the wrong amount
@@ -41,6 +42,7 @@ export const stringifyFfmpegFilter = ({
`adelay=${new Array(channels + 1).fill(startInVideoSeconds).join('|')}`,
calculateATempo(playbackRate),
`volume=${volumeFilter.value}:eval=${volumeFilter.eval}`,
+ 'apad=whole_dur=' + (durationInFrames / fps).toFixed(3),
]
.filter(Internals.truthy)
.join(',') +
diff --git a/packages/renderer/src/test/ffmpeg-filters.test.ts b/packages/renderer/src/test/ffmpeg-filters.test.ts
index db528ac9f1..490851b463 100644
--- a/packages/renderer/src/test/ffmpeg-filters.test.ts
+++ b/packages/renderer/src/test/ffmpeg-filters.test.ts
@@ -1,3 +1,4 @@
+import fs from 'fs';
import {AssetAudioDetails, MediaAsset} from '../assets/types';
import {calculateFfmpegFilters} from '../calculate-ffmpeg-filters';
@@ -15,88 +16,111 @@ const asset: MediaAsset = {
playbackRate: 1,
};
-test('Should create a basic filter correctly', () => {
+test('Should create a basic filter correctly', async () => {
const assetAudioDetails = new Map<string, AssetAudioDetails>();
assetAudioDetails.set(src, {
channels: 1,
});
expect(
- calculateFfmpegFilters({
- fps: 30,
- assetPositions: [asset],
- assetAudioDetails,
- })[0]
+ await fs.promises.readFile(
+ (
+ await calculateFfmpegFilters({
+ fps: 30,
+ assetPositions: [asset],
+ assetAudioDetails,
+ durationInFrames: 100,
+ })
+ )[0].filter,
+ 'utf8'
+ )
).toBe(
'[0:a]apad,atrim=0.000:0.667,adelay=0|0,atempo=1.00000,volume=1:eval=once[a0]'
);
});
-test('Should handle trim correctly', () => {
+test('Should handle trim correctly', async () => {
const assetAudioDetails = new Map<string, AssetAudioDetails>();
assetAudioDetails.set(src, {
channels: 1,
});
expect(
- calculateFfmpegFilters({
- fps: 30,
- assetPositions: [
- {
- ...asset,
- trimLeft: 10,
- },
- ],
- assetAudioDetails,
- })[0]
+ await fs.promises.readFile(
+ (
+ await calculateFfmpegFilters({
+ fps: 30,
+ assetPositions: [
+ {
+ ...asset,
+ trimLeft: 10,
+ },
+ ],
+ assetAudioDetails,
+ durationInFrames: 100,
+ })
+ )[0].filter,
+ 'utf8'
+ )
).toBe(
'[0:a]apad,atrim=0.333:1.000,adelay=0|0,atempo=1.00000,volume=1:eval=once[a0]'
);
});
-test('Should handle delay correctly', () => {
+test('Should handle delay correctly', async () => {
const assetAudioDetails = new Map<string, AssetAudioDetails>();
assetAudioDetails.set(src, {
channels: 1,
});
expect(
- calculateFfmpegFilters({
- fps: 30,
- assetPositions: [
- {
- ...asset,
- trimLeft: 10,
- startInVideo: 80,
- },
- ],
- assetAudioDetails,
- })[0]
+ await fs.promises.readFile(
+ (
+ await calculateFfmpegFilters({
+ fps: 30,
+ assetPositions: [
+ {
+ ...asset,
+ trimLeft: 10,
+ startInVideo: 80,
+ },
+ ],
+ assetAudioDetails,
+ durationInFrames: 100,
+ })
+ )[0].filter,
+ 'utf8'
+ )
).toBe(
'[0:a]apad,atrim=0.333:1.000,adelay=2667|2667,atempo=1.00000,volume=1:eval=once[a0]'
);
});
-test('Should offset multiple channels', () => {
+test('Should offset multiple channels', async () => {
const assetAudioDetails = new Map<string, AssetAudioDetails>();
assetAudioDetails.set(src, {
channels: 3,
});
expect(
- calculateFfmpegFilters({
- fps: 30,
- assetPositions: [
- {
- ...asset,
- trimLeft: 10,
- startInVideo: 80,
- },
- ],
- assetAudioDetails,
- })[0]
+ await fs.promises.readFile(
+ (
+ await calculateFfmpegFilters({
+ fps: 30,
+ assetPositions: [
+ {
+ ...asset,
+ trimLeft: 10,
+ startInVideo: 80,
+ },
+ ],
+ assetAudioDetails,
+ durationInFrames: 100,
+ })
+ )[0].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', () => {
+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, {
@@ -126,8 +150,11 @@ test('Should calculate correct indices even if some muted channels are removed b
},
],
assetAudioDetails,
+ durationInFrames: 100,
});
- expect(makeFilters()[0]).toBe(
+ 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]'
);
@@ -136,10 +163,14 @@ test('Should calculate correct indices even if some muted channels are removed b
assetAudioDetails.set(mutedSrc, {
channels: 1,
});
- expect(makeFilters()[0]).toBe(
+ 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(makeFilters()[1]).toBe(
+ 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]'
);
});