diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index cb879c1..fd7015d 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -109,7 +109,7 @@ impl AudioSession { path: impl AsRef, segs: &[(f64, f64)], ) -> crate::Result)>> { - let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); + let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect(); Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs) } @@ -119,13 +119,18 @@ impl AudioSession { /// fresh either way. Each source contributes *its own* priming, packet table /// and length, which is the whole reason the resolution is per source. /// + /// A segment naming **no** source is a *gap*: that many seconds of silence + /// are synthesised into the stream as ordinary chunks. Real chunks, not a + /// pause — the master clock counts what the device has been fed, so a hole + /// that fed nothing would stall the whole timeline on it. + /// /// Only the sources some segment names are opened. `Ok(None)` when `sources` /// is empty or its first entry has no AAC track; a later source that is /// missing audio or disagrees on rate/layout is an `Err` — import refuses /// those up front (one timeline, one output device), this is the backstop. pub fn open_multi_segments( sources: &[PathBuf], - segs: &[(usize, f64, f64)], + segs: &[(Option, f64, f64)], ) -> crate::Result)>> { let Some(first) = sources.first() else { return Ok(None); @@ -147,6 +152,9 @@ impl AudioSession { let mut tracks: Vec> = sources.iter().map(|_| None).collect(); tracks[0] = Some(first); for &(source, ..) in segs { + let Some(source) = source else { + continue; // a gap opens no file + }; let slot = tracks .get_mut(source) .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; @@ -171,18 +179,23 @@ impl AudioSession { let segments: Vec = segs .iter() - .map(|&(source, start_secs, end_secs)| { - tracks[source] + .map(|&(source, start_secs, end_secs)| match source { + Some(source) => tracks[source] .as_ref() .expect("opened above") - .segment(source, start_secs, end_secs) + .segment(source, start_secs, end_secs), + None => Segment::silence( + ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, + ), }) .collect(); // Chunk numbering is continuous across every join, counted from the first // segment's audible start in its own source (see `open_segments`). - let timeline = segments.first().map_or(0, |s| { - s.media_target - .saturating_sub(tracks[s.source].as_ref().expect("opened above").priming) + let timeline = segments.first().map_or(0, |s| match s.source { + Some(source) => s + .media_target + .saturating_sub(tracks[source].as_ref().expect("opened above").priming), + None => 0, }); // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so @@ -242,7 +255,7 @@ impl AudioSession { path: impl AsRef, segs: &[(f64, f64)], ) -> crate::Result)>> { - let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); + let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect(); Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs) } @@ -255,12 +268,26 @@ impl AudioSession { /// Every source must declare the same [`AacTrackParams`]: the copy becomes /// one output track with one esds. Import refuses a mismatch up front; the /// check here is the backstop, as is the missing-track `Err`. + /// + /// A segment naming **no** source is a gap. There is no AAC encoder here to + /// make silence with, so the gap is spent as *time* instead: its length is + /// added to the [`samples`](AacPacket::samples) of the packet next to it, + /// which is the duration the writer puts in the stts. Every packet after + /// the gap therefore still lands at its timeline position, so nothing + /// drifts out of lip sync, and a conforming reader renders the hole as + /// silence. + /// + /// ponytail: a gap at the *head* of the timeline has no packet before it to + /// lengthen, so its length goes on the first packet instead — that one + /// packet (23 ms) plays at zero rather than after the hole, and everything + /// from the second packet on is exact. Upgrade path is an empty `elst` + /// entry at the head of the audio track. pub fn copy_multi_segments( sources: &[PathBuf], - segs: &[(usize, f64, f64)], + segs: &[(Option, f64, f64)], ) -> crate::Result)>> { - let Some(&(first, ..)) = segs.first() else { - return Ok(None); + let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else { + return Ok(None); // no segments, or nothing but silence }; let path = sources .get(first) @@ -273,8 +300,19 @@ impl AudioSession { tracks[first] = Some(track); let mut err = 0i64; - let mut packets = Vec::new(); - for (i, &(source, start_secs, end_secs)) in segs.iter().enumerate() { + let mut packets: Vec = Vec::new(); + // Gap time with no packet in front of it to carry it: a leading gap, + // which the first packet written picks up (see the ponytail above). + let mut owed = 0u32; + for &(source, start_secs, end_secs) in segs { + let Some(source) = source else { + let len = ((end_secs - start_secs).max(0.0) * f64::from(params.sample_rate)) as u32; + match packets.last_mut() { + Some(prev) => prev.samples += len, + None => owed += len, + } + continue; + }; let track = source_at(&mut tracks, sources, source)?; if track.track_params() != params { return Err(format!( @@ -289,7 +327,7 @@ impl AudioSession { let available = track.sample_count.saturating_sub(start_id - 1); // The head packet is the priming of the first segment only: a reader // drops exactly one, so an interior join must not add another. - let head = (i == 0 && start_id > 1).then(|| start_id - 1); + let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1); let ids = head .into_iter() .chain(start_id..start_id + packet_run(&mut err, ideal, available)); @@ -304,6 +342,9 @@ impl AudioSession { }); } } + if let Some(first) = packets.first_mut() { + first.samples += owed; + } Ok(Some((params, packets))) } } @@ -435,7 +476,7 @@ impl Track { // output is discarded below, so this only costs decode time. let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL); Segment { - source, + source: Some(source), start_id, start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), media_target, @@ -586,11 +627,13 @@ fn packet_at( last } -/// One window of a source to decode, resolved to media samples and packets. +/// One window of a source to decode, resolved to media samples and packets — +/// or, with no source, a stretch of synthesised silence. struct Segment { /// Index into the worker's tracks; the media positions below are that - /// source's, not the timeline's. - source: usize, + /// source's, not the timeline's. `None` for a gap, where only the length + /// (`media_end`) means anything. + source: Option, /// First packet to feed the decoder, 1-based; includes the pre-roll. start_id: u32, /// Media position of `start_id`'s first frame, in samples-per-channel. @@ -602,6 +645,19 @@ struct Segment { media_end: u64, } +impl Segment { + /// `frames` per channel of silence — a gap in the audio lane. + fn silence(frames: u64) -> Self { + Self { + source: None, + start_id: 0, + start_pos: 0, + media_target: 0, + media_end: frames, + } + } +} + struct Worker { /// Indexed by [`Segment::source`]; only the sources some segment names are /// `Some`, the rest were never opened. @@ -621,7 +677,26 @@ fn run(mut w: Worker) { let segments = std::mem::take(&mut w.segments); for seg in &segments { - let Some(track) = w.tracks[seg.source].as_mut() else { + let Some(source) = seg.source else { + // A gap: hand the device real silence rather than nothing at all, + // in the same packet-sized chunks decoding produces, so `fed` and + // the master clock keep counting straight through the hole. + let mut left = seg.media_end; + while left > 0 { + let frames = left.min(u64::from(SAMPLES_PER_PACKET)); + let chunk = AudioChunk { + start_sample: timeline, + samples: vec![0.0; frames as usize * channels], + }; + if w.tx.send(chunk).is_err() { + return; // caller moved on + } + timeline += frames; + left -= frames; + } + continue; + }; + let Some(track) = w.tracks[source].as_mut() else { continue; // opener fills every named source; nothing to decode }; let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 6fe674b..369d3a2 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -108,6 +108,49 @@ impl DecodeSession { Ok((meta, rx, worker.detach())) } + /// A worker that decodes nothing and emits `len` black frames, indexed from + /// zero -- what a *gap* in the video lane looks like. It goes down the same + /// channel as decoded frames, so a gap costs the caller no branch at all + /// beyond choosing this opener: same bounded channel, same backpressure, + /// same cancel, same retire path. + pub(crate) fn open_black(width: u32, height: u32, len: u32) -> (Receiver, Worker) { + let (tx, rx) = sync_channel(2); + let cancel = Arc::new(AtomicBool::new(false)); + if len == 0 { + return ( + rx, + Worker { + cancel, + handle: None, + }, + ); + } + let worker_cancel = Arc::clone(&cancel); + // One buffer, cloned per frame: opaque black is a constant, and the + // clone is a memcpy against a decode this replaces entirely. + let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat(); + let handle = thread::Builder::new() + .name("black".into()) + .spawn(move || { + for index in 0..len { + if worker_cancel.load(Ordering::Relaxed) { + return; + } + let frame = Frame { + index, + width, + height, + bgra: black.clone(), + }; + if tx.send(frame).is_err() { + return; // caller moved on + } + } + }) + .ok(); + (rx, Worker { cancel, handle }) + } + /// As [`DecodeSession::open_range`], but the caller gets the whole /// [`Worker`] and can therefore *wait* for it. In-process only: a caller /// that outlives its workers has to be able to join them at exit. diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 0818638..e37e3d7 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,15 +1,27 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 1 +//! edith 2 //! playhead 90 //! source test_av.mp4 //! source /elsewhere/test_av2.mp4 -//! clip 0 120 0 -//! clip 0 120 1 +//! video 0 0 120 0 0 +//! audio 0 0 120 0 0 +//! video 120 0 120 1 - //! ``` //! -//! Text because an edit list is three integers and a path, and a path is +//! A lane line is ` `: where the clip +//! sits on the timeline, the half-open source range it plays, the file it plays +//! from, and its group id (`-` for none). Timeline placement is explicit, so a +//! *gap* is simply a stretch no line covers -- there is nothing to write for +//! one, and nothing that can disagree about its length. +//! +//! **Version 1** wrote one lane, queued end to end: `clip `. +//! Such a file still loads -- the clips are laid out cumulatively and copied +//! onto both lanes as one group each, which is exactly what a v1 timeline meant +//! -- and saving it again writes v2. A v1 reader refuses a v2 file by name. +//! +//! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. //! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is //! everything a line-based format cannot carry) and survives round-trip @@ -35,9 +47,10 @@ use std::path::{Path, PathBuf}; use crate::project::Clip; -/// First line, exactly. The version is part of it: a v2 reader will accept a -/// `edith 1` file, and a v1 reader refuses a `edith 2` one by name. -const MAGIC: &[u8] = b"edith 1"; +/// What [`save`] writes. Read support goes back to `edith 1`; see the module +/// docs for what that dialect looked like. +const MAGIC: &[u8] = b"edith 2"; +const MAGIC_V1: &[u8] = b"edith 1"; /// What a project file says: an edit list plus where the playhead stood. /// Structurally valid by construction -- see [`parse`]. @@ -45,13 +58,20 @@ const MAGIC: &[u8] = b"edith 1"; pub struct Document { /// Absolute, relative entries already joined to the file's own directory. pub sources: Vec, - pub clips: Vec, + pub video: Vec, + pub audio: Vec, pub playhead: u32, } /// Writes the project to `path`, atomically. `sources` should already be /// orphan-free ([`crate::Project::without_orphan_sources`]). -pub fn save(path: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> crate::Result<()> { +pub fn save( + path: &Path, + sources: &[PathBuf], + video: &[Clip], + audio: &[Clip], + playhead: u32, +) -> crate::Result<()> { let dir = project_dir(path); let mut part = path.to_path_buf().into_os_string(); part.push(".part"); @@ -62,7 +82,7 @@ pub fn save(path: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> // the second one puts the name itself there. let result = std::fs::File::create(&part) .and_then(|mut f| { - f.write_all(&emit(&dir, sources, clips, playhead))?; + f.write_all(&emit(&dir, sources, video, audio, playhead))?; f.sync_all() }) .and_then(|()| std::fs::rename(&part, path)) @@ -92,7 +112,7 @@ fn project_dir(path: &Path) -> PathBuf { dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) } -fn emit(dir: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> Vec { +fn emit(dir: &Path, sources: &[PathBuf], video: &[Clip], audio: &[Clip], playhead: u32) -> Vec { let mut out = Vec::new(); out.extend_from_slice(MAGIC); out.push(b'\n'); @@ -102,10 +122,19 @@ fn emit(dir: &Path, sources: &[PathBuf], clips: &[Clip], playhead: u32) -> Vec crate::Result { let body = data.strip_suffix(b"\n").unwrap_or(data); let mut lines = body.split(|&b| b == b'\n').enumerate(); let (_, first) = lines.next().unwrap_or((0, &[])); - if first != MAGIC { + let v1 = first == MAGIC_V1; + if first != MAGIC && !v1 { return Err(match first.strip_prefix(b"edith ") { Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)), None => "line 1: not a edith file".to_string(), @@ -126,10 +156,14 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { let mut doc = Document { sources: Vec::new(), - clips: Vec::new(), + video: Vec::new(), + audio: Vec::new(), playhead: 0, }; let mut playhead_seen = false; + // Where the next v1 clip is placed: that dialect had no `start` field, the + // clips simply queued up. + let mut queued = 0u32; for (i, line) in lines { let n = i + 1; let (keyword, rest) = match line.iter().position(|&b| b == b' ') { @@ -147,7 +181,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { playhead_seen = true; } b"source" => { - if !doc.clips.is_empty() { + if !doc.video.is_empty() || !doc.audio.is_empty() { return Err(format!("line {n}: source after a clip").into()); } if rest.is_empty() { @@ -162,37 +196,60 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { dir.join(path) }); } - b"clip" => { - let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect(); - if fields.len() != 3 { - return Err( - format!("line {n}: clip wants 3 fields, found {}", fields.len()).into(), - ); - } - let clip = Clip { - in_frame: number(fields[0], n)?, - out_frame: number(fields[1], n)?, - source: number(fields[2], n)? as usize, + // v1: one lane, no placement, no groups. Every clip becomes one + // grouped video+audio pair laid where the queue reached, which is + // what the file always meant. + b"clip" if v1 => { + let f = fields(rest, 3, "clip", n)?; + let clip = check( + Clip { + start: queued, + in_frame: number(f[0], n)?, + out_frame: number(f[1], n)?, + source: number(f[2], n)? as usize, + link: Some(doc.video.len() as u32), + }, + &doc, + n, + )?; + queued = clip.end(); + doc.video.push(clip); + doc.audio.push(clip); + } + b"video" | b"audio" if !v1 => { + let f = fields(rest, 5, "clip", n)?; + let clip = check( + Clip { + start: number(f[0], n)?, + in_frame: number(f[1], n)?, + out_frame: number(f[2], n)?, + source: number(f[3], n)? as usize, + link: match f[4] { + b"-" => None, + field => Some(number(field, n)?), + }, + }, + &doc, + n, + )?; + let lane = match keyword { + b"video" => &mut doc.video, + _ => &mut doc.audio, }; - if clip.out_frame <= clip.in_frame { + // The sorted, non-overlapping placement invariant, checked at + // the only door untrusted clips come in through. + if lane.last().is_some_and(|prev| prev.end() > clip.start) { return Err(format!( - "line {n}: clip [{}, {}) is empty", - clip.in_frame, clip.out_frame + "line {n}: clip at {} overlaps the one before it, or comes before it", + clip.start ) .into()); } - if clip.source >= doc.sources.len() { - return Err(format!( - "line {n}: clip names source {} of {}", - clip.source, - doc.sources.len() - ) - .into()); - } - doc.clips.push(clip); + lane.push(clip); } // Empty lines land here too: nothing in this format is optional - // whitespace. + // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one) + // is a file mixing dialects, and is refused the same way. _ => { return Err(format!( "line {n}: unknown keyword {:?}", @@ -202,12 +259,50 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } } } - if doc.clips.is_empty() { + if doc.video.is_empty() && doc.audio.is_empty() { return Err("no clips: an empty timeline is not a project".into()); } Ok(doc) } +/// Splits a line's fields, refusing the wrong count by name. +fn fields<'a>( + rest: &'a [u8], + want: usize, + what: &str, + line: usize, +) -> crate::Result> { + let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect(); + if fields.len() != want { + return Err(format!( + "line {line}: {what} wants {want} fields, found {}", + fields.len() + ) + .into()); + } + Ok(fields) +} + +/// The per-clip structure checks both dialects share. +fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result { + if clip.out_frame <= clip.in_frame { + return Err(format!( + "line {line}: clip [{}, {}) is empty", + clip.in_frame, clip.out_frame + ) + .into()); + } + if clip.source >= doc.sources.len() { + return Err(format!( + "line {line}: clip names source {} of {}", + clip.source, + doc.sources.len() + ) + .into()); + } + Ok(clip) +} + fn number(field: &[u8], line: usize) -> crate::Result { match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) { Some(n) => Ok(n), @@ -258,42 +353,113 @@ fn unescape(field: &[u8], line: usize) -> crate::Result { mod tests { use super::*; - fn clip(in_frame: u32, out_frame: u32, source: usize) -> Clip { + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { + start, in_frame, out_frame, source, + link, } } - /// Two sources, one under the project's own directory and one not, and a - /// clip from each -- the shape every case below starts from. - fn doc() -> (PathBuf, Vec, Vec) { + /// Two sources, one under the project's own directory and one not, a clip + /// from each on the video lane, and an audio lane with a gap in the middle + /// -- the shape every case below starts from. + fn doc() -> (PathBuf, Vec, Vec, Vec) { ( PathBuf::from("/proj"), vec![ PathBuf::from("/proj/a.mp4"), PathBuf::from("/elsewhere/b.mp4"), ], - vec![clip(0, 30, 0), clip(10, 20, 1)], + vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))], + vec![clip(0, 0, 30, 0, Some(0))], ) } #[test] fn relative_and_absolute_paths_round_trip() { - let (dir, sources, clips) = doc(); - let bytes = emit(&dir, &sources, &clips, 12); + let (dir, sources, video, audio) = doc(); + let bytes = emit(&dir, &sources, &video, &audio, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 1\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\nclip 0 30 0\nclip 10 20 1\n", + "edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\ + video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n", "the file under the project directory is written relative to it" ); let back = parse(&bytes, &dir).expect("parse"); assert_eq!(back.sources, sources, "relative entries rejoin the dir"); - assert_eq!(back.clips, clips); + assert_eq!(back.video, video); + assert_eq!( + back.audio, audio, + "the trailing gap needs no line of its own" + ); assert_eq!(back.playhead, 12); // ...and emitting the parsed document reproduces the same bytes. - assert_eq!(emit(&dir, &back.sources, &back.clips, back.playhead), bytes); + assert_eq!( + emit(&dir, &back.sources, &back.video, &back.audio, back.playhead), + bytes + ); + } + + /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of + /// lanes, and saving it again writes v2. + #[test] + fn a_v1_file_loads_as_two_grouped_lanes() { + let dir = PathBuf::from("/proj"); + let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n"; + let back = parse(v1, &dir).expect("v1 parses"); + assert_eq!( + back.video, + vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))], + "v1 clips queue up: the second starts where the first ended" + ); + assert_eq!(back.audio, back.video, "one take per clip, on both lanes"); + assert_eq!(back.playhead, 5); + // Saved again it is v2, and that round-trips to the same document. + let v2 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead); + assert!(v2.starts_with(b"edith 2\n")); + let again = parse(&v2, &dir).expect("v2 parses"); + assert_eq!((again.video, again.audio), (back.video, back.audio)); + // A dialect may not be mixed: lane lines under v1, `clip` under v2. + for (bytes, want) in [ + ( + &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..], + "line 3: unknown keyword \"video\"", + ), + ( + b"edith 2\nsource a.mp4\nclip 0 30 0\n", + "line 3: unknown keyword \"clip\"", + ), + ] { + assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want); + } + } + + /// A gap is the absence of a line, so a lane's placements must arrive in + /// order and never overlap -- the invariant the whole model rests on. + #[test] + fn a_lane_out_of_order_or_overlapping_is_refused() { + let dir = PathBuf::from("/proj"); + for bytes in [ + &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..], + b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n", + ] { + let err = parse(bytes, &dir).unwrap_err().to_string(); + assert!(err.starts_with("line 4: clip at "), "{err}"); + } + // The lanes are independent, so a video line never crowds an audio one. + assert!( + parse( + b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n", + &dir + ) + .is_ok() + ); + // ...and a lane may be empty as long as the other one is not. + let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse"); + assert!(only_audio.video.is_empty()); } /// The relocatability promise, from the two directions a project path @@ -316,11 +482,12 @@ mod tests { let source = dir.join("real/a.mp4"); let path = dir.join("link/p.edith"); - save(&path, &[source], &[clip(0, 30, 0)], 0).expect("save"); + let one = [clip(0, 0, 30, 0, None)]; + save(&path, &[source], &one, &one, 0).expect("save"); let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 1\nplayhead 0\nsource a.mp4\nclip 0 30 0\n" + "edith 2\nplayhead 0\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n" ); // Loading rejoins the *given* directory, so the file is reached by the // way the project was opened -- the same file, through the link. @@ -336,7 +503,7 @@ mod tests { let dir = PathBuf::from("/proj"); // A newline and a percent in a filename, plus a non-UTF-8 byte. let nasty = PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())); - let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 5, 0)], 0); + let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 0, 5, 0, None)], &[], 0); assert_eq!( bytes.iter().filter(|&&b| b == b'\n').count(), 4, @@ -349,10 +516,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 2\nsource a.mp4\nclip 0 5 0\n", &dir) + let err = parse(b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 2"); + assert_eq!(err, "line 1: unsupported version 3"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), @@ -421,8 +588,8 @@ mod tests { /// Every truncation of a good file either parses or refuses; none panics. #[test] fn truncations_never_panic() { - let (dir, sources, clips) = doc(); - let bytes = emit(&dir, &sources, &clips, 12); + let (dir, sources, video, audio) = doc(); + let bytes = emit(&dir, &sources, &video, &audio, 12); for cut in 0..bytes.len() { let _ = parse(&bytes[..cut], &dir); // ...and the same file with a byte lopped off the front, which diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 108ec9e..8dfe585 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -24,7 +24,7 @@ use crate::audio::AudioSession; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; -use crate::project::Project; +use crate::project::{Lane, Project}; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. @@ -169,18 +169,31 @@ fn run( let mut encoder = Enc::open(meta, settings)?; let mut muxer = None; let mut done = 0u32; - for clip in project.clips() { + let black = Black::new(meta); + // Spans, not clips: a gap in the video lane is part of the timeline and + // gets encoded too, as black frames. The picture count is therefore + // `timeline_frames` however the lane is arranged. + for span in project.spans_from(Lane::Video, 0) { // Every clip reopens its own source file at its own in point; the // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the // file boundaries, which are just cuts that change the path. - let source = sources - .get(clip.source) - .ok_or_else(|| format!("clip names source {} of {}", clip.source, sources.len()))?; - let mut pictures = ClipDecoder::open(source, clip.in_frame)?; - for _ in 0..clip.len() { + let mut pictures = match span.from { + Some((source, in_frame)) => { + let path = sources + .get(source) + .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; + Some(ClipDecoder::open(path, in_frame)?) + } + None => None, + }; + for _ in 0..span.len { cancelled(shared)?; - let Some((y, u, v, width, height)) = pictures.next()? else { + let picture = match &mut pictures { + Some(pictures) => pictures.next()?, + None => Some(black.picture()), + }; + let Some((y, u, v, width, height)) = picture else { break; // source ran out early; the clip list outlives the file }; if let Some(au) = encoder.encode(y, u, v, width, height)? { @@ -204,7 +217,7 @@ fn run( }; if let Some((_, packets)) = audio { for packet in packets { - muxer.write_audio_packet(&packet.bytes)?; + muxer.write_audio_packet(&packet.bytes, packet.samples)?; } } cancelled(shared)?; @@ -213,6 +226,33 @@ fn run( Ok(()) } +/// The I420 planes of one black picture, allocated once for a whole export: a +/// gap in the video lane is encoded, not skipped, or every frame after it would +/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention +/// [`crate::convert`] decodes with. +struct Black { + y: Vec, + uv: Vec, + width: u32, + height: u32, +} + +impl Black { + fn new(meta: &VideoMeta) -> Self { + let (w, h) = (meta.width as usize, meta.height as usize); + Self { + y: vec![16; w * h], + uv: vec![128; w.div_ceil(2) * h.div_ceil(2)], + width: meta.width, + height: meta.height, + } + } + + fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { + (&self.y, &self.uv, &self.uv, self.width, self.height) + } +} + /// `Err` once a cancel has been asked for. Called at every point where the work /// left is more than an instant, so an `esc` at 99.9% still stops the export /// instead of quietly completing it. diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 00ed8f1..2d182d4 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -144,7 +144,12 @@ impl Mp4Muxer { } /// One raw AAC packet (no ADTS header), copied verbatim from the source. - pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> { + /// `samples` is what the sample table says it occupies -- normally the + /// [`AAC_PACKET_SAMPLES`] the codec fixes, but longer for the packet that + /// carries a gap in the timeline's audio (see + /// [`AudioSession::copy_multi_segments`](crate::AudioSession::copy_multi_segments)), + /// where the extra duration is the silence a reader renders. + pub fn write_audio_packet(&mut self, bytes: &[u8], samples: u32) -> crate::Result<()> { if !self.has_audio { return Err("audio packet written to a video-only file".into()); } @@ -152,7 +157,7 @@ impl Mp4Muxer { AUDIO_TRACK, &Mp4Sample { start_time: 0, - duration: AAC_PACKET_SAMPLES, + duration: samples.max(AAC_PACKET_SAMPLES), rendering_offset: 0, // Every AAC packet is a sync point; saying so per-sample would emit // an `stss` listing all of them, while no `stss` means the same thing. @@ -386,8 +391,14 @@ mod tests { for unit in &units { muxer.write_video_au(unit).unwrap(); } - muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap(); - muxer.write_audio_packet(&[0x24, 0x25]).unwrap(); + muxer + .write_audio_packet(&[0x21, 0x22, 0x23], AAC_PACKET_SAMPLES) + .unwrap(); + // The second packet carries a gap: 1024 of its own plus half a second + // of silence, which is what the sample table has to say. + muxer + .write_audio_packet(&[0x24, 0x25], AAC_PACKET_SAMPLES + 22_050) + .unwrap(); muxer.finish().unwrap(); let file = File::open(&out).unwrap(); @@ -413,6 +424,13 @@ mod tests { [0x21, 0x22, 0x23], "audio packets copied verbatim" ); + let with_gap = reader.read_sample(audio_id, 2).unwrap().unwrap(); + assert_eq!(&with_gap.bytes[..], [0x24, 0x25], "gap or not, verbatim"); + assert_eq!( + with_gap.duration, + AAC_PACKET_SAMPLES + 22_050, + "the gap is spent as duration, and the track ends half a second later" + ); let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap(); assert_eq!(meta.frame_count, 3); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 3a3b652..fc85360 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Demuxer, VideoMeta}; -use crate::project::{Clip, Project}; +use crate::project::{Clip, Lane, Project, Span}; /// How long the feeder waits out a full ring. The ring holds a second, so this /// only has to be short next to that; it costs one wakeup per 10 ms of audio. @@ -104,12 +104,13 @@ pub struct PlaybackSession { /// The edit list. Everything a caller says in seconds is a *timeline* /// position; only this maps it onto the file. project: Project, - /// Source range the current decode worker was opened for, and where that - /// range starts on the timeline -- together they rewrite a source frame - /// index into a timeline one. Not a clip index: a `cut` splits the clip - /// under a running worker, and only the mapping survives that. - range: Clip, - timeline_start: u32, + /// What the current video worker was opened for: where it sits on the + /// timeline, how long it runs, and which source frame it started at -- + /// together they rewrite a source frame index into a timeline one. Not a + /// clip index: a `split` cuts the clip under a running worker, and only the + /// mapping survives that. A span with no source is a *gap*, and the worker + /// feeding it emits black frames indexed from zero. + span: Span, /// The last clip has been played out; see [`PlaybackSession::is_eos`]. eos: bool, } @@ -127,10 +128,10 @@ impl PlaybackSession { Some(_) => ClockSource::Audio, None => ClockSource::Wall, }; - // One clip covering the file, so timeline == source until the first - // edit -- and the range opened above is exactly that clip's. + // One clip per lane covering the file, so timeline == source until the + // first edit -- and the range opened above is exactly that clip's. let project = Project::single(&path, meta.frame_count); - let range = project.clips()[0]; + let span = project.span_at(Lane::Video, 0).expect("never empty"); Ok(Self { meta, frames, @@ -139,8 +140,7 @@ impl PlaybackSession { clock: PlaybackClock::new(source), audio, project, - range, - timeline_start: 0, + span, eos: false, }) } @@ -178,7 +178,7 @@ impl PlaybackSession { .map_err(|e| format!("source {}: {e}", source.display()))?; counts.push(other.frame_count); } - for (i, clip) in doc.clips.iter().enumerate() { + for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() { if clip.out_frame > counts[clip.source] { return Err(format!( "clip {i} ends at frame {} but {} has {} frames", @@ -191,9 +191,9 @@ impl PlaybackSession { } let playhead = doc.playhead; - let project = Project::from_parts(doc.sources, doc.clips) + let project = Project::from_parts(doc.sources, doc.video, doc.audio) .ok_or("the project's clips do not fit its sources")?; - let range = project.clips()[0]; + let span = project.span_at(Lane::Video, 0).expect("never empty"); let mut session = Self { meta, frames, @@ -205,8 +205,7 @@ impl PlaybackSession { }), audio, project, - range, - timeline_start: 0, + span, eos: false, }; // The scaffolding above opened source 0 from its first frame and the @@ -232,10 +231,10 @@ impl PlaybackSession { /// [`crate::edith`]). Sources no clip plays from are left out, and the /// playhead is saved with it so a reopened project resumes where it stood. pub fn save_project(&self, path: &Path) -> crate::Result<()> { - let (sources, clips) = self.project.without_orphan_sources(); + let (sources, video, audio) = self.project.without_orphan_sources(); let playhead = secs_to_frame(self.now(), self.meta.frame_rate) .min(self.project.timeline_frames().saturating_sub(1)); - crate::edith::save(path, &sources, &clips, playhead) + crate::edith::save(path, &sources, &video, &audio, playhead) } /// The next decoded frame, its `index` rewritten from a source frame to a @@ -249,8 +248,10 @@ impl PlaybackSession { loop { match self.frames.try_recv() { Ok(mut frame) => { - frame.index = - self.timeline_start + frame.index.saturating_sub(self.range.in_frame); + // A gap's worker indexes from zero, a decoder's from its in + // point: `base` is whichever this span started at. + let base = self.span.from.map_or(0, |(_, in_frame)| in_frame); + frame.index = self.span.start + frame.index.saturating_sub(base); return Some(frame); } Err(TryRecvError::Empty) => return None, @@ -287,41 +288,55 @@ impl PlaybackSession { self.retired.retain(|w| !w.is_finished()); } - /// Starts decoding whatever follows the current range on the timeline; - /// `false` past the end. The next timeline frame is derived rather than - /// remembered as a clip index, because a `cut` while playing splits the + /// Starts feeding whatever follows the current span on the timeline -- + /// another clip, or a gap, which is black frames from a worker that opens no + /// file. `false` past the end. The next timeline frame is derived rather + /// than remembered as a clip index, because a `split` while playing cuts the /// clip under the running worker and only the mapping stays true. fn next_clip(&mut self) -> bool { - let next = self.timeline_start + self.range.len(); - let Some((idx, source)) = self.project.map_timeline(next) else { + let next = self.span.end(); + let Some(span) = self.project.span_at(Lane::Video, next) else { return false; }; - let clip = self.project.clips()[idx]; - let out = clip.out_frame; // We only get here on a disconnect, so the old worker has already // returned; cancel anyway, so `retire` treats every path alike. self.worker.cancel(); - match DecodeSession::open_worker(&self.project.sources()[clip.source], source, out) { - Ok((_, frames, worker)) => { - // Receiver first, worker second: the drop of the old receiver - // is what wakes a worker parked in `send`, and only then can it - // return and be reaped by a later sweep. - self.frames = frames; - self.retire(worker); - } - // Disappearing-file case, as in `seek`. The old receiver is still - // disconnected, so the next pass moves on to the clip after this. - Err(e) => eprintln!("clip at timeline frame {next}: video open failed: {e}"), - } - self.range = Clip { - in_frame: source, - out_frame: out, - ..clip - }; - self.timeline_start = next; + self.start_span(span); true } + /// Points the video worker at `span`: a decoder over its source range, or a + /// black-frame generator for a gap. The old worker must already have been + /// cancelled -- this is the half both `seek` and `next_clip` share. + /// + /// A source that will not open leaves the *span* installed anyway: the + /// timeline still moves, there are simply no more pictures, and the + /// disconnected receiver carries the session on to the next span. + fn start_span(&mut self, span: Span) { + let opened = match span.from { + Some((source, in_frame)) => DecodeSession::open_worker( + &self.project.sources()[source], + in_frame, + in_frame + span.len, + ) + .map(|(_, frames, worker)| (frames, worker)) + .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)), + None => Ok(DecodeSession::open_black( + self.meta.width, + self.meta.height, + span.len, + )), + }; + if let Ok((frames, worker)) = opened { + // Receiver first, worker second: the drop of the old receiver is + // what wakes a worker parked in `send`, and only then can it return + // and be reaped by a later sweep. + self.frames = frames; + self.retire(worker); + } + self.span = span; + } + /// Length of the edited timeline in seconds -- what a ruler shows, and it /// shrinks with every delete. pub fn timeline_duration(&self) -> f64 { @@ -343,20 +358,46 @@ impl PlaybackSession { /// [`Project::sources`] each clip plays from -- what a lane needs to colour /// an imported clip differently from the file the session was opened with. pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> { - self.clip_spans() - .into_iter() - .zip(self.project.clips()) - .map(|((start, len), clip)| (start, len, clip.source)) + self.lane_spans_by_source(Lane::Video) + } + + /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane, + /// with each clip's group id -- what a two-lane front-end draws. The holes + /// between consecutive entries are the gaps. + pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> { + let fps = self.meta.frame_rate; + self.project + .lane(lane) + .iter() + .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source)) .collect() } - /// Splits the clip under `timeline_secs` in two. Metadata only: a cut never - /// changes the timeline->source mapping, so the running decoder stays - /// correct and playback does not blink. `false` at a clip start or past the - /// end, where there would be nothing to split off. + /// Splits every lane at `timeline_secs`, so the two sides become two + /// groups. Metadata only: a split never changes the timeline->source + /// mapping, so the running decoder stays correct and playback does not + /// blink. `false` at a clip start, in a gap and past the end, where there + /// would be nothing to split off. pub fn cut_at(&mut self, timeline_secs: f64) -> bool { self.project - .cut(secs_to_frame(timeline_secs, self.meta.frame_rate)) + .split(secs_to_frame(timeline_secs, self.meta.frame_rate)) + } + + /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at + /// `timeline_secs` in every lane and puts them back in one group. `false` + /// unless a split could have produced what is there. Metadata only, like the + /// split -- no reseek. + pub fn regroup_at(&mut self, timeline_secs: f64) -> bool { + self.project + .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) + } + + /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, + /// silence on the audio one, and nothing else moves. Reseeks, because what + /// the playhead sits on has changed. `false` for a bad index and for the + /// lift that would leave the whole timeline empty. + pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { + self.edit(|p| p.lift(lane, idx)) } /// The clip at `idx` -- what a caller copies. It is a pair of source frame @@ -374,14 +415,16 @@ impl PlaybackSession { self.edit(|p| p.paste(at, clip)) } - /// Removes a clip and closes the gap. Unlike a cut this *does* move every - /// following frame, so the session reseeks to wherever the playhead now - /// points. `false` for a bad index or the last remaining clip. + /// Removes the video clip at `idx` and everything under it, closing the gap + /// on every lane. Unlike a split this *does* move every following frame, so + /// the session reseeks to wherever the playhead now points. + /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead. + /// `false` for a bad index or the last remaining clip. pub fn delete_clip(&mut self, idx: usize) -> bool { self.edit(|p| p.delete(idx)) } - /// Undoes the last successful cut or delete, and reseeks like a delete. + /// Undoes the last successful edit, and reseeks like a delete. pub fn undo(&mut self) -> bool { self.edit(Project::undo) } @@ -495,28 +538,11 @@ impl PlaybackSession { // [`retire`](Self::retire), which is what keeps a scrub off the price // of a VA-API init. self.worker.cancel(); - // `target` is inside the timeline (never empty), so this always maps; - // the range runs from there to the end of the clip it landed in. - if let Some((idx, source)) = self.project.map_timeline(target) { - let clip = self.project.clips()[idx]; - let out = clip.out_frame; - match DecodeSession::open_worker(&self.project.sources()[clip.source], source, out) { - Ok((_, frames, worker)) => { - // Receiver first, worker second -- see `next_clip`. - self.frames = frames; - self.retire(worker); - } - // The file opened once already, so this is a disappearing-file - // case: the timeline still moves, there are simply no more - // pictures. - Err(e) => eprintln!("seek: video reopen failed: {e}"), - } - self.range = Clip { - in_frame: source, - out_frame: out, - ..clip - }; - self.timeline_start = target; + // `target` is inside the timeline (never empty), so this always spans; + // the span runs from there to the end of whatever it landed in -- a + // clip, or a gap, which starts a black-frame worker instead. + if let Some(span) = self.project.span_at(Lane::Video, target) { + self.start_span(span); } self.eos = false; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index ec0791e..c35937b 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1,19 +1,36 @@ -//! Edit list: the timeline as a list of source ranges. Pure data, no I/O. +//! Edit list: two lanes of *placed* source ranges. Pure data, no I/O. //! -//! A [`Project`] is an ordered list of [`Clip`]s, each a half-open `[in, out)` -//! range of *source* frames. Playing the timeline means playing those ranges -//! back to back, so timeline frame `t` is found by walking the clips and -//! consuming their lengths; the mapping is [`Project::map_timeline`] and it is -//! the only place that conversion lives. +//! A [`Project`] holds a video lane and an audio lane. Each lane is a list of +//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of +//! *source* frames it plays, which file it plays it from, and -- the whole model +//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an +//! offset rather than queued end to end, so: +//! +//! * a **gap** is not an object, it is the absence of a placement. Nothing has +//! to be inserted, kept in sync or garbage-collected for a hole to exist, and +//! a hole cannot disagree with its neighbours about how long it is; +//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a +//! splice of the list; +//! * the lanes are independent: deleting audio under a picture is one lane's +//! business, and the picture does not shift. +//! +//! The price is one invariant this module enforces at every mutation and every +//! constructor: within a lane, clips are **sorted by `start` and never overlap** +//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a +//! walk over that order. //! //! Two frame spaces meet here and are never mixed: *source* frames index the //! decoded file, *timeline* frames index what the viewer sees. Both are 0-based //! (sample ids in the demuxer are 1-based; that conversion stays in `decode`). //! -//! Editing is metadata only. [`Project::cut`] splits a clip in two without -//! changing any timeline->source mapping, so a running decoder stays correct -//! across a cut; [`Project::delete`] does change the mapping and the caller -//! must reseek. Every successful edit snapshots the clip list, so +//! Grouping is [`Clip::link`]: clips carrying the same id were split from the +//! same take and move together. [`Project::split`] cuts every lane at a timeline +//! frame and hands the two sides two fresh ids; [`Project::regroup`] is its +//! inverse and rejoins them. +//! +//! Editing is metadata only. [`Project::split`] changes no timeline->source +//! mapping, so a running decoder stays correct across it; everything else does +//! and the caller must reseek. Every successful edit snapshots both lanes, so //! [`Project::undo`] is an exact restore. //! //! A clip names its file by *index* into [`Project::sources`], which is @@ -25,13 +42,21 @@ use std::path::{Path, PathBuf}; /// A half-open `[in_frame, out_frame)` range of frames of source -/// [`source`](Clip::source). Never empty. +/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). +/// Never empty. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Clip { + /// Timeline frame the clip's first frame is shown at. Meaningless on a + /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it + /// with where the caller asked for. + pub start: u32, pub in_frame: u32, pub out_frame: u32, /// Index into [`Project::sources`]. pub source: usize, + /// Group id: clips sharing one were split from the same take. `None` for a + /// clip that belongs to no group. + pub link: Option, } impl Clip { @@ -39,6 +64,48 @@ impl Clip { pub fn len(&self) -> u32 { self.out_frame - self.in_frame } + + /// One past the last timeline frame it covers. + pub fn end(&self) -> u32 { + self.start + self.len() + } +} + +/// Which lane an operation acts on. The lanes are peers: no operation reads one +/// to decide what to do to the other, except the grouped ones that say so. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Lane { + Video, + Audio, +} + +impl Lane { + pub const ALL: [Lane; 2] = [Lane::Video, Lane::Audio]; + + fn index(self) -> usize { + self as usize + } +} + +/// What a lane holds over one stretch of the timeline: either a placed clip or +/// a gap. Returned already trimmed to the position it was asked about, so a +/// caller can hand `len` straight to a decoder (or to a black-frame generator). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Span { + /// Timeline frame the span starts at. + pub start: u32, + /// Frames it covers; `>= 1`. + pub len: u32, + /// `(source index, first source frame)`, or `None` for a gap -- which the + /// engine renders as black frames and as silence. + pub from: Option<(usize, u32)>, +} + +impl Span { + /// One past the last timeline frame it covers. + pub fn end(&self) -> u32 { + self.start + self.len + } } /// The edit list plus its undo history. @@ -46,49 +113,77 @@ impl Clip { pub struct Project { /// Append-only: never popped, never reordered. See the module docs. sources: Vec, - clips: Vec, + /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint. + lanes: [Vec; 2], /// Snapshots pushed *before* each successful edit; `undo` pops one. - history: Vec>, + history: Vec<[Vec; 2]>, + /// Never rolled back by an undo: an id retired by an undone split must not + /// come back and group two clips that were never together. + next_link: u32, } impl Project { - /// One clip covering the whole of `path` -- the state of a freshly opened - /// video, where the timeline is the source. `frame_count` of 0 would break - /// the never-empty invariant, so it is clamped to one frame. + /// One clip per lane covering the whole of `path`, the two grouped -- the + /// state of a freshly opened video, where the timeline is the source. + /// `frame_count` of 0 would break the never-empty invariant, so it is + /// clamped to one frame. pub fn single(path: impl AsRef, frame_count: u32) -> Self { + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: frame_count.max(1), + source: 0, + link: Some(0), + }; Self { sources: vec![canonical(path.as_ref())], - clips: vec![Clip { - in_frame: 0, - out_frame: frame_count.max(1), - source: 0, - }], + lanes: [vec![clip], vec![clip]], history: Vec::new(), + next_link: 1, } } /// A project rebuilt from a saved edit list -- the load half of /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is /// `false` until the first edit of the new session. `None` when the parts - /// would break an invariant every other constructor keeps: no clips, an - /// empty clip, or a clip naming a source that is not there. - pub fn from_parts(sources: Vec, clips: Vec) -> Option { - if clips.is_empty() - || clips - .iter() - .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame) - { + /// would break an invariant every other constructor keeps: both lanes + /// empty, an empty clip, a clip naming a source that is not there, or a + /// lane that is unsorted or self-overlapping. + pub fn from_parts(sources: Vec, video: Vec, audio: Vec) -> Option { + if video.is_empty() && audio.is_empty() { return None; } + let lanes = [video, audio]; + if lanes.iter().any(|lane| { + !sorted_disjoint(lane) + || lane + .iter() + .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame) + }) { + return None; + } + let next_link = lanes + .iter() + .flatten() + .filter_map(|c| c.link) + .max() + .map_or(0, |m| m + 1); Some(Self { sources: sources.iter().map(|s| canonical(s)).collect(), - clips, + lanes, history: Vec::new(), + next_link, }) } + /// The video lane -- what an export renders and what a single-lane caller + /// still means by "the clips". pub fn clips(&self) -> &[Clip] { - &self.clips + self.lane(Lane::Video) + } + + pub fn lane(&self, lane: Lane) -> &[Clip] { + &self.lanes[lane.index()] } /// The files the clips index into, in import order; index 0 is the file the @@ -99,8 +194,8 @@ impl Project { /// Index for `path`, appending it if it is new. Deduped by /// `fs::canonicalize`, so the same file reached by two paths imports once. - /// The clip list is untouched -- see [`Project::append_clip`] -- so this - /// pushes no history: a source entry alone changes nothing playable. + /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes + /// no history: a source entry alone changes nothing playable. pub fn import(&mut self, path: impl AsRef) -> usize { let path = canonical(path.as_ref()); match self.sources.iter().position(|s| *s == path) { @@ -112,20 +207,26 @@ impl Project { } } - /// Append a whole-file clip of `source` to the end of the timeline. One - /// history snapshot, so an import is one undo step -- and undoing it leaves - /// the (harmless) source entry behind, because indexes are forever. - /// Refused for an unknown source index. + /// Append a whole-file clip of `source` to the end of *both* lanes, grouped + /// -- an import lands as one take. One history snapshot, so an import is one + /// undo step, and undoing it leaves the (harmless) source entry behind, + /// because indexes are forever. Refused for an unknown source index. pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool { if source >= self.sources.len() { return false; } - self.history.push(self.clips.clone()); - self.clips.push(Clip { + self.snapshot(); + let start = self.timeline_frames(); + let clip = Clip { + start, in_frame: 0, out_frame: frame_count.max(1), source, - }); + link: Some(self.new_link()), + }; + for lane in &mut self.lanes { + lane.push(clip); + } true } @@ -134,12 +235,13 @@ impl Project { /// [`Project::append_clip`]), so an undone import leaves an orphan source /// entry behind; writing that orphan to a project file would let a file /// nothing plays refuse a future load. New indexes are assigned in order of - /// first use, so the same project always emits the same bytes. - pub fn without_orphan_sources(&self) -> (Vec, Vec) { + /// first use -- video lane first, then audio -- so the same project always + /// emits the same bytes. + pub fn without_orphan_sources(&self) -> (Vec, Vec, Vec) { let mut moved = vec![None; self.sources.len()]; let mut sources = Vec::new(); - let mut clips = self.clips.clone(); - for c in &mut clips { + let mut lanes = self.lanes.clone(); + for c in lanes.iter_mut().flatten() { let old = c.source; c.source = match moved[old] { Some(new) => new, @@ -150,121 +252,267 @@ impl Project { } }; } - (sources, clips) + let [video, audio] = lanes; + (sources, video, audio) } - /// Length of the timeline in frames. + /// Length of the timeline in frames: where the *last* lane runs out. A lane + /// that ends early is a trailing gap in that lane, not a shorter timeline. pub fn timeline_frames(&self) -> u32 { - self.clips.iter().map(Clip::len).sum() + self.lanes + .iter() + .filter_map(|lane| lane.last().map(Clip::end)) + .max() + .unwrap_or(0) } - /// `(timeline_start, len)` per clip, in order -- what a UI lane needs to - /// lay clips out without redoing the cumulative sum. + /// `(timeline_start, len)` per video clip, in order -- what a UI lane needs + /// to lay clips out. Gaps show up as the holes between consecutive entries. pub fn clip_spans(&self) -> Vec<(u32, u32)> { - let mut start = 0; - self.clips - .iter() - .map(|c| { - let span = (start, c.len()); - start += c.len(); - span - }) - .collect() + self.lane_spans(Lane::Video) + } + + pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> { + self.lane(lane).iter().map(|c| (c.start, c.len())).collect() + } + + /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap + /// and past the end -- [`Project::span_at`] is the version that tells those + /// two apart. + pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> { + let clips = self.lane(lane); + let idx = at(clips, timeline_frame)?; + Some(( + idx, + clips[idx].in_frame + (timeline_frame - clips[idx].start), + )) } - /// Timeline frame -> `(clip index, source frame)`. `None` past the end. + /// [`map`](Project::map) on the video lane -- the mapping a decoder follows. pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> { - let mut start = 0; - for (i, c) in self.clips.iter().enumerate() { - if timeline_frame < start + c.len() { - return Some((i, c.in_frame + (timeline_frame - start))); - } - start += c.len(); + self.map(Lane::Video, timeline_frame) + } + + /// What `lane` holds from `timeline_frame` on: the rest of the clip covering + /// it, or the gap running to the next clip (or to the end of the timeline, + /// which is where a lane shorter than its neighbour keeps showing black). + /// `None` at or past the end of the timeline, which is the only "nothing + /// left" there is. + pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option { + let total = self.timeline_frames(); + if timeline_frame >= total { + return None; + } + let clips = self.lane(lane); + Some(match at(clips, timeline_frame) { + Some(idx) => Span { + start: timeline_frame, + len: clips[idx].end() - timeline_frame, + from: Some(( + clips[idx].source, + clips[idx].in_frame + (timeline_frame - clips[idx].start), + )), + }, + None => Span { + start: timeline_frame, + // The next placement, or the end of the timeline: a gap is + // bounded by what comes after it, never by its own bookkeeping. + len: clips + .iter() + .find(|c| c.start > timeline_frame) + .map_or(total, |c| c.start) + - timeline_frame, + from: None, + }, + }) + } + + /// Every span of `lane` from `timeline_frame` to the end of the timeline, + /// gaps included -- the whole play list, which is what an export walks. + pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec { + let mut out = Vec::new(); + let mut t = timeline_frame; + while let Some(span) = self.span_at(lane, t) { + t = span.end(); + out.push(span); } - None + out } - /// Split the clip containing `timeline_frame` so that frame becomes the - /// first frame of a new clip. Refused (`false`, no change) at timeline 0, - /// at an existing clip boundary, and at or past the end -- all three would - /// produce an empty clip. Metadata only: no mapping changes. - pub fn cut(&mut self, timeline_frame: u32) -> bool { - let Some((idx, source)) = self.map_timeline(timeline_frame) else { + /// Split every lane at `timeline_frame`, so that frame becomes the first + /// frame of a new clip, and hand the two sides two fresh group ids. Refused + /// (`false`, no change) when no lane has a clip to split there -- at a + /// placement's own start, in a gap, and past the end -- all of which would + /// produce an empty clip or nothing at all. + /// + /// Metadata only: no mapping changes, in any lane. + pub fn split(&mut self, timeline_frame: u32) -> bool { + if !self + .lanes + .iter() + .any(|lane| splittable(lane, timeline_frame).is_some()) + { return false; - }; - if source == self.clips[idx].in_frame { - return false; // start of a clip: nothing to split off } - self.history.push(self.clips.clone()); - let out = self.clips[idx].out_frame; - self.clips[idx].out_frame = source; - self.clips.insert( - idx + 1, - Clip { - in_frame: source, - out_frame: out, - ..self.clips[idx] - }, - ); + self.snapshot(); + let (left, right) = (self.new_link(), self.new_link()); + for lane in &mut self.lanes { + let Some(idx) = splittable(lane, timeline_frame) else { + continue; + }; + let mut tail = lane[idx]; + tail.in_frame += timeline_frame - tail.start; + tail.start = timeline_frame; + tail.link = Some(right); + lane[idx].out_frame = tail.in_frame; + lane[idx].link = Some(left); + lane.insert(idx + 1, tail); + } true } - /// Insert `clip` so that it starts at `timeline_frame`. Mid-clip the - /// containing clip is split there and `clip` goes between the halves; at an - /// existing boundary (0 included) it goes in front of the clip that starts - /// there; at or past the end of the timeline it is appended -- a paste past - /// the end clamps rather than refuses, because there is nothing between the - /// end and it. Refused only for an empty `clip`, which the never-empty - /// invariant forbids but the public fields still allow a caller to build. + /// The inverse of [`split`](Project::split): rejoin the placements that meet + /// at `timeline_frame` in every lane and put the result back in one group. + /// Only what a split could have produced is rejoined -- the two sides must + /// touch on the timeline *and* be consecutive frames of the same source -- + /// so the clip list comes back exactly as it was and traversal with it. + /// `false` when no lane has such a pair. + pub fn regroup(&mut self, timeline_frame: u32) -> bool { + if !self + .lanes + .iter() + .any(|lane| joinable(lane, timeline_frame).is_some()) + { + return false; + } + self.snapshot(); + let link = self.new_link(); + for lane in &mut self.lanes { + let Some(idx) = joinable(lane, timeline_frame) else { + continue; + }; + lane[idx].out_frame = lane[idx + 1].out_frame; + lane[idx].link = Some(link); + lane.remove(idx + 1); + } + true + } + + /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it + /// lands on and leaving every other clip exactly where it is -- the + /// per-lane paste. Anything already there is trimmed away (and split in two + /// if `clip` lands inside it), which is what keeps the lane sorted and + /// disjoint; nothing ripples, so a gap before the placement simply stays a + /// gap. Refused only for an empty `clip`. + pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool { + if clip.out_frame <= clip.in_frame { + return false; + } + self.snapshot(); + let clip = Clip { + start: timeline_frame, + ..clip + }; + let lane = &mut self.lanes[lane.index()]; + clear(lane, clip.start, clip.end()); + let idx = lane.partition_point(|c| c.start < clip.start); + lane.insert(idx, clip); + debug_assert!(sorted_disjoint(lane)); + true + } + + /// Insert `clip` into *both* lanes at `timeline_frame` as one new group, + /// pushing everything from there on later by its length -- the grouped, + /// rippling paste a clipboard does. Mid-clip the clip it lands in is split + /// around it; at or past the end of the timeline it is appended, because a + /// paste means "put it here", not "put it here and leave black in front". + /// Use [`place`](Project::place) to paste into one lane, or to make a gap. /// - /// Exactly one history snapshot, so one [`Project::undo`] takes it back -- - /// hence the splice rather than a `cut` plus an insert. Changes the - /// timeline->source mapping: the caller must reseek. + /// Exactly one history snapshot, so one [`Project::undo`] takes it back. + /// Changes the timeline->source mapping: the caller must reseek. Refused + /// only for an empty `clip`, which the never-empty invariant forbids but the + /// public fields still allow a caller to build. pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool { if clip.out_frame <= clip.in_frame { return false; } - self.history.push(self.clips.clone()); - match self.map_timeline(timeline_frame) { - Some((idx, source)) if source > self.clips[idx].in_frame => { - let out = self.clips[idx].out_frame; - self.clips[idx].out_frame = source; - self.clips.splice( - idx + 1..idx + 1, - [ - clip, - Clip { - in_frame: source, - out_frame: out, - ..self.clips[idx] - }, - ], - ); - } - Some((idx, _)) => self.clips.insert(idx, clip), - None => self.clips.push(clip), + self.snapshot(); + let at = timeline_frame.min(self.timeline_frames()); + let clip = Clip { + start: at, + link: Some(self.new_link()), + ..clip + }; + for lane in &mut self.lanes { + open_room(lane, at, clip.len()); + let idx = lane.partition_point(|c| c.start < at); + lane.insert(idx, clip); + debug_assert!(sorted_disjoint(lane)); } true } - /// Remove a clip and close the gap. Refused for an out-of-range index and - /// for the last remaining clip (an empty timeline is undefined this slice). - /// Changes the timeline->source mapping: the caller must reseek. - pub fn delete(&mut self, idx: usize) -> bool { - if idx >= self.clips.len() || self.clips.len() == 1 { + /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or + /// silence, and nothing else moves. Refused for an out-of-range index and + /// for the lift that would leave *both* lanes empty -- an empty timeline is + /// the front-end's state, not a project's (see the never-empty invariant). + pub fn lift(&mut self, lane: Lane, idx: usize) -> bool { + let placed: usize = self.lanes.iter().map(Vec::len).sum(); + if idx >= self.lane(lane).len() || placed == 1 { return false; } - self.history.push(self.clips.clone()); - self.clips.remove(idx); + self.snapshot(); + self.lanes[lane.index()].remove(idx); true } - /// Restore the clip list from before the last successful edit. `false` when + /// Cut the timeline frames `[at, at + len)` out of *every* lane and close + /// the hole: everything after slides back by `len`. The rippling delete -- + /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an + /// empty range and when it would leave both lanes empty. + pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool { + if len == 0 { + return false; + } + let survivors: usize = self + .lanes + .iter() + .map(|lane| { + lane.iter() + .filter(|c| c.start < at || c.end() > at + len) + .count() + }) + .sum(); + if survivors == 0 { + return false; + } + self.snapshot(); + for lane in &mut self.lanes { + clear(lane, at, at + len); + for c in lane.iter_mut().filter(|c| c.start >= at) { + c.start -= len; + } + debug_assert!(sorted_disjoint(lane)); + } + true + } + + /// Remove the video clip at `idx` and everything under it, closing the gap + /// -- the whole-group delete a single-lane front-end means. `false` for a + /// bad index. Changes the mapping: the caller must reseek. + pub fn delete(&mut self, idx: usize) -> bool { + let Some(clip) = self.clips().get(idx).copied() else { + return false; + }; + self.ripple_delete(clip.start, clip.len()) + } + + /// Restore both lanes from before the last successful edit. `false` when /// there is nothing left to undo. pub fn undo(&mut self) -> bool { match self.history.pop() { Some(prev) => { - self.clips = prev; + self.lanes = prev; true } None => false, @@ -273,27 +521,120 @@ impl Project { /// Half-open `(source, start, end)` segments in *source* seconds, from /// `timeline_frame` to the end of the timeline -- the play list for the - /// audio worker. The first entry is partial when the position is mid-clip. - /// Empty when the position is past the end or `fps` is not usable. - pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(usize, f64, f64)> { + /// audio worker, read off the **audio** lane. A `None` source is a gap: the + /// worker synthesises that many seconds of silence, which is what keeps the + /// audio master clock counting across a hole instead of stalling on it. + /// The first entry is partial when the position is mid-clip. Empty when the + /// position is past the end or `fps` is not usable. + pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option, f64, f64)> { if !(fps.is_finite() && fps > 0.0) { return Vec::new(); } - let Some((idx, source)) = self.map_timeline(timeline_frame) else { - return Vec::new(); - }; - let head = self.clips[idx]; - let mut segs = vec![( - head.source, - source as f64 / fps, - head.out_frame as f64 / fps, - )]; - segs.extend( - self.clips[idx + 1..] - .iter() - .map(|c| (c.source, c.in_frame as f64 / fps, c.out_frame as f64 / fps)), - ); - segs + self.spans_from(Lane::Audio, timeline_frame) + .iter() + .map(|span| match span.from { + // A clip's window is in *source* seconds: where in the file it + // reads from, which a delete before it never shifts. + Some((source, in_frame)) => ( + Some(source), + f64::from(in_frame) / fps, + f64::from(in_frame + span.len) / fps, + ), + // A gap has no file, so all it can say is how long it is. + None => (None, 0.0, f64::from(span.len) / fps), + }) + .collect() + } + + /// Pushes the undo snapshot. Every mutating method calls this once, *after* + /// it has decided it will succeed -- a refusal must not cost an undo step. + fn snapshot(&mut self) { + self.history.push(self.lanes.clone()); + } + + fn new_link(&mut self) -> u32 { + self.next_link += 1; + self.next_link - 1 + } +} + +/// Index of the clip covering `frame`, or `None` for a gap or past the end. +/// Binary search: the sorted-disjoint invariant is what makes it legal. +fn at(clips: &[Clip], frame: u32) -> Option { + let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?; + (frame < clips[idx].end()).then_some(idx) +} + +/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split +/// there would cut in two. A placement's own first frame is not inside it. +fn splittable(clips: &[Clip], frame: u32) -> Option { + let idx = at(clips, frame)?; + (frame > clips[idx].start).then_some(idx) +} + +/// Index of the first of the two clips a [`Project::regroup`] at `frame` would +/// rejoin: they must touch there, and be consecutive frames of one source. +fn joinable(clips: &[Clip], frame: u32) -> Option { + let idx = clips.iter().position(|c| c.end() == frame)?; + let next = clips.get(idx + 1)?; + (next.start == frame + && next.source == clips[idx].source + && next.in_frame == clips[idx].out_frame) + .then_some(idx) +} + +/// The lane invariant: sorted by `start`, no two placements overlapping, no +/// empty placement. Checked at every constructor and asserted after every +/// mutation -- the offset model is only tractable while it holds. +fn sorted_disjoint(clips: &[Clip]) -> bool { + clips.iter().all(|c| c.out_frame > c.in_frame) + && clips.windows(2).all(|w| w[0].end() <= w[1].start) +} + +/// Removes the timeline frames `[start, end)` from `clips`: placements inside +/// it go, one straddling it is split in two, one overlapping an edge is +/// trimmed. Source frames follow the trim, so what is left plays what it always +/// played. Leaves the lane sorted and disjoint. +fn clear(clips: &mut Vec, start: u32, end: u32) { + let mut out = Vec::with_capacity(clips.len() + 1); + for c in clips.drain(..) { + // Disjoint from the hole: untouched. + if c.end() <= start || c.start >= end { + out.push(c); + continue; + } + // The head that survives in front of the hole. + if c.start < start { + out.push(Clip { + out_frame: c.in_frame + (start - c.start), + ..c + }); + } + // ...and the tail behind it, which keeps reading where it would have. + if c.end() > end { + out.push(Clip { + start: end, + in_frame: c.in_frame + (end - c.start), + ..c + }); + } + } + *clips = out; +} + +/// Slides everything from `at` on later by `len`, splitting a placement that +/// straddles `at` so the two halves end up on either side of the hole. The +/// insert half of a rippling paste. +fn open_room(clips: &mut Vec, at: u32, len: u32) { + if let Some(idx) = splittable(clips, at) { + let mut tail = clips[idx]; + tail.in_frame += at - tail.start; + tail.start = at; + clips[idx].out_frame = tail.in_frame; + clips.insert(idx + 1, tail); + } + for c in clips.iter_mut().filter(|c| c.start >= at) { + c.start += len; } } @@ -314,41 +655,62 @@ mod tests { const FILE: &str = "/nonexistent/a.mp4"; const FILE2: &str = "/nonexistent/b.mp4"; - /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built - /// through `cut` so the constructor path is exercised too. + /// A contiguous placement, group id ignored: what most assertions compare. + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip { + Clip { + start, + in_frame, + out_frame, + source, + link: None, + } + } + + /// Both lanes with their group ids blanked, for comparing shape. + fn shape(p: &Project) -> [Vec; 2] { + Lane::ALL.map(|l| { + p.lane(l) + .iter() + .map(|c| Clip { link: None, ..*c }) + .collect() + }) + } + + /// The *source frame* every timeline frame reads, per lane -- the traversal + /// a player performs. Deliberately not the clip index: a split changes which + /// clip a frame belongs to, and nothing else. + fn traversal(p: &Project) -> Vec<[Option; 2]> { + (0..p.timeline_frames() + 2) + .map(|f| Lane::ALL.map(|l| p.map(l, f).map(|(_, source)| source))) + .collect() + } + + /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one + /// fixture. Built through `split` so the constructor path is exercised too. fn three() -> Project { let mut p = Project::single(FILE, 9); - assert!(p.cut(3)); - assert!(p.cut(5)); + assert!(p.split(3)); + assert!(p.split(5)); assert_eq!( - p.clips(), + shape(&p), [ - Clip { - source: 0, - in_frame: 0, - out_frame: 3 - }, - Clip { - source: 0, - in_frame: 3, - out_frame: 5 - }, - Clip { - source: 0, - in_frame: 5, - out_frame: 9 - }, + vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)], + vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)], ] ); p } #[test] - fn single_is_the_whole_file() { + fn single_is_the_whole_file_on_both_lanes() { let p = Project::single(FILE, 150); assert_eq!(p.clips().len(), 1); + assert_eq!(p.lane(Lane::Audio).len(), 1); assert_eq!(p.timeline_frames(), 150); assert_eq!(p.clip_spans(), vec![(0, 150)]); + // grouped: video and audio carry the same link + assert_eq!(p.clips()[0].link, p.lane(Lane::Audio)[0].link); + assert!(p.clips()[0].link.is_some()); // degenerate mapping: timeline == source assert_eq!(p.map_timeline(0), Some((0, 0))); assert_eq!(p.map_timeline(149), Some((0, 149))); @@ -358,54 +720,77 @@ mod tests { } #[test] - fn cut_mid_clip_splits() { + fn split_cuts_every_lane_and_regroups_it_back() { let mut p = Project::single(FILE, 9); - assert!(p.cut(4)); + let before = traversal(&p); + let before_shape = shape(&p); + + assert!(p.split(4)); + for l in Lane::ALL { + assert_eq!(p.lane(l).len(), 2, "{l:?} split"); + } + // The two sides are two groups, one per side, matching across the lanes. + let (v, a) = (p.lane(Lane::Video), p.lane(Lane::Audio)); + assert_eq!(v[0].link, a[0].link); + assert_eq!(v[1].link, a[1].link); + assert_ne!(v[0].link, v[1].link, "the halves are no longer one take"); + // A split changes no mapping, in either lane. + assert_eq!(traversal(&p), before, "a split moves nothing"); + + assert!(p.regroup(4), "the inverse rejoins them"); + assert_eq!(shape(&p), before_shape, "bit-exact back to one clip"); + assert_eq!(traversal(&p), before); assert_eq!( - p.clips(), - [ - Clip { - source: 0, - in_frame: 0, - out_frame: 4 - }, - Clip { - source: 0, - in_frame: 4, - out_frame: 9 - }, - ] + p.lane(Lane::Video)[0].link, + p.lane(Lane::Audio)[0].link, + "and the rejoined clip is one group again" ); - assert_eq!(p.timeline_frames(), 9); } #[test] - fn cut_refused_at_zero_boundary_and_end() { + fn split_refused_at_zero_boundary_end_and_in_a_gap() { let mut p = three(); - let before = p.clips().to_vec(); - assert!(!p.cut(0), "timeline 0 has nothing before it"); - assert!(!p.cut(3), "existing boundary"); - assert!(!p.cut(5), "existing boundary"); - assert!(!p.cut(9), "one past the last frame"); - assert!(!p.cut(1_000)); - assert_eq!(p.clips(), before.as_slice()); - // one undo lands before the *second* cut, so the refusals pushed nothing + let before = shape(&p); + assert!(!p.split(0), "timeline 0 has nothing before it"); + assert!(!p.split(3), "existing boundary"); + assert!(!p.split(5), "existing boundary"); + assert!(!p.split(9), "one past the last frame"); + assert!(!p.split(1_000)); + assert_eq!(shape(&p), before); + // one undo lands before the *second* split, so the refusals pushed nothing assert!(p.undo()); - assert_eq!(p.clips().len(), 2, "refused cuts push no history"); + assert_eq!(p.clips().len(), 2, "refused splits push no history"); + + // ...and a frame that is a gap in both lanes has nothing to split. + let mut p = three(); + assert!(p.lift(Lane::Video, 1)); + assert!(p.lift(Lane::Audio, 1)); + assert!(!p.split(4), "a gap is not a clip"); } #[test] - fn cut_never_changes_the_mapping() { - let p = three(); - let before: Vec<_> = (0..9).map(|f| p.map_timeline(f).unwrap().1).collect(); - let mut after = p.clone(); - assert!(after.cut(7)); - let now: Vec<_> = (0..9).map(|f| after.map_timeline(f).unwrap().1).collect(); - assert_eq!(before, now); + fn regroup_refuses_what_a_split_could_not_have_made() { + let mut p = three(); + // [3,5) and [5,9) are source-contiguous: that pair rejoins. + assert!(p.regroup(5)); + assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]); + // A boundary with a gap on one side, and one where the sources do not + // meet, are both refused. + let mut p = three(); + assert!(p.lift(Lane::Video, 1)); + assert!(p.lift(Lane::Audio, 1)); + assert!(!p.regroup(3), "nothing starts at 3 any more"); + let mut p = three(); + for l in Lane::ALL { + assert!(p.place(l, 3, clip(0, 100, 102, 0))); + } + assert!(!p.regroup(3), "source 100 does not follow source 3"); + assert!(!p.regroup(0), "nothing ends at 0"); + assert!(!p.regroup(1_000)); } #[test] - fn map_timeline_sweeps_every_boundary() { + fn map_and_spans_sweep_every_boundary() { let p = three(); assert_eq!(p.timeline_frames(), 9); assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]); @@ -425,14 +810,26 @@ mod tests { assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}"); } assert_eq!(p.map_timeline(9), None); + // A span is the rest of the clip from where it was asked about. + assert_eq!( + p.span_at(Lane::Video, 6), + Some(Span { + start: 6, + len: 3, + from: Some((0, 6)) + }) + ); + assert_eq!(p.span_at(Lane::Video, 9), None); } /// The clip a copy would hand back: source `[100, 102)`, unrelated to /// anything in `three()` so it is recognisable wherever it lands. const PASTED: Clip = Clip { - source: 0, + start: 0, in_frame: 100, out_frame: 102, + source: 0, + link: None, }; #[test] @@ -441,31 +838,16 @@ mod tests { assert!(p.paste(6, PASTED)); // inside [5,9), one frame in assert_eq!(p.timeline_frames(), 11); assert_eq!( - p.clips(), - [ - Clip { - source: 0, - in_frame: 0, - out_frame: 3 - }, - Clip { - source: 0, - in_frame: 3, - out_frame: 5 - }, - Clip { - source: 0, - in_frame: 5, - out_frame: 6 - }, - PASTED, - Clip { - source: 0, - in_frame: 6, - out_frame: 9 - }, + shape(&p)[0], + vec![ + clip(0, 0, 3, 0), + clip(3, 3, 5, 0), + clip(5, 5, 6, 0), + clip(6, 100, 102, 0), + clip(8, 6, 9, 0), ] ); + assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes"); // The pasted frames are exactly where they were asked for, and the // split-off remainder resumes after them. assert_eq!(p.map_timeline(6), Some((3, 100))); @@ -485,7 +867,8 @@ mod tests { assert_eq!(p.map_timeline(0), Some((0, 100))); assert_eq!(p.map_timeline(2), Some((1, 0))); - // At the end and past it both append -- there is nothing to sit before. + // At the end and past it both append -- a paste never leaves black in + // front of itself; `place` is the call that makes a gap. let mut p = three(); assert!(p.paste(9, PASTED)); assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]); @@ -494,24 +877,17 @@ mod tests { // An empty clip is the one thing refused, and it pushes no history. let mut p = three(); - assert!(!p.paste( - 4, - Clip { - source: 0, - in_frame: 7, - out_frame: 7 - } - )); + assert!(!p.paste(4, clip(0, 7, 7, 0))); assert_eq!(p.clips().len(), 3); } #[test] fn paste_undoes_in_one_step() { let mut p = three(); - let before = p.clips().to_vec(); + let before = shape(&p); assert!(p.paste(6, PASTED)); assert!(p.undo()); - assert_eq!(p.clips(), before.as_slice(), "a paste is one undo step"); + assert_eq!(shape(&p), before, "a paste is one undo step"); } #[test] @@ -526,11 +902,12 @@ mod tests { } #[test] - fn delete_closes_the_gap() { + fn delete_closes_the_gap_on_both_lanes() { let mut p = three(); assert!(p.delete(1)); assert_eq!(p.timeline_frames(), 7); assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]); + assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 4)]); // timeline 3 used to be source 3; the gap closed so it is source 5 now assert_eq!(p.map_timeline(3), Some((1, 5))); assert_eq!(p.map_timeline(6), Some((1, 8))); @@ -555,60 +932,201 @@ mod tests { assert_eq!(p.clips().len(), 1); } + /// The offset model's point: one lane loses a clip, the other does not move. + #[test] + fn a_lift_leaves_a_gap_and_moves_nothing() { + let mut p = three(); + let video_before = shape(&p)[0].clone(); + assert!(p.lift(Lane::Audio, 1)); + assert_eq!(shape(&p)[0], video_before, "the picture never moved"); + assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter"); + assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (5, 4)]); + // The hole is a gap: mapped as nothing, spanned as a gap of its length. + assert_eq!(p.map(Lane::Audio, 4), None); + assert_eq!( + p.span_at(Lane::Audio, 3), + Some(Span { + start: 3, + len: 2, + from: None + }) + ); + assert_eq!(p.map(Lane::Video, 4), Some((1, 4)), "video plays on"); + assert!(p.undo()); + assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 2), (5, 4)]); + } + + #[test] + fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() { + let mut p = three(); + assert!(p.lift(Lane::Audio, 2)); + assert_eq!(p.timeline_frames(), 9, "video still runs to 9"); + assert_eq!( + p.span_at(Lane::Audio, 5), + Some(Span { + start: 5, + len: 4, + from: None + }), + "the audio lane holds silence to the end of the picture" + ); + assert_eq!(p.span_at(Lane::Audio, 9), None); + // Every lane covers the timeline exactly, gaps included. + for l in Lane::ALL { + let spans = p.spans_from(l, 0); + assert_eq!(spans.iter().map(|s| s.len).sum::(), 9, "{l:?}"); + assert_eq!(spans[0].start, 0); + } + } + + #[test] + fn the_last_clip_of_the_last_lane_cannot_be_lifted() { + let mut p = Project::single(FILE, 9); + assert!(p.lift(Lane::Audio, 0), "a silent timeline is fine"); + assert!(!p.lift(Lane::Video, 0), "an empty one is not"); + assert!(!p.lift(Lane::Audio, 0), "index past the end"); + assert_eq!(p.timeline_frames(), 9); + } + + #[test] + fn place_overwrites_only_its_own_lane() { + let mut p = three(); + let audio_before = shape(&p)[1].clone(); + // Straddles [3,5) and eats into [5,9): the first is trimmed, the second + // is trimmed, nothing shifts. + assert!(p.place(Lane::Video, 4, clip(0, 100, 102, 0))); + assert_eq!( + shape(&p)[0], + vec![ + clip(0, 0, 3, 0), + clip(3, 3, 4, 0), + clip(4, 100, 102, 0), + clip(6, 6, 9, 0), + ] + ); + assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched"); + assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert"); + + // Placed inside one clip, it splits it in two. + let mut p = Project::single(FILE, 9); + assert!(p.place(Lane::Video, 4, clip(0, 100, 101, 0))); + assert_eq!( + shape(&p)[0], + vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)] + ); + // ...and placed past the end it makes a gap, which is the whole point. + assert!(p.place(Lane::Video, 20, clip(0, 100, 102, 0))); + assert_eq!(p.timeline_frames(), 22); + assert_eq!( + p.span_at(Lane::Video, 9), + Some(Span { + start: 9, + len: 11, + from: None + }) + ); + assert!(!p.place(Lane::Video, 0, clip(0, 7, 7, 0)), "empty clip"); + } + + #[test] + fn ripple_delete_spans_partial_clips() { + let mut p = three(); + // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2. + assert!(p.ripple_delete(2, 4)); + assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]); + assert_eq!(shape(&p)[1], shape(&p)[0]); + assert_eq!(p.timeline_frames(), 5); + assert!(!p.ripple_delete(0, 0), "an empty range is not a delete"); + assert!(!p.ripple_delete(0, 100), "and one that empties every lane"); + assert!(p.undo()); + assert_eq!(shape(&p), shape(&three())); + } + #[test] fn undo_restores_exactly() { let mut p = three(); - let after_cuts = p.clips().to_vec(); + let after_splits = shape(&p); assert!(p.delete(1)); assert!(p.undo()); - assert_eq!(p.clips(), after_cuts.as_slice()); + assert_eq!(shape(&p), after_splits); - // walk all the way back through both cuts, then run dry + // walk all the way back through both splits, then run dry assert!(p.undo()); assert_eq!(p.clips().len(), 2); assert!(p.undo()); - assert_eq!( - p.clips(), - [Clip { - source: 0, - in_frame: 0, - out_frame: 9 - }] - ); + assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); assert!(!p.undo(), "empty history"); - assert_eq!( - p.clips(), - [Clip { - source: 0, - in_frame: 0, - out_frame: 9 - }] - ); + assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]); } + /// Undo/redo by hand across a split must never merge two takes into one + /// group by reusing an id. #[test] - fn segments_from_trims_the_first_entry() { + fn group_ids_are_never_reused() { + let mut p = Project::single(FILE, 9); + assert!(p.split(3)); + let first = p.clips()[1].link; + assert!(p.undo()); + assert!(p.split(5)); + assert_ne!(p.clips()[1].link, first, "a retired id must not come back"); + } + + #[test] + fn segments_from_reads_the_audio_lane() { let p = three(); // mid-clip: partial first segment, whole clips after it assert_eq!( p.segments_from(4, FPS), - vec![(0, 4.0 / 30.0, 5.0 / 30.0), (0, 5.0 / 30.0, 9.0 / 30.0)] + vec![ + (Some(0), 4.0 / 30.0, 5.0 / 30.0), + (Some(0), 5.0 / 30.0, 9.0 / 30.0) + ] ); // on a boundary: nothing partial assert_eq!( p.segments_from(3, FPS), - vec![(0, 3.0 / 30.0, 5.0 / 30.0), (0, 5.0 / 30.0, 9.0 / 30.0)] + vec![ + (Some(0), 3.0 / 30.0, 5.0 / 30.0), + (Some(0), 5.0 / 30.0, 9.0 / 30.0) + ] ); // from the top: one entry per clip assert_eq!(p.segments_from(0, FPS).len(), 3); // last clip only - assert_eq!(p.segments_from(8, FPS), vec![(0, 8.0 / 30.0, 0.3)]); + assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]); // past the end / unusable fps assert!(p.segments_from(9, FPS).is_empty()); assert!(p.segments_from(0, 0.0).is_empty()); assert!(p.segments_from(0, f64::NAN).is_empty()); } + #[test] + fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() { + let mut p = three(); + assert!(p.lift(Lane::Audio, 1)); // silence over timeline [3, 5) + assert_eq!( + p.segments_from(0, FPS), + vec![ + (Some(0), 0.0, 3.0 / 30.0), + (None, 0.0, 2.0 / 30.0), + (Some(0), 5.0 / 30.0, 9.0 / 30.0), + ] + ); + // The list still covers exactly the timeline: that is what stops the + // master clock stalling at the hole. + let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); + assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}"); + // Starting inside the gap trims the silence, not the clip after it. + assert_eq!( + p.segments_from(4, FPS), + vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)] + ); + // ...and a lane that is nothing but gap is a run of silence. + assert!(p.lift(Lane::Audio, 0)); + assert!(p.lift(Lane::Audio, 0)); + assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]); + } + /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9) /// of source 0 then [0,4) of source 1. fn two_sources() -> Project { @@ -643,17 +1161,11 @@ mod tests { fn append_clip_is_one_undo_step() { let mut p = two_sources(); assert_eq!(p.timeline_frames(), 13); - assert_eq!( - p.clips()[3], - Clip { - in_frame: 0, - out_frame: 4, - source: 1 - } - ); + assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1)); + assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane"); assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9"); assert!(p.undo()); - assert_eq!(p.clips(), three().clips(), "one step back to one source"); + assert_eq!(shape(&p), shape(&three()), "one step back to one source"); assert_eq!( p.sources().len(), 2, @@ -667,30 +1179,17 @@ mod tests { #[test] fn edits_carry_the_source_along() { let mut p = two_sources(); - // A cut inside the second source splits into two source-1 clips. - assert!(p.cut(11)); - assert_eq!( - p.clips()[3], - Clip { - in_frame: 0, - out_frame: 2, - source: 1 - } - ); - assert_eq!( - p.clips()[4], - Clip { - in_frame: 2, - out_frame: 4, - source: 1 - } - ); + // A split inside the second source splits into two source-1 clips. + assert!(p.split(11)); + assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1)); + assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1)); // A source-1 clip pasted into source-0 territory keeps its file, and so // does the source-0 half that got split off around it. let copied = p.clips()[4]; assert!(p.paste(1, copied)); - assert_eq!(p.clips()[1], copied); + assert_eq!(p.clips()[1].source, 1); + assert_eq!(p.clips()[1].in_frame, 2); assert_eq!(p.clips()[2].source, 0); assert!(p.undo()); assert_eq!(p.clips()[1].source, 0, "undo restores sources too"); @@ -703,13 +1202,16 @@ mod tests { assert_eq!( p.segments_from(4, FPS), vec![ - (0, 4.0 / 30.0, 5.0 / 30.0), - (0, 5.0 / 30.0, 9.0 / 30.0), - (1, 0.0, 4.0 / 30.0), + (Some(0), 4.0 / 30.0, 5.0 / 30.0), + (Some(0), 5.0 / 30.0, 9.0 / 30.0), + (Some(1), 0.0, 4.0 / 30.0), ] ); // Mid-clip in source 1: only that source is left. - assert_eq!(p.segments_from(10, FPS), vec![(1, 1.0 / 30.0, 4.0 / 30.0)]); + assert_eq!( + p.segments_from(10, FPS), + vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)] + ); assert!(p.segments_from(13, FPS).is_empty()); // Segments still cover exactly the timeline across the join. let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); @@ -722,7 +1224,10 @@ mod tests { assert!(p.delete(0)); // source seconds, not timeline: deleting the head does not shift them let segs = p.segments_from(0, 25.0); - assert_eq!(segs, vec![(0, 3.0 / 25.0, 0.2), (0, 0.2, 9.0 / 25.0)]); + assert_eq!( + segs, + vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)] + ); let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum(); assert!( (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, @@ -735,9 +1240,10 @@ mod tests { // Import a second file, undo it: source 1 is now an orphan. let mut p = two_sources(); assert!(p.undo()); - let (sources, clips) = p.without_orphan_sources(); + let (sources, video, audio) = p.without_orphan_sources(); assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone"); - assert_eq!(clips, three().clips(), "the clips are untouched"); + assert_eq!(video, three().clips(), "the clips are untouched"); + assert_eq!(audio, three().lane(Lane::Audio)); // Three sources where only the middle one is orphaned: the survivors // renumber, and the clips follow. @@ -745,51 +1251,47 @@ mod tests { assert_eq!(p.import(FILE2), 1); assert_eq!(p.import("/nonexistent/c.mp4"), 2); assert!(p.append_clip(2, 4)); - let (sources, clips) = p.without_orphan_sources(); + let (sources, video, audio) = p.without_orphan_sources(); assert_eq!( sources, vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")] ); - assert_eq!(clips.iter().map(|c| c.source).collect::>(), [0, 1]); + assert_eq!(video.iter().map(|c| c.source).collect::>(), [0, 1]); // ...and what comes out is loadable, with the same timeline. - let reloaded = Project::from_parts(sources, clips).expect("from_parts"); + let reloaded = Project::from_parts(sources, video, audio).expect("from_parts"); assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); assert_eq!(reloaded.sources().len(), 2); } #[test] fn from_parts_has_no_history_and_checks_the_invariants() { - let (sources, clips) = three().without_orphan_sources(); - let mut p = Project::from_parts(sources.clone(), clips.clone()).expect("valid parts"); + let (sources, video, audio) = three().without_orphan_sources(); + let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone()) + .expect("valid parts"); assert_eq!(p.clips(), three().clips()); assert!(!p.undo(), "a loaded project has nothing to undo"); - assert!(p.cut(4), "...and is editable from there"); + assert!(p.split(4), "...and is editable from there"); assert!(p.undo()); - assert!(Project::from_parts(sources.clone(), Vec::new()).is_none()); - assert!( - Project::from_parts( - sources.clone(), - vec![Clip { - source: 1, - in_frame: 0, - out_frame: 3 - }] - ) - .is_none(), - "clip names a source that is not there" - ); - assert!( - Project::from_parts( - sources, - vec![Clip { - source: 0, - in_frame: 3, - out_frame: 3 - }] - ) - .is_none(), - "empty clip" - ); + // A lane may be empty; both may not. + assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_some()); + assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_none()); + let bad: [Vec; 4] = [ + vec![clip(0, 0, 3, 1)], // source that is not there + vec![clip(0, 3, 3, 0)], // empty clip + vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order + vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping + ]; + for clips in bad { + assert!( + Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_none(), + "{clips:?}" + ); + assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_none()); + } + // Group ids survive a load, and the next split gets a fresh one. + let mut p = Project::from_parts(sources, video, audio).expect("valid parts"); + assert!(p.split(4)); + assert!(p.clips().iter().all(|c| c.link.is_some())); } } diff --git a/crates/engine/tests/audio_multi.rs b/crates/engine/tests/audio_multi.rs index dfb37a2..fa9221b 100644 --- a/crates/engine/tests/audio_multi.rs +++ b/crates/engine/tests/audio_multi.rs @@ -30,6 +30,12 @@ fn sources() -> Vec { /// Drains a session flat, asserting chunks are contiguous, and reports the /// first chunk's `start_sample` plus how many chunks arrived. +/// Every segment names a source: these tests are about joins between files, +/// not about gaps (which name none). +fn named(segs: &[(usize, f64, f64)]) -> Vec<(Option, f64, f64)> { + segs.iter().map(|&(s, a, b)| (Some(s), a, b)).collect() +} + fn drain(rx: Receiver) -> (Vec, u64, usize) { let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize); for AudioChunk { @@ -48,7 +54,8 @@ fn drain(rx: Receiver) -> (Vec, u64, usize) { } fn multi(segs: &[(usize, f64, f64)]) -> (Vec, u64, usize) { - let (_, rx) = AudioSession::open_multi_segments(&sources(), segs) + let segs = named(segs); + let (_, rx) = AudioSession::open_multi_segments(&sources(), &segs) .expect("open") .expect("the first source has an audio track"); drain(rx) @@ -128,7 +135,7 @@ fn assert_same_bytes(got: &[AacPacket], want: &[Vec], what: &str) { } fn copy(segs: &[(usize, f64, f64)]) -> Vec { - AudioSession::copy_multi_segments(&sources(), segs) + AudioSession::copy_multi_segments(&sources(), &named(segs)) .expect("copy") .expect("the first source has an audio track") .1 @@ -246,7 +253,7 @@ fn a_source_without_the_timeline_audio_is_refused() { // the copy and the decode paths refuse them again rather than mislabel one // esds for two different tracks. let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; - let segs = [(0, 0.0, 1.0), (1, 0.0, 1.0)]; + let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) for e in [ AudioSession::copy_multi_segments(&mixed, &segs).err(), @@ -258,6 +265,6 @@ fn a_source_without_the_timeline_audio_is_refused() { assert!(msg.contains("source 1"), "{msg}"); } // An out-of-range index is an error, not a panic. - assert!(AudioSession::copy_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); - assert!(AudioSession::open_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); + assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); + assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); } diff --git a/crates/engine/tests/audio_segments.rs b/crates/engine/tests/audio_segments.rs index 19d2fd5..08a7e72 100644 --- a/crates/engine/tests/audio_segments.rs +++ b/crates/engine/tests/audio_segments.rs @@ -134,3 +134,114 @@ fn no_segments_ends_clean() { "an empty edit list decodes nothing" ); } + +/// A segment naming no source is a gap, and a gap is *synthesised silence* in +/// the same stream -- real chunks, contiguous with the audible ones (`drain` +/// asserts that), so the master clock keeps counting through the hole instead +/// of stalling on it. +#[test] +fn a_gap_segment_is_silence_of_its_own_length() { + let sources = [asset()]; + let segs = [ + (Some(0), 0.0, 0.5), + (None, 0.0, 1.0), // one second of hole + (Some(0), 2.0, 2.5), + ]; + let (_, rx) = AudioSession::open_multi_segments(&sources, &segs) + .expect("open") + .expect("test_av.mp4 has an audio track"); + let (samples, first, _) = drain(rx); + assert_eq!(first, 0, "the run still starts at audible zero"); + + let frames = samples.len() as u64 / CHANNELS as u64; + let want = 2 * RATE / 2 + RATE; + assert!( + frames.abs_diff(want) <= PACKET, + "{frames} frames for {want} asked for: a gap must cost exactly its length" + ); + // The hole itself is digital silence, and what surrounds it is not. + let hole = (RATE / 2) as usize * CHANNELS..(RATE / 2 + RATE) as usize * CHANNELS; + assert!( + samples[hole.clone()].iter().all(|s| *s == 0.0), + "the gap must be silent" + ); + assert!( + samples[..hole.start].iter().any(|s| s.abs() > 1e-3) + && samples[hole.end..].iter().any(|s| s.abs() > 1e-3), + "the clips around it must not be" + ); + + // Nothing but gap is a valid run of silence; the meta still comes from the + // source, because that is what the device was opened with. + let (meta, rx) = AudioSession::open_multi_segments(&sources, &[(None, 0.0, 0.25)]) + .expect("open") + .expect("meta comes from source 0 even with nothing to decode"); + assert_eq!(meta.sample_rate as u64, RATE); + let (samples, _, _) = drain(rx); + assert!(samples.iter().all(|s| *s == 0.0)); + assert!( + (samples.len() as u64 / CHANNELS as u64).abs_diff(RATE / 4) <= PACKET, + "quarter second of silence" + ); +} + +/// The copy side of a gap: there is no AAC encoder here to make silence with, +/// so the hole is spent as *duration* on the packet in front of it. Every +/// packet after the gap therefore still lands at its timeline position. +#[test] +fn a_copied_gap_becomes_the_duration_of_the_packet_before_it() { + let sources = [asset()]; + let plain = [(Some(0), 0.0, 1.0), (Some(0), 2.0, 3.0)]; + let gapped = [(Some(0), 0.0, 1.0), (None, 0.0, 1.0), (Some(0), 2.0, 3.0)]; + + let (_, without) = AudioSession::copy_multi_segments(&sources, &plain) + .unwrap() + .unwrap(); + let (_, with) = AudioSession::copy_multi_segments(&sources, &gapped) + .unwrap() + .unwrap(); + assert_eq!( + with.len(), + without.len(), + "a gap copies no packets: there is nothing in it" + ); + let total = |p: &[engine::AacPacket]| p.iter().map(|p| u64::from(p.samples)).sum::(); + assert_eq!( + total(&with) - total(&without), + RATE, + "...it costs exactly its own second of stts duration" + ); + // Exactly one packet grew, and it is an interior one -- the last before + // the hole -- so every packet after the hole is pushed to where the + // timeline wants it rather than the whole tail drifting early. + let grown: Vec = with + .iter() + .zip(&without) + .enumerate() + .filter(|(_, (a, b))| a.samples != b.samples) + .map(|(i, _)| i) + .collect(); + assert_eq!(grown.len(), 1, "one packet carries the whole gap"); + assert!( + grown[0] > 0 && grown[0] < with.len() - 1, + "the gap rides on an interior packet, at {} of {}", + grown[0], + with.len() + ); + assert!( + with.iter().zip(&without).all(|(a, b)| a.bytes == b.bytes), + "and not one byte of audio moved" + ); + + // A gap at the *head* has no packet before it: the first one picks it up + // (the documented ponytail), so nothing but that packet is misplaced. + let (_, leading) = + AudioSession::copy_multi_segments(&sources, &[(None, 0.0, 0.5), (Some(0), 0.0, 1.0)]) + .unwrap() + .unwrap(); + assert_eq!( + u64::from(leading[0].samples), + 1024 + RATE / 2, + "the head gap rides on the first packet" + ); +} diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 164adff..1281078 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -22,6 +22,7 @@ use std::time::{Duration, Instant}; use engine::export::ExportSettings; use engine::hw::HwEncoder; use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; +use engine::project::Lane; use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; const FPS: f64 = 30.0; @@ -183,7 +184,7 @@ fn two_sources() -> Project { let second = project.import(asset("test_av2.mp4")); assert_eq!(second, 1, "a second file is a second source"); assert!(project.append_clip(second, av2.frame_count)); - assert!(project.cut(120), "cut a second before the end of test_av"); + assert!(project.split(120), "cut a second before the end of test_av"); assert!(project.delete(1), "drop test_av's tail"); assert_eq!(project.timeline_frames(), 120 + av2.frame_count); assert_eq!( @@ -318,11 +319,11 @@ fn a_vanished_source_fails_the_export() { // Five frames of each: the export has to get going and then fail. let mut project = Project::single(&baseline, meta.frame_count); - assert!(project.cut(5)); + assert!(project.split(5)); assert!(project.delete(1)); let second = project.import(&doomed); assert!(project.append_clip(second, meta.frame_count)); - assert!(project.cut(10)); + assert!(project.split(10)); assert!(project.delete(2)); assert_eq!(project.timeline_frames(), 10); @@ -548,3 +549,74 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec< vec![192u8.wrapping_sub(index as u8); cw * ch], ) } + +/// A timeline with a hole in each lane, exported. The video gap is encoded as +/// black rather than skipped -- the file is as long as the timeline, frame for +/// frame -- and the audio gap is spent as sample-table duration, so the audio +/// track still covers the whole timeline inside the bresenham bound instead of +/// ending a second early. +#[test] +fn exports_a_gapped_timeline_as_black_and_silence() { + pin_software(); + let source = asset("test_av.mp4"); + let mut session = PlaybackSession::open(&source).expect("open source"); + assert!(session.cut_at(1.0), "split at 1 s"); + assert!(session.cut_at(2.0), "split at 2 s"); + // Lift the middle out of *both* lanes: one second of black and silence in + // the middle of a five-second timeline, with the length unchanged. + assert!(session.lift_clip(Lane::Video, 1)); + assert!(session.lift_clip(Lane::Audio, 1)); + session.pause(); + let timeline = session.timeline_duration(); + let frames = (timeline * FPS).round() as u32; + let out = out_path("gapped"); + + let handle = session.export_to(&out); + wait(&handle, Duration::from_secs(180)).expect("export"); + + // Every frame is there, and the ones over the hole are black. + let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); + assert_eq!( + video.frame_count, frames, + "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline", + video.frame_count + ); + let pictures = decode_all(&out); + assert_eq!(pictures.len() as u32, frames); + let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize); + // Encoded black, so not bit-exact: a mean absolute distance from true black + // well under one code value per channel is what "black" can mean here. + let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4); + for (i, picture) in pictures.iter().enumerate() { + let diff = mean_abs_diff(picture, &black); + if (hole..hole_end).contains(&i) { + assert!( + diff < 4.0, + "frame {i} of the gap is not black (MAE {diff:.2})" + ); + } + } + let lit = mean_abs_diff(&pictures[0], &black); + assert!(lit > 4.0, "the clips around the gap came out black too"); + + // The audio track still spans the whole timeline: the gap paid its way in + // stts duration, so nothing after it moved earlier. + let file = File::open(&out).unwrap(); + let size = file.metadata().unwrap().len(); + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + let track = &reader.tracks()[&2]; + let duration = track.duration().as_secs_f64(); + println!("gapped export: audio track {duration:.3}s for a {timeline:.3}s timeline"); + assert!( + (duration - timeline).abs() < 3.0 * 1024.0 / 44_100.0, + "audio track is {duration:.3}s, timeline {timeline:.3}s" + ); + // ...and the packets themselves cover only the audible four seconds, within + // the same half-packet-per-join bound the copier promises. + let packets = f64::from(reader.sample_count(2).expect("audio track") * 1024); + let audible = (timeline - 1.0) * 44_100.0; + assert!( + (packets - audible).abs() < 3.0 * 1024.0, + "{packets} samples copied for {audible} audible ones" + ); +} diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index df89873..154dbdb 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -11,6 +11,7 @@ use std::path::{Path, PathBuf}; use std::thread::sleep; use std::time::{Duration, Instant}; +use engine::project::Lane; use engine::{DecodeSession, Frame, PlaybackSession}; fn asset(name: &str) -> PathBuf { @@ -903,3 +904,99 @@ fn audio_runs_across_a_source_join() { // real time, so the decoder may well have reached 9 s while the clock is at // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none). } + +/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap* +/// rather than closing up, and a gap plays: the timeline keeps its length, the +/// frame numbering stays contiguous straight through, and every picture over +/// the hole is black. No audio needed, so this runs anywhere. +#[test] +fn a_video_gap_plays_black_without_shortening_the_timeline() { + let path = asset("test_baseline.mp4"); + let mut session = PlaybackSession::open(&path).expect("open"); + let (fps, total) = (session.meta().frame_rate, session.meta().frame_count); + let whole = session.timeline_duration(); + + assert!(session.cut_at(2.0), "split at 2 s"); + assert!(session.cut_at(3.5), "split at 3.5 s"); + assert!( + session.lift_clip(Lane::Video, 1), + "lift the middle picture out" + ); + assert_eq!( + session.clip_spans().len(), + 2, + "two placements, and a hole between them" + ); + assert!( + (session.timeline_duration() - whole).abs() < 1e-9, + "a lift leaves a gap: the timeline is exactly as long as it was" + ); + + let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32); + session.seek(0.0); + session.play(); + let deadline = Instant::now() + Duration::from_secs(20); + let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32); + loop { + session.tick(); + while let Some(frame) = session.try_frame() { + assert_eq!(frame.index, expect, "timeline indices must be contiguous"); + let is_black = frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]); + if (hole..hole_end).contains(&frame.index) { + assert!(is_black, "frame {} is inside the gap", frame.index); + black += 1; + } else { + lit += 1; + } + expect += 1; + } + if session.is_eos() { + break; + } + assert!(Instant::now() < deadline, "still draining after 20 s"); + sleep(Duration::from_millis(4)); + } + assert_eq!(expect, total, "the whole timeline, gap included"); + assert_eq!(black, hole_end - hole, "every frame of the hole was black"); + assert!(lit > 0, "and the clips around it still decoded"); + + // The gap is one undo step back to the clip that was there. + assert!(session.undo()); + assert_eq!(session.clip_spans().len(), 3); +} + +/// A hole in the *audio* lane, with the device running: the master clock counts +/// samples the device has been fed, so silence has to be fed as real chunks or +/// the timeline would stall on the hole. Needs a PipeWire daemon and the output +/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`). +#[test] +#[ignore = "needs a running PipeWire daemon"] +fn an_audio_gap_is_silent_and_the_clock_keeps_counting() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + assert!(session.cut_at(1.0), "split at 1 s"); + assert!(session.cut_at(2.0), "split at 2 s"); + // Silence over [1, 2) s while the picture plays on -- the two lanes part. + assert!( + session.lift_clip(Lane::Audio, 1), + "lift the middle sound out" + ); + assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched"); + let duration = session.timeline_duration(); + + session.seek(0.0); + let mut last_index = None; + session.play(); + // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at + // 1 s, so a stall anywhere inside it cannot hide. + run_for(&mut session, &mut last_index, Duration::from_millis(2_400)); + let now = session.now(); + assert!( + now > 2.2 && now < duration, + "the clock stalled on the audio gap at {now:.3}s" + ); + assert!( + last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true), + "pictures stopped over the silence: {last_index:?}" + ); + eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}"); +} diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index ce5ba9d..55ce569 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -56,6 +56,61 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec, f6 ) } +/// The version-1 promise: a file written before the lanes existed still opens, +/// as one grouped video+audio pair per clip laid end to end, and saving it +/// again writes version 2 -- which reopens as the same timeline. +#[test] +fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() { + let dir = scratch("v1"); + copy_in(&dir, "test_av.mp4"); + let path = dir.join("old.edith"); + // 60 frames of picture from two clips: [0,30) then [60,90) of the source. + std::fs::write( + &path, + "edith 1\nplayhead 45\nsource test_av.mp4\nclip 0 30 0\nclip 60 90 0\n", + ) + .expect("write a v1 file"); + + let loaded = PlaybackSession::open_project(&path).expect("a v1 file still opens"); + let fps = loaded.meta().frame_rate; + assert_eq!( + loaded.clip_spans_by_source(), + vec![(0.0, 30.0 / fps, 0), (30.0 / fps, 30.0 / fps, 0)], + "v1 clips queue up, the second starting where the first ended" + ); + assert_eq!( + loaded.lane_spans_by_source(engine::project::Lane::Audio), + loaded.clip_spans_by_source(), + "both lanes, fully grouped: a v1 timeline had no holes" + ); + assert!( + (loaded.now() - 45.0 / fps).abs() < 1.0 / fps, + "playhead kept" + ); + + // Saved again it is v2, and v2 round-trips to the same timeline. + let v2 = dir.join("new.edith"); + loaded.save_project(&v2).expect("save"); + let text = std::fs::read_to_string(&v2).expect("read back"); + assert!(text.starts_with("edith 2\n"), "{text}"); + assert_eq!( + text.lines().filter(|l| l.starts_with("video ")).count(), + 2, + "{text}" + ); + assert_eq!( + text.lines().filter(|l| l.starts_with("audio ")).count(), + 2, + "{text}" + ); + let again = PlaybackSession::open_project(&v2).expect("open the v2 file"); + assert_eq!(shape(&again), shape(&loaded)); + // ...and re-saving it is byte-identical, so a round trip is stable. + let third = dir.join("third.edith"); + again.save_project(&third).expect("save"); + assert_eq!(std::fs::read(&third).expect("read"), text.as_bytes()); +} + #[test] fn a_saved_project_reopens_as_the_same_timeline() { let dir = scratch("round_trip"); @@ -225,8 +280,16 @@ fn malformed_files_are_numbered_errors_and_never_panics() { let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n"; for (text, want) in [ - ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 1"), + ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 1"), ("not a project at all\n", "line 1"), + // Dialects do not mix: lane lines are v2's, `clip` is v1's. + ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 3"), + ("edith 1\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 3"), + ("edith 2\nsource test_av.mp4\nvideo 0 0 30 0\n", "line 3"), + ( + "edith 2\nsource test_av.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n", + "line 4", + ), ("edith 1\nsource test_av.mp4\nclip 0 30\n", "line 3"), ("edith 1\nsource test_av.mp4\nclip 0 30 4\n", "line 3"), ("edith 1\nsource test_av.mp4\nclip 30 30 0\n", "line 3"),