- Add compositor/shell/backlight.mbt for backlight control in the shell - Update wit/capabilities.wit and wit/host/plasmoids.wit, then regenerate the component and interface ffi.mbt bindings (mostly export reordering) - Add world/launcher-widget/README.md
This commit is contained in:
1 parent
2e00009c79
commit
74235cb0ca
84 files changed
+1525
-864
No files matched your search
+151
-9
@@ -439,10 +439,28 @@ def query_camera(path):
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def list_libcameras():
|
||||
"""[(libcamera:id, label, '')] for cameras exposed through libcamera."""
|
||||
try:
|
||||
import libcamera
|
||||
except ImportError:
|
||||
return []
|
||||
out = []
|
||||
cm = libcamera.CameraManager.singleton()
|
||||
loc_names = {0: "Front", 1: "Back", 2: "External"}
|
||||
for cam in cm.cameras:
|
||||
props = cam.properties
|
||||
loc = loc_names.get(props.get(libcamera.properties.Location), "")
|
||||
model = str(props.get(libcamera.properties.Model) or cam.id)
|
||||
label = "%s camera (%s)" % (loc, model) if loc else model
|
||||
out.append(("libcamera:" + cam.id, label, ""))
|
||||
return out
|
||||
|
||||
|
||||
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()
|
||||
"""[(path, name, why not or '')]: libcamera cameras, /dev/v4l/by-id links, then /dev/video*."""
|
||||
out = list_libcameras()
|
||||
seen = set()
|
||||
for p in sorted(glob.glob("/dev/v4l/by-id/*")):
|
||||
seen.add(os.path.realpath(p))
|
||||
out.append((p,) + query_camera(p))
|
||||
@@ -460,9 +478,19 @@ def cameras_text(cams):
|
||||
|
||||
|
||||
def camera_problem(device):
|
||||
"""Why the configured camera can't be used, or "" (only checks the node, not streaming)."""
|
||||
"""Why the configured camera can't be used, or '' (only checks the node, not streaming)."""
|
||||
if device.startswith("images:"):
|
||||
return ""
|
||||
if device.startswith("libcamera:"):
|
||||
cid = device[len("libcamera:"):]
|
||||
try:
|
||||
import libcamera
|
||||
except ImportError:
|
||||
return "python-libcamera is not installed (cannot open %s)" % device
|
||||
cm = libcamera.CameraManager.singleton()
|
||||
if cm.get(cid) is None:
|
||||
return "no libcamera camera %s; %s" % (cid, cameras_text(list_cameras()))
|
||||
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"
|
||||
@@ -475,6 +503,112 @@ def camera_problem(device):
|
||||
return ""
|
||||
|
||||
|
||||
class LibcameraCamera:
|
||||
"""Capture BGR frames via python-libcamera (MIPI/SoftISP phone cameras)."""
|
||||
|
||||
def __init__(self, device):
|
||||
problem = camera_problem(device)
|
||||
if problem:
|
||||
raise Fail(problem, 2)
|
||||
import cv2
|
||||
import libcamera
|
||||
import mmap
|
||||
import numpy as np
|
||||
|
||||
self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np
|
||||
cid = device[len("libcamera:"):]
|
||||
self.cm = libcamera.CameraManager.singleton()
|
||||
self.cam = self.cm.get(cid)
|
||||
if self.cam is None:
|
||||
raise Fail("camera %s disappeared" % device, 2)
|
||||
self.rot = int(self.cam.properties.get(libcamera.properties.Rotation) or 0)
|
||||
try:
|
||||
self.cam.acquire()
|
||||
except Exception as e:
|
||||
raise Fail("couldn't acquire camera %s: %s" % (device, e), 2)
|
||||
try:
|
||||
cfg = self.cam.generate_configuration([libcamera.StreamRole.Viewfinder])
|
||||
self.sc = cfg.at(0)
|
||||
self.sc.size = libcamera.Size(640, 480)
|
||||
cfg.validate()
|
||||
self.cam.configure(cfg)
|
||||
self.alloc = libcamera.FrameBufferAllocator(self.cam)
|
||||
if self.alloc.allocate(self.sc.stream) <= 0:
|
||||
raise Fail("couldn't allocate camera buffers for %s" % device, 2)
|
||||
self.requests = []
|
||||
for buf in self.alloc.buffers(self.sc.stream):
|
||||
r = self.cam.create_request()
|
||||
r.add_buffer(self.sc.stream, buf)
|
||||
self.requests.append(r)
|
||||
self.cam.start()
|
||||
for r in self.requests:
|
||||
self.cam.queue_request(r)
|
||||
except Exception as e:
|
||||
self.close()
|
||||
if isinstance(e, Fail):
|
||||
raise
|
||||
raise Fail("couldn't start libcamera %s: %s" % (device, e), 2)
|
||||
self._first = True
|
||||
|
||||
def _to_bgr(self, buf):
|
||||
p = buf.planes[0]
|
||||
w, h, stride = self.sc.size.width, self.sc.size.height, self.sc.stride
|
||||
fmt = str(self.sc.pixel_format)
|
||||
with self.mmap.mmap(p.fd, p.offset + p.length, self.mmap.MAP_SHARED, self.mmap.PROT_READ) as mm:
|
||||
raw = bytes(mm[p.offset:p.offset + p.length])
|
||||
arr = self.np.frombuffer(raw, dtype=self.np.uint8)
|
||||
if fmt in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"):
|
||||
img = arr[:h * stride].reshape((h, stride // 4, 4))[:, :w, :3]
|
||||
bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if "BGR" in fmt else self.np.ascontiguousarray(img)
|
||||
elif fmt in ("RGB888", "BGR888"):
|
||||
img = arr[:h * stride].reshape((h, stride // 3, 3))[:, :w, :]
|
||||
bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if fmt == "RGB888" else self.np.ascontiguousarray(img)
|
||||
else:
|
||||
raise Fail("unsupported libcamera pixel format %s" % fmt, 2)
|
||||
if self.rot == 90:
|
||||
return self.cv2.rotate(bgr, self.cv2.ROTATE_90_CLOCKWISE)
|
||||
if self.rot == 180:
|
||||
return self.cv2.rotate(bgr, self.cv2.ROTATE_180)
|
||||
if self.rot == 270:
|
||||
return self.cv2.rotate(bgr, self.cv2.ROTATE_90_COUNTERCLOCKWISE)
|
||||
return bgr
|
||||
|
||||
def read(self):
|
||||
timeout = 3.0 if self._first else 1.5
|
||||
self._first = False
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
ready = self.cm.get_ready_requests()
|
||||
if ready:
|
||||
for old in ready[:-1]:
|
||||
old.reuse(self.libcamera.Request.ReuseFlag.ReuseBuffers)
|
||||
self.cam.queue_request(old)
|
||||
req = ready[-1]
|
||||
frame = None
|
||||
try:
|
||||
if req.status == self.libcamera.Request.Status.Complete:
|
||||
frame = self._to_bgr(req.buffers[self.sc.stream])
|
||||
finally:
|
||||
req.reuse(self.libcamera.Request.ReuseFlag.ReuseBuffers)
|
||||
self.cam.queue_request(req)
|
||||
if frame is not None:
|
||||
return frame
|
||||
time.sleep(0.01)
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.cam.stop()
|
||||
except Exception:
|
||||
pass
|
||||
self.requests = []
|
||||
self.alloc = None
|
||||
try:
|
||||
self.cam.release()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class V4L2Camera:
|
||||
def __init__(self, device):
|
||||
problem = camera_problem(device)
|
||||
@@ -502,6 +636,8 @@ class V4L2Camera:
|
||||
def open_camera(cfg, loop=False):
|
||||
if cfg.device.startswith("images:"):
|
||||
return ImageCamera(cfg.device, cfg, loop)
|
||||
if cfg.device.startswith("libcamera:"):
|
||||
return LibcameraCamera(cfg.device)
|
||||
return V4L2Camera(cfg.device)
|
||||
|
||||
|
||||
@@ -1008,11 +1144,17 @@ def cmd_cameras(out):
|
||||
|
||||
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))
|
||||
if path.startswith("libcamera:"):
|
||||
why = camera_problem(path)
|
||||
if why:
|
||||
raise Fail(why)
|
||||
name = next((n for p, n, _ in list_libcameras() if p == path), path)
|
||||
else:
|
||||
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")
|
||||
|
||||
+15
-4
@@ -64,11 +64,22 @@ def find_pixi():
|
||||
|
||||
|
||||
def make_env():
|
||||
"""The root-owned pixi environment the helper and the PAM module run; its python3."""
|
||||
pixi = find_pixi()
|
||||
"""The Python environment the helper and PAM module run; its python3."""
|
||||
sys_py = shutil.which("python3") or "/usr/bin/python3"
|
||||
use_sys = "--system-python" in sys.argv
|
||||
pixi = None if use_sys else find_pixi()
|
||||
if not pixi:
|
||||
sys.exit("pixi not found: install it (https://pixi.sh) or pass --pixi PATH; "
|
||||
"`just install` passes the one on your PATH")
|
||||
if os.access(sys_py, os.X_OK) and subprocess.run(
|
||||
[sys_py, "-I", "-c", "import cv2, numpy"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
).returncode == 0:
|
||||
print("using system Python", sys_py, "(OpenCV, numpy)")
|
||||
return sys_py
|
||||
if use_sys:
|
||||
sys.exit("--system-python asked, but %s cannot import cv2, numpy" % sys_py)
|
||||
sys.exit("pixi not found: install it (https://pixi.sh) or pass --pixi PATH, "
|
||||
"or install system python-opencv + python-numpy and pass --system-python")
|
||||
os.makedirs(env_dir, 0o755, exist_ok=True)
|
||||
for f in ("pixi.toml", "pixi.lock"):
|
||||
shutil.copyfile(os.path.join(here, f), os.path.join(env_dir, f))
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# gives it a /dev with no cameras, so pam_chandra_face.so could never see one there.
|
||||
[Service]
|
||||
PrivateDevices=no
|
||||
# Of the real /dev, only the standard pseudo devices and cameras can be opened.
|
||||
# Of the real /dev, only the standard pseudo devices and cameras (V4L2, media, dma_heap) can be opened.
|
||||
DevicePolicy=closed
|
||||
DeviceAllow=char-video4linux rw
|
||||
DeviceAllow=char-media rw
|
||||
DeviceAllow=char-dma_heap rw
|
||||
# What PrivateDevices=yes also did, kept.
|
||||
CapabilityBoundingSet=~CAP_MKNOD CAP_SYS_RAWIO
|
||||
SystemCallFilter=~@raw-io
|
||||
Reference in new issue
Block a user