Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

refactor(scene): carry fractions across the native contract, never pixels

Etienne Lescot0f320f35243f
diff --git a/docs/openscreen-ux-ui-spec.md b/docs/openscreen-ux-ui-spec.md
index d73cb8c14..47c2c3f59 100644
--- a/docs/openscreen-ux-ui-spec.md
+++ b/docs/openscreen-ux-ui-spec.md
@@ -300,7 +300,9 @@ Only visible if a webcam video is present.
There is no fixed split anymore: it falls out of those three constraints and adapts to both the capture ratio and the scene ratio. When the geometry allows a near-square camera that also fills the scene, both happen at once (e.g. a 4:3 capture top/bottom in a 9:16 scene → square camera, 100 % fill). Camera Shape and Webcam Size do not apply to either preset. The single tunable is the square tolerance.
-Both halves are framed identically: the camera is always a **rectangle** with the *same* corner radius as the screen, whatever shape the user last picked under PiP. The mask picker is hidden here, but the setting survives — so the layout resolves the shape (`webcamRect.maskShape`) and the radius (`webcamRadius`) itself and every renderer, native compositor included, consumes those rather than the raw setting. Shipping the raw one is what used to let a circle chosen in PiP follow the user into Side by side and round the camera off into a disc, with the rounding changing depending on which shape happened to be stored.
+Both halves are framed identically: the camera is always a **rectangle** with the *same* corner radius as the screen, whatever shape the user last picked under PiP. The mask picker is hidden here, but the setting survives — so the layout resolves the shape (`webcamRect.maskShape`) and the radius (`webcamRadiusFrac`) itself and every renderer, native compositor included, consumes those rather than the raw setting. Shipping the raw one is what used to let a circle chosen in PiP follow the user into Side by side and round the camera off into a disc, with the rounding changing depending on which shape happened to be stored.
+
+**Every length crossing the native scene contract is a fraction, never a pixel count.** The compositor rasterises the preview into a small contain-fitted frame and the export at full output size, so "a pixel" means two different things on the two sides of that boundary — an absolute value crossing it silently becomes *render-target* pixels. Each quantity names its own reference: a corner radius is a fraction of **its own box's short side** (`screenRadiusFrac`, `webcamRadiusFrac`), so the rounding stays put when the box is resized; the Roundness slider, the drop shadows and the cursor are fractions of the **frame's short side**. The sliders stay in pixels for the user — the division happens once, in `buildSceneDescription`. This is not hygiene: absolute pixels crossing the contract are what drew the PiP circle as a shrunken blob in the preview while the export was correct, and what gave a 4K export a proportionally weaker shadow and a smaller cursor than a 1080p one.
The webcam bubble can also be dragged around the canvas (mouse-drag) — the position persists as `webcamPosition`.
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index bca5d84b3..20eec05d4 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -218,10 +218,13 @@ pub fn webcam_shape_code(shape: &str) -> u32 {
/// Unités identiques à `RightPanes.tsx` (mêmes conversions, pas de re-normalisation) : voir
/// `sceneDescription.ts` pour la correspondance settings -> champs de scène.
pub fn live_params_from_scene(s: &crate::scene::Scene) -> LiveParams {
- const NATIVE_SCREEN_BASE_RADIUS_PX: f32 = 24.0;
LiveParams {
shadow_scale: s.effects.shadow,
- radius_scale: s.effects.roundness_px / NATIVE_SCREEN_BASE_RADIUS_PX,
+ // `radius_scale` reste le multiplicateur du chemin INSPECTOR (bench/GUI standalone) ; le
+ // rayon écran d'une scène vient désormais de `effects.roundness_frac`, lu directement
+ // dans `compose_frame`. Le faire transiter ici obligeait à le normaliser par un rayon de
+ // fixture (`p.screen.radius`, 24 px) pour ressortir la valeur de départ — un aller-retour
+ // qui ne servait qu'à faire passer des pixels pour un ratio.
padding: s.effects.padding,
webcam_size_scale: s.layout.webcam_size,
webcam_mirror: s.layout.webcam_mirror,
@@ -341,6 +344,23 @@ pub const HALF_H: u32 = OUT_H / 2;
pub const FIXTURE_FRAMES: u32 = 360;
const FPS: f32 = 60.0;
+/// Longueurs de style exprimées en FRACTION du petit côté du cadre, et non en pixels.
+///
+/// Elles étaient écrites en px bruts au point d'appel, ce qui voulait dire « px du render
+/// target » — donc une proportion DIFFÉRENTE selon la taille de rendu : 40 px, c'est 3,7 % d'un
+/// cadre 1080 mais 1,9 % d'un 2160. L'ombre était donc deux fois plus douce en preview qu'à
+/// l'export, et un export 4K la recevait deux fois plus faible qu'un 1080p — même famille de bug
+/// que les rayons venus de l'app, mais née à l'intérieur du natif. Les valeurs ci-dessous sont
+/// les anciennes constantes rapportées au cadre 1080 contre lequel elles avaient été réglées :
+/// le rendu à cette résolution est donc inchangé, et devient enfin identique partout ailleurs.
+const SHADOW_TUNING_REF_PX: f32 = 1080.0;
+const SCREEN_SHADOW_SPREAD_FRAC: f32 = 40.0 / SHADOW_TUNING_REF_PX;
+const SCREEN_SHADOW_OFFSET_FRAC: f32 = 16.0 / SHADOW_TUNING_REF_PX;
+const WEBCAM_SHADOW_SPREAD_FRAC: f32 = 32.0 / SHADOW_TUNING_REF_PX;
+const WEBCAM_SHADOW_OFFSET_FRAC: f32 = 12.0 / SHADOW_TUNING_REF_PX;
+/// Taille de base du curseur, même convention (34 px réglés contre un cadre 1080).
+const CURSOR_BASE_SIZE_FRAC: f32 = 34.0 / SHADOW_TUNING_REF_PX;
+
fn ease_in_out_cubic(x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
if x < 0.5 {
@@ -1511,6 +1531,11 @@ impl Compositor {
let lerp = |a: f32, b: f32| a + (b - a) * progress;
[lerp(dst[0], 0.0), lerp(dst[1], 0.0), lerp(dst[2], 1.0), lerp(dst[3], 1.0)]
};
+ // Petit côté de la boîte caméra AVANT que Full Camera ne la fasse grandir. C'est la
+ // référence du rayon de coin : le zoom réactif est déjà dedans (il rétrécit la boîte,
+ // donc l'arrondi suit tout seul — parité `borderRadius * reactiveFactor` côté TS), alors
+ // que Full Camera ne fait pas grossir l'arrondi, il le DISSOUT (cf. `shape_fade`).
+ let w_nominal_min = (w_dst[2] * self.rw()).min(w_dst[3] * self.rh());
w_dst = fullscreen_dst(w_dst, cam_progress);
w_dst_prev = fullscreen_dst(w_dst_prev, cam_progress_prev);
@@ -1524,71 +1549,54 @@ impl Compositor {
// reste préservé (letterboxé/pillarboxé sur le fond, qui lui reste plein cadre) — mode
// "fit"/contain. Si l'utilisateur veut un rendu "fill" (remplir sans bandes), il ajuste
// le crop lui-même ; le natif ne fait plus ce choix à sa place en étirant l'image.
- // `roundness_px` est un px ABSOLU de la résolution de SORTIE (comme un border-radius
- // CSS). Le dessin du coin (SDF, shaders.hlsl) pré-déforme lui-même ses coordonnées par
- // `stretch_x`/`stretch_y` (mb.yz) avant de comparer à ce rayon, donc `s_radius` reste
- // ici une valeur BRUTE en px de sortie réelle — pas de correction scalaire à faire ici
- // (une correction scalaire par `uniform_stretch` seul compenserait la MAGNITUDE mais pas
- // l'ANISOTROPIE : elle laissait les coins elliptiques dès que stretch_x != stretch_y,
- // càd dès que le ratio de sortie n'est pas 16:9 — cf. rapport utilisateur sur le 9:16).
- // Rayon écran : celui que le preset impose quand l'app en envoie un (les layouts en bloc
- // encadrent écran et caméra à l'identique), sinon le slider Roundness comme avant.
+ // Le dessin du coin (SDF, shaders.hlsl) compare le rayon à `quad_px`, exprimé en px du
+ // RENDER TARGET : c'est donc dans cet espace-là qu'il faut le lui donner.
//
- // Les rayons que l'app résout sont en px de la SORTIE, alors que la SDF les compare à
- // `quad_px`, exprimé en px du RENDER TARGET. À l'export les deux coïncident ; en preview
- // le rendu se fait dans un cadre contain-fitté plus petit (même ratio, cf.
- // `preview_render_size`), et un rayon absolu y devient proportionnellement trop grand.
- // `sd_round_rect` ne borne PAS r à la demi-boîte : au-delà, la forme ne sature pas en
- // disque, elle dégénère en tache rétrécie — c'est ce qui cassait le cercle du PiP en
- // preview alors que l'export, lui, restait juste. Ce facteur ramène ces rayons dans
- // l'espace du render target ; il vaut exactement 1 à l'export.
- let app_px_to_render = scene_ref
- .as_ref()
- .map(|s| s.output.width as f32)
- .filter(|w| *w > 0.0)
- .map(|w| self.rw() / w)
- .unwrap_or(1.0);
- let app_screen_radius = scene_ref.as_ref().and_then(|s| s.layout.screen_radius);
- let s_radius = match (cfg.rounded, app_screen_radius) {
- (false, _) => 0.0,
- (true, Some(r)) => r * app_px_to_render,
- (true, None) => p.screen.radius * lp.radius_scale,
+ // Toutes les longueurs de la scène sont des FRACTIONS ; on les multiplie ici par ce
+ // qu'elles mesurent, dans l'espace du render target. C'est ce qui rend preview et export
+ // identiques : « un pixel » n'y désigne pas la même chose (la preview rastérise dans un
+ // cadre contain-fitté plus petit, cf. `preview_render_size`), alors qu'une fraction, si.
+ // `frame_min_px` est la référence des quantités relatives au CADRE ; un rayon de coin,
+ // lui, se mesure contre sa propre boîte — il doit rester en place quand on redimensionne
+ // la boîte, pas suivre le cadre.
+ let frame_min_px = self.rw().min(self.rh());
+ let s_min_px = (s_dst[2] * self.rw()).min(s_dst[3] * self.rh());
+ let app_screen_radius_frac = scene_ref.as_ref().and_then(|s| s.layout.screen_radius_frac);
+ let scene_roundness_frac = scene_ref.as_ref().map(|s| s.effects.roundness_frac);
+ let s_radius = match (cfg.rounded, app_screen_radius_frac, scene_roundness_frac) {
+ (false, _, _) => 0.0,
+ // Preset en bloc : le rayon appartient à la boîte écran (parité exacte avec la caméra).
+ (true, Some(f), _) => f * s_min_px,
+ // Scène sans rayon imposé : slider Roundness, relatif au cadre.
+ (true, None, Some(f)) => f * frame_min_px,
+ // Fixture/bench (pas de scène) : chemin inspector historique, inchangé.
+ (true, None, None) => p.screen.radius * lp.radius_scale,
};
let w_px = [w_dst[2] * self.rw(), w_dst[3] * self.rh()];
// Rayon caméra. Le slider Roundness ne s'y applique jamais (il ne vaut que pour l'ÉCRAN).
- // Rayon "brut" (SDF anisotrope, cf. écran ci-dessus) dérivé de la taille FINALE du quad,
- // pour un rayon proportionnellement correct quel que soit le ratio de sortie.
- let w_px_final = w_px;
- let w_min_final = w_px_final[0].min(w_px_final[1]);
- // Quand l'app résout le rayon (`computeCompositeLayout`, source unique), on le prend :
- // c'est la seule façon que les deux moitiés d'un layout en bloc soient encadrées à
- // l'identique, l'écran consommant déjà `screen_radius` du même calcul. La table ci-dessous
- // en était une SECONDE, indépendante — fractions différentes (0.12 vs 0.06 côté web) et
- // sans bornes — donc écran et caméra ne pouvaient pas s'accorder.
- //
- // Le rayon de l'app vaut pour la taille NOMINALE de la caméra, et `webcam_size_scale` est
- // précisément ce qui l'en écarte (zoom réactif ; l'échelle du slider est déjà cuite dans
- // le rect de l'app, cf. `base_size_scale`). Le multiplier redonne mot pour mot ce que fait
- // le TS — `borderRadius * reactiveFactor` — sans repasser par la taille finale de la boîte.
- // `app_px_to_render` le ramène ensuite dans l'espace du render target (cf. plus haut).
- let app_webcam_radius = scene_ref.as_ref().and_then(|s| s.layout.webcam_radius);
+ // Quand l'app le résout (`computeCompositeLayout`, source unique), on le prend : c'est la
+ // seule façon que les deux moitiés d'un layout en bloc soient encadrées à l'identique,
+ // l'écran consommant déjà `screen_radius_frac` du même calcul. La table ci-dessous en
+ // était une SECONDE, indépendante — fraction différente (0.12 vs 0.06 côté web) et sans
+ // bornes — donc écran et caméra ne pouvaient pas s'accorder.
+ let app_webcam_radius_frac = scene_ref.as_ref().and_then(|s| s.layout.webcam_radius_frac);
// Full Camera dissout la forme en même temps qu'elle prend le cadre : le rayon fond
// vers 0 avec `cam_progress`, donc le cercle devient un rect à coins de plus en plus
// francs puis un plein cadre net — aucun masque ne survit au plein écran (parité
// `computeCameraFullscreenRect`, qui ramène `maskShape` à "rectangle" et lerpe le
- // rayon vers 0 pour exactement la même raison). `reactive_scale` vaut déjà 1 pendant
- // Full Camera, donc les deux animations ne se composent pas — comme côté TS.
+ // rayon vers 0 pour exactement la même raison).
let shape_fade = (1.0 - cam_progress).clamp(0.0, 1.0);
let w_radius = shape_fade
- * match app_webcam_radius {
- Some(r) => r * webcam_size_scale * app_px_to_render,
- // Fallback (payload sans rayon, fixture/bench) : l'ancienne table, keyée sur la
+ * w_nominal_min
+ * match app_webcam_radius_frac {
+ Some(f) => f,
+ // Fallback (payload sans fraction, fixture/bench) : l'ancienne table, keyée sur la
// forme. Rectangle ET square n'ont qu'un léger arrondi (0.12) et ne diffèrent que
// par le ratio ; rounded est nettement plus arrondi (0.3) ; circle = demi-côté.
None => match lp.webcam_shape {
- 1 => w_min_final * 0.5,
- 3 => w_min_final * 0.3,
- _ => w_min_final * 0.12,
+ 1 => 0.5,
+ 3 => 0.3,
+ _ => 0.12,
},
};
@@ -1712,7 +1720,14 @@ impl Compositor {
cover(screen_source_rect(u_max, v_max, active_crop, pp.zoom, p.focus));
let (hu_p, hv_p) = ((su1_p - su0_p) * 0.5, (sv1_p - sv0_p) * 0.5);
if cfg.shadow {
- self.draw_shadow(s_dst, s_px, s_radius, 40.0, [0.0, 16.0], 0.45 * lp.shadow_scale);
+ self.draw_shadow(
+ s_dst,
+ s_px,
+ s_radius,
+ SCREEN_SHADOW_SPREAD_FRAC * frame_min_px,
+ [0.0, SCREEN_SHADOW_OFFSET_FRAC * frame_min_px],
+ 0.45 * lp.shadow_scale,
+ );
}
if crate::regions::is_identity_rotation(zoom_rotation) {
self.draw_video(
@@ -1819,7 +1834,9 @@ impl Compositor {
// pareil pour rester à l'échelle du contenu (sinon sa pointe semble se
// décaler/dériver à mesure que le padding grandit).
let bounce = 1.0 + (track.bounce(t) - 1.0) * lp.cursor_bounce_scale;
- let sz = 34.0 * lp.cursor_size_scale * bounce * padding_scale;
+ let sz =
+ CURSOR_BASE_SIZE_FRAC * frame_min_px * lp.cursor_size_scale * bounce
+ * padding_scale;
// flou de mouvement DU CURSEUR, indépendant de cfg.mblur_n (écran/vidéo).
// BUG corrigé : augmenter l'intensité ne faisait auparavant que sur-échantillonner
// (plus de taps) un écart figé d'1 frame (1/60s) -> la traînée ne s'allongeait
@@ -1912,7 +1929,14 @@ impl Compositor {
// (`shape_fade`), pour qu'au plein écran plus rien n'encadre la caméra.
if cfg.shadow && shape_fade > 0.0 {
let strength = 0.5 * lp.shadow_scale * shape_fade;
- self.draw_shadow(w_dst, w_px, w_radius, 32.0, [0.0, 12.0], strength);
+ self.draw_shadow(
+ w_dst,
+ w_px,
+ w_radius,
+ WEBCAM_SHADOW_SPREAD_FRAC * frame_min_px,
+ [0.0, WEBCAM_SHADOW_OFFSET_FRAC * frame_min_px],
+ strength,
+ );
}
self.draw_video(
&LayerCB {
diff --git a/poc-d3d/src/live.rs b/poc-d3d/src/live.rs
index 6fd35319d..2e066d27c 100644
--- a/poc-d3d/src/live.rs
+++ b/poc-d3d/src/live.rs
@@ -1371,7 +1371,7 @@ mod tests {
{"screenPath":"/distinct-screen.mp4","webcamPath":"/distinct-webcam.mp4","sourceStartSec":100,"sourceEndSec":104,"webcamOffsetSec":0.5,"hasAudio":true}
],
"layout":{"preset":"picture-in-picture","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},
- "effects":{"padding":0,"blur":false,"shadow":0,"roundnessPx":0,"motionBlur":0},
+ "effects":{"padding":0,"blur":false,"shadow":0,"roundnessFrac":0,"motionBlur":0},
"background":{"kind":"color","color":"#000000"},
"zoomRegions":[],
"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},
@@ -1408,7 +1408,7 @@ mod tests {
fn scene_with_output(w: u32, h: u32) -> Scene {
Scene::from_json(&format!(
- r##"{{"clips":[],"layout":{{"preset":"no-webcam","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false}},"effects":{{"padding":0,"blur":false,"shadow":0,"roundnessPx":0,"motionBlur":0}},"background":{{"kind":"color","color":"#000000"}},"zoomRegions":[],"cursor":{{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"}},"cropByClip":[],"output":{{"width":{w},"height":{h},"fps":null}}}}"##
+ r##"{{"clips":[],"layout":{{"preset":"no-webcam","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false}},"effects":{{"padding":0,"blur":false,"shadow":0,"roundnessFrac":0,"motionBlur":0}},"background":{{"kind":"color","color":"#000000"}},"zoomRegions":[],"cursor":{{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"}},"cropByClip":[],"output":{{"width":{w},"height":{h},"fps":null}}}}"##
))
.expect("scene valide")
}
diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rs
index 21a871588..d8ebdd367 100644
--- a/poc-d3d/src/scene.rs
+++ b/poc-d3d/src/scene.rs
@@ -64,10 +64,11 @@ pub struct SceneLayout {
/// `#[serde(default)]` : ancien payload / tests → None → fallback `preset_placements`.
#[serde(default)]
pub screen_rect: Option<SceneRect>,
- /// Rayon des coins de l'écran en px de la sortie, quand le preset en impose un (les layouts
- /// en bloc encadrent écran et caméra à l'identique). None → slider Roundness, comme avant.
+ /// Rayon des coins de l'écran, en FRACTION du petit côté de sa propre boîte, quand le preset
+ /// en impose un (les layouts en bloc encadrent écran et caméra à l'identique). None → slider
+ /// Roundness. Une fraction, pas des px : cf. `SceneEffects::roundness_frac`.
#[serde(default)]
- pub screen_radius: Option<f32>,
+ pub screen_radius_frac: Option<f32>,
/// L'écran doit-il REMPLIR sa boîte quitte à être rogné (`object-fit: cover`) plutôt que d'y
/// tenir en entier ? Vrai pour les layouts en bloc, dont la boîte écran est un slot au ratio
/// arbitraire : c'est ce que `computeCompositeLayout` renvoie sous `screenCover` et que
@@ -92,22 +93,24 @@ pub struct SceneLayout {
/// `compose_frame` continue de lire un seul `layout` sans branche supplémentaire.
#[serde(default)]
pub layout_by_clip: Vec<Option<ResolvedClipLayout>>,
- /// Rayon des coins de la CAMÉRA, même convention px-de-sortie que `screen_radius` et issu du
- /// même appel `computeCompositeLayout`. C'est la seule façon que « le bloc encadre écran et
- /// caméra à l'identique » soit vrai : sans lui l'écran prenait le rayon de l'app pendant que
- /// la caméra gardait la table Rust indépendante ci-dessous (`min * 0.5 | 0.3 | 0.12`, non
- /// bornée), donc deux moitiés d'un même bloc arrondies par deux formules différentes.
- ///
- /// Donné pour la taille NOMINALE de la caméra ; le natif le remet à l'échelle de la boîte
- /// réellement dessinée (zoom réactif, Full Camera).
+ /// Rayon des coins de la CAMÉRA, en fraction du petit côté de SA boîte — même règle que
+ /// `screen_radius_frac`, issu du même appel `computeCompositeLayout`. C'est la seule façon
+ /// que « le bloc encadre écran et caméra à l'identique » soit vrai : sans lui l'écran prenait
+ /// le rayon de l'app pendant que la caméra gardait la table Rust indépendante
+ /// (`min * 0.5 | 0.3 | 0.12`, non bornée), donc deux moitiés d'un même bloc arrondies par
+ /// deux formules différentes.
///
/// `#[serde(default)]` : ancien payload / tests → None → table Rust historique.
#[serde(default)]
- pub webcam_radius: Option<f32>,
+ pub webcam_radius_frac: Option<f32>,
}
/// La moitié du layout qui dépend de la FORME de la source, résolue pour un clip.
/// Voir `SceneLayout::layout_by_clip`.
+///
+/// Les rayons sont des fractions du petit côté de LEUR boîte, exactement comme les champs
+/// scalaires `screen_radius_frac`/`webcam_radius_frac` — aucune longueur ne traverse ce
+/// contrat en pixels, par clip ou non.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolvedClipLayout {
@@ -115,9 +118,9 @@ pub struct ResolvedClipLayout {
#[serde(default)]
pub webcam_rect: Option<SceneRect>,
#[serde(default)]
- pub screen_radius: Option<f32>,
+ pub screen_radius_frac: Option<f32>,
#[serde(default)]
- pub webcam_radius: Option<f32>,
+ pub webcam_radius_frac: Option<f32>,
#[serde(default)]
pub webcam_shape: Option<String>,
#[serde(default)]
@@ -143,8 +146,17 @@ pub struct SceneEffects {
pub blur: bool,
/// 0..1 force de l'ombre.
pub shadow: f32,
- /// rayon des coins en px de sortie.
- pub roundness_px: f32,
+ /// Slider Roundness, en FRACTION du petit côté du cadre de sortie.
+ ///
+ /// Toute longueur qui traverse ce contrat est une fraction, jamais un nombre de pixels, et
+ /// c'est porteur : le compositeur rastérise la preview dans un cadre contain-fitté petit et
+ /// l'export à la pleine résolution, donc « un pixel » ne désigne pas la même chose des deux
+ /// côtés de la frontière. Des valeurs absolues la traversaient et signifiaient en silence
+ /// « px du render target » — d'où le cercle PiP dégénéré en preview alors que l'export était
+ /// juste, et l'ombre proportionnellement plus faible en 4K qu'en 1080p. Une fraction n'a
+ /// pas d'unité à confondre : le natif multiplie par ce que sa référence mesure ici et
+ /// maintenant.
+ pub roundness_frac: f32,
/// 0..1 flou de mouvement.
pub motion_blur: f32,
}
@@ -311,8 +323,8 @@ impl Scene {
if let Some(Some(l)) = scene.layout.layout_by_clip.get(clip_index).cloned() {
scene.layout.screen_rect = Some(l.screen_rect);
scene.layout.webcam_rect = l.webcam_rect;
- scene.layout.screen_radius = l.screen_radius;
- scene.layout.webcam_radius = l.webcam_radius;
+ scene.layout.screen_radius_frac = l.screen_radius_frac;
+ scene.layout.webcam_radius_frac = l.webcam_radius_frac;
scene.layout.screen_cover = l.screen_cover;
if let Some(shape) = l.webcam_shape {
scene.layout.webcam_shape = shape;
@@ -332,7 +344,7 @@ mod tests {
let json = r##"{
"clips": [{"screenPath":"/s.mp4","webcamPath":"/w.mp4","sourceStartSec":0,"sourceEndSec":4,"webcamOffsetSec":0,"hasAudio":true}],
"layout": {"preset":"picture-in-picture","webcamSize":1.5,"webcamShape":"circle","webcamMirror":true,"webcamPosition":null,"webcamReactiveZoom":false},
- "effects": {"padding":0.5,"blur":true,"shadow":0.8,"roundnessPx":24,"motionBlur":0.0},
+ "effects": {"padding":0.5,"blur":true,"shadow":0.8,"roundnessFrac":0.0222,"motionBlur":0.0},
"background": {"kind":"gradient","angleDeg":135,"stops":["#eaebed","#bcc0c6"]},
"zoomRegions": [{"clipIndex":0,"startSec":1.0,"endSec":3.0,"scale":2.0,"focusX":0.5,"focusY":0.3,"rotation":"iso"}],
"speedRegions": [{"clipIndex":0,"startSec":1.0,"endSec":2.0,"speed":2.0}],
@@ -345,7 +357,7 @@ mod tests {
assert_eq!(scene.clips[0].screen_path, "/s.mp4");
assert_eq!(scene.layout.preset, "picture-in-picture");
assert!(scene.layout.webcam_mirror);
- assert_eq!(scene.effects.roundness_px, 24.0);
+ assert!((scene.effects.roundness_frac - 0.0222).abs() < 1e-6);
match scene.background {
SceneBackground::Gradient { angle_deg, ref stops } => {
assert_eq!(angle_deg, 135.0);
@@ -363,7 +375,7 @@ mod tests {
#[test]
fn parses_color_and_image_backgrounds() {
- let color = r##"{"clips":[],"layout":{"preset":"no-webcam","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},"effects":{"padding":0,"blur":false,"shadow":0,"roundnessPx":0,"motionBlur":0},"background":{"kind":"color","color":"#123456"},"zoomRegions":[],"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},"cropByClip":[],"output":{"width":1280,"height":720,"fps":30}}"##;
+ let color = r##"{"clips":[],"layout":{"preset":"no-webcam","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},"effects":{"padding":0,"blur":false,"shadow":0,"roundnessFrac":0,"motionBlur":0},"background":{"kind":"color","color":"#123456"},"zoomRegions":[],"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},"cropByClip":[],"output":{"width":1280,"height":720,"fps":30}}"##;
let s = Scene::from_json(color).expect("parse color");
match s.background {
SceneBackground::Color { ref color } => assert_eq!(color, "#123456"),
@@ -387,7 +399,7 @@ mod tests {
"webcamReactiveZoom": false,
"webcamRect": { "x": 0.8125, "y": 0.8125, "width": 0.1666667, "height": 0.1666667 }
},
- "effects": {"padding": 0, "blur": false, "shadow": 0, "roundnessPx": 24, "motionBlur": 0},
+ "effects": {"padding": 0, "blur": false, "shadow": 0, "roundnessFrac": 0.0222, "motionBlur": 0},
"background": {"kind":"color","color":"#000000"},
"zoomRegions": [],
"cursor": {"show": true, "size": 1, "smoothing": 0, "motionBlur": 0, "clickBounce": 1, "clipToBounds": false, "theme": "default"},
@@ -409,7 +421,7 @@ mod tests {
fn webcam_rect_field_optional_in_payload() {
// L'ancien payload sans `webcamRect` doit toujours parser sans erreur (le champ est
// `#[serde(default)]`) ; `webcam_rect` est alors None → fallback `preset_placements`.
- let json = r##"{"clips":[],"layout":{"preset":"picture-in-picture","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},"effects":{"padding":0,"blur":false,"shadow":0,"roundnessPx":0,"motionBlur":0},"background":{"kind":"color","color":"#000000"},"zoomRegions":[],"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},"cropByClip":[],"output":{"width":1920,"height":1080,"fps":null}}"##;
+ let json = r##"{"clips":[],"layout":{"preset":"picture-in-picture","webcamSize":1,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},"effects":{"padding":0,"blur":false,"shadow":0,"roundnessFrac":0,"motionBlur":0},"background":{"kind":"color","color":"#000000"},"zoomRegions":[],"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},"cropByClip":[],"output":{"width":1920,"height":1080,"fps":null}}"##;
let s = Scene::from_json(json).expect("parse sans webcam_rect");
assert!(s.layout.webcam_rect.is_none());
assert_eq!(s.layout.preset, "picture-in-picture");
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 7dd5d75d8..97f48e6df 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -670,9 +670,45 @@ describe("buildSceneDescription.settings mapping", () => {
expect(buildSceneDescription(doc).effects.padding).toBe(0.5);
});
- it("roundnessPx equals borderRadius", () => {
+ it("roundnessFrac is the slider divided by the frame's short side, not raw pixels", () => {
+ // The contract carries no pixel counts: the compositor rasterises the preview
+ // smaller than the export, so a pixel means two different things across the
+ // boundary. Absolute values crossing it is what drew the PiP circle as a blob.
const doc = makeDoc({ legacyEditor: { borderRadius: 12 } });
- expect(buildSceneDescription(doc).effects.roundnessPx).toBe(12);
+ const scene = buildSceneDescription(doc);
+ const shortSide = Math.min(scene.output.width, scene.output.height);
+ expect(scene.effects.roundnessFrac).toBeCloseTo(12 / shortSide, 10);
+ });
+
+ it("round-trips the authored pixel value at output size, whatever the resolution", () => {
+ // The slider keeps meaning "N pixels of the finished video" — the fraction only
+ // exists so the native side can rebuild it against whatever it is rasterising
+ // into. Multiplying back by the output's short side must return exactly N.
+ const at = (w: number, h: number) => {
+ const doc = makeDoc({
+ assets: [
+ makeAsset({
+ id: "a",
+ originalPath: "/a.mp4",
+ video: { codec: "h264", width: w, height: h, fps: 30 },
+ }),
+ ],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ ],
+ legacyEditor: { borderRadius: 24 },
+ });
+ const scene = buildSceneDescription(doc);
+ return scene.effects.roundnessFrac * Math.min(scene.output.width, scene.output.height);
+ };
+ expect(at(1920, 1080)).toBeCloseTo(24, 6);
+ expect(at(3840, 2160)).toBeCloseTo(24, 6);
});
it("webcamSize is webcamSizeToFraction(webcamSizePreset) — clamp(preset,10,50)/100", () => {
@@ -813,12 +849,12 @@ describe("buildSceneDescription.settings mapping", () => {
expect(cam!.x).toBeGreaterThan(screen!.x + screen!.width);
expect(cam!.height).toBeCloseTo(screen!.height, 3);
// The block layouts impose their corner radius on the screen too.
- expect(scene.layout.screenRadius).toBeGreaterThan(0);
+ expect(scene.layout.screenRadiusFrac).toBeGreaterThan(0);
});
- it("leaves screenRadius null for picture-in-picture, so the Roundness slider still drives it", () => {
+ it("leaves screenRadiusFrac null for picture-in-picture, so the Roundness slider still drives it", () => {
const doc = makeDoc({ legacyEditor: { webcamLayoutPreset: "picture-in-picture" } });
- expect(buildSceneDescription(doc).layout.screenRadius).toBeNull();
+ expect(buildSceneDescription(doc).layout.screenRadiusFrac).toBeNull();
});
/** A document with a camera on its only clip, so the layout resolves a webcam box. */
@@ -869,17 +905,26 @@ describe("buildSceneDescription.settings mapping", () => {
const reference = buildSceneDescription(
docWithCamera({ webcamLayoutPreset: "dual-frame", webcamMaskShape: "rectangle" }),
);
- expect(scene.layout.webcamRadius).toBe(reference.layout.webcamRadius);
- expect(scene.layout.webcamRadius).toBeGreaterThan(0);
+ expect(scene.layout.webcamRadiusFrac).toBe(reference.layout.webcamRadiusFrac);
+ expect(scene.layout.webcamRadiusFrac).toBeGreaterThan(0);
});
it("rounds both halves of a block alike — one radius, not two formulas", () => {
// The native side used to derive the camera's radius from its own table while the
- // screen took the app's, so the welded block could never match itself.
+ // screen took the app's, so the welded block could never match itself. Both are
+ // fractions of their OWN box, and the block gives the two boxes different shapes,
+ // so equality has to be checked back in output pixels.
const scene = buildSceneDescription(
docWithCamera({ webcamLayoutPreset: "vertical-stack", webcamMaskShape: "circle" }),
);
- expect(scene.layout.webcamRadius).toBe(scene.layout.screenRadius);
+ const px = (frac: number | null | undefined, box: { width: number; height: number } | null) =>
+ frac != null && box
+ ? frac * Math.min(box.width * scene.output.width, box.height * scene.output.height)
+ : null;
+ expect(px(scene.layout.webcamRadiusFrac, scene.layout.webcamRect ?? null)).toBeCloseTo(
+ px(scene.layout.screenRadiusFrac, scene.layout.screenRect ?? null) ?? 0,
+ 6,
+ );
});
it("still honours the shape picker under picture-in-picture", () => {
@@ -887,16 +932,15 @@ describe("buildSceneDescription.settings mapping", () => {
docWithCamera({ webcamLayoutPreset: "picture-in-picture", webcamMaskShape: "circle" }),
);
expect(scene.layout.webcamShape).toBe("circle");
- // A circle's radius is half its (square) box — what makes the native rounded-box
- // SDF draw an actual circle.
- const cam = scene.layout.webcamRect;
- expect(cam).not.toBeNull();
- expect(scene.layout.webcamRadius).toBeGreaterThan(0);
+ // A circle is a rounded rect whose radius is HALF its (square) box — that exact
+ // fraction is what makes the native rounded-box SDF draw a disc rather than a
+ // blob, at any render size.
+ expect(scene.layout.webcamRadiusFrac).toBeCloseTo(0.5, 2);
});
- it("leaves webcamRadius null when the layout resolves no camera box", () => {
+ it("leaves webcamRadiusFrac null when the layout resolves no camera box", () => {
const doc = makeDoc({ legacyEditor: { webcamLayoutPreset: "no-webcam" } });
- expect(buildSceneDescription(doc).layout.webcamRadius).toBeNull();
+ expect(buildSceneDescription(doc).layout.webcamRadiusFrac).toBeNull();
});
});
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index acf3fd516..a82e922d6 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -139,12 +139,6 @@ export interface SceneLayout {
* pushed the side-by-side camera past the edge of the scene.
*/
screenRect?: SceneRect | null;
- /**
- * Corner radius of the screen box in pixels of the output frame, when the preset
- * imposes one (the block layouts frame screen and camera alike). Null → the native
- * side keeps deriving it from the user's Roundness slider.
- */
- screenRadius?: number | null;
/**
* Should the screen FILL its box, cropping the overflow (`object-fit: cover`), rather
* than fit inside it? True for the block layouts, whose screen box is an arbitrary-ratio
@@ -170,26 +164,38 @@ export interface SceneLayout {
*/
layoutByClip?: Array<ResolvedClipLayout | null>;
/**
- * Corner radius of the webcam box, same output-pixel convention as `screenRadius`
- * and resolved by the same `computeCompositeLayout` call — so "the block frames
- * screen and camera alike" can actually hold. It could not before: the screen took
- * the app's radius while the camera kept a second, independent table in Rust
- * (`min * 0.5 | 0.3 | 0.12`, unclamped, keyed off the raw mask shape), so the two
- * halves of one welded block were rounded by two different formulas.
+ * Corner radius of the screen box, as a fraction of that box's own SHORT SIDE, when
+ * the preset imposes one (the block layouts frame screen and camera alike). Null →
+ * the native side falls back to the user's Roundness slider.
*
- * Given at the webcam's NOMINAL size: the native side rescales it with the box when
- * reactive zoom shrinks the bubble or Full Camera grows it, which is what keeps the
- * rounding proportional through those animations.
+ * A fraction, not pixels — see `roundnessFrac` for why the whole contract works this
+ * way. The denominator is the box rather than the frame on purpose: a corner radius
+ * belongs to the thing it rounds, so the rounding stays put when the box is resized.
+ */
+ screenRadiusFrac?: number | null;
+ /**
+ * Corner radius of the webcam box, as a fraction of ITS own short side — same rule as
+ * `screenRadiusFrac`, resolved by the same `computeCompositeLayout` call, so "the
+ * block frames screen and camera alike" can actually hold. It could not before: the
+ * screen took the app's radius while the camera kept a second, independent table in
+ * Rust (`min * 0.5 | 0.3 | 0.12`, unclamped, keyed off the raw mask shape), so the two
+ * halves of one welded block were rounded by two formulas that could not agree.
*/
- webcamRadius?: number | null;
+ webcamRadiusFrac?: number | null;
}
-/** The shape-dependent half of a layout, resolved for one clip. See `layoutByClip`. */
+/**
+ * The shape-dependent half of a layout, resolved for one clip. See `layoutByClip`.
+ *
+ * Radii are fractions of their own box's short side, exactly as the scalar
+ * `screenRadiusFrac`/`webcamRadiusFrac` above — no length crosses this contract in
+ * pixels, per-clip or not.
+ */
export interface ResolvedClipLayout {
screenRect: SceneRect;
webcamRect: SceneRect | null;
- screenRadius: number | null;
- webcamRadius: number | null;
+ screenRadiusFrac: number | null;
+ webcamRadiusFrac: number | null;
webcamShape: "rectangle" | "circle" | "square" | "rounded";
screenCover: boolean;
}
@@ -202,8 +208,21 @@ export interface SceneEffects {
blur: boolean;
/** 0..1 drop-shadow strength. */
shadow: number;
- /** Corner radius in output px. */
- roundnessPx: number;
+ /**
+ * Roundness slider, as a fraction of the output frame's SHORT SIDE.
+ *
+ * Every length crossing this contract is a fraction, never a pixel count, and that is
+ * load-bearing rather than stylistic: the native compositor rasterises the preview
+ * into a small contain-fitted frame and the export at full output size, so a pixel
+ * means two different things on the two sides of the boundary. Absolute values used to
+ * cross it and silently meant "render-target pixels" — which is why the preview drew
+ * the PiP circle as a shrunken blob while the export was correct, and why a 4K export
+ * got a proportionally weaker shadow than a 1080p one. A fraction has no unit to get
+ * wrong; the native side multiplies by whatever its reference measures right now.
+ *
+ * The slider itself stays in pixels for the user — the division happens here, once.
+ */
+ roundnessFrac: number;
/** 0..1 motion blur. */
motionBlur: number;
}
@@ -541,13 +560,21 @@ export function buildSceneDescription(
width: r.width / outputDims.width,
height: r.height / outputDims.height,
});
+ // Corner radii leave as a fraction of the box they round (see `screenRadiusFrac`).
+ // Both the radius and the box are measured in output pixels here, so the ratio is
+ // scale-invariant — the clamp `computeCompositeLayout` applies in absolute pixels
+ // still lands exactly where it did, at any render size.
+ const radiusFractionOf = (box: RenderRect | null | undefined, radius: number | undefined) => {
+ const shortSide = box ? Math.min(box.width, box.height) : 0;
+ return box && shortSide > 0 && radius != null ? radius / shortSide : null;
+ };
const resolvedLayoutOf = (layout: ReturnType<typeof layoutForScreenSize>) =>
layout
? {
screenRect: toFrameFractions(layout.screenRect),
webcamRect: layout.webcamRect ? toFrameFractions(layout.webcamRect) : null,
- screenRadius: layout.screenBorderRadius ?? null,
- webcamRadius: layout.webcamRect?.borderRadius ?? null,
+ screenRadiusFrac: radiusFractionOf(layout.screenRect, layout.screenBorderRadius),
+ webcamRadiusFrac: radiusFractionOf(layout.webcamRect, layout.webcamRect?.borderRadius),
webcamShape: layout.webcamRect?.maskShape ?? settings.webcamMaskShape,
screenCover: layout.screenCover ?? false,
}
@@ -588,16 +615,25 @@ export function buildSceneDescription(
),
webcamRect,
screenRect,
- screenRadius: computedLayout?.screenBorderRadius ?? null,
+ screenRadiusFrac: radiusFractionOf(
+ computedLayout?.screenRect,
+ computedLayout?.screenBorderRadius,
+ ),
screenCover: computedLayout?.screenCover ?? false,
- webcamRadius: computedLayout?.webcamRect?.borderRadius ?? null,
+ webcamRadiusFrac: radiusFractionOf(
+ computedLayout?.webcamRect,
+ computedLayout?.webcamRect?.borderRadius,
+ ),
layoutByClip,
},
effects: {
padding: settings.padding / 100,
blur: settings.showBlur,
shadow: settings.shadowIntensity,
- roundnessPx: settings.borderRadius,
+ // The slider is in output pixels; the contract is in fractions of the frame's
+ // short side. This division is the whole conversion — see `roundnessFrac`.
+ roundnessFrac:
+ settings.borderRadius / Math.max(1, Math.min(outputDims.width, outputDims.height)),
motionBlur: settings.motionBlurAmount,
},
cursor: {