Video+audio lanes with offset-placed clips, gaps, .edith v2
Browse files at this commit59eb78e8f6a75d874844a3485fb30c94bff18c9eParent: 24d9b93- feat
- video+audio lanes with offset-placed clips, gaps, .edith v2
12 changed files +1726 -505
- crates/engine/src/audio.rs +95 -20
- crates/engine/src/decode.rs +43 -0
- crates/engine/src/edith.rs +227 -60
- crates/engine/src/export.rs +49 -9
- crates/engine/src/mux.rs +22 -4
- crates/engine/src/playback.rs +107 -81
- crates/engine/src/project.rs +824 -322
- crates/engine/tests/audio_multi.rs +12 -5
- crates/engine/tests/audio_segments.rs +111 -0
- crates/engine/tests/export.rs +75 -3
- crates/engine/tests/playback.rs +97 -0
- crates/engine/tests/saveload.rs +64 -1
crates/engine/src/audio.rsmodified+95 -20
| @@ -109,7 +109,7 @@ impl AudioSession { | |||
| 109 | path: impl AsRef<Path>, | 109 | path: impl AsRef<Path>, |
| 110 | segs: &[(f64, f64)], | 110 | segs: &[(f64, f64)], |
| 111 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 111 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 112 | - let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); | 112 | + let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect(); |
| 113 | Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs) | 113 | Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs) |
| 114 | } | 114 | } |
| 115 | 115 | ||
| @@ -119,13 +119,18 @@ impl AudioSession { | |||
| 119 | /// fresh either way. Each source contributes *its own* priming, packet table | 119 | /// fresh either way. Each source contributes *its own* priming, packet table |
| 120 | /// and length, which is the whole reason the resolution is per source. | 120 | /// and length, which is the whole reason the resolution is per source. |
| 121 | /// | 121 | /// |
| 122 | + /// A segment naming **no** source is a *gap*: that many seconds of silence | ||
| 123 | + /// are synthesised into the stream as ordinary chunks. Real chunks, not a | ||
| 124 | + /// pause — the master clock counts what the device has been fed, so a hole | ||
| 125 | + /// that fed nothing would stall the whole timeline on it. | ||
| 126 | + /// | ||
| 122 | /// Only the sources some segment names are opened. `Ok(None)` when `sources` | 127 | /// Only the sources some segment names are opened. `Ok(None)` when `sources` |
| 123 | /// is empty or its first entry has no AAC track; a later source that is | 128 | /// is empty or its first entry has no AAC track; a later source that is |
| 124 | /// missing audio or disagrees on rate/layout is an `Err` — import refuses | 129 | /// missing audio or disagrees on rate/layout is an `Err` — import refuses |
| 125 | /// those up front (one timeline, one output device), this is the backstop. | 130 | /// those up front (one timeline, one output device), this is the backstop. |
| 126 | pub fn open_multi_segments( | 131 | pub fn open_multi_segments( |
| 127 | sources: &[PathBuf], | 132 | sources: &[PathBuf], |
| 128 | - segs: &[(usize, f64, f64)], | 133 | + segs: &[(Option<usize>, f64, f64)], |
| 129 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 134 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 130 | let Some(first) = sources.first() else { | 135 | let Some(first) = sources.first() else { |
| 131 | return Ok(None); | 136 | return Ok(None); |
| @@ -147,6 +152,9 @@ impl AudioSession { | |||
| 147 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); | 152 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); |
| 148 | tracks[0] = Some(first); | 153 | tracks[0] = Some(first); |
| 149 | for &(source, ..) in segs { | 154 | for &(source, ..) in segs { |
| 155 | + let Some(source) = source else { | ||
| 156 | + continue; // a gap opens no file | ||
| 157 | + }; | ||
| 150 | let slot = tracks | 158 | let slot = tracks |
| 151 | .get_mut(source) | 159 | .get_mut(source) |
| 152 | .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; | 160 | .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; |
| @@ -171,18 +179,23 @@ impl AudioSession { | |||
| 171 | 179 | ||
| 172 | let segments: Vec<Segment> = segs | 180 | let segments: Vec<Segment> = segs |
| 173 | .iter() | 181 | .iter() |
| 174 | - .map(|&(source, start_secs, end_secs)| { | 182 | + .map(|&(source, start_secs, end_secs)| match source { |
| 175 | - tracks[source] | 183 | + Some(source) => tracks[source] |
| 176 | .as_ref() | 184 | .as_ref() |
| 177 | .expect("opened above") | 185 | .expect("opened above") |
| 178 | - .segment(source, start_secs, end_secs) | 186 | + .segment(source, start_secs, end_secs), |
| 187 | + None => Segment::silence( | ||
| 188 | + ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, | ||
| 189 | + ), | ||
| 179 | }) | 190 | }) |
| 180 | .collect(); | 191 | .collect(); |
| 181 | // Chunk numbering is continuous across every join, counted from the first | 192 | // Chunk numbering is continuous across every join, counted from the first |
| 182 | // segment's audible start in its own source (see `open_segments`). | 193 | // segment's audible start in its own source (see `open_segments`). |
| 183 | - let timeline = segments.first().map_or(0, |s| { | 194 | + let timeline = segments.first().map_or(0, |s| match s.source { |
| 184 | - s.media_target | 195 | + Some(source) => s |
| 185 | - .saturating_sub(tracks[s.source].as_ref().expect("opened above").priming) | 196 | + .media_target |
| 197 | + .saturating_sub(tracks[source].as_ref().expect("opened above").priming), | ||
| 198 | + None => 0, | ||
| 186 | }); | 199 | }); |
| 187 | 200 | ||
| 188 | // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so | 201 | // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so |
| @@ -242,7 +255,7 @@ impl AudioSession { | |||
| 242 | path: impl AsRef<Path>, | 255 | path: impl AsRef<Path>, |
| 243 | segs: &[(f64, f64)], | 256 | segs: &[(f64, f64)], |
| 244 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { | 257 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { |
| 245 | - let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); | 258 | + let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect(); |
| 246 | Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs) | 259 | Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs) |
| 247 | } | 260 | } |
| 248 | 261 | ||
| @@ -255,12 +268,26 @@ impl AudioSession { | |||
| 255 | /// Every source must declare the same [`AacTrackParams`]: the copy becomes | 268 | /// Every source must declare the same [`AacTrackParams`]: the copy becomes |
| 256 | /// one output track with one esds. Import refuses a mismatch up front; the | 269 | /// one output track with one esds. Import refuses a mismatch up front; the |
| 257 | /// check here is the backstop, as is the missing-track `Err`. | 270 | /// check here is the backstop, as is the missing-track `Err`. |
| 271 | + /// | ||
| 272 | + /// A segment naming **no** source is a gap. There is no AAC encoder here to | ||
| 273 | + /// make silence with, so the gap is spent as *time* instead: its length is | ||
| 274 | + /// added to the [`samples`](AacPacket::samples) of the packet next to it, | ||
| 275 | + /// which is the duration the writer puts in the stts. Every packet after | ||
| 276 | + /// the gap therefore still lands at its timeline position, so nothing | ||
| 277 | + /// drifts out of lip sync, and a conforming reader renders the hole as | ||
| 278 | + /// silence. | ||
| 279 | + /// | ||
| 280 | + /// ponytail: a gap at the *head* of the timeline has no packet before it to | ||
| 281 | + /// lengthen, so its length goes on the first packet instead — that one | ||
| 282 | + /// packet (23 ms) plays at zero rather than after the hole, and everything | ||
| 283 | + /// from the second packet on is exact. Upgrade path is an empty `elst` | ||
| 284 | + /// entry at the head of the audio track. | ||
| 258 | pub fn copy_multi_segments( | 285 | pub fn copy_multi_segments( |
| 259 | sources: &[PathBuf], | 286 | sources: &[PathBuf], |
| 260 | - segs: &[(usize, f64, f64)], | 287 | + segs: &[(Option<usize>, f64, f64)], |
| 261 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { | 288 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { |
| 262 | - let Some(&(first, ..)) = segs.first() else { | 289 | + let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else { |
| 263 | - return Ok(None); | 290 | + return Ok(None); // no segments, or nothing but silence |
| 264 | }; | 291 | }; |
| 265 | let path = sources | 292 | let path = sources |
| 266 | .get(first) | 293 | .get(first) |
| @@ -273,8 +300,19 @@ impl AudioSession { | |||
| 273 | tracks[first] = Some(track); | 300 | tracks[first] = Some(track); |
| 274 | 301 | ||
| 275 | let mut err = 0i64; | 302 | let mut err = 0i64; |
| 276 | - let mut packets = Vec::new(); | 303 | + let mut packets: Vec<AacPacket> = Vec::new(); |
| 277 | - for (i, &(source, start_secs, end_secs)) in segs.iter().enumerate() { | 304 | + // Gap time with no packet in front of it to carry it: a leading gap, |
| 305 | + // which the first packet written picks up (see the ponytail above). | ||
| 306 | + let mut owed = 0u32; | ||
| 307 | + for &(source, start_secs, end_secs) in segs { | ||
| 308 | + let Some(source) = source else { | ||
| 309 | + let len = ((end_secs - start_secs).max(0.0) * f64::from(params.sample_rate)) as u32; | ||
| 310 | + match packets.last_mut() { | ||
| 311 | + Some(prev) => prev.samples += len, | ||
| 312 | + None => owed += len, | ||
| 313 | + } | ||
| 314 | + continue; | ||
| 315 | + }; | ||
| 278 | let track = source_at(&mut tracks, sources, source)?; | 316 | let track = source_at(&mut tracks, sources, source)?; |
| 279 | if track.track_params() != params { | 317 | if track.track_params() != params { |
| 280 | return Err(format!( | 318 | return Err(format!( |
| @@ -289,7 +327,7 @@ impl AudioSession { | |||
| 289 | let available = track.sample_count.saturating_sub(start_id - 1); | 327 | let available = track.sample_count.saturating_sub(start_id - 1); |
| 290 | // The head packet is the priming of the first segment only: a reader | 328 | // The head packet is the priming of the first segment only: a reader |
| 291 | // drops exactly one, so an interior join must not add another. | 329 | // drops exactly one, so an interior join must not add another. |
| 292 | - let head = (i == 0 && start_id > 1).then(|| start_id - 1); | 330 | + let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1); |
| 293 | let ids = head | 331 | let ids = head |
| 294 | .into_iter() | 332 | .into_iter() |
| 295 | .chain(start_id..start_id + packet_run(&mut err, ideal, available)); | 333 | .chain(start_id..start_id + packet_run(&mut err, ideal, available)); |
| @@ -304,6 +342,9 @@ impl AudioSession { | |||
| 304 | }); | 342 | }); |
| 305 | } | 343 | } |
| 306 | } | 344 | } |
| 345 | + if let Some(first) = packets.first_mut() { | ||
| 346 | + first.samples += owed; | ||
| 347 | + } | ||
| 307 | Ok(Some((params, packets))) | 348 | Ok(Some((params, packets))) |
| 308 | } | 349 | } |
| 309 | } | 350 | } |
| @@ -435,7 +476,7 @@ impl Track { | |||
| 435 | // output is discarded below, so this only costs decode time. | 476 | // output is discarded below, so this only costs decode time. |
| 436 | let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL); | 477 | let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL); |
| 437 | Segment { | 478 | Segment { |
| 438 | - source, | 479 | + source: Some(source), |
| 439 | start_id, | 480 | start_id, |
| 440 | start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), | 481 | start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), |
| 441 | media_target, | 482 | media_target, |
| @@ -586,11 +627,13 @@ fn packet_at( | |||
| 586 | last | 627 | last |
| 587 | } | 628 | } |
| 588 | 629 | ||
| 589 | -/// One window of a source to decode, resolved to media samples and packets. | 630 | +/// One window of a source to decode, resolved to media samples and packets — |
| 631 | +/// or, with no source, a stretch of synthesised silence. | ||
| 590 | struct Segment { | 632 | struct Segment { |
| 591 | /// Index into the worker's tracks; the media positions below are that | 633 | /// Index into the worker's tracks; the media positions below are that |
| 592 | - /// source's, not the timeline's. | 634 | + /// source's, not the timeline's. `None` for a gap, where only the length |
| 593 | - source: usize, | 635 | + /// (`media_end`) means anything. |
| 636 | + source: Option<usize>, | ||
| 594 | /// First packet to feed the decoder, 1-based; includes the pre-roll. | 637 | /// First packet to feed the decoder, 1-based; includes the pre-roll. |
| 595 | start_id: u32, | 638 | start_id: u32, |
| 596 | /// Media position of `start_id`'s first frame, in samples-per-channel. | 639 | /// Media position of `start_id`'s first frame, in samples-per-channel. |
| @@ -602,6 +645,19 @@ struct Segment { | |||
| 602 | media_end: u64, | 645 | media_end: u64, |
| 603 | } | 646 | } |
| 604 | 647 | ||
| 648 | +impl Segment { | ||
| 649 | + /// `frames` per channel of silence — a gap in the audio lane. | ||
| 650 | + fn silence(frames: u64) -> Self { | ||
| 651 | + Self { | ||
| 652 | + source: None, | ||
| 653 | + start_id: 0, | ||
| 654 | + start_pos: 0, | ||
| 655 | + media_target: 0, | ||
| 656 | + media_end: frames, | ||
| 657 | + } | ||
| 658 | + } | ||
| 659 | +} | ||
| 660 | + | ||
| 605 | struct Worker { | 661 | struct Worker { |
| 606 | /// Indexed by [`Segment::source`]; only the sources some segment names are | 662 | /// Indexed by [`Segment::source`]; only the sources some segment names are |
| 607 | /// `Some`, the rest were never opened. | 663 | /// `Some`, the rest were never opened. |
| @@ -621,7 +677,26 @@ fn run(mut w: Worker) { | |||
| 621 | let segments = std::mem::take(&mut w.segments); | 677 | let segments = std::mem::take(&mut w.segments); |
| 622 | 678 | ||
| 623 | for seg in &segments { | 679 | for seg in &segments { |
| 624 | - let Some(track) = w.tracks[seg.source].as_mut() else { | 680 | + let Some(source) = seg.source else { |
| 681 | + // A gap: hand the device real silence rather than nothing at all, | ||
| 682 | + // in the same packet-sized chunks decoding produces, so `fed` and | ||
| 683 | + // the master clock keep counting straight through the hole. | ||
| 684 | + let mut left = seg.media_end; | ||
| 685 | + while left > 0 { | ||
| 686 | + let frames = left.min(u64::from(SAMPLES_PER_PACKET)); | ||
| 687 | + let chunk = AudioChunk { | ||
| 688 | + start_sample: timeline, | ||
| 689 | + samples: vec![0.0; frames as usize * channels], | ||
| 690 | + }; | ||
| 691 | + if w.tx.send(chunk).is_err() { | ||
| 692 | + return; // caller moved on | ||
| 693 | + } | ||
| 694 | + timeline += frames; | ||
| 695 | + left -= frames; | ||
| 696 | + } | ||
| 697 | + continue; | ||
| 698 | + }; | ||
| 699 | + let Some(track) = w.tracks[source].as_mut() else { | ||
| 625 | continue; // opener fills every named source; nothing to decode | 700 | continue; // opener fills every named source; nothing to decode |
| 626 | }; | 701 | }; |
| 627 | let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) | 702 | let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) |
crates/engine/src/decode.rsmodified+43 -0
| @@ -108,6 +108,49 @@ impl DecodeSession { | |||
| 108 | Ok((meta, rx, worker.detach())) | 108 | Ok((meta, rx, worker.detach())) |
| 109 | } | 109 | } |
| 110 | 110 | ||
| 111 | + /// A worker that decodes nothing and emits `len` black frames, indexed from | ||
| 112 | + /// zero -- what a *gap* in the video lane looks like. It goes down the same | ||
| 113 | + /// channel as decoded frames, so a gap costs the caller no branch at all | ||
| 114 | + /// beyond choosing this opener: same bounded channel, same backpressure, | ||
| 115 | + /// same cancel, same retire path. | ||
| 116 | + pub(crate) fn open_black(width: u32, height: u32, len: u32) -> (Receiver<Frame>, Worker) { | ||
| 117 | + let (tx, rx) = sync_channel(2); | ||
| 118 | + let cancel = Arc::new(AtomicBool::new(false)); | ||
| 119 | + if len == 0 { | ||
| 120 | + return ( | ||
| 121 | + rx, | ||
| 122 | + Worker { | ||
| 123 | + cancel, | ||
| 124 | + handle: None, | ||
| 125 | + }, | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | + let worker_cancel = Arc::clone(&cancel); | ||
| 129 | + // One buffer, cloned per frame: opaque black is a constant, and the | ||
| 130 | + // clone is a memcpy against a decode this replaces entirely. | ||
| 131 | + let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat(); | ||
| 132 | + let handle = thread::Builder::new() | ||
| 133 | + .name("black".into()) | ||
| 134 | + .spawn(move || { | ||
| 135 | + for index in 0..len { | ||
| 136 | + if worker_cancel.load(Ordering::Relaxed) { | ||
| 137 | + return; | ||
| 138 | + } | ||
| 139 | + let frame = Frame { | ||
| 140 | + index, | ||
| 141 | + width, | ||
| 142 | + height, | ||
| 143 | + bgra: black.clone(), | ||
| 144 | + }; | ||
| 145 | + if tx.send(frame).is_err() { | ||
| 146 | + return; // caller moved on | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + }) | ||
| 150 | + .ok(); | ||
| 151 | + (rx, Worker { cancel, handle }) | ||
| 152 | + } | ||
| 153 | + | ||
| 111 | /// As [`DecodeSession::open_range`], but the caller gets the whole | 154 | /// As [`DecodeSession::open_range`], but the caller gets the whole |
| 112 | /// [`Worker`] and can therefore *wait* for it. In-process only: a caller | 155 | /// [`Worker`] and can therefore *wait* for it. In-process only: a caller |
| 113 | /// that outlives its workers has to be able to join them at exit. | 156 | /// that outlives its workers has to be able to join them at exit. |
crates/engine/src/edith.rsmodified+227 -60
| @@ -1,15 +1,27 @@ | |||
| 1 | //! The project file: a line of text per thing, and nothing else. | 1 | //! The project file: a line of text per thing, and nothing else. |
| 2 | //! | 2 | //! |
| 3 | //! ```text | 3 | //! ```text |
| 4 | -//! edith 1 | 4 | +//! edith 2 |
| 5 | //! playhead 90 | 5 | //! playhead 90 |
| 6 | //! source test_av.mp4 | 6 | //! source test_av.mp4 |
| 7 | //! source /elsewhere/test_av2.mp4 | 7 | //! source /elsewhere/test_av2.mp4 |
| 8 | -//! clip 0 120 0 | 8 | +//! video 0 0 120 0 0 |
| 9 | -//! clip 0 120 1 | 9 | +//! audio 0 0 120 0 0 |
| 10 | +//! video 120 0 120 1 - | ||
| 10 | //! ``` | 11 | //! ``` |
| 11 | //! | 12 | //! |
| 12 | -//! Text because an edit list is three integers and a path, and a path is | 13 | +//! A lane line is `<lane> <start> <in> <out> <source> <link>`: where the clip |
| 14 | +//! sits on the timeline, the half-open source range it plays, the file it plays | ||
| 15 | +//! from, and its group id (`-` for none). Timeline placement is explicit, so a | ||
| 16 | +//! *gap* is simply a stretch no line covers -- there is nothing to write for | ||
| 17 | +//! one, and nothing that can disagree about its length. | ||
| 18 | +//! | ||
| 19 | +//! **Version 1** wrote one lane, queued end to end: `clip <in> <out> <source>`. | ||
| 20 | +//! Such a file still loads -- the clips are laid out cumulatively and copied | ||
| 21 | +//! onto both lanes as one group each, which is exactly what a v1 timeline meant | ||
| 22 | +//! -- and saving it again writes v2. A v1 reader refuses a v2 file by name. | ||
| 23 | +//! | ||
| 24 | +//! Text because an edit list is a few integers and a path, and a path is | ||
| 13 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. | 25 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. |
| 14 | //! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is | 26 | //! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is |
| 15 | //! everything a line-based format cannot carry) and survives round-trip | 27 | //! everything a line-based format cannot carry) and survives round-trip |
| @@ -35,9 +47,10 @@ use std::path::{Path, PathBuf}; | |||
| 35 | 47 | ||
| 36 | use crate::project::Clip; | 48 | use crate::project::Clip; |
| 37 | 49 | ||
| 38 | -/// First line, exactly. The version is part of it: a v2 reader will accept a | 50 | +/// What [`save`] writes. Read support goes back to `edith 1`; see the module |
| 39 | -/// `edith 1` file, and a v1 reader refuses a `edith 2` one by name. | 51 | +/// docs for what that dialect looked like. |
| 40 | -const MAGIC: &[u8] = b"edith 1"; | 52 | +const MAGIC: &[u8] = b"edith 2"; |
| 53 | +const MAGIC_V1: &[u8] = b"edith 1"; | ||
| 41 | 54 | ||
| 42 | /// What a project file says: an edit list plus where the playhead stood. | 55 | /// What a project file says: an edit list plus where the playhead stood. |
| 43 | /// Structurally valid by construction -- see [`parse`]. | 56 | /// Structurally valid by construction -- see [`parse`]. |
| @@ -45,13 +58,20 @@ const MAGIC: &[u8] = b"edith 1"; | |||
| 45 | pub struct Document { | 58 | pub struct Document { |
| 46 | /// Absolute, relative entries already joined to the file's own directory. | 59 | /// Absolute, relative entries already joined to the file's own directory. |
| 47 | pub sources: Vec<PathBuf>, | 60 | pub sources: Vec<PathBuf>, |
| 48 | - pub clips: Vec<Clip>, | 61 | + pub video: Vec<Clip>, |
| 62 | + pub audio: Vec<Clip>, | ||
| 49 | pub playhead: u32, | 63 | pub playhead: u32, |
| 50 | } | 64 | } |
| 51 | 65 | ||
| 52 | /// Writes the project to `path`, atomically. `sources` should already be | 66 | /// Writes the project to `path`, atomically. `sources` should already be |
| 53 | /// orphan-free ([`crate::Project::without_orphan_sources`]). | 67 | /// orphan-free ([`crate::Project::without_orphan_sources`]). |
| 54 | -pub fn save(path: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> crate::Result<()> { | 68 | +pub fn save( |
| 69 | + path: &Path, | ||
| 70 | + sources: &[PathBuf], | ||
| 71 | + video: &[Clip], | ||
| 72 | + audio: &[Clip], | ||
| 73 | + playhead: u32, | ||
| 74 | +) -> crate::Result<()> { | ||
| 55 | let dir = project_dir(path); | 75 | let dir = project_dir(path); |
| 56 | let mut part = path.to_path_buf().into_os_string(); | 76 | let mut part = path.to_path_buf().into_os_string(); |
| 57 | part.push(".part"); | 77 | part.push(".part"); |
| @@ -62,7 +82,7 @@ pub fn save(path: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> | |||
| 62 | // the second one puts the name itself there. | 82 | // the second one puts the name itself there. |
| 63 | let result = std::fs::File::create(&part) | 83 | let result = std::fs::File::create(&part) |
| 64 | .and_then(|mut f| { | 84 | .and_then(|mut f| { |
| 65 | - f.write_all(&emit(&dir, sources, clips, playhead))?; | 85 | + f.write_all(&emit(&dir, sources, video, audio, playhead))?; |
| 66 | f.sync_all() | 86 | f.sync_all() |
| 67 | }) | 87 | }) |
| 68 | .and_then(|()| std::fs::rename(&part, path)) | 88 | .and_then(|()| std::fs::rename(&part, path)) |
| @@ -92,7 +112,7 @@ fn project_dir(path: &Path) -> PathBuf { | |||
| 92 | dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) | 112 | dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) |
| 93 | } | 113 | } |
| 94 | 114 | ||
| 95 | -fn emit(dir: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> Vec<u8> { | 115 | +fn emit(dir: &Path, sources: &[PathBuf], video: &[Clip], audio: &[Clip], playhead: u32) -> Vec<u8> { |
| 96 | let mut out = Vec::new(); | 116 | let mut out = Vec::new(); |
| 97 | out.extend_from_slice(MAGIC); | 117 | out.extend_from_slice(MAGIC); |
| 98 | out.push(b'\n'); | 118 | out.push(b'\n'); |
| @@ -102,10 +122,19 @@ fn emit(dir: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> Vec<u | |||
| 102 | escape(s.strip_prefix(dir).unwrap_or(s), &mut out); | 122 | escape(s.strip_prefix(dir).unwrap_or(s), &mut out); |
| 103 | out.push(b'\n'); | 123 | out.push(b'\n'); |
| 104 | } | 124 | } |
| 105 | - for c in clips { | 125 | + // Lane by lane rather than interleaved by time: a lane reads as a list, and |
| 106 | - out.extend_from_slice( | 126 | + // the parser gets its sortedness check for free from the order it is in. |
| 107 | - format!("clip {} {} {}\n", c.in_frame, c.out_frame, c.source).as_bytes(), | 127 | + for (keyword, clips) in [("video", video), ("audio", audio)] { |
| 108 | - ); | 128 | + for c in clips { |
| 129 | + let link = c.link.map_or("-".to_string(), |l| l.to_string()); | ||
| 130 | + out.extend_from_slice( | ||
| 131 | + format!( | ||
| 132 | + "{keyword} {} {} {} {} {link}\n", | ||
| 133 | + c.start, c.in_frame, c.out_frame, c.source | ||
| 134 | + ) | ||
| 135 | + .as_bytes(), | ||
| 136 | + ); | ||
| 137 | + } | ||
| 109 | } | 138 | } |
| 110 | out | 139 | out |
| 111 | } | 140 | } |
| @@ -116,7 +145,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 116 | let body = data.strip_suffix(b"\n").unwrap_or(data); | 145 | let body = data.strip_suffix(b"\n").unwrap_or(data); |
| 117 | let mut lines = body.split(|&b| b == b'\n').enumerate(); | 146 | let mut lines = body.split(|&b| b == b'\n').enumerate(); |
| 118 | let (_, first) = lines.next().unwrap_or((0, &[])); | 147 | let (_, first) = lines.next().unwrap_or((0, &[])); |
| 119 | - if first != MAGIC { | 148 | + let v1 = first == MAGIC_V1; |
| 149 | + if first != MAGIC && !v1 { | ||
| 120 | return Err(match first.strip_prefix(b"edith ") { | 150 | return Err(match first.strip_prefix(b"edith ") { |
| 121 | Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)), | 151 | Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)), |
| 122 | None => "line 1: not a edith file".to_string(), | 152 | None => "line 1: not a edith file".to_string(), |
| @@ -126,10 +156,14 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 126 | 156 | ||
| 127 | let mut doc = Document { | 157 | let mut doc = Document { |
| 128 | sources: Vec::new(), | 158 | sources: Vec::new(), |
| 129 | - clips: Vec::new(), | 159 | + video: Vec::new(), |
| 160 | + audio: Vec::new(), | ||
| 130 | playhead: 0, | 161 | playhead: 0, |
| 131 | }; | 162 | }; |
| 132 | let mut playhead_seen = false; | 163 | let mut playhead_seen = false; |
| 164 | + // Where the next v1 clip is placed: that dialect had no `start` field, the | ||
| 165 | + // clips simply queued up. | ||
| 166 | + let mut queued = 0u32; | ||
| 133 | for (i, line) in lines { | 167 | for (i, line) in lines { |
| 134 | let n = i + 1; | 168 | let n = i + 1; |
| 135 | let (keyword, rest) = match line.iter().position(|&b| b == b' ') { | 169 | let (keyword, rest) = match line.iter().position(|&b| b == b' ') { |
| @@ -147,7 +181,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 147 | playhead_seen = true; | 181 | playhead_seen = true; |
| 148 | } | 182 | } |
| 149 | b"source" => { | 183 | b"source" => { |
| 150 | - if !doc.clips.is_empty() { | 184 | + if !doc.video.is_empty() || !doc.audio.is_empty() { |
| 151 | return Err(format!("line {n}: source after a clip").into()); | 185 | return Err(format!("line {n}: source after a clip").into()); |
| 152 | } | 186 | } |
| 153 | if rest.is_empty() { | 187 | if rest.is_empty() { |
| @@ -162,37 +196,60 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 162 | dir.join(path) | 196 | dir.join(path) |
| 163 | }); | 197 | }); |
| 164 | } | 198 | } |
| 165 | - b"clip" => { | 199 | + // v1: one lane, no placement, no groups. Every clip becomes one |
| 166 | - let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect(); | 200 | + // grouped video+audio pair laid where the queue reached, which is |
| 167 | - if fields.len() != 3 { | 201 | + // what the file always meant. |
| 168 | - return Err( | 202 | + b"clip" if v1 => { |
| 169 | - format!("line {n}: clip wants 3 fields, found {}", fields.len()).into(), | 203 | + let f = fields(rest, 3, "clip", n)?; |
| 170 | - ); | 204 | + let clip = check( |
| 171 | - } | 205 | + Clip { |
| 172 | - let clip = Clip { | 206 | + start: queued, |
| 173 | - in_frame: number(fields[0], n)?, | 207 | + in_frame: number(f[0], n)?, |
| 174 | - out_frame: number(fields[1], n)?, | 208 | + out_frame: number(f[1], n)?, |
| 175 | - source: number(fields[2], n)? as usize, | 209 | + source: number(f[2], n)? as usize, |
| 210 | + link: Some(doc.video.len() as u32), | ||
| 211 | + }, | ||
| 212 | + &doc, | ||
| 213 | + n, | ||
| 214 | + )?; | ||
| 215 | + queued = clip.end(); | ||
| 216 | + doc.video.push(clip); | ||
| 217 | + doc.audio.push(clip); | ||
| 218 | + } | ||
| 219 | + b"video" | b"audio" if !v1 => { | ||
| 220 | + let f = fields(rest, 5, "clip", n)?; | ||
| 221 | + let clip = check( | ||
| 222 | + Clip { | ||
| 223 | + start: number(f[0], n)?, | ||
| 224 | + in_frame: number(f[1], n)?, | ||
| 225 | + out_frame: number(f[2], n)?, | ||
| 226 | + source: number(f[3], n)? as usize, | ||
| 227 | + link: match f[4] { | ||
| 228 | + b"-" => None, | ||
| 229 | + field => Some(number(field, n)?), | ||
| 230 | + }, | ||
| 231 | + }, | ||
| 232 | + &doc, | ||
| 233 | + n, | ||
| 234 | + )?; | ||
| 235 | + let lane = match keyword { | ||
| 236 | + b"video" => &mut doc.video, | ||
| 237 | + _ => &mut doc.audio, | ||
| 176 | }; | 238 | }; |
| 177 | - if clip.out_frame <= clip.in_frame { | 239 | + // The sorted, non-overlapping placement invariant, checked at |
| 240 | + // the only door untrusted clips come in through. | ||
| 241 | + if lane.last().is_some_and(|prev| prev.end() > clip.start) { | ||
| 178 | return Err(format!( | 242 | return Err(format!( |
| 179 | - "line {n}: clip [{}, {}) is empty", | 243 | + "line {n}: clip at {} overlaps the one before it, or comes before it", |
| 180 | - clip.in_frame, clip.out_frame | 244 | + clip.start |
| 181 | ) | 245 | ) |
| 182 | .into()); | 246 | .into()); |
| 183 | } | 247 | } |
| 184 | - if clip.source >= doc.sources.len() { | 248 | + lane.push(clip); |
| 185 | - return Err(format!( | ||
| 186 | - "line {n}: clip names source {} of {}", | ||
| 187 | - clip.source, | ||
| 188 | - doc.sources.len() | ||
| 189 | - ) | ||
| 190 | - .into()); | ||
| 191 | - } | ||
| 192 | - doc.clips.push(clip); | ||
| 193 | } | 249 | } |
| 194 | // Empty lines land here too: nothing in this format is optional | 250 | // Empty lines land here too: nothing in this format is optional |
| 195 | - // whitespace. | 251 | + // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one) |
| 252 | + // is a file mixing dialects, and is refused the same way. | ||
| 196 | _ => { | 253 | _ => { |
| 197 | return Err(format!( | 254 | return Err(format!( |
| 198 | "line {n}: unknown keyword {:?}", | 255 | "line {n}: unknown keyword {:?}", |
| @@ -202,12 +259,50 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 202 | } | 259 | } |
| 203 | } | 260 | } |
| 204 | } | 261 | } |
| 205 | - if doc.clips.is_empty() { | 262 | + if doc.video.is_empty() && doc.audio.is_empty() { |
| 206 | return Err("no clips: an empty timeline is not a project".into()); | 263 | return Err("no clips: an empty timeline is not a project".into()); |
| 207 | } | 264 | } |
| 208 | Ok(doc) | 265 | Ok(doc) |
| 209 | } | 266 | } |
| 210 | 267 | ||
| 268 | +/// Splits a line's fields, refusing the wrong count by name. | ||
| 269 | +fn fields<'a>( | ||
| 270 | + rest: &'a [u8], | ||
| 271 | + want: usize, | ||
| 272 | + what: &str, | ||
| 273 | + line: usize, | ||
| 274 | +) -> crate::Result<Vec<&'a [u8]>> { | ||
| 275 | + let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect(); | ||
| 276 | + if fields.len() != want { | ||
| 277 | + return Err(format!( | ||
| 278 | + "line {line}: {what} wants {want} fields, found {}", | ||
| 279 | + fields.len() | ||
| 280 | + ) | ||
| 281 | + .into()); | ||
| 282 | + } | ||
| 283 | + Ok(fields) | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +/// The per-clip structure checks both dialects share. | ||
| 287 | +fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> { | ||
| 288 | + if clip.out_frame <= clip.in_frame { | ||
| 289 | + return Err(format!( | ||
| 290 | + "line {line}: clip [{}, {}) is empty", | ||
| 291 | + clip.in_frame, clip.out_frame | ||
| 292 | + ) | ||
| 293 | + .into()); | ||
| 294 | + } | ||
| 295 | + if clip.source >= doc.sources.len() { | ||
| 296 | + return Err(format!( | ||
| 297 | + "line {line}: clip names source {} of {}", | ||
| 298 | + clip.source, | ||
| 299 | + doc.sources.len() | ||
| 300 | + ) | ||
| 301 | + .into()); | ||
| 302 | + } | ||
| 303 | + Ok(clip) | ||
| 304 | +} | ||
| 305 | + | ||
| 211 | fn number(field: &[u8], line: usize) -> crate::Result<u32> { | 306 | fn number(field: &[u8], line: usize) -> crate::Result<u32> { |
| 212 | match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) { | 307 | match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) { |
| 213 | Some(n) => Ok(n), | 308 | Some(n) => Ok(n), |
| @@ -258,42 +353,113 @@ fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> { | |||
| 258 | mod tests { | 353 | mod tests { |
| 259 | use super::*; | 354 | use super::*; |
| 260 | 355 | ||
| 261 | - fn clip(in_frame: u32, out_frame: u32, source: usize) -> Clip { | 356 | + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { |
| 262 | Clip { | 357 | Clip { |
| 358 | + start, | ||
| 263 | in_frame, | 359 | in_frame, |
| 264 | out_frame, | 360 | out_frame, |
| 265 | source, | 361 | source, |
| 362 | + link, | ||
| 266 | } | 363 | } |
| 267 | } | 364 | } |
| 268 | 365 | ||
| 269 | - /// Two sources, one under the project's own directory and one not, and a | 366 | + /// Two sources, one under the project's own directory and one not, a clip |
| 270 | - /// clip from each -- the shape every case below starts from. | 367 | + /// from each on the video lane, and an audio lane with a gap in the middle |
| 271 | - fn doc() -> (PathBuf, Vec<PathBuf>, Vec<Clip>) { | 368 | + /// -- the shape every case below starts from. |
| 369 | + fn doc() -> (PathBuf, Vec<PathBuf>, Vec<Clip>, Vec<Clip>) { | ||
| 272 | ( | 370 | ( |
| 273 | PathBuf::from("/proj"), | 371 | PathBuf::from("/proj"), |
| 274 | vec![ | 372 | vec![ |
| 275 | PathBuf::from("/proj/a.mp4"), | 373 | PathBuf::from("/proj/a.mp4"), |
| 276 | PathBuf::from("/elsewhere/b.mp4"), | 374 | PathBuf::from("/elsewhere/b.mp4"), |
| 277 | ], | 375 | ], |
| 278 | - vec![clip(0, 30, 0), clip(10, 20, 1)], | 376 | + vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))], |
| 377 | + vec![clip(0, 0, 30, 0, Some(0))], | ||
| 279 | ) | 378 | ) |
| 280 | } | 379 | } |
| 281 | 380 | ||
| 282 | #[test] | 381 | #[test] |
| 283 | fn relative_and_absolute_paths_round_trip() { | 382 | fn relative_and_absolute_paths_round_trip() { |
| 284 | - let (dir, sources, clips) = doc(); | 383 | + let (dir, sources, video, audio) = doc(); |
| 285 | - let bytes = emit(&dir, &sources, &clips, 12); | 384 | + let bytes = emit(&dir, &sources, &video, &audio, 12); |
| 286 | assert_eq!( | 385 | assert_eq!( |
| 287 | String::from_utf8_lossy(&bytes), | 386 | String::from_utf8_lossy(&bytes), |
| 288 | - "edith 1\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\nclip 0 30 0\nclip 10 20 1\n", | 387 | + "edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\ |
| 388 | + video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n", | ||
| 289 | "the file under the project directory is written relative to it" | 389 | "the file under the project directory is written relative to it" |
| 290 | ); | 390 | ); |
| 291 | let back = parse(&bytes, &dir).expect("parse"); | 391 | let back = parse(&bytes, &dir).expect("parse"); |
| 292 | assert_eq!(back.sources, sources, "relative entries rejoin the dir"); | 392 | assert_eq!(back.sources, sources, "relative entries rejoin the dir"); |
| 293 | - assert_eq!(back.clips, clips); | 393 | + assert_eq!(back.video, video); |
| 394 | + assert_eq!( | ||
| 395 | + back.audio, audio, | ||
| 396 | + "the trailing gap needs no line of its own" | ||
| 397 | + ); | ||
| 294 | assert_eq!(back.playhead, 12); | 398 | assert_eq!(back.playhead, 12); |
| 295 | // ...and emitting the parsed document reproduces the same bytes. | 399 | // ...and emitting the parsed document reproduces the same bytes. |
| 296 | - assert_eq!(emit(&dir, &back.sources, &back.clips, back.playhead), bytes); | 400 | + assert_eq!( |
| 401 | + emit(&dir, &back.sources, &back.video, &back.audio, back.playhead), | ||
| 402 | + bytes | ||
| 403 | + ); | ||
| 404 | + } | ||
| 405 | + | ||
| 406 | + /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of | ||
| 407 | + /// lanes, and saving it again writes v2. | ||
| 408 | + #[test] | ||
| 409 | + fn a_v1_file_loads_as_two_grouped_lanes() { | ||
| 410 | + let dir = PathBuf::from("/proj"); | ||
| 411 | + let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n"; | ||
| 412 | + let back = parse(v1, &dir).expect("v1 parses"); | ||
| 413 | + assert_eq!( | ||
| 414 | + back.video, | ||
| 415 | + vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))], | ||
| 416 | + "v1 clips queue up: the second starts where the first ended" | ||
| 417 | + ); | ||
| 418 | + assert_eq!(back.audio, back.video, "one take per clip, on both lanes"); | ||
| 419 | + assert_eq!(back.playhead, 5); | ||
| 420 | + // Saved again it is v2, and that round-trips to the same document. | ||
| 421 | + let v2 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead); | ||
| 422 | + assert!(v2.starts_with(b"edith 2\n")); | ||
| 423 | + let again = parse(&v2, &dir).expect("v2 parses"); | ||
| 424 | + assert_eq!((again.video, again.audio), (back.video, back.audio)); | ||
| 425 | + // A dialect may not be mixed: lane lines under v1, `clip` under v2. | ||
| 426 | + for (bytes, want) in [ | ||
| 427 | + ( | ||
| 428 | + &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..], | ||
| 429 | + "line 3: unknown keyword \"video\"", | ||
| 430 | + ), | ||
| 431 | + ( | ||
| 432 | + b"edith 2\nsource a.mp4\nclip 0 30 0\n", | ||
| 433 | + "line 3: unknown keyword \"clip\"", | ||
| 434 | + ), | ||
| 435 | + ] { | ||
| 436 | + assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want); | ||
| 437 | + } | ||
| 438 | + } | ||
| 439 | + | ||
| 440 | + /// A gap is the absence of a line, so a lane's placements must arrive in | ||
| 441 | + /// order and never overlap -- the invariant the whole model rests on. | ||
| 442 | + #[test] | ||
| 443 | + fn a_lane_out_of_order_or_overlapping_is_refused() { | ||
| 444 | + let dir = PathBuf::from("/proj"); | ||
| 445 | + for bytes in [ | ||
| 446 | + &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..], | ||
| 447 | + b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n", | ||
| 448 | + ] { | ||
| 449 | + let err = parse(bytes, &dir).unwrap_err().to_string(); | ||
| 450 | + assert!(err.starts_with("line 4: clip at "), "{err}"); | ||
| 451 | + } | ||
| 452 | + // The lanes are independent, so a video line never crowds an audio one. | ||
| 453 | + assert!( | ||
| 454 | + parse( | ||
| 455 | + b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n", | ||
| 456 | + &dir | ||
| 457 | + ) | ||
| 458 | + .is_ok() | ||
| 459 | + ); | ||
| 460 | + // ...and a lane may be empty as long as the other one is not. | ||
| 461 | + let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse"); | ||
| 462 | + assert!(only_audio.video.is_empty()); | ||
| 297 | } | 463 | } |
| 298 | 464 | ||
| 299 | /// The relocatability promise, from the two directions a project path | 465 | /// The relocatability promise, from the two directions a project path |
| @@ -316,11 +482,12 @@ mod tests { | |||
| 316 | let source = dir.join("real/a.mp4"); | 482 | let source = dir.join("real/a.mp4"); |
| 317 | let path = dir.join("link/p.edith"); | 483 | let path = dir.join("link/p.edith"); |
| 318 | 484 | ||
| 319 | - save(&path, &[source], &[clip(0, 30, 0)], 0).expect("save"); | 485 | + let one = [clip(0, 0, 30, 0, None)]; |
| 486 | + save(&path, &[source], &one, &one, 0).expect("save"); | ||
| 320 | let bytes = std::fs::read(&path).expect("read back"); | 487 | let bytes = std::fs::read(&path).expect("read back"); |
| 321 | assert_eq!( | 488 | assert_eq!( |
| 322 | String::from_utf8_lossy(&bytes), | 489 | String::from_utf8_lossy(&bytes), |
| 323 | - "edith 1\nplayhead 0\nsource a.mp4\nclip 0 30 0\n" | 490 | + "edith 2\nplayhead 0\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n" |
| 324 | ); | 491 | ); |
| 325 | // Loading rejoins the *given* directory, so the file is reached by the | 492 | // Loading rejoins the *given* directory, so the file is reached by the |
| 326 | // way the project was opened -- the same file, through the link. | 493 | // way the project was opened -- the same file, through the link. |
| @@ -336,7 +503,7 @@ mod tests { | |||
| 336 | let dir = PathBuf::from("/proj"); | 503 | let dir = PathBuf::from("/proj"); |
| 337 | // A newline and a percent in a filename, plus a non-UTF-8 byte. | 504 | // A newline and a percent in a filename, plus a non-UTF-8 byte. |
| 338 | let nasty = PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())); | 505 | let nasty = PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())); |
| 339 | - let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 5, 0)], 0); | 506 | + let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 0, 5, 0, None)], &[], 0); |
| 340 | assert_eq!( | 507 | assert_eq!( |
| 341 | bytes.iter().filter(|&&b| b == b'\n').count(), | 508 | bytes.iter().filter(|&&b| b == b'\n').count(), |
| 342 | 4, | 509 | 4, |
| @@ -349,10 +516,10 @@ mod tests { | |||
| 349 | #[test] | 516 | #[test] |
| 350 | fn a_wrong_first_line_is_refused_by_name() { | 517 | fn a_wrong_first_line_is_refused_by_name() { |
| 351 | let dir = PathBuf::from("/proj"); | 518 | let dir = PathBuf::from("/proj"); |
| 352 | - let err = parse(b"edith 2\nsource a.mp4\nclip 0 5 0\n", &dir) | 519 | + let err = parse(b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n", &dir) |
| 353 | .unwrap_err() | 520 | .unwrap_err() |
| 354 | .to_string(); | 521 | .to_string(); |
| 355 | - assert_eq!(err, "line 1: unsupported version 2"); | 522 | + assert_eq!(err, "line 1: unsupported version 3"); |
| 356 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { | 523 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { |
| 357 | assert_eq!( | 524 | assert_eq!( |
| 358 | parse(junk, &dir).unwrap_err().to_string(), | 525 | parse(junk, &dir).unwrap_err().to_string(), |
| @@ -421,8 +588,8 @@ mod tests { | |||
| 421 | /// Every truncation of a good file either parses or refuses; none panics. | 588 | /// Every truncation of a good file either parses or refuses; none panics. |
| 422 | #[test] | 589 | #[test] |
| 423 | fn truncations_never_panic() { | 590 | fn truncations_never_panic() { |
| 424 | - let (dir, sources, clips) = doc(); | 591 | + let (dir, sources, video, audio) = doc(); |
| 425 | - let bytes = emit(&dir, &sources, &clips, 12); | 592 | + let bytes = emit(&dir, &sources, &video, &audio, 12); |
| 426 | for cut in 0..bytes.len() { | 593 | for cut in 0..bytes.len() { |
| 427 | let _ = parse(&bytes[..cut], &dir); | 594 | let _ = parse(&bytes[..cut], &dir); |
| 428 | // ...and the same file with a byte lopped off the front, which | 595 | // ...and the same file with a byte lopped off the front, which |
crates/engine/src/export.rsmodified+49 -9
| @@ -24,7 +24,7 @@ use crate::audio::AudioSession; | |||
| 24 | use crate::demux::{Demuxer, VideoMeta}; | 24 | use crate::demux::{Demuxer, VideoMeta}; |
| 25 | use crate::hw::{HwEncoder, HwSession}; | 25 | use crate::hw::{HwEncoder, HwSession}; |
| 26 | use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; | 26 | use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; |
| 27 | -use crate::project::Project; | 27 | +use crate::project::{Lane, Project}; |
| 28 | 28 | ||
| 29 | /// Progress is reported in permille: an atomic integer the render loop can read | 29 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 30 | /// without a lock, fine enough for any progress bar. | 30 | /// without a lock, fine enough for any progress bar. |
| @@ -169,18 +169,31 @@ fn run( | |||
| 169 | let mut encoder = Enc::open(meta, settings)?; | 169 | let mut encoder = Enc::open(meta, settings)?; |
| 170 | let mut muxer = None; | 170 | let mut muxer = None; |
| 171 | let mut done = 0u32; | 171 | let mut done = 0u32; |
| 172 | - for clip in project.clips() { | 172 | + let black = Black::new(meta); |
| 173 | + // Spans, not clips: a gap in the video lane is part of the timeline and | ||
| 174 | + // gets encoded too, as black frames. The picture count is therefore | ||
| 175 | + // `timeline_frames` however the lane is arranged. | ||
| 176 | + for span in project.spans_from(Lane::Video, 0) { | ||
| 173 | // Every clip reopens its own source file at its own in point; the | 177 | // Every clip reopens its own source file at its own in point; the |
| 174 | // encoder is *not* reopened, so the export is one continuous stream | 178 | // encoder is *not* reopened, so the export is one continuous stream |
| 175 | // whose GOP boundaries need not line up with the cuts -- nor with the | 179 | // whose GOP boundaries need not line up with the cuts -- nor with the |
| 176 | // file boundaries, which are just cuts that change the path. | 180 | // file boundaries, which are just cuts that change the path. |
| 177 | - let source = sources | 181 | + let mut pictures = match span.from { |
| 178 | - .get(clip.source) | 182 | + Some((source, in_frame)) => { |
| 179 | - .ok_or_else(|| format!("clip names source {} of {}", clip.source, sources.len()))?; | 183 | + let path = sources |
| 180 | - let mut pictures = ClipDecoder::open(source, clip.in_frame)?; | 184 | + .get(source) |
| 181 | - for _ in 0..clip.len() { | 185 | + .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 186 | + Some(ClipDecoder::open(path, in_frame)?) | ||
| 187 | + } | ||
| 188 | + None => None, | ||
| 189 | + }; | ||
| 190 | + for _ in 0..span.len { | ||
| 182 | cancelled(shared)?; | 191 | cancelled(shared)?; |
| 183 | - let Some((y, u, v, width, height)) = pictures.next()? else { | 192 | + let picture = match &mut pictures { |
| 193 | + Some(pictures) => pictures.next()?, | ||
| 194 | + None => Some(black.picture()), | ||
| 195 | + }; | ||
| 196 | + let Some((y, u, v, width, height)) = picture else { | ||
| 184 | break; // source ran out early; the clip list outlives the file | 197 | break; // source ran out early; the clip list outlives the file |
| 185 | }; | 198 | }; |
| 186 | if let Some(au) = encoder.encode(y, u, v, width, height)? { | 199 | if let Some(au) = encoder.encode(y, u, v, width, height)? { |
| @@ -204,7 +217,7 @@ fn run( | |||
| 204 | }; | 217 | }; |
| 205 | if let Some((_, packets)) = audio { | 218 | if let Some((_, packets)) = audio { |
| 206 | for packet in packets { | 219 | for packet in packets { |
| 207 | - muxer.write_audio_packet(&packet.bytes)?; | 220 | + muxer.write_audio_packet(&packet.bytes, packet.samples)?; |
| 208 | } | 221 | } |
| 209 | } | 222 | } |
| 210 | cancelled(shared)?; | 223 | cancelled(shared)?; |
| @@ -213,6 +226,33 @@ fn run( | |||
| 213 | Ok(()) | 226 | Ok(()) |
| 214 | } | 227 | } |
| 215 | 228 | ||
| 229 | +/// The I420 planes of one black picture, allocated once for a whole export: a | ||
| 230 | +/// gap in the video lane is encoded, not skipped, or every frame after it would | ||
| 231 | +/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention | ||
| 232 | +/// [`crate::convert`] decodes with. | ||
| 233 | +struct Black { | ||
| 234 | + y: Vec<u8>, | ||
| 235 | + uv: Vec<u8>, | ||
| 236 | + width: u32, | ||
| 237 | + height: u32, | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +impl Black { | ||
| 241 | + fn new(meta: &VideoMeta) -> Self { | ||
| 242 | + let (w, h) = (meta.width as usize, meta.height as usize); | ||
| 243 | + Self { | ||
| 244 | + y: vec![16; w * h], | ||
| 245 | + uv: vec![128; w.div_ceil(2) * h.div_ceil(2)], | ||
| 246 | + width: meta.width, | ||
| 247 | + height: meta.height, | ||
| 248 | + } | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { | ||
| 252 | + (&self.y, &self.uv, &self.uv, self.width, self.height) | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 216 | /// `Err` once a cancel has been asked for. Called at every point where the work | 256 | /// `Err` once a cancel has been asked for. Called at every point where the work |
| 217 | /// left is more than an instant, so an `esc` at 99.9% still stops the export | 257 | /// left is more than an instant, so an `esc` at 99.9% still stops the export |
| 218 | /// instead of quietly completing it. | 258 | /// instead of quietly completing it. |
crates/engine/src/mux.rsmodified+22 -4
| @@ -144,7 +144,12 @@ impl Mp4Muxer { | |||
| 144 | } | 144 | } |
| 145 | 145 | ||
| 146 | /// One raw AAC packet (no ADTS header), copied verbatim from the source. | 146 | /// One raw AAC packet (no ADTS header), copied verbatim from the source. |
| 147 | - pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> { | 147 | + /// `samples` is what the sample table says it occupies -- normally the |
| 148 | + /// [`AAC_PACKET_SAMPLES`] the codec fixes, but longer for the packet that | ||
| 149 | + /// carries a gap in the timeline's audio (see | ||
| 150 | + /// [`AudioSession::copy_multi_segments`](crate::AudioSession::copy_multi_segments)), | ||
| 151 | + /// where the extra duration is the silence a reader renders. | ||
| 152 | + pub fn write_audio_packet(&mut self, bytes: &[u8], samples: u32) -> crate::Result<()> { | ||
| 148 | if !self.has_audio { | 153 | if !self.has_audio { |
| 149 | return Err("audio packet written to a video-only file".into()); | 154 | return Err("audio packet written to a video-only file".into()); |
| 150 | } | 155 | } |
| @@ -152,7 +157,7 @@ impl Mp4Muxer { | |||
| 152 | AUDIO_TRACK, | 157 | AUDIO_TRACK, |
| 153 | &Mp4Sample { | 158 | &Mp4Sample { |
| 154 | start_time: 0, | 159 | start_time: 0, |
| 155 | - duration: AAC_PACKET_SAMPLES, | 160 | + duration: samples.max(AAC_PACKET_SAMPLES), |
| 156 | rendering_offset: 0, | 161 | rendering_offset: 0, |
| 157 | // Every AAC packet is a sync point; saying so per-sample would emit | 162 | // Every AAC packet is a sync point; saying so per-sample would emit |
| 158 | // an `stss` listing all of them, while no `stss` means the same thing. | 163 | // an `stss` listing all of them, while no `stss` means the same thing. |
| @@ -386,8 +391,14 @@ mod tests { | |||
| 386 | for unit in &units { | 391 | for unit in &units { |
| 387 | muxer.write_video_au(unit).unwrap(); | 392 | muxer.write_video_au(unit).unwrap(); |
| 388 | } | 393 | } |
| 389 | - muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap(); | 394 | + muxer |
| 390 | - muxer.write_audio_packet(&[0x24, 0x25]).unwrap(); | 395 | + .write_audio_packet(&[0x21, 0x22, 0x23], AAC_PACKET_SAMPLES) |
| 396 | + .unwrap(); | ||
| 397 | + // The second packet carries a gap: 1024 of its own plus half a second | ||
| 398 | + // of silence, which is what the sample table has to say. | ||
| 399 | + muxer | ||
| 400 | + .write_audio_packet(&[0x24, 0x25], AAC_PACKET_SAMPLES + 22_050) | ||
| 401 | + .unwrap(); | ||
| 391 | muxer.finish().unwrap(); | 402 | muxer.finish().unwrap(); |
| 392 | 403 | ||
| 393 | let file = File::open(&out).unwrap(); | 404 | let file = File::open(&out).unwrap(); |
| @@ -413,6 +424,13 @@ mod tests { | |||
| 413 | [0x21, 0x22, 0x23], | 424 | [0x21, 0x22, 0x23], |
| 414 | "audio packets copied verbatim" | 425 | "audio packets copied verbatim" |
| 415 | ); | 426 | ); |
| 427 | + let with_gap = reader.read_sample(audio_id, 2).unwrap().unwrap(); | ||
| 428 | + assert_eq!(&with_gap.bytes[..], [0x24, 0x25], "gap or not, verbatim"); | ||
| 429 | + assert_eq!( | ||
| 430 | + with_gap.duration, | ||
| 431 | + AAC_PACKET_SAMPLES + 22_050, | ||
| 432 | + "the gap is spent as duration, and the track ends half a second later" | ||
| 433 | + ); | ||
| 416 | 434 | ||
| 417 | let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap(); | 435 | let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap(); |
| 418 | assert_eq!(meta.frame_count, 3); | 436 | assert_eq!(meta.frame_count, 3); |
crates/engine/src/playback.rsmodified+107 -81
| @@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession}; | |||
| 23 | use crate::clock::{ClockSource, PlaybackClock}; | 23 | use crate::clock::{ClockSource, PlaybackClock}; |
| 24 | use crate::decode::{DecodeSession, Frame, Worker}; | 24 | use crate::decode::{DecodeSession, Frame, Worker}; |
| 25 | use crate::demux::{Demuxer, VideoMeta}; | 25 | use crate::demux::{Demuxer, VideoMeta}; |
| 26 | -use crate::project::{Clip, Project}; | 26 | +use crate::project::{Clip, Lane, Project, Span}; |
| 27 | 27 | ||
| 28 | /// How long the feeder waits out a full ring. The ring holds a second, so this | 28 | /// How long the feeder waits out a full ring. The ring holds a second, so this |
| 29 | /// only has to be short next to that; it costs one wakeup per 10 ms of audio. | 29 | /// only has to be short next to that; it costs one wakeup per 10 ms of audio. |
| @@ -104,12 +104,13 @@ pub struct PlaybackSession { | |||
| 104 | /// The edit list. Everything a caller says in seconds is a *timeline* | 104 | /// The edit list. Everything a caller says in seconds is a *timeline* |
| 105 | /// position; only this maps it onto the file. | 105 | /// position; only this maps it onto the file. |
| 106 | project: Project, | 106 | project: Project, |
| 107 | - /// Source range the current decode worker was opened for, and where that | 107 | + /// What the current video worker was opened for: where it sits on the |
| 108 | - /// range starts on the timeline -- together they rewrite a source frame | 108 | + /// timeline, how long it runs, and which source frame it started at -- |
| 109 | - /// index into a timeline one. Not a clip index: a `cut` splits the clip | 109 | + /// together they rewrite a source frame index into a timeline one. Not a |
| 110 | - /// under a running worker, and only the mapping survives that. | 110 | + /// clip index: a `split` cuts the clip under a running worker, and only the |
| 111 | - range: Clip, | 111 | + /// mapping survives that. A span with no source is a *gap*, and the worker |
| 112 | - timeline_start: u32, | 112 | + /// feeding it emits black frames indexed from zero. |
| 113 | + span: Span, | ||
| 113 | /// The last clip has been played out; see [`PlaybackSession::is_eos`]. | 114 | /// The last clip has been played out; see [`PlaybackSession::is_eos`]. |
| 114 | eos: bool, | 115 | eos: bool, |
| 115 | } | 116 | } |
| @@ -127,10 +128,10 @@ impl PlaybackSession { | |||
| 127 | Some(_) => ClockSource::Audio, | 128 | Some(_) => ClockSource::Audio, |
| 128 | None => ClockSource::Wall, | 129 | None => ClockSource::Wall, |
| 129 | }; | 130 | }; |
| 130 | - // One clip covering the file, so timeline == source until the first | 131 | + // One clip per lane covering the file, so timeline == source until the |
| 131 | - // edit -- and the range opened above is exactly that clip's. | 132 | + // first edit -- and the range opened above is exactly that clip's. |
| 132 | let project = Project::single(&path, meta.frame_count); | 133 | let project = Project::single(&path, meta.frame_count); |
| 133 | - let range = project.clips()[0]; | 134 | + let span = project.span_at(Lane::Video, 0).expect("never empty"); |
| 134 | Ok(Self { | 135 | Ok(Self { |
| 135 | meta, | 136 | meta, |
| 136 | frames, | 137 | frames, |
| @@ -139,8 +140,7 @@ impl PlaybackSession { | |||
| 139 | clock: PlaybackClock::new(source), | 140 | clock: PlaybackClock::new(source), |
| 140 | audio, | 141 | audio, |
| 141 | project, | 142 | project, |
| 142 | - range, | 143 | + span, |
| 143 | - timeline_start: 0, | ||
| 144 | eos: false, | 144 | eos: false, |
| 145 | }) | 145 | }) |
| 146 | } | 146 | } |
| @@ -178,7 +178,7 @@ impl PlaybackSession { | |||
| 178 | .map_err(|e| format!("source {}: {e}", source.display()))?; | 178 | .map_err(|e| format!("source {}: {e}", source.display()))?; |
| 179 | counts.push(other.frame_count); | 179 | counts.push(other.frame_count); |
| 180 | } | 180 | } |
| 181 | - for (i, clip) in doc.clips.iter().enumerate() { | 181 | + for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() { |
| 182 | if clip.out_frame > counts[clip.source] { | 182 | if clip.out_frame > counts[clip.source] { |
| 183 | return Err(format!( | 183 | return Err(format!( |
| 184 | "clip {i} ends at frame {} but {} has {} frames", | 184 | "clip {i} ends at frame {} but {} has {} frames", |
| @@ -191,9 +191,9 @@ impl PlaybackSession { | |||
| 191 | } | 191 | } |
| 192 | 192 | ||
| 193 | let playhead = doc.playhead; | 193 | let playhead = doc.playhead; |
| 194 | - let project = Project::from_parts(doc.sources, doc.clips) | 194 | + let project = Project::from_parts(doc.sources, doc.video, doc.audio) |
| 195 | .ok_or("the project's clips do not fit its sources")?; | 195 | .ok_or("the project's clips do not fit its sources")?; |
| 196 | - let range = project.clips()[0]; | 196 | + let span = project.span_at(Lane::Video, 0).expect("never empty"); |
| 197 | let mut session = Self { | 197 | let mut session = Self { |
| 198 | meta, | 198 | meta, |
| 199 | frames, | 199 | frames, |
| @@ -205,8 +205,7 @@ impl PlaybackSession { | |||
| 205 | }), | 205 | }), |
| 206 | audio, | 206 | audio, |
| 207 | project, | 207 | project, |
| 208 | - range, | 208 | + span, |
| 209 | - timeline_start: 0, | ||
| 210 | eos: false, | 209 | eos: false, |
| 211 | }; | 210 | }; |
| 212 | // The scaffolding above opened source 0 from its first frame and the | 211 | // The scaffolding above opened source 0 from its first frame and the |
| @@ -232,10 +231,10 @@ impl PlaybackSession { | |||
| 232 | /// [`crate::edith`]). Sources no clip plays from are left out, and the | 231 | /// [`crate::edith`]). Sources no clip plays from are left out, and the |
| 233 | /// playhead is saved with it so a reopened project resumes where it stood. | 232 | /// playhead is saved with it so a reopened project resumes where it stood. |
| 234 | pub fn save_project(&self, path: &Path) -> crate::Result<()> { | 233 | pub fn save_project(&self, path: &Path) -> crate::Result<()> { |
| 235 | - let (sources, clips) = self.project.without_orphan_sources(); | 234 | + let (sources, video, audio) = self.project.without_orphan_sources(); |
| 236 | let playhead = secs_to_frame(self.now(), self.meta.frame_rate) | 235 | let playhead = secs_to_frame(self.now(), self.meta.frame_rate) |
| 237 | .min(self.project.timeline_frames().saturating_sub(1)); | 236 | .min(self.project.timeline_frames().saturating_sub(1)); |
| 238 | - crate::edith::save(path, &sources, &clips, playhead) | 237 | + crate::edith::save(path, &sources, &video, &audio, playhead) |
| 239 | } | 238 | } |
| 240 | 239 | ||
| 241 | /// The next decoded frame, its `index` rewritten from a source frame to a | 240 | /// The next decoded frame, its `index` rewritten from a source frame to a |
| @@ -249,8 +248,10 @@ impl PlaybackSession { | |||
| 249 | loop { | 248 | loop { |
| 250 | match self.frames.try_recv() { | 249 | match self.frames.try_recv() { |
| 251 | Ok(mut frame) => { | 250 | Ok(mut frame) => { |
| 252 | - frame.index = | 251 | + // A gap's worker indexes from zero, a decoder's from its in |
| 253 | - self.timeline_start + frame.index.saturating_sub(self.range.in_frame); | 252 | + // point: `base` is whichever this span started at. |
| 253 | + let base = self.span.from.map_or(0, |(_, in_frame)| in_frame); | ||
| 254 | + frame.index = self.span.start + frame.index.saturating_sub(base); | ||
| 254 | return Some(frame); | 255 | return Some(frame); |
| 255 | } | 256 | } |
| 256 | Err(TryRecvError::Empty) => return None, | 257 | Err(TryRecvError::Empty) => return None, |
| @@ -287,41 +288,55 @@ impl PlaybackSession { | |||
| 287 | self.retired.retain(|w| !w.is_finished()); | 288 | self.retired.retain(|w| !w.is_finished()); |
| 288 | } | 289 | } |
| 289 | 290 | ||
| 290 | - /// Starts decoding whatever follows the current range on the timeline; | 291 | + /// Starts feeding whatever follows the current span on the timeline -- |
| 291 | - /// `false` past the end. The next timeline frame is derived rather than | 292 | + /// another clip, or a gap, which is black frames from a worker that opens no |
| 292 | - /// remembered as a clip index, because a `cut` while playing splits the | 293 | + /// file. `false` past the end. The next timeline frame is derived rather |
| 294 | + /// than remembered as a clip index, because a `split` while playing cuts the | ||
| 293 | /// clip under the running worker and only the mapping stays true. | 295 | /// clip under the running worker and only the mapping stays true. |
| 294 | fn next_clip(&mut self) -> bool { | 296 | fn next_clip(&mut self) -> bool { |
| 295 | - let next = self.timeline_start + self.range.len(); | 297 | + let next = self.span.end(); |
| 296 | - let Some((idx, source)) = self.project.map_timeline(next) else { | 298 | + let Some(span) = self.project.span_at(Lane::Video, next) else { |
| 297 | return false; | 299 | return false; |
| 298 | }; | 300 | }; |
| 299 | - let clip = self.project.clips()[idx]; | ||
| 300 | - let out = clip.out_frame; | ||
| 301 | // We only get here on a disconnect, so the old worker has already | 301 | // We only get here on a disconnect, so the old worker has already |
| 302 | // returned; cancel anyway, so `retire` treats every path alike. | 302 | // returned; cancel anyway, so `retire` treats every path alike. |
| 303 | self.worker.cancel(); | 303 | self.worker.cancel(); |
| 304 | - match DecodeSession::open_worker(&self.project.sources()[clip.source], source, out) { | 304 | + self.start_span(span); |
| 305 | - Ok((_, frames, worker)) => { | ||
| 306 | - // Receiver first, worker second: the drop of the old receiver | ||
| 307 | - // is what wakes a worker parked in `send`, and only then can it | ||
| 308 | - // return and be reaped by a later sweep. | ||
| 309 | - self.frames = frames; | ||
| 310 | - self.retire(worker); | ||
| 311 | - } | ||
| 312 | - // Disappearing-file case, as in `seek`. The old receiver is still | ||
| 313 | - // disconnected, so the next pass moves on to the clip after this. | ||
| 314 | - Err(e) => eprintln!("clip at timeline frame {next}: video open failed: {e}"), | ||
| 315 | - } | ||
| 316 | - self.range = Clip { | ||
| 317 | - in_frame: source, | ||
| 318 | - out_frame: out, | ||
| 319 | - ..clip | ||
| 320 | - }; | ||
| 321 | - self.timeline_start = next; | ||
| 322 | true | 305 | true |
| 323 | } | 306 | } |
| 324 | 307 | ||
| 308 | + /// Points the video worker at `span`: a decoder over its source range, or a | ||
| 309 | + /// black-frame generator for a gap. The old worker must already have been | ||
| 310 | + /// cancelled -- this is the half both `seek` and `next_clip` share. | ||
| 311 | + /// | ||
| 312 | + /// A source that will not open leaves the *span* installed anyway: the | ||
| 313 | + /// timeline still moves, there are simply no more pictures, and the | ||
| 314 | + /// disconnected receiver carries the session on to the next span. | ||
| 315 | + fn start_span(&mut self, span: Span) { | ||
| 316 | + let opened = match span.from { | ||
| 317 | + Some((source, in_frame)) => DecodeSession::open_worker( | ||
| 318 | + &self.project.sources()[source], | ||
| 319 | + in_frame, | ||
| 320 | + in_frame + span.len, | ||
| 321 | + ) | ||
| 322 | + .map(|(_, frames, worker)| (frames, worker)) | ||
| 323 | + .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)), | ||
| 324 | + None => Ok(DecodeSession::open_black( | ||
| 325 | + self.meta.width, | ||
| 326 | + self.meta.height, | ||
| 327 | + span.len, | ||
| 328 | + )), | ||
| 329 | + }; | ||
| 330 | + if let Ok((frames, worker)) = opened { | ||
| 331 | + // Receiver first, worker second: the drop of the old receiver is | ||
| 332 | + // what wakes a worker parked in `send`, and only then can it return | ||
| 333 | + // and be reaped by a later sweep. | ||
| 334 | + self.frames = frames; | ||
| 335 | + self.retire(worker); | ||
| 336 | + } | ||
| 337 | + self.span = span; | ||
| 338 | + } | ||
| 339 | + | ||
| 325 | /// Length of the edited timeline in seconds -- what a ruler shows, and it | 340 | /// Length of the edited timeline in seconds -- what a ruler shows, and it |
| 326 | /// shrinks with every delete. | 341 | /// shrinks with every delete. |
| 327 | pub fn timeline_duration(&self) -> f64 { | 342 | pub fn timeline_duration(&self) -> f64 { |
| @@ -343,20 +358,46 @@ impl PlaybackSession { | |||
| 343 | /// [`Project::sources`] each clip plays from -- what a lane needs to colour | 358 | /// [`Project::sources`] each clip plays from -- what a lane needs to colour |
| 344 | /// an imported clip differently from the file the session was opened with. | 359 | /// an imported clip differently from the file the session was opened with. |
| 345 | pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> { | 360 | pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> { |
| 346 | - self.clip_spans() | 361 | + self.lane_spans_by_source(Lane::Video) |
| 347 | - .into_iter() | 362 | + } |
| 348 | - .zip(self.project.clips()) | 363 | + |
| 349 | - .map(|((start, len), clip)| (start, len, clip.source)) | 364 | + /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane, |
| 365 | + /// with each clip's group id -- what a two-lane front-end draws. The holes | ||
| 366 | + /// between consecutive entries are the gaps. | ||
| 367 | + pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> { | ||
| 368 | + let fps = self.meta.frame_rate; | ||
| 369 | + self.project | ||
| 370 | + .lane(lane) | ||
| 371 | + .iter() | ||
| 372 | + .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source)) | ||
| 350 | .collect() | 373 | .collect() |
| 351 | } | 374 | } |
| 352 | 375 | ||
| 353 | - /// Splits the clip under `timeline_secs` in two. Metadata only: a cut never | 376 | + /// Splits every lane at `timeline_secs`, so the two sides become two |
| 354 | - /// changes the timeline->source mapping, so the running decoder stays | 377 | + /// groups. Metadata only: a split never changes the timeline->source |
| 355 | - /// correct and playback does not blink. `false` at a clip start or past the | 378 | + /// mapping, so the running decoder stays correct and playback does not |
| 356 | - /// end, where there would be nothing to split off. | 379 | + /// blink. `false` at a clip start, in a gap and past the end, where there |
| 380 | + /// would be nothing to split off. | ||
| 357 | pub fn cut_at(&mut self, timeline_secs: f64) -> bool { | 381 | pub fn cut_at(&mut self, timeline_secs: f64) -> bool { |
| 358 | self.project | 382 | self.project |
| 359 | - .cut(secs_to_frame(timeline_secs, self.meta.frame_rate)) | 383 | + .split(secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 384 | + } | ||
| 385 | + | ||
| 386 | + /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at | ||
| 387 | + /// `timeline_secs` in every lane and puts them back in one group. `false` | ||
| 388 | + /// unless a split could have produced what is there. Metadata only, like the | ||
| 389 | + /// split -- no reseek. | ||
| 390 | + pub fn regroup_at(&mut self, timeline_secs: f64) -> bool { | ||
| 391 | + self.project | ||
| 392 | + .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) | ||
| 393 | + } | ||
| 394 | + | ||
| 395 | + /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, | ||
| 396 | + /// silence on the audio one, and nothing else moves. Reseeks, because what | ||
| 397 | + /// the playhead sits on has changed. `false` for a bad index and for the | ||
| 398 | + /// lift that would leave the whole timeline empty. | ||
| 399 | + pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { | ||
| 400 | + self.edit(|p| p.lift(lane, idx)) | ||
| 360 | } | 401 | } |
| 361 | 402 | ||
| 362 | /// The clip at `idx` -- what a caller copies. It is a pair of source frame | 403 | /// The clip at `idx` -- what a caller copies. It is a pair of source frame |
| @@ -374,14 +415,16 @@ impl PlaybackSession { | |||
| 374 | self.edit(|p| p.paste(at, clip)) | 415 | self.edit(|p| p.paste(at, clip)) |
| 375 | } | 416 | } |
| 376 | 417 | ||
| 377 | - /// Removes a clip and closes the gap. Unlike a cut this *does* move every | 418 | + /// Removes the video clip at `idx` and everything under it, closing the gap |
| 378 | - /// following frame, so the session reseeks to wherever the playhead now | 419 | + /// on every lane. Unlike a split this *does* move every following frame, so |
| 379 | - /// points. `false` for a bad index or the last remaining clip. | 420 | + /// the session reseeks to wherever the playhead now points. |
| 421 | + /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead. | ||
| 422 | + /// `false` for a bad index or the last remaining clip. | ||
| 380 | pub fn delete_clip(&mut self, idx: usize) -> bool { | 423 | pub fn delete_clip(&mut self, idx: usize) -> bool { |
| 381 | self.edit(|p| p.delete(idx)) | 424 | self.edit(|p| p.delete(idx)) |
| 382 | } | 425 | } |
| 383 | 426 | ||
| 384 | - /// Undoes the last successful cut or delete, and reseeks like a delete. | 427 | + /// Undoes the last successful edit, and reseeks like a delete. |
| 385 | pub fn undo(&mut self) -> bool { | 428 | pub fn undo(&mut self) -> bool { |
| 386 | self.edit(Project::undo) | 429 | self.edit(Project::undo) |
| 387 | } | 430 | } |
| @@ -495,28 +538,11 @@ impl PlaybackSession { | |||
| 495 | // [`retire`](Self::retire), which is what keeps a scrub off the price | 538 | // [`retire`](Self::retire), which is what keeps a scrub off the price |
| 496 | // of a VA-API init. | 539 | // of a VA-API init. |
| 497 | self.worker.cancel(); | 540 | self.worker.cancel(); |
| 498 | - // `target` is inside the timeline (never empty), so this always maps; | 541 | + // `target` is inside the timeline (never empty), so this always spans; |
| 499 | - // the range runs from there to the end of the clip it landed in. | 542 | + // the span runs from there to the end of whatever it landed in -- a |
| 500 | - if let Some((idx, source)) = self.project.map_timeline(target) { | 543 | + // clip, or a gap, which starts a black-frame worker instead. |
| 501 | - let clip = self.project.clips()[idx]; | 544 | + if let Some(span) = self.project.span_at(Lane::Video, target) { |
| 502 | - let out = clip.out_frame; | 545 | + self.start_span(span); |
| 503 | - match DecodeSession::open_worker(&self.project.sources()[clip.source], source, out) { | ||
| 504 | - Ok((_, frames, worker)) => { | ||
| 505 | - // Receiver first, worker second -- see `next_clip`. | ||
| 506 | - self.frames = frames; | ||
| 507 | - self.retire(worker); | ||
| 508 | - } | ||
| 509 | - // The file opened once already, so this is a disappearing-file | ||
| 510 | - // case: the timeline still moves, there are simply no more | ||
| 511 | - // pictures. | ||
| 512 | - Err(e) => eprintln!("seek: video reopen failed: {e}"), | ||
| 513 | - } | ||
| 514 | - self.range = Clip { | ||
| 515 | - in_frame: source, | ||
| 516 | - out_frame: out, | ||
| 517 | - ..clip | ||
| 518 | - }; | ||
| 519 | - self.timeline_start = target; | ||
| 520 | } | 546 | } |
| 521 | self.eos = false; | 547 | self.eos = false; |
| 522 | 548 | ||
crates/engine/src/project.rsmodified+824 -322
| @@ -1,19 +1,36 @@ | |||
| 1 | -//! Edit list: the timeline as a list of source ranges. Pure data, no I/O. | 1 | +//! Edit list: two lanes of *placed* source ranges. Pure data, no I/O. |
| 2 | //! | 2 | //! |
| 3 | -//! A [`Project`] is an ordered list of [`Clip`]s, each a half-open `[in, out)` | 3 | +//! A [`Project`] holds a video lane and an audio lane. Each lane is a list of |
| 4 | -//! range of *source* frames. Playing the timeline means playing those ranges | 4 | +//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of |
| 5 | -//! back to back, so timeline frame `t` is found by walking the clips and | 5 | +//! *source* frames it plays, which file it plays it from, and -- the whole model |
| 6 | -//! consuming their lengths; the mapping is [`Project::map_timeline`] and it is | 6 | +//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an |
| 7 | -//! the only place that conversion lives. | 7 | +//! offset rather than queued end to end, so: |
| 8 | +//! | ||
| 9 | +//! * a **gap** is not an object, it is the absence of a placement. Nothing has | ||
| 10 | +//! to be inserted, kept in sync or garbage-collected for a hole to exist, and | ||
| 11 | +//! a hole cannot disagree with its neighbours about how long it is; | ||
| 12 | +//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a | ||
| 13 | +//! splice of the list; | ||
| 14 | +//! * the lanes are independent: deleting audio under a picture is one lane's | ||
| 15 | +//! business, and the picture does not shift. | ||
| 16 | +//! | ||
| 17 | +//! The price is one invariant this module enforces at every mutation and every | ||
| 18 | +//! constructor: within a lane, clips are **sorted by `start` and never overlap** | ||
| 19 | +//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a | ||
| 20 | +//! walk over that order. | ||
| 8 | //! | 21 | //! |
| 9 | //! Two frame spaces meet here and are never mixed: *source* frames index the | 22 | //! 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 | 23 | //! 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`). | 24 | //! (sample ids in the demuxer are 1-based; that conversion stays in `decode`). |
| 12 | //! | 25 | //! |
| 13 | -//! Editing is metadata only. [`Project::cut`] splits a clip in two without | 26 | +//! Grouping is [`Clip::link`]: clips carrying the same id were split from the |
| 14 | -//! changing any timeline->source mapping, so a running decoder stays correct | 27 | +//! same take and move together. [`Project::split`] cuts every lane at a timeline |
| 15 | -//! across a cut; [`Project::delete`] does change the mapping and the caller | 28 | +//! frame and hands the two sides two fresh ids; [`Project::regroup`] is its |
| 16 | -//! must reseek. Every successful edit snapshots the clip list, so | 29 | +//! inverse and rejoins them. |
| 30 | +//! | ||
| 31 | +//! Editing is metadata only. [`Project::split`] changes no timeline->source | ||
| 32 | +//! mapping, so a running decoder stays correct across it; everything else does | ||
| 33 | +//! and the caller must reseek. Every successful edit snapshots both lanes, so | ||
| 17 | //! [`Project::undo`] is an exact restore. | 34 | //! [`Project::undo`] is an exact restore. |
| 18 | //! | 35 | //! |
| 19 | //! A clip names its file by *index* into [`Project::sources`], which is | 36 | //! A clip names its file by *index* into [`Project::sources`], which is |
| @@ -25,13 +42,21 @@ | |||
| 25 | use std::path::{Path, PathBuf}; | 42 | use std::path::{Path, PathBuf}; |
| 26 | 43 | ||
| 27 | /// A half-open `[in_frame, out_frame)` range of frames of source | 44 | /// A half-open `[in_frame, out_frame)` range of frames of source |
| 28 | -/// [`source`](Clip::source). Never empty. | 45 | +/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). |
| 46 | +/// Never empty. | ||
| 29 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | 47 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 30 | pub struct Clip { | 48 | pub struct Clip { |
| 49 | + /// Timeline frame the clip's first frame is shown at. Meaningless on a | ||
| 50 | + /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it | ||
| 51 | + /// with where the caller asked for. | ||
| 52 | + pub start: u32, | ||
| 31 | pub in_frame: u32, | 53 | pub in_frame: u32, |
| 32 | pub out_frame: u32, | 54 | pub out_frame: u32, |
| 33 | /// Index into [`Project::sources`]. | 55 | /// Index into [`Project::sources`]. |
| 34 | pub source: usize, | 56 | pub source: usize, |
| 57 | + /// Group id: clips sharing one were split from the same take. `None` for a | ||
| 58 | + /// clip that belongs to no group. | ||
| 59 | + pub link: Option<u32>, | ||
| 35 | } | 60 | } |
| 36 | 61 | ||
| 37 | impl Clip { | 62 | impl Clip { |
| @@ -39,6 +64,48 @@ impl Clip { | |||
| 39 | pub fn len(&self) -> u32 { | 64 | pub fn len(&self) -> u32 { |
| 40 | self.out_frame - self.in_frame | 65 | self.out_frame - self.in_frame |
| 41 | } | 66 | } |
| 67 | + | ||
| 68 | + /// One past the last timeline frame it covers. | ||
| 69 | + pub fn end(&self) -> u32 { | ||
| 70 | + self.start + self.len() | ||
| 71 | + } | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// Which lane an operation acts on. The lanes are peers: no operation reads one | ||
| 75 | +/// to decide what to do to the other, except the grouped ones that say so. | ||
| 76 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 77 | +pub enum Lane { | ||
| 78 | + Video, | ||
| 79 | + Audio, | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +impl Lane { | ||
| 83 | + pub const ALL: [Lane; 2] = [Lane::Video, Lane::Audio]; | ||
| 84 | + | ||
| 85 | + fn index(self) -> usize { | ||
| 86 | + self as usize | ||
| 87 | + } | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// What a lane holds over one stretch of the timeline: either a placed clip or | ||
| 91 | +/// a gap. Returned already trimmed to the position it was asked about, so a | ||
| 92 | +/// caller can hand `len` straight to a decoder (or to a black-frame generator). | ||
| 93 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 94 | +pub struct Span { | ||
| 95 | + /// Timeline frame the span starts at. | ||
| 96 | + pub start: u32, | ||
| 97 | + /// Frames it covers; `>= 1`. | ||
| 98 | + pub len: u32, | ||
| 99 | + /// `(source index, first source frame)`, or `None` for a gap -- which the | ||
| 100 | + /// engine renders as black frames and as silence. | ||
| 101 | + pub from: Option<(usize, u32)>, | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +impl Span { | ||
| 105 | + /// One past the last timeline frame it covers. | ||
| 106 | + pub fn end(&self) -> u32 { | ||
| 107 | + self.start + self.len | ||
| 108 | + } | ||
| 42 | } | 109 | } |
| 43 | 110 | ||
| 44 | /// The edit list plus its undo history. | 111 | /// The edit list plus its undo history. |
| @@ -46,49 +113,77 @@ impl Clip { | |||
| 46 | pub struct Project { | 113 | pub struct Project { |
| 47 | /// Append-only: never popped, never reordered. See the module docs. | 114 | /// Append-only: never popped, never reordered. See the module docs. |
| 48 | sources: Vec<PathBuf>, | 115 | sources: Vec<PathBuf>, |
| 49 | - clips: Vec<Clip>, | 116 | + /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint. |
| 117 | + lanes: [Vec<Clip>; 2], | ||
| 50 | /// Snapshots pushed *before* each successful edit; `undo` pops one. | 118 | /// Snapshots pushed *before* each successful edit; `undo` pops one. |
| 51 | - history: Vec<Vec<Clip>>, | 119 | + history: Vec<[Vec<Clip>; 2]>, |
| 120 | + /// Never rolled back by an undo: an id retired by an undone split must not | ||
| 121 | + /// come back and group two clips that were never together. | ||
| 122 | + next_link: u32, | ||
| 52 | } | 123 | } |
| 53 | 124 | ||
| 54 | impl Project { | 125 | impl Project { |
| 55 | - /// One clip covering the whole of `path` -- the state of a freshly opened | 126 | + /// One clip per lane covering the whole of `path`, the two grouped -- the |
| 56 | - /// video, where the timeline is the source. `frame_count` of 0 would break | 127 | + /// state of a freshly opened video, where the timeline is the source. |
| 57 | - /// the never-empty invariant, so it is clamped to one frame. | 128 | + /// `frame_count` of 0 would break the never-empty invariant, so it is |
| 129 | + /// clamped to one frame. | ||
| 58 | pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self { | 130 | pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self { |
| 131 | + let clip = Clip { | ||
| 132 | + start: 0, | ||
| 133 | + in_frame: 0, | ||
| 134 | + out_frame: frame_count.max(1), | ||
| 135 | + source: 0, | ||
| 136 | + link: Some(0), | ||
| 137 | + }; | ||
| 59 | Self { | 138 | Self { |
| 60 | sources: vec![canonical(path.as_ref())], | 139 | sources: vec![canonical(path.as_ref())], |
| 61 | - clips: vec![Clip { | 140 | + lanes: [vec![clip], vec![clip]], |
| 62 | - in_frame: 0, | ||
| 63 | - out_frame: frame_count.max(1), | ||
| 64 | - source: 0, | ||
| 65 | - }], | ||
| 66 | history: Vec::new(), | 141 | history: Vec::new(), |
| 142 | + next_link: 1, | ||
| 67 | } | 143 | } |
| 68 | } | 144 | } |
| 69 | 145 | ||
| 70 | /// A project rebuilt from a saved edit list -- the load half of | 146 | /// A project rebuilt from a saved edit list -- the load half of |
| 71 | /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is | 147 | /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is |
| 72 | /// `false` until the first edit of the new session. `None` when the parts | 148 | /// `false` until the first edit of the new session. `None` when the parts |
| 73 | - /// would break an invariant every other constructor keeps: no clips, an | 149 | + /// would break an invariant every other constructor keeps: both lanes |
| 74 | - /// empty clip, or a clip naming a source that is not there. | 150 | + /// empty, an empty clip, a clip naming a source that is not there, or a |
| 75 | - pub fn from_parts(sources: Vec<PathBuf>, clips: Vec<Clip>) -> Option<Self> { | 151 | + /// lane that is unsorted or self-overlapping. |
| 76 | - if clips.is_empty() | 152 | + pub fn from_parts(sources: Vec<PathBuf>, video: Vec<Clip>, audio: Vec<Clip>) -> Option<Self> { |
| 77 | - || clips | 153 | + if video.is_empty() && audio.is_empty() { |
| 78 | - .iter() | ||
| 79 | - .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame) | ||
| 80 | - { | ||
| 81 | return None; | 154 | return None; |
| 82 | } | 155 | } |
| 156 | + let lanes = [video, audio]; | ||
| 157 | + if lanes.iter().any(|lane| { | ||
| 158 | + !sorted_disjoint(lane) | ||
| 159 | + || lane | ||
| 160 | + .iter() | ||
| 161 | + .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame) | ||
| 162 | + }) { | ||
| 163 | + return None; | ||
| 164 | + } | ||
| 165 | + let next_link = lanes | ||
| 166 | + .iter() | ||
| 167 | + .flatten() | ||
| 168 | + .filter_map(|c| c.link) | ||
| 169 | + .max() | ||
| 170 | + .map_or(0, |m| m + 1); | ||
| 83 | Some(Self { | 171 | Some(Self { |
| 84 | sources: sources.iter().map(|s| canonical(s)).collect(), | 172 | sources: sources.iter().map(|s| canonical(s)).collect(), |
| 85 | - clips, | 173 | + lanes, |
| 86 | history: Vec::new(), | 174 | history: Vec::new(), |
| 175 | + next_link, | ||
| 87 | }) | 176 | }) |
| 88 | } | 177 | } |
| 89 | 178 | ||
| 179 | + /// The video lane -- what an export renders and what a single-lane caller | ||
| 180 | + /// still means by "the clips". | ||
| 90 | pub fn clips(&self) -> &[Clip] { | 181 | pub fn clips(&self) -> &[Clip] { |
| 91 | - &self.clips | 182 | + self.lane(Lane::Video) |
| 183 | + } | ||
| 184 | + | ||
| 185 | + pub fn lane(&self, lane: Lane) -> &[Clip] { | ||
| 186 | + &self.lanes[lane.index()] | ||
| 92 | } | 187 | } |
| 93 | 188 | ||
| 94 | /// The files the clips index into, in import order; index 0 is the file the | 189 | /// The files the clips index into, in import order; index 0 is the file the |
| @@ -99,8 +194,8 @@ impl Project { | |||
| 99 | 194 | ||
| 100 | /// Index for `path`, appending it if it is new. Deduped by | 195 | /// Index for `path`, appending it if it is new. Deduped by |
| 101 | /// `fs::canonicalize`, so the same file reached by two paths imports once. | 196 | /// `fs::canonicalize`, so the same file reached by two paths imports once. |
| 102 | - /// The clip list is untouched -- see [`Project::append_clip`] -- so this | 197 | + /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes |
| 103 | - /// pushes no history: a source entry alone changes nothing playable. | 198 | + /// no history: a source entry alone changes nothing playable. |
| 104 | pub fn import(&mut self, path: impl AsRef<Path>) -> usize { | 199 | pub fn import(&mut self, path: impl AsRef<Path>) -> usize { |
| 105 | let path = canonical(path.as_ref()); | 200 | let path = canonical(path.as_ref()); |
| 106 | match self.sources.iter().position(|s| *s == path) { | 201 | match self.sources.iter().position(|s| *s == path) { |
| @@ -112,20 +207,26 @@ impl Project { | |||
| 112 | } | 207 | } |
| 113 | } | 208 | } |
| 114 | 209 | ||
| 115 | - /// Append a whole-file clip of `source` to the end of the timeline. One | 210 | + /// Append a whole-file clip of `source` to the end of *both* lanes, grouped |
| 116 | - /// history snapshot, so an import is one undo step -- and undoing it leaves | 211 | + /// -- an import lands as one take. One history snapshot, so an import is one |
| 117 | - /// the (harmless) source entry behind, because indexes are forever. | 212 | + /// undo step, and undoing it leaves the (harmless) source entry behind, |
| 118 | - /// Refused for an unknown source index. | 213 | + /// because indexes are forever. Refused for an unknown source index. |
| 119 | pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool { | 214 | pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool { |
| 120 | if source >= self.sources.len() { | 215 | if source >= self.sources.len() { |
| 121 | return false; | 216 | return false; |
| 122 | } | 217 | } |
| 123 | - self.history.push(self.clips.clone()); | 218 | + self.snapshot(); |
| 124 | - self.clips.push(Clip { | 219 | + let start = self.timeline_frames(); |
| 220 | + let clip = Clip { | ||
| 221 | + start, | ||
| 125 | in_frame: 0, | 222 | in_frame: 0, |
| 126 | out_frame: frame_count.max(1), | 223 | out_frame: frame_count.max(1), |
| 127 | source, | 224 | source, |
| 128 | - }); | 225 | + link: Some(self.new_link()), |
| 226 | + }; | ||
| 227 | + for lane in &mut self.lanes { | ||
| 228 | + lane.push(clip); | ||
| 229 | + } | ||
| 129 | true | 230 | true |
| 130 | } | 231 | } |
| 131 | 232 | ||
| @@ -134,12 +235,13 @@ impl Project { | |||
| 134 | /// [`Project::append_clip`]), so an undone import leaves an orphan source | 235 | /// [`Project::append_clip`]), so an undone import leaves an orphan source |
| 135 | /// entry behind; writing that orphan to a project file would let a file | 236 | /// entry behind; writing that orphan to a project file would let a file |
| 136 | /// nothing plays refuse a future load. New indexes are assigned in order of | 237 | /// nothing plays refuse a future load. New indexes are assigned in order of |
| 137 | - /// first use, so the same project always emits the same bytes. | 238 | + /// first use -- video lane first, then audio -- so the same project always |
| 138 | - pub fn without_orphan_sources(&self) -> (Vec<PathBuf>, Vec<Clip>) { | 239 | + /// emits the same bytes. |
| 240 | + pub fn without_orphan_sources(&self) -> (Vec<PathBuf>, Vec<Clip>, Vec<Clip>) { | ||
| 139 | let mut moved = vec![None; self.sources.len()]; | 241 | let mut moved = vec![None; self.sources.len()]; |
| 140 | let mut sources = Vec::new(); | 242 | let mut sources = Vec::new(); |
| 141 | - let mut clips = self.clips.clone(); | 243 | + let mut lanes = self.lanes.clone(); |
| 142 | - for c in &mut clips { | 244 | + for c in lanes.iter_mut().flatten() { |
| 143 | let old = c.source; | 245 | let old = c.source; |
| 144 | c.source = match moved[old] { | 246 | c.source = match moved[old] { |
| 145 | Some(new) => new, | 247 | Some(new) => new, |
| @@ -150,121 +252,267 @@ impl Project { | |||
| 150 | } | 252 | } |
| 151 | }; | 253 | }; |
| 152 | } | 254 | } |
| 153 | - (sources, clips) | 255 | + let [video, audio] = lanes; |
| 256 | + (sources, video, audio) | ||
| 154 | } | 257 | } |
| 155 | 258 | ||
| 156 | - /// Length of the timeline in frames. | 259 | + /// Length of the timeline in frames: where the *last* lane runs out. A lane |
| 260 | + /// that ends early is a trailing gap in that lane, not a shorter timeline. | ||
| 157 | pub fn timeline_frames(&self) -> u32 { | 261 | pub fn timeline_frames(&self) -> u32 { |
| 158 | - self.clips.iter().map(Clip::len).sum() | 262 | + self.lanes |
| 263 | + .iter() | ||
| 264 | + .filter_map(|lane| lane.last().map(Clip::end)) | ||
| 265 | + .max() | ||
| 266 | + .unwrap_or(0) | ||
| 159 | } | 267 | } |
| 160 | 268 | ||
| 161 | - /// `(timeline_start, len)` per clip, in order -- what a UI lane needs to | 269 | + /// `(timeline_start, len)` per video clip, in order -- what a UI lane needs |
| 162 | - /// lay clips out without redoing the cumulative sum. | 270 | + /// to lay clips out. Gaps show up as the holes between consecutive entries. |
| 163 | pub fn clip_spans(&self) -> Vec<(u32, u32)> { | 271 | pub fn clip_spans(&self) -> Vec<(u32, u32)> { |
| 164 | - let mut start = 0; | 272 | + self.lane_spans(Lane::Video) |
| 165 | - self.clips | 273 | + } |
| 166 | - .iter() | 274 | + |
| 167 | - .map(|c| { | 275 | + pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> { |
| 168 | - let span = (start, c.len()); | 276 | + self.lane(lane).iter().map(|c| (c.start, c.len())).collect() |
| 169 | - start += c.len(); | 277 | + } |
| 170 | - span | 278 | + |
| 171 | - }) | 279 | + /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap |
| 172 | - .collect() | 280 | + /// and past the end -- [`Project::span_at`] is the version that tells those |
| 281 | + /// two apart. | ||
| 282 | + pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> { | ||
| 283 | + let clips = self.lane(lane); | ||
| 284 | + let idx = at(clips, timeline_frame)?; | ||
| 285 | + Some(( | ||
| 286 | + idx, | ||
| 287 | + clips[idx].in_frame + (timeline_frame - clips[idx].start), | ||
| 288 | + )) | ||
| 173 | } | 289 | } |
| 174 | 290 | ||
| 175 | - /// Timeline frame -> `(clip index, source frame)`. `None` past the end. | 291 | + /// [`map`](Project::map) on the video lane -- the mapping a decoder follows. |
| 176 | pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> { | 292 | pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> { |
| 177 | - let mut start = 0; | 293 | + self.map(Lane::Video, timeline_frame) |
| 178 | - for (i, c) in self.clips.iter().enumerate() { | 294 | + } |
| 179 | - if timeline_frame < start + c.len() { | 295 | + |
| 180 | - return Some((i, c.in_frame + (timeline_frame - start))); | 296 | + /// What `lane` holds from `timeline_frame` on: the rest of the clip covering |
| 181 | - } | 297 | + /// it, or the gap running to the next clip (or to the end of the timeline, |
| 182 | - start += c.len(); | 298 | + /// which is where a lane shorter than its neighbour keeps showing black). |
| 299 | + /// `None` at or past the end of the timeline, which is the only "nothing | ||
| 300 | + /// left" there is. | ||
| 301 | + pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> { | ||
| 302 | + let total = self.timeline_frames(); | ||
| 303 | + if timeline_frame >= total { | ||
| 304 | + return None; | ||
| 305 | + } | ||
| 306 | + let clips = self.lane(lane); | ||
| 307 | + Some(match at(clips, timeline_frame) { | ||
| 308 | + Some(idx) => Span { | ||
| 309 | + start: timeline_frame, | ||
| 310 | + len: clips[idx].end() - timeline_frame, | ||
| 311 | + from: Some(( | ||
| 312 | + clips[idx].source, | ||
| 313 | + clips[idx].in_frame + (timeline_frame - clips[idx].start), | ||
| 314 | + )), | ||
| 315 | + }, | ||
| 316 | + None => Span { | ||
| 317 | + start: timeline_frame, | ||
| 318 | + // The next placement, or the end of the timeline: a gap is | ||
| 319 | + // bounded by what comes after it, never by its own bookkeeping. | ||
| 320 | + len: clips | ||
| 321 | + .iter() | ||
| 322 | + .find(|c| c.start > timeline_frame) | ||
| 323 | + .map_or(total, |c| c.start) | ||
| 324 | + - timeline_frame, | ||
| 325 | + from: None, | ||
| 326 | + }, | ||
| 327 | + }) | ||
| 328 | + } | ||
| 329 | + | ||
| 330 | + /// Every span of `lane` from `timeline_frame` to the end of the timeline, | ||
| 331 | + /// gaps included -- the whole play list, which is what an export walks. | ||
| 332 | + pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> { | ||
| 333 | + let mut out = Vec::new(); | ||
| 334 | + let mut t = timeline_frame; | ||
| 335 | + while let Some(span) = self.span_at(lane, t) { | ||
| 336 | + t = span.end(); | ||
| 337 | + out.push(span); | ||
| 183 | } | 338 | } |
| 184 | - None | 339 | + out |
| 185 | } | 340 | } |
| 186 | 341 | ||
| 187 | - /// Split the clip containing `timeline_frame` so that frame becomes the | 342 | + /// Split every lane at `timeline_frame`, so that frame becomes the first |
| 188 | - /// first frame of a new clip. Refused (`false`, no change) at timeline 0, | 343 | + /// frame of a new clip, and hand the two sides two fresh group ids. Refused |
| 189 | - /// at an existing clip boundary, and at or past the end -- all three would | 344 | + /// (`false`, no change) when no lane has a clip to split there -- at a |
| 190 | - /// produce an empty clip. Metadata only: no mapping changes. | 345 | + /// placement's own start, in a gap, and past the end -- all of which would |
| 191 | - pub fn cut(&mut self, timeline_frame: u32) -> bool { | 346 | + /// produce an empty clip or nothing at all. |
| 192 | - let Some((idx, source)) = self.map_timeline(timeline_frame) else { | 347 | + /// |
| 348 | + /// Metadata only: no mapping changes, in any lane. | ||
| 349 | + pub fn split(&mut self, timeline_frame: u32) -> bool { | ||
| 350 | + if !self | ||
| 351 | + .lanes | ||
| 352 | + .iter() | ||
| 353 | + .any(|lane| splittable(lane, timeline_frame).is_some()) | ||
| 354 | + { | ||
| 193 | return false; | 355 | return false; |
| 194 | - }; | ||
| 195 | - if source == self.clips[idx].in_frame { | ||
| 196 | - return false; // start of a clip: nothing to split off | ||
| 197 | } | 356 | } |
| 198 | - self.history.push(self.clips.clone()); | 357 | + self.snapshot(); |
| 199 | - let out = self.clips[idx].out_frame; | 358 | + let (left, right) = (self.new_link(), self.new_link()); |
| 200 | - self.clips[idx].out_frame = source; | 359 | + for lane in &mut self.lanes { |
| 201 | - self.clips.insert( | 360 | + let Some(idx) = splittable(lane, timeline_frame) else { |
| 202 | - idx + 1, | 361 | + continue; |
| 203 | - Clip { | 362 | + }; |
| 204 | - in_frame: source, | 363 | + let mut tail = lane[idx]; |
| 205 | - out_frame: out, | 364 | + tail.in_frame += timeline_frame - tail.start; |
| 206 | - ..self.clips[idx] | 365 | + tail.start = timeline_frame; |
| 207 | - }, | 366 | + tail.link = Some(right); |
| 208 | - ); | 367 | + lane[idx].out_frame = tail.in_frame; |
| 368 | + lane[idx].link = Some(left); | ||
| 369 | + lane.insert(idx + 1, tail); | ||
| 370 | + } | ||
| 209 | true | 371 | true |
| 210 | } | 372 | } |
| 211 | 373 | ||
| 212 | - /// Insert `clip` so that it starts at `timeline_frame`. Mid-clip the | 374 | + /// The inverse of [`split`](Project::split): rejoin the placements that meet |
| 213 | - /// containing clip is split there and `clip` goes between the halves; at an | 375 | + /// at `timeline_frame` in every lane and put the result back in one group. |
| 214 | - /// existing boundary (0 included) it goes in front of the clip that starts | 376 | + /// Only what a split could have produced is rejoined -- the two sides must |
| 215 | - /// there; at or past the end of the timeline it is appended -- a paste past | 377 | + /// touch on the timeline *and* be consecutive frames of the same source -- |
| 216 | - /// the end clamps rather than refuses, because there is nothing between the | 378 | + /// so the clip list comes back exactly as it was and traversal with it. |
| 217 | - /// end and it. Refused only for an empty `clip`, which the never-empty | 379 | + /// `false` when no lane has such a pair. |
| 218 | - /// invariant forbids but the public fields still allow a caller to build. | 380 | + pub fn regroup(&mut self, timeline_frame: u32) -> bool { |
| 381 | + if !self | ||
| 382 | + .lanes | ||
| 383 | + .iter() | ||
| 384 | + .any(|lane| joinable(lane, timeline_frame).is_some()) | ||
| 385 | + { | ||
| 386 | + return false; | ||
| 387 | + } | ||
| 388 | + self.snapshot(); | ||
| 389 | + let link = self.new_link(); | ||
| 390 | + for lane in &mut self.lanes { | ||
| 391 | + let Some(idx) = joinable(lane, timeline_frame) else { | ||
| 392 | + continue; | ||
| 393 | + }; | ||
| 394 | + lane[idx].out_frame = lane[idx + 1].out_frame; | ||
| 395 | + lane[idx].link = Some(link); | ||
| 396 | + lane.remove(idx + 1); | ||
| 397 | + } | ||
| 398 | + true | ||
| 399 | + } | ||
| 400 | + | ||
| 401 | + /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it | ||
| 402 | + /// lands on and leaving every other clip exactly where it is -- the | ||
| 403 | + /// per-lane paste. Anything already there is trimmed away (and split in two | ||
| 404 | + /// if `clip` lands inside it), which is what keeps the lane sorted and | ||
| 405 | + /// disjoint; nothing ripples, so a gap before the placement simply stays a | ||
| 406 | + /// gap. Refused only for an empty `clip`. | ||
| 407 | + pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool { | ||
| 408 | + if clip.out_frame <= clip.in_frame { | ||
| 409 | + return false; | ||
| 410 | + } | ||
| 411 | + self.snapshot(); | ||
| 412 | + let clip = Clip { | ||
| 413 | + start: timeline_frame, | ||
| 414 | + ..clip | ||
| 415 | + }; | ||
| 416 | + let lane = &mut self.lanes[lane.index()]; | ||
| 417 | + clear(lane, clip.start, clip.end()); | ||
| 418 | + let idx = lane.partition_point(|c| c.start < clip.start); | ||
| 419 | + lane.insert(idx, clip); | ||
| 420 | + debug_assert!(sorted_disjoint(lane)); | ||
| 421 | + true | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + /// Insert `clip` into *both* lanes at `timeline_frame` as one new group, | ||
| 425 | + /// pushing everything from there on later by its length -- the grouped, | ||
| 426 | + /// rippling paste a clipboard does. Mid-clip the clip it lands in is split | ||
| 427 | + /// around it; at or past the end of the timeline it is appended, because a | ||
| 428 | + /// paste means "put it here", not "put it here and leave black in front". | ||
| 429 | + /// Use [`place`](Project::place) to paste into one lane, or to make a gap. | ||
| 219 | /// | 430 | /// |
| 220 | - /// Exactly one history snapshot, so one [`Project::undo`] takes it back -- | 431 | + /// Exactly one history snapshot, so one [`Project::undo`] takes it back. |
| 221 | - /// hence the splice rather than a `cut` plus an insert. Changes the | 432 | + /// Changes the timeline->source mapping: the caller must reseek. Refused |
| 222 | - /// timeline->source mapping: the caller must reseek. | 433 | + /// only for an empty `clip`, which the never-empty invariant forbids but the |
| 434 | + /// public fields still allow a caller to build. | ||
| 223 | pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool { | 435 | pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool { |
| 224 | if clip.out_frame <= clip.in_frame { | 436 | if clip.out_frame <= clip.in_frame { |
| 225 | return false; | 437 | return false; |
| 226 | } | 438 | } |
| 227 | - self.history.push(self.clips.clone()); | 439 | + self.snapshot(); |
| 228 | - match self.map_timeline(timeline_frame) { | 440 | + let at = timeline_frame.min(self.timeline_frames()); |
| 229 | - Some((idx, source)) if source > self.clips[idx].in_frame => { | 441 | + let clip = Clip { |
| 230 | - let out = self.clips[idx].out_frame; | 442 | + start: at, |
| 231 | - self.clips[idx].out_frame = source; | 443 | + link: Some(self.new_link()), |
| 232 | - self.clips.splice( | 444 | + ..clip |
| 233 | - idx + 1..idx + 1, | 445 | + }; |
| 234 | - [ | 446 | + for lane in &mut self.lanes { |
| 235 | - clip, | 447 | + open_room(lane, at, clip.len()); |
| 236 | - Clip { | 448 | + let idx = lane.partition_point(|c| c.start < at); |
| 237 | - in_frame: source, | 449 | + lane.insert(idx, clip); |
| 238 | - out_frame: out, | 450 | + debug_assert!(sorted_disjoint(lane)); |
| 239 | - ..self.clips[idx] | ||
| 240 | - }, | ||
| 241 | - ], | ||
| 242 | - ); | ||
| 243 | - } | ||
| 244 | - Some((idx, _)) => self.clips.insert(idx, clip), | ||
| 245 | - None => self.clips.push(clip), | ||
| 246 | } | 451 | } |
| 247 | true | 452 | true |
| 248 | } | 453 | } |
| 249 | 454 | ||
| 250 | - /// Remove a clip and close the gap. Refused for an out-of-range index and | 455 | + /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or |
| 251 | - /// for the last remaining clip (an empty timeline is undefined this slice). | 456 | + /// silence, and nothing else moves. Refused for an out-of-range index and |
| 252 | - /// Changes the timeline->source mapping: the caller must reseek. | 457 | + /// for the lift that would leave *both* lanes empty -- an empty timeline is |
| 253 | - pub fn delete(&mut self, idx: usize) -> bool { | 458 | + /// the front-end's state, not a project's (see the never-empty invariant). |
| 254 | - if idx >= self.clips.len() || self.clips.len() == 1 { | 459 | + pub fn lift(&mut self, lane: Lane, idx: usize) -> bool { |
| 460 | + let placed: usize = self.lanes.iter().map(Vec::len).sum(); | ||
| 461 | + if idx >= self.lane(lane).len() || placed == 1 { | ||
| 255 | return false; | 462 | return false; |
| 256 | } | 463 | } |
| 257 | - self.history.push(self.clips.clone()); | 464 | + self.snapshot(); |
| 258 | - self.clips.remove(idx); | 465 | + self.lanes[lane.index()].remove(idx); |
| 259 | true | 466 | true |
| 260 | } | 467 | } |
| 261 | 468 | ||
| 262 | - /// Restore the clip list from before the last successful edit. `false` when | 469 | + /// Cut the timeline frames `[at, at + len)` out of *every* lane and close |
| 470 | + /// the hole: everything after slides back by `len`. The rippling delete -- | ||
| 471 | + /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an | ||
| 472 | + /// empty range and when it would leave both lanes empty. | ||
| 473 | + pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool { | ||
| 474 | + if len == 0 { | ||
| 475 | + return false; | ||
| 476 | + } | ||
| 477 | + let survivors: usize = self | ||
| 478 | + .lanes | ||
| 479 | + .iter() | ||
| 480 | + .map(|lane| { | ||
| 481 | + lane.iter() | ||
| 482 | + .filter(|c| c.start < at || c.end() > at + len) | ||
| 483 | + .count() | ||
| 484 | + }) | ||
| 485 | + .sum(); | ||
| 486 | + if survivors == 0 { | ||
| 487 | + return false; | ||
| 488 | + } | ||
| 489 | + self.snapshot(); | ||
| 490 | + for lane in &mut self.lanes { | ||
| 491 | + clear(lane, at, at + len); | ||
| 492 | + for c in lane.iter_mut().filter(|c| c.start >= at) { | ||
| 493 | + c.start -= len; | ||
| 494 | + } | ||
| 495 | + debug_assert!(sorted_disjoint(lane)); | ||
| 496 | + } | ||
| 497 | + true | ||
| 498 | + } | ||
| 499 | + | ||
| 500 | + /// Remove the video clip at `idx` and everything under it, closing the gap | ||
| 501 | + /// -- the whole-group delete a single-lane front-end means. `false` for a | ||
| 502 | + /// bad index. Changes the mapping: the caller must reseek. | ||
| 503 | + pub fn delete(&mut self, idx: usize) -> bool { | ||
| 504 | + let Some(clip) = self.clips().get(idx).copied() else { | ||
| 505 | + return false; | ||
| 506 | + }; | ||
| 507 | + self.ripple_delete(clip.start, clip.len()) | ||
| 508 | + } | ||
| 509 | + | ||
| 510 | + /// Restore both lanes from before the last successful edit. `false` when | ||
| 263 | /// there is nothing left to undo. | 511 | /// there is nothing left to undo. |
| 264 | pub fn undo(&mut self) -> bool { | 512 | pub fn undo(&mut self) -> bool { |
| 265 | match self.history.pop() { | 513 | match self.history.pop() { |
| 266 | Some(prev) => { | 514 | Some(prev) => { |
| 267 | - self.clips = prev; | 515 | + self.lanes = prev; |
| 268 | true | 516 | true |
| 269 | } | 517 | } |
| 270 | None => false, | 518 | None => false, |
| @@ -273,27 +521,120 @@ impl Project { | |||
| 273 | 521 | ||
| 274 | /// Half-open `(source, start, end)` segments in *source* seconds, from | 522 | /// Half-open `(source, start, end)` segments in *source* seconds, from |
| 275 | /// `timeline_frame` to the end of the timeline -- the play list for the | 523 | /// `timeline_frame` to the end of the timeline -- the play list for the |
| 276 | - /// audio worker. The first entry is partial when the position is mid-clip. | 524 | + /// audio worker, read off the **audio** lane. A `None` source is a gap: the |
| 277 | - /// Empty when the position is past the end or `fps` is not usable. | 525 | + /// worker synthesises that many seconds of silence, which is what keeps the |
| 278 | - pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(usize, f64, f64)> { | 526 | + /// audio master clock counting across a hole instead of stalling on it. |
| 527 | + /// The first entry is partial when the position is mid-clip. Empty when the | ||
| 528 | + /// position is past the end or `fps` is not usable. | ||
| 529 | + pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> { | ||
| 279 | if !(fps.is_finite() && fps > 0.0) { | 530 | if !(fps.is_finite() && fps > 0.0) { |
| 280 | return Vec::new(); | 531 | return Vec::new(); |
| 281 | } | 532 | } |
| 282 | - let Some((idx, source)) = self.map_timeline(timeline_frame) else { | 533 | + self.spans_from(Lane::Audio, timeline_frame) |
| 283 | - return Vec::new(); | 534 | + .iter() |
| 284 | - }; | 535 | + .map(|span| match span.from { |
| 285 | - let head = self.clips[idx]; | 536 | + // A clip's window is in *source* seconds: where in the file it |
| 286 | - let mut segs = vec![( | 537 | + // reads from, which a delete before it never shifts. |
| 287 | - head.source, | 538 | + Some((source, in_frame)) => ( |
| 288 | - source as f64 / fps, | 539 | + Some(source), |
| 289 | - head.out_frame as f64 / fps, | 540 | + f64::from(in_frame) / fps, |
| 290 | - )]; | 541 | + f64::from(in_frame + span.len) / fps, |
| 291 | - segs.extend( | 542 | + ), |
| 292 | - self.clips[idx + 1..] | 543 | + // A gap has no file, so all it can say is how long it is. |
| 293 | - .iter() | 544 | + None => (None, 0.0, f64::from(span.len) / fps), |
| 294 | - .map(|c| (c.source, c.in_frame as f64 / fps, c.out_frame as f64 / fps)), | 545 | + }) |
| 295 | - ); | 546 | + .collect() |
| 296 | - segs | 547 | + } |
| 548 | + | ||
| 549 | + /// Pushes the undo snapshot. Every mutating method calls this once, *after* | ||
| 550 | + /// it has decided it will succeed -- a refusal must not cost an undo step. | ||
| 551 | + fn snapshot(&mut self) { | ||
| 552 | + self.history.push(self.lanes.clone()); | ||
| 553 | + } | ||
| 554 | + | ||
| 555 | + fn new_link(&mut self) -> u32 { | ||
| 556 | + self.next_link += 1; | ||
| 557 | + self.next_link - 1 | ||
| 558 | + } | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +/// Index of the clip covering `frame`, or `None` for a gap or past the end. | ||
| 562 | +/// Binary search: the sorted-disjoint invariant is what makes it legal. | ||
| 563 | +fn at(clips: &[Clip], frame: u32) -> Option<usize> { | ||
| 564 | + let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?; | ||
| 565 | + (frame < clips[idx].end()).then_some(idx) | ||
| 566 | +} | ||
| 567 | + | ||
| 568 | +/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split | ||
| 569 | +/// there would cut in two. A placement's own first frame is not inside it. | ||
| 570 | +fn splittable(clips: &[Clip], frame: u32) -> Option<usize> { | ||
| 571 | + let idx = at(clips, frame)?; | ||
| 572 | + (frame > clips[idx].start).then_some(idx) | ||
| 573 | +} | ||
| 574 | + | ||
| 575 | +/// Index of the first of the two clips a [`Project::regroup`] at `frame` would | ||
| 576 | +/// rejoin: they must touch there, and be consecutive frames of one source. | ||
| 577 | +fn joinable(clips: &[Clip], frame: u32) -> Option<usize> { | ||
| 578 | + let idx = clips.iter().position(|c| c.end() == frame)?; | ||
| 579 | + let next = clips.get(idx + 1)?; | ||
| 580 | + (next.start == frame | ||
| 581 | + && next.source == clips[idx].source | ||
| 582 | + && next.in_frame == clips[idx].out_frame) | ||
| 583 | + .then_some(idx) | ||
| 584 | +} | ||
| 585 | + | ||
| 586 | +/// The lane invariant: sorted by `start`, no two placements overlapping, no | ||
| 587 | +/// empty placement. Checked at every constructor and asserted after every | ||
| 588 | +/// mutation -- the offset model is only tractable while it holds. | ||
| 589 | +fn sorted_disjoint(clips: &[Clip]) -> bool { | ||
| 590 | + clips.iter().all(|c| c.out_frame > c.in_frame) | ||
| 591 | + && clips.windows(2).all(|w| w[0].end() <= w[1].start) | ||
| 592 | +} | ||
| 593 | + | ||
| 594 | +/// Removes the timeline frames `[start, end)` from `clips`: placements inside | ||
| 595 | +/// it go, one straddling it is split in two, one overlapping an edge is | ||
| 596 | +/// trimmed. Source frames follow the trim, so what is left plays what it always | ||
| 597 | +/// played. Leaves the lane sorted and disjoint. | ||
| 598 | +fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) { | ||
| 599 | + let mut out = Vec::with_capacity(clips.len() + 1); | ||
| 600 | + for c in clips.drain(..) { | ||
| 601 | + // Disjoint from the hole: untouched. | ||
| 602 | + if c.end() <= start || c.start >= end { | ||
| 603 | + out.push(c); | ||
| 604 | + continue; | ||
| 605 | + } | ||
| 606 | + // The head that survives in front of the hole. | ||
| 607 | + if c.start < start { | ||
| 608 | + out.push(Clip { | ||
| 609 | + out_frame: c.in_frame + (start - c.start), | ||
| 610 | + ..c | ||
| 611 | + }); | ||
| 612 | + } | ||
| 613 | + // ...and the tail behind it, which keeps reading where it would have. | ||
| 614 | + if c.end() > end { | ||
| 615 | + out.push(Clip { | ||
| 616 | + start: end, | ||
| 617 | + in_frame: c.in_frame + (end - c.start), | ||
| 618 | + ..c | ||
| 619 | + }); | ||
| 620 | + } | ||
| 621 | + } | ||
| 622 | + *clips = out; | ||
| 623 | +} | ||
| 624 | + | ||
| 625 | +/// Slides everything from `at` on later by `len`, splitting a placement that | ||
| 626 | +/// straddles `at` so the two halves end up on either side of the hole. The | ||
| 627 | +/// insert half of a rippling paste. | ||
| 628 | +fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) { | ||
| 629 | + if let Some(idx) = splittable(clips, at) { | ||
| 630 | + let mut tail = clips[idx]; | ||
| 631 | + tail.in_frame += at - tail.start; | ||
| 632 | + tail.start = at; | ||
| 633 | + clips[idx].out_frame = tail.in_frame; | ||
| 634 | + clips.insert(idx + 1, tail); | ||
| 635 | + } | ||
| 636 | + for c in clips.iter_mut().filter(|c| c.start >= at) { | ||
| 637 | + c.start += len; | ||
| 297 | } | 638 | } |
| 298 | } | 639 | } |
| 299 | 640 | ||
| @@ -314,41 +655,62 @@ mod tests { | |||
| 314 | const FILE: &str = "/nonexistent/a.mp4"; | 655 | const FILE: &str = "/nonexistent/a.mp4"; |
| 315 | const FILE2: &str = "/nonexistent/b.mp4"; | 656 | const FILE2: &str = "/nonexistent/b.mp4"; |
| 316 | 657 | ||
| 317 | - /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built | 658 | + /// A contiguous placement, group id ignored: what most assertions compare. |
| 318 | - /// through `cut` so the constructor path is exercised too. | 659 | + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip { |
| 660 | + Clip { | ||
| 661 | + start, | ||
| 662 | + in_frame, | ||
| 663 | + out_frame, | ||
| 664 | + source, | ||
| 665 | + link: None, | ||
| 666 | + } | ||
| 667 | + } | ||
| 668 | + | ||
| 669 | + /// Both lanes with their group ids blanked, for comparing shape. | ||
| 670 | + fn shape(p: &Project) -> [Vec<Clip>; 2] { | ||
| 671 | + Lane::ALL.map(|l| { | ||
| 672 | + p.lane(l) | ||
| 673 | + .iter() | ||
| 674 | + .map(|c| Clip { link: None, ..*c }) | ||
| 675 | + .collect() | ||
| 676 | + }) | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + /// The *source frame* every timeline frame reads, per lane -- the traversal | ||
| 680 | + /// a player performs. Deliberately not the clip index: a split changes which | ||
| 681 | + /// clip a frame belongs to, and nothing else. | ||
| 682 | + fn traversal(p: &Project) -> Vec<[Option<u32>; 2]> { | ||
| 683 | + (0..p.timeline_frames() + 2) | ||
| 684 | + .map(|f| Lane::ALL.map(|l| p.map(l, f).map(|(_, source)| source))) | ||
| 685 | + .collect() | ||
| 686 | + } | ||
| 687 | + | ||
| 688 | + /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one | ||
| 689 | + /// fixture. Built through `split` so the constructor path is exercised too. | ||
| 319 | fn three() -> Project { | 690 | fn three() -> Project { |
| 320 | let mut p = Project::single(FILE, 9); | 691 | let mut p = Project::single(FILE, 9); |
| 321 | - assert!(p.cut(3)); | 692 | + assert!(p.split(3)); |
| 322 | - assert!(p.cut(5)); | 693 | + assert!(p.split(5)); |
| 323 | assert_eq!( | 694 | assert_eq!( |
| 324 | - p.clips(), | 695 | + shape(&p), |
| 325 | [ | 696 | [ |
| 326 | - Clip { | 697 | + vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)], |
| 327 | - source: 0, | 698 | + vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)], |
| 328 | - in_frame: 0, | ||
| 329 | - out_frame: 3 | ||
| 330 | - }, | ||
| 331 | - Clip { | ||
| 332 | - source: 0, | ||
| 333 | - in_frame: 3, | ||
| 334 | - out_frame: 5 | ||
| 335 | - }, | ||
| 336 | - Clip { | ||
| 337 | - source: 0, | ||
| 338 | - in_frame: 5, | ||
| 339 | - out_frame: 9 | ||
| 340 | - }, | ||
| 341 | ] | 699 | ] |
| 342 | ); | 700 | ); |
| 343 | p | 701 | p |
| 344 | } | 702 | } |
| 345 | 703 | ||
| 346 | #[test] | 704 | #[test] |
| 347 | - fn single_is_the_whole_file() { | 705 | + fn single_is_the_whole_file_on_both_lanes() { |
| 348 | let p = Project::single(FILE, 150); | 706 | let p = Project::single(FILE, 150); |
| 349 | assert_eq!(p.clips().len(), 1); | 707 | assert_eq!(p.clips().len(), 1); |
| 708 | + assert_eq!(p.lane(Lane::Audio).len(), 1); | ||
| 350 | assert_eq!(p.timeline_frames(), 150); | 709 | assert_eq!(p.timeline_frames(), 150); |
| 351 | assert_eq!(p.clip_spans(), vec![(0, 150)]); | 710 | assert_eq!(p.clip_spans(), vec![(0, 150)]); |
| 711 | + // grouped: video and audio carry the same link | ||
| 712 | + assert_eq!(p.clips()[0].link, p.lane(Lane::Audio)[0].link); | ||
| 713 | + assert!(p.clips()[0].link.is_some()); | ||
| 352 | // degenerate mapping: timeline == source | 714 | // degenerate mapping: timeline == source |
| 353 | assert_eq!(p.map_timeline(0), Some((0, 0))); | 715 | assert_eq!(p.map_timeline(0), Some((0, 0))); |
| 354 | assert_eq!(p.map_timeline(149), Some((0, 149))); | 716 | assert_eq!(p.map_timeline(149), Some((0, 149))); |
| @@ -358,54 +720,77 @@ mod tests { | |||
| 358 | } | 720 | } |
| 359 | 721 | ||
| 360 | #[test] | 722 | #[test] |
| 361 | - fn cut_mid_clip_splits() { | 723 | + fn split_cuts_every_lane_and_regroups_it_back() { |
| 362 | let mut p = Project::single(FILE, 9); | 724 | let mut p = Project::single(FILE, 9); |
| 363 | - assert!(p.cut(4)); | 725 | + let before = traversal(&p); |
| 726 | + let before_shape = shape(&p); | ||
| 727 | + | ||
| 728 | + assert!(p.split(4)); | ||
| 729 | + for l in Lane::ALL { | ||
| 730 | + assert_eq!(p.lane(l).len(), 2, "{l:?} split"); | ||
| 731 | + } | ||
| 732 | + // The two sides are two groups, one per side, matching across the lanes. | ||
| 733 | + let (v, a) = (p.lane(Lane::Video), p.lane(Lane::Audio)); | ||
| 734 | + assert_eq!(v[0].link, a[0].link); | ||
| 735 | + assert_eq!(v[1].link, a[1].link); | ||
| 736 | + assert_ne!(v[0].link, v[1].link, "the halves are no longer one take"); | ||
| 737 | + // A split changes no mapping, in either lane. | ||
| 738 | + assert_eq!(traversal(&p), before, "a split moves nothing"); | ||
| 739 | + | ||
| 740 | + assert!(p.regroup(4), "the inverse rejoins them"); | ||
| 741 | + assert_eq!(shape(&p), before_shape, "bit-exact back to one clip"); | ||
| 742 | + assert_eq!(traversal(&p), before); | ||
| 364 | assert_eq!( | 743 | assert_eq!( |
| 365 | - p.clips(), | 744 | + p.lane(Lane::Video)[0].link, |
| 366 | - [ | 745 | + p.lane(Lane::Audio)[0].link, |
| 367 | - Clip { | 746 | + "and the rejoined clip is one group again" |
| 368 | - source: 0, | ||
| 369 | - in_frame: 0, | ||
| 370 | - out_frame: 4 | ||
| 371 | - }, | ||
| 372 | - Clip { | ||
| 373 | - source: 0, | ||
| 374 | - in_frame: 4, | ||
| 375 | - out_frame: 9 | ||
| 376 | - }, | ||
| 377 | - ] | ||
| 378 | ); | 747 | ); |
| 379 | - assert_eq!(p.timeline_frames(), 9); | ||
| 380 | } | 748 | } |
| 381 | 749 | ||
| 382 | #[test] | 750 | #[test] |
| 383 | - fn cut_refused_at_zero_boundary_and_end() { | 751 | + fn split_refused_at_zero_boundary_end_and_in_a_gap() { |
| 384 | let mut p = three(); | 752 | let mut p = three(); |
| 385 | - let before = p.clips().to_vec(); | 753 | + let before = shape(&p); |
| 386 | - assert!(!p.cut(0), "timeline 0 has nothing before it"); | 754 | + assert!(!p.split(0), "timeline 0 has nothing before it"); |
| 387 | - assert!(!p.cut(3), "existing boundary"); | 755 | + assert!(!p.split(3), "existing boundary"); |
| 388 | - assert!(!p.cut(5), "existing boundary"); | 756 | + assert!(!p.split(5), "existing boundary"); |
| 389 | - assert!(!p.cut(9), "one past the last frame"); | 757 | + assert!(!p.split(9), "one past the last frame"); |
| 390 | - assert!(!p.cut(1_000)); | 758 | + assert!(!p.split(1_000)); |
| 391 | - assert_eq!(p.clips(), before.as_slice()); | 759 | + assert_eq!(shape(&p), before); |
| 392 | - // one undo lands before the *second* cut, so the refusals pushed nothing | 760 | + // one undo lands before the *second* split, so the refusals pushed nothing |
| 393 | assert!(p.undo()); | 761 | assert!(p.undo()); |
| 394 | - assert_eq!(p.clips().len(), 2, "refused cuts push no history"); | 762 | + assert_eq!(p.clips().len(), 2, "refused splits push no history"); |
| 763 | + | ||
| 764 | + // ...and a frame that is a gap in both lanes has nothing to split. | ||
| 765 | + let mut p = three(); | ||
| 766 | + assert!(p.lift(Lane::Video, 1)); | ||
| 767 | + assert!(p.lift(Lane::Audio, 1)); | ||
| 768 | + assert!(!p.split(4), "a gap is not a clip"); | ||
| 395 | } | 769 | } |
| 396 | 770 | ||
| 397 | #[test] | 771 | #[test] |
| 398 | - fn cut_never_changes_the_mapping() { | 772 | + fn regroup_refuses_what_a_split_could_not_have_made() { |
| 399 | - let p = three(); | 773 | + let mut p = three(); |
| 400 | - let before: Vec<_> = (0..9).map(|f| p.map_timeline(f).unwrap().1).collect(); | 774 | + // [3,5) and [5,9) are source-contiguous: that pair rejoins. |
| 401 | - let mut after = p.clone(); | 775 | + assert!(p.regroup(5)); |
| 402 | - assert!(after.cut(7)); | 776 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]); |
| 403 | - let now: Vec<_> = (0..9).map(|f| after.map_timeline(f).unwrap().1).collect(); | 777 | + // A boundary with a gap on one side, and one where the sources do not |
| 404 | - assert_eq!(before, now); | 778 | + // meet, are both refused. |
| 779 | + let mut p = three(); | ||
| 780 | + assert!(p.lift(Lane::Video, 1)); | ||
| 781 | + assert!(p.lift(Lane::Audio, 1)); | ||
| 782 | + assert!(!p.regroup(3), "nothing starts at 3 any more"); | ||
| 783 | + let mut p = three(); | ||
| 784 | + for l in Lane::ALL { | ||
| 785 | + assert!(p.place(l, 3, clip(0, 100, 102, 0))); | ||
| 786 | + } | ||
| 787 | + assert!(!p.regroup(3), "source 100 does not follow source 3"); | ||
| 788 | + assert!(!p.regroup(0), "nothing ends at 0"); | ||
| 789 | + assert!(!p.regroup(1_000)); | ||
| 405 | } | 790 | } |
| 406 | 791 | ||
| 407 | #[test] | 792 | #[test] |
| 408 | - fn map_timeline_sweeps_every_boundary() { | 793 | + fn map_and_spans_sweep_every_boundary() { |
| 409 | let p = three(); | 794 | let p = three(); |
| 410 | assert_eq!(p.timeline_frames(), 9); | 795 | assert_eq!(p.timeline_frames(), 9); |
| 411 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]); | 796 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]); |
| @@ -425,14 +810,26 @@ mod tests { | |||
| 425 | assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}"); | 810 | assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}"); |
| 426 | } | 811 | } |
| 427 | assert_eq!(p.map_timeline(9), None); | 812 | assert_eq!(p.map_timeline(9), None); |
| 813 | + // A span is the rest of the clip from where it was asked about. | ||
| 814 | + assert_eq!( | ||
| 815 | + p.span_at(Lane::Video, 6), | ||
| 816 | + Some(Span { | ||
| 817 | + start: 6, | ||
| 818 | + len: 3, | ||
| 819 | + from: Some((0, 6)) | ||
| 820 | + }) | ||
| 821 | + ); | ||
| 822 | + assert_eq!(p.span_at(Lane::Video, 9), None); | ||
| 428 | } | 823 | } |
| 429 | 824 | ||
| 430 | /// The clip a copy would hand back: source `[100, 102)`, unrelated to | 825 | /// The clip a copy would hand back: source `[100, 102)`, unrelated to |
| 431 | /// anything in `three()` so it is recognisable wherever it lands. | 826 | /// anything in `three()` so it is recognisable wherever it lands. |
| 432 | const PASTED: Clip = Clip { | 827 | const PASTED: Clip = Clip { |
| 433 | - source: 0, | 828 | + start: 0, |
| 434 | in_frame: 100, | 829 | in_frame: 100, |
| 435 | out_frame: 102, | 830 | out_frame: 102, |
| 831 | + source: 0, | ||
| 832 | + link: None, | ||
| 436 | }; | 833 | }; |
| 437 | 834 | ||
| 438 | #[test] | 835 | #[test] |
| @@ -441,31 +838,16 @@ mod tests { | |||
| 441 | assert!(p.paste(6, PASTED)); // inside [5,9), one frame in | 838 | assert!(p.paste(6, PASTED)); // inside [5,9), one frame in |
| 442 | assert_eq!(p.timeline_frames(), 11); | 839 | assert_eq!(p.timeline_frames(), 11); |
| 443 | assert_eq!( | 840 | assert_eq!( |
| 444 | - p.clips(), | 841 | + shape(&p)[0], |
| 445 | - [ | 842 | + vec![ |
| 446 | - Clip { | 843 | + clip(0, 0, 3, 0), |
| 447 | - source: 0, | 844 | + clip(3, 3, 5, 0), |
| 448 | - in_frame: 0, | 845 | + clip(5, 5, 6, 0), |
| 449 | - out_frame: 3 | 846 | + clip(6, 100, 102, 0), |
| 450 | - }, | 847 | + clip(8, 6, 9, 0), |
| 451 | - Clip { | ||
| 452 | - source: 0, | ||
| 453 | - in_frame: 3, | ||
| 454 | - out_frame: 5 | ||
| 455 | - }, | ||
| 456 | - Clip { | ||
| 457 | - source: 0, | ||
| 458 | - in_frame: 5, | ||
| 459 | - out_frame: 6 | ||
| 460 | - }, | ||
| 461 | - PASTED, | ||
| 462 | - Clip { | ||
| 463 | - source: 0, | ||
| 464 | - in_frame: 6, | ||
| 465 | - out_frame: 9 | ||
| 466 | - }, | ||
| 467 | ] | 848 | ] |
| 468 | ); | 849 | ); |
| 850 | + assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes"); | ||
| 469 | // The pasted frames are exactly where they were asked for, and the | 851 | // The pasted frames are exactly where they were asked for, and the |
| 470 | // split-off remainder resumes after them. | 852 | // split-off remainder resumes after them. |
| 471 | assert_eq!(p.map_timeline(6), Some((3, 100))); | 853 | assert_eq!(p.map_timeline(6), Some((3, 100))); |
| @@ -485,7 +867,8 @@ mod tests { | |||
| 485 | assert_eq!(p.map_timeline(0), Some((0, 100))); | 867 | assert_eq!(p.map_timeline(0), Some((0, 100))); |
| 486 | assert_eq!(p.map_timeline(2), Some((1, 0))); | 868 | assert_eq!(p.map_timeline(2), Some((1, 0))); |
| 487 | 869 | ||
| 488 | - // At the end and past it both append -- there is nothing to sit before. | 870 | + // At the end and past it both append -- a paste never leaves black in |
| 871 | + // front of itself; `place` is the call that makes a gap. | ||
| 489 | let mut p = three(); | 872 | let mut p = three(); |
| 490 | assert!(p.paste(9, PASTED)); | 873 | assert!(p.paste(9, PASTED)); |
| 491 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]); | 874 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]); |
| @@ -494,24 +877,17 @@ mod tests { | |||
| 494 | 877 | ||
| 495 | // An empty clip is the one thing refused, and it pushes no history. | 878 | // An empty clip is the one thing refused, and it pushes no history. |
| 496 | let mut p = three(); | 879 | let mut p = three(); |
| 497 | - assert!(!p.paste( | 880 | + assert!(!p.paste(4, clip(0, 7, 7, 0))); |
| 498 | - 4, | ||
| 499 | - Clip { | ||
| 500 | - source: 0, | ||
| 501 | - in_frame: 7, | ||
| 502 | - out_frame: 7 | ||
| 503 | - } | ||
| 504 | - )); | ||
| 505 | assert_eq!(p.clips().len(), 3); | 881 | assert_eq!(p.clips().len(), 3); |
| 506 | } | 882 | } |
| 507 | 883 | ||
| 508 | #[test] | 884 | #[test] |
| 509 | fn paste_undoes_in_one_step() { | 885 | fn paste_undoes_in_one_step() { |
| 510 | let mut p = three(); | 886 | let mut p = three(); |
| 511 | - let before = p.clips().to_vec(); | 887 | + let before = shape(&p); |
| 512 | assert!(p.paste(6, PASTED)); | 888 | assert!(p.paste(6, PASTED)); |
| 513 | assert!(p.undo()); | 889 | assert!(p.undo()); |
| 514 | - assert_eq!(p.clips(), before.as_slice(), "a paste is one undo step"); | 890 | + assert_eq!(shape(&p), before, "a paste is one undo step"); |
| 515 | } | 891 | } |
| 516 | 892 | ||
| 517 | #[test] | 893 | #[test] |
| @@ -526,11 +902,12 @@ mod tests { | |||
| 526 | } | 902 | } |
| 527 | 903 | ||
| 528 | #[test] | 904 | #[test] |
| 529 | - fn delete_closes_the_gap() { | 905 | + fn delete_closes_the_gap_on_both_lanes() { |
| 530 | let mut p = three(); | 906 | let mut p = three(); |
| 531 | assert!(p.delete(1)); | 907 | assert!(p.delete(1)); |
| 532 | assert_eq!(p.timeline_frames(), 7); | 908 | assert_eq!(p.timeline_frames(), 7); |
| 533 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]); | 909 | assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]); |
| 910 | + assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 4)]); | ||
| 534 | // timeline 3 used to be source 3; the gap closed so it is source 5 now | 911 | // timeline 3 used to be source 3; the gap closed so it is source 5 now |
| 535 | assert_eq!(p.map_timeline(3), Some((1, 5))); | 912 | assert_eq!(p.map_timeline(3), Some((1, 5))); |
| 536 | assert_eq!(p.map_timeline(6), Some((1, 8))); | 913 | assert_eq!(p.map_timeline(6), Some((1, 8))); |
| @@ -555,60 +932,201 @@ mod tests { | |||
| 555 | assert_eq!(p.clips().len(), 1); | 932 | assert_eq!(p.clips().len(), 1); |
| 556 | } | 933 | } |
| 557 | 934 | ||
| 935 | + /// The offset model's point: one lane loses a clip, the other does not move. | ||
| 936 | + #[test] | ||
| 937 | + fn a_lift_leaves_a_gap_and_moves_nothing() { | ||
| 938 | + let mut p = three(); | ||
| 939 | + let video_before = shape(&p)[0].clone(); | ||
| 940 | + assert!(p.lift(Lane::Audio, 1)); | ||
| 941 | + assert_eq!(shape(&p)[0], video_before, "the picture never moved"); | ||
| 942 | + assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter"); | ||
| 943 | + assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (5, 4)]); | ||
| 944 | + // The hole is a gap: mapped as nothing, spanned as a gap of its length. | ||
| 945 | + assert_eq!(p.map(Lane::Audio, 4), None); | ||
| 946 | + assert_eq!( | ||
| 947 | + p.span_at(Lane::Audio, 3), | ||
| 948 | + Some(Span { | ||
| 949 | + start: 3, | ||
| 950 | + len: 2, | ||
| 951 | + from: None | ||
| 952 | + }) | ||
| 953 | + ); | ||
| 954 | + assert_eq!(p.map(Lane::Video, 4), Some((1, 4)), "video plays on"); | ||
| 955 | + assert!(p.undo()); | ||
| 956 | + assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 2), (5, 4)]); | ||
| 957 | + } | ||
| 958 | + | ||
| 959 | + #[test] | ||
| 960 | + fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() { | ||
| 961 | + let mut p = three(); | ||
| 962 | + assert!(p.lift(Lane::Audio, 2)); | ||
| 963 | + assert_eq!(p.timeline_frames(), 9, "video still runs to 9"); | ||
| 964 | + assert_eq!( | ||
| 965 | + p.span_at(Lane::Audio, 5), | ||
| 966 | + Some(Span { | ||
| 967 | + start: 5, | ||
| 968 | + len: 4, | ||
| 969 | + from: None | ||
| 970 | + }), | ||
| 971 | + "the audio lane holds silence to the end of the picture" | ||
| 972 | + ); | ||
| 973 | + assert_eq!(p.span_at(Lane::Audio, 9), None); | ||
| 974 | + // Every lane covers the timeline exactly, gaps included. | ||
| 975 | + for l in Lane::ALL { | ||
| 976 | + let spans = p.spans_from(l, 0); | ||
| 977 | + assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{l:?}"); | ||
| 978 | + assert_eq!(spans[0].start, 0); | ||
| 979 | + } | ||
| 980 | + } | ||
| 981 | + | ||
| 982 | + #[test] | ||
| 983 | + fn the_last_clip_of_the_last_lane_cannot_be_lifted() { | ||
| 984 | + let mut p = Project::single(FILE, 9); | ||
| 985 | + assert!(p.lift(Lane::Audio, 0), "a silent timeline is fine"); | ||
| 986 | + assert!(!p.lift(Lane::Video, 0), "an empty one is not"); | ||
| 987 | + assert!(!p.lift(Lane::Audio, 0), "index past the end"); | ||
| 988 | + assert_eq!(p.timeline_frames(), 9); | ||
| 989 | + } | ||
| 990 | + | ||
| 991 | + #[test] | ||
| 992 | + fn place_overwrites_only_its_own_lane() { | ||
| 993 | + let mut p = three(); | ||
| 994 | + let audio_before = shape(&p)[1].clone(); | ||
| 995 | + // Straddles [3,5) and eats into [5,9): the first is trimmed, the second | ||
| 996 | + // is trimmed, nothing shifts. | ||
| 997 | + assert!(p.place(Lane::Video, 4, clip(0, 100, 102, 0))); | ||
| 998 | + assert_eq!( | ||
| 999 | + shape(&p)[0], | ||
| 1000 | + vec![ | ||
| 1001 | + clip(0, 0, 3, 0), | ||
| 1002 | + clip(3, 3, 4, 0), | ||
| 1003 | + clip(4, 100, 102, 0), | ||
| 1004 | + clip(6, 6, 9, 0), | ||
| 1005 | + ] | ||
| 1006 | + ); | ||
| 1007 | + assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched"); | ||
| 1008 | + assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert"); | ||
| 1009 | + | ||
| 1010 | + // Placed inside one clip, it splits it in two. | ||
| 1011 | + let mut p = Project::single(FILE, 9); | ||
| 1012 | + assert!(p.place(Lane::Video, 4, clip(0, 100, 101, 0))); | ||
| 1013 | + assert_eq!( | ||
| 1014 | + shape(&p)[0], | ||
| 1015 | + vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)] | ||
| 1016 | + ); | ||
| 1017 | + // ...and placed past the end it makes a gap, which is the whole point. | ||
| 1018 | + assert!(p.place(Lane::Video, 20, clip(0, 100, 102, 0))); | ||
| 1019 | + assert_eq!(p.timeline_frames(), 22); | ||
| 1020 | + assert_eq!( | ||
| 1021 | + p.span_at(Lane::Video, 9), | ||
| 1022 | + Some(Span { | ||
| 1023 | + start: 9, | ||
| 1024 | + len: 11, | ||
| 1025 | + from: None | ||
| 1026 | + }) | ||
| 1027 | + ); | ||
| 1028 | + assert!(!p.place(Lane::Video, 0, clip(0, 7, 7, 0)), "empty clip"); | ||
| 1029 | + } | ||
| 1030 | + | ||
| 1031 | + #[test] | ||
| 1032 | + fn ripple_delete_spans_partial_clips() { | ||
| 1033 | + let mut p = three(); | ||
| 1034 | + // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2. | ||
| 1035 | + assert!(p.ripple_delete(2, 4)); | ||
| 1036 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]); | ||
| 1037 | + assert_eq!(shape(&p)[1], shape(&p)[0]); | ||
| 1038 | + assert_eq!(p.timeline_frames(), 5); | ||
| 1039 | + assert!(!p.ripple_delete(0, 0), "an empty range is not a delete"); | ||
| 1040 | + assert!(!p.ripple_delete(0, 100), "and one that empties every lane"); | ||
| 1041 | + assert!(p.undo()); | ||
| 1042 | + assert_eq!(shape(&p), shape(&three())); | ||
| 1043 | + } | ||
| 1044 | + | ||
| 558 | #[test] | 1045 | #[test] |
| 559 | fn undo_restores_exactly() { | 1046 | fn undo_restores_exactly() { |
| 560 | let mut p = three(); | 1047 | let mut p = three(); |
| 561 | - let after_cuts = p.clips().to_vec(); | 1048 | + let after_splits = shape(&p); |
| 562 | assert!(p.delete(1)); | 1049 | assert!(p.delete(1)); |
| 563 | assert!(p.undo()); | 1050 | assert!(p.undo()); |
| 564 | - assert_eq!(p.clips(), after_cuts.as_slice()); | 1051 | + assert_eq!(shape(&p), after_splits); |
| 565 | 1052 | ||
| 566 | - // walk all the way back through both cuts, then run dry | 1053 | + // walk all the way back through both splits, then run dry |
| 567 | assert!(p.undo()); | 1054 | assert!(p.undo()); |
| 568 | assert_eq!(p.clips().len(), 2); | 1055 | assert_eq!(p.clips().len(), 2); |
| 569 | assert!(p.undo()); | 1056 | assert!(p.undo()); |
| 570 | - assert_eq!( | 1057 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); |
| 571 | - p.clips(), | ||
| 572 | - [Clip { | ||
| 573 | - source: 0, | ||
| 574 | - in_frame: 0, | ||
| 575 | - out_frame: 9 | ||
| 576 | - }] | ||
| 577 | - ); | ||
| 578 | assert!(!p.undo(), "empty history"); | 1058 | assert!(!p.undo(), "empty history"); |
| 579 | - assert_eq!( | 1059 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); |
| 580 | - p.clips(), | ||
| 581 | - [Clip { | ||
| 582 | - source: 0, | ||
| 583 | - in_frame: 0, | ||
| 584 | - out_frame: 9 | ||
| 585 | - }] | ||
| 586 | - ); | ||
| 587 | } | 1060 | } |
| 588 | 1061 | ||
| 1062 | + /// Undo/redo by hand across a split must never merge two takes into one | ||
| 1063 | + /// group by reusing an id. | ||
| 589 | #[test] | 1064 | #[test] |
| 590 | - fn segments_from_trims_the_first_entry() { | 1065 | + fn group_ids_are_never_reused() { |
| 1066 | + let mut p = Project::single(FILE, 9); | ||
| 1067 | + assert!(p.split(3)); | ||
| 1068 | + let first = p.clips()[1].link; | ||
| 1069 | + assert!(p.undo()); | ||
| 1070 | + assert!(p.split(5)); | ||
| 1071 | + assert_ne!(p.clips()[1].link, first, "a retired id must not come back"); | ||
| 1072 | + } | ||
| 1073 | + | ||
| 1074 | + #[test] | ||
| 1075 | + fn segments_from_reads_the_audio_lane() { | ||
| 591 | let p = three(); | 1076 | let p = three(); |
| 592 | // mid-clip: partial first segment, whole clips after it | 1077 | // mid-clip: partial first segment, whole clips after it |
| 593 | assert_eq!( | 1078 | assert_eq!( |
| 594 | p.segments_from(4, FPS), | 1079 | p.segments_from(4, FPS), |
| 595 | - vec![(0, 4.0 / 30.0, 5.0 / 30.0), (0, 5.0 / 30.0, 9.0 / 30.0)] | 1080 | + vec![ |
| 1081 | + (Some(0), 4.0 / 30.0, 5.0 / 30.0), | ||
| 1082 | + (Some(0), 5.0 / 30.0, 9.0 / 30.0) | ||
| 1083 | + ] | ||
| 596 | ); | 1084 | ); |
| 597 | // on a boundary: nothing partial | 1085 | // on a boundary: nothing partial |
| 598 | assert_eq!( | 1086 | assert_eq!( |
| 599 | p.segments_from(3, FPS), | 1087 | p.segments_from(3, FPS), |
| 600 | - vec![(0, 3.0 / 30.0, 5.0 / 30.0), (0, 5.0 / 30.0, 9.0 / 30.0)] | 1088 | + vec![ |
| 1089 | + (Some(0), 3.0 / 30.0, 5.0 / 30.0), | ||
| 1090 | + (Some(0), 5.0 / 30.0, 9.0 / 30.0) | ||
| 1091 | + ] | ||
| 601 | ); | 1092 | ); |
| 602 | // from the top: one entry per clip | 1093 | // from the top: one entry per clip |
| 603 | assert_eq!(p.segments_from(0, FPS).len(), 3); | 1094 | assert_eq!(p.segments_from(0, FPS).len(), 3); |
| 604 | // last clip only | 1095 | // last clip only |
| 605 | - assert_eq!(p.segments_from(8, FPS), vec![(0, 8.0 / 30.0, 0.3)]); | 1096 | + assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]); |
| 606 | // past the end / unusable fps | 1097 | // past the end / unusable fps |
| 607 | assert!(p.segments_from(9, FPS).is_empty()); | 1098 | assert!(p.segments_from(9, FPS).is_empty()); |
| 608 | assert!(p.segments_from(0, 0.0).is_empty()); | 1099 | assert!(p.segments_from(0, 0.0).is_empty()); |
| 609 | assert!(p.segments_from(0, f64::NAN).is_empty()); | 1100 | assert!(p.segments_from(0, f64::NAN).is_empty()); |
| 610 | } | 1101 | } |
| 611 | 1102 | ||
| 1103 | + #[test] | ||
| 1104 | + fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() { | ||
| 1105 | + let mut p = three(); | ||
| 1106 | + assert!(p.lift(Lane::Audio, 1)); // silence over timeline [3, 5) | ||
| 1107 | + assert_eq!( | ||
| 1108 | + p.segments_from(0, FPS), | ||
| 1109 | + vec![ | ||
| 1110 | + (Some(0), 0.0, 3.0 / 30.0), | ||
| 1111 | + (None, 0.0, 2.0 / 30.0), | ||
| 1112 | + (Some(0), 5.0 / 30.0, 9.0 / 30.0), | ||
| 1113 | + ] | ||
| 1114 | + ); | ||
| 1115 | + // The list still covers exactly the timeline: that is what stops the | ||
| 1116 | + // master clock stalling at the hole. | ||
| 1117 | + let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); | ||
| 1118 | + assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}"); | ||
| 1119 | + // Starting inside the gap trims the silence, not the clip after it. | ||
| 1120 | + assert_eq!( | ||
| 1121 | + p.segments_from(4, FPS), | ||
| 1122 | + vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)] | ||
| 1123 | + ); | ||
| 1124 | + // ...and a lane that is nothing but gap is a run of silence. | ||
| 1125 | + assert!(p.lift(Lane::Audio, 0)); | ||
| 1126 | + assert!(p.lift(Lane::Audio, 0)); | ||
| 1127 | + assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]); | ||
| 1128 | + } | ||
| 1129 | + | ||
| 612 | /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9) | 1130 | /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9) |
| 613 | /// of source 0 then [0,4) of source 1. | 1131 | /// of source 0 then [0,4) of source 1. |
| 614 | fn two_sources() -> Project { | 1132 | fn two_sources() -> Project { |
| @@ -643,17 +1161,11 @@ mod tests { | |||
| 643 | fn append_clip_is_one_undo_step() { | 1161 | fn append_clip_is_one_undo_step() { |
| 644 | let mut p = two_sources(); | 1162 | let mut p = two_sources(); |
| 645 | assert_eq!(p.timeline_frames(), 13); | 1163 | assert_eq!(p.timeline_frames(), 13); |
| 646 | - assert_eq!( | 1164 | + assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1)); |
| 647 | - p.clips()[3], | 1165 | + assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane"); |
| 648 | - Clip { | ||
| 649 | - in_frame: 0, | ||
| 650 | - out_frame: 4, | ||
| 651 | - source: 1 | ||
| 652 | - } | ||
| 653 | - ); | ||
| 654 | assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9"); | 1166 | assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9"); |
| 655 | assert!(p.undo()); | 1167 | assert!(p.undo()); |
| 656 | - assert_eq!(p.clips(), three().clips(), "one step back to one source"); | 1168 | + assert_eq!(shape(&p), shape(&three()), "one step back to one source"); |
| 657 | assert_eq!( | 1169 | assert_eq!( |
| 658 | p.sources().len(), | 1170 | p.sources().len(), |
| 659 | 2, | 1171 | 2, |
| @@ -667,30 +1179,17 @@ mod tests { | |||
| 667 | #[test] | 1179 | #[test] |
| 668 | fn edits_carry_the_source_along() { | 1180 | fn edits_carry_the_source_along() { |
| 669 | let mut p = two_sources(); | 1181 | let mut p = two_sources(); |
| 670 | - // A cut inside the second source splits into two source-1 clips. | 1182 | + // A split inside the second source splits into two source-1 clips. |
| 671 | - assert!(p.cut(11)); | 1183 | + assert!(p.split(11)); |
| 672 | - assert_eq!( | 1184 | + assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1)); |
| 673 | - p.clips()[3], | 1185 | + assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1)); |
| 674 | - Clip { | ||
| 675 | - in_frame: 0, | ||
| 676 | - out_frame: 2, | ||
| 677 | - source: 1 | ||
| 678 | - } | ||
| 679 | - ); | ||
| 680 | - assert_eq!( | ||
| 681 | - p.clips()[4], | ||
| 682 | - Clip { | ||
| 683 | - in_frame: 2, | ||
| 684 | - out_frame: 4, | ||
| 685 | - source: 1 | ||
| 686 | - } | ||
| 687 | - ); | ||
| 688 | 1186 | ||
| 689 | // A source-1 clip pasted into source-0 territory keeps its file, and so | 1187 | // A source-1 clip pasted into source-0 territory keeps its file, and so |
| 690 | // does the source-0 half that got split off around it. | 1188 | // does the source-0 half that got split off around it. |
| 691 | let copied = p.clips()[4]; | 1189 | let copied = p.clips()[4]; |
| 692 | assert!(p.paste(1, copied)); | 1190 | assert!(p.paste(1, copied)); |
| 693 | - assert_eq!(p.clips()[1], copied); | 1191 | + assert_eq!(p.clips()[1].source, 1); |
| 1192 | + assert_eq!(p.clips()[1].in_frame, 2); | ||
| 694 | assert_eq!(p.clips()[2].source, 0); | 1193 | assert_eq!(p.clips()[2].source, 0); |
| 695 | assert!(p.undo()); | 1194 | assert!(p.undo()); |
| 696 | assert_eq!(p.clips()[1].source, 0, "undo restores sources too"); | 1195 | assert_eq!(p.clips()[1].source, 0, "undo restores sources too"); |
| @@ -703,13 +1202,16 @@ mod tests { | |||
| 703 | assert_eq!( | 1202 | assert_eq!( |
| 704 | p.segments_from(4, FPS), | 1203 | p.segments_from(4, FPS), |
| 705 | vec![ | 1204 | vec![ |
| 706 | - (0, 4.0 / 30.0, 5.0 / 30.0), | 1205 | + (Some(0), 4.0 / 30.0, 5.0 / 30.0), |
| 707 | - (0, 5.0 / 30.0, 9.0 / 30.0), | 1206 | + (Some(0), 5.0 / 30.0, 9.0 / 30.0), |
| 708 | - (1, 0.0, 4.0 / 30.0), | 1207 | + (Some(1), 0.0, 4.0 / 30.0), |
| 709 | ] | 1208 | ] |
| 710 | ); | 1209 | ); |
| 711 | // Mid-clip in source 1: only that source is left. | 1210 | // Mid-clip in source 1: only that source is left. |
| 712 | - assert_eq!(p.segments_from(10, FPS), vec![(1, 1.0 / 30.0, 4.0 / 30.0)]); | 1211 | + assert_eq!( |
| 1212 | + p.segments_from(10, FPS), | ||
| 1213 | + vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)] | ||
| 1214 | + ); | ||
| 713 | assert!(p.segments_from(13, FPS).is_empty()); | 1215 | assert!(p.segments_from(13, FPS).is_empty()); |
| 714 | // Segments still cover exactly the timeline across the join. | 1216 | // Segments still cover exactly the timeline across the join. |
| 715 | let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); | 1217 | let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); |
| @@ -722,7 +1224,10 @@ mod tests { | |||
| 722 | assert!(p.delete(0)); | 1224 | assert!(p.delete(0)); |
| 723 | // source seconds, not timeline: deleting the head does not shift them | 1225 | // source seconds, not timeline: deleting the head does not shift them |
| 724 | let segs = p.segments_from(0, 25.0); | 1226 | let segs = p.segments_from(0, 25.0); |
| 725 | - assert_eq!(segs, vec![(0, 3.0 / 25.0, 0.2), (0, 0.2, 9.0 / 25.0)]); | 1227 | + assert_eq!( |
| 1228 | + segs, | ||
| 1229 | + vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)] | ||
| 1230 | + ); | ||
| 726 | let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum(); | 1231 | let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum(); |
| 727 | assert!( | 1232 | assert!( |
| 728 | (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, | 1233 | (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, |
| @@ -735,9 +1240,10 @@ mod tests { | |||
| 735 | // Import a second file, undo it: source 1 is now an orphan. | 1240 | // Import a second file, undo it: source 1 is now an orphan. |
| 736 | let mut p = two_sources(); | 1241 | let mut p = two_sources(); |
| 737 | assert!(p.undo()); | 1242 | assert!(p.undo()); |
| 738 | - let (sources, clips) = p.without_orphan_sources(); | 1243 | + let (sources, video, audio) = p.without_orphan_sources(); |
| 739 | assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone"); | 1244 | assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone"); |
| 740 | - assert_eq!(clips, three().clips(), "the clips are untouched"); | 1245 | + assert_eq!(video, three().clips(), "the clips are untouched"); |
| 1246 | + assert_eq!(audio, three().lane(Lane::Audio)); | ||
| 741 | 1247 | ||
| 742 | // Three sources where only the middle one is orphaned: the survivors | 1248 | // Three sources where only the middle one is orphaned: the survivors |
| 743 | // renumber, and the clips follow. | 1249 | // renumber, and the clips follow. |
| @@ -745,51 +1251,47 @@ mod tests { | |||
| 745 | assert_eq!(p.import(FILE2), 1); | 1251 | assert_eq!(p.import(FILE2), 1); |
| 746 | assert_eq!(p.import("/nonexistent/c.mp4"), 2); | 1252 | assert_eq!(p.import("/nonexistent/c.mp4"), 2); |
| 747 | assert!(p.append_clip(2, 4)); | 1253 | assert!(p.append_clip(2, 4)); |
| 748 | - let (sources, clips) = p.without_orphan_sources(); | 1254 | + let (sources, video, audio) = p.without_orphan_sources(); |
| 749 | assert_eq!( | 1255 | assert_eq!( |
| 750 | sources, | 1256 | sources, |
| 751 | vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")] | 1257 | vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")] |
| 752 | ); | 1258 | ); |
| 753 | - assert_eq!(clips.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]); | 1259 | + assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]); |
| 754 | // ...and what comes out is loadable, with the same timeline. | 1260 | // ...and what comes out is loadable, with the same timeline. |
| 755 | - let reloaded = Project::from_parts(sources, clips).expect("from_parts"); | 1261 | + let reloaded = Project::from_parts(sources, video, audio).expect("from_parts"); |
| 756 | assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); | 1262 | assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); |
| 757 | assert_eq!(reloaded.sources().len(), 2); | 1263 | assert_eq!(reloaded.sources().len(), 2); |
| 758 | } | 1264 | } |
| 759 | 1265 | ||
| 760 | #[test] | 1266 | #[test] |
| 761 | fn from_parts_has_no_history_and_checks_the_invariants() { | 1267 | fn from_parts_has_no_history_and_checks_the_invariants() { |
| 762 | - let (sources, clips) = three().without_orphan_sources(); | 1268 | + let (sources, video, audio) = three().without_orphan_sources(); |
| 763 | - let mut p = Project::from_parts(sources.clone(), clips.clone()).expect("valid parts"); | 1269 | + let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone()) |
| 1270 | + .expect("valid parts"); | ||
| 764 | assert_eq!(p.clips(), three().clips()); | 1271 | assert_eq!(p.clips(), three().clips()); |
| 765 | assert!(!p.undo(), "a loaded project has nothing to undo"); | 1272 | assert!(!p.undo(), "a loaded project has nothing to undo"); |
| 766 | - assert!(p.cut(4), "...and is editable from there"); | 1273 | + assert!(p.split(4), "...and is editable from there"); |
| 767 | assert!(p.undo()); | 1274 | assert!(p.undo()); |
| 768 | 1275 | ||
| 769 | - assert!(Project::from_parts(sources.clone(), Vec::new()).is_none()); | 1276 | + // A lane may be empty; both may not. |
| 770 | - assert!( | 1277 | + assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_some()); |
| 771 | - Project::from_parts( | 1278 | + assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_none()); |
| 772 | - sources.clone(), | 1279 | + let bad: [Vec<Clip>; 4] = [ |
| 773 | - vec![Clip { | 1280 | + vec![clip(0, 0, 3, 1)], // source that is not there |
| 774 | - source: 1, | 1281 | + vec![clip(0, 3, 3, 0)], // empty clip |
| 775 | - in_frame: 0, | 1282 | + vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order |
| 776 | - out_frame: 3 | 1283 | + vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping |
| 777 | - }] | 1284 | + ]; |
| 778 | - ) | 1285 | + for clips in bad { |
| 779 | - .is_none(), | 1286 | + assert!( |
| 780 | - "clip names a source that is not there" | 1287 | + Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_none(), |
| 781 | - ); | 1288 | + "{clips:?}" |
| 782 | - assert!( | 1289 | + ); |
| 783 | - Project::from_parts( | 1290 | + assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_none()); |
| 784 | - sources, | 1291 | + } |
| 785 | - vec![Clip { | 1292 | + // Group ids survive a load, and the next split gets a fresh one. |
| 786 | - source: 0, | 1293 | + let mut p = Project::from_parts(sources, video, audio).expect("valid parts"); |
| 787 | - in_frame: 3, | 1294 | + assert!(p.split(4)); |
| 788 | - out_frame: 3 | 1295 | + assert!(p.clips().iter().all(|c| c.link.is_some())); |
| 789 | - }] | ||
| 790 | - ) | ||
| 791 | - .is_none(), | ||
| 792 | - "empty clip" | ||
| 793 | - ); | ||
| 794 | } | 1296 | } |
| 795 | } | 1297 | } |
crates/engine/tests/audio_multi.rsmodified+12 -5
| @@ -30,6 +30,12 @@ fn sources() -> Vec<PathBuf> { | |||
| 30 | 30 | ||
| 31 | /// Drains a session flat, asserting chunks are contiguous, and reports the | 31 | /// Drains a session flat, asserting chunks are contiguous, and reports the |
| 32 | /// first chunk's `start_sample` plus how many chunks arrived. | 32 | /// first chunk's `start_sample` plus how many chunks arrived. |
| 33 | +/// Every segment names a source: these tests are about joins between files, | ||
| 34 | +/// not about gaps (which name none). | ||
| 35 | +fn named(segs: &[(usize, f64, f64)]) -> Vec<(Option<usize>, f64, f64)> { | ||
| 36 | + segs.iter().map(|&(s, a, b)| (Some(s), a, b)).collect() | ||
| 37 | +} | ||
| 38 | + | ||
| 33 | fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) { | 39 | fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) { |
| 34 | let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize); | 40 | let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize); |
| 35 | for AudioChunk { | 41 | for AudioChunk { |
| @@ -48,7 +54,8 @@ fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) { | |||
| 48 | } | 54 | } |
| 49 | 55 | ||
| 50 | fn multi(segs: &[(usize, f64, f64)]) -> (Vec<f32>, u64, usize) { | 56 | fn multi(segs: &[(usize, f64, f64)]) -> (Vec<f32>, u64, usize) { |
| 51 | - let (_, rx) = AudioSession::open_multi_segments(&sources(), segs) | 57 | + let segs = named(segs); |
| 58 | + let (_, rx) = AudioSession::open_multi_segments(&sources(), &segs) | ||
| 52 | .expect("open") | 59 | .expect("open") |
| 53 | .expect("the first source has an audio track"); | 60 | .expect("the first source has an audio track"); |
| 54 | drain(rx) | 61 | drain(rx) |
| @@ -128,7 +135,7 @@ fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) { | |||
| 128 | } | 135 | } |
| 129 | 136 | ||
| 130 | fn copy(segs: &[(usize, f64, f64)]) -> Vec<AacPacket> { | 137 | fn copy(segs: &[(usize, f64, f64)]) -> Vec<AacPacket> { |
| 131 | - AudioSession::copy_multi_segments(&sources(), segs) | 138 | + AudioSession::copy_multi_segments(&sources(), &named(segs)) |
| 132 | .expect("copy") | 139 | .expect("copy") |
| 133 | .expect("the first source has an audio track") | 140 | .expect("the first source has an audio track") |
| 134 | .1 | 141 | .1 |
| @@ -246,7 +253,7 @@ fn a_source_without_the_timeline_audio_is_refused() { | |||
| 246 | // the copy and the decode paths refuse them again rather than mislabel one | 253 | // the copy and the decode paths refuse them again rather than mislabel one |
| 247 | // esds for two different tracks. | 254 | // esds for two different tracks. |
| 248 | let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; | 255 | let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; |
| 249 | - let segs = [(0, 0.0, 1.0), (1, 0.0, 1.0)]; | 256 | + let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; |
| 250 | // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) | 257 | // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) |
| 251 | for e in [ | 258 | for e in [ |
| 252 | AudioSession::copy_multi_segments(&mixed, &segs).err(), | 259 | AudioSession::copy_multi_segments(&mixed, &segs).err(), |
| @@ -258,6 +265,6 @@ fn a_source_without_the_timeline_audio_is_refused() { | |||
| 258 | assert!(msg.contains("source 1"), "{msg}"); | 265 | assert!(msg.contains("source 1"), "{msg}"); |
| 259 | } | 266 | } |
| 260 | // An out-of-range index is an error, not a panic. | 267 | // An out-of-range index is an error, not a panic. |
| 261 | - assert!(AudioSession::copy_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); | 268 | + assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); |
| 262 | - assert!(AudioSession::open_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); | 269 | + assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); |
| 263 | } | 270 | } |
crates/engine/tests/audio_segments.rsmodified+111 -0
| @@ -134,3 +134,114 @@ fn no_segments_ends_clean() { | |||
| 134 | "an empty edit list decodes nothing" | 134 | "an empty edit list decodes nothing" |
| 135 | ); | 135 | ); |
| 136 | } | 136 | } |
| 137 | + | ||
| 138 | +/// A segment naming no source is a gap, and a gap is *synthesised silence* in | ||
| 139 | +/// the same stream -- real chunks, contiguous with the audible ones (`drain` | ||
| 140 | +/// asserts that), so the master clock keeps counting through the hole instead | ||
| 141 | +/// of stalling on it. | ||
| 142 | +#[test] | ||
| 143 | +fn a_gap_segment_is_silence_of_its_own_length() { | ||
| 144 | + let sources = [asset()]; | ||
| 145 | + let segs = [ | ||
| 146 | + (Some(0), 0.0, 0.5), | ||
| 147 | + (None, 0.0, 1.0), // one second of hole | ||
| 148 | + (Some(0), 2.0, 2.5), | ||
| 149 | + ]; | ||
| 150 | + let (_, rx) = AudioSession::open_multi_segments(&sources, &segs) | ||
| 151 | + .expect("open") | ||
| 152 | + .expect("test_av.mp4 has an audio track"); | ||
| 153 | + let (samples, first, _) = drain(rx); | ||
| 154 | + assert_eq!(first, 0, "the run still starts at audible zero"); | ||
| 155 | + | ||
| 156 | + let frames = samples.len() as u64 / CHANNELS as u64; | ||
| 157 | + let want = 2 * RATE / 2 + RATE; | ||
| 158 | + assert!( | ||
| 159 | + frames.abs_diff(want) <= PACKET, | ||
| 160 | + "{frames} frames for {want} asked for: a gap must cost exactly its length" | ||
| 161 | + ); | ||
| 162 | + // The hole itself is digital silence, and what surrounds it is not. | ||
| 163 | + let hole = (RATE / 2) as usize * CHANNELS..(RATE / 2 + RATE) as usize * CHANNELS; | ||
| 164 | + assert!( | ||
| 165 | + samples[hole.clone()].iter().all(|s| *s == 0.0), | ||
| 166 | + "the gap must be silent" | ||
| 167 | + ); | ||
| 168 | + assert!( | ||
| 169 | + samples[..hole.start].iter().any(|s| s.abs() > 1e-3) | ||
| 170 | + && samples[hole.end..].iter().any(|s| s.abs() > 1e-3), | ||
| 171 | + "the clips around it must not be" | ||
| 172 | + ); | ||
| 173 | + | ||
| 174 | + // Nothing but gap is a valid run of silence; the meta still comes from the | ||
| 175 | + // source, because that is what the device was opened with. | ||
| 176 | + let (meta, rx) = AudioSession::open_multi_segments(&sources, &[(None, 0.0, 0.25)]) | ||
| 177 | + .expect("open") | ||
| 178 | + .expect("meta comes from source 0 even with nothing to decode"); | ||
| 179 | + assert_eq!(meta.sample_rate as u64, RATE); | ||
| 180 | + let (samples, _, _) = drain(rx); | ||
| 181 | + assert!(samples.iter().all(|s| *s == 0.0)); | ||
| 182 | + assert!( | ||
| 183 | + (samples.len() as u64 / CHANNELS as u64).abs_diff(RATE / 4) <= PACKET, | ||
| 184 | + "quarter second of silence" | ||
| 185 | + ); | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +/// The copy side of a gap: there is no AAC encoder here to make silence with, | ||
| 189 | +/// so the hole is spent as *duration* on the packet in front of it. Every | ||
| 190 | +/// packet after the gap therefore still lands at its timeline position. | ||
| 191 | +#[test] | ||
| 192 | +fn a_copied_gap_becomes_the_duration_of_the_packet_before_it() { | ||
| 193 | + let sources = [asset()]; | ||
| 194 | + let plain = [(Some(0), 0.0, 1.0), (Some(0), 2.0, 3.0)]; | ||
| 195 | + let gapped = [(Some(0), 0.0, 1.0), (None, 0.0, 1.0), (Some(0), 2.0, 3.0)]; | ||
| 196 | + | ||
| 197 | + let (_, without) = AudioSession::copy_multi_segments(&sources, &plain) | ||
| 198 | + .unwrap() | ||
| 199 | + .unwrap(); | ||
| 200 | + let (_, with) = AudioSession::copy_multi_segments(&sources, &gapped) | ||
| 201 | + .unwrap() | ||
| 202 | + .unwrap(); | ||
| 203 | + assert_eq!( | ||
| 204 | + with.len(), | ||
| 205 | + without.len(), | ||
| 206 | + "a gap copies no packets: there is nothing in it" | ||
| 207 | + ); | ||
| 208 | + let total = |p: &[engine::AacPacket]| p.iter().map(|p| u64::from(p.samples)).sum::<u64>(); | ||
| 209 | + assert_eq!( | ||
| 210 | + total(&with) - total(&without), | ||
| 211 | + RATE, | ||
| 212 | + "...it costs exactly its own second of stts duration" | ||
| 213 | + ); | ||
| 214 | + // Exactly one packet grew, and it is an interior one -- the last before | ||
| 215 | + // the hole -- so every packet after the hole is pushed to where the | ||
| 216 | + // timeline wants it rather than the whole tail drifting early. | ||
| 217 | + let grown: Vec<usize> = with | ||
| 218 | + .iter() | ||
| 219 | + .zip(&without) | ||
| 220 | + .enumerate() | ||
| 221 | + .filter(|(_, (a, b))| a.samples != b.samples) | ||
| 222 | + .map(|(i, _)| i) | ||
| 223 | + .collect(); | ||
| 224 | + assert_eq!(grown.len(), 1, "one packet carries the whole gap"); | ||
| 225 | + assert!( | ||
| 226 | + grown[0] > 0 && grown[0] < with.len() - 1, | ||
| 227 | + "the gap rides on an interior packet, at {} of {}", | ||
| 228 | + grown[0], | ||
| 229 | + with.len() | ||
| 230 | + ); | ||
| 231 | + assert!( | ||
| 232 | + with.iter().zip(&without).all(|(a, b)| a.bytes == b.bytes), | ||
| 233 | + "and not one byte of audio moved" | ||
| 234 | + ); | ||
| 235 | + | ||
| 236 | + // A gap at the *head* has no packet before it: the first one picks it up | ||
| 237 | + // (the documented ponytail), so nothing but that packet is misplaced. | ||
| 238 | + let (_, leading) = | ||
| 239 | + AudioSession::copy_multi_segments(&sources, &[(None, 0.0, 0.5), (Some(0), 0.0, 1.0)]) | ||
| 240 | + .unwrap() | ||
| 241 | + .unwrap(); | ||
| 242 | + assert_eq!( | ||
| 243 | + u64::from(leading[0].samples), | ||
| 244 | + 1024 + RATE / 2, | ||
| 245 | + "the head gap rides on the first packet" | ||
| 246 | + ); | ||
| 247 | +} | ||
crates/engine/tests/export.rsmodified+75 -3
| @@ -22,6 +22,7 @@ use std::time::{Duration, Instant}; | |||
| 22 | use engine::export::ExportSettings; | 22 | use engine::export::ExportSettings; |
| 23 | use engine::hw::HwEncoder; | 23 | use engine::hw::HwEncoder; |
| 24 | use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; | 24 | use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; |
| 25 | +use engine::project::Lane; | ||
| 25 | use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; | 26 | use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; |
| 26 | 27 | ||
| 27 | const FPS: f64 = 30.0; | 28 | const FPS: f64 = 30.0; |
| @@ -183,7 +184,7 @@ fn two_sources() -> Project { | |||
| 183 | let second = project.import(asset("test_av2.mp4")); | 184 | let second = project.import(asset("test_av2.mp4")); |
| 184 | assert_eq!(second, 1, "a second file is a second source"); | 185 | assert_eq!(second, 1, "a second file is a second source"); |
| 185 | assert!(project.append_clip(second, av2.frame_count)); | 186 | assert!(project.append_clip(second, av2.frame_count)); |
| 186 | - assert!(project.cut(120), "cut a second before the end of test_av"); | 187 | + assert!(project.split(120), "cut a second before the end of test_av"); |
| 187 | assert!(project.delete(1), "drop test_av's tail"); | 188 | assert!(project.delete(1), "drop test_av's tail"); |
| 188 | assert_eq!(project.timeline_frames(), 120 + av2.frame_count); | 189 | assert_eq!(project.timeline_frames(), 120 + av2.frame_count); |
| 189 | assert_eq!( | 190 | assert_eq!( |
| @@ -318,11 +319,11 @@ fn a_vanished_source_fails_the_export() { | |||
| 318 | 319 | ||
| 319 | // Five frames of each: the export has to get going and then fail. | 320 | // Five frames of each: the export has to get going and then fail. |
| 320 | let mut project = Project::single(&baseline, meta.frame_count); | 321 | let mut project = Project::single(&baseline, meta.frame_count); |
| 321 | - assert!(project.cut(5)); | 322 | + assert!(project.split(5)); |
| 322 | assert!(project.delete(1)); | 323 | assert!(project.delete(1)); |
| 323 | let second = project.import(&doomed); | 324 | let second = project.import(&doomed); |
| 324 | assert!(project.append_clip(second, meta.frame_count)); | 325 | assert!(project.append_clip(second, meta.frame_count)); |
| 325 | - assert!(project.cut(10)); | 326 | + assert!(project.split(10)); |
| 326 | assert!(project.delete(2)); | 327 | assert!(project.delete(2)); |
| 327 | assert_eq!(project.timeline_frames(), 10); | 328 | assert_eq!(project.timeline_frames(), 10); |
| 328 | 329 | ||
| @@ -548,3 +549,74 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec< | |||
| 548 | vec![192u8.wrapping_sub(index as u8); cw * ch], | 549 | vec![192u8.wrapping_sub(index as u8); cw * ch], |
| 549 | ) | 550 | ) |
| 550 | } | 551 | } |
| 552 | + | ||
| 553 | +/// A timeline with a hole in each lane, exported. The video gap is encoded as | ||
| 554 | +/// black rather than skipped -- the file is as long as the timeline, frame for | ||
| 555 | +/// frame -- and the audio gap is spent as sample-table duration, so the audio | ||
| 556 | +/// track still covers the whole timeline inside the bresenham bound instead of | ||
| 557 | +/// ending a second early. | ||
| 558 | +#[test] | ||
| 559 | +fn exports_a_gapped_timeline_as_black_and_silence() { | ||
| 560 | + pin_software(); | ||
| 561 | + let source = asset("test_av.mp4"); | ||
| 562 | + let mut session = PlaybackSession::open(&source).expect("open source"); | ||
| 563 | + assert!(session.cut_at(1.0), "split at 1 s"); | ||
| 564 | + assert!(session.cut_at(2.0), "split at 2 s"); | ||
| 565 | + // Lift the middle out of *both* lanes: one second of black and silence in | ||
| 566 | + // the middle of a five-second timeline, with the length unchanged. | ||
| 567 | + assert!(session.lift_clip(Lane::Video, 1)); | ||
| 568 | + assert!(session.lift_clip(Lane::Audio, 1)); | ||
| 569 | + session.pause(); | ||
| 570 | + let timeline = session.timeline_duration(); | ||
| 571 | + let frames = (timeline * FPS).round() as u32; | ||
| 572 | + let out = out_path("gapped"); | ||
| 573 | + | ||
| 574 | + let handle = session.export_to(&out); | ||
| 575 | + wait(&handle, Duration::from_secs(180)).expect("export"); | ||
| 576 | + | ||
| 577 | + // Every frame is there, and the ones over the hole are black. | ||
| 578 | + let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); | ||
| 579 | + assert_eq!( | ||
| 580 | + video.frame_count, frames, | ||
| 581 | + "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline", | ||
| 582 | + video.frame_count | ||
| 583 | + ); | ||
| 584 | + let pictures = decode_all(&out); | ||
| 585 | + assert_eq!(pictures.len() as u32, frames); | ||
| 586 | + let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize); | ||
| 587 | + // Encoded black, so not bit-exact: a mean absolute distance from true black | ||
| 588 | + // well under one code value per channel is what "black" can mean here. | ||
| 589 | + let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4); | ||
| 590 | + for (i, picture) in pictures.iter().enumerate() { | ||
| 591 | + let diff = mean_abs_diff(picture, &black); | ||
| 592 | + if (hole..hole_end).contains(&i) { | ||
| 593 | + assert!( | ||
| 594 | + diff < 4.0, | ||
| 595 | + "frame {i} of the gap is not black (MAE {diff:.2})" | ||
| 596 | + ); | ||
| 597 | + } | ||
| 598 | + } | ||
| 599 | + let lit = mean_abs_diff(&pictures[0], &black); | ||
| 600 | + assert!(lit > 4.0, "the clips around the gap came out black too"); | ||
| 601 | + | ||
| 602 | + // The audio track still spans the whole timeline: the gap paid its way in | ||
| 603 | + // stts duration, so nothing after it moved earlier. | ||
| 604 | + let file = File::open(&out).unwrap(); | ||
| 605 | + let size = file.metadata().unwrap().len(); | ||
| 606 | + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); | ||
| 607 | + let track = &reader.tracks()[&2]; | ||
| 608 | + let duration = track.duration().as_secs_f64(); | ||
| 609 | + println!("gapped export: audio track {duration:.3}s for a {timeline:.3}s timeline"); | ||
| 610 | + assert!( | ||
| 611 | + (duration - timeline).abs() < 3.0 * 1024.0 / 44_100.0, | ||
| 612 | + "audio track is {duration:.3}s, timeline {timeline:.3}s" | ||
| 613 | + ); | ||
| 614 | + // ...and the packets themselves cover only the audible four seconds, within | ||
| 615 | + // the same half-packet-per-join bound the copier promises. | ||
| 616 | + let packets = f64::from(reader.sample_count(2).expect("audio track") * 1024); | ||
| 617 | + let audible = (timeline - 1.0) * 44_100.0; | ||
| 618 | + assert!( | ||
| 619 | + (packets - audible).abs() < 3.0 * 1024.0, | ||
| 620 | + "{packets} samples copied for {audible} audible ones" | ||
| 621 | + ); | ||
| 622 | +} | ||
crates/engine/tests/playback.rsmodified+97 -0
| @@ -11,6 +11,7 @@ use std::path::{Path, PathBuf}; | |||
| 11 | use std::thread::sleep; | 11 | use std::thread::sleep; |
| 12 | use std::time::{Duration, Instant}; | 12 | use std::time::{Duration, Instant}; |
| 13 | 13 | ||
| 14 | +use engine::project::Lane; | ||
| 14 | use engine::{DecodeSession, Frame, PlaybackSession}; | 15 | use engine::{DecodeSession, Frame, PlaybackSession}; |
| 15 | 16 | ||
| 16 | fn asset(name: &str) -> PathBuf { | 17 | fn asset(name: &str) -> PathBuf { |
| @@ -903,3 +904,99 @@ fn audio_runs_across_a_source_join() { | |||
| 903 | // real time, so the decoder may well have reached 9 s while the clock is at | 904 | // real time, so the decoder may well have reached 9 s while the clock is at |
| 904 | // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none). | 905 | // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none). |
| 905 | } | 906 | } |
| 907 | + | ||
| 908 | +/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap* | ||
| 909 | +/// rather than closing up, and a gap plays: the timeline keeps its length, the | ||
| 910 | +/// frame numbering stays contiguous straight through, and every picture over | ||
| 911 | +/// the hole is black. No audio needed, so this runs anywhere. | ||
| 912 | +#[test] | ||
| 913 | +fn a_video_gap_plays_black_without_shortening_the_timeline() { | ||
| 914 | + let path = asset("test_baseline.mp4"); | ||
| 915 | + let mut session = PlaybackSession::open(&path).expect("open"); | ||
| 916 | + let (fps, total) = (session.meta().frame_rate, session.meta().frame_count); | ||
| 917 | + let whole = session.timeline_duration(); | ||
| 918 | + | ||
| 919 | + assert!(session.cut_at(2.0), "split at 2 s"); | ||
| 920 | + assert!(session.cut_at(3.5), "split at 3.5 s"); | ||
| 921 | + assert!( | ||
| 922 | + session.lift_clip(Lane::Video, 1), | ||
| 923 | + "lift the middle picture out" | ||
| 924 | + ); | ||
| 925 | + assert_eq!( | ||
| 926 | + session.clip_spans().len(), | ||
| 927 | + 2, | ||
| 928 | + "two placements, and a hole between them" | ||
| 929 | + ); | ||
| 930 | + assert!( | ||
| 931 | + (session.timeline_duration() - whole).abs() < 1e-9, | ||
| 932 | + "a lift leaves a gap: the timeline is exactly as long as it was" | ||
| 933 | + ); | ||
| 934 | + | ||
| 935 | + let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32); | ||
| 936 | + session.seek(0.0); | ||
| 937 | + session.play(); | ||
| 938 | + let deadline = Instant::now() + Duration::from_secs(20); | ||
| 939 | + let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32); | ||
| 940 | + loop { | ||
| 941 | + session.tick(); | ||
| 942 | + while let Some(frame) = session.try_frame() { | ||
| 943 | + assert_eq!(frame.index, expect, "timeline indices must be contiguous"); | ||
| 944 | + let is_black = frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]); | ||
| 945 | + if (hole..hole_end).contains(&frame.index) { | ||
| 946 | + assert!(is_black, "frame {} is inside the gap", frame.index); | ||
| 947 | + black += 1; | ||
| 948 | + } else { | ||
| 949 | + lit += 1; | ||
| 950 | + } | ||
| 951 | + expect += 1; | ||
| 952 | + } | ||
| 953 | + if session.is_eos() { | ||
| 954 | + break; | ||
| 955 | + } | ||
| 956 | + assert!(Instant::now() < deadline, "still draining after 20 s"); | ||
| 957 | + sleep(Duration::from_millis(4)); | ||
| 958 | + } | ||
| 959 | + assert_eq!(expect, total, "the whole timeline, gap included"); | ||
| 960 | + assert_eq!(black, hole_end - hole, "every frame of the hole was black"); | ||
| 961 | + assert!(lit > 0, "and the clips around it still decoded"); | ||
| 962 | + | ||
| 963 | + // The gap is one undo step back to the clip that was there. | ||
| 964 | + assert!(session.undo()); | ||
| 965 | + assert_eq!(session.clip_spans().len(), 3); | ||
| 966 | +} | ||
| 967 | + | ||
| 968 | +/// A hole in the *audio* lane, with the device running: the master clock counts | ||
| 969 | +/// samples the device has been fed, so silence has to be fed as real chunks or | ||
| 970 | +/// the timeline would stall on the hole. Needs a PipeWire daemon and the output | ||
| 971 | +/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`). | ||
| 972 | +#[test] | ||
| 973 | +#[ignore = "needs a running PipeWire daemon"] | ||
| 974 | +fn an_audio_gap_is_silent_and_the_clock_keeps_counting() { | ||
| 975 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); | ||
| 976 | + assert!(session.cut_at(1.0), "split at 1 s"); | ||
| 977 | + assert!(session.cut_at(2.0), "split at 2 s"); | ||
| 978 | + // Silence over [1, 2) s while the picture plays on -- the two lanes part. | ||
| 979 | + assert!( | ||
| 980 | + session.lift_clip(Lane::Audio, 1), | ||
| 981 | + "lift the middle sound out" | ||
| 982 | + ); | ||
| 983 | + assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched"); | ||
| 984 | + let duration = session.timeline_duration(); | ||
| 985 | + | ||
| 986 | + session.seek(0.0); | ||
| 987 | + let mut last_index = None; | ||
| 988 | + session.play(); | ||
| 989 | + // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at | ||
| 990 | + // 1 s, so a stall anywhere inside it cannot hide. | ||
| 991 | + run_for(&mut session, &mut last_index, Duration::from_millis(2_400)); | ||
| 992 | + let now = session.now(); | ||
| 993 | + assert!( | ||
| 994 | + now > 2.2 && now < duration, | ||
| 995 | + "the clock stalled on the audio gap at {now:.3}s" | ||
| 996 | + ); | ||
| 997 | + assert!( | ||
| 998 | + last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true), | ||
| 999 | + "pictures stopped over the silence: {last_index:?}" | ||
| 1000 | + ); | ||
| 1001 | + eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}"); | ||
| 1002 | +} | ||
crates/engine/tests/saveload.rsmodified+64 -1
| @@ -56,6 +56,61 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<PathBuf>, f6 | |||
| 56 | ) | 56 | ) |
| 57 | } | 57 | } |
| 58 | 58 | ||
| 59 | +/// The version-1 promise: a file written before the lanes existed still opens, | ||
| 60 | +/// as one grouped video+audio pair per clip laid end to end, and saving it | ||
| 61 | +/// again writes version 2 -- which reopens as the same timeline. | ||
| 62 | +#[test] | ||
| 63 | +fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() { | ||
| 64 | + let dir = scratch("v1"); | ||
| 65 | + copy_in(&dir, "test_av.mp4"); | ||
| 66 | + let path = dir.join("old.edith"); | ||
| 67 | + // 60 frames of picture from two clips: [0,30) then [60,90) of the source. | ||
| 68 | + std::fs::write( | ||
| 69 | + &path, | ||
| 70 | + "edith 1\nplayhead 45\nsource test_av.mp4\nclip 0 30 0\nclip 60 90 0\n", | ||
| 71 | + ) | ||
| 72 | + .expect("write a v1 file"); | ||
| 73 | + | ||
| 74 | + let loaded = PlaybackSession::open_project(&path).expect("a v1 file still opens"); | ||
| 75 | + let fps = loaded.meta().frame_rate; | ||
| 76 | + assert_eq!( | ||
| 77 | + loaded.clip_spans_by_source(), | ||
| 78 | + vec![(0.0, 30.0 / fps, 0), (30.0 / fps, 30.0 / fps, 0)], | ||
| 79 | + "v1 clips queue up, the second starting where the first ended" | ||
| 80 | + ); | ||
| 81 | + assert_eq!( | ||
| 82 | + loaded.lane_spans_by_source(engine::project::Lane::Audio), | ||
| 83 | + loaded.clip_spans_by_source(), | ||
| 84 | + "both lanes, fully grouped: a v1 timeline had no holes" | ||
| 85 | + ); | ||
| 86 | + assert!( | ||
| 87 | + (loaded.now() - 45.0 / fps).abs() < 1.0 / fps, | ||
| 88 | + "playhead kept" | ||
| 89 | + ); | ||
| 90 | + | ||
| 91 | + // Saved again it is v2, and v2 round-trips to the same timeline. | ||
| 92 | + let v2 = dir.join("new.edith"); | ||
| 93 | + loaded.save_project(&v2).expect("save"); | ||
| 94 | + let text = std::fs::read_to_string(&v2).expect("read back"); | ||
| 95 | + assert!(text.starts_with("edith 2\n"), "{text}"); | ||
| 96 | + assert_eq!( | ||
| 97 | + text.lines().filter(|l| l.starts_with("video ")).count(), | ||
| 98 | + 2, | ||
| 99 | + "{text}" | ||
| 100 | + ); | ||
| 101 | + assert_eq!( | ||
| 102 | + text.lines().filter(|l| l.starts_with("audio ")).count(), | ||
| 103 | + 2, | ||
| 104 | + "{text}" | ||
| 105 | + ); | ||
| 106 | + let again = PlaybackSession::open_project(&v2).expect("open the v2 file"); | ||
| 107 | + assert_eq!(shape(&again), shape(&loaded)); | ||
| 108 | + // ...and re-saving it is byte-identical, so a round trip is stable. | ||
| 109 | + let third = dir.join("third.edith"); | ||
| 110 | + again.save_project(&third).expect("save"); | ||
| 111 | + assert_eq!(std::fs::read(&third).expect("read"), text.as_bytes()); | ||
| 112 | +} | ||
| 113 | + | ||
| 59 | #[test] | 114 | #[test] |
| 60 | fn a_saved_project_reopens_as_the_same_timeline() { | 115 | fn a_saved_project_reopens_as_the_same_timeline() { |
| 61 | let dir = scratch("round_trip"); | 116 | let dir = scratch("round_trip"); |
| @@ -225,8 +280,16 @@ fn malformed_files_are_numbered_errors_and_never_panics() { | |||
| 225 | let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n"; | 280 | let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n"; |
| 226 | 281 | ||
| 227 | for (text, want) in [ | 282 | for (text, want) in [ |
| 228 | - ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 1"), | 283 | + ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 1"), |
| 229 | ("not a project at all\n", "line 1"), | 284 | ("not a project at all\n", "line 1"), |
| 285 | + // Dialects do not mix: lane lines are v2's, `clip` is v1's. | ||
| 286 | + ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 3"), | ||
| 287 | + ("edith 1\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 3"), | ||
| 288 | + ("edith 2\nsource test_av.mp4\nvideo 0 0 30 0\n", "line 3"), | ||
| 289 | + ( | ||
| 290 | + "edith 2\nsource test_av.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n", | ||
| 291 | + "line 4", | ||
| 292 | + ), | ||
| 230 | ("edith 1\nsource test_av.mp4\nclip 0 30\n", "line 3"), | 293 | ("edith 1\nsource test_av.mp4\nclip 0 30\n", "line 3"), |
| 231 | ("edith 1\nsource test_av.mp4\nclip 0 30 4\n", "line 3"), | 294 | ("edith 1\nsource test_av.mp4\nclip 0 30 4\n", "line 3"), |
| 232 | ("edith 1\nsource test_av.mp4\nclip 30 30 0\n", "line 3"), | 295 | ("edith 1\nsource test_av.mp4\nclip 30 30 0\n", "line 3"), |