forge
Explore
Log in

Don't you dare go Hollow

Clips primitives — edit-list model, bounded decode, segmented audio

Browse files at this commit

e75a7ba02d98fe360fac4bcceb2c7de92e093f9dAhmet Kaan GümüşParent: e259516
  • feat
    • clips primitives — edit-list model, bounded decode, segmented audio
Show full message
✨ feat(engine): clips primitives — edit-list model, bounded decode, segmented audio

Lane 1 of the clips slice; PlaybackSession traversal comes next.

- project.rs: Clip/Project — cut (metadata-only, refuses no-op
  splits), delete (closes gap, keeps ≥1 clip), undo snapshots,
  timeline↔source mapping with boundary sweep tests
- decode: open_range(start, end) — both backends stop after end-1,
  empty/inverted ranges disconnect cleanly without spawning a worker
- audio: open_segments — one worker walks the edit list; segments
  bit-exact vs equivalent seeks, joins gapless by contiguity assert,
  head+tail trim inside a single AAC packet handled
crates/engine/src/audio.rsmodified+140 -72
@@ -62,6 +62,24 @@ impl AudioSession {
6262 pub fn open_at(
6363 path: impl AsRef<Path>,
6464 start_secs: f64,
65+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
66+ Self::open_segments(path, &[(start_secs, f64::INFINITY)])
67+ }
68+
69+ /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds —
70+ /// back to back as one continuous stream: the chunks carry no gap at a join,
71+ /// so pouring them into a ring is seamless. Each segment gets a fresh
72+ /// decoder and its own pre-roll, which makes a seeked segment perceptually
73+ /// but not bit-exactly equal to the same window of a full run (perceptual
74+ /// noise substitution reseeds; measured below 1e-3).
75+ ///
76+ /// `start_sample` counts from the *first* segment's own audible start, so a
77+ /// single segment reads as absolute media time (what [`open_at`](Self::open_at)
78+ /// promises) and a list reads as one timeline. Segment ends past the track
79+ /// are capped; an empty list is a valid session with no chunks.
80+ pub fn open_segments(
81+ path: impl AsRef<Path>,
82+ segs: &[(f64, f64)],
6583 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
6684 let file = File::open(path.as_ref())?;
6785 let size = file.metadata()?.len();
@@ -104,29 +122,44 @@ impl AudioSession {
104122 .for_codec(CODEC_ID_AAC)
105123 .with_sample_rate(sample_rate)
106124 .with_extra_data(audio_specific_config(track)?);
107- let decoder = AacDecoder::try_new(&params, &AudioDecoderOptions::default())?;
108-
109- // Where to land, in media samples (priming included, so it is directly
110- // comparable to decoded position), and which packet holds it.
111- let media_target = (start_secs * f64::from(sample_rate)) as u64 + priming;
112- let target_ts = unscale(media_target, sample_rate, track.timescale());
113- // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
114- // packet to cancel aliasing, plus one more to warm the decoder up. Their
115- // output is discarded below, so this only costs decode time.
116- let (start_id, start_ts) = packet_at(
117- track
118- .trak
119- .mdia
120- .minf
121- .stbl
122- .stts
123- .entries
124- .iter()
125- .map(|e| (e.sample_count, e.sample_delta)),
126- target_ts,
127- PRE_ROLL,
128- );
129- let start_pos = scale(start_ts, sample_rate, track.timescale()).unwrap_or(0);
125+ // Built here only so an undecodable stream is an `Err` from the opener
126+ // rather than a silently empty channel; the worker makes its own.
127+ AacDecoder::try_new(&params, &AudioDecoderOptions::default())?;
128+
129+ // Segment bounds in media samples (priming included, so they compare
130+ // directly against the decoded position). `f64::INFINITY` saturates.
131+ let media = |secs: f64| ((secs * f64::from(sample_rate)) as u64).saturating_add(priming);
132+ let segments: Vec<Segment> = segs
133+ .iter()
134+ .map(|&(start_secs, end_secs)| {
135+ let media_target = media(start_secs);
136+ let target_ts = unscale(media_target, sample_rate, track.timescale());
137+ // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the
138+ // previous packet to cancel aliasing, plus one more to warm the
139+ // decoder up. Their output is discarded below, so this only
140+ // costs decode time.
141+ let (start_id, start_ts) = packet_at(
142+ track
143+ .trak
144+ .mdia
145+ .minf
146+ .stbl
147+ .stts
148+ .entries
149+ .iter()
150+ .map(|e| (e.sample_count, e.sample_delta)),
151+ target_ts,
152+ PRE_ROLL,
153+ );
154+ Segment {
155+ start_id,
156+ start_pos: scale(start_ts, sample_rate, track.timescale()).unwrap_or(0),
157+ media_target,
158+ // An inverted segment is an empty one, never a backwards run.
159+ media_end: media(end_secs).max(media_target),
160+ }
161+ })
162+ .collect();
130163
131164 let sample_count = reader.sample_count(track_id)?;
132165 let meta = AudioMeta {
@@ -143,14 +176,12 @@ impl AudioSession {
143176 .spawn(move || {
144177 run(Worker {
145178 reader,
146- decoder,
179+ params,
147180 track_id,
148181 sample_count,
149182 channels: channels as usize,
150183 priming,
151- start_id,
152- start_pos,
153- media_target,
184+ segments,
154185 tx,
155186 })
156187 })?;
@@ -258,13 +289,8 @@ fn packet_at(
258289 last
259290 }
260291
261-struct Worker {
262- reader: Mp4Reader<BufReader<File>>,
263- decoder: AacDecoder,
264- track_id: u32,
265- sample_count: u32,
266- channels: usize,
267- priming: u64,
292+/// One window of the source to decode, resolved to media samples and packets.
293+struct Segment {
268294 /// First packet to feed the decoder, 1-based; includes the pre-roll.
269295 start_id: u32,
270296 /// Media position of `start_id`'s first frame, in samples-per-channel.
@@ -272,56 +298,98 @@ struct Worker {
272298 /// Media position of the first frame to emit. Everything decoded before it
273299 /// is pre-roll, priming, or seek overshoot, and gets dropped.
274300 media_target: u64,
301+ /// One past the last frame to emit; `u64::MAX` for "to the end of track".
302+ media_end: u64,
303+}
304+
305+struct Worker {
306+ reader: Mp4Reader<BufReader<File>>,
307+ /// A fresh decoder is built from these per segment: seeking mid-stream
308+ /// leaves MDCT and PNS state that belongs to the packets we skipped.
309+ params: AudioCodecParameters,
310+ track_id: u32,
311+ sample_count: u32,
312+ channels: usize,
313+ priming: u64,
314+ segments: Vec<Segment>,
275315 tx: SyncSender<AudioChunk>,
276316 }
277317
278318 fn run(mut w: Worker) {
279319 let mut interleaved = Vec::new();
280- let mut pos = w.start_pos;
320+ // Chunk numbering is continuous across the segment joins, counted from the
321+ // first segment's audible start (see `open_segments`).
322+ let mut timeline = w
323+ .segments
324+ .first()
325+ .map_or(0, |s| s.media_target.saturating_sub(w.priming));
281326
282- for id in w.start_id..=w.sample_count {
283- let sample = match w.reader.read_sample(w.track_id, id) {
284- Ok(Some(sample)) => sample,
285- Ok(None) => break,
327+ for seg in &w.segments {
328+ let mut decoder = match AacDecoder::try_new(&w.params, &AudioDecoderOptions::default()) {
329+ Ok(decoder) => decoder,
286330 Err(e) => {
287- eprintln!("audio demux error at sample {id}: {e}");
288- break;
331+ eprintln!("audio decoder init failed: {e}");
332+ return;
289333 }
290334 };
291- let packet = Packet::new(
292- w.track_id,
293- units::Timestamp::new(sample.start_time as i64),
294- units::Duration::new(u64::from(sample.duration)),
295- &sample.bytes[..],
296- );
297- let buf = match w.decoder.decode(&packet) {
298- Ok(buf) => buf,
299- Err(e) => {
300- eprintln!("audio decode error at sample {id}: {e}");
301- break;
335+ let mut pos = seg.start_pos;
336+
337+ for id in seg.start_id..=w.sample_count {
338+ if pos >= seg.media_end {
339+ break; // segment done, on to the next one
302340 }
303- };
304- buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
305- let next = pos + (interleaved.len() / w.channels) as u64;
341+ let sample = match w.reader.read_sample(w.track_id, id) {
342+ Ok(Some(sample)) => sample,
343+ Ok(None) => break,
344+ Err(e) => {
345+ eprintln!("audio demux error at sample {id}: {e}");
346+ break;
347+ }
348+ };
349+ let packet = Packet::new(
350+ w.track_id,
351+ units::Timestamp::new(sample.start_time as i64),
352+ units::Duration::new(u64::from(sample.duration)),
353+ &sample.bytes[..],
354+ );
355+ let buf = match decoder.decode(&packet) {
356+ Ok(buf) => buf,
357+ Err(e) => {
358+ eprintln!("audio decode error at sample {id}: {e}");
359+ break;
360+ }
361+ };
362+ buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
363+ let next = pos + (interleaved.len() / w.channels) as u64;
306364
307- // Everything before the target is encoder priming and/or decoder
308- // pre-roll, not audio the caller asked for: drop it, splitting the
309- // packet that straddles the target.
310- if next <= w.media_target {
365+ // Everything before the target is encoder priming and/or decoder
366+ // pre-roll, not audio the caller asked for: drop it, splitting the
367+ // packet that straddles the target.
368+ if next <= seg.media_target {
369+ pos = next;
370+ continue;
371+ }
372+ if pos < seg.media_target {
373+ interleaved.drain(..(seg.media_target - pos) as usize * w.channels);
374+ pos = seg.media_target;
375+ }
376+ // And the tail past the segment end goes too — on a short segment
377+ // that is this same buffer, trimmed at both ends.
378+ if next > seg.media_end {
379+ interleaved.truncate((seg.media_end - pos) as usize * w.channels);
380+ }
311381 pos = next;
312- continue;
313- }
314- if pos < w.media_target {
315- interleaved.drain(..(w.media_target - pos) as usize * w.channels);
316- pos = w.media_target;
317- }
318- let chunk = AudioChunk {
319- start_sample: pos - w.priming,
320- samples: std::mem::take(&mut interleaved),
321- };
322- pos = next;
323- if w.tx.send(chunk).is_err() {
324- break; // consumer went away
382+ if interleaved.is_empty() {
383+ continue; // nothing left of it; the loop head ends the segment
384+ }
385+ let chunk = AudioChunk {
386+ start_sample: timeline,
387+ samples: std::mem::take(&mut interleaved),
388+ };
389+ timeline += (chunk.samples.len() / w.channels) as u64;
390+ if w.tx.send(chunk).is_err() {
391+ return; // consumer went away
392+ }
325393 }
326394 }
327395 }
crates/engine/src/decode.rsmodified+37 -3
@@ -41,13 +41,34 @@ impl DecodeSession {
4141 pub fn open_at(
4242 path: impl AsRef<Path>,
4343 start_frame: u32,
44+ ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
45+ // `u32::MAX` is clamped to the stream's frame count below, so this is
46+ // "to the end of the file".
47+ Self::open_range(path, start_frame, u32::MAX)
48+ }
49+
50+ /// As [`DecodeSession::open_at`], but the worker also stops on its own
51+ /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
52+ /// absolute source frames, which is what a clip of a longer file needs.
53+ /// `end_frame` is capped at the stream's frame count, and an empty range
54+ /// yields a receiver that is simply already disconnected.
55+ pub fn open_range(
56+ path: impl AsRef<Path>,
57+ start_frame: u32,
58+ end_frame: u32,
4459 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
4560 let path = path.as_ref().to_path_buf();
4661 let (meta, demuxer) = Demuxer::open(&path)?;
62+ let end_frame = end_frame.min(meta.frame_count);
4763 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
4864 // decoder run ahead of the display without limit.
4965 let (tx, rx) = sync_channel(2);
5066 let cancel = Arc::new(AtomicBool::new(false));
67+ if end_frame <= start_frame {
68+ // Nothing to decode: dropping `tx` here closes the channel cleanly,
69+ // so the caller sees an immediate end of stream rather than an error.
70+ return Ok((meta, rx, cancel));
71+ }
5172 let worker_cancel = Arc::clone(&cancel);
5273 thread::Builder::new()
5374 .name("decode".into())
@@ -56,7 +77,7 @@ impl DecodeSession {
5677 // VA-API state is not `Send`-safe across a later hand-off.
5778 if let Some(hw) = open_hw(&path, start_frame) {
5879 eprintln!("decode backend: hardware (VA-API plugin)");
59- if run_hw(hw, &tx, start_frame, &worker_cancel) {
80+ if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) {
6081 return;
6182 }
6283 // A driver that opens but cannot decode a single frame is
@@ -64,7 +85,7 @@ impl DecodeSession {
6485 eprintln!("hardware decode failed before any frame, falling back to software");
6586 }
6687 eprintln!("decode backend: software (rusty_h264)");
67- run(demuxer, tx, start_frame, &worker_cancel)
88+ run(demuxer, tx, start_frame, end_frame, &worker_cancel)
6889 })?;
6990 Ok((meta, rx, cancel))
7091 }
@@ -89,6 +110,7 @@ fn run_hw(
89110 mut hw: HwSession,
90111 tx: &SyncSender<Frame>,
91112 start_frame: u32,
113+ end_frame: u32,
92114 cancel: &AtomicBool,
93115 ) -> bool {
94116 let mut index = start_frame;
@@ -108,6 +130,9 @@ fn run_hw(
108130 if tx.send(frame).is_err() {
109131 return true; // consumer went away
110132 }
133+ if index >= end_frame {
134+ return true; // end of the requested range
135+ }
111136 }
112137 Ok(None) => return true,
113138 Err(e) => {
@@ -121,7 +146,13 @@ fn run_hw(
121146 }
122147 }
123148
124-fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>, start_frame: u32, cancel: &AtomicBool) {
149+fn run(
150+ mut demuxer: Demuxer,
151+ tx: SyncSender<Frame>,
152+ start_frame: u32,
153+ end_frame: u32,
154+ cancel: &AtomicBool,
155+) {
125156 let mut decoder = Decoder::new();
126157 // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at
127158 // a sync sample, so pictures between it and `start_frame` are decoded (the
@@ -165,5 +196,8 @@ fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>, start_frame: u32, cancel: &A
165196 if tx.send(frame).is_err() {
166197 break; // consumer went away
167198 }
199+ if index >= end_frame {
200+ break; // end of the requested range
201+ }
168202 }
169203 }
crates/engine/src/lib.rsmodified+2 -0
@@ -8,12 +8,14 @@ pub mod decode;
88 pub mod demux;
99 pub mod hw;
1010 pub mod playback;
11+pub mod project;
1112
1213 pub use audio::{AudioChunk, AudioMeta, AudioSession};
1314 pub use clock::PlaybackClock;
1415 pub use decode::{DecodeSession, Frame};
1516 pub use demux::VideoMeta;
1617 pub use playback::PlaybackSession;
18+pub use project::{Clip, Project};
1719
1820 /// Boxed error; the engine has few failure modes and every one of them is fatal
1921 /// to the session, so a message is all a caller can act on.
crates/engine/src/project.rsadded+368 -0
@@ -0,0 +1,368 @@
1+//! Edit list: the timeline as a list of source ranges. Pure data, no I/O.
2+//!
3+//! A [`Project`] is an ordered list of [`Clip`]s, each a half-open `[in, out)`
4+//! range of *source* frames. Playing the timeline means playing those ranges
5+//! back to back, so timeline frame `t` is found by walking the clips and
6+//! consuming their lengths; the mapping is [`Project::map_timeline`] and it is
7+//! the only place that conversion lives.
8+//!
9+//! Two frame spaces meet here and are never mixed: *source* frames index the
10+//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
11+//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
12+//!
13+//! Editing is metadata only. [`Project::cut`] splits a clip in two without
14+//! changing any timeline->source mapping, so a running decoder stays correct
15+//! across a cut; [`Project::delete`] does change the mapping and the caller
16+//! must reseek. Every successful edit snapshots the clip list, so
17+//! [`Project::undo`] is an exact restore.
18+
19+/// A half-open `[in_frame, out_frame)` range of source frames. Never empty.
20+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21+pub struct Clip {
22+ pub in_frame: u32,
23+ pub out_frame: u32,
24+}
25+
26+impl Clip {
27+ /// Frame count; `>= 1` by the never-empty invariant.
28+ pub fn len(&self) -> u32 {
29+ self.out_frame - self.in_frame
30+ }
31+}
32+
33+/// The edit list plus its undo history.
34+#[derive(Clone, Debug)]
35+pub struct Project {
36+ clips: Vec<Clip>,
37+ /// Snapshots pushed *before* each successful edit; `undo` pops one.
38+ history: Vec<Vec<Clip>>,
39+}
40+
41+impl Project {
42+ /// One clip covering the whole file -- the state of a freshly opened video,
43+ /// where the timeline is the source. `frame_count` of 0 would break the
44+ /// never-empty invariant, so it is clamped to one frame.
45+ pub fn single(frame_count: u32) -> Self {
46+ Self {
47+ clips: vec![Clip {
48+ in_frame: 0,
49+ out_frame: frame_count.max(1),
50+ }],
51+ history: Vec::new(),
52+ }
53+ }
54+
55+ pub fn clips(&self) -> &[Clip] {
56+ &self.clips
57+ }
58+
59+ /// Length of the timeline in frames.
60+ pub fn timeline_frames(&self) -> u32 {
61+ self.clips.iter().map(Clip::len).sum()
62+ }
63+
64+ /// `(timeline_start, len)` per clip, in order -- what a UI lane needs to
65+ /// lay clips out without redoing the cumulative sum.
66+ pub fn clip_spans(&self) -> Vec<(u32, u32)> {
67+ let mut start = 0;
68+ self.clips
69+ .iter()
70+ .map(|c| {
71+ let span = (start, c.len());
72+ start += c.len();
73+ span
74+ })
75+ .collect()
76+ }
77+
78+ /// Timeline frame -> `(clip index, source frame)`. `None` past the end.
79+ pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
80+ let mut start = 0;
81+ for (i, c) in self.clips.iter().enumerate() {
82+ if timeline_frame < start + c.len() {
83+ return Some((i, c.in_frame + (timeline_frame - start)));
84+ }
85+ start += c.len();
86+ }
87+ None
88+ }
89+
90+ /// Split the clip containing `timeline_frame` so that frame becomes the
91+ /// first frame of a new clip. Refused (`false`, no change) at timeline 0,
92+ /// at an existing clip boundary, and at or past the end -- all three would
93+ /// produce an empty clip. Metadata only: no mapping changes.
94+ pub fn cut(&mut self, timeline_frame: u32) -> bool {
95+ let Some((idx, source)) = self.map_timeline(timeline_frame) else {
96+ return false;
97+ };
98+ if source == self.clips[idx].in_frame {
99+ return false; // start of a clip: nothing to split off
100+ }
101+ self.history.push(self.clips.clone());
102+ let out = self.clips[idx].out_frame;
103+ self.clips[idx].out_frame = source;
104+ self.clips.insert(
105+ idx + 1,
106+ Clip {
107+ in_frame: source,
108+ out_frame: out,
109+ },
110+ );
111+ true
112+ }
113+
114+ /// Remove a clip and close the gap. Refused for an out-of-range index and
115+ /// for the last remaining clip (an empty timeline is undefined this slice).
116+ /// Changes the timeline->source mapping: the caller must reseek.
117+ pub fn delete(&mut self, idx: usize) -> bool {
118+ if idx >= self.clips.len() || self.clips.len() == 1 {
119+ return false;
120+ }
121+ self.history.push(self.clips.clone());
122+ self.clips.remove(idx);
123+ true
124+ }
125+
126+ /// Restore the clip list from before the last successful edit. `false` when
127+ /// there is nothing left to undo.
128+ pub fn undo(&mut self) -> bool {
129+ match self.history.pop() {
130+ Some(prev) => {
131+ self.clips = prev;
132+ true
133+ }
134+ None => false,
135+ }
136+ }
137+
138+ /// Half-open `(start, end)` segments in *source* seconds, from
139+ /// `timeline_frame` to the end of the timeline -- the play list for the
140+ /// audio worker. The first entry is partial when the position is mid-clip.
141+ /// Empty when the position is past the end or `fps` is not usable.
142+ pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(f64, f64)> {
143+ if !(fps.is_finite() && fps > 0.0) {
144+ return Vec::new();
145+ }
146+ let Some((idx, source)) = self.map_timeline(timeline_frame) else {
147+ return Vec::new();
148+ };
149+ let mut segs = vec![(source as f64 / fps, self.clips[idx].out_frame as f64 / fps)];
150+ segs.extend(
151+ self.clips[idx + 1..]
152+ .iter()
153+ .map(|c| (c.in_frame as f64 / fps, c.out_frame as f64 / fps)),
154+ );
155+ segs
156+ }
157+}
158+
159+#[cfg(test)]
160+mod tests {
161+ use super::*;
162+
163+ const FPS: f64 = 30.0;
164+
165+ /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built
166+ /// through `cut` so the constructor path is exercised too.
167+ fn three() -> Project {
168+ let mut p = Project::single(9);
169+ assert!(p.cut(3));
170+ assert!(p.cut(5));
171+ assert_eq!(
172+ p.clips(),
173+ [
174+ Clip {
175+ in_frame: 0,
176+ out_frame: 3
177+ },
178+ Clip {
179+ in_frame: 3,
180+ out_frame: 5
181+ },
182+ Clip {
183+ in_frame: 5,
184+ out_frame: 9
185+ },
186+ ]
187+ );
188+ p
189+ }
190+
191+ #[test]
192+ fn single_is_the_whole_file() {
193+ let p = Project::single(150);
194+ assert_eq!(p.clips().len(), 1);
195+ assert_eq!(p.timeline_frames(), 150);
196+ assert_eq!(p.clip_spans(), vec![(0, 150)]);
197+ // degenerate mapping: timeline == source
198+ assert_eq!(p.map_timeline(0), Some((0, 0)));
199+ assert_eq!(p.map_timeline(149), Some((0, 149)));
200+ assert_eq!(p.map_timeline(150), None);
201+ // never-empty invariant survives a bogus frame count
202+ assert_eq!(Project::single(0).timeline_frames(), 1);
203+ }
204+
205+ #[test]
206+ fn cut_mid_clip_splits() {
207+ let mut p = Project::single(9);
208+ assert!(p.cut(4));
209+ assert_eq!(
210+ p.clips(),
211+ [
212+ Clip {
213+ in_frame: 0,
214+ out_frame: 4
215+ },
216+ Clip {
217+ in_frame: 4,
218+ out_frame: 9
219+ },
220+ ]
221+ );
222+ assert_eq!(p.timeline_frames(), 9);
223+ }
224+
225+ #[test]
226+ fn cut_refused_at_zero_boundary_and_end() {
227+ let mut p = three();
228+ let before = p.clips().to_vec();
229+ assert!(!p.cut(0), "timeline 0 has nothing before it");
230+ assert!(!p.cut(3), "existing boundary");
231+ assert!(!p.cut(5), "existing boundary");
232+ assert!(!p.cut(9), "one past the last frame");
233+ assert!(!p.cut(1_000));
234+ assert_eq!(p.clips(), before.as_slice());
235+ // one undo lands before the *second* cut, so the refusals pushed nothing
236+ assert!(p.undo());
237+ assert_eq!(p.clips().len(), 2, "refused cuts push no history");
238+ }
239+
240+ #[test]
241+ fn cut_never_changes_the_mapping() {
242+ let p = three();
243+ let before: Vec<_> = (0..9).map(|f| p.map_timeline(f).unwrap().1).collect();
244+ let mut after = p.clone();
245+ assert!(after.cut(7));
246+ let now: Vec<_> = (0..9).map(|f| after.map_timeline(f).unwrap().1).collect();
247+ assert_eq!(before, now);
248+ }
249+
250+ #[test]
251+ fn map_timeline_sweeps_every_boundary() {
252+ let p = three();
253+ assert_eq!(p.timeline_frames(), 9);
254+ assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
255+ // contiguous source here, so the clip index is what actually moves
256+ let expect = [
257+ (0, (0, 0)),
258+ (1, (0, 1)),
259+ (2, (0, 2)),
260+ (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
261+ (4, (1, 4)),
262+ (5, (2, 5)),
263+ (6, (2, 6)),
264+ (7, (2, 7)),
265+ (8, (2, 8)),
266+ ];
267+ for (t, want) in expect {
268+ assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
269+ }
270+ assert_eq!(p.map_timeline(9), None);
271+ }
272+
273+ #[test]
274+ fn delete_closes_the_gap() {
275+ let mut p = three();
276+ assert!(p.delete(1));
277+ assert_eq!(p.timeline_frames(), 7);
278+ assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
279+ // timeline 3 used to be source 3; the gap closed so it is source 5 now
280+ assert_eq!(p.map_timeline(3), Some((1, 5)));
281+ assert_eq!(p.map_timeline(6), Some((1, 8)));
282+ assert_eq!(p.map_timeline(7), None);
283+ }
284+
285+ #[test]
286+ fn delete_first_last_and_only() {
287+ let mut p = three();
288+ assert!(p.delete(0));
289+ assert_eq!(p.map_timeline(0), Some((0, 3)));
290+ assert_eq!(p.timeline_frames(), 6);
291+
292+ let mut p = three();
293+ assert!(p.delete(2));
294+ assert_eq!(p.timeline_frames(), 5);
295+ assert_eq!(p.map_timeline(4), Some((1, 4)));
296+
297+ assert!(!p.delete(2), "index past the end");
298+ assert!(p.delete(1));
299+ assert!(!p.delete(0), "the last remaining clip stays");
300+ assert_eq!(p.clips().len(), 1);
301+ }
302+
303+ #[test]
304+ fn undo_restores_exactly() {
305+ let mut p = three();
306+ let after_cuts = p.clips().to_vec();
307+ assert!(p.delete(1));
308+ assert!(p.undo());
309+ assert_eq!(p.clips(), after_cuts.as_slice());
310+
311+ // walk all the way back through both cuts, then run dry
312+ assert!(p.undo());
313+ assert_eq!(p.clips().len(), 2);
314+ assert!(p.undo());
315+ assert_eq!(
316+ p.clips(),
317+ [Clip {
318+ in_frame: 0,
319+ out_frame: 9
320+ }]
321+ );
322+ assert!(!p.undo(), "empty history");
323+ assert_eq!(
324+ p.clips(),
325+ [Clip {
326+ in_frame: 0,
327+ out_frame: 9
328+ }]
329+ );
330+ }
331+
332+ #[test]
333+ fn segments_from_trims_the_first_entry() {
334+ let p = three();
335+ // mid-clip: partial first segment, whole clips after it
336+ assert_eq!(
337+ p.segments_from(4, FPS),
338+ vec![(4.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)]
339+ );
340+ // on a boundary: nothing partial
341+ assert_eq!(
342+ p.segments_from(3, FPS),
343+ vec![(3.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)]
344+ );
345+ // from the top: one entry per clip
346+ assert_eq!(p.segments_from(0, FPS).len(), 3);
347+ // last clip only
348+ assert_eq!(p.segments_from(8, FPS), vec![(8.0 / 30.0, 0.3)]);
349+ // past the end / unusable fps
350+ assert!(p.segments_from(9, FPS).is_empty());
351+ assert!(p.segments_from(0, 0.0).is_empty());
352+ assert!(p.segments_from(0, f64::NAN).is_empty());
353+ }
354+
355+ #[test]
356+ fn segments_follow_deletes_and_fps() {
357+ let mut p = three();
358+ assert!(p.delete(0));
359+ // source seconds, not timeline: deleting the head does not shift them
360+ let segs = p.segments_from(0, 25.0);
361+ assert_eq!(segs, vec![(3.0 / 25.0, 0.2), (0.2, 9.0 / 25.0)]);
362+ let played: f64 = segs.iter().map(|(a, b)| b - a).sum();
363+ assert!(
364+ (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
365+ "segments must cover exactly the timeline: {played}"
366+ );
367+ }
368+}
crates/engine/tests/audio_segments.rsadded+136 -0
@@ -0,0 +1,136 @@
1+//! `AudioSession::open_segments` must pour source windows back to back: each
2+//! segment equal to the matching window of a plain `open_at`, `start_sample`
3+//! continuous across the join, and the trims exact down to a sub-packet clip.
4+
5+use std::path::PathBuf;
6+use std::sync::mpsc::Receiver;
7+
8+use engine::audio::{AudioChunk, AudioSession};
9+
10+const RATE: u64 = 44100;
11+const CHANNELS: usize = 2;
12+/// One AAC-LC packet, in frames per channel.
13+const PACKET: u64 = 1024;
14+
15+fn asset() -> PathBuf {
16+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4")
17+}
18+
19+/// Drains a session flat, asserting chunks are contiguous, and reports the
20+/// first chunk's `start_sample` plus how many chunks arrived.
21+fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) {
22+ let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize);
23+ for AudioChunk {
24+ start_sample,
25+ samples: s,
26+ } in rx
27+ {
28+ assert!(!s.is_empty(), "empty chunk {chunks}");
29+ let want = first.unwrap_or(start_sample) + (samples.len() / CHANNELS) as u64;
30+ assert_eq!(start_sample, want, "gap or overlap before chunk {chunks}");
31+ first.get_or_insert(start_sample);
32+ samples.extend(s);
33+ chunks += 1;
34+ }
35+ (samples, first.unwrap_or(0), chunks)
36+}
37+
38+fn segments(segs: &[(f64, f64)]) -> (Vec<f32>, u64, usize) {
39+ let (_, rx) = AudioSession::open_segments(asset(), segs)
40+ .expect("open")
41+ .expect("test_av.mp4 has an audio track");
42+ drain(rx)
43+}
44+
45+/// The first `frames` per channel of a plain `open_at(start)`.
46+fn window(start: f64, frames: u64) -> Vec<f32> {
47+ let (_, rx) = AudioSession::open_at(asset(), start).unwrap().unwrap();
48+ let (mut samples, _, _) = drain(rx);
49+ assert!(samples.len() >= frames as usize * CHANNELS, "short window");
50+ samples.truncate(frames as usize * CHANNELS);
51+ samples
52+}
53+
54+/// Largest per-sample difference, and where it is.
55+fn max_diff(a: &[f32], b: &[f32]) -> (f32, usize) {
56+ assert_eq!(a.len(), b.len(), "length mismatch");
57+ a.iter()
58+ .zip(b)
59+ .enumerate()
60+ .map(|(i, (x, y))| ((x - y).abs(), i))
61+ .fold((0.0, 0), |m, d| if d.0 > m.0 { d } else { m })
62+}
63+
64+/// Perceptual noise substitution reseeds per decoder, so a segment can never be
65+/// promised bit-exact against another run (engine/src/audio.rs docs, ledger).
66+fn assert_close(got: &[f32], want: &[f32], what: &str) {
67+ let (diff, at) = max_diff(got, want);
68+ eprintln!(
69+ "{what}: max abs diff {diff:e} at sample {at} of {}",
70+ got.len()
71+ );
72+ assert!(diff < 1e-3, "{what}: max abs diff {diff} at sample {at}");
73+}
74+
75+#[test]
76+fn two_segments_concat() {
77+ let (got, first, chunks) = segments(&[(1.0, 2.0), (3.0, 4.0)]);
78+ // `drain` already proved every chunk butts against the previous one, so a
79+ // full-length run is a joint with no gap and no overlap.
80+ assert_eq!(first, RATE, "numbering starts at the first segment's start");
81+ assert_eq!(
82+ got.len() as u64 / CHANNELS as u64,
83+ 2 * RATE,
84+ "{chunks} chunks"
85+ );
86+
87+ let want: Vec<f32> = [window(1.0, RATE), window(3.0, RATE)].concat();
88+ assert_close(&got, &want, "two segments");
89+}
90+
91+#[test]
92+fn tiny_segment_is_one_frame_long() {
93+ // A single 30 fps video frame's worth of audio: 1470 samples per channel,
94+ // decoded from two packets and trimmed at both.
95+ let (got, first, chunks) = segments(&[(1.0, 1.0 + 1.0 / 30.0)]);
96+ assert_eq!(first, RATE);
97+ assert_eq!(got.len() as u64 / CHANNELS as u64, 1470, "{chunks} chunks");
98+ assert_close(&got, &window(1.0, 1470), "one video frame");
99+}
100+
101+#[test]
102+fn sub_packet_segment_trims_one_buffer_at_both_ends() {
103+ // 441 samples starting 44100 in: with priming that is media 45124..45565,
104+ // both inside packet 45 ([45056, 46080)), so the head trim and the tail trim
105+ // hit the same decoded buffer.
106+ let (got, first, chunks) = segments(&[(1.0, 1.01)]);
107+ assert_eq!(first, RATE);
108+ assert_eq!(got.len() as u64 / CHANNELS as u64, 441);
109+ assert_eq!(chunks, 1, "both trims must land in one decoded buffer");
110+ assert_close(&got, &window(1.0, 441), "sub-packet segment");
111+}
112+
113+#[test]
114+fn segment_past_the_end_is_capped() {
115+ // test_av.mp4 is 5 s: the ask runs 55 s past the track and must simply stop.
116+ let (got, first, _) = segments(&[(4.0, 60.0)]);
117+ assert_eq!(first, 4 * RATE);
118+ let frames = got.len() as u64 / CHANNELS as u64;
119+ assert!(
120+ (RATE..=RATE + PACKET).contains(&frames),
121+ "{frames} frames for the last second (+0..={PACKET} tail padding)"
122+ );
123+}
124+
125+#[test]
126+fn no_segments_ends_clean() {
127+ let (meta, rx) = AudioSession::open_segments(asset(), &[])
128+ .expect("open")
129+ .expect("test_av.mp4 has an audio track");
130+ assert_eq!(meta.sample_rate as u64, RATE);
131+ assert_eq!(
132+ rx.into_iter().count(),
133+ 0,
134+ "an empty edit list decodes nothing"
135+ );
136+}
crates/engine/tests/hw_decode.rsmodified+36 -0
@@ -123,6 +123,42 @@ fn seek_matches_linear() {
123123 );
124124 }
125125
126+/// Drains a bounded session, returning the indices it delivered. The loop ends
127+/// only on `RecvError`, i.e. the worker closed the channel by itself.
128+fn range_indices(path: &Path, start: u32, end: u32) -> Vec<u32> {
129+ let (_, rx, _cancel) = DecodeSession::open_range(path, start, end).expect("open_range");
130+ let mut got = Vec::new();
131+ while let Ok(frame) = rx.recv() {
132+ got.push(frame.index);
133+ }
134+ got
135+}
136+
137+/// A bounded range must stop on its own — both backends — with `Frame::index`
138+/// still the absolute source index, and then disconnect rather than hang.
139+#[test]
140+#[ignore = "needs libengine_hw.so and a VA-API driver"]
141+fn range_stops_at_end() {
142+ const START: u32 = 30;
143+ const END: u32 = 60;
144+ let path = asset("test_baseline.mp4");
145+ let want: Vec<u32> = (START..END).collect();
146+
147+ // Another test in this binary may already have pinned VE_SW; clear it so
148+ // the hardware half really is hardware. SAFETY: --test-threads=1.
149+ unsafe { std::env::remove_var("VE_SW") };
150+ assert_eq!(range_indices(&path, START, END), want, "hardware range");
151+
152+ unsafe { std::env::set_var("VE_SW", "1") };
153+ assert_eq!(range_indices(&path, START, END), want, "software range");
154+
155+ // Degenerate ranges close cleanly instead of decoding to EOF.
156+ assert!(range_indices(&path, 30, 30).is_empty(), "empty range");
157+ assert!(range_indices(&path, 60, 30).is_empty(), "inverted range");
158+ // Past the end is clamped to the frame count.
159+ assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range");
160+}
161+
126162 /// H.264 8-bit decode is bit-exact by conformance, so the two backends must
127163 /// agree. A mismatch means a driver deviation and is reported, not swallowed.
128164 #[test]