Camera: cut viewfinder CPU use
CI / test (push) Failing after 49s

- Decode half-size frames at 24 fps (15 on the raw front camera) for the viewfinder; full frames only for photos, video, focusing and QR scans
- Swap channels with OpenCV instead of numpy; 2 OpenCV threads for live frames; OpenMP threads sleep when idle

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Opus 5.5 committed 2026-11-29 01:14:29 -08:00
1 parent f5a252e063
commit 019c9ada6c
3 files changed
+138 -25

No files matched your search

+91 -25
View File
@@ -21,6 +21,8 @@ import time
import urllib.parse
os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR")
# libgomp's idle threads (the ISP library) sleep between frames instead of spinning.
os.environ.setdefault("OMP_WAIT_POLICY", "passive")
APP_ID = "chandra-camera"
APP_TITLE = "Camera"
@@ -35,6 +37,17 @@ QUAD_BAYER_MODELS = {"imx371"}
# Pause between QR scans: scanning runs as long as the photo viewfinder is open.
QR_SCAN_INTERVAL_S = 0.5
# The viewfinder is shown at 540 px, so frames nobody keeps are decoded small and no more often
# than this. Photos, videos, focusing and QR scans get full frames (`grab_full_frame`).
PREVIEW_INTERVAL_S = 1.0 / 24.0
# Raw Quad-Bayer cameras unpack a 16 MP frame on the CPU each time.
RAW_PREVIEW_INTERVAL_S = 1.0 / 15.0
RAW_PREVIEW_SIZE = (576, 432)
# Full-rate frames after opening a camera, while exposure and white balance settle.
PREVIEW_SETTLE_FRAMES = 20
# OpenCV threads for live frames: more only wake cores for a millisecond of work each.
LIVE_CV_THREADS = 2
# Default live viewfinder/video sizes: 1600x1200 selects full-FOV 2x2-binned 4:3 on IMX519.
PREFERRED_VIEWFINDER_SIZES = [
(1600, 1200),
@@ -325,8 +338,11 @@ def rotate_bgr(bgr, rot, cv2_mod):
return bgr
def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None):
"""Convert raw camera buffer bytes/memoryview into a contiguous upright uint8 BGR image."""
def convert_frame(raw, width, height, stride, fmt, rot=0, half=False, cv2_mod=None, np_mod=None):
"""Convert raw camera buffer bytes/memoryview into a contiguous upright uint8 BGR image.
`half` scales it down to half size first, for the viewfinder.
"""
if np_mod is None:
import numpy as np_mod
if cv2_mod is None:
@@ -335,22 +351,19 @@ def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=N
arr = np_mod.frombuffer(raw, dtype=np_mod.uint8)
fmt_u = str(fmt).upper()
if fmt_u in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"):
row_px = stride // 4
img = arr[:height * stride].reshape((height, row_px, 4))[:, :width, :3]
if "BGR" in fmt_u:
bgr = np_mod.ascontiguousarray(img[:, :, ::-1])
else:
bgr = np_mod.ascontiguousarray(img)
channels = 4
code = cv2_mod.COLOR_RGBA2BGR if "BGR" in fmt_u else cv2_mod.COLOR_BGRA2BGR
elif fmt_u in ("RGB888", "BGR888"):
row_px = stride // 3
img = arr[:height * stride].reshape((height, row_px, 3))[:, :width, :]
if fmt_u == "RGB888":
bgr = np_mod.ascontiguousarray(img[:, :, ::-1])
else:
bgr = np_mod.ascontiguousarray(img)
channels = 3
code = cv2_mod.COLOR_RGB2BGR if fmt_u == "RGB888" else None
else:
raise RuntimeError("unsupported pixel format %s" % fmt)
img = arr[:height * stride].reshape((height, stride // channels, channels))[:, :width]
if half and width >= 2 and height >= 2:
img = cv2_mod.resize(img, (width // 2, height // 2), interpolation=cv2_mod.INTER_AREA)
bgr = cv2_mod.cvtColor(img, code) if code is not None else np_mod.array(img)
return np_mod.ascontiguousarray(rotate_bgr(bgr, rot, cv2_mod))
@@ -1409,6 +1422,12 @@ class CameraEngine:
self._latest_bgr = None
self._latest_ts_ns = 0
self._latest_seq = 0
self._full_cond = threading.Condition()
self._full_wanted = False
self._full_frame = None
self._full_seq = 0
self._preview_due = 0.0
self._cv_threads = cv2.getNumThreads()
self._want_switch = None
self._want_focus = None
self._still_request = None # (dst_path, burst_count)
@@ -1440,6 +1459,33 @@ class CameraEngine:
with self._lock:
return self._latest_bgr, self._latest_seq
def grab_full_frame(self, timeout=2.0):
"""The next full-size live frame (the viewfinder's own are small), or None."""
with self._full_cond:
seq = self._full_seq
self._full_wanted = True
if not self._full_cond.wait_for(lambda: self._full_seq != seq, timeout):
return None
return self._full_frame
def _needs_full_frame(self):
with self._full_cond:
if self._full_wanted:
return True
# Focusing counts frames and compares fine detail: full rate, full size.
focusing = self._af is not None and self._af.state in ("coarse", "fine")
return focusing or self.is_recording()
def _preview_frame_due(self, now):
"""Whether the viewfinder wants a frame now (paced, unless the camera just opened)."""
if self._frames_since_open < PREVIEW_SETTLE_FRAMES:
return True
if now < self._preview_due:
return False
step = RAW_PREVIEW_INTERVAL_S if self._raw_sc is not None else PREVIEW_INTERVAL_S
self._preview_due = max(self._preview_due + step, now)
return True
def is_recording(self):
with self._rec_lock:
return self._rec_proc is not None
@@ -1749,10 +1795,16 @@ class CameraEngine:
pass
return time.monotonic_ns()
def _read_libcamera_frame(self, cam_info, high_quality=False, target_size=(1152, 864), unpack_only_bgr16=False):
def _read_libcamera_frame(self, cam_info, high_quality=False, target_size=(1152, 864), unpack_only_bgr16=False, preview=False):
ready = self.cm.get_ready_requests()
if not ready:
return None, None
if preview and not self._preview_frame_due(time.monotonic()):
for req in ready:
self._requeue(req)
return None, None
if preview:
target_size = RAW_PREVIEW_SIZE
# Requeue older queued requests immediately without wasting CPU debayering stale frames.
for stale in ready[:-1]:
self._requeue(stale)
@@ -1825,6 +1877,7 @@ class CameraEngine:
stride,
fmt,
rot=cam_info.rotation,
half=preview,
cv2_mod=self.cv2,
np_mod=self.np,
)
@@ -1864,6 +1917,7 @@ class CameraEngine:
time.sleep(0.008)
def _run_loop(self):
self.cv2.setNumThreads(LIVE_CV_THREADS)
try:
self._open_camera(self.active_camera)
if self.on_camera_changed:
@@ -1911,7 +1965,11 @@ class CameraEngine:
still_req = self._still_request
self._still_request = None
if still_req is not None:
self._perform_still_capture(*still_req)
self.cv2.setNumThreads(self._cv_threads)
try:
self._perform_still_capture(*still_req)
finally:
self.cv2.setNumThreads(LIVE_CV_THREADS)
info = self.active_camera
if info is None:
@@ -1921,6 +1979,7 @@ class CameraEngine:
# 4. Capture next live frame.
frame = None
ts_ns = None
full = True
if info.backend == "v4l2":
if self._v4l2 is not None:
ok, f = self._v4l2.read()
@@ -1930,7 +1989,8 @@ class CameraEngine:
else:
time.sleep(0.02)
else:
frame, ts_ns = self._read_libcamera_frame(info)
full = self._needs_full_frame()
frame, ts_ns = self._read_libcamera_frame(info, preview=not full)
if frame is None:
self._wait_for_libcamera_event(0.03)
@@ -1950,7 +2010,13 @@ class CameraEngine:
self._latest_bgr = frame
self._latest_ts_ns = ts_ns or time.monotonic_ns()
self._latest_seq += 1
self._push_video_frame(frame, ts_ns)
if full:
with self._full_cond:
self._full_frame = frame if self._full_wanted else None
self._full_wanted = False
self._full_seq += 1
self._full_cond.notify_all()
self._push_video_frame(frame, ts_ns)
if self.on_frame:
self.on_frame()
finally:
@@ -2081,7 +2147,7 @@ class CameraEngine:
return saved
if not high_res:
frame, _ = self.latest_frame()
frame = self.grab_full_frame()
if frame is None:
raise RuntimeError("camera is still warming up")
if frame.shape[0] >= 64 and frame.shape[1] >= 64:
@@ -2107,7 +2173,7 @@ class CameraEngine:
"""Start recording exact-PTS VFR H.264 MP4 via Matroska I420 pipe to ffmpeg."""
if shutil.which("ffmpeg") is None:
raise RuntimeError("ffmpeg is not installed")
frame, _ = self.latest_frame()
frame = self.grab_full_frame()
if frame is None:
raise RuntimeError("camera is still warming up")
even = ensure_even_frame(frame)
@@ -2383,7 +2449,9 @@ def run_worker(cameras, initial_index):
scale = 540.0 / float(max_dim)
pw = max(2, int(round(w * scale)))
ph = max(2, int(round(h * scale)))
preview = cv2.resize(frame, (pw, ph), interpolation=cv2.INTER_AREA)
# Area averaging only matters (and only then is it worth its cost) past 2:1.
interp = cv2.INTER_AREA if scale < 0.5 else cv2.INTER_LINEAR
preview = cv2.resize(frame, (pw, ph), interpolation=interp)
else:
pw, ph = w, h
preview = frame
@@ -2407,15 +2475,13 @@ def run_worker(cameras, initial_index):
def qr_loop():
scanner = QRScanner(cv2)
reporter = QRReporter()
last_seq = -1
while not stop_flag.wait(QR_SCAN_INTERVAL_S):
eng = engine_holder[0]
if eng is None or not qr_on.is_set() or eng.is_recording():
continue
frame, seq = eng.latest_frame()
if frame is None or seq == last_seq:
frame = eng.grab_full_frame(timeout=1.0)
if frame is None:
continue
last_seq = seq
text = scanner.scan(frame)
# Switched off while scanning: the result is no longer wanted.
if qr_on.is_set() and reporter.update(text, time.monotonic()):