Skip to content

Commit a607e20

Browse files
committed
feat(compositor): the Linux pass of shader effects
The wgpu compositor now draws agent-written effects, as the Windows one does: same targets (image, text layer, both), same lanes, same blocking rule (the export waits for the pipeline, the live view skips it until it lands). - The WGSL goes to wgpu as it is. A background thread builds the module and the pipeline against an explicit layout of the prelude's four bindings. - wgpu panics on a validation error: `analyze` now also refuses any binding the prelude does not declare, so nothing invalid reaches it. - `check_for_agent` translates the effect to SPIR-V on Linux. - live.rs turns the preview's non-blocking mode on for Linux too. Tested on lavapipe under WSL: the six GPU tests of the Windows pass, ported, and the full compositor suite. Tier calibration on lavapipe goes to rendering-performance.md and the spec (C.7, H.2).
1 parent 7907021 commit a607e20

7 files changed

Lines changed: 688 additions & 27 deletions

File tree

‎crates/compositor/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ naga = { version = "24", features = ["wgsl-in", "hlsl-out"] }
5353
[target.'cfg(target_os = "linux")'.dependencies]
5454
ash = "0.38"
5555
wgpu-hal = { version = "24", features = ["vulkan"] }
56+
# `shader_fx::check_for_agent` traduit l'effet en SPIR-V, comme wgpu le fera pour Vulkan.
57+
naga = { version = "24", features = ["spv-out"] }
5658

5759
# Windows : D3D11 + D3D11VA + Direct2D/DirectWrite + HLSL à l'exécution.
5860
[target.'cfg(windows)'.dependencies]

‎crates/compositor/src/compositor_linux.rs‎

Lines changed: 595 additions & 6 deletions
Large diffs are not rendered by default.

‎crates/compositor/src/live.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1493,7 +1493,7 @@ unsafe fn render_thread(
14931493
let mut comp = Compositor::new(&gpu)?;
14941494
// La preview ne bloque jamais sur la compilation d'un effet shader : elle le saute le temps
14951495
// qu'il compile (voir `shader_fx_landed` plus bas). L'export, lui, attend.
1496-
#[cfg(windows)]
1496+
#[cfg(any(windows, target_os = "linux"))]
14971497
comp.set_shader_fx_blocking(false);
14981498
// Vue live = le VRAI enregistrement, pas la fenêtre fixture (100s@6s, taillée pour l'ancien
14991499
// fixture POC). On charge toute la piste depuis t=0 ; 24h couvre large toute recording réelle.
@@ -1786,9 +1786,9 @@ unsafe fn render_thread(
17861786
}
17871787

17881788
// Un effet shader vient de finir de compiler : la frame en pause doit le montrer.
1789-
#[cfg(windows)]
1789+
#[cfg(any(windows, target_os = "linux"))]
17901790
let fx_landed = comp.shader_fx_landed();
1791-
#[cfg(not(windows))]
1791+
#[cfg(not(any(windows, target_os = "linux")))]
17921792
let fx_landed = false;
17931793

17941794
// avance : seek app-piloté (presentTime) prioritaire, sinon lecture libre (60 fps)

‎crates/compositor/src/shader_fx.rs‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,17 @@ pub fn analyze(user: &str, params: &[ShaderParamDecl]) -> Result<Parsed, String>
226226
)
227227
.validate(&module)
228228
.map_err(|e| e.emit_to_string(&src))?;
229+
// Les bindings sont ceux du prélude, et eux seuls : chaque backend lie ces quatre-là. Linux
230+
// valide le pipeline contre ce layout, et une erreur de validation wgpu y fait paniquer.
231+
for (handle, var) in module.global_variables.iter() {
232+
let name = var.name.as_deref().unwrap_or("?");
233+
if var.binding.is_some() && !["fx_frame", "fx_sampler", "ctx", "params"].contains(&name) {
234+
let line = module.global_variables.get_span(handle).location(&src).line_number;
235+
return Err(format!(
236+
"`{name}` at line {line}: an effect declares no binding of its own, it reads frame(), ctx and params"
237+
));
238+
}
239+
}
229240
let entry = module
230241
.entry_points
231242
.iter()
@@ -657,13 +668,23 @@ pub fn spawn_compile(effect: &SceneShaderEffect) -> std::sync::mpsc::Receiver<Re
657668
rx
658669
}
659670

671+
/// Le SPIR-V que wgpu tirera du même module pour Vulkan. Le compositeur Linux passe le WGSL à
672+
/// wgpu, qui refait cette traduction lui-même : celle-ci ne sert qu'à la vérifier d'avance.
673+
#[cfg(target_os = "linux")]
674+
fn to_spirv(parsed: &Parsed) -> Result<Vec<u32>, String> {
675+
naga::back::spv::write_vec(&parsed.module, &parsed.info, &naga::back::spv::Options::default(), None)
676+
.map_err(|e| e.to_string())
677+
}
678+
660679
/// Ce que l'outil de l'agent demande avant d'accepter un code : la validation, la compilation
661680
/// réelle pour le backend de la machine quand elle existe, et le palier.
662681
pub fn check_for_agent(code: &str, params: &[ShaderParamDecl]) -> Result<EffectReport, String> {
663-
let report = analyze(code, params)?.report;
682+
let parsed = analyze(code, params)?;
664683
#[cfg(windows)]
665684
compile_dxbc(code, params)?;
666-
Ok(report)
685+
#[cfg(target_os = "linux")]
686+
to_spirv(&parsed)?;
687+
Ok(parsed.report)
667688
}
668689

669690
/// `check_for_agent`, les paramètres reçus en JSON (`[{ "name", "type" }, …]`) depuis l'addon.
@@ -725,6 +746,21 @@ mod tests {
725746
assert!(analyze("fn other() {}", &[]).is_err());
726747
}
727748

749+
#[test]
750+
fn an_effect_declares_no_binding_of_its_own() {
751+
let code = "@group(0) @binding(4) var extra: texture_2d<f32>;\n\
752+
fn effect(uv: vec2<f32>) -> vec4<f32> { return textureLoad(extra, vec2<i32>(0), 0); }\n";
753+
let err = analyze(code, &[]).err().expect("refusé");
754+
assert!(err.contains("`extra` at line 1"), "{err}");
755+
}
756+
757+
#[cfg(target_os = "linux")]
758+
#[test]
759+
fn a_valid_effect_becomes_spirv() {
760+
let parsed = analyze(VIGNETTE, &[decl("strength", ShaderParamType::Number)]).expect("analyze");
761+
assert!(!to_spirv(&parsed).expect("spirv").is_empty());
762+
}
763+
728764
#[test]
729765
fn parameter_names_are_checked() {
730766
for bad in ["Strength", "2x", "unused", "a-b"] {

‎docs/shader-effects.md‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ libre, et les erreurs pointent ainsi les lignes que l'agent a écrites.
230230
la souris arrive pile au moment du clic. Ce cas est rare sur une vraie prise.
231231
- **Le spike exposait un seul clic** (`ctx.click`). Avec quatre, deux clics rapprochés gardent
232232
chacun leur onde.
233+
- **Rien d'autre n'est lié.** Une variable `@group`/`@binding` dans le code de l'agent est
234+
refusée, avec sa ligne : aucun backend ne la lierait.
233235

234236
### C.3 Les paramètres sont nommés et typés
235237

@@ -338,6 +340,10 @@ refusé parce que la machine qui l'écrit est modeste.
338340
1080p et 17 µs en 4K, au-dessus d'un fixe de 0,03 ms. Un effet léger coûte au plus 0,06 ms par
339341
frame en 1080p, un moyen 0,14 ms, un lourd 0,54 ms, 512 lectures 2,1 ms. Le détail est dans
340342
[rendering-performance.md](../technical-documentation/engineering/rendering-performance.md).
343+
- **Mesuré sur lavapipe** (le repli CPU de Linux, 16 threads) : environ 1,4 ms par lecture en
344+
1080p, 350 fois la RTX. Un effet léger y ajoute jusqu'à 11 ms à une frame qui en coûte 7,5 ;
345+
un lourd, 234 ms. L'ordre des paliers tient, mais sans GPU même un effet léger double le
346+
temps d'export.
341347
- **Le GPU intégré de référence** (le Radeon 610M des mesures Linux) reste à mesurer : on y attend
342348
plusieurs fois ces coûts. La description de l'outil donnera les paliers en ms sur les deux
343349
machines, pour que l'agent raisonne en temps et non en lectures.
@@ -424,10 +430,10 @@ Une seule source WGSL, traduite par naga au moment de compiler.
424430
|---|---|---|---|
425431
| Traduction | naga vers HLSL SM 5.0 | naga vers MSL | aucune : WGSL tel quel |
426432
| Compilation | `D3DCompile` (FXC) vers DXBC, puis `CreateVertexShader`/`CreatePixelShader` | `new_library_with_source`, puis `make_pipeline(…, Blend::Replace)` | `create_shader_module`, puis `create_render_pipeline` |
427-
| Thread de fond | naga et FXC (fait) | bibliothèque et pipeline, sous `autoreleasepool` | module et pipeline |
428-
| Copie du RT | `CopySubresourceRegion` vers `ann_copy` (fait) | `snapshot_rt(cmd_buf, false)` | `copy_texture_to_texture` vers `ann_copy` (comme le verre) |
429-
| Insertion | fin de `compose_frame` (fait) | entre `draw_annotations(…, false)` et `submit` | entre l'ann-pass et `submit` |
430-
| Uniforms | `Map(WRITE_DISCARD)` (fait) | `set_fragment_bytes` | `create_buffer_init(UNIFORM)` par draw |
433+
| Thread de fond | naga et FXC (fait) | bibliothèque et pipeline, sous `autoreleasepool` | module et pipeline (fait) |
434+
| Copie du RT | `CopySubresourceRegion` vers `ann_copy` (fait) | `snapshot_rt(cmd_buf, false)` | `copy_texture_to_texture` vers le niveau 0 d'`ann_copy` (fait) |
435+
| Insertion | fin de `compose_frame` (fait) | entre `draw_annotations(…, false)` et `submit` | `image` entre la passe caméra et l'ann-pass, `text` et `both` après (fait) |
436+
| Uniforms | `Map(WRITE_DISCARD)` (fait) | `set_fragment_bytes` | `create_buffer_init(UNIFORM)` par passe (fait) |
431437

432438
**macOS en détail**
433439
- **Activer `msl-out`.** Le dépôt l'obtient aujourd'hui par unification des features de wgpu ; le
@@ -447,7 +453,14 @@ Une seule source WGSL, traduite par naga au moment de compiler.
447453
- **Le thread de fond.** `wgpu::Device` est `Send`, `Sync` et `Clone` : le pipeline peut se
448454
construire hors du thread de rendu.
449455
- **Valider avant wgpu.** Aucun `on_uncaptured_error` n'est posé, donc une erreur de validation
450-
wgpu fait paniquer. La pré-validation par naga (`shader_fx::validate`) en protège.
456+
wgpu fait paniquer. La pré-validation (`shader_fx::analyze`) en protège : naga 24, celui de
457+
wgpu 24, et le refus de tout binding que le prélude ne déclare pas. Si wgpu panique malgré tout,
458+
seul le thread de compilation meurt, et l'effet ne se dessine pas (D.6).
459+
- **« Accepté » sous Linux.** `check_for_agent` traduit l'effet en SPIR-V par naga, comme wgpu le
460+
fera. La compilation par le pilote Vulkan n'a lieu qu'à `set_scene`, faute de device dans
461+
l'outil.
462+
- **Le calque des textes** est une texture RGBA8 transparente, posée sur le RT par la passe qui
463+
recopie déjà `accum` (`pipeline_copy`, « over » prémultiplié).
451464

452465
**naga reste en 24.** À partir de la 25, sa sortie HLSL déclare les samplers dans un tas D3D12
453466
(`register(s0, space0)`), que FXC refuse en `ps_5_0` (erreur X3721). Le test
@@ -692,10 +705,12 @@ qu'on n'a pas écrit.
692705
| Export de 180 frames en 1752×1080 : sans effet, avec effet, avec effet lourd | 520, 523 et 521 ms |
693706
| Preview en lecture, source à 30 i/s | 30 i/s avec et sans effet |
694707

708+
Mesuré à la passe Linux (lavapipe sous WSL, 16 threads) : effet prêt en 18 ms après `set_scene`,
709+
module et pipeline compris ; les paliers en C.7.
710+
695711
À mesurer à l'implémentation :
696712
- un GPU intégré (le Radeon 610M des mesures Linux) ;
697-
- le compilateur Metal ;
698-
- lavapipe en CI.
713+
- le compilateur Metal.
699714

700715
Les résultats iront dans
701716
[rendering-performance.md](../technical-documentation/engineering/rendering-performance.md).

‎technical-documentation/architecture/native-compositor.md‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ and without that flag the runtime corruption is silent.
2929
| [`crates/compositor/src/ffi.rs`](../../crates/compositor/src/ffi.rs) | bindgen-generated `libav*` bindings (ffmpeg 8.x headers) |
3030
| [`crates/compositor/src/compositor.rs`](../../crates/compositor/src/compositor_windows.rs) | HLSL compositor — every per-frame pass (`compose_frame`, background, screen, webcam, cursor, annotations, shadows, blur) |
3131
| [`crates/compositor/src/scene.rs`](../../crates/compositor/src/scene.rs) | the `Scene` struct parsed from the app's `SceneDescription` JSON |
32-
| [`crates/compositor/src/shader_fx.rs`](../../crates/compositor/src/shader_fx.rs) | agent-written shader effects: the WGSL contract, validation and loop rule, cost tiers, parameter packing, background compilation (FXC on Windows) |
32+
| [`crates/compositor/src/shader_fx.rs`](../../crates/compositor/src/shader_fx.rs) | agent-written shader effects: the WGSL contract, validation and loop rule, cost tiers, parameter packing, background compilation (FXC on Windows; on Linux, `compositor_linux.rs` builds wgpu pipelines) |
3333
| [`crates/compositor/src/regions.rs`](../../crates/compositor/src/regions.rs) | zoom / speed / Full Camera regions — envelope shapes and per-frame state sampling |
3434
| [`crates/compositor/src/pipeline.rs`](../../crates/compositor/src/pipeline_windows.rs) | demux + `D3D11VA` decode + composite + AMF encode + mux (`run_c0` for decode/encode only, `run_composited` for the full path) |
3535
| [`crates/compositor/src/audio.rs`](../../crates/compositor/src/audio.rs) | per-clip audio decode, swresample → f32 planar 48 kHz stereo, libavfilter `atempo` speed stretch (WSOLA fallback), multi-track mix, AAC encoder |
@@ -186,11 +186,17 @@ backend-specific.
186186
parameters, bound at `b3`), then the contract-v1 prelude: `frame()`, `ctx` (`b2`), `fx_px`,
187187
`fx_hash` and the `fx_vs`/`fx_fs` entry points. Errors therefore point at the agent's lines.
188188
- **Validation** (`analyze`) is naga's, plus the loop rule: every loop is a `for` with literal
189-
bounds, at most 4 096 iterations per pixel. It also estimates the cost, in `frame()` reads per
190-
pixel, as an indicative tier (light, medium, heavy, very heavy). Nothing is refused on cost.
189+
bounds, at most 4 096 iterations per pixel. An effect declares no binding beyond the prelude's
190+
four. It also estimates the cost, in `frame()` reads per pixel, as an indicative tier (light,
191+
medium, heavy, very heavy). Nothing is refused on cost.
191192
- **Compilation never happens on the render thread.** `set_scene` starts one background compile per
192-
new source (naga to HLSL SM 5.0, then FXC). The cache is keyed by contract, code and parameter
193-
layout, and keeps the 64 most recently used.
193+
new source. The cache is keyed by contract, code and parameter layout, and keeps the 64 most
194+
recently used.
195+
- **Windows:** naga to HLSL SM 5.0, then FXC.
196+
- **Linux:** the WGSL goes to wgpu as it is. The thread builds the shader module and the
197+
pipeline, against an explicit layout of the prelude's four bindings. wgpu panics on a
198+
validation error, since no `on_uncaptured_error` is set: `analyze` runs first so that none
199+
can happen, and a panic would only kill that thread, leaving the effect undrawn.
194200
- **Blocking.** The export compositor waits for a pending compile and never draws a frame without
195201
its effect. The live view (`set_shader_fx_blocking(false)`) skips the effect until it lands, then
196202
recomposes the paused frame (`shader_fx_landed`).
@@ -436,10 +442,11 @@ licence. D3D11VA + AMF survive the LGPL-shared build (verified:
436442
rasteriser: one that needs no D3D device at all. Giving the helper a WARP
437443
device would add a slow path nobody needs alongside a working one.
438444

439-
### Known gap: shader effects draw on Windows only
445+
### Known gap: shader effects do not draw on macOS
440446

441-
The Metal and wgpu compositors parse `shader_effects` but do not draw them: an effect is visible on
442-
Windows only. [docs/shader-effects.md](../../docs/shader-effects.md) (D.5) specifies both passes.
447+
The Metal compositor parses `shader_effects` but does not draw them: an effect is visible on
448+
Windows and Linux only. [docs/shader-effects.md](../../docs/shader-effects.md) (D.5) specifies the
449+
Metal pass.
443450

444451
### Known gap: the capture fallback is unreachable on a host that fails D3D
445452

‎technical-documentation/engineering/rendering-performance.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,19 @@ An agent-written effect (`crates/compositor/src/shader_fx.rs`, [docs/shader-effe
448448

449449
- **The cost is linear in the reads,** about 4 µs per read at 1080p and 17 µs at 4K, over a fixed 0.03 ms (1080p) for the copy and the pass. It is the texture bandwidth that pays, which is why the tiers count reads.
450450
- **The export does not notice a light effect:** 180 frames at 1752×1080 took 520 ms without, 523 ms with the spike's effect, and 521 ms with a heavier one. The preview held the source's 30 fps either way.
451-
- **Not measured yet:** an integrated GPU, where the same reads cost several times more, and the Metal and wgpu passes.
451+
- **On lavapipe, the Linux CPU fallback,** the same bench (`compositor_linux::tests::shader_fx_tier_calibration`, release, best of three runs of 5 frames, WSL on 16 threads) gives about 1.4 ms per read at 1080p, 350 times the RTX:
452+
453+
| `frame()` reads | Tier | 1080p | 4K |
454+
|---:|---|---:|---:|
455+
| none (the frame alone) | | 7.5 ms | 29.5 ms |
456+
| 1 | light | +3.2 ms | +13.4 ms |
457+
| 8 | light | +11.2 ms | +44.4 ms |
458+
| 32 | medium | +42.1 ms | +159 ms |
459+
| 128 | heavy | +234 ms | +958 ms |
460+
| 512 | very heavy | +1 035 ms | +5 068 ms |
461+
462+
- **The tiers keep their order on lavapipe,** but without a GPU a light effect already doubles the frame. The pipeline is ready 18 ms after `set_scene` there, module and driver compile included.
463+
- **Not measured yet:** an integrated GPU, where the same reads cost several times more, and the Metal pass.
452464

453465
## How we got here — the WebCodecs trail
454466

0 commit comments

Comments
 (0)