Skip to content

🎥 Make videos programmatically with React

Fix splitting clips with timing like trimBefore={4 * fps}

Cursor Agente1db82b67338
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 19819870f1..061497b7bd 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1588,6 +1588,7 @@ export const createBrowserStudioOperations = ({
node: {filePath: sequence.fileName, nodePath: sequence.nodePath},
frame: sequence.splitFrame,
sequenceKeys: sequence.sequenceKeys,
+ videoConfig: sequence.videoConfigValues ?? undefined,
})),
});
const nodePathMutation = controller.applyMutation({
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 8ac19b74e3..12c8b54dff 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -896,6 +896,7 @@ registerRoot(Root);`,
nodePath: subscription.nodePath.nodePath,
sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
splitFrame: 10,
+ videoConfigValues: subscription.nodePath.videoConfigValues,
},
],
});
@@ -913,6 +914,7 @@ registerRoot(Root);`,
nodePath: subscription.nodePath.nodePath,
sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
splitFrame: 15,
+ videoConfigValues: subscription.nodePath.videoConfigValues,
},
],
});
diff --git a/packages/codemods/src/split-jsx-sequence.ts b/packages/codemods/src/split-jsx-sequence.ts
index f0acd8d9f2..e419518125 100644
--- a/packages/codemods/src/split-jsx-sequence.ts
+++ b/packages/codemods/src/split-jsx-sequence.ts
@@ -17,7 +17,11 @@ import {
} from '@remotion/studio-shared';
import type {namedTypes as AstNamedTypes} from 'ast-types';
import * as recast from 'recast';
-import type {SequenceNodePath} from 'remotion';
+import type {
+ SequenceNodePath,
+ VideoConfigNumericExpression,
+ VideoConfigValues,
+} from 'remotion';
import {
findJsxElementPathForDeletion,
getJsxElementTagLabel,
@@ -29,6 +33,14 @@ import {
import {printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';
+import {
+ parseVideoConfigNumericExpression,
+ updateVideoConfigNumericExpression,
+} from './sequence-props/video-config-numeric-expression';
+import {
+ getVideoConfigIdentifierValues,
+ type VideoConfigIdentifierValues,
+} from './sequence-props/video-config-values';
import {applySourceEdits} from './source-edits';
import {
getEndOfLine,
@@ -43,25 +55,35 @@ const normalizeComputedTiming = (value: number): number => {
return Number.isInteger(value) ? value : Number(value.toPrecision(15));
};
+// `null` means the prop is absent.
type SequenceTiming = {
- from: number;
- durationInFrames: number;
- trimBefore: number;
+ from: VideoConfigNumericExpression | null;
+ durationInFrames: VideoConfigNumericExpression | null;
+ trimBefore: VideoConfigNumericExpression | null;
playbackRate: number;
- hasFrom: boolean;
- hasDurationInFrames: boolean;
- hasTrimBefore: boolean;
};
const jsxId = (name: string) => ({type: 'JSXIdentifier' as const, name});
-const numericAttribute = (name: string, value: number): JSXAttribute => ({
+const numericAttribute = ({
+ name,
+ value,
+ expression,
+}: {
+ name: string;
+ value: number;
+ expression: VideoConfigNumericExpression | null;
+}): JSXAttribute => ({
type: 'JSXAttribute',
name: jsxId(name),
value: {
type: 'JSXExpressionContainer',
expression:
- value === Infinity ? b.identifier('Infinity') : b.numericLiteral(value),
+ value === Infinity
+ ? b.identifier('Infinity')
+ : expression
+ ? updateVideoConfigNumericExpression({expression, value})
+ : b.numericLiteral(value),
} as JSXExpressionContainer,
});
@@ -78,9 +100,13 @@ const getAttributeName = (
return attribute.name.name;
};
-const getStaticNumber = (
- attribute: JSXElement['openingElement']['attributes'][number],
-): number | null => {
+const getStaticNumber = ({
+ attribute,
+ videoConfigValues,
+}: {
+ attribute: JSXElement['openingElement']['attributes'][number];
+ videoConfigValues: VideoConfigIdentifierValues;
+}): VideoConfigNumericExpression | null => {
if (attribute.type !== 'JSXAttribute') {
return null;
}
@@ -91,7 +117,7 @@ const getStaticNumber = (
if (attribute.value.type === 'StringLiteral') {
const parsed = Number(attribute.value.value);
- return Number.isFinite(parsed) ? parsed : null;
+ return Number.isFinite(parsed) ? {type: 'literal', value: parsed} : null;
}
if (attribute.value.type !== 'JSXExpressionContainer') {
@@ -99,33 +125,31 @@ const getStaticNumber = (
}
const {expression} = attribute.value;
- if (expression.type === 'NumericLiteral') {
- return expression.value;
- }
-
- if (
- expression.type === 'UnaryExpression' &&
- expression.operator === '-' &&
- expression.argument.type === 'NumericLiteral'
- ) {
- return -expression.argument.value;
+ if (expression.type === 'JSXEmptyExpression') {
+ return null;
}
if (expression.type === 'Identifier' && expression.name === 'Infinity') {
- return Infinity;
+ return {type: 'literal', value: Infinity};
}
- return null;
+ return parseVideoConfigNumericExpression({
+ node: expression,
+ videoConfigValues,
+ });
};
-const readSequenceTiming = (element: JSXElement): SequenceTiming => {
- let from = 0;
- let durationInFrames = Infinity;
- let trimBefore = 0;
+const readSequenceTiming = ({
+ element,
+ videoConfigValues,
+}: {
+ element: JSXElement;
+ videoConfigValues: VideoConfigIdentifierValues;
+}): SequenceTiming => {
+ let from: VideoConfigNumericExpression | null = null;
+ let durationInFrames: VideoConfigNumericExpression | null = null;
+ let trimBefore: VideoConfigNumericExpression | null = null;
let playbackRate = 1;
- let hasFrom = false;
- let hasDurationInFrames = false;
- let hasTrimBefore = false;
for (const attribute of element.openingElement.attributes) {
const name = getAttributeName(attribute);
@@ -142,32 +166,29 @@ const readSequenceTiming = (element: JSXElement): SequenceTiming => {
continue;
}
- const value = getStaticNumber(attribute);
+ const value = getStaticNumber({attribute, videoConfigValues});
if (value === null) {
throw new Error(`Cannot split sequence with dynamic ${name}`);
}
if (name === 'from') {
from = value;
- hasFrom = true;
}
if (name === 'durationInFrames') {
durationInFrames = value;
- hasDurationInFrames = true;
}
if (name === 'trimBefore') {
trimBefore = value;
- hasTrimBefore = true;
}
if (name === 'playbackRate') {
- if (!Number.isFinite(value) || value <= 0) {
+ if (!Number.isFinite(value.value) || value.value <= 0) {
throw new Error('Cannot split sequence with invalid playbackRate');
}
- playbackRate = value;
+ playbackRate = value.value;
}
}
@@ -176,9 +197,6 @@ const readSequenceTiming = (element: JSXElement): SequenceTiming => {
durationInFrames,
trimBefore,
playbackRate,
- hasFrom,
- hasDurationInFrames,
- hasTrimBefore,
};
};
@@ -186,11 +204,13 @@ const setNumericAttribute = ({
element,
name,
value,
+ expression,
omitIfMissing,
}: {
element: JSXElement;
name: string;
value: number | null;
+ expression: VideoConfigNumericExpression | null;
omitIfMissing: boolean;
}) => {
const {
@@ -208,7 +228,7 @@ const setNumericAttribute = ({
return;
}
- const next = numericAttribute(name, value);
+ const next = numericAttribute({name, value, expression});
if (index === -1) {
attributes.push(next);
} else {
@@ -401,6 +421,7 @@ export type SplitJsxSequenceItem = {
nodePath: SequenceNodePath;
sequenceKeys: string[];
splitFrame: number;
+ videoConfigValues: VideoConfigValues | null;
};
export const splitJsxSequences = ({
@@ -423,55 +444,63 @@ export const splitJsxSequences = ({
const ast = parseAst(input);
const capturedNodePaths = captureJsxNodePaths(ast);
- const targets = splits.map(({nodePath, sequenceKeys, splitFrame}) => {
- if (!Number.isFinite(splitFrame)) {
- throw new Error('Split frame must be finite');
- }
-
- const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
- if (!jsxPath) {
- throw new Error(
- 'Could not find a JSX sequence at the specified location to split',
- );
- }
+ const targets = splits.map(
+ ({nodePath, sequenceKeys, splitFrame, videoConfigValues}) => {
+ if (!Number.isFinite(splitFrame)) {
+ throw new Error('Split frame must be finite');
+ }
- const jsxElement = jsxPath.node as JSXElement;
- const tagName = getSplittableSequenceTagName(jsxElement);
- if (!hasSequenceTimingTraits(sequenceKeys)) {
- throw new Error(`<${tagName}> cannot be split`);
- }
+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!jsxPath) {
+ throw new Error(
+ 'Could not find a JSX sequence at the specified location to split',
+ );
+ }
- const timing = readSequenceTiming(jsxElement);
- const contentDuration = timing.durationInFrames;
- const timelineDuration = contentDuration / timing.playbackRate;
- const finiteEnd =
- timelineDuration === Infinity ? Infinity : timing.from + timelineDuration;
+ const jsxElement = jsxPath.node as JSXElement;
+ const tagName = getSplittableSequenceTagName(jsxElement);
+ if (!hasSequenceTimingTraits(sequenceKeys)) {
+ throw new Error(`<${tagName}> cannot be split`);
+ }
- if (splitFrame <= timing.from) {
- throw new Error('Cannot split at or before the sequence start');
- }
+ const timing = readSequenceTiming({
+ element: jsxElement,
+ videoConfigValues: getVideoConfigIdentifierValues({
+ ast,
+ videoConfigValues,
+ }),
+ });
+ const from = timing.from?.value ?? 0;
+ const contentDuration = timing.durationInFrames?.value ?? Infinity;
+ const timelineDuration = contentDuration / timing.playbackRate;
+ const finiteEnd =
+ timelineDuration === Infinity ? Infinity : from + timelineDuration;
+
+ if (splitFrame <= from) {
+ throw new Error('Cannot split at or before the sequence start');
+ }
- if (splitFrame >= finiteEnd) {
- throw new Error('Cannot split at or after the sequence end');
- }
+ if (splitFrame >= finiteEnd) {
+ throw new Error('Cannot split at or after the sequence end');
+ }
- return {
- contentDuration,
- jsxElement,
- jsxPath,
- splitFrame,
- timing,
- };
- });
+ return {
+ contentDuration,
+ from,
+ jsxElement,
+ jsxPath,
+ splitFrame,
+ timing,
+ };
+ },
+ );
const nodeLabels: string[] = [];
const logLines: number[] = [];
const sourceEdits = targets.map(
- ({contentDuration, jsxElement, jsxPath, splitFrame, timing}) => {
+ ({contentDuration, from, jsxElement, jsxPath, splitFrame, timing}) => {
const right = cloneJsxElement(jsxElement);
// Match Studio's numeric dragger precision while retaining fractional frames.
- const leftTimelineDuration = normalizeComputedTiming(
- splitFrame - timing.from,
- );
+ const leftTimelineDuration = normalizeComputedTiming(splitFrame - from);
const leftDuration = normalizeComputedTiming(
leftTimelineDuration * timing.playbackRate,
);
@@ -480,32 +509,36 @@ export const splitJsxSequences = ({
? Infinity
: normalizeComputedTiming(contentDuration - leftDuration);
const rightTrimBefore = normalizeComputedTiming(
- timing.trimBefore + leftDuration,
+ (timing.trimBefore?.value ?? 0) + leftDuration,
);
setNumericAttribute({
element: jsxElement,
name: 'durationInFrames',
value: leftDuration,
+ expression: timing.durationInFrames,
omitIfMissing: false,
});
setNumericAttribute({
element: right,
name: 'from',
value: splitFrame,
+ expression: timing.from,
omitIfMissing: false,
});
setNumericAttribute({
element: right,
name: 'durationInFrames',
value: rightDuration === Infinity ? null : rightDuration,
+ expression: timing.durationInFrames,
omitIfMissing: false,
});
setNumericAttribute({
element: right,
name: 'trimBefore',
value: rightTrimBefore === 0 ? null : rightTrimBefore,
- omitIfMissing: !timing.hasTrimBefore && rightTrimBefore === 0,
+ expression: timing.trimBefore,
+ omitIfMissing: timing.trimBefore === null && rightTrimBefore === 0,
});
orderTimingAttributes(jsxElement);
orderTimingAttributes(right);
@@ -557,12 +590,14 @@ export const splitJsxSequence = async ({
nodePath,
sequenceKeys,
splitFrame,
+ videoConfigValues,
prettierConfigOverride,
}: {
input: string;
nodePath: SequenceNodePath;
sequenceKeys: string[];
splitFrame: number;
+ videoConfigValues: VideoConfigValues | null;
prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{
output: string;
@@ -574,7 +609,7 @@ export const splitJsxSequence = async ({
await splitJsxSequences({
input,
prettierConfigOverride,
- splits: [{nodePath, sequenceKeys, splitFrame}],
+ splits: [{nodePath, sequenceKeys, splitFrame, videoConfigValues}],
});
return {
diff --git a/packages/codemods/src/split-sequences.ts b/packages/codemods/src/split-sequences.ts
index b800ba9097..6384545b81 100644
--- a/packages/codemods/src/split-sequences.ts
+++ b/packages/codemods/src/split-sequences.ts
@@ -1,3 +1,4 @@
+import type {VideoConfigValues} from 'remotion';
import type {CodemodProject} from './codemod-project';
import type {DuplicateNodesResult} from './duplicate-nodes';
import {getNodeProps} from './get-node-props';
@@ -12,7 +13,12 @@ import {splitJsxSequences} from './split-jsx-sequence';
export type SplitSequencesOptions<Project extends CodemodProject> = {
project: Project;
- splits: {node: NodeReference; frame: number; sequenceKeys?: string[]}[];
+ splits: {
+ node: NodeReference;
+ frame: number;
+ sequenceKeys?: string[];
+ videoConfig?: VideoConfigValues;
+ }[];
};
export const splitSequences = async <Project extends CodemodProject>({
@@ -46,6 +52,7 @@ export const splitSequences = async <Project extends CodemodProject>({
project,
node: split.node,
keys: ['from', 'durationInFrames', 'trimBefore'],
+ videoConfig: split.videoConfig,
});
if (
Object.values(status.props).some((prop) => prop.status !== 'static')
@@ -74,7 +81,7 @@ export const splitSequences = async <Project extends CodemodProject>({
filePath,
...(await splitJsxSequences({
input: project.files[filePath],
- splits: group.map(({node, frame, sequenceKeys}) => ({
+ splits: group.map(({node, frame, sequenceKeys, videoConfig}) => ({
nodePath: node.nodePath,
splitFrame: frame,
sequenceKeys: sequenceKeys ?? [
@@ -82,6 +89,7 @@ export const splitSequences = async <Project extends CodemodProject>({
'durationInFrames',
'trimBefore',
],
+ videoConfigValues: videoConfig ?? null,
})),
})),
})),
diff --git a/packages/codemods/src/test/split-jsx-sequence.test.ts b/packages/codemods/src/test/split-jsx-sequence.test.ts
index da514c04b6..f1f47fc80c 100644
--- a/packages/codemods/src/test/split-jsx-sequence.test.ts
+++ b/packages/codemods/src/test/split-jsx-sequence.test.ts
@@ -25,6 +25,7 @@ test('splits fractional timing without persisting arithmetic noise', async () =>
nodePath,
sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
splitFrame: 1,
+ videoConfigValues: null,
});
expect(output).toContain('durationInFrames={0.9}');
expect(output).toContain('durationInFrames={0.3}');
@@ -60,6 +61,7 @@ test('splits multiple sibling sequences from the same source snapshot', async ()
nodePath,
sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
splitFrame: 30,
+ videoConfigValues: null,
})),
});
@@ -97,6 +99,7 @@ test('splitting a sped-up sequence preserves its child clock across a fractional
nodePath,
sequenceKeys: ['from', 'durationInFrames', 'trimBefore', 'playbackRate'],
splitFrame: 22.5,
+ videoConfigValues: null,
});
expect(output.replace(/\s+/g, ' ')).toContain(
'from={10} durationInFrames={25} trimBefore={5} playbackRate={2}',
@@ -134,6 +137,7 @@ const split = async (
nodePath: lineColumnToNodePath(input, sequenceLine),
sequenceKeys,
splitFrame,
+ videoConfigValues: null,
});
return output;
@@ -155,6 +159,7 @@ test('splitJsxSequence remaps following JSX siblings', async () => {
nodePath: lineContainingToNodePath(input, 'name="split"'),
sequenceKeys: sequenceTimingKeys,
splitFrame: 30,
+ videoConfigValues: null,
});
expect(nodePathRemappings).toEqual([
@@ -236,6 +241,7 @@ export const Comp = () => {
nodePath: lineContainingToNodePath(input, '<Sequence'),
sequenceKeys: sequenceTimingKeys,
splitFrame: 30,
+ videoConfigValues: null,
});
expect(output).toStartWith(
@@ -261,6 +267,7 @@ const keep = { value : true }
nodePath: lineContainingToNodePath(input, '<Sequence'),
sequenceKeys: sequenceTimingKeys,
splitFrame: 30,
+ videoConfigValues: null,
});
expect(output).toBe(`export const Comp = () => <>
diff --git a/packages/docs/docs/codemods/split-sequences.mdx b/packages/docs/docs/codemods/split-sequences.mdx
index 36023df209..64b3227ca7 100644
--- a/packages/docs/docs/codemods/split-sequences.mdx
+++ b/packages/docs/docs/codemods/split-sequences.mdx
@@ -28,7 +28,7 @@ const result = await splitSequences({
console.log(result);
```
-Adjusts `from`, `durationInFrames`, and `trimBefore`. Timing must be static; dynamic timing and spreads that may override it are rejected. The media file itself is unchanged.
+Adjusts `from`, `durationInFrames`, and `trimBefore`. Timing must be static; dynamic timing and spreads that may override it are rejected. Supported expressions such as `4 * fps` are kept when the new value can be written in the same form exactly. The media file itself is unchanged.
## Options
@@ -48,6 +48,10 @@ The node reference of a Remotion sequence, interactive element, or supported tim
The integer frame at which to split, in the same parent timeline coordinate system as the node's `from` prop. It must be strictly inside the sequence.
+#### videoConfig?<AvailableFrom v="4.0.533" />
+
+The composition's `width`, `height`, `fps`, and `durationInFrames`. Supply these to interpret supported timing expressions using [`useVideoConfig()`](/docs/use-video-config). By default, those runtime values are unknown.
+
## Return value
A promise resolving to an object with the following properties.
diff --git a/packages/studio-server/src/preview-server/routes/split-sequences.ts b/packages/studio-server/src/preview-server/routes/split-sequences.ts
index 752a376948..767ca00643 100644
--- a/packages/studio-server/src/preview-server/routes/split-sequences.ts
+++ b/packages/studio-server/src/preview-server/routes/split-sequences.ts
@@ -55,10 +55,11 @@ export const splitSequencesHandler: ApiHandler<
rootDir: remotionRoot,
},
splits: fileSequences.map(
- ({nodePath, sequenceKeys, splitFrame}) => ({
+ ({nodePath, sequenceKeys, splitFrame, videoConfigValues}) => ({
node: {filePath: absolutePath, nodePath},
sequenceKeys,
frame: splitFrame,
+ videoConfig: videoConfigValues ?? undefined,
}),
),
});
diff --git a/packages/studio-server/src/test/node-path-mutation-routes.test.ts b/packages/studio-server/src/test/node-path-mutation-routes.test.ts
index 88eb32cd03..734331b691 100644
--- a/packages/studio-server/src/test/node-path-mutation-routes.test.ts
+++ b/packages/studio-server/src/test/node-path-mutation-routes.test.ts
@@ -202,6 +202,7 @@ test('JSX structure routes broadcast and return node path mutations before writi
nodePath: lineContainingToNodePath(before, 'name="c"'),
sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
splitFrame: 30,
+ videoConfigValues: null,
},
],
},
diff --git a/packages/studio-server/src/test/split-sequences.test.ts b/packages/studio-server/src/test/split-sequences.test.ts
index 13c2f0ce5d..673d112cb7 100644
--- a/packages/studio-server/src/test/split-sequences.test.ts
+++ b/packages/studio-server/src/test/split-sequences.test.ts
@@ -88,12 +88,14 @@ test('splitSequencesHandler writes success and failure responses', async () => {
nodePath: lineContainingToNodePath(input, 'name="one"'),
sequenceKeys: sequenceTimingKeys,
splitFrame: 30,
+ videoConfigValues: null,
},
{
fileName: entryPoint,
nodePath: lineContainingToNodePath(input, 'name="two"'),
sequenceKeys: sequenceTimingKeys,
splitFrame: 30,
+ videoConfigValues: null,
},
],
},
@@ -156,6 +158,7 @@ test('splitSequencesHandler writes success and failure responses', async () => {
nodePath: lineContainingToNodePath(input, 'name="one"'),
sequenceKeys: sequenceTimingKeys,
splitFrame: 0,
+ videoConfigValues: null,
},
],
},
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index f522330752..4d28151989 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -1017,6 +1017,7 @@ export type SplitSequencesRequestItem = {
nodePath: SequenceNodePath;
sequenceKeys: string[];
splitFrame: number;
+ videoConfigValues: VideoConfigValues | null;
};
export type SplitSequencesRequest = {
diff --git a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
index 0bb6fb9999..e52865fc8b 100644
--- a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
@@ -196,6 +196,7 @@ export const splitTimelineSequencesFromSource = ({
nodePath: nodePath.nodePath,
sequenceKeys: nodePath.sequenceKeys,
splitFrame,
+ videoConfigValues: nodePath.videoConfigValues,
};
}),
})