Skip to main content

sim_app/
video.rs

1//! Recording the 3D view: numbered PNG frames in `recordings/<date-time>/` under the working directory, made into
2//! `recordings/<date-time>.mp4` by Blender where it is installed. Blender is a big, optional program, so it is
3//! looked for, not depended on; without it the frames stay for any other encoder.
4
5use crate::model::Message;
6use bevy::asset::RenderAssetUsages;
7use bevy::ecs::observer::On;
8use bevy::image::Image;
9use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
10use bevy::render::view::screenshot::ScreenshotCaptured;
11use std::ffi::OsString;
12use std::ops::Range;
13use std::path::{Path, PathBuf};
14use std::process::{Command, Stdio};
15use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
16use std::sync::{Arc, mpsc};
17use std::thread::JoinHandle;
18use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
19
20/// Frames per second of real time, in the frames and in the video.
21pub const FPS: f64 = 30.0;
22
23/// The Blender script that encodes the frames, carried in the program so that it works away from the sources too.
24const SCRIPT: &str = include_str!("../tools/frames_to_mp4.py");
25
26/// A cropped frame, which saves itself into the folder given under each of its numbers.
27type Frame = Box<dyn FnOnce(&Path) -> Result<(), String> + Send>;
28
29/// Frames waiting for the writer at most. Where the disk cannot keep up, more would only grow the memory (a frame
30/// is some megabytes) or, waited for, hold up the window; past this many a frame is dropped and counted instead.
31const QUEUE: usize = 8;
32
33/// A recording in progress. Frames are written on a thread of their own, since encoding a PNG takes about as long
34/// as drawing a frame; that thread then runs Blender, so the window never waits for either.
35pub struct Recording {
36    pub dir: PathBuf,
37    started: Instant,
38    next: u64,
39    /// The size every frame is cut to, fixed at the first: Blender makes the video at the first frame's size.
40    size: Option<[u32; 2]>,
41    frames: mpsc::SyncSender<Frame>,
42    /// Frame numbers dropped since the queue was full.
43    dropped: Arc<AtomicU64>,
44    /// The app is closing: the writer stops at an empty queue rather than waiting for screenshots never taken.
45    closing: Arc<AtomicBool>,
46    writer: JoinHandle<Vec<Message>>,
47}
48
49/// The video being made from a stopped recording; its messages come once Blender is done.
50pub struct Encoding {
51    video: PathBuf,
52    closing: Arc<AtomicBool>,
53    writer: Option<JoinHandle<Vec<Message>>>,
54}
55
56impl Encoding {
57    /// The messages, once, when the video is made or given up on.
58    pub fn poll(&mut self) -> Option<Vec<Message>> {
59        let done = self.writer.take_if(|writer| writer.is_finished())?;
60        Some(done.join().unwrap_or_else(|_| vec![("ui-video-refused", String::new())]))
61    }
62
63    /// At the app's exit: the frames still queued are written, and the video waited for until `deadline`. Blender
64    /// still working then is left to finish on its own, which it does without the app (it reads only the frames,
65    /// all written by then); killing it would lose a video that is nearly made, and waiting longer would hold the
66    /// closing window for minutes. The message says so, and where the video will be.
67    pub fn finish(mut self, deadline: Instant) -> Vec<Message> {
68        self.closing.store(true, Ordering::Relaxed);
69        loop {
70            if let Some(messages) = self.poll() {
71                return messages;
72            }
73            if Instant::now() >= deadline {
74                return vec![("ui-video-detached", self.video.display().to_string())];
75            }
76            std::thread::sleep(Duration::from_millis(20));
77        }
78    }
79}
80
81impl Recording {
82    /// Starts a recording into a new folder named after the time now (UTC: the standard library knows no time zone).
83    pub fn start() -> Result<Self, Message> {
84        // Absolute: Blender reads relative paths from elsewhere, and the messages say where the files are.
85        let refused = |e: std::io::Error| ("ui-video-refused", e.to_string());
86        let dir =
87            new_folder(&std::path::absolute("recordings").map_err(refused)?, SystemTime::now()).map_err(refused)?;
88        let (frames, received) = mpsc::sync_channel::<Frame>(QUEUE);
89        let (dropped, closing) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicBool::new(false)));
90        let (folder, lost, close) = (dir.clone(), dropped.clone(), closing.clone());
91        let writer = std::thread::spawn(move || {
92            let mut failed = None;
93            // Ends when every sender is gone: the recording's, and those of screenshots still on their way. At the
94            // app's exit, once the queue is empty: the screenshots not yet taken then never come.
95            loop {
96                let frame = match received.recv_timeout(Duration::from_millis(50)) {
97                    Ok(frame) => frame,
98                    Err(mpsc::RecvTimeoutError::Timeout) if !close.load(Ordering::Relaxed) => continue,
99                    Err(_) => break,
100                };
101                if let Err(why) = frame(&folder) {
102                    failed.get_or_insert(why);
103                }
104            }
105            let mut messages = vec![match failed {
106                Some(why) => ("ui-video-refused", why),
107                None => encode(&folder),
108            }];
109            match lost.load(Ordering::Relaxed) {
110                0 => {}
111                n => messages.push(("ui-video-dropped", n.to_string())),
112            }
113            messages
114        });
115        Ok(Self { dir, started: Instant::now(), next: 0, size: None, frames, dropped, closing, writer })
116    }
117
118    /// Seconds since the recording started.
119    pub fn seconds(&self) -> f64 {
120        self.started.elapsed().as_secs_f64()
121    }
122
123    /// The frame numbers due by now, at `FPS` of real time. Empty where the window draws faster than that: the
124    /// frame is skipped. More than one where it draws slower: the one picture is repeated under each, so the video
125    /// keeps real time.
126    pub fn due(&mut self) -> Range<u64> {
127        let until = (self.seconds() * FPS) as u64 + 1;
128        let due = self.next..until.max(self.next);
129        self.next = due.end;
130        due
131    }
132
133    /// What saves a screenshot of the window as the frames `numbers`, cut to the view at `view` (left, top, width,
134    /// height in physical pixels), for `Screenshot`'s `observe`. Every frame has the first one's size, made even
135    /// (H.264 stores colour at half resolution), however the window or the panels change meanwhile (`cut`); `fill`
136    /// is the window's clear colour, for where the view got smaller.
137    pub fn saver(
138        &mut self,
139        view: [u32; 4],
140        fill: [u8; 4],
141        numbers: Range<u64>,
142    ) -> impl FnMut(On<ScreenshotCaptured>) + use<> {
143        let size = *self.size.get_or_insert([view[2] & !1, view[3] & !1]);
144        let (frames, dropped) = (self.frames.clone(), self.dropped.clone());
145        move |captured| {
146            let Ok(window) = captured.image.clone().try_into_dynamic() else { return };
147            let window = window.to_rgba8();
148            let pixels = cut(&window, [window.width(), window.height()], view, size, fill);
149            let extent = Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 };
150            let picture = Image::new(
151                extent,
152                TextureDimension::D2,
153                pixels,
154                TextureFormat::Rgba8UnormSrgb,
155                RenderAssetUsages::default(),
156            );
157            let Ok(picture) = picture.try_into_dynamic() else { return };
158            let picture = picture.to_rgb8();
159            let numbers = numbers.clone();
160            let count = numbers.end - numbers.start;
161            let save = move |folder: &Path| {
162                save_numbered(folder, numbers, |file| picture.save(file).map_err(|e| e.to_string()))
163            };
164            // Never waits: a full queue would hold up the window until the disk caught up. The numbers left out are
165            // held by the frame before when the script encodes (`frames_to_mp4.py`), so the video keeps real time.
166            if frames.try_send(Box::new(save)).is_err() {
167                dropped.fetch_add(count, Ordering::Relaxed);
168            }
169        }
170    }
171
172    /// Stops recording; the video is made once the last frames are written.
173    pub fn stop(self) -> Encoding {
174        Encoding { video: self.dir.with_extension("mp4"), closing: self.closing, writer: Some(self.writer) }
175    }
176}
177
178/// What saves a screenshot of the window, cut to `area` (left, top, width, height in physical pixels: a plot), as the
179/// PNG file `path`, for `Screenshot`'s `observe`; what it says (saved, or why not) goes into `said`.
180pub fn picture_saver(
181    area: [u32; 4],
182    path: PathBuf,
183    said: Arc<std::sync::Mutex<Vec<Message>>>,
184) -> impl FnMut(On<ScreenshotCaptured>) + use<> {
185    move |captured| {
186        let saved = (|| -> Result<(), String> {
187            let window = captured.image.clone().try_into_dynamic().map_err(|e| e.to_string())?.to_rgba8();
188            let size = [area[2].max(1), area[3].max(1)];
189            let pixels = cut(&window, [window.width(), window.height()], area, size, [0, 0, 0, 255]);
190            let extent = Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 };
191            let picture = Image::new(
192                extent,
193                TextureDimension::D2,
194                pixels,
195                TextureFormat::Rgba8UnormSrgb,
196                RenderAssetUsages::default(),
197            );
198            let picture = picture.try_into_dynamic().map_err(|e| e.to_string())?;
199            picture.to_rgb8().save(&path).map_err(|e| e.to_string())
200        })();
201        let message = match saved {
202            Ok(()) => ("ui-plot-saved", path.display().to_string()),
203            Err(e) => ("ui-export-failed", format!("{}: {e}", path.display())),
204        };
205        if let Ok(mut said) = said.lock() {
206            said.push(message);
207        }
208    }
209}
210
211/// A new folder in `parent`, named after `now`; a recording started in the same second gets "_2", "_3" and so on,
212/// since its frames and video would otherwise go over the first one's.
213fn new_folder(parent: &Path, now: SystemTime) -> std::io::Result<PathBuf> {
214    std::fs::create_dir_all(parent)?;
215    let name = timestamp(now);
216    let mut n = 1;
217    loop {
218        let dir = parent.join(if n == 1 { name.clone() } else { format!("{name}_{n}") });
219        // `create_dir`, not `create_dir_all`: it fails on a folder already there, which is how a taken name shows.
220        match std::fs::create_dir(&dir) {
221            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
222            made => return made.map(|()| dir),
223        }
224    }
225}
226
227/// The view at `view` (left, top, width, height) in a window's RGBA picture `[width, height]` across, cut to `size`:
228/// from the view's top left, as much of the view as fits in `size` and in the picture, the rest `fill`.
229fn cut(
230    window: &[u8],
231    [width, height]: [u32; 2],
232    [left, top, view_width, view_height]: [u32; 4],
233    size: [u32; 2],
234    fill: [u8; 4],
235) -> Vec<u8> {
236    let (left, top) = (left.min(width) as usize, top.min(height) as usize);
237    let (width, size_x) = (width as usize, size[0] as usize);
238    let across = (view_width as usize).min(size_x).min(width - left);
239    let down = (view_height.min(size[1]) as usize).min(height as usize - top);
240    let mut out = fill.repeat(size_x * size[1] as usize);
241    for y in 0..down {
242        let from = ((top + y) * width + left) * 4;
243        out[y * size_x * 4..][..across * 4].copy_from_slice(&window[from..][..across * 4]);
244    }
245    out
246}
247
248/// Saves one picture as each of the frames `numbers` in `folder`: encoded once by `write`, then copied, since a
249/// repeated frame is the same file and a copy is far quicker than encoding it again.
250fn save_numbered(
251    folder: &Path,
252    numbers: Range<u64>,
253    write: impl FnOnce(&Path) -> Result<(), String>,
254) -> Result<(), String> {
255    let file = |n: u64| folder.join(format!("{n:06}.png"));
256    let first = file(numbers.start);
257    write(&first)?;
258    for n in numbers.skip(1) {
259        std::fs::copy(&first, file(n)).map_err(|e| e.to_string())?;
260    }
261    Ok(())
262}
263
264/// Runs Blender on the frames in `folder`, into `folder` with ".mp4"; says where the video is, or where the frames
265/// are where there is no Blender or it failed.
266fn encode(folder: &Path) -> Message {
267    let frames = ("ui-video-frames", folder.display().to_string());
268    let Some(blender) = blender() else { return frames };
269    let script = folder.with_file_name("frames_to_mp4.py");
270    let video = folder.with_extension("mp4");
271    if std::fs::write(&script, SCRIPT).is_err() {
272        return frames;
273    }
274    let mut command = Command::new(blender);
275    command.args(["--background", "--factory-startup", "--python"]).arg(&script).arg("--").arg(folder).arg(&video);
276    command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
277    #[cfg(windows)]
278    {
279        // No console window flashing up over the app.
280        use std::os::windows::process::CommandExt;
281        command.creation_flags(0x0800_0000);
282    }
283    match command.status() {
284        Ok(status) if status.success() && video.is_file() => ("ui-video-saved", video.display().to_string()),
285        _ => ("ui-video-failed", folder.display().to_string()),
286    }
287}
288
289/// Blender: the environment variable BLENDER, else the newest of the standard installs on Windows.
290fn blender() -> Option<PathBuf> {
291    find_blender(std::env::var_os("BLENDER"), Path::new(r"C:\Program Files\Blender Foundation"))
292}
293
294/// `named` where that is a file, else the newest Blender in `installs`. A BLENDER naming no file (an install moved
295/// or removed) is passed over, so that the message says no Blender was found rather than that Blender failed.
296fn find_blender(named: Option<OsString>, installs: &Path) -> Option<PathBuf> {
297    if let Some(path) = named.map(PathBuf::from).filter(|path| path.is_file()) {
298        return Some(path);
299    }
300    let installs = std::fs::read_dir(installs).ok()?;
301    let found = installs.flatten().filter_map(|entry| {
302        let name = entry.file_name().into_string().ok()?;
303        // "Blender 5.2" → [5, 2], so that 5.10 counts as newer than 5.9.
304        let version: Vec<u32> =
305            name.strip_prefix("Blender ")?.split('.').map(|n| n.parse().ok()).collect::<Option<_>>()?;
306        let exe = entry.path().join("blender.exe");
307        exe.is_file().then_some((version, exe))
308    });
309    found.max_by(|a, b| a.0.cmp(&b.0)).map(|(_, exe)| exe)
310}
311
312/// "2026-11-13_08-15-30" for now, in UTC: for names of files saved, so that one does not overwrite the last.
313pub fn now_stamp() -> String {
314    timestamp(SystemTime::now())
315}
316
317/// "2026-11-13_08-15-30" for a time, in UTC.
318fn timestamp(time: SystemTime) -> String {
319    let seconds = time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
320    let (days, rest) = (seconds / 86_400, seconds % 86_400);
321    // Days since 1970 to the civil date (Howard Hinnant's algorithm).
322    let z = days as i64 + 719_468;
323    let era = z.div_euclid(146_097);
324    let doe = z - era * 146_097;
325    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
326    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
327    let mp = (5 * doy + 2) / 153;
328    let day = doy - (153 * mp + 2) / 5 + 1;
329    let month = if mp < 10 { mp + 3 } else { mp - 9 };
330    let year = yoe + era * 400 + i64::from(month <= 2);
331    format!("{year:04}-{month:02}-{day:02}_{:02}-{:02}-{:02}", rest / 3600, rest % 3600 / 60, rest % 60)
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use std::time::Duration;
338
339    #[test]
340    fn names_the_folder_after_the_date_and_time() {
341        assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01_00-00-00");
342        // 2024-02-29 23:59:58, a leap day.
343        assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_198)), "2024-02-29_23-59-58");
344    }
345
346    /// A folder of its own for the test, empty.
347    fn scratch(name: &str) -> PathBuf {
348        let dir = std::env::temp_dir().join(format!("sim-app-video-{name}-{}", std::process::id()));
349        let _ = std::fs::remove_dir_all(&dir);
350        std::fs::create_dir_all(&dir).unwrap();
351        dir
352    }
353
354    /// Two recordings started in the same second get folders of their own (and so videos of their own); they used
355    /// to share one, the second writing over the first one's frames.
356    #[test]
357    fn recordings_started_in_one_second_get_folders_of_their_own() {
358        let parent = scratch("folders");
359        let now = UNIX_EPOCH + Duration::from_millis(1_709_251_198_250);
360        let first = new_folder(&parent, now).unwrap();
361        let second = new_folder(&parent, now + Duration::from_millis(500)).unwrap();
362        let third = new_folder(&parent, now).unwrap();
363        assert_eq!(first, parent.join("2024-02-29_23-59-58"));
364        assert_eq!(second, parent.join("2024-02-29_23-59-58_2"));
365        assert_eq!(third, parent.join("2024-02-29_23-59-58_3"));
366        assert_ne!(first.with_extension("mp4"), second.with_extension("mp4"));
367        std::fs::remove_dir_all(&parent).unwrap();
368    }
369
370    /// Every frame is cut to the size the first one fixed, even, whether the view later grew, shrank or moved, or
371    /// the window got narrower than the cut: the view from its top left, the rest the fill.
372    #[test]
373    fn frames_keep_the_first_ones_even_size() {
374        // A window whose every pixel tells where it is.
375        let window = |w: u32, h: u32| {
376            (0..h).flat_map(|y| (0..w).flat_map(move |x| [x as u8, y as u8, 0, 255])).collect::<Vec<u8>>()
377        };
378        let pixel = |out: &[u8], x: usize, y: usize| <[u8; 4]>::try_from(&out[(y * 4 + x) * 4..][..4]).unwrap();
379        let fill = [9, 9, 9, 255];
380        // The size as `saver` fixes it: the first view's, made even.
381        let mut fixed = None;
382        let mut size = |view: [u32; 4]| *fixed.get_or_insert([view[2] & !1, view[3] & !1]);
383        // The first view, 5 by 3 at (1, 2) in a window 8 by 6: the cut is 4 by 2.
384        let first = [1, 2, 5, 3];
385        assert_eq!(size(first), [4, 2]);
386        let out = cut(&window(8, 6), [8, 6], first, [4, 2], fill);
387        assert_eq!((out.len(), pixel(&out, 0, 0), pixel(&out, 3, 1)), (4 * 2 * 4, [1, 2, 0, 255], [4, 3, 0, 255]));
388        // Grown and moved: the same size, from the new top left.
389        let grown = [0, 1, 7, 5];
390        assert_eq!(size(grown), [4, 2]);
391        let out = cut(&window(8, 6), [8, 6], grown, [4, 2], fill);
392        assert_eq!((out.len(), pixel(&out, 0, 0)), (32, [0, 1, 0, 255]));
393        // Shrunk to 3 by 1: padded right and below.
394        let out = cut(&window(8, 6), [8, 6], [2, 2, 3, 1], [4, 2], fill);
395        assert_eq!(
396            (out.len(), pixel(&out, 2, 0), pixel(&out, 3, 0), pixel(&out, 0, 1)),
397            (32, [4, 2, 0, 255], fill, fill)
398        );
399        // The window itself narrower than the cut, and a view reaching past it: nothing read outside the picture.
400        let out = cut(&window(3, 1), [3, 1], [1, 0, 9, 9], [4, 2], fill);
401        assert_eq!((out.len(), pixel(&out, 1, 0), pixel(&out, 2, 0)), (32, [2, 0, 0, 255], fill));
402    }
403
404    /// A BLENDER naming no file falls back to the search; it used to be run and to fail, saying that Blender could
405    /// not make the video rather than that none was found.
406    #[test]
407    fn a_missing_blender_variable_falls_back_to_the_search() {
408        let installs = scratch("blender");
409        for version in ["Blender 5.9", "Blender 5.10", "Blender 4.2", "Other"] {
410            std::fs::create_dir_all(installs.join(version)).unwrap();
411            std::fs::write(installs.join(version).join("blender.exe"), b"").unwrap();
412        }
413        let newest = installs.join("Blender 5.10").join("blender.exe");
414        assert_eq!(find_blender(Some(installs.join("gone.exe").into()), &installs), Some(newest.clone()));
415        assert_eq!(find_blender(None, &installs), Some(newest));
416        let named = installs.join("Blender 4.2").join("blender.exe");
417        assert_eq!(find_blender(Some(named.clone().into()), &installs), Some(named));
418        assert_eq!(find_blender(Some(installs.join("gone.exe").into()), &installs.join("none")), None);
419        std::fs::remove_dir_all(&installs).unwrap();
420    }
421
422    /// A frame repeated (the window drew slower than the video's frame rate) is encoded once and copied.
423    #[test]
424    fn a_repeated_frame_is_a_copy() {
425        let folder = scratch("repeat");
426        let mut writes = 0;
427        save_numbered(&folder, 7..10, |file| {
428            writes += 1;
429            std::fs::write(file, b"picture").map_err(|e| e.to_string())
430        })
431        .unwrap();
432        assert_eq!(writes, 1);
433        for n in 7..10 {
434            assert_eq!(std::fs::read(folder.join(format!("{n:06}.png"))).unwrap(), b"picture");
435        }
436        assert!(!folder.join("000010.png").exists());
437        std::fs::remove_dir_all(&folder).unwrap();
438    }
439}