| 1 | //! Export worker management, PNG/MP4/ProRes export triggers, and the bottom export status strip UI. |
| 2 | |
| 3 | use crate::menus::{native_save_file_dialog, sanitize_filename}; |
| 4 | use crate::{Studio, UserEvent, studio_btn}; |
| 5 | use engine::ExportOptions; |
| 6 | use engine::export::{ |
| 7 | ExportControl, ExportProgress, VideoCodec, VideoExportOptions, export_node_frame_png, |
| 8 | export_node_video_ffmpeg_with_progress, export_saver_png_sequence_with_progress, select_saver, |
| 9 | }; |
| 10 | use engine::Engine; |
| 11 | use std::sync::mpsc; |
| 12 | use std::time::Instant; |
| 13 | |
| 14 | pub(crate) enum ExportOutcome { |
| 15 | Completed(String), |
| 16 | Cancelled, |
| 17 | Failed(String), |
| 18 | } |
| 19 | |
| 20 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 21 | pub(crate) enum ExportKind { |
| 22 | SaverPngs, |
| 23 | ViewerVideo, |
| 24 | } |
| 25 | |
| 26 | impl ExportKind { |
| 27 | fn verb(self) -> &'static str { |
| 28 | match self { |
| 29 | Self::SaverPngs | Self::ViewerVideo => "Exporting", |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | pub(crate) struct ActiveExport { |
| 35 | pub(crate) kind: ExportKind, |
| 36 | pub(crate) control: ExportControl, |
| 37 | pub(crate) rx: mpsc::Receiver<ExportOutcome>, |
| 38 | pub(crate) cancelling: bool, |
| 39 | pub(crate) handle: Option<std::thread::JoinHandle<()>>, |
| 40 | } |
| 41 | |
| 42 | impl Drop for ActiveExport { |
| 43 | fn drop(&mut self) { |
| 44 | self.control.cancel(); |
| 45 | if let Some(handle) = self.handle.take() { |
| 46 | let deadline = Instant::now() + std::time::Duration::from_millis(250); |
| 47 | while !handle.is_finished() && Instant::now() < deadline { |
| 48 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 49 | } |
| 50 | if handle.is_finished() { |
| 51 | let _ = handle.join(); |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub(crate) struct StatusStripActions { |
| 58 | pub(crate) cancel_export: bool, |
| 59 | pub(crate) dismiss_notice: bool, |
| 60 | } |
| 61 | |
| 62 | pub(crate) fn build_status_strip( |
| 63 | ui: &mut ui::Ui, |
| 64 | strip_h: f32, |
| 65 | export_snapshot: &Option<(ExportProgress, ExportKind, bool)>, |
| 66 | notice_banner: &Option<String>, |
| 67 | ) -> StatusStripActions { |
| 68 | let mut actions = StatusStripActions { |
| 69 | cancel_export: false, |
| 70 | dismiss_notice: false, |
| 71 | }; |
| 72 | |
| 73 | ui.open( |
| 74 | "studio-status-strip", |
| 75 | ui::Spec { |
| 76 | size: [ui::fill(), ui::px(strip_h)], |
| 77 | axis: ui::Axis::X, |
| 78 | pad: [10.0, 3.0], |
| 79 | gap: 8.0, |
| 80 | fill: Some(ui.theme.strip), |
| 81 | border: Some(ui.theme.rule), |
| 82 | ..ui::Spec::default() |
| 83 | }, |
| 84 | ); |
| 85 | if let Some((prog, kind, cancelling)) = export_snapshot { |
| 86 | let total = prog.total_frames.max(1); |
| 87 | let frac = (prog.completed_frames as f32 / total as f32).clamp(0.0, 1.0); |
| 88 | let pct = (frac * 100.0).round() as u32; |
| 89 | let fill_w = (frac * 176.0).round(); |
| 90 | let bar_bg = ui.theme.base; |
| 91 | let bar_border = ui.theme.rule; |
| 92 | let bar_accent = ui.theme.accent; |
| 93 | ui.open( |
| 94 | "export-progress-track", |
| 95 | ui::Spec { |
| 96 | size: [ui::px(180.0), ui::px(12.0)], |
| 97 | axis: ui::Axis::X, |
| 98 | pad: [2.0, 2.0], |
| 99 | fill: Some(bar_bg), |
| 100 | border: Some(bar_border), |
| 101 | radius: 4.0, |
| 102 | ..ui::Spec::default() |
| 103 | }, |
| 104 | ); |
| 105 | if fill_w > 0.0 { |
| 106 | ui.leaf( |
| 107 | "export-progress-fill", |
| 108 | ui::Spec { |
| 109 | size: [ui::px(fill_w), ui::fill()], |
| 110 | fill: Some(bar_accent), |
| 111 | radius: 2.0, |
| 112 | ..ui::Spec::default() |
| 113 | }, |
| 114 | ); |
| 115 | } |
| 116 | ui.close(); |
| 117 | |
| 118 | let status_txt = if *cancelling { |
| 119 | format!( |
| 120 | "Cancelling {} ({}/{})…", |
| 121 | prog.label, prog.completed_frames, prog.total_frames |
| 122 | ) |
| 123 | } else { |
| 124 | format!( |
| 125 | "{} {} {}/{} ({pct}%) · f{:04} · {:.1}s", |
| 126 | kind.verb(), |
| 127 | prog.label, |
| 128 | prog.completed_frames, |
| 129 | prog.total_frames, |
| 130 | prog.frame, |
| 131 | prog.elapsed_secs |
| 132 | ) |
| 133 | }; |
| 134 | let ink = ui.theme.text; |
| 135 | ui.leaf( |
| 136 | "export-progress-label", |
| 137 | ui::Spec { |
| 138 | size: [ui::fill(), ui::fill()], |
| 139 | text: Some(&status_txt), |
| 140 | font_size: Some(11.0), |
| 141 | medium: true, |
| 142 | color: Some(ink), |
| 143 | ..ui::Spec::default() |
| 144 | }, |
| 145 | ); |
| 146 | let cancel_lbl = if *cancelling { "Cancelling…" } else { "Cancel" }; |
| 147 | if studio_btn(ui, "export-cancel-btn", cancel_lbl, *cancelling).clicked && !*cancelling { |
| 148 | actions.cancel_export = true; |
| 149 | } |
| 150 | } else if let Some(msg) = notice_banner { |
| 151 | let ink = ui.theme.text; |
| 152 | ui.leaf( |
| 153 | "status-notice-label", |
| 154 | ui::Spec { |
| 155 | size: [ui::fill(), ui::fill()], |
| 156 | text: Some(msg), |
| 157 | font_size: Some(11.0), |
| 158 | color: Some(ink), |
| 159 | ..ui::Spec::default() |
| 160 | }, |
| 161 | ); |
| 162 | if studio_btn(ui, "status-notice-dismiss", "×", false).clicked { |
| 163 | actions.dismiss_notice = true; |
| 164 | } |
| 165 | } |
| 166 | ui.close(); |
| 167 | |
| 168 | actions |
| 169 | } |
| 170 | |
| 171 | const EXPORT_VRAM_BUDGET_BYTES: u64 = 256 * 1024 * 1024; |
| 172 | const EXPORT_MEDIA_BUDGET_BYTES: u64 = 128 * 1024 * 1024; |
| 173 | |
| 174 | impl Studio { |
| 175 | pub(crate) fn poll_export(&mut self) { |
| 176 | let Some(exp) = &self.active_export else { |
| 177 | return; |
| 178 | }; |
| 179 | match exp.rx.try_recv() { |
| 180 | Ok(outcome) => { |
| 181 | let mut finished = self.active_export.take().unwrap(); |
| 182 | if let Some(handle) = finished.handle.take() { |
| 183 | let _ = handle.join(); |
| 184 | } |
| 185 | self.last_prefetch_sig = None; |
| 186 | match outcome { |
| 187 | ExportOutcome::Completed(msg) => { |
| 188 | eprintln!("{msg}"); |
| 189 | self.set_notice(msg); |
| 190 | } |
| 191 | ExportOutcome::Cancelled => { |
| 192 | eprintln!("Export cancelled"); |
| 193 | self.set_notice("Export cancelled"); |
| 194 | } |
| 195 | ExportOutcome::Failed(err) => { |
| 196 | eprintln!("{err}"); |
| 197 | self.set_notice(err); |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | Err(mpsc::TryRecvError::Disconnected) => { |
| 202 | let mut finished = self.active_export.take().unwrap(); |
| 203 | if let Some(handle) = finished.handle.take() { |
| 204 | let _ = handle.join(); |
| 205 | } |
| 206 | self.last_prefetch_sig = None; |
| 207 | self.set_notice("Export worker stopped unexpectedly"); |
| 208 | } |
| 209 | Err(mpsc::TryRecvError::Empty) => {} |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | pub(crate) fn spawn_export_worker<F>( |
| 214 | &mut self, |
| 215 | kind: ExportKind, |
| 216 | initial_progress: ExportProgress, |
| 217 | job: F, |
| 218 | ) -> Result<String, String> |
| 219 | where |
| 220 | F: FnOnce(&mut Engine, &ExportControl, &dyn Fn()) -> Result<String, String> + Send + 'static, |
| 221 | { |
| 222 | let control = ExportControl::new(); |
| 223 | control.update_progress(&initial_progress); |
| 224 | let ctrl_worker = control.clone(); |
| 225 | let proxy = self.redraw_proxy.clone(); |
| 226 | let (tx, rx) = mpsc::channel(); |
| 227 | |
| 228 | let handle = std::thread::Builder::new() |
| 229 | .name("fission-export".to_owned()) |
| 230 | .spawn(move || { |
| 231 | let notify_redraw = move || { |
| 232 | if let Some(p) = &proxy { |
| 233 | let _ = p.send_event(UserEvent::Redraw); |
| 234 | } |
| 235 | }; |
| 236 | // Dedicated headless wgpu::Device so background export never submits onto |
| 237 | // the window surface's Device while a live window resize calls Surface::configure. |
| 238 | let outcome = match Engine::new_headless() { |
| 239 | Ok(mut export_engine) => { |
| 240 | export_engine.set_vram_budget_mb(EXPORT_VRAM_BUDGET_BYTES / (1024 * 1024)); |
| 241 | export_engine.media.set_budget_mb(EXPORT_MEDIA_BUDGET_BYTES / (1024 * 1024)); |
| 242 | match job(&mut export_engine, &ctrl_worker, &notify_redraw) { |
| 243 | Ok(msg) => ExportOutcome::Completed(msg), |
| 244 | Err(e) if e == "Cancelled" => ExportOutcome::Cancelled, |
| 245 | Err(e) => ExportOutcome::Failed(e), |
| 246 | } |
| 247 | } |
| 248 | Err(e) => ExportOutcome::Failed(format!("Failed to initialize export GPU: {e}")), |
| 249 | }; |
| 250 | let _ = tx.send(outcome); |
| 251 | notify_redraw(); |
| 252 | }) |
| 253 | .map_err(|e| format!("Failed to start export thread: {e}"))?; |
| 254 | |
| 255 | if let Some(pf) = &self.prefetcher { |
| 256 | pf.cancel(); |
| 257 | } |
| 258 | self.last_prefetch_sig = None; |
| 259 | self.active_export = Some(ActiveExport { |
| 260 | kind, |
| 261 | control, |
| 262 | rx, |
| 263 | cancelling: false, |
| 264 | handle: Some(handle), |
| 265 | }); |
| 266 | Ok("Export started".to_owned()) |
| 267 | } |
| 268 | |
| 269 | pub(crate) fn export_saver_pngs(&mut self) -> Result<String, String> { |
| 270 | if self.active_export.is_some() { |
| 271 | let msg = "Export already in progress".to_owned(); |
| 272 | self.set_notice(msg.clone()); |
| 273 | return Err(msg); |
| 274 | } |
| 275 | let saver = match select_saver(&self.comp, None) { |
| 276 | Ok(s) => s, |
| 277 | Err(e) => { |
| 278 | let err = format!("Export failed: {e}"); |
| 279 | self.set_notice(err.clone()); |
| 280 | return Err(err); |
| 281 | } |
| 282 | }; |
| 283 | let [start, end] = saver.range; |
| 284 | if end < start { |
| 285 | let err = format!("Invalid Saver frame range {start}..={end}"); |
| 286 | self.set_notice(err.clone()); |
| 287 | return Err(err); |
| 288 | } |
| 289 | |
| 290 | let comp_snapshot = self.comp.clone(); |
| 291 | let opts = ExportOptions { |
| 292 | hiq: self.engine.hiq, |
| 293 | proxy_scale: self.engine.proxy_scale, |
| 294 | ..Default::default() |
| 295 | }; |
| 296 | let total = (end - start + 1) as u32; |
| 297 | let initial = ExportProgress { |
| 298 | frame: start, |
| 299 | total: total as usize, |
| 300 | saver_name: saver.name.clone(), |
| 301 | current_frame: start.max(0) as u32, |
| 302 | total_frames: total, |
| 303 | label: saver.name, |
| 304 | ..Default::default() |
| 305 | }; |
| 306 | |
| 307 | self.spawn_export_worker(ExportKind::SaverPngs, initial, move |engine, control, notify| { |
| 308 | let t0 = Instant::now(); |
| 309 | match export_saver_png_sequence_with_progress(engine, &comp_snapshot, &opts, Some(control), |p| { |
| 310 | if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { |
| 311 | let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6); |
| 312 | eprintln!( |
| 313 | " [export {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}", |
| 314 | p.index + 1, |
| 315 | p.total, |
| 316 | p.saver_name, |
| 317 | p.frame, |
| 318 | p.eval_ms, |
| 319 | fps, |
| 320 | p.out_path.display() |
| 321 | ); |
| 322 | } |
| 323 | notify(); |
| 324 | }) { |
| 325 | Ok(summary) => { |
| 326 | let secs = (summary.total_ms / 1000.0).max(1e-6); |
| 327 | Ok(format!( |
| 328 | "Exported {} PNGs via {} ({:.1} fps)", |
| 329 | summary.frames_written, |
| 330 | summary.saver_name, |
| 331 | summary.frames_written as f64 / secs |
| 332 | )) |
| 333 | } |
| 334 | Err(e) if e == "Cancelled" => Err(e), |
| 335 | Err(e) => Err(format!("Export failed: {e}")), |
| 336 | } |
| 337 | }) |
| 338 | } |
| 339 | |
| 340 | pub(crate) fn export_viewer_mp4(&mut self, slot: usize) -> Result<String, String> { |
| 341 | if self.active_export.is_some() { |
| 342 | let msg = "Export already in progress".to_owned(); |
| 343 | self.set_notice(msg.clone()); |
| 344 | return Err(msg); |
| 345 | } |
| 346 | let Some(target) = self.viewers[slot].viewed_node else { |
| 347 | let msg = format!("Viewer {} has no node loaded", slot + 1); |
| 348 | self.set_notice(msg.clone()); |
| 349 | return Err(msg); |
| 350 | }; |
| 351 | let [in_f, out_f] = self.playback.effective_preview_range(&self.comp); |
| 352 | let node_name = self.comp.node(target).name.clone(); |
| 353 | let default_name = format!( |
| 354 | "{}_{}_f{}-{}.mp4", |
| 355 | sanitize_filename(&self.comp.name), |
| 356 | sanitize_filename(&node_name), |
| 357 | in_f, |
| 358 | out_f |
| 359 | ); |
| 360 | let Some(mut path) = native_save_file_dialog("Export Preview MP4 / ProRes", &default_name) else { |
| 361 | return Err("Export cancelled".to_owned()); |
| 362 | }; |
| 363 | if path.extension().is_none() { |
| 364 | path.set_extension("mp4"); |
| 365 | } |
| 366 | let codec = if path |
| 367 | .extension() |
| 368 | .and_then(|e| e.to_str()) |
| 369 | .is_some_and(|e| e.eq_ignore_ascii_case("mov")) |
| 370 | { |
| 371 | VideoCodec::ProRes422 |
| 372 | } else { |
| 373 | VideoCodec::H264Share |
| 374 | }; |
| 375 | |
| 376 | let comp_snapshot = self.comp.clone(); |
| 377 | let opts = VideoExportOptions { |
| 378 | target, |
| 379 | out_path: path.clone(), |
| 380 | range: [in_f, out_f], |
| 381 | codec, |
| 382 | crf: 26, |
| 383 | max_height: None, |
| 384 | include_audio: true, |
| 385 | hiq: self.engine.hiq, |
| 386 | proxy_scale: self.engine.proxy_scale, |
| 387 | }; |
| 388 | let total = (out_f - in_f + 1).max(1) as u32; |
| 389 | let label = match codec { |
| 390 | VideoCodec::ProRes422 | VideoCodec::ProRes4444 => format!("{node_name} (ProRes)"), |
| 391 | VideoCodec::H264Share => format!("{node_name} (MP4)"), |
| 392 | }; |
| 393 | let initial = ExportProgress { |
| 394 | frame: in_f, |
| 395 | total: total as usize, |
| 396 | out_path: path, |
| 397 | saver_name: node_name, |
| 398 | current_frame: in_f.max(0) as u32, |
| 399 | total_frames: total, |
| 400 | label, |
| 401 | ..Default::default() |
| 402 | }; |
| 403 | |
| 404 | self.spawn_export_worker(ExportKind::ViewerVideo, initial, move |engine, control, notify| { |
| 405 | let t0 = Instant::now(); |
| 406 | match export_node_video_ffmpeg_with_progress(engine, &comp_snapshot, &opts, Some(control), |p| { |
| 407 | if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { |
| 408 | let fps = (p.index + 1) as f64 / t0.elapsed().as_secs_f64().max(1e-6); |
| 409 | eprintln!( |
| 410 | " [video {}/{}] {} f{:04} ({:.1}ms, {:.1} fps) -> {}", |
| 411 | p.index + 1, |
| 412 | p.total, |
| 413 | p.saver_name, |
| 414 | p.frame, |
| 415 | p.eval_ms, |
| 416 | fps, |
| 417 | p.out_path.display() |
| 418 | ); |
| 419 | } |
| 420 | notify(); |
| 421 | }) { |
| 422 | Ok(summary) => { |
| 423 | let mb = summary.file_bytes as f64 / (1024.0 * 1024.0); |
| 424 | let audio_tag = if summary.has_audio { " + audio" } else { "" }; |
| 425 | Ok(format!( |
| 426 | "Exported {} frames{audio_tag} ({mb:.2} MB) -> {}", |
| 427 | summary.frames_written, |
| 428 | summary.out_path.file_name().and_then(|n| n.to_str()).unwrap_or("video") |
| 429 | )) |
| 430 | } |
| 431 | Err(e) if e == "Cancelled" => Err(e), |
| 432 | Err(e) => Err(format!("Video export failed: {e}")), |
| 433 | } |
| 434 | }) |
| 435 | } |
| 436 | |
| 437 | pub(crate) fn save_viewer_frame_png(&mut self, slot: usize) -> Result<String, String> { |
| 438 | let Some(target) = self.viewers[slot].viewed_node else { |
| 439 | let msg = format!("Viewer {} has no node loaded", slot + 1); |
| 440 | self.set_notice(msg.clone()); |
| 441 | return Err(msg); |
| 442 | }; |
| 443 | let frame_f = self.playback.current_frame; |
| 444 | let frame_i = frame_f.round() as i64; |
| 445 | let node_name = self.comp.node(target).name.clone(); |
| 446 | let default_name = format!( |
| 447 | "{}_{}_f{}.png", |
| 448 | sanitize_filename(&self.comp.name), |
| 449 | sanitize_filename(&node_name), |
| 450 | frame_i |
| 451 | ); |
| 452 | let Some(mut path) = native_save_file_dialog("Save Frame PNG", &default_name) else { |
| 453 | return Err("Save Frame cancelled".to_owned()); |
| 454 | }; |
| 455 | if path.extension().is_none() { |
| 456 | path.set_extension("png"); |
| 457 | } |
| 458 | match export_node_frame_png(&mut self.engine, &self.comp, target, frame_f, &path) { |
| 459 | Ok(saved) => { |
| 460 | let msg = format!("Saved frame f{frame_i} PNG"); |
| 461 | eprintln!("{msg} -> {}", saved.display()); |
| 462 | self.set_notice(msg.clone()); |
| 463 | Ok(msg) |
| 464 | } |
| 465 | Err(e) => { |
| 466 | let err = format!("Save PNG failed: {e}"); |
| 467 | eprintln!("{err}"); |
| 468 | self.set_notice(err.clone()); |
| 469 | Err(err) |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | } |