- 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:
1 parent
f5a252e063
commit
019c9ada6c
3 files changed
+136
-23
No files matched your search
+89
-23
@@ -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.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,6 +2010,12 @@ class CameraEngine:
|
||||
self._latest_bgr = frame
|
||||
self._latest_ts_ns = ts_ns or time.monotonic_ns()
|
||||
self._latest_seq += 1
|
||||
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()
|
||||
@@ -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()):
|
||||
|
||||
@@ -332,6 +332,52 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
self.assertAlmostEqual(pts_ms[4], 145.0, delta=5.0)
|
||||
|
||||
|
||||
class PreviewCostTests(unittest.TestCase):
|
||||
"""The viewfinder decodes small, paced frames; whoever asks gets full ones."""
|
||||
|
||||
def engine(self):
|
||||
eng = cam_mod.CameraEngine([])
|
||||
eng._frames_since_open = cam_mod.PREVIEW_SETTLE_FRAMES
|
||||
return eng
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "needs OpenCV")
|
||||
def test_half_frame_is_the_full_one_scaled(self):
|
||||
rng = np.random.default_rng(3)
|
||||
small = rng.integers(0, 256, (6, 8, 4), dtype=np.uint8)
|
||||
big = small.repeat(2, axis=0).repeat(2, axis=1)
|
||||
stride = 16 * 4 + 12
|
||||
rows = np.zeros((12, stride), np.uint8)
|
||||
rows[:, :64] = big.reshape(12, 64)
|
||||
for rot in (0, 90, 270):
|
||||
for fmt in ("ABGR8888", "ARGB8888"):
|
||||
kw = dict(rot=rot, cv2_mod=cv2, np_mod=np)
|
||||
full = cam_mod.convert_frame(rows.tobytes(), 16, 12, stride, fmt, **kw)
|
||||
half = cam_mod.convert_frame(rows.tobytes(), 16, 12, stride, fmt, half=True, **kw)
|
||||
self.assertTrue(np.array_equal(half, full[::2, ::2]))
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "needs OpenCV")
|
||||
def test_preview_is_paced(self):
|
||||
eng = self.engine()
|
||||
due = sum(eng._preview_frame_due(100.0 + i / 34.0) for i in range(34 * 4))
|
||||
self.assertTrue(92 <= due <= 98, due)
|
||||
eng._frames_since_open = 0
|
||||
self.assertTrue(eng._preview_frame_due(100.0) and eng._preview_frame_due(100.0))
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "needs OpenCV")
|
||||
def test_full_frames_are_for_whoever_asks(self):
|
||||
eng = self.engine()
|
||||
self.assertFalse(eng._needs_full_frame())
|
||||
self.assertIsNone(eng.grab_full_frame(timeout=0.01))
|
||||
self.assertTrue(eng._needs_full_frame())
|
||||
eng._full_wanted = False
|
||||
|
||||
class AF:
|
||||
state = "coarse"
|
||||
|
||||
eng._af = AF()
|
||||
self.assertTrue(eng._needs_full_frame())
|
||||
|
||||
|
||||
class QRTests(unittest.TestCase):
|
||||
def test_reporter_reports_once_until_out_of_view(self):
|
||||
r = cam_mod.QRReporter()
|
||||
|
||||
@@ -60,6 +60,7 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux
|
||||
## Camera App (`chandra-camera`)
|
||||
|
||||
- [`camera/chandra-camera`](../camera/chandra-camera), [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c), and [`camera/chandra-camera-isp.c`](../camera/chandra-camera-isp.c) provide a native GTK3/Cairo Wayland camera app with a C/OpenMP Quad-Bayer ISP library (`libchandra-camera-isp.so`) installed via [`session/install.py`](../session/install.py) with its desktop launcher and icon (`Camera`).
|
||||
- **Heat:** the viewfinder decodes half-size frames at 24 fps (15 on the raw front camera); photos, video, focusing and QR scans take full frames (`CameraEngine.grab_full_frame`).
|
||||
- **QR scanner:** in photo mode the camera reads QR codes with OpenCV's own detectors about twice a second (the **QR** pill turns it off). A card shows the text with **Open** (web links), **Join** (WPA and open `WIFI:` codes, through NetworkManager) and **Copy**; nothing is opened or joined before a tap.
|
||||
- Supports multi-sensor `libcamera` discovery and live switching (`Back · imx519`, `Front · imx371`, `Back 2 · imx376` on OnePlus 6T, with automatic V4L2 fallback on desktops), sensor orientation transform + front-camera mirror preview, `libcamera` SoftISP CCM tuning (`camera/ipa/simple/*.yaml`), VCM contrast autofocus with tap-to-focus (`lc898217xc`), Photo mode (`HD` instant / `Full` high-resolution `StillCapture` or 3-frame raw burst merge on Quad-Bayer, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording exact-PTS VFR H.264 MP4s (`MatroskaI420Muxer` + `ffmpeg`) to `~/Videos/Camera`, an in-app photo gallery viewer, rear flash/torch LED control (`/sys/class/leds/white:flash`) through `org.freedesktop.login1.Session.SetBrightness`, and hardware volume-button or `Space`/`Return` shutter control.
|
||||
|
||||
|
||||
Reference in new issue
Block a user