authoravatarclover caruso<git@paperclover.net>2026-12-01 17:05:07-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 17:13:06-08:00
logf060ca793fdbbd56f6255bc20980ce9a90af94bd
treef54c09c369716c6117b3379d23c52fe7f4ee9f4b
parenta791d487f17137e2647e72ee5a0841e504575f7c
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Wave 29B: harden VideoToolbox export cancellation/fallback and fix streaming comp saver edge cases


3 files changed, 524 insertions(+), 71 deletions(-)

crates/engine/src/export.rs+157-41
......@@ -928,6 +928,18 @@ impl VideoExportError {
928928 }
929929}
930930
931fn h264_scale_filter_and_dims(width: u32, height: u32, max_height: Option<u32>) -> (String, u32, u32) {
932 if let Some(max_h) = max_height.filter(|&h| h >= 2) {
933 let oh = (height.min(max_h) & !1).max(2);
934 let ow = ((((width as f64) * (oh as f64) / (height as f64)) / 2.0).round() as u32 * 2).max(2);
935 (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh)
936 } else {
937 let ow = (width & !1).max(2);
938 let oh = (height & !1).max(2);
939 ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh)
940 }
941}
942
931943/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
932944/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.
933945pub fn export_node_video_ffmpeg_with_progress(
......@@ -962,6 +974,7 @@ pub fn export_node_video_ffmpeg_with_progress(
962974 engine.hiq = opts.hiq;
963975 engine.proxy_scale = opts.proxy_scale.max(1);
964976
977 let started_at = Instant::now();
965978 let vt = probe_videotoolbox_support();
966979 let encoder = select_video_encoder(opts.codec, vt, true);
967980 let res = match export_node_video_ffmpeg_with_encoder(
......@@ -971,19 +984,25 @@ pub fn export_node_video_ffmpeg_with_progress(
971984 control,
972985 &mut on_progress,
973986 encoder,
987 started_at,
974988 ) {
975989 Ok(summary) => Ok(summary),
976990 Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => {
977 let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false);
978 export_node_video_ffmpeg_with_encoder(
979 engine,
980 comp,
981 opts,
982 control,
983 &mut on_progress,
984 fallback,
985 )
986 .map_err(VideoExportError::into_string)
991 if control.is_some_and(ExportControl::is_cancelled) {
992 Err("Cancelled".to_owned())
993 } else {
994 let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false);
995 export_node_video_ffmpeg_with_encoder(
996 engine,
997 comp,
998 opts,
999 control,
1000 &mut on_progress,
1001 fallback,
1002 started_at,
1003 )
1004 .map_err(VideoExportError::into_string)
1005 }
9871006 }
9881007 Err(err) => Err(err.into_string()),
9891008 };
......@@ -1000,9 +1019,9 @@ fn export_node_video_ffmpeg_with_encoder(
10001019 control: Option<&ExportControl>,
10011020 on_progress: &mut impl FnMut(ExportProgress),
10021021 encoder: VideoEncoder,
1022 started_at: Instant,
10031023) -> Result<VideoExportSummary, VideoExportError> {
10041024 let [start, end] = opts.range;
1005 let t0 = Instant::now();
10061025 let total = (end - start + 1) as usize;
10071026 let fps = comp.fps.max(1.0);
10081027 let node_name = comp.node(opts.target).name.clone();
......@@ -1096,20 +1115,7 @@ fn export_node_video_ffmpeg_with_encoder(
10961115
10971116 let (out_width, out_height) = match opts.codec {
10981117 VideoCodec::H264Share => {
1099 let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) {
1100 let oh = (height.min(max_h) & !1).max(2);
1101 let ow = if height > max_h {
1102 let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32;
1103 (scaled & !1).max(2)
1104 } else {
1105 (width & !1).max(2)
1106 };
1107 (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh)
1108 } else {
1109 let ow = (width & !1).max(2);
1110 let oh = (height & !1).max(2);
1111 ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh)
1112 };
1118 let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height);
11131119 let mut encoder_args = Vec::new();
11141120 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf));
11151121 cmd.args(&encoder_args);
......@@ -1145,7 +1151,7 @@ fn export_node_video_ffmpeg_with_encoder(
11451151 .stderr(Stdio::piped());
11461152
11471153 let mut child = cmd.spawn().map_err(|e| {
1148 VideoExportError::EncoderFailed(format!(
1154 VideoExportError::Fatal(format!(
11491155 "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"
11501156 ))
11511157 })?;
......@@ -1164,10 +1170,15 @@ fn export_node_video_ffmpeg_with_encoder(
11641170 let mut cancelled = false;
11651171 let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
11661172 let writer_failed = Arc::new(AtomicBool::new(false));
1167 let stdin = child
1168 .stdin
1169 .take()
1170 .ok_or_else(|| VideoExportError::EncoderFailed("failed to open ffmpeg stdin".to_owned()))?;
1173 let writer_fatal = Arc::new(AtomicBool::new(false));
1174 let Some(stdin) = child.stdin.take() else {
1175 let _ = child.kill();
1176 let _ = child.wait();
1177 let _ = stderr_thread.join();
1178 return Err(VideoExportError::Fatal(
1179 "failed to open ffmpeg stdin".to_owned(),
1180 ));
1181 };
11711182
11721183 let frame_bytes_len = (width as usize)
11731184 .saturating_mul(height as usize)
......@@ -1178,6 +1189,7 @@ fn export_node_video_ffmpeg_with_encoder(
11781189 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + 2);
11791190 let writer_err_c = Arc::clone(&writer_err);
11801191 let writer_failed_c = Arc::clone(&writer_failed);
1192 let writer_fatal_c = Arc::clone(&writer_fatal);
11811193 let dst_size = [width, height];
11821194 let writer_thread = std::thread::spawn(move || {
11831195 let mut stdin = stdin;
......@@ -1190,6 +1202,7 @@ fn export_node_video_ffmpeg_with_encoder(
11901202 *g = Some(e);
11911203 }
11921204 }
1205 writer_fatal_c.store(true, Ordering::Release);
11931206 writer_failed_c.store(true, Ordering::Release);
11941207 break;
11951208 }
......@@ -1223,7 +1236,7 @@ fn export_node_video_ffmpeg_with_encoder(
12231236 first_stats.eval_ms,
12241237 opts.out_path.clone(),
12251238 node_name.clone(),
1226 t0,
1239 started_at,
12271240 );
12281241 if let Some(ctrl) = control {
12291242 ctrl.update_progress(&first_prog);
......@@ -1247,13 +1260,13 @@ fn export_node_video_ffmpeg_with_encoder(
12471260 }
12481261 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
12491262 for (idx, frame) in ((start + 1)..=end).enumerate() {
1250 if writer_failed.load(Ordering::Acquire) {
1251 break;
1252 }
12531263 if control.is_some_and(ExportControl::is_cancelled) {
12541264 cancelled = true;
12551265 break;
12561266 }
1267 if writer_failed.load(Ordering::Acquire) {
1268 break;
1269 }
12571270 prefetch.set_current_seq(idx);
12581271 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;
12591272 if ahead_frame <= end {
......@@ -1297,7 +1310,7 @@ fn export_node_video_ffmpeg_with_encoder(
12971310 prev_ms,
12981311 opts.out_path.clone(),
12991312 node_name.clone(),
1300 t0,
1313 started_at,
13011314 );
13021315 if let Some(ctrl) = control {
13031316 ctrl.update_progress(&prog);
......@@ -1305,6 +1318,9 @@ fn export_node_video_ffmpeg_with_encoder(
13051318 on_progress(prog);
13061319 }
13071320 }
1321 if control.is_some_and(ExportControl::is_cancelled) {
1322 cancelled = true;
1323 }
13081324 if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {
13091325 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {
13101326 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
......@@ -1320,12 +1336,15 @@ fn export_node_video_ffmpeg_with_encoder(
13201336 prev_ms,
13211337 opts.out_path.clone(),
13221338 node_name.clone(),
1323 t0,
1339 started_at,
13241340 );
13251341 if let Some(ctrl) = control {
13261342 ctrl.update_progress(&prog);
13271343 }
13281344 on_progress(prog);
1345 if control.is_some_and(ExportControl::is_cancelled) {
1346 cancelled = true;
1347 }
13291348 }
13301349 }
13311350 Err(e) => {
......@@ -1340,6 +1359,9 @@ fn export_node_video_ffmpeg_with_encoder(
13401359 }
13411360 drop(tx);
13421361
1362 if control.is_some_and(ExportControl::is_cancelled) {
1363 cancelled = true;
1364 }
13431365 if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) {
13441366 // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately.
13451367 let _ = child.kill();
......@@ -1353,26 +1375,33 @@ fn export_node_video_ffmpeg_with_encoder(
13531375 if pipe_err.is_some() && !cancelled {
13541376 let _ = child.kill();
13551377 }
1356 let status = child
1357 .wait()
1358 .map_err(|e| VideoExportError::EncoderFailed(format!("failed waiting on ffmpeg: {e}")))?;
1378 let wait_res = child.wait();
13591379 let stderr_text = stderr_thread.join().unwrap_or_default();
13601380 let stderr_trim = stderr_text.trim();
13611381
1362 if cancelled {
1382 if cancelled || control.is_some_and(ExportControl::is_cancelled) {
13631383 return Err(VideoExportError::Cancelled);
13641384 }
13651385 if let Some(err) = readback_err {
13661386 return Err(VideoExportError::Fatal(err));
13671387 }
13681388 if let Some(err) = pipe_err {
1389 if writer_fatal.load(Ordering::Acquire) {
1390 return Err(VideoExportError::Fatal(err));
1391 }
13691392 return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() {
13701393 format!("{err} (ffmpeg: {stderr_trim})")
13711394 } else {
13721395 err
13731396 }));
13741397 }
1398 let status = wait_res.map_err(|e| {
1399 VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}"))
1400 })?;
13751401 if !status.success() {
1402 if control.is_some_and(ExportControl::is_cancelled) {
1403 return Err(VideoExportError::Cancelled);
1404 }
13761405 return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() {
13771406 format!("ffmpeg exited with {status}")
13781407 } else {
......@@ -1395,7 +1424,7 @@ fn export_node_video_ffmpeg_with_encoder(
13951424 width: out_width,
13961425 height: out_height,
13971426 has_audio,
1398 total_ms: t0.elapsed().as_secs_f64() * 1000.0,
1427 total_ms: started_at.elapsed().as_secs_f64() * 1000.0,
13991428 file_bytes,
14001429 })
14011430}
......@@ -2440,6 +2469,7 @@ Encoders:
24402469 None,
24412470 &mut noop,
24422471 VideoEncoder::Libx264,
2472 Instant::now(),
24432473 )
24442474 .expect("software libx264 fallback export");
24452475 assert_eq!(sw_summary.frames_written, 3);
......@@ -2463,6 +2493,7 @@ Encoders:
24632493 None,
24642494 &mut noop,
24652495 VideoEncoder::ProResKs422,
2496 Instant::now(),
24662497 )
24672498 .expect("software prores_ks fallback export");
24682499 assert_eq!(sw_prores.frames_written, 3);
......@@ -2470,4 +2501,89 @@ Encoders:
24702501
24712502 let _ = std::fs::remove_dir_all(&tmp_dir);
24722503 }
2504
2505 #[test]
2506 fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() {
2507 // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102
2508 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100));
2509 assert_eq!((w, h), (102, 100));
2510 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200));
2511 assert_eq!((w, h), (102, 100));
2512 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50));
2513 assert_eq!((w, h), (50, 50));
2514
2515 // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666
2516 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700));
2517 assert_eq!((w, h), (934, 700));
2518 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400));
2519 assert_eq!((w, h), (534, 400));
2520 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500));
2521 assert_eq!((w, h), (666, 500));
2522 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750));
2523 assert_eq!((w, h), (1000, 750));
2524
2525 // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward
2526 let (_, w, h) = h264_scale_filter_and_dims(101, 100, None);
2527 assert_eq!((w, h), (100, 100));
2528 }
2529
2530 #[test]
2531 fn video_export_cancel_on_final_frame_progress_cancels_cleanly() {
2532 let tmp_dir = std::env::temp_dir().join(format!(
2533 "fission-video-cancel-final-{}",
2534 std::process::id()
2535 ));
2536 let _ = std::fs::remove_dir_all(&tmp_dir);
2537 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
2538
2539 let comp_src = r#"Composition {
2540 CurrentTime = 0,
2541 RenderRange = { 0, 2 },
2542 GlobalRange = { 0, 2 },
2543 Tools = ordered() {
2544 BG = Background {
2545 Inputs = {
2546 Width = Input { Value = 64, },
2547 Height = Input { Value = 36, },
2548 TopLeftRed = Input { Value = 0.5, },
2549 TopLeftAlpha = Input { Value = 1, },
2550 },
2551 },
2552 },
2553 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
2554}"#;
2555 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
2556 let target = comp.find_node("BG").expect("find BG");
2557 let mut engine = Engine::new_headless().expect("headless wgpu engine");
2558 let out_mp4 = tmp_dir.join("final_cancel.mp4");
2559 let control = ExportControl::new();
2560 let ctrl_cb = control.clone();
2561
2562 let err = export_node_video_ffmpeg_with_progress(
2563 &mut engine,
2564 &comp,
2565 &VideoExportOptions {
2566 target,
2567 out_path: out_mp4.clone(),
2568 range: [0, 2],
2569 codec: VideoCodec::H264Share,
2570 crf: 26,
2571 max_height: None,
2572 include_audio: false,
2573 hiq: true,
2574 proxy_scale: 1,
2575 },
2576 Some(&control),
2577 |p| {
2578 if p.completed_frames == p.total_frames {
2579 ctrl_cb.cancel();
2580 }
2581 },
2582 )
2583 .expect_err("cancelling on final frame callback must return Cancelled");
2584 assert_eq!(err, "Cancelled");
2585 assert!(!out_mp4.exists(), "cancelled export must not publish output file");
2586
2587 let _ = std::fs::remove_dir_all(&tmp_dir);
2588 }
24732589}
crates/model/src/comp/save.rs+327-22
......@@ -325,10 +325,35 @@ impl Comp {
325325 if has_call_args(root) {
326326 return None;
327327 }
328 let mut seen_special_root_keys = 0u8;
329 for (k, _) in &root.entries {
330 if let LuaKey::Str(name) = k {
331 let bit = match name.as_str() {
332 "CurrentTime" => 1 << 0,
333 "GlobalRange" => 1 << 1,
334 "RenderRange" => 1 << 2,
335 "AudioFilename" => 1 << 3,
336 "AudioOffset" => 1 << 4,
337 "Prefs" => 1 << 5,
338 "Tools" => 1 << 6,
339 "FrameFormat" => 1 << 7,
340 _ => 0,
341 };
342 if bit != 0 {
343 if (seen_special_root_keys & bit) != 0 {
344 return None;
345 }
346 seen_special_root_keys |= bit;
347 }
348 }
349 }
328350 let tools = root.get_table("Tools")?;
329351 if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4)
330352 || has_call_args(tools)
331 || !tools.entries.iter().all(|(k, _)| matches!(k, LuaKey::Str(_)))
353 || !tools
354 .entries
355 .iter()
356 .all(|(k, v)| matches!(k, LuaKey::Str(_)) && v.as_table().is_some())
332357 {
333358 return None;
334359 }
......@@ -447,13 +472,15 @@ impl Comp {
447472 seen_tools = true;
448473 write_indent(&mut out, 1);
449474 write_entry_key(k, positional, &mut out);
450 self.write_tools_streaming(
475 if !self.write_tools_streaming(
451476 tools,
452477 &mut top_pool,
453478 &mut inner_pool,
454479 &instance_defaults,
455480 &mut out,
456 );
481 ) {
482 return None;
483 }
457484 out.push_str(",\n");
458485 continue;
459486 }
......@@ -553,7 +580,7 @@ impl Comp {
553580 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
554581 instance_defaults: &HashMap<(&str, &str), ParamValue>,
555582 out: &mut String,
556 ) {
583 ) -> bool {
557584 let mut remaining_splines: HashMap<&str, &BezierSpline> =
558585 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();
559586
......@@ -572,6 +599,7 @@ impl Comp {
572599 }
573600
574601 let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len());
602 let mut emitted_entries: usize = 0;
575603
576604 write_table_prefix(tools.tag.as_deref(), &[], 1, out);
577605 out.push_str("{\n");
......@@ -582,6 +610,7 @@ impl Comp {
582610 write_entry_key(k, true, out);
583611 write_value(v, 2, out);
584612 out.push_str(",\n");
613 emitted_entries += 1;
585614 continue;
586615 };
587616 let Some(tbl) = v.as_table() else {
......@@ -590,6 +619,7 @@ impl Comp {
590619 write_entry_key(k, true, out);
591620 write_value(v, 2, out);
592621 out.push_str(",\n");
622 emitted_entries += 1;
593623 continue;
594624 };
595625
......@@ -610,6 +640,7 @@ impl Comp {
610640 write_table(tbl, 2, out);
611641 }
612642 out.push_str(",\n");
643 emitted_entries += 1;
613644 continue;
614645 }
615646
......@@ -673,6 +704,7 @@ impl Comp {
673704 write_table(&cloned, 2, out);
674705 }
675706 out.push_str(",\n");
707 emitted_entries += 1;
676708 }
677709
678710 // Newly added top-level nodes not yet present in `tools`
......@@ -712,6 +744,7 @@ impl Comp {
712744 write_entry_key(&LuaKey::Str(node.name.clone()), true, out);
713745 write_table(&new_tbl, 2, out);
714746 out.push_str(",\n");
747 emitted_entries += 1;
715748 }
716749
717750 // Newly added splines not yet present in `tools`
......@@ -736,11 +769,17 @@ impl Comp {
736769 write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out);
737770 write_table(&sp_tbl, 2, out);
738771 out.push_str(",\n");
772 emitted_entries += 1;
739773 }
740774 }
741775
776 if emitted_entries == 0 || (tools.tag.as_deref() != Some("ordered") && emitted_entries <= 4) {
777 return false;
778 }
779
742780 write_indent(out, 1);
743781 out.push('}');
782 true
744783 }
745784
746785 fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool {
......@@ -824,7 +863,13 @@ impl Comp {
824863 return false;
825864 }
826865 if let Some(inner) = tool_tbl.get_table("Tools") {
827 if !nested_splines_verbatim(inner, remaining_splines, top_level_spline_names) {
866 let mut claimed_splines: HashSet<&str> = HashSet::new();
867 if !nested_splines_verbatim(
868 inner,
869 remaining_splines,
870 top_level_spline_names,
871 &mut claimed_splines,
872 ) {
828873 return false;
829874 }
830875 consume_nested_splines(inner, remaining_splines, top_level_spline_names);
......@@ -851,6 +896,7 @@ impl Comp {
851896 return true;
852897 };
853898 let mut peek_offsets: HashMap<&str, usize> = HashMap::new();
899 let mut claimed_splines: HashSet<&str> = HashSet::new();
854900 if !self.check_inner_tools_verbatim(
855901 inner_tools,
856902 inner_pool,
......@@ -858,6 +904,7 @@ impl Comp {
858904 instance_defaults,
859905 remaining_splines,
860906 top_level_spline_names,
907 &mut claimed_splines,
861908 ) {
862909 return false;
863910 }
......@@ -879,17 +926,39 @@ impl Comp {
879926 instance_defaults: &HashMap<(&str, &str), ParamValue>,
880927 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
881928 top_level_spline_names: &HashSet<&str>,
929 claimed_splines: &mut HashSet<&'b str>,
882930 ) -> bool {
883 // Check modifiers at this level first (matching `sync_existing_splines_in_tools` top-down order).
884 for (k, v) in &inner_tools.entries {
885 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
886 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
887 if is_modifier_type(tag) {
888 if !top_level_spline_names.contains(name.as_str()) {
931 // Pass 1: check direct entries at this `inner_tools` level BEFORE recursing into
932 // nested `.Tools` tables (matching `sync_existing_splines_in_tools` top-down order).
933 if !remaining_splines.is_empty() {
934 for (k, v) in &inner_tools.entries {
935 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
936 if !top_level_spline_names.contains(name.as_str())
937 && !claimed_splines.contains(name.as_str())
938 {
889939 if let Some(&spline) = remaining_splines.get(name.as_str()) {
890940 if spline_needs_sync(name, spline, tbl) {
891941 return false;
892942 }
943 claimed_splines.insert(name.as_str());
944 }
945 }
946 }
947 }
948
949 // Pass 2: validate flow nodes and recurse into nested `.Tools` tables.
950 for (k, v) in &inner_tools.entries {
951 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
952 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
953 if is_modifier_type(tag) {
954 if let Some(sub_tools) = tbl.get_table("Tools") {
955 if !nested_splines_verbatim(
956 sub_tools,
957 remaining_splines,
958 top_level_spline_names,
959 claimed_splines,
960 ) {
961 return false;
893962 }
894963 }
895964 continue;
......@@ -914,6 +983,7 @@ impl Comp {
914983 instance_defaults,
915984 remaining_splines,
916985 top_level_spline_names,
986 claimed_splines,
917987 ) {
918988 return false;
919989 }
......@@ -937,7 +1007,12 @@ impl Comp {
9371007 return false;
9381008 }
9391009 if let Some(sub_tools) = tbl.get_table("Tools") {
940 if !nested_splines_verbatim(sub_tools, remaining_splines, top_level_spline_names) {
1010 if !nested_splines_verbatim(
1011 sub_tools,
1012 remaining_splines,
1013 top_level_spline_names,
1014 claimed_splines,
1015 ) {
9411016 return false;
9421017 }
9431018 }
......@@ -1037,12 +1112,26 @@ fn commit_inner_tools_verbatim<'a>(
10371112 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
10381113 top_level_spline_names: &HashSet<&str>,
10391114) {
1115 // Pass 1: consume direct entries at this level BEFORE recursing into nested `.Tools`
1116 // (matching `sync_existing_splines_in_tools` top-down order).
1117 if !remaining_splines.is_empty() {
1118 for (k, v) in &inner_tools.entries {
1119 let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue };
1120 if !top_level_spline_names.contains(name.as_str()) {
1121 remaining_splines.remove(name.as_str());
1122 if remaining_splines.is_empty() {
1123 break;
1124 }
1125 }
1126 }
1127 }
1128 // Pass 2: pop inner flow nodes and recurse into nested `.Tools`.
10401129 for (k, v) in &inner_tools.entries {
10411130 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
10421131 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
10431132 if is_modifier_type(tag) {
1044 if !top_level_spline_names.contains(name.as_str()) {
1045 remaining_splines.remove(name.as_str());
1133 if let Some(sub_tools) = tbl.get_table("Tools") {
1134 consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names);
10461135 }
10471136 continue;
10481137 }
......@@ -1057,25 +1146,36 @@ fn commit_inner_tools_verbatim<'a>(
10571146 }
10581147}
10591148
1060fn nested_splines_verbatim(
1061 tools: &LuaTable,
1062 remaining_splines: &HashMap<&str, &BezierSpline>,
1149fn nested_splines_verbatim<'a, 'b>(
1150 tools: &'b LuaTable,
1151 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
10631152 top_level_spline_names: &HashSet<&str>,
1153 claimed_splines: &mut HashSet<&'b str>,
10641154) -> bool {
10651155 if remaining_splines.is_empty() {
10661156 return true;
10671157 }
10681158 for (k, v) in &tools.entries {
10691159 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1070 if !top_level_spline_names.contains(name.as_str()) {
1160 if !top_level_spline_names.contains(name.as_str())
1161 && !claimed_splines.contains(name.as_str())
1162 {
10711163 if let Some(&spline) = remaining_splines.get(name.as_str()) {
10721164 if spline_needs_sync(name, spline, tbl) {
10731165 return false;
10741166 }
1167 claimed_splines.insert(name.as_str());
10751168 }
10761169 }
1077 if let Some(sub) = tbl.get_table("Tools") {
1078 if !nested_splines_verbatim(sub, remaining_splines, top_level_spline_names) {
1170 }
1171 for (_, v) in &tools.entries {
1172 if let Some(sub) = v.as_table().and_then(|t| t.get_table("Tools")) {
1173 if !nested_splines_verbatim(
1174 sub,
1175 remaining_splines,
1176 top_level_spline_names,
1177 claimed_splines,
1178 ) {
10791179 return false;
10801180 }
10811181 }
......@@ -1092,12 +1192,20 @@ fn consume_nested_splines(
10921192 return;
10931193 }
10941194 for (k, v) in &tools.entries {
1095 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1195 let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue };
10961196 if !top_level_spline_names.contains(name.as_str()) {
10971197 remaining_splines.remove(name.as_str());
1198 if remaining_splines.is_empty() {
1199 return;
1200 }
10981201 }
1099 if let Some(sub) = tbl.get_table("Tools") {
1202 }
1203 for (_, v) in &tools.entries {
1204 if let Some(sub) = v.as_table().and_then(|t| t.get_table("Tools")) {
11001205 consume_nested_splines(sub, remaining_splines, top_level_spline_names);
1206 if remaining_splines.is_empty() {
1207 return;
1208 }
11011209 }
11021210 }
11031211}
......@@ -1947,4 +2055,201 @@ mod tests {
19472055 assert_eq!(in_b.connected_node("Input"), None);
19482056 assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#));
19492057 }
2058
2059 fn ast_fusion_string(comp: &Comp) -> String {
2060 let mut s = comp.sync_to_raw_ast().to_fusion_string();
2061 if !s.ends_with('\n') {
2062 s.push('\n');
2063 }
2064 s
2065 }
2066
2067 #[test]
2068 fn streaming_matches_ast_for_same_named_nested_splines() {
2069 let src = r#"Composition {
2070 Tools = ordered() {
2071 Outer = GroupOperator {
2072 Tools = ordered() {
2073 Inner = GroupOperator {
2074 Tools = ordered() {
2075 SharedSpline = BezierSpline {
2076 SplineColor = { Red = 255, Green = 0, Blue = 0 },
2077 KeyFrames = {
2078 [0] = { 0.1 },
2079 [10] = { 0.2 },
2080 },
2081 },
2082 InnerBG = Background {},
2083 },
2084 },
2085 SharedSpline = BezierSpline {
2086 SplineColor = { Red = 0, Green = 255, Blue = 0 },
2087 KeyFrames = {
2088 [0] = { 0.5 },
2089 [10] = { 1.0 },
2090 },
2091 },
2092 },
2093 },
2094 },
2095 }"#;
2096 let mut comp = Comp::from_fusion_str(src).unwrap();
2097
2098 // Case 1: active spline matches Outer.Tools.SharedSpline while Inner.Tools.SharedSpline differs.
2099 {
2100 let sp = comp.splines.get_mut("SharedSpline").expect("SharedSpline loaded");
2101 sp.color = [0, 255, 0];
2102 sp.keyframes[0].time = 0.0;
2103 sp.keyframes[0].value = 0.5;
2104 sp.keyframes[1].time = 10.0;
2105 sp.keyframes[1].value = 1.0;
2106 }
2107 assert!(comp.try_to_fusion_string_streaming().is_some());
2108 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2109
2110 // Case 2: active spline matches Inner.Tools.SharedSpline (differs from Outer.Tools.SharedSpline).
2111 // `sync_existing_splines_in_tools` updates Outer.Tools.SharedSpline first and leaves Inner untouched.
2112 {
2113 let sp = comp.splines.get_mut("SharedSpline").unwrap();
2114 sp.color = [255, 0, 0];
2115 sp.keyframes[0].value = 0.1;
2116 sp.keyframes[1].value = 0.2;
2117 }
2118 assert!(comp.try_to_fusion_string_streaming().is_some());
2119 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2120
2121 // Case 3: active spline edited to a brand-new value.
2122 {
2123 let sp = comp.splines.get_mut("SharedSpline").unwrap();
2124 sp.keyframes[0].value = 0.75;
2125 }
2126 assert!(comp.try_to_fusion_string_streaming().is_some());
2127 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2128 }
2129
2130 #[test]
2131 fn streaming_bails_and_matches_ast_when_all_nodes_deleted() {
2132 let src = r#"Composition {
2133 Tools = ordered() {
2134 A = Blur {},
2135 B = Blur {},
2136 },
2137 }"#;
2138 // Path 1: deleted via `delete_nodes`
2139 let mut comp = Comp::from_fusion_str(src).unwrap();
2140 let a = comp.find_node("A").unwrap();
2141 let b = comp.find_node("B").unwrap();
2142 comp.delete_nodes(&[a, b]);
2143 assert!(comp.try_to_fusion_string_streaming().is_none());
2144 let saved = comp.to_fusion_string();
2145 assert_eq!(saved, ast_fusion_string(&comp));
2146 assert!(saved.contains("Tools = ordered() {},"));
2147
2148 // Path 2: `raw_root.Tools` still has entries, but all flow nodes removed from `comp.nodes`
2149 let mut comp2 = Comp::from_fusion_str(src).unwrap();
2150 comp2.nodes.clear();
2151 comp2.node_by_name.clear();
2152 assert!(comp2.try_to_fusion_string_streaming().is_none());
2153 let saved2 = comp2.to_fusion_string();
2154 assert_eq!(saved2, ast_fusion_string(&comp2));
2155 assert!(saved2.contains("Tools = ordered() {},"));
2156 }
2157
2158 #[test]
2159 fn streaming_bails_and_matches_ast_for_non_table_entry_in_tools() {
2160 let src = r#"Composition {
2161 Tools = ordered() {
2162 Foo = "not_a_table",
2163 BG = Background {},
2164 },
2165 }"#;
2166 let mut comp = Comp::from_fusion_str(src).unwrap();
2167 // Add a flow node named "Foo" without mutating `raw_root.Tools`, so `raw_root.Tools`
2168 // retains the colliding non-table `Foo = "not_a_table"` entry.
2169 let id = super::super::NodeId(comp.nodes.len());
2170 comp.nodes.push(Node {
2171 id,
2172 name: "Foo".to_owned(),
2173 kind: "Blur".to_owned(),
2174 pos: [10.0, 20.0],
2175 bypassed: false,
2176 internal: false,
2177 macro_output: None,
2178 inputs: HashMap::new(),
2179 clips: Vec::new(),
2180 raw: LuaTable::default(),
2181 });
2182 comp.node_by_name.insert("Foo".to_owned(), id);
2183
2184 assert!(comp.try_to_fusion_string_streaming().is_none());
2185 let saved = comp.to_fusion_string();
2186 assert_eq!(saved, ast_fusion_string(&comp));
2187 assert!(saved.contains("Foo = Blur {"));
2188 assert!(!saved.contains("not_a_table"));
2189 }
2190
2191 #[test]
2192 fn streaming_bails_and_matches_ast_for_duplicate_root_and_tools_keys() {
2193 let dup_root_src = r#"Composition {
2194 CurrentTime = 5,
2195 CurrentTime = 99,
2196 RenderRange = { 0, 10 },
2197 RenderRange = { 5, 25 },
2198 Tools = ordered() {
2199 BG = Background {},
2200 },
2201 }"#;
2202 let mut comp = Comp::from_fusion_str(dup_root_src).unwrap();
2203 comp.current_time = 12.0;
2204 assert!(comp.try_to_fusion_string_streaming().is_none());
2205 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2206
2207 let dup_tools_src = r#"Composition {
2208 CurrentTime = 0,
2209 Tools = ordered() {
2210 BG = Background {},
2211 },
2212 Tools = ordered() {
2213 Shadowed = Blur {},
2214 },
2215 }"#;
2216 let comp2 = Comp::from_fusion_str(dup_tools_src).unwrap();
2217 assert!(comp2.try_to_fusion_string_streaming().is_none());
2218 assert_eq!(comp2.to_fusion_string(), ast_fusion_string(&comp2));
2219 }
2220
2221 #[test]
2222 fn streaming_bails_and_matches_ast_when_untagged_tools_shrinks_to_four_or_fewer() {
2223 let src = r#"Composition {
2224 Tools = {
2225 A = Blur {},
2226 B = Blur {},
2227 C = Blur {},
2228 D = Blur {},
2229 E = Blur {},
2230 },
2231 }"#;
2232 let mut comp = Comp::from_fusion_str(src).unwrap();
2233 // With 5 entries, streaming can run.
2234 assert!(comp.try_to_fusion_string_streaming().is_some());
2235 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2236
2237 // Remove 3 nodes from `comp.nodes` while `raw_root.Tools` still holds 5 entries, so
2238 // post-edit untagged `Tools` shrinks from 5 -> 2 (<= 4, eligible for inline formatting).
2239 comp.nodes.retain(|n| n.name == "A" || n.name == "B");
2240 comp.node_by_name.retain(|name, _| name == "A" || name == "B");
2241 assert!(comp.try_to_fusion_string_streaming().is_none());
2242 let saved = comp.to_fusion_string();
2243 assert_eq!(saved, ast_fusion_string(&comp));
2244 assert!(saved.contains("Tools = { A = Blur {}, B = Blur {} },"));
2245
2246 // Also verify via `delete_nodes`.
2247 let mut comp2 = Comp::from_fusion_str(src).unwrap();
2248 let ids: Vec<_> = ["C", "D", "E"].iter().map(|n| comp2.find_node(n).unwrap()).collect();
2249 comp2.delete_nodes(&ids);
2250 assert!(comp2.try_to_fusion_string_streaming().is_none());
2251 let saved2 = comp2.to_fusion_string();
2252 assert_eq!(saved2, ast_fusion_string(&comp2));
2253 assert!(saved2.contains("Tools = { A = Blur {}, B = Blur {} },"));
2254 }
19502255}
crates/model/src/lua_value.rs+40-8
......@@ -254,7 +254,7 @@ impl<'a> Parser<'a> {
254254 if p < len && src[p] == b'[' {
255255 self.pos = p;
256256 if let Some(level) = self.try_open_long_bracket() {
257 self.skip_long_bracket(level)?;
257 self.skip_long_bracket_discard(level)?;
258258 p = self.pos;
259259 continue;
260260 }
......@@ -291,7 +291,7 @@ impl<'a> Parser<'a> {
291291 }
292292 }
293293
294 fn skip_long_bracket(&mut self, level: usize) -> Result<String, ParseError> {
294 fn skip_long_bracket_range(&mut self, level: usize) -> Result<(usize, usize), ParseError> {
295295 let start = self.pos;
296296 let src = self.src;
297297 let len = src.len();
......@@ -305,13 +305,8 @@ impl<'a> Parser<'a> {
305305 eq += 1;
306306 }
307307 if eq == level && i < len && src[i] == b']' {
308 let slice = &src[start..close_start];
309 let s = match std::str::from_utf8(slice) {
310 Ok(v) => v.to_owned(),
311 Err(_) => String::from_utf8_lossy(slice).into_owned(),
312 };
313308 self.pos = i + 1;
314 return Ok(s);
309 return Ok((start, close_start));
315310 }
316311 p = close_start + 1;
317312 }
......@@ -319,6 +314,19 @@ impl<'a> Parser<'a> {
319314 Err(self.err("unterminated long bracket string/comment"))
320315 }
321316
317 fn skip_long_bracket_discard(&mut self, level: usize) -> Result<(), ParseError> {
318 self.skip_long_bracket_range(level).map(|_| ())
319 }
320
321 fn skip_long_bracket(&mut self, level: usize) -> Result<String, ParseError> {
322 let (start, close_start) = self.skip_long_bracket_range(level)?;
323 let slice = &self.src[start..close_start];
324 Ok(match std::str::from_utf8(slice) {
325 Ok(v) => v.to_owned(),
326 Err(_) => String::from_utf8_lossy(slice).into_owned(),
327 })
328 }
329
322330 fn parse_value(&mut self) -> Result<LuaValue, ParseError> {
323331 self.skip_ws_and_comments()?;
324332 let Some(b) = self.peek() else {
......@@ -1101,3 +1109,27 @@ pub(crate) fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) {
11011109 write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out);
11021110 write_table_body(tbl, body.into_iter(), depth, out);
11031111}
1112
1113#[cfg(test)]
1114mod tests {
1115 use super::*;
1116
1117 #[test]
1118 fn skips_long_bracket_block_comments_without_corrupting_parse() {
1119 let src = r#"
1120 --[[ simple block comment
1121 spanning multiple lines ]]
1122 Composition {
1123 --[=[ leveled comment with ]] inside ]=]
1124 CurrentTime = --[==[ nested ]=] still comment ]==] 42,
1125 Name = [=[kept long string]=],
1126 }
1127 "#;
1128 let val = parse_lua(src).expect("parse with long block comments");
1129 let tbl = val.as_table().expect("root table");
1130 assert_eq!(tbl.get_f64("CurrentTime"), Some(42.0));
1131 assert_eq!(tbl.get_str("Name"), Some("kept long string"));
1132
1133 assert!(parse_lua("--[=[ unterminated comment\n{}").is_err());
1134 }
1135}