🎥 Make videos programmatically with React
`@remotion/renderer`: `imageSequencePattern` option for renderFrames()
Jonny Burger0ac6e890625b
diff --git a/packages/cli/src/config/image-sequence-pattern.ts b/packages/cli/src/config/image-sequence-pattern.tsnew file mode 100644index 0000000000..1370d9185d--- /dev/null+++ b/packages/cli/src/config/image-sequence-pattern.ts@@ -0,0 +1,9 @@+let currentImageSequencePattern: string | undefined;++export const setImageSequencePattern = (pattern: string | undefined) => {+ currentImageSequencePattern = pattern;+};++export const getImageSequencePattern = () => {+ return currentImageSequencePattern;+};diff --git a/packages/cli/src/config/index.ts b/packages/cli/src/config/index.tsindex f3bcdb842a..a0e7608c54 100644--- a/packages/cli/src/config/index.ts+++ b/packages/cli/src/config/index.ts@@ -14,6 +14,10 @@ import {setVideoImageFormat,} from './image-format';import {getShouldOutputImageSequence} from './image-sequence';+import {+ getImageSequencePattern,+ setImageSequencePattern,+} from './image-sequence-pattern';import {getOutputLocation} from './output-location';import {defaultOverrideFunction,@@ -500,6 +504,11 @@ declare global {* Prefer lossless audio encoding. Default: false*/readonly setPublicPath: (publicPath: string | null) => void;+ /**+ * Set the pattern for naming image sequence files. Supports [frame] and [ext] replacements.+ * @param pattern The pattern string, e.g. 'frame_[frame].[ext]'.+ */+ readonly setImageSequencePattern: (pattern: string | undefined) => void;}}@@ -674,6 +683,7 @@ export const Config: FlatConfig = {setBinariesDirectory: binariesDirectoryOption.setConfig,setPreferLosslessAudio: preferLosslessOption.setConfig,setPublicPath: publicPathOption.setConfig,+ setImageSequencePattern,setHardwareAcceleration: hardwareAccelerationOption.setConfig,setEnableCrossSiteIsolation: enableCrossSiteIsolationOption.setConfig,};@@ -715,3 +725,5 @@ export const ConfigInternals = {getBufferStateDelayInMilliseconds,getOutputCodecOrUndefined: BrowserSafeApis.getOutputCodecOrUndefined,};++export {getImageSequencePattern, setImageSequencePattern};diff --git a/packages/cli/src/parse-command-line.ts b/packages/cli/src/parse-command-line.tsindex fd308ce13b..2adbc53163 100644--- a/packages/cli/src/parse-command-line.ts+++ b/packages/cli/src/parse-command-line.ts@@ -107,6 +107,7 @@ export type CommandLineOptions = {typeof enableMultiprocessOnLinuxOption>;repro: boolean;+ 'image-sequence-pattern': string;};export const parseCommandLine = () => {@@ -114,6 +115,10 @@ export const parseCommandLine = () => {Config.setPixelFormat(parsedCli['pixel-format']);}+ if (parsedCli['image-sequence-pattern']) {+ Config.setImageSequencePattern(parsedCli['image-sequence-pattern']);+ }+if (parsedCli['browser-executable']) {Config.setBrowserExecutable(parsedCli['browser-executable']);}diff --git a/packages/cli/src/render-flows/render.ts b/packages/cli/src/render-flows/render.tsindex 134175a5ac..158017d19e 100644--- a/packages/cli/src/render-flows/render.ts+++ b/packages/cli/src/render-flows/render.ts@@ -535,6 +535,7 @@ export const renderVideoFlow = async ({onBrowserDownload,onArtifact,chromeMode,+ imageSequencePattern: parsedCli['image-sequence-pattern'],});Log.info({indent, logLevel}, chalk.blue(`â–¶ ${absoluteOutputFile}`));diff --git a/packages/docs/docs/cli/render.mdx b/packages/docs/docs/cli/render.mdxindex 277226d8a5..5e87f3e861 100644--- a/packages/docs/docs/cli/render.mdx+++ b/packages/docs/docs/cli/render.mdx@@ -51,6 +51,17 @@ Inline JSON string isn't supported on Windows shells because it removes the `"`[`jpeg` or `png` - JPEG is faster, but doesn't support transparency.](/docs/config#setvideoimageformat) The default image format is `jpeg` since v1.1.+### `--image-sequence-pattern` <AvailableFrom v="4.0.313" />++[Pattern for naming image sequence files. Supports `[frame]` for the zero-padded frame number and `[ext]` for the file extension.]++**Example:**++```bash+npx remotion render ... --sequence --image-sequence-pattern='frame_[frame]_custom.[ext]'+# Produces: frame_0001_custom.jpeg, frame_0002_custom.jpeg, ...+```+### `--config`<AvailableFrom v="1.2.0" />Specify a location for the Remotion config file.diff --git a/packages/docs/docs/config.mdx b/packages/docs/docs/config.mdxindex 270f85cc2f..d8e2208756 100644--- a/packages/docs/docs/config.mdx+++ b/packages/docs/docs/config.mdx@@ -969,3 +969,21 @@ The old way is deprecated, but will work for the foreseeable future.## See also- [Encoding guide](/docs/encoding)++### setImageSequencePattern(pattern)++Set the pattern for naming image sequence files when rendering an image sequence.++- `[frame]` will be replaced with the zero-padded frame number (e.g. 0001, 0002, ...)+- `[ext]` will be replaced with the image format extension (e.g. jpeg, png)++**Example:**++```js+// remotion.config.ts+import {Config} from 'remotion';++Config.setImageSequencePattern('frame_[frame]_custom.[ext]');+```++This will produce files like `frame_0001_custom.jpeg`, `frame_0002_custom.jpeg`, ...diff --git a/packages/docs/docs/renderer/render-frames.mdx b/packages/docs/docs/renderer/render-frames.mdxindex bb85024f11..bb0160f0a4 100644--- a/packages/docs/docs/renderer/render-frames.mdx+++ b/packages/docs/docs/renderer/render-frames.mdx@@ -95,6 +95,25 @@ _optional since v4.0 - default "jpeg"_- Choose `png` if you want your image sequence to have an alpha channel (for transparency).- Choose `none` if you only want to render audio.+### `imageSequencePattern?` <AvailableFrom v="4.0.313" />++A string pattern for naming the output image sequence files. You can use the following magic replacements:++- `[frame]`: Will be replaced with the zero-padded frame number (e.g. 0001, 0002, ...)+- `[ext]`: Will be replaced with the image format extension (e.g. jpeg, png)++Default: `element-%0[frame]d.[ext]`++**Example:**++```js+renderFrames({+ ...otherOptions,+ imageSequencePattern: 'frame_[frame]_custom.[ext]',+});+// Produces: frame_0001_custom.jpeg, frame_0002_custom.jpeg, ...+```+### `concurrency?`_optional_diff --git a/packages/docs/src/components/VideoPlayerWithControls.tsx b/packages/docs/src/components/VideoPlayerWithControls.tsxindex 3786bdcdf7..b7be248e6e 100644--- a/packages/docs/src/components/VideoPlayerWithControls.tsx+++ b/packages/docs/src/components/VideoPlayerWithControls.tsx@@ -97,6 +97,7 @@ export const VideoPlayerWithControls = forwardRef<);useEffect(() => {+ // @ts-expect-error we don't bother to type itwindow.global_seek_to = (time: number) => {if (videoRef.current) {videoRef.current.currentTime = time;diff --git a/packages/renderer/src/get-frame-padded-index.ts b/packages/renderer/src/get-frame-padded-index.tsindex f60eac69ef..00559c43b3 100644--- a/packages/renderer/src/get-frame-padded-index.ts+++ b/packages/renderer/src/get-frame-padded-index.ts@@ -7,14 +7,16 @@ import type {VideoImageFormat} from './image-format';export type CountType = 'from-zero' | 'actual-frames';-const padIndex = ({- num,- filePadLength,+export const getFrameOutputFileNameFromPattern = ({+ pattern,+ frame,+ ext,}: {- num: number;- filePadLength: number;+ pattern: string;+ frame: string;+ ext: string;}) => {- return String(num).padStart(filePadLength, '0');+ return pattern.replace(/\[frame\]/g, frame).replace(/\[ext\]/g, ext);};export const getFrameOutputFileName = ({@@ -24,6 +26,7 @@ export const getFrameOutputFileName = ({countType,lastFrame,totalFrames,+ pattern,}: {index: number;frame: number;@@ -31,19 +34,28 @@ export const getFrameOutputFileName = ({countType: CountType;lastFrame: number;totalFrames: number;+ pattern?: string;}) => {const filePadLength = getFilePadLength({lastFrame, countType, totalFrames});+ const frameStr =+ countType === 'actual-frames'+ ? String(frame).padStart(filePadLength, '0')+ : String(index).padStart(filePadLength, '0');+ if (pattern) {+ return getFrameOutputFileNameFromPattern({+ pattern,+ frame: frameStr,+ ext: imageFormat,+ });+ }const prefix = 'element';-if (countType === 'actual-frames') {- const paddedIndex = padIndex({filePadLength, num: frame});- return `${prefix}-${paddedIndex}.${imageFormat}`;+ return `${prefix}-${frameStr}.${imageFormat}`;}if (countType === 'from-zero') {- const paddedIndex = padIndex({filePadLength, num: index});- return `${prefix}-${paddedIndex}.${imageFormat}`;+ return `${prefix}-${frameStr}.${imageFormat}`;}throw new TypeError('Unknown count type');diff --git a/packages/renderer/src/options/image-sequence-pattern.tsx b/packages/renderer/src/options/image-sequence-pattern.tsxnew file mode 100644index 0000000000..0fede668ac--- /dev/null+++ b/packages/renderer/src/options/image-sequence-pattern.tsx@@ -0,0 +1,24 @@+import type {AnyRemotionOption} from './option';++const cliFlag = 'image-sequence-pattern' as const;++// Option for --image-sequence-pattern+export const imageSequencePatternOption = {+ name: 'Image Sequence Pattern',+ cliFlag,+ ssrName: 'imageSequencePattern',+ description: () => (+ <>+ Pattern for naming image sequence files. Supports <code>[frame]</code> for+ the zero-padded frame number and <code>[ext]</code> for the file+ extension.+ </>+ ),+ docLink: null,+ type: 'string' as string | null,+ getValue: ({commandLine}) => ({+ value: commandLine[cliFlag] as string,+ source: 'cli',+ }),+ setConfig: () => {},+} satisfies AnyRemotionOption<string | null>;diff --git a/packages/renderer/src/options/options-map.ts b/packages/renderer/src/options/options-map.tsindex ae20912c63..da40e7573c 100644--- a/packages/renderer/src/options/options-map.ts+++ b/packages/renderer/src/options/options-map.ts@@ -11,6 +11,7 @@ import {encodingMaxRateOption} from './encoding-max-rate';import {enforceAudioOption} from './enforce-audio';import {forSeamlessAacConcatenationOption} from './for-seamless-aac-concatenation';import {hardwareAccelerationOption} from './hardware-acceleration';+import {imageSequencePatternOption} from './image-sequence-pattern';import {jpegQualityOption} from './jpeg-quality';import {logLevelOption} from './log-level';import {mutedOption} from './mute';@@ -95,6 +96,7 @@ export const optionsMap = {binariesDirectory: binariesDirectoryOption,onBrowserDownload: onBrowserDownloadOption,chromeMode: chromeModeOption,+ imageSequencePattern: imageSequencePatternOption,},renderMediaOnLambda: {offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytesOption,diff --git a/packages/renderer/src/render-frames.ts b/packages/renderer/src/render-frames.tsindex 90fb6f0d40..8b4ffcb581 100644--- a/packages/renderer/src/render-frames.ts+++ b/packages/renderer/src/render-frames.ts@@ -225,6 +225,7 @@ const innerRenderFrames = async ({forSeamlessAacConcatenation,onArtifact,binariesDirectory,+ imageSequencePattern,}: Omit<InnerRenderFramesOptions,'offthreadVideoCacheSizeInBytes'@@ -400,15 +401,18 @@ const innerRenderFrames = async ({const firstFrameIndex = countType === 'from-zero' ? 0 : framesToRender[0];await Promise.all(downloadPromises);++ const pattern = imageSequencePattern || `element-%0[frame]d.[ext]`;+ const imageSequenceName = pattern+ .replace(/\[frame\]/g, `%0${filePadLength}d`)+ .replace(/\[ext\]/g, imageFormat);+return {assetsInfo: {assets: assets.sort((a, b) => {return a.frame - b.frame;}),- imageSequenceName: path.join(- frameDir,- `element-%0${filePadLength}d.${imageFormat}`,- ),+ imageSequenceName: path.join(frameDir, imageSequenceName),firstFrameIndex,downloadMap,trimLeftOffset,@@ -459,6 +463,7 @@ const internalRenderFramesRaw = ({onArtifact,chromeMode,offthreadVideoThreads,+ imageSequencePattern,}: InternalRenderFramesOptions): Promise<RenderFramesOutput> => {validateDimension(composition.height,@@ -591,6 +596,7 @@ const internalRenderFramesRaw = ({onArtifact,chromeMode,offthreadVideoThreads,+ imageSequencePattern,});}),])@@ -689,6 +695,7 @@ export const renderFrames = (onArtifact,chromeMode,offthreadVideoThreads,+ imageSequencePattern,} = options;if (!composition) {@@ -763,5 +770,6 @@ export const renderFrames = (onArtifact: onArtifact ?? null,chromeMode: chromeMode ?? 'headless-shell',offthreadVideoThreads: offthreadVideoThreads ?? null,+ imageSequencePattern: imageSequencePattern ?? null,});};diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex c957c9d17a..e8de08ecd3 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -678,6 +678,7 @@ const internalRenderMediaRaw = ({onBrowserDownload,onArtifact,chromeMode,+ imageSequencePattern: null,});return renderFramesProc;