forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc439c14Tahinli25 days ago1006 commits

sequence.rs179 lines, 7.8 KiBHistoryRawDownload
1//! Numbered still runs: `shot_0001.png`, `shot_0002.png`, ... read as one picture track.
2//!
3//! Importing one file of a run (two or more frames, the same stem, digit width and extension)
4//! makes ONE source whose "file" is a spelling that names the whole run, `shot_[0001-0010].png`,
5//! in the run's folder. The spelling is not a file: it is parsed by [`Run::parse`] and never
6//! opened, as [`crate::generate`] does for its generators. [`crate::decode::Still`] reads frame
7//! `k` of the run when it is asked for it ([`Run::frame`]), so a run of a thousand frames costs
8//! one decode per frame shown and nothing at import beyond a directory listing.
9//!
10//! A run's frames are taken at the timeline's rate: frame `k` is the picture for the `k`th frame
11//! of the clip, so a run of ten frames is a clip of ten frames.
12
13use std::path::{Path, PathBuf};
14
15/// One numbered run of still frames.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct Run {
18 /// The folder the frames live in.
19 pub dir: PathBuf,
20 /// The name before the number: `shot_` for `shot_0001.png`.
21 pub stem: String,
22 /// The extension as the files spell it (`png`, `JPG`).
23 pub ext: String,
24 /// How many digits the numbers are padded to.
25 pub digits: usize,
26 /// The first number of the run.
27 pub first: u32,
28 /// How many frames the run holds (two or more).
29 pub count: u32,
30}
31
32/// The extensions a numbered run may be spelled with: the still formats this engine decodes.
33fn is_still_ext(ext: &str) -> bool {
34 matches!(ext.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "webp")
35}
36
37/// Splits `shot_0001.png` into `("shot_", "0001", "png")`, for a name whose stem ends in digits.
38fn split_name(path: &Path) -> Option<(String, String, String)> {
39 let stem = path.file_stem()?.to_str()?;
40 let ext = path.extension()?.to_str()?;
41 if !is_still_ext(ext) {
42 return None;
43 }
44 let digits = stem.len() - stem.trim_end_matches(|c: char| c.is_ascii_digit()).len();
45 if digits == 0 {
46 return None;
47 }
48 let (prefix, number) = stem.split_at(stem.len() - digits);
49 Some((prefix.to_string(), number.to_string(), ext.to_string()))
50}
51
52impl Run {
53 /// The run `path` belongs to, read from the folder beside it: the contiguous numbers that
54 /// share its stem, digit width and extension. `None` for a file with no number in its name,
55 /// an extension that is not a still format, or a number with no neighbour to make a run of
56 /// two. The file itself need not be the first frame.
57 pub fn detect(path: &Path) -> Option<Self> {
58 if Self::parse(path).is_some() {
59 return None; // already a spelled run: nothing to detect
60 }
61 let (stem, number, ext) = split_name(path)?;
62 let digits = number.len();
63 let at: u32 = number.parse().ok()?;
64 let dir = path.parent().map_or_else(|| PathBuf::from("."), Path::to_path_buf);
65 let mut taken = std::collections::BTreeSet::new();
66 for entry in std::fs::read_dir(&dir).ok()?.flatten() {
67 let other = entry.path();
68 let Some((s, n, e)) = split_name(&other) else { continue };
69 if s == stem && e.eq_ignore_ascii_case(&ext) && n.len() == digits && let Ok(v) = n.parse::<u32>() {
70 taken.insert(v);
71 }
72 }
73 if !taken.contains(&at) {
74 return None;
75 }
76 let mut first = at;
77 while first > 0 && taken.contains(&(first - 1)) {
78 first -= 1;
79 }
80 let mut last = at;
81 while taken.contains(&(last + 1)) {
82 last += 1;
83 }
84 let count = last - first + 1;
85 (count >= 2).then_some(Self { dir, stem, ext, digits, first, count })
86 }
87
88 /// The run a spelling names (`dir/shot_[0001-0010].png`), with no file read. `None` for any
89 /// other path, so a real file is never mistaken for a run.
90 pub fn parse(path: &Path) -> Option<Self> {
91 let name = path.file_name()?.to_str()?;
92 let ext_at = name.rfind('.')?;
93 let (head, ext) = (&name[..ext_at], &name[ext_at + 1..]);
94 if !is_still_ext(ext) || !head.ends_with(']') {
95 return None;
96 }
97 let open = head.rfind('[')?;
98 let (stem, range) = (&head[..open], &head[open + 1..head.len() - 1]);
99 let (lo, hi) = range.split_once('-')?;
100 if lo.len() != hi.len() || lo.is_empty() || !lo.bytes().chain(hi.bytes()).all(|b| b.is_ascii_digit()) {
101 return None;
102 }
103 let (first, last): (u32, u32) = (lo.parse().ok()?, hi.parse().ok()?);
104 if last < first || last - first >= u32::MAX - 1 {
105 return None;
106 }
107 Some(Self {
108 dir: path.parent().map_or_else(|| PathBuf::from("."), Path::to_path_buf),
109 stem: stem.to_string(),
110 ext: ext.to_string(),
111 digits: lo.len(),
112 first,
113 count: last - first + 1,
114 })
115 }
116
117 /// The spelling of this run: the one name a source carries for the whole run.
118 pub fn spelled(&self) -> PathBuf {
119 let last = self.first + self.count - 1;
120 self.dir.join(format!(
121 "{}[{:0w$}-{:0w$}].{}",
122 self.stem,
123 self.first,
124 last,
125 self.ext,
126 w = self.digits
127 ))
128 }
129
130 /// The file of frame `k` of the run. A `k` past the last frame is the last frame: a clip
131 /// held longer than its run holds its final picture rather than reading a file that is not
132 /// there.
133 pub fn frame(&self, k: u32) -> PathBuf {
134 let n = self.first + k.min(self.count - 1);
135 self.dir.join(format!("{}{:0w$}.{}", self.stem, n, self.ext, w = self.digits))
136 }
137}
138
139/// The file a path reads its picture from: frame 0 of a run's spelling, the path itself otherwise.
140/// For the header reads (size, EXIF turn) that want one picture and not the whole run.
141pub fn first_frame(path: &Path) -> PathBuf {
142 Run::parse(path).map_or_else(|| path.to_path_buf(), |r| r.frame(0))
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148
149 /// A spelling names its whole run and parses back to it, a real file is never read as a
150 /// spelling, and one frame of a run on disk finds the run around it and nothing else.
151 #[test]
152 fn a_run_is_spelled_back_and_found_from_one_of_its_frames() {
153 let run = Run { dir: "/clips".into(), stem: "shot_".into(), ext: "png".into(), digits: 4, first: 1, count: 10 };
154 let spelled = run.spelled();
155 assert_eq!(spelled, PathBuf::from("/clips/shot_[0001-0010].png"));
156 assert_eq!(Run::parse(&spelled), Some(run.clone()));
157 assert_eq!(run.frame(9), PathBuf::from("/clips/shot_0010.png"));
158 assert_eq!(run.frame(40), PathBuf::from("/clips/shot_0010.png"), "past the end holds the last frame");
159 for name in ["shot_0001.png", "shot_[0001-0010].mp4", "shot_[1-10].png", "shot_[0001-0010]", "a[x-y].png"] {
160 assert!(Run::parse(Path::new(&format!("/clips/{name}"))).is_none(), "{name}");
161 }
162
163 let dir = std::env::temp_dir().join(format!("edith-seq-detect-{}", std::process::id()));
164 let _ = std::fs::remove_dir_all(&dir);
165 std::fs::create_dir_all(&dir).unwrap();
166 // 1..=3 are a run; 5 stands alone; a different stem and a different width do not join it.
167 for n in [1, 2, 3, 5] {
168 std::fs::write(dir.join(format!("f_{n:04}.png")), b"x").unwrap();
169 }
170 std::fs::write(dir.join("g_0004.png"), b"x").unwrap();
171 std::fs::write(dir.join("f_4.png"), b"x").unwrap();
172 let found = Run::detect(&dir.join("f_0002.png")).expect("a run of three");
173 assert_eq!((found.first, found.count, found.digits), (1, 3, 4));
174 assert!(Run::detect(&dir.join("f_0005.png")).is_none(), "a lone frame is not a run");
175 assert!(Run::detect(&dir.join("g_0004.png")).is_none());
176 assert!(Run::detect(&dir.join("f_4.png")).is_none());
177 let _ = std::fs::remove_dir_all(&dir);
178 }
179}