Free Motion Capture for Everyone πβ¨
TypeScript
import type { CharucoObservation } from "@/services/server/server-helpers/image-overlay/charuco-types";
import type { SkeletonObservation } from "@/services/server/server-helpers/image-overlay/skeleton-types";
import type { TrackedObjectDefinition } from "@/services/server/server-helpers/tracked-object-definition";
export interface CanvasWorker {
worker: Worker;
canvas: HTMLCanvasElement;
initialized: boolean;
}
export class CanvasManager {
private workers: Map<string, CanvasWorker> = new Map();
private workerErrors: Map<string, number> = new Map();
private pendingCanvases: Map<string, HTMLCanvasElement> = new Map();
private readonly maxWorkerErrors: number = 3;
// Overlay visibility + schema apply to ALL camera workers. Stored so a worker
// created mid-stream (camera added) gets current state right after init.
private visibility: { charuco: boolean; skeleton: boolean } = { charuco: true, skeleton: true };
private schema: { schemas: Record<string, TrackedObjectDefinition>; activeId: string | null } | null = null;
/**
* Set or update the canvas for a camera.
* Only creates a new worker if one doesn't exist or if the canvas has changed.
*/
public setCanvasForCamera(cameraId: string, canvas: HTMLCanvasElement): boolean {
// Check if this exact canvas is already set up
const existing = this.workers.get(cameraId);
if (existing?.canvas === canvas && existing.initialized) {
return true;
}
// Check if this is a different canvas for the same camera
if (existing && existing.canvas !== canvas) {
console.log(`Canvas changed for camera ${cameraId}, recreating worker`);
this.terminateWorker(cameraId);
}
// Store pending canvas in case we need to retry
this.pendingCanvases.set(cameraId, canvas);
try {
const worker = this.createWorker(cameraId);
const offscreen = canvas.transferControlToOffscreen();
worker.postMessage(
{ type: 'init', canvas: offscreen },
[offscreen]
);
// Give the freshly-created worker the current overlay state so a camera
// added mid-stream composites correctly without waiting for the next toggle.
worker.postMessage({ type: 'visibility', charuco: this.visibility.charuco, skeleton: this.visibility.skeleton });
if (this.schema) {
worker.postMessage({ type: 'schema', schemas: this.schema.schemas, activeId: this.schema.activeId });
}
this.workers.set(cameraId, {
worker,
canvas,
initialized: true
});
// Reset error count on successful creation
this.workerErrors.delete(cameraId);
this.pendingCanvases.delete(cameraId);
console.log(`Worker created for camera ${cameraId}`);
return true;
} catch (error) {
console.error(`Failed to create worker for camera ${cameraId}:`, error);
this.recordWorkerError(cameraId);
return false;
}
}
/**
* Send a frame to a worker. Creates the worker if it doesn't exist yet.
* Transfers the raw pixel buffer (ArrayBuffer) β ImageBitmap creation
* happens in the per-camera worker so GPU uploads are independent.
*/
public sendFrameToWorker(
cameraId: string,
pixelBuffer: ArrayBuffer,
width: number,
height: number,
): boolean {
const workerInfo = this.workers.get(cameraId);
if (!workerInfo?.initialized) {
const pendingCanvas = this.pendingCanvases.get(cameraId);
if (pendingCanvas) {
console.log(`Worker not ready for ${cameraId}, attempting to create from pending canvas`);
if (this.setCanvasForCamera(cameraId, pendingCanvas)) {
return this.sendFrameToWorker(cameraId, pixelBuffer, width, height);
}
}
console.warn(`No initialized worker for camera ${cameraId}, dropping frame`);
return false;
}
try {
workerInfo.worker.postMessage(
{ type: 'frame', pixelBuffer, width, height },
[pixelBuffer],
);
return true;
} catch (error) {
console.error(`Failed to send frame to worker ${cameraId}:`, error);
this.recordWorkerError(cameraId);
return false;
}
}
/**
* Terminate a worker for a specific camera
*/
public terminateWorker(cameraId: string): void {
const workerInfo = this.workers.get(cameraId);
if (workerInfo) {
try {
workerInfo.worker.terminate();
console.log(`Worker terminated for camera ${cameraId}`);
} catch (error) {
console.error(`Error terminating worker for ${cameraId}:`, error);
}
this.workers.delete(cameraId);
}
// Also clean up any pending canvas
this.pendingCanvases.delete(cameraId);
}
/**
* Terminate all workers
*/
public terminateAllWorkers(): void {
if (this.workers.size === 0) return;
console.log(`Terminating all workers (${this.workers.size} active)`);
for (const [cameraId] of this.workers) {
this.terminateWorker(cameraId);
}
this.workerErrors.clear();
this.pendingCanvases.clear();
}
/**
* Get list of active camera IDs
*/
public getActiveCameraIds(): string[] {
return Array.from(this.workers.keys());
}
/**
* Per-camera display size in physical pixels (CSS size Γ devicePixelRatio).
* Read at ack-time from the canvas element β no ResizeObserver, no listeners,
* no DOM reflow. The backend uses these to downscale JPEGs before encoding,
* cutting decode time, GPU upload, and bandwidth proportionally.
*/
public getDisplaySizes(): Record<string, { width: number; height: number }> {
const sizes: Record<string, { width: number; height: number }> = {};
const dpr = window.devicePixelRatio || 1;
for (const [cameraId, { canvas, initialized }] of this.workers) {
if (!initialized) continue;
sizes[cameraId] = {
width: canvas.clientWidth * dpr,
height: canvas.clientHeight * dpr,
};
}
return sizes;
}
/**
* Check if a worker exists and is initialized for a camera
*/
public hasWorker(cameraId: string): boolean {
const worker = this.workers.get(cameraId);
return worker?.initialized ?? false;
}
private createWorker(cameraId: string): Worker {
const worker = new Worker(
new URL("./offscreen-renderer.worker.ts", import.meta.url),
{ type: "module" },
);
// Set up error handling
worker.onerror = (error) => {
console.error(`Worker error for camera ${cameraId}:`, error);
this.recordWorkerError(cameraId);
};
worker.onmessageerror = (error) => {
console.error(`Worker message error for camera ${cameraId}:`, error);
};
return worker;
}
/**
* Route the latest overlay observations to each camera's worker. Inputs are
* per-camera dicts (cameraId β observation); each worker gets only its own.
*/
public updateOverlays(
charuco: Record<string, CharucoObservation> | null | undefined,
skeleton: Record<string, SkeletonObservation> | null | undefined,
): void {
const cameraIds = new Set<string>();
if (charuco) for (const id of Object.keys(charuco)) cameraIds.add(id);
if (skeleton) for (const id of Object.keys(skeleton)) cameraIds.add(id);
for (const cameraId of cameraIds) {
const info = this.workers.get(cameraId);
if (info?.initialized) {
info.worker.postMessage({
type: "overlays",
charuco: charuco?.[cameraId] ?? null,
skeleton: skeleton?.[cameraId] ?? null,
});
}
}
}
/** Toggle which overlay types every camera worker composites. */
public setOverlayVisibility(charuco: boolean, skeleton: boolean): void {
this.visibility = { charuco, skeleton };
for (const { worker, initialized } of this.workers.values()) {
if (initialized) worker.postMessage({ type: "visibility", charuco, skeleton });
}
}
/** Push the active tracker schema (skeleton connections) to every camera worker. */
public setSchema(schemas: Record<string, TrackedObjectDefinition>, activeId: string | null): void {
this.schema = { schemas, activeId };
for (const { worker, initialized } of this.workers.values()) {
if (initialized) worker.postMessage({ type: "schema", schemas, activeId });
}
}
private recordWorkerError(cameraId: string): void {
const errorCount = (this.workerErrors.get(cameraId) ?? 0) + 1;
this.workerErrors.set(cameraId, errorCount);
if (errorCount >= this.maxWorkerErrors) {
console.error(
`Worker for camera ${cameraId} has failed ${errorCount} times, disabling. ` +
`Worker will be recreated if canvas is set again.`
);
this.terminateWorker(cameraId);
}
}
}