Skip to content

🎥 Make videos programmatically with React

only add apad filter if really necessary

Jonny Burger46d47b5903d2
diff --git a/packages/renderer/src/assets/get-audio-channels.ts b/packages/renderer/src/assets/get-audio-channels.ts
index 3d1e2e8d02..715a017b9a 100644
--- a/packages/renderer/src/assets/get-audio-channels.ts
+++ b/packages/renderer/src/assets/get-audio-channels.ts
@@ -1,9 +1,12 @@
import execa from 'execa';
-export async function getAudioChannels(path: string) {
+export async function getAudioChannelsAndDuration(path: string): Promise<{
+ channels: number;
+ duration: number | null;
+}> {
const args = [
['-v', 'error'],
- ['-show_entries', 'stream=channels'],
+ ['-show_entries', 'stream=channels:format=duration'],
['-of', 'default=nw=1'],
[path],
]
@@ -11,14 +14,12 @@ export async function getAudioChannels(path: string) {
.filter(Boolean) as string[];
const task = await execa('ffprobe', args);
- if (!task.stdout.includes('channels=')) {
- return 0;
- }
- const channels = parseInt(task.stdout.replace('channels=', ''), 10);
- if (isNaN(channels)) {
- throw new TypeError('Unexpected result from ffprobe for channel probing: ');
- }
+ const channels = task.stdout.match(/channels=([0-9]+)/);
+ const duration = task.stdout.match(/duration=([0-9.]+)/);
- return channels;
+ return {
+ channels: channels ? parseInt(channels[1], 10) : 0,
+ duration: duration ? parseFloat(duration[1]) : null,
+ };
}
diff --git a/packages/renderer/src/calculate-ffmpeg-filters.ts b/packages/renderer/src/calculate-ffmpeg-filters.ts
index c972f8d76f..ced98b9211 100644
--- a/packages/renderer/src/calculate-ffmpeg-filters.ts
+++ b/packages/renderer/src/calculate-ffmpeg-filters.ts
@@ -7,11 +7,13 @@ export const calculateFfmpegFilter = ({
fps,
durationInFrames,
channels,
+ assetDuration,
}: {
asset: MediaAsset;
fps: number;
durationInFrames: number;
channels: number;
+ assetDuration: number | null;
}): string | null => {
if (channels === 0) {
return null;
@@ -21,7 +23,7 @@ export const calculateFfmpegFilter = ({
const assetTrimRight =
(asset.trimLeft + asset.duration * asset.playbackRate) / fps;
- const filter = stringifyFfmpegFilter({
+ return stringifyFfmpegFilter({
channels,
startInVideo: asset.startInVideo,
trimLeft: assetTrimLeft,
@@ -30,7 +32,6 @@ export const calculateFfmpegFilter = ({
fps,
playbackRate: asset.playbackRate,
durationInFrames,
+ assetDuration,
});
-
- return filter;
};
diff --git a/packages/renderer/src/preprocess-audio-track.ts b/packages/renderer/src/preprocess-audio-track.ts
index fba88c0b50..342ee33041 100644
--- a/packages/renderer/src/preprocess-audio-track.ts
+++ b/packages/renderer/src/preprocess-audio-track.ts
@@ -1,6 +1,6 @@
import execa from 'execa';
import {FfmpegExecutable} from 'remotion';
-import {getAudioChannels} from './assets/get-audio-channels';
+import {getAudioChannelsAndDuration} from './assets/get-audio-channels';
import {MediaAsset} from './assets/types';
import {calculateFfmpegFilter} from './calculate-ffmpeg-filters';
import {makeFfmpegFilterFile} from './ffmpeg-filter-file';
@@ -22,13 +22,16 @@ const preprocessAudioTrackUnlimited = async ({
expectedFrames,
fps,
}: Options): Promise<string | null> => {
- const channels = await getAudioChannels(resolveAssetSrc(asset.src));
+ const {channels, duration} = await getAudioChannelsAndDuration(
+ resolveAssetSrc(asset.src)
+ );
const filter = calculateFfmpegFilter({
asset,
durationInFrames: expectedFrames,
fps,
channels,
+ assetDuration: duration,
});
if (filter === null) {
diff --git a/packages/renderer/src/stringify-ffmpeg-filter.ts b/packages/renderer/src/stringify-ffmpeg-filter.ts
index 0153080b82..a0bd60564c 100644
--- a/packages/renderer/src/stringify-ffmpeg-filter.ts
+++ b/packages/renderer/src/stringify-ffmpeg-filter.ts
@@ -12,6 +12,7 @@ export const stringifyFfmpegFilter = ({
fps,
playbackRate,
durationInFrames,
+ assetDuration,
}: {
trimLeft: number;
trimRight: number;
@@ -21,6 +22,7 @@ export const stringifyFfmpegFilter = ({
fps: number;
durationInFrames: number;
playbackRate: number;
+ assetDuration: number | null;
}) => {
const startInVideoSeconds = startInVideo / fps;
@@ -32,11 +34,20 @@ export const stringifyFfmpegFilter = ({
// Avoid setting filters if possible, as combining them can create noise
+ const chunkLength = durationInFrames / fps;
+
+ const actualTrimRight = assetDuration
+ ? Math.min(trimRight, assetDuration)
+ : trimRight;
+
+ const padAtEnd =
+ chunkLength - (actualTrimRight - trimLeft) - startInVideoSeconds;
+
return (
`[0:a]` +
[
// Order matters! First trim the audio
- `atrim=${trimLeft.toFixed(6)}:${trimRight.toFixed(6)}`,
+ `atrim=${trimLeft.toFixed(6)}:${actualTrimRight.toFixed(6)}`,
// then set the tempo
calculateATempo(playbackRate),
// For n channels, we delay n + 1 channels.
@@ -54,9 +65,8 @@ export const stringifyFfmpegFilter = ({
volumeFilter.value === '1'
? null
: `volume=${volumeFilter.value}:eval=${volumeFilter.eval}`,
-
// Only in the end, we pad to the full length.
- 'apad=whole_dur=' + (durationInFrames / fps).toFixed(6),
+ padAtEnd > 0.0000001 ? 'apad=pad_dur=' + padAtEnd.toFixed(6) : null,
]
.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 8189fc1965..8a8e8ad184 100644
--- a/packages/renderer/src/test/ffmpeg-filters.test.ts
+++ b/packages/renderer/src/test/ffmpeg-filters.test.ts
@@ -16,14 +16,29 @@ const asset: MediaAsset = {
};
test('Should create a basic filter correctly', () => {
+ expect(
+ calculateFfmpegFilter({
+ fps: 30,
+ asset: {
+ ...asset,
+ duration: 200,
+ },
+ durationInFrames: 100,
+ channels: 1,
+ assetDuration: 10,
+ })
+ ).toBe('[0:a]atrim=0.000000:6.666667[a0]');
+});
+test('Trim the end', () => {
expect(
calculateFfmpegFilter({
fps: 30,
asset,
durationInFrames: 100,
channels: 1,
+ assetDuration: 10,
})
- ).toBe('[0:a]atrim=0.000000:0.666667,apad=whole_dur=3.333333[a0]');
+ ).toBe('[0:a]atrim=0.000000:0.666667,apad=pad_dur=2.666667[a0]');
});
test('Should handle trim correctly', () => {
@@ -36,8 +51,24 @@ test('Should handle trim correctly', () => {
},
durationInFrames: 100,
channels: 1,
+ assetDuration: 10,
+ })
+ ).toBe('[0:a]atrim=0.333333:1.000000,apad=pad_dur=2.666667[a0]');
+});
+
+test('Should add padding if audio is too short', () => {
+ expect(
+ calculateFfmpegFilter({
+ fps: 30,
+ asset: {
+ ...asset,
+ trimLeft: 10,
+ },
+ durationInFrames: 100,
+ channels: 1,
+ assetDuration: 1,
})
- ).toBe('[0:a]atrim=0.333333:1.000000,apad=whole_dur=3.333333[a0]');
+ ).toBe('[0:a]atrim=0.333333:1.000000,apad=pad_dur=2.666667[a0]');
});
test('Should handle delay correctly', () => {
@@ -52,10 +83,9 @@ test('Should handle delay correctly', () => {
durationInFrames: 100,
channels: 1,
+ assetDuration: 1,
})
- ).toBe(
- '[0:a]atrim=0.333333:1.000000,adelay=2667|2667,apad=whole_dur=3.333333[a0]'
- );
+ ).toBe('[0:a]atrim=0.333333:1.000000,adelay=2667|2667[a0]');
});
test('Should offset multiple channels', () => {
@@ -69,8 +99,7 @@ test('Should offset multiple channels', () => {
},
durationInFrames: 100,
channels: 3,
+ assetDuration: 1,
})
- ).toBe(
- '[0:a]atrim=0.333333:1.000000,adelay=2667|2667|2667|2667,apad=whole_dur=3.333333[a0]'
- );
+ ).toBe('[0:a]atrim=0.333333:1.000000,adelay=2667|2667|2667|2667[a0]');
});
diff --git a/packages/renderer/src/test/get-audio-channels.test.ts b/packages/renderer/src/test/get-audio-channels.test.ts
index d4d640e5bc..86b119b94f 100644
--- a/packages/renderer/src/test/get-audio-channels.test.ts
+++ b/packages/renderer/src/test/get-audio-channels.test.ts
@@ -1,6 +1,7 @@
import {existsSync} from 'fs';
import path from 'path';
-import {getAudioChannels} from '../assets/get-audio-channels';
+import {getAudioChannelsAndDuration} from '../assets/get-audio-channels';
+
jest.setTimeout(10000);
test('Get audio channels for video', async () => {
@@ -14,9 +15,9 @@ test('Get audio channels for video', async () => {
'resources',
'framer-music.mp4'
);
- expect(existsSync(videoWithoutAudio)).toBe(true);
- const channels = await getAudioChannels(videoWithoutAudio);
- expect(channels).toBe(2);
+ expect(existsSync(videoWithoutAudio)).toEqual(true);
+ const channels = await getAudioChannelsAndDuration(videoWithoutAudio);
+ expect(channels).toEqual({channels: 2, duration: 10});
});
test('Get audio channels for video without music', async () => {
@@ -30,12 +31,12 @@ test('Get audio channels for video without music', async () => {
'resources',
'framer.mp4'
);
- expect(existsSync(videoWithAudio)).toBe(true);
- const channels = await getAudioChannels(videoWithAudio);
- expect(channels).toBe(0);
+ expect(existsSync(videoWithAudio)).toEqual(true);
+ const channels = await getAudioChannelsAndDuration(videoWithAudio);
+ expect(channels).toEqual({channels: 0, duration: 3.334});
});
-test('Get audio channels for video without music', async () => {
+test('Get audio channels for video with music', async () => {
const audio = path.join(
__dirname,
'..',
@@ -46,15 +47,15 @@ test('Get audio channels for video without music', async () => {
'resources',
'sound1.mp3'
);
- expect(existsSync(audio)).toBe(true);
- const channels = await getAudioChannels(audio);
- expect(channels).toBe(2);
+ expect(existsSync(audio)).toEqual(true);
+ const channels = await getAudioChannelsAndDuration(audio);
+ expect(channels).toEqual({channels: 2, duration: 56.529});
});
test('Throw error if parsing a non video file', () => {
const tsFile = path.join(__dirname, '..', 'ffmpeg-flags.ts');
- expect(existsSync(tsFile)).toBe(true);
- expect(() => getAudioChannels(tsFile)).rejects.toThrow(
+ expect(existsSync(tsFile)).toEqual(true);
+ expect(() => getAudioChannelsAndDuration(tsFile)).rejects.toThrow(
/Invalid data found when processing input/
);
});