# Recording contract

This independent product reproduces the desktop recorder's RGB dataset conventions, not its rendering implementation. Native LuckyEngine was inspected read-only. The contract was checked against `ParquetDataWriter.cpp`, `RobotRecorder.cpp`, `MujocoRecorderUtils.cpp`, `FFmpegWriter.cpp`, `DataTypes.h`, and recording-integrity guidance under `Hazel/src/Hazel/Data/` and `.claude/docs/`.

## Snapshot ownership and timing

The physics worker is the sole owner of MuJoCo model/data. Recording resets the authored scene, stops realtime stepping, and accepts sequential frame requests. Frame `f` captures at physics tick `ceil(f * physics_hz / 30)`, where `physics_hz` is the reciprocal of the compiled model timestep. `Project.physicsTimestep` defaults to 0.002 seconds (500 Hz) and also supports 0.005 seconds (200 Hz). Row timestamps remain `f / 30` and video uses 30 fps. The physical sample can be less than one physics step after nominal camera time; its actual time and `physics_hz` are retained in the trace and export metadata. Older recordings without a rate default to 500 Hz.

The main thread applies that snapshot's exact geom transforms, renders the scene camera into a float render target at the selected output dimensions, applies the renderer’s exposure/ACES tone mapping/sRGB conversion through Three.js OutputPass, flips the GPU pixels vertically, and saves a lossless PNG. Editor handles, camera icons, selection outlines, and grid are excluded via layers. The encoder worker must acknowledge both image and row before the next simulation step. Rendering speed and wall-clock scheduling cannot introduce missing/duplicated data frames. Manual control changes are applied before the next requested sample interval. A separate worker encodes bounded batches during capture, keeping the editor responsive; simulation waits for acknowledgement when encoding is slower than real time.

## Data channels and units

Columns, in native order: `index:int64`, `robot_id:int64`, `timestamp:float64`, `episode_index:int64`, `frame_index:int64`, `task_index:int64`, `frame_flags:uint8`, `action:fixed_size_list<float64>[A]`, `observation.state:fixed_size_list<float64>[S]`. The original Panda example uses A=S=8; imported scenes discover dimensions from their models.

For version-1 starter scenes, Panda actuator order is actuator1–actuator8. Observations are joint1–joint7 and finger_joint1; the passive coupled second finger is not duplicated. Joint positions/actions are radians; the finger is meters (0–0.04). Gripper control 0–255 is rescaled into this physical range using native float arithmetic before float64 serialization. Raw control values and simulation state are retained in the evidence trace for replay. The recorder retains the lossless per-physics-tick control signal (`frame_trace.raw_ctrl_ticks`), of which the 30 Hz `action` column is a downsampled view. Imported policy inference is awaited before its scheduled physics tick. `motion_trace` retains each inference's observations, actions, model hash and `inferenceTick`; `motions` carries frame-boundary policy status. Frame zero stores `initial_state` (`qpos`, `qvel`, `act`). Replay validates the rate and dimensions, restores that state and raw controls, then advances recorded control vectors without rerunning the policy. A finished reference ends capture on the aligned frame and does not set task success.

Version-2 editor scenes use raw actuator controls and all robot qpos entries (including passive, ball and free joints), excluding environment-object joints. Channel names include instance prefixes; joint-state units and `rawControls: true` are explicit in evidence metadata. No torque-to-position rescaling is inferred. All instances form one composite robot channel vector with robot_id=1, not separate per-robot episodes. `robot_type` is `mujoco`. Unsupported native plugins/flex/skins remain outside the supported import path.

MuJoCo 3.13's JS bool-array getters are unbound. The legacy Panda recorder asserts its known limited-actuator contract; the generic recorder avoids those getters and exports raw values. Inspector/API bounds use declared numeric control ranges; they do not claim to expose the model's bool-array flags.

Enabled JavaScript behaviors run through the same fixed-step engine while recording. Their source, imported robot ZIPs and authored scene are embedded in `evidence/project.lucky.zip`. The built-in Panda is a pinned application asset dependency. Reset recreates behavior contexts; scripts receive simulation time rather than wall time.

Bit 1 (`PostReset`, value 2) marks the first frame. Bit 0 (`NewPolicyStep`) remains clear because these examples/manual controls do not run policy inference. Robot ID is 1, episode/task indices start at 0. The scripted push sets success only when actual block displacement exceeds 13 cm; manual episodes remain ungraded (`success=false`).

## Depth & segmentation

Every frame also records two lossless 16-bit grayscale PNG channels, produced from the same snapshot and poses as the RGB frame, so their `frame-%06d.png` index and implied `frame_index / 30` timestamp are identical to the RGB row by construction:

- `sensors/depth/frame-%06d.png` — the Euclidean distance from the camera optical centre along each view ray, in millimetres (saturated at 65535 mm; 0 = no surface within the near/far planes, 0.02 m / 100 m). It is a depth map `meta/info.json` declares `is_depth_map: true`.
- `sensors/segmentation/frame-%06d.png` — the authored entity of the nearest visible geom per pixel (1-based instance id; 0 = background), with `meta/sensors.json` mapping each id to its entity (floor, table, object and robot-instance IDs, or `world`/`robot` for unowned/legacy geometry).

Depth and segmentation render at a sensor resolution decoupled from the RGB video resolution: the video's aspect ratio is preserved and the larger dimension is capped at 256 px (256² → 256×256, 512² → 256×256, 720p HD → 256×144, 1080p Full HD → 256×144). This keeps the channels pixel-aligned with the RGB field of view while bounding the per-frame ray-tracing cost and the accumulated PNG bytes, so 720p/1080p RGB retains the full 90-second take. `meta/sensors.json` records the sensor `width`/`height` alongside the `video_width`/`video_height` they align to.

Browser depth and segmentation use `src/viewport/sensor-capture.ts` on the viewport's existing WebGL context. The pass uses actual visible triangles, world transforms and material alpha tests, including imported GLB and procedural meshes; editor overlays are excluded. RGB and sensor passes run before the physics/frame acknowledgement barrier advances. Runtime-hidden meshes disappear, and spawned entities receive stable IDs for the remainder of the take. Transparent surfaces report the nearest surface above the material alpha threshold (at least 0.001); depth does not simulate refraction. `tests/visual-sensors-browser.ts` checks a tetrahedron at an independently calculated 975 mm, visibility, occlusion, stable IDs, alpha, roll and renderer-state restoration. The separate CPU `SensorRenderer` remains a physics-geometry reference for headless tests; it is not the browser's ground-truth source.

## Additional cameras

Beyond the scene camera, a project can author additional cameras in `cameras` (up to 24). Each has a stable `id` (its dataset key), a `name`, a `position`/`target`, a vertical `fov` (20–100°), and an optional `mount` naming a robot instance and one of its bodies (e.g. `{ robot: "panda-1", body: "hand" }`).

- A fixed camera records from its authored world pose.
- A robot-mounted camera authors `position`/`target` as offsets in the mounted body's local frame; each frame the physics worker composes the body's live MuJoCo `xpos`/`xmat` with that offset, so the camera tracks the link exactly as it moves.

Every camera records its own video plus depth and segmentation with the identical frame indices and timestamps as the RGB data row — the encoder appends them all inside the same per-frame message, so they share `frame_index` and `frame_index / 30` by construction, and any frame-count divergence fails the take. The scene camera keeps the single-camera keys (`observation.images.scene_camera`, `observation.depth`, `observation.instance_segmentation` and the `sensors/depth`/`sensors/segmentation` paths); each additional camera uses `observation.images.<id>` for its video and `sensors/<id>/depth/…` / `sensors/<id>/segmentation/…` for its channels.

Per-camera resolution/aspect: every camera's RGB video is captured at the selected recording resolution (256², 512², 720p HD or 1080p Full HD) with that resolution's aspect ratio; a camera's field of view is its authored vertical `fov` at that aspect. Depth and segmentation for every camera render at the same aspect-matched sensor resolution capped at 256 px on the larger dimension (independent of the video resolution), exactly as the scene camera does today. `meta/sensors.json` lists one entry per camera with its key, the sensor `width`/`height`, and the `video_width`/`video_height` they align to.

## Files and encoding

```
data/chunk-000/file-000.parquet
videos/observation.images.scene_camera/chunk-000/file-000.mp4
sensors/depth/frame-*.png
sensors/segmentation/frame-*.png
meta/episodes/chunk-000/file-000.parquet
meta/tasks.parquet
meta/info.json
meta/stats.json
meta/sensors.json
evidence/{scene.lucky.json,trace.json,recording.json,integrity.json,frame-*.png}
.complete
```

Each additional camera adds a video at `videos/observation.images.<camera>/chunk-000/file-000.mp4` and depth/segmentation under `sensors/<camera>/depth/` and `sensors/<camera>/segmentation/`.

Tasks use the native pandas string index; episode ranges have an exclusive end. Info declares canonical LeRobot `v3.0`, the robot type, 30 Hz, video dimensions, chunk templates, native `lucky_names`, and native action/state statistics. Native `hz` is retained; LeRobot 0.6.1 logs that this extra field is ignored. The reader successfully loads actions, states, task labels, and RGB images.

Video uses FFmpeg WASM's libx264 with `-preset ultrafast -crf 18 -pix_fmt yuv420p -movflags +faststart -an`, matching the desktop generic software writer. The recording panel defaults to 1280×720 HD. 1920×1080 Full HD and the existing 256²/512² options are also supported; HD uses a 16:9 sensor preview with the same vertical field of view as capture. PNG staging is lossless; H.264 is lossy. Three.js pixels and a different encoder build are not expected to be byte-identical to native output.

The worker encodes at most 12 PNGs or 48 MiB per batch, releases those PNG files, and joins the compressed H.264 segments by packet copy using the [FFmpeg concat demuxer](https://ffmpeg.org/ffmpeg-formats.html#concat). Segments use 30,000 Hz movie and video time bases. Concat durations come from differences of cumulative frame times rounded to microseconds, preventing drift when a byte-limited batch ends between whole milliseconds. Finalization decodes/counts all frames with FFprobe and requires matching dimensions, codec, pixel format, rate, finite duration, exact frame count, and every presentation timestamp equal to frame_index / 30 (within one microsecond). It then writes Parquet, metadata, SHA-256 hashes, and the completion marker before exposing downloads. Core 0.12.10's public JS FFprobe wrapper returns stale `Module.ret`; `video.ts` calls the exported C entry point for its actual exit code. Corrupt input and shape/rate/count mismatches are regression-tested.

Source evidence retains the first and last PNG and a deterministic power-of-two reference near the middle of the take. Their actual indices are listed in `evidence/recording.json.reference_frames`; this avoids retaining every PNG just to recover an exact midpoint after Stop. The independent verifier accepts both this list and older datasets with an exact midpoint. LeRobot channel schemas and units are unchanged.

## Limits and failure behavior

Up to eight robot instances and 24 additional cameras share one episode ZIP, with a maximum of 90 seconds at 30 fps. Each camera has a 256 MiB compressed-video cap; all cameras together share a 512 MiB depth/segmentation PNG cap. Sensor dimensions are capped at 256 px (256×144 for HD), so reducing square video from 512 to 256 does not reduce sensor storage. Compressed sizes depend on the actual visible scene. Reaching a cap aborts the take without producing a completed dataset; reduce duration or camera count.

Raw frames stream into IndexedDB during capture; this limits raw-frame buffering but does not make the entire process bounded-memory. FFmpeg retains encoded video segments, and finalization reads persisted frames to construct an in-memory archive. Long/multi-camera recordings can therefore need substantial memory. True streaming final packaging, full video streaming to disk, multi-episode append, separate per-robot datasets and policy-inference metadata remain outside this version. Completed episodes survive reload after the device-local save succeeds; a storage error is shown with instructions to download before closing. Unfinished recordings are lost on reload/close.

Stop finishes the current acknowledged frame and closes the episode. Cancel terminates encoding and discards the result. Worker errors, corrupt frames, memory limits, timeouts, or video mismatch fail visibly and cannot produce a completed download. Asset edits/reset/play are locked while recording; manual joint targets remain available only in manual capture. Recorder cleanup releases the physics lock before another episode starts.

## Reproduce validation

`npm test` runs real physics, recorder, and encoder checks. `npm run test:hd` checks actual H.264 output at all four resolutions, frame order across batch boundaries, partial final batches, exact timestamps, source-buffer release, and invalid/corrupt input rejection. `npm run test:cameras` records two cameras (a fixed camera and one mounted on the Panda hand) and verifies the mounted pose against MuJoCo's live body transform, each camera's depth against known geometry, the shared frame indices/timestamps, and two independently probed H.264 streams. For an actual browser download:

```sh
python3 scripts/verify-recording.py /path/to/episode.zip
npx tsx tests/replay-recording.ts /path/to/episode.zip
```

The Python verifier needs NumPy, Pillow, PyArrow, and system FFmpeg/FFprobe. Optional `--lerobot` also uses the official LeRobot reader with its PyAV backend. The validation environment used LeRobot 0.6.1, CPU Torch 2.11.0, Torchvision 0.26.0, PyAV 15.1.0, datasets 4.8.5, Pandas 2.3.3, PyArrow 25.0.1, and NumPy 2.2.6, isolated under `.cache/`. These are validation tools, not browser runtime dependencies.


## Photographic capture

The recording **Quality** selection is shared with the viewport. Live uses contact shadows and PBR raster rendering. Photographic accumulates 8–128 path tracing samples per frame, then denoises, applies ACES and writes sRGB PNGs to the same H.264 encoder. Physics stays frozen until every camera and sensor channel for that frame completes. Wall-clock capture can be much slower than 30 fps; dataset timestamps remain exactly 30 fps. The chosen quality/sample count is saved in recording evidence. Editable directional, point and spot lights contribute to both modes. Cancel is checked between samples; a context loss or a frame exceeding five minutes fails explicitly.

The recording library now stores summaries separately from payloads. An additive IndexedDB v1-to-v2 migration preserves original ZIP/MP4 bytes and builds the summary index atomically; a failed upgrade rolls back. Old tabs must reload after an upgrade. For a code rollback, retain DB version 2 and the original `episodes` store reader; no payload contraction/deletion is part of this migration. Listings read only summaries, and saves report success only after transaction commit. `tests/dataset-store-browser.ts` checks legacy migration, byte identity and abort-after-request-success behavior in real IndexedDB.
