A from-scratch Rust library for decoding and encoding 1D and 2D barcodes, aiming for the widest possible symbology coverage while preserving every variation of a code.
▶ Live WASM demo — generate any symbology (Apple App Clip Codes included), decode an image, and run live-camera scanning with a tracked target-lock overlay, all in the browser (the library compiled to WebAssembly, no wasm-bindgen).
- Lossless round-trip. A decoded [
Symbol] carries not just its payload but the exact encoding decisions — segmentation, version/size, error-correction level, mask. Feeding a decoded symbol straight back into the encoder reproduces the original symbol byte-for-byte. - Live-video ready. A cheap per-frame detection pass (locate + classify) is separated from a heavier analysis/decode pass, and previous-frame hints let the pipeline skip re-analyzing codes it already knows.
- Portable input. The video boundary is a borrowed luminance buffer
(
GrayFrame); the caller owns capture and color conversion, so the core has no media dependencies.
The full symbology catalog is modeled in the Symbology enum, but
implementations land incrementally. Query Symbology::is_implemented() at runtime.
Legend: ✅ done · 🚧 in progress · ⬜ planned.
| Symbology | Encode | Decode | Detect |
|---|---|---|---|
| QR Code (v1–40, all EC levels & masks) | ✅ | ✅ | ✅¹ |
| Data Matrix (ECC 200, square + rectangular + DMRE, all encodations, GS1) | ✅ | ✅ | ✅³ |
| Aztec (compact + full range, all modes) · Aztec Runes | ✅ | ✅ | ✅⁶ |
| Micro QR Code (M1–M4) | ✅ | ✅ | ✅⁶ |
| Rectangular Micro QR (rMQR, all 32 sizes) | ✅ | ✅ | ✅⁶ |
| MaxiCode (modes 2–6) | ✅ | ✅ | ✅⁸ |
| Han Xin (versions 1–3, Numeric/Text/Byte) | ✅ | ✅ | ⬜ |
| DotCode (GF(113) RS) | ✅ | ✅ | ⬜ |
| Grid Matrix (all 13 versions) | ✅ | ✅ | ⬜ |
| Apple App Clip Code (URL codec + SVG, camera & NFC variants)⁵ | ✅ | ✅ | ✅ |
| Symbology | Encode | Decode | Detect |
|---|---|---|---|
| PDF417 (Text/Byte/Numeric, EC 0–8) | ✅ | ✅ | ✅⁴ |
| MicroPDF417 (all 34 size variants) | ✅ | ✅ | ✅⁷ |
| Code 16K · Code 49 · Codablock F | ✅ | ✅ | ⬜ |
| GS1 DataBar Stacked / Stacked Omni / Expanded Stacked | ✅ | ✅ | ✅² |
| Symbology | Encode | Decode | Detect |
|---|---|---|---|
| EAN-13 · EAN-8 · UPC-A · UPC-E | ✅ | ✅ | ✅² |
| UPC/EAN add-ons: EAN-2 · EAN-5 | ✅ | ✅ | ✅² |
| Code 128 · GS1-128 | ✅ | ✅ | ✅² |
| Code 39 · Code 93 · Code 11 | ✅ | ✅ | ✅² |
| ITF · Standard / IATA / Matrix 2 of 5 | ✅ | ✅ | ✅² |
| Codabar · MSI Plessey · Plessey | ✅ | ✅ | ✅² |
| Telepen | ✅ | ✅ | ✅² |
| Pharmacode (1- & 2-track) | ✅ | ✅ | ⬜ |
| GS1 DataBar Omni (RSS-14) · Limited · Expanded | ✅ | ✅ | ✅² (not Limited) |
| DX Film Edge | ✅ | ✅ | ⬜ |
| Symbology | Encode | Decode | Detect |
|---|---|---|---|
| POSTNET · PLANET · Intelligent Mail (IMb) | ✅ | ✅ | ⬜ |
| Royal Mail (RM4SCC) · Dutch KIX | ✅ | ✅ | ⬜ |
| Royal Mail Mailmark (Barcode C & L) | ✅ | ✅ | ⬜ |
| Australia Post 4-State · Japan Post 4-State | ✅ | ✅ | ⬜ |
¹ QR ships a hardened image sampler: a global-Otsu → adaptive (Bradley/Sauvola)
binarization ladder, dual-axis finder detection with a synthesized-third-corner
fallback, perspective recovery via the alignment pattern, and — for curved or
degraded captures — a thin-plate-spline dewarp anchored on every finder, alignment
pattern and timing-pattern crossing, biased module classification, and a
Reed–Solomon-arbitrated brute force over all 32 format configurations when blur
wrecks the format fields. Robust to any-angle rotation, tilt, blur, noise, uneven
lighting and cylinder curvature; clean-render envelope in tests/harness_image.rs,
real-capture envelope (bottle and can labels down to ≈4.6 px/module) in
tests/real_world.rs.
² 1D detection is the shared scan1d luminance front-end. Each scan line is a
band-averaged profile (real pixels, no interpolation) thresholded against a sliding
local mid-level, then cut into spans at every run too wide to be a symbol element —
so a label edge, a dark surface beyond the label, print beside the code or a second
code on the same line do not disturb the read — and each span is quantized on its own
with a joint module-width / bar-vs-space-bias fit. Scan lines run at any angle, straight
out of the frame. pipeline::scan_1d tries horizontal, then the crop's
edge-orientation peaks, then vertical; pipeline::scan_1d_at takes a known reading
axis (the locator reports one), refined by profile sharpness. Readings are accepted by
consensus, not on a single decode: at least two scan lines must agree, the span must
show real quiet zones, the payload must be plausibly long for its symbology (only
Code 128, Code 93 and EAN/UPC carry a check character), and a reading that is a fragment
of a longer, equally supported one is dropped. EAN/UPC additionally has a width-ratio
reader for curved and blurred captures. The shared entry points currently try the
Code 128, EAN/UPC, Code 93, Code 39, ITF and Codabar decoders; the other linear decoders
are driven by handing scan1d::scan_spans candidates to scan1d::try_decode. GS1
DataBar has no start/stop pattern to cut a span by, so it has its own reader on the
same scan lines (codes::databar::scan): it finds the finder patterns by their
width ratios, reads the data characters either side of each, and assembles a symbol
from halves (Omnidirectional family) or blocks (Expanded family) that at least two scan
lines read identically, that pass the checksum, and that lie where the parts of one
symbol do — which is also how the rows of a stacked symbol, read on different lines,
come together. DataBar Limited and Pharmacode still need dedicated samplers. End-to-end
coverage: tests/live_pipeline.rs, tests/scan1d_pipeline.rs, tests/rotated1d.rs,
tests/databar_image.rs.
³ Data Matrix ships an image sampler: Otsu binarization → the largest few dark
components tried in turn, each analysed under a mask clipped to its own quad (so a dark
surface behind the label or print beside the code neither displaces the symbol nor
attracts the corner and edge fits) → solid-L finder + timing-edge line fitting → perspective corners → imgproc grid
sampling, with symbol size and grid chirality confirmed by Reed–Solomon. Robust to
any-angle rotation, scale, blur/noise and (size-graded) tilt; envelope in
tests/datamatrix_image.rs.
⁴ PDF417 (finder-less) is located by its start/stop guard columns → RANSAC edge fit →
affine grid sampling → RS-corrected decode. Handles upright, rotation ≤±10°, scale,
blur and noise; perspective keystoning is out of scope (no interior anchor). Envelope
in tests/pdf417_image.rs. On the live path the locator reports a PDF417 as a linear
region with its axis, and pipeline::scan_linear_at derotates the crop by it first, so
located symbols read at any rotation.
⁶ Aztec, Micro QR and rMQR ship image samplers built on their native fiducials:
Aztec's bullseye (equal-run cross-section scan → the enclosed light annulus floods
cleanly and its corners anchor a core homography → the mode-message ring, read in
image space, gives the exact symbol size); Micro QR's single finder (QR-style ratio
scan → the separator-isolated outer ring's corners anchor the grid → four rotations
× four sizes arbitrated by format/ECC); and rMQR's finder plus its finder-side
format copy, which is read in image space to learn the exact rectangle before
sampling — with the finder-sub centre dot pinned as a far anchor so wide symbols
(up to 139 modules) stay registered. All handle any-angle rotation, scale, blur and
noise; envelopes in tests/aztec_image.rs / tests/microqr_image.rs /
tests/rmqr_image.rs.
⁵ Apple has never published the App Clip Code format; this is an independent,
from-scratch implementation following the public reverse engineering of Apple's
generator (rs/appclipcode, MIT), byte-verified against URLCompression.framework
output. Encode produces the circular five-ring SVG (all 18 Apple color templates,
camera and NFC center glyphs); decode covers both the structural path (ring bits →
URL) and camera detection — a grayscale ring detector (gradient-normal Hough over the
five-ring geometry, affine/tilt refinement, rotation search, RS-arbitrated bit
recovery) wired into pipeline::scan_2d. The trained
Huffman tables embed ~1.7 MB, so the module sits behind its own appclip cargo
feature (part of the default all-codes; see Cargo features). Apple, App Clips and
related marks are trademarks of Apple Inc.
⁷ MicroPDF417 has no start/stop guards (its Row Address Patterns vary per row), but
only 34 rigid size variants exist: the sampler corners the dark-pixel cloud (as the
Data Matrix sampler does), then tries the variants whose module aspect matches the
measured quad, nearest first, across the four rotations — Reed–Solomon arbitrates.
Any-angle rotation, scale, blur, noise; envelope in tests/micropdf417_image.rs.
⁸ MaxiCode ships an image sampler built on its bullseye: a row scan for the
eleven-run cross-section (no binarization — the grey rows are classified as they are
read, against Otsu and then a sliding mean) → rays over the grey image fit an ellipse
to the rings → the hexagonal lattice's rotation and pitch are searched for the pose
under which the image is constant within a module and changes between modules → the
six orientation triplets pick the upright sixth of a turn → patches of modules are
slid into register and a homography solved through them, outwards from the bullseye →
Reed–Solomon validates. Any-angle rotation, 4 px modules and up, blur, noise, shadow,
ink spread, and tilt to a 20 % foreshortening; envelope in tests/maxicode_image.rs.
codes::maxicode::render_hex draws the printed symbol (hexagons and bullseye), which
the square-module render cannot.
Naming note. GS1 DataBar was formerly "RSS": DataBar Omnidirectional = RSS-14, DataBar Limited = RSS Limited, DataBar Expanded = RSS Expanded. Codabar is sometimes called "Coda"/NW-7. These are aliases for the same
Symbologyvariants above.
The library is always #![no_std], and every capability and symbology is a cargo
feature. The defaults turn everything on; for a lean or embedded build, disable them
and pick what you need:
# QR + Code 128 encode/decode on a no_std target with a global allocator
anyd = { version = "0.1", default-features = false, features = ["alloc", "encode", "decode", "qr", "code128"] }| Feature | Enables |
|---|---|
std (default) |
alloc + float math: image scanning, image transforms, std interop |
alloc |
the owned data model (Symbol, Segment, BitMatrix, LinearPattern, ...) |
encode (default) |
encoders: heap-free encode_into (see below), plus the Encode trait with alloc |
decode (default) |
structural decoders (Decode trait); implies alloc |
scan (default) |
camera / still-image samplers, detect, pipeline, scan1d; implies std + decode |
all-codes (default) |
every symbology below |
matrix / stacked / linear / postal |
one family |
qr microqr rmqr aztec datamatrix maxicode hanxin dotcode gridmatrix appclip |
2D matrix codes |
pdf417 (incl. MicroPDF417) code16k code49 codablockf |
stacked codes |
ean code128 code39 code93 code11 itf twoof5 codabar msi telepen pharmacode dxfilm databar |
linear codes |
cli / wasm |
the anyd binary / the browser-demo FFI shim (both enable everything) |
Symbology::is_implemented() reports which symbologies a given build carries.
Without alloc, the encode feature still provides encode_into encoders that write
into memory you own, with sizing constants and no allocation:
- 1D codes — Code 128 / GS1-128 (including the code-set planner), Code 39, Code 93,
Code 11, EAN/UPC with add-ons, ITF, 2 of 5, Codabar, MSI / Plessey, Telepen and
Pharmacode — write to any
LinearSink: a bit-packedLinearBufover a byte array, or your own sink that streams bars straight to a printer or display. - QR, Micro QR and Data Matrix write a bit-packed
MatrixBufinto caller buffers, choosing the version/size and mask themselves unless you pin them.
use anyd::codes::qr::{EcLevel, QrEncoder};
let mut scratch = [0u8; QrEncoder::MAX_BUFFER_LEN]; // 3917 bytes covers version 40
let mut storage = [0u8; QrEncoder::MAX_BUFFER_LEN];
let (grid, meta) = QrEncoder::new()
.encode_text_into(b"HELLO WORLD", EcLevel::Q, &mut scratch, &mut storage)
.unwrap();
// grid.get(x, y) == true is a dark module; meta pins version, EC level and mask.With alloc, the Encode implementations are thin wrappers over these cores, so both
paths produce byte-identical symbols. Decoding and image scanning require alloc
(and std for scanning).
use anyd::codes::qr::{EcLevel, QrDecoder, QrEncoder};
use anyd::traits::{Decode, Encode};
let encoder = QrEncoder::new();
let symbol = encoder.build_text("HELLO WORLD", EcLevel::Q).unwrap();
let encoding = encoder.encode(&symbol).unwrap();
let decoded = QrDecoder::new().decode(&encoding).unwrap();
assert_eq!(decoded.text().as_deref(), Some("HELLO WORLD"));
// Re-encoding the decoded symbol yields the identical matrix.
assert_eq!(encoder.encode(&decoded).unwrap(), encoding);For a camera feed you rarely want to fully decode every frame. The detect module
provides a fast, symbology-agnostic locator that returns the position of every
code (a quad + coarse family guess) in a single downscaled pass, without decoding —
the cheap stage of the two-stage Detect → Analyze pipeline.
It box-averages the frame down, thresholds it against its local neighbourhood (so a
lighting falloff, a shadow or a code on a dark product still binarizes), and sums each
tile's gradients into a structure tensor. A tile whose edges all share one direction is
a patch of bars — at any rotation — and such tiles cluster only with neighbours on
the same axis, so a barcode separates from the print around it and comes back as a box
aligned with the code plus its reading axis (Location::rotation). Incoherent
edge-dense tiles are matrix/texture; concentric-finder hits (cross-checked on both axes
and a diagonal) vouch for QR/Aztec. It is recall-biased but structurally picky: linear
regions need a barcode's worth of unbroken bars filling their box, finderless matrix
guesses need two well-separated tones at code-like ink coverage, scene-sized blobs and
duplicates are dropped, and a close-up code that defeats the texture pass is still
reported from its finders alone.
use anyd::detect::{locate, LocateOptions};
use anyd::pipeline::{scan_all, scan_linear_at};
for c in locate(&frame, &LocateOptions::default()) {
// c.location.outline — where; c.symbology — family guess; for a linear region
// c.location.rotation — the axis to scan along. Crop the outline's bounds (plus a
// margin) and decode just that:
// linear → scan_linear_at(&crop, axis) (1D readers, then PDF417 family)
// matrix → scan_all(&crop)
}detect::FrameDetector wraps this as a Detect that also reuses Hints: a candidate
is matched to a previously decoded symbol when it sits where that symbol was and looks
like it (a noise- and shift-tolerant ink fingerprint), so known codes skip re-analysis
without a swapped-in code inheriting the old value.
Benchmark (cargo bench --bench detect, dependency-free, std::time::Instant),
locating all codes of all families per frame vs. a full QR decode:
| resolution | locate median | locate FPS | full QR decode | detect speedup |
|---|---|---|---|---|
| 640×480 | 0.43 ms | ~2300 | 4.5 ms | ~10× |
| 1280×720 | 1.24 ms | ~800 | 6.6 ms | ~5× |
| 1920×1080 | 2.75 ms | ~360 | 10.1 ms | ~4× |
Those frames are pristine renders on white, which any locator finds. The number that
matters is end-to-end on camera-like scenes — codes planted off-centre in a 720p frame,
rotated 0–90°, on a page, a dark surface or amid print, under a 2:1 lighting falloff,
blurred and noisy — replayed through the same locate → crop → decode loop a front-end
runs (cargo run --release --example liveeval):
| read rate | wrong values | decode time / frame | |
|---|---|---|---|
| 1D (EAN-13, Code 128, Code 39, ITF) | 100% (240/240) | 0 | ~50 ms crop batch |
| 2D (QR, Data Matrix, Aztec, PDF417) | 95% (228/240) | 0 | ~80 ms whole-frame pass |
QR and Data Matrix read 60/60, Aztec 58/60; PDF417 (50/60) is the weak one — its sampler
is affine-only and wants ≥3 px modules. tests/live_pipeline.rs pins this behaviour in CI, including the things that
must not read: text, half an EAN-13 (structurally a UPC-E), ITF fragments.
The demo page shows the intended live wiring: the main thread runs locate on a
half-resolution grab ~30×/s; a crop worker decodes located regions off-thread, linear
crops first and along their reported axis; a second worker reads self-localizing 2D
codes off the frame, alternating the half-resolution frame with the central half at
full resolution; and decoded locks are position-tracked across frames so the overlay
follows the code between reads.
An optional binary is bundled behind the cli feature, so the library itself
stays dependency-free. It reads/writes PNG via oxideav-png (with default features
off — no codec-registry dependency) and can also emit Unicode (for the terminal) or
SVG (raw XML).
$ cargo build --release --features cli # builds target/release/anyd
# Encode → PNG / SVG / terminal
$ anyd encode qr "https://example.com" --format png --out qr.png --scale 8
$ anyd encode ean13 5901234123457 --format svg --out barcode.svg
$ anyd encode qr "HELLO" --format unicode # half-block art in the terminal
# Decode a PNG (tries QR, Micro QR, rMQR, Data Matrix, Aztec, MaxiCode, PDF417,
# MicroPDF417, App Clip Code, and the rotation-complete 1D front-end)
$ anyd decode qr.png
QR Code: https://example.com
$ anyd list # encodable symbology namesOptions: --format png|unicode|svg, --out FILE, --scale N (px/module),
--ec L|M|Q|H (QR/Micro QR) or --ec 0-8 (PDF417), --invert (terminal colours).
Symbol ─── the lossless currency: segments + symbology-specific meta
│
├─ Encode ──▶ Encoding (BitMatrix for 2D, LinearPattern for 1D)
└─ Decode ◀── Encoding
Image pipeline (pixels → symbol):
GrayFrame ─▶ [ imgproc: binarize · homography · grid-sample ] ─▶ BitMatrix ─▶ Decode (2D)
GrayFrame ─▶ [ scan1d: edge-detect · run-length · quantize ] ─▶ LinearPattern ─▶ Decode (1D)
Live video: GrayFrame ──▶ Detect ──▶ Candidate ──▶ Analyze ──▶ Symbol
▲ │
└────── Hints ◀────────────┘ (skip known codes)
Supporting modules: imgproc (Otsu/adaptive binarization, connected components,
4-point homography, thin-plate-spline warps, dominant-orientation estimation,
sub-pixel grid sampling — the 2D sampler toolkit), scan1d (generic 1D luminance
front-end), render (Encoding → grayscale) and transform
(rotation/perspective/blur/noise) for the test harness.
Correctness is anchored to independent reference vectors, not self-consistency: the ISO/IEC 18004 QR example, the ISO/IEC 16022 Data Matrix example, ISO/IEC 15438 + ZXing vectors for PDF417, BWIPP-rendered patterns for DataBar, and documented check-digit/pattern references for the 1D codes — plus exhaustive encode→decode→ re-encode identity tests, and full image-pipeline tests (encode → render → transform → sample → decode) for QR and the 1D front-end.
MIT © Karpelès Lab Inc.