fix: move capture inference and print hook off camera thread

This commit is contained in:
2026-11-10 15:10:19 +01:00
parent 838becdd70
commit 898ceb5726
4 changed files with 170 additions and 14 deletions

View File

@@ -46,7 +46,13 @@ does not depend on a separate eye detector. It estimates frontal head orientatio
not eye gaze. Small, occluded or strongly tilted faces can still be missed;
validate group-photo accuracy and timings on the target kiosk.
The clean mirrored camera frame is counted once after capture. Debug logs retain
The camera copies and queues the clean mirrored frame after the countdown,
then immediately resumes the feed. A dedicated capture worker loads YuNet,
counts faces once, and calls the print hook sequentially. The bounded job channel
uses nonblocking submission; the next countdown waits until the worker is idle.
Accepted jobs are drained at shutdown. Lighting stays on until the frame snapshot
has been copied and queued, rather than waiting for face counting or printing.
Debug logs retain
candidate boxes, confidence, accepted/rejected counts, intended copies and timing.
The count is passed to an intentionally empty `print_picture` hook. There is no
printer command, image encoding, file output or physical printing yet.
@@ -58,4 +64,9 @@ results after 1.5 seconds. Green (`#84bf65`) means accepted; blue (`#4caee3`) me
rejected for head orientation. Rectangles use mirrored camera coordinates and
share the preview crop, but never enter capture or detector input. Counts are
always recomputed on the captured frame and can differ from the last live sample.
OpenCV remains limited to two threads; actual kiosk latency needs measurement.
All model loading and inference happen on background workers: palm/hand pose,
capture-time faces/print hook, and debug-only live faces. Camera and UI threads
never wait for inference or print scheduling. OpenCV uses one inference thread
per worker to reduce contention on the dual-core kiosk. This removes direct
blocking; actual feed timing still depends on CPU load and camera behavior and
needs measurement on the kiosk.

View File

@@ -1,4 +1,10 @@
use std::time::{Duration, Instant};
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::{Duration, Instant},
};
#[derive(Default)]
enum Phase {
@@ -46,7 +52,7 @@ impl Sequence {
Presentation {
countdown: (3 - elapsed as i32).clamp(1, 3),
// The monitor lights the room: hold white illumination until
// the countdown completes and take_picture() returns.
// the clean frame is captured and queued after the countdown.
flash_opacity: 0.75,
awaiting_release: false,
}
@@ -60,6 +66,81 @@ impl Sequence {
}
}
/// Single background pipeline for capture-time inference and future print scheduling.
/// At most one job is active and one is queued; submission never waits on work.
pub struct Worker {
sender: Option<std::sync::mpsc::SyncSender<opencv::core::Mat>>,
thread: Option<std::thread::JoinHandle<()>>,
pending: Arc<AtomicUsize>,
}
impl Worker {
pub fn new() -> Self {
Self::spawn(|| {
// Load and own the model on the worker too.
let mut detector = crate::faces::Detector::new();
move |frame| match &mut detector {
Ok(detector) => {
if let Err(error) = take_picture(&frame, detector) {
eprintln!("[capture ERROR] Face counting failed: {error}");
}
}
Err(error) => eprintln!("[capture ERROR] Face model unavailable: {error}"),
}
})
}
fn spawn<F, P>(initialize: F) -> Self
where
F: FnOnce() -> P + Send + 'static,
P: FnMut(opencv::core::Mat) + 'static,
{
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
let pending = Arc::new(AtomicUsize::new(0));
let worker_pending = Arc::clone(&pending);
let thread = std::thread::spawn(move || {
let mut process = initialize();
while let Ok(frame) = receiver.recv() {
process(frame);
worker_pending.fetch_sub(1, Ordering::Release);
}
});
Self {
sender: Some(sender),
thread: Some(thread),
pending,
}
}
/// Takes ownership of a clean frame snapshot. Returns it when the bounded
/// queue is full/disconnected, allowing the caller to report rejection.
pub fn submit(
&self,
frame: opencv::core::Mat,
) -> Result<(), std::sync::mpsc::TrySendError<opencv::core::Mat>> {
self.pending.fetch_add(1, Ordering::Relaxed);
let result = self.sender.as_ref().unwrap().try_send(frame);
if result.is_err() {
self.pending.fetch_sub(1, Ordering::Release);
}
result
}
pub fn is_idle(&self) -> bool {
self.pending.load(Ordering::Acquire) == 0
}
}
impl Drop for Worker {
fn drop(&mut self) {
// Only shutdown waits: drain accepted jobs before releasing their frames.
self.sender.take();
if self.thread.take().unwrap().join().is_err() {
eprintln!("[capture ERROR] Capture/print worker panicked");
}
}
}
/// Count the captured, clean selfie frame and pass the intended copies to the
/// print hook. Printer integration is intentionally left unimplemented.
pub fn take_picture(
@@ -74,12 +155,56 @@ pub fn take_picture(
fn print_picture(_frame: &opencv::core::Mat, _copies: usize) {
// TODO: Implement printing.
// TO AGENT: KEEP THIS BLANK UNTIL SPECIFICALLY ASKED TO IMPLEMENT!!!
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slow_processing_never_blocks_submission_and_shutdown_drains_jobs() {
use opencv::{
core::{CV_8UC1, Mat, Scalar},
prelude::*,
};
use std::sync::mpsc::{self, TrySendError};
let caller = std::thread::current().id();
let (started_tx, started_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let (processed_tx, processed_rx) = mpsc::channel();
let worker = Worker::spawn(move || {
assert_ne!(std::thread::current().id(), caller);
let mut first = true;
move |frame: Mat| {
if first {
started_tx.send(()).unwrap();
release_rx.recv().unwrap();
first = false;
}
processed_tx
.send(*frame.at_2d::<u8>(0, 0).unwrap())
.unwrap();
}
});
let frame =
|value| Mat::new_rows_cols_with_default(1, 1, CV_8UC1, Scalar::all(value)).unwrap();
assert!(worker.is_idle());
worker.submit(frame(1.0)).unwrap();
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert!(!worker.is_idle());
// The first job is deliberately blocked, but enqueueing and rejecting
// excess jobs must both return before it is allowed to finish.
worker.submit(frame(2.0)).unwrap();
assert!(matches!(
worker.submit(frame(3.0)),
Err(TrySendError::Full(_))
));
release_tx.send(()).unwrap();
drop(worker);
assert_eq!(processed_rx.into_iter().collect::<Vec<_>>(), vec![1, 2]);
}
#[test]
fn flash_countdown_and_single_capture_then_release() {
let start = Instant::now();

View File

@@ -166,11 +166,17 @@ pub struct LivePreview {
impl LivePreview {
pub fn new() -> opencv::Result<Self> {
use std::sync::{Arc, Mutex, mpsc};
let mut detector = Detector::new()?;
let (sender, receiver) = mpsc::sync_channel::<Mat>(0);
let result = Arc::new(Mutex::new((Instant::now(), Vec::new())));
let worker_result = Arc::clone(&result);
let worker = std::thread::spawn(move || {
let mut detector = match Detector::new() {
Ok(detector) => detector,
Err(error) => {
eprintln!("[faces ERROR] Could not load debug face model: {error}");
return;
}
};
while let Ok(frame) = receiver.recv() {
let started = Instant::now();
let faces = detector.detect(&frame, false).unwrap_or_else(|error| {

View File

@@ -34,7 +34,9 @@ struct PreviewFrame {
}
fn main() -> Result<(), Box<dyn Error>> {
core::set_num_threads(2)?;
// One OpenCV inference thread per worker leaves CPU time for the camera/UI
// on the dual-core kiosk instead of each model spawning two busy threads.
core::set_num_threads(1)?;
if let Err(error) = diagnostics::log_runtime() {
eprintln!("Failed to read OpenCV runtime diagnostics: {error}");
}
@@ -46,8 +48,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let (mut cam, mut frame) = camera::wait_until_ready(&mut camera_log)?;
mirror_frame(&mut frame)?;
let mut detector = palm::Detector::new()?;
let mut face_detector = faces::Detector::new()?;
let capture_worker = capture::Worker::new();
#[cfg(debug_assertions)]
let mut live_faces = faces::LivePreview::new()?;
let ui = AppWindow::new()?;
@@ -70,6 +71,13 @@ fn main() -> Result<(), Box<dyn Error>> {
// A rendezvous channel drops samples while inference is busy, avoiding a backlog.
let (detection_tx, detection_rx) = mpsc::sync_channel::<Mat>(0);
let detection_worker = thread::spawn(move || {
let mut detector = match palm::Detector::new() {
Ok(detector) => detector,
Err(error) => {
eprintln!("[detection ERROR] Could not load palm/hand models: {error}");
return;
}
};
let mut inference_log = diagnostics::SlowLog::new(
"palm + open-hand detection",
palm::DETECTION_INTERVAL,
@@ -123,14 +131,20 @@ fn main() -> Result<(), Box<dyn Error>> {
live_faces.sample(&frame)?;
let mut tracker_guard = tracker.lock().unwrap();
let hand_detected = tracker_guard.has_palm(now);
let take_picture = sequence.tick(tracker_guard.complete(now), hand_detected, now);
// Wait to start another countdown while a capture/print job is
// pending. The live preview and palm tracking keep running.
let take_picture = sequence.tick(
tracker_guard.complete(now) && capture_worker.is_idle(),
hand_detected,
now,
);
if take_picture {
// Release the palm tracker lock while analyzing the captured frame.
drop(tracker_guard);
if let Err(error) = capture::take_picture(&frame, &mut face_detector) {
eprintln!("[capture ERROR] Face counting failed: {error}");
// The snapshot is the capture: lighting can end after this copy.
// Face counting and the empty print hook run on their own worker.
let snapshot = frame.try_clone()?;
if let Err(error) = capture_worker.submit(snapshot) {
eprintln!("[capture ERROR] Capture not queued: {error}");
}
tracker_guard = tracker.lock().unwrap();
}
if sequence.tracking() {
tracker_guard.draw(&mut frame, now)?;