Skip to content

🎥 Make videos programmatically with React

getCanExtractFramesFast()

Jonny Burger15ac21b3e67b
diff --git a/packages/docs/docs/renderer/get-can-extract-frames-fast.md b/packages/docs/docs/renderer/get-can-extract-frames-fast.md
new file mode 100644
index 0000000000..9f843e393a
--- /dev/null
+++ b/packages/docs/docs/renderer/get-can-extract-frames-fast.md
@@ -0,0 +1,64 @@
+---
+title: getCanExtractFramesFast()
+id: can-extract-frames-fast
+---
+
+_Available since v3.3.2 - Part of the `@remotion/renderer` package._
+
+Probes whether frames of a video can be efficiently extracted when using [`<OffthreadVideo>`](/docs/offthreadvideo).
+
+```ts twoslash
+// @module: ESNext
+// @target: ESNext
+import { getCanExtractFramesFast } from "@remotion/renderer";
+
+const result = await getCanExtractFramesFast({
+ src: "/var/path/to/video.mp4",
+});
+
+console.log(result.canExtractFramesFast); // false
+console.log(result.shouldReencode); // true
+```
+
+## When to use this API
+
+If you are using [`<OffthreadVideo>`](/docs/offthreadvideo), you might get a warning ["Using a slow method to extract the frame"](/docs/slow-method-to-extract-frame) if a video is included which does not include enough metadata to efficiently extract a certain frame of a video. This might result in the render becoming slow.
+
+Using this API, you can probe whether this issue affects your video file. It will try to extract the last frame of a video and if it succeeds, your video is not affected. Otherwise, `canExtractFramesFast` will be `false`.
+
+## How to act on the results
+
+When `canExtractFramesFast` is `false`, you should check the `shouldReencode` flag. If it is true, you can re-encode the video to make the render faster. Note that it is not always faster to re-encode the video than it is to deal with a slow render.
+
+Videos with a VP8 codec don't support fast frame extraction at all, and therefore `shouldReencode` can be false even if `canExtractFramesFast` is false.
+
+## Arguments
+
+An object containing one or more of the following options:
+
+### `src`
+
+Pointing to a video file. Must be an absolute file path.
+
+### `ffmpegExecutable?`
+
+_string - optional_
+
+An absolute path overriding the `ffmpeg` executable to use.
+
+### `ffprobeExecutable?`
+
+_string, options_
+
+An absolute path overriding the `ffprobe` executable to use.
+
+## Return value
+
+Returns a promise which resolves to an object with the following parameters:
+
+- `canExtractFramesFast`: _boolean_ Whether it will be fast to extract a frame from a video.
+- `shouldReencode`: _boolean_ Whether the video can be re-encoded to make the render faster.
+
+## See also
+
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/renderer/src/can-extract-frames-fast.ts)
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index cecaec42ca..6784640f99 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -108,6 +108,7 @@ module.exports = {
"renderer/make-cancel-signal",
"renderer/ensure-ffmpeg",
"renderer/ensure-ffprobe",
+ "renderer/can-extract-frames-fast",
],
},
{
diff --git a/packages/renderer/src/determine-resize-params.ts b/packages/renderer/src/determine-resize-params.ts
new file mode 100644
index 0000000000..135a8feaa7
--- /dev/null
+++ b/packages/renderer/src/determine-resize-params.ts
@@ -0,0 +1,9 @@
+export const determineResizeParams = (
+ needsResize: [number, number] | null
+): string[] => {
+ if (needsResize === null) {
+ return [];
+ }
+
+ return ['-s', `${needsResize[0]}x${needsResize[1]}`];
+};
diff --git a/packages/renderer/src/determine-vcodec-ffmepg-flags.ts b/packages/renderer/src/determine-vcodec-ffmepg-flags.ts
new file mode 100644
index 0000000000..1595989ec1
--- /dev/null
+++ b/packages/renderer/src/determine-vcodec-ffmepg-flags.ts
@@ -0,0 +1,13 @@
+import type {SpecialVCodecForTransparency} from './assets/download-map';
+import {truthy} from './truthy';
+
+export const determineVcodecFfmepgFlags = (
+ vcodecFlag: SpecialVCodecForTransparency
+) => {
+ return [
+ vcodecFlag === 'vp9' ? '-vcodec' : null,
+ vcodecFlag === 'vp9' ? 'libvpx-vp9' : null,
+ vcodecFlag === 'vp8' ? '-vcodec' : null,
+ vcodecFlag === 'vp8' ? 'libvpx' : null,
+ ].filter(truthy);
+};
diff --git a/packages/renderer/src/ensure-presentation-timestamp.ts b/packages/renderer/src/ensure-presentation-timestamp.ts
index 4acaa77e47..d0cb1798e7 100644
--- a/packages/renderer/src/ensure-presentation-timestamp.ts
+++ b/packages/renderer/src/ensure-presentation-timestamp.ts
@@ -46,35 +46,17 @@ const getTemporaryOutputName = async ({
.join(path.sep);
};
-export const ensurePresentationTimestamps = async ({
- downloadMap,
+export const ensurePresentationTimestampWithoutCache = async ({
src,
remotionRoot,
ffmpegExecutable,
ffprobeExecutable,
}: {
- downloadMap: DownloadMap;
src: string;
remotionRoot: string;
ffmpegExecutable: FfmpegExecutable;
ffprobeExecutable: FfmpegExecutable;
-}): Promise<string> => {
- const elem = downloadMap.ensureFileHasPresentationTimestamp[src];
- if (elem?.type === 'encoding') {
- return new Promise<string>((resolve) => {
- callbacks.push({
- src,
- fn: (newSrc: string) => resolve(newSrc),
- });
- });
- }
-
- if (elem?.type === 'done') {
- return elem.src;
- }
-
- downloadMap.ensureFileHasPresentationTimestamp[src] = {type: 'encoding'};
-
+}) => {
// If there is no file extension for the video, then we need to tempoa
const output = await getTemporaryOutputName({
src,
@@ -98,6 +80,45 @@ export const ensurePresentationTimestamps = async ({
]
);
+ return output;
+};
+
+export const ensurePresentationTimestamps = async ({
+ downloadMap,
+ src,
+ remotionRoot,
+ ffmpegExecutable,
+ ffprobeExecutable,
+}: {
+ downloadMap: DownloadMap;
+ src: string;
+ remotionRoot: string;
+ ffmpegExecutable: FfmpegExecutable;
+ ffprobeExecutable: FfmpegExecutable;
+}): Promise<string> => {
+ const elem = downloadMap.ensureFileHasPresentationTimestamp[src];
+ if (elem?.type === 'encoding') {
+ return new Promise<string>((resolve) => {
+ callbacks.push({
+ src,
+ fn: (newSrc: string) => resolve(newSrc),
+ });
+ });
+ }
+
+ if (elem?.type === 'done') {
+ return elem.src;
+ }
+
+ downloadMap.ensureFileHasPresentationTimestamp[src] = {type: 'encoding'};
+
+ const output = await ensurePresentationTimestampWithoutCache({
+ ffmpegExecutable,
+ ffprobeExecutable,
+ remotionRoot,
+ src,
+ });
+
callbacks = callbacks.filter((c) => {
if (c.src === src) {
c.fn(output);
diff --git a/packages/renderer/src/extract-frame-from-video.ts b/packages/renderer/src/extract-frame-from-video.ts
index f8d734e580..93e3f681aa 100644
--- a/packages/renderer/src/extract-frame-from-video.ts
+++ b/packages/renderer/src/extract-frame-from-video.ts
@@ -1,20 +1,16 @@
import execa from 'execa';
import type {OffthreadVideoImageFormat} from 'remotion';
-import type {
- DownloadMap,
- NeedsResize,
- SpecialVCodecForTransparency,
-} from './assets/download-map';
-import {
- getVideoStreamDuration,
- getVideoStreamDurationwithoutCache,
-} from './assets/get-video-stream-duration';
+import type {DownloadMap} from './assets/download-map';
+import {getVideoStreamDuration} from './assets/get-video-stream-duration';
+import {determineResizeParams} from './determine-resize-params';
+import {determineVcodecFfmepgFlags} from './determine-vcodec-ffmepg-flags';
import {ensurePresentationTimestamps} from './ensure-presentation-timestamp';
import type {FfmpegExecutable} from './ffmpeg-executable';
import {getExecutableBinary} from './ffmpeg-flags';
-import {findRemotionRoot} from './find-closest-package-json';
import {frameToFfmpegTimestamp} from './frame-to-ffmpeg-timestamp';
-import {getVideoInfo, getVideoInfoUncached} from './get-video-info';
+import {ACCEPTABLE_OFFSET_THRESHOLD} from './get-can-extract-frames-fast';
+import {getFrameOfVideoSlow} from './get-frame-of-video-slow';
+import {getVideoInfo} from './get-video-info';
import {isBeyondLastFrame, markAsBeyondLastFrame} from './is-beyond-last-frame';
import type {LastFrameOptions} from './last-frame-from-video-cache';
import {
@@ -24,136 +20,11 @@ import {
import {pLimit} from './p-limit';
import {startPerfMeasure, stopPerfMeasure} from './perf';
import {truthy} from './truthy';
+import {tryToExtractFrameOfVideoFast} from './try-to-extract-frame-of-video-fast';
const lastFrameLimit = pLimit(1);
const mainLimit = pLimit(5);
-const ACCEPTABLE_OFFSET_THRESHOLD = 40;
-
-const determineVcodecFfmepgFlags = (
- vcodecFlag: SpecialVCodecForTransparency
-) => {
- return [
- vcodecFlag === 'vp9' ? '-vcodec' : null,
- vcodecFlag === 'vp9' ? 'libvpx-vp9' : null,
- vcodecFlag === 'vp8' ? '-vcodec' : null,
- vcodecFlag === 'vp8' ? 'libvpx' : null,
- ].filter(truthy);
-};
-
-const determineResizeParams = (
- needsResize: [number, number] | null
-): string[] => {
- if (needsResize === null) {
- return [];
- }
-
- return ['-s', `${needsResize[0]}x${needsResize[1]}`];
-};
-
-// Uses no seeking, therefore the whole video has to be decoded. This is a last resort and should only happen
-// if the video is corrupted
-const getFrameOfVideoSlow = async ({
- src,
- duration,
- ffmpegExecutable,
- imageFormat,
- specialVCodecForTransparency,
- needsResize,
- offset,
- fps,
- remotionRoot,
-}: {
- ffmpegExecutable: FfmpegExecutable;
- src: string;
- duration: number;
- imageFormat: OffthreadVideoImageFormat;
- specialVCodecForTransparency: SpecialVCodecForTransparency;
- needsResize: [number, number] | null;
- offset: number;
- fps: number | null;
- remotionRoot: string;
-}): Promise<Buffer> => {
- console.warn(
- `\nUsing a slow method to extract the frame at ${duration}ms of ${src}. See https://remotion.dev/docs/slow-method-to-extract-frame for advice`
- );
-
- const actualOffset = `-${duration * 1000 - offset}ms`;
- const command = [
- '-itsoffset',
- actualOffset,
- ...determineVcodecFfmepgFlags(specialVCodecForTransparency),
- '-i',
- src,
- '-frames:v',
- '1',
- '-c:v',
- imageFormat === 'jpeg' ? 'mjpeg' : 'png',
- '-f',
- 'image2pipe',
- ...determineResizeParams(needsResize),
- '-',
- ].filter(truthy);
-
- const {stdout, stderr} = execa(
- await getExecutableBinary(ffmpegExecutable, remotionRoot, 'ffmpeg'),
- command
- );
-
- if (!stderr) {
- throw new Error('unexpectedly did not get stderr');
- }
-
- if (!stdout) {
- throw new Error('unexpectedly did not get stdout');
- }
-
- const stderrChunks: Buffer[] = [];
- const stdoutChunks: Buffer[] = [];
-
- const stdErrString = new Promise<string>((resolve, reject) => {
- stderr.on('data', (d) => stderrChunks.push(d));
- stderr.on('error', (err) => reject(err));
- stderr.on('end', () =>
- resolve(Buffer.concat(stderrChunks).toString('utf-8'))
- );
- });
-
- const stdoutChunk = new Promise<Buffer>((resolve, reject) => {
- stdout.on('data', (d) => stdoutChunks.push(d));
- stdout.on('error', (err) => reject(err));
- stdout.on('end', () => resolve(Buffer.concat(stdoutChunks)));
- });
-
- const [stdErr, stdoutBuffer] = await Promise.all([stdErrString, stdoutChunk]);
-
- const isEmpty = stdErr.includes('Output file is empty');
- if (isEmpty) {
- if (offset > 70) {
- throw new Error(
- `Could not get last frame of ${src}. Tried to seek to the end using the command "ffmpeg ${command.join(
- ' '
- )}" but got no frame. Most likely this video is corrupted.`
- );
- }
-
- return getFrameOfVideoSlow({
- ffmpegExecutable,
- duration,
- // Decrement in 10ms increments, or 1 frame (e.g. fps = 25 --> 40ms)
- offset: offset + (fps === null ? 10 : 1000 / fps),
- src,
- imageFormat,
- specialVCodecForTransparency,
- needsResize,
- fps,
- remotionRoot,
- });
- }
-
- return stdoutBuffer;
-};
-
const getLastFrameOfVideoFastUnlimited = async (
options: LastFrameOptions
): Promise<Buffer> => {
@@ -249,141 +120,6 @@ type Options = {
remotionRoot: string;
};
-export const canExtractFramesFast = async ({
- src,
- ffmpegExecutable,
- ffprobeExecutable,
-}: {
- src: string;
- ffmpegExecutable: FfmpegExecutable;
- ffprobeExecutable: FfmpegExecutable;
-}): Promise<{
- canExtractFramesFast: boolean;
- shouldReencode: boolean;
-}> => {
- const remotionRoot = findRemotionRoot();
- const {specialVcodecForTransparency: specialVcodec} =
- await getVideoInfoUncached({
- src,
- ffprobeExecutable,
- remotionRoot,
- });
-
- if (specialVcodec === 'vp8') {
- return {
- canExtractFramesFast: false,
- shouldReencode: false,
- };
- }
-
- const {duration} = await getVideoStreamDurationwithoutCache({
- ffprobeExecutable,
- remotionRoot,
- src,
- });
- if (duration === null) {
- throw new Error(
- `Could not determine the duration of ${src} using FFMPEG. The file is not supported.`
- );
- }
-
- const actualOffset = `${duration * 1000 - ACCEPTABLE_OFFSET_THRESHOLD}ms`;
-
- const [stdErr] = await tryToExtractFrameOfVideoFast({
- actualOffset,
- ffmpegExecutable,
- imageFormat: 'jpeg',
- // Intentionally leaving needsResize as null, because we don't need to resize
- needsResize: null,
- remotionRoot,
- specialVCodecForTransparency: specialVcodec,
- src,
- });
- const isEmpty = stdErr.includes('Output file is empty');
-
- if (isEmpty) {
- return {
- canExtractFramesFast: false,
- shouldReencode: true,
- };
- }
-
- return {
- canExtractFramesFast: true,
- shouldReencode: false,
- };
-};
-
-const tryToExtractFrameOfVideoFast = async ({
- ffmpegExecutable,
- remotionRoot,
- specialVCodecForTransparency,
- imageFormat,
- needsResize,
- src,
- actualOffset,
-}: {
- ffmpegExecutable: FfmpegExecutable;
- remotionRoot: string;
- imageFormat: OffthreadVideoImageFormat;
- needsResize: NeedsResize;
- src: string;
- specialVCodecForTransparency: SpecialVCodecForTransparency;
- actualOffset: string;
-}) => {
- const {stdout, stderr} = execa(
- await getExecutableBinary(ffmpegExecutable, remotionRoot, 'ffmpeg'),
- [
- '-ss',
- actualOffset,
- ...determineVcodecFfmepgFlags(specialVCodecForTransparency),
- '-i',
- src,
- '-frames:v',
- '1',
- '-c:v',
- imageFormat === 'jpeg' ? 'mjpeg' : 'png',
- '-f',
- 'image2pipe',
- ...determineResizeParams(needsResize),
- '-',
- ].filter(truthy)
- );
- if (!stderr) {
- throw new Error('unexpectedly did not get stderr');
- }
-
- if (!stdout) {
- throw new Error('unexpectedly did not get stdout');
- }
-
- const stderrChunks: Buffer[] = [];
- const stdoutChunks: Buffer[] = [];
-
- const stdErrString = new Promise<string>((resolve, reject) => {
- stderr.on('data', (d) => stderrChunks.push(d));
- stderr.on('error', (err) => reject(err));
- stderr.on('end', () =>
- resolve(Buffer.concat(stderrChunks).toString('utf-8'))
- );
- });
-
- const stdoutChunk = new Promise<Buffer>((resolve, reject) => {
- stdout.on('data', (d) => {
- stdoutChunks.push(d);
- });
- stdout.on('error', (err) => {
- reject(err);
- });
- stdout.on('end', () => {
- resolve(Buffer.concat(stdoutChunks));
- });
- });
-
- const [stdErr, stdoutBuffer] = await Promise.all([stdErrString, stdoutChunk]);
- return [stdErr, stdoutBuffer] as const;
-};
-
const extractFrameFromVideoFn = async ({
time,
ffmpegExecutable,
diff --git a/packages/renderer/src/get-can-extract-frames-fast.ts b/packages/renderer/src/get-can-extract-frames-fast.ts
new file mode 100644
index 0000000000..8ffd3a5e8f
--- /dev/null
+++ b/packages/renderer/src/get-can-extract-frames-fast.ts
@@ -0,0 +1,85 @@
+import fs from 'fs';
+import {getVideoStreamDurationwithoutCache} from './assets/get-video-stream-duration';
+import {ensurePresentationTimestampWithoutCache} from './ensure-presentation-timestamp';
+import type {FfmpegExecutable} from './ffmpeg-executable';
+import {findRemotionRoot} from './find-closest-package-json';
+import {getVideoInfoUncached} from './get-video-info';
+import {tryToExtractFrameOfVideoFast} from './try-to-extract-frame-of-video-fast';
+
+export const ACCEPTABLE_OFFSET_THRESHOLD = 40;
+
+export const getCanExtractFramesFast = async ({
+ src,
+ ffmpegExecutable,
+ ffprobeExecutable,
+}: {
+ src: string;
+ ffmpegExecutable?: FfmpegExecutable;
+ ffprobeExecutable?: FfmpegExecutable;
+}): Promise<{
+ canExtractFramesFast: boolean;
+ shouldReencode: boolean;
+}> => {
+ const remotionRoot = findRemotionRoot();
+ const out = await ensurePresentationTimestampWithoutCache({
+ ffmpegExecutable: ffmpegExecutable ?? null,
+ ffprobeExecutable: ffprobeExecutable ?? null,
+ remotionRoot,
+ src,
+ });
+ const {specialVcodecForTransparency: specialVcodec} =
+ await getVideoInfoUncached({
+ src: out,
+ ffprobeExecutable: ffprobeExecutable ?? null,
+ remotionRoot,
+ });
+
+ if (specialVcodec === 'vp8') {
+ fs.unlinkSync(out);
+ return {
+ canExtractFramesFast: false,
+ shouldReencode: false,
+ };
+ }
+
+ const {duration} = await getVideoStreamDurationwithoutCache({
+ ffprobeExecutable: ffprobeExecutable ?? null,
+ remotionRoot,
+ src: out,
+ });
+
+ if (duration === null) {
+ fs.unlinkSync(out);
+ throw new Error(
+ `Could not determine the duration of ${src} using FFMPEG. The file is not supported.`
+ );
+ }
+
+ const actualOffset = `${duration * 1000 - ACCEPTABLE_OFFSET_THRESHOLD}ms`;
+
+ const [stdErr] = await tryToExtractFrameOfVideoFast({
+ actualOffset,
+ ffmpegExecutable: ffmpegExecutable ?? null,
+ imageFormat: 'jpeg',
+ // Intentionally leaving needsResize as null, because we don't need to resize
+ needsResize: null,
+ remotionRoot,
+ specialVCodecForTransparency: specialVcodec,
+ src: out,
+ });
+ fs.unlinkSync(out);
+
+ const isEmpty = stdErr.includes('Output file is empty');
+
+ if (isEmpty) {
+ return {
+ canExtractFramesFast: false,
+ shouldReencode: true,
+ };
+ }
+
+ return {
+ canExtractFramesFast: true,
+ shouldReencode: false,
+ };
+};
diff --git a/packages/renderer/src/get-frame-of-video-slow.ts b/packages/renderer/src/get-frame-of-video-slow.ts
new file mode 100644
index 0000000000..d432d43c44
--- /dev/null
+++ b/packages/renderer/src/get-frame-of-video-slow.ts
@@ -0,0 +1,110 @@
+// Uses no seeking, therefore the whole video has to be decoded. This is a last resort and should only happen
+// if the video is corrupted
+import execa from 'execa';
+import type {OffthreadVideoImageFormat} from 'remotion';
+import type {SpecialVCodecForTransparency} from './assets/download-map';
+import {determineResizeParams} from './determine-resize-params';
+import {determineVcodecFfmepgFlags} from './determine-vcodec-ffmepg-flags';
+import type {FfmpegExecutable} from './ffmpeg-executable';
+import {getExecutableBinary} from './ffmpeg-flags';
+import {truthy} from './truthy';
+export const getFrameOfVideoSlow = async ({
+ src,
+ duration,
+ ffmpegExecutable,
+ imageFormat,
+ specialVCodecForTransparency,
+ needsResize,
+ offset,
+ fps,
+ remotionRoot,
+}: {
+ ffmpegExecutable: FfmpegExecutable;
+ src: string;
+ duration: number;
+ imageFormat: OffthreadVideoImageFormat;
+ specialVCodecForTransparency: SpecialVCodecForTransparency;
+ needsResize: [number, number] | null;
+ offset: number;
+ fps: number | null;
+ remotionRoot: string;
+}): Promise<Buffer> => {
+ console.warn(
+ `\nUsing a slow method to extract the frame at ${duration}ms of ${src}. See https://remotion.dev/docs/slow-method-to-extract-frame for advice`
+ );
+
+ const actualOffset = `-${duration * 1000 - offset}ms`;
+ const command = [
+ '-itsoffset',
+ actualOffset,
+ ...determineVcodecFfmepgFlags(specialVCodecForTransparency),
+ '-i',
+ src,
+ '-frames:v',
+ '1',
+ '-c:v',
+ imageFormat === 'jpeg' ? 'mjpeg' : 'png',
+ '-f',
+ 'image2pipe',
+ ...determineResizeParams(needsResize),
+ '-',
+ ].filter(truthy);
+
+ const {stdout, stderr} = execa(
+ await getExecutableBinary(ffmpegExecutable, remotionRoot, 'ffmpeg'),
+ command
+ );
+
+ if (!stderr) {
+ throw new Error('unexpectedly did not get stderr');
+ }
+
+ if (!stdout) {
+ throw new Error('unexpectedly did not get stdout');
+ }
+
+ const stderrChunks: Buffer[] = [];
+ const stdoutChunks: Buffer[] = [];
+
+ const stdErrString = new Promise<string>((resolve, reject) => {
+ stderr.on('data', (d) => stderrChunks.push(d));
+ stderr.on('error', (err) => reject(err));
+ stderr.on('end', () =>
+ resolve(Buffer.concat(stderrChunks).toString('utf-8'))
+ );
+ });
+
+ const stdoutChunk = new Promise<Buffer>((resolve, reject) => {
+ stdout.on('data', (d) => stdoutChunks.push(d));
+ stdout.on('error', (err) => reject(err));
+ stdout.on('end', () => resolve(Buffer.concat(stdoutChunks)));
+ });
+
+ const [stdErr, stdoutBuffer] = await Promise.all([stdErrString, stdoutChunk]);
+
+ const isEmpty = stdErr.includes('Output file is empty');
+ if (isEmpty) {
+ if (offset > 70) {
+ throw new Error(
+ `Could not get last frame of ${src}. Tried to seek to the end using the command "ffmpeg ${command.join(
+ ' '
+ )}" but got no frame. Most likely this video is corrupted.`
+ );
+ }
+
+ return getFrameOfVideoSlow({
+ ffmpegExecutable,
+ duration,
+ // Decrement in 10ms increments, or 1 frame (e.g. fps = 25 --> 40ms)
+ offset: offset + (fps === null ? 10 : 1000 / fps),
+ src,
+ imageFormat,
+ specialVCodecForTransparency,
+ needsResize,
+ fps,
+ remotionRoot,
+ });
+ }
+
+ return stdoutBuffer;
+};
diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts
index 9cdb53e80b..15450701c4 100644
--- a/packages/renderer/src/index.ts
+++ b/packages/renderer/src/index.ts
@@ -11,7 +11,6 @@ import {deleteDirectory} from './delete-directory';
import {ensureOutputDirectory} from './ensure-output-directory';
import {symbolicateError} from './error-handling/symbolicate-error';
import {SymbolicateableError} from './error-handling/symbolicateable-error';
-import {canExtractFramesFast} from './extract-frame-from-video';
import {
ffmpegHasFeature,
getExecutableBinary,
@@ -71,6 +70,7 @@ export {FfmpegExecutable} from './ffmpeg-executable';
export {FfmpegVersion} from './ffmpeg-flags';
export type {FfmpegOverrideFn} from './ffmpeg-override';
export {FrameRange} from './frame-range';
+export {getCanExtractFramesFast} from './get-can-extract-frames-fast';
export {getCompositions} from './get-compositions';
export {
ImageFormat,
@@ -153,7 +153,6 @@ export const RenderInternals = {
getExecutableBinary,
validateBitrate,
getFfmpegVersion,
- canExtractFramesFast,
};
// Warn of potential performance issues with Apple Silicon (M1 chip under Rosetta)
diff --git a/packages/renderer/src/try-to-extract-frame-of-video-fast.ts b/packages/renderer/src/try-to-extract-frame-of-video-fast.ts
new file mode 100644
index 0000000000..61ef449290
--- /dev/null
+++ b/packages/renderer/src/try-to-extract-frame-of-video-fast.ts
@@ -0,0 +1,80 @@
+import execa from 'execa';
+import type {OffthreadVideoImageFormat} from 'remotion';
+import type {
+ NeedsResize,
+ SpecialVCodecForTransparency,
+} from './assets/download-map';
+import {determineResizeParams} from './determine-resize-params';
+import {determineVcodecFfmepgFlags} from './determine-vcodec-ffmepg-flags';
+import type {FfmpegExecutable} from './ffmpeg-executable';
+import {getExecutableBinary} from './ffmpeg-flags';
+import {truthy} from './truthy';
+export const tryToExtractFrameOfVideoFast = async ({
+ ffmpegExecutable,
+ remotionRoot,
+ specialVCodecForTransparency,
+ imageFormat,
+ needsResize,
+ src,
+ actualOffset,
+}: {
+ ffmpegExecutable: FfmpegExecutable;
+ remotionRoot: string;
+ imageFormat: OffthreadVideoImageFormat;
+ needsResize: NeedsResize;
+ src: string;
+ specialVCodecForTransparency: SpecialVCodecForTransparency;
+ actualOffset: string;
+}) => {
+ const {stdout, stderr} = execa(
+ await getExecutableBinary(ffmpegExecutable, remotionRoot, 'ffmpeg'),
+ [
+ '-ss',
+ actualOffset,
+ ...determineVcodecFfmepgFlags(specialVCodecForTransparency),
+ '-i',
+ src,
+ '-frames:v',
+ '1',
+ '-c:v',
+ imageFormat === 'jpeg' ? 'mjpeg' : 'png',
+ '-f',
+ 'image2pipe',
+ ...determineResizeParams(needsResize),
+ '-',
+ ].filter(truthy)
+ );
+ if (!stderr) {
+ throw new Error('unexpectedly did not get stderr');
+ }
+
+ if (!stdout) {
+ throw new Error('unexpectedly did not get stdout');
+ }
+
+ const stderrChunks: Buffer[] = [];
+ const stdoutChunks: Buffer[] = [];
+
+ const stdErrString = new Promise<string>((resolve, reject) => {
+ stderr.on('data', (d) => stderrChunks.push(d));
+ stderr.on('error', (err) => reject(err));
+ stderr.on('end', () =>
+ resolve(Buffer.concat(stderrChunks).toString('utf-8'))
+ );
+ });
+
+ const stdoutChunk = new Promise<Buffer>((resolve, reject) => {
+ stdout.on('data', (d) => {
+ stdoutChunks.push(d);
+ });
+ stdout.on('error', (err) => {
+ reject(err);
+ });
+ stdout.on('end', () => {
+ resolve(Buffer.concat(stdoutChunks));
+ });
+ });
+
+ const [stdErr, stdoutBuffer] = await Promise.all([stdErrString, stdoutChunk]);
+ return [stdErr, stdoutBuffer] as const;
+};