Skip to main content

kitchen_views/video/
sequence.rs

1//! A folder of frames: what high-speed and machine-vision cameras write (one PNG, JPEG or TIFF
2//! per frame). Frames are ordered by the number in their names (`frame_9` before `frame_10`).
3//! Their times come from `timestamps.csv` in the folder when there is one (one time in seconds
4//! per line, or `index,time`), else from a frame rate.
5
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use crate::video::{Frame, FrameTimes, VideoError, VideoInfo, VideoResult, VideoSource};
10
11const EXTENSIONS: [&str; 6] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp"];
12
13/// The timestamp file read beside the frames.
14pub const TIMESTAMPS: &str = "timestamps.csv";
15
16/// An image sequence.
17pub struct Sequence {
18    info: VideoInfo,
19    files: Vec<PathBuf>,
20}
21
22impl Sequence {
23    /// The frames in `dir`; `rate` is used when the folder has no timestamps (30 when none is
24    /// given either).
25    pub fn open(dir: &Path, rate: Option<f64>) -> VideoResult<Self> {
26        let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
27            .map_err(|e| VideoError::io(dir, e))?
28            .flatten()
29            .map(|e| e.path())
30            .filter(|p| p.extension().and_then(|e| e.to_str()).is_some_and(|e| EXTENSIONS.contains(&e.to_ascii_lowercase().as_str())))
31            .collect();
32        files.sort_by(|a, b| natural_key(a).cmp(&natural_key(b)));
33        let first = files.first().ok_or_else(|| VideoError::Unsupported { path: dir.to_path_buf(), hint: "no PNG, JPEG or TIFF frames in this folder".into() })?;
34        let (width, height) = image::image_dimensions(first).map_err(|e| VideoError::io(first, e))?;
35        let times = match read_timestamps(&dir.join(TIMESTAMPS))? {
36            Some(t) if t.len() == files.len() => FrameTimes::from_times(t),
37            Some(t) => {
38                return Err(VideoError::Unsupported {
39                    path: dir.join(TIMESTAMPS),
40                    hint: format!("{} timestamps for {} frames: one per frame", t.len(), files.len()),
41                });
42            }
43            None => FrameTimes::constant(files.len(), rate.unwrap_or(30.0), 0.0),
44        };
45        let ext = first.extension().and_then(|e| e.to_str()).unwrap_or("").to_uppercase();
46        Ok(Self { info: VideoInfo { path: dir.to_path_buf(), width, height, times, format: format!("{ext} sequence") }, files })
47    }
48}
49
50impl VideoSource for Sequence {
51    fn info(&self) -> &VideoInfo {
52        &self.info
53    }
54
55    fn frame(&mut self, index: usize) -> VideoResult<Frame> {
56        let path = self.files.get(index).ok_or(VideoError::NoFrame { index, frames: self.files.len() })?;
57        let image = image::open(path).map_err(|e| VideoError::io(path, e))?.into_rgba8();
58        let (width, height) = image.dimensions();
59        Ok(Frame { index, time: self.info.times.time(index).unwrap_or(0.0), width, height, rgba: Arc::new(image.into_raw()) })
60    }
61}
62
63/// Timestamps from `path`: one number a line, or `index,time` (a header line is skipped). None
64/// when there is no file.
65fn read_timestamps(path: &Path) -> VideoResult<Option<Vec<f64>>> {
66    let Ok(text) = std::fs::read_to_string(path) else { return Ok(None) };
67    let mut out = Vec::new();
68    for (i, line) in text.lines().enumerate() {
69        let last = line.split([',', '\t', ' ']).filter(|f| !f.is_empty()).last().unwrap_or("");
70        match last.parse::<f64>() {
71            Ok(t) => out.push(t),
72            Err(_) if i == 0 || line.trim().is_empty() => {}
73            Err(_) => return Err(VideoError::Unsupported { path: path.to_path_buf(), hint: format!("line {}: not a time in seconds", i + 1) }),
74        }
75    }
76    Ok(Some(out))
77}
78
79/// A name's sort key: its text with every run of digits compared as a number.
80fn natural_key(path: &Path) -> Vec<(String, u64)> {
81    let name = path.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
82    let mut key = Vec::new();
83    let (mut text, mut digits) = (String::new(), String::new());
84    for c in name.chars() {
85        if c.is_ascii_digit() {
86            digits.push(c);
87        } else {
88            if !digits.is_empty() {
89                key.push((std::mem::take(&mut text), digits.parse().unwrap_or(u64::MAX)));
90                digits.clear();
91            }
92            text.push(c);
93        }
94    }
95    key.push((text, digits.parse().unwrap_or(0)));
96    key
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn frames_sort_by_their_numbers_and_take_their_timestamps() {
105        let dir = std::env::temp_dir().join(format!("kitchen-views-seq-{}", std::process::id()));
106        let _ = std::fs::remove_dir_all(&dir);
107        std::fs::create_dir_all(&dir).unwrap();
108        for i in [1, 2, 10] {
109            image::RgbImage::from_pixel(4, 3, image::Rgb([i as u8, 0, 0])).save(dir.join(format!("frame_{i}.png"))).unwrap();
110        }
111        let mut s = Sequence::open(&dir, Some(100.0)).unwrap();
112        assert_eq!((s.info().width, s.info().height, s.info().frames()), (4, 3, 3));
113        assert_eq!(s.frame(2).unwrap().rgba[0], 10, "frame_10 is last");
114        assert!((s.info().times.time(1).unwrap() - 0.01).abs() < 1e-12);
115        std::fs::write(dir.join(TIMESTAMPS), "index,time\n0,5.0\n1,5.02\n2,5.05\n").unwrap();
116        let s = Sequence::open(&dir, None).unwrap();
117        assert_eq!(s.info().times.time(2), Some(5.05));
118        let _ = std::fs::remove_dir_all(&dir);
119    }
120}