- 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
This commit is contained in:
1 parent
851c39d827
commit
52b42890d6
34 files changed
+2851
-364
No files matched your search
+241
-36
@@ -1,10 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host-side unit tests for chandra-camera frame/camera helpers (no hardware required)."""
|
||||
"""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:
|
||||
@@ -24,6 +29,65 @@ 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 = [
|
||||
@@ -41,12 +105,9 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_convert_abgr8888_with_stride_and_rotations(self):
|
||||
# 2x3 image with stride padding (row = 2*4 + 4 padding bytes = 12)
|
||||
h, w, stride = 3, 2, 12
|
||||
buf = bytearray(h * stride)
|
||||
# Pixel (x=0, y=0): ABGR8888 in LE memory is [R, G, B, A] = [10, 20, 200, 255] -> BGR [200, 20, 10]
|
||||
buf[0:4] = bytes([10, 20, 200, 255])
|
||||
# Pixel (x=1, y=0): R=40, G=50, B=60 -> BGR [60, 50, 40]
|
||||
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)
|
||||
@@ -56,24 +117,20 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
|
||||
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))
|
||||
# Libcamera Rotation=90 (CCW mounting) rotates CCW: (row=0, col=0) -> (row=w-1=1, col=0)
|
||||
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))
|
||||
# Libcamera Rotation=270 rotates CW: (row=0, col=0) -> (row=0, col=h-1=2)
|
||||
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):
|
||||
# ARGB8888 in LE memory is [B, G, R, A]
|
||||
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)
|
||||
# Inverted horizontally+vertically and channel-flipped -> [66, 55, 44] then [33, 22, 11]
|
||||
self.assertEqual(tuple(bgr2[0, 0]), (66, 55, 44))
|
||||
self.assertEqual(tuple(bgr2[0, 1]), (33, 22, 11))
|
||||
|
||||
@@ -89,41 +146,189 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_debayer_quad_csi2p(self):
|
||||
# Construct an 8x8 CSI-2 10-bit packed 4x4 Quad-Bayer SRGGB image:
|
||||
# Top half (rows 0..3): strong red (R=200, G=24, B=24)
|
||||
# Bottom half (rows 4..7): strong blue (R=24, G=24, B=200)
|
||||
w, h, stride = 8, 8, 10
|
||||
arr = np.zeros((h, stride), dtype=np.uint8)
|
||||
for y in range(h):
|
||||
top = y < 4
|
||||
for x_blk in range(2): # 4 pixels per block, 5 bytes per block
|
||||
# Row phase inside 4x4 Quad-Bayer: y%4 in {0,1} -> R,R,G,G; {2,3} -> G,G,B,B
|
||||
if (y % 4) < 2:
|
||||
c0 = 200 if top else 24 # R
|
||||
c1 = 24 # G
|
||||
else:
|
||||
c0 = 24 # G
|
||||
c1 = 24 if top else 200 # B
|
||||
base = x_blk * 5
|
||||
arr[y, base + 0] = c0
|
||||
arr[y, base + 1] = c0
|
||||
arr[y, base + 2] = c1
|
||||
arr[y, base + 3] = c1
|
||||
arr[y, base + 4] = 0
|
||||
raw = arr.tobytes()
|
||||
|
||||
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, w, h, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np
|
||||
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, w, h, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np
|
||||
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)) # 8x8 -> 4x4, rot=90 keeps 4x4
|
||||
self.assertEqual(out_hq.shape, (4, 6, 3)) # resized to WxH = 6x4
|
||||
# Top row in rot=0 should have R > B; bottom row should have B > R.
|
||||
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()
|
||||
Reference in new issue
Block a user