forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

audio.rs1079 lines, 45.8 KiBHistoryRawDownload
1//! Background audio decode worker: pulls the AAC track out of an MP4 and hands
2//! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own
3//! `Mp4Reader` so the video demuxer stays single-owner.
4
5use std::fs::File;
6use std::io::BufReader;
7use std::path::{Path, PathBuf};
8use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
9use std::thread;
10
11use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};
12use symphonia_codec_aac::AacDecoder;
13use symphonia_core::codecs::audio::{
14 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,
15};
16use symphonia_core::packet::Packet;
17use symphonia_core::units;
18
19/// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
20/// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
21const DEFAULT_PRIMING: u64 = 1024;
22
23/// An edit list entry that only shifts the timeline, carrying no media.
24const EMPTY_EDIT: u64 = u32::MAX as u64;
25
26/// Packets decoded and thrown away ahead of a seek target: one for the MDCT
27/// overlap-add that reconstructs the target packet, one to warm the decoder.
28const PRE_ROLL: u32 = 2;
29
30/// Frames per channel one AAC-LC packet carries. Fixed by the codec.
31const SAMPLES_PER_PACKET: u32 = 1024;
32
33#[derive(Debug, Clone, Copy, PartialEq)]
34pub struct AudioMeta {
35 pub sample_rate: u32,
36 pub channels: u16,
37 /// Frames per channel the container claims, priming subtracted. `None` when
38 /// the header does not say.
39 pub total_samples: Option<u64>,
40}
41
42/// One decoder output block, ready to hand to an output device.
43pub struct AudioChunk {
44 /// Position of the first frame, in samples-per-channel counted from the
45 /// first audible sample: priming is already dropped, so 0 is media time 0.
46 pub start_sample: u64,
47 /// Interleaved, `AudioMeta::channels` values per frame.
48 pub samples: Vec<f32>,
49}
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)]
54pub 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.
62pub 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
68/// Everything an import check needs from a candidate file's audio track. Two
69/// files may share a timeline only when their probes are equal (or both `None`).
70#[derive(Debug, Clone, Copy, PartialEq)]
71pub struct AudioProbe {
72 pub params: AacTrackParams,
73 pub channels: u16,
74}
75
76/// One audio stream of a file as its header describes it. Every audio track is
77/// described, decodable or not: a picker shows the ones we refuse greyed out
78/// rather than pretending a BluRay remux has fewer streams than it has.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct StreamInfo {
81 /// Position among this file's audio tracks in file order — the `stream`
82 /// [`AudioSession::open_multi_streams`] takes.
83 pub index: usize,
84 /// Container codec.
85 ///
86 /// ponytail: mp4 0.14 parses `mp4a` sample entries and silently drops every
87 /// other kind (`stsd.rs` `_ => {}`), keeping no fourcc, so an AC-3/DTS/PCM
88 /// stream can only be `"unknown"` here — enough to grey a row out, not
89 /// enough to name the codec. Upgrade path is reading the sample entry's
90 /// fourcc out of the file ourselves.
91 pub codec: String,
92 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
93 pub channels: u16,
94 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
95 pub sample_rate: u32,
96 /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write.
97 pub lang: Option<String>,
98 /// Whether opening this stream would decode: AAC-LC, mono or stereo. The
99 /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels`
100 /// make one file at a time.
101 pub decodable: bool,
102}
103
104pub struct AudioSession;
105
106impl AudioSession {
107 /// Opens the audio track of `path`. `Ok(None)` means the file simply has no
108 /// audio, which is a valid session; `Err` is a real failure.
109 pub fn open(
110 path: impl AsRef<Path>,
111 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
112 Self::open_at(path, 0.0)
113 }
114
115 /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on
116 /// the audible timeline; `start_sample` stays absolute from audible zero, so
117 /// the output is the tail of a full run. Past the end yields no chunks.
118 pub fn open_at(
119 path: impl AsRef<Path>,
120 start_secs: f64,
121 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
122 Self::open_segments(path, &[(start_secs, f64::INFINITY)])
123 }
124
125 /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds —
126 /// back to back as one continuous stream: the chunks carry no gap at a join,
127 /// so pouring them into a ring is seamless. Each segment gets a fresh
128 /// decoder and its own pre-roll, which makes a seeked segment perceptually
129 /// but not bit-exactly equal to the same window of a full run (perceptual
130 /// noise substitution reseeds; measured below 1e-3).
131 ///
132 /// `start_sample` counts from the *first* segment's own audible start, so a
133 /// single segment reads as absolute media time (what [`open_at`](Self::open_at)
134 /// promises) and a list reads as one timeline. Segment ends past the track
135 /// are capped; an empty list is a valid session with no chunks.
136 pub fn open_segments(
137 path: impl AsRef<Path>,
138 segs: &[(f64, f64)],
139 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
140 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
141 Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs)
142 }
143
144 /// [`open_segments`](Self::open_segments) over several files: a segment names
145 /// its source by index into `sources`, and a source join behaves exactly like
146 /// a cut inside one file — `start_sample` stays continuous, the decoder is
147 /// fresh either way. Each source contributes *its own* priming, packet table
148 /// and length, which is the whole reason the resolution is per source.
149 ///
150 /// A segment naming **no** source is a *gap*: that many seconds of silence
151 /// are synthesised into the stream as ordinary chunks. Real chunks, not a
152 /// pause — the master clock counts what the device has been fed, so a hole
153 /// that fed nothing would stall the whole timeline on it.
154 ///
155 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
156 /// is empty or its first entry has no AAC track; a later source that is
157 /// missing audio or disagrees on rate/layout is an `Err` — import refuses
158 /// those up front (one timeline, one output device), this is the backstop.
159 pub fn open_multi_segments(
160 sources: &[PathBuf],
161 segs: &[(Option<usize>, f64, f64)],
162 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
163 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
164 Self::open_multi_streams(&sources, segs)
165 }
166
167 /// [`open_multi_segments`](Self::open_multi_segments) with each source
168 /// naming *which* of its audio streams to decode — files carrying several
169 /// (a remux with one track per language) are otherwise stuck on their first.
170 /// The index counts audio tracks in file order, as
171 /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not
172 /// exist or does not decode is an `Err` here, never a panic.
173 pub fn open_multi_streams(
174 sources: &[(PathBuf, usize)],
175 segs: &[(Option<usize>, f64, f64)],
176 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
177 let Some((path, stream)) = sources.first() else {
178 return Ok(None);
179 };
180 let Some(first) = Track::open(path, *stream)? else {
181 return Ok(None);
182 };
183 // The timeline's meta is the first source's: policy makes every other
184 // source match it, and the checks below hold them to that.
185 let meta = AudioMeta {
186 sample_rate: first.sample_rate,
187 channels: first.channels()?,
188 total_samples: first.total_samples,
189 };
190 // Built here only so an undecodable stream is an `Err` from the opener
191 // rather than a silently empty channel; the worker makes its own.
192 AacDecoder::try_new(&first.params, &AudioDecoderOptions::default())?;
193
194 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
195 tracks[0] = Some(first);
196 for &(source, ..) in segs {
197 let Some(source) = source else {
198 continue; // a gap opens no file
199 };
200 let slot = tracks
201 .get_mut(source)
202 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
203 if slot.is_some() {
204 continue; // already opened, and the checks below already ran
205 }
206 let (path, stream) = &sources[source];
207 let track = Track::open(path, *stream)?
208 .ok_or_else(|| format!("source {source} has no audio track"))?;
209 if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) {
210 return Err(format!(
211 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
212 track.sample_rate,
213 track.channels()?,
214 meta.sample_rate,
215 meta.channels
216 )
217 .into());
218 }
219 AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())?;
220 *slot = Some(track);
221 }
222
223 let segments: Vec<Segment> = segs
224 .iter()
225 .map(|&(source, start_secs, end_secs)| match source {
226 Some(source) => tracks[source]
227 .as_ref()
228 .expect("opened above")
229 .segment(source, start_secs, end_secs),
230 None => Segment::silence(
231 ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
232 ),
233 })
234 .collect();
235 // Chunk numbering is continuous across every join, counted from the first
236 // segment's audible start in its own source (see `open_segments`).
237 let timeline = segments.first().map_or(0, |s| match s.source {
238 Some(source) => s
239 .media_target
240 .saturating_sub(tracks[source].as_ref().expect("opened above").priming),
241 None => 0,
242 });
243
244 // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so
245 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
246 // without making a pause take a second to bite.
247 let (tx, rx) = sync_channel(32);
248 thread::Builder::new()
249 .name("audio-decode".into())
250 .spawn(move || {
251 run(Worker {
252 tracks,
253 channels: meta.channels as usize,
254 segments,
255 timeline,
256 tx,
257 })
258 })?;
259 Ok(Some((meta, rx)))
260 }
261
262 /// The audio parameters of `path`, for checking an import against the
263 /// timeline's first source: header only, no decoder and no worker.
264 /// `Ok(None)` means no AAC track — an audio-less file, which import pairs
265 /// only with other audio-less files.
266 pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> {
267 let Some(track) = Track::open(path.as_ref(), 0)? else {
268 return Ok(None);
269 };
270 Ok(Some(AudioProbe {
271 params: track.track_params(),
272 channels: track.channels()?,
273 }))
274 }
275
276 /// Every audio stream of `path`, in file order: an entry's `index` is the
277 /// stream number [`open_multi_streams`](Self::open_multi_streams) takes.
278 /// Header only, no decoder and no worker — and no filtering either, so a
279 /// stream this engine cannot decode is listed with `decodable: false`
280 /// instead of vanishing.
281 ///
282 /// An empty list means the file has no audio at all, which is a valid
283 /// silent source.
284 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
285 let file = File::open(path.as_ref())?;
286 let size = file.metadata()?.len();
287 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
288 Ok(audio_track_ids(&reader)
289 .into_iter()
290 .enumerate()
291 .map(|(index, id)| {
292 let track = &reader.tracks()[&id];
293 let aac = matches!(track.media_type(), Ok(MediaType::AAC));
294 let lang = track.language();
295 StreamInfo {
296 index,
297 codec: if aac { "aac" } else { "unknown" }.into(),
298 channels: track.channel_config().map_or(0, channel_count),
299 sample_rate: track.sample_freq_index().map_or(0, |f| f.freq()),
300 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),
301 decodable: aac
302 && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity))
303 && matches!(
304 track.channel_config(),
305 Ok(ChannelConfig::Mono | ChannelConfig::Stereo)
306 ),
307 }
308 })
309 .collect())
310 }
311
312 /// The raw AAC packets covering `segs` — the same half-open source-second
313 /// windows [`open_segments`](Self::open_segments) decodes — copied out
314 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
315 /// straight into an mp4 writer, which is the only way to keep audio in an
316 /// export at all (no pure-Rust AAC encoder exists).
317 ///
318 /// Cut points do not land on 1024-sample boundaries, so each segment is
319 /// rounded to whole packets against an error carried across the joins (see
320 /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the
321 /// asked-for length however many cuts there are, instead of drifting out of
322 /// lip sync one rounding at a time.
323 ///
324 /// The run starts one packet before the first audible one, which a reader
325 /// drops as encoder priming — for a segment list starting at 0.0 that is the
326 /// source's own priming packet, so the copy is the whole track from sample 1.
327 ///
328 /// `Ok(None)` for a file with no AAC track, and for an empty segment list.
329 ///
330 /// ponytail: the first packet after an *interior* join decodes without its
331 /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is
332 /// re-encoding just the join packets, which needs an encoder we do not have.
333 pub fn copy_segments(
334 path: impl AsRef<Path>,
335 segs: &[(f64, f64)],
336 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
337 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
338 Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs)
339 }
340
341 /// [`copy_segments`](Self::copy_segments) over several files, segments naming
342 /// their source by index into `sources`. The rounding debt is carried across
343 /// a source join exactly as across a cut inside one file, so the bound stays
344 /// half a packet over the whole list however many files it spans, and the
345 /// extra priming packet is still the very first segment's alone.
346 ///
347 /// Every source must declare the same [`AacTrackParams`]: the copy becomes
348 /// one output track with one esds. Import refuses a mismatch up front; the
349 /// check here is the backstop, as is the missing-track `Err`.
350 ///
351 /// A segment naming **no** source is a gap, and is copied as that many
352 /// packets of [`silent_packet`] silence — the rounding debt carried through
353 /// it like any other, so the hole occupies its exact duration and the audio
354 /// after it stays in sync with the picture. A gap the track *opens* on gets
355 /// one silent packet more, which is the priming a reader drops.
356 pub fn copy_multi_segments(
357 sources: &[PathBuf],
358 segs: &[(Option<usize>, f64, f64)],
359 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
360 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {
361 return Ok(None); // no segments, or nothing but silence
362 };
363 let path = sources
364 .get(first)
365 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
366 let Some(track) = Track::open(path, 0)? else {
367 return Ok(None); // silent source, silent export
368 };
369 let params = track.track_params();
370 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
371 tracks[first] = Some(track);
372
373 let sample_rate = params.sample_rate;
374 let mut err = 0i64;
375 let mut packets: Vec<AacPacket> = Vec::new();
376 for &(source, start_secs, end_secs) in segs {
377 let Some(source) = source else {
378 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
379 let bytes = silent_packet(params.chan_conf)?;
380 // A reader drops the first packet of an AAC track as the
381 // encoder's priming. When the track opens on a hole, that has to
382 // come out of one *extra* packet of silence: dropped out of the
383 // hole itself it would shorten it, and everything after the hole
384 // would play a packet early. It is not part of the run, so it
385 // owes the rounding debt nothing.
386 let priming = u32::from(packets.is_empty());
387 for _ in 0..packet_run(&mut err, ideal, u32::MAX) + priming {
388 packets.push(AacPacket {
389 bytes: bytes.clone(),
390 samples: SAMPLES_PER_PACKET,
391 });
392 }
393 continue;
394 };
395 let track = source_at(&mut tracks, sources, source)?;
396 if track.track_params() != params {
397 return Err(format!(
398 "source {source} audio is {:?}, the timeline's is {params:?}",
399 track.track_params()
400 )
401 .into());
402 }
403 let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale);
404 let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0);
405 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64;
406 let available = track.sample_count.saturating_sub(start_id - 1);
407 // The head packet is the priming of the first segment only: a reader
408 // drops exactly one, so an interior join must not add another --
409 // and neither must a segment behind a leading gap, which already
410 // paid the priming in silence.
411 let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1);
412 let ids = head
413 .into_iter()
414 .chain(start_id..start_id + packet_run(&mut err, ideal, available));
415 for id in ids {
416 let Some(sample) = track.reader.read_sample(track.track_id, id)? else {
417 let count = track.sample_count;
418 return Err(format!("audio sample {id} of {count} is missing").into());
419 };
420 packets.push(AacPacket {
421 bytes: sample.bytes.to_vec(),
422 samples: SAMPLES_PER_PACKET,
423 });
424 }
425 }
426 Ok(Some((params, packets)))
427 }
428}
429
430/// One AAC-LC access unit of silence, for the gaps in an exported timeline —
431/// the export copies packets and has no AAC encoder, so the only silence it can
432/// write is one spelled out by hand.
433///
434/// It is the shortest legal `raw_data_block` there is: one element carrying
435/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
436/// spectral data at all and therefore 1024 samples of exact zero. Every field
437/// is zero except the element id and the terminating `ID_END`, so the whole
438/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the
439/// unit tests, which is the only claim worth making about hand-written
440/// bitstream.
441///
442/// ponytail: mono and stereo only, because `chan_conf` beyond 2 needs more
443/// elements per block; the timeline refuses such a source at import today, so
444/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements.
445fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
446 match chan_conf {
447 // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned.
448 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]),
449 // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END.
450 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]),
451 n => Err(format!("cannot write silence for a {n}-channel AAC track").into()),
452 }
453}
454
455/// The source at `index`, opened on first use. Sources a segment list never
456/// names are never touched: a project's list only grows.
457///
458/// ponytail: the copy path is still stream 0 of every source — an export of a
459/// timeline playing stream 1 would carry stream 0's audio. Upgrade path is the
460/// `(PathBuf, usize)` list [`AudioSession::open_multi_streams`] already takes,
461/// which is S4b's job once a stream can be picked at all.
462fn source_at<'a>(
463 tracks: &'a mut [Option<Track>],
464 sources: &[PathBuf],
465 index: usize,
466) -> crate::Result<&'a mut Track> {
467 let slot = tracks
468 .get_mut(index)
469 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
470 if slot.is_none() {
471 *slot = Some(
472 Track::open(&sources[index], 0)?
473 .ok_or_else(|| format!("source {index} has no audio track"))?,
474 );
475 }
476 Ok(slot.as_mut().expect("just opened"))
477}
478
479/// One source's AAC track, resolved once: the reader plus everything the header
480/// has to say about it. `stts` is copied out because every other field would
481/// otherwise keep a borrow alive on the reader the worker needs mutably — a real
482/// AAC track has one entry, so it is two `u32`s.
483struct Track {
484 reader: Mp4Reader<BufReader<File>>,
485 track_id: u32,
486 sample_count: u32,
487 sample_rate: u32,
488 timescale: u32,
489 /// Encoder delay of *this* file. Sources are joined, priming is not shared.
490 priming: u64,
491 total_samples: Option<u64>,
492 stts: Vec<(u32, u32)>,
493 config: ChannelConfig,
494 freq_index: u8,
495 chan_conf: u8,
496 /// A fresh decoder is built from these per segment: seeking mid-stream
497 /// leaves MDCT and PNS state that belongs to the packets we skipped.
498 params: AudioCodecParameters,
499}
500
501impl Track {
502 /// The `stream`-th audio track of `path`, counted in file order over *all*
503 /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out.
504 ///
505 /// Stream 0 is best effort: `Ok(None)` when there is no audio there at all
506 /// or the codec is one we do not decode, which is a valid silent source (a
507 /// file whose audio is AC-3 still has a picture worth editing). A stream the
508 /// caller *named* is a promise instead, so out of range or undecodable
509 /// there is an `Err` rather than silence the caller did not ask for.
510 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
511 let file = File::open(path)?;
512 let size = file.metadata()?.len();
513 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
514
515 let ids = audio_track_ids(&reader);
516 let Some(track) = ids.get(stream).map(|id| &reader.tracks()[id]) else {
517 return match stream {
518 0 => Ok(None),
519 n => Err(format!(
520 "{}: audio stream {n} of {} streams",
521 path.display(),
522 ids.len()
523 )
524 .into()),
525 };
526 };
527 if !matches!(track.media_type(), Ok(MediaType::AAC)) {
528 return match stream {
529 0 => Ok(None),
530 n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()),
531 };
532 }
533 // Refuse early with a message instead of failing packet by packet — and
534 // a copy carries no profile of its own: the writer rebuilds the
535 // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a
536 // non-LC source would be mislabelled rather than merely unplayable.
537 match track.audio_profile()? {
538 AudioObjectType::AacLowComplexity => {}
539 other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()),
540 }
541
542 let track_id = track.track_id();
543 let sample_rate = track.sample_freq_index()?.freq();
544 let timescale = track.timescale();
545 let priming = priming_samples(track, sample_rate);
546 let (_, freq_index, chan_conf) = asc_fields(track)?;
547 let mut params = AudioCodecParameters::new();
548 params
549 .for_codec(CODEC_ID_AAC)
550 .with_sample_rate(sample_rate)
551 .with_extra_data(audio_specific_config(track)?);
552 let this = Self {
553 track_id,
554 sample_count: reader.sample_count(track_id)?,
555 sample_rate,
556 timescale,
557 priming,
558 total_samples: scale(track.trak.mdia.mdhd.duration, sample_rate, timescale)
559 .map(|d| d.saturating_sub(priming)),
560 stts: stts_pairs(track).collect(),
561 config: track.channel_config()?,
562 freq_index,
563 chan_conf,
564 params,
565 reader,
566 };
567 Ok(Some(this))
568 }
569
570 /// Channel count. `AacDecoder` only does mono and stereo, so anything else
571 /// is refused here rather than one packet at a time.
572 fn channels(&self) -> crate::Result<u16> {
573 match self.config {
574 ChannelConfig::Mono => Ok(1),
575 ChannelConfig::Stereo => Ok(2),
576 other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()),
577 }
578 }
579
580 fn track_params(&self) -> AacTrackParams {
581 AacTrackParams {
582 freq_index: self.freq_index,
583 chan_conf: self.chan_conf,
584 sample_rate: self.sample_rate,
585 }
586 }
587
588 /// `secs` on this source's audible timeline into media samples (priming
589 /// included, so it compares directly against a decoded position).
590 /// `f64::INFINITY` saturates.
591 fn media(&self, secs: f64) -> u64 {
592 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
593 }
594
595 /// One `[start, end)` window of this source's seconds, resolved to its own
596 /// packets and media samples.
597 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
598 let media_target = self.media(start_secs);
599 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
600 // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
601 // packet to cancel aliasing, plus one more to warm the decoder up. Their
602 // output is discarded below, so this only costs decode time.
603 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL);
604 Segment {
605 source: Some(source),
606 start_id,
607 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
608 media_target,
609 // An inverted segment is an empty one, never a backwards run.
610 media_end: self.media(end_secs).max(media_target),
611 }
612 }
613}
614
615/// How many whole packets to copy for a window of `ideal` samples per channel,
616/// capped at the `available` packets left in the track.
617///
618/// `err` is "samples copied so far minus samples asked for", carried across the
619/// segment joins: rounding to nearest *against the running debt* keeps the
620/// cumulative error inside half a packet forever, where independent per-segment
621/// rounding would random-walk away from sync (charter D1: < 1024 at every join).
622fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
623 let packet = i64::from(SAMPLES_PER_PACKET);
624 // Never carry a debt the track cannot pay: a segment running past the end
625 // would otherwise inflate every later one. (Also tames `f64::INFINITY`,
626 // which saturates to `i64::MAX` on the cast above.)
627 let ideal = ideal.min(i64::from(available) * packet);
628 let want = (ideal - *err) as f64 / packet as f64;
629 let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32;
630 *err += i64::from(n) * packet - ideal;
631 n
632}
633
634/// This file's audio tracks in file order — the order a stream index counts in.
635/// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a
636/// `HashMap`: iterating that would make "stream 0" a different track from one
637/// run to the next on any file carrying more than one.
638fn audio_track_ids<R>(reader: &Mp4Reader<R>) -> Vec<u32> {
639 reader
640 .moov
641 .traks
642 .iter()
643 .filter(|trak| {
644 matches!(
645 TrackType::try_from(&trak.mdia.hdlr.handler_type),
646 Ok(TrackType::Audio)
647 )
648 })
649 .map(|trak| trak.tkhd.track_id)
650 .collect()
651}
652
653/// Channels in an AAC channel configuration. The config number *is* the channel
654/// count up to 5.1; 7.1 is the one that is not.
655fn channel_count(config: ChannelConfig) -> u16 {
656 match config {
657 ChannelConfig::SevenOne => 8,
658 other => other as u16,
659 }
660}
661
662/// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a
663/// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside
664/// the crate (same trap as `SttsEntry`, see [`packet_at`]).
665fn asc_fields(track: &Mp4Track) -> crate::Result<(u8, u8, u8)> {
666 let esds = track
667 .trak
668 .mdia
669 .minf
670 .stbl
671 .stsd
672 .mp4a
673 .as_ref()
674 .and_then(|mp4a| mp4a.esds.as_ref())
675 .ok_or("AAC track has no esds descriptor")?;
676 let cfg = &esds.es_desc.dec_config.dec_specific;
677 Ok((cfg.profile, cfg.freq_index, cfg.chan_conf))
678}
679
680/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14
681/// parses those out and drops the raw bytes, so this is the exact inverse of its
682/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`).
683fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {
684 let (profile, freq_index, chan_conf) = asc_fields(track)?;
685 Ok(Box::new([
686 (profile << 3) | (freq_index >> 1),
687 (freq_index << 7) | (chan_conf << 3),
688 ]))
689}
690
691/// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`]
692/// walks; the box's own entry type is `pub(crate)` in mp4 0.14.
693fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
694 track
695 .trak
696 .mdia
697 .minf
698 .stbl
699 .stts
700 .entries
701 .iter()
702 .map(|e| (e.sample_count, e.sample_delta))
703}
704
705/// Encoder delay in samples-per-channel: the edit list's first real entry says
706/// how far into the media the presentation starts.
707///
708/// ponytail: an explicit `media_time` of 0 is taken at face value (no trim).
709/// Muxers that write a zero edit list despite a primed stream would leak the
710/// priming; upgrade path is preferring the codec delay when it disagrees.
711fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 {
712 track
713 .trak
714 .edts
715 .as_ref()
716 .and_then(|edts| edts.elst.as_ref())
717 .and_then(|elst| {
718 elst.entries
719 .iter()
720 .map(|e| e.media_time)
721 .find(|&t| t != EMPTY_EDIT && t != u64::MAX)
722 })
723 .and_then(|t| scale(t, sample_rate, track.timescale()))
724 .unwrap_or(DEFAULT_PRIMING)
725}
726
727/// `value` from the track timescale into samples-per-channel. `None` on a zero
728/// timescale, which would be a broken header.
729fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
730 let timescale = u64::from(timescale);
731 (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
732}
733
734/// Inverse of [`scale`]: samples-per-channel back into the track timescale.
735fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 {
736 match sample_rate {
737 0 => 0,
738 rate => samples * u64::from(timescale) / u64::from(rate),
739 }
740}
741
742/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll`
743/// packets, plus that packet's own start time. Inverse of the mp4 crate's
744/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is
745/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs.
746///
747/// ponytail: the walk-back is clamped to the start of the containing stts entry
748/// rather than crossing into the previous one, so a target within `pre_roll`
749/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
750/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
751/// carrying the previous entry's delta through the walk.
752fn packet_at(
753 entries: impl IntoIterator<Item = (u32, u32)>,
754 target_ts: u64,
755 pre_roll: u32,
756) -> (u32, u64) {
757 let mut first_id = 1u32;
758 let mut elapsed = 0u64;
759 let mut last = (1u32, 0u64);
760 for (count, delta) in entries {
761 let span = u64::from(count) * u64::from(delta);
762 let index = if target_ts < elapsed + span && delta != 0 {
763 ((target_ts - elapsed) / u64::from(delta)) as u32
764 } else {
765 // Past this entry: remember its last packet in case the target runs
766 // past the end of the track entirely.
767 last = (
768 first_id + count.saturating_sub(1),
769 elapsed + span.saturating_sub(u64::from(delta)),
770 );
771 first_id += count;
772 elapsed += span;
773 continue;
774 };
775 let index = index - index.min(pre_roll);
776 return (
777 first_id + index,
778 elapsed + u64::from(index) * u64::from(delta),
779 );
780 }
781 last
782}
783
784/// One window of a source to decode, resolved to media samples and packets —
785/// or, with no source, a stretch of synthesised silence.
786struct Segment {
787 /// Index into the worker's tracks; the media positions below are that
788 /// source's, not the timeline's. `None` for a gap, where only the length
789 /// (`media_end`) means anything.
790 source: Option<usize>,
791 /// First packet to feed the decoder, 1-based; includes the pre-roll.
792 start_id: u32,
793 /// Media position of `start_id`'s first frame, in samples-per-channel.
794 start_pos: u64,
795 /// Media position of the first frame to emit. Everything decoded before it
796 /// is pre-roll, priming, or seek overshoot, and gets dropped.
797 media_target: u64,
798 /// One past the last frame to emit; `u64::MAX` for "to the end of track".
799 media_end: u64,
800}
801
802impl Segment {
803 /// `frames` per channel of silence — a gap in the audio lane.
804 fn silence(frames: u64) -> Self {
805 Self {
806 source: None,
807 start_id: 0,
808 start_pos: 0,
809 media_target: 0,
810 media_end: frames,
811 }
812 }
813}
814
815struct Worker {
816 /// Indexed by [`Segment::source`]; only the sources some segment names are
817 /// `Some`, the rest were never opened.
818 tracks: Vec<Option<Track>>,
819 channels: usize,
820 segments: Vec<Segment>,
821 /// `start_sample` of the first chunk.
822 timeline: u64,
823 tx: SyncSender<AudioChunk>,
824}
825
826fn run(mut w: Worker) {
827 let mut interleaved = Vec::new();
828 let channels = w.channels;
829 // Chunk numbering is continuous across every join, source ones included.
830 let mut timeline = w.timeline;
831 let segments = std::mem::take(&mut w.segments);
832
833 for seg in &segments {
834 let Some(source) = seg.source else {
835 // A gap: hand the device real silence rather than nothing at all,
836 // in the same packet-sized chunks decoding produces, so `fed` and
837 // the master clock keep counting straight through the hole.
838 let mut left = seg.media_end;
839 while left > 0 {
840 let frames = left.min(u64::from(SAMPLES_PER_PACKET));
841 let chunk = AudioChunk {
842 start_sample: timeline,
843 samples: vec![0.0; frames as usize * channels],
844 };
845 if w.tx.send(chunk).is_err() {
846 return; // caller moved on
847 }
848 timeline += frames;
849 left -= frames;
850 }
851 continue;
852 };
853 let Some(track) = w.tracks[source].as_mut() else {
854 continue; // opener fills every named source; nothing to decode
855 };
856 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())
857 {
858 Ok(decoder) => decoder,
859 Err(e) => {
860 eprintln!("audio decoder init failed: {e}");
861 return;
862 }
863 };
864 let mut pos = seg.start_pos;
865
866 for id in seg.start_id..=track.sample_count {
867 if pos >= seg.media_end {
868 break; // segment done, on to the next one
869 }
870 let sample = match track.reader.read_sample(track.track_id, id) {
871 Ok(Some(sample)) => sample,
872 Ok(None) => break,
873 Err(e) => {
874 eprintln!("audio demux error at sample {id}: {e}");
875 break;
876 }
877 };
878 let packet = Packet::new(
879 track.track_id,
880 units::Timestamp::new(sample.start_time as i64),
881 units::Duration::new(u64::from(sample.duration)),
882 &sample.bytes[..],
883 );
884 let buf = match decoder.decode(&packet) {
885 Ok(buf) => buf,
886 Err(e) => {
887 eprintln!("audio decode error at sample {id}: {e}");
888 break;
889 }
890 };
891 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
892 let next = pos + (interleaved.len() / channels) as u64;
893
894 // Everything before the target is encoder priming and/or decoder
895 // pre-roll, not audio the caller asked for: drop it, splitting the
896 // packet that straddles the target.
897 if next <= seg.media_target {
898 pos = next;
899 continue;
900 }
901 if pos < seg.media_target {
902 interleaved.drain(..(seg.media_target - pos) as usize * channels);
903 pos = seg.media_target;
904 }
905 // And the tail past the segment end goes too — on a short segment
906 // that is this same buffer, trimmed at both ends.
907 if next > seg.media_end {
908 interleaved.truncate((seg.media_end - pos) as usize * channels);
909 }
910 pos = next;
911 if interleaved.is_empty() {
912 continue; // nothing left of it; the loop head ends the segment
913 }
914 let chunk = AudioChunk {
915 start_sample: timeline,
916 samples: std::mem::take(&mut interleaved),
917 };
918 timeline += (chunk.samples.len() / channels) as u64;
919 if w.tx.send(chunk).is_err() {
920 return; // consumer went away
921 }
922 }
923 }
924}
925
926#[cfg(test)]
927mod tests {
928 use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run};
929
930 /// A real AAC track: one stts entry, N packets of 1024.
931 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
932 [(count, 1024)]
933 }
934
935 #[test]
936 fn packet_at_walks_back_by_the_pre_roll() {
937 // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..).
938 assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064));
939 assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016));
940 // Exactly on a packet boundary is the start of that packet, not the end
941 // of the previous one.
942 assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048));
943 }
944
945 #[test]
946 fn packet_at_clamps_both_ends() {
947 // Head: no room for the walk-back, and packet ids are 1-based.
948 assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0));
949 assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0));
950 // Past the end: the last packet, so the worker decodes ~nothing.
951 assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776));
952 // Degenerate boxes must not panic or wrap.
953 assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0));
954 assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0));
955 }
956
957 #[test]
958 fn packet_at_crosses_stts_entries() {
959 // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240
960 // with packet 11.
961 let entries = [(10u32, 1024u32), (10, 512)];
962 assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288));
963 assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264));
964 // The ponytail clamp: on the first packet of the second entry the
965 // walk-back stops there instead of stepping into the first entry.
966 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
967 }
968
969 /// xorshift64: adversarial segment lists do not deserve a dependency.
970 fn rng(state: &mut u64) -> u64 {
971 *state ^= *state << 13;
972 *state ^= *state >> 7;
973 *state ^= *state << 17;
974 *state
975 }
976
977 #[test]
978 fn packet_run_keeps_cumulative_error_under_a_packet() {
979 let packet = i64::from(SAMPLES_PER_PACKET);
980 let mut state = 0x5eed_1234_9876_abcd;
981 for rate in [44100i64, 48000] {
982 for list in 0..100 {
983 let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64);
984 // 3..43 joins of anything from one video frame to four seconds.
985 for join in 0..3 + rng(&mut state) % 40 {
986 let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64;
987 copied += i64::from(packet_run(&mut err, ideal, u32::MAX));
988 asked += ideal;
989 assert!(
990 err.abs() < packet,
991 "rate {rate} list {list} join {join}: err {err}"
992 );
993 }
994 // The accumulator is the whole story: what it says is the drift.
995 assert_eq!(copied * packet - asked, err);
996 }
997 }
998 }
999
1000 #[test]
1001 fn packet_run_rounds_against_the_running_debt() {
1002 // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples
1003 // owed, and the debt is repaid by a 44-packet second once it crosses a
1004 // half packet — never by letting each second round on its own.
1005 let mut err = 0;
1006 assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43);
1007 assert_eq!(err, -68);
1008 let mut seconds = 1;
1009 while packet_run(&mut err, 44100, u32::MAX) == 43 {
1010 seconds += 1;
1011 assert!(seconds < 20, "debt never repaid, err {err}");
1012 }
1013 assert_eq!(seconds, 7, "68 samples a second, half a packet is 512");
1014 assert!(err > 0, "the repaying second overshoots, err {err}");
1015 }
1016
1017 #[test]
1018 fn packet_run_forgives_a_debt_the_track_cannot_pay() {
1019 // Asking a second of a track with ten packets left: it delivers ten and
1020 // does not make the next segment copy the shortfall from elsewhere.
1021 let mut err = 0;
1022 assert_eq!(packet_run(&mut err, 44100, 10), 10);
1023 assert_eq!(err, 0);
1024 // Degenerate windows are empty, not negative.
1025 assert_eq!(packet_run(&mut err, 0, 10), 0);
1026 assert_eq!(packet_run(&mut err, i64::MAX, 7), 7);
1027 }
1028
1029 #[test]
1030 fn asc_round_trips_aac_lc_44100_stereo() {
1031 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
1032 let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8);
1033 let asc = [
1034 (profile << 3) | (freq_index >> 1),
1035 (freq_index << 7) | (chan_conf << 3),
1036 ];
1037 assert_eq!(asc, [0x12, 0x10]);
1038 }
1039
1040 /// The one claim worth making about a hand-written bitstream: our own
1041 /// decoder turns it into exactly one packet of exactly zero.
1042 #[test]
1043 fn a_silent_packet_decodes_to_a_packet_of_zero() {
1044 use super::{AacDecoder, AudioDecoder, AudioDecoderOptions, silent_packet};
1045 use symphonia_core::codecs::audio::{AudioCodecParameters, well_known::CODEC_ID_AAC};
1046 use symphonia_core::{packet::Packet, units};
1047
1048 for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] {
1049 // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels.
1050 let asc: Box<[u8]> = Box::new([(2 << 3) | (4 >> 1), (4 << 7) | (chan_conf << 3)]);
1051 let mut params = AudioCodecParameters::new();
1052 params
1053 .for_codec(CODEC_ID_AAC)
1054 .with_sample_rate(44100)
1055 .with_extra_data(asc);
1056 let mut decoder =
1057 AacDecoder::try_new(&params, &AudioDecoderOptions::default()).expect("decoder");
1058 let bytes = silent_packet(chan_conf).expect("silence");
1059 let packet = Packet::new(
1060 0,
1061 units::Timestamp::new(0),
1062 units::Duration::new(u64::from(SAMPLES_PER_PACKET)),
1063 &bytes[..],
1064 );
1065 let buf = decoder.decode(&packet).expect("decodes as AAC-LC");
1066 let mut out = Vec::new();
1067 buf.copy_to_vec_interleaved::<f32>(&mut out);
1068 assert_eq!(out.len(), SAMPLES_PER_PACKET as usize * channels);
1069 assert!(
1070 out.iter().all(|&s| s == 0.0),
1071 "{chan_conf} ch is not silent"
1072 );
1073 }
1074 assert!(
1075 silent_packet(6).is_err(),
1076 "beyond stereo is refused, not faked"
1077 );
1078 }
1079}