forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

audio.rs2042 lines, 87.0 KiBHistoryRawDownload
1//! Background audio decode worker: pulls a source's audio track and hands
2//! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own
3//! reader so the video demuxer stays single-owner.
4//!
5//! Three readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as
6//! it always has -- that path also yields the raw access units the export
7//! copies, which is the only reason it is kept separate -- and a standalone
8//! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through
9//! symphonia's own format probe. An mp4's **AC-3** track is the third: the same
10//! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the
11//! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo
12//! timeline. Everything downstream of [`Track`] sees the
13//! same samples either way; only the packet copy asks which reader it came from,
14//! because there is nothing to copy out of an mp3 that an mp4 can hold.
15//!
16//! One output, however many lanes: a timeline's audio lanes are decoded side by
17//! side and summed ([`AudioSession::open_mixed_streams`]), which is what both
18//! the device and an audio-only export are handed. One lane skips the mixer
19//! entirely and is the plain single-stream path it always was.
20//!
21//! Both readers are addressed as `(path, stream)`. An mp4 may carry several
22//! audio tracks and the caller picks one; a standalone audio file carries
23//! exactly one, so any stream above 0 there is an `Err` rather than a silent
24//! fallback to the only track it has.
25
26use std::fs::File;
27use std::io::BufReader;
28use std::path::{Path, PathBuf};
29use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
30use std::thread;
31
32use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};
33use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet};
34use symphonia_codec_aac::AacDecoder;
35use symphonia_core::codecs::audio::{
36 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,
37};
38use symphonia_core::formats::probe::Hint;
39// `TrackType` is the name both readers give their track kinds; the mp4 one is
40// imported above and used far more often here, so symphonia's is the one aliased.
41use symphonia_core::formats::{
42 FormatOptions, FormatReader, SeekMode, SeekTo, TrackType as SymKind,
43};
44use symphonia_core::io::MediaSourceStream;
45use symphonia_core::meta::MetadataOptions;
46use symphonia_core::packet::Packet;
47use symphonia_core::units;
48use symphonia_core::units::{Time, TimeBase};
49
50use crate::eq::{EqParams, EqState};
51
52/// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
53/// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
54const DEFAULT_PRIMING: u64 = 1024;
55
56/// An edit list entry that only shifts the timeline, carrying no media.
57const EMPTY_EDIT: u64 = u32::MAX as u64;
58
59/// Packets decoded and thrown away ahead of a seek target: one for the MDCT
60/// overlap-add that reconstructs the target packet, one to warm the decoder.
61const PRE_ROLL: u32 = 2;
62
63/// Frames per channel one AAC-LC packet carries. Fixed by the codec.
64const SAMPLES_PER_PACKET: u32 = 1024;
65
66/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks
67/// of 256), the way 1024 is fixed for AAC-LC.
68const AC3_SAMPLES_PER_FRAME: u32 = 1536;
69
70/// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the
71/// 256-sample overlap-add the target frame is reconstructed with.
72const AC3_PRE_ROLL: u32 = 1;
73
74/// Frames per channel a seek into a standalone audio file lands ahead of the
75/// window, decoded and thrown away: enough to refill an mp3's bit reservoir
76/// (a frame is 1152 samples and the reservoir reaches back two of them) at any
77/// rate we accept.
78const SYM_PRE_ROLL: u64 = 8192;
79
80#[derive(Debug, Clone, Copy, PartialEq)]
81pub struct AudioMeta {
82 pub sample_rate: u32,
83 pub channels: u16,
84 /// Frames per channel the container claims, priming subtracted. `None` when
85 /// the header does not say.
86 pub total_samples: Option<u64>,
87}
88
89/// One decoder output block, ready to hand to an output device.
90pub struct AudioChunk {
91 /// Position of the first frame, in samples-per-channel counted from the
92 /// first audible sample: priming is already dropped, so 0 is media time 0.
93 pub start_sample: u64,
94 /// Interleaved, `AudioMeta::channels` values per frame.
95 pub samples: Vec<f32>,
96}
97
98/// What a writer needs to declare an AAC track that plays copied packets: the
99/// esds fields verbatim from the source, no re-derivation.
100#[derive(Debug, Clone, Copy, PartialEq)]
101pub struct AacTrackParams {
102 pub freq_index: u8,
103 pub chan_conf: u8,
104 pub sample_rate: u32,
105}
106
107/// One raw AAC access unit exactly as it sits in the source `mdat` — no ADTS
108/// header, which is the form an `mp4a` sample table wants.
109pub struct AacPacket {
110 pub bytes: Vec<u8>,
111 /// Frames per channel it decodes to, for the writer's stts.
112 pub samples: u32,
113}
114
115/// Everything an import check needs from a candidate file's audio track. Two
116/// files may share a timeline only when their probes are equal (or both `None`).
117///
118/// Rate and layout only: those are what one output device and one exported track
119/// can carry, and an mp3 that agrees on both may join a timeline of mp4s even
120/// though nothing about it can be *copied* into an export -- that is a separate
121/// refusal, at export time, in [`AudioSession::copy_multi_segments`].
122#[derive(Debug, Clone, Copy, PartialEq)]
123pub struct AudioProbe {
124 pub sample_rate: u32,
125 pub channels: u16,
126}
127
128/// One audio stream of a file as its header describes it. Every audio track is
129/// described, decodable or not: a picker shows the ones we refuse greyed out
130/// rather than pretending a BluRay remux has fewer streams than it has.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct StreamInfo {
133 /// Position among this file's audio tracks in file order — the `stream`
134 /// [`AudioSession::open_multi_streams`] takes.
135 pub index: usize,
136 /// Container codec.
137 ///
138 /// ponytail: mp4 0.14 parses `mp4a` sample entries and silently drops every
139 /// other kind (`stsd.rs` `_ => {}`), keeping no fourcc, so an AC-3/DTS/PCM
140 /// stream can only be `"unknown"` here — enough to grey a row out, not
141 /// enough to name the codec. Upgrade path is reading the sample entry's
142 /// fourcc out of the file ourselves.
143 pub codec: String,
144 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
145 pub channels: u16,
146 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
147 pub sample_rate: u32,
148 /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write.
149 pub lang: Option<String>,
150 /// Whether opening this stream would decode: AAC-LC, mono or stereo. The
151 /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels`
152 /// make one file at a time.
153 pub decodable: bool,
154}
155
156pub struct AudioSession;
157
158impl AudioSession {
159 /// Opens the audio track of `path`. `Ok(None)` means the file simply has no
160 /// audio, which is a valid session; `Err` is a real failure.
161 pub fn open(
162 path: impl AsRef<Path>,
163 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
164 Self::open_at(path, 0.0)
165 }
166
167 /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on
168 /// the audible timeline; `start_sample` stays absolute from audible zero, so
169 /// the output is the tail of a full run. Past the end yields no chunks.
170 pub fn open_at(
171 path: impl AsRef<Path>,
172 start_secs: f64,
173 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
174 Self::open_segments(path, &[(start_secs, f64::INFINITY)])
175 }
176
177 /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds —
178 /// back to back as one continuous stream: the chunks carry no gap at a join,
179 /// so pouring them into a ring is seamless. Each segment gets a fresh
180 /// decoder and its own pre-roll, which makes a seeked segment perceptually
181 /// but not bit-exactly equal to the same window of a full run (perceptual
182 /// noise substitution reseeds; measured below 1e-3).
183 ///
184 /// `start_sample` counts from the *first* segment's own audible start, so a
185 /// single segment reads as absolute media time (what [`open_at`](Self::open_at)
186 /// promises) and a list reads as one timeline. Segment ends past the track
187 /// are capped; an empty list is a valid session with no chunks.
188 pub fn open_segments(
189 path: impl AsRef<Path>,
190 segs: &[(f64, f64)],
191 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
192 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
193 Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs)
194 }
195
196 /// [`open_segments`](Self::open_segments) over several files: a segment names
197 /// its source by index into `sources`, and a source join behaves exactly like
198 /// a cut inside one file — `start_sample` stays continuous, the decoder is
199 /// fresh either way. Each source contributes *its own* priming, packet table
200 /// and length, which is the whole reason the resolution is per source.
201 ///
202 /// A segment naming **no** source is a *gap*: that many seconds of silence
203 /// are synthesised into the stream as ordinary chunks. Real chunks, not a
204 /// pause — the master clock counts what the device has been fed, so a hole
205 /// that fed nothing would stall the whole timeline on it.
206 ///
207 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
208 /// is empty or its first entry has no AAC track; a later source that is
209 /// missing audio or disagrees on rate/layout is an `Err` — import refuses
210 /// those up front (one timeline, one output device), this is the backstop.
211 pub fn open_multi_segments(
212 sources: &[PathBuf],
213 segs: &[(Option<usize>, f64, f64)],
214 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
215 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
216 Self::open_multi_streams(&sources, segs)
217 }
218
219 /// [`open_multi_segments`](Self::open_multi_segments) with each source
220 /// naming *which* of its audio streams to decode — files carrying several
221 /// (a remux with one track per language) are otherwise stuck on their first.
222 /// The index counts audio tracks in file order, as
223 /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not
224 /// exist or does not decode is an `Err` here, never a panic.
225 pub fn open_multi_streams(
226 sources: &[(PathBuf, usize)],
227 segs: &[(Option<usize>, f64, f64)],
228 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
229 Self::open_multi_streams_eq(sources, segs, &[])
230 }
231
232 /// [`open_multi_streams`](Self::open_multi_streams) with an equalizer per
233 /// segment: `eqs[i]` is what segment `i` plays through, `None` for one that
234 /// plays flat. Filtering happens **per segment**, inside the worker, before
235 /// anything is mixed -- two clips with different curves must not be blurred
236 /// into one another, and a segment's filter memory starts clean and dies
237 /// with it, which is also what makes a seek a reset for free.
238 ///
239 /// A parallel list, not a fourth tuple element: see
240 /// [`crate::Project::audio_eqs_from`], which is what builds it. A list
241 /// shorter than `segs` (the empty one every plain caller passes) means the
242 /// rest play flat, so a mismatch cannot panic and cannot silently shift a
243 /// curve onto the wrong clip.
244 pub fn open_multi_streams_eq(
245 sources: &[(PathBuf, usize)],
246 segs: &[(Option<usize>, f64, f64)],
247 eqs: &[Option<EqParams>],
248 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
249 let Some((path, stream)) = sources.first() else {
250 return Ok(None);
251 };
252 let Some(first) = Track::open(path, *stream)? else {
253 return Ok(None);
254 };
255 // The timeline's meta is the first source's: policy makes every other
256 // source match it, and the checks below hold them to that.
257 let meta = AudioMeta {
258 sample_rate: first.sample_rate(),
259 channels: first.channels()?,
260 total_samples: first.total_samples(),
261 };
262 // Built here only so an undecodable stream is an `Err` from the opener
263 // rather than a silently empty channel; the worker makes its own.
264 first.check_decoder()?;
265
266 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
267 tracks[0] = Some(first);
268 for &(source, ..) in segs {
269 let Some(source) = source else {
270 continue; // a gap opens no file
271 };
272 let slot = tracks
273 .get_mut(source)
274 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
275 if slot.is_some() {
276 continue; // already opened, and the checks below already ran
277 }
278 let (path, stream) = &sources[source];
279 let track = Track::open(path, *stream)?
280 .ok_or_else(|| format!("source {source} has no audio track"))?;
281 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {
282 return Err(format!(
283 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
284 track.sample_rate(),
285 track.channels()?,
286 meta.sample_rate,
287 meta.channels
288 )
289 .into());
290 }
291 track.check_decoder()?;
292 *slot = Some(track);
293 }
294
295 let segments: Vec<Segment> = segs
296 .iter()
297 .map(|&(source, start_secs, end_secs)| match source {
298 Some(source) => tracks[source]
299 .as_ref()
300 .expect("opened above")
301 .segment(source, start_secs, end_secs),
302 None => Segment::silence(
303 ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
304 ),
305 })
306 .collect();
307 // Chunk numbering is continuous across every join, counted from the first
308 // segment's audible start in its own source (see `open_segments`).
309 let timeline = segments.first().map_or(0, |s| match s.source {
310 Some(source) => s
311 .media_target
312 .saturating_sub(tracks[source].as_ref().expect("opened above").priming()),
313 None => 0,
314 });
315
316 // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so
317 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
318 // without making a pause take a second to bite.
319 // One filter per segment, built here where the rate and the layout are
320 // known and off the thread that will run it. An identity curve costs a
321 // branch and nothing else ([`EqState::process`]), and a segment with no
322 // curve at all is not even that.
323 let eqs: Vec<Option<EqState>> = segments
324 .iter()
325 .enumerate()
326 .map(|(i, _)| {
327 eqs.get(i)
328 .and_then(Option::as_ref)
329 .map(|p| EqState::new(p, meta.sample_rate, meta.channels))
330 })
331 .collect();
332
333 let (tx, rx) = sync_channel(32);
334 thread::Builder::new()
335 .name("audio-decode".into())
336 .spawn(move || {
337 run(Worker {
338 tracks,
339 channels: meta.channels as usize,
340 segments,
341 eqs,
342 timeline,
343 tx,
344 })
345 })?;
346 Ok(Some((meta, rx)))
347 }
348
349 /// Every audio lane of a timeline, summed into one stream: `lanes` is one
350 /// play list per lane, each in the shape
351 /// [`open_multi_streams`](Self::open_multi_streams) takes, and what comes
352 /// out is what the device hears -- the lanes decoded side by side and added
353 /// sample for sample, clamped to `[-1, 1]` so a loud pair cannot wrap the
354 /// output.
355 ///
356 /// **One lane is not mixed at all**: it is `open_multi_streams` verbatim, so
357 /// a timeline with a single audio lane decodes exactly the samples it always
358 /// did, down to the bit and down to the thread count.
359 ///
360 /// Lengths need not agree: a lane that has run out contributes silence to
361 /// what is left, which is what a shorter lane means. Each lane keeps its own
362 /// gap rule -- a hole in it is real silence from its own worker, not a
363 /// skipped chunk -- so the sum feeds the master clock a sample per sample of
364 /// timeline however the lanes are arranged. `start_sample` numbers from the
365 /// first lane's own start (see [`AudioChunk`]).
366 pub fn open_mixed_streams(
367 sources: &[(PathBuf, usize)],
368 lanes: &[Vec<(Option<usize>, f64, f64)>],
369 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
370 Self::open_mixed_streams_eq(sources, lanes, &[])
371 }
372
373 /// [`open_mixed_streams`](Self::open_mixed_streams) with
374 /// [`open_multi_streams_eq`](Self::open_multi_streams_eq)'s per-segment
375 /// equalizers, one list per lane -- [`crate::Project::audio_eqs_from`] is
376 /// what shapes them.
377 ///
378 /// Filtering is each lane's worker's own business and therefore happens
379 /// **before** the sum: a clip's curve reaches that clip's samples and stops
380 /// there, where filtering the mix would smear every lane's curve over
381 /// everything playing at the same instant. A missing or short list plays
382 /// flat, as it does one lane down.
383 pub fn open_mixed_streams_eq(
384 sources: &[(PathBuf, usize)],
385 lanes: &[Vec<(Option<usize>, f64, f64)>],
386 eqs: &[Vec<Option<EqParams>>],
387 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
388 let [first, rest @ ..] = lanes else {
389 return Ok(None);
390 };
391 if rest.is_empty() {
392 let flat = Vec::new();
393 return Self::open_multi_streams_eq(sources, first, eqs.first().unwrap_or(&flat));
394 }
395 let mut meta = None;
396 let mut rxs = Vec::with_capacity(lanes.len());
397 for (i, segs) in lanes.iter().enumerate() {
398 // Every lane probes the same source 0, so the metas agree by
399 // construction; `None` from any of them is a silent timeline.
400 let flat = Vec::new();
401 let Some((lane_meta, rx)) =
402 Self::open_multi_streams_eq(sources, segs, eqs.get(i).unwrap_or(&flat))?
403 else {
404 return Ok(None);
405 };
406 meta = Some(lane_meta);
407 rxs.push(rx);
408 }
409 let meta = meta.expect("at least two lanes opened above");
410 let (tx, rx) = sync_channel(32);
411 let channels = usize::from(meta.channels);
412 thread::Builder::new()
413 .name("audio-mix".into())
414 .spawn(move || mix(&rxs, channels, &tx))?;
415 Ok(Some((meta, rx)))
416 }
417
418 /// Why [`open`](Self::open) came back silent for a file that *has* sound:
419 /// `Some(reason)` when there is an audio track and it is not the AAC-LC
420 /// this decodes (an AC-3 remux, say). `None` when the file is simply silent
421 /// -- nothing to tell the user there. Header only, and only worth calling
422 /// once the open has already returned no audio.
423 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
424 // Matroska: the demuxer reads its picture and nothing else yet, so a
425 // file that has sound is told so by name rather than playing silent
426 // with no reason given. A Matroska file with no audio track at all
427 // returns `None` here like any other silent file.
428 if crate::demux::is_matroska(path.as_ref()) {
429 return Ok(
430 crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {
431 format!("{codec} audio in a Matroska file is not wired to the decoder yet")
432 }),
433 );
434 }
435 let file = File::open(path.as_ref())?;
436 let size = file.metadata()?.len();
437 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
438 Ok(reader
439 .tracks()
440 .values()
441 .find(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
442 .map(|t| match t.media_type() {
443 Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"),
444 Err(_) => {
445 "the audio track is in a codec we cannot decode (AAC-LC only)".to_string()
446 }
447 }))
448 }
449
450 /// The audio parameters of `path`'s `stream`, for checking an import
451 /// against the timeline's first source: header only, no decoder and no
452 /// worker. `Ok(None)` means no audio track — a silent file, which import
453 /// pairs only with other silent files. A *named* stream that is not there
454 /// or does not decode is an `Err`, as everywhere else.
455 pub fn probe(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<AudioProbe>> {
456 let Some(track) = Track::open(path.as_ref(), stream)? else {
457 return Ok(None);
458 };
459 Ok(Some(AudioProbe {
460 sample_rate: track.sample_rate(),
461 channels: track.channels()?,
462 }))
463 }
464
465 /// Every audio stream of `path`, in file order: an entry's `index` is the
466 /// stream number [`open_multi_streams`](Self::open_multi_streams) takes.
467 /// Header only, no decoder and no worker — and no filtering either, so a
468 /// stream this engine cannot decode is listed with `decodable: false`
469 /// instead of vanishing.
470 ///
471 /// An empty list means the file has no audio at all, which is a valid
472 /// silent source.
473 ///
474 /// A standalone audio file ([`crate::is_audio`]) has exactly one stream by
475 /// construction — one track, no picture beside it — so it is described from
476 /// symphonia's own header rather than walked as an mp4, which an mp3 is not
477 /// and an ALAC `.m4a` only half is.
478 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
479 let path = path.as_ref();
480 // A Matroska file's audio tracks are not readable here yet ([`Track`]),
481 // and a stream nothing can open is not one to offer: an mkv lists as
482 // the silent source it currently is.
483 if crate::demux::is_matroska(path) {
484 return Ok(Vec::new());
485 }
486 if crate::is_audio(path) {
487 let track = SymTrack::open(path)?;
488 return Ok(vec![StreamInfo {
489 index: 0,
490 codec: track.codec.into(),
491 channels: track.channels,
492 sample_rate: track.sample_rate,
493 // Neither the mp3 nor the wav headers carry an ISO-639 tag the
494 // way an mdhd does, and a lone track needs no telling apart.
495 lang: None,
496 decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(),
497 }]);
498 }
499 let file = File::open(path)?;
500 let size = file.metadata()?.len();
501 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
502 Ok(audio_track_ids(&reader)
503 .into_iter()
504 .enumerate()
505 .map(|(index, id)| {
506 let track = &reader.tracks()[&id];
507 let aac = matches!(track.media_type(), Ok(MediaType::AAC));
508 // An AC-3 track describes itself through its own reader: mp4
509 // 0.14 parses no sample entry for it, so `channel_config` and
510 // `sample_freq_index` have nothing to say. What is listed is
511 // the *decoded* shape -- stereo, because that is what the §7.8
512 // downmix hands the timeline (see [`Ac3Track`]).
513 let ac3 = (!aac)
514 .then(|| Ac3Track::open(path, index).ok().flatten())
515 .flatten();
516 let lang = track.language();
517 StreamInfo {
518 index,
519 codec: match (aac, &ac3) {
520 (true, _) => "aac",
521 (_, Some(_)) => "ac-3",
522 _ => "unknown",
523 }
524 .into(),
525 channels: ac3
526 .as_ref()
527 .map_or_else(|| track.channel_config().map_or(0, channel_count), |t| {
528 t.channels
529 }),
530 sample_rate: ac3.as_ref().map_or_else(
531 || track.sample_freq_index().map_or(0, |f| f.freq()),
532 |t| t.sample_rate,
533 ),
534 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),
535 decodable: ac3.as_ref().is_some_and(|t| matches!(t.channels, 1 | 2))
536 || aac
537 && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity))
538 && matches!(
539 track.channel_config(),
540 Ok(ChannelConfig::Mono | ChannelConfig::Stereo)
541 ),
542 }
543 })
544 .collect())
545 }
546
547 /// How long `path`'s audio plays, in seconds. `Ok(None)` for a silent file.
548 ///
549 /// A standalone audio file is a source with no frame count of its own, so
550 /// this is what its length on the timeline is derived from. Taken from the
551 /// header where there is one; a stream that does not say — a bare mp3 with
552 /// no Xing header is the usual one — is *decoded* to find out, which is
553 /// linear in its length (~0.5 ms per source second) and happens once, at
554 /// import, rather than per repaint.
555 ///
556 /// Stream 0: this answers for a standalone audio file, whose only stream
557 /// that is. A video source's length is its frame count, never this.
558 pub fn duration_secs(path: impl AsRef<Path>) -> crate::Result<Option<f64>> {
559 let path = path.as_ref();
560 let Some(track) = Track::open(path, 0)? else {
561 return Ok(None);
562 };
563 let rate = f64::from(track.sample_rate().max(1));
564 if let Some(total) = track.total_samples() {
565 return Ok(Some(total as f64 / rate));
566 }
567 drop(track);
568 let Some((meta, rx)) = Self::open(path)? else {
569 return Ok(None);
570 };
571 let channels = usize::from(meta.channels.max(1));
572 let last = rx.into_iter().fold(0, |_, chunk| {
573 chunk.start_sample + (chunk.samples.len() / channels) as u64
574 });
575 Ok(Some(last as f64 / f64::from(meta.sample_rate.max(1))))
576 }
577
578 /// The raw AAC packets covering `segs` — the same half-open source-second
579 /// windows [`open_segments`](Self::open_segments) decodes — copied out
580 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
581 /// straight into an mp4 writer, which is the only way to keep audio in an
582 /// export at all (no pure-Rust AAC encoder exists).
583 ///
584 /// Cut points do not land on 1024-sample boundaries, so each segment is
585 /// rounded to whole packets against an error carried across the joins (see
586 /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the
587 /// asked-for length however many cuts there are, instead of drifting out of
588 /// lip sync one rounding at a time.
589 ///
590 /// The run starts one packet before the first audible one, which a reader
591 /// drops as encoder priming — for a segment list starting at 0.0 that is the
592 /// source's own priming packet, so the copy is the whole track from sample 1.
593 ///
594 /// `Ok(None)` for a file with no AAC track, and for an empty segment list.
595 ///
596 /// ponytail: the first packet after an *interior* join decodes without its
597 /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is
598 /// re-encoding just the join packets, which needs an encoder we do not have.
599 pub fn copy_segments(
600 path: impl AsRef<Path>,
601 segs: &[(f64, f64)],
602 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
603 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
604 Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs)
605 }
606
607 /// [`copy_segments`](Self::copy_segments) over several files, segments naming
608 /// their source by index into `sources`. The rounding debt is carried across
609 /// a source join exactly as across a cut inside one file, so the bound stays
610 /// half a packet over the whole list however many files it spans, and the
611 /// extra priming packet is still the very first segment's alone.
612 ///
613 /// Every source must declare the same [`AacTrackParams`]: the copy becomes
614 /// one output track with one esds. Import refuses a mismatch up front; the
615 /// check here is the backstop, as is the missing-track `Err`.
616 ///
617 /// A segment naming **no** source is a gap, and is copied as that many
618 /// packets of [`silent_packet`] silence — the rounding debt carried through
619 /// it like any other, so the hole occupies its exact duration and the audio
620 /// after it stays in sync with the picture. A gap the track *opens* on gets
621 /// one silent packet more, which is the priming a reader drops.
622 pub fn copy_multi_segments(
623 sources: &[PathBuf],
624 segs: &[(Option<usize>, f64, f64)],
625 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
626 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
627 Self::copy_multi_streams(&sources, segs)
628 }
629
630 /// [`copy_multi_segments`](Self::copy_multi_segments) with each source
631 /// naming *which* of its audio streams to copy — the same `(path, stream)`
632 /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two
633 /// take it in the same shape on purpose: an export that copied a different
634 /// stream from the one the timeline played would be a file that sounds
635 /// nothing like what was edited, and nothing would say so.
636 pub fn copy_multi_streams(
637 sources: &[(PathBuf, usize)],
638 segs: &[(Option<usize>, f64, f64)],
639 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
640 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {
641 return Ok(None); // no segments, or nothing but silence
642 };
643 let (path, stream) = sources
644 .get(first)
645 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
646 let Some(track) = copy_track(path, *stream)? else {
647 return Ok(None); // silent source, silent export
648 };
649 let params = track.track_params();
650 let mut tracks: Vec<Option<AacTrack>> = sources.iter().map(|_| None).collect();
651 tracks[first] = Some(track);
652
653 let sample_rate = params.sample_rate;
654 let mut err = 0i64;
655 let mut packets: Vec<AacPacket> = Vec::new();
656 for &(source, start_secs, end_secs) in segs {
657 let Some(source) = source else {
658 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
659 let bytes = silent_packet(params.chan_conf)?;
660 // A reader drops the first packet of an AAC track as the
661 // encoder's priming. When the track opens on a hole, that has to
662 // come out of one *extra* packet of silence: dropped out of the
663 // hole itself it would shorten it, and everything after the hole
664 // would play a packet early. It is not part of the run, so it
665 // owes the rounding debt nothing.
666 let priming = u32::from(packets.is_empty());
667 for _ in 0..packet_run(&mut err, ideal, u32::MAX) + priming {
668 packets.push(AacPacket {
669 bytes: bytes.clone(),
670 samples: SAMPLES_PER_PACKET,
671 });
672 }
673 continue;
674 };
675 let track = source_at(&mut tracks, sources, source)?;
676 if track.track_params() != params {
677 return Err(format!(
678 "source {source} audio is {:?}, the timeline's is {params:?}",
679 track.track_params()
680 )
681 .into());
682 }
683 let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale);
684 let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0);
685 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64;
686 let available = track.sample_count.saturating_sub(start_id - 1);
687 // The head packet is the priming of the first segment only: a reader
688 // drops exactly one, so an interior join must not add another --
689 // and neither must a segment behind a leading gap, which already
690 // paid the priming in silence.
691 let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1);
692 let ids = head
693 .into_iter()
694 .chain(start_id..start_id + packet_run(&mut err, ideal, available));
695 for id in ids {
696 let Some(sample) = track.reader.read_sample(track.track_id, id)? else {
697 let count = track.sample_count;
698 return Err(format!("audio sample {id} of {count} is missing").into());
699 };
700 packets.push(AacPacket {
701 bytes: sample.bytes.to_vec(),
702 samples: SAMPLES_PER_PACKET,
703 });
704 }
705 }
706 Ok(Some((params, packets)))
707 }
708}
709
710/// One AAC-LC access unit of silence, for the gaps in an exported timeline —
711/// the export copies packets and has no AAC encoder, so the only silence it can
712/// write is one spelled out by hand.
713///
714/// It is the shortest legal `raw_data_block` there is: one element carrying
715/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
716/// spectral data at all and therefore 1024 samples of exact zero. Every field
717/// is zero except the element id and the terminating `ID_END`, so the whole
718/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the
719/// unit tests, which is the only claim worth making about hand-written
720/// bitstream.
721///
722/// ponytail: mono and stereo only, because `chan_conf` beyond 2 needs more
723/// elements per block; the timeline refuses such a source at import today, so
724/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements.
725fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
726 match chan_conf {
727 // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned.
728 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]),
729 // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END.
730 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]),
731 n => Err(format!("cannot write silence for a {n}-channel AAC track").into()),
732 }
733}
734
735/// The source at `index`, on the stream it names, opened on first use. Sources
736/// a segment list never names are never touched: a project's list only grows.
737fn source_at<'a>(
738 tracks: &'a mut [Option<AacTrack>],
739 sources: &[(PathBuf, usize)],
740 index: usize,
741) -> crate::Result<&'a mut AacTrack> {
742 let slot = tracks
743 .get_mut(index)
744 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
745 if slot.is_none() {
746 let (path, stream) = &sources[index];
747 *slot = Some(
748 copy_track(path, *stream)?
749 .ok_or_else(|| format!("source {index} has no audio track"))?,
750 );
751 }
752 Ok(slot.as_mut().expect("just opened"))
753}
754
755/// A source's track for the *copy* path, which needs raw AAC access units.
756///
757/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by
758/// name and by format rather than exported silent or, worse, exported as noise:
759/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]),
760/// so a timeline carrying one of those simply cannot become an mp4 today. The
761/// wording is what a front-end shows.
762///
763/// `Ok(None)` for a file with no audio at all, which is a silent export.
764fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
765 match Track::open(path, stream)? {
766 None => Ok(None),
767 Some(Track::Aac(track)) => Ok(Some(track)),
768 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
769 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
770 // sample table can hold, and there is no AAC encoder here to turn it
771 // into one. A WAV/FLAC export of the same timeline decodes fine.
772 Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),
773 }
774}
775
776/// The one wording for "this source's audio cannot be copied into an mp4",
777/// shared by every format that cannot be: a front-end shows it verbatim.
778fn uncopyable(path: &Path, codec: &str) -> crate::Error {
779 format!(
780 "export needs AAC audio today; {} is {codec}",
781 path.file_name()
782 .unwrap_or(path.as_os_str())
783 .to_string_lossy(),
784 )
785 .into()
786}
787
788/// One source's audio, however it is stored: the mp4 AAC track the export can
789/// copy, or a standalone file read through symphonia's probe. The opener and
790/// the worker speak to this, never to either reader directly.
791enum Track {
792 Aac(AacTrack),
793 Ac3(Ac3Track),
794 Sym(SymTrack),
795}
796
797impl Track {
798 /// `Ok(None)` for a file with no audio, which is a valid silent source.
799 ///
800 /// The mp4 reader goes first and its verdict is final for anything that is
801 /// not [`crate::is_audio`]: a video file's audio track is exactly what it
802 /// always was, silent mp4s included (an mp4 whose only `soun` track is one
803 /// we cannot decode has always been a silent source, not an error). Only a
804 /// standalone audio file falls through to symphonia — which is also how an
805 /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track.
806 ///
807 /// `stream` counts audio tracks in file order, as
808 /// [`AudioSession::probe_streams`] hands them out. A standalone audio file
809 /// has exactly one, so any `stream` above 0 there is a promise the file
810 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
811 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
812 // A Matroska file's sound is not wired to either reader yet: its picture
813 // is what this slice delivers, and the source counts as a silent one --
814 // which `AudioSession::unsupported` puts into words for the user.
815 if crate::demux::is_matroska(path) {
816 return Ok(None);
817 }
818 let audio_file = crate::is_audio(path);
819 // Ahead of the AAC reader, because that one answers "not AAC" for a
820 // *named* stream with an `Err` and an AC-3 track is not an error any
821 // more. `Ok(None)` here means "not an AC-3 track", so every other file
822 // falls through to exactly the reader it always used.
823 if !audio_file
824 && let Some(track) = Ac3Track::open(path, stream)?
825 {
826 return Ok(Some(Self::Ac3(track)));
827 }
828 match AacTrack::open(path, stream) {
829 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
830 Ok(None) if !audio_file => return Ok(None),
831 Err(e) if !audio_file => return Err(e),
832 _ => {}
833 }
834 if stream > 0 {
835 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
836 }
837 SymTrack::open(path).map(|track| Some(Self::Sym(track)))
838 }
839
840 fn sample_rate(&self) -> u32 {
841 match self {
842 Self::Aac(t) => t.sample_rate,
843 Self::Ac3(t) => t.sample_rate,
844 Self::Sym(t) => t.sample_rate,
845 }
846 }
847
848 /// Mono or stereo; anything wider is refused here rather than one packet at
849 /// a time, because one output device and one copied track is all there is.
850 fn channels(&self) -> crate::Result<u16> {
851 match self {
852 Self::Aac(t) => t.channels(),
853 // Already downmixed: `channels` is what comes *out* of the decoder,
854 // which is 2 for everything from mono to 5.1 (see [`Ac3Track`]).
855 Self::Ac3(t) => match t.channels {
856 1 | 2 => Ok(t.channels),
857 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
858 },
859 Self::Sym(t) => match t.channels {
860 1 | 2 => Ok(t.channels),
861 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
862 },
863 }
864 }
865
866 /// Frames per channel of *audible* audio, priming already subtracted.
867 fn total_samples(&self) -> Option<u64> {
868 match self {
869 Self::Aac(t) => t.total_samples,
870 Self::Ac3(t) => t.total_samples,
871 Self::Sym(t) => t.total_samples,
872 }
873 }
874
875 /// Encoder delay of this file. Sources are joined, priming is not shared.
876 fn priming(&self) -> u64 {
877 match self {
878 Self::Aac(t) => t.priming,
879 Self::Ac3(t) => t.priming,
880 Self::Sym(t) => t.priming,
881 }
882 }
883
884 /// One `[start, end)` window of this source's seconds, resolved to whatever
885 /// its own reader needs to find it again.
886 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
887 match self {
888 Self::Aac(t) => t.segment(source, start_secs, end_secs),
889 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
890 Self::Sym(t) => {
891 let media_target = t.media(start_secs);
892 Segment {
893 source: Some(source),
894 start_id: 0,
895 start_pos: 0,
896 media_target,
897 media_end: t.media(end_secs).max(media_target),
898 }
899 }
900 }
901 }
902
903 /// Builds and throws away a decoder, so an undecodable stream is an `Err`
904 /// from the opener rather than a silently empty channel.
905 fn check_decoder(&self) -> crate::Result<()> {
906 match self {
907 Self::Aac(t) => {
908 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
909 }
910 Self::Ac3(t) => {
911 ac3_decoder(t.requested)?;
912 }
913 Self::Sym(t) => {
914 t.decoder()?;
915 }
916 }
917 Ok(())
918 }
919}
920
921/// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read
922/// through symphonia's own probe and codec registry. No packet table and no
923/// sample ids: the reader is *seeked* per segment and the packets it then hands
924/// out carry their own timestamps.
925struct SymTrack {
926 reader: Box<dyn FormatReader>,
927 track_id: u32,
928 sample_rate: u32,
929 channels: u16,
930 /// Frames per channel of audible audio, `None` when the header does not say.
931 total_samples: Option<u64>,
932 /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the
933 /// container where it declares one (mp3's Xing/LAME tag, ALAC's edit list).
934 priming: u64,
935 time_base: TimeBase,
936 params: AudioCodecParameters,
937 /// The format's short name, for the export refusal. `&'static` because it
938 /// comes out of the codec registry, which outlives everything here.
939 codec: &'static str,
940}
941
942impl SymTrack {
943 fn open(path: &Path) -> crate::Result<Self> {
944 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
945 // The extension is a hint, not a decision: the probe reads the magic and
946 // is free to disagree, which is what makes a mislabelled file work.
947 let mut hint = Hint::new();
948 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
949 hint.with_extension(ext);
950 }
951 let reader = symphonia::default::get_probe().probe(
952 &hint,
953 mss,
954 FormatOptions::default(),
955 MetadataOptions::default(),
956 )?;
957 let track = reader
958 .default_track(SymKind::Audio)
959 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
960 let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay);
961 let time_base = track
962 .time_base
963 .ok_or_else(|| format!("{} declares no time base", path.display()))?;
964 let Some(symphonia_core::codecs::CodecParameters::Audio(params)) =
965 track.codec_params.clone()
966 else {
967 return Err(format!("{} declares no audio codec", path.display()).into());
968 };
969 let sample_rate = params
970 .sample_rate
971 .ok_or_else(|| format!("{} declares no sample rate", path.display()))?;
972 let channels = params
973 .channels
974 .as_ref()
975 .map(|c| c.count() as u16)
976 .ok_or_else(|| format!("{} declares no channel layout", path.display()))?;
977 let codec = symphonia::default::get_codecs()
978 .get_audio_decoder(params.codec)
979 .map_or("an unsupported format", |d| d.codec.info.short_name);
980 Ok(Self {
981 reader,
982 track_id,
983 sample_rate,
984 channels,
985 total_samples: num_frames,
986 priming: u64::from(delay.unwrap_or(0)),
987 time_base,
988 params,
989 codec,
990 })
991 }
992
993 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
994 /// packets we skipped, exactly as on the AAC path.
995 fn decoder(&self) -> crate::Result<Box<dyn AudioDecoder>> {
996 Ok(symphonia::default::get_codecs()
997 .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?)
998 }
999
1000 /// `secs` on this source's audible timeline into media samples (priming
1001 /// included, so it compares directly against a decoded position).
1002 fn media(&self, secs: f64) -> u64 {
1003 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1004 }
1005
1006 /// A packet timestamp in the track's time base, as samples per channel.
1007 fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {
1008 let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
1009 (secs.max(0.0) * f64::from(self.sample_rate)) as u64
1010 }
1011}
1012
1013/// One source's AC-3 track: the same mp4 sample tables the AAC track is read
1014/// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder
1015/// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and
1016/// one timeline layout is all there is. A 5.1 BluRay track therefore arrives
1017/// here as an ordinary stereo source, and its rows in the picker say so.
1018///
1019/// `channels` is what the decoder actually emitted for the first frame rather
1020/// than an assumed 2: everything from mono to 5.1 downmixes to stereo, but a 2.1
1021/// stream is a passthrough the library leaves at 3, and that is refused by name
1022/// in [`Track::channels`] instead of being mislabelled.
1023struct Ac3Track {
1024 reader: Mp4Reader<BufReader<File>>,
1025 track_id: u32,
1026 sample_count: u32,
1027 sample_rate: u32,
1028 channels: u16,
1029 timescale: u32,
1030 priming: u64,
1031 total_samples: Option<u64>,
1032 stts: Vec<(u32, u32)>,
1033 /// What the decoder is asked to hand out, from this track's own layout:
1034 /// `Some(2)` for anything with more than one front channel, `None` — the
1035 /// library's passthrough — for a mono track. See [`ac3_decoder`].
1036 requested: Option<u16>,
1037}
1038
1039impl Ac3Track {
1040 /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it
1041 /// is anything else (including out of range) — the caller then goes on to
1042 /// the AAC reader, which owns those verdicts and their wording.
1043 ///
1044 /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without
1045 /// keeping the fourcc, so what the track *is* comes out of the `stsd` by
1046 /// hand ([`crate::demux::sample_entry`]); the rate and the channel count
1047 /// come out of the first syncframe, which is where AC-3 states them.
1048 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1049 let file = File::open(path)?;
1050 let size = file.metadata()?.len();
1051 let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?;
1052 let ids = audio_track_ids(&reader);
1053 let Some(&track_id) = ids.get(stream) else {
1054 return Ok(None);
1055 };
1056 if !matches!(crate::demux::sample_entry(path, track_id), Ok((kind, _)) if &kind == b"ac-3")
1057 {
1058 return Ok(None);
1059 }
1060 let track = &reader.tracks()[&track_id];
1061 let timescale = track.timescale();
1062 let duration = track.trak.mdia.mdhd.duration;
1063 let edit = edit_media_time(track);
1064 let stts: Vec<(u32, u32)> = stts_pairs(track).collect();
1065 let sample_count = reader.sample_count(track_id)?;
1066
1067 let first = reader
1068 .read_sample(track_id, 1)?
1069 .ok_or("the AC-3 track has no samples")?;
1070 let sample_rate = oxideav_ac3::syncinfo::parse(&first.bytes)
1071 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?
1072 .sample_rate;
1073 let nfchans = oxideav_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default())
1074 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
1075 .nfchans;
1076 let requested = (nfchans > 1).then_some(2);
1077 let mut decoder = ac3_decoder(requested)?;
1078 let channels = decode_ac3(&mut decoder, &first.bytes)?
1079 .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16)
1080 .filter(|&c| c > 0)
1081 .ok_or("the first AC-3 syncframe decoded to nothing")?;
1082
1083 // No encoder delay in AC-3; a remux that writes an edit list is still
1084 // honoured, exactly as the AAC track honours it.
1085 let priming = edit
1086 .and_then(|t| scale(t, sample_rate, timescale))
1087 .unwrap_or(0);
1088 Ok(Some(Self {
1089 track_id,
1090 sample_count,
1091 sample_rate,
1092 channels,
1093 timescale,
1094 priming,
1095 total_samples: scale(duration, sample_rate, timescale)
1096 .map(|d| d.saturating_sub(priming)),
1097 stts,
1098 requested,
1099 reader,
1100 }))
1101 }
1102
1103 /// `secs` on this source's audible timeline into media samples.
1104 fn media(&self, secs: f64) -> u64 {
1105 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1106 }
1107
1108 /// One `[start, end)` window, resolved to syncframes and media samples —
1109 /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll.
1110 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1111 let media_target = self.media(start_secs);
1112 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
1113 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL);
1114 Segment {
1115 source: Some(source),
1116 start_id,
1117 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
1118 media_target,
1119 media_end: self.media(end_secs).max(media_target),
1120 }
1121 }
1122}
1123
1124/// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own
1125/// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a
1126/// 5.1 track at all. Fresh per segment for the same reason every other decoder
1127/// here is: a seek leaves overlap-add state belonging to the frames we skipped.
1128///
1129/// ponytail: `Some(2)` on a **mono** (`acmod` 1/0) source decodes to digital
1130/// silence in oxideav-ac3 0.0.10 — measured, 5.1 and stereo are correct — so a
1131/// mono track asks for no downmix at all and stays the mono source it is. The
1132/// upgrade path is `Some(2)` unconditionally once the library duplicates the
1133/// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change.
1134fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {
1135 let mut registry = CodecRegistry::new();
1136 oxideav_ac3::register_codecs(&mut registry);
1137 let mut params = CodecParameters::audio(CodecId::new("ac3"));
1138 params.channels = channels;
1139 registry
1140 .first_decoder(&params)
1141 .map_err(|e| format!("no AC-3 decoder: {e:?}").into())
1142}
1143
1144/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the
1145/// decoder wants more input before it can hand a frame back, which is not an
1146/// error. The library speaks S16 little-endian; `/32768` is the whole
1147/// conversion, and it lands in the `[-1, 1)` every other reader here emits.
1148fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> {
1149 let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());
1150 decoder
1151 .send_packet(&packet)
1152 .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;
1153 match decoder.receive_frame() {
1154 Ok(Frame::Audio(audio)) => Ok(Some(
1155 audio.data[0]
1156 .chunks_exact(2)
1157 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
1158 .collect(),
1159 )),
1160 Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),
1161 Err(oxideav_core::Error::NeedMore) => Ok(None),
1162 Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),
1163 }
1164}
1165
1166/// One source's AAC track, resolved once: the reader plus everything the header
1167/// has to say about it. `stts` is copied out because every other field would
1168/// otherwise keep a borrow alive on the reader the worker needs mutably — a real
1169/// AAC track has one entry, so it is two `u32`s.
1170struct AacTrack {
1171 reader: Mp4Reader<BufReader<File>>,
1172 track_id: u32,
1173 sample_count: u32,
1174 sample_rate: u32,
1175 timescale: u32,
1176 /// Encoder delay of *this* file. Sources are joined, priming is not shared.
1177 priming: u64,
1178 total_samples: Option<u64>,
1179 stts: Vec<(u32, u32)>,
1180 config: ChannelConfig,
1181 freq_index: u8,
1182 chan_conf: u8,
1183 /// A fresh decoder is built from these per segment: seeking mid-stream
1184 /// leaves MDCT and PNS state that belongs to the packets we skipped.
1185 params: AudioCodecParameters,
1186}
1187
1188impl AacTrack {
1189 /// The `stream`-th audio track of `path`, counted in file order over *all*
1190 /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out.
1191 ///
1192 /// Stream 0 is best effort: `Ok(None)` when there is no AAC track there at
1193 /// all, which is a valid silent source (a file whose audio is AC-3 still has
1194 /// a picture worth editing) and, for a standalone audio file, the door
1195 /// through to symphonia ([`Track::open`]). A stream the caller *named* is a
1196 /// promise instead, so out of range or not AAC there is an `Err` rather than
1197 /// silence the caller did not ask for.
1198 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1199 let file = File::open(path)?;
1200 let size = file.metadata()?.len();
1201 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
1202
1203 let ids = audio_track_ids(&reader);
1204 let Some(track) = ids.get(stream).map(|id| &reader.tracks()[id]) else {
1205 return match stream {
1206 0 => Ok(None),
1207 n => Err(format!(
1208 "{}: audio stream {n} of {} streams",
1209 path.display(),
1210 ids.len()
1211 )
1212 .into()),
1213 };
1214 };
1215 if !matches!(track.media_type(), Ok(MediaType::AAC)) {
1216 return match stream {
1217 0 => Ok(None),
1218 n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()),
1219 };
1220 }
1221 // Refuse early with a message instead of failing packet by packet — and
1222 // a copy carries no profile of its own: the writer rebuilds the
1223 // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a
1224 // non-LC source would be mislabelled rather than merely unplayable.
1225 match track.audio_profile()? {
1226 AudioObjectType::AacLowComplexity => {}
1227 other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()),
1228 }
1229
1230 let track_id = track.track_id();
1231 let sample_rate = track.sample_freq_index()?.freq();
1232 let timescale = track.timescale();
1233 let priming = priming_samples(track, sample_rate);
1234 let (_, freq_index, chan_conf) = asc_fields(track)?;
1235 let mut params = AudioCodecParameters::new();
1236 params
1237 .for_codec(CODEC_ID_AAC)
1238 .with_sample_rate(sample_rate)
1239 .with_extra_data(audio_specific_config(track)?);
1240 let this = Self {
1241 track_id,
1242 sample_count: reader.sample_count(track_id)?,
1243 sample_rate,
1244 timescale,
1245 priming,
1246 total_samples: scale(track.trak.mdia.mdhd.duration, sample_rate, timescale)
1247 .map(|d| d.saturating_sub(priming)),
1248 stts: stts_pairs(track).collect(),
1249 config: track.channel_config()?,
1250 freq_index,
1251 chan_conf,
1252 params,
1253 reader,
1254 };
1255 Ok(Some(this))
1256 }
1257
1258 /// Channel count. `AacDecoder` only does mono and stereo, so anything else
1259 /// is refused here rather than one packet at a time.
1260 fn channels(&self) -> crate::Result<u16> {
1261 match self.config {
1262 ChannelConfig::Mono => Ok(1),
1263 ChannelConfig::Stereo => Ok(2),
1264 other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()),
1265 }
1266 }
1267
1268 fn track_params(&self) -> AacTrackParams {
1269 AacTrackParams {
1270 freq_index: self.freq_index,
1271 chan_conf: self.chan_conf,
1272 sample_rate: self.sample_rate,
1273 }
1274 }
1275
1276 /// `secs` on this source's audible timeline into media samples (priming
1277 /// included, so it compares directly against a decoded position).
1278 /// `f64::INFINITY` saturates.
1279 fn media(&self, secs: f64) -> u64 {
1280 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1281 }
1282
1283 /// One `[start, end)` window of this source's seconds, resolved to its own
1284 /// packets and media samples.
1285 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1286 let media_target = self.media(start_secs);
1287 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
1288 // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
1289 // packet to cancel aliasing, plus one more to warm the decoder up. Their
1290 // output is discarded below, so this only costs decode time.
1291 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL);
1292 Segment {
1293 source: Some(source),
1294 start_id,
1295 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
1296 media_target,
1297 // An inverted segment is an empty one, never a backwards run.
1298 media_end: self.media(end_secs).max(media_target),
1299 }
1300 }
1301}
1302
1303/// How many whole packets to copy for a window of `ideal` samples per channel,
1304/// capped at the `available` packets left in the track.
1305///
1306/// `err` is "samples copied so far minus samples asked for", carried across the
1307/// segment joins: rounding to nearest *against the running debt* keeps the
1308/// cumulative error inside half a packet forever, where independent per-segment
1309/// rounding would random-walk away from sync (charter D1: < 1024 at every join).
1310fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
1311 let packet = i64::from(SAMPLES_PER_PACKET);
1312 // Never carry a debt the track cannot pay: a segment running past the end
1313 // would otherwise inflate every later one. (Also tames `f64::INFINITY`,
1314 // which saturates to `i64::MAX` on the cast above.)
1315 let ideal = ideal.min(i64::from(available) * packet);
1316 let want = (ideal - *err) as f64 / packet as f64;
1317 let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32;
1318 *err += i64::from(n) * packet - ideal;
1319 n
1320}
1321
1322/// This file's audio tracks in file order — the order a stream index counts in.
1323/// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a
1324/// `HashMap`: iterating that would make "stream 0" a different track from one
1325/// run to the next on any file carrying more than one.
1326fn audio_track_ids<R>(reader: &Mp4Reader<R>) -> Vec<u32> {
1327 reader
1328 .moov
1329 .traks
1330 .iter()
1331 .filter(|trak| {
1332 matches!(
1333 TrackType::try_from(&trak.mdia.hdlr.handler_type),
1334 Ok(TrackType::Audio)
1335 )
1336 })
1337 .map(|trak| trak.tkhd.track_id)
1338 .collect()
1339}
1340
1341/// Channels in an AAC channel configuration. The config number *is* the channel
1342/// count up to 5.1; 7.1 is the one that is not.
1343fn channel_count(config: ChannelConfig) -> u16 {
1344 match config {
1345 ChannelConfig::SevenOne => 8,
1346 other => other as u16,
1347 }
1348}
1349
1350/// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a
1351/// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside
1352/// the crate (same trap as `SttsEntry`, see [`packet_at`]).
1353fn asc_fields(track: &Mp4Track) -> crate::Result<(u8, u8, u8)> {
1354 let esds = track
1355 .trak
1356 .mdia
1357 .minf
1358 .stbl
1359 .stsd
1360 .mp4a
1361 .as_ref()
1362 .and_then(|mp4a| mp4a.esds.as_ref())
1363 .ok_or("AAC track has no esds descriptor")?;
1364 let cfg = &esds.es_desc.dec_config.dec_specific;
1365 Ok((cfg.profile, cfg.freq_index, cfg.chan_conf))
1366}
1367
1368/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14
1369/// parses those out and drops the raw bytes, so this is the exact inverse of its
1370/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`).
1371fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {
1372 let (profile, freq_index, chan_conf) = asc_fields(track)?;
1373 Ok(Box::new([
1374 (profile << 3) | (freq_index >> 1),
1375 (freq_index << 7) | (chan_conf << 3),
1376 ]))
1377}
1378
1379/// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`]
1380/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. Shared with
1381/// `demux`, which walks a video trak's table with the same two helpers.
1382pub(crate) fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
1383 track
1384 .trak
1385 .mdia
1386 .minf
1387 .stbl
1388 .stts
1389 .entries
1390 .iter()
1391 .map(|e| (e.sample_count, e.sample_delta))
1392}
1393
1394/// Encoder delay in samples-per-channel: the edit list's first real entry says
1395/// how far into the media the presentation starts.
1396///
1397/// ponytail: an explicit `media_time` of 0 is taken at face value (no trim).
1398/// Muxers that write a zero edit list despite a primed stream would leak the
1399/// priming; upgrade path is preferring the codec delay when it disagrees.
1400fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 {
1401 edit_media_time(track)
1402 .and_then(|t| scale(t, sample_rate, track.timescale()))
1403 .unwrap_or(DEFAULT_PRIMING)
1404}
1405
1406/// `media_time` of the edit list's first real entry, in the track's own
1407/// timescale: where the presentation starts inside the media. `None` when there
1408/// is no edit list, or only empty entries -- those shift the timeline rather
1409/// than trim the media, and neither track honours that shift (see
1410/// [`priming_samples`]'s ponytail). Shared with `demux`, which owes the video
1411/// track the same trim.
1412pub(crate) fn edit_media_time(track: &Mp4Track) -> Option<u64> {
1413 track
1414 .trak
1415 .edts
1416 .as_ref()
1417 .and_then(|edts| edts.elst.as_ref())
1418 .and_then(|elst| {
1419 elst.entries
1420 .iter()
1421 .map(|e| e.media_time)
1422 .find(|&t| t != EMPTY_EDIT && t != u64::MAX)
1423 })
1424}
1425
1426/// `value` from the track timescale into samples-per-channel. `None` on a zero
1427/// timescale, which would be a broken header.
1428fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
1429 let timescale = u64::from(timescale);
1430 (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
1431}
1432
1433/// Inverse of [`scale`]: samples-per-channel back into the track timescale.
1434fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 {
1435 match sample_rate {
1436 0 => 0,
1437 rate => samples * u64::from(timescale) / u64::from(rate),
1438 }
1439}
1440
1441/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll`
1442/// packets, plus that packet's own start time. Inverse of the mp4 crate's
1443/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is
1444/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs.
1445///
1446/// ponytail: the walk-back is clamped to the start of the containing stts entry
1447/// rather than crossing into the previous one, so a target within `pre_roll`
1448/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
1449/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
1450/// carrying the previous entry's delta through the walk.
1451pub(crate) fn packet_at(
1452 entries: impl IntoIterator<Item = (u32, u32)>,
1453 target_ts: u64,
1454 pre_roll: u32,
1455) -> (u32, u64) {
1456 let mut first_id = 1u32;
1457 let mut elapsed = 0u64;
1458 let mut last = (1u32, 0u64);
1459 for (count, delta) in entries {
1460 let span = u64::from(count) * u64::from(delta);
1461 let index = if target_ts < elapsed + span && delta != 0 {
1462 ((target_ts - elapsed) / u64::from(delta)) as u32
1463 } else {
1464 // Past this entry: remember its last packet in case the target runs
1465 // past the end of the track entirely.
1466 last = (
1467 first_id + count.saturating_sub(1),
1468 elapsed + span.saturating_sub(u64::from(delta)),
1469 );
1470 first_id += count;
1471 elapsed += span;
1472 continue;
1473 };
1474 let index = index - index.min(pre_roll);
1475 return (
1476 first_id + index,
1477 elapsed + u64::from(index) * u64::from(delta),
1478 );
1479 }
1480 last
1481}
1482
1483/// One window of a source to decode, resolved to media samples and packets —
1484/// or, with no source, a stretch of synthesised silence.
1485struct Segment {
1486 /// Index into the worker's tracks; the media positions below are that
1487 /// source's, not the timeline's. `None` for a gap, where only the length
1488 /// (`media_end`) means anything.
1489 source: Option<usize>,
1490 /// First packet to feed the decoder, 1-based; includes the pre-roll.
1491 start_id: u32,
1492 /// Media position of `start_id`'s first frame, in samples-per-channel.
1493 start_pos: u64,
1494 /// Media position of the first frame to emit. Everything decoded before it
1495 /// is pre-roll, priming, or seek overshoot, and gets dropped.
1496 media_target: u64,
1497 /// One past the last frame to emit; `u64::MAX` for "to the end of track".
1498 media_end: u64,
1499}
1500
1501impl Segment {
1502 /// `frames` per channel of silence — a gap in the audio lane.
1503 fn silence(frames: u64) -> Self {
1504 Self {
1505 source: None,
1506 start_id: 0,
1507 start_pos: 0,
1508 media_target: 0,
1509 media_end: frames,
1510 }
1511 }
1512}
1513
1514struct Worker {
1515 /// Indexed by [`Segment::source`]; only the sources some segment names are
1516 /// `Some`, the rest were never opened.
1517 tracks: Vec<Option<Track>>,
1518 channels: usize,
1519 segments: Vec<Segment>,
1520 /// One per entry of `segments`, in the same order: the filter that segment's
1521 /// samples pass through on the way out, or `None` for one that plays flat.
1522 /// Beside the segments rather than inside them so the emit path can hold the
1523 /// window rules and the filter memory at once without splitting a borrow.
1524 eqs: Vec<Option<EqState>>,
1525 /// `start_sample` of the first chunk.
1526 timeline: u64,
1527 tx: SyncSender<AudioChunk>,
1528}
1529
1530/// Sums one worker per lane into one stream (see
1531/// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline
1532/// position and synthesises its own gaps, so the lanes are sample-aligned by
1533/// construction and a mix is an add: no resampling, no positioning, no drift to
1534/// correct. What is emitted at each turn is the shortest block every still-live
1535/// lane can supply, which keeps a slow lane from being outrun and never buffers
1536/// more than the chunks already in flight.
1537///
1538/// A lane whose channel has closed has ended and simply stops being added --
1539/// that is what "shorter lane" means here. The mix ends when all of them have.
1540/// The accumulator is reused across turns; the one allocation per chunk is the
1541/// buffer the channel takes ownership of, and none of this is the RT path (the
1542/// device callback reads the ring the feeder has already filled).
1543fn mix(rxs: &[Receiver<AudioChunk>], channels: usize, tx: &SyncSender<AudioChunk>) {
1544 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
1545 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
1546 // Numbering follows lane 0, whose first chunk says where it starts.
1547 let mut base = 0;
1548 let mut emitted = 0;
1549 let mut out: Vec<f32> = Vec::new();
1550 loop {
1551 for (i, rx) in rxs.iter().enumerate() {
1552 while live[i] && pending[i].is_empty() {
1553 match rx.recv() {
1554 Ok(chunk) => {
1555 if i == 0 && emitted == 0 {
1556 base = chunk.start_sample;
1557 }
1558 pending[i] = chunk.samples;
1559 }
1560 Err(_) => live[i] = false,
1561 }
1562 }
1563 }
1564 // The block every lane still playing can cover; `None` once they are all
1565 // done, which is the only way out of this loop besides a gone consumer.
1566 let Some(frames) = pending
1567 .iter()
1568 .filter(|p| !p.is_empty())
1569 .map(|p| p.len() / channels)
1570 .min()
1571 .filter(|&f| f > 0)
1572 else {
1573 return;
1574 };
1575 let block = frames * channels;
1576 out.clear();
1577 out.resize(block, 0.0);
1578 for lane in pending.iter_mut().filter(|p| !p.is_empty()) {
1579 for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) {
1580 *sum += sample;
1581 }
1582 }
1583 let chunk = AudioChunk {
1584 start_sample: base + emitted,
1585 // Clamped, not wrapped: two lanes at full scale are what a mix has
1586 // to survive, and the device takes `[-1, 1]`.
1587 samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(),
1588 };
1589 if tx.send(chunk).is_err() {
1590 return; // caller moved on
1591 }
1592 emitted += frames as u64;
1593 }
1594}
1595
1596fn run(mut w: Worker) {
1597 let mut interleaved = Vec::new();
1598 let channels = w.channels;
1599 // Chunk numbering is continuous across every join, source ones included.
1600 let mut timeline = w.timeline;
1601 let segments = std::mem::take(&mut w.segments);
1602 let mut eqs = std::mem::take(&mut w.eqs);
1603 // A short list is "flat from here on" (`open_multi_streams_eq`), which this
1604 // pads out so the zip below still walks every segment.
1605 eqs.resize_with(segments.len(), || None);
1606
1607 for (seg, eq) in segments.iter().zip(eqs.iter_mut()) {
1608 let Some(source) = seg.source else {
1609 // A gap: hand the device real silence rather than nothing at all,
1610 // in the same packet-sized chunks decoding produces, so `fed` and
1611 // the master clock keep counting straight through the hole.
1612 let mut left = seg.media_end;
1613 while left > 0 {
1614 let frames = left.min(u64::from(SAMPLES_PER_PACKET));
1615 let chunk = AudioChunk {
1616 start_sample: timeline,
1617 samples: vec![0.0; frames as usize * channels],
1618 };
1619 if w.tx.send(chunk).is_err() {
1620 return; // caller moved on
1621 }
1622 timeline += frames;
1623 left -= frames;
1624 }
1625 continue;
1626 };
1627 let Some(track) = w.tracks[source].as_mut() else {
1628 continue; // opener fills every named source; nothing to decode
1629 };
1630 let track = match track {
1631 Track::Sym(track) => {
1632 if !run_sym(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) {
1633 return; // consumer went away
1634 }
1635 continue;
1636 }
1637 Track::Ac3(track) => {
1638 if !run_ac3(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) {
1639 return; // consumer went away
1640 }
1641 continue;
1642 }
1643 Track::Aac(track) => track,
1644 };
1645 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())
1646 {
1647 Ok(decoder) => decoder,
1648 Err(e) => {
1649 eprintln!("audio decoder init failed: {e}");
1650 return;
1651 }
1652 };
1653 let mut pos = seg.start_pos;
1654
1655 for id in seg.start_id..=track.sample_count {
1656 if pos >= seg.media_end {
1657 break; // segment done, on to the next one
1658 }
1659 let sample = match track.reader.read_sample(track.track_id, id) {
1660 Ok(Some(sample)) => sample,
1661 Ok(None) => break,
1662 Err(e) => {
1663 eprintln!("audio demux error at sample {id}: {e}");
1664 break;
1665 }
1666 };
1667 let packet = Packet::new(
1668 track.track_id,
1669 units::Timestamp::new(sample.start_time as i64),
1670 units::Duration::new(u64::from(sample.duration)),
1671 &sample.bytes[..],
1672 );
1673 let buf = match decoder.decode(&packet) {
1674 Ok(buf) => buf,
1675 Err(e) => {
1676 eprintln!("audio decode error at sample {id}: {e}");
1677 break;
1678 }
1679 };
1680 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
1681 let next = pos + (interleaved.len() / channels) as u64;
1682 if !emit(
1683 &mut interleaved,
1684 channels,
1685 seg,
1686 eq.as_mut(),
1687 pos,
1688 next,
1689 &mut timeline,
1690 &w.tx,
1691 ) {
1692 return; // consumer went away
1693 }
1694 pos = next;
1695 }
1696 }
1697}
1698
1699/// Trims one decoded buffer to the segment window and sends what survives.
1700/// `pos` is the media position of its first frame and `next` of the one after
1701/// it; both readers hand the same thing here, which is why the window rules
1702/// live in one place. `false` means the consumer went away.
1703///
1704/// Everything before the target is encoder priming and/or decoder pre-roll, not
1705/// audio the caller asked for: it is dropped, splitting the buffer that
1706/// straddles the target. The tail past the segment end goes too — on a short
1707/// segment that is this same buffer, trimmed at both ends.
1708///
1709/// The segment's equalizer runs here, on the trimmed buffer and nowhere else:
1710/// this is the one place both readers hand their samples over, so playback and
1711/// an audio export get the same filtered stream by construction rather than by
1712/// two call sites agreeing. Trimmed first, so the pre-roll a listener never
1713/// hears cannot ring the filter either. Nothing is allocated -- the device
1714/// callback is two hand-offs downstream of here in any case.
1715fn emit(
1716 interleaved: &mut Vec<f32>,
1717 channels: usize,
1718 seg: &Segment,
1719 eq: Option<&mut EqState>,
1720 pos: u64,
1721 next: u64,
1722 timeline: &mut u64,
1723 tx: &SyncSender<AudioChunk>,
1724) -> bool {
1725 if next <= seg.media_target {
1726 return true;
1727 }
1728 let mut pos = pos;
1729 if pos < seg.media_target {
1730 interleaved.drain(..(seg.media_target - pos) as usize * channels);
1731 pos = seg.media_target;
1732 }
1733 if next > seg.media_end {
1734 interleaved.truncate((seg.media_end - pos) as usize * channels);
1735 }
1736 if interleaved.is_empty() {
1737 return true; // nothing left of it; the loop head ends the segment
1738 }
1739 if let Some(eq) = eq {
1740 eq.process(interleaved);
1741 }
1742 let chunk = AudioChunk {
1743 start_sample: *timeline,
1744 samples: std::mem::take(interleaved),
1745 };
1746 *timeline += (chunk.samples.len() / channels) as u64;
1747 tx.send(chunk).is_ok()
1748}
1749
1750/// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids
1751/// come out of the same mp4 tables, the window rules are [`emit`]'s as always,
1752/// and what reaches the mixer is already the stereo downmix. `false` means the
1753/// consumer went away.
1754fn run_ac3(
1755 track: &mut Ac3Track,
1756 seg: &Segment,
1757 mut eq: Option<&mut EqState>,
1758 channels: usize,
1759 timeline: &mut u64,
1760 tx: &SyncSender<AudioChunk>,
1761) -> bool {
1762 let mut decoder = match ac3_decoder(track.requested) {
1763 Ok(decoder) => decoder,
1764 Err(e) => {
1765 eprintln!("audio decoder init failed: {e}");
1766 return true;
1767 }
1768 };
1769 let mut pos = seg.start_pos;
1770 for id in seg.start_id..=track.sample_count {
1771 let mut interleaved;
1772 if pos >= seg.media_end {
1773 return true; // segment done, on to the next one
1774 }
1775 let sample = match track.reader.read_sample(track.track_id, id) {
1776 Ok(Some(sample)) => sample,
1777 Ok(None) => return true,
1778 Err(e) => {
1779 eprintln!("audio demux error at sample {id}: {e}");
1780 return true;
1781 }
1782 };
1783 match decode_ac3(&mut decoder, &sample.bytes) {
1784 Ok(Some(pcm)) => interleaved = pcm,
1785 Ok(None) => continue, // the decoder wants another frame first
1786 Err(e) => {
1787 eprintln!("audio decode error at sample {id}: {e}");
1788 return true;
1789 }
1790 }
1791 let next = pos + (interleaved.len() / channels) as u64;
1792 if !emit(
1793 &mut interleaved,
1794 channels,
1795 seg,
1796 eq.as_deref_mut(),
1797 pos,
1798 next,
1799 timeline,
1800 tx,
1801 ) {
1802 return false;
1803 }
1804 pos = next;
1805 }
1806 true
1807}
1808
1809/// One segment of a standalone audio file: seek the reader to just before the
1810/// window, then decode forward until the window is filled.
1811///
1812/// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the
1813/// target is thrown away by [`emit`], which is what gives a codec with decoder
1814/// state — mp3's bit reservoir above all — something to warm up on, exactly as
1815/// the AAC path's two-packet pre-roll does. A reader that cannot seek at all
1816/// simply decodes from wherever it is; the window rules still hold, it is only
1817/// slower. `false` means the consumer went away.
1818fn run_sym(
1819 track: &mut SymTrack,
1820 seg: &Segment,
1821 mut eq: Option<&mut EqState>,
1822 channels: usize,
1823 timeline: &mut u64,
1824 tx: &SyncSender<AudioChunk>,
1825) -> bool {
1826 let mut decoder = match track.decoder() {
1827 Ok(decoder) => decoder,
1828 Err(e) => {
1829 eprintln!("audio decoder init failed: {e}");
1830 return true;
1831 }
1832 };
1833 let rate = f64::from(track.sample_rate.max(1));
1834 let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate;
1835 if let Some(time) = Time::try_from_secs_f64(from) {
1836 let to = SeekTo::Time {
1837 time,
1838 track_id: Some(track.track_id),
1839 };
1840 // A failed seek is not fatal: it leaves the reader where it was, and
1841 // the window rules below still only emit what the segment asked for.
1842 if let Err(e) = track.reader.seek(SeekMode::Accurate, to) {
1843 eprintln!("audio seek to {from:.3}s failed: {e}");
1844 }
1845 }
1846 let mut interleaved = Vec::new();
1847 loop {
1848 let packet = match track.reader.next_packet() {
1849 Ok(Some(packet)) => packet,
1850 Ok(None) => return true, // end of the file, and of the segment
1851 Err(e) => {
1852 eprintln!("audio demux error: {e}");
1853 return true;
1854 }
1855 };
1856 if packet.track_id != track.track_id {
1857 continue; // another track of the same container
1858 }
1859 let pos = track.samples_at(packet.pts);
1860 if pos >= seg.media_end {
1861 return true; // segment done, on to the next one
1862 }
1863 let buf = match decoder.decode(&packet) {
1864 Ok(buf) => buf,
1865 Err(e) => {
1866 eprintln!("audio decode error at sample {pos}: {e}");
1867 return true;
1868 }
1869 };
1870 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
1871 let next = pos + (interleaved.len() / channels) as u64;
1872 // Reborrowed per packet: the filter memory has to carry across the
1873 // packet boundary, so this is one `EqState` for the whole segment.
1874 if !emit(
1875 &mut interleaved,
1876 channels,
1877 seg,
1878 eq.as_deref_mut(),
1879 pos,
1880 next,
1881 timeline,
1882 tx,
1883 ) {
1884 return false;
1885 }
1886 }
1887}
1888
1889#[cfg(test)]
1890mod tests {
1891 use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run};
1892
1893 /// A real AAC track: one stts entry, N packets of 1024.
1894 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
1895 [(count, 1024)]
1896 }
1897
1898 #[test]
1899 fn packet_at_walks_back_by_the_pre_roll() {
1900 // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..).
1901 assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064));
1902 assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016));
1903 // Exactly on a packet boundary is the start of that packet, not the end
1904 // of the previous one.
1905 assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048));
1906 }
1907
1908 #[test]
1909 fn packet_at_clamps_both_ends() {
1910 // Head: no room for the walk-back, and packet ids are 1-based.
1911 assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0));
1912 assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0));
1913 // Past the end: the last packet, so the worker decodes ~nothing.
1914 assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776));
1915 // Degenerate boxes must not panic or wrap.
1916 assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0));
1917 assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0));
1918 }
1919
1920 #[test]
1921 fn packet_at_crosses_stts_entries() {
1922 // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240
1923 // with packet 11.
1924 let entries = [(10u32, 1024u32), (10, 512)];
1925 assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288));
1926 assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264));
1927 // The ponytail clamp: on the first packet of the second entry the
1928 // walk-back stops there instead of stepping into the first entry.
1929 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
1930 }
1931
1932 /// xorshift64: adversarial segment lists do not deserve a dependency.
1933 fn rng(state: &mut u64) -> u64 {
1934 *state ^= *state << 13;
1935 *state ^= *state >> 7;
1936 *state ^= *state << 17;
1937 *state
1938 }
1939
1940 #[test]
1941 fn packet_run_keeps_cumulative_error_under_a_packet() {
1942 let packet = i64::from(SAMPLES_PER_PACKET);
1943 let mut state = 0x5eed_1234_9876_abcd;
1944 for rate in [44100i64, 48000] {
1945 for list in 0..100 {
1946 let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64);
1947 // 3..43 joins of anything from one video frame to four seconds.
1948 for join in 0..3 + rng(&mut state) % 40 {
1949 let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64;
1950 copied += i64::from(packet_run(&mut err, ideal, u32::MAX));
1951 asked += ideal;
1952 assert!(
1953 err.abs() < packet,
1954 "rate {rate} list {list} join {join}: err {err}"
1955 );
1956 }
1957 // The accumulator is the whole story: what it says is the drift.
1958 assert_eq!(copied * packet - asked, err);
1959 }
1960 }
1961 }
1962
1963 #[test]
1964 fn packet_run_rounds_against_the_running_debt() {
1965 // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples
1966 // owed, and the debt is repaid by a 44-packet second once it crosses a
1967 // half packet — never by letting each second round on its own.
1968 let mut err = 0;
1969 assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43);
1970 assert_eq!(err, -68);
1971 let mut seconds = 1;
1972 while packet_run(&mut err, 44100, u32::MAX) == 43 {
1973 seconds += 1;
1974 assert!(seconds < 20, "debt never repaid, err {err}");
1975 }
1976 assert_eq!(seconds, 7, "68 samples a second, half a packet is 512");
1977 assert!(err > 0, "the repaying second overshoots, err {err}");
1978 }
1979
1980 #[test]
1981 fn packet_run_forgives_a_debt_the_track_cannot_pay() {
1982 // Asking a second of a track with ten packets left: it delivers ten and
1983 // does not make the next segment copy the shortfall from elsewhere.
1984 let mut err = 0;
1985 assert_eq!(packet_run(&mut err, 44100, 10), 10);
1986 assert_eq!(err, 0);
1987 // Degenerate windows are empty, not negative.
1988 assert_eq!(packet_run(&mut err, 0, 10), 0);
1989 assert_eq!(packet_run(&mut err, i64::MAX, 7), 7);
1990 }
1991
1992 #[test]
1993 fn asc_round_trips_aac_lc_44100_stereo() {
1994 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
1995 let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8);
1996 let asc = [
1997 (profile << 3) | (freq_index >> 1),
1998 (freq_index << 7) | (chan_conf << 3),
1999 ];
2000 assert_eq!(asc, [0x12, 0x10]);
2001 }
2002
2003 /// The one claim worth making about a hand-written bitstream: our own
2004 /// decoder turns it into exactly one packet of exactly zero.
2005 #[test]
2006 fn a_silent_packet_decodes_to_a_packet_of_zero() {
2007 use super::{AacDecoder, AudioDecoder, AudioDecoderOptions, silent_packet};
2008 use symphonia_core::codecs::audio::{AudioCodecParameters, well_known::CODEC_ID_AAC};
2009 use symphonia_core::{packet::Packet, units};
2010
2011 for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] {
2012 // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels.
2013 let asc: Box<[u8]> = Box::new([(2 << 3) | (4 >> 1), (4 << 7) | (chan_conf << 3)]);
2014 let mut params = AudioCodecParameters::new();
2015 params
2016 .for_codec(CODEC_ID_AAC)
2017 .with_sample_rate(44100)
2018 .with_extra_data(asc);
2019 let mut decoder =
2020 AacDecoder::try_new(&params, &AudioDecoderOptions::default()).expect("decoder");
2021 let bytes = silent_packet(chan_conf).expect("silence");
2022 let packet = Packet::new(
2023 0,
2024 units::Timestamp::new(0),
2025 units::Duration::new(u64::from(SAMPLES_PER_PACKET)),
2026 &bytes[..],
2027 );
2028 let buf = decoder.decode(&packet).expect("decodes as AAC-LC");
2029 let mut out = Vec::new();
2030 buf.copy_to_vec_interleaved::<f32>(&mut out);
2031 assert_eq!(out.len(), SAMPLES_PER_PACKET as usize * channels);
2032 assert!(
2033 out.iter().all(|&s| s == 0.0),
2034 "{chan_conf} ch is not silent"
2035 );
2036 }
2037 assert!(
2038 silent_packet(6).is_err(),
2039 "beyond stereo is refused, not faked"
2040 );
2041 }
2042}