forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2c8e3aaTahinli3 months ago335 commits

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