🎥 Make videos programmatically with React
expanded asset
Jonny Burger4f6fb84672ea
diff --git a/packages/cli/src/render-flows/render.ts b/packages/cli/src/render-flows/render.tsindex 5139172564..750e8cf0d2 100644--- a/packages/cli/src/render-flows/render.ts+++ b/packages/cli/src/render-flows/render.ts@@ -444,6 +444,7 @@ export const renderVideoFlow = async ({parallelEncodingEnabled: isUsingParallelEncoding,binariesDirectory,compositionStart: 0,+ extraFramesToCaptureAssets: [],});updateRenderProgress({newline: true, printToConsole: true});diff --git a/packages/renderer/src/assets/convert-assets-to-file-urls.ts b/packages/renderer/src/assets/convert-assets-to-file-urls.tsindex 0e412d0640..1d75a95bec 100644--- a/packages/renderer/src/assets/convert-assets-to-file-urls.ts+++ b/packages/renderer/src/assets/convert-assets-to-file-urls.ts@@ -1,5 +1,6 @@import type {TRenderAsset} from 'remotion/no-react';import type {LogLevel} from '../log-level';+import type {FrameAndAssets} from '../render-frames';import type {RenderMediaOnDownload} from './download-and-map-assets-to-file';import {downloadAndMapAssetsToFileUrl} from './download-and-map-assets-to-file';import type {DownloadMap} from './download-map';@@ -19,7 +20,7 @@ export const convertAssetsToFileUrls = async ({indent,logLevel,}: {- assets: TRenderAsset[][];+ assets: FrameAndAssets[];onDownload: RenderMediaOnDownload;downloadMap: DownloadMap;indent: boolean;@@ -29,21 +30,19 @@ export const convertAssetsToFileUrls = async ({const results: TRenderAsset[][][] = [];for (const ch of chunks) {- const result = await Promise.all(- ch.map((assetsForFrame) => {- return Promise.all(- assetsForFrame.map((a) => {- return downloadAndMapAssetsToFileUrl({- renderAsset: a,- onDownload,- downloadMap,- indent,- logLevel,- });- }),- );- }),- );+ const assetPromises = ch.map((frame) => {+ const frameAssetPromises = frame.assets.map((a) => {+ return downloadAndMapAssetsToFileUrl({+ renderAsset: a,+ onDownload,+ downloadMap,+ indent,+ logLevel,+ });+ });+ return Promise.all(frameAssetPromises);+ });+ const result = await Promise.all(assetPromises);results.push(result);}diff --git a/packages/renderer/src/assets/download-map.ts b/packages/renderer/src/assets/download-map.tsindex 9f396084ec..9146813517 100644--- a/packages/renderer/src/assets/download-map.ts+++ b/packages/renderer/src/assets/download-map.ts@@ -1,8 +1,8 @@import fs, {mkdirSync} from 'node:fs';import path from 'node:path';-import type {TRenderAsset} from 'remotion/no-react';import {deleteDirectory} from '../delete-directory';import {OffthreadVideoServerEmitter} from '../offthread-video-server';+import type {FrameAndAssets} from '../render-frames';import {tmpDir} from '../tmp-dir';import type {RenderMediaOnDownload} from './download-and-map-assets-to-file';@@ -46,12 +46,13 @@ export type DownloadMap = {};export type RenderAssetInfo = {- assets: TRenderAsset[][];+ assets: FrameAndAssets[];imageSequenceName: string;firstFrameIndex: number;downloadMap: DownloadMap;- compositionStart: number;- chunkStart: number;+ chunkLengthInSeconds: number;+ trimLeftOffset: number;+ trimRightOffset: number;};const makeAndReturn = (dir: string, name: string) => {diff --git a/packages/renderer/src/calculate-ffmpeg-filters.ts b/packages/renderer/src/calculate-ffmpeg-filters.tsindex f743987a0f..f5f0458382 100644--- a/packages/renderer/src/calculate-ffmpeg-filters.ts+++ b/packages/renderer/src/calculate-ffmpeg-filters.ts@@ -1,72 +1,45 @@import {flattenVolumeArray} from './assets/flatten-volume-array';import type {MediaAsset} from './assets/types';-import {getClosestAlignedTime} from './combine-audio';-import {DEFAULT_SAMPLE_RATE} from './sample-rate';import type {FilterWithoutPaddingApplied} from './stringify-ffmpeg-filter';import {stringifyFfmpegFilter} from './stringify-ffmpeg-filter';export const calculateFfmpegFilter = ({asset,fps,- durationInFrames,channels,assetDuration,- forSeamlessAacConcatenation,- compositionStart,- chunkStart,+ trimLeftOffset,+ trimRightOffset,+ chunkLengthInSeconds,}: {asset: MediaAsset;fps: number;- durationInFrames: number;channels: number;assetDuration: number | null;- forSeamlessAacConcatenation: boolean;- compositionStart: number;- chunkStart: number;+ trimLeftOffset: number;+ trimRightOffset: number;+ chunkLengthInSeconds: number;}): FilterWithoutPaddingApplied | null => {if (channels === 0) {return null;}- const realLeftEnd = chunkStart - compositionStart;- const realRightEnd = realLeftEnd + durationInFrames / fps;-- const aacAdjustedLeftEnd = Math.max(- 0,- getClosestAlignedTime(realLeftEnd) - 2 * (1024 / DEFAULT_SAMPLE_RATE),- );- const aacAdjustedRightEnd =- getClosestAlignedTime(realRightEnd) + 2 * (1024 / DEFAULT_SAMPLE_RATE);-- const aacAdjustedLeft = forSeamlessAacConcatenation- ? aacAdjustedLeftEnd - realLeftEnd- : 0;- const aacAdjustedRight = forSeamlessAacConcatenation- ? aacAdjustedRightEnd - realRightEnd- : 0;-- const normalTrimLeft = (asset.trimLeft * asset.playbackRate) / fps;- const normalTrimRight =- ((asset.trimLeft + asset.duration) * asset.playbackRate) / fps;-- const assetTrimLeft = forSeamlessAacConcatenation- ? normalTrimLeft + aacAdjustedLeft- : normalTrimLeft;- const assetTrimRight = forSeamlessAacConcatenation- ? normalTrimRight + aacAdjustedRight- : normalTrimRight;+ const trimLeft = (asset.trimLeft * asset.playbackRate) / fps + trimLeftOffset;+ const trimRight =+ ((asset.trimLeft + asset.duration) * asset.playbackRate) / fps ++ trimRightOffset;return stringifyFfmpegFilter({channels,startInVideo: asset.startInVideo,- trimLeft: assetTrimLeft,- trimRight: assetTrimRight,+ trimLeft,+ trimRight,volume: flattenVolumeArray(asset.volume),fps,playbackRate: asset.playbackRate,- durationInFrames,assetDuration,allowAmplificationDuringRender: asset.allowAmplificationDuringRender,toneFrequency: asset.toneFrequency,+ chunkLengthInSeconds,});};diff --git a/packages/renderer/src/compress-audio.ts b/packages/renderer/src/compress-audio.tsindex 335a9ca314..20fce1eed2 100644--- a/packages/renderer/src/compress-audio.ts+++ b/packages/renderer/src/compress-audio.ts@@ -18,7 +18,7 @@ export const compressAudio = async ({cancelSignal,inName,onProgress,- expectedFrames,+ chunkLengthInSeconds,fps,}: {audioCodec: AudioCodec;@@ -30,7 +30,7 @@ export const compressAudio = async ({cancelSignal: CancelSignal | undefined;inName: string;onProgress: (progress: number) => void;- expectedFrames: number;+ chunkLengthInSeconds: number;fps: number;}) => {if (audioCodec === 'pcm-16') {@@ -65,7 +65,7 @@ export const compressAudio = async ({if (parsed === undefined) {Log.verbose({indent, logLevel}, utf8);} else {- onProgress(parsed / expectedFrames);+ onProgress(parsed / (chunkLengthInSeconds * fps));}});diff --git a/packages/renderer/src/create-audio.ts b/packages/renderer/src/create-audio.tsindex d630a01664..da8c0ad56f 100644--- a/packages/renderer/src/create-audio.ts+++ b/packages/renderer/src/create-audio.ts@@ -1,5 +1,4 @@import path from 'path';-import type {TRenderAsset} from 'remotion/no-react';import {calculateAssetPositions} from './assets/calculate-asset-positions';import {convertAssetsToFileUrls} from './assets/convert-assets-to-file-urls';import type {RenderMediaOnDownload} from './assets/download-and-map-assets-to-file';@@ -15,13 +14,19 @@ import {mergeAudioTrack} from './merge-audio-track';import type {AudioCodec} from './options/audio-codec';import {getExtensionFromAudioCodec} from './options/audio-codec';import {preprocessAudioTrack} from './preprocess-audio-track';+import type {FrameAndAssets} from './render-frames';import {truthy} from './truthy';+export type SeamlessAudioInfo = {+ chunkLengthInSeconds: number;+ trimLeftOffset: number;+ trimRightOffset: number;+};+export const createAudio = async ({assets,onDownload,fps,- expectedFrames,logLevel,onProgress,downloadMap,@@ -31,14 +36,13 @@ export const createAudio = async ({audioBitrate,audioCodec,cancelSignal,- forSeamlessAacConcatenation,- compositionStart,- chunkStart,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}: {- assets: TRenderAsset[][];+ assets: FrameAndAssets[];onDownload: RenderMediaOnDownload | undefined;fps: number;- expectedFrames: number;logLevel: LogLevel;onProgress: (progress: number) => void;downloadMap: DownloadMap;@@ -48,9 +52,9 @@ export const createAudio = async ({audioBitrate: string | null;audioCodec: AudioCodec;cancelSignal: CancelSignal | undefined;- forSeamlessAacConcatenation: boolean;- compositionStart: number;- chunkStart: number;+ chunkLengthInSeconds: number;+ trimLeftOffset: number;+ trimRightOffset: number;}): Promise<string> => {const fileUrlAssets = await convertAssetsToFileUrls({assets,@@ -91,20 +95,19 @@ export const createAudio = async ({const result = await preprocessAudioTrack({outName: filterFile,asset,- expectedFrames,fps,downloadMap,indent,logLevel,binariesDirectory,cancelSignal,- forSeamlessAacConcatenation,onProgress: (progress) => {preprocessProgress[index] = progress;updateProgress();},- compositionStart,- chunkStart,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,});preprocessProgress[index] = 1;updateProgress();@@ -134,7 +137,7 @@ export const createAudio = async ({mergeProgress = progress;updateProgress();},- expectedFrames,+ chunkLengthInSeconds,});await compressAudio({@@ -146,7 +149,7 @@ export const createAudio = async ({inName: merged,outName,cancelSignal,- expectedFrames,+ chunkLengthInSeconds,fps,onProgress: (progress) => {compressProgress = progress;diff --git a/packages/renderer/src/create-silent-audio.ts b/packages/renderer/src/create-silent-audio.tsindex 072df149f7..6063a7e0f1 100644--- a/packages/renderer/src/create-silent-audio.ts+++ b/packages/renderer/src/create-silent-audio.ts@@ -4,14 +4,14 @@ import type {CancelSignal} from './make-cancel-signal';import {DEFAULT_SAMPLE_RATE} from './sample-rate';export const createSilentAudio = async ({- numberOfSeconds,outName,indent,logLevel,binariesDirectory,cancelSignal,+ chunkLengthInSeconds,}: {- numberOfSeconds: number;+ chunkLengthInSeconds: number;outName: string;indent: boolean;logLevel: LogLevel;@@ -28,7 +28,7 @@ export const createSilentAudio = async ({'-c:a','pcm_s16le','-t',- String(numberOfSeconds),+ String(chunkLengthInSeconds),'-ar',String(DEFAULT_SAMPLE_RATE),outName,diff --git a/packages/renderer/src/get-extra-frames-to-capture.ts b/packages/renderer/src/get-extra-frames-to-capture.tsnew file mode 100644index 0000000000..679efcbbe3--- /dev/null+++ b/packages/renderer/src/get-extra-frames-to-capture.ts@@ -0,0 +1,96 @@+// For seamless AAC concatenation, we need to capture a bit of extra audio on both sides+// to later align the audio correctly. This function calculates the exact frames to capture.++import {getClosestAlignedTime} from './combine-audio';+import {DEFAULT_SAMPLE_RATE} from './sample-rate';++type ReturnType = {+ extraFramesToCaptureAssets: number[];+ trimLeftOffset: number;+ trimRightOffset: number;+ chunkLengthInSeconds: number;+};++export const getExtraFramesToCapture = ({+ compositionStart,+ realFrameRange,+ fps,+ forSeamlessAacConcatenation,+}: {+ fps: number;+ compositionStart: number;+ realFrameRange: [number, number];+ forSeamlessAacConcatenation: boolean;+}): ReturnType => {+ if (!forSeamlessAacConcatenation) {+ return {+ extraFramesToCaptureAssets: [],+ chunkLengthInSeconds: (realFrameRange[1] - realFrameRange[0] + 1) / fps,+ trimLeftOffset: 0,+ trimRightOffset: 0,+ };+ }++ const chunkStart = realFrameRange[0] / fps;++ if (chunkStart < compositionStart) {+ throw new Error('chunkStart may not be below compositionStart');+ }++ const realLeftEnd = chunkStart - compositionStart;+ if (realLeftEnd < 0) {+ throw new Error('chunkStat - compositionStart may not be below 0');+ }++ const realRightEnd =+ realLeftEnd + (realFrameRange[1] - realFrameRange[0] + 1) / fps;++ const aacAdjustedLeftEnd = Math.max(+ 0,+ getClosestAlignedTime(realLeftEnd) - 2 * (1024 / DEFAULT_SAMPLE_RATE),+ );+ const aacAdjustedRightEnd =+ getClosestAlignedTime(realRightEnd) + 2 * (1024 / DEFAULT_SAMPLE_RATE);++ const startTimeWithoutOffset = Math.floor(aacAdjustedLeftEnd * fps);++ // TODO: Prevent floating point issues by dividing and then multiplying by FPS+ const startFrame = startTimeWithoutOffset + compositionStart * fps;++ const trimLeftOffset =+ (aacAdjustedLeftEnd * fps - startTimeWithoutOffset) / fps;++ const endFrame =+ Math.ceil(aacAdjustedRightEnd * fps) + compositionStart * fps;++ const trimRightOffset =+ (aacAdjustedRightEnd * fps - Math.ceil(aacAdjustedRightEnd * fps)) / fps;++ const extraFramesToCaptureAudioOnly = new Array(+ realFrameRange[0] - startFrame,+ )+ .fill(true)+ .map((_, f) => {+ return f + startFrame;+ });++ const extraFramesToCaptureAudioOnlyBackend = new Array(+ endFrame - realFrameRange[1] - 1,+ )+ .fill(true)+ .map((_, f) => {+ return f + realFrameRange[1] + 1;+ });++ const chunkLengthInSeconds = aacAdjustedRightEnd - aacAdjustedLeftEnd;++ return {+ extraFramesToCaptureAssets: [+ ...extraFramesToCaptureAudioOnly,+ ...extraFramesToCaptureAudioOnlyBackend,+ ],+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ };+};diff --git a/packages/renderer/src/merge-audio-track.ts b/packages/renderer/src/merge-audio-track.tsindex f32011fb2a..694682d3cd 100644--- a/packages/renderer/src/merge-audio-track.ts+++ b/packages/renderer/src/merge-audio-track.ts@@ -26,7 +26,7 @@ type Options = {cancelSignal: CancelSignal | undefined;onProgress: (progress: number) => void;fps: number;- expectedFrames: number;+ chunkLengthInSeconds: number;};const mergeAudioTrackUnlimited = async ({@@ -40,14 +40,12 @@ const mergeAudioTrackUnlimited = async ({cancelSignal,onProgress,fps,- expectedFrames,+ chunkLengthInSeconds,}: Options): Promise<void> => {- const numberOfSeconds = Number((expectedFrames / fps).toFixed(3));-if (files.length === 0) {await createSilentAudio({outName,- numberOfSeconds,+ chunkLengthInSeconds,indent,logLevel,binariesDirectory,@@ -81,7 +79,7 @@ const mergeAudioTrackUnlimited = async ({const chunkOutname = path.join(tempPath, `chunk-${i}.wav`);await mergeAudioTrack({files: chunkFiles,- expectedFrames,+ chunkLengthInSeconds,outName: chunkOutname,downloadMap,remotionRoot,@@ -119,7 +117,7 @@ const mergeAudioTrackUnlimited = async ({callProgress();},fps,- expectedFrames,+ chunkLengthInSeconds,});return;} finally {@@ -158,7 +156,7 @@ const mergeAudioTrackUnlimited = async ({if (parsed === undefined) {Log.verbose({indent, logLevel}, utf8);} else {- onProgress(parsed / expectedFrames);+ onProgress(parsed / (chunkLengthInSeconds * fps));}});diff --git a/packages/renderer/src/options/options-map.ts b/packages/renderer/src/options/options-map.tsindex aa666f9dd9..92a5963cc9 100644--- a/packages/renderer/src/options/options-map.ts+++ b/packages/renderer/src/options/options-map.ts@@ -44,7 +44,6 @@ export const optionsMap = {audioCodec: audioCodecOption,},stitchFramesToVideo: {- forSeamlessAacConcatenation: forSeamlessAacConcatenationOption,separateAudioTo: separateAudioOption,},renderStill: {@@ -67,6 +66,7 @@ export const optionsMap = {binariesDirectory: binariesDirectoryOption,},renderFrames: {+ forSeamlessAacConcatenation: forSeamlessAacConcatenationOption,offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytesOption,jpegQuality: jpegQualityOption,logLevel: logLevelOption,diff --git a/packages/renderer/src/preprocess-audio-track.ts b/packages/renderer/src/preprocess-audio-track.tsindex 0f6335bd70..55f9174703 100644--- a/packages/renderer/src/preprocess-audio-track.ts+++ b/packages/renderer/src/preprocess-audio-track.ts@@ -16,16 +16,15 @@ import type {ProcessedTrack} from './stringify-ffmpeg-filter';type Options = {outName: string;asset: MediaAsset;- expectedFrames: number;fps: number;downloadMap: DownloadMap;indent: boolean;logLevel: LogLevel;binariesDirectory: string | null;cancelSignal: CancelSignal | undefined;- forSeamlessAacConcatenation: boolean;- compositionStart: number;- chunkStart: number;+ chunkLengthInSeconds: number;+ trimLeftOffset: number;+ trimRightOffset: number;onProgress: (progress: number) => void;};@@ -37,17 +36,16 @@ export type PreprocessedAudioTrack = {const preprocessAudioTrackUnlimited = async ({outName,asset,- expectedFrames,fps,downloadMap,indent,logLevel,binariesDirectory,cancelSignal,- forSeamlessAacConcatenation,onProgress,- compositionStart,- chunkStart,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}: Options): Promise<PreprocessedAudioTrack | null> => {const {channels, duration} = await getAudioChannelsAndDuration({downloadMap,@@ -60,13 +58,12 @@ const preprocessAudioTrackUnlimited = async ({const filter = calculateFfmpegFilter({asset,- durationInFrames: expectedFrames,fps,channels,assetDuration: duration,- forSeamlessAacConcatenation,- compositionStart,- chunkStart,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,});if (filter === null) {@@ -108,7 +105,7 @@ const preprocessAudioTrackUnlimited = async ({if (parsed === undefined) {Log.verbose({indent, logLevel}, utf8);} else {- onProgress(parsed / expectedFrames);+ onProgress(parsed / (chunkLengthInSeconds * fps));}});diff --git a/packages/renderer/src/render-frames.ts b/packages/renderer/src/render-frames.tsindex 2ee092e4db..332c83ab40 100644--- a/packages/renderer/src/render-frames.ts+++ b/packages/renderer/src/render-frames.ts@@ -1,7 +1,9 @@import fs from 'node:fs';import path from 'node:path';import {performance} from 'perf_hooks';-import type {TRenderAsset, VideoConfig} from 'remotion/no-react';+// eslint-disable-next-line no-restricted-imports+import type {TAsset} from 'remotion';+import type {VideoConfig} from 'remotion/no-react';import {NoReactInternals} from 'remotion/no-react';import type {RenderMediaOnDownload} from './assets/download-and-map-assets-to-file';import {downloadAndMapAssetsToFileUrl} from './assets/download-and-map-assets-to-file';@@ -24,6 +26,7 @@ import {findRemotionRoot} from './find-closest-package-json';import type {FrameRange} from './frame-range';import {getActualConcurrency} from './get-concurrency';import {getFramesToRender} from './get-duration-from-frame-range';+import {getExtraFramesToCapture} from './get-extra-frames-to-capture';import type {CountType} from './get-frame-padded-index';import {getFilePadLength,@@ -136,6 +139,11 @@ type InnerRenderFramesOptions = {compositionStart: number;} & ToOptions<typeof optionsMap.renderFrames>;+export type FrameAndAssets = {+ frame: number;+ assets: TAsset[];+};+export type RenderFramesOptions = {onStart: (data: OnStartData) => void;onFrameUpdate: (@@ -210,6 +218,7 @@ const innerRenderFrames = async ({indent,parallelEncodingEnabled,compositionStart,+ forSeamlessAacConcatenation,}: Omit<InnerRenderFramesOptions,'offthreadVideoCacheSizeInBytes'@@ -229,6 +238,18 @@ const innerRenderFrames = async ({frameRange,);+ const {+ extraFramesToCaptureAssets,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ } = getExtraFramesToCapture({+ fps: composition.fps,+ compositionStart,+ realFrameRange,+ forSeamlessAacConcatenation,+ });+const framesToRender = getFramesToRender(realFrameRange, everyNthFrame);const lastFrame = framesToRender[framesToRender.length - 1];@@ -341,9 +362,9 @@ const innerRenderFrames = async ({parallelEncoding: parallelEncodingEnabled,});- const assets: TRenderAsset[][] = new Array(framesToRender.length).fill(- undefined,- );+ const assets: FrameAndAssets[] = new Array(+ framesToRender.length + extraFramesToCaptureAssets.length,+ ).fill(undefined);let stopped = false;cancelSignal?.(() => {stopped = true;@@ -358,6 +379,7 @@ const innerRenderFrames = async ({width,height,compId,+ assetsOnly,}: {frame: number;index: number;@@ -365,6 +387,7 @@ const innerRenderFrames = async ({width: number;height: number;compId: string;+ assetsOnly: boolean;}) => {const pool = await poolPromise;const freePage = await pool.acquire();@@ -423,7 +446,7 @@ const innerRenderFrames = async ({frame,freePage,height,- imageFormat,+ imageFormat: assetsOnly ? 'none' : imageFormat,output: path.join(frameDir,getFrameOutputFileName({@@ -443,7 +466,7 @@ const innerRenderFrames = async ({compositor,timeoutInMilliseconds,});- if (onFrameBuffer) {+ if (onFrameBuffer && !assetsOnly) {if (!buffer) {throw new Error('unexpected null buffer');}@@ -454,9 +477,18 @@ const innerRenderFrames = async ({stopPerfMeasure(id);const compressedAssets = collectedAssets.map((asset) =>- compressAsset(assets.filter(truthy).flat(1), asset),+ compressAsset(+ assets+ .filter(truthy)+ .map((a) => a.assets)+ .flat(2),+ asset,+ ),);- assets[index] = compressedAssets;+ assets.push({+ assets: compressedAssets,+ frame,+ });compressedAssets.forEach((renderAsset) => {downloadAndMapAssetsToFileUrl({renderAsset,@@ -470,14 +502,17 @@ const innerRenderFrames = async ({);});});- framesRendered++;- onFrameUpdate?.(framesRendered, frame, performance.now() - startTime);+ if (!assetsOnly) {+ framesRendered++;+ onFrameUpdate?.(framesRendered, frame, performance.now() - startTime);+ }+cleanupPageError();freePage.off('error', errorCallbackOnFrame);pool.release(freePage);};- const renderFrame = (frame: number, index: number) => {+ const renderFrame = (frame: number, index: number, assetsOnly: boolean) => {return new Promise<void>((resolve, reject) => {renderFrameWithOptionToReject({frame,@@ -486,6 +521,7 @@ const innerRenderFrames = async ({width: composition.width,height: composition.height,compId: composition.id,+ assetsOnly,}).then(() => {resolve();@@ -501,15 +537,17 @@ const innerRenderFrames = async ({index,retriesLeft,attempt,+ assetsOnly,}: {frame: number;index: number;retriesLeft: number;attempt: number;+ assetsOnly: boolean;}) => {try {await Promise.race([- renderFrame(frame, index),+ renderFrame(frame, index, assetsOnly),new Promise((_, reject) => {cancelSignal?.(() => {reject(new Error(cancelErrorMessages.renderFrames));@@ -554,38 +592,45 @@ const innerRenderFrames = async ({index,retriesLeft: retriesLeft - 1,attempt: attempt + 1,+ assetsOnly,});}};const progress = Promise.all(- framesToRender.map((frame, index) =>- renderFrameAndRetryTargetClose({- frame,- index,- retriesLeft: MAX_RETRIES_PER_FRAME,- attempt: 1,- }),- ),+ [...framesToRender, ...extraFramesToCaptureAssets]+ .sort()+ .map((frame, index) =>+ renderFrameAndRetryTargetClose({+ frame,+ index,+ retriesLeft: MAX_RETRIES_PER_FRAME,+ attempt: 1,+ assetsOnly: extraFramesToCaptureAssets.includes(frame),+ }),+ ),);const happyPath = progress.then(() => {const firstFrameIndex = countType === 'from-zero' ? 0 : framesToRender[0];const returnValue: RenderFramesOutput = {assetsInfo: {- assets,+ assets: assets.sort((a, b) => {+ return a.frame - b.frame;+ }),imageSequenceName: path.join(frameDir,`element-%0${filePadLength}d.${imageFormat}`,),firstFrameIndex,downloadMap,- chunkStart:- frameRange === null ? 0 : realFrameRange[0] / composition.fps,- compositionStart,+ trimLeftOffset,+ trimRightOffset,+ chunkLengthInSeconds,},frameCount: framesToRender.length,};+ console.log(returnValue.assetsInfo.assets);return returnValue;});@@ -627,6 +672,7 @@ const internalRenderFramesRaw = ({offthreadVideoCacheSizeInBytes,parallelEncodingEnabled,binariesDirectory,+ forSeamlessAacConcatenation,compositionStart,}: InternalRenderFramesOptions): Promise<RenderFramesOutput> => {validateDimension(@@ -753,6 +799,7 @@ const internalRenderFramesRaw = ({serializedResolvedPropsWithCustomSchema,parallelEncodingEnabled,binariesDirectory,+ forSeamlessAacConcatenation,compositionStart,});}),@@ -898,7 +945,7 @@ export const renderFrames = (offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytes ?? null,parallelEncodingEnabled: false,binariesDirectory: binariesDirectory ?? null,- // TODO: In the future, introduce this as a public API when launching the distributed rendering APIcompositionStart: 0,+ forSeamlessAacConcatenation: false,});};diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex 1a706cb712..3391526a68 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -628,6 +628,7 @@ const internalRenderMediaRaw = ({parallelEncodingEnabled: parallelEncoding,binariesDirectory,compositionStart,+ forSeamlessAacConcatenation,});return renderFramesProc;@@ -694,7 +695,6 @@ const internalRenderMediaRaw = ({colorSpace,binariesDirectory,separateAudioTo,- forSeamlessAacConcatenation,}),stitchStart,]);diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.tsindex cf86fbec6d..120505c814 100644--- a/packages/renderer/src/stitch-frames-to-video.ts+++ b/packages/renderer/src/stitch-frames-to-video.ts@@ -134,7 +134,6 @@ const innerStitchFramesToVideo = async (colorSpace,binariesDirectory,separateAudioTo,- forSeamlessAacConcatenation,}: InternalStitchFramesToVideoOptions,remotionRoot: string,): Promise<ReturnType> => {@@ -246,8 +245,6 @@ const innerStitchFramesToVideo = async (});validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);- const expectedFrames = assetsInfo.assets.length;-const updateProgress = (muxProgress: number) => {onProgress?.(muxProgress);};@@ -258,7 +255,7 @@ const innerStitchFramesToVideo = async (assets: assetsInfo.assets,onDownload,fps,- expectedFrames,+ chunkLengthInSeconds: assetsInfo.chunkLengthInSeconds,logLevel,onProgress: () => updateProgress(0),downloadMap: assetsInfo.downloadMap,@@ -268,9 +265,8 @@ const innerStitchFramesToVideo = async (audioBitrate,audioCodec: resolvedAudioCodec,cancelSignal: cancelSignal ?? undefined,- forSeamlessAacConcatenation,- compositionStart: assetsInfo.compositionStart,- chunkStart: assetsInfo.chunkStart,+ trimLeftOffset: assetsInfo.trimLeftOffset,+ trimRightOffset: assetsInfo.trimRightOffset,}): null;@@ -294,7 +290,7 @@ const innerStitchFramesToVideo = async (}cpSync(audio, outputLocation ?? (tempFile as string));- onProgress?.(expectedFrames);+ onProgress?.(Math.round(assetsInfo.chunkLengthInSeconds * fps));deleteDirectory(path.dirname(audio));const file = await new Promise<Buffer | null>((resolve, reject) => {@@ -393,7 +389,7 @@ const innerStitchFramesToVideo = async (// Example repo: https://github.com/JonnyBurger/ffmpeg-repro (access can be given upon request)if (parsed !== undefined) {// If two times in a row the finishing frame is logged, we quit the render- if (parsed === expectedFrames) {+ if (parsed === assetsInfo.assets.length) {if (isFinished) {task.stdin?.write('q');} else {@@ -502,7 +498,6 @@ export const stitchFramesToVideo = ({colorSpace,binariesDirectory,separateAudioTo,- forSeamlessAacConcatenation,}: StitchFramesToVideoOptions): Promise<Buffer | null> => {return internalStitchFramesToVideo({assetsInfo,@@ -535,6 +530,5 @@ export const stitchFramesToVideo = ({colorSpace: colorSpace ?? 'default',binariesDirectory: binariesDirectory ?? null,separateAudioTo: separateAudioTo ?? null,- forSeamlessAacConcatenation: forSeamlessAacConcatenation ?? false,});};diff --git a/packages/renderer/src/stringify-ffmpeg-filter.ts b/packages/renderer/src/stringify-ffmpeg-filter.tsindex 509180b707..434f21643b 100644--- a/packages/renderer/src/stringify-ffmpeg-filter.ts+++ b/packages/renderer/src/stringify-ffmpeg-filter.ts@@ -21,10 +21,10 @@ export const stringifyFfmpegFilter = ({volume,fps,playbackRate,- durationInFrames,assetDuration,allowAmplificationDuringRender,toneFrequency,+ chunkLengthInSeconds,}: {trimLeft: number;trimRight: number;@@ -32,11 +32,11 @@ export const stringifyFfmpegFilter = ({startInVideo: number;volume: AssetVolume;fps: number;- durationInFrames: number;playbackRate: number;assetDuration: number | null;allowAmplificationDuringRender: boolean;toneFrequency: number | null;+ chunkLengthInSeconds: number;}): FilterWithoutPaddingApplied | null => {const startInVideoSeconds = startInVideo / fps;@@ -59,15 +59,13 @@ export const stringifyFfmpegFilter = ({// Avoid setting filters if possible, as combining them can create noise- const chunkLength = durationInFrames / fps;-const actualTrimRight = assetDuration? Math.min(trimRight, assetDuration): trimRight;const audibleDuration = (actualTrimRight - trimLeft) / playbackRate;- const padAtEnd = chunkLength - audibleDuration - startInVideoSeconds;+ const padAtEnd = chunkLengthInSeconds - audibleDuration - startInVideoSeconds;return {filter:diff --git a/packages/renderer/src/test/extra-frames-to-capture.test.ts b/packages/renderer/src/test/extra-frames-to-capture.test.tsnew file mode 100644index 0000000000..8c05aaf238--- /dev/null+++ b/packages/renderer/src/test/extra-frames-to-capture.test.ts@@ -0,0 +1,54 @@+import {expect, test} from 'vitest';+import {getExtraFramesToCapture} from '../get-extra-frames-to-capture';++test('Extra frames to capture 0', () => {+ const {extraFramesToCaptureAssets} = getExtraFramesToCapture({+ fps: 30,+ compositionStart: 0,+ realFrameRange: [0, 30],+ forSeamlessAacConcatenation: true,+ });++ expect(extraFramesToCaptureAssets).toEqual([31]);+});++test('Extra frames to capture 1', () => {+ const {extraFramesToCaptureAssets} = getExtraFramesToCapture({+ fps: 30,+ compositionStart: 3.3333333333333335,+ realFrameRange: [100, 116],+ forSeamlessAacConcatenation: true,+ });++ expect(extraFramesToCaptureAssets).toEqual([117, 118]);+});++test('Extra frames to capture 2', () => {+ const {extraFramesToCaptureAssets} = getExtraFramesToCapture({+ fps: 30,+ compositionStart: 3.3333333333333335,+ realFrameRange: [151, 167],+ forSeamlessAacConcatenation: true,+ });++ expect(extraFramesToCaptureAssets).toEqual([149, 150, 168, 169]);+});++test('Extra frames to capture 3', () => {+ const {+ extraFramesToCaptureAssets,+ trimLeftOffset,+ trimRightOffset,+ chunkLengthInSeconds,+ } = getExtraFramesToCapture({+ fps: 30,+ compositionStart: 3.3333333333333335,+ realFrameRange: [134, 150],+ forSeamlessAacConcatenation: true,+ });++ expect(extraFramesToCaptureAssets).toEqual([132, 133, 151, 152]);+ expect(trimLeftOffset).toEqual(0.021333333333333114);+ expect(trimRightOffset).toEqual(-0.017333333333333437);+ expect(chunkLengthInSeconds).toEqual(0.6613333333333333);+});diff --git a/packages/renderer/src/test/ffmpeg-filters.test.ts b/packages/renderer/src/test/ffmpeg-filters.test.tsindex 26f2290bb8..1938ae9af7 100644--- a/packages/renderer/src/test/ffmpeg-filters.test.ts+++ b/packages/renderer/src/test/ffmpeg-filters.test.ts@@ -1,11 +1,12 @@import {expect, test} from 'vitest';import type {MediaAsset} from '../assets/types';import {calculateFfmpegFilter} from '../calculate-ffmpeg-filters';+import {getExtraFramesToCapture} from '../get-extra-frames-to-capture';const src ='/var/folders/hl/p8pg9kw15dbg3l7dbpn0scc80000gn/T/react-motion-graphicsh871Pk/1fe4a495500e1658167982183be07231.mp4';-const asset: MediaAsset = {+const baseAsset: MediaAsset = {type: 'video',src,duration: 20,@@ -18,139 +19,220 @@ const asset: MediaAsset = {toneFrequency: null,};+const expandAsset = ({+ base,+ extraFramesToCaptureAssets,+}: {+ base: MediaAsset;+ extraFramesToCaptureAssets: number[];+}): MediaAsset => {+ return {+ ...base,+ duration: base.duration + extraFramesToCaptureAssets.length,+ };+};+test('Should create a basic filter correctly', () => {expect(calculateFfmpegFilter({fps: 30,asset: {- ...asset,+ ...baseAsset,duration: 200,},- durationInFrames: 100,channels: 1,assetDuration: 10,- forSeamlessAacConcatenation: true,- compositionStart: 0,- chunkStart: 0,+ chunkLengthInSeconds: 3.3333,+ trimLeftOffset: 0,+ trimRightOffset: 0,}),).toEqual({filter:- '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=0us:6720000us[a0]',+ '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=0us:6666666.666666667us[a0]',pad_end: null,pad_start: null,});});test('Trim the end', () => {+ const {+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ extraFramesToCaptureAssets,+ } = getExtraFramesToCapture({+ compositionStart: 0,+ forSeamlessAacConcatenation: true,+ fps: 30,+ realFrameRange: [0, 99],+ });++ expect(chunkLengthInSeconds).toEqual(3.3706666666666667);+ expect(trimLeftOffset).toEqual(0);+ expect(trimRightOffset).toEqual(-0.02933333333333318);++ const padding = Math.round((chunkLengthInSeconds - 0.704) * 48000);+expect(calculateFfmpegFilter({fps: 30,- asset,- durationInFrames: 100,+ asset: expandAsset({extraFramesToCaptureAssets, base: baseAsset}),channels: 1,- assetDuration: 10,- forSeamlessAacConcatenation: true,- compositionStart: 0,- chunkStart: 0,+ assetDuration: 100,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}),).toEqual({filter:- '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=0us:703999.9999999999us[a0]',- pad_end: 'apad=pad_len=126208',+ '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=0us:704000.0000000001us[a0]',+ pad_end: 'apad=pad_len=' + padding,pad_start: null,});});test('Should handle trim correctly', () => {+ const {+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ extraFramesToCaptureAssets,+ } = getExtraFramesToCapture({+ compositionStart: 0,+ forSeamlessAacConcatenation: true,+ fps: 30,+ realFrameRange: [0, 99],+ });++ expect(chunkLengthInSeconds).toEqual(3.3706666666666667);+ expect(trimRightOffset).toEqual(-0.02933333333333318);+expect(calculateFfmpegFilter({fps: 30,- asset: {- ...asset,- trimLeft: 10,- },- durationInFrames: 100,+ asset: expandAsset({+ base: {+ ...baseAsset,+ trimLeft: 10,+ },+ extraFramesToCaptureAssets,+ }),channels: 1,assetDuration: 10,- forSeamlessAacConcatenation: true,- compositionStart: 0,- chunkStart: 0,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}),).toEqual({filter:- '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=298666.6666666666us:1045333.3333333333us[a0]',- pad_end: 'apad=pad_len=124160',+ '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=333333.3333333333us:1037333.3333333335us[a0]',+ pad_end: 'apad=pad_len=128000',pad_start: null,});});test('Should add padding if audio is too short', () => {+ const {trimLeftOffset, trimRightOffset} = getExtraFramesToCapture({+ compositionStart: 0,+ forSeamlessAacConcatenation: false,+ fps: 30,+ realFrameRange: [0, 99],+ });++ const padding = Math.round((3.3333 - 2 / 3) * 48000);+expect(calculateFfmpegFilter({fps: 30,asset: {- ...asset,+ ...baseAsset,trimLeft: 10,},- durationInFrames: 100,channels: 1,assetDuration: 1,- forSeamlessAacConcatenation: false,- compositionStart: 0,- chunkStart: 0,+ chunkLengthInSeconds: 3.3333,+ trimLeftOffset,+ trimRightOffset,}),).toEqual({filter:'[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=333333.3333333333us:1000000us[a0]',- pad_end: 'apad=pad_len=128000',+ pad_end: `apad=pad_len=${padding}`,pad_start: null,});});test('Should handle delay correctly', () => {+ const {+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ extraFramesToCaptureAssets,+ } = getExtraFramesToCapture({+ compositionStart: 0,+ forSeamlessAacConcatenation: true,+ fps: 30,+ realFrameRange: [0, 99],+ });+expect(calculateFfmpegFilter({fps: 30,- asset: {- ...asset,- trimLeft: 10,- startInVideo: 80,- },-- durationInFrames: 100,+ asset: expandAsset({+ base: {+ ...baseAsset,+ trimLeft: 10,+ startInVideo: 80,+ },+ extraFramesToCaptureAssets,+ }),channels: 1,assetDuration: 1,- forSeamlessAacConcatenation: true,- compositionStart: 0,- chunkStart: 0,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}),).toEqual({filter:- '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=298666.6666666666us:1000000us[a0]',- pad_end: null,+ '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=333333.3333333333us:1000000us[a0]',+ pad_end: 'apad=pad_len=1792',pad_start: 'adelay=2667|2667',});});test('Should offset multiple channels', () => {+ const {+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ extraFramesToCaptureAssets,+ } = getExtraFramesToCapture({+ compositionStart: 0,+ forSeamlessAacConcatenation: true,+ fps: 30,+ realFrameRange: [0, 99],+ });+expect(calculateFfmpegFilter({fps: 30,- asset: {- ...asset,- trimLeft: 10,- startInVideo: 80,- },- durationInFrames: 100,+ asset: expandAsset({+ base: {+ ...baseAsset,+ trimLeft: 10,+ startInVideo: 80,+ },+ extraFramesToCaptureAssets,+ }),channels: 3,assetDuration: 1,- forSeamlessAacConcatenation: true,- compositionStart: 0,- chunkStart: 0,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}),).toEqual({filter:- '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=298666.6666666666us:1000000us[a0]',- pad_end: null,+ '[0:a]aformat=sample_fmts=s32:sample_rates=48000,atrim=333333.3333333333us:1000000us[a0]',+ pad_end: 'apad=pad_len=1792',pad_start: 'adelay=2667|2667|2667|2667',});});@@ -159,27 +241,42 @@ test('Should calculate pad correctly with a lot of playbackRate', () => {const naturalDurationInSeconds = 1000 / 30 / 16;const expectedPadLength =(2000 / 30) * 48000 - naturalDurationInSeconds * 48000;++ const {+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,+ extraFramesToCaptureAssets,+ } = getExtraFramesToCapture({+ compositionStart: 0,+ forSeamlessAacConcatenation: false,+ fps: 30,+ realFrameRange: [0, 1999],+ });+expect(calculateFfmpegFilter({fps: 30,- asset: {- type: 'video',- src,- duration: 1000,- volume: 1,- id: '1',- trimLeft: 0,- startInVideo: 0,- playbackRate: 16,- allowAmplificationDuringRender: false,- toneFrequency: null,- },- durationInFrames: 2000,+ asset: expandAsset({+ base: {+ type: 'video',+ src,+ duration: 1000,+ volume: 1,+ id: '1',+ trimLeft: 0,+ startInVideo: 0,+ playbackRate: 16,+ allowAmplificationDuringRender: false,+ toneFrequency: null,+ },+ extraFramesToCaptureAssets,+ }),channels: 1,assetDuration: 33.333333,- forSeamlessAacConcatenation: true,- compositionStart: 0,- chunkStart: 0,+ chunkLengthInSeconds,+ trimLeftOffset,+ trimRightOffset,}),).toEqual({filter: