forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

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