Files
winf-photobooth-app/src/capture.rs

204 lines
6.5 KiB
Rust

use std::time::{Duration, Instant};
#[derive(Default)]
enum Phase {
#[default]
Tracking,
Countdown(Instant),
AwaitingRelease,
}
#[derive(Default)]
pub struct Sequence {
phase: Phase,
}
#[derive(Default)]
pub struct Presentation {
pub countdown: i32,
pub flash_opacity: f32,
pub awaiting_release: bool,
}
impl Sequence {
/// Returns true exactly once when a countdown finishes, even if frames skip.
pub fn tick(&mut self, complete: bool, hand_present: bool, now: Instant) -> bool {
match self.phase {
Phase::Tracking if complete => self.phase = Phase::Countdown(now),
Phase::Countdown(start) if now.duration_since(start) >= Duration::from_secs(3) => {
self.phase = Phase::AwaitingRelease;
return true;
}
Phase::AwaitingRelease if !hand_present => self.phase = Phase::Tracking,
_ => {}
}
false
}
pub fn tracking(&self) -> bool {
matches!(self.phase, Phase::Tracking)
}
pub fn presentation(&self, now: Instant) -> Presentation {
match self.phase {
Phase::Countdown(start) => {
let elapsed = now.duration_since(start).as_secs_f32();
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.
flash_opacity: 0.75,
awaiting_release: false,
}
}
Phase::AwaitingRelease => Presentation {
awaiting_release: true,
..Default::default()
},
Phase::Tracking => Presentation::default(),
}
}
}
/// Submit the clean, mirrored camera frame to the default CUPS printer.
/// JPEG travels over stdin, so captured photos are never left in temporary files.
pub fn take_picture(
frame: &opencv::core::Mat,
detector: &mut crate::faces::Detector,
) -> Result<(), Box<dyn std::error::Error>> {
use opencv::{core::Vector, imgcodecs};
let copies = detector.count(frame)?;
if copies == 0 {
eprintln!("[capture DEBUG] No frontal faces; skipping print job");
return Ok(());
}
let mut jpeg = Vector::<u8>::new();
if !imgcodecs::imencode(".jpg", frame, &mut jpeg, &Vector::new())? {
return Err("Could not encode captured image".into());
}
submit_print(
jpeg.as_slice(),
copies,
&mut std::process::Command::new("lp"),
)
}
fn submit_print(
jpeg: &[u8],
copies: usize,
command: &mut std::process::Command,
) -> Result<(), Box<dyn std::error::Error>> {
use std::{io::Write, process::Stdio};
let mut child = command
.args([
"-n",
&copies.to_string(),
"-t",
"winf photobooth",
"-o",
"fit-to-page",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let written = child
.stdin
.take()
.ok_or("Printer stdin unavailable")?
.write_all(jpeg);
// Reap lp even if writing fails; never retry an ambiguously submitted job.
let output = child.wait_with_output()?;
if !output.status.success() {
return Err(format!(
"lp failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr)
)
.into());
}
written?;
eprintln!(
"[capture DEBUG] Submitted copies={copies}: {}",
String::from_utf8_lossy(&output.stdout).trim()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn printer_receives_copy_count_and_image_and_reports_failure() {
use std::process::Command;
let mut printer = Command::new("sh");
printer.args(["-c", r#"test "$1" = -n && test "$2" = 3 && test "$4" = 'winf photobooth' && test "$6" = fit-to-page && test "$(cat)" = photo"#, "mock-lp"]);
submit_print(b"photo", 3, &mut printer).unwrap();
let mut failing = Command::new("sh");
failing.args(["-c", "cat >/dev/null; echo unavailable >&2; exit 1"]);
assert!(
submit_print(b"photo", 2, &mut failing)
.unwrap_err()
.to_string()
.contains("unavailable")
);
}
#[test]
fn flash_countdown_and_single_capture_then_release() {
let start = Instant::now();
let mut sequence = Sequence::default();
assert!(!sequence.tick(false, true, start));
assert!(sequence.tracking());
assert!(!sequence.tick(true, true, start));
assert!(!sequence.tracking());
assert_eq!(sequence.presentation(start).countdown, 3);
assert_eq!(sequence.presentation(start).flash_opacity, 0.75);
assert_eq!(
sequence
.presentation(start + Duration::from_millis(200))
.flash_opacity,
0.75
);
for (ms, number) in [(999, 3), (1000, 2), (1999, 2), (2000, 1), (2999, 1)] {
let now = start + Duration::from_millis(ms);
// Lowering the hand must not cancel an already-started countdown.
assert!(!sequence.tick(false, false, now));
assert_eq!(sequence.presentation(now).countdown, number);
assert_eq!(sequence.presentation(now).flash_opacity, 0.75);
}
assert!(sequence.tick(true, true, start + Duration::from_secs(3)));
assert!(
sequence
.presentation(start + Duration::from_secs(3))
.awaiting_release
);
assert_eq!(
sequence
.presentation(start + Duration::from_secs(3))
.countdown,
0
);
assert_eq!(
sequence
.presentation(start + Duration::from_secs(3))
.flash_opacity,
0.0
);
assert!(!sequence.tick(true, true, start + Duration::from_secs(4)));
assert!(!sequence.tracking());
assert!(!sequence.tick(false, false, start + Duration::from_secs(5)));
assert!(sequence.tracking());
}
#[test]
fn delayed_frame_still_finishes_only_once() {
let now = Instant::now();
let mut sequence = Sequence::default();
sequence.tick(true, true, now);
assert!(sequence.tick(false, false, now + Duration::from_secs(10)));
assert!(!sequence.tick(false, false, now + Duration::from_secs(11)));
}
}