diff --git a/crates/pptx/src/read/timing.rs b/crates/pptx/src/read/timing.rs index 1caa0001f..ca29f4592 100644 --- a/crates/pptx/src/read/timing.rs +++ b/crates/pptx/src/read/timing.rs @@ -57,14 +57,44 @@ struct Found<'a> { group: usize, /// Sum of the start delays of the time nodes between the click group and the effect, in ms. offset: u32, + /// Whether any ancestor time node defers start until an event (`onClick`, `onEnd`, targeted `onBegin`) or nonzero delay. + deferred: bool, } /// Where `collect` is in the time tree: the click group and the delay accumulated inside it. #[derive(Clone, Copy)] struct At { trigger: Option, + main_seq_id: Option, group: usize, offset: u32, + deferred: bool, +} + +/// Returns whether `st` (`p:stCondLst`) is PowerPoint's automatic main-sequence step wrapper: +/// `` paired only with `` +/// referencing the immediate enclosing `mainSeq` ``. +fn is_main_seq_auto(st: &El, main_seq_id: Option) -> bool { + let Some(ms_id) = main_seq_id else { + return false; + }; + let is_indefinite = |d: &El| { + d.attr("evt").is_none() + && d.attr("delay").map(str::trim) == Some("indefinite") + && d.child("tgtEl").is_none() + && d.child("tn").is_none() + && d.child("rtn").is_none() + }; + let is_main_seq_on_begin = |d: &El| { + d.attr("evt") == Some("onBegin") + && d.attr("delay").map(str::trim) == Some("0") + && d.child("tgtEl").is_none() + && d.child("rtn").is_none() + && d.child("tn").and_then(|tn| tn.u32("val")) == Some(ms_id) + }; + st.children_named("cond").any(is_indefinite) + && st.children_named("cond").any(is_main_seq_on_begin) + && st.children_named("cond").all(|d| is_indefinite(d) || is_main_seq_on_begin(d)) } fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, depth: usize) { @@ -73,7 +103,8 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, } for c in e.elements() { if c.is("cTn") && c.has_attr("presetClass") { - out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset }); + let deferred = at.deferred || c.child("stCondLst").is_some_and(defers_start); + out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset, deferred }); continue; } let mut at = at; @@ -82,17 +113,25 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, && ctn.attr("nodeType") == Some("interactiveSeq") { at.trigger = ctn.path(&["stCondLst", "cond", "tgtEl", "spTgt"]).and_then(|s| s.u32("spid")); + at.main_seq_id = None; } - if c.is("cTn") - && let Some(cond) = c.path(&["stCondLst", "cond"]) - { - if cond.attr("delay").map(str::trim) == Some("indefinite") { - *groups += 1; - at.group = *groups; - at.offset = 0; - } else { - at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); + if c.is("cTn") { + let is_main_seq = c.attr("nodeType") == Some("mainSeq"); + if let Some(st) = c.child("stCondLst") { + if !(!is_main_seq && !at.deferred && is_main_seq_auto(st, at.main_seq_id)) && defers_start(st) { + at.deferred = true; + } + if let Some(cond) = st.child("cond") { + if cond.attr("delay").map(str::trim) == Some("indefinite") { + *groups += 1; + at.group = *groups; + at.offset = 0; + } else { + at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); + } + } } + at.main_seq_id = if is_main_seq && !at.deferred { c.u32("id") } else { None }; } collect(c, at, groups, out, depth + 1); } @@ -207,12 +246,44 @@ fn behaviour_auto_reverses(c: &El) -> bool { /// Volume, mute, Loop until Stopped, Hide While Not Playing and Play Full Screen live in the timing tree /// (`p:video`/`p:audio` > `p:cMediaNode`), not on the picture: copy them onto the target's `MediaClip`. +/// Returns whether `st` (`p:stCondLst`) defers playback instead of starting immediately on slide entry. +fn defers_start(st: &El) -> bool { + let is_auto_begin = |c: &El| { + c.attr("evt") == Some("onBegin") + && c.attr("delay").map(str::trim) == Some("0") + && c.child("tgtEl").is_none() + && c.child("tn").is_none() + && c.child("rtn").is_none() + }; + let has_on_begin = st.children_named("cond").any(is_auto_begin); + st.children_named("cond") + .any(|c| (c.attr("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr("delay").map(str::trim) != Some("0"))) +} + +/// Applies `p:video`/`p:audio` timing node settings and main-sequence autoplay triggers to media shapes. pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { - let mut nodes = vec![]; - for tag in ["video", "audio"] { - timing.find_all(tag, &mut nodes); + fn collect_media<'a>(e: &'a El, deferred: bool, out: &mut Vec<(&'a El, bool)>, depth: usize) { + if depth > 64 || out.len() >= 10_000 { + return; + } + let mut deferred = deferred; + if e.is("cTn") + && let Some(st) = e.child("stCondLst") + && defers_start(st) + { + deferred = true; + } + if e.is("video") || e.is("audio") { + out.push((e, deferred)); + return; + } + for c in e.elements() { + collect_media(c, deferred, out, depth + 1); + } } - for node in nodes.into_iter().take(10_000) { + let mut nodes = vec![]; + collect_media(timing, false, &mut nodes, 0); + for (node, deferred) in nodes { let Some(cm) = node.child("cMediaNode") else { continue }; let Some(id) = cm.path(&["tgtEl", "spTgt"]).and_then(|t| t.u32("spid")).and_then(|f| ctx.lookup(f)) else { continue }; let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) else { continue }; @@ -228,10 +299,44 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { if cm.child("cTn").and_then(|c| c.attr("repeatCount")) == Some("indefinite") { clip.loop_play = true; } + if cm.child("cTn").and_then(|c| c.attr("fill")) == Some("remove") { + clip.rewind = true; + } + if cm.u32("numSld").is_some_and(|n| n > 1) { + clip.play_across_slides = true; + } + if !deferred && cm.path(&["cTn", "stCondLst", "cond"]).is_some_and(|c| c.attr("evt").is_none() && c.attr("delay").map(str::trim) == Some("0")) + { + clip.autoplay = true; + } if node.bool("fullScrn") == Some(true) { clip.full_screen = true; } } + let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(defers_start); + if !root_deferred && let Some(tn) = timing.child("tnLst") { + let mut found = vec![]; + collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); + for f in found.into_iter().filter(|f| f.trigger.is_none()) { + let c = f.ctn; + if c.attr("nodeType") == Some("clickEffect") || f.deferred { + break; + } + let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr")); + let preset = c.u32("presetID").unwrap_or(0); + let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class)); + let delay = c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0); + if class == AnimClass::Media + && effect == "play" + && f.offset == 0 + && delay == 0 + && let Some(id) = c.find("spTgt").and_then(|t| t.u32("spid")).and_then(|s| ctx.lookup(s)) + && let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) + { + clip.autoplay = true; + } + } + } } /// Flatten the timing tree into the Animation Pane list. @@ -239,7 +344,7 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes: let _ = (imp, part); let Some(tn) = timing.child("tnLst") else { return vec![] }; let mut found = vec![]; - collect(tn, At { trigger: None, group: 0, offset: 0 }, &mut 0, &mut found, 0); + collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); // Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`. let bld_p: std::collections::HashMap<(u32, String), bool> = timing .child("bldLst") diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 6683615d9..96cd5800a 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -822,9 +822,7 @@ fn slide_xml(x: &mut Exp, o: &mut Out, s: &Slide, comment_rel: Option<&str>) -> if let Some(t) = &s.transition { timing::transition(&mut w, x, o, t); } - if !s.animations.is_empty() { - timing::timing(&mut w, x, &s.animations, &s.shapes, &ids); - } + timing::timing(&mut w, x, &s.animations, &s.shapes, &ids); slide_ext_list(&mut w, s.raw_ext.as_deref(), comment_rel); w.close("p:sld"); w.finish() diff --git a/crates/pptx/src/write/timing.rs b/crates/pptx/src/write/timing.rs index 6376e3ca0..90daac780 100644 --- a/crates/pptx/src/write/timing.rs +++ b/crates/pptx/src/write/timing.rs @@ -592,7 +592,7 @@ fn shape_index<'a>(shapes: &'a [Shape], depth: usize, out: &mut std::collections } } -/// Write `p:timing` for a slide's animations. +/// Write `p:timing` for a slide's animations and media settings. pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idmap: &IdMap) { let mut grp_count: std::collections::HashMap = Default::default(); let mut main: Vec = vec![]; @@ -686,7 +686,8 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm None => main.extend(effs), } } - if main.is_empty() && triggered.is_empty() { + let media = collect_media(shapes, idmap); + if main.is_empty() && triggered.is_empty() && media.is_empty() { return; } let mut ids = Ids(0); @@ -757,6 +758,9 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm w.close("p:nextCondLst"); w.close("p:seq"); } + for (spid, clip) in &media { + write_media_node(w, &mut ids, *spid, clip); + } w.close("p:childTnLst"); w.close("p:cTn"); w.close("p:par"); @@ -770,3 +774,57 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm } w.close("p:timing"); } + +/// Collects media shapes on the slide that have non-default playback settings requiring a `p:video`/`p:audio` timing node. +fn collect_media<'a>(shapes: &'a [Shape], idmap: &IdMap) -> Vec<(u32, &'a deckcraft_model::MediaClip)> { + let mut media = Vec::new(); + deckcraft_model::walk(shapes, &mut |shape, _| { + if let ShapeKind::Media(clip) = &shape.kind + && (clip.autoplay + || (clip.volume - 1.0).abs() > 1e-6 + || clip.hide_while_not_playing + || clip.loop_play + || clip.rewind + || clip.play_across_slides + || (clip.video && clip.full_screen)) + && let Some(spid) = idmap.get(shape.id) + { + media.push((spid, clip)); + } + }); + media +} + +/// Writes a `p:video` or `p:audio` media timing node (`p:cMediaNode`) for a media shape. +fn write_media_node(w: &mut W, ids: &mut Ids, spid: u32, clip: &deckcraft_model::MediaClip) { + let tag = if clip.video { "p:video" } else { "p:audio" }; + w.open(tag, A::new().t("fullScrn", clip.video && clip.full_screen)); + let mut cm = A::new().a("vol", (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32); + if clip.volume <= 1e-6 { + cm = cm.t("mute", true); + } + if clip.hide_while_not_playing { + cm = cm.a("showWhenStopped", 0); + } + if clip.play_across_slides { + cm = cm.a("numSld", 999); + } + w.open("p:cMediaNode", cm); + w.open( + "p:cTn", + A::new() + .a("id", ids.next()) + .a("fill", if clip.rewind { "remove" } else { "hold" }) + .a("display", 0) + .o("repeatCount", clip.loop_play.then_some("indefinite")), + ); + w.open0("p:stCondLst"); + w.empty("p:cond", A::new().a("delay", if clip.autoplay { "0" } else { "indefinite" })); + w.close("p:stCondLst"); + w.close("p:cTn"); + w.open0("p:tgtEl"); + w.empty("p:spTgt", A::new().a("spid", spid)); + w.close("p:tgtEl"); + w.close("p:cMediaNode"); + w.close(tag); +} diff --git a/crates/pptx/tests/it/media_timing.rs b/crates/pptx/tests/it/media_timing.rs index 8fe325964..43323500b 100644 --- a/crates/pptx/tests/it/media_timing.rs +++ b/crates/pptx/tests/it/media_timing.rs @@ -74,3 +74,129 @@ fn muted_audio_has_no_volume_and_other_clips_keep_theirs() { assert_eq!(c[0].volume, 1.0); assert_eq!((c[1].volume, c[1].loop_play, c[1].full_screen), (0.0, false, false)); } + +#[test] +fn media_autoplay_respects_ancestor_conditions_and_delays() { + let immediate = clips(|v, a| { + format!( + r#""# + ) + }); + assert!(immediate[0].autoplay, "delay=0 ancestor allows autoplay"); + assert!(immediate[1].autoplay, "untargeted onBegin delay=0 ancestor allows autoplay"); + + let delayed_and_onclick = clips(|v, a| { + format!( + r#""# + ) + }); + assert!(!delayed_and_onclick[0].autoplay, "delayed ancestor blocks autoplay"); + assert!(!delayed_and_onclick[1].autoplay, "onClick ancestor blocks autoplay"); + + let targeted_tn_and_own_cond = clips(|v, a| { + format!( + r#""# + ) + }); + assert!(!targeted_tn_and_own_cond[0].autoplay, "targeted onBegin ancestor blocks autoplay"); + assert!(!targeted_tn_and_own_cond[1].autoplay, "media cond with explicit evt is not autoplay"); + + let delayed_media_cond = clips(|v, _| { + format!( + r#""# + ) + }); + assert!(!delayed_media_cond[0].autoplay, "non-zero media cond delay is not autoplay"); +} + +#[test] +fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() { + let mut p = defaults::new_presentation(None); + let video = p.add_media("clip.mp4", "video/mp4", b"video".to_vec()).expect("media"); + let audio = p.add_media("clip.m4a", "audio/mp4", b"audio".to_vec()).expect("media"); + let vid_id = ShapeId(p.alloc_id().expect("id")); + let aud_id = ShapeId(p.alloc_id().expect("id")); + let s0 = Arc::make_mut(&mut p.slides[0]); + s0.shapes.push(deckcraft_model::Shape { + id: vid_id, + name: "AutoplayVideo".into(), + xfrm: Some(Xfrm::new(40.0, 40.0, 200.0, 100.0)), + kind: ShapeKind::Media(MediaClip { + media: video, + video: true, + autoplay: true, + volume: 0.75, + hide_while_not_playing: true, + loop_play: true, + rewind: true, + play_across_slides: true, + full_screen: true, + ..Default::default() + }), + ..Default::default() + }); + s0.shapes.push(deckcraft_model::Shape { + id: aud_id, + name: "ManualMutedAudio".into(), + xfrm: Some(Xfrm::new(40.0, 160.0, 200.0, 100.0)), + kind: ShapeKind::Media(MediaClip { media: audio, video: false, autoplay: false, volume: 0.0, loop_play: true, ..Default::default() }), + ..Default::default() + }); + let bytes = deckcraft_pptx::export(&p).expect("export"); + let back = deckcraft_pptx::import(&bytes).expect("import"); + let clips: Vec<&MediaClip> = back.slides[0] + .shapes + .iter() + .filter_map(|s| match &s.kind { + ShapeKind::Media(m) => Some(m), + _ => None, + }) + .collect(); + assert_eq!(clips.len(), 2); + assert!( + clips[0].video + && clips[0].autoplay + && clips[0].hide_while_not_playing + && clips[0].loop_play + && clips[0].rewind + && clips[0].play_across_slides + && clips[0].full_screen + ); + assert!((clips[0].volume - 0.75).abs() < 1e-4); + assert!( + !clips[1].video + && !clips[1].autoplay + && clips[1].loop_play + && !clips[1].rewind + && !clips[1].play_across_slides + && !clips[1].hide_while_not_playing + && !clips[1].full_screen + ); + assert_eq!(clips[1].volume, 0.0); + + // Main-sequence automatic Play (mediacall) effect with indefinite media node also sets autoplay. + let main_seq_play = self::clips(|v, _| { + format!( + r#""# + ) + }); + assert!(main_seq_play[0].autoplay, "main-sequence automatic Play effect sets autoplay"); + + // An `indefinite` + `onBegin delay="0"` condition whose `` references a different + // click-dependent time node rather than the enclosing `mainSeq` must stay deferred. + let non_main_seq_tn_play = self::clips(|v, _| { + format!( + r#""# + ) + }); + assert!(!non_main_seq_tn_play[0].autoplay, "onBegin referencing non-mainSeq click-dependent node is not autoplay"); + + // Command-based Play beneath an onClick or onEnd ancestor must not set autoplay. + let deferred_cmd_play = self::clips(|v, a| { + format!( + r#""# + ) + }); + assert!(!deferred_cmd_play[0].autoplay, "command-based Play under onClick ancestor is not autoplay"); + assert!(!deferred_cmd_play[1].autoplay, "command-based Play under onEnd ancestor is not autoplay"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 30f76cff3..005d13516 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -92,7 +92,7 @@ the round trip even though DeckCraft doesn't model it. | Charts (`cx:` chartex: waterfall, funnel, treemap, sunburst, histogram, Pareto, box) | yes | yes | Unchanged parts kept, with their embedded workbook (#335); edited and new ones written from the model with a plain-chart fallback. Treemap and sunburst hierarchy levels kept; region maps kept, drawn as tiles (no map geometry) | | SmartArt (`dgm`) | the drawing part as a group (text laid out on its `dsp:txXfrm` rectangle), and the outline from the data model (Text Pane) | as a diagram: data model from the outline; layout, quick style and colour parts (the file's own kept until the layout is switched); the group as the cached drawing | DeckCraft's layout definitions are simple; a diagram without a cached drawing isn't drawn. SmartArt kept only as XML, without its relationship parts, still loses the drawing and data parts (#203) | | Equations (OMML, `a14:m`) | no | no | PR #55 open | -| Audio / video (`p14:media`, trim, fades, bookmarks) | yes | partly | Playback options lost on save (#74) | +| Audio / video (`p14:media`, trim, fades, bookmarks, playback options) | yes | yes | Volume, mute, autoplay, loop, rewind, play across slides, hide while not playing and full screen round-trip (`media_timing.rs`) | | Ink (`contentPart`) | yes | as a group of freeform lines | PowerPoint sees shapes, not ink | | Transitions incl. p14/p15 (Vortex, Morph…) | all 48 | all 48 | `every_transition_kind_round_trips` | | Animations: timing tree, build paragraphs, triggers, motion paths | yes (flattened to the Animation Pane list) | yes (rebuilt) | `every_animation_effect_survives`; repeat, triggers, bounce end and rewind kept |