jbig2-decoder
A dependency-free, #![forbid(unsafe_code)], Verus-verified Rust decoder for
JBIG2 black-and-white images.
Production readiness: jbig2-decoder is ready for integration into
consumer products (including PDF engines and document pipelines processing
untrusted standalone or embedded JBIG2 streams) under application-appropriate
Limits. Whole-crate Verus verification (1,910 obligations,
0 errors, 843 verified production functions, 20 explicitly reviewed
limitations on release/0.3) and external validation approval on main
(#135) are complete.
Explicit scope boundaries: This is not an Annex F profile 1 conformance
certificate, and deeper end-to-end raster/stream equivalence theorems remain
longer-term assurance work. Existing bi-level APIs do not decode colour;
version 0.3 additionally offers a separate, limited
generic-region RGB8 profile. Encoding remains
outside the crate's scope. Standard library internals, compiler codegen,
allocator RSS/OOM behavior, and caller-provided Read/PageSink callbacks
remain explicit trust boundaries; see
verification limitations and the
threat model.
jbig2-decoder 0.3.3 is the current published
release on crates.io from
release/0.3.
Decode a document
The Cargo package is jbig2-decoder; the Rust import is jbig2_decoder.
The runtime MSRV is Rust 1.88.0 with zero runtime dependencies.
[]
= "0.3.3"
use File;
use ;
Consumers need only ordinary Rust and Cargo, not Verus or the repository's
proof files. Choose application-appropriate Limits before accepting input.
The 0.3 byte-slice API additionally offers explicit, bounded standalone compatibility, with recovery diagnostics and no partial-output fallback. Existing APIs remain strict.
For supported coloured generic regions, decode_rgb and
decode_rgb_with_policy return separate DecodedColourDocument / RgbBitmap
values. They preserve RGB channels rather than flattening colour to bi-level
pixels; their profile and recovery scope are deliberately narrower.
Use with the image crate
The experimental jbig2-image companion implements
image::ImageDecoder and opt-in ImageReader hooks for a single standalone
JBIG2 page, with L8 output and explicit codec limits. It is an unpublished,
separate crate, not a core feature or part of the decoder's Verus proof claim.
The core remains dependency-free. Embedded PDF streams, globals, recovery and
multi-page selection continue to use the core API.
Root Cargo commands keep their existing scope; test the companion with
cargo test --manifest-path adapters/image/Cargo.toml --locked.
Measured context/dictionary optimizations and the Verus-verified
optimizations shipped in 0.3.1 (#247–#254) and 0.3.2 (#270–#274), plus the
bounded BestEffort embedded recoveries in 0.3.3 (#278–#280), are documented
in performance improvements, the
0.3.3 release notes, the
0.3.2 release notes, and the
0.3.1 release notes. The
0.3.0 release notes document the 0.3 baseline
additions and intentional refusals.
Decoder scope
- Standalone sequential and random-access JBIG2 files.
- Embedded page streams with reusable validated global segments.
- Known-height, unknown-height, multi-page and striped pages.
- Arithmetic decisions, integers and IAID; standard/custom Huffman; MMR.
- Generic/refinement regions, symbol dictionaries, text, patterns and halftones.
- Clipping, combination operators, retention, and owned/reader/page-sink APIs.
The crate decodes JBIG2 segment streams; it does not parse PDF containers. The support matrix describes feature handling and resource limits. Unsupported syntax, malformed input, resource exhaustion, allocation failure and I/O failure have distinct typed errors.
Choose the right API
| Need | Entry point and behavior |
|---|---|
| Inspect structure and dimensions | inspect / inspect_reader validate the envelope and page lifecycle, not compressed region payloads. Successful inspection does not guarantee successful decoding. |
| Collect decoded pages | decode / decode_reader return an owned DecodedDocument. |
| Receive completed pages | decode_with_sink / decode_reader_with_sink transfer each Page to a PageSink; closures can serve as sinks. Earlier callback effects are not rolled back after a later error. |
| Decode embedded streams | decode_embedded, or parse_globals followed by decode_embedded_with_globals. Callers supply the extracted JBIG2 streams. |
| Reuse scratch storage | Decoder::context returns a DecoderContext; reuse does not retain previous document semantics. |
| Decode the 0.3 generic RGB8 profile | Byte-only decode_rgb / decode_rgb_with_policy; see the profile contract. Existing reader/context/sink APIs and the image companion remain bi-level. |
Production integration checklist
When integrating jbig2-decoder into a PDF engine or document service:
- Depend on
jbig2-decoder = "0.3.3"(or later 0.3.x) to include all Verus-verified PDFium performance optimizations (#247–#254, #270–#274) and boundedBestEffortembedded recoveries (#278–#280) with zero runtime dependencies and#![forbid(unsafe_code)]. - Set explicit
Limitsfor maximum stream bytes, image dimensions, total pixels, retained bytes, and decode work before accepting untrusted input. - Reuse scratch storage and parsed globals: call
Decoder::contextacross pages/documents andparse_globalsonce per shared PDFJBIG2Globalsstream. - Choose strict vs bounded recovery: default APIs are strict; for real-world
nonconforming embedded PDF streams, opt into
decode_embedded_with_policywithEmbeddedPolicy::BestEffort(complete output + recovery diagnostics, never partial bitmaps). - Respect packed pixel layout:
1/trueis black,0/falseis white, MSB-first per byte, row stride in bytes; read onlywidthbits per row and ignore trailing row-padding bits.
Reader methods buffer bounded compressed input through EOF before parsing or
delivering pages. A sink avoids collecting all decoded pages, but does not make
compressed input incremental or guarantee constant process memory. Reader
position and sink side effects are not restored on failure. I/O errors,
including Interrupted, remain typed errors rather than being silently retried.
For PDF integration, including PDFium, the end of the complete supplied embedded page stream may replace the final end-of-page segment. Initially unknown-height pages still require a completed final stripe; malformed headers, truncated payloads and incomplete bitmap data are not recovered. Standalone files still require end-of-page segments. A page-information segment must contain its complete 19-byte payload; PDF image dimensions are not guessed or substituted.
Existing entry points remain strict. For explicitly selected recovery of a small
set of nonconforming embedded inputs, use decode_embedded_with_policy or
inspect_embedded_with_policy with EmbeddedPolicy::BestEffort. Their
EmbeddedResult includes every applied recovery; errors never return a partial
bitmap. See the allowlist, budgets and compatibility dispositions.
Packed pixels use 1 / true for black and 0 / false for white.
The first pixel is the most significant bit of its byte; row stride is in
bytes. Read only the declared width, not padding bits. An 8-bit grayscale
adapter must expand the bits and map black to 0 and white to 255.
Decoded pages and sink callbacks use stream order, which need not be page-number
order. DocumentInfo::pages() is sorted by page number; match pages using
Page::number(), not slice position.
See the API documentation and crate-level guide for more examples.
How it is validated
Validation combines complementary checks:
- Native tests exercise public APIs, exact pixel/error results, coding primitives, malformed inputs and resource boundaries.
- Verus proves contracts on the same Rust source compiled by Cargo (
1,732obligations,0errors,799verified production functions, and20explicitly reviewed I/O/callback/formatting limitations onrelease/0.3; subsequent proof-only work onmaincompleted 100% T.88/T.6 clause-level enumeration and external validation approval in #135). - Compiling strong/weaker contract tests (
65semantic groups /510contrasts) and native mutations check sensitivity to deliberately broken results and guards. - LLVM coverage measures ordinary executing Rust, with aggregate and per-file non-regression checks.
- Bounded generated fuzz campaigns retain reproducible failures.
- Distribution CI tests the actual archive and a fresh exact-output consumer on Linux, Windows and macOS with MSRV/stable toolchains.
- External conformance and differential tests record exact inputs, bitmap outcomes and expected rejections separately.
These are not interchangeable guarantees. A verified storage invariant is not a complete decoded-output proof; successful tests are not exhaustive input coverage. Official-case rejections are not bitmap passes. See the validation guide, release evidence and threat model.
Build and test
For explicit MSRV checks:
Compiler and development-tool pins are in
config/toolchain.json.
The optional distribution check uses Python 3.11+:
It tests the archive outside the checkout, without proof assets or inherited credentials. The publication rehearsal never uploads a crate.
Implementation and proof boundary
src/ is the single executable implementation. specs/
contains project models and proofs/ contains supporting lemmas and
proof bodies attached to that source. Separate proof/model directories are
excluded from the Cargo package; inline ghost code and proof attributes remain
cfg-inactive in ordinary builds.
The crate forbids handwritten unsafe Rust. Compiler-generated code, standard library internals and the Rust/Verus/vstd toolchains remain trust boundaries. This is not a binary-wide no-unsafe or universal no-panic proof. The proof-only capacity interface is an additional explicit boundary; it supplies no allocator or memory-bound facts.
Run Verus through Cargo
Put the pinned Verus release and bundled cargo-verus on PATH, install its
proof Rust toolchain, then run:
This verifies and builds the production library. Python is not required for
this command. The proof manifest targets the same src/lib.rs as ordinary
Cargo; vstd and proof-interface dependencies are not runtime dependencies.
Interpret the result
A zero-error run establishes the submitted contracts under their preconditions and trusted interfaces. Obligation counts are not percentages of the JBIG2 standard, and selected-module success does not replace whole-crate verification and compilation. Some contracts establish bounds or state preservation rather than complete decoded output.
Start with the model reading guide. For detail, see verification limitations, statement traceability and the auditor index. Remaining coverage work is listed in the development roadmap.
License and security
Licensed under the MIT license. External standards, validation vectors and comparison tools are not distributed with the crate and have separate terms.
Report vulnerabilities through the channels in SECURITY.md.