forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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