forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

collect.rs313 lines, 12.0 KiBHistoryRawDownload
1//! Collect a project's media: copy every source the project uses into one folder and point
2//! the project at the copies, so the folder and the `.edith` can be moved or archived together.
3//!
4//! Three steps the window and the MCP server share: [`plan`] reads the sources and decides the
5//! copies, [`copy_all`] makes them (cancellable, with progress), and
6//! [`crate::PlaybackSession::relink_all`] points the project at them as one undo step.
7//! Generated sources (solids, bars, titles' backdrops) are files nowhere and are skipped; a source
8//! whose file is missing is skipped and named; one already inside the folder stays where it is.
9
10use std::io::{Read, Write};
11use std::path::{Path, PathBuf};
12use std::sync::atomic::{AtomicBool, Ordering};
13
14use crate::project::Source;
15
16/// One file to copy, and every source (stream) of the project that plays from it.
17#[derive(Clone, Debug)]
18pub struct Item {
19 pub indices: Vec<usize>,
20 pub from: PathBuf,
21 pub to: PathBuf,
22 pub bytes: u64,
23 /// The copy is already in the folder and is the same bytes: nothing to write.
24 pub present: bool,
25}
26
27#[derive(Clone, Debug, Default)]
28pub struct Plan {
29 pub folder: PathBuf,
30 pub items: Vec<Item>,
31 /// Sources that are generated, not files.
32 pub generated: usize,
33 /// Files the project names that are not on disk.
34 pub offline: Vec<PathBuf>,
35 /// Sources already inside the folder.
36 pub already: usize,
37}
38
39impl Plan {
40 /// Bytes still to write.
41 pub fn bytes(&self) -> u64 {
42 self.items.iter().filter(|i| !i.present).map(|i| i.bytes).sum()
43 }
44}
45
46/// What a finished copy did.
47#[derive(Clone, Debug, Default)]
48pub struct Done {
49 /// `(source index, the copy)`, ready for [`crate::PlaybackSession::relink_all`].
50 pub pairs: Vec<(usize, PathBuf)>,
51 /// Files written now.
52 pub files: usize,
53 pub bytes: u64,
54 created: Vec<PathBuf>,
55}
56
57#[derive(Debug, PartialEq, Eq)]
58pub enum Stop {
59 Cancelled,
60 Failed(String),
61}
62
63/// `<project dir>/<project stem>_media`.
64pub fn default_folder(project: &Path) -> PathBuf {
65 let stem = project.file_stem().map_or_else(|| "project".to_string(), |s| s.to_string_lossy().into_owned());
66 project.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")).join(format!("{stem}_media"))
67}
68
69/// Decides the copies of `sources` into `folder`. Reads file sizes; writes nothing.
70pub fn plan(sources: &[Source], folder: &Path) -> Plan {
71 let mut plan = Plan { folder: folder.to_path_buf(), ..Plan::default() };
72 let real_folder = folder.canonicalize().unwrap_or_else(|_| folder.to_path_buf());
73 let mut taken: Vec<PathBuf> = Vec::new();
74 for (index, source) in sources.iter().enumerate() {
75 if crate::generate::is_generated(&source.path) {
76 plan.generated += 1;
77 continue;
78 }
79 let Ok(meta) = std::fs::metadata(&source.path) else {
80 if !plan.offline.contains(&source.path) {
81 plan.offline.push(source.path.clone());
82 }
83 continue;
84 };
85 if source.path.parent() == Some(real_folder.as_path()) {
86 plan.already += 1;
87 continue;
88 }
89 // Two streams of one file are two sources and one copy.
90 if let Some(item) = plan.items.iter_mut().find(|i| i.from == source.path) {
91 item.indices.push(index);
92 continue;
93 }
94 let (to, present) = destination(&source.path, folder, meta.len(), &taken);
95 taken.push(to.clone());
96 plan.items.push(Item { indices: vec![index], from: source.path.clone(), to, bytes: meta.len(), present });
97 }
98 plan
99}
100
101/// Where `from` lands: its own name in `folder`; if that name is taken by another file (or by
102/// another source of this plan) `name-2.ext`, `name-3.ext`... The same bytes already there are
103/// reused, so collecting twice copies nothing twice.
104fn destination(from: &Path, folder: &Path, len: u64, taken: &[PathBuf]) -> (PathBuf, bool) {
105 let name = from.file_name().map_or_else(|| "media".to_string(), |n| n.to_string_lossy().into_owned());
106 let (stem, ext) = match name.rfind('.') {
107 Some(dot) if dot > 0 => (name[..dot].to_string(), name[dot..].to_string()),
108 _ => (name.clone(), String::new()),
109 };
110 let mut n = 1;
111 loop {
112 let candidate = if n == 1 { folder.join(&name) } else { folder.join(format!("{stem}-{n}{ext}")) };
113 if !taken.contains(&candidate) {
114 match std::fs::metadata(&candidate) {
115 Err(_) => return (candidate, false),
116 Ok(m) if m.len() == len && same_bytes(from, &candidate) => return (candidate, true),
117 Ok(_) => {}
118 }
119 }
120 n += 1;
121 }
122}
123
124fn same_bytes(a: &Path, b: &Path) -> bool {
125 let (Ok(mut fa), Ok(mut fb)) = (std::fs::File::open(a), std::fs::File::open(b)) else {
126 return false;
127 };
128 let (mut ba, mut bb) = (vec![0u8; 1 << 20], vec![0u8; 1 << 20]);
129 loop {
130 let (Ok(na), Ok(nb)) = (read_full(&mut fa, &mut ba), read_full(&mut fb, &mut bb)) else {
131 return false;
132 };
133 if na != nb || ba[..na] != bb[..nb] {
134 return false;
135 }
136 if na == 0 {
137 return true;
138 }
139 }
140}
141
142fn read_full(f: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result<usize> {
143 let mut got = 0;
144 while got < buf.len() {
145 match f.read(&mut buf[got..])? {
146 0 => break,
147 n => got += n,
148 }
149 }
150 Ok(got)
151}
152
153/// Makes the copies of `plan`. `progress(done, total)` counts bytes and is called as the copy
154/// goes; `cancel` is looked at between chunks. A cancel or a failure removes what this call wrote
155/// and returns [`Stop`]; the project is not touched either way.
156pub fn copy_all(plan: &Plan, cancel: &AtomicBool, progress: &mut dyn FnMut(u64, u64)) -> Result<Done, Stop> {
157 let total = plan.bytes();
158 let mut done = Done::default();
159 let mut written = 0u64;
160 let fail = |done: &Done, stop: Stop| {
161 for p in &done.created {
162 let _ = std::fs::remove_file(p);
163 }
164 Err(stop)
165 };
166 if plan.items.iter().any(|i| !i.present)
167 && let Err(e) = std::fs::create_dir_all(&plan.folder)
168 {
169 return Err(Stop::Failed(format!("cannot make {}: {e}", plan.folder.display())));
170 }
171 progress(0, total);
172 for item in &plan.items {
173 if !item.present {
174 let mut name = item.to.file_name().unwrap_or_default().to_os_string();
175 name.push(".edith-part");
176 let part = item.to.with_file_name(name);
177 let result = copy_one(&item.from, &part, cancel, &mut |n| {
178 written += n;
179 progress(written, total);
180 });
181 match result {
182 Ok(()) => {}
183 Err(stop) => {
184 let _ = std::fs::remove_file(&part);
185 return fail(&done, stop);
186 }
187 }
188 if let Err(e) = std::fs::rename(&part, &item.to) {
189 let _ = std::fs::remove_file(&part);
190 return fail(&done, Stop::Failed(format!("cannot write {}: {e}", item.to.display())));
191 }
192 done.created.push(item.to.clone());
193 done.files += 1;
194 done.bytes += item.bytes;
195 }
196 done.pairs.extend(item.indices.iter().map(|&i| (i, item.to.clone())));
197 }
198 Ok(done)
199}
200
201fn copy_one(from: &Path, to: &Path, cancel: &AtomicBool, step: &mut dyn FnMut(u64)) -> Result<(), Stop> {
202 let mut src = std::fs::File::open(from).map_err(|e| Stop::Failed(format!("cannot read {}: {e}", from.display())))?;
203 let mut dst = std::fs::File::create(to).map_err(|e| Stop::Failed(format!("cannot write {}: {e}", to.display())))?;
204 let mut buf = vec![0u8; 1 << 20];
205 loop {
206 if cancel.load(Ordering::Relaxed) {
207 return Err(Stop::Cancelled);
208 }
209 let n = src.read(&mut buf).map_err(|e| Stop::Failed(format!("cannot read {}: {e}", from.display())))?;
210 if n == 0 {
211 break;
212 }
213 dst.write_all(&buf[..n]).map_err(|e| Stop::Failed(format!("cannot write {}: {e}", to.display())))?;
214 step(n as u64);
215 }
216 dst.sync_all().map_err(|e| Stop::Failed(format!("cannot write {}: {e}", to.display())))?;
217 Ok(())
218}
219
220/// `1.4 GB`, `82 MB`, `3 KB`.
221pub fn size_text(bytes: u64) -> String {
222 const UNITS: [(&str, f64); 3] = [("GB", 1e9), ("MB", 1e6), ("KB", 1e3)];
223 for (unit, size) in UNITS {
224 if bytes as f64 >= size {
225 let v = bytes as f64 / size;
226 return if v >= 100. || unit == "KB" { format!("{v:.0} {unit}") } else { format!("{v:.1} {unit}") };
227 }
228 }
229 format!("{bytes} B")
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 fn write(p: &Path, bytes: &[u8]) {
237 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
238 std::fs::write(p, bytes).unwrap();
239 }
240
241 #[test]
242 fn plans_skip_generated_and_offline_and_rename_clashes() {
243 let dir = crate::scratch::Scratch::dir("ve_collect_plan");
244 let (a, b) = (dir.join("one/clip.mp4"), dir.join("two/clip.mp4"));
245 write(&a, b"aaaa");
246 write(&b, b"bbbbbb");
247 let gone = dir.join("gone.mp4");
248 let solid = crate::generate::Gen::named("solid", 64, 64, 25.).unwrap().path();
249 let sources = vec![Source::new(&a, 0), Source::new(&a, 1), Source::new(&b, 0), Source { path: gone.clone(), audio_stream: 0, ..Default::default() }, Source { path: solid, audio_stream: 0, ..Default::default() }];
250 let folder = dir.join("media");
251 let p = plan(&sources, &folder);
252 assert_eq!((p.generated, p.offline.clone(), p.items.len()), (1, vec![gone], 2));
253 assert_eq!(p.items[0].indices, vec![0, 1]);
254 assert_eq!(p.items[0].to, folder.join("clip.mp4"));
255 assert_eq!(p.items[1].to, folder.join("clip-2.mp4"));
256 assert_eq!(p.bytes(), 10);
257
258 let mut seen = 0;
259 let done = copy_all(&p, &AtomicBool::new(false), &mut |d, t| {
260 assert!(d <= t);
261 seen = d;
262 })
263 .expect("copies");
264 assert_eq!((done.files, done.bytes, seen), (2, 10, 10));
265 assert_eq!(done.pairs.len(), 3);
266 assert_eq!(std::fs::read(folder.join("clip-2.mp4")).unwrap(), b"bbbbbb");
267 // Collecting again finds the same bytes there: nothing to write.
268 let again = plan(&sources, &folder);
269 assert!(again.items.iter().all(|i| i.present) && again.bytes() == 0);
270 // And sources already in the folder stay.
271 let moved = vec![Source::new(folder.join("clip.mp4"), 0)];
272 assert_eq!(plan(&moved, &folder).already, 1);
273 }
274
275 #[test]
276 fn a_cancel_leaves_nothing_behind() {
277 let dir = crate::scratch::Scratch::dir("ve_collect_cancel");
278 let a = dir.join("a.bin");
279 write(&a, &vec![7u8; 3 << 20]);
280 let p = plan(&[Source::new(&a, 0)], &dir.join("m"));
281 let cancel = AtomicBool::new(false);
282 let r = copy_all(&p, &cancel, &mut |d, _| {
283 if d > 0 {
284 cancel.store(true, Ordering::Relaxed);
285 }
286 });
287 assert_eq!(r.err(), Some(Stop::Cancelled));
288 assert_eq!(std::fs::read_dir(dir.join("m")).unwrap().count(), 0);
289 }
290
291 #[test]
292 fn sizes_read_plainly() {
293 assert_eq!(size_text(999), "999 B");
294 assert_eq!(size_text(3_400), "3 KB");
295 assert_eq!(size_text(82_000_000), "82.0 MB");
296 assert_eq!(size_text(1_400_000_000), "1.4 GB");
297 }
298
299 #[test]
300 fn collecting_relinks_a_session_in_one_undo_step() {
301 let dir = crate::scratch::Scratch::dir("ve_collect_session");
302 let media = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
303 let mut s = crate::PlaybackSession::open(&media).expect("open test asset");
304 let was = s.sources()[0].path.clone();
305 let p = plan(s.sources(), &dir.join("m"));
306 let done = copy_all(&p, &AtomicBool::new(false), &mut |_, _| {}).expect("copies");
307 assert_eq!(s.relink_all(&done.pairs), 1);
308 assert_eq!(s.sources()[0].path.parent().unwrap().file_name().unwrap(), "m");
309 assert_eq!(s.relink_all(&done.pairs), 0, "already there: no second step");
310 assert!(s.undo());
311 assert_eq!(s.sources()[0].path, was);
312 }
313}