diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index c58cd6b..1f9e8a8 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -27,6 +27,9 @@ const EMPTY_EDIT: u64 = u32::MAX as u64; /// overlap-add that reconstructs the target packet, one to warm the decoder. const PRE_ROLL: u32 = 2; +/// Frames per channel one AAC-LC packet carries. Fixed by the codec. +const SAMPLES_PER_PACKET: u32 = 1024; + #[derive(Debug, Clone, Copy, PartialEq)] pub struct AudioMeta { pub sample_rate: u32, @@ -45,6 +48,23 @@ pub struct AudioChunk { pub samples: Vec, } +/// What a writer needs to declare an AAC track that plays copied packets: the +/// esds fields verbatim from the source, no re-derivation. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AacTrackParams { + pub freq_index: u8, + pub chan_conf: u8, + pub sample_rate: u32, +} + +/// One raw AAC access unit exactly as it sits in the source `mdat` — no ADTS +/// header, which is the form an `mp4a` sample table wants. +pub struct AacPacket { + pub bytes: Vec, + /// Frames per channel it decodes to, for the writer's stts. + pub samples: u32, +} + pub struct AudioSession; impl AudioSession { @@ -138,19 +158,7 @@ impl AudioSession { // 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_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), @@ -187,12 +195,122 @@ impl AudioSession { })?; Ok(Some((meta, rx))) } + + /// 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 + /// straight into an mp4 writer, which is the only way to keep audio in an + /// export at all (no pure-Rust AAC encoder exists). + /// + /// Cut points do not land on 1024-sample boundaries, so each segment is + /// rounded to whole packets against an error carried across the joins (see + /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the + /// asked-for length however many cuts there are, instead of drifting out of + /// lip sync one rounding at a time. + /// + /// The run starts one packet before the first audible one, which a reader + /// drops as encoder priming — for a segment list starting at 0.0 that is the + /// source's own priming packet, so the copy is the whole track from sample 1. + /// + /// `Ok(None)` for a file with no AAC track, and for an empty segment list. + /// + /// ponytail: the first packet after an *interior* join decodes without its + /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is + /// re-encoding just the join packets, which needs an encoder we do not have. + pub fn copy_segments( + path: impl AsRef, + segs: &[(f64, f64)], + ) -> crate::Result)>> { + if segs.is_empty() { + return Ok(None); + } + let file = File::open(path.as_ref())?; + let size = file.metadata()?.len(); + let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?; + + let Some(track) = reader + .tracks() + .values() + .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) + else { + return Ok(None); + }; + // The 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. + match track.audio_profile()? { + AudioObjectType::AacLowComplexity => {} + other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), + } + + let track_id = track.track_id(); + let sample_rate = track.sample_freq_index()?.freq(); + 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)?; + + // 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)); + } + + 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, + ))) + } } -/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14 -/// parses those out and drops the raw bytes, so this is the exact inverse of its -/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`). -fn audio_specific_config(track: &Mp4Track) -> crate::Result> { +/// How many whole packets to copy for a window of `ideal` samples per channel, +/// capped at the `available` packets left in the track. +/// +/// `err` is "samples copied so far minus samples asked for", carried across the +/// segment joins: rounding to nearest *against the running debt* keeps the +/// cumulative error inside half a packet forever, where independent per-segment +/// rounding would random-walk away from sync (charter D1: < 1024 at every join). +fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { + let packet = i64::from(SAMPLES_PER_PACKET); + // Never carry a debt the track cannot pay: a segment running past the end + // would otherwise inflate every later one. (Also tames `f64::INFINITY`, + // which saturates to `i64::MAX` on the cast above.) + let ideal = ideal.min(i64::from(available) * packet); + let want = (ideal - *err) as f64 / packet as f64; + let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32; + *err += i64::from(n) * packet - ideal; + n +} + +/// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a +/// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside +/// the crate (same trap as `SttsEntry`, see [`packet_at`]). +fn asc_fields(track: &Mp4Track) -> crate::Result<(u8, u8, u8)> { let esds = track .trak .mdia @@ -204,12 +322,34 @@ fn audio_specific_config(track: &Mp4Track) -> crate::Result> { .and_then(|mp4a| mp4a.esds.as_ref()) .ok_or("AAC track has no esds descriptor")?; let cfg = &esds.es_desc.dec_config.dec_specific; + Ok((cfg.profile, cfg.freq_index, cfg.chan_conf)) +} + +/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14 +/// parses those out and drops the raw bytes, so this is the exact inverse of its +/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`). +fn audio_specific_config(track: &Mp4Track) -> crate::Result> { + let (profile, freq_index, chan_conf) = asc_fields(track)?; Ok(Box::new([ - (cfg.profile << 3) | (cfg.freq_index >> 1), - (cfg.freq_index << 7) | (cfg.chan_conf << 3), + (profile << 3) | (freq_index >> 1), + (freq_index << 7) | (chan_conf << 3), ])) } +/// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`] +/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. +fn stts_pairs(track: &Mp4Track) -> impl Iterator + '_ { + track + .trak + .mdia + .minf + .stbl + .stts + .entries + .iter() + .map(|e| (e.sample_count, e.sample_delta)) +} + /// Encoder delay in samples-per-channel: the edit list's first real entry says /// how far into the media the presentation starts. /// @@ -396,7 +536,7 @@ fn run(mut w: Worker) { #[cfg(test)] mod tests { - use super::{PRE_ROLL, packet_at}; + use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run}; /// A real AAC track: one stts entry, N packets of 1024. fn aac(count: u32) -> impl IntoIterator { @@ -437,6 +577,66 @@ mod tests { assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240)); } + /// xorshift64: adversarial segment lists do not deserve a dependency. + fn rng(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } + + #[test] + fn packet_run_keeps_cumulative_error_under_a_packet() { + let packet = i64::from(SAMPLES_PER_PACKET); + let mut state = 0x5eed_1234_9876_abcd; + for rate in [44100i64, 48000] { + for list in 0..100 { + let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64); + // 3..43 joins of anything from one video frame to four seconds. + for join in 0..3 + rng(&mut state) % 40 { + let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64; + copied += i64::from(packet_run(&mut err, ideal, u32::MAX)); + asked += ideal; + assert!( + err.abs() < packet, + "rate {rate} list {list} join {join}: err {err}" + ); + } + // The accumulator is the whole story: what it says is the drift. + assert_eq!(copied * packet - asked, err); + } + } + } + + #[test] + fn packet_run_rounds_against_the_running_debt() { + // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples + // owed, and the debt is repaid by a 44-packet second once it crosses a + // half packet — never by letting each second round on its own. + let mut err = 0; + assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43); + assert_eq!(err, -68); + let mut seconds = 1; + while packet_run(&mut err, 44100, u32::MAX) == 43 { + seconds += 1; + assert!(seconds < 20, "debt never repaid, err {err}"); + } + assert_eq!(seconds, 7, "68 samples a second, half a packet is 512"); + assert!(err > 0, "the repaying second overshoots, err {err}"); + } + + #[test] + fn packet_run_forgives_a_debt_the_track_cannot_pay() { + // Asking a second of a track with ten packets left: it delivers ten and + // does not make the next segment copy the shortfall from elsewhere. + let mut err = 0; + assert_eq!(packet_run(&mut err, 44100, 10), 10); + assert_eq!(err, 0); + // Degenerate windows are empty, not negative. + assert_eq!(packet_run(&mut err, 0, 10), 0); + assert_eq!(packet_run(&mut err, i64::MAX, 7), 7); + } + #[test] fn asc_round_trips_aac_lc_44100_stereo() { // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5df93f5..83b4cc8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,6 +7,7 @@ pub mod convert; pub mod decode; pub mod demux; pub mod hw; +pub mod mux; pub mod playback; pub mod project; @@ -14,6 +15,7 @@ pub use audio::{AudioChunk, AudioMeta, AudioSession}; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; +pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; pub use project::{Clip, Project}; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs new file mode 100644 index 0000000..12e61a4 --- /dev/null +++ b/crates/engine/src/mux.rs @@ -0,0 +1,417 @@ +//! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs, +//! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`. + +use std::fs::File; +use std::io::BufWriter; +use std::path::Path; + +use mp4::{ + AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config, + Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, +}; + +/// 90 kHz is the H.264 convention; frame durations round to well under a +/// microsecond of error at every fps we care about. +const VIDEO_TIMESCALE: u32 = 90_000; +const MOVIE_TIMESCALE: u32 = 1_000; +/// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the +/// per-packet duration is this constant. +const AAC_PACKET_SAMPLES: u32 = 1024; + +const NAL_IDR: u8 = 5; +const NAL_SEI: u8 = 6; +const NAL_SPS: u8 = 7; +const NAL_PPS: u8 = 8; +const NAL_AUD: u8 = 9; + +pub struct VideoParams<'a> { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + pub sps: &'a [u8], + pub pps: &'a [u8], +} + +/// Read straight off the source file's `esds`: export copies AAC packets, it +/// never re-encodes, so the decoder config is passed through unchanged. +pub struct AudioParams { + pub freq_index: u8, + pub chan_conf: u8, +} + +/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores +/// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so +/// every sample handed over must carry an exact duration or the tracks drift. +pub struct Mp4Muxer { + writer: Mp4Writer>, + frame_duration: u32, + has_audio: bool, +} + +const VIDEO_TRACK: u32 = 1; +const AUDIO_TRACK: u32 = 2; + +impl Mp4Muxer { + pub fn create( + path: &Path, + video: &VideoParams, + audio: Option<&AudioParams>, + ) -> crate::Result { + if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { + return Err(format!("bad frame rate {}", video.frame_rate).into()); + } + if video.width == 0 + || video.height == 0 + || video.width > u16::MAX as u32 + || video.height > u16::MAX as u32 + { + return Err(format!("bad dimensions {}x{}", video.width, video.height).into()); + } + // AvcCBox::new indexes sps[1..=3] for profile/level, so a short SPS panics + // inside the mp4 crate; refuse it here where the message still means something. + if video.sps.len() < 4 || video.pps.is_empty() { + return Err("no usable SPS/PPS for the video track".into()); + } + + let mut writer = Mp4Writer::write_start( + BufWriter::new(File::create(path)?), + &Mp4Config { + major_brand: FourCC::from(*b"isom"), + minor_version: 512, + compatible_brands: vec![ + FourCC::from(*b"isom"), + FourCC::from(*b"iso2"), + FourCC::from(*b"avc1"), + FourCC::from(*b"mp41"), + ], + timescale: MOVIE_TIMESCALE, + }, + )?; + writer.add_track(&TrackConfig { + track_type: TrackType::Video, + timescale: VIDEO_TIMESCALE, + language: "und".to_string(), + media_conf: MediaConfig::AvcConfig(AvcConfig { + width: video.width as u16, + height: video.height as u16, + seq_param_set: video.sps.to_vec(), + pic_param_set: video.pps.to_vec(), + }), + })?; + if let Some(audio) = audio { + let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; + let sample_rate = freq_index.freq(); + writer.add_track(&TrackConfig { + track_type: TrackType::Audio, + timescale: sample_rate, + language: "und".to_string(), + media_conf: MediaConfig::AacConfig(AacConfig { + bitrate: 0, + profile: AudioObjectType::AacLowComplexity, + freq_index, + chan_conf: ChannelConfig::try_from(audio.chan_conf)?, + }), + })?; + } + + Ok(Self { + writer, + frame_duration: (VIDEO_TIMESCALE as f64 / video.frame_rate).round() as u32, + has_audio: audio.is_some(), + }) + } + + /// One coded picture, Annex-B framed. Parameter sets inside it are dropped + /// (they are already in `avcC`); an IDR slice marks the sample as a sync point. + pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> { + let (bytes, is_sync) = annex_b_to_avcc(annex_b)?; + self.writer.write_sample( + VIDEO_TRACK, + &Mp4Sample { + start_time: 0, // ignored by the writer; timing is duration-accumulated + duration: self.frame_duration, + rendering_offset: 0, // no B-frames on either encode path + is_sync, + bytes: Bytes::from(bytes), + }, + )?; + Ok(()) + } + + /// One raw AAC packet (no ADTS header), copied verbatim from the source. + pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> { + if !self.has_audio { + return Err("audio packet written to a video-only file".into()); + } + self.writer.write_sample( + AUDIO_TRACK, + &Mp4Sample { + start_time: 0, + duration: AAC_PACKET_SAMPLES, + rendering_offset: 0, + // Every AAC packet is a sync point; saying so per-sample would emit + // an `stss` listing all of them, while no `stss` means the same thing. + is_sync: false, + bytes: Bytes::copy_from_slice(bytes), + }, + )?; + Ok(()) + } + + pub fn finish(mut self) -> crate::Result<()> { + self.writer.write_end()?; + Ok(()) + } +} + +/// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the +/// unit does not carry both, which the first exported unit always must. +pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { + let nals = split_annex_b(annex_b); + let sps = nals.iter().find(|n| nal_type(n) == NAL_SPS)?; + let pps = nals.iter().find(|n| nal_type(n) == NAL_PPS)?; + Some((sps, pps)) +} + +/// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only +/// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`). +/// Parameter sets, access unit delimiters and SEI are stripped — the first two +/// are redundant with `avcC`, SEI is not worth carrying. Returns the sample +/// bytes and whether the unit is an IDR. +fn annex_b_to_avcc(annex_b: &[u8]) -> crate::Result<(Vec, bool)> { + let mut out = Vec::with_capacity(annex_b.len()); + let mut is_idr = false; + for nal in split_annex_b(annex_b) { + match nal_type(nal) { + NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue, + NAL_IDR => is_idr = true, + _ => {} + } + out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); + out.extend_from_slice(nal); + } + if out.is_empty() { + return Err("access unit has no coded slice".into()); + } + Ok((out, is_idr)) +} + +/// NAL payloads of an Annex-B buffer, both 3- and 4-byte start codes, trailing +/// zero bytes trimmed (they belong to the next start code, or are padding). +fn split_annex_b(src: &[u8]) -> Vec<&[u8]> { + let mut nals = Vec::new(); + let mut start = None; + let mut i = 0; + while i + 2 < src.len() { + if src[i] == 0 && src[i + 1] == 0 && src[i + 2] == 1 { + if let Some(s) = start { + push_nal(&mut nals, &src[s..i]); + } + i += 3; + start = Some(i); + } else { + i += 1; + } + } + if let Some(s) = start { + push_nal(&mut nals, &src[s..]); + } + nals +} + +fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) { + let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1); + if end > 0 { + nals.push(&nal[..end]); + } +} + +fn nal_type(nal: &[u8]) -> u8 { + nal[0] & 0x1F +} + +#[cfg(test)] +mod tests { + use std::io::BufReader; + + use super::*; + + const SPS: &[u8] = &[0x67, 0x42, 0x00, 0x1E, 0xAB]; + const PPS: &[u8] = &[0x68, 0xCE, 0x3C, 0x80]; + + fn au(nals: &[&[u8]]) -> Vec { + let mut v = Vec::new(); + for nal in nals { + v.extend_from_slice(&[0, 0, 0, 1]); + v.extend_from_slice(nal); + } + v + } + + #[test] + fn splits_both_start_code_lengths() { + let src = [ + 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68, 0xBB, 0, 0, 0, 1, 0x65, 0xCC, + ]; + let nals = split_annex_b(&src); + assert_eq!(nals, [&[0x67, 0xAA][..], &[0x68, 0xBB], &[0x65, 0xCC]]); + } + + #[test] + fn trims_trailing_zero_padding() { + let src = [0, 0, 0, 1, 0x65, 0xCC, 0, 0, 0]; + assert_eq!(split_annex_b(&src), [&[0x65, 0xCC][..]]); + } + + #[test] + fn repacks_multi_nal_unit_and_drops_parameter_sets() { + let slice = [0x65, 0x88, 0x99]; + let (bytes, is_idr) = annex_b_to_avcc(&au(&[SPS, PPS, &[0x09, 0x10], &slice])).unwrap(); + assert!(is_idr); + assert_eq!( + bytes, + [0, 0, 0, 3, 0x65, 0x88, 0x99], + "4-byte prefix, slice only" + ); + + let (bytes, is_idr) = annex_b_to_avcc(&au(&[&[0x41, 0x9A], &[0x41, 0x9B]])).unwrap(); + assert!(!is_idr, "no IDR slice in the unit"); + assert_eq!(bytes, [0, 0, 0, 2, 0x41, 0x9A, 0, 0, 0, 2, 0x41, 0x9B]); + } + + #[test] + fn rejects_units_with_no_slice() { + assert!(annex_b_to_avcc(&[]).is_err(), "empty"); + assert!(annex_b_to_avcc(&[0x65, 0x88]).is_err(), "no start code"); + assert!( + annex_b_to_avcc(&au(&[SPS, PPS])).is_err(), + "parameter sets only" + ); + } + + #[test] + fn finds_parameter_sets() { + assert_eq!( + parameter_sets(&au(&[SPS, PPS, &[0x65, 0x11]])), + Some((SPS, PPS)) + ); + assert!( + parameter_sets(&au(&[SPS, &[0x65, 0x11]])).is_none(), + "no PPS" + ); + } + + #[test] + fn create_rejects_unusable_config() { + let out = std::env::temp_dir().join("ve_mux_never_written.mp4"); + let ok = VideoParams { + width: 64, + height: 64, + frame_rate: 30.0, + sps: SPS, + pps: PPS, + }; + assert!( + Mp4Muxer::create( + &out, + &VideoParams { + sps: &SPS[..3], + ..ok + }, + None + ) + .is_err(), + "SPS too short for avcC" + ); + assert!( + Mp4Muxer::create( + &out, + &VideoParams { + frame_rate: 0.0, + ..ok + }, + None + ) + .is_err() + ); + assert!( + Mp4Muxer::create(&out, &VideoParams { width: 0, ..ok }, None).is_err(), + "zero width" + ); + let _ = std::fs::remove_file(&out); + } + + /// Three encoder-shaped access units out, then back in through both `mp4`'s + /// own reader and our `Demuxer` — the round trip is what proves the repack is + /// the exact inverse of `demux::append_annex_b`. + #[test] + fn round_trips_through_both_readers() { + let units = [ + au(&[SPS, PPS, &[0x65, 0x01, 0x02, 0x03]]), + au(&[&[0x41, 0x04, 0x05]]), + au(&[&[0x41, 0x06]]), + ]; + let out = std::env::temp_dir().join(format!("ve_mux_{}.mp4", std::process::id())); + + let mut muxer = Mp4Muxer::create( + &out, + &VideoParams { + width: 1280, + height: 720, + frame_rate: 30.0, + sps: SPS, + pps: PPS, + }, + Some(&AudioParams { + freq_index: 4, // 44100 + chan_conf: 2, + }), + ) + .unwrap(); + for unit in &units { + muxer.write_video_au(unit).unwrap(); + } + muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap(); + muxer.write_audio_packet(&[0x24, 0x25]).unwrap(); + muxer.finish().unwrap(); + + let file = File::open(&out).unwrap(); + let size = file.metadata().unwrap().len(); + let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + let (video_id, audio_id) = (VIDEO_TRACK, AUDIO_TRACK); + assert_eq!(reader.sample_count(video_id).unwrap(), 3); + assert_eq!(reader.sample_count(audio_id).unwrap(), 2); + { + let track = &reader.tracks()[&video_id]; + assert_eq!((track.width(), track.height()), (1280, 720)); + assert_eq!(track.frame_rate().round(), 30.0); + assert_eq!(track.sequence_parameter_set().unwrap(), SPS); + assert_eq!(track.picture_parameter_set().unwrap(), PPS); + } + let first = reader.read_sample(video_id, 1).unwrap().unwrap(); + assert!(first.is_sync, "IDR unit is a sync sample"); + assert_eq!(first.duration, 3000, "90000 / 30 fps"); + assert_eq!(&first.bytes[..], [0, 0, 0, 4, 0x65, 0x01, 0x02, 0x03]); + assert!(!reader.read_sample(video_id, 2).unwrap().unwrap().is_sync); + assert_eq!( + &reader.read_sample(audio_id, 1).unwrap().unwrap().bytes[..], + [0x21, 0x22, 0x23], + "audio packets copied verbatim" + ); + + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap(); + assert_eq!(meta.frame_count, 3); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert_eq!(meta.frame_rate.round(), 30.0); + for expected in &units { + assert_eq!( + &demuxer.next_access_unit().unwrap().unwrap(), + expected, + "demux returns the exact bytes that went in" + ); + } + assert!(demuxer.next_access_unit().unwrap().is_none()); + + std::fs::remove_file(&out).unwrap(); + } +} diff --git a/crates/engine/tests/audio_copy.rs b/crates/engine/tests/audio_copy.rs new file mode 100644 index 0000000..905a609 --- /dev/null +++ b/crates/engine/tests/audio_copy.rs @@ -0,0 +1,124 @@ +//! `AudioSession::copy_segments` hands out the source's own AAC bytes — nothing +//! is decoded and nothing is re-encoded. What has to hold: the bytes are +//! verbatim, the run starts one packet early (the source priming packet), and +//! the per-segment packet counts follow the bresenham rounding so a cut list +//! does not walk out of lip sync. + +use std::fs::File; +use std::io::BufReader; +use std::path::PathBuf; + +use engine::audio::{AacPacket, AudioSession}; +use mp4::{MediaType, Mp4Reader}; + +const RATE: f64 = 44100.0; +/// Frames per channel in one AAC-LC packet. +const PACKET: usize = 1024; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn copy(segs: &[(f64, f64)]) -> Vec { + AudioSession::copy_segments(asset("test_av.mp4"), segs) + .expect("copy") + .expect("test_av.mp4 has an audio track") + .1 +} + +/// The AAC track's sample bytes for 1-based `ids`, read straight from the +/// demuxer — the reference the copy must match byte for byte. +fn raw(ids: impl IntoIterator) -> Vec> { + let file = File::open(asset("test_av.mp4")).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}")) + .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()); + assert_eq!(p.samples as usize, PACKET, "{what}: packet {i} duration"); + } +} + +#[test] +fn whole_track_copy_is_byte_identical() { + // The fixture is 5 s, so this asks for all of it: the copy must be the raw + // sample table from id 1 (priming packet included) with nothing rewritten. + let packets = copy(&[(0.0, 5.0)]); + let ids = 1..=packets.len() as u32; + eprintln!("copied {} packets", packets.len()); + assert_same_bytes(&packets, &raw(ids), "0..5 s"); + + // Audible length (priming dropped by the reader) inside half a packet of 5 s. + let audible = ((packets.len() - 1) * PACKET) as f64; + assert!( + (audible - 5.0 * RATE).abs() < PACKET as f64, + "{audible} samples for 5 s" + ); +} + +#[test] +fn two_segments_match_the_bresenham_prediction() { + let packets = copy(&[(0.0, 1.0), (2.0, 3.0)]); + // One second is 43.07 packets: the first segment copies 43 and owes 68 + // samples, so the second is measured against 44100 + 68 = 43.13 -> 43 too. + let n1 = (RATE / PACKET as f64).round(); + let err = n1 * PACKET as f64 - RATE; + let n2 = ((RATE - err) / PACKET as f64).round(); + assert_eq!((n1, n2), (43.0, 43.0), "arithmetic changed, not the code"); + assert_eq!(packets.len(), 1 + n1 as usize + n2 as usize); + + // Segment 1 is ids 1 (priming) .. 1 + 43; the fixture carries the standard + // 1024 priming (see tests/audio_segments.rs), so 2.0 s is media sample + // 88200 + 1024 = 89224, which packet 88 ([89088, 90112)) holds. + let split = 1 + n1 as usize; + assert_same_bytes(&packets[..split], &raw(1..=split as u32), "0..1 s"); + assert_same_bytes( + &packets[split..], + &raw(88..88 + n2 as u32), + "2..3 s starting at packet 88", + ); + + // Two seconds asked for, two seconds copied, to inside half a packet. + let audible = ((packets.len() - 1) * PACKET) as f64; + assert!( + (audible - 2.0 * RATE).abs() < PACKET as f64, + "{audible} samples for 2 s over one join" + ); +} + +#[test] +fn nothing_to_copy_is_a_clean_none() { + assert!( + AudioSession::copy_segments(asset("test_av.mp4"), &[]) + .unwrap() + .is_none(), + "an empty edit list copies nothing" + ); + assert!( + AudioSession::copy_segments(asset("test_baseline.mp4"), &[(0.0, 1.0)]) + .unwrap() + .is_none(), + "a file with no AAC track is a valid silent session" + ); +}