The VS Code of video editing, built for agents.
TypeScript
Refactor export functionality and enhance scene handling
konstantin-paulus312f6c585955
diff --git a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsxindex 735cf2b6..eed29ac0 100644--- a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx+++ b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx@@ -17,20 +17,19 @@ import { For, Show, createMemo } from "solid-js";import { toast } from "somoto";import { generateProjectName } from "@/components/engine/db";import { createProject, deleteProject, duplicateProject, ensureProjectsRoot } from "@/projects";-import { Not } from "bitecs";-import { ChildOf, isScene, useQuery } from "@/components/engine";-import { AssetId, getAssetFile } from "@diffusionstudio/runtime";+import { AssetId, ChildOf, Name, Root, Scene, getAssetFile, getActiveEntity, sortByItemIndex } from "@diffusionstudio/runtime";import { assetName } from "@diffusionstudio/assets";-import { useWorld } from "@diffusionstudio/koota-solid";+import { useQuery, useWorld } from "@diffusionstudio/koota-solid";import { useLibrary } from "@/engine/library";import { pickAndImport } from "@/engine/asset-actions";import { projectRoute } from "@/hooks/use-project-route";import { useProject } from "@/context/project";-import { useEngine } from "@/context/engine";import { useExport } from "@/context/export";import { getDefaultExportTemplate } from "@/components/sidebar-right/inspector/export-templates";import { mimeTypeToExtension } from "@/utils";+import type { Entity } from "koota";+export function FileMenu() {const navigate = useNavigate();const project = useProject();@@ -237,23 +236,17 @@ export function FileAssetMenu() {);}-/**- * The last of this menu still on the bitecs engine: the render pipeline- * (`@/context/render` → `@/components/engine/encode`) takes an old-world- * scene, so both the scene it exports and the list below have to come from- * there. Moves to koota with the encoder (see the TODO in inspector/export).- */export function FileExportMenu() {- const { world } = useEngine();+ const world = useWorld();const { exportScene, exportCurrentFrame } = useExport();const handleExportScene = async () => {- const sceneEid = world.selection.scene;- if (sceneEid === null) {+ const scene = getActiveEntity(world);+ if (scene === null) {toast("No active scene to export");return;}- await exportScene(sceneEid, getDefaultExportTemplate());+ await exportScene(scene, getDefaultExportTemplate());};return (@@ -286,15 +279,16 @@ export function FileExportMenu() {}export function FileExportSpecificSceneMenu() {- const { world } = useEngine();+ const world = useWorld();const { exportScene } = useExport();- const c = world.components;- const children = useQuery([c.Geometry, c.Playback, Not(ChildOf('*')), Not(c.Deleted)]);- const scenes = createMemo(() => children().filter((eid) => isScene(world, eid)));+ // Scenes are top-level by definition; the order is the stage's, so the menu+ // reads the way the timeline's scene switcher does.+ const children = useQuery(Scene, ChildOf(world.get(Root)!));+ const scenes = createMemo(() => [...children()].sort(sortByItemIndex));- const handleExport = async (sceneEid: number) => {- await exportScene(sceneEid, getDefaultExportTemplate());+ const handleExport = async (scene: Entity) => {+ await exportScene(scene, getDefaultExportTemplate());};return (@@ -306,9 +300,9 @@ export function FileExportSpecificSceneMenu() {}><For each={scenes()}>- {(sceneEid, index) => (- <DropdownMenuItem onSelect={() => handleExport(sceneEid)}>- {world.components.Name[sceneEid] || `Scene ${index() + 1}`}+ {(scene, index) => (+ <DropdownMenuItem onSelect={() => handleExport(scene)}>+ {scene.get(Name)?.value || `Scene ${index() + 1}`}</DropdownMenuItem>)}</For>diff --git a/apps/web/src/components/sidebar-right/inspector/export-progress.tsx b/apps/web/src/components/sidebar-right/inspector/export-progress.tsxindex e6ac12c4..89787ba9 100644--- a/apps/web/src/components/sidebar-right/inspector/export-progress.tsx+++ b/apps/web/src/components/sidebar-right/inspector/export-progress.tsx@@ -6,9 +6,13 @@ import { Show, Portal } from "solid-js/web";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";import { formatDuration } from "@/utils/formatters";-import type { EncoderConfig } from "@/components/engine/encode/interfaces";+import type { EncoderConfig } from "@diffusionstudio/encoder";-export type ExportConfig = Omit<EncoderConfig, "target" | "scene" | "onProgress">;+/** The settings this overlay reads: the encoder's, less how it is driven. */+export type ExportConfig = Omit<+ EncoderConfig,+ "target" | "scene" | "onProgress" | "realizeScene" | "comment"+>;type ExportProgressProps = {open: boolean;diff --git a/apps/web/src/components/sidebar-right/inspector/export.tsx b/apps/web/src/components/sidebar-right/inspector/export.tsxindex b521fac7..e7ca730e 100644--- a/apps/web/src/components/sidebar-right/inspector/export.tsx+++ b/apps/web/src/components/sidebar-right/inspector/export.tsx@@ -3,7 +3,6 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { Show, createMemo, createSignal } from "solid-js";-import { toast } from "somoto";import { PanelSection } from "@/components/ui/panel-section";import { Button } from "@/components/ui/button";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";@@ -32,6 +31,7 @@ import { useTrait, useWorld } from "@diffusionstudio/koota-solid";import { Computed, FrameRate } from "@diffusionstudio/runtime";import { useDerived } from "@/engine/hooks";import { useProjectConfig } from "@/engine/project-config";+import { useExport } from "@/context/export";import {DEFAULT_EXPORT_TEMPLATE_ID,TEMPLATE_BY_ID,@@ -74,6 +74,7 @@ function templateSettings(id: string): ProjectExportConfig | null {export function ExportPanel(props: ExportPanelProps) {const world = useWorld();const config = useProjectConfig();+ const { exportScene, exporting } = useExport();const entity = () => props.selection[0]!;const [isInspectorOpen, setIsInspectorOpen] = createSignal(false);@@ -131,12 +132,15 @@ export function ExportPanel(props: ExportPanelProps) {setIsInspectorOpen(false);};- const exportScene = () => {- // TODO(koota): render through @diffusionstudio/encoder with- // `{ ...settings(), scene: entity() }` once the export path is on the- // koota world; the settings are already in its shape.- toast("Export is not available yet", {- description: "Exporting is not wired to the new engine yet.",+ // The settings are already the encoder's shape; `template` is the panel's+ // own label for them and no part of how the file is made.+ const runExport = () => {+ const current = settings();+ if (!current) return;+ exportScene(entity(), {+ format: current.format,+ video: current.video,+ audio: current.audio,});};@@ -184,7 +188,7 @@ export function ExportPanel(props: ExportPanelProps) {<TooltipContent>Remove export</TooltipContent></Tooltip></ItemRow>- <Button class="w-full" onClick={exportScene}>+ <Button class="w-full" onClick={runExport} disabled={exporting()}>Export</Button><div class="flex justify-between items-center h-7">diff --git a/apps/web/src/context/export.tsx b/apps/web/src/context/export.tsxindex bb31c191..38c2fc12 100644--- a/apps/web/src/context/export.tsx+++ b/apps/web/src/context/export.tsx@@ -4,8 +4,9 @@import { createContext, useContext, onCleanup, onMount } from "solid-js";import { toast } from "somoto";+import { useWorld } from "@diffusionstudio/koota-solid";+import { Computed, FrameRate, getActiveEntity } from "@diffusionstudio/runtime";import { assert, downloadObject, isInputTarget } from "@/utils";-import { useEngine } from "@/context/engine";import { useEngineContext } from "@/engine";import { useProject } from "@/context/project";import { track } from "@/lib/analytics";@@ -16,10 +17,11 @@ import {getDefaultExportTemplate,} from "@/components/sidebar-right/inspector/export-templates";+import type { Entity } from "koota";import type { JSX, Accessor } from "solid-js";type ExportContextValue = {- exportScene: (sceneEid: number, config: ExportConfig) => Promise<void>;+ exportScene: (scene: Entity, config: ExportConfig) => Promise<void>;exportCurrentFrame: () => Promise<void>;exporting: Accessor<boolean>;};@@ -27,18 +29,17 @@ type ExportContextValue = {const ExportContext = createContext<ExportContextValue>();export function ExportProvider(props: { children: JSX.Element }) {- const engine = useEngine();- const { world } = engine;- const stage = useEngineContext();+ const engine = useEngineContext();+ const world = useWorld();const project = useProject();const exporting = () => !!renderOverlay();- const sceneDurationSeconds = (sceneEid: number) =>- world.components.Computed.duration[sceneEid] / world.frameRate;+ const sceneDurationSeconds = (scene: Entity) =>+ (scene.get(Computed)?.duration ?? 0) / (world.get(FrameRate)?.value || 30);- const exportScene: ExportContextValue["exportScene"] = async (sceneEid, config) => {- if (!sceneEid) return;+ const exportScene: ExportContextValue["exportScene"] = async (scene, config) => {+ if (!scene?.isAlive()) return;const format = config.format ?? "mp4";const mimeType = MIME_TYPES[format];@@ -72,12 +73,12 @@ export function ExportProvider(props: { children: JSX.Element }) {fps: config.video?.fps,video_codec: config.video?.codec,audio_codec: config.audio?.codec,- scene_duration_s: Math.round(sceneDurationSeconds(sceneEid)),+ scene_duration_s: Math.round(sceneDurationSeconds(scene)),});const startedAt = performance.now();try {- const result = await renderScene(engine, { scene: sceneEid, target, config });+ const result = await renderScene(engine, { scene, target, config });if (result.type === "error") {console.error("Export failed:", result.error);@@ -97,7 +98,7 @@ export function ExportProvider(props: { children: JSX.Element }) {format,resolution: config.video?.resolution,fps: config.video?.fps,- scene_duration_s: Math.round(sceneDurationSeconds(sceneEid)),+ scene_duration_s: Math.round(sceneDurationSeconds(scene)),duration_ms: Math.round(performance.now() - startedAt),});}@@ -115,9 +116,7 @@ export function ExportProvider(props: { children: JSX.Element }) {};const exportCurrentFrame: ExportContextValue["exportCurrentFrame"] = async () => {- // Taken from the engine that draws the stage, not from the deprecated- // canvas this provider still renders scenes through.- const blob = await stage.snapshot();+ const blob = await engine.snapshot();if (!blob) {toast.error("Failed to capture frame");@@ -129,11 +128,11 @@ export function ExportProvider(props: { children: JSX.Element }) {};const exportActiveScene = () => {- const sid = world.selection.scene;- if (sid === null) {+ const scene = getActiveEntity(world);+ if (scene === null) {return toast("No active scene to export");}- exportScene(sid, getDefaultExportTemplate());+ void exportScene(scene, getDefaultExportTemplate());};/**diff --git a/apps/web/src/context/render.ts b/apps/web/src/context/render.tsindex 816c0575..fa618258 100644--- a/apps/web/src/context/render.ts+++ b/apps/web/src/context/render.ts@@ -3,18 +3,23 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { createSignal } from "solid-js";+import { createEncoder } from "@diffusionstudio/encoder";+import { Computed, FrameRate, Workarea } from "@diffusionstudio/runtime";-import { createEncoder } from "@/components/engine/encode/encoder";+import { createCapture } from "@/engine/capture";+import { version } from "../../package.json";-import type { Engine } from "@/components/engine";-import type { EncoderConfig } from "@/components/engine/encode/interfaces";-import type { ExportResult } from "@/components/engine/encode/types";+import type { Entity } from "koota";+import type { EncoderConfig, ExportResult } from "@diffusionstudio/encoder";+import type { Capture } from "@/engine/capture";+import type { Engine } from "@/engine";import type { ExportConfig } from "@/components/sidebar-right/inspector/export-progress";/*** Unified scene render path, used by the UI export (`ExportProvider.exportScene`):- * the "Exporting Composition" overlay, the engine stop/start lifecycle, encoder- * creation, progress reporting, and cancel wiring all live in {@link renderScene}.+ * the "Exporting Composition" overlay, the engine stop/start lifecycle, the+ * capture world the encode runs against, progress reporting, and cancel wiring+ * all live in {@link renderScene}.*/export type RenderOverlayState = {@@ -37,7 +42,7 @@ export function cancelRender() {export type RenderSceneOptions = {/** Scene entity to encode. */- scene: number;+ scene: Entity;/** Where to write the output (a save-picker handle in the UI, a file path handle from the CLI). */target: NonNullable<EncoderConfig["target"]>;/** Encoder settings (resolution, codecs, format, ...). */@@ -48,18 +53,30 @@ export async function renderScene(engine: Engine,{ scene, target, config }: RenderSceneOptions,): Promise<ExportResult> {- const w = engine.world;- const duration = w.components.Computed.duration[scene] / w.frameRate;+ const world = engine.world;++ const workarea = scene.get(Workarea);+ const frames = workarea+ ? workarea.end - workarea.start+ : scene.get(Computed)?.duration ?? 0;+ const duration = frames / (world.get(FrameRate)?.value || 30);cancelActive = undefined;setOverlay({ config, duration, progress: 0, remaining: undefined });+engine.stop();+ let capture: Capture | undefined;try {- const encoder = await createEncoder(w, {+ capture = createCapture(world, scene, {+ frameRate: config?.video?.fps,+ mode: config?.video?.enabled === false || config?.format === "ogg" ? "offline-audio" : "offline-video",+ });++ const encoder = await createEncoder(capture.world, {...config,- scene,target,+ comment: `Made with Diffusion v${version}`,onProgress(p) {const percent = Math.round((p.progress / p.total) * 100);setOverlay((prev) =>@@ -82,6 +99,7 @@ export async function renderScene(} finally {cancelActive = undefined;setOverlay(null);+ capture?.dispose();engine.start();}}diff --git a/apps/web/src/engine/capture.ts b/apps/web/src/engine/capture.tsnew file mode 100644index 00000000..0cebd8af--- /dev/null+++ b/apps/web/src/engine/capture.ts@@ -0,0 +1,155 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * The world an encode runs against: the project rendered a second time, into+ * a world of its own, reduced to the one node being encoded.+ *+ * Rendered rather than copied, because a copy of the entities is only what+ * the composition holds as data — a `<surface>`'s drawing, an `<html>`+ * subtree and every value a `useTicker` memo feeds live in the node the+ * project's render made, and the offline world has to have its own. So the+ * bundle that is on the canvas is mounted again here, against an offline+ * world at the export's frame rate, and the encoder is handed the result.+ *+ * The whole project renders, not the one scene: a scene is not a project, and+ * what each of them holds is only known by running the whole thing. The stage+ * is reduced to the scene straight after, before a system has looked at any+ * of it, so nothing outside it is ever drawn, decoded, mixed or advanced, nor+ * is any `src` of it resolved.+ */++import { mount } from '@diffusionstudio/reconciler';+import {+ Ai, ChildOf, FramePromises, FrameRate, Fonts, Hidden, Library, Mode, Project,+ RenderSurface, Root, Source, TranscriptionRequest,+ createRuntimeWorld, disposeDecoders, getParentNode, removeChild, resetCamera,+} from '@diffusionstudio/runtime';++import { ProjectBundle } from './traits';++import type { RuntimeMode } from '@diffusionstudio/runtime';+import type { Entity, World } from 'koota';++export interface CaptureOptions {+ /** Frames per second the copy is timed at; the source world's by default. */+ frameRate?: number;+ /** What is being encoded. Audio-only skips nothing, it just draws nothing. */+ mode?: RuntimeMode;+}++export interface Capture {+ /** The world to hand to an encoder. */+ world: World;+ /** The node in it — the stage's only child. */+ node: Entity;+ /** Drops the render, the canvas, the decoders it opened, and the world. */+ dispose(): void;+}++/**+ * Builds the capture world for an encode of `node`, an entity of `source` —+ * the editor's world. A scene, for a render of the composition; any node for+ * an image capture of it alone. Throws when there is no project to render,+ * when the node has no source stamp yet (an element the writer has not put in+ * the file), or when rendering the project produces nothing for that stamp.+ */+export function createCapture(source: World, node: Entity, options: CaptureOptions = {}): Capture {+ const code = source.get(ProjectBundle)?.code;+ if (!code) throw new Error('There is no project to render');++ // The stamp, not the entity: the two worlds hand out ids of their own, and+ // the stamp is the same element in both.+ const stamp = node.get(Source)?.value;+ if (!stamp) {+ throw new Error('This element is not in the project source yet — save the project and try again.');+ }++ const mode = options.mode ?? 'offline-video';+ const frameRate = options.frameRate ?? source.get(FrameRate)?.value ?? 30;++ // Created before the world is filled: the DOM-backed paints (`<html>`,+ // `<htmlPaint>`) attach their layout roots to it as their element is made.+ // The encoder sizes it once it knows how big the picture is.+ const canvas = document.createElement('canvas');+ canvas.width = 2;+ canvas.height = 2;+ canvas.style.cssText = 'position:fixed;left:-100000px;top:0;pointer-events:none;';+ document.body.appendChild(canvas);++ // Shares the source's assets and generation service — a `src` names the+ // same file in both — and its fonts, which are loaded into the document+ // already, so copying the list only tracks them as loaded rather than+ // having this world add them again.+ const world = createRuntimeWorld(source.get(Project)?.id ?? '');+ world.set(Mode, { value: mode });+ world.set(Library, source.get(Library) ?? null);+ world.set(Ai, source.get(Ai) ?? null);+ world.set(Fonts, { list: [...(source.get(Fonts)?.list ?? [])] });+ world.set(RenderSurface, { canvas, ctx: canvas.getContext('2d'), resolution: 1 });+ world.set(FrameRate, { value: frameRate });+ // The barrier offline capture awaits: the systems push decoder and source+ // readiness here and the encoder drains it before sampling a frame.+ world.set(FramePromises, { list: [] });++ const dispose = (mounted?: { dispose(): void }) => () => {+ mounted?.dispose();+ canvas.remove();+ // Release the decoder file handles and caches, then the world slot+ // itself: koota caps live worlds at 16, so a throwaway one has to be+ // destroyed rather than dropped.+ disposeDecoders(world, world.get(Root)!);+ world.destroy();+ };++ let mounted: { dispose(): void };+ try {+ // The frame rate is set above, so every authored time lands in this+ // world's frames as the document converts it — nothing to rescale.+ mounted = mount(code, world);+ } catch (error) {+ dispose()();+ throw error;+ }++ const rendered = world.query(Source).find((entity) => entity.get(Source)?.value === stamp);++ if (!rendered) {+ dispose(mounted)();+ throw new Error(`The project rendered nothing for "${stamp}"`);+ }++ // A node from inside a scene becomes the whole world, so it goes to the+ // top and whatever kept it from being seen in there no longer applies —+ // it is what was asked for. A scene is already a root and keeps both.+ if (getParentNode(rendered) !== null) {+ removeChild(world, rendered, getParentNode(rendered)!);+ rendered.remove(Hidden);+ }++ // Down to the one node. Destroying a root takes its subtree with it+ // (ChildOf is autoDestroy 'orphan'); what those nodes held outside the+ // world — an `<html>` root parked on the canvas, a `<surface>`'s own+ // canvas — is unreachable from here and goes when the canvas does.+ for (const root of world.query(ChildOf(world.get(Root)!))) {+ if (root !== rendered) root.destroy();+ }++ // The project may have spelled `<stage camera={…}>`, which is where the+ // editor was last looking — no part of the composition, and the view an+ // encode draws with is the plain one.+ resetCamera(world);++ // A `<captions>` with no src transcribes the scene it is in, and a+ // transcription encodes that scene's audio — through a capture world of+ // its own, whose captions would ask for the transcript that is still being+ // made. Nothing audible comes from a caption anyway.+ if (mode === 'offline-audio') {+ for (const entity of world.query(TranscriptionRequest)) {+ entity.remove(TranscriptionRequest);+ }+ }++ return { world, node: rendered, dispose: dispose(mounted) };+}diff --git a/apps/web/src/engine/create-engine.ts b/apps/web/src/engine/create-engine.tsindex 30abafe6..7d028845 100644--- a/apps/web/src/engine/create-engine.ts+++ b/apps/web/src/engine/create-engine.ts@@ -5,7 +5,7 @@import { assetSystem, renderSystem, transformSystem, playbackSystem, motionSystem, AudioEngine, createRuntimeWorld, Geometry, Mode, RenderSurface, Time, ChildOf, syncInteractiveState } from '@diffusionstudio/runtime';import { hudSystem } from './hud';import { createSignal, type Accessor, type Setter } from 'solid-js';-import { AssetSelection, Hud, Keys, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';+import { AssetSelection, Hud, Keys, Pointer, PointerEvents, ProjectBundle, ProjectConfig, SnapLines } from './traits';import { inputSystem } from './input/input-system';import { clearClipFrames, clearClipPeaks, clearMedia, clearPeaks, timelineSystem, TimelineSurface } from './timeline';import { shortcutSystem } from './input/shortcuts';@@ -49,7 +49,7 @@ class Engine {public constructor(projectId: string, options: EngineOptions = {}) {this.world = createRuntimeWorld(projectId);- this.world.add(Pointer, Keys, SnapLines, Hud, PointerEvents, AssetSelection, ProjectConfig, TimelineSurface);+ this.world.add(Pointer, Keys, SnapLines, Hud, PointerEvents, AssetSelection, ProjectConfig, ProjectBundle, TimelineSurface);this.unsubscribe.push(this.world.onAdd(ChildOf('*'), () => (this.interactiveDirty = true)),diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.tsindex 085cf59e..4f2b8edd 100644--- a/apps/web/src/engine/index.ts+++ b/apps/web/src/engine/index.ts@@ -5,6 +5,7 @@export * from './create-engine';export * from './context';export * from './canvas';+export * from './capture';export * from './camera';export * from './camera-controller';export * from './hooks';diff --git a/apps/web/src/engine/timeline/render/ruler.ts b/apps/web/src/engine/timeline/render/ruler.tsindex f914ec4a..129d6828 100644--- a/apps/web/src/engine/timeline/render/ruler.ts+++ b/apps/web/src/engine/timeline/render/ruler.ts@@ -2,7 +2,7 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Playback, Workarea, setPlayhead } from '@diffusionstudio/runtime';+import { Playback, setPlayhead } from '@diffusionstudio/runtime';import { assert } from '@/utils';import { RULER_INTERVALS } from '../constants';@@ -13,6 +13,7 @@ import {RULER_TICK_HEIGHT_MINOR,TARGET_MAJOR_TICK_DISTANCE,} from '../config';+import { editWorkarea } from '../../timing';import { framesToPixels, getFrameRate, getResolution, getScrollX, getViewport, pixelsToFrames } from '../view';import type { Entity, World } from 'koota';@@ -59,8 +60,7 @@ export function renderRuler(world: World, scene: Entity, surface: TimelineSurfacconst start = pixelsToFrames(pointer.position.initialX + scrollX * resolution, resolution);const end = pixelsToFrames(pointer.position.currentX + scrollX * resolution, resolution);- scene.add(Workarea);- scene.set(Workarea, { start, end });+ editWorkarea(world, scene, [start, end]);// The playhead follows the edge being dragged, so the frame under the// pointer is the one on the canvas.diff --git a/apps/web/src/engine/timeline/render/workarea.ts b/apps/web/src/engine/timeline/render/workarea.tsindex 0a5fa7ef..ff135798 100644--- a/apps/web/src/engine/timeline/render/workarea.ts+++ b/apps/web/src/engine/timeline/render/workarea.ts@@ -5,6 +5,7 @@import { Workarea } from '@diffusionstudio/runtime';import { assert } from '@/utils';+import { editWorkarea } from '../../timing';import { IN_POINT_PATH, OUT_POINT_PATH } from '../paths';import { RULER_HEIGHT } from '../config';import { framesToPixels, getResolution, getScrollX, pixelsToFrames } from '../view';@@ -23,9 +24,6 @@ let dragOrigin: [start: number, end: number] = [0, 0];* The work area — the stretch of the scene that plays and exports — as a bar* in the ruler with a handle at each end. Drag the bar to move the window,* a handle to move one edge, double-click to drop it altogether.- *- * Nothing here is an edit: the work area is a way of looking at the scene,- * not part of it, so it lives only as long as the world does.*/export function renderWorkarea(world: World, scene: Entity, surface: TimelineSurfaceState): void {const { ctx, pointer } = surface;@@ -60,11 +58,11 @@ export function renderWorkarea(world: World, scene: Entity, surface: TimelineSurif (dragging) {const delta = draggedFrames();- scene.set(Workarea, { start: dragOrigin[0] + delta, end: dragOrigin[1] + delta });+ editWorkarea(world, scene, [dragOrigin[0] + delta, dragOrigin[1] + delta]);}if (doubleClicked) {- scene.remove(Workarea);+ editWorkarea(world, scene, null);ctx.restore();return;}@@ -90,7 +88,7 @@ export function renderWorkarea(world: World, scene: Entity, surface: TimelineSurconst { dragging, pressed } = pointer.region(0, 0, HANDLE_WIDTH, BAR_HEIGHT);if (pressed) dragOrigin = [workarea.start, workarea.end];- if (dragging) scene.set(Workarea, { start: dragOrigin[0] + draggedFrames() });+ if (dragging) editWorkarea(world, scene, [dragOrigin[0] + draggedFrames(), dragOrigin[1]]);}// The out handle, relative to the in handle the context is now at.@@ -102,7 +100,7 @@ export function renderWorkarea(world: World, scene: Entity, surface: TimelineSurconst { dragging, pressed } = pointer.region(0, 0, HANDLE_WIDTH, BAR_HEIGHT);if (pressed) dragOrigin = [workarea.start, workarea.end];- if (dragging) scene.set(Workarea, { end: dragOrigin[1] + draggedFrames() });+ if (dragging) editWorkarea(world, scene, [dragOrigin[0], dragOrigin[1] + draggedFrames()]);}ctx.restore();diff --git a/apps/web/src/engine/timing.ts b/apps/web/src/engine/timing.tsindex a8405a13..c42ef3ca 100644--- a/apps/web/src/engine/timing.ts+++ b/apps/web/src/engine/timing.ts@@ -42,6 +42,20 @@ export function editTime(world: World, entity: Entity, name: TimeProp, frames: ngetDocumentEditor(world).editProperty(entity, name, unset ? false : framesToSeconds(frames, fps));}+/**+ * Writes the scene's work area from a frame range of this project, or takes+ * it off with `null`. The file spells it in seconds like every other time,+ * and `false` is the value the writer drops the attribute for.+ */+export function editWorkarea(world: World, scene: Entity, range: [start: number, end: number] | null): void {+ const fps = world.get(FrameRate)?.value ?? 30;+ getDocumentEditor(world).editProperty(+ scene,+ 'workarea',+ range ? [framesToSeconds(range[0], fps), framesToSeconds(range[1], fps)] : false,+ );+}+/*** Moves the node's in point to scene frame `frame`, keeping the rest of the* clip where it is: the runtime's `trimEntityIn`, as edits. The out point isdiff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.tsindex 92a341c9..663870ce 100644--- a/apps/web/src/engine/traits.ts+++ b/apps/web/src/engine/traits.ts@@ -82,3 +82,14 @@ export const AssetSelection = trait({ id: null as string | null });* like Library: the values are its own reactive state.*/export const ProjectConfig = trait(() => null as ProjectConfigStore | null);++/**+ * The compiled bundle the world's project is mounted from. Kept because a+ * render of it is not reproducible from the entities alone: what a+ * `<surface>` draws, what an `<html>` subtree shows and what a `useTicker`+ * memo feeds only exist while the project's graph runs, so an export renders+ * the same bundle a second time into its offline world (see+ * `@/context/render`). Empty until the first mount lands; a compile that+ * fails leaves the last good one, the way the canvas keeps the last render.+ */+export const ProjectBundle = trait({ code: '' });diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsxindex 4a667db2..5828372a 100644--- a/apps/web/src/pages/editor.tsx+++ b/apps/web/src/pages/editor.tsx@@ -18,6 +18,7 @@ import { getDocumentEditor } from '@/engine/editor';import { attachLibrary, isLibraryFile } from '@/engine/library';import { attachAi } from '@/utils/gen-ai';import { attachProjectConfig, isProjectConfigFile } from '@/engine/project-config';+import { ProjectBundle } from '@/engine/traits';import { isCacheFile } from '@diffusionstudio/assets';import { createEditWriter } from '@/projects/edits';import { compileProject, watchProject } from '@/projects/host';@@ -84,6 +85,8 @@ export function EditorPage() {unmount();try {mounted = mount(result.code, world);+ // What an export renders a second time, for the one scene it is of.+ world.set(ProjectBundle, { code: result.code });// The rendered scene knows which element every entity came from, so// from here on an edit in the editor can find its way back.writer = createEditWriter(dir, world);diff --git a/apps/web/src/utils/gen-ai.ts b/apps/web/src/utils/gen-ai.tsindex d855c1e5..d19f5f19 100644--- a/apps/web/src/utils/gen-ai.ts+++ b/apps/web/src/utils/gen-ai.ts@@ -9,6 +9,7 @@ import {} from "@diffusionstudio/runtime";import type { SourceModifierValues } from "@diffusionstudio/runtime";import { createEncoder } from "@diffusionstudio/encoder";+import { createCapture } from "@/engine/capture";import { assetName, GENERATED_DIR } from "@diffusionstudio/assets";import {PROMPT_INPUT_AUDIO_MODEL_OPTIONS,@@ -26,6 +27,7 @@ import { toast } from "somoto";import type { AspectRatio, AssetInput, AssetRef, AssetSpecInput } from "@diffusionstudio/jsx";import type { Asset, AssetLibrary, AssetType } from "@diffusionstudio/assets";import type { FileRef } from "@diffusionstudio/api-contract";+import type { ExportResult } from "@diffusionstudio/encoder";import type { Entity, World } from "koota";/** What a failure is called where the user reads about it. */@@ -144,13 +146,20 @@ export class EditorGenAi extends GenAi {private async runTranscription(world: World, scene: Entity, key: string): Promise<Asset> {assert(sceneHasAudio(world, scene), "No audio found. Add an audio or video clip to the scene to generate captions.");- const encoder = await createEncoder(world, {- scene,- format: "ogg",- video: { enabled: false },- audio: { enabled: true, codec: "opus", sampleRate: 24000 },- });- const result = await encoder.render();+ // The scene's own capture world: the project rendered again, reduced to+ // this scene, with nothing drawn — see `createCapture`.+ const capture = createCapture(world, scene, { mode: "offline-audio" });+ let result: ExportResult;+ try {+ const encoder = await createEncoder(capture.world, {+ format: "ogg",+ video: { enabled: false },+ audio: { enabled: true, codec: "opus", sampleRate: 24000 },+ });+ result = await encoder.render();+ } finally {+ capture.dispose();+ }assert(result.type === "success" && result.data !== undefined, "Failed to encode the scene audio");const uploadId = crypto.randomUUID();diff --git a/packages/encoder/src/encoder.ts b/packages/encoder/src/encoder.tsindex b1a94294..d6e6dac2 100644--- a/packages/encoder/src/encoder.ts+++ b/packages/encoder/src/encoder.ts@@ -10,124 +10,115 @@ import {} from 'mediabunny';import { Not, Or } from 'koota';import {- createRuntimeWorld, setActive, serializeEntity, cloneFromRecords,- getEntityTree, propagateTimeRangeDown, framesToSeconds,- assert, store, disposeDecoders,+ setActive, propagateTimeRangeDown, framesToSeconds,+ assert, store, isScene,assetSystem, playbackSystem, motionSystem, transformSystem, renderSystem,AudioBus, AudioBusHandle,ChildOf, Geometry, Group, Paint, Workarea, Playback,- AudioPlayback, Computed, Start, End, SourceIn, SourceOut,- Transition, Keyframe, Animation,+ AudioPlayback, Computed,Position, Offset, Rotation, Scale, Skew,- Project, Mode, Time, FrameRate, RenderSurface, AudioEngine, Root,- resetCamera,- Library, Ai, Fonts, FramePromises,+ Time, FrameRate, RenderSurface, AudioEngine, Root,+ FramePromises,} from '@diffusionstudio/runtime';import { TargetBuffer } from './buffer';import { createOutputFormat } from './format';import { createRenderEventDetail } from './utils';-import type { World } from 'koota';+import type { Entity, World } from 'koota';import type { EncoderConfig } from './interfaces';import type { ExportResult } from './types';-export async function createEncoder(sourceWorld: World, config: EncoderConfig) {- const sourceComputed = store(sourceWorld, Computed);- const sourceScene = config.scene;- const sourceSceneId = sourceScene.id();- const sourceFrameRate = sourceWorld.get(FrameRate)?.value ?? 30;- const frameRate = config.video?.fps ?? sourceFrameRate;- const numberOfChannels = config.audio?.numberOfChannels ?? 2;- const sampleRate = config.audio?.sampleRate ?? 48000;- const sceneWidth = sourceComputed.width[sourceSceneId]!;- const sceneHeight = sourceComputed.height[sourceSceneId]!;- const sceneEnd = sourceComputed.end[sourceSceneId]!;+/**+ * The scene a capture world holds. An encoder takes the world as it is —+ * what to encode is the whole of what is in it — so a stage with anything+ * else under it is a caller that has not finished preparing the world.+ */+function captureScene(world: World): Entity {+ const roots = [...world.query(ChildOf(world.get(Root)!))];+ assert(roots.length === 1, `A capture world holds one scene, this one holds ${roots.length}`);++ const scene = roots[0]!;+ assert(isScene(scene), 'What the capture world holds is not a scene');+ return scene;+}++/**+ * Encodes the scene a capture world holds into a file.+ *+ * `world` is not the editor's: it is a world built for this encode, holding+ * the composition as it is to be written and nothing else — see the app's+ * capture builder, which renders the project into a fresh world and reduces+ * its stage to the one scene. Everything the encode needs is read from there:+ * the scene is the stage's only child, the frame rate is the world's, the+ * camera is the view it is drawn with, and the canvas the DOM-backed paints+ * attached themselves to is the one drawn into.+ *+ * The world stays the caller's — it built it, it disposes it. What is created+ * here is the audio context, the output, and the frames.+ */+export async function createEncoder(world: World, config: EncoderConfig) {+ const scene = captureScene(world);+ const sceneId = scene.id();+ const computed = store(world, Computed);+ const playback = store(world, Playback);++ const frameRate = world.get(FrameRate)?.value ?? 30;+ const sceneWidth = computed.width[sceneId]!;+ const sceneHeight = computed.height[sceneId]!;+ const sceneEnd = computed.end[sceneId]!;// Honor the scene's Workarea trait: render only the frames between// Workarea.start and Workarea.end instead of the full scene duration.- const hasWorkarea = sourceScene.has(Workarea);- const sourceWorkarea = store(sourceWorld, Workarea);- const workareaStart = hasWorkarea- ? Math.max(0, Math.min(sceneEnd, sourceWorkarea.start[sourceSceneId] ?? 0))- : 0;- const workareaEnd = hasWorkarea- ? Math.max(workareaStart, Math.min(sceneEnd, sourceWorkarea.end[sourceSceneId] ?? sceneEnd))+ const workarea = scene.get(Workarea);+ const workareaStart = workarea ? Math.max(0, Math.min(sceneEnd, workarea.start)) : 0;+ const workareaEnd = workarea+ ? Math.max(workareaStart, Math.min(sceneEnd, workarea.end || sceneEnd)): sceneEnd;- const workareaFrames = workareaEnd - workareaStart;- const playheadStartSeconds = framesToSeconds(workareaStart, sourceFrameRate);- const duration = framesToSeconds(workareaFrames, sourceFrameRate);+ const playheadStartSeconds = framesToSeconds(workareaStart, frameRate);+ const duration = framesToSeconds(workareaEnd - workareaStart, frameRate);++ // Before the two below read them: ogg is an audio container, so asking for+ // one is asking for the audio alone — and with `videoEnabled` derived+ // first, it would still have gone looking for pictures to put in it.+ if (config.format === 'ogg') {+ config.audio = { ...config.audio, enabled: true };+ config.video = { ...config.video, enabled: false };+ }++ const audioEnabled = config.audio?.enabled ?? true;+ const videoEnabled = config.video?.enabled ?? true;+ const numberOfChannels = config.audio?.numberOfChannels ?? 2;+ const sampleRate = config.audio?.sampleRate ?? 48000;const audioBitrate = config.audio?.bitrate ?? 128e3;const videoBitrate = config.video?.bitrate ?? 10e6;const audioCodec = config.audio?.codec ?? 'aac';+ const videoCodec = config.video?.codec ?? 'avc';+ const containerFormat = config.format ?? 'mp4';const resolution = config.video?.resolution ?? 1080;const scale = Math.round(resolution * 1e6 / sceneHeight) / 1e6;const width = Math.round(sceneWidth * scale / 2) * 2;const height = Math.round(sceneHeight * scale / 2) * 2;- const videoCodec = config.video?.codec ?? 'avc';- const containerFormat = config.format ?? 'mp4';- const audioEnabled = config.audio?.enabled ?? true;- const videoEnabled = config.video?.enabled ?? true;const frameDuration = 1 / frameRate;- if (config.format === 'ogg') {- config.audio = { ...config.audio, enabled: true };- config.video = { ...config.video, enabled: false };- }+ const canvas = world.get(RenderSurface)?.canvas;+ assert(canvas instanceof HTMLCanvasElement, 'The capture world has no canvas to draw into');+ canvas.width = width;+ canvas.height = height;+ world.set(RenderSurface, { resolution: scale });- const sceneSubtree = getEntityTree(sourceWorld, sourceScene);- const subtreeRecords = sceneSubtree.map(entity => serializeEntity(entity));-- // HTML paints need their layout roots attached to the destination canvas.- const offscreenCanvas = document.createElement('canvas');- offscreenCanvas.width = width;- offscreenCanvas.height = height;- offscreenCanvas.style.cssText = 'position:fixed;left:-100000px;top:0;pointer-events:none;';- document.body.appendChild(offscreenCanvas);- const offscreenCtx = offscreenCanvas.getContext('2d')!;-- // Offline audio contextconst offlineAudioCtx = new OfflineAudioContext(numberOfChannels,Math.ceil(duration * sampleRate),sampleRate,);-- // Build a fresh offline world that shares assets with the source. Fonts are- // already loaded into the document; copying the array just tracks them as- // loaded so the new world doesn't try to re-add them.- const world = createRuntimeWorld(sourceWorld.get(Project)?.id ?? '');- world.set(Mode, { value: videoEnabled ? 'offline-video' : 'offline-audio' });- world.set(Library, sourceWorld.get(Library) ?? null);- world.set(Ai, sourceWorld.get(Ai) ?? null);- world.set(Fonts, { list: [...(sourceWorld.get(Fonts)?.list ?? [])] });- world.set(RenderSurface, { canvas: offscreenCanvas, ctx: offscreenCtx, resolution: scale });world.set(AudioEngine, { context: offlineAudioCtx });- world.set(FrameRate, { value: frameRate });- world.set(FramePromises, { list: [] });-- resetCamera(world);-- const eidMap = cloneFromRecords(world, subtreeRecords);- const scene = eidMap.get(sourceScene);- assert(scene !== undefined, 'Failed to clone scene subtree');-- rescaleFrameTimestamps(world, sourceFrameRate, frameRate);- recomputeAllTimeRanges(world);- normalizeSceneTransform(world, scene.id());setActive(world, scene);- const computed = store(world, Computed);- const playback = store(world, Playback);- // The workarea (Workarea trait) is runtime-only and never serialized, so it- // isn't cloned into the offline world — nothing to strip here. The encoder- // drives the playhead explicitly within the [workareaStart, workareaEnd]- // window computed from the source scene above.- const sceneId = scene.id();computed.localTimeInSeconds[sceneId] = playheadStartSeconds;- computed.localTime[sceneId] = Math.round(playheadStartSeconds * frameRate);+ computed.localTime[sceneId] = workareaStart;playback.playing[sceneId] = true;playback.loop[sceneId] = false;playback.speed[sceneId] = 1;@@ -139,11 +130,6 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {audioPlayback.contextOffsetInSeconds[sceneId] = 0;audioPlayback.timelineOffsetInSeconds[sceneId] = playheadStartSeconds;- // Re-execute any mounts into this offline world so it owns its own reactive- // graphs + runtime hosts (surface/html). The per-frame playbackSystem then- // drives them via the Mounts trait, so ticker-animated surfaces render.- const mounts = videoEnabled ? (await config.realizeMounts?.(world)) ?? null : null;-// Set up mediabunny outputconst buffer = await TargetBuffer.create(config.target);const format = await createOutputFormat(buffer, config.format);@@ -160,7 +146,7 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {const sceneFills = [...world.query(Paint, Not(Geometry), ChildOf(scene))];- const videoSource = new CanvasSource(offscreenCanvas, {+ const videoSource = new CanvasSource(canvas, {codec: videoCodec,bitrate: videoBitrate,latencyMode: 'quality',@@ -246,6 +232,12 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {const render = async (): Promise<ExportResult> => {try {+ // A rendered project starts with every `src` unresolved, and the+ // decoders the playback system opens are keyed off the asset an+ // element is bound to. Settle them before the first frame, or+ // frame zero is drawn against media that is not there yet.+ await warmupAssets(world);+await output.start();const start = performance.now();const startTime = start;@@ -282,6 +274,8 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {playbackSystem(world);await resolverSystem(world);motionSystem(world);+ // May be changed by a system+ normalizeSceneTransform(world, sceneId);}if (videoEnabled) {@@ -345,16 +339,9 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {error: e instanceof Error ? e : new Error('Unknown error'),};} finally {+ // The world, its canvas and the decoders opened in it are the+ // caller's to release; only the worklet is this encode's.URL.revokeObjectURL(audioWorkletUrl);- offscreenCanvas.remove();- // Free the graphs and DOM roots realized above before discarding the- // offline world.- mounts?.disposeAll();- // Release decoder file handles/caches, then the world slot itself- // (koota caps live worlds at 16, so throwaway offline worlds must- // be destroyed — bitecs could just drop them).- disposeDecoders(world, world.get(Root)!);- world.destroy();}};@@ -427,43 +414,6 @@ function createThrottledCallback<T>(callback: ((value: T) => void) | undefined,};}-function rescaleFrameTimestamps(- world: World,- sourceFrameRate: number,- targetFrameRate: number,-): void {- if (sourceFrameRate === targetFrameRate) return;-- const ratio = targetFrameRate / sourceFrameRate;- const rescale = (v: number) => Math.round(v * ratio);-- const transition = store(world, Transition);- const keyframe = store(world, Keyframe);- const animation = store(world, Animation);-- for (const trait of [Start, End, SourceIn, SourceOut]) {- const values = store(world, trait).value;- for (const entity of world.query(trait)) {- const eid = entity.id();- values[eid] = rescale(values[eid] ?? 0);- }- }-- for (const entity of world.query(Or(Transition, Keyframe, Animation))) {- const eid = entity.id();- if (entity.has(Transition)) {- transition.duration[eid] = rescale(transition.duration[eid] ?? 0);- }- if (entity.has(Keyframe)) {- keyframe.time[eid] = rescale(keyframe.time[eid] ?? 0);- }- if (entity.has(Animation)) {- animation.duration[eid] = rescale(animation.duration[eid] ?? 0);- animation.delay[eid] = rescale(animation.delay[eid] ?? 0);- }- }-}-function normalizeSceneTransform(world: World, sceneId: number): void {const position = store(world, Position);const offset = store(world, Offset);@@ -479,12 +429,6 @@ function normalizeSceneTransform(world: World, sceneId: number): void {scaleStore.y[sceneId] = 1;skew.x[sceneId] = 0;skew.y[sceneId] = 0;- // computeLocalMatrix reads the Computed.* mirror, not the raw traits. The- // base traits are populated via entity.set during the clone, which fires- // the observer that copies the (canvas) position into Computed. Writing- // the raw stores above bypasses that observer, so the Computed mirror must- // be reset here too — otherwise the scene renders at its canvas position- // instead of centered in the export.const computed = store(world, Computed);computed.positionX[sceneId] = 0;computed.positionY[sceneId] = 0;@@ -497,6 +441,20 @@ function normalizeSceneTransform(world: World, sceneId: number): void {computed.skewY[sceneId] = 0;}+/**+ * Runs the asset system until it has nothing left in flight: each pass can+ * start resolutions the previous one's answers asked for (a modifier chain,+ * a transcript that waits for the scene's own sources to land). Bounded, so+ * a source that keeps re-requesting cannot hold an export open forever.+ */+async function warmupAssets(world: World): Promise<void> {+ for (let pass = 0; pass < 16; pass++) {+ assetSystem(world);+ if (!world.get(FramePromises)?.list?.length) return;+ await resolverSystem(world);+ }+}+export async function resolverSystem(world: World) {const promises = world.get(FramePromises)?.list;if (promises?.length) {diff --git a/packages/encoder/src/image-encoder.ts b/packages/encoder/src/image-encoder.tsindex fb20262d..0db7f872 100644--- a/packages/encoder/src/image-encoder.ts+++ b/packages/encoder/src/image-encoder.ts@@ -4,15 +4,14 @@import { Or } from 'koota';import {- createRuntimeWorld, createEntity, appendChild, serializeEntity,- cloneFromRecords, getEntityTree, framesToSeconds,- formatTimecode, assert, store, disposeDecoders,+ createEntity, appendChild, getEntityTree, framesToSeconds,+ formatTimecode, assert, store,assetSystem, playbackSystem, motionSystem, transformSystem, renderSystem,ChildOf, Geometry, Group, Hidden, IsMask, Muted, Culled,ClipsContent, Playback, Computed, WorldBounds,- Project, Mode, RenderSurface, AudioEngine, Library, Ai, Fonts, Root,- resetCamera, setCamera,- FramePromises, Time, FrameRate,+ RenderSurface, AudioEngine, Root,+ setCamera,+ Time, FrameRate,} from '@diffusionstudio/runtime';import { resolverSystem, recomputeAllTimeRanges } from './encoder';@@ -30,106 +29,80 @@ export type ImageExportResult =| { type: 'error'; error: Error };/**- * Renders single frames of one entity into standalone PNGs (base64, no- * data-url prefix). The entity's subtree is cloned into a fresh offline- * world and drawn at the top level: the canvas is sized to the union of the- * entity's world-space AABBs across the requested frames and the camera- * shifts that box onto the canvas, so the node is fully visible regardless- * of where it sat in its source scene.+ * Renders single frames of the node a capture world holds into standalone+ * PNGs (base64, no data-url prefix).+ *+ * `world` is the caller's, built for this capture and holding the node as the+ * stage's only child — the same arrangement `createEncoder` takes, and for+ * the same reason. The canvas is sized to the union of the node's world-space+ * AABBs across the requested frames and the camera shifts that box onto it,+ * so the node is fully visible wherever it sat in the scene it was rendered+ * in.*/-export async function createImageEncoder(sourceWorld: World, config: ImageEncoderConfig) {+export async function createImageEncoder(world: World, config: ImageEncoderConfig) {assert(config.frames.length > 0, 'No frames requested');- const subtree = getEntityTree(sourceWorld, config.entity);- const records = subtree.map(entity => serializeEntity(entity));-- // Re-root the node. Its parent isn't part of the clone, so a dangling- // ChildOf would attach to an arbitrary entity in the new world;- const rootRecord = records.find(record => record.eid === config.entity);- assert(rootRecord !== undefined, `No such entity: ${config.entity}`);- delete rootRecord.ChildOf;- delete rootRecord.Hidden;- const rootStart = rootRecord.Start ?? 0;- delete rootRecord.Start;- if (rootRecord.End !== undefined) {- rootRecord.End -= rootStart;- }+ const roots = [...world.query(ChildOf(world.get(Root)!))];+ assert(roots.length === 1, `A capture world holds one node, this one holds ${roots.length}`);+ const root = roots[0]!;++ const canvas = world.get(RenderSurface)?.canvas;+ assert(canvas instanceof HTMLCanvasElement, 'The capture world has no canvas to draw into');++ // Never started — image capture is video-only; the context is only there+ // for the lazy audio-bus wiring to have something to bind to.+ world.set(AudioEngine, { context: new OfflineAudioContext(2, 1, 48000) });- const offscreenCanvas = document.createElement('canvas');- offscreenCanvas.width = 2;- offscreenCanvas.height = 2;- offscreenCanvas.style.cssText = 'position:fixed;left:-100000px;top:0;pointer-events:none;';- document.body.appendChild(offscreenCanvas);- const offscreenCtx = offscreenCanvas.getContext('2d')!;-- // Never started — image capture is video-only; the context just satisfies- // world construction and lazy audio-bus wiring.- const offlineAudioCtx = new OfflineAudioContext(2, 1, 48000);-- const sourceFrameRate = sourceWorld.get(FrameRate)?.value ?? 30;- const world = createRuntimeWorld(sourceWorld.get(Project)?.id ?? '');- world.set(Mode, { value: 'offline-video' });- world.set(Library, sourceWorld.get(Library) ?? null);- world.set(Ai, sourceWorld.get(Ai) ?? null);- world.set(Fonts, { list: [...(sourceWorld.get(Fonts)?.list ?? [])] });- world.set(RenderSurface, { canvas: offscreenCanvas, ctx: offscreenCtx, resolution: 1 });- world.set(AudioEngine, { context: offlineAudioCtx });- world.set(FrameRate, { value: sourceFrameRate });- world.set(FramePromises, { list: [] });-- resetCamera(world);-- const eidMap = cloneFromRecords(world, records);- const root = eidMap.get(config.entity);- assert(root !== undefined, 'Failed to clone entity subtree');-- const mounts = (await config.realizeMounts?.(world)) ?? null;-- const cloned = [...eidMap.values()];+ const frameRate = world.get(FrameRate)?.value ?? 30;const computed = store(world, Computed);const playback = store(world, Playback);const worldBounds = store(world, WorldBounds);+ const subtree = getEntityTree(world, root);+// Mute everything so the playback system never initializes audio decoders.- for (const entity of cloned) {+ for (const entity of subtree) {entity.add(Muted);}// The motion system only samples parented entities, so the node's own// keyframes would be skipped as a top-level root. A synthetic group above- // it owns the playhead instead and keeps the node an ordinary child.- const stage = createEntity(world);- stage.add(Group);- appendChild(world, root, stage);+ // it owns the playhead instead and keeps the node an ordinary child. It+ // goes under the stage, or nothing below it would be walked at all.+ const clock = createEntity(world);+ clock.add(Group);+ clock.add(Playback);+ appendChild(world, clock, world.get(Root)!);+ appendChild(world, root, clock);recomputeAllTimeRanges(world);- // Map "frame 0 = first visible frame": the node now starts at 0, and its- // source window puts its own in point there.+ // Map "frame 0 = the node's first visible frame": the node keeps the time+ // it was authored at, so where it begins is the offset every requested+ // frame is counted from.const startFrame = computed.start[root.id()] ?? 0;- // Entities in the clone that own a timeline clock+ // Everything in this world that owns a timeline clock, the synthetic one+ // above included.const clocks = [...world.query(Playback)];const seek = (frame: number) => {const stageFrame = startFrame + frame;- const stageSeconds = framesToSeconds(stageFrame, sourceFrameRate);- computed.localTime[stage.id()] = stageFrame;- computed.localTimeInSeconds[stage.id()] = stageSeconds;-- for (const clock of clocks) {- computed.localTime[clock.id()] = stageFrame;- computed.localTimeInSeconds[clock.id()] = stageSeconds;- playback.playing[clock.id()] = true;+ const stageSeconds = framesToSeconds(stageFrame, frameRate);++ for (const entity of clocks) {+ computed.localTime[entity.id()] = stageFrame;+ computed.localTimeInSeconds[entity.id()] = stageSeconds;+ playback.playing[entity.id()] = true;}- const delta = 1000 / sourceFrameRate;+ const delta = 1000 / frameRate;const time = world.get(Time)!;world.set(Time, { delta, now: time.now + delta });// Cull flags derived from a stale canvas/camera would make the motion// system skip entities and keep decoders idle — clear them every tick.- for (const entity of cloned) {+ for (const entity of subtree) {if (entity.has(Culled)) entity.remove(Culled);}@@ -179,8 +152,8 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncode/** Re-target the output height; callers that lay frames out do this once measured. */const resize = (height?: number) => {const scale = height ? height / boundsHeight : 1;- offscreenCanvas.width = Math.max(1, Math.round(boundsWidth * scale));- offscreenCanvas.height = Math.max(1, Math.round(boundsHeight * scale));+ canvas.width = Math.max(1, Math.round(boundsWidth * scale));+ canvas.height = Math.max(1, Math.round(boundsHeight * scale));world.set(RenderSurface, { resolution: scale });};@@ -210,8 +183,8 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncodeconst stampFrame = startFrame + frame;images.push({- base64: await toBase64Png(offscreenCanvas),- timecode: formatTimecode(framesToSeconds(stampFrame, sourceFrameRate), sourceFrameRate),+ base64: await toBase64Png(canvas),+ timecode: formatTimecode(framesToSeconds(stampFrame, frameRate), frameRate),});}@@ -221,15 +194,8 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncodetype: 'error',error: e instanceof Error ? e : new Error('Unknown error'),};- } finally {- offscreenCanvas.remove();- // Free the graphs and DOM roots realized above, then release decoders- // and the world slot itself- // (koota caps live worlds at 16).- mounts?.disposeAll();- disposeDecoders(world, world.get(Root)!);- world.destroy();}+ // The world, its canvas and its decoders are the caller's to release.};return {diff --git a/packages/encoder/src/interfaces.ts b/packages/encoder/src/interfaces.tsindex 57a539e6..8cf34572 100644--- a/packages/encoder/src/interfaces.ts+++ b/packages/encoder/src/interfaces.ts@@ -3,8 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import type { VideoCodec, AudioCodec } from 'mediabunny';-import type { Entity, World } from 'koota';-import type { ContainerFormat, EncoderProgress, RealizedMounts, WritableFileTarget } from './types';+import type { ContainerFormat, EncoderProgress, WritableFileTarget } from './types';export interface AudioConfig {/**@@ -63,8 +62,10 @@ export interface VideoConfig {bitrate?: number;/**- * Defines the fps at which the composition will be rendered- * @default 30+ * Defines the fps at which the composition will be rendered. Read by+ * whoever builds the capture world — the copy is timed at it — rather+ * than by the encoder, which takes the world's own frame rate.+ * @default the source world's*/fps?: number;@@ -96,17 +97,6 @@ export interface EncoderConfig {*/format?: ContainerFormat;- /**- * Defines the range of the composition to encode- */- trim?: {- /**- * Defines the time when the encoding should end- * @default scene.duration- */- end?: number;- };-/*** Defines the target file to encode to.* When a FileSystemFileHandle (or any WritableFileTarget) is provided, the@@ -120,18 +110,6 @@ export interface EncoderConfig {*/onProgress?: (progress: EncoderProgress) => void;- /**- * Defines the source scene to encode- */- scene: Entity;-- /**- * Re-executes the source world's mounts into the offline world so their- * reactive graphs and runtime hosts (surface/html) render during capture.- * Mount realization needs the host app's module loader, so it is injected.- */- realizeMounts?: (world: World) => Promise<RealizedMounts | null>;-/*** Metadata comment tag written into the container (e.g. an app version).*/@@ -139,17 +117,9 @@ export interface EncoderConfig {}export interface ImageEncoderConfig {- /**- * The source entity to capture- */- entity: Entity;-- /** Frames to capture, relative to the entity's first visible frame. */+ /** Frames to capture, relative to the node's first visible frame. */frames: number[];- /** Target output height in px (default: the entity's native size). */+ /** Target output height in px (default: the node's native size). */resolution?: number;-- /** See EncoderConfig.realizeMounts. */- realizeMounts?: (world: World) => Promise<RealizedMounts | null>;}diff --git a/packages/encoder/src/types.ts b/packages/encoder/src/types.tsindex 974d49ce..91c3cc58 100644--- a/packages/encoder/src/types.ts+++ b/packages/encoder/src/types.ts@@ -30,6 +30,3 @@ export type ExportResult =type: 'error';error: Error;};--/** Mount graphs re-executed into an offline world (see EncoderConfig.realizeMounts). */-export type RealizedMounts = { disposeAll(): void };diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.tsindex b68810a5..78e95507 100644--- a/packages/jsx/src/types.ts+++ b/packages/jsx/src/types.ts@@ -450,6 +450,17 @@ export type SceneProps = IdentityProps & PositionProps & Required<SizeProps> & F* -Infinity = silence. A clip's own `volume` composes with this one.*/volume?: number;+ /**+ * The stretch of the scene that plays and exports, as `[in, out]`: playback+ * loops within it, and an export is of it and nothing else — so this is+ * where a render is trimmed. `null` for the whole scene, which is what a+ * scene without one is.+ *+ * Editor state carried by the source the way `active` is (the timeline's+ * brackets have nowhere else to be written back to), but unlike `active` it+ * is read wherever the file is: what it says is what comes out of a render.+ */+ workarea?: [inPoint: Time, outPoint: Time] | null;children?: SolidJSX.Element;};diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsindex 6545fad0..de2c327f 100644--- a/packages/reconciler/src/document.ts+++ b/packages/reconciler/src/document.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Active, AdjustmentLayer, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, bindAsset, BlendMode, BlendModeType, Blur, Caption, CaptionAlign, CaptionType, Chars, ClipHeight, ClipsContent, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Effect, EffectType, End, Expanded, FontStyle, FrameRate, Generating, GenerationRequest, Loop, LoadRequest, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsMask, isText, ItemIndex, Keyframe, KeyframeTrack, MixedCornerRadius, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, Playback, PlaybackRate, Position, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceError, SourceIn, SourceOut, SourceFrameRate, SourceModifiers, hasModifier, setCameraMatrix, Start, Stroke, StrokeCap, StrokeJoin, StrokeStyle, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, TranscriptionRequest, Transition, TransitionType, UniformScale, Volume } from '@diffusionstudio/runtime';+import { Active, AdjustmentLayer, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, bindAsset, BlendMode, BlendModeType, Blur, Caption, CaptionAlign, CaptionType, Chars, ClipHeight, ClipsContent, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Effect, EffectType, End, Expanded, FontStyle, FrameRate, Generating, GenerationRequest, Loop, LoadRequest, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsMask, isText, ItemIndex, Keyframe, KeyframeTrack, MixedCornerRadius, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, Playback, PlaybackRate, Position, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceError, SourceIn, SourceOut, SourceFrameRate, SourceModifiers, hasModifier, setCameraMatrix, Start, Stroke, StrokeCap, StrokeJoin, StrokeStyle, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, TranscriptionRequest, Transition, TransitionType, UniformScale, Volume, Workarea } from '@diffusionstudio/runtime';import { LOOP_ATTR, parseTime, SOURCE_ATTR } from '@diffusionstudio/jsx';import { SVGElements } from 'solid-js/web';import { IsExcluded } from 'koota';@@ -1344,6 +1344,20 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {entity.set(TranscriptionRequest, { seed: toNumber(value) ?? 0 });return;}+ case 'workarea': {+ // Two times or none: a half-authored range says nothing, and+ // `false` is what the editor writes to take the brackets off.+ const range = Array.isArray(value) ? value.map(toSeconds) : [];+ const [start, end] = range;+ if (range.length !== 2 || start === undefined || end === undefined) {+ entity.remove(Workarea);+ return;+ }++ entity.add(Workarea);+ entity.set(Workarea, { start: this.toFrames(start), end: this.toFrames(end) });+ return;+ }case 'background': {const color = parseColor(value);this.stage.entity.set(Background, { value: color ?? DEFAULT_BACKGROUND });