Face unlock: say why a camera can't be used, list the cameras, pick one
CI / test (push) Canceled after 21m7s

"no camera at PATH" now says why (not there or a broken link, permission
denied, not a V4L2 device, a metadata node rather than the picture node,
OpenCV couldn't start it or it gives no picture: another app using it) and
lists the cameras found (VIDIOC_QUERYCAP on /dev/v4l/by-id/* and /dev/video*).
New commands: `chandra-face cameras`, `chandra-face set-camera PATH` (root,
edits device in face.conf after checking it is a capture node). The Face
unlock window shows the cameras found with a Use button (one password), then
opens again. just install prints NOT READY with the reason when the
configured camera can't be used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
Claude committed 2026-11-26 04:47:06 +00:00
1 parent ff6f733810
commit 516180196f
7 files changed
+251 -9

No files matched your search

+36
View File
@@ -24,6 +24,12 @@ fn fake_face_tool(dir : String) -> String {
#| # The Face unlock window's camera: a grey 4x3 picture with a face box, a white 2x2
#| # thumbnail per snap, and an apply that changes the faces file.
#| pic() { printf 'frame 4 3 1 0 2 2 36\n'; head -c 36 /dev/zero | tr '\000' '\200'; }
#| if [ -e "$S/nocam" ]; then
#| echo "error no camera at /dev/v4l/by-id/usb-Old-video-index0 (not there: unplugged, or its name differs)"
#| printf 'camera /dev/v4l/by-id/usb-EMEET-video-index0\tEMEET SmartCam C960\t\n'
#| printf 'camera /dev/v4l/by-id/usb-EMEET-video-index1\tEMEET SmartCam C960\tnot a picture node\n'
#| exit 2
#| fi
#| echo "info Look at the camera and press Snap"; pic
#| n=0; kept=0
#| while read -r cmd arg; do
@@ -47,6 +53,8 @@ fn fake_face_tool(dir : String) -> String {
#| quit) exit 0 ;;
#| esac
#| done ;;
#|set-camera)
#| echo "$2" > "$S/camera"; rm -f "$S/nocam"; echo "done Camera: EMEET SmartCam C960" ;;
#|pam)
#| if [ "$2" = enable ]; then echo "polkit-1,sudo" > "$S/pam"; else : > "$S/pam"; fi
#| echo "done ok" ;;
@@ -174,6 +182,34 @@ test "the Face unlock window: live picture, snaps, a face marked for removal, on
comp.close()
}
///|
test "the Face unlock window: a missing camera says why and offers the cameras found" {
let dir = "/tmp/chandra-face-nocam-" + @sys.getpid().to_string()
let tool = fake_face_tool(dir)
ignore(@sys.write_file_bytes(dir + "/nocam", b""))
let comp = new_comp("facenocam")
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.ended).unwrap_or(false) }))
let w = comp.shell.face.window.unwrap()
assert_true(w.error)
assert_true(w.message.has_prefix("no camera at /dev/v4l/by-id/usb-Old-video-index0"))
assert_eq(w.cameras.length(), 2)
assert_eq(w.cameras[1].2, "not a picture node")
let shots = @sys.getenv("CHANDRA_AUTH_SHOTS")
if shots != "" {
ignore(@sys.write_file_bytes(shots + "/19-face-no-camera.png", @renderer.encode_png_compressed(comp.compose_frame())))
}
// "Use" saves it (as root) and opens the window again, now with a picture.
comp.shell.face.use_camera(w.cameras[0].0)
assert_true(face_settle(comp, fn() { comp.shell.face.window.map(w => w.picture != 0U).unwrap_or(false) }))
assert_eq(@sys.read_file_bytes(dir + "/camera") |> @utf8.decode_lossy, "/dev/v4l/by-id/usb-EMEET-video-index0\n")
comp.shell.face.cancel_window()
comp.close()
}
///|
test "face unlock status lines" {
let f = @shell.FaceUnlock::new()
+24
View File
@@ -16,6 +16,7 @@ pub(all) enum FaceHit {
Snap
DropSnap(Int)
ToggleFace(String)
UseCamera(String)
Apply
Cancel
} derive(Eq)
@@ -50,6 +51,7 @@ fn ChandraCompositor::face_window_activate(self : ChandraCompositor, h : FaceHit
Snap => f.snap()
DropSnap(i) => f.drop_snap(i)
ToggleFace(id) => f.toggle_remove(id)
UseCamera(path) => f.use_camera(path)
Apply => f.apply()
Cancel => f.cancel_window()
}
@@ -195,6 +197,28 @@ fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene.
my = my + fs + 3
}
y = y + bh.max(msg_lines.length() * (fs + 3)) + 14
// The configured camera can't be used: the ones that can, to pick from (saved as root).
if win.ended && win.cameras.length() > 0 {
body.push(@scene.DrawOp::Text(pad, y + 8, "Cameras here", fs - 2, p.foreground_muted, @scene.TextAlign::Left, true))
y = y + 20
let rh = 34
for c in win.cameras {
let (path, name, why) = c
let bw = @renderer.text_width("Use", fs - 1, false, false) + 32
let br = @scene.Rect::new(pad + inner - bw, y + 3, bw, rh - 6)
let title = if name != "" { name } else { path }
body.push(@scene.DrawOp::Text(pad, y + rh / 2 - 7, title, fs - 1, if why == "" { p.foreground } else { p.foreground_muted }, @scene.TextAlign::Left, why == ""))
let sub = if why == "" { path } else { path + ": " + why }
let sub_lines = wrap_text(sub, fs - 3, false, false, inner - bw - 12)
body.push(@scene.DrawOp::Text(pad, y + rh / 2 + 9, sub_lines[0], fs - 3, p.foreground_muted, @scene.TextAlign::Left, false))
if why == "" {
auth_button(br, "Use", false, false, hover == Some(UseCamera(path)), true, p, fs - 1, rad, body)
hits.push((br, UseCamera(path)))
}
y = y + rh + 4
}
y = y + 8
}
// The snaps: click one to drop it.
if win.snaps.length() > 0 {
body.push(@scene.DrawOp::Text(pad, y + 8, "New pictures (click one to drop it)", fs - 2, p.foreground_muted, @scene.TextAlign::Left, true))
+30
View File
@@ -39,6 +39,8 @@ pub(all) struct FaceUnlock {
mut loaded : Bool
mut dirty : Bool
/// The Face unlock window, while it is open, and a count of its changes (the host redraws).
/// `reopen`: open it again when the running change (set-camera) ends.
mut reopen : Bool
mut window : FaceWindow?
mut window_rev : Int
/// Image handles to reuse for the live picture (two, in turn, so a new picture is a changed
@@ -75,6 +77,9 @@ pub(all) struct FaceWindow {
mut applying : Bool
/// When the camera process ended without a picture: the window shows why.
mut ended : 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)]
}
///|
@@ -103,6 +108,7 @@ pub fn FaceUnlock::new() -> FaceUnlock {
queue: [],
loaded: false,
dirty: true,
reopen: false,
window: None,
window_rev: 0,
pics: [],
@@ -222,6 +228,10 @@ pub fn FaceUnlock::poll(self : FaceUnlock) -> Unit {
self.change = false
self.dirty = true
self.refresh()
if self.reopen {
self.reopen = false
self.open_window(None)
}
} else {
self.apply_status(self.lines)
}
@@ -365,6 +375,7 @@ pub fn FaceUnlock::open_window(self : FaceUnlock, mark : String?) -> Unit {
error: false,
applying: false,
ended: fd < 0,
cameras: [],
}
if fd < 0 {
w.message = "Couldn't run chandra-face"
@@ -425,6 +436,19 @@ pub fn FaceUnlock::toggle_remove(self : FaceUnlock, id : String) -> Unit {
}
}
///| Use the camera at `path` from now on (root: one password), then open the window again.
pub fn FaceUnlock::use_camera(self : FaceUnlock, path : String) -> Unit {
match self.window {
Some(w) if w.ended => {
self.close_window()
self.message = "Waiting for the password…"
self.reopen = true
self.run(["set-camera", path], true)
}
_ => ()
}
}
///| Whether Apply has anything to do.
pub fn FaceWindow::can_apply(self : FaceWindow) -> Bool {
!self.applying && self.fd >= 0 && (self.snaps.length() > 0 || self.remove.length() > 0)
@@ -573,6 +597,12 @@ fn FaceUnlock::window_line(self : FaceUnlock, w : FaceWindow, kind : String, tex
w.message = text
w.error = true
}
"camera" => {
let f = text.split("\t").map(s => s.to_string()).to_array()
if f.length() == 3 {
w.cameras.push((f[0], f[1], f[2]))
}
}
"applied" =>
if text != "0" {
// Refused or cancelled: the camera starts again, the snaps and marks are still there.
+8
View File
@@ -69,6 +69,8 @@ chandra-face clear # forget every face
chandra-face pam enable polkit-1 sudo
chandra-face pam disable # polkit-1 and sudo by default
chandra-face status # what is set up, what is missing
chandra-face cameras # the cameras here, and why one can't be used
sudo chandra-face set-camera /dev/v4l/by-id/usb-...-video-index0 # use that one
just uninstall [--purge] # takes it out of every PAM service first (--purge: faces too)
```
@@ -131,6 +133,12 @@ store = /var/lib/chandra-face
models = /usr/local/share/chandra/face
```
When the configured camera can't be used, every command and the Face unlock window say why
(not there, a broken link, permission denied, a metadata node rather than the picture node, busy
in another app) and list the cameras found; the window has a **Use** button for each one that
takes pictures (it saves `device` as root, so the password is asked, and opens again). A
by-id camera usually has two nodes: `-video-index0` is the picture, `-video-index1` metadata.
`chandra-face test` prints the score of each frame, which helps pick a threshold for your camera.
## How it works
+128 -8
View File
@@ -16,6 +16,8 @@
a small live picture with the face box, keeps snaps
(their embeddings) in memory, and on "apply" saves
the snaps and removals in one root step (one password)
chandra-face cameras the cameras here, and why one can't be used (anyone)
chandra-face set-camera PATH use the camera at PATH (root; edits face.conf)
chandra-face apply [--user U] add and remove faces in one go, from JSON on stdin:
{"add": [{"label", "vectors"}], "remove": [ids]} (root)
@@ -32,6 +34,9 @@ be fooled by a good photo, more easily with an RGB webcam than an IR camera; see
"""
import configparser
import fcntl
import glob
import struct
import hashlib
import json
import math
@@ -403,14 +408,88 @@ class ImageCamera:
pass
VIDIOC_QUERYCAP = 0x80685600
V4L2_CAP_VIDEO_CAPTURE = 0x1
V4L2_CAP_VIDEO_CAPTURE_MPLANE = 0x1000
V4L2_CAP_DEVICE_CAPS = 0x80000000
def query_camera(path):
"""(name, "") when `path` is a V4L2 node that captures pictures, else (name or "", why not)."""
try:
fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)
except OSError as e:
why = e.strerror or str(e)
if e.errno in (13, 1): # EACCES, EPERM
why += " (you need access to it: be logged in at this seat, or in the video group)"
return "", why
try:
buf = bytearray(104)
try:
fcntl.ioctl(fd, VIDIOC_QUERYCAP, buf)
except OSError as e:
return "", "not a V4L2 camera (%s)" % (e.strerror or e)
name = bytes(buf[16:48]).split(b"\0")[0].decode("utf-8", "replace")
caps, dev_caps = struct.unpack_from("<II", buf, 84)
c = dev_caps if caps & V4L2_CAP_DEVICE_CAPS else caps
if not c & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_CAPTURE_MPLANE):
return name, "not a picture node (metadata; its -video-index0 sibling is the camera)"
return name, ""
finally:
os.close(fd)
def list_cameras():
"""[(path, name, why not or "")]: the /dev/v4l/by-id links, then /dev/video* nodes no link
points at."""
out, seen = [], set()
for p in sorted(glob.glob("/dev/v4l/by-id/*")):
seen.add(os.path.realpath(p))
out.append((p,) + query_camera(p))
for p in sorted(glob.glob("/dev/video*"), key=lambda s: (len(s), s)):
if os.path.realpath(p) not in seen:
out.append((p,) + query_camera(p))
return out
def cameras_text(cams):
ok = ["%s (%s)" % (n or "camera", p) for p, n, why in cams if not why]
if not ok:
return "no camera that takes pictures is connected"
return "cameras here: " + "; ".join(ok)
def camera_problem(device):
"""Why the configured camera can't be used, or "" (only checks the node, not streaming)."""
if device.startswith("images:"):
return ""
path = "/dev/video" + device if device.isdigit() else device
if not os.path.exists(path):
why = "broken link" if os.path.islink(path) else "not there"
return ("no camera at %s (%s: unplugged, or its name differs); %s. Pick one in Settings > "
"Session > Add or remove faces, or run chandra-face set-camera PATH"
% (path, why, cameras_text(list_cameras())))
name, why = query_camera(path)
if why:
return "camera %s: %s; %s" % (path, why, cameras_text(list_cameras()))
return ""
class V4L2Camera:
def __init__(self, device):
problem = camera_problem(device)
if problem:
raise Fail(problem, 2)
import cv2
self.cv2 = cv2
dev = int(device) if device.isdigit() else device
self.cap = cv2.VideoCapture(dev, cv2.CAP_V4L2)
if not self.cap.isOpened():
raise Fail("camera %s not available" % device, 2)
raise Fail("OpenCV couldn't start camera %s (is another app using it?)" % device, 2)
ok, _ = self.cap.read()
if not ok:
self.cap.release()
raise Fail("camera %s gives no picture (is another app using it?)" % device, 2)
def read(self):
ok, frame = self.cap.read()
@@ -423,8 +502,6 @@ class V4L2Camera:
def open_camera(cfg, loop=False):
if cfg.device.startswith("images:"):
return ImageCamera(cfg.device, cfg, loop)
if not cfg.device.isdigit() and not os.path.exists(cfg.device):
raise Fail("no camera at %s" % cfg.device, 2)
return V4L2Camera(cfg.device)
@@ -674,7 +751,13 @@ def cmd_camera(cfg, user, label, out, cfg_path, no_elevate):
of the snaps kept go to the root `apply`, through a pipe."""
check_user(user)
rec = make_recognizer(cfg)
cam = open_camera(cfg, loop=True)
try:
cam = open_camera(cfg, loop=True)
except Fail as e:
# Say why, and which cameras there are: the window offers them.
out.error(str(e))
cmd_cameras(out)
return e.code
snaps = {} # id -> embedding
next_id = 1
last = None
@@ -901,9 +984,8 @@ def cmd_status(cfg, user, out):
if not os.path.exists(os.path.join(cfg.models, m)):
problem = "face models missing: run chandra-face fetch-models"
break
if not problem and not cfg.device.startswith("images:") and not cfg.device.isdigit() \
and not os.path.exists(cfg.device):
problem = "no camera at %s" % cfg.device
if not problem:
problem = camera_problem(cfg.device)
out.emit("backend", backend)
out.emit("device", cfg.device)
if problem:
@@ -917,6 +999,38 @@ def cmd_status(cfg, user, out):
return 0
def cmd_cameras(out):
"""Lines `camera PATH<TAB>NAME<TAB>WHY` (WHY empty: it takes pictures)."""
for p, n, why in list_cameras():
out.emit("camera", "%s\t%s\t%s" % (p, n, why))
return 0
def cmd_set_camera(cfg, path, out):
"""Point face.conf's `device` at `path` (root), after checking it is a camera."""
if not path.startswith("/dev/") or not os.path.exists(path):
raise Fail("no camera at %s" % path)
name, why = query_camera(path)
if why:
raise Fail("%s: %s" % (path, why))
conf = cfg.path
text = open(conf).read() if os.path.exists(conf) else "[face]\n"
lines = text.split("\n")
at = next((i for i, l in enumerate(lines) if re.match(r"^\s*device\s*=", l)), None)
if at is None:
sec = next((i for i, l in enumerate(lines) if l.strip() == "[face]"), None)
if sec is None:
lines += ["[face]"]
sec = len(lines) - 1
lines.insert(sec + 1, "device = " + path)
else:
lines[at] = "device = " + path
os.makedirs(os.path.dirname(conf) or ".", exist_ok=True)
write_atomic(conf, "\n".join(lines), 0o644)
out.emit("done", "Camera: %s" % (name or path))
return 0
def cmd_fetch_models(cfg, out):
import urllib.request
@@ -943,7 +1057,7 @@ def cmd_fetch_models(cfg, out):
# ---------------------------------------------------------------- main
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply")
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply", "set-camera")
def elevate(argv, user):
@@ -1016,6 +1130,12 @@ def main(argv):
return cmd_apply(cfg, user, out)
if cmd == "camera":
return cmd_camera(cfg, user, label, out, cfg_path, no_elevate)
if cmd == "cameras":
return cmd_cameras(out)
if cmd == "set-camera":
if not params:
raise Fail("set-camera PATH (see chandra-face cameras)")
return cmd_set_camera(cfg, params[0], out)
if cmd == "remove":
if not params:
raise Fail("remove ID")
+5
View File
@@ -167,5 +167,10 @@ if "--no-models" not in sys.argv:
subprocess.check_call([py, "-I", helper, "--no-elevate", "fetch-models"])
if "--pam" in sys.argv:
subprocess.check_call([py, "-I", helper, "--no-elevate", "pam", "enable"])
# Say now when it can't work yet (no camera at the configured path, say), and what is there.
st = subprocess.run([py, "-I", helper, "--no-elevate", "status", "--machine"], capture_output=True, text=True)
for line in st.stdout.splitlines():
if line.startswith("problem "):
print("face unlock: NOT READY: " + line[len("problem "):], file=sys.stderr)
print("face unlock: add a face in Settings > Session > Face unlock (after logging in to the new "
"session), or now with `chandra-face enroll`, then `chandra-face pam enable`")
+20 -1
View File
@@ -237,7 +237,8 @@ class FaceTests(unittest.TestCase):
self.assertEqual(rc, 0)
self.assertTrue(any(l.startswith("problem ") for l in out), out)
self.env.camera([], device="/dev/no-such-camera")
self.assertIn("problem no camera at /dev/no-such-camera", self.env.run("status")[1])
out = self.env.run("status")[1]
self.assertTrue(any(l.startswith("problem no camera at /dev/no-such-camera (not there") for l in out), out)
class Session:
@@ -354,6 +355,24 @@ class CameraWindowTests(unittest.TestCase):
self.assertEqual(s.finish(), 0)
self.assertEqual(len(self.vectors()[0]["vectors"]), 2)
def test_a_missing_camera_says_why_and_lists_the_cameras(self):
self.env.camera([], device="/dev/v4l/by-id/usb-No-Such-Camera-video-index0", backend="fake")
s = Session(self.env)
words, _ = s.next("error")
text = " ".join(words[1:])
self.assertTrue(text.startswith("no camera at /dev/v4l/by-id/usb-No-Such-Camera-video-index0 (not there"), text)
self.assertIn("chandra-face set-camera PATH", text)
self.assertEqual(s.finish(), 2)
rc, out = self.env.run("status")
self.assertTrue(any(l.startswith("problem no camera at /dev/v4l/by-id/usb-No-Such") for l in out), out)
def test_set_camera_refuses_what_is_not_a_camera(self):
for bad in ("/dev/null", "/dev/v4l/by-id/nothing", "/etc/passwd"):
rc, out = self.env.run("set-camera", bad)
self.assertNotEqual(rc, 0, bad)
self.assertTrue(out[-1].startswith("error"), out)
self.assertNotIn("/dev/null", slurp(self.env.conf))
def test_apply_refuses_bad_data(self):
for bad in (b"[]", b"{\"add\": [{\"vectors\": [[1, 2]]}]}",
b"{\"add\": [{\"vectors\": [[1e999, 0, 0, 0]]}]}", b"{\"remove\": [7]}", b"nonsense"):