forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

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