jbig2-decoder 0.3.3

Memory-safe JBIG2 decoder under development
Documentation

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.

[dependencies]
jbig2-decoder = "0.3.3"
use std::fs::File;
use jbig2_decoder::{Decoder, Limits};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let decoder = Decoder::new(Limits::default());
    let mut input = File::open("document.jb2")?;
    let document = decoder.decode_reader(&mut input)?;

    for page in document.pages() {
        let bitmap = page.bitmap();
        println!("page {}: {} x {}", page.number(), bitmap.width(), bitmap.height());
    }
    Ok(())
}

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:

  1. 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 bounded BestEffort embedded recoveries (#278–#280) with zero runtime dependencies and #![forbid(unsafe_code)].
  2. Set explicit Limits for maximum stream bytes, image dimensions, total pixels, retained bytes, and decode work before accepting untrusted input.
  3. Reuse scratch storage and parsed globals: call Decoder::context across pages/documents and parse_globals once per shared PDF JBIG2Globals stream.
  4. Choose strict vs bounded recovery: default APIs are strict; for real-world nonconforming embedded PDF streams, opt into decode_embedded_with_policy with EmbeddedPolicy::BestEffort (complete output + recovery diagnostics, never partial bitmaps).
  5. Respect packed pixel layout: 1 / true is black, 0 / false is white, MSB-first per byte, row stride in bytes; read only width bits 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,732 obligations, 0 errors, 799 verified production functions, and 20 explicitly reviewed I/O/callback/formatting limitations on release/0.3; subsequent proof-only work on main completed 100% T.88/T.6 clause-level enumeration and external validation approval in #135).
  • Compiling strong/weaker contract tests (65 semantic groups / 510 contrasts) 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

cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features
cargo doc --no-deps
cargo package --locked

For explicit MSRV checks:

cargo +1.88.0 test --locked --all-targets
cargo +1.88.0 test --locked --doc
cargo +1.88.0 check --locked --release --all-targets

Compiler and development-tool pins are in config/toolchain.json. The optional distribution check uses Python 3.11+:

python3 -B tools/check_distribution.py --toolchain 1.88.0 --publish-dry-run \
  --output target/distribution/msrv.json

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:

cargo +1.98.1 verus build --manifest-path verification/Cargo.toml --locked -- \
  --num-threads 1 --rlimit 30 --triggers-mode silent

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.