Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

playback perf bits

Richie McIlroy9a7a8b7f6148
diff --git a/apps/desktop/src-tauri/src/frame_ws.rs b/apps/desktop/src-tauri/src/frame_ws.rs
index eb09acc53..0241b6a73 100644
--- a/apps/desktop/src-tauri/src/frame_ws.rs
+++ b/apps/desktop/src-tauri/src/frame_ws.rs
@@ -197,8 +197,6 @@ pub async fn create_watch_frame_ws(
}
}
- let mut last_frame_number: Option<u32> = None;
-
loop {
tokio::select! {
msg = socket.recv() => {
@@ -217,10 +215,6 @@ pub async fn create_watch_frame_ws(
_ = camera_rx.changed() => {
let frame_opt = camera_rx.borrow_and_update().clone();
if let Some(frame) = frame_opt {
- if last_frame_number == Some(frame.frame_number) {
- continue;
- }
- last_frame_number = Some(frame.frame_number);
let (nv12_data, scaled_width, scaled_height) = downscale_and_convert_to_nv12(
&frame.data,
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index e54fc0383..e378c1a4c 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1631,8 +1631,16 @@ async fn set_project_config(
async fn update_project_config_in_memory(
editor_instance: WindowEditorInstance,
config: ProjectConfiguration,
+ frame_number: Option<u32>,
+ fps: Option<u32>,
+ resolution_base: Option<XY<u32>>,
) -> Result<(), String> {
editor_instance.project_config.0.send(config).ok();
+ if let (Some(frame), Some(f), Some(res)) = (frame_number, fps, resolution_base) {
+ editor_instance.preview_tx.send_modify(|v| {
+ *v = Some((frame, f, res));
+ });
+ }
Ok(())
}
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index f8d72653a..1e2a01903 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -208,9 +208,21 @@ function Inner() {
const doConfigUpdate = async (time: number) => {
const config = serializeProjectConfiguration(project);
- await commands.updateProjectConfigInMemory(config);
- canvasControls()?.resetFrameState();
- renderFrame(time);
+ const frameNumber = Math.max(Math.floor(time * FPS), 0);
+ const resBase = previewResolutionBase();
+ try {
+ await commands.updateProjectConfigInMemory(
+ config,
+ frameNumber,
+ FPS,
+ resBase,
+ );
+ } catch (e) {
+ console.error(
+ "[Editor] doConfigUpdate - ERROR sending config to Rust:",
+ e,
+ );
+ }
};
const throttledConfigUpdate = throttle(doConfigUpdate, 1000 / FPS);
const trailingConfigUpdate = debounce(doConfigUpdate, 1000 / FPS + 16);
@@ -220,10 +232,13 @@ function Inner() {
};
createEffect(
on(
- () => trackDeep(project),
() => {
- updateConfigAndRender(editorState.playbackTime);
+ trackDeep(project);
+ },
+ () => {
+ updateConfigAndRender(frameNumberToRender());
},
+ { defer: true },
),
);
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 8322496ac..93de36ffe 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -461,7 +461,10 @@ function PreviewCanvas() {
const hasRenderedFrame = () => canvasControls()?.hasRenderedFrame() ?? false;
- const canvasTransferredRef = { current: false };
+ const canvasInitializedRef = { current: false };
+ const [canvasRef, setCanvasRef] = createSignal<HTMLCanvasElement | null>(
+ null,
+ );
const [canvasContainerRef, setCanvasContainerRef] =
createSignal<HTMLDivElement>();
@@ -487,90 +490,99 @@ function PreviewCanvas() {
}
});
- const initCanvas = (canvas: HTMLCanvasElement) => {
- if (canvasTransferredRef.current) return;
+ createEffect(() => {
+ const canvas = canvasRef();
const controls = canvasControls();
- if (!controls) return;
+ console.warn("[Player] Canvas init effect", {
+ hasCanvas: !!canvas,
+ hasControls: !!controls,
+ alreadyInit: canvasInitializedRef.current,
+ });
+ if (canvasInitializedRef.current || !canvas || !controls) return;
+ console.warn("[Player] Initializing canvas", {
+ canvasId: canvas.id,
+ isConnected: canvas.isConnected,
+ });
controls.initDirectCanvas(canvas);
- canvasTransferredRef.current = true;
+ canvasInitializedRef.current = true;
+ console.warn("[Player] Canvas initialized successfully");
+ });
+
+ const padding = 4;
+ const frameWidth = () => latestFrame()?.width ?? 1920;
+ const frameHeight = () => latestFrame()?.height ?? 1080;
+
+ const availableWidth = () =>
+ Math.max(debouncedBounds().width - padding * 2, 0);
+ const availableHeight = () =>
+ Math.max(debouncedBounds().height - padding * 2, 0);
+
+ const containerAspect = () => {
+ const width = availableWidth();
+ const height = availableHeight();
+ if (width === 0 || height === 0) return 1;
+ return width / height;
};
+ const frameAspect = () => {
+ const width = frameWidth();
+ const height = frameHeight();
+ if (width === 0 || height === 0) return containerAspect();
+ return width / height;
+ };
+
+ const size = () => {
+ let width: number;
+ let height: number;
+ if (frameAspect() < containerAspect()) {
+ height = availableHeight();
+ width = height * frameAspect();
+ } else {
+ width = availableWidth();
+ height = width / frameAspect();
+ }
+
+ return { width, height };
+ };
+
+ const hasFrame = () => !!latestFrame();
+
return (
<div
ref={setCanvasContainerRef}
class="relative flex-1 justify-center items-center"
style={{ contain: "layout style" }}
>
- <Show when={latestFrame()}>
- {(currentFrame) => {
- const padding = 4;
- const frameWidth = () => currentFrame().width;
- const frameHeight = () => currentFrame().height;
-
- const availableWidth = () =>
- Math.max(debouncedBounds().width - padding * 2, 0);
- const availableHeight = () =>
- Math.max(debouncedBounds().height - padding * 2, 0);
-
- const containerAspect = () => {
- const width = availableWidth();
- const height = availableHeight();
- if (width === 0 || height === 0) return 1;
- return width / height;
- };
-
- const frameAspect = () => {
- const width = frameWidth();
- const height = frameHeight();
- if (width === 0 || height === 0) return containerAspect();
- return width / height;
- };
-
- const size = () => {
- let width: number;
- let height: number;
- if (frameAspect() < containerAspect()) {
- height = availableHeight();
- width = height * frameAspect();
- } else {
- width = availableWidth();
- height = width / frameAspect();
- }
-
- return { width, height };
- };
-
- return (
- <div class="flex overflow-hidden absolute inset-0 justify-center items-center h-full">
- <div
- class="relative"
- style={{
- width: `${size().width}px`,
- height: `${size().height}px`,
- contain: "strict",
- }}
- >
- <canvas
- style={{
- width: `${size().width}px`,
- height: `${size().height}px`,
- "image-rendering": "auto",
- "background-color": "#000000",
- ...(hasRenderedFrame() ? gridStyle : {}),
- }}
- ref={initCanvas}
- id="canvas"
- width={frameWidth()}
- height={frameHeight()}
- />
- <MaskOverlay size={size()} />
- <TextOverlay size={size()} />
- </div>
- </div>
- );
- }}
- </Show>
+ <div
+ class="flex overflow-hidden absolute inset-0 justify-center items-center h-full"
+ style={{ visibility: hasFrame() ? "visible" : "hidden" }}
+ >
+ <div
+ class="relative"
+ style={{
+ width: `${size().width}px`,
+ height: `${size().height}px`,
+ contain: "strict",
+ }}
+ >
+ <canvas
+ style={{
+ width: `${size().width}px`,
+ height: `${size().height}px`,
+ "image-rendering": "auto",
+ "background-color": "#000000",
+ ...(hasRenderedFrame() ? gridStyle : {}),
+ }}
+ ref={setCanvasRef}
+ id="canvas"
+ />
+ <Show when={hasFrame()}>
+ <MaskOverlay size={size()} />
+ <TextOverlay size={size()} />
+ </Show>
+ </div>
+ </div>
</div>
);
}
diff --git a/apps/desktop/src/utils/socket.ts b/apps/desktop/src/utils/socket.ts
index a7c50bbf0..3b603025d 100644
--- a/apps/desktop/src/utils/socket.ts
+++ b/apps/desktop/src/utils/socket.ts
@@ -273,6 +273,52 @@ export function createImageDataWS(
}
}
+ function renderPendingFrameCanvas2D() {
+ if (!pendingNv12Frame || !directCanvas || !directCtx) return;
+
+ const buffer = pendingNv12Frame;
+ pendingNv12Frame = null;
+
+ const NV12_MAGIC = 0x4e563132;
+ if (buffer.byteLength < 28) return;
+
+ const formatCheck = new DataView(buffer, buffer.byteLength - 4, 4);
+ if (formatCheck.getUint32(0, true) !== NV12_MAGIC) return;
+
+ const metadataOffset = buffer.byteLength - 28;
+ const meta = new DataView(buffer, metadataOffset, 28);
+ const yStride = meta.getUint32(0, true);
+ const height = meta.getUint32(4, true);
+ const width = meta.getUint32(8, true);
+
+ if (width > 0 && height > 0) {
+ const ySize = yStride * height;
+ const uvSize = width * (height / 2);
+ const totalSize = ySize + uvSize;
+
+ const frameData = new Uint8ClampedArray(buffer, 0, totalSize);
+
+ if (directCanvas.width !== width || directCanvas.height !== height) {
+ directCanvas.width = width;
+ directCanvas.height = height;
+ }
+
+ const rgba = convertNv12ToRgbaMainThread(
+ frameData,
+ width,
+ height,
+ yStride,
+ );
+ const imageData = new ImageData(rgba, width, height);
+ directCtx.putImageData(imageData, 0, 0);
+
+ if (!hasRenderedFrame()) {
+ setHasRenderedFrame(true);
+ }
+ onmessage({ width, height });
+ }
+ }
+
const canvasControls: CanvasControls = {
initCanvas: (canvas: OffscreenCanvas) => {
worker.postMessage({ type: "init-canvas", canvas }, [canvas]);
@@ -282,6 +328,17 @@ export function createImageDataWS(
},
hasRenderedFrame,
initDirectCanvas: (canvas: HTMLCanvasElement) => {
+ const isNewCanvas = directCanvas !== canvas;
+
+ if (isNewCanvas && directCanvas) {
+ if (mainThreadWebGPU) {
+ disposeWebGPU(mainThreadWebGPU);
+ mainThreadWebGPU = null;
+ }
+ directCtx = null;
+ mainThreadWebGPUInitializing = false;
+ }
+
directCanvas = canvas;
if (!mainThreadWebGPUInitializing && !mainThreadWebGPU) {
@@ -294,20 +351,27 @@ export function createImageDataWS(
mainThreadWebGPUInitializing = false;
if (pendingNv12Frame && directCanvas) {
renderPendingNv12Frame();
- } else {
- onRequestFrame?.();
}
+ onRequestFrame?.();
})
.catch((e) => {
mainThreadWebGPUInitializing = false;
- console.error("[socket] Main thread WebGPU init failed:", e);
+ console.error("[Socket] Main thread WebGPU init failed:", e);
directCtx =
directCanvas?.getContext("2d", { alpha: false }) ?? null;
+ if (pendingNv12Frame && directCanvas && directCtx) {
+ renderPendingFrameCanvas2D();
+ }
+ onRequestFrame?.();
});
} else {
mainThreadWebGPUInitializing = false;
directCtx =
directCanvas?.getContext("2d", { alpha: false }) ?? null;
+ if (pendingNv12Frame && directCanvas && directCtx) {
+ renderPendingFrameCanvas2D();
+ }
+ onRequestFrame?.();
}
});
}
@@ -512,6 +576,7 @@ export function createImageDataWS(
const yStride = meta.getUint32(0, true);
const height = meta.getUint32(4, true);
const width = meta.getUint32(8, true);
+ const frameNumber = meta.getUint32(12, true);
if (width > 0 && height > 0) {
const ySize = yStride * height;
@@ -556,11 +621,30 @@ export function createImageDataWS(
}
if (directCanvas && directCtx) {
+ if (!directCanvas.isConnected) {
+ const domCanvas = document.getElementById(
+ "canvas",
+ ) as HTMLCanvasElement | null;
+ if (domCanvas && domCanvas !== directCanvas) {
+ directCanvas = domCanvas;
+ directCtx = domCanvas.getContext("2d", { alpha: false });
+ if (!directCtx) {
+ console.error(
+ "[Socket] Failed to get 2D context from DOM canvas",
+ );
+ return;
+ }
+ } else {
+ return;
+ }
+ }
+
const metadataOffset = buffer.byteLength - 28;
const meta = new DataView(buffer, metadataOffset, 28);
const yStride = meta.getUint32(0, true);
const height = meta.getUint32(4, true);
const width = meta.getUint32(8, true);
+ const frameNumber = meta.getUint32(12, true);
if (width > 0 && height > 0) {
const ySize = yStride * height;
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 2cde6342c..ed4697493 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -134,8 +134,8 @@ async setPlayheadPosition(frameNumber: number) : Promise<null> {
async setProjectConfig(config: ProjectConfiguration) : Promise<null> {
return await TAURI_INVOKE("set_project_config", { config });
},
-async updateProjectConfigInMemory(config: ProjectConfiguration) : Promise<null> {
- return await TAURI_INVOKE("update_project_config_in_memory", { config });
+async updateProjectConfigInMemory(config: ProjectConfiguration, frameNumber: number | null, fps: number | null, resolutionBase: XY<number> | null) : Promise<null> {
+ return await TAURI_INVOKE("update_project_config_in_memory", { config, frameNumber, fps, resolutionBase });
},
async generateZoomSegmentsFromClicks() : Promise<ZoomSegment[]> {
return await TAURI_INVOKE("generate_zoom_segments_from_clicks");
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 7015644e3..926a28057 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -434,11 +434,9 @@ impl EditorInstance {
&segment_medias.cursor,
&segment_frames,
);
- tracing::debug!(frame_number, "Preview: sending frame to renderer");
self.renderer
.render_frame(segment_frames, uniforms, segment_medias.cursor.clone())
.await;
- tracing::debug!(frame_number, "Preview: renderer accepted frame");
} else {
warn!("Preview renderer: no frames returned for frame {}", frame_number);
}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index ad6da5253..b32ecf141 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -89,6 +89,7 @@ declare global {
const IconLucideRatio: typeof import('~icons/lucide/ratio.jsx')['default']
const IconLucideRectangleHorizontal: typeof import('~icons/lucide/rectangle-horizontal.jsx')['default']
const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
+ const IconLucideRotateCw: typeof import('~icons/lucide/rotate-cw.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
const IconLucideSparkles: typeof import('~icons/lucide/sparkles.jsx')['default']
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']