From 40c5d6722cafa2d10e4fb9eb9dd40a1d672227a2 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sat, 28 Nov 2026 18:32:15 -0800 Subject: [PATCH] Face unlock: screen fill-light for low light; fix Quad-Bayer AE ramp - Boost the backlight to 90% while enrolling with the light on or while sign-in is scanning, then restore the previous level when that ends or the window closes. - Add a Light: On/Off toggle (L key) to the Face window; the backdrop turns soft white while the light is on. - Quad-Bayer AE: compute the low-light gain once and cap it by the highlight limit, so ramp-up and highlight back-off agree. - Tests: backlight round-trip through the Face window, Quad-Bayer debayer color/low-light/dark-frame cases, and the AE ramp, back-off and restore order. --- camera/chandra-camera | 9 +- compositor/host/auth_draw.mbt | 12 ++- compositor/host/compositor.mbt | 7 ++ compositor/host/face_test.mbt | 36 ++++++++ compositor/host/face_window.mbt | 49 ++++++++++- compositor/shell/face.mbt | 14 ++++ face/chandra-face | 9 +- face/test_face.py | 142 ++++++++++++++++++++++++++++++++ 8 files changed, 266 insertions(+), 12 deletions(-) diff --git a/camera/chandra-camera b/camera/chandra-camera index 7cad54d..beb5357 100755 --- a/camera/chandra-camera +++ b/camera/chandra-camera @@ -437,12 +437,11 @@ class QuadSensorAE: return False if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: return False + ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) if raw_p95 > 240.0: - ratio = max(0.35, 200.0 / max(raw_p95, 1.0)) - else: - ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) - if raw_p95 > 120.0 and raw_p95 * ratio > 235.0: - ratio = max(0.25, min(ratio, 235.0 / raw_p95)) + ratio = min(ratio, max(0.25, 200.0 / max(raw_p95, 1.0))) + elif raw_p95 > 120.0 and raw_p95 * ratio > 235.0: + ratio = max(0.25, min(ratio, 235.0 / raw_p95)) new_ev = max(self.e_min, min(self.ev_total * (ratio ** 0.75), self.e_max)) if abs(new_ev - self.ev_total) <= self.ev_total * 0.05: return False diff --git a/compositor/host/auth_draw.mbt b/compositor/host/auth_draw.mbt index f8deb14..c9a80f8 100644 --- a/compositor/host/auth_draw.mbt +++ b/compositor/host/auth_draw.mbt @@ -136,7 +136,17 @@ fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] let rad = self.theme.radius + 2 let sw = self.output_w let sh = self.output_h - ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), @scene.Rgba::new(0, 0, 0, 150), 0)) + ops.push( + @scene.DrawOp::FillRect( + @scene.Rect::new(0, 0, sw, sh), + if d.face == Scanning { + @scene.Rgba::new(255, 250, 242, 235) + } else { + @scene.Rgba::new(0, 0, 0, 150) + }, + 0, + ), + ) let w = (sw - 32).min(460) let pad = 24 let inner = w - pad * 2 diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 09259f7..dbaa8ec 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -298,6 +298,7 @@ pub(all) struct ChandraCompositor { /// it last drawn. face_hits : Array[(@scene.Rect, FaceHit)] mut face_rev : Int + mut face_saved_brightness : Int /// The keymap the dialog types through (parsed from the one clients get). mut keymap : (Bytes, @polkit.Keymap)? /// Another polkit agent was started (the Settings switch for Chandra's dialog is off). @@ -373,6 +374,7 @@ pub fn ChandraCompositor::new( auth_slow_said: false, face_hits: [], face_rev: -1, + face_saved_brightness: -1, keymap: None, fallback_agent_started: false, mods_latched: 0U, @@ -622,6 +624,11 @@ pub fn ChandraCompositor::resize(self : ChandraCompositor, w : Int, h : Int) -> ///| pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit { self.stop_recording() + if self.face_saved_brightness >= 0 { + let prev = self.face_saved_brightness + self.face_saved_brightness = -1 + ignore(self.shell.set_brightness(prev)) + } for _, win in self.windows { release_snapshot(win.surface) } diff --git a/compositor/host/face_test.mbt b/compositor/host/face_test.mbt index 8e55929..0e70e99 100644 --- a/compositor/host/face_test.mbt +++ b/compositor/host/face_test.mbt @@ -230,3 +230,39 @@ test "face unlock status lines" { assert_eq(@shell.face_progress("error couldn't see a face clearly"), Some("Couldn't see a face clearly")) assert_eq(@shell.face_progress("face 1\tDesk\t2026-11-20"), None) } + +///| +test "the Face unlock window: screen fill-light boosts backlight and restores on close" { + let root = "/tmp/chandra-test-face-backlight-" + @sys.getpid().to_string() + let dev = root + "/ae94000.dsi.0" + ignore(@sys.mkdir_p(dev)) + assert_eq(@sys.write_file_bytes(dev + "/max_brightness", @utf8.encode("1000\n")), 0) + assert_eq(@sys.write_file_bytes(dev + "/brightness", @utf8.encode("500\n")), 0) + @shell.set_backlight_root(root) + let dir = "/tmp/chandra-face-light-" + @sys.getpid().to_string() + let tool = fake_face_tool(dir) + let comp = new_comp("facelight") + comp.shell.set_face_tool(["/bin/sh", tool]) + assert_true(comp.shell.open_settings(Session)) + assert_true(face_settle(comp, fn() { face_texts(comp).contains("Desk") })) + face_click(comp, "Add or remove faces…", 10U) + assert_true(face_settle(comp, fn() { comp.shell.face.window.map(w => w.picture != 0U).unwrap_or(false) })) + let w = comp.shell.face.window.unwrap() + assert_true(w.fill_light) + assert_eq(@shell.read_backlight_percent(), 90) + // Pressing L toggles fill-light off and restores previous backlight immediately. + face_key(comp, 38U, 20U) + assert_false(w.fill_light) + assert_eq(@shell.read_backlight_percent(), 50) + // Pressing L again boosts back to 90. + face_key(comp, 38U, 30U) + assert_true(w.fill_light) + assert_eq(@shell.read_backlight_percent(), 90) + // Esc closes window and restores backlight cleanly. + face_key(comp, 1U, 40U) + ignore(comp.compose_frame()) + assert_true(comp.shell.face.window is None) + assert_eq(@shell.read_backlight_percent(), 50) + comp.close() + @shell.set_backlight_root("/sys/class/backlight") +} diff --git a/compositor/host/face_window.mbt b/compositor/host/face_window.mbt index 91555c5..d7b9408 100644 --- a/compositor/host/face_window.mbt +++ b/compositor/host/face_window.mbt @@ -17,14 +17,42 @@ pub(all) enum FaceHit { DropSnap(Int) ToggleFace(String) UseCamera(String) + ToggleLight Apply Cancel } derive(Eq) +///| Boost display backlight while the screen acts as a face fill-light, and restore it when done. +fn ChandraCompositor::sync_face_fill_light(self : ChandraCompositor) -> Unit { + let enroll_light = match self.shell.face.window { + Some(w) => !w.applying && !w.ended && w.fill_light + None => false + } + let auth_light = match self.auth { + Some(u) => u.view.face == Scanning + None => false + } + let want_boost = enroll_light || auth_light + if want_boost { + if self.face_saved_brightness < 0 { + let cur = @shell.read_backlight_percent() + if cur >= 0 && cur < 90 { + self.face_saved_brightness = cur + ignore(self.shell.set_brightness(90)) + } + } + } else if self.face_saved_brightness >= 0 { + let prev = self.face_saved_brightness + self.face_saved_brightness = -1 + ignore(self.shell.set_brightness(prev)) + } +} + ///| Follow the camera process and redraw when the window changed. fn ChandraCompositor::face_window_tick(self : ChandraCompositor) -> Unit { let f = self.shell.face f.poll_window() + self.sync_face_fill_light() if f.window_rev != self.face_rev { self.face_rev = f.window_rev self.damage.mark_full() @@ -52,6 +80,7 @@ fn ChandraCompositor::face_window_activate(self : ChandraCompositor, h : FaceHit DropSnap(i) => f.drop_snap(i) ToggleFace(id) => f.toggle_remove(id) UseCamera(path) => f.use_camera(path) + ToggleLight => f.toggle_fill_light() Apply => f.apply() Cancel => f.cancel_window() } @@ -79,6 +108,8 @@ fn ChandraCompositor::face_window_input(self : ChandraCompositor, ev : @nested.I self.face_window_activate(Apply) } else if code == key_space { self.face_window_activate(Snap) + } else if code == key_l { + self.face_window_activate(ToggleLight) } } true @@ -106,8 +137,12 @@ fn ChandraCompositor::face_window_input(self : ChandraCompositor, ev : @nested.I ///| let key_space : UInt = 57 +///| +let key_l : UInt = 38 + ///| The window, when it is open. fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] { + self.sync_face_fill_light() let ops : Array[@scene.DrawOp] = [] let f = self.shell.face let win = match f.window { @@ -136,7 +171,12 @@ fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene. let rad = self.theme.radius + 2 let sw = self.output_w let sh = self.output_h - ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), @scene.Rgba::new(0, 0, 0, 150), 0)) + let backdrop = if win.fill_light && !win.ended { + @scene.Rgba::new(255, 250, 242, 245) + } else { + @scene.Rgba::new(0, 0, 0, 150) + } + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), backdrop, 0)) let w = (sw - 32).min(560) let pad = 24 let inner = w - pad * 2 @@ -145,6 +185,13 @@ fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene. let hits : Array[(@scene.Rect, FaceHit)] = [] let mut y = pad body.push(@scene.DrawOp::Text(pad, y + 7, "FACE UNLOCK", fs - 3, p.accent, @scene.TextAlign::Left, true)) + if !win.ended { + let light_label = if win.fill_light { "Light: On" } else { "Light: Off" } + let light_w = @renderer.text_width("Light: Off", fs - 2, false, false) + 22 + let lr = @scene.Rect::new(pad + inner - light_w, pad, light_w, 28) + auth_button(lr, light_label, false, false, hover == Some(ToggleLight), true, p, fs - 2, rad, body) + hits.push((lr, ToggleLight)) + } y = y + 18 body.push(@scene.DrawOp::Text(pad, y + (fs + 8) / 2, "Add or remove faces", fs + 3, p.foreground, @scene.TextAlign::Left, true)) y = y + fs + 10 diff --git a/compositor/shell/face.mbt b/compositor/shell/face.mbt index da5d18a..18b180d 100644 --- a/compositor/shell/face.mbt +++ b/compositor/shell/face.mbt @@ -77,6 +77,8 @@ pub(all) struct FaceWindow { mut applying : Bool /// When the camera process ended without a picture: the window shows why. mut ended : Bool + /// Soft white surround fill-light for low-light enrollment. + mut fill_light : Bool /// The cameras chandra-face found when the configured one can't be used: (path, name, why /// not; empty when it takes pictures). The window offers the usable ones. cameras : Array[(String, String, String)] @@ -375,6 +377,7 @@ pub fn FaceUnlock::open_window(self : FaceUnlock, mark : String?) -> Unit { error: false, applying: false, ended: fd < 0, + fill_light: true, cameras: [], } if fd < 0 { @@ -406,6 +409,17 @@ pub fn FaceUnlock::snap(self : FaceUnlock) -> Unit { } } +///| Toggle the soft screen fill-light while taking enrollment pictures. +pub fn FaceUnlock::toggle_fill_light(self : FaceUnlock) -> Unit { + match self.window { + Some(w) if !w.applying && !w.ended => { + w.fill_light = !w.fill_light + self.touch() + } + _ => () + } +} + ///| Forget snap `i`. pub fn FaceUnlock::drop_snap(self : FaceUnlock, i : Int) -> Unit { match self.window { diff --git a/face/chandra-face b/face/chandra-face index 7ec355a..7f4d77f 100755 --- a/face/chandra-face +++ b/face/chandra-face @@ -711,12 +711,11 @@ class QuadSensorAE: return False if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: return False + ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) if raw_p95 > 240.0: - ratio = max(0.35, 200.0 / max(raw_p95, 1.0)) - else: - ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) - if raw_p95 > 120.0 and raw_p95 * ratio > 235.0: - ratio = max(0.25, min(ratio, 235.0 / raw_p95)) + ratio = min(ratio, max(0.25, 200.0 / max(raw_p95, 1.0))) + elif raw_p95 > 120.0 and raw_p95 * ratio > 235.0: + ratio = max(0.25, min(ratio, 235.0 / raw_p95)) new_ev = max(self.e_min, min(self.ev_total * (ratio ** 0.75), self.e_max)) if abs(new_ev - self.ev_total) <= self.ev_total * 0.05: return False diff --git a/face/test_face.py b/face/test_face.py index 177e275..9c99f78 100644 --- a/face/test_face.py +++ b/face/test_face.py @@ -398,6 +398,148 @@ class OpenCVTests(unittest.TestCase): env.close() +try: + import cv2 as _cv2 # noqa + import numpy as _np # noqa + HAS_CV2_NUMPY = True +except ImportError: + HAS_CV2_NUMPY = False + + +def _make_quad_raw(w, h, p8_func): + """Build an unpacked->CSI2P Quad-Bayer raw buffer from per-block pixel helper `p8_func(x, y, phase)`.""" + stride = (w // 4) * 5 + arr = _np.zeros((h, stride), dtype=_np.uint8) + for y in range(h): + for xb in range(w // 4): + c0, c1 = p8_func(xb, y) + base = xb * 5 + arr[y, base + 0] = c0 + arr[y, base + 1] = c0 + arr[y, base + 2] = c1 + arr[y, base + 3] = c1 + return arr.tobytes(), stride + + +@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") +class QuadDebayerTests(unittest.TestCase): + def test_quad_debayer_color_lowlight_and_covered_dark(self): + # 1. Normal color response: red top half, blue bottom half + def rb(xb, y): + if (y % 4) < 2: + return (200, 24) if y < 4 else (24, 24) + return (24, 24) if y < 4 else (24, 200) + + raw, stride = _make_quad_raw(8, 8, rb) + out = cf.debayer_quad_csi2p(raw, 8, 8, stride, rot=0, target_size=None, cv2_mod=_cv2, np_mod=_np) + self.assertEqual(out.shape, (4, 4, 3)) + self.assertGreater(float(out[0, :, 2].mean()), float(out[0, :, 0].mean()) + 30.0) + self.assertGreater(float(out[3, :, 0].mean()), float(out[3, :, 2].mean()) + 30.0) + + # 2. Low-light scene: optical black=15 (sum=60), signal +2..+3 per p8 (8..12 above black in 2x2 sum) + w, h = 80, 80 + raw_dim, stride_dim = _make_quad_raw(w, h, lambda xb, y: (17 if xb < w // 8 else 18, 17 if y < h // 2 else 18)) + out_dim, stats_dim = cf.debayer_quad_csi2p( + raw_dim, w, h, stride_dim, rot=0, target_size=(80, 80), return_stats=True, cv2_mod=_cv2, np_mod=_np + ) + self.assertEqual(len(stats_dim), 2) + self.assertGreater(float(out_dim.mean()), 65.0) + + # 3. Covered lens dark frame: constant black=15 (zero signal above black 60) -> must stay dark + raw_dark, stride_dark = _make_quad_raw(w, h, lambda xb, y: (15, 15)) + out_dark, stats_dark = cf.debayer_quad_csi2p( + raw_dark, w, h, stride_dark, rot=0, target_size=(80, 80), return_stats=True, cv2_mod=_cv2, np_mod=_np + ) + self.assertLess(float(out_dark.mean()), 12.0) + self.assertLess(stats_dark[1], 0.8) + + +class _MockSubdevIO: + def __init__(self): + self.meta = { + cf.V4L2_CID_VBLANK: (56, 62029, 1, 56), + cf.V4L2_CID_EXPOSURE: (4, 3542, 1, 1000), + cf.V4L2_CID_ANALOGUE_GAIN: (0, 480, 1, 0), + cf.V4L2_CID_DIGITAL_GAIN: (0, 4096, 1, 1024), + } + self.vals = { + cf.V4L2_CID_VBLANK: 56, + cf.V4L2_CID_EXPOSURE: 1000, + cf.V4L2_CID_ANALOGUE_GAIN: 0, + cf.V4L2_CID_DIGITAL_GAIN: 1024, + } + self.log = [] + self.closed = False + + def query(self, cid): + if cid == cf.V4L2_CID_EXPOSURE: + extra = max(0, self.vals[cf.V4L2_CID_VBLANK] - 56) + return (4, 3542 + extra, 1, 1000) + return self.meta[cid] + + def get(self, cid): + return self.vals[cid] + + def set(self, cid, val): + if cid == cf.V4L2_CID_EXPOSURE: + max_exp = 3542 + max(0, self.vals[cf.V4L2_CID_VBLANK] - 56) + if val > max_exp: + raise AssertionError("EXPOSURE %d set before VBLANK raised (max %d)" % (val, max_exp)) + elif cid == cf.V4L2_CID_VBLANK: + max_exp_after = 3542 + max(0, val - 56) + if self.vals[cf.V4L2_CID_EXPOSURE] > max_exp_after: + raise AssertionError("VBLANK %d lowered while EXPOSURE still %d" % (val, self.vals[cf.V4L2_CID_EXPOSURE])) + self.vals[cid] = val + self.log.append((cid, val)) + return val + + def close(self): + self.closed = True + + +class QuadSensorAETests(unittest.TestCase): + def test_lowlight_ramp_cooldown_and_restore(self): + io = _MockSubdevIO() + ae = cf.QuadSensorAE("/dev/null", io=io) + ae.apply_initial() + self.assertEqual(ae.cooldown, 2) + # Cooldown skips 2 frames + self.assertFalse(ae.update(4.0, 8.0)) + self.assertEqual(ae.cooldown, 1) + self.assertFalse(ae.update(4.0, 8.0)) + self.assertEqual(ae.cooldown, 0) + + # Ramp in pitch dimness through vblank/exposure, analogue gain, then digital gain + for _ in range(10): + ae.cooldown = 0 + ae.update(3.0, 6.0) + self.assertGreater(io.vals[cf.V4L2_CID_VBLANK], 56) + self.assertGreater(io.vals[cf.V4L2_CID_EXPOSURE], 3542) + self.assertEqual(io.vals[cf.V4L2_CID_ANALOGUE_GAIN], 480) + self.assertGreater(io.vals[cf.V4L2_CID_DIGITAL_GAIN], 1024) + + # Bright highlight overload backs off exposure safely before reducing vblank + io.log.clear() + for _ in range(12): + ae.cooldown = 0 + ae.update(210.0, 250.0) + self.assertEqual(io.vals[cf.V4L2_CID_VBLANK], 56) + self.assertLess(io.vals[cf.V4L2_CID_EXPOSURE], 3542) + self.assertEqual(io.vals[cf.V4L2_CID_DIGITAL_GAIN], 1024) + + # Raise again then close() to test clean restore order + ae.cooldown = 0 + for _ in range(8): + ae.cooldown = 0 + ae.update(3.0, 6.0) + ae.close() + self.assertTrue(io.closed) + self.assertEqual(io.vals[cf.V4L2_CID_VBLANK], 56) + self.assertEqual(io.vals[cf.V4L2_CID_EXPOSURE], 1000) + self.assertEqual(io.vals[cf.V4L2_CID_ANALOGUE_GAIN], 0) + self.assertEqual(io.vals[cf.V4L2_CID_DIGITAL_GAIN], 1024) + + @unittest.skipUnless("--pam" in sys.argv, "pass --pam to test the PAM module") class PamTests(unittest.TestCase): """pam_chandra_face.so through pamtester, with a throwaway service in /etc/pam.d."""