diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rs index d79d85ab6a..98491570e0 100644 --- a/crates/compositor/src/compositor_linux.rs +++ b/crates/compositor/src/compositor_linux.rs @@ -1422,7 +1422,7 @@ impl Compositor { ) }; let params: Vec = - crate::shader_fx::pack_params(effect).iter().flat_map(|v| v.to_ne_bytes()).collect(); + crate::shader_fx::pack_params(effect, ctx.region[2]).iter().flat_map(|v| v.to_ne_bytes()).collect(); let uniform = |label: &str, contents: &[u8]| { self.gpu.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), @@ -7305,6 +7305,19 @@ mod tests { assert_eq!(corner, [0, 255, 0]); } + /// Une piste d'images clés remplace la valeur fixe : `tint` est vert dans `values`, sa piste le + /// tient bleu jusqu'à 1,5 s. À 2 s de programme, soit 1 s dans la région, le shader lit bleu. + #[test] + fn an_animated_parameter_reaches_the_shader_at_its_keyframe_value() { + let mut effect = fx(TINT, "image"); + effect["animate"] = serde_json::json!({"tint": [ + {"atSec": 0.0, "value": [0.0, 0.0, 1.0, 1.0], "hold": true}, + {"atSec": 1.5, "value": [0.0, 1.0, 0.0, 1.0]}, + ]}); + let Some(corner) = corner_under(serde_json::json!([effect])) else { return }; + assert_eq!(corner, [0, 0, 255]); + } + /// La scène de ces tests masque le curseur (`cursor.show` faux) : rien n'est dessiné, mais un /// effet voit toujours la pointe et le clic de l'enregistrement (`effect_pointer`). Il peint /// `ctx.cursor.z` en rouge et `ctx.clicks[0].w` en vert : jaune, il a vu les deux. diff --git a/crates/compositor/src/compositor_macos.rs b/crates/compositor/src/compositor_macos.rs index 4e7e98cd6c..87cc42deaf 100644 --- a/crates/compositor/src/compositor_macos.rs +++ b/crates/compositor/src/compositor_macos.rs @@ -1095,7 +1095,7 @@ impl Compositor { // On ne lit pas la cible sur laquelle on dessine : copie dans `ann_copy` (les flous // d'annotation et le cristal de Prism Glow l'ont déjà lue). self.snapshot(cmd, dst, false); - let params = crate::shader_fx::pack_params(effect); + let params = crate::shader_fx::pack_params(effect, ctx.region[2]); let e = self.begin_pass(cmd, dst, None, &pipeline)?; e.set_fragment_texture(0, Some(&self.ann_copy)); // `footage()`, liée seulement pour un effet qui la lit : les autres ne la déclarent pas. @@ -5266,6 +5266,19 @@ mod tests { assert_eq!(corner, [0, 255, 0]); } + /// Une piste d'images clés remplace la valeur fixe : `tint` est vert dans `values`, sa piste le + /// tient bleu jusqu'à 1,5 s. À 2 s de programme, soit 1 s dans la région, le shader lit bleu. + #[test] + fn an_animated_parameter_reaches_the_shader_at_its_keyframe_value() { + let mut effect = fx(TINT, "image"); + effect["animate"] = serde_json::json!({"tint": [ + {"atSec": 0.0, "value": [0.0, 0.0, 1.0, 1.0], "hold": true}, + {"atSec": 1.5, "value": [0.0, 1.0, 0.0, 1.0]}, + ]}); + let Some(corner) = corner_under(serde_json::json!([effect])) else { return }; + assert_eq!(corner, [0, 0, 255]); + } + /// `fx_to_footage` retrouve le point du métrage que le compositeur a dessiné sous un pixel, /// à plat, sous un angle fixe (warp bilinéaire) et sous la caméra réelle (homographie), et /// `fx_from_footage` le ramène sur ce pixel. En 1080p, l'arrondi 8 bits et le demi-pixel diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rs index 3231bf5d6a..bf8198edfd 100644 --- a/crates/compositor/src/compositor_windows.rs +++ b/crates/compositor/src/compositor_windows.rs @@ -1067,7 +1067,7 @@ impl Compositor { cb as *const crate::shader_fx::FxContext as *const u8, std::mem::size_of::(), ); - let params = crate::shader_fx::pack_params(effect); + let params = crate::shader_fx::pack_params(effect, cb.region[2]); let params_bytes = std::slice::from_raw_parts( params.as_ptr() as *const u8, (params.len() * 4).min(crate::shader_fx::PARAMS_BUFFER_BYTES), @@ -4237,6 +4237,19 @@ mod tests { assert_eq!(corner, [0, 255, 0]); } + /// Une piste d'images clés remplace la valeur fixe : `tint` est vert dans `values`, sa piste le + /// tient bleu jusqu'à 1,5 s. À 2 s de programme, soit 1 s dans la région, le shader lit bleu. + #[test] + fn an_animated_parameter_reaches_the_shader_at_its_keyframe_value() { + let mut effect = fx(TINT, "image"); + effect["animate"] = serde_json::json!({"tint": [ + {"atSec": 0.0, "value": [0.0, 0.0, 1.0, 1.0], "hold": true}, + {"atSec": 1.5, "value": [0.0, 1.0, 0.0, 1.0]}, + ]}); + let Some(corner) = corner_under(serde_json::json!([effect])) else { return }; + assert_eq!(corner, [0, 0, 255]); + } + /// `fx_to_footage` retrouve le point du métrage que le compositeur a dessiné sous un pixel, /// à plat, sous un angle fixe (warp bilinéaire) et sous la caméra réelle (homographie), et /// `fx_from_footage` le ramène sur ce pixel. En 1080p, l'arrondi 8 bits et le demi-pixel diff --git a/crates/compositor/src/regions.rs b/crates/compositor/src/regions.rs index ad7865f025..91ce7c6115 100644 --- a/crates/compositor/src/regions.rs +++ b/crates/compositor/src/regions.rs @@ -327,7 +327,7 @@ const ZOOM_TRANSITION_BASE_S: f32 = 0.6; const ZOOM_TRANSITION_PER_LN_S: f32 = 0.55; // ω·T du ressort de `ease_spring` : assez haut pour que la fin de fenêtre soit à l'arrêt (1,5 % // du pic), assez bas pour ne pas figer la seconde moitié. -const SPRING_OMEGA_T: f32 = 7.0; +pub(crate) const SPRING_OMEGA_T: f32 = 7.0; // port de `CHAINED_ZOOM_PAN_GAP_MS` / `CONNECTED_ZOOM_PAN_DURATION_MS` (TS). const CHAINED_ZOOM_PAN_GAP_S: f32 = 1.5; const CONNECTED_ZOOM_PAN_DURATION_S: f32 = 1.0; @@ -347,7 +347,7 @@ fn sample_cubic_bezier_derivative(a1: f32, a2: f32, t: f32) -> f32 { } /// Port direct de `cubicBezier` (TS) : Newton-Raphson puis bissection de repli. -fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 { +pub(crate) fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 { let target_x = clamp01(t); let mut solved_t = target_x; for _ in 0..8 { @@ -395,7 +395,7 @@ fn scale_lerp(a: f32, b: f32, t: f32) -> f32 { /// Montée d'un ressort critique (sans rebond), ramenée pile sur [0, 1] à la fin de la fenêtre : /// vitesse nulle au départ, donc pas d'à-coup, et arrivée amortie. L'ancienne courbe du zoom /// (cubic-bezier(0.16, 1, 0.3, 1)) partait à pleine vitesse dès la première frame. -fn ease_spring(t: f32) -> f32 { +pub(crate) fn ease_spring(t: f32) -> f32 { let x = SPRING_OMEGA_T * clamp01(t); let end = 1.0 - (1.0 + SPRING_OMEGA_T) * (-SPRING_OMEGA_T).exp(); (1.0 - (1.0 + x) * (-x).exp()) / end diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs index b4a5fb11d9..8d5a65242f 100644 --- a/crates/compositor/src/scene.rs +++ b/crates/compositor/src/scene.rs @@ -666,6 +666,30 @@ pub struct SceneShaderEffect { /// Les valeurs, déjà normalisées par l'app : un nombre, ou 2 ou 4 floats. #[serde(default)] pub values: std::collections::HashMap, + /// Les paramètres animés : nom → images clés triées par `at_sec`. Une piste remplace la valeur + /// de `values` ; absente (le cas courant), le paramètre garde sa valeur fixe. + #[serde(default)] + pub animate: std::collections::HashMap>, +} + +/// Une image clé d'un paramètre animé. `at_sec` est compté depuis le début de la pilule, sur +/// l'horloge de `ctx.region.z`. La courbe va de cette image clé à la suivante : linéaire par +/// défaut, `bezier` (x1, y1, x2, y2), `spring` (le rebond, 0 à 0,9) ou `hold` (palier). +/// +/// Des champs optionnels plutôt qu'une enum, pour la même raison que `SceneAnnotation::space` : +/// une forme de courbe inconnue d'un binaire plus ancien retombe sur le linéaire au lieu de faire +/// échouer toute la scène. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ShaderKeyframe { + pub at_sec: f32, + pub value: ShaderParamValue, + #[serde(default)] + pub bezier: Option<[f32; 4]>, + #[serde(default)] + pub spring: Option, + #[serde(default)] + pub hold: bool, } fn default_contract() -> u32 { diff --git a/crates/compositor/src/shader_fx.rs b/crates/compositor/src/shader_fx.rs index 0f19f01ec7..6e6cbe7325 100644 --- a/crates/compositor/src/shader_fx.rs +++ b/crates/compositor/src/shader_fx.rs @@ -12,7 +12,9 @@ //! l'autre au seek) et l'export (qui les rend dans l'ordre) d'accord. use crate::frame_geometry::FootageQuad; -use crate::scene::{SceneShaderEffect, ShaderEffectTarget, ShaderParamDecl, ShaderParamType, ShaderParamValue}; +use crate::scene::{ + SceneShaderEffect, ShaderEffectTarget, ShaderKeyframe, ShaderParamDecl, ShaderParamType, ShaderParamValue, +}; use std::hash::{Hash, Hasher}; /// La version du contrat que ce prélude implémente. Un prélude livré ne change plus : une entrée @@ -863,9 +865,49 @@ pub fn context( } } +/// La valeur d'une piste d'images clés au temps `t` (secondes depuis le début de la pilule) : +/// palier avant la première et après la dernière, interpolation composante par composante entre +/// deux, selon la courbe de la première. Vide : aucune valeur. +pub fn sample_track(track: &[ShaderKeyframe], t: f32) -> Vec { + let floats = |v: &ShaderParamValue| match v { + ShaderParamValue::Scalar(x) => vec![*x], + ShaderParamValue::Vector(x) => x.clone(), + }; + let Some(i) = track.iter().rposition(|k| k.at_sec <= t) else { + return track.first().map(|k| floats(&k.value)).unwrap_or_default(); + }; + let (a, Some(b)) = (&track[i], track.get(i + 1)) else { return floats(&track[i].value) }; + let span = b.at_sec - a.at_sec; + if a.hold || span <= 0.0 { + return floats(&a.value); + } + let x = ((t - a.at_sec) / span).clamp(0.0, 1.0); + let k = match (a.bezier, a.spring) { + (Some([x1, y1, x2, y2]), _) => crate::regions::cubic_bezier(x1, y1, x2, y2, x), + (None, Some(bounce)) => spring(bounce, x), + (None, None) => x, + }; + floats(&a.value).iter().zip(floats(&b.value)).map(|(from, to)| from + (to - from) * k).collect() +} + +/// Un ressort sur [0, 1] qui part à vitesse nulle et arrive pile sur 1 à la fin. Sans rebond, +/// c'est le ressort critique des zooms ; avec, l'amortissement baisse (ζ = 1 − rebond) à la même +/// pulsation, et la petite erreur restante en fin de fenêtre est rattrapée linéairement. +fn spring(bounce: f32, t: f32) -> f32 { + let zeta = 1.0 - bounce.clamp(0.0, 0.9); + if zeta >= 0.999 { + return crate::regions::ease_spring(t); + } + let w = crate::regions::SPRING_OMEGA_T; + let wd = w * (1.0 - zeta * zeta).sqrt(); + let x = |t: f32| 1.0 - (-zeta * w * t).exp() * ((wd * t).cos() + zeta * w / wd * (wd * t).sin()); + x(t) + (1.0 - x(1.0)) * t +} + /// Les paramètres de la région, rangés comme la struct `FxParams` générée (règles d'alignement de -/// WGSL), en mots de 4 octets. Une valeur absente vaut 0 : l'app envoie déjà les défauts. -pub fn pack_params(effect: &SceneShaderEffect) -> Vec { +/// WGSL), en mots de 4 octets. Une valeur absente vaut 0 : l'app envoie déjà les défauts. Un +/// paramètre animé prend la valeur de sa piste à `region_sec` (`ctx.region.z`). +pub fn pack_params(effect: &SceneShaderEffect, region_sec: f32) -> Vec { let mut words: Vec = Vec::new(); let mut offset = 0usize; for p in &effect.params { @@ -873,10 +915,11 @@ pub fn pack_params(effect: &SceneShaderEffect) -> Vec { offset = offset.div_ceil(align) * align; let end = offset + size; words.resize(end / 4, 0.0); - let value: Vec = match effect.values.get(&p.name) { - Some(ShaderParamValue::Scalar(v)) => vec![*v], - Some(ShaderParamValue::Vector(v)) => v.clone(), - None => Vec::new(), + let value: Vec = match (effect.animate.get(&p.name), effect.values.get(&p.name)) { + (Some(track), _) if !track.is_empty() => sample_track(track, region_sec), + (_, Some(ShaderParamValue::Scalar(v))) => vec![*v], + (_, Some(ShaderParamValue::Vector(v))) => v.clone(), + (_, None) => Vec::new(), }; for (i, v) in value.into_iter().take(size / 4).enumerate() { words[offset / 4 + i] = v; @@ -999,6 +1042,7 @@ pub(crate) fn test_effect(code: &str, params: Vec, values: &[(& code: code.into(), params, values: values.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(), + animate: Default::default(), } } @@ -1111,7 +1155,7 @@ mod tests { ("at", ShaderParamValue::Vector(vec![7.0, 8.0])), ("b", ShaderParamValue::Scalar(9.0)), ]; - let words = pack_params(&test_effect(code, params, &values)); + let words = pack_params(&test_effect(code, params, &values), 0.0); assert_eq!(words.len() * 4, (*span as usize).div_ceil(16) * 16); let first = |name: &str| members.iter().find(|m| m.name.as_deref() == Some(name)).unwrap().offset as usize / 4; assert_eq!(words[first("a")], 1.0); @@ -1121,6 +1165,111 @@ mod tests { assert_eq!(words[first("b")], 9.0); } + fn key(at_sec: f32, value: ShaderParamValue) -> ShaderKeyframe { + ShaderKeyframe { at_sec, value, bezier: None, spring: None, hold: false } + } + + fn scalar(track: &[ShaderKeyframe], t: f32) -> f32 { + sample_track(track, t)[0] + } + + #[test] + fn a_track_holds_outside_its_keyframes_and_is_linear_between() { + let track = [key(1.0, ShaderParamValue::Scalar(2.0)), key(3.0, ShaderParamValue::Scalar(6.0))]; + assert_eq!(scalar(&track, 0.0), 2.0); + assert_eq!(scalar(&track, 2.0), 4.0); + assert_eq!(scalar(&track, 3.0), 6.0); + assert_eq!(scalar(&track, 10.0), 6.0); + assert_eq!(sample_track(&[key(0.5, ShaderParamValue::Scalar(7.0))], 9.0), vec![7.0]); + // Composante par composante : une couleur, un point. + let color = [ + key(0.0, ShaderParamValue::Vector(vec![0.0, 0.0, 0.0, 1.0])), + key(2.0, ShaderParamValue::Vector(vec![1.0, 0.5, 0.0, 1.0])), + ]; + assert_eq!(sample_track(&color, 1.0), vec![0.5, 0.25, 0.0, 1.0]); + } + + #[test] + fn a_bezier_segment_follows_the_regions_curve() { + let mut from = key(0.0, ShaderParamValue::Scalar(0.0)); + from.bezier = Some([0.42, 0.0, 0.58, 1.0]); + let track = [from, key(2.0, ShaderParamValue::Scalar(10.0))]; + for t in [0.3_f32, 0.5, 1.0, 1.7] { + let expected = 10.0 * crate::regions::cubic_bezier(0.42, 0.0, 0.58, 1.0, t / 2.0); + assert_eq!(scalar(&track, t), expected); + } + assert!(scalar(&track, 0.3) < 1.5, "ease-in-out starts slow"); + } + + #[test] + fn a_spring_lands_exactly_on_the_next_keyframe() { + for bounce in [0.0_f32, 0.3, 0.9] { + let mut from = key(1.0, ShaderParamValue::Scalar(0.0)); + from.spring = Some(bounce); + let track = [from, key(2.0, ShaderParamValue::Scalar(5.0))]; + assert_eq!(scalar(&track, 1.0), 0.0); + assert!((scalar(&track, 1.999_99) - 5.0).abs() < 1e-3, "bounce {bounce}"); + assert_eq!(scalar(&track, 2.0), 5.0); + } + // Avec du rebond, la courbe dépasse la cible avant d'y revenir. + let mut from = key(0.0, ShaderParamValue::Scalar(0.0)); + from.spring = Some(0.5); + let track = [from, key(1.0, ShaderParamValue::Scalar(1.0))]; + assert!((1..100).any(|i| scalar(&track, i as f32 / 100.0) > 1.01)); + assert_eq!(spring(0.0, 0.4), crate::regions::ease_spring(0.4)); + } + + /// Un toggle arrive en `hold` (la scène le force) : il saute à chaque image clé, sans valeur + /// intermédiaire. + #[test] + fn a_hold_segment_steps_at_the_keyframe() { + let mut off = key(0.0, ShaderParamValue::Scalar(0.0)); + off.hold = true; + let track = [off, key(1.0, ShaderParamValue::Scalar(1.0))]; + assert_eq!(scalar(&track, 0.999), 0.0); + assert_eq!(scalar(&track, 1.0), 1.0); + } + + /// Ce qui garde un projet sans animation identique à avant : sans piste, les mots sont ceux des + /// valeurs, quel que soit le temps. + #[test] + fn without_a_track_the_packed_words_are_the_values() { + let params = vec![decl("a", ShaderParamType::Number), decl("tint", ShaderParamType::Color)]; + let values = [("a", ShaderParamValue::Scalar(0.25)), ("tint", ShaderParamValue::Vector(vec![0.1, 0.2, 0.3, 1.0]))]; + let effect = test_effect(VIGNETTE, params, &values); + let expected = vec![0.25, 0.0, 0.0, 0.0, 0.1, 0.2, 0.3, 1.0]; + assert_eq!(pack_params(&effect, 0.0), expected); + assert_eq!(pack_params(&effect, 42.0), expected); + } + + #[test] + fn an_animated_parameter_packs_its_sampled_value() { + let params = vec![decl("a", ShaderParamType::Number), decl("b", ShaderParamType::Number)]; + let values = [("a", ShaderParamValue::Scalar(9.0)), ("b", ShaderParamValue::Scalar(3.0))]; + let mut effect = test_effect(VIGNETTE, params, &values); + effect.animate.insert( + "a".into(), + vec![key(0.0, ShaderParamValue::Scalar(0.0)), key(2.0, ShaderParamValue::Scalar(1.0))], + ); + assert_eq!(pack_params(&effect, 1.0), vec![0.5, 3.0, 0.0, 0.0]); + } + + #[test] + fn a_scene_without_animate_parses_and_one_with_it_reads_every_curve() { + let plain: SceneShaderEffect = + serde_json::from_str(r#"{"startSec":0,"endSec":1,"code":"x","values":{"a":1}}"#).unwrap(); + assert!(plain.animate.is_empty()); + let json = r#"{"startSec":0,"endSec":1,"code":"x","animate":{"a":[ + {"atSec":0,"value":0,"bezier":[0.42,0,1,1]},{"atSec":1,"value":1,"spring":0.4}, + {"atSec":2,"value":2,"hold":true},{"atSec":3,"value":3,"future":"curve"}]}}"#; + let animated: SceneShaderEffect = serde_json::from_str(json).unwrap(); + let track = &animated.animate["a"]; + assert_eq!(track[0].bezier, Some([0.42, 0.0, 1.0, 1.0])); + assert_eq!(track[1].spring, Some(0.4)); + assert!(track[2].hold); + assert_eq!(track[3].bezier, None); + } + #[test] fn the_context_matches_its_wgsl_struct() { let parsed = analyze(VIGNETTE, &[decl("strength", ShaderParamType::Number)]).unwrap(); diff --git a/crates/compositor/tests/render_frames_match_export.rs b/crates/compositor/tests/render_frames_match_export.rs index 40a805e497..fa713e8fc8 100644 --- a/crates/compositor/tests/render_frames_match_export.rs +++ b/crates/compositor/tests/render_frames_match_export.rs @@ -4,7 +4,8 @@ //! ici à la marche complète, où toutes les frames sont demandées et aucune n'est sautée. //! //! La scène met deux coupes du même fichier, une région 2× dans la seconde, un effet shader qui -//! lit le temps programme, et le curseur de la prise s'il a sa piste à côté. +//! lit le temps programme et un paramètre animé par images clés, et le curseur de la prise s'il a +//! sa piste à côté. //! //! La sortie est à 24 i/s : sur une source à 30 i/s, ses instants tombent entre deux frames //! source, là où un rattrapage qui viserait la cible au lieu de la précéder montrerait la frame @@ -51,8 +52,13 @@ fn scene_json(source: &str) -> String { "output": {{"width":640,"height":360,"fps":null}}, "shaderEffects": [{{ "clipIndex": 1, "startSec": 6.0, "endSec": 20.0, "target": "image", "contract": 1, - "code": "fn effect(uv: vec2) -> vec4 {{ let c = frame(uv); return vec4(c.rgb * (0.6 + 0.4 * sin(ctx.time * 3.0)), 1.0); }}", - "params": [], "values": {{}} + "code": "fn effect(uv: vec2) -> vec4 {{ let c = frame(uv); return vec4(c.rgb * (0.6 + 0.4 * sin(ctx.time * 3.0)) * params.gain, 1.0); }}", + "params": [{{"name":"gain","type":"number"}}], "values": {{"gain":0.5}}, + "animate": {{"gain": [ + {{"atSec":0,"value":0.2,"bezier":[0.42,0,0.58,1]}}, + {{"atSec":4,"value":1.0,"spring":0.4}}, + {{"atSec":9,"value":0.6}} + ]}} }}] }}"##, clips = clips.join(",") diff --git a/docs/shader-effects.md b/docs/shader-effects.md index ef9db3a477..82e4202431 100644 --- a/docs/shader-effects.md +++ b/docs/shader-effects.md @@ -92,6 +92,7 @@ export const shaderEffectRangeSchema = endGteStart(z.object({ ...clipAnchorShape, effectId: z.string().min(1), values: z.record(z.string(), shaderEffectValueSchema).default({}), + animate: z.record(z.string(), z.array(keyframe).min(1).max(64)).optional(), // B.6 target: z.enum(["image", "text", "both"]).default("image"), }), "endMs", "startMs"); @@ -103,6 +104,8 @@ shaderEffectRanges: z.array(shaderEffectRangeSchema).optional(), - **`values`** ne porte que ce qui diffère du `default` de la définition. Une valeur hors bornes est ramenée dans ses bornes à l'écriture (les outils) et à la lecture (la scène), sans erreur. Le parse ne le peut pas : les bornes sont dans la définition, pas dans la région. +- **Une valeur est fixe sur la région, sauf si le paramètre est animé** (`animate`, B.6) : il suit + alors ses images clés, et sa valeur de `values` ne sert plus. - **Les `label`** sont écrits par l'agent, dans la langue de l'utilisateur, et affichés tels quels. Ils ne passent pas par l'i18n : c'est du contenu, pas de l'interface. - **Une pilule, ce sont les fragments identiques et contigus** (`regionIdentityKey`), comme pour @@ -171,7 +174,10 @@ ajoute à chaque fragment ce que le compositeur ne peut pas recalculer : "target": "image", "contract": 1, "code": "fn effect(uv: vec2) -> vec4 { … }", "params": [ { "name": "strength", "type": "number" } ], - "values": { "strength": 1.0 } + "values": { "strength": 1.0 }, + "animate": { "strength": [ { "atSec": 0, "value": 0, "bezier": [0, 0, 0.58, 1] }, + { "atSec": 0.6, "value": 1.5, "spring": 0.3 }, + { "atSec": 2, "value": 1 } ] } }] ``` @@ -181,10 +187,37 @@ ajoute à chaque fragment ce que le compositeur ne peut pas recalculer : 2 floats, et une valeur absente prend son `default`. - **Le packing dans l'uniform** se fait côté Rust, au même endroit que la struct WGSL générée. Le layout n'a qu'une source. +- **`animate` est absent** quand la région n'anime rien : la scène d'un projet sans animation est + identique, octet pour octet, à celle d'avant (B.6). - **Les fragments sous un trim** (`underTrim`) restent dans la scène, comme pour les autres régions. Ils se dessinent quand la tête de lecture est posée sur le trim, et l'export ne les rencontre jamais. +### B.6 Les paramètres animés + +Une région peut faire varier un paramètre dans le temps au lieu de le tenir fixe : `animate` donne, +par nom de paramètre, une liste de 1 à 64 images clés `{ atSec, value, ease? }`. + +- **`atSec`** compte depuis le début de la pilule, sur l'horloge de `ctx.region.z`. Avant la + première image clé le paramètre tient sa valeur, après la dernière aussi. +- **`ease`** donne la forme du trajet jusqu'à l'image clé suivante : `linear` (défaut), `hold`, + `ease-in`, `ease-out`, `ease-in-out`, une cubic-bezier `[x1, y1, x2, y2]` (x dans 0..1), ou + `{ spring: { bounce } }` (rebond de 0 à 0,9). Un toggle tient toujours sa valeur : il saute à + chaque image clé. +- **À l'écriture**, les images clés sont triées par `atSec` et chaque valeur est ramenée dans ses + bornes comme une valeur simple. Un nom non déclaré, ou une valeur du mauvais type, est refusé + par l'outil. +- **Pourquoi.** Un minutage (un fondu, une pulsation à une seconde donnée) reste réglable sans + réécrire le shader, qui lit `params.` comme d'habitude. +- **Évalué sur le CPU, à chaque frame,** dans `pack_params` (`shader_fx.rs`), que les trois + backends appellent avec `ctx.region.z`. Aucun changement du prélude ni des bindings ; la preview + et l'export passent par `compose_frame` et restent identiques. Les courbes nommées deviennent + des cubic-bezier dans la projection de scène, résolues par le solveur des zooms (`regions.rs`). +- **Additif, sans montée de `schemaVersion`** (K.1) : un document sans `animate` se lit et + s'enregistre tel quel, et sans piste `pack_params` rend exactement les mêmes mots qu'avant. +- **L'inspecteur masque le contrôle** d'un paramètre animé sur la région sélectionnée : un curseur + n'y changerait rien à l'écran. + --- ## C. Le contrat WGSL (version 1) @@ -534,9 +567,9 @@ intégré les reçoit par le même tableau. | Outil | Arguments | Effet | |---|---|---| -| `addEffect` | `startSec`, `endSec` (secondes de règle), `effect` **ou** `effectId`, `values?`, `target?` | Pose une région. Avec `effect` (`name`, `description`, `code`, `params?`), crée d'abord la définition. Avec `effectId`, réutilise une définition du projet. | -| `setEffect` | `effectRegionId`, `startSec?`, `endSec?`, `values?`, `target?` | Change une région. Seuls les champs passés changent. | -| `setEffectDefinition` | `effectId`, `name?`, `description?`, `code?`, `params?` | Change une définition, donc toutes les régions qui l'utilisent. Un code neuf est compilé avant d'être accepté. Les `values` d'un paramètre retiré tombent, un paramètre nouveau prend son `default`. | +| `addEffect` | `startSec`, `endSec` (secondes de règle), `effect` **ou** `effectId`, `values?`, `animate?`, `target?` | Pose une région. Avec `effect` (`name`, `description`, `code`, `params?`), crée d'abord la définition. Avec `effectId`, réutilise une définition du projet. | +| `setEffect` | `effectRegionId`, `startSec?`, `endSec?`, `values?`, `animate?`, `target?` | Change une région. Seuls les champs passés changent. Dans `animate`, un paramètre passé remplace toute sa liste, une liste vide le retire. | +| `setEffectDefinition` | `effectId`, `name?`, `description?`, `code?`, `params?` | Change une définition, donc toutes les régions qui l'utilisent. Un code neuf est compilé avant d'être accepté. Les `values` et les images clés d'un paramètre retiré tombent, comme les images clés d'un paramètre qui change de type ; un paramètre nouveau prend son `default`. | | `getEffect` | `effectId` | Lecture : la définition entière, code compris. | | `removeModifier` | `id` | Retire une région d'effet, comme un zoom. | @@ -683,7 +716,8 @@ l'ordre : - **le nom de l'effet,** sans phrase d'explication sous les contrôles ; - **un contrôle par paramètre déclaré,** généré depuis `params` (curseur, interrupteur, couleur - ou point), qui écrit `values` sur la région ; + ou point), qui écrit `values` sur la région ; pas de contrôle pour un paramètre animé sur la + région (B.6) ; - **la cible :** « Image », « Textes » ou « Les deux » (`target`) ; - **le palier de coût,** en un mot (léger, moyen, lourd, très lourd), sans phrase ; - **le code,** replié par défaut, en lecture seule, avec un bouton copier ; l'édition du code diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts index 44fa595e36..d969e5c055 100644 --- a/electron/ai-edition/agent-tools.test.ts +++ b/electron/ai-edition/agent-tools.test.ts @@ -221,6 +221,7 @@ describe("the mutating-tool table", () => { "setEffect", "setEffectDefinition", "setEditorSettings", + "applyStylePreset", "setLayoutPreset", "setSpeed", "setTrim", @@ -3505,6 +3506,56 @@ describe("region tools reach the inspector's settings (#1180)", () => { expect(added.payload).toMatchObject({ type: "text", fontSize: 48 }); }); + it("sets a text's font family from the shipped list, refits its box, and refuses another", () => { + const added = run(fixtureDocument(), "addAnnotation", { + startSec: 1, + endSec: 3, + text: "Shipped fonts", + fontFamily: "Oswald", + }); + expect(added.ok).toBe(true); + expect(added.document?.annotations[0].style.fontFamily).toBe("Oswald"); + expect(added.payload).toMatchObject({ fontFamily: "Oswald" }); + expect(snapshot(added.document).annotations[0]).toMatchObject({ fontFamily: "Oswald" }); + + // The box is the size of its words, measured in the face it is drawn in: a new face + // refits it. + vi.stubEnv("OPENSCREEN_FONTS_DIR", path.resolve(__dirname, "../../public/fonts")); + try { + const inShippedFonts = run(fixtureDocument(), "addAnnotation", { + startSec: 1, + endSec: 3, + text: "Shipped fonts", + fontFamily: "Oswald", + }); + const mono = run(inShippedFonts.document as AxcutDocument, "setAnnotation", { + annotationId: inShippedFonts.payload.annotationId, + fontFamily: "IBM Plex Mono", + }); + expect(mono.ok).toBe(true); + const stored = mono.document?.annotations[0]; + expect(stored?.style.fontFamily).toBe("IBM Plex Mono"); + expect(stored?.size.width).toBeGreaterThan( + inShippedFonts.document?.annotations[0].size.width ?? Number.POSITIVE_INFINITY, + ); + } finally { + vi.unstubAllEnvs(); + } + + // The default text reads back the family the renderer draws it in. + const plain = run(fixtureDocument(), "addAnnotation", { startSec: 1, endSec: 3, text: "Hi" }); + expect(plain.payload).toMatchObject({ fontFamily: "Inter" }); + + const comic = run(fixtureDocument(), "addAnnotation", { + startSec: 1, + endSec: 3, + text: "Hi", + fontFamily: "Comic Sans MS", + }); + expect(comic.ok).toBe(false); + expect(comic.document).toBeUndefined(); + }); + it("adds a privacy blur on the recording's picture, sized and placed as asked", () => { const added = run(fixtureDocument(), "addAnnotation", { startSec: 1, @@ -3741,6 +3792,53 @@ describe("clip structure (#1180)", () => { expect(run(twoTakes(), "insertClip", { assetId: "asset_2", sourceStartSec: 9 }).ok).toBe(false); }); + /** An imported image: a video asset whose file is the hold generated from it. */ + function withStill(): AxcutDocument { + const document = twoTakes(); + return { + ...document, + assets: [ + ...document.assets, + { + id: "still_1", + kind: "video", + label: "logo.png", + originalPath: "C:/rec/stills/logo_1a2b3c4d_5000.still.mp4", + durationSec: 5, + video: { codec: "h264", width: 802, height: 602, fps: 30 }, + } as AxcutDocument["assets"][number], + ], + }; + } + + it("insertClip shows a still for its whole hold by default", () => { + const result = run(withStill(), "insertClip", { assetId: "still_1" }); + expect(result.ok).toBe(true); + expect((result.document as AxcutDocument).timeline.clips.at(-1)).toMatchObject({ + assetId: "still_1", + sourceStartSec: 0, + sourceEndSec: 5, + }); + }); + + it("setClipRange shortens a still and never takes it past its hold", () => { + const placed = run(withStill(), "insertClip", { assetId: "still_1" }); + const { clipId } = JSON.parse(placed.resultJson); + const document = placed.document as AxcutDocument; + const shorter = run(document, "setClipRange", { clipId, sourceEndSec: 2 }); + expect( + (shorter.document as AxcutDocument).timeline.clips.find((c) => c.id === clipId), + ).toMatchObject({ sourceStartSec: 0, sourceEndSec: 2 }); + // Clamped to the hold, as any video of known length is. + const longer = run(shorter.document as AxcutDocument, "setClipRange", { + clipId, + sourceEndSec: 9, + }); + expect(JSON.parse(longer.resultJson).sourceEndSec).toBe(5); + const past = run(document, "setClipRange", { clipId, sourceStartSec: 6, sourceEndSec: 8 }); + expect(past.ok).toBe(false); + }); + it("duplicateClip puts the copy right after the original, with its own copy of the cuts", () => { const result = run(twoTakes(), "duplicateClip", { clipId: "clip_1" }); const payload = JSON.parse(result.resultJson); @@ -3822,6 +3920,106 @@ describe("clip structure (#1180)", () => { ]); }); + it("setClipRange turns a clip upside down and back, and the snapshot reads it back", () => { + const crop = { x: 0.1, y: 0.2, width: 0.5, height: 0.6 }; + const cropped = run(twoTakes(), "setClipRange", { clipId: "clip_1", cropRegion: crop }) + .document as AxcutDocument; + const turned = run(cropped, "setClipRange", { clipId: "clip_1", rotation: 180 }); + expect(turned.ok).toBe(true); + const document = turned.document as AxcutDocument; + // The range, the crop (in the recording's own coordinates) and the cut stay as they were. + expect(document.timeline.clips[0]).toMatchObject({ + sourceStartSec: 0, + sourceEndSec: 10, + cropRegion: crop, + rotation: 180, + }); + expect(document.timeline.trimRanges).toHaveLength(1); + expect(JSON.parse(turned.resultJson)).toMatchObject({ rotation: 180, cropRegion: crop }); + expect(() => documentSchema.parse(document)).not.toThrow(); + const snapshot = JSON.parse(run(document, "getCurrentDocument", {}).resultJson); + expect(snapshot.clips[0].rotation).toBe(180); + + const upright = run(document, "setClipRange", { clipId: "clip_1", rotation: 0 }); + expect((upright.document as AxcutDocument).timeline.clips[0]).not.toHaveProperty("rotation"); + const plain = JSON.parse( + run(upright.document as AxcutDocument, "getCurrentDocument", {}).resultJson, + ); + expect(plain.clips[0]).not.toHaveProperty("rotation"); + }); + + it("setClipRange turns the clip's zoom focus with its picture", () => { + const zoomed = run(twoTakes(), "addZoom", { + startSec: 5, + endSec: 7, + focus: { cx: 0.2, cy: 0.3 }, + }); + const turned = run(zoomed.document as AxcutDocument, "setClipRange", { + clipId: "clip_1", + rotation: 180, + }); + expect((turned.document as AxcutDocument).zoomRanges[0].focus).toEqual({ + cx: 0.8, + cy: 0.7, + }); + }); + + it("setClipRange says how the clip ended when turning it folds it into its neighbour", () => { + // clip_1 is upside down. A second clip continues its media upright, so the two stay apart + // until the second is turned too: then they are one clip again, and it is gone. + const turned = run(twoTakes(), "setClipRange", { clipId: "clip_1", rotation: 180 }) + .document as AxcutDocument; + const placed = run(turned, "insertClip", { + assetId: "asset_1", + sourceStartSec: 10, + sourceEndSec: 16, + }); + const { clipId } = JSON.parse(placed.resultJson); + expect((placed.document as AxcutDocument).timeline.clips.map((c) => c.id)).toContain(clipId); + + const folded = run(placed.document as AxcutDocument, "setClipRange", { clipId, rotation: 180 }); + expect(folded.ok).toBe(true); + expect((folded.document as AxcutDocument).timeline.clips.map((c) => c.id)).not.toContain( + clipId, + ); + expect(JSON.parse(folded.resultJson)).toMatchObject({ + joinedIntoNeighbour: true, + rotation: 180, + }); + }); + + it("setClipRange reports the crop a clip folded into its neighbour ended with", () => { + const crop = { x: 0.1, y: 0.1, width: 0.5, height: 0.5 }; + // Both clips framed alike, the first upside down: turning the second joins them. + const framed = run(twoTakes(), "setClipRange", { + clipId: "clip_1", + cropRegion: crop, + rotation: 180, + }).document as AxcutDocument; + const placed = run(framed, "insertClip", { + assetId: "asset_1", + sourceStartSec: 10, + sourceEndSec: 16, + }); + const { clipId } = JSON.parse(placed.resultJson); + const cropped = run(placed.document as AxcutDocument, "setClipRange", { + clipId, + cropRegion: crop, + }).document as AxcutDocument; + const folded = run(cropped, "setClipRange", { clipId, rotation: 180 }); + expect(JSON.parse(folded.resultJson)).toMatchObject({ + joinedIntoNeighbour: true, + cropRegion: crop, + rotation: 180, + }); + }); + + it("setClipRange accepts only the rotations the Edit clip dialog offers", () => { + const sideways = run(twoTakes(), "setClipRange", { clipId: "clip_1", rotation: 90 }); + expect(sideways.ok).toBe(false); + expect(sideways.document).toBeUndefined(); + }); + it("setClipRange moves one edge and keeps the other", () => { const result = run(twoTakes(), "setClipRange", { clipId: "clip_1", sourceEndSec: 6 }); expect((result.document as AxcutDocument).timeline.clips[0]).toMatchObject({ @@ -4080,6 +4278,128 @@ describe("shader effects", () => { ); expect(JSON.parse(added.resultJson)).toMatchObject({ validated: false, cost: null }); }); + + describe("animate", () => { + const fadeIn = [ + { atSec: 1, value: 3 }, + { atSec: 0, value: 0, ease: "ease-out" }, + ]; + + it("poses keyframes sorted and clamped, and shows them in the snapshot and getEffect", () => { + const added = add(fixtureDocument(), { animate: { level: fadeIn } }); + expect(added.ok).toBe(true); + const doc = added.document as AxcutDocument; + const stored = [ + { atSec: 0, value: 0, ease: "ease-out" }, + { atSec: 1, value: 2 }, + ]; + expect(doc.shaderEffectRanges?.[0].animate).toEqual({ level: stored }); + expect(() => documentSchema.parse(doc)).not.toThrow(); + const snapshot = JSON.parse(run(doc, "getCurrentDocument", {}).resultJson); + expect(snapshot.effects[0].animate).toEqual({ level: stored }); + const effectId = doc.shaderEffects?.[0].id; + const read = JSON.parse(run(doc, "getEffect", { effectId }).resultJson); + expect(read.regions[0].animate).toEqual({ level: stored }); + }); + + it("adds no animate key to a region without keyframes", () => { + const doc = add(fixtureDocument(), { animate: { level: [] } }).document as AxcutDocument; + expect("animate" in (doc.shaderEffectRanges?.[0] ?? {})).toBe(false); + const snapshot = JSON.parse(run(doc, "getCurrentDocument", {}).resultJson); + expect("animate" in snapshot.effects[0]).toBe(false); + }); + + it("refuses an unknown parameter, listing the declared ones, and changes nothing", () => { + const refused = add(fixtureDocument(), { animate: { strength: fadeIn } }); + expect(refused.ok).toBe(false); + expect(refused.document).toBeUndefined(); + expect(JSON.parse(refused.resultJson).error).toMatch(/"strength"[\s\S]*level, tint/); + }); + + it("refuses a keyframe value of the wrong type, naming the keyframe and the type", () => { + const refused = add(fixtureDocument(), { + animate: { + tint: [ + { atSec: 0, value: "#ff0000" }, + { atSec: 1, value: 0.5 }, + ], + }, + }); + expect(refused.ok).toBe(false); + expect(JSON.parse(refused.resultJson).error).toMatch(/animate\.tint\[1\][\s\S]*color/); + }); + + it("replaces a parameter's whole list in setEffect, removes it with an empty one", () => { + const doc = add(fixtureDocument(), { animate: { level: fadeIn } }).document as AxcutDocument; + const effectRegionId = doc.shaderEffectRanges?.[0].id; + const tinted = run(doc, "setEffect", { + effectRegionId, + animate: { tint: [{ atSec: 0.5, value: "#ffffff", ease: "hold" }] }, + }); + expect(tinted.ok).toBe(true); + expect(Object.keys(tinted.document?.shaderEffectRanges?.[0].animate ?? {})).toEqual([ + "level", + "tint", + ]); + const replaced = run(tinted.document as AxcutDocument, "setEffect", { + effectRegionId, + animate: { level: [{ atSec: 2, value: 1 }] }, + }); + expect(replaced.document?.shaderEffectRanges?.[0].animate?.level).toEqual([ + { atSec: 2, value: 1 }, + ]); + const cleared = run(replaced.document as AxcutDocument, "setEffect", { + effectRegionId, + animate: { level: [], tint: [] }, + }); + expect(cleared.ok).toBe(true); + expect("animate" in (cleared.document?.shaderEffectRanges?.[0] ?? {})).toBe(false); + // A re-tune that does not pass animate keeps the keyframes. + const retuned = run(tinted.document as AxcutDocument, "setEffect", { + effectRegionId, + target: "both", + }); + expect(retuned.document?.shaderEffectRanges?.[0].animate).toEqual( + tinted.document?.shaderEffectRanges?.[0].animate, + ); + }); + + it("refuses an unknown parameter in setEffect", () => { + const doc = add(fixtureDocument()).document as AxcutDocument; + const refused = run(doc, "setEffect", { + effectRegionId: doc.shaderEffectRanges?.[0].id, + animate: { nope: [{ atSec: 0, value: 1 }] }, + }); + expect(refused.ok).toBe(false); + expect(JSON.parse(refused.resultJson).error).toMatch(/"nope"[\s\S]*level, tint/); + }); + + it("drops the keyframes of a parameter setEffectDefinition removes or re-types", () => { + const doc = add(fixtureDocument(), { + animate: { + level: [{ atSec: 0, value: 1.5 }], + tint: [{ atSec: 0, value: "#ff0000" }], + }, + }).document as AxcutDocument; + const effectId = doc.shaderEffects?.[0].id; + const changed = run(doc, "setEffectDefinition", { + effectId, + params: [ + { type: "number", name: "level", label: "Level", default: 0.5, min: 0, max: 1 }, + { type: "number", name: "tint", label: "Tint", default: 0, min: 0, max: 1 }, + ], + }); + expect(changed.ok).toBe(true); + expect(changed.document?.shaderEffectRanges?.[0].animate).toEqual({ + level: [{ atSec: 0, value: 1 }], + }); + const removed = run(changed.document as AxcutDocument, "setEffectDefinition", { + effectId, + params: [{ type: "number", name: "tint", label: "Tint", default: 0, min: 0, max: 1 }], + }); + expect("animate" in (removed.document?.shaderEffectRanges?.[0] ?? {})).toBe(false); + }); + }); }); describe("the executor's view of a check asked beforehand", () => { diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts index 3cbccdb011..7e443aba1a 100644 --- a/electron/ai-edition/agent-tools.ts +++ b/electron/ai-edition/agent-tools.ts @@ -22,6 +22,7 @@ import { DEFAULT_ANNOTATION_BOX, fitTextInFrame, } from "../../src/lib/ai-edition/annotations/placement"; +import { clipRotation } from "../../src/lib/ai-edition/clipRotation"; import { AUDIO_FADE_MAX_MS, collapseTracksToPills, @@ -49,6 +50,7 @@ import { removeRegion, replaceTimeline, setClipCrop, + setClipRotation, setClipSourceRange, } from "../../src/lib/ai-edition/document/timeline"; import { setDocumentWordText } from "../../src/lib/ai-edition/document/transcript"; @@ -60,6 +62,7 @@ import { blurDataSchema, clipCropRegionSchema, figureDataSchema, + shaderEffectKeyframeSchema, shaderEffectParamSchema, shaderEffectSchema, shaderEffectValueSchema, @@ -70,9 +73,12 @@ import { type ShaderEffectCheck, type ShaderEffectCheckLookup, shaderEffectCostAdvice, + storedShaderEffectAnimate, storedShaderEffectValues, + withShaderEffectAnimate, } from "../../src/lib/ai-edition/shaderEffects"; import { getEditorSettings } from "../../src/lib/ai-edition/store/editorSettings"; +import type { StylePreset } from "../../src/lib/ai-edition/stylePresets"; import { appendAutoZoomSuggestions } from "../../src/lib/ai-edition/timeline/apply-auto-zooms"; import { hasAnyClipWithCamera } from "../../src/lib/ai-edition/timeline/camera"; import { isGeneratedAssetId } from "../../src/lib/ai-edition/timeline/clip-parts"; @@ -106,11 +112,21 @@ import { } from "../../src/lib/ai-edition/timeline/zoom-transitions"; import { LAYOUT_PRESETS } from "../../src/lib/layoutTypes"; import { SETTING_BOUNDS } from "../../src/lib/projectDefaults"; +import { + resolveTextFontFamily, + TEXT_FONT_FAMILIES, + type TextFontFamily, +} from "../../src/lib/textFonts"; import type { SegmentationSupport } from "../../src/native/contracts"; import { annotationFootageRect, zoomScaleLimit } from "../../src/native/sceneDescription"; import { ASPECT_RATIO_PRESETS } from "../../src/utils/aspectRatioUtils"; import { CAPTION_TOOL_NAMES, executeCaptionTool, MUTATING_CAPTION_TOOLS } from "./caption-tools"; -import { editorSettingsSnapshot, executeSetEditorSettings } from "./editor-settings-tool"; +import { + editorSettingsSnapshot, + executeApplyStylePreset, + executeListStylePresets, + executeSetEditorSettings, +} from "./editor-settings-tool"; import { measureTextInShippedFonts } from "./text-measure"; export interface AgentToolExecution { @@ -218,6 +234,7 @@ function refuseIfBlocked { text: a.content || a.textContent || "", ...geometry, fontSize: a.style.fontSize, + fontFamily: resolveTextFontFamily(a.style.fontFamily), color: a.style.color, background: a.style.backgroundColor === "transparent" ? "none" : a.style.backgroundColor, bold: a.style.fontWeight === "bold", @@ -716,6 +735,12 @@ export const setClipRangeArgs = z.object({ .describe( "The part of the source frame this clip shows, as 0–1 fractions of it ({x, y, width, height}); null shows the whole frame again.", ), + rotation: z + .union([z.literal(0), z.literal(180)]) + .optional() + .describe( + "Turns the clip's picture: 180 shows it upside down (a camera mounted the wrong way up), 0 upright again.", + ), }); /** `beforeClipId`, never an index, for the reason `moveClipArgs` gives. */ @@ -925,6 +950,10 @@ const annotationLookArgs = { .max(200) .optional() .describe("Text size; 32 is the editor's default, a title reads well at 56 to 80."), + fontFamily: z + .enum(TEXT_FONT_FAMILIES) + .optional() + .describe("Typeface: one of the families the app ships and draws. Inter by default."), color: z.string().optional().describe("Text colour, a CSS colour such as #ffffff."), background: z .string() @@ -1023,6 +1052,8 @@ export const addCameraFullscreenArgs = z.object({ const effectTargetSchema = z.enum(["image", "text", "both"]); const effectValuesSchema = z.record(z.string(), shaderEffectValueSchema); +// Per parameter, its whole keyframe list; an empty list removes that parameter's animation. +const effectAnimateSchema = z.record(z.string(), z.array(shaderEffectKeyframeSchema).max(64)); export const addEffectArgs = z.object({ startSec: secondsSchema, @@ -1037,6 +1068,7 @@ export const addEffectArgs = z.object({ }) .optional(), values: effectValuesSchema.optional(), + animate: effectAnimateSchema.optional(), target: effectTargetSchema.optional(), }); @@ -1045,6 +1077,7 @@ export const setEffectArgs = z.object({ startSec: secondsSchema.optional(), endSec: secondsSchema.optional(), values: effectValuesSchema.optional(), + animate: effectAnimateSchema.optional(), target: effectTargetSchema.optional(), }); @@ -1160,6 +1193,8 @@ export const OPENSCREEN_TOOL_NAMES = [ "removeClip", "setAspectRatio", "setEditorSettings", + "listStylePresets", + "applyStylePreset", ...CAPTION_TOOL_NAMES, ] as const; @@ -1244,6 +1279,7 @@ export const MUTATING_TOOL_NAMES: ReadonlySet = new Set([ "removeClip", "setAspectRatio", "setEditorSettings", + "applyStylePreset", ...MUTATING_CAPTION_TOOLS, ]); @@ -1460,6 +1496,8 @@ export function documentSnapshotForModel( timelineEndSec: c.timelineEndSec, // Only when set: absent is the whole frame. ...(c.cropRegion ? { cropRegion: c.cropRegion } : {}), + // Only when turned: absent is upright. + ...(c.rotation === 180 ? { rotation: 180 } : {}), })), trimRanges: document.timeline.trimRanges.map((s) => ({ id: s.id, @@ -1522,6 +1560,7 @@ export function documentSnapshotForModel( endSec: roundSec(r.endMs), target: r.target, values: r.values, + ...(r.animate ? { animate: r.animate } : {}), })), effectDefinitions: (document.shaderEffects ?? []).map((e) => ({ effectId: e.id, @@ -1815,6 +1854,9 @@ export interface AgentToolOptions { /** `addAutoZooms`' plan, made by the async wrapper from the recorded clicks. Absent means * no cursor reader is wired here, which the tool reports as "could not look". */ autoZooms?: AutoZoomPlan; + /** The user's saved style presets, read by the async wrapper for the two preset tools. + * Absent where nothing can read them: only the built-in one is offered, and that is said. */ + stylePresets?: StylePreset[]; } /** What the timeline wand would add, and what each recording's cursor read gave. */ @@ -2059,6 +2101,16 @@ export function executeAgentTool( }; } + case "listStylePresets": + return executeListStylePresets(document, options?.stylePresets); + case "applyStylePreset": + return executeApplyStylePreset( + document, + args, + options?.stylePresets, + options?.cameraSegmentation?.() ?? null, + ); + case "setEditorSettings": return executeSetEditorSettings(document, args, options?.cameraSegmentation?.() ?? null); @@ -2592,26 +2644,31 @@ export function executeAgentTool( case "setClipRange": { const parsed = setClipRangeArgs.safeParse(args); if (!parsed.success) return failure(parsed.error.message); - const { clipId, cropRegion } = parsed.data; + const { clipId, cropRegion, rotation } = parsed.data; const clip = document.timeline.clips.find((c) => c.id === clipId); if (!clip) return failure(`Unknown clip: ${clipId}. ${clipRoster(document)}`); const ranged = parsed.data.sourceStartSec !== undefined || parsed.data.sourceEndSec !== undefined; - if (!ranged && cropRegion === undefined) { + if (!ranged && cropRegion === undefined && rotation === undefined) { return failure( - "Pass sourceStartSec / sourceEndSec, cropRegion, or both: nothing to change.", + "Pass sourceStartSec / sourceEndSec, cropRegion, rotation, or any of them together: nothing to change.", ); } const start = parsed.data.sourceStartSec ?? clip.sourceStartSec; - const end = - parsed.data.sourceEndSec ?? - clip.sourceEndSec ?? - document.assets.find((a) => a.id === clip.assetId)?.durationSec; + const mediaSec = document.assets.find((a) => a.id === clip.assetId)?.durationSec; + const end = parsed.data.sourceEndSec ?? clip.sourceEndSec ?? mediaSec; if (end === undefined) { return failure(`Clip ${clipId} has no known end yet: pass sourceEndSec too.`); } - const sourceStartSec = Math.min(start, end); - const sourceEndSec = Math.max(start, end); + // Never past the media's known end, as insertClip bounds it: there is no picture there. + const bound = (sec: number) => (mediaSec === undefined ? sec : Math.min(sec, mediaSec)); + const sourceStartSec = bound(Math.min(start, end)); + const sourceEndSec = bound(Math.max(start, end)); + if (ranged && mediaSec !== undefined && sourceStartSec >= mediaSec) { + return failure( + `That range starts at or past the end of ${clip.assetId}, which lasts ${formatSec(mediaSec)}.`, + ); + } // The clip's Edit modal, as one document: the range through the one shared mutator // (which recomputes the clip's width and clamps / drops the anchored pills the new // window no longer covers), then the crop. `null` clears it, and so does the whole @@ -2622,10 +2679,14 @@ export function executeAgentTool( cropRegion.width === 1 && cropRegion.height === 1; const crop = cropRegion === undefined ? undefined : wholeFrame ? null : cropRegion; - // One pass for both, as the dialog's Apply: the fold weighs range and crop together. + // The rotation first, as the dialog's Apply does it, then one pass for range and crop: the + // fold weighs range, crop and rotation together. Without a range or a new crop, the clip's + // own crop goes back through `setClipCrop`, which is what folds or splits the neighbours. + const turned = + rotation === undefined ? document : setClipRotation(document, clipId, rotation); const next = ranged - ? setClipSourceRange(document, clipId, sourceStartSec, sourceEndSec, crop) - : setClipCrop(document, clipId, crop ?? null); + ? setClipSourceRange(turned, clipId, sourceStartSec, sourceEndSec, crop) + : setClipCrop(turned, clipId, crop === undefined ? (clip.cropRegion ?? null) : crop); const dropped = droppedByEdit(document, next); const casualties = dropped.droppedModifierIds.length + dropped.droppedTrimIds.length; const after = next.timeline.clips.find((c) => c.id === clipId); @@ -2636,7 +2697,14 @@ export function executeAgentTool( clipId, sourceStartSec, sourceEndSec, - cropRegion: after?.cropRegion ?? null, + // Folded into its neighbour, the clip is gone: it ended as the call framed and turned + // it, which is how the neighbour it joined is framed and turned. + cropRegion: after + ? (after.cropRegion ?? null) + : crop === undefined + ? (clip.cropRegion ?? null) + : crop, + rotation: after ? clipRotation(after) : (rotation ?? clipRotation(clip)), // Its media now continues the clip before it, with the same framing: one clip. ...(after ? {} @@ -2644,10 +2712,17 @@ export function executeAgentTool( ...dropped, }), summary: - (ranged - ? `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}` - : `cropped clip ${clipId}`) + - (ranged && cropRegion !== undefined ? ", cropped" : "") + + [ + ranged + ? `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}` + : null, + cropRegion !== undefined ? `cropped clip ${clipId}` : null, + rotation !== undefined + ? `turned clip ${clipId} ${rotation === 180 ? "upside down" : "upright"}` + : null, + ] + .filter(Boolean) + .join(", ") + (casualties > 0 ? ` — dropped ${[...dropped.droppedModifierIds, ...dropped.droppedTrimIds].join(", ")}` : ""), @@ -3307,12 +3382,13 @@ export function executeAgentTool( }; const moved = x !== undefined || y !== undefined; if (a.type === "text") { - // A text box is the size of its text: refit it whenever the text, its size or its - // weight changes, around its centre or the new one. One saved before frame placement + // A text box is the size of its text: refit it whenever the text, its size, its font + // or its weight changes, around its centre or the new one. One saved before frame placement // moves onto the frame the first time it is moved, as the editor does. const resized = text !== undefined || parsed.data.fontSize !== undefined || + parsed.data.fontFamily !== undefined || parsed.data.bold !== undefined; return moved || (resized && a.space === "frame") ? placeTextOnFrame(next, centre, document) @@ -3494,12 +3570,15 @@ export function executeAgentTool( const endMs = toMs(Math.max(parsed.data.startSec, parsed.data.endSec)); const blocked = effectBlocked(document.shaderEffectRanges ?? [], startMs, endMs); if (blocked) return failure(`The effect was NOT placed: ${blocked}`); + const animated = storedShaderEffectAnimate(definition, parsed.data.animate ?? {}); + if ("error" in animated) return failure(`The effect was NOT placed: ${animated.error}`); const region = { id: createId("fxr"), startMs, endMs, effectId: definition.id, values: storedShaderEffectValues(definition, values), + ...(animated.animate ? { animate: animated.animate } : {}), target, }; const placed = anchorForAgent(region, document, "fxr"); @@ -3538,7 +3617,13 @@ export function executeAgentTool( if (!definition) return failure(`Effect ${existing.effectId} is missing from the project.`); const pillIds = new Set(resolvePillIds(prev, existing.id)); const pill = coalesceRegionsForRuler(prev).find((p) => p.ids.includes(existing.id)); - const { values, target } = parsed.data; + const { values, animate, target } = parsed.data; + // Each parameter passed replaces its whole keyframe list; an empty list removes it. + const animated = storedShaderEffectAnimate(definition, { + ...existing.animate, + ...animate, + }); + if ("error" in animated) return failure(`The effect was NOT changed: ${animated.error}`); const { startMs, endMs } = resolveSpanMs( pill ? { startMs: Math.round(pill.start * 1000), endMs: Math.round(pill.end * 1000) } @@ -3557,18 +3642,18 @@ export function executeAgentTool( ) : prev; const others = new Set(prev.filter((r) => !pillIds.has(r.id)).map((r) => r.id)); - const rebuilt = spanned.map((r) => - others.has(r.id) - ? r - : { - ...r, - values: - values === undefined - ? r.values - : storedShaderEffectValues(definition, { ...r.values, ...values }), - target: target ?? r.target, - }, - ); + const rebuilt = spanned.map((r) => { + if (others.has(r.id)) return r; + const patched = { + ...r, + values: + values === undefined + ? r.values + : storedShaderEffectValues(definition, { ...r.values, ...values }), + target: target ?? r.target, + }; + return animate === undefined ? patched : withShaderEffectAnimate(patched, animated.animate); + }); const landing = landingAfterPillEdit(prev, rebuilt, pillIds, document); if (!landing.anchored) return coversNoClip("effect", startMs / 1000, endMs / 1000, document); const next: AxcutDocument = { ...document, shaderEffectRanges: rebuilt }; @@ -3610,7 +3695,17 @@ export function executeAgentTool( if (!checked.success) return failure(checked.error.message); definition = checked.data; } - // The regions follow the new parameters: a removed one's value drops, bounds re-clamp. + // The regions follow the new parameters: a removed one's value drops, bounds re-clamp. The + // keyframes of a parameter removed or re-typed drop too; the others re-clamp. + const typeOf = (params: AxcutShaderEffect["params"], name: string) => + params.find((p) => p.name === name)?.type; + const keptAnimate = (animate: AxcutShaderEffectRange["animate"]) => { + const kept = Object.entries(animate ?? {}).filter( + ([name]) => typeOf(definition.params, name) === typeOf(existing.params, name), + ); + const stored = storedShaderEffectAnimate(definition, Object.fromEntries(kept)); + return "error" in stored ? undefined : stored.animate; + }; const next: AxcutDocument = { ...document, shaderEffects: (document.shaderEffects ?? []).map((e) => @@ -3618,7 +3713,10 @@ export function executeAgentTool( ), shaderEffectRanges: (document.shaderEffectRanges ?? []).map((r) => r.effectId === effectId - ? { ...r, values: storedShaderEffectValues(definition, r.values) } + ? withShaderEffectAnimate( + { ...r, values: storedShaderEffectValues(definition, r.values) }, + keptAnimate(r.animate), + ) : r, ), }; @@ -3651,6 +3749,7 @@ export function executeAgentTool( endSec: roundSec(r.endMs), target: r.target, values: r.values, + ...(r.animate ? { animate: r.animate } : {}), })); return { ok: true, diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts index e1ea71ee7a..dfe905d856 100644 --- a/electron/ai-edition/chat-service.ts +++ b/electron/ai-edition/chat-service.ts @@ -18,6 +18,7 @@ import { documentSchema, } from "../../src/lib/ai-edition/schema"; import type { ShaderEffectChecker } from "../../src/lib/ai-edition/shaderEffects"; +import type { StylePreset } from "../../src/lib/ai-edition/stylePresets"; import type { AgentTurnUsage, AiEditionChatMessage, @@ -327,6 +328,8 @@ export interface ChatRunEnv { cameraSegmentation?: () => SegmentationSupport; /** The compositor's check of an agent-written effect's WGSL. */ checkShaderEffect?: ShaderEffectChecker; + /** The user's saved style presets (`StylePresetService.list`). */ + stylePresets?: () => Promise; /** Runtime-only model retry override used by bounded measurement harnesses. */ maxRetries?: number; } @@ -518,6 +521,7 @@ export async function runChat( cursor: env.cursor, cameraSegmentation: env.cameraSegmentation, checkShaderEffect: env.checkShaderEffect, + stylePresets: env.stylePresets, }); const executionSteps = execution.finish(Boolean(result.cancelled)); diff --git a/electron/ai-edition/deep-agent/service.test.ts b/electron/ai-edition/deep-agent/service.test.ts index 839d33a0a7..25ce58e201 100644 --- a/electron/ai-edition/deep-agent/service.test.ts +++ b/electron/ai-edition/deep-agent/service.test.ts @@ -24,6 +24,8 @@ import { createEmptyDocument, documentSchema, } from "../../../src/lib/ai-edition/schema"; +import type { StylePreset } from "../../../src/lib/ai-edition/stylePresets"; +import { factoryStylePresetAppearance } from "../../../src/lib/ai-edition/stylePresetsEditor"; import { ZOOM_DEPTH_LEGEND, ZOOM_DEPTH_SCALES, @@ -115,6 +117,8 @@ const ARGS: Record = { removeClip: { clipId: "clip_1" }, setAspectRatio: { aspectRatio: "16:9" }, setEditorSettings: { padding: 30 }, + listStylePresets: {}, + applyStylePreset: { presetId: "openscreen-factory" }, getCaptions: {}, setCaptionSettings: { enabled: true, style: "bold" }, getCaptionTranslationUnits: { language: "fr" }, @@ -445,6 +449,7 @@ describe("one description of the tools, not two", () => { "getTranscriptWords", "getCursorTrack", "getEffect", + "listStylePresets", "getCaptions", "getCaptionTranslationUnits", ]); @@ -823,6 +828,51 @@ describe("addAutoZooms reads the clicks through the runtime's cursor reader", () }); }); +describe("the style preset tools read the saved presets before the executor runs", () => { + const preset = (padding: number): StylePreset => ({ + id: "Roomy", + name: "Roomy", + updatedAt: "2026-11-01T00:00:00.000Z", + appearance: { ...factoryStylePresetAppearance(), padding }, + }); + + it("hands the executor the list the runtime reads, and only to those two tools", async () => { + let reads = 0; + const runtime = { + stylePresets: async () => { + reads += 1; + return [preset(40)]; + }, + }; + const listed = await runDocumentTool(fixtureDocument(), "listStylePresets", {}, true, runtime); + expect(JSON.parse(listed.resultJson).presets.map((p: { id: string }) => p.id)).toEqual([ + "openscreen-factory", + "Roomy", + ]); + const applied = await runDocumentTool( + fixtureDocument(), + "applyStylePreset", + { presetId: "Roomy" }, + true, + runtime, + ); + expect(applied.ok).toBe(true); + expect(JSON.parse(applied.resultJson).settings.padding).toBe(40); + await runDocumentTool(fixtureDocument(), "getCurrentDocument", {}, true, runtime); + expect(reads).toBe(2); + }); + + it("reports a folder that cannot be read rather than failing the call", async () => { + const result = await runDocumentTool(fixtureDocument(), "listStylePresets", {}, true, { + stylePresets: async () => { + throw new Error("EACCES"); + }, + }); + expect(result.ok).toBe(true); + expect(JSON.parse(result.resultJson).warning).toContain("could not be read"); + }); +}); + describe("an effect's code is checked off the main thread, before the executor reads it", () => { const LEVEL = { type: "number", name: "level", label: "Level", default: 1, min: 0, max: 2 }; const effect = (code: string) => ({ diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts index b7dafcb93e..fb1dbafc45 100644 --- a/electron/ai-edition/deep-agent/service.ts +++ b/electron/ai-edition/deep-agent/service.ts @@ -38,6 +38,7 @@ import { AUDIO_FADE_MAX_MS } from "../../../src/lib/ai-edition/document/audioTra import { VOCABULARY_MAX_CHARS } from "../../../src/lib/ai-edition/document/transcript"; import type { AxcutDocument } from "../../../src/lib/ai-edition/schema"; import type { ShaderEffectChecker } from "../../../src/lib/ai-edition/shaderEffects"; +import type { StylePreset } from "../../../src/lib/ai-edition/stylePresets"; import { collectAutoZoomSuggestionsForDocument } from "../../../src/lib/ai-edition/timeline/apply-auto-zooms"; // ponytail: the legend is DERIVED from the depth→scale table, not retyped. Both // tool descriptions used to assert "depth 1–6 maps to 1.0×–3.5×" — a formula @@ -49,6 +50,7 @@ import { ZOOM_DEPTH_LEGEND, } from "../../../src/lib/ai-edition/timeline/zoom-scale"; import { ZOOM_TRANSITION_LEGEND } from "../../../src/lib/ai-edition/timeline/zoom-transitions"; +import { TEXT_FONT_FAMILIES } from "../../../src/lib/textFonts"; import type { AgentTurnUsage, SegmentationSupport } from "../../../src/native/contracts"; import { AGENT_EDITS_SETTING, @@ -109,7 +111,11 @@ import { executionText, toolExecutionStep, } from "../chat-execution"; -import { setEditorSettingsArgs } from "../editor-settings-tool"; +import { + applyStylePresetArgs, + listStylePresetsArgs, + setEditorSettingsArgs, +} from "../editor-settings-tool"; import { abortable } from "./cancellation"; import { createOpenScreenChatModel, @@ -252,11 +258,11 @@ export const TOOL_DESCRIPTIONS: Record = { addTrims: `Add MANY trim ranges in one call: \`ranges\` is a list, each entry taking exactly the fields addTrim takes. Use this whenever you have more than one cut to make — 'remove the silences' on a half-hour recording is hundreds of cuts, and sending them one at a time costs one round trip each. Each range stands or falls ALONE: one that cannot be placed is refused by itself and listed in \`refused\` with its index and the reason, while every other range is still applied. Nothing is rolled back, so a single bad bound never costs you the rest. The result leads with requested / appliedCount / refusedCount so you can see a partial outcome without re-reading the document — report what was refused rather than claiming the whole list landed. ${ZOOM_TRANSITIONS_NOTE} Each applied entry carries the same \`cutTransitions\` warning addTrim reports.`, setTrim: `Move or resize an existing trim range by id. Times are source-time seconds. The cut follows to whichever clip the new range lands in, when that clip is unambiguous. ${ZOOM_TRANSITIONS_NOTE} ${CUT_TRANSITIONS_RESULT}`, setClipRange: - "Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip) — and/or its crop. Only the fields you pass are changed. All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Change the range ONLY when the user explicitly asks to shorten or extend a clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim. cropRegion is the part of the source frame the clip shows, {x, y, width, height} in 0–1 fractions of it, per clip as in the editor's Edit clip; null shows the whole frame again. getCurrentDocument reports it on the clip, absent when the clip shows the whole frame. Two neighbouring clips of the same asset whose source ranges meet and whose crops match are one clip: the result says joinedIntoNeighbour when an edit made them so.", + "Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip) — and/or its crop and rotation. Only the fields you pass are changed. All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Change the range ONLY when the user explicitly asks to shorten or extend a clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim. cropRegion is the part of the source frame the clip shows, {x, y, width, height} in 0–1 fractions of it, per clip as in the editor's Edit clip; null shows the whole frame again. getCurrentDocument reports it on the clip, absent when the clip shows the whole frame. rotation 180 turns the clip's picture upside down (a camera mounted the wrong way up), 0 turns it upright again, as the Edit clip dialog's rotation does: the clip's zoom focus and its privacy blurs follow the turned picture, text and arrows on the frame do not move, and cropRegion stays in the recording's own unturned coordinates. getCurrentDocument reports rotation on the clip, absent when upright. Two neighbouring clips of the same asset whose source ranges meet and whose crops and rotations match are one clip: the result says joinedIntoNeighbour when an edit made them so. A clip of an imported image (a still) can be shortened, never made longer than the holdSec it was imported with: import the image again for a longer one.", moveClip: "Reorder a placed clip: move `clipId` so it plays just before `beforeClipId` (pass null, or omit it, to move it last). Ids come from getCurrentDocument, where each clip carries its `index` and its label in `reason`. This preserves every clip id, every source range, every trim, and the zooms / speed regions / annotations anchored to each clip. This is the tool for 'swap these clips', 'put X first' and 'change the clip order' — replaceTimeline cannot reorder anything.", insertClip: - "Place a clip of a video asset on the timeline, just before `beforeClipId` (null, or omitted, places it last): another take, or footage imported in the editor. Any video asset of getCurrentDocument works, the primary one too. sourceStartSec/sourceEndSec pick the stretch of the asset in its source seconds, the whole asset by default. Clips stay back to back, so the clips after it shift. Its media continuing the clip before it makes the two one clip (joinedIntoNeighbour). An audio asset is not footage: use addAudio. Nothing here imports a file from disk.", + "Place a clip of a video asset on the timeline, just before `beforeClipId` (null, or omitted, places it last): another take, or footage imported in the editor. Any video asset of getCurrentDocument works, the primary one too. sourceStartSec/sourceEndSec pick the stretch of the asset in its source seconds, the whole asset by default. Clips stay back to back, so the clips after it shift. Its media continuing the clip before it makes the two one clip (joinedIntoNeighbour). An audio asset is not footage: use addAudio. An imported image (a still) is a video asset too: by default its clip shows the image for its whole holdSec. Nothing here imports a file from disk.", duplicateClip: "Copy a clip, placed right after it: the same footage, crop and source range, with its own copy of the clip's trims and of the zooms, speed regions, annotations and camera-fullscreen regions on it. Edits to one no longer touch the other. Returns the copy's clipId; moveClip puts it somewhere else.", replaceTimeline: @@ -270,20 +276,23 @@ export const TOOL_DESCRIPTIONS: Record = { "Add a speed-change region over a span of the edited timeline (virtual seconds). speed > 1 fast-forwards, < 1 slows down, from 0.25× to 16× (default 1.5×). Use to speed through slow stretches without cutting them.", setSpeed: "Move, resize, or change the multiplier of an existing speed region by id (virtual-timeline seconds). Only the fields you pass are changed.", - addAnnotation: - "Add an annotation over a span of the edited timeline (virtual seconds). type picks what it is: 'text' (the default) for callouts, labels and titles; 'figure' for an arrow pointing at something; 'blur' for a privacy mask that blurs or pixelates what is under it, the way to hide an email address, a token, a password field or any private detail the recording shows. Image annotations are not available here: they need a file, added in the editor. x/y place the centre, 0–100 percent of the annotation's box (default the centre). Text and arrows sit on the output frame, the whole picture padding included, as the editor places them: zooms and padding never move them. A blur sits on the recording's picture instead, so x/y/width/height are percent of the recording and it stays on what it hides when padding or a zoom moves the picture. A text box is sized to its words and kept inside the frame; it is drawn on a dark plate by default, and fontSize, color, background, bold and animation set its look. An arrow or a blur takes width/height (default 30 × 20) and its own data: figureData {arrowDirection, color, strokeWidth} for an arrow, blurData {type 'blur' or 'mosaic', shape 'rectangle' or 'oval', color, intensity, blockSize} for a blur. The result reads the annotation back as getCurrentDocument reports it.", + addAnnotation: `Add an annotation over a span of the edited timeline (virtual seconds). type picks what it is: 'text' (the default) for callouts, labels and titles; 'figure' for an arrow pointing at something; 'blur' for a privacy mask that blurs or pixelates what is under it, the way to hide an email address, a token, a password field or any private detail the recording shows. Image annotations are not available here: they need a file, added in the editor. x/y place the centre, 0–100 percent of the annotation's box (default the centre). Text and arrows sit on the output frame, the whole picture padding included, as the editor places them: zooms and padding never move them. A blur sits on the recording's picture instead, so x/y/width/height are percent of the recording and it stays on what it hides when padding or a zoom moves the picture. A text box is sized to its words and kept inside the frame; it is drawn on a dark plate by default, and fontSize, fontFamily (${TEXT_FONT_FAMILIES.join(", ")}; Inter by default), color, background, bold and animation set its look. An arrow or a blur takes width/height (default 30 × 20) and its own data: figureData {arrowDirection, color, strokeWidth} for an arrow, blurData {type 'blur' or 'mosaic', shape 'rectangle' or 'oval', color, intensity, blockSize} for a blur. The result reads the annotation back as getCurrentDocument reports it.`, setAnnotation: - "Change an existing annotation by id: its span (virtual-timeline seconds), its type, its centre (x/y, percent of its box), its size (width/height, arrow and blur only), its text and look (text only: fontSize, color, background, bold, animation), or its figureData / blurData, of which only the keys you pass change. Only the fields you pass are changed. A type change converts it as the editor's type switch does: it stays where it is on screen, a text turned into an arrow or a blur takes the default box, and the text is kept to come back to. A text box is refitted to its text around its centre. Arguments that belong to another kind (width on a text, blurData on an arrow) are refused. A new span that would run into another annotation is refused, naming it.", + "Change an existing annotation by id: its span (virtual-timeline seconds), its type, its centre (x/y, percent of its box), its size (width/height, arrow and blur only), its text and look (text only: fontSize, fontFamily, color, background, bold, animation), or its figureData / blurData, of which only the keys you pass change. Only the fields you pass are changed. A type change converts it as the editor's type switch does: it stays where it is on screen, a text turned into an arrow or a blur takes the default box, and the text is kept to come back to. A text box is refitted to its text around its centre. Arguments that belong to another kind (width on a text, blurData on an arrow) are refused. A new span that would run into another annotation is refused, naming it.", setAspectRatio: "Set the shape of the exported video: 16:9 for X, YouTube or a slide, 9:16 for a vertical story or short, 1:1 or 4:5 for a square feed, auto to follow the recording, or one of the clips' own shapes (getCurrentDocument's settingsContext.originalAspectRatios). Annotations on the frame keep their place and shape. The same as setEditorSettings with aspectRatio alone.", setEditorSettings: 'Change the project\'s look: pass only the settings to change, named as getCurrentDocument returns them under `settings`. Background: wallpaper (a bundled path from settingsContext.bundledWallpapers, a CSS colour or gradient, or a base64 PNG/JPEG data URL; never a file path or web URL; an embedded image reads back as a marker, leave the key out to keep it), wallpaperMotion (moves a gradient or image only), backgroundBlur 0–1. Frame: aspectRatio ("auto", a preset, or an originalAspectRatios token; a fixed format picked for the first time fills the frame with a window that follows the cursor, which formatFollowCursor turns off when settingsContext.formatFill is "available"), padding 0–100 %, borderRadius 0–64 px, shadowIntensity 0–1, frame (none, window, laptop, phone, monitor) and frameTheme (light, dark), motionBlurAmount 0–1, depthOfField (blurs 3D-tilted zooms only). Camera: webcamLayoutPreset, webcamMirrored, webcamReactiveZoom (shrinks on zoom), webcamMaskShape (square or rectangle, the camera\'s own proportions; an untouched roundness follows it), webcamRoundness 0–1, webcamSizePreset 15–60, webcamAnchor (a corner or an edge middle), webcamCropRegion (the framing: a square share of the picture, width = height ≥ 1/3) and webcamCropPan (where that window sits, 0–1 per axis, 0.5 centred), webcamBackgroundMode (none, transparent, blur, custom: needs settingsContext.cameraSegmentation ready), webcamBlurIntensity 0–1, webcamWallpaper (as wallpaper). Cursor, under `cursor`: show, autoHide, theme (settingsContext.cursorThemes), asArrow (the recorded cursor kinds drawn as the arrow instead), size 1.5–6, smoothing 0–1, motionBlur 0–1, clickBounce 0–2, clickImpact, clickSound (only heard when the take recorded clicks) and clickSoundGainDb −24–0, model3d. Also autoFocusAll (every zoom follows the cursor), audioGainDb −12–12 dB, the master volume, and recordingMuted (silences the recording\'s own sound in the preview and the export; added audio tracks still play). A value out of range or a key not listed is refused with the reason, and nothing changes. The result lists what was applied, including what the editor changes with it, and `inactive` for any of those the current state leaves without effect.', + listStylePresets: + "List the style presets the editor's Style presets menu offers: the built-in OpenScreen look first, then the user's saved presets. Each comes with its id, name, builtIn, forNewProjects when new projects start from it, `look` (the settings it applies, in the editor's settings shape, embedded images elided) and `active`, true for the one preset whose look is the project's look now (at most one). Takes no arguments. `warning` says when the saved presets could not be read from here and only the built-in one is listed.", + applyStylePreset: + "Apply a style preset by its id from listStylePresets, as the editor's Style presets menu applies it: the whole look in one edit (background, frame, padding, corners, shadow, blur, output format, camera shape and style, cursor look). A preset is the project's look, never its content: clips, cuts, zooms, annotations, captions and audio are untouched. The result gives the project's settings after it, in getCurrentDocument's `settings` shape, and `inactive` for any setting the current state leaves without effect. setEditorSettings changes single settings afterwards.", addEffect: - "Write a visual effect as a shader and pose it over a span of the edited timeline (virtual seconds), or pose one of this project's effects again (effectId). Use it for a look the settings do not offer. `effect.code` is WGSL that defines `fn effect(uv: vec2) -> vec4`, called for every pixel; uv is 0..1 with (0,0) top-left. Available inside it: `frame(uv)` samples the composed picture; `footage(p)` samples the recording itself at its own resolution at point p of its surface (the space of `fx_to_footage`), transparent outside 0..1, with no cursor or webcam on it: read it for anything that magnifies, frame() for the rest; `params.` reads each declared parameter; `ctx.time` is programme seconds; `ctx.region.x` goes 0 to 1 across the region (y its length in s, z seconds since it began); `ctx.resolution` and `ctx.aspect`; `ctx.cursor` (xy in uv, z = 1 when on screen); `ctx.clicks[0..3]`, the last four clicks, newest first (xy in uv where it happened, z seconds since, w = 1 when the slot holds one); `ctx.footage` and `ctx.camera`, the recording's and the webcam's rects (x, y, w, h in uv; camera zero-sized when absent) — all already placed through zoom and layout; `fx_to_footage(uv)` and `fx_from_footage(p)` map between output uv and the recording's own surface (0..1 across the recording) through the warp the compositor draws it with, zoom, layout and 3D camera included, and `ctx.footage_aspect` is its width over height: the effect works in whichever of the two spaces fits it; `fx_px(n)`, n pixels of a 1080p frame as a fraction of the height; `fx_hash(vec2)`, a random number in [0,1) identical on every GPU. Rules: the effect is a pure function of those inputs (no state between frames), so the preview and the export show the same pixels; reason in uv or fx_px, never raw pixels; every loop is a `for` with literal bounds (`for (var i = 0; i < 16; i++)`), at most 4096 iterations per pixel — the one hard rule. `params` declares up to 8 (recommended) parameters, each `{type: number|toggle|color|point, name, label, default}` (number also `min`, `max`); declare one only when moving it visibly changes the effect over its whole range. `target`: `image` (default: the picture under the annotations and captions), `text` (the annotations and captions alone, premultiplied alpha), `both` (everything); use text or both only when asked. One effect runs at a time: to combine two looks, write them in one shader. The result gives the cost tier, in frame() and footage() reads per pixel, with what a 1080p frame pays on a fast discrete GPU (RTX 4070 Ti) and on an integrated one (Apple M1): light ≤ 8, up to 0.06 ms and 1.3 ms; medium ≤ 32, 0.14 ms and 4.3 ms; heavy ≤ 128, 0.54 ms and 16 ms; very heavy beyond, 2 ms and 49 ms at 512 reads. It also gives a recommendation when the tier runs long: light anywhere, medium up to a minute, heavy up to 10 s, very heavy a few seconds. It is a recommendation, never a refusal. Code that does not compile is refused with the compiler's error at the line of your code: fix it and call again. Check the result with getFrames.", + "Write a visual effect as a shader and pose it over a span of the edited timeline (virtual seconds), or pose one of this project's effects again (effectId). Use it for a look the settings do not offer. `effect.code` is WGSL that defines `fn effect(uv: vec2) -> vec4`, called for every pixel; uv is 0..1 with (0,0) top-left. Available inside it: `frame(uv)` samples the composed picture; `footage(p)` samples the recording itself at its own resolution at point p of its surface (the space of `fx_to_footage`), transparent outside 0..1, with no cursor or webcam on it: read it for anything that magnifies, frame() for the rest; `params.` reads each declared parameter; `ctx.time` is programme seconds; `ctx.region.x` goes 0 to 1 across the region (y its length in s, z seconds since it began); `ctx.resolution` and `ctx.aspect`; `ctx.cursor` (xy in uv, z = 1 when on screen); `ctx.clicks[0..3]`, the last four clicks, newest first (xy in uv where it happened, z seconds since, w = 1 when the slot holds one); `ctx.footage` and `ctx.camera`, the recording's and the webcam's rects (x, y, w, h in uv; camera zero-sized when absent) — all already placed through zoom and layout; `fx_to_footage(uv)` and `fx_from_footage(p)` map between output uv and the recording's own surface (0..1 across the recording) through the warp the compositor draws it with, zoom, layout and 3D camera included, and `ctx.footage_aspect` is its width over height: the effect works in whichever of the two spaces fits it; `fx_px(n)`, n pixels of a 1080p frame as a fraction of the height; `fx_hash(vec2)`, a random number in [0,1) identical on every GPU. Rules: the effect is a pure function of those inputs (no state between frames), so the preview and the export show the same pixels; reason in uv or fx_px, never raw pixels; every loop is a `for` with literal bounds (`for (var i = 0; i < 16; i++)`), at most 4096 iterations per pixel — the one hard rule. `params` declares up to 8 (recommended) parameters, each `{type: number|toggle|color|point, name, label, default}` (number also `min`, `max`); declare one only when moving it visibly changes the effect over its whole range. `target`: `image` (default: the picture under the annotations and captions), `text` (the annotations and captions alone, premultiplied alpha), `both` (everything); use text or both only when asked. One effect runs at a time: to combine two looks, write them in one shader. The result gives the cost tier, in frame() and footage() reads per pixel, with what a 1080p frame pays on a fast discrete GPU (RTX 4070 Ti) and on an integrated one (Apple M1): light ≤ 8, up to 0.06 ms and 1.3 ms; medium ≤ 32, 0.14 ms and 4.3 ms; heavy ≤ 128, 0.54 ms and 16 ms; very heavy beyond, 2 ms and 49 ms at 512 reads. It also gives a recommendation when the tier runs long: light anywhere, medium up to a minute, heavy up to 10 s, very heavy a few seconds. It is a recommendation, never a refusal. Code that does not compile is refused with the compiler's error at the line of your code: fix it and call again. When a parameter's motion is a timing decision (a fade in, a pulse on a beat), animate it with `animate: { : [{ atSec, value, ease? }] }` (atSec from the region's start; ease linear, hold, ease-in, ease-out, ease-in-out, a cubic-bezier [x1, y1, x2, y2] or { spring: { bounce } }) instead of writing the timing into the shader: it stays tunable without new code. Check the result with getFrames.", setEffect: - "Move, resize or re-tune an effect region by id (virtual seconds): its span, its parameter `values`, or its `target`. Only the fields you pass change; a value equal to the default is dropped. Refused if the new span runs into another effect: one runs at a time.", + "Move, resize or re-tune an effect region by id (virtual seconds): its span, its parameter `values`, or its `target`. Only the fields you pass change; a value equal to the default is dropped. `animate` sets a parameter's keyframes `[{ atSec, value, ease? }]`, so its timing stays tunable without rewriting the shader: each parameter you pass replaces its whole list, and an empty list removes it. Refused if the new span runs into another effect: one runs at a time.", setEffectDefinition: - "Change an effect itself by effectId — its name, description, WGSL `code` or `params` — and with it every region that uses it. New code is compiled first and refused with the compiler's error if it does not compile. A removed parameter's values drop; the bounds re-clamp the others. Read the current code with getEffect before rewriting it.", + "Change an effect itself by effectId — its name, description, WGSL `code` or `params` — and with it every region that uses it. New code is compiled first and refused with the compiler's error if it does not compile. A removed parameter's values and keyframes drop, and so do the keyframes of a re-typed one; the bounds re-clamp the others. Read the current code with getEffect before rewriting it.", getEffect: "Read one effect of the project in full: its WGSL code, parameters, description, cost and the regions that use it. getCurrentDocument lists effects without their code.", addAudio: `Lay an ALREADY-IMPORTED audio file over the recording across a span of the edited timeline (virtual seconds): a voiceover, or a music bed. assetId must name an asset whose kind is 'audio' — getCurrentDocument lists them. If there is none, a file has to be imported first (importMedia, where it is offered): never guess an id. Omit endSec to play the whole file from offsetSec. kind picks the lane ('voiceover' or 'music'). offsetSec is where in the FILE playback starts, gainDb its level (0 unchanged, negative ducks it), fadeInMs / fadeOutMs its fades (0 to ${AUDIO_FADE_MAX_MS} ms, default none; a track too short for both shares its span between them). A voiceover-lane track is also what gets transcribed, so the lane is not only cosmetic.`, @@ -347,8 +356,16 @@ export interface ToolRuntime { cameraSegmentation?: () => SegmentationSupport; /** Asks the compositor to check an effect's WGSL. */ checkShaderEffect?: ShaderEffectChecker; + /** Reads the user's saved style presets (`StylePresetService.list`). */ + stylePresets?: () => Promise; } +/** The tools that read the user's saved style presets before the executor runs. */ +const TOOLS_READING_STYLE_PRESETS: ReadonlySet = new Set([ + "listStylePresets", + "applyStylePreset", +]); + /** * The tools whose RESULT depends on the recorded pointer track, so the async * wrapper knows to do the read before entering the synchronous executor. @@ -493,6 +510,13 @@ export async function runDocumentTool( await runtime.checkShaderEffect(effectSource.code, effectSource.params), ) : undefined; + const stylePresets = + TOOLS_READING_STYLE_PRESETS.has(name) && runtime.stylePresets + ? await runtime.stylePresets().catch((error) => { + console.warn("[agent] style presets unavailable:", error); + return undefined; + }) + : undefined; // Async work above is read-only. An abort discards its result before the // synchronous executor or document holder can commit anything. runtime.signal?.throwIfAborted(); @@ -502,6 +526,7 @@ export async function runDocumentTool( cameraSegmentation: runtime.cameraSegmentation, checkShaderEffect, autoZooms, + stylePresets, }); } @@ -625,6 +650,8 @@ export const TOOL_ARG_SCHEMAS: ReadonlyArray = [ ["removeClip", removeClipArgs], ["setAspectRatio", setAspectRatioArgs], ["setEditorSettings", setEditorSettingsArgs], + ["listStylePresets", listStylePresetsArgs], + ["applyStylePreset", applyStylePresetArgs], ["getCaptions", getCaptionsArgs], ["setCaptionSettings", setCaptionSettingsArgs], ["getCaptionTranslationUnits", getCaptionTranslationUnitsArgs], @@ -673,6 +700,8 @@ export interface InvokeArgs { cameraSegmentation?: () => SegmentationSupport; /** Injected the same way: the compositor's check of an effect's WGSL. */ checkShaderEffect?: ShaderEffectChecker; + /** Injected the same way: the user's saved style presets. */ + stylePresets?: () => Promise; } /** One cheap probe per asset, run before the tools are built so the very first @@ -775,6 +804,7 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise { expect(inactive["cursor.model3d"]).toMatch(/hidden/); }); }); + +describe("style presets", () => { + const look = { + ...factoryStylePresetAppearance(), + padding: 12, + borderRadius: 30, + aspectRatio: "9:16" as const, + wallpaper: "#123456", + }; + const saved: StylePreset[] = [ + { id: "Vertical", name: "Vertical", updatedAt: "2026-11-01T00:00:00.000Z", appearance: look }, + ]; + const list = (document: AxcutDocument, presets: StylePreset[] | undefined) => + JSON.parse( + executeAgentTool(document, "listStylePresets", "", { stylePresets: presets }).resultJson, + ); + // `null`: nothing could read the saved presets. + const apply = ( + document: AxcutDocument, + presetId: string, + presets: StylePreset[] | null = saved, + ) => + executeAgentTool(document, "applyStylePreset", JSON.stringify({ presetId }), { + stylePresets: presets ?? undefined, + }); + + it("lists the built-in look first, then the saved ones, and lights the one in use", () => { + const listed = list(fixture(), saved); + expect(listed.presets.map((p: { id: string }) => p.id)).toEqual([ + "openscreen-factory", + "Vertical", + ]); + expect(listed.presets[0]).toMatchObject({ name: "OpenScreen", builtIn: true, active: true }); + expect(listed.presets[1]).toMatchObject({ + builtIn: false, + active: false, + look: { padding: 12, aspectRatio: "9:16" }, + }); + expect(listed).not.toHaveProperty("warning"); + }); + + it("applies a preset's whole look as the menu does, and leaves the content alone", () => { + const document = fixture(); + const applied = apply(document, "Vertical"); + expect(applied.ok).toBe(true); + const next = applied.document as AxcutDocument; + expect(() => documentSchema.parse(next)).not.toThrow(); + expect(stylePresetAppearanceFromSettings(getEditorSettings(next))).toEqual(look); + expect(next.timeline).toEqual(document.timeline); + expect(JSON.parse(applied.resultJson)).toMatchObject({ + presetId: "Vertical", + name: "Vertical", + settings: { padding: 12, borderRadius: 30, aspectRatio: "9:16" }, + }); + expect(list(next, saved).presets.map((p: { active: boolean }) => p.active)).toEqual([ + false, + true, + ]); + + // And back to the built-in look. + const reset = apply(next, "openscreen-factory").document as AxcutDocument; + expect(stylePresetAppearanceFromSettings(getEditorSettings(reset))).toEqual( + factoryStylePresetAppearance(), + ); + }); + + it("refuses an unknown preset, naming the ones there are", () => { + const unknown = apply(fixture(), "Nope"); + expect(unknown.ok).toBe(false); + expect(unknown.document).toBeUndefined(); + expect(unknown.resultJson).toContain("Vertical (Vertical)"); + }); + + it("says so when the saved presets cannot be read, and still offers the built-in one", () => { + const listed = list(fixture(), undefined); + expect(listed.presets).toHaveLength(1); + expect(listed.warning).toContain("could not be read"); + expect(apply(fixture(), "openscreen-factory", null).ok).toBe(true); + expect(apply(fixture(), "Vertical", null).resultJson).toContain("could not be read"); + }); + + it("is a write, refused while edits are off", () => { + const refused = executeAgentTool( + fixture(), + "applyStylePreset", + JSON.stringify({ presetId: "openscreen-factory" }), + { editsAllowed: false }, + ); + expect(refused.ok).toBe(false); + expect(refused.document).toBeUndefined(); + }); +}); diff --git a/electron/ai-edition/editor-settings-tool.ts b/electron/ai-edition/editor-settings-tool.ts index 9b708b957e..20fd1adec5 100644 --- a/electron/ai-edition/editor-settings-tool.ts +++ b/electron/ai-edition/editor-settings-tool.ts @@ -30,7 +30,18 @@ import { panOfCropRegion, } from "../../src/lib/ai-edition/store/editorSettings"; import { applySettingsPatch } from "../../src/lib/ai-edition/store/settingsPatch"; -import { parseStylePresetWallpaper } from "../../src/lib/ai-edition/stylePresets"; +import { + FACTORY_STYLE_PRESET_ID, + parseStylePresetWallpaper, + type StylePreset, + type StylePresetAppearance, +} from "../../src/lib/ai-edition/stylePresets"; +import { + factoryStylePresetAppearance, + sameStylePresetLook, + stylePresetAppearanceFromSettings, + stylePresetPatch, +} from "../../src/lib/ai-edition/stylePresetsEditor"; import { hasAnyClipWithCamera } from "../../src/lib/ai-edition/timeline/camera"; import { resolveWebcamLayoutPreset, @@ -460,3 +471,113 @@ export function executeSetEditorSettings( summary: `set ${keys.join(", ")}`, }; } + +// ---- Style presets ------------------------------------------------------------------- +// The editor's Style presets menu, for the agent: a preset is the project's LOOK, never its +// content, applied as the menu applies it (`stylePresetPatch`, one settings patch). The presets +// themselves are files the main process reads (`StylePresetService`); the async wrapper reads +// them and hands this pure layer the list. + +export const listStylePresetsArgs = z.object({}); + +export const applyStylePresetArgs = z.object({ + presetId: z.string().min(1).describe("A preset id from listStylePresets."), +}); + +/** The menu's built-in row: the look a new project has before anything is changed. */ +const FACTORY_PRESET_NAME = "OpenScreen"; + +/** The menu's rows, built-in first, as it orders them. */ +function presetRows(presets: StylePreset[]) { + return [ + { + id: FACTORY_STYLE_PRESET_ID, + name: FACTORY_PRESET_NAME, + builtIn: true, + appearance: factoryStylePresetAppearance(), + }, + ...presets.map((preset) => ({ + id: preset.id, + name: preset.name, + builtIn: false, + appearance: preset.appearance, + ...(preset.forNewProjects ? { forNewProjects: true } : {}), + })), + ]; +} + +const PRESETS_UNREADABLE = + "The saved style presets could not be read from here; only the built-in one is listed."; + +/** A preset's look as the model reads it: its embedded images elided. */ +function appearanceForModel(appearance: StylePresetAppearance) { + return { + ...appearance, + wallpaper: elideDataUrl(appearance.wallpaper), + webcamWallpaper: elideDataUrl(appearance.webcamWallpaper), + }; +} + +/** + * Every preset, built-in first, each with its look and whether it is the project's look now. + * At most one reads as active, the first match in menu order, as the menu lights one row. + * `presets` absent: nothing here can read the folder, which is said rather than listed as none. + */ +export function executeListStylePresets( + document: AxcutDocument, + presets: StylePreset[] | undefined, +): AgentToolExecution { + const current = stylePresetAppearanceFromSettings(getEditorSettings(document)); + const rows = presetRows(presets ?? []); + const activeId = rows.find((row) => sameStylePresetLook(row.appearance, current))?.id ?? null; + return { + ok: true, + resultJson: JSON.stringify({ + presets: rows.map(({ appearance, ...row }) => ({ + ...row, + active: row.id === activeId, + look: appearanceForModel(appearance), + })), + ...(presets ? {} : { warning: PRESETS_UNREADABLE }), + }), + }; +} + +/** The menu's apply: the whole look as one patch, through the editor's own write. */ +export function executeApplyStylePreset( + document: AxcutDocument, + args: unknown, + presets: StylePreset[] | undefined, + segmentation: SegmentationSupport | null, +): AgentToolExecution { + const parsed = applyStylePresetArgs.safeParse(args); + if (!parsed.success) { + return { ok: false, resultJson: JSON.stringify({ error: parsed.error.message }) }; + } + const rows = presetRows(presets ?? []); + const row = rows.find((r) => r.id === parsed.data.presetId); + if (!row) { + const known = rows.map((r) => `${r.id} (${r.name})`).join(", "); + const error = presets + ? `Unknown style preset: ${parsed.data.presetId}. The presets are: ${known}.` + : `Unknown style preset: ${parsed.data.presetId}. ${PRESETS_UNREADABLE} It is ${known}.`; + return { ok: false, resultJson: JSON.stringify({ error }) }; + } + const next = applySettingsPatch( + document, + stylePresetPatch(row.appearance), + measureTextInShippedFonts, + ); + const inactive = inactiveSettings(next, segmentation); + return { + ok: true, + document: next, + resultJson: JSON.stringify({ + presetId: row.id, + name: row.name, + settings: settingsForModel(next), + ...(Object.keys(inactive).length ? { inactive } : {}), + }), + summary: `applied style preset "${row.name}"`, + }; +} diff --git a/electron/cli/cliMain.ts b/electron/cli/cliMain.ts index b8d600a65b..3a0f3a54c3 100644 --- a/electron/cli/cliMain.ts +++ b/electron/cli/cliMain.ts @@ -11,6 +11,7 @@ import { renameWithRetry } from "../atomic-rename"; import { isDiagnosticModeEnabled } from "../diagnostics/main-log-file"; import { getInstallChannel, ownsItsUpdates } from "../install-channel"; import { getSelectedDesktopSource, registerIpcHandlers } from "../ipc/handlers"; +import { frameImages } from "../mcp/frame-images"; import { openVideoInHiddenWindow } from "../mcp/hidden-video"; import { watchForMacMcpShutdown } from "../mcp/mac-update-shutdown"; import { serveMcpOverStdio } from "../mcp/stdio-server"; @@ -421,6 +422,7 @@ export function runCli(command: CliCommand): void { userDataDir, runners, openVideo: openVideoInHiddenWindow, + images: frameImages, updateNotice: tellsAboutUpdates ? (updateNotice(app.getVersion(), readReleaseLookup(userDataDir)) ?? undefined) : undefined, diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts index f0c93ff955..de3ced04e6 100644 --- a/electron/electron-env.d.ts +++ b/electron/electron-env.d.ts @@ -340,9 +340,11 @@ interface Window { success: boolean; path?: string; // Browser-mode shim only: a blob: URL has no meaningful basename, so - // the shim carries the picked File's real name here for the label. + // the shim carries the picked File's real name here for the label. A + // picked image carries its own name too: `path` is the still made from it. name?: string; canceled?: boolean; + message?: string; }>; // Import an external audio file from the timeline toolbar (issue #350). openAudioFilePicker: () => Promise<{ diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts index e4bab0f5cb..eea3d34d1a 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -90,6 +90,7 @@ import { } from "../main"; import { createAppRecorder, pickTakePrefs, takePrefs } from "../mcp/app-recorder"; import { EditorDocumentHost } from "../mcp/editor-document-host"; +import { frameImages } from "../mcp/frame-images"; import { openVideoInHiddenWindow } from "../mcp/hidden-video"; import { NAMED_TAKE_NEEDS_SCREEN_ACCESS, namedTakeMayEnumerate } from "../mcp/macNamedTake"; import { McpController } from "../mcp/mcp-controller"; @@ -105,6 +106,12 @@ import { } from "../media/cursorSidecar"; import { findMediaLinksByFingerprint, registerMediaLinks } from "../media/mediaLinksRegistry"; import { relinkProjectMedia } from "../media/projectMediaRelinker"; +import { + DEFAULT_HOLD_SEC, + ensureStillClip, + IMAGE_EXTENSIONS, + isImagePath, +} from "../media/stillClip"; import { showOpenDialogOver, showSaveDialogOver } from "../messageBox"; import { isPortalCancelled, @@ -181,6 +188,7 @@ import { shouldPersistSelectedSource, } from "../recording-source-settings"; import { getSttManager } from "../stt"; +import { countToolCall } from "../usage-ping"; import { usesWaylandBackend } from "../wayland"; import { createCameraPreviewWindow, @@ -4567,17 +4575,29 @@ export function registerIpcHandlers( } }); - // The media tab imports VIDEO (it arranges clips). Audio is imported from the - // timeline toolbar instead (issue #350) — see `open-audio-file-picker` below. + // The media tab imports VIDEO (it arranges clips), and images as the still clip + // made from them. Audio is imported from the timeline toolbar instead (issue + // #350) — see `open-audio-file-picker` below. ipcMain.handle("open-video-file-picker", async (event) => { try { const dialogOptions: Electron.OpenDialogOptions = { - title: mainT("dialogs", "fileDialogs.selectVideo"), + title: mainT("dialogs", "fileDialogs.selectVideoOrImage"), defaultPath: RECORDINGS_DIR, filters: [ { - name: mainT("dialogs", "fileDialogs.videoFiles"), - extensions: ["webm", "mp4", "mov", "avi", "mkv", "m4v", "wmv", "flv", "ts"], + name: mainT("dialogs", "fileDialogs.videoAndImageFiles"), + extensions: [ + "webm", + "mp4", + "mov", + "avi", + "mkv", + "m4v", + "wmv", + "flv", + "ts", + ...IMAGE_EXTENSIONS.map((ext) => ext.slice(1)), + ], }, { name: mainT("dialogs", "fileDialogs.allFiles"), extensions: ["*"] }, ], @@ -4592,7 +4612,18 @@ export function registerIpcHandlers( return { success: false, canceled: true }; } - const normalizedPath = await approveReadableVideoPath(result.filePaths[0]); + const picked = result.filePaths[0]; + if (isImagePath(picked)) { + const still = await ensureStillClip(picked, DEFAULT_HOLD_SEC, RECORDINGS_DIR).catch( + (error: Error) => error, + ); + if (still instanceof Error) return { success: false, message: still.message }; + approveFilePath(still.path); + currentProjectPath = null; + return { success: true, path: still.path, name: path.basename(picked) }; + } + + const normalizedPath = await approveReadableVideoPath(picked); if (!normalizedPath) { return { success: false, @@ -5405,6 +5436,7 @@ export function registerIpcHandlers( cursor: agentCursorTelemetryReader, cameraSegmentation: () => loudnessService.probeSegmentation(), checkShaderEffect: (code, params) => loudnessService.checkShaderEffect(code, params), + stylePresets: () => stylePresets.list(), // The editor's own engine, in this process: `openscreen mcp` transcribes without the app. transcribe: (request) => getSttManager().transcribe(request), version: app.getVersion(), @@ -5415,6 +5447,9 @@ export function registerIpcHandlers( const media = normalizeVideoSourcePath(filePath); if (media && hasAllowedImportMediaExtension(media)) approveFilePath(media); }, + makeStill: (imagePath, holdSec) => ensureStillClip(imagePath, holdSec, RECORDINGS_DIR), + // The tool's name and nothing of the call, for the daily count to carry. + onToolCall: (name) => countToolCall(app.getPath("userData"), getInstallChannel(), name), }; // One runner, so one queue and one checkpoint store, for the in-app server and every // `openscreen mcp` the app answers through its channel (app-channel.ts, started by main.ts). @@ -5518,6 +5553,7 @@ export function registerIpcHandlers( documents: aiEditionDocuments, openVideo: openVideoInHiddenWindow, renderFrames: (...args) => loudnessService.renderFrames(...args), + images: frameImages, readCursor: async (videoPath) => (await readCursorTelemetryFile(videoPath)).samples, // Never overriding the switch: setPointerTrack is refused while MCP edits is off. runTool: mcpRunTool, @@ -5590,6 +5626,7 @@ export function registerIpcHandlers( cursor: agentCursorTelemetryReader, cameraSegmentation: () => loudnessService.probeSegmentation(), checkShaderEffect: (code, params) => loudnessService.checkShaderEffect(code, params), + stylePresets: () => stylePresets.list(), }), undoAiEditionToolBatch: (_projectId, _sessionId) => ({ success: false, diff --git a/electron/main.ts b/electron/main.ts index 7e6b8d94e4..5d04e8ccd6 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -738,9 +738,26 @@ function showUsagePingToggle(): boolean { return getInstallChannel() !== "dev" && !doNotTrack(process.env); } -function persistUsagePingEnabled(enabled: boolean) { - usagePingEnabled = enabled; - setUsagePingEnabled(app.getPath("userData"), enabled); +/** The box shows a choice once it is stored: one the disk refused leaves it as it was. */ +async function persistUsagePingEnabled(enabled: boolean) { + const userData = app.getPath("userData"); + while (!setUsagePingEnabled(userData, enabled)) { + const choice = await showMessageBox({ + type: "warning", + title: PRODUCT_NAME, + message: + mainT("common", "usagePing.notSaved") || + "OpenScreen could not save this choice, so it is unchanged.", + buttons: [ + mainT("common", "actions.tryAgain") || "Try Again", + mainT("common", "actions.cancel") || "Cancel", + ], + defaultId: 0, + cancelId: 1, + }); + if (choice.response !== 0) break; + } + usagePingEnabled = loadUsagePingState(userData).enabled; updateTrayMenu(isRecording); } @@ -1047,7 +1064,12 @@ function updateTrayMenu(recording: boolean = false) { label: mainT("common", "actions.usagePing") || "Send Anonymous Usage Count", type: "checkbox" as const, checked: usagePingEnabled, - click: () => persistUsagePingEnabled(!usagePingEnabled), + click: (item: Electron.MenuItem) => { + // Electron ticks the box before this runs: it shows the stored choice + // until the new one is stored. + item.checked = usagePingEnabled; + void persistUsagePingEnabled(!usagePingEnabled); + }, }, ] : []), diff --git a/electron/mcp/app-channel.test.ts b/electron/mcp/app-channel.test.ts index 179e6fc200..5ea72ef84a 100644 --- a/electron/mcp/app-channel.test.ts +++ b/electron/mcp/app-channel.test.ts @@ -111,6 +111,8 @@ let appRunTool: McpToolRunner; let channel: AppChannel | null; let http: RunningMcpServer | null; let localCalls: string[]; +/** The tool calls the app counted for its usage ping. */ +let countedCalls: string[]; function cliRouter() { const local = createToolRunner({ @@ -151,11 +153,13 @@ beforeEach(async () => { projects: appProjects, editsAllowed: () => false, version: "0.0.0", + onToolCall: (name) => countedCalls.push(name), }; appRunTool = createToolRunner(appDeps); channel = null; http = null; localCalls = []; + countedCalls = []; }); afterEach(async () => { @@ -339,10 +343,20 @@ describe("checkpoints", () => { const edited = await appProjects.getProject("proj_closed"); expect(edited.timeline.trimRanges).toHaveLength(1); + // getBeforeAfter's read of it comes here too, and is no tool a client is served. + const read = await route("readCheckpoint", { projectId: "proj_closed", checkpointId }); + expect(read.isError).toBeFalsy(); + expect(JSON.parse(text(read)).timeline.trimRanges).toHaveLength(0); + const served = (await client.listTools()).tools.map((tool) => tool.name); + expect(served).not.toContain("readCheckpoint"); + const restored = await route("restoreCheckpoint", { projectId: "proj_closed", checkpointId }); expect(restored.isError).toBeFalsy(); expect((await appProjects.getProject("proj_closed")).timeline.trimRanges).toHaveLength(0); expect(localCalls).toEqual([]); + // The app counts the call its own client made. What `openscreen mcp` forwards was + // counted there, where its client made it: never a second time here. + expect(countedCalls).toEqual(["createCheckpoint"]); } finally { await client.close(); } diff --git a/electron/mcp/app-channel.ts b/electron/mcp/app-channel.ts index 3aa69ed5b7..f7fee6a8a2 100644 --- a/electron/mcp/app-channel.ts +++ b/electron/mcp/app-channel.ts @@ -45,6 +45,8 @@ import { LIST_PROJECTS_TOOL, type McpToolDeps, type McpToolRunner, + READ_CHECKPOINT_SCHEMA, + READ_CHECKPOINT_TOOL, TRANSCRIBE_TOOL, } from "./openscreen-mcp-server"; import { PROJECT_EDIT_TOOLS } from "./project-tools"; @@ -104,7 +106,8 @@ export async function serveAppChannel(options: { }): Promise { const token = randomBytes(32).toString("hex"); const endpoint = newEndpoint(options.userDataDir); - const deps: McpToolDeps = { ...options.deps, editsAllowed: () => true }; + // No tool-call count here: `openscreen mcp` counted each call where its client made it. + const deps: McpToolDeps = { ...options.deps, editsAllowed: () => true, onToolCall: undefined }; const runTool = (name: string, args: unknown) => options.runTool(name, args, { editsAllowed: true }); const sockets = new Set(); @@ -150,6 +153,10 @@ export async function serveAppChannel(options: { }, ), ); + // The checkpoints are this process's: `openscreen mcp` reads one here for getBeforeAfter. + session.registerTool(READ_CHECKPOINT_TOOL, { inputSchema: READ_CHECKPOINT_SCHEMA }, (args) => + options.runTool(READ_CHECKPOINT_TOOL, args, { editsAllowed: true }), + ); socket.once("close", () => void session.close()); // A JSON-RPC-lines transport over any stream pair, despite its name. session.connect(new StdioServerTransport(input, socket)).catch(() => socket.destroy()); diff --git a/electron/mcp/audio-report.test.ts b/electron/mcp/audio-report.test.ts new file mode 100644 index 0000000000..bd09ce2619 --- /dev/null +++ b/electron/mcp/audio-report.test.ts @@ -0,0 +1,224 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { measureWav, readWavLayout } from "./audio-report"; + +type Encoding = "s16" | "s24" | "f32"; + +/** A WAV of `channels` (one array of samples each, in -1..1), as a writer would lay it out. */ +function wav( + channels: Float64Array[], + sampleRate = 48_000, + encoding: Encoding = "s16", + options: { extensible?: boolean; before?: Buffer } = {}, +): Buffer { + const bytesPerSample = encoding === "s16" ? 2 : encoding === "s24" ? 3 : 4; + const frames = channels[0].length; + const data = Buffer.alloc(frames * channels.length * bytesPerSample); + for (let i = 0; i < frames; i++) { + channels.forEach((samples, c) => { + const at = (i * channels.length + c) * bytesPerSample; + const value = Math.max(-1, Math.min(1, samples[i])); + if (encoding === "f32") data.writeFloatLE(value, at); + else if (encoding === "s16") data.writeInt16LE(Math.round(value * 32767), at); + else data.writeIntLE(Math.round(value * 8388607), at, 3); + }); + } + const tag = encoding === "f32" ? 3 : 1; + const fmt = Buffer.alloc(options.extensible ? 40 : 16); + fmt.writeUInt16LE(options.extensible ? 0xfffe : tag, 0); + fmt.writeUInt16LE(channels.length, 2); + fmt.writeUInt32LE(sampleRate, 4); + fmt.writeUInt32LE(sampleRate * channels.length * bytesPerSample, 8); + fmt.writeUInt16LE(channels.length * bytesPerSample, 12); + fmt.writeUInt16LE(bytesPerSample * 8, 14); + if (options.extensible) { + fmt.writeUInt16LE(22, 16); + fmt.writeUInt16LE(bytesPerSample * 8, 18); + fmt.writeUInt16LE(tag, 24); + } + const chunk = (id: string, body: Buffer) => { + const head = Buffer.alloc(8); + head.write(id, 0, "latin1"); + head.writeUInt32LE(body.length, 4); + return Buffer.concat([head, body, Buffer.alloc(body.length % 2)]); + }; + const body = Buffer.concat([ + Buffer.from("WAVE", "latin1"), + chunk("fmt ", fmt), + ...(options.before ? [chunk("LIST", options.before)] : []), + chunk("data", data), + ]); + const riff = Buffer.alloc(8); + riff.write("RIFF", 0, "latin1"); + riff.writeUInt32LE(body.length, 4); + return Buffer.concat([riff, body]); +} + +const dbToAmplitude = (db: number) => 10 ** (db / 20); + +/** A sine at `hz`, `db` dBFS at its crest, for `seconds`. */ +function tone(db: number, seconds: number, sampleRate = 48_000, hz = 1_000, phase = 0) { + const samples = new Float64Array(Math.round(seconds * sampleRate)); + const amplitude = dbToAmplitude(db); + for (let i = 0; i < samples.length; i++) { + samples[i] = amplitude * Math.sin((2 * Math.PI * hz * i) / sampleRate + phase); + } + return samples; +} + +function join(...parts: Float64Array[]): Float64Array { + const joined = new Float64Array(parts.reduce((total, part) => total + part.length, 0)); + let at = 0; + for (const part of parts) { + joined.set(part, at); + at += part.length; + } + return joined; +} + +const silence = (seconds: number, sampleRate = 48_000) => + new Float64Array(Math.round(seconds * sampleRate)); + +let dir = ""; +beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "audio-report-")); +}); +afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); +}); + +async function measure(file: Buffer) { + const filePath = path.join(dir, "audio.wav"); + await fs.writeFile(filePath, file); + return measureWav(filePath); +} + +describe("measureWav", () => { + it("reads a stereo tone at its level: -23 dBFS on both channels is -23 LUFS", async () => { + const sine = tone(-23, 5); + const report = await measure(wav([sine, sine])); + expect(report).toMatchObject({ durationSec: 5, sampleRate: 48_000, channels: 2, silences: [] }); + expect(report.integratedLufs).toBeCloseTo(-23, 1); + expect(report.truePeakDbtp).toBeCloseTo(-23, 1); + }); + + it("weights the same at another sample rate", async () => { + const sine = tone(-23, 5, 44_100); + const report = await measure(wav([sine, sine], 44_100)); + expect(report.sampleRate).toBe(44_100); + expect(report.integratedLufs).toBeCloseTo(-23, 1); + }); + + it("weights low and high tones as the standard's own filter does", async () => { + // BS.1770-4's two filters at 48 kHz, as the standard prints them. A 1 kHz tone cannot tell + // a wrong weighting from a right one; these two can. + const stages = [ + { + b: [1.53512485958697, -2.69169618940638, 1.19839281085285], + a: [1, -1.69065929318241, 0.73248077421585], + }, + { b: [1, -2, 1], a: [1, -1.99004745483398, 0.99007225036621] }, + ]; + const gainDb = (hz: number) => { + const w = (2 * Math.PI * hz) / 48_000; + const power = (c: number[]) => + (c[0] + c[1] * Math.cos(w) + c[2] * Math.cos(2 * w)) ** 2 + + (c[1] * Math.sin(w) + c[2] * Math.sin(2 * w)) ** 2; + return 10 * Math.log10(stages.reduce((all, { b, a }) => (all * power(b)) / power(a), 1)); + }; + // Far from flat: the low tone is turned down, the high one up by several decibels. + expect(gainDb(100)).toBeLessThan(-0.5); + expect(gainDb(10_000)).toBeGreaterThan(3); + for (const hz of [100, 10_000]) { + const sine = tone(-23, 10, 48_000, hz); + const { integratedLufs } = await measure(wav([sine, sine], 48_000, "f32")); + // A stereo sine at -23 dBFS carries a mean square of -23 dB over its two channels. + expect(integratedLufs).toBeCloseTo(-0.691 - 23 + gainDb(hz), 1); + } + }); + + it("finds a peak between the very last samples", async () => { + // Half a second of nothing, then two samples: the wave they belong to crests between them. + const burst = new Float64Array(24_002); + burst[24_000] = Math.SQRT1_2; + burst[24_001] = Math.SQRT1_2; + const { truePeakDbtp } = await measure(wav([burst], 48_000, "f32")); + // The samples themselves stand at -3 dB. + expect(truePeakDbtp).toBeGreaterThan(-2); + expect(truePeakDbtp).toBeLessThan(0); + }); + + it("counts one channel alone 3 LU under two", async () => { + const report = await measure(wav([tone(-23, 5)])); + expect(report.integratedLufs).toBeCloseTo(-26, 1); + }); + + it("finds the peak between the samples, which no sample shows", async () => { + // A quarter of the sample rate, 45° off: every sample sits 3 dB under the wave's crest. + const report = await measure(wav([tone(0, 1, 48_000, 12_000, Math.PI / 4)], 48_000, "f32")); + expect(report.truePeakDbtp).toBeGreaterThan(-0.6); + expect(report.truePeakDbtp).toBeLessThan(0.3); + }); + + it("leaves a quiet passage out of the loudness, as the R128 gate does", async () => { + const mixed = join(tone(-23, 10), tone(-50, 10)); + const report = await measure(wav([mixed, mixed])); + // Ungated, the quiet half would pull the figure down to -26. The few blocks that straddle + // the change of level still count, as the standard has it: a hair under -23. + expect(report.integratedLufs).toBeGreaterThan(-23.2); + expect(report.integratedLufs).toBeLessThan(-22.9); + }); + + it("lists the stretches with no sound of half a second or more, not the shorter ones", async () => { + const film = join(silence(1), tone(-20, 1), silence(0.3), tone(-20, 1), silence(0.8)); + const { silences, durationSec } = await measure(wav([film, film])); + expect(durationSec).toBeCloseTo(4.1, 5); + expect(silences).toHaveLength(2); + expect(silences[0].startSec).toBe(0); + expect(silences[0].endSec).toBeCloseTo(1, 2); + expect(silences[1].startSec).toBeCloseTo(3.3, 2); + expect(silences[1].endSec).toBeCloseTo(4.1, 2); + }); + + it("has no loudness and no peak to give for digital silence", async () => { + const report = await measure(wav([silence(2), silence(2)])); + expect(report.integratedLufs).toBeNull(); + expect(report.truePeakDbtp).toBeNull(); + expect(report.silences).toEqual([{ startSec: 0, endSec: 2 }]); + }); + + it("reads 24-bit samples behind an extensible header and a chunk of tags", async () => { + const sine = tone(-23, 2); + const report = await measure( + wav([sine, sine], 48_000, "s24", { extensible: true, before: Buffer.from("INFOodd") }), + ); + expect(report.channels).toBe(2); + expect(report.durationSec).toBe(2); + expect(report.integratedLufs).toBeCloseTo(-23, 1); + }); + + it("says why it cannot read a file", async () => { + await expect(measure(Buffer.from("not a wav at all"))).rejects.toThrow("Not a WAV file"); + const mp3InWav = wav([tone(-23, 0.1)]); + mp3InWav.writeUInt16LE(85, 20); + await expect(measure(mp3InWav)).rejects.toThrow("Unsupported WAV encoding (format 85)"); + }); +}); + +describe("readWavLayout", () => { + it("runs the samples to the end of the file when a streaming writer left their size open", () => { + const file = wav([tone(-23, 0.01)]); + const dataSizeAt = file.indexOf("data", 0, "latin1") + 4; + file.writeUInt32LE(0xffffffff, dataSizeAt); + const layout = readWavLayout(file, file.length); + expect(layout.dataBytes).toBe(file.length - layout.dataStart); + expect(layout).toMatchObject({ + channels: 1, + sampleRate: 48_000, + bytesPerSample: 2, + float: false, + }); + }); +}); diff --git a/electron/mcp/audio-report.ts b/electron/mcp/audio-report.ts new file mode 100644 index 0000000000..93b55f2628 --- /dev/null +++ b/electron/mcp/audio-report.ts @@ -0,0 +1,350 @@ +// What a film sounds like, in numbers: its integrated loudness, its true peak and the stretches +// with no sound at all, measured on the WAV an audio export writes. An agent cannot listen, and +// a still frame says nothing of the sound: these three numbers are how it checks a mix. +// +// The file is read in chunks and measured as it goes, so an hour of audio costs no more memory +// than a minute. + +import { open } from "node:fs/promises"; + +export interface AudioReport { + durationSec: number; + sampleRate: number; + channels: number; + /** LUFS, per ITU-R BS.1770-4 with the EBU R128 gates; `null` when nothing clears them. */ + integratedLufs: number | null; + /** dBTP, the highest peak of the signal oversampled four times; `null` for digital silence. */ + truePeakDbtp: number | null; + /** Every stretch of at least `SILENCE_MIN_SEC` that stays under `SILENCE_FLOOR`. */ + silences: Array<{ startSec: number; endSec: number }>; +} + +/** Under -60 dBFS nothing is heard: an encoder's dither, not a sound someone placed. */ +const SILENCE_FLOOR = 10 ** (-60 / 20); +/** Shorter than this is a breath between two words, not dead air. */ +const SILENCE_MIN_SEC = 0.5; + +const ABSOLUTE_GATE_LUFS = -70; +const RELATIVE_GATE_LU = -10; +/** Gating blocks last 400 ms and overlap by 75 %: four hops of 100 ms. */ +const HOPS_PER_BLOCK = 4; + +/** Samples each side of an oversampled point: BS.1770's own interpolator spans as many. */ +const TAPS_PER_PHASE = 12; +const OVERSAMPLING = 4; + +type Biquad = readonly [b0: number, b1: number, b2: number, a1: number, a2: number]; + +/** The K-weighting of BS.1770 at any sample rate: a high shelf for the head, then a high-pass. + * Derived from the standard's analogue prototypes, as libebur128 does; at 48 kHz they are the + * standard's own coefficients. */ +function kWeighting(sampleRate: number): [Biquad, Biquad] { + const shelfK = Math.tan((Math.PI * 1681.974450955533) / sampleRate); + const shelfQ = 0.7071752369554196; + const vh = 10 ** (3.999843853973347 / 20); + const vb = vh ** 0.4996667741545416; + const shelfNorm = 1 + shelfK / shelfQ + shelfK * shelfK; + const passK = Math.tan((Math.PI * 38.13547087602444) / sampleRate); + const passQ = 0.5003270373238773; + const passNorm = 1 + passK / passQ + passK * passK; + return [ + [ + (vh + (vb * shelfK) / shelfQ + shelfK * shelfK) / shelfNorm, + (2 * (shelfK * shelfK - vh)) / shelfNorm, + (vh - (vb * shelfK) / shelfQ + shelfK * shelfK) / shelfNorm, + (2 * (shelfK * shelfK - 1)) / shelfNorm, + (1 - shelfK / shelfQ + shelfK * shelfK) / shelfNorm, + ], + [ + 1, + -2, + 1, + (2 * (passK * passK - 1)) / passNorm, + (1 - passK / passQ + passK * passK) / passNorm, + ], + ]; +} + +/** A windowed-sinc interpolator, one row of taps per point between two samples. Each row sums + * to one, so a steady level comes through at its own height. */ +function interpolator(): Float64Array[] { + const length = TAPS_PER_PHASE * OVERSAMPLING; + const centre = (length - 1) / 2; + return Array.from({ length: OVERSAMPLING }, (_, phase) => { + const taps = new Float64Array(TAPS_PER_PHASE); + let sum = 0; + for (let k = 0; k < TAPS_PER_PHASE; k++) { + const n = k * OVERSAMPLING + phase; + const x = (Math.PI * (n - centre)) / OVERSAMPLING; + const sinc = x === 0 ? 1 : Math.sin(x) / x; + const window = 0.5 - 0.5 * Math.cos((2 * Math.PI * (n + 0.5)) / length); + taps[k] = sinc * window; + sum += taps[k]; + } + return taps.map((tap) => tap / sum); + }); +} + +const INTERPOLATOR = interpolator(); + +/** Measures interleaved samples pushed frame by frame. */ +class AudioMeter { + private readonly filters: [Biquad, Biquad]; + /** Per channel, the two filters' memories: x1, x2, y1, y2, twice. */ + private readonly state: Float64Array; + /** Per channel, the last `TAPS_PER_PHASE` samples, oldest first from `historyAt`. */ + private readonly history: Float64Array; + private historyAt = 0; + private readonly hopFrames: number; + private hopEnergy = 0; + private hopFilled = 0; + /** Mean square of each finished 100 ms hop, the channels summed. */ + private readonly hops: number[] = []; + private peak = 0; + private frames = 0; + private quietSince: number | null = 0; + private readonly silences: Array<{ startSec: number; endSec: number }> = []; + + constructor( + private readonly sampleRate: number, + private readonly channels: number, + ) { + this.filters = kWeighting(sampleRate); + this.state = new Float64Array(channels * 8); + this.history = new Float64Array(channels * TAPS_PER_PHASE); + this.hopFrames = Math.round(sampleRate / 10); + } + + /** One frame: `frame[c]` is channel `c`'s sample, in -1..1. */ + push(frame: Float64Array): void { + let loudest = 0; + for (let c = 0; c < this.channels; c++) { + const x = frame[c]; + const magnitude = Math.abs(x); + if (magnitude > loudest) loudest = magnitude; + this.hopEnergy += this.weighted(c, x) ** 2; + this.history[c * TAPS_PER_PHASE + this.historyAt] = x; + } + this.historyAt = (this.historyAt + 1) % TAPS_PER_PHASE; + if (loudest > this.peak) this.peak = loudest; + this.measureBetweenSamples(); + + if (loudest < SILENCE_FLOOR) { + this.quietSince ??= this.frames; + } else { + this.endSilence(this.frames); + } + this.frames++; + if (++this.hopFilled === this.hopFrames) { + this.hops.push(this.hopEnergy / this.hopFrames); + this.hopEnergy = 0; + this.hopFilled = 0; + } + } + + private weighted(channel: number, x: number): number { + const s = this.state; + let value = x; + for (let stage = 0; stage < 2; stage++) { + const [b0, b1, b2, a1, a2] = this.filters[stage]; + const at = channel * 8 + stage * 4; + const y = b0 * value + b1 * s[at] + b2 * s[at + 1] - a1 * s[at + 2] - a2 * s[at + 3]; + s[at + 1] = s[at]; + s[at] = value; + s[at + 3] = s[at + 2]; + s[at + 2] = y; + value = y; + } + return value; + } + + /** The signal between the two samples in the middle of the history, where the interpolator + * is centred: half its span behind the newest sample. */ + private measureBetweenSamples(): void { + // The newest sample, kept positive for the modulo below. + const newest = this.historyAt - 1 + TAPS_PER_PHASE; + const half = TAPS_PER_PHASE / 2; + for (let c = 0; c < this.channels; c++) { + const base = c * TAPS_PER_PHASE; + const around = Math.max( + Math.abs(this.history[base + ((newest - half + 1) % TAPS_PER_PHASE)]), + Math.abs(this.history[base + ((newest - half) % TAPS_PER_PHASE)]), + ); + // A peak between two samples rises a few decibels above them at most: where they are + // well under the peak already found, there is none to look for. + if (around === 0 || around * 2 < this.peak) continue; + for (const taps of INTERPOLATOR) { + let value = 0; + for (let k = 0; k < TAPS_PER_PHASE; k++) { + value += taps[k] * this.history[base + ((newest - k) % TAPS_PER_PHASE)]; + } + if (Math.abs(value) > this.peak) this.peak = Math.abs(value); + } + } + } + + /** Lets the last samples reach the middle of the history: a peak right at the end counts. */ + private flushHistory(): void { + for (let i = 0; i < TAPS_PER_PHASE / 2; i++) { + for (let c = 0; c < this.channels; c++) { + this.history[c * TAPS_PER_PHASE + this.historyAt] = 0; + } + this.historyAt = (this.historyAt + 1) % TAPS_PER_PHASE; + this.measureBetweenSamples(); + } + } + + private endSilence(atFrame: number): void { + if (this.quietSince === null) return; + const startSec = this.quietSince / this.sampleRate; + const endSec = atFrame / this.sampleRate; + if (endSec - startSec >= SILENCE_MIN_SEC) this.silences.push({ startSec, endSec }); + this.quietSince = null; + } + + finish(): AudioReport { + this.endSilence(this.frames); + this.flushHistory(); + return { + durationSec: this.frames / this.sampleRate, + sampleRate: this.sampleRate, + channels: this.channels, + integratedLufs: this.integratedLoudness(), + truePeakDbtp: this.peak > 0 ? 20 * Math.log10(this.peak) : null, + silences: this.silences, + }; + } + + private integratedLoudness(): number | null { + const blocks: number[] = []; + for (let i = 0; i + HOPS_PER_BLOCK <= this.hops.length; i++) { + let sum = 0; + for (let k = 0; k < HOPS_PER_BLOCK; k++) sum += this.hops[i + k]; + blocks.push(sum / HOPS_PER_BLOCK); + } + const lufs = (meanSquare: number) => -0.691 + 10 * Math.log10(meanSquare); + const mean = (values: number[]) => + values.reduce((sum, value) => sum + value, 0) / values.length; + const heard = blocks.filter((block) => lufs(block) > ABSOLUTE_GATE_LUFS); + if (heard.length === 0) return null; + const relativeGate = lufs(mean(heard)) + RELATIVE_GATE_LU; + const counted = heard.filter((block) => lufs(block) > relativeGate); + return counted.length === 0 ? null : lufs(mean(counted)); + } +} + +interface WavLayout { + sampleRate: number; + channels: number; + bytesPerSample: number; + float: boolean; + dataStart: number; + dataBytes: number; +} + +const WAVE_FORMAT_PCM = 1; +const WAVE_FORMAT_FLOAT = 3; +const WAVE_FORMAT_EXTENSIBLE = 0xfffe; + +/** Where a WAV's samples are and how they are written, from its header. */ +export function readWavLayout(header: Buffer, fileBytes: number): WavLayout { + if ( + header.length < 12 || + header.toString("latin1", 0, 4) !== "RIFF" || + header.toString("latin1", 8, 12) !== "WAVE" + ) { + throw new Error("Not a WAV file"); + } + let format: Omit | null = null; + let at = 12; + while (at + 8 <= header.length) { + const id = header.toString("latin1", at, at + 4); + const size = header.readUInt32LE(at + 4); + const body = at + 8; + if (id === "fmt " && body + 16 <= header.length) { + let tag = header.readUInt16LE(body); + const bits = header.readUInt16LE(body + 14); + // The extensible form keeps the real format in the first bytes of its sub-format. + if (tag === WAVE_FORMAT_EXTENSIBLE && size >= 26 && body + 26 <= header.length) { + tag = header.readUInt16LE(body + 24); + } + if (tag !== WAVE_FORMAT_PCM && tag !== WAVE_FORMAT_FLOAT) { + throw new Error(`Unsupported WAV encoding (format ${tag})`); + } + format = { + channels: header.readUInt16LE(body + 2), + sampleRate: header.readUInt32LE(body + 4), + bytesPerSample: bits / 8, + float: tag === WAVE_FORMAT_FLOAT, + }; + } else if (id === "data") { + if (!format) throw new Error("The WAV's samples come before its format"); + const supported = format.float + ? [4, 8].includes(format.bytesPerSample) + : [1, 2, 3, 4].includes(format.bytesPerSample); + if (!supported || format.channels < 1 || format.sampleRate < 1) { + throw new Error("Unsupported WAV sample format"); + } + // A writer that streams leaves the size at zero or all ones: the samples run to the end. + const declared = size === 0 || size === 0xffffffff ? Number.POSITIVE_INFINITY : size; + return { ...format, dataStart: body, dataBytes: Math.min(declared, fileBytes - body) }; + } + at = body + size + (size % 2); + } + throw new Error("The WAV has no samples"); +} + +function sampleReader(layout: WavLayout): (buffer: Buffer, at: number) => number { + if (layout.float) { + return layout.bytesPerSample === 4 + ? (buffer, at) => buffer.readFloatLE(at) + : (buffer, at) => buffer.readDoubleLE(at); + } + switch (layout.bytesPerSample) { + case 1: + return (buffer, at) => (buffer[at] - 128) / 128; + case 2: + return (buffer, at) => buffer.readInt16LE(at) / 32768; + case 3: + return (buffer, at) => buffer.readIntLE(at, 3) / 8388608; + default: + return (buffer, at) => buffer.readInt32LE(at) / 2147483648; + } +} + +/** Enough for the chunks a writer puts before the samples (a LIST of tags, say). */ +const HEADER_BYTES = 64 * 1024; +const CHUNK_FRAMES = 16_384; + +/** Measures the WAV at `path`. Throws, saying why, when it is not a WAV this reads. */ +export async function measureWav(path: string): Promise { + const file = await open(path, "r"); + try { + const { size } = await file.stat(); + const header = Buffer.alloc(Math.min(HEADER_BYTES, size)); + await file.read(header, 0, header.length, 0); + const layout = readWavLayout(header, size); + const read = sampleReader(layout); + const frameBytes = layout.bytesPerSample * layout.channels; + const meter = new AudioMeter(layout.sampleRate, layout.channels); + const frame = new Float64Array(layout.channels); + const chunk = Buffer.alloc(CHUNK_FRAMES * frameBytes); + const end = layout.dataStart + layout.dataBytes - (layout.dataBytes % frameBytes); + for (let position = layout.dataStart; position < end; ) { + const wanted = Math.min(chunk.length, end - position); + const { bytesRead } = await file.read(chunk, 0, wanted, position); + const whole = bytesRead - (bytesRead % frameBytes); + if (whole === 0) break; + for (let at = 0; at < whole; at += frameBytes) { + for (let c = 0; c < layout.channels; c++) { + frame[c] = read(chunk, at + c * layout.bytesPerSample); + } + meter.push(frame); + } + position += whole; + } + return meter.finish(); + } finally { + await file.close(); + } +} diff --git a/electron/mcp/contact-sheet.test.ts b/electron/mcp/contact-sheet.test.ts new file mode 100644 index 0000000000..6a12c08408 --- /dev/null +++ b/electron/mcp/contact-sheet.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, it } from "vitest"; +import { + type Bitmap, + changedRegion, + composeContactSheet, + regionRect, + tileWidthFor, +} from "./contact-sheet"; + +/** A tile of one value, so a pixel says which tile it came from. */ +function flat(width: number, height: number, value: number): Bitmap { + return { width, height, pixels: Buffer.alloc(width * height * 4, value) }; +} + +function pixel(bitmap: Bitmap, x: number, y: number): number { + return bitmap.pixels[(y * bitmap.width + x) * 4]; +} + +/** How many pixels of a rectangle hold `value`. */ +function count( + bitmap: Bitmap, + left: number, + top: number, + width: number, + height: number, + value: number, +) { + let found = 0; + for (let y = top; y < top + height; y++) { + for (let x = left; x < left + width; x++) { + if (pixel(bitmap, x, y) === value) found++; + } + } + return found; +} + +describe("regionRect", () => { + it("turns fractions into pixels of the picture", () => { + expect(regionRect(1920, 1080, { x: 0.5, y: 0.25, width: 0.25, height: 0.5 })).toEqual({ + x: 960, + y: 270, + width: 480, + height: 540, + }); + }); + + it("stays inside the picture, and never comes out empty", () => { + expect(regionRect(100, 50, { x: 0.9, y: 0.9, width: 0.5, height: 0.5 })).toEqual({ + x: 90, + y: 45, + width: 10, + height: 5, + }); + expect(regionRect(100, 50, { x: 1, y: 1, width: 0.001, height: 0.001 })).toEqual({ + x: 99, + y: 49, + width: 1, + height: 1, + }); + }); +}); + +describe("tileWidthFor", () => { + it("fits the columns and their gaps in the width of one frame", () => { + expect(tileWidthFor(4)).toBe(318); + expect(4 * tileWidthFor(4) + 3 * 2).toBeLessThanOrEqual(1280); + expect(6 * tileWidthFor(6) + 5 * 2).toBeLessThanOrEqual(1280); + expect(tileWidthFor(2)).toBe(639); + }); +}); + +describe("changedRegion", () => { + /** A flat picture with one pixel set apart. */ + function withPixel(x: number, y: number, value: number): Bitmap { + const bitmap = flat(100, 50, 60); + bitmap.pixels.fill(value, (y * 100 + x) * 4, (y * 100 + x) * 4 + 3); + return bitmap; + } + + it("finds nothing between two pictures that match", () => { + expect(changedRegion(flat(100, 50, 60), flat(100, 50, 60))).toBeNull(); + }); + + it("boxes every changed pixel, in fractions of the picture", () => { + const after = flat(100, 50, 60); + for (const [x, y] of [ + [20, 10], + [59, 10], + [40, 29], + ]) { + after.pixels.fill(200, (y * 100 + x) * 4, (y * 100 + x) * 4 + 3); + } + expect(changedRegion(flat(100, 50, 60), after)).toEqual({ + share: 3 / 5000, + region: { x: 0.2, y: 0.2, width: 0.4, height: 0.4 }, + }); + }); + + it("lets through what resampling leaves, and catches a faint tint", () => { + const before = flat(100, 50, 60); + expect(changedRegion(before, withPixel(5, 5, 68))).toBeNull(); + expect(changedRegion(before, withPixel(5, 5, 69))?.share).toBe(1 / 5000); + // One channel is enough: a tint moves a colour, not a brightness. + const tinted = flat(100, 50, 60); + tinted.pixels[(5 * 100 + 5) * 4 + 2] = 90; + expect(changedRegion(before, tinted)?.region).toEqual({ + x: 0.05, + y: 0.1, + width: 0.01, + height: 0.02, + }); + }); +}); + +describe("a sheet of thin strips", () => { + it("gives each row the height of its label, so no time spills into the next cell", () => { + const tileWidth = tileWidthFor(2); + // Three strips one pixel high, two across: the fourth cell stays empty. + const strip = () => flat(tileWidth, 1, 120); + const sheet = composeContactSheet( + [ + { bitmap: strip(), label: "1.00s" }, + { bitmap: strip(), label: "2.00s" }, + { bitmap: strip(), label: "3.00s" }, + ], + 2, + tileWidth, + 1, + ); + // A label plate is 9 glyph rows of 4 px at this width: each row is that tall. + expect(sheet.height).toBe(2 * 36 + 2); + // The third strip starts the second row, at 36 + 2, seen right of its label plate... + expect(count(sheet, tileWidth - 10, 38, 10, 1, 120)).toBe(10); + // ...and the gap above it is background: it was not laid over the first label. + expect(count(sheet, 0, 36, tileWidth, 2, 32)).toBe(tileWidth * 2); + // The empty fourth cell is background all over: the second label did not reach it. + expect(count(sheet, tileWidth + 2, 38, tileWidth, 36, 32)).toBe(tileWidth * 36); + }); +}); + +describe("composeContactSheet", () => { + const tileWidth = 80; + const tileHeight = 45; + const sheet = composeContactSheet( + [ + { bitmap: flat(tileWidth, tileHeight, 100), label: "0.50s" }, + { bitmap: flat(tileWidth, tileHeight, 150), label: "1.00s" }, + { bitmap: null, label: "9.99s" }, + ], + 2, + tileWidth, + tileHeight, + ); + + it("lays the tiles out in reading order, a gap apart", () => { + expect(sheet.width).toBe(2 * tileWidth + 2); + expect(sheet.height).toBe(2 * tileHeight + 2); + expect(sheet.pixels).toHaveLength(sheet.width * sheet.height * 4); + // Bottom-right of each tile: clear of its label. + expect(pixel(sheet, tileWidth - 1, tileHeight - 1)).toBe(100); + expect(pixel(sheet, tileWidth + 2 + tileWidth - 1, tileHeight - 1)).toBe(150); + // The gap, and the place of the tile that has no frame. + expect(pixel(sheet, tileWidth, 10)).toBe(32); + expect(pixel(sheet, tileWidth - 1, tileHeight + 2 + tileHeight - 1)).toBe(32); + // No tile in the last cell. + expect(pixel(sheet, tileWidth + 2 + 10, tileHeight + 2 + 30)).toBe(32); + }); + + it("is opaque everywhere", () => { + for (let alpha = 3; alpha < sheet.pixels.length; alpha += 4) { + if (sheet.pixels[alpha] !== 255) throw new Error(`transparent at byte ${alpha}`); + } + }); + + it("prints each tile's time in white on a black plate, the missing frame's too", () => { + // "0.50s" at scale 2: five characters, 12 px each, on a plate 18 px high. + for (const [left, top] of [ + [0, 0], + [tileWidth + 2, 0], + [0, tileHeight + 2], + ]) { + const white = count(sheet, left, top, 62, 18, 255); + const black = count(sheet, left, top, 62, 18, 0); + expect(white).toBeGreaterThan(40); + expect(black).toBeGreaterThan(white); + expect(white + black).toBe(62 * 18); + } + }); + + it("draws different times differently, and the same time the same", () => { + const one = composeContactSheet([{ bitmap: null, label: "1.00s" }], 1, 80, 45); + const same = composeContactSheet([{ bitmap: null, label: "1.00s" }], 1, 80, 45); + const other = composeContactSheet([{ bitmap: null, label: "7.25s" }], 1, 80, 45); + expect(one.pixels.equals(same.pixels)).toBe(true); + expect(one.pixels.equals(other.pixels)).toBe(false); + }); + + it("cuts a tile larger than its cell instead of spilling into the next", () => { + const spilled = composeContactSheet( + [ + { bitmap: flat(tileWidth + 20, tileHeight + 20, 200), label: "" }, + { bitmap: flat(tileWidth, tileHeight, 90), label: "" }, + ], + 2, + tileWidth, + tileHeight, + ); + expect(pixel(spilled, tileWidth, 20)).toBe(32); + expect(pixel(spilled, tileWidth + 2, 20)).toBe(90); + }); +}); diff --git a/electron/mcp/contact-sheet.ts b/electron/mcp/contact-sheet.ts new file mode 100644 index 0000000000..8d5db1adf3 --- /dev/null +++ b/electron/mcp/contact-sheet.ts @@ -0,0 +1,219 @@ +// A contact sheet: frames of a video laid out as one picture, each with its time on it, so a +// client reads a film's rhythm, or a transition frame by frame, for the cost of one image. +// +// Pixels only. The host decodes and encodes (frame-images.ts, Electron's own codec), so the +// layout and the labels run under plain vitest. + +/** Raw pixels, four bytes each, in whatever channel order the host's decoder gives. The sheet + * only moves them and draws in white, black and grey, which read the same in any order. */ +export interface Bitmap { + width: number; + height: number; + pixels: Buffer; +} + +/** Part of a frame, as fractions of its width and height from its top-left corner. */ +export interface FrameRegion { + x: number; + y: number; + width: number; + height: number; +} + +/** The pixel work the media tools ask their host for. */ +export interface FrameImages { + /** A JPEG's pixels, scaled down to at most `maxWidth` wide. */ + decode(jpeg: Buffer, maxWidth: number): Bitmap; + encode(bitmap: Bitmap): Buffer; + /** The part of a JPEG inside `region`, at its own resolution, scaled down only when it is + * wider than `maxWidth`. */ + crop(jpeg: Buffer, region: FrameRegion, maxWidth: number): Buffer; +} + +/** `region` in whole pixels of a `width` by `height` picture: inside it, and never empty. */ +export function regionRect( + width: number, + height: number, + region: FrameRegion, +): { x: number; y: number; width: number; height: number } { + const x = Math.min(width - 1, Math.max(0, Math.round(region.x * width))); + const y = Math.min(height - 1, Math.max(0, Math.round(region.y * height))); + return { + x, + y, + width: Math.max(1, Math.min(width - x, Math.round(region.width * width))), + height: Math.max(1, Math.min(height - y, Math.round(region.height * height))), + }; +} + +/** How far a channel must move for a pixel to count as changed: above what resampling leaves + * beside an edit, below a faint tint or shadow. */ +const CHANGE_THRESHOLD = 8; + +/** + * Where two pictures of the same size differ: the share of their pixels that changed, and the + * box around all of them as fractions of the picture, the form a frame's `region` takes. + * `null` when no pixel changed. + */ +export function changedRegion( + before: Bitmap, + after: Bitmap, +): { share: number; region: FrameRegion } | null { + const { width, height } = before; + let changed = 0; + let left = width; + let top = height; + let right = -1; + let bottom = -1; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const at = (y * width + x) * 4; + if ( + Math.abs(before.pixels[at] - after.pixels[at]) <= CHANGE_THRESHOLD && + Math.abs(before.pixels[at + 1] - after.pixels[at + 1]) <= CHANGE_THRESHOLD && + Math.abs(before.pixels[at + 2] - after.pixels[at + 2]) <= CHANGE_THRESHOLD + ) { + continue; + } + changed++; + left = Math.min(left, x); + right = Math.max(right, x); + top = Math.min(top, y); + bottom = Math.max(bottom, y); + } + } + if (changed === 0) return null; + return { + share: changed / (width * height), + region: { + x: left / width, + y: top / height, + width: (right - left + 1) / width, + height: (bottom - top + 1) / height, + }, + }; +} + +/** As wide as a single frame of getFrames, so a sheet costs a client what one frame does. */ +const SHEET_WIDTH = 1280; +/** Between two tiles: enough to tell where one frame ends. */ +const GAP = 2; +/** Behind the tiles, and in place of a frame the video does not have. */ +const BACKGROUND = 32; + +export function tileWidthFor(columns: number): number { + return Math.floor((SHEET_WIDTH - GAP * (columns - 1)) / columns); +} + +// Five by seven, the characters a time takes: "12.40s". +const GLYPHS: Record = { + "0": [".###.", "#...#", "#..##", "#.#.#", "##..#", "#...#", ".###."], + "1": ["..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###."], + "2": [".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####"], + "3": [".###.", "#...#", "....#", "..##.", "....#", "#...#", ".###."], + "4": ["...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#."], + "5": ["#####", "#....", "####.", "....#", "....#", "#...#", ".###."], + "6": ["..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###."], + "7": ["#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..."], + "8": [".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###."], + "9": [".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##.."], + ".": [".....", ".....", ".....", ".....", ".....", ".##..", ".##.."], + s: [".....", ".....", ".####", "#....", ".###.", "....#", "####."], +}; +const GLYPH_WIDTH = 5; +const GLYPH_HEIGHT = 7; + +export interface SheetTile { + /** `null` where the video has no frame: the tile keeps its place and its label. */ + bitmap: Bitmap | null; + label: string; +} + +/** The tiles in reading order, `columns` across, each `tileWidth` by `tileHeight`. */ +export function composeContactSheet( + tiles: readonly SheetTile[], + columns: number, + tileWidth: number, + tileHeight: number, +): Bitmap { + // Read at a glance on a narrow tile, without covering a wide one. + const scale = Math.max(2, Math.round(tileWidth / 160)); + // A row is never shorter than its labels: a thin strip cropped out of a frame still has its + // time in its own cell, not over the next row. + const rowHeight = Math.max(tileHeight, (GLYPH_HEIGHT + 2) * scale); + const rows = Math.ceil(tiles.length / columns); + const width = columns * tileWidth + (columns - 1) * GAP; + const height = rows * rowHeight + (rows - 1) * GAP; + const pixels = Buffer.alloc(width * height * 4, BACKGROUND); + const sheet = { width, height, pixels }; + tiles.forEach((tile, i) => { + const left = (i % columns) * (tileWidth + GAP); + const top = Math.floor(i / columns) * (rowHeight + GAP); + if (tile.bitmap) blit(sheet, tile.bitmap, left, top, tileWidth, tileHeight); + drawLabel(sheet, tile.label, left, top, scale); + }); + // Opaque whatever the tiles carried: a sheet is a picture, not a layer. + for (let alpha = 3; alpha < pixels.length; alpha += 4) pixels[alpha] = 255; + return sheet; +} + +/** Copies `source` onto `sheet` at (`left`, `top`), cut to `maxWidth` by `maxHeight`. */ +function blit( + sheet: Bitmap, + source: Bitmap, + left: number, + top: number, + maxWidth: number, + maxHeight: number, +): void { + const rowBytes = Math.min(source.width, maxWidth) * 4; + const rows = Math.min(source.height, maxHeight); + for (let y = 0; y < rows; y++) { + const from = y * source.width * 4; + source.pixels.copy(sheet.pixels, ((top + y) * sheet.width + left) * 4, from, from + rowBytes); + } +} + +function fill( + sheet: Bitmap, + left: number, + top: number, + width: number, + height: number, + value: number, +): void { + const right = Math.min(sheet.width, left + width); + const bottom = Math.min(sheet.height, top + height); + for (let y = top; y < bottom; y++) { + const row = y * sheet.width; + for (let x = left; x < right; x++) { + const at = (row + x) * 4; + sheet.pixels[at] = value; + sheet.pixels[at + 1] = value; + sheet.pixels[at + 2] = value; + } + } +} + +/** White on a black plate, in the tile's top-left corner: readable over any frame. */ +function drawLabel(sheet: Bitmap, label: string, left: number, top: number, scale: number): void { + const advance = (GLYPH_WIDTH + 1) * scale; + fill(sheet, left, top, label.length * advance + scale, (GLYPH_HEIGHT + 2) * scale, 0); + [...label].forEach((character, index) => { + const glyph = GLYPHS[character]; + if (!glyph) return; + glyph.forEach((row, y) => { + for (let x = 0; x < GLYPH_WIDTH; x++) { + if (row[x] !== "#") continue; + fill( + sheet, + left + scale + index * advance + x * scale, + top + scale + y * scale, + scale, + scale, + 255, + ); + } + }); + }); +} diff --git a/electron/mcp/effects-contract.ts b/electron/mcp/effects-contract.ts index 414cbbe236..ba41dcd9a0 100644 --- a/electron/mcp/effects-contract.ts +++ b/electron/mcp/effects-contract.ts @@ -70,6 +70,29 @@ Declare each one as \`{ type, name, label, default }\`; a number also takes \`mi Names are snake_case. Up to 8 is recommended. Declare a parameter only when moving it visibly changes the effect over its whole range: each one becomes a control in the editor. +## Animating a parameter + +A region can move a parameter over time instead of holding one value: pass \`animate\` to +addEffect or setEffect, a list of keyframes per parameter. + + "animate": { "strength": [ + { "atSec": 0, "value": 0, "ease": "ease-out" }, + { "atSec": 0.6, "value": 1.5 }, + { "atSec": 2, "value": 1 } + ] } + +- **atSec** counts from the start of the region, on the clock of \`ctx.region.z\`. Before the first + keyframe the parameter holds its value, and after the last too. +- **ease** shapes the move to the next keyframe: \`linear\` (default), \`hold\`, \`ease-in\`, + \`ease-out\`, \`ease-in-out\`, a cubic-bezier \`[x1, y1, x2, y2]\`, or + \`{ "spring": { "bounce": 0.3 } }\` (bounce 0 to 0.9). A toggle always holds. +- Up to 64 keyframes per parameter. In setEffect, a parameter you pass replaces its whole list and + an empty list removes it. + +Use \`animate\` when the motion is a timing decision (a fade in, a pulse at a given second): it stays +tunable without rewriting the shader. The shader reads \`params.\` as usual. Write the motion +into the code only when it follows something the shader computes itself (a click, the cursor). + ## Rules - **Pure.** The result depends only on uv, frame(), footage(), ctx and params. No state between frames, no diff --git a/electron/mcp/frame-images.ts b/electron/mcp/frame-images.ts new file mode 100644 index 0000000000..6ae02af185 --- /dev/null +++ b/electron/mcp/frame-images.ts @@ -0,0 +1,36 @@ +// The media tools' pixel work, done by Electron's own image codec: no window, no canvas and no +// dependency. Both servers hand this to the tools (media-tools.ts), which import no `electron`. + +import { nativeImage } from "electron"; +import { type FrameImages, regionRect } from "./contact-sheet"; + +/** What the addon and the hidden video window encode their frames at. */ +const JPEG_QUALITY = 85; + +function decoded(jpeg: Buffer): Electron.NativeImage { + const image = nativeImage.createFromBuffer(jpeg); + if (image.isEmpty()) throw new Error("a frame is not a picture this build can decode"); + return image; +} + +/** No wider than `maxWidth`: scaled down, never up. */ +function fitted(image: Electron.NativeImage, maxWidth: number): Electron.NativeImage { + return image.getSize().width > maxWidth + ? image.resize({ width: Math.max(1, Math.round(maxWidth)), quality: "best" }) + : image; +} + +export const frameImages: FrameImages = { + decode(jpeg, maxWidth) { + const image = fitted(decoded(jpeg), maxWidth); + return { ...image.getSize(), pixels: image.toBitmap() }; + }, + encode({ width, height, pixels }) { + return nativeImage.createFromBitmap(pixels, { width, height }).toJPEG(JPEG_QUALITY); + }, + crop(jpeg, region, maxWidth) { + const image = decoded(jpeg); + const { width, height } = image.getSize(); + return fitted(image.crop(regionRect(width, height, region)), maxWidth).toJPEG(JPEG_QUALITY); + }, +}; diff --git a/electron/mcp/media-tools.test.ts b/electron/mcp/media-tools.test.ts index 126a5cfd26..6855be5a5e 100644 --- a/electron/mcp/media-tools.test.ts +++ b/electron/mcp/media-tools.test.ts @@ -2,6 +2,7 @@ // hand projects to: a real DocumentService on a temp directory, the real tool // runner, and stand-ins for the runner windows and the video decoder. +import { writeFileSync } from "node:fs"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -42,6 +43,8 @@ class FakeRunners { holdExport = false; releaseExport: () => void = () => undefined; private exportHeld: () => void = () => undefined; + /** What an audio render to a WAV writes, as the export runner would. */ + wav: Buffer | null = null; open = 0; constructor(private readonly videoPath: string) {} @@ -86,6 +89,10 @@ class FakeRunners { }, }; const result = this.results[request.kind] ?? { success: true }; + const rendersWav = request.kind === "export" && request.format === "wav"; + if (rendersWav && request.outPath && this.wav && result.success) { + writeFileSync(request.outPath, this.wav); + } if (request.kind === "export" && this.holdExport) { this.releaseExport = () => finish(result); this.exportHeld(); @@ -123,6 +130,8 @@ let videoPath = ""; let documents: DocumentService; let runners: FakeRunners; let closed: number; +/** The widths the video decoder was asked for its frames at, in order. */ +let capturedWidths: number[]; let openVideoFails: boolean; let client: Client; let media: ReturnType; @@ -130,6 +139,8 @@ let media: ReturnType; let stdioDeps: MediaToolDeps; /** The addon's frame renderer, when a test gives it one: none by default, as an older addon. */ let renderFrames: MediaToolDeps["renderFrames"]; +/** The tool calls the server reported for the usage count: names, in order. */ +let countedCalls: string[]; /** The pointer recorded with the take, as the sidecar beside the video. */ async function readSidecar(video: string): Promise { @@ -149,8 +160,10 @@ beforeEach(async () => { await fs.writeFile(`${videoPath}.cursor.json`, JSON.stringify({ samples: clickTrack() })); runners = new FakeRunners(videoPath); closed = 0; + capturedWidths = []; openVideoFails = false; renderFrames = undefined; + countedCalls = []; const toolDeps: McpToolDeps = { transport: "stdio", @@ -158,6 +171,7 @@ beforeEach(async () => { projects: documents, editsAllowed: () => true, version: "test", + onToolCall: (name) => countedCalls.push(name), }; const runTool = createToolRunner(toolDeps); stdioDeps = { @@ -171,10 +185,13 @@ beforeEach(async () => { durationSec: 12, width: 1920, height: 1080, - capture: async (timeSec) => ({ - mimeType: "image/jpeg", - data: Buffer.from(`frame@${timeSec}`).toString("base64"), - }), + capture: async (timeSec, maxWidth) => { + capturedWidths.push(maxWidth); + return { + mimeType: "image/jpeg", + data: Buffer.from(`frame@${timeSec}`).toString("base64"), + }; + }, close: () => { closed++; }, @@ -182,6 +199,30 @@ beforeEach(async () => { }, readCursor: readSidecar, renderFrames: async (...args) => (renderFrames ? renderFrames(...args) : null), + // The host's image codec: a frame decodes to a flat 16:9 picture as wide as asked, and + // a crop or a sheet says what it was made from. + images: { + decode: (jpeg, maxWidth) => { + // A frame marked tall decodes square: a file whose size changes midway. + const height = jpeg.includes("tall") ? maxWidth : Math.round((maxWidth * 9) / 16); + const pixels = Buffer.alloc(maxWidth * height * 4, 7); + // A frame that names a box holds one: two frames can then differ somewhere known. + const box = /box (\d+),(\d+) (\d+)x(\d+)/.exec(jpeg.toString()); + if (box) { + const [left, top, boxWidth, boxHeight] = box.slice(1).map(Number); + for (let y = top; y < top + boxHeight; y++) { + const row = (y * maxWidth + left) * 4; + pixels.fill(200, row, row + boxWidth * 4); + } + } + return { width: maxWidth, height, pixels }; + }, + encode: (bitmap) => Buffer.from(`sheet ${bitmap.width}x${bitmap.height}`), + crop: (jpeg, region, maxWidth) => + Buffer.from( + `${jpeg} cropped to ${region.x},${region.y} ${region.width}x${region.height} within ${maxWidth}`, + ), + }, runTool, now: () => 1_000, }; @@ -215,6 +256,23 @@ async function recordTake(title = "Demo") { }; } +describe("the usage count", () => { + it("is told the name of each tool a client calls, and nothing of the call", async () => { + const { projectId } = await recordTake(); + // A media tool, a document tool, and a call that is refused: all three were calls. + await call("getFrames", { path: "take.mp4", atSec: [1] }); + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + await call("getFrames", {}); + expect(countedCalls).toEqual([ + "startRecording", + "stopRecording", + "getFrames", + "addTrim", + "getFrames", + ]); + }); +}); + describe("what `openscreen mcp` tells its client", () => { it("composes the media block with the checkpoint rule, and nothing true only in the app", () => { const instructions = client.getInstructions() ?? ""; @@ -889,6 +947,96 @@ describe("exportAudio", () => { }); }); +describe("exportCaptions", () => { + /** The take with two spoken lines in its transcript. */ + async function spokenTake() { + const { projectId } = await recordTake(); + const project = await documents.getProject(projectId); + const assetId = project.project.primaryAssetId as string; + const word = ( + id: string, + segmentId: string, + startSec: number, + endSec: number, + text: string, + ) => ({ + id, + segmentId, + startSec, + endSec, + text, + }); + await documents.saveProject({ + ...project, + transcripts: [ + { + assetId, + language: "en", + segments: [ + { + id: "s1", + kind: "speech", + startSec: 1, + endSec: 2, + text: "hello there", + wordIds: ["w1", "w2"], + }, + { id: "s2", kind: "speech", startSec: 4, endSec: 5, text: "goodbye", wordIds: ["w3"] }, + ], + words: [ + word("w1", "s1", 1, 1.5, "hello"), + word("w2", "s1", 1.5, 2, "there"), + word("w3", "s2", 4, 5, "goodbye"), + ], + }, + ], + }); + return projectId; + } + + it("writes the captions to the subtitle file the extension names", async () => { + const projectId = await spokenTake(); + const srt = path.join(dir, "demo.srt"); + const written = await call("exportCaptions", { projectId, path: srt }); + expect(written.isError).toBeFalsy(); + expect(JSON.parse(textOf(written))).toEqual({ + path: srt, + format: "srt", + language: null, + entries: 2, + }); + expect(await fs.readFile(srt, "utf8")).toBe( + "1\n00:00:01,000 --> 00:00:02,000\nhello there\n\n2\n00:00:04,000 --> 00:00:05,000\ngoodbye\n", + ); + const vtt = path.join(dir, "demo.vtt"); + await call("exportCaptions", { projectId, path: vtt }); + expect((await fs.readFile(vtt, "utf8")).startsWith("WEBVTT\n\n00:00:01.000")).toBe(true); + // Nothing is rendered for it. + expect(runners.started.filter((request) => request.kind === "export")).toHaveLength(0); + }); + + it("refuses a project with no words, a layer it lacks, another extension or an unknown project", async () => { + const { projectId } = await recordTake(); + const empty = await call("exportCaptions", { projectId, path: path.join(dir, "none.srt") }); + expect(empty.isError).toBe(true); + expect(textOf(empty)).toContain("transcribe"); + await expect(fs.access(path.join(dir, "none.srt"))).rejects.toThrow(); + + const spoken = await spokenTake(); + const layer = await call("exportCaptions", { + projectId: spoken, + path: path.join(dir, "fr.srt"), + language: "fr", + }); + expect(textOf(layer)).toContain('no "fr" caption translation'); + expect((await call("exportCaptions", { projectId: spoken, path: "out.txt" })).isError).toBe( + true, + ); + const unknown = await call("exportCaptions", { projectId: "proj_x", path: "out.srt" }); + expect(textOf(unknown)).toContain('No project has the id "proj_x"'); + }); +}); + describe("getFrames on a project", () => { it("reads the last export at the ruler seconds the document tools use", async () => { const { projectId } = await recordTake(); @@ -1061,6 +1209,551 @@ describe("getFrames", () => { }); }); +/** What a frame result says of each frame, without its opening line. */ +const captionsOf = (result: CallToolResult) => + result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).slice(1); + +/** The picture of a result, as the stand-in codec wrote it. */ +const pictureOf = (result: CallToolResult) => { + const image = result.content.find((part) => part.type === "image"); + return image?.type === "image" ? Buffer.from(image.data, "base64").toString() : null; +}; + +describe("frameTimes over a span", () => { + it("runs from one end of the span to the other, both shown", () => { + expect(frameTimes(12, null, 3, { startSec: 2, endSec: 4 })).toEqual([2, 3, 4]); + expect(frameTimes(12, null, 1, { startSec: 2, endSec: 4 })).toEqual([3]); + expect(frameTimes(12, null, 2, { endSec: 6 })).toEqual([0, 6]); + // An open end is the video's own, one frame short of it. + const toTheEnd = frameTimes(12, null, 2, { startSec: 10 }); + expect(toTheEnd[0]).toBe(10); + expect(toTheEnd[1]).toBeGreaterThan(11.9); + expect(toTheEnd[1]).toBeLessThan(12); + // A span past the end shows the last frame, never a time the video does not have. + const past = frameTimes(12, null, 2, { startSec: 20, endSec: 30 }); + expect(past).toHaveLength(2); + for (const t of past) expect(t).toBeCloseTo(12 - 1 / 60, 6); + }); +}); + +describe("getFrames over a span and on a region", () => { + it("spreads the frames from startSec to endSec", async () => { + const result = await call("getFrames", { + path: "take.mp4", + startSec: 2, + endSec: 4, + count: 3, + }); + expect(captionsOf(result)).toEqual(["2.00s", "3.00s", "4.00s"]); + expect(capturedWidths).toEqual([1280, 1280, 1280]); + }); + + it("takes times or a span, not both, and a span that runs forward", async () => { + const both = await call("getFrames", { path: "take.mp4", atSec: [1], startSec: 0 }); + expect(both.isError).toBe(true); + expect(textOf(both)).toContain("not both"); + const backwards = await call("getFrames", { path: "take.mp4", startSec: 4, endSec: 2 }); + expect(backwards.isError).toBe(true); + expect(textOf(backwards)).toContain("endSec must be after startSec"); + }); + + it("crops each frame to the region, out of the video at its own size", async () => { + const result = await call("getFrames", { + path: "take.mp4", + atSec: [1], + region: { x: 0.5, y: 0, width: 0.5, height: 0.5 }, + }); + expect(pictureOf(result)).toBe("frame@1 cropped to 0.5,0 0.5x0.5 within 1280"); + // Asked wider than any video, so the crop is cut from every pixel the frame has. + expect(capturedWidths).toEqual([16_384]); + }); + + it("renders a project's frames at full size before it crops them", async () => { + const { projectId } = await recordTake(); + const widths: number[] = []; + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => { + widths.push(maxWidth); + return frames.map((index) => ({ + index, + width: 1920, + height: 1080, + jpeg: Buffer.from(`render@${index}`), + })); + }; + const result = await call("getFrames", { + projectId, + atSec: [1], + region: { x: 0, y: 0, width: 0.25, height: 0.25 }, + }); + expect(pictureOf(result)).toBe("render@60 cropped to 0,0 0.25x0.25 within 1280"); + expect(widths).toEqual([16_384]); + }); +}); + +describe("getContactSheet", () => { + it("makes the rows as tall as the tallest frame, so none is cut", async () => { + const { projectId } = await recordTake(); + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => + frames.map((index, i) => ({ + index, + width: maxWidth, + height: 359, + jpeg: Buffer.from(i === 1 ? `render@${index} tall` : `render@${index}`), + })); + const result = await call("getContactSheet", { projectId, atSec: [1, 2], columns: 2 }); + // The second frame decodes 639 px square, taller than the first: the row takes its height. + expect(pictureOf(result)).toBe(`sheet ${2 * 639 + 2}x639`); + }); + + it("lays a video's frames out on one image, and says the times in reading order", async () => { + const result = await call("getContactSheet", { + path: "take.mp4", + startSec: 0, + endSec: 10, + count: 6, + columns: 3, + }); + expect(result.isError).toBeFalsy(); + expect(result.content).toHaveLength(2); + expect(textOf(result)).toContain( + "3 across, in reading order: 0.00s, 2.00s, 4.00s, 6.00s, 8.00s, 10.00s.", + ); + // Three tiles of 425 px and two gaps wide; two rows of 239 px and one gap high. + expect(pictureOf(result)).toBe("sheet 1279x480"); + // Each frame is asked for at the width of its tile, never larger. + expect(capturedWidths).toEqual(Array(6).fill(425)); + expect(closed).toBe(1); + }); + + it("shows twelve moments of the whole film, four across, rendered from a project with no export", async () => { + const { projectId } = await recordTake(); + const asked: Array<{ frames: number; maxWidth: number }> = []; + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => { + asked.push({ frames: frames.length, maxWidth }); + return frames.map((index) => ({ + index, + width: maxWidth, + height: 179, + jpeg: Buffer.from(`render@${index}`), + })); + }; + const result = await call("getContactSheet", { projectId }); + expect(asked).toEqual([{ frames: 12, maxWidth: 318 }]); + expect(textOf(result)).toContain("rendered from the project"); + expect(textOf(result)).toContain("4 across"); + // Three rows of four tiles, 318 by 179. + expect(pictureOf(result)).toBe(`sheet ${4 * 318 + 3 * 2}x${3 * 179 + 2 * 2}`); + }); + + it("keeps the place and the time of a frame the video does not have", async () => { + const { projectId } = await recordTake(); + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => + frames.slice(0, 1).map((index) => ({ + index, + width: maxWidth, + height: 360, + jpeg: Buffer.from("the only frame"), + })); + const partial = await call("getContactSheet", { projectId, atSec: [1, 2], columns: 2 }); + expect(textOf(partial)).toContain("in reading order: 1.00s, 2.00s."); + expect(pictureOf(partial)).toBe(`sheet ${2 * 639 + 2}x359`); + + renderFrames = async () => []; + const none = await call("getContactSheet", { projectId, atSec: [1] }); + expect(none.isError).toBe(true); + expect(textOf(none)).toContain("No frame to show"); + }); + + it("cuts the region out of the full-size frame before it makes a tile of it", async () => { + const result = await call("getContactSheet", { + path: "take.mp4", + atSec: [1], + columns: 2, + region: { x: 0, y: 0, width: 0.5, height: 0.5 }, + }); + expect(result.isError).toBeFalsy(); + expect(capturedWidths).toEqual([16_384]); + }); + + it("labels a file's frame with the time it was taken at, not a time past the end", async () => { + const result = await call("getContactSheet", { path: "take.mp4", atSec: [20], columns: 2 }); + expect(textOf(result)).toContain("in reading order: 11.98s."); + }); + + it("puts more frames across as there are more of them, unless told how many", async () => { + const many = await call("getContactSheet", { path: "take.mp4", count: 30 }); + expect(textOf(many)).toContain("6 across"); + const some = await call("getContactSheet", { path: "take.mp4", count: 20 }); + expect(textOf(some)).toContain("5 across"); + const asked = await call("getContactSheet", { path: "take.mp4", count: 30, columns: 3 }); + expect(textOf(asked)).toContain("3 across"); + }); + + it("takes a project or a file like getFrames, and refuses the same mistakes", async () => { + expect((await call("getContactSheet", {})).isError).toBe(true); + const both = await call("getContactSheet", { path: "take.mp4", atSec: [1], endSec: 3 }); + expect(textOf(both)).toContain("not both"); + }); +}); + +describe("getBeforeAfter", () => { + const momentsOf = (result: CallToolResult) => { + const report = result.content[1]; + return report?.type === "text" ? JSON.parse(report.text).moments : null; + }; + /** What each render was asked for: how many clips, which frames, how wide. */ + let asked: Array<{ clips: number; frames: number[]; maxWidth: number }>; + // The project's frames hold a box once it is cut in two: somewhere known to differ. + beforeEach(() => { + asked = []; + renderFrames = async (clips, _scene, _fps, frames, maxWidth) => { + asked.push({ clips: clips.length, frames, maxWidth }); + return frames.map((index) => ({ + index, + width: maxWidth, + height: 359, + jpeg: Buffer.from( + clips.length > 1 ? `render@${index} box 64,36 128x72` : `render@${index}`, + ), + })); + }; + }); + + it("pairs each moment at the checkpoint with the same moment now, and says where they differ", async () => { + const { projectId, checkpointId } = await recordTake(); + const untouched = await call("getBeforeAfter", { projectId, checkpointId, atSec: [1, 6] }); + expect(momentsOf(untouched)).toEqual([ + { sec: 1, changed: false }, + { sec: 6, changed: false }, + ]); + + // A cut of 2 s: ruler 6 s was frame 360 of the export, and is now frame 240. + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + const edited = await documents.getProject(projectId); + asked = []; + const result = await call("getBeforeAfter", { projectId, checkpointId, atSec: [1, 6] }); + expect(result.isError).toBeFalsy(); + expect(textOf(result)).toContain("left, at the checkpoint; right, as it is now"); + // The checkpoint first, then the project as it is, each at the width of its tile. + expect(asked).toEqual([ + { clips: 1, frames: [60, 360], maxWidth: 639 }, + { clips: 2, frames: [60, 240], maxWidth: 639 }, + ]); + // Two rows of two tiles, 639 by 359, and the gaps between them. + expect(pictureOf(result)).toBe(`sheet ${2 * 639 + 2}x${2 * 359 + 2}`); + const box = { x: 0.1002, y: 0.1003, width: 0.2003, height: 0.2006 }; + expect(momentsOf(result)).toEqual([ + { sec: 1, changed: true, changedShare: 0.0402, region: box }, + { sec: 6, changed: true, changedShare: 0.0402, region: box }, + ]); + // Looking changed nothing: the edit is still there, and so is the checkpoint. + expect(await documents.getProject(projectId)).toEqual(edited); + const restored = await call("restoreCheckpoint", { projectId, checkpointId }); + expect(restored.isError).toBeFalsy(); + }); + + it("compares one part of the frame at full size, and places the change in the whole frame", async () => { + const { projectId, checkpointId } = await recordTake(); + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + asked = []; + const result = await call("getBeforeAfter", { + projectId, + checkpointId, + atSec: [1], + region: { x: 0.5, y: 0, width: 0.5, height: 1 }, + }); + expect(asked.map((render) => render.maxWidth)).toEqual([16_384, 16_384]); + // The box sits at a tenth of the right half: just past the middle of the frame. + expect(momentsOf(result)).toEqual([ + { + sec: 1, + changed: true, + changedShare: 0.0402, + region: { x: 0.5501, y: 0.1003, width: 0.1002, height: 0.2006 }, + }, + ]); + }); + + it("says a side that has no frame changed, without pointing anywhere", async () => { + const { projectId, checkpointId } = await recordTake(); + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + // The checkpoint renders nothing; the project as it is, its frame. + renderFrames = async (clips, _scene, _fps, frames, maxWidth) => + clips.length > 1 + ? frames.map((index) => ({ index, width: maxWidth, height: 359, jpeg: Buffer.from("now") })) + : []; + const result = await call("getBeforeAfter", { projectId, checkpointId, atSec: [1] }); + expect(momentsOf(result)).toEqual([{ sec: 1, changed: true, missing: "checkpoint" }]); + expect(pictureOf(result)).toBe(`sheet ${2 * 639 + 2}x359`); + }); + + it("keeps each moment where it was asked, and says which side's film ends before it", async () => { + const { projectId, checkpointId } = await recordTake(); + // The take is 12 s; the project now plays its first 8 s only. + const [clip] = (await documents.getProject(projectId)).timeline.clips; + await call("setClipRange", { projectId, clipId: clip.id, sourceStartSec: 0, sourceEndSec: 8 }); + asked = []; + const result = await call("getBeforeAfter", { projectId, checkpointId, atSec: [2, 10] }); + // The checkpoint shows 10 s; the project, which ends at 8, is not asked for it at all. + expect(asked).toEqual([ + { clips: 1, frames: [120, 600], maxWidth: 639 }, + { clips: 1, frames: [120], maxWidth: 639 }, + ]); + expect(momentsOf(result)).toEqual([ + { sec: 2, changed: false }, + { sec: 10, changed: true, missing: "now" }, + ]); + // Spread over the longer film when no time is asked: 0 to 12 s, not 0 to 8. + asked = []; + await call("getBeforeAfter", { projectId, checkpointId, count: 2, startSec: 0 }); + expect(asked[0].frames.at(-1)).toBeGreaterThan(700); + }); + + it("keeps a moment just before the end as asked through a slowed end, and has none at the end", async () => { + const { projectId, checkpointId } = await recordTake(); + // The take's last second now plays at half speed: the film ends at 13 s of output. + await call("addSpeed", { projectId, startSec: 11, endSec: 12, speed: 0.5 }); + asked = []; + const result = await call("getBeforeAfter", { projectId, checkpointId, atSec: [11.995, 12] }); + // 11.995 s is output frame 719 at the checkpoint, and 779 now: the last of 13 s, not + // the one a clamp to a 60th of a ruler second before the end would give. 12 s is the end. + expect(asked).toEqual([ + { clips: 1, frames: [719], maxWidth: 639 }, + { clips: 1, frames: [779], maxWidth: 639 }, + ]); + expect(momentsOf(result)).toEqual([ + { sec: 11.99, changed: false }, + { sec: 12, changed: false, missing: "both" }, + ]); + }); + + it("shows a checkpoint taken before the first clip as missing, and still renders the project", async () => { + const empty = await documents.createProject("Empty"); + const projectId = empty.project.id; + const checkpoint = await call("createCheckpoint", { projectId }); + const { checkpointId } = JSON.parse(textOf(checkpoint)); + // The take's clip laid into the project the checkpoint saw empty. + const take = await documents.getProject((await recordTake()).projectId); + await documents.saveProject({ ...take, project: { ...take.project, id: projectId } }); + asked = []; + const result = await call("getBeforeAfter", { projectId, checkpointId, atSec: [1] }); + expect(result.isError).toBeFalsy(); + expect(asked).toHaveLength(1); + expect(momentsOf(result)).toEqual([{ sec: 1, changed: true, missing: "checkpoint" }]); + }); + + it("places a change found on a region cut at the frame's edge inside the frame", async () => { + const { projectId, checkpointId } = await recordTake(); + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + // A region that runs past the right edge: only the frame's last tenth is compared. + const result = await call("getBeforeAfter", { + projectId, + checkpointId, + atSec: [1], + region: { x: 0.9, y: 0, width: 0.5, height: 1 }, + }); + const [moment] = momentsOf(result); + expect(moment.changed).toBe(true); + expect(moment.region.x).toBeGreaterThanOrEqual(0.9); + expect(moment.region.x + moment.region.width).toBeLessThanOrEqual(1.0001); + }); + + it("refuses what it cannot compare, and says why", async () => { + const take = await recordTake(); + const unknown = await call("getBeforeAfter", { + projectId: take.projectId, + checkpointId: "cp_nope", + }); + expect(unknown.isError).toBe(true); + expect(textOf(unknown)).toContain("Unknown checkpointId"); + + const other = await documents.createProject("Other"); + const foreign = await call("getBeforeAfter", { + projectId: other.project.id, + checkpointId: take.checkpointId, + }); + expect(foreign.isError).toBe(true); + expect(textOf(foreign)).toContain("belongs to another project"); + + const nowhere = await call("getBeforeAfter", { projectId: "proj_nope", checkpointId: "cp" }); + expect(textOf(nowhere)).toContain('No project has the id "proj_nope"'); + + const { projectId, checkpointId } = take; + const both = await call("getBeforeAfter", { projectId, checkpointId, atSec: [1], startSec: 0 }); + expect(textOf(both)).toContain("not both"); + + renderFrames = async () => null; + const noAddon = await call("getBeforeAfter", { projectId, checkpointId, atSec: [1] }); + expect(noAddon.isError).toBe(true); + expect(textOf(noAddon)).toContain("cannot render"); + }); +}); + +/** A 16-bit stereo WAV: each part is a 1 kHz tone at `db` dBFS, or silence when `db` is null. */ +function wavOf(parts: Array<[db: number | null, seconds: number]>): Buffer { + const sampleRate = 48_000; + const frames = parts.reduce((total, [, seconds]) => total + Math.round(seconds * sampleRate), 0); + const file = Buffer.alloc(44 + frames * 4); + file.write("RIFF", 0, "latin1"); + file.writeUInt32LE(36 + frames * 4, 4); + file.write("WAVEfmt ", 8, "latin1"); + file.writeUInt32LE(16, 16); + file.writeUInt16LE(1, 20); + file.writeUInt16LE(2, 22); + file.writeUInt32LE(sampleRate, 24); + file.writeUInt32LE(sampleRate * 4, 28); + file.writeUInt16LE(4, 32); + file.writeUInt16LE(16, 34); + file.write("data", 36, "latin1"); + file.writeUInt32LE(frames * 4, 40); + let at = 44; + let n = 0; + for (const [db, seconds] of parts) { + const amplitude = db === null ? 0 : 10 ** (db / 20); + for (let i = 0; i < Math.round(seconds * sampleRate); i++, n++) { + const value = Math.round( + amplitude * Math.sin((2 * Math.PI * 1_000 * n) / sampleRate) * 32767, + ); + file.writeInt16LE(value, at); + file.writeInt16LE(value, at + 2); + at += 4; + } + } + return file; +} + +describe("getAudioReport", () => { + const reportOf = async (args: Record) => + JSON.parse(textOf(await call("getAudioReport", args))) as { + durationSec: number; + integratedLufs: number | null; + truePeakDbtp: number | null; + silences: Array<{ startSec: number; endSec: number }>; + }; + + it("measures the project's sound, and places its silences on the ruler", async () => { + const { projectId } = await recordTake(); + // A cut of 2 s early in the take: what the export plays at 5 s is ruler second 7. + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + runners.wav = wavOf([ + [-20, 5], + [null, 1], + [-20, 4], + ]); + const report = await reportOf({ projectId }); + expect(report.durationSec).toBe(10); + expect(report.integratedLufs).toBeCloseTo(-20, 0); + expect(report.truePeakDbtp).toBeCloseTo(-20, 0); + expect(report.silences).toEqual([{ startSec: 7, endSec: 8 }]); + + const request = runners.started.at(-1); + expect(request).toMatchObject({ kind: "export", format: "wav", audioTrackId: null }); + // Rendered to a file of its own, gone once it is measured. + const rendered = (request?.kind === "export" && request.outPath) || ""; + expect(path.dirname(rendered)).toBe(os.tmpdir()); + await expect(fs.access(rendered)).rejects.toThrow(); + expect(media.isBusy()).toBe(false); + }); + + it("keeps a silence that touches a cut clear of the cut, and follows a speed region", async () => { + const { projectId } = await recordTake(); + // Ruler 2 to 4 is cut, and ruler 6 to 10 plays twice as fast: the export lasts 8 s. + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + expect( + (await call("addSpeed", { projectId, startSec: 6, endSec: 10, speed: 2 })).isError, + ).toBeFalsy(); + // Quiet for the second right after the cut, then again from 5 s to 5.5 s of the export. + runners.wav = wavOf([ + [-20, 2], + [null, 1], + [-20, 2], + [null, 0.5], + [-20, 2.5], + ]); + const { silences } = await reportOf({ projectId }); + expect(silences).toEqual([ + // It starts after the cut, never inside it. + { startSec: 4, endSec: 5 }, + // One export second past ruler 6 is two ruler seconds. + { startSec: 8, endSec: 9 }, + ]); + }); + + it("leaves a cut inside a silence out of it: the export never played the cut", async () => { + const { projectId } = await recordTake(); + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + // Quiet from 1 s to 3 s of the export: ruler 1 to 2, then ruler 4 to 5, the cut between. + runners.wav = wavOf([ + [-20, 1], + [null, 2], + [-20, 5], + ]); + const { silences } = await reportOf({ projectId }); + expect(silences).toEqual([ + { startSec: 1, endSec: 2 }, + { startSec: 4, endSec: 5 }, + ]); + }); + + it("measures one imported track alone", async () => { + const { projectId } = await recordTake(); + runners.wav = wavOf([[-30, 2]]); + const report = await reportOf({ projectId, audioId: "music" }); + expect(report.integratedLufs).toBeCloseTo(-30, 0); + expect(runners.started.at(-1)).toMatchObject({ audioTrackId: "music" }); + }); + + it("says a silent film is silent, rather than give it a loudness", async () => { + const { projectId } = await recordTake(); + runners.wav = wavOf([[null, 2]]); + const report = await reportOf({ projectId }); + expect(report).toMatchObject({ integratedLufs: null, truePeakDbtp: null }); + expect(report.silences).toEqual([{ startSec: 0, endSec: 2 }]); + }); + + it("says why it has nothing to give: no such project, a failed render, a file it cannot read", async () => { + expect(textOf(await call("getAudioReport", { projectId: "nope" }))).toContain( + 'No project has the id "nope"', + ); + const { projectId } = await recordTake(); + runners.results.export = { success: false, error: "no audio track" }; + const failed = await call("getAudioReport", { projectId }); + expect(failed.isError).toBe(true); + expect(textOf(failed)).toContain("could not be rendered: no audio track"); + + runners.results.export = { success: true }; + runners.wav = Buffer.from("not a wav"); + const unreadable = await call("getAudioReport", { projectId }); + expect(unreadable.isError).toBe(true); + expect(textOf(unreadable)).toContain("could not be measured: Not a WAV file"); + expect(media.isBusy()).toBe(false); + }); + + it("gives no silences when the project was saved while its sound was measured", async () => { + const { projectId } = await recordTake(); + runners.wav = wavOf([[-20, 2]]); + const held = runners.holdExports(); + const measuring = call("getAudioReport", { projectId }); + await held; + // The runner may have rendered either version: the ruler seconds would be a guess. + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + runners.releaseExport(); + const answer = await measuring; + expect(answer.isError).toBe(true); + expect(textOf(answer)).toContain("changed while its sound was measured"); + expect(media.isBusy()).toBe(false); + }); + + it("waits for a take to end", async () => { + const { projectId } = await recordTake(); + await call("startRecording", { window: "My App" }); + const during = await call("getAudioReport", { projectId }); + expect(during.isError).toBe(true); + expect(textOf(during)).toContain("A recording is running"); + await call("stopRecording", { title: "Second" }); + }); +}); + describe("the media tools in the app", () => { let allowed: boolean; let asked: Parameters[0][]; @@ -1159,7 +1852,7 @@ describe("the media tools in the app", () => { allowed = false; const app = await connectApp(); expect(app.getInstructions()).toContain( - "startRecording, exportVideo, exportAudio and createProject are refused too while 'MCP edits'", + "startRecording, exportVideo, exportAudio, exportCaptions and createProject are refused too while 'MCP edits'", ); const started = await callOn(app, "startRecording", {}); expect(started.isError).toBe(true); @@ -1258,6 +1951,31 @@ describe("waitForRecording through MCP", () => { return { observer, subscription }; } + it("renders no sound while the user records from the HUD, and does once the take is saved", async () => { + const { projectId } = await recordTake(); + const completion = new RecordingCompletion(); + completion.started(7, 1_000); + const { observer } = await observing(completion); + const during = (await observer.callTool({ + name: "getAudioReport", + arguments: { projectId }, + })) as CallToolResult; + expect(during.isError).toBe(true); + expect(textOf(during)).toContain("A recording is running"); + expect(runners.started.filter((request) => request.kind === "export")).toEqual([]); + + completion.saved(7, videoPath); + completion.completed(7, { projectId, videoPath, durationSec: 12, autoZooms: 0 }); + runners.wav = wavOf([[-20, 2]]); + const after = (await observer.callTool({ + name: "getAudioReport", + arguments: { projectId }, + })) as CallToolResult; + expect(after.isError).toBeFalsy(); + expect(JSON.parse(textOf(after))).toMatchObject({ durationSec: 2, silences: [] }); + expect(runners.started.filter((request) => request.kind === "export")).toHaveLength(1); + }); + it("returns the stopRecording fields for a user take while MCP edits is off, without recording commands", async () => { const project = await documents.createProject("User take"); const completion = new RecordingCompletion(); diff --git a/electron/mcp/media-tools.ts b/electron/mcp/media-tools.ts index 85ee0f6c29..722698300f 100644 --- a/electron/mcp/media-tools.ts +++ b/electron/mcp/media-tools.ts @@ -12,6 +12,9 @@ // No `electron` import: the runners, the recorder, the decoder and the documents are // handed in, so the tools run under plain vitest with stand-ins. +import { randomUUID } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; import path from "node:path"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; @@ -22,15 +25,23 @@ import type { } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; import type { CursorTelemetryPoint } from "../../src/components/video-editor/types"; +import { getCaptionSettings } from "../../src/lib/ai-edition/captions/settings"; +import { + formatSubtitleFile, + isSubtitleFileFormat, + subtitleCuesForExport, +} from "../../src/lib/ai-edition/captions/subtitleFile"; +import { getCaptionTranslations } from "../../src/lib/ai-edition/captions/translations"; import { projectRawTimelineSecToPlayback, readSpeedRegions, } from "../../src/lib/ai-edition/document/timeline"; -import type { AxcutDocument } from "../../src/lib/ai-edition/schema"; +import { type AxcutDocument, documentSchema } from "../../src/lib/ai-edition/schema"; import { appendAutoZoomSuggestions, collectAutoZoomSuggestionsForDocument, } from "../../src/lib/ai-edition/timeline/apply-auto-zooms"; +import { removedRawSpans, subtractRemoved } from "../../src/lib/ai-edition/timeline/programme-time"; import { type CliDoneResult, type CliRecordRequest, @@ -52,12 +63,23 @@ import type { import { buildNativeClipList, buildSceneDescription } from "../../src/native/sceneDescription"; import { runDocumentTool } from "../ai-edition/deep-agent/service"; import type { DocumentService } from "../ai-edition/document-service"; +import { writeFileReplacing } from "../atomic-rename"; import type { RunnerHandlers } from "../cli/runnerHost"; +import { type AudioReport, measureWav } from "./audio-report"; +import { + changedRegion, + composeContactSheet, + type FrameImages, + type FrameRegion, + regionRect, + tileWidthFor, +} from "./contact-sheet"; import type { OpenedVideo } from "./hidden-video"; import { MCP_EDITS_SETTING, type McpToolRunner, type McpTransport, + READ_CHECKPOINT_TOOL, type RunnerEdit, textResult as text, } from "./openscreen-mcp-server"; @@ -138,6 +160,9 @@ export interface MediaToolDeps { frames: number[], maxWidth: number, ): Promise | null>; + /** Crops frames and lays them out as a contact sheet (frame-images.ts). Absent, a region + * and a sheet are refused. */ + images?: FrameImages; /** The pointer samples recorded with a video; empty when there are none. */ readCursor(videoPath: string): Promise; /** The document tools' runner: a fresh project's checkpoint and every edit go through it. */ @@ -150,18 +175,154 @@ export const NO_WEBCAM_PICTURE = "The webcam delivered no picture, so the take has no camera. Call listSources and pass startRecording part of the name of a camera that works."; export const MAX_FRAMES = 12; +/** The most a contact sheet holds: six rows of six. */ +export const MAX_SHEET_FRAMES = 36; +/** The most moments getBeforeAfter pairs up: six rows of two make a sheet a client still reads. */ +export const MAX_PAIRS = 6; // Wide enough to read UI text, small enough that a dozen frames stay cheap. const FRAME_WIDTH = 1280; +/** Wider than any render or video: a frame asked for at this width comes at its own size. */ +const FULL_WIDTH = 16_384; /** exportVideo's frame rate when none is asked: the grid getFrames renders on without an export. */ const EXPORT_FPS = 60; // A seek to the exact end shows no frame in Chromium; stop one frame short of it. const END_MARGIN_SEC = 1 / 60; -/** The times to grab: `atSec` clamped inside the video, else `count` centred in equal slices. */ -export function frameTimes(durationSec: number, atSec: number[] | null, count: number): number[] { +/** The stretch of a video a client asks to see frames of; an open end is the video's own. */ +interface FrameSpan { + startSec?: number; + endSec?: number; +} + +/** + * The times to grab: `atSec` clamped inside the video, else `count` of them. Over a `span` + * they run from one of its ends to the other, both shown: a transition is read from its first + * frame to its last. Over the whole video they sit centred in equal slices, clear of a black + * first frame. + */ +export function frameTimes( + durationSec: number, + atSec: number[] | null, + count: number, + span: FrameSpan = {}, +): number[] { const last = Math.max(0, durationSec - END_MARGIN_SEC); if (atSec) return atSec.map((t) => Math.min(t, last)); - return Array.from({ length: count }, (_, i) => Math.min(((i + 0.5) * durationSec) / count, last)); + if (span.startSec === undefined && span.endSec === undefined) { + return Array.from({ length: count }, (_, i) => + Math.min(((i + 0.5) * durationSec) / count, last), + ); + } + const from = Math.min(span.startSec ?? 0, last); + const to = Math.max(from, Math.min(span.endSec ?? last, last)); + if (count === 1) return [(from + to) / 2]; + return Array.from({ length: count }, (_, i) => from + ((to - from) * i) / (count - 1)); +} + +/** The moments a client asks to see, of a project or of a video file. */ +interface FrameQuery extends FrameSpan { + projectId?: string; + path?: string; + atSec?: number[]; + count?: number; +} + +/** One moment looked at: what is said before its picture, and the picture when there is one. */ +interface Shot { + caption: string; + /** The moment, in the seconds the client asked in. */ + sec: number; + jpeg: Buffer | null; + /** The picture's size in pixels, when the renderer says it. */ + size?: { width: number; height: number }; +} + +interface Shots { + intro: string; + shots: Shot[]; +} + +/** A frame query answered with its frames, not with why it could not be. A tool result takes + * any key, so the type alone does not tell the two apart. */ +function isShots(found: Shots | CallToolResult): found is Shots { + return Array.isArray(found.shots); +} + +/** Why a frame query cannot be answered as asked, or `null`. */ +function frameQueryProblem(query: FrameQuery): string | null { + if ((query.projectId === undefined) === (query.path === undefined)) { + return "Pass either projectId or path."; + } + if (query.atSec && (query.startSec !== undefined || query.endSec !== undefined)) { + return "Pass atSec, or startSec and endSec with count, not both."; + } + if ( + query.startSec !== undefined && + query.endSec !== undefined && + query.endSec <= query.startSec + ) { + return "endSec must be after startSec."; + } + return null; +} + +const round = (value: number, digits: number) => Number(value.toFixed(digits)); + +const NO_FRAME_HERE = "No frame here: the rendered video ends before it."; +const NO_IMAGE_WORK = "This OpenScreen cannot crop frames or lay them out on a sheet."; + +const REGION_SCHEMA: z.ZodType = z + .object({ + x: z.number().min(0).max(1), + y: z.number().min(0).max(1), + width: z.number().gt(0).max(1), + height: z.number().gt(0).max(1), + }) + .describe( + "Only this part of each frame, as fractions of the frame from its top-left corner: x 0.5, y 0, width 0.5, height 0.5 is the top-right quarter.", + ); + +/** What getFrames and getContactSheet both take, to say which moments of what. */ +function frameQueryShape(transport: McpTransport, maxFrames: number, defaultCount: number) { + return { + projectId: z + .string() + .optional() + .describe("Look at this project: its last export, or the frames an export would show."), + path: z + .string() + .optional() + .describe( + transport === "http" + ? "Or look at this video file, by its absolute path." + : "Or look at this video file.", + ), + atSec: z + .array(z.number().nonnegative()) + .max(maxFrames) + .optional() + .describe("Times in seconds: ruler seconds with projectId, the file's own with path."), + count: z + .number() + .int() + .min(1) + .max(maxFrames) + .optional() + .describe( + `How many frames, when atSec is not given. Default ${defaultCount}. Spread evenly over the whole video, or from startSec to endSec when either is given.`, + ), + startSec: z + .number() + .nonnegative() + .optional() + .describe("With count: the first frame's time. Default: the start of the video."), + endSec: z + .number() + .nonnegative() + .optional() + .describe("With count: the last frame's time. Default: the end of the video."), + region: REGION_SCHEMA.optional(), + }; } export interface PointerEvent { @@ -248,8 +409,8 @@ const TAKE_NOTES: Record = { export function mediaPreamble(transport: McpTransport): string { return [ "OpenScreen records the screen, turns each take into a project you edit with the document tools, and exports it as a video.", - "A demo goes: listSources, then startRecording, then drive the app, then stopRecording. To observe a take the user controls on the in-app HTTP server, call waitForRecording while it is recording or saving; the user stops it. It returns the projectId and a checkpointId. Edit with the document tools, always passing that projectId: every edit is saved to the project straight away, and restoreCheckpoint with the checkpointId takes the project back to the raw take in one step. Then exportVideo, and getFrames with the projectId to check the export before you hand it over: it takes the same ruler seconds as the document tools, so a trim or a speed region never shifts what you look at.", - "To edit a video you already have instead, createProject with its videoPath; importMedia adds a video or an audio file to a project.", + "A demo goes: listSources, then startRecording, then drive the app, then stopRecording. To observe a take the user controls on the in-app HTTP server, call waitForRecording while it is recording or saving; the user stops it. It returns the projectId and a checkpointId. Edit with the document tools, always passing that projectId: every edit is saved to the project straight away, and restoreCheckpoint with the checkpointId takes the project back to the raw take in one step. Then exportVideo, and getFrames with the projectId to check the export before you hand it over: it takes the same ruler seconds as the document tools, so a trim or a speed region never shifts what you look at. getContactSheet shows many moments as one image, to read the rhythm of the whole film or a transition frame by frame, getBeforeAfter shows what your edits changed since a checkpoint, and getAudioReport measures the sound, which no frame shows.", + "To edit a video you already have instead, createProject with its videoPath; importMedia adds a video, an audio file or an image to a project, an image as a silent clip of it.", "Drive the app with the real mouse when you can: OpenScreen records the pointer, draws a clean cursor and zooms on the clicks as the editor does: clicks close in time and on screen share one zoom, and the first seconds and the end stay on the whole screen. If you drive it from a script instead (Playwright, CDP), the screen pointer never moves: log each action as the script runs it, then hand the log to setPointerTrack after stopRecording. A video your script captured itself takes one too: createProject with it, then setPointerTrack with recordingStartedAt.", TAKE_NOTES[transport], ].join("\n"); @@ -293,6 +454,12 @@ const AUDIO_PATH_DESCRIPTIONS: Record = { "Where to write the audio: an absolute path, or one relative to this server's working directory, ending in .wav or .m4a.", }; +const CAPTIONS_PATH_DESCRIPTIONS: Record = { + http: "Where to write the subtitles: an absolute path ending in .srt or .vtt. This server runs inside the app, so it has no working directory of yours to resolve a relative one against.", + stdio: + "Where to write the subtitles: an absolute path, or one relative to this server's working directory, ending in .srt or .vtt.", +}; + const GATED_MESSAGE = `Nothing was recorded or exported: OpenScreen lets MCP clients record and export only while the user allows it. Ask the user to turn on ${MCP_EDITS_SETTING}.`; /** A path a client passed, resolved; `null` for a relative one the in-app server cannot place. */ @@ -562,6 +729,9 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { const recorder = deps.recorder ?? runnerRecorder(deps); /** The take being recorded, then saved: held until it is a project. */ let take: TakeSlot | null = null; + /** A take runs: this server's own, or one the user started from the HUD, which the in-app + * host reports. An export or a measure would take frames from it either way. */ + const recording = () => take !== null || deps.recordingActive?.() === true; // A take and an export never run together: each is a heavy job of its own, and a // take's capture must not lose frames to an export. let exporting = false; @@ -575,12 +745,13 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { /** getFrames when no export shows the project as it is (`docs/shader-effects.md`, E.4): its * frames composed as its export would compose them, on the export's default frame grid, * without encoding a video. `null` when the addon cannot render them: the export decides. */ - async function renderProjectFrames( + async function renderProjectShots( document: AxcutDocument, - atSec: number[] | null, + query: FrameQuery, count: number, + maxWidth: number, why: string, - ): Promise { + ): Promise { if (!deps.renderFrames) return null; // The frame grid below counts every clip, the render only those with media: past a clip // without one, the two would disagree on which frame a moment is. @@ -591,39 +762,150 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { const clips = buildNativeClipList(document); if (clips.length === 0) return text("This project's timeline has no clip to show.", true); const rulerEndSec = Math.max(0, ...document.timeline.clips.map((clip) => clip.timelineEndSec)); - const times = frameTimes(rulerEndSec, atSec, count); + // Asked times are kept as asked up to the end: the clamp to the last frame is made on the + // output's frames below, where a slowed end does not stretch it. + const times = query.atSec + ? query.atSec.map((sec) => Math.min(sec, rulerEndSec)) + : frameTimes(rulerEndSec, null, count, query); + const lastIndex = Math.max( + 0, + Math.ceil(programmeSecOf(document, rulerEndSec) * EXPORT_FPS - 1e-6) - 1, + ); // The output frame showing at that moment: the last one that starts at or before it. const indices = times.map((sec) => - Math.floor(programmeSecOf(document, sec) * EXPORT_FPS + 1e-6), + Math.min(Math.floor(programmeSecOf(document, sec) * EXPORT_FPS + 1e-6), lastIndex), ); let frames: Awaited>>; try { const scene = JSON.stringify(buildSceneDescription(document)); - frames = await deps.renderFrames(clips, scene, EXPORT_FPS, indices, FRAME_WIDTH); + frames = await deps.renderFrames(clips, scene, EXPORT_FPS, indices, maxWidth); } catch (error) { const message = error instanceof Error ? error.message : String(error); return text(`The frames could not be rendered: ${message}`, true); } if (!frames) return null; const byIndex = new Map(frames.map((frame) => [frame.index, frame])); - const content: CallToolResult["content"] = [ - { - type: "text", - text: `${times.length} frame(s) rendered from the project as its export would show them: ${why}.`, - }, - ]; - times.forEach((sec, i) => { - content.push({ type: "text", text: `${sec.toFixed(2)}s on the ruler` }); - const frame = byIndex.get(indices[i]); - content.push( - frame - ? { type: "image", data: frame.jpeg.toString("base64"), mimeType: "image/jpeg" } - : { type: "text", text: "No frame here: the rendered video ends before it." }, - ); - }); - return { content }; + return { + intro: `${times.length} frame(s) rendered from the project as its export would show them: ${why}.`, + shots: times.map((sec, i) => { + const frame = byIndex.get(indices[i]); + return { + caption: `${sec.toFixed(2)}s on the ruler`, + sec, + jpeg: frame?.jpeg ?? null, + ...(frame ? { size: { width: frame.width, height: frame.height } } : {}), + }; + }), + }; } + /** + * The frames a query asks for, at most `maxWidth` wide: of a project (its current export, + * else rendered from it) or of a video file. An error result when they cannot be had. + */ + async function shotsOf( + query: FrameQuery, + defaultCount: number, + maxWidth: number, + ): Promise { + const problem = frameQueryProblem(query); + if (problem) return text(problem, true); + const count = query.count ?? defaultCount; + let videoPath: string; + /** Ruler seconds → seconds of the exported file, when looking at a project. */ + let toVideoSec = (sec: number) => sec; + let rulerEndSec: number | null = null; + let note = ""; + if (query.projectId !== undefined) { + const exported = lastExports.get(query.projectId); + // A project deleted since still left its export on disk: show it, unflagged. + const current = await deps.documents.getProject(query.projectId).catch(() => null); + const stale = + exported !== undefined && + current !== null && + Date.parse(current.project.updatedAt) > exported.at.getTime(); + // No export shows the project as it is: render its frames as an export would. + if (current && (!exported || stale)) { + const why = exported ? "it changed after its last export" : "it has no export yet"; + const rendered = await renderProjectShots(current, query, count, maxWidth, why); + if (rendered) return rendered; + } + if (!exported) { + return text("This project has no export yet: call exportVideo first.", true); + } + // Mapped through the document the export rendered, so a cut made since cannot shift + // which frame of this video is shown; the current one only says whether it is stale. + const { rendered } = exported; + videoPath = exported.path; + toVideoSec = (sec) => programmeSecOf(rendered, sec); + rulerEndSec = Math.max(0, ...rendered.timeline.clips.map((clip) => clip.timelineEndSec)); + if (stale) { + note = " The project changed after this export: export it again to see the changes."; + } + } else { + const resolved = clientPath(transport, query.path ?? ""); + if (!resolved) return text(`The path must be absolute, got "${query.path}".`, true); + videoPath = resolved; + } + + const video = await deps.openVideo(videoPath); + try { + const asked = + query.atSec ?? (rulerEndSec === null ? null : frameTimes(rulerEndSec, null, count, query)); + const times = asked + ? asked.map((sec) => ({ + asked: sec, + at: frameTimes(video.durationSec, [toVideoSec(sec)], 1)[0], + })) + : frameTimes(video.durationSec, null, count, query).map((at) => ({ asked: at, at })); + const shots: Shot[] = []; + for (const { asked: askedSec, at } of times) { + const frame = await video.capture(at, maxWidth); + shots.push({ + caption: + rulerEndSec === null + ? `${at.toFixed(2)}s` + : `${askedSec.toFixed(2)}s on the ruler, ${at.toFixed(2)}s into the video`, + // A file's frame is labelled with the time it was taken at, which a time past the + // end is not; a project's keeps the ruler second it was asked at. + sec: rulerEndSec === null ? at : askedSec, + jpeg: Buffer.from(frame.data, "base64"), + }); + } + return { + intro: `${times.length} frame(s) of a ${video.width}x${video.height} video lasting ${video.durationSec.toFixed(2)}s.${note}`, + shots, + }; + } finally { + video.close(); + } + } + + /** The request an audio render makes of the export runner: exportAudio's, and the report's. */ + const audioRender = ( + projectId: string, + outPath: string, + format: "wav" | "m4a", + audioId: string | undefined, + ): CliRequest => ({ + kind: "export", + projectPath: deps.documents.filePathFor(projectId), + projectId, + outPath, + format, + quality: null, + // The frame grid exportVideo lays the audio out on by default. + mp4FrameRate: EXPORT_FPS, + gifFrameRate: null, + gifSizePreset: null, + gifLoop: null, + autoZoom: false, + audioPath: null, + audioMode: "mix", + audioOffsetSec: 0, + audioTrackId: audioId ?? null, + }); + /** A fresh project's checkpoint, so a client can edit it at once and take it back in one step. */ async function checkpointOf(projectId: string): Promise { // Never fails the call: the project exists either way, and its id is the answer. @@ -917,7 +1199,7 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { }, async (args, extra) => { if (!deps.editsAllowed()) return text(GATED_MESSAGE, true); - if (take) return text("A recording is running. Stop it before exporting.", true); + if (recording()) return text("A recording is running. Stop it before exporting.", true); if (exporting) return text("An export is already running. Wait for it, then try again.", true); const outPath = clientPath(transport, args.path); @@ -1019,7 +1301,7 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { }, async (args, extra) => { if (!deps.editsAllowed()) return text(GATED_MESSAGE, true); - if (take) return text("A recording is running. Stop it before exporting.", true); + if (recording()) return text("A recording is running. Stop it before exporting.", true); if (exporting) return text("An export is already running. Wait for it, then try again.", true); const outPath = clientPath(transport, args.path); @@ -1034,27 +1316,9 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { return text(`No project has the id "${args.projectId}".`, true); } const result = await finish( - deps.runners.start( - { - kind: "export", - projectPath: deps.documents.filePathFor(args.projectId), - projectId: args.projectId, - outPath, - format, - quality: null, - // The frame grid exportVideo lays the audio out on by default. - mp4FrameRate: EXPORT_FPS, - gifFrameRate: null, - gifSizePreset: null, - gifLoop: null, - autoZoom: false, - audioPath: null, - audioMode: "mix", - audioOffsetSec: 0, - audioTrackId: args.audioId ?? null, - }, - { onProgress: progressNotifier(extra) }, - ), + deps.runners.start(audioRender(args.projectId, outPath, format, args.audioId), { + onProgress: progressNotifier(extra), + }), ); if (!result.success) { return text(`The export failed: ${result.error ?? "unknown error"}`, true); @@ -1067,117 +1331,427 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { ); server.registerTool( - "getFrames", + "exportCaptions", { - description: [ - `Look at a video as still images, at most ${MAX_FRAMES} per call. Ask for the moments you need to check, such as each zoom and each callout.`, - "To check an edit, pass projectId: atSec are the ruler seconds the document tools use, mapped through the trims and speed regions to the moment the export plays them. You get the project's last export, or, when it has none or has changed since, the frames its export would show, rendered from the project without exporting it. With path instead, you get any video file (a take's videoPath, say) and atSec are that file's own seconds.", - ].join("\n"), + description: + "Write a project's captions to a subtitle file, SubRip (.srt) or WebVTT (.vtt), picked by the path's extension. The entries are the lines the burnt-in captions show, with the same words per line, timed in seconds of the exported video: after the trims and the speed regions, so the file plays in sync with exportVideo's MP4. It does not need the captions to be on, and does not turn them on. language picks the words: omitted, the language the captions show (getCaptions' language); null, the transcript's own words; a code, that translation layer (getCaptions lists them under translations). Captions come from the transcript, so a project with none on its caption lane has nothing to write and is refused. Returns the path, the format, the language written and the number of entries. Instant: nothing is rendered.", inputSchema: z.object({ - projectId: z - .string() - .optional() - .describe("Look at this project: its last export, or the frames an export would show."), - path: z + projectId: z.string(), + path: z.string().describe(CAPTIONS_PATH_DESCRIPTIONS[transport]), + language: z .string() + .nullable() .optional() .describe( - transport === "http" - ? "Or look at this video file, by its absolute path." - : "Or look at this video file.", + "A translation layer's code, null for the transcript's own words, omitted for what the captions show.", ), - atSec: z - .array(z.number().nonnegative()) - .max(MAX_FRAMES) + }), + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }, + async (args) => { + if (!deps.editsAllowed()) return text(GATED_MESSAGE, true); + const outPath = clientPath(transport, args.path); + if (!outPath) return text(`The path must be absolute, got "${args.path}".`, true); + const format = path.extname(outPath).toLowerCase().slice(1); + if (!isSubtitleFileFormat(format)) { + return text(`The path must end in .srt or .vtt, got "${args.path}".`, true); + } + const document = await deps.documents.getProject(args.projectId).catch(() => null); + if (!document) return text(`No project has the id "${args.projectId}".`, true); + if (typeof args.language === "string") { + const layers = Object.keys(getCaptionTranslations(document)); + if (!layers.includes(args.language)) { + return text( + `The project has no "${args.language}" caption translation. ${ + layers.length + ? `Its layers are: ${layers.join(", ")}.` + : "It has none: putCaptionTranslation writes one." + } Pass null for the transcript's own words.`, + true, + ); + } + } + const cues = subtitleCuesForExport(document, args.language); + if (cues.length === 0) { + return text( + "Nothing was written: the captions have no words to show. They come from the transcript of what the caption lane plays, so transcribe it first (transcribe), or check getCaptions' captionedAssets.", + true, + ); + } + // Staged under a short name, then renamed over the file: a write that fails halfway + // leaves a subtitle file already there as it was, and a replaced one keeps its mode. + try { + await writeFileReplacing(outPath, Buffer.from(formatSubtitleFile(cues, format), "utf8")); + } catch (error) { + return text( + `The subtitles could not be written to "${outPath}": ${error instanceof Error ? error.message : String(error)}`, + true, + ); + } + const language = + args.language === undefined ? getCaptionSettings(document).language : args.language; + return text(JSON.stringify({ path: outPath, format, language, entries: cues.length })); + }, + ); + + server.registerTool( + "getAudioReport", + { + description: [ + "Measure a project's sound, exactly as exportVideo's MP4 mixes it: you cannot hear a film, so check its mix with these numbers. Returns integratedLufs, the loudness of the whole film (null when it is silent; video platforms play at about -14 LUFS); truePeakDbtp, its highest peak; durationSec, the exported film's length; and silences, every stretch of half a second or more that stays under -60 dBFS, in the ruler seconds the document tools use.", + "With audioId (addAudio's, or an audioTracks entry's trackId, its id when it has no trackId), that imported track alone: a music bed and a voice measured apart say how far one sits under the other. It renders the project as an export does, so it takes about as long as exportVideo. Call it again after an edit that moves time (a trim, a speed region, a track's offset).", + ].join("\n"), + inputSchema: z.object({ + projectId: z.string(), + audioId: z + .string() .optional() - .describe("Times in seconds: ruler seconds with projectId, the file's own with path."), - count: z + .describe("Measure this imported track alone. Default: the whole programme audio."), + }), + annotations: READ_ONLY, + }, + async (args, extra) => { + if (recording()) { + return text("A recording is running. Stop it before measuring the sound.", true); + } + if (exporting) + return text("An export is already running. Wait for it, then try again.", true); + // Rendered beside nothing of the client's: measured, then removed. + const wavPath = path.join(os.tmpdir(), `openscreen-audio-report-${randomUUID()}.wav`); + exporting = true; + try { + const document = await deps.documents.getProject(args.projectId).catch(() => null); + if (!document) return text(`No project has the id "${args.projectId}".`, true); + const result = await finish( + deps.runners.start(audioRender(args.projectId, wavPath, "wav", args.audioId), { + onProgress: progressNotifier(extra), + }), + ); + if (!result.success) { + return text( + `The sound could not be rendered: ${result.error ?? "unknown error"}`, + true, + ); + } + let report: AudioReport; + try { + report = await measureWav(result.outputPath ?? wavPath); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The sound could not be measured: ${message}`, true); + } + // The runner read the project file itself: a save since `document` was read may have + // moved the sound, and the silences would be placed on the wrong ruler seconds. + const after = await deps.documents.getProject(args.projectId).catch(() => null); + if (after?.project.updatedAt !== document.project.updatedAt) { + return text( + "The project changed while its sound was measured. Measure it again.", + true, + ); + } + const removed = removedRawSpans(document.timeline.clips, document.timeline.trimRanges); + return text( + JSON.stringify({ + durationSec: round(report.durationSec, 2), + integratedLufs: + report.integratedLufs === null ? null : round(report.integratedLufs, 1), + truePeakDbtp: report.truePeakDbtp === null ? null : round(report.truePeakDbtp, 1), + silences: report.silences.flatMap(({ startSec, endSec }) => { + const from = rulerSecOf(document, startSec, true); + const to = rulerSecOf(document, endSec, false); + // A cut inside a silence is not silent, it is not played: the silence + // is the pieces on either side of it. + const pieces = subtractRemoved(from, to, removed); + return (pieces.length > 0 ? pieces : [{ startSec: from, endSec: to }]).map( + (piece) => ({ + startSec: round(piece.startSec, 2), + endSec: round(piece.endSec, 2), + }), + ); + }), + }), + ); + } finally { + exporting = false; + await fs.rm(wavPath, { force: true }).catch(() => undefined); + } + }, + ); + + server.registerTool( + "getFrames", + { + description: [ + `Look at a video as still images, at most ${MAX_FRAMES} per call. Ask for the moments you need to check, such as each zoom and each callout.`, + "To check an edit, pass projectId: atSec are the ruler seconds the document tools use, mapped through the trims and speed regions to the moment the export plays them. You get the project's last export, or, when it has none or has changed since, the frames its export would show, rendered from the project without exporting it. With path instead, you get any video file (a take's videoPath, say) and atSec are that file's own seconds.", + "With region, each frame is only that part of the picture, at the video's own resolution, scaled down only when that part is wider than 1280 pixels: the way to read small text, or to check an edge or a corner. To see many moments at once, such as the rhythm of the whole film or a transition frame by frame, use getContactSheet.", + ].join("\n"), + inputSchema: z.object(frameQueryShape(transport, MAX_FRAMES, 6)), + annotations: READ_ONLY, + }, + async (args) => { + const { region } = args; + if (region && !deps.images) return text(NO_IMAGE_WORK, true); + const found = await shotsOf(args, 6, region ? FULL_WIDTH : FRAME_WIDTH); + if (!isShots(found)) return found; + const content: CallToolResult["content"] = [{ type: "text", text: found.intro }]; + try { + for (const shot of found.shots) { + content.push({ type: "text", text: shot.caption }); + if (!shot.jpeg) { + content.push({ type: "text", text: NO_FRAME_HERE }); + continue; + } + const jpeg = + region && deps.images ? deps.images.crop(shot.jpeg, region, FRAME_WIDTH) : shot.jpeg; + content.push({ type: "image", data: jpeg.toString("base64"), mimeType: "image/jpeg" }); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The frames could not be cropped: ${message}`, true); + } + return { content }; + }, + ); + + server.registerTool( + "getContactSheet", + { + description: [ + `Look at many moments of a video as one image, 1280 pixels wide: a grid of up to ${MAX_SHEET_FRAMES} small frames, each with its time printed in its corner, read left to right then top to bottom. A dozen frames, four across, make an image the size of one frame of getFrames.`, + "Over the whole film (the default) it shows the rhythm: where the zooms, the callouts and the cuts fall. Over a short span, startSec to endSec, it shows a zoom's move, an effect or a cut frame by frame: 12 frames over one second, say. The frames are too small to read text: use getFrames, with region if need be, for that.", + "projectId, path and the times mean what they mean for getFrames: ruler seconds with projectId, rendered from the project when it has no current export; the file's own seconds with path.", + ].join("\n"), + inputSchema: z.object({ + ...frameQueryShape(transport, MAX_SHEET_FRAMES, 12), + columns: z .number() .int() - .min(1) - .max(MAX_FRAMES) + .min(2) + .max(6) .optional() - .describe("Frames spread evenly, when atSec is not given. Default 6."), + .describe( + "Frames per row. Fewer make each frame larger and the image taller. Default: 4 for up to 12 frames, 5 for up to 24, 6 beyond.", + ), }), annotations: READ_ONLY, }, async (args) => { - if ((args.projectId === undefined) === (args.path === undefined)) { - return text("Pass either projectId or path.", true); - } - let videoPath: string; - /** Ruler seconds → seconds of the exported file, when looking at a project. */ - let toVideoSec = (sec: number) => sec; - let rulerEndSec: number | null = null; - let note = ""; - if (args.projectId !== undefined) { - const exported = lastExports.get(args.projectId); - // A project deleted since still left its export on disk: show it, unflagged. - const current = await deps.documents.getProject(args.projectId).catch(() => null); - const stale = - exported !== undefined && - current !== null && - Date.parse(current.project.updatedAt) > exported.at.getTime(); - // No export shows the project as it is: render its frames as an export would. - if (current && (!exported || stale)) { - const why = exported ? "it changed after its last export" : "it has no export yet"; - const rendered = await renderProjectFrames( - current, - args.atSec ?? null, - args.count ?? 6, - why, - ); - if (rendered) return rendered; + const { images } = deps; + if (!images) return text(NO_IMAGE_WORK, true); + const { region } = args; + // More frames, more across: the sheet stays about as tall as one frame. + const wanted = args.atSec?.length ?? args.count ?? 12; + const columns = args.columns ?? (wanted > 24 ? 6 : wanted > 12 ? 5 : 4); + const tileWidth = tileWidthFor(columns); + const found = await shotsOf(args, 12, region ? FULL_WIDTH : tileWidth); + if (!isShots(found)) return found; + try { + const tiles = found.shots.map((shot) => ({ + label: `${shot.sec.toFixed(2)}s`, + bitmap: shot.jpeg + ? images.decode( + region ? images.crop(shot.jpeg, region, tileWidth) : shot.jpeg, + tileWidth, + ) + : null, + })); + // The tallest tile: a file whose resolution changes midway has frames of two heights. + const tileHeight = Math.max(0, ...tiles.map((tile) => tile.bitmap?.height ?? 0)); + if (tileHeight === 0) { + return text("No frame to show: the video ends before these times.", true); } - if (!exported) { - return text("This project has no export yet: call exportVideo first.", true); + const sheet = composeContactSheet(tiles, columns, tileWidth, tileHeight); + return { + content: [ + { + type: "text", + text: `${found.intro} On one sheet, ${columns} across, in reading order: ${tiles.map((tile) => tile.label).join(", ")}.`, + }, + { + type: "image", + data: images.encode(sheet).toString("base64"), + mimeType: "image/jpeg", + }, + ], + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The sheet could not be made: ${message}`, true); + } + }, + ); + + const pairShape = frameQueryShape(transport, MAX_PAIRS, 4); + server.registerTool( + "getBeforeAfter", + { + description: [ + `See what your edits changed: up to ${MAX_PAIRS} moments of a project as one image, 1280 pixels wide, one moment per row. Left, the project as it was at a checkpoint; right, as it is now. Both sides are rendered from the project as its export would show them, without exporting it.`, + "For each moment the answer also says whether the two frames differ and, when they do, over what share of the picture and inside which region of the frame: pass that region to getFrames to read the change at full resolution. A moment reported unchanged shows no difference this comparison can see: it compares the sheet's tiles and lets through a shift of a few levels, so a faint or very small change can pass unseen. Compare a region when that matters.", + "checkpointId is one that createCheckpoint, createProject or stopRecording returned for this project. The times are ruler seconds, the same on both sides: past a cut or a speed change made since the checkpoint, the two sides of a moment no longer show the same footage. The pointer is drawn from the track beside the video as it is now, on both sides: what setPointerTrack changed shows through the zooms it added, not through the pointer.", + ].join("\n"), + inputSchema: z.object({ + projectId: z.string().describe("The project to look at."), + checkpointId: z.string().describe("The state to compare the project with."), + atSec: pairShape.atSec, + count: pairShape.count, + startSec: pairShape.startSec, + endSec: pairShape.endSec, + region: pairShape.region, + }), + annotations: READ_ONLY, + }, + async ({ projectId, checkpointId, region, ...moments }) => { + const { images } = deps; + if (!images) return text(NO_IMAGE_WORK, true); + const problem = frameQueryProblem({ projectId, ...moments }); + if (problem) return text(problem, true); + const current = await deps.documents.getProject(projectId).catch(() => null); + if (!current) { + return text( + `No project has the id "${projectId}". Call listProjects for the valid ids.`, + true, + ); + } + // Through the runner, which holds the checkpoints: the app's, when it runs. + const read = await deps.runTool(READ_CHECKPOINT_TOOL, { projectId, checkpointId }); + const readText = read.content[0]?.type === "text" ? read.content[0].text : ""; + if (read.isError) return text(readText, true); + let before: AxcutDocument; + try { + before = documentSchema.parse(JSON.parse(readText)); + } catch { + return text("The checkpoint could not be read.", true); + } + + // The same ruler seconds on both sides, each mapped through its own trims and speeds. + // Times asked are kept as asked; spread ones cover the longer of the two films. + const rulerEnd = (document: AxcutDocument) => + Math.max(0, ...document.timeline.clips.map((clip) => clip.timelineEndSec)); + const times = + moments.atSec ?? + frameTimes( + Math.max(rulerEnd(before), rulerEnd(current)), + null, + moments.count ?? 4, + moments, + ); + const tileWidth = tileWidthFor(2); + const sides: Array> = []; + for (const document of [before, current]) { + // A side has no frame from its own end on, nor any at all with nothing on its + // timeline (a checkpoint taken before the first clip): missing there, not an error. + const end = rulerEnd(document); + const inRange = + document.timeline.clips.length === 0 ? [] : times.filter((sec) => sec < end); + if (inRange.length === 0) { + sides.push(times.map(() => null)); + continue; } - // Mapped through the document the export rendered, so a cut made since cannot shift - // which frame of this video is shown; the current one only says whether it is stale. - const { rendered } = exported; - videoPath = exported.path; - toVideoSec = (sec) => programmeSecOf(rendered, sec); - rulerEndSec = Math.max(0, ...rendered.timeline.clips.map((clip) => clip.timelineEndSec)); - if (stale) { - note = " The project changed after this export: export it again to see the changes."; + const rendered = await renderProjectShots( + document, + { atSec: inRange }, + inRange.length, + region ? FULL_WIDTH : tileWidth, + "", + ); + if (!rendered) { + return text( + "This OpenScreen cannot render a project's frames without exporting it, so it has no checkpoint to show.", + true, + ); } - } else { - const resolved = clientPath(transport, args.path ?? ""); - if (!resolved) return text(`The path must be absolute, got "${args.path}".`, true); - videoPath = resolved; + if (!isShots(rendered)) return rendered; + sides.push(times.map((sec) => (sec < end ? rendered.shots[inRange.indexOf(sec)] : null))); } - const video = await deps.openVideo(videoPath); try { - const asked = - args.atSec ?? - (rulerEndSec === null ? null : frameTimes(rulerEndSec, null, args.count ?? 6)); - const times = asked - ? asked.map((sec) => ({ - asked: sec, - at: frameTimes(video.durationSec, [toVideoSec(sec)], 1)[0], - })) - : frameTimes(video.durationSec, null, args.count ?? 6).map((at) => ({ asked: at, at })); - const content: CallToolResult["content"] = [ - { - type: "text", - text: `${times.length} frame(s) of a ${video.width}x${video.height} video lasting ${video.durationSec.toFixed(2)}s.${note}`, - }, - ]; - for (const { asked: askedSec, at } of times) { - const frame = await video.capture(at, FRAME_WIDTH); - content.push({ - type: "text", - text: - rulerEndSec === null - ? `${at.toFixed(2)}s` - : `${askedSec.toFixed(2)}s on the ruler, ${at.toFixed(2)}s into the video`, - }); - content.push({ type: "image", data: frame.data, mimeType: frame.mimeType }); + const bitmapOf = (shot: Shot | null) => + shot?.jpeg + ? images.decode( + region ? images.crop(shot.jpeg, region, tileWidth) : shot.jpeg, + tileWidth, + ) + : null; + /** Where a change found in the compared picture sits in the whole frame: through + * the crop actually taken, which stops at the frame's edge. */ + const inFrame = (shot: Shot | null, change: FrameRegion): FrameRegion => { + if (!region) return change; + const { width, height } = shot?.size ?? { width: 1, height: 1 }; + const cut = shot?.size + ? regionRect(width, height, region) + : { + x: region.x, + y: region.y, + width: Math.min(region.width, 1 - region.x), + height: Math.min(region.height, 1 - region.y), + }; + return { + x: (cut.x + change.x * cut.width) / width, + y: (cut.y + change.y * cut.height) / height, + width: (change.width * cut.width) / width, + height: (change.height * cut.height) / height, + }; + }; + const pairs = times.map((sec, i) => ({ + sec, + shot: sides[1][i], + before: bitmapOf(sides[0][i]), + after: bitmapOf(sides[1][i]), + })); + const tiles = pairs.flatMap(({ sec, before, after }) => + [before, after].map((bitmap) => ({ bitmap, label: `${sec.toFixed(2)}s` })), + ); + const tileHeight = Math.max(0, ...tiles.map((tile) => tile.bitmap?.height ?? 0)); + if (tileHeight === 0) { + return text("No frame to show: the project ends before these times.", true); } - return { content }; - } finally { - video.close(); + const sheet = composeContactSheet(tiles, 2, tileWidth, tileHeight); + const report = pairs.map(({ sec, shot, before, after }) => { + const at = round(sec, 2); + // A side with no frame at this moment: changed, with nowhere to point at. + if (!before || !after) { + const missing = !before && !after ? "both" : !before ? "checkpoint" : "now"; + return { sec: at, changed: missing !== "both", missing }; + } + // Frames of another size (the output format changed): nowhere to point at either. + if (before.width !== after.width || before.height !== after.height) { + return { sec: at, changed: true }; + } + const change = changedRegion(before, after); + if (!change) return { sec: at, changed: false }; + const placed = inFrame(shot, change.region); + return { + sec: at, + changed: true, + changedShare: round(change.share, 4), + // In fractions of the whole frame, whichever part of it was compared. + region: { + x: round(placed.x, 4), + y: round(placed.y, 4), + width: round(placed.width, 4), + height: round(placed.height, 4), + }, + }; + }); + return { + content: [ + { + type: "text", + text: `${pairs.length} moment(s) of the project, one per row: left, at the checkpoint; right, as it is now. Both rendered as its export would show them. A side marked missing has no frame at that moment: its film ends before it, or had nothing on its timeline.`, + }, + { type: "text", text: JSON.stringify({ moments: report }) }, + { + type: "image", + data: images.encode(sheet).toString("base64"), + mimeType: "image/jpeg", + }, + ], + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The comparison could not be made: ${message}`, true); } }, ); @@ -1280,3 +1854,22 @@ function programmeSecOf(document: AxcutDocument, rulerSec: number): number { readSpeedRegions(document), ); } + +/** + * The ruler second the export plays at `programmeSec`: `programmeSecOf` read backwards, which + * it allows because it never goes back. A cut makes a stretch of ruler seconds play at the same + * instant: what `starts` there starts after the cut, at its last second; what ends there ends + * before it, at its first. Either way the stretch a client reads stays clear of the cut. + */ +function rulerSecOf(document: AxcutDocument, programmeSec: number, starts: boolean): number { + let before = 0; + let after = Math.max(0, ...document.timeline.clips.map((clip) => clip.timelineEndSec)); + // Forty halvings of any film come down to well under a frame. + for (let step = 0; step < 40; step++) { + const middle = (before + after) / 2; + const played = programmeSecOf(document, middle); + if (starts ? played <= programmeSec : played < programmeSec) before = middle; + else after = middle; + } + return starts ? before : after; +} diff --git a/electron/mcp/openscreen-mcp-server.test.ts b/electron/mcp/openscreen-mcp-server.test.ts index f04a5489b0..1094e00897 100644 --- a/electron/mcp/openscreen-mcp-server.test.ts +++ b/electron/mcp/openscreen-mcp-server.test.ts @@ -156,7 +156,7 @@ async function connect( options: { editsAllowed?: boolean; headers?: Record; - media?: Pick; + media?: Pick; waitForRecording?: MediaToolDeps["waitForRecording"]; } = {}, ) { @@ -331,7 +331,11 @@ describe("the MCP tool surface", () => { "setPointerTrack", "exportVideo", "exportAudio", + "exportCaptions", + "getAudioReport", "getFrames", + "getContactSheet", + "getBeforeAfter", "createProject", ]); for (const tool of tools.slice(1, 1 + OPENSCREEN_TOOL_NAMES.length)) { @@ -382,7 +386,7 @@ describe("the MCP tool surface", () => { ); expect(instructions).toContain("startRecording hands over to OpenScreen's recording bar"); expect(instructions).toContain( - "startRecording, exportVideo, exportAudio and createProject are refused too", + "startRecording, exportVideo, exportAudio, exportCaptions and createProject are refused too", ); expect(instructions).toContain("all of them are lost when OpenScreen quits."); expect(instructions).toContain("turn on 'MCP edits' under MCP server in AI settings"); @@ -686,6 +690,91 @@ describe("the project's name and media", () => { expect(editor.applied).toHaveLength(0); }); + /** Stands in for stillClip.ts: writes the file the import stats, at the size it reports. */ + function stillMaker() { + return vi.fn(async (imagePath: string, holdSec: number) => { + const still = path.join(dir, `${path.parse(imagePath).name}_${holdSec * 1000}.still.mp4`); + writeFileSync(still, "still"); + return { path: still, width: 802, height: 602 }; + }); + } + + it("imports an image as a silent video of its hold, 5 seconds by default", async () => { + const editor = new FakeEditor(); + const openVideo = probe(); + const approveMedia = vi.fn(); + const makeStill = stillMaker(); + const mcp = await connect(editor, { media: { openVideo, approveMedia, makeStill } }); + const image = mediaFile("logo.png"); + const result = await mcp.callTool({ name: "importMedia", arguments: { path: image } }); + expect(result.isError).toBeFalsy(); + const payload = JSON.parse(resultText(result)); + expect(payload).toMatchObject({ + kind: "video", + still: true, + label: "logo.png", + durationSec: 5, + width: 802, + height: 602, + }); + expect(makeStill).toHaveBeenCalledWith(image, 5); + const asset = editor.document?.assets.find((a) => a.id === payload.assetId); + expect(asset).toMatchObject({ kind: "video", durationSec: 5 }); + expect(asset?.originalPath).toMatch(/\.still\.mp4$/); + expect(asset?.video).toMatchObject({ width: 802, height: 602, fps: 30 }); + // The editor plays the generated video, never the image. + expect(approveMedia).toHaveBeenCalledWith(asset?.originalPath); + expect(openVideo).not.toHaveBeenCalled(); + }); + + it("takes a hold from 0.5 to 60 seconds, for an image only", async () => { + const editor = new FakeEditor(); + const makeStill = stillMaker(); + const mcp = await connect(editor, { media: { makeStill } }); + const image = mediaFile("card.jpg"); + for (const holdSec of [0.5, 60]) { + const result = await mcp.callTool({ + name: "importMedia", + arguments: { path: image, holdSec }, + }); + expect(JSON.parse(resultText(result)).durationSec).toBe(holdSec); + } + for (const holdSec of [0.4, 61]) { + const result = await mcp.callTool({ + name: "importMedia", + arguments: { path: image, holdSec }, + }); + expect(result.isError).toBe(true); + } + const onVideo = await mcp.callTool({ + name: "importMedia", + arguments: { path: mediaFile("take.mp4"), holdSec: 3 }, + }); + expect(onVideo.isError).toBe(true); + expect(resultText(onVideo)).toContain("holdSec is for an image only"); + expect(makeStill).toHaveBeenCalledTimes(2); + }); + + it("names the image extensions when it refuses one, and reports a still it could not make", async () => { + const editor = new FakeEditor(); + const makeStill = vi.fn(async () => { + throw new Error("OpenScreen found no ffmpeg to turn the image into a clip with."); + }); + const mcp = await connect(editor, { media: { makeStill } }); + const gif = await mcp.callTool({ + name: "importMedia", + arguments: { path: mediaFile("a.gif") }, + }); + expect(resultText(gif)).toContain("Image: .png, .jpg, .jpeg, .webp"); + const failed = await mcp.callTool({ + name: "importMedia", + arguments: { path: mediaFile("b.webp") }, + }); + expect(failed.isError).toBe(true); + expect(resultText(failed)).toContain("found no ffmpeg"); + expect(editor.applied).toHaveLength(0); + }); + it("imports nothing while MCP edits is off", async () => { const editor = new FakeEditor(); const openVideo = probe(); diff --git a/electron/mcp/openscreen-mcp-server.ts b/electron/mcp/openscreen-mcp-server.ts index 774f3ccde0..9e50df4756 100644 --- a/electron/mcp/openscreen-mcp-server.ts +++ b/electron/mcp/openscreen-mcp-server.ts @@ -55,6 +55,7 @@ import { } from "../../src/lib/ai-edition/document/transcript"; import { type AxcutDocument, documentSchema } from "../../src/lib/ai-edition/schema"; import type { ShaderEffectChecker } from "../../src/lib/ai-edition/shaderEffects"; +import type { StylePreset } from "../../src/lib/ai-edition/stylePresets"; import { segmentsFromStt, transcriptFromSegments, @@ -174,16 +175,25 @@ export interface McpToolDeps extends ImportMediaDeps { cameraSegmentation?: () => SegmentationSupport; /** The compositor's check of an agent-written effect's WGSL; absent where nothing can ask. */ checkShaderEffect?: ShaderEffectChecker; + /** The user's saved style presets (`StylePresetService.list`); absent where none can be read. */ + stylePresets?: () => Promise; /** The main process's on-device Whisper (`SttManager.transcribe`). Absent: no transcribe tool. */ transcribe?(request: SttTranscribeRequest): Promise; version: string; /** `openscreen mcp` only: a newer OpenScreen to tell the user about, for the user who never * opens the app and so never sees its update button. */ updateNotice?: string; + /** Told the name of each tool a client calls, and nothing of the call (usage-ping.ts). + * Absent on the app's channel: `openscreen mcp` counted the call where the client made it. */ + onToolCall?(name: string): void; } export const LIST_PROJECTS_TOOL = "listProjects"; export const TRANSCRIBE_TOOL = "transcribe"; +/** The runner's own: getBeforeAfter reads a checkpoint through it. No client is served it; + * the app's channel is, so `openscreen mcp` reads the checkpoints the running app holds. */ +export const READ_CHECKPOINT_TOOL = "readCheckpoint"; +export const READ_CHECKPOINT_SCHEMA = z.object({ projectId: z.string(), checkpointId: z.string() }); const transcribeArgs = z.object({ assetId: z @@ -302,7 +312,7 @@ export function mcpInstructions(options: { CHECKPOINT_LIFETIMES[transport], ...(media && !editsAllowed ? [ - `startRecording, exportVideo, exportAudio and createProject are refused too while ${MCP_EDITS_SETTING} is off.`, + `startRecording, exportVideo, exportAudio, exportCaptions and createProject are refused too while ${MCP_EDITS_SETTING} is off.`, ] : []), ...(options.transcribe ? [TRANSCRIBE_NOTE] : []), @@ -463,6 +473,25 @@ export function createToolRunner(deps: McpToolDeps): McpToolRunner { }; } + /** A checkpoint's document, as it was saved: read, never restored. */ + function readCheckpoint(document: AxcutDocument, args: unknown): AgentToolExecution { + const id = (args as { checkpointId?: unknown } | null)?.checkpointId; + const checkpoint = typeof id === "string" ? checkpoints.get(id) : undefined; + if (!checkpoint) { + return { + ok: false, + resultJson: `Unknown checkpointId. ${CHECKPOINT_LIFETIMES[deps.transport]}`, + }; + } + if (checkpoint.document.project.id !== document.project.id) { + return { + ok: false, + resultJson: `This checkpoint belongs to another project. Pass projectId "${checkpoint.document.project.id}".`, + }; + } + return { ok: true, resultJson: JSON.stringify(checkpoint.document) }; + } + function hasCheckpoint(projectId: string): boolean { for (const checkpoint of checkpoints.values()) { if (checkpoint.document.project.id === projectId) return true; @@ -574,6 +603,7 @@ export function createToolRunner(deps: McpToolDeps): McpToolRunner { ): Promise { if (name === "createCheckpoint") return createCheckpoint(document); if (name === "restoreCheckpoint") return restoreCheckpoint(document, args, editsAllowed); + if (name === READ_CHECKPOINT_TOOL) return readCheckpoint(document, args); // This server's own switch, so the refusal names it rather than the in-app agent's. if ((edit || isMutatingTool(name) || PROJECT_EDIT_TOOLS.has(name)) && !editsAllowed) { return consentRequired(name, args, MCP_EDITS_SETTING); @@ -587,6 +617,7 @@ export function createToolRunner(deps: McpToolDeps): McpToolRunner { availableByAssetId, cameraSegmentation: deps.cameraSegmentation, checkShaderEffect: deps.checkShaderEffect, + stylePresets: deps.stylePresets, }); } @@ -853,13 +884,37 @@ function keepTranscriptsMadeSince( return restored; } +/** + * `server`, with every tool registered through it telling `onToolCall` its name on each call. + * One place for the document tools and the media tools alike, whoever registers them. + */ +function countingToolCalls(server: McpServer, onToolCall: (name: string) => void): McpServer { + return new Proxy(server, { + get(target, key) { + if (key !== "registerTool") { + const value = Reflect.get(target, key, target); + return typeof value === "function" ? value.bind(target) : value; + } + return (name: string, config: unknown, handler: (...args: unknown[]) => unknown) => + Reflect.apply(target.registerTool, target, [ + name, + config, + (...args: unknown[]) => { + onToolCall(name); + return handler(...args); + }, + ]); + }, + }); +} + export function createOpenScreenMcpServer( deps: McpToolDeps, runTool: McpToolRunner, /** The media tools (media-tools.ts), served by both servers but not the app's channel. */ media?: MediaTools, ): McpServer { - const server = new McpServer( + const mcpServer = new McpServer( { name: MCP_SERVER_NAME, version: deps.version }, { instructions: mcpInstructions({ @@ -871,6 +926,7 @@ export function createOpenScreenMcpServer( }), }, ); + const server = deps.onToolCall ? countingToolCalls(mcpServer, deps.onToolCall) : mcpServer; const projectIdArg = z.string().optional().describe(PROJECT_ID_DESCRIPTIONS[deps.transport]); server.registerTool( LIST_PROJECTS_TOOL, @@ -953,7 +1009,7 @@ export function createOpenScreenMcpServer( contents: [{ uri: uri.href, mimeType: "text/markdown", text: EFFECTS_CONTRACT }], }), ); - return server; + return mcpServer; } function isAllowedHost(hostHeader: string | undefined, port: number): boolean { diff --git a/electron/mcp/plugin-launcher.test.ts b/electron/mcp/plugin-launcher.test.ts new file mode 100644 index 0000000000..fc476122db --- /dev/null +++ b/electron/mcp/plugin-launcher.test.ts @@ -0,0 +1,233 @@ +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createInterface } from "node:readline"; +import { afterEach, describe, expect, it } from "vitest"; + +// The plugin's MCP launcher (plugin/scripts/openscreen-mcp.mjs), run as Claude Code runs it: +// `node