Add chandra-remote: VNC and web control over Tailscale
CI / test (push) Failing after 50s

- remote/: shared-memory framebuffer mirror served as RFB 3.8 (VNC, port 5900) and an HTTP/WebSocket PWA (port 6080), bound to the Tailscale interface and loopback by default
- Compositor: remote pointer, button, scroll, modifier, key, key-tap, text and clipboard input, routed past OLED blanking
- chandra-ctl: add status, refresh and osk commands; add input-* and clipboard-set for remote control
- Camera: debayer 10-bit CSI-2 Quad-Bayer frames for imx371 and high-quality still capture
- Camera: rotate frames by the libcamera mounting angle (CCW for 90), fix the expected test values, and restyle the UI for a dark theme
This commit is contained in:
nandi committed 2026-11-28 17:57:55 -08:00
1 parent de39b74282
commit bfc60ee0e5
24 files changed
+5310 -79

No files matched your search

+162 -32
View File
@@ -24,6 +24,8 @@ FLASH_LED_PATH = "/sys/class/leds/white:flash/brightness"
IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp")
VIDEO_EXTS = (".mp4", ".mkv", ".webm")
QUAD_BAYER_MODELS = {"imx371"}
# Fallback resolutions when a camera reports no enumerated StillCapture sizes.
DEFAULT_VIEWFINDER_SIZE = (1280, 960)
PREFERRED_STILL_SIZES = [
@@ -212,6 +214,18 @@ def select_initial_camera(cameras, spec):
return 0
def rotate_bgr(bgr, rot, cv2_mod):
"""Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle)."""
rot_i = int(rot) % 360
if rot_i == 90:
return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE)
if rot_i == 180:
return cv2_mod.rotate(bgr, cv2_mod.ROTATE_180)
if rot_i == 270:
return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE)
return bgr
def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None):
"""Convert raw camera buffer bytes into a contiguous upright uint8 BGR image."""
if np_mod is None:
@@ -238,14 +252,64 @@ def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=N
else:
raise RuntimeError("unsupported pixel format %s" % fmt)
rot_i = int(rot) % 360
if rot_i == 90:
return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE))
if rot_i == 180:
return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_180))
if rot_i == 270:
return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE))
return bgr
return np_mod.ascontiguousarray(rotate_bgr(bgr, rot, cv2_mod))
def debayer_quad_csi2p(
raw_buf,
width,
height,
stride,
rot=0,
offset=0,
target_size=(960, 720),
high_quality=False,
gamma_lut=None,
cv2_mod=None,
np_mod=None,
):
"""Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into upright BGR uint8."""
if np_mod is None:
import numpy as np_mod
if cv2_mod is None:
import cv2 as cv2_mod
arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride))
row_bytes = (width // 4) * 5
even_h = (height // 2) * 2
even_w = (width // 4) * 4
if high_quality:
p8 = arr[:even_h, :row_bytes].reshape((even_h, even_w // 4, 5))[:, :, :4].reshape((even_h, even_w))
bayer = (
(
p8[0::2, 0::2].astype(np_mod.uint16)
+ p8[0::2, 1::2]
+ p8[1::2, 0::2]
+ p8[1::2, 1::2]
)
>> 2
).astype(np_mod.uint8)
else:
b5 = arr[:even_h:2, :row_bytes].reshape((even_h // 2, even_w // 4, 5))
bayer = np_mod.ascontiguousarray(b5[:, :, [0, 2]].reshape((even_h // 2, even_w // 2)))
bgr = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR)
if target_size is not None:
bgr = cv2_mod.resize(bgr, target_size, interpolation=cv2_mod.INTER_AREA)
f = np_mod.maximum(bgr.astype(np_mod.float32) - 16.0, 0.0)
means = f.mean(axis=(0, 1))
avg = float(means.mean())
if avg > 1.0:
gains = np_mod.clip(avg / np_mod.maximum(means, 1.0), 0.65, 2.2)
boost = float(np_mod.clip(75.0 / avg, 1.0, 3.8))
u8 = np_mod.clip(f * (gains * boost), 0, 255).astype(np_mod.uint8)
else:
u8 = np_mod.clip(f, 0, 255).astype(np_mod.uint8)
if gamma_lut is None:
gamma_lut = np_mod.clip((np_mod.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8)
out = cv2_mod.LUT(u8, gamma_lut)
return np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod))
def bgr_to_cairo_argb32(bgr, np_mod=None):
@@ -355,11 +419,13 @@ class CameraEngine:
self._cam = None
self._sc = None
self._raw_sc = None
self._alloc = None
self._requests = []
self._v4l2 = None
self._started = False
self._reuse_arg = None
self._gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np.uint8)
self._latest_bgr = None
self._latest_seq = 0
@@ -463,34 +529,61 @@ class CameraEngine:
cam.acquire()
self._cam = cam
try:
role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder
sizes = target_sizes or ([DEFAULT_VIEWFINDER_SIZE] if role_name == "viewfinder" else PREFERRED_STILL_SIZES)
chosen_exc = None
self._raw_sc = None
configured = False
for w, h in sizes:
if role_name == "viewfinder" and info.model.lower() in QUAD_BAYER_MODELS:
try:
cfg = cam.generate_configuration([role])
sc = cfg.at(0)
sc.size = libcamera.Size(w, h)
cfg.validate()
cam.configure(cfg)
self._sc = sc
configured = True
break
except Exception as exc:
chosen_exc = exc
cfg = cam.generate_configuration([
libcamera.StreamRole.Viewfinder,
libcamera.StreamRole.Raw,
])
if cfg is not None and len(cfg) >= 2:
cfg.at(0).size = libcamera.Size(640, 480)
cfg.validate()
cam.configure(cfg)
self._sc = cfg.at(0)
self._raw_sc = cfg.at(1)
configured = True
except Exception:
self._raw_sc = None
if not configured:
raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc))
role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder
sizes = target_sizes or ([DEFAULT_VIEWFINDER_SIZE] if role_name == "viewfinder" else PREFERRED_STILL_SIZES)
chosen_exc = None
for w, h in sizes:
try:
cfg = cam.generate_configuration([role])
sc = cfg.at(0)
sc.size = libcamera.Size(w, h)
cfg.validate()
cam.configure(cfg)
self._sc = sc
configured = True
break
except Exception as exc:
chosen_exc = exc
if not configured:
raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc))
alloc = libcamera.FrameBufferAllocator(cam)
if alloc.allocate(self._sc.stream) <= 0:
raise RuntimeError("failed to allocate camera buffers for %s" % info.label)
self._alloc = alloc
reqs = []
for buf in alloc.buffers(self._sc.stream):
r = cam.create_request()
r.add_buffer(self._sc.stream, buf)
reqs.append(r)
if self._raw_sc is not None:
if alloc.allocate(self._raw_sc.stream) <= 0:
raise RuntimeError("failed to allocate raw buffers for %s" % info.label)
for b0, b1 in zip(alloc.buffers(self._sc.stream), alloc.buffers(self._raw_sc.stream)):
r = cam.create_request()
r.add_buffer(self._sc.stream, b0)
r.add_buffer(self._raw_sc.stream, b1)
reqs.append(r)
else:
for buf in alloc.buffers(self._sc.stream):
r = cam.create_request()
r.add_buffer(self._sc.stream, buf)
reqs.append(r)
self._requests = reqs
# Drain any stale completed requests before starting the newly acquired sensor.
self.cm.get_ready_requests()
@@ -525,20 +618,43 @@ class CameraEngine:
self._requests = []
self._alloc = None
self._sc = None
self._raw_sc = None
try:
self._cam.release()
except Exception:
pass
self._cam = None
def _read_libcamera_frame(self, cam_info):
def _read_libcamera_frame(self, cam_info, high_quality=False, target_size=(960, 720)):
ready = self.cm.get_ready_requests()
if not ready:
return None
frame = None
for req in ready:
if self._sc is not None and self._sc.stream in req.buffers:
if req.status == self.libcamera.Request.Status.Complete:
if req.status == self.libcamera.Request.Status.Complete:
if self._raw_sc is not None and self._raw_sc.stream in req.buffers:
buf = req.buffers[self._raw_sc.stream]
plane = buf.planes[0]
w = self._raw_sc.size.width
h = self._raw_sc.size.height
stride = self._raw_sc.stride
fmt = str(self._raw_sc.pixel_format)
if "CSI2P" in fmt.upper():
with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm:
frame = debayer_quad_csi2p(
mm,
w,
h,
stride,
rot=cam_info.rotation,
offset=plane.offset,
target_size=target_size,
high_quality=high_quality,
gamma_lut=self._gamma_lut,
cv2_mod=self.cv2,
np_mod=self.np,
)
elif self._sc is not None and self._sc.stream in req.buffers:
buf = req.buffers[self._sc.stream]
plane = buf.planes[0]
w = self._sc.size.width
@@ -557,7 +673,7 @@ class CameraEngine:
cv2_mod=self.cv2,
np_mod=self.np,
)
self._requeue(req)
self._requeue(req)
return frame
def _run_loop(self):
@@ -630,7 +746,21 @@ class CameraEngine:
def _perform_still_capture(self, dst_path):
info = self.active_camera
try:
if info.backend == "libcamera":
if info.backend == "libcamera" and self._raw_sc is not None:
captured = None
deadline = time.monotonic() + 4.0
while time.monotonic() < deadline and not self._stop_event.is_set():
captured = self._read_libcamera_frame(info, high_quality=True, target_size=None)
if captured is not None:
break
time.sleep(0.01)
if captured is None:
raise RuntimeError("still capture timed out")
os.makedirs(os.path.dirname(dst_path), exist_ok=True)
if not self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95]):
raise RuntimeError("failed to write %s" % dst_path)
self._still_result = (dst_path, None)
elif info.backend == "libcamera":
self._close_camera()
self._open_camera(info, role_name="still", target_sizes=PREFERRED_STILL_SIZES)
captured = None