Skip to content

🎥 Make videos programmatically with React

calculate video stream duration differently from whole container duration

Jonny Burgera3ec5f995ecb
diff --git a/packages/renderer/src/assets/get-video-stream-duration.ts b/packages/renderer/src/assets/get-video-stream-duration.ts
new file mode 100644
index 0000000000..88bb58e873
--- /dev/null
+++ b/packages/renderer/src/assets/get-video-stream-duration.ts
@@ -0,0 +1,48 @@
+import execa from 'execa';
+import type {FfmpegExecutable} from 'remotion';
+import {pLimit} from '../p-limit';
+
+type Result = {
+ duration: number | null;
+};
+
+const durationOfAssetCache: Record<string, Result> = {};
+
+const limit = pLimit(1);
+
+async function getVideoStreamDurationUnlimited(
+ src: string,
+ ffprobeExecutable: FfmpegExecutable
+): Promise<Result> {
+ if (durationOfAssetCache[src]) {
+ return durationOfAssetCache[src];
+ }
+
+ const args = [
+ ['-v', 'error'],
+ ['-select_streams', 'v:0'],
+ ['-show_entries', 'stream=duration'],
+ [src],
+ ]
+ .reduce<(string | null)[]>((acc, val) => acc.concat(val), [])
+ .filter(Boolean) as string[];
+
+ const task = await execa(ffprobeExecutable ?? 'ffprobe', args);
+
+ const duration = task.stdout.match(/duration=([0-9.]+)/);
+
+ const result: Result = {
+ duration: duration ? parseFloat(duration[1]) : null,
+ };
+
+ durationOfAssetCache[src] = result;
+
+ return result;
+}
+
+export const getVideoStreamDuration = (
+ src: string,
+ ffprobeExecutable: FfmpegExecutable
+): Promise<Result> => {
+ return limit(() => getVideoStreamDurationUnlimited(src, ffprobeExecutable));
+};
diff --git a/packages/renderer/src/extract-frame-from-video.ts b/packages/renderer/src/extract-frame-from-video.ts
index 620cce477a..13534b1148 100644
--- a/packages/renderer/src/extract-frame-from-video.ts
+++ b/packages/renderer/src/extract-frame-from-video.ts
@@ -1,7 +1,7 @@
import execa from 'execa';
import type {FfmpegExecutable, OffthreadVideoImageFormat} from 'remotion';
import {Internals} from 'remotion';
-import {getAudioChannelsAndDuration} from './assets/get-audio-channels';
+import {getVideoStreamDuration} from './assets/get-video-stream-duration';
import {ensurePresentationTimestamps} from './ensure-presentation-timestamp';
import {frameToFfmpegTimestamp} from './frame-to-ffmpeg-timestamp';
import type {SpecialVCodecForTransparency} from './get-video-info';
@@ -126,7 +126,7 @@ const getLastFrameOfVideoFastUnlimited = async (
return fromCache;
}
- const {duration} = await getAudioChannelsAndDuration(src, ffprobeExecutable);
+ const {duration} = await getVideoStreamDuration(src, ffprobeExecutable);
if (duration === null) {
throw new Error(
`Could not determine the duration of ${src} using FFMPEG. The file is not supported.`