feat: print captured photos on an ESC/POS thermal printer

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bankosegger
2026-11-11 14:56:41 +01:00
parent 898ceb5726
commit eae81bb052
3 changed files with 261 additions and 12 deletions

View File

@@ -79,9 +79,13 @@ impl Worker {
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();
if printer.is_none() {
eprintln!("[capture] PHOTOBOOTH_PRINTER not set; printing disabled");
}
move |frame| match &mut detector {
Ok(detector) => {
if let Err(error) = take_picture(&frame, detector) {
if let Err(error) = take_picture(&frame, detector, printer.as_ref()) {
eprintln!("[capture ERROR] Face counting failed: {error}");
}
}
@@ -141,23 +145,34 @@ impl Drop for Worker {
}
}
/// Count the captured, clean selfie frame and pass the intended copies to the
/// print hook. Printer integration is intentionally left unimplemented.
/// 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 copies = detector.count(frame)?;
eprintln!("[capture DEBUG] faces={copies} requested_copies={copies} printing=unimplemented");
print_picture(frame, copies);
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}");
}
Ok(())
}
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::*;

View File

@@ -26,6 +26,7 @@ mod diagnostics;
mod faces;
mod hand_pose;
mod palm;
mod printer;
struct PreviewFrame {
buffer: SharedPixelBuffer<Rgb8Pixel>,
@@ -140,7 +141,7 @@ fn main() -> Result<(), Box<dyn Error>> {
);
if take_picture {
// The snapshot is the capture: lighting can end after this copy.
// Face counting and the empty print hook run on their own worker.
// 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}");

233
src/printer.rs Normal file
View File

@@ -0,0 +1,233 @@
//! ESC/POS thermal printing for captured photos.
//!
//! Configuration (environment variables, 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). Printing is disabled when unset.
//! - `PHOTOBOOTH_PRINTER_DOTS`: printable width in dots, rounded down to a multiple
//! of 8. Defaults to 384 (58 mm paper); use 576 for 80 mm paper.
//!
//! 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 opencv::{
core::{Mat, Size},
imgproc,
prelude::*,
};
const DEFAULT_DOTS: usize = 384;
const DEFAULT_NETWORK_PORT: u16 = 9100;
const NETWORK_TIMEOUT: Duration = Duration::from_secs(5);
/// Raster rows per `GS v 0` command; small bands fit every printer's buffer.
const BAND_ROWS: usize = 128;
const FEED_LINES: u8 = 4;
#[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)),
})
}
}
pub struct Printer {
target: Target,
dots: usize,
}
impl Printer {
pub fn from_env() -> Option<Self> {
let target = Target::parse(&std::env::var("PHOTOBOOTH_PRINTER").ok()?)?;
let dots = std::env::var("PHOTOBOOTH_PRINTER_DOTS")
.ok()
.and_then(|value| value.trim().parse::<usize>().ok())
.map_or(DEFAULT_DOTS, |dots| dots / 8 * 8)
.max(8);
Some(Self { target, dots })
}
/// 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).map_err(|error| format!("render: {error}"))?;
self.send(&encode(&bitmap, copies))
}
fn send(&self, job: &[u8]) -> Result<(), String> {
match &self.target {
Target::Device(path) => {
// Opened per job so an unplugged and re-attached printer recovers.
let mut device = OpenOptions::new()
.write(true)
.open(path)
.map_err(|error| format!("open {}: {error}", path.display()))?;
device.write_all(job).and_then(|()| device.flush())
}
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 mut 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}"))?;
stream.write_all(job).and_then(|()| stream.flush())
}
}
.map_err(|error| format!("write: {error}"))
}
}
/// 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) -> 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)?;
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,
)?;
let resized = resized.try_clone()?; // contiguous bytes
Ok(Bitmap {
width_bytes: dots / 8,
data: dither(resized.data_bytes()?, dots, rows),
})
}
/// Floyd-Steinberg error diffusion: thermal heads only print black or nothing.
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 by one cell on each side to avoid edge branches.
let mut current = vec![0f32; width + 2];
let mut next = vec![0f32; width + 2];
for y in 0..rows {
for x in 0..width {
let wanted = f32::from(gray[y * width + x]) + current[x + 1];
let black = wanted < 128.0;
let error = wanted - if black { 0.0 } else { 255.0 };
if black {
packed[y * stride + x / 8] |= 0x80 >> (x % 8);
}
current[x + 2] += error * 7.0 / 16.0;
next[x] += error * 3.0 / 16.0;
next[x + 1] += error * 5.0 / 16.0;
next[x + 2] += error / 16.0;
}
std::mem::swap(&mut current, &mut next);
next.fill(0.0);
}
packed
}
fn encode(bitmap: &Bitmap, copies: usize) -> Vec<u8> {
let mut job = vec![0x1B, b'@']; // ESC @: initialize
for _ in 0..copies {
for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) {
let rows = band.len() / bitmap.width_bytes;
job.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density
job.extend((bitmap.width_bytes as u16).to_le_bytes());
job.extend((rows as u16).to_le_bytes());
job.extend(band);
}
job.extend([0x1B, b'd', FEED_LINES]); // ESC d n: feed n lines
job.extend([0x1D, b'V', 66, 3]); // GS V 66 n: feed and partial cut
}
job
}
#[cfg(test)]
mod tests {
use super::*;
#[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 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_banded_raster_copies_with_cuts() {
let bitmap = Bitmap {
width_bytes: 2,
data: vec![0xAA; 2 * (BAND_ROWS + 1)],
};
let job = encode(&bitmap, 2);
let first_band = [0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0];
assert_eq!(&job[..2], [0x1B, b'@']);
assert_eq!(&job[2..10], first_band);
let second_header = 2 + 8 + 2 * BAND_ROWS;
assert_eq!(
&job[second_header..second_header + 8],
[0x1D, b'v', b'0', 0, 2, 0, 1, 0]
);
let cuts = job.windows(4).filter(|w| *w == [0x1D, b'V', 66, 3]).count();
assert_eq!(cuts, 2);
// Per copy: two headers, all raster bytes, feed and cut.
let per_copy = 8 + 8 + bitmap.data.len() + 3 + 4;
assert_eq!(job.len(), 2 + 2 * per_copy);
}
}