diff --git a/camera/chandra-camera b/camera/chandra-camera index beb5357..b50dfed 100755 --- a/camera/chandra-camera +++ b/camera/chandra-camera @@ -2,13 +2,14 @@ """chandra-camera: mobile Wayland camera app for Chandra using libcamera / V4L2.""" import argparse +import ctypes from dataclasses import dataclass import datetime import fcntl import glob -import mmap import os import queue +import select import shutil import signal import struct @@ -29,7 +30,12 @@ VIDEO_EXTS = (".mp4", ".mkv", ".webm") QUAD_BAYER_MODELS = {"imx371"} -# Fallback resolutions when a camera reports no enumerated StillCapture sizes. +# Default live viewfinder/video sizes: 1600x1200 selects full-FOV 2x2-binned 4:3 on IMX519. +PREFERRED_VIEWFINDER_SIZES = [ + (1600, 1200), + (1440, 1080), + (1280, 960), +] DEFAULT_VIEWFINDER_SIZE = (1280, 960) PREFERRED_STILL_SIZES = [ (4648, 3496), @@ -40,6 +46,19 @@ PREFERRED_STILL_SIZES = [ (1280, 960), ] +# Calibrated linear RGB -> sRGB CCM for Sony IMX371 Quad-Bayer sensor (rows sum to 1.0). +QUAD_CCM_RGB = ( + 1.42, -0.30, -0.12, + -0.22, 1.40, -0.18, + -0.04, -0.44, 1.48, +) +QUAD_TONE_LUT_MAX = 3.0 + +# Linux dma-buf synchronization ioctl (DMA_BUF_IOCTL_SYNC = _IOW('b', 0, __u64)). +DMA_BUF_IOCTL_SYNC = 0x40086200 +DMA_BUF_SYNC_START_READ = 1 +DMA_BUF_SYNC_END_READ = 5 + @dataclass class CameraInfo: @@ -62,13 +81,86 @@ class CameraInfo: return self.location == 1 -def _import_libcamera(): - """Import libcamera after silencing non-error C++ log noise.""" +def _configure_libcamera_env(): + """Set IPA tuning path and SoftISP mode before importing libcamera.""" os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR") + if "LIBCAMERA_SOFTISP_MODE" not in os.environ: + os.environ["LIBCAMERA_SOFTISP_MODE"] = os.environ.get("CHANDRA_SOFTISP_MODE", "gpu") + + here_ipa = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ipa") + share_ipa = "/usr/local/share/chandra/ipa" + ipa_dirs = [d for d in (here_ipa, share_ipa) if os.path.isdir(d)] + if ipa_dirs: + cur = os.environ.get("LIBCAMERA_IPA_CONFIG_PATH", "") + parts = [p for p in cur.split(":") if p] + for d in reversed(ipa_dirs): + if d not in parts: + parts.insert(0, d) + if "/usr/share/libcamera/ipa" not in parts: + parts.append("/usr/share/libcamera/ipa") + os.environ["LIBCAMERA_IPA_CONFIG_PATH"] = ":".join(parts) + + +def _import_libcamera(): + """Import libcamera after configuring tuning paths and silencing log noise.""" + _configure_libcamera_env() import libcamera return libcamera +_ISP_LIB = None +_ISP_LIB_TRIED = False + + +def load_isp_lib(): + """Load compiled C/OpenMP ISP library if built/installed, else return None.""" + global _ISP_LIB, _ISP_LIB_TRIED + if _ISP_LIB_TRIED: + return _ISP_LIB + _ISP_LIB_TRIED = True + + root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + candidates = [ + os.environ.get("CHANDRA_CAMERA_ISP", ""), + os.path.join(root_dir, "build", "libchandra-camera-isp.so"), + "/usr/local/lib/chandra/libchandra-camera-isp.so", + ] + for path in candidates: + if not path or not os.path.isfile(path): + continue + try: + lib = ctypes.CDLL(path) + lib.quad_csi2p_to_bgr16_4x4.argtypes = [ + ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_void_p + ] + lib.quad_csi2p_to_bgr16_4x4.restype = None + + lib.quad_csi2p_to_bayer16_2x2.argtypes = [ + ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_void_p + ] + lib.quad_csi2p_to_bayer16_2x2.restype = None + + lib.isp_ccm_tone_bgr16_to_bgr8.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, + ctypes.c_float, ctypes.c_float, + ctypes.c_float, ctypes.c_float, ctypes.c_float, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_float, + ] + lib.isp_ccm_tone_bgr16_to_bgr8.restype = None + + lib.burst_merge_bgr16.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, + ctypes.c_void_p, ctypes.c_int, ctypes.c_float, + ] + lib.burst_merge_bgr16.restype = None + + _ISP_LIB = lib + return lib + except Exception: + continue + return None + + def _short_model_name(raw_model, fallback_id): """Turn a libcamera Model property or device path into a compact sensor label.""" if raw_model: @@ -99,7 +191,7 @@ def sort_and_label_cameras(raw_items): primary_back_cid = best_back[0] def sort_key(item): - cid, _backend, model, loc, _rot, max_px = item + cid, _backend, _model, loc, _rot, max_px = item if loc == 1: group = 0 if cid == primary_back_cid else 2 elif loc == 0: @@ -170,7 +262,6 @@ def discover_cameras(): return sort_and_label_cameras(raw) # V4L2 fallback for desktops without libcamera sensors. - import glob v4l2 = [] for idx in range(10): path = "/dev/video%d" % idx @@ -230,7 +321,7 @@ def rotate_bgr(bgr, rot, cv2_mod): def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None): - """Convert raw camera buffer bytes into a contiguous upright uint8 BGR image.""" + """Convert raw camera buffer bytes/memoryview into a contiguous upright uint8 BGR image.""" if np_mod is None: import numpy as np_mod if cv2_mod is None: @@ -262,6 +353,7 @@ VIDIOC_G_CTRL = 0xC008561B VIDIOC_S_CTRL = 0xC008561C VIDIOC_QUERYCTRL = 0xC0445624 V4L2_CID_EXPOSURE = 0x00980911 +V4L2_CID_FOCUS_ABSOLUTE = 0x009A090A V4L2_CID_VBLANK = 0x009E0901 V4L2_CID_ANALOGUE_GAIN = 0x009E0903 V4L2_CID_DIGITAL_GAIN = 0x009F0905 @@ -270,12 +362,17 @@ _QUAD_TONE_LUT = None def _build_tone_lut(np_mod): - """Build 4096-entry uint8 tone LUT: linear 0..160, smooth highlight roll-off to 768, gamma 2.2.""" - x = np_mod.linspace(0.0, 768.0, 4096, dtype=np_mod.float32) - t = np_mod.maximum(x - 160.0, 0.0) / 95.0 - y = np_mod.where(x <= 160.0, x, 160.0 + 95.0 * (t / (1.0 + 0.65 * t))) - y = np_mod.clip(y / 255.0, 0.0, 1.0) - return np_mod.clip((y ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) + """Build 4096-entry uint8 filmic-shoulder + true sRGB OETF LUT over linear [0.0, 3.0].""" + x = np_mod.linspace(0.0, QUAD_TONE_LUT_MAX, 4096, dtype=np_mod.float32) + t = np_mod.maximum(x - 0.75, 0.0) / 0.25 + y = np_mod.where(x <= 0.75, x, 0.75 + 0.25 * (t / (1.0 + 0.8 * t))) + y = np_mod.clip(y, 0.0, 1.0) + srgb = np_mod.where( + y <= 0.0031308, + 12.92 * y, + 1.055 * (np_mod.maximum(y, 0.0031308) ** (1.0 / 2.4)) - 0.055, + ) + return np_mod.clip(srgb * 255.0 + 0.5, 0, 255).astype(np_mod.uint8) def _get_tone_lut(np_mod): @@ -301,6 +398,44 @@ def find_sensor_subdev(model): return None +def find_lens_subdev(sensor_model): + """Find sibling VCM lens subdevice on the same I2C bus as `sensor_model`.""" + sensor_dev = find_sensor_subdev(sensor_model) + if not sensor_dev: + return None + sensor_name_path = "/sys/class/video4linux/%s/name" % os.path.basename(sensor_dev) + try: + sensor_full = open(sensor_name_path).read().strip().lower() + except OSError: + return None + parts = sensor_full.split() + if len(parts) < 2 or "-" not in parts[1]: + return None + bus_prefix = parts[1].split("-", 1)[0] + "-" + + for p in sorted(glob.glob("/sys/class/video4linux/v4l-subdev*/name")): + dev = "/dev/" + os.path.basename(os.path.dirname(p)) + if dev == sensor_dev: + continue + try: + name = open(p).read().strip().lower() + except OSError: + continue + if (" " + bus_prefix) not in name and not name.startswith(bus_prefix): + continue + io = None + try: + io = _V4L2SubdevIO(dev) + io.query(V4L2_CID_FOCUS_ABSOLUTE) + return dev + except Exception: + pass + finally: + if io is not None: + io.close() + return None + + class _V4L2SubdevIO: """Thin ioctl wrapper over a V4L2 subdevice file descriptor.""" @@ -358,7 +493,10 @@ class QuadSensorAE: raise self.exp_base_max = max(self.exp_min + 1, self.exp_max_now - max(0, self.init_vblank - self.vb_min)) - self.vb_cap = min(self.vb_max, 9500) + self.vb_cap_photo = min(self.vb_max, self.vb_min + 2200) + self.vb_cap_video = min(self.vb_max, self.vb_min + 800) + self.video_mode = False + self.vb_cap = self.vb_cap_photo self.exp_lowlight_max = min(self.exp_base_max + max(0, self.vb_cap - self.vb_min), 12000) self.ag_max_x = 512.0 / max(512 - min(self.ag_max, 504), 1) self.dg_max_x = min(self.dg_max / 1024.0, 4.0) if self.has_dgain else 1.0 @@ -371,26 +509,37 @@ class QuadSensorAE: self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) self.cooldown = 0 + def set_video_mode(self, enabled): + """Tighten vblank ceiling in video mode to guarantee >=20 FPS and smoother AE steps.""" + self.video_mode = bool(enabled) + self.vb_cap = self.vb_cap_video if self.video_mode else self.vb_cap_photo + self.exp_lowlight_max = min(self.exp_base_max + max(0, self.vb_cap - self.vb_min), 12000) + self.e_max = float(self.exp_lowlight_max) * self.ag_max_x * self.dg_max_x + if self.ev_total > self.e_max: + self.ev_total = self.e_max + if self.cur_vblank > self.vb_cap: + vb, exp, ag, dg = self.plan(self.ev_total) + self._apply(vb, exp, ag, dg) + self.cooldown = 2 + def plan(self, ev_total): - """Map scalar exposure target E = exp * ag_x * dg_x to (vblank, exp, ag_code, dg_code).""" + """Map scalar exposure target E = exp * ag_x * dg_x to (vblank, exp, ag_code, dg_code). + + Prioritizes maxing sensor exposure within base frame duration and full analog gain + before extending vertical blanking, keeping live preview and video frame rate high. + """ ev = max(self.e_min, min(float(ev_total), self.e_max)) - mid_ag = min(8.0, self.ag_max_x) if ev <= self.exp_base_max: exp, ag_x, dg_x, vb = int(round(ev)), 1.0, 1.0, self.vb_min - elif ev <= self.exp_base_max * mid_ag: + elif ev <= self.exp_base_max * self.ag_max_x: exp = self.exp_base_max ag_x = ev / max(exp, 1) dg_x, vb = 1.0, self.vb_min - elif ev <= self.exp_lowlight_max * mid_ag: - ag_x = mid_ag + elif ev <= self.exp_lowlight_max * self.ag_max_x: + ag_x = self.ag_max_x exp = int(round(ev / ag_x)) dg_x = 1.0 vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) - elif ev <= self.exp_lowlight_max * self.ag_max_x: - exp = self.exp_lowlight_max - vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) - ag_x = ev / max(exp, 1) - dg_x = 1.0 else: exp = self.exp_lowlight_max vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) @@ -431,7 +580,7 @@ class QuadSensorAE: self.cooldown = 2 def update(self, raw_p50, raw_p95): - """Adjust exposure/gain from raw 0..255 luma stats with 2-frame pipeline settling cooldown.""" + """Adjust exposure/gain from raw 0..255 luma stats with pipeline settling cooldown.""" if self.cooldown > 0: self.cooldown -= 1 return False @@ -442,14 +591,15 @@ class QuadSensorAE: 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)) + damp = 0.55 if self.video_mode else 0.72 + new_ev = max(self.e_min, min(self.ev_total * (ratio ** damp), self.e_max)) if abs(new_ev - self.ev_total) <= self.ev_total * 0.05: return False vb, exp, ag, dg = self.plan(new_ev) self.ev_total = new_ev if (vb, exp, ag, dg) != (self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg): self._apply(vb, exp, ag, dg) - self.cooldown = 2 + self.cooldown = 3 if self.video_mode else 2 return True return False @@ -475,91 +625,208 @@ class QuadSensorAE: self.io.close() -def debayer_quad_csi2p( - raw_buf, - width, - height, - stride, - rot=0, - offset=0, - target_size=(960, 720), - high_quality=False, - gamma_lut=None, - tone_lut=None, - return_stats=False, - cv2_mod=None, - np_mod=None, -): - """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into upright BGR uint8.""" - if np_mod is None: - import numpy as np_mod - if cv2_mod is None: - import cv2 as cv2_mod +class ContrastAF: + """Non-blocking contrast-detection VCM autofocus state machine (coarse + fine sweep).""" - arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) - even_h = (height // 2) * 2 - even_w = (width // 4) * 4 - row_bytes = (even_w // 4) * 5 - b5 = arr[:even_h, :row_bytes].reshape((even_h // 2, 2, even_w // 4, 5)) + def __init__(self, subdev_path, io=None): + self.io = io if io is not None else _V4L2SubdevIO(subdev_path) + self._closed = False + try: + mn, mx, step, df = self.io.query(V4L2_CID_FOCUS_ABSOLUTE) + self.pos_min = int(mn) + self.pos_max = int(mx) + self.pos_step = max(1, int(step)) + self.pos_default = int(df) + self.init_pos = int(self.io.get(V4L2_CID_FOCUS_ABSOLUTE)) + except Exception: + self.io.close() + raise - if high_quality: - lo = b5[:, :, :, 4] - g0_hi = ( - b5[:, 0, :, 0].astype(np_mod.uint16) - + b5[:, 0, :, 1] - + b5[:, 1, :, 0] - + b5[:, 1, :, 1] - ) << 2 - g0_lo = ( - (lo[:, 0, :] & 3).astype(np_mod.uint16) - + ((lo[:, 0, :] >> 2) & 3) - + (lo[:, 1, :] & 3) - + ((lo[:, 1, :] >> 2) & 3) - ) - g1_hi = ( - b5[:, 0, :, 2].astype(np_mod.uint16) - + b5[:, 0, :, 3] - + b5[:, 1, :, 2] - + b5[:, 1, :, 3] - ) << 2 - g1_lo = ( - ((lo[:, 0, :] >> 4) & 3).astype(np_mod.uint16) - + ((lo[:, 0, :] >> 6) & 3) - + ((lo[:, 1, :] >> 4) & 3) - + ((lo[:, 1, :] >> 6) & 3) - ) - bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16) - bayer[:, 0::2] = g0_hi + g0_lo - bayer[:, 1::2] = g1_hi + g1_lo - max_val = 4092.0 - black_cap = 256.0 + self.state = "idle" # "idle", "coarse", "fine", "locked" + self.roi = (0.5, 0.5) + self.positions = [] + self.idx = 0 + self.settle = 0 + self.scores = [] + self.best_pos = self.init_pos + self.best_score = -1.0 + self.cur_pos = self.init_pos + + def _quantize(self, pos): + p = max(self.pos_min, min(int(round(pos)), self.pos_max)) + if self.pos_step > 1: + p = self.pos_min + ((p - self.pos_min + self.pos_step // 2) // self.pos_step) * self.pos_step + p = max(self.pos_min, min(p, self.pos_max)) + return p + + def _linspace_positions(self, lo, hi, count): + if count <= 1 or hi <= lo: + return [self._quantize(lo)] + out = [] + for i in range(count): + p = self._quantize(lo + (hi - lo) * i / float(count - 1)) + if not out or p != out[-1]: + out.append(p) + return out + + def _move(self, pos): + p = self._quantize(pos) + self.io.set(V4L2_CID_FOCUS_ABSOLUTE, p) + self.cur_pos = p + + def set_position(self, pos): + """Move lens to a specific focus position (e.g. restoring focus after camera reopen).""" + self._move(pos) + self.best_pos = self.cur_pos + + def trigger(self, nx=0.5, ny=0.5): + """Start a non-blocking coarse+fine sweep centered on normalized ROI `(nx, ny)`.""" + nx = max(0.1, min(0.9, float(nx))) + ny = max(0.1, min(0.9, float(ny))) + self.roi = (nx, ny) + # Skip extreme macro/infinity padding only slightly if full range is wide; cover full range cleanly. + self.positions = self._linspace_positions(self.pos_min, self.pos_max, 9) + self.state = "coarse" + self.idx = 0 + self.settle = 2 + self.scores = [] + self._move(self.positions[0]) + + @staticmethod + def compute_sharpness(bgr, roi=(0.5, 0.5), cv2_mod=None, np_mod=None): + """Brightness-normalized Laplacian variance over a 35% ROI around `(nx, ny)`.""" + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + h, w = bgr.shape[:2] + if h < 16 or w < 16: + return 0.0 + sz = max(32, int(round(min(h, w) * 0.35))) + cx = int(round(roi[0] * w)) + cy = int(round(roi[1] * h)) + x0 = max(0, min(w - sz, cx - sz // 2)) + y0 = max(0, min(h - sz, cy - sz // 2)) + crop = bgr[y0:y0 + sz, x0:x0 + sz] + gray = cv2_mod.cvtColor(crop, cv2_mod.COLOR_BGR2GRAY) + if max(gray.shape[:2]) > 256: + scale = 256.0 / float(max(gray.shape[:2])) + gray = cv2_mod.resize( + gray, + (max(16, int(round(gray.shape[1] * scale))), max(16, int(round(gray.shape[0] * scale)))), + interpolation=cv2_mod.INTER_AREA, + ) + lap = cv2_mod.Laplacian(gray, cv2_mod.CV_32F) + var = float(lap.var()) + mean_luma = float(gray.mean()) + return var / max(mean_luma ** 1.2, 16.0) + + def step(self, bgr, cv2_mod=None, np_mod=None): + """Advance AF state machine by one frame. Returns event string or None.""" + if self.state not in ("coarse", "fine"): + return None + if self.settle > 0: + self.settle -= 1 + return None + + score = self.compute_sharpness(bgr, self.roi, cv2_mod=cv2_mod, np_mod=np_mod) + self.scores.append((self.positions[self.idx], score)) + self.idx += 1 + if self.idx < len(self.positions): + self._move(self.positions[self.idx]) + self.settle = 2 + return None + + best_p, best_s = max(self.scores, key=lambda it: it[1]) + if self.state == "coarse": + span = max(self.pos_step * 2, (self.pos_max - self.pos_min) // 7) + lo = max(self.pos_min, best_p - span) + hi = min(self.pos_max, best_p + span) + self.positions = self._linspace_positions(lo, hi, 5) + self.state = "fine" + self.idx = 0 + self.settle = 2 + self.scores = [] + self._move(self.positions[0]) + return "coarse_done" + + self._move(best_p) + self.best_pos = self.cur_pos + self.best_score = best_s + self.state = "locked" + return "locked" + + def close(self): + if self._closed: + return + self._closed = True + try: + self._move(self.init_pos) + except Exception: + pass + finally: + self.io.close() + + +class QuadISPState: + """Temporally smoothed black level, AWB gains, and exposure boost for flicker-free video.""" + + def __init__(self, alpha=0.18): + self.alpha = float(alpha) + self.initialized = False + self.black = 0.0 + self.gains = None + self.boost = 1.0 + + def reset(self): + self.initialized = False + self.black = 0.0 + self.gains = None + self.boost = 1.0 + + def update(self, black, gains, boost, np_mod): + g = np_mod.asarray(gains, dtype=np_mod.float32) + if not self.initialized: + self.black = float(black) + self.gains = g.copy() + self.boost = float(boost) + self.initialized = True + else: + a = self.alpha + self.black += a * (float(black) - self.black) + self.gains += a * (g - self.gains) + self.boost += a * (float(boost) - self.boost) + return self.black, self.gains, self.boost + + +def _compute_quad_stats_and_gains(bgr16, max_val, black_cap, np_mod): + """Compute black level, midtone-weighted AWB gains, raw luma percentiles, and digital boost.""" + fh, fw = bgr16.shape[:2] + step = max(1, min(fh, fw) // 160) + sub16 = bgr16[::step, ::step].astype(np_mod.float32) + if fh > 32 and fw > 32: + border_m = max(1, 8 // step) + sub_raw = sub16[border_m:-border_m, border_m:-border_m] if sub16.shape[0] > border_m * 2 + 2 and sub16.shape[1] > border_m * 2 + 2 else sub16 else: - p8 = b5[:, :, :, :4] - s = p8[:, 0, :, :].astype(np_mod.uint16) - s += p8[:, 1, :, :] - bayer = np_mod.ascontiguousarray((s[:, :, 0::2] + s[:, :, 1::2]).reshape((even_h // 2, even_w // 2))) - max_val = 1020.0 - black_cap = 64.0 + sub_raw = sub16 - bgr16 = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR) - if target_size is not None: - bgr16 = cv2_mod.resize(bgr16, target_size, interpolation=cv2_mod.INTER_AREA) - - f = bgr16.astype(np_mod.float32) - fh, fw = f.shape[:2] - sub_raw = f[8:-8:4, 8:-8:4] if (fh > 32 and fw > 32) else f black = float(np_mod.clip(np_mod.percentile(sub_raw, 1), 0.0, black_cap)) - f = np_mod.maximum(f - black, 0.0) * (255.0 / max(max_val - black, 1.0)) + f = np_mod.maximum(sub16 - black, 0.0) * (255.0 / max(max_val - black, 1.0)) - sub = f[::4, ::4] if (fh >= 32 and fw >= 32) else f - means = sub.mean(axis=(0, 1)) - avg = float(means.mean()) - raw_luma = sub.mean(axis=2) + raw_luma = f.mean(axis=2) raw_p50 = float(np_mod.percentile(raw_luma, 50)) raw_p95 = float(np_mod.percentile(raw_luma, 95)) + # Prefer midtone non-clipped pixels for stable AWB without blown-highlight bias. + mid_mask = (raw_luma > 5.0) & (raw_luma < 220.0) + if int(mid_mask.sum()) >= 64: + means = f[mid_mask].mean(axis=0) + else: + means = f.mean(axis=(0, 1)) + avg = float(means.mean()) + if avg > 0.25: - gains = np_mod.clip(avg / np_mod.maximum(means, max(avg * 0.4, 0.25)), 0.7, 2.0) + gains = np_mod.clip(avg / np_mod.maximum(means, max(avg * 0.4, 0.25)), 0.75, 2.2).astype(np_mod.float32) else: gains = np_mod.ones(3, dtype=np_mod.float32) @@ -570,18 +837,184 @@ def debayer_quad_csi2p( if raw_p95 * boost > 240.0: boost = max(1.0, min(boost, 300.0 / max(raw_p95, 1.0))) + return black, gains, boost, raw_p50, raw_p95 + + +def _apply_ccm_tone_numpy(bgr16, black, scale_norm, gains, ccm_rgb, tone_lut, np_mod): + """Pure-NumPy fallback matching C isp_ccm_tone_bgr16_to_bgr8.""" + f = np_mod.maximum(bgr16.astype(np_mod.float32) - float(black), 0.0) * float(scale_norm) + f *= gains.reshape((1, 1, 3)) + b_in, g_in, r_in = f[:, :, 0], f[:, :, 1], f[:, :, 2] + m = ccm_rgb + r_c = m[0] * r_in + m[1] * g_in + m[2] * b_in + g_c = m[3] * r_in + m[4] * g_in + m[5] * b_in + b_c = m[6] * r_in + m[7] * g_in + m[8] * b_in + bgr_lin = np_mod.stack([b_c, g_c, r_c], axis=2) + idx = np_mod.clip((bgr_lin * (4095.0 / QUAD_TONE_LUT_MAX) + 0.5).astype(np_mod.int32), 0, 4095) + return tone_lut[idx] + + +def _unpack_quad_4x4_numpy(arr, even_w, even_h, np_mod): + """Pure-NumPy 10-bit 4x4 Quad-Bayer SRGGB supercell unpack into uint16 BGR (0..4092).""" + w4 = (even_w // 4) * 4 + h4 = (even_h // 4) * 4 + row_bytes = (w4 // 4) * 5 + b5 = arr[:h4, :row_bytes].reshape((h4 // 4, 4, w4 // 4, 5)) + lo = b5[:, :, :, 4] + + r_hi = (b5[:, 0, :, 0].astype(np_mod.uint16) + b5[:, 0, :, 1] + b5[:, 1, :, 0] + b5[:, 1, :, 1]) << 2 + r_lo = (lo[:, 0, :] & 3).astype(np_mod.uint16) + ((lo[:, 0, :] >> 2) & 3) + (lo[:, 1, :] & 3) + ((lo[:, 1, :] >> 2) & 3) + + gr_hi = (b5[:, 0, :, 2].astype(np_mod.uint16) + b5[:, 0, :, 3] + b5[:, 1, :, 2] + b5[:, 1, :, 3]) << 2 + gr_lo = ((lo[:, 0, :] >> 4) & 3).astype(np_mod.uint16) + ((lo[:, 0, :] >> 6) & 3) + ((lo[:, 1, :] >> 4) & 3) + ((lo[:, 1, :] >> 6) & 3) + + gb_hi = (b5[:, 2, :, 0].astype(np_mod.uint16) + b5[:, 2, :, 1] + b5[:, 3, :, 0] + b5[:, 3, :, 1]) << 2 + gb_lo = (lo[:, 2, :] & 3).astype(np_mod.uint16) + ((lo[:, 2, :] >> 2) & 3) + (lo[:, 3, :] & 3) + ((lo[:, 3, :] >> 2) & 3) + + b_hi = (b5[:, 2, :, 2].astype(np_mod.uint16) + b5[:, 2, :, 3] + b5[:, 3, :, 2] + b5[:, 3, :, 3]) << 2 + b_lo = ((lo[:, 2, :] >> 4) & 3).astype(np_mod.uint16) + ((lo[:, 2, :] >> 6) & 3) + ((lo[:, 3, :] >> 4) & 3) + ((lo[:, 3, :] >> 6) & 3) + + out = np_mod.empty((h4 // 4, w4 // 4, 3), dtype=np_mod.uint16) + out[:, :, 0] = b_hi + b_lo + out[:, :, 1] = ((gr_hi + gr_lo) + (gb_hi + gb_lo) + 1) >> 1 + out[:, :, 2] = r_hi + r_lo + return out + + +def _unpack_quad_2x2_numpy(arr, even_w, even_h, np_mod): + """Pure-NumPy 10-bit 2x2-binned Quad-Bayer SRGGB unpack into uint16 Bayer (0..4092).""" + row_bytes = (even_w // 4) * 5 + b5 = arr[:even_h, :row_bytes].reshape((even_h // 2, 2, even_w // 4, 5)) + lo = b5[:, :, :, 4] + g0_hi = (b5[:, 0, :, 0].astype(np_mod.uint16) + b5[:, 0, :, 1] + b5[:, 1, :, 0] + b5[:, 1, :, 1]) << 2 + g0_lo = (lo[:, 0, :] & 3).astype(np_mod.uint16) + ((lo[:, 0, :] >> 2) & 3) + (lo[:, 1, :] & 3) + ((lo[:, 1, :] >> 2) & 3) + g1_hi = (b5[:, 0, :, 2].astype(np_mod.uint16) + b5[:, 0, :, 3] + b5[:, 1, :, 2] + b5[:, 1, :, 3]) << 2 + g1_lo = ((lo[:, 0, :] >> 4) & 3).astype(np_mod.uint16) + ((lo[:, 0, :] >> 6) & 3) + ((lo[:, 1, :] >> 4) & 3) + ((lo[:, 1, :] >> 6) & 3) + bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16) + bayer[:, 0::2] = g0_hi + g0_lo + bayer[:, 1::2] = g1_hi + g1_lo + return bayer + + +def quad_raw_to_bgr16( + raw_buf, + width, + height, + stride, + offset=0, + target_size=(1152, 864), + high_quality=False, + cv2_mod=None, + np_mod=None, +): + """Unpack 10-bit CSI-2 Quad-Bayer raw into linear 16-bit BGR (0..4092).""" + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + + arr = np_mod.ascontiguousarray( + np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) + ) + even_h = (height // 2) * 2 + even_w = (width // 4) * 4 + isp = load_isp_lib() + + can_4x4 = (not high_quality) and (target_size is not None) and (even_w // 4 >= target_size[0] and even_h // 4 >= target_size[1]) + if can_4x4: + w4 = even_w // 4 + h4 = even_h // 4 + if isp is not None: + bgr16 = np_mod.empty((h4, w4, 3), dtype=np_mod.uint16) + isp.quad_csi2p_to_bgr16_4x4(arr.ctypes.data, even_w, even_h, stride, bgr16.ctypes.data) + else: + bgr16 = _unpack_quad_4x4_numpy(arr, even_w, even_h, np_mod) + tw, th = int(target_size[0]), int(target_size[1]) + if tw == w4 and th == h4: + pass + elif (w4 - tw) <= 32 and (h4 - th) <= 32 and w4 >= tw and h4 >= th: + dx = (w4 - tw) // 2 + dy = (h4 - th) // 2 + bgr16 = np_mod.ascontiguousarray(bgr16[dy:dy + th, dx:dx + tw]) + else: + bgr16 = cv2_mod.resize(bgr16, (tw, th), interpolation=cv2_mod.INTER_AREA) + return bgr16 + + # 2x2 10-bit Bayer path (for HQ stills or explicit target sizes larger than 4x4 supercell). + if isp is not None: + bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16) + isp.quad_csi2p_to_bayer16_2x2(arr.ctypes.data, even_w, even_h, stride, bayer.ctypes.data) + else: + bayer = _unpack_quad_2x2_numpy(arr, even_w, even_h, np_mod) + + demosaic_code = getattr(cv2_mod, "COLOR_BayerBG2BGR_EA", cv2_mod.COLOR_BayerBG2BGR) if high_quality else cv2_mod.COLOR_BayerBG2BGR + bgr16 = cv2_mod.cvtColor(bayer, demosaic_code) + if target_size is not None and (bgr16.shape[1], bgr16.shape[0]) != (int(target_size[0]), int(target_size[1])): + bgr16 = cv2_mod.resize(bgr16, (int(target_size[0]), int(target_size[1])), interpolation=cv2_mod.INTER_AREA) + return np_mod.ascontiguousarray(bgr16) + + +def isp_finish_bgr16( + bgr16, + rot=0, + high_quality=False, + tone_lut=None, + isp_state=None, + return_stats=False, + cv2_mod=None, + np_mod=None, +): + """Apply black-level, AWB, CCM, sRGB LUT, chroma denoise, optional sharpen, and rotation.""" + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + + max_val = 4092.0 + black_cap = 256.0 + black, gains, boost, raw_p50, raw_p95 = _compute_quad_stats_and_gains(bgr16, max_val, black_cap, np_mod) + if isp_state is not None and not high_quality: + black, gains, boost = isp_state.update(black, gains, boost, np_mod) + if tone_lut is None: tone_lut = _get_tone_lut(np_mod) - idx = np_mod.clip((f * (gains * boost) * (4095.0 / 768.0)).astype(np_mod.int32), 0, 4095) - out = tone_lut[idx] - if boost > 1.8 and out.shape[0] >= 64 and out.shape[1] >= 64: - lab = cv2_mod.cvtColor(out, cv2_mod.COLOR_BGR2LAB) - l_ch, a_ch, b_ch = cv2_mod.split(lab) - l_ch = cv2_mod.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l_ch) - a_ch = cv2_mod.GaussianBlur(a_ch, (5, 5), 0) - b_ch = cv2_mod.GaussianBlur(b_ch, (5, 5), 0) - out = cv2_mod.cvtColor(cv2_mod.merge([l_ch, a_ch, b_ch]), cv2_mod.COLOR_LAB2BGR) + scale_norm = boost / max(max_val - black, 1.0) + ccm_arr = np_mod.asarray(QUAD_CCM_RGB, dtype=np_mod.float32) + + isp = load_isp_lib() + bgr16_c = np_mod.ascontiguousarray(bgr16, dtype=np_mod.uint16) + h, w = bgr16_c.shape[:2] + if isp is not None: + out = np_mod.empty((h, w, 3), dtype=np_mod.uint8) + isp.isp_ccm_tone_bgr16_to_bgr8( + bgr16_c.ctypes.data, + out.ctypes.data, + int(h * w), + float(black), + float(scale_norm), + float(gains[0]), + float(gains[1]), + float(gains[2]), + ccm_arr.ctypes.data, + tone_lut.ctypes.data, + float(QUAD_TONE_LUT_MAX), + ) + else: + out = _apply_ccm_tone_numpy(bgr16_c, black, scale_norm, gains, ccm_arr, tone_lut, np_mod) + + if boost > 1.25 and out.shape[0] >= 32 and out.shape[1] >= 32: + ycrcb = cv2_mod.cvtColor(out, cv2_mod.COLOR_BGR2YCrCb) + y_ch, cr_ch, cb_ch = cv2_mod.split(ycrcb) + cr_ch = cv2_mod.GaussianBlur(cr_ch, (5, 5), 0) + cb_ch = cv2_mod.GaussianBlur(cb_ch, (5, 5), 0) + if boost > 2.8: + y_ch = cv2_mod.bilateralFilter(y_ch, 3, 18, 18) + out = cv2_mod.cvtColor(cv2_mod.merge([y_ch, cr_ch, cb_ch]), cv2_mod.COLOR_YCrCb2BGR) + + if high_quality and out.shape[0] >= 64 and out.shape[1] >= 64: + blur = cv2_mod.GaussianBlur(out, (0, 0), 1.2) + out = cv2_mod.addWeighted(out, 1.18, blur, -0.18, 0) res = np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) if return_stats: @@ -589,8 +1022,56 @@ def debayer_quad_csi2p( return res -def bgr_to_cairo_argb32(bgr, np_mod=None): +def debayer_quad_csi2p( + raw_buf, + width, + height, + stride, + rot=0, + offset=0, + target_size=(1152, 864), + high_quality=False, + gamma_lut=None, + tone_lut=None, + isp_state=None, + return_stats=False, + cv2_mod=None, + np_mod=None, +): + """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into upright BGR uint8.""" + del gamma_lut + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + + bgr16 = quad_raw_to_bgr16( + raw_buf, + width, + height, + stride, + offset=offset, + target_size=target_size, + high_quality=high_quality, + cv2_mod=cv2_mod, + np_mod=np_mod, + ) + return isp_finish_bgr16( + bgr16, + rot=rot, + high_quality=high_quality, + tone_lut=tone_lut, + isp_state=isp_state, + return_stats=return_stats, + cv2_mod=cv2_mod, + np_mod=np_mod, + ) + + +def bgr_to_cairo_argb32(bgr, cv2_mod=None, np_mod=None): """Convert contiguous (H, W, 3) uint8 BGR frame into (H, W, 4) BGRA for Cairo FORMAT_RGB24.""" + if cv2_mod is not None: + return np_mod.ascontiguousarray(cv2_mod.cvtColor(bgr, cv2_mod.COLOR_BGR2BGRA)) if np_mod is not None else cv2_mod.cvtColor(bgr, cv2_mod.COLOR_BGR2BGRA) if np_mod is None: import numpy as np_mod h, w, _ = bgr.shape @@ -610,7 +1091,6 @@ def set_flash_led(on, brightness=96): if val > 255: val = 255 - # Prefer direct sysfs write when permitted, else logind session D-Bus helper. try: with open(FLASH_LED_PATH, "w") as f: f.write(str(val)) @@ -673,10 +1153,107 @@ def ensure_even_frame(bgr): return bgr[:eh, :ew] -class CameraEngine: - """Thread-safe libcamera/V4L2 streaming, photo capture, and H.264 recording engine.""" +class MatroskaI420Muxer: + """Minimal streaming Matroska muxer for VFR raw I420 video frames with 1ms timescale.""" - def __init__(self, cameras, initial_index=0, on_frame=None, on_error=None, on_camera_changed=None): + def __init__(self, width, height): + self.width = int(width) + self.height = int(height) + self._header_sent = False + self._cluster_ts = None + self._last_ts = -1 + + @staticmethod + def _uint_bytes(val): + if val == 0: + return b"\x00" + out = [] + v = int(val) + while v > 0: + out.append(v & 0xFF) + v >>= 8 + return bytes(reversed(out)) + + @staticmethod + def _vint_size(n): + if n < 0x7F: + return bytes([0x80 | n]) + if n < 0x3FFF: + return bytes([0x40 | (n >> 8), n & 0xFF]) + if n < 0x1FFFFF: + return bytes([0x20 | (n >> 16), (n >> 8) & 0xFF, n & 0xFF]) + if n < 0x0FFFFFFF: + return bytes([0x10 | (n >> 24), (n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF]) + raise ValueError("EBML element too large: %d" % n) + + @classmethod + def _elem(cls, eid, data): + return eid + cls._vint_size(len(data)) + data + + def build_header(self): + ebml = self._elem( + b"\x1A\x45\xDF\xA3", + self._elem(b"\x42\x86", b"\x01") + + self._elem(b"\x42\xF7", b"\x01") + + self._elem(b"\x42\xF2", b"\x04") + + self._elem(b"\x42\xF3", b"\x08") + + self._elem(b"\x42\x82", b"matroska") + + self._elem(b"\x42\x87", b"\x04") + + self._elem(b"\x42\x85", b"\x02"), + ) + # 1ms TimecodeScale (1,000,000 ns) + info = self._elem(b"\x15\x49\xA9\x66", self._elem(b"\x2A\xD7\xB1", self._uint_bytes(1000000))) + frame_sz = self.width * self.height * 3 // 2 + bih = struct.pack( + "= 30000: + self._cluster_ts = ts + chunks.append(b"\x1F\x43\xB6\x75\x01\xFF\xFF\xFF\xFF\xFF\xFF\xFF") + chunks.append(self._elem(b"\xE7", self._uint_bytes(ts))) + + rel_ms = ts - self._cluster_ts + hdr = b"\x81" + struct.pack(">hB", rel_ms, 0x80) + block_len = len(hdr) + len(i420_bytes) + chunks.append(b"\xA3" + self._vint_size(block_len) + hdr + i420_bytes) + return b"".join(chunks) + + +class CameraEngine: + """Thread-safe libcamera/V4L2 streaming, photo capture, AF/AE, and VFR H.264 recording.""" + + def __init__(self, cameras, initial_index=0, on_frame=None, on_error=None, on_camera_changed=None, on_af_state=None): import cv2 import numpy as np @@ -689,6 +1266,7 @@ class CameraEngine: self.on_frame = on_frame self.on_error = on_error self.on_camera_changed = on_camera_changed + self.on_af_state = on_af_state self._lock = threading.Lock() self._stop_event = threading.Event() @@ -699,16 +1277,24 @@ class CameraEngine: self._raw_sc = None self._alloc = None self._requests = [] + self._mapped_fds = {} # fd -> (mmap_obj, length) self._v4l2 = None self._ae = None + self._af = None + self._saved_focus_pos = None + self._isp_state = QuadISPState() self._started = False self._reuse_arg = None self._tone_lut = _build_tone_lut(np) + self._frames_since_open = 0 + self._initial_af_done = False self._latest_bgr = None + self._latest_ts_ns = 0 self._latest_seq = 0 self._want_switch = None - self._still_request = None + self._want_focus = None + self._still_request = None # (dst_path, burst_count) self._still_done = threading.Event() self._still_result = (None, None) @@ -719,6 +1305,8 @@ class CameraEngine: self._rec_path = None self._rec_start_mono = 0.0 self._rec_frames = 0 + self._rec_dropped = 0 + self._rec_duration_ms = 0 self._rec_size = None @property @@ -727,6 +1315,10 @@ class CameraEngine: return self.cameras[self.active_index] return None + def has_af(self): + with self._lock: + return self._af is not None + def latest_frame(self): with self._lock: return self._latest_bgr, self._latest_seq @@ -765,12 +1357,17 @@ class CameraEngine: set_flash_led(False) with self._lock: self._want_switch = target + self._saved_focus_pos = None def cycle_camera(self): if len(self.cameras) <= 1: return self.switch_camera((self.active_index + 1) % len(self.cameras)) + def trigger_focus(self, nx=0.5, ny=0.5): + with self._lock: + self._want_focus = (float(nx), float(ny)) + def _requeue(self, req): if self._reuse_arg is not None: try: @@ -782,7 +1379,41 @@ class CameraEngine: req.reuse() self._cam.queue_request(req) + def _dma_sync(self, fd, flags): + try: + fcntl.ioctl(fd, DMA_BUF_IOCTL_SYNC, struct.pack(" 0: + return ts + except Exception: + pass + try: + ts = req.metadata.get(self.libcamera.controls.SensorTimestamp) + if ts and int(ts) > 0: + return int(ts) + except Exception: + pass + return time.monotonic_ns() + + def _read_libcamera_frame(self, cam_info, high_quality=False, target_size=(1152, 864), unpack_only_bgr16=False): ready = self.cm.get_ready_requests() if not ready: - return None + return None, None + # Requeue older queued requests immediately without wasting CPU debayering stale frames. + for stale in ready[:-1]: + self._requeue(stale) + + req = ready[-1] frame = None + ts_ns = None latest_stats = None - for req in ready: + + try: if req.status == self.libcamera.Request.Status.Complete: if self._raw_sc is not None and self._raw_sc.stream in req.buffers: buf = req.buffers[self._raw_sc.stream] @@ -959,22 +1652,39 @@ class CameraEngine: h = self._raw_sc.size.height stride = self._raw_sc.stride fmt = str(self._raw_sc.pixel_format) + ts_ns = self._extract_req_ts_ns(req, buf) if "CSI2P" in fmt.upper(): - with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm: - frame, latest_stats = debayer_quad_csi2p( + mm = self._get_mmap(plane) + self._dma_sync(plane.fd, DMA_BUF_SYNC_START_READ) + try: + bgr16 = quad_raw_to_bgr16( mm, w, h, stride, - rot=cam_info.rotation, offset=plane.offset, target_size=target_size, high_quality=high_quality, - tone_lut=self._tone_lut, - return_stats=True, cv2_mod=self.cv2, np_mod=self.np, ) + finally: + self._dma_sync(plane.fd, DMA_BUF_SYNC_END_READ) + # Return hardware buffer before finishing ISP/post-processing! + self._requeue(req) + req = None + if unpack_only_bgr16: + return bgr16, ts_ns + frame, latest_stats = isp_finish_bgr16( + bgr16, + rot=cam_info.rotation, + high_quality=high_quality, + tone_lut=self._tone_lut, + isp_state=None if high_quality else self._isp_state, + return_stats=True, + cv2_mod=self.cv2, + np_mod=self.np, + ) elif self._sc is not None and self._sc.stream in req.buffers: buf = req.buffers[self._sc.stream] plane = buf.planes[0] @@ -982,29 +1692,58 @@ class CameraEngine: h = self._sc.size.height stride = self._sc.stride fmt = str(self._sc.pixel_format) - with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm: - raw = mm[plane.offset:plane.offset + plane.length] - frame = convert_frame( - raw, - w, - h, - stride, - fmt, - rot=cam_info.rotation, - cv2_mod=self.cv2, - np_mod=self.np, - ) - self._requeue(req) - if latest_stats is not None and self._ae is not None: + ts_ns = self._extract_req_ts_ns(req, buf) + mm = self._get_mmap(plane) + self._dma_sync(plane.fd, DMA_BUF_SYNC_START_READ) + try: + mv = memoryview(mm)[plane.offset:plane.offset + plane.length] + frame = convert_frame( + mv, + w, + h, + stride, + fmt, + rot=cam_info.rotation, + cv2_mod=self.cv2, + np_mod=self.np, + ) + finally: + self._dma_sync(plane.fd, DMA_BUF_SYNC_END_READ) + self._requeue(req) + req = None + finally: + if req is not None: + self._requeue(req) + + if latest_stats is not None and self._ae is not None and not high_quality: try: self._ae.update(*latest_stats) except Exception: pass - return frame + return frame, ts_ns + + def _emit_af_state(self, state, roi): + if self.on_af_state: + try: + self.on_af_state(state, roi[0], roi[1]) + except Exception: + pass + + def _wait_for_libcamera_event(self, timeout=0.03): + try: + efd = self.cm.event_fd + if efd is not None and efd >= 0: + select.select([efd], [], [], timeout) + return + except Exception: + pass + time.sleep(0.008) def _run_loop(self): try: self._open_camera(self.active_camera) + if self.on_camera_changed: + self.on_camera_changed() except Exception as exc: if self.on_error: self.on_error(str(exc)) @@ -1030,81 +1769,145 @@ class CameraEngine: self.on_error("Switch failed: %s" % exc) break - # 2. Pending full-resolution still capture? - still_out = None + # 2. Pending tap-to-focus request? + focus_req = None + with self._lock: + if self._want_focus is not None: + focus_req = self._want_focus + self._want_focus = None + if focus_req is not None and self._af is not None: + self._af.trigger(*focus_req) + self._initial_af_done = True + self._emit_af_state("focusing", self._af.roi) + + # 3. Pending photo capture? + still_req = None with self._lock: if self._still_request is not None: - still_out = self._still_request + still_req = self._still_request self._still_request = None - if still_out is not None: - self._perform_still_capture(still_out) + if still_req is not None: + self._perform_still_capture(*still_req) info = self.active_camera if info is None: time.sleep(0.05) continue - # 3. Capture next live frame. + # 4. Capture next live frame. frame = None + ts_ns = None if info.backend == "v4l2": if self._v4l2 is not None: ok, f = self._v4l2.read() if ok and f is not None: frame = self.np.ascontiguousarray(f) + ts_ns = time.monotonic_ns() else: time.sleep(0.02) else: - frame = self._read_libcamera_frame(info) + frame, ts_ns = self._read_libcamera_frame(info) if frame is None: - time.sleep(0.008) + self._wait_for_libcamera_event(0.03) if frame is not None: + self._frames_since_open += 1 + if self._af is not None: + if not self._initial_af_done and self._frames_since_open >= 6 and not self.is_recording(): + self._initial_af_done = True + self._af.trigger(0.5, 0.5) + self._emit_af_state("focusing", self._af.roi) + else: + ev = self._af.step(frame, cv2_mod=self.cv2, np_mod=self.np) + if ev == "locked": + self._emit_af_state("locked", self._af.roi) + with self._lock: self._latest_bgr = frame + self._latest_ts_ns = ts_ns or time.monotonic_ns() self._latest_seq += 1 - self._push_video_frame(frame) + self._push_video_frame(frame, ts_ns) if self.on_frame: self.on_frame() finally: self.stop_video() self._close_camera() - def _perform_still_capture(self, dst_path): + def _perform_still_capture(self, dst_path, burst_count=3): info = self.active_camera try: if info.backend == "libcamera" and self._raw_sc is not None: - captured = None + isp = load_isp_lib() + want_frames = burst_count if (burst_count > 1 and isp is not None) else 1 + bgr16_list = [] deadline = time.monotonic() + 4.0 - while time.monotonic() < deadline and not self._stop_event.is_set(): - captured = self._read_libcamera_frame(info, high_quality=True, target_size=None) - if captured is not None: - break - time.sleep(0.01) - if captured is None: + while time.monotonic() < deadline and len(bgr16_list) < want_frames and not self._stop_event.is_set(): + b16, _ = self._read_libcamera_frame( + info, high_quality=True, target_size=None, unpack_only_bgr16=True + ) + if b16 is not None: + bgr16_list.append(b16) + else: + self._wait_for_libcamera_event(0.03) + if not bgr16_list: raise RuntimeError("still capture timed out") + + if len(bgr16_list) > 1 and isp is not None: + base = self.np.ascontiguousarray(bgr16_list[0], dtype=self.np.uint16) + others = [self.np.ascontiguousarray(x, dtype=self.np.uint16) for x in bgr16_list[1:]] + ptrs = (ctypes.c_void_p * len(others))(*[x.ctypes.data for x in others]) + merged = self.np.empty_like(base) + h, w = base.shape[:2] + isp.burst_merge_bgr16(base.ctypes.data, ptrs, len(others), merged.ctypes.data, int(h * w), 140.0) + else: + merged = bgr16_list[0] + + captured = isp_finish_bgr16( + merged, + rot=info.rotation, + high_quality=True, + tone_lut=self._tone_lut, + isp_state=None, + return_stats=False, + cv2_mod=self.cv2, + np_mod=self.np, + ) os.makedirs(os.path.dirname(dst_path), exist_ok=True) if not self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95]): raise RuntimeError("failed to write %s" % dst_path) self._still_result = (dst_path, None) + elif info.backend == "libcamera": + if self._af is not None: + self._saved_focus_pos = self._af.best_pos self._close_camera() self._open_camera(info, role_name="still", target_sizes=PREFERRED_STILL_SIZES) captured = None - deadline = time.monotonic() + 5.0 + deadline = time.monotonic() + 4.0 warmup = 0 + prev_luma = None + stable_cnt = 0 while time.monotonic() < deadline and not self._stop_event.is_set(): - f = self._read_libcamera_frame(info) + f, _ = self._read_libcamera_frame(info) if f is not None: captured = f warmup += 1 - if warmup >= 6: + luma = float(f[::16, ::16].mean()) + if prev_luma is not None and abs(luma - prev_luma) <= max(1.5, prev_luma * 0.02): + stable_cnt += 1 + else: + stable_cnt = 0 + prev_luma = luma + if warmup >= 16 or (warmup >= 8 and stable_cnt >= 3): break else: - time.sleep(0.01) + self._wait_for_libcamera_event(0.03) self._close_camera() - self._open_camera(info, role_name="viewfinder", target_sizes=[DEFAULT_VIEWFINDER_SIZE]) + self._open_camera(info, role_name="viewfinder", target_sizes=PREFERRED_VIEWFINDER_SIZES) if captured is None: raise RuntimeError("still capture timed out") + blur = self.cv2.GaussianBlur(captured, (0, 0), 1.0) + captured = self.cv2.addWeighted(captured, 1.12, blur, -0.12, 0) os.makedirs(os.path.dirname(dst_path), exist_ok=True) ok = self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95]) if not ok: @@ -1121,10 +1924,9 @@ class CameraEngine: self._still_result = (dst_path, None) except Exception as exc: self._still_result = (None, str(exc)) - # Recover viewfinder if still capture interrupted it. if self._cam is None and self._v4l2 is None and info is not None: try: - self._open_camera(info, role_name="viewfinder", target_sizes=[DEFAULT_VIEWFINDER_SIZE]) + self._open_camera(info, role_name="viewfinder", target_sizes=PREFERRED_VIEWFINDER_SIZES) except Exception: pass finally: @@ -1141,10 +1943,26 @@ class CameraEngine: dst_path = os.path.join(PICTURE_DIR, "IMG_%s_%d.jpg" % (stamp, suffix)) suffix += 1 + # On Quad-Bayer raw stream, HD captures instant 4.1 MP HQ without restart, Full does 3-frame burst merge. + if self._raw_sc is not None: + self._still_done.clear() + self._still_result = (None, None) + with self._lock: + self._still_request = (dst_path, 3 if high_res else 1) + if not self._still_done.wait(timeout=12.0): + raise RuntimeError("photo capture timed out") + saved, err = self._still_result + if err: + raise RuntimeError(err) + return saved + if not high_res: frame, _ = self.latest_frame() if frame is None: raise RuntimeError("camera is still warming up") + if frame.shape[0] >= 64 and frame.shape[1] >= 64: + blur = self.cv2.GaussianBlur(frame, (0, 0), 1.0) + frame = self.cv2.addWeighted(frame, 1.12, blur, -0.12, 0) os.makedirs(os.path.dirname(dst_path), exist_ok=True) if not self.cv2.imwrite(dst_path, frame, [self.cv2.IMWRITE_JPEG_QUALITY, 95]): raise RuntimeError("failed to save %s" % dst_path) @@ -1153,7 +1971,7 @@ class CameraEngine: self._still_done.clear() self._still_result = (None, None) with self._lock: - self._still_request = dst_path + self._still_request = (dst_path, 1) if not self._still_done.wait(timeout=12.0): raise RuntimeError("high-res capture timed out") saved, err = self._still_result @@ -1162,10 +1980,12 @@ class CameraEngine: return saved def start_video(self, dst_path=None): - """Start recording H.264 MP4 from upright viewfinder frames via ffmpeg.""" + """Start recording exact-PTS VFR H.264 MP4 via Matroska I420 pipe to ffmpeg.""" if shutil.which("ffmpeg") is None: raise RuntimeError("ffmpeg is not installed") - frame, _ = self.latest_frame() + with self._lock: + frame = self._latest_bgr + init_ts_ns = self._latest_ts_ns if frame is None: raise RuntimeError("camera is still warming up") even = ensure_even_frame(frame) @@ -1182,49 +2002,85 @@ class CameraEngine: else: os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True) + if self._ae is not None: + try: + self._ae.set_video_mode(True) + except Exception: + pass + cmd = [ "ffmpeg", "-y", "-loglevel", "error", "-f", - "rawvideo", - "-pix_fmt", - "bgr24", - "-s", - "%dx%d" % (w, h), - "-r", - "20", + "matroska", "-i", "-", + "-fps_mode", + "passthrough", + "-video_track_timescale", + "1000", "-c:v", "libx264", "-preset", - "ultrafast", - "-tune", - "zerolatency", + "superfast", + "-crf", + "20", + "-bf", + "0", + "-threads", + "4", "-pix_fmt", "yuv420p", + "-color_range", + "tv", + "-colorspace", + "bt709", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", "-movflags", "+faststart", dst_path, ] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE) - q = queue.Queue(maxsize=6) + q = queue.Queue(maxsize=30) + muxer = MatroskaI420Muxer(w, h) + cv2_mod = self.cv2 def writer(): + first_ts_ns = None + last_pts_ms = 0 try: while True: item = q.get() if item is None: break + fr, ts_ns = item + ev = ensure_even_frame(fr) + fh, fw = ev.shape[:2] + if (fw, fh) != (w, h): + ev = cv2_mod.resize(ev, (w, h), interpolation=cv2_mod.INTER_AREA) + i420 = cv2_mod.cvtColor(ev, cv2_mod.COLOR_BGR2YUV_I420).tobytes() + if first_ts_ns is None: + first_ts_ns = ts_ns + pts_ms = 0 + else: + pts_ms = max(last_pts_ms + 1, int((ts_ns - first_ts_ns) // 1000000)) + last_pts_ms = pts_ms + pkt = muxer.encode_frame(i420, pts_ms) if proc.stdin is not None: - proc.stdin.write(item) + proc.stdin.write(pkt) + with self._rec_lock: + self._rec_duration_ms = last_pts_ms except Exception: pass finally: try: if proc.stdin is not None: + proc.stdin.flush() proc.stdin.close() except Exception: pass @@ -1237,42 +2093,42 @@ class CameraEngine: self._rec_path = dst_path self._rec_start_mono = time.monotonic() self._rec_frames = 0 + self._rec_dropped = 0 + self._rec_duration_ms = 0 self._rec_size = (w, h) wt.start() - self._push_video_frame(frame) + self._push_video_frame(frame, init_ts_ns or time.monotonic_ns()) return dst_path - def _push_video_frame(self, frame): + def _push_video_frame(self, frame, ts_ns=None): with self._rec_lock: q = self._rec_queue proc = self._rec_proc - target_size = self._rec_size if q is None or proc is None or proc.poll() is not None: return - even = ensure_even_frame(frame) - h, w = even.shape[:2] - if target_size and (w, h) != target_size: - even = self.cv2.resize(even, target_size) - raw = even.tobytes() + if ts_ns is None: + ts_ns = time.monotonic_ns() + item = (frame, int(ts_ns)) try: - q.put_nowait(raw) + q.put_nowait(item) with self._rec_lock: self._rec_frames += 1 except queue.Full: - # Drop oldest queued frame so live preview remains responsive. try: q.get_nowait() + with self._rec_lock: + self._rec_dropped += 1 except queue.Empty: pass try: - q.put_nowait(raw) + q.put_nowait(item) with self._rec_lock: self._rec_frames += 1 except queue.Full: pass def stop_video(self): - """Stop video recording and finalize the MP4 container cleanly.""" + """Stop video recording, drain queued frames cleanly, and finalize MP4 container.""" with self._rec_lock: proc = self._rec_proc q = self._rec_queue @@ -1286,21 +2142,27 @@ class CameraEngine: self._rec_frames = 0 self._rec_size = None + if self._ae is not None: + try: + self._ae.set_video_mode(False) + except Exception: + pass + if proc is None: return None, 0 if q is not None: + # Wait briefly for room if queue is completely full so we never drop the sentinel. try: - while not q.empty(): - try: - q.get_nowait() - except queue.Empty: - break - q.put_nowait(None) + q.put(None, timeout=1.0) except Exception: - pass + try: + q.get_nowait() + q.put_nowait(None) + except Exception: + pass if wt is not None: - wt.join(timeout=5.0) - rc = proc.wait(timeout=10.0) + wt.join(timeout=15.0) + rc = proc.wait(timeout=15.0) if rc != 0 and proc.stderr is not None: err = proc.stderr.read().decode("utf-8", "replace").strip() if err and self.on_error: @@ -1329,7 +2191,6 @@ def run_worker(cameras, initial_index): write_lock = threading.Lock() has_flash = 1 if os.path.exists(FLASH_LED_PATH) else 0 stop_flag = threading.Event() - last_sent = [0.0] def emit(line): data = (line + "\n").encode("utf-8", "replace") @@ -1352,57 +2213,93 @@ def run_worker(cameras, initial_index): )) engine_holder = [None] + preview_cond = threading.Condition() + preview_latest = [None] + + def preview_loop(): + last_sent = 0.0 + while not stop_flag.is_set(): + with preview_cond: + while preview_latest[0] is None and not stop_flag.is_set(): + preview_cond.wait(timeout=0.2) + if stop_flag.is_set(): + break + frame = preview_latest[0] + preview_latest[0] = None + + eng = engine_holder[0] + if frame is None or eng is None: + continue + + min_interval = 0.062 if eng.is_recording() else 0.040 + now = time.monotonic() + wait_s = min_interval - (now - last_sent) + if wait_s > 0.002: + time.sleep(wait_s) + last_sent = time.monotonic() + + h, w = frame.shape[:2] + max_dim = max(w, h) + if max_dim > 540: + scale = 540.0 / float(max_dim) + pw = max(2, int(round(w * scale))) + ph = max(2, int(round(h * scale))) + preview = cv2.resize(frame, (pw, ph), interpolation=cv2.INTER_AREA) + else: + pw, ph = w, h + preview = frame + + raw = bgr_to_cairo_argb32(preview, cv2_mod=cv2, np_mod=eng.np).tobytes() + hdr = ("frame %d %d %d\n" % (pw, ph, len(raw))).encode("ascii") + with write_lock: + try: + sys.stdout.buffer.write(hdr) + sys.stdout.buffer.write(raw) + sys.stdout.buffer.flush() + except (BrokenPipeError, OSError): + stop_flag.set() + break + + preview_thread = threading.Thread(target=preview_loop, name="chandra-cam-preview", daemon=True) + preview_thread.start() def on_frame(): if stop_flag.is_set(): return - now = time.monotonic() - if now - last_sent[0] < 0.045: - return eng = engine_holder[0] if eng is None: return frame, _ = eng.latest_frame() if frame is None: return - last_sent[0] = now - h, w = frame.shape[:2] - max_dim = max(w, h) - if max_dim > 640: - scale = 640.0 / float(max_dim) - pw = max(2, int(round(w * scale))) - ph = max(2, int(round(h * scale))) - preview = cv2.resize(frame, (pw, ph), interpolation=cv2.INTER_AREA) - else: - pw, ph = w, h - preview = frame - raw = bgr_to_cairo_argb32(preview, np_mod=eng.np).tobytes() - hdr = ("frame %d %d %d\n" % (pw, ph, len(raw))).encode("ascii") - with write_lock: - try: - sys.stdout.buffer.write(hdr) - sys.stdout.buffer.write(raw) - sys.stdout.buffer.flush() - except (BrokenPipeError, OSError): - stop_flag.set() + with preview_cond: + preview_latest[0] = frame + preview_cond.notify() def on_camera_changed(): eng = engine_holder[0] if eng is not None: emit_active(eng.active_camera, eng.active_index) + emit("af_caps %d" % (1 if eng.has_af() else 0)) emit("flash 0") + def on_af_state(state, nx, ny): + emit("af_state %s %.3f %.3f" % (state, nx, ny)) + engine = CameraEngine( cameras, initial_index=initial_index, on_frame=on_frame, on_error=lambda msg: emit("toast " + str(msg).replace("\n", " ")), on_camera_changed=on_camera_changed, + on_af_state=on_af_state, ) engine_holder[0] = engine def _sig_stop(*_): stop_flag.set() + with preview_cond: + preview_cond.notify_all() signal.signal(signal.SIGINT, _sig_stop) signal.signal(signal.SIGTERM, _sig_stop) @@ -1427,6 +2324,13 @@ def run_worker(cameras, initial_index): if cmd == "switch": set_flash_led(False) engine.cycle_camera() + elif cmd.startswith("focus "): + parts = cmd.split() + if len(parts) >= 3: + try: + engine.trigger_focus(float(parts[1]), float(parts[2])) + except ValueError: + pass elif cmd in ("snap", "snap_full"): high_res = cmd == "snap_full" @@ -1446,10 +2350,13 @@ def run_worker(cameras, initial_index): emit("toast " + str(exc).replace("\n", " ")) elif cmd == "rec_stop": try: + dur_ms_est = int(round(engine.recording_elapsed() * 1000.0)) p, frames = engine.stop_video() + with engine._rec_lock: + dur_ms = engine._rec_duration_ms or dur_ms_est emit("rec_state 0") if p: - emit("saved_video %d %s" % (frames, p)) + emit("saved_video %d %d %s" % (frames, dur_ms, p)) except Exception as exc: emit("rec_state 0") emit("toast " + str(exc).replace("\n", " ")) @@ -1465,7 +2372,11 @@ def run_worker(cameras, initial_index): set_flash_led(False) emit("flash 0") finally: + stop_flag.set() + with preview_cond: + preview_cond.notify_all() engine.stop() + preview_thread.join(timeout=2.0) set_flash_led(False) return 0 @@ -1512,7 +2423,6 @@ def run_self_test(cameras): engine = CameraEngine(cameras, initial_index=0) engine.start() try: - # 1. Wait for first camera frames. t0 = time.monotonic() while time.monotonic() - t0 < 5.0: f, seq = engine.latest_frame() @@ -1524,7 +2434,6 @@ def run_self_test(cameras): raise RuntimeError("no frames from initial camera %s" % cameras[0].label) print("Initial camera %s frame: shape=%s seq=%d" % (cameras[0].label, f0.shape, seq0)) - # 2. Switch to front camera if different and capture JPEG photo + 2s H.264 video. if front_idx != engine.active_index: engine.switch_camera(front_idx) t0 = time.monotonic() @@ -1556,7 +2465,6 @@ def run_self_test(cameras): raise RuntimeError("invalid captured video at %s (frames=%d)" % (final_video, nframes)) print("Saved MP4: %s (%d bytes, frames=%d)" % (final_video, os.path.getsize(final_video), nframes)) - # 3. Switch back to camera 0 to prove bidirectional switch cleanly releases qcom-camss. if len(cameras) > 1: back_target = 0 if engine.active_index != 0 else 1 _, seq_before_back = engine.latest_frame() diff --git a/camera/chandra-camera-isp.c b/camera/chandra-camera-isp.c new file mode 100644 index 0000000..5063c9d --- /dev/null +++ b/camera/chandra-camera-isp.c @@ -0,0 +1,219 @@ +#include +#include +#include + +#ifdef _OPENMP +#include +#endif + +/* Unpack 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into 4x4 supercell BGR16 (0..4092). */ +void quad_csi2p_to_bgr16_4x4( + const uint8_t *raw, + int width, + int height, + int stride, + uint16_t *out_bgr16 +) { + if (!raw || !out_bgr16 || width < 4 || height < 4 || stride <= 0) { + return; + } + const int out_w = width / 4; + const int out_h = height / 4; + +#ifdef _OPENMP +#pragma omp parallel for schedule(static) num_threads(4) if (out_h >= 64) +#endif + for (int cy = 0; cy < out_h; cy++) { + const uint8_t *r0 = raw + (size_t)(cy * 4 + 0) * (size_t)stride; + const uint8_t *r1 = raw + (size_t)(cy * 4 + 1) * (size_t)stride; + const uint8_t *r2 = raw + (size_t)(cy * 4 + 2) * (size_t)stride; + const uint8_t *r3 = raw + (size_t)(cy * 4 + 3) * (size_t)stride; + uint16_t *dst = out_bgr16 + (size_t)cy * (size_t)out_w * 3; + + for (int cx = 0; cx < out_w; cx++) { + const size_t off = (size_t)cx * 5; + const uint8_t lo0 = r0[off + 4]; + const uint8_t lo1 = r1[off + 4]; + const uint8_t lo2 = r2[off + 4]; + const uint8_t lo3 = r3[off + 4]; + + /* Rows 4y, 4y+1: (p0, p1) = R, (p2, p3) = Gr */ + uint32_t r_sum = ((uint32_t)r0[off + 0] + r0[off + 1] + r1[off + 0] + r1[off + 1]) << 2; + r_sum += (uint32_t)(lo0 & 3U) + ((lo0 >> 2) & 3U) + (lo1 & 3U) + ((lo1 >> 2) & 3U); + + uint32_t gr_sum = ((uint32_t)r0[off + 2] + r0[off + 3] + r1[off + 2] + r1[off + 3]) << 2; + gr_sum += (uint32_t)((lo0 >> 4) & 3U) + ((lo0 >> 6) & 3U) + ((lo1 >> 4) & 3U) + ((lo1 >> 6) & 3U); + + /* Rows 4y+2, 4y+3: (p0, p1) = Gb, (p2, p3) = B */ + uint32_t gb_sum = ((uint32_t)r2[off + 0] + r2[off + 1] + r3[off + 0] + r3[off + 1]) << 2; + gb_sum += (uint32_t)(lo2 & 3U) + ((lo2 >> 2) & 3U) + (lo3 & 3U) + ((lo3 >> 2) & 3U); + + uint32_t b_sum = ((uint32_t)r2[off + 2] + r2[off + 3] + r3[off + 2] + r3[off + 3]) << 2; + b_sum += (uint32_t)((lo2 >> 4) & 3U) + ((lo2 >> 6) & 3U) + ((lo3 >> 4) & 3U) + ((lo3 >> 6) & 3U); + + uint32_t g_avg = (gr_sum + gb_sum + 1U) >> 1; + + dst[0] = (uint16_t)b_sum; + dst[1] = (uint16_t)g_avg; + dst[2] = (uint16_t)r_sum; + dst += 3; + } + } +} + +/* Unpack 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into 16-bit Bayer (0..4092). */ +void quad_csi2p_to_bayer16_2x2( + const uint8_t *raw, + int width, + int height, + int stride, + uint16_t *out_bayer16 +) { + if (!raw || !out_bayer16 || width < 4 || height < 2 || stride <= 0) { + return; + } + const int nblk = width / 4; + const int out_w = nblk * 2; + const int out_h = height / 2; + +#ifdef _OPENMP +#pragma omp parallel for schedule(static) num_threads(4) if (out_h >= 64) +#endif + for (int by = 0; by < out_h; by++) { + const uint8_t *r0 = raw + (size_t)(by * 2 + 0) * (size_t)stride; + const uint8_t *r1 = raw + (size_t)(by * 2 + 1) * (size_t)stride; + uint16_t *dst = out_bayer16 + (size_t)by * (size_t)out_w; + + for (int bx = 0; bx < nblk; bx++) { + const size_t off = (size_t)bx * 5; + const uint8_t lo0 = r0[off + 4]; + const uint8_t lo1 = r1[off + 4]; + + uint32_t c0 = ((uint32_t)r0[off + 0] + r0[off + 1] + r1[off + 0] + r1[off + 1]) << 2; + c0 += (uint32_t)(lo0 & 3U) + ((lo0 >> 2) & 3U) + (lo1 & 3U) + ((lo1 >> 2) & 3U); + + uint32_t c1 = ((uint32_t)r0[off + 2] + r0[off + 3] + r1[off + 2] + r1[off + 3]) << 2; + c1 += (uint32_t)((lo0 >> 4) & 3U) + ((lo0 >> 6) & 3U) + ((lo1 >> 4) & 3U) + ((lo1 >> 6) & 3U); + + dst[0] = (uint16_t)c0; + dst[1] = (uint16_t)c1; + dst += 2; + } + } +} + +/* Fused black-level subtraction, AWB + exposure scaling, 3x3 linear RGB CCM, and LUT tone-map. */ +void isp_ccm_tone_bgr16_to_bgr8( + const uint16_t *in_bgr16, + uint8_t *out_bgr8, + int pixels, + float black, + float scale_norm, + float gain_b, + float gain_g, + float gain_r, + const float ccm_rgb[9], + const uint8_t lut[4096], + float lut_max +) { + if (!in_bgr16 || !out_bgr8 || !ccm_rgb || !lut || pixels <= 0) { + return; + } + const float m00 = ccm_rgb[0], m01 = ccm_rgb[1], m02 = ccm_rgb[2]; + const float m10 = ccm_rgb[3], m11 = ccm_rgb[4], m12 = ccm_rgb[5]; + const float m20 = ccm_rgb[6], m21 = ccm_rgb[7], m22 = ccm_rgb[8]; + const float sb = scale_norm * gain_b; + const float sg = scale_norm * gain_g; + const float sr = scale_norm * gain_r; + const float inv_lut = 4095.0f / (lut_max > 1e-6f ? lut_max : 1.0f); + +#ifdef _OPENMP +#pragma omp parallel for schedule(static) num_threads(4) if (pixels >= 16384) +#endif + for (int i = 0; i < pixels; i++) { + const size_t idx = (size_t)i * 3; + float b = (float)in_bgr16[idx + 0] - black; + float g = (float)in_bgr16[idx + 1] - black; + float r = (float)in_bgr16[idx + 2] - black; + if (b < 0.0f) b = 0.0f; + if (g < 0.0f) g = 0.0f; + if (r < 0.0f) r = 0.0f; + + b *= sb; + g *= sg; + r *= sr; + + float rc = m00 * r + m01 * g + m02 * b; + float gc = m10 * r + m11 * g + m12 * b; + float bc = m20 * r + m21 * g + m22 * b; + + int ir = (int)(rc * inv_lut + 0.5f); + int ig = (int)(gc * inv_lut + 0.5f); + int ib = (int)(bc * inv_lut + 0.5f); + if (ir < 0) ir = 0; else if (ir > 4095) ir = 4095; + if (ig < 0) ig = 0; else if (ig > 4095) ig = 4095; + if (ib < 0) ib = 0; else if (ib > 4095) ib = 4095; + + out_bgr8[idx + 0] = lut[ib]; + out_bgr8[idx + 1] = lut[ig]; + out_bgr8[idx + 2] = lut[ir]; + } +} + +/* Motion-guarded multi-frame temporal merge in linear 16-bit BGR space. */ +void burst_merge_bgr16( + const uint16_t *base, + const uint16_t *const *others, + int num_others, + uint16_t *out, + int pixels, + float noise_thresh +) { + if (!base || !out || pixels <= 0) { + return; + } + const float inv_nt = 1.0f / (noise_thresh > 1.0f ? noise_thresh : 1.0f); + +#ifdef _OPENMP +#pragma omp parallel for schedule(static) num_threads(4) if (pixels >= 16384) +#endif + for (int i = 0; i < pixels; i++) { + const size_t idx = (size_t)i * 3; + const float b0 = (float)base[idx + 0]; + const float g0 = (float)base[idx + 1]; + const float r0 = (float)base[idx + 2]; + const float l0 = 0.114f * b0 + 0.587f * g0 + 0.299f * r0; + + float acc_b = b0; + float acc_g = g0; + float acc_r = r0; + float w_sum = 1.0f; + + for (int k = 0; k < num_others; k++) { + const uint16_t *oth = others[k]; + if (!oth) continue; + const float bk = (float)oth[idx + 0]; + const float gk = (float)oth[idx + 1]; + const float rk = (float)oth[idx + 2]; + const float lk = 0.114f * bk + 0.587f * gk + 0.299f * rk; + const float d = fabsf(lk - l0) * inv_nt; + const float d2 = d * d; + const float w = 1.0f / (1.0f + d2 * d2); + acc_b += w * bk; + acc_g += w * gk; + acc_r += w * rk; + w_sum += w; + } + + const float inv_w = 1.0f / w_sum; + int ob = (int)(acc_b * inv_w + 0.5f); + int og = (int)(acc_g * inv_w + 0.5f); + int or_v = (int)(acc_r * inv_w + 0.5f); + if (ob < 0) ob = 0; else if (ob > 65535) ob = 65535; + if (og < 0) og = 0; else if (og > 65535) og = 65535; + if (or_v < 0) or_v = 0; else if (or_v > 65535) or_v = 65535; + out[idx + 0] = (uint16_t)ob; + out[idx + 1] = (uint16_t)og; + out[idx + 2] = (uint16_t)or_v; + } +} diff --git a/camera/chandra-camera-ui.c b/camera/chandra-camera-ui.c index bb4ef42..0213edd 100644 --- a/camera/chandra-camera-ui.c +++ b/camera/chandra-camera-ui.c @@ -63,19 +63,36 @@ typedef struct { /* Shared latest frame from worker (CAIRO_FORMAT_RGB24 BGRA32) */ GMutex frame_mutex; uint8_t *frame_buf; + size_t frame_cap; int frame_w; int frame_h; size_t frame_len; uint64_t frame_seq; gboolean draw_pending; - /* Paint copy owned exclusively by GTK main thread */ + /* Paint & reader buffers swapped under frame_mutex (zero per-frame alloc/memcpy) */ uint8_t *paint_buf; + size_t paint_cap; int paint_w; int paint_h; size_t paint_len; uint64_t paint_seq; + uint8_t *read_buf; + size_t read_cap; + + /* Viewfinder draw rect & tap-to-focus reticle */ + double view_rx; + double view_ry; + double view_rw; + double view_rh; + gboolean has_af; + gboolean af_active; + gboolean af_locked; + double af_nx; + double af_ny; + int64_t af_until_us; + /* Camera & UI state */ int cam_count; gboolean has_flash; @@ -366,18 +383,19 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) { cairo_set_source_rgb(cr, 0.043, 0.051, 0.078); cairo_paint(cr); - /* Copy latest frame buffer without holding frame_mutex during Cairo paint. */ + /* Swap latest frame pointer without holding frame_mutex during Cairo paint. */ g_mutex_lock(&app->frame_mutex); if (app->frame_buf && app->frame_seq != app->paint_seq) { - uint8_t *nb = (uint8_t *)realloc(app->paint_buf, app->frame_len); - if (nb) { - app->paint_buf = nb; - memcpy(app->paint_buf, app->frame_buf, app->frame_len); - app->paint_w = app->frame_w; - app->paint_h = app->frame_h; - app->paint_len = app->frame_len; - app->paint_seq = app->frame_seq; - } + uint8_t *tmp_buf = app->paint_buf; + size_t tmp_cap = app->paint_cap; + app->paint_buf = app->frame_buf; + app->paint_cap = app->frame_cap; + app->paint_w = app->frame_w; + app->paint_h = app->frame_h; + app->paint_len = app->frame_len; + app->paint_seq = app->frame_seq; + app->frame_buf = tmp_buf; + app->frame_cap = tmp_cap; } g_mutex_unlock(&app->frame_mutex); @@ -399,6 +417,10 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) { ry = y; rw = dw; rh = dh; + app->view_rx = rx; + app->view_ry = ry; + app->view_rw = rw; + app->view_rh = rh; cairo_surface_t *surf = cairo_image_surface_create_for_data( app->paint_buf, CAIRO_FORMAT_RGB24, iw, ih, iw * 4); @@ -441,6 +463,20 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) { cairo_stroke(cr); } + if (app->af_active && g_get_monotonic_time() <= app->af_until_us) { + double fx = rx + app->af_nx * rw; + double fy = ry + app->af_ny * rh; + double sz = app->af_locked ? 46.0 : 54.0; + rounded_rect_path(cr, fx - sz / 2.0, fy - sz / 2.0, sz, sz, 10.0); + if (app->af_locked) { + cairo_set_source_rgba(cr, 0.20, 0.83, 0.60, 0.92); + } else { + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.88); + } + cairo_set_line_width(cr, 2.0); + cairo_stroke(cr); + } + if (app->countdown_left > 0) { char buf[16]; snprintf(buf, sizeof(buf), "%d", app->countdown_left); @@ -685,6 +721,27 @@ static gboolean handle_worker_line_idle(gpointer data) { gtk_label_set_text(GTK_LABEL(app->rec_label), "● 00:00"); } sync_ui_labels(app); + } else if (strncmp(line, "af_caps ", 8) == 0) { + app->has_af = (atoi(line + 8) != 0); + if (!app->has_af) { + app->af_active = FALSE; + gtk_widget_queue_draw(app->view_area); + } + } else if (strncmp(line, "af_state ", 9) == 0) { + char st[32] = ""; + double nx = 0.5, ny = 0.5; + if (sscanf(line + 9, "%31s %lf %lf", st, &nx, &ny) >= 1) { + if (strcmp(st, "idle") == 0) { + app->af_active = FALSE; + } else { + app->af_nx = fmax(0.05, fmin(0.95, nx)); + app->af_ny = fmax(0.05, fmin(0.95, ny)); + app->af_locked = (strcmp(st, "locked") == 0); + app->af_active = TRUE; + app->af_until_us = g_get_monotonic_time() + (app->af_locked ? 1200000LL : 4000000LL); + } + gtk_widget_queue_draw(app->view_area); + } } else if (strncmp(line, "saved_photo ", 12) == 0) { gchar *base = g_path_get_basename(line + 12); gchar *msg = g_strdup_printf("Saved %s", base); @@ -694,15 +751,41 @@ static gboolean handle_worker_line_idle(gpointer data) { refresh_thumbnail(app); } else if (strncmp(line, "saved_video ", 12) == 0) { int frames = 0; + int dur_ms = 0; const char *p = line + 12; const char *sp = strchr(p, ' '); if (sp) { frames = atoi(p); - gchar *base = g_path_get_basename(sp + 1); - gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames); - show_toast(app, msg, 2.8); - g_free(base); - g_free(msg); + const char *rest = sp + 1; + const char *sp2 = strchr(rest, ' '); + gboolean has_dur = FALSE; + if (sp2 && isdigit((unsigned char)rest[0])) { + has_dur = TRUE; + for (const char *c = rest; c < sp2; c++) { + if (!isdigit((unsigned char)*c)) { + has_dur = FALSE; + break; + } + } + } + if (has_dur) { + dur_ms = atoi(rest); + gchar *base = g_path_get_basename(sp2 + 1); + double secs = dur_ms > 0 ? (dur_ms / 1000.0) : 0.0; + double fps = (secs > 0.05 && frames > 0) ? (frames / secs) : 0.0; + gchar *msg = (fps > 0.5) + ? g_strdup_printf("Saved %s (%.1fs · %.0f fps)", base, secs, fps) + : g_strdup_printf("Saved %s (%d frames)", base, frames); + show_toast(app, msg, 2.8); + g_free(base); + g_free(msg); + } else { + gchar *base = g_path_get_basename(rest); + gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames); + show_toast(app, msg, 2.8); + g_free(base); + g_free(msg); + } } } else if (strncmp(line, "toast ", 6) == 0) { show_toast(app, line + 6, 3.0); @@ -723,25 +806,32 @@ static gpointer worker_reader_func(gpointer data) { if (sscanf(line + 6, "%d %d %lu", &w, &h, &len) == 3 && w > 0 && h > 0 && len == (unsigned long)w * (unsigned long)h * 4UL && len <= 16UL * 1024UL * 1024UL) { - uint8_t *buf = (uint8_t *)malloc((size_t)len); - if (!buf) break; + if ((size_t)len > app->read_cap) { + uint8_t *nb = (uint8_t *)realloc(app->read_buf, (size_t)len); + if (!nb) break; + app->read_buf = nb; + app->read_cap = (size_t)len; + } size_t got = 0; while (got < (size_t)len) { - size_t n = fread(buf + got, 1, (size_t)len - got, app->from_worker); + size_t n = fread(app->read_buf + got, 1, (size_t)len - got, app->from_worker); if (n == 0) break; got += n; } if (got != (size_t)len) { - free(buf); break; } g_mutex_lock(&app->frame_mutex); - free(app->frame_buf); - app->frame_buf = buf; + uint8_t *tmp_buf = app->frame_buf; + size_t tmp_cap = app->frame_cap; + app->frame_buf = app->read_buf; + app->frame_cap = app->read_cap; app->frame_w = w; app->frame_h = h; app->frame_len = (size_t)len; app->frame_seq++; + app->read_buf = tmp_buf; + app->read_cap = tmp_cap; gboolean need_schedule = !app->draw_pending; if (need_schedule) app->draw_pending = TRUE; g_mutex_unlock(&app->frame_mutex); @@ -774,6 +864,10 @@ static gboolean tick_ui(gpointer data) { app->toast_text = NULL; dirty = TRUE; } + if (app->af_active && now > app->af_until_us) { + app->af_active = FALSE; + dirty = TRUE; + } if (app->is_recording) { int secs = (int)((now - app->rec_start_us) / 1000000LL); if (secs < 0) secs = 0; @@ -1100,10 +1194,38 @@ static gboolean start_worker_process(CameraApp *app) { if (!app->to_worker || !app->from_worker) { return FALSE; } + setvbuf(app->from_worker, NULL, _IOFBF, 256 * 1024); app->reader_thread = g_thread_new("cam-reader", worker_reader_func, app); return TRUE; } +static gboolean on_view_button_press(GtkWidget *w, GdkEventButton *ev, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + if (ev->type != GDK_BUTTON_PRESS || ev->button != 1) return FALSE; + if (!app->has_af || app->view_rw <= 20.0 || app->view_rh <= 20.0) return FALSE; + if (ev->x < app->view_rx || ev->x > app->view_rx + app->view_rw || + ev->y < app->view_ry || ev->y > app->view_ry + app->view_rh) { + return FALSE; + } + double nx = (ev->x - app->view_rx) / app->view_rw; + double ny = (ev->y - app->view_ry) / app->view_rh; + if (app->active_is_front) nx = 1.0 - nx; + nx = fmax(0.1, fmin(0.9, nx)); + ny = fmax(0.1, fmin(0.9, ny)); + + char cmd[64]; + snprintf(cmd, sizeof(cmd), "focus %.3f %.3f", nx, ny); + send_worker(app, cmd); + app->af_nx = app->active_is_front ? (1.0 - nx) : nx; + app->af_ny = ny; + app->af_locked = FALSE; + app->af_active = TRUE; + app->af_until_us = g_get_monotonic_time() + 4000000LL; + gtk_widget_queue_draw(app->view_area); + return TRUE; +} + static void build_ui(CameraApp *app) { GtkSettings *settings = gtk_settings_get_default(); if (settings) { @@ -1165,7 +1287,9 @@ static void build_ui(CameraApp *app) { app->view_area = gtk_drawing_area_new(); gtk_widget_set_hexpand(app->view_area, TRUE); gtk_widget_set_vexpand(app->view_area, TRUE); + gtk_widget_add_events(app->view_area, GDK_BUTTON_PRESS_MASK); g_signal_connect(app->view_area, "draw", G_CALLBACK(draw_viewfinder), app); + g_signal_connect(app->view_area, "button-press-event", G_CALLBACK(on_view_button_press), app); gtk_container_add(GTK_CONTAINER(overlay), app->view_area); GtkWidget *top_bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8); @@ -1409,6 +1533,7 @@ int main(int argc, char **argv) { free(app.frame_buf); free(app.paint_buf); + free(app.read_buf); g_free(app.worker_exe); g_free(app.initial_camera); g_free(app.active_label); diff --git a/camera/ipa/simple/imx376.yaml b/camera/ipa/simple/imx376.yaml new file mode 100644 index 0000000..31755c3 --- /dev/null +++ b/camera/ipa/simple/imx376.yaml @@ -0,0 +1,24 @@ +# SPDX-License-Identifier: CC0-1.0 +%YAML 1.1 +--- +version: 1 +algorithms: + - BlackLevel: + - Awb: + - Ccm: + ccms: + - ct: 3000 + ccm: [ 1.38, -0.22, -0.16, + -0.28, 1.42, -0.14, + -0.03, -0.56, 1.59 ] + - ct: 4500 + ccm: [ 1.40, -0.24, -0.16, + -0.24, 1.44, -0.20, + -0.03, -0.46, 1.49 ] + - ct: 6500 + ccm: [ 1.44, -0.28, -0.16, + -0.21, 1.43, -0.22, + -0.05, -0.42, 1.47 ] + - Adjust: + - Agc: +... diff --git a/camera/ipa/simple/imx519.yaml b/camera/ipa/simple/imx519.yaml new file mode 100644 index 0000000..ffabf13 --- /dev/null +++ b/camera/ipa/simple/imx519.yaml @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: CC0-1.0 +%YAML 1.1 +--- +version: 1 +algorithms: + - BlackLevel: + - Awb: + - Ccm: + ccms: + - ct: 2890 + ccm: [ 1.36754, -0.18448, -0.18306, + -0.32356, 1.44826, -0.12471, + -0.00412, -0.69936, 1.70348 ] + - ct: 3550 + ccm: [ 1.42836, -0.27235, -0.15601, + -0.28751, 1.41075, -0.12325, + -0.01812, -0.54849, 1.56661 ] + - ct: 4500 + ccm: [ 1.36328, -0.19569, -0.16759, + -0.25254, 1.52248, -0.26994, + -0.01575, -0.53155, 1.54729 ] + - ct: 5700 + ccm: [ 1.49207, -0.37245, -0.11963, + -0.21493, 1.40005, -0.18512, + -0.03781, -0.38779, 1.42561 ] + - ct: 7900 + ccm: [ 1.34849, -0.05425, -0.29424, + -0.22182, 1.77684, -0.55502, + -0.07403, -0.55336, 1.62739 ] + - Adjust: + - Agc: +... diff --git a/camera/ipa/simple/uncalibrated.yaml b/camera/ipa/simple/uncalibrated.yaml new file mode 100644 index 0000000..99b05a2 --- /dev/null +++ b/camera/ipa/simple/uncalibrated.yaml @@ -0,0 +1,10 @@ +# SPDX-License-Identifier: CC0-1.0 +%YAML 1.1 +--- +version: 1 +algorithms: + - BlackLevel: + - Awb: + - Adjust: + - Agc: +... diff --git a/camera/test_camera.py b/camera/test_camera.py index cf41b62..bf8ebef 100644 --- a/camera/test_camera.py +++ b/camera/test_camera.py @@ -1,10 +1,15 @@ #!/usr/bin/env python3 -"""Host-side unit tests for chandra-camera frame/camera helpers (no hardware required).""" +"""Host-side unit tests for chandra-camera frame/camera/AE/AF/VFR-mux helpers (no hardware required).""" +import ctypes import importlib.machinery import importlib.util +import json import os +import shutil +import subprocess import sys +import tempfile import unittest try: @@ -24,6 +29,65 @@ sys.modules["chandra_camera_mod"] = cam_mod _loader.exec_module(cam_mod) +class _FakeSubdevIO: + """In-memory mock for _V4L2SubdevIO supporting query/get/set/close.""" + + def __init__(self, ctrls): + # ctrls: cid -> (mn, mx, step, df, val) + self.ctrls = {k: list(v) for k, v in ctrls.items()} + self.history = [] + self.closed = False + + def query(self, cid): + if cid not in self.ctrls: + raise OSError("unsupported ctrl 0x%x" % cid) + mn, mx, step, df, _ = self.ctrls[cid] + return mn, mx, step, df + + def get(self, cid): + if cid not in self.ctrls: + raise OSError("unsupported ctrl 0x%x" % cid) + return self.ctrls[cid][4] + + def set(self, cid, val): + if cid not in self.ctrls: + raise OSError("unsupported ctrl 0x%x" % cid) + mn, mx, _step, _df, _ = self.ctrls[cid] + v = max(mn, min(int(val), mx)) + self.ctrls[cid][4] = v + self.history.append((cid, v)) + return v + + def close(self): + self.closed = True + + +def _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96): + """Build a 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB frame preserving all 10 bits.""" + stride = (w // 4) * 5 + arr = np.zeros((h, stride), dtype=np.uint8) + + def pack4(p0, p1, p2, p3): + b0 = (p0 >> 2) & 0xFF + b1 = (p1 >> 2) & 0xFF + b2 = (p2 >> 2) & 0xFF + b3 = (p3 >> 2) & 0xFF + b4 = (p0 & 3) | ((p1 & 3) << 2) | ((p2 & 3) << 4) | ((p3 & 3) << 6) + return b0, b1, b2, b3, b4 + + for y in range(h): + top = y < (h // 2) + for x_blk in range(w // 4): + if (y % 4) < 2: + c0 = top_val if top else bg_val # R + c1 = bg_val # Gr + else: + c0 = bg_val # Gb + c1 = bg_val if top else bot_val # B + arr[y, x_blk * 5:x_blk * 5 + 5] = pack4(c0, c0, c1, c1) + return arr.tobytes(), stride + + class TestCameraHelpers(unittest.TestCase): def test_sort_and_label_cameras(self): raw = [ @@ -41,12 +105,9 @@ class TestCameraHelpers(unittest.TestCase): @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) @@ -56,24 +117,20 @@ class TestCameraHelpers(unittest.TestCase): 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)) - # Libcamera Rotation=90 (CCW mounting) rotates CCW: (row=0, col=0) -> (row=w-1=1, col=0) self.assertEqual(tuple(bgr90[1, 0]), (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)) - # Libcamera Rotation=270 rotates CW: (row=0, col=0) -> (row=0, col=h-1=2) self.assertEqual(tuple(bgr270[0, 2]), (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)) @@ -89,41 +146,189 @@ class TestCameraHelpers(unittest.TestCase): @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") def test_debayer_quad_csi2p(self): - # Construct an 8x8 CSI-2 10-bit packed 4x4 Quad-Bayer SRGGB image: - # Top half (rows 0..3): strong red (R=200, G=24, B=24) - # Bottom half (rows 4..7): strong blue (R=24, G=24, B=200) - w, h, stride = 8, 8, 10 - arr = np.zeros((h, stride), dtype=np.uint8) - for y in range(h): - top = y < 4 - for x_blk in range(2): # 4 pixels per block, 5 bytes per block - # Row phase inside 4x4 Quad-Bayer: y%4 in {0,1} -> R,R,G,G; {2,3} -> G,G,B,B - if (y % 4) < 2: - c0 = 200 if top else 24 # R - c1 = 24 # G - else: - c0 = 24 # G - c1 = 24 if top else 200 # B - base = x_blk * 5 - arr[y, base + 0] = c0 - arr[y, base + 1] = c0 - arr[y, base + 2] = c1 - arr[y, base + 3] = c1 - arr[y, base + 4] = 0 - raw = arr.tobytes() - + raw, stride = _make_quad_csi2p_image(w=8, h=8, top_val=800, bot_val=800, bg_val=96) out_live = cam_mod.debayer_quad_csi2p( - raw, w, h, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np + raw, 8, 8, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np ) out_hq = cam_mod.debayer_quad_csi2p( - raw, w, h, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np + raw, 8, 8, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np ) - self.assertEqual(out_live.shape, (4, 4, 3)) # 8x8 -> 4x4, rot=90 keeps 4x4 - self.assertEqual(out_hq.shape, (4, 6, 3)) # resized to WxH = 6x4 - # Top row in rot=0 should have R > B; bottom row should have B > R. + self.assertEqual(out_live.shape, (4, 4, 3)) + self.assertEqual(out_hq.shape, (4, 6, 3)) self.assertGreater(float(out_hq[0, :, 2].mean()), float(out_hq[0, :, 0].mean()) + 30.0) self.assertGreater(float(out_hq[3, :, 0].mean()), float(out_hq[3, :, 2].mean()) + 30.0) + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_c_isp_vs_numpy_fallback_and_10bit_lsbs(self): + lib = cam_mod.load_isp_lib() + self.assertIsNotNone(lib, "expected compiled build/libchandra-camera-isp.so") + + raw_a, stride = _make_quad_csi2p_image(w=16, h=16, top_val=803, bot_val=803, bg_val=99) + raw_b, _ = _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96) + + # Verify 10-bit LSBs change raw_a vs raw_b in C 4x4 unpacking. + arr_a = np.frombuffer(raw_a, dtype=np.uint8).reshape((16, stride)) + arr_b = np.frombuffer(raw_b, dtype=np.uint8).reshape((16, stride)) + out_a = np.empty((4, 4, 3), dtype=np.uint16) + out_b = np.empty((4, 4, 3), dtype=np.uint16) + lib.quad_csi2p_to_bgr16_4x4(arr_a.ctypes.data, 16, 16, stride, out_a.ctypes.data) + lib.quad_csi2p_to_bgr16_4x4(arr_b.ctypes.data, 16, 16, stride, out_b.ctypes.data) + self.assertEqual(int(out_a[0, 0, 2]) - int(out_b[0, 0, 2]), 12) # 4 pixels * 3 LSB = 12 + + # Compare full C ISP vs NumPy fallback on both 4x4 live and 2x2 HQ paths. + c_live = cam_mod.debayer_quad_csi2p( + raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np + ) + c_hq = cam_mod.debayer_quad_csi2p( + raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np + ) + saved_lib, saved_tried = cam_mod._ISP_LIB, cam_mod._ISP_LIB_TRIED + try: + cam_mod._ISP_LIB = None + cam_mod._ISP_LIB_TRIED = True + np_live = cam_mod.debayer_quad_csi2p( + raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np + ) + np_hq = cam_mod.debayer_quad_csi2p( + raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np + ) + finally: + cam_mod._ISP_LIB = saved_lib + cam_mod._ISP_LIB_TRIED = saved_tried + + self.assertEqual(c_live.shape, (4, 4, 3)) + self.assertEqual(c_hq.shape, (8, 8, 3)) + self.assertLessEqual(int(np.abs(c_live.astype(np.int32) - np_live.astype(np.int32)).max()), 1) + self.assertLessEqual(int(np.abs(c_hq.astype(np.int32) - np_hq.astype(np.int32)).max()), 1) + + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_burst_merge_bgr16(self): + lib = cam_mod.load_isp_lib() + self.assertIsNotNone(lib) + rng = np.random.default_rng(42) + h, w = 32, 32 + base_clean = np.full((h, w, 3), 1000, dtype=np.int32) + frames = [] + for _ in range(4): + noise = rng.normal(0.0, 25.0, size=(h, w, 3)) + f = np.clip(base_clean + noise, 0, 4092).astype(np.uint16) + frames.append(np.ascontiguousarray(f)) + # Inject strong motion artifact in frame 2 on top-left 8x8 block. + frames[2][:8, :8, :] = 3500 + + base = frames[0] + others = frames[1:] + ptrs = (ctypes.c_void_p * len(others))(*[x.ctypes.data for x in others]) + out = np.empty_like(base) + lib.burst_merge_bgr16(base.ctypes.data, ptrs, len(others), out.ctypes.data, int(h * w), 120.0) + + static_std_before = float(base[12:, 12:, :].std()) + static_std_after = float(out[12:, 12:, :].std()) + self.assertLess(static_std_after, static_std_before * 0.7) + # Moving patch from frame 2 must not ghost into merged static base. + self.assertLess(float(out[:8, :8, :].mean()), 1200.0) + + def test_quad_sensor_ae_gain_priority_and_video_mode(self): + io = _FakeSubdevIO({ + cam_mod.V4L2_CID_VBLANK: (56, 62029, 1, 56, 56), + cam_mod.V4L2_CID_EXPOSURE: (4, 3542, 1, 1000, 1000), + cam_mod.V4L2_CID_ANALOGUE_GAIN: (0, 480, 1, 0, 0), + cam_mod.V4L2_CID_DIGITAL_GAIN: (0, 4096, 1, 1024, 1024), + }) + ae = cam_mod.QuadSensorAE("/dev/null", io=io) + # Mid-high EV (e.g. 10x base exposure): should stay at vb_min and raise analogue gain up to 16x first. + vb, exp, ag, dg = ae.plan(3542.0 * 10.0) + self.assertEqual(vb, 56) + self.assertEqual(exp, 3542) + self.assertGreater(ag, 400) + self.assertEqual(dg, 1024) + + # Very low light: photo mode extends vblank up to vb_cap_photo, video mode tightens to vb_cap_video. + vb_photo, _, _, _ = ae.plan(ae.e_max) + self.assertEqual(vb_photo, ae.vb_cap_photo) + ae.cur_vblank = vb_photo + ae.ev_total = ae.e_max + ae.set_video_mode(True) + self.assertLessEqual(ae.cur_vblank, ae.vb_cap_video) + + ae.close() + self.assertTrue(io.closed) + self.assertEqual(io.get(cam_mod.V4L2_CID_VBLANK), 56) + self.assertEqual(io.get(cam_mod.V4L2_CID_EXPOSURE), 1000) + self.assertEqual(io.get(cam_mod.V4L2_CID_ANALOGUE_GAIN), 0) + self.assertEqual(io.get(cam_mod.V4L2_CID_DIGITAL_GAIN), 1024) + + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_contrast_af_sweep_finds_sharp_peak(self): + io = _FakeSubdevIO({ + cam_mod.V4L2_CID_FOCUS_ABSOLUTE: (0, 1023, 1, 0, 120), + }) + af = cam_mod.ContrastAF("/dev/null", io=io) + + # Build crisp high-contrast checkerboard target. + sharp_img = np.zeros((160, 160, 3), dtype=np.uint8) + for y in range(0, 160, 8): + for x in range(0, 160, 8): + if ((x // 8) + (y // 8)) % 2 == 0: + sharp_img[y:y + 8, x:x + 8] = 220 + + af.trigger(0.5, 0.5) + steps = 0 + while af.state != "locked" and steps < 100: + dist = abs(af.cur_pos - 600) + sigma = 0.2 + dist / 90.0 + if sigma > 0.6: + frame = cv2.GaussianBlur(sharp_img, (0, 0), sigma) + else: + frame = sharp_img.copy() + af.step(frame, cv2_mod=cv2, np_mod=np) + steps += 1 + + self.assertEqual(af.state, "locked") + self.assertLess(abs(af.best_pos - 600), 60) + af.close() + self.assertTrue(io.closed) + self.assertEqual(io.get(cam_mod.V4L2_CID_FOCUS_ABSOLUTE), 120) + + @unittest.skipUnless(HAS_CV2_NUMPY and shutil.which("ffmpeg") and shutil.which("ffprobe"), "requires cv2, numpy, ffmpeg, ffprobe") + def test_matroska_i420_muxer_vfr_and_cluster_rollover(self): + w, h = 64, 48 + muxer = cam_mod.MatroskaI420Muxer(w, h) + timestamps = [0, 33, 67, 100, 145, 200, 31000, 31040] + bgr = np.full((h, w, 3), 120, dtype=np.uint8) + i420 = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV_I420).tobytes() + + with tempfile.TemporaryDirectory() as td: + out_mp4 = os.path.join(td, "vfr.mp4") + cmd = [ + "ffmpeg", "-y", "-loglevel", "error", + "-f", "matroska", "-i", "-", + "-fps_mode", "passthrough", + "-video_track_timescale", "1000", + "-c:v", "libx264", "-preset", "superfast", "-crf", "22", "-bf", "0", + "-pix_fmt", "yuv420p", + "-movflags", "+faststart", out_mp4, + ] + proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE) + for ts in timestamps: + proc.stdin.write(muxer.encode_frame(i420, ts)) + proc.stdin.close() + rc = proc.wait(timeout=15) + err = proc.stderr.read().decode("utf-8", "replace") + self.assertEqual(rc, 0, msg="ffmpeg failed: " + err) + + info = json.loads(subprocess.check_output([ + "ffprobe", "-v", "error", "-show_streams", "-show_frames", "-of", "json", out_mp4 + ], text=True)) + stream = info["streams"][0] + frames = info["frames"] + self.assertEqual(stream["codec_name"], "h264") + self.assertEqual(stream["pix_fmt"], "yuv420p") + self.assertEqual(len(frames), len(timestamps)) + pts_ms = [round(float(f["pts_time"]) * 1000.0) for f in frames] + self.assertAlmostEqual(pts_ms[-1], 31040.0, delta=5.0) + self.assertAlmostEqual(pts_ms[4], 145.0, delta=5.0) + if __name__ == "__main__": unittest.main() diff --git a/components/network/gen/interface/chandra/desktop/plasmoid/stub.mbt b/components/network/gen/interface/chandra/desktop/plasmoid/stub.mbt index 4e0e926..687e315 100644 --- a/components/network/gen/interface/chandra/desktop/plasmoid/stub.mbt +++ b/components/network/gen/interface/chandra/desktop/plasmoid/stub.mbt @@ -207,17 +207,57 @@ fn status_line(s : @net.NetStatus) -> String { } } +///| Display-cell width of one Unicode scalar value in `fit` (0 for emoji modifiers/tags, +/// 2 for supplementary emoji, 1 otherwise). +fn fit_cells(cp : Int) -> Int { + if cp == 0xFE0E || + cp == 0xFE0F || + cp == 0x200D || + cp == 0x20E3 || + (cp >= 0x1F3FB && cp <= 0x1F3FF) || + (cp >= 0xE0020 && cp <= 0xE007F) { + 0 + } else if cp >= 0x1F000 { + 2 + } else { + 1 + } +} + ///| `s` cut to fit `w` pixels at font size `fs`. fn fit(s : String, w : Int, fs : Int) -> String { - let cw = (fs * 6 + 9) / 10 - let n = if cw > 0 { w / cw } else { s.length() } - if s.length() <= n { - s - } else if n <= 1 { - "" - } else { - s[:n - 1].to_string() + "…" + let chars = s.to_array() + let mut total = 0 + for ch in chars { + total = total + fit_cells(ch.to_int()) } + let cw = (fs * 6 + 9) / 10 + let n = if cw > 0 { w / cw } else { total } + if total <= n { + return s + } + if n <= 1 { + return "" + } + let kept : Array[Char] = [] + let mut used = 0 + for ch in chars { + let c = fit_cells(ch.to_int()) + if used + c > n - 1 { + break + } + kept.push(ch) + used = used + c + } + while kept.length() > 0 && kept[kept.length() - 1].to_int() == 0x200D { + ignore(kept.pop()) + } + let sb = StringBuilder::new() + for ch in kept { + sb.write_char(ch) + } + sb.write_char('…') + sb.to_string() } ///| diff --git a/compositor/emoji/font.mbt b/compositor/emoji/font.mbt index 4169c7f..3776153 100644 --- a/compositor/emoji/font.mbt +++ b/compositor/emoji/font.mbt @@ -368,6 +368,197 @@ pub fn EmojiFont::has(self : EmojiFont, text : String) -> Bool raise EmojiFontEr gs.length() == 1 && self.glyph_png(gs[0]) is Some(_) } +///| Whether `cp` is an emoji skin tone modifier (Fitzpatrick Type-1-2 through Type-6). +fn is_skin_tone(cp : Int) -> Bool { + cp >= 0x1F3FB && cp <= 0x1F3FF +} + +///| Whether `text` contains any code point >= U+203C (covering emoji, keycap combining +/// enclosing keycap U+20E3, and variation selector U+FE0F). +pub fn text_may_have_emoji(text : String) -> Bool { + for ch in text { + if ch.to_int() >= 0x203C { + return true + } + } + false +} + +///| Default-ignorable emoji joiner / variation selectors (U+FE0E, U+FE0F, U+200D). +pub fn is_ignorable_emoji_mod(cp : Int) -> Bool { + cp == 0xFE0E || cp == 0xFE0F || cp == 0x200D +} + +///| Whether a non-ASCII code point >= U+203C sits in a Unicode block that can start an emoji. +fn may_start_emoji_non_ascii(cp : Int) -> Bool { + (cp >= 0x203C && cp <= 0x21AA) || + (cp >= 0x2300 && cp <= 0x27BF) || + (cp >= 0x2934 && cp <= 0x2935) || + (cp >= 0x2B00 && cp <= 0x2BFF) || + cp == 0x3030 || + cp == 0x303D || + cp == 0x3297 || + cp == 0x3299 || + (cp >= 0x1F000 && cp <= 0x1FBFF) +} + +///| Exclusive end index of the maximal candidate emoji cluster starting at `chars[start]`, +/// or `start` when `chars[start]` cannot start an emoji sequence. +pub fn candidate_end(chars : Array[Char], start : Int) -> Int { + let n = chars.length() + if start < 0 || start >= n { + return start + } + let cp = chars[start].to_int() + if is_ignorable_emoji_mod(cp) || cp == 0x20E3 { + return start + } + if cp < 0x80 { + // ASCII can only start a keycap emoji (#️⃣, *️⃣, 0️⃣..9️⃣). + let is_keycap = cp == 0x23 || cp == 0x2A || (cp >= 0x30 && cp <= 0x39) + if !is_keycap { + return start + } + if start + 1 < n && chars[start + 1].to_int() == 0x20E3 { + return start + 2 + } + if start + 2 < n && chars[start + 1].to_int() == 0xFE0F && chars[start + 2].to_int() == 0x20E3 { + return start + 3 + } + return start + } + if cp < 0x203C { + // Only ©️ / ®️ with explicit emoji presentation selector. + if (cp == 0xA9 || cp == 0xAE) && start + 1 < n && chars[start + 1].to_int() == 0xFE0F { + return start + 2 + } + return start + } + if !may_start_emoji_non_ascii(cp) { + return start + } + if cp >= 0x1F1E6 && cp <= 0x1F1FF { + if start + 1 < n { + let next = chars[start + 1].to_int() + if next >= 0x1F1E6 && next <= 0x1F1FF { + return start + 2 + } + } + return start + 1 + } + let limit = if start + 16 < n { start + 16 } else { n } + if cp == 0x1F3F4 && start + 1 < limit { + let first_tag = chars[start + 1].to_int() + if first_tag >= 0xE0020 && first_tag <= 0xE007E { + let mut j = start + 1 + while j < limit - 1 { + let t = chars[j].to_int() + if t >= 0xE0020 && t <= 0xE007E { + j = j + 1 + } else { + break + } + } + if j < limit && chars[j].to_int() == 0xE007F { + return j + 1 + } + } + } + let mut i = start + 1 + if i < limit && chars[i].to_int() == 0xFE0F { + i = i + 1 + } + if i < limit && is_skin_tone(chars[i].to_int()) { + i = i + 1 + } + while i + 1 < limit && chars[i].to_int() == 0x200D { + let next = chars[i + 1].to_int() + if next < 0x80 || is_ignorable_emoji_mod(next) || next == 0x20E3 { + break + } + i = i + 2 + if i < limit && chars[i].to_int() == 0xFE0F { + i = i + 1 + } + if i < limit && is_skin_tone(chars[i].to_int()) { + i = i + 1 + } + } + i +} + +///| Match the longest emoji sequence starting at `chars[start]` accepted by `has_emoji`. +/// Respects U+FE0E text presentation and keeps bare BMP symbols monochrome when `has_text_glyph` +/// reports the text font has them. +pub fn match_with( + chars : Array[Char], + start : Int, + has_text_glyph : (Int) -> Bool, + has_emoji : (String) -> Bool, +) -> (Int, String)? { + let max_end = candidate_end(chars, start) + if max_end <= start { + return None + } + let cp = chars[start].to_int() + if start + 1 < chars.length() && chars[start + 1].to_int() == 0xFE0E && has_text_glyph(cp) { + return None + } + let mut end = max_end + while end > start { + if chars[end - 1].to_int() == 0x200D { + end = end - 1 + continue + } + if cp < 0x80 && chars[end - 1].to_int() != 0x20E3 { + end = end - 1 + continue + } + if end == start + 1 && cp < 0x1F000 && has_text_glyph(cp) { + return None + } + let sb = StringBuilder::new() + for k = start; k < end; k = k + 1 { + sb.write_char(chars[k]) + } + let sub = sb.to_string() + if has_emoji(sub) { + return Some((end, sub)) + } + end = end - 1 + } + None +} + +///| Match the longest emoji sequence starting at `chars[start]` that this font can draw. +pub fn EmojiFont::match_at( + self : EmojiFont, + chars : Array[Char], + start : Int, + has_text_glyph : (Int) -> Bool, +) -> (Int, String)? raise EmojiFontError { + if start < 0 || start >= chars.length() { + return None + } + let cp = chars[start].to_int() + if cp >= 0x80 && self.glyph(cp) == 0 { + return None + } + let mut err : EmojiFontError? = None + let res = match_with(chars, start, has_text_glyph, s => { + try self.has(s) catch { + e => { + err = Some(e) + false + } + } + }) + match err { + Some(e) => raise e + None => res + } +} + ///| The picture for `text`, `px` x `px` (the bitmap scaled to fit and centred), straight RGBA. /// None when the font has no single picture for it. pub fn EmojiFont::picture(self : EmojiFont, text : String, px : Int) -> @renderer.Pixmap? raise EmojiFontError { @@ -515,3 +706,26 @@ pub fn EmojiSource::image(self : EmojiSource, text : String, px : Int, put : (@r self.images.set(key, h) h } + +///| Match the longest emoji sequence starting at `chars[start]` using the open font. +/// Opens the font lazily on first use; does not retry a failed open on every text draw call. +pub fn EmojiSource::match_at( + self : EmojiSource, + chars : Array[Char], + start : Int, + has_text_glyph : (Int) -> Bool, +) -> (Int, String)? { + if self.state is None { + ignore(self.font()) + } + match self.state { + Some(Ok((_, f))) => + try f.match_at(chars, start, has_text_glyph) catch { + EmojiFontError(why) => { + @sys.log("emoji: can't match inline emoji: " + why) + None + } + } + _ => None + } +} diff --git a/compositor/emoji/font_test.mbt b/compositor/emoji/font_test.mbt index c9cad02..4d0d1a9 100644 --- a/compositor/emoji/font_test.mbt +++ b/compositor/emoji/font_test.mbt @@ -68,3 +68,55 @@ test "a file that is not a colour emoji font is an error that says why" { assert_true(msg.contains("no cmap table")) assert_true(@emoji.missing_font_message("").contains("just install")) } + +///| +test "inline emoji matcher handles turtle, sequences, VS15/VS16, and BMP symbols" { + assert_false(@emoji.text_may_have_emoji("Regency 215-223 WiFi")) + assert_false(@emoji.text_may_have_emoji("Café • … — ©")) + assert_true(@emoji.text_may_have_emoji("🐢")) + assert_true(@emoji.text_may_have_emoji("Connected to 🐢 (72%)")) + assert_true(@emoji.text_may_have_emoji("#️⃣")) + assert_true(@emoji.text_may_have_emoji("©️")) + + let f = open_font() + let all_have = fn(_cp : Int) { true } + let none_have = fn(_cp : Int) { false } + + assert_eq(f.match_at("🐢".to_array(), 0, all_have), Some((1, "🐢"))) + assert_eq(f.match_at("Connected to 🐢 (72%)".to_array(), 13, all_have), Some((14, "🐢"))) + assert_eq(f.match_at("👍🏽!".to_array(), 0, all_have), Some((2, "👍🏽"))) + assert_eq(f.match_at("#️⃣x".to_array(), 0, all_have), Some((3, "#️⃣"))) + assert_eq(f.match_at("🇺🇸x".to_array(), 0, all_have), Some((2, "🇺🇸"))) + assert_eq(f.match_at("👨‍👩‍👧‍👦x".to_array(), 0, all_have), Some((7, "👨‍👩‍👧‍👦"))) + + // Bare BMP symbols stay monochrome when the UI text font has them; VS16 switches to colour, VS15 keeps text. + assert_eq(f.match_at("▶".to_array(), 0, all_have), None) + assert_eq(f.match_at("▶️".to_array(), 0, all_have), Some((2, "▶️"))) + assert_eq(f.match_at("▶\u{FE0E}".to_array(), 0, all_have), None) + assert_eq(f.match_at("☀".to_array(), 0, none_have), Some((1, "☀"))) + + // Non-emoji ASCII / CJK / unsupported Emoji 18.0 characters do not match. + assert_eq(f.match_at("#1".to_array(), 0, all_have), None) + assert_eq(f.match_at("日本語".to_array(), 0, none_have), None) + let cracking = @emoji.all().filter(e => e.name == "cracking face")[0] + assert_eq(f.match_at(cracking.text.to_array(), 0, none_have), None) + + // Noto Color Emoji's turtle renders olive-green opaque pixels at inline size. + let p = f.picture("🐢", 16).unwrap() + assert_eq((p.width, p.height), (16, 16)) + let mut green = 0 + for i = 0; i < p.width * p.height; i = i + 1 { + let o = i * 4 + let r = p.data[o].to_int() + let g = p.data[o + 1].to_int() + let b = p.data[o + 2].to_int() + let a = p.data[o + 3].to_int() + if a > 200 && g > r && g > b + 40 { + green = green + 1 + } + } + assert_true(green > 10) + + let src = @emoji.EmojiSource::new() + assert_eq(src.match_at("🐢".to_array(), 0, all_have), Some((1, "🐢"))) +} diff --git a/compositor/font/font.mbt b/compositor/font/font.mbt index af0e483..057ca8c 100644 --- a/compositor/font/font.mbt +++ b/compositor/font/font.mbt @@ -69,6 +69,40 @@ fn rasterise(slot : Int, cp : Int, size : Int, embolden : Bool) -> @renderer.Gly } } +///| +let loaded : FixedArray[Bool] = FixedArray::make(4, false) + +///| +fn pick_slot(bold : Bool, mono : Bool) -> Int { + let has_mono = loaded[0] + let has_sans = loaded[2] + if !has_mono && !has_sans { + return -1 + } + let has_bold = has_mono && loaded[1] + if mono && has_mono { + if bold && has_bold { + 1 + } else { + 0 + } + } else if has_sans { + 2 + } else { + 0 + } +} + +///| Whether the face used for (`bold`, `mono`) has a glyph for `cp`. +pub fn has_glyph(cp : Int, bold : Bool, mono : Bool) -> Bool { + let slot = pick_slot(bold, mono) + if slot < 0 { + false + } else { + b_has_glyph(slot, cp) + } +} + ///| Install Allo Variable (UI text, falling back to Adwaita Sans) and Adwaita Mono (code) as the renderer's /// faces. Returns false (keeping the bitmap font) when no face can be found. /// Slots: 0 mono, 1 mono bold, 2 sans. Sans is a variable font whose bold @@ -77,9 +111,15 @@ pub fn install() -> Bool { let has_mono = load_first(0, regular_paths) let has_sans = load_first(2, sans_paths) if !has_mono && !has_sans { + loaded[0] = false + loaded[1] = false + loaded[2] = false return false } let has_bold = has_mono && load_first(1, bold_paths) + loaded[0] = has_mono + loaded[1] = has_bold + loaded[2] = has_sans @renderer.set_glyph_source(fn(cp, size, bold, mono) { if mono && has_mono { if bold && has_bold { diff --git a/compositor/font/font_native.mbt b/compositor/font/font_native.mbt index 67b5423..7356822 100644 --- a/compositor/font/font_native.mbt +++ b/compositor/font/font_native.mbt @@ -24,6 +24,9 @@ extern "C" fn c_font_bitmap( buf : Bytes, ) = "mp_font_bitmap" +///| +extern "C" fn c_font_has_glyph(slot : Int, cp : Int) -> Int = "mp_font_has_glyph" + ///| fn utf8(s : String) -> Bytes { let out : Array[Byte] = [] @@ -68,3 +71,8 @@ fn b_glyph(slot : Int, cp : Int, size : Int) -> RawGlyph { } { w, h, xoff: info[2], yoff: info[3], advance: info[4], coverage: buf } } + +///| Whether `slot` has a glyph for `cp` (not `.notdef`). +fn b_has_glyph(slot : Int, cp : Int) -> Bool { + c_font_has_glyph(slot, cp) != 0 +} diff --git a/compositor/font/font_stub.c b/compositor/font/font_stub.c index bccbd59..5b799cf 100644 --- a/compositor/font/font_stub.c +++ b/compositor/font/font_stub.c @@ -61,3 +61,10 @@ void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h if (w <= 0 || h <= 0 || Moonbit_array_length(buf) < w * h) return; stbtt_MakeGlyphBitmap(fi, (unsigned char *)buf, w, h, w, scale, scale, stbtt_FindGlyphIndex(fi, cp)); } + +/* 1 when `slot` has a glyph for code point `cp` (not .notdef), 0 otherwise. */ +MOONBIT_FFI_EXPORT +int32_t mp_font_has_glyph(int32_t slot, int32_t cp) { + if (slot < 0 || slot >= MAX_SLOTS || !font_data[slot]) return 0; + return stbtt_FindGlyphIndex(&fonts[slot], cp) != 0 ? 1 : 0; +} diff --git a/compositor/font/font_wasm.mbt b/compositor/font/font_wasm.mbt index 44c7df2..d265a63 100644 --- a/compositor/font/font_wasm.mbt +++ b/compositor/font/font_wasm.mbt @@ -22,3 +22,42 @@ fn b_glyph(slot : Int, cp : Int, size : Int) -> RawGlyph { coverage: Bytes::from_fixedarray(g.coverage), } } + +///| Cached `.notdef` glyph (cp 0 at 16 px) per slot for wasm glyph-presence checks. +let wasm_notdef : Map[Int, RawGlyph] = {} + +///| Cached `b_has_glyph` results keyed by `slot * 0x110000 + cp`. +let wasm_has_cache : Map[Int, Bool] = {} + +///| +fn raw_glyph_eq(a : RawGlyph, b : RawGlyph) -> Bool { + a.w == b.w && + a.h == b.h && + a.xoff == b.xoff && + a.yoff == b.yoff && + a.advance == b.advance && + a.coverage == b.coverage +} + +///| Whether `slot` has a glyph for `cp` (not `.notdef`). +fn b_has_glyph(slot : Int, cp : Int) -> Bool { + if cp >= 0x1F000 { + return false + } + let key = slot * 0x110000 + cp + match wasm_has_cache.get(key) { + Some(v) => return v + None => () + } + let notdef = match wasm_notdef.get(slot) { + Some(g) => g + None => { + let g = b_glyph(slot, 0, 16) + wasm_notdef.set(slot, g) + g + } + } + let has = !raw_glyph_eq(b_glyph(slot, cp, 16), notdef) + wasm_has_cache.set(key, has) + has +} diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 39ac913..9b10b2f 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -341,6 +341,7 @@ pub fn ChandraCompositor::new( output_h : Int, ) -> ChandraCompositor? { ignore(@font.install()) // Adwaita Mono; keeps the bitmap font if it's missing + @raster.install_emoji_text(fn(cp, bold, mono) { @font.has_glyph(cp, bold, mono) }) let server = match @wayland.WaylandServer::listen(socket_path, output_w, output_h) { Some(s) => s None => return None diff --git a/compositor/host/desktop_test.mbt b/compositor/host/desktop_test.mbt index cf686a9..2f5a19e 100644 --- a/compositor/host/desktop_test.mbt +++ b/compositor/host/desktop_test.mbt @@ -298,3 +298,40 @@ test "desktop screenshots: icons, starfield, the Desktop tab" { } ignore(@sys.write_file_bytes("_build/desktop_settings.png", @renderer.encode_png(comp.compose_frame()))) } + +///| +test "mobile tap on desktop icon with finger drift launches without moving any icon" { + let socket_path = "/tmp/wayland-moon-desk-mobile-" + @sys.getpid().to_string() + ".sock" + let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 540, 1170).unwrap() + comp.shell.apps.clear() + for i = 0; i < 6; i = i + 1 { + let id = "app" + i.to_string() + comp.shell.apps.push({ + id, + name: ["Files", "Browser", "Terminal", "Editor", "Mail", "Music"][i], + comment: "", + category: "", + glyph: "", + }) + comp.shell.exec.set(id, "true") + } + comp.shell.apps_dirty = true + assert_true(comp.shell.set_desktop("icon-desktop")) + ignore(comp.compose_frame()) + // At 540x1170 with 96px medium cells and 20px margin, app5 is at column 0, row 5: center (68, 548). + // Tap with an 18 px touch-drift between press and release: must launch app5 and keep every icon in place. + comp.handle_input(@nested.InputEvent::PointerMove(68.0, 548.0), 10U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 11U) + comp.handle_input(@nested.InputEvent::PointerMove(86.0, 548.0), 12U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 13U) + ignore(comp.compose_frame()) + assert_eq(comp.shell.recents[0], "app5") + assert_eq(comp.shell.apps[0].id, "app5") + let places = desk_setting(comp, "places") + assert_true(places.contains("app0=0,0")) + assert_true(places.contains("app5=0,5")) + // A deliberate drag (> 50 px) to column 1, row 0 (center 164, 68) still moves app5 there. + desk_drag(comp, 68, 548, 164, 68, 30U) + assert_true(desk_setting(comp, "places").contains("app5=1,0")) + comp.close() +} diff --git a/compositor/host/network_test.mbt b/compositor/host/network_test.mbt index 99a48cb..bbe06c2 100644 --- a/compositor/host/network_test.mbt +++ b/compositor/host/network_test.mbt @@ -129,3 +129,63 @@ test "the Wi-Fi and airplane switches, and status only without NetworkManager" { click_row(comp, 1, 20U) assert_eq(fake.actions.length(), n) } + +///| Whether any pixel in `r` looks like Noto Color Emoji's olive-green turtle (`g > r && g > b + 40`). +fn has_turtle_pixels(px : @renderer.Pixmap, r : @scene.Rect) -> Bool { + for y = r.y; y < r.y + r.h; y = y + 1 { + for x = r.x; x < r.x + r.w; x = x + 1 { + match px.pixel(x, y) { + Some(c) => { + let cr = c.r.to_int() + let cg = c.g.to_int() + let cb = c.b.to_int() + if cg > cr && cg > cb + 40 { + return true + } + } + None => () + } + } + } + false +} + +///| Whether any Text draw op inside `ops` contains `sub`. +fn ops_have_text(ops : Array[@scene.DrawOp], sub : String) -> Bool { + for op in ops { + match op { + Text(_, _, s, _, _, _, _) | MonoText(_, _, s, _, _, _, _) => + if s.contains(sub) { + return true + } + _ => () + } + } + false +} + +///| +test "Wi-Fi SSID with turtle emoji survives wasm boundary and renders in colour" { + let comp = new_comp("net-turtle") + let fake = @network.FakeNet::new( + { ..net_status(), name: "🐢" }, + [ + { ssid: "🐢", signal: 72, secured: true, active: true, saved: true }, + { ssid: "🐢 5G", signal: 55, secured: true, active: false, saved: false }, + ], + ) + comp.shell.set_network_backend(fake as &@network.NetBackend) + click_module(comp, "network", 1U) + comp.damage.mark_full() + let sg = comp.compose_scene().unwrap() + assert_true(ops_have_text(sg.panel_ops, "🐢")) + assert_true(ops_have_text(sg.panel_ops, "Connected to 🐢 (72%)")) + assert_true(ops_have_text(sg.panel_ops, "🐢 5G")) + let px = @renderer.render_scene(sg) + let slot = comp.shell.slot_of("network") + let btn = comp.shell.slot_rect(slot) + let pop = comp.shell.slot_popup_rect(slot) + assert_true(btn.w > 0 && pop.w > 0) + assert_true(has_turtle_pixels(px, btn)) + assert_true(has_turtle_pixels(px, pop)) +} diff --git a/compositor/kms/kms_stub.c b/compositor/kms/kms_stub.c index db1aae9..868f8c8 100644 --- a/compositor/kms/kms_stub.c +++ b/compositor/kms/kms_stub.c @@ -35,7 +35,7 @@ #define BTN_LEFT_CODE 0x110 #define BTN_RIGHT_CODE 0x111 #define TOUCH_LONG_MS 500 -#define TOUCH_DRAG_PX 12 +#define TOUCH_DRAG_PX 18 /* ---- damage ---- */ @@ -451,7 +451,7 @@ static void handle_li_event(struct libinput_event *ev) { if (g_touch_state == TOUCH_PENDING) { int dx = g_px - g_touch_x0; int dy = g_py - g_touch_y0; - if (dx < -TOUCH_DRAG_PX || dx > TOUCH_DRAG_PX || dy < -TOUCH_DRAG_PX || dy > TOUCH_DRAG_PX) { + if (dx * dx + dy * dy > TOUCH_DRAG_PX * TOUCH_DRAG_PX) { touch_timer_disarm(); g_touch_state = TOUCH_DRAG; q_push(EV_MOVE, g_touch_x0, g_touch_y0, 0, 0); @@ -473,9 +473,12 @@ static void handle_li_event(struct libinput_event *ev) { touch_timer_disarm(); g_touch_state = TOUCH_IDLE; if (st == TOUCH_PENDING) { + g_px = g_touch_x0; + g_py = g_touch_y0; q_push(EV_MOVE, g_px, g_py, 0, 0); q_push(EV_BUTTON, BTN_LEFT_CODE, 1, 0, 0); q_push(EV_BUTTON, BTN_LEFT_CODE, 0, 0, 0); + cursor_apply(); } else if (st == TOUCH_DRAG) { q_push(EV_BUTTON, BTN_LEFT_CODE, 0, 0, 0); } diff --git a/compositor/raster/raster_native.mbt b/compositor/raster/raster_native.mbt index 0b1c1ad..9081f67 100644 --- a/compositor/raster/raster_native.mbt +++ b/compositor/raster/raster_native.mbt @@ -90,3 +90,13 @@ pub fn emoji_has(texts : Array[String]) -> Array[Bool] { pub fn emoji_image(text : String, px : Int) -> UInt { emoji_source.image(text, px, p => @renderer.add_image(p)) } + +///| Enable inline colour emoji fallback for general UI text. +pub fn install_emoji_text(has_glyph : (Int, Bool, Bool) -> Bool) -> Unit { + @renderer.set_emoji_source( + fn(chars, start, bold, mono) { + emoji_source.match_at(chars, start, cp => has_glyph(cp, bold, mono)) + }, + emoji_image, + ) +} diff --git a/compositor/raster/raster_wasm.mbt b/compositor/raster/raster_wasm.mbt index 04ca378..53b9e7c 100644 --- a/compositor/raster/raster_wasm.mbt +++ b/compositor/raster/raster_wasm.mbt @@ -163,3 +163,29 @@ pub fn emoji_has(texts : Array[String]) -> Array[Bool] { pub fn emoji_image(text : String, px : Int) -> UInt { @hostraster.emoji_image(text, px) } + +///| Cached emoji availability by sequence string for wasm-side `text_width` calculations. +let wasm_emoji_has : Map[String, Bool] = {} + +///| +fn wasm_has_emoji(seq : String) -> Bool { + match wasm_emoji_has.get(seq) { + Some(v) => v + None => { + let res = @hostraster.emoji_has([seq]) + let ok = res.length() > 0 && res[0] + wasm_emoji_has.set(seq, ok) + ok + } + } +} + +///| Enable inline colour emoji matching for `@renderer.text_width` in the wasm compositor. +pub fn install_emoji_text(has_glyph : (Int, Bool, Bool) -> Bool) -> Unit { + @renderer.set_emoji_source( + fn(chars, start, bold, mono) { + @emoji.match_with(chars, start, cp => has_glyph(cp, bold, mono), wasm_has_emoji) + }, + emoji_image, + ) +} diff --git a/compositor/renderer/pkg.generated.mbti b/compositor/renderer/pkg.generated.mbti index d0b0582..992c8a2 100644 --- a/compositor/renderer/pkg.generated.mbti +++ b/compositor/renderer/pkg.generated.mbti @@ -20,14 +20,18 @@ pub fn encode_png_compressed(Pixmap) -> Bytes pub fn encode_ppm(Pixmap) -> Bytes +pub fn inline_emoji_px(Int32) -> Int32 + pub fn render_scene(@scene.SceneGraph) -> Pixmap pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap -pub fn set_image(UInt32, Pixmap) -> UInt32 +pub fn set_emoji_source((Array[Char], Int32, Bool, Bool) -> (Int32, String)?, (String, Int32) -> UInt32) -> Unit pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit +pub fn set_image(UInt32, Pixmap) -> UInt32 + pub fn shm_thumbnail(@scene.ShmBufferSnapshot, Int32, Int32) -> Pixmap? pub fn text_width(String, Int32, Bool, Bool) -> Int32 diff --git a/compositor/renderer/renderer.mbt b/compositor/renderer/renderer.mbt index 5564854..6116027 100644 --- a/compositor/renderer/renderer.mbt +++ b/compositor/renderer/renderer.mbt @@ -496,10 +496,99 @@ pub fn set_glyph_source(f : (Int, Int, Bool, Bool) -> Glyph) -> Unit { glyph_source.val = Some(f) } +///| Pixel square size for inline colour emoji at font `size` (~1.2em, matching UI line height). +pub fn inline_emoji_px(size : Int) -> Int { + if size <= 0 { + 0 + } else { + (size * 6 + 4) / 5 + } +} + +///| Optional inline emoji matcher and image provider for general UI text. +let emoji_match_source : Ref[((Array[Char], Int, Bool, Bool) -> (Int, String)?)?] = { + val: None, +} + +///| +let emoji_image_source : Ref[((String, Int) -> UInt)?] = { val: None } + +///| Register inline colour emoji lookup (`match_at`) and image rasteriser (`image`). +pub fn set_emoji_source( + match_at : (Array[Char], Int, Bool, Bool) -> (Int, String)?, + image : (String, Int) -> UInt, +) -> Unit { + emoji_match_source.val = Some(match_at) + emoji_image_source.val = Some(image) +} + +///| +priv enum TextPiece { + TextGlyph(Glyph) + TextEmoji(String) +} + +///| +fn renderer_may_have_emoji(text : String) -> Bool { + for ch in text { + if ch.to_int() >= 0x203C { + return true + } + } + false +} + +///| +fn renderer_ignorable_mod(cp : Int) -> Bool { + cp == 0xFE0E || cp == 0xFE0F || cp == 0x200D +} + +///| Segment `text` into text glyphs and inline emoji clusters, returning `(pieces, total_w)`. +fn layout_text( + src : (Int, Int, Bool, Bool) -> Glyph, + match_at : (Array[Char], Int, Bool, Bool) -> (Int, String)?, + text : String, + size : Int, + bold : Bool, + mono : Bool, +) -> (Array[TextPiece], Int) { + let chars = text.to_array() + let epx = inline_emoji_px(size) + let pieces : Array[TextPiece] = [] + let mut total_w = 0 + let mut i = 0 + while i < chars.length() { + match match_at(chars, i, bold, mono) { + Some((next, seq)) => { + pieces.push(TextEmoji(seq)) + total_w = total_w + epx + i = next + } + None => { + let cp = chars[i].to_int() + if !renderer_ignorable_mod(cp) { + let g = src(cp, size, bold, mono) + pieces.push(TextGlyph(g)) + total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 }) + } + i = i + 1 + } + } + } + (pieces, total_w) +} + ///| Pixel width `text` would occupy when drawn with the given face. pub fn text_width(text : String, size : Int, bold : Bool, mono : Bool) -> Int { match glyph_source.val { Some(src) => { + match emoji_match_source.val { + Some(match_at) if renderer_may_have_emoji(text) => { + let (_, w) = layout_text(src, match_at, text, size, bold, mono) + return w + } + _ => () + } let mut w = 0 for ch in text { let g = src(ch.to_int(), size, bold, mono) @@ -525,12 +614,20 @@ fn draw_text_font( bold : Bool, clip : @scene.Rect?, ) -> Unit { - let glyphs : Array[Glyph] = [] - let mut total_w = 0 - for ch in text { - let g = src(ch.to_int(), size, bold, mono) - glyphs.push(g) - total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 }) + let epx = inline_emoji_px(size) + let (pieces, total_w) = match (emoji_match_source.val, emoji_image_source.val) { + (Some(match_at), Some(_)) if renderer_may_have_emoji(text) => + layout_text(src, match_at, text, size, bold, mono) + _ => { + let pieces : Array[TextPiece] = [] + let mut total_w = 0 + for ch in text { + let g = src(ch.to_int(), size, bold, mono) + pieces.push(TextGlyph(g)) + total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 }) + } + (pieces, total_w) + } } let start_x = match align { Left => x @@ -545,21 +642,37 @@ fn draw_text_font( let cb = color.b.to_int() let ca = color.a.to_int() let mut pen = start_x - for g in glyphs { - for row = 0; row < g.h; row = row + 1 { - for col = 0; col < g.w; col = col + 1 { - let cov = g.coverage[row * g.w + col].to_int() - if cov > 0 { - let px = pen + g.xoff + col - let py = baseline + g.yoff + row - blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip) - if g.embolden { - blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip) + for piece in pieces { + match piece { + TextGlyph(g) => { + for row = 0; row < g.h; row = row + 1 { + for col = 0; col < g.w; col = col + 1 { + let cov = g.coverage[row * g.w + col].to_int() + if cov > 0 { + let px = pen + g.xoff + col + let py = baseline + g.yoff + row + blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip) + if g.embolden { + blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip) + } + } } } + pen = pen + g.advance + (if g.embolden { 1 } else { 0 }) + } + TextEmoji(seq) => { + match emoji_image_source.val { + Some(img_fn) if epx > 0 => { + let h = img_fn(seq, epx) + if h != 0U { + draw_image(dst, h, @scene.Rect::new(pen, y - epx / 2, epx, epx), clip) + } + } + _ => () + } + pen = pen + epx } } - pen = pen + g.advance + (if g.embolden { 1 } else { 0 }) } } diff --git a/compositor/renderer/renderer_test.mbt b/compositor/renderer/renderer_test.mbt index 1b9f430..5321660 100644 --- a/compositor/renderer/renderer_test.mbt +++ b/compositor/renderer/renderer_test.mbt @@ -137,3 +137,58 @@ test "shm_thumbnail scales a client buffer; set_image swaps an image in place" { @renderer.draw_ops(dst, [@scene.DrawOp::Image(@scene.Rect::new(0, 0, 2, 1), h)], 0, 0) assert_eq(dst.pixel(0, 0), Some(@scene.Rgba::new(0, 0, 255, 255))) } + +///| +test "inline emoji source integrates into text_width and draw_ops" { + assert_eq(@renderer.inline_emoji_px(0), 0) + assert_eq(@renderer.inline_emoji_px(12), 15) + assert_eq(@renderer.inline_emoji_px(13), 16) + assert_eq(@renderer.inline_emoji_px(14), 17) + + let epx = @renderer.inline_emoji_px(13) + let turtle = @renderer.Pixmap::new(epx, epx) + for y = 0; y < epx; y = y + 1 { + for x = 0; x < epx; x = x + 1 { + let o = (y * epx + x) * 4 + turtle.data[o] = (110).to_byte() + turtle.data[o + 1] = (130).to_byte() + turtle.data[o + 2] = (58).to_byte() + turtle.data[o + 3] = b'\xff' + } + } + let th = @renderer.add_image(turtle) + let block = Bytes::make(4 * 8, b'\xff') + @renderer.set_glyph_source(fn(cp, _size, _bold, _mono) { + if cp == 0x1F422 { + { w: 0, h: 0, xoff: 0, yoff: 0, advance: 6, coverage: b"", embolden: false } + } else if cp == 32 { + { w: 0, h: 0, xoff: 0, yoff: 0, advance: 6, coverage: b"", embolden: false } + } else { + { w: 4, h: 8, xoff: 0, yoff: -8, advance: 6, coverage: block, embolden: false } + } + }) + @renderer.set_emoji_source( + fn(chars, start, _bold, _mono) { + if start < chars.length() && chars[start].to_int() == 0x1F422 { + Some((start + 1, "🐢")) + } else { + None + } + }, + fn(seq, _px) { if seq == "🐢" { th } else { 0U } }, + ) + + assert_eq(@renderer.text_width("Hi 🐢", 13, false, false), 18 + epx) + assert_eq(@renderer.text_width("Hi \u{200D}🐢\u{FE0F}", 13, false, false), 18 + epx) + + let pm = @renderer.Pixmap::new(64, 40) + @renderer.draw_ops( + pm, + [@scene.DrawOp::Text(10, 20, "Hi 🐢", 13, @scene.Rgba::new(255, 255, 255, 255), Left, false)], + 0, + 0, + ) + // 'H' at x=10..13, y=(20 + 8/2) - 8 .. = 16..23 is white; inline turtle at x=28..28+epx-1 is olive-green. + assert_eq(pm.pixel(11, 20), Some(@scene.Rgba::new(255, 255, 255, 255))) + assert_eq(pm.pixel(28 + epx / 2, 20), Some(@scene.Rgba::new(110, 130, 58, 255))) +} diff --git a/compositor/scene/scene.mbt b/compositor/scene/scene.mbt index d0f2e11..ac3116d 100644 --- a/compositor/scene/scene.mbt +++ b/compositor/scene/scene.mbt @@ -404,12 +404,18 @@ pub fn build_breeze_decoration( let label = if title.length() > 0 { title } else { app_id } let char_w = if tokens.font_size >= 14 { 12 } else { 6 } let max_chars = (min_x - 8 - 14) / char_w + let chars = label.to_array() let shown = if max_chars < 3 { "" - } else if label.length() <= max_chars { + } else if chars.length() <= max_chars { label } else { - label[:max_chars - 2].to_string() + ".." + let sb = StringBuilder::new() + for i = 0; i < max_chars - 2; i = i + 1 { + sb.write_char(chars[i]) + } + sb.write_string("..") + sb.to_string() } ops.push( Text(14, title_h / 2, shown, tokens.font_size, title_fg, Left, focused), diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index 06a1ced..568ed1f 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -93,6 +93,11 @@ fn module_dirs() -> Array[String] { } } } + let checkout_dirs = ["build/components", "../build/components", "../../build/components"] + let test_cfg = @sys.getenv("CHANDRA_TEST_CONFIG") != "" + if test_cfg { + dirs.append(checkout_dirs) + } let data_home = { let x = @sys.getenv("XDG_DATA_HOME") if x.length() > 0 { x } else { @sys.getenv("HOME") + "/.local/share" } @@ -101,10 +106,10 @@ fn module_dirs() -> Array[String] { dirs.push("/usr/local/share/chandra/modules") dirs.push("/usr/share/chandra/modules") dirs.push("modules") // the login session runs from /usr/local/share/chandra - // In a source checkout (and from a package directory when running its tests). - dirs.push("build/components") - dirs.push("../build/components") - dirs.push("../../build/components") + if !test_cfg { + // In a source checkout (and from a package directory when running its tests). + dirs.append(checkout_dirs) + } dirs } diff --git a/compositor/wasm/wasm_native.mbt b/compositor/wasm/wasm_native.mbt index 3078e06..cc57952 100644 --- a/compositor/wasm/wasm_native.mbt +++ b/compositor/wasm/wasm_native.mbt @@ -235,8 +235,28 @@ fn Plasmoid::str(self : Plasmoid, ptr : Int, len : Int) -> String { None => "" Some(b) => { let sb = StringBuilder::new() - for i = 0; i < len; i = i + 1 { - sb.write_char((b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8)).unsafe_to_char()) + let mut i = 0 + while i < len { + let u = b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8) + if u >= 0xD800 && u <= 0xDBFF { + if i + 1 < len { + let lo = b[2 * (i + 1)].to_int() | (b[2 * (i + 1) + 1].to_int() << 8) + if lo >= 0xDC00 && lo <= 0xDFFF { + let cp = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00) + sb.write_char(cp.unsafe_to_char()) + i = i + 2 + continue + } + } + sb.write_char('\u{FFFD}') + i = i + 1 + } else if u >= 0xDC00 && u <= 0xDFFF { + sb.write_char('\u{FFFD}') + i = i + 1 + } else { + sb.write_char(u.unsafe_to_char()) + i = i + 1 + } } sb.to_string() } diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c index 73485bb..7b35031 100644 --- a/compositor/wasm/wasm_stub.c +++ b/compositor/wasm/wasm_stub.c @@ -189,7 +189,12 @@ static char *guest_str(Inst *in, int32_t ptr, int32_t units) { size_t o = 0; for (int i = 0; i < units; i++) { uint32_t cp = u[i]; - if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units) { cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); i++; } + if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units && u[i + 1] >= 0xDC00 && u[i + 1] < 0xE000) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); + i++; + } else if (cp >= 0xD800 && cp < 0xE000) { + cp = 0xFFFD; + } if (cp < 0x80) out[o++] = (char)cp; else if (cp < 0x800) { out[o++] = (char)(0xC0 | (cp >> 6)); out[o++] = (char)(0x80 | (cp & 0x3F)); } else if (cp < 0x10000) { out[o++] = (char)(0xE0 | (cp >> 12)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); } diff --git a/docs/handset.md b/docs/handset.md index a04b047..6259525 100644 --- a/docs/handset.md +++ b/docs/handset.md @@ -48,8 +48,8 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux ## Camera App (`chandra-camera`) -- [`camera/chandra-camera`](../camera/chandra-camera) and [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c) provide a native GTK3/Cairo Wayland camera app (no extra Python GI packages required) 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. +- [`camera/chandra-camera`](../camera/chandra-camera), [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c), and [`camera/chandra-camera-isp.c`](../camera/chandra-camera-isp.c) provide a native GTK3/Cairo Wayland camera app with a C/OpenMP Quad-Bayer ISP library (`libchandra-camera-isp.so`) 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, `libcamera` SoftISP CCM tuning (`camera/ipa/simple/*.yaml`), VCM contrast autofocus with tap-to-focus (`lc898217xc`), Photo mode (`HD` instant / `Full` high-resolution `StillCapture` or 3-frame raw burst merge on Quad-Bayer, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording exact-PTS VFR H.264 MP4s (`MatroskaI420Muxer` + `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. ## Remote Control Over Tailscale (`chandra-remote`) diff --git a/lib/icondesk/icondesk.mbt b/lib/icondesk/icondesk.mbt index e2e62c9..0d5b9b0 100644 --- a/lib/icondesk/icondesk.mbt +++ b/lib/icondesk/icondesk.mbt @@ -42,9 +42,6 @@ fn nat(s : String, dflt : Int) -> Int { ///| Space kept free around the grid, in pixels. let margin : Int = 20 -///| A drag starts once the pointer has moved this far from the press. -let drag_threshold : Int = 5 - ///| What the module asks of the host after an event. #derive(Eq, Debug) pub(all) enum Action { @@ -58,6 +55,9 @@ pub(all) struct Desk { mut size : String /// Where icons were put: app id -> (column, row). places : Map[String, (Int, Int)] + /// First-seen order of shown app ids, so recents reordering never shuffles unplaced icons. + seen : Map[String, Int] + mut next_seen : Int mut w : Int mut h : Int /// Kept free at the bottom (the panel). @@ -82,6 +82,8 @@ pub fn Desk::new() -> Desk { count: "12", size: "Medium", places: {}, + seen: {}, + next_seen: 0, w: 0, h: 0, bottom: 40, @@ -106,6 +108,13 @@ pub fn Desk::cell(self : Desk) -> (Int, Int, Int) { } } +///| A drag starts once the pointer has moved this far from the press. +fn Desk::drag_threshold(self : Desk) -> Int { + let (cw, _, _) = self.cell() + let t = cw / 3 + if t < 24 { 24 } else { t } +} + ///| Columns and rows that fit on the desktop (at least one of each). pub fn Desk::grid(self : Desk) -> (Int, Int) { let (cw, ch, _) = self.cell() @@ -129,9 +138,15 @@ pub fn Desk::shown(self : Desk, apps : Array[@types.AppEntry]) -> Array[@types.A } ///| Each shown app's cell, in `shown` order: its saved place when that is on the grid and free, -/// else the first free cell, a column at a time. (-1, -1) when the grid is full. +/// else the first free cell, a column at a time, in first-seen order. (-1, -1) when full. pub fn Desk::layout(self : Desk, apps : Array[@types.AppEntry]) -> Array[(Int, Int)] { let shown = self.shown(apps) + for a in shown { + if !self.seen.contains(a.id) { + self.seen.set(a.id, self.next_seen) + self.next_seen = self.next_seen + 1 + } + } let (cols, rows) = self.grid() let taken : Map[(Int, Int), Bool] = {} let out : Array[(Int, Int)] = Array::make(shown.length(), (-1, -1)) @@ -144,11 +159,19 @@ pub fn Desk::layout(self : Desk, apps : Array[@types.AppEntry]) -> Array[(Int, I _ => () } } - let mut next = 0 + let unplaced : Array[Int] = [] for i = 0; i < shown.length(); i = i + 1 { - if out[i] != (-1, -1) { - continue + if out[i] == (-1, -1) { + unplaced.push(i) } + } + unplaced.sort_by(fn(a, b) { + let sa = self.seen.get(shown[a].id).unwrap_or(a) + let sb = self.seen.get(shown[b].id).unwrap_or(b) + if sa != sb { sa - sb } else { a - b } + }) + let mut next = 0 + for i in unplaced { while next < cols * rows && taken.contains((next / rows, next % rows)) { next = next + 1 } @@ -192,6 +215,20 @@ pub fn Desk::app_at(self : Desk, apps : Array[@types.AppEntry], x : Int, y : Int "" } +///| Pin every unplaced shown icon at its current grid cell without overwriting existing places. +fn Desk::pin_unplaced(self : Desk, apps : Array[@types.AppEntry]) -> Unit { + if self.w <= 0 || self.h <= 0 { + return + } + let shown = self.shown(apps) + let cells = self.layout(apps) + for i, a in shown { + if cells[i] != (-1, -1) && !self.places.contains(a.id) { + self.places.set(a.id, cells[i]) + } + } +} + ///| Remember every shown icon where it is now, then put `id` at `to`, swapping with the icon /// there (which takes `id`'s old cell). fn Desk::move_to(self : Desk, apps : Array[@types.AppEntry], id : String, to : (Int, Int)) -> Unit { @@ -199,13 +236,18 @@ fn Desk::move_to(self : Desk, apps : Array[@types.AppEntry], id : String, to : ( let cells = self.layout(apps) let mut from = (-1, -1) for i, a in shown { - if cells[i] != (-1, -1) { - self.places.set(a.id, cells[i]) - } if a.id == id { from = cells[i] } } + if from == (-1, -1) || from == to { + return + } + for i, a in shown { + if cells[i] != (-1, -1) { + self.places.set(a.id, cells[i]) + } + } for i, a in shown { if a.id != id && cells[i] == to { self.places.set(a.id, from) @@ -315,9 +357,13 @@ pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.Inpu PointerMove(p) => { self.ptr_x = p.x self.ptr_y = p.y - if self.press_id != "" && !self.dragging && - ((p.x - self.press_x).abs() > drag_threshold || (p.y - self.press_y).abs() > drag_threshold) { - self.dragging = true + if self.press_id != "" && !self.dragging { + let dx = p.x - self.press_x + let dy = p.y - self.press_y + let t = self.drag_threshold() + if dx * dx + dy * dy > t * t { + self.dragging = true + } } if self.dragging { return (true, NoAction) @@ -355,10 +401,16 @@ pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.Inpu self.move_to(apps, id, self.cell_at(p.x, p.y)) self.hover = self.app_at(apps, p.x, p.y) (true, NoAction) - } else if self.app_at(apps, p.x, p.y) == id { - (true, Launch(id)) } else { - (true, NoAction) + let dx = p.x - self.press_x + let dy = p.y - self.press_y + let t = self.drag_threshold() + if self.app_at(apps, p.x, p.y) == id || dx * dx + dy * dy <= t * t { + self.pin_unplaced(apps) + (true, Launch(id)) + } else { + (true, NoAction) + } } } FocusLost => { @@ -375,7 +427,12 @@ pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.Inpu "ArrowUp" | "Up" => self.step_selection(apps, 0, -1) "ArrowDown" | "Down" => self.step_selection(apps, 0, 1) "Enter" | " " => - return (false, if self.selected != "" { Launch(self.selected) } else { NoAction }) + if self.selected != "" { + self.pin_unplaced(apps) + return (false, Launch(self.selected)) + } else { + return (false, NoAction) + } "Escape" => self.selected = "" _ => if k.length() == 1 { ignore(self.jump_to(apps, k)) } else { return (false, NoAction) } } diff --git a/lib/icondesk/icondesk_test.mbt b/lib/icondesk/icondesk_test.mbt index 329911e..ac76cc8 100644 --- a/lib/icondesk/icondesk_test.mbt +++ b/lib/icondesk/icondesk_test.mbt @@ -85,3 +85,86 @@ test "keyboard moves the selection and launches" { ignore(d.handle(a, FocusLost)) assert_false(d.focused) } + +///| +test "tapping with finger-roll drift launches without dragging or moving icons" { + let d = desk() + let a = apps(12) + let before = d.layout(a) + // 20 px drift inside cell (0,0): stays below the 32 px medium-cell drag threshold. + ignore(d.handle(a, PointerDown({ x: 60, y: 60 }))) + ignore(d.handle(a, PointerMove({ x: 80, y: 64 }))) + assert_false(d.dragging) + assert_eq(d.handle(a, PointerUp({ x: 80, y: 64 })), (true, Launch("app0"))) + assert_eq(d.layout(a), before) + // 15 px drift starting near the right edge of cell (0,0) and crossing into cell (1,0) still + // launches app0 without moving any icon. + ignore(d.handle(a, PointerDown({ x: 110, y: 60 }))) + ignore(d.handle(a, PointerMove({ x: 125, y: 60 }))) + assert_false(d.dragging) + assert_eq(d.handle(a, PointerUp({ x: 125, y: 60 })), (true, Launch("app0"))) + assert_eq(d.layout(a), before) +} + +///| +test "launching and reordering apps by recency keeps every icon in its cell" { + let a = apps(12) + // Simulate an app launched from elsewhere (places empty): first-seen order keeps cells stable. + let d_unpinned = desk() + let expected_by_id : Map[String, (Int, Int)] = {} + let initial = d_unpinned.layout(a) + for i, app in a { + expected_by_id.set(app.id, initial[i]) + } + let reordered = [a[0], a[1], a[2], a[3], a[4], a[7], a[5], a[6], a[8], a[9], a[10], a[11]] + let after_unpinned = d_unpinned.layout(reordered) + for i, app in reordered { + assert_eq(after_unpinned[i], expected_by_id.get(app.id).unwrap()) + } + // Launching app7 on the desktop pins existing cells and keeps stability across recents reorder, + // off-grid rotation/resize fallback, and reload into a fresh Desk. + let d = desk() + ignore(d.layout(a)) + // app7 is at cell (1, 2): x = 20 + 96 + 40 = 156, y = 20 + 2 * 96 + 40 = 252. + ignore(d.handle(a, PointerDown({ x: 156, y: 252 }))) + assert_eq(d.handle(a, PointerUp({ x: 156, y: 252 })), (true, Launch("app7"))) + let after_launch = d.layout(reordered) + for i, app in reordered { + assert_eq(after_launch[i], expected_by_id.get(app.id).unwrap()) + } + // Portrait resize where column >= 1 falls off-grid: off-grid apps fall back in seen order, + // not recents order (app5 before app6 before app7). + d.w = 220 + d.h = 1200 + let portrait = d.layout(reordered) + let p_by_id : Map[String, (Int, Int)] = {} + for i, app in reordered { + p_by_id.set(app.id, portrait[i]) + } + assert_true(p_by_id.get("app5").unwrap().1 < p_by_id.get("app6").unwrap().1) + assert_true(p_by_id.get("app6").unwrap().1 < p_by_id.get("app7").unwrap().1) + // Saved places round-trip into a fresh Desk with the reordered catalog. + let saved = d.config_items().filter(c => c.key == "places")[0] + let d2 = desk() + ignore(d2.set_config("places", saved.value)) + let reloaded = d2.layout(reordered) + for i, app in reordered { + assert_eq(reloaded[i], expected_by_id.get(app.id).unwrap()) + } +} + +///| +test "dragging past threshold and dropping on the same cell cancels cleanly" { + let d = desk() + let a = apps(12) + let before = d.layout(a) + let places_val = fn(x : @icondesk.Desk) { x.config_items().filter(c => c.key == "places")[0].value } + assert_eq(places_val(d), "") + // Move 45 px (> 32 px threshold) while staying inside cell (0,0) (20..116). + ignore(d.handle(a, PointerDown({ x: 60, y: 60 }))) + ignore(d.handle(a, PointerMove({ x: 105, y: 60 }))) + assert_true(d.dragging) + assert_eq(d.handle(a, PointerUp({ x: 105, y: 60 })), (true, NoAction)) + assert_eq(d.layout(a), before) + assert_eq(places_val(d), "") +} diff --git a/remote/web/index.html b/remote/web/index.html index 1e1619a..a2304ed 100644 --- a/remote/web/index.html +++ b/remote/web/index.html @@ -389,13 +389,14 @@ mode: 'one', sx: e.clientX, sy: e.clientY, lx: e.clientX, ly: e.clientY, + sfx: fx, sfy: fy, fx, fy, moved: false, dragging: false, longFired: false, longTimer: setTimeout(() => { if (!gesture || gesture.mode !== 'one' || gesture.moved) return; gesture.longFired = true; if (navigator.vibrate) navigator.vibrate(25); - const rx = trackpadMode ? cursorX : gesture.fx; - const ry = trackpadMode ? cursorY : gesture.fy; + const rx = trackpadMode ? cursorX : gesture.sfx; + const ry = trackpadMode ? cursorY : gesture.sfy; sendJson({ t: 'tap', x: rx, y: ry, b: 3 }); }, 450) }; @@ -435,13 +436,14 @@ } const [fx, fy] = clientToFb(e.clientX, e.clientY); gesture.fx = fx; gesture.fy = fy; - if (!gesture.moved && dist > 10) { + if (!gesture.moved && dist > 14) { gesture.moved = true; clearLongTimer(); if (!gesture.longFired) { gesture.dragging = true; - sendJson({ t: 'ptr', x: fx, y: fy }); + sendJson({ t: 'ptr', x: gesture.sfx, y: gesture.sfy }); sendJson({ t: 'btn', b: 1, d: 1 }); + sendJson({ t: 'ptr', x: fx, y: fy }); } } else if (gesture.dragging) { const now = performance.now(); @@ -477,8 +479,8 @@ sendJson({ t: 'ptr', x: fx, y: fy }); sendJson({ t: 'btn', b: 1, d: 0 }); } else if (!gesture.moved && !gesture.longFired) { - const tx = trackpadMode ? cursorX : gesture.fx; - const ty = trackpadMode ? cursorY : gesture.fy; + const tx = trackpadMode ? cursorX : gesture.sfx; + const ty = trackpadMode ? cursorY : gesture.sfy; sendJson({ t: 'tap', x: tx, y: ty, b: 1 }); } gesture = null; diff --git a/session/install.py b/session/install.py index 4bab7a9..fc4f104 100755 --- a/session/install.py +++ b/session/install.py @@ -75,6 +75,7 @@ targets = [ "/usr/local/bin/chandra-kde-colors", "/usr/local/bin/chandra-camera", "/usr/local/lib/chandra/chandra-camera-ui", + "/usr/local/lib/chandra/libchandra-camera-isp.so", "/usr/share/applications/chandra-camera.desktop", "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", "/usr/local/bin/chandra-remote", @@ -200,6 +201,30 @@ subprocess.check_call([cc, "-O2", "-Wall", "-Wextra", "-o", cam_ui_dst + ".new", os.chmod(cam_ui_dst + ".new", 0o755) os.replace(cam_ui_dst + ".new", cam_ui_dst) print("installed", cam_ui_dst) +cam_isp_src = os.path.join(root, "camera/chandra-camera-isp.c") +cam_isp_dst = "/usr/local/lib/chandra/libchandra-camera-isp.so" +if os.path.exists(cam_isp_src): + rc = subprocess.call([ + cc, "-O3", "-fopenmp", "-shared", "-fPIC", "-Wall", "-Wextra", + "-o", cam_isp_dst + ".new", cam_isp_src, "-lm", + ]) + if rc != 0: + subprocess.check_call([ + cc, "-O3", "-shared", "-fPIC", "-Wall", "-Wextra", + "-o", cam_isp_dst + ".new", cam_isp_src, "-lm", + ]) + os.chmod(cam_isp_dst + ".new", 0o755) + os.replace(cam_isp_dst + ".new", cam_isp_dst) + print("installed", cam_isp_dst) +cam_ipa_src = os.path.join(root, "camera/ipa/simple") +cam_ipa_dst = os.path.join(share, "ipa", "simple") +if os.path.isdir(cam_ipa_src): + os.makedirs(cam_ipa_dst, exist_ok=True) + os.chmod(os.path.join(share, "ipa"), 0o755) + os.chmod(cam_ipa_dst, 0o755) + for fn in sorted(os.listdir(cam_ipa_src)): + if fn.endswith(".yaml"): + put(os.path.join(cam_ipa_src, fn), os.path.join(cam_ipa_dst, fn), 0o644) 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) remote_srcs = [ diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt index 94bd1f4..c971ef3 100644 --- a/wasmhost/bin/raster.mbt +++ b/wasmhost/bin/raster.mbt @@ -85,6 +85,9 @@ fn font_load(slot : Int, path : String) -> Bool { ///| extern "C" fn rs_font_has(slot : Int) -> Int = "rs_font_has" +///| +extern "C" fn rs_font_has_glyph(slot : Int, cp : Int) -> Int = "rs_font_has_glyph" + ///| #borrow(info) extern "C" fn rs_glyph_info( @@ -361,6 +364,12 @@ fn advance(slot : Int, cp : Int, size : Int) -> Int { glyph_info[4] } +///| +priv enum WasmTextPiece { + WasmGlyph(Int) + WasmEmoji(String) +} + ///| fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit { let text = l.field("text").to_string() @@ -376,13 +385,40 @@ fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit { Some(f) => f None => return // no face loaded: nothing to draw with } + let (cap_slot, _) = match pick_face(false, mono) { + Some(f) => f + None => return + } let extra = if embolden { 1 } else { 0 } - let cps : Array[Int] = [] + let epx = @renderer.inline_emoji_px(size) + let pieces : Array[WasmTextPiece] = [] let mut total_w = 0 - for ch in text { - let cp = ch.to_int() - cps.push(cp) - total_w += advance(slot, cp, size) + extra + if !@emoji.text_may_have_emoji(text) { + for ch in text { + let cp = ch.to_int() + pieces.push(WasmGlyph(cp)) + total_w += advance(slot, cp, size) + extra + } + } else { + let chars = text.to_array() + let mut i = 0 + while i < chars.length() { + match emoji_source.match_at(chars, i, cp => rs_font_has_glyph(slot, cp) != 0) { + Some((next, seq)) => { + pieces.push(WasmEmoji(seq)) + total_w += epx + i = next + } + None => { + let cp = chars[i].to_int() + if !@emoji.is_ignorable_emoji_mod(cp) { + pieces.push(WasmGlyph(cp)) + total_w += advance(slot, cp, size) + extra + } + i = i + 1 + } + } + } } let x = l.field("x").to_int() + ox let start_x = match l.field("align").to_int() { @@ -391,19 +427,29 @@ fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit { _ => x } // `y` is the vertical centre of the text; centre the capital height ('H') on it. - let (cap_slot, _) = match pick_face(false, mono) { - Some(f) => f - None => return - } rs_glyph_info(cap_slot, 72, size, glyph_info) - let baseline = l.field("y").to_int() + oy + -glyph_info[3] / 2 + let cy = l.field("y").to_int() + oy + let baseline = cy + -glyph_info[3] / 2 let r = col.field("r").to_int() let g = col.field("g").to_int() let b = col.field("b").to_int() let mut pen = start_x - for cp in cps { - rs_draw_glyph(slot, cp, size, pen, baseline, r, g, b, ca, extra) - pen += advance(slot, cp, size) + extra + for piece in pieces { + match piece { + WasmGlyph(cp) => { + rs_draw_glyph(slot, cp, size, pen, baseline, r, g, b, ca, extra) + pen += advance(slot, cp, size) + extra + } + WasmEmoji(seq) => { + if epx > 0 { + let h = emoji_image(seq, epx) + if h != 0U { + rs_draw_image(h.reinterpret_as_int(), pen, cy - epx / 2, epx, epx) + } + } + pen += epx + } + } } } diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index 752e9e9..ed53c6f 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -33,6 +33,7 @@ int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes); void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info); void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf); +int32_t mp_font_has_glyph(int32_t slot, int32_t cp); /* ------------------------------------------------------------------ canvas */ @@ -315,6 +316,11 @@ void rs_font_loaded(int32_t slot) { int32_t rs_font_has(int32_t slot) { return slot >= 0 && slot < 4 && font_loaded[slot]; } +int32_t rs_font_has_glyph(int32_t slot, int32_t cp) { + if (slot < 0 || slot >= 4 || !font_loaded[slot]) return 0; + return mp_font_has_glyph(slot, cp); +} + /* Metrics into info: width, height, xoff, yoff, advance. */ void rs_glyph_info(int32_t slot, int32_t cp, int32_t size, int32_t *info) { Glyph *g = glyph(slot, cp, size);