Skip to main content

forgesworn_qr/
lib.rs

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
16/// The two tolerances of the finder scan, strict then looser.
17pub const TOLERANCES: [f64; 2] = [0.5, 0.8];
18/// The reduction factors, coarse to fine.
19pub const REDUCTIONS: [usize; 3] = [8, 4, 2];
20/// A reduced picture narrower or shorter than this cannot hold a version 1 symbol.
21pub const MIN_REDUCED: usize = 21;
22
23/// The finder candidates found in a binarised picture and in its inverse, at both tolerances.
24fn candidates(luminance: &Luminance) -> u32 {
25    let t = thresholds(luminance);
26    let bits: BitImage = binarise(luminance, &t);
27    // The inverse changes colour where the picture does, so one set of edges serves both.
28    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
40/// What the decoder does on a frame that yields no finder triple: greyscale,
41/// then the scan at full size and at each reduced size that can hold a symbol.
42/// Returns the number of finder candidates found in all.
43/// `channels` is 4 (RGBA) or 1 (grey); rows are `width` pixels apart.
44pub 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    /// The browser adapter's ABI version. Changes when existing exports change meaning.
60    #[no_mangle]
61    pub extern "C" fn qr_abi_version() -> u32 { if cfg!(feature = "host-text") { 2 } else { 1 } }
62
63    /// Reserves `len` bytes of WebAssembly memory and returns their address.
64    #[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    /// Gives back what `alloc(len)` returned.
73    ///
74    /// # Safety
75    /// `ptr` must come from `alloc(len)` with the same `len`, and not have been freed.
76    #[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    /// Runs the front end on `width` x `height` pixels at `ptr`, `channels`
82    /// bytes each (1 or 4), and returns the finder candidates found.
83    ///
84    /// # Safety
85    /// `ptr` must address `width * height * channels` readable bytes.
86    #[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    /// Runs the whole decoder on `width` x `height` pixels at `ptr`, `channels`
93    /// bytes each (1 or 4), rows `width` pixels apart, dark on light and then
94    /// light on dark. Returns 0 when nothing reads, else the number of payload
95    /// bytes read plus 1.
96    ///
97    /// # Safety
98    /// `ptr` must address `width * height * channels` readable bytes.
99    #[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    // The whole result of a decode. `read_picture` and `read_grid` return a
110    // handle (never 0) for a symbol read, or 0; `read_error()` then says why.
111    // Give the handle back with `read_free`. Argument encoding:
112    //
113    //   read_picture(ptr, len, width, height, channels, row_stride, inversion)
114    //     ptr, len     the pixels: `len` bytes at `ptr`, which must cover the
115    //                  last row (`row_stride * (height - 1) + width` pixels of
116    //                  `channels` bytes)
117    //     channels     1 (grey) or 4 (RGBA)
118    //     row_stride   pixels from one row to the next, at least `width`
119    //     inversion    0 both (dark on light first), 1 normal, 2 inverted
120    //   read_grid(ptr, len, size)
121    //     the module grid of `size * size` bytes (nonzero for dark, row by
122    //     row, no quiet zone) as `decode_modules` reads it; mirrored grids read
123    //
124    // `read_error()` after a call: 0 a symbol was read, 1 nothing read, 2
125    // channels neither 1 nor 4, 3 width or height 0, 4 row_stride under
126    // width, 5 fewer bytes than the picture or grid needs, 6 inversion not 0,
127    // 1 or 2. Where the TypeScript `decode` throws, this is 2 to 6; where it
128    // returns undefined, this is 1.
129    //
130    // Accessors take the handle. Pointers address bytes inside the WebAssembly
131    // memory, valid until `read_free`, and are not to be read when the length
132    // is 0. Booleans are 0 or 1. Coordinates are `f64`, which the host sees as
133    // JavaScript numbers with the same bits.
134    //
135    //   read_bytes_ptr, read_bytes_len     the payload bytes
136    //   read_text_ptr, read_text_len       the text as UTF-8
137    //   read_version, read_level (0 L, 1 M, 2 Q, 3 H), read_mask, read_corrected
138    //   read_mirrored, read_inverted
139    //   read_eci_count, read_eci(h, i)     the ECI assignments, in order
140    //   read_located(h)                    1 for a picture, 0 for a grid
141    //   read_point_x(h, which), read_point_y(h, which)
142    //                                      which 0 top-left, 1 top-right,
143    //                                      2 bottom-left, 3 alignment; 0.0 for
144    //                                      a grid
145    //   read_has_alignment(h)
146    //   read_sa_present, read_sa_index, read_sa_total, read_sa_parity
147    //   read_fnc1(h)                       0 none, 1 first position, 2 second
148    //   read_fnc1_ptr, read_fnc1_len       the application indicator (second
149    //                                      position only), ASCII
150    //
151    // The eight work counters of the last `read_picture` (steps, compared,
152    // scanned, maps, second, meshes, probed, reduced; all zero after a bad
153    // argument or `read_grid`) are 64-bit, so they come as two unsigned 32-bit
154    // halves: `work_low(i)` and `work_high(i)`, for i 0 to 7. The host joins
155    // them as high * 2^32 + low. They stay readable after a call that read
156    // nothing.
157
158    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    /// Why the last `read_picture` or `read_grid` returned 0; 0 if it read a symbol.
175    #[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    /// Decodes the picture. See above for the arguments.
195    ///
196    /// # Safety
197    /// `ptr` must address `len` readable bytes.
198    #[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    /// Reads the module grid. See above for the arguments.
231    ///
232    /// # Safety
233    /// `ptr` must address `len` readable bytes.
234    #[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    /// Gives back a result. The handle is not valid afterwards.
252    ///
253    /// # Safety
254    /// `h` must come from `read_picture` or `read_grid` and be freed once.
255    #[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                /// An accessor on a result handle; see the notes above.
264                ///
265                /// # Safety
266                /// `h` must come from `read_picture` or `read_grid` and not have been freed.
267                #[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    /// The `i`th ECI assignment (0 when `i` is out of range).
316    ///
317    /// # Safety
318    /// As the other accessors.
319    #[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    /// The x of a location point (see above for `which`); 0.0 if there is none.
336    ///
337    /// # Safety
338    /// As the other accessors.
339    #[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    /// The y of a location point (see above for `which`); 0.0 if there is none.
345    ///
346    /// # Safety
347    /// As the other accessors.
348    #[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    /// The low 32 bits of work counter `i` (0 to 7) of the last `read_picture`.
354    #[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    /// The high 32 bits of work counter `i` (0 to 7) of the last `read_picture`.
360    #[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    // The encoder. Argument encoding, shared by `encode_text` and `encode_bytes`:
366    //
367    //   ecc          0 L, 1 M, 2 Q, 3 H
368    //   version      0 for "the smallest that fits", else 1 to 40
369    //   min_version  0 for 1, else 1 to 40
370    //   mask         0xFFFFFFFF (-1) for "the best", else 0 to 7
371    //   mode         0 for "the cheapest mix", 1 numeric, 2 alphanumeric, 3 byte
372    //                (`encode_bytes` has no mode: bytes are one byte segment)
373    //   eci          0 for none, nonzero for a UTF-8 ECI designator
374    //
375    // Both return a handle (never 0) for a finished symbol, or 0 on failure;
376    // `encode_error()` then says why. Read the symbol with `qr_size`,
377    // `qr_version`, `qr_mask`, `qr_mode` and `qr_modules` (the address of
378    // `size * size` bytes, 1 for dark, row by row, no quiet zone, valid until
379    // `qr_free`), then give the handle back with `qr_free`. Text is UTF-8;
380    // bytes that are not valid UTF-8 become U+FFFD as TextEncoder would have
381    // made them, so the JavaScript side need not check.
382
383    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    /// Why the last `encode_text` or `encode_bytes` returned 0: 1 data does not
392    /// fit, 2 version out of range, 3 min_version out of range, 4 mask out of
393    /// range, 5 version below min_version, 6 mode other than byte for bytes,
394    /// 7 text outside the named mode, 8 unknown level, 9 unknown mode.
395    #[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    /// Encodes the UTF-8 text of `len` bytes at `ptr`. See above for the other arguments.
443    ///
444    /// # Safety
445    /// `ptr` must address `len` readable bytes.
446    #[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    /// Encodes the `len` bytes at `ptr` as one byte segment. See above for the other arguments.
460    ///
461    /// # Safety
462    /// `ptr` must address `len` readable bytes.
463    #[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    /// Modules per side of the symbol behind `handle`.
476    ///
477    /// # Safety
478    /// `handle` must come from `encode_text` or `encode_bytes` and not have been freed.
479    #[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    /// The version, 1 to 40.
485    ///
486    /// # Safety
487    /// As `qr_size`.
488    #[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    /// The mask, 0 to 7.
494    ///
495    /// # Safety
496    /// As `qr_size`.
497    #[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    /// The widest mode: 1 numeric, 2 alphanumeric, 3 byte.
503    ///
504    /// # Safety
505    /// As `qr_size`.
506    #[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    /// The level: 0 L, 1 M, 2 Q, 3 H.
512    ///
513    /// # Safety
514    /// As `qr_size`.
515    #[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    /// Number of data segments.
521    ///
522    /// # Safety
523    /// As `qr_size`.
524    #[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    /// Segment mode: 1 numeric, 2 alphanumeric, 3 byte; 0 for an invalid index.
530    ///
531    /// # Safety
532    /// As `qr_size`.
533    #[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    /// Segment character count (byte count in byte mode); 0 for an invalid index.
539    ///
540    /// # Safety
541    /// As `qr_size`.
542    #[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    /// The address of the modules: `size * size` bytes, 1 for dark, valid until `qr_free`.
548    ///
549    /// # Safety
550    /// As `qr_size`.
551    #[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    /// Gives back a symbol. The handle is not valid afterwards.
557    ///
558    /// # Safety
559    /// As `qr_size`, and each handle is freed once.
560    #[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}