From f060ca793fdbbd56f6255bc20980ce9a90af94bd Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 17:05:07 -0800 Subject: [PATCH] Wave 29B: harden VideoToolbox export cancellation/fallback and fix streaming comp saver edge cases --- crates/engine/src/export.rs | 198 +++++++++++++++---- crates/model/src/comp/save.rs | 349 +++++++++++++++++++++++++++++++--- crates/model/src/lua_value.rs | 48 ++++- 3 files changed, 524 insertions(+), 71 deletions(-) diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index d5195aa00441cf4bf2a6b42dfe27fe03f42e3003..790f307d9d893ab3a573a63ff6d1896d6181e9cc 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -928,6 +928,18 @@ impl VideoExportError { } } +fn h264_scale_filter_and_dims(width: u32, height: u32, max_height: Option) -> (String, u32, u32) { + if let Some(max_h) = max_height.filter(|&h| h >= 2) { + let oh = (height.min(max_h) & !1).max(2); + let ow = ((((width as f64) * (oh as f64) / (height as f64)) / 2.0).round() as u32 * 2).max(2); + (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) + } else { + let ow = (width & !1).max(2); + let oh = (height & !1).max(2); + ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) + } +} + /// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames /// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`. pub fn export_node_video_ffmpeg_with_progress( @@ -962,6 +974,7 @@ pub fn export_node_video_ffmpeg_with_progress( engine.hiq = opts.hiq; engine.proxy_scale = opts.proxy_scale.max(1); + let started_at = Instant::now(); let vt = probe_videotoolbox_support(); let encoder = select_video_encoder(opts.codec, vt, true); let res = match export_node_video_ffmpeg_with_encoder( @@ -971,19 +984,25 @@ pub fn export_node_video_ffmpeg_with_progress( control, &mut on_progress, encoder, + started_at, ) { Ok(summary) => Ok(summary), Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => { - let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false); - export_node_video_ffmpeg_with_encoder( - engine, - comp, - opts, - control, - &mut on_progress, - fallback, - ) - .map_err(VideoExportError::into_string) + if control.is_some_and(ExportControl::is_cancelled) { + Err("Cancelled".to_owned()) + } else { + let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false); + export_node_video_ffmpeg_with_encoder( + engine, + comp, + opts, + control, + &mut on_progress, + fallback, + started_at, + ) + .map_err(VideoExportError::into_string) + } } Err(err) => Err(err.into_string()), }; @@ -1000,9 +1019,9 @@ fn export_node_video_ffmpeg_with_encoder( control: Option<&ExportControl>, on_progress: &mut impl FnMut(ExportProgress), encoder: VideoEncoder, + started_at: Instant, ) -> Result { let [start, end] = opts.range; - let t0 = Instant::now(); let total = (end - start + 1) as usize; let fps = comp.fps.max(1.0); let node_name = comp.node(opts.target).name.clone(); @@ -1096,20 +1115,7 @@ fn export_node_video_ffmpeg_with_encoder( let (out_width, out_height) = match opts.codec { VideoCodec::H264Share => { - let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) { - let oh = (height.min(max_h) & !1).max(2); - let ow = if height > max_h { - let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32; - (scaled & !1).max(2) - } else { - (width & !1).max(2) - }; - (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) - } else { - let ow = (width & !1).max(2); - let oh = (height & !1).max(2); - ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) - }; + let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height); let mut encoder_args = Vec::new(); push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf)); cmd.args(&encoder_args); @@ -1145,7 +1151,7 @@ fn export_node_video_ffmpeg_with_encoder( .stderr(Stdio::piped()); let mut child = cmd.spawn().map_err(|e| { - VideoExportError::EncoderFailed(format!( + VideoExportError::Fatal(format!( "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}" )) })?; @@ -1164,10 +1170,15 @@ fn export_node_video_ffmpeg_with_encoder( let mut cancelled = false; let writer_err: Arc>> = Arc::new(Mutex::new(None)); let writer_failed = Arc::new(AtomicBool::new(false)); - let stdin = child - .stdin - .take() - .ok_or_else(|| VideoExportError::EncoderFailed("failed to open ffmpeg stdin".to_owned()))?; + let writer_fatal = Arc::new(AtomicBool::new(false)); + let Some(stdin) = child.stdin.take() else { + let _ = child.kill(); + let _ = child.wait(); + let _ = stderr_thread.join(); + return Err(VideoExportError::Fatal( + "failed to open ffmpeg stdin".to_owned(), + )); + }; let frame_bytes_len = (width as usize) .saturating_mul(height as usize) @@ -1178,6 +1189,7 @@ fn export_node_video_ffmpeg_with_encoder( let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(queue_cap + 2); let writer_err_c = Arc::clone(&writer_err); let writer_failed_c = Arc::clone(&writer_failed); + let writer_fatal_c = Arc::clone(&writer_fatal); let dst_size = [width, height]; let writer_thread = std::thread::spawn(move || { let mut stdin = stdin; @@ -1190,6 +1202,7 @@ fn export_node_video_ffmpeg_with_encoder( *g = Some(e); } } + writer_fatal_c.store(true, Ordering::Release); writer_failed_c.store(true, Ordering::Release); break; } @@ -1223,7 +1236,7 @@ fn export_node_video_ffmpeg_with_encoder( first_stats.eval_ms, opts.out_path.clone(), node_name.clone(), - t0, + started_at, ); if let Some(ctrl) = control { ctrl.update_progress(&first_prog); @@ -1247,13 +1260,13 @@ fn export_node_video_ffmpeg_with_encoder( } let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; for (idx, frame) in ((start + 1)..=end).enumerate() { - if writer_failed.load(Ordering::Acquire) { - break; - } if control.is_some_and(ExportControl::is_cancelled) { cancelled = true; break; } + if writer_failed.load(Ordering::Acquire) { + break; + } prefetch.set_current_seq(idx); let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; if ahead_frame <= end { @@ -1297,7 +1310,7 @@ fn export_node_video_ffmpeg_with_encoder( prev_ms, opts.out_path.clone(), node_name.clone(), - t0, + started_at, ); if let Some(ctrl) = control { ctrl.update_progress(&prog); @@ -1305,6 +1318,9 @@ fn export_node_video_ffmpeg_with_encoder( on_progress(prog); } } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) { if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() { let mut pixels = recycle_rx.try_recv().unwrap_or_default(); @@ -1320,12 +1336,15 @@ fn export_node_video_ffmpeg_with_encoder( prev_ms, opts.out_path.clone(), node_name.clone(), - t0, + started_at, ); if let Some(ctrl) = control { ctrl.update_progress(&prog); } on_progress(prog); + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } } } Err(e) => { @@ -1340,6 +1359,9 @@ fn export_node_video_ffmpeg_with_encoder( } drop(tx); + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) { // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately. let _ = child.kill(); @@ -1353,26 +1375,33 @@ fn export_node_video_ffmpeg_with_encoder( if pipe_err.is_some() && !cancelled { let _ = child.kill(); } - let status = child - .wait() - .map_err(|e| VideoExportError::EncoderFailed(format!("failed waiting on ffmpeg: {e}")))?; + let wait_res = child.wait(); let stderr_text = stderr_thread.join().unwrap_or_default(); let stderr_trim = stderr_text.trim(); - if cancelled { + if cancelled || control.is_some_and(ExportControl::is_cancelled) { return Err(VideoExportError::Cancelled); } if let Some(err) = readback_err { return Err(VideoExportError::Fatal(err)); } if let Some(err) = pipe_err { + if writer_fatal.load(Ordering::Acquire) { + return Err(VideoExportError::Fatal(err)); + } return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() { format!("{err} (ffmpeg: {stderr_trim})") } else { err })); } + let status = wait_res.map_err(|e| { + VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}")) + })?; if !status.success() { + if control.is_some_and(ExportControl::is_cancelled) { + return Err(VideoExportError::Cancelled); + } return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() { format!("ffmpeg exited with {status}") } else { @@ -1395,7 +1424,7 @@ fn export_node_video_ffmpeg_with_encoder( width: out_width, height: out_height, has_audio, - total_ms: t0.elapsed().as_secs_f64() * 1000.0, + total_ms: started_at.elapsed().as_secs_f64() * 1000.0, file_bytes, }) } @@ -2440,6 +2469,7 @@ Encoders: None, &mut noop, VideoEncoder::Libx264, + Instant::now(), ) .expect("software libx264 fallback export"); assert_eq!(sw_summary.frames_written, 3); @@ -2463,6 +2493,7 @@ Encoders: None, &mut noop, VideoEncoder::ProResKs422, + Instant::now(), ) .expect("software prores_ks fallback export"); assert_eq!(sw_prores.frames_written, 3); @@ -2470,4 +2501,89 @@ Encoders: let _ = std::fs::remove_dir_all(&tmp_dir); } + + #[test] + fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() { + // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102 + let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100)); + assert_eq!((w, h), (102, 100)); + let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200)); + assert_eq!((w, h), (102, 100)); + let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50)); + assert_eq!((w, h), (50, 50)); + + // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666 + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700)); + assert_eq!((w, h), (934, 700)); + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400)); + assert_eq!((w, h), (534, 400)); + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500)); + assert_eq!((w, h), (666, 500)); + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750)); + assert_eq!((w, h), (1000, 750)); + + // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward + let (_, w, h) = h264_scale_filter_and_dims(101, 100, None); + assert_eq!((w, h), (100, 100)); + } + + #[test] + fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-video-cancel-final-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let comp_src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 2 }, + GlobalRange = { 0, 2 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 36, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftAlpha = Input { Value = 1, }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, +}"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let target = comp.find_node("BG").expect("find BG"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + let out_mp4 = tmp_dir.join("final_cancel.mp4"); + let control = ExportControl::new(); + let ctrl_cb = control.clone(); + + let err = export_node_video_ffmpeg_with_progress( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: out_mp4.clone(), + range: [0, 2], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + Some(&control), + |p| { + if p.completed_frames == p.total_frames { + ctrl_cb.cancel(); + } + }, + ) + .expect_err("cancelling on final frame callback must return Cancelled"); + assert_eq!(err, "Cancelled"); + assert!(!out_mp4.exists(), "cancelled export must not publish output file"); + + let _ = std::fs::remove_dir_all(&tmp_dir); + } } diff --git a/crates/model/src/comp/save.rs b/crates/model/src/comp/save.rs index 57a526ba45bc9a32d8528a44b7792488e4422fae..73cfb0abf5e9561fa677d37601cd9ef9735c5cc4 100644 --- a/crates/model/src/comp/save.rs +++ b/crates/model/src/comp/save.rs @@ -325,10 +325,35 @@ impl Comp { if has_call_args(root) { return None; } + let mut seen_special_root_keys = 0u8; + for (k, _) in &root.entries { + if let LuaKey::Str(name) = k { + let bit = match name.as_str() { + "CurrentTime" => 1 << 0, + "GlobalRange" => 1 << 1, + "RenderRange" => 1 << 2, + "AudioFilename" => 1 << 3, + "AudioOffset" => 1 << 4, + "Prefs" => 1 << 5, + "Tools" => 1 << 6, + "FrameFormat" => 1 << 7, + _ => 0, + }; + if bit != 0 { + if (seen_special_root_keys & bit) != 0 { + return None; + } + seen_special_root_keys |= bit; + } + } + } let tools = root.get_table("Tools")?; if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4) || has_call_args(tools) - || !tools.entries.iter().all(|(k, _)| matches!(k, LuaKey::Str(_))) + || !tools + .entries + .iter() + .all(|(k, v)| matches!(k, LuaKey::Str(_)) && v.as_table().is_some()) { return None; } @@ -447,13 +472,15 @@ impl Comp { seen_tools = true; write_indent(&mut out, 1); write_entry_key(k, positional, &mut out); - self.write_tools_streaming( + if !self.write_tools_streaming( tools, &mut top_pool, &mut inner_pool, &instance_defaults, &mut out, - ); + ) { + return None; + } out.push_str(",\n"); continue; } @@ -553,7 +580,7 @@ impl Comp { inner_pool: &mut HashMap<&'a str, NodePool<'a>>, instance_defaults: &HashMap<(&str, &str), ParamValue>, out: &mut String, - ) { + ) -> bool { let mut remaining_splines: HashMap<&str, &BezierSpline> = self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect(); @@ -572,6 +599,7 @@ impl Comp { } let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len()); + let mut emitted_entries: usize = 0; write_table_prefix(tools.tag.as_deref(), &[], 1, out); out.push_str("{\n"); @@ -582,6 +610,7 @@ impl Comp { write_entry_key(k, true, out); write_value(v, 2, out); out.push_str(",\n"); + emitted_entries += 1; continue; }; let Some(tbl) = v.as_table() else { @@ -590,6 +619,7 @@ impl Comp { write_entry_key(k, true, out); write_value(v, 2, out); out.push_str(",\n"); + emitted_entries += 1; continue; }; @@ -610,6 +640,7 @@ impl Comp { write_table(tbl, 2, out); } out.push_str(",\n"); + emitted_entries += 1; continue; } @@ -673,6 +704,7 @@ impl Comp { write_table(&cloned, 2, out); } out.push_str(",\n"); + emitted_entries += 1; } // Newly added top-level nodes not yet present in `tools` @@ -712,6 +744,7 @@ impl Comp { write_entry_key(&LuaKey::Str(node.name.clone()), true, out); write_table(&new_tbl, 2, out); out.push_str(",\n"); + emitted_entries += 1; } // Newly added splines not yet present in `tools` @@ -736,11 +769,17 @@ impl Comp { write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out); write_table(&sp_tbl, 2, out); out.push_str(",\n"); + emitted_entries += 1; } } + if emitted_entries == 0 || (tools.tag.as_deref() != Some("ordered") && emitted_entries <= 4) { + return false; + } + write_indent(out, 1); out.push('}'); + true } fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool { @@ -824,7 +863,13 @@ impl Comp { return false; } if let Some(inner) = tool_tbl.get_table("Tools") { - if !nested_splines_verbatim(inner, remaining_splines, top_level_spline_names) { + let mut claimed_splines: HashSet<&str> = HashSet::new(); + if !nested_splines_verbatim( + inner, + remaining_splines, + top_level_spline_names, + &mut claimed_splines, + ) { return false; } consume_nested_splines(inner, remaining_splines, top_level_spline_names); @@ -851,6 +896,7 @@ impl Comp { return true; }; let mut peek_offsets: HashMap<&str, usize> = HashMap::new(); + let mut claimed_splines: HashSet<&str> = HashSet::new(); if !self.check_inner_tools_verbatim( inner_tools, inner_pool, @@ -858,6 +904,7 @@ impl Comp { instance_defaults, remaining_splines, top_level_spline_names, + &mut claimed_splines, ) { return false; } @@ -879,17 +926,39 @@ impl Comp { instance_defaults: &HashMap<(&str, &str), ParamValue>, remaining_splines: &HashMap<&'a str, &'a BezierSpline>, top_level_spline_names: &HashSet<&str>, + claimed_splines: &mut HashSet<&'b str>, ) -> bool { - // Check modifiers at this level first (matching `sync_existing_splines_in_tools` top-down order). - for (k, v) in &inner_tools.entries { - let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; - let tag = tbl.tag.as_deref().unwrap_or("Unknown"); - if is_modifier_type(tag) { - if !top_level_spline_names.contains(name.as_str()) { + // Pass 1: check direct entries at this `inner_tools` level BEFORE recursing into + // nested `.Tools` tables (matching `sync_existing_splines_in_tools` top-down order). + if !remaining_splines.is_empty() { + for (k, v) in &inner_tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !top_level_spline_names.contains(name.as_str()) + && !claimed_splines.contains(name.as_str()) + { if let Some(&spline) = remaining_splines.get(name.as_str()) { if spline_needs_sync(name, spline, tbl) { return false; } + claimed_splines.insert(name.as_str()); + } + } + } + } + + // Pass 2: validate flow nodes and recurse into nested `.Tools` tables. + for (k, v) in &inner_tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + let tag = tbl.tag.as_deref().unwrap_or("Unknown"); + if is_modifier_type(tag) { + if let Some(sub_tools) = tbl.get_table("Tools") { + if !nested_splines_verbatim( + sub_tools, + remaining_splines, + top_level_spline_names, + claimed_splines, + ) { + return false; } } continue; @@ -914,6 +983,7 @@ impl Comp { instance_defaults, remaining_splines, top_level_spline_names, + claimed_splines, ) { return false; } @@ -937,7 +1007,12 @@ impl Comp { return false; } if let Some(sub_tools) = tbl.get_table("Tools") { - if !nested_splines_verbatim(sub_tools, remaining_splines, top_level_spline_names) { + if !nested_splines_verbatim( + sub_tools, + remaining_splines, + top_level_spline_names, + claimed_splines, + ) { return false; } } @@ -1037,12 +1112,26 @@ fn commit_inner_tools_verbatim<'a>( remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>, top_level_spline_names: &HashSet<&str>, ) { + // Pass 1: consume direct entries at this level BEFORE recursing into nested `.Tools` + // (matching `sync_existing_splines_in_tools` top-down order). + if !remaining_splines.is_empty() { + for (k, v) in &inner_tools.entries { + let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue }; + if !top_level_spline_names.contains(name.as_str()) { + remaining_splines.remove(name.as_str()); + if remaining_splines.is_empty() { + break; + } + } + } + } + // Pass 2: pop inner flow nodes and recurse into nested `.Tools`. for (k, v) in &inner_tools.entries { let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; let tag = tbl.tag.as_deref().unwrap_or("Unknown"); if is_modifier_type(tag) { - if !top_level_spline_names.contains(name.as_str()) { - remaining_splines.remove(name.as_str()); + if let Some(sub_tools) = tbl.get_table("Tools") { + consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names); } continue; } @@ -1057,25 +1146,36 @@ fn commit_inner_tools_verbatim<'a>( } } -fn nested_splines_verbatim( - tools: &LuaTable, - remaining_splines: &HashMap<&str, &BezierSpline>, +fn nested_splines_verbatim<'a, 'b>( + tools: &'b LuaTable, + remaining_splines: &HashMap<&'a str, &'a BezierSpline>, top_level_spline_names: &HashSet<&str>, + claimed_splines: &mut HashSet<&'b str>, ) -> bool { if remaining_splines.is_empty() { return true; } for (k, v) in &tools.entries { let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; - if !top_level_spline_names.contains(name.as_str()) { + if !top_level_spline_names.contains(name.as_str()) + && !claimed_splines.contains(name.as_str()) + { if let Some(&spline) = remaining_splines.get(name.as_str()) { if spline_needs_sync(name, spline, tbl) { return false; } + claimed_splines.insert(name.as_str()); } } - if let Some(sub) = tbl.get_table("Tools") { - if !nested_splines_verbatim(sub, remaining_splines, top_level_spline_names) { + } + for (_, v) in &tools.entries { + if let Some(sub) = v.as_table().and_then(|t| t.get_table("Tools")) { + if !nested_splines_verbatim( + sub, + remaining_splines, + top_level_spline_names, + claimed_splines, + ) { return false; } } @@ -1092,12 +1192,20 @@ fn consume_nested_splines( return; } for (k, v) in &tools.entries { - let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue }; if !top_level_spline_names.contains(name.as_str()) { remaining_splines.remove(name.as_str()); + if remaining_splines.is_empty() { + return; + } } - if let Some(sub) = tbl.get_table("Tools") { + } + for (_, v) in &tools.entries { + if let Some(sub) = v.as_table().and_then(|t| t.get_table("Tools")) { consume_nested_splines(sub, remaining_splines, top_level_spline_names); + if remaining_splines.is_empty() { + return; + } } } } @@ -1947,4 +2055,201 @@ mod tests { assert_eq!(in_b.connected_node("Input"), None); assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#)); } + + fn ast_fusion_string(comp: &Comp) -> String { + let mut s = comp.sync_to_raw_ast().to_fusion_string(); + if !s.ends_with('\n') { + s.push('\n'); + } + s + } + + #[test] + fn streaming_matches_ast_for_same_named_nested_splines() { + let src = r#"Composition { + Tools = ordered() { + Outer = GroupOperator { + Tools = ordered() { + Inner = GroupOperator { + Tools = ordered() { + SharedSpline = BezierSpline { + SplineColor = { Red = 255, Green = 0, Blue = 0 }, + KeyFrames = { + [0] = { 0.1 }, + [10] = { 0.2 }, + }, + }, + InnerBG = Background {}, + }, + }, + SharedSpline = BezierSpline { + SplineColor = { Red = 0, Green = 255, Blue = 0 }, + KeyFrames = { + [0] = { 0.5 }, + [10] = { 1.0 }, + }, + }, + }, + }, + }, + }"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + + // Case 1: active spline matches Outer.Tools.SharedSpline while Inner.Tools.SharedSpline differs. + { + let sp = comp.splines.get_mut("SharedSpline").expect("SharedSpline loaded"); + sp.color = [0, 255, 0]; + sp.keyframes[0].time = 0.0; + sp.keyframes[0].value = 0.5; + sp.keyframes[1].time = 10.0; + sp.keyframes[1].value = 1.0; + } + assert!(comp.try_to_fusion_string_streaming().is_some()); + assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp)); + + // Case 2: active spline matches Inner.Tools.SharedSpline (differs from Outer.Tools.SharedSpline). + // `sync_existing_splines_in_tools` updates Outer.Tools.SharedSpline first and leaves Inner untouched. + { + let sp = comp.splines.get_mut("SharedSpline").unwrap(); + sp.color = [255, 0, 0]; + sp.keyframes[0].value = 0.1; + sp.keyframes[1].value = 0.2; + } + assert!(comp.try_to_fusion_string_streaming().is_some()); + assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp)); + + // Case 3: active spline edited to a brand-new value. + { + let sp = comp.splines.get_mut("SharedSpline").unwrap(); + sp.keyframes[0].value = 0.75; + } + assert!(comp.try_to_fusion_string_streaming().is_some()); + assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp)); + } + + #[test] + fn streaming_bails_and_matches_ast_when_all_nodes_deleted() { + let src = r#"Composition { + Tools = ordered() { + A = Blur {}, + B = Blur {}, + }, + }"#; + // Path 1: deleted via `delete_nodes` + let mut comp = Comp::from_fusion_str(src).unwrap(); + let a = comp.find_node("A").unwrap(); + let b = comp.find_node("B").unwrap(); + comp.delete_nodes(&[a, b]); + assert!(comp.try_to_fusion_string_streaming().is_none()); + let saved = comp.to_fusion_string(); + assert_eq!(saved, ast_fusion_string(&comp)); + assert!(saved.contains("Tools = ordered() {},")); + + // Path 2: `raw_root.Tools` still has entries, but all flow nodes removed from `comp.nodes` + let mut comp2 = Comp::from_fusion_str(src).unwrap(); + comp2.nodes.clear(); + comp2.node_by_name.clear(); + assert!(comp2.try_to_fusion_string_streaming().is_none()); + let saved2 = comp2.to_fusion_string(); + assert_eq!(saved2, ast_fusion_string(&comp2)); + assert!(saved2.contains("Tools = ordered() {},")); + } + + #[test] + fn streaming_bails_and_matches_ast_for_non_table_entry_in_tools() { + let src = r#"Composition { + Tools = ordered() { + Foo = "not_a_table", + BG = Background {}, + }, + }"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + // Add a flow node named "Foo" without mutating `raw_root.Tools`, so `raw_root.Tools` + // retains the colliding non-table `Foo = "not_a_table"` entry. + let id = super::super::NodeId(comp.nodes.len()); + comp.nodes.push(Node { + id, + name: "Foo".to_owned(), + kind: "Blur".to_owned(), + pos: [10.0, 20.0], + bypassed: false, + internal: false, + macro_output: None, + inputs: HashMap::new(), + clips: Vec::new(), + raw: LuaTable::default(), + }); + comp.node_by_name.insert("Foo".to_owned(), id); + + assert!(comp.try_to_fusion_string_streaming().is_none()); + let saved = comp.to_fusion_string(); + assert_eq!(saved, ast_fusion_string(&comp)); + assert!(saved.contains("Foo = Blur {")); + assert!(!saved.contains("not_a_table")); + } + + #[test] + fn streaming_bails_and_matches_ast_for_duplicate_root_and_tools_keys() { + let dup_root_src = r#"Composition { + CurrentTime = 5, + CurrentTime = 99, + RenderRange = { 0, 10 }, + RenderRange = { 5, 25 }, + Tools = ordered() { + BG = Background {}, + }, + }"#; + let mut comp = Comp::from_fusion_str(dup_root_src).unwrap(); + comp.current_time = 12.0; + assert!(comp.try_to_fusion_string_streaming().is_none()); + assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp)); + + let dup_tools_src = r#"Composition { + CurrentTime = 0, + Tools = ordered() { + BG = Background {}, + }, + Tools = ordered() { + Shadowed = Blur {}, + }, + }"#; + let comp2 = Comp::from_fusion_str(dup_tools_src).unwrap(); + assert!(comp2.try_to_fusion_string_streaming().is_none()); + assert_eq!(comp2.to_fusion_string(), ast_fusion_string(&comp2)); + } + + #[test] + fn streaming_bails_and_matches_ast_when_untagged_tools_shrinks_to_four_or_fewer() { + let src = r#"Composition { + Tools = { + A = Blur {}, + B = Blur {}, + C = Blur {}, + D = Blur {}, + E = Blur {}, + }, + }"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + // With 5 entries, streaming can run. + assert!(comp.try_to_fusion_string_streaming().is_some()); + assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp)); + + // Remove 3 nodes from `comp.nodes` while `raw_root.Tools` still holds 5 entries, so + // post-edit untagged `Tools` shrinks from 5 -> 2 (<= 4, eligible for inline formatting). + comp.nodes.retain(|n| n.name == "A" || n.name == "B"); + comp.node_by_name.retain(|name, _| name == "A" || name == "B"); + assert!(comp.try_to_fusion_string_streaming().is_none()); + let saved = comp.to_fusion_string(); + assert_eq!(saved, ast_fusion_string(&comp)); + assert!(saved.contains("Tools = { A = Blur {}, B = Blur {} },")); + + // Also verify via `delete_nodes`. + let mut comp2 = Comp::from_fusion_str(src).unwrap(); + let ids: Vec<_> = ["C", "D", "E"].iter().map(|n| comp2.find_node(n).unwrap()).collect(); + comp2.delete_nodes(&ids); + assert!(comp2.try_to_fusion_string_streaming().is_none()); + let saved2 = comp2.to_fusion_string(); + assert_eq!(saved2, ast_fusion_string(&comp2)); + assert!(saved2.contains("Tools = { A = Blur {}, B = Blur {} },")); + } } diff --git a/crates/model/src/lua_value.rs b/crates/model/src/lua_value.rs index 36e09ee7ed6dd011aa59e7cdf4ad501f9d48061b..e9ecbeb5a7366ee68bd26550482642e7a6681a9b 100644 --- a/crates/model/src/lua_value.rs +++ b/crates/model/src/lua_value.rs @@ -254,7 +254,7 @@ impl<'a> Parser<'a> { if p < len && src[p] == b'[' { self.pos = p; if let Some(level) = self.try_open_long_bracket() { - self.skip_long_bracket(level)?; + self.skip_long_bracket_discard(level)?; p = self.pos; continue; } @@ -291,7 +291,7 @@ impl<'a> Parser<'a> { } } - fn skip_long_bracket(&mut self, level: usize) -> Result { + fn skip_long_bracket_range(&mut self, level: usize) -> Result<(usize, usize), ParseError> { let start = self.pos; let src = self.src; let len = src.len(); @@ -305,13 +305,8 @@ impl<'a> Parser<'a> { eq += 1; } if eq == level && i < len && src[i] == b']' { - let slice = &src[start..close_start]; - let s = match std::str::from_utf8(slice) { - Ok(v) => v.to_owned(), - Err(_) => String::from_utf8_lossy(slice).into_owned(), - }; self.pos = i + 1; - return Ok(s); + return Ok((start, close_start)); } p = close_start + 1; } @@ -319,6 +314,19 @@ impl<'a> Parser<'a> { Err(self.err("unterminated long bracket string/comment")) } + fn skip_long_bracket_discard(&mut self, level: usize) -> Result<(), ParseError> { + self.skip_long_bracket_range(level).map(|_| ()) + } + + fn skip_long_bracket(&mut self, level: usize) -> Result { + let (start, close_start) = self.skip_long_bracket_range(level)?; + let slice = &self.src[start..close_start]; + Ok(match std::str::from_utf8(slice) { + Ok(v) => v.to_owned(), + Err(_) => String::from_utf8_lossy(slice).into_owned(), + }) + } + fn parse_value(&mut self) -> Result { self.skip_ws_and_comments()?; let Some(b) = self.peek() else { @@ -1101,3 +1109,27 @@ pub(crate) fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out); write_table_body(tbl, body.into_iter(), depth, out); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn skips_long_bracket_block_comments_without_corrupting_parse() { + let src = r#" + --[[ simple block comment + spanning multiple lines ]] + Composition { + --[=[ leveled comment with ]] inside ]=] + CurrentTime = --[==[ nested ]=] still comment ]==] 42, + Name = [=[kept long string]=], + } + "#; + let val = parse_lua(src).expect("parse with long block comments"); + let tbl = val.as_table().expect("root table"); + assert_eq!(tbl.get_f64("CurrentTime"), Some(42.0)); + assert_eq!(tbl.get_str("Name"), Some("kept long string")); + + assert!(parse_lua("--[=[ unterminated comment\n{}").is_err()); + } +} -- 2.54.1