| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | |
| 15 | |
| 16 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 17 | pub struct Run { |
| 18 | |
| 19 | pub dir: PathBuf, |
| 20 | |
| 21 | pub stem: String, |
| 22 | |
| 23 | pub ext: String, |
| 24 | |
| 25 | pub digits: usize, |
| 26 | |
| 27 | pub first: u32, |
| 28 | |
| 29 | pub count: u32, |
| 30 | } |
| 31 | |
| 32 | |
| 33 | fn is_still_ext(ext: &str) -> bool { |
| 34 | matches!(ext.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "webp") |
| 35 | } |
| 36 | |
| 37 | |
| 38 | fn 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 | |
| 52 | impl Run { |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | pub fn detect(path: &Path) -> Option<Self> { |
| 58 | if Self::parse(path).is_some() { |
| 59 | return None; |
| 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 | |
| 89 | |
| 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 | |
| 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 | |
| 131 | |
| 132 | |
| 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 | |
| 140 | |
| 141 | pub 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)] |
| 146 | mod tests { |
| 147 | use super::*; |
| 148 | |
| 149 | |
| 150 | |
| 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 | |
| 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 | } |