A complete camera ISP pipeline in Rust with Vulkan GPU acceleration.
Converts raw Bayer sensor data into display-ready images in real-time:
Raw Sensor → Unpack → BLC → WB → Demosaic → CCM → Tone → Denoise → Display
The pipeline is data-driven: every stage is an IspBlock that can be composed,
converted to ONNX, fused into GPU "Extra" ops, and executed on CPU (pure Rust)
or on the GPU (MNN Vulkan). Per-frame parameters (gain, saturation, sharpen,
gamma, CCM weights, tone curve, warp grid, …) are feedable at runtime.
Note on ONNX usage: The ONNX graph is an optimization/dispatch pattern, not a guaranteed-correct algorithm specification. softISP emits ONNX primarily so that MNN's fusion rules rewrite the standard ops into custom ISP opset shaders (e.g.
isp.unpack_packed,isp.argb_convert,isp.gamma). The ONNX op sequence is there to trigger MNN's custom-opset code path — it does not assert that the numerical behavior of every block has been independently verified against the pure-Rust reference. Treat ONNX/MNN output as a GPU fast path; the authoritative pipeline semantics live inCpuEngine.If you implement a new algorithm as an
IspBlock, you must make sure the ONNX op sequence you emit is actually recognized bylibMNNConvertDepsand gets fused into the intended customisp.*opset. If the pattern is not recognized, the converter silently falls back to the standard ONNX→MNN opset path. Worse, a partially matching (but semantically different) pattern can be mis-classified as an existingisp.*opset and executed via the wrong custom shader — producing incorrect output with no error. Always validate a new block's GPU/MNN result numerically against theCpuEnginereference.
// Create a GPU engine (falls back to CPU automatically)
let mut engine = select_engine_by_name("mnn_vulkan")?;
// Process a frame
let params = ProcessParams::new(3840, 2160, &raw_bayer);
let frame = engine.process(¶ms)?;Build & test (from the workspace root):
cargo fmt --all -- --check
cargo test -p cam-isp --features rectifier # lib tests
cargo run --example camera_isp -p cam-isp --features mnn -- --width 640 --height 480- 52 ISP blocks across input, black-level, white-balance, demosaic, color, tone, denoise, warp, and display categories (see Pipeline Blocks).
- Vulkan GPU acceleration — the fused chain is 12 blocks at 4K: 8 image stages
plus 4 statistics taps, of which 4 stages are single
isp.*dispatches. Measured end to end: 3.1 FPS at 3840×2160 and 5.7 FPS at 1920×1080 forFUSED, 7.2 / 9.6 FPS forWHOLE, against 1.9 / 4.0 for the primitive chain. See Performance. - Software fallback —
CpuEngineimplements the full 11-stage ISP in pure Rust (with AVX2/SSE2/NEON/NEON-FP16/NEON-DOTPROD SIMD backends). - Deshake — software video stabilization (block-matching motion estimation +
trajectory smoothing) with an optional fully-GPU pipeline; integrates with
WarpGridBlockfor GDC + EIS + lens-shading + rotation. - Neural controller — ONNX-based 3A (AWB/AE/AF/CCM/tone/scene) and a
NeuralControllerthat emits ISP params. It loads an ONNX model (via theisp-rectifierneural ISP controller) to compute metadata coefficients — exposure, gain, colour gains, CCM matrix, tone curve — from scene stats and applies them per-frame through the ISP pipeline. - Multiple profiles — LITE / MED / HEAVY / PRO / UNIFIED, plus FUSED and
WHOLE (whole-pipeline
isp.pipeline). - HAL integration — bridges for Android Camera HAL3, V4L2, and AOSP binder HAL.
- libcamera IPA —
libcamera-ipacrate implements libcamera'sIPAInterface/IPASoftIspInterfaceas a C FFI plugin, built on top of the stablecam-ipaRust API.cam-ipa(Image Processing Algorithm API) is now stable:IpaContext,IpaController,BufferManager,EngineBackend,ControlList, and the fullIpaConfigsurface are version-stable and reusable across frontends (libcamera plugin, Android JNI, ANativeWindow consumer, CLI). - Zero-copy memory — CMA / ION / memfd buffer manager for camera → ISP → MNN.
- CLI (
ipa_sk/cam-ipa-sk) — Swiss-army-knife test binary:generate(synthetic frames),capture(V4L2),process,bench(FPS/latency),stats(CMOS characterization),zerocopy(memfd/dmabuf),probe(capabilities),profile-json,cmos-dump(libcamera-compatible CMOS JSON). Use it to exercise the ISP pipeline end to end without building the APK. - 801 lib tests pass with
--features rectifier, 0 failures.
The cam-isp crate ships 52 block implementations (src/blocks/). They are
grouped by function:
RawInputBlock— ingest INT16/INT32/FP32 sensor tensorNormalizeBlock— black-level normalize to [0,1]CfaBlock/UnpackCfaBlock— CFA unpack (native + packed variants)UnpackBlock/UnpackBayerFp16Block— packed-Bayer → planar (incl. FP16)BayerProcBlock— combined Bayer preprocessingHdrDebayerBlock/HdrMergeBlock/HdrToneBlock— multi-exposure HDR
BlcBlock/Blc50Block— black-level correction (10-bit / 12-bit)BayerWbBlock— per-channel Bayer white balance
DemosaicBlock/BayerDemosaicBlock— bilinear / MHCC demosaicDemosaicCcmBlock— fused demosaic + CCMDemosaicInterpBlock— interpolation variants
CcmBlock— color correction matrixToneBlock— S-curve tone mapping (shadow lift / highlight roll)GammaBlock— gamma / sRGBColorSpaceBlock— colorspace conversionSaturationBlock— chroma controlFcsBlock— false-color suppressionAutoContrastBlock— adaptive contrastLdciBlock— local dynamic contrastEeBlock— edge enhancementGrayscaleBlock— luminance extractVignettingBlock— lens vignette correctionWatermarkBlock— overlay
WarpBlock/GpuWarpBlock/RuntimeWarpBlock— GDC + EIS + lens-shading + rotation (grid computed on GPU, fed via runtime tensorsgdc_k1/k2/k3,zoom,vcm,eis_dx/eis_dy)ChromaticAberrationBlock— lateral CA correctionAspectCropBlock/DynResizeBlock/ResizeBlock/AdaptiveDownscaleBlock— geometry
BilateralBlock— edge-preserving denoiseWaveletDenoiseBlock— wavelet threshold denoiseTemporalDenoiseBlock— multi-frame temporal denoiseLaplacianPyramidBlock/PyramidBlock— multi-scaleNoiseEstimateBlock— noise profilingSharpenBlock— unsharp maskSuperResBlock— super-resolutionStereoDepthBlock— stereo depth-from-disparity
DisplayBlock— sRGB gamma + format packing (RGBA / ARGB / AGBR)IdentityBlock/PassthroughBlock— no-ops for graph shapingStatsBlock— histogram / statistics extractionStageBlock/PluginBlock— composable sub-pipelines
Blocks can emit a purpose-built MNN op instead of a chain of ONNX primitives. The fused op is one Vulkan dispatch with its coefficients fed as per-frame tensors, so a stage that was five elementwise ops becomes one pass over the frame.
FuseStages gates them one at a time, and each one in FuseStages::ALL is backed by
a probe that compares it against its primitive form:
| Stage | Replaces | Verified difference |
|---|---|---|
isp.unpack_blc_normal_cfa |
cast, div, sub, clip, CFA conv | mean|Δ| 0.00010 |
isp.demosaic_ccm + folded WB |
demosaic, WB mul, CCM conv | pixel-identical |
isp.ee |
3×3 unsharp conv | peak|Δ| 0.0136 |
isp.ldci |
local-contrast chain | mean|Δ| ≤ 0.001 |
isp.downscale |
Resize |
mean|Δ| 0.00037 |
isp.display |
gamma pow + clip | mean|Δ| ≤ 0.001 |
isp.cfa_downscale |
statistics tap Resize |
statistics only |
isp.pipeline |
the whole RAW→display chain | mean 0.6019 vs MED's 0.6243 (box-filter demosaic) |
PipelineProfile::FUSED enables the per-stage set — 8 blocks instead of MED's 15:
isp.unpack_blc_normal_cfa → isp.demosaic_ccm → tone → isp.ee
→ saturation → isp.display (+ two stats taps)
PipelineProfile::WHOLE goes further and emits a single isp.pipeline dispatch for
the entire chain (2 blocks, ~80–115 ms at 1296×970 against MED's ~190–260 ms). It
trades away the 3A readback, edge-directed demosaic and the EIS warp, and it is not
the app default for that reason.
Measured at 1296×970, same stage set, on-device:
| Profile | Blocks | ms |
|---|---|---|
| MED (primitives) | 15 | 166–242 |
| FUSED | 8 | 150 |
| WHOLE | 2 | 80–115 |
The statistics are also a lever: stats_downscale_max reduces the CFA quad before
the 3A blocks read it (isp.cfa_downscale), and
MnnEngine::set_stats_interval(n) measures them every n frames instead of every
frame. A skipped frame reports IspAuxOutput::stats_measured == false, so a
consumer can tell "nothing new" from "the readback failed".
src/deshake/ provides software video stabilization:
DeshakeEngine(deshake/mod.rs) — block-matching motion estimation (estimate_motion) → EMA trajectory smoothing →motion_to_grid()→ warp grid.motion— diamond search, full search, parabolic refinement, weighted median, SAD.warp— bilinear interpolation, crop, border handling.gpu_pipeline—DeshakeGpuPipeline, a fully GPU-accelerated stabilization path that reusesWarpGridBlock(GridSample on Vulkan).
Flow:
Frame N-1 ─┐
├→ estimate_motion → (dx,dy) → EMA smooth → motion_to_grid()
Frame N ─┘ ↓
WarpGridBlock (GPU GridSample)
↓
Stabilized Frame
EIS is also exposed standalone via EisEngine (eis.rs), driven by gyroscope
samples, and composable into WarpGridBlock.
src/integration.rs connects the ISP engine to camera stacks:
ZeroCopyBufferManager— CMA / ION / memfd allocation for camera ↔ ISP ↔ MNN.CameraIspService— high-level service wrapping anIspEngine; auto-builds the CPU pipeline soprocess_raw_frame()works out of the box.AndroidHalIspBridge— bridges Android Camera HAL3 frames into the ISP.V4l2IspBridge— bridges V4L2 captures (viacam-hal-linux) into the ISP, withprocess_frame()/process_batch()andBridgeStats.libcamera-ipa— libcamera C FFI plugin (IPAInterface/IPASoftIspInterface) that bridges libcamera into the ISP through the stablecam-ipaRust API (IpaContext,IpaController,BufferManager,EngineBackend,ControlList).cam-ipahas a stable API and is reusable across frontends: the libcamera plugin, Android JNI, ANativeWindow consumer, and theipa_skCLI.
Real capture lives in cam-hal-linux (V4L2 adapter) and cam-hal-android
(Camera2 HAL3 + AHardwareBuffer); the bridges above run only the ISP stage.
The cli crate builds ipa_sk (binary wrapper) and libcam_ipa_sk.so (cdylib
exporting ipa_sk_main for dlopen). It is a Swiss-army-knife for exercising the
ISP pipeline end to end without building the APK:
generate— synthetic Bayer test frames, run through the full ISP pipelinecapture— real V4L2 frames viacam-hal-linux(featurev4l2)bench— FPS/latency over N framesstats— per-frame stats for CMOS sensor characterizationzerocopy— memfd/dmabuf zero-copy buffer path testprobe— profile capabilities and engine info (--jsonfor JSON)profile-json— dump or load a pipeline profile as JSONcmos-dump— read V4L2 sensor metadata and output libcamera-compatible CMOS JSON
Build and run:
cargo build -p cam-ipa-sk # synthetic only
cargo build -p cam-ipa-sk --features v4l2 # + V4L2 capture
./target/debug/ipa_sk generate --count 1 --profile fused --width 3840 --height 2160
./target/debug/ipa_sk bench --count 30 --profile fused
./target/debug/ipa_sk probe --jsonEnd-to-end, whole chain, raw Bayer in → planar RGB out, 8 frames warmup then
20–30 measured. p50 over the run, not an average of block times.
Measure with tracing off. Every ISP trace — the per-command markers, the
zero-copy log, the [VulkanFuse-PERF] dispatch report — is behind one switch that
is off by default:
MNN_ISP_TRACE=1 <command> # turn them all on, for one debugging runWith it off a timing run adds zero bytes to /sdcard/Download/isp_vlog_trace and
emits no per-dispatch lines; with it on, one three-profile run writes 26 KB. An op
that falls back off the GPU is still reported unconditionally, because that costs
two full-frame copies and is worth more than any tuning.
3840×2160 (PERF_FRAMES=40 cargo test -p cam-isp --test probe_4k_perf perf_4k_all --features mnn -- --ignored --nocapture)
Measured on this device (Termux/Android, Vulkan GPU, MNN backend). Output format changes the cost materially — PackedRgb is a single fused dispatch; BGRA needs an extra format-conversion pass. MED/HEAVY/UNIFIED PackedRgb produce blank output on this build (known graph/packing gap) and are shown only for BGRA/ARGB where they render.
| Profile | Blocks | p50 | p95 | FPS | Format |
|---|---|---|---|---|---|
| FUSED | 14 | 156.8 ms | 161.3 ms | 6.4 | PackedRgb |
| FUSED, statistics off | 14 | 157.1 ms | 177.9 ms | 6.4 | PackedRgb |
| FUSED | 14 | 274.7 ms | 297.3 ms | 3.6 | BGRA |
| FUSED, statistics off | 14 | 258.4 ms | 312.4 ms | 3.9 | BGRA |
| MED (primitives) | 19 | 468.1 ms | 509.3 ms | 2.1 | BGRA |
| MED (primitives) | 19 | 498.6 ms | 526.0 ms | 2.0 | ARGB |
WHOLE (isp.pipeline) |
2 | 181.2 ms | 201.4 ms | 5.5 | PackedRgb |
| UNIFIED | 14 | 164.8 ms | 183.1 ms | 6.1 | PackedRgb |
| UNIFIED | 14 | 216.5 ms | 295.1 ms | 4.6 | BGRA |
| DUAL fused (stats ON+OFF ping-pong) | 14 | 142.1 ms | 162.5 ms | 7.0 | PackedRgb |
| DUAL fused | 14 | 276.5 ms | 322.0 ms | 3.6 | BGRA |
Statistics readback costs ~2.5 ms per frame (~2% of p50) at 4K — the per-block statistics taps were already pooled into one shared AveragePool (stats_downscale_max = 540), so the 3A branches are ~6% of the frame instead of 38%.
1920×1080 (PERF_W=1920 PERF_H=1080 PERF_FRAMES=25 …)
| Profile | Blocks | p50 | p95 | FPS |
|---|---|---|---|---|
| MED (primitives) | 19 | 132.3 ms | 156.7 ms | 7.6 |
| FUSED | 13 | 74.5 ms | 83.5 ms | 13.4 |
| FUSED, statistics off | 13 | 70.3 ms | 79.2 ms | 14.2 |
WHOLE (isp.pipeline) |
2 | 19.7 ms | 22.1 ms | 50.8 |
| UNIFIED (FUSED + all stages) | 13 | 72.6 ms | 80.7 ms | 13.8 |
Fusion buys ~1.8× at FHD and ~3× at 4K (FUSED PackedRgb 156.8 ms vs MED BGRA 468.1 ms). Collapsing the whole chain into one dispatch (WHOLE) was worth 2.4× while the statistics still reduced the full frame; with them pooled, FUSED is within ~4× of WHOLE at FHD while keeping the 3A loop closed. UNIFIED mirrors FUSED with tiled rendering at 4K and matches it within noise, confirming the fusion is the driver. The DUAL engine (ping-pong two MnnEngine instances, stats on A / off B) reaches 7.0 FPS at 4K PackedRgb — the best single-engine number.
Absolute numbers move with device temperature — the same configuration measured 437.1 ms then 298.0 ms back to back (probe_4k_drift). Compare rows within a run.
The 3A statistics were the whole problem. Each block used to shrink the frame for itself, so four blocks meant four traversals of a 100 MB tensor:
| Removed | Saves | Share of the chain |
|---|---|---|
| all statistics | 225.3 ms | 67% |
tone_stats |
105.6 ms | 31% |
zone_stats |
82.4 ms | 24% |
channel_means |
40.6 ms | 12% |
| saturation | 33.7 ms | 10% |
ee |
−104.4 ms | noise |
They now share one AveragePool (stats_downscale_max = 540), and the 3A branches
cost ~6% of the frame instead of 38%. The numbers they hand the controller do
not move: a mean is exact under a box filter, so the calibration quad means are
[0.9962, 1.0000, 0.9987] pooled against [0.9963, 1.0000, 0.9987] at full
resolution.
The two run-time levers still apply on top: set_stats_interval(n) measures every
n frames, and set_stats_enabled(false) skips the readback entirely (a frame that
skipped reports stats_measured == false). Anything under ~10% in the table above is
inside run-to-run spread — no ee coming out negative is the honest reminder.
The earlier figures in this README (680 / 438 / 78 FPS at HD / FHD / 4K) were per-block micro-benchmarks taken before the MNN DCE and fused-opset work. They measured a chain that did not run the same ops this one does; the numbers above supersede them.
| Crate | Purpose |
|---|---|
cam-types |
Core types: Frame, FrameFormat, ToneParams, BlockDef |
cam-isp |
ISP engine: CpuEngine, MnnEngine, OnnxEngine, 52 blocks, controllers, deshake, HAL integration |
cam-hal |
Hardware abstraction: ICameraAdapter trait, buffer management |
cam-hal-linux |
V4L2 adapter via rscam |
cam-hal-android |
Android Camera2 HAL3 (camera3.h FFI, AHardwareBuffer) |
cam-core |
PipelineManager, HAL bridge |
cam-onnx |
ONNX Runtime bindings (ort v2.0.0-rc.12) |
cam-motion |
MotionCompensator (EIS/deshake glue) |
cam-binder |
Android AIDL-style binder HAL + ISP session integration |
anw |
Camera app cdylib libsoftisp.so (NativeActivity, ISP pipeline driver) |
- ✅ 52 ISP blocks, 801 lib tests (
--features rectifier), 0 failures - ✅ Full GPU ISP pipeline (MNN Vulkan), measured end to end on-device:
- 3840×2160: MED 1.9 FPS ·
FUSED3.1 ·WHOLE7.2 - 1920×1080: MED 4.0 FPS ·
FUSED5.7 ·WHOLE9.6 - the 3A statistics are 67% of the 4K cost, hence
set_stats_interval/set_stats_enabled
- 3840×2160: MED 1.9 FPS ·
- ✅
CpuEngine— 11-stage software ISP with SIMD backends - ✅ Deshake (CPU + GPU) and EIS stabilization
- ✅ Runtime-feedable params (29 per-frame inputs across 11 blocks)
- ✅ Fused
isp.*opset —FUSEDprofile: 12 blocks at 4K where MED needs 19 (323 vs 530 ms);WHOLEprofile: 2 blocks at 139 ms - ✅ 3A statistics on a reduced CFA quad (
isp.cfa_downscale) and a per-framestats_interval, withstats_measuredtelling a consumer a frame skipped them - ✅
PipelineBuilderfluent API + 5 presets + config roundtrip - ✅ HAL integration module (Android HAL3 / V4L2 / binder) + zero-copy buffers
- ✅ 3A controllers (AWB/AE/AF/CCM/Tone/Scene) + NeuralController
- ✅ ONNX model generator (pure-Rust protobuf encoder) + MNN same-process conversion
- ✅ ONNX
TypeProto/TensorShapeProtoencoding correct — no more MNN DCE - ✅
synth_bayermodule (5 generators) for stress-test inputs
A debug build of the camera app is checked in at
release/softisp-camera-debug.apk — ~13 MB,
arm64-v8a, package com.softisp.camera, signed with the standard debug keystore.
The user installs it directly — no adb install, pm install, or
install-apk.sh from Termux (AGENTS.md §1.7). Transfer the APK to the device
and let the user install it through the normal Android flow, then launch from
the app drawer ("SoftISP Camera").
It ships the whole fused stack: libMNN.so, the libMNN_Vulkan.so plugin with the
isp.* shaders embedded, and libMNNConvertDeps.so for the same-process ONNX→MNN
conversion. Nothing is fetched at run time.
Building it yourself:
./build-apk.sh
# -> target/debug/apk/softisp-camera.apk (workspace root)anw/ owns the NativeActivity code and produces libsoftisp.so;
android-app/ holds only the manifest and resources.
For ISP/MNN code changes, you do not need to repack or reinstall the APK. Build the shim-only test APK once, then push only the core library to the device:
# One-time: build the shim-only APK and push libs
./build-test-apk.sh # -> target/debug/apk/softisp-test.apk
# user installs target/debug/apk/softisp-test.apk
./push-test-libs.sh # copies core + MNN libs to /sdcard/download/
# Daily loop: rebuild core, stop app, relaunch, verify
./shim-debug.sh core # cargo apk2 -- build -p softisp-anw + push
./shim-debug.sh stop # control intent (no shell force-stop)
./shim-debug.sh launch # am start ShimActivity
./shim-debug.sh verify # MD5 fingerprint comparison
./shim-debug.sh logs # tail /sdcard/download/softisp-app.log
# or all at once: WAIT_SECS=12 ./shim-debug.sh cycleThe test APK contains only libsoftisp_shim.so (no MNN, no core) — the shim
dlopens a separately pushed libsoftisp.so from /sdcard/download/. See
docs/build/SHIM_DEBUG_WORKFLOW.md for
the full workflow, including §9 on debugging the MNN Vulkan backend
("probe session create fail").
- Architecture — system design
- Summary — detailed overview
- Pipeline Blocks — block reference
- Runtime Params — per-frame parameter API
- MNN/Vulkan Guide — GPU setup
cargo test -p cam-isp --features rectifier # 801 lib tests
cargo test -p cam-isp --features mnn # GPU/ONNX backends
cargo test --workspace --features mnn # full workspace- Code: GPL-3.0-or-later — see LICENSE
- Models: CC BY-NC 4.0 (non-commercial)