Files
chandra/camera/test_camera.py
T
nandi 52b42890d6
CI / test (push) Canceled after 0s
Camera: C ISP pipeline, contrast autofocus, and VFR video
- Add chandra-camera-isp.c (C/OpenMP) for Quad-Bayer unpack, CCM, and tone mapping, with a NumPy fallback when it is not built
- Add non-blocking contrast-detection VCM autofocus, with lens subdev discovery on the sensor's I2C bus
- Tune Quad-Bayer AE: a video-mode vblank cap, damped steps, and full analog gain before extending blanking
- Record variable-frame-rate video through a streaming Matroska muxer, and count dropped frames
- Ship libcamera IPA tuning files for imx376, imx519, and uncalibrated sensors
- Map camera buffers by fd and sync them with dma-buf ioctls
2026-11-28 19:25:43 -08:00

335 lines
14 KiB
Python

#!/usr/bin/env python3
"""Host-side unit tests for chandra-camera frame/camera/AE/AF/VFR-mux helpers (no hardware required)."""
import ctypes
import importlib.machinery
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
try:
import cv2
import numpy as np
HAS_CV2_NUMPY = True
except ImportError:
cv2 = None
np = None
HAS_CV2_NUMPY = False
CAM_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chandra-camera")
_loader = importlib.machinery.SourceFileLoader("chandra_camera_mod", CAM_PATH)
_spec = importlib.util.spec_from_loader("chandra_camera_mod", _loader)
cam_mod = importlib.util.module_from_spec(_spec)
sys.modules["chandra_camera_mod"] = cam_mod
_loader.exec_module(cam_mod)
class _FakeSubdevIO:
"""In-memory mock for _V4L2SubdevIO supporting query/get/set/close."""
def __init__(self, ctrls):
# ctrls: cid -> (mn, mx, step, df, val)
self.ctrls = {k: list(v) for k, v in ctrls.items()}
self.history = []
self.closed = False
def query(self, cid):
if cid not in self.ctrls:
raise OSError("unsupported ctrl 0x%x" % cid)
mn, mx, step, df, _ = self.ctrls[cid]
return mn, mx, step, df
def get(self, cid):
if cid not in self.ctrls:
raise OSError("unsupported ctrl 0x%x" % cid)
return self.ctrls[cid][4]
def set(self, cid, val):
if cid not in self.ctrls:
raise OSError("unsupported ctrl 0x%x" % cid)
mn, mx, _step, _df, _ = self.ctrls[cid]
v = max(mn, min(int(val), mx))
self.ctrls[cid][4] = v
self.history.append((cid, v))
return v
def close(self):
self.closed = True
def _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96):
"""Build a 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB frame preserving all 10 bits."""
stride = (w // 4) * 5
arr = np.zeros((h, stride), dtype=np.uint8)
def pack4(p0, p1, p2, p3):
b0 = (p0 >> 2) & 0xFF
b1 = (p1 >> 2) & 0xFF
b2 = (p2 >> 2) & 0xFF
b3 = (p3 >> 2) & 0xFF
b4 = (p0 & 3) | ((p1 & 3) << 2) | ((p2 & 3) << 4) | ((p3 & 3) << 6)
return b0, b1, b2, b3, b4
for y in range(h):
top = y < (h // 2)
for x_blk in range(w // 4):
if (y % 4) < 2:
c0 = top_val if top else bg_val # R
c1 = bg_val # Gr
else:
c0 = bg_val # Gb
c1 = bg_val if top else bot_val # B
arr[y, x_blk * 5:x_blk * 5 + 5] = pack4(c0, c0, c1, c1)
return arr.tobytes(), stride
class TestCameraHelpers(unittest.TestCase):
def test_sort_and_label_cameras(self):
raw = [
("/base/front", "libcamera", "imx371", 0, 90, 4656 * 3496),
("/base/back2", "libcamera", "imx376", 1, 270, 2592 * 1944),
("/base/back1", "libcamera", "imx519", 1, 270, 4656 * 3496),
]
cams = cam_mod.sort_and_label_cameras(raw)
self.assertEqual([c.model for c in cams], ["imx519", "imx371", "imx376"])
self.assertEqual([c.label for c in cams], ["Back · imx519", "Front · imx371", "Back 2 · imx376"])
self.assertEqual(cam_mod.select_initial_camera(cams, ""), 0)
self.assertEqual(cam_mod.select_initial_camera(cams, "front"), 1)
self.assertEqual(cam_mod.select_initial_camera(cams, "back"), 0)
self.assertEqual(cam_mod.select_initial_camera(cams, "imx376"), 2)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_convert_abgr8888_with_stride_and_rotations(self):
h, w, stride = 3, 2, 12
buf = bytearray(h * stride)
buf[0:4] = bytes([10, 20, 200, 255])
buf[4:8] = bytes([40, 50, 60, 255])
bgr0 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=0, cv2_mod=cv2, np_mod=np)
self.assertEqual(bgr0.shape, (3, 2, 3))
self.assertEqual(tuple(bgr0[0, 0]), (200, 20, 10))
self.assertEqual(tuple(bgr0[0, 1]), (60, 50, 40))
bgr90 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=90, cv2_mod=cv2, np_mod=np)
self.assertEqual(bgr90.shape, (2, 3, 3))
self.assertEqual(tuple(bgr90[1, 0]), (200, 20, 10))
bgr270 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=270, cv2_mod=cv2, np_mod=np)
self.assertEqual(bgr270.shape, (2, 3, 3))
self.assertEqual(tuple(bgr270[0, 2]), (200, 20, 10))
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_convert_argb_rgb_and_cairo_bgra(self):
buf = bytes([210, 110, 30, 255, 10, 20, 30, 255])
bgr = cam_mod.convert_frame(buf, 2, 1, 8, "ARGB8888", rot=0, cv2_mod=cv2, np_mod=np)
self.assertEqual(tuple(bgr[0, 0]), (210, 110, 30))
rgb_buf = bytes([11, 22, 33, 44, 55, 66])
bgr2 = cam_mod.convert_frame(rgb_buf, 2, 1, 6, "RGB888", rot=180, cv2_mod=cv2, np_mod=np)
self.assertEqual(tuple(bgr2[0, 0]), (66, 55, 44))
self.assertEqual(tuple(bgr2[0, 1]), (33, 22, 11))
argb32 = cam_mod.bgr_to_cairo_argb32(bgr, np_mod=np)
self.assertEqual(argb32.shape, (1, 2, 4))
self.assertEqual(tuple(argb32[0, 0]), (210, 110, 30, 255))
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_ensure_even_frame(self):
odd = np.zeros((101, 203, 3), dtype=np.uint8)
even = cam_mod.ensure_even_frame(odd)
self.assertEqual(even.shape, (100, 202, 3))
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_debayer_quad_csi2p(self):
raw, stride = _make_quad_csi2p_image(w=8, h=8, top_val=800, bot_val=800, bg_val=96)
out_live = cam_mod.debayer_quad_csi2p(
raw, 8, 8, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np
)
out_hq = cam_mod.debayer_quad_csi2p(
raw, 8, 8, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np
)
self.assertEqual(out_live.shape, (4, 4, 3))
self.assertEqual(out_hq.shape, (4, 6, 3))
self.assertGreater(float(out_hq[0, :, 2].mean()), float(out_hq[0, :, 0].mean()) + 30.0)
self.assertGreater(float(out_hq[3, :, 0].mean()), float(out_hq[3, :, 2].mean()) + 30.0)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_c_isp_vs_numpy_fallback_and_10bit_lsbs(self):
lib = cam_mod.load_isp_lib()
self.assertIsNotNone(lib, "expected compiled build/libchandra-camera-isp.so")
raw_a, stride = _make_quad_csi2p_image(w=16, h=16, top_val=803, bot_val=803, bg_val=99)
raw_b, _ = _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96)
# Verify 10-bit LSBs change raw_a vs raw_b in C 4x4 unpacking.
arr_a = np.frombuffer(raw_a, dtype=np.uint8).reshape((16, stride))
arr_b = np.frombuffer(raw_b, dtype=np.uint8).reshape((16, stride))
out_a = np.empty((4, 4, 3), dtype=np.uint16)
out_b = np.empty((4, 4, 3), dtype=np.uint16)
lib.quad_csi2p_to_bgr16_4x4(arr_a.ctypes.data, 16, 16, stride, out_a.ctypes.data)
lib.quad_csi2p_to_bgr16_4x4(arr_b.ctypes.data, 16, 16, stride, out_b.ctypes.data)
self.assertEqual(int(out_a[0, 0, 2]) - int(out_b[0, 0, 2]), 12) # 4 pixels * 3 LSB = 12
# Compare full C ISP vs NumPy fallback on both 4x4 live and 2x2 HQ paths.
c_live = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np
)
c_hq = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np
)
saved_lib, saved_tried = cam_mod._ISP_LIB, cam_mod._ISP_LIB_TRIED
try:
cam_mod._ISP_LIB = None
cam_mod._ISP_LIB_TRIED = True
np_live = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np
)
np_hq = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np
)
finally:
cam_mod._ISP_LIB = saved_lib
cam_mod._ISP_LIB_TRIED = saved_tried
self.assertEqual(c_live.shape, (4, 4, 3))
self.assertEqual(c_hq.shape, (8, 8, 3))
self.assertLessEqual(int(np.abs(c_live.astype(np.int32) - np_live.astype(np.int32)).max()), 1)
self.assertLessEqual(int(np.abs(c_hq.astype(np.int32) - np_hq.astype(np.int32)).max()), 1)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_burst_merge_bgr16(self):
lib = cam_mod.load_isp_lib()
self.assertIsNotNone(lib)
rng = np.random.default_rng(42)
h, w = 32, 32
base_clean = np.full((h, w, 3), 1000, dtype=np.int32)
frames = []
for _ in range(4):
noise = rng.normal(0.0, 25.0, size=(h, w, 3))
f = np.clip(base_clean + noise, 0, 4092).astype(np.uint16)
frames.append(np.ascontiguousarray(f))
# Inject strong motion artifact in frame 2 on top-left 8x8 block.
frames[2][:8, :8, :] = 3500
base = frames[0]
others = frames[1:]
ptrs = (ctypes.c_void_p * len(others))(*[x.ctypes.data for x in others])
out = np.empty_like(base)
lib.burst_merge_bgr16(base.ctypes.data, ptrs, len(others), out.ctypes.data, int(h * w), 120.0)
static_std_before = float(base[12:, 12:, :].std())
static_std_after = float(out[12:, 12:, :].std())
self.assertLess(static_std_after, static_std_before * 0.7)
# Moving patch from frame 2 must not ghost into merged static base.
self.assertLess(float(out[:8, :8, :].mean()), 1200.0)
def test_quad_sensor_ae_gain_priority_and_video_mode(self):
io = _FakeSubdevIO({
cam_mod.V4L2_CID_VBLANK: (56, 62029, 1, 56, 56),
cam_mod.V4L2_CID_EXPOSURE: (4, 3542, 1, 1000, 1000),
cam_mod.V4L2_CID_ANALOGUE_GAIN: (0, 480, 1, 0, 0),
cam_mod.V4L2_CID_DIGITAL_GAIN: (0, 4096, 1, 1024, 1024),
})
ae = cam_mod.QuadSensorAE("/dev/null", io=io)
# Mid-high EV (e.g. 10x base exposure): should stay at vb_min and raise analogue gain up to 16x first.
vb, exp, ag, dg = ae.plan(3542.0 * 10.0)
self.assertEqual(vb, 56)
self.assertEqual(exp, 3542)
self.assertGreater(ag, 400)
self.assertEqual(dg, 1024)
# Very low light: photo mode extends vblank up to vb_cap_photo, video mode tightens to vb_cap_video.
vb_photo, _, _, _ = ae.plan(ae.e_max)
self.assertEqual(vb_photo, ae.vb_cap_photo)
ae.cur_vblank = vb_photo
ae.ev_total = ae.e_max
ae.set_video_mode(True)
self.assertLessEqual(ae.cur_vblank, ae.vb_cap_video)
ae.close()
self.assertTrue(io.closed)
self.assertEqual(io.get(cam_mod.V4L2_CID_VBLANK), 56)
self.assertEqual(io.get(cam_mod.V4L2_CID_EXPOSURE), 1000)
self.assertEqual(io.get(cam_mod.V4L2_CID_ANALOGUE_GAIN), 0)
self.assertEqual(io.get(cam_mod.V4L2_CID_DIGITAL_GAIN), 1024)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_contrast_af_sweep_finds_sharp_peak(self):
io = _FakeSubdevIO({
cam_mod.V4L2_CID_FOCUS_ABSOLUTE: (0, 1023, 1, 0, 120),
})
af = cam_mod.ContrastAF("/dev/null", io=io)
# Build crisp high-contrast checkerboard target.
sharp_img = np.zeros((160, 160, 3), dtype=np.uint8)
for y in range(0, 160, 8):
for x in range(0, 160, 8):
if ((x // 8) + (y // 8)) % 2 == 0:
sharp_img[y:y + 8, x:x + 8] = 220
af.trigger(0.5, 0.5)
steps = 0
while af.state != "locked" and steps < 100:
dist = abs(af.cur_pos - 600)
sigma = 0.2 + dist / 90.0
if sigma > 0.6:
frame = cv2.GaussianBlur(sharp_img, (0, 0), sigma)
else:
frame = sharp_img.copy()
af.step(frame, cv2_mod=cv2, np_mod=np)
steps += 1
self.assertEqual(af.state, "locked")
self.assertLess(abs(af.best_pos - 600), 60)
af.close()
self.assertTrue(io.closed)
self.assertEqual(io.get(cam_mod.V4L2_CID_FOCUS_ABSOLUTE), 120)
@unittest.skipUnless(HAS_CV2_NUMPY and shutil.which("ffmpeg") and shutil.which("ffprobe"), "requires cv2, numpy, ffmpeg, ffprobe")
def test_matroska_i420_muxer_vfr_and_cluster_rollover(self):
w, h = 64, 48
muxer = cam_mod.MatroskaI420Muxer(w, h)
timestamps = [0, 33, 67, 100, 145, 200, 31000, 31040]
bgr = np.full((h, w, 3), 120, dtype=np.uint8)
i420 = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV_I420).tobytes()
with tempfile.TemporaryDirectory() as td:
out_mp4 = os.path.join(td, "vfr.mp4")
cmd = [
"ffmpeg", "-y", "-loglevel", "error",
"-f", "matroska", "-i", "-",
"-fps_mode", "passthrough",
"-video_track_timescale", "1000",
"-c:v", "libx264", "-preset", "superfast", "-crf", "22", "-bf", "0",
"-pix_fmt", "yuv420p",
"-movflags", "+faststart", out_mp4,
]
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
for ts in timestamps:
proc.stdin.write(muxer.encode_frame(i420, ts))
proc.stdin.close()
rc = proc.wait(timeout=15)
err = proc.stderr.read().decode("utf-8", "replace")
self.assertEqual(rc, 0, msg="ffmpeg failed: " + err)
info = json.loads(subprocess.check_output([
"ffprobe", "-v", "error", "-show_streams", "-show_frames", "-of", "json", out_mp4
], text=True))
stream = info["streams"][0]
frames = info["frames"]
self.assertEqual(stream["codec_name"], "h264")
self.assertEqual(stream["pix_fmt"], "yuv420p")
self.assertEqual(len(frames), len(timestamps))
pts_ms = [round(float(f["pts_time"]) * 1000.0) for f in frames]
self.assertAlmostEqual(pts_ms[-1], 31040.0, delta=5.0)
self.assertAlmostEqual(pts_ms[4], 145.0, delta=5.0)
if __name__ == "__main__":
unittest.main()