Skip to content

🎥 Make videos programmatically with React

new strategy

Jonny Burgerf369b0c51d6f
diff --git a/packages/renderer/src/assets/get-audio-channels.ts b/packages/renderer/src/assets/get-audio-channels.ts
index f9cf700693..062ba00030 100644
--- a/packages/renderer/src/assets/get-audio-channels.ts
+++ b/packages/renderer/src/assets/get-audio-channels.ts
@@ -1,18 +1,29 @@
import execa from 'execa';
import {FfmpegExecutable} from 'remotion';
+import {pLimit} from '../p-limit';
-export async function getAudioChannelsAndDuration(
- path: string,
- ffprobeExecutable: FfmpegExecutable
-): Promise<{
+type Result = {
channels: number;
duration: number | null;
-}> {
+};
+
+const durationOfAssetCache: Record<string, Result> = {};
+
+const limit = pLimit(1);
+
+export async function getAudioChannelsAndDurationUnlimited(
+ src: string,
+ ffprobeExecutable: FfmpegExecutable
+): Promise<Result> {
+ if (durationOfAssetCache[src]) {
+ return durationOfAssetCache[src];
+ }
+
const args = [
['-v', 'error'],
['-show_entries', 'stream=channels:format=duration'],
['-of', 'default=nw=1'],
- [path],
+ [src],
]
.reduce<(string | null)[]>((acc, val) => acc.concat(val), [])
.filter(Boolean) as string[];
@@ -22,8 +33,21 @@ export async function getAudioChannelsAndDuration(
const channels = task.stdout.match(/channels=([0-9]+)/);
const duration = task.stdout.match(/duration=([0-9.]+)/);
- return {
+ const result: Result = {
channels: channels ? parseInt(channels[1], 10) : 0,
duration: duration ? parseFloat(duration[1]) : null,
};
+
+ durationOfAssetCache[src] = result;
+
+ return result;
}
+
+export const getAudioChannelsAndDuration = (
+ src: string,
+ ffprobeExecutable: FfmpegExecutable
+): Promise<Result> => {
+ return limit(() =>
+ getAudioChannelsAndDurationUnlimited(src, ffprobeExecutable)
+ );
+};
diff --git a/packages/renderer/src/ensure-presentation-timestamp.ts b/packages/renderer/src/ensure-presentation-timestamp.ts
new file mode 100644
index 0000000000..48bb6fdc0f
--- /dev/null
+++ b/packages/renderer/src/ensure-presentation-timestamp.ts
@@ -0,0 +1,67 @@
+import execa from 'execa';
+import {rename, unlink} from 'fs/promises';
+import path from 'path';
+
+const ensureFileHasPresentationTimestamp: Record<string, 'encoding' | 'done'> =
+ {};
+
+type Callback = {
+ src: string;
+ fn: () => void;
+};
+
+let callbacks: Callback[] = [];
+
+export const ensurePresentationTimestamps = async (src: string) => {
+ if (ensureFileHasPresentationTimestamp[src] === 'encoding') {
+ return new Promise((resolve) => {
+ callbacks.push({
+ src,
+ fn: () => resolve,
+ });
+ });
+ }
+
+ if (ensureFileHasPresentationTimestamp[src] === 'done') {
+ return;
+ }
+
+ ensureFileHasPresentationTimestamp[src] = 'encoding';
+
+ const parts = src.split(path.sep);
+ const output = parts
+ .map((p, i) => {
+ if (i === parts.length - 1) {
+ return `pts-${p}`;
+ }
+ return p;
+ })
+ .join(path.sep);
+
+ await execa('ffmpeg', [
+ '-i',
+ src,
+ '-fflags',
+ '+genpts+igndts',
+ '-map',
+ '0:v',
+ '-vcodec',
+ 'copy',
+ '-acodec',
+ 'copy',
+ output,
+ '-y',
+ ]);
+
+ await unlink(src);
+ await rename(output, src);
+
+ callbacks = callbacks.filter((c) => {
+ if (c.src === src) {
+ c.fn();
+ return false;
+ }
+ return true;
+ });
+ ensureFileHasPresentationTimestamp[src] = 'done';
+};
diff --git a/packages/renderer/src/extract-frame-from-video.ts b/packages/renderer/src/extract-frame-from-video.ts
index 881829712f..d775d7d69b 100644
--- a/packages/renderer/src/extract-frame-from-video.ts
+++ b/packages/renderer/src/extract-frame-from-video.ts
@@ -1,8 +1,9 @@
import execa from 'execa';
import {FfmpegExecutable, Internals} from 'remotion';
import {Readable} from 'stream';
+import {getAudioChannelsAndDuration} from './assets/get-audio-channels';
+import {ensurePresentationTimestamps} from './ensure-presentation-timestamp';
import {frameToFfmpegTimestamp} from './frame-to-ffmpeg-timestamp';
-import {getDurationOfAsset} from './get-duration-of-asset';
import {isBeyondLastFrame, markAsBeyondLastFrame} from './is-beyond-last-frame';
import {
getLastFrameFromCache,
@@ -100,10 +101,12 @@ const getLastFrameOfVideoFastUnlimited = async (
return fromCache;
}
- const duration = await getDurationOfAsset({
- src,
- ffprobeExecutable,
- });
+ const {duration} = await getAudioChannelsAndDuration(src, ffprobeExecutable);
+ if (duration === null) {
+ throw new Error(
+ `Could not determine the duration of ${src} using FFMPEG. The file is not supported.`
+ );
+ }
if (offset > 40) {
const last = await getLastFrameOfVideoSlow({
duration,
@@ -199,6 +202,8 @@ export const extractFrameFromVideoFn = async ({
ffmpegExecutable,
ffprobeExecutable,
}: Options): Promise<Buffer> => {
+ await ensurePresentationTimestamps(src);
+
if (isBeyondLastFrame(src, time)) {
const lastFrame = await getLastFrameOfVideo({
ffmpegExecutable,
diff --git a/packages/renderer/src/get-duration-of-asset.ts b/packages/renderer/src/get-duration-of-asset.ts
deleted file mode 100644
index b6a9c8387f..0000000000
--- a/packages/renderer/src/get-duration-of-asset.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import execa from 'execa';
-import {FfmpegExecutable} from 'remotion';
-import {pLimit} from './p-limit';
-
-const durationOfAssetCache: Record<string, number> = {};
-
-type Options = {
- ffprobeExecutable: FfmpegExecutable;
- src: string;
-};
-
-const limit = pLimit(1);
-
-const getDurationOfAssetUnlimited = async ({
- ffprobeExecutable,
- src,
-}: Options): Promise<number> => {
- if (durationOfAssetCache[src]) {
- return durationOfAssetCache[src];
- }
-
- const durationCmd = await execa(ffprobeExecutable ?? 'ffprobe', [
- '-v',
- 'error',
- '-select_streams',
- 'v:0',
- '-show_entries',
- 'stream=duration',
- '-of',
- 'default=noprint_wrappers=1:nokey=1',
- src,
- ]);
-
- const duration = parseFloat(durationCmd.stdout);
-
- if (Number.isNaN(duration)) {
- throw new TypeError(
- `Could not get duration of ${src}: ${durationCmd.stdout}`
- );
- }
-
- durationOfAssetCache[src] = duration;
-
- return duration;
-};
-
-export const getDurationOfAsset = (options: Options) => {
- return limit(getDurationOfAssetUnlimited, options);
-};