#!/usr/bin/env python3
"""chandra-camera: mobile Wayland camera app for Chandra using libcamera / V4L2."""

import argparse
import ctypes
from dataclasses import dataclass
import datetime
import fcntl
import gc
import glob
import os
import queue
import select
import shutil
import signal
import struct
import subprocess
import sys
import threading
import time
import urllib.parse

os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR")

APP_ID = "chandra-camera"
APP_TITLE = "Camera"
PICTURE_DIR = os.path.expanduser("~/Pictures/Camera")
VIDEO_DIR = os.path.expanduser("~/Videos/Camera")
FLASH_LED_PATH = "/sys/class/leds/white:flash/brightness"
IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp")
VIDEO_EXTS = (".mp4", ".mkv", ".webm")

QUAD_BAYER_MODELS = {"imx371"}

# Pause between QR scans: scanning runs as long as the photo viewfinder is open.
QR_SCAN_INTERVAL_S = 0.5

# 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),
    (3840, 2160),
    (2584, 1940),
    (2320, 1740),
    (1920, 1440),
    (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:
    """Descriptor for one discovered libcamera or V4L2 camera."""

    cid: str
    backend: str  # "libcamera" or "v4l2"
    model: str
    location: int  # 0=Front, 1=Back, 2=External
    rotation: int
    label: str
    max_pixels: int = 0

    @property
    def is_front(self):
        return self.location == 0

    @property
    def is_back(self):
        return self.location == 1


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:
        s = str(raw_model).strip()
        if "/" in s:
            s = s.rsplit("/", 1)[-1]
        if s:
            return s
    tail = fallback_id.rsplit("/", 1)[-1]
    return tail or fallback_id


def sort_and_label_cameras(raw_items):
    """Sort cameras (primary Back first, then Front, then extra Back/External) and assign unique labels.

    Each item in raw_items is a tuple:
      (cid, backend, model, location, rotation, max_pixels)
    """
    loc_word = {0: "Front", 1: "Back", 2: "External"}

    back_items = [it for it in raw_items if it[3] == 1]
    primary_back_cid = None
    if back_items:
        best_back = min(
            back_items,
            key=lambda it: (0 if "imx519" in it[2].lower() else 1, -it[5], it[0]),
        )
        primary_back_cid = best_back[0]

    def sort_key(item):
        cid, _backend, _model, loc, _rot, max_px = item
        if loc == 1:
            group = 0 if cid == primary_back_cid else 2
        elif loc == 0:
            group = 1
        else:
            group = 3
        return (group, -max_px, cid)

    ordered = sorted(raw_items, key=sort_key)
    counts_by_loc = {}
    for item in ordered:
        loc = item[3]
        counts_by_loc[loc] = counts_by_loc.get(loc, 0) + 1

    seen_by_loc = {}
    out = []
    for cid, backend, model, loc, rot, max_px in ordered:
        idx = seen_by_loc.get(loc, 0) + 1
        seen_by_loc[loc] = idx
        prefix = loc_word.get(loc, "Camera")
        if counts_by_loc.get(loc, 0) > 1 and idx > 1:
            tag = "%s %d" % (prefix, idx)
        else:
            tag = prefix
        short = _short_model_name(model, cid)
        label = "%s · %s" % (tag, short) if short else tag
        out.append(
            CameraInfo(
                cid=cid,
                backend=backend,
                model=short,
                location=loc,
                rotation=int(rot or 0),
                label=label,
                max_pixels=int(max_px or 0),
            )
        )
    return out


def discover_cameras():
    """Return sorted CameraInfo list from libcamera, falling back to V4L2."""
    raw = []
    try:
        libcamera = _import_libcamera()
        cm = libcamera.CameraManager.singleton()
        for cam in cm.cameras:
            props = cam.properties
            loc = props.get(libcamera.properties.Location)
            if loc is None:
                loc = 2
            rot = props.get(libcamera.properties.Rotation) or 0
            model = str(props.get(libcamera.properties.Model) or _short_model_name("", cam.id))
            max_px = 0
            try:
                pa = props.get(libcamera.properties.PixelArraySize)
                if pa is not None:
                    max_px = int(pa.width) * int(pa.height)
            except Exception:
                max_px = 0
            raw.append((cam.id, "libcamera", model, int(loc), int(rot), max_px))
    except ImportError:
        raw = []
    except Exception:
        raw = []

    if raw:
        return sort_and_label_cameras(raw)

    # V4L2 fallback for desktops without libcamera sensors.
    v4l2 = []
    for idx in range(10):
        path = "/dev/video%d" % idx
        if not os.path.exists(path):
            continue
        sys_name = "/sys/class/video4linux/video%d/name" % idx
        name = "Camera %d" % idx
        if os.path.exists(sys_name):
            try:
                name = open(sys_name).read().strip() or name
            except OSError:
                pass
        if "metadata" in name.lower() or "decoder" in name.lower() or "encoder" in name.lower():
            continue
        v4l2.append((path, "v4l2", name, 2, 0, 0))
    if not v4l2:
        for path in sorted(glob.glob("/dev/v4l/by-id/*-video-index0")):
            v4l2.append((path, "v4l2", os.path.basename(path), 2, 0, 0))
    return sort_and_label_cameras(v4l2)


def select_initial_camera(cameras, spec):
    """Pick camera index matching `--camera` spec ('back', 'front', index, or substring)."""
    if not cameras:
        return 0
    if not spec:
        return 0
    q = spec.strip().lower()
    if q.isdigit():
        idx = int(q)
        if 0 <= idx < len(cameras):
            return idx
    if q in ("back", "rear"):
        for i, c in enumerate(cameras):
            if c.is_back:
                return i
    if q in ("front", "selfie"):
        for i, c in enumerate(cameras):
            if c.is_front:
                return i
    for i, c in enumerate(cameras):
        if q in c.cid.lower() or q in c.model.lower() or q in c.label.lower():
            return i
    return 0


def rotate_bgr(bgr, rot, cv2_mod):
    """Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle)."""
    rot_i = int(rot) % 360
    if rot_i == 90:
        return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE)
    if rot_i == 180:
        return cv2_mod.rotate(bgr, cv2_mod.ROTATE_180)
    if rot_i == 270:
        return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE)
    return bgr


def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None):
    """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:
        import cv2 as cv2_mod

    arr = np_mod.frombuffer(raw, dtype=np_mod.uint8)
    fmt_u = str(fmt).upper()
    if fmt_u in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"):
        row_px = stride // 4
        img = arr[:height * stride].reshape((height, row_px, 4))[:, :width, :3]
        if "BGR" in fmt_u:
            bgr = np_mod.ascontiguousarray(img[:, :, ::-1])
        else:
            bgr = np_mod.ascontiguousarray(img)
    elif fmt_u in ("RGB888", "BGR888"):
        row_px = stride // 3
        img = arr[:height * stride].reshape((height, row_px, 3))[:, :width, :]
        if fmt_u == "RGB888":
            bgr = np_mod.ascontiguousarray(img[:, :, ::-1])
        else:
            bgr = np_mod.ascontiguousarray(img)
    else:
        raise RuntimeError("unsupported pixel format %s" % fmt)

    return np_mod.ascontiguousarray(rotate_bgr(bgr, rot, cv2_mod))


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

_QUAD_TONE_LUT = None


def _build_tone_lut(np_mod):
    """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):
    global _QUAD_TONE_LUT
    if _QUAD_TONE_LUT is None:
        _QUAD_TONE_LUT = _build_tone_lut(np_mod)
    return _QUAD_TONE_LUT


def find_sensor_subdev(model):
    """Find /dev/v4l-subdevN matching sensor `model`, or None."""
    if not model:
        return None
    want = model.lower()
    for p in sorted(glob.glob("/sys/class/video4linux/v4l-subdev*/name")):
        try:
            with open(p) as fh:
                name = fh.read().strip().lower()
        except OSError:
            continue
        if name == want or name.startswith(want + " "):
            return "/dev/" + os.path.basename(os.path.dirname(p))
    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."""

    def __init__(self, path):
        self.fd = os.open(path, os.O_RDWR)

    def query(self, cid):
        buf = bytearray(68)
        struct.pack_into("<I", buf, 0, cid)
        fcntl.ioctl(self.fd, VIDIOC_QUERYCTRL, buf)
        mn, mx, step, df, _flags = struct.unpack_from("<iiiiI", buf, 40)
        return mn, mx, step, df

    def get(self, cid):
        buf = bytearray(8)
        struct.pack_into("<Ii", buf, 0, cid, 0)
        fcntl.ioctl(self.fd, VIDIOC_G_CTRL, buf)
        return struct.unpack_from("<Ii", buf, 0)[1]

    def set(self, cid, val):
        buf = bytearray(8)
        struct.pack_into("<Ii", buf, 0, cid, int(val))
        fcntl.ioctl(self.fd, VIDIOC_S_CTRL, buf)
        return struct.unpack_from("<Ii", buf, 0)[1]

    def close(self):
        if self.fd >= 0:
            try:
                os.close(self.fd)
            finally:
                self.fd = -1


class QuadSensorAE:
    """Direct V4L2 subdev auto-exposure and gain controller for Raw-only Quad-Bayer capture."""

    def __init__(self, subdev_path, io=None):
        self.io = io if io is not None else _V4L2SubdevIO(subdev_path)
        self._closed = False
        try:
            self.vb_min, self.vb_max, _, _ = self.io.query(V4L2_CID_VBLANK)
            self.exp_min, self.exp_max_now, _, _ = self.io.query(V4L2_CID_EXPOSURE)
            self.ag_min, self.ag_max, _, _ = self.io.query(V4L2_CID_ANALOGUE_GAIN)
            self.init_vblank = self.io.get(V4L2_CID_VBLANK)
            self.init_exp = self.io.get(V4L2_CID_EXPOSURE)
            self.init_ag = self.io.get(V4L2_CID_ANALOGUE_GAIN)
            try:
                self.dg_min, self.dg_max, _, _ = self.io.query(V4L2_CID_DIGITAL_GAIN)
                self.init_dg = self.io.get(V4L2_CID_DIGITAL_GAIN)
                self.has_dgain = True
            except OSError:
                self.dg_min, self.dg_max, self.init_dg, self.has_dgain = 1024, 1024, 1024, False
        except Exception:
            self.io.close()
            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_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
        self.e_min = float(max(20, self.exp_min))
        self.e_max = float(self.exp_lowlight_max) * self.ag_max_x * self.dg_max_x
        self.cur_vblank = self.init_vblank
        self.cur_exp = self.init_exp
        self.cur_ag = self.init_ag
        self.cur_dg = self.init_dg
        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).

        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))
        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 * 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 * 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)
        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)
            ag_x = self.ag_max_x
            dg_x = ev / max(exp * ag_x, 1.0)

        vb = max(self.vb_min, min(vb, self.vb_cap))
        exp = max(self.exp_min, min(exp, self.exp_lowlight_max))
        ag_code = int(round(512.0 * (1.0 - 1.0 / max(ag_x, 1.0))))
        ag_code = max(self.ag_min, min(ag_code, self.ag_max))
        dg_code = int(round(1024.0 * max(dg_x, 1.0))) if self.has_dgain else 1024
        if self.has_dgain:
            dg_code = max(min(1024, self.dg_max), min(dg_code, self.dg_max))
        return vb, exp, ag_code, dg_code

    def _apply_exp_vblank(self, vb, exp):
        """Enforce sensor ordering: raise VBLANK before raising EXPOSURE; shrink EXPOSURE before shrinking VBLANK."""
        if vb > self.cur_vblank:
            self.io.set(V4L2_CID_VBLANK, vb)
            self.io.set(V4L2_CID_EXPOSURE, exp)
        elif vb < self.cur_vblank:
            self.io.set(V4L2_CID_EXPOSURE, exp)
            self.io.set(V4L2_CID_VBLANK, vb)
        else:
            self.io.set(V4L2_CID_EXPOSURE, exp)

    def _apply(self, vb, exp, ag_code, dg_code):
        self._apply_exp_vblank(vb, exp)
        self.io.set(V4L2_CID_ANALOGUE_GAIN, ag_code)
        if self.has_dgain:
            self.io.set(V4L2_CID_DIGITAL_GAIN, dg_code)
        self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg = vb, exp, ag_code, dg_code

    def apply_initial(self):
        self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x)
        vb, exp, ag, dg = self.plan(self.ev_total)
        self._apply(vb, exp, ag, dg)
        self.cooldown = 2

    def update(self, raw_p50, raw_p95):
        """Adjust exposure/gain from raw 0..255 luma stats with pipeline settling cooldown."""
        if self.cooldown > 0:
            self.cooldown -= 1
            return False
        if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0:
            return False
        ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5)))
        if raw_p95 > 240.0:
            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))
        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 = 3 if self.video_mode else 2
            return True
        return False

    def close(self):
        if self._closed:
            return
        self._closed = True
        try:
            if self.has_dgain:
                try:
                    self.io.set(V4L2_CID_DIGITAL_GAIN, self.init_dg)
                except Exception:
                    pass
            try:
                self.io.set(V4L2_CID_ANALOGUE_GAIN, self.init_ag)
            except Exception:
                pass
            try:
                self._apply_exp_vblank(self.init_vblank, self.init_exp)
            except Exception:
                pass
        finally:
            self.io.close()


class ContrastAF:
    """Non-blocking contrast-detection VCM autofocus state machine (coarse + fine sweep)."""

    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

        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, exposure boost, and reusable scratch buffers."""

    def __init__(self, alpha=0.18):
        self.alpha = float(alpha)
        self.initialized = False
        self.black = 0.0
        self.gains = None
        self.boost = 1.0
        self._bgr16_raw_buf = None
        self._bgr16_crop_buf = None
        self._bgr8_buf = None

    def reset(self):
        self.initialized = False
        self.black = 0.0
        self.gains = None
        self.boost = 1.0
        self._bgr16_raw_buf = None
        self._bgr16_crop_buf = None
        self._bgr8_buf = None

    def get_bgr16_raw(self, h, w, np_mod):
        shape = (h, w, 3)
        if self._bgr16_raw_buf is None or self._bgr16_raw_buf.shape != shape:
            self._bgr16_raw_buf = np_mod.empty(shape, dtype=np_mod.uint16)
        return self._bgr16_raw_buf

    def get_bgr16_crop(self, h, w, np_mod):
        shape = (h, w, 3)
        if self._bgr16_crop_buf is None or self._bgr16_crop_buf.shape != shape:
            self._bgr16_crop_buf = np_mod.empty(shape, dtype=np_mod.uint16)
        return self._bgr16_crop_buf

    def get_bgr8(self, h, w, np_mod):
        shape = (h, w, 3)
        if self._bgr8_buf is None or self._bgr8_buf.shape != shape:
            self._bgr8_buf = np_mod.empty(shape, dtype=np_mod.uint8)
        return self._bgr8_buf

    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) // 96)
    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:
        sub_raw = sub16

    black = float(np_mod.clip(np_mod.percentile(sub_raw, 1), 0.0, black_cap))
    f = np_mod.maximum(sub16 - black, 0.0) * (255.0 / max(max_val - black, 1.0))

    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.75, 2.2).astype(np_mod.float32)
    else:
        gains = np_mod.ones(3, dtype=np_mod.float32)

    if raw_p95 < 0.8 and avg < 0.35:
        boost = 1.0
    else:
        boost = float(np_mod.clip(52.0 / max(raw_p50, avg, 0.25), 1.0, 20.0))
        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,
    isp_state=None,
    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()
    use_scratch = (isp_state is not None) and (not high_quality)

    try:
        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 = isp_state.get_bgr16_raw(h4, w4, np_mod) if use_scratch else 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
                if use_scratch:
                    crop_dst = isp_state.get_bgr16_crop(th, tw, np_mod)
                    np_mod.copyto(crop_dst, bgr16[dy:dy + th, dx:dx + tw])
                    bgr16 = crop_dst
                else:
                    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)
    finally:
        del arr


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)

    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]
    scratch_out = None
    if isp is not None:
        if isp_state is not None and not high_quality:
            out = isp_state.get_bgr8(h, w, np_mod)
            scratch_out = out
        else:
            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)

    rot_res = rotate_bgr(out, rot, cv2_mod)
    # Never return an alias to isp_state._bgr8_buf because callers retain frames for preview/video.
    if scratch_out is not None and rot_res is scratch_out:
        res = rot_res.copy()
    else:
        res = np_mod.ascontiguousarray(rot_res)
    if return_stats:
        return res, (raw_p50, raw_p95)
    return res


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,
        isp_state=isp_state,
        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
    buf = np_mod.empty((h, w, 4), dtype=np_mod.uint8)
    buf[:, :, :3] = bgr
    buf[:, :, 3] = 255
    return np_mod.ascontiguousarray(buf)


def set_flash_led(on, brightness=96):
    """Toggle the rear white torch LED via logind SetBrightness (fallback to sysfs)."""
    if not os.path.exists(FLASH_LED_PATH):
        return False
    val = int(brightness) if on else 0
    if val < 0:
        val = 0
    if val > 255:
        val = 255

    try:
        with open(FLASH_LED_PATH, "w") as f:
            f.write(str(val))
        return True
    except OSError:
        pass

    sid = os.environ.get("XDG_SESSION_ID", "").strip()
    if not sid:
        try:
            r = subprocess.run(
                ["loginctl", "list-sessions", "--no-legend"],
                capture_output=True,
                text=True,
                timeout=2,
                check=False,
            )
            uid_s = str(os.getuid())
            for line in r.stdout.splitlines():
                parts = line.split()
                if len(parts) >= 2 and parts[1] == uid_s:
                    sid = parts[0]
                    break
        except Exception:
            sid = ""
    if not sid:
        sid = "auto"

    try:
        r = subprocess.run(
            [
                "busctl",
                "call",
                "org.freedesktop.login1",
                "/org/freedesktop/login1/session/" + sid,
                "org.freedesktop.login1.Session",
                "SetBrightness",
                "ssu",
                "leds",
                "white:flash",
                str(val),
            ],
            capture_output=True,
            text=True,
            timeout=3,
            check=False,
        )
        return r.returncode == 0
    except Exception:
        return False


class QRScanner:
    """Reads QR codes from viewfinder frames with OpenCV's own detectors (no extra packages)."""

    MAX_DIM = 800

    def __init__(self, cv2_mod=None):
        if cv2_mod is None:
            import cv2 as cv2_mod
        self.cv2 = cv2_mod
        # The aruco detector reads small and tilted codes the plain one misses; the plain one does
        # better on dim ones.
        self._detectors = []
        for name in ("QRCodeDetectorAruco", "QRCodeDetector"):
            if hasattr(cv2_mod, name):
                self._detectors.append(getattr(cv2_mod, name)())
        self._centre = False

    def _view(self, bgr):
        """Gray view to scan: the whole frame, or every other time its middle at finer scale."""
        h, w = bgr.shape[:2]
        if self._centre:
            bgr = bgr[h // 4:h - h // 4, w // 4:w - w // 4]
            h, w = bgr.shape[:2]
        self._centre = not self._centre
        scale = self.MAX_DIM / float(max(h, w))
        if scale < 1.0:
            size = (max(1, int(w * scale)), max(1, int(h * scale)))
            bgr = self.cv2.resize(bgr, size, interpolation=self.cv2.INTER_AREA)
        return self.cv2.cvtColor(bgr, self.cv2.COLOR_BGR2GRAY)

    def scan(self, bgr):
        """The text of a QR code in `bgr`, or ""."""
        gray = self._view(bgr)
        for det in self._detectors:
            try:
                text, _, _ = det.detectAndDecode(gray)
            except (self.cv2.error, UnicodeDecodeError):
                continue
            text = text.replace("\0", "").strip()
            if text:
                return text
        return ""


class QRReporter:
    """Says when a scan result is news: a new code, or one that had been out of view a while."""

    FORGET_S = 3.0

    def __init__(self):
        self._text = ""
        self._seen = 0.0

    def update(self, text, now):
        if not text:
            return False
        news = text != self._text or now - self._seen > self.FORGET_S
        self._text = text
        self._seen = now
        return news


def qr_line(text):
    """The worker protocol line for a scanned text (percent-encoded: it may hold anything)."""
    return "qr " + urllib.parse.quote(text, safe="")


def ensure_even_frame(bgr):
    """Crop at most 1 pixel from bottom/right edge so width and height are even for H.264."""
    h, w = bgr.shape[:2]
    ew = w & ~1
    eh = h & ~1
    if ew == w and eh == h:
        return bgr
    return bgr[:eh, :ew]


class MatroskaI420Muxer:
    """Minimal streaming Matroska muxer for VFR raw I420 video frames with 1ms timescale."""

    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(
            "<IiiHH4sIiiII",
            40, self.width, self.height, 1, 12, b"I420", frame_sz, 0, 0, 0, 0,
        )
        video = self._elem(
            b"\xE0",
            self._elem(b"\xB0", self._uint_bytes(self.width))
            + self._elem(b"\xBA", self._uint_bytes(self.height)),
        )
        track = self._elem(
            b"\xAE",
            self._elem(b"\xD7", b"\x01")
            + self._elem(b"\x73\xC5", b"\x01")
            + self._elem(b"\x83", b"\x01")
            + self._elem(b"\x86", b"V_MS/VFW/FOURCC")
            + self._elem(b"\x63\xA2", bih)
            + video,
        )
        tracks = self._elem(b"\x16\x54\xAE\x6B", track)
        seg = b"\x18\x53\x80\x67\x01\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
        return ebml + seg + info + tracks

    def encode_frame(self, i420_bytes, ts_ms):
        """Return bytes to write to Matroska stream for `i420_bytes` at timestamp `ts_ms`."""
        ts = int(ts_ms)
        if ts <= self._last_ts:
            ts = self._last_ts + 1
        self._last_ts = ts

        chunks = []
        if not self._header_sent:
            chunks.append(self.build_header())
            self._header_sent = True

        if self._cluster_ts is None or (ts - self._cluster_ts) >= 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

        self.cv2 = cv2
        self.np = np
        self.libcamera = None
        self.cm = None
        self.cameras = cameras
        self.active_index = initial_index if cameras else -1
        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()
        self._thread = None

        self._cam = None
        self._sc = None
        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._want_focus = None
        self._still_request = None  # (dst_path, burst_count)
        self._still_done = threading.Event()
        self._still_result = (None, None)

        self._rec_lock = threading.Lock()
        self._rec_proc = None
        self._rec_queue = None
        self._rec_thread = None
        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
    def active_camera(self):
        if 0 <= self.active_index < len(self.cameras):
            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

    def is_recording(self):
        with self._rec_lock:
            return self._rec_proc is not None

    def recording_elapsed(self):
        with self._rec_lock:
            if self._rec_proc is None:
                return 0.0
            return max(0.0, time.monotonic() - self._rec_start_mono)

    def start(self):
        if self._thread is not None or not self.cameras:
            return
        self._stop_event.clear()
        self._thread = threading.Thread(target=self._run_loop, name="chandra-cam-worker", daemon=True)
        self._thread.start()

    def stop(self):
        self.stop_video()
        self._stop_event.set()
        if self._thread is not None:
            self._thread.join(timeout=6.0)
            self._thread = None
        set_flash_led(False)

    def switch_camera(self, index):
        if not self.cameras:
            return
        target = index % len(self.cameras)
        self.stop_video()
        if self.cameras[target].is_front:
            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:
                req.reuse(self._reuse_arg)
            except TypeError:
                self._reuse_arg = None
                req.reuse()
        else:
            req.reuse()
        self._cam.queue_request(req)

    def _dma_sync(self, fd, flags):
        try:
            fcntl.ioctl(fd, DMA_BUF_IOCTL_SYNC, struct.pack("<Q", flags))
        except OSError:
            pass

    def _get_mmap(self, plane):
        import mmap
        fd = plane.fd
        entry = self._mapped_fds.get(fd)
        need = int(plane.offset + plane.length)
        if entry is None or entry[1] < need:
            if entry is not None:
                try:
                    entry[0].close()
                except Exception:
                    pass
            mm = mmap.mmap(fd, need, mmap.MAP_SHARED, mmap.PROT_READ)
            self._mapped_fds[fd] = (mm, need)
            return mm
        return entry[0]

    def _close_mmaps(self):
        if self._mapped_fds:
            gc.collect()
        for mm, _sz in self._mapped_fds.values():
            try:
                mm.close()
            except Exception:
                pass
        self._mapped_fds.clear()

    def _open_camera(self, info, role_name="viewfinder", target_sizes=None):
        self._isp_state.reset()
        self._frames_since_open = 0
        self._initial_af_done = False

        if info.backend == "v4l2":
            dev = int(info.cid) if info.cid.isdigit() else info.cid
            cap = self.cv2.VideoCapture(dev, self.cv2.CAP_V4L2)
            if not cap.isOpened():
                cap = self.cv2.VideoCapture(dev)
            if not cap.isOpened():
                raise RuntimeError("failed to open V4L2 camera %s" % info.cid)
            cap.set(self.cv2.CAP_PROP_FRAME_WIDTH, 1280)
            cap.set(self.cv2.CAP_PROP_FRAME_HEIGHT, 960)
            self._v4l2 = cap
            return

        libcamera = _import_libcamera()
        self.libcamera = libcamera
        self.cm = libcamera.CameraManager.singleton()
        reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None)
        self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None

        cam = self.cm.get(info.cid)
        if cam is None:
            raise RuntimeError("camera %s disappeared" % info.cid)
        cam.acquire()
        self._cam = cam
        try:
            self._sc = None
            self._raw_sc = None
            configured = False
            if role_name == "viewfinder" and info.model.lower() in QUAD_BAYER_MODELS:
                subdev = find_sensor_subdev(info.model)
                if subdev:
                    ae = None
                    try:
                        ae = QuadSensorAE(subdev)
                        cfg = cam.generate_configuration([libcamera.StreamRole.Raw])
                        if cfg is not None and len(cfg) >= 1:
                            cfg.validate()
                            cam.configure(cfg)
                            self._raw_sc = cfg.at(0)
                            self._sc = None
                            self._ae = ae
                            configured = True
                    except Exception:
                        if ae is not None:
                            ae.close()
                        self._ae = None
                        self._raw_sc = None

                if not configured:
                    try:
                        cfg = cam.generate_configuration([
                            libcamera.StreamRole.Viewfinder,
                            libcamera.StreamRole.Raw,
                        ])
                        if cfg is not None and len(cfg) >= 2:
                            cfg.at(0).size = libcamera.Size(640, 480)
                            cfg.validate()
                            cam.configure(cfg)
                            self._sc = cfg.at(0)
                            self._raw_sc = cfg.at(1)
                            configured = True
                    except Exception:
                        self._raw_sc = None

            if not configured:
                role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder
                sizes = target_sizes or (PREFERRED_VIEWFINDER_SIZES if role_name == "viewfinder" else PREFERRED_STILL_SIZES)
                chosen_exc = None
                for w, h in sizes:
                    try:
                        cfg = cam.generate_configuration([role])
                        sc = cfg.at(0)
                        sc.size = libcamera.Size(w, h)
                        cfg.validate()
                        cam.configure(cfg)
                        self._sc = sc
                        configured = True
                        break
                    except Exception as exc:
                        chosen_exc = exc
                if not configured:
                    raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc))

            # Pre-map buffers once per camera open for zero-churn DMA-BUF access.
            alloc = libcamera.FrameBufferAllocator(cam)
            self._alloc = alloc
            reqs = []
            if self._sc is not None and self._raw_sc is not None:
                if alloc.allocate(self._sc.stream) <= 0 or alloc.allocate(self._raw_sc.stream) <= 0:
                    raise RuntimeError("failed to allocate camera buffers for %s" % info.label)
                for b0, b1 in zip(alloc.buffers(self._sc.stream), alloc.buffers(self._raw_sc.stream)):
                    self._get_mmap(b0.planes[0])
                    self._get_mmap(b1.planes[0])
                    r = cam.create_request()
                    r.add_buffer(self._sc.stream, b0)
                    r.add_buffer(self._raw_sc.stream, b1)
                    reqs.append(r)
            elif self._raw_sc is not None:
                if alloc.allocate(self._raw_sc.stream) <= 0:
                    raise RuntimeError("failed to allocate raw buffers for %s" % info.label)
                for b in alloc.buffers(self._raw_sc.stream):
                    self._get_mmap(b.planes[0])
                    r = cam.create_request()
                    r.add_buffer(self._raw_sc.stream, b)
                    reqs.append(r)
            else:
                if alloc.allocate(self._sc.stream) <= 0:
                    raise RuntimeError("failed to allocate camera buffers for %s" % info.label)
                for buf in alloc.buffers(self._sc.stream):
                    self._get_mmap(buf.planes[0])
                    r = cam.create_request()
                    r.add_buffer(self._sc.stream, buf)
                    reqs.append(r)
            self._requests = reqs
            self.cm.get_ready_requests()

            start_ctrls = {}
            try:
                if self._raw_sc is None and hasattr(libcamera.controls, "FrameDurationLimits"):
                    if libcamera.controls.FrameDurationLimits in cam.controls:
                        start_ctrls[libcamera.controls.FrameDurationLimits] = (33333, 50000)
            except Exception:
                start_ctrls = {}

            try:
                if start_ctrls:
                    cam.start(start_ctrls)
                else:
                    cam.start()
            except Exception:
                cam.start()
            self._started = True

            if self._ae is not None:
                try:
                    self._ae.apply_initial()
                except Exception:
                    self._ae.close()
                    self._ae = None

            if info.is_back:
                lens_dev = find_lens_subdev(info.model)
                if lens_dev:
                    try:
                        self._af = ContrastAF(lens_dev)
                        if self._saved_focus_pos is not None:
                            self._af.set_position(self._saved_focus_pos)
                            self._initial_af_done = True
                    except Exception:
                        self._af = None

            for r in self._requests:
                cam.queue_request(r)
        except Exception:
            self._close_camera()
            raise

    def _close_camera(self):
        if self._af is not None:
            try:
                self._af.close()
            except Exception:
                pass
            self._af = None

        if self._ae is not None:
            try:
                self._ae.close()
            except Exception:
                pass
            self._ae = None

        if self._v4l2 is not None:
            try:
                self._v4l2.release()
            except Exception:
                pass
            self._v4l2 = None

        if self._cam is not None:
            try:
                if self._started:
                    self._cam.stop()
            except Exception:
                pass
            self._started = False
            if self.cm is not None:
                try:
                    self.cm.get_ready_requests()
                except Exception:
                    pass
            self._close_mmaps()
            self._requests = []
            self._alloc = None
            self._sc = None
            self._raw_sc = None
            try:
                self._cam.release()
            except Exception:
                pass
            self._cam = None

    def _extract_req_ts_ns(self, req, buf):
        try:
            ts = int(buf.metadata.timestamp)
            if ts > 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, 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

        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]
                    plane = buf.planes[0]
                    w = self._raw_sc.size.width
                    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():
                        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,
                                offset=plane.offset,
                                target_size=target_size,
                                high_quality=high_quality,
                                isp_state=None if high_quality else self._isp_state,
                                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]
                    w = self._sc.size.width
                    h = self._sc.size.height
                    stride = self._sc.stride
                    fmt = str(self._sc.pixel_format)
                    ts_ns = self._extract_req_ts_ns(req, buf)
                    mm = self._get_mmap(plane)
                    self._dma_sync(plane.fd, DMA_BUF_SYNC_START_READ)
                    mv = None
                    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:
                        if mv is not None:
                            mv.release()
                            del mv
                        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, 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))
            return

        try:
            while not self._stop_event.is_set():
                # 1. Pending camera switch?
                switch_to = None
                with self._lock:
                    if self._want_switch is not None:
                        switch_to = self._want_switch
                        self._want_switch = None
                if switch_to is not None and switch_to != self.active_index:
                    self._close_camera()
                    self.active_index = switch_to
                    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("Switch failed: %s" % exc)
                        break

                # 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_req = self._still_request
                        self._still_request = None
                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

                # 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, ts_ns = self._read_libcamera_frame(info)
                    if frame is None:
                        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, ts_ns)
                    if self.on_frame:
                        self.on_frame()
        finally:
            self.stop_video()
            self._close_camera()

    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:
                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 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() + 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)
                    if f is not None:
                        captured = f
                        warmup += 1
                        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:
                        self._wait_for_libcamera_event(0.03)
                self._close_camera()
                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:
                    raise RuntimeError("failed to write %s" % dst_path)
                self._still_result = (dst_path, None)
            else:
                frame, _ = self.latest_frame()
                if frame is None:
                    raise RuntimeError("no frame yet")
                os.makedirs(os.path.dirname(dst_path), exist_ok=True)
                ok = self.cv2.imwrite(dst_path, frame, [self.cv2.IMWRITE_JPEG_QUALITY, 95])
                if not ok:
                    raise RuntimeError("failed to write %s" % dst_path)
                self._still_result = (dst_path, None)
        except Exception as exc:
            self._still_result = (None, str(exc))
            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=PREFERRED_VIEWFINDER_SIZES)
                except Exception:
                    pass
        finally:
            self._still_done.set()

    def capture_photo(self, high_res=False, dst_path=None):
        """Save a JPEG photo into ~/Pictures/Camera (or dst_path) and return its path."""
        if dst_path is None:
            os.makedirs(PICTURE_DIR, exist_ok=True)
            stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            dst_path = os.path.join(PICTURE_DIR, "IMG_%s.jpg" % stamp)
            suffix = 1
            while os.path.exists(dst_path):
                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)
            return dst_path

        self._still_done.clear()
        self._still_result = (None, None)
        with self._lock:
            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
        if err:
            raise RuntimeError(err)
        return saved

    def start_video(self, dst_path=None):
        """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()
        if frame is None:
            raise RuntimeError("camera is still warming up")
        even = ensure_even_frame(frame)
        h, w = even.shape[:2]

        if dst_path is None:
            os.makedirs(VIDEO_DIR, exist_ok=True)
            stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            dst_path = os.path.join(VIDEO_DIR, "VID_%s.mp4" % stamp)
            suffix = 1
            while os.path.exists(dst_path):
                dst_path = os.path.join(VIDEO_DIR, "VID_%s_%d.mp4" % (stamp, suffix))
                suffix += 1
        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",
            "matroska",
            "-i",
            "-",
            "-fps_mode",
            "passthrough",
            "-enc_time_base",
            "demux",
            "-video_track_timescale",
            "1000",
            "-c:v",
            "libx264",
            "-preset",
            "superfast",
            "-crf",
            "23",
            "-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=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(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

        wt = threading.Thread(target=writer, name="chandra-cam-rec", daemon=True)
        with self._rec_lock:
            self._rec_proc = proc
            self._rec_queue = q
            self._rec_thread = wt
            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()
        return dst_path

    def _push_video_frame(self, frame, ts_ns=None):
        with self._rec_lock:
            q = self._rec_queue
            proc = self._rec_proc
            if q is None or proc is None or proc.poll() is not None:
                return
        if ts_ns is None:
            ts_ns = time.monotonic_ns()
        item = (frame, int(ts_ns))
        try:
            q.put_nowait(item)
            with self._rec_lock:
                self._rec_frames += 1
        except queue.Full:
            try:
                q.get_nowait()
                with self._rec_lock:
                    self._rec_dropped += 1
            except queue.Empty:
                pass
            try:
                q.put_nowait(item)
                with self._rec_lock:
                    self._rec_frames += 1
            except queue.Full:
                pass

    def stop_video(self):
        """Stop video recording, drain queued frames cleanly, and finalize MP4 container."""
        with self._rec_lock:
            proc = self._rec_proc
            q = self._rec_queue
            wt = self._rec_thread
            path = self._rec_path
            frames = self._rec_frames
            self._rec_proc = None
            self._rec_queue = None
            self._rec_thread = None
            self._rec_path = None
            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 stopped before a fresh frame arrived from _run_loop, emit latest frame so MP4 is valid.
        if frames == 0:
            fb, _ = self.latest_frame()
            if fb is not None and q is not None:
                try:
                    q.put_nowait((fb, time.monotonic_ns()))
                    frames += 1
                except Exception:
                    pass
        if q is not None:
            # Wait briefly for room if queue is completely full so we never drop the sentinel.
            try:
                q.put(None, timeout=1.0)
            except Exception:
                try:
                    q.get_nowait()
                    q.put_nowait(None)
                except Exception:
                    pass
        if wt is not None:
            wt.join(timeout=15.0)
        rc = proc.wait(timeout=15.0)
        if proc.stderr is not None:
            try:
                if rc != 0:
                    err = proc.stderr.read().decode("utf-8", "replace").strip()
                    if err and self.on_error:
                        self.on_error("Video encode error: " + err)
            finally:
                try:
                    proc.stderr.close()
                except Exception:
                    pass
        return path, frames


def list_gallery_photos():
    """Return newest-first list of saved photos in ~/Pictures/Camera."""
    if not os.path.isdir(PICTURE_DIR):
        return []
    files = []
    for name in os.listdir(PICTURE_DIR):
        if name.lower().endswith(IMAGE_EXTS):
            p = os.path.join(PICTURE_DIR, name)
            if os.path.isfile(p):
                files.append(p)
    files.sort(key=lambda p: (os.path.getmtime(p), p), reverse=True)
    return files


def run_worker(cameras, initial_index):
    """Stream Cairo BGRA viewfinder frames to stdout and handle UI commands on stdin."""
    import cv2

    write_lock = threading.Lock()
    has_flash = 1 if os.path.exists(FLASH_LED_PATH) else 0
    stop_flag = threading.Event()

    def emit(line):
        data = (line + "\n").encode("utf-8", "replace")
        with write_lock:
            try:
                sys.stdout.buffer.write(data)
                sys.stdout.buffer.flush()
            except (BrokenPipeError, OSError):
                stop_flag.set()

    def emit_active(info, idx):
        if info is None:
            emit("active -1 0 0 No camera")
        else:
            emit("active %d %d %d %s" % (
                idx,
                1 if info.is_front else 0,
                1 if info.is_back else 0,
                info.label,
            ))

    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()

    qr_on = threading.Event()

    def qr_loop():
        scanner = QRScanner(cv2)
        reporter = QRReporter()
        last_seq = -1
        while not stop_flag.wait(QR_SCAN_INTERVAL_S):
            eng = engine_holder[0]
            if eng is None or not qr_on.is_set() or eng.is_recording():
                continue
            frame, seq = eng.latest_frame()
            if frame is None or seq == last_seq:
                continue
            last_seq = seq
            text = scanner.scan(frame)
            # Switched off while scanning: the result is no longer wanted.
            if qr_on.is_set() and reporter.update(text, time.monotonic()):
                emit(qr_line(text))

    qr_thread = threading.Thread(target=qr_loop, name="chandra-cam-qr", daemon=True)
    qr_thread.start()

    def on_frame():
        if stop_flag.is_set():
            return
        eng = engine_holder[0]
        if eng is None:
            return
        frame, _ = eng.latest_frame()
        if frame is None:
            return
        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)

    emit("info %d %d" % (len(cameras), has_flash))
    emit_active(engine.active_camera, engine.active_index)
    if cameras:
        engine.start()
    else:
        emit("toast No camera connected")

    try:
        while not stop_flag.is_set():
            line = sys.stdin.readline()
            if not line:
                break
            cmd = line.strip()
            if not cmd:
                continue
            if cmd == "quit":
                break
            if cmd == "switch":
                set_flash_led(False)
                engine.cycle_camera()
            elif cmd == "qr 1":
                qr_on.set()
            elif cmd == "qr 0":
                qr_on.clear()
            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"

                def snap_job(hr=high_res):
                    try:
                        p = engine.capture_photo(high_res=hr)
                        emit("saved_photo " + p)
                    except Exception as exc:
                        emit("toast " + str(exc).replace("\n", " "))

                threading.Thread(target=snap_job, daemon=True).start()
            elif cmd == "rec_start":
                try:
                    engine.start_video()
                    emit("rec_state 1")
                except Exception as exc:
                    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 %d %s" % (frames, dur_ms, p))
                except Exception as exc:
                    emit("rec_state 0")
                    emit("toast " + str(exc).replace("\n", " "))
            elif cmd.startswith("flash "):
                want_on = cmd.split(None, 1)[1].strip() in ("1", "on", "true")
                if want_on:
                    if set_flash_led(True):
                        emit("flash 1")
                    else:
                        emit("flash 0")
                        emit("toast Flash control unavailable")
                else:
                    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)
        qr_thread.join(timeout=1.0)
        set_flash_led(False)
    return 0


def launch_ui(args):
    """Execute the native GTK3 + Cairo UI binary pointing back to this worker."""
    repo_ui = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        "build",
        "chandra-camera-ui",
    )
    candidates = [
        os.environ.get("CHANDRA_CAMERA_UI", ""),
        repo_ui,
        "/usr/local/lib/chandra/chandra-camera-ui",
    ]
    ui_bin = next((p for p in candidates if p and os.access(p, os.X_OK)), "")
    if not ui_bin:
        print(
            "chandra-camera: UI binary not found (checked CHANDRA_CAMERA_UI, %s, /usr/local/lib/chandra/chandra-camera-ui)"
            % repo_ui,
            file=sys.stderr,
        )
        return 1

    cmd = [ui_bin, "--worker-exe", os.path.abspath(__file__)]
    if args.camera:
        cmd += ["--camera", args.camera]
    if args.open_gallery:
        cmd.append("--open-gallery")
    os.execv(ui_bin, cmd)


def run_self_test(cameras):
    """Verify multi-camera discovery, switching, JPEG capture, MP4 recording, and clean release."""
    if not cameras:
        print("FAIL: no cameras discovered", file=sys.stderr)
        return 1
    print("Discovered %d camera(s):" % len(cameras))
    for i, c in enumerate(cameras):
        print("  [%d] %s (%s, cid=%s, rot=%d, max_px=%d)" % (i, c.label, c.backend, c.cid, c.rotation, c.max_pixels))

    front_idx = select_initial_camera(cameras, "front")
    engine = CameraEngine(cameras, initial_index=0)
    engine.start()
    try:
        t0 = time.monotonic()
        while time.monotonic() - t0 < 5.0:
            f, seq = engine.latest_frame()
            if f is not None and seq >= 3:
                break
            time.sleep(0.05)
        f0, seq0 = engine.latest_frame()
        if f0 is None:
            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))

        if front_idx != engine.active_index:
            engine.switch_camera(front_idx)
            t0 = time.monotonic()
            while time.monotonic() - t0 < 5.0:
                if engine.active_index == front_idx:
                    f, seq = engine.latest_frame()
                    if f is not None and seq > seq0 + 3:
                        break
                time.sleep(0.05)

        f1, _ = engine.latest_frame()
        if f1 is None or int(f1.max()) == 0:
            raise RuntimeError("active camera %s produced empty/black frame" % engine.active_camera.label)
        print("Active photo camera %s frame: shape=%s mean=%.1f max=%d" % (
            engine.active_camera.label, f1.shape, float(f1.mean()), int(f1.max())
        ))

        photo_path = engine.capture_photo(high_res=False)
        import cv2
        saved_img = cv2.imread(photo_path)
        if saved_img is None or os.path.getsize(photo_path) <= 0:
            raise RuntimeError("invalid captured photo at %s" % photo_path)
        print("Saved JPEG: %s (%d bytes, shape=%s)" % (photo_path, os.path.getsize(photo_path), saved_img.shape))

        video_path = engine.start_video()
        time.sleep(2.0)
        final_video, nframes = engine.stop_video()
        if not final_video or not os.path.exists(final_video) or os.path.getsize(final_video) <= 0 or nframes < 5:
            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))

        if len(cameras) > 1:
            back_target = 0 if engine.active_index != 0 else 1
            _, seq_before_back = engine.latest_frame()
            engine.switch_camera(back_target)
            t0 = time.monotonic()
            ok_back = False
            while time.monotonic() - t0 < 5.0:
                if engine.active_index == back_target:
                    fb, seqb = engine.latest_frame()
                    if fb is not None and seqb > seq_before_back + 1:
                        ok_back = True
                        print("Switched back to %s: shape=%s seq=%d" % (cameras[back_target].label, fb.shape, seqb))
                        break
                time.sleep(0.05)
            if not ok_back:
                raise RuntimeError("timed out switching back to camera %s" % cameras[back_target].label)
    finally:
        engine.stop()

    print("SELF_TEST_OK photo=%s video=%s" % (photo_path, final_video))
    return 0


def parse_args(argv):
    p = argparse.ArgumentParser(prog=APP_ID, description="Chandra Wayland Camera App")
    p.add_argument("--camera", default="", help="Initial camera ('back', 'front', index, or model/id)")
    p.add_argument("--open-gallery", action="store_true", help="Open directly in the in-app gallery")
    p.add_argument("--worker", action="store_true", help="Run stdio frame/control worker for native UI")
    p.add_argument("--self-test", action="store_true", help="Run non-interactive capture & switch self-test")
    p.add_argument("--list-cameras", action="store_true", help="List detected cameras and exit")
    return p.parse_args(argv)


def main(argv=None):
    args = parse_args(sys.argv[1:] if argv is None else argv)
    if args.list_cameras or args.self_test or args.worker:
        cameras = discover_cameras()
        if args.list_cameras:
            for i, c in enumerate(cameras):
                print("%d\t%s\t%s\t%s\trot=%d" % (i, c.label, c.backend, c.cid, c.rotation))
            return 0
        if args.self_test:
            return run_self_test(cameras)
        initial = select_initial_camera(cameras, args.camera)
        return run_worker(cameras, initial_index=initial)
    return launch_ui(args)


if __name__ == "__main__":
    sys.exit(main())
