forge
Explore
Log in

Don't you dare go Hollow

Real silent AAC for export gaps, link + overflow guards

Browse files at this commit

301e29badba26e1ffdff7ab05a2813288e85a5bbAhmet Kaan GümüşParent: 59eb78e
  • feat
    • real silent AAC for export gaps, link + overflow guards
Show full message
✨ feat(engine): real silent AAC for export gaps, link + overflow guards

Grafts the losing candidate's hand-written AAC-LC silence into the
offset-placed lanes: a gap in the audio lane is copied as max_sfb=0
access units (4 bytes mono, 7 stereo, verified against our own decoder)
instead of being spent as stts duration on the packet in front of it.
That retires the 23 ms leading-gap misplacement, so every packet is one
1024-frame sample table entry again and the muxer takes no duration.

from_parts becomes the release-active untrusted door it claims to be:
per-cause errors, an end-overflow bound, and the grouping rules -- a
link id names at most one clip per lane, and a pair covers one span.
The parser bounds the same overflow by line number, `place` strips the
incoming group id, and the two lane surgeries (`clear`, `open_room`)
drop the id from what they cut, which is where duplicates came from.
crates/engine/src/audio.rsmodified+77 -23
@@ -269,19 +269,10 @@ impl AudioSession {
269 /// one output track with one esds. Import refuses a mismatch up front; the269 /// one output track with one esds. Import refuses a mismatch up front; the
270 /// check here is the backstop, as is the missing-track `Err`.270 /// check here is the backstop, as is the missing-track `Err`.
271 ///271 ///
272- /// A segment naming **no** source is a gap. There is no AAC encoder here to272+ /// A segment naming **no** source is a gap, and is copied as that many
273- /// make silence with, so the gap is spent as *time* instead: its length is273+ /// packets of [`silent_packet`] silence — the rounding debt carried through
274- /// added to the [`samples`](AacPacket::samples) of the packet next to it,274+ /// it like any other, so the hole occupies its exact duration and the audio
275- /// which is the duration the writer puts in the stts. Every packet after275+ /// after it stays in sync with the picture.
276- /// the gap therefore still lands at its timeline position, so nothing
277- /// drifts out of lip sync, and a conforming reader renders the hole as
278- /// silence.
279- ///
280- /// ponytail: a gap at the *head* of the timeline has no packet before it to
281- /// lengthen, so its length goes on the first packet instead — that one
282- /// packet (23 ms) plays at zero rather than after the hole, and everything
283- /// from the second packet on is exact. Upgrade path is an empty `elst`
284- /// entry at the head of the audio track.
285 pub fn copy_multi_segments(276 pub fn copy_multi_segments(
286 sources: &[PathBuf],277 sources: &[PathBuf],
287 segs: &[(Option<usize>, f64, f64)],278 segs: &[(Option<usize>, f64, f64)],
@@ -299,17 +290,18 @@ impl AudioSession {
299 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();290 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
300 tracks[first] = Some(track);291 tracks[first] = Some(track);
301 292
293+ let sample_rate = params.sample_rate;
302 let mut err = 0i64;294 let mut err = 0i64;
303 let mut packets: Vec<AacPacket> = Vec::new();295 let mut packets: Vec<AacPacket> = Vec::new();
304- // Gap time with no packet in front of it to carry it: a leading gap,
305- // which the first packet written picks up (see the ponytail above).
306- let mut owed = 0u32;
307 for &(source, start_secs, end_secs) in segs {296 for &(source, start_secs, end_secs) in segs {
308 let Some(source) = source else {297 let Some(source) = source else {
309- let len = ((end_secs - start_secs).max(0.0) * f64::from(params.sample_rate)) as u32;298+ let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
310- match packets.last_mut() {299+ let bytes = silent_packet(params.chan_conf)?;
311- Some(prev) => prev.samples += len,300+ for _ in 0..packet_run(&mut err, ideal, u32::MAX) {
312- None => owed += len,301+ packets.push(AacPacket {
302+ bytes: bytes.clone(),
303+ samples: SAMPLES_PER_PACKET,
304+ });
313 }305 }
314 continue;306 continue;
315 };307 };
@@ -342,13 +334,35 @@ impl AudioSession {
342 });334 });
343 }335 }
344 }336 }
345- if let Some(first) = packets.first_mut() {
346- first.samples += owed;
347- }
348 Ok(Some((params, packets)))337 Ok(Some((params, packets)))
349 }338 }
350 }339 }
351 340
341+/// One AAC-LC access unit of silence, for the gaps in an exported timeline —
342+/// the export copies packets and has no AAC encoder, so the only silence it can
343+/// write is one spelled out by hand.
344+///
345+/// It is the shortest legal `raw_data_block` there is: one element carrying
346+/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
347+/// spectral data at all and therefore 1024 samples of exact zero. Every field
348+/// is zero except the element id and the terminating `ID_END`, so the whole
349+/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the
350+/// unit tests, which is the only claim worth making about hand-written
351+/// bitstream.
352+///
353+/// ponytail: mono and stereo only, because `chan_conf` beyond 2 needs more
354+/// elements per block; the timeline refuses such a source at import today, so
355+/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements.
356+fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
357+ match chan_conf {
358+ // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned.
359+ 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]),
360+ // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END.
361+ 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]),
362+ n => Err(format!("cannot write silence for a {n}-channel AAC track").into()),
363+ }
364+}
365+
352 /// The source at `index`, opened on first use. Sources a segment list never366 /// The source at `index`, opened on first use. Sources a segment list never
353 /// names are never touched: a project's list only grows.367 /// names are never touched: a project's list only grows.
354 fn source_at<'a>(368 fn source_at<'a>(
@@ -882,4 +896,44 @@ mod tests {
882 ];896 ];
883 assert_eq!(asc, [0x12, 0x10]);897 assert_eq!(asc, [0x12, 0x10]);
884 }898 }
899+
900+ /// The one claim worth making about a hand-written bitstream: our own
901+ /// decoder turns it into exactly one packet of exactly zero.
902+ #[test]
903+ fn a_silent_packet_decodes_to_a_packet_of_zero() {
904+ use super::{AacDecoder, AudioDecoder, AudioDecoderOptions, silent_packet};
905+ use symphonia_core::codecs::audio::{AudioCodecParameters, well_known::CODEC_ID_AAC};
906+ use symphonia_core::{packet::Packet, units};
907+
908+ for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] {
909+ // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels.
910+ let asc: Box<[u8]> = Box::new([(2 << 3) | (4 >> 1), (4 << 7) | (chan_conf << 3)]);
911+ let mut params = AudioCodecParameters::new();
912+ params
913+ .for_codec(CODEC_ID_AAC)
914+ .with_sample_rate(44100)
915+ .with_extra_data(asc);
916+ let mut decoder =
917+ AacDecoder::try_new(&params, &AudioDecoderOptions::default()).expect("decoder");
918+ let bytes = silent_packet(chan_conf).expect("silence");
919+ let packet = Packet::new(
920+ 0,
921+ units::Timestamp::new(0),
922+ units::Duration::new(u64::from(SAMPLES_PER_PACKET)),
923+ &bytes[..],
924+ );
925+ let buf = decoder.decode(&packet).expect("decodes as AAC-LC");
926+ let mut out = Vec::new();
927+ buf.copy_to_vec_interleaved::<f32>(&mut out);
928+ assert_eq!(out.len(), SAMPLES_PER_PACKET as usize * channels);
929+ assert!(
930+ out.iter().all(|&s| s == 0.0),
931+ "{chan_conf} ch is not silent"
932+ );
933+ }
934+ assert!(
935+ silent_packet(6).is_err(),
936+ "beyond stereo is refused, not faked"
937+ );
938+ }
885 }939 }
crates/engine/src/edith.rsmodified+31 -0
@@ -300,6 +300,16 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
300 )300 )
301 .into());301 .into());
302 }302 }
303+ // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
304+ // adds `start + len` as plain `u32`, which panics in debug and wraps in
305+ // release on a crafted file. Bound it here, at the door.
306+ if clip.start.checked_add(clip.len()).is_none() {
307+ return Err(format!(
308+ "line {line}: clip at {} runs past the last frame there is",
309+ clip.start
310+ )
311+ .into());
312+ }
303 Ok(clip)313 Ok(clip)
304 }314 }
305 315
@@ -462,6 +472,27 @@ mod tests {
462 assert!(only_audio.video.is_empty());472 assert!(only_audio.video.is_empty());
463 }473 }
464 474
475+ /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
476+ /// and wrap in release, and a wrapped end passes the overlap check --
477+ /// crafted numbers must be refused by name, in both dialects.
478+ #[test]
479+ fn a_clip_whose_end_overflows_is_refused() {
480+ let dir = PathBuf::from("/proj");
481+ for bytes in [
482+ &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
483+ // Two of them: the second would land *before* the first once wrapped.
484+ b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
485+ // v1 has no `start` field, but its queue reaches the same ceiling.
486+ b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
487+ ] {
488+ let err = parse(bytes, &dir).unwrap_err().to_string();
489+ assert!(
490+ err.contains("runs past the last frame there is"),
491+ "not refused by name: {err}"
492+ );
493+ }
494+ }
495+
465 /// The relocatability promise, from the two directions a project path496 /// The relocatability promise, from the two directions a project path
466 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith497 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
467 /// clip.mp4`, whose parent is `""`) and a directory reached through a498 /// clip.mp4`, whose parent is `""`) and a directory reached through a
crates/engine/src/export.rsmodified+1 -1
@@ -217,7 +217,7 @@ fn run(
217 };217 };
218 if let Some((_, packets)) = audio {218 if let Some((_, packets)) = audio {
219 for packet in packets {219 for packet in packets {
220- muxer.write_audio_packet(&packet.bytes, packet.samples)?;220+ muxer.write_audio_packet(&packet.bytes)?;
221 }221 }
222 }222 }
223 cancelled(shared)?;223 cancelled(shared)?;
crates/engine/src/mux.rsmodified+11 -21
@@ -143,13 +143,10 @@ impl Mp4Muxer {
143 Ok(())143 Ok(())
144 }144 }
145 145
146- /// One raw AAC packet (no ADTS header), copied verbatim from the source.146+ /// One raw AAC packet (no ADTS header), copied verbatim from the source --
147- /// `samples` is what the sample table says it occupies -- normally the147+ /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
148- /// [`AAC_PACKET_SAMPLES`] the codec fixes, but longer for the packet that148+ /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
149- /// carries a gap in the timeline's audio (see149+ pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {
150- /// [`AudioSession::copy_multi_segments`](crate::AudioSession::copy_multi_segments)),
151- /// where the extra duration is the silence a reader renders.
152- pub fn write_audio_packet(&mut self, bytes: &[u8], samples: u32) -> crate::Result<()> {
153 if !self.has_audio {150 if !self.has_audio {
154 return Err("audio packet written to a video-only file".into());151 return Err("audio packet written to a video-only file".into());
155 }152 }
@@ -157,7 +154,7 @@ impl Mp4Muxer {
157 AUDIO_TRACK,154 AUDIO_TRACK,
158 &Mp4Sample {155 &Mp4Sample {
159 start_time: 0,156 start_time: 0,
160- duration: samples.max(AAC_PACKET_SAMPLES),157+ duration: AAC_PACKET_SAMPLES,
161 rendering_offset: 0,158 rendering_offset: 0,
162 // Every AAC packet is a sync point; saying so per-sample would emit159 // Every AAC packet is a sync point; saying so per-sample would emit
163 // an `stss` listing all of them, while no `stss` means the same thing.160 // an `stss` listing all of them, while no `stss` means the same thing.
@@ -391,14 +388,8 @@ mod tests {
391 for unit in &units {388 for unit in &units {
392 muxer.write_video_au(unit).unwrap();389 muxer.write_video_au(unit).unwrap();
393 }390 }
394- muxer391+ muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap();
395- .write_audio_packet(&[0x21, 0x22, 0x23], AAC_PACKET_SAMPLES)392+ muxer.write_audio_packet(&[0x24, 0x25]).unwrap();
396- .unwrap();
397- // The second packet carries a gap: 1024 of its own plus half a second
398- // of silence, which is what the sample table has to say.
399- muxer
400- .write_audio_packet(&[0x24, 0x25], AAC_PACKET_SAMPLES + 22_050)
401- .unwrap();
402 muxer.finish().unwrap();393 muxer.finish().unwrap();
403 394
404 let file = File::open(&out).unwrap();395 let file = File::open(&out).unwrap();
@@ -424,12 +415,11 @@ mod tests {
424 [0x21, 0x22, 0x23],415 [0x21, 0x22, 0x23],
425 "audio packets copied verbatim"416 "audio packets copied verbatim"
426 );417 );
427- let with_gap = reader.read_sample(audio_id, 2).unwrap().unwrap();418+ let second = reader.read_sample(audio_id, 2).unwrap().unwrap();
428- assert_eq!(&with_gap.bytes[..], [0x24, 0x25], "gap or not, verbatim");419+ assert_eq!(&second.bytes[..], [0x24, 0x25], "verbatim");
429 assert_eq!(420 assert_eq!(
430- with_gap.duration,421+ second.duration, AAC_PACKET_SAMPLES,
431- AAC_PACKET_SAMPLES + 22_050,422+ "every AAC-LC packet is one 1024-frame stts entry"
432- "the gap is spent as duration, and the track ends half a second later"
433 );423 );
434 424
435 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap();425 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap();
crates/engine/src/playback.rsmodified+1 -2
@@ -191,8 +191,7 @@ impl PlaybackSession {
191 }191 }
192 192
193 let playhead = doc.playhead;193 let playhead = doc.playhead;
194- let project = Project::from_parts(doc.sources, doc.video, doc.audio)194+ let project = Project::from_parts(doc.sources, doc.video, doc.audio)?;
195- .ok_or("the project's clips do not fit its sources")?;
196 let span = project.span_at(Lane::Video, 0).expect("never empty");195 let span = project.span_at(Lane::Video, 0).expect("never empty");
197 let mut session = Self {196 let mut session = Self {
198 meta,197 meta,
crates/engine/src/project.rsmodified+185 -23
@@ -145,30 +145,61 @@ impl Project {
145 145
146 /// A project rebuilt from a saved edit list -- the load half of146 /// A project rebuilt from a saved edit list -- the load half of
147 /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is147 /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is
148- /// `false` until the first edit of the new session. `None` when the parts148+ /// `false` until the first edit of the new session. This is the one door
149- /// would break an invariant every other constructor keeps: both lanes149+ /// untrusted parts come in through, so every invariant every other
150- /// empty, an empty clip, a clip naming a source that is not there, or a150+ /// constructor keeps is checked here, by name and in release: both lanes
151- /// lane that is unsorted or self-overlapping.151+ /// empty, an empty clip, a clip naming a source that is not there, a clip
152- pub fn from_parts(sources: Vec<PathBuf>, video: Vec<Clip>, audio: Vec<Clip>) -> Option<Self> {152+ /// whose end overflows, a lane that is unsorted or self-overlapping, and
153+ /// the grouping rules of [`Clip::link`] below.
154+ pub fn from_parts(
155+ sources: Vec<PathBuf>,
156+ video: Vec<Clip>,
157+ audio: Vec<Clip>,
158+ ) -> crate::Result<Self> {
153 if video.is_empty() && audio.is_empty() {159 if video.is_empty() && audio.is_empty() {
154- return None;160+ return Err("both lanes are empty: that is not a project".into());
155 }161 }
156 let lanes = [video, audio];162 let lanes = [video, audio];
157- if lanes.iter().any(|lane| {163+ for (lane, name) in lanes.iter().zip(["video", "audio"]) {
158- !sorted_disjoint(lane)164+ for c in lane {
159- || lane165+ if c.out_frame <= c.in_frame {
160- .iter()166+ return Err(format!(
161- .any(|c| c.source >= sources.len() || c.out_frame <= c.in_frame)167+ "{name} clip at {} plays the empty range [{}, {})",
162- }) {168+ c.start, c.in_frame, c.out_frame
163- return None;169+ )
170+ .into());
171+ }
172+ if c.source >= sources.len() {
173+ return Err(format!(
174+ "{name} clip at {} names source {} of {}",
175+ c.start,
176+ c.source,
177+ sources.len()
178+ )
179+ .into());
180+ }
181+ if c.start.checked_add(c.len()).is_none() {
182+ return Err(format!(
183+ "{name} clip at {} runs past the last frame there is",
184+ c.start
185+ )
186+ .into());
187+ }
188+ }
189+ if !sorted_disjoint(lane) {
190+ return Err(format!("the {name} lane is out of order or overlaps itself").into());
191+ }
164 }192 }
193+ links_are_consistent(&lanes)?;
165 let next_link = lanes194 let next_link = lanes
166 .iter()195 .iter()
167 .flatten()196 .flatten()
168 .filter_map(|c| c.link)197 .filter_map(|c| c.link)
169 .max()198 .max()
170- .map_or(0, |m| m + 1);199+ // Saturating so a crafted file cannot make the counter wrap: at the
171- Some(Self {200+ // ceiling ids stop being fresh, which loses grouping, not memory.
201+ .map_or(0, |m| m.saturating_add(1));
202+ Ok(Self {
172 sources: sources.iter().map(|s| canonical(s)).collect(),203 sources: sources.iter().map(|s| canonical(s)).collect(),
173 lanes,204 lanes,
174 history: Vec::new(),205 history: Vec::new(),
@@ -404,6 +435,14 @@ impl Project {
404 /// if `clip` lands inside it), which is what keeps the lane sorted and435 /// if `clip` lands inside it), which is what keeps the lane sorted and
405 /// disjoint; nothing ripples, so a gap before the placement simply stays a436 /// disjoint; nothing ripples, so a gap before the placement simply stays a
406 /// gap. Refused only for an empty `clip`.437 /// gap. Refused only for an empty `clip`.
438+ ///
439+ /// The placement belongs to no group: a clipboard clip carries the link id
440+ /// of the take it was copied from, and placing it twice -- or placing a copy
441+ /// back over the clip it came from -- would put that id on two clips of one
442+ /// lane, which is what a link may never mean (see [`links_are_consistent`]).
443+ /// `None` rather than a fresh id because a one-lane placement has nothing on
444+ /// the other lane to be grouped *with*; [`Project::regroup`] is how clips
445+ /// become a group again.
407 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {446 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
408 if clip.out_frame <= clip.in_frame {447 if clip.out_frame <= clip.in_frame {
409 return false;448 return false;
@@ -411,6 +450,7 @@ impl Project {
411 self.snapshot();450 self.snapshot();
412 let clip = Clip {451 let clip = Clip {
413 start: timeline_frame,452 start: timeline_frame,
453+ link: None,
414 ..clip454 ..clip
415 };455 };
416 let lane = &mut self.lanes[lane.index()];456 let lane = &mut self.lanes[lane.index()];
@@ -553,8 +593,9 @@ impl Project {
553 }593 }
554 594
555 fn new_link(&mut self) -> u32 {595 fn new_link(&mut self) -> u32 {
556- self.next_link += 1;596+ let id = self.next_link;
557- self.next_link - 1597+ self.next_link = self.next_link.saturating_add(1);
598+ id
558 }599 }
559 }600 }
560 601
@@ -591,10 +632,50 @@ fn sorted_disjoint(clips: &[Clip]) -> bool {
591 && clips.windows(2).all(|w| w[0].end() <= w[1].start)632 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
592 }633 }
593 634
635+/// The grouping invariant, checked in release at [`Project::from_parts`]: a link
636+/// id names **at most one** clip per lane, and when it names one in each, the two
637+/// cover the same timeline span -- that is all "these move together" can mean.
638+///
639+/// A link the *other* lane does not carry is legal and is not an error: lifting
640+/// one half of a group ([`Project::lift`]) leaves exactly that, and a save of
641+/// that timeline has to load again.
642+fn links_are_consistent(lanes: &[Vec<Clip>; 2]) -> crate::Result<()> {
643+ let find = |lane: &Vec<Clip>, id: u32| lane.iter().find(|c| c.link == Some(id)).copied();
644+ for (lane, name) in lanes.iter().zip(["video", "audio"]) {
645+ for (i, c) in lane.iter().enumerate() {
646+ let Some(id) = c.link else { continue };
647+ if lane[..i].iter().any(|prev| prev.link == Some(id)) {
648+ return Err(format!("link {id} names two clips in the {name} lane").into());
649+ }
650+ }
651+ }
652+ for a in lanes[0].iter().filter(|c| c.link.is_some()) {
653+ let id = a.link.expect("filtered");
654+ let Some(b) = find(&lanes[1], id) else {
655+ continue;
656+ };
657+ if (a.start, a.end()) != (b.start, b.end()) {
658+ return Err(format!(
659+ "link {id} covers [{}, {}) in video and [{}, {}) in audio",
660+ a.start,
661+ a.end(),
662+ b.start,
663+ b.end()
664+ )
665+ .into());
666+ }
667+ }
668+ Ok(())
669+}
670+
594 /// Removes the timeline frames `[start, end)` from `clips`: placements inside671 /// Removes the timeline frames `[start, end)` from `clips`: placements inside
595 /// it go, one straddling it is split in two, one overlapping an edge is672 /// it go, one straddling it is split in two, one overlapping an edge is
596 /// trimmed. Source frames follow the trim, so what is left plays what it always673 /// trimmed. Source frames follow the trim, so what is left plays what it always
597 /// played. Leaves the lane sorted and disjoint.674 /// played. Leaves the lane sorted and disjoint.
675+///
676+/// A piece the hole cut is no longer the take its group id names -- and both
677+/// halves of a straddled placement carrying that id would be the same id twice
678+/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
598 fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {679 fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
599 let mut out = Vec::with_capacity(clips.len() + 1);680 let mut out = Vec::with_capacity(clips.len() + 1);
600 for c in clips.drain(..) {681 for c in clips.drain(..) {
@@ -607,6 +688,7 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
607 if c.start < start {688 if c.start < start {
608 out.push(Clip {689 out.push(Clip {
609 out_frame: c.in_frame + (start - c.start),690 out_frame: c.in_frame + (start - c.start),
691+ link: None,
610 ..c692 ..c
611 });693 });
612 }694 }
@@ -615,6 +697,7 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
615 out.push(Clip {697 out.push(Clip {
616 start: end,698 start: end,
617 in_frame: c.in_frame + (end - c.start),699 in_frame: c.in_frame + (end - c.start),
700+ link: None,
618 ..c701 ..c
619 });702 });
620 }703 }
@@ -624,13 +707,16 @@ fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
624 707
625 /// Slides everything from `at` on later by `len`, splitting a placement that708 /// Slides everything from `at` on later by `len`, splitting a placement that
626 /// straddles `at` so the two halves end up on either side of the hole. The709 /// straddles `at` so the two halves end up on either side of the hole. The
627-/// insert half of a rippling paste.710+/// insert half of a rippling paste. The two halves lose the group id for the
711+/// reason [`clear`] gives.
628 fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {712 fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
629 if let Some(idx) = splittable(clips, at) {713 if let Some(idx) = splittable(clips, at) {
630 let mut tail = clips[idx];714 let mut tail = clips[idx];
631 tail.in_frame += at - tail.start;715 tail.in_frame += at - tail.start;
632 tail.start = at;716 tail.start = at;
717+ tail.link = None;
633 clips[idx].out_frame = tail.in_frame;718 clips[idx].out_frame = tail.in_frame;
719+ clips[idx].link = None;
634 clips.insert(idx + 1, tail);720 clips.insert(idx + 1, tail);
635 }721 }
636 for c in clips.iter_mut().filter(|c| c.start >= at) {722 for c in clips.iter_mut().filter(|c| c.start >= at) {
@@ -1274,24 +1360,100 @@ mod tests {
1274 assert!(p.undo());1360 assert!(p.undo());
1275 1361
1276 // A lane may be empty; both may not.1362 // A lane may be empty; both may not.
1277- assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_some());1363+ assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_ok());
1278- assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_none());1364+ assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err());
1279- let bad: [Vec<Clip>; 4] = [1365+ let bad: [Vec<Clip>; 5] = [
1280 vec![clip(0, 0, 3, 1)], // source that is not there1366 vec![clip(0, 0, 3, 1)], // source that is not there
1281 vec![clip(0, 3, 3, 0)], // empty clip1367 vec![clip(0, 3, 3, 0)], // empty clip
1282 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order1368 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
1283 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping1369 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
1370+ vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
1284 ];1371 ];
1285 for clips in bad {1372 for clips in bad {
1286 assert!(1373 assert!(
1287- Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_none(),1374+ Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_err(),
1288 "{clips:?}"1375 "{clips:?}"
1289 );1376 );
1290- assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_none());1377+ assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_err());
1291 }1378 }
1292 // Group ids survive a load, and the next split gets a fresh one.1379 // Group ids survive a load, and the next split gets a fresh one.
1293 let mut p = Project::from_parts(sources, video, audio).expect("valid parts");1380 let mut p = Project::from_parts(sources, video, audio).expect("valid parts");
1294 assert!(p.split(4));1381 assert!(p.split(4));
1295 assert!(p.clips().iter().all(|c| c.link.is_some()));1382 assert!(p.clips().iter().all(|c| c.link.is_some()));
1296 }1383 }
1384+
1385+ /// The grouping rules, at the untrusted door and after every edit that can
1386+ /// touch a link. A link id is at most one clip per lane and, when both lanes
1387+ /// carry it, one span -- and no sequence of edits may produce otherwise,
1388+ /// because what an edit produces is what a save writes and a load reads.
1389+ #[test]
1390+ fn a_link_id_is_never_two_clips_of_one_lane() {
1391+ let sources = vec![PathBuf::from(FILE)];
1392+ let linked = |start, in_frame, out_frame, link| Clip {
1393+ start,
1394+ in_frame,
1395+ out_frame,
1396+ source: 0,
1397+ link: Some(link),
1398+ };
1399+
1400+ // The door: named errors, one per cause.
1401+ let err = |video: Vec<Clip>, audio: Vec<Clip>| {
1402+ Project::from_parts(sources.clone(), video, audio)
1403+ .expect_err("refused")
1404+ .to_string()
1405+ };
1406+ assert!(
1407+ err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
1408+ .contains("link 7 names two clips in the video lane"),
1409+ "a duplicate id inside one lane is refused by name"
1410+ );
1411+ assert!(
1412+ err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])
1413+ .contains("link 2 covers [0, 5) in video and [0, 3) in audio"),
1414+ "a pair that does not cover one span is refused by name"
1415+ );
1416+ // A one-sided link is *not* an error: it is what a lift leaves behind.
1417+ let mut p = Project::single(FILE, 9);
1418+ assert!(p.lift(Lane::Audio, 0));
1419+ let (sources, video, audio) = p.clone().without_orphan_sources();
1420+ assert!(
1421+ Project::from_parts(sources, video, audio).is_ok(),
1422+ "a lifted lane's project has to load again"
1423+ );
1424+
1425+ // The edits: nothing below may break either rule.
1426+ let consistent = |p: &Project, what: &str| {
1427+ let lanes = Lane::ALL.map(|l| p.lane(l).to_vec());
1428+ assert!(links_are_consistent(&lanes).is_ok(), "{what}: {lanes:?}");
1429+ };
1430+ let mut p = three();
1431+ let copied = p.clips()[0];
1432+ assert!(
1433+ copied.link.is_some(),
1434+ "the clipboard clip carries its group"
1435+ );
1436+ assert!(p.lift(Lane::Video, 0));
1437+ assert!(p.place(Lane::Video, 0, copied));
1438+ assert!(p.place(Lane::Video, 20, copied), "and again, further out");
1439+ assert_eq!(
1440+ p.clips().iter().filter(|c| c.link == copied.link).count(),
1441+ 0,
1442+ "a placement belongs to no group, so it cannot duplicate one"
1443+ );
1444+ consistent(&p, "lift + place twice");
1445+ assert!(
1446+ p.place(Lane::Audio, 4, copied),
1447+ "over a linked clip's middle"
1448+ );
1449+ consistent(&p, "place through a grouped clip");
1450+ assert!(p.paste(6, copied), "a rippling paste through another");
1451+ consistent(&p, "paste");
1452+ assert!(p.split(2));
1453+ consistent(&p, "split");
1454+ assert!(p.ripple_delete(1, 3));
1455+ consistent(&p, "ripple_delete");
1456+ assert!(p.undo());
1457+ consistent(&p, "undo");
1458+ }
1297 }1459 }
crates/engine/tests/audio_segments.rsmodified+38 -33
@@ -185,11 +185,12 @@ fn a_gap_segment_is_silence_of_its_own_length() {
185 );185 );
186 }186 }
187 187
188-/// The copy side of a gap: there is no AAC encoder here to make silence with,188+/// The copy side of a gap: there is no AAC encoder here, so the hole is copied
189-/// so the hole is spent as *duration* on the packet in front of it. Every189+/// as hand-written silent packets -- real access units, one 1024-frame stts
190-/// packet after the gap therefore still lands at its timeline position.190+/// entry each, the rounding debt carried through them like any other segment.
191+/// Every packet after the gap therefore still lands at its timeline position.
191 #[test]192 #[test]
192-fn a_copied_gap_becomes_the_duration_of_the_packet_before_it() {193+fn a_copied_gap_is_packets_of_hand_written_silence() {
193 let sources = [asset()];194 let sources = [asset()];
194 let plain = [(Some(0), 0.0, 1.0), (Some(0), 2.0, 3.0)];195 let plain = [(Some(0), 0.0, 1.0), (Some(0), 2.0, 3.0)];
195 let gapped = [(Some(0), 0.0, 1.0), (None, 0.0, 1.0), (Some(0), 2.0, 3.0)];196 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() {
200 let (_, with) = AudioSession::copy_multi_segments(&sources, &gapped)201 let (_, with) = AudioSession::copy_multi_segments(&sources, &gapped)
201 .unwrap()202 .unwrap()
202 .unwrap();203 .unwrap();
203- assert_eq!(
204- with.len(),
205- without.len(),
206- "a gap copies no packets: there is nothing in it"
207- );
208 let total = |p: &[engine::AacPacket]| p.iter().map(|p| u64::from(p.samples)).sum::<u64>();204 let total = |p: &[engine::AacPacket]| p.iter().map(|p| u64::from(p.samples)).sum::<u64>();
209- assert_eq!(205+ assert!(
210- total(&with) - total(&without),206+ with.iter().all(|p| u64::from(p.samples) == PACKET),
211- RATE,207+ "gap or not, every AAC-LC packet is 1024 frames"
212- "...it costs exactly its own second of stts duration"208+ );
209+ let gap = total(&with) - total(&without);
210+ assert!(
211+ gap.abs_diff(RATE) <= PACKET / 2,
212+ "the hole is {gap} frames of silence for a second of timeline"
213 );213 );
214- // Exactly one packet grew, and it is an interior one -- the last before214+ // The audible packets are the same bytes in the same order: the silence was
215- // the hole -- so every packet after the hole is pushed to where the215+ // inserted between them, not spliced through them.
216- // timeline wants it rather than the whole tail drifting early.216+ let audible: Vec<&Vec<u8>> = with
217- let grown: Vec<usize> = with217+ .iter()
218+ .map(|p| &p.bytes)
219+ .filter(|b| b.len() > 7)
220+ .collect();
221+ let want: Vec<&Vec<u8>> = without.iter().map(|p| &p.bytes).collect();
222+ assert_eq!(audible, want, "not one byte of audio moved");
223+ // Stereo silence is the 7-byte block, and it sits where the hole is.
224+ let silent = |p: &engine::AacPacket| p.bytes == [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E];
225+ let run: Vec<usize> = with
218 .iter()226 .iter()
219- .zip(&without)
220 .enumerate()227 .enumerate()
221- .filter(|(_, (a, b))| a.samples != b.samples)228+ .filter(|(_, p)| silent(p))
222 .map(|(i, _)| i)229 .map(|(i, _)| i)
223 .collect();230 .collect();
224- assert_eq!(grown.len(), 1, "one packet carries the whole gap");231+ assert_eq!(
225- assert!(232+ run.len() as u64,
226- grown[0] > 0 && grown[0] < with.len() - 1,233+ gap / PACKET,
227- "the gap rides on an interior packet, at {} of {}",234+ "the gap is that many silent packets"
228- grown[0],
229- with.len()
230 );235 );
231 assert!(236 assert!(
232- with.iter().zip(&without).all(|(a, b)| a.bytes == b.bytes),237+ run.windows(2).all(|w| w[1] == w[0] + 1) && run[0] > 0,
233- "and not one byte of audio moved"238+ "and they are one interior run, at {run:?}"
234 );239 );
235 240
236- // A gap at the *head* has no packet before it: the first one picks it up241+ // A gap at the *head* is packets of its own: nothing rides on a neighbour,
237- // (the documented ponytail), so nothing but that packet is misplaced.242+ // so there is no leading misplacement left to document.
238 let (_, leading) =243 let (_, leading) =
239 AudioSession::copy_multi_segments(&sources, &[(None, 0.0, 0.5), (Some(0), 0.0, 1.0)])244 AudioSession::copy_multi_segments(&sources, &[(None, 0.0, 0.5), (Some(0), 0.0, 1.0)])
240 .unwrap()245 .unwrap()
241 .unwrap();246 .unwrap();
242- assert_eq!(247+ let head = leading.iter().take_while(|p| silent(p)).count() as u64;
243- u64::from(leading[0].samples),248+ assert!(
244- 1024 + RATE / 2,249+ (head * PACKET).abs_diff(RATE / 2) <= PACKET,
245- "the head gap rides on the first packet"250+ "{head} silent packets for half a second of leading hole"
246 );251 );
247 }252 }
crates/engine/tests/export.rsmodified+39 -19
@@ -33,8 +33,10 @@ fn asset(name: &str) -> PathBuf {
33 .join(name)33 .join(name)
34 }34 }
35 35
36+/// Per-run unique: two suite runs at once (a release sweep beside a debug one,
37+/// or two agents) would otherwise write and delete each other's export.
36 fn out_path(name: &str) -> PathBuf {38 fn out_path(name: &str) -> PathBuf {
37- let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4"));39+ let path = std::env::temp_dir().join(format!("ve_export_{name}_{}.mp4", std::process::id()));
38 let _ = std::fs::remove_file(&path);40 let _ = std::fs::remove_file(&path);
39 let _ = std::fs::remove_file(part_path(&path));41 let _ = std::fs::remove_file(part_path(&path));
40 path42 path
@@ -552,9 +554,9 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<
552 554
553 /// A timeline with a hole in each lane, exported. The video gap is encoded as555 /// A timeline with a hole in each lane, exported. The video gap is encoded as
554 /// black rather than skipped -- the file is as long as the timeline, frame for556 /// black rather than skipped -- the file is as long as the timeline, frame for
555-/// frame -- and the audio gap is spent as sample-table duration, so the audio557+/// frame -- and the audio gap is copied as real silent packets, so the audio
556-/// track still covers the whole timeline inside the bresenham bound instead of558+/// track covers the whole timeline inside the bresenham bound instead of ending
557-/// ending a second early.559+/// a second early.
558 #[test]560 #[test]
559 fn exports_a_gapped_timeline_as_black_and_silence() {561 fn exports_a_gapped_timeline_as_black_and_silence() {
560 pin_software();562 pin_software();
@@ -599,24 +601,42 @@ fn exports_a_gapped_timeline_as_black_and_silence() {
599 let lit = mean_abs_diff(&pictures[0], &black);601 let lit = mean_abs_diff(&pictures[0], &black);
600 assert!(lit > 4.0, "the clips around the gap came out black too");602 assert!(lit > 4.0, "the clips around the gap came out black too");
601 603
602- // The audio track still spans the whole timeline: the gap paid its way in604+ // The audio track spans the whole timeline in packets: the hole is real
603- // stts duration, so nothing after it moved earlier.605+ // silent access units, so the bresenham bound the copier promises -- half a
606+ // packet per join, carried through the gap -- covers the gap too.
604 let file = File::open(&out).unwrap();607 let file = File::open(&out).unwrap();
605 let size = file.metadata().unwrap().len();608 let size = file.metadata().unwrap().len();
606 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();609 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
607- let track = &reader.tracks()[&2];610+ let count = reader.sample_count(2).expect("audio track");
608- let duration = track.duration().as_secs_f64();611+ let samples = f64::from(count * 1024);
609- println!("gapped export: audio track {duration:.3}s for a {timeline:.3}s timeline");612+ let wanted = timeline * 44_100.0;
610- assert!(613+ println!("gapped export: {count} packets = {samples} samples for {wanted}");
611- (duration - timeline).abs() < 3.0 * 1024.0 / 44_100.0,
612- "audio track is {duration:.3}s, timeline {timeline:.3}s"
613- );
614- // ...and the packets themselves cover only the audible four seconds, within
615- // the same half-packet-per-join bound the copier promises.
616- let packets = f64::from(reader.sample_count(2).expect("audio track") * 1024);
617- let audible = (timeline - 1.0) * 44_100.0;
618 assert!(614 assert!(
619- (packets - audible).abs() < 3.0 * 1024.0,615+ (samples - wanted).abs() < 3.0 * 1024.0,
620- "{packets} samples copied for {audible} audible ones"616+ "audio length {samples} drifted from {wanted} across the gap"
621 );617 );
618+
619+ // ...and the silence is really silent, where the lift was.
620+ let (_, chunks) = engine::AudioSession::open(&out)
621+ .expect("reopen export audio")
622+ .expect("export has an audio track");
623+ let mut pcm: Vec<f32> = Vec::new();
624+ while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) {
625+ pcm.resize(chunk.start_sample as usize * 2, 0.0);
626+ pcm.extend_from_slice(&chunk.samples);
627+ }
628+ let window = |from: f64, to: f64| {
629+ let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2);
630+ pcm[a.min(pcm.len())..b.min(pcm.len())]
631+ .iter()
632+ .fold(0.0f32, |m, s| m.max(s.abs()))
633+ };
634+ // Inside the hole, off its own edges: AAC is lapped, so the packets either
635+ // side of a splice carry a little of their neighbour.
636+ let quiet = window(1.2, 1.8);
637+ assert!(quiet < 1e-3, "the gap is not silent: {quiet}");
638+ assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing");
639+ assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing");
640+
641+ std::fs::remove_file(&out).unwrap();
622 }642 }