🎥 Make videos programmatically with React
disable parallel encoding when system has not enough RAM
Jonny Burgera412504d1994
diff --git a/packages/renderer/src/prestitcher-memory-usage.ts b/packages/renderer/src/prestitcher-memory-usage.tsnew file mode 100644index 0000000000..2abb44a44b--- /dev/null+++ b/packages/renderer/src/prestitcher-memory-usage.ts@@ -0,0 +1,40 @@+import os from 'os';++export const estimateMemoryUsageForPrestitcher = ({+ width,+ height,+}: {+ width: number;+ height: number;+}) => {+ // Empirically we detected that per 1 million pixels, FFMPEG uses around 1GB of memory, relatively independent of+ // the duration of the video.+ const memoryUsageFor4K = 1_000_000_000;+ const memoryUsageOfPixel = memoryUsageFor4K / 1_000_000;++ return memoryUsageOfPixel * width * height;+};++export const shouldUseParallelEncoding = ({+ width,+ height,+}: {+ width: number;+ height: number;+}) => {+ const freeMemory = os.freemem();+ const estimatedUsage = estimateMemoryUsageForPrestitcher({+ height,+ width,+ });++ const hasEnoughMemory =+ freeMemory - estimatedUsage > 2_000_000_000 &&+ estimatedUsage / freeMemory < 0.5;++ return {+ hasEnoughMemory,+ freeMemory,+ estimatedUsage,+ };+};diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex b168b21e9b..77f9a10a46 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -31,6 +31,7 @@ import {DEFAULT_OVERWRITE} from './overwrite';import {startPerfMeasure, stopPerfMeasure} from './perf';import type {PixelFormat} from './pixel-format';import {prespawnFfmpeg} from './prespawn-ffmpeg';+import {shouldUseParallelEncoding} from './prestitcher-memory-usage';import type {ProResProfile} from './prores-profile';import {validateQuality} from './quality';import {renderFrames} from './render-frames';@@ -150,7 +151,31 @@ export const renderMedia = ({const renderStart = Date.now();const downloadMap = options.downloadMap ?? makeDownloadMap();- const parallelEncoding = canUseParallelEncoding(codec);+ const {estimatedUsage, freeMemory, hasEnoughMemory} =+ shouldUseParallelEncoding({+ height: composition.height,+ width: composition.width,+ });+ const parallelEncoding = hasEnoughMemory && canUseParallelEncoding(codec);++ if (options.verbose) {+ console.log(+ '[PRESTITCHER] Free memory:',+ freeMemory,+ 'Estimated usage parallel encoding',+ estimatedUsage+ );+ console.log(+ '[PRESTICHER]: Codec supports parallel rendering:',+ canUseParallelEncoding(codec)+ );+ if (parallelEncoding) {+ console.log('[PRESTICHER] Parallel encoding is enabled.');+ } else {+ console.log('[PRESTITCHER] Parallel encoding is disabled.');+ }+ }+const actualImageFormat = imageFormat ?? 'jpeg';const preEncodedFileLocation = parallelEncoding