diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 1f9e8a8..cb879c1 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -4,7 +4,7 @@ use std::fs::File; use std::io::BufReader; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; @@ -65,6 +65,14 @@ pub struct AacPacket { pub samples: u32, } +/// Everything an import check needs from a candidate file's audio track. Two +/// files may share a timeline only when their probes are equal (or both `None`). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AudioProbe { + pub params: AacTrackParams, + pub channels: u16, +} + pub struct AudioSession; impl AudioSession { @@ -101,80 +109,82 @@ impl AudioSession { path: impl AsRef, segs: &[(f64, f64)], ) -> crate::Result)>> { - let file = File::open(path.as_ref())?; - let size = file.metadata()?.len(); - let reader = Mp4Reader::read_header(BufReader::new(file), size)?; + let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); + Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs) + } - let Some(track) = reader - .tracks() - .values() - .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) - else { + /// [`open_segments`](Self::open_segments) over several files: a segment names + /// its source by index into `sources`, and a source join behaves exactly like + /// a cut inside one file — `start_sample` stays continuous, the decoder is + /// fresh either way. Each source contributes *its own* priming, packet table + /// and length, which is the whole reason the resolution is per source. + /// + /// Only the sources some segment names are opened. `Ok(None)` when `sources` + /// is empty or its first entry has no AAC track; a later source that is + /// missing audio or disagrees on rate/layout is an `Err` — import refuses + /// those up front (one timeline, one output device), this is the backstop. + pub fn open_multi_segments( + sources: &[PathBuf], + segs: &[(usize, f64, f64)], + ) -> crate::Result)>> { + let Some(first) = sources.first() else { return Ok(None); }; - - // AacDecoder only does plain LC, mono/stereo; refuse early with a - // message instead of letting it fail packet by packet. - match track.audio_profile()? { - AudioObjectType::AacLowComplexity => {} - other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), - } - let channels: u16 = match track.channel_config()? { - ChannelConfig::Mono => 1, - ChannelConfig::Stereo => 2, - other => { - return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()); - } + let Some(first) = Track::open(first)? else { + return Ok(None); + }; + // The timeline's meta is the first source's: policy makes every other + // source match it, and the checks below hold them to that. + let meta = AudioMeta { + sample_rate: first.sample_rate, + channels: first.channels()?, + total_samples: first.total_samples, }; - - let track_id = track.track_id(); - let sample_rate = track.sample_freq_index()?.freq(); - let priming = priming_samples(track, sample_rate); - let total_samples = scale( - track.trak.mdia.mdhd.duration, - sample_rate, - track.timescale(), - ) - .map(|d| d.saturating_sub(priming)); - - let mut params = AudioCodecParameters::new(); - params - .for_codec(CODEC_ID_AAC) - .with_sample_rate(sample_rate) - .with_extra_data(audio_specific_config(track)?); // 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())?; + AacDecoder::try_new(&first.params, &AudioDecoderOptions::default())?; + + let mut tracks: Vec> = sources.iter().map(|_| None).collect(); + tracks[0] = Some(first); + for &(source, ..) in segs { + let slot = tracks + .get_mut(source) + .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; + if slot.is_some() { + continue; // already opened, and the checks below already ran + } + let track = Track::open(&sources[source])? + .ok_or_else(|| format!("source {source} has no audio track"))?; + if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { + return Err(format!( + "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", + track.sample_rate, + track.channels()?, + meta.sample_rate, + meta.channels + ) + .into()); + } + AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())?; + *slot = Some(track); + } - // 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(stts_pairs(track), 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), - } + .map(|&(source, start_secs, end_secs)| { + tracks[source] + .as_ref() + .expect("opened above") + .segment(source, start_secs, end_secs) }) .collect(); + // Chunk numbering is continuous across every join, counted from the first + // segment's audible start in its own source (see `open_segments`). + let timeline = segments.first().map_or(0, |s| { + s.media_target + .saturating_sub(tracks[s.source].as_ref().expect("opened above").priming) + }); - let sample_count = reader.sample_count(track_id)?; - let meta = AudioMeta { - sample_rate, - channels, - total_samples, - }; // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so // this bound is ~0.75 s of lookahead — enough to ride out decode jitter // without making a pause take a second to bite. @@ -183,19 +193,30 @@ impl AudioSession { .name("audio-decode".into()) .spawn(move || { run(Worker { - reader, - params, - track_id, - sample_count, - channels: channels as usize, - priming, + tracks, + channels: meta.channels as usize, segments, + timeline, tx, }) })?; Ok(Some((meta, rx))) } + /// The audio parameters of `path`, for checking an import against the + /// timeline's first source: header only, no decoder and no worker. + /// `Ok(None)` means no AAC track — an audio-less file, which import pairs + /// only with other audio-less files. + pub fn probe(path: impl AsRef) -> crate::Result> { + let Some(track) = Track::open(path.as_ref())? else { + return Ok(None); + }; + Ok(Some(AudioProbe { + params: track.track_params(), + channels: track.channels()?, + })) + } + /// The raw AAC packets covering `segs` — the same half-open source-second /// windows [`open_segments`](Self::open_segments) decodes — copied out /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go @@ -221,12 +242,119 @@ impl AudioSession { path: impl AsRef, segs: &[(f64, f64)], ) -> crate::Result)>> { - if segs.is_empty() { + let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); + Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs) + } + + /// [`copy_segments`](Self::copy_segments) over several files, segments naming + /// their source by index into `sources`. The rounding debt is carried across + /// a source join exactly as across a cut inside one file, so the bound stays + /// half a packet over the whole list however many files it spans, and the + /// extra priming packet is still the very first segment's alone. + /// + /// Every source must declare the same [`AacTrackParams`]: the copy becomes + /// one output track with one esds. Import refuses a mismatch up front; the + /// check here is the backstop, as is the missing-track `Err`. + pub fn copy_multi_segments( + sources: &[PathBuf], + segs: &[(usize, f64, f64)], + ) -> crate::Result)>> { + let Some(&(first, ..)) = segs.first() else { return Ok(None); + }; + let path = sources + .get(first) + .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; + let Some(track) = Track::open(path)? else { + return Ok(None); // silent source, silent export + }; + let params = track.track_params(); + let mut tracks: Vec> = sources.iter().map(|_| None).collect(); + tracks[first] = Some(track); + + let mut err = 0i64; + let mut packets = Vec::new(); + for (i, &(source, start_secs, end_secs)) in segs.iter().enumerate() { + let track = source_at(&mut tracks, sources, source)?; + if track.track_params() != params { + return Err(format!( + "source {source} audio is {:?}, the timeline's is {params:?}", + track.track_params() + ) + .into()); + } + let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale); + let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0); + let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64; + let available = track.sample_count.saturating_sub(start_id - 1); + // The head packet is the priming of the first segment only: a reader + // drops exactly one, so an interior join must not add another. + let head = (i == 0 && start_id > 1).then(|| start_id - 1); + let ids = head + .into_iter() + .chain(start_id..start_id + packet_run(&mut err, ideal, available)); + for id in ids { + let Some(sample) = track.reader.read_sample(track.track_id, id)? else { + let count = track.sample_count; + return Err(format!("audio sample {id} of {count} is missing").into()); + }; + packets.push(AacPacket { + bytes: sample.bytes.to_vec(), + samples: SAMPLES_PER_PACKET, + }); + } } - let file = File::open(path.as_ref())?; + Ok(Some((params, packets))) + } +} + +/// The source at `index`, opened on first use. Sources a segment list never +/// names are never touched: a project's list only grows. +fn source_at<'a>( + tracks: &'a mut [Option], + sources: &[PathBuf], + index: usize, +) -> crate::Result<&'a mut Track> { + let slot = tracks + .get_mut(index) + .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; + if slot.is_none() { + *slot = Some( + Track::open(&sources[index])? + .ok_or_else(|| format!("source {index} has no audio track"))?, + ); + } + Ok(slot.as_mut().expect("just opened")) +} + +/// One source's AAC track, resolved once: the reader plus everything the header +/// has to say about it. `stts` is copied out because every other field would +/// otherwise keep a borrow alive on the reader the worker needs mutably — a real +/// AAC track has one entry, so it is two `u32`s. +struct Track { + reader: Mp4Reader>, + track_id: u32, + sample_count: u32, + sample_rate: u32, + timescale: u32, + /// Encoder delay of *this* file. Sources are joined, priming is not shared. + priming: u64, + total_samples: Option, + stts: Vec<(u32, u32)>, + config: ChannelConfig, + freq_index: u8, + chan_conf: u8, + /// 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, +} + +impl Track { + /// `Ok(None)` for a file with no AAC track, which is a valid silent source. + fn open(path: &Path) -> crate::Result> { + let file = File::open(path)?; let size = file.metadata()?.len(); - let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?; + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; let Some(track) = reader .tracks() @@ -235,9 +363,10 @@ impl AudioSession { else { return Ok(None); }; - // The copy carries no profile of its own: the writer rebuilds the + // Refuse early with a message instead of failing packet by packet — and + // a copy carries no profile of its own: the writer rebuilds the // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a - // non-LC source would be mislabelled rather than merely unplayable here. + // non-LC source would be mislabelled rather than merely unplayable. match track.audio_profile()? { AudioObjectType::AacLowComplexity => {} other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), @@ -248,43 +377,71 @@ impl AudioSession { let timescale = track.timescale(); let priming = priming_samples(track, sample_rate); let (_, freq_index, chan_conf) = asc_fields(track)?; - let sample_count = reader.sample_count(track_id)?; + let mut params = AudioCodecParameters::new(); + params + .for_codec(CODEC_ID_AAC) + .with_sample_rate(sample_rate) + .with_extra_data(audio_specific_config(track)?); + let this = Self { + track_id, + sample_count: reader.sample_count(track_id)?, + sample_rate, + timescale, + priming, + total_samples: scale(track.trak.mdia.mdhd.duration, sample_rate, timescale) + .map(|d| d.saturating_sub(priming)), + stts: stts_pairs(track).collect(), + config: track.channel_config()?, + freq_index, + chan_conf, + params, + reader, + }; + Ok(Some(this)) + } - // Resolve every packet id first: `read_sample` needs the reader mutably, - // which ends the borrow `track` holds. - let media = |secs: f64| ((secs * f64::from(sample_rate)) as u64).saturating_add(priming); - let mut err = 0i64; - let mut ids: Vec = Vec::new(); - for (i, &(start_secs, end_secs)) in segs.iter().enumerate() { - let target_ts = unscale(media(start_secs), sample_rate, timescale); - let (start_id, _) = packet_at(stts_pairs(track), target_ts, 0); - let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; - let available = sample_count.saturating_sub(start_id - 1); - if i == 0 && start_id > 1 { - ids.push(start_id - 1); // priming, see the doc comment - } - ids.extend(start_id..start_id + packet_run(&mut err, ideal, available)); + /// Channel count. `AacDecoder` only does mono and stereo, so anything else + /// is refused here rather than one packet at a time. + fn channels(&self) -> crate::Result { + match self.config { + ChannelConfig::Mono => Ok(1), + ChannelConfig::Stereo => Ok(2), + other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()), } + } - let packets = ids - .into_iter() - .map(|id| match reader.read_sample(track_id, id)? { - Some(sample) => Ok(AacPacket { - bytes: sample.bytes.to_vec(), - samples: SAMPLES_PER_PACKET, - }), - None => Err(format!("audio sample {id} of {sample_count} is missing").into()), - }) - .collect::>>()?; - - Ok(Some(( - AacTrackParams { - freq_index, - chan_conf, - sample_rate, - }, - packets, - ))) + fn track_params(&self) -> AacTrackParams { + AacTrackParams { + freq_index: self.freq_index, + chan_conf: self.chan_conf, + sample_rate: self.sample_rate, + } + } + + /// `secs` on this source's audible timeline into media samples (priming + /// included, so it compares directly against a decoded position). + /// `f64::INFINITY` saturates. + fn media(&self, secs: f64) -> u64 { + ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) + } + + /// One `[start, end)` window of this source's seconds, resolved to its own + /// packets and media samples. + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { + let media_target = self.media(start_secs); + let target_ts = unscale(media_target, self.sample_rate, self.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(self.stts.iter().copied(), target_ts, PRE_ROLL); + Segment { + source, + start_id, + start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), + media_target, + // An inverted segment is an empty one, never a backwards run. + media_end: self.media(end_secs).max(media_target), + } } } @@ -429,8 +586,11 @@ fn packet_at( last } -/// One window of the source to decode, resolved to media samples and packets. +/// One window of a source to decode, resolved to media samples and packets. struct Segment { + /// Index into the worker's tracks; the media positions below are that + /// source's, not the timeline's. + source: usize, /// 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. @@ -443,29 +603,29 @@ struct Segment { } 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, + /// Indexed by [`Segment::source`]; only the sources some segment names are + /// `Some`, the rest were never opened. + tracks: Vec>, channels: usize, - priming: u64, segments: Vec, + /// `start_sample` of the first chunk. + timeline: u64, tx: SyncSender, } fn run(mut w: Worker) { let mut interleaved = Vec::new(); - // 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 seg in &w.segments { - let mut decoder = match AacDecoder::try_new(&w.params, &AudioDecoderOptions::default()) { + let channels = w.channels; + // Chunk numbering is continuous across every join, source ones included. + let mut timeline = w.timeline; + let segments = std::mem::take(&mut w.segments); + + for seg in &segments { + let Some(track) = w.tracks[seg.source].as_mut() else { + continue; // opener fills every named source; nothing to decode + }; + let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) + { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); @@ -474,11 +634,11 @@ fn run(mut w: Worker) { }; let mut pos = seg.start_pos; - for id in seg.start_id..=w.sample_count { + for id in seg.start_id..=track.sample_count { if pos >= seg.media_end { break; // segment done, on to the next one } - let sample = match w.reader.read_sample(w.track_id, id) { + let sample = match track.reader.read_sample(track.track_id, id) { Ok(Some(sample)) => sample, Ok(None) => break, Err(e) => { @@ -487,7 +647,7 @@ fn run(mut w: Worker) { } }; let packet = Packet::new( - w.track_id, + track.track_id, units::Timestamp::new(sample.start_time as i64), units::Duration::new(u64::from(sample.duration)), &sample.bytes[..], @@ -500,7 +660,7 @@ fn run(mut w: Worker) { } }; buf.copy_to_vec_interleaved::(&mut interleaved); - let next = pos + (interleaved.len() / w.channels) as u64; + let next = pos + (interleaved.len() / 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 @@ -510,13 +670,13 @@ fn run(mut w: Worker) { continue; } if pos < seg.media_target { - interleaved.drain(..(seg.media_target - pos) as usize * w.channels); + interleaved.drain(..(seg.media_target - pos) as usize * 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); + interleaved.truncate((seg.media_end - pos) as usize * channels); } pos = next; if interleaved.is_empty() { @@ -526,7 +686,7 @@ fn run(mut w: Worker) { start_sample: timeline, samples: std::mem::take(&mut interleaved), }; - timeline += (chunk.samples.len() / w.channels) as u64; + timeline += (chunk.samples.len() / channels) as u64; if w.tx.send(chunk).is_err() { return; // consumer went away } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 1cf0e8f..0dbfc75 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -131,7 +131,14 @@ fn run( // ponytail: this holds the whole exported AAC track in memory (~3 kB per // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming // `copy_segments` that yields packets instead of collecting them. - let audio = AudioSession::copy_segments(source, &project.segments_from(0, meta.frame_rate))?; + // Source indexes dropped: every clip is still source 0 until multi-source + // export lands, and `copy_segments` takes the one path above. + let segs: Vec<(f64, f64)> = project + .segments_from(0, meta.frame_rate) + .into_iter() + .map(|(_, start, end)| (start, end)) + .collect(); + let audio = AudioSession::copy_segments(source, &segs)?; let audio_params = audio.as_ref().map(|(track, _)| AudioParams { freq_index: track.freq_index, chan_conf: track.chan_conf, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index b89a0d7..ea8f3e0 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -118,7 +118,7 @@ impl PlaybackSession { }; // One clip covering the file, so timeline == source until the first // edit -- and `open_at(_, 0)` is exactly that clip's range. - let project = Project::single(meta.frame_count); + let project = Project::single(&path, meta.frame_count); let range = project.clips()[0]; Ok(Self { path, @@ -182,7 +182,8 @@ impl PlaybackSession { let Some((idx, source)) = self.project.map_timeline(next) else { return false; }; - let out = self.project.clips()[idx].out_frame; + let clip = self.project.clips()[idx]; + let out = clip.out_frame; match DecodeSession::open_range(&self.path, source, out) { Ok((_, frames, cancel)) => { self.frames = frames; @@ -195,6 +196,7 @@ impl PlaybackSession { self.range = Clip { in_frame: source, out_frame: out, + ..clip }; self.timeline_start = next; true @@ -336,7 +338,8 @@ impl PlaybackSession { // `target` is inside the timeline (never empty), so this always maps; // the range runs from there to the end of the clip it landed in. if let Some((idx, source)) = self.project.map_timeline(target) { - let out = self.project.clips()[idx].out_frame; + let clip = self.project.clips()[idx]; + let out = clip.out_frame; match DecodeSession::open_range(&self.path, source, out) { Ok((_, frames, cancel)) => { self.frames = frames; @@ -350,6 +353,7 @@ impl PlaybackSession { self.range = Clip { in_frame: source, out_frame: out, + ..clip }; self.timeline_start = target; } @@ -367,7 +371,14 @@ impl PlaybackSession { // One worker for the whole rest of the timeline, so the joins // between clips are gapless: the video reopens at a boundary, the // ear never hears it. - let segs = self.project.segments_from(target, fps); + // Every source index is 0 until multi-source playback lands; the + // audio worker still takes one path plus bare `(start, end)`. + let segs: Vec<(f64, f64)> = self + .project + .segments_from(target, fps) + .into_iter() + .map(|(_, start, end)| (start, end)) + .collect(); audio_running = match AudioSession::open_segments(&self.path, &segs) { Ok(Some((_, rx))) => audio.spawn_feeder(rx), _ => false, diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 5140b8e..b14416a 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -15,12 +15,23 @@ //! 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 clip names its file by *index* into [`Project::sources`], which is +//! append-only: an index handed out once stays valid forever, so a clip on the +//! clipboard or inside an undo snapshot can never dangle. An index -- not an +//! `Arc` -- because [`Clip`] is `Copy`, which is what makes copy/paste a +//! plain assignment. + +use std::path::{Path, PathBuf}; -/// A half-open `[in_frame, out_frame)` range of source frames. Never empty. +/// A half-open `[in_frame, out_frame)` range of frames of source +/// [`source`](Clip::source). Never empty. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Clip { pub in_frame: u32, pub out_frame: u32, + /// Index into [`Project::sources`]. + pub source: usize, } impl Clip { @@ -33,20 +44,24 @@ impl Clip { /// The edit list plus its undo history. #[derive(Clone, Debug)] pub struct Project { + /// Append-only: never popped, never reordered. See the module docs. + sources: Vec, 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 { + /// One clip covering the whole of `path` -- the state of a freshly opened + /// video, where the timeline is the source. `frame_count` of 0 would break + /// the never-empty invariant, so it is clamped to one frame. + pub fn single(path: impl AsRef, frame_count: u32) -> Self { Self { + sources: vec![canonical(path.as_ref())], clips: vec![Clip { in_frame: 0, out_frame: frame_count.max(1), + source: 0, }], history: Vec::new(), } @@ -56,6 +71,44 @@ impl Project { &self.clips } + /// The files the clips index into, in import order; index 0 is the file the + /// project was opened with. + pub fn sources(&self) -> &[PathBuf] { + &self.sources + } + + /// Index for `path`, appending it if it is new. Deduped by + /// `fs::canonicalize`, so the same file reached by two paths imports once. + /// The clip list is untouched -- see [`Project::append_clip`] -- so this + /// pushes no history: a source entry alone changes nothing playable. + pub fn import(&mut self, path: impl AsRef) -> usize { + let path = canonical(path.as_ref()); + match self.sources.iter().position(|s| *s == path) { + Some(idx) => idx, + None => { + self.sources.push(path); + self.sources.len() - 1 + } + } + } + + /// Append a whole-file clip of `source` to the end of the timeline. One + /// history snapshot, so an import is one undo step -- and undoing it leaves + /// the (harmless) source entry behind, because indexes are forever. + /// Refused for an unknown source index. + pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool { + if source >= self.sources.len() { + return false; + } + self.history.push(self.clips.clone()); + self.clips.push(Clip { + in_frame: 0, + out_frame: frame_count.max(1), + source, + }); + true + } + /// Length of the timeline in frames. pub fn timeline_frames(&self) -> u32 { self.clips.iter().map(Clip::len).sum() @@ -106,6 +159,7 @@ impl Project { Clip { in_frame: source, out_frame: out, + ..self.clips[idx] }, ); true @@ -138,6 +192,7 @@ impl Project { Clip { in_frame: source, out_frame: out, + ..self.clips[idx] }, ], ); @@ -172,51 +227,70 @@ impl Project { } } - /// Half-open `(start, end)` segments in *source* seconds, from + /// Half-open `(source, start, end)` segments in *source* seconds, from /// `timeline_frame` to the end of the timeline -- the play list for the /// audio worker. The first entry is partial when the position is mid-clip. /// Empty when the position is past the end or `fps` is not usable. - pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(f64, f64)> { + pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(usize, 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)]; + let head = self.clips[idx]; + let mut segs = vec![( + head.source, + source as f64 / fps, + head.out_frame as f64 / fps, + )]; segs.extend( self.clips[idx + 1..] .iter() - .map(|c| (c.in_frame as f64 / fps, c.out_frame as f64 / fps)), + .map(|c| (c.source, c.in_frame as f64 / fps, c.out_frame as f64 / fps)), ); segs } } +/// Absolute, symlink-resolved when the file is reachable; the path as given +/// when it is not -- an unreadable path still deserves an index, it simply +/// dedups by spelling. +fn canonical(path: &Path) -> PathBuf { + std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) +} + #[cfg(test)] mod tests { use super::*; const FPS: f64 = 30.0; + /// Never opened -- `Project` is pure data, so a path that does not exist is + /// simply a path that dedups by spelling. + const FILE: &str = "/nonexistent/a.mp4"; + const FILE2: &str = "/nonexistent/b.mp4"; /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built /// through `cut` so the constructor path is exercised too. fn three() -> Project { - let mut p = Project::single(9); + let mut p = Project::single(FILE, 9); assert!(p.cut(3)); assert!(p.cut(5)); assert_eq!( p.clips(), [ Clip { + source: 0, in_frame: 0, out_frame: 3 }, Clip { + source: 0, in_frame: 3, out_frame: 5 }, Clip { + source: 0, in_frame: 5, out_frame: 9 }, @@ -227,7 +301,7 @@ mod tests { #[test] fn single_is_the_whole_file() { - let p = Project::single(150); + let p = Project::single(FILE, 150); assert_eq!(p.clips().len(), 1); assert_eq!(p.timeline_frames(), 150); assert_eq!(p.clip_spans(), vec![(0, 150)]); @@ -236,21 +310,23 @@ mod tests { 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); + assert_eq!(Project::single(FILE, 0).timeline_frames(), 1); } #[test] fn cut_mid_clip_splits() { - let mut p = Project::single(9); + let mut p = Project::single(FILE, 9); assert!(p.cut(4)); assert_eq!( p.clips(), [ Clip { + source: 0, in_frame: 0, out_frame: 4 }, Clip { + source: 0, in_frame: 4, out_frame: 9 }, @@ -310,6 +386,7 @@ mod tests { /// The clip a copy would hand back: source `[100, 102)`, unrelated to /// anything in `three()` so it is recognisable wherever it lands. const PASTED: Clip = Clip { + source: 0, in_frame: 100, out_frame: 102, }; @@ -323,19 +400,23 @@ mod tests { p.clips(), [ Clip { + source: 0, in_frame: 0, out_frame: 3 }, Clip { + source: 0, in_frame: 3, out_frame: 5 }, Clip { + source: 0, in_frame: 5, out_frame: 6 }, PASTED, Clip { + source: 0, in_frame: 6, out_frame: 9 }, @@ -372,6 +453,7 @@ mod tests { assert!(!p.paste( 4, Clip { + source: 0, in_frame: 7, out_frame: 7 } @@ -444,6 +526,7 @@ mod tests { assert_eq!( p.clips(), [Clip { + source: 0, in_frame: 0, out_frame: 9 }] @@ -452,6 +535,7 @@ mod tests { assert_eq!( p.clips(), [Clip { + source: 0, in_frame: 0, out_frame: 9 }] @@ -464,31 +548,138 @@ mod tests { // 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)] + vec![(0, 4.0 / 30.0, 5.0 / 30.0), (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)] + vec![(0, 3.0 / 30.0, 5.0 / 30.0), (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)]); + assert_eq!(p.segments_from(8, FPS), vec![(0, 8.0 / 30.0, 0.3)]); // past the end / unusable fps assert!(p.segments_from(9, FPS).is_empty()); assert!(p.segments_from(0, 0.0).is_empty()); assert!(p.segments_from(0, f64::NAN).is_empty()); } + /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9) + /// of source 0 then [0,4) of source 1. + fn two_sources() -> Project { + let mut p = three(); + let s = p.import(FILE2); + assert_eq!(s, 1); + assert!(p.append_clip(s, 4)); + p + } + + #[test] + fn import_dedups_and_appends() { + let mut p = Project::single(FILE, 9); + assert_eq!(p.sources().len(), 1, "the opened file is source 0"); + assert_eq!(p.import(FILE), 0, "reimporting the open file reuses 0"); + assert_eq!(p.import(FILE2), 1); + assert_eq!(p.import(FILE2), 1, "second import of the same path"); + assert_eq!(p.sources().len(), 2); + assert!(!p.append_clip(2, 5), "unknown source index"); + assert_eq!(p.clips().len(), 1, "a refusal changes nothing"); + + // Two spellings of one real file are one source: this is the case the + // raw-path comparison above would get wrong. + let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs"); + let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs"); + let mut p = Project::single(here, 9); + assert_eq!(p.import(detour), 0); + assert_eq!(p.sources().len(), 1); + } + + #[test] + fn append_clip_is_one_undo_step() { + let mut p = two_sources(); + assert_eq!(p.timeline_frames(), 13); + assert_eq!( + p.clips()[3], + Clip { + in_frame: 0, + out_frame: 4, + source: 1 + } + ); + assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9"); + assert!(p.undo()); + assert_eq!(p.clips(), three().clips(), "one step back to one source"); + assert_eq!( + p.sources().len(), + 2, + "the orphan source entry stays -- indexes are forever" + ); + // ...and it is still usable, so a redo-by-hand costs no reimport. + assert!(p.append_clip(1, 0)); + assert_eq!(p.clips()[3].len(), 1, "clamped like `single`"); + } + + #[test] + fn edits_carry_the_source_along() { + let mut p = two_sources(); + // A cut inside the second source splits into two source-1 clips. + assert!(p.cut(11)); + assert_eq!( + p.clips()[3], + Clip { + in_frame: 0, + out_frame: 2, + source: 1 + } + ); + assert_eq!( + p.clips()[4], + Clip { + in_frame: 2, + out_frame: 4, + source: 1 + } + ); + + // A source-1 clip pasted into source-0 territory keeps its file, and so + // does the source-0 half that got split off around it. + let copied = p.clips()[4]; + assert!(p.paste(1, copied)); + assert_eq!(p.clips()[1], copied); + assert_eq!(p.clips()[2].source, 0); + assert!(p.undo()); + assert_eq!(p.clips()[1].source, 0, "undo restores sources too"); + } + + #[test] + fn segments_from_names_the_source() { + let p = two_sources(); + // Mid-clip in source 0, then the rest of source 0, then source 1 whole. + assert_eq!( + p.segments_from(4, FPS), + vec![ + (0, 4.0 / 30.0, 5.0 / 30.0), + (0, 5.0 / 30.0, 9.0 / 30.0), + (1, 0.0, 4.0 / 30.0), + ] + ); + // Mid-clip in source 1: only that source is left. + assert_eq!(p.segments_from(10, FPS), vec![(1, 1.0 / 30.0, 4.0 / 30.0)]); + assert!(p.segments_from(13, FPS).is_empty()); + // Segments still cover exactly the timeline across the join. + let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); + assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9); + } + #[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_eq!(segs, vec![(0, 3.0 / 25.0, 0.2), (0, 0.2, 9.0 / 25.0)]); + let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum(); assert!( (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, "segments must cover exactly the timeline: {played}" diff --git a/crates/engine/tests/audio_multi.rs b/crates/engine/tests/audio_multi.rs new file mode 100644 index 0000000..dfb37a2 --- /dev/null +++ b/crates/engine/tests/audio_multi.rs @@ -0,0 +1,263 @@ +//! Multi-source audio: two files poured into one stream. A source join has to +//! behave exactly like a cut inside one file — no gap in `start_sample`, no +//! second priming packet, one shared rounding debt — while each source still +//! contributes its own content, its own packet table and its own length. + +use std::fs::File; +use std::io::BufReader; +use std::path::PathBuf; +use std::sync::mpsc::Receiver; + +use engine::audio::{AacPacket, AudioChunk, AudioSession}; +use mp4::{MediaType, Mp4Reader}; + +const RATE: u64 = 44100; +const CHANNELS: usize = 2; +/// Frames per channel in one AAC-LC packet. +const PACKET: u64 = 1024; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The import-policy pair: same 1280x720@30 / AAC-LC 44.1k stereo, plainly +/// different content (440/880 Hz vs 660/1320 Hz, 5 s vs 4 s). +fn sources() -> Vec { + vec![asset("test_av.mp4"), asset("test_av2.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 multi(segs: &[(usize, f64, f64)]) -> (Vec, u64, usize) { + let (_, rx) = AudioSession::open_multi_segments(&sources(), segs) + .expect("open") + .expect("the first source has an audio track"); + drain(rx) +} + +/// The first `frames` per channel of a plain single-file `open_at(start)`. +fn window(name: &str, start: f64, frames: u64) -> Vec { + let (_, rx) = AudioSession::open_at(asset(name), start).unwrap().unwrap(); + let (mut samples, _, _) = drain(rx); + assert!(samples.len() >= frames as usize * CHANNELS, "short window"); + samples.truncate(frames as usize * CHANNELS); + samples +} + +/// 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) { + assert_eq!(got.len(), want.len(), "{what}: length"); + let (diff, at) = got + .iter() + .zip(want) + .enumerate() + .map(|(i, (x, y))| ((x - y).abs(), i)) + .fold((0.0f32, 0), |m, d| if d.0 > m.0 { d } else { m }); + 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}"); +} + +/// Cycles of the left channel: rising edges through a deadband, so the coding +/// noise around the fixture's 1 Hz volume dip is not counted as a cycle. One +/// second of the 440 Hz source reads ~440, of the 660 Hz one ~660. +fn cycles(samples: &[f32]) -> usize { + let (mut n, mut high) = (0usize, false); + for &s in samples.iter().step_by(CHANNELS) { + if !high && s > 0.05 { + high = true; + n += 1; + } else if high && s < -0.05 { + high = false; + } + } + n +} + +/// The AAC sample bytes for 1-based `ids` of `name`, read straight from the +/// demuxer — the reference a copy must match byte for byte. +fn raw(name: &str, ids: impl IntoIterator) -> Vec> { + let file = File::open(asset(name)).unwrap(); + let size = file.metadata().unwrap().len(); + let mut reader = Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + let track = reader + .tracks() + .values() + .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) + .unwrap() + .track_id(); + ids.into_iter() + .map(|id| { + reader + .read_sample(track, id) + .unwrap() + .unwrap_or_else(|| panic!("no sample {id} in {name}")) + .bytes + .to_vec() + }) + .collect() +} + +fn assert_same_bytes(got: &[AacPacket], want: &[Vec], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: packet count"); + for (i, (p, w)) in got.iter().zip(want).enumerate() { + assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len()); + } +} + +fn copy(segs: &[(usize, f64, f64)]) -> Vec { + AudioSession::copy_multi_segments(&sources(), segs) + .expect("copy") + .expect("the first source has an audio track") + .1 +} + +#[test] +fn two_sources_join_without_a_gap() { + let (got, first, chunks) = multi(&[(0, 1.0, 2.0), (1, 0.0, 1.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 half = RATE as usize * CHANNELS; + assert_close(&got[..half], &window("test_av.mp4", 1.0, RATE), "source 0"); + assert_close(&got[half..], &window("test_av2.mp4", 0.0, RATE), "source 1"); + + // And the two halves are audibly different files, not the same one twice: + // an octave-and-a-fifth apart, 440 -> 660 Hz. + let (c0, c1) = (cycles(&got[..half]), cycles(&got[half..])); + eprintln!("cycles: {c0} then {c1}"); + assert!( + (c1 as f64 / c0 as f64 - 1.5).abs() < 0.1, + "{c0} then {c1} cycles: expected the 440 Hz source then the 660 Hz one" + ); +} + +#[test] +fn each_source_ends_where_its_own_track_does() { + // test_av2 is 4 s: the ask runs a second past it and must simply stop there, + // then the next segment continues the numbering (`drain` checks that). + let (got, first, _) = multi(&[(1, 3.5, 5.0), (0, 0.0, 0.5)]); + assert_eq!(first, 3 * RATE + RATE / 2); + let frames = got.len() as u64 / CHANNELS as u64; + assert!( + (RATE..=RATE + PACKET).contains(&frames), + "{frames} frames for 0.5 s of a 4 s source plus 0.5 s of the next \ + (+0..={PACKET} tail padding)" + ); + let tail = got.len() - RATE as usize / 2 * CHANNELS; + assert_close( + &got[tail..], + &window("test_av.mp4", 0.0, RATE / 2), + "back to source 0", + ); +} + +#[test] +fn probe_reads_the_import_policy_fields() { + let av = AudioSession::probe(asset("test_av.mp4")) + .expect("probe") + .expect("test_av.mp4 has audio"); + assert_eq!(av.channels, 2); + assert_eq!(av.params.sample_rate, RATE as u32); + assert_eq!( + AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(), + av, + "the fixtures are the matching pair import must accept" + ); + for silent in ["test_baseline.mp4", "test_mismatch.mp4"] { + assert!( + AudioSession::probe(asset(silent)).unwrap().is_none(), + "{silent} has no audio track" + ); + } +} + +#[test] +fn one_rounding_debt_is_carried_across_the_source_joins() { + // A second is 43.07 packets, so seven seconds copy 43 each and owe 68 + // samples apiece; the eighth crosses half a packet and copies 44 (the unit + // test `packet_run_rounds_against_the_running_debt` pins that arithmetic). + // Per segment rounding would copy 43 eight times and start drifting out of + // sync — and every one of these joins is a *source* join. + let segs: Vec<_> = (0..8).map(|i| (i % 2, 0.0, 1.0)).collect(); + let packets = copy(&segs); + assert_eq!( + packets.len(), + 1 + 7 * 43 + 44, + "priming packet + seven seconds owing 68 each + the eighth repaying" + ); + let audible = (packets.len() as u64 - 1) * PACKET; + assert!( + (audible as i64 - 8 * RATE as i64).unsigned_abs() < PACKET, + "{audible} samples for 8 s over seven source joins" + ); +} + +#[test] +fn the_join_carries_no_second_priming_packet() { + let packets = copy(&[(0, 0.0, 1.0), (1, 0.0, 1.0)]); + let split = 1 + 43; + assert_eq!(packets.len(), split + 43); + for p in &packets { + assert_eq!(p.samples as u64, PACKET, "AAC-LC packets are 1024 frames"); + } + // Source 0 from id 1 — its own priming packet, the one the reader drops. + assert_same_bytes(&packets[..split], &raw("test_av.mp4", 1..=44), "source 0"); + // Source 1 from id 2: 0.0 s is media 1024 (its priming), which packet 2 + // holds. Starting at id 1 here would insert a packet the reader keeps. + assert_same_bytes( + &packets[split..], + &raw("test_av2.mp4", 2..45), + "source 1 at the join", + ); +} + +#[test] +fn a_source_without_the_timeline_audio_is_refused() { + // Import refuses these up front (same rate, same layout, or both silent); + // the copy and the decode paths refuse them again rather than mislabel one + // esds for two different tracks. + let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; + let segs = [(0, 0.0, 1.0), (1, 0.0, 1.0)]; + // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) + for e in [ + AudioSession::copy_multi_segments(&mixed, &segs).err(), + AudioSession::open_multi_segments(&mixed, &segs).err(), + ] + .map(|e| e.expect("a source with no audio track must be refused")) + { + let msg = e.to_string(); + assert!(msg.contains("source 1"), "{msg}"); + } + // An out-of-range index is an error, not a panic. + assert!(AudioSession::copy_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); + assert!(AudioSession::open_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); +}