"""Background capture worker that feeds a FrameBuffer.""" from __future__ import annotations import threading import time from typing import Optional from .buffer import FrameBuffer from .config import CaptureConfig, CaptureHealth, CaptureMode from .source import CaptureSource, is_live_camera, normalize_source class CaptureWorker: """One thread per live camera: read → publish → optional reconnect.""" def __init__( self, source: CaptureSource, buffer: Optional[FrameBuffer] = None, ): self.source = source self.config: CaptureConfig = source.config self.buffer = buffer or FrameBuffer( mode=self.config.mode, maxsize=self.config.queue_size, overflow=self.config.overflow, ) self._thread: Optional[threading.Thread] = None self._running = False self._last_consumed_seq = -1 @property def running(self) -> bool: return self._running def start(self) -> None: if self._thread is not None: return if not self.source.is_open(): self.source.open() self._running = True self._thread = threading.Thread(target=self._loop, daemon=True, name="orisys-capture") self._thread.start() if self.config.verbose: mode = self.config.mode.value if isinstance(self.config.mode, CaptureMode) else self.config.mode print(f"Capture worker started (mode={mode}).") def stop(self, timeout: float = 1.0) -> None: self._running = False if self._thread is not None: self._thread.join(timeout=timeout) self._thread = None self.buffer.clear() def close(self) -> None: self.stop() self.source.release() def read(self, *, copy: bool = True, wait_s: float = 1.0) -> tuple[bool, object]: """Read according to configured mode; mirrors Sensor._read_frame semantics.""" if not self._running: ok, frame = self.source.read_raw() return ok, frame if self.config.mode == CaptureMode.QUEUE: ok, frame, seq = self.buffer.read_next(copy=copy, wait_s=wait_s) else: # Startup race: wait briefly for first frame. wait = wait_s if wait_s > 0 else 1.0 ok, frame, seq = self.buffer.read_latest(copy=copy, wait_s=wait) if ok: self._last_consumed_seq = seq return ok, frame def _loop(self) -> None: while self._running: if self.source.should_reconnect(): if not self.source.reconnect(): # Back off a bit before retrying the should_reconnect check. time.sleep(0.05) if self.source.status.health == CaptureHealth.FAILED: time.sleep(0.2) continue ok, frame = self.source.read_raw() if not ok or frame is None: if self.source.should_reconnect(): continue time.sleep(0.001) continue before_dropped = self.buffer.dropped_frames seq = self.buffer.publish(frame) after_dropped = self.buffer.dropped_frames if after_dropped > before_dropped: self.source.note_dropped(after_dropped - before_dropped) self.source.note_published(seq) def open_capture( config: CaptureConfig, *, factory=None, start_worker: Optional[bool] = None, ) -> CaptureWorker: """Open a capture source and optionally start its worker thread. For live cameras, the worker starts by default (``config.start_worker``). File/video sources stay synchronous unless ``start_worker=True``. """ source = CaptureSource(config, factory=factory) source.open() buffer = FrameBuffer( mode=config.mode, maxsize=config.queue_size, overflow=config.overflow, ) worker = CaptureWorker(source, buffer) should_start = config.start_worker if start_worker is None else start_worker live = is_live_camera(normalize_source(config.source)) if should_start and live: worker.start() return worker