Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Optimize NV12 conversion, RGBA path & WebGPU tweaks

Richie McIlroy4fcf6e640d83
diff --git a/apps/desktop/src/utils/frame-worker.ts b/apps/desktop/src/utils/frame-worker.ts
index 07786d9ff..2be2376cb 100644
--- a/apps/desktop/src/utils/frame-worker.ts
+++ b/apps/desktop/src/utils/frame-worker.ts
@@ -37,6 +37,10 @@ interface ResetFrameStateMessage {
type: "reset-frame-state";
}
+interface WakeMessage {
+ type: "wake";
+}
+
interface ReadyMessage {
type: "ready";
}
@@ -90,7 +94,8 @@ type IncomingMessage =
| ResizeMessage
| InitSharedBufferMessage
| CleanupMessage
- | ResetFrameStateMessage;
+ | ResetFrameStateMessage
+ | WakeMessage;
interface FrameTiming {
frameNumber: number;
@@ -307,23 +312,21 @@ function convertNv12ToRgba(
for (let row = 0; row < height; row++) {
const yRowOffset = row * yStride;
- const uvRowOffset = Math.floor(row / 2) * uvStride;
+ const uvRowOffset = (row >> 1) * uvStride;
const rgbaRowOffset = row * width * 4;
- for (let col = 0; col < width; col++) {
- const y = yPlane[yRowOffset + col] - 16;
-
- const uvCol = Math.floor(col / 2) * 2;
+ for (let col = 0; col < width; col += 2) {
+ const uvCol = (col >> 1) * 2;
const u = uvPlane[uvRowOffset + uvCol] - 128;
const v = uvPlane[uvRowOffset + uvCol + 1] - 128;
-
- const c = 298 * y;
const d = u;
const e = v;
- let r = (c + 409 * e + 128) >> 8;
- let g = (c - 100 * d - 208 * e + 128) >> 8;
- let b = (c + 516 * d + 128) >> 8;
+ const y0 = yPlane[yRowOffset + col] - 16;
+ const c0 = 298 * y0;
+ let r = (c0 + 409 * e + 128) >> 8;
+ let g = (c0 - 100 * d - 208 * e + 128) >> 8;
+ let b = (c0 + 516 * d + 128) >> 8;
r = r < 0 ? 0 : r > 255 ? 255 : r;
g = g < 0 ? 0 : g > 255 ? 255 : g;
@@ -334,6 +337,25 @@ function convertNv12ToRgba(
rgba[rgbaOffset + 1] = g;
rgba[rgbaOffset + 2] = b;
rgba[rgbaOffset + 3] = 255;
+
+ const nextCol = col + 1;
+ if (nextCol < width) {
+ const y1 = yPlane[yRowOffset + nextCol] - 16;
+ const c1 = 298 * y1;
+ let nextR = (c1 + 409 * e + 128) >> 8;
+ let nextG = (c1 - 100 * d - 208 * e + 128) >> 8;
+ let nextB = (c1 + 516 * d + 128) >> 8;
+
+ nextR = nextR < 0 ? 0 : nextR > 255 ? 255 : nextR;
+ nextG = nextG < 0 ? 0 : nextG > 255 ? 255 : nextG;
+ nextB = nextB < 0 ? 0 : nextB > 255 ? 255 : nextB;
+
+ const nextRgbaOffset = rgbaOffset + 4;
+ rgba[nextRgbaOffset] = nextR;
+ rgba[nextRgbaOffset + 1] = nextG;
+ rgba[nextRgbaOffset + 2] = nextB;
+ rgba[nextRgbaOffset + 3] = 255;
+ }
}
}
@@ -1095,6 +1117,11 @@ self.onmessage = async (e: MessageEvent<IncomingMessage>) => {
return;
}
+ if (e.data.type === "wake") {
+ startRenderLoop();
+ return;
+ }
+
if (e.data.type === "init-shared-buffer") {
consumer = createConsumer(e.data.buffer);
useSharedBuffer = true;
diff --git a/apps/desktop/src/utils/socket.ts b/apps/desktop/src/utils/socket.ts
index 3c0e718a4..cea9c9aa9 100644
--- a/apps/desktop/src/utils/socket.ts
+++ b/apps/desktop/src/utils/socket.ts
@@ -66,23 +66,21 @@ function convertNv12ToRgbaMainThread(
for (let row = 0; row < height; row++) {
const yRowOffset = row * yStride;
- const uvRowOffset = Math.floor(row / 2) * uvStride;
+ const uvRowOffset = (row >> 1) * uvStride;
const rgbaRowOffset = row * width * 4;
- for (let col = 0; col < width; col++) {
- const y = yPlane[yRowOffset + col] - 16;
-
- const uvCol = Math.floor(col / 2) * 2;
+ for (let col = 0; col < width; col += 2) {
+ const uvCol = (col >> 1) * 2;
const u = uvPlane[uvRowOffset + uvCol] - 128;
const v = uvPlane[uvRowOffset + uvCol + 1] - 128;
-
- const c = 298 * y;
const d = u;
const e = v;
- let r = (c + 409 * e + 128) >> 8;
- let g = (c - 100 * d - 208 * e + 128) >> 8;
- let b = (c + 516 * d + 128) >> 8;
+ const y0 = yPlane[yRowOffset + col] - 16;
+ const c0 = 298 * y0;
+ let r = (c0 + 409 * e + 128) >> 8;
+ let g = (c0 - 100 * d - 208 * e + 128) >> 8;
+ let b = (c0 + 516 * d + 128) >> 8;
r = r < 0 ? 0 : r > 255 ? 255 : r;
g = g < 0 ? 0 : g > 255 ? 255 : g;
@@ -93,6 +91,25 @@ function convertNv12ToRgbaMainThread(
rgba[rgbaOffset + 1] = g;
rgba[rgbaOffset + 2] = b;
rgba[rgbaOffset + 3] = 255;
+
+ const nextCol = col + 1;
+ if (nextCol < width) {
+ const y1 = yPlane[yRowOffset + nextCol] - 16;
+ const c1 = 298 * y1;
+ let nextR = (c1 + 409 * e + 128) >> 8;
+ let nextG = (c1 - 100 * d - 208 * e + 128) >> 8;
+ let nextB = (c1 + 516 * d + 128) >> 8;
+
+ nextR = nextR < 0 ? 0 : nextR > 255 ? 255 : nextR;
+ nextG = nextG < 0 ? 0 : nextG > 255 ? 255 : nextG;
+ nextB = nextB < 0 ? 0 : nextB > 255 ? 255 : nextB;
+
+ const nextRgbaOffset = rgbaOffset + 4;
+ rgba[nextRgbaOffset] = nextR;
+ rgba[nextRgbaOffset + 1] = nextG;
+ rgba[nextRgbaOffset + 2] = nextB;
+ rgba[nextRgbaOffset + 3] = 255;
+ }
}
}
@@ -172,6 +189,7 @@ export function createImageDataWS(
const worker = new FrameWorker();
let pendingFrame: ArrayBuffer | null = null;
let isProcessing = false;
+ let isProcessingSharedFrame = false;
let nextFrame: ArrayBuffer | null = null;
let producer: Producer | null = null;
@@ -210,7 +228,9 @@ export function createImageDataWS(
let mainThreadWebGPU: WebGPURenderer | null = null;
let mainThreadWebGPUInitializing = false;
let pendingNv12Frame: ArrayBuffer | null = null;
+ let pendingRgbaFrame: ArrayBuffer | null = null;
let pendingNv12RafId: number | null = null;
+ let pendingRgbaRafId: number | null = null;
let lastRenderedFrameData: {
data: Uint8ClampedArray;
@@ -227,24 +247,13 @@ export function createImageDataWS(
yStride: number,
isNv12: boolean,
) {
- if (
- lastRenderedFrameData &&
- lastRenderedFrameData.data.length === frameData.length
- ) {
- lastRenderedFrameData.data.set(frameData);
- lastRenderedFrameData.width = width;
- lastRenderedFrameData.height = height;
- lastRenderedFrameData.yStride = yStride;
- lastRenderedFrameData.isNv12 = isNv12;
- } else {
- lastRenderedFrameData = {
- data: new Uint8ClampedArray(frameData),
- width,
- height,
- yStride,
- isNv12,
- };
- }
+ lastRenderedFrameData = {
+ data: frameData,
+ width,
+ height,
+ yStride,
+ isNv12,
+ };
if (!hasRenderedFrame()) {
setHasRenderedFrame(true);
}
@@ -273,6 +282,7 @@ export function createImageDataWS(
pendingFrame = null;
nextFrame = null;
isProcessing = false;
+ isProcessingSharedFrame = false;
if (mainThreadWebGPU) {
disposeWebGPU(mainThreadWebGPU);
@@ -281,10 +291,15 @@ export function createImageDataWS(
mainThreadWebGPUInitializing = false;
pendingNv12Frame = null;
+ pendingRgbaFrame = null;
if (pendingNv12RafId !== null) {
cancelAnimationFrame(pendingNv12RafId);
pendingNv12RafId = null;
}
+ if (pendingRgbaRafId !== null) {
+ cancelAnimationFrame(pendingRgbaRafId);
+ pendingRgbaRafId = null;
+ }
mainThreadNv12Buffer = null;
mainThreadNv12BufferSize = 0;
cachedDirectImageData = null;
@@ -362,6 +377,87 @@ export function createImageDataWS(
});
}
+ function renderPendingRgbaFrame() {
+ if (!pendingRgbaFrame || !mainThreadWebGPU || !directCanvas) return;
+
+ const buffer = pendingRgbaFrame;
+ pendingRgbaFrame = null;
+
+ if (buffer.byteLength < 24) return;
+
+ const metadataOffset = buffer.byteLength - 24;
+ const meta = new DataView(buffer, metadataOffset, 24);
+ const strideBytes = meta.getUint32(0, true);
+ const height = meta.getUint32(4, true);
+ const width = meta.getUint32(8, true);
+
+ if (width > 0 && height > 0) {
+ const frameDataSize = strideBytes * height;
+ if (strideBytes === 0 || buffer.byteLength - 24 < frameDataSize) return;
+
+ const frameData = new Uint8ClampedArray(buffer, 0, frameDataSize);
+
+ if (directCanvas.width !== width || directCanvas.height !== height) {
+ directCanvas.width = width;
+ directCanvas.height = height;
+ }
+
+ renderFrameWebGPU(
+ mainThreadWebGPU,
+ frameData,
+ width,
+ height,
+ strideBytes,
+ );
+ actualRendersCount++;
+
+ storeRenderedFrame(frameData, width, height, strideBytes, false);
+ onmessage({ width, height });
+ }
+ }
+
+ function schedulePendingRgbaFrame(buffer: ArrayBuffer) {
+ pendingRgbaFrame = buffer;
+ if (pendingRgbaRafId !== null) return;
+
+ pendingRgbaRafId = requestAnimationFrame(() => {
+ pendingRgbaRafId = null;
+ renderPendingRgbaFrame();
+ });
+ }
+
+ function renderNv12FrameCanvas2D(
+ frameData: Uint8ClampedArray,
+ width: number,
+ height: number,
+ yStride: number,
+ ) {
+ if (!directCanvas || !directCtx) return;
+
+ if (directCanvas.width !== width || directCanvas.height !== height) {
+ directCanvas.width = width;
+ directCanvas.height = height;
+ }
+
+ const rgba = convertNv12ToRgbaMainThread(frameData, width, height, yStride);
+
+ if (
+ !cachedDirectImageData ||
+ cachedDirectWidth !== width ||
+ cachedDirectHeight !== height
+ ) {
+ cachedDirectImageData = new ImageData(width, height);
+ cachedDirectWidth = width;
+ cachedDirectHeight = height;
+ }
+ cachedDirectImageData.data.set(rgba);
+ directCtx.putImageData(cachedDirectImageData, 0, 0);
+
+ storeRenderedFrame(frameData, width, height, yStride, true);
+ actualRendersCount++;
+ onmessage({ width, height });
+ }
+
function renderPendingFrameCanvas2D() {
if (!pendingNv12Frame || !directCanvas || !directCtx) return;
@@ -386,27 +482,7 @@ export function createImageDataWS(
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(
- new Uint8ClampedArray(rgba),
- width,
- height,
- );
- directCtx.putImageData(imageData, 0, 0);
-
- storeRenderedFrame(frameData, width, height, yStride, true);
- onmessage({ width, height });
+ renderNv12FrameCanvas2D(frameData, width, height, yStride);
}
}
@@ -448,6 +524,9 @@ export function createImageDataWS(
if (pendingNv12Frame && directCanvas) {
renderPendingNv12Frame();
}
+ if (pendingRgbaFrame && directCanvas) {
+ renderPendingRgbaFrame();
+ }
onRequestFrame?.();
})
.catch((e) => {
@@ -523,7 +602,21 @@ export function createImageDataWS(
const rgba = convertNv12ToRgbaMainThread(data, width, height, yStride);
imageData = new ImageData(new Uint8ClampedArray(rgba), width, height);
} else {
- imageData = new ImageData(new Uint8ClampedArray(data), width, height);
+ const expectedRowBytes = width * 4;
+ if (yStride === expectedRowBytes) {
+ imageData = new ImageData(new Uint8ClampedArray(data), width, height);
+ } else {
+ const normalized = new Uint8ClampedArray(expectedRowBytes * height);
+ for (let row = 0; row < height; row++) {
+ const srcStart = row * yStride;
+ const destStart = row * expectedRowBytes;
+ normalized.set(
+ data.subarray(srcStart, srcStart + expectedRowBytes),
+ destStart,
+ );
+ }
+ imageData = new ImageData(normalized, width, height);
+ }
}
const canvas = document.createElement("canvas");
canvas.width = width;
@@ -556,6 +649,7 @@ export function createImageDataWS(
if (e.data.type === "error") {
console.error("[FrameWorker]", e.data.message);
+ isProcessingSharedFrame = false;
isProcessing = false;
processNextFrame();
return;
@@ -564,6 +658,7 @@ export function createImageDataWS(
if (e.data.type === "frame-queued") {
const { width, height } = e.data;
onmessage({ width, height });
+ isProcessingSharedFrame = false;
isProcessing = false;
processNextFrame();
return;
@@ -576,6 +671,11 @@ export function createImageDataWS(
if (!hasRenderedFrame()) {
setHasRenderedFrame(true);
}
+ if (isProcessingSharedFrame) {
+ isProcessingSharedFrame = false;
+ isProcessing = false;
+ processNextFrame();
+ }
return;
}
@@ -587,6 +687,7 @@ export function createImageDataWS(
if (e.data.type === "decoded") {
const { bitmap, width, height } = e.data;
onmessage({ width, height, bitmap });
+ isProcessingSharedFrame = false;
isProcessing = false;
processNextFrame();
}
@@ -609,9 +710,14 @@ export function createImageDataWS(
if (producer) {
const written = producer.write(buffer);
if (!written) {
+ isProcessingSharedFrame = false;
worker.postMessage({ type: "frame", buffer }, [buffer]);
+ } else {
+ isProcessingSharedFrame = true;
+ worker.postMessage({ type: "wake" });
}
} else {
+ isProcessingSharedFrame = false;
worker.postMessage({ type: "frame", buffer }, [buffer]);
}
}
@@ -743,34 +849,7 @@ export function createImageDataWS(
const totalSize = ySize + uvSize;
const nv12Data = new Uint8ClampedArray(buffer, 0, totalSize);
- const rgbaData = convertNv12ToRgbaMainThread(
- nv12Data,
- width,
- height,
- yStride,
- );
-
- if (directCanvas.width !== width || directCanvas.height !== height) {
- directCanvas.width = width;
- directCanvas.height = height;
- }
-
- if (
- !cachedDirectImageData ||
- cachedDirectWidth !== width ||
- cachedDirectHeight !== height
- ) {
- cachedDirectImageData = new ImageData(width, height);
- cachedDirectWidth = width;
- cachedDirectHeight = height;
- }
- cachedDirectImageData.data.set(rgbaData);
- directCtx.putImageData(cachedDirectImageData, 0, 0);
-
- storeRenderedFrame(nv12Data, width, height, yStride, true);
- actualRendersCount++;
-
- onmessage({ width, height });
+ renderNv12FrameCanvas2D(nv12Data, width, height, yStride);
}
return;
}
@@ -787,30 +866,16 @@ export function createImageDataWS(
if (mainThreadWebGPU && directCanvas && buffer.byteLength >= 24) {
const metadataOffset = buffer.byteLength - 24;
const meta = new DataView(buffer, metadataOffset, 24);
- const strideBytes = meta.getUint32(0, true);
const height = meta.getUint32(4, true);
const width = meta.getUint32(8, true);
if (width > 0 && height > 0) {
- const frameDataSize = strideBytes * height;
- const frameData = new Uint8ClampedArray(buffer, 0, frameDataSize);
-
if (directCanvas.width !== width || directCanvas.height !== height) {
directCanvas.width = width;
directCanvas.height = height;
}
- renderFrameWebGPU(
- mainThreadWebGPU,
- frameData,
- width,
- height,
- strideBytes,
- );
- actualRendersCount++;
-
- storeRenderedFrame(frameData, width, height, strideBytes, false);
- onmessage({ width, height });
+ schedulePendingRgbaFrame(buffer);
}
return;
}
diff --git a/apps/desktop/src/utils/webgpu-renderer.ts b/apps/desktop/src/utils/webgpu-renderer.ts
index 560bb759a..46b0db13d 100644
--- a/apps/desktop/src/utils/webgpu-renderer.ts
+++ b/apps/desktop/src/utils/webgpu-renderer.ts
@@ -76,14 +76,22 @@ export interface WebGPURenderer {
canvas: OffscreenCanvas;
}
+async function requestWebGPUAdapter(): Promise<GPUAdapter | null> {
+ let highPerformanceAdapter: GPUAdapter | null = null;
+ try {
+ highPerformanceAdapter = await navigator.gpu.requestAdapter({
+ powerPreference: "high-performance",
+ });
+ } catch {}
+ return highPerformanceAdapter ?? navigator.gpu.requestAdapter();
+}
+
export async function isWebGPUSupported(): Promise<boolean> {
if (typeof navigator === "undefined" || !navigator.gpu) {
return false;
}
try {
- const adapter = await navigator.gpu.requestAdapter({
- powerPreference: "high-performance",
- });
+ const adapter = await requestWebGPUAdapter();
return adapter !== null;
} catch {
return false;
@@ -93,9 +101,7 @@ export async function isWebGPUSupported(): Promise<boolean> {
export async function initWebGPU(
canvas: OffscreenCanvas,
): Promise<WebGPURenderer> {
- const adapter = await navigator.gpu.requestAdapter({
- powerPreference: "high-performance",
- });
+ const adapter = await requestWebGPUAdapter();
if (!adapter) {
throw new Error("No WebGPU adapter available");
}
@@ -299,7 +305,8 @@ export function renderFrameWebGPU(
colorAttachments: [
{
view: currentTexture.createView(),
- loadOp: "load",
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
+ loadOp: "clear",
storeOp: "store",
},
],
@@ -412,7 +419,8 @@ export function renderNv12FrameWebGPU(
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
- loadOp: "load",
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
+ loadOp: "clear",
storeOp: "store",
},
],