Skip to content

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

feat(annotations): render annotations in the native compositor — arrows, masks, images, text

Etienne Lescotf4c5a19d4d01
diff --git a/poc-d3d/Cargo.toml b/poc-d3d/Cargo.toml
index f44b5ae56..a1d97d83a 100644
--- a/poc-d3d/Cargo.toml
+++ b/poc-d3d/Cargo.toml
@@ -47,6 +47,10 @@ features = [
"Win32_Graphics_Direct3D11",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
+ "Foundation_Numerics", # requis par les méthodes D2D à brosse (CreateSolidColorBrush)
+ "Win32_Graphics_Direct2D", # cible de rendu D2D sur surface DXGI (texte, text.rs)
+ "Win32_Graphics_Direct2D_Common", # D2D1_COLOR_F / PIXEL_FORMAT
+ "Win32_Graphics_DirectWrite", # mise en page + rastérisation du texte
"Win32_Graphics_Gdi", # brosses/police GUI de la preview (app.rs)
"Win32_System_Performance", # QueryPerformanceCounter / Frequency (§10)
"Win32_System_LibraryLoader", # GetModuleHandleW (hInstance, app.rs)
diff --git a/poc-d3d/src/compositor.rs b/poc-d3d/src/compositor.rs
index cc32e0ec7..460d21cda 100644
--- a/poc-d3d/src/compositor.rs
+++ b/poc-d3d/src/compositor.rs
@@ -23,6 +23,44 @@ pub const OUT_H: u32 = 1080;
/// Parse une couleur "#rgb" / "#rrggbb" (sRGB, comme les wallpapers web) → [r,g,b,a] 0..1.
/// Les couleurs plates suivent le même chemin que `bg_color` (pas de linéarisation).
+/// Décode une data URL base64 (`data:image/png;base64,AAAA…`) en octets. `None` si ce n'en est
+/// pas une — l'appelant retombe alors sur une lecture disque.
+///
+/// Écrit à la main plutôt qu'avec une dépendance : c'est le seul usage de base64 du projet, et le
+/// décodeur tient en quinze lignes vérifiables. Les caractères hors alphabet (retours à la ligne
+/// d'un URI replié, `=` de padding) sont ignorés, ce qui rend la fonction tolérante sans être
+/// laxiste : un caractère invalide ne peut pas décaler le flux, il est simplement absent.
+fn decode_data_uri(uri: &str) -> Option<Vec<u8>> {
+ let rest = uri.strip_prefix("data:")?;
+ let comma = rest.find(',')?;
+ if !rest[..comma].contains("base64") {
+ return None;
+ }
+ let payload = &rest[comma + 1..];
+ let sextet = |c: u8| -> Option<u32> {
+ match c {
+ b'A'..=b'Z' => Some((c - b'A') as u32),
+ b'a'..=b'z' => Some((c - b'a') as u32 + 26),
+ b'0'..=b'9' => Some((c - b'0') as u32 + 52),
+ b'+' => Some(62),
+ b'/' => Some(63),
+ _ => None,
+ }
+ };
+ let mut out = Vec::with_capacity(payload.len() / 4 * 3);
+ let (mut acc, mut bits) = (0u32, 0u32);
+ for byte in payload.bytes() {
+ let Some(v) = sextet(byte) else { continue };
+ acc = (acc << 6) | v;
+ bits += 6;
+ if bits >= 8 {
+ bits -= 8;
+ out.push((acc >> bits) as u8);
+ }
+ }
+ Some(out)
+}
+
fn parse_hex(s: &str) -> Option<[f32; 4]> {
let h = s.trim().trim_start_matches('#');
let (r, g, b) = match h.len() {
@@ -269,6 +307,12 @@ pub struct Compositor {
q_srv: ID3D11ShaderResourceView,
e_rtv: ID3D11RenderTargetView,
e_srv: ID3D11ShaderResourceView,
+ /// Copie pleine réso de l'image composée, pour les annotations de type flou : on ne peut pas
+ /// échantillonner le render target sur lequel on dessine, donc on le recopie ici d'abord.
+ /// Distincte de `accum` à dessein — `accum` sert au motion blur, qui appelle `compose_frame`
+ /// plusieurs fois par frame et dont l'accumulation serait écrasée.
+ ann_copy: ID3D11Texture2D,
+ ann_copy_srv: ID3D11ShaderResourceView,
// accumulateur pour le flou de mouvement (supersampling temporel)
accum: ID3D11Texture2D,
accum_rtv: ID3D11RenderTargetView,
@@ -294,6 +338,18 @@ pub struct Compositor {
/// Scène pilotée par l'app (contrat) : quand présente, remplace le layout fixture de
/// `timeline()`. Voir `scene.rs` / `SceneDescription` (TS).
scene: RefCell<Option<Scene>>,
+ /// Rastériseur de texte (Direct2D/DirectWrite). `Option` parce qu'un échec d'init des
+ /// fabriques ne doit pas empêcher tout le compositeur de tourner : sans lui, les annotations
+ /// texte sont simplement absentes, comme avant.
+ text_raster: Option<crate::text::TextRasterizer>,
+ /// Cache des textures de texte, indexé sur l'ID d'annotation. La `u64` est la clé de contenu
+ /// (`TextSpec::cache_key`) : on ne re-rastérise que si elle change, donc jamais pour un
+ /// déplacement ou une animation.
+ text_cache: RefCell<HashMap<String, (ID3D11ShaderResourceView, u64)>>,
+ /// Cache des textures d'annotation image, indexé sur l'ID d'annotation (SRV, w, h, longueur
+ /// de la source). Séparé de `img_cache` : les wallpapers sont des chemins disque, ces images
+ /// des data URL de plusieurs Mo qu'on ne veut pas utiliser comme clés de hachage.
+ ann_img_cache: RefCell<HashMap<String, (ID3D11ShaderResourceView, u32, u32, usize)>>,
/// Cache des textures wallpaper image (clé = chemin absolu) : décodage/upload une seule
/// fois, puis réutilisées par frame. (SRV, largeur, hauteur).
img_cache: RefCell<HashMap<String, (ID3D11ShaderResourceView, u32, u32)>>,
@@ -812,6 +868,22 @@ impl Compositor {
let mut accum_srv: Option<ID3D11ShaderResourceView> = None;
dev.CreateShaderResourceView(&accum, None, Some(&mut accum_srv))?;
+ // Copie de travail des annotations flou. Chaîne de mips COMPLÈTE (`MipLevels: 0`) : c'est
+ // elle qui fournit le flou. Échantillonner un niveau plus bas donne un vrai lissage pour
+ // n'importe quel rayon à coût constant, là où un noyau de quelques taps espacés produit
+ // des copies fantômes au lieu d'un flou.
+ let ann_desc = D3D11_TEXTURE2D_DESC {
+ MipLevels: 0,
+ BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,
+ MiscFlags: D3D11_RESOURCE_MISC_GENERATE_MIPS.0 as u32,
+ ..ad
+ };
+ let mut ann_copy: Option<ID3D11Texture2D> = None;
+ dev.CreateTexture2D(&ann_desc, None, Some(&mut ann_copy))?;
+ let ann_copy = ann_copy.unwrap();
+ let mut ann_copy_srv: Option<ID3D11ShaderResourceView> = None;
+ dev.CreateShaderResourceView(&ann_copy, None, Some(&mut ann_copy_srv))?;
+
let mut bla = D3D11_BLEND_DESC::default();
bla.RenderTarget[0] = D3D11_RENDER_TARGET_BLEND_DESC {
BlendEnable: true.into(),
@@ -857,6 +929,8 @@ impl Compositor {
q_srv,
e_rtv,
e_srv,
+ ann_copy,
+ ann_copy_srv: ann_copy_srv.unwrap(),
accum,
accum_rtv: accum_rtv.unwrap(),
accum_srv: accum_srv.unwrap(),
@@ -867,6 +941,15 @@ impl Compositor {
srv_cache: RefCell::new(HashMap::new()),
live_params: RefCell::new(LiveParams::default()),
scene: RefCell::new(None),
+ text_raster: match crate::text::TextRasterizer::new() {
+ Ok(r) => Some(r),
+ Err(e) => {
+ eprintln!("[texte] init Direct2D/DirectWrite impossible, annotations texte désactivées: {e}");
+ None
+ }
+ },
+ text_cache: RefCell::new(HashMap::new()),
+ ann_img_cache: RefCell::new(HashMap::new()),
img_cache: RefCell::new(HashMap::new()),
render_size: Cell::new((out_w, out_h)),
resize_target: RefCell::new(None),
@@ -1110,9 +1193,18 @@ impl Compositor {
/// Décode un fichier image (jpg/png) → texture RGBA immuable + SRV.
unsafe fn load_image_srv(&self, path: &str) -> Result<(ID3D11ShaderResourceView, u32, u32)> {
- let img = image::open(path)
- .map_err(|e| anyhow::anyhow!("wallpaper {}: {}", path, e))?
- .to_rgba8();
+ // Les annotations image stockent une data URL (cf. `types.ts` : « Separate storage for
+ // image data URL »), pas un chemin : on décode alors depuis la mémoire. Les wallpapers
+ // continuent de passer par le disque.
+ let img = if let Some(bytes) = decode_data_uri(path) {
+ image::load_from_memory(&bytes)
+ .map_err(|e| anyhow::anyhow!("data URI image ({} octets): {}", bytes.len(), e))?
+ .to_rgba8()
+ } else {
+ image::open(path)
+ .map_err(|e| anyhow::anyhow!("wallpaper {}: {}", path, e))?
+ .to_rgba8()
+ };
let (w, h) = (img.width(), img.height());
let pixels = img.into_raw();
let td = D3D11_TEXTURE2D_DESC {
@@ -1969,9 +2061,242 @@ impl Compositor {
&wuv,
);
}
+
+ // --- annotations : calque le plus haut, comme dans le DOM de la preview (le calque y est
+ // monté après la vidéo). Ancrées sur `s_dst`, le rect ÉCRAN — c'est le conteneur que reçoit
+ // l'overlay web (`layout.screenRect`) — et volontairement pas sur le rect de sortie, ni
+ // sujettes au crop de zoom : dans la preview l'overlay est frère de l'élément qui porte la
+ // transform, donc les annotations restent en place pendant que le contenu zoome dessous.
+ // `source_t`, la même base de temps que les zoom/speed regions : le temps SOURCE du clip,
+ // pas le compteur de frames. C'est ce qui garde une annotation alignée sur l'image quand
+ // une speed region répète ou saute des frames.
+ self.draw_annotations(scene_ref.as_ref(), source_t, s_dst);
Ok(())
}
+ /// Dessine les annotations visibles à `t`. `screen_dst` = rect écran en fractions de sortie.
+ ///
+ /// Seule la « figure » (flèche) est rendue à ce stade ; texte, image et flou suivront. Les
+ /// types non gérés sont ignorés silencieusement plutôt que dessinés de travers : mieux vaut
+ /// l'absence connue qu'un placeholder qui ferait croire à un bug de style.
+ unsafe fn draw_annotations(&self, scene: Option<&Scene>, t: f32, screen_dst: [f32; 4]) {
+ let Some(scene) = scene else { return };
+ if scene.annotations.is_empty() {
+ return;
+ }
+ let visible = |a: &crate::scene::SceneAnnotation| {
+ t >= a.start_sec as f32 && t < a.end_sec as f32
+ };
+ // Une seule recopie du render target pour TOUTES les annotations flou de la frame — leur
+ // lecture doit voir l'image composée sans les flous eux-mêmes, sinon deux zones qui se
+ // recouvrent s'échantillonneraient l'une l'autre selon l'ordre de dessin.
+ let needs_copy = scene
+ .annotations
+ .iter()
+ .any(|a| visible(a) && a.kind == "blur" && a.blur.is_some());
+ if needs_copy {
+ // `CopySubresourceRegion` et non `CopyResource` : les deux textures n'ont pas le même
+ // nombre de niveaux, on ne remplit que le mip 0 puis on laisse le GPU dériver le reste.
+ self.ctx.CopySubresourceRegion(&self.ann_copy, 0, 0, 0, 0, &self.rt, 0, None);
+ self.ctx.GenerateMips(&self.ann_copy_srv);
+ }
+ // La liste arrive déjà triée par zIndex croissant côté app, donc l'ordre d'itération EST
+ // l'ordre de peinture — pas de tri par frame.
+ for annotation in &scene.annotations {
+ if !visible(annotation) {
+ continue;
+ }
+ let dst = [
+ screen_dst[0] + annotation.x * screen_dst[2],
+ screen_dst[1] + annotation.y * screen_dst[3],
+ annotation.w * screen_dst[2],
+ annotation.h * screen_dst[3],
+ ];
+ let quad_px = [dst[2] * self.rw(), dst[3] * self.rh()];
+ if quad_px[0] <= 0.0 || quad_px[1] <= 0.0 {
+ continue;
+ }
+ match annotation.kind.as_str() {
+ "figure" => {
+ let Some(figure) = annotation.figure.as_ref() else { continue };
+ let (segments, half_stroke) = crate::regions::arrow_local_geometry(
+ &figure.direction,
+ figure.stroke_width,
+ quad_px,
+ );
+ let rgba = parse_hex(&figure.color).unwrap_or([1.0, 1.0, 1.0, 1.0]);
+ self.draw_solid(&LayerCB {
+ dst,
+ quad_px,
+ mode: 9.0,
+ color: rgba,
+ fx: segments[0],
+ src_prev: segments[1],
+ dst_prev: segments[2],
+ mb: [1.0, half_stroke, 0.0, 0.0],
+ ..Default::default()
+ });
+ }
+ "blur" => {
+ let Some(blur) = annotation.blur.as_ref() else { continue };
+ // Le masque en tracé libre demande une liste de points côté GPU (buffer
+ // structuré), pas encore faite : on masque alors la BOÎTE ENGLOBANTE.
+ //
+ // Ce choix est délibéré et asymétrique. Ne rien dessiner laisserait passer en
+ // clair, dans le fichier exporté, ce que l'utilisateur a explicitement désigné
+ // comme à cacher — un masque de confidentialité qui ne masque pas est pire que
+ // pas de masque, parce qu'il donne confiance à tort. Sur-flouter une marge
+ // autour de la zone ne trahit personne.
+ let freehand_fallback = blur.shape == "freehand";
+ let is_blur = if blur.style == "blur" { 1.0 } else { 0.0 };
+ // `intensity` pilote le rayon du flou, `block_size` la grille de mosaïque —
+ // deux réglages distincts côté app, un seul paramètre ici selon le style.
+ let amount = if is_blur > 0.5 { blur.intensity } else { blur.block_size };
+ // Le repli du tracé libre passe par le rectangle, pas l'ovale : un ovale
+ // inscrit dans la boîte englobante en retirerait les coins, donc une partie de
+ // ce que l'utilisateur a couvert.
+ let is_oval = if blur.shape == "oval" && !freehand_fallback { 1.0 } else { 0.0 };
+ // La teinte n'a de sens qu'en mosaïque : elle sert à marquer visiblement une
+ // zone caviardée. Un flou teinté ne ressemblerait plus à un flou.
+ let tinted = if is_blur > 0.5 { 0.0 } else { 1.0 };
+ let tint = if blur.color == "black" {
+ [0.0, 0.0, 0.0, 1.0]
+ } else {
+ [1.0, 1.0, 1.0, 1.0]
+ };
+ self.ctx.PSSetShaderResources(2, Some(&[Some(self.ann_copy_srv.clone())]));
+ self.draw_solid(&LayerCB {
+ dst,
+ quad_px,
+ mode: 10.0,
+ color: tint,
+ fx: [is_blur, amount.max(1.0), is_oval, tinted],
+ ..Default::default()
+ });
+ }
+ "image" => {
+ let Some(src) = annotation.image_path.as_ref() else { continue };
+ if src.is_empty() {
+ continue;
+ }
+ // Cache indexé sur l'ID de l'annotation, pas sur la data URL : celle-ci pèse
+ // souvent des mégaoctets, et la prendre comme clé de HashMap la ferait hacher
+ // à chaque frame. La longueur, stockée à côté, sert de garde-fou quand
+ // l'utilisateur change l'image (une nouvelle image de longueur identique au
+ // bit près serait manquée jusqu'au rechargement — coût accepté en connaissance).
+ let key = annotation.id.clone();
+ let cached = {
+ let cache = self.ann_img_cache.borrow();
+ cache.get(&key).filter(|(_, _, _, len)| *len == src.len()).cloned()
+ };
+ let Some((srv, iw, ih, _)) = cached.or_else(|| {
+ match self.load_image_srv(src) {
+ Ok((srv, w, h)) => {
+ let entry = (srv, w, h, src.len());
+ self.ann_img_cache.borrow_mut().insert(key, entry.clone());
+ Some(entry)
+ }
+ Err(e) => {
+ eprintln!("[annotation image] {}: {e}", annotation.id);
+ None
+ }
+ }
+ }) else {
+ continue;
+ };
+ if iw == 0 || ih == 0 {
+ continue;
+ }
+ // `object-contain`, comme la preview : mise à l'échelle uniforme pour tenir
+ // DANS la boîte, centrée. On rétrécit le rect de destination au ratio de
+ // l'image plutôt que de recadrer la source, ce qui donne exactement ça.
+ let box_aspect = quad_px[0] / quad_px[1];
+ let img_aspect = iw as f32 / ih as f32;
+ let (fit_w, fit_h) = if img_aspect > box_aspect {
+ (dst[2], dst[3] * (box_aspect / img_aspect))
+ } else {
+ (dst[2] * (img_aspect / box_aspect), dst[3])
+ };
+ let fit = [
+ dst[0] + (dst[2] - fit_w) * 0.5,
+ dst[1] + (dst[3] - fit_h) * 0.5,
+ fit_w,
+ fit_h,
+ ];
+ self.ctx.PSSetShaderResources(2, Some(&[Some(srv)]));
+ self.draw_solid(&LayerCB {
+ dst: fit,
+ src: [0.0, 0.0, 1.0, 1.0],
+ quad_px: [fit_w * self.rw(), fit_h * self.rh()],
+ // mode 7 = sprite RGBA avec alpha, déjà utilisé par les thèmes de curseur :
+ // exactement ce qu'il faut ici, donc aucun shader de plus. `fx` est son
+ // rect de clip — plein cadre, pour ne rien découper.
+ mode: 7.0,
+ color: [1.0, 1.0, 1.0, 1.0],
+ fx: [0.0, 0.0, 1.0, 1.0],
+ ..Default::default()
+ });
+ }
+ "text" => {
+ let Some(text) = annotation.text.as_ref() else { continue };
+ let Some(raster) = self.text_raster.as_ref() else { continue };
+ if text.content.trim().is_empty() {
+ continue;
+ }
+ // `font_size_rel` est une fraction de la HAUTEUR DU RECT ÉCRAN (cf. le contrat
+ // et `annotationScale.ts`) : on la ramène en pixels de sortie ici, avec le même
+ // produit que la preview applique contre sa propre boîte.
+ let screen_h_px = screen_dst[3] * self.rh();
+ let spec = crate::text::TextSpec {
+ content: text.content.clone(),
+ color: parse_hex(&text.color).unwrap_or([1.0, 1.0, 1.0, 1.0]),
+ // "transparent" ne parse pas en hex : alpha 0 => pas de fond, ce qui est
+ // exactement la sémantique CSS.
+ background: parse_hex(&text.background_color).unwrap_or([0.0, 0.0, 0.0, 0.0]),
+ font_size_px: text.font_size_rel * screen_h_px,
+ font_family: text.font_family.clone(),
+ bold: text.font_weight == "bold",
+ italic: text.font_style == "italic",
+ underline: text.text_decoration == "underline",
+ align: text.text_align.clone(),
+ box_px: [quad_px[0].round() as u32, quad_px[1].round() as u32],
+ };
+ let key = spec.cache_key();
+ let cached = {
+ let cache = self.text_cache.borrow();
+ cache.get(&annotation.id).filter(|(_, k)| *k == key).map(|(srv, _)| srv.clone())
+ };
+ let Some(srv) = cached.or_else(|| match raster.rasterize(&self.dev, &spec) {
+ Ok(srv) => {
+ self.text_cache
+ .borrow_mut()
+ .insert(annotation.id.clone(), (srv.clone(), key));
+ Some(srv)
+ }
+ Err(e) => {
+ eprintln!("[annotation texte] {}: {e}", annotation.id);
+ None
+ }
+ }) else {
+ continue;
+ };
+ self.ctx.PSSetShaderResources(2, Some(&[Some(srv)]));
+ self.draw_solid(&LayerCB {
+ dst,
+ src: [0.0, 0.0, 1.0, 1.0],
+ quad_px,
+ // mode 11 : sprite en alpha DÉJÀ prémultiplié (ce que produit D2D).
+ mode: 11.0,
+ color: [1.0, 1.0, 1.0, 1.0],
+ ..Default::default()
+ });
+ }
+ _ => {}
+ }
+ }
+ self.ctx.PSSetShaderResources(2, Some(&[None]));
+ }
+
/// Flou de mouvement (§8) : moyenne de `n` sous-frames aux temps intermédiaires
/// (mêmes textures vidéo, params d'animation à frame+k/n). Résultat laissé dans le RT.
pub unsafe fn compose_frame_mb(
@@ -2446,6 +2771,35 @@ mod tests {
}
}
+ #[test]
+ fn decodes_a_base64_data_uri() {
+ // "Hi!" -> SGkh
+ assert_eq!(decode_data_uri("data:image/png;base64,SGkh").unwrap(), b"Hi!".to_vec());
+ }
+
+ #[test]
+ fn ignores_padding_and_line_breaks_inside_the_payload() {
+ // Un URI replié ou paddé doit décoder à l'identique : les caractères hors alphabet sont
+ // sautés, donc ils ne peuvent pas décaler le flux.
+ let folded = "data:image/png;base64,SGkh
+==";
+ assert_eq!(decode_data_uri(folded).unwrap(), b"Hi!".to_vec());
+ }
+
+ #[test]
+ fn a_plain_path_is_not_a_data_uri() {
+ // Le repli lecture-disque des wallpapers en dépend.
+ assert!(decode_data_uri("/wallpapers/x.jpg").is_none());
+ assert!(decode_data_uri("C:/img/y.png").is_none());
+ }
+
+ #[test]
+ fn a_non_base64_data_uri_is_refused() {
+ // `data:image/svg+xml,<svg…>` n'est pas du base64 : mieux vaut échouer que décoder du
+ // texte comme des octets.
+ assert!(decode_data_uri("data:image/svg+xml,<svg/>").is_none());
+ }
+
#[test]
fn crop_maps_visible_frame_fractions_to_texture_uvs() {
let crop = SceneCrop { x: 0.25, y: 0.1, width: 0.5, height: 0.6 };
diff --git a/poc-d3d/src/lib.rs b/poc-d3d/src/lib.rs
index 256873eb6..5e6f9d473 100644
--- a/poc-d3d/src/lib.rs
+++ b/poc-d3d/src/lib.rs
@@ -13,8 +13,9 @@ pub mod live;
pub mod pipeline;
pub mod regions;
pub mod scene;
+pub mod text;
-use anyhow::Result;
+use anyhow::{Context as _, Result};
use compositor::Compositor;
use std::fmt::Write as _;
@@ -80,6 +81,18 @@ fn run_bench(args: &[String]) -> Result<()> {
let track = cursor::CursorTrack::load(&format!("{fixture}/screen.cursor.json"), 100_000.0, 6.0)?;
comp.set_cursor(track);
+ // `--scene <fichier.json>` : compose avec une VRAIE scène d'app au lieu du planning fixture.
+ // Sert à deux choses : sortir une preuve visuelle pour ce que seule une scène peut décrire
+ // (les annotations, qu'aucune UI ne crée encore pour certains types), et mesurer un
+ // avant/après perf sur une scène représentative.
+ let scene_arg = get("--scene", "");
+ if !scene_arg.is_empty() {
+ let json = std::fs::read_to_string(&scene_arg)
+ .with_context(|| format!("lecture de la scène {scene_arg}"))?;
+ comp.set_scene(Some(scene::Scene::from_json(&json)?));
+ println!("scène chargée depuis {scene_arg}");
+ }
+
let mut rows: Vec<(String, u64, f64, f64, f64, String)> = Vec::new(); // name, frames, best_wall, fps, ms/f, spread
let mut json = String::from("{\n \"runs\": [\n");
diff --git a/poc-d3d/src/regions.rs b/poc-d3d/src/regions.rs
index 6f4e89755..5dfaab471 100644
--- a/poc-d3d/src/regions.rs
+++ b/poc-d3d/src/regions.rs
@@ -224,6 +224,55 @@ fn lerp_rotation3d(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] {
[lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]
}
+/// Les trois segments d'une flèche d'annotation, en unités du viewBox SVG (0..100), repris
+/// VERBATIM des tracés de `ArrowSvgs.tsx` : hampe puis deux barbes, toutes à bouts ronds. Garder
+/// les mêmes nombres est ce qui garantit que le rendu natif et la preview dessinent la même
+/// flèche — inutile de réinventer une géométrie « équivalente ».
+pub fn arrow_segments_viewbox(direction: &str) -> [[f32; 4]; 3] {
+ match direction {
+ "up" => [[50.0, 20.0, 50.0, 80.0], [50.0, 20.0, 35.0, 35.0], [50.0, 20.0, 65.0, 35.0]],
+ "down" => [[50.0, 20.0, 50.0, 80.0], [50.0, 80.0, 35.0, 65.0], [50.0, 80.0, 65.0, 65.0]],
+ "left" => [[80.0, 50.0, 20.0, 50.0], [20.0, 50.0, 35.0, 35.0], [20.0, 50.0, 35.0, 65.0]],
+ "up-right" => [[25.0, 75.0, 75.0, 25.0], [75.0, 25.0, 60.0, 30.0], [75.0, 25.0, 70.0, 40.0]],
+ "up-left" => [[75.0, 75.0, 25.0, 25.0], [25.0, 25.0, 40.0, 30.0], [25.0, 25.0, 30.0, 40.0]],
+ "down-right" => {
+ [[25.0, 25.0, 75.0, 75.0], [75.0, 75.0, 70.0, 60.0], [75.0, 75.0, 60.0, 70.0]]
+ }
+ "down-left" => {
+ [[75.0, 25.0, 25.0, 75.0], [25.0, 75.0, 30.0, 60.0], [25.0, 75.0, 40.0, 70.0]]
+ }
+ // "right" et tout ce qui n'est pas reconnu — même défaut que le schéma côté app.
+ _ => [[20.0, 50.0, 80.0, 50.0], [80.0, 50.0, 65.0, 35.0], [80.0, 50.0, 65.0, 65.0]],
+ }
+}
+
+/// Passe les segments du viewBox aux px locaux du quad, et rend la demi-épaisseur du trait.
+///
+/// Le SVG n'a pas de `preserveAspectRatio` explicite, donc il vaut `xMidYMid meet` : mise à
+/// l'échelle **uniforme** au plus petit côté, centrée. La flèche n'est donc jamais étirée quand la
+/// boîte n'est pas carrée, et `strokeWidth` suit la même échelle — c'est pour ça qu'il n'a pas
+/// besoin de la convention de proportionnalité du `fontSize` : il est déjà exprimé dans le
+/// viewBox, donc déjà relatif à la boîte.
+pub fn arrow_local_geometry(
+ direction: &str,
+ stroke_width_viewbox: f32,
+ quad_px: [f32; 2],
+) -> ([[f32; 4]; 3], f32) {
+ let scale = quad_px[0].min(quad_px[1]) / 100.0;
+ let off = [(quad_px[0] - 100.0 * scale) * 0.5, (quad_px[1] - 100.0 * scale) * 0.5];
+ let to_local = |v: [f32; 4]| {
+ [
+ off[0] + v[0] * scale,
+ off[1] + v[1] * scale,
+ off[0] + v[2] * scale,
+ off[1] + v[3] * scale,
+ ]
+ };
+ let segments = arrow_segments_viewbox(direction);
+ let half_stroke = (stroke_width_viewbox.max(0.0) * scale) * 0.5;
+ ([to_local(segments[0]), to_local(segments[1]), to_local(segments[2])], half_stroke)
+}
+
/// Focus effectif d'une région à `t` : sa position fixe, sauf en mode "auto" où elle suit la
/// télémétrie curseur (port de `getResolvedFocus`, sans le clamp — le crop-window de
/// `compositor.rs` clampe déjà après coup, cf. `su0.clamp(...)`, donc redondant ici).
@@ -536,3 +585,61 @@ mod zoom_focus_tests {
assert_eq!(state.focus, [0.5, 0.5]);
}
}
+
+#[cfg(test)]
+mod arrow_tests {
+ use super::*;
+
+ #[test]
+ fn the_geometry_is_the_svg_geometry_verbatim() {
+ // Parité avec `ArrowSvgs.tsx` : si ces nombres divergent, le rendu et la preview
+ // dessinent deux flèches différentes.
+ assert_eq!(
+ arrow_segments_viewbox("right"),
+ [[20.0, 50.0, 80.0, 50.0], [80.0, 50.0, 65.0, 35.0], [80.0, 50.0, 65.0, 65.0]]
+ );
+ assert_eq!(
+ arrow_segments_viewbox("up"),
+ [[50.0, 20.0, 50.0, 80.0], [50.0, 20.0, 35.0, 35.0], [50.0, 20.0, 65.0, 35.0]]
+ );
+ }
+
+ #[test]
+ fn an_unknown_direction_falls_back_to_right() {
+ // Même défaut que le schéma côté app, pour qu'une donnée abîmée dessine quelque chose
+ // de sensé plutôt que rien.
+ assert_eq!(arrow_segments_viewbox("sideways"), arrow_segments_viewbox("right"));
+ }
+
+ #[test]
+ fn a_square_quad_maps_the_viewbox_one_to_one() {
+ let (segments, half) = arrow_local_geometry("right", 10.0, [100.0, 100.0]);
+ // échelle 1, aucun centrage à appliquer
+ assert_eq!(segments[0], [20.0, 50.0, 80.0, 50.0]);
+ assert!((half - 5.0).abs() < 1e-6);
+ }
+
+ #[test]
+ fn a_wide_quad_scales_uniformly_and_centres() {
+ // `preserveAspectRatio` vaut `xMidYMid meet` par défaut : la flèche tient dans le PLUS
+ // PETIT côté et se centre — elle n'est jamais étirée. Ici 400x200 -> échelle 2, et
+ // 200px de marge horizontale à répartir, donc +100 sur les x.
+ let (segments, half) = arrow_local_geometry("right", 4.0, [400.0, 200.0]);
+ assert_eq!(segments[0], [100.0 + 40.0, 100.0, 100.0 + 160.0, 100.0]);
+ // l'épaisseur suit la même échelle uniforme
+ assert!((half - 4.0).abs() < 1e-6);
+ }
+
+ #[test]
+ fn a_tall_quad_centres_vertically() {
+ let (segments, _) = arrow_local_geometry("up", 4.0, [100.0, 300.0]);
+ // échelle 1 (plus petit côté = 100), 200px de marge verticale -> +100 sur les y
+ assert_eq!(segments[0], [50.0, 100.0 + 20.0, 50.0, 100.0 + 80.0]);
+ }
+
+ #[test]
+ fn a_negative_stroke_width_cannot_produce_a_negative_half_width() {
+ let (_, half) = arrow_local_geometry("right", -5.0, [100.0, 100.0]);
+ assert_eq!(half, 0.0);
+ }
+}
diff --git a/poc-d3d/src/scene.rs b/poc-d3d/src/scene.rs
index d8ebdd367..aadf885cd 100644
--- a/poc-d3d/src/scene.rs
+++ b/poc-d3d/src/scene.rs
@@ -174,6 +174,94 @@ pub enum SceneBackground {
Image { path: String },
}
+/// Une annotation de la timeline (temps en secondes, source du clip).
+///
+/// Espace de coordonnées — à respecter au rendu : `x`/`y`/`w`/`h` sont des fractions du **rect
+/// écran**, pas du cadre de sortie (le calque web reçoit `layout.screenRect` comme conteneur), et
+/// elles ne subissent **pas** le crop de zoom : l'overlay est frère de l'élément qui porte la
+/// transform, donc les annotations restent en place pendant que le contenu zoome dessous.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneAnnotation {
+ #[serde(default)]
+ pub id: String,
+ /// Voir `SceneZoomRegion::clip_index`.
+ #[serde(default)]
+ pub clip_index: Option<usize>,
+ pub start_sec: f64,
+ pub end_sec: f64,
+ /// "text" | "image" | "figure" | "blur".
+ pub kind: String,
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ /// Ordre de peinture ; l'app envoie déjà la liste triée croissante.
+ #[serde(default)]
+ pub z_index: i32,
+ #[serde(default)]
+ pub text: Option<SceneAnnotationText>,
+ #[serde(default)]
+ pub image_path: Option<String>,
+ #[serde(default)]
+ pub figure: Option<SceneAnnotationFigure>,
+ #[serde(default)]
+ pub blur: Option<SceneAnnotationBlur>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneAnnotationText {
+ pub content: String,
+ /// Chaînes CSS, parsées ici comme la couleur de fond (`parse_hex`) ; "transparent" = pas de
+ /// remplissage.
+ pub color: String,
+ pub background_color: String,
+ /// Taille de police en **fraction de la hauteur du rect écran**, comme tout le reste de ce
+ /// contrat : à multiplier par la hauteur du rect en pixels de sortie. La preview applique le
+ /// même produit contre sa propre boîte (`annotationScale.ts`), donc preview et rendu
+ /// s'accordent à n'importe quelle résolution.
+ pub font_size_rel: f32,
+ pub font_family: String,
+ pub font_weight: String,
+ pub font_style: String,
+ pub text_decoration: String,
+ pub text_align: String,
+ #[serde(default)]
+ pub animation: Option<String>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneAnnotationFigure {
+ /// "up" | "down" | "left" | "right" | "up-right" | "up-left" | "down-right" | "down-left".
+ pub direction: String,
+ pub color: String,
+ pub stroke_width: f32,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneAnnotationBlur {
+ /// "blur" | "mosaic".
+ pub style: String,
+ /// "rectangle" | "oval" | "freehand".
+ pub shape: String,
+ /// "white" | "black".
+ pub color: String,
+ pub intensity: f32,
+ pub block_size: f32,
+ /// Fractions du rect écran, même espace que le rect.
+ #[serde(default)]
+ pub freehand_points: Option<Vec<SceneAnnotationPoint>>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct SceneAnnotationPoint {
+ pub x: f32,
+ pub y: f32,
+}
+
/// Une zone de zoom de la timeline (temps en secondes).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -273,6 +361,9 @@ pub struct Scene {
pub zoom_regions: Vec<SceneZoomRegion>,
/// `#[serde(default)]` : champ ajouté après coup, absent des JSON de test existants.
#[serde(default)]
+ pub annotations: Vec<SceneAnnotation>,
+ /// `#[serde(default)]` : champ ajouté après coup, absent des JSON de test existants.
+ #[serde(default)]
pub speed_regions: Vec<SceneSpeedRegion>,
/// `#[serde(default)]` : champ ajouté après coup, absent des JSON de test existants.
#[serde(default)]
@@ -316,6 +407,9 @@ impl Scene {
scene.camera_fullscreen_regions.retain(|region| {
belongs(region.clip_index, region.start_sec, region.end_sec)
});
+ scene.annotations.retain(|annotation| {
+ belongs(annotation.clip_index, annotation.start_sec, annotation.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 à
@@ -427,3 +521,74 @@ mod tests {
assert_eq!(s.layout.preset, "picture-in-picture");
}
}
+
+#[cfg(test)]
+mod annotation_tests {
+ use super::*;
+
+ /// Enveloppe minimale valide + les annotations passées en paramètre.
+ fn scene_json(annotations: &str) -> String {
+ format!(
+ 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":[],"annotations":{annotations},"cursor":{{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"}},"cropByClip":[],"output":{{"width":1920,"height":1080,"fps":30}}}}"##
+ )
+ }
+
+ #[test]
+ fn an_older_payload_without_annotations_still_parses() {
+ // `#[serde(default)]` : tout JSON produit avant ce champ doit continuer à charger.
+ let json = scene_json("[]").replace(r#""annotations":[],"#, "");
+ let scene = Scene::from_json(&json).expect("parse sans annotations");
+ assert!(scene.annotations.is_empty());
+ }
+
+ #[test]
+ fn parses_a_text_annotation_with_its_style() {
+ let json = scene_json(
+ r##"[{"id":"ann1","clipIndex":0,"startSec":1.0,"endSec":3.0,"kind":"text","x":0.25,"y":0.5,"w":0.4,"h":0.1,"zIndex":2,"text":{"content":"Bonjour","color":"#ffffff","backgroundColor":"transparent","fontSizeRel":0.0296,"fontFamily":"Inter","fontWeight":"bold","fontStyle":"normal","textDecoration":"none","textAlign":"center","animation":"fade"}}]"##,
+ );
+ let scene = Scene::from_json(&json).expect("parse texte");
+ let ann = &scene.annotations[0];
+ assert_eq!(ann.kind, "text");
+ assert_eq!(ann.clip_index, Some(0));
+ assert_eq!(ann.z_index, 2);
+ assert!((ann.x - 0.25).abs() < 1e-6 && (ann.h - 0.1).abs() < 1e-6);
+ let text = ann.text.as_ref().expect("payload texte");
+ assert_eq!(text.content, "Bonjour");
+ assert_eq!(text.text_align, "center");
+ assert_eq!(text.animation.as_deref(), Some("fade"));
+ assert!(ann.figure.is_none() && ann.blur.is_none());
+ }
+
+ #[test]
+ fn parses_figure_and_blur_payloads() {
+ let json = scene_json(
+ r##"[{"id":"f","startSec":0.0,"endSec":1.0,"kind":"figure","x":0.1,"y":0.1,"w":0.2,"h":0.2,"zIndex":0,"figure":{"direction":"up-left","color":"#34B27B","strokeWidth":6}},
+ {"id":"b","startSec":0.0,"endSec":1.0,"kind":"blur","x":0.0,"y":0.0,"w":0.5,"h":0.5,"zIndex":1,"blur":{"style":"mosaic","shape":"freehand","color":"black","intensity":8,"blockSize":16,"freehandPoints":[{"x":0.1,"y":0.2},{"x":0.3,"y":0.4}]}}]"##,
+ );
+ let scene = Scene::from_json(&json).expect("parse figure+blur");
+ let figure = scene.annotations[0].figure.as_ref().expect("payload figure");
+ assert_eq!(figure.direction, "up-left");
+ assert!((figure.stroke_width - 6.0).abs() < 1e-6);
+ let blur = scene.annotations[1].blur.as_ref().expect("payload blur");
+ assert_eq!(blur.shape, "freehand");
+ let points = blur.freehand_points.as_ref().expect("points");
+ assert_eq!(points.len(), 2);
+ assert!((points[1].x - 0.3).abs() < 1e-6);
+ }
+
+ #[test]
+ fn for_clip_window_keeps_only_the_annotations_of_the_composed_clip() {
+ // Même règle que les zoom/speed/camera regions : bon clip ET recouvrement de la fenêtre.
+ let json = scene_json(
+ r##"[{"id":"keep","clipIndex":0,"startSec":1.0,"endSec":2.0,"kind":"figure","x":0,"y":0,"w":0.1,"h":0.1,"zIndex":0},
+ {"id":"other-clip","clipIndex":1,"startSec":1.0,"endSec":2.0,"kind":"figure","x":0,"y":0,"w":0.1,"h":0.1,"zIndex":0},
+ {"id":"out-of-window","clipIndex":0,"startSec":50.0,"endSec":51.0,"kind":"figure","x":0,"y":0,"w":0.1,"h":0.1,"zIndex":0}]"##,
+ );
+ let scene = Scene::from_json(&json).expect("parse");
+ let filtered = scene.for_clip_window(0, 0.0, 10.0);
+ assert_eq!(
+ filtered.annotations.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(),
+ vec!["keep"]
+ );
+ }
+}
diff --git a/poc-d3d/src/shaders.hlsl b/poc-d3d/src/shaders.hlsl
index e6449814f..061ff41c9 100644
--- a/poc-d3d/src/shaders.hlsl
+++ b/poc-d3d/src/shaders.hlsl
@@ -61,6 +61,16 @@ float3 sample_yuv(float2 uv)
return yuv709_limited(y, cbcr);
}
+// SDF segment à bouts ronds — la primitive des flèches d'annotation, dont les tracés SVG sont
+// trois segments `stroke-linecap="round"` (cf. ArrowSvgs.tsx).
+float sd_segment(float2 p, float2 a, float2 b)
+{
+ float2 pa = p - a;
+ float2 ba = b - a;
+ float h = saturate(dot(pa, ba) / max(dot(ba, ba), 1e-6));
+ return length(pa - ba * h);
+}
+
// SDF rectangle à coins arrondis (§7 E2) : <0 dedans.
float sd_round_rect(float2 p, float2 halfsz, float r)
{
@@ -76,6 +86,92 @@ float4 ps_main(VSOut i) : SV_Target
// de perspective-correct exact, mais indiscernable à l'œil pour un tilt de 10-22°) et
// échantillonne la vidéo à l'UV correspondant, sinon transparent (hors du quad projeté).
// fx.xy/fx.zw = coins TL/TR (px locaux, 0..quad_px) ; src_prev.xy/.zw = coins BR/BL.
+ // mode 11 : texte d'annotation, rastérisé par Direct2D (voir text.rs). D2D écrit sur une
+ // surface DXGI en alpha PRÉMULTIPLIÉ, donc contrairement au mode 7 (sprite curseur, alpha
+ // droit) il ne faut SURTOUT pas re-multiplier ici : les bords adoucis des glyphes
+ // deviendraient deux fois trop transparents et le texte paraîtrait délavé.
+ // `color.a` reste l'opacité globale (fondu d'animation).
+ if (mode > 10.5)
+ {
+ float4 s = texImg.Sample(samp, i.uv);
+ return s * color.a;
+ }
+
+ // mode 10 : annotation « flou » — masque la zone en réutilisant l'image DÉJÀ composée, qui
+ // arrive dans `texImg` (recopie du render target : on ne peut pas échantillonner la cible sur
+ // laquelle on dessine). `i.pout` donne directement l'UV de sortie, donc aucun mapping à
+ // refaire. fx.x = 0 mosaïque / 1 flou ; fx.y = taille de bloc px (mosaïque) ou rayon px
+ // (flou) ; fx.z = 0 rectangle / 1 ovale ; fx.w = 1 si le masque doit être teinté.
+ if (mode > 9.5)
+ {
+ // Masque de forme, en coords locales normalisées du quad.
+ float2 n = i.local / max(quad_px, 1e-6);
+ float cov = 1.0;
+ if (fx.z > 0.5)
+ {
+ // Ovale inscrit : distance au centre en unités de demi-axes, adoucie sur ~1px.
+ float2 d = (n - 0.5) * 2.0;
+ float r = length(d);
+ float aa = 2.0 / max(min(quad_px.x, quad_px.y), 1.0);
+ cov = 1.0 - smoothstep(1.0 - aa, 1.0, r);
+ }
+ if (cov <= 0.0) return float4(0.0, 0.0, 0.0, 0.0);
+
+ float3 rgb;
+ if (fx.x > 0.5)
+ {
+ // Flou : on échantillonne un niveau de mip de l'image composée. `log2(rayon)` donne
+ // le niveau dont un texel couvre à peu près le rayon demandé, et le filtrage
+ // trilinéaire lisse la transition entre deux niveaux quand le rayon varie.
+ //
+ // Un noyau de quelques taps espacés du rayon ne floute PAS : il superpose autant de
+ // copies décalées, ce qui se voit comme du texte fantôme. Atteindre un vrai lissage
+ // par taps demanderait un tap par pixel de rayon ; la pyramide de mips donne le même
+ // résultat à coût constant, et c'est le GPU qui l'a construite.
+ float lod = log2(max(fx.y, 1.0));
+ rgb = texImg.SampleLevel(samp, i.pout, lod).rgb;
+ }
+ else
+ {
+ // Mosaïque : on quantifie l'UV sur une grille de `fx.y` px, alignée sur le quad pour
+ // que les blocs ne rampent pas quand l'annotation bouge.
+ float2 px_uv = dst.zw / max(quad_px, 1e-6);
+ float2 block = max(fx.y, 1.0) * px_uv;
+ float2 origin = dst.xy;
+ float2 q = origin + (floor((i.pout - origin) / block) + 0.5) * block;
+ // `SampleLevel(..., 0)` et non `Sample` : l'UV quantifié est une marche d'escalier,
+ // donc ses dérivées explosent en bord de bloc et le choix automatique de mip
+ // ramollirait justement les arêtes qui font la mosaïque.
+ rgb = texImg.SampleLevel(samp, q, 0.0).rgb;
+ }
+
+ if (fx.w > 0.5)
+ {
+ // Teinte blanc/noir : la couleur choisie, mêlée à moitié, garde la forme lisible sans
+ // effacer complètement ce qu'il y a dessous.
+ rgb = lerp(rgb, color.rgb, 0.5);
+ }
+ float a = cov * color.a;
+ return float4(rgb * a, a); // prémultiplié
+ }
+
+ // mode 9 : annotation « figure » — une flèche. Parité EXACTE avec `ArrowSvgs.tsx`, dont
+ // chaque direction est un tracé de trois segments à bouts ronds dans un viewBox 0..100 :
+ // une hampe et deux barbes. Trois `sd_segment` et un `min` reproduisent donc la forme telle
+ // quelle, pas une approximation. Les extrémités arrivent déjà converties en px locaux du
+ // quad (échelle uniforme centrée, comme le `preserveAspectRatio` par défaut du SVG).
+ // fx = hampe (a.xy, b.xy), src_prev = barbe 1, dst_prev = barbe 2 ; mb.y = demi-épaisseur px.
+ if (mode > 8.5)
+ {
+ float d = sd_segment(i.local, fx.xy, fx.zw);
+ d = min(d, sd_segment(i.local, src_prev.xy, src_prev.zw));
+ d = min(d, sd_segment(i.local, dst_prev.xy, dst_prev.zw));
+ // Couverture sur ~1 px : le trait reste net sans crénelage, et une flèche fine ne
+ // disparaît pas quand la demi-épaisseur descend sous le pixel.
+ float a = saturate(mb.y - d + 0.5) * color.a;
+ return float4(color.rgb * a, a); // prémultiplié, comme tous les autres modes
+ }
+
if (mode > 7.5)
{
float2 c00 = fx.xy, c10 = fx.zw, c11 = src_prev.xy, c01 = src_prev.zw;
diff --git a/poc-d3d/src/text.rs b/poc-d3d/src/text.rs
new file mode 100644
index 000000000..551990c4c
--- /dev/null
+++ b/poc-d3d/src/text.rs
@@ -0,0 +1,290 @@
+//! Rastérisation du texte des annotations, via DirectWrite (mise en page) et Direct2D (dessin)
+//! sur une surface DXGI partagée avec D3D11.
+//!
+//! Pourquoi DirectWrite et pas un rasterizer de glyphes maison : l'app expédie en 13 langues,
+//! dont l'arabe, et le texte d'une annotation est saisi librement. Le façonnage (ligatures,
+//! bidirectionnel, CJK, sélection de police de repli) est un travail que DirectWrite fait
+//! correctement et qu'on ne réécrira pas. Le device D3D11 est déjà créé avec
+//! `D3D11_CREATE_DEVICE_BGRA_SUPPORT` (cf. `d3d.rs`, dont le commentaire anticipait cet usage),
+//! donc l'interop ne coûte aucun changement de pipeline.
+//!
+//! Pourquoi ça ne coûte rien par frame : le texte d'une annotation est un contenu STATIQUE. On le
+//! rastérise une fois dans une texture, et la boucle de rendu ne fait plus qu'un quad texturé de
+//! plus. Le travail cher — façonnage, mise en page, rendu des glyphes — sort du chemin chaud, et
+//! le cache est invalidé sur le contenu, le style et la taille de boîte, JAMAIS sur la
+//! transformation : déplacer, redimensionner ou animer une annotation n'est pas une raison de
+//! re-rastériser (c'est l'affaire du vertex shader).
+
+use anyhow::{bail, Result};
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct2D::Common::{
+ D2D1_ALPHA_MODE_PREMULTIPLIED, D2D1_COLOR_F, D2D1_PIXEL_FORMAT, D2D_POINT_2F, D2D_RECT_F,
+};
+use windows::Win32::Graphics::Direct2D::{
+ D2D1CreateFactory, ID2D1Factory, D2D1_DRAW_TEXT_OPTIONS_NONE, D2D1_FACTORY_TYPE_SINGLE_THREADED,
+ D2D1_FEATURE_LEVEL_DEFAULT, D2D1_RENDER_TARGET_PROPERTIES, D2D1_RENDER_TARGET_TYPE_DEFAULT,
+ D2D1_RENDER_TARGET_USAGE_NONE,
+};
+use windows::Win32::Graphics::Direct3D11::{
+ ID3D11Device, ID3D11ShaderResourceView, ID3D11Texture2D, D3D11_BIND_RENDER_TARGET,
+ D3D11_BIND_SHADER_RESOURCE, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT,
+};
+use windows::Win32::Graphics::DirectWrite::{
+ DWriteCreateFactory, IDWriteFactory, DWRITE_FACTORY_TYPE_SHARED,
+ DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_ITALIC, DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_PARAGRAPH_ALIGNMENT_CENTER,
+ DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_TEXT_ALIGNMENT_TRAILING,
+ DWRITE_TEXT_METRICS, DWRITE_TEXT_RANGE,
+};
+use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
+use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
+use windows::Win32::Graphics::Dxgi::IDXGISurface;
+
+/// Tout ce dont le rendu d'un texte dépend. Sert aussi de clé de cache : deux specs égales
+/// donnent la même texture, donc `cache_key` couvre exactement ces champs.
+#[derive(Clone, PartialEq)]
+pub struct TextSpec {
+ pub content: String,
+ /// RGBA 0..1 (déjà parsé depuis la chaîne CSS côté appelant).
+ pub color: [f32; 4],
+ /// RGBA 0..1 ; alpha 0 = pas de fond (le CSS `transparent`).
+ pub background: [f32; 4],
+ pub font_size_px: f32,
+ pub font_family: String,
+ pub bold: bool,
+ pub italic: bool,
+ pub underline: bool,
+ /// "left" | "center" | "right".
+ pub align: String,
+ /// Taille de la boîte en px de sortie — la mise en page en dépend (retours à la ligne).
+ pub box_px: [u32; 2],
+}
+
+impl TextSpec {
+ /// FNV-1a sur les champs. Utilisé pour décider s'il faut re-rastériser ; volontairement
+ /// insensible à tout ce qui n'affecte pas les pixels (position, opacité d'animation…).
+ pub fn cache_key(&self) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ let mut mix = |bytes: &[u8]| {
+ for b in bytes {
+ h ^= *b as u64;
+ h = h.wrapping_mul(0x100_0000_01b3);
+ }
+ };
+ mix(self.content.as_bytes());
+ mix(self.font_family.as_bytes());
+ mix(&self.font_size_px.to_bits().to_le_bytes());
+ for c in self.color.iter().chain(self.background.iter()) {
+ mix(&c.to_bits().to_le_bytes());
+ }
+ mix(&[self.bold as u8, self.italic as u8, self.underline as u8]);
+ mix(self.align.as_bytes());
+ mix(&self.box_px[0].to_le_bytes());
+ mix(&self.box_px[1].to_le_bytes());
+ h
+ }
+}
+
+/// Chaîne UTF-16 terminée par un zéro, pour les API Win32 qui prennent un `PCWSTR`.
+fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+}
+
+pub struct TextRasterizer {
+ d2d: ID2D1Factory,
+ dwrite: IDWriteFactory,
+}
+
+impl TextRasterizer {
+ pub fn new() -> Result<TextRasterizer> {
+ unsafe {
+ // SINGLE_THREADED : tout le rendu du compositeur vit sur un seul thread, et le mode
+ // multithread ajoute un verrou par appel pour rien.
+ let d2d: ID2D1Factory =
+ D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, None)?;
+ let dwrite: IDWriteFactory = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
+ Ok(TextRasterizer { d2d, dwrite })
+ }
+ }
+
+ /// Rastérise `spec` dans une texture neuve et rend sa SRV. Le fond éventuel est dessiné
+ /// derrière le texte, ajusté aux métriques de la mise en page — comme le CSS, où
+ /// `backgroundColor` est porté par le `<span>` et épouse donc le texte, pas la boîte.
+ pub unsafe fn rasterize(
+ &self,
+ dev: &ID3D11Device,
+ spec: &TextSpec,
+ ) -> Result<ID3D11ShaderResourceView> {
+ let (w, h) = (spec.box_px[0].max(1), spec.box_px[1].max(1));
+ if spec.content.is_empty() {
+ bail!("texte vide");
+ }
+
+ // B8G8R8A8 : le format qu'exige une cible de rendu D2D. DXGI expose déjà les composantes
+ // dans l'ordre RGBA au shader, donc rien à ré-échanger côté HLSL.
+ let desc = D3D11_TEXTURE2D_DESC {
+ Width: w,
+ Height: h,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ };
+ let mut tex: Option<ID3D11Texture2D> = None;
+ dev.CreateTexture2D(&desc, None, Some(&mut tex))?;
+ let tex = tex.unwrap();
+
+ let surface: IDXGISurface = tex.cast()?;
+ let props = D2D1_RENDER_TARGET_PROPERTIES {
+ r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
+ pixelFormat: D2D1_PIXEL_FORMAT {
+ format: DXGI_FORMAT_B8G8R8A8_UNORM,
+ // PREMULTIPLIED : ce que D2D produit sur une surface DXGI. Le shader ne doit donc
+ // PAS re-multiplier par l'alpha (cf. mode 11 dans shaders.hlsl).
+ alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED,
+ },
+ // 96 dpi = 1 unité D2D pour 1 pixel : la mise en page se fait donc directement en
+ // pixels de sortie, ce qui rend `font_size_px` littéral.
+ dpiX: 96.0,
+ dpiY: 96.0,
+ usage: D2D1_RENDER_TARGET_USAGE_NONE,
+ minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
+ };
+ let rt = self.d2d.CreateDxgiSurfaceRenderTarget(&surface, &props)?;
+
+ let family = wide(&spec.font_family);
+ let locale = wide("");
+ let format = self.dwrite.CreateTextFormat(
+ windows::core::PCWSTR(family.as_ptr()),
+ None,
+ if spec.bold { DWRITE_FONT_WEIGHT_BOLD } else { DWRITE_FONT_WEIGHT_NORMAL },
+ if spec.italic { DWRITE_FONT_STYLE_ITALIC } else { DWRITE_FONT_STYLE_NORMAL },
+ DWRITE_FONT_STRETCH_NORMAL,
+ spec.font_size_px.max(1.0),
+ windows::core::PCWSTR(locale.as_ptr()),
+ )?;
+ format.SetTextAlignment(match spec.align.as_str() {
+ "left" => DWRITE_TEXT_ALIGNMENT_LEADING,
+ "right" => DWRITE_TEXT_ALIGNMENT_TRAILING,
+ _ => DWRITE_TEXT_ALIGNMENT_CENTER,
+ })?;
+ // Centrage vertical : l'overlay web met `alignItems: center` sur le conteneur.
+ format.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)?;
+
+ let text: Vec<u16> = spec.content.encode_utf16().collect();
+ let layout =
+ self.dwrite.CreateTextLayout(&text, &format, w as f32, h as f32)?;
+ if spec.underline {
+ layout.SetUnderline(
+ true,
+ DWRITE_TEXT_RANGE { startPosition: 0, length: text.len() as u32 },
+ )?;
+ }
+
+ let color = D2D1_COLOR_F {
+ r: spec.color[0],
+ g: spec.color[1],
+ b: spec.color[2],
+ a: spec.color[3],
+ };
+ let brush = rt.CreateSolidColorBrush(&color, None)?;
+
+ rt.BeginDraw();
+ rt.Clear(Some(&D2D1_COLOR_F { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }));
+ if spec.background[3] > 0.0 {
+ let mut m = DWRITE_TEXT_METRICS::default();
+ layout.GetMetrics(&mut m)?;
+ let bg = D2D1_COLOR_F {
+ r: spec.background[0],
+ g: spec.background[1],
+ b: spec.background[2],
+ a: spec.background[3],
+ };
+ let bg_brush = rt.CreateSolidColorBrush(&bg, None)?;
+ rt.FillRectangle(
+ &D2D_RECT_F {
+ left: m.left,
+ top: m.top,
+ right: m.left + m.width,
+ bottom: m.top + m.height,
+ },
+ &bg_brush,
+ );
+ }
+ rt.DrawTextLayout(
+ D2D_POINT_2F { x: 0.0, y: 0.0 },
+ &layout,
+ &brush,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+ // `EndDraw` rapporte une perte de device par son HRESULT plutôt qu'en échouant tout de
+ // suite : on le propage pour que l'appelant sache que la texture n'est pas exploitable.
+ rt.EndDraw(None, None)?;
+
+ let mut srv: Option<ID3D11ShaderResourceView> = None;
+ dev.CreateShaderResourceView(&tex, None, Some(&mut srv))?;
+ Ok(srv.unwrap())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn spec(content: &str) -> TextSpec {
+ TextSpec {
+ content: content.into(),
+ color: [1.0, 1.0, 1.0, 1.0],
+ background: [0.0, 0.0, 0.0, 0.0],
+ font_size_px: 32.0,
+ font_family: "Inter".into(),
+ bold: true,
+ italic: false,
+ underline: false,
+ align: "center".into(),
+ box_px: [400, 120],
+ }
+ }
+
+ #[test]
+ fn identical_specs_share_a_cache_key() {
+ assert_eq!(spec("Bonjour").cache_key(), spec("Bonjour").cache_key());
+ }
+
+ #[test]
+ fn the_key_changes_with_anything_that_changes_the_pixels() {
+ let base = spec("Bonjour").cache_key();
+ let mut other = spec("Bonsoir");
+ assert_ne!(other.cache_key(), base, "contenu");
+ other = spec("Bonjour");
+ other.font_size_px = 33.0;
+ assert_ne!(other.cache_key(), base, "taille");
+ other = spec("Bonjour");
+ other.italic = true;
+ assert_ne!(other.cache_key(), base, "style");
+ other = spec("Bonjour");
+ other.color = [1.0, 0.0, 0.0, 1.0];
+ assert_ne!(other.cache_key(), base, "couleur");
+ other = spec("Bonjour");
+ other.align = "left".into();
+ assert_ne!(other.cache_key(), base, "alignement");
+ other = spec("Bonjour");
+ // La taille de boîte compte : elle décide des retours à la ligne, donc des pixels.
+ other.box_px = [401, 120];
+ assert_ne!(other.cache_key(), base, "boîte");
+ }
+
+ #[test]
+ fn the_key_is_stable_across_unicode_content() {
+ // Le façonnage est délégué à DirectWrite ; la clé ne doit pas pour autant se briser sur
+ // du non-ASCII (l'app expédie en 13 langues).
+ for text in ["مرحبا", "こんにちは", "Grüße", "Здравствуйте"] {
+ assert_eq!(spec(text).cache_key(), spec(text).cache_key());
+ }
+ assert_ne!(spec("مرحبا").cache_key(), spec("こんにちは").cache_key());
+ }
+}
diff --git a/src/components/ai-edition/AnnotationOverlay.tsx b/src/components/ai-edition/AnnotationOverlay.tsx
index ffd85b2eb..22077eb74 100644
--- a/src/components/ai-edition/AnnotationOverlay.tsx
+++ b/src/components/ai-edition/AnnotationOverlay.tsx
@@ -9,6 +9,7 @@
import { type CSSProperties, type PointerEvent, useEffect, useRef, useState } from "react";
import { Rnd } from "react-rnd";
import { useScopedT } from "@/contexts/I18nContext";
+import { annotationFontSizePx } from "@/lib/ai-edition/annotationScale";
import {
getBlurOverlayColor,
getMosaicGridOverlayColor,
@@ -296,7 +297,7 @@ export function AnnotationOverlay({
style={{
color: annotation.style.color,
backgroundColor: annotation.style.backgroundColor,
- fontSize: `${annotation.style.fontSize}px`,
+ fontSize: `${annotationFontSizePx(annotation.style.fontSize, containerHeight)}px`,
fontFamily: annotation.style.fontFamily,
fontWeight: annotation.style.fontWeight,
fontStyle: annotation.style.fontStyle,
diff --git a/src/lib/ai-edition/annotationScale.ts b/src/lib/ai-edition/annotationScale.ts
new file mode 100644
index 000000000..216f95a64
--- /dev/null
+++ b/src/lib/ai-edition/annotationScale.ts
@@ -0,0 +1,40 @@
+/**
+ * One rule for turning an annotation's authored `style.fontSize` into a real size, shared by the
+ * preview overlay and the native renderer so the two cannot drift.
+ *
+ * Everything else about an annotation is already proportional — `position` and `size` are
+ * percentages of the screen rect, so they survive any output resolution. `fontSize` was the
+ * exception: the preview applied it as absolute CSS pixels against whatever size the panel
+ * happened to be (`fontSize: ${style.fontSize}px`), which meant the same document showed
+ * different text sizes at different window sizes, and a native render at 1080p would have shown
+ * text roughly half the size the author saw in a ~960px-wide panel.
+ *
+ * So the authored number is defined as "pixels at `ANNOTATION_REFERENCE_HEIGHT`", and both
+ * consumers scale it by the height of the box they are drawing into. The preview becomes a
+ * faithful scale model of the render, which is the point.
+ *
+ * Consequence worth knowing: text in the preview now tracks the panel size instead of ignoring
+ * it, so an existing project's captions look smaller in a small panel than they used to. What
+ * they looked like before was never what the export would have produced.
+ */
+
+/**
+ * The height the authored `fontSize` is expressed against. 1080 because it is the canonical
+ * output height, so a project authored while previewing near full size needs no adjustment and
+ * the number in the inspector keeps meaning what a user would guess it means.
+ */
+export const ANNOTATION_REFERENCE_HEIGHT = 1080;
+
+/** Authored font size → fraction of the screen rect's height. Resolution-free, which is the form
+ * the native scene carries. */
+export function annotationFontSizeFraction(fontSizePx: number): number {
+ if (!Number.isFinite(fontSizePx) || fontSizePx <= 0) return 0;
+ return fontSizePx / ANNOTATION_REFERENCE_HEIGHT;
+}
+
+/** Authored font size → pixels, for a box of `containerHeightPx`. Used by the preview overlay;
+ * the native renderer applies the same product against the screen rect in output pixels. */
+export function annotationFontSizePx(fontSizePx: number, containerHeightPx: number): number {
+ if (!Number.isFinite(containerHeightPx) || containerHeightPx <= 0) return 0;
+ return annotationFontSizeFraction(fontSizePx) * containerHeightPx;
+}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 97f48e6df..d88007bcc 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -77,7 +77,7 @@ function makeDoc(
captionRanges: [],
...(overrides.timeline ?? {}),
},
- annotations: [],
+ annotations: overrides.annotations ?? [],
zoomRanges: overrides.zoomRanges ?? [],
legacyEditor: overrides.legacyEditor ?? null,
agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },
@@ -1178,3 +1178,182 @@ describe("buildSceneDescription.layout.layoutByClip", () => {
expect(scene.layout.screenRect).toEqual(scene.layout.layoutByClip?.[0]?.screenRect);
});
});
+
+// --- annotations -----------------------------------------------------------
+
+describe("buildSceneDescription.annotations", () => {
+ const style = {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold" as const,
+ fontStyle: "normal" as const,
+ textDecoration: "none" as const,
+ textAlign: "center" as const,
+ };
+
+ function docWithAnnotations(annotations: AxcutDocument["annotations"]) {
+ return makeDoc({
+ assets: [makeAsset({ id: "a1", originalPath: "/tmp/a1.mp4", durationSec: 30 })],
+ clips: [
+ makeClip({
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 30,
+ timelineStartSec: 0,
+ timelineEndSec: 30,
+ }),
+ ],
+ annotations,
+ });
+ }
+
+ it("converts the authored percentages into screen-rect fractions", () => {
+ // The web overlay divides by 100 against `layout.screenRect`; native gets the same space
+ // as fractions so it never has to know about percent.
+ const scene = buildSceneDescription(
+ docWithAnnotations([
+ {
+ id: "ann1",
+ startMs: 1000,
+ endMs: 3000,
+ type: "text",
+ content: "",
+ textContent: "Hello",
+ position: { x: 25, y: 50 },
+ size: { width: 40, height: 10 },
+ style,
+ zIndex: 0,
+ },
+ ]),
+ );
+ expect(scene.annotations).toHaveLength(1);
+ expect(scene.annotations[0]).toMatchObject({
+ id: "ann1",
+ kind: "text",
+ startSec: 1,
+ endSec: 3,
+ x: 0.25,
+ y: 0.5,
+ w: 0.4,
+ h: 0.1,
+ clipIndex: 0,
+ });
+ });
+
+ it("carries the text payload, preferring textContent over the legacy content field", () => {
+ const scene = buildSceneDescription(
+ docWithAnnotations([
+ {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "migrated",
+ textContent: "live",
+ position: { x: 0, y: 0 },
+ size: { width: 10, height: 10 },
+ style: { ...style, textAlign: "left", textAnimation: "fade" },
+ zIndex: 0,
+ },
+ ]),
+ );
+ expect(scene.annotations[0].text).toMatchObject({
+ content: "live",
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ // 32 px authored against ANNOTATION_REFERENCE_HEIGHT (1080) -> fraction of the rect.
+ fontSizeRel: 32 / 1080,
+ textAlign: "left",
+ animation: "fade",
+ });
+ });
+
+ it("defaults a figure's arrow data when the document omits it", () => {
+ const scene = buildSceneDescription(
+ docWithAnnotations([
+ {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "figure",
+ content: "",
+ position: { x: 10, y: 10 },
+ size: { width: 20, height: 20 },
+ style,
+ zIndex: 0,
+ },
+ ]),
+ );
+ expect(scene.annotations[0].figure).toEqual({
+ direction: "right",
+ color: "#34B27B",
+ strokeWidth: 4,
+ });
+ expect(scene.annotations[0].text).toBeUndefined();
+ });
+
+ it("normalises freehand blur points into the same space as the rect", () => {
+ const scene = buildSceneDescription(
+ docWithAnnotations([
+ {
+ id: "ann1",
+ startMs: 0,
+ endMs: 1000,
+ type: "blur",
+ content: "",
+ position: { x: 0, y: 0 },
+ size: { width: 50, height: 50 },
+ style,
+ zIndex: 0,
+ blurData: {
+ type: "mosaic",
+ shape: "freehand",
+ color: "black",
+ intensity: 8,
+ blockSize: 16,
+ freehandPoints: [
+ { x: 10, y: 20 },
+ { x: 30, y: 40 },
+ ],
+ },
+ },
+ ]),
+ );
+ expect(scene.annotations[0].blur).toMatchObject({
+ style: "mosaic",
+ shape: "freehand",
+ color: "black",
+ intensity: 8,
+ blockSize: 16,
+ freehandPoints: [
+ { x: 0.1, y: 0.2 },
+ { x: 0.3, y: 0.4 },
+ ],
+ });
+ });
+
+ it("emits ascending zIndex so the compositor can paint without sorting per frame", () => {
+ const at = (id: string, zIndex: number) => ({
+ id,
+ startMs: 0,
+ endMs: 1000,
+ type: "text" as const,
+ content: "",
+ textContent: id,
+ position: { x: 0, y: 0 },
+ size: { width: 10, height: 10 },
+ style,
+ zIndex,
+ });
+ const scene = buildSceneDescription(docWithAnnotations([at("top", 5), at("bottom", 1)]));
+ expect(scene.annotations.map((a) => a.id)).toEqual(["bottom", "top"]);
+ });
+
+ it("is empty when the document has no annotations", () => {
+ const scene = buildSceneDescription(docWithAnnotations([]));
+ expect(scene.annotations).toEqual([]);
+ });
+});
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 34d2fae1a..a4214c8d7 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -17,6 +17,7 @@
import type { CameraFullscreenRegion, SpeedRegion } from "@/components/video-editor/types";
import { DEFAULT_CROP_REGION } from "@/components/video-editor/types";
+import { annotationFontSizeFraction } from "@/lib/ai-edition/annotationScale";
import { createId } from "@/lib/ai-edition/document/ids";
import { pickOutputDims } from "@/lib/ai-edition/document/outputFormat";
import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
@@ -83,6 +84,78 @@ export interface SceneSpeedRegion {
clipIndex?: number;
}
+/** A timeline annotation (`document.annotations`), projected onto each clip's source time the
+ * same way zoom and speed regions are.
+ *
+ * Until now annotations never crossed this bridge at all: `AnnotationLayer` draws them as DOM
+ * siblings of the preview, so they showed up in the preview and were simply absent from every
+ * render. Sending them here is what lets the compositor draw them into the actual output.
+ *
+ * Coordinate space, which the renderer must match exactly: `x`/`y`/`w`/`h` are fractions of the
+ * SCREEN layer's rect, not of the output frame — the web overlay is handed
+ * `layout.screenRect` as its container. And they are deliberately NOT affected by the zoom
+ * crop: the overlay is a sibling of the element carrying the zoom transform, so annotations
+ * hold still while the content zooms underneath them. */
+export interface SceneAnnotation {
+ id: string;
+ startSec: number;
+ endSec: number;
+ /** See `SceneZoomRegion.clipIndex`. */
+ clipIndex?: number;
+ kind: "text" | "image" | "figure" | "blur";
+ /** Rect as fractions of the screen layer (x, y top-left). */
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ /** Paint order among annotations; the compositor draws ascending. */
+ zIndex: number;
+ /** Present for `kind: "text"`. Colours are CSS strings, parsed native-side like the
+ * background colour is (`parse_hex`); `"transparent"` means no fill. */
+ text?: {
+ content: string;
+ color: string;
+ backgroundColor: string;
+ /** Font size as a FRACTION of the screen rect's height, like everything else in this
+ * struct — multiply by the rect's height in output pixels. See `annotationScale.ts`:
+ * the preview applies the identical product against its own box, so preview and render
+ * agree at any resolution. */
+ fontSizeRel: number;
+ fontFamily: string;
+ fontWeight: "normal" | "bold";
+ fontStyle: "normal" | "italic";
+ textDecoration: "none" | "underline";
+ textAlign: "left" | "center" | "right";
+ animation: string | null;
+ };
+ /** Present for `kind: "image"` — the authored `imageContent` (path or data URI). */
+ imagePath?: string;
+ /** Present for `kind: "figure"`. */
+ figure?: {
+ direction:
+ | "up"
+ | "down"
+ | "left"
+ | "right"
+ | "up-right"
+ | "up-left"
+ | "down-right"
+ | "down-left";
+ color: string;
+ strokeWidth: number;
+ };
+ /** Present for `kind: "blur"`. `freehandPoints` are fractions of the screen layer, same
+ * space as the rect. */
+ blur?: {
+ style: "blur" | "mosaic";
+ shape: "rectangle" | "oval" | "freehand";
+ color: "white" | "black";
+ intensity: number;
+ blockSize: number;
+ freehandPoints?: Array<{ x: number; y: number }>;
+ };
+}
+
/** Normalized rect in 0..1 of the output frame (x, y top-left; width, height). */
export interface SceneRect {
x: number;
@@ -248,6 +321,11 @@ export interface SceneDescription {
effects: SceneEffects;
background: SceneBackground;
zoomRegions: SceneZoomRegion[];
+ /**
+ * Annotations projected onto each clip's source time, ascending by `zIndex` so the
+ * compositor can draw them in order without re-sorting. Empty when none set.
+ */
+ annotations: SceneAnnotation[];
/**
* "Full Camera" regions projected onto each clip's source time (one entry per
* source-time span after `projectRegionsToSourceTime`). Empty when none set.
@@ -408,6 +486,14 @@ export function buildSceneDescription(
document.timeline.clips,
() => createId("zoom"),
);
+ // Same raw→source projection as the zoom regions above, for the same reason: annotations are
+ // authored in RAW document time and the compositor matches each frame's SOURCE time.
+ const projectedAnnotations = projectRegionsToSource(
+ document.annotations ?? [],
+ visibleClips,
+ document.timeline.clips,
+ () => createId("ann"),
+ );
const projectedCameraFullscreenRegions = projectRegionsToSource(
((document.legacyEditor as Record<string, unknown> | null)?.cameraFullscreenRegions as
| CameraFullscreenRegion[]
@@ -600,6 +686,81 @@ export function buildSceneDescription(
rotation: region.rotationPreset ?? null,
clipIndex: region.clipIndex,
})),
+ annotations: projectedAnnotations
+ .map((region) => {
+ const style = region.style;
+ const base = {
+ id: region.id,
+ startSec: region.startMs / 1000,
+ endSec: region.endMs / 1000,
+ clipIndex: region.clipIndex,
+ kind: region.type,
+ // Authored as percentages of the screen rect; the native side wants fractions.
+ x: region.position.x / 100,
+ y: region.position.y / 100,
+ w: region.size.width / 100,
+ h: region.size.height / 100,
+ zIndex: region.zIndex,
+ } as const;
+ if (region.type === "text") {
+ return {
+ ...base,
+ text: {
+ // `textContent` is the live field the inspector edits; `content` is the
+ // older single-field form still present on migrated documents.
+ content: region.textContent ?? region.content ?? "",
+ color: style.color,
+ backgroundColor: style.backgroundColor,
+ fontSizeRel: annotationFontSizeFraction(style.fontSize),
+ fontFamily: style.fontFamily,
+ fontWeight: style.fontWeight,
+ fontStyle: style.fontStyle,
+ textDecoration: style.textDecoration,
+ textAlign: style.textAlign,
+ animation: style.textAnimation ?? null,
+ },
+ };
+ }
+ if (region.type === "image") {
+ // `content` first: that is the field the live overlay reads (it checks
+ // `content.startsWith("data:image")`), `imageContent` being the parallel slot
+ // older documents used. Reading them the other way round would render an image
+ // the preview isn't showing.
+ return { ...base, imagePath: region.content || region.imageContent || "" };
+ }
+ if (region.type === "figure") {
+ const figure = region.figureData;
+ return {
+ ...base,
+ figure: {
+ direction: figure?.arrowDirection ?? "right",
+ color: figure?.color ?? "#34B27B",
+ strokeWidth: figure?.strokeWidth ?? 4,
+ },
+ };
+ }
+ const blur = region.blurData;
+ return {
+ ...base,
+ blur: {
+ style: blur?.type ?? "mosaic",
+ shape: blur?.shape ?? "rectangle",
+ color: blur?.color ?? "white",
+ intensity: blur?.intensity ?? 12,
+ blockSize: blur?.blockSize ?? 12,
+ ...(blur?.freehandPoints
+ ? {
+ freehandPoints: blur.freehandPoints.map((p) => ({
+ x: p.x / 100,
+ y: p.y / 100,
+ })),
+ }
+ : {}),
+ },
+ };
+ })
+ // Ascending zIndex so the compositor paints in order without sorting per frame.
+ .sort((a, b) => a.zIndex - b.zIndex),
cameraFullscreenRegions: projectedCameraFullscreenRegions.map((region) => ({
startSec: region.startMs / 1000,
endSec: region.endMs / 1000,