🎥 Make videos programmatically with React
Merge main and retain Fiber projection caching in commit adapter
Jonny Burgere781c5798de8
diff --cc packages/sdk/src/commit-outline-collector.tsindex 9bfc531ad6,0000000000..3a89969defmode 100644,000000..100644--- a/packages/sdk/src/commit-outline-collector.ts+++ b/packages/sdk/src/commit-outline-collector.ts@@@ -1,83 -1,0 +1,82 @@@+import type {RefObject} from 'react';+import {Internals} from 'remotion';- import type {Fiber, CommittedMetadata} from './react-commit-types';++import type {FiberProjection} from './project-committed-fiber-tree';++import type {CommittedMetadata} from './react-commit-types';++export type OutlineCollectors = readonly (Element | Text)[][] | null;+- export const createCommitOutlineCollector = () => {++export const createCommitOutlineCollector = (projectionFailed: boolean) => {+ const outlineNodesByRef = new Map<+ RefObject<Element | null>,+ (Element | Text)[]+ >();- let outlineCollectionFailed = false;++ let outlineCollectionFailed = projectionFailed;+ return {+ visit: (- fiber: Fiber,++ fiber: FiberProjection,+ metadata: CommittedMetadata | null,+ outlineCollectors: OutlineCollectors,+ ): OutlineCollectors => {+ let childOutlineCollectors = outlineCollectors;+ if (outlineCollectionFailed) {+ childOutlineCollectors = null;+ } else {+ try {+ // A portal ends the current DOM group, but can contain new sequences.+ // Hidden Offscreen trees must not contribute geometry, including new groups.- const {tag} = fiber;++ const {outline} = fiber;+ const skipOutline =- outlineCollectors === null ||- (tag === 22 && fiber.memoizedState !== null);++ outlineCollectors === null || outline?.type === 'hidden';+ childOutlineCollectors = skipOutline+ ? null- : tag === 4++ : outline?.type === 'portal'+ ? []+ : outlineCollectors;+ if (metadata?.type === 'sequence') {+ const outlineRef = metadata.outlineChildrenRef;+ if (outlineRef !== null) {+ const nodes: (Element | Text)[] = [];+ outlineNodesByRef.set(outlineRef, nodes);+ if (childOutlineCollectors !== null) {+ childOutlineCollectors = [...childOutlineCollectors, nodes];+ }+ }+ }++ if (+ childOutlineCollectors !== null &&+ childOutlineCollectors.length > 0 &&- (tag === 5 || tag === 6) &&- fiber.stateNode !== null++ outline?.type === 'host'+ ) {+ for (const collector of childOutlineCollectors) {- collector.push(fiber.stateNode as Element | Text);++ collector.push(outline.node);+ }++ // Only first-level DOM nodes belong to this group. Keep traversing+ // for sequence order and for new groups nested inside this element.+ childOutlineCollectors = [];+ }+ } catch {+ // Discard incomplete geometry for this commit without losing registrations.+ // The next commit retries outline collection with a fresh map.+ outlineCollectionFailed = true;+ outlineNodesByRef.clear();+ childOutlineCollectors = null;+ }+ }++ return childOutlineCollectors;+ },+ publish: () => {+ for (const [ref, nodes] of outlineNodesByRef) {+ try {+ Internals.SequenceOutlineInternals.setNodes(ref, nodes);+ } catch {+ // A failed outline publication is retried on the next commit.+ }+ }++ return outlineNodesByRef.size;+ },+ };+};diff --cc packages/sdk/src/project-committed-fiber-tree.tsindex 0000000000,0000000000..9cd5f16132new file mode 100644--- /dev/null+++ b/packages/sdk/src/project-committed-fiber-tree.ts@@@ -1,0 -1,0 +1,123 @@@++import {++ getCommittedMetadata,++ type Fiber,++ type CommittedMetadata,++} from './react-commit-types';++++export type FiberProjection = {++ readonly metadata: CommittedMetadata | null;++ readonly outline:++ | {readonly type: 'host'; readonly node: Element | Text}++ | {readonly type: 'portal' | 'hidden'}++ | null;++ readonly children: readonly FiberProjection[];++ readonly hasMetadata: boolean;++};++++type CommittedFiberSnapshot = {++ readonly fiber: Fiber;++ readonly child: Fiber | null;++ readonly children: readonly CommittedFiberSnapshot[];++ readonly projectedChildren: readonly FiberProjection[];++ readonly projection: FiberProjection | null;++};++++export type FiberProjectionCache = {++ current: CommittedFiberSnapshot | null;++};++++export const projectCommittedFiberTree = (++ root: Fiber,++ cache: FiberProjectionCache | null,++) => {++ let outlineCollectionFailed = false;++ const visit = (++ fiber: Fiber,++ previous: CommittedFiberSnapshot | null,++ ): CommittedFiberSnapshot => {++ const metadata = getCommittedMetadata(fiber.memoizedProps);++ let outline: FiberProjection['outline'] = null;++ if (!outlineCollectionFailed) {++ try {++ if (fiber.tag === 22 && fiber.memoizedState !== null) {++ outline = {type: 'hidden'};++ } else if (fiber.tag === 4) {++ outline = {type: 'portal'};++ } else if (++ (fiber.tag === 5 || fiber.tag === 6) &&++ fiber.stateNode !== null++ ) {++ outline = {type: 'host', node: fiber.stateNode as Element | Text};++ }++ } catch {++ outlineCollectionFailed = true;++ }++ }++++ let childSnapshots: readonly CommittedFiberSnapshot[];++ let projectedChildren: readonly FiberProjection[];++ if (previous !== null && previous.child === fiber.child) {++ // React clones the direct child list before rendering descendants. A++ // retained child pointer is its own bailout check. Keep snapshots in the++ // last committed tree, not a lifetime Fiber cache: alternates are recycled.++ childSnapshots = previous.children;++ projectedChildren = previous.projectedChildren;++ } else {++ const previousChildren = new Map(++ previous?.children.map((entry) => [entry.fiber, entry]),++ );++ const snapshots: CommittedFiberSnapshot[] = [];++ const next: FiberProjection[] = [];++ let {child} = fiber;++ while (child !== null) {++ const childSnapshot = visit(++ child,++ previousChildren.get(child) ??++ (child.alternate++ ? (previousChildren.get(child.alternate) ?? null)++ : null),++ );++ snapshots.push(childSnapshot);++ if (childSnapshot.projection !== null) {++ next.push(childSnapshot.projection);++ }++++ child = child.sibling;++ }++++ childSnapshots = snapshots;++ projectedChildren = next;++ }++++ let children = projectedChildren;++ if (outline !== null) {++ // Host nodes end the incoming DOM frontier; portals and hidden trees++ // cannot contribute to it. Only nested registration scopes remain useful.++ children = children.filter((child) => child.hasMetadata);++ }++++ const hasMetadata =++ metadata !== null || children.some((child) => child.hasMetadata);++ const projection: FiberProjection | null =++ metadata === null && outline?.type !== 'host' && children.length === 0++ ? null++ : metadata === null && outline === null && children.length === 1++ ? children[0]++ : {metadata, outline, children, hasMetadata};++ return {++ fiber,++ child: fiber.child,++ children: childSnapshots,++ projectedChildren,++ projection,++ };++ };++++ const snapshot = visit(root, cache?.current ?? null);++ if (cache !== null) {++ // Geometry failures must retry from live Fibers on the next commit.++ cache.current = outlineCollectionFailed ? null : snapshot;++ }++++ return {projection: snapshot.projection, outlineCollectionFailed};++};diff --cc packages/sdk/src/react-commit-adapter.tsindex 3a7167725e,0000000000..883a465760mode 100644,000000..100644--- a/packages/sdk/src/react-commit-adapter.ts+++ b/packages/sdk/src/react-commit-adapter.ts@@@ -1,175 -1,0 +1,206 @@@+import {Internals} from 'remotion';+import {+ createCommitOutlineCollector,+ type OutlineCollectors,+} from './commit-outline-collector';+import {+ createCommitRegistryCollector,+ type CommittedSequenceRegistration,+ type CommittedCompositionRegistration,+} from './commit-registry-collector';+import {- getCommittedMetadata,- type Fiber,- type FiberRoot,- type HookTarget,- } from './react-commit-types';++ projectCommittedFiberTree,++ type FiberProjection,++ type FiberProjectionCache,++} from './project-committed-fiber-tree';++import {type FiberRoot, type HookTarget} from './react-commit-types';+const {installationMarker} = Internals.CommittedMetadataInternals;- // Share one committed-tree traversal between registration and DOM discovery.++// Share a cached projection of the committed tree between registration and DOM discovery.+export const collectReactCommit = (+ root: FiberRoot,- ...args: Parameters<typeof createCommitRegistryCollector>++ registrations: Map<string, CommittedSequenceRegistration> | null = null,++ previousRegistrations: ReadonlyMap<++ string,++ CommittedSequenceRegistration++ > | null = null,++ compositionRegistry: {++ readonly registrations: Map<string, CommittedCompositionRegistration>;++ readonly previous: ReadonlyMap<++ string,++ CommittedCompositionRegistration++ > | null;++ } | null = null,++ projectionCache: FiberProjectionCache | null = null,+) => {- const registry = createCommitRegistryCollector(...args);- const outlines = createCommitOutlineCollector();++ const projected = projectCommittedFiberTree(root.current, projectionCache);++ const registry = createCommitRegistryCollector(++ registrations,++ previousRegistrations,++ compositionRegistry,++ );++ const outlines = createCommitOutlineCollector(++ projected.outlineCollectionFailed,++ );+ const visit = (- fiber: Fiber,++ fiber: FiberProjection,+ currentSequenceManagerId: string | null,+ currentCompositionManagerId: string | null,+ outlineCollectors: OutlineCollectors,+ ) => {- const metadata = getCommittedMetadata(fiber.memoizedProps);++ const {metadata} = fiber;++ if (!fiber.hasMetadata && !outlineCollectors?.length) {++ return;++ }+++ const sequenceManagerId =+ metadata?.type === 'sequence-manager'+ ? metadata.id+ : currentSequenceManagerId;+ const compositionManagerId =+ metadata?.type === 'composition-manager'+ ? metadata.id+ : currentCompositionManagerId;+ registry.visit(metadata, sequenceManagerId, compositionManagerId);+ const childOutlines =+ outlineCollectors === null && metadata === null+ ? null+ : outlines.visit(fiber, metadata, outlineCollectors);- let {child} = fiber;- while (child !== null) {++ for (const child of fiber.children) {+ visit(child, sequenceManagerId, compositionManagerId, childOutlines);- child = child.sibling;+ }+ };+- visit(root.current, null, null, []);++ if (projected.projection !== null) {++ visit(projected.projection, null, null, []);++ }++ return {...registry.getSnapshot(), outlineCount: outlines.publish()};+};++export const installReactCommitObserver = (target: HookTarget): boolean => {+ const hook = target.__REACT_DEVTOOLS_GLOBAL_HOOK__;+ if (!hook?.supportsFiber) {+ return false;+ }++ if (hook[installationMarker] === true) {+ return true;+ }++ const previousOnCommitFiberRoot = hook.onCommitFiberRoot;+ const registrationsByRoot = new WeakMap<+ FiberRoot,+ Map<string, CommittedSequenceRegistration>+ >();+ const compositionRegistrationsByRoot = new WeakMap<+ FiberRoot,+ Map<string, CommittedCompositionRegistration>+ >();+++ const projectionCachesByRoot = new WeakMap<FiberRoot, FiberProjectionCache>();+++ hook.onCommitFiberRoot = function (...args) {+ let order: ReturnType<typeof collectReactCommit> | null = null;+ try {+ const [, root] = args;++ const projectionCache = projectionCachesByRoot.get(root) ?? {++ current: null,++ };++ projectionCachesByRoot.set(root, projectionCache);+ const registrations = new Map<string, CommittedSequenceRegistration>();+ const previousRegistrations = registrationsByRoot.get(root);+ const compositionRegistrations = new Map<+ string,+ CommittedCompositionRegistration+ >();+ const previousCompositionRegistrations =+ compositionRegistrationsByRoot.get(root);+ order = collectReactCommit(+ root,+ registrations,+ previousRegistrations ?? null,+ {+ registrations: compositionRegistrations,+ previous: previousCompositionRegistrations ?? null,+ },++ projectionCache,+ );+ registrationsByRoot.set(root, registrations);+ compositionRegistrationsByRoot.set(root, compositionRegistrations);+ for (const [managerId, registration] of registrations) {+ if (registration !== previousRegistrations?.get(managerId)) {+ registration.onCommit(+ registration.sequences,+ registration.sequenceIds,+ );+ }+ }++ if (previousRegistrations) {+ for (const [managerId, registration] of previousRegistrations) {+ if (!registrations.has(managerId)) {+ registration.onCommit([], []);+ }+ }+ }++ for (const [managerId, registration] of compositionRegistrations) {+ if (registration !== previousCompositionRegistrations?.get(managerId)) {+ registration.onCommit(registration.snapshot);+ }+ }++ if (previousCompositionRegistrations) {+ for (const [+ managerId,+ registration,+ ] of previousCompositionRegistrations) {+ if (!compositionRegistrations.has(managerId)) {+ registration.onCommit({+ compositions: [],+ folders: [],+ orderIds: [],+ });+ }+ }+ }+ } catch {+ // A registration collection or delivery failure permanently selects effect+ // fallback for this hook. Retrying registration would risk repeated teardown.++ projectionCachesByRoot.delete(args[1]);+ hook[Internals.CommittedMetadataInternals.failureMarker] = true;+ order = null;+ try {+ target.dispatchEvent(+ new CustomEvent(+ Internals.CommittedMetadataInternals.registrationErrorEventName,+ ),+ );+ } catch {+ // Notification failure must not prevent the previous hook from running.+ }+ }++ if (+ order !== null &&+ (order.outlineCount > 0 || order.sequenceManagers.length > 0)+ ) {+ try {+ target.dispatchEvent(+ new CustomEvent(Internals.CommittedMetadataInternals.eventName, {+ detail: {+ sequenceManagers: order.sequenceManagers,+ },+ }),+ );+ } catch {+ // Order notifications are independent of registration and retry next commit.+ }+ }++ return previousOnCommitFiberRoot?.apply(this, args);+ };++ hook[installationMarker] = true;+ return true;+};diff --cc packages/sdk/src/react-commit-types.tsindex ef503ee2e4,0000000000..1203ca9401mode 100644,000000..100644--- a/packages/sdk/src/react-commit-types.ts+++ b/packages/sdk/src/react-commit-types.ts@@@ -1,52 -1,0 +1,53 @@@+import type {ComponentProps} from 'react';+import {Internals} from 'remotion';+export type Fiber = {++ readonly alternate: Fiber | null;+ readonly child: Fiber | null;+ readonly memoizedProps: unknown;+ readonly sibling: Fiber | null;+ readonly tag: number | null;+ readonly stateNode: unknown;+ readonly memoizedState: unknown;+};++export type FiberRoot = {+ readonly current: Fiber;+};++type DevToolsHook = {+ readonly supportsFiber?: boolean;+ onCommitFiberRoot?: (+ this: DevToolsHook,+ rendererId: number,+ root: FiberRoot,+ priorityLevel: unknown,+ didError: boolean,+ ) => unknown;+ [key: symbol]: unknown;+};++export type HookTarget = Window &+ typeof globalThis & {+ __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook;+ };++const {metadataProp} = Internals.CommittedMetadataInternals;++export type CommittedMetadata = NonNullable<+ ComponentProps<+ typeof Internals.CommittedMetadataProvider+ >[typeof metadataProp]+>;++export const getCommittedMetadata = (+ props: unknown,+): CommittedMetadata | null => {+ if (typeof props !== 'object' || props === null) {+ return null;+ }++ const metadata: unknown = Reflect.get(props, metadataProp);+ return typeof metadata === 'object' && metadata !== null+ ? (metadata as CommittedMetadata)+ : null;+};diff --cc packages/studio/src/test/fiber-sequence-order-observer.test.tsindex 3c2b51d65b,8f7764f80e..4a161b3010--- a/packages/studio/src/test/fiber-sequence-order-observer.test.ts+++ b/packages/studio/src/test/fiber-sequence-order-observer.test.ts@@@ -2,9 -2,11 +2,10 @@@ import {afterEach, expect, test} from 'import {CanvasInternals} from '@remotion/sdk';import {Internals} from 'remotion';-const {collectCommitOrderFromFiber, installFiberCommitOrderObserver} =- CanvasInternals;+const {collectReactCommit, installReactCommitObserver} = CanvasInternals;type TestFiber = {+ alternate: TestFiber | null;child: TestFiber | null;memoizedProps: unknown;sibling: TestFiber | null;@@@ -223,3 -226,173 +225,173 @@@ test('chains the existing commit hook a},]);});++ test('reuses retained subtrees on one root and refreshes reordered and removed metadata', () => {+ const outlineRef = Internals.SequenceOutlineInternals.createRef();+ const node = document.createElement('div');+ let retainedReads = 0;+ const host = makeFiber();+ host.tag = 5;+ host.stateNode = node;+ Object.defineProperty(host, 'memoizedProps', {+ get: () => {+ retainedReads++;+ return {};+ },+ });+ const first = makeFiber({+ props: {+ _remotionCommitMetadata: {+ type: 'sequence',+ id: 'first',+ value: null,+ outlineChildrenRef: outlineRef,+ },+ },+ children: [host],+ });+ const second = makeFiber({+ props: {+ _remotionCommitMetadata: {+ type: 'sequence',+ id: 'second',+ value: null,+ outlineChildrenRef: null,+ },+ },+ });+ const composition = makeFiber({+ props: {+ _remotionCommitMetadata: {+ type: 'composition',+ id: 'video',+ value: {id: 'video', durationInFrames: 100},+ },+ },+ });+ const snapshots: unknown[] = [];+ const compositionManager = makeFiber({+ props: {+ _remotionCommitMetadata: {+ type: 'composition-manager',+ id: 'compositions',+ onCommit: (snapshot: unknown) => snapshots.push(snapshot),+ },+ },+ children: [composition],+ });+ const manager = makeFiber({+ props: {+ _remotionCommitMetadata: {+ type: 'sequence-manager',+ id: 'sequences',+ onCommit: null,+ },+ },+ children: [first, second, compositionManager],+ });+ const root = {current: makeFiber({children: [manager]})};+ const hook = {+ supportsFiber: true,+ onCommitFiberRoot: (..._args: unknown[]) => undefined,+ };+ Reflect.set(window, '__REACT_DEVTOOLS_GLOBAL_HOOK__', hook);+ const events: unknown[] = [];+ const onOrder = (event: Event) => {+ events.push((event as CustomEvent).detail);+ };++ window.addEventListener(+ Internals.CommittedMetadataInternals.eventName,+ onOrder,+ );+ const commitAndCompare = (sequenceIds: string[], expectedReads: number) => {+ const before = retainedReads;+ hook.onCommitFiberRoot(1, root, null, false);+ expect(retainedReads - before).toBe(expectedReads);+ const cachedNodes = Internals.SequenceOutlineInternals.getNodes(outlineRef);+ const registrations: NonNullable<- Parameters<typeof collectCommitOrderFromFiber>[3]++ Parameters<typeof collectReactCommit>[3]+ >['registrations'] = new Map();- const fresh = collectCommitOrderFromFiber(root, null, null, {++ const fresh = collectReactCommit(root, null, null, {+ registrations,+ previous: null,+ });+ expect(events.at(-1)).toEqual({sequenceManagers: fresh.sequenceManagers});+ expect(fresh.sequenceManagers).toEqual([+ {managerId: 'sequences', sequenceIds},+ ]);+ expect(fresh.outlineCount).toBe(1);+ expect(cachedNodes).toEqual([node]);+ expect(Internals.SequenceOutlineInternals.getNodes(outlineRef)).toEqual(+ cachedNodes,+ );+ expect(snapshots.at(-1)).toEqual(+ registrations.get('compositions')?.snapshot,+ );+ };++ try {- expect(installFiberCommitOrderObserver(window)).toBe(true);++ expect(installReactCommitObserver(window)).toBe(true);+ commitAndCompare(['first', 'second'], 1);+ // A new root Fiber with the exact retained child list must skip descendants.+ root.current = {...root.current, alternate: root.current};+ commitAndCompare(['first', 'second'], 0);+ expect(snapshots).toHaveLength(1);++ // React uses alternate Fibers for changed/reordered children. The first+ // sequence retains its host child, while composition metadata changes.+ const nextFirst = {...first, alternate: first, sibling: null};+ const nextSecond = {...second, alternate: second, sibling: null};+ const nextComposition = {+ ...composition,+ alternate: composition,+ memoizedProps: {+ _remotionCommitMetadata: {+ type: 'composition',+ id: 'video',+ value: {id: 'video', durationInFrames: 200},+ },+ },+ };+ const nextCompositionManager = makeFiber({+ props: compositionManager.memoizedProps,+ children: [nextComposition],+ });+ nextCompositionManager.alternate = compositionManager;+ const nextManager = makeFiber({+ props: manager.memoizedProps,+ children: [nextSecond, nextFirst, nextCompositionManager],+ });+ nextManager.alternate = manager;+ root.current = {+ ...makeFiber({children: [nextManager]}),+ alternate: root.current,+ };+ commitAndCompare(['second', 'first'], 0);+ expect(snapshots).toHaveLength(2);+ expect(snapshots.at(-1)).toEqual({+ compositions: [{id: 'video', durationInFrames: 200}],+ folders: [],+ orderIds: ['composition:video'],+ });++ const remainingFirst = {...first, alternate: nextFirst, sibling: null};+ const remainingManager = makeFiber({+ props: manager.memoizedProps,+ children: [remainingFirst, nextCompositionManager],+ });+ remainingManager.alternate = nextManager;+ root.current = {+ ...makeFiber({children: [remainingManager]}),+ alternate: root.current,+ };+ commitAndCompare(['first'], 0);+ expect(events).toHaveLength(4);+ } finally {+ window.removeEventListener(+ Internals.CommittedMetadataInternals.eventName,+ onOrder,+ );+ }+ });