forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export_queue.rs365 lines, 12.8 KiBHistoryRawDownload
1//! The export queue: exports set up now and run later, one after another.
2//! Each job owns the timeline as it was when it was added, so editing on
3//! afterwards never changes a queued file. This module is only the state
4//! machine; the player starts the workers and polls them
5//! (`Player::poll_queue`), which keeps every rule here testable without a
6//! window.
7
8use engine::export::ExportSettings;
9use engine::project::Project;
10use engine::{ExportHandle, VideoMeta};
11use std::path::{Path, PathBuf};
12use std::time::Instant;
13
14/// Where a queued job stands.
15#[derive(Debug, Clone, PartialEq)]
16pub(crate) enum JobState {
17 Waiting,
18 Running,
19 Done { bytes: u64, wall_secs: f64 },
20 Failed(String),
21 Cancelled,
22}
23
24/// The timeline and settings a job writes from, taken when it was added.
25pub(crate) struct Snapshot {
26 pub project: Project,
27 pub meta: VideoMeta,
28 pub settings: ExportSettings,
29 pub sample_rate: Option<u32>,
30}
31
32pub(crate) struct QueueJob {
33 pub id: u64,
34 pub out: PathBuf,
35 /// Format, preset and length in plain words, for the row.
36 pub summary: String,
37 pub state: JobState,
38 /// Dropped once the worker has it (or the job is cancelled).
39 pub snapshot: Option<Snapshot>,
40 pub handle: Option<ExportHandle>,
41 pub started: Option<Instant>,
42 /// Cancel was asked while the worker was running: it settles as Cancelled.
43 pub cancelling: bool,
44}
45
46#[derive(Default)]
47pub(crate) struct ExportQueue {
48 pub jobs: Vec<QueueJob>,
49 next_id: u64,
50 /// "Start queue" was pressed: the next waiting job starts whenever nothing
51 /// else is encoding. Cleared by "Pause after this job" and when the queue
52 /// runs dry.
53 go: bool,
54}
55
56impl ExportQueue {
57 pub(crate) fn add(&mut self, out: PathBuf, summary: String, snapshot: Snapshot) -> u64 {
58 self.next_id += 1;
59 self.jobs.push(QueueJob {
60 id: self.next_id,
61 out,
62 summary,
63 state: JobState::Waiting,
64 snapshot: Some(snapshot),
65 handle: None,
66 started: None,
67 cancelling: false,
68 });
69 self.next_id
70 }
71
72 pub(crate) fn job(&self, id: u64) -> Option<&QueueJob> {
73 self.jobs.iter().find(|j| j.id == id)
74 }
75
76 fn job_mut(&mut self, id: u64) -> Option<&mut QueueJob> {
77 self.jobs.iter_mut().find(|j| j.id == id)
78 }
79
80 pub(crate) fn waiting(&self) -> usize {
81 self.jobs.iter().filter(|j| j.state == JobState::Waiting).count()
82 }
83
84 pub(crate) fn running_id(&self) -> Option<u64> {
85 self.jobs.iter().find(|j| j.state == JobState::Running).map(|j| j.id)
86 }
87
88 /// Jobs still to be written: waiting or running.
89 pub(crate) fn unfinished(&self) -> usize {
90 self.waiting() + usize::from(self.running_id().is_some())
91 }
92
93 pub(crate) fn finished(&self) -> usize {
94 self.jobs.len() - self.unfinished()
95 }
96
97 /// Whether the queue is going: started and not yet dry. A direct Export
98 /// then joins the end of the queue.
99 pub(crate) fn is_going(&self) -> bool {
100 self.go && self.unfinished() > 0
101 }
102
103 pub(crate) fn start(&mut self) {
104 self.go = true;
105 }
106
107 /// The running job finishes; nothing after it starts.
108 pub(crate) fn pause(&mut self) {
109 self.go = false;
110 }
111
112 /// The job to start now, if any: the queue is going, no worker of the
113 /// queue is writing and nothing else (`blocked`) is encoding.
114 pub(crate) fn next_ready(&self, blocked: bool) -> Option<u64> {
115 if !self.go || blocked || self.running_id().is_some() {
116 return None;
117 }
118 self.jobs.iter().find(|j| j.state == JobState::Waiting).map(|j| j.id)
119 }
120
121 /// Takes the snapshot of a waiting job and marks it running.
122 pub(crate) fn begin(&mut self, id: u64) -> Option<(Snapshot, PathBuf)> {
123 let job = self.job_mut(id).filter(|j| j.state == JobState::Waiting)?;
124 let snap = job.snapshot.take()?;
125 job.state = JobState::Running;
126 job.started = Some(Instant::now());
127 Some((snap, job.out.clone()))
128 }
129
130 pub(crate) fn attach(&mut self, id: u64, handle: ExportHandle) {
131 if let Some(job) = self.job_mut(id) {
132 job.handle = Some(handle);
133 }
134 }
135
136 /// The worker's verdict. A job cancelled while it ran settles as
137 /// Cancelled whatever the worker said. Returns the final state.
138 pub(crate) fn settle(&mut self, id: u64, result: Result<(), String>, bytes: u64) -> Option<JobState> {
139 let job = self.job_mut(id).filter(|j| j.state == JobState::Running)?;
140 let wall_secs = job.started.map_or(0., |t| t.elapsed().as_secs_f64());
141 job.handle = None;
142 job.state = match (job.cancelling, result) {
143 (true, _) => JobState::Cancelled,
144 (false, Ok(())) => JobState::Done { bytes, wall_secs },
145 (false, Err(e)) => JobState::Failed(e),
146 };
147 let state = job.state.clone();
148 if self.waiting() == 0 {
149 self.go = false;
150 }
151 Some(state)
152 }
153
154 /// Cancel one job: a waiting one never starts; a running one is asked to
155 /// stop and settles as Cancelled once its worker has cleaned up.
156 pub(crate) fn cancel(&mut self, id: u64) {
157 let Some(job) = self.job_mut(id) else { return };
158 match job.state {
159 JobState::Waiting => {
160 job.snapshot = None;
161 job.state = JobState::Cancelled;
162 }
163 JobState::Running => {
164 job.cancelling = true;
165 if let Some(h) = &job.handle {
166 h.cancel();
167 }
168 }
169 _ => {}
170 }
171 if self.waiting() == 0 && self.running_id().is_none() {
172 self.go = false;
173 }
174 }
175
176 /// Takes a job off the list. A running one cannot be removed, only cancelled.
177 pub(crate) fn remove(&mut self, id: u64) -> bool {
178 let before = self.jobs.len();
179 self.jobs.retain(|j| j.id != id || j.state == JobState::Running);
180 if self.unfinished() == 0 {
181 self.go = false;
182 }
183 self.jobs.len() != before
184 }
185
186 pub(crate) fn clear_finished(&mut self) {
187 self.jobs.retain(|j| matches!(j.state, JobState::Waiting | JobState::Running));
188 }
189
190 /// Cancels everything unfinished (the window is closing).
191 pub(crate) fn cancel_all(&mut self) {
192 let ids: Vec<u64> = self.jobs.iter().map(|j| j.id).collect();
193 for id in ids {
194 self.cancel(id);
195 }
196 }
197
198 /// Files the queue still means to write: a new job must not take the same name.
199 pub(crate) fn claimed(&self, path: &Path) -> bool {
200 self.jobs
201 .iter()
202 .any(|j| matches!(j.state, JobState::Waiting | JobState::Running) && j.out == path)
203 }
204}
205
206/// `out` if nothing is there and the queue has not claimed it; otherwise the
207/// same name with " 2", " 3" ... before the extension. A queued job never
208/// asks about overwriting (the question belongs to the moment of the click),
209/// so it picks a free name instead of replacing anything.
210pub(crate) fn free_name(out: &Path, taken: impl Fn(&Path) -> bool) -> PathBuf {
211 if !taken(out) {
212 return out.to_path_buf();
213 }
214 let stem = out.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
215 let ext = out.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
216 (2..)
217 .map(|n| out.with_file_name(format!("{stem} {n}{ext}")))
218 .find(|p| !taken(p))
219 .unwrap_or_else(|| out.to_path_buf())
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 use engine::PlaybackSession;
226
227 fn session() -> PlaybackSession {
228 let path = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR"));
229 PlaybackSession::open(path).expect("open the fixture")
230 }
231
232 fn snap(s: &PlaybackSession) -> Snapshot {
233 let (project, meta) = s.export_snapshot();
234 Snapshot { project, meta, settings: ExportSettings::default(), sample_rate: s.sample_rate() }
235 }
236
237 fn add(q: &mut ExportQueue, s: &PlaybackSession, name: &str) -> u64 {
238 q.add(PathBuf::from(name), "MP4".into(), snap(s))
239 }
240
241 #[test]
242 fn nothing_starts_until_the_queue_is_started() {
243 let s = session();
244 let mut q = ExportQueue::default();
245 let a = add(&mut q, &s, "a.mp4");
246 assert_eq!(q.next_ready(false), None, "added jobs wait for Start queue");
247 assert!(!q.is_going());
248 q.start();
249 assert_eq!(q.next_ready(false), Some(a));
250 assert_eq!(q.next_ready(true), None, "a direct export encoding holds the queue off");
251 }
252
253 #[test]
254 fn jobs_run_one_at_a_time_in_order_and_settle() {
255 let s = session();
256 let mut q = ExportQueue::default();
257 let (a, b) = (add(&mut q, &s, "a.mp4"), add(&mut q, &s, "b.mp4"));
258 q.start();
259 assert_eq!(q.next_ready(false), Some(a));
260 assert!(q.begin(a).is_some());
261 assert_eq!(q.running_id(), Some(a));
262 assert_eq!(q.next_ready(false), None, "never two at once");
263 assert!(matches!(q.settle(a, Ok(()), 10), Some(JobState::Done { bytes: 10, .. })));
264 assert_eq!(q.next_ready(false), Some(b));
265 assert!(q.begin(b).is_some());
266 assert!(matches!(q.settle(b, Err("disk full".into()), 0), Some(JobState::Failed(e)) if e == "disk full"));
267 assert!(!q.is_going(), "a dry queue stops going");
268 assert_eq!(q.finished(), 2);
269 }
270
271 #[test]
272 fn a_failed_job_does_not_stop_the_next() {
273 let s = session();
274 let mut q = ExportQueue::default();
275 let (a, b) = (add(&mut q, &s, "a.mp4"), add(&mut q, &s, "b.mp4"));
276 q.start();
277 q.begin(a);
278 q.settle(a, Err("bad".into()), 0);
279 assert!(q.is_going());
280 assert_eq!(q.next_ready(false), Some(b));
281 }
282
283 #[test]
284 fn cancel_a_waiting_job_it_never_starts() {
285 let s = session();
286 let mut q = ExportQueue::default();
287 let (a, b) = (add(&mut q, &s, "a.mp4"), add(&mut q, &s, "b.mp4"));
288 q.start();
289 q.cancel(a);
290 assert_eq!(q.job(a).unwrap().state, JobState::Cancelled);
291 assert!(q.job(a).unwrap().snapshot.is_none(), "the copy is let go");
292 assert_eq!(q.next_ready(false), Some(b), "the queue moves past it");
293 assert!(q.begin(a).is_none());
294 }
295
296 #[test]
297 fn cancel_a_running_job_settles_cancelled_whatever_the_worker_says() {
298 let s = session();
299 let mut q = ExportQueue::default();
300 let a = add(&mut q, &s, "a.mp4");
301 q.start();
302 q.begin(a);
303 q.cancel(a);
304 assert_eq!(q.job(a).unwrap().state, JobState::Running, "until its worker has cleaned up");
305 assert!(!q.remove(a), "a running job cannot be removed");
306 assert_eq!(q.settle(a, Err("export cancelled".into()), 0), Some(JobState::Cancelled));
307 }
308
309 #[test]
310 fn pause_lets_the_running_job_finish_and_holds_the_rest() {
311 let s = session();
312 let mut q = ExportQueue::default();
313 let (a, b) = (add(&mut q, &s, "a.mp4"), add(&mut q, &s, "b.mp4"));
314 q.start();
315 q.begin(a);
316 q.pause();
317 q.settle(a, Ok(()), 1);
318 assert_eq!(q.next_ready(false), None, "paused after the job");
319 q.start();
320 assert_eq!(q.next_ready(false), Some(b));
321 }
322
323 #[test]
324 fn remove_and_clear_finished_keep_what_is_still_to_do() {
325 let s = session();
326 let mut q = ExportQueue::default();
327 let (a, b, c) = (add(&mut q, &s, "a.mp4"), add(&mut q, &s, "b.mp4"), add(&mut q, &s, "c.mp4"));
328 q.start();
329 q.begin(a);
330 q.settle(a, Ok(()), 1);
331 assert!(q.remove(c));
332 assert_eq!(q.jobs.len(), 2);
333 q.clear_finished();
334 assert_eq!(q.jobs.iter().map(|j| j.id).collect::<Vec<_>>(), vec![b]);
335 }
336
337 #[test]
338 fn a_job_keeps_the_timeline_it_was_added_with() {
339 let mut s = session();
340 let mut q = ExportQueue::default();
341 let before = s.export_snapshot().0.media_frames();
342 assert!(before > 4);
343 let a = add(&mut q, &s, "a.mp4");
344 // Edit the live timeline after queuing: delete every clip.
345 for lane in s.lanes() {
346 while !s.lane_clips(lane).is_empty() {
347 assert!(s.delete_clip(lane, 0));
348 }
349 }
350 let after = s.export_snapshot().0.media_frames();
351 let queued = q.job(a).unwrap().snapshot.as_ref().unwrap().project.media_frames();
352 assert_eq!(queued, before, "the queued copy is the timeline as added");
353 assert_ne!(after, before, "the live timeline did change");
354 }
355
356 #[test]
357 fn a_queued_name_is_never_one_already_there_or_claimed() {
358 let s = session();
359 let mut q = ExportQueue::default();
360 add(&mut q, &s, "/x/a.mp4");
361 let taken = |p: &Path| q.claimed(p) || p == Path::new("/x/a 2.mp4");
362 assert_eq!(free_name(Path::new("/x/a.mp4"), taken), PathBuf::from("/x/a 3.mp4"));
363 assert_eq!(free_name(Path::new("/x/b.mp4"), taken), PathBuf::from("/x/b.mp4"));
364 }
365}