A mirrored 8x4 cell sprite, 72 dots high on 80 mm paper, is printed centred below the quote and differs per copy. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
244 lines
8.5 KiB
Rust
244 lines
8.5 KiB
Rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
|
|
|
use std::{
|
|
error::Error,
|
|
sync::{
|
|
Arc, Mutex,
|
|
atomic::{AtomicBool, Ordering},
|
|
mpsc,
|
|
},
|
|
thread,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use opencv::{
|
|
core::{self, Mat},
|
|
imgproc,
|
|
prelude::*,
|
|
};
|
|
use slint::{Rgb8Pixel, SharedPixelBuffer};
|
|
|
|
slint::include_modules!();
|
|
|
|
mod artwork;
|
|
mod camera;
|
|
mod capture;
|
|
mod diagnostics;
|
|
mod faces;
|
|
mod hand_pose;
|
|
mod palm;
|
|
mod printer;
|
|
mod quotes;
|
|
|
|
struct PreviewFrame {
|
|
buffer: SharedPixelBuffer<Rgb8Pixel>,
|
|
hand_detected: bool,
|
|
presentation: capture::Presentation,
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
// Load `.env` before any thread starts, since it sets process variables.
|
|
// Values already present in the real environment take precedence.
|
|
match dotenvy::dotenv() {
|
|
Ok(path) => eprintln!("[config INFO] Loaded {}", path.display()),
|
|
Err(error) if error.not_found() => {}
|
|
Err(error) => eprintln!("[config ERROR] Could not load .env: {error}"),
|
|
}
|
|
// 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}");
|
|
}
|
|
let mut camera_log = diagnostics::SlowLog::new(
|
|
"camera read",
|
|
Duration::from_millis(100),
|
|
"Check camera passthrough and camera frame rate.",
|
|
);
|
|
let (mut cam, mut frame) = camera::wait_until_ready(&mut camera_log)?;
|
|
mirror_frame(&mut frame)?;
|
|
|
|
let capture_worker = capture::Worker::new();
|
|
#[cfg(debug_assertions)]
|
|
let mut live_faces = faces::LivePreview::new()?;
|
|
let ui = AppWindow::new()?;
|
|
|
|
ui.window()
|
|
.on_close_requested(|| slint::CloseRequestResponse::KeepWindowShown);
|
|
|
|
let latest_frame = Arc::new(Mutex::new(Some(PreviewFrame {
|
|
buffer: frame_to_buffer(&frame)?,
|
|
hand_detected: false,
|
|
presentation: capture::Presentation::default(),
|
|
})));
|
|
let running = Arc::new(AtomicBool::new(true));
|
|
|
|
let worker_frame = Arc::clone(&latest_frame);
|
|
let worker_running = Arc::clone(&running);
|
|
|
|
let tracker = Arc::new(Mutex::new(palm::Tracker::default()));
|
|
let detection_tracker = Arc::clone(&tracker);
|
|
// 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,
|
|
"Detection exceeds the 250 ms sampling budget; check model-stage warnings.",
|
|
);
|
|
let mut gap_log = diagnostics::SlowLog::new(
|
|
"detection result interval",
|
|
palm::STALE_AFTER,
|
|
"Results are at least 750 ms apart: the tracker expires and the steadiness timer restarts.",
|
|
);
|
|
let mut last_result: Option<Instant> = None;
|
|
while let Ok(sample) = detection_rx.recv() {
|
|
let result = match inference_log.run(|| detector.detect(&sample)) {
|
|
Ok(palm) => palm,
|
|
Err(error) => {
|
|
eprintln!("Palm detection error: {error}");
|
|
None
|
|
}
|
|
};
|
|
let now = Instant::now();
|
|
if let Some(previous) = last_result {
|
|
gap_log.record(now.duration_since(previous));
|
|
}
|
|
last_result = Some(now);
|
|
detection_tracker.lock().unwrap().update(result, now);
|
|
}
|
|
});
|
|
|
|
let worker = thread::spawn(move || -> opencv::Result<()> {
|
|
let mut processing_log = diagnostics::SlowLog::new(
|
|
"preview processing",
|
|
Duration::from_millis(100),
|
|
"Includes tracker lock, circle drawing and RGB conversion; excludes camera read.",
|
|
);
|
|
let mut sequence = capture::Sequence::default();
|
|
let mut last_detection = Instant::now() - palm::DETECTION_INTERVAL;
|
|
while worker_running.load(Ordering::Relaxed) {
|
|
if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() {
|
|
eprintln!("Camera stopped providing frames");
|
|
break;
|
|
}
|
|
|
|
let now = Instant::now();
|
|
// Use the same selfie coordinates for detection and the preview.
|
|
mirror_frame(&mut frame)?;
|
|
if now.duration_since(last_detection) >= palm::DETECTION_INTERVAL {
|
|
let _ = detection_tx.try_send(frame.try_clone()?);
|
|
last_detection = now;
|
|
}
|
|
#[cfg(debug_assertions)]
|
|
live_faces.sample(&frame)?;
|
|
let mut tracker_guard = tracker.lock().unwrap();
|
|
let hand_detected = tracker_guard.has_palm(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 {
|
|
// The snapshot is the capture: lighting can end after this copy.
|
|
// Face counting and thermal printing 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}");
|
|
}
|
|
}
|
|
if sequence.tracking() {
|
|
tracker_guard.draw(&mut frame, now)?;
|
|
}
|
|
drop(tracker_guard);
|
|
// Draw only after capture and palm sampling so printed photos and
|
|
// detector inputs never contain debug rectangles.
|
|
#[cfg(debug_assertions)]
|
|
live_faces.draw(&mut frame)?;
|
|
let preview = PreviewFrame {
|
|
buffer: frame_to_buffer(&frame)?,
|
|
hand_detected,
|
|
presentation: sequence.presentation(now),
|
|
};
|
|
|
|
processing_log.record(now.elapsed());
|
|
|
|
// Publish image and presentation together so a countdown frame never
|
|
// accidentally contains the palm circle from an older capture frame.
|
|
*worker_frame.lock().unwrap() = Some(preview);
|
|
}
|
|
|
|
Ok(())
|
|
});
|
|
|
|
let ui_handle = ui.as_weak();
|
|
let timer = slint::Timer::default();
|
|
|
|
timer.start(
|
|
slint::TimerMode::Repeated,
|
|
Duration::from_millis(33),
|
|
move || {
|
|
let preview = latest_frame.lock().unwrap().take();
|
|
|
|
if let (Some(app), Some(preview)) = (ui_handle.upgrade(), preview) {
|
|
app.set_video_frame(slint::Image::from_rgb8(preview.buffer));
|
|
app.set_hand_detected(preview.hand_detected);
|
|
app.set_countdown(preview.presentation.countdown);
|
|
app.set_flash_opacity(preview.presentation.flash_opacity);
|
|
app.set_awaiting_release(preview.presentation.awaiting_release);
|
|
}
|
|
},
|
|
);
|
|
|
|
// Keep `timer` alive while the interface is running.
|
|
let result = ui.run();
|
|
|
|
timer.stop();
|
|
running.store(false, Ordering::Relaxed);
|
|
|
|
// Wait for the current camera read to finish and release the camera.
|
|
match worker.join() {
|
|
Ok(Ok(())) => {}
|
|
Ok(Err(error)) => eprintln!("Capture error: {error}"),
|
|
Err(_) => eprintln!("Capture thread panicked"),
|
|
}
|
|
|
|
if detection_worker.join().is_err() {
|
|
eprintln!("Palm detection thread panicked");
|
|
}
|
|
|
|
result?;
|
|
Ok(())
|
|
}
|
|
|
|
fn mirror_frame(frame: &mut Mat) -> opencv::Result<()> {
|
|
let mut mirrored = Mat::default();
|
|
core::flip(frame, &mut mirrored, 1)?;
|
|
*frame = mirrored;
|
|
Ok(())
|
|
}
|
|
|
|
fn frame_to_buffer(frame: &Mat) -> opencv::Result<SharedPixelBuffer<Rgb8Pixel>> {
|
|
let mut rgb = Mat::default();
|
|
|
|
imgproc::cvt_color_def(frame, &mut rgb, imgproc::COLOR_BGR2RGB)?;
|
|
|
|
// Ensure the bytes are contiguous.
|
|
let rgb = rgb.try_clone()?;
|
|
|
|
Ok(SharedPixelBuffer::<Rgb8Pixel>::clone_from_slice(
|
|
rgb.data_bytes()?,
|
|
rgb.cols() as u32,
|
|
rgb.rows() as u32,
|
|
))
|
|
}
|