Skip to content

🎥 Make videos programmatically with React

remove stuff not needed anymore

Jonny Burgere686d3962043
diff --git a/packages/core/src/video/index.ts b/packages/core/src/video/index.ts
index f9560e772d..5573c995af 100644
--- a/packages/core/src/video/index.ts
+++ b/packages/core/src/video/index.ts
@@ -1,6 +1,5 @@
export {OffthreadVideo} from './OffthreadVideo.js';
export {
- OffthreadVideoImageFormat,
OffthreadVideoProps as RemotionOffthreadVideoProps,
RemotionMainVideoProps,
RemotionVideoProps,
diff --git a/packages/renderer/src/assets/download-map.ts b/packages/renderer/src/assets/download-map.ts
index 12a0939e77..be080825f1 100644
--- a/packages/renderer/src/assets/download-map.ts
+++ b/packages/renderer/src/assets/download-map.ts
@@ -4,24 +4,6 @@ import type {TAsset} from 'remotion';
import {deleteDirectory} from '../delete-directory';
import {tmpDir} from '../tmp-dir';
-type EncodingStatus =
- | {
- type: 'encoding';
- }
- | {
- type: 'done';
- src: string;
- }
- | undefined;
-
-export type SpecialVCodecForTransparency = 'vp9' | 'vp8' | 'none';
-
-export type NeedsResize = [number, number] | null;
-
-export type Vp9Result = {
- specialVcodecForTransparency: SpecialVCodecForTransparency;
- needsResize: NeedsResize;
-};
export type VideoDurationResult = {
duration: number | null;
fps: number | null;
@@ -49,10 +31,6 @@ export type DownloadMap = {
| undefined;
};
listeners: {[key: string]: {[downloadDir: string]: (() => void)[]}};
- lastFrameMap: Record<string, {lastAccessed: number; data: Buffer}>;
- isBeyondLastFrameMap: Record<string, number>;
- isVp9VideoCache: Record<string, Vp9Result>;
- ensureFileHasPresentationTimestamp: Record<string, EncodingStatus>;
videoDurationResultCache: Record<string, VideoDurationResult>;
durationOfAssetCache: Record<string, AudioChannelsAndDurationResultCache>;
downloadDir: string;
@@ -96,10 +74,6 @@ export const makeDownloadMap = (): DownloadMap => {
isDownloadingMap: {},
hasBeenDownloadedMap: {},
listeners: {},
- lastFrameMap: {},
- isBeyondLastFrameMap: {},
- ensureFileHasPresentationTimestamp: {},
- isVp9VideoCache: {},
videoDurationResultCache: {},
durationOfAssetCache: {},
id: String(Math.random()),
diff --git a/packages/renderer/src/determine-vcodec-ffmpeg-flags.ts b/packages/renderer/src/determine-vcodec-ffmpeg-flags.ts
deleted file mode 100644
index 4291911f5a..0000000000
--- a/packages/renderer/src/determine-vcodec-ffmpeg-flags.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type {SpecialVCodecForTransparency} from './assets/download-map';
-import {truthy} from './truthy';
-
-export const determineVcodecFfmpegFlags = (
- 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
deleted file mode 100644
index 9c4a48c926..0000000000
--- a/packages/renderer/src/ensure-presentation-timestamp.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import path from 'path';
-import type {DownloadMap} from './assets/download-map';
-import {callFf} from './call-ffmpeg';
-import {guessExtensionForVideo} from './guess-extension-for-media';
-import {truthy} from './truthy';
-
-type Callback = {
- src: string;
- fn: (newsrc: string) => void;
-};
-
-let callbacks: Callback[] = [];
-
-const getTemporaryOutputName = async ({src}: {src: string}) => {
- const parts = src.split(path.sep);
-
- // If there is no file extension for the video, then we need to temporarily add an extension
-
- const lastPart = parts[parts.length - 1];
- const extraExtension = lastPart.includes('.')
- ? null
- : await guessExtensionForVideo({
- src,
- });
-
- return parts
- .map((p, i) => {
- if (i === parts.length - 1) {
- return [`pts-${p}`, extraExtension].filter(truthy).join('.');
- }
-
- return p;
- })
- .join(path.sep);
-};
-
-export const ensurePresentationTimestampWithoutCache = async ({
- src,
-}: {
- src: string;
-}) => {
- // If there is no file extension for the video, then we need to tempoa
- const output = await getTemporaryOutputName({
- src,
- });
-
- await callFf('ffmpeg', [
- '-i',
- src,
- '-fflags',
- '+genpts+igndts',
- '-vcodec',
- 'copy',
- '-acodec',
- 'copy',
- output,
- '-y',
- ]);
-
- return output;
-};
-
-export const ensurePresentationTimestamps = async ({
- downloadMap,
- src,
-}: {
- downloadMap: DownloadMap;
- src: string;
-}): 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({
- src,
- });
-
- callbacks = callbacks.filter((c) => {
- if (c.src === src) {
- c.fn(output);
- return false;
- }
-
- return true;
- });
- downloadMap.ensureFileHasPresentationTimestamp[src] = {
- type: 'done',
- src: output,
- };
- return output;
-};
diff --git a/packages/renderer/src/extract-frame-from-video.ts b/packages/renderer/src/extract-frame-from-video.ts
deleted file mode 100644
index 96b26c3d40..0000000000
--- a/packages/renderer/src/extract-frame-from-video.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-import type {OffthreadVideoImageFormat} from 'remotion';
-import type {DownloadMap} from './assets/download-map';
-import {getVideoStreamDuration} from './assets/get-video-stream-duration';
-import {callFf} from './call-ffmpeg';
-import {determineResizeParams} from './determine-resize-params';
-import {determineVcodecFfmpegFlags} from './determine-vcodec-ffmpeg-flags';
-import {ensurePresentationTimestamps} from './ensure-presentation-timestamp';
-import {frameToFfmpegTimestamp} from './frame-to-ffmpeg-timestamp';
-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 {
- getLastFrameFromCache,
- setLastFrameInCache,
-} from './last-frame-from-video-cache';
-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 getLastFrameOfVideoFastUnlimited = async (
- options: LastFrameOptions
-): Promise<Buffer> => {
- const {offset, src, downloadMap} = options;
- const fromCache = getLastFrameFromCache({...options, offset: 0});
- if (fromCache) {
- return fromCache;
- }
-
- const {duration, fps} = await getVideoStreamDuration(downloadMap, src);
-
- if (duration === null) {
- throw new Error(
- `Could not determine the duration of ${src} using FFMPEG. The file is not supported.`
- );
- }
-
- if (
- options.specialVCodecForTransparency === 'vp8' ||
- offset > ACCEPTABLE_OFFSET_THRESHOLD
- ) {
- const last = await getFrameOfVideoSlow({
- duration,
- src,
- imageFormat: options.imageFormat,
- specialVCodecForTransparency: options.specialVCodecForTransparency,
- needsResize: options.needsResize,
- offset: offset - 1000 / (fps === null ? 10 : fps),
- fps,
- });
- return last;
- }
-
- const actualOffset = `${duration * 1000 - offset}ms`;
- const [stdErr, stdoutBuffer] = await tryToExtractFrameOfVideoFast({
- actualOffset,
- imageFormat: options.imageFormat,
- needsResize: options.needsResize,
- specialVCodecForTransparency: options.specialVCodecForTransparency,
- src,
- });
-
- const isEmpty = stdErr.includes('Output file is empty');
- if (isEmpty) {
- const unlimited = await getLastFrameOfVideoFastUnlimited({
- // Decrement in 10ms increments, or 1 frame (e.g. fps = 25 --> 40ms)
- offset: offset + (fps === null ? 10 : 1000 / fps),
- src,
- imageFormat: options.imageFormat,
- specialVCodecForTransparency: options.specialVCodecForTransparency,
- needsResize: options.needsResize,
- downloadMap: options.downloadMap,
- });
-
- return unlimited;
- }
-
- return stdoutBuffer;
-};
-
-export const getLastFrameOfVideo = async (
- options: LastFrameOptions
-): Promise<Buffer> => {
- const result = await lastFrameLimit(
- getLastFrameOfVideoFastUnlimited,
- options
- );
- setLastFrameInCache(options, result);
-
- return result;
-};
-
-type Options = {
- time: number;
- src: string;
- imageFormat: OffthreadVideoImageFormat;
- downloadMap: DownloadMap;
- remotionRoot: string;
-};
-
-const extractFrameFromVideoFn = async ({
- time,
- imageFormat,
- downloadMap,
- remotionRoot,
- ...options
-}: Options): Promise<Buffer> => {
- // We make a new copy of the video only for video because the conversion may affect
- // audio rendering, so we work with 2 different files
- const src = await ensurePresentationTimestamps({
- downloadMap,
- src: options.src,
- });
- const {specialVcodecForTransparency: specialVcodec, needsResize} =
- await getVideoInfo(downloadMap, src);
-
- if (specialVcodec === 'vp8') {
- const {fps} = await getVideoStreamDuration(downloadMap, src);
- return getFrameOfVideoSlow({
- imageFormat,
- specialVCodecForTransparency: specialVcodec,
- src,
- duration: time,
- needsResize,
- offset: 0,
- fps,
- });
- }
-
- if (isBeyondLastFrame(downloadMap, src, time)) {
- const lastFrame = await getLastFrameOfVideo({
- offset: 0,
- src,
- imageFormat,
- specialVCodecForTransparency: specialVcodec,
- needsResize,
- downloadMap,
- });
- return lastFrame;
- }
-
- const ffmpegTimestamp = frameToFfmpegTimestamp(time);
- const {stdout, stderr} = callFf(
- 'ffmpeg',
- [
- '-ss',
- ffmpegTimestamp,
- ...determineVcodecFfmpegFlags(specialVcodec),
- '-i',
- src,
- '-frames:v',
- '1',
- '-f',
- 'image2pipe',
- '-vcodec',
- imageFormat === 'jpeg' ? 'mjpeg' : 'png',
- ...determineResizeParams(needsResize),
- '-',
- ].filter(truthy),
- {
- buffer: false,
- }
- );
-
- if (!stderr) {
- throw new Error('unexpectedly did not get stderr');
- }
-
- if (!stdout) {
- throw new Error('unexpectedly did not get stdout');
- }
-
- const stdoutChunks: Buffer[] = [];
- 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'))
- );
- });
-
- 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)));
- });
-
- const [stderrStr, stdOut] = await Promise.all([
- stderrStringProm,
- stdoutBuffer,
- ]);
-
- if (stderrStr.includes('Output file is empty')) {
- markAsBeyondLastFrame(downloadMap, src, time);
- const last = await getLastFrameOfVideo({
- offset: 0,
- src,
- imageFormat,
- specialVCodecForTransparency: specialVcodec,
- needsResize,
- downloadMap,
- });
-
- return last;
- }
-
- if (stdOut.length === 0) {
- console.log('FFMPEG Logs:');
- console.log(stderrStr);
- throw new Error(
- "Couldn't extract frame from video - FFMPEG did not return any data. Check logs to see more information"
- );
- }
-
- return stdOut;
-};
-
-export const extractFrameFromVideo = async (options: Options) => {
- const perf = startPerfMeasure('extract-frame');
- const res = await mainLimit(extractFrameFromVideoFn, options);
- stopPerfMeasure(perf);
- return res;
-};
diff --git a/packages/renderer/src/get-can-extract-frames-fast.ts b/packages/renderer/src/get-can-extract-frames-fast.ts
deleted file mode 100644
index 4194990327..0000000000
--- a/packages/renderer/src/get-can-extract-frames-fast.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import fs from 'fs';
-import {getVideoStreamDurationwithoutCache} from './assets/get-video-stream-duration';
-import {ensurePresentationTimestampWithoutCache} from './ensure-presentation-timestamp';
-import {getVideoInfoUncached} from './get-video-info';
-import {tryToExtractFrameOfVideoFast} from './try-to-extract-frame-of-video-fast';
-
-export const ACCEPTABLE_OFFSET_THRESHOLD = 50;
-
-/**
- * @description Probes whether frames of a video can be efficiently extracted when using <OffthreadVideo>.
- * @see [Documentation](https://www.remotion.dev/docs/renderer/get-can-extract-frames-fast)
- */
-export const getCanExtractFramesFast = async ({
- src,
-}: {
- src: string;
-}): Promise<{
- canExtractFramesFast: boolean;
- shouldReencode: boolean;
-}> => {
- const out = await ensurePresentationTimestampWithoutCache({
- src,
- });
- const {specialVcodecForTransparency: specialVcodec} =
- await getVideoInfoUncached({
- src: out,
- });
-
- if (specialVcodec === 'vp8') {
- fs.unlinkSync(out);
- return {
- canExtractFramesFast: false,
- shouldReencode: false,
- };
- }
-
- const {duration} = await getVideoStreamDurationwithoutCache({
- 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,
- imageFormat: 'jpeg',
- // Intentionally leaving needsResize as null, because we don't need to resize
- needsResize: null,
- 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
deleted file mode 100644
index e2ecd6d804..0000000000
--- a/packages/renderer/src/get-frame-of-video-slow.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-// 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 type {OffthreadVideoImageFormat} from 'remotion';
-import type {SpecialVCodecForTransparency} from './assets/download-map';
-import {callFf} from './call-ffmpeg';
-import {determineResizeParams} from './determine-resize-params';
-import {determineVcodecFfmpegFlags} from './determine-vcodec-ffmpeg-flags';
-import {truthy} from './truthy';
-export const getFrameOfVideoSlow = async ({
- src,
- duration,
- imageFormat,
- specialVCodecForTransparency,
- needsResize,
- offset,
- fps,
-}: {
- src: string;
- duration: number;
- imageFormat: OffthreadVideoImageFormat;
- specialVCodecForTransparency: SpecialVCodecForTransparency;
- needsResize: [number, number] | null;
- offset: number;
- fps: number | null;
-}): 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,
- ...determineVcodecFfmpegFlags(specialVCodecForTransparency),
- '-i',
- src,
- '-frames:v',
- '1',
- '-c:v',
- imageFormat === 'jpeg' ? 'mjpeg' : 'png',
- '-f',
- 'image2pipe',
- ...determineResizeParams(needsResize),
- '-',
- ].filter(truthy);
-
- const {stdout, stderr} = callFf('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({
- 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,
- });
- }
-
- return stdoutBuffer;
-};
diff --git a/packages/renderer/src/get-video-info.ts b/packages/renderer/src/get-video-info.ts
deleted file mode 100644
index 57975e4c69..0000000000
--- a/packages/renderer/src/get-video-info.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type {DownloadMap, Vp9Result} from './assets/download-map';
-import {calculateDisplayVideoSize} from './calculate-sar-dar-pixels';
-import {callFf} from './call-ffmpeg';
-import {pLimit} from './p-limit';
-
-const limit = pLimit(1);
-
-export async function getVideoInfoUncached({
- src,
-}: {
- src: string;
-}): Promise<Vp9Result> {
- const task = await callFf('ffprobe', [src]);
-
- const isVp9 = task.stderr.includes('Video: vp9');
- const isVp8 = task.stderr.includes('Video: vp8');
-
- const dimensions = task.stderr
- .split('\n')
- .find((n) => n.trim().startsWith('Stream #'))
- ?.match(/([0-9]{2,6})x([0-9]{2,6})/);
- const dar = task.stderr.match(/DAR\s([0-9]+):([0-9]+)/);
-
- let needsResize: null | [number, number] = null;
-
- if (dimensions && dar) {
- const width = parseInt(dimensions[1], 10);
- const height = parseInt(dimensions[2], 10);
- const darWidth = parseInt(dar[1], 10);
- const darHeight = parseInt(dar[2], 10);
-
- const {width: actualWidth, height: actualHeight} =
- calculateDisplayVideoSize({
- darX: darWidth,
- darY: darHeight,
- x: width,
- y: height,
- });
-
- if (actualWidth !== width || actualHeight !== height) {
- needsResize = [actualWidth, actualHeight];
- }
- }
-
- const result: Vp9Result = {
- specialVcodecForTransparency: isVp9 ? 'vp9' : isVp8 ? 'vp8' : 'none',
- needsResize,
- };
-
- return result;
-}
-
-async function getVideoInfoUnlimited(
- downloadMap: DownloadMap,
- src: string
-): Promise<Vp9Result> {
- if (typeof downloadMap.isVp9VideoCache[src] !== 'undefined') {
- return downloadMap.isVp9VideoCache[src];
- }
-
- const result = await getVideoInfoUncached({
- src,
- });
-
- downloadMap.isVp9VideoCache[src] = result;
-
- return downloadMap.isVp9VideoCache[src];
-}
-
-export const getVideoInfo = (
- downloadMap: DownloadMap,
- src: string
-): Promise<Vp9Result> => {
- return limit(() => getVideoInfoUnlimited(downloadMap, src));
-};
diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts
index fb232f977d..c5a053cbd5 100644
--- a/packages/renderer/src/index.ts
+++ b/packages/renderer/src/index.ts
@@ -79,7 +79,6 @@ export {ErrorWithStackFrame} from './error-handling/handle-javascript-exception'
export type {FfmpegOverrideFn} from './ffmpeg-override';
export {FileExtension} from './file-extensions';
export {FrameRange} from './frame-range';
-export {getCanExtractFramesFast} from './get-can-extract-frames-fast';
export {getCompositions} from './get-compositions';
export {getActualConcurrency} from './get-concurrency';
export {
diff --git a/packages/renderer/src/is-beyond-last-frame.ts b/packages/renderer/src/is-beyond-last-frame.ts
deleted file mode 100644
index b72df428f7..0000000000
--- a/packages/renderer/src/is-beyond-last-frame.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type {DownloadMap} from './assets/download-map';
-
-export const isBeyondLastFrame = (
- downloadMap: DownloadMap,
- src: string,
- time: number
-) => {
- return (
- downloadMap.isBeyondLastFrameMap[src] &&
- time >= downloadMap.isBeyondLastFrameMap[src]
- );
-};
-
-export const markAsBeyondLastFrame = (
- downloadMap: DownloadMap,
- src: string,
- time: number
-) => {
- downloadMap.isBeyondLastFrameMap[src] = time;
-};
diff --git a/packages/renderer/src/last-frame-from-video-cache.ts b/packages/renderer/src/last-frame-from-video-cache.ts
deleted file mode 100644
index b644d0abc6..0000000000
--- a/packages/renderer/src/last-frame-from-video-cache.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-// OffthreadVideo requires sometimes that the last frame of a video gets extracted, however, this can be slow. We allocate a cache for it but that can be garbage collected
-
-import type {OffthreadVideoImageFormat} from 'remotion';
-import type {
- DownloadMap,
- SpecialVCodecForTransparency,
-} from './assets/download-map';
-
-export type LastFrameOptions = {
- offset: number;
- src: string;
- specialVCodecForTransparency: SpecialVCodecForTransparency;
- imageFormat: OffthreadVideoImageFormat;
- needsResize: [number, number] | null;
- downloadMap: DownloadMap;
-};
-
-const MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
-
-let bufferSize = 0;
-
-const makeLastFrameCacheKey = (options: LastFrameOptions) => {
- return [
- options.offset,
- options.src,
- options.imageFormat,
- options.downloadMap.id,
- ].join('-');
-};
-
-export const setLastFrameInCache = (
- options: LastFrameOptions,
- data: Buffer
-) => {
- const key = makeLastFrameCacheKey(options);
- if (options.downloadMap.lastFrameMap[key]) {
- bufferSize -= options.downloadMap.lastFrameMap[key].data.byteLength;
- }
-
- options.downloadMap.lastFrameMap[key] = {data, lastAccessed: Date.now()};
- bufferSize += data.byteLength;
- ensureMaxSize(options.downloadMap);
-};
-
-export const getLastFrameFromCache = (
- options: LastFrameOptions
-): Buffer | null => {
- const key = makeLastFrameCacheKey(options);
-
- if (!options.downloadMap.lastFrameMap[key]) {
- return null;
- }
-
- options.downloadMap.lastFrameMap[key].lastAccessed = Date.now();
- return options.downloadMap.lastFrameMap[key].data ?? null;
-};
-
-const removedLastFrameFromCache = (key: string, downloadMap: DownloadMap) => {
- if (!downloadMap.lastFrameMap[key]) {
- return;
- }
-
- bufferSize -= downloadMap.lastFrameMap[key].data.byteLength;
-
- delete downloadMap.lastFrameMap[key];
-};
-
-const ensureMaxSize = (downloadMap: DownloadMap) => {
- // eslint-disable-next-line no-unmodified-loop-condition
- while (bufferSize > MAX_CACHE_SIZE) {
- const earliest = Object.entries(downloadMap.lastFrameMap).sort((a, b) => {
- return a[1].lastAccessed - b[1].lastAccessed;
- })[0];
-
- removedLastFrameFromCache(earliest[0], downloadMap);
- }
-};
-
-export const clearLastFileCache = (downloadMap: DownloadMap) => {
- downloadMap.lastFrameMap = {};
-};
diff --git a/packages/renderer/src/test/extract-frame-from-video.test.ts b/packages/renderer/src/test/extract-frame-from-video.test.ts
index 06a0b3a9dc..3ef407fc98 100644
--- a/packages/renderer/src/test/extract-frame-from-video.test.ts
+++ b/packages/renderer/src/test/extract-frame-from-video.test.ts
@@ -1,7 +1,6 @@
import path from 'path';
import {expect, test} from 'vitest';
import {cleanDownloadMap, makeDownloadMap} from '../assets/download-map';
-import {extractFrameFromVideo} from '../extract-frame-from-video';
const src = path.join(
__dirname,
diff --git a/packages/renderer/src/test/last-frame-video-cache.test.ts b/packages/renderer/src/test/last-frame-video-cache.test.ts
deleted file mode 100644
index aaa90066de..0000000000
--- a/packages/renderer/src/test/last-frame-video-cache.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import crypto from 'crypto';
-import {expect, test} from 'vitest';
-import type {DownloadMap} from '../assets/download-map';
-import {cleanDownloadMap, makeDownloadMap} from '../assets/download-map';
-import type {LastFrameOptions} from '../last-frame-from-video-cache';
-import {
- clearLastFileCache,
- getLastFrameFromCache,
- setLastFrameInCache,
-} from '../last-frame-from-video-cache';
-
-const makeKey = (id: string, downloadMap: DownloadMap): LastFrameOptions => {
- return {
- offset: 10,
- src: id,
- imageFormat: 'jpeg',
- specialVCodecForTransparency: 'none',
- needsResize: null,
- downloadMap,
- };
-};
-
-test('Last frame video cache', () => {
- const downloadMap = makeDownloadMap();
- expect(getLastFrameFromCache(makeKey('1', downloadMap))).toBe(null);
-
- const buf = crypto.randomBytes(10 * 1024 * 1024);
- setLastFrameInCache(makeKey('1', downloadMap), buf);
- expect(getLastFrameFromCache(makeKey('1', downloadMap))?.byteLength).toBe(
- 10 * 1024 * 1024
- );
- setLastFrameInCache(makeKey('2', downloadMap), buf);
- setLastFrameInCache(makeKey('3', downloadMap), buf);
- setLastFrameInCache(makeKey('4', downloadMap), buf);
- setLastFrameInCache(makeKey('5', downloadMap), buf);
- setLastFrameInCache(makeKey('6', downloadMap), buf);
-
- expect(
- getLastFrameFromCache(makeKey('1', downloadMap))?.byteLength ?? 0
- ).toBe(0);
- expect(getLastFrameFromCache(makeKey('2', downloadMap))?.byteLength).toBe(
- 10 * 1024 * 1024
- );
- expect(getLastFrameFromCache(makeKey('3', downloadMap))?.byteLength).toBe(
- 10 * 1024 * 1024
- );
- expect(getLastFrameFromCache(makeKey('4', downloadMap))?.byteLength).toBe(
- 10 * 1024 * 1024
- );
- expect(getLastFrameFromCache(makeKey('5', downloadMap))?.byteLength).toBe(
- 10 * 1024 * 1024
- );
- expect(getLastFrameFromCache(makeKey('6', downloadMap))?.byteLength).toBe(
- 10 * 1024 * 1024
- );
-
- clearLastFileCache(downloadMap);
- cleanDownloadMap(downloadMap);
-});
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
deleted file mode 100644
index fc471264e0..0000000000
--- a/packages/renderer/src/try-to-extract-frame-of-video-fast.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type {OffthreadVideoImageFormat} from 'remotion';
-import type {
- NeedsResize,
- SpecialVCodecForTransparency,
-} from './assets/download-map';
-import {callFf} from './call-ffmpeg';
-import {determineResizeParams} from './determine-resize-params';
-import {determineVcodecFfmpegFlags} from './determine-vcodec-ffmpeg-flags';
-import {truthy} from './truthy';
-
-export const tryToExtractFrameOfVideoFast = async ({
- specialVCodecForTransparency,
- imageFormat,
- needsResize,
- src,
- actualOffset,
-}: {
- imageFormat: OffthreadVideoImageFormat;
- needsResize: NeedsResize;
- src: string;
- specialVCodecForTransparency: SpecialVCodecForTransparency;
- actualOffset: string;
-}) => {
- const {stdout, stderr} = callFf(
- 'ffmpeg',
- [
- '-ss',
- actualOffset,
- ...determineVcodecFfmpegFlags(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;
-};