Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript
14.9 KB
Raw Blame
---
sidebar_position: 5
title: Frontend Backend Communication
---

import { AiGeneratedBanner, Tip } from '@freemocap/skellydocs';

<AiGeneratedBanner />

# Backend Communication (Frontend Side)

The frontend talks to the Python backend over three channels: **REST** for commands, **WebSocket** for streaming data, and **Electron IPC** for desktop operations. All three are managed through the service layer in `src/services/`.

## Service Layer Overview

```
src/services/
β”œβ”€β”€ server/
β”‚   β”œβ”€β”€ ServerContextProvider.tsx     Central service manager (~700 lines)
β”‚   β”œβ”€β”€ server-context.ts            ServerContext interface + useServer hook
β”‚   └── server-helpers/
β”‚       β”œβ”€β”€ websocket-connection.ts   WebSocket wrapper with auto-reconnect
β”‚       β”œβ”€β”€ websocket-message-types.ts Type guards for message discrimination
β”‚       β”œβ”€β”€ frame-processor/          Binary frame parsing + JPEG decode worker
β”‚       β”‚   β”œβ”€β”€ frame-processor.ts    Main frame processing logic
β”‚       β”‚   β”œβ”€β”€ binary-frame-parser.ts Binary frame header parsing
β”‚       β”‚   β”œβ”€β”€ binary-protocol.ts    Frame protocol constants
β”‚       β”‚   └── frame-decode.worker.ts Web Worker for JPEG decoding
β”‚       β”œβ”€β”€ image-overlay/            2D overlay compositing on camera feeds
β”‚       β”‚   β”œβ”€β”€ image-overlay-system.ts    Central overlay manager
β”‚       β”‚   β”œβ”€β”€ overlay-renderer-factory.ts Creates renderers per tracker type
β”‚       β”‚   β”œβ”€β”€ charuco-overlay-renderer.ts CharUco marker overlay
β”‚       β”‚   └── mediapipe-overlay-renderer.ts MediaPipe skeleton overlay
β”‚       β”œβ”€β”€ canvas-manager.ts         Per-camera offscreen canvas rendering
β”‚       β”œβ”€β”€ offscreen-renderer.worker.ts Web Worker for canvas compositing
β”‚       β”œβ”€β”€ framerate-store.ts        Observable framerate data
β”‚       β”œβ”€β”€ log-store.ts              Buffered server logs with localStorage
β”‚       β”œβ”€β”€ console-log-bridge.ts     Intercepts console.log β†’ log store
β”‚       └── tracked-object-definition.ts Tracker schema types
└── electron-ipc/
    β”œβ”€β”€ electron-ipc.ts               isElectron() guard
    β”œβ”€β”€ electron-ipc-client.ts        tRPC proxy client over Electron IPC
    └── index.ts
```

## ServerContextProvider

`ServerContextProvider.tsx` is the largest single file in the frontend (~700 lines). It manages everything that depends on the WebSocket connection. Its responsibilities grew together because they share one WebSocket, one rAF loop, and one lifecycle β€” but this is the current state, not the target architecture. A refactor to break it into focused pieces (connection management, frame pipeline, overlay system) is planned but deferred.

### What it owns
- `WebSocketConnection` β€” raw WebSocket with auto-reconnect and heartbeat
- `FrameProcessor` β€” binary JPEG frame parsing and decoding (in a Web Worker)
- `CanvasManager` β€” per-camera offscreen canvas renderers
- `OverlayManager` / `OverlayRendererFactory` β€” 2D overlay compositing (CharUco markers, MediaPipe skeletons)
- `FramerateStore` β€” observable framerate data (both backend-reported and browser-measured FPS)
- `LogStore` β€” buffered server logs with localStorage persistence

### What it provides (via React Context)
- `isConnected`, `connect(host, port)`, `disconnect()`
- `sendWebsocketMessage(type, payload)` β€” send arbitrary JSON messages
- `setCanvasForCamera(cameraId, canvas)` β€” register a canvas element for a camera
- `getFps()`, `getServerFps()` β€” read current framerate
- `subscribeToKeypointsRaw(callback)`, `subscribeToKeypointsFiltered(callback)`, `subscribeToRigidBodies(callback)` β€” subscribe to 3D data streams
- `setOverlayVisibility(trackerId, visible)` β€” toggle overlay rendering
- `trackerSchemas`, `activeTrackerId`, `getActiveSchema()` β€” tracker metadata

### Lifecycle

```
Mount β†’ create service instances β†’ connect WebSocket β†’ start rAF loop
                                                                β”‚
                                                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                                      β”‚  every frame:       β”‚
                                                      β”‚  1. ack frame       β”‚
                                                      β”‚  2. dispatch JSON    β”‚
                                                      β”‚  3. decode binary    β”‚
                                                      β”‚  4. measure FPS      β”‚
                                                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Unmount β†’ stop rAF loop β†’ disconnect WebSocket β†’ destroy services
```

## WebSocket Connection

The WebSocket wrapper (`websocket-connection.ts`) provides:

- **Auto-reconnect** with exponential backoff: 1s β†’ 2s β†’ 4s β†’ 8s β†’ 16s (max 5 attempts, then stops)
- **Heartbeat**: ping/pong every 30 seconds to detect dead connections
- **Message dispatch**: routes binary messages to the frame processor, JSON messages through type guards

Message types are discriminated by first byte or JSON shape:

| Type | Direction | Format | Purpose |
|---|---|---|---|
| Binary frame | Server β†’ Client | Structured header+camera+footer | Camera frames (see API Boundary for full format) |
| Binary keypoints | Server β†’ Client | Structured header+blocks+footer | 3D keypoint positions (when binary mode enabled) |
| JSON: log_record | Server β†’ Client | `{message_type: "log_record", levelname, message, timestamp}` | Server logs |
| JSON: framerate_update | Server β†’ Client | `{message_type: "framerate_update", backend_framerate, frontend_framerate}` | FPS metrics |
| JSON: frontend_payload | Server β†’ Client | `{message_type: "frontend_payload", payload_type, data}` | Keypoints, rigid bodies, overlays, pupil data |
| JSON: posthoc_progress | Server β†’ Client | `{message_type: "posthoc_progress", pipeline_id, phase, progress_fraction}` | Pipeline stage progress |
| JSON: tracker_schemas | Server β†’ Client | `{message_type: "tracker_schemas", schemas}` | Tracker metadata (plural: multiple schemas in one message) |
| JSON: command | Client β†’ Server | `{frameNumber: N}`, `{ping}`, etc. | Frame acks, heartbeat |

## The rAF Processing Loop

Why `requestAnimationFrame` instead of processing WebSocket messages as they arrive?

**WebSocket messages can storm.** With N cameras at 30fps, the server sends N binary frames every ~33ms. If you process each message with `await` (for decoding), the event loop yields between messages. A storm of messages means you never finish processing one batch before the next arrives β€” the microtask queue fills, the main thread starves, and the UI freezes.

**rAF gives you one tick per frame.** The loop runs at display refresh rate (typically 60Hz). Each tick, it drains all queued messages, processes them, and renders. Then it waits for the next frame. This guarantees the UI stays responsive.

### Loop Structure (each tick)

```
1. ACK FRAME NUMBER
   Send the latest frame number back to the server immediately.
   This lets the server pipeline the next batch of frames while
   we decode the current batch.

2. DISPATCH JSON PAYLOADS (synchronous)
   Drain any buffered JSON messages:
   - Keypoints β†’ notify subscribers (Three.js update)
   - Rigid bodies β†’ notify subscribers
   - Overlays β†’ queue for overlay compositing
   - Logs β†’ push to LogStore
   - Pipeline progress β†’ dispatch to Redux
   - Framerate β†’ update FramerateStore

3. DECODE BINARY FRAMES (asynchronous, non-blocking)
   JPEG frames are decoded in a Web Worker so the main thread
   stays free. Decoded frames are posted back and rendered
   to their per-camera canvases.

4. MEASURE FRONTEND FRAMERATE
   Track inter-arrival times between decoded frames to compute
   the effective frontend FPS.
```

<Tip shortInfo="The frame acknowledgment (step 1) happens before decoding (step 3). This is critical: it means the backend can pipeline the next batch of frames while the frontend decodes the current batch. Without this, throughput drops by ~2x." />

## REST API (`ServerUrls`)

The `ServerUrls` singleton (`src/constants/server-urls.ts`) centralizes all REST endpoint URLs. Default backend: `localhost:53117`.

### Endpoint Categories

**Camera Management (SkellyCam)**
- `POST /skellycam/camera/detect` β€” Detect connected USB cameras
- `POST /skellycam/camera/group/apply` β€” Connect cameras with configurations
- `DELETE /skellycam/camera/group/close/all` β€” Disconnect all cameras
- `GET /skellycam/camera/group/all/pause_unpause` β€” Toggle camera stream pause
- `POST /skellycam/camera/group/all/record/start` β€” Start recording on all cameras
- `GET /skellycam/camera/group/all/record/stop` β€” Stop recording

**Playback**
- `GET /freemocap/playback/recordings` β€” List all recordings
- `GET /freemocap/playback/{id}/videos` β€” List videos in a recording
- `GET /freemocap/playback/{id}/videos/{video_id}` β€” Stream a video file
- `GET /freemocap/playback/{id}/timestamps` β€” Get all timestamps
- `GET /freemocap/playback/{id}/status` β€” Get recording status
- `GET /freemocap/playback/{id}/bundle` β€” Get full playback bundle

**Calibration**
- `POST /freemocap/calibration/recording/start` β€” Start calibration recording
- `POST /freemocap/calibration/recording/stop` β€” Stop calibration recording
- `POST /freemocap/calibration/recording/calibrate` β€” Run calibration solver

**Mocap**
- `POST /freemocap/mocap/recording/start` β€” Start mocap recording
- `POST /freemocap/mocap/recording/stop` β€” Stop mocap recording
- `POST /freemocap/mocap/recording/process` β€” Run mocap post-processing

**Realtime**
- `POST /freemocap/realtime/apply` β€” Apply realtime pipeline config
- `DELETE /freemocap/realtime/all/close` β€” Close realtime pipeline

**Posthoc**
- `DELETE /freemocap/posthoc/pipeline/{id}` β€” Stop a specific pipeline
- `DELETE /freemocap/posthoc/pipeline` β€” Stop all pipelines

**Blender**
- `GET /freemocap/blender/detect` β€” Detect Blender installation
- `POST /freemocap/blender/export` β€” Export to .blend
- `GET /freemocap/blender/open` β€” Open in Blender

**System**
- `GET /health` β€” Health check
- `GET /shutdown` β€” Shut down server

## Electron IPC (tRPC)

For Electron-specific operations, the frontend uses a **tRPC proxy client** over Electron's IPC bridge.

### How it works
1. The Electron main process exposes an API via `contextBridge` as `window.electronAPI`
2. `electron-ipc-client.ts` creates a tRPC proxy that calls `window.electronAPI.invoke(path, input)`
3. Data is serialized with `superjson` (handles Dates, Maps, Sets, etc.)
4. The `isElectron()` guard lets the same code run in a browser (Electron IPC calls just no-op)

### Available operations
- File system: open folder dialogs, directory validation, read assets
- Telemetry: enable/disable
- Menu actions: forward native menu events to the renderer
- Auto-update: check for updates, download progress, install

## Data Flow: Which Data Takes Which Path

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ DATA TYPE          β”‚ CHANNEL      β”‚ ENDPOINT / MESSAGE       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Camera frames      β”‚ WebSocket    β”‚ Binary (msgType 0)       β”‚
β”‚                    β”‚              β”‚ β†’ rAF β†’ FrameProcessor   β”‚
β”‚                    β”‚              β”‚ β†’ CanvasManager β†’ <canvas>β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Keypoints (3D)     β”‚ WebSocket    β”‚ Binary (msgType 3)       β”‚
β”‚                    β”‚              β”‚ β†’ rAF β†’ subscriber Set    β”‚
β”‚                    β”‚              β”‚ β†’ Three.js scene          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Rigid bodies       β”‚ WebSocket    β”‚ JSON frontend_payload    β”‚
β”‚                    β”‚              β”‚ β†’ rAF β†’ subscriber Set    β”‚
β”‚                    β”‚              β”‚ β†’ Three.js scene          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Overlays           β”‚ WebSocket    β”‚ JSON frontend_payload    β”‚
β”‚ (CharUco, skel.)   β”‚              β”‚ β†’ rAF β†’ OverlayManager   β”‚
β”‚                    β”‚              β”‚ β†’ CanvasManager           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Commands           β”‚ REST         β”‚ Various POST/GET          β”‚
β”‚ (detect, record,   β”‚              β”‚ β†’ Redux thunk             β”‚
β”‚  calibrate, etc.)  β”‚              β”‚ β†’ state update            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Pipeline progress  β”‚ WebSocket    β”‚ JSON posthoc_progress     β”‚
β”‚                    β”‚              β”‚ β†’ rAF β†’ Redux dispatch    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Server logs        β”‚ WebSocket    β”‚ JSON log_record          β”‚
β”‚                    β”‚              β”‚ β†’ rAF β†’ LogStore          β”‚
β”‚                    β”‚              β”‚ β†’ Redux (log slice)       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Framerate stats    β”‚ WebSocket    β”‚ JSON framerate_update    β”‚
β”‚                    β”‚ + local      β”‚ β†’ rAF β†’ FramerateStore   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Electron ops       β”‚ Electron IPC β”‚ tRPC proxy               β”‚
β”‚ (file dialogs,     β”‚              β”‚ β†’ main process            β”‚
β”‚  menus, updates)   β”‚              β”‚                           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```