Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
#!/usr/bin/env python
# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Publish the TOM rig's USB cameras to a LiveKit room as live WebRTC video tracks.
Runs on the Raspberry Pi next to the cameras. Each camera becomes its own named video track
(``top``, ``side``, ``wrist_1`` ...) in one room, so any LiveKit client (a browser on your Mac)
can subscribe and watch all feeds with sub-200ms latency over the LAN.
This script is deliberately standalone — it talks to the cameras directly via OpenCV (no lerobot /
torch import) so it runs even when the training stack isn't installed. The device paths mirror
``src/lerobot/robots/tom/config_tom.py`` (stable /dev/v4l/by-path symlinks; see that file for why
path, not index).
Setup (in the project venv):
uv pip install "livekit>=1.0" livekit-api # opencv + numpy already present
Run a LiveKit server in dev mode on the Pi first (devkey/secret, binds all interfaces):
livekit-server --dev --bind 0.0.0.0
Then publish (token is self-minted from the dev key/secret):
python -m tomctl.livekit.cameras --room tom-cams
View on the Mac: open livekit_viewer.html (see its header for the one-liner).
"""
from __future__ import annotations
import argparse
import asyncio
import inspect
import json
import logging
import os
import signal
import threading
import time
import cv2
import numpy as np
from livekit import api, rtc
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("tom-livekit")
# Mirrors config_tom.py. name -> stable by-path capture node. The remote rig publishes up to FOUR
# feeds: wrist_1 + wrist_2 (one per arm), top, side. Every camera is OPTIONAL — a name whose device
# node is absent (or fails to open) is logged and skipped, never blocking the others or remote control.
# Cameras are identical UVC units, so pin by /dev/v4l/by-path (USB port), never /dev/videoN (reorders
# across reboots/replug) — see [[tom-camera-mapping]].
TOM_CAMERAS: dict[str, str] = {
"top": "/dev/v4l/by-path/platform-xhci-hcd.1-usb-0:2:1.0-video-index0",
"side": "/dev/v4l/by-path/platform-xhci-hcd.0-usb-0:2:1.0-video-index0",
"wrist_1": "/dev/v4l/by-path/platform-xhci-hcd.1-usb-0:1.3.3:1.0-video-index0",
"wrist_2": "/dev/v4l/by-path/platform-xhci-hcd.0-usb-0:1:1.0-video-index0",
}
class CameraReader(threading.Thread):
"""Continuously grab frames from one camera on a background thread.
OpenCV's read() is blocking, so we keep it off the asyncio loop and just stash the latest BGR
frame. The publish task reads ``latest`` whenever it's ready to send — a dropped/late grab just
means it reuses the previous frame, which is exactly what you want for a live monitor.
"""
def __init__(self, name: str, device: str, width: int, height: int, capture_fps: int):
super().__init__(name=f"cam-{name}", daemon=True)
self.cam_name = name
self.device = device
self.width = width
self.height = height
self.capture_fps = capture_fps
self._lock = threading.Lock()
self._latest: np.ndarray | None = None
self._stop = threading.Event()
self._failed = False
def _open(self) -> cv2.VideoCapture:
cap = cv2.VideoCapture(self.device, cv2.CAP_V4L2)
# MJPG is the only compressed mode these units expose (raw YUYV would saturate the shared
# USB 2.0 bus). BUFFERSIZE=1 keeps only the newest frame queued so a throttled reader still
# gets a fresh image instead of a backlog.
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG"))
cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
if not cap.isOpened():
raise RuntimeError(f"[{self.cam_name}] could not open {self.device}")
return cap
def failed(self) -> bool:
return self._failed
def run(self) -> None:
try:
cap = self._open()
except Exception as exc: # noqa: BLE001 optional camera: a bad device must not kill the rest
logger.warning("camera %r failed to open, skipping (optional): %s", self.cam_name, exc)
self._failed = True
return
# The cameras stream faster than we publish (e.g. 720p@60). JPEG-decoding every one of those
# frames is the dominant CPU cost, so throttle to the publish rate: grab() drains the stale
# frame cheaply (no decode), then read() decodes just the one we keep. Decode work drops from
# the camera's native fps to ~capture_fps per camera, which is what makes higher res afford-
# able when three of these run at once on the Pi's software encoder.
period = 1.0 / self.capture_fps
try:
while not self._stop.is_set():
start = time.monotonic()
# grab() advances to the newest queued frame (cheap, no decode); retrieve() decodes
# only that one. A single dequeue per cycle keeps USB pressure low — important for the
# wrist cam, which shares a USB 2.0 bus and sits two hub hops deep.
if cap.grab():
ok, frame = cap.retrieve()
if ok and frame is not None and frame.size != 0:
with self._lock:
self._latest = frame
# else: transient corrupt MJPG frame; keep the previous one
remaining = period - (time.monotonic() - start)
if remaining > 0:
self._stop.wait(remaining)
finally:
cap.release()
def latest(self) -> np.ndarray | None:
with self._lock:
return None if self._latest is None else self._latest
def stop(self) -> None:
self._stop.set()
async def _publish_camera(
room: rtc.Room, reader: CameraReader, width: int, height: int, fps: int, bitrate: int
) -> None:
"""Create a video track for one camera and pump RGBA frames into it at the target fps.
Optional camera: wait briefly for the first frame; if the reader failed to open or never delivers,
skip publishing this track entirely (so a dead camera is simply absent, not a broken/empty feed)."""
for _ in range(40): # up to ~2 s for the device to warm up and deliver a frame
if reader.failed():
return
if reader.latest() is not None:
break
await asyncio.sleep(0.05)
if reader.latest() is None:
logger.warning("camera %r delivered no frames, not publishing (optional)", reader.cam_name)
return
source = rtc.VideoSource(width, height)
track = rtc.LocalVideoTrack.create_video_track(reader.cam_name, source)
options = rtc.TrackPublishOptions(
source=rtc.TrackSource.SOURCE_CAMERA,
video_encoding=rtc.VideoEncoding(max_framerate=fps, max_bitrate=bitrate),
)
await room.local_participant.publish_track(track, options)
logger.info(
"published track %r (%dx%d @ %dfps, %.1f Mbps)",
reader.cam_name, width, height, fps, bitrate / 1e6,
)
period = 1.0 / fps
while True:
bgr = reader.latest()
if bgr is not None:
# LiveKit wants a tightly packed RGBA byte buffer of width*height*4.
rgba = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGBA)
frame = rtc.VideoFrame(width, height, rtc.VideoBufferType.RGBA, rgba.tobytes())
# capture_frame is synchronous in current livekit-rtc; guard in case a version returns a
# coroutine so this keeps working across SDK updates.
result = source.capture_frame(frame)
if inspect.isawaitable(result):
await result
await asyncio.sleep(period)
async def main(args: argparse.Namespace) -> None:
requested = TOM_CAMERAS if not args.cameras else {n: TOM_CAMERAS[n] for n in args.cameras}
# Every camera is OPTIONAL: keep only the ones whose device node is present right now. A missing
# camera is logged and skipped so it never blocks the others (or remote control). Zero cameras is
# fine too — we still connect as a publisher (with no tracks), so the control path is unaffected.
cameras = {n: dev for n, dev in requested.items() if os.path.exists(dev)}
for n, dev in requested.items():
if n not in cameras:
logger.warning("camera %r device not present, skipping (optional): %s", n, dev)
if not cameras:
logger.warning("no cameras available — connecting as a publisher with no video tracks")
token = (
api.AccessToken(args.api_key, args.api_secret)
.with_identity(args.identity)
.with_name("TOM Pi publisher")
.with_grants(api.VideoGrants(room_join=True, room=args.room))
.to_jwt()
)
room = rtc.Room()
# The control bridge broadcasts the active driver's PRIMARY camera on topic "session". We're the
# camera-streaming server, so it's communicated to us here. This is DESIGNATION ONLY — we don't
# change any encoding/bitrate; we just record the pick and expose it as our participant metadata so
# any client can read which camera is pinned. (The web app does the actual enlarging.)
pinned = {"camera": None}
@room.on("data_received")
def _on_session(packet: "rtc.DataPacket") -> None:
if (packet.topic or "") != "session":
return
try:
cam = json.loads(packet.data.decode()).get("primary_camera")
except Exception:
return
if cam == pinned["camera"]:
return
pinned["camera"] = cam
logger.info("primary camera pinned -> %r", cam)
try:
res = room.local_participant.set_metadata(json.dumps({"primary_camera": cam}))
if inspect.isawaitable(res):
asyncio.create_task(res)
except Exception as exc: # noqa: BLE001 metadata is best-effort
logger.debug("set_metadata failed: %s", exc)
await room.connect(args.url, token)
logger.info("connected to %s room=%r as %r", args.url, args.room, args.identity)
readers = [CameraReader(n, dev, args.width, args.height, args.fps) for n, dev in cameras.items()]
for r in readers:
r.start()
tasks = [
asyncio.create_task(
_publish_camera(room, r, args.width, args.height, args.fps, args.bitrate)
)
for r in readers
]
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
logger.info("streaming %d camera(s): %s — Ctrl-C to stop", len(readers), ", ".join(cameras))
await stop.wait()
logger.info("shutting down")
for t in tasks:
t.cancel()
for r in readers:
r.stop()
await room.disconnect()
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--url", default="ws://localhost:7880", help="LiveKit server ws URL")
p.add_argument("--api-key", default="devkey", help="LiveKit API key (dev mode: devkey)")
p.add_argument("--api-secret", default="secret", help="LiveKit API secret (dev mode: secret)")
p.add_argument("--room", default="tom-cams", help="Room name to publish into")
p.add_argument("--identity", default="pi-publisher", help="Participant identity")
p.add_argument("--fps", type=int, default=15, help="Publish + capture frame rate (reader throttles to this)")
p.add_argument("--width", type=int, default=1280)
p.add_argument("--height", type=int, default=720)
p.add_argument(
"--bitrate", type=int, default=2_000_000,
help="Max bitrate per stream in bits/s. Default 2 Mbps keeps 4 streams within the Pi's WiFi "
"uplink headroom (~8 Mbps total, to avoid the brcmfmac TX stall); raise on a wired/low-"
"contention link for crisper motion.",
)
p.add_argument(
"--cameras",
nargs="+",
choices=list(TOM_CAMERAS),
help="Subset of cameras to publish (default: all)",
)
return p.parse_args()
if __name__ == "__main__":
asyncio.run(main(parse_args()))
05241c15dThis file is pinned to the selected release. Download the original to open it in your design tool.