diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index b61fd1d..c58cd6b 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -62,6 +62,24 @@ impl AudioSession { pub fn open_at( path: impl AsRef, start_secs: f64, + ) -> crate::Result)>> { + Self::open_segments(path, &[(start_secs, f64::INFINITY)]) + } + + /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds — + /// back to back as one continuous stream: the chunks carry no gap at a join, + /// so pouring them into a ring is seamless. Each segment gets a fresh + /// decoder and its own pre-roll, which makes a seeked segment perceptually + /// but not bit-exactly equal to the same window of a full run (perceptual + /// noise substitution reseeds; measured below 1e-3). + /// + /// `start_sample` counts from the *first* segment's own audible start, so a + /// single segment reads as absolute media time (what [`open_at`](Self::open_at) + /// promises) and a list reads as one timeline. Segment ends past the track + /// are capped; an empty list is a valid session with no chunks. + pub fn open_segments( + path: impl AsRef, + segs: &[(f64, f64)], ) -> crate::Result)>> { let file = File::open(path.as_ref())?; let size = file.metadata()?.len(); @@ -104,29 +122,44 @@ impl AudioSession { .for_codec(CODEC_ID_AAC) .with_sample_rate(sample_rate) .with_extra_data(audio_specific_config(track)?); - let decoder = AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())?; - - // Where to land, in media samples (priming included, so it is directly - // comparable to decoded position), and which packet holds it. - let media_target = (start_secs * f64::from(sample_rate)) as u64 + priming; - let target_ts = unscale(media_target, sample_rate, track.timescale()); - // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous - // packet to cancel aliasing, plus one more to warm the decoder up. Their - // output is discarded below, so this only costs decode time. - let (start_id, start_ts) = packet_at( - track - .trak - .mdia - .minf - .stbl - .stts - .entries - .iter() - .map(|e| (e.sample_count, e.sample_delta)), - target_ts, - PRE_ROLL, - ); - let start_pos = scale(start_ts, sample_rate, track.timescale()).unwrap_or(0); + // Built here only so an undecodable stream is an `Err` from the opener + // rather than a silently empty channel; the worker makes its own. + AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())?; + + // Segment bounds in media samples (priming included, so they compare + // directly against the decoded position). `f64::INFINITY` saturates. + let media = |secs: f64| ((secs * f64::from(sample_rate)) as u64).saturating_add(priming); + let segments: Vec = segs + .iter() + .map(|&(start_secs, end_secs)| { + let media_target = media(start_secs); + let target_ts = unscale(media_target, sample_rate, track.timescale()); + // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the + // previous packet to cancel aliasing, plus one more to warm the + // decoder up. Their output is discarded below, so this only + // costs decode time. + let (start_id, start_ts) = packet_at( + track + .trak + .mdia + .minf + .stbl + .stts + .entries + .iter() + .map(|e| (e.sample_count, e.sample_delta)), + target_ts, + PRE_ROLL, + ); + Segment { + start_id, + start_pos: scale(start_ts, sample_rate, track.timescale()).unwrap_or(0), + media_target, + // An inverted segment is an empty one, never a backwards run. + media_end: media(end_secs).max(media_target), + } + }) + .collect(); let sample_count = reader.sample_count(track_id)?; let meta = AudioMeta { @@ -143,14 +176,12 @@ impl AudioSession { .spawn(move || { run(Worker { reader, - decoder, + params, track_id, sample_count, channels: channels as usize, priming, - start_id, - start_pos, - media_target, + segments, tx, }) })?; @@ -258,13 +289,8 @@ fn packet_at( last } -struct Worker { - reader: Mp4Reader>, - decoder: AacDecoder, - track_id: u32, - sample_count: u32, - channels: usize, - priming: u64, +/// One window of the source to decode, resolved to media samples and packets. +struct Segment { /// First packet to feed the decoder, 1-based; includes the pre-roll. start_id: u32, /// Media position of `start_id`'s first frame, in samples-per-channel. @@ -272,56 +298,98 @@ struct Worker { /// Media position of the first frame to emit. Everything decoded before it /// is pre-roll, priming, or seek overshoot, and gets dropped. media_target: u64, + /// One past the last frame to emit; `u64::MAX` for "to the end of track". + media_end: u64, +} + +struct Worker { + reader: Mp4Reader>, + /// A fresh decoder is built from these per segment: seeking mid-stream + /// leaves MDCT and PNS state that belongs to the packets we skipped. + params: AudioCodecParameters, + track_id: u32, + sample_count: u32, + channels: usize, + priming: u64, + segments: Vec, tx: SyncSender, } fn run(mut w: Worker) { let mut interleaved = Vec::new(); - let mut pos = w.start_pos; + // Chunk numbering is continuous across the segment joins, counted from the + // first segment's audible start (see `open_segments`). + let mut timeline = w + .segments + .first() + .map_or(0, |s| s.media_target.saturating_sub(w.priming)); - for id in w.start_id..=w.sample_count { - let sample = match w.reader.read_sample(w.track_id, id) { - Ok(Some(sample)) => sample, - Ok(None) => break, + for seg in &w.segments { + let mut decoder = match AacDecoder::try_new(&w.params, &AudioDecoderOptions::default()) { + Ok(decoder) => decoder, Err(e) => { - eprintln!("audio demux error at sample {id}: {e}"); - break; + eprintln!("audio decoder init failed: {e}"); + return; } }; - let packet = Packet::new( - w.track_id, - units::Timestamp::new(sample.start_time as i64), - units::Duration::new(u64::from(sample.duration)), - &sample.bytes[..], - ); - let buf = match w.decoder.decode(&packet) { - Ok(buf) => buf, - Err(e) => { - eprintln!("audio decode error at sample {id}: {e}"); - break; + let mut pos = seg.start_pos; + + for id in seg.start_id..=w.sample_count { + if pos >= seg.media_end { + break; // segment done, on to the next one } - }; - buf.copy_to_vec_interleaved::(&mut interleaved); - let next = pos + (interleaved.len() / w.channels) as u64; + let sample = match w.reader.read_sample(w.track_id, id) { + Ok(Some(sample)) => sample, + Ok(None) => break, + Err(e) => { + eprintln!("audio demux error at sample {id}: {e}"); + break; + } + }; + let packet = Packet::new( + w.track_id, + units::Timestamp::new(sample.start_time as i64), + units::Duration::new(u64::from(sample.duration)), + &sample.bytes[..], + ); + let buf = match decoder.decode(&packet) { + Ok(buf) => buf, + Err(e) => { + eprintln!("audio decode error at sample {id}: {e}"); + break; + } + }; + buf.copy_to_vec_interleaved::(&mut interleaved); + let next = pos + (interleaved.len() / w.channels) as u64; - // Everything before the target is encoder priming and/or decoder - // pre-roll, not audio the caller asked for: drop it, splitting the - // packet that straddles the target. - if next <= w.media_target { + // Everything before the target is encoder priming and/or decoder + // pre-roll, not audio the caller asked for: drop it, splitting the + // packet that straddles the target. + if next <= seg.media_target { + pos = next; + continue; + } + if pos < seg.media_target { + interleaved.drain(..(seg.media_target - pos) as usize * w.channels); + pos = seg.media_target; + } + // And the tail past the segment end goes too — on a short segment + // that is this same buffer, trimmed at both ends. + if next > seg.media_end { + interleaved.truncate((seg.media_end - pos) as usize * w.channels); + } pos = next; - continue; - } - if pos < w.media_target { - interleaved.drain(..(w.media_target - pos) as usize * w.channels); - pos = w.media_target; - } - let chunk = AudioChunk { - start_sample: pos - w.priming, - samples: std::mem::take(&mut interleaved), - }; - pos = next; - if w.tx.send(chunk).is_err() { - break; // consumer went away + if interleaved.is_empty() { + continue; // nothing left of it; the loop head ends the segment + } + let chunk = AudioChunk { + start_sample: timeline, + samples: std::mem::take(&mut interleaved), + }; + timeline += (chunk.samples.len() / w.channels) as u64; + if w.tx.send(chunk).is_err() { + return; // consumer went away + } } } } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 2b81cf1..93dd2b3 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -41,13 +41,34 @@ impl DecodeSession { pub fn open_at( path: impl AsRef, start_frame: u32, + ) -> crate::Result<(VideoMeta, Receiver, Arc)> { + // `u32::MAX` is clamped to the stream's frame count below, so this is + // "to the end of the file". + Self::open_range(path, start_frame, u32::MAX) + } + + /// As [`DecodeSession::open_at`], but the worker also stops on its own + /// after sending `end_frame - 1`: the range is half-open `[start, end)` in + /// absolute source frames, which is what a clip of a longer file needs. + /// `end_frame` is capped at the stream's frame count, and an empty range + /// yields a receiver that is simply already disconnected. + pub fn open_range( + path: impl AsRef, + start_frame: u32, + end_frame: u32, ) -> crate::Result<(VideoMeta, Receiver, Arc)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; + let end_frame = end_frame.min(meta.frame_count); // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); + if end_frame <= start_frame { + // Nothing to decode: dropping `tx` here closes the channel cleanly, + // so the caller sees an immediate end of stream rather than an error. + return Ok((meta, rx, cancel)); + } let worker_cancel = Arc::clone(&cancel); thread::Builder::new() .name("decode".into()) @@ -56,7 +77,7 @@ impl DecodeSession { // VA-API state is not `Send`-safe across a later hand-off. if let Some(hw) = open_hw(&path, start_frame) { eprintln!("decode backend: hardware (VA-API plugin)"); - if run_hw(hw, &tx, start_frame, &worker_cancel) { + if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) { return; } // A driver that opens but cannot decode a single frame is @@ -64,7 +85,7 @@ impl DecodeSession { eprintln!("hardware decode failed before any frame, falling back to software"); } eprintln!("decode backend: software (rusty_h264)"); - run(demuxer, tx, start_frame, &worker_cancel) + run(demuxer, tx, start_frame, end_frame, &worker_cancel) })?; Ok((meta, rx, cancel)) } @@ -89,6 +110,7 @@ fn run_hw( mut hw: HwSession, tx: &SyncSender, start_frame: u32, + end_frame: u32, cancel: &AtomicBool, ) -> bool { let mut index = start_frame; @@ -108,6 +130,9 @@ fn run_hw( if tx.send(frame).is_err() { return true; // consumer went away } + if index >= end_frame { + return true; // end of the requested range + } } Ok(None) => return true, Err(e) => { @@ -121,7 +146,13 @@ fn run_hw( } } -fn run(mut demuxer: Demuxer, tx: SyncSender, start_frame: u32, cancel: &AtomicBool) { +fn run( + mut demuxer: Demuxer, + tx: SyncSender, + start_frame: u32, + end_frame: u32, + cancel: &AtomicBool, +) { let mut decoder = Decoder::new(); // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at // a sync sample, so pictures between it and `start_frame` are decoded (the @@ -165,5 +196,8 @@ fn run(mut demuxer: Demuxer, tx: SyncSender, start_frame: u32, cancel: &A if tx.send(frame).is_err() { break; // consumer went away } + if index >= end_frame { + break; // end of the requested range + } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8b43931..5df93f5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,12 +8,14 @@ pub mod decode; pub mod demux; pub mod hw; pub mod playback; +pub mod project; pub use audio::{AudioChunk, AudioMeta, AudioSession}; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; pub use playback::PlaybackSession; +pub use project::{Clip, Project}; /// Boxed error; the engine has few failure modes and every one of them is fatal /// to the session, so a message is all a caller can act on. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs new file mode 100644 index 0000000..76d56ea --- /dev/null +++ b/crates/engine/src/project.rs @@ -0,0 +1,368 @@ +//! Edit list: the timeline as a list of source ranges. Pure data, no I/O. +//! +//! A [`Project`] is an ordered list of [`Clip`]s, each a half-open `[in, out)` +//! range of *source* frames. Playing the timeline means playing those ranges +//! back to back, so timeline frame `t` is found by walking the clips and +//! consuming their lengths; the mapping is [`Project::map_timeline`] and it is +//! the only place that conversion lives. +//! +//! Two frame spaces meet here and are never mixed: *source* frames index the +//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based +//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`). +//! +//! Editing is metadata only. [`Project::cut`] splits a clip in two without +//! changing any timeline->source mapping, so a running decoder stays correct +//! across a cut; [`Project::delete`] does change the mapping and the caller +//! must reseek. Every successful edit snapshots the clip list, so +//! [`Project::undo`] is an exact restore. + +/// A half-open `[in_frame, out_frame)` range of source frames. Never empty. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Clip { + pub in_frame: u32, + pub out_frame: u32, +} + +impl Clip { + /// Frame count; `>= 1` by the never-empty invariant. + pub fn len(&self) -> u32 { + self.out_frame - self.in_frame + } +} + +/// The edit list plus its undo history. +#[derive(Clone, Debug)] +pub struct Project { + clips: Vec, + /// Snapshots pushed *before* each successful edit; `undo` pops one. + history: Vec>, +} + +impl Project { + /// One clip covering the whole file -- the state of a freshly opened video, + /// where the timeline is the source. `frame_count` of 0 would break the + /// never-empty invariant, so it is clamped to one frame. + pub fn single(frame_count: u32) -> Self { + Self { + clips: vec![Clip { + in_frame: 0, + out_frame: frame_count.max(1), + }], + history: Vec::new(), + } + } + + pub fn clips(&self) -> &[Clip] { + &self.clips + } + + /// Length of the timeline in frames. + pub fn timeline_frames(&self) -> u32 { + self.clips.iter().map(Clip::len).sum() + } + + /// `(timeline_start, len)` per clip, in order -- what a UI lane needs to + /// lay clips out without redoing the cumulative sum. + pub fn clip_spans(&self) -> Vec<(u32, u32)> { + let mut start = 0; + self.clips + .iter() + .map(|c| { + let span = (start, c.len()); + start += c.len(); + span + }) + .collect() + } + + /// Timeline frame -> `(clip index, source frame)`. `None` past the end. + pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> { + let mut start = 0; + for (i, c) in self.clips.iter().enumerate() { + if timeline_frame < start + c.len() { + return Some((i, c.in_frame + (timeline_frame - start))); + } + start += c.len(); + } + None + } + + /// Split the clip containing `timeline_frame` so that frame becomes the + /// first frame of a new clip. Refused (`false`, no change) at timeline 0, + /// at an existing clip boundary, and at or past the end -- all three would + /// produce an empty clip. Metadata only: no mapping changes. + pub fn cut(&mut self, timeline_frame: u32) -> bool { + let Some((idx, source)) = self.map_timeline(timeline_frame) else { + return false; + }; + if source == self.clips[idx].in_frame { + return false; // start of a clip: nothing to split off + } + self.history.push(self.clips.clone()); + let out = self.clips[idx].out_frame; + self.clips[idx].out_frame = source; + self.clips.insert( + idx + 1, + Clip { + in_frame: source, + out_frame: out, + }, + ); + true + } + + /// Remove a clip and close the gap. Refused for an out-of-range index and + /// for the last remaining clip (an empty timeline is undefined this slice). + /// Changes the timeline->source mapping: the caller must reseek. + pub fn delete(&mut self, idx: usize) -> bool { + if idx >= self.clips.len() || self.clips.len() == 1 { + return false; + } + self.history.push(self.clips.clone()); + self.clips.remove(idx); + true + } + + /// Restore the clip list from before the last successful edit. `false` when + /// there is nothing left to undo. + pub fn undo(&mut self) -> bool { + match self.history.pop() { + Some(prev) => { + self.clips = prev; + true + } + None => false, + } + } + + /// Half-open `(start, end)` segments in *source* seconds, from + /// `timeline_frame` to the end of the timeline -- the play list for the + /// audio worker. The first entry is partial when the position is mid-clip. + /// Empty when the position is past the end or `fps` is not usable. + pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(f64, f64)> { + if !(fps.is_finite() && fps > 0.0) { + return Vec::new(); + } + let Some((idx, source)) = self.map_timeline(timeline_frame) else { + return Vec::new(); + }; + let mut segs = vec![(source as f64 / fps, self.clips[idx].out_frame as f64 / fps)]; + segs.extend( + self.clips[idx + 1..] + .iter() + .map(|c| (c.in_frame as f64 / fps, c.out_frame as f64 / fps)), + ); + segs + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FPS: f64 = 30.0; + + /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built + /// through `cut` so the constructor path is exercised too. + fn three() -> Project { + let mut p = Project::single(9); + assert!(p.cut(3)); + assert!(p.cut(5)); + assert_eq!( + p.clips(), + [ + Clip { + in_frame: 0, + out_frame: 3 + }, + Clip { + in_frame: 3, + out_frame: 5 + }, + Clip { + in_frame: 5, + out_frame: 9 + }, + ] + ); + p + } + + #[test] + fn single_is_the_whole_file() { + let p = Project::single(150); + assert_eq!(p.clips().len(), 1); + assert_eq!(p.timeline_frames(), 150); + assert_eq!(p.clip_spans(), vec![(0, 150)]); + // degenerate mapping: timeline == source + assert_eq!(p.map_timeline(0), Some((0, 0))); + assert_eq!(p.map_timeline(149), Some((0, 149))); + assert_eq!(p.map_timeline(150), None); + // never-empty invariant survives a bogus frame count + assert_eq!(Project::single(0).timeline_frames(), 1); + } + + #[test] + fn cut_mid_clip_splits() { + let mut p = Project::single(9); + assert!(p.cut(4)); + assert_eq!( + p.clips(), + [ + Clip { + in_frame: 0, + out_frame: 4 + }, + Clip { + in_frame: 4, + out_frame: 9 + }, + ] + ); + assert_eq!(p.timeline_frames(), 9); + } + + #[test] + fn cut_refused_at_zero_boundary_and_end() { + let mut p = three(); + let before = p.clips().to_vec(); + assert!(!p.cut(0), "timeline 0 has nothing before it"); + assert!(!p.cut(3), "existing boundary"); + assert!(!p.cut(5), "existing boundary"); + assert!(!p.cut(9), "one past the last frame"); + assert!(!p.cut(1_000)); + assert_eq!(p.clips(), before.as_slice()); + // one undo lands before the *second* cut, so the refusals pushed nothing + assert!(p.undo()); + assert_eq!(p.clips().len(), 2, "refused cuts push no history"); + } + + #[test] + fn cut_never_changes_the_mapping() { + let p = three(); + let before: Vec<_> = (0..9).map(|f| p.map_timeline(f).unwrap().1).collect(); + let mut after = p.clone(); + assert!(after.cut(7)); + let now: Vec<_> = (0..9).map(|f| after.map_timeline(f).unwrap().1).collect(); + assert_eq!(before, now); + } + + #[test] + fn map_timeline_sweeps_every_boundary() { + let p = three(); + assert_eq!(p.timeline_frames(), 9); + assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]); + // contiguous source here, so the clip index is what actually moves + let expect = [ + (0, (0, 0)), + (1, (0, 1)), + (2, (0, 2)), + (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip + (4, (1, 4)), + (5, (2, 5)), + (6, (2, 6)), + (7, (2, 7)), + (8, (2, 8)), + ]; + for (t, want) in expect { + assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}"); + } + assert_eq!(p.map_timeline(9), None); + } + + #[test] + fn delete_closes_the_gap() { + let mut p = three(); + assert!(p.delete(1)); + assert_eq!(p.timeline_frames(), 7); + assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]); + // timeline 3 used to be source 3; the gap closed so it is source 5 now + assert_eq!(p.map_timeline(3), Some((1, 5))); + assert_eq!(p.map_timeline(6), Some((1, 8))); + assert_eq!(p.map_timeline(7), None); + } + + #[test] + fn delete_first_last_and_only() { + let mut p = three(); + assert!(p.delete(0)); + assert_eq!(p.map_timeline(0), Some((0, 3))); + assert_eq!(p.timeline_frames(), 6); + + let mut p = three(); + assert!(p.delete(2)); + assert_eq!(p.timeline_frames(), 5); + assert_eq!(p.map_timeline(4), Some((1, 4))); + + assert!(!p.delete(2), "index past the end"); + assert!(p.delete(1)); + assert!(!p.delete(0), "the last remaining clip stays"); + assert_eq!(p.clips().len(), 1); + } + + #[test] + fn undo_restores_exactly() { + let mut p = three(); + let after_cuts = p.clips().to_vec(); + assert!(p.delete(1)); + assert!(p.undo()); + assert_eq!(p.clips(), after_cuts.as_slice()); + + // walk all the way back through both cuts, then run dry + assert!(p.undo()); + assert_eq!(p.clips().len(), 2); + assert!(p.undo()); + assert_eq!( + p.clips(), + [Clip { + in_frame: 0, + out_frame: 9 + }] + ); + assert!(!p.undo(), "empty history"); + assert_eq!( + p.clips(), + [Clip { + in_frame: 0, + out_frame: 9 + }] + ); + } + + #[test] + fn segments_from_trims_the_first_entry() { + let p = three(); + // mid-clip: partial first segment, whole clips after it + assert_eq!( + p.segments_from(4, FPS), + vec![(4.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)] + ); + // on a boundary: nothing partial + assert_eq!( + p.segments_from(3, FPS), + vec![(3.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)] + ); + // from the top: one entry per clip + assert_eq!(p.segments_from(0, FPS).len(), 3); + // last clip only + assert_eq!(p.segments_from(8, FPS), vec![(8.0 / 30.0, 0.3)]); + // past the end / unusable fps + assert!(p.segments_from(9, FPS).is_empty()); + assert!(p.segments_from(0, 0.0).is_empty()); + assert!(p.segments_from(0, f64::NAN).is_empty()); + } + + #[test] + fn segments_follow_deletes_and_fps() { + let mut p = three(); + assert!(p.delete(0)); + // source seconds, not timeline: deleting the head does not shift them + let segs = p.segments_from(0, 25.0); + assert_eq!(segs, vec![(3.0 / 25.0, 0.2), (0.2, 9.0 / 25.0)]); + let played: f64 = segs.iter().map(|(a, b)| b - a).sum(); + assert!( + (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, + "segments must cover exactly the timeline: {played}" + ); + } +} diff --git a/crates/engine/tests/audio_segments.rs b/crates/engine/tests/audio_segments.rs new file mode 100644 index 0000000..19d2fd5 --- /dev/null +++ b/crates/engine/tests/audio_segments.rs @@ -0,0 +1,136 @@ +//! `AudioSession::open_segments` must pour source windows back to back: each +//! segment equal to the matching window of a plain `open_at`, `start_sample` +//! continuous across the join, and the trims exact down to a sub-packet clip. + +use std::path::PathBuf; +use std::sync::mpsc::Receiver; + +use engine::audio::{AudioChunk, AudioSession}; + +const RATE: u64 = 44100; +const CHANNELS: usize = 2; +/// One AAC-LC packet, in frames per channel. +const PACKET: u64 = 1024; + +fn asset() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4") +} + +/// Drains a session flat, asserting chunks are contiguous, and reports the +/// first chunk's `start_sample` plus how many chunks arrived. +fn drain(rx: Receiver) -> (Vec, u64, usize) { + let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize); + for AudioChunk { + start_sample, + samples: s, + } in rx + { + assert!(!s.is_empty(), "empty chunk {chunks}"); + let want = first.unwrap_or(start_sample) + (samples.len() / CHANNELS) as u64; + assert_eq!(start_sample, want, "gap or overlap before chunk {chunks}"); + first.get_or_insert(start_sample); + samples.extend(s); + chunks += 1; + } + (samples, first.unwrap_or(0), chunks) +} + +fn segments(segs: &[(f64, f64)]) -> (Vec, u64, usize) { + let (_, rx) = AudioSession::open_segments(asset(), segs) + .expect("open") + .expect("test_av.mp4 has an audio track"); + drain(rx) +} + +/// The first `frames` per channel of a plain `open_at(start)`. +fn window(start: f64, frames: u64) -> Vec { + let (_, rx) = AudioSession::open_at(asset(), start).unwrap().unwrap(); + let (mut samples, _, _) = drain(rx); + assert!(samples.len() >= frames as usize * CHANNELS, "short window"); + samples.truncate(frames as usize * CHANNELS); + samples +} + +/// Largest per-sample difference, and where it is. +fn max_diff(a: &[f32], b: &[f32]) -> (f32, usize) { + assert_eq!(a.len(), b.len(), "length mismatch"); + a.iter() + .zip(b) + .enumerate() + .map(|(i, (x, y))| ((x - y).abs(), i)) + .fold((0.0, 0), |m, d| if d.0 > m.0 { d } else { m }) +} + +/// Perceptual noise substitution reseeds per decoder, so a segment can never be +/// promised bit-exact against another run (engine/src/audio.rs docs, ledger). +fn assert_close(got: &[f32], want: &[f32], what: &str) { + let (diff, at) = max_diff(got, want); + eprintln!( + "{what}: max abs diff {diff:e} at sample {at} of {}", + got.len() + ); + assert!(diff < 1e-3, "{what}: max abs diff {diff} at sample {at}"); +} + +#[test] +fn two_segments_concat() { + let (got, first, chunks) = segments(&[(1.0, 2.0), (3.0, 4.0)]); + // `drain` already proved every chunk butts against the previous one, so a + // full-length run is a joint with no gap and no overlap. + assert_eq!(first, RATE, "numbering starts at the first segment's start"); + assert_eq!( + got.len() as u64 / CHANNELS as u64, + 2 * RATE, + "{chunks} chunks" + ); + + let want: Vec = [window(1.0, RATE), window(3.0, RATE)].concat(); + assert_close(&got, &want, "two segments"); +} + +#[test] +fn tiny_segment_is_one_frame_long() { + // A single 30 fps video frame's worth of audio: 1470 samples per channel, + // decoded from two packets and trimmed at both. + let (got, first, chunks) = segments(&[(1.0, 1.0 + 1.0 / 30.0)]); + assert_eq!(first, RATE); + assert_eq!(got.len() as u64 / CHANNELS as u64, 1470, "{chunks} chunks"); + assert_close(&got, &window(1.0, 1470), "one video frame"); +} + +#[test] +fn sub_packet_segment_trims_one_buffer_at_both_ends() { + // 441 samples starting 44100 in: with priming that is media 45124..45565, + // both inside packet 45 ([45056, 46080)), so the head trim and the tail trim + // hit the same decoded buffer. + let (got, first, chunks) = segments(&[(1.0, 1.01)]); + assert_eq!(first, RATE); + assert_eq!(got.len() as u64 / CHANNELS as u64, 441); + assert_eq!(chunks, 1, "both trims must land in one decoded buffer"); + assert_close(&got, &window(1.0, 441), "sub-packet segment"); +} + +#[test] +fn segment_past_the_end_is_capped() { + // test_av.mp4 is 5 s: the ask runs 55 s past the track and must simply stop. + let (got, first, _) = segments(&[(4.0, 60.0)]); + assert_eq!(first, 4 * RATE); + let frames = got.len() as u64 / CHANNELS as u64; + assert!( + (RATE..=RATE + PACKET).contains(&frames), + "{frames} frames for the last second (+0..={PACKET} tail padding)" + ); +} + +#[test] +fn no_segments_ends_clean() { + let (meta, rx) = AudioSession::open_segments(asset(), &[]) + .expect("open") + .expect("test_av.mp4 has an audio track"); + assert_eq!(meta.sample_rate as u64, RATE); + assert_eq!( + rx.into_iter().count(), + 0, + "an empty edit list decodes nothing" + ); +} diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index adfeb90..240a74e 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -123,6 +123,42 @@ fn seek_matches_linear() { ); } +/// Drains a bounded session, returning the indices it delivered. The loop ends +/// only on `RecvError`, i.e. the worker closed the channel by itself. +fn range_indices(path: &Path, start: u32, end: u32) -> Vec { + let (_, rx, _cancel) = DecodeSession::open_range(path, start, end).expect("open_range"); + let mut got = Vec::new(); + while let Ok(frame) = rx.recv() { + got.push(frame.index); + } + got +} + +/// A bounded range must stop on its own — both backends — with `Frame::index` +/// still the absolute source index, and then disconnect rather than hang. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn range_stops_at_end() { + const START: u32 = 30; + const END: u32 = 60; + let path = asset("test_baseline.mp4"); + let want: Vec = (START..END).collect(); + + // Another test in this binary may already have pinned VE_SW; clear it so + // the hardware half really is hardware. SAFETY: --test-threads=1. + unsafe { std::env::remove_var("VE_SW") }; + assert_eq!(range_indices(&path, START, END), want, "hardware range"); + + unsafe { std::env::set_var("VE_SW", "1") }; + assert_eq!(range_indices(&path, START, END), want, "software range"); + + // Degenerate ranges close cleanly instead of decoding to EOF. + assert!(range_indices(&path, 30, 30).is_empty(), "empty range"); + assert!(range_indices(&path, 60, 30).is_empty(), "inverted range"); + // Past the end is clamped to the frame count. + assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range"); +} + /// H.264 8-bit decode is bit-exact by conformance, so the two backends must /// agree. A mismatch means a driver deviation and is reported, not swallowed. #[test]