forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB9eac4beTahinli3 months ago20 commits

project.rs497 lines, 16.6 KiBHistoryRawDownload
1//! Edit list: the timeline as a list of source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] is an ordered list of [`Clip`]s, each a half-open `[in, out)`
4//! range of *source* frames. Playing the timeline means playing those ranges
5//! back to back, so timeline frame `t` is found by walking the clips and
6//! consuming their lengths; the mapping is [`Project::map_timeline`] and it is
7//! the only place that conversion lives.
8//!
9//! Two frame spaces meet here and are never mixed: *source* frames index the
10//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
11//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
12//!
13//! Editing is metadata only. [`Project::cut`] splits a clip in two without
14//! changing any timeline->source mapping, so a running decoder stays correct
15//! across a cut; [`Project::delete`] does change the mapping and the caller
16//! must reseek. Every successful edit snapshots the clip list, so
17//! [`Project::undo`] is an exact restore.
18
19/// A half-open `[in_frame, out_frame)` range of source frames. Never empty.
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub struct Clip {
22 pub in_frame: u32,
23 pub out_frame: u32,
24}
25
26impl Clip {
27 /// Frame count; `>= 1` by the never-empty invariant.
28 pub fn len(&self) -> u32 {
29 self.out_frame - self.in_frame
30 }
31}
32
33/// The edit list plus its undo history.
34#[derive(Clone, Debug)]
35pub struct Project {
36 clips: Vec<Clip>,
37 /// Snapshots pushed *before* each successful edit; `undo` pops one.
38 history: Vec<Vec<Clip>>,
39}
40
41impl Project {
42 /// One clip covering the whole file -- the state of a freshly opened video,
43 /// where the timeline is the source. `frame_count` of 0 would break the
44 /// never-empty invariant, so it is clamped to one frame.
45 pub fn single(frame_count: u32) -> Self {
46 Self {
47 clips: vec![Clip {
48 in_frame: 0,
49 out_frame: frame_count.max(1),
50 }],
51 history: Vec::new(),
52 }
53 }
54
55 pub fn clips(&self) -> &[Clip] {
56 &self.clips
57 }
58
59 /// Length of the timeline in frames.
60 pub fn timeline_frames(&self) -> u32 {
61 self.clips.iter().map(Clip::len).sum()
62 }
63
64 /// `(timeline_start, len)` per clip, in order -- what a UI lane needs to
65 /// lay clips out without redoing the cumulative sum.
66 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
67 let mut start = 0;
68 self.clips
69 .iter()
70 .map(|c| {
71 let span = (start, c.len());
72 start += c.len();
73 span
74 })
75 .collect()
76 }
77
78 /// Timeline frame -> `(clip index, source frame)`. `None` past the end.
79 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
80 let mut start = 0;
81 for (i, c) in self.clips.iter().enumerate() {
82 if timeline_frame < start + c.len() {
83 return Some((i, c.in_frame + (timeline_frame - start)));
84 }
85 start += c.len();
86 }
87 None
88 }
89
90 /// Split the clip containing `timeline_frame` so that frame becomes the
91 /// first frame of a new clip. Refused (`false`, no change) at timeline 0,
92 /// at an existing clip boundary, and at or past the end -- all three would
93 /// produce an empty clip. Metadata only: no mapping changes.
94 pub fn cut(&mut self, timeline_frame: u32) -> bool {
95 let Some((idx, source)) = self.map_timeline(timeline_frame) else {
96 return false;
97 };
98 if source == self.clips[idx].in_frame {
99 return false; // start of a clip: nothing to split off
100 }
101 self.history.push(self.clips.clone());
102 let out = self.clips[idx].out_frame;
103 self.clips[idx].out_frame = source;
104 self.clips.insert(
105 idx + 1,
106 Clip {
107 in_frame: source,
108 out_frame: out,
109 },
110 );
111 true
112 }
113
114 /// Insert `clip` so that it starts at `timeline_frame`. Mid-clip the
115 /// containing clip is split there and `clip` goes between the halves; at an
116 /// existing boundary (0 included) it goes in front of the clip that starts
117 /// there; at or past the end of the timeline it is appended -- a paste past
118 /// the end clamps rather than refuses, because there is nothing between the
119 /// end and it. Refused only for an empty `clip`, which the never-empty
120 /// invariant forbids but the public fields still allow a caller to build.
121 ///
122 /// Exactly one history snapshot, so one [`Project::undo`] takes it back --
123 /// hence the splice rather than a `cut` plus an insert. Changes the
124 /// timeline->source mapping: the caller must reseek.
125 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
126 if clip.out_frame <= clip.in_frame {
127 return false;
128 }
129 self.history.push(self.clips.clone());
130 match self.map_timeline(timeline_frame) {
131 Some((idx, source)) if source > self.clips[idx].in_frame => {
132 let out = self.clips[idx].out_frame;
133 self.clips[idx].out_frame = source;
134 self.clips.splice(
135 idx + 1..idx + 1,
136 [
137 clip,
138 Clip {
139 in_frame: source,
140 out_frame: out,
141 },
142 ],
143 );
144 }
145 Some((idx, _)) => self.clips.insert(idx, clip),
146 None => self.clips.push(clip),
147 }
148 true
149 }
150
151 /// Remove a clip and close the gap. Refused for an out-of-range index and
152 /// for the last remaining clip (an empty timeline is undefined this slice).
153 /// Changes the timeline->source mapping: the caller must reseek.
154 pub fn delete(&mut self, idx: usize) -> bool {
155 if idx >= self.clips.len() || self.clips.len() == 1 {
156 return false;
157 }
158 self.history.push(self.clips.clone());
159 self.clips.remove(idx);
160 true
161 }
162
163 /// Restore the clip list from before the last successful edit. `false` when
164 /// there is nothing left to undo.
165 pub fn undo(&mut self) -> bool {
166 match self.history.pop() {
167 Some(prev) => {
168 self.clips = prev;
169 true
170 }
171 None => false,
172 }
173 }
174
175 /// Half-open `(start, end)` segments in *source* seconds, from
176 /// `timeline_frame` to the end of the timeline -- the play list for the
177 /// audio worker. The first entry is partial when the position is mid-clip.
178 /// Empty when the position is past the end or `fps` is not usable.
179 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(f64, f64)> {
180 if !(fps.is_finite() && fps > 0.0) {
181 return Vec::new();
182 }
183 let Some((idx, source)) = self.map_timeline(timeline_frame) else {
184 return Vec::new();
185 };
186 let mut segs = vec![(source as f64 / fps, self.clips[idx].out_frame as f64 / fps)];
187 segs.extend(
188 self.clips[idx + 1..]
189 .iter()
190 .map(|c| (c.in_frame as f64 / fps, c.out_frame as f64 / fps)),
191 );
192 segs
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 const FPS: f64 = 30.0;
201
202 /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built
203 /// through `cut` so the constructor path is exercised too.
204 fn three() -> Project {
205 let mut p = Project::single(9);
206 assert!(p.cut(3));
207 assert!(p.cut(5));
208 assert_eq!(
209 p.clips(),
210 [
211 Clip {
212 in_frame: 0,
213 out_frame: 3
214 },
215 Clip {
216 in_frame: 3,
217 out_frame: 5
218 },
219 Clip {
220 in_frame: 5,
221 out_frame: 9
222 },
223 ]
224 );
225 p
226 }
227
228 #[test]
229 fn single_is_the_whole_file() {
230 let p = Project::single(150);
231 assert_eq!(p.clips().len(), 1);
232 assert_eq!(p.timeline_frames(), 150);
233 assert_eq!(p.clip_spans(), vec![(0, 150)]);
234 // degenerate mapping: timeline == source
235 assert_eq!(p.map_timeline(0), Some((0, 0)));
236 assert_eq!(p.map_timeline(149), Some((0, 149)));
237 assert_eq!(p.map_timeline(150), None);
238 // never-empty invariant survives a bogus frame count
239 assert_eq!(Project::single(0).timeline_frames(), 1);
240 }
241
242 #[test]
243 fn cut_mid_clip_splits() {
244 let mut p = Project::single(9);
245 assert!(p.cut(4));
246 assert_eq!(
247 p.clips(),
248 [
249 Clip {
250 in_frame: 0,
251 out_frame: 4
252 },
253 Clip {
254 in_frame: 4,
255 out_frame: 9
256 },
257 ]
258 );
259 assert_eq!(p.timeline_frames(), 9);
260 }
261
262 #[test]
263 fn cut_refused_at_zero_boundary_and_end() {
264 let mut p = three();
265 let before = p.clips().to_vec();
266 assert!(!p.cut(0), "timeline 0 has nothing before it");
267 assert!(!p.cut(3), "existing boundary");
268 assert!(!p.cut(5), "existing boundary");
269 assert!(!p.cut(9), "one past the last frame");
270 assert!(!p.cut(1_000));
271 assert_eq!(p.clips(), before.as_slice());
272 // one undo lands before the *second* cut, so the refusals pushed nothing
273 assert!(p.undo());
274 assert_eq!(p.clips().len(), 2, "refused cuts push no history");
275 }
276
277 #[test]
278 fn cut_never_changes_the_mapping() {
279 let p = three();
280 let before: Vec<_> = (0..9).map(|f| p.map_timeline(f).unwrap().1).collect();
281 let mut after = p.clone();
282 assert!(after.cut(7));
283 let now: Vec<_> = (0..9).map(|f| after.map_timeline(f).unwrap().1).collect();
284 assert_eq!(before, now);
285 }
286
287 #[test]
288 fn map_timeline_sweeps_every_boundary() {
289 let p = three();
290 assert_eq!(p.timeline_frames(), 9);
291 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
292 // contiguous source here, so the clip index is what actually moves
293 let expect = [
294 (0, (0, 0)),
295 (1, (0, 1)),
296 (2, (0, 2)),
297 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
298 (4, (1, 4)),
299 (5, (2, 5)),
300 (6, (2, 6)),
301 (7, (2, 7)),
302 (8, (2, 8)),
303 ];
304 for (t, want) in expect {
305 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
306 }
307 assert_eq!(p.map_timeline(9), None);
308 }
309
310 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
311 /// anything in `three()` so it is recognisable wherever it lands.
312 const PASTED: Clip = Clip {
313 in_frame: 100,
314 out_frame: 102,
315 };
316
317 #[test]
318 fn paste_mid_clip_splits_around_it() {
319 let mut p = three();
320 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
321 assert_eq!(p.timeline_frames(), 11);
322 assert_eq!(
323 p.clips(),
324 [
325 Clip {
326 in_frame: 0,
327 out_frame: 3
328 },
329 Clip {
330 in_frame: 3,
331 out_frame: 5
332 },
333 Clip {
334 in_frame: 5,
335 out_frame: 6
336 },
337 PASTED,
338 Clip {
339 in_frame: 6,
340 out_frame: 9
341 },
342 ]
343 );
344 // The pasted frames are exactly where they were asked for, and the
345 // split-off remainder resumes after them.
346 assert_eq!(p.map_timeline(6), Some((3, 100)));
347 assert_eq!(p.map_timeline(7), Some((3, 101)));
348 assert_eq!(p.map_timeline(8), Some((4, 6)));
349 }
350
351 #[test]
352 fn paste_at_boundary_zero_and_end() {
353 let mut p = three();
354 assert!(p.paste(3, PASTED), "existing boundary: no split");
355 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
356 assert_eq!(p.map_timeline(3), Some((1, 100)));
357
358 let mut p = three();
359 assert!(p.paste(0, PASTED));
360 assert_eq!(p.map_timeline(0), Some((0, 100)));
361 assert_eq!(p.map_timeline(2), Some((1, 0)));
362
363 // At the end and past it both append -- there is nothing to sit before.
364 let mut p = three();
365 assert!(p.paste(9, PASTED));
366 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
367 assert!(p.paste(1_000, PASTED));
368 assert_eq!(p.timeline_frames(), 13);
369
370 // An empty clip is the one thing refused, and it pushes no history.
371 let mut p = three();
372 assert!(!p.paste(
373 4,
374 Clip {
375 in_frame: 7,
376 out_frame: 7
377 }
378 ));
379 assert_eq!(p.clips().len(), 3);
380 }
381
382 #[test]
383 fn paste_undoes_in_one_step() {
384 let mut p = three();
385 let before = p.clips().to_vec();
386 assert!(p.paste(6, PASTED));
387 assert!(p.undo());
388 assert_eq!(p.clips(), before.as_slice(), "a paste is one undo step");
389 }
390
391 #[test]
392 fn a_copy_outlives_the_clip_it_came_from() {
393 let mut p = three();
394 let copied = p.clips()[1]; // [3,5)
395 assert!(p.delete(1));
396 // Just a frame range: the source is still on disk either way.
397 assert!(p.paste(0, copied));
398 assert_eq!(p.map_timeline(0), Some((0, 3)));
399 assert_eq!(p.timeline_frames(), 9);
400 }
401
402 #[test]
403 fn delete_closes_the_gap() {
404 let mut p = three();
405 assert!(p.delete(1));
406 assert_eq!(p.timeline_frames(), 7);
407 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
408 // timeline 3 used to be source 3; the gap closed so it is source 5 now
409 assert_eq!(p.map_timeline(3), Some((1, 5)));
410 assert_eq!(p.map_timeline(6), Some((1, 8)));
411 assert_eq!(p.map_timeline(7), None);
412 }
413
414 #[test]
415 fn delete_first_last_and_only() {
416 let mut p = three();
417 assert!(p.delete(0));
418 assert_eq!(p.map_timeline(0), Some((0, 3)));
419 assert_eq!(p.timeline_frames(), 6);
420
421 let mut p = three();
422 assert!(p.delete(2));
423 assert_eq!(p.timeline_frames(), 5);
424 assert_eq!(p.map_timeline(4), Some((1, 4)));
425
426 assert!(!p.delete(2), "index past the end");
427 assert!(p.delete(1));
428 assert!(!p.delete(0), "the last remaining clip stays");
429 assert_eq!(p.clips().len(), 1);
430 }
431
432 #[test]
433 fn undo_restores_exactly() {
434 let mut p = three();
435 let after_cuts = p.clips().to_vec();
436 assert!(p.delete(1));
437 assert!(p.undo());
438 assert_eq!(p.clips(), after_cuts.as_slice());
439
440 // walk all the way back through both cuts, then run dry
441 assert!(p.undo());
442 assert_eq!(p.clips().len(), 2);
443 assert!(p.undo());
444 assert_eq!(
445 p.clips(),
446 [Clip {
447 in_frame: 0,
448 out_frame: 9
449 }]
450 );
451 assert!(!p.undo(), "empty history");
452 assert_eq!(
453 p.clips(),
454 [Clip {
455 in_frame: 0,
456 out_frame: 9
457 }]
458 );
459 }
460
461 #[test]
462 fn segments_from_trims_the_first_entry() {
463 let p = three();
464 // mid-clip: partial first segment, whole clips after it
465 assert_eq!(
466 p.segments_from(4, FPS),
467 vec![(4.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)]
468 );
469 // on a boundary: nothing partial
470 assert_eq!(
471 p.segments_from(3, FPS),
472 vec![(3.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)]
473 );
474 // from the top: one entry per clip
475 assert_eq!(p.segments_from(0, FPS).len(), 3);
476 // last clip only
477 assert_eq!(p.segments_from(8, FPS), vec![(8.0 / 30.0, 0.3)]);
478 // past the end / unusable fps
479 assert!(p.segments_from(9, FPS).is_empty());
480 assert!(p.segments_from(0, 0.0).is_empty());
481 assert!(p.segments_from(0, f64::NAN).is_empty());
482 }
483
484 #[test]
485 fn segments_follow_deletes_and_fps() {
486 let mut p = three();
487 assert!(p.delete(0));
488 // source seconds, not timeline: deleting the head does not shift them
489 let segs = p.segments_from(0, 25.0);
490 assert_eq!(segs, vec![(3.0 / 25.0, 0.2), (0.2, 9.0 / 25.0)]);
491 let played: f64 = segs.iter().map(|(a, b)| b - a).sum();
492 assert!(
493 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
494 "segments must cover exactly the timeline: {played}"
495 );
496 }
497}