🎥 Make videos programmatically with React
Scope and cache keyframe trim source analysis
JonnyBurger6d2aab2a7da6
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsxindex 126ad86e1f..3c4abb7155 100644--- a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx@@ -1828,12 +1828,34 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{const initialEdgeClientY = handleRect.top;const initialTimelineEdge = latestRef.current.initialEdgeFrame;+ const getTargets = (statuses: PropStatuses) =>+ canCalculateDelta+ ? (getTimelineSequenceLeftEdgeDragTargets({+ draggedNodePathInfo: latestNodePathInfo,+ selectedItems: latestSelectedItems,+ sequences,+ overrideIdsToNodePaths,+ propStatuses: statuses,+ timelineDurationInFrames,+ trimBeforeOnly,+ rippleEdit: mode === 'ripple',+ }) ?? [])+ : [];+ const initialTargets = getTargets(propStatuses);+stopPointerSessionRef.current?.();stopPointerSessionRef.current = startPreparedPointerSession({event: downEvent,captureTarget,prepare: () =>- loadKeyframeTrimConstraints({propStatuses, overrideIdsToNodePaths}),+ loadKeyframeTrimConstraints({+ propStatuses,+ overrideIdsToNodePaths,+ sequences,+ affectedNodePaths: initialTargets.map(+ (target) => target.ripplePrevious?.nodePath ?? target.nodePath,+ ),+ }),onCancel: () => {stopPointerSessionRef.current = null;finishDrag(false);@@ -1844,18 +1866,7 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{3000,),onReady: (preparedPropStatuses) => {- const targets = canCalculateDelta- ? (getTimelineSequenceLeftEdgeDragTargets({- draggedNodePathInfo: latestNodePathInfo,- selectedItems: latestSelectedItems,- sequences,- overrideIdsToNodePaths,- propStatuses: preparedPropStatuses,- timelineDurationInFrames,- trimBeforeOnly,- rippleEdit: mode === 'ripple',- }) ?? [])- : [];+ const targets = getTargets(preparedPropStatuses);const draggedKey = stringifySequenceSubscriptionKey(latestNodePathInfo.sequenceSubscriptionKey,);@@ -2771,12 +2782,34 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{const initialEdgeClientY = handleRect.top;const initialTimelineEdge = latestRef.current.initialEdgeFrame;+ const getTargets = (statuses: PropStatuses) =>+ canCalculateDelta+ ? (getTimelineSequenceDurationDragTargets({+ draggedNodePathInfo: latestNodePathInfo,+ draggedSequenceMediaDurationDragLimits:+ latestMediaDurationDragLimits,+ selectedSequenceMediaDurationDragLimits:+ mediaDurationDragLimitsRegistry?.current ?? null,+ selectedItems: latestSelectedItems,+ sequences,+ overrideIdsToNodePaths,+ propStatuses: statuses,+ timelineDurationInFrames,+ }) ?? [])+ : [];+ const initialTargets = getTargets(propStatuses);+stopPointerSessionRef.current?.();stopPointerSessionRef.current = startPreparedPointerSession({event: downEvent,captureTarget,prepare: () =>- loadKeyframeTrimConstraints({propStatuses, overrideIdsToNodePaths}),+ loadKeyframeTrimConstraints({+ propStatuses,+ overrideIdsToNodePaths,+ sequences,+ affectedNodePaths: initialTargets.map((target) => target.nodePath),+ }),onCancel: () => {stopPointerSessionRef.current = null;finishDrag(false);@@ -2787,20 +2820,7 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{3000,),onReady: (preparedPropStatuses) => {- const targets = canCalculateDelta- ? (getTimelineSequenceDurationDragTargets({- draggedNodePathInfo: latestNodePathInfo,- draggedSequenceMediaDurationDragLimits:- latestMediaDurationDragLimits,- selectedSequenceMediaDurationDragLimits:- mediaDurationDragLimitsRegistry?.current ?? null,- selectedItems: latestSelectedItems,- sequences,- overrideIdsToNodePaths,- propStatuses: preparedPropStatuses,- timelineDurationInFrames,- }) ?? [])- : [];+ const targets = getTargets(preparedPropStatuses);const draggedKey = stringifySequenceSubscriptionKey(latestNodePathInfo.sequenceSubscriptionKey,);diff --git a/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.ts b/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.tsindex 2bd1106b0b..fb94dd43c4 100644--- a/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.ts+++ b/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.ts@@ -1,57 +1,176 @@-import type {OverrideIdToNodePaths, PropStatuses} from 'remotion';+import type {+ CanUpdateSequencePropsResponseTrue,+ OverrideIdToNodePaths,+ PropStatuses,+ SequencePropsSubscriptionKey,+ TSequence,+} from 'remotion';import {Internals} from 'remotion';import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';+import {+ subscribeToPreviewServerConnectionState,+ subscribeToPreviewServerEvents,+} from '../../helpers/preview-server-events';++type CachedSource = {+ contents: string;+ constraints: Map<+ string,+ CanUpdateSequencePropsResponseTrue['durationDependentKeyframes']+ >;+};+const sourceCache = new Map<string, Promise<CachedSource>>();+let subscribedToSourceChanges = false;export const loadKeyframeTrimConstraints = async ({propStatuses,overrideIdsToNodePaths,+ sequences,+ affectedNodePaths,}: {propStatuses: PropStatuses;overrideIdsToNodePaths: OverrideIdToNodePaths;+ sequences: readonly TSequence[];+ affectedNodePaths: readonly SequencePropsSubscriptionKey[];}): Promise<PropStatuses> => {- const sources = new Map(- Object.values(overrideIdsToNodePaths).flatMap((nodePath) => {- const key = Internals.makeSequencePropsSubscriptionKey(nodePath);- return propStatuses[key]?.canUpdate ? [[key, nodePath] as const] : [];- }),+ const affectedKeys = new Set(+ affectedNodePaths.map(Internals.makeSequencePropsSubscriptionKey),);+ const children = new Map<string, TSequence[]>();+ const pending: TSequence[] = [];+ for (const sequence of sequences) {+ const nodePath =+ sequence.controls && overrideIdsToNodePaths[sequence.controls.overrideId];+ if (+ nodePath &&+ affectedKeys.has(Internals.makeSequencePropsSubscriptionKey(nodePath))+ ) {+ pending.push(sequence);+ }++ if (sequence.parent !== null) {+ const siblings = children.get(sequence.parent) ?? [];+ siblings.push(sequence);+ children.set(sequence.parent, siblings);+ }+ }++ const sources = new Map<string, SequencePropsSubscriptionKey>();+ const visited = new Set<string>();+ for (let index = 0; index < pending.length; index++) {+ const sequence = pending[index];+ if (visited.has(sequence.id)) continue;+ visited.add(sequence.id);+ pending.push(...(children.get(sequence.id) ?? []));+ const nodePath =+ sequence.controls && overrideIdsToNodePaths[sequence.controls.overrideId];+ if (!nodePath) continue;+ const key = Internals.makeSequencePropsSubscriptionKey(nodePath);+ if (propStatuses[key]?.canUpdate) sources.set(key, nodePath);+ }+if (sources.size === 0) return propStatuses;- // Neither the parser nor source files are loaded during rendering or prop- // subscription updates. Keep this snapshot local to the editing gesture.+ if (!subscribedToSourceChanges) {+ subscribedToSourceChanges = true;+ // Invalidation is cheap and never fetches or scans source. Watcher events+ // cover edits/undo; HMR also covers changed component/effect identities.+ subscribeToPreviewServerEvents((event) => {+ if (event.type === 'hmr' || event.type === 'init') {+ sourceCache.clear();+ } else if (event.type === 'sequence-node-paths-remapped') {+ for (const file of event.mutation.files)+ sourceCache.delete(file.absolutePath);+ } else if (event.type === 'sequence-props-updated') {+ sourceCache.delete(event.nodePath.absolutePath);+ } else if (event.type === 'lost-node-path') {+ // This event only carries a possibly relative source-map filename.+ sourceCache.clear();+ } else if (+ event.type === 'watched-file-deleted' ||+ event.type === 'watched-file-undeleted'+ ) {+ sourceCache.delete(event.file);+ }+ });+ subscribeToPreviewServerConnectionState((state) => {+ if (state.type !== 'connected') sourceCache.clear();+ });+ }++ // Only affected clips and descendants need source analysis. Concurrent+ // gestures/inspector fields share in-flight reads as well as parsed results.const browserOperations = getBrowserStudioOperations();- const [codemods, files] = await Promise.all([- import('@remotion/codemods'),- Promise.all(- [- ...new Set([...sources.values()].map((source) => source.absolutePath)),- ].map(async (fileName) => {+ const entries = new Map<string, Promise<CachedSource>>();+ for (const source of sources.values()) {+ const fileName = source.absolutePath;+ if (entries.has(fileName)) continue;+ let entry = sourceCache.get(fileName);+ if (!entry) {+ entry = (async (): Promise<CachedSource> => {+ let contents: string;if (browserOperations) {- const contents = await browserOperations.getFileSource(fileName);- if (contents === null) throw new Error(`Could not load ${fileName}`);- return [fileName, contents] as const;+ const value = await browserOperations.getFileSource(fileName);+ if (value === null) throw new Error(`Could not load ${fileName}`);+ contents = value;+ } else {+ const response = await fetch(+ `/api/file-source?f=${encodeURIComponent(fileName)}`,+ {cache: 'no-store'},+ );+ if (!response.ok) throw new Error(`Could not load ${fileName}`);+ contents = await response.text();}- const response = await fetch(- `/api/file-source?f=${encodeURIComponent(fileName)}`,- );- if (!response.ok) throw new Error(`Could not load ${fileName}`);- return [fileName, await response.text()] as const;- }),+ return {contents, constraints: new Map()};+ })();+ sourceCache.set(fileName, entry);+ const pendingEntry = entry;+ entry.catch(() => {+ if (sourceCache.get(fileName) === pendingEntry)+ sourceCache.delete(fileName);+ });+ }++ entries.set(fileName, entry);+ }++ const [codemods, files] = await Promise.all([+ import('@remotion/codemods'),+ Promise.all(+ [...entries].map(+ async ([fileName, entry]) => [fileName, await entry] as const,+ ),),]);+ for (const [fileName, entry] of entries) {+ if (sourceCache.get(fileName) !== entry) {+ throw new Error(+ 'Source changed while checking trim constraints. Try again.',+ );+ }+ }+const contentsByFile = new Map(files);const result = {...propStatuses};for (const [key, source] of sources) {const status = propStatuses[key];if (!status?.canUpdate) continue;- result[key] = {- ...status,- durationDependentKeyframes:+ const cached = contentsByFile.get(source.absolutePath)!;+ const pathKey = JSON.stringify(source.nodePath);+ if (!cached.constraints.has(pathKey)) {+ cached.constraints.set(+ pathKey,codemods.CodemodsInternals.getDurationDependentKeyframesFromContent({- fileContents: contentsByFile.get(source.absolutePath)!,+ fileContents: cached.contents,nodePath: source.nodePath,}),+ );+ }++ result[key] = {+ ...status,+ durationDependentKeyframes: cached.constraints.get(pathKey)!,};}diff --git a/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts b/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.tsindex 185fb85aac..2254b9036c 100644--- a/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts+++ b/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts@@ -20,12 +20,8 @@ export const useClampSequenceTimingValue = () => {Promise<ReturnType<typeof getTimelineSequenceTimingLimits> | null>>(),);- const preparedPropsRef = useRef<ReturnType<- typeof loadKeyframeTrimConstraints- > | null>(null);const clearTimingLimits = useCallback(() => {limitsRef.current.clear();- preparedPropsRef.current = null;}, []);const clampTimingValue = useCallback(async (@@ -51,10 +47,12 @@ export const useClampSequenceTimingValue = () => {const preparedProps =fieldKey === 'from'? Promise.resolve(propStatusesRef.current)- : (preparedPropsRef.current ??= loadKeyframeTrimConstraints({+ : loadKeyframeTrimConstraints({propStatuses: propStatusesRef.current,overrideIdsToNodePaths: mappingsRef.current,- }));+ sequences,+ affectedNodePaths: [nodePath],+ });const matching = tracks.filter((track) =>track.nodePathInfo &&