#![doc = include_str!("../README.md")]
pub mod binarise;
pub mod decode;
pub mod encode;
pub mod locate;
pub mod place;
pub mod refine;
pub mod render;
pub mod symbol;
pub mod tables;
use binarise::{binarise, invert, thresholds, to_luminance, BitImage, Luminance, Reductions};
use locate::{find_finders, Edges};
pub const TOLERANCES: [f64; 2] = [0.5, 0.8];
pub const REDUCTIONS: [usize; 3] = [8, 4, 2];
pub const MIN_REDUCED: usize = 21;
fn candidates(luminance: &Luminance) -> u32 {
let t = thresholds(luminance);
let bits: BitImage = binarise(luminance, &t);
let mut edges = Edges::new(&bits);
let mut total = 0usize;
for tolerance in TOLERANCES {
total += find_finders(&bits, tolerance, None, &mut edges).len();
}
let inverse = invert(&bits);
for tolerance in TOLERANCES {
total += find_finders(&inverse, tolerance, None, &mut edges).len();
}
total as u32
}
pub fn front(data: &[u8], width: usize, height: usize, channels: usize) -> u32 {
let luminance = to_luminance(data, width, height, channels, width);
let mut total = candidates(&luminance);
let mut shrunk = Reductions::new(&luminance);
for f in REDUCTIONS {
if width / f < MIN_REDUCED || height / f < MIN_REDUCED {
continue;
}
total += candidates(&shrunk.get(f));
}
total
}
#[cfg(target_arch = "wasm32")]
mod exports {
#[no_mangle]
pub extern "C" fn qr_abi_version() -> u32 { if cfg!(feature = "host-text") { 2 } else { 1 } }
#[no_mangle]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
let mut v = Vec::<u8>::with_capacity(len);
let ptr = v.as_mut_ptr();
std::mem::forget(v);
ptr
}
#[no_mangle]
pub unsafe extern "C" fn free(ptr: *mut u8, len: usize) {
drop(Vec::from_raw_parts(ptr, 0, len));
}
#[no_mangle]
pub unsafe extern "C" fn front(ptr: *const u8, width: u32, height: u32, channels: u32) -> u32 {
let len = width as usize * height as usize * channels as usize;
super::front(std::slice::from_raw_parts(ptr, len), width as usize, height as usize, channels as usize)
}
#[no_mangle]
pub unsafe extern "C" fn decode(ptr: *const u8, width: u32, height: u32, channels: u32) -> u32 {
let len = width as usize * height as usize * channels as usize;
let pixels = std::slice::from_raw_parts(ptr, len);
match super::decode::decode(pixels, width as usize, height as usize, channels as usize, width as usize, super::decode::Inversion::Both, None) {
Some(reading) => reading.payload.bytes.len() as u32 + 1,
None => 0,
}
}
use crate::decode::{decode as decode_picture, Inversion, Place};
use crate::locate::Work;
use crate::symbol::{decode_modules, Fnc1, Payload};
struct Read {
payload: Payload,
mirrored: bool,
inverted: bool,
location: Option<Place>,
}
thread_local! {
static LAST_READ_ERROR: Cell<u32> = const { Cell::new(0) };
static LAST_WORK: Cell<[u64; 8]> = const { Cell::new([0; 8]) };
}
#[no_mangle]
pub extern "C" fn read_error() -> u32 {
LAST_READ_ERROR.with(|e| e.get())
}
fn set_work(work: [u64; 8]) {
LAST_WORK.with(|w| w.set(work));
}
fn fail(code: u32) -> u32 {
LAST_READ_ERROR.with(|e| e.set(code));
0
}
fn handle(read: Read) -> u32 {
LAST_READ_ERROR.with(|e| e.set(0));
Box::into_raw(Box::new(read)) as usize as u32
}
#[no_mangle]
pub unsafe extern "C" fn read_picture(ptr: *const u8, len: usize, width: u32, height: u32, channels: u32, row_stride: u32, inversion: u32) -> u32 {
set_work([0; 8]);
if channels != 1 && channels != 4 {
return fail(2);
}
if width == 0 || height == 0 {
return fail(3);
}
if row_stride < width {
return fail(4);
}
let inversion = match inversion {
0 => Inversion::Both,
1 => Inversion::Normal,
2 => Inversion::Inverted,
_ => return fail(6),
};
let needed = (row_stride as u64 * (height as u64 - 1) + width as u64) * channels as u64;
if (len as u64) < needed {
return fail(5);
}
let pixels = std::slice::from_raw_parts(ptr, len);
let mut work = Work::default();
let found = decode_picture(pixels, width as usize, height as usize, channels as usize, row_stride as usize, inversion, Some(&mut work));
set_work([work.steps, work.compared, work.scanned, work.maps, work.second, work.meshes, work.probed, work.reduced]);
match found {
Some(r) => handle(Read { payload: r.payload, mirrored: r.mirrored, inverted: r.inverted, location: Some(r.location) }),
None => fail(1),
}
}
#[no_mangle]
pub unsafe extern "C" fn read_grid(ptr: *const u8, len: usize, size: u32) -> u32 {
set_work([0; 8]);
if (len as u64) < size as u64 * size as u64 {
return fail(5);
}
let modules = if len == 0 { &[][..] } else { std::slice::from_raw_parts(ptr, len) };
match decode_modules(modules, size as usize) {
Some(d) => handle(Read { payload: d.payload, mirrored: d.mirrored, inverted: false, location: None }),
None => fail(1),
}
}
unsafe fn read<'a>(h: u32) -> &'a Read {
&*(h as usize as *const Read)
}
#[no_mangle]
pub unsafe extern "C" fn read_free(h: u32) {
drop(Box::from_raw(h as usize as *mut Read));
}
macro_rules! accessors {
($($name:ident($r:ident) -> $t:ty $body:block)*) => {
$(
/// An accessor on a result handle; see the notes above.
///
/// # Safety
/// `h` must come from `read_picture` or `read_grid` and not have been freed.
#[no_mangle]
pub unsafe extern "C" fn $name(h: u32) -> $t {
let $r = read(h);
$body
}
)*
};
}
accessors! {
read_bytes_ptr(r) -> *const u8 { r.payload.bytes.as_ptr() }
read_bytes_len(r) -> u32 { r.payload.bytes.len() as u32 }
read_text_ptr(r) -> *const u8 { r.payload.text.as_ptr() }
read_text_len(r) -> u32 { r.payload.text.len() as u32 }
read_version(r) -> u32 { r.payload.version as u32 }
read_level(r) -> u32 { r.payload.ecc as u32 }
read_mask(r) -> u32 { r.payload.mask as u32 }
read_corrected(r) -> u32 { r.payload.corrected as u32 }
read_mirrored(r) -> u32 { r.mirrored as u32 }
read_inverted(r) -> u32 { r.inverted as u32 }
read_eci_count(r) -> u32 { r.payload.eci.len() as u32 }
read_located(r) -> u32 { r.location.is_some() as u32 }
read_has_alignment(r) -> u32 { r.location.is_some_and(|p| p.alignment.is_some()) as u32 }
read_sa_present(r) -> u32 { r.payload.structured_append.is_some() as u32 }
read_sa_index(r) -> u32 { r.payload.structured_append.map_or(0, |s| s.index) }
read_sa_total(r) -> u32 { r.payload.structured_append.map_or(0, |s| s.total) }
read_sa_parity(r) -> u32 { r.payload.structured_append.map_or(0, |s| s.parity) }
read_fnc1(r) -> u32 {
match r.payload.fnc1 {
None => 0,
Some(Fnc1::First) => 1,
Some(Fnc1::Second(_)) => 2,
}
}
read_fnc1_ptr(r) -> *const u8 {
match &r.payload.fnc1 {
Some(Fnc1::Second(s)) => s.as_ptr(),
_ => std::ptr::NonNull::dangling().as_ptr(),
}
}
read_fnc1_len(r) -> u32 {
match &r.payload.fnc1 {
Some(Fnc1::Second(s)) => s.len() as u32,
_ => 0,
}
}
}
#[no_mangle]
pub unsafe extern "C" fn read_eci(h: u32, i: u32) -> u32 {
read(h).payload.eci.get(i as usize).copied().unwrap_or(0)
}
fn point(r: &Read, which: u32) -> Option<crate::place::Point> {
let p = r.location?;
match which {
0 => Some(p.top_left),
1 => Some(p.top_right),
2 => Some(p.bottom_left),
3 => p.alignment,
_ => None,
}
}
#[no_mangle]
pub unsafe extern "C" fn read_point_x(h: u32, which: u32) -> f64 {
point(read(h), which).map_or(0.0, |p| p.x)
}
#[no_mangle]
pub unsafe extern "C" fn read_point_y(h: u32, which: u32) -> f64 {
point(read(h), which).map_or(0.0, |p| p.y)
}
#[no_mangle]
pub extern "C" fn work_low(i: u32) -> u32 {
LAST_WORK.with(|w| w.get().get(i as usize).map_or(0, |&v| v as u32))
}
#[no_mangle]
pub extern "C" fn work_high(i: u32) -> u32 {
LAST_WORK.with(|w| w.get().get(i as usize).map_or(0, |&v| (v >> 32) as u32))
}
use crate::encode::{encode, Error, Mode, Options, QrCode};
use crate::symbol::Ecc;
use std::cell::Cell;
thread_local! {
static LAST_ERROR: Cell<u32> = const { Cell::new(0) };
}
#[no_mangle]
pub extern "C" fn encode_error() -> u32 {
LAST_ERROR.with(|e| e.get())
}
fn options(ecc: u32, version: u32, min_version: u32, mask: u32, mode: u32, eci: u32) -> Result<Options, u32> {
let ecc = *Ecc::ORDER.get(ecc as usize).ok_or(8u32)?;
let mode = match mode {
0 => None,
1 => Some(Mode::Numeric),
2 => Some(Mode::Alphanumeric),
3 => Some(Mode::Byte),
_ => return Err(9),
};
Ok(Options {
ecc,
version: (version != 0).then_some(version as usize),
min_version: (min_version != 0).then_some(min_version as usize),
mask: (mask != u32::MAX).then_some(mask as usize),
mode,
eci: eci != 0,
})
}
fn finish(result: Result<QrCode, Error>) -> u32 {
match result {
Ok(qr) => {
LAST_ERROR.with(|e| e.set(0));
Box::into_raw(Box::new(qr)) as usize as u32
}
Err(e) => {
LAST_ERROR.with(|c| {
c.set(match e {
Error::Capacity { .. } => 1,
Error::InvalidVersion(_) => 2,
Error::InvalidMinVersion(_) => 3,
Error::InvalidMask(_) => 4,
Error::VersionBelowMinimum { .. } => 5,
Error::BytesNeedByteMode(_) => 6,
Error::NotInMode { .. } => 7,
})
});
0
}
}
}
#[no_mangle]
pub unsafe extern "C" fn encode_text(ptr: *const u8, len: usize, ecc: u32, version: u32, min_version: u32, mask: u32, mode: u32, eci: u32) -> u32 {
let bytes = if len == 0 { &[][..] } else { std::slice::from_raw_parts(ptr, len) };
let text = String::from_utf8_lossy(bytes);
match options(ecc, version, min_version, mask, mode, eci) {
Ok(o) => finish(encode(&*text, &o)),
Err(code) => {
LAST_ERROR.with(|e| e.set(code));
0
}
}
}
#[no_mangle]
pub unsafe extern "C" fn encode_bytes(ptr: *const u8, len: usize, ecc: u32, version: u32, min_version: u32, mask: u32, eci: u32) -> u32 {
let bytes = if len == 0 { &[][..] } else { std::slice::from_raw_parts(ptr, len) };
match options(ecc, version, min_version, mask, 0, eci) {
Ok(o) => finish(encode(bytes, &o)),
Err(code) => {
LAST_ERROR.with(|e| e.set(code));
0
}
}
}
#[no_mangle]
pub unsafe extern "C" fn qr_size(handle: u32) -> u32 {
(*(handle as usize as *const QrCode)).size as u32
}
#[no_mangle]
pub unsafe extern "C" fn qr_version(handle: u32) -> u32 {
(*(handle as usize as *const QrCode)).version as u32
}
#[no_mangle]
pub unsafe extern "C" fn qr_mask(handle: u32) -> u32 {
(*(handle as usize as *const QrCode)).mask as u32
}
#[no_mangle]
pub unsafe extern "C" fn qr_mode(handle: u32) -> u32 {
(*(handle as usize as *const QrCode)).mode as u32 + 1
}
#[no_mangle]
pub unsafe extern "C" fn qr_level(handle: u32) -> u32 {
(*(handle as usize as *const QrCode)).ecc as u32
}
#[no_mangle]
pub unsafe extern "C" fn qr_segments(handle: u32) -> u32 {
(*(handle as usize as *const QrCode)).segments.len() as u32
}
#[no_mangle]
pub unsafe extern "C" fn qr_segment_mode(handle: u32, index: u32) -> u32 {
(&(*(handle as usize as *const QrCode)).segments).get(index as usize).map_or(0, |s| s.mode as u32 + 1)
}
#[no_mangle]
pub unsafe extern "C" fn qr_segment_count(handle: u32, index: u32) -> u32 {
(&(*(handle as usize as *const QrCode)).segments).get(index as usize).map_or(0, |s| s.count as u32)
}
#[no_mangle]
pub unsafe extern "C" fn qr_modules(handle: u32) -> *const u8 {
(*(handle as usize as *const QrCode)).modules.as_ptr()
}
#[no_mangle]
pub unsafe extern "C" fn qr_free(handle: u32) {
drop(Box::from_raw(handle as usize as *mut QrCode));
}
}