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| {
31                p.extension()
32                    .and_then(|e| e.to_str())
33                    .is_some_and(|e| EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
34            })
35            .collect();
36        files.sort_by(|a, b| natural_key(a).cmp(&natural_key(b)));
37        let first = files.first().ok_or_else(|| VideoError::Unsupported {
38            path: dir.to_path_buf(),
39            hint: "no PNG, JPEG or TIFF frames in this folder".into(),
40        })?;
41        let (width, height) = image::image_dimensions(first).map_err(|e| VideoError::io(first, e))?;
42        let times = match read_timestamps(&dir.join(TIMESTAMPS))? {
43            Some(t) if t.len() == files.len() => FrameTimes::from_times(t),
44            Some(t) => {
45                return Err(VideoError::Unsupported {
46                    path: dir.join(TIMESTAMPS),
47                    hint: format!("{} timestamps for {} frames: one per frame", t.len(), files.len()),
48                });
49            }
50            None => FrameTimes::constant(files.len(), rate.unwrap_or(30.0), 0.0),
51        };
52        let ext = first.extension().and_then(|e| e.to_str()).unwrap_or("").to_uppercase();
53        Ok(Self {
54            info: VideoInfo { path: dir.to_path_buf(), width, height, times, format: format!("{ext} sequence") },
55            files,
56        })
57    }
58}
59
60impl VideoSource for Sequence {
61    fn info(&self) -> &VideoInfo {
62        &self.info
63    }
64
65    fn frame(&mut self, index: usize) -> VideoResult<Frame> {
66        let path = self.files.get(index).ok_or(VideoError::NoFrame { index, frames: self.files.len() })?;
67        let image = image::open(path).map_err(|e| VideoError::io(path, e))?.into_rgba8();
68        let (width, height) = image.dimensions();
69        Ok(Frame {
70            index,
71            time: self.info.times.time(index).unwrap_or(0.0),
72            width,
73            height,
74            rgba: Arc::new(image.into_raw()),
75        })
76    }
77}
78
79/// Timestamps from `path`: one number a line, or `index,time` (a header line is skipped). None
80/// when there is no file.
81fn read_timestamps(path: &Path) -> VideoResult<Option<Vec<f64>>> {
82    let Ok(text) = std::fs::read_to_string(path) else { return Ok(None) };
83    let mut out = Vec::new();
84    for (i, line) in text.lines().enumerate() {
85        let last = line.split([',', '\t', ' ']).filter(|f| !f.is_empty()).last().unwrap_or("");
86        match last.parse::<f64>() {
87            Ok(t) => out.push(t),
88            Err(_) if i == 0 || line.trim().is_empty() => {}
89            Err(_) => {
90                return Err(VideoError::Unsupported {
91                    path: path.to_path_buf(),
92                    hint: format!("line {}: not a time in seconds", i + 1),
93                });
94            }
95        }
96    }
97    Ok(Some(out))
98}
99
100/// A name's sort key: its text with every run of digits compared as a number.
101fn natural_key(path: &Path) -> Vec<(String, u64)> {
102    let name = path.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
103    let mut key = Vec::new();
104    let (mut text, mut digits) = (String::new(), String::new());
105    for c in name.chars() {
106        if c.is_ascii_digit() {
107            digits.push(c);
108        } else {
109            if !digits.is_empty() {
110                key.push((std::mem::take(&mut text), digits.parse().unwrap_or(u64::MAX)));
111                digits.clear();
112            }
113            text.push(c);
114        }
115    }
116    key.push((text, digits.parse().unwrap_or(0)));
117    key
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn frames_sort_by_their_numbers_and_take_their_timestamps() {
126        let dir = std::env::temp_dir().join(format!("kitchen-views-seq-{}", std::process::id()));
127        let _ = std::fs::remove_dir_all(&dir);
128        std::fs::create_dir_all(&dir).unwrap();
129        for i in [1, 2, 10] {
130            image::RgbImage::from_pixel(4, 3, image::Rgb([i as u8, 0, 0]))
131                .save(dir.join(format!("frame_{i}.png")))
132                .unwrap();
133        }
134        let mut s = Sequence::open(&dir, Some(100.0)).unwrap();
135        assert_eq!((s.info().width, s.info().height, s.info().frames()), (4, 3, 3));
136        assert_eq!(s.frame(2).unwrap().rgba[0], 10, "frame_10 is last");
137        assert!((s.info().times.time(1).unwrap() - 0.01).abs() < 1e-12);
138        std::fs::write(dir.join(TIMESTAMPS), "index,time\n0,5.0\n1,5.02\n2,5.05\n").unwrap();
139        let s = Sequence::open(&dir, None).unwrap();
140        assert_eq!(s.info().times.time(2), Some(5.05));
141        let _ = std::fs::remove_dir_all(&dir);
142    }
143}