Compare commits
18 Commits
085a5e9cc0
...
printer-ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d06077a257 | ||
|
|
1ff006bc3c | ||
|
|
f406b36c5f | ||
|
|
181a0512bd | ||
|
|
c7af3e320b | ||
|
|
b71e2b32e6 | ||
|
|
8c43984652 | ||
|
|
fb5ce525bb | ||
|
|
c28428a2f3 | ||
|
|
4fb2ad7757 | ||
|
|
a2b83744db | ||
|
|
eae81bb052 | ||
|
|
898ceb5726 | ||
|
|
838becdd70 | ||
|
|
9cf760e7a6 | ||
|
|
6437261a65 | ||
|
|
994c78cc26 | ||
|
|
2e21946300 |
24
.env
Normal file
24
.env
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Photobooth configuration, loaded from the directory the app is started from.
|
||||||
|
# Variables already set in the environment (e.g. by systemd) take precedence.
|
||||||
|
# Every variable is optional; the values below are the built-in defaults.
|
||||||
|
|
||||||
|
# Thermal printer (ESC/POS). Set to an empty value to disable printing.
|
||||||
|
# A device path for USB/serial printers, or tcp://host[:port] for network
|
||||||
|
# printers (port defaults to 9100).
|
||||||
|
PHOTOBOOTH_PRINTER=/dev/usb/lp0
|
||||||
|
|
||||||
|
# Printable width in dots: 576 for 80 mm paper (384 for 58 mm).
|
||||||
|
PHOTOBOOTH_PRINTER_DOTS=576
|
||||||
|
|
||||||
|
# Mid-tone brightening before dithering, offsetting thermal dot gain
|
||||||
|
# (1.8-2.5 is typical; 1 disables it).
|
||||||
|
PHOTOBOOTH_PRINTER_GAMMA=2.0
|
||||||
|
|
||||||
|
# Head energy in percent of rated (70-130) and print speed: quality (120 mm/s),
|
||||||
|
# low (150), silent (180) or high (200). Both are SII RP-D10 commands (DC2 ~
|
||||||
|
# and GS s); the Birch 0CP-Q3 in the booth misparses either one and then prints
|
||||||
|
# the photo as two metres of text, so leave both empty unless the printer is
|
||||||
|
# known to understand them.
|
||||||
|
PHOTOBOOTH_PRINTER_DENSITY=
|
||||||
|
|
||||||
|
PHOTOBOOTH_PRINTER_SPEED=
|
||||||
8
Cargo.lock
generated
8
Cargo.lock
generated
@@ -991,6 +991,12 @@ dependencies = [
|
|||||||
"litrs",
|
"litrs",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dotenvy"
|
||||||
|
version = "0.15.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "downcast-rs"
|
name = "downcast-rs"
|
||||||
version = "1.2.1"
|
version = "1.2.1"
|
||||||
@@ -5444,6 +5450,8 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
|||||||
name = "winf-photobooth-app"
|
name = "winf-photobooth-app"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"chrono",
|
||||||
|
"dotenvy",
|
||||||
"opencv",
|
"opencv",
|
||||||
"slint",
|
"slint",
|
||||||
"slint-build",
|
"slint-build",
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] }
|
||||||
|
dotenvy = "0.15.7"
|
||||||
opencv = "0.101.1"
|
opencv = "0.101.1"
|
||||||
slint = {
|
slint = {
|
||||||
version = "1.18.1",
|
version = "1.18.1",
|
||||||
|
|||||||
@@ -21,3 +21,52 @@ Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models
|
|||||||
SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
|
SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
|
||||||
|
|
||||||
`src/hand_pose.rs` rotates and crops the detected hand, requires at least 0.65 hand confidence, and checks all five fingers for extension using 3D landmarks. Finger extension tolerates natural curvature and a relaxed thumb while rejecting curled fingers and fists. Rejected poses reset the dwell/progress timer; the outline persists for up to 750 ms after the last accepted sample to avoid flicker. This verifies an open hand, not whether the palm side rather than the back faces the camera. Thresholds may need tuning for the camera and viewing distance.
|
`src/hand_pose.rs` rotates and crops the detected hand, requires at least 0.65 hand confidence, and checks all five fingers for extension using 3D landmarks. Finger extension tolerates natural curvature and a relaxed thumb while rejecting curled fingers and fists. Rejected poses reset the dwell/progress timer; the outline persists for up to 750 ms after the last accepted sample to avoid flicker. This verifies an open hand, not whether the palm side rather than the back faces the camera. Thresholds may need tuning for the camera and viewing distance.
|
||||||
|
|
||||||
|
# Capture face counting
|
||||||
|
|
||||||
|
Faces are detected with OpenCV YuNet (`face_detection_yunet_2023mar.onnx`),
|
||||||
|
replacing the Haar face and eye cascades. The 228 KiB ONNX model is embedded in
|
||||||
|
the executable, loaded once, and run with OpenCV DNN on CPU. OpenCV 4.8 or newer
|
||||||
|
with DNN and FaceDetectorYN buffer loading is required (tested with 4.10).
|
||||||
|
|
||||||
|
Source: https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet
|
||||||
|
|
||||||
|
Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx
|
||||||
|
|
||||||
|
SHA-256: `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4`
|
||||||
|
|
||||||
|
License: MIT, reproduced in `YUNET_LICENSE`.
|
||||||
|
|
||||||
|
Images retain their aspect ratio, with the longest edge resized to 320 px and
|
||||||
|
black padding to 320×320. Confidence threshold is 0.8, NMS threshold 0.3 and top K
|
||||||
|
500. Predicted eye and nose landmarks filter strongly turned faces: the nose
|
||||||
|
projection must fall within the central 70% of the eye line, with eye separation
|
||||||
|
at least 23% of the face width. This tolerates roll and mirrored coordinates and
|
||||||
|
does not depend on a separate eye detector. It estimates frontal head orientation,
|
||||||
|
not eye gaze. Small, occluded or strongly tilted faces can still be missed;
|
||||||
|
validate group-photo accuracy and timings on the target kiosk.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Face rectangles and live face inference are enabled only in debug builds
|
||||||
|
(`cargo run`); release builds (`cargo run --release`) have neither. The debug
|
||||||
|
worker samples at most twice per second, drops samples while busy, and expires
|
||||||
|
results after 1.5 seconds. Green (`#84bf65`) means accepted; blue (`#4caee3`) means
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
|||||||
21
models/YUNET_LICENSE
Normal file
21
models/YUNET_LICENSE
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2020 Shiqi Yu <shiqi.yu@gmail.com>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
BIN
models/face_detection_yunet_2023mar.onnx
Normal file
BIN
models/face_detection_yunet_2023mar.onnx
Normal file
Binary file not shown.
222
src/capture.rs
222
src/capture.rs
@@ -1,4 +1,14 @@
|
|||||||
use std::time::{Duration, Instant};
|
use std::{
|
||||||
|
path::Path,
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
},
|
||||||
|
thread,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use opencv::prelude::MatTraitConst;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
enum Phase {
|
enum Phase {
|
||||||
@@ -25,7 +35,7 @@ impl Sequence {
|
|||||||
pub fn tick(&mut self, complete: bool, hand_present: bool, now: Instant) -> bool {
|
pub fn tick(&mut self, complete: bool, hand_present: bool, now: Instant) -> bool {
|
||||||
match self.phase {
|
match self.phase {
|
||||||
Phase::Tracking if complete => self.phase = Phase::Countdown(now),
|
Phase::Tracking if complete => self.phase = Phase::Countdown(now),
|
||||||
Phase::Countdown(start) if now.duration_since(start) >= Duration::from_secs(3) => {
|
Phase::Countdown(start) if now.duration_since(start) >= Duration::from_secs(5) => {
|
||||||
self.phase = Phase::AwaitingRelease;
|
self.phase = Phase::AwaitingRelease;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -44,10 +54,10 @@ impl Sequence {
|
|||||||
Phase::Countdown(start) => {
|
Phase::Countdown(start) => {
|
||||||
let elapsed = now.duration_since(start).as_secs_f32();
|
let elapsed = now.duration_since(start).as_secs_f32();
|
||||||
Presentation {
|
Presentation {
|
||||||
countdown: (3 - elapsed as i32).clamp(1, 3),
|
countdown: (5 - elapsed as i32).clamp(1, 5),
|
||||||
// The monitor lights the room: hold white illumination until
|
// 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,
|
flash_opacity: 0.95,
|
||||||
awaiting_release: false,
|
awaiting_release: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,14 +70,180 @@ impl Sequence {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn take_picture() {
|
/// Single background pipeline for capture-time inference and future print scheduling.
|
||||||
// TODO: Take a picture here after the countdown. No capture or file writes yet.
|
/// 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();
|
||||||
|
let printer = crate::printer::Printer::from_env();
|
||||||
|
match &printer {
|
||||||
|
Some(printer) => eprintln!("[capture INFO] Printing to {printer:?}"),
|
||||||
|
None => eprintln!("[capture INFO] PHOTOBOOTH_PRINTER is empty; printing disabled"),
|
||||||
|
}
|
||||||
|
move |frame| match &mut detector {
|
||||||
|
Ok(detector) => {
|
||||||
|
if let Err(error) = take_picture(&frame, detector, printer.as_ref()) {
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upper bound on copies per capture so a misdetection cannot waste a paper roll.
|
||||||
|
const MAX_COPIES: usize = 5;
|
||||||
|
|
||||||
|
/// Count the faces in the captured, clean selfie frame and print one copy each.
|
||||||
|
/// Print failures are reported but never abort the worker.
|
||||||
|
pub fn take_picture(
|
||||||
|
frame: &opencv::core::Mat,
|
||||||
|
detector: &mut crate::faces::Detector,
|
||||||
|
printer: Option<&crate::printer::Printer>,
|
||||||
|
) -> opencv::Result<()> {
|
||||||
|
let faces = detector.count(frame)?;
|
||||||
|
let copies = faces.min(MAX_COPIES);
|
||||||
|
eprintln!(
|
||||||
|
"[capture DEBUG] faces={faces} requested_copies={copies} printing={}",
|
||||||
|
if printer.is_some() {
|
||||||
|
"enabled"
|
||||||
|
} else {
|
||||||
|
"disabled"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if let Some(printer) = printer
|
||||||
|
&& let Err(error) = printer.print(frame, copies)
|
||||||
|
{
|
||||||
|
eprintln!("[capture ERROR] Printing failed: {error}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asynchronously write the photo to /dev/shm/latest.png if /dev/shm exists
|
||||||
|
let shm_path = Path::new("/dev/shm");
|
||||||
|
if shm_path.exists() && shm_path.is_dir() {
|
||||||
|
let output_path = shm_path.join("latest.png");
|
||||||
|
let frame_clone = frame.try_clone()?;
|
||||||
|
thread::spawn(move || {
|
||||||
|
if let Err(error) = opencv::imgcodecs::imwrite(
|
||||||
|
output_path.to_str().unwrap_or("latest.png"),
|
||||||
|
&frame_clone,
|
||||||
|
&opencv::core::Vector::new(),
|
||||||
|
) {
|
||||||
|
eprintln!("[capture ERROR] Failed to write to /dev/shm/latest.png: {error}");
|
||||||
|
} else {
|
||||||
|
eprintln!("[capture DEBUG] Wrote photo to /dev/shm/latest.png");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn flash_countdown_and_single_capture_then_release() {
|
fn flash_countdown_and_single_capture_then_release() {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
@@ -76,42 +252,52 @@ mod tests {
|
|||||||
assert!(sequence.tracking());
|
assert!(sequence.tracking());
|
||||||
assert!(!sequence.tick(true, true, start));
|
assert!(!sequence.tick(true, true, start));
|
||||||
assert!(!sequence.tracking());
|
assert!(!sequence.tracking());
|
||||||
assert_eq!(sequence.presentation(start).countdown, 3);
|
assert_eq!(sequence.presentation(start).countdown, 5);
|
||||||
assert_eq!(sequence.presentation(start).flash_opacity, 0.75);
|
assert_eq!(sequence.presentation(start).flash_opacity, 0.95);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sequence
|
sequence
|
||||||
.presentation(start + Duration::from_millis(200))
|
.presentation(start + Duration::from_millis(200))
|
||||||
.flash_opacity,
|
.flash_opacity,
|
||||||
0.75
|
0.95
|
||||||
);
|
);
|
||||||
for (ms, number) in [(999, 3), (1000, 2), (1999, 2), (2000, 1), (2999, 1)] {
|
for (ms, number) in [
|
||||||
|
(999, 5),
|
||||||
|
(1000, 4),
|
||||||
|
(1999, 4),
|
||||||
|
(2000, 3),
|
||||||
|
(2999, 3),
|
||||||
|
(3000, 2),
|
||||||
|
(3999, 2),
|
||||||
|
(4000, 1),
|
||||||
|
(4999, 1),
|
||||||
|
] {
|
||||||
let now = start + Duration::from_millis(ms);
|
let now = start + Duration::from_millis(ms);
|
||||||
// Lowering the hand must not cancel an already-started countdown.
|
// Lowering the hand must not cancel an already-started countdown.
|
||||||
assert!(!sequence.tick(false, false, now));
|
assert!(!sequence.tick(false, false, now));
|
||||||
assert_eq!(sequence.presentation(now).countdown, number);
|
assert_eq!(sequence.presentation(now).countdown, number);
|
||||||
assert_eq!(sequence.presentation(now).flash_opacity, 0.75);
|
assert_eq!(sequence.presentation(now).flash_opacity, 0.95);
|
||||||
}
|
}
|
||||||
assert!(sequence.tick(true, true, start + Duration::from_secs(3)));
|
assert!(sequence.tick(true, true, start + Duration::from_secs(5)));
|
||||||
assert!(
|
assert!(
|
||||||
sequence
|
sequence
|
||||||
.presentation(start + Duration::from_secs(3))
|
.presentation(start + Duration::from_secs(5))
|
||||||
.awaiting_release
|
.awaiting_release
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sequence
|
sequence
|
||||||
.presentation(start + Duration::from_secs(3))
|
.presentation(start + Duration::from_secs(5))
|
||||||
.countdown,
|
.countdown,
|
||||||
0
|
0
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sequence
|
sequence
|
||||||
.presentation(start + Duration::from_secs(3))
|
.presentation(start + Duration::from_secs(5))
|
||||||
.flash_opacity,
|
.flash_opacity,
|
||||||
0.0
|
0.0
|
||||||
);
|
);
|
||||||
assert!(!sequence.tick(true, true, start + Duration::from_secs(4)));
|
assert!(!sequence.tick(true, true, start + Duration::from_secs(6)));
|
||||||
assert!(!sequence.tracking());
|
assert!(!sequence.tracking());
|
||||||
assert!(!sequence.tick(false, false, start + Duration::from_secs(5)));
|
assert!(!sequence.tick(false, false, start + Duration::from_secs(7)));
|
||||||
assert!(sequence.tracking());
|
assert!(sequence.tracking());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
297
src/faces.rs
Normal file
297
src/faces.rs
Normal file
@@ -0,0 +1,297 @@
|
|||||||
|
//! Lightweight YuNet detection, shared by capture and debug-only live preview.
|
||||||
|
use opencv::{
|
||||||
|
core::{self, Mat, Point2f, Rect, Size, Vector},
|
||||||
|
dnn, imgproc, objdetect,
|
||||||
|
prelude::*,
|
||||||
|
};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
pub struct Face {
|
||||||
|
#[cfg_attr(not(debug_assertions), allow(dead_code))]
|
||||||
|
pub bounds: Rect,
|
||||||
|
pub accepted: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
/// BGR colors match the UI: green counts toward prints, blue is rejected.
|
||||||
|
pub fn draw(frame: &mut Mat, faces: &[Face]) -> opencv::Result<()> {
|
||||||
|
let thickness = (frame.cols().min(frame.rows()) / 240).max(1);
|
||||||
|
for face in faces {
|
||||||
|
let color = if face.accepted {
|
||||||
|
core::Scalar::new(101.0, 191.0, 132.0, 0.0)
|
||||||
|
} else {
|
||||||
|
core::Scalar::new(227.0, 174.0, 76.0, 0.0)
|
||||||
|
};
|
||||||
|
imgproc::rectangle(frame, face.bounds, color, thickness, imgproc::LINE_8, 0)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Detector {
|
||||||
|
net: core::Ptr<objdetect::FaceDetectorYN>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Detector {
|
||||||
|
pub fn new() -> opencv::Result<Self> {
|
||||||
|
let bytes = Vector::from_slice(include_bytes!(
|
||||||
|
"../models/face_detection_yunet_2023mar.onnx"
|
||||||
|
));
|
||||||
|
Ok(Self {
|
||||||
|
net: objdetect::FaceDetectorYN::create_1(
|
||||||
|
"onnx",
|
||||||
|
&bytes,
|
||||||
|
&Vector::new(),
|
||||||
|
Size::new(320, 320),
|
||||||
|
0.8,
|
||||||
|
0.3,
|
||||||
|
500,
|
||||||
|
dnn::DNN_BACKEND_OPENCV,
|
||||||
|
dnn::DNN_TARGET_CPU,
|
||||||
|
)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn count(&mut self, frame: &Mat) -> opencv::Result<usize> {
|
||||||
|
Ok(self
|
||||||
|
.detect(frame, true)?
|
||||||
|
.iter()
|
||||||
|
.filter(|face| face.accepted)
|
||||||
|
.count())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn detect(&mut self, frame: &Mat, debug: bool) -> opencv::Result<Vec<Face>> {
|
||||||
|
let start = Instant::now();
|
||||||
|
if frame.empty() {
|
||||||
|
return Err(opencv::Error::new(
|
||||||
|
core::StsBadArg,
|
||||||
|
"Empty face detection image",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Aspect-preserving resize and padding keep inference at 320x320.
|
||||||
|
let scale = 320.0 / frame.cols().max(frame.rows()) as f64;
|
||||||
|
let width = (frame.cols() as f64 * scale).round() as i32;
|
||||||
|
let height = (frame.rows() as f64 * scale).round() as i32;
|
||||||
|
let mut resized = Mat::default();
|
||||||
|
imgproc::resize(
|
||||||
|
frame,
|
||||||
|
&mut resized,
|
||||||
|
Size::new(width, height),
|
||||||
|
0.0,
|
||||||
|
0.0,
|
||||||
|
imgproc::INTER_LINEAR,
|
||||||
|
)?;
|
||||||
|
let mut padded = Mat::default();
|
||||||
|
core::copy_make_border(
|
||||||
|
&resized,
|
||||||
|
&mut padded,
|
||||||
|
0,
|
||||||
|
320 - height,
|
||||||
|
0,
|
||||||
|
320 - width,
|
||||||
|
core::BORDER_CONSTANT,
|
||||||
|
core::Scalar::all(0.0),
|
||||||
|
)?;
|
||||||
|
let mut rows = Mat::default();
|
||||||
|
self.net.detect(&padded, &mut rows)?;
|
||||||
|
let mut faces = Vec::new();
|
||||||
|
for row in 0..rows.rows() {
|
||||||
|
let value = |col| rows.at_2d::<f32>(row, col).copied();
|
||||||
|
let x = value(0)?;
|
||||||
|
let y = value(1)?;
|
||||||
|
let w = value(2)?;
|
||||||
|
let h = value(3)?;
|
||||||
|
let eye_a = Point2f::new(value(4)?, value(5)?);
|
||||||
|
let eye_b = Point2f::new(value(6)?, value(7)?);
|
||||||
|
let nose = Point2f::new(value(8)?, value(9)?);
|
||||||
|
let accepted = facing_camera(eye_a, eye_b, nose, w);
|
||||||
|
let bounds = map_bounds(x, y, w, h, Size::new(width, height), frame.size()?);
|
||||||
|
if bounds.width <= 0 || bounds.height <= 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if debug {
|
||||||
|
eprintln!(
|
||||||
|
"[capture DEBUG] detector=yunet face={bounds:?} confidence={:.3} facing_camera={accepted}",
|
||||||
|
value(14)?
|
||||||
|
);
|
||||||
|
}
|
||||||
|
faces.push(Face { bounds, accepted });
|
||||||
|
}
|
||||||
|
if debug {
|
||||||
|
let count = faces.iter().filter(|face| face.accepted).count();
|
||||||
|
eprintln!(
|
||||||
|
"[capture DEBUG] detector=yunet candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis=320x320",
|
||||||
|
faces.len(),
|
||||||
|
faces.len() - count,
|
||||||
|
start.elapsed().as_millis()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(faces)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_bounds(x: f32, y: f32, w: f32, h: f32, input: Size, output: Size) -> Rect {
|
||||||
|
let sx = output.width as f32 / input.width as f32;
|
||||||
|
let sy = output.height as f32 / input.height as f32;
|
||||||
|
let left = (x * sx).floor().clamp(0.0, output.width as f32) as i32;
|
||||||
|
let top = (y * sy).floor().clamp(0.0, output.height as f32) as i32;
|
||||||
|
let right = ((x + w) * sx).ceil().clamp(0.0, output.width as f32) as i32;
|
||||||
|
let bottom = ((y + h) * sy).ceil().clamp(0.0, output.height as f32) as i32;
|
||||||
|
Rect::new(left, top, (right - left).max(0), (bottom - top).max(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Project the nose onto the eye line: rotation and selfie mirroring do not
|
||||||
|
// change the test. Reject strongly offset noses and compressed eye separation.
|
||||||
|
// This estimates frontal head orientation, not where a person's eyes are looking.
|
||||||
|
fn facing_camera(a: Point2f, b: Point2f, nose: Point2f, width: f32) -> bool {
|
||||||
|
let dx = b.x - a.x;
|
||||||
|
let dy = b.y - a.y;
|
||||||
|
let distance_sq = dx * dx + dy * dy;
|
||||||
|
let nose_position = ((nose.x - a.x) * dx + (nose.y - a.y) * dy) / distance_sq;
|
||||||
|
width.is_finite()
|
||||||
|
&& width > 0.0
|
||||||
|
&& distance_sq.is_finite()
|
||||||
|
&& distance_sq.sqrt() >= width * 0.23
|
||||||
|
&& (0.15..=0.85).contains(&nose_position)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
pub struct LivePreview {
|
||||||
|
sender: Option<std::sync::mpsc::SyncSender<Mat>>,
|
||||||
|
result: std::sync::Arc<std::sync::Mutex<(Instant, Vec<Face>)>>,
|
||||||
|
worker: Option<std::thread::JoinHandle<()>>,
|
||||||
|
last_sample: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
impl LivePreview {
|
||||||
|
pub fn new() -> opencv::Result<Self> {
|
||||||
|
use std::sync::{Arc, Mutex, mpsc};
|
||||||
|
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| {
|
||||||
|
eprintln!("[faces ERROR] Live detection failed: {error}");
|
||||||
|
Vec::new()
|
||||||
|
});
|
||||||
|
*worker_result.lock().unwrap() = (started, faces);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(Self {
|
||||||
|
sender: Some(sender),
|
||||||
|
result,
|
||||||
|
worker: Some(worker),
|
||||||
|
last_sample: Instant::now() - std::time::Duration::from_millis(500),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sample(&mut self, frame: &Mat) -> opencv::Result<()> {
|
||||||
|
if self.last_sample.elapsed() >= std::time::Duration::from_millis(500) {
|
||||||
|
// Drop samples while inference is busy: no backlog on the old kiosk CPU.
|
||||||
|
let _ = self.sender.as_ref().unwrap().try_send(frame.try_clone()?);
|
||||||
|
self.last_sample = Instant::now();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw(&self, frame: &mut Mat) -> opencv::Result<()> {
|
||||||
|
let result = self.result.lock().unwrap();
|
||||||
|
if result.0.elapsed() < std::time::Duration::from_millis(1500) {
|
||||||
|
draw(frame, &result.1)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
impl Drop for LivePreview {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.sender.take();
|
||||||
|
if self.worker.take().unwrap().join().is_err() {
|
||||||
|
eprintln!("[faces ERROR] Live detection worker panicked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
#[test]
|
||||||
|
fn overlay_draws_all_candidates_in_status_colors_without_filling_faces() -> opencv::Result<()> {
|
||||||
|
let mut frame =
|
||||||
|
Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(0.0))?;
|
||||||
|
draw(
|
||||||
|
&mut frame,
|
||||||
|
&[
|
||||||
|
Face {
|
||||||
|
bounds: Rect::new(50, 60, 100, 100),
|
||||||
|
accepted: true,
|
||||||
|
},
|
||||||
|
Face {
|
||||||
|
bounds: Rect::new(200, 60, 100, 100),
|
||||||
|
accepted: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
assert_eq!(
|
||||||
|
*frame.at_2d::<core::Vec3b>(60, 50)?,
|
||||||
|
core::Vec3b::from([101, 191, 132])
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
*frame.at_2d::<core::Vec3b>(60, 200)?,
|
||||||
|
core::Vec3b::from([227, 174, 76])
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
*frame.at_2d::<core::Vec3b>(100, 100)?,
|
||||||
|
core::Vec3b::from([0, 0, 0])
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn head_orientation_tolerates_roll_and_mirroring_but_rejects_profiles() {
|
||||||
|
let a = Point2f::new(20.0, 30.0);
|
||||||
|
let b = Point2f::new(70.0, 40.0);
|
||||||
|
let nose = Point2f::new(42.0, 60.0);
|
||||||
|
assert!(facing_camera(a, b, nose, 100.0));
|
||||||
|
assert!(facing_camera(b, a, nose, 100.0));
|
||||||
|
assert!(!facing_camera(a, b, Point2f::new(75.0, 50.0), 100.0));
|
||||||
|
assert!(!facing_camera(a, Point2f::new(30.0, 30.0), nose, 100.0));
|
||||||
|
assert!(!facing_camera(a, a, nose, 100.0));
|
||||||
|
assert!(!facing_camera(a, b, Point2f::new(f32::NAN, 50.0), 100.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bounds_scale_back_to_selfie_frame_and_clip_padding() {
|
||||||
|
let input = Size::new(320, 240);
|
||||||
|
let output = Size::new(640, 480);
|
||||||
|
assert_eq!(
|
||||||
|
map_bounds(150.0, 50.0, 80.0, 90.0, input, output),
|
||||||
|
Rect::new(300, 100, 160, 180)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
map_bounds(-10.0, 220.0, 50.0, 60.0, input, output),
|
||||||
|
Rect::new(0, 440, 80, 40)
|
||||||
|
);
|
||||||
|
assert_eq!(map_bounds(20.0, 250.0, 50.0, 40.0, input, output).height, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bundled_yunet_runs_on_blank_capture() -> opencv::Result<()> {
|
||||||
|
let mut detector = Detector::new()?;
|
||||||
|
let frame =
|
||||||
|
Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(128.0))?;
|
||||||
|
assert_eq!(detector.count(&frame)?, 0);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
53
src/main.rs
53
src/main.rs
@@ -23,8 +23,10 @@ slint::include_modules!();
|
|||||||
mod camera;
|
mod camera;
|
||||||
mod capture;
|
mod capture;
|
||||||
mod diagnostics;
|
mod diagnostics;
|
||||||
|
mod faces;
|
||||||
mod hand_pose;
|
mod hand_pose;
|
||||||
mod palm;
|
mod palm;
|
||||||
|
mod printer;
|
||||||
|
|
||||||
struct PreviewFrame {
|
struct PreviewFrame {
|
||||||
buffer: SharedPixelBuffer<Rgb8Pixel>,
|
buffer: SharedPixelBuffer<Rgb8Pixel>,
|
||||||
@@ -33,6 +35,16 @@ struct PreviewFrame {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn Error>> {
|
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() {
|
if let Err(error) = diagnostics::log_runtime() {
|
||||||
eprintln!("Failed to read OpenCV runtime diagnostics: {error}");
|
eprintln!("Failed to read OpenCV runtime diagnostics: {error}");
|
||||||
}
|
}
|
||||||
@@ -44,7 +56,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let (mut cam, mut frame) = camera::wait_until_ready(&mut camera_log)?;
|
let (mut cam, mut frame) = camera::wait_until_ready(&mut camera_log)?;
|
||||||
mirror_frame(&mut frame)?;
|
mirror_frame(&mut frame)?;
|
||||||
|
|
||||||
let mut detector = palm::Detector::new()?;
|
let capture_worker = capture::Worker::new();
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
let mut live_faces = faces::LivePreview::new()?;
|
||||||
let ui = AppWindow::new()?;
|
let ui = AppWindow::new()?;
|
||||||
|
|
||||||
ui.window()
|
ui.window()
|
||||||
@@ -65,6 +79,13 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
// A rendezvous channel drops samples while inference is busy, avoiding a backlog.
|
// A rendezvous channel drops samples while inference is busy, avoiding a backlog.
|
||||||
let (detection_tx, detection_rx) = mpsc::sync_channel::<Mat>(0);
|
let (detection_tx, detection_rx) = mpsc::sync_channel::<Mat>(0);
|
||||||
let detection_worker = thread::spawn(move || {
|
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(
|
let mut inference_log = diagnostics::SlowLog::new(
|
||||||
"palm + open-hand detection",
|
"palm + open-hand detection",
|
||||||
palm::DETECTION_INTERVAL,
|
palm::DETECTION_INTERVAL,
|
||||||
@@ -114,15 +135,33 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
let _ = detection_tx.try_send(frame.try_clone()?);
|
let _ = detection_tx.try_send(frame.try_clone()?);
|
||||||
last_detection = now;
|
last_detection = now;
|
||||||
}
|
}
|
||||||
let mut tracker = tracker.lock().unwrap();
|
#[cfg(debug_assertions)]
|
||||||
let hand_detected = tracker.has_palm(now);
|
live_faces.sample(&frame)?;
|
||||||
if sequence.tick(tracker.complete(now), hand_detected, now) {
|
let mut tracker_guard = tracker.lock().unwrap();
|
||||||
capture::take_picture();
|
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() {
|
if sequence.tracking() {
|
||||||
tracker.draw(&mut frame, now)?;
|
tracker_guard.draw(&mut frame, now)?;
|
||||||
}
|
}
|
||||||
drop(tracker);
|
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 {
|
let preview = PreviewFrame {
|
||||||
buffer: frame_to_buffer(&frame)?,
|
buffer: frame_to_buffer(&frame)?,
|
||||||
hand_detected,
|
hand_detected,
|
||||||
|
|||||||
679
src/printer.rs
Normal file
679
src/printer.rs
Normal file
@@ -0,0 +1,679 @@
|
|||||||
|
//! ESC/POS thermal printing for captured photos.
|
||||||
|
//!
|
||||||
|
//! Configuration (environment variables or the committed `.env`; read once at
|
||||||
|
//! startup):
|
||||||
|
//! - `PHOTOBOOTH_PRINTER`: where to send print data. Either a device path such as
|
||||||
|
//! `/dev/usb/lp0` (USB printer class) or a raw network printer as
|
||||||
|
//! `tcp://host[:port]` (port defaults to 9100). Defaults to `/dev/usb/lp0`;
|
||||||
|
//! set it to an empty value to disable printing.
|
||||||
|
//! - `PHOTOBOOTH_PRINTER_DOTS`: printable width in dots, rounded down to a multiple
|
||||||
|
//! of 8. Defaults to 576 (80 mm paper); use 384 for 58 mm paper.
|
||||||
|
//! - `PHOTOBOOTH_PRINTER_GAMMA`: mid-tone brightening applied before dithering
|
||||||
|
//! to offset the dot gain of thermal paper (`out = in^(1/gamma)`). Defaults to
|
||||||
|
//! 2.0; typical values are 1.8-2.5, and 1 disables it.
|
||||||
|
//! - `PHOTOBOOTH_PRINTER_DENSITY`: thermal head energy in percent of the rated
|
||||||
|
//! energy, 70-130 (SII `DC2 ~ n`). Unset by default.
|
||||||
|
//! - `PHOTOBOOTH_PRINTER_SPEED`: `quality` (120 mm/s), `low` (150 mm/s),
|
||||||
|
//! `silent` (180 mm/s) or `high` (200 mm/s) (SII `GS s n`). Unset by default.
|
||||||
|
//!
|
||||||
|
//! Both head settings belong to the SII RP-D10 command set and are only sent
|
||||||
|
//! when configured, because a printer that does not implement them loses sync
|
||||||
|
//! and prints the raster data that follows as text - metres of it. The tested
|
||||||
|
//! Birch 0CP-Q3 does exactly that with either command, so leave both unset
|
||||||
|
//! unless the printer is known to understand them. They are sent with every
|
||||||
|
//! band and are not stored by the printer (no memory switch writes).
|
||||||
|
//!
|
||||||
|
//! Each photo is captioned with the event name and place above it, and a
|
||||||
|
//! keepsake line, the capture date and time and one of `QUOTES` below it, in
|
||||||
|
//! German with the English directly underneath. The timestamp is the system
|
||||||
|
//! clock in local time, so the booth's clock has to be right for it to mean
|
||||||
|
//! anything. Text goes out in the printer's own code page (PC437), since it
|
||||||
|
//! prints UTF-8 bytes as separate glyphs; see `code_page`.
|
||||||
|
//!
|
||||||
|
//! Each photo is converted to gray, resized to the exact dot width, contrast
|
||||||
|
//! equalized (CLAHE), slightly sharpened, gamma brightened and finally Atkinson
|
||||||
|
//! dithered, in that order: scaling a dithered image would ruin the pattern.
|
||||||
|
//!
|
||||||
|
//! Serial printers must have their baud rate set beforehand (for example with
|
||||||
|
//! `stty -F /dev/ttyUSB0 9600`); this module only writes bytes.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
fs::OpenOptions,
|
||||||
|
io::Write,
|
||||||
|
net::{TcpStream, ToSocketAddrs},
|
||||||
|
path::PathBuf,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use chrono::Local;
|
||||||
|
use opencv::{
|
||||||
|
core::{self, Mat, Size},
|
||||||
|
imgproc,
|
||||||
|
prelude::*,
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_PRINTER: &str = "/dev/usb/lp0";
|
||||||
|
const DEFAULT_DOTS: usize = 576;
|
||||||
|
const DEFAULT_GAMMA: f32 = 2.0;
|
||||||
|
const DENSITY_RANGE: std::ops::RangeInclusive<u8> = 70..=130;
|
||||||
|
/// CLAHE settings: contrast limit and tiles across the image.
|
||||||
|
const CLAHE_CLIP_LIMIT: f64 = 2.0;
|
||||||
|
const CLAHE_TILES: i32 = 8;
|
||||||
|
/// Unsharp mask: blur radius in dots and how much of the detail to add back.
|
||||||
|
const SHARPEN_SIGMA: f64 = 1.0;
|
||||||
|
const SHARPEN_AMOUNT: f64 = 0.5;
|
||||||
|
const DEFAULT_NETWORK_PORT: u16 = 9100;
|
||||||
|
const NETWORK_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
/// Raster rows per `GS v 0` command, 4.5 KiB per band at 576 dots.
|
||||||
|
const BAND_ROWS: usize = 64;
|
||||||
|
const FEED_LINES: u8 = 4;
|
||||||
|
/// Caption printed around every photo.
|
||||||
|
const EVENT_TITLE: &str = "WINFNACHTEN";
|
||||||
|
const EVENT_PLACE: &str = "WINF Treitlstraße 3";
|
||||||
|
const KEEPSAKE_DE: &str = "Ich war dabei!";
|
||||||
|
const KEEPSAKE_EN: &str = "I was there!";
|
||||||
|
/// Capture time, written the German way and the same in both languages.
|
||||||
|
const STAMP_FORMAT: &str = "%d.%m.%Y, %H:%M";
|
||||||
|
/// One is printed per slip. Each line is short enough for a single 80 mm line;
|
||||||
|
/// on 58 mm paper the longer ones wrap.
|
||||||
|
const QUOTES: [[&str; 2]; 8] = [
|
||||||
|
[
|
||||||
|
"Analysis bestanden. Wunder gibt es doch.",
|
||||||
|
"Passed Analysis. Miracles do happen.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Im Freihaus gibt es Kaffee und Hoffnung.",
|
||||||
|
"The Freihaus serves coffee and hope.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"TISS sagt nein. Mein Herz sagt auch nein.",
|
||||||
|
"TISS says no. So does my heart.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"WINF: zwei Fächer, eine Deadline.",
|
||||||
|
"WINF: two subjects, one deadline.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Karlsplatz: der schönste Umweg zur Uni.",
|
||||||
|
"Karlsplatz: the prettiest detour to class.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Prüfungswoche: Schlafen ist optional.",
|
||||||
|
"Exam week: sleeping is optional.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Die Bibliothek kennt alle meine Ausreden.",
|
||||||
|
"The library has heard all my excuses.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Mathe ist einfach, sagt die Mathematik.",
|
||||||
|
"Maths is easy, says maths.",
|
||||||
|
],
|
||||||
|
];
|
||||||
|
/// Pause between writes, leaving the head time to drain a band (8 mm of paper)
|
||||||
|
/// before the next one arrives.
|
||||||
|
const PACE: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
enum Target {
|
||||||
|
Device(PathBuf),
|
||||||
|
Network(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Target {
|
||||||
|
fn parse(value: &str) -> Option<Self> {
|
||||||
|
let value = value.trim();
|
||||||
|
if value.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(match value.strip_prefix("tcp://") {
|
||||||
|
Some(address) if address.contains(':') => Self::Network(address.to_owned()),
|
||||||
|
Some(address) => Self::Network(format!("{address}:{DEFAULT_NETWORK_PORT}")),
|
||||||
|
None => Self::Device(PathBuf::from(value)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maximum print speeds of the SII `GS s n` command.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
enum Speed {
|
||||||
|
High,
|
||||||
|
Quality,
|
||||||
|
Low,
|
||||||
|
Silent,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Speed {
|
||||||
|
fn parse(value: &str) -> Option<Self> {
|
||||||
|
match value.trim().to_ascii_lowercase().as_str() {
|
||||||
|
"high" => Some(Self::High),
|
||||||
|
"quality" => Some(Self::Quality),
|
||||||
|
"low" => Some(Self::Low),
|
||||||
|
"silent" => Some(Self::Silent),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn code(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::High => 0,
|
||||||
|
Self::Quality => 1,
|
||||||
|
Self::Low => 2,
|
||||||
|
Self::Silent => 3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Head settings sent before each job; `None` leaves the printer's own setting.
|
||||||
|
#[derive(Debug, Default, PartialEq)]
|
||||||
|
struct Head {
|
||||||
|
density: Option<u8>,
|
||||||
|
speed: Option<Speed>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Head {
|
||||||
|
/// Either command is sent only when its variable holds a valid value, so
|
||||||
|
/// that printers which do not implement them never see them.
|
||||||
|
fn from_values(density: Option<&str>, speed: Option<&str>) -> Self {
|
||||||
|
Self {
|
||||||
|
density: density
|
||||||
|
.and_then(|value| value.trim().parse::<u8>().ok())
|
||||||
|
.filter(|density| DENSITY_RANGE.contains(density)),
|
||||||
|
speed: speed.and_then(Speed::parse),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commands(&self) -> Vec<u8> {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
if let Some(density) = self.density {
|
||||||
|
bytes.extend([0x12, b'~', density]); // DC2 ~ n: print density in %
|
||||||
|
}
|
||||||
|
if let Some(speed) = self.speed {
|
||||||
|
bytes.extend([0x1D, b's', speed.code()]); // GS s n: print speed
|
||||||
|
}
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Printer {
|
||||||
|
target: Target,
|
||||||
|
dots: usize,
|
||||||
|
gamma: f32,
|
||||||
|
head: Head,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Printer {
|
||||||
|
/// Returns `None` only when `PHOTOBOOTH_PRINTER` is explicitly empty.
|
||||||
|
pub fn from_env() -> Option<Self> {
|
||||||
|
Self::from_values(
|
||||||
|
std::env::var("PHOTOBOOTH_PRINTER").ok().as_deref(),
|
||||||
|
std::env::var("PHOTOBOOTH_PRINTER_DOTS").ok().as_deref(),
|
||||||
|
std::env::var("PHOTOBOOTH_PRINTER_GAMMA").ok().as_deref(),
|
||||||
|
)
|
||||||
|
.map(|printer| Self {
|
||||||
|
head: Head::from_values(
|
||||||
|
std::env::var("PHOTOBOOTH_PRINTER_DENSITY").ok().as_deref(),
|
||||||
|
std::env::var("PHOTOBOOTH_PRINTER_SPEED").ok().as_deref(),
|
||||||
|
),
|
||||||
|
..printer
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_values(printer: Option<&str>, dots: Option<&str>, gamma: Option<&str>) -> Option<Self> {
|
||||||
|
let target = Target::parse(printer.unwrap_or(DEFAULT_PRINTER))?;
|
||||||
|
let dots = dots
|
||||||
|
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||||
|
.map_or(DEFAULT_DOTS, |dots| dots / 8 * 8)
|
||||||
|
.max(8);
|
||||||
|
let gamma = gamma
|
||||||
|
.and_then(|value| value.trim().parse::<f32>().ok())
|
||||||
|
.filter(|gamma| gamma.is_finite() && *gamma > 0.0)
|
||||||
|
.unwrap_or(DEFAULT_GAMMA);
|
||||||
|
Some(Self {
|
||||||
|
target,
|
||||||
|
dots,
|
||||||
|
gamma,
|
||||||
|
head: Head::from_values(None, None),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prints `copies` identical cut-separated copies of the (BGR) frame.
|
||||||
|
pub fn print(&self, frame: &Mat, copies: usize) -> Result<(), String> {
|
||||||
|
if copies == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let bitmap =
|
||||||
|
render(frame, self.dots, self.gamma).map_err(|error| format!("render: {error}"))?;
|
||||||
|
let stamp = Local::now().format(STAMP_FORMAT).to_string();
|
||||||
|
self.send(&encode(&bitmap, &self.head, copies, &stamp, first_quote()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends the job one write at a time, pacing them to the print head.
|
||||||
|
fn send(&self, job: &[Vec<u8>]) -> Result<(), String> {
|
||||||
|
let mut sink: Box<dyn Write> = match &self.target {
|
||||||
|
Target::Device(path) => Box::new(
|
||||||
|
// Opened per job so an unplugged and re-attached printer recovers.
|
||||||
|
OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.open(path)
|
||||||
|
.map_err(|error| format!("open {}: {error}", path.display()))?,
|
||||||
|
),
|
||||||
|
Target::Network(address) => {
|
||||||
|
let socket = address
|
||||||
|
.to_socket_addrs()
|
||||||
|
.map_err(|error| format!("resolve {address}: {error}"))?
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| format!("resolve {address}: no address"))?;
|
||||||
|
let stream = TcpStream::connect_timeout(&socket, NETWORK_TIMEOUT)
|
||||||
|
.map_err(|error| format!("connect {address}: {error}"))?;
|
||||||
|
stream
|
||||||
|
.set_write_timeout(Some(NETWORK_TIMEOUT * 2))
|
||||||
|
.map_err(|error| format!("configure {address}: {error}"))?;
|
||||||
|
Box::new(stream)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (index, write) in job.iter().enumerate() {
|
||||||
|
if index > 0 {
|
||||||
|
std::thread::sleep(PACE);
|
||||||
|
}
|
||||||
|
sink.write_all(write)
|
||||||
|
.and_then(|()| sink.flush())
|
||||||
|
.map_err(|error| format!("write: {error}"))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1-bit bitmap, row-major, most significant bit first; a set bit is a black dot.
|
||||||
|
struct Bitmap {
|
||||||
|
width_bytes: usize,
|
||||||
|
data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(frame: &Mat, dots: usize, gamma: f32) -> opencv::Result<Bitmap> {
|
||||||
|
let rows = (frame.rows() as usize * dots / frame.cols().max(1) as usize).max(1);
|
||||||
|
let mut gray = Mat::default();
|
||||||
|
imgproc::cvt_color_def(frame, &mut gray, imgproc::COLOR_BGR2GRAY)?;
|
||||||
|
// Resize to the exact head width first; everything after works per dot.
|
||||||
|
let mut resized = Mat::default();
|
||||||
|
imgproc::resize(
|
||||||
|
&gray,
|
||||||
|
&mut resized,
|
||||||
|
Size::new(dots as i32, rows as i32),
|
||||||
|
0.0,
|
||||||
|
0.0,
|
||||||
|
imgproc::INTER_AREA,
|
||||||
|
)?;
|
||||||
|
// Local contrast equalization keeps faces from sinking into the shadows.
|
||||||
|
let mut equalized = Mat::default();
|
||||||
|
imgproc::create_clahe(CLAHE_CLIP_LIMIT, Size::new(CLAHE_TILES, CLAHE_TILES))?
|
||||||
|
.apply(&resized, &mut equalized)?;
|
||||||
|
// Unsharp mask: original + amount * (original - blurred).
|
||||||
|
let mut blurred = Mat::default();
|
||||||
|
imgproc::gaussian_blur_def(&equalized, &mut blurred, Size::new(0, 0), SHARPEN_SIGMA)?;
|
||||||
|
let mut sharpened = Mat::default();
|
||||||
|
core::add_weighted_def(
|
||||||
|
&equalized,
|
||||||
|
1.0 + SHARPEN_AMOUNT,
|
||||||
|
&blurred,
|
||||||
|
-SHARPEN_AMOUNT,
|
||||||
|
0.0,
|
||||||
|
&mut sharpened,
|
||||||
|
)?;
|
||||||
|
let sharpened = sharpened.try_clone()?; // contiguous bytes
|
||||||
|
let curve = gamma_curve(gamma);
|
||||||
|
let brightened: Vec<u8> = sharpened
|
||||||
|
.data_bytes()?
|
||||||
|
.iter()
|
||||||
|
.map(|&value| curve[usize::from(value)])
|
||||||
|
.collect();
|
||||||
|
Ok(Bitmap {
|
||||||
|
width_bytes: dots / 8,
|
||||||
|
data: dither(&brightened, dots, rows),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lookup table lifting mid-tones, since thermal dot gain darkens them again.
|
||||||
|
fn gamma_curve(gamma: f32) -> [u8; 256] {
|
||||||
|
std::array::from_fn(|value| (255.0 * (value as f32 / 255.0).powf(1.0 / gamma)).round() as u8)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Atkinson error diffusion: thermal heads only print black or nothing.
|
||||||
|
///
|
||||||
|
/// Only 6/8 of the error is passed on, which keeps highlights open and gives
|
||||||
|
/// the lighter look that suits thermal paper better than Floyd-Steinberg.
|
||||||
|
fn dither(gray: &[u8], width: usize, rows: usize) -> Vec<u8> {
|
||||||
|
let stride = width / 8;
|
||||||
|
let mut packed = vec![0u8; stride * rows];
|
||||||
|
// Error rows are padded (one cell left, two right) to avoid edge branches;
|
||||||
|
// cell `x + 1` belongs to pixel `x`.
|
||||||
|
let mut errors = [(); 3].map(|()| vec![0f32; width + 3]);
|
||||||
|
for y in 0..rows {
|
||||||
|
for x in 0..width {
|
||||||
|
let wanted = f32::from(gray[y * width + x]) + errors[0][x + 1];
|
||||||
|
let black = wanted < 128.0;
|
||||||
|
if black {
|
||||||
|
packed[y * stride + x / 8] |= 0x80 >> (x % 8);
|
||||||
|
}
|
||||||
|
let share = (wanted - if black { 0.0 } else { 255.0 }) / 8.0;
|
||||||
|
errors[0][x + 2] += share;
|
||||||
|
errors[0][x + 3] += share;
|
||||||
|
errors[1][x] += share;
|
||||||
|
errors[1][x + 1] += share;
|
||||||
|
errors[1][x + 2] += share;
|
||||||
|
errors[2][x + 1] += share;
|
||||||
|
}
|
||||||
|
errors.rotate_left(1);
|
||||||
|
errors[2].fill(0.0);
|
||||||
|
}
|
||||||
|
packed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes the job as a sequence of writes: one per raster band, then one feed
|
||||||
|
/// and cut per copy.
|
||||||
|
///
|
||||||
|
/// Every band is re-initialized and carries exactly one raster command. The
|
||||||
|
/// tested Birch 0CP-Q3 only keeps sync when `GS v 0` follows `ESC @` directly:
|
||||||
|
/// given several bands in one initialized stream it abandons the image and
|
||||||
|
/// prints the remaining dot data as text, about two metres of it per photo.
|
||||||
|
fn encode(
|
||||||
|
bitmap: &Bitmap,
|
||||||
|
head: &Head,
|
||||||
|
copies: usize,
|
||||||
|
stamp: &str,
|
||||||
|
first_quote: usize,
|
||||||
|
) -> Vec<Vec<u8>> {
|
||||||
|
let mut job = Vec::new();
|
||||||
|
for copy in 0..copies {
|
||||||
|
job.push(header(head));
|
||||||
|
for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) {
|
||||||
|
let rows = band.len() / bitmap.width_bytes;
|
||||||
|
let mut write = vec![0x1B, b'@']; // ESC @: initialize
|
||||||
|
write.extend(head.commands());
|
||||||
|
write.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density
|
||||||
|
write.extend((bitmap.width_bytes as u16).to_le_bytes());
|
||||||
|
write.extend((rows as u16).to_le_bytes());
|
||||||
|
write.extend(band);
|
||||||
|
job.push(write);
|
||||||
|
}
|
||||||
|
job.push(footer(head, stamp, "ES[(first_quote + copy) % QUOTES.len()]));
|
||||||
|
}
|
||||||
|
job
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The German letters in the captions as single PC437 bytes, the code page the
|
||||||
|
/// booth's printer starts in. Anything else non-ASCII would need a wider table
|
||||||
|
/// or `ESC t`, so a test keeps the printed text within this set.
|
||||||
|
fn code_page(character: char) -> Option<u8> {
|
||||||
|
Some(match character {
|
||||||
|
'ä' => 0x84,
|
||||||
|
'ö' => 0x94,
|
||||||
|
'ü' => 0x81,
|
||||||
|
'Ä' => 0x8E,
|
||||||
|
'Ö' => 0x99,
|
||||||
|
'Ü' => 0x9A,
|
||||||
|
'ß' => 0xE1,
|
||||||
|
ascii if ascii.is_ascii() => ascii as u8,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends one line of text, encoded for the printer.
|
||||||
|
fn text_line(write: &mut Vec<u8>, line: &str) {
|
||||||
|
write.extend(line.chars().map(|character| code_page(character).unwrap_or(b'?')));
|
||||||
|
write.push(b'\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a write with `ESC @` and the head settings, then centres the text.
|
||||||
|
fn centered(head: &Head) -> Vec<u8> {
|
||||||
|
let mut write = vec![0x1B, b'@']; // ESC @: initialize
|
||||||
|
write.extend(head.commands());
|
||||||
|
write.extend([0x1B, b'a', 1]); // ESC a n: centre the following lines
|
||||||
|
write
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emphasizes the next line: double width and height, bold.
|
||||||
|
const LARGE: [u8; 6] = [0x1D, b'!', 0x11, 0x1B, b'E', 1]; // GS ! n, ESC E n
|
||||||
|
const SMALL: [u8; 6] = [0x1D, b'!', 0x00, 0x1B, b'E', 0];
|
||||||
|
|
||||||
|
fn header(head: &Head) -> Vec<u8> {
|
||||||
|
let mut write = centered(head);
|
||||||
|
write.extend(LARGE);
|
||||||
|
text_line(&mut write, EVENT_TITLE);
|
||||||
|
write.extend(SMALL);
|
||||||
|
text_line(&mut write, EVENT_PLACE);
|
||||||
|
write.extend([0x1B, b'd', 1]); // a blank line between caption and photo
|
||||||
|
write
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which quote the next slip gets. The clock is random enough for a joke, and
|
||||||
|
/// saves pulling in a generator.
|
||||||
|
fn first_quote() -> usize {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_or(0, |since| since.subsec_nanos() as usize)
|
||||||
|
% QUOTES.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn footer(head: &Head, stamp: &str, quote: &[&str; 2]) -> Vec<u8> {
|
||||||
|
let mut write = centered(head);
|
||||||
|
write.extend([0x1B, b'd', 1]);
|
||||||
|
write.extend(LARGE);
|
||||||
|
text_line(&mut write, KEEPSAKE_DE);
|
||||||
|
write.extend(SMALL);
|
||||||
|
text_line(&mut write, KEEPSAKE_EN);
|
||||||
|
write.extend([0x1B, b'd', 1]);
|
||||||
|
text_line(&mut write, stamp);
|
||||||
|
write.extend([0x1B, b'd', 1]);
|
||||||
|
text_line(&mut write, quote[0]);
|
||||||
|
text_line(&mut write, quote[1]);
|
||||||
|
write.extend([0x1B, b'd', FEED_LINES]); // ESC d n: feed n lines
|
||||||
|
write.extend([0x1D, b'V', 66, 3]); // GS V 66 n: feed and partial cut
|
||||||
|
write
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const STAMP: &str = "14.11.2026, 15:42";
|
||||||
|
|
||||||
|
/// Every line the booth prints, large or small.
|
||||||
|
fn printed_lines() -> impl Iterator<Item = &'static str> {
|
||||||
|
[EVENT_TITLE, EVENT_PLACE, KEEPSAKE_DE, KEEPSAKE_EN, STAMP]
|
||||||
|
.into_iter()
|
||||||
|
.chain(QUOTES.iter().flatten().copied())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains_line(write: &[u8], line: &str) -> bool {
|
||||||
|
let mut needle = Vec::new();
|
||||||
|
text_line(&mut needle, line);
|
||||||
|
write.windows(needle.len()).any(|window| window == needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn printed_lines_fit_an_80_mm_line() {
|
||||||
|
// Font A is 12 dots wide, so 48 columns; the large lines take two each.
|
||||||
|
let columns = DEFAULT_DOTS / 12;
|
||||||
|
for line in [EVENT_TITLE, KEEPSAKE_DE] {
|
||||||
|
assert!(line.chars().count() <= columns / 2, "{line}");
|
||||||
|
}
|
||||||
|
for line in printed_lines().filter(|line| ![EVENT_TITLE, KEEPSAKE_DE].contains(line)) {
|
||||||
|
assert!(line.chars().count() <= columns, "{line}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn german_text_is_sent_in_the_printers_code_page() {
|
||||||
|
let mut write = Vec::new();
|
||||||
|
text_line(&mut write, "schönste Prüfung, Fächer, Straße");
|
||||||
|
assert_eq!(write, b"sch\x94nste Pr\x81fung, F\x84cher, Stra\xE1e\n");
|
||||||
|
// No printed line needs a character the code page lacks.
|
||||||
|
for line in printed_lines() {
|
||||||
|
assert!(
|
||||||
|
line.chars().all(|character| code_page(character).is_some()),
|
||||||
|
"{line}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quotes_are_picked_from_the_list_and_vary() {
|
||||||
|
let picked: std::collections::BTreeSet<usize> =
|
||||||
|
(0..1000).map(|_| first_quote()).collect();
|
||||||
|
assert!(picked.last().is_some_and(|last| *last < QUOTES.len()));
|
||||||
|
// Not all eight on a coarse clock, but a slip must not be predictable.
|
||||||
|
assert!(picked.len() > 1, "{picked:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_device_and_network_targets() {
|
||||||
|
assert_eq!(Target::parse(" "), None);
|
||||||
|
assert_eq!(
|
||||||
|
Target::parse("/dev/usb/lp0"),
|
||||||
|
Some(Target::Device("/dev/usb/lp0".into()))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Target::parse("tcp://192.168.0.5"),
|
||||||
|
Some(Target::Network("192.168.0.5:9100".into()))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Target::parse("tcp://printer.local:9101"),
|
||||||
|
Some(Target::Network("printer.local:9101".into()))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unset_variables_fall_back_to_80mm_usb_printer() {
|
||||||
|
let printer = Printer::from_values(None, None, None).unwrap();
|
||||||
|
assert_eq!(printer.target, Target::Device("/dev/usb/lp0".into()));
|
||||||
|
assert_eq!(printer.dots, 576);
|
||||||
|
assert_eq!(printer.gamma, 2.0);
|
||||||
|
// Unparsable widths fall back; valid ones are rounded to whole bytes.
|
||||||
|
let dots = |value| Printer::from_values(None, Some(value), None).unwrap().dots;
|
||||||
|
assert_eq!(dots("wide"), 576);
|
||||||
|
assert_eq!(dots(" 390 "), 384);
|
||||||
|
// Gamma must be a positive number.
|
||||||
|
let gamma = |value| Printer::from_values(None, None, Some(value)).unwrap().gamma;
|
||||||
|
assert_eq!(gamma(" 2.4 "), 2.4);
|
||||||
|
assert_eq!(gamma("0"), 2.0);
|
||||||
|
assert_eq!(gamma("bright"), 2.0);
|
||||||
|
// An explicitly empty printer disables printing.
|
||||||
|
assert!(Printer::from_values(Some(""), None, None).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn head_commands_are_sent_only_when_configured() {
|
||||||
|
// Unset, empty, out-of-range and unknown values all send nothing.
|
||||||
|
for (density, speed) in [
|
||||||
|
(None, None),
|
||||||
|
(Some(""), Some(" ")),
|
||||||
|
(Some("140"), Some("fast")),
|
||||||
|
] {
|
||||||
|
let head = Head::from_values(density, speed);
|
||||||
|
assert_eq!(head, Head::default(), "{density:?} {speed:?}");
|
||||||
|
assert!(head.commands().is_empty(), "{density:?} {speed:?}");
|
||||||
|
}
|
||||||
|
// Valid values are sent as the SII commands.
|
||||||
|
let head = Head::from_values(Some(" 70 "), Some("Low"));
|
||||||
|
assert_eq!(head.commands(), [0x12, b'~', 70, 0x1D, b's', 2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn configured_head_settings_precede_every_raster_band() {
|
||||||
|
let bitmap = Bitmap {
|
||||||
|
width_bytes: 1,
|
||||||
|
data: vec![0; BAND_ROWS + 1],
|
||||||
|
};
|
||||||
|
let job = encode(&bitmap, &Head::from_values(Some("85"), Some("quality")), 1, STAMP, 0);
|
||||||
|
for band in &job[1..3] {
|
||||||
|
assert_eq!(
|
||||||
|
&band[..12],
|
||||||
|
[0x1B, b'@', 0x12, b'~', 85, 0x1D, b's', 1, 0x1D, b'v', b'0', 0]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gamma_curve_lifts_mid_tones_and_keeps_endpoints() {
|
||||||
|
let curve = gamma_curve(2.0);
|
||||||
|
assert_eq!((curve[0], curve[255]), (0, 255));
|
||||||
|
assert_eq!(curve[64], 128); // sqrt(0.25) = 0.5
|
||||||
|
assert!(curve.windows(2).all(|pair| pair[0] <= pair[1]));
|
||||||
|
assert_eq!(gamma_curve(1.0), std::array::from_fn(|value| value as u8));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dithers_extremes_and_packs_msb_first() {
|
||||||
|
assert_eq!(dither(&[0; 16], 16, 1), vec![0xFF, 0xFF]);
|
||||||
|
assert_eq!(dither(&[255; 16], 16, 1), vec![0x00, 0x00]);
|
||||||
|
let mut half = [255u8; 8];
|
||||||
|
half[0] = 0;
|
||||||
|
assert_eq!(dither(&half, 8, 1), vec![0x80]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mid_gray_prints_roughly_half_the_dots() {
|
||||||
|
let packed = dither(&[128; 64 * 64], 64, 64);
|
||||||
|
let black: u32 = packed.iter().map(|byte| byte.count_ones()).sum();
|
||||||
|
assert!((1800..2300).contains(&black), "black dots: {black}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encodes_one_initialized_raster_command_per_write() {
|
||||||
|
let bitmap = Bitmap {
|
||||||
|
width_bytes: 2,
|
||||||
|
data: vec![0xAA; 2 * (BAND_ROWS + 1)],
|
||||||
|
};
|
||||||
|
let job = encode(&bitmap, &Head::default(), 2, STAMP, 0);
|
||||||
|
// Per copy: the caption, a full band, the leftover row, then the footer.
|
||||||
|
assert_eq!(job.len(), 2 * 4);
|
||||||
|
for copy in job.chunks(4) {
|
||||||
|
assert_eq!(
|
||||||
|
©[1][..10],
|
||||||
|
[0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0]
|
||||||
|
);
|
||||||
|
assert_eq!(copy[1].len(), 10 + 2 * BAND_ROWS);
|
||||||
|
assert_eq!(
|
||||||
|
copy[2],
|
||||||
|
[vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], vec![0xAA; 2]].concat()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Every write initializes first, so no dot data is read as commands.
|
||||||
|
assert!(job.iter().all(|write| write.starts_with(&[0x1B, b'@'])));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn captions_the_photo_and_cuts_once_per_copy() {
|
||||||
|
let bitmap = Bitmap {
|
||||||
|
width_bytes: 1,
|
||||||
|
data: vec![0; 1],
|
||||||
|
};
|
||||||
|
let job = encode(&bitmap, &Head::default(), 2, STAMP, 6);
|
||||||
|
assert!(contains_line(&job[0], EVENT_TITLE) && contains_line(&job[0], EVENT_PLACE));
|
||||||
|
assert!(contains_line(&job[2], KEEPSAKE_DE) && contains_line(&job[2], KEEPSAKE_EN));
|
||||||
|
assert!(contains_line(&job[2], STAMP));
|
||||||
|
// Consecutive copies get consecutive quotes, wrapping round the list.
|
||||||
|
assert!(contains_line(&job[2], QUOTES[6][0]) && contains_line(&job[2], QUOTES[6][1]));
|
||||||
|
assert!(contains_line(&job[5], QUOTES[7][0]) && contains_line(&job[5], QUOTES[7][1]));
|
||||||
|
assert!(
|
||||||
|
encode(&bitmap, &Head::default(), 1, STAMP, QUOTES.len() - 1)[2]
|
||||||
|
.ends_with(&footer(&Head::default(), STAMP, "ES[QUOTES.len() - 1])[1..])
|
||||||
|
);
|
||||||
|
// The real stamp is as wide as the one used here.
|
||||||
|
let now = Local::now().format(STAMP_FORMAT).to_string();
|
||||||
|
assert!(now.is_ascii() && now.len() == STAMP.len(), "{now}");
|
||||||
|
let cuts = job
|
||||||
|
.iter()
|
||||||
|
.filter(|write| write.ends_with(&[0x1D, b'V', 66, 3]))
|
||||||
|
.count();
|
||||||
|
assert_eq!(cuts, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ fn check_transitions(repaint: RepaintBufferType, buffer_count: usize) {
|
|||||||
let instructions = frames.render(&ui, &window);
|
let instructions = frames.render(&ui, &window);
|
||||||
for _ in 0..2 {
|
for _ in 0..2 {
|
||||||
ui.set_countdown(3);
|
ui.set_countdown(3);
|
||||||
ui.set_flash_opacity(0.75);
|
ui.set_flash_opacity(0.95);
|
||||||
for _ in 0..3 {
|
for _ in 0..3 {
|
||||||
frames.render(&ui, &window);
|
frames.render(&ui, &window);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -142,6 +142,35 @@ export component AppWindow inherits Window {
|
|||||||
active: root.hand-detected;
|
active: root.hand-detected;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if root.flash-opacity > 0: Rectangle {
|
||||||
|
// Keep the portrait below the central countdown and most of the
|
||||||
|
// monitor white so it continues to provide light for the photo.
|
||||||
|
width: min(360px * root.ui-scale, root.width * 0.65, root.height * 0.36);
|
||||||
|
height: self.width * 200 / 360 + 40px * root.ui-scale;
|
||||||
|
x: (root.width - self.width) / 2;
|
||||||
|
y: root.height - self.height - root.inset - root.safe-area-insets.bottom;
|
||||||
|
background: transparent;
|
||||||
|
pose-label := Text {
|
||||||
|
x: 0px;
|
||||||
|
y: 0px;
|
||||||
|
width: parent.width;
|
||||||
|
height: 32px * root.ui-scale;
|
||||||
|
text: "Pose!";
|
||||||
|
color: #20302b77;
|
||||||
|
font-size: 26px * root.ui-scale;
|
||||||
|
font-weight: 600;
|
||||||
|
horizontal-alignment: center;
|
||||||
|
vertical-alignment: center;
|
||||||
|
}
|
||||||
|
Image {
|
||||||
|
x: 0px;
|
||||||
|
y: pose-label.y + pose-label.height + 8px * root.ui-scale;
|
||||||
|
width: parent.width;
|
||||||
|
height: parent.height - self.y;
|
||||||
|
source: @image-url("assets/photo-pose.svg");
|
||||||
|
image-fit: contain;
|
||||||
|
}
|
||||||
|
}
|
||||||
if root.countdown > 0: Text {
|
if root.countdown > 0: Text {
|
||||||
width: root.width;
|
width: root.width;
|
||||||
height: root.height;
|
height: root.height;
|
||||||
|
|||||||
27
ui/assets/photo-pose.svg
Normal file
27
ui/assets/photo-pose.svg
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="360" height="200" viewBox="0 0 360 200" fill="none" stroke="#20302b" stroke-opacity="0.467" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<!-- Round portrait proportions: peace sign and hand on hip. -->
|
||||||
|
<ellipse cx="91" cy="48" rx="29" ry="31" transform="rotate(-12 91 48)"/>
|
||||||
|
<path d="M78 80C65 82 62 98 55 99S40 87 34 81M30 92C40 110 51 122 62 117L69 113C65 129 63 139 71 145C82 153 109 153 118 145C124 139 120 123 118 114L133 125L121 136C115 142 123 151 130 146L149 132C157 126 154 118 148 113L117 88Q109 82 105 82"/>
|
||||||
|
<path d="M34 81Q42 72 38 63L37 45C37 39 29 39 29 45L29 61L22 45C19 39 12 43 15 49L24 70C15 61 9 69 15 76L30 92M73 147L68 174Q50 175 51 184Q52 190 62 190L75 190Q82 190 84 182L92 158L103 174L98 180Q91 190 100 193Q105 195 110 190L124 179Q130 174 125 167L113 149"/>
|
||||||
|
<!-- A different pose: arms arched overhead and a leg kicked sideways. -->
|
||||||
|
<ellipse cx="267" cy="72" rx="30" ry="29" transform="rotate(15 267 72)"/>
|
||||||
|
<!-- A single body outline keeps the hips and kicked leg free of seams.
|
||||||
|
Both raised arms stay clear of the head. -->
|
||||||
|
<path d="M232 68
|
||||||
|
C229 61 225 45 230 35
|
||||||
|
Q235 27 229 23 Q223 19 218 27
|
||||||
|
C209 42 215 61 226 80
|
||||||
|
C233 93 245 103 255 104
|
||||||
|
C245 115 241 131 248 145
|
||||||
|
L244 173 Q227 175 229 183
|
||||||
|
Q230 190 240 189 L250 188
|
||||||
|
Q259 187 260 179 L266 155
|
||||||
|
L301 172 Q309 176 316 169
|
||||||
|
L337 149 Q344 142 338 137
|
||||||
|
Q332 132 326 139 L308 154
|
||||||
|
L287 134 C285 121 284 112 279 104
|
||||||
|
C289 100 301 89 309 75
|
||||||
|
C320 57 324 37 315 24
|
||||||
|
Q310 17 304 21 Q298 25 303 33
|
||||||
|
C308 44 306 57 303 64"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.6 KiB |
Reference in New Issue
Block a user