keyfork/crates/qrcode/keyfork-qrcode/src/lib.rs

164 lines
5.0 KiB
Rust
Raw Normal View History

2024-01-16 02:44:48 +00:00
//! Encoding and decoding QR codes.
use keyfork_bug as bug;
2024-01-12 00:49:56 +00:00
use image::io::Reader as ImageReader;
use std::{
io::{Cursor, Write},
time::{Duration, SystemTime},
process::{Command, Stdio},
};
use v4l::{
buffer::Type,
io::{userptr::Stream, traits::CaptureStream},
video::Capture,
FourCC,
2024-01-13 07:52:43 +00:00
Device,
2024-01-12 00:49:56 +00:00
};
2024-01-16 02:44:48 +00:00
/// A QR code could not be generated.
2024-01-12 00:49:56 +00:00
#[derive(thiserror::Error, Debug)]
pub enum QRGenerationError {
2024-01-16 02:44:48 +00:00
/// The resulting QR coode could not be read from the generator program.
2024-01-12 00:49:56 +00:00
#[error("{0}")]
Io(#[from] std::io::Error),
2024-01-16 02:44:48 +00:00
/// The generator program produced invalid data.
2024-01-12 00:49:56 +00:00
#[error("Could not decode output of qrencode (this is a bug!): {0}")]
StringParse(#[from] std::string::FromUtf8Error),
}
2024-01-16 02:44:48 +00:00
/// An error occurred while scanning for a QR code.
2024-01-12 00:49:56 +00:00
#[derive(thiserror::Error, Debug)]
pub enum QRCodeScanError {
2024-01-16 02:44:48 +00:00
/// The camera could not load the requested format.
2024-01-12 00:49:56 +00:00
#[error("Camera could not use {expected} format, instead used {actual}")]
CameraGaveBadFormat {
2024-01-16 02:44:48 +00:00
/// The expected format, in FourCC format.
2024-01-12 00:49:56 +00:00
expected: String,
2024-01-16 02:44:48 +00:00
/// The actual format, in FourCC format.
2024-01-12 00:49:56 +00:00
actual: String,
},
2024-01-16 02:44:48 +00:00
/// Interfacing with the camera resulted in an error.
2024-01-12 00:49:56 +00:00
#[error("Unable to interface with camera: {0}")]
CameraIO(#[from] std::io::Error),
2024-01-16 02:44:48 +00:00
/// Decoding an image from the camera resulted in an error.
2024-01-12 00:49:56 +00:00
#[error("Could not decode image: {0}")]
ImageDecode(#[from] image::ImageError),
}
2024-01-16 02:44:48 +00:00
/// The level of error correction when generating a QR code.
2024-01-12 00:49:56 +00:00
#[derive(Default)]
pub enum ErrorCorrection {
2024-01-16 02:44:48 +00:00
/// 7% of the QR code can be recovered.
2024-01-12 00:49:56 +00:00
#[default]
Lowest,
2024-01-16 02:44:48 +00:00
/// 15% of the QR code can be recovered.
2024-01-12 00:49:56 +00:00
Medium,
2024-01-16 02:44:48 +00:00
/// 25% of the QR code can be recovered.
2024-01-12 00:49:56 +00:00
Quartile,
2024-01-16 02:44:48 +00:00
/// 30% of the QR code can be recovered.
2024-01-12 00:49:56 +00:00
Highest,
}
/// Generate a terminal-printable QR code for a given string. Uses the `qrencode` CLI utility.
2024-01-16 02:44:48 +00:00
///
/// # Errors
/// The function may return an error if interacting with the QR code generation program fails.
2024-01-12 00:49:56 +00:00
pub fn qrencode(
text: &str,
error_correction: impl Into<Option<ErrorCorrection>>,
) -> Result<String, QRGenerationError> {
let error_correction_arg = match error_correction.into().unwrap_or_default() {
ErrorCorrection::Lowest => "L",
ErrorCorrection::Medium => "M",
ErrorCorrection::Quartile => "Q",
ErrorCorrection::Highest => "H",
};
let mut qrencode = Command::new("qrencode")
.arg("-t")
.arg("ansiutf8")
.arg("-m")
.arg("2")
.arg("-l")
.arg(error_correction_arg)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
if let Some(stdin) = qrencode.stdin.as_mut() {
stdin.write_all(text.as_bytes())?;
}
let output = qrencode.wait_with_output()?;
let result = String::from_utf8(output.stdout)?;
Ok(result)
}
const VIDEO_FORMAT_READ_ERROR: &str = "Failed to read video device format";
2024-01-16 02:44:48 +00:00
/// Continuously scan the `index`-th camera for a QR code.
2024-01-13 07:52:43 +00:00
#[cfg(feature = "decode-backend-rqrr")]
2024-01-12 00:49:56 +00:00
pub fn scan_camera(timeout: Duration, index: usize) -> Result<Option<String>, QRCodeScanError> {
let device = Device::new(index)?;
let mut fmt = device.format().unwrap_or_else(bug::panic!(VIDEO_FORMAT_READ_ERROR));
fmt.fourcc = FourCC::new(b"MPG1");
device.set_format(&fmt)?;
2024-01-12 00:49:56 +00:00
let mut stream = Stream::with_buffers(&device, Type::VideoCapture, 4)?;
let start = SystemTime::now();
while SystemTime::now()
.duration_since(start)
.unwrap_or(Duration::from_secs(0))
< timeout
{
let (buffer, _) = stream.next()?;
let image = ImageReader::new(Cursor::new(buffer))
.with_guessed_format()?
.decode()?
.to_luma8();
2024-01-13 07:52:43 +00:00
let mut image = rqrr::PreparedImage::prepare(image);
2024-01-12 00:49:56 +00:00
for grid in image.detect_grids() {
if let Ok((_, content)) = grid.decode() {
return Ok(Some(content))
}
}
}
Ok(None)
}
2024-01-13 07:52:43 +00:00
2024-01-16 02:44:48 +00:00
/// Continuously scan the `index`-th camera for a QR code.
2024-01-13 07:52:43 +00:00
#[cfg(feature = "decode-backend-zbar")]
pub fn scan_camera(timeout: Duration, index: usize) -> Result<Option<String>, QRCodeScanError> {
let device = Device::new(index)?;
let mut fmt = device.format().unwrap_or_else(bug::panic!(VIDEO_FORMAT_READ_ERROR));
fmt.fourcc = FourCC::new(b"MPG1");
device.set_format(&fmt)?;
2024-01-13 07:52:43 +00:00
let mut stream = Stream::with_buffers(&device, Type::VideoCapture, 4)?;
let start = SystemTime::now();
let mut scanner = keyfork_zbar::image_scanner::ImageScanner::new();
while SystemTime::now()
.duration_since(start)
.unwrap_or(Duration::from_secs(0))
< timeout
{
let (buffer, _) = stream.next()?;
let image = ImageReader::new(Cursor::new(buffer))
.with_guessed_format()?
.decode()?;
let image = keyfork_zbar::image::Image::from(image);
for symbol in scanner.scan_image(&image) {
return Ok(Some(String::from_utf8_lossy(symbol.data()).to_string()));
}
}
Ok(None)
}