1#![doc = include_str!("../README.md")]
2
3pub mod binarise;
4pub mod decode;
5pub mod encode;
6pub mod locate;
7pub mod place;
8pub mod refine;
9pub mod render;
10pub mod symbol;
11pub mod tables;
12
13use binarise::{binarise, invert, thresholds, to_luminance, BitImage, Luminance, Reductions};
14use locate::{find_finders, Edges};
15
16pub const TOLERANCES: [f64; 2] = [0.5, 0.8];
18pub const REDUCTIONS: [usize; 3] = [8, 4, 2];
20pub const MIN_REDUCED: usize = 21;
22
23fn candidates(luminance: &Luminance) -> u32 {
25 let t = thresholds(luminance);
26 let bits: BitImage = binarise(luminance, &t);
27 let mut edges = Edges::new(&bits);
29 let mut total = 0usize;
30 for tolerance in TOLERANCES {
31 total += find_finders(&bits, tolerance, None, &mut edges).len();
32 }
33 let inverse = invert(&bits);
34 for tolerance in TOLERANCES {
35 total += find_finders(&inverse, tolerance, None, &mut edges).len();
36 }
37 total as u32
38}
39
40pub fn front(data: &[u8], width: usize, height: usize, channels: usize) -> u32 {
45 let luminance = to_luminance(data, width, height, channels, width);
46 let mut total = candidates(&luminance);
47 let mut shrunk = Reductions::new(&luminance);
48 for f in REDUCTIONS {
49 if width / f < MIN_REDUCED || height / f < MIN_REDUCED {
50 continue;
51 }
52 total += candidates(&shrunk.get(f));
53 }
54 total
55}
56
57#[cfg(target_arch = "wasm32")]
58mod exports {
59 #[no_mangle]
61 pub extern "C" fn qr_abi_version() -> u32 { if cfg!(feature = "host-text") { 2 } else { 1 } }
62
63 #[no_mangle]
65 pub extern "C" fn alloc(len: usize) -> *mut u8 {
66 let mut v = Vec::<u8>::with_capacity(len);
67 let ptr = v.as_mut_ptr();
68 std::mem::forget(v);
69 ptr
70 }
71
72 #[no_mangle]
77 pub unsafe extern "C" fn free(ptr: *mut u8, len: usize) {
78 drop(Vec::from_raw_parts(ptr, 0, len));
79 }
80
81 #[no_mangle]
87 pub unsafe extern "C" fn front(ptr: *const u8, width: u32, height: u32, channels: u32) -> u32 {
88 let len = width as usize * height as usize * channels as usize;
89 super::front(std::slice::from_raw_parts(ptr, len), width as usize, height as usize, channels as usize)
90 }
91
92 #[no_mangle]
100 pub unsafe extern "C" fn decode(ptr: *const u8, width: u32, height: u32, channels: u32) -> u32 {
101 let len = width as usize * height as usize * channels as usize;
102 let pixels = std::slice::from_raw_parts(ptr, len);
103 match super::decode::decode(pixels, width as usize, height as usize, channels as usize, width as usize, super::decode::Inversion::Both, None) {
104 Some(reading) => reading.payload.bytes.len() as u32 + 1,
105 None => 0,
106 }
107 }
108
109 use crate::decode::{decode as decode_picture, Inversion, Place};
159 use crate::locate::Work;
160 use crate::symbol::{decode_modules, Fnc1, Payload};
161
162 struct Read {
163 payload: Payload,
164 mirrored: bool,
165 inverted: bool,
166 location: Option<Place>,
167 }
168
169 thread_local! {
170 static LAST_READ_ERROR: Cell<u32> = const { Cell::new(0) };
171 static LAST_WORK: Cell<[u64; 8]> = const { Cell::new([0; 8]) };
172 }
173
174 #[no_mangle]
176 pub extern "C" fn read_error() -> u32 {
177 LAST_READ_ERROR.with(|e| e.get())
178 }
179
180 fn set_work(work: [u64; 8]) {
181 LAST_WORK.with(|w| w.set(work));
182 }
183
184 fn fail(code: u32) -> u32 {
185 LAST_READ_ERROR.with(|e| e.set(code));
186 0
187 }
188
189 fn handle(read: Read) -> u32 {
190 LAST_READ_ERROR.with(|e| e.set(0));
191 Box::into_raw(Box::new(read)) as usize as u32
192 }
193
194 #[no_mangle]
199 pub unsafe extern "C" fn read_picture(ptr: *const u8, len: usize, width: u32, height: u32, channels: u32, row_stride: u32, inversion: u32) -> u32 {
200 set_work([0; 8]);
201 if channels != 1 && channels != 4 {
202 return fail(2);
203 }
204 if width == 0 || height == 0 {
205 return fail(3);
206 }
207 if row_stride < width {
208 return fail(4);
209 }
210 let inversion = match inversion {
211 0 => Inversion::Both,
212 1 => Inversion::Normal,
213 2 => Inversion::Inverted,
214 _ => return fail(6),
215 };
216 let needed = (row_stride as u64 * (height as u64 - 1) + width as u64) * channels as u64;
217 if (len as u64) < needed {
218 return fail(5);
219 }
220 let pixels = std::slice::from_raw_parts(ptr, len);
221 let mut work = Work::default();
222 let found = decode_picture(pixels, width as usize, height as usize, channels as usize, row_stride as usize, inversion, Some(&mut work));
223 set_work([work.steps, work.compared, work.scanned, work.maps, work.second, work.meshes, work.probed, work.reduced]);
224 match found {
225 Some(r) => handle(Read { payload: r.payload, mirrored: r.mirrored, inverted: r.inverted, location: Some(r.location) }),
226 None => fail(1),
227 }
228 }
229
230 #[no_mangle]
235 pub unsafe extern "C" fn read_grid(ptr: *const u8, len: usize, size: u32) -> u32 {
236 set_work([0; 8]);
237 if (len as u64) < size as u64 * size as u64 {
238 return fail(5);
239 }
240 let modules = if len == 0 { &[][..] } else { std::slice::from_raw_parts(ptr, len) };
241 match decode_modules(modules, size as usize) {
242 Some(d) => handle(Read { payload: d.payload, mirrored: d.mirrored, inverted: false, location: None }),
243 None => fail(1),
244 }
245 }
246
247 unsafe fn read<'a>(h: u32) -> &'a Read {
248 &*(h as usize as *const Read)
249 }
250
251 #[no_mangle]
256 pub unsafe extern "C" fn read_free(h: u32) {
257 drop(Box::from_raw(h as usize as *mut Read));
258 }
259
260 macro_rules! accessors {
261 ($($name:ident($r:ident) -> $t:ty $body:block)*) => {
262 $(
263 #[no_mangle]
268 pub unsafe extern "C" fn $name(h: u32) -> $t {
269 let $r = read(h);
270 $body
271 }
272 )*
273 };
274 }
275
276 accessors! {
277 read_bytes_ptr(r) -> *const u8 { r.payload.bytes.as_ptr() }
278 read_bytes_len(r) -> u32 { r.payload.bytes.len() as u32 }
279 read_text_ptr(r) -> *const u8 { r.payload.text.as_ptr() }
280 read_text_len(r) -> u32 { r.payload.text.len() as u32 }
281 read_version(r) -> u32 { r.payload.version as u32 }
282 read_level(r) -> u32 { r.payload.ecc as u32 }
283 read_mask(r) -> u32 { r.payload.mask as u32 }
284 read_corrected(r) -> u32 { r.payload.corrected as u32 }
285 read_mirrored(r) -> u32 { r.mirrored as u32 }
286 read_inverted(r) -> u32 { r.inverted as u32 }
287 read_eci_count(r) -> u32 { r.payload.eci.len() as u32 }
288 read_located(r) -> u32 { r.location.is_some() as u32 }
289 read_has_alignment(r) -> u32 { r.location.is_some_and(|p| p.alignment.is_some()) as u32 }
290 read_sa_present(r) -> u32 { r.payload.structured_append.is_some() as u32 }
291 read_sa_index(r) -> u32 { r.payload.structured_append.map_or(0, |s| s.index) }
292 read_sa_total(r) -> u32 { r.payload.structured_append.map_or(0, |s| s.total) }
293 read_sa_parity(r) -> u32 { r.payload.structured_append.map_or(0, |s| s.parity) }
294 read_fnc1(r) -> u32 {
295 match r.payload.fnc1 {
296 None => 0,
297 Some(Fnc1::First) => 1,
298 Some(Fnc1::Second(_)) => 2,
299 }
300 }
301 read_fnc1_ptr(r) -> *const u8 {
302 match &r.payload.fnc1 {
303 Some(Fnc1::Second(s)) => s.as_ptr(),
304 _ => std::ptr::NonNull::dangling().as_ptr(),
305 }
306 }
307 read_fnc1_len(r) -> u32 {
308 match &r.payload.fnc1 {
309 Some(Fnc1::Second(s)) => s.len() as u32,
310 _ => 0,
311 }
312 }
313 }
314
315 #[no_mangle]
320 pub unsafe extern "C" fn read_eci(h: u32, i: u32) -> u32 {
321 read(h).payload.eci.get(i as usize).copied().unwrap_or(0)
322 }
323
324 fn point(r: &Read, which: u32) -> Option<crate::place::Point> {
325 let p = r.location?;
326 match which {
327 0 => Some(p.top_left),
328 1 => Some(p.top_right),
329 2 => Some(p.bottom_left),
330 3 => p.alignment,
331 _ => None,
332 }
333 }
334
335 #[no_mangle]
340 pub unsafe extern "C" fn read_point_x(h: u32, which: u32) -> f64 {
341 point(read(h), which).map_or(0.0, |p| p.x)
342 }
343
344 #[no_mangle]
349 pub unsafe extern "C" fn read_point_y(h: u32, which: u32) -> f64 {
350 point(read(h), which).map_or(0.0, |p| p.y)
351 }
352
353 #[no_mangle]
355 pub extern "C" fn work_low(i: u32) -> u32 {
356 LAST_WORK.with(|w| w.get().get(i as usize).map_or(0, |&v| v as u32))
357 }
358
359 #[no_mangle]
361 pub extern "C" fn work_high(i: u32) -> u32 {
362 LAST_WORK.with(|w| w.get().get(i as usize).map_or(0, |&v| (v >> 32) as u32))
363 }
364
365 use crate::encode::{encode, Error, Mode, Options, QrCode};
384 use crate::symbol::Ecc;
385 use std::cell::Cell;
386
387 thread_local! {
388 static LAST_ERROR: Cell<u32> = const { Cell::new(0) };
389 }
390
391 #[no_mangle]
396 pub extern "C" fn encode_error() -> u32 {
397 LAST_ERROR.with(|e| e.get())
398 }
399
400 fn options(ecc: u32, version: u32, min_version: u32, mask: u32, mode: u32, eci: u32) -> Result<Options, u32> {
401 let ecc = *Ecc::ORDER.get(ecc as usize).ok_or(8u32)?;
402 let mode = match mode {
403 0 => None,
404 1 => Some(Mode::Numeric),
405 2 => Some(Mode::Alphanumeric),
406 3 => Some(Mode::Byte),
407 _ => return Err(9),
408 };
409 Ok(Options {
410 ecc,
411 version: (version != 0).then_some(version as usize),
412 min_version: (min_version != 0).then_some(min_version as usize),
413 mask: (mask != u32::MAX).then_some(mask as usize),
414 mode,
415 eci: eci != 0,
416 })
417 }
418
419 fn finish(result: Result<QrCode, Error>) -> u32 {
420 match result {
421 Ok(qr) => {
422 LAST_ERROR.with(|e| e.set(0));
423 Box::into_raw(Box::new(qr)) as usize as u32
424 }
425 Err(e) => {
426 LAST_ERROR.with(|c| {
427 c.set(match e {
428 Error::Capacity { .. } => 1,
429 Error::InvalidVersion(_) => 2,
430 Error::InvalidMinVersion(_) => 3,
431 Error::InvalidMask(_) => 4,
432 Error::VersionBelowMinimum { .. } => 5,
433 Error::BytesNeedByteMode(_) => 6,
434 Error::NotInMode { .. } => 7,
435 })
436 });
437 0
438 }
439 }
440 }
441
442 #[no_mangle]
447 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 {
448 let bytes = if len == 0 { &[][..] } else { std::slice::from_raw_parts(ptr, len) };
449 let text = String::from_utf8_lossy(bytes);
450 match options(ecc, version, min_version, mask, mode, eci) {
451 Ok(o) => finish(encode(&*text, &o)),
452 Err(code) => {
453 LAST_ERROR.with(|e| e.set(code));
454 0
455 }
456 }
457 }
458
459 #[no_mangle]
464 pub unsafe extern "C" fn encode_bytes(ptr: *const u8, len: usize, ecc: u32, version: u32, min_version: u32, mask: u32, eci: u32) -> u32 {
465 let bytes = if len == 0 { &[][..] } else { std::slice::from_raw_parts(ptr, len) };
466 match options(ecc, version, min_version, mask, 0, eci) {
467 Ok(o) => finish(encode(bytes, &o)),
468 Err(code) => {
469 LAST_ERROR.with(|e| e.set(code));
470 0
471 }
472 }
473 }
474
475 #[no_mangle]
480 pub unsafe extern "C" fn qr_size(handle: u32) -> u32 {
481 (*(handle as usize as *const QrCode)).size as u32
482 }
483
484 #[no_mangle]
489 pub unsafe extern "C" fn qr_version(handle: u32) -> u32 {
490 (*(handle as usize as *const QrCode)).version as u32
491 }
492
493 #[no_mangle]
498 pub unsafe extern "C" fn qr_mask(handle: u32) -> u32 {
499 (*(handle as usize as *const QrCode)).mask as u32
500 }
501
502 #[no_mangle]
507 pub unsafe extern "C" fn qr_mode(handle: u32) -> u32 {
508 (*(handle as usize as *const QrCode)).mode as u32 + 1
509 }
510
511 #[no_mangle]
516 pub unsafe extern "C" fn qr_level(handle: u32) -> u32 {
517 (*(handle as usize as *const QrCode)).ecc as u32
518 }
519
520 #[no_mangle]
525 pub unsafe extern "C" fn qr_segments(handle: u32) -> u32 {
526 (*(handle as usize as *const QrCode)).segments.len() as u32
527 }
528
529 #[no_mangle]
534 pub unsafe extern "C" fn qr_segment_mode(handle: u32, index: u32) -> u32 {
535 (&(*(handle as usize as *const QrCode)).segments).get(index as usize).map_or(0, |s| s.mode as u32 + 1)
536 }
537
538 #[no_mangle]
543 pub unsafe extern "C" fn qr_segment_count(handle: u32, index: u32) -> u32 {
544 (&(*(handle as usize as *const QrCode)).segments).get(index as usize).map_or(0, |s| s.count as u32)
545 }
546
547 #[no_mangle]
552 pub unsafe extern "C" fn qr_modules(handle: u32) -> *const u8 {
553 (*(handle as usize as *const QrCode)).modules.as_ptr()
554 }
555
556 #[no_mangle]
561 pub unsafe extern "C" fn qr_free(handle: u32) {
562 drop(Box::from_raw(handle as usize as *mut QrCode));
563 }
564}