Skip to content

🎥 Make videos programmatically with React

new eslint styles

Jonny Burger8412a18f325e
diff --git a/packages/cli/.eslintrc b/packages/cli/.eslintrc
index ab99307a23..f7938fb6da 100644
--- a/packages/cli/.eslintrc
+++ b/packages/cli/.eslintrc
@@ -8,6 +8,7 @@
"patterns": ["@remotion/*/src/*"]
}
],
+ "@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-restricted-imports": [
"error",
{
diff --git a/packages/cloudrun/src/admin/bundle-installer.ts b/packages/cloudrun/src/admin/bundle-installer.ts
index d1158a5338..9fb82d1776 100644
--- a/packages/cloudrun/src/admin/bundle-installer.ts
+++ b/packages/cloudrun/src/admin/bundle-installer.ts
@@ -3,6 +3,15 @@ import {execSync} from 'child_process';
import {copyFileSync, mkdirSync, rmSync} from 'fs';
import path from 'path';
+export const hasGTar = () => {
+ try {
+ const output = execSync('gtar --usage', {});
+ return output.includes('--sort');
+ } catch {
+ return false;
+ }
+};
+
const bundleInstaller = async () => {
const outdir = path.join(__dirname, '..', `build-installer`);
mkdirSync(outdir, {recursive: true});
@@ -56,12 +65,3 @@ const bundleInstaller = async () => {
};
bundleInstaller();
-
-export const hasGTar = () => {
- try {
- const output = execSync('gtar --usage', {});
- return output.includes('--sort');
- } catch {
- return false;
- }
-};
diff --git a/packages/core/src/Composition.tsx b/packages/core/src/Composition.tsx
index 0f0eabe5c4..b26c844f83 100644
--- a/packages/core/src/Composition.tsx
+++ b/packages/core/src/Composition.tsx
@@ -94,6 +94,27 @@ export type StillProps<
CompProps<Props> &
PropsIfHasProps<Schema, Props>;
+export const ClipComposition: React.FC<PropsWithChildren> = ({children}) => {
+ const {clipRegion} = useContext(NativeLayersContext);
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ display: 'flex',
+ flexDirection: 'row',
+ opacity: clipRegion === 'hide' ? 0 : 1,
+ clipPath:
+ clipRegion && clipRegion !== 'hide'
+ ? `polygon(${clipRegion.x}px ${clipRegion.y}px, ${clipRegion.x}px ${
+ clipRegion.height + clipRegion.y
+ }px, ${clipRegion.width + clipRegion.x}px ${
+ clipRegion.height + clipRegion.y
+ }px, ${clipRegion.width + clipRegion.x}px ${clipRegion.y}px)`
+ : undefined,
+ };
+ }, [clipRegion]);
+
+ return <AbsoluteFill style={style}>{children}</AbsoluteFill>;
+};
+
export type CompositionProps<
Schema extends AnyZodObject,
Props extends Record<string, unknown>,
@@ -244,24 +265,3 @@ export const Composition = <
return null;
};
-
-export const ClipComposition: React.FC<PropsWithChildren> = ({children}) => {
- const {clipRegion} = useContext(NativeLayersContext);
- const style: React.CSSProperties = useMemo(() => {
- return {
- display: 'flex',
- flexDirection: 'row',
- opacity: clipRegion === 'hide' ? 0 : 1,
- clipPath:
- clipRegion && clipRegion !== 'hide'
- ? `polygon(${clipRegion.x}px ${clipRegion.y}px, ${clipRegion.x}px ${
- clipRegion.height + clipRegion.y
- }px, ${clipRegion.width + clipRegion.x}px ${
- clipRegion.height + clipRegion.y
- }px, ${clipRegion.width + clipRegion.x}px ${clipRegion.y}px)`
- : undefined,
- };
- }, [clipRegion]);
-
- return <AbsoluteFill style={style}>{children}</AbsoluteFill>;
-};
diff --git a/packages/core/src/ResolveCompositionConfig.tsx b/packages/core/src/ResolveCompositionConfig.tsx
index 997ea7999f..42a735b4ff 100644
--- a/packages/core/src/ResolveCompositionConfig.tsx
+++ b/packages/core/src/ResolveCompositionConfig.tsx
@@ -43,6 +43,10 @@ type VideoConfigState =
error: Error;
};
+export const needsResolution = (composition: AnyComposition) => {
+ return Boolean(composition.calculateMetadata);
+};
+
export const ResolveCompositionConfig: React.FC<
PropsWithChildren<{
children: React.ReactNode;
@@ -232,10 +236,6 @@ export const ResolveCompositionConfig: React.FC<
);
};
-export const needsResolution = (composition: AnyComposition) => {
- return Boolean(composition.calculateMetadata);
-};
-
export const useResolvedVideoConfig = (
preferredCompositionId: string | null,
): VideoConfigState | null => {
diff --git a/packages/core/src/audio/Audio.tsx b/packages/core/src/audio/Audio.tsx
index 6501193910..19cd141a4d 100644
--- a/packages/core/src/audio/Audio.tsx
+++ b/packages/core/src/audio/Audio.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-use-before-define */
import React, {forwardRef, useCallback, useContext} from 'react';
import {getAbsoluteSrc} from '../absolute-src.js';
import {calculateLoopDuration} from '../calculate-loop.js';
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 86dfa62196..fcb28c281f 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -89,13 +89,12 @@ import {
RemotionContextProvider,
useRemotionContexts,
} from './wrap-remotion-context.js';
-const Timeline = TimelinePosition;
// Mark them as Internals so use don't assume this is public
// API and are less likely to use it
export const Internals = {
useUnsafeVideoConfig,
- Timeline,
+ Timeline: TimelinePosition,
CompositionManager,
SequenceManager,
RemotionRoot,
@@ -159,7 +158,7 @@ export const Internals = {
export type {
TComposition,
- Timeline,
+ TimelinePosition as Timeline,
TCompMetadata,
TSequence,
TRenderAsset as TAsset,
diff --git a/packages/core/src/resolve-video-config.ts b/packages/core/src/resolve-video-config.ts
index 1d10cfaf78..416c2de2d4 100644
--- a/packages/core/src/resolve-video-config.ts
+++ b/packages/core/src/resolve-video-config.ts
@@ -6,6 +6,54 @@ import {validateDurationInFrames} from './validation/validate-duration-in-frames
import {validateFps} from './validation/validate-fps.js';
import type {VideoConfig} from './video-config.js';
+const validateCalculated = ({
+ composition,
+ calculated,
+}: {
+ composition: TCompMetadataWithCalcFunction<
+ AnyZodObject,
+ Record<string, unknown>
+ >;
+ calculated: CalcMetadataReturnType<Record<string, unknown>> | null;
+}) => {
+ const calculateMetadataErrorLocation = `calculated by calculateMetadata() for the composition "${composition.id}"`;
+ const defaultErrorLocation = `of the "<Composition />" component with the id "${composition.id}"`;
+
+ const width = calculated?.width ?? composition.width ?? undefined;
+
+ validateDimension(
+ width,
+ 'width',
+ calculated?.width ? calculateMetadataErrorLocation : defaultErrorLocation,
+ );
+
+ const height = calculated?.height ?? composition.height ?? undefined;
+
+ validateDimension(
+ height,
+ 'height',
+ calculated?.height ? calculateMetadataErrorLocation : defaultErrorLocation,
+ );
+
+ const fps = calculated?.fps ?? composition.fps ?? null;
+
+ validateFps(
+ fps,
+ calculated?.fps ? calculateMetadataErrorLocation : defaultErrorLocation,
+ false,
+ );
+
+ const durationInFrames =
+ calculated?.durationInFrames ?? composition.durationInFrames ?? null;
+
+ validateDurationInFrames(durationInFrames, {
+ allowFloats: false,
+ component: `of the "<Composition />" component with the id "${composition.id}"`,
+ });
+
+ return {width, height, fps, durationInFrames};
+};
+
export const resolveVideoConfig = ({
composition,
editorProps: editorPropsOrUndefined,
@@ -80,51 +128,3 @@ export const resolveVideoConfig = ({
props: calculatedProm.props ?? composition.defaultProps ?? {},
};
};
-
-const validateCalculated = ({
- composition,
- calculated,
-}: {
- composition: TCompMetadataWithCalcFunction<
- AnyZodObject,
- Record<string, unknown>
- >;
- calculated: CalcMetadataReturnType<Record<string, unknown>> | null;
-}) => {
- const calculateMetadataErrorLocation = `calculated by calculateMetadata() for the composition "${composition.id}"`;
- const defaultErrorLocation = `of the "<Composition />" component with the id "${composition.id}"`;
-
- const width = calculated?.width ?? composition.width ?? undefined;
-
- validateDimension(
- width,
- 'width',
- calculated?.width ? calculateMetadataErrorLocation : defaultErrorLocation,
- );
-
- const height = calculated?.height ?? composition.height ?? undefined;
-
- validateDimension(
- height,
- 'height',
- calculated?.height ? calculateMetadataErrorLocation : defaultErrorLocation,
- );
-
- const fps = calculated?.fps ?? composition.fps ?? null;
-
- validateFps(
- fps,
- calculated?.fps ? calculateMetadataErrorLocation : defaultErrorLocation,
- false,
- );
-
- const durationInFrames =
- calculated?.durationInFrames ?? composition.durationInFrames ?? null;
-
- validateDurationInFrames(durationInFrames, {
- allowFloats: false,
- component: `of the "<Composition />" component with the id "${composition.id}"`,
- });
-
- return {width, height, fps, durationInFrames};
-};
diff --git a/packages/core/src/test/freeze.test.tsx b/packages/core/src/test/freeze.test.tsx
index 10356fdb9e..bf19c8ebdd 100644
--- a/packages/core/src/test/freeze.test.tsx
+++ b/packages/core/src/test/freeze.test.tsx
@@ -12,6 +12,11 @@ import {useCurrentFrame} from '../use-current-frame.js';
import {expectToThrow} from './expect-to-throw.js';
import {WrapSequenceContext} from './wrap-sequence-context.js';
+const TestComponent: React.FC = () => {
+ const frame = useCurrentFrame();
+ return <div>{frame}</div>;
+};
+
describe('Prop validation', () => {
test('It should throw if Freeze has string as frame prop value', () => {
expectToThrow(
@@ -89,11 +94,6 @@ const WithSequence: React.FC = () => {
);
};
-const TestComponent: React.FC = () => {
- const frame = useCurrentFrame();
- return <div>{frame}</div>;
-};
-
describe('Integration tests', () => {
test('Basic test', () => {
const {container} = renderForFrame(0, <Basic />);
diff --git a/packages/core/src/test/nested-sequences.test.tsx b/packages/core/src/test/nested-sequences.test.tsx
index 97cddf74ee..7dd921fb5d 100644
--- a/packages/core/src/test/nested-sequences.test.tsx
+++ b/packages/core/src/test/nested-sequences.test.tsx
@@ -12,24 +12,53 @@ import {WrapSequenceContext} from './wrap-sequence-context.js';
afterEach(cleanup);
+const getForFrame = (frame: number, content: React.ReactNode) => {
+ const {queryByText} = render(
+ <WrapSequenceContext>
+ <TimelineContext.Provider
+ value={{
+ frame: {
+ 'my-comp': frame,
+ },
+ playing: false,
+ rootId: 'hi',
+ imperativePlaying: {
+ current: false,
+ },
+ playbackRate: 1,
+ setPlaybackRate: () => {
+ throw new Error('playback rate');
+ },
+ audioAndVideoTags: {
+ current: [],
+ },
+ }}
+ >
+ {content}
+ </TimelineContext.Provider>
+ </WrapSequenceContext>,
+ );
+ return queryByText;
+};
+
test('It should calculate the correct offset in nested sequences', () => {
const NestedChild = () => {
const frame = useCurrentFrame();
return <div>{'frame' + frame}</div>;
};
- const Child = () => {
+ const Child2 = () => {
return (
- <Sequence from={10} durationInFrames={50}>
- <Child2 />
+ <Sequence from={1} durationInFrames={50}>
+ <NestedChild />
</Sequence>
);
};
- const Child2 = () => {
+ const Child = () => {
return (
- <Sequence from={1} durationInFrames={50}>
- <NestedChild />
+ <Sequence from={10} durationInFrames={50}>
+ <Child2 />
</Sequence>
);
};
@@ -64,35 +93,6 @@ test('Negative offset test', () => {
expect(result(/^frame220/i)).not.toBe(null);
});
-const getForFrame = (frame: number, content: React.ReactNode) => {
- const {queryByText} = render(
- <WrapSequenceContext>
- <TimelineContext.Provider
- value={{
- frame: {
- 'my-comp': frame,
- },
- playing: false,
- rootId: 'hi',
- imperativePlaying: {
- current: false,
- },
- playbackRate: 1,
- setPlaybackRate: () => {
- throw new Error('playback rate');
- },
- audioAndVideoTags: {
- current: [],
- },
- }}
- >
- {content}
- </TimelineContext.Provider>
- </WrapSequenceContext>,
- );
- return queryByText;
-};
-
test('Nested negative offset test', () => {
const NestedChild = () => {
const frame = useCurrentFrame();
diff --git a/packages/core/src/validation/validate-composition-id.ts b/packages/core/src/validation/validate-composition-id.ts
index d23ffe1cfa..2750263f6e 100644
--- a/packages/core/src/validation/validate-composition-id.ts
+++ b/packages/core/src/validation/validate-composition-id.ts
@@ -1,3 +1,7 @@
+const getRegex = () => /^([a-zA-Z0-9-])+$/g;
+
+export const isCompositionIdValid = (id: string) => id.match(getRegex());
+
export const validateCompositionId = (id: string) => {
if (!isCompositionIdValid(id)) {
throw new Error(
@@ -6,10 +10,6 @@ export const validateCompositionId = (id: string) => {
}
};
-const getRegex = () => /^([a-zA-Z0-9-])+$/g;
-
-export const isCompositionIdValid = (id: string) => id.match(getRegex());
-
export const invalidCompositionErrorMessage = `Composition ID must match ${String(
getRegex(),
)}`;
diff --git a/packages/core/src/validation/validate-folder-name.ts b/packages/core/src/validation/validate-folder-name.ts
index 2b57eeea16..b0573abf07 100644
--- a/packages/core/src/validation/validate-folder-name.ts
+++ b/packages/core/src/validation/validate-folder-name.ts
@@ -1,3 +1,7 @@
+const getRegex = () => /^([a-zA-Z0-9-])+$/g;
+
+export const isFolderNameValid = (name: string) => name.match(getRegex());
+
export const validateFolderName = (name: string | null) => {
if (name === undefined || name === null) {
throw new TypeError('You must pass a name to a <Folder />.');
@@ -16,10 +20,6 @@ export const validateFolderName = (name: string | null) => {
}
};
-const getRegex = () => /^([a-zA-Z0-9-])+$/g;
-
-export const isFolderNameValid = (name: string) => name.match(getRegex());
-
export const invalidFolderNameErrorMessage = `Folder name must match ${String(
getRegex(),
)}`;
diff --git a/packages/core/src/video/Video.tsx b/packages/core/src/video/Video.tsx
index edf7b351a6..4c1aa8d629 100644
--- a/packages/core/src/video/Video.tsx
+++ b/packages/core/src/video/Video.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-use-before-define */
import React, {forwardRef, useCallback, useContext} from 'react';
import {getAbsoluteSrc} from '../absolute-src.js';
import {calculateLoopDuration} from '../calculate-loop.js';
diff --git a/packages/core/src/video/video-fragment.ts b/packages/core/src/video/video-fragment.ts
index 3167f62250..e8d8405ebd 100644
--- a/packages/core/src/video/video-fragment.ts
+++ b/packages/core/src/video/video-fragment.ts
@@ -4,56 +4,6 @@ const toSeconds = (time: number, fps: number) => {
return Math.round((time / fps) * 100) / 100;
};
-const isSubsetOfDuration = (
- prevStartFrom: number,
- newStartFrom: number,
- prevDuration: number,
- newDuration: number,
-) => {
- return (
- prevStartFrom <= newStartFrom &&
- prevStartFrom + prevDuration >= newStartFrom + newDuration
- );
-};
-
-export const useAppendVideoFragment = ({
- actualSrc: initialActualSrc,
- actualFrom: initialActualFrom,
- duration: initialDuration,
- fps,
-}: {
- actualSrc: string;
- actualFrom: number;
- duration: number;
- fps: number;
-}) => {
- const actualFromRef = useRef(initialActualFrom);
- const actualDuration = useRef(initialDuration);
- const actualSrc = useRef(initialActualSrc);
-
- if (!isSubsetOfDuration || initialActualSrc !== actualSrc.current) {
- actualFromRef.current = initialActualFrom;
- actualDuration.current = initialDuration;
- actualSrc.current = initialActualSrc;
- }
-
- const appended = appendVideoFragment({
- actualSrc: actualSrc.current,
- actualFrom: actualFromRef.current,
- duration: actualDuration.current,
- fps,
- });
-
- return appended;
-};
-
-export const isIosSafari = () => {
- return typeof window === 'undefined'
- ? false
- : /iP(ad|od|hone)/i.test(window.navigator.userAgent) &&
- Boolean(navigator.userAgent.match(/Version\/[\d.]+.*Safari/));
-};
-
// https://github.com/remotion-dev/remotion/issues/1655
const isIOSSafariCase = (actualSrc: string) => {
return typeof window === 'undefined'
@@ -108,3 +58,53 @@ export const appendVideoFragment = ({
return actualSrc;
};
+
+const isSubsetOfDuration = (
+ prevStartFrom: number,
+ newStartFrom: number,
+ prevDuration: number,
+ newDuration: number,
+) => {
+ return (
+ prevStartFrom <= newStartFrom &&
+ prevStartFrom + prevDuration >= newStartFrom + newDuration
+ );
+};
+
+export const useAppendVideoFragment = ({
+ actualSrc: initialActualSrc,
+ actualFrom: initialActualFrom,
+ duration: initialDuration,
+ fps,
+}: {
+ actualSrc: string;
+ actualFrom: number;
+ duration: number;
+ fps: number;
+}) => {
+ const actualFromRef = useRef(initialActualFrom);
+ const actualDuration = useRef(initialDuration);
+ const actualSrc = useRef(initialActualSrc);
+
+ if (!isSubsetOfDuration || initialActualSrc !== actualSrc.current) {
+ actualFromRef.current = initialActualFrom;
+ actualDuration.current = initialDuration;
+ actualSrc.current = initialActualSrc;
+ }
+
+ const appended = appendVideoFragment({
+ actualSrc: actualSrc.current,
+ actualFrom: actualFromRef.current,
+ duration: actualDuration.current,
+ fps,
+ });
+
+ return appended;
+};
+
+export const isIosSafari = () => {
+ return typeof window === 'undefined'
+ ? false
+ : /iP(ad|od|hone)/i.test(window.navigator.userAgent) &&
+ Boolean(navigator.userAgent.match(/Version\/[\d.]+.*Safari/));
+};
diff --git a/packages/docs/src/components/DoMoreHero/join-inbetween-tiles.ts b/packages/docs/src/components/DoMoreHero/join-inbetween-tiles.ts
index 77c11a0acf..7e3a3b01a1 100644
--- a/packages/docs/src/components/DoMoreHero/join-inbetween-tiles.ts
+++ b/packages/docs/src/components/DoMoreHero/join-inbetween-tiles.ts
@@ -12,6 +12,51 @@ import { translateZ } from "./matrix";
import { subdivideInstructions } from "./subdivide-instruction";
import { truthy } from "./truthy";
+const inverseInstruction = (
+ instruction: ThreeDReducedInstruction,
+ comingFrom: Vector4D,
+): ThreeDReducedInstruction => {
+ if (instruction.type === "M") {
+ return {
+ type: "M",
+ point: comingFrom,
+ };
+ }
+
+ if (instruction.type === "L") {
+ return {
+ type: "L",
+ point: comingFrom,
+ };
+ }
+
+ if (instruction.type === "C") {
+ return {
+ type: "C",
+ point: comingFrom,
+ cp1: instruction.cp2,
+ cp2: instruction.cp1,
+ };
+ }
+
+ if (instruction.type === "Q") {
+ return {
+ type: "Q",
+ point: comingFrom,
+ cp: instruction.cp,
+ };
+ }
+
+ if (instruction.type === "Z") {
+ return {
+ type: "L",
+ point: comingFrom,
+ };
+ }
+
+ throw new Error("Unknown instruction type");
+};
+
export const extrudeElement = ({
depth,
sideColor,
@@ -128,48 +173,3 @@ export const extrudeElement = ({
description,
);
};
-
-const inverseInstruction = (
- instruction: ThreeDReducedInstruction,
- comingFrom: Vector4D,
-): ThreeDReducedInstruction => {
- if (instruction.type === "M") {
- return {
- type: "M",
- point: comingFrom,
- };
- }
-
- if (instruction.type === "L") {
- return {
- type: "L",
- point: comingFrom,
- };
- }
-
- if (instruction.type === "C") {
- return {
- type: "C",
- point: comingFrom,
- cp1: instruction.cp2,
- cp2: instruction.cp1,
- };
- }
-
- if (instruction.type === "Q") {
- return {
- type: "Q",
- point: comingFrom,
- cp: instruction.cp,
- };
- }
-
- if (instruction.type === "Z") {
- return {
- type: "L",
- point: comingFrom,
- };
- }
-
- throw new Error("Unknown instruction type");
-};
diff --git a/packages/docs/src/components/DoMoreHero/matrix.ts b/packages/docs/src/components/DoMoreHero/matrix.ts
index 61d6496d3b..9c75159587 100644
--- a/packages/docs/src/components/DoMoreHero/matrix.ts
+++ b/packages/docs/src/components/DoMoreHero/matrix.ts
@@ -1,9 +1,5 @@
import type { ThreeDReducedInstruction } from "./3d-svg";
-export const translated4d = function (vec: Vector) {
- return stride({ v: vec, m: identity4(), width: 4, offset: 3, colStride: 0 });
-};
-
export const stride = function ({
v,
m,
@@ -38,32 +34,10 @@ export const identity4 = function (): MatrixTransform4D {
return m;
};
-export const m44multiply = (
- ...matrices: MatrixTransform4D[]
-): MatrixTransform4D => {
- return multiplyMany(4, matrices);
+export const translated4d = function (vec: Vector) {
+ return stride({ v: vec, m: identity4(), width: 4, offset: 3, colStride: 0 });
};
-// Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
-// number of matrices following it.
-function multiplyMany(
- size: number,
- listOfMatrices: MatrixTransform4D[],
-): MatrixTransform4D {
- if (listOfMatrices.length < 2) {
- throw new Error("multiplication expected two or more matrices");
- }
-
- let result = mul(listOfMatrices[0], listOfMatrices[1], size);
- let next = 2;
- while (next < listOfMatrices.length) {
- result = mul(result, listOfMatrices[next], size);
- next++;
- }
-
- return result as MatrixTransform4D;
-}
-
function mul(m1: number[], m2: number[], size: number): number[] {
if (m1.length !== m2.length) {
throw new Error(
@@ -93,29 +67,35 @@ function mul(m1: number[], m2: number[], size: number): number[] {
return result;
}
-export type Vector2D = [number, number];
-export type Vector = [number, number, number];
-export type Vector4D = [number, number, number, number];
+// Accept an integer indicating the size of the matrices being multiplied (3 for 3x3), and any
+// number of matrices following it.
+function multiplyMany(
+ size: number,
+ listOfMatrices: MatrixTransform4D[],
+): MatrixTransform4D {
+ if (listOfMatrices.length < 2) {
+ throw new Error("multiplication expected two or more matrices");
+ }
-const rotated = function (axisVec: Vector, radians: number): MatrixTransform4D {
- return rotatedUnitSinCos(
- normalize(axisVec),
- Math.sin(radians),
- Math.cos(radians),
- );
-};
+ let result = mul(listOfMatrices[0], listOfMatrices[1], size);
+ let next = 2;
+ while (next < listOfMatrices.length) {
+ result = mul(result, listOfMatrices[next], size);
+ next++;
+ }
-export const rotateX = (radians: number) => {
- return rotated([1, 0, 0], radians);
-};
+ return result as MatrixTransform4D;
+}
-export const rotateY = (radians: number) => {
- return rotated([0, 1, 0], radians);
+export const m44multiply = (
+ ...matrices: MatrixTransform4D[]
+): MatrixTransform4D => {
+ return multiplyMany(4, matrices);
};
-export const rotateZ = (radians: number) => {
- return rotated([0, 0, 1], radians);
-};
+export type Vector2D = [number, number];
+export type Vector = [number, number, number];
+export type Vector4D = [number, number, number, number];
export type MatrixTransform4D = [
number,
@@ -172,22 +152,6 @@ const rotatedUnitSinCos = function (
];
};
-export const normalize = function (v: Vector): Vector {
- return mulScalar(v, 1 / vectorLength(v));
-};
-
-export const normalize4d = function (v: Vector4D): Vector4D {
- return mulScalar(v, 1 / vectorLength(v));
-};
-
-const vectorLength = function (v: number[]) {
- return Math.sqrt(lengthSquared(v));
-};
-
-const lengthSquared = function (v: number[]) {
- return dot(v, v);
-};
-
export const dot = function (a: number[], b: number[]) {
if (a.length !== b.length) {
throw new Error(
@@ -226,6 +190,48 @@ export const translateZ = (z: number) => {
return translated([0, 0, z]);
};
+const lengthSquared = function (v: number[]) {
+ return dot(v, v);
+};
+
+const vectorLength = function (v: number[]) {
+ return Math.sqrt(lengthSquared(v));
+};
+
+export const mulScalar = function <T extends number[]>(v: T, s: number): T {
+ return v.map((i) => {
+ return i * s;
+ }) as T;
+};
+
+export const normalize = function (v: Vector): Vector {
+ return mulScalar(v, 1 / vectorLength(v));
+};
+
+export const normalize4d = function (v: Vector4D): Vector4D {
+ return mulScalar(v, 1 / vectorLength(v));
+};
+
+const rotated = function (axisVec: Vector, radians: number): MatrixTransform4D {
+ return rotatedUnitSinCos(
+ normalize(axisVec),
+ Math.sin(radians),
+ Math.cos(radians),
+ );
+};
+
+export const rotateX = (radians: number) => {
+ return rotated([1, 0, 0], radians);
+};
+
+export const rotateY = (radians: number) => {
+ return rotated([0, 1, 0], radians);
+};
+
+export const rotateZ = (radians: number) => {
+ return rotated([0, 0, 1], radians);
+};
+
export type Camera = {
near: number;
far: number;
@@ -235,10 +241,23 @@ export type Camera = {
up: Vector;
};
-export const mulScalar = function <T extends number[]>(v: T, s: number): T {
- return v.map((i) => {
- return i * s;
- }) as T;
+export const multiplyMatrix = (
+ matrix: MatrixTransform4D,
+ point: Vector4D,
+): Vector4D => {
+ if (matrix.length !== 16 || point.length !== 4) {
+ throw new Error("Invalid matrix or vector dimension");
+ }
+
+ const result: Vector4D = [0, 0, 0, 0];
+
+ for (let i = 0; i < 4; i++) {
+ for (let j = 0; j < 4; j++) {
+ result[i] += matrix[i * 4 + j] * point[j];
+ }
+ }
+
+ return result;
};
export function multiplyMatrixAndSvgInstruction(
@@ -286,25 +305,6 @@ export function multiplyMatrixAndSvgInstruction(
throw new Error("Unknown instruction type: " + JSON.stringify(point));
}
-export const multiplyMatrix = (
- matrix: MatrixTransform4D,
- point: Vector4D,
-): Vector4D => {
- if (matrix.length !== 16 || point.length !== 4) {
- throw new Error("Invalid matrix or vector dimension");
- }
-
- const result: Vector4D = [0, 0, 0, 0];
-
- for (let i = 0; i < 4; i++) {
- for (let j = 0; j < 4; j++) {
- result[i] += matrix[i * 4 + j] * point[j];
- }
- }
-
- return result;
-};
-
export const sub4d = function (a: Vector4D, b: Vector4D): Vector4D {
return a.map((v, i) => {
return v - b[i];
diff --git a/packages/docs/src/components/DoMoreHero/subdivide-instruction.ts b/packages/docs/src/components/DoMoreHero/subdivide-instruction.ts
index b28a8d2e5e..2e81d450b9 100644
--- a/packages/docs/src/components/DoMoreHero/subdivide-instruction.ts
+++ b/packages/docs/src/components/DoMoreHero/subdivide-instruction.ts
@@ -2,54 +2,6 @@ import type { Instruction } from "@remotion/paths";
import type { ThreeDReducedInstruction } from "./3d-svg";
import type { Vector2D, Vector4D } from "./matrix";
-export const subdivideInstructions = (
- instructions: ThreeDReducedInstruction[],
-): ThreeDReducedInstruction[] => {
- const newInstructions: ThreeDReducedInstruction[] = [];
- instructions.forEach((instruction, i) => {
- if (instruction.type === "M") {
- newInstructions.push(instruction);
- return;
- }
-
- if (instruction.type === "Z") {
- newInstructions.push(instruction);
- return;
- }
-
- const previousInstruction = instructions[i - 1];
- const subdivided = subdivideInstruction(
- previousInstruction.point,
- instruction,
- );
- newInstructions.push(...subdivided);
- });
- return newInstructions;
-};
-
-const subdivideInstruction = (
- from: Vector4D,
- instruction: ThreeDReducedInstruction,
-): ThreeDReducedInstruction[] => {
- if (instruction.type === "C") {
- return subdivide3DCInstruction(from, instruction);
- }
-
- if (instruction.type === "L" || instruction.type === "M") {
- return subdivideLOrMInstruction(from, instruction);
- }
-
- if (instruction.type === "Q") {
- return subdivideQInstruction(from, instruction);
- }
-
- if (instruction.type === "Z") {
- return [instruction];
- }
-
- throw new Error("Cannot subdivide instruction");
-};
-
const subdivideLOrMInstruction = (
from: Vector4D,
instruction: ThreeDReducedInstruction,
@@ -236,3 +188,51 @@ const subdivideQInstruction = (
return newInstructions;
};
+
+const subdivideInstruction = (
+ from: Vector4D,
+ instruction: ThreeDReducedInstruction,
+): ThreeDReducedInstruction[] => {
+ if (instruction.type === "C") {
+ return subdivide3DCInstruction(from, instruction);
+ }
+
+ if (instruction.type === "L" || instruction.type === "M") {
+ return subdivideLOrMInstruction(from, instruction);
+ }
+
+ if (instruction.type === "Q") {
+ return subdivideQInstruction(from, instruction);
+ }
+
+ if (instruction.type === "Z") {
+ return [instruction];
+ }
+
+ throw new Error("Cannot subdivide instruction");
+};
+
+export const subdivideInstructions = (
+ instructions: ThreeDReducedInstruction[],
+): ThreeDReducedInstruction[] => {
+ const newInstructions: ThreeDReducedInstruction[] = [];
+ instructions.forEach((instruction, i) => {
+ if (instruction.type === "M") {
+ newInstructions.push(instruction);
+ return;
+ }
+
+ if (instruction.type === "Z") {
+ newInstructions.push(instruction);
+ return;
+ }
+
+ const previousInstruction = instructions[i - 1];
+ const subdivided = subdivideInstruction(
+ previousInstruction.point,
+ instruction,
+ );
+ newInstructions.push(...subdivided);
+ });
+ return newInstructions;
+};
diff --git a/packages/docs/src/components/Options.tsx b/packages/docs/src/components/Options.tsx
index 201749c657..4c7087b689 100644
--- a/packages/docs/src/components/Options.tsx
+++ b/packages/docs/src/components/Options.tsx
@@ -2,15 +2,6 @@ import type { AnyRemotionOption } from "@remotion/renderer";
import { BrowserSafeApis } from "@remotion/renderer/client";
import type React from "react";
-export const Options: React.FC<{
- id: string;
- cli?: boolean;
-}> = ({ id, cli }) => {
- const option = getOption(id);
-
- return option.description(cli ? "cli" : "ssr") as JSX.Element;
-};
-
const options = Object.values(BrowserSafeApis.options);
const getOption = (id: string): AnyRemotionOption => {
@@ -22,3 +13,12 @@ const getOption = (id: string): AnyRemotionOption => {
return option;
};
+
+export const Options: React.FC<{
+ id: string;
+ cli?: boolean;
+}> = ({ id, cli }) => {
+ const option = getOption(id);
+
+ return option.description(cli ? "cli" : "ssr") as JSX.Element;
+};
diff --git a/packages/docs/src/components/V4Countdown.tsx b/packages/docs/src/components/V4Countdown.tsx
index 9895a5f38b..b94f90f488 100644
--- a/packages/docs/src/components/V4Countdown.tsx
+++ b/packages/docs/src/components/V4Countdown.tsx
@@ -45,15 +45,6 @@ export const V4Countdown: React.FC<{
const targetUnixTimeStamp = 1688403600;
- useEffect(() => {
- const interval = setInterval(() => {
- const currentCountdown = getUpdatedCountdown();
- setCountdown(currentCountdown);
- }, 1000);
-
- return () => clearInterval(interval);
- }, [countdown]);
-
const getUpdatedCountdown = (): [string, string, string, string] => {
const currentUnixTime = Math.floor(Date.now() / 1000);
@@ -77,6 +68,15 @@ export const V4Countdown: React.FC<{
return [strDays, strHours, strMinutes, strSeconds];
};
+ useEffect(() => {
+ const interval = setInterval(() => {
+ const currentCountdown = getUpdatedCountdown();
+ setCountdown(currentCountdown);
+ }, 1000);
+
+ return () => clearInterval(interval);
+ }, [countdown]);
+
if (Math.floor(Date.now() / 1000) > targetUnixTimeStamp) {
setShowCountdown(false);
}
diff --git a/packages/docs/src/pages/4/index.tsx b/packages/docs/src/pages/4/index.tsx
index 7dd3a43a5a..13fc77ed39 100644
--- a/packages/docs/src/pages/4/index.tsx
+++ b/packages/docs/src/pages/4/index.tsx
@@ -19,6 +19,64 @@ const errorStyle: React.CSSProperties = {
textAlign: "center",
};
+export const EventComp: React.FC<{
+ date: string;
+ title: string;
+ description: string;
+ youtubeId?: string;
+}> = ({ date, title, description, youtubeId }) => {
+ return (
+ <div
+ style={{
+ border: "2px solid var(--ifm-font-color-base)",
+ borderBottomWidth: 4,
+ borderRadius: 8,
+ padding: 10,
+ }}
+ >
+ <p className={styles.date}>{date}</p>
+ <p className={styles.eventtitle}>{title}</p>
+ <p>{description}</p>
+ {youtubeId ? (
+ <iframe
+ style={{
+ width: "100%",
+ aspectRatio: "16 / 9",
+ }}
+ src={`https://www.youtube.com/embed/${youtubeId}`}
+ title="YouTube video player"
+ frameBorder="0"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowFullScreen
+ />
+ ) : (
+ <div
+ style={{
+ width: "100%",
+ aspectRatio: "16 / 9",
+ backgroundColor: "var(--ifm-out-of-focus)",
+ borderRadius: 5,
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
+ <div
+ style={{
+ color: "var(--ifm-subtitle)",
+ justifyContent: "center",
+ alignItems: "center",
+ fontWeight: "bold",
+ }}
+ >
+ Check back {date}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
const V4: React.FC = () => {
const context = useDocusaurusContext();
@@ -183,62 +241,4 @@ const V4: React.FC = () => {
);
};
-export const EventComp: React.FC<{
- date: string;
- title: string;
- description: string;
- youtubeId?: string;
-}> = ({ date, title, description, youtubeId }) => {
- return (
- <div
- style={{
- border: "2px solid var(--ifm-font-color-base)",
- borderBottomWidth: 4,
- borderRadius: 8,
- padding: 10,
- }}
- >
- <p className={styles.date}>{date}</p>
- <p className={styles.eventtitle}>{title}</p>
- <p>{description}</p>
- {youtubeId ? (
- <iframe
- style={{
- width: "100%",
- aspectRatio: "16 / 9",
- }}
- src={`https://www.youtube.com/embed/${youtubeId}`}
- title="YouTube video player"
- frameBorder="0"
- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
- allowFullScreen
- />
- ) : (
- <div
- style={{
- width: "100%",
- aspectRatio: "16 / 9",
- backgroundColor: "var(--ifm-out-of-focus)",
- borderRadius: 5,
- display: "flex",
- justifyContent: "center",
- alignItems: "center",
- }}
- >
- <div
- style={{
- color: "var(--ifm-subtitle)",
- justifyContent: "center",
- alignItems: "center",
- fontWeight: "bold",
- }}
- >
- Check back {date}
- </div>
- </div>
- )}
- </div>
- );
-};
-
export default V4;
diff --git a/packages/docs/src/pages/templates/index.tsx b/packages/docs/src/pages/templates/index.tsx
index 26f3981023..dca458318d 100644
--- a/packages/docs/src/pages/templates/index.tsx
+++ b/packages/docs/src/pages/templates/index.tsx
@@ -24,6 +24,54 @@ const lowerpara: React.CSSProperties = {
color: "var(--light-text-color)",
};
+const outer: React.CSSProperties = {
+ display: "flex",
+ cursor: "pointer",
+ color: "var(--text-color)",
+ textDecoration: "none",
+};
+
+const icon: React.CSSProperties = {
+ display: "flex",
+ margin: 0,
+ marginRight: 10,
+ height: 30,
+ width: 30,
+ justifyContent: "center",
+ alignItems: "center",
+};
+
+const labelStyle: React.CSSProperties = {
+ fontWeight: "bold",
+};
+
+const descriptionStyle: React.CSSProperties = {
+ fontSize: 14,
+ marginTop: 10,
+ color: "var(--light-text-color)",
+ marginBottom: 10,
+};
+
+const Item: React.FC<{
+ label: string;
+ description: React.ReactNode;
+ children: React.ReactNode;
+}> = ({ children, label, description }) => {
+ return (
+ <div>
+ <div
+ style={{ flexDirection: "row", display: "flex", alignItems: "center" }}
+ >
+ <div style={icon}>{children}</div>
+ <div style={labelStyle}>{label}</div>
+ </div>
+ <div>
+ <p style={descriptionStyle}>{description}</p>
+ </div>
+ </div>
+ );
+};
+
export default () => {
const imgSrc = `/generated/template-all.png`;
const context = useDocusaurusContext();
@@ -75,51 +123,3 @@ export default () => {
</Layout>
);
};
-
-const Item: React.FC<{
- label: string;
- description: React.ReactNode;
- children: React.ReactNode;
-}> = ({ children, label, description }) => {
- return (
- <div>
- <div
- style={{ flexDirection: "row", display: "flex", alignItems: "center" }}
- >
- <div style={icon}>{children}</div>
- <div style={labelStyle}>{label}</div>
- </div>
- <div>
- <p style={descriptionStyle}>{description}</p>
- </div>
- </div>
- );
-};
-
-const outer: React.CSSProperties = {
- display: "flex",
- cursor: "pointer",
- color: "var(--text-color)",
- textDecoration: "none",
-};
-
-const icon: React.CSSProperties = {
- display: "flex",
- margin: 0,
- marginRight: 10,
- height: 30,
- width: 30,
- justifyContent: "center",
- alignItems: "center",
-};
-
-const labelStyle: React.CSSProperties = {
- fontWeight: "bold",
-};
-
-const descriptionStyle: React.CSSProperties = {
- fontSize: 14,
- marginTop: 10,
- color: "var(--light-text-color)",
- marginBottom: 10,
-};
diff --git a/packages/example/runlambda.sh b/packages/example/runlambda.sh
index 9d00e8bde4..7a8c2bd9d8 100644
--- a/packages/example/runlambda.sh
+++ b/packages/example/runlambda.sh
@@ -5,6 +5,6 @@ npm run buildlambda
cd ..
cd example
pnpm exec remotion lambda functions rmall -f
-pnpm exec remotion lambda functions deploy --memory=3000
+pnpm exec remotion lambda functions deploy --memory=4000 --timeout=900 --disk=10000
pnpm exec remotion lambda sites create --site-name=testbed-v6 --log=verbose --enable-folder-expiry
-pnpm exec remotion lambda render testbed-v6 react-svg --out-name=ggg.mp4 ggg.mp4 --log=verbose --delete-after="1-day"
+# pnpm exec remotion lambda render testbed-v6 OffthreadRemoteVideo --log=verbose --delete-after="1-day"
diff --git a/packages/example/src/OffthreadRemoteVideo/OffthreadRemoteVideo.tsx b/packages/example/src/OffthreadRemoteVideo/OffthreadRemoteVideo.tsx
index 8501e9f347..094bd56d9e 100644
--- a/packages/example/src/OffthreadRemoteVideo/OffthreadRemoteVideo.tsx
+++ b/packages/example/src/OffthreadRemoteVideo/OffthreadRemoteVideo.tsx
@@ -1,13 +1,11 @@
-import {interpolate, OffthreadVideo, staticFile} from 'remotion';
+import {Loop} from 'remotion';
+import {OffthreadVideo, staticFile} from 'remotion';
export const OffthreadRemoteVideo: React.FC = () => {
return (
- <OffthreadVideo
- volume={(f) =>
- interpolate(f, [0, 500], [1, 0], {extrapolateRight: 'clamp'})
- }
- src={staticFile('vid1.mp4')}
- />
+ <Loop durationInFrames={15 * 30}>
+ <OffthreadVideo src={staticFile('vid1.mp4')} />
+ </Loop>
);
};
diff --git a/packages/gif/src/parse-generate.ts b/packages/gif/src/parse-generate.ts
index d7e5758437..2686d11458 100644
--- a/packages/gif/src/parse-generate.ts
+++ b/packages/gif/src/parse-generate.ts
@@ -15,6 +15,35 @@ const validateAndFix = (gif: ParsedGif) => {
}
};
+const putPixels = (
+ typedArray: Uint8ClampedArray,
+ frame: ParsedFrameWithoutPatch,
+ gifSize: {
+ width: number;
+ height: number;
+ },
+) => {
+ const {width, height, top: dy, left: dx} = frame.dims;
+ const offset = dy * gifSize.width + dx;
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const pPos = y * width + x;
+ const colorIndex = frame.pixels[pPos];
+ if (colorIndex !== frame.transparentIndex) {
+ const taPos = offset + y * gifSize.width + x;
+ const color = frame.colorTable[colorIndex];
+ typedArray[taPos * 4] = color[0];
+ typedArray[taPos * 4 + 1] = color[1];
+ typedArray[taPos * 4 + 2] = color[2];
+ typedArray[taPos * 4 + 3] =
+ colorIndex === frame.transparentIndex ? 0 : 255;
+ }
+ }
+ }
+
+ return typedArray;
+};
+
export const parse = (
src: string,
{
@@ -83,35 +112,6 @@ export const parse = (
};
});
-const putPixels = (
- typedArray: Uint8ClampedArray,
- frame: ParsedFrameWithoutPatch,
- gifSize: {
- width: number;
- height: number;
- },
-) => {
- const {width, height, top: dy, left: dx} = frame.dims;
- const offset = dy * gifSize.width + dx;
- for (let y = 0; y < height; y++) {
- for (let x = 0; x < width; x++) {
- const pPos = y * width + x;
- const colorIndex = frame.pixels[pPos];
- if (colorIndex !== frame.transparentIndex) {
- const taPos = offset + y * gifSize.width + x;
- const color = frame.colorTable[colorIndex];
- typedArray[taPos * 4] = color[0];
- typedArray[taPos * 4 + 1] = color[1];
- typedArray[taPos * 4 + 2] = color[2];
- typedArray[taPos * 4 + 3] =
- colorIndex === frame.transparentIndex ? 0 : 255;
- }
- }
- }
-
- return typedArray;
-};
-
type ParserCallbackArgs = {
width: number;
height: number;
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index 57215554fa..3610464781 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -29,6 +29,15 @@ import {makeMultiProgressFromStatus, makeProgressString} from './progress';
export const RENDER_COMMAND = 'render';
+function getTotalFrames(status: RenderProgress): number | null {
+ return status.renderMetadata
+ ? RenderInternals.getFramesToRender(
+ status.renderMetadata.frameRange,
+ status.renderMetadata.everyNthFrame,
+ ).length
+ : null;
+}
+
export const renderCommand = async (args: string[], remotionRoot: string) => {
const serveUrl = args[0];
if (!serveUrl) {
@@ -398,12 +407,3 @@ export const renderCommand = async (args: string[], remotionRoot: string) => {
}
}
};
-
-function getTotalFrames(status: RenderProgress): number | null {
- return status.renderMetadata
- ? RenderInternals.getFramesToRender(
- status.renderMetadata.frameRange,
- status.renderMetadata.everyNthFrame,
- ).length
- : null;
-}
diff --git a/packages/lambda/src/functions/helpers/streamify-response.ts b/packages/lambda/src/functions/helpers/streamify-response.ts
index bffe220dca..499ad6451b 100644
--- a/packages/lambda/src/functions/helpers/streamify-response.ts
+++ b/packages/lambda/src/functions/helpers/streamify-response.ts
@@ -31,6 +31,16 @@ export class ResponseStream extends Stream.Writable {
this._isBase64Encoded = isBase64Encoded;
}
}
+
+function patchArgs(argList: unknown[]): ResponseStream {
+ if (!(argList[1] instanceof ResponseStream)) {
+ const responseStream = new ResponseStream();
+ argList.splice(1, 0, responseStream);
+ }
+
+ return argList[1] as ResponseStream;
+}
+
export const HANDLER_STREAMING = Symbol.for(
'aws.lambda.runtime.handler.streaming',
);
@@ -76,12 +86,3 @@ export function streamifyResponse(handler: Function): Function {
},
});
}
-
-function patchArgs(argList: unknown[]): ResponseStream {
- if (!(argList[1] instanceof ResponseStream)) {
- const responseStream = new ResponseStream();
- argList.splice(1, 0, responseStream);
- }
-
- return argList[1] as ResponseStream;
-}
diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.ts
index ca06389ba8..4779664629 100644
--- a/packages/lambda/src/functions/launch.ts
+++ b/packages/lambda/src/functions/launch.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-use-before-define */
import {InvokeCommand} from '@aws-sdk/client-lambda';
import {RenderInternals} from '@remotion/renderer';
import {VERSION} from 'remotion/version';
diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.ts
index d09396ca68..035e798dbe 100644
--- a/packages/lambda/src/shared/call-lambda.ts
+++ b/packages/lambda/src/shared/call-lambda.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-use-before-define */
import type {InvokeWithResponseStreamResponseEvent} from '@aws-sdk/client-lambda';
import {InvokeWithResponseStreamCommand} from '@aws-sdk/client-lambda';
import type {StreamingPayloads} from '../functions/helpers/streaming-payloads';
@@ -18,6 +19,60 @@ type Options<T extends LambdaRoutines> = {
timeoutInTest: number;
};
+const parseJsonWithErrorSurfacing = (input: string) => {
+ try {
+ return JSON.parse(input);
+ } catch {
+ throw new Error(`${INVALID_JSON_MESSAGE}. Response: ${input}`);
+ }
+};
+
+const parseJson = <T extends LambdaRoutines>(input: string) => {
+ let json = parseJsonWithErrorSurfacing(input) as
+ | OrError<Awaited<LambdaReturnValues[T]>>
+ | {
+ errorType: string;
+ errorMessage: string;
+ trace: string[];
+ }
+ | {
+ statusCode: string;
+ body: string;
+ };
+
+ if ('statusCode' in json) {
+ json = parseJsonWithErrorSurfacing(json.body) as
+ | OrError<Awaited<LambdaReturnValues[T]>>
+ | {
+ errorType: string;
+ errorMessage: string;
+ trace: string[];
+ };
+ }
+
+ if ('errorMessage' in json) {
+ const err = new Error(json.errorMessage);
+ err.name = json.errorType;
+ err.stack = (json.trace ?? []).join('\n');
+ throw err;
+ }
+
+ // This will not happen, it is for narrowing purposes
+ if ('statusCode' in json) {
+ throw new Error(
+ `Lambda function failed with status code ${json.statusCode}`,
+ );
+ }
+
+ if (json.type === 'error') {
+ const err = new Error(json.message);
+ err.stack = json.stack;
+ throw err;
+ }
+
+ return json;
+};
+
export const callLambda = async <T extends LambdaRoutines>(
options: Options<T> & {
retriesRemaining: number;
@@ -105,57 +160,3 @@ const callLambdaWithoutRetry = async <T extends LambdaRoutines>({
return json;
};
-
-const parseJsonWithErrorSurfacing = (input: string) => {
- try {
- return JSON.parse(input);
- } catch {
- throw new Error(`${INVALID_JSON_MESSAGE}. Response: ${input}`);
- }
-};
-
-const parseJson = <T extends LambdaRoutines>(input: string) => {
- let json = parseJsonWithErrorSurfacing(input) as
- | OrError<Awaited<LambdaReturnValues[T]>>
- | {
- errorType: string;
- errorMessage: string;
- trace: string[];
- }
- | {
- statusCode: string;
- body: string;
- };
-
- if ('statusCode' in json) {
- json = parseJsonWithErrorSurfacing(json.body) as
- | OrError<Awaited<LambdaReturnValues[T]>>
- | {
- errorType: string;
- errorMessage: string;
- trace: string[];
- };
- }
-
- if ('errorMessage' in json) {
- const err = new Error(json.errorMessage);
- err.name = json.errorType;
- err.stack = (json.trace ?? []).join('\n');
- throw err;
- }
-
- // This will not happen, it is for narrowing purposes
- if ('statusCode' in json) {
- throw new Error(
- `Lambda function failed with status code ${json.statusCode}`,
- );
- }
-
- if (json.type === 'error') {
- const err = new Error(json.message);
- err.stack = json.stack;
- throw err;
- }
-
- return json;
-};
diff --git a/packages/lambda/src/shared/compress-props.ts b/packages/lambda/src/shared/compress-props.ts
index 416ee9724a..9fc09fd3aa 100644
--- a/packages/lambda/src/shared/compress-props.ts
+++ b/packages/lambda/src/shared/compress-props.ts
@@ -10,6 +10,14 @@ import {MAX_WEBHOOK_CUSTOM_DATA_SIZE} from './validate-webhook';
type PropsType = 'input-props' | 'resolved-props';
+const makeKey = (type: PropsType, hash: string): string => {
+ if (type === 'input-props') {
+ return inputPropsKey(hash);
+ }
+
+ return resolvedPropsKey(hash);
+};
+
export const serializeOrThrow = (
inputProps: Record<string, unknown>,
propsType: PropsType,
@@ -138,11 +146,3 @@ export const decompressInputProps = async ({
);
}
};
-
-const makeKey = (type: PropsType, hash: string): string => {
- if (type === 'input-props') {
- return inputPropsKey(hash);
- }
-
- return resolvedPropsKey(hash);
-};
diff --git a/packages/lambda/src/shared/get-aws-urls.ts b/packages/lambda/src/shared/get-aws-urls.ts
index 2e249e71f1..57bd63abb0 100644
--- a/packages/lambda/src/shared/get-aws-urls.ts
+++ b/packages/lambda/src/shared/get-aws-urls.ts
@@ -2,6 +2,20 @@ import type {AwsRegion} from '../client';
import type {LambdaRoutines} from './constants';
import {encodeAwsUrlParams} from './encode-aws-url-params';
+const cloudWatchUrlWithQuery = ({
+ region,
+ functionNameToUse,
+ query,
+}: {
+ region: AwsRegion;
+ functionNameToUse: string;
+ query: string;
+}) => {
+ return `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${functionNameToUse}/log-events$3FfilterPattern$3D${encodeAwsUrlParams(
+ query,
+ )}`;
+};
+
export const getCloudwatchMethodUrl = ({
region,
functionName,
@@ -42,20 +56,6 @@ export const getCloudwatchRendererUrl = ({
return cloudWatchUrlWithQuery({region, functionNameToUse, query});
};
-const cloudWatchUrlWithQuery = ({
- region,
- functionNameToUse,
- query,
-}: {
- region: AwsRegion;
- functionNameToUse: string;
- query: string;
-}) => {
- return `https://${region}.console.aws.amazon.com/cloudwatch/home?region=${region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${functionNameToUse}/log-events$3FfilterPattern$3D${encodeAwsUrlParams(
- query,
- )}`;
-};
-
export const getS3RenderUrl = ({
renderId,
region,
diff --git a/packages/lambda/src/shared/invoke-webhook.ts b/packages/lambda/src/shared/invoke-webhook.ts
index 79df371c1b..2016b7aae8 100644
--- a/packages/lambda/src/shared/invoke-webhook.ts
+++ b/packages/lambda/src/shared/invoke-webhook.ts
@@ -50,6 +50,11 @@ export type WebhookPayload = {
customData: Record<string, unknown> | null;
} & DynamicWebhookPayload;
+export const mockableHttpClients = {
+ http: http.request,
+ https: https.request,
+};
+
const getWebhookClient = (url: string) => {
if (url.startsWith('https://')) {
return mockableHttpClients.https;
@@ -62,11 +67,6 @@ const getWebhookClient = (url: string) => {
throw new Error('Can only request URLs starting with http:// or https://');
};
-export const mockableHttpClients = {
- http: http.request,
- https: https.request,
-};
-
type InvokeWebhookOptions = {
payload: WebhookPayload;
url: string;
diff --git a/packages/media-utils/src/get-audio-duration-in-seconds.ts b/packages/media-utils/src/get-audio-duration-in-seconds.ts
index 73d849c163..387320f729 100644
--- a/packages/media-utils/src/get-audio-duration-in-seconds.ts
+++ b/packages/media-utils/src/get-audio-duration-in-seconds.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-use-before-define */
import {pLimit} from './p-limit';
const limit = pLimit(3);
diff --git a/packages/paths/src/get-bounding-box.ts b/packages/paths/src/get-bounding-box.ts
index 2e2fb5a84a..e5919311f3 100644
--- a/packages/paths/src/get-bounding-box.ts
+++ b/packages/paths/src/get-bounding-box.ts
@@ -88,18 +88,6 @@ function minmaxC(A: [number, number, number, number]): minMax {
return [min, max];
}
-/**
- * @description Returns the bounding box of the given path, suitable for calculating the viewBox value that you need to pass to an SVG.
- * @param {string} d
- * @see [Documentation](https://www.remotion.dev/docs/paths/get-bounding-box)
- */
-export const getBoundingBox = (d: string): BoundingBox => {
- const parsed = parsePath(d) as AbsoluteInstruction[];
- const unarced = removeATSHVInstructions(normalizeInstructions(parsed));
-
- return getBoundingBoxFromInstructions(unarced);
-};
-
export const getBoundingBoxFromInstructions = (
instructions: ReducedInstruction[],
): BoundingBox => {
@@ -233,3 +221,15 @@ export const getBoundingBoxFromInstructions = (
height: maxY - minY,
};
};
+
+/**
+ * @description Returns the bounding box of the given path, suitable for calculating the viewBox value that you need to pass to an SVG.
+ * @param {string} d
+ * @see [Documentation](https://www.remotion.dev/docs/paths/get-bounding-box)
+ */
+export const getBoundingBox = (d: string): BoundingBox => {
+ const parsed = parsePath(d) as AbsoluteInstruction[];
+ const unarced = removeATSHVInstructions(normalizeInstructions(parsed));
+
+ return getBoundingBoxFromInstructions(unarced);
+};
diff --git a/packages/paths/src/helpers/arc.ts b/packages/paths/src/helpers/arc.ts
index ea3ddc91bc..e3c39aac26 100644
--- a/packages/paths/src/helpers/arc.ts
+++ b/packages/paths/src/helpers/arc.ts
@@ -2,113 +2,31 @@
import type {Point, Properties} from './types';
-export const makeArc = ({
- x0,
- y0,
- rx,
- ry,
- xAxisRotate,
- LargeArcFlag,
- SweepFlag,
- x1,
- y1,
-}: {
- x0: number;
- y0: number;
- rx: number;
- ry: number;
- xAxisRotate: number;
- LargeArcFlag: boolean;
- SweepFlag: boolean;
- x1: number;
- y1: number;
-}): Properties => {
- const lengthProperties = approximateArcLengthOfCurve(300, (t: number) => {
- return pointOnEllipticalArc({
- p0: {x: x0, y: y0},
- rx,
- ry,
- xAxisRotation: xAxisRotate,
- largeArcFlag: LargeArcFlag,
- sweepFlag: SweepFlag,
- p1: {x: x1, y: y1},
- t,
- });
- });
- const length = lengthProperties.arcLength;
-
- const getTotalLength = () => {
- return length;
- };
-
- const getPointAtLength = (fractionLength: number): Point => {
- if (fractionLength < 0) {
- fractionLength = 0;
- } else if (fractionLength > length) {
- fractionLength = length;
- }
-
- const position = pointOnEllipticalArc({
- p0: {x: x0, y: y0},
- rx,
- ry,
- xAxisRotation: xAxisRotate,
- largeArcFlag: LargeArcFlag,
- sweepFlag: SweepFlag,
- p1: {x: x1, y: y1},
- t: fractionLength / length,
- });
-
- return {x: position.x, y: position.y};
- };
-
- const getTangentAtLength = (fractionLength: number): Point => {
- if (fractionLength < 0) {
- fractionLength = 0;
- } else if (fractionLength > length) {
- fractionLength = length;
- }
-
- const point_dist = 0.05; // needs testing
- const p1 = getPointAtLength(fractionLength);
- let p2: Point;
-
- if (fractionLength < 0) {
- fractionLength = 0;
- } else if (fractionLength > length) {
- fractionLength = length;
- }
+const mod = (x: number, m: number) => {
+ return ((x % m) + m) % m;
+};
- if (fractionLength < length - point_dist) {
- p2 = getPointAtLength(fractionLength + point_dist);
- } else {
- p2 = getPointAtLength(fractionLength - point_dist);
- }
+const toRadians = (angle: number) => {
+ return angle * (Math.PI / 180);
+};
- const xDist = p2.x - p1.x;
- const yDist = p2.y - p1.y;
- const dist = Math.sqrt(xDist * xDist + yDist * yDist);
+const distance = (p0: Point, p1: Point) => {
+ return Math.sqrt((p1.x - p0.x) ** 2 + (p1.y - p0.y) ** 2);
+};
- if (fractionLength < length - point_dist) {
- return {x: -xDist / dist, y: -yDist / dist};
- }
+const clamp = (val: number, min: number, max: number) => {
+ return Math.min(Math.max(val, min), max);
+};
- return {x: xDist / dist, y: yDist / dist};
- };
+const angleBetween = (v0: Point, v1: Point) => {
+ const p = v0.x * v1.x + v0.y * v1.y;
+ const n = Math.sqrt((v0.x ** 2 + v0.y ** 2) * (v1.x ** 2 + v1.y ** 2));
+ const sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1 : 1;
+ const angle = sign * Math.acos(p / n);
- return {
- getPointAtLength,
- getTangentAtLength,
- getTotalLength,
- };
+ return angle;
};
-interface PointOnEllipticalArc {
- x: number;
- y: number;
- ellipticalArcAngle: number;
-}
-
const pointOnEllipticalArc = ({
p0,
rx,
@@ -291,27 +209,109 @@ const approximateArcLengthOfCurve = (
};
};
-const mod = (x: number, m: number) => {
- return ((x % m) + m) % m;
-};
+export const makeArc = ({
+ x0,
+ y0,
+ rx,
+ ry,
+ xAxisRotate,
+ LargeArcFlag,
+ SweepFlag,
+ x1,
+ y1,
+}: {
+ x0: number;
+ y0: number;
+ rx: number;
+ ry: number;
+ xAxisRotate: number;
+ LargeArcFlag: boolean;
+ SweepFlag: boolean;
+ x1: number;
+ y1: number;
+}): Properties => {
+ const lengthProperties = approximateArcLengthOfCurve(300, (t: number) => {
+ return pointOnEllipticalArc({
+ p0: {x: x0, y: y0},
+ rx,
+ ry,
+ xAxisRotation: xAxisRotate,
+ largeArcFlag: LargeArcFlag,
+ sweepFlag: SweepFlag,
+ p1: {x: x1, y: y1},
+ t,
+ });
+ });
+ const length = lengthProperties.arcLength;
-const toRadians = (angle: number) => {
- return angle * (Math.PI / 180);
-};
+ const getTotalLength = () => {
+ return length;
+ };
-const distance = (p0: Point, p1: Point) => {
- return Math.sqrt((p1.x - p0.x) ** 2 + (p1.y - p0.y) ** 2);
-};
+ const getPointAtLength = (fractionLength: number): Point => {
+ if (fractionLength < 0) {
+ fractionLength = 0;
+ } else if (fractionLength > length) {
+ fractionLength = length;
+ }
-const clamp = (val: number, min: number, max: number) => {
- return Math.min(Math.max(val, min), max);
-};
+ const position = pointOnEllipticalArc({
+ p0: {x: x0, y: y0},
+ rx,
+ ry,
+ xAxisRotation: xAxisRotate,
+ largeArcFlag: LargeArcFlag,
+ sweepFlag: SweepFlag,
+ p1: {x: x1, y: y1},
+ t: fractionLength / length,
+ });
-const angleBetween = (v0: Point, v1: Point) => {
- const p = v0.x * v1.x + v0.y * v1.y;
- const n = Math.sqrt((v0.x ** 2 + v0.y ** 2) * (v1.x ** 2 + v1.y ** 2));
- const sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1 : 1;
- const angle = sign * Math.acos(p / n);
+ return {x: position.x, y: position.y};
+ };
- return angle;
+ const getTangentAtLength = (fractionLength: number): Point => {
+ if (fractionLength < 0) {
+ fractionLength = 0;
+ } else if (fractionLength > length) {
+ fractionLength = length;
+ }
+
+ const point_dist = 0.05; // needs testing
+ const p1 = getPointAtLength(fractionLength);
+ let p2: Point;
+
+ if (fractionLength < 0) {
+ fractionLength = 0;
+ } else if (fractionLength > length) {
+ fractionLength = length;
+ }
+
+ if (fractionLength < length - point_dist) {
+ p2 = getPointAtLength(fractionLength + point_dist);
+ } else {
+ p2 = getPointAtLength(fractionLength - point_dist);
+ }
+
+ const xDist = p2.x - p1.x;
+ const yDist = p2.y - p1.y;
+ const dist = Math.sqrt(xDist * xDist + yDist * yDist);
+
+ if (fractionLength < length - point_dist) {
+ return {x: -xDist / dist, y: -yDist / dist};
+ }
+
+ return {x: xDist / dist, y: yDist / dist};
+ };
+
+ return {
+ getPointAtLength,
+ getTangentAtLength,
+ getTotalLength,
+ };
};
+
+interface PointOnEllipticalArc {
+ x: number;
+ y: number;
+ ellipticalArcAngle: number;
+}
diff --git a/packages/paths/src/helpers/bezier-functions.ts b/packages/paths/src/helpers/bezier-functions.ts
index 9d93481248..ad0f554ae2 100644
--- a/packages/paths/src/helpers/bezier-functions.ts
+++ b/packages/paths/src/helpers/bezier-functions.ts
@@ -15,15 +15,45 @@ export const cubicPoint = (xs: number[], ys: number[], t: number): Point => {
return {x, y};
};
-export const cubicDerivative = (xs: number[], ys: number[], t: number) => {
- const derivative = quadraticPoint(
- [3 * (xs[1] - xs[0]), 3 * (xs[2] - xs[1]), 3 * (xs[3] - xs[2])],
- [3 * (ys[1] - ys[0]), 3 * (ys[2] - ys[1]), 3 * (ys[3] - ys[2])],
- t,
- );
- return derivative;
+/**
+ * Compute the curve derivative (hodograph) at t.
+ */
+const getDerivative = (derivative: number, t: number, vs: number[]): number => {
+ // the derivative of any 't'-less function is zero.
+ const n = vs.length - 1;
+ let value;
+
+ if (n === 0) {
+ return 0;
+ }
+
+ // direct values? compute!
+ if (derivative === 0) {
+ value = 0;
+ for (let k = 0; k <= n; k++) {
+ value += binomialCoefficients[n][k] * (1 - t) ** (n - k) * t ** k * vs[k];
+ }
+
+ return value;
+ }
+
+ // Still some derivative? go down one order, then try
+ // for the lower order curve's.
+ const _vs = new Array(n);
+ for (let k = 0; k < n; k++) {
+ _vs[k] = n * (vs[k + 1] - vs[k]);
+ }
+
+ return getDerivative(derivative - 1, t, _vs);
};
+function bFunc(xs: number[], ys: number[], t: number) {
+ const xbase = getDerivative(1, t, xs);
+ const ybase = getDerivative(1, t, ys);
+ const combined = xbase * xbase + ybase * ybase;
+ return Math.sqrt(combined);
+}
+
export const getCubicArcLength = (xs: number[], ys: number[], t: number) => {
let correctedT: number;
@@ -49,6 +79,15 @@ export const quadraticPoint = (
return {x, y};
};
+export const cubicDerivative = (xs: number[], ys: number[], t: number) => {
+ const derivative = quadraticPoint(
+ [3 * (xs[1] - xs[0]), 3 * (xs[2] - xs[1]), 3 * (xs[3] - xs[2])],
+ [3 * (ys[1] - ys[0]), 3 * (ys[2] - ys[1]), 3 * (ys[3] - ys[2])],
+ t,
+ );
+ return derivative;
+};
+
export const getQuadraticArcLength = (
xs: number[],
ys: number[],
@@ -92,45 +131,6 @@ export const quadraticDerivative = (xs: number[], ys: number[], t: number) => {
};
};
-function bFunc(xs: number[], ys: number[], t: number) {
- const xbase = getDerivative(1, t, xs);
- const ybase = getDerivative(1, t, ys);
- const combined = xbase * xbase + ybase * ybase;
- return Math.sqrt(combined);
-}
-
-/**
- * Compute the curve derivative (hodograph) at t.
- */
-const getDerivative = (derivative: number, t: number, vs: number[]): number => {
- // the derivative of any 't'-less function is zero.
- const n = vs.length - 1;
- let value;
-
- if (n === 0) {
- return 0;
- }
-
- // direct values? compute!
- if (derivative === 0) {
- value = 0;
- for (let k = 0; k <= n; k++) {
- value += binomialCoefficients[n][k] * (1 - t) ** (n - k) * t ** k * vs[k];
- }
-
- return value;
- }
-
- // Still some derivative? go down one order, then try
- // for the lower order curve's.
- const _vs = new Array(n);
- for (let k = 0; k < n; k++) {
- _vs[k] = n * (vs[k + 1] - vs[k]);
- }
-
- return getDerivative(derivative - 1, t, _vs);
-};
-
export const t2length = (
length: number,
totalLength: number,
diff --git a/packages/paths/src/helpers/remove-a-s-t-curves.ts b/packages/paths/src/helpers/remove-a-s-t-curves.ts
index 0ea95c7772..d8ed110577 100644
--- a/packages/paths/src/helpers/remove-a-s-t-curves.ts
+++ b/packages/paths/src/helpers/remove-a-s-t-curves.ts
@@ -23,6 +23,111 @@ function approximate_unit_arc(theta1: number, delta_theta: number) {
];
}
+function unit_vector_angle(ux: number, uy: number, vx: number, vy: number) {
+ const sign = ux * vy - uy * vx < 0 ? -1 : 1;
+ let dot = ux * vx + uy * vy;
+
+ // Add this to work with arbitrary vectors:
+ // dot /= Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy);
+
+ // rounding errors, e.g. -1.0000000000000002 can screw up this
+ if (dot > 1.0) {
+ dot = 1.0;
+ }
+
+ if (dot < -1.0) {
+ dot = -1.0;
+ }
+
+ return sign * Math.acos(dot);
+}
+
+function get_arc_center({
+ x1,
+ y1,
+ x2,
+ y2,
+ largeArcFlag,
+ sweepFlag,
+ rx,
+ ry,
+ sin_phi,
+ cos_phi,
+}: {
+ x1: number;
+ y1: number;
+ x2: number;
+ y2: number;
+ largeArcFlag: boolean;
+ sweepFlag: boolean;
+ rx: number;
+ ry: number;
+ sin_phi: number;
+ cos_phi: number;
+}) {
+ // Step 1.
+ //
+ // Moving an ellipse so origin will be the middlepoint between our two
+ // points. After that, rotate it to line up ellipse axes with coordinate
+ // axes.
+ //
+ const x1p = (cos_phi * (x1 - x2)) / 2 + (sin_phi * (y1 - y2)) / 2;
+ const y1p = (-sin_phi * (x1 - x2)) / 2 + (cos_phi * (y1 - y2)) / 2;
+
+ const rx_sq = rx * rx;
+ const ry_sq = ry * ry;
+ const x1p_sq = x1p * x1p;
+ const y1p_sq = y1p * y1p;
+
+ // Step 2.
+ //
+ // Compute coordinates of the centre of this ellipse (cx', cy')
+ // in the new coordinate system.
+ //
+ let radicant = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
+
+ if (radicant < 0) {
+ // due to rounding errors it might be e.g. -1.3877787807814457e-17
+ radicant = 0;
+ }
+
+ radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq;
+ radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
+
+ const cxp = ((radicant * rx) / ry) * y1p;
+ const cyp = ((radicant * -ry) / rx) * x1p;
+
+ // Step 3.
+ //
+ // Transform back to get centre coordinates (cx, cy) in the original
+ // coordinate system.
+ //
+ const cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2;
+ const cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2;
+
+ // Step 4.
+ //
+ // Compute angles (theta1, delta_theta).
+ //
+ const v1x = (x1p - cxp) / rx;
+ const v1y = (y1p - cyp) / ry;
+ const v2x = (-x1p - cxp) / rx;
+ const v2y = (-y1p - cyp) / ry;
+
+ const theta1 = unit_vector_angle(1, 0, v1x, v1y);
+ let delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y);
+
+ if (sweepFlag === false && delta_theta > 0) {
+ delta_theta -= TAU;
+ }
+
+ if (sweepFlag === true && delta_theta < 0) {
+ delta_theta += TAU;
+ }
+
+ return [cx, cy, theta1, delta_theta];
+}
+
function arcToCircle({
x1,
y1,
@@ -254,108 +359,3 @@ export const removeATSHVInstructions = (
},
});
};
-
-function get_arc_center({
- x1,
- y1,
- x2,
- y2,
- largeArcFlag,
- sweepFlag,
- rx,
- ry,
- sin_phi,
- cos_phi,
-}: {
- x1: number;
- y1: number;
- x2: number;
- y2: number;
- largeArcFlag: boolean;
- sweepFlag: boolean;
- rx: number;
- ry: number;
- sin_phi: number;
- cos_phi: number;
-}) {
- // Step 1.
- //
- // Moving an ellipse so origin will be the middlepoint between our two
- // points. After that, rotate it to line up ellipse axes with coordinate
- // axes.
- //
- const x1p = (cos_phi * (x1 - x2)) / 2 + (sin_phi * (y1 - y2)) / 2;
- const y1p = (-sin_phi * (x1 - x2)) / 2 + (cos_phi * (y1 - y2)) / 2;
-
- const rx_sq = rx * rx;
- const ry_sq = ry * ry;
- const x1p_sq = x1p * x1p;
- const y1p_sq = y1p * y1p;
-
- // Step 2.
- //
- // Compute coordinates of the centre of this ellipse (cx', cy')
- // in the new coordinate system.
- //
- let radicant = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
-
- if (radicant < 0) {
- // due to rounding errors it might be e.g. -1.3877787807814457e-17
- radicant = 0;
- }
-
- radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq;
- radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
-
- const cxp = ((radicant * rx) / ry) * y1p;
- const cyp = ((radicant * -ry) / rx) * x1p;
-
- // Step 3.
- //
- // Transform back to get centre coordinates (cx, cy) in the original
- // coordinate system.
- //
- const cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2;
- const cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2;
-
- // Step 4.
- //
- // Compute angles (theta1, delta_theta).
- //
- const v1x = (x1p - cxp) / rx;
- const v1y = (y1p - cyp) / ry;
- const v2x = (-x1p - cxp) / rx;
- const v2y = (-y1p - cyp) / ry;
-
- const theta1 = unit_vector_angle(1, 0, v1x, v1y);
- let delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y);
-
- if (sweepFlag === false && delta_theta > 0) {
- delta_theta -= TAU;
- }
-
- if (sweepFlag === true && delta_theta < 0) {
- delta_theta += TAU;
- }
-
- return [cx, cy, theta1, delta_theta];
-}
-
-function unit_vector_angle(ux: number, uy: number, vx: number, vy: number) {
- const sign = ux * vy - uy * vx < 0 ? -1 : 1;
- let dot = ux * vx + uy * vy;
-
- // Add this to work with arbitrary vectors:
- // dot /= Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy);
-
- // rounding errors, e.g. -1.0000000000000002 can screw up this
- if (dot > 1.0) {
- dot = 1.0;
- }
-
- if (dot < -1.0) {
- dot = -1.0;
- }
-
- return sign * Math.acos(dot);
-}
diff --git a/packages/paths/src/normalize-path.ts b/packages/paths/src/normalize-path.ts
index 692effd3a4..94bfeb2896 100644
--- a/packages/paths/src/normalize-path.ts
+++ b/packages/paths/src/normalize-path.ts
@@ -1,18 +1,6 @@
import type {AbsoluteInstruction, Instruction} from './helpers/types';
import {parsePath} from './parse-path';
import {serializeInstructions} from './serialize-instructions';
-
-/**
- * @description Removes all relative coordinates from an SVG path and converts them into absolute coordinates.
- * @param {string} path A valid SVG path
- * @see [Documentation](https://remotion.dev/docs/paths/normalize-path)
- */
-export const normalizePath = (path: string): string => {
- const instructions = parsePath(path);
- const normalized = normalizeInstructions(instructions);
- return serializeInstructions(normalized);
-};
-
export const normalizeInstructions = (
instructions: Instruction[],
): AbsoluteInstruction[] => {
@@ -182,3 +170,14 @@ export const normalizeInstructions = (
return normalized;
};
+
+/**
+ * @description Removes all relative coordinates from an SVG path and converts them into absolute coordinates.
+ * @param {string} path A valid SVG path
+ * @see [Documentation](https://remotion.dev/docs/paths/normalize-path)
+ */
+export const normalizePath = (path: string): string => {
+ const instructions = parsePath(path);
+ const normalized = normalizeInstructions(instructions);
+ return serializeInstructions(normalized);
+};
diff --git a/packages/paths/src/parse-path.ts b/packages/paths/src/parse-path.ts
index fedb5cca23..c326daa505 100644
--- a/packages/paths/src/parse-path.ts
+++ b/packages/paths/src/parse-path.ts
@@ -60,6 +60,33 @@ const makeInstructions = (
const segmentRegExp = /([astvzqmhlc])([^astvzqmhlc]*)/gi;
const numberRegExp = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;
+const parseValues = (
+ args: string,
+ instructionType: Instruction['type'] | 'z',
+) => {
+ const numbers = args.match(numberRegExp);
+ if (!numbers) {
+ if (instructionType === 'Z' || instructionType === 'z') {
+ return [];
+ }
+
+ throw new Error(
+ `Malformed path data: ${instructionType} was expected to have numbers afterwards`,
+ );
+ }
+
+ const expectedArguments = length[instructionType];
+ if (numbers.length % expectedArguments !== 0) {
+ throw new Error(
+ `Malformed path data: ${instructionType} was expected to have a multiple of ${expectedArguments} numbers, but got "${instructionType} ${numbers.join(
+ ' ',
+ )} instead"`,
+ );
+ }
+
+ return numbers.map(Number);
+};
+
/**
* @description Parses an SVG string path into an array of Instruction's.
* @param {string} path
@@ -296,30 +323,3 @@ export const parsePath = (path: string): Instruction[] => {
}, [])
.flat(1);
};
-
-const parseValues = (
- args: string,
- instructionType: Instruction['type'] | 'z',
-) => {
- const numbers = args.match(numberRegExp);
- if (!numbers) {
- if (instructionType === 'Z' || instructionType === 'z') {
- return [];
- }
-
- throw new Error(
- `Malformed path data: ${instructionType} was expected to have numbers afterwards`,
- );
- }
-
- const expectedArguments = length[instructionType];
- if (numbers.length % expectedArguments !== 0) {
- throw new Error(
- `Malformed path data: ${instructionType} was expected to have a multiple of ${expectedArguments} numbers, but got "${instructionType} ${numbers.join(
- ' ',
- )} instead"`,
- );
- }
-
- return numbers.map(Number);
-};
diff --git a/packages/paths/src/warp-path/warp-helpers.ts b/packages/paths/src/warp-path/warp-helpers.ts
index e04aa85ea3..77ed086903 100644
--- a/packages/paths/src/warp-path/warp-helpers.ts
+++ b/packages/paths/src/warp-path/warp-helpers.ts
@@ -5,28 +5,115 @@ export type WarpPathFn = (point: {x: number; y: number}) => {
y: number;
};
-export function svgPathInterpolate(
- path: ReducedInstruction[],
+const euclideanDistance = (points: [number, number][]) => {
+ const startPoint = points[0];
+ const endPoint = points[points.length - 1];
+ let d2 = 0;
+
+ for (let i = 0; i < startPoint.length; i++) {
+ const d = endPoint[i] - startPoint[i];
+ d2 += d ** 2;
+ }
+
+ return Math.sqrt(d2);
+};
+
+export function split(p: number[][], t = 0.5) {
+ const seg0 = [];
+ const seg1 = [];
+ const orders = [p];
+
+ while (orders.length < p.length) {
+ const q = orders[orders.length - 1];
+ const r = [];
+
+ for (let i = 1; i < q.length; i++) {
+ const q0 = q[i - 1];
+ const q1 = q[i];
+ const s = [];
+ const dim = Math.max(q0.length, q1.length);
+
+ for (let j = 0; j < dim; j++) {
+ const s0 = q0[j] || 0;
+ const s1 = q1[j] || 0;
+
+ s.push(s0 + (s1 - s0) * t);
+ }
+
+ r.push(s);
+ }
+
+ orders.push(r);
+ }
+
+ for (let i = 0; i < orders.length; i++) {
+ seg0.push(orders[i][0]);
+ seg1.push(orders[orders.length - 1 - i][i]);
+ }
+
+ return [seg0, seg1];
+}
+
+export function interpolateUntil(
+ points: [number, number][],
threshold: number,
-): ReducedInstruction[] {
- let didWork = false;
+ deltaFunction = euclideanDistance,
+) {
+ const stack = [points];
+ const segments = [];
- const deltaFunction: DeltaFunction = (points) => {
- const linearPoints = [
- points[0].slice(0, 2),
- points[points.length - 1].slice(0, 2),
- ] as [number, number][];
+ while (stack.length > 0) {
+ const currentPoints = stack.pop() as [number, number][];
- const delta = euclideanDistance(linearPoints);
- didWork = didWork || delta > threshold;
+ if (deltaFunction(currentPoints) > threshold) {
+ const newPoints = split(currentPoints);
- return delta;
- };
+ // Add new segments backwards so they end up in correct order
+ for (let i = newPoints.length - 1; i >= 0; i--) {
+ stack.push(newPoints[i] as [number, number][]);
+ }
+ } else {
+ segments.push(currentPoints);
+ }
+ }
- return warpInterpolate(path, threshold, deltaFunction);
+ return segments;
}
-type DeltaFunction = (points: [number, number][]) => number;
+export function createLineSegment(points: number[][]): ReducedInstruction {
+ switch (points.length) {
+ case 2:
+ return {
+ type: 'L',
+ x: points[1][0],
+ y: points[1][1],
+ };
+
+ case 3:
+ return {
+ type: 'Q',
+ cpx: points[1][0],
+ cpy: points[1][1],
+ x: points[2][0],
+ y: points[2][1],
+ };
+
+ case 4:
+ return {
+ type: 'C',
+ cp1x: points[1][0],
+ cp1y: points[1][1],
+ cp2x: points[2][0],
+ cp2y: points[2][1],
+ x: points[3][0],
+ y: points[3][1],
+ };
+ default:
+ throw new Error(
+ 'Expected 2, 3 or 4 points for a line segment, got ' + points.length,
+ );
+ }
+}
function warpInterpolate(
path: ReducedInstruction[],
@@ -75,6 +162,29 @@ function warpInterpolate(
.flat(1);
}
+export function svgPathInterpolate(
+ path: ReducedInstruction[],
+ threshold: number,
+): ReducedInstruction[] {
+ let didWork = false;
+
+ const deltaFunction: DeltaFunction = (points) => {
+ const linearPoints = [
+ points[0].slice(0, 2),
+ points[points.length - 1].slice(0, 2),
+ ] as [number, number][];
+
+ const delta = euclideanDistance(linearPoints);
+ didWork = didWork || delta > threshold;
+
+ return delta;
+ };
+
+ return warpInterpolate(path, threshold, deltaFunction);
+}
+
+type DeltaFunction = (points: [number, number][]) => number;
+
export const warpTransform = (
path: ReducedInstruction[],
transformer: WarpPathFn,
@@ -180,113 +290,3 @@ export const fixZInstruction = (
})
.flat(1);
};
-
-const euclideanDistance = (points: [number, number][]) => {
- const startPoint = points[0];
- const endPoint = points[points.length - 1];
- let d2 = 0;
-
- for (let i = 0; i < startPoint.length; i++) {
- const d = endPoint[i] - startPoint[i];
- d2 += d ** 2;
- }
-
- return Math.sqrt(d2);
-};
-
-export function interpolateUntil(
- points: [number, number][],
- threshold: number,
- deltaFunction = euclideanDistance,
-) {
- const stack = [points];
- const segments = [];
-
- while (stack.length > 0) {
- const currentPoints = stack.pop() as [number, number][];
-
- if (deltaFunction(currentPoints) > threshold) {
- const newPoints = split(currentPoints);
-
- // Add new segments backwards so they end up in correct order
- for (let i = newPoints.length - 1; i >= 0; i--) {
- stack.push(newPoints[i] as [number, number][]);
- }
- } else {
- segments.push(currentPoints);
- }
- }
-
- return segments;
-}
-
-export function split(p: number[][], t = 0.5) {
- const seg0 = [];
- const seg1 = [];
- const orders = [p];
-
- while (orders.length < p.length) {
- const q = orders[orders.length - 1];
- const r = [];
-
- for (let i = 1; i < q.length; i++) {
- const q0 = q[i - 1];
- const q1 = q[i];
- const s = [];
- const dim = Math.max(q0.length, q1.length);
-
- for (let j = 0; j < dim; j++) {
- const s0 = q0[j] || 0;
- const s1 = q1[j] || 0;
-
- s.push(s0 + (s1 - s0) * t);
- }
-
- r.push(s);
- }
-
- orders.push(r);
- }
-
- for (let i = 0; i < orders.length; i++) {
- seg0.push(orders[i][0]);
- seg1.push(orders[orders.length - 1 - i][i]);
- }
-
- return [seg0, seg1];
-}
-
-export function createLineSegment(points: number[][]): ReducedInstruction {
- switch (points.length) {
- case 2:
- return {
- type: 'L',
- x: points[1][0],
- y: points[1][1],
- };
-
- case 3:
- return {
- type: 'Q',
- cpx: points[1][0],
- cpy: points[1][1],
- x: points[2][0],
- y: points[2][1],
- };
-
- case 4:
- return {
- type: 'C',
- cp1x: points[1][0],
- cp1y: points[1][1],
- cp2x: points[2][0],
- cp2y: points[2][1],
- x: points[3][0],
- y: points[3][1],
- };
- default:
- throw new Error(
- 'Expected 2, 3 or 4 points for a line segment, got ' + points.length,
- );
- }
-}
diff --git a/packages/player-example/src/App.tsx b/packages/player-example/src/App.tsx
index 6bbae98de4..1c57bfe05b 100644
--- a/packages/player-example/src/App.tsx
+++ b/packages/player-example/src/App.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
import {
CallbackListener,
ErrorFallback,
diff --git a/packages/player/src/PlaybackrateControl.tsx b/packages/player/src/PlaybackrateControl.tsx
index de00fd613a..e294dcf1f3 100644
--- a/packages/player/src/PlaybackrateControl.tsx
+++ b/packages/player/src/PlaybackrateControl.tsx
@@ -44,6 +44,58 @@ export const Checkmark = () => (
</svg>
);
+const PlaybackrateOption: React.FC<{
+ rate: number;
+ selectedRate: number;
+ onSelect: (rate: number) => void;
+ keyboardSelectedRate: number;
+}> = ({rate, onSelect, selectedRate, keyboardSelectedRate}) => {
+ const onClick: React.MouseEventHandler<HTMLDivElement> = useCallback(
+ (e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ onSelect(rate);
+ },
+ [onSelect, rate],
+ );
+
+ const [hovered, setHovered] = useState(false);
+
+ const onMouseEnter: React.MouseEventHandler<HTMLDivElement> =
+ useCallback(() => {
+ setHovered(true);
+ }, []);
+
+ const onMouseLeave: React.MouseEventHandler<HTMLDivElement> =
+ useCallback(() => {
+ setHovered(false);
+ }, []);
+
+ const actualStyle = useMemo(() => {
+ return {
+ ...rateDiv,
+ backgroundColor:
+ hovered || keyboardSelectedRate === rate ? '#eee' : 'transparent',
+ };
+ }, [hovered, keyboardSelectedRate, rate]);
+
+ return (
+ <div
+ key={rate}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ tabIndex={0}
+ style={actualStyle}
+ onClick={onClick}
+ >
+ <div style={checkmarkContainer}>
+ {rate === selectedRate ? <Checkmark /> : null}
+ </div>
+ {rate.toFixed(1)}x
+ </div>
+ );
+};
+
const PlaybackPopup: React.FC<{
setIsComponentVisible: React.Dispatch<React.SetStateAction<boolean>>;
playbackRates: number[];
@@ -143,58 +195,6 @@ const PlaybackPopup: React.FC<{
);
};
-const PlaybackrateOption: React.FC<{
- rate: number;
- selectedRate: number;
- onSelect: (rate: number) => void;
- keyboardSelectedRate: number;
-}> = ({rate, onSelect, selectedRate, keyboardSelectedRate}) => {
- const onClick: React.MouseEventHandler<HTMLDivElement> = useCallback(
- (e) => {
- e.stopPropagation();
- e.preventDefault();
- onSelect(rate);
- },
- [onSelect, rate],
- );
-
- const [hovered, setHovered] = useState(false);
-
- const onMouseEnter: React.MouseEventHandler<HTMLDivElement> =
- useCallback(() => {
- setHovered(true);
- }, []);
-
- const onMouseLeave: React.MouseEventHandler<HTMLDivElement> =
- useCallback(() => {
- setHovered(false);
- }, []);
-
- const actualStyle = useMemo(() => {
- return {
- ...rateDiv,
- backgroundColor:
- hovered || keyboardSelectedRate === rate ? '#eee' : 'transparent',
- };
- }, [hovered, keyboardSelectedRate, rate]);
-
- return (
- <div
- key={rate}
- onMouseEnter={onMouseEnter}
- onMouseLeave={onMouseLeave}
- tabIndex={0}
- style={actualStyle}
- onClick={onClick}
- >
- <div style={checkmarkContainer}>
- {rate === selectedRate ? <Checkmark /> : null}
- </div>
- {rate.toFixed(1)}x
- </div>
- );
-};
-
const label: React.CSSProperties = {
fontSize: 13,
fontWeight: 'bold',
diff --git a/packages/player/src/use-playback.ts b/packages/player/src/use-playback.ts
index aff8c3c656..27d9db278f 100644
--- a/packages/player/src/use-playback.ts
+++ b/packages/player/src/use-playback.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-use-before-define */
import {useEffect, useRef} from 'react';
import {Internals} from 'remotion';
import {calculateNextFrame} from './calculate-next-frame.js';
diff --git a/packages/renderer/.eslintrc b/packages/renderer/.eslintrc
index f989dec13f..78c857b78e 100644
--- a/packages/renderer/.eslintrc
+++ b/packages/renderer/.eslintrc
@@ -1,5 +1,8 @@
{
"extends": "@jonny",
+ "rules": {
+ "@typescript-eslint/no-use-before-define": "off"
+ },
"overrides": [
{
"files": "src/browser/**",
diff --git a/packages/renderer/src/options/audio-bitrate.tsx b/packages/renderer/src/options/audio-bitrate.tsx
index 5014419bf2..2bdfff661c 100644
--- a/packages/renderer/src/options/audio-bitrate.tsx
+++ b/packages/renderer/src/options/audio-bitrate.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const audioBitrateOption = {
name: 'Audio Bitrate',
diff --git a/packages/renderer/src/options/color-space.tsx b/packages/renderer/src/options/color-space.tsx
index 476f83707a..d9126cc6c8 100644
--- a/packages/renderer/src/options/color-space.tsx
+++ b/packages/renderer/src/options/color-space.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const validColorSpaces = ['default', 'bt709'] as const;
diff --git a/packages/renderer/src/options/crf.tsx b/packages/renderer/src/options/crf.tsx
index dc93f0f5d3..f80766a380 100644
--- a/packages/renderer/src/options/crf.tsx
+++ b/packages/renderer/src/options/crf.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const crfOption = {
name: 'CRF',
diff --git a/packages/renderer/src/options/delete-after.tsx b/packages/renderer/src/options/delete-after.tsx
index 74842463cf..e7904da499 100644
--- a/packages/renderer/src/options/delete-after.tsx
+++ b/packages/renderer/src/options/delete-after.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const deleteAfterOption = {
name: 'Lambda render expiration',
diff --git a/packages/renderer/src/options/enable-multiprocess-on-linux.tsx b/packages/renderer/src/options/enable-multiprocess-on-linux.tsx
index 10fc4c2490..5f5c11b01b 100644
--- a/packages/renderer/src/options/enable-multiprocess-on-linux.tsx
+++ b/packages/renderer/src/options/enable-multiprocess-on-linux.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const enableMultiprocessOnLinuxOption = {
name: 'Enable Multiprocess on Linux',
diff --git a/packages/renderer/src/options/enforce-audio.tsx b/packages/renderer/src/options/enforce-audio.tsx
index 7bd41d9b34..073e630c8d 100644
--- a/packages/renderer/src/options/enforce-audio.tsx
+++ b/packages/renderer/src/options/enforce-audio.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const enforceAudioOption = {
name: 'Enforce Audio Track',
diff --git a/packages/renderer/src/options/folder-expiry.tsx b/packages/renderer/src/options/folder-expiry.tsx
index 89d0f89639..b2394fdbc4 100644
--- a/packages/renderer/src/options/folder-expiry.tsx
+++ b/packages/renderer/src/options/folder-expiry.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const folderExpiryOption = {
name: 'Lambda render expiration',
diff --git a/packages/renderer/src/options/jpeg-quality.tsx b/packages/renderer/src/options/jpeg-quality.tsx
index 84b6d23818..b4162d0529 100644
--- a/packages/renderer/src/options/jpeg-quality.tsx
+++ b/packages/renderer/src/options/jpeg-quality.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const jpegQualityOption = {
name: 'JPEG Quality',
diff --git a/packages/renderer/src/options/mute.tsx b/packages/renderer/src/options/mute.tsx
index e0ad6953eb..7026110449 100644
--- a/packages/renderer/src/options/mute.tsx
+++ b/packages/renderer/src/options/mute.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const muteOption = {
name: 'Muted',
diff --git a/packages/renderer/src/options/offthreadvideo-cache-size.tsx b/packages/renderer/src/options/offthreadvideo-cache-size.tsx
index 8ad798fc3a..c89a507ecf 100644
--- a/packages/renderer/src/options/offthreadvideo-cache-size.tsx
+++ b/packages/renderer/src/options/offthreadvideo-cache-size.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const offthreadVideoCacheSizeInBytesOption = {
name: 'OffthreadVideo cache size',
diff --git a/packages/renderer/src/options/scale.tsx b/packages/renderer/src/options/scale.tsx
index 652fb2c70b..674466a9ff 100644
--- a/packages/renderer/src/options/scale.tsx
+++ b/packages/renderer/src/options/scale.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const scaleOption = {
name: 'Scale',
diff --git a/packages/renderer/src/options/video-bitrate.tsx b/packages/renderer/src/options/video-bitrate.tsx
index df448cee46..505f1e21f8 100644
--- a/packages/renderer/src/options/video-bitrate.tsx
+++ b/packages/renderer/src/options/video-bitrate.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const videoBitrate = {
name: 'Video Bitrate',
diff --git a/packages/renderer/src/options/video-codec.tsx b/packages/renderer/src/options/video-codec.tsx
index 68a27739e1..723b6a12df 100644
--- a/packages/renderer/src/options/video-codec.tsx
+++ b/packages/renderer/src/options/video-codec.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const videoCodecOption = {
name: 'Codec',
diff --git a/packages/renderer/src/options/webhook-custom-data.tsx b/packages/renderer/src/options/webhook-custom-data.tsx
index 9469fbbbc2..996303e1b0 100644
--- a/packages/renderer/src/options/webhook-custom-data.tsx
+++ b/packages/renderer/src/options/webhook-custom-data.tsx
@@ -1,4 +1,4 @@
-import {AnyRemotionOption} from './option';
+import type {AnyRemotionOption} from './option';
export const webhookCustomDataOption = {
name: 'Webhook custom data',