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 {...@@ -928,6 +928,18 @@ impl VideoExportError {
928 }928 }
929}929}
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
931/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames943/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
932/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.944/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.
933pub fn export_node_video_ffmpeg_with_progress(945pub fn export_node_video_ffmpeg_with_progress(
...@@ -962,6 +974,7 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -962,6 +974,7 @@ pub fn export_node_video_ffmpeg_with_progress(
962 engine.hiq = opts.hiq;974 engine.hiq = opts.hiq;
963 engine.proxy_scale = opts.proxy_scale.max(1);975 engine.proxy_scale = opts.proxy_scale.max(1);
964976
977 let started_at = Instant::now();
965 let vt = probe_videotoolbox_support();978 let vt = probe_videotoolbox_support();
966 let encoder = select_video_encoder(opts.codec, vt, true);979 let encoder = select_video_encoder(opts.codec, vt, true);
967 let res = match export_node_video_ffmpeg_with_encoder(980 let res = match export_node_video_ffmpeg_with_encoder(
...@@ -971,19 +984,25 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -971,19 +984,25 @@ pub fn export_node_video_ffmpeg_with_progress(
971 control,984 control,
972 &mut on_progress,985 &mut on_progress,
973 encoder,986 encoder,
987 started_at,
974 ) {988 ) {
975 Ok(summary) => Ok(summary),989 Ok(summary) => Ok(summary),
976 Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => {990 Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => {
977 let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false);991 if control.is_some_and(ExportControl::is_cancelled) {
978 export_node_video_ffmpeg_with_encoder(992 Err("Cancelled".to_owned())
979 engine,993 } else {
980 comp,994 let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false);
981 opts,995 export_node_video_ffmpeg_with_encoder(
982 control,996 engine,
983 &mut on_progress,997 comp,
984 fallback,998 opts,
985 )999 control,
986 .map_err(VideoExportError::into_string)1000 &mut on_progress,
1001 fallback,
1002 started_at,
1003 )
1004 .map_err(VideoExportError::into_string)
1005 }
987 }1006 }
988 Err(err) => Err(err.into_string()),1007 Err(err) => Err(err.into_string()),
989 };1008 };
...@@ -1000,9 +1019,9 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1000,9 +1019,9 @@ fn export_node_video_ffmpeg_with_encoder(
1000 control: Option<&ExportControl>,1019 control: Option<&ExportControl>,
1001 on_progress: &mut impl FnMut(ExportProgress),1020 on_progress: &mut impl FnMut(ExportProgress),
1002 encoder: VideoEncoder,1021 encoder: VideoEncoder,
1022 started_at: Instant,
1003) -> Result<VideoExportSummary, VideoExportError> {1023) -> Result<VideoExportSummary, VideoExportError> {
1004 let [start, end] = opts.range;1024 let [start, end] = opts.range;
1005 let t0 = Instant::now();
1006 let total = (end - start + 1) as usize;1025 let total = (end - start + 1) as usize;
1007 let fps = comp.fps.max(1.0);1026 let fps = comp.fps.max(1.0);
1008 let node_name = comp.node(opts.target).name.clone();1027 let node_name = comp.node(opts.target).name.clone();
...@@ -1096,20 +1115,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1096,20 +1115,7 @@ fn export_node_video_ffmpeg_with_encoder(
10961115
1097 let (out_width, out_height) = match opts.codec {1116 let (out_width, out_height) = match opts.codec {
1098 VideoCodec::H264Share => {1117 VideoCodec::H264Share => {
1099 let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) {1118 let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height);
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 };
1113 let mut encoder_args = Vec::new();1119 let mut encoder_args = Vec::new();
1114 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf));1120 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf));
1115 cmd.args(&encoder_args);1121 cmd.args(&encoder_args);
...@@ -1145,7 +1151,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1145,7 +1151,7 @@ fn export_node_video_ffmpeg_with_encoder(
1145 .stderr(Stdio::piped());1151 .stderr(Stdio::piped());
11461152
1147 let mut child = cmd.spawn().map_err(|e| {1153 let mut child = cmd.spawn().map_err(|e| {
1148 VideoExportError::EncoderFailed(format!(1154 VideoExportError::Fatal(format!(
1149 "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"1155 "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"
1150 ))1156 ))
1151 })?;1157 })?;
...@@ -1164,10 +1170,15 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1164,10 +1170,15 @@ fn export_node_video_ffmpeg_with_encoder(
1164 let mut cancelled = false;1170 let mut cancelled = false;
1165 let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));1171 let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
1166 let writer_failed = Arc::new(AtomicBool::new(false));1172 let writer_failed = Arc::new(AtomicBool::new(false));
1167 let stdin = child1173 let writer_fatal = Arc::new(AtomicBool::new(false));
1168 .stdin1174 let Some(stdin) = child.stdin.take() else {
1169 .take()1175 let _ = child.kill();
1170 .ok_or_else(|| VideoExportError::EncoderFailed("failed to open ffmpeg stdin".to_owned()))?;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
1172 let frame_bytes_len = (width as usize)1183 let frame_bytes_len = (width as usize)
1173 .saturating_mul(height as usize)1184 .saturating_mul(height as usize)
...@@ -1178,6 +1189,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1178,6 +1189,7 @@ fn export_node_video_ffmpeg_with_encoder(
1178 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + 2);1189 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + 2);
1179 let writer_err_c = Arc::clone(&writer_err);1190 let writer_err_c = Arc::clone(&writer_err);
1180 let writer_failed_c = Arc::clone(&writer_failed);1191 let writer_failed_c = Arc::clone(&writer_failed);
1192 let writer_fatal_c = Arc::clone(&writer_fatal);
1181 let dst_size = [width, height];1193 let dst_size = [width, height];
1182 let writer_thread = std::thread::spawn(move || {1194 let writer_thread = std::thread::spawn(move || {
1183 let mut stdin = stdin;1195 let mut stdin = stdin;
...@@ -1190,6 +1202,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1190,6 +1202,7 @@ fn export_node_video_ffmpeg_with_encoder(
1190 *g = Some(e);1202 *g = Some(e);
1191 }1203 }
1192 }1204 }
1205 writer_fatal_c.store(true, Ordering::Release);
1193 writer_failed_c.store(true, Ordering::Release);1206 writer_failed_c.store(true, Ordering::Release);
1194 break;1207 break;
1195 }1208 }
...@@ -1223,7 +1236,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1223,7 +1236,7 @@ fn export_node_video_ffmpeg_with_encoder(
1223 first_stats.eval_ms,1236 first_stats.eval_ms,
1224 opts.out_path.clone(),1237 opts.out_path.clone(),
1225 node_name.clone(),1238 node_name.clone(),
1226 t0,1239 started_at,
1227 );1240 );
1228 if let Some(ctrl) = control {1241 if let Some(ctrl) = control {
1229 ctrl.update_progress(&first_prog);1242 ctrl.update_progress(&first_prog);
...@@ -1247,13 +1260,13 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1247,13 +1260,13 @@ fn export_node_video_ffmpeg_with_encoder(
1247 }1260 }
1248 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;1261 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
1249 for (idx, frame) in ((start + 1)..=end).enumerate() {1262 for (idx, frame) in ((start + 1)..=end).enumerate() {
1250 if writer_failed.load(Ordering::Acquire) {
1251 break;
1252 }
1253 if control.is_some_and(ExportControl::is_cancelled) {1263 if control.is_some_and(ExportControl::is_cancelled) {
1254 cancelled = true;1264 cancelled = true;
1255 break;1265 break;
1256 }1266 }
1267 if writer_failed.load(Ordering::Acquire) {
1268 break;
1269 }
1257 prefetch.set_current_seq(idx);1270 prefetch.set_current_seq(idx);
1258 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;1271 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;
1259 if ahead_frame <= end {1272 if ahead_frame <= end {
...@@ -1297,7 +1310,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1297,7 +1310,7 @@ fn export_node_video_ffmpeg_with_encoder(
1297 prev_ms,1310 prev_ms,
1298 opts.out_path.clone(),1311 opts.out_path.clone(),
1299 node_name.clone(),1312 node_name.clone(),
1300 t0,1313 started_at,
1301 );1314 );
1302 if let Some(ctrl) = control {1315 if let Some(ctrl) = control {
1303 ctrl.update_progress(&prog);1316 ctrl.update_progress(&prog);
...@@ -1305,6 +1318,9 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1305,6 +1318,9 @@ fn export_node_video_ffmpeg_with_encoder(
1305 on_progress(prog);1318 on_progress(prog);
1306 }1319 }
1307 }1320 }
1321 if control.is_some_and(ExportControl::is_cancelled) {
1322 cancelled = true;
1323 }
1308 if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {1324 if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {
1309 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {1325 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {
1310 let mut pixels = recycle_rx.try_recv().unwrap_or_default();1326 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
...@@ -1320,12 +1336,15 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1320,12 +1336,15 @@ fn export_node_video_ffmpeg_with_encoder(
1320 prev_ms,1336 prev_ms,
1321 opts.out_path.clone(),1337 opts.out_path.clone(),
1322 node_name.clone(),1338 node_name.clone(),
1323 t0,1339 started_at,
1324 );1340 );
1325 if let Some(ctrl) = control {1341 if let Some(ctrl) = control {
1326 ctrl.update_progress(&prog);1342 ctrl.update_progress(&prog);
1327 }1343 }
1328 on_progress(prog);1344 on_progress(prog);
1345 if control.is_some_and(ExportControl::is_cancelled) {
1346 cancelled = true;
1347 }
1329 }1348 }
1330 }1349 }
1331 Err(e) => {1350 Err(e) => {
...@@ -1340,6 +1359,9 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1340,6 +1359,9 @@ fn export_node_video_ffmpeg_with_encoder(
1340 }1359 }
1341 drop(tx);1360 drop(tx);
13421361
1362 if control.is_some_and(ExportControl::is_cancelled) {
1363 cancelled = true;
1364 }
1343 if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) {1365 if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) {
1344 // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately.1366 // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately.
1345 let _ = child.kill();1367 let _ = child.kill();
...@@ -1353,26 +1375,33 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1353,26 +1375,33 @@ fn export_node_video_ffmpeg_with_encoder(
1353 if pipe_err.is_some() && !cancelled {1375 if pipe_err.is_some() && !cancelled {
1354 let _ = child.kill();1376 let _ = child.kill();
1355 }1377 }
1356 let status = child1378 let wait_res = child.wait();
1357 .wait()
1358 .map_err(|e| VideoExportError::EncoderFailed(format!("failed waiting on ffmpeg: {e}")))?;
1359 let stderr_text = stderr_thread.join().unwrap_or_default();1379 let stderr_text = stderr_thread.join().unwrap_or_default();
1360 let stderr_trim = stderr_text.trim();1380 let stderr_trim = stderr_text.trim();
13611381
1362 if cancelled {1382 if cancelled || control.is_some_and(ExportControl::is_cancelled) {
1363 return Err(VideoExportError::Cancelled);1383 return Err(VideoExportError::Cancelled);
1364 }1384 }
1365 if let Some(err) = readback_err {1385 if let Some(err) = readback_err {
1366 return Err(VideoExportError::Fatal(err));1386 return Err(VideoExportError::Fatal(err));
1367 }1387 }
1368 if let Some(err) = pipe_err {1388 if let Some(err) = pipe_err {
1389 if writer_fatal.load(Ordering::Acquire) {
1390 return Err(VideoExportError::Fatal(err));
1391 }
1369 return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() {1392 return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() {
1370 format!("{err} (ffmpeg: {stderr_trim})")1393 format!("{err} (ffmpeg: {stderr_trim})")
1371 } else {1394 } else {
1372 err1395 err
1373 }));1396 }));
1374 }1397 }
1398 let status = wait_res.map_err(|e| {
1399 VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}"))
1400 })?;
1375 if !status.success() {1401 if !status.success() {
1402 if control.is_some_and(ExportControl::is_cancelled) {
1403 return Err(VideoExportError::Cancelled);
1404 }
1376 return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() {1405 return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() {
1377 format!("ffmpeg exited with {status}")1406 format!("ffmpeg exited with {status}")
1378 } else {1407 } else {
...@@ -1395,7 +1424,7 @@ fn export_node_video_ffmpeg_with_encoder(...@@ -1395,7 +1424,7 @@ fn export_node_video_ffmpeg_with_encoder(
1395 width: out_width,1424 width: out_width,
1396 height: out_height,1425 height: out_height,
1397 has_audio,1426 has_audio,
1398 total_ms: t0.elapsed().as_secs_f64() * 1000.0,1427 total_ms: started_at.elapsed().as_secs_f64() * 1000.0,
1399 file_bytes,1428 file_bytes,
1400 })1429 })
1401}1430}
...@@ -2440,6 +2469,7 @@ Encoders:...@@ -2440,6 +2469,7 @@ Encoders:
2440 None,2469 None,
2441 &mut noop,2470 &mut noop,
2442 VideoEncoder::Libx264,2471 VideoEncoder::Libx264,
2472 Instant::now(),
2443 )2473 )
2444 .expect("software libx264 fallback export");2474 .expect("software libx264 fallback export");
2445 assert_eq!(sw_summary.frames_written, 3);2475 assert_eq!(sw_summary.frames_written, 3);
...@@ -2463,6 +2493,7 @@ Encoders:...@@ -2463,6 +2493,7 @@ Encoders:
2463 None,2493 None,
2464 &mut noop,2494 &mut noop,
2465 VideoEncoder::ProResKs422,2495 VideoEncoder::ProResKs422,
2496 Instant::now(),
2466 )2497 )
2467 .expect("software prores_ks fallback export");2498 .expect("software prores_ks fallback export");
2468 assert_eq!(sw_prores.frames_written, 3);2499 assert_eq!(sw_prores.frames_written, 3);
...@@ -2470,4 +2501,89 @@ Encoders:...@@ -2470,4 +2501,89 @@ Encoders:
24702501
2471 let _ = std::fs::remove_dir_all(&tmp_dir);2502 let _ = std::fs::remove_dir_all(&tmp_dir);
2472 }2503 }
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 }
2473}2589}
crates/model/src/comp/save.rs+327-22
...@@ -325,10 +325,35 @@ impl Comp {...@@ -325,10 +325,35 @@ impl Comp {
325 if has_call_args(root) {325 if has_call_args(root) {
326 return None;326 return None;
327 }327 }
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 }
328 let tools = root.get_table("Tools")?;350 let tools = root.get_table("Tools")?;
329 if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4)351 if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4)
330 || has_call_args(tools)352 || 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())
332 {357 {
333 return None;358 return None;
334 }359 }
...@@ -447,13 +472,15 @@ impl Comp {...@@ -447,13 +472,15 @@ impl Comp {
447 seen_tools = true;472 seen_tools = true;
448 write_indent(&mut out, 1);473 write_indent(&mut out, 1);
449 write_entry_key(k, positional, &mut out);474 write_entry_key(k, positional, &mut out);
450 self.write_tools_streaming(475 if !self.write_tools_streaming(
451 tools,476 tools,
452 &mut top_pool,477 &mut top_pool,
453 &mut inner_pool,478 &mut inner_pool,
454 &instance_defaults,479 &instance_defaults,
455 &mut out,480 &mut out,
456 );481 ) {
482 return None;
483 }
457 out.push_str(",\n");484 out.push_str(",\n");
458 continue;485 continue;
459 }486 }
...@@ -553,7 +580,7 @@ impl Comp {...@@ -553,7 +580,7 @@ impl Comp {
553 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,580 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
554 instance_defaults: &HashMap<(&str, &str), ParamValue>,581 instance_defaults: &HashMap<(&str, &str), ParamValue>,
555 out: &mut String,582 out: &mut String,
556 ) {583 ) -> bool {
557 let mut remaining_splines: HashMap<&str, &BezierSpline> =584 let mut remaining_splines: HashMap<&str, &BezierSpline> =
558 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();585 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();
559586
...@@ -572,6 +599,7 @@ impl Comp {...@@ -572,6 +599,7 @@ impl Comp {
572 }599 }
573600
574 let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len());601 let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len());
602 let mut emitted_entries: usize = 0;
575603
576 write_table_prefix(tools.tag.as_deref(), &[], 1, out);604 write_table_prefix(tools.tag.as_deref(), &[], 1, out);
577 out.push_str("{\n");605 out.push_str("{\n");
...@@ -582,6 +610,7 @@ impl Comp {...@@ -582,6 +610,7 @@ impl Comp {
582 write_entry_key(k, true, out);610 write_entry_key(k, true, out);
583 write_value(v, 2, out);611 write_value(v, 2, out);
584 out.push_str(",\n");612 out.push_str(",\n");
613 emitted_entries += 1;
585 continue;614 continue;
586 };615 };
587 let Some(tbl) = v.as_table() else {616 let Some(tbl) = v.as_table() else {
...@@ -590,6 +619,7 @@ impl Comp {...@@ -590,6 +619,7 @@ impl Comp {
590 write_entry_key(k, true, out);619 write_entry_key(k, true, out);
591 write_value(v, 2, out);620 write_value(v, 2, out);
592 out.push_str(",\n");621 out.push_str(",\n");
622 emitted_entries += 1;
593 continue;623 continue;
594 };624 };
595625
...@@ -610,6 +640,7 @@ impl Comp {...@@ -610,6 +640,7 @@ impl Comp {
610 write_table(tbl, 2, out);640 write_table(tbl, 2, out);
611 }641 }
612 out.push_str(",\n");642 out.push_str(",\n");
643 emitted_entries += 1;
613 continue;644 continue;
614 }645 }
615646
...@@ -673,6 +704,7 @@ impl Comp {...@@ -673,6 +704,7 @@ impl Comp {
673 write_table(&cloned, 2, out);704 write_table(&cloned, 2, out);
674 }705 }
675 out.push_str(",\n");706 out.push_str(",\n");
707 emitted_entries += 1;
676 }708 }
677709
678 // Newly added top-level nodes not yet present in `tools`710 // Newly added top-level nodes not yet present in `tools`
...@@ -712,6 +744,7 @@ impl Comp {...@@ -712,6 +744,7 @@ impl Comp {
712 write_entry_key(&LuaKey::Str(node.name.clone()), true, out);744 write_entry_key(&LuaKey::Str(node.name.clone()), true, out);
713 write_table(&new_tbl, 2, out);745 write_table(&new_tbl, 2, out);
714 out.push_str(",\n");746 out.push_str(",\n");
747 emitted_entries += 1;
715 }748 }
716749
717 // Newly added splines not yet present in `tools`750 // Newly added splines not yet present in `tools`
...@@ -736,11 +769,17 @@ impl Comp {...@@ -736,11 +769,17 @@ impl Comp {
736 write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out);769 write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out);
737 write_table(&sp_tbl, 2, out);770 write_table(&sp_tbl, 2, out);
738 out.push_str(",\n");771 out.push_str(",\n");
772 emitted_entries += 1;
739 }773 }
740 }774 }
741775
776 if emitted_entries == 0 || (tools.tag.as_deref() != Some("ordered") && emitted_entries <= 4) {
777 return false;
778 }
779
742 write_indent(out, 1);780 write_indent(out, 1);
743 out.push('}');781 out.push('}');
782 true
744 }783 }
745784
746 fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool {785 fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool {
...@@ -824,7 +863,13 @@ impl Comp {...@@ -824,7 +863,13 @@ impl Comp {
824 return false;863 return false;
825 }864 }
826 if let Some(inner) = tool_tbl.get_table("Tools") {865 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 ) {
828 return false;873 return false;
829 }874 }
830 consume_nested_splines(inner, remaining_splines, top_level_spline_names);875 consume_nested_splines(inner, remaining_splines, top_level_spline_names);
...@@ -851,6 +896,7 @@ impl Comp {...@@ -851,6 +896,7 @@ impl Comp {
851 return true;896 return true;
852 };897 };
853 let mut peek_offsets: HashMap<&str, usize> = HashMap::new();898 let mut peek_offsets: HashMap<&str, usize> = HashMap::new();
899 let mut claimed_splines: HashSet<&str> = HashSet::new();
854 if !self.check_inner_tools_verbatim(900 if !self.check_inner_tools_verbatim(
855 inner_tools,901 inner_tools,
856 inner_pool,902 inner_pool,
...@@ -858,6 +904,7 @@ impl Comp {...@@ -858,6 +904,7 @@ impl Comp {
858 instance_defaults,904 instance_defaults,
859 remaining_splines,905 remaining_splines,
860 top_level_spline_names,906 top_level_spline_names,
907 &mut claimed_splines,
861 ) {908 ) {
862 return false;909 return false;
863 }910 }
...@@ -879,17 +926,39 @@ impl Comp {...@@ -879,17 +926,39 @@ impl Comp {
879 instance_defaults: &HashMap<(&str, &str), ParamValue>,926 instance_defaults: &HashMap<(&str, &str), ParamValue>,
880 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,927 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
881 top_level_spline_names: &HashSet<&str>,928 top_level_spline_names: &HashSet<&str>,
929 claimed_splines: &mut HashSet<&'b str>,
882 ) -> bool {930 ) -> bool {
883 // Check modifiers at this level first (matching `sync_existing_splines_in_tools` top-down order).931 // Pass 1: check direct entries at this `inner_tools` level BEFORE recursing into
884 for (k, v) in &inner_tools.entries {932 // nested `.Tools` tables (matching `sync_existing_splines_in_tools` top-down order).
885 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };933 if !remaining_splines.is_empty() {
886 let tag = tbl.tag.as_deref().unwrap_or("Unknown");934 for (k, v) in &inner_tools.entries {
887 if is_modifier_type(tag) {935 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
888 if !top_level_spline_names.contains(name.as_str()) {936 if !top_level_spline_names.contains(name.as_str())
937 && !claimed_splines.contains(name.as_str())
938 {
889 if let Some(&spline) = remaining_splines.get(name.as_str()) {939 if let Some(&spline) = remaining_splines.get(name.as_str()) {
890 if spline_needs_sync(name, spline, tbl) {940 if spline_needs_sync(name, spline, tbl) {
891 return false;941 return false;
892 }942 }
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;
893 }962 }
894 }963 }
895 continue;964 continue;
...@@ -914,6 +983,7 @@ impl Comp {...@@ -914,6 +983,7 @@ impl Comp {
914 instance_defaults,983 instance_defaults,
915 remaining_splines,984 remaining_splines,
916 top_level_spline_names,985 top_level_spline_names,
986 claimed_splines,
917 ) {987 ) {
918 return false;988 return false;
919 }989 }
...@@ -937,7 +1007,12 @@ impl Comp {...@@ -937,7 +1007,12 @@ impl Comp {
937 return false;1007 return false;
938 }1008 }
939 if let Some(sub_tools) = tbl.get_table("Tools") {1009 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 ) {
941 return false;1016 return false;
942 }1017 }
943 }1018 }
...@@ -1037,12 +1112,26 @@ fn commit_inner_tools_verbatim<'a>(...@@ -1037,12 +1112,26 @@ fn commit_inner_tools_verbatim<'a>(
1037 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,1112 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
1038 top_level_spline_names: &HashSet<&str>,1113 top_level_spline_names: &HashSet<&str>,
1039) {1114) {
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`.
1040 for (k, v) in &inner_tools.entries {1129 for (k, v) in &inner_tools.entries {
1041 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };1130 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1042 let tag = tbl.tag.as_deref().unwrap_or("Unknown");1131 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
1043 if is_modifier_type(tag) {1132 if is_modifier_type(tag) {
1044 if !top_level_spline_names.contains(name.as_str()) {1133 if let Some(sub_tools) = tbl.get_table("Tools") {
1045 remaining_splines.remove(name.as_str());1134 consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names);
1046 }1135 }
1047 continue;1136 continue;
1048 }1137 }
...@@ -1057,25 +1146,36 @@ fn commit_inner_tools_verbatim<'a>(...@@ -1057,25 +1146,36 @@ fn commit_inner_tools_verbatim<'a>(
1057 }1146 }
1058}1147}
10591148
1060fn nested_splines_verbatim(1149fn nested_splines_verbatim<'a, 'b>(
1061 tools: &LuaTable,1150 tools: &'b LuaTable,
1062 remaining_splines: &HashMap<&str, &BezierSpline>,1151 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
1063 top_level_spline_names: &HashSet<&str>,1152 top_level_spline_names: &HashSet<&str>,
1153 claimed_splines: &mut HashSet<&'b str>,
1064) -> bool {1154) -> bool {
1065 if remaining_splines.is_empty() {1155 if remaining_splines.is_empty() {
1066 return true;1156 return true;
1067 }1157 }
1068 for (k, v) in &tools.entries {1158 for (k, v) in &tools.entries {
1069 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };1159 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 {
1071 if let Some(&spline) = remaining_splines.get(name.as_str()) {1163 if let Some(&spline) = remaining_splines.get(name.as_str()) {
1072 if spline_needs_sync(name, spline, tbl) {1164 if spline_needs_sync(name, spline, tbl) {
1073 return false;1165 return false;
1074 }1166 }
1167 claimed_splines.insert(name.as_str());
1075 }1168 }
1076 }1169 }
1077 if let Some(sub) = tbl.get_table("Tools") {1170 }
1078 if !nested_splines_verbatim(sub, remaining_splines, top_level_spline_names) {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 ) {
1079 return false;1179 return false;
1080 }1180 }
1081 }1181 }
...@@ -1092,12 +1192,20 @@ fn consume_nested_splines(...@@ -1092,12 +1192,20 @@ fn consume_nested_splines(
1092 return;1192 return;
1093 }1193 }
1094 for (k, v) in &tools.entries {1194 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 };
1096 if !top_level_spline_names.contains(name.as_str()) {1196 if !top_level_spline_names.contains(name.as_str()) {
1097 remaining_splines.remove(name.as_str());1197 remaining_splines.remove(name.as_str());
1198 if remaining_splines.is_empty() {
1199 return;
1200 }
1098 }1201 }
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")) {
1100 consume_nested_splines(sub, remaining_splines, top_level_spline_names);1205 consume_nested_splines(sub, remaining_splines, top_level_spline_names);
1206 if remaining_splines.is_empty() {
1207 return;
1208 }
1101 }1209 }
1102 }1210 }
1103}1211}
...@@ -1947,4 +2055,201 @@ mod tests {...@@ -1947,4 +2055,201 @@ mod tests {
1947 assert_eq!(in_b.connected_node("Input"), None);2055 assert_eq!(in_b.connected_node("Input"), None);
1948 assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#));2056 assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#));
1949 }2057 }
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 }
1950}2255}
crates/model/src/lua_value.rs+40-8
...@@ -254,7 +254,7 @@ impl<'a> Parser<'a> {...@@ -254,7 +254,7 @@ impl<'a> Parser<'a> {
254 if p < len && src[p] == b'[' {254 if p < len && src[p] == b'[' {
255 self.pos = p;255 self.pos = p;
256 if let Some(level) = self.try_open_long_bracket() {256 if let Some(level) = self.try_open_long_bracket() {
257 self.skip_long_bracket(level)?;257 self.skip_long_bracket_discard(level)?;
258 p = self.pos;258 p = self.pos;
259 continue;259 continue;
260 }260 }
...@@ -291,7 +291,7 @@ impl<'a> Parser<'a> {...@@ -291,7 +291,7 @@ impl<'a> Parser<'a> {
291 }291 }
292 }292 }
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> {
295 let start = self.pos;295 let start = self.pos;
296 let src = self.src;296 let src = self.src;
297 let len = src.len();297 let len = src.len();
...@@ -305,13 +305,8 @@ impl<'a> Parser<'a> {...@@ -305,13 +305,8 @@ impl<'a> Parser<'a> {
305 eq += 1;305 eq += 1;
306 }306 }
307 if eq == level && i < len && src[i] == b']' {307 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 };
313 self.pos = i + 1;308 self.pos = i + 1;
314 return Ok(s);309 return Ok((start, close_start));
315 }310 }
316 p = close_start + 1;311 p = close_start + 1;
317 }312 }
...@@ -319,6 +314,19 @@ impl<'a> Parser<'a> {...@@ -319,6 +314,19 @@ impl<'a> Parser<'a> {
319 Err(self.err("unterminated long bracket string/comment"))314 Err(self.err("unterminated long bracket string/comment"))
320 }315 }
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
322 fn parse_value(&mut self) -> Result<LuaValue, ParseError> {330 fn parse_value(&mut self) -> Result<LuaValue, ParseError> {
323 self.skip_ws_and_comments()?;331 self.skip_ws_and_comments()?;
324 let Some(b) = self.peek() else {332 let Some(b) = self.peek() else {
...@@ -1101,3 +1109,27 @@ pub(crate) fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) {...@@ -1101,3 +1109,27 @@ pub(crate) fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) {
1101 write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out);1109 write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out);
1102 write_table_body(tbl, body.into_iter(), depth, out);1110 write_table_body(tbl, body.into_iter(), depth, out);
1103}1111}
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}