diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index fd7015d..b123d38 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -269,19 +269,10 @@ impl AudioSession { /// 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. + /// A segment naming **no** source is a gap, and is copied as that many + /// packets of [`silent_packet`] silence — the rounding debt carried through + /// it like any other, so the hole occupies its exact duration and the audio + /// after it stays in sync with the picture. pub fn copy_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], @@ -299,17 +290,18 @@ impl AudioSession { let mut tracks: Vec> = sources.iter().map(|_| None).collect(); tracks[first] = Some(track); + let sample_rate = params.sample_rate; let mut err = 0i64; 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, + let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; + let bytes = silent_packet(params.chan_conf)?; + for _ in 0..packet_run(&mut err, ideal, u32::MAX) { + packets.push(AacPacket { + bytes: bytes.clone(), + samples: SAMPLES_PER_PACKET, + }); } continue; }; @@ -342,13 +334,35 @@ impl AudioSession { }); } } - if let Some(first) = packets.first_mut() { - first.samples += owed; - } Ok(Some((params, packets))) } } +/// One AAC-LC access unit of silence, for the gaps in an exported timeline — +/// the export copies packets and has no AAC encoder, so the only silence it can +/// write is one spelled out by hand. +/// +/// It is the shortest legal `raw_data_block` there is: one element carrying +/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no +/// spectral data at all and therefore 1024 samples of exact zero. Every field +/// is zero except the element id and the terminating `ID_END`, so the whole +/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the +/// unit tests, which is the only claim worth making about hand-written +/// bitstream. +/// +/// ponytail: mono and stereo only, because `chan_conf` beyond 2 needs more +/// elements per block; the timeline refuses such a source at import today, so +/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements. +fn silent_packet(chan_conf: u8) -> crate::Result> { + match chan_conf { + // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned. + 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]), + // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END. + 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]), + n => Err(format!("cannot write silence for a {n}-channel AAC track").into()), + } +} + /// The source at `index`, opened on first use. Sources a segment list never /// names are never touched: a project's list only grows. fn source_at<'a>( @@ -882,4 +896,44 @@ mod tests { ]; assert_eq!(asc, [0x12, 0x10]); } + + /// The one claim worth making about a hand-written bitstream: our own + /// decoder turns it into exactly one packet of exactly zero. + #[test] + fn a_silent_packet_decodes_to_a_packet_of_zero() { + use super::{AacDecoder, AudioDecoder, AudioDecoderOptions, silent_packet}; + use symphonia_core::codecs::audio::{AudioCodecParameters, well_known::CODEC_ID_AAC}; + use symphonia_core::{packet::Packet, units}; + + for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] { + // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels. + let asc: Box<[u8]> = Box::new([(2 << 3) | (4 >> 1), (4 << 7) | (chan_conf << 3)]); + let mut params = AudioCodecParameters::new(); + params + .for_codec(CODEC_ID_AAC) + .with_sample_rate(44100) + .with_extra_data(asc); + let mut decoder = + AacDecoder::try_new(¶ms, &AudioDecoderOptions::default()).expect("decoder"); + let bytes = silent_packet(chan_conf).expect("silence"); + let packet = Packet::new( + 0, + units::Timestamp::new(0), + units::Duration::new(u64::from(SAMPLES_PER_PACKET)), + &bytes[..], + ); + let buf = decoder.decode(&packet).expect("decodes as AAC-LC"); + let mut out = Vec::new(); + buf.copy_to_vec_interleaved::(&mut out); + assert_eq!(out.len(), SAMPLES_PER_PACKET as usize * channels); + assert!( + out.iter().all(|&s| s == 0.0), + "{chan_conf} ch is not silent" + ); + } + assert!( + silent_packet(6).is_err(), + "beyond stereo is refused, not faked" + ); + } } diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index e37e3d7..5f66d32 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -300,6 +300,16 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result { ) .into()); } + // Everything downstream -- `Clip::end`, the overlap check, the v1 queue -- + // adds `start + len` as plain `u32`, which panics in debug and wraps in + // release on a crafted file. Bound it here, at the door. + if clip.start.checked_add(clip.len()).is_none() { + return Err(format!( + "line {line}: clip at {} runs past the last frame there is", + clip.start + ) + .into()); + } Ok(clip) } @@ -462,6 +472,27 @@ mod tests { assert!(only_audio.video.is_empty()); } + /// A `start` near the top of `u32` used to make `Clip::end` panic in debug + /// and wrap in release, and a wrapped end passes the overlap check -- + /// crafted numbers must be refused by name, in both dialects. + #[test] + fn a_clip_whose_end_overflows_is_refused() { + let dir = PathBuf::from("/proj"); + for bytes in [ + &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..], + // Two of them: the second would land *before* the first once wrapped. + b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n", + // v1 has no `start` field, but its queue reaches the same ceiling. + b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n", + ] { + let err = parse(bytes, &dir).unwrap_err().to_string(); + assert!( + err.contains("runs past the last frame there is"), + "not refused by name: {err}" + ); + } + } + /// The relocatability promise, from the two directions a project path /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith /// clip.mp4`, whose parent is `""`) and a directory reached through a diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 8dfe585..42bdcc4 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -217,7 +217,7 @@ fn run( }; if let Some((_, packets)) = audio { for packet in packets { - muxer.write_audio_packet(&packet.bytes, packet.samples)?; + muxer.write_audio_packet(&packet.bytes)?; } } cancelled(shared)?; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 2d182d4..a24cd50 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -143,13 +143,10 @@ impl Mp4Muxer { Ok(()) } - /// One raw AAC packet (no ADTS header), copied verbatim from the source. - /// `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<()> { + /// One raw AAC packet (no ADTS header), copied verbatim from the source -- + /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC + /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. + pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> { if !self.has_audio { return Err("audio packet written to a video-only file".into()); } @@ -157,7 +154,7 @@ impl Mp4Muxer { AUDIO_TRACK, &Mp4Sample { start_time: 0, - duration: samples.max(AAC_PACKET_SAMPLES), + duration: 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. @@ -391,14 +388,8 @@ mod tests { for unit in &units { muxer.write_video_au(unit).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.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap(); + muxer.write_audio_packet(&[0x24, 0x25]).unwrap(); muxer.finish().unwrap(); let file = File::open(&out).unwrap(); @@ -424,12 +415,11 @@ 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"); + let second = reader.read_sample(audio_id, 2).unwrap().unwrap(); + assert_eq!(&second.bytes[..], [0x24, 0x25], "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" + second.duration, AAC_PACKET_SAMPLES, + "every AAC-LC packet is one 1024-frame stts entry" ); let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap(); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index fc85360..1c7c04f 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -191,8 +191,7 @@ impl PlaybackSession { } let playhead = doc.playhead; - let project = Project::from_parts(doc.sources, doc.video, doc.audio) - .ok_or("the project's clips do not fit its sources")?; + let project = Project::from_parts(doc.sources, doc.video, doc.audio)?; let span = project.span_at(Lane::Video, 0).expect("never empty"); let mut session = Self { meta, diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index c35937b..70cbb4a 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -145,30 +145,61 @@ impl Project { /// 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: 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 { + /// `false` until the first edit of the new session. This is the one door + /// untrusted parts come in through, so every invariant every other + /// constructor keeps is checked here, by name and in release: both lanes + /// empty, an empty clip, a clip naming a source that is not there, a clip + /// whose end overflows, a lane that is unsorted or self-overlapping, and + /// the grouping rules of [`Clip::link`] below. + pub fn from_parts( + sources: Vec, + video: Vec, + audio: Vec, + ) -> crate::Result { if video.is_empty() && audio.is_empty() { - return None; + return Err("both lanes are empty: that is not a project".into()); } 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; + for (lane, name) in lanes.iter().zip(["video", "audio"]) { + for c in lane { + if c.out_frame <= c.in_frame { + return Err(format!( + "{name} clip at {} plays the empty range [{}, {})", + c.start, c.in_frame, c.out_frame + ) + .into()); + } + if c.source >= sources.len() { + return Err(format!( + "{name} clip at {} names source {} of {}", + c.start, + c.source, + sources.len() + ) + .into()); + } + if c.start.checked_add(c.len()).is_none() { + return Err(format!( + "{name} clip at {} runs past the last frame there is", + c.start + ) + .into()); + } + } + if !sorted_disjoint(lane) { + return Err(format!("the {name} lane is out of order or overlaps itself").into()); + } } + links_are_consistent(&lanes)?; let next_link = lanes .iter() .flatten() .filter_map(|c| c.link) .max() - .map_or(0, |m| m + 1); - Some(Self { + // Saturating so a crafted file cannot make the counter wrap: at the + // ceiling ids stop being fresh, which loses grouping, not memory. + .map_or(0, |m| m.saturating_add(1)); + Ok(Self { sources: sources.iter().map(|s| canonical(s)).collect(), lanes, history: Vec::new(), @@ -404,6 +435,14 @@ impl Project { /// 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`. + /// + /// The placement belongs to no group: a clipboard clip carries the link id + /// of the take it was copied from, and placing it twice -- or placing a copy + /// back over the clip it came from -- would put that id on two clips of one + /// lane, which is what a link may never mean (see [`links_are_consistent`]). + /// `None` rather than a fresh id because a one-lane placement has nothing on + /// the other lane to be grouped *with*; [`Project::regroup`] is how clips + /// become a group again. pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool { if clip.out_frame <= clip.in_frame { return false; @@ -411,6 +450,7 @@ impl Project { self.snapshot(); let clip = Clip { start: timeline_frame, + link: None, ..clip }; let lane = &mut self.lanes[lane.index()]; @@ -553,8 +593,9 @@ impl Project { } fn new_link(&mut self) -> u32 { - self.next_link += 1; - self.next_link - 1 + let id = self.next_link; + self.next_link = self.next_link.saturating_add(1); + id } } @@ -591,10 +632,50 @@ fn sorted_disjoint(clips: &[Clip]) -> bool { && clips.windows(2).all(|w| w[0].end() <= w[1].start) } +/// The grouping invariant, checked in release at [`Project::from_parts`]: a link +/// id names **at most one** clip per lane, and when it names one in each, the two +/// cover the same timeline span -- that is all "these move together" can mean. +/// +/// A link the *other* lane does not carry is legal and is not an error: lifting +/// one half of a group ([`Project::lift`]) leaves exactly that, and a save of +/// that timeline has to load again. +fn links_are_consistent(lanes: &[Vec; 2]) -> crate::Result<()> { + let find = |lane: &Vec, id: u32| lane.iter().find(|c| c.link == Some(id)).copied(); + for (lane, name) in lanes.iter().zip(["video", "audio"]) { + for (i, c) in lane.iter().enumerate() { + let Some(id) = c.link else { continue }; + if lane[..i].iter().any(|prev| prev.link == Some(id)) { + return Err(format!("link {id} names two clips in the {name} lane").into()); + } + } + } + for a in lanes[0].iter().filter(|c| c.link.is_some()) { + let id = a.link.expect("filtered"); + let Some(b) = find(&lanes[1], id) else { + continue; + }; + if (a.start, a.end()) != (b.start, b.end()) { + return Err(format!( + "link {id} covers [{}, {}) in video and [{}, {}) in audio", + a.start, + a.end(), + b.start, + b.end() + ) + .into()); + } + } + Ok(()) +} + /// 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. +/// +/// A piece the hole cut is no longer the take its group id names -- and both +/// halves of a straddled placement carrying that id would be the same id twice +/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]). fn clear(clips: &mut Vec, start: u32, end: u32) { let mut out = Vec::with_capacity(clips.len() + 1); for c in clips.drain(..) { @@ -607,6 +688,7 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { if c.start < start { out.push(Clip { out_frame: c.in_frame + (start - c.start), + link: None, ..c }); } @@ -615,6 +697,7 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { out.push(Clip { start: end, in_frame: c.in_frame + (end - c.start), + link: None, ..c }); } @@ -624,13 +707,16 @@ fn clear(clips: &mut Vec, start: u32, end: u32) { /// 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. +/// insert half of a rippling paste. The two halves lose the group id for the +/// reason [`clear`] gives. 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; + tail.link = None; clips[idx].out_frame = tail.in_frame; + clips[idx].link = None; clips.insert(idx + 1, tail); } for c in clips.iter_mut().filter(|c| c.start >= at) { @@ -1274,24 +1360,100 @@ mod tests { assert!(p.undo()); // 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] = [ + assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_ok()); + assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err()); + let bad: [Vec; 5] = [ 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 + vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame ]; for clips in bad { assert!( - Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_none(), + Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_err(), "{clips:?}" ); - assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_none()); + assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_err()); } // 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())); } + + /// The grouping rules, at the untrusted door and after every edit that can + /// touch a link. A link id is at most one clip per lane and, when both lanes + /// carry it, one span -- and no sequence of edits may produce otherwise, + /// because what an edit produces is what a save writes and a load reads. + #[test] + fn a_link_id_is_never_two_clips_of_one_lane() { + let sources = vec![PathBuf::from(FILE)]; + let linked = |start, in_frame, out_frame, link| Clip { + start, + in_frame, + out_frame, + source: 0, + link: Some(link), + }; + + // The door: named errors, one per cause. + let err = |video: Vec, audio: Vec| { + Project::from_parts(sources.clone(), video, audio) + .expect_err("refused") + .to_string() + }; + assert!( + err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new()) + .contains("link 7 names two clips in the video lane"), + "a duplicate id inside one lane is refused by name" + ); + assert!( + err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]) + .contains("link 2 covers [0, 5) in video and [0, 3) in audio"), + "a pair that does not cover one span is refused by name" + ); + // A one-sided link is *not* an error: it is what a lift leaves behind. + let mut p = Project::single(FILE, 9); + assert!(p.lift(Lane::Audio, 0)); + let (sources, video, audio) = p.clone().without_orphan_sources(); + assert!( + Project::from_parts(sources, video, audio).is_ok(), + "a lifted lane's project has to load again" + ); + + // The edits: nothing below may break either rule. + let consistent = |p: &Project, what: &str| { + let lanes = Lane::ALL.map(|l| p.lane(l).to_vec()); + assert!(links_are_consistent(&lanes).is_ok(), "{what}: {lanes:?}"); + }; + let mut p = three(); + let copied = p.clips()[0]; + assert!( + copied.link.is_some(), + "the clipboard clip carries its group" + ); + assert!(p.lift(Lane::Video, 0)); + assert!(p.place(Lane::Video, 0, copied)); + assert!(p.place(Lane::Video, 20, copied), "and again, further out"); + assert_eq!( + p.clips().iter().filter(|c| c.link == copied.link).count(), + 0, + "a placement belongs to no group, so it cannot duplicate one" + ); + consistent(&p, "lift + place twice"); + assert!( + p.place(Lane::Audio, 4, copied), + "over a linked clip's middle" + ); + consistent(&p, "place through a grouped clip"); + assert!(p.paste(6, copied), "a rippling paste through another"); + consistent(&p, "paste"); + assert!(p.split(2)); + consistent(&p, "split"); + assert!(p.ripple_delete(1, 3)); + consistent(&p, "ripple_delete"); + assert!(p.undo()); + consistent(&p, "undo"); + } } diff --git a/crates/engine/tests/audio_segments.rs b/crates/engine/tests/audio_segments.rs index 08a7e72..3bd3c1e 100644 --- a/crates/engine/tests/audio_segments.rs +++ b/crates/engine/tests/audio_segments.rs @@ -185,11 +185,12 @@ fn a_gap_segment_is_silence_of_its_own_length() { ); } -/// 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. +/// The copy side of a gap: there is no AAC encoder here, so the hole is copied +/// as hand-written silent packets -- real access units, one 1024-frame stts +/// entry each, the rounding debt carried through them like any other segment. +/// 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() { +fn a_copied_gap_is_packets_of_hand_written_silence() { 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)]; @@ -200,48 +201,52 @@ fn a_copied_gap_becomes_the_duration_of_the_packet_before_it() { 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" + assert!( + with.iter().all(|p| u64::from(p.samples) == PACKET), + "gap or not, every AAC-LC packet is 1024 frames" + ); + let gap = total(&with) - total(&without); + assert!( + gap.abs_diff(RATE) <= PACKET / 2, + "the hole is {gap} frames of silence for a second of timeline" ); - // 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 + // The audible packets are the same bytes in the same order: the silence was + // inserted between them, not spliced through them. + let audible: Vec<&Vec> = with + .iter() + .map(|p| &p.bytes) + .filter(|b| b.len() > 7) + .collect(); + let want: Vec<&Vec> = without.iter().map(|p| &p.bytes).collect(); + assert_eq!(audible, want, "not one byte of audio moved"); + // Stereo silence is the 7-byte block, and it sits where the hole is. + let silent = |p: &engine::AacPacket| p.bytes == [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]; + let run: Vec = with .iter() - .zip(&without) .enumerate() - .filter(|(_, (a, b))| a.samples != b.samples) + .filter(|(_, p)| silent(p)) .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_eq!( + run.len() as u64, + gap / PACKET, + "the gap is that many silent packets" ); assert!( - with.iter().zip(&without).all(|(a, b)| a.bytes == b.bytes), - "and not one byte of audio moved" + run.windows(2).all(|w| w[1] == w[0] + 1) && run[0] > 0, + "and they are one interior run, at {run:?}" ); - // 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. + // A gap at the *head* is packets of its own: nothing rides on a neighbour, + // so there is no leading misplacement left to document. 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" + let head = leading.iter().take_while(|p| silent(p)).count() as u64; + assert!( + (head * PACKET).abs_diff(RATE / 2) <= PACKET, + "{head} silent packets for half a second of leading hole" ); } diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 1281078..e02bf1d 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -33,8 +33,10 @@ fn asset(name: &str) -> PathBuf { .join(name) } +/// Per-run unique: two suite runs at once (a release sweep beside a debug one, +/// or two agents) would otherwise write and delete each other's export. fn out_path(name: &str) -> PathBuf { - let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4")); + let path = std::env::temp_dir().join(format!("ve_export_{name}_{}.mp4", std::process::id())); let _ = std::fs::remove_file(&path); let _ = std::fs::remove_file(part_path(&path)); path @@ -552,9 +554,9 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec< /// 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. +/// frame -- and the audio gap is copied as real silent packets, so the audio +/// track 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(); @@ -599,24 +601,42 @@ fn exports_a_gapped_timeline_as_black_and_silence() { 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. + // The audio track spans the whole timeline in packets: the hole is real + // silent access units, so the bresenham bound the copier promises -- half a + // packet per join, carried through the gap -- covers the gap too. 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; + let count = reader.sample_count(2).expect("audio track"); + let samples = f64::from(count * 1024); + let wanted = timeline * 44_100.0; + println!("gapped export: {count} packets = {samples} samples for {wanted}"); assert!( - (packets - audible).abs() < 3.0 * 1024.0, - "{packets} samples copied for {audible} audible ones" + (samples - wanted).abs() < 3.0 * 1024.0, + "audio length {samples} drifted from {wanted} across the gap" ); + + // ...and the silence is really silent, where the lift was. + let (_, chunks) = engine::AudioSession::open(&out) + .expect("reopen export audio") + .expect("export has an audio track"); + let mut pcm: Vec = Vec::new(); + while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { + pcm.resize(chunk.start_sample as usize * 2, 0.0); + pcm.extend_from_slice(&chunk.samples); + } + let window = |from: f64, to: f64| { + let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2); + pcm[a.min(pcm.len())..b.min(pcm.len())] + .iter() + .fold(0.0f32, |m, s| m.max(s.abs())) + }; + // Inside the hole, off its own edges: AAC is lapped, so the packets either + // side of a splice carry a little of their neighbour. + let quiet = window(1.2, 1.8); + assert!(quiet < 1e-3, "the gap is not silent: {quiet}"); + assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing"); + assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing"); + + std::fs::remove_file(&out).unwrap(); }