forge
Explore
Log in

Don't you dare go Hollow

Export lane 1 — mux module, AAC packet copy

Browse files at this commit

5ce68fe331a1f4da8c181321bda67f8314db4fe8Ahmet Kaan GümüşParent: bffc034
  • feat
    • export lane 1 — mux module, AAC packet copy
Show full message
✨ feat(engine): export lane 1 — mux module, AAC packet copy

mux.rs is the write side of demux.rs: split_annex_b/nal_type feed a
repack to 4-byte-length-prefixed samples (mp4 0.14 hardcodes
length_size_minus_one=3), SPS/PPS/AUD/SEI stripped out of the sample
bytes, is_sync taken from an actual NAL type 5 rather than GOP
arithmetic. Mp4Muxer::create wants the parameter sets up front, so
mux::parameter_sets pulls them out of a buffered first access unit
before the muxer exists. Timescales are 90000 video / sample_rate audio
/ 1000 movie, per-frame duration (90000/fps).round(), and mp4 0.14
ignores Mp4Sample::start_time on write -- timing is duration
accumulation only. An SPS shorter than 4 bytes panics inside the crate
(avc1.rs indexes sps[1..3]), so create rejects that and the other
degenerate shapes up front instead.

Audio is copied, not re-encoded: there is no pure-Rust AAC encoder and
mp4 0.14 has no PCM MediaConfig, so the only honest option is to hand
the source packets back through verbatim.
AudioSession::copy_segments does that -- stts walk to packet ids, no
decode, bytes straight from read_sample. Cut points do not land on
1024-sample boundaries (23.2 ms packets vs 33.3 ms frames), so a
bresenham accumulator picks the packet run per segment and keeps the
cumulative A/V offset under 512 samples, proven by induction over the
carry and measured over 200 random join lists. The first segment starts
one packet early to feed the 1024-sample priming drop; interior
segments do not, because an extra head packet there is 23 ms of
pre-cut audio at every join and it would not fix the missing MDCT
predecessor anyway. That artifact is documented at the seam.
crates/engine/src/audio.rsmodified+220 -20
@@ -27,6 +27,9 @@ const EMPTY_EDIT: u64 = u32::MAX as u64;
27 /// overlap-add that reconstructs the target packet, one to warm the decoder.27 /// overlap-add that reconstructs the target packet, one to warm the decoder.
28 const PRE_ROLL: u32 = 2;28 const PRE_ROLL: u32 = 2;
29 29
30+/// Frames per channel one AAC-LC packet carries. Fixed by the codec.
31+const SAMPLES_PER_PACKET: u32 = 1024;
32+
30 #[derive(Debug, Clone, Copy, PartialEq)]33 #[derive(Debug, Clone, Copy, PartialEq)]
31 pub struct AudioMeta {34 pub struct AudioMeta {
32 pub sample_rate: u32,35 pub sample_rate: u32,
@@ -45,6 +48,23 @@ pub struct AudioChunk {
45 pub samples: Vec<f32>,48 pub samples: Vec<f32>,
46 }49 }
47 50
51+/// What a writer needs to declare an AAC track that plays copied packets: the
52+/// esds fields verbatim from the source, no re-derivation.
53+#[derive(Debug, Clone, Copy, PartialEq)]
54+pub struct AacTrackParams {
55+ pub freq_index: u8,
56+ pub chan_conf: u8,
57+ pub sample_rate: u32,
58+}
59+
60+/// One raw AAC access unit exactly as it sits in the source `mdat` — no ADTS
61+/// header, which is the form an `mp4a` sample table wants.
62+pub struct AacPacket {
63+ pub bytes: Vec<u8>,
64+ /// Frames per channel it decodes to, for the writer's stts.
65+ pub samples: u32,
66+}
67+
48 pub struct AudioSession;68 pub struct AudioSession;
49 69
50 impl AudioSession {70 impl AudioSession {
@@ -138,19 +158,7 @@ impl AudioSession {
138 // previous packet to cancel aliasing, plus one more to warm the158 // previous packet to cancel aliasing, plus one more to warm the
139 // decoder up. Their output is discarded below, so this only159 // decoder up. Their output is discarded below, so this only
140 // costs decode time.160 // costs decode time.
141- let (start_id, start_ts) = packet_at(161+ let (start_id, start_ts) = packet_at(stts_pairs(track), target_ts, PRE_ROLL);
142- track
143- .trak
144- .mdia
145- .minf
146- .stbl
147- .stts
148- .entries
149- .iter()
150- .map(|e| (e.sample_count, e.sample_delta)),
151- target_ts,
152- PRE_ROLL,
153- );
154 Segment {162 Segment {
155 start_id,163 start_id,
156 start_pos: scale(start_ts, sample_rate, track.timescale()).unwrap_or(0),164 start_pos: scale(start_ts, sample_rate, track.timescale()).unwrap_or(0),
@@ -187,12 +195,122 @@ impl AudioSession {
187 })?;195 })?;
188 Ok(Some((meta, rx)))196 Ok(Some((meta, rx)))
189 }197 }
198+
199+ /// The raw AAC packets covering `segs` — the same half-open source-second
200+ /// windows [`open_segments`](Self::open_segments) decodes — copied out
201+ /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
202+ /// straight into an mp4 writer, which is the only way to keep audio in an
203+ /// export at all (no pure-Rust AAC encoder exists).
204+ ///
205+ /// Cut points do not land on 1024-sample boundaries, so each segment is
206+ /// rounded to whole packets against an error carried across the joins (see
207+ /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the
208+ /// asked-for length however many cuts there are, instead of drifting out of
209+ /// lip sync one rounding at a time.
210+ ///
211+ /// The run starts one packet before the first audible one, which a reader
212+ /// drops as encoder priming — for a segment list starting at 0.0 that is the
213+ /// source's own priming packet, so the copy is the whole track from sample 1.
214+ ///
215+ /// `Ok(None)` for a file with no AAC track, and for an empty segment list.
216+ ///
217+ /// ponytail: the first packet after an *interior* join decodes without its
218+ /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is
219+ /// re-encoding just the join packets, which needs an encoder we do not have.
220+ pub fn copy_segments(
221+ path: impl AsRef<Path>,
222+ segs: &[(f64, f64)],
223+ ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
224+ if segs.is_empty() {
225+ return Ok(None);
226+ }
227+ let file = File::open(path.as_ref())?;
228+ let size = file.metadata()?.len();
229+ let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?;
230+
231+ let Some(track) = reader
232+ .tracks()
233+ .values()
234+ .find(|t| matches!(t.media_type(), Ok(MediaType::AAC)))
235+ else {
236+ return Ok(None);
237+ };
238+ // The copy carries no profile of its own: the writer rebuilds the
239+ // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a
240+ // non-LC source would be mislabelled rather than merely unplayable here.
241+ match track.audio_profile()? {
242+ AudioObjectType::AacLowComplexity => {}
243+ other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()),
244+ }
245+
246+ let track_id = track.track_id();
247+ let sample_rate = track.sample_freq_index()?.freq();
248+ let timescale = track.timescale();
249+ let priming = priming_samples(track, sample_rate);
250+ let (_, freq_index, chan_conf) = asc_fields(track)?;
251+ let sample_count = reader.sample_count(track_id)?;
252+
253+ // Resolve every packet id first: `read_sample` needs the reader mutably,
254+ // which ends the borrow `track` holds.
255+ let media = |secs: f64| ((secs * f64::from(sample_rate)) as u64).saturating_add(priming);
256+ let mut err = 0i64;
257+ let mut ids: Vec<u32> = Vec::new();
258+ for (i, &(start_secs, end_secs)) in segs.iter().enumerate() {
259+ let target_ts = unscale(media(start_secs), sample_rate, timescale);
260+ let (start_id, _) = packet_at(stts_pairs(track), target_ts, 0);
261+ let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
262+ let available = sample_count.saturating_sub(start_id - 1);
263+ if i == 0 && start_id > 1 {
264+ ids.push(start_id - 1); // priming, see the doc comment
265+ }
266+ ids.extend(start_id..start_id + packet_run(&mut err, ideal, available));
267+ }
268+
269+ let packets = ids
270+ .into_iter()
271+ .map(|id| match reader.read_sample(track_id, id)? {
272+ Some(sample) => Ok(AacPacket {
273+ bytes: sample.bytes.to_vec(),
274+ samples: SAMPLES_PER_PACKET,
275+ }),
276+ None => Err(format!("audio sample {id} of {sample_count} is missing").into()),
277+ })
278+ .collect::<crate::Result<Vec<_>>>()?;
279+
280+ Ok(Some((
281+ AacTrackParams {
282+ freq_index,
283+ chan_conf,
284+ sample_rate,
285+ },
286+ packets,
287+ )))
288+ }
190 }289 }
191 290
192-/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14291+/// How many whole packets to copy for a window of `ideal` samples per channel,
193-/// parses those out and drops the raw bytes, so this is the exact inverse of its292+/// capped at the `available` packets left in the track.
194-/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`).293+///
195-fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {294+/// `err` is "samples copied so far minus samples asked for", carried across the
295+/// segment joins: rounding to nearest *against the running debt* keeps the
296+/// cumulative error inside half a packet forever, where independent per-segment
297+/// rounding would random-walk away from sync (charter D1: < 1024 at every join).
298+fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
299+ let packet = i64::from(SAMPLES_PER_PACKET);
300+ // Never carry a debt the track cannot pay: a segment running past the end
301+ // would otherwise inflate every later one. (Also tames `f64::INFINITY`,
302+ // which saturates to `i64::MAX` on the cast above.)
303+ let ideal = ideal.min(i64::from(available) * packet);
304+ let want = (ideal - *err) as f64 / packet as f64;
305+ let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32;
306+ *err += i64::from(n) * packet - ideal;
307+ n
308+}
309+
310+/// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a
311+/// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside
312+/// the crate (same trap as `SttsEntry`, see [`packet_at`]).
313+fn asc_fields(track: &Mp4Track) -> crate::Result<(u8, u8, u8)> {
196 let esds = track314 let esds = track
197 .trak315 .trak
198 .mdia316 .mdia
@@ -204,12 +322,34 @@ fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {
204 .and_then(|mp4a| mp4a.esds.as_ref())322 .and_then(|mp4a| mp4a.esds.as_ref())
205 .ok_or("AAC track has no esds descriptor")?;323 .ok_or("AAC track has no esds descriptor")?;
206 let cfg = &esds.es_desc.dec_config.dec_specific;324 let cfg = &esds.es_desc.dec_config.dec_specific;
325+ Ok((cfg.profile, cfg.freq_index, cfg.chan_conf))
326+}
327+
328+/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14
329+/// parses those out and drops the raw bytes, so this is the exact inverse of its
330+/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`).
331+fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {
332+ let (profile, freq_index, chan_conf) = asc_fields(track)?;
207 Ok(Box::new([333 Ok(Box::new([
208- (cfg.profile << 3) | (cfg.freq_index >> 1),334+ (profile << 3) | (freq_index >> 1),
209- (cfg.freq_index << 7) | (cfg.chan_conf << 3),335+ (freq_index << 7) | (chan_conf << 3),
210 ]))336 ]))
211 }337 }
212 338
339+/// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`]
340+/// walks; the box's own entry type is `pub(crate)` in mp4 0.14.
341+fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
342+ track
343+ .trak
344+ .mdia
345+ .minf
346+ .stbl
347+ .stts
348+ .entries
349+ .iter()
350+ .map(|e| (e.sample_count, e.sample_delta))
351+}
352+
213 /// Encoder delay in samples-per-channel: the edit list's first real entry says353 /// Encoder delay in samples-per-channel: the edit list's first real entry says
214 /// how far into the media the presentation starts.354 /// how far into the media the presentation starts.
215 ///355 ///
@@ -396,7 +536,7 @@ fn run(mut w: Worker) {
396 536
397 #[cfg(test)]537 #[cfg(test)]
398 mod tests {538 mod tests {
399- use super::{PRE_ROLL, packet_at};539+ use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run};
400 540
401 /// A real AAC track: one stts entry, N packets of 1024.541 /// A real AAC track: one stts entry, N packets of 1024.
402 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {542 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
@@ -437,6 +577,66 @@ mod tests {
437 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));577 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
438 }578 }
439 579
580+ /// xorshift64: adversarial segment lists do not deserve a dependency.
581+ fn rng(state: &mut u64) -> u64 {
582+ *state ^= *state << 13;
583+ *state ^= *state >> 7;
584+ *state ^= *state << 17;
585+ *state
586+ }
587+
588+ #[test]
589+ fn packet_run_keeps_cumulative_error_under_a_packet() {
590+ let packet = i64::from(SAMPLES_PER_PACKET);
591+ let mut state = 0x5eed_1234_9876_abcd;
592+ for rate in [44100i64, 48000] {
593+ for list in 0..100 {
594+ let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64);
595+ // 3..43 joins of anything from one video frame to four seconds.
596+ for join in 0..3 + rng(&mut state) % 40 {
597+ let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64;
598+ copied += i64::from(packet_run(&mut err, ideal, u32::MAX));
599+ asked += ideal;
600+ assert!(
601+ err.abs() < packet,
602+ "rate {rate} list {list} join {join}: err {err}"
603+ );
604+ }
605+ // The accumulator is the whole story: what it says is the drift.
606+ assert_eq!(copied * packet - asked, err);
607+ }
608+ }
609+ }
610+
611+ #[test]
612+ fn packet_run_rounds_against_the_running_debt() {
613+ // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples
614+ // owed, and the debt is repaid by a 44-packet second once it crosses a
615+ // half packet — never by letting each second round on its own.
616+ let mut err = 0;
617+ assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43);
618+ assert_eq!(err, -68);
619+ let mut seconds = 1;
620+ while packet_run(&mut err, 44100, u32::MAX) == 43 {
621+ seconds += 1;
622+ assert!(seconds < 20, "debt never repaid, err {err}");
623+ }
624+ assert_eq!(seconds, 7, "68 samples a second, half a packet is 512");
625+ assert!(err > 0, "the repaying second overshoots, err {err}");
626+ }
627+
628+ #[test]
629+ fn packet_run_forgives_a_debt_the_track_cannot_pay() {
630+ // Asking a second of a track with ten packets left: it delivers ten and
631+ // does not make the next segment copy the shortfall from elsewhere.
632+ let mut err = 0;
633+ assert_eq!(packet_run(&mut err, 44100, 10), 10);
634+ assert_eq!(err, 0);
635+ // Degenerate windows are empty, not negative.
636+ assert_eq!(packet_run(&mut err, 0, 10), 0);
637+ assert_eq!(packet_run(&mut err, i64::MAX, 7), 7);
638+ }
639+
440 #[test]640 #[test]
441 fn asc_round_trips_aac_lc_44100_stereo() {641 fn asc_round_trips_aac_lc_44100_stereo() {
442 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).642 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
crates/engine/src/lib.rsmodified+2 -0
@@ -7,6 +7,7 @@ pub mod convert;
7 pub mod decode;7 pub mod decode;
8 pub mod demux;8 pub mod demux;
9 pub mod hw;9 pub mod hw;
10+pub mod mux;
10 pub mod playback;11 pub mod playback;
11 pub mod project;12 pub mod project;
12 13
@@ -14,6 +15,7 @@ pub use audio::{AudioChunk, AudioMeta, AudioSession};
14 pub use clock::PlaybackClock;15 pub use clock::PlaybackClock;
15 pub use decode::{DecodeSession, Frame};16 pub use decode::{DecodeSession, Frame};
16 pub use demux::VideoMeta;17 pub use demux::VideoMeta;
18+pub use mux::{AudioParams, Mp4Muxer, VideoParams};
17 pub use playback::PlaybackSession;19 pub use playback::PlaybackSession;
18 pub use project::{Clip, Project};20 pub use project::{Clip, Project};
19 21
crates/engine/src/mux.rsadded+417 -0
@@ -0,0 +1,417 @@
1+//! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs,
2+//! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`.
3+
4+use std::fs::File;
5+use std::io::BufWriter;
6+use std::path::Path;
7+
8+use mp4::{
9+ AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,
10+ Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType,
11+};
12+
13+/// 90 kHz is the H.264 convention; frame durations round to well under a
14+/// microsecond of error at every fps we care about.
15+const VIDEO_TIMESCALE: u32 = 90_000;
16+const MOVIE_TIMESCALE: u32 = 1_000;
17+/// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the
18+/// per-packet duration is this constant.
19+const AAC_PACKET_SAMPLES: u32 = 1024;
20+
21+const NAL_IDR: u8 = 5;
22+const NAL_SEI: u8 = 6;
23+const NAL_SPS: u8 = 7;
24+const NAL_PPS: u8 = 8;
25+const NAL_AUD: u8 = 9;
26+
27+pub struct VideoParams<'a> {
28+ pub width: u32,
29+ pub height: u32,
30+ pub frame_rate: f64,
31+ pub sps: &'a [u8],
32+ pub pps: &'a [u8],
33+}
34+
35+/// Read straight off the source file's `esds`: export copies AAC packets, it
36+/// never re-encodes, so the decoder config is passed through unchanged.
37+pub struct AudioParams {
38+ pub freq_index: u8,
39+ pub chan_conf: u8,
40+}
41+
42+/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores
43+/// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so
44+/// every sample handed over must carry an exact duration or the tracks drift.
45+pub struct Mp4Muxer {
46+ writer: Mp4Writer<BufWriter<File>>,
47+ frame_duration: u32,
48+ has_audio: bool,
49+}
50+
51+const VIDEO_TRACK: u32 = 1;
52+const AUDIO_TRACK: u32 = 2;
53+
54+impl Mp4Muxer {
55+ pub fn create(
56+ path: &Path,
57+ video: &VideoParams,
58+ audio: Option<&AudioParams>,
59+ ) -> crate::Result<Self> {
60+ if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
61+ return Err(format!("bad frame rate {}", video.frame_rate).into());
62+ }
63+ if video.width == 0
64+ || video.height == 0
65+ || video.width > u16::MAX as u32
66+ || video.height > u16::MAX as u32
67+ {
68+ return Err(format!("bad dimensions {}x{}", video.width, video.height).into());
69+ }
70+ // AvcCBox::new indexes sps[1..=3] for profile/level, so a short SPS panics
71+ // inside the mp4 crate; refuse it here where the message still means something.
72+ if video.sps.len() < 4 || video.pps.is_empty() {
73+ return Err("no usable SPS/PPS for the video track".into());
74+ }
75+
76+ let mut writer = Mp4Writer::write_start(
77+ BufWriter::new(File::create(path)?),
78+ &Mp4Config {
79+ major_brand: FourCC::from(*b"isom"),
80+ minor_version: 512,
81+ compatible_brands: vec![
82+ FourCC::from(*b"isom"),
83+ FourCC::from(*b"iso2"),
84+ FourCC::from(*b"avc1"),
85+ FourCC::from(*b"mp41"),
86+ ],
87+ timescale: MOVIE_TIMESCALE,
88+ },
89+ )?;
90+ writer.add_track(&TrackConfig {
91+ track_type: TrackType::Video,
92+ timescale: VIDEO_TIMESCALE,
93+ language: "und".to_string(),
94+ media_conf: MediaConfig::AvcConfig(AvcConfig {
95+ width: video.width as u16,
96+ height: video.height as u16,
97+ seq_param_set: video.sps.to_vec(),
98+ pic_param_set: video.pps.to_vec(),
99+ }),
100+ })?;
101+ if let Some(audio) = audio {
102+ let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;
103+ let sample_rate = freq_index.freq();
104+ writer.add_track(&TrackConfig {
105+ track_type: TrackType::Audio,
106+ timescale: sample_rate,
107+ language: "und".to_string(),
108+ media_conf: MediaConfig::AacConfig(AacConfig {
109+ bitrate: 0,
110+ profile: AudioObjectType::AacLowComplexity,
111+ freq_index,
112+ chan_conf: ChannelConfig::try_from(audio.chan_conf)?,
113+ }),
114+ })?;
115+ }
116+
117+ Ok(Self {
118+ writer,
119+ frame_duration: (VIDEO_TIMESCALE as f64 / video.frame_rate).round() as u32,
120+ has_audio: audio.is_some(),
121+ })
122+ }
123+
124+ /// One coded picture, Annex-B framed. Parameter sets inside it are dropped
125+ /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.
126+ pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {
127+ let (bytes, is_sync) = annex_b_to_avcc(annex_b)?;
128+ self.writer.write_sample(
129+ VIDEO_TRACK,
130+ &Mp4Sample {
131+ start_time: 0, // ignored by the writer; timing is duration-accumulated
132+ duration: self.frame_duration,
133+ rendering_offset: 0, // no B-frames on either encode path
134+ is_sync,
135+ bytes: Bytes::from(bytes),
136+ },
137+ )?;
138+ Ok(())
139+ }
140+
141+ /// One raw AAC packet (no ADTS header), copied verbatim from the source.
142+ pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {
143+ if !self.has_audio {
144+ return Err("audio packet written to a video-only file".into());
145+ }
146+ self.writer.write_sample(
147+ AUDIO_TRACK,
148+ &Mp4Sample {
149+ start_time: 0,
150+ duration: AAC_PACKET_SAMPLES,
151+ rendering_offset: 0,
152+ // Every AAC packet is a sync point; saying so per-sample would emit
153+ // an `stss` listing all of them, while no `stss` means the same thing.
154+ is_sync: false,
155+ bytes: Bytes::copy_from_slice(bytes),
156+ },
157+ )?;
158+ Ok(())
159+ }
160+
161+ pub fn finish(mut self) -> crate::Result<()> {
162+ self.writer.write_end()?;
163+ Ok(())
164+ }
165+}
166+
167+/// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the
168+/// unit does not carry both, which the first exported unit always must.
169+pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> {
170+ let nals = split_annex_b(annex_b);
171+ let sps = nals.iter().find(|n| nal_type(n) == NAL_SPS)?;
172+ let pps = nals.iter().find(|n| nal_type(n) == NAL_PPS)?;
173+ Some((sps, pps))
174+}
175+
176+/// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only
177+/// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`).
178+/// Parameter sets, access unit delimiters and SEI are stripped — the first two
179+/// are redundant with `avcC`, SEI is not worth carrying. Returns the sample
180+/// bytes and whether the unit is an IDR.
181+fn annex_b_to_avcc(annex_b: &[u8]) -> crate::Result<(Vec<u8>, bool)> {
182+ let mut out = Vec::with_capacity(annex_b.len());
183+ let mut is_idr = false;
184+ for nal in split_annex_b(annex_b) {
185+ match nal_type(nal) {
186+ NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue,
187+ NAL_IDR => is_idr = true,
188+ _ => {}
189+ }
190+ out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
191+ out.extend_from_slice(nal);
192+ }
193+ if out.is_empty() {
194+ return Err("access unit has no coded slice".into());
195+ }
196+ Ok((out, is_idr))
197+}
198+
199+/// NAL payloads of an Annex-B buffer, both 3- and 4-byte start codes, trailing
200+/// zero bytes trimmed (they belong to the next start code, or are padding).
201+fn split_annex_b(src: &[u8]) -> Vec<&[u8]> {
202+ let mut nals = Vec::new();
203+ let mut start = None;
204+ let mut i = 0;
205+ while i + 2 < src.len() {
206+ if src[i] == 0 && src[i + 1] == 0 && src[i + 2] == 1 {
207+ if let Some(s) = start {
208+ push_nal(&mut nals, &src[s..i]);
209+ }
210+ i += 3;
211+ start = Some(i);
212+ } else {
213+ i += 1;
214+ }
215+ }
216+ if let Some(s) = start {
217+ push_nal(&mut nals, &src[s..]);
218+ }
219+ nals
220+}
221+
222+fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) {
223+ let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1);
224+ if end > 0 {
225+ nals.push(&nal[..end]);
226+ }
227+}
228+
229+fn nal_type(nal: &[u8]) -> u8 {
230+ nal[0] & 0x1F
231+}
232+
233+#[cfg(test)]
234+mod tests {
235+ use std::io::BufReader;
236+
237+ use super::*;
238+
239+ const SPS: &[u8] = &[0x67, 0x42, 0x00, 0x1E, 0xAB];
240+ const PPS: &[u8] = &[0x68, 0xCE, 0x3C, 0x80];
241+
242+ fn au(nals: &[&[u8]]) -> Vec<u8> {
243+ let mut v = Vec::new();
244+ for nal in nals {
245+ v.extend_from_slice(&[0, 0, 0, 1]);
246+ v.extend_from_slice(nal);
247+ }
248+ v
249+ }
250+
251+ #[test]
252+ fn splits_both_start_code_lengths() {
253+ let src = [
254+ 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68, 0xBB, 0, 0, 0, 1, 0x65, 0xCC,
255+ ];
256+ let nals = split_annex_b(&src);
257+ assert_eq!(nals, [&[0x67, 0xAA][..], &[0x68, 0xBB], &[0x65, 0xCC]]);
258+ }
259+
260+ #[test]
261+ fn trims_trailing_zero_padding() {
262+ let src = [0, 0, 0, 1, 0x65, 0xCC, 0, 0, 0];
263+ assert_eq!(split_annex_b(&src), [&[0x65, 0xCC][..]]);
264+ }
265+
266+ #[test]
267+ fn repacks_multi_nal_unit_and_drops_parameter_sets() {
268+ let slice = [0x65, 0x88, 0x99];
269+ let (bytes, is_idr) = annex_b_to_avcc(&au(&[SPS, PPS, &[0x09, 0x10], &slice])).unwrap();
270+ assert!(is_idr);
271+ assert_eq!(
272+ bytes,
273+ [0, 0, 0, 3, 0x65, 0x88, 0x99],
274+ "4-byte prefix, slice only"
275+ );
276+
277+ let (bytes, is_idr) = annex_b_to_avcc(&au(&[&[0x41, 0x9A], &[0x41, 0x9B]])).unwrap();
278+ assert!(!is_idr, "no IDR slice in the unit");
279+ assert_eq!(bytes, [0, 0, 0, 2, 0x41, 0x9A, 0, 0, 0, 2, 0x41, 0x9B]);
280+ }
281+
282+ #[test]
283+ fn rejects_units_with_no_slice() {
284+ assert!(annex_b_to_avcc(&[]).is_err(), "empty");
285+ assert!(annex_b_to_avcc(&[0x65, 0x88]).is_err(), "no start code");
286+ assert!(
287+ annex_b_to_avcc(&au(&[SPS, PPS])).is_err(),
288+ "parameter sets only"
289+ );
290+ }
291+
292+ #[test]
293+ fn finds_parameter_sets() {
294+ assert_eq!(
295+ parameter_sets(&au(&[SPS, PPS, &[0x65, 0x11]])),
296+ Some((SPS, PPS))
297+ );
298+ assert!(
299+ parameter_sets(&au(&[SPS, &[0x65, 0x11]])).is_none(),
300+ "no PPS"
301+ );
302+ }
303+
304+ #[test]
305+ fn create_rejects_unusable_config() {
306+ let out = std::env::temp_dir().join("ve_mux_never_written.mp4");
307+ let ok = VideoParams {
308+ width: 64,
309+ height: 64,
310+ frame_rate: 30.0,
311+ sps: SPS,
312+ pps: PPS,
313+ };
314+ assert!(
315+ Mp4Muxer::create(
316+ &out,
317+ &VideoParams {
318+ sps: &SPS[..3],
319+ ..ok
320+ },
321+ None
322+ )
323+ .is_err(),
324+ "SPS too short for avcC"
325+ );
326+ assert!(
327+ Mp4Muxer::create(
328+ &out,
329+ &VideoParams {
330+ frame_rate: 0.0,
331+ ..ok
332+ },
333+ None
334+ )
335+ .is_err()
336+ );
337+ assert!(
338+ Mp4Muxer::create(&out, &VideoParams { width: 0, ..ok }, None).is_err(),
339+ "zero width"
340+ );
341+ let _ = std::fs::remove_file(&out);
342+ }
343+
344+ /// Three encoder-shaped access units out, then back in through both `mp4`'s
345+ /// own reader and our `Demuxer` — the round trip is what proves the repack is
346+ /// the exact inverse of `demux::append_annex_b`.
347+ #[test]
348+ fn round_trips_through_both_readers() {
349+ let units = [
350+ au(&[SPS, PPS, &[0x65, 0x01, 0x02, 0x03]]),
351+ au(&[&[0x41, 0x04, 0x05]]),
352+ au(&[&[0x41, 0x06]]),
353+ ];
354+ let out = std::env::temp_dir().join(format!("ve_mux_{}.mp4", std::process::id()));
355+
356+ let mut muxer = Mp4Muxer::create(
357+ &out,
358+ &VideoParams {
359+ width: 1280,
360+ height: 720,
361+ frame_rate: 30.0,
362+ sps: SPS,
363+ pps: PPS,
364+ },
365+ Some(&AudioParams {
366+ freq_index: 4, // 44100
367+ chan_conf: 2,
368+ }),
369+ )
370+ .unwrap();
371+ for unit in &units {
372+ muxer.write_video_au(unit).unwrap();
373+ }
374+ muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap();
375+ muxer.write_audio_packet(&[0x24, 0x25]).unwrap();
376+ muxer.finish().unwrap();
377+
378+ let file = File::open(&out).unwrap();
379+ let size = file.metadata().unwrap().len();
380+ let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
381+ let (video_id, audio_id) = (VIDEO_TRACK, AUDIO_TRACK);
382+ assert_eq!(reader.sample_count(video_id).unwrap(), 3);
383+ assert_eq!(reader.sample_count(audio_id).unwrap(), 2);
384+ {
385+ let track = &reader.tracks()[&video_id];
386+ assert_eq!((track.width(), track.height()), (1280, 720));
387+ assert_eq!(track.frame_rate().round(), 30.0);
388+ assert_eq!(track.sequence_parameter_set().unwrap(), SPS);
389+ assert_eq!(track.picture_parameter_set().unwrap(), PPS);
390+ }
391+ let first = reader.read_sample(video_id, 1).unwrap().unwrap();
392+ assert!(first.is_sync, "IDR unit is a sync sample");
393+ assert_eq!(first.duration, 3000, "90000 / 30 fps");
394+ assert_eq!(&first.bytes[..], [0, 0, 0, 4, 0x65, 0x01, 0x02, 0x03]);
395+ assert!(!reader.read_sample(video_id, 2).unwrap().unwrap().is_sync);
396+ assert_eq!(
397+ &reader.read_sample(audio_id, 1).unwrap().unwrap().bytes[..],
398+ [0x21, 0x22, 0x23],
399+ "audio packets copied verbatim"
400+ );
401+
402+ let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap();
403+ assert_eq!(meta.frame_count, 3);
404+ assert_eq!((meta.width, meta.height), (1280, 720));
405+ assert_eq!(meta.frame_rate.round(), 30.0);
406+ for expected in &units {
407+ assert_eq!(
408+ &demuxer.next_access_unit().unwrap().unwrap(),
409+ expected,
410+ "demux returns the exact bytes that went in"
411+ );
412+ }
413+ assert!(demuxer.next_access_unit().unwrap().is_none());
414+
415+ std::fs::remove_file(&out).unwrap();
416+ }
417+}
crates/engine/tests/audio_copy.rsadded+124 -0
@@ -0,0 +1,124 @@
1+//! `AudioSession::copy_segments` hands out the source's own AAC bytes — nothing
2+//! is decoded and nothing is re-encoded. What has to hold: the bytes are
3+//! verbatim, the run starts one packet early (the source priming packet), and
4+//! the per-segment packet counts follow the bresenham rounding so a cut list
5+//! does not walk out of lip sync.
6+
7+use std::fs::File;
8+use std::io::BufReader;
9+use std::path::PathBuf;
10+
11+use engine::audio::{AacPacket, AudioSession};
12+use mp4::{MediaType, Mp4Reader};
13+
14+const RATE: f64 = 44100.0;
15+/// Frames per channel in one AAC-LC packet.
16+const PACKET: usize = 1024;
17+
18+fn asset(name: &str) -> PathBuf {
19+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
20+ .join("../../assets")
21+ .join(name)
22+}
23+
24+fn copy(segs: &[(f64, f64)]) -> Vec<AacPacket> {
25+ AudioSession::copy_segments(asset("test_av.mp4"), segs)
26+ .expect("copy")
27+ .expect("test_av.mp4 has an audio track")
28+ .1
29+}
30+
31+/// The AAC track's sample bytes for 1-based `ids`, read straight from the
32+/// demuxer — the reference the copy must match byte for byte.
33+fn raw(ids: impl IntoIterator<Item = u32>) -> Vec<Vec<u8>> {
34+ let file = File::open(asset("test_av.mp4")).unwrap();
35+ let size = file.metadata().unwrap().len();
36+ let mut reader = Mp4Reader::read_header(BufReader::new(file), size).unwrap();
37+ let track = reader
38+ .tracks()
39+ .values()
40+ .find(|t| matches!(t.media_type(), Ok(MediaType::AAC)))
41+ .unwrap()
42+ .track_id();
43+ ids.into_iter()
44+ .map(|id| {
45+ reader
46+ .read_sample(track, id)
47+ .unwrap()
48+ .unwrap_or_else(|| panic!("no sample {id}"))
49+ .bytes
50+ .to_vec()
51+ })
52+ .collect()
53+}
54+
55+fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) {
56+ assert_eq!(got.len(), want.len(), "{what}: packet count");
57+ for (i, (p, w)) in got.iter().zip(want).enumerate() {
58+ assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len());
59+ assert_eq!(p.samples as usize, PACKET, "{what}: packet {i} duration");
60+ }
61+}
62+
63+#[test]
64+fn whole_track_copy_is_byte_identical() {
65+ // The fixture is 5 s, so this asks for all of it: the copy must be the raw
66+ // sample table from id 1 (priming packet included) with nothing rewritten.
67+ let packets = copy(&[(0.0, 5.0)]);
68+ let ids = 1..=packets.len() as u32;
69+ eprintln!("copied {} packets", packets.len());
70+ assert_same_bytes(&packets, &raw(ids), "0..5 s");
71+
72+ // Audible length (priming dropped by the reader) inside half a packet of 5 s.
73+ let audible = ((packets.len() - 1) * PACKET) as f64;
74+ assert!(
75+ (audible - 5.0 * RATE).abs() < PACKET as f64,
76+ "{audible} samples for 5 s"
77+ );
78+}
79+
80+#[test]
81+fn two_segments_match_the_bresenham_prediction() {
82+ let packets = copy(&[(0.0, 1.0), (2.0, 3.0)]);
83+ // One second is 43.07 packets: the first segment copies 43 and owes 68
84+ // samples, so the second is measured against 44100 + 68 = 43.13 -> 43 too.
85+ let n1 = (RATE / PACKET as f64).round();
86+ let err = n1 * PACKET as f64 - RATE;
87+ let n2 = ((RATE - err) / PACKET as f64).round();
88+ assert_eq!((n1, n2), (43.0, 43.0), "arithmetic changed, not the code");
89+ assert_eq!(packets.len(), 1 + n1 as usize + n2 as usize);
90+
91+ // Segment 1 is ids 1 (priming) .. 1 + 43; the fixture carries the standard
92+ // 1024 priming (see tests/audio_segments.rs), so 2.0 s is media sample
93+ // 88200 + 1024 = 89224, which packet 88 ([89088, 90112)) holds.
94+ let split = 1 + n1 as usize;
95+ assert_same_bytes(&packets[..split], &raw(1..=split as u32), "0..1 s");
96+ assert_same_bytes(
97+ &packets[split..],
98+ &raw(88..88 + n2 as u32),
99+ "2..3 s starting at packet 88",
100+ );
101+
102+ // Two seconds asked for, two seconds copied, to inside half a packet.
103+ let audible = ((packets.len() - 1) * PACKET) as f64;
104+ assert!(
105+ (audible - 2.0 * RATE).abs() < PACKET as f64,
106+ "{audible} samples for 2 s over one join"
107+ );
108+}
109+
110+#[test]
111+fn nothing_to_copy_is_a_clean_none() {
112+ assert!(
113+ AudioSession::copy_segments(asset("test_av.mp4"), &[])
114+ .unwrap()
115+ .is_none(),
116+ "an empty edit list copies nothing"
117+ );
118+ assert!(
119+ AudioSession::copy_segments(asset("test_baseline.mp4"), &[(0.0, 1.0)])
120+ .unwrap()
121+ .is_none(),
122+ "a file with no AAC track is a valid silent session"
123+ );
124+}