Skip to content

🎥 Make videos programmatically with React

Support tuple output ranges in interpolate

Cursor Agented308774d1aa
diff --git a/packages/core/src/interpolate-keyframed-status.ts b/packages/core/src/interpolate-keyframed-status.ts
index 5cb4942765..ba3af43565 100644
--- a/packages/core/src/interpolate-keyframed-status.ts
+++ b/packages/core/src/interpolate-keyframed-status.ts
@@ -8,6 +8,8 @@ import type {
CanUpdateSequencePropStatusKeyframed,
} from './use-schema.js';
+type InterpolateKeyframedStatusResult = number | string | number[] | null;
+
const easingToFn = (e: CanUpdateSequencePropStatusEasing): EasingFunction => {
if (e === 'linear') {
return Easing.linear;
@@ -22,7 +24,7 @@ export const interpolateKeyframedStatus = ({
}: {
frame: number;
status: CanUpdateSequencePropStatusKeyframed;
-}): number | string | null => {
+}): InterpolateKeyframedStatusResult => {
const {keyframes, easing, clamping, interpolationFunction} = status;
if (keyframes.length === 0) {
return null;
@@ -55,12 +57,17 @@ export const interpolateKeyframedStatus = ({
}
try {
- return interpolate(frame, inputRange, outputs as (number | string)[], {
- easing: easing.map(easingToFn),
- extrapolateLeft: clamping.left,
- extrapolateRight: clamping.right,
- posterize: status.posterize,
- });
+ return interpolate(
+ frame,
+ inputRange,
+ outputs as (number | string | number[])[],
+ {
+ easing: easing.map(easingToFn),
+ extrapolateLeft: clamping.left,
+ extrapolateRight: clamping.right,
+ posterize: status.posterize,
+ },
+ );
} catch {
return null;
}
diff --git a/packages/core/src/interpolate.ts b/packages/core/src/interpolate.ts
index 6f9eed34ac..8ad720077d 100644
--- a/packages/core/src/interpolate.ts
+++ b/packages/core/src/interpolate.ts
@@ -33,6 +33,12 @@ type ParsedStringInterpolationValue = {
dimensions: number;
};
+type NumericTuple = readonly [number, ...number[]];
+type InterpolateOutputValue = number | string | readonly number[];
+type WidenNumericTuple<T extends readonly number[]> = {
+ readonly [Key in keyof T]: number;
+};
+
const angleUnits = new Set(['deg', 'rad', 'grad', 'turn']);
const lengthUnits = new Set([
'%',
@@ -397,6 +403,62 @@ const interpolateString = ({
});
};
+const validateTupleOutputRange = (
+ outputRange: readonly (readonly unknown[])[],
+): number => {
+ const dimensions = outputRange[0]?.length;
+ if (dimensions === undefined) {
+ throw new Error('outputRange must have at least 1 element');
+ }
+
+ if (dimensions === 0) {
+ throw new TypeError('outputRange tuples must contain at least 1 number');
+ }
+
+ for (const output of outputRange) {
+ if (output.length !== dimensions) {
+ throw new TypeError(
+ `outputRange tuples must all have the same length, but got ${dimensions} and ${output.length}`,
+ );
+ }
+
+ for (const value of output) {
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ throw new TypeError(
+ `outputRange tuples must contain only finite numbers, but got [${output.join(
+ ',',
+ )}]`,
+ );
+ }
+ }
+ }
+
+ return dimensions;
+};
+
+const interpolateTuple = ({
+ input,
+ inputRange,
+ outputRange,
+ options,
+}: {
+ input: number;
+ inputRange: readonly number[];
+ outputRange: readonly (readonly unknown[])[];
+ options: InterpolateOptions | undefined;
+}): number[] => {
+ const dimensions = validateTupleOutputRange(outputRange);
+
+ return new Array(dimensions).fill(true).map((_, axis) =>
+ interpolateNumber({
+ input,
+ inputRange,
+ outputRange: outputRange.map((output) => output[axis] as number),
+ options,
+ }),
+ );
+};
+
function checkValidInputRange(arr: readonly number[]) {
for (let i = 1; i < arr.length; ++i) {
if (!(arr[i] > arr[i - 1])) {
@@ -488,18 +550,30 @@ export function interpolate(
outputRange: readonly string[],
options?: InterpolateOptions,
): string;
+export function interpolate<const Tuple extends NumericTuple>(
+ input: number,
+ inputRange: readonly number[],
+ outputRange: readonly Tuple[],
+ options?: InterpolateOptions,
+): WidenNumericTuple<Tuple>;
export function interpolate(
input: number,
inputRange: readonly number[],
- outputRange: readonly (number | string)[],
+ outputRange: readonly (readonly number[])[],
options?: InterpolateOptions,
-): number | string;
+): number[];
export function interpolate(
input: number,
inputRange: readonly number[],
- outputRange: readonly (number | string)[],
+ outputRange: readonly (number | string | readonly number[])[],
options?: InterpolateOptions,
-): number | string {
+): number | string | number[];
+export function interpolate(
+ input: number,
+ inputRange: readonly number[],
+ outputRange: readonly InterpolateOutputValue[],
+ options?: InterpolateOptions,
+): number | string | number[] {
if (typeof input === 'undefined') {
throw new Error('input can not be undefined');
}
@@ -553,9 +627,13 @@ export function interpolate(
return interpolateString({input, inputRange, outputRange, options});
}
+ if (outputRange.every((output) => Array.isArray(output))) {
+ return interpolateTuple({input, inputRange, outputRange, options});
+ }
+
if (!outputRange.every((output) => typeof output === 'number')) {
throw new TypeError(
- 'outputRange must contain only numbers, or supported scale, translate, and rotate strings',
+ 'outputRange must contain only numbers, numeric tuples, or supported scale, translate, and rotate strings',
);
}
diff --git a/packages/core/src/test/interpolate-keyframed-status.test.ts b/packages/core/src/test/interpolate-keyframed-status.test.ts
index 52e423c2fe..f9c8b4e625 100644
--- a/packages/core/src/test/interpolate-keyframed-status.test.ts
+++ b/packages/core/src/test/interpolate-keyframed-status.test.ts
@@ -20,6 +20,25 @@ test('interpolates linear numeric keyframes', () => {
expect(result).toBe(50);
});
+test('interpolates linear tuple keyframes', () => {
+ const result = interpolateKeyframedStatus({
+ frame: 30,
+ status: {
+ status: 'keyframed',
+ codeValue: undefined,
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: [0, 0.5]},
+ {frame: 60, value: [1, 0.5]},
+ ],
+ easing: ['linear'],
+ clamping: {left: 'extend', right: 'extend'},
+ posterize: undefined,
+ },
+ });
+ expect(result).toEqual([0.5, 0.5]);
+});
+
test('sorts keyframes before interpolating numeric values', () => {
const result = interpolateKeyframedStatus({
frame: 75,
diff --git a/packages/core/src/test/interpolate.test.ts b/packages/core/src/test/interpolate.test.ts
index d5c1515e79..fdcba9cfbb 100644
--- a/packages/core/src/test/interpolate.test.ts
+++ b/packages/core/src/test/interpolate.test.ts
@@ -206,6 +206,129 @@ test('Posterize option must be a positive finite number', () => {
}, /posterize must be a positive finite number, but got NaN/);
});
+test('Interpolates numeric tuples component-wise', () => {
+ const start: readonly [number, number] = interpolate(
+ 30,
+ [0, 60],
+ [
+ [0, 0.5],
+ [1, 0.5],
+ ],
+ );
+ expect(start).toEqual([0.5, 0.5]);
+
+ expect(
+ interpolate(
+ 15,
+ [0, 30],
+ [
+ [1, 2, 3],
+ [2, 4, 6],
+ ],
+ ),
+ ).toEqual([1.5, 3, 4.5]);
+
+ expect(
+ interpolate(
+ 75,
+ [0, 50, 100],
+ [
+ [0, 0],
+ [1, 1],
+ [0, 0.5],
+ ],
+ ),
+ ).toEqual([0.5, 0.75]);
+});
+
+test('Interpolates numeric tuples with one keyframe', () => {
+ expect(interpolate(999, [0], [[0.2, 0.8]])).toEqual([0.2, 0.8]);
+});
+
+test('Numeric tuple interpolation supports easing, extrapolation and posterization', () => {
+ expect(
+ interpolate(
+ 15,
+ [0, 30],
+ [
+ [0, 0],
+ [100, 50],
+ ],
+ {easing: Easing.quad},
+ ),
+ ).toEqual([25, 12.5]);
+ expect(
+ interpolate(
+ 45,
+ [0, 30],
+ [
+ [0, 0],
+ [100, 50],
+ ],
+ {extrapolateRight: 'clamp'},
+ ),
+ ).toEqual([100, 50]);
+ expect(
+ interpolate(
+ 19,
+ [0, 30],
+ [
+ [0, 0],
+ [90, 30],
+ ],
+ {posterize: 10},
+ ),
+ ).toEqual([30, 10]);
+});
+
+test('Numeric tuple interpolation throws on type and length mismatches', () => {
+ expectToThrow(() => interpolate(0, [0, 1], [[0, 0.5], 1]), /numeric tuples/);
+ expectToThrow(
+ () => interpolate(0, [0, 1], [[0, 0.5], '1px']),
+ /supported scale, translate, and rotate strings/,
+ );
+ expectToThrow(
+ () =>
+ interpolate(
+ 0,
+ [0, 1],
+ [
+ [0, 0.5],
+ [1, 0.5, 0],
+ ],
+ ),
+ /outputRange tuples must all have the same length/,
+ );
+ expectToThrow(
+ () =>
+ interpolate(
+ 0,
+ [0, 1],
+ [
+ [NaN, 0.5],
+ [1, 0.5],
+ ],
+ ),
+ /outputRange tuples must contain only finite numbers/,
+ );
+ expectToThrow(
+ () =>
+ interpolate(
+ 0,
+ [0, 1],
+ [
+ [Infinity, 0.5],
+ [1, 0.5],
+ ],
+ ),
+ /outputRange tuples must contain only finite numbers/,
+ );
+ expectToThrow(
+ () => interpolate(0, [0, 1], [[], [1, 0.5]]),
+ /outputRange tuples must contain at least 1 number/,
+ );
+});
+
test('Interpolates scale strings', () => {
expect(interpolate(15, [0, 30], ['1', '2'])).toBe('1.5');
expect(interpolate(15, [0, 30], ['1 2', '2 4'])).toBe('1.5 3');
diff --git a/packages/docs/docs/interpolate.mdx b/packages/docs/docs/interpolate.mdx
index 1153d010f9..12a87c4a16 100644
--- a/packages/docs/docs/interpolate.mdx
+++ b/packages/docs/docs/interpolate.mdx
@@ -140,6 +140,31 @@ All values in one interpolation must have the same type.
For each component, units must match.
For missing dimensions, CSS defaults are used: scale defaults to `1`, translate and rotate default to `0`.
+## Example: Numeric tuples<AvailableFrom v="4.0.473" />
+
+`outputRange` may contain numeric tuples.
+Each tuple must contain the same number of numbers.
+
+```tsx twoslash title="MyComposition.tsx"
+import {interpolate, useCurrentFrame} from 'remotion';
+
+export const MyComposition: React.FC = () => {
+ const frame = useCurrentFrame();
+ const start: readonly [number, number] = interpolate(
+ frame,
+ [0, 60],
+ [
+ [0, 0.5],
+ [1, 0.5],
+ ],
+ );
+
+ return <div>{start.join(', ')}</div>;
+};
+```
+
+This is useful for UV coordinates such as effect `start` and `end` values.
+
## API
Takes four arguments: