forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

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