Docs / Concepts
concept / research
Concept: optimization and native engines
Status: concept / research, not a commitment. Written on 2026-12-05 together with studio-gap-analysis.md. It decides where heavy work should run (main thread, workers, WebAssembly, WebGPU, or native Rust in the desktop app), lists the hotspots found in the code, proposes a measurement harness with budgets, and orders the work into waves of about four parallel pull requests.
It builds on, and does not repeat:
- performance.md: design rules, current measurements, the worker pool, size budgets.
- roadmap-next-major.md item R5 (Pixel live filters off the main thread, lazy effects registry, i18n split, an optional Wasm path for blur, unsharp and bilateral). This document turns R5.5 into a general engine strategy and extends it to the other studios.
- world-studio.md sections 4 and 17 (renderer backends, performance targets and memory limits for 3D). World keeps its own plan; this page only adds the shared parts.
Contents#
- Principles
- Where each kind of work runs
- Hotspots found in the code
- Engine architecture: one Rust core, two targets
- WebGPU compute
- Desktop-only native paths
- Memory and start-up
- Measurement harness and budgets
- Candidate libraries and licenses
- Risks
- Wave plan
- Open questions
- Sources
Principles#
- Measure, then move. performance.md already says "add a job to
jobs.jsonly with a measurement". The same rule applies to every language boundary: a kernel moves to Wasm, WebGPU or Rust only with a benchmark that shows at least 3× on the reference machines and a size cost recorded inscripts/size-budget.json. - The JavaScript implementation stays the reference. Every accelerated kernel has a golden test against the pure JS version (results equal, or within ±1 per 8-bit channel where floating-point order differs). Tests keep passing on machines without Rust, WebGPU or Wasm, and the PWA works everywhere.
- The PWA and the desktop app share one engine. Kernels are written once in Rust and compiled to WebAssembly so the browser, the PWA and the desktop WebView all get the speed. Native-only Rust is reserved for work that needs the file system, system codecs or more memory than a WebView allows.
- Never cross IPC per frame. Data that lives in the WebView and is touched every frame (viewport pixels, live filters, compositing) stays in the WebView: worker, Wasm or GPU. Tauri IPC is for file-bound and long-running jobs.
- Bounded and cancellable. Every off-thread job takes an
AbortSignal, reports progress and has a memory ceiling, as the worker pool already does. - Small by default. Wasm modules and GPU shaders are lazy chunks, outside the start-up budget, cached by the service worker on first use (as pdf.js is today).
Where each kind of work runs#
| Kind of work | First choice | Second | Last resort | Never |
|---|---|---|---|---|
| Per-pixel adjustments on the viewport (levels, curves, HSL, color grade) | WebGPU compute or fragment shader | Wasm SIMD in a worker | JS in a worker | Rust over IPC |
| Neighborhood filters (blur, unsharp, median, bilateral, guided filter) | WebGPU compute (separable passes) | Wasm SIMD in workers, tiled | JS in workers | Rust over IPC |
| Whole-image operations (resize, rotate, warp, inpaint, trace) | Wasm SIMD in workers, one tile per worker | JS in workers | — | main thread |
File parsing (PSD, TIFF, IDML, XLSX, PPTX, DOCX, Sketch, .fig) | JS or Wasm in a worker, streaming | — | main thread for files under 1 MB | — |
| Text shaping and line breaking | Wasm shaper (lazy) + JS line breaker, cached per run | JS-only shaping for Latin | — | — |
| Spreadsheet recalculation | JS incremental on the main thread under a budget, worker above | Wasm engine only if JS misses the budget | — | — |
| Video decode and encode | WebCodecs in a worker | Native Rust encoder on the desktop (Linux, pro codecs) | Seek-per-frame (today's fallback) | — |
| RAW decode | Rust → Wasm (pack) | Native Rust on the desktop for very large files | — | — |
| Mesh operations (World) | JS kernel in workers (World plan) | Rust → Wasm for proven hotspots; manifold Wasm for booleans | — | main thread |
| Hashing, compression, collecting media, thumbnails of folders | Native Rust on the desktop | Wasm or CompressionStream in a worker | — | — |
Hotspots found in the code#
Sizes from wc -l; times from performance.md where measured. "Unmeasured" rows are the first
job of wave E0.
| Area | Code | What is slow today | Evidence | Target placement |
|---|---|---|---|---|
| Pixel live filters and adjustments | engine/pixel/filters.js (315 lines), adjustments.js (1 177), fx-blur.js (494), blur.js (383), develop.js (670) | Computed in JS on the viewport pixels on the main thread; 12 MP + HSL + live Gaussian blur = 133 ms per frame (45 ms as a half-resolution draft); Gaussian blur on 2 MP ≈ 110 ms; Develop ≈ 180 ms | performance.md "Known limits" and "Pixel engine" | Worker (R5.2) → Wasm SIMD (E2.1) → WebGPU (E3.1) |
| Pixel compositing | engine/backends/canvas.js, engine/pixel/image.js | Layers are canvases; getImageData / putImageData gaps of ~115 ms on big resizes; 12 MP document holds 88 MB heap | performance.md worker pool table | Tiled typed-array store (R13.2, E5.1); GPU display compositing (E3.2) |
| Content-aware fill / object eraser | engine/pixel/inpaint.js (372) | Falls back to a blurry fill above ~60 000 px because patch synthesis is too slow in JS | known-limits.md Pixel | Wasm PatchMatch on a pyramid (E2.3, closes R20.1) |
| Resampling and warps | engine/pixel/transform.js, transform3d.js | Lanczos 4000×3000 → 2000×1500 ≈ 480 ms per layer (already in a worker) | performance.md | Wasm SIMD resize (E2.2) |
| Selection tracing and masks | engine/pixel/selection.js (1 189) | Contour tracing on a 4000² disc ≈ 100 ms on the main thread | performance.md | Worker job first (E1.2), Wasm if still over budget |
| Text layout | engine/layout/text-layout.js (2 057), line-break.js, sfnt.js (937, kerning from kern/GPOS only) | Unmeasured for long documents; no shaping engine yet; reflow of a long story is synchronous | R9, R15 need it | Shaper in Wasm (E2.4), reflow per story with a dirty range, measured on a 300-page fixture (E0.4) |
| Spreadsheet recalculation | office/sheet/formula.js (983), functions.js (873), model.js (829) | Already incremental with a dependency index and post-order evaluation; unmeasured on 100k-formula sheets; full recalc on open runs on the main thread | office-sheet.md "Formulas" | Budgeted slices on the main thread, worker above a threshold (E1.3) |
| Office and image file parsing | office/sheet/xlsx.js (864), office/slides/pptx.js, engine/office/docx.js, engine/formats/psd.js (1 262), idml.js, tiff.js; unzip in engine/office/zip.js with fflate | Unzip on open stays on the main thread (~35 ms for an 11 MB document.json); PSD and Office parsing are synchronous | performance.md worker pool | Worker parsing with transferable results (E1.2); DecompressionStream("deflate-raw") where available |
| Scene export | scene/export.js, decode.js, demux.js, mux.js, render.js, gl.js | WebCodecs path ~12× real time at 720p in Chromium; seek-per-frame fallback ~real time; MP4 export often unavailable on WebKitGTK; no files over 4 GB | scene-studio.md Formats and Limits | Encoder and muxer in a worker; native encoder on the desktop (E4.1) |
| Vector booleans | engine/vector/boolean.js (275) on vendored polygon-clipping | Fine for destructive operations; unmeasured against R8's live target (60 fps for 200-node shapes) | R8.2 acceptance | Benchmark; Rust boolean crate in Wasm if JS misses the target (E2.1 follow-up) |
| Proto rendering | engine/proto, app/src/proto | Has its own perf harness (tests/proto/perf, scripts/proto-perf.mjs) | Proto concept §4.3 | Keep; fold into the shared harness (E0.1) |
| World mesh kernel | engine/world/mesh (planned, JS) | Targets in world-studio.md 17.1 (100k-vertex edits < 50 ms, subdivision level 2 of 10k quads < 100 ms) | World plan | Measure in World's tasks; Rust → Wasm only for misses (E5.3) |
| Start-up | scripts/size-budget.json (start-up 354 KiB budget, 343.6 KiB measured) | Close to the cap; the pixel effects registry (~41 KiB) and all locales load at start | known-limits.md, refactoring-audit.md | R5.3, R5.4 (E1.4) |
Engine architecture: one Rust core, two targets#
engines/ new Cargo workspace (outside src-tauri, so the app builds without it)
crates/
of-kernels/ pixel kernels: blur, unsharp, bilateral, median, color conversions, LUTs
of-resample/ resize, rotate, warp (Lanczos, bicubic), homography
of-inpaint/ PatchMatch on a pyramid, membrane blend
of-shape/ text shaping wrapper (decision in E2.4)
of-raw/ DNG decoder and demosaic (E4.2)
of-codec/ native-only: encode and mux (E4.1)
wasm/ thin wasm-bindgen (or plain extern "C") wrappers, one module per crate
app/vendor/engines/ built .wasm files, committed with SHA-256 sums, listed in THIRD_PARTY_NOTICES.md
app/src/engine/native/ JS loader: capability probe, instantiate per worker, fallbacks, golden-test hooks
src-tauri/ links of-raw and of-codec natively for the desktop-only paths
- Build.
npm run engines:buildrunscargo build --target wasm32-unknown-unknown --releasewith-C target-feature=+simd128, thenwasm-opt -Oz. CI rebuilds on every change underengines/and fails when the committed artifact's hash differs, so contributors without Rust never need to build it and reviewers see a reproducible binary. - Threads. WebAssembly threads need
SharedArrayBuffer, which needs a cross-origin-isolated page (COOP + COEP). OpenFini is not isolated, and turning it on would break cross-origin images, the Code studio preview, Figma plugin frames and embeds. So: single-threaded Wasm instances, one per pool worker, with parallelism through tiles (the pattern the worker pool already uses). The desktop app could later isolate its own origin through Tauri's custom protocol headers; that is an open question, not a dependency. - Memory. Each instance gets a growable linear memory capped per job (for example 512 MiB); tiles are copied in and
out with transferable
ArrayBuffers; no long-lived pixel data lives inside Wasm memory. - API shape.
engine/native/kernels.jsexposes the same function signatures as the JS modules (gaussianBlurImage(src, sigma)), so callers do not change; a capability probe picks WebGPU, Wasm or JS once per session and the Doctor report records the choice. - Testing. Golden tests run every kernel through JS and Wasm in Node (Node runs Wasm SIMD) with random and fixture images; property tests check alpha handling, edges and odd sizes.
WebGPU compute#
WebGPU is available in Chromium and WebView2 (Windows desktop app), Safari 26 and WKWebView on macOS 26 and iOS 26, and Firefox on Windows since 141. It is not available in WebKitGTK, so the Linux desktop app and older macOS always use the Wasm path. World already plans a WebGPU backend with device-loss handling (world-studio.md 4.2); the 2D studios should share its device probe and GPU memory meter rather than create a second one.
- Scope. Per-pixel adjustments, separable convolutions and the live filter stack of the viewport (about 1–4 MP), with the result drawn straight to a canvas. Export, history and saved pixels keep using the CPU path, which stays the reference (the "two compositors tested against each other" idea also used by PhotoCraft).
- Precision. Compute in
f16/f32textures; parity tests compare GPU and CPU output within a tolerance on SwiftShader in CI and on real GPUs by hand. - Scene. Scene's effects run on WebGL 2 today (
scene/gl.js, with a CPU fallback). Moving them to WebGPU is not a goal by itself; only LUTs and scopes (SC-5) are new GPU work.
Desktop-only native paths#
Tauri commands are a good fit for file-bound work; a per-frame pixel exchange is not. Tauri 2 can return binary
data without JSON (tauri::ipc::Response) and stream it through Channel, but every call is still a serialized
message through the WebView's fetch path, so the cost per call must be measured (E0.3) before any design depends on it.
OpenFini already streams with a Channel in src-tauri/src/ollama.rs.
| Path | Why native | Shape |
|---|---|---|
| Video encode on Linux and pro formats (E4.1) | WebKitGTK often lacks encoders; no ProRes; MP4 over 4 GB | Frames rendered in the WebView, converted to YUV 4:2:0 in Wasm (about 3 MB per 1080p frame instead of 8 MB RGBA), streamed to Rust; Rust muxes and hands off to an encoder. Default encoder: a user-installed ffmpeg found on the PATH (ADR 0029 desktop path), run as a separate process, never bundled (license and patent reasons). Optional bundled encoders only with royalty-free codecs (AV1 via rav1e, VP9) after a license review |
| RAW decode of large files (E4.2) | 50–100 MB files, memory-heavy demosaic | Same crate as the Wasm pack, native for speed and memory on the desktop |
| Large-file IO (E4.3) | PSB over 2 GB, hashing referenced media, collecting projects | Streaming readers in Rust returning tiles or metadata, not whole files |
| Proxy generation (SC-6) | Long camera files | Background job through the same encoder path |
Security: every new command validates sizes and paths through fileaccess.rs, parsers are fuzzed (cargo fuzz) before
they ship, and native parsers run in a short-lived worker thread with a memory cap.
Memory and start-up#
- Pixel layers as tiles. The tiled store of R13.2 (256×256 tiles of typed arrays, canvas only as a display cache) is the base for 16-bit, smart objects and lower peaks. Add cold-tile compression (LZ4 in Wasm) for tiles not touched for 30 s and an LRU over decompressed tiles; history already stores dirty rectangles.
- Memory meter. One shared meter for CPU tiles, GPU textures (World's meter) and Scene media; the status bar shows pressure; low-power mode lowers caps (performance.md "Low-power mode").
- Worker lifetime. Wasm instances are freed after 60 s idle (the World rule), so a session that used a filter once does not keep megabytes alive.
- Start-up. Lower the start-up budget from 354 KiB to ≤ 320 KiB: lazy pixel effects registry (R5.3, ~41 KiB),
locale split (R5.4), and a check that no Wasm module or GPU code enters the static import closure. Record the desktop
cold start (window shown, first interactive frame) with the
--smokerun of R4.1.
Measurement harness and budgets#
Harness (E0.1). One command, npm run bench, with three layers:
- Node micro-benchmarks for pure kernels (extends
tests/pixel/bench.mjs): median of 7 runs after warm-up, output as JSON. - Browser scenarios in headless Chromium (the pattern of
scripts/proto-perf.mjs): open a fixture, perform a scripted interaction, record User Timing marks,longtaskentries and frame times throughPerformanceObserver, JS heap where exposed. - Desktop scenarios later, through the
--smokeflag of R4.1.
Results go to perf/results/<machine>.json; a checked-in perf/baseline.json holds reference numbers per scenario.
CI runs layer 1 on every PR and fails on a regression above 25 % (shared runners are noisy); layer 2 runs nightly and
posts a trend table. Fixtures are generated (no third-party files): a 12 MP photo-like image, a 300-page story, a
100k-formula workbook, a 50-slide deck, a 2 000-element board, a 1 080p 60-second clip.
Budgets (reference: a 2023 laptop with integrated graphics; numbers in parentheses are today's where measured):
| Scenario | Budget |
|---|---|
| Longest main-thread task while dragging a slider of a live filter on a 12 MP document | ≤ 50 ms (today up to 133 ms) |
| Live filter stack (HSL + Gaussian blur) on a 1.2 MP viewport, full quality | ≤ 33 ms per frame (today 133 ms) |
| Gaussian blur, 2 MP, sigma 10 | ≤ 25 ms in Wasm (today ~110 ms JS) |
| Content-aware fill of a 4000×3000 corner region | ≤ 3 s with texture (today: blurry above 60 000 px) |
| Open a 200 MB layered PSD | first view ≤ 3 s, UI never blocked > 100 ms |
| Recalculate after one edit in a 100k-formula workbook (chain of 1 000 dependents) | ≤ 50 ms; full recalc on open ≤ 1 s, off the main thread |
| Reflow a 300-page story after typing on page 1 | ≤ 100 ms to the visible page, rest in idle slices |
| Scene export 1080p, H.264 | ≥ 3× real time where WebCodecs exists; ≥ 1× on Linux with the native path |
| Start-up JavaScript (gzip, static closure) | ≤ 320 KiB (today 343.6 of 354) |
| JS heap with a 12 MP document | ≤ 64 MB plus tiles in use (today 88 MB) |
| Any Wasm module | ≤ 150 KiB gzip each, lazy; total of all engine modules ≤ 600 KiB |
Candidate libraries and licenses#
Only permissive licenses go into the app (clean-room.md rule 6). Checked through the GitHub API on 2026-12-05; GitHub shows one detected license even for dual-licensed crates, so each must be re-checked at the pinned version.
| Need | Candidate | License | Note |
|---|---|---|---|
| Resize kernels (reference or reuse) | fast_image_resize | MIT OR Apache-2.0 | SIMD, wasm32 support |
| Text shaping | rustybuzz (Rust port of HarfBuzz) / harfbuzzjs (HarfBuzz in Wasm) | MIT / MIT (HarfBuzz itself "Old MIT") | E2.4 compares size and speed; R9.1 estimated 300–400 KiB for harfbuzzjs |
| Text layout (ideas) | parley | Apache-2.0 OR MIT | Used by PhotoCraft's text crate |
| Polygon booleans | i_overlay | MIT OR Apache-2.0 | For live booleans if polygon-clipping misses 60 fps |
| Polygon booleans (alternative) | Clipper2 | Boost Software License 1.0 | Permissive; C++ to Wasm |
| Mesh booleans (World) | manifold | Apache-2.0 | Already planned in World |
| Mesh optimization (World) | meshoptimizer | MIT | Already planned in World |
| Spreadsheet oracle | IronCalc | MIT OR Apache-2.0 | Test vectors and semantics, not embedded by default |
| AV1 encode (optional) | rav1e | BSD-2-Clause | Royalty-free codec |
| H.264 encode | openh264 | BSD-2-Clause, but patent coverage only for Cisco's own binaries | Do not bundle; prefer OS encoders or user ffmpeg |
| RAW decode | rawloader | LGPL-2.1 | Not for static linking into the MIT core |
| RAW / PSD (Rust) | craft-libs (craft-raw, craft-psd) | MIT OR Apache-2.0 | Young (since 2026-09-30); review per the ArtCraft verdict |
| Image processing (ideas) | photon | Apache-2.0 | Rust/Wasm image filters |
Risks#
| Risk | Effect | Mitigation |
|---|---|---|
| A second language and toolchain (Rust for Wasm) raises the contribution barrier | Fewer contributors to kernels | Committed, hash-checked artifacts; JS stays the reference so tests run without Rust; small crates with one purpose |
| JS and Wasm/GPU results drift | Export differs from preview, flaky tests | Golden and parity tests with explicit tolerances; export always uses the CPU reference path |
| Download size grows | Breaks the "light" promise | Per-module budget, lazy loading, wasm-opt -Oz, no module in the start-up closure |
| WebGPU driver bugs and device loss | Crashes or black viewports | Share World's backend with device-loss recovery; blocklist via the Doctor report; Wasm fallback always present |
| WebKitGTK lacks WebGPU and WebCodecs encoders | Linux stays slower | Wasm path and native encoder are designed for Linux first |
| IPC overhead larger than expected | Native paths slower than Wasm | E0.3 measures before E4 starts; per-frame IPC is ruled out by principle 4 |
| Codec patents and licenses | Legal exposure | Never bundle H.264/HEVC encoders; use OS encoders, WebCodecs or a user-installed ffmpeg |
| Native parsers are an attack surface | Crafted files crash or exploit the app | cargo fuzz corpora in CI, size limits, Wasm sandbox for untrusted files in the browser |
| Reusing young third-party crates (Craft libs) | Churn, hidden license issues | Pin, vendor, review, re-check NOTICE files; prefer own code from public specs |
| Benchmarks on shared CI runners are noisy | False alarms or missed regressions | 25 % threshold for PR checks, nightly trends, manual numbers on reference machines in PR descriptions |
Wave plan#
Each task is one pull request with its own benchmark numbers in the description. About four run in parallel; a wave starts when its dependencies are merged. Waves E0 to E2 can run alongside World 1.4.x because they touch different files.
| Wave | Tasks (parallel) | Gate |
|---|---|---|
| E0 Measure | E0.1 npm run bench harness (Node + headless Chromium layers, JSON results, baseline, CI regression check) · E0.2 long-task and frame-time instrumentation behind Settings ▸ Developer, recorded in the Doctor report · E0.3 Tauri IPC benchmark (JSON vs ipc::Response vs Channel, 1–64 MB, three OSes) and ADR 0036 "native engines" · E0.4 generated fixtures (300-page story, 100k-formula workbook, 50-slide deck, 2 000-element board, 12 MP image, 60 s clip) | Baseline recorded for every row of the budget table |
| E1 Off the main thread (no new language) | E1.1 live filters in the worker pool with tiles and cancellation (R5.2) · E1.2 file parsing in workers (unzip on open, PSD, TIFF, XLSX, PPTX, DOCX, IDML) with DecompressionStream where available · E1.3 spreadsheet recalc in time slices and a worker above a formula-count threshold · E1.4 start-up savings (R5.3 lazy effects registry, R5.4 locale split), budget lowered | Longest task while dragging a live filter ≤ 50 ms; start-up ≤ 330 KiB |
| E2 Rust → Wasm foundation | E2.1 engines/ workspace, build and hash check, engine/native loader with fallbacks, golden-test harness, first kernels (box and Gaussian blur, unsharp) · E2.2 resample, rotate and warp kernels; color conversions · E2.3 PatchMatch inpainting on a pyramid (closes R20.1) · E2.4 shaping decision and integration (rustybuzz vs harfbuzzjs; feeds R9) | Blur 2 MP ≤ 25 ms; 4000×3000 content-aware fill ≤ 3 s; shaping ADR accepted |
| E3 GPU | E3.1 WebGPU compute for adjustments and separable filters on the viewport · E3.2 GPU display compositing of Pixel layers (blend modes; CPU stays reference) · E3.3 GPU/CPU parity harness on SwiftShader in CI · E3.4 shared device probe and GPU memory meter with World | Live stack on a 1.2 MP viewport ≤ 33 ms on WebGPU machines; parity tests green |
| E4 Desktop native | E4.1 native video export path (user ffmpeg detection, YUV in Wasm, Channel streaming, 64-bit MP4) · E4.2 RAW decode crate (DNG first; review of craft-raw vs own code; Wasm pack + native) · E4.3 streaming large-file IO (PSB, media hashing, project collect) · E4.4 cargo fuzz for every native parser in CI | Linux 1080p export ≥ 1× real time; DNG opens; fuzzers run nightly |
| E5 Memory and scale | E5.1 tiled typed-array layer store (R13.2) on top of the Wasm kernels · E5.2 cold-tile LZ4 compression, LRU and the shared memory meter · E5.3 World kernel hotspots ported to Wasm where 17.1 targets were missed · E5.4 budgets enforced in CI and documented in performance.md | 12 MP document heap ≤ 64 MB plus tiles; 100 MP document opens |
Dependencies: E1 needs E0.1; E2.1 needs E0.1; E2.2–E2.4 need E2.1; E3 needs E1.1 (the async render pipeline) and E0.2; E4.1 needs E0.3; E5.1 needs E2.1 and is the start of R13 (2.0).
Open questions#
- Should the desktop app become cross-origin isolated (custom protocol headers) to enable Wasm threads there, at the cost of two code paths?
- Where are the
.wasmartifacts built for releases: in the app repository's CI (simplest) or in the engine-packs repository planned in R11.1? - Which reference machines are the owner's own, so the budget table can be checked by hand on each release?
- Is a bundled royalty-free encoder (rav1e AV1) worth its size, or is "use WebCodecs, else your ffmpeg" enough?
Sources#
Accessed 2026-12-05.
- Tauri 2: calling Rust from the frontend and calling the frontend from Rust (channels)
- Tauri
ipcmodule source (Response) and the discussion on IPC performance in v2 - web.dev: WebGPU is now supported in major browsers
- WebKit bug 257694: WebGPU in the GTK port and WebKitGTK 2.52 highlights (no WebGPU)
- MDN: WebGPU API
- MDN:
crossOriginIsolatedand web.dev: WebAssembly threads - MDN:
DecompressionStream - MDN: WebCodecs API
- wasm-bindgen-rayon (why threads need isolation)
- Libraries: fast_image_resize, rustybuzz, harfbuzzjs, parley, i_overlay, Clipper2, manifold, meshoptimizer, IronCalc, rav1e, OpenH264 and its binary license note, rawloader, photon, craft-libs
- PhotoCraft README, "Under the hood" (CPU reference compositor tested against a wgpu compositor; copy-on-write tiles)
- OpenFini: performance.md, known-limits.md,
scene-studio.md, office-sheet.md,
refactoring-audit.md,
scripts/size-budget.json
Edit on GitHub → docs/concepts/optimization-native-engines.md