Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(layout): fit the screen box to the crop, and resolve the layout per clip
Etienne Lescot373eef2df24b
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rsindex bd9e0e537..bca5d84b3 100644--- a/poc-d3d/src/compositor.rs+++ b/poc-d3d/src/compositor.rs@@ -96,14 +96,45 @@ fn screen_source_rect(fn cover_crop_uv(visible: [f32; 2], tex: [f32; 2], box_ar: f32) -> (f32, f32, f32, f32) {let (cam_w, cam_h) = (visible[0].max(1.0), visible[1].max(1.0));let (tex_w, tex_h) = (tex[0].max(1.0), tex[1].max(1.0));- let box_ar = if box_ar.is_finite() && box_ar > 0.0 { box_ar } else { cam_w / cam_h };- let (crop_w, crop_h) = if box_ar >= cam_w / cam_h {- (cam_w, cam_w / box_ar) // boîte plus large que la source → pleine largeur, on rogne en hauteur+ let full = [0.0, 0.0, cam_w / tex_w, cam_h / tex_h];+ let [u0, v0, u1, v1] = cover_uv_rect(full, tex, box_ar);+ (u0, v0, u1, v1)+}++/// Rétrécit un rect SOURCE déjà exprimé en UV (`[u0, v0, u1, v1]`) autour de son+/// centre pour qu'il porte le ratio `box_ar` une fois rapporté aux pixels de la+/// texture. C'est la forme générale de `object-fit: cover`, et LA primitive qui+/// garantit qu'une couche vidéo n'est jamais étirée.+///+/// Deux appelants, deux points d'entrée dans le rect :+/// - la **webcam** part de la frame visible entière (`cover_crop_uv`) ;+/// - l'**écran** part du rect déjà réduit par le crop utilisateur ET le zoom,+/// et n'applique ce cover que dans les layouts qui le demandent+/// (`Scene.layout.screen_cover` — les blocs side-by-side / top-bottom, où le+/// web fait exactement la même chose via `screenCover`).+///+/// Rogner APRÈS le crop et le zoom est ce qui rend l'opération composable : le+/// crop décide quoi montrer, le zoom où regarder, le cover comment habiller la+/// boîte. Chacun réduit le rect précédent, jamais ne le déforme.+///+/// Quand le rect a déjà le ratio de la boîte, il est renvoyé inchangé — donc+/// aucun placement déjà correct ne bouge.+fn cover_uv_rect(uv: [f32; 4], tex: [f32; 2], box_ar: f32) -> [f32; 4] {+ let (tex_w, tex_h) = (tex[0].max(1.0), tex[1].max(1.0));+ let (w_uv, h_uv) = ((uv[2] - uv[0]).max(1e-6), (uv[3] - uv[1]).max(1e-6));+ // ratio du rect courant, en PIXELS (les UV sont anisotropes dès que la+ // texture n'est pas carrée — d'où le passage par `tex`).+ let (w_px, h_px) = (w_uv * tex_w, h_uv * tex_h);+ let cur_ar = w_px / h_px;+ let box_ar = if box_ar.is_finite() && box_ar > 0.0 { box_ar } else { cur_ar };+ let (new_w_px, new_h_px) = if box_ar >= cur_ar {+ (w_px, w_px / box_ar) // boîte plus large → pleine largeur, on rogne en hauteur} else {- (cam_h * box_ar, cam_h) // boîte plus haute → pleine hauteur, on rogne en largeur+ (h_px * box_ar, h_px) // boîte plus haute → pleine hauteur, on rogne en largeur};- let (x0, y0) = ((cam_w - crop_w) * 0.5, (cam_h - crop_h) * 0.5);- (x0 / tex_w, y0 / tex_h, (x0 + crop_w) / tex_w, (y0 + crop_h) / tex_h)+ let (new_w, new_h) = (new_w_px / tex_w, new_h_px / tex_h);+ let (cx, cy) = (uv[0] + w_uv * 0.5, uv[1] + h_uv * 0.5);+ [cx - new_w * 0.5, cy - new_h * 0.5, cx + new_w * 0.5, cy + new_h * 0.5]}/// Constant buffer d'un calque (doit matcher `cbuffer Layer` du HLSL, 64 octets).@@ -1255,23 +1286,29 @@ impl Compositor {.as_ref().and_then(|s| s.layout.screen_rect).map(|r| [r.x, r.y, r.width, r.height]);- let (mut p, mut pp) = match (&scene_preset, app_webcam_rect) {- (Some(_preset), Some(wr)) => {- // webcam rect résolu côté app → on s'aligne strictement. Idem pour l'écran quand- // l'app le fournit ; sinon il reste plein cadre (le padding slider l'insètera- // ensuite dans `scale_frame`).- let mut fp = preset_placements(_preset);- fp.webcam.dst = wr;+ let (mut p, mut pp) = match &scene_preset {+ Some(preset) => {+ // Chaque rect résolu par l'app remplace INDÉPENDAMMENT sa contrepartie du+ // preset ; sinon celle du preset reste (le padding slider l'insèrera ensuite+ // dans `scale_frame`).+ //+ // Avant, ce match portait sur `app_webcam_rect` et le rect ÉCRAN n'était donc+ // honoré que si un rect webcam arrivait aussi. Un layout sans caméra gardait+ // l'écran plein cadre du preset — pendant que `fit_screen` (plus bas) coupait+ // quand même son fit au ratio du crop, puisqu'un `app_screen_rect` était bien+ // présent. Résultat : un clip recadré sans caméra était étiré, et aucune des+ // deux voies ne le rattrapait. Coupler l'écran à la présence de la caméra+ // n'avait aucune raison d'être — ce sont deux calques indépendants.+ let mut fp = preset_placements(preset);+ if let Some(wr) = app_webcam_rect {+ fp.webcam.dst = wr;+ }if let Some(sr) = app_screen_rect {fp.screen.dst = sr;}(fp, fp) // layout statique → vélocité nulle}- (Some(preset), None) => {- let fp = preset_placements(preset);- (fp, fp)- }- (None, _) => (timeline(frame, cfg), timeline(frame - 1.0, cfg)),+ None => (timeline(frame, cfg), timeline(frame - 1.0, cfg)),};let lp = *self.live_params.borrow();// Motion blur écran : quand la scène (contrat de l'app) est posée, c'est elle qui pilote@@ -1649,13 +1686,31 @@ impl Compositor {// `for_clip_window` conserve l'index pour distinguer plusieurs clips du même asset.// `active_crop` déjà résolu plus haut (utilisé pour dimensionner `s_dst`) — une seule// source de vérité pour ce lookup.- let [su0, sv0, su1, sv1] = screen_source_rect(u_max, v_max, active_crop, p.zoom, p.focus);+ let s_px = [s_dst[2] * self.rw(), s_dst[3] * self.rh()];+ // Layouts "bloc" (side-by-side / top-bottom) : la boîte écran est un SLOT au ratio+ // arbitraire, et le web y fait tenir l'image en `cover` (`computeCompositeLayout`+ // renvoie `screenCover: true`, honoré par `frameRenderer`). Le natif l'ignorait, donc+ // il étirait la source pour remplir le slot — visible dès que le clip est recadré,+ // puisque le crop éloigne encore le ratio de la source de celui du slot.+ //+ // Le cover s'applique APRÈS le crop et le zoom, sur leur rect résultant : le crop+ // décide quoi montrer, le zoom où regarder, le cover comment habiller la boîte.+ let cover_box_ar = scene_ref+ .as_ref()+ .and_then(|s| s.layout.screen_cover.then_some(s_px[0] / s_px[1].max(0.0001)));+ let cover = |uv: [f32; 4]| -> [f32; 4] {+ match cover_box_ar {+ Some(ar) => cover_uv_rect(uv, [stw as f32, sth as f32], ar),+ None => uv,+ }+ };+ let [su0, sv0, su1, sv1] =+ cover(screen_source_rect(u_max, v_max, active_crop, p.zoom, p.focus));let (hu, hv) = ((su1 - su0) * 0.5, (sv1 - sv0) * 0.5);// Le focus courant reste volontairement utilisé pour la frame précédente, comme avant.let [su0_p, sv0_p, su1_p, sv1_p] =- screen_source_rect(u_max, v_max, active_crop, pp.zoom, p.focus);+ 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);- let s_px = [s_dst[2] * self.rw(), s_dst[3] * self.rh()];if cfg.shadow {self.draw_shadow(s_dst, s_px, s_radius, 40.0, [0.0, 16.0], 0.45 * lp.shadow_scale);}@@ -2409,6 +2464,32 @@ mod tests {}}+ /// L'écran en layout bloc : le cover s'applique au rect DÉJÀ réduit par le crop+ /// et le zoom. Quel que soit ce rect de départ, ce qui atterrit dans la boîte a+ /// le ratio de la boîte — c'est ce qui empêche l'étirement.+ #[test]+ fn cover_uv_rect_gives_the_box_aspect_whatever_the_crop_and_zoom_left() {+ let tex = [2048.0, 1024.0];+ // rects source plausibles : plein cadre, bande verticale (crop portrait), zoom serré+ for &uv in &[+ [0.0, 0.0, 0.9375, 0.7031],+ [0.41, 0.04, 0.55, 0.67],+ [0.30, 0.20, 0.55, 0.45],+ ] {+ for &box_ar in &[0.4, 0.75, 1.0, 1.9, 3.2] {+ let out = cover_uv_rect(uv, tex, box_ar);+ let got = ((out[2] - out[0]) * tex[0]) / ((out[3] - out[1]) * tex[1]);+ assert!(+ (got - box_ar).abs() / box_ar < 1e-3,+ "uv {uv:?} boite {box_ar} -> ratio {got}",+ );+ // le cover RÉDUIT : il ne va jamais chercher des pixels hors du rect source+ assert!(out[0] >= uv[0] - 1e-6 && out[1] >= uv[1] - 1e-6, "deborde en haut/gauche");+ assert!(out[2] <= uv[2] + 1e-6 && out[3] <= uv[3] + 1e-6, "deborde en bas/droite");+ }+ }+ }+/// Propriété de sûreté : quand la boîte a DÉJÀ le ratio de la source (tous les/// placements qui étaient corrects — PiP par défaut, vertical-stack, et le/// center-crop carré de square/circle), la coupe est la frame entière. Lediff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rsindex 1609d36d3..21a871588 100644--- a/poc-d3d/src/scene.rs+++ b/poc-d3d/src/scene.rs@@ -68,6 +68,30 @@ pub struct SceneLayout {/// en bloc encadrent écran et caméra à l'identique). None → slider Roundness, comme avant.#[serde(default)]pub screen_radius: 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+ /// `frameRenderer` applique déjà côté web. Sans ce drapeau le natif étirait la source pour+ /// remplir le slot — d'autant plus visible sur un clip recadré, le crop éloignant encore le+ /// ratio de la source de celui du slot.+ ///+ /// `#[serde(default)]` : absent → `false` → comportement "contain" historique.+ #[serde(default)]+ pub screen_cover: bool,+ /// Un layout résolu PAR CLIP visible, aligné par index sur `Scene::clips` / `crop_by_clip`.+ /// Les champs scalaires ci-dessus sont ceux du PREMIER clip (repli pour un payload sans ce+ /// tableau, et valeur de départ tant qu'aucun clip n'est actif).+ ///+ /// Par clip parce que la FORME de la source écran l'est : un clip est un enregistrement+ /// d'écran + une caméra et un son optionnels, et rien n'impose à deux clips d'avoir été+ /// enregistrés à la même taille ni au même ratio. Le crop n'est qu'une manière de plus de+ /// faire varier cette forme — un 16:9 recadré en 9:16 doit se disposer exactement comme un+ /// enregistrement nativement en 9:16. À ne pas confondre avec le ratio de la SCÈNE, global.+ ///+ /// `for_clip_window` recopie l'entrée du clip composé dans les champs scalaires, si bien que+ /// `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@@ -82,6 +106,24 @@ pub struct SceneLayout {pub webcam_radius: 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`.+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ResolvedClipLayout {+ pub screen_rect: SceneRect,+ #[serde(default)]+ pub webcam_rect: Option<SceneRect>,+ #[serde(default)]+ pub screen_radius: Option<f32>,+ #[serde(default)]+ pub webcam_radius: Option<f32>,+ #[serde(default)]+ pub webcam_shape: Option<String>,+ #[serde(default)]+ pub screen_cover: bool,+}+/// Rect normalisé 0..1 du cadre de sortie : x, y en haut-gauche ; width, height.#[derive(Debug, Clone, Copy, Deserialize)]#[serde(rename_all = "camelCase")]@@ -262,6 +304,20 @@ impl Scene {scene.camera_fullscreen_regions.retain(|region| {belongs(region.clip_index, region.start_sec, region.end_sec)});+ // Le layout dépend de la FORME de la source du clip (dimensions natives × crop), qui+ // varie d'un clip à l'autre. On installe donc celui du clip composé dans les champs+ // scalaires : `compose_frame` continue de lire un seul `layout`, sans jamais avoir à+ // savoir qu'il en existe un par clip. Absent (payload ancien) → on garde les scalaires.+ 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_cover = l.screen_cover;+ if let Some(shape) = l.webcam_shape {+ scene.layout.webcam_shape = shape;+ }+ }scene.active_clip_index = clip_index;scene}diff --git a/poc-d3d/tests/output_geometry_golden.rs b/poc-d3d/tests/output_geometry_golden.rsindex 4ca9d2970..d4dcca2d5 100644--- a/poc-d3d/tests/output_geometry_golden.rs+++ b/poc-d3d/tests/output_geometry_golden.rs@@ -241,3 +241,71 @@ fn golden_side_by_side_webcam_is_not_stretched() {write_ppm(&path, &rgba, w, h).expect("ecrire le ppm");println!("side-by-side ecrit: {}", path.display());}++/// Rend un clip RECADRÉ avec le `screenRect` que l'app résout — le chemin qui a+/// régressé. `compositor.rs::fit_screen` consomme ce rect TEL QUEL (il saute son+/// propre fit au ratio du crop, le rect étant censé y être déjà) : si le rect ne+/// porte pas le ratio du crop, la vidéo est étirée pour remplir une boîte mal+/// formée, sans rien en aval pour rattraper.+///+/// `SCREEN_RECT_AR` doit rester le ratio du crop (0.30*1920 / 0.89*1080 ≈ 0.599).+/// Le PPM permet de vérifier à l'œil que le texte n'est pas étiré.+#[test]+fn golden_cropped_clip_is_not_stretched() {+ let (screen, webcam) = match (+ std::env::var("OPENSCREEN_GOLDEN_SCREEN"),+ std::env::var("OPENSCREEN_GOLDEN_WEBCAM"),+ ) {+ (Ok(s), Ok(w)) => (s, w),+ _ => {+ println!("SKIP: definir OPENSCREEN_GOLDEN_SCREEN / _WEBCAM");+ return;+ }+ };+ let out_dir = std::env::var("OPENSCREEN_GOLDEN_OUT")+ .map(std::path::PathBuf::from)+ .unwrap_or_else(|_| std::path::PathBuf::from("target/golden"));+ std::fs::create_dir_all(&out_dir).expect("dossier de sortie");++ let (w, h) = (1920u32, 1080u32);+ let (s, c) = (screen.replace('\\', "/"), webcam.replace('\\', "/"));+ // Crop du rapport utilisateur : bande verticale 30% x 89% d'une source 16:9.+ let (crop_w, crop_h) = (0.30f32, 0.89f32);+ let crop_ar = (1920.0 * crop_w) / (1080.0 * crop_h); // ≈ 0.599+ // Le rect que l'app DOIT produire : contain de ce ratio dans le cadre de sortie.+ let rect_h = 0.94f32;+ let rect_w = rect_h * crop_ar * (h as f32 / w as f32);+ let scene_json = format!(+ r##"{{+ "clips": [{{"screenPath":"{s}","webcamPath":"{c}","sourceStartSec":0,"sourceEndSec":30,"webcamOffsetSec":0,"hasAudio":true}}],+ "layout": {{"preset":"no-webcam","webcamSize":1.0,"webcamShape":"rectangle","webcamMirror":false,+ "screenRect":{{"x":{sx},"y":{sy},"width":{rect_w},"height":{rect_h}}},"webcamReactiveZoom":false}},+ "effects": {{"padding":0.0,"blur":true,"shadow":1.0,"roundnessPx":24,"motionBlur":0.0}},+ "background": {{"kind":"gradient","angleDeg":135,"stops":["#1e3a5f","#0d1b2a"]}},+ "zoomRegions": [], "speedRegions": [],+ "cursor": {{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"}},+ "cropByClip": [{{"x":0.44,"y":0.06,"width":{crop_w},"height":{crop_h}}}],+ "output": {{"width":{w},"height":{h},"fps":null}}+ }}"##,+ sx = 0.5 - rect_w * 0.5,+ sy = 0.5 - rect_h * 0.5,+ );++ let mut cfg = config::all().pop().expect("au moins une config");+ cfg.zoom = false;+ cfg.layout_anim = false;++ let gpu = Gpu::create(false).expect("device d3d11");+ let comp = Compositor::new_sized(&gpu, w, h).expect("compositor");+ comp.set_scene(Some(Scene::from_json(&scene_json).expect("scene valide")));+ comp.clear_cursor();++ let rgba = unsafe {+ let mut player = Player::open(&screen, &webcam, &gpu).expect("ouvrir les sources");+ player.present_frame(&comp, &cfg, AT_SEC).expect("composer");+ comp.readback_resized(w, h).expect("readback")+ };+ let path = out_dir.join("cropped-clip.ppm");+ write_ppm(&path, &rgba, w, h).expect("ecrire le ppm");+ println!("crop ar={crop_ar:.3} rect={rect_w:.3}x{rect_h:.3} -> {}", path.display());+}diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex a51b0e597..7dd5d75d8 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -1014,3 +1014,123 @@ describe("buildSceneDescription.output", () => {expect(output.height).toBe(1920);});});++// --- screenRect vs crop ------------------------------------------------------++describe("buildSceneDescription.layout.screenRect", () => {+ // `compositor.rs` consumes `layout.screenRect` AS-IS — its `fit_screen` closure skips+ // its own crop fit precisely because the rect is documented as "already at the crop's+ // aspect ratio". So the rect's aspect IS the contract: get it wrong and the video is+ // stretched to fill a mis-shaped box, with nothing downstream to catch it.+ const cropped = (crop: { x: number; y: number; width: number; height: number } | undefined) => {+ const asset = makeAsset({+ id: "a",+ originalPath: "/screen.mp4",+ video: { width: 1920, height: 1080 },+ });+ const clip = makeClip({+ id: "c1",+ assetId: "a",+ sourceStartSec: 0,+ sourceEndSec: 4,+ timelineStartSec: 0,+ timelineEndSec: 4,+ ...(crop ? { cropRegion: crop } : {}),+ });+ const scene = buildSceneDescription(makeDoc({ assets: [asset], clips: [clip] }));+ const r = scene.layout.screenRect;+ if (!r) throw new Error("screenRect absent");+ // fractions of the output frame -> pixels, to compare a real aspect+ return (r.width * scene.output.width) / (r.height * scene.output.height);+ };++ // `computeCompositeLayout` works in integer pixels, so an extreme aspect quantizes+ // by a fraction of a percent. A RELATIVE tolerance is the meaningful check here:+ // the failure this guards against is off by 2-3x, not by 0.1%.+ const expectAspect = (got: number, want: number) =>+ expect(Math.abs(got - want) / want).toBeLessThan(0.01);++ it("matches the cropped source aspect, not the full frame's", () => {+ // The reported regression: a tall narrow crop (30% x 89% of a 16:9 source) was+ // handed a 16:9 box, so the strip was stretched ~2.8x horizontally.+ const crop = { x: 0.44, y: 0.06, width: 0.3, height: 0.89 };+ expectAspect(cropped(crop), (1920 * crop.width) / (1080 * crop.height));+ });++ it("keeps the full source aspect when the clip is not cropped", () => {+ expectAspect(cropped(undefined), 1920 / 1080);+ });++ it("follows a wide letterbox crop too", () => {+ const crop = { x: 0, y: 0.3, width: 1, height: 0.4 };+ expectAspect(cropped(crop), (1920 * 1) / (1080 * 0.4));+ });+});++// --- layoutByClip : la forme de la source est PAR CLIP -----------------------++describe("buildSceneDescription.layout.layoutByClip", () => {+ // Un clip est un enregistrement d'ecran + camera/son optionnels : rien n'impose a deux+ // clips la meme taille ni le meme ratio. Le crop n'est qu'une maniere de plus de faire+ // varier cette forme. Un layout unique pour toute la scene ne peut donc pas etre juste —+ // c'est ce qui etirait un clip croppe place apres un clip non croppe (cas rapporte).+ const aspectOf = (r: { width: number; height: number }, out: { width: number; height: number }) =>+ (r.width * out.width) / (r.height * out.height);++ const twoClipDoc = () => {+ const asset = makeAsset({+ id: "a",+ originalPath: "/screen.mp4",+ video: { width: 1920, height: 1080 },+ });+ const plain = makeClip({+ id: "c1",+ assetId: "a",+ sourceStartSec: 0,+ sourceEndSec: 4,+ timelineStartSec: 0,+ timelineEndSec: 4,+ });+ const cropped = makeClip({+ id: "c2",+ assetId: "a",+ sourceStartSec: 4,+ sourceEndSec: 8,+ timelineStartSec: 4,+ timelineEndSec: 8,+ cropRegion: { x: 0.45, y: 0.11, width: 0.31, height: 0.89 },+ });+ return makeDoc({ assets: [asset], clips: [plain, cropped] });+ };++ it("gives each clip a layout at ITS OWN source aspect", () => {+ const scene = buildSceneDescription(twoClipDoc());+ const byClip = scene.layout.layoutByClip;+ if (!byClip) throw new Error("layoutByClip absent");+ expect(byClip).toHaveLength(2);++ const plain = byClip[0];+ const cropped = byClip[1];+ if (!plain || !cropped) throw new Error("entree manquante");++ // clip 0 : pas de crop -> ratio de la source+ expect(aspectOf(plain.screenRect, scene.output)).toBeCloseTo(1920 / 1080, 1);+ // clip 1 : croppe -> ratio du crop, PAS celui du clip 0+ const want = (1920 * 0.31) / (1080 * 0.89);+ const got = aspectOf(cropped.screenRect, scene.output);+ expect(Math.abs(got - want) / want).toBeLessThan(0.01);+ });++ it("is index-aligned with clips and cropByClip", () => {+ const scene = buildSceneDescription(twoClipDoc());+ expect(scene.layout.layoutByClip).toHaveLength(scene.clips.length);+ expect(scene.cropByClip).toHaveLength(scene.clips.length);+ expect(scene.cropByClip[0]).toBeNull();+ expect(scene.cropByClip[1]).not.toBeNull();+ });++ it("keeps the scalar layout fields as the first clip's entry", () => {+ const scene = buildSceneDescription(twoClipDoc());+ expect(scene.layout.screenRect).toEqual(scene.layout.layoutByClip?.[0]?.screenRect);+ });+});diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex bcfa631b5..acf3fd516 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -145,6 +145,30 @@ export interface SceneLayout {* 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+ * slot. This is `computeCompositeLayout(...).screenCover`, which `frameRenderer` already+ * honours on the web path; shipping it here is what lets the native compositor agree.+ * Without it native stretched the source to fill the slot — most visible on a cropped+ * clip, the crop pushing the source aspect further from the slot's.+ */+ screenCover?: boolean;+ /**+ * One resolved layout per visible clip, index-aligned with `SceneDescription.clips`+ * and `cropByClip`. The scalar fields above are the FIRST clip's entry (fallback for+ * older payloads and the value native uses before a clip is active).+ *+ * Per clip because the screen source's SHAPE is per clip — a clip is a screen+ * recording plus an optional camera and audio, and nothing forces two clips to share+ * a recording size or ratio. Cropping is one more way that shape varies: a 16:9+ * recording cropped to 9:16 must lay out exactly like one recorded natively in 9:16.+ * Distinct from the scene's aspect ratio, which is global.+ *+ * Resolving one layout for the whole scene was therefore already wrong for a document+ * mixing recording resolutions; cropping only made it reachable in a single document.+ */+ 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@@ -160,6 +184,16 @@ export interface SceneLayout {webcamRadius?: number | null;}+/** The shape-dependent half of a layout, resolved for one clip. See `layoutByClip`. */+export interface ResolvedClipLayout {+ screenRect: SceneRect;+ webcamRect: SceneRect | null;+ screenRadius: number | null;+ webcamRadius: number | null;+ webcamShape: "rectangle" | "circle" | "square" | "rounded";+ screenCover: boolean;+}+/** Frame-styling effects, from the editor settings. */export interface SceneEffects {/** 0..1 extra inset of the screen (padding). */@@ -461,29 +495,74 @@ export function buildSceneDescription(// `webcamRect` verbatim (it only scale_frame's the SCREEN by padding), so an// unpadded rect here would leave the camera behind while the screen moved.const paddingFit = 1 - (Math.min(100, Math.max(0, settings.padding)) / 100) * 0.4;- const computedLayout = computeCompositeLayout({- canvasSize: outputDims,- maxContentSize: {- width: Math.round(outputDims.width * paddingFit),- height: Math.round(outputDims.height * paddingFit),- },- screenSize: { width: 1920, height: 1080 },- webcamSize:- settings.webcamLayoutPreset === "no-webcam"- ? null- : (webcamSourceSize ?? { width: 960, height: 720 }),- layoutPreset: settings.webcamLayoutPreset,- webcamSizePreset: settings.webcamSizePreset,- webcamPosition:- settings.webcamLayoutPreset === "picture-in-picture" ? settings.webcamPosition : null,- webcamMaskShape: settings.webcamMaskShape,- });+ /**+ * The screen source SHAPE of a clip = its recording's own dimensions × its crop.+ *+ * Both halves vary per clip and always have: a clip is a screen recording + an+ * optional camera + optional audio, and nothing forces two clips to have been+ * recorded at the same size or ratio. Cropping is simply one more way that shape+ * varies — a 16:9 recording cropped to 9:16 must lay out exactly like a clip+ * recorded natively in 9:16. This is NOT the scene's aspect ratio, which is global+ * (`outputDims`); it is per clip.+ *+ * So the layout has to be resolved per clip. Resolving it once for the whole scene+ * was already wrong for a document mixing recording resolutions — the crop only+ * made the existing defect visible, by letting one document hold two shapes.+ */+ const screenSourceSizeOf = (clip: AxcutClip, index: number) => {+ const video = assetById.get(clip.assetId)?.video;+ const crop = cropByClip[index]; // index-aligned; null = identity crop+ return {+ width: Math.max(1, Math.round((video?.width || 1920) * (crop?.width ?? 1))),+ height: Math.max(1, Math.round((video?.height || 1080) * (crop?.height ?? 1))),+ };+ };+ const layoutForScreenSize = (screenSize: { width: number; height: number }) =>+ computeCompositeLayout({+ canvasSize: outputDims,+ maxContentSize: {+ width: Math.round(outputDims.width * paddingFit),+ height: Math.round(outputDims.height * paddingFit),+ },+ screenSize,+ webcamSize:+ settings.webcamLayoutPreset === "no-webcam"+ ? null+ : (webcamSourceSize ?? { width: 960, height: 720 }),+ layoutPreset: settings.webcamLayoutPreset,+ webcamSizePreset: settings.webcamSizePreset,+ webcamPosition:+ settings.webcamLayoutPreset === "picture-in-picture" ? settings.webcamPosition : null,+ webcamMaskShape: settings.webcamMaskShape,+ });const toFrameFractions = (r: RenderRect) => ({x: r.x / outputDims.width,y: r.y / outputDims.height,width: r.width / outputDims.width,height: r.height / outputDims.height,});+ 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,+ webcamShape: layout.webcamRect?.maskShape ?? settings.webcamMaskShape,+ screenCover: layout.screenCover ?? false,+ }+ : null;+ // One resolved layout per visible clip, index-aligned with `clips` / `cropByClip`.+ // `for_clip_window` (Rust) selects the entry for the clip being composed, so the+ // draw path keeps reading a single `layout` and needs no per-clip branch of its own.+ const layoutByClip = visibleClips.map((clip, index) =>+ resolvedLayoutOf(layoutForScreenSize(screenSourceSizeOf(clip, index))),+ );+ // Scalar fields stay the FIRST clip's layout: they are the fallback for a payload+ // without `layoutByClip`, and the value native starts from before any clip is active.+ const computedLayout = visibleClips[0]+ ? layoutForScreenSize(screenSourceSizeOf(visibleClips[0], 0))+ : null;const webcamRect = computedLayout?.webcamRect? toFrameFractions(computedLayout.webcamRect): null;@@ -510,7 +589,9 @@ export function buildSceneDescription(webcamRect,screenRect,screenRadius: computedLayout?.screenBorderRadius ?? null,+ screenCover: computedLayout?.screenCover ?? false,webcamRadius: computedLayout?.webcamRect?.borderRadius ?? null,+ layoutByClip,},effects: {padding: settings.padding / 100,