forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

audio.rs3059 lines, 134.6 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, as does the AAC track of a **Matroska** file:
10//! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to
11//! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same
12//! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the
13//! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo
14//! timeline. Everything downstream of [`Track`] sees the
15//! same samples either way; only the packet copy asks which reader it came from,
16//! because there is nothing to copy out of an mp3 that an mp4 can hold.
17//!
18//! One output, however many lanes: a timeline's audio lanes are decoded side by
19//! side and summed ([`AudioSession::open_mixed_streams`]), which is what both
20//! the device and an audio-only export are handed. One lane skips the mixer
21//! entirely and is the plain single-stream path it always was.
22//!
23//! Both readers are addressed as `(path, stream)`. An mp4 may carry several
24//! audio tracks and the caller picks one; a standalone audio file carries
25//! exactly one, so any stream above 0 there is an `Err` rather than a silent
26//! fallback to the only track it has.
27
28use std::fs::File;
29use std::io::BufReader;
30use std::path::{Path, PathBuf};
31use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
32use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
33use std::sync::{Arc, Mutex};
34use std::thread;
35
36use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};
37use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet};
38use symphonia_codec_aac::AacDecoder;
39use symphonia_core::codecs::audio::{
40 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,
41};
42use symphonia_core::formats::probe::Hint;
43// `TrackType` is the name both readers give their track kinds; the mp4 one is
44// imported above and used far more often here, so symphonia's is the one aliased.
45use symphonia_core::formats::{
46 FormatOptions, FormatReader, SeekMode, SeekTo, TrackType as SymKind,
47};
48use symphonia_core::io::MediaSourceStream;
49use symphonia_core::meta::MetadataOptions;
50use symphonia_core::packet::Packet;
51use symphonia_core::units;
52use symphonia_core::units::{Time, TimeBase};
53
54use crate::eq::{EqParams, EqState};
55use crate::limiter::{Limiter, LimiterState};
56
57/// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
58/// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
59const DEFAULT_PRIMING: u64 = 1024;
60
61/// An edit list entry that only shifts the timeline, carrying no media.
62const EMPTY_EDIT: u64 = u32::MAX as u64;
63
64/// Packets decoded and thrown away ahead of a seek target: one for the MDCT
65/// overlap-add that reconstructs the target packet, one to warm the decoder.
66const PRE_ROLL: u32 = 2;
67
68/// Frames per channel one AAC-LC packet carries. Fixed by the codec.
69const SAMPLES_PER_PACKET: u32 = 1024;
70
71/// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the
72/// 256-sample overlap-add the target frame is reconstructed with.
73const AC3_PRE_ROLL: u32 = 1;
74
75/// Frames per channel a seek into a standalone audio file lands ahead of the
76/// window, decoded and thrown away: enough to refill an mp3's bit reservoir
77/// (a frame is 1152 samples and the reservoir reaches back two of them) at any
78/// rate we accept.
79const SYM_PRE_ROLL: u64 = 8192;
80
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct AudioMeta {
83 pub sample_rate: u32,
84 pub channels: u16,
85 /// Frames per channel the container claims, priming subtracted. `None` when
86 /// the header does not say.
87 pub total_samples: Option<u64>,
88}
89
90/// One decoder output block, ready to hand to an output device.
91pub struct AudioChunk {
92 /// Position of the first frame, in samples-per-channel counted from the
93 /// first audible sample: priming is already dropped, so 0 is media time 0.
94 pub start_sample: u64,
95 /// Interleaved, `AudioMeta::channels` values per frame.
96 pub samples: Vec<f32>,
97}
98
99/// What a writer needs to declare an AAC track that plays copied packets: the
100/// esds fields verbatim from the source, no re-derivation.
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub struct AacTrackParams {
103 pub freq_index: u8,
104 pub chan_conf: u8,
105 pub sample_rate: u32,
106}
107
108/// One raw AAC access unit exactly as it sits in the source `mdat` — no ADTS
109/// header, which is the form an `mp4a` sample table wants.
110pub struct AacPacket {
111 pub bytes: Vec<u8>,
112 /// Frames per channel it decodes to, for the writer's stts.
113 pub samples: u32,
114}
115
116/// Everything an import check needs from a candidate file's audio track. Two
117/// files may share a timeline only when their probes are equal (or both `None`).
118///
119/// Rate and layout only: those are what one output device and one exported track
120/// can carry, and an mp3 that agrees on both may join a timeline of mp4s even
121/// though nothing about it can be *copied* into an export -- that is a separate
122/// refusal, at export time, in [`AudioSession::copy_multi_segments`].
123#[derive(Debug, Clone, Copy, PartialEq)]
124pub struct AudioProbe {
125 pub sample_rate: u32,
126 pub channels: u16,
127}
128
129/// One audio stream of a file as its header describes it. Every audio track is
130/// described, decodable or not: a picker shows the ones we refuse greyed out
131/// rather than pretending a BluRay remux has fewer streams than it has.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct StreamInfo {
134 /// Position among this file's audio tracks in file order — the `stream`
135 /// [`AudioSession::open_multi_streams`] takes.
136 pub index: usize,
137 /// Container codec.
138 ///
139 /// ponytail: mp4 0.14 parses `mp4a` sample entries and silently drops every
140 /// other kind (`stsd.rs` `_ => {}`), keeping no fourcc, so an AC-3/DTS/PCM
141 /// stream can only be `"unknown"` here — enough to grey a row out, not
142 /// enough to name the codec. Upgrade path is reading the sample entry's
143 /// fourcc out of the file ourselves.
144 pub codec: String,
145 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
146 pub channels: u16,
147 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
148 pub sample_rate: u32,
149 /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write.
150 pub lang: Option<String>,
151 /// Whether opening this stream would decode: AAC-LC, mono or stereo. The
152 /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels`
153 /// make one file at a time.
154 pub decodable: bool,
155}
156
157/// The mix settings a *running* mixer reads: what each lane is turned by on its
158/// way into the sum and the ceiling the sum comes out through, both swappable
159/// while the stream plays.
160///
161/// This is what keeps a fader off the reseek path. Everything else a timeline
162/// says lives inside a decode worker -- a segment's window, its curve, its rate
163/// -- and can only be changed by rebuilding it, which is a flush, a re-open and
164/// a hole in the sound. These two live at the sum, where nothing is decoded, so
165/// the mixer can pick them up between one block and the next: an arrow key held
166/// down on a fader moves the level and nothing else moves at all.
167///
168/// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live)
169/// is what says whether a mixer is actually reading it -- a single lane at
170/// unity with the limiter off is not mixed at all
171/// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this
172/// dead has to reopen the stream to be heard.
173pub struct MixControls {
174 /// Bumped by every change; the mixer reloads when the number it last saw
175 /// is not this one, so an unchanged mix costs one relaxed load per block.
176 version: AtomicU64,
177 /// The lane amplitudes and the limiter, together: they are set together and
178 /// a mixer that read half of one change and half of the next would be
179 /// mixing a state nobody asked for.
180 state: Mutex<(Vec<f32>, Limiter)>,
181 /// A mixer thread has these; see the type docs.
182 live: AtomicBool,
183}
184
185impl MixControls {
186 pub fn new(gains: Vec<f32>, limiter: Limiter) -> Arc<Self> {
187 Arc::new(Self {
188 version: AtomicU64::new(0),
189 state: Mutex::new((gains, limiter)),
190 live: AtomicBool::new(false),
191 })
192 }
193
194 /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock
195 /// held for a `Vec` swap and an atomic.
196 pub fn set(&self, gains: Vec<f32>, limiter: Limiter) {
197 *self.state.lock().unwrap() = (gains, limiter);
198 self.version.fetch_add(1, Ordering::Release);
199 }
200
201 /// Whether a mixer thread is reading this at all.
202 pub fn is_live(&self) -> bool {
203 self.live.load(Ordering::Acquire)
204 }
205
206 /// The mix, if it has moved since `seen`. `None` -- the every-block case --
207 /// takes no lock.
208 fn changed(&self, seen: &mut u64) -> Option<(Vec<f32>, Limiter)> {
209 let now = self.version.load(Ordering::Acquire);
210 if now == *seen {
211 return None;
212 }
213 *seen = now;
214 Some(self.state.lock().unwrap().clone())
215 }
216}
217
218pub struct AudioSession;
219
220impl AudioSession {
221 /// Opens the audio track of `path`. `Ok(None)` means the file simply has no
222 /// audio, which is a valid session; `Err` is a real failure.
223 pub fn open(
224 path: impl AsRef<Path>,
225 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
226 Self::open_at(path, 0.0)
227 }
228
229 /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on
230 /// the audible timeline; `start_sample` stays absolute from audible zero, so
231 /// the output is the tail of a full run. Past the end yields no chunks.
232 pub fn open_at(
233 path: impl AsRef<Path>,
234 start_secs: f64,
235 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
236 Self::open_segments(path, &[(start_secs, f64::INFINITY)])
237 }
238
239 /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds —
240 /// back to back as one continuous stream: the chunks carry no gap at a join,
241 /// so pouring them into a ring is seamless. Each segment gets a fresh
242 /// decoder and its own pre-roll, which makes a seeked segment perceptually
243 /// but not bit-exactly equal to the same window of a full run (perceptual
244 /// noise substitution reseeds; measured below 1e-3).
245 ///
246 /// `start_sample` counts from the *first* segment's own audible start, so a
247 /// single segment reads as absolute media time (what [`open_at`](Self::open_at)
248 /// promises) and a list reads as one timeline. Segment ends past the track
249 /// are capped; an empty list is a valid session with no chunks.
250 pub fn open_segments(
251 path: impl AsRef<Path>,
252 segs: &[(f64, f64)],
253 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
254 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
255 Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs)
256 }
257
258 /// [`open_segments`](Self::open_segments) over several files: a segment names
259 /// its source by index into `sources`, and a source join behaves exactly like
260 /// a cut inside one file — `start_sample` stays continuous, the decoder is
261 /// fresh either way. Each source contributes *its own* priming, packet table
262 /// and length, which is the whole reason the resolution is per source.
263 ///
264 /// A segment naming **no** source is a *gap*: that many seconds of silence
265 /// are synthesised into the stream as ordinary chunks. Real chunks, not a
266 /// pause — the master clock counts what the device has been fed, so a hole
267 /// that fed nothing would stall the whole timeline on it.
268 ///
269 /// A segment naming a source that has **no track** is the same silence: a
270 /// clip of a silent file is a hole with a picture over it, and the timeline
271 /// let it in on exactly that footing ([`crate::PlaybackSession::import`]).
272 ///
273 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
274 /// is empty or its first entry has no AAC track; a later source that
275 /// disagrees on rate/layout is an `Err` — import refuses those up front (one
276 /// timeline, one output device), this is the backstop.
277 pub fn open_multi_segments(
278 sources: &[PathBuf],
279 segs: &[(Option<usize>, f64, f64)],
280 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
281 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
282 Self::open_multi_streams(&sources, segs)
283 }
284
285 /// [`open_multi_segments`](Self::open_multi_segments) with each source
286 /// naming *which* of its audio streams to decode — files carrying several
287 /// (a remux with one track per language) are otherwise stuck on their first.
288 /// The index counts audio tracks in file order, as
289 /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not
290 /// exist or does not decode is an `Err` here, never a panic.
291 pub fn open_multi_streams(
292 sources: &[(PathBuf, usize)],
293 segs: &[(Option<usize>, f64, f64)],
294 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
295 Self::open_multi_streams_eq(sources, segs, &[])
296 }
297
298 /// [`open_multi_streams`](Self::open_multi_streams) with an equalizer per
299 /// segment: `eqs[i]` is what segment `i` plays through, `None` for one that
300 /// plays flat. Filtering happens **per segment**, inside the worker, before
301 /// anything is mixed -- two clips with different curves must not be blurred
302 /// into one another, and a segment's filter memory starts clean and dies
303 /// with it, which is also what makes a seek a reset for free.
304 ///
305 /// A parallel list, not a fourth tuple element: see
306 /// [`crate::Project::audio_eqs_from`], which is what builds it. A list
307 /// shorter than `segs` (the empty one every plain caller passes) means the
308 /// rest play flat, so a mismatch cannot panic and cannot silently shift a
309 /// curve onto the wrong clip.
310 pub fn open_multi_streams_eq(
311 sources: &[(PathBuf, usize)],
312 segs: &[(Option<usize>, f64, f64)],
313 eqs: &[Option<EqParams>],
314 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
315 Self::open_multi_streams_speed(sources, segs, eqs, &[])
316 }
317
318 /// [`open_multi_streams_eq`](Self::open_multi_streams_eq) with a *rate* per
319 /// segment as well: `speeds[i]` says how fast segment `i` is read and how
320 /// much timeline it owes ([`crate::project::Stretch`]), `None` for one at
321 /// real time. [`crate::Project::audio_speeds_from`] is what builds it, beside
322 /// the very list the segments come from.
323 ///
324 /// Resampling happens **per segment**, inside the worker and before the mix,
325 /// for the equalizer's reasons: two clips at two speeds must not be read
326 /// into one another, and the interpolator's memory dies with the segment. A
327 /// list shorter than `segs` (the empty one every plain caller passes) means
328 /// the rest play at real time, so nothing here can shift a rate onto the
329 /// wrong clip and a project with no speeds decodes exactly the samples it
330 /// always did.
331 pub fn open_multi_streams_speed(
332 sources: &[(PathBuf, usize)],
333 segs: &[(Option<usize>, f64, f64)],
334 eqs: &[Option<EqParams>],
335 speeds: &[Option<crate::project::Stretch>],
336 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
337 // The first source that could have a track, which is not always index 0:
338 // a still image has none, and one at the front of the list (a save
339 // renumbers, a library removal moves indexes) would be opened as a
340 // broken audio file and take the whole timeline's sound down with it.
341 // The same rule `PlaybackSession` probes by (`audio_source_of`).
342 let Some((at, (path, stream))) = sources
343 .iter()
344 .enumerate()
345 .find(|(_, (path, _))| !crate::is_image(path))
346 else {
347 return Ok(None);
348 };
349 let Some(first) = Track::open(path, *stream)? else {
350 return Ok(None);
351 };
352 // The timeline's meta is that source's: policy makes every other source
353 // match it, and the checks below hold them to that.
354 let meta = AudioMeta {
355 sample_rate: first.sample_rate(),
356 channels: first.channels()?,
357 total_samples: first.total_samples(),
358 };
359 // Built here only so an undecodable stream is an `Err` from the opener
360 // rather than a silently empty channel; the worker makes its own.
361 first.check_decoder()?;
362
363 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
364 // ...and which of them turned out to have no track at all, so a silent
365 // source is opened once like any other rather than once per segment
366 // naming it.
367 let mut silent: Vec<bool> = sources.iter().map(|_| false).collect();
368 tracks[at] = Some(first);
369 for &(source, ..) in segs {
370 let Some(source) = source else {
371 continue; // a gap opens no file
372 };
373 if silent.get(source) == Some(&true) {
374 continue;
375 }
376 let slot = tracks
377 .get_mut(source)
378 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
379 if slot.is_some() {
380 continue; // already opened, and the checks below already ran
381 }
382 let (path, stream) = &sources[source];
383 // A source with no audio track at all is not a failure: its
384 // segments are silence, exactly as a gap's are, and the slot stays
385 // empty to say so. That is what a silent clip on an audio lane
386 // means -- a picture over a hole.
387 let Some(track) = Track::open(path, *stream)? else {
388 silent[source] = true;
389 continue;
390 };
391 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {
392 return Err(format!(
393 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
394 track.sample_rate(),
395 track.channels()?,
396 meta.sample_rate,
397 meta.channels
398 )
399 .into());
400 }
401 track.check_decoder()?;
402 *slot = Some(track);
403 }
404
405 let segments: Vec<Segment> = segs
406 .iter()
407 // A gap, and a source with no track to decode, are the same stretch
408 // of nothing: as many frames of silence as the window is long.
409 .map(|&(source, start_secs, end_secs)| {
410 match source.and_then(|source| Some((source, tracks[source].as_ref()?))) {
411 Some((source, track)) => track.segment(source, start_secs, end_secs),
412 None => Segment::silence(
413 ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
414 ),
415 }
416 })
417 .collect();
418 // Chunk numbering is continuous across every join, counted from the first
419 // segment's audible start in its own source (see `open_segments`).
420 let timeline = segments.first().map_or(0, |s| match s.source {
421 Some(source) => s
422 .media_target
423 .saturating_sub(tracks[source].as_ref().expect("opened above").priming()),
424 None => 0,
425 });
426
427 // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so
428 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
429 // without making a pause take a second to bite.
430 // One filter per segment, built here where the rate and the layout are
431 // known and off the thread that will run it. An identity curve costs a
432 // branch and nothing else ([`EqState::process`]), and a segment with no
433 // curve at all is not even that.
434 let eqs: Vec<Option<EqState>> = segments
435 .iter()
436 .enumerate()
437 .map(|(i, _)| {
438 eqs.get(i)
439 .and_then(Option::as_ref)
440 .map(|p| EqState::new(p, meta.sample_rate, meta.channels))
441 })
442 .collect();
443
444 // One resampler per speeded segment, built where the sample rate is
445 // known: what the timeline owes it is seconds there and frames here.
446 let speeds: Vec<Option<Resample>> = segments
447 .iter()
448 .enumerate()
449 .map(|(i, _)| {
450 speeds.get(i).and_then(Option::as_ref).map(|s| {
451 Resample::new(
452 s.step,
453 (s.timeline_secs * f64::from(meta.sample_rate))
454 .round()
455 .max(0.) as u64,
456 )
457 })
458 })
459 .collect();
460
461 let (tx, rx) = sync_channel(32);
462 thread::Builder::new()
463 .name("audio-decode".into())
464 .spawn(move || {
465 run(Worker {
466 tracks,
467 channels: meta.channels as usize,
468 segments,
469 eqs,
470 speeds,
471 timeline,
472 tx,
473 })
474 })?;
475 Ok(Some((meta, rx)))
476 }
477
478 /// Every audio lane of a timeline, summed into one stream: `lanes` is one
479 /// play list per lane, each in the shape
480 /// [`open_multi_streams`](Self::open_multi_streams) takes, and what comes
481 /// out is what the device hears -- the lanes decoded side by side and added
482 /// sample for sample, clamped to `[-1, 1]` so a loud pair cannot wrap the
483 /// output.
484 ///
485 /// **One lane is not mixed at all**: it is `open_multi_streams` verbatim, so
486 /// a timeline with a single audio lane decodes exactly the samples it always
487 /// did, down to the bit and down to the thread count.
488 ///
489 /// Lengths need not agree: a lane that has run out contributes silence to
490 /// what is left, which is what a shorter lane means. Each lane keeps its own
491 /// gap rule -- a hole in it is real silence from its own worker, not a
492 /// skipped chunk -- so the sum feeds the master clock a sample per sample of
493 /// timeline however the lanes are arranged. `start_sample` numbers from the
494 /// first lane's own start (see [`AudioChunk`]).
495 pub fn open_mixed_streams(
496 sources: &[(PathBuf, usize)],
497 lanes: &[Vec<(Option<usize>, f64, f64)>],
498 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
499 Self::open_mixed_streams_eq(sources, lanes, &[])
500 }
501
502 /// [`open_mixed_streams`](Self::open_mixed_streams) with
503 /// [`open_multi_streams_eq`](Self::open_multi_streams_eq)'s per-segment
504 /// equalizers, one list per lane -- [`crate::Project::audio_eqs_from`] is
505 /// what shapes them.
506 ///
507 /// Filtering is each lane's worker's own business and therefore happens
508 /// **before** the sum: a clip's curve reaches that clip's samples and stops
509 /// there, where filtering the mix would smear every lane's curve over
510 /// everything playing at the same instant. A missing or short list plays
511 /// flat, as it does one lane down.
512 pub fn open_mixed_streams_eq(
513 sources: &[(PathBuf, usize)],
514 lanes: &[Vec<(Option<usize>, f64, f64)>],
515 eqs: &[Vec<Option<EqParams>>],
516 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
517 Self::open_mixed_streams_speed(sources, lanes, eqs, &[])
518 }
519
520 /// [`open_mixed_streams_eq`](Self::open_mixed_streams_eq) with
521 /// [`open_multi_streams_speed`](Self::open_multi_streams_speed)'s per-segment
522 /// rates, one list per lane -- [`crate::Project::audio_speeds_from`] is what
523 /// shapes them, off the same walk the segments come from.
524 ///
525 /// A resample is each lane's worker's own business and happens **before**
526 /// the sum, exactly as the filtering does: every lane still hands the mixer
527 /// as many samples as the timeline says, so the lanes stay sample-aligned by
528 /// construction and a mix is still an add.
529 pub fn open_mixed_streams_speed(
530 sources: &[(PathBuf, usize)],
531 lanes: &[Vec<(Option<usize>, f64, f64)>],
532 eqs: &[Vec<Option<EqParams>>],
533 speeds: &[Vec<Option<crate::project::Stretch>>],
534 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
535 Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default())
536 }
537
538 /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two
539 /// settings that belong to the *mix* rather than to a clip: what each lane
540 /// is turned up or down by on its way into the sum (`gains[i]`, an
541 /// amplitude, [`crate::Project::audio_gains`] builds it) and the master
542 /// limiter the sum comes out through.
543 ///
544 /// Both live at the sum and nowhere else, which is what makes a lane volume
545 /// a *lane* volume and a limiter a master one: a gain applied per segment
546 /// would have to agree with itself across a lane's cuts, and a limiter
547 /// applied per lane would pump each lane against the others. A short or
548 /// empty gain list means the rest play as they are, exactly as a short eq
549 /// list means flat.
550 ///
551 /// Flat settings take the same path the mixer always took, down to the bit:
552 /// one lane at unity with the limiter off is still `open_multi_streams`
553 /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or
554 /// a limiter that is on, is what puts a single-lane timeline through the
555 /// mixer -- a sum of one, which is where both settings live.
556 pub fn open_mixed_streams_master(
557 sources: &[(PathBuf, usize)],
558 lanes: &[Vec<(Option<usize>, f64, f64)>],
559 eqs: &[Vec<Option<EqParams>>],
560 speeds: &[Vec<Option<crate::project::Stretch>>],
561 gains: &[f32],
562 limiter: Limiter,
563 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
564 Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None)
565 }
566
567 /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the
568 /// mix left *reachable*: `live` is the handle the mixer picks its gains and
569 /// its limiter off between blocks, so a fader moved while the stream plays
570 /// is heard without the stream being rebuilt ([`MixControls`]).
571 ///
572 /// `gains`/`limiter` still say what it starts as -- they are what decides
573 /// whether there is a mixer at all -- and the handle is marked live only
574 /// when there is one. An export passes `None`: nothing can move under it.
575 pub fn open_mixed_streams_live(
576 sources: &[(PathBuf, usize)],
577 lanes: &[Vec<(Option<usize>, f64, f64)>],
578 eqs: &[Vec<Option<EqParams>>],
579 speeds: &[Vec<Option<crate::project::Stretch>>],
580 gains: &[f32],
581 limiter: Limiter,
582 live: Option<&Arc<MixControls>>,
583 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
584 let [first, rest @ ..] = lanes else {
585 return Ok(None);
586 };
587 let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0);
588 if rest.is_empty() && !mastered {
589 let flat = Vec::new();
590 let plain = Vec::new();
591 return Self::open_multi_streams_speed(
592 sources,
593 first,
594 eqs.first().unwrap_or(&flat),
595 speeds.first().unwrap_or(&plain),
596 );
597 }
598 let mut meta = None;
599 let mut rxs = Vec::with_capacity(lanes.len());
600 for (i, segs) in lanes.iter().enumerate() {
601 // Every lane takes its meta from the same source, so the metas
602 // agree by construction; `None` from any of them is a silent
603 // timeline.
604 let flat = Vec::new();
605 let plain = Vec::new();
606 let Some((lane_meta, rx)) = Self::open_multi_streams_speed(
607 sources,
608 segs,
609 eqs.get(i).unwrap_or(&flat),
610 speeds.get(i).unwrap_or(&plain),
611 )?
612 else {
613 return Ok(None);
614 };
615 meta = Some(lane_meta);
616 rxs.push(rx);
617 }
618 let meta = meta.expect("at least one lane opened above");
619 let (tx, rx) = sync_channel(32);
620 let channels = usize::from(meta.channels);
621 // One per lane, in the lanes' own order, padded with unity: a short
622 // list is "as it is from here on", the eq list's rule.
623 let mut gains = gains.to_vec();
624 gains.resize(lanes.len(), 1.0);
625 // Built here, off the thread that will run it, where the rate is known.
626 let state = limiter
627 .is_active()
628 .then(|| LimiterState::new(&limiter, meta.sample_rate, channels));
629 // Marked before the spawn rather than inside it: a caller asks this the
630 // moment the open returns, and a flag set on the far thread would still
631 // read dead.
632 let live = live.map(|live| {
633 live.live.store(true, Ordering::Release);
634 live.clone()
635 });
636 let rate = meta.sample_rate;
637 thread::Builder::new()
638 .name("audio-mix".into())
639 .spawn(move || mix(&rxs, channels, gains, state, rate, live.as_deref(), &tx))?;
640 Ok(Some((meta, rx)))
641 }
642
643 /// Why [`open`](Self::open) came back silent for a file that *has* sound:
644 /// `Some(reason)` when there is an audio track and it is not the AAC-LC
645 /// this decodes (an AC-3 remux, say). `None` when the file is simply silent
646 /// -- nothing to tell the user there. Header only, and only worth calling
647 /// once the open has already returned no audio.
648 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
649 // Matroska: what symphonia reads out of one ([`Track::open`]) plus the
650 // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder
651 // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here
652 // has at any version -- is named rather than left playing silent with no
653 // reason given. A Matroska file with no audio track at all returns
654 // `None` here like any other silent file.
655 if crate::demux::is_matroska(path.as_ref()) {
656 let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else {
657 return Ok(None);
658 };
659 // An AC-3 track that came up silent all the same is one that could
660 // not be read -- a laced block, an unreadable syncframe -- and the
661 // reader's own words are the ones worth showing.
662 return Ok(Some(match MkvAc3Track::open(path.as_ref()) {
663 Ok(Some(_)) => return Ok(None),
664 Ok(None) => format!(
665 "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)"
666 ),
667 Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"),
668 }));
669 }
670 let file = File::open(path.as_ref())?;
671 let size = file.metadata()?.len();
672 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
673 Ok(reader
674 .tracks()
675 .values()
676 .find(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
677 .map(|t| match t.media_type() {
678 Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"),
679 Err(_) => {
680 "the audio track is in a codec we cannot decode (AAC-LC only)".to_string()
681 }
682 }))
683 }
684
685 /// The audio parameters of `path`'s `stream`, for checking an import
686 /// against the timeline's first source: header only, no decoder and no
687 /// worker. `Ok(None)` means no audio track — a silent file, which import
688 /// pairs only with other silent files. A *named* stream that is not there
689 /// or does not decode is an `Err`, as everywhere else.
690 pub fn probe(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<AudioProbe>> {
691 let Some(track) = Track::open(path.as_ref(), stream)? else {
692 return Ok(None);
693 };
694 Ok(Some(AudioProbe {
695 sample_rate: track.sample_rate(),
696 channels: track.channels()?,
697 }))
698 }
699
700 /// Every audio stream of `path`, in file order: an entry's `index` is the
701 /// stream number [`open_multi_streams`](Self::open_multi_streams) takes.
702 /// Header only, no decoder and no worker — and no filtering either, so a
703 /// stream this engine cannot decode is listed with `decodable: false`
704 /// instead of vanishing.
705 ///
706 /// An empty list means the file has no audio at all, which is a valid
707 /// silent source.
708 ///
709 /// A standalone audio file ([`crate::is_audio`]) has exactly one stream by
710 /// construction — one track, no picture beside it — so it is described from
711 /// symphonia's own header rather than walked as an mp4, which an mp3 is not
712 /// and an ALAC `.m4a` only half is.
713 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
714 let path = path.as_ref();
715 // A Matroska file lists one row per `TrackEntry` of audio -- a
716 // dual-audio remux has two, and the second one used to be invisible --
717 // numbered by [`mkv_stream_order`]: the track that already plays first,
718 // then the rest in file order. A file whose header will not walk at all
719 // is an `Err` here, as it is in [`Track::open`]: a listing that quietly
720 // came back empty for a broken file is how a lane ends up silent with
721 // nothing to go on. No audio track at all is an empty list, which is
722 // the silent source it says it is.
723 if crate::demux::is_matroska(path) {
724 let tracks = crate::demux::matroska_audio_tracks(path)?;
725 let mut streams = Vec::new();
726 for (index, entry) in mkv_stream_order(path, &tracks)
727 .into_iter()
728 .map(|at| &tracks[at])
729 .enumerate()
730 {
731 // The routing [`Track::open`] does, one row at a time, so a row
732 // describes the track that would really open: AC-3 and E-AC-3
733 // through the Dolby decoder's own reader, everything else
734 // through symphonia. The AC-3 row describes what the decoder
735 // *emits*, which is the stereo the §7.8 downmix hands the
736 // timeline, not the 5.1 the file carries -- exactly as the mp4
737 // AC-3 rows do.
738 let ac3 = matches!(entry.codec.as_str(), "A_AC3" | "A_EAC3")
739 .then(|| MkvAc3Track::open_track(path, entry.number).ok().flatten())
740 .flatten();
741 // A track symphonia cannot even describe is listed undecodable
742 // by the name the container gives it, rather than taking the
743 // whole listing down with it: the other language still plays.
744 let sym = match &ac3 {
745 Some(_) => None,
746 None => SymTrack::open_track(path, entry.number).ok().flatten(),
747 };
748 let channels = ac3.as_ref().map_or_else(
749 || sym.as_ref().map_or(0, |t| t.channels),
750 |t| t.channels,
751 );
752 streams.push(StreamInfo {
753 index,
754 codec: mkv_codec_name(&entry.codec),
755 channels,
756 sample_rate: ac3.as_ref().map_or_else(
757 || sym.as_ref().map_or(0, |t| t.sample_rate),
758 |t| t.sample_rate,
759 ),
760 lang: (entry.language != "und" && !entry.language.is_empty())
761 .then(|| entry.language.clone()),
762 decodable: matches!(channels, 1 | 2)
763 && (ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok())),
764 });
765 }
766 return Ok(streams);
767 }
768 if crate::is_audio(path) {
769 let track = SymTrack::open_required(path)?;
770 return Ok(vec![StreamInfo {
771 index: 0,
772 codec: track.codec.into(),
773 channels: track.channels,
774 sample_rate: track.sample_rate,
775 // Neither the mp3 nor the wav headers carry an ISO-639 tag the
776 // way an mdhd does, and a lone track needs no telling apart.
777 lang: None,
778 decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(),
779 }]);
780 }
781 let file = File::open(path)?;
782 let size = file.metadata()?.len();
783 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
784 Ok(audio_track_ids(&reader)
785 .into_iter()
786 .enumerate()
787 .map(|(index, id)| {
788 let track = &reader.tracks()[&id];
789 let aac = matches!(track.media_type(), Ok(MediaType::AAC));
790 // An AC-3 track describes itself through its own reader: mp4
791 // 0.14 parses no sample entry for it, so `channel_config` and
792 // `sample_freq_index` have nothing to say. What is listed is
793 // the *decoded* shape -- stereo, because that is what the §7.8
794 // downmix hands the timeline (see [`Ac3Track`]).
795 let ac3 = (!aac)
796 .then(|| Ac3Track::open(path, index).ok().flatten())
797 .flatten();
798 let lang = track.language();
799 StreamInfo {
800 index,
801 codec: match (aac, &ac3) {
802 (true, _) => "aac",
803 (_, Some(_)) => "ac-3",
804 _ => "unknown",
805 }
806 .into(),
807 channels: ac3
808 .as_ref()
809 .map_or_else(|| track.channel_config().map_or(0, channel_count), |t| {
810 t.channels
811 }),
812 sample_rate: ac3.as_ref().map_or_else(
813 || track.sample_freq_index().map_or(0, |f| f.freq()),
814 |t| t.sample_rate,
815 ),
816 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),
817 decodable: ac3.as_ref().is_some_and(|t| matches!(t.channels, 1 | 2))
818 || aac
819 && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity))
820 && matches!(
821 track.channel_config(),
822 Ok(ChannelConfig::Mono | ChannelConfig::Stereo)
823 ),
824 }
825 })
826 .collect())
827 }
828
829 /// How long `path`'s audio plays, in seconds. `Ok(None)` for a silent file.
830 ///
831 /// A standalone audio file is a source with no frame count of its own, so
832 /// this is what its length on the timeline is derived from. Taken from the
833 /// header where there is one; a stream that does not say — a bare mp3 with
834 /// no Xing header is the usual one — is *decoded* to find out, which is
835 /// linear in its length (~0.5 ms per source second) and happens once, at
836 /// import, rather than per repaint.
837 ///
838 /// Stream 0: this answers for a standalone audio file, whose only stream
839 /// that is. A video source's length is its frame count, never this.
840 pub fn duration_secs(path: impl AsRef<Path>) -> crate::Result<Option<f64>> {
841 let path = path.as_ref();
842 let Some(track) = Track::open(path, 0)? else {
843 return Ok(None);
844 };
845 let rate = f64::from(track.sample_rate().max(1));
846 if let Some(total) = track.total_samples() {
847 return Ok(Some(total as f64 / rate));
848 }
849 drop(track);
850 let Some((meta, rx)) = Self::open(path)? else {
851 return Ok(None);
852 };
853 let channels = usize::from(meta.channels.max(1));
854 let last = rx.into_iter().fold(0, |_, chunk| {
855 chunk.start_sample + (chunk.samples.len() / channels) as u64
856 });
857 Ok(Some(last as f64 / f64::from(meta.sample_rate.max(1))))
858 }
859
860 /// The raw AAC packets covering `segs` — the same half-open source-second
861 /// windows [`open_segments`](Self::open_segments) decodes — copied out
862 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
863 /// straight into an mp4 writer, which is how an export keeps its sound exact
864 /// wherever the edit lets it (a lane carrying an equalizer cannot be copied
865 /// and is re-encoded instead -- `export::encode_audio`).
866 ///
867 /// Cut points do not land on 1024-sample boundaries, so each segment is
868 /// rounded to whole packets against an error carried across the joins (see
869 /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the
870 /// asked-for length however many cuts there are, instead of drifting out of
871 /// lip sync one rounding at a time.
872 ///
873 /// The run starts one packet before the first audible one, which a reader
874 /// drops as encoder priming — for a segment list starting at 0.0 that is the
875 /// source's own priming packet, so the copy is the whole track from sample 1.
876 ///
877 /// `Ok(None)` for a file with no AAC track, and for an empty segment list.
878 ///
879 /// ponytail: the first packet after an *interior* join decodes without its
880 /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is
881 /// re-encoding just the join packets, which needs an encoder we do not have.
882 pub fn copy_segments(
883 path: impl AsRef<Path>,
884 segs: &[(f64, f64)],
885 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
886 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
887 Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs)
888 }
889
890 /// [`copy_segments`](Self::copy_segments) over several files, segments naming
891 /// their source by index into `sources`. The rounding debt is carried across
892 /// a source join exactly as across a cut inside one file, so the bound stays
893 /// half a packet over the whole list however many files it spans, and the
894 /// extra priming packet is still the very first segment's alone.
895 ///
896 /// Every source that *has* a track must declare the same
897 /// [`AacTrackParams`]: the copy becomes one output track with one esds.
898 /// Import refuses a mismatch up front; the check here is the backstop.
899 ///
900 /// A segment naming **no** source is a gap, and is copied as that many
901 /// packets of [`silent_packet`] silence — the rounding debt carried through
902 /// it like any other, so the hole occupies its exact duration and the audio
903 /// after it stays in sync with the picture. A gap the track *opens* on gets
904 /// one silent packet more, which is the priming a reader drops. A segment
905 /// naming a *silent* source is written the same way: a clip whose file has
906 /// no audio track is a hole with a picture over it, and the timeline it
907 /// joined already said so ([`crate::PlaybackSession::import`]).
908 pub fn copy_multi_segments(
909 sources: &[PathBuf],
910 segs: &[(Option<usize>, f64, f64)],
911 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
912 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
913 Self::copy_multi_streams(&sources, segs)
914 }
915
916 /// [`copy_multi_segments`](Self::copy_multi_segments) with each source
917 /// naming *which* of its audio streams to copy — the same `(path, stream)`
918 /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two
919 /// take it in the same shape on purpose: an export that copied a different
920 /// stream from the one the timeline played would be a file that sounds
921 /// nothing like what was edited, and nothing would say so.
922 pub fn copy_multi_streams(
923 sources: &[(PathBuf, usize)],
924 segs: &[(Option<usize>, f64, f64)],
925 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
926 // The output track is declared from the first source that has one --
927 // not simply the first one named, which may be a silent clip. Such a
928 // clip defines no rate and no layout; it is written as silence below
929 // and the track goes on being the audible sources' track.
930 let mut tracks: Vec<Option<Option<AacTrack>>> = sources.iter().map(|_| None).collect();
931 let mut first = None;
932 for &(source, ..) in segs {
933 let Some(source) = source else { continue };
934 if let Some(track) = source_at(&mut tracks, sources, source)? {
935 first = Some(track.track_params());
936 break;
937 }
938 }
939 let Some(params) = first else {
940 return Ok(None); // no segments, or nothing but silence
941 };
942
943 let sample_rate = params.sample_rate;
944 let mut err = 0i64;
945 let mut packets: Vec<AacPacket> = Vec::new();
946 for &(source, start_secs, end_secs) in segs {
947 // A gap, and a clip whose source carries no track, are the same hole
948 // to write: silence for as long as the window is.
949 let named = match source {
950 Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)),
951 None => None,
952 };
953 let Some((source, track)) = named else {
954 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
955 let bytes = silent_packet(params.chan_conf)?;
956 // A reader drops the first packet of an AAC track as the
957 // encoder's priming. When the track opens on a hole, that has to
958 // come out of one *extra* packet of silence: dropped out of the
959 // hole itself it would shorten it, and everything after the hole
960 // would play a packet early. It is not part of the run, so it
961 // owes the rounding debt nothing.
962 let priming = u32::from(packets.is_empty());
963 for _ in 0..packet_run(&mut err, ideal, u32::MAX) + priming {
964 packets.push(AacPacket {
965 bytes: bytes.clone(),
966 samples: SAMPLES_PER_PACKET,
967 });
968 }
969 continue;
970 };
971 if track.track_params() != params {
972 return Err(format!(
973 "source {source} audio is {:?}, the timeline's is {params:?}",
974 track.track_params()
975 )
976 .into());
977 }
978 let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale);
979 let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0);
980 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64;
981 let available = track.sample_count.saturating_sub(start_id - 1);
982 // The head packet is the priming of the first segment only: a reader
983 // drops exactly one, so an interior join must not add another --
984 // and neither must a segment behind a leading gap, which already
985 // paid the priming in silence.
986 let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1);
987 let ids = head
988 .into_iter()
989 .chain(start_id..start_id + packet_run(&mut err, ideal, available));
990 for id in ids {
991 let Some(sample) = track.reader.read_sample(track.track_id, id)? else {
992 let count = track.sample_count;
993 return Err(format!("audio sample {id} of {count} is missing").into());
994 };
995 packets.push(AacPacket {
996 bytes: sample.bytes.to_vec(),
997 samples: SAMPLES_PER_PACKET,
998 });
999 }
1000 }
1001 Ok(Some((params, packets)))
1002 }
1003}
1004
1005/// One AAC-LC access unit of silence, for the gaps in an exported timeline —
1006/// this is the *copy* path, which never encodes anything, so the only silence it
1007/// can write is one spelled out by hand. (The re-encode path next door has a
1008/// real encoder and needs none of this: its gaps are zero samples.)
1009///
1010/// It is the shortest legal `raw_data_block` there is: one element carrying
1011/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
1012/// spectral data at all and therefore 1024 samples of exact zero. Every field
1013/// is zero except the element id and the terminating `ID_END`, so the whole
1014/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the
1015/// unit tests, which is the only claim worth making about hand-written
1016/// bitstream.
1017///
1018/// ponytail: mono and stereo only, because `chan_conf` beyond 2 needs more
1019/// elements per block; the timeline refuses such a source at import today, so
1020/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements.
1021fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
1022 match chan_conf {
1023 // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned.
1024 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]),
1025 // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END.
1026 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]),
1027 n => Err(format!("cannot write silence for a {n}-channel AAC track").into()),
1028 }
1029}
1030
1031/// The source at `index`, on the stream it names, opened on first use -- and
1032/// `None` for a source that has no track at all, which the caller writes as
1033/// silence exactly as it writes a gap. The outer `Option` is "has it been
1034/// opened", the inner one "was there anything in it", so a silent source is
1035/// opened once like any other. Sources a segment list never names are never
1036/// touched: a project's list only grows.
1037fn source_at<'a>(
1038 tracks: &'a mut [Option<Option<AacTrack>>],
1039 sources: &[(PathBuf, usize)],
1040 index: usize,
1041) -> crate::Result<Option<&'a mut AacTrack>> {
1042 let slot = tracks
1043 .get_mut(index)
1044 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
1045 if slot.is_none() {
1046 let (path, stream) = &sources[index];
1047 *slot = Some(copy_track(path, *stream)?);
1048 }
1049 Ok(slot.as_mut().expect("just opened").as_mut())
1050}
1051
1052/// A source's track for the *copy* path, which needs raw AAC access units.
1053///
1054/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name
1055/// and by format. That is no longer the end of the road: `export::copy_audio`
1056/// takes it as the answer "not copyable" and decodes and re-encodes the timeline
1057/// instead, so these words are a fallback's reason rather than a user's refusal.
1058/// They are still worded for a person, because a caller with no encoder to fall
1059/// back on shows them verbatim.
1060///
1061/// `Ok(None)` for a file with no audio at all, which is a silent export.
1062fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
1063 match Track::open(path, stream)? {
1064 None => Ok(None),
1065 Some(Track::Aac(track)) => Ok(Some(track)),
1066 // A Matroska source gets its own words: its packets *are* AAC, so
1067 // "export needs AAC audio today" would read as a contradiction. What
1068 // they are not is packets of an mp4 sample table, which is what the
1069 // copy walks. The export decodes such a source and encodes it again
1070 // rather than showing this, so a film's sound reaches an mp4 either way;
1071 // the words stay for a caller that copies and cannot re-encode.
1072 //
1073 // ponytail: the ceiling is the copy path being written against the mp4
1074 // reader, not anything about the bytes. Upgrade path is a
1075 // `copy_segments` that walks a Matroska track, which would make this a
1076 // copy again instead of a re-encode.
1077 Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(
1078 "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \
1079 a copy walks an mp4's own sample table. It is decoded and encoded again \
1080 instead",
1081 path.file_name()
1082 .unwrap_or(path.as_os_str())
1083 .to_string_lossy(),
1084 )
1085 .into()),
1086 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
1087 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
1088 // sample table can hold. The export decodes it and encodes AAC, exactly
1089 // as it does for every other source no copy reaches.
1090 Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")),
1091 }
1092}
1093
1094/// The one wording for "this source's audio cannot be *copied* into an mp4",
1095/// shared by every format that cannot be. What the export does about it is
1096/// decode and re-encode; this is the reason it had to.
1097fn uncopyable(path: &Path, codec: &str) -> crate::Error {
1098 format!(
1099 "a packet copy needs AAC in an mp4; {} is {codec}",
1100 path.file_name()
1101 .unwrap_or(path.as_os_str())
1102 .to_string_lossy(),
1103 )
1104 .into()
1105}
1106
1107/// One source's audio, however it is stored: the mp4 AAC track the export can
1108/// copy, or a standalone file read through symphonia's probe. The opener and
1109/// the worker speak to this, never to either reader directly.
1110enum Track {
1111 Aac(AacTrack),
1112 Ac3(Ac3Track),
1113 /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an
1114 /// mp4's sample table.
1115 Mkv(MkvAc3Track),
1116 Sym(SymTrack),
1117}
1118
1119impl Track {
1120 /// `Ok(None)` for a file with no audio, which is a valid silent source.
1121 ///
1122 /// The mp4 reader goes first and its verdict is final for anything that is
1123 /// not [`crate::is_audio`]: a video file's audio track is exactly what it
1124 /// always was, silent mp4s included (an mp4 whose only `soun` track is one
1125 /// we cannot decode has always been a silent source, not an error). Only a
1126 /// standalone audio file falls through to symphonia — which is also how an
1127 /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track.
1128 ///
1129 /// `stream` counts audio tracks in file order, as
1130 /// [`AudioSession::probe_streams`] hands them out. A standalone audio file
1131 /// has exactly one, so any `stream` above 0 there is a promise the file
1132 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
1133 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1134 // A Matroska file goes to symphonia, whose `mkv` reader is the one thing
1135 // here that reads its packets -- neither mp4 reader can open the file at
1136 // all -- except for the two codecs symphonia has no decoder for at any
1137 // version and this project does: AC-3 and E-AC-3 are handed to the Dolby
1138 // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither
1139 // one can decode (Opus, DTS) leaves the source the silent one it always
1140 // was, which `AudioSession::unsupported` puts into words, rather than
1141 // failing the import of a file whose picture is fine. A track that will
1142 // not open at all is *not* in that group: see below.
1143 if crate::demux::is_matroska(path) {
1144 // The numbering `probe_streams` lists and a project saves, from the
1145 // one function that decides it ([`mkv_stream_order`]): the stream
1146 // index picks a `TrackEntry`, that entry's *track number* is what
1147 // both readers are then pointed at. Positions are never handed to a
1148 // reader -- symphonia's own order is its business -- because a
1149 // mapping that drifts plays the wrong language and saves it into
1150 // the project.
1151 let tracks = crate::demux::matroska_audio_tracks(path)?;
1152 if tracks.is_empty() {
1153 return Ok(None);
1154 }
1155 let order = mkv_stream_order(path, &tracks);
1156 let Some(entry) = order.get(stream).map(|at| &tracks[*at]) else {
1157 return Err(format!(
1158 "{}: audio stream {stream} of {} stream{}",
1159 path.display(),
1160 tracks.len(),
1161 if tracks.len() == 1 { "" } else { "s" }
1162 )
1163 .into());
1164 };
1165 match MkvAc3Track::open_track(path, entry.number) {
1166 Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1167 Ok(None) => {}
1168 // Named on the way past rather than returned: symphonia gets the
1169 // same file next and may read the track perfectly well (a laced
1170 // block is [`MkvAc3Track`]'s limitation, not the file's), and
1171 // if it cannot either, *its* `Err` is the one that comes back.
1172 Err(e) => eprintln!("matroska audio: {}: {e}", path.display()),
1173 }
1174 // Two things are silent here and no more: a file with no audio
1175 // track at all, and a track whose codec nothing in this project
1176 // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts
1177 // that into words). A track that will not *open* is an `Err`, the
1178 // same answer the mp4 arm gives: turned into silence it would play
1179 // and export as a hole with only an eprintln to say why, which is a
1180 // bug wearing a feature's clothes.
1181 let Some(track) = SymTrack::open_track(path, entry.number)? else {
1182 return Ok(None);
1183 };
1184 if let Err(e) = track.decoder() {
1185 eprintln!("matroska audio: {}: {e}", path.display());
1186 return Ok(None);
1187 }
1188 return Ok(Some(Self::Sym(track)));
1189 }
1190 let audio_file = crate::is_audio(path);
1191 // Ahead of the AAC reader, because that one answers "not AAC" for a
1192 // *named* stream with an `Err` and an AC-3 track is not an error any
1193 // more. `Ok(None)` here means "not an AC-3 track", so every other file
1194 // falls through to exactly the reader it always used.
1195 if !audio_file
1196 && let Some(track) = Ac3Track::open(path, stream)?
1197 {
1198 return Ok(Some(Self::Ac3(track)));
1199 }
1200 match AacTrack::open(path, stream) {
1201 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
1202 Ok(None) if !audio_file => return Ok(None),
1203 Err(e) if !audio_file => return Err(e),
1204 _ => {}
1205 }
1206 if stream > 0 {
1207 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
1208 }
1209 SymTrack::open_required(path).map(|track| Some(Self::Sym(track)))
1210 }
1211
1212 fn sample_rate(&self) -> u32 {
1213 match self {
1214 Self::Aac(t) => t.sample_rate,
1215 Self::Ac3(t) => t.sample_rate,
1216 Self::Mkv(t) => t.sample_rate,
1217 Self::Sym(t) => t.sample_rate,
1218 }
1219 }
1220
1221 /// Mono or stereo; anything wider is refused here rather than one packet at
1222 /// a time, because one output device and one copied track is all there is.
1223 fn channels(&self) -> crate::Result<u16> {
1224 match self {
1225 Self::Aac(t) => t.channels(),
1226 // Already downmixed: `channels` is what comes *out* of the decoder,
1227 // which is 2 for everything from mono to 5.1 (see [`Ac3Track`]).
1228 Self::Ac3(t) => match t.channels {
1229 1 | 2 => Ok(t.channels),
1230 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1231 },
1232 // Downmixed by the very same decoder, out of a Matroska file.
1233 Self::Mkv(t) => match t.channels {
1234 1 | 2 => Ok(t.channels),
1235 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1236 },
1237 Self::Sym(t) => match t.channels {
1238 1 | 2 => Ok(t.channels),
1239 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1240 },
1241 }
1242 }
1243
1244 /// Frames per channel of *audible* audio, priming already subtracted.
1245 fn total_samples(&self) -> Option<u64> {
1246 match self {
1247 Self::Aac(t) => t.total_samples,
1248 Self::Ac3(t) => t.total_samples,
1249 Self::Mkv(t) => t.total_samples,
1250 Self::Sym(t) => t.total_samples,
1251 }
1252 }
1253
1254 /// Encoder delay of this file. Sources are joined, priming is not shared.
1255 fn priming(&self) -> u64 {
1256 match self {
1257 Self::Aac(t) => t.priming,
1258 Self::Ac3(t) => t.priming,
1259 // Matroska writes no edit list and AC-3 has no encoder delay:
1260 // block 0 is sample 0.
1261 Self::Mkv(_) => 0,
1262 Self::Sym(t) => t.priming,
1263 }
1264 }
1265
1266 /// One `[start, end)` window of this source's seconds, resolved to whatever
1267 /// its own reader needs to find it again.
1268 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1269 match self {
1270 Self::Aac(t) => t.segment(source, start_secs, end_secs),
1271 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
1272 Self::Mkv(t) => t.segment(source, start_secs, end_secs),
1273 Self::Sym(t) => {
1274 let media_target = t.media(start_secs);
1275 Segment {
1276 source: Some(source),
1277 start_id: 0,
1278 start_pos: 0,
1279 media_target,
1280 media_end: t.media(end_secs).max(media_target),
1281 }
1282 }
1283 }
1284 }
1285
1286 /// Builds and throws away a decoder, so an undecodable stream is an `Err`
1287 /// from the opener rather than a silently empty channel.
1288 fn check_decoder(&self) -> crate::Result<()> {
1289 match self {
1290 Self::Aac(t) => {
1291 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
1292 }
1293 Self::Ac3(t) => {
1294 ac3_decoder("ac3", t.requested)?;
1295 }
1296 Self::Mkv(t) => {
1297 ac3_decoder(t.mkv.codec, t.requested)?;
1298 }
1299 Self::Sym(t) => {
1300 t.decoder()?;
1301 }
1302 }
1303 Ok(())
1304 }
1305}
1306
1307/// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read
1308/// through symphonia's own probe and codec registry. No packet table and no
1309/// sample ids: the reader is *seeked* per segment and the packets it then hands
1310/// out carry their own timestamps.
1311struct SymTrack {
1312 reader: Box<dyn FormatReader>,
1313 track_id: u32,
1314 sample_rate: u32,
1315 /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track,
1316 /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's
1317 /// decoder folds its own.
1318 channels: u16,
1319 /// What the decoder emits, which is what the fold reads.
1320 source_channels: u16,
1321 /// Frames per channel of audible audio, `None` when the header does not say.
1322 total_samples: Option<u64>,
1323 /// Encoder delay, and **always zero here**: symphonia 0.6 drops the leading
1324 /// frames itself, so a reader that skipped `Track::delay` on top would skip
1325 /// them twice. Kept as a field because [`Track::priming`] asks every track
1326 /// for one and the AAC and AC-3 readers beside it do owe a real number.
1327 ///
1328 /// This used to carry `delay` and cost the double skip on the two formats
1329 /// that declare one: a `.mp3` lost its first 1105 samples (25 ms) and read
1330 /// 25 ms short, an `.ogg` its first 128. Measured 2026-08-11 against
1331 /// `test_tone.flac` -- lossless, and the only one of the three whose
1332 /// container declares no delay at all -- which the mp3 and the ogg of the
1333 /// same tone align with sample for sample once this is not subtracted.
1334 priming: u64,
1335 time_base: TimeBase,
1336 params: AudioCodecParameters,
1337 /// The format's short name, for the export refusal. `&'static` because it
1338 /// comes out of the codec registry, which outlives everything here.
1339 codec: &'static str,
1340}
1341
1342impl SymTrack {
1343 /// `Ok(None)` for a container that opened and holds no audio track at all --
1344 /// a silent source, which is a thing a file is allowed to be. Everything
1345 /// else that goes wrong here is an `Err`: a file that will not open, will
1346 /// not parse, or carries a track it cannot describe is *broken*, and the
1347 /// difference matters because silence is played and exported without a word
1348 /// while an `Err` is shown ([`Track::open`]).
1349 fn open(path: &Path) -> crate::Result<Option<Self>> {
1350 Self::open_inner(path, None)
1351 }
1352
1353 /// [`open`](Self::open) pointed at one **named** track: a Matroska
1354 /// `TrackNumber`, which symphonia keeps as the track's id
1355 /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second
1356 /// language of a dual-audio file reachable, and it is matched by number
1357 /// rather than by position so this reader and
1358 /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which
1359 /// track a stream index meant. `Ok(None)` for a number the reader does not
1360 /// carry.
1361 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
1362 Self::open_inner(path, Some(number))
1363 }
1364
1365 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
1366 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
1367 // The extension is a hint, not a decision: the probe reads the magic and
1368 // is free to disagree, which is what makes a mislabelled file work.
1369 let mut hint = Hint::new();
1370 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
1371 hint.with_extension(ext);
1372 }
1373 let reader = symphonia::default::get_probe().probe(
1374 &hint,
1375 mss,
1376 FormatOptions::default(),
1377 MetadataOptions::default(),
1378 )?;
1379 let track = match number {
1380 Some(number) => reader
1381 .tracks()
1382 .iter()
1383 .find(|t| u64::from(t.id) == number),
1384 None => reader.default_track(SymKind::Audio),
1385 };
1386 let Some(track) = track else {
1387 return Ok(None);
1388 };
1389 // `track.delay` is deliberately not read: see the `priming` field.
1390 let (track_id, num_frames) = (track.id, track.num_frames);
1391 let time_base = track
1392 .time_base
1393 .ok_or_else(|| format!("{} declares no time base", path.display()))?;
1394 let Some(symphonia_core::codecs::CodecParameters::Audio(params)) =
1395 track.codec_params.clone()
1396 else {
1397 return Err(format!("{} declares no audio codec", path.display()).into());
1398 };
1399 let sample_rate = params
1400 .sample_rate
1401 .ok_or_else(|| format!("{} declares no sample rate", path.display()))?;
1402 let channels = params
1403 .channels
1404 .as_ref()
1405 .map(|c| c.count() as u16)
1406 .ok_or_else(|| format!("{} declares no channel layout", path.display()))?;
1407 let codec = symphonia::default::get_codecs()
1408 .get_audio_decoder(params.codec)
1409 .map_or("an unsupported format", |d| d.codec.info.short_name);
1410 Ok(Some(Self {
1411 reader,
1412 track_id,
1413 sample_rate,
1414 // 5.1 arrives as a stereo source, whatever it was stored as; every
1415 // other layout is passed through and refused above stereo by
1416 // [`Track::channels`], where it always was.
1417 channels: if channels == 6 { 2 } else { channels },
1418 source_channels: channels,
1419 total_samples: num_frames,
1420 priming: 0,
1421 time_base,
1422 params,
1423 codec,
1424 }))
1425 }
1426
1427 /// [`open`](Self::open) where having no audio track is itself the error:
1428 /// what a standalone audio file is held to, since a song with no sound in
1429 /// it is a broken file and not a silent source.
1430 fn open_required(path: &Path) -> crate::Result<Self> {
1431 Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into())
1432 }
1433
1434 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
1435 /// packets we skipped, exactly as on the AAC path.
1436 ///
1437 /// Which decoder is not the caller's business, and it is not always
1438 /// symphonia's: its AAC decoder refuses anything wider than stereo outright
1439 /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track
1440 /// of a film in an mkv, so that one goes to `rusty_aac` instead.
1441 fn decoder(&self) -> crate::Result<SymDecoder> {
1442 let fold = self.source_channels != self.channels;
1443 if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 {
1444 let asc = self
1445 .params
1446 .extra_data
1447 .as_deref()
1448 .ok_or("a multichannel AAC track with no AudioSpecificConfig")?;
1449 let decoder = rusty_aac::AacDecoder::with_config_bytes(asc)
1450 .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?;
1451 return Ok(SymDecoder::Aac(Box::new(decoder), fold));
1452 }
1453 Ok(SymDecoder::Sym(
1454 symphonia::default::get_codecs()
1455 .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,
1456 fold,
1457 ))
1458 }
1459
1460 /// `secs` on this source's audible timeline into media samples (priming
1461 /// included, so it compares directly against a decoded position).
1462 fn media(&self, secs: f64) -> u64 {
1463 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1464 }
1465
1466 /// A packet timestamp in the track's time base, as samples per channel.
1467 fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {
1468 let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
1469 (secs.max(0.0) * f64::from(self.sample_rate)) as u64
1470 }
1471}
1472
1473/// One packet in, interleaved f32 out — whichever library did the decoding, and
1474/// already folded to the layout [`SymTrack::channels`] promised. The flag is
1475/// that fold: `true` for a 5.1 track, and there is nothing else it can be.
1476enum SymDecoder {
1477 Sym(Box<dyn AudioDecoder>, bool),
1478 /// Boxed because the decoder carries its own IMDCT tables and this enum is
1479 /// moved into the worker.
1480 Aac(Box<rusty_aac::AacDecoder>, bool),
1481}
1482
1483impl SymDecoder {
1484 fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {
1485 match self {
1486 Self::Sym(decoder, fold) => {
1487 decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);
1488 fold_5_1(out, *fold);
1489 }
1490 Self::Aac(decoder, fold) => {
1491 let pcm = decoder
1492 .decode(&packet.data, None)
1493 .map_err(|e| format!("AAC decode failed: {e}"))?;
1494 *out = pcm.samples;
1495 fold_5_1(out, *fold);
1496 }
1497 }
1498 Ok(())
1499 }
1500}
1501
1502/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of
1503/// each side join that side at -3 dB, and the LFE is dropped -- it carries no
1504/// programme a stereo pair could put anywhere. Both outputs are divided by the
1505/// sum of their own coefficients, so a source at full scale cannot come out
1506/// clipped; that is what every player does by default.
1507///
1508/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders
1509/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls,
1510/// Rs, LFE element order into it: `decode.rs:779`).
1511///
1512/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands
1513/// out, which does not normalise and can overload -- so a film plays quieter
1514/// here than in a player beside it. It is the loudness the AC-3 5.1 path already
1515/// has (measured within 1.3 dB), so the two agree; the upgrade path is a
1516/// limiter on the output, at which point the coefficients can go back to 1.0.
1517fn fold_5_1(samples: &mut Vec<f32>, fold: bool) {
1518 if !fold {
1519 return;
1520 }
1521 const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2;
1522 const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE);
1523 for frame in 0..samples.len() / 6 {
1524 let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6])
1525 .expect("six samples of a 5.1 frame");
1526 samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM;
1527 samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM;
1528 }
1529 samples.truncate(samples.len() / 6 * 2);
1530}
1531
1532/// One source's AC-3 track: the same mp4 sample tables the AAC track is read
1533/// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder
1534/// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and
1535/// one timeline layout is all there is. A 5.1 BluRay track therefore arrives
1536/// here as an ordinary stereo source, and its rows in the picker say so.
1537///
1538/// `channels` is what the decoder actually emitted for the first frame rather
1539/// than an assumed 2: everything from mono to 5.1 downmixes to stereo, but a 2.1
1540/// stream is a passthrough the library leaves at 3, and that is refused by name
1541/// in [`Track::channels`] instead of being mislabelled.
1542struct Ac3Track {
1543 reader: Mp4Reader<BufReader<File>>,
1544 track_id: u32,
1545 sample_count: u32,
1546 sample_rate: u32,
1547 channels: u16,
1548 timescale: u32,
1549 priming: u64,
1550 total_samples: Option<u64>,
1551 stts: Vec<(u32, u32)>,
1552 /// What the decoder is asked to hand out, from this track's own layout:
1553 /// `Some(2)` for anything with more than one front channel, `None` — the
1554 /// library's passthrough — for a mono track. See [`ac3_decoder`].
1555 requested: Option<u16>,
1556}
1557
1558impl Ac3Track {
1559 /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it
1560 /// is anything else (including out of range) — the caller then goes on to
1561 /// the AAC reader, which owns those verdicts and their wording.
1562 ///
1563 /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without
1564 /// keeping the fourcc, so what the track *is* comes out of the `stsd` by
1565 /// hand ([`crate::demux::sample_entry`]); the rate and the channel count
1566 /// come out of the first syncframe, which is where AC-3 states them.
1567 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1568 let file = File::open(path)?;
1569 let size = file.metadata()?.len();
1570 let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?;
1571 let ids = audio_track_ids(&reader);
1572 let Some(&track_id) = ids.get(stream) else {
1573 return Ok(None);
1574 };
1575 if !matches!(crate::demux::sample_entry(path, track_id), Ok((kind, _)) if &kind == b"ac-3")
1576 {
1577 return Ok(None);
1578 }
1579 let track = &reader.tracks()[&track_id];
1580 let timescale = track.timescale();
1581 let duration = track.trak.mdia.mdhd.duration;
1582 let edit = edit_media_time(track);
1583 let stts: Vec<(u32, u32)> = stts_pairs(track).collect();
1584 let sample_count = reader.sample_count(track_id)?;
1585
1586 let first = reader
1587 .read_sample(track_id, 1)?
1588 .ok_or("the AC-3 track has no samples")?;
1589 let sample_rate = oxideav_ac3::syncinfo::parse(&first.bytes)
1590 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?
1591 .sample_rate;
1592 let nfchans = oxideav_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default())
1593 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
1594 .nfchans;
1595 let requested = (nfchans > 1).then_some(2);
1596 let mut decoder = ac3_decoder("ac3", requested)?;
1597 let channels = decode_ac3(&mut decoder, &first.bytes)?
1598 .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16)
1599 .filter(|&c| c > 0)
1600 .ok_or("the first AC-3 syncframe decoded to nothing")?;
1601
1602 // No encoder delay in AC-3; a remux that writes an edit list is still
1603 // honoured, exactly as the AAC track honours it.
1604 let priming = edit
1605 .and_then(|t| scale(t, sample_rate, timescale))
1606 .unwrap_or(0);
1607 Ok(Some(Self {
1608 track_id,
1609 sample_count,
1610 sample_rate,
1611 channels,
1612 timescale,
1613 priming,
1614 total_samples: scale(duration, sample_rate, timescale)
1615 .map(|d| d.saturating_sub(priming)),
1616 stts,
1617 requested,
1618 reader,
1619 }))
1620 }
1621
1622 /// `secs` on this source's audible timeline into media samples.
1623 fn media(&self, secs: f64) -> u64 {
1624 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1625 }
1626
1627 /// One `[start, end)` window, resolved to syncframes and media samples —
1628 /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll.
1629 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1630 let media_target = self.media(start_secs);
1631 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
1632 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL);
1633 Segment {
1634 source: Some(source),
1635 start_id,
1636 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
1637 media_target,
1638 media_end: self.media(end_secs).max(media_target),
1639 }
1640 }
1641}
1642
1643/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same
1644/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of
1645/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux
1646/// therefore arrives on the timeline as an ordinary stereo source, exactly as
1647/// the mp4 path's does, and the mono passthrough quirk is the same one.
1648///
1649/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side
1650/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]):
1651/// one block is one packet, one packet is one syncframe, and a seek lands on
1652/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in
1653/// front of it.
1654struct MkvAc3Track {
1655 mkv: crate::demux::MkvAudio,
1656 sample_rate: u32,
1657 /// What comes *out* of the decoder, measured on the first frame — 2 for
1658 /// anything from stereo to 5.1, 1 for a mono track (see `requested`).
1659 channels: u16,
1660 total_samples: Option<u64>,
1661 /// What the decoder is asked to hand out, from this track's own layout:
1662 /// `Some(2)` for anything with more than one front channel, `None` for a
1663 /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's.
1664 requested: Option<u16>,
1665}
1666
1667impl MkvAc3Track {
1668 /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 —
1669 /// that mkv is the silent source it has always been. An `Err` is a track
1670 /// that is one and could not be read, which
1671 /// [`AudioSession::unsupported`] quotes back to the user.
1672 fn open(path: &Path) -> crate::Result<Option<Self>> {
1673 Self::from_blocks(crate::demux::MkvAudio::open(path)?)
1674 }
1675
1676 /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]),
1677 /// which is how the AC-3 half of a dual-audio file is reached.
1678 ///
1679 /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number
1680 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
1681 Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?)
1682 }
1683
1684 fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> {
1685 let Some(mut mkv) = mkv else {
1686 return Ok(None);
1687 };
1688 let first = mkv
1689 .frame(0)?
1690 .ok_or("the AC-3 track of this Matroska file has no blocks")?;
1691 // Rate and layout come out of the bit stream, which is where AC-3
1692 // states them: Matroska's `Audio` element repeats them and muxers get
1693 // that wrong often enough that the frame is the better source.
1694 // `nfchans` excludes the LFE in both syntaxes, which is what the
1695 // downmix decision wants.
1696 let (sample_rate, nfchans) = if mkv.codec == "eac3" {
1697 // Annex E's BSI starts right after the 16-bit syncword.
1698 let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default())
1699 .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?;
1700 (bsi.sample_rate, bsi.nfchans)
1701 } else {
1702 let sync = oxideav_ac3::syncinfo::parse(&first)
1703 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?;
1704 let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default())
1705 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?;
1706 (sync.sample_rate, bsi.nfchans)
1707 };
1708 let requested = (nfchans > 1).then_some(2);
1709 let mut decoder = ac3_decoder(mkv.codec, requested)?;
1710 let (pcm, samples) =
1711 decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?;
1712 let channels = (pcm.len() as u64 / samples.max(1)) as u16;
1713 if channels == 0 {
1714 return Err("the first AC-3 syncframe decoded to nothing".into());
1715 }
1716 // The track runs to the last block's timestamp plus that block's own
1717 // frame -- a container that indexes nothing states no duration either,
1718 // and every frame of a syncframe stream is the same length.
1719 let last = mkv.secs(mkv.blocks().saturating_sub(1));
1720 Ok(Some(Self {
1721 total_samples: Some((last * f64::from(sample_rate)) as u64 + samples),
1722 sample_rate,
1723 channels,
1724 requested,
1725 mkv,
1726 }))
1727 }
1728
1729 /// `secs` on this source's timeline into media samples. No priming: the
1730 /// container carries no edit list and AC-3 no encoder delay.
1731 fn media(&self, secs: f64) -> u64 {
1732 (secs.max(0.0) * f64::from(self.sample_rate)) as u64
1733 }
1734
1735 /// One `[start, end)` window, resolved to blocks and media samples —
1736 /// [`Ac3Track::segment`] against block timestamps instead of an `stts`.
1737 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1738 let media_target = self.media(start_secs);
1739 let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize);
1740 Segment {
1741 source: Some(source),
1742 start_id: start_id as u32,
1743 start_pos: self.media(self.mkv.secs(start_id)),
1744 media_target,
1745 media_end: self.media(end_secs).max(media_target),
1746 }
1747 }
1748}
1749
1750/// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own
1751/// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a
1752/// 5.1 track at all. Fresh per segment for the same reason every other decoder
1753/// here is: a seek leaves overlap-add state belonging to the frames we skipped.
1754///
1755/// ponytail: `Some(2)` on a **mono** (`acmod` 1/0) source decodes to digital
1756/// silence in oxideav-ac3 0.0.10 — measured, 5.1 and stereo are correct — so a
1757/// mono track asks for no downmix at all and stays the mono source it is. The
1758/// upgrade path is `Some(2)` unconditionally once the library duplicates the
1759/// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change.
1760///
1761/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers
1762/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct
1763/// behind both dispatches per packet on `bsid` in any case, so what this picks
1764/// is the capability set, not the syntax.
1765fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {
1766 let mut registry = CodecRegistry::new();
1767 oxideav_ac3::register_codecs(&mut registry);
1768 let mut params = CodecParameters::audio(CodecId::new(codec));
1769 params.channels = channels;
1770 registry
1771 .first_decoder(&params)
1772 .map_err(|e| format!("no AC-3 decoder: {e:?}").into())
1773}
1774
1775/// One syncframe in, one buffer of interleaved f32 out and the frames per
1776/// channel it holds. `Ok(None)` when the decoder wants more input before it can
1777/// hand a frame back, which is not an error. The library speaks S16
1778/// little-endian; `/32768` is the whole conversion, and it lands in the
1779/// `[-1, 1)` every other reader here emits.
1780///
1781/// The frame count comes back beside the samples because an E-AC-3 frame is not
1782/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2
1783/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the
1784/// channel count and every media position after it out.
1785fn decode_ac3(
1786 decoder: &mut Box<dyn Decoder>,
1787 bytes: &[u8],
1788) -> crate::Result<Option<(Vec<f32>, u64)>> {
1789 let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());
1790 decoder
1791 .send_packet(&packet)
1792 .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;
1793 match decoder.receive_frame() {
1794 Ok(Frame::Audio(audio)) => Ok(Some((
1795 audio.data[0]
1796 .chunks_exact(2)
1797 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
1798 .collect(),
1799 u64::from(audio.samples),
1800 ))),
1801 Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),
1802 Err(oxideav_core::Error::NeedMore) => Ok(None),
1803 Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),
1804 }
1805}
1806
1807/// One source's AAC track, resolved once: the reader plus everything the header
1808/// has to say about it. `stts` is copied out because every other field would
1809/// otherwise keep a borrow alive on the reader the worker needs mutably — a real
1810/// AAC track has one entry, so it is two `u32`s.
1811struct AacTrack {
1812 reader: Mp4Reader<BufReader<File>>,
1813 track_id: u32,
1814 sample_count: u32,
1815 sample_rate: u32,
1816 timescale: u32,
1817 /// Encoder delay of *this* file. Sources are joined, priming is not shared.
1818 priming: u64,
1819 total_samples: Option<u64>,
1820 stts: Vec<(u32, u32)>,
1821 config: ChannelConfig,
1822 freq_index: u8,
1823 chan_conf: u8,
1824 /// A fresh decoder is built from these per segment: seeking mid-stream
1825 /// leaves MDCT and PNS state that belongs to the packets we skipped.
1826 params: AudioCodecParameters,
1827}
1828
1829impl AacTrack {
1830 /// The `stream`-th audio track of `path`, counted in file order over *all*
1831 /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out.
1832 ///
1833 /// Stream 0 is best effort: `Ok(None)` when there is no AAC track there at
1834 /// all, which is a valid silent source (a file whose audio is AC-3 still has
1835 /// a picture worth editing) and, for a standalone audio file, the door
1836 /// through to symphonia ([`Track::open`]). A stream the caller *named* is a
1837 /// promise instead, so out of range or not AAC there is an `Err` rather than
1838 /// silence the caller did not ask for.
1839 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1840 let file = File::open(path)?;
1841 let size = file.metadata()?.len();
1842 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
1843
1844 let ids = audio_track_ids(&reader);
1845 let Some(track) = ids.get(stream).map(|id| &reader.tracks()[id]) else {
1846 return match stream {
1847 0 => Ok(None),
1848 n => Err(format!(
1849 "{}: audio stream {n} of {} streams",
1850 path.display(),
1851 ids.len()
1852 )
1853 .into()),
1854 };
1855 };
1856 if !matches!(track.media_type(), Ok(MediaType::AAC)) {
1857 return match stream {
1858 0 => Ok(None),
1859 n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()),
1860 };
1861 }
1862 // Refuse early with a message instead of failing packet by packet — and
1863 // a copy carries no profile of its own: the writer rebuilds the
1864 // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a
1865 // non-LC source would be mislabelled rather than merely unplayable.
1866 match track.audio_profile()? {
1867 AudioObjectType::AacLowComplexity => {}
1868 other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()),
1869 }
1870
1871 let track_id = track.track_id();
1872 let sample_rate = track.sample_freq_index()?.freq();
1873 let timescale = track.timescale();
1874 let priming = priming_samples(track, sample_rate);
1875 let (_, freq_index, chan_conf) = asc_fields(track)?;
1876 let mut params = AudioCodecParameters::new();
1877 params
1878 .for_codec(CODEC_ID_AAC)
1879 .with_sample_rate(sample_rate)
1880 .with_extra_data(audio_specific_config(track)?);
1881 let this = Self {
1882 track_id,
1883 sample_count: reader.sample_count(track_id)?,
1884 sample_rate,
1885 timescale,
1886 priming,
1887 total_samples: scale(track.trak.mdia.mdhd.duration, sample_rate, timescale)
1888 .map(|d| d.saturating_sub(priming)),
1889 stts: stts_pairs(track).collect(),
1890 config: track.channel_config()?,
1891 freq_index,
1892 chan_conf,
1893 params,
1894 reader,
1895 };
1896 Ok(Some(this))
1897 }
1898
1899 /// Channel count. `AacDecoder` only does mono and stereo, so anything else
1900 /// is refused here rather than one packet at a time.
1901 fn channels(&self) -> crate::Result<u16> {
1902 match self.config {
1903 ChannelConfig::Mono => Ok(1),
1904 ChannelConfig::Stereo => Ok(2),
1905 other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()),
1906 }
1907 }
1908
1909 fn track_params(&self) -> AacTrackParams {
1910 AacTrackParams {
1911 freq_index: self.freq_index,
1912 chan_conf: self.chan_conf,
1913 sample_rate: self.sample_rate,
1914 }
1915 }
1916
1917 /// `secs` on this source's audible timeline into media samples (priming
1918 /// included, so it compares directly against a decoded position).
1919 /// `f64::INFINITY` saturates.
1920 fn media(&self, secs: f64) -> u64 {
1921 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1922 }
1923
1924 /// One `[start, end)` window of this source's seconds, resolved to its own
1925 /// packets and media samples.
1926 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1927 let media_target = self.media(start_secs);
1928 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
1929 // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
1930 // packet to cancel aliasing, plus one more to warm the decoder up. Their
1931 // output is discarded below, so this only costs decode time.
1932 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL);
1933 Segment {
1934 source: Some(source),
1935 start_id,
1936 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
1937 media_target,
1938 // An inverted segment is an empty one, never a backwards run.
1939 media_end: self.media(end_secs).max(media_target),
1940 }
1941 }
1942}
1943
1944/// How many whole packets to copy for a window of `ideal` samples per channel,
1945/// capped at the `available` packets left in the track.
1946///
1947/// `err` is "samples copied so far minus samples asked for", carried across the
1948/// segment joins: rounding to nearest *against the running debt* keeps the
1949/// cumulative error inside half a packet forever, where independent per-segment
1950/// rounding would random-walk away from sync (charter D1: < 1024 at every join).
1951fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
1952 let packet = i64::from(SAMPLES_PER_PACKET);
1953 // Never carry a debt the track cannot pay: a segment running past the end
1954 // would otherwise inflate every later one. (Also tames `f64::INFINITY`,
1955 // which saturates to `i64::MAX` on the cast above.)
1956 let ideal = ideal.min(i64::from(available) * packet);
1957 let want = (ideal - *err) as f64 / packet as f64;
1958 let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32;
1959 *err += i64::from(n) * packet - ideal;
1960 n
1961}
1962
1963/// The order a Matroska file's audio streams are numbered in, as positions into
1964/// `tracks` (which is file order): **stream 0 is the track this project has
1965/// always opened**, and the rest follow in file order behind it.
1966///
1967/// Not file order outright, and the difference is a saved project's sound. A
1968/// remux flags the language it wants heard with `FlagDefault` on whichever
1969/// track it likes -- mkvmerge writes it on the second one all the time -- and
1970/// that flag is what every reader here used to pick with. Numbering by file
1971/// position would have made stream 0 a *different* track on those files, so an
1972/// `.edith` project saved before this would quietly start playing the other
1973/// language. Nothing that already plays may change what it plays.
1974///
1975/// The old pick is not re-derived here, it is *run*: the AC-3 arm asks
1976/// [`MkvAc3Track`] the same question [`Track::open`] asked it (and only of the
1977/// file's first audio track, which is as far as [`crate::demux::MkvAudio`]
1978/// ever looked), and everything else asks symphonia for its default track,
1979/// which is `FlagDefault` where a muxer set one and the first readable track
1980/// where nobody did.
1981fn mkv_stream_order(path: &Path, tracks: &[crate::demux::MkvAudioTrack]) -> Vec<usize> {
1982 // One track is its own order, and it is the common case: no second probe
1983 // for the file that cannot have a second answer.
1984 if tracks.len() < 2 {
1985 return (0..tracks.len()).collect();
1986 }
1987 let head = match tracks.first() {
1988 Some(first)
1989 if matches!(first.codec.as_str(), "A_AC3" | "A_EAC3")
1990 && matches!(MkvAc3Track::open_track(path, first.number), Ok(Some(_))) =>
1991 {
1992 0
1993 }
1994 // A file symphonia will not open at all keeps file order: the open
1995 // itself is where that failure is reported, not the numbering.
1996 _ => SymTrack::open(path)
1997 .ok()
1998 .flatten()
1999 .and_then(|track| {
2000 tracks
2001 .iter()
2002 .position(|entry| entry.number == u64::from(track.track_id))
2003 })
2004 .unwrap_or(0),
2005 };
2006 std::iter::once(head)
2007 .chain((0..tracks.len()).filter(|i| *i != head))
2008 .collect()
2009}
2010
2011/// The name a Matroska audio row wears: the container's own codec id, cut down
2012/// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`.
2013///
2014/// The codec id rather than symphonia's short name, because the rows that most
2015/// need naming are exactly the ones it has no decoder for: an Opus or DTS track
2016/// is greyed out with the codec in the reason (`unusable` in the app reads this
2017/// very string), where symphonia would call it "an unsupported format".
2018fn mkv_codec_name(id: &str) -> String {
2019 match id {
2020 "A_AC3" => "ac-3".into(),
2021 "A_EAC3" => "e-ac-3".into(),
2022 "A_MPEG/L3" => "mp3".into(),
2023 _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(),
2024 }
2025}
2026
2027/// This file's audio tracks in file order — the order a stream index counts in.
2028/// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a
2029/// `HashMap`: iterating that would make "stream 0" a different track from one
2030/// run to the next on any file carrying more than one.
2031fn audio_track_ids<R>(reader: &Mp4Reader<R>) -> Vec<u32> {
2032 reader
2033 .moov
2034 .traks
2035 .iter()
2036 .filter(|trak| {
2037 matches!(
2038 TrackType::try_from(&trak.mdia.hdlr.handler_type),
2039 Ok(TrackType::Audio)
2040 )
2041 })
2042 .map(|trak| trak.tkhd.track_id)
2043 .collect()
2044}
2045
2046/// Channels in an AAC channel configuration. The config number *is* the channel
2047/// count up to 5.1; 7.1 is the one that is not.
2048fn channel_count(config: ChannelConfig) -> u16 {
2049 match config {
2050 ChannelConfig::SevenOne => 8,
2051 other => other as u16,
2052 }
2053}
2054
2055/// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a
2056/// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside
2057/// the crate (same trap as `SttsEntry`, see [`packet_at`]).
2058fn asc_fields(track: &Mp4Track) -> crate::Result<(u8, u8, u8)> {
2059 let esds = track
2060 .trak
2061 .mdia
2062 .minf
2063 .stbl
2064 .stsd
2065 .mp4a
2066 .as_ref()
2067 .and_then(|mp4a| mp4a.esds.as_ref())
2068 .ok_or("AAC track has no esds descriptor")?;
2069 let cfg = &esds.es_desc.dec_config.dec_specific;
2070 Ok((cfg.profile, cfg.freq_index, cfg.chan_conf))
2071}
2072
2073/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14
2074/// parses those out and drops the raw bytes, so this is the exact inverse of its
2075/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`).
2076fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {
2077 let (profile, freq_index, chan_conf) = asc_fields(track)?;
2078 Ok(Box::new([
2079 (profile << 3) | (freq_index >> 1),
2080 (freq_index << 7) | (chan_conf << 3),
2081 ]))
2082}
2083
2084/// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`]
2085/// walks; the box's own entry type is `pub(crate)` in mp4 0.14. Shared with
2086/// `demux`, which walks a video trak's table with the same two helpers.
2087pub(crate) fn stts_pairs(track: &Mp4Track) -> impl Iterator<Item = (u32, u32)> + '_ {
2088 track
2089 .trak
2090 .mdia
2091 .minf
2092 .stbl
2093 .stts
2094 .entries
2095 .iter()
2096 .map(|e| (e.sample_count, e.sample_delta))
2097}
2098
2099/// Encoder delay in samples-per-channel: the edit list's first real entry says
2100/// how far into the media the presentation starts.
2101///
2102/// ponytail: an explicit `media_time` of 0 is taken at face value (no trim).
2103/// Muxers that write a zero edit list despite a primed stream would leak the
2104/// priming; upgrade path is preferring the codec delay when it disagrees.
2105fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 {
2106 edit_media_time(track)
2107 .and_then(|t| scale(t, sample_rate, track.timescale()))
2108 .unwrap_or(DEFAULT_PRIMING)
2109}
2110
2111/// `media_time` of the edit list's first real entry, in the track's own
2112/// timescale: where the presentation starts inside the media. `None` when there
2113/// is no edit list, or only empty entries -- those shift the timeline rather
2114/// than trim the media, and neither track honours that shift (see
2115/// [`priming_samples`]'s ponytail). Shared with `demux`, which owes the video
2116/// track the same trim.
2117pub(crate) fn edit_media_time(track: &Mp4Track) -> Option<u64> {
2118 track
2119 .trak
2120 .edts
2121 .as_ref()
2122 .and_then(|edts| edts.elst.as_ref())
2123 .and_then(|elst| {
2124 elst.entries
2125 .iter()
2126 .map(|e| e.media_time)
2127 .find(|&t| t != EMPTY_EDIT && t != u64::MAX)
2128 })
2129}
2130
2131/// `value` from the track timescale into samples-per-channel. `None` on a zero
2132/// timescale, which would be a broken header.
2133fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
2134 let timescale = u64::from(timescale);
2135 (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
2136}
2137
2138/// Inverse of [`scale`]: samples-per-channel back into the track timescale.
2139fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 {
2140 match sample_rate {
2141 0 => 0,
2142 rate => samples * u64::from(timescale) / u64::from(rate),
2143 }
2144}
2145
2146/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll`
2147/// packets, plus that packet's own start time. Inverse of the mp4 crate's
2148/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is
2149/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs.
2150///
2151/// ponytail: the walk-back is clamped to the start of the containing stts entry
2152/// rather than crossing into the previous one, so a target within `pre_roll`
2153/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
2154/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
2155/// carrying the previous entry's delta through the walk.
2156pub(crate) fn packet_at(
2157 entries: impl IntoIterator<Item = (u32, u32)>,
2158 target_ts: u64,
2159 pre_roll: u32,
2160) -> (u32, u64) {
2161 let mut first_id = 1u32;
2162 let mut elapsed = 0u64;
2163 let mut last = (1u32, 0u64);
2164 for (count, delta) in entries {
2165 let span = u64::from(count) * u64::from(delta);
2166 let index = if target_ts < elapsed + span && delta != 0 {
2167 ((target_ts - elapsed) / u64::from(delta)) as u32
2168 } else {
2169 // Past this entry: remember its last packet in case the target runs
2170 // past the end of the track entirely.
2171 last = (
2172 first_id + count.saturating_sub(1),
2173 elapsed + span.saturating_sub(u64::from(delta)),
2174 );
2175 first_id += count;
2176 elapsed += span;
2177 continue;
2178 };
2179 let index = index - index.min(pre_roll);
2180 return (
2181 first_id + index,
2182 elapsed + u64::from(index) * u64::from(delta),
2183 );
2184 }
2185 last
2186}
2187
2188/// One window of a source to decode, resolved to media samples and packets —
2189/// or, with no source, a stretch of synthesised silence.
2190struct Segment {
2191 /// Index into the worker's tracks; the media positions below are that
2192 /// source's, not the timeline's. `None` for a gap, where only the length
2193 /// (`media_end`) means anything.
2194 source: Option<usize>,
2195 /// First packet to feed the decoder, 1-based; includes the pre-roll.
2196 start_id: u32,
2197 /// Media position of `start_id`'s first frame, in samples-per-channel.
2198 start_pos: u64,
2199 /// Media position of the first frame to emit. Everything decoded before it
2200 /// is pre-roll, priming, or seek overshoot, and gets dropped.
2201 media_target: u64,
2202 /// One past the last frame to emit; `u64::MAX` for "to the end of track".
2203 media_end: u64,
2204}
2205
2206impl Segment {
2207 /// `frames` per channel of silence — a gap in the audio lane.
2208 fn silence(frames: u64) -> Self {
2209 Self {
2210 source: None,
2211 start_id: 0,
2212 start_pos: 0,
2213 media_target: 0,
2214 media_end: frames,
2215 }
2216 }
2217}
2218
2219/// One speeded segment's resampler: the tape effect, done by reading the
2220/// decoded samples at a rate other than the one they were written at, so the
2221/// pitch moves with the speed. Linear interpolation between the two frames a
2222/// fractional position falls between -- one multiply-add per channel, which is
2223/// nothing beside the decode that produced them, and enough that a 2x clip is
2224/// not the aliasing mess plain sample-dropping would give.
2225///
2226/// It lives across the whole segment: `pos` carries the fraction over a packet
2227/// boundary and `tail` keeps the frame before the buffer, so the interpolation
2228/// at the seam is the same one it would have been inside a buffer. A segment
2229/// starts one clean and drops it at the end, which is what makes a seek a reset
2230/// for free -- exactly as the equalizer's state does.
2231///
2232/// `owed` is what the timeline gives the segment, in frames per channel:
2233/// resampling resolves to whole samples and a clip's own window resolves to
2234/// whole *source* frames, so the two miss each other by a sample or two per
2235/// clip. Truncating and padding to what is owed keeps that from accumulating
2236/// into audible drift over a timeline of speeded cuts -- the picture's clip
2237/// boundaries are exact by construction, and this makes the sound's exact too.
2238struct Resample {
2239 /// Source frames per output frame: the speed itself.
2240 step: f64,
2241 /// Where the next output frame reads, relative to the current buffer's
2242 /// first frame. Negative means it reads across the seam, into `tail`.
2243 pos: f64,
2244 /// The last frame of the buffer before this one, one sample per channel.
2245 tail: Vec<f32>,
2246 /// Output frames per channel still to be emitted for this segment.
2247 owed: u64,
2248}
2249
2250impl Resample {
2251 fn new(step: f64, owed: u64) -> Self {
2252 Self {
2253 step,
2254 pos: 0.,
2255 tail: Vec::new(),
2256 owed,
2257 }
2258 }
2259
2260 /// Rewrites `buf` in place as the frames this rate reads out of it. Never
2261 /// more than is owed, so the segment cannot overrun the room the timeline
2262 /// gave it.
2263 fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
2264 let frames = buf.len() / channels;
2265 if frames == 0 || channels == 0 {
2266 return;
2267 }
2268 let mut out: Vec<f32> = Vec::with_capacity(buf.len());
2269 while self.owed > (out.len() / channels) as u64 {
2270 let left = self.pos.floor();
2271 let right = left as i64 + 1;
2272 if right > frames as i64 - 1 {
2273 break; // the frame it would interpolate towards is not here yet
2274 }
2275 let frac = (self.pos - left) as f32;
2276 let (left, right) = (left as i64, right as usize);
2277 for c in 0..channels {
2278 // Before the buffer means the previous one's last frame; at the
2279 // very first buffer of a segment `pos` is 0, so this cannot be
2280 // asked for an empty tail.
2281 let a = match left < 0 {
2282 true => self.tail.get(c).copied().unwrap_or(0.),
2283 false => buf[left as usize * channels + c],
2284 };
2285 let b = buf[right * channels + c];
2286 out.push(a + (b - a) * frac);
2287 }
2288 self.pos += self.step;
2289 }
2290 self.tail.clear();
2291 self.tail.extend_from_slice(&buf[(frames - 1) * channels..]);
2292 self.pos -= frames as f64;
2293 self.owed -= (out.len() / channels) as u64;
2294 *buf = out;
2295 }
2296
2297 /// The silence the segment still owes when its source ran out before the
2298 /// timeline did -- a rounding frame or two, or a clip whose file is shorter
2299 /// than the edit says. `false` means the consumer went away.
2300 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
2301 while self.owed > 0 {
2302 let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET));
2303 let chunk = AudioChunk {
2304 start_sample: *timeline,
2305 samples: vec![0.0; frames as usize * channels],
2306 };
2307 if tx.send(chunk).is_err() {
2308 return false;
2309 }
2310 *timeline += frames;
2311 self.owed -= frames;
2312 }
2313 true
2314 }
2315}
2316
2317struct Worker {
2318 /// Indexed by [`Segment::source`]; only the sources some segment names are
2319 /// `Some`, the rest were never opened.
2320 tracks: Vec<Option<Track>>,
2321 channels: usize,
2322 segments: Vec<Segment>,
2323 /// One per entry of `segments`, in the same order: the filter that segment's
2324 /// samples pass through on the way out, or `None` for one that plays flat.
2325 /// Beside the segments rather than inside them so the emit path can hold the
2326 /// window rules and the filter memory at once without splitting a borrow.
2327 eqs: Vec<Option<EqState>>,
2328 /// One per entry of `segments` again: the rate that segment is read at, or
2329 /// `None` for one at real time -- which is every segment of a project nobody
2330 /// has speeded, and the path that emits the decoder's own samples untouched.
2331 speeds: Vec<Option<Resample>>,
2332 /// `start_sample` of the first chunk.
2333 timeline: u64,
2334 tx: SyncSender<AudioChunk>,
2335}
2336
2337/// Sums one worker per lane into one stream (see
2338/// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline
2339/// position and synthesises its own gaps, so the lanes are sample-aligned by
2340/// construction and a mix is an add: no resampling, no positioning, no drift to
2341/// correct. What is emitted at each turn is the shortest block every still-live
2342/// lane can supply, which keeps a slow lane from being outrun and never buffers
2343/// more than the chunks already in flight.
2344///
2345/// A lane whose channel has closed has ended and simply stops being added --
2346/// that is what "shorter lane" means here. The mix ends when all of them have.
2347/// The accumulator is reused across turns; the one allocation per chunk is the
2348/// buffer the channel takes ownership of, and none of this is the RT path (the
2349/// device callback reads the ring the feeder has already filled).
2350fn mix(
2351 rxs: &[Receiver<AudioChunk>],
2352 channels: usize,
2353 mut gains: Vec<f32>,
2354 mut limiter: Option<LimiterState>,
2355 rate: u32,
2356 controls: Option<&MixControls>,
2357 tx: &SyncSender<AudioChunk>,
2358) {
2359 // The version of the mix these gains and this limiter came from; see the
2360 // reload at the head of the loop.
2361 let mut seen = 0;
2362 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
2363 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
2364 // Numbering follows lane 0, whose first chunk says where it starts.
2365 let mut base = 0;
2366 let mut emitted = 0;
2367 let mut out: Vec<f32> = Vec::new();
2368 loop {
2369 // A mix moved while the stream plays, picked up between two blocks:
2370 // the levels change at a block boundary and nothing else changes at
2371 // all -- no flush, no re-open, no hole. The limiter is *retuned* rather
2372 // than rebuilt, so its delay line keeps running and the sample count
2373 // the master clock is made of does not move ([`LimiterState::retune`]).
2374 if let Some((next, params)) = controls.and_then(|c| c.changed(&mut seen)) {
2375 gains = next;
2376 gains.resize(rxs.len(), 1.0);
2377 match limiter.as_mut() {
2378 Some(state) => state.retune(&params),
2379 // First time it has ever been switched in on this stream: the
2380 // one that swallows nothing, for the count's sake.
2381 None if params.is_active() => {
2382 limiter = Some(LimiterState::engaged(&params, rate, channels));
2383 }
2384 None => {}
2385 }
2386 }
2387 for (i, rx) in rxs.iter().enumerate() {
2388 while live[i] && pending[i].is_empty() {
2389 match rx.recv() {
2390 Ok(chunk) => {
2391 if i == 0 && emitted == 0 {
2392 base = chunk.start_sample;
2393 }
2394 pending[i] = chunk.samples;
2395 }
2396 Err(_) => live[i] = false,
2397 }
2398 }
2399 }
2400 // The block every lane still playing can cover; `None` once they are all
2401 // done, which is the only way out of this loop besides a gone consumer.
2402 let Some(frames) = pending
2403 .iter()
2404 .filter(|p| !p.is_empty())
2405 .map(|p| p.len() / channels)
2406 .min()
2407 .filter(|&f| f > 0)
2408 else {
2409 return;
2410 };
2411 let block = frames * channels;
2412 out.clear();
2413 out.resize(block, 0.0);
2414 for (i, lane) in pending
2415 .iter_mut()
2416 .enumerate()
2417 .filter(|(_, p)| !p.is_empty())
2418 {
2419 // The lane's own volume, applied on its way into the sum: this is
2420 // the one place every lane's samples pass through, so a lane that
2421 // is turned down is turned down in an export exactly as it is in
2422 // the room. Unity is a multiply by 1.0, which f32 leaves alone.
2423 let gain = gains.get(i).copied().unwrap_or(1.0);
2424 for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) {
2425 *sum += sample * gain;
2426 }
2427 }
2428 // ...and the master limiter over the sum, before the clamp: what the
2429 // clamp used to catch by squaring it off is held under the ceiling
2430 // here instead ([`crate::limiter`]). Off, this is not even a branch
2431 // per sample.
2432 if let Some(limiter) = limiter.as_mut() {
2433 limiter.process(&mut out);
2434 }
2435 let frames = out.len() / channels;
2436 if frames == 0 {
2437 continue; // the limiter's delay line is still filling
2438 }
2439 let chunk = AudioChunk {
2440 start_sample: base + emitted,
2441 // Clamped, not wrapped: two lanes at full scale are what a mix has
2442 // to survive, and the device takes `[-1, 1]`.
2443 samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(),
2444 };
2445 if tx.send(chunk).is_err() {
2446 return; // caller moved on
2447 }
2448 emitted += frames as u64;
2449 }
2450}
2451
2452fn run(mut w: Worker) {
2453 let mut interleaved = Vec::new();
2454 let channels = w.channels;
2455 // Chunk numbering is continuous across every join, source ones included.
2456 let mut timeline = w.timeline;
2457 let segments = std::mem::take(&mut w.segments);
2458 let mut eqs = std::mem::take(&mut w.eqs);
2459 // A short list is "flat from here on" (`open_multi_streams_eq`), which this
2460 // pads out so the zip below still walks every segment.
2461 eqs.resize_with(segments.len(), || None);
2462 let mut speeds = std::mem::take(&mut w.speeds);
2463 // ...and a short rate list is "real time from here on", for the same reason.
2464 speeds.resize_with(segments.len(), || None);
2465
2466 for ((seg, eq), speed) in segments.iter().zip(eqs.iter_mut()).zip(speeds.iter_mut()) {
2467 let Some(source) = seg.source else {
2468 // A gap: hand the device real silence rather than nothing at all,
2469 // in the same packet-sized chunks decoding produces, so `fed` and
2470 // the master clock keep counting straight through the hole.
2471 let mut left = seg.media_end;
2472 while left > 0 {
2473 let frames = left.min(u64::from(SAMPLES_PER_PACKET));
2474 let chunk = AudioChunk {
2475 start_sample: timeline,
2476 samples: vec![0.0; frames as usize * channels],
2477 };
2478 if w.tx.send(chunk).is_err() {
2479 return; // caller moved on
2480 }
2481 timeline += frames;
2482 left -= frames;
2483 }
2484 continue;
2485 };
2486 let Some(track) = w.tracks[source].as_mut() else {
2487 continue; // opener fills every named source; nothing to decode
2488 };
2489 let track = match track {
2490 Track::Sym(track) => {
2491 if !run_sym(
2492 track,
2493 seg,
2494 eq.as_mut(),
2495 speed,
2496 channels,
2497 &mut timeline,
2498 &w.tx,
2499 ) || !settle(speed, channels, &mut timeline, &w.tx)
2500 {
2501 return; // consumer went away
2502 }
2503 continue;
2504 }
2505 Track::Mkv(track) => {
2506 if !run_mkv_ac3(
2507 track,
2508 seg,
2509 eq.as_mut(),
2510 speed,
2511 channels,
2512 &mut timeline,
2513 &w.tx,
2514 ) || !settle(speed, channels, &mut timeline, &w.tx)
2515 {
2516 return; // consumer went away
2517 }
2518 continue;
2519 }
2520 Track::Ac3(track) => {
2521 if !run_ac3(
2522 track,
2523 seg,
2524 eq.as_mut(),
2525 speed,
2526 channels,
2527 &mut timeline,
2528 &w.tx,
2529 ) || !settle(speed, channels, &mut timeline, &w.tx)
2530 {
2531 return; // consumer went away
2532 }
2533 continue;
2534 }
2535 Track::Aac(track) => track,
2536 };
2537 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())
2538 {
2539 Ok(decoder) => decoder,
2540 Err(e) => {
2541 eprintln!("audio decoder init failed: {e}");
2542 return;
2543 }
2544 };
2545 let mut pos = seg.start_pos;
2546
2547 for id in seg.start_id..=track.sample_count {
2548 if pos >= seg.media_end {
2549 break; // segment done, on to the next one
2550 }
2551 let sample = match track.reader.read_sample(track.track_id, id) {
2552 Ok(Some(sample)) => sample,
2553 Ok(None) => break,
2554 Err(e) => {
2555 eprintln!("audio demux error at sample {id}: {e}");
2556 break;
2557 }
2558 };
2559 let packet = Packet::new(
2560 track.track_id,
2561 units::Timestamp::new(sample.start_time as i64),
2562 units::Duration::new(u64::from(sample.duration)),
2563 &sample.bytes[..],
2564 );
2565 let buf = match decoder.decode(&packet) {
2566 Ok(buf) => buf,
2567 Err(e) => {
2568 eprintln!("audio decode error at sample {id}: {e}");
2569 break;
2570 }
2571 };
2572 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
2573 let next = pos + (interleaved.len() / channels) as u64;
2574 if !emit(
2575 &mut interleaved,
2576 channels,
2577 seg,
2578 eq.as_mut(),
2579 speed.as_mut(),
2580 pos,
2581 next,
2582 &mut timeline,
2583 &w.tx,
2584 ) {
2585 return; // consumer went away
2586 }
2587 pos = next;
2588 }
2589 if !settle(speed, channels, &mut timeline, &w.tx) {
2590 return; // consumer went away
2591 }
2592 }
2593}
2594
2595/// Pays out whatever silence a speeded segment still owes the timeline (see
2596/// [`Resample::flush`]). Nothing at all at real time, where a segment owes the
2597/// timeline only the samples it decoded.
2598fn settle(
2599 speed: &mut Option<Resample>,
2600 channels: usize,
2601 timeline: &mut u64,
2602 tx: &SyncSender<AudioChunk>,
2603) -> bool {
2604 match speed {
2605 Some(speed) => speed.flush(channels, timeline, tx),
2606 None => true,
2607 }
2608}
2609
2610/// Trims one decoded buffer to the segment window and sends what survives.
2611/// `pos` is the media position of its first frame and `next` of the one after
2612/// it; both readers hand the same thing here, which is why the window rules
2613/// live in one place. `false` means the consumer went away.
2614///
2615/// Everything before the target is encoder priming and/or decoder pre-roll, not
2616/// audio the caller asked for: it is dropped, splitting the buffer that
2617/// straddles the target. The tail past the segment end goes too — on a short
2618/// segment that is this same buffer, trimmed at both ends.
2619///
2620/// The segment's equalizer runs here, on the trimmed buffer and nowhere else:
2621/// this is the one place both readers hand their samples over, so playback and
2622/// an audio export get the same filtered stream by construction rather than by
2623/// two call sites agreeing. Trimmed first, so the pre-roll a listener never
2624/// hears cannot ring the filter either. Nothing is allocated -- the device
2625/// callback is two hand-offs downstream of here in any case.
2626fn emit(
2627 interleaved: &mut Vec<f32>,
2628 channels: usize,
2629 seg: &Segment,
2630 eq: Option<&mut EqState>,
2631 speed: Option<&mut Resample>,
2632 pos: u64,
2633 next: u64,
2634 timeline: &mut u64,
2635 tx: &SyncSender<AudioChunk>,
2636) -> bool {
2637 if next <= seg.media_target {
2638 return true;
2639 }
2640 let mut pos = pos;
2641 if pos < seg.media_target {
2642 interleaved.drain(..(seg.media_target - pos) as usize * channels);
2643 pos = seg.media_target;
2644 }
2645 if next > seg.media_end {
2646 interleaved.truncate((seg.media_end - pos) as usize * channels);
2647 }
2648 if interleaved.is_empty() {
2649 return true; // nothing left of it; the loop head ends the segment
2650 }
2651 // The rate first, the filter second: what the equalizer's bands are set in
2652 // is the frequency a listener hears, and after a resample that is not the
2653 // frequency the file was written at. A segment at real time has no
2654 // resampler at all and reaches the filter with the decoder's own samples.
2655 if let Some(speed) = speed {
2656 speed.process(interleaved, channels);
2657 if interleaved.is_empty() {
2658 return true; // this buffer resolved to no output frame of its own
2659 }
2660 }
2661 if let Some(eq) = eq {
2662 eq.process(interleaved);
2663 }
2664 let chunk = AudioChunk {
2665 start_sample: *timeline,
2666 samples: std::mem::take(interleaved),
2667 };
2668 *timeline += (chunk.samples.len() / channels) as u64;
2669 tx.send(chunk).is_ok()
2670}
2671
2672/// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids
2673/// come out of the same mp4 tables, the window rules are [`emit`]'s as always,
2674/// and what reaches the mixer is already the stereo downmix. `false` means the
2675/// consumer went away.
2676fn run_ac3(
2677 track: &mut Ac3Track,
2678 seg: &Segment,
2679 mut eq: Option<&mut EqState>,
2680 speed: &mut Option<Resample>,
2681 channels: usize,
2682 timeline: &mut u64,
2683 tx: &SyncSender<AudioChunk>,
2684) -> bool {
2685 let mut decoder = match ac3_decoder("ac3", track.requested) {
2686 Ok(decoder) => decoder,
2687 Err(e) => {
2688 eprintln!("audio decoder init failed: {e}");
2689 return true;
2690 }
2691 };
2692 let mut pos = seg.start_pos;
2693 for id in seg.start_id..=track.sample_count {
2694 if pos >= seg.media_end {
2695 return true; // segment done, on to the next one
2696 }
2697 let sample = match track.reader.read_sample(track.track_id, id) {
2698 Ok(Some(sample)) => sample,
2699 Ok(None) => return true,
2700 Err(e) => {
2701 eprintln!("audio demux error at sample {id}: {e}");
2702 return true;
2703 }
2704 };
2705 let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) {
2706 Ok(Some(decoded)) => decoded,
2707 Ok(None) => continue, // the decoder wants another frame first
2708 Err(e) => {
2709 eprintln!("audio decode error at sample {id}: {e}");
2710 return true;
2711 }
2712 };
2713 let next = pos + samples;
2714 if !emit(
2715 &mut interleaved,
2716 channels,
2717 seg,
2718 eq.as_deref_mut(),
2719 speed.as_mut(),
2720 pos,
2721 next,
2722 timeline,
2723 tx,
2724 ) {
2725 return false;
2726 }
2727 pos = next;
2728 }
2729 true
2730}
2731
2732/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks
2733/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the
2734/// stereo downmix are the same ones; only where a packet comes from differs.
2735/// `false` means the consumer went away.
2736fn run_mkv_ac3(
2737 track: &mut MkvAc3Track,
2738 seg: &Segment,
2739 mut eq: Option<&mut EqState>,
2740 speed: &mut Option<Resample>,
2741 channels: usize,
2742 timeline: &mut u64,
2743 tx: &SyncSender<AudioChunk>,
2744) -> bool {
2745 let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) {
2746 Ok(decoder) => decoder,
2747 Err(e) => {
2748 eprintln!("audio decoder init failed: {e}");
2749 return true;
2750 }
2751 };
2752 let mut pos = seg.start_pos;
2753 for id in seg.start_id as usize.. {
2754 if pos >= seg.media_end {
2755 return true; // segment done, on to the next one
2756 }
2757 let block = match track.mkv.frame(id) {
2758 Ok(Some(bytes)) => bytes,
2759 Ok(None) => return true, // end of the track
2760 Err(e) => {
2761 eprintln!("audio demux error at block {id}: {e}");
2762 return true;
2763 }
2764 };
2765 let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) {
2766 Ok(Some(decoded)) => decoded,
2767 Ok(None) => continue, // the decoder wants another frame first
2768 Err(e) => {
2769 eprintln!("audio decode error at block {id}: {e}");
2770 return true;
2771 }
2772 };
2773 let next = pos + samples;
2774 if !emit(
2775 &mut interleaved,
2776 channels,
2777 seg,
2778 eq.as_deref_mut(),
2779 speed.as_mut(),
2780 pos,
2781 next,
2782 timeline,
2783 tx,
2784 ) {
2785 return false;
2786 }
2787 pos = next;
2788 }
2789 true
2790}
2791
2792/// One segment of a standalone audio file: seek the reader to just before the
2793/// window, then decode forward until the window is filled.
2794///
2795/// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the
2796/// target is thrown away by [`emit`], which is what gives a codec with decoder
2797/// state — mp3's bit reservoir above all — something to warm up on, exactly as
2798/// the AAC path's two-packet pre-roll does. A reader that cannot seek at all
2799/// simply decodes from wherever it is; the window rules still hold, it is only
2800/// slower. `false` means the consumer went away.
2801fn run_sym(
2802 track: &mut SymTrack,
2803 seg: &Segment,
2804 mut eq: Option<&mut EqState>,
2805 speed: &mut Option<Resample>,
2806 channels: usize,
2807 timeline: &mut u64,
2808 tx: &SyncSender<AudioChunk>,
2809) -> bool {
2810 let mut decoder = match track.decoder() {
2811 Ok(decoder) => decoder,
2812 Err(e) => {
2813 eprintln!("audio decoder init failed: {e}");
2814 return true;
2815 }
2816 };
2817 let rate = f64::from(track.sample_rate.max(1));
2818 let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate;
2819 if let Some(time) = Time::try_from_secs_f64(from) {
2820 let to = SeekTo::Time {
2821 time,
2822 track_id: Some(track.track_id),
2823 };
2824 // A failed seek is not fatal: it leaves the reader where it was, and
2825 // the window rules below still only emit what the segment asked for.
2826 if let Err(e) = track.reader.seek(SeekMode::Accurate, to) {
2827 eprintln!("audio seek to {from:.3}s failed: {e}");
2828 }
2829 }
2830 let mut interleaved = Vec::new();
2831 loop {
2832 let packet = match track.reader.next_packet() {
2833 Ok(Some(packet)) => packet,
2834 Ok(None) => return true, // end of the file, and of the segment
2835 Err(e) => {
2836 eprintln!("audio demux error: {e}");
2837 return true;
2838 }
2839 };
2840 if packet.track_id != track.track_id {
2841 continue; // another track of the same container
2842 }
2843 let pos = track.samples_at(packet.pts);
2844 if pos >= seg.media_end {
2845 return true; // segment done, on to the next one
2846 }
2847 if let Err(e) = decoder.decode(&packet, &mut interleaved) {
2848 eprintln!("audio decode error at sample {pos}: {e}");
2849 return true;
2850 }
2851 let next = pos + (interleaved.len() / channels) as u64;
2852 // Reborrowed per packet: the filter memory has to carry across the
2853 // packet boundary, so this is one `EqState` for the whole segment.
2854 if !emit(
2855 &mut interleaved,
2856 channels,
2857 seg,
2858 eq.as_deref_mut(),
2859 speed.as_mut(),
2860 pos,
2861 next,
2862 timeline,
2863 tx,
2864 ) {
2865 return false;
2866 }
2867 }
2868}
2869
2870#[cfg(test)]
2871mod tests {
2872 use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run};
2873
2874 /// The 5.1 fold: each side keeps its own front channel, takes the centre
2875 /// and its own surround at -3 dB, drops the LFE, and comes out unable to
2876 /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR.
2877 #[test]
2878 fn five_one_folds_to_stereo_without_clipping() {
2879 // One frame per channel at full scale, one channel at a time.
2880 for (channel, (left, right)) in [
2881 (0, (1.0, 0.0)), // FL
2882 (1, (0.0, 1.0)), // FR
2883 (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC
2884 (3, (0.0, 0.0)), // LFE, dropped
2885 (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL
2886 (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR
2887 ] {
2888 let mut frame = vec![0.0f32; 6];
2889 frame[channel] = 1.0;
2890 fold_5_1(&mut frame, true);
2891 let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2);
2892 assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame");
2893 assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}");
2894 assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}");
2895 }
2896 // Every channel at once is what a normalised fold exists for.
2897 let mut loud = vec![1.0f32; 12];
2898 fold_5_1(&mut loud, true);
2899 assert_eq!(loud.len(), 4);
2900 assert!(
2901 loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),
2902 "full scale in, full scale out, never past it: {loud:?}"
2903 );
2904 // A track that is not 5.1 is handed over untouched.
2905 let mut stereo = vec![0.5f32, -0.5];
2906 fold_5_1(&mut stereo, false);
2907 assert_eq!(stereo, [0.5, -0.5]);
2908 }
2909
2910 /// A real AAC track: one stts entry, N packets of 1024.
2911 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
2912 [(count, 1024)]
2913 }
2914
2915 #[test]
2916 fn packet_at_walks_back_by_the_pre_roll() {
2917 // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..).
2918 assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064));
2919 assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016));
2920 // Exactly on a packet boundary is the start of that packet, not the end
2921 // of the previous one.
2922 assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048));
2923 }
2924
2925 #[test]
2926 fn packet_at_clamps_both_ends() {
2927 // Head: no room for the walk-back, and packet ids are 1-based.
2928 assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0));
2929 assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0));
2930 // Past the end: the last packet, so the worker decodes ~nothing.
2931 assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776));
2932 // Degenerate boxes must not panic or wrap.
2933 assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0));
2934 assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0));
2935 }
2936
2937 #[test]
2938 fn packet_at_crosses_stts_entries() {
2939 // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240
2940 // with packet 11.
2941 let entries = [(10u32, 1024u32), (10, 512)];
2942 assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288));
2943 assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264));
2944 // The ponytail clamp: on the first packet of the second entry the
2945 // walk-back stops there instead of stepping into the first entry.
2946 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
2947 }
2948
2949 /// xorshift64: adversarial segment lists do not deserve a dependency.
2950 fn rng(state: &mut u64) -> u64 {
2951 *state ^= *state << 13;
2952 *state ^= *state >> 7;
2953 *state ^= *state << 17;
2954 *state
2955 }
2956
2957 #[test]
2958 fn packet_run_keeps_cumulative_error_under_a_packet() {
2959 let packet = i64::from(SAMPLES_PER_PACKET);
2960 let mut state = 0x5eed_1234_9876_abcd;
2961 for rate in [44100i64, 48000] {
2962 for list in 0..100 {
2963 let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64);
2964 // 3..43 joins of anything from one video frame to four seconds.
2965 for join in 0..3 + rng(&mut state) % 40 {
2966 let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64;
2967 copied += i64::from(packet_run(&mut err, ideal, u32::MAX));
2968 asked += ideal;
2969 assert!(
2970 err.abs() < packet,
2971 "rate {rate} list {list} join {join}: err {err}"
2972 );
2973 }
2974 // The accumulator is the whole story: what it says is the drift.
2975 assert_eq!(copied * packet - asked, err);
2976 }
2977 }
2978 }
2979
2980 #[test]
2981 fn packet_run_rounds_against_the_running_debt() {
2982 // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples
2983 // owed, and the debt is repaid by a 44-packet second once it crosses a
2984 // half packet — never by letting each second round on its own.
2985 let mut err = 0;
2986 assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43);
2987 assert_eq!(err, -68);
2988 let mut seconds = 1;
2989 while packet_run(&mut err, 44100, u32::MAX) == 43 {
2990 seconds += 1;
2991 assert!(seconds < 20, "debt never repaid, err {err}");
2992 }
2993 assert_eq!(seconds, 7, "68 samples a second, half a packet is 512");
2994 assert!(err > 0, "the repaying second overshoots, err {err}");
2995 }
2996
2997 #[test]
2998 fn packet_run_forgives_a_debt_the_track_cannot_pay() {
2999 // Asking a second of a track with ten packets left: it delivers ten and
3000 // does not make the next segment copy the shortfall from elsewhere.
3001 let mut err = 0;
3002 assert_eq!(packet_run(&mut err, 44100, 10), 10);
3003 assert_eq!(err, 0);
3004 // Degenerate windows are empty, not negative.
3005 assert_eq!(packet_run(&mut err, 0, 10), 0);
3006 assert_eq!(packet_run(&mut err, i64::MAX, 7), 7);
3007 }
3008
3009 #[test]
3010 fn asc_round_trips_aac_lc_44100_stereo() {
3011 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
3012 let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8);
3013 let asc = [
3014 (profile << 3) | (freq_index >> 1),
3015 (freq_index << 7) | (chan_conf << 3),
3016 ];
3017 assert_eq!(asc, [0x12, 0x10]);
3018 }
3019
3020 /// The one claim worth making about a hand-written bitstream: our own
3021 /// decoder turns it into exactly one packet of exactly zero.
3022 #[test]
3023 fn a_silent_packet_decodes_to_a_packet_of_zero() {
3024 use super::{AacDecoder, AudioDecoder, AudioDecoderOptions, silent_packet};
3025 use symphonia_core::codecs::audio::{AudioCodecParameters, well_known::CODEC_ID_AAC};
3026 use symphonia_core::{packet::Packet, units};
3027
3028 for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] {
3029 // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels.
3030 let asc: Box<[u8]> = Box::new([(2 << 3) | (4 >> 1), (4 << 7) | (chan_conf << 3)]);
3031 let mut params = AudioCodecParameters::new();
3032 params
3033 .for_codec(CODEC_ID_AAC)
3034 .with_sample_rate(44100)
3035 .with_extra_data(asc);
3036 let mut decoder =
3037 AacDecoder::try_new(&params, &AudioDecoderOptions::default()).expect("decoder");
3038 let bytes = silent_packet(chan_conf).expect("silence");
3039 let packet = Packet::new(
3040 0,
3041 units::Timestamp::new(0),
3042 units::Duration::new(u64::from(SAMPLES_PER_PACKET)),
3043 &bytes[..],
3044 );
3045 let buf = decoder.decode(&packet).expect("decodes as AAC-LC");
3046 let mut out = Vec::new();
3047 buf.copy_to_vec_interleaved::<f32>(&mut out);
3048 assert_eq!(out.len(), SAMPLES_PER_PACKET as usize * channels);
3049 assert!(
3050 out.iter().all(|&s| s == 0.0),
3051 "{chan_conf} ch is not silent"
3052 );
3053 }
3054 assert!(
3055 silent_packet(6).is_err(),
3056 "beyond stereo is refused, not faked"
3057 );
3058 }
3059}