🎥 Make videos programmatically with React
handle corrupted video better
Jonny Burger6a7aacd01314
diff --git a/packages/example/public/corrupted.mp4 b/packages/example/public/corrupted.mp4new file mode 100644index 0000000000..70ff2ac2b5Binary files /dev/null and b/packages/example/public/corrupted.mp4 differdiff --git a/packages/example/src/CorruptVideo/index.tsx b/packages/example/src/CorruptVideo/index.tsxnew file mode 100644index 0000000000..1a5df6d731--- /dev/null+++ b/packages/example/src/CorruptVideo/index.tsx@@ -0,0 +1,14 @@+import {interpolate, OffthreadVideo, staticFile} from 'remotion';++const CorruptVideo: React.FC = () => {+ return (+ <OffthreadVideo+ volume={(f) =>+ interpolate(f, [0, 500], [1, 0], {extrapolateRight: 'clamp'})+ }+ src={staticFile('corrupted.mp4')}+ />+ );+};++export default CorruptVideo;diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsxindex f4628f3717..eee5992e5f 100644--- a/packages/example/src/Video.tsx+++ b/packages/example/src/Video.tsx@@ -5,6 +5,7 @@ import {TwentyTwoKHzAudio} from './22KhzAudio';import BetaText from './BetaText';import {ColorInterpolation} from './ColorInterpolation';import {MyCtx, WrappedInContext} from './Context';+import CorruptVideo from './CorruptVideo';import {ErrorOnFrame10} from './ErrorOnFrame10';import {FontDemo} from './Fonts';import {Framer} from './Framer';@@ -267,6 +268,14 @@ export const Index: React.FC = () => {fps={30}durationInFrames={600}/>+ <Composition+ id="corrupt-video"+ component={CorruptVideo}+ width={1280}+ height={720}+ fps={30}+ durationInFrames={2000}+ /><Compositionid="2hrvideo"component={InfinityVideo}diff --git a/packages/renderer/src/extract-frame-from-video.ts b/packages/renderer/src/extract-frame-from-video.tsindex ec882613af..33c6b7f948 100644--- a/packages/renderer/src/extract-frame-from-video.ts+++ b/packages/renderer/src/extract-frame-from-video.ts@@ -2,6 +2,7 @@ import execa from 'execa';import {FfmpegExecutable, Internals} from 'remotion';import {Readable} from 'stream';import {frameToFfmpegTimestamp} from './frame-to-ffmpeg-timestamp';+import {getDurationOfAsset} from './get-duration-of-asset';import {isBeyondLastFrame, markAsBeyondLastFrame} from './is-beyond-last-frame';import {getLastFrameFromCache,@@ -22,40 +23,97 @@ export function streamToString(stream: Readable) {const lastFrameLimit = pLimit(5);const mainLimit = pLimit(5);-const getLastFrameOfVideoUnlimited = async ({- ffmpegExecutable,- ffprobeExecutable,- offset,+// 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 getLastFrameOfVideoSlow = async ({src,-}: LastFrameOptions): Promise<Buffer> => {- if (offset > 100) {- throw new Error(- 'could not get last frame of ' +- src +- '. Tried to seek 100ms before the end of the video and no frame was found. The video container has a duration that is longer than it contains video.'- );- }+ duration,+ ffmpegExecutable,+}: {+ ffmpegExecutable: FfmpegExecutable;+ src: string;+ duration: number;+}) => {+ console.warn(+ `Using a slow method to determine the last frame of ${src}. The render can be sped up by re-encoding the video properly.`+ );- const durationCmd = await execa(ffprobeExecutable ?? 'ffprobe', [- '-v',- 'error',- '-select_streams',- 'v:0',- '-show_entries',- 'stream=duration',- '-of',- 'default=noprint_wrappers=1:nokey=1',+ const actualOffset = `-${duration * 1000}ms`;+ const command = [+ '-itsoffset',+ actualOffset,+ '-i',src,- ]);+ '-frames:v',+ '1',+ '-f',+ 'image2pipe',+ '-',+ ];+ const {stdout, stderr} = execa(ffmpegExecutable ?? '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 duration = parseFloat(durationCmd.stdout);+ 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)));+ });- if (Number.isNaN(duration)) {- throw new TypeError(- `Could not get duration of ${src}: ${durationCmd.stdout}`+ const [stdErr, stdoutBuffer] = await Promise.all([stdErrString, stdoutChunk]);++ const isEmpty = stdErr.includes('Output file is empty');+ if (isEmpty) {+ throw new Error(+ `Could not get last frame of ' + src + '. Tried to seek to the end using the command "ffmpeg ${[+ '-itsoffset',+ actualOffset,+ '-i',+ src,+ '-frames:v',+ '1',+ '-f',+ 'image2pipe',+ '-',+ ].join(' ')}" but got no frame. Most likely this video is corrupted.`);}+ return stdoutBuffer;+};++const getLastFrameOfVideoFastUnlimited = async ({+ ffmpegExecutable,+ ffprobeExecutable,+ offset,+ src,+}: LastFrameOptions): Promise<Buffer> => {+ const duration = await getDurationOfAsset({src, ffprobeExecutable});+ if (offset > 40) {+ return getLastFrameOfVideoSlow({+ duration,+ ffmpegExecutable,+ src,+ });+ }+const actualOffset = `${duration * 1000 - offset - 10}ms`;const {stdout, stderr} = execa(ffmpegExecutable ?? 'ffmpeg', ['-ss',@@ -104,7 +162,7 @@ const getLastFrameOfVideoUnlimited = async ({const isEmpty = stdErr.includes('Output file is empty');if (isEmpty) {- return getLastFrameOfVideoUnlimited({+ return getLastFrameOfVideoFastUnlimited({ffmpegExecutable,offset: offset + 10,src,@@ -123,7 +181,10 @@ export const getLastFrameOfVideo = async (return fromCache;}- const result = await lastFrameLimit(getLastFrameOfVideoUnlimited, options);+ const result = await lastFrameLimit(+ getLastFrameOfVideoFastUnlimited,+ options+ );setLastFrameInCache(options, result);return result;@@ -182,27 +243,17 @@ export const extractFrameFromVideoFn = async ({const stderrChunks: Buffer[] = [];const stderrStringProm = 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('utf8'));- });+ stderr.on('data', (d) => stderrChunks.push(d));+ stderr.on('error', (err) => reject(err));+ stderr.on('end', () =>+ resolve(Buffer.concat(stderrChunks).toString('utf8'))+ );});const stdoutBuffer = 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));- });+ stdout.on('data', (d) => stdoutChunks.push(d));+ stdout.on('error', (err) => reject(err));+ stdout.on('end', () => resolve(Buffer.concat(stdoutChunks)));});const [stderrStr, stdOut] = await Promise.all([diff --git a/packages/renderer/src/get-duration-of-asset.ts b/packages/renderer/src/get-duration-of-asset.tsnew file mode 100644index 0000000000..b6a9c8387f--- /dev/null+++ b/packages/renderer/src/get-duration-of-asset.ts@@ -0,0 +1,49 @@+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);+};diff --git a/packages/renderer/src/offthread-video-server.ts b/packages/renderer/src/offthread-video-server.tsindex b45fb89948..b23c639d1d 100644--- a/packages/renderer/src/offthread-video-server.ts+++ b/packages/renderer/src/offthread-video-server.ts@@ -90,6 +90,7 @@ export const startOffthreadVideoServer = ({.catch((err) => {res.writeHead(500);res.end();+ onError(err);console.log('Error occurred', err);});};diff --git a/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.ts b/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.tsnew file mode 100644index 0000000000..847d88b0c1--- /dev/null+++ b/packages/renderer/src/test/get-last-frame-of-corrupted-video.test.ts@@ -0,0 +1,19 @@+import path from 'path';+import {getLastFrameOfVideo} from '../extract-frame-from-video';++test('Get last frame of corrupted video', async () => {+ await getLastFrameOfVideo({+ ffmpegExecutable: null,+ ffprobeExecutable: null,+ offset: 0,+ src: path.join(+ __dirname,+ '..',+ '..',+ '..',+ 'example',+ 'public',+ 'corrupted.mp4'+ ),+ });+});