Add a camera app: photo and video on libcamera or V4L2
CI / test (push) Failing after 52s

- Discover libcamera cameras, falling back to V4L2; label them Back, Front or External and pick the rear sensor first
- Photo mode: JPEG saves to ~/Pictures/Camera, with an optional high-res still capture
- Video mode: H.264 MP4 recording through ffmpeg, saved to ~/Videos/Camera
- Rear torch LED toggle via sysfs, falling back to logind SetBrightness
- GTK3 + Cairo Wayland UI with a viewfinder, timer, grid, camera switch and gallery view
- Add the desktop entry, icon and camera tests
This commit is contained in:
nandi committed 2026-11-28 12:22:36 -08:00
1 parent 74235cb0ca
commit 1c954aa657
10 files changed
+3479 -8

No files matched your search

+1881
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
[Desktop Entry]
Type=Application
Name=Camera
GenericName=Camera
Comment=Take photos and record videos
Exec=/usr/local/bin/chandra-camera
Icon=chandra-camera
Terminal=false
Categories=AudioVideo;Video;Photography;Utility;
StartupNotify=true
StartupWMClass=chandra-camera
+25
View File
@@ -0,0 +1,25 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#1b223a"/>
<stop offset="100%" stop-color="#0f1322"/>
</linearGradient>
<linearGradient id="lensRing" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#8ba6ff"/>
<stop offset="100%" stop-color="#4e6ee8"/>
</linearGradient>
<radialGradient id="glass" cx="40%" cy="35%" r="60%">
<stop offset="0%" stop-color="#2c3e75"/>
<stop offset="55%" stop-color="#11172b"/>
<stop offset="100%" stop-color="#080b14"/>
</radialGradient>
</defs>
<rect x="8" y="8" width="112" height="112" rx="28" fill="url(#bg)" stroke="#3b4973" stroke-width="2"/>
<path d="M36 42 L44 33 C46 31 48 30 51 30 L77 30 C80 30 82 31 84 33 L92 42 L98 42 C104 42 108 46 108 52 L108 86 C108 92 104 96 98 96 L30 96 C24 96 20 92 20 86 L20 52 C20 46 24 42 30 42 Z"
fill="#242c47" stroke="#53669c" stroke-width="2"/>
<circle cx="64" cy="68" r="22" fill="#0d111d" stroke="url(#lensRing)" stroke-width="4"/>
<circle cx="64" cy="68" r="15" fill="url(#glass)"/>
<circle cx="58" cy="61" r="4.5" fill="#9fb7ff" fill-opacity="0.72"/>
<circle cx="71" cy="74" r="2.2" fill="#6e8cff" fill-opacity="0.55"/>
<circle cx="94" cy="52" r="3.5" fill="#6e8cff"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Host-side unit tests for chandra-camera frame/camera helpers (no hardware required)."""
import importlib.machinery
import importlib.util
import os
import sys
import unittest
try:
import cv2
import numpy as np
HAS_CV2_NUMPY = True
except ImportError:
cv2 = None
np = None
HAS_CV2_NUMPY = False
CAM_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chandra-camera")
_loader = importlib.machinery.SourceFileLoader("chandra_camera_mod", CAM_PATH)
_spec = importlib.util.spec_from_loader("chandra_camera_mod", _loader)
cam_mod = importlib.util.module_from_spec(_spec)
sys.modules["chandra_camera_mod"] = cam_mod
_loader.exec_module(cam_mod)
class TestCameraHelpers(unittest.TestCase):
def test_sort_and_label_cameras(self):
raw = [
("/base/front", "libcamera", "imx371", 0, 90, 4656 * 3496),
("/base/back2", "libcamera", "imx376", 1, 270, 2592 * 1944),
("/base/back1", "libcamera", "imx519", 1, 270, 4656 * 3496),
]
cams = cam_mod.sort_and_label_cameras(raw)
self.assertEqual([c.model for c in cams], ["imx519", "imx371", "imx376"])
self.assertEqual([c.label for c in cams], ["Back · imx519", "Front · imx371", "Back 2 · imx376"])
self.assertEqual(cam_mod.select_initial_camera(cams, ""), 0)
self.assertEqual(cam_mod.select_initial_camera(cams, "front"), 1)
self.assertEqual(cam_mod.select_initial_camera(cams, "back"), 0)
self.assertEqual(cam_mod.select_initial_camera(cams, "imx376"), 2)
@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)
self.assertEqual(bgr0.shape, (3, 2, 3))
self.assertEqual(tuple(bgr0[0, 0]), (200, 20, 10))
self.assertEqual(tuple(bgr0[0, 1]), (60, 50, 40))
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))
# Clockwise 90 deg puts original (row=0, col=0) at (row=0, col=h-1=2)
self.assertEqual(tuple(bgr90[0, 2]), (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))
# Counter-clockwise 90 deg puts original (row=0, col=0) at (row=w-1=1, col=0)
self.assertEqual(tuple(bgr270[1, 0]), (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))
argb32 = cam_mod.bgr_to_cairo_argb32(bgr, np_mod=np)
self.assertEqual(argb32.shape, (1, 2, 4))
self.assertEqual(tuple(argb32[0, 0]), (210, 110, 30, 255))
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_ensure_even_frame(self):
odd = np.zeros((101, 203, 3), dtype=np.uint8)
even = cam_mod.ensure_even_frame(odd)
self.assertEqual(even.shape, (100, 202, 3))
if __name__ == "__main__":
unittest.main()
+27
View File
@@ -216,6 +216,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
"rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display", "rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display",
"screen [on|off|toggle|status] blank or wake the display", "screen [on|off|toggle|status] blank or wake the display",
"brightness [PCT|status] read or set display backlight percent (5..100)", "brightness [PCT|status] read or set display backlight percent (5..100)",
"settings [TAB] open Settings popup (session, desktop, panel, power, shortcuts, apps)",
"auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " + "auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " +
@polkit.demo_modes.join(", "), @polkit.demo_modes.join(", "),
"auth-status the password dialog's agent: running, registered, or why not", "auth-status the password dialog's agent: running, registered, or why not",
@@ -458,6 +459,32 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
} }
} }
} }
"settings" => {
let arg = if words.length() >= 2 { words[1] } else { "session" }
if words.length() > 2 {
return (["error usage: settings [session|desktop|panel|power|shortcuts|apps]"], false)
}
let tab : @shell.SettingsTab? = match arg {
"session" => Some(Session)
"desktop" => Some(Desktop)
"panel" => Some(Panel)
"power" => Some(Power)
"shortcuts" => Some(Shortcuts)
"apps" => Some(Apps)
_ => None
}
match tab {
None => (["error usage: settings [session|desktop|panel|power|shortcuts|apps]"], false)
Some(t) =>
if self.shell.open_settings(t) {
self.frame_changed = true
self.damage.mark_full()
(["ok " + arg], true)
} else {
(["error settings module not loaded"], false)
}
}
}
other => (["error unknown command '" + other + "' (try: help)"], false) other => (["error unknown command '" + other + "' (try: help)"], false)
} }
} }
+5
View File
@@ -45,3 +45,8 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux
## Face Unlock (`libcamera`) ## Face Unlock (`libcamera`)
- On phones whose MIPI sensors (`imx371`, `imx519`, `imx376`) require `libcamera` SoftISP rather than raw V4L2 nodes, [`face/chandra-face`](../face/chandra-face) supports `libcamera:<camera-id>` entries via `python-libcamera` and applies `libcamera.properties.Rotation`. [`face/install.py`](../face/install.py) supports `--system-python` to run with system `python-opencv` + `python-numpy` on `aarch64`, and [`face/polkit-agent-helper.conf`](../face/polkit-agent-helper.conf) grants `char-video4linux`, `char-media`, and `char-dma_heap` access to polkit's helper sandbox. - On phones whose MIPI sensors (`imx371`, `imx519`, `imx376`) require `libcamera` SoftISP rather than raw V4L2 nodes, [`face/chandra-face`](../face/chandra-face) supports `libcamera:<camera-id>` entries via `python-libcamera` and applies `libcamera.properties.Rotation`. [`face/install.py`](../face/install.py) supports `--system-python` to run with system `python-opencv` + `python-numpy` on `aarch64`, and [`face/polkit-agent-helper.conf`](../face/polkit-agent-helper.conf) grants `char-video4linux`, `char-media`, and `char-dma_heap` access to polkit's helper sandbox.
## Camera App (`chandra-camera`)
- [`camera/chandra-camera`](../camera/chandra-camera) provides a native GTK3/Cairo Wayland camera app installed via [`session/install.py`](../session/install.py) with its desktop launcher and icon (`Camera`).
- Supports multi-sensor `libcamera` discovery and live switching (`Back · imx519`, `Front · imx371`, `Back 2 · imx376` on OnePlus 6T, with automatic V4L2 fallback on desktops), sensor orientation transform + front-camera mirror preview, Photo mode (`HD` instant / `Full` high-resolution `StillCapture`, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording H.264 MP4s via `ffmpeg` to `~/Videos/Camera`, an in-app photo gallery viewer, rear flash/torch LED control (`/sys/class/leds/white:flash`) through `org.freedesktop.login1.Session.SetBrightness`, and hardware volume-button or `Space`/`Return` shutter control.
+24 -7
View File
@@ -439,10 +439,16 @@ def query_camera(path):
os.close(fd) os.close(fd)
def _import_libcamera():
os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR")
import libcamera
return libcamera
def list_libcameras(): def list_libcameras():
"""[(libcamera:id, label, '')] for cameras exposed through libcamera.""" """[(libcamera:id, label, '')] for cameras exposed through libcamera."""
try: try:
import libcamera libcamera = _import_libcamera()
except ImportError: except ImportError:
return [] return []
out = [] out = []
@@ -484,7 +490,7 @@ def camera_problem(device):
if device.startswith("libcamera:"): if device.startswith("libcamera:"):
cid = device[len("libcamera:"):] cid = device[len("libcamera:"):]
try: try:
import libcamera libcamera = _import_libcamera()
except ImportError: except ImportError:
return "python-libcamera is not installed (cannot open %s)" % device return "python-libcamera is not installed (cannot open %s)" % device
cm = libcamera.CameraManager.singleton() cm = libcamera.CameraManager.singleton()
@@ -511,11 +517,13 @@ class LibcameraCamera:
if problem: if problem:
raise Fail(problem, 2) raise Fail(problem, 2)
import cv2 import cv2
import libcamera
import mmap import mmap
import numpy as np import numpy as np
libcamera = _import_libcamera()
self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np
reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None)
self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None
cid = device[len("libcamera:"):] cid = device[len("libcamera:"):]
self.cm = libcamera.CameraManager.singleton() self.cm = libcamera.CameraManager.singleton()
self.cam = self.cm.get(cid) self.cam = self.cm.get(cid)
@@ -573,6 +581,17 @@ class LibcameraCamera:
return self.cv2.rotate(bgr, self.cv2.ROTATE_90_COUNTERCLOCKWISE) return self.cv2.rotate(bgr, self.cv2.ROTATE_90_COUNTERCLOCKWISE)
return bgr return bgr
def _requeue(self, req):
if self._reuse_arg is not None:
try:
req.reuse(self._reuse_arg)
except TypeError:
self._reuse_arg = None
req.reuse()
else:
req.reuse()
self.cam.queue_request(req)
def read(self): def read(self):
timeout = 3.0 if self._first else 1.5 timeout = 3.0 if self._first else 1.5
self._first = False self._first = False
@@ -581,16 +600,14 @@ class LibcameraCamera:
ready = self.cm.get_ready_requests() ready = self.cm.get_ready_requests()
if ready: if ready:
for old in ready[:-1]: for old in ready[:-1]:
old.reuse(self.libcamera.Request.ReuseFlag.ReuseBuffers) self._requeue(old)
self.cam.queue_request(old)
req = ready[-1] req = ready[-1]
frame = None frame = None
try: try:
if req.status == self.libcamera.Request.Status.Complete: if req.status == self.libcamera.Request.Status.Complete:
frame = self._to_bgr(req.buffers[self.sc.stream]) frame = self._to_bgr(req.buffers[self.sc.stream])
finally: finally:
req.reuse(self.libcamera.Request.ReuseFlag.ReuseBuffers) self._requeue(req)
self.cam.queue_request(req)
if frame is not None: if frame is not None:
return frame return frame
time.sleep(0.01) time.sleep(0.01)
+2 -1
View File
@@ -13,6 +13,7 @@
chandra-ctl rotate [ARG] rotate/flip display (cw, ccw, flip, 0, 90, 180, 270, status) chandra-ctl rotate [ARG] rotate/flip display (cw, ccw, flip, 0, 90, 180, 270, status)
chandra-ctl screen [ARG] turn display off/on (on, off, toggle, status) chandra-ctl screen [ARG] turn display off/on (on, off, toggle, status)
chandra-ctl brightness [ARG] get/set backlight brightness percent (5..100, status) chandra-ctl brightness [ARG] get/set backlight brightness percent (5..100, status)
chandra-ctl settings [TAB] open Settings popup tab (session, desktop, panel, power, shortcuts, apps)
chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo"); chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo");
MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md) MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md)
chandra-ctl auth-status the password dialog's agent: registered with polkit, or why not chandra-ctl auth-status the password dialog's agent: registered with polkit, or why not
@@ -28,7 +29,7 @@ import os
import socket import socket
import sys import sys
USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | auth-demo [MODE] | auth-status | help}" USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | settings [TAB] | auth-demo [MODE] | auth-status | help}"
def runtime_dir(): def runtime_dir():
+11
View File
@@ -31,6 +31,9 @@ Installs:
/usr/local/bin/chandra-auto-rotate DRM session accelerometer watcher (iio-sensor-proxy) /usr/local/bin/chandra-auto-rotate DRM session accelerometer watcher (iio-sensor-proxy)
/usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into /usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into
kdeglobals (docs/dark-mode.md) kdeglobals (docs/dark-mode.md)
/usr/local/bin/chandra-camera Wayland Camera app (libcamera / V4L2)
/usr/share/applications/chandra-camera.desktop Camera app desktop entry
/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg Camera app icon
/usr/local/share/color-schemes/Chandra{Dark,Light}.colors KDE color schemes, used when Breeze's /usr/local/share/color-schemes/Chandra{Dark,Light}.colors KDE color schemes, used when Breeze's
aren't installed aren't installed
/usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime /usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime
@@ -67,6 +70,9 @@ targets = [
"/usr/local/bin/chandra-ctl", "/usr/local/bin/chandra-ctl",
"/usr/local/bin/chandra-auto-rotate", "/usr/local/bin/chandra-auto-rotate",
"/usr/local/bin/chandra-kde-colors", "/usr/local/bin/chandra-kde-colors",
"/usr/local/bin/chandra-camera",
"/usr/share/applications/chandra-camera.desktop",
"/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg",
"/usr/local/share/color-schemes/ChandraDark.colors", "/usr/local/share/color-schemes/ChandraDark.colors",
"/usr/local/share/color-schemes/ChandraLight.colors", "/usr/local/share/color-schemes/ChandraLight.colors",
"/usr/share/wayland-sessions/chandra.desktop", "/usr/share/wayland-sessions/chandra.desktop",
@@ -177,6 +183,11 @@ else:
install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl") install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl")
install(os.path.join(root, "session/chandra-auto-rotate"), "/usr/local/bin/chandra-auto-rotate") install(os.path.join(root, "session/chandra-auto-rotate"), "/usr/local/bin/chandra-auto-rotate")
install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors") install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors")
install(os.path.join(root, "camera/chandra-camera"), "/usr/local/bin/chandra-camera")
put(os.path.join(root, "camera/chandra-camera.desktop"), "/usr/share/applications/chandra-camera.desktop", 0o644)
put(os.path.join(root, "camera/chandra-camera.svg"), "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", 0o644)
if shutil.which("gtk-update-icon-cache"):
subprocess.run(["gtk-update-icon-cache", "-q", "-f", "/usr/share/icons/hicolor"], check=False)
for f in ("ChandraDark.colors", "ChandraLight.colors"): for f in ("ChandraDark.colors", "ChandraLight.colors"):
put(os.path.join(root, "session/color-schemes", f), "/usr/local/share/color-schemes/" + f, 0o644) put(os.path.join(root, "session/color-schemes", f), "/usr/local/share/color-schemes/" + f, 0o644)
# The display-manager entry stays a real file: some managers don't follow symlinks there. # The display-manager entry stays a real file: some managers don't follow symlinks there.