Face unlock: screen fill-light for low light; fix Quad-Bayer AE ramp
CI / test (push) Failing after 51s

- 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.
This commit is contained in:
nandi committed 2026-11-28 18:32:15 -08:00
1 parent c5b96e2c70
commit 40c5d6722c
8 files changed
+266 -12

No files matched your search

+4 -5
View File
@@ -437,12 +437,11 @@ class QuadSensorAE:
return False return False
if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0:
return False return False
ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5)))
if raw_p95 > 240.0: if raw_p95 > 240.0:
ratio = max(0.35, 200.0 / max(raw_p95, 1.0)) ratio = min(ratio, max(0.25, 200.0 / max(raw_p95, 1.0)))
else: elif raw_p95 > 120.0 and raw_p95 * ratio > 235.0:
ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) ratio = max(0.25, min(ratio, 235.0 / raw_p95))
if 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)) 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: if abs(new_ev - self.ev_total) <= self.ev_total * 0.05:
return False return False
+11 -1
View File
@@ -136,7 +136,17 @@ fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp]
let rad = self.theme.radius + 2 let rad = self.theme.radius + 2
let sw = self.output_w let sw = self.output_w
let sh = self.output_h 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 w = (sw - 32).min(460)
let pad = 24 let pad = 24
let inner = w - pad * 2 let inner = w - pad * 2
+7
View File
@@ -298,6 +298,7 @@ pub(all) struct ChandraCompositor {
/// it last drawn. /// it last drawn.
face_hits : Array[(@scene.Rect, FaceHit)] face_hits : Array[(@scene.Rect, FaceHit)]
mut face_rev : Int mut face_rev : Int
mut face_saved_brightness : Int
/// The keymap the dialog types through (parsed from the one clients get). /// The keymap the dialog types through (parsed from the one clients get).
mut keymap : (Bytes, @polkit.Keymap)? mut keymap : (Bytes, @polkit.Keymap)?
/// Another polkit agent was started (the Settings switch for Chandra's dialog is off). /// 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, auth_slow_said: false,
face_hits: [], face_hits: [],
face_rev: -1, face_rev: -1,
face_saved_brightness: -1,
keymap: None, keymap: None,
fallback_agent_started: false, fallback_agent_started: false,
mods_latched: 0U, mods_latched: 0U,
@@ -622,6 +624,11 @@ pub fn ChandraCompositor::resize(self : ChandraCompositor, w : Int, h : Int) ->
///| ///|
pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit { pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
self.stop_recording() 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 { for _, win in self.windows {
release_snapshot(win.surface) release_snapshot(win.surface)
} }
+36
View File
@@ -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("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) 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")
}
+48 -1
View File
@@ -17,14 +17,42 @@ pub(all) enum FaceHit {
DropSnap(Int) DropSnap(Int)
ToggleFace(String) ToggleFace(String)
UseCamera(String) UseCamera(String)
ToggleLight
Apply Apply
Cancel Cancel
} derive(Eq) } 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. ///| Follow the camera process and redraw when the window changed.
fn ChandraCompositor::face_window_tick(self : ChandraCompositor) -> Unit { fn ChandraCompositor::face_window_tick(self : ChandraCompositor) -> Unit {
let f = self.shell.face let f = self.shell.face
f.poll_window() f.poll_window()
self.sync_face_fill_light()
if f.window_rev != self.face_rev { if f.window_rev != self.face_rev {
self.face_rev = f.window_rev self.face_rev = f.window_rev
self.damage.mark_full() self.damage.mark_full()
@@ -52,6 +80,7 @@ fn ChandraCompositor::face_window_activate(self : ChandraCompositor, h : FaceHit
DropSnap(i) => f.drop_snap(i) DropSnap(i) => f.drop_snap(i)
ToggleFace(id) => f.toggle_remove(id) ToggleFace(id) => f.toggle_remove(id)
UseCamera(path) => f.use_camera(path) UseCamera(path) => f.use_camera(path)
ToggleLight => f.toggle_fill_light()
Apply => f.apply() Apply => f.apply()
Cancel => f.cancel_window() Cancel => f.cancel_window()
} }
@@ -79,6 +108,8 @@ fn ChandraCompositor::face_window_input(self : ChandraCompositor, ev : @nested.I
self.face_window_activate(Apply) self.face_window_activate(Apply)
} else if code == key_space { } else if code == key_space {
self.face_window_activate(Snap) self.face_window_activate(Snap)
} else if code == key_l {
self.face_window_activate(ToggleLight)
} }
} }
true true
@@ -106,8 +137,12 @@ fn ChandraCompositor::face_window_input(self : ChandraCompositor, ev : @nested.I
///| ///|
let key_space : UInt = 57 let key_space : UInt = 57
///|
let key_l : UInt = 38
///| The window, when it is open. ///| The window, when it is open.
fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] { fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
self.sync_face_fill_light()
let ops : Array[@scene.DrawOp] = [] let ops : Array[@scene.DrawOp] = []
let f = self.shell.face let f = self.shell.face
let win = match f.window { 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 rad = self.theme.radius + 2
let sw = self.output_w let sw = self.output_w
let sh = self.output_h 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 w = (sw - 32).min(560)
let pad = 24 let pad = 24
let inner = w - pad * 2 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 hits : Array[(@scene.Rect, FaceHit)] = []
let mut y = pad let mut y = pad
body.push(@scene.DrawOp::Text(pad, y + 7, "FACE UNLOCK", fs - 3, p.accent, @scene.TextAlign::Left, true)) 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 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)) 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 y = y + fs + 10
+14
View File
@@ -77,6 +77,8 @@ pub(all) struct FaceWindow {
mut applying : Bool mut applying : Bool
/// When the camera process ended without a picture: the window shows why. /// When the camera process ended without a picture: the window shows why.
mut ended : Bool 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 /// 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. /// not; empty when it takes pictures). The window offers the usable ones.
cameras : Array[(String, String, String)] cameras : Array[(String, String, String)]
@@ -375,6 +377,7 @@ pub fn FaceUnlock::open_window(self : FaceUnlock, mark : String?) -> Unit {
error: false, error: false,
applying: false, applying: false,
ended: fd < 0, ended: fd < 0,
fill_light: true,
cameras: [], cameras: [],
} }
if fd < 0 { 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`. ///| Forget snap `i`.
pub fn FaceUnlock::drop_snap(self : FaceUnlock, i : Int) -> Unit { pub fn FaceUnlock::drop_snap(self : FaceUnlock, i : Int) -> Unit {
match self.window { match self.window {
+4 -5
View File
@@ -711,12 +711,11 @@ class QuadSensorAE:
return False return False
if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0:
return False return False
ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5)))
if raw_p95 > 240.0: if raw_p95 > 240.0:
ratio = max(0.35, 200.0 / max(raw_p95, 1.0)) ratio = min(ratio, max(0.25, 200.0 / max(raw_p95, 1.0)))
else: elif raw_p95 > 120.0 and raw_p95 * ratio > 235.0:
ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) ratio = max(0.25, min(ratio, 235.0 / raw_p95))
if 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)) 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: if abs(new_ev - self.ev_total) <= self.ev_total * 0.05:
return False return False
+142
View File
@@ -398,6 +398,148 @@ class OpenCVTests(unittest.TestCase):
env.close() 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") @unittest.skipUnless("--pam" in sys.argv, "pass --pam to test the PAM module")
class PamTests(unittest.TestCase): class PamTests(unittest.TestCase):
"""pam_chandra_face.so through pamtester, with a throwaway service in /etc/pam.d.""" """pam_chandra_face.so through pamtester, with a throwaway service in /etc/pam.d."""