fix: print each raster band as its own ESC/POS job

The Birch 0CP-Q3 loses sync unless GS v 0 directly follows ESC @, and on
either SII head command, printing the dot data as metres of text instead
of the photo. Initialize per band and leave density and speed unset.
This commit is contained in:
bankosegger
2026-11-14 15:31:48 +01:00
parent b71e2b32e6
commit c7af3e320b
2 changed files with 291 additions and 58 deletions

13
.env
View File

@@ -9,3 +9,16 @@ PHOTOBOOTH_PRINTER=/dev/usb/lp0
# Printable width in dots: 576 for 80 mm paper (384 for 58 mm). # Printable width in dots: 576 for 80 mm paper (384 for 58 mm).
PHOTOBOOTH_PRINTER_DOTS=576 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=

View File

@@ -8,6 +8,24 @@
//! set it to an empty value to disable printing. //! set it to an empty value to disable printing.
//! - `PHOTOBOOTH_PRINTER_DOTS`: printable width in dots, rounded down to a multiple //! - `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. //! 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 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 //! Serial printers must have their baud rate set beforehand (for example with
//! `stty -F /dev/ttyUSB0 9600`); this module only writes bytes. //! `stty -F /dev/ttyUSB0 9600`); this module only writes bytes.
@@ -21,18 +39,29 @@ use std::{
}; };
use opencv::{ use opencv::{
core::{Mat, Size}, core::{self, Mat, Size},
imgproc, imgproc,
prelude::*, prelude::*,
}; };
const DEFAULT_PRINTER: &str = "/dev/usb/lp0"; const DEFAULT_PRINTER: &str = "/dev/usb/lp0";
const DEFAULT_DOTS: usize = 576; 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 DEFAULT_NETWORK_PORT: u16 = 9100;
const NETWORK_TIMEOUT: Duration = Duration::from_secs(5); const NETWORK_TIMEOUT: Duration = Duration::from_secs(5);
/// Raster rows per `GS v 0` command; small bands fit every printer's buffer. /// Raster rows per `GS v 0` command, 4.5 KiB per band at 576 dots.
const BAND_ROWS: usize = 128; const BAND_ROWS: usize = 64;
const FEED_LINES: u8 = 4; const FEED_LINES: u8 = 4;
/// 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)] #[derive(Debug, PartialEq)]
enum Target { enum Target {
@@ -54,10 +83,73 @@ impl Target {
} }
} }
/// 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)] #[derive(Debug)]
pub struct Printer { pub struct Printer {
target: Target, target: Target,
dots: usize, dots: usize,
gamma: f32,
head: Head,
} }
impl Printer { impl Printer {
@@ -66,16 +158,33 @@ impl Printer {
Self::from_values( Self::from_values(
std::env::var("PHOTOBOOTH_PRINTER").ok().as_deref(), std::env::var("PHOTOBOOTH_PRINTER").ok().as_deref(),
std::env::var("PHOTOBOOTH_PRINTER_DOTS").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>) -> Option<Self> { fn from_values(printer: Option<&str>, dots: Option<&str>, gamma: Option<&str>) -> Option<Self> {
let target = Target::parse(printer.unwrap_or(DEFAULT_PRINTER))?; let target = Target::parse(printer.unwrap_or(DEFAULT_PRINTER))?;
let dots = dots let dots = dots
.and_then(|value| value.trim().parse::<usize>().ok()) .and_then(|value| value.trim().parse::<usize>().ok())
.map_or(DEFAULT_DOTS, |dots| dots / 8 * 8) .map_or(DEFAULT_DOTS, |dots| dots / 8 * 8)
.max(8); .max(8);
Some(Self { target, dots }) 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. /// Prints `copies` identical cut-separated copies of the (BGR) frame.
@@ -83,35 +192,44 @@ impl Printer {
if copies == 0 { if copies == 0 {
return Ok(()); return Ok(());
} }
let bitmap = render(frame, self.dots).map_err(|error| format!("render: {error}"))?; let bitmap =
self.send(&encode(&bitmap, copies)) render(frame, self.dots, self.gamma).map_err(|error| format!("render: {error}"))?;
self.send(&encode(&bitmap, &self.head, copies))
} }
fn send(&self, job: &[u8]) -> Result<(), String> { /// Sends the job one write at a time, pacing them to the print head.
match &self.target { fn send(&self, job: &[Vec<u8>]) -> Result<(), String> {
Target::Device(path) => { 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. // Opened per job so an unplugged and re-attached printer recovers.
let mut device = OpenOptions::new() OpenOptions::new()
.write(true) .write(true)
.open(path) .open(path)
.map_err(|error| format!("open {}: {error}", path.display()))?; .map_err(|error| format!("open {}: {error}", path.display()))?,
device.write_all(job).and_then(|()| device.flush()) ),
}
Target::Network(address) => { Target::Network(address) => {
let socket = address let socket = address
.to_socket_addrs() .to_socket_addrs()
.map_err(|error| format!("resolve {address}: {error}"))? .map_err(|error| format!("resolve {address}: {error}"))?
.next() .next()
.ok_or_else(|| format!("resolve {address}: no address"))?; .ok_or_else(|| format!("resolve {address}: no address"))?;
let mut stream = TcpStream::connect_timeout(&socket, NETWORK_TIMEOUT) let stream = TcpStream::connect_timeout(&socket, NETWORK_TIMEOUT)
.map_err(|error| format!("connect {address}: {error}"))?; .map_err(|error| format!("connect {address}: {error}"))?;
stream stream
.set_write_timeout(Some(NETWORK_TIMEOUT * 2)) .set_write_timeout(Some(NETWORK_TIMEOUT * 2))
.map_err(|error| format!("configure {address}: {error}"))?; .map_err(|error| format!("configure {address}: {error}"))?;
stream.write_all(job).and_then(|()| stream.flush()) 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}"))?;
} }
.map_err(|error| format!("write: {error}")) Ok(())
} }
} }
@@ -121,10 +239,11 @@ struct Bitmap {
data: Vec<u8>, data: Vec<u8>,
} }
fn render(frame: &Mat, dots: usize) -> opencv::Result<Bitmap> { 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 rows = (frame.rows() as usize * dots / frame.cols().max(1) as usize).max(1);
let mut gray = Mat::default(); let mut gray = Mat::default();
imgproc::cvt_color_def(frame, &mut gray, imgproc::COLOR_BGR2GRAY)?; 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(); let mut resized = Mat::default();
imgproc::resize( imgproc::resize(
&gray, &gray,
@@ -134,51 +253,95 @@ fn render(frame: &Mat, dots: usize) -> opencv::Result<Bitmap> {
0.0, 0.0,
imgproc::INTER_AREA, imgproc::INTER_AREA,
)?; )?;
let resized = resized.try_clone()?; // contiguous bytes // 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 { Ok(Bitmap {
width_bytes: dots / 8, width_bytes: dots / 8,
data: dither(resized.data_bytes()?, dots, rows), data: dither(&brightened, dots, rows),
}) })
} }
/// Floyd-Steinberg error diffusion: thermal heads only print black or nothing. /// 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> { fn dither(gray: &[u8], width: usize, rows: usize) -> Vec<u8> {
let stride = width / 8; let stride = width / 8;
let mut packed = vec![0u8; stride * rows]; let mut packed = vec![0u8; stride * rows];
// Error rows are padded by one cell on each side to avoid edge branches. // Error rows are padded (one cell left, two right) to avoid edge branches;
let mut current = vec![0f32; width + 2]; // cell `x + 1` belongs to pixel `x`.
let mut next = vec![0f32; width + 2]; let mut errors = [(); 3].map(|()| vec![0f32; width + 3]);
for y in 0..rows { for y in 0..rows {
for x in 0..width { for x in 0..width {
let wanted = f32::from(gray[y * width + x]) + current[x + 1]; let wanted = f32::from(gray[y * width + x]) + errors[0][x + 1];
let black = wanted < 128.0; let black = wanted < 128.0;
let error = wanted - if black { 0.0 } else { 255.0 };
if black { if black {
packed[y * stride + x / 8] |= 0x80 >> (x % 8); packed[y * stride + x / 8] |= 0x80 >> (x % 8);
} }
current[x + 2] += error * 7.0 / 16.0; let share = (wanted - if black { 0.0 } else { 255.0 }) / 8.0;
next[x] += error * 3.0 / 16.0; errors[0][x + 2] += share;
next[x + 1] += error * 5.0 / 16.0; errors[0][x + 3] += share;
next[x + 2] += error / 16.0; errors[1][x] += share;
errors[1][x + 1] += share;
errors[1][x + 2] += share;
errors[2][x + 1] += share;
} }
std::mem::swap(&mut current, &mut next); errors.rotate_left(1);
next.fill(0.0); errors[2].fill(0.0);
} }
packed packed
} }
fn encode(bitmap: &Bitmap, copies: usize) -> Vec<u8> { /// Encodes the job as a sequence of writes: one per raster band, then one feed
let mut job = vec![0x1B, b'@']; // ESC @: initialize /// 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) -> Vec<Vec<u8>> {
let mut job = Vec::new();
for _ in 0..copies { for _ in 0..copies {
for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) { for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) {
let rows = band.len() / 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 let mut write = vec![0x1B, b'@']; // ESC @: initialize
job.extend((bitmap.width_bytes as u16).to_le_bytes()); write.extend(head.commands());
job.extend((rows as u16).to_le_bytes()); write.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density
job.extend(band); 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.extend([0x1B, b'd', FEED_LINES]); // ESC d n: feed n lines job.push(vec![
job.extend([0x1D, b'V', 66, 3]); // GS V 66 n: feed and partial cut 0x1B, b'd', FEED_LINES, // ESC d n: feed n lines
0x1D, b'V', 66, 3, // GS V 66 n: feed and partial cut
]);
} }
job job
} }
@@ -206,14 +369,62 @@ mod tests {
#[test] #[test]
fn unset_variables_fall_back_to_80mm_usb_printer() { fn unset_variables_fall_back_to_80mm_usb_printer() {
let printer = Printer::from_values(None, None).unwrap(); let printer = Printer::from_values(None, None, None).unwrap();
assert_eq!(printer.target, Target::Device("/dev/usb/lp0".into())); assert_eq!(printer.target, Target::Device("/dev/usb/lp0".into()));
assert_eq!(printer.dots, 576); assert_eq!(printer.dots, 576);
assert_eq!(printer.gamma, 2.0);
// Unparsable widths fall back; valid ones are rounded to whole bytes. // Unparsable widths fall back; valid ones are rounded to whole bytes.
assert_eq!(Printer::from_values(None, Some("wide")).unwrap().dots, 576); let dots = |value| Printer::from_values(None, Some(value), None).unwrap().dots;
assert_eq!(Printer::from_values(None, Some(" 390 ")).unwrap().dots, 384); 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. // An explicitly empty printer disables printing.
assert!(Printer::from_values(Some(""), None).is_none()); 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);
for band in &job[..2] {
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] #[test]
@@ -233,24 +444,33 @@ mod tests {
} }
#[test] #[test]
fn encodes_banded_raster_copies_with_cuts() { fn encodes_one_initialized_raster_command_per_write() {
let bitmap = Bitmap { let bitmap = Bitmap {
width_bytes: 2, width_bytes: 2,
data: vec![0xAA; 2 * (BAND_ROWS + 1)], data: vec![0xAA; 2 * (BAND_ROWS + 1)],
}; };
let job = encode(&bitmap, 2); let job = encode(&bitmap, &Head::default(), 2);
let first_band = [0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0]; // Per copy: a full band, the leftover row, then the feed and cut.
assert_eq!(&job[..2], [0x1B, b'@']); assert_eq!(job.len(), 2 * 3);
assert_eq!(&job[2..10], first_band); let cut = vec![0x1B, b'd', FEED_LINES, 0x1D, b'V', 66, 3];
let second_header = 2 + 8 + 2 * BAND_ROWS; for copy in job.chunks(3) {
assert_eq!( assert_eq!(
&job[second_header..second_header + 8], &copy[0][..10],
[0x1D, b'v', b'0', 0, 2, 0, 1, 0] [0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0]
);
assert_eq!(copy[0].len(), 10 + 2 * BAND_ROWS);
assert_eq!(
copy[1],
[vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], vec![0xAA; 2]].concat()
);
assert_eq!(copy[2], cut);
}
// No write carries dot data without initializing first.
assert!(
job.iter()
.all(|write| write.starts_with(&[0x1B, b'@']) || *write == cut)
); );
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);
} }
} }