forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

audio.rs5627 lines, 247.8 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` as it always has -- that
6//! path also yields the raw access units the export copies, which is the only
7//! reason it is kept separate -- and every AAC stream, from any container, is
8//! decoded by `ec-aac`, HE-AAC (SBR) included. A standalone
9//! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through
10//! symphonia's own format probe, as does the AAC track of a **Matroska** file:
11//! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to
12//! stereo on the way out ([`SymDecoder`]). An ADTS file is read by [`crate::adts`],
13//! since symphonia's ADTS reader sits behind the `aac` feature this project does
14//! not link. An mp4's **AC-3** track is the third: the same
15//! sample tables, decoded by `ec-ac3` and downmixed to stereo by the
16//! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo
17//! timeline. Everything downstream of [`Track`] sees the
18//! same samples either way; only the packet copy asks which reader it came from,
19//! because there is nothing to copy out of an mp3 that an mp4 can hold.
20//!
21//! One output, however many lanes: a timeline's audio lanes are decoded side by
22//! side and summed ([`AudioSession::open_mixed_streams`]), which is what both
23//! the device and an audio-only export are handed. One lane skips the mixer
24//! entirely and is the plain single-stream path it always was.
25//!
26//! Both readers are addressed as `(path, stream)`. An mp4 may carry several
27//! audio tracks and the caller picks one; a standalone audio file carries
28//! exactly one, so any stream above 0 there is an `Err` rather than a silent
29//! fallback to the only track it has.
30
31use std::fs::File;
32use std::io::{Read, Seek, SeekFrom};
33use std::path::{Path, PathBuf};
34use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
35use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
36use std::sync::{Arc, Mutex};
37use std::thread;
38
39use crate::mp4track;
40use ec_core::CodecId;
41use symphonia_core::codecs::audio::{
42 AudioCodecParameters, AudioDecoder, AudioDecoderOptions,
43 well_known::{CODEC_ID_AAC, CODEC_ID_OPUS, CODEC_ID_VORBIS},
44};
45use symphonia_core::formats::probe::Hint;
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::duck::{Duck, Ducker};
56use crate::eq::{EqParams, EqState};
57use crate::limiter::{Limiter, LimiterState};
58use crate::stretch::TimeStretch;
59use crate::voice::VoiceFx;
60
61/// The rate a mix runs at when nothing picks one: the highest rate among the
62/// sources it names, so a 22.05 kHz voiceover beside a 48 kHz bed is mixed at
63/// 48 kHz and the bed is not resampled down to the voice. A mix whose sources
64/// are all 44.1 kHz stays 44.1 kHz, and 48 kHz-only stays 48 kHz. Only when
65/// every source is below 44.1 kHz (a 22.05 kHz voiceover alone, say) does the
66/// mix go to 48 kHz, which every AAC output accepts and which a WebM or
67/// Matroska Opus output needs. `None` when no source has a track.
68fn mix_rate(rates: impl IntoIterator<Item = u32>) -> Option<u32> {
69 rates
70 .into_iter()
71 .max()
72 .map(|rate| if rate < 44_100 { 48_000 } else { rate })
73}
74
75/// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
76/// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
77const DEFAULT_PRIMING: u64 = 1024;
78
79/// What the sound of a *Matroska* file is read with, named for a refusal:
80/// symphonia's registry as this project enables it (see the feature list in
81/// `Cargo.toml`) plus the families no symphonia version carries and this
82/// project decodes anyway -- AAC through `ec-aac` ([`SymDecoder::Aac`]),
83/// AC-3/E-AC-3 through `ec-ac3` ([`MkvAc3Track`]) and Opus through `ec-opus`
84/// ([`SymDecoder::Opus`]).
85///
86/// Written down per container because capability is not one set: an mp4 video's
87/// sound never reaches symphonia ([`Track::open`] answers before it), so it
88/// reads fewer codecs than a Matroska file does. Both strings were "AAC only"
89/// long after that stopped being true, which is how a user came to re-encode a
90/// film whose FLAC track already played; `capability_matrix` opens one file per
91/// codec named here.
92const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, Opus, PCM, TrueHD/MLP and Vorbis";
93
94/// The name a person knows a sound codec by, from a Matroska `CodecID` (`A_WAVPACK4`, `A_MPEG/L2`)
95/// or a bare codec tag (`WAVPACK4`, `MPC`). A tag nothing names comes back as its own text with the
96/// `A_` prefix and any `/` suffix taken off, which is still better than the id.
97pub fn codec_display_name(raw: &str) -> String {
98 let id = raw.strip_prefix("A_").unwrap_or(raw);
99 let upper = id.to_ascii_uppercase();
100 let known = match upper.as_str() {
101 "MPEG/L1" => "MP1",
102 "MPEG/L2" => "MP2",
103 "MPEG/L3" => "MP3",
104 "WAVPACK4" | "WAVPACK" => "WavPack",
105 "MPC" | "MPC8" | "MUSEPACK" => "Musepack",
106 "TTA" | "TTA1" => "TTA",
107 "ALAC" => "ALAC",
108 "SPEEX" => "Speex",
109 "AC3" | "AC-3" => "AC-3",
110 "EAC3" | "E-AC-3" => "E-AC-3",
111 "MS/ACM" => "ACM",
112 "TRUEHD" | "MLP" => "TrueHD",
113 _ => "",
114 };
115 if !known.is_empty() {
116 return known.to_string();
117 }
118 let family = upper.split('/').next().unwrap_or(&upper);
119 let named = match family {
120 "WMA" | "WMAV1" | "WMAV2" | "WMAPRO" | "WMALOSSLESS" => "WMA",
121 "AAC" => "AAC",
122 "DTS" => "DTS",
123 "VORBIS" => "Vorbis",
124 "OPUS" => "Opus",
125 "FLAC" => "FLAC",
126 "REAL" => "RealAudio",
127 "PCM" => "PCM",
128 _ => "",
129 };
130 if !named.is_empty() {
131 return named.to_string();
132 }
133 id.split('/').next().unwrap_or(id).to_string()
134}
135
136/// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video
137/// file's sound is read and where it stops.
138const MP4_DECODED: &str = "AAC-LC, HE-AAC v1/v2 and AC-3/E-AC-3";
139
140/// Packets decoded and thrown away ahead of a seek target: one for the MDCT
141/// overlap-add that reconstructs the target packet, one to warm the decoder.
142const PRE_ROLL: u32 = 2;
143
144/// Frames per channel one AAC-LC packet carries. Fixed by the codec.
145pub(crate) const SAMPLES_PER_PACKET: u32 = 1024;
146
147/// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the
148/// 256-sample overlap-add the target frame is reconstructed with.
149const AC3_PRE_ROLL: u32 = 1;
150
151/// Frames per channel a seek into a standalone audio file lands ahead of the
152/// window, decoded and thrown away: enough to refill an mp3's bit reservoir
153/// (a frame is 1152 samples and the reservoir reaches back two of them) at any
154/// rate we accept.
155const SYM_PRE_ROLL: u64 = 8192;
156
157#[derive(Debug, Clone, Copy, PartialEq)]
158pub struct AudioMeta {
159 pub sample_rate: u32,
160 pub channels: u16,
161 /// Frames per channel the container claims, priming subtracted. `None` when
162 /// the header does not say.
163 pub total_samples: Option<u64>,
164}
165
166/// One decoder output block, ready to hand to an output device.
167pub struct AudioChunk {
168 /// Position of the first frame, in samples-per-channel counted from the
169 /// first audible sample: priming is already dropped, so 0 is media time 0.
170 pub start_sample: u64,
171 /// Interleaved, `AudioMeta::channels` values per frame.
172 pub samples: Vec<f32>,
173}
174
175/// What a writer needs to declare an AAC track that plays copied packets: the
176/// esds fields verbatim from the source, no re-derivation.
177#[derive(Debug, Clone, Copy, PartialEq)]
178pub struct AacTrackParams {
179 pub freq_index: u8,
180 pub chan_conf: u8,
181 pub sample_rate: u32,
182}
183
184/// One raw AAC access unit exactly as it sits in the source `mdat` — no ADTS
185/// header, which is the form an `mp4a` sample table wants.
186pub struct AacPacket {
187 pub bytes: Vec<u8>,
188 /// Frames per channel it decodes to, for the writer's stts.
189 pub samples: u32,
190}
191
192/// Everything an import check needs from a candidate file's audio track. Two
193/// files may share a timeline when their layouts agree (or both are `None`).
194///
195/// Rate and layout, of which only the **layout** is held to the timeline's: one
196/// output device and one exported track carry one width, while a rate of its own
197/// is resampled at the decoder's door ([`Resample`]). An mp3 that agrees on the
198/// layout may join a timeline of mp4s even though nothing about it can be
199/// *copied* into an export -- that is a separate refusal, at export time, in
200/// [`AudioSession::copy_multi_segments`].
201#[derive(Debug, Clone, Copy, PartialEq)]
202pub struct AudioProbe {
203 pub sample_rate: u32,
204 pub channels: u16,
205}
206
207/// A diagnostic line for stderr, printed only under `EDITH_DEBUG` and then once
208/// per distinct line for the life of the process. The same file is opened many
209/// times in one run (every probe, every open), and an unsupported track used to
210/// print the same line each time. Anything a user must act on goes in a returned
211/// warning instead ([`crate::PlaybackSession::import_with_warnings`]).
212pub(crate) fn debug_once(line: String) {
213 static SEEN: std::sync::OnceLock<Mutex<std::collections::HashSet<String>>> =
214 std::sync::OnceLock::new();
215 if std::env::var_os("EDITH_DEBUG").is_none() {
216 return;
217 }
218 let seen = SEEN.get_or_init(Default::default);
219 let fresh = seen.lock().map(|mut set| set.insert(line.clone())).unwrap_or(true);
220 if fresh {
221 eprintln!("{line}");
222 }
223}
224
225/// One audio stream of a file as its header describes it. Every audio track is
226/// described, decodable or not: a picker shows the ones we refuse greyed out
227/// rather than pretending a BluRay remux has fewer streams than it has.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct StreamInfo {
230 /// Position among this file's audio tracks in file order — the `stream`
231 /// [`AudioSession::open_multi_streams`] takes.
232 pub index: usize,
233 /// Codec, named by its sample entry's fourcc read out of the file by hand
234 /// (mp4 0.14 keeps none for a kind it does not parse). `"unknown"` only where
235 /// the fourcc itself cannot be read.
236 pub codec: String,
237 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
238 pub channels: u16,
239 /// `0` for a stream whose sample entry mp4 0.14 does not parse.
240 pub sample_rate: u32,
241 /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write.
242 pub lang: Option<String>,
243 /// Whether opening this stream would decode -- a codec question only now
244 /// that no width is refused. The grey-out rule, mirroring what `Track::open`
245 /// answers one file at a time.
246 pub decodable: bool,
247 /// Bits per sample, for a PCM track whose sample entry states them. `None`
248 /// for every compressed codec, and for a Matroska track (its `BitDepth` is
249 /// not read here).
250 pub bit_depth: Option<u8>,
251 /// Bits per second this track's own samples take over the file's stated
252 /// playing time -- the same measure as [`crate::MediaBitrate::audio`]. `None`
253 /// where the header does not state the length, and for Matroska, whose
254 /// per-track bytes need a cluster walk this listing does not do.
255 pub bitrate: Option<u64>,
256}
257
258/// The mix settings a *running* mixer reads: what each lane is turned by on its
259/// way into the sum and the ceiling the sum comes out through, both swappable
260/// while the stream plays.
261///
262/// This is what keeps a fader off the reseek path. Everything else a timeline
263/// says lives inside a decode worker -- a segment's window, its curve, its rate
264/// -- and can only be changed by rebuilding it, which is a flush, a re-open and
265/// a hole in the sound. These two live at the sum, where nothing is decoded, so
266/// the mixer can pick them up between one block and the next: an arrow key held
267/// down on a fader moves the level and nothing else moves at all.
268///
269/// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live)
270/// is what says whether a mixer is actually reading it -- a single lane at
271/// unity with the limiter off is not mixed at all
272/// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this
273/// dead has to reopen the stream to be heard.
274pub struct MixControls {
275 /// Bumped by every change; the mixer reloads when the number it last saw
276 /// is not this one, so an unchanged mix costs one relaxed load per block.
277 version: AtomicU64,
278 /// The lane amplitudes and the limiter, together: they are set together and
279 /// a mixer that read half of one change and half of the next would be
280 /// mixing a state nobody asked for.
281 state: Mutex<(Vec<f32>, Vec<Vec<Duck>>, Limiter)>,
282 /// A mixer thread has these; see the type docs.
283 live: AtomicBool,
284 /// The open these were handed to finished without a mixer: a silent
285 /// timeline, or a source that would not open. Set by whoever ran that open
286 /// ([`PlaybackSession::start_audio`] does it from the feeder), because
287 /// [`Self::live`] alone cannot tell "no mixer will ever read this" from
288 /// "the mixer is still being opened" -- and a caller that cannot tell those
289 /// apart either rebuilds the sound under a cold open, once per fader nudge,
290 /// or hands a mix to nobody and never notices.
291 detached: AtomicBool,
292 /// The highest level each lane has reached since it was last read, after
293 /// its gain and before the sum. Written by the mixer once per block (never
294 /// on the device's callback); read and cleared by [`Self::take_lane_peaks`].
295 lane_peaks: Mutex<Vec<f32>>,
296}
297
298impl MixControls {
299 pub fn new(gains: Vec<f32>, ducks: Vec<Vec<Duck>>, limiter: Limiter) -> Arc<Self> {
300 Arc::new(Self {
301 version: AtomicU64::new(0),
302 lane_peaks: Mutex::new(vec![0.0; gains.len()]),
303 state: Mutex::new((gains, ducks, limiter)),
304 live: AtomicBool::new(false),
305 detached: AtomicBool::new(false),
306 })
307 }
308
309 /// Raises lane `lane`'s peak to `peak` if that is higher. A lane with no
310 /// slot (a mix handed more lanes than it was built with) is ignored rather
311 /// than grown here: it is a meter, not the mix.
312 fn note_lane_peak(&self, lane: usize, peak: f32) {
313 if let Some(held) = self.lane_peaks.lock().unwrap().get_mut(lane)
314 && peak > *held
315 {
316 *held = peak;
317 }
318 }
319
320 /// The per-lane peaks since the last call, and starts them over from zero.
321 pub fn take_lane_peaks(&self) -> Vec<f32> {
322 let mut held = self.lane_peaks.lock().unwrap();
323 let taken = held.clone();
324 held.iter_mut().for_each(|p| *p = 0.0);
325 taken
326 }
327
328 /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock
329 /// held for a `Vec` swap and an atomic.
330 pub fn set(&self, gains: Vec<f32>, ducks: Vec<Vec<Duck>>, limiter: Limiter) {
331 *self.state.lock().unwrap() = (gains, ducks, limiter);
332 self.version.fetch_add(1, Ordering::Release);
333 }
334
335 /// Whether a mixer thread is reading this at all.
336 pub fn is_live(&self) -> bool {
337 self.live.load(Ordering::Acquire)
338 }
339
340 /// Says the open is over and left no mixer behind; see [`Self::detached`].
341 pub fn detach(&self) {
342 self.detached.store(true, Ordering::Release);
343 }
344
345 /// Whether anything can still hear a [`set`](Self::set): a mixer reading
346 /// these, or an open still on its way to being one.
347 pub fn is_reachable(&self) -> bool {
348 !self.detached.load(Ordering::Acquire)
349 }
350
351 /// The mix, if it has moved since `seen`. `None` -- the every-block case --
352 /// takes no lock.
353 #[allow(clippy::type_complexity)]
354 fn changed(&self, seen: &mut u64) -> Option<(Vec<f32>, Vec<Vec<Duck>>, Limiter)> {
355 let now = self.version.load(Ordering::Acquire);
356 if now == *seen {
357 return None;
358 }
359 *seen = now;
360 Some(self.state.lock().unwrap().clone())
361 }
362}
363
364pub struct AudioSession;
365
366impl AudioSession {
367 /// Opens the audio track of `path`. `Ok(None)` means the file simply has no
368 /// audio, which is a valid session; `Err` is a real failure.
369 pub fn open(
370 path: impl AsRef<Path>,
371 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
372 Self::open_at(path, 0.0)
373 }
374
375 /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on
376 /// the audible timeline; `start_sample` stays absolute from audible zero, so
377 /// the output is the tail of a full run. Past the end yields no chunks.
378 pub fn open_at(
379 path: impl AsRef<Path>,
380 start_secs: f64,
381 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
382 Self::open_segments(path, &[(start_secs, f64::INFINITY)])
383 }
384
385 /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds —
386 /// back to back as one continuous stream: the chunks carry no gap at a join,
387 /// so pouring them into a ring is seamless. Each segment gets a fresh
388 /// decoder and its own pre-roll, which makes a seeked segment perceptually
389 /// but not bit-exactly equal to the same window of a full run (perceptual
390 /// noise substitution reseeds; measured below 1e-3).
391 ///
392 /// `start_sample` counts from the *first* segment's own audible start, so a
393 /// single segment reads as absolute media time (what [`open_at`](Self::open_at)
394 /// promises) and a list reads as one timeline. Segment ends past the track
395 /// are capped; an empty list is a valid session with no chunks.
396 pub fn open_segments(
397 path: impl AsRef<Path>,
398 segs: &[(f64, f64)],
399 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
400 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
401 Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs)
402 }
403
404 /// [`open_segments`](Self::open_segments) over several files: a segment names
405 /// its source by index into `sources`, and a source join behaves exactly like
406 /// a cut inside one file — `start_sample` stays continuous, the decoder is
407 /// fresh either way. Each source contributes *its own* priming, packet table
408 /// and length, which is the whole reason the resolution is per source.
409 ///
410 /// A segment naming **no** source is a *gap*: that many seconds of silence
411 /// are synthesised into the stream as ordinary chunks. Real chunks, not a
412 /// pause — the master clock counts what the device has been fed, so a hole
413 /// that fed nothing would stall the whole timeline on it.
414 ///
415 /// A segment naming a source that has **no track** is the same silence: a
416 /// clip of a silent file is a hole with a picture over it, and the timeline
417 /// let it in on exactly that footing ([`crate::PlaybackSession::import`]).
418 ///
419 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
420 /// is empty or its first entry has no AAC track; a later source that
421 /// disagrees on *layout* is an `Err` — import refuses those up front (one
422 /// timeline, one output device), this is the backstop. A source at another
423 /// sample rate is not one of those: it is resampled, per segment.
424 pub fn open_multi_segments(
425 sources: &[PathBuf],
426 segs: &[(Option<usize>, f64, f64)],
427 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
428 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
429 Self::open_multi_streams(&sources, segs)
430 }
431
432 /// [`open_multi_segments`](Self::open_multi_segments) with each source
433 /// naming *which* of its audio streams to decode — files carrying several
434 /// (a remux with one track per language) are otherwise stuck on their first.
435 /// The index counts audio tracks in file order, as
436 /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not
437 /// exist or does not decode is an `Err` here, never a panic.
438 pub fn open_multi_streams(
439 sources: &[(PathBuf, usize)],
440 segs: &[(Option<usize>, f64, f64)],
441 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
442 Self::open_multi_streams_eq(sources, segs, &[])
443 }
444
445 /// [`open_multi_streams`](Self::open_multi_streams) with an equalizer per
446 /// segment: `eqs[i]` is what segment `i` plays through, `None` for one that
447 /// plays flat. Filtering happens **per segment**, inside the worker, before
448 /// anything is mixed -- two clips with different curves must not be blurred
449 /// into one another, and a segment's filter memory starts clean and dies
450 /// with it, which is also what makes a seek a reset for free.
451 ///
452 /// A parallel list, not a fourth tuple element: see
453 /// [`crate::Project::audio_eqs_from`], which is what builds it. A list
454 /// shorter than `segs` (the empty one every plain caller passes) means the
455 /// rest play flat, so a mismatch cannot panic and cannot silently shift a
456 /// curve onto the wrong clip.
457 pub fn open_multi_streams_eq(
458 sources: &[(PathBuf, usize)],
459 segs: &[(Option<usize>, f64, f64)],
460 eqs: &[Option<EqParams>],
461 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
462 Self::open_multi_streams_speed(sources, segs, eqs, &[])
463 }
464
465 /// [`open_multi_streams_eq`](Self::open_multi_streams_eq) with a *rate* per
466 /// segment as well: `speeds[i]` says how fast segment `i` is read and how
467 /// much timeline it owes ([`crate::project::Stretch`]), `None` for one at
468 /// real time. [`crate::Project::audio_speeds_from`] is what builds it, beside
469 /// the very list the segments come from.
470 ///
471 /// Resampling happens **per segment**, inside the worker and before the mix,
472 /// for the equalizer's reasons: two clips at two speeds must not be read
473 /// into one another, and the interpolator's memory dies with the segment. A
474 /// list shorter than `segs` (the empty one every plain caller passes) means
475 /// the rest play at real time, so nothing here can shift a rate onto the
476 /// wrong clip and a project with no speeds decodes exactly the samples it
477 /// always did.
478 pub fn open_multi_streams_speed(
479 sources: &[(PathBuf, usize)],
480 segs: &[(Option<usize>, f64, f64)],
481 eqs: &[Option<EqParams>],
482 speeds: &[Option<crate::project::Stretch>],
483 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
484 Self::open_multi_streams_speed_at(sources, segs, eqs, speeds, None)
485 }
486
487 /// [`open_multi_streams_speed`] with the project's own rate, when one was
488 /// picked ([`crate::edith::Document::sample_rate`]), overriding the source's
489 /// derived one. The per-segment [`Rate`] chain below already conforms any
490 /// segment whose own rate differs from `meta.sample_rate`, so naming a rate
491 /// here costs nothing new -- it only changes which rate that chain conforms
492 /// *to*.
493 pub fn open_multi_streams_speed_at(
494 sources: &[(PathBuf, usize)],
495 segs: &[(Option<usize>, f64, f64)],
496 eqs: &[Option<EqParams>],
497 speeds: &[Option<crate::project::Stretch>],
498 sample_rate: Option<u32>,
499 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
500 // No fades on this path, so the fps a `Fade` would be rescaled by is
501 // never read; any finite value does.
502 Self::open_multi_streams_speed_at_fade(sources, segs, eqs, speeds, &[], 1.0, sample_rate)
503 }
504
505 /// [`open_multi_streams_speed_at`](Self::open_multi_streams_speed_at) with a
506 /// fade envelope per segment: `fades[i]` is what segment `i` plays through
507 /// ([`emit`]'s last effect, after the rate and the equalizer), built the
508 /// same way `eqs` and `speeds` are -- one entry per `segs`, a short list
509 /// meaning flat from there on. `fps` is the timeline rate each `Fade` was
510 /// built at ([`crate::Project::audio_fades_from`]) -- this is the one
511 /// place that rate meets the audio one ([`crate::project::Fade::scaled`]).
512 pub fn open_multi_streams_speed_at_fade(
513 sources: &[(PathBuf, usize)],
514 segs: &[(Option<usize>, f64, f64)],
515 eqs: &[Option<EqParams>],
516 speeds: &[Option<crate::project::Stretch>],
517 fades: &[Option<crate::project::Fade>],
518 fps: f64,
519 sample_rate: Option<u32>,
520 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
521 Self::open_lane(sources, segs, eqs, speeds, fades, fps, sample_rate, None)
522 }
523
524 /// [`open_multi_streams_speed_at_fade`](Self::open_multi_streams_speed_at_fade)
525 /// with the timeline's width given instead of derived from this lane alone.
526 /// A mix has one width for every lane ([`mix_width`]): a lane whose own
527 /// sources are all mono must still run at the mix's width, or its samples
528 /// are summed as frames of the wrong size and it plays at half its length.
529 #[allow(
530 clippy::too_many_arguments,
531 reason = "one private opener behind the public family; the parameters are the public ones plus the width"
532 )]
533 fn open_lane(
534 sources: &[(PathBuf, usize)],
535 segs: &[(Option<usize>, f64, f64)],
536 eqs: &[Option<EqParams>],
537 speeds: &[Option<crate::project::Stretch>],
538 fades: &[Option<crate::project::Fade>],
539 fps: f64,
540 sample_rate: Option<u32>,
541 width: Option<u16>,
542 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
543 // Every source the segments name is opened here, once, before the
544 // timeline's width is settled. The width is the *widest* of them: a mono
545 // voiceover first on the lane with a stereo music bed under it used to
546 // pin the whole mix to mono and fold the bed down with it. The rate and
547 // the length are still the first opened source's, as they always were.
548 // A source with no audio track at all is silence -- its segments are
549 // silence, exactly as a gap's are, and the slot stays empty to say so --
550 // and a source that cannot be opened is an error once a segment names it.
551 let mut named = vec![false; sources.len()];
552 for &(source, ..) in segs {
553 if let Some(source) = source {
554 *named
555 .get_mut(source)
556 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))? = true;
557 }
558 }
559 // The *rate* is not held to the timeline's: a source written at another
560 // one is read through its segment's [`Resample`], the very interpolator a
561 // speeded clip already goes through, so it plays at the pitch it was
562 // recorded at. The layout is held: see the width check below. A still
563 // image has no track by definition.
564 // The length is still the first non-image source's that opens, named
565 // or not, as it always was: an unnamed source is opened for that alone, and
566 // one that cannot be opened is skipped rather than refused. Only the named
567 // ones take part in the width and the rate, and only they are played.
568 let mut opened: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
569 for (at, (path, stream)) in sources.iter().enumerate() {
570 if crate::is_image(path) {
571 continue;
572 }
573 opened[at] = if named[at] {
574 Track::open(path, *stream)?
575 } else {
576 Track::open(path, *stream).ok().flatten()
577 };
578 }
579 let Some(first_at) = opened.iter().position(Option::is_some) else {
580 return Ok(None);
581 };
582 let first = opened[first_at].as_ref().expect("found above");
583 // The rate, when no caller picked one: the highest of the named sources'
584 // (see [`mix_rate`]). A lane of only unnamed sources falls back to the
585 // first one that opened.
586 let rate = sample_rate.unwrap_or_else(|| {
587 mix_rate(
588 opened
589 .iter()
590 .zip(&named)
591 .filter(|(_, named)| **named)
592 .filter_map(|(track, _)| track.as_ref())
593 .map(|t| t.sample_rate()),
594 )
595 .unwrap_or_else(|| first.sample_rate())
596 });
597 // The length is counted in samples of the first source's own rate, so it
598 // is restated at the mix's rate: the same seconds either way.
599 let length = first.total_samples().map(|n| {
600 n.saturating_mul(u64::from(rate)) / u64::from(first.sample_rate().max(1))
601 });
602 let meta = AudioMeta {
603 sample_rate: rate,
604 channels: width.unwrap_or_else(|| {
605 opened
606 .iter()
607 .zip(&named)
608 .filter(|(_, named)| **named)
609 .filter_map(|(track, _)| track.as_ref())
610 .map(|t| t.channels())
611 .max()
612 .unwrap_or_else(|| first.channels())
613 }),
614 total_samples: length,
615 };
616
617 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
618 for (source, track) in opened.into_iter().enumerate() {
619 let Some(track) = track.filter(|_| named[source]) else {
620 continue;
621 };
622 // One output device carries one width, and everything wider than a
623 // pair is already folded to one. A mono source is the one exception
624 // (DEBT #46): [`widen`] duplicates it into every channel of a stereo
625 // timeline. The same gate as [`PlaybackSession`]'s own
626 // ([`crate::playback::audio_matches_probed`]), so what plays exports.
627 let mono_into_wider = track.channels() == 1 && meta.channels > 1;
628 if track.channels() != meta.channels && !mono_into_wider {
629 return Err(format!(
630 "source {source} is {} ch, the timeline is {} ch",
631 track.channels(),
632 meta.channels
633 )
634 .into());
635 }
636 track.check_decoder()?;
637 tracks[source] = Some(track);
638 }
639
640 let owed_by_segment = owed_samples(segs, speeds, meta.sample_rate);
641 // The segments played backwards, as the blocks they are decoded in
642 // (`reverse_blocks`), beside the segment list the way the rate chains are.
643 let mut reversed: Vec<Option<Vec<Segment>>> = segs.iter().map(|_| None).collect();
644 let segments: Vec<Segment> = segs
645 .iter()
646 .enumerate()
647 // A gap, and a source with no track to decode, are the same stretch
648 // of nothing: as many frames of silence as the window is long.
649 .map(|(i, &(source, start_secs, end_secs))| {
650 match source.and_then(|source| Some((source, tracks[source].as_ref()?))) {
651 Some((source, track)) => {
652 let mut seg = track.segment(source, start_secs, end_secs);
653 // A plain window at the mix rate reads exactly what it owes:
654 // its end is set from the running count, not the source's own
655 // rounding, so the cuts never drift against the picture. A
656 // reversed one at real time is as plain as a forward one: it
657 // reads the same window, last to first.
658 let backwards = speeds.get(i).and_then(Option::as_ref).is_some_and(|s| s.reverse);
659 let plain = speeds.get(i).is_none_or(|s| s.as_ref().is_none_or(crate::project::Stretch::is_straight));
660 if let (true, true, Some(owed)) = (
661 plain,
662 track.sample_rate() == meta.sample_rate,
663 owed_by_segment[i],
664 ) {
665 seg.media_end = seg.media_target + owed;
666 }
667 if backwards {
668 reversed[i] = Some(reverse_blocks(track, source, start_secs, &seg));
669 }
670 seg
671 }
672 None => Segment::silence(owed_by_segment[i].unwrap_or(
673 ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
674 )),
675 }
676 })
677 .collect();
678 // Chunk numbering is continuous across every join, counted from the first
679 // segment's audible start in its own source (see `open_segments`).
680 let timeline = segments.first().map_or(0, |s| match s.source {
681 Some(source) => {
682 let track = tracks[source].as_ref().expect("opened above");
683 // ...in *timeline* frames, which is not the source's own count
684 // when it was written at another rate. Integer, so the equal-rate
685 // case -- every project before this -- is the number it always was.
686 let at = s.media_target.saturating_sub(track.priming());
687 at.saturating_mul(u64::from(meta.sample_rate))
688 / u64::from(track.sample_rate().max(1))
689 }
690 None => 0,
691 });
692
693 // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so
694 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
695 // without making a pause take a second to bite.
696 // One filter per segment, built here where the rate and the layout are
697 // known and off the thread that will run it. An identity curve costs a
698 // branch and nothing else ([`EqState::process`]), and a segment with no
699 // curve at all is not even that.
700 let eqs: Vec<Option<EqState>> = segments
701 .iter()
702 .enumerate()
703 .map(|(i, _)| {
704 eqs.get(i)
705 .and_then(Option::as_ref)
706 .map(|p| EqState::new(p, meta.sample_rate, meta.channels))
707 })
708 .collect();
709
710 // One rate chain per segment that needs one, built where the sample
711 // rate is known: what the timeline owes it is seconds there and frames
712 // here.
713 //
714 // Two things ask for one, and they are NOT the same thing: a source
715 // written at a rate other than the timeline's is a *rate conversion*
716 // -- reading the samples at the ratio of the two rates is what keeps
717 // a 48 kHz file's pitch on a 44.1 kHz timeline, and is the resampler's
718 // whole duty now. A clip whose own [`Speed`] is not real time is a
719 // *time* change: the resample hands the stretch a pitch-true stream
720 // and the stretch hands the timeline the clip's compressed or
721 // stretched seconds with every period of the signal kept (the tape
722 // effect this used to be -- one resample at the speed -- moved the
723 // pitch with the rate). A segment with neither has no chain at all
724 // and reaches the mixer with the decoder's own samples, byte for
725 // byte, as it always did.
726 let speeds: Vec<Option<Rate>> = segments
727 .iter()
728 .zip(segs)
729 .enumerate()
730 .map(|(i, (seg, _))| {
731 let rate = seg
732 .source
733 .and_then(|source| tracks[source].as_ref())
734 .map_or(meta.sample_rate, Track::sample_rate);
735 let ratio = f64::from(rate) / f64::from(meta.sample_rate.max(1));
736 // A direction alone is no change of time: it needs no stretch.
737 let stretch = speeds
738 .get(i)
739 .and_then(Option::as_ref)
740 .filter(|s| !s.is_straight());
741 if stretch.is_none() && rate == meta.sample_rate {
742 return None;
743 }
744 // A pitch shift is a stretch and a resample together (see [`Stretch::pitch`]):
745 // the resample reads `2^(pitch/12)` times as fast, so the pitch moves by that,
746 // and the stretch takes back the same factor, so the length does not change.
747 let pitch = stretch.map_or(1.0, crate::project::Stretch::pitch_ratio);
748 let channels = usize::from(meta.channels);
749 // A speeded clip states the timeline it owes; a plain one owes
750 // the window it was placed for, and an open-ended window owes
751 // whatever its source has ([`Resample::UNBOUNDED`]).
752 let owed = match owed_by_segment[i] {
753 Some(frames) => frames.min(Resample::UNBOUNDED - 1),
754 None => Resample::UNBOUNDED,
755 };
756 Some(match stretch {
757 // A rate conversion alone: the resampler owns the
758 // segment's promise, as it always has.
759 None => Rate {
760 resample: Resample::new(ratio, owed),
761 stretch: None,
762 },
763 // A speeded clip: the resample is only the rate
764 // conversion -- unbounded, because the ratio is all it
765 // is asked for -- and the stretch lands the timeline's
766 // frames exactly.
767 Some(s) => Rate {
768 resample: Resample::new(ratio * pitch, Resample::UNBOUNDED),
769 stretch: Some(TimeStretch::new(
770 s.step / pitch,
771 owed,
772 channels,
773 // Samples per timeline frame: what turns the ramp's
774 // frames into the stretch's own samples.
775 s.ramp
776 .map(|r| (r.scaled(1.0 / pitch), f64::from(meta.sample_rate) / s.fps)),
777 )),
778 },
779 })
780 })
781 .collect();
782
783 // One [`crate::project::Fade`] per segment, exactly the eq and speed
784 // lists' rule: a short `fades` (the empty one every plain caller
785 // passes) means the rest play flat, and it is cloned rather than
786 // built here because [`Project::audio_fades_from`] already resolved
787 // each clip's own frame count against where this segment lands --
788 // in timeline frames, though, which is `fps`-relative and not yet
789 // the rate `Fade::apply` will count samples at; `.scaled` re-counts
790 // it in frames of `meta.sample_rate` now that this is known.
791 let fade_ratio = f64::from(meta.sample_rate) / fps;
792 let fades: Vec<Option<crate::project::Fade>> = segments
793 .iter()
794 .enumerate()
795 .map(|(i, _)| {
796 fades
797 .get(i)
798 .cloned()
799 .flatten()
800 .map(|f| f.scaled(fade_ratio))
801 })
802 .collect();
803
804 let (tx, rx) = sync_channel(32);
805 thread::Builder::new()
806 .name("audio-decode".into())
807 .spawn(move || {
808 run(Worker {
809 tracks,
810 channels: meta.channels as usize,
811 segments,
812 eqs,
813 speeds,
814 fades,
815 reversed,
816 timeline,
817 tx,
818 })
819 })?;
820 Ok(Some((meta, rx)))
821 }
822
823 /// Every audio lane of a timeline, summed into one stream: `lanes` is one
824 /// play list per lane, each in the shape
825 /// [`open_multi_streams`](Self::open_multi_streams) takes, and what comes
826 /// out is what the device hears -- the lanes decoded side by side and added
827 /// sample for sample, clamped to `[-1, 1]` so a loud pair cannot wrap the
828 /// output.
829 ///
830 /// **One lane is not mixed at all**: it is `open_multi_streams` verbatim, so
831 /// a timeline with a single audio lane decodes exactly the samples it always
832 /// did, down to the bit and down to the thread count.
833 ///
834 /// Lengths need not agree: a lane that has run out contributes silence to
835 /// what is left, which is what a shorter lane means. Each lane keeps its own
836 /// gap rule -- a hole in it is real silence from its own worker, not a
837 /// skipped chunk -- so the sum feeds the master clock a sample per sample of
838 /// timeline however the lanes are arranged. `start_sample` numbers from the
839 /// first lane's own start (see [`AudioChunk`]).
840 pub fn open_mixed_streams(
841 sources: &[(PathBuf, usize)],
842 lanes: &[Vec<(Option<usize>, f64, f64)>],
843 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
844 Self::open_mixed_streams_eq(sources, lanes, &[])
845 }
846
847 /// [`open_mixed_streams`](Self::open_mixed_streams) with
848 /// [`open_multi_streams_eq`](Self::open_multi_streams_eq)'s per-segment
849 /// equalizers, one list per lane -- [`crate::Project::audio_eqs_from`] is
850 /// what shapes them.
851 ///
852 /// Filtering is each lane's worker's own business and therefore happens
853 /// **before** the sum: a clip's curve reaches that clip's samples and stops
854 /// there, where filtering the mix would smear every lane's curve over
855 /// everything playing at the same instant. A missing or short list plays
856 /// flat, as it does one lane down.
857 pub fn open_mixed_streams_eq(
858 sources: &[(PathBuf, usize)],
859 lanes: &[Vec<(Option<usize>, f64, f64)>],
860 eqs: &[Vec<Option<EqParams>>],
861 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
862 Self::open_mixed_streams_speed(sources, lanes, eqs, &[])
863 }
864
865 /// [`open_mixed_streams_eq`](Self::open_mixed_streams_eq) with
866 /// [`open_multi_streams_speed`](Self::open_multi_streams_speed)'s per-segment
867 /// rates, one list per lane -- [`crate::Project::audio_speeds_from`] is what
868 /// shapes them, off the same walk the segments come from.
869 ///
870 /// A resample is each lane's worker's own business and happens **before**
871 /// the sum, exactly as the filtering does: every lane still hands the mixer
872 /// as many samples as the timeline says, so the lanes stay sample-aligned by
873 /// construction and a mix is still an add.
874 pub fn open_mixed_streams_speed(
875 sources: &[(PathBuf, usize)],
876 lanes: &[Vec<(Option<usize>, f64, f64)>],
877 eqs: &[Vec<Option<EqParams>>],
878 speeds: &[Vec<Option<crate::project::Stretch>>],
879 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
880 Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default())
881 }
882
883 /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two
884 /// settings that belong to the *mix* rather than to a clip: what each lane
885 /// is turned up or down by on its way into the sum (`gains[i]`, an
886 /// amplitude, [`crate::Project::audio_gains`] builds it) and the master
887 /// limiter the sum comes out through.
888 ///
889 /// Both live at the sum and nowhere else, which is what makes a lane volume
890 /// a *lane* volume and a limiter a master one: a gain applied per segment
891 /// would have to agree with itself across a lane's cuts, and a limiter
892 /// applied per lane would pump each lane against the others. A short or
893 /// empty gain list means the rest play as they are, exactly as a short eq
894 /// list means flat.
895 ///
896 /// Flat settings take the same path the mixer always took, down to the bit:
897 /// one lane at unity with the limiter off is still `open_multi_streams`
898 /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or
899 /// a limiter that is on, is what puts a single-lane timeline through the
900 /// mixer -- a sum of one, which is where both settings live.
901 pub fn open_mixed_streams_master(
902 sources: &[(PathBuf, usize)],
903 lanes: &[Vec<(Option<usize>, f64, f64)>],
904 eqs: &[Vec<Option<EqParams>>],
905 speeds: &[Vec<Option<crate::project::Stretch>>],
906 gains: &[f32],
907 limiter: Limiter,
908 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
909 Self::open_mixed_streams_master_at(sources, lanes, eqs, speeds, gains, limiter, None)
910 }
911
912 /// [`open_mixed_streams_master`] with the project's own rate
913 /// ([`crate::edith::Document::sample_rate`]) overriding the derived one, the
914 /// same rate every lane's meta agrees on ([`open_mixed_streams_live`]'s
915 /// invariant).
916 pub fn open_mixed_streams_master_at(
917 sources: &[(PathBuf, usize)],
918 lanes: &[Vec<(Option<usize>, f64, f64)>],
919 eqs: &[Vec<Option<EqParams>>],
920 speeds: &[Vec<Option<crate::project::Stretch>>],
921 gains: &[f32],
922 limiter: Limiter,
923 sample_rate: Option<u32>,
924 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
925 // No fades on this path -- see `open_multi_streams_speed_at`'s same
926 // placeholder.
927 Self::open_mixed_streams_master_at_fade(
928 sources,
929 lanes,
930 eqs,
931 speeds,
932 &[],
933 1.0,
934 gains,
935 &[],
936 &[],
937 limiter,
938 sample_rate,
939 )
940 }
941
942 /// [`open_mixed_streams_master_at`](Self::open_mixed_streams_master_at)
943 /// with a fade envelope per segment; see
944 /// [`open_mixed_streams_live_fade`](Self::open_mixed_streams_live_fade).
945 /// `fps` is [`open_multi_streams_speed_at_fade`](Self::open_multi_streams_speed_at_fade)'s.
946 #[allow(
947 clippy::too_many_arguments,
948 reason = "public mix openers form one family, each fixing one more argument of the next; a parameter struct would only rename the list at every step"
949 )]
950 pub fn open_mixed_streams_master_at_fade(
951 sources: &[(PathBuf, usize)],
952 lanes: &[Vec<(Option<usize>, f64, f64)>],
953 eqs: &[Vec<Option<EqParams>>],
954 speeds: &[Vec<Option<crate::project::Stretch>>],
955 fades: &[Vec<Option<crate::project::Fade>>],
956 fps: f64,
957 gains: &[f32],
958 ducks: &[Vec<Duck>],
959 voices: &[VoiceFx],
960 limiter: Limiter,
961 sample_rate: Option<u32>,
962 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
963 Self::open_mixed_streams_live_fade(
964 sources,
965 lanes,
966 eqs,
967 speeds,
968 fades,
969 fps,
970 gains,
971 ducks,
972 voices,
973 limiter,
974 None,
975 sample_rate,
976 )
977 }
978
979 /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the
980 /// mix left *reachable*: `live` is the handle the mixer picks its gains and
981 /// its limiter off between blocks, so a fader moved while the stream plays
982 /// is heard without the stream being rebuilt ([`MixControls`]).
983 ///
984 /// `gains`/`limiter` still say what it starts as -- they are what decides
985 /// whether there is a mixer at all -- and the handle is marked live only
986 /// when there is one. An export passes `None`: nothing can move under it.
987 #[allow(
988 clippy::too_many_arguments,
989 reason = "public mix openers form one family, each fixing one more argument of the next; a parameter struct would only rename the list at every step"
990 )]
991 pub fn open_mixed_streams_live(
992 sources: &[(PathBuf, usize)],
993 lanes: &[Vec<(Option<usize>, f64, f64)>],
994 eqs: &[Vec<Option<EqParams>>],
995 speeds: &[Vec<Option<crate::project::Stretch>>],
996 gains: &[f32],
997 limiter: Limiter,
998 live: Option<&Arc<MixControls>>,
999 sample_rate: Option<u32>,
1000 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
1001 // No fades on this path -- see `open_multi_streams_speed_at`'s same
1002 // placeholder.
1003 Self::open_mixed_streams_live_fade(
1004 sources,
1005 lanes,
1006 eqs,
1007 speeds,
1008 &[],
1009 1.0,
1010 gains,
1011 &[],
1012 &[],
1013 limiter,
1014 live,
1015 sample_rate,
1016 )
1017 }
1018
1019 /// [`open_mixed_streams_live`](Self::open_mixed_streams_live) with a fade
1020 /// envelope per segment as well: `fades[i]` is what segment `i` plays
1021 /// through -- [`crate::Project::audio_fades_from`] is what builds it, off
1022 /// the same walk the segments come from. A short or missing list means
1023 /// the rest play flat, the eq list's rule. `fps` is the timeline rate
1024 /// those fades were built at ([`crate::project::Fade::scaled`]).
1025 #[allow(
1026 clippy::too_many_arguments,
1027 reason = "public mix openers form one family, each fixing one more argument of the next; a parameter struct would only rename the list at every step"
1028 )]
1029 pub fn open_mixed_streams_live_fade(
1030 sources: &[(PathBuf, usize)],
1031 lanes: &[Vec<(Option<usize>, f64, f64)>],
1032 eqs: &[Vec<Option<EqParams>>],
1033 speeds: &[Vec<Option<crate::project::Stretch>>],
1034 fades: &[Vec<Option<crate::project::Fade>>],
1035 fps: f64,
1036 gains: &[f32],
1037 ducks: &[Vec<Duck>],
1038 voices: &[VoiceFx],
1039 limiter: Limiter,
1040 live: Option<&Arc<MixControls>>,
1041 sample_rate: Option<u32>,
1042 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
1043 let [first, ..] = lanes else {
1044 return Ok(None);
1045 };
1046 if !Self::is_mixed(lanes.len(), gains, limiter, voices) {
1047 let flat = Vec::new();
1048 let plain = Vec::new();
1049 let flat_fade = Vec::new();
1050 return Self::open_multi_streams_speed_at_fade(
1051 sources,
1052 first,
1053 eqs.first().unwrap_or(&flat),
1054 speeds.first().unwrap_or(&plain),
1055 fades.first().unwrap_or(&flat_fade),
1056 fps,
1057 sample_rate,
1058 );
1059 }
1060 // Settled once for the whole mix, as the width is: every lane is opened
1061 // at the same rate, so no lane's own sources pick a rate of their own.
1062 let (width, mix_rate) = Self::mix_format(sources, lanes)?;
1063 let sample_rate = sample_rate.or(mix_rate);
1064 let mut meta = None;
1065 let mut rxs = Vec::with_capacity(lanes.len());
1066 for (i, segs) in lanes.iter().enumerate() {
1067 // Every lane takes its meta from the same source, so the metas
1068 // agree by construction; `None` from any of them is a silent
1069 // timeline.
1070 let flat = Vec::new();
1071 let flat_fade = Vec::new();
1072 let plain = Vec::new();
1073 let Some((lane_meta, rx)) = Self::open_lane(
1074 sources,
1075 segs,
1076 eqs.get(i).unwrap_or(&flat),
1077 speeds.get(i).unwrap_or(&plain),
1078 fades.get(i).unwrap_or(&flat_fade),
1079 fps,
1080 sample_rate,
1081 width,
1082 )?
1083 else {
1084 return Ok(None);
1085 };
1086 // A lane with voice processors on runs them on its own stream, before
1087 // anything is summed ([`crate::voice`]); one without is left as it was.
1088 let rx = match voices.get(i).filter(|v| v.is_active()) {
1089 Some(fx) => crate::voice::spawn_stage(rx, fx, lane_meta.sample_rate, usize::from(lane_meta.channels)),
1090 None => rx,
1091 };
1092 meta = Some(lane_meta);
1093 rxs.push(rx);
1094 }
1095 let meta = meta.expect("at least one lane opened above");
1096 let (tx, rx) = sync_channel(32);
1097 let channels = usize::from(meta.channels);
1098 // One per lane, in the lanes' own order, padded with unity: a short
1099 // list is "as it is from here on", the eq list's rule.
1100 let mut gains = gains.to_vec();
1101 gains.resize(lanes.len(), 1.0);
1102 // Built here, off the thread that will run it, where the rate is known.
1103 let state = limiter
1104 .is_active()
1105 .then(|| LimiterState::new(&limiter, meta.sample_rate, channels));
1106 // One list per lane, padded with no duck: a short list is "unducked from here on".
1107 let mut ducks = ducks.to_vec();
1108 ducks.resize(lanes.len(), Vec::new());
1109 // Marked before the spawn rather than inside it: a caller asks this the
1110 // moment the open returns, and a flag set on the far thread would still
1111 // read dead.
1112 let live = live.map(|live| {
1113 live.live.store(true, Ordering::Release);
1114 live.clone()
1115 });
1116 let rate = meta.sample_rate;
1117 thread::Builder::new()
1118 .name("audio-mix".into())
1119 .spawn(move || {
1120 mix(
1121 &rxs,
1122 channels,
1123 MixState { gains, ducks, limiter: state },
1124 rate,
1125 live.as_deref(),
1126 &tx,
1127 )
1128 })?;
1129 Ok(Some((meta, rx)))
1130 }
1131
1132 /// The width and the rate every lane of a mix runs at, from the sources any
1133 /// lane names. The width is the widest of them (a mono source counts as
1134 /// mono, so a mono-only mix stays mono). Each lane used to derive its own
1135 /// from its own sources, which put a mono voice lane beside a stereo bed at
1136 /// one channel while the sum was two: the voice was then read as half as
1137 /// many frames, and ended at half its length. The rate is [`mix_rate`] over
1138 /// the same sources: a lane of its own would otherwise mix a 22.05 kHz
1139 /// voiceover at its own rate beside a 48 kHz bed. Each part is `None` when
1140 /// no lane names a source with an audio track.
1141 fn mix_format(
1142 sources: &[(PathBuf, usize)],
1143 lanes: &[Vec<(Option<usize>, f64, f64)>],
1144 ) -> crate::Result<(Option<u16>, Option<u32>)> {
1145 let mut width: Option<u16> = None;
1146 let mut rates = Vec::new();
1147 for &(source, ..) in lanes.iter().flatten() {
1148 let Some(source) = source else {
1149 continue;
1150 };
1151 let (path, stream) = sources
1152 .get(source)
1153 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
1154 if crate::is_image(path) {
1155 continue;
1156 }
1157 if let Some(track) = Track::open(path, *stream)? {
1158 width = Some(width.map_or(track.channels(), |w| w.max(track.channels())));
1159 rates.push(track.sample_rate());
1160 }
1161 }
1162 Ok((width, mix_rate(rates)))
1163 }
1164
1165 /// Whether these settings put the timeline through the **mixer**: more than
1166 /// one lane to sum, a lane off unity, or a limiter over the sum. Anything
1167 /// else is the single-lane flat path, which is `open_multi_streams`
1168 /// verbatim and has no mixer thread to talk to.
1169 ///
1170 /// Public to the crate because [`crate::PlaybackSession`] has to know the
1171 /// answer *before* the open now that it happens on another thread, and the
1172 /// answer must not be spelled out twice: what it decides is whether a fader
1173 /// is handed to a running mixer or rebuilds the stream.
1174 pub(crate) fn is_mixed(lanes: usize, gains: &[f32], limiter: Limiter, voices: &[VoiceFx]) -> bool {
1175 lanes > 1 || limiter.is_active() || gains.iter().any(|&g| g != 1.0) || voices.iter().any(VoiceFx::is_active)
1176 }
1177
1178 /// Why [`open`](Self::open) came back silent for a file that *has* sound:
1179 /// `Some(reason)` when there is an audio track in a codec this does not
1180 /// decode (an Opus web rip, say). `None` when the file is simply silent
1181 /// -- nothing to tell the user there. Header only, and only worth calling
1182 /// once the open has already returned no audio.
1183 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
1184 // An Ogg Speex stream is named, not decoded: the reason is what the import warns with.
1185 if crate::demux::is_ogg_speex(path.as_ref()) {
1186 return Ok(Some(crate::demux::SPEEX_REFUSAL.to_string()));
1187 }
1188 // Matroska: what symphonia reads out of one ([`Track::open`]) plus the
1189 // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder
1190 // ([`MkvAc3Track`]) and the Opus its own decoder takes; everything else
1191 // -- DTS, and whatever else no decoder here has -- is named rather than
1192 // left playing silent with no reason given. A Matroska file with no
1193 // audio track at all returns `None` here like any other silent file.
1194 if crate::demux::is_matroska(path.as_ref()) {
1195 let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else {
1196 return Ok(None);
1197 };
1198 let name = codec_display_name(&codec);
1199 // An AC-3 track that came up silent all the same is one that could
1200 // not be read -- a laced block, an unreadable syncframe -- and the
1201 // reader's own words are the ones worth showing.
1202 // A TrueHD track its decoder opens is sound, not an unsupported one.
1203 if matches!(MkvTruehdTrack::open(path.as_ref()), Ok(Some(_))) {
1204 return Ok(None);
1205 }
1206 // ...and so is a DTS track `ec-dts` opens; one it refuses (XLL) says why.
1207 if (crate::extaudio::is_mkv_dts(&codec) || crate::extaudio::is_mkv_mpeg_layer(&codec))
1208 && let Some(first) = crate::demux::matroska_audio_tracks(path.as_ref())?.first()
1209 {
1210 match crate::extaudio::ExtFileTrack::open_native(path.as_ref(), first.number) {
1211 Ok(Some(_)) => return Ok(None),
1212 Err(e) => {
1213 return Ok(Some(format!("the {name} track of this Matroska file cannot be decoded: {e}")));
1214 }
1215 Ok(None) => {}
1216 }
1217 }
1218 return Ok(Some(match MkvAc3Track::open(path.as_ref()) {
1219 Ok(Some(_)) => return Ok(None),
1220 // ...and the same question asked of the other reader, because a
1221 // refusal is a claim: a track symphonia's side really opens and
1222 // builds a decoder for is not one to tell the user about. This
1223 // is what stopped naming `A_OPUS` the moment Opus decoded.
1224 Ok(None) | Err(_)
1225 if SymTrack::open(path.as_ref())
1226 .ok()
1227 .flatten()
1228 .is_some_and(|t| t.decoder().is_ok()) =>
1229 {
1230 return Ok(None);
1231 }
1232 Ok(None) => format!(
1233 "the {name} track of this Matroska file cannot be decoded — {MKV_DECODED} are"
1234 ),
1235 Err(e) => format!("the {name} track of this Matroska file cannot be decoded: {e}"),
1236 }));
1237 }
1238 // A transport stream: the first sound track, if the build cannot decode it.
1239 if crate::demux::is_mpeg_system(path.as_ref()) {
1240 let file = crate::demux::ts::describe(path.as_ref())?;
1241 let flavor = crate::demux::ts::Flavor::of(path.as_ref());
1242 return Ok(file.audio.first().and_then(|a| match (&a.refusal, a.stream) {
1243 (Some(why), _) => Some(crate::demux::ts::refusal_text_for(why, false, flavor)),
1244 (None, None) => Some(crate::demux::ts::refusal_text_for(
1245 &format!("the {} audio track cannot be decoded", a.codec),
1246 false,
1247 flavor,
1248 )),
1249 _ => None,
1250 }));
1251 }
1252 // File order, out of `moov.traks`: naming a codec off a `HashMap` walk
1253 // would tell the user about a different track from one run to the next
1254 // on a film with two.
1255 let reader = mp4track::open(path.as_ref())?;
1256 // Flagged only when the decoders `open` itself would try cannot take the
1257 // first track: AC-3 first, then the AAC reader, as `open_track` orders
1258 // them. A track either one opens is playable, so not a refusal.
1259 if matches!(Ac3Track::open(path.as_ref(), 0), Ok(Some(_)))
1260 || matches!(Track::open(path.as_ref(), 0), Ok(Some(_)))
1261 {
1262 return Ok(None);
1263 }
1264 Ok(mp4track::audio_tracks(&reader).first().map(|&(_, stream)| {
1265 match stream.and_then(|s| mp4track::codec(&reader, s)) {
1266 Some(codec) => {
1267 format!("the {} audio track cannot be decoded — {MP4_DECODED} are", codec.name())
1268 }
1269 None => format!("the audio track is in a codec we cannot decode — {MP4_DECODED} are"),
1270 }
1271 }))
1272 }
1273
1274 /// The audio parameters of `path`'s `stream`, for checking an import
1275 /// against the timeline's first source: header only, no decoder and no
1276 /// worker. `Ok(None)` means no audio track — a silent file, which import
1277 /// pairs only with other silent files. A *named* stream that is not there
1278 /// or does not decode is an `Err`, as everywhere else.
1279 pub fn probe(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<AudioProbe>> {
1280 let Some(track) = Track::open(path.as_ref(), stream)? else {
1281 return Ok(None);
1282 };
1283 Ok(Some(AudioProbe {
1284 sample_rate: track.sample_rate(),
1285 channels: track.channels(),
1286 }))
1287 }
1288
1289 /// Every audio stream of `path`, in file order: an entry's `index` is the
1290 /// stream number [`open_multi_streams`](Self::open_multi_streams) takes.
1291 /// Header only, no decoder and no worker — and no filtering either, so a
1292 /// stream this engine cannot decode is listed with `decodable: false`
1293 /// instead of vanishing.
1294 ///
1295 /// An empty list means the file has no audio at all, which is a valid
1296 /// silent source.
1297 ///
1298 /// A standalone audio file ([`crate::is_audio`]) has exactly one stream by
1299 /// construction — one track, no picture beside it — so it is described from
1300 /// symphonia's own header rather than walked as an mp4, which an mp3 is not
1301 /// and an ALAC `.m4a` only half is.
1302 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
1303 let path = path.as_ref();
1304 crate::demux::refuse_speex(path)?;
1305 // A Matroska file lists one row per `TrackEntry` of audio -- a
1306 // dual-audio remux has two, and the second one used to be invisible --
1307 // numbered by [`mkv_stream_order`]: the track that already plays first,
1308 // then the rest in file order. A file whose header will not walk at all
1309 // is an `Err` here, as it is in [`Track::open`]: a listing that quietly
1310 // came back empty for a broken file is how a lane ends up silent with
1311 // nothing to go on. No audio track at all is an empty list, which is
1312 // the silent source it says it is.
1313 if crate::demux::is_matroska(path) {
1314 let tracks = crate::demux::matroska_audio_tracks(path)?;
1315 let mut streams = Vec::new();
1316 for (index, entry) in mkv_stream_order(path, &tracks)
1317 .into_iter()
1318 .map(|at| &tracks[at])
1319 .enumerate()
1320 {
1321 // The routing [`Track::open`] does, one row at a time, so a row
1322 // describes the track that would really open: AC-3 and E-AC-3
1323 // through the Dolby decoder's own reader, everything else
1324 // through symphonia. The AC-3 row describes what the decoder
1325 // *emits*, which is the stereo the §7.8 downmix hands the
1326 // timeline, not the 5.1 the file carries -- exactly as the mp4
1327 // AC-3 rows do.
1328 let ac3 = matches!(entry.codec.as_str(), "A_AC3" | "A_EAC3")
1329 .then(|| MkvAc3Track::open_track(path, entry.number).ok().flatten())
1330 .flatten();
1331 // A track symphonia cannot even describe is listed undecodable
1332 // by the name the container gives it, rather than taking the
1333 // whole listing down with it: the other language still plays.
1334 // TrueHD and MLP through their own decoder, the same way.
1335 let truehd = matches!(entry.codec.as_str(), "A_TRUEHD" | "A_MLP")
1336 .then(|| MkvTruehdTrack::open_track(path, entry.number).ok().flatten())
1337 .flatten();
1338 let ext = (crate::extaudio::is_mkv_dts(&entry.codec) || crate::extaudio::is_mkv_mpeg_layer(&entry.codec))
1339 .then(|| crate::extaudio::ExtFileTrack::open_native(path, entry.number).ok().flatten())
1340 .flatten();
1341 let sym = match (&ac3, &truehd, &ext) {
1342 (None, None, None) => SymTrack::open_track(path, entry.number).ok().flatten(),
1343 _ => None,
1344 };
1345 // What the row describes: the Dolby decoders' own output where one
1346 // took the track, symphonia's where it did not.
1347 let (channels, sample_rate) = match (&ac3, &truehd) {
1348 (Some(t), _) => (t.channels, t.sample_rate),
1349 (_, Some(t)) => (t.channels, t.sample_rate),
1350 _ if ext.is_some() => ext.as_ref().map_or((0, 0), |t| (t.channels(), t.sample_rate)),
1351 _ => sym
1352 .as_ref()
1353 .map_or((0, 0), |t| (t.channels, t.sample_rate)),
1354 };
1355 streams.push(StreamInfo {
1356 index,
1357 bit_depth: None,
1358 bitrate: None,
1359 codec: mkv_codec_name(&entry.codec),
1360 channels,
1361 sample_rate,
1362 lang: (entry.language != "und" && !entry.language.is_empty())
1363 .then(|| entry.language.clone()),
1364 // No width gate any more: `channels` is what reaches the
1365 // timeline, which [`downmix`] makes a pair out of whatever
1366 // the file carries. What greys a row out is a codec nothing
1367 // here decodes, and nothing else.
1368 decodable: ac3.is_some()
1369 || truehd.is_some()
1370 || ext.is_some()
1371 || sym.is_some_and(|t| t.decoder().is_ok()),
1372 });
1373 }
1374 return Ok(streams);
1375 }
1376 // A transport stream lists every sound track of its program in PMT order, the ones
1377 // this build has no decoder for (LATM and the like) greyed out by name.
1378 if crate::demux::is_mpeg_system(path) {
1379 let file = crate::demux::ts::describe(path)?;
1380 return Ok(file
1381 .audio
1382 .iter()
1383 .enumerate()
1384 .map(|(index, a)| {
1385 let track = a
1386 .stream
1387 .and_then(|_| crate::demux::ts::TsAudio::open(path, index).ok().flatten());
1388 StreamInfo {
1389 index,
1390 bit_depth: crate::demux::ts::pcm_depth(a.codec_id),
1391 bitrate: None,
1392 codec: a.codec.clone(),
1393 channels: track.as_ref().map_or(a.channels, |t| t.channels()),
1394 sample_rate: track.as_ref().map_or(a.sample_rate, |t| t.sample_rate),
1395 lang: a.language.clone().filter(|l| l != "und"),
1396 decodable: track.is_some_and(|t| t.decoder().is_ok()),
1397 }
1398 })
1399 .collect());
1400 }
1401 if crate::is_audio(path) {
1402 if let Some(track) = crate::extaudio::ExtFileTrack::open(path, 0)? {
1403 return Ok(vec![StreamInfo {
1404 index: 0,
1405 codec: track.codec_name().into(),
1406 channels: track.channels(),
1407 sample_rate: track.sample_rate,
1408 lang: None,
1409 decodable: track.decoder().is_ok(),
1410 bit_depth: None,
1411 bitrate: None,
1412 }]);
1413 }
1414 let track = SymTrack::open_required(path)?;
1415 return Ok(vec![StreamInfo {
1416 index: 0,
1417 codec: track.codec.into(),
1418 channels: track.channels,
1419 sample_rate: track.sample_rate,
1420 // Neither the mp3 nor the wav headers carry an ISO-639 tag the
1421 // way an mdhd does, and a lone track needs no telling apart.
1422 lang: None,
1423 decodable: track.decoder().is_ok(),
1424 bit_depth: None,
1425 bitrate: None,
1426 }]);
1427 }
1428 let reader = mp4track::open(path)?;
1429 // The playing time the header states, which is what a track's bytes are
1430 // divided by for its rate. A header that states none leaves the rate out.
1431 let secs = reader.duration_secs();
1432 Ok(mp4track::audio_tracks(&reader)
1433 .into_iter()
1434 .enumerate()
1435 .map(|(index, (track_id, stream))| {
1436 let codec = stream.and_then(|s| mp4track::codec(&reader, s));
1437 let bitrate = stream
1438 .zip(secs)
1439 .and_then(|(s, secs)| {
1440 crate::demux::bits_per_second(mp4track::sample_bytes(&reader, s), secs)
1441 });
1442 let aac = codec == Some(CodecId::Aac);
1443 // An AC-3 track is described through its own reader: what is
1444 // listed is the *decoded* shape -- stereo, because that is what
1445 // the §7.8 downmix hands the timeline (see [`Ac3Track`]).
1446 let ac3 = (!aac)
1447 .then(|| Ac3Track::open(path, index).ok().flatten())
1448 .flatten();
1449 // DTS, ADPCM, A-law / mu-law and AMR go through `ec-probe`'s reader.
1450 let ext = (!aac && ac3.is_none() && codec.is_some_and(crate::extaudio::is_ext_codec))
1451 .then(|| crate::extaudio::ExtFileTrack::open(path, index).ok().flatten())
1452 .flatten();
1453 let lang = mp4track::language(&reader, track_id).filter(|l| l != "und");
1454 let profile = stream
1455 .and_then(|s| mp4track::extradata(&reader, s))
1456 .and_then(|asc| asc_fields(&asc).ok())
1457 .map(|(profile, _, _)| profile);
1458 StreamInfo {
1459 index,
1460 bit_depth: None,
1461 bitrate,
1462 codec: match (aac, &ac3) {
1463 (true, _) => "aac",
1464 (_, Some(_)) => "ac-3",
1465 _ => match codec.filter(|c| crate::extaudio::is_ext_codec(*c)) {
1466 Some(c) => c.name(),
1467 None => "unknown",
1468 },
1469 }
1470 .into(),
1471 channels: match (&ac3, &ext) {
1472 (Some(t), _) => t.channels,
1473 (_, Some(t)) => t.channels(),
1474 _ => stream.map_or(0, |s| mp4track::channels(&reader, s) as u16),
1475 },
1476 sample_rate: match (&ac3, &ext) {
1477 (Some(t), _) => t.sample_rate,
1478 (_, Some(t)) => t.sample_rate,
1479 _ => stream.map_or(0, |s| mp4track::sample_rate(&reader, s)),
1480 },
1481 lang,
1482 // The profile still gates -- the writer rebuilds an
1483 // AudioSpecificConfig and calls it LC -- but the layout no
1484 // longer does: a 5.1 or 7.1 AAC track decodes through
1485 // `ec-aac` and folds to the pair the timeline carries
1486 // ([`aac_decoder`]).
1487 decodable: ac3.is_some()
1488 || ext.is_some()
1489 || aac && matches!(profile, Some(AAC_LC | AAC_SBR | AAC_PS)),
1490 }
1491 })
1492 .collect())
1493 }
1494
1495 /// How long `path`'s audio plays, in seconds. `Ok(None)` for a silent file.
1496 ///
1497 /// A standalone audio file is a source with no frame count of its own, so
1498 /// this is what its length on the timeline is derived from. Taken from the
1499 /// header where there is one; a stream that does not say — a bare mp3 with
1500 /// no Xing header is the usual one — is *decoded* to find out, which is
1501 /// linear in its length (~0.5 ms per source second) and happens once, at
1502 /// import, rather than per repaint.
1503 ///
1504 /// Stream 0: this answers for a standalone audio file, whose only stream
1505 /// that is. A video source's length is its frame count, never this.
1506 pub fn duration_secs(path: impl AsRef<Path>) -> crate::Result<Option<f64>> {
1507 Self::stream_duration_secs(path, 0)
1508 }
1509
1510 /// [`duration_secs`](Self::duration_secs) for audio stream `stream` of the file: its own
1511 /// playing time, which can be longer than the picture a video file carries.
1512 pub fn stream_duration_secs(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<f64>> {
1513 let path = path.as_ref();
1514 let timed = Self::decoded_secs(path, stream);
1515 if let Ok(Some(secs)) = timed {
1516 return Ok(Some(secs));
1517 }
1518 // A track nothing here opens or decodes cannot be timed by reading it, but the
1519 // file's own header states how long it plays: that length is what it is held to,
1520 // so its sound comes in silent rather than refused for want of a duration.
1521 match crate::demux::header_audio_secs(path, stream) {
1522 Some(secs) => Ok(Some(secs)),
1523 None => timed,
1524 }
1525 }
1526
1527 /// [`stream_duration_secs`](Self::stream_duration_secs) by reading the track: its sample
1528 /// count, or a decode of it when the count is not stated.
1529 fn decoded_secs(path: &Path, stream: usize) -> crate::Result<Option<f64>> {
1530 let Some(track) = Track::open(path, stream)? else {
1531 return Ok(None);
1532 };
1533 let rate = f64::from(track.sample_rate().max(1));
1534 if let Some(total) = track.total_samples() {
1535 return Ok(Some(total as f64 / rate));
1536 }
1537 drop(track);
1538 let Some((meta, rx)) = Self::open(path)? else {
1539 return Ok(None);
1540 };
1541 let channels = usize::from(meta.channels.max(1));
1542 let last = rx.into_iter().fold(0, |_, chunk| {
1543 chunk.start_sample + (chunk.samples.len() / channels) as u64
1544 });
1545 Ok(Some(last as f64 / f64::from(meta.sample_rate.max(1))))
1546 }
1547
1548 /// The raw AAC packets covering `segs` — the same half-open source-second
1549 /// windows [`open_segments`](Self::open_segments) decodes — copied out
1550 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
1551 /// straight into an mp4 writer, which is how an export keeps its sound exact
1552 /// wherever the edit lets it (a lane carrying an equalizer cannot be copied
1553 /// and is re-encoded instead -- `export::encode_audio`).
1554 ///
1555 /// Cut points do not land on 1024-sample boundaries, so each segment is
1556 /// rounded to whole packets against an error carried across the joins (see
1557 /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the
1558 /// asked-for length however many cuts there are, instead of drifting out of
1559 /// lip sync one rounding at a time.
1560 ///
1561 /// The run starts one packet before the first audible one, which a reader
1562 /// drops as encoder priming — for a segment list starting at 0.0 that is the
1563 /// source's own priming packet, so the copy is the whole track from sample 1.
1564 ///
1565 /// `Ok(None)` for a file with no AAC track, and for an empty segment list.
1566 ///
1567 /// corner-cut: the first packet after an *interior* join decodes without its
1568 /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is
1569 /// re-encoding just the join packets, which needs an encoder we do not have.
1570 pub fn copy_segments(
1571 path: impl AsRef<Path>,
1572 segs: &[(f64, f64)],
1573 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
1574 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
1575 Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs)
1576 }
1577
1578 /// [`copy_segments`](Self::copy_segments) over several files, segments naming
1579 /// their source by index into `sources`. The rounding debt is carried across
1580 /// a source join exactly as across a cut inside one file, so the bound stays
1581 /// half a packet over the whole list however many files it spans, and the
1582 /// extra priming packet is still the very first segment's alone.
1583 ///
1584 /// Every source that *has* a track must declare the same
1585 /// [`AacTrackParams`]: the copy becomes one output track with one esds.
1586 /// Import refuses a mismatch up front; the check here is the backstop.
1587 ///
1588 /// A segment naming **no** source is a gap, and is copied as that many
1589 /// packets of [`silent_packet`] silence — the rounding debt carried through
1590 /// it like any other, so the hole occupies its exact duration and the audio
1591 /// after it stays in sync with the picture. A gap the track *opens* on gets
1592 /// one silent packet more, which is the priming a reader drops. A segment
1593 /// naming a *silent* source is written the same way: a clip whose file has
1594 /// no audio track is a hole with a picture over it, and the timeline it
1595 /// joined already said so ([`crate::PlaybackSession::import`]).
1596 pub fn copy_multi_segments(
1597 sources: &[PathBuf],
1598 segs: &[(Option<usize>, f64, f64)],
1599 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
1600 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
1601 Self::copy_multi_streams(&sources, segs)
1602 }
1603
1604 /// [`copy_multi_segments`](Self::copy_multi_segments) with each source
1605 /// naming *which* of its audio streams to copy — the same `(path, stream)`
1606 /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two
1607 /// take it in the same shape on purpose: an export that copied a different
1608 /// stream from the one the timeline played would be a file that sounds
1609 /// nothing like what was edited, and nothing would say so.
1610 pub fn copy_multi_streams(
1611 sources: &[(PathBuf, usize)],
1612 segs: &[(Option<usize>, f64, f64)],
1613 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
1614 // The output track is declared from the first source that has one --
1615 // not simply the first one named, which may be a silent clip. Such a
1616 // clip defines no rate and no layout; it is written as silence below
1617 // and the track goes on being the audible sources' track.
1618 let mut tracks: Vec<Option<Option<AacTrack>>> = sources.iter().map(|_| None).collect();
1619 let mut first = None;
1620 for &(source, ..) in segs {
1621 let Some(source) = source else { continue };
1622 if let Some(track) = source_at(&mut tracks, sources, source)? {
1623 first = Some(track.track_params());
1624 break;
1625 }
1626 }
1627 let Some(params) = first else {
1628 return Ok(None); // no segments, or nothing but silence
1629 };
1630
1631 let sample_rate = params.sample_rate;
1632 let mut err = 0i64;
1633 let mut packets: Vec<AacPacket> = Vec::new();
1634 for (at, &(source, start_secs, end_secs)) in segs.iter().enumerate() {
1635 // The last segment is the only one no later join pays a rounding
1636 // debt in, so its run rounds up ([`packet_run_last`]).
1637 let last = at + 1 == segs.len();
1638 // A gap, and a clip whose source carries no track, are the same hole
1639 // to write: silence for as long as the window is.
1640 let named = match source {
1641 Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)),
1642 None => None,
1643 };
1644 let Some((source, track)) = named else {
1645 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
1646 let bytes = silent_packet(params.chan_conf)?;
1647 // A reader drops the first packet of an AAC track as the
1648 // encoder's priming. When the track opens on a hole, that has to
1649 // come out of one *extra* packet of silence: dropped out of the
1650 // hole itself it would shorten it, and everything after the hole
1651 // would play a packet early. It is not part of the run, so it
1652 // owes the rounding debt nothing.
1653 let priming = u32::from(packets.is_empty());
1654 let run = match last {
1655 true => packet_run_last(&mut err, ideal, u32::MAX),
1656 false => packet_run(&mut err, ideal, u32::MAX),
1657 };
1658 for _ in 0..run + priming {
1659 packets.push(AacPacket {
1660 bytes: bytes.clone(),
1661 samples: SAMPLES_PER_PACKET,
1662 });
1663 }
1664 continue;
1665 };
1666 if track.track_params() != params {
1667 return Err(format!(
1668 "source {source} audio is {:?}, the timeline's is {params:?}",
1669 track.track_params()
1670 )
1671 .into());
1672 }
1673 let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale);
1674 let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0);
1675 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64;
1676 let available = track.sample_count.saturating_sub(start_id - 1);
1677 // The head packet is the priming of the first segment only: a reader
1678 // drops exactly one, so an interior join must not add another --
1679 // and neither must a segment behind a leading gap, which already
1680 // paid the priming in silence.
1681 let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1);
1682 let run = match last {
1683 true => packet_run_last(&mut err, ideal, available),
1684 false => packet_run(&mut err, ideal, available),
1685 };
1686 let ids = head
1687 .into_iter()
1688 .chain(start_id..start_id + run);
1689 for id in ids {
1690 let Some(sample) = mp4track::sample(&mut track.reader, track.stream, id)? else {
1691 let count = track.sample_count;
1692 return Err(format!("audio sample {id} of {count} is missing").into());
1693 };
1694 packets.push(AacPacket {
1695 bytes: sample.data.to_vec(),
1696 samples: SAMPLES_PER_PACKET,
1697 });
1698 }
1699 }
1700 Ok(Some((params, packets)))
1701 }
1702}
1703
1704/// One AAC-LC access unit of silence, for the gaps in an exported timeline —
1705/// this is the *copy* path, which never encodes anything, so the only silence it
1706/// can write is one spelled out by hand. (The re-encode path next door has a
1707/// real encoder and needs none of this: its gaps are zero samples.)
1708///
1709/// It is the shortest legal `raw_data_block` there is: one element carrying
1710/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
1711/// spectral data at all and therefore 1024 samples of exact zero. Every field
1712/// is zero except the element id and the terminating `ID_END`, so the whole
1713/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the
1714/// unit tests, which is the only claim worth making about hand-written
1715/// bitstream.
1716///
1717/// corner-cut: mono and stereo only, because `chan_conf` beyond 2 needs more
1718/// elements per block; the timeline refuses such a source at import today, so
1719/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements.
1720fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
1721 match chan_conf {
1722 // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned.
1723 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]),
1724 // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END.
1725 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]),
1726 n => Err(format!("cannot write silence for a {n}-channel AAC track").into()),
1727 }
1728}
1729
1730/// The source at `index`, on the stream it names, opened on first use -- and
1731/// `None` for a source that has no track at all, which the caller writes as
1732/// silence exactly as it writes a gap. The outer `Option` is "has it been
1733/// opened", the inner one "was there anything in it", so a silent source is
1734/// opened once like any other. Sources a segment list never names are never
1735/// touched: a project's list only grows.
1736fn source_at<'a>(
1737 tracks: &'a mut [Option<Option<AacTrack>>],
1738 sources: &[(PathBuf, usize)],
1739 index: usize,
1740) -> crate::Result<Option<&'a mut AacTrack>> {
1741 let slot = tracks
1742 .get_mut(index)
1743 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
1744 if slot.is_none() {
1745 let (path, stream) = &sources[index];
1746 *slot = Some(copy_track(path, *stream)?);
1747 }
1748 Ok(slot.as_mut().expect("just opened").as_mut())
1749}
1750
1751/// A source's track for the *copy* path, which needs raw AAC access units.
1752///
1753/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name
1754/// and by format. That is no longer the end of the road: `export::copy_audio`
1755/// takes it as the answer "not copyable" and decodes and re-encodes the timeline
1756/// instead, so these words are a fallback's reason rather than a user's refusal.
1757/// They are still worded for a person, because a caller with no encoder to fall
1758/// back on shows them verbatim.
1759///
1760/// `Ok(None)` for a file with no audio at all, which is a silent export.
1761fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
1762 match Track::open(path, stream)? {
1763 None => Ok(None),
1764 // An HE-AAC track has packets of 2048 frames and a config the copy
1765 // cannot rebuild, so it is re-encoded like every other uncopyable source.
1766 Some(Track::Aac(track)) if track.sbr => Err(format!(
1767 "a packet copy needs AAC-LC in an mp4; {} is HE-AAC",
1768 path.file_name()
1769 .unwrap_or(path.as_os_str())
1770 .to_string_lossy(),
1771 )
1772 .into()),
1773 Some(Track::Aac(track)) => Ok(Some(track)),
1774 // A Matroska source gets its own words: its packets *are* AAC, so
1775 // "export needs AAC audio today" would read as a contradiction. What
1776 // they are not is packets of an mp4 sample table, which is what the
1777 // copy walks. The export decodes such a source and encodes it again
1778 // rather than showing this, so a film's sound reaches an mp4 either way;
1779 // the words stay for a caller that copies and cannot re-encode.
1780 //
1781 // corner-cut: the ceiling is the copy path being written against the mp4
1782 // reader, not anything about the bytes. Upgrade path is a
1783 // `copy_segments` that walks a Matroska track, which would make this a
1784 // copy again instead of a re-encode.
1785 Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(
1786 "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \
1787 a copy walks an mp4's own sample table. It is decoded and encoded again \
1788 instead",
1789 path.file_name()
1790 .unwrap_or(path.as_os_str())
1791 .to_string_lossy(),
1792 )
1793 .into()),
1794 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
1795 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
1796 // sample table can hold. The export decodes it and encodes AAC, exactly
1797 // as it does for every other source no copy reaches.
1798 Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")),
1799 // The same reason again: a TrueHD access unit is not an `mp4a` sample.
1800 Some(Track::Truehd(_)) => Err(uncopyable(path, "TrueHD")),
1801 Some(Track::Ext(_)) => Err(uncopyable(path, "DTS, ADPCM, A-law, mu-law or AMR")),
1802 // A transport stream's packets are not an mp4's sample table either.
1803 Some(Track::Ts(_)) => Err(uncopyable(path, "an MPEG system stream's sound")),
1804 }
1805}
1806
1807/// The one wording for "this source's audio cannot be *copied* into an mp4",
1808/// shared by every format that cannot be. What the export does about it is
1809/// decode and re-encode; this is the reason it had to.
1810fn uncopyable(path: &Path, codec: &str) -> crate::Error {
1811 format!(
1812 "a packet copy needs AAC in an mp4; {} is {codec}",
1813 path.file_name()
1814 .unwrap_or(path.as_os_str())
1815 .to_string_lossy(),
1816 )
1817 .into()
1818}
1819
1820/// One source's audio, however it is stored: the mp4 AAC track the export can
1821/// copy, or a standalone file read through symphonia's probe. The opener and
1822/// the worker speak to this, never to either reader directly.
1823enum Track {
1824 Aac(AacTrack),
1825 Ac3(Ac3Track),
1826 /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an
1827 /// mp4's sample table.
1828 Mkv(MkvAc3Track),
1829 /// Dolby TrueHD or MLP, out of a Matroska file's blocks, decoded by
1830 /// `ec-truehd`.
1831 Truehd(MkvTruehdTrack),
1832 /// DTS, ADPCM, A-law / mu-law and AMR out of a Matroska, mp4 / QuickTime /
1833 /// 3GP, WAVE or raw file, read by `ec-probe` ([`crate::extaudio`]).
1834 Ext(Box<crate::extaudio::ExtFileTrack>),
1835 Sym(SymTrack),
1836 /// One sound track of an MPEG transport stream, its own demuxer under it
1837 /// ([`crate::demux::ts`]): AAC in ADTS, AC-3, E-AC-3, MP3 and HDMV LPCM.
1838 Ts(Box<crate::demux::ts::TsAudio>),
1839}
1840
1841impl Track {
1842 /// `Ok(None)` for a file with no audio, which is a valid silent source.
1843 ///
1844 /// The mp4 reader goes first and its verdict is final for anything that is
1845 /// not [`crate::is_audio`]: a video file's audio track is exactly what it
1846 /// always was, silent mp4s included (an mp4 whose only `soun` track is one
1847 /// we cannot decode has always been a silent source, not an error). Only a
1848 /// standalone audio file falls through to symphonia — which is also how an
1849 /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track.
1850 ///
1851 /// `stream` counts audio tracks in file order, as
1852 /// [`AudioSession::probe_streams`] hands them out. A standalone audio file
1853 /// has exactly one, so any `stream` above 0 there is a promise the file
1854 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
1855 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1856 crate::demux::refuse_speex(path)?;
1857 crate::demux::refuse_asf(path)?;
1858 // A Matroska file goes to symphonia, whose `mkv` reader is the one thing
1859 // here that reads its packets -- neither mp4 reader can open the file at
1860 // all -- except for the two codecs symphonia has no decoder for at any
1861 // version and this project does: AC-3 and E-AC-3 are handed to the Dolby
1862 // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither
1863 // one can decode (Opus, DTS) leaves the source the silent one it always
1864 // was, which `AudioSession::unsupported` puts into words, rather than
1865 // failing the import of a file whose picture is fine. A track that will
1866 // not open at all is *not* in that group: see below.
1867 if crate::demux::is_matroska(path) {
1868 // The numbering `probe_streams` lists and a project saves, from the
1869 // one function that decides it ([`mkv_stream_order`]): the stream
1870 // index picks a `TrackEntry`, that entry's *track number* is what
1871 // both readers are then pointed at. Positions are never handed to a
1872 // reader -- symphonia's own order is its business -- because a
1873 // mapping that drifts plays the wrong language and saves it into
1874 // the project.
1875 let tracks = crate::demux::matroska_audio_tracks(path)?;
1876 if tracks.is_empty() {
1877 return Ok(None);
1878 }
1879 let order = mkv_stream_order(path, &tracks);
1880 let Some(entry) = order.get(stream).map(|at| &tracks[*at]) else {
1881 return Err(format!(
1882 "{}: audio stream {stream} of {} stream{}",
1883 path.display(),
1884 tracks.len(),
1885 if tracks.len() == 1 { "" } else { "s" }
1886 )
1887 .into());
1888 };
1889 // TrueHD and MLP go to their own decoder out of the same blocks. An
1890 // open failure is returned, not passed on: symphonia cannot read the
1891 // track either, and the silence it would give is the bug
1892 // [`MkvTruehdTrack`] exists to avoid -- an Atmos track's refusal is
1893 // the answer the user needs.
1894 if matches!(entry.codec.as_str(), "A_TRUEHD" | "A_MLP")
1895 && let Some(track) = MkvTruehdTrack::open_track(path, entry.number)?
1896 {
1897 return Ok(Some(Self::Truehd(track)));
1898 }
1899 match MkvAc3Track::open_track(path, entry.number) {
1900 Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1901 Ok(None) => {}
1902 // Named on the way past rather than returned: symphonia gets the
1903 // same file next and may read the track perfectly well (a laced
1904 // block is [`MkvAc3Track`]'s limitation, not the file's), and
1905 // if it cannot either, *its* `Err` is the one that comes back.
1906 Err(e) => debug_once(format!("matroska audio: {}: {e}", path.display())),
1907 }
1908 // Two things are silent here and no more: a file with no audio
1909 // track at all, and a track whose codec nothing in this project
1910 // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts
1911 // that into words). A track that will not *open* is an `Err`, the
1912 // same answer the mp4 arm gives: turned into silence it would play
1913 // and export as a hole with only an eprintln to say why, which is a
1914 // bug wearing a feature's clothes.
1915 // DTS (and its DTS-HD core) through `ec-dts`, out of the same blocks. An
1916 // open failure is returned: an XLL-only lossless track is refused by name.
1917 if (crate::extaudio::is_mkv_dts(&entry.codec) || crate::extaudio::is_mkv_mpeg_layer(&entry.codec))
1918 && let Some(track) = crate::extaudio::ExtFileTrack::open_native(path, entry.number)?
1919 {
1920 return Ok(Some(Self::Ext(Box::new(track))));
1921 }
1922 // Speex has no reader in this build (symphonia cannot open it): silent, and
1923 // `AudioSession::unsupported` names it for the warning.
1924 if codec_display_name(&entry.codec) == "Speex" {
1925 return Ok(None);
1926 }
1927 let Some(track) = SymTrack::open_track(path, entry.number)? else {
1928 return Ok(None);
1929 };
1930 if let Err(e) = track.decoder() {
1931 debug_once(format!("matroska audio: {}: {e}", path.display()));
1932 return Ok(None);
1933 }
1934 return Ok(Some(Self::Sym(track)));
1935 }
1936 // A transport stream is read by its own demuxer, whatever the sound in it is.
1937 if crate::demux::is_mpeg_system(path) {
1938 return Ok(crate::demux::ts::TsAudio::open(path, stream)?.map(|t| Self::Ts(Box::new(t))));
1939 }
1940 let audio_file = crate::is_audio(path);
1941 // Ahead of the AAC reader, because that one answers "not AAC" for a
1942 // *named* stream with an `Err` and an AC-3 track is not an error any
1943 // more. `Ok(None)` here means "not an AC-3 track", so every other file
1944 // falls through to exactly the reader it always used.
1945 if !audio_file && let Some(track) = Ac3Track::open(path, stream)? {
1946 return Ok(Some(Self::Ac3(track)));
1947 }
1948 match AacTrack::open(path, stream) {
1949 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
1950 Ok(None) if !audio_file => {
1951 // Not AAC: DTS, ADPCM, A-law / mu-law or AMR in an mp4 / QuickTime / 3GP file.
1952 return Ok(crate::extaudio::ExtFileTrack::open(path, stream)?.map(|t| Self::Ext(Box::new(t))));
1953 }
1954 Err(e) if !audio_file => {
1955 return match crate::extaudio::ExtFileTrack::open(path, stream) {
1956 Ok(Some(t)) => Ok(Some(Self::Ext(Box::new(t)))),
1957 _ => Err(e),
1958 };
1959 }
1960 _ => {}
1961 }
1962 // A WAVE file that is not plain PCM (ADPCM, A-law, mu-law, DTS), a raw `.dts`
1963 // or `.amr`: `ec-probe`'s reader, ahead of symphonia's.
1964 if stream == 0
1965 && let Some(track) = crate::extaudio::ExtFileTrack::open(path, 0)?
1966 {
1967 return Ok(Some(Self::Ext(Box::new(track))));
1968 }
1969 if stream > 0 {
1970 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
1971 }
1972 SymTrack::open_required(path).map(|track| Some(Self::Sym(track)))
1973 }
1974
1975 fn sample_rate(&self) -> u32 {
1976 match self {
1977 Self::Aac(t) => t.sample_rate,
1978 Self::Ac3(t) => t.sample_rate,
1979 Self::Mkv(t) => t.sample_rate,
1980 Self::Truehd(t) => t.sample_rate,
1981 Self::Ext(t) => t.sample_rate,
1982 Self::Sym(t) => t.sample_rate,
1983 Self::Ts(t) => t.sample_rate,
1984 }
1985 }
1986
1987 /// What this track hands the timeline: mono, or stereo for everything else.
1988 /// Nothing is refused for its width any more -- a layout wider than a pair
1989 /// is folded to one at the decoder's door ([`downmix`]), because one output
1990 /// device is all there is, not because the file is unreadable.
1991 fn channels(&self) -> u16 {
1992 match self {
1993 Self::Aac(t) => t.channels(),
1994 // Downmixed to a pair by the AC-3 decoder itself (§7.8.2); a mono
1995 // track passes through as the one channel it is (see [`ac3_decoder`]),
1996 // so what `channels` measures is already the timeline width.
1997 Self::Ac3(t) => t.channels,
1998 // The same decoder, out of a Matroska file.
1999 Self::Mkv(t) => t.channels,
2000 // Folded to a pair by [`downmix`] in the worker; see [`MkvTruehdTrack`].
2001 Self::Truehd(t) => t.channels,
2002 Self::Ext(t) => t.channels(),
2003 Self::Sym(t) => t.channels,
2004 Self::Ts(t) => t.channels(),
2005 }
2006 }
2007
2008 /// Frames per channel of *audible* audio, priming already subtracted.
2009 fn total_samples(&self) -> Option<u64> {
2010 match self {
2011 Self::Aac(t) => t.total_samples,
2012 Self::Ac3(t) => t.total_samples,
2013 Self::Mkv(t) => t.total_samples,
2014 Self::Truehd(t) => t.total_samples,
2015 Self::Ext(t) => t.total_samples,
2016 Self::Sym(t) => t.total_samples,
2017 Self::Ts(t) => t.total_samples,
2018 }
2019 }
2020
2021 /// Encoder delay of this file. Sources are joined, priming is not shared.
2022 fn priming(&self) -> u64 {
2023 match self {
2024 Self::Aac(t) => t.priming,
2025 Self::Ac3(t) => t.priming,
2026 // Matroska writes no edit list and AC-3 has no encoder delay:
2027 // block 0 is sample 0.
2028 Self::Mkv(_) | Self::Truehd(_) | Self::Ts(_) => 0,
2029 Self::Ext(t) => t.priming,
2030 Self::Sym(t) => t.priming,
2031 }
2032 }
2033
2034 /// One `[start, end)` window of this source's seconds, resolved to whatever
2035 /// its own reader needs to find it again.
2036 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
2037 match self {
2038 Self::Aac(t) => t.segment(source, start_secs, end_secs),
2039 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
2040 Self::Mkv(t) => t.segment(source, start_secs, end_secs),
2041 Self::Truehd(t) => t.segment(source, start_secs, end_secs),
2042 Self::Ext(t) => {
2043 let rate = f64::from(t.sample_rate);
2044 let media_target = (start_secs.max(0.0) * rate).round() as u64 + t.priming;
2045 Segment {
2046 source: Some(source),
2047 start_id: 0,
2048 start_pos: 0,
2049 media_target,
2050 media_end: (((end_secs.max(0.0) * rate).round() as u64).saturating_add(t.priming)).max(media_target),
2051 }
2052 }
2053 Self::Ts(t) => {
2054 let rate = f64::from(t.sample_rate);
2055 let media_target = (start_secs.max(0.0) * rate).round() as u64;
2056 Segment {
2057 source: Some(source),
2058 start_id: 0,
2059 start_pos: 0,
2060 media_target,
2061 media_end: ((end_secs.max(0.0) * rate).round() as u64).max(media_target),
2062 }
2063 }
2064 Self::Sym(t) => {
2065 let media_target = t.media(start_secs);
2066 Segment {
2067 source: Some(source),
2068 start_id: 0,
2069 start_pos: 0,
2070 media_target,
2071 media_end: t.media(end_secs).max(media_target),
2072 }
2073 }
2074 }
2075 }
2076
2077 /// Builds and throws away a decoder, so an undecodable stream is an `Err`
2078 /// from the opener rather than a silently empty channel.
2079 fn check_decoder(&self) -> crate::Result<()> {
2080 match self {
2081 Self::Aac(t) => {
2082 aac_decoder(&t.params, t.source_channels())?;
2083 }
2084 Self::Ac3(t) => {
2085 ac3_decoder(t.requested)?;
2086 }
2087 Self::Mkv(t) => {
2088 ac3_decoder(t.requested)?;
2089 }
2090 // Its first access unit was decoded by the opener already.
2091 Self::Truehd(_) => {}
2092 Self::Ext(t) => {
2093 t.decoder()?;
2094 }
2095 Self::Ts(t) => {
2096 t.decoder()?;
2097 }
2098 Self::Sym(t) => {
2099 t.decoder()?;
2100 }
2101 }
2102 Ok(())
2103 }
2104}
2105
2106/// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read
2107/// through symphonia's own probe and codec registry. No packet table and no
2108/// sample ids: the reader is *seeked* per segment and the packets it then hands
2109/// out carry their own timestamps.
2110struct SymTrack {
2111 reader: Box<dyn FormatReader>,
2112 /// The file the reader reads, kept because a seek builds a *new* one
2113 /// ([`SymTrack::seek_to`]).
2114 path: PathBuf,
2115 track_id: u32,
2116 sample_rate: u32,
2117 /// What reaches the timeline: the file's own layout, or 2 for anything
2118 /// wider, which is folded down by [`SymDecoder`] exactly as the AC-3
2119 /// reader's decoder folds its own.
2120 channels: u16,
2121 /// What the decoder emits, which is what the fold reads.
2122 source_channels: u16,
2123 /// Frames per channel of audible audio, `None` when the header does not say.
2124 total_samples: Option<u64>,
2125 /// Frames withheld at the very end of the track and never played: the
2126 /// `DiscardPadding` of Vorbis in Matroska, whose blocks carry no granule to
2127 /// cut by. Zero for everything else (Ogg Vorbis is cut by its granules, per
2128 /// packet).
2129 tail_hold: u64,
2130 /// Every packet of a Matroska Vorbis track with its exact start in samples
2131 /// ([`VorbisStarts`]). Matroska stamps a block in whole milliseconds, up to
2132 /// half a millisecond (22 samples at 44.1 kHz) off the samples it holds, so
2133 /// a track with this index is read by it -- packet by packet, and sought by
2134 /// sample -- rather than through symphonia's stamp-based reader. `None` for
2135 /// everything else, which keeps its packets' own timestamps or granules.
2136 vorbis_starts: Option<VorbisStartsRef>,
2137 /// The file the indexed packets are read from.
2138 vorbis_file: Option<File>,
2139 /// The index of the next packet [`SymTrack::next_packet`] reads.
2140 vorbis_next: usize,
2141 /// Encoder delay, and **always zero here**: symphonia 0.6 drops the leading
2142 /// frames itself, so a reader that skipped `Track::delay` on top would skip
2143 /// them twice. Kept as a field because [`Track::priming`] asks every track
2144 /// for one and the AAC and AC-3 readers beside it do owe a real number.
2145 ///
2146 /// This used to carry `delay` and cost the double skip on the two formats
2147 /// that declare one: a `.mp3` lost its first 1105 samples (25 ms) and read
2148 /// 25 ms short, an `.ogg` its first 128. Measured 2026-08-11 against
2149 /// `test_tone.flac` -- lossless, and the only one of the three whose
2150 /// container declares no delay at all -- which the mp3 and the ogg of the
2151 /// same tone align with sample for sample once this is not subtracted.
2152 priming: u64,
2153 time_base: TimeBase,
2154 params: AudioCodecParameters,
2155 /// The format's short name, for the export refusal. `&'static` because it
2156 /// comes out of the codec registry, which outlives everything here.
2157 codec: &'static str,
2158}
2159
2160impl SymTrack {
2161 /// `Ok(None)` for a container that opened and holds no audio track at all --
2162 /// a silent source, which is a thing a file is allowed to be. Everything
2163 /// else that goes wrong here is an `Err`: a file that will not open, will
2164 /// not parse, or carries a track it cannot describe is *broken*, and the
2165 /// difference matters because silence is played and exported without a word
2166 /// while an `Err` is shown ([`Track::open`]).
2167 fn open(path: &Path) -> crate::Result<Option<Self>> {
2168 Self::open_inner(path, None)
2169 }
2170
2171 /// [`open`](Self::open) pointed at one **named** track: a Matroska
2172 /// `TrackNumber`, which symphonia keeps as the track's id
2173 /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second
2174 /// language of a dual-audio file reachable, and it is matched by number
2175 /// rather than by position so this reader and
2176 /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which
2177 /// track a stream index meant. `Ok(None)` for a number the reader does not
2178 /// carry.
2179 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
2180 Self::open_inner(path, Some(number))
2181 }
2182
2183 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
2184 let reader = sym_reader(path)?;
2185 let track = match number {
2186 Some(number) => reader.tracks().iter().find(|t| u64::from(t.id) == number),
2187 None => reader.default_track(SymKind::Audio),
2188 };
2189 let Some(track) = track else {
2190 return Ok(None);
2191 };
2192 // `track.delay` is deliberately not read: see the `priming` field.
2193 let (track_id, num_frames) = (track.id, track.num_frames);
2194 let time_base = track
2195 .time_base
2196 .ok_or_else(|| format!("{} declares no time base", path.display()))?;
2197 let Some(symphonia_core::codecs::CodecParameters::Audio(params)) =
2198 track.codec_params.clone()
2199 else {
2200 return Err(format!("{} declares no audio codec", path.display()).into());
2201 };
2202 // An AAC track's rate is the one `ec-aac` decodes at, which for HE-AAC
2203 // is the SBR extension rate (2x the core the container may state). An
2204 // ADTS stream carries no config to read that from, so its header's rate
2205 // is only the core's until the first frames are decoded (see below).
2206 let mut sample_rate = match (params.codec, params.extra_data.as_deref()) {
2207 (CODEC_ID_AAC, Some(asc)) => aac_output_rate(asc)?,
2208 _ => params.sample_rate,
2209 }
2210 .ok_or_else(|| format!("{} declares no sample rate", path.display()))?;
2211 let mut channels = params.channels.as_ref().map(|c| c.count() as u16);
2212 // A plain-LC config, or an ADTS stream with none, may still be HE-AAC by
2213 // implicit signalling: its rate only doubles once a frame has carried an
2214 // SBR payload, so the first frames are decoded to read the real rate.
2215 if params.codec == CODEC_ID_AAC
2216 && aac_may_be_implicit(params.extra_data.as_deref())?
2217 && let Some(primed) = sym_aac_prime(path, track_id, params.extra_data.as_deref())?
2218 {
2219 sample_rate = primed.sample_rate;
2220 channels = Some(primed.channels);
2221 }
2222 let channels = channels
2223 .ok_or_else(|| format!("{} declares no channel layout", path.display()))?;
2224 // Vorbis in Matroska states no length on the track and its blocks carry
2225 // no granule: the last block's padding is what its muxer says to drop
2226 // from the end ([`crate::demux::matroska_tail_padding_ns`]).
2227 let tail_hold = match params.codec {
2228 CODEC_ID_VORBIS => crate::demux::matroska_tail_padding_ns(path, u64::from(track_id))
2229 .map_or(0, |ns| (ns as f64 * f64::from(sample_rate) / 1e9).round() as u64),
2230 _ => 0,
2231 };
2232 let vorbis_starts = match params.codec {
2233 CODEC_ID_VORBIS if crate::demux::is_matroska(path) => {
2234 matroska_vorbis_starts(path, u64::from(track_id), &params)
2235 }
2236 _ => None,
2237 };
2238 let vorbis_file = match vorbis_starts {
2239 Some(_) => Some(File::open(path)?),
2240 None => None,
2241 };
2242 // AAC is decoded by `ec-aac`, which symphonia's registry does not list.
2243 let codec = match params.codec {
2244 CODEC_ID_AAC => "aac",
2245 _ => symphonia::default::get_codecs()
2246 .get_audio_decoder(params.codec)
2247 .map_or("an unsupported format", |d| d.codec.info.short_name),
2248 };
2249 // The one codec here that *does* owe a priming number: Opus states its
2250 // encoder delay in the stream itself (`OpusHead`'s pre-skip, 312 samples
2251 // on a film remux) and neither reader drops it, because symphonia trims
2252 // for its own decoders and the Opus one is this crate's. Measured against
2253 // ffmpeg's decode of the same file: 312 samples late in *both* an mkv and
2254 // an ogg until this is subtracted, sample-exact after (correlation
2255 // 1.00000). It is priming exactly as an AAC track's is, and it is read
2256 // off the stream rather than the container for that reason.
2257 let priming = match params.codec {
2258 CODEC_ID_OPUS => opus_pre_skip(params.extra_data.as_deref().unwrap_or_default()),
2259 _ => 0,
2260 };
2261 Ok(Some(Self {
2262 reader,
2263 path: path.to_path_buf(),
2264 track_id,
2265 sample_rate,
2266 // Anything wider than a pair arrives as a stereo source, whatever it
2267 // was stored as: 5.1, 7.1 and everything between are folded by
2268 // [`downmix`] at the decoder's door ([`SymDecoder`]).
2269 channels: channels.min(2),
2270 source_channels: channels,
2271 total_samples: num_frames.map(|n| n.saturating_sub(priming)),
2272 tail_hold,
2273 vorbis_starts,
2274 vorbis_file,
2275 vorbis_next: 0,
2276 priming,
2277 time_base,
2278 params,
2279 codec,
2280 }))
2281 }
2282
2283 /// [`open`](Self::open) where having no audio track is itself the error:
2284 /// what a standalone audio file is held to, since a song with no sound in
2285 /// it is a broken file and not a silent source.
2286 fn open_required(path: &Path) -> crate::Result<Self> {
2287 Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into())
2288 }
2289
2290 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
2291 /// packets we skipped, exactly as on the AAC path.
2292 ///
2293 /// Which decoder is not the caller's business, and it is not always
2294 /// symphonia's: it has no AAC decoder in this build at all (its HE-AAC
2295 /// refusal, "aac: aac too complex", is why), so every AAC track goes to
2296 /// `ec-aac` instead ([`aac_decoder`]), and it has no Opus decoder either, so
2297 /// that one goes to `ec-opus` ([`SymDecoder::Opus`]).
2298 fn decoder(&self) -> crate::Result<SymDecoder> {
2299 let from = usize::from(self.source_channels);
2300 if self.params.codec == CODEC_ID_OPUS {
2301 let (streams, coupled, mapping) =
2302 opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?;
2303 // 48 kHz whatever the container says: that is the only rate Opus
2304 // decodes at, and the rate both readers declare for it.
2305 let decoder =
2306 ec_opus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping);
2307 return Ok(SymDecoder::Opus(Box::new(decoder), from));
2308 }
2309 if self.params.codec == CODEC_ID_AAC {
2310 return aac_decoder(&self.params, from);
2311 }
2312 if self.params.codec == CODEC_ID_VORBIS {
2313 return vorbis_decoder(&self.params);
2314 }
2315 Ok(SymDecoder::Sym(
2316 symphonia::default::get_codecs()
2317 .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,
2318 from,
2319 ))
2320 }
2321
2322 /// `secs` on this source's audible timeline into media samples (priming
2323 /// included, so it compares directly against a decoded position).
2324 fn media(&self, secs: f64) -> u64 {
2325 ((secs * f64::from(self.sample_rate)).round() as u64).saturating_add(self.priming)
2326 }
2327
2328 /// Where the packet stamped `ts` begins, exactly, for a track with an index
2329 /// ([`VorbisStarts`]). `None` where there is none, or `ts` is not one of its
2330 /// packets' stamps.
2331 fn exact_start(&self, ts: units::Timestamp) -> Option<u64> {
2332 let starts = self.vorbis_starts.as_deref()?;
2333 Some(starts.packets[starts.at(ts.get())?].start)
2334 }
2335
2336 /// The next packet of the track: from the index's file where the track has
2337 /// one, stamped with its own stamp, and from the reader otherwise.
2338 fn next_packet(&mut self) -> Result<Option<Packet>, String> {
2339 let (Some(starts), Some(file)) = (self.vorbis_starts.as_deref(), self.vorbis_file.as_mut())
2340 else {
2341 return self.reader.next_packet().map_err(|e| e.to_string());
2342 };
2343 let Some(block) = starts.packets.get(self.vorbis_next) else {
2344 return Ok(None);
2345 };
2346 self.vorbis_next += 1;
2347 crate::demux::check_extent(file, block.at, block.len).map_err(|e| e.to_string())?;
2348 let mut data = vec![0u8; block.len];
2349 file.seek(SeekFrom::Start(block.at))
2350 .and_then(|_| file.read_exact(&mut data))
2351 .map_err(|e| format!("reading a Vorbis block: {e}"))?;
2352 let stamp = units::Timestamp::new(block.stamp);
2353 Ok(Some(Packet::new(self.track_id, stamp, units::Duration::ZERO, data)))
2354 }
2355
2356 /// A packet timestamp in the track's time base, as a media position: the
2357 /// scale [`media`](Self::media) hands out, so a landing compares directly
2358 /// against a segment's target.
2359 ///
2360 /// The priming comes *off* it because a Matroska Opus track's blocks are
2361 /// timestamped for the audible stream while the decoder hands its samples
2362 /// back with the pre-skip still in front of them. Measured against ffmpeg's
2363 /// decode of the same second of a real 5.1 Opus remux: without this term a seeked
2364 /// Opus track came out 6.5 ms -- one pre-skip, 312 samples -- ahead of it,
2365 /// with it, on the same sample.
2366 fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {
2367 let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
2368 // Rounded, not truncated: a position is a whole sample, and the seconds
2369 // it was converted through sit a sample low when truncated (11840 came
2370 // back 11839), which the seek test's exact check caught.
2371 ((secs.max(0.0) * f64::from(self.sample_rate)).round() as u64).saturating_sub(self.priming)
2372 }
2373
2374 /// Puts the reader **at or before** `media_target`, [`SYM_PRE_ROLL`] ahead
2375 /// of it where the container allows, so that everything the caller did not
2376 /// ask for is decoder warm-up that [`emit`] drops.
2377 ///
2378 /// At or before is the whole point, and it is not what one seek gives. A
2379 /// Matroska seek lands on the first frame whose timestamp is at or past the
2380 /// one asked for, and its cue table can put that a whole cluster further on
2381 /// still: measured on a real 5.1 Opus remux, asking for 599.83 s (600 s less the
2382 /// pre-roll) landed at 601.487 s and asking for 609.83 s at 613.407 s.
2383 /// Samples that far *behind* the reader can never be emitted, and the film
2384 /// played from there while the timeline said 600 s -- 1.5 s of sound
2385 /// against picture, which is the seek desync this exists to kill. So the
2386 /// landing is read back, and an overshoot is asked again from far enough
2387 /// before it to swallow the overshoot.
2388 ///
2389 /// Each attempt gets a **new reader**, because symphonia's mkv seek is
2390 /// reliable exactly once per reader: it neither clears the frames it has
2391 /// already queued (they come out ahead of the new position, carrying the
2392 /// old block's timestamp) nor recovers its element iterator, and a second
2393 /// seek measured on the same file landed the reader back at the first
2394 /// cluster, 0.094 s, whatever it was asked for. Opening again costs 2 ms on
2395 /// a 5 GB film, which is what a seek is allowed to cost.
2396 fn seek_to(&mut self, media_target: u64) {
2397 // With an index the packet is found by its sample, not by a seek of the
2398 // container's: the decoder starts at the packet before the first one
2399 // whose start is at or before the target, since a fresh decoder answers
2400 // nothing for the packet it starts on and the next one is the first
2401 // that answers. Nothing is read here; [`SymTrack::next_packet`] reads it.
2402 if let Some(starts) = self.vorbis_starts.as_deref() {
2403 let at_or_before = starts
2404 .packets
2405 .partition_point(|p| p.start <= media_target);
2406 self.vorbis_next = at_or_before.saturating_sub(2);
2407 return;
2408 }
2409 let rate = f64::from(self.sample_rate.max(1));
2410 let mut back = SYM_PRE_ROLL;
2411 // Enough for any overshoot a cue table can hold: each attempt asks from
2412 // strictly further back than the last, and the seek to 0 is the floor.
2413 for _ in 0..8 {
2414 let from = media_target.saturating_sub(back);
2415 match sym_reader(&self.path) {
2416 Ok(reader) => self.reader = reader,
2417 // Whatever the file did, the reader in hand still reads: fall
2418 // back to seeking that one, exactly as before this loop existed.
2419 Err(e) => eprintln!("audio reopen failed: {e}"),
2420 }
2421 // Asking for the beginning is asking for nothing: a fresh reader is
2422 // already there, and *seeking* there is how the first 167 ms of a
2423 // real 5.1 Opus remux went missing -- the cue table's first point put the
2424 // reader past them and no window rule can reach back.
2425 if from == 0 {
2426 return;
2427 }
2428 let secs = from as f64 / rate;
2429 let Some(time) = Time::try_from_secs_f64(secs) else {
2430 return;
2431 };
2432 let to = SeekTo::Time {
2433 time,
2434 track_id: Some(self.track_id),
2435 };
2436 // A failed seek is not fatal: it leaves the reader where it was, and
2437 // the window rules still only emit what the segment asked for.
2438 let landed = match self.reader.seek(SeekMode::Accurate, to) {
2439 Ok(landed) => self.samples_at(landed.actual_ts),
2440 Err(e) => {
2441 eprintln!("audio seek to {secs:.3}s failed: {e}");
2442 return;
2443 }
2444 };
2445 if landed <= media_target {
2446 return;
2447 }
2448 back += (landed - media_target) + SYM_PRE_ROLL;
2449 }
2450 }
2451}
2452
2453/// One symphonia reader over `path`, which is both how a track is opened and
2454/// how it is seeked ([`SymTrack::seek_to`]).
2455///
2456/// A raw ADTS stream is read by [`crate::adts`] rather than probed: symphonia's
2457/// own ADTS reader lives behind the `aac` feature this project does not link,
2458/// and an ADTS sync word is the one thing it would have answered to anyway.
2459fn sym_reader(path: &Path) -> crate::Result<Box<dyn FormatReader>> {
2460 let mut head = [0u8; 2];
2461 if File::open(path)?.read(&mut head)? == 2 && ec_aac::is_adts(&head) {
2462 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
2463 return Ok(Box::new(crate::adts::AdtsReader::try_new(mss)?));
2464 }
2465 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
2466 // The extension is a hint, not a decision: the probe reads the magic and
2467 // is free to disagree, which is what makes a mislabelled file work.
2468 let mut hint = Hint::new();
2469 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
2470 hint.with_extension(ext);
2471 }
2472 Ok(symphonia::default::get_probe().probe(
2473 &hint,
2474 mss,
2475 FormatOptions::default(),
2476 MetadataOptions::default(),
2477 )?)
2478}
2479
2480/// One packet in, interleaved f32 out — whichever library did the decoding, and
2481/// already folded to the layout [`SymTrack::channels`] promised. The number
2482/// beside each is the width the decoder itself emits, which is what
2483/// [`downmix`] folds from; 1 and 2 fold to nothing.
2484enum SymDecoder {
2485 Sym(Box<dyn AudioDecoder>, usize),
2486 /// Every AAC track, mono to 7.1 and LC or HE-AAC: `ec-aac` takes the config
2487 /// the track carries, or the first ADTS frame's when it carries none. Boxed
2488 /// because the decoder carries its own IMDCT and SBR tables and this enum is
2489 /// moved into the worker.
2490 Aac(Box<ec_aac::AacDecoder>, usize),
2491 /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of
2492 /// a packet, the channel mapping table and the routing between them are all
2493 /// its business -- and the same width.
2494 Opus(Box<ec_opus::MultistreamDecoder>, usize),
2495 /// Every Vorbis track, Ogg or Matroska, mono to 7.1: `ec-vorbis` decodes
2496 /// the blocks, in the stream's channel order, and the second field is the
2497 /// width. The third maps each of those channels to the family's order
2498 /// ([`ec_vorbis::channel_map`]).
2499 Vorbis(Box<ec_vorbis::VorbisDecoder>, usize, Vec<usize>),
2500}
2501
2502impl SymDecoder {
2503 fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {
2504 match self {
2505 Self::Sym(decoder, from) => {
2506 decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);
2507 downmix(out, *from);
2508 }
2509 Self::Aac(decoder, from) => {
2510 let pcm = decoder
2511 .decode(&packet.data, None)
2512 .map_err(|e| format!("AAC decode failed: {e}"))?;
2513 // `pcm.sample_rate` is what this block is at; the track was
2514 // opened at the same rate ([`aac_output_rate`]), so the timeline
2515 // and the samples agree. The frame count comes from the block
2516 // itself, not from a fixed packet size, because HE-AAC carries
2517 // twice the frames of its core.
2518 *out = pcm.samples;
2519 downmix(out, *from);
2520 }
2521 Self::Vorbis(decoder, from, to_ec) => {
2522 let blocks = decoder
2523 .decode_audio(&packet.data)
2524 .map_err(|e| format!("Vorbis decode failed: {e}"))?;
2525 let mut planes = vec![Vec::new(); blocks.len()];
2526 for (channel, plane) in blocks.into_iter().enumerate() {
2527 if let Some(&slot) = to_ec.get(channel) {
2528 planes[slot] = plane;
2529 }
2530 }
2531 interleave_planes(&planes, out);
2532 vorbis_packet_window(out, planes.len(), packet);
2533 downmix(out, *from);
2534 }
2535 Self::Opus(decoder, from) => {
2536 *out = decoder
2537 .decode_packet(&packet.data)
2538 .map_err(|e| format!("Opus decode failed: {e}"))?;
2539 // The encoder delay is not dropped here: it is this track's
2540 // priming ([`SymTrack::open_inner`]), which the window rules
2541 // subtract once for the whole segment rather than per packet.
2542 vorbis_to_film_order(out, *from);
2543 downmix(out, *from);
2544 }
2545 }
2546 Ok(())
2547 }
2548}
2549
2550/// The decoder for a Vorbis track: `ec-vorbis`, from the identification and
2551/// setup headers symphonia states in the track's extra data (the same layout
2552/// in Ogg and in Matroska).
2553fn vorbis_decoder(params: &AudioCodecParameters) -> crate::Result<SymDecoder> {
2554 let decoder = vorbis_headers(params)?;
2555 let channels = usize::from(decoder.identification().channels);
2556 let (_, to_ec) = ec_vorbis::channel_map(channels);
2557 Ok(SymDecoder::Vorbis(Box::new(decoder), channels, to_ec))
2558}
2559
2560/// `ec-vorbis` built from a Vorbis track's headers, without a decoding state.
2561fn vorbis_headers(params: &AudioCodecParameters) -> crate::Result<ec_vorbis::VorbisDecoder> {
2562 let extra = params
2563 .extra_data
2564 .as_deref()
2565 .ok_or("a Vorbis track carries no headers")?;
2566 // symphonia states the identification header (30 bytes, fixed by Vorbis I)
2567 // and then the setup header; `ec-vorbis` wants all three, so the comment
2568 // header is written here as an empty one.
2569 let (ident, setup) = extra
2570 .split_at_checked(VORBIS_IDENT_LEN)
2571 .ok_or("a Vorbis track's identification header is short")?;
2572 ec_vorbis::VorbisDecoder::new(&[ident, VORBIS_EMPTY_COMMENTS, setup])
2573 .map_err(|e| format!("Vorbis headers: {e}").into())
2574}
2575
2576/// The starts of a Matroska Vorbis track's packets, in samples from its first.
2577///
2578/// Packet `n` answers the quarter of block `n-1` plus the quarter of block `n`
2579/// samples (`ec-vorbis` `packet_blocksize`), and the first packet answers none,
2580/// so the count of every packet before it is its exact position. The timestamp
2581/// alone cannot give that, since it is rounded to milliseconds, so the blocks
2582/// are counted: one byte each (their mode), in the cached block list of
2583/// [`crate::demux::matroska_track_blocks`]. The walk costs one read per block, and
2584/// it is kept per file, so a seek pays it once.
2585type VorbisStartsRef = Arc<VorbisStarts>;
2586
2587/// The packets of one Matroska Vorbis track, in storage order.
2588struct VorbisStarts {
2589 packets: Vec<VorbisPacket>,
2590}
2591
2592struct VorbisPacket {
2593 /// The block's own timestamp in the file, in `TimestampScale` ticks.
2594 stamp: i64,
2595 /// Where the packet's samples begin, in the track's own count from its start.
2596 start: u64,
2597 /// Where the block's bytes are, and how many.
2598 at: u64,
2599 len: usize,
2600}
2601
2602impl VorbisStarts {
2603 /// The index of the packet stamped `stamp`.
2604 fn at(&self, stamp: i64) -> Option<usize> {
2605 self.packets.binary_search_by_key(&stamp, |p| p.stamp).ok()
2606 }
2607}
2608
2609type StartsKey = (PathBuf, u64, u64, Option<std::time::SystemTime>);
2610
2611/// The most files whose packet index is kept; a seek reuses one of them.
2612const VORBIS_STARTS_KEPT: usize = 8;
2613
2614static VORBIS_STARTS: Mutex<Vec<(StartsKey, VorbisStartsRef)>> = Mutex::new(Vec::new());
2615
2616fn matroska_vorbis_starts(
2617 path: &Path,
2618 number: u64,
2619 params: &AudioCodecParameters,
2620) -> Option<VorbisStartsRef> {
2621 let meta = std::fs::metadata(path).ok()?;
2622 let key: StartsKey = (path.to_path_buf(), number, meta.len(), meta.modified().ok());
2623 if let Ok(kept) = VORBIS_STARTS.lock()
2624 && let Some((_, hit)) = kept.iter().find(|(k, _)| *k == key)
2625 {
2626 return Some(Arc::clone(hit));
2627 }
2628 let starts = Arc::new(vorbis_starts_walk(path, number, params)?);
2629 if let Ok(mut kept) = VORBIS_STARTS.lock() {
2630 if kept.len() >= VORBIS_STARTS_KEPT {
2631 kept.remove(0);
2632 }
2633 kept.push((key, Arc::clone(&starts)));
2634 }
2635 Some(starts)
2636}
2637
2638fn vorbis_starts_walk(
2639 path: &Path,
2640 number: u64,
2641 params: &AudioCodecParameters,
2642) -> Option<VorbisStarts> {
2643 let blocks = crate::demux::matroska_track_blocks(path, number)?;
2644 // The search by stamp needs them in order, which Matroska requires of a track.
2645 if blocks.windows(2).any(|w| w[0].0 >= w[1].0) {
2646 return None;
2647 }
2648 let headers = vorbis_headers(params).ok()?;
2649 let mut file = File::open(path).ok()?;
2650 let mut packets = Vec::with_capacity(blocks.len());
2651 let (mut samples, mut previous) = (0u64, None::<usize>);
2652 for (stamp, at, len) in blocks {
2653 packets.push(VorbisPacket {
2654 stamp,
2655 start: samples,
2656 at,
2657 len,
2658 });
2659 // The mode is in a packet's first byte, so the first bytes are all that is read.
2660 let mut head = [0u8; 8];
2661 let n = len.min(head.len());
2662 file.seek(SeekFrom::Start(at)).ok()?;
2663 file.read_exact(&mut head[..n]).ok()?;
2664 let size = headers.packet_blocksize(&head[..n]).ok()?;
2665 if let Some(previous) = previous {
2666 samples += (previous / 4 + size / 4) as u64;
2667 }
2668 previous = Some(size);
2669 }
2670 Some(VorbisStarts { packets })
2671}
2672
2673/// The fixed length of a Vorbis identification header (Vorbis I, A.2).
2674const VORBIS_IDENT_LEN: usize = 30;
2675
2676/// A Vorbis comment header with an empty vendor string and no comments, framed:
2677/// what `ec-vorbis` needs where symphonia's extra data carries none.
2678const VORBIS_EMPTY_COMMENTS: &[u8] = b"\x03vorbis\x00\x00\x00\x00\x00\x00\x00\x00\x01";
2679
2680/// Interleaves per-channel planes, in the order they are given.
2681fn interleave_planes(planes: &[Vec<f32>], out: &mut Vec<f32>) {
2682 let frames = planes.first().map_or(0, Vec::len);
2683 out.clear();
2684 out.reserve(frames * planes.len());
2685 for frame in 0..frames {
2686 for plane in planes {
2687 out.push(plane.get(frame).copied().unwrap_or(0.0));
2688 }
2689 }
2690}
2691
2692/// Cuts one Vorbis packet's decoded block down to the samples symphonia says
2693/// the packet owns: `dur` after its trims, from `trim_start`. Symphonia takes
2694/// both from the page granules (the stream's last block overhangs its end and
2695/// the first block has nothing before it), so the cut is the container's own.
2696/// A packet stating no duration keeps all of its block.
2697fn vorbis_packet_window(out: &mut Vec<f32>, channels: usize, packet: &Packet) {
2698 let channels = channels.max(1);
2699 let frames = out.len() / channels;
2700 let start = usize::try_from(packet.trim_start.get())
2701 .unwrap_or(usize::MAX)
2702 .min(frames);
2703 let end = match packet.dur.get() {
2704 0 => frames,
2705 dur => usize::try_from(dur).unwrap_or(usize::MAX).saturating_add(start).min(frames),
2706 };
2707 out.truncate(end * channels);
2708 out.drain(..start * channels);
2709}
2710
2711/// Samples per channel of a full HE-AAC frame: the SBR output of a 1024-sample
2712/// core. A frame whose header is missing comes out as the core alone, half this.
2713const SBR_FULL_FRAME: usize = 2048;
2714
2715/// The packet an SBR track's decoder starts on: the nearest one at or before
2716/// `from` whose own frame decodes with its SBR header, so every frame after it
2717/// is reconstructed. Headers come back every few packets (every 10 in libfdk's
2718/// streams), not on each one; a fresh decoder on a headerless frame gives its
2719/// core alone, which is how a frame without its header is told apart. Packet 1
2720/// always carries one.
2721fn sbr_start_packet(track: &mut AacTrack, from: u32) -> u32 {
2722 let mut id = from.max(1);
2723 while id > 1 {
2724 if sbr_packet_has_header(track, id) {
2725 return id;
2726 }
2727 id -= 1;
2728 }
2729 1
2730}
2731
2732/// Whether packet `id`, decoded on its own by a fresh decoder, comes out as a
2733/// full SBR frame. A failed read or decode counts as no.
2734fn sbr_packet_has_header(track: &mut AacTrack, id: u32) -> bool {
2735 let Ok(Some(sample)) = mp4track::sample(&mut track.reader, track.stream, id) else {
2736 return false;
2737 };
2738 let Ok(mut decoder) = aac_decoder(&track.params, track.source_channels()) else {
2739 return false;
2740 };
2741 let packet = Packet::new(
2742 track.track_id,
2743 units::Timestamp::new(sample.dts.unwrap_or(0)),
2744 units::Duration::new(u64::from(sample.duration.unwrap_or(0).max(0) as u32)),
2745 &sample.data[..],
2746 );
2747 let mut out = Vec::new();
2748 if decoder.decode(&packet, &mut out).is_err() {
2749 return false;
2750 }
2751 out.len() >= SBR_FULL_FRAME * track.source_channels()
2752}
2753
2754/// Where packet `id` starts on the track's timeline, from its time-to-sample
2755/// entries (`(count, delta)` runs, as [`packet_at`] reads them).
2756fn packet_start_ts(stts: &[(u32, u32)], id: u32) -> u64 {
2757 let mut first = 1u32;
2758 let mut ts = 0u64;
2759 for &(count, delta) in stts {
2760 if id < first + count {
2761 return ts + u64::from(id - first) * u64::from(delta);
2762 }
2763 first += count;
2764 ts += u64::from(count) * u64::from(delta);
2765 }
2766 ts
2767}
2768
2769/// The decoder for an AAC track of `from` channels: `ec-aac`, whatever the
2770/// width and whether or not the stream is HE-AAC. symphonia's own refused SBR
2771/// outright ("aac: aac too complex", `aac/mod.rs:91-96`), so it is not asked.
2772///
2773/// The config is the track's AudioSpecificConfig when it has one (mp4 `esds`,
2774/// Matroska `CodecPrivate`), which is what arms SBR. An ADTS stream has none,
2775/// and `ec-aac` takes its parameters from the first frame it reads.
2776fn aac_decoder(params: &AudioCodecParameters, from: usize) -> crate::Result<SymDecoder> {
2777 let decoder = match params.extra_data.as_deref() {
2778 Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)
2779 .map_err(|e| format!("AAC decoder init failed: {e}"))?,
2780 None => ec_aac::AacDecoder::new(),
2781 };
2782 Ok(SymDecoder::Aac(Box::new(decoder), from))
2783}
2784
2785/// The rate an AudioSpecificConfig decodes at: the extension rate for HE-AAC
2786/// (SBR reconstructed), the core rate otherwise. `Err` for a config `ec-aac`
2787/// cannot parse, which is a track that will not decode either.
2788fn aac_output_rate(asc: &[u8]) -> crate::Result<Option<u32>> {
2789 let decoder = ec_aac::AacDecoder::with_config_bytes(asc)
2790 .map_err(|e| format!("AAC config does not parse: {e}"))?;
2791 Ok(decoder.output_sample_rate())
2792}
2793
2794/// How many access units the implicit-SBR probe decodes. An SBR payload shows
2795/// in the first frame that carries one, and every SBR frame carries one, so two
2796/// frames are enough and bound the cost of opening a track.
2797const AAC_PRIME_UNITS: usize = 2;
2798
2799/// Whether an AAC track's rate can still change under implicit SBR: no config
2800/// (ADTS), or a plain AAC-LC one. An explicit SBR config states its rate, and a
2801/// PS one states its stereo output and rate, so neither is decoded to find out.
2802fn aac_may_be_implicit(asc: Option<&[u8]>) -> crate::Result<bool> {
2803 let Some(asc) = asc else {
2804 return Ok(true);
2805 };
2806 let decoder = ec_aac::AacDecoder::with_config_bytes(asc)
2807 .map_err(|e| format!("AAC config does not parse: {e}"))?;
2808 Ok(decoder.sbr_support() == ec_aac::SbrSupport::NotSignalled)
2809}
2810
2811/// What an AAC track decodes at, as a throwaway decoder finds it after its first
2812/// access units.
2813struct AacPrimed {
2814 sample_rate: u32,
2815 channels: u16,
2816 /// Whether an implicit SBR payload switched the rate on.
2817 implicit: bool,
2818}
2819
2820/// Decodes up to [`AAC_PRIME_UNITS`] of `units` through a fresh decoder, built
2821/// from `asc` or else from the first ADTS header, and reads back the rate it
2822/// now decodes at. `None` when no unit decodes: the caller keeps the rate its
2823/// container states, and the decode error surfaces on playback as it always has.
2824fn aac_prime(asc: Option<&[u8]>, units: &[&[u8]]) -> crate::Result<Option<AacPrimed>> {
2825 let mut decoder = match asc {
2826 Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)
2827 .map_err(|e| format!("AAC config does not parse: {e}"))?,
2828 None => ec_aac::AacDecoder::new(),
2829 };
2830 let mut channels = None;
2831 for unit in units.iter().take(AAC_PRIME_UNITS) {
2832 let Ok(pcm) = decoder.decode(unit, None) else {
2833 break;
2834 };
2835 channels = Some(pcm.channels);
2836 if decoder.sbr_implicit() {
2837 break;
2838 }
2839 }
2840 let (Some(channels), Some(sample_rate)) = (channels, decoder.output_sample_rate()) else {
2841 return Ok(None);
2842 };
2843 Ok(Some(AacPrimed {
2844 sample_rate,
2845 channels,
2846 implicit: decoder.sbr_implicit(),
2847 }))
2848}
2849
2850/// The first `count` packets of track `track_id` (for Matroska, its `TrackNumber`),
2851/// read through a fresh reader. Empty where the file cannot be read or has none,
2852/// and then the caller keeps what the header states.
2853pub(crate) fn first_packets(path: &Path, track_id: u32, count: usize) -> Vec<Vec<u8>> {
2854 let Ok(mut reader) = sym_reader(path) else {
2855 return Vec::new();
2856 };
2857 let mut out = Vec::with_capacity(count);
2858 while out.len() < count {
2859 match reader.next_packet() {
2860 Ok(Some(packet)) if packet.track_id == track_id => out.push(packet.data.to_vec()),
2861 Ok(Some(_)) => {}
2862 _ => break,
2863 }
2864 }
2865 out
2866}
2867
2868/// [`aac_prime`] over the first packets of `track_id`, read through a fresh
2869/// reader on `path`. A raw ADTS frame carries its own header, so it is decoded
2870/// as it stands.
2871fn sym_aac_prime(
2872 path: &Path,
2873 track_id: u32,
2874 asc: Option<&[u8]>,
2875) -> crate::Result<Option<AacPrimed>> {
2876 let mut reader = sym_reader(path)?;
2877 let mut units: Vec<Box<[u8]>> = Vec::with_capacity(AAC_PRIME_UNITS);
2878 while units.len() < AAC_PRIME_UNITS {
2879 match reader.next_packet()? {
2880 Some(packet) if packet.track_id == track_id => units.push(packet.data),
2881 Some(_) => {}
2882 None => break,
2883 }
2884 }
2885 let refs: Vec<&[u8]> = units.iter().map(|u| &u[..]).collect();
2886 aac_prime(asc, &refs)
2887}
2888
2889/// [`aac_prime`] over the first samples of an mp4 track, read through a fresh
2890/// reader on `path`: the track's own reader is borrowed by the track it opens.
2891fn mp4_aac_prime(path: &Path, stream: u32, asc: &[u8]) -> crate::Result<Option<AacPrimed>> {
2892 let mut reader = mp4track::open(path)?;
2893 let mut units: Vec<Vec<u8>> = Vec::with_capacity(AAC_PRIME_UNITS);
2894 for id in 1..=AAC_PRIME_UNITS as u32 {
2895 match mp4track::sample(&mut reader, stream, id) {
2896 Ok(Some(sample)) => units.push(sample.data.to_vec()),
2897 _ => break,
2898 }
2899 }
2900 let refs: Vec<&[u8]> = units.iter().map(Vec::as_slice).collect();
2901 aac_prime(Some(asc), &refs)
2902}
2903
2904/// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of
2905/// `OpusHead`, little-endian. Zero for a track whose header is missing or too
2906/// short to hold one -- there is nothing to subtract that we can trust.
2907fn opus_pre_skip(head: &[u8]) -> u64 {
2908 match head {
2909 [
2910 b'O',
2911 b'p',
2912 b'u',
2913 b's',
2914 b'H',
2915 b'e',
2916 b'a',
2917 b'd',
2918 _,
2919 _,
2920 lo,
2921 hi,
2922 ..,
2923 ] => u64::from(u16::from_le_bytes([*lo, *hi])),
2924 _ => 0,
2925 }
2926}
2927
2928/// The stream layout of an Opus track, off the file's own `OpusHead`: how many
2929/// elementary streams one packet carries, how many of those are coupled
2930/// (stereo), and which decoded channel each output channel comes from. Both
2931/// readers hand the header over as `extra_data` verbatim -- an mkv's
2932/// `CodecPrivate`, an ogg's identification packet.
2933///
2934/// Mapping family 0 carries no table at all and is mono or stereo by definition;
2935/// every other family writes one (RFC 7845 §5.1), and family 1 -- the Vorbis
2936/// surround layout a 5.1 film track is written with -- is four streams of which
2937/// two are coupled.
2938///
2939/// Everything here is checked rather than trusted: `MultistreamDecoder::with_rate`
2940/// *panics* on a layout that breaks the RFC's limits, and this header comes
2941/// straight out of a file, so a truncated or hostile one has to come back as an
2942/// `Err` and be refused like any other undecodable track.
2943fn opus_layout(head: &[u8], channels: usize) -> crate::Result<(usize, usize, Vec<u8>)> {
2944 if !(1..=255).contains(&channels) {
2945 return Err(format!("an Opus track of {channels} channels").into());
2946 }
2947 let table = match head {
2948 [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', rest @ ..] if rest.len() > 10 => {
2949 // Byte 18 of the header is the mapping family; the table, when there
2950 // is one, is the two counts and one byte per output channel after it.
2951 match rest[10] {
2952 0 => None,
2953 _ => Some(rest.get(11..13 + channels).ok_or("a truncated OpusHead")?),
2954 }
2955 }
2956 // No header at all: the container declared the channel count and nothing
2957 // else, which only family 0 can honestly be.
2958 _ => None,
2959 };
2960 let Some(table) = table else {
2961 if channels > 2 {
2962 return Err(format!("an Opus track of {channels} channels with no mapping").into());
2963 }
2964 return Ok((1, channels - 1, (0..channels as u8).collect()));
2965 };
2966 let (streams, coupled) = (usize::from(table[0]), usize::from(table[1]));
2967 let mapping = table[2..].to_vec();
2968 let decoded = streams + coupled;
2969 if streams < 1 || coupled > streams || decoded > 255 {
2970 return Err(format!("an Opus track of {streams} streams, {coupled} coupled").into());
2971 }
2972 if !mapping
2973 .iter()
2974 .all(|&m| m == 255 || usize::from(m) < decoded)
2975 {
2976 return Err(format!("an Opus channel mapping outside its {decoded} streams").into());
2977 }
2978 Ok((streams, coupled, mapping))
2979}
2980
2981/// Surround Opus is stored in Vorbis channel order (RFC 7845 §5.1.1.2) and
2982/// [`downmix`] reads the film order every other decoder here hands back. This is
2983/// that permutation, in place, per width: each entry says which *source* channel
2984/// the output slot of that index reads. Mono, stereo and quad agree already, and
2985/// a width the RFC does not lay out is left alone rather than shuffled by guess.
2986fn vorbis_to_film_order(samples: &mut [f32], from: usize) {
2987 let order: &[usize] = match from {
2988 3 => &[0, 2, 1], // FL FC FR
2989 5 => &[0, 2, 1, 3, 4], // FL FC FR SL SR
2990 6 => &[0, 2, 1, 5, 3, 4], // FL FC FR SL SR LFE
2991 7 => &[0, 2, 1, 6, 5, 3, 4], // FL FC FR SL SR BC LFE
2992 8 => &[0, 2, 1, 7, 5, 6, 3, 4], // FL FC FR SL SR BL BR LFE
2993 _ => return,
2994 };
2995 let mut frame = [0.0f32; 8];
2996 for chunk in samples.chunks_exact_mut(from) {
2997 frame[..from].copy_from_slice(chunk);
2998 for (out, &src) in chunk.iter_mut().zip(order) {
2999 *out = frame[src];
3000 }
3001 }
3002}
3003
3004/// What each channel of a `from`-wide film-order layout contributes to the left
3005/// and the right of a stereo fold. ITU-R BS.775: a front channel keeps its own
3006/// side, the centre and the back centre go to both at -3 dB, a surround joins
3007/// its own side at -3 dB, and the LFE is dropped -- it carries no programme a
3008/// stereo pair could put anywhere, and neither ffmpeg's default downmix nor any
3009/// player's puts it there.
3010///
3011/// The film order is FL, FR, FC, LFE, BL, BR, SL, SR, which is what symphonia's
3012/// decoders and `ec-aac` both hand back (the latter reorders AAC's own
3013/// C, L, R, Ls, Rs, LFE element order into it: its `film_order`) and what the
3014/// AC-3 decoder's own passthrough uses.
3015///
3016/// corner-cut: a width past 7.1 (22.2, ambisonics) keeps its front pair and drops
3017/// the rest -- no table here places those, and inventing one silently would be
3018/// worse than a fold that is merely narrow. Upgrade path is one more arm.
3019fn fold_coeffs(from: usize) -> Vec<(f32, f32)> {
3020 const C: f32 = std::f32::consts::FRAC_1_SQRT_2;
3021 const L: (f32, f32) = (1.0, 0.0);
3022 const R: (f32, f32) = (0.0, 1.0);
3023 const M: (f32, f32) = (C, C);
3024 const SL: (f32, f32) = (C, 0.0);
3025 const SR: (f32, f32) = (0.0, C);
3026 const X: (f32, f32) = (0.0, 0.0);
3027 match from {
3028 3 => vec![L, R, X], // L R LFE (the 2.1 passthrough)
3029 4 => vec![L, R, SL, SR], // FL FR BL BR
3030 5 => vec![L, R, M, SL, SR], // FL FR FC BL BR
3031 6 => vec![L, R, M, X, SL, SR], // 5.1
3032 7 => vec![L, R, M, X, M, SL, SR], // FL FR FC LFE BC SL SR
3033 8 => vec![L, R, M, X, SL, SR, SL, SR], // 7.1
3034 n => (0..n).map(|c| [L, R][usize::from(c > 0)]).collect(),
3035 }
3036}
3037
3038/// Anything wider than a stereo pair down to one, in place -- `from` is the
3039/// channel count the decoder actually emitted, and 1 or 2 is not touched at all.
3040/// This is what makes a 5.1 or 7.1 film an ordinary stereo source on the
3041/// timeline instead of an import refusal.
3042///
3043/// Both outputs are divided by the sum of their own coefficients
3044/// ([`fold_coeffs`]), so a source at full scale cannot come out clipped.
3045///
3046/// corner-cut: that normalisation costs 7.7 dB at 5.1 (9.9 at 7.1) against what
3047/// ffmpeg's `-ac 2` hands out, which does not normalise and can overload -- so a
3048/// film plays quieter here than in a player beside it. It is the loudness the
3049/// AC-3 5.1 path already has (measured within 1.3 dB), so the two agree; the
3050/// upgrade path is a limiter on the output, at which point the coefficients can
3051/// go back to 1.0.
3052fn downmix(samples: &mut Vec<f32>, from: usize) {
3053 if from < 3 {
3054 return;
3055 }
3056 let coeffs = fold_coeffs(from);
3057 let (left, right) = coeffs
3058 .iter()
3059 .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1));
3060 // Never a boost: a layout with nothing on one side stays where it is.
3061 let (left, right) = (1.0 / left.max(1.0), 1.0 / right.max(1.0));
3062 for frame in 0..samples.len() / from {
3063 let (mut l, mut r) = (0.0, 0.0);
3064 for (c, &(cl, cr)) in coeffs.iter().enumerate() {
3065 let sample = samples[frame * from + c];
3066 l += cl * sample;
3067 r += cr * sample;
3068 }
3069 samples[2 * frame] = l * left;
3070 samples[2 * frame + 1] = r * right;
3071 }
3072 samples.truncate(samples.len() / from * 2);
3073}
3074
3075/// The inverse of [`downmix`]: a mono buffer duplicated into every channel of
3076/// a wider timeline, in place. `from` is the width the decoder actually
3077/// handed back (already folded to 1 or 2 by [`downmix`] at its own door) and
3078/// `to` is the timeline's own width ([`mix`]'s `channels`); anything that is
3079/// not exactly the mono-into-wider case is left untouched -- a source already
3080/// at `to`, and a source wider than `to` other than a stereo pair onto a mono
3081/// timeline. That one is the remix the other way: each frame's two channels
3082/// are averaged into the timeline's single one (half of each, so full scale
3083/// in is full scale out), the same fold ffmpeg's `-ac 1` makes. Without it a
3084/// stereo file joining a mono timeline would hand the mixer twice the samples
3085/// it expects and play at double speed.
3086fn widen(samples: &mut Vec<f32>, from: usize, to: usize) {
3087 if from == 2 && to == 1 {
3088 let mut out = Vec::with_capacity(samples.len() / 2);
3089 out.extend(
3090 samples
3091 .as_chunks::<2>()
3092 .0
3093 .iter()
3094 .map(|f| (f[0] + f[1]) * 0.5),
3095 );
3096 *samples = out;
3097 return;
3098 }
3099 if from != 1 || to <= 1 {
3100 return;
3101 }
3102 let mut out = Vec::with_capacity(samples.len() * to);
3103 for &s in samples.iter() {
3104 out.extend(std::iter::repeat_n(s, to));
3105 }
3106 *samples = out;
3107}
3108
3109/// One source's AC-3 track: the same mp4 sample tables the AAC track is read
3110/// from, decoded through `ec-ac3` and **downmixed to stereo by the decoder
3111/// itself** (ATSC A/52 §7.8.2, [`ec_ac3::Downmix::Stereo`]), because one output
3112/// device and one timeline layout is all there is. A 5.1 BluRay track therefore
3113/// arrives here as an ordinary stereo source, and its rows in the picker say so.
3114///
3115/// `channels` is what the decoder actually emitted for the first frame rather
3116/// than an assumed 2: everything from stereo to 5.1 downmixes to stereo and a
3117/// mono track passes through as the one channel it is (`acmod` carries the
3118/// programme in the centre; duplicating it is the timeline's business, see
3119/// [`widen`]). The §7.8.2 fold is position-aware — every `acmod` from 1/0 to
3120/// 3/2 puts its centre and surrounds where the matrix says — so no width is
3121/// refused or mislabelled.
3122struct Ac3Track {
3123 reader: mp4track::Reader,
3124 stream: u32,
3125 sample_count: u32,
3126 sample_rate: u32,
3127 channels: u16,
3128 timescale: u32,
3129 priming: u64,
3130 total_samples: Option<u64>,
3131 stts: Vec<(u32, u32)>,
3132 /// What the decoder is asked to hand out, from this track's own layout:
3133 /// [`ec_ac3::Downmix::Stereo`] for anything with more than one front
3134 /// channel, [`ec_ac3::Downmix::Native`] — the coded channels untouched —
3135 /// for a mono track. See [`ac3_decoder`].
3136 requested: Option<u16>,
3137}
3138
3139impl Ac3Track {
3140 /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it
3141 /// is anything else (including out of range) — the caller then goes on to
3142 /// the AAC reader, which owns those verdicts and their wording.
3143 ///
3144 /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without
3145 /// keeping the fourcc, so what the track *is* comes out of the `stsd` by
3146 /// hand ([`crate::demux::sample_entry`]); the rate and the channel count
3147 /// come out of the first syncframe, which is where AC-3 states them.
3148 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
3149 let mut reader = mp4track::open(path)?;
3150 let Some(&(track_id, stream_id)) = mp4track::audio_tracks(&reader).get(stream) else {
3151 return Ok(None);
3152 };
3153 let Some(stream_id) = stream_id else {
3154 return Ok(None);
3155 };
3156 if &mp4track::sample_entry(&reader, track_id) != b"ac-3" {
3157 return Ok(None);
3158 }
3159 let timescale = mp4track::timescale(&reader, stream_id);
3160 let duration = mp4track::duration(&reader, stream_id).unwrap_or(0);
3161 let edit = mp4track::media_time(&reader, track_id);
3162 let stts = mp4track::stts(&reader, stream_id);
3163 let sample_count = mp4track::sample_count(&reader, stream_id);
3164
3165 let first = mp4track::sample(&mut reader, stream_id, 1)?
3166 .ok_or("the AC-3 track has no samples")?;
3167 let sample_rate = ec_ac3::syncinfo::parse(&first.data)
3168 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?
3169 .sample_rate;
3170 let nfchans = ec_ac3::bsi::parse(first.data.get(5..).unwrap_or_default())
3171 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
3172 .nfchans;
3173 let requested = (nfchans > 1).then_some(2);
3174 let mut decoder = ac3_decoder(requested)?;
3175 let channels = decode_ac3(&mut decoder, &first.data)?
3176 .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16)
3177 .filter(|&c| c > 0)
3178 .ok_or("the first AC-3 syncframe decoded to nothing")?;
3179
3180 // No encoder delay in AC-3; a remux that writes an edit list is still
3181 // honoured, exactly as the AAC track honours it.
3182 let priming = edit
3183 .and_then(|t| scale(t, sample_rate, timescale))
3184 .unwrap_or(0);
3185 Ok(Some(Self {
3186 stream: stream_id,
3187 sample_count,
3188 sample_rate,
3189 channels,
3190 timescale,
3191 priming,
3192 total_samples: scale(duration, sample_rate, timescale)
3193 .map(|d| d.saturating_sub(priming)),
3194 stts,
3195 requested,
3196 reader,
3197 }))
3198 }
3199
3200 /// `secs` on this source's audible timeline into media samples.
3201 fn media(&self, secs: f64) -> u64 {
3202 ((secs * f64::from(self.sample_rate)).round() as u64).saturating_add(self.priming)
3203 }
3204
3205 /// One `[start, end)` window, resolved to syncframes and media samples —
3206 /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll.
3207 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
3208 let media_target = self.media(start_secs);
3209 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
3210 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL);
3211 Segment {
3212 source: Some(source),
3213 start_id,
3214 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
3215 media_target,
3216 media_end: self.media(end_secs).max(media_target),
3217 }
3218 }
3219}
3220
3221/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same
3222/// decoder and the very same §7.8.2 stereo downmix [`Ac3Track`] runs, fed out of
3223/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux
3224/// therefore arrives on the timeline as an ordinary stereo source, exactly as
3225/// the mp4 path's does, and mono passes through exactly the same way.
3226///
3227/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side
3228/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]):
3229/// one block is one packet, one packet is one syncframe, and a seek lands on
3230/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in
3231/// front of it.
3232struct MkvAc3Track {
3233 mkv: crate::demux::MkvAudio,
3234 sample_rate: u32,
3235 /// What comes *out* of the decoder, measured on the first frame — 2 for
3236 /// anything from stereo to 5.1, 1 for a mono track (see `requested`).
3237 channels: u16,
3238 total_samples: Option<u64>,
3239 /// What the decoder is asked to hand out, from this track's own layout:
3240 /// `Some(2)` for anything with more than one front channel, `None` for a
3241 /// mono track. See [`ac3_decoder`].
3242 requested: Option<u16>,
3243}
3244
3245impl MkvAc3Track {
3246 /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 —
3247 /// that mkv is the silent source it has always been. An `Err` is a track
3248 /// that is one and could not be read, which
3249 /// [`AudioSession::unsupported`] quotes back to the user.
3250 fn open(path: &Path) -> crate::Result<Option<Self>> {
3251 Self::from_blocks(crate::demux::MkvAudio::open(path)?)
3252 }
3253
3254 /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]),
3255 /// which is how the AC-3 half of a dual-audio file is reached.
3256 ///
3257 /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number
3258 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
3259 Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?)
3260 }
3261
3262 fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> {
3263 let Some(mut mkv) = mkv else {
3264 return Ok(None);
3265 };
3266 // A TrueHD or MLP track has blocks too, and its own decoder ([`MkvTruehdTrack`]).
3267 if !matches!(mkv.codec, "ac3" | "eac3") {
3268 return Ok(None);
3269 }
3270 let first = mkv
3271 .frame(0)?
3272 .ok_or("the AC-3 track of this Matroska file has no blocks")?;
3273 // Rate and layout come out of the bit stream, which is where AC-3
3274 // states them: Matroska's `Audio` element repeats them and muxers get
3275 // that wrong often enough that the frame is the better source.
3276 // `nfchans` excludes the LFE in both syntaxes, which is what the
3277 // downmix decision wants.
3278 let (sample_rate, nfchans) = if mkv.codec == "eac3" {
3279 // Annex E's BSI starts right after the 16-bit syncword.
3280 let bsi = ec_ac3::eac3::parse(first.get(2..).unwrap_or_default())
3281 .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?;
3282 (bsi.sample_rate, bsi.nfchans)
3283 } else {
3284 let sync = ec_ac3::syncinfo::parse(&first)
3285 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?;
3286 let bsi = ec_ac3::bsi::parse(first.get(5..).unwrap_or_default())
3287 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?;
3288 (sync.sample_rate, bsi.nfchans)
3289 };
3290 let requested = (nfchans > 1).then_some(2);
3291 let mut decoder = ac3_decoder(requested)?;
3292 let (pcm, samples) = decode_ac3(&mut decoder, &first)?
3293 .ok_or("the first AC-3 syncframe decoded to nothing")?;
3294 let channels = (pcm.len() as u64 / samples.max(1)) as u16;
3295 if channels == 0 {
3296 return Err("the first AC-3 syncframe decoded to nothing".into());
3297 }
3298 // The track runs to the last block's timestamp plus that block's own
3299 // frame -- a container that indexes nothing states no duration either,
3300 // and every frame of a syncframe stream is the same length.
3301 let last = mkv.secs(mkv.blocks().saturating_sub(1));
3302 Ok(Some(Self {
3303 total_samples: Some((last * f64::from(sample_rate)) as u64 + samples),
3304 sample_rate,
3305 channels,
3306 requested,
3307 mkv,
3308 }))
3309 }
3310
3311 /// `secs` on this source's timeline into media samples. No priming: the
3312 /// container carries no edit list and AC-3 no encoder delay.
3313 fn media(&self, secs: f64) -> u64 {
3314 (secs.max(0.0) * f64::from(self.sample_rate)).round() as u64
3315 }
3316
3317 /// One `[start, end)` window, resolved to blocks and media samples —
3318 /// [`Ac3Track::segment`] against block timestamps instead of an `stts`.
3319 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
3320 let media_target = self.media(start_secs);
3321 let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize);
3322 Segment {
3323 source: Some(source),
3324 start_id: start_id as u32,
3325 start_pos: self.media(self.mkv.secs(start_id)),
3326 media_target,
3327 media_end: self.media(end_secs).max(media_target),
3328 }
3329 }
3330}
3331
3332/// A fresh AC-3 / E-AC-3 decoder. `requested` is the downmix ask: `Some(2)`
3333/// hands back the library's own A/52 §7.8.2 stereo fold — per-position
3334/// coefficients from the frame's own `acmod` and mix levels, LFE dropped,
3335/// normalised so a full-scale mix cannot clip — which is the whole reason the
3336/// timeline can carry a 5.1 track at all; `None` passes the coded channels
3337/// through, which is what a mono track asks for (`acmod` 1/0 carries the
3338/// programme in the centre, and duplicating it is the timeline's business, see
3339/// [`widen`]). Fresh per segment for the same reason every other decoder here
3340/// is: a seek leaves overlap-add state belonging to the frames we skipped.
3341///
3342/// The syntax is not an argument: one decoder reads AC-3 and E-AC-3 alike,
3343/// dispatching per packet on `bsid`.
3344fn ac3_decoder(requested: Option<u16>) -> crate::Result<ec_ac3::Ac3Decoder> {
3345 Ok(ec_ac3::Ac3Decoder::with_options(ec_ac3::Options {
3346 downmix: requested
3347 .map(|_| ec_ac3::Downmix::Stereo)
3348 .unwrap_or(ec_ac3::Downmix::Native),
3349 ..ec_ac3::Options::default()
3350 }))
3351}
3352
3353/// One syncframe in, one buffer of interleaved f32 out and the frames per
3354/// channel it holds. `Ok(None)` when the decoder wants more input before it can
3355/// hand a frame back, which is not an error. The library speaks interleaved
3356/// little-endian f32 — the same `[-1, 1)` every other reader here emits.
3357///
3358/// The frame count comes back beside the samples because an E-AC-3 frame is not
3359/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2
3360/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the
3361/// channel count and every media position after it out.
3362fn decode_ac3(
3363 decoder: &mut ec_ac3::Ac3Decoder,
3364 bytes: &[u8],
3365) -> crate::Result<Option<(Vec<f32>, u64)>> {
3366 match decoder.decode_frame(bytes) {
3367 Ok(frame) => Ok(Some((
3368 frame.data[0]
3369 .as_chunks::<4>()
3370 .0
3371 .iter()
3372 .map(|s| f32::from_le_bytes(*s))
3373 .collect(),
3374 frame.samples as u64,
3375 ))),
3376 Err(ec_ac3::Error::NeedMore) => Ok(None),
3377 Err(e) => Err(format!("AC-3 decode failed: {e}").into()),
3378 }
3379}
3380
3381/// One source's AAC track, resolved once: the reader plus everything the header
3382/// has to say about it. `stts` is copied out because every other field would
3383/// otherwise keep a borrow alive on the reader the worker needs mutably — a real
3384/// AAC track has one entry, so it is two `u32`s.
3385struct AacTrack {
3386 reader: mp4track::Reader,
3387 stream: u32,
3388 track_id: u32,
3389 sample_count: u32,
3390 sample_rate: u32,
3391 timescale: u32,
3392 /// Encoder delay of *this* file. Sources are joined, priming is not shared.
3393 priming: u64,
3394 total_samples: Option<u64>,
3395 stts: Vec<(u32, u32)>,
3396 /// Channels the decoder emits, from the config: 1 for mono.
3397 layout_channels: usize,
3398 freq_index: u8,
3399 chan_conf: u8,
3400 /// HE-AAC: the stream carries SBR, so [`sample_rate`](Self::sample_rate) is
3401 /// the extension rate and a packet holds twice the core's frames. Such a
3402 /// track decodes but cannot be packet-copied, because the copy writes an
3403 /// AAC-LC config back out from `freq_index`/`chan_conf`.
3404 sbr: bool,
3405 /// A fresh decoder is built from these per segment: seeking mid-stream
3406 /// leaves MDCT and PNS state that belongs to the packets we skipped.
3407 params: AudioCodecParameters,
3408}
3409
3410impl AacTrack {
3411 /// The `stream`-th audio track of `path`, counted in file order over *all*
3412 /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out.
3413 ///
3414 /// Stream 0 is best effort: `Ok(None)` when there is no AAC track there at
3415 /// all, which is a valid silent source (a file whose audio is AC-3 still has
3416 /// a picture worth editing) and, for a standalone audio file, the door
3417 /// through to symphonia ([`Track::open`]). A stream the caller *named* is a
3418 /// promise instead, so out of range or not AAC there is an `Err` rather than
3419 /// silence the caller did not ask for.
3420 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
3421 let reader = mp4track::open(path)?;
3422 let audio = mp4track::audio_tracks(&reader);
3423 let Some(&(track_id, codec_stream)) = audio.get(stream) else {
3424 return match stream {
3425 0 => Ok(None),
3426 n => Err(format!(
3427 "{}: audio stream {n} of {} streams",
3428 path.display(),
3429 audio.len()
3430 )
3431 .into()),
3432 };
3433 };
3434 let stream_id = match codec_stream {
3435 Some(s) if mp4track::codec(&reader, s) == Some(CodecId::Aac) => s,
3436 _ => {
3437 return match stream {
3438 0 => Ok(None),
3439 n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()),
3440 };
3441 }
3442 };
3443 // The config as the file states it, extension frequency and all: the
3444 // decoder needs the SBR part, which a bare rate and channel count do not
3445 // carry.
3446 let asc: Box<[u8]> = mp4track::extradata(&reader, stream_id)
3447 .ok_or_else(|| format!("{}: AAC track has no config", path.display()))?;
3448 // Refuse early with a message instead of failing packet by packet. LC,
3449 // HE-AAC v1 (SBR) and HE-AAC v2 (SBR with PS) all decode through `ec-aac`.
3450 let (mut sbr, ps) = match asc_fields(&asc)?.0 {
3451 AAC_LC => (false, false),
3452 AAC_SBR => (true, false),
3453 AAC_PS => (true, true),
3454 other => {
3455 return Err(format!(
3456 "unsupported AAC profile: audio object type {other} (only AAC-LC, HE-AAC v1 and v2)"
3457 )
3458 .into());
3459 }
3460 };
3461
3462 let mut layout_channels = mp4track::channels(&reader, stream_id);
3463 if layout_channels == 0 {
3464 return Err(format!("{}: AAC config declares no channels", path.display()).into());
3465 }
3466 // The rate `ec-aac` decodes at, which for HE-AAC is the extension rate:
3467 // the container's own rate is the core's, and a timeline counted in it
3468 // would run at half speed against the decoded samples.
3469 let mut sample_rate = aac_output_rate(&asc)?
3470 .ok_or_else(|| format!("{}: AAC config declares no sample rate", path.display()))?;
3471 // Plain LC may carry SBR by implicit signalling: the rate is the decoded
3472 // one, read off the first access units, as for an ADTS or mkv stream.
3473 if aac_may_be_implicit(Some(&asc[..]))?
3474 && let Some(primed) = mp4_aac_prime(path, stream_id, &asc)?
3475 {
3476 sample_rate = primed.sample_rate;
3477 sbr |= primed.implicit;
3478 // The decoder's own width: an implicit PS payload makes a mono core
3479 // stereo, and the container's channel count does not say so.
3480 layout_channels = usize::from(primed.channels);
3481 }
3482 // Explicit HE-AAC v2 is stereo whatever the core's channel count.
3483 if ps {
3484 layout_channels = 2;
3485 }
3486 let timescale = mp4track::timescale(&reader, stream_id);
3487 let priming = priming_samples(
3488 mp4track::media_time(&reader, track_id),
3489 sample_rate,
3490 timescale,
3491 );
3492 let (_, freq_index, chan_conf) = asc_fields(&asc)?;
3493 let duration = mp4track::duration(&reader, stream_id);
3494 let mut params = AudioCodecParameters::new();
3495 params
3496 .for_codec(CODEC_ID_AAC)
3497 .with_sample_rate(sample_rate)
3498 .with_extra_data(asc);
3499 let this = Self {
3500 sample_count: mp4track::sample_count(&reader, stream_id),
3501 stts: mp4track::stts(&reader, stream_id),
3502 total_samples: duration
3503 .and_then(|d| scale(d, sample_rate, timescale))
3504 .map(|d| d.saturating_sub(priming)),
3505 stream: stream_id,
3506 track_id,
3507 sample_rate,
3508 timescale,
3509 priming,
3510 layout_channels,
3511 freq_index,
3512 chan_conf,
3513 sbr,
3514 params,
3515 reader,
3516 };
3517 Ok(Some(this))
3518 }
3519
3520 /// What reaches the timeline: mono, or the stereo everything wider is folded
3521 /// to by [`downmix`] at the decoder's door.
3522 fn channels(&self) -> u16 {
3523 match self.source_channels() {
3524 1 => 1,
3525 _ => 2,
3526 }
3527 }
3528
3529 /// What the decoder emits, which is what the fold reads.
3530 fn source_channels(&self) -> usize {
3531 self.layout_channels.max(1)
3532 }
3533
3534 fn track_params(&self) -> AacTrackParams {
3535 AacTrackParams {
3536 freq_index: self.freq_index,
3537 chan_conf: self.chan_conf,
3538 sample_rate: self.sample_rate,
3539 }
3540 }
3541
3542 /// `secs` on this source's audible timeline into media samples (priming
3543 /// included, so it compares directly against a decoded position).
3544 /// `f64::INFINITY` saturates.
3545 fn media(&self, secs: f64) -> u64 {
3546 ((secs * f64::from(self.sample_rate)).round() as u64).saturating_add(self.priming)
3547 }
3548
3549 /// One `[start, end)` window of this source's seconds, resolved to its own
3550 /// packets and media samples.
3551 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
3552 let media_target = self.media(start_secs);
3553 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
3554 // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
3555 // packet to cancel aliasing, plus one more to warm the decoder up. Their
3556 // output is discarded below, so this only costs decode time. An SBR track
3557 // is walked back further when it is decoded ([`sbr_start_packet`]).
3558 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL);
3559 Segment {
3560 source: Some(source),
3561 start_id,
3562 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
3563 media_target,
3564 // An inverted segment is an empty one, never a backwards run.
3565 media_end: self.media(end_secs).max(media_target),
3566 }
3567 }
3568}
3569
3570/// [`packet_run`] for the last segment of a copy. Rounded to nearest, the debt
3571/// that run leaves is never paid: `test_sync.mp4`'s 4.0 s is 172.27 packets, so
3572/// 172 were copied and the sound stopped 6 ms short of its picture. Nothing
3573/// follows the last segment to take the shortfall, so this rounds up instead --
3574/// at most one packet, under a frame, past the picture.
3575fn packet_run_last(err: &mut i64, ideal: i64, available: u32) -> u32 {
3576 let packet = i64::from(SAMPLES_PER_PACKET);
3577 let ideal = ideal.min(i64::from(available) * packet);
3578 let want = (ideal - *err) as f64 / packet as f64;
3579 let n = (want.ceil().max(0.0) as i64).min(i64::from(available)) as u32;
3580 *err += i64::from(n) * packet - ideal;
3581 n
3582}
3583
3584/// How many whole packets to copy for a window of `ideal` samples per channel,
3585/// capped at the `available` packets left in the track.
3586///
3587/// `err` is "samples copied so far minus samples asked for", carried across the
3588/// segment joins: rounding to nearest *against the running debt* keeps the
3589/// cumulative error inside half a packet forever, where independent per-segment
3590/// rounding would random-walk away from sync (charter D1: < 1024 at every join).
3591fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
3592 let packet = i64::from(SAMPLES_PER_PACKET);
3593 // Never carry a debt the track cannot pay: a segment running past the end
3594 // would otherwise inflate every later one. (Also tames `f64::INFINITY`,
3595 // which saturates to `i64::MAX` on the cast above.)
3596 let ideal = ideal.min(i64::from(available) * packet);
3597 let want = (ideal - *err) as f64 / packet as f64;
3598 let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32;
3599 *err += i64::from(n) * packet - ideal;
3600 n
3601}
3602
3603/// The order a Matroska file's audio streams are numbered in, as positions into
3604/// `tracks` (which is file order): **stream 0 is the track this project has
3605/// always opened**, and the rest follow in file order behind it.
3606///
3607/// Not file order outright, and the difference is a saved project's sound. A
3608/// remux flags the language it wants heard with `FlagDefault` on whichever
3609/// track it likes -- mkvmerge writes it on the second one all the time -- and
3610/// that flag is what every reader here used to pick with. Numbering by file
3611/// position would have made stream 0 a *different* track on those files, so an
3612/// `.edith` project saved before this would quietly start playing the other
3613/// language. Nothing that already plays may change what it plays.
3614///
3615/// The old pick is not re-derived here, it is *run*: the AC-3 arm asks
3616/// [`MkvAc3Track`] the same question [`Track::open`] asked it (and only of the
3617/// file's first audio track, which is as far as [`crate::demux::MkvAudio`]
3618/// ever looked), and everything else asks symphonia for its default track,
3619/// which is `FlagDefault` where a muxer set one and the first readable track
3620/// where nobody did.
3621pub(crate) fn mkv_stream_order(path: &Path, tracks: &[crate::demux::MkvAudioTrack]) -> Vec<usize> {
3622 // One track is its own order, and it is the common case: no second probe
3623 // for the file that cannot have a second answer.
3624 if tracks.len() < 2 {
3625 return (0..tracks.len()).collect();
3626 }
3627 let head = match tracks.first() {
3628 Some(first) if dolby_track_opens(path, first) => 0,
3629 // A file symphonia will not open at all keeps file order: the open
3630 // itself is where that failure is reported, not the numbering.
3631 _ => SymTrack::open(path)
3632 .ok()
3633 .flatten()
3634 .and_then(|track| {
3635 tracks
3636 .iter()
3637 .position(|entry| entry.number == u64::from(track.track_id))
3638 })
3639 .unwrap_or(0),
3640 };
3641 std::iter::once(head)
3642 .chain((0..tracks.len()).filter(|i| *i != head))
3643 .collect()
3644}
3645
3646/// Whether `entry` is an AC-3, E-AC-3, TrueHD or MLP track one of the Dolby
3647/// decoders reads straight out of the blocks, and that decoder opens. The
3648/// question [`mkv_stream_order`] asks of the file's first track.
3649fn dolby_track_opens(path: &Path, entry: &crate::demux::MkvAudioTrack) -> bool {
3650 match entry.codec.as_str() {
3651 "A_AC3" | "A_EAC3" => matches!(MkvAc3Track::open_track(path, entry.number), Ok(Some(_))),
3652 "A_TRUEHD" | "A_MLP" => {
3653 matches!(MkvTruehdTrack::open_track(path, entry.number), Ok(Some(_)))
3654 }
3655 id if crate::extaudio::is_mkv_dts(id) || crate::extaudio::is_mkv_mpeg_layer(id) => {
3656 matches!(crate::extaudio::ExtFileTrack::open_native(path, entry.number), Ok(Some(_)))
3657 }
3658 _ => false,
3659 }
3660}
3661
3662/// The name a Matroska audio row wears: the container's own codec id, cut down
3663/// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`.
3664///
3665/// The codec id rather than symphonia's short name, because the rows that most
3666/// need naming are exactly the ones it has no decoder for: an Opus or DTS track
3667/// is greyed out with the codec in the reason (`unusable` in the app reads this
3668/// very string), where symphonia would call it "an unsupported format".
3669fn mkv_codec_name(id: &str) -> String {
3670 match id {
3671 "A_AC3" => "ac-3".into(),
3672 "A_EAC3" => "e-ac-3".into(),
3673 "A_MPEG/L3" => "mp3".into(),
3674 "A_MPEG/L1" | "A_MPEG/L2" => codec_display_name(id).to_ascii_lowercase(),
3675 _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(),
3676 }
3677}
3678
3679/// The AAC `audioObjectType`s this reads: LC, HE-AAC v1 (LC with SBR) and
3680/// HE-AAC v2 (SBR with Parametric Stereo).
3681const AAC_LC: u8 = 2;
3682const AAC_SBR: u8 = 5;
3683const AAC_PS: u8 = 29;
3684
3685/// `(profile, freq_index, chan_conf)` out of an `AudioSpecificConfig` (ISO
3686/// 14496-3 §1.6.2.1): the first five bits are the object type, the next four
3687/// the sampling-frequency index, the next four the channel configuration.
3688fn asc_fields(asc: &[u8]) -> crate::Result<(u8, u8, u8)> {
3689 match asc {
3690 [a, b, ..] => Ok((a >> 3, ((a & 0x7) << 1) | (b >> 7), (b >> 3) & 0xf)),
3691 _ => Err("AudioSpecificConfig shorter than its fixed header".into()),
3692 }
3693}
3694
3695/// Encoder delay in samples-per-channel: the edit list's first real entry says
3696/// how far into the media the presentation starts.
3697///
3698/// corner-cut: an explicit `media_time` of 0 is taken at face value (no trim).
3699/// Muxers that write a zero edit list despite a primed stream would leak the
3700/// priming; upgrade path is preferring the codec delay when it disagrees.
3701fn priming_samples(media_time: Option<u64>, sample_rate: u32, timescale: u32) -> u64 {
3702 media_time
3703 .and_then(|t| scale(t, sample_rate, timescale))
3704 .unwrap_or(DEFAULT_PRIMING)
3705}
3706
3707/// `value` from the track timescale into samples-per-channel. `None` on a zero
3708/// timescale, which would be a broken header.
3709fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
3710 let timescale = u64::from(timescale);
3711 (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
3712}
3713
3714/// Inverse of [`scale`]: samples-per-channel back into the track timescale.
3715fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 {
3716 match sample_rate {
3717 0 => 0,
3718 rate => samples * u64::from(timescale) / u64::from(rate),
3719 }
3720}
3721
3722/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll`
3723/// packets, plus that packet's own start time. Inverse of the mp4 crate's
3724/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is
3725/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs.
3726///
3727/// corner-cut: the walk-back is clamped to the start of the containing stts entry
3728/// rather than crossing into the previous one, so a target within `pre_roll`
3729/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
3730/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
3731/// carrying the previous entry's delta through the walk.
3732pub(crate) fn packet_at(
3733 entries: impl IntoIterator<Item = (u32, u32)>,
3734 target_ts: u64,
3735 pre_roll: u32,
3736) -> (u32, u64) {
3737 let mut first_id = 1u32;
3738 let mut elapsed = 0u64;
3739 let mut last = (1u32, 0u64);
3740 for (count, delta) in entries {
3741 let span = u64::from(count) * u64::from(delta);
3742 let index = if target_ts < elapsed + span && delta != 0 {
3743 ((target_ts - elapsed) / u64::from(delta)) as u32
3744 } else {
3745 // Past this entry: remember its last packet in case the target runs
3746 // past the end of the track entirely.
3747 last = (
3748 first_id + count.saturating_sub(1),
3749 elapsed + span.saturating_sub(u64::from(delta)),
3750 );
3751 first_id += count;
3752 elapsed += span;
3753 continue;
3754 };
3755 let index = index - index.min(pre_roll);
3756 return (
3757 first_id + index,
3758 elapsed + u64::from(index) * u64::from(delta),
3759 );
3760 }
3761 last
3762}
3763
3764/// One window of a source to decode, resolved to media samples and packets —
3765/// or, with no source, a stretch of synthesised silence.
3766struct Segment {
3767 /// Index into the worker's tracks; the media positions below are that
3768 /// source's, not the timeline's. `None` for a gap, where only the length
3769 /// (`media_end`) means anything.
3770 source: Option<usize>,
3771 /// First packet to feed the decoder, 1-based; includes the pre-roll.
3772 start_id: u32,
3773 /// Media position of `start_id`'s first frame, in samples-per-channel.
3774 start_pos: u64,
3775 /// Media position of the first frame to emit. Everything decoded before it
3776 /// is pre-roll, priming, or seek overshoot, and gets dropped.
3777 media_target: u64,
3778 /// One past the last frame to emit; `u64::MAX` for "to the end of track".
3779 media_end: u64,
3780}
3781
3782impl Segment {
3783 /// `frames` per channel of silence — a gap in the audio lane.
3784 fn silence(frames: u64) -> Self {
3785 Self {
3786 source: None,
3787 start_id: 0,
3788 start_pos: 0,
3789 media_target: 0,
3790 media_end: frames,
3791 }
3792 }
3793}
3794
3795/// The sample of a mix at `rate` that `secs` of timeline (from the mix's start) ends on:
3796/// the one rounding [`owed_samples`] makes of its running total, so anything that
3797/// has to land on the mix's own samples (an export's warm-up) counts them the same way.
3798pub(crate) fn timeline_sample(secs: f64, rate: u32) -> u64 {
3799 (secs * f64::from(rate)).round() as u64
3800}
3801
3802/// What each segment of a mix owes the timeline in samples, `None` for an
3803/// open-ended window. The sample each segment ends on is the running total of
3804/// the seconds it owes, rounded once against the mix rate, and a segment owes
3805/// the difference of two such roundings. Rounding each segment's own length
3806/// instead drifts: one frame at 59.94 fps is 800.8 samples, so every cut would
3807/// gain or lose up to a fifth of a sample, and a few thousand short cuts add up
3808/// to tens of samples.
3809fn owed_samples(
3810 segs: &[(Option<usize>, f64, f64)],
3811 speeds: &[Option<crate::project::Stretch>],
3812 rate: u32,
3813) -> Vec<Option<u64>> {
3814 let mut total_secs = 0.0f64;
3815 let mut at = 0u64;
3816 segs.iter()
3817 .enumerate()
3818 .map(|(i, &(_, start_secs, end_secs))| {
3819 let secs = speeds
3820 .get(i)
3821 .copied()
3822 .flatten()
3823 .map_or(end_secs - start_secs, |s| s.timeline_secs);
3824 if !secs.is_finite() {
3825 return None;
3826 }
3827 total_secs += secs.max(0.0);
3828 let end = timeline_sample(total_secs, rate);
3829 let owed = end.saturating_sub(at);
3830 at = end;
3831 Some(owed)
3832 })
3833 .collect()
3834}
3835
3836/// One segment's rate conversion: the decoded samples read at the ratio of
3837/// the source's own sample rate to the timeline's, which is a pure rate
3838/// conversion -- the pitch is preserved because the frames are read at the
3839/// ratio of the rates rather than dropped, and 48 kHz onto a 44.1 kHz
3840/// timeline is one resampler, not two. Linear interpolation between the two
3841/// frames a fractional position falls between -- one multiply-add per
3842/// channel, which is nothing beside the decode that produced them, and for a
3843/// 48:44.1 ratio its worst-case image lands ~40 dB down; the alternative is
3844/// a windowed-sinc kernel and a new state machine for a conversion that is
3845/// not the audible risk in this path.
3846///
3847/// It lives across the whole segment: `pos` carries the fraction over a packet
3848/// boundary and `tail` keeps the frame before the buffer, so the interpolation
3849/// at the seam is the same one it would have been inside a buffer. A segment
3850/// starts one clean and drops it at the end, which is what makes a seek a
3851/// reset for free -- exactly as the equalizer's state does.
3852///
3853/// Time is no longer this struct's business: a clip whose own
3854/// [`Speed`](crate::project::Speed) is not real time is re-timed by the
3855/// [`TimeStretch`] behind it in its [`Rate`] chain, which compresses or
3856/// stretches the timeline while keeping every period of the signal its own
3857/// length -- this hands it a pitch-true stream at the timeline's rate and
3858/// that is the whole of the hand-off.
3859///
3860/// `owed` is what the timeline gives the segment, in frames per channel:
3861/// resampling resolves to whole samples and a clip's own window resolves to
3862/// whole *source* frames, so the two miss each other by a sample or two per
3863/// clip. Truncating and padding to what is owed keeps that from accumulating
3864/// into audible drift over a timeline of rate-mismatched cuts -- the picture's
3865/// clip boundaries are exact by construction, and this makes the sound's
3866/// exact too.
3867struct Resample {
3868 /// Source frames per output frame: the ratio of the two sample rates.
3869 step: f64,
3870 /// Where the next output frame reads, relative to the current buffer's
3871 /// first frame. Negative means it reads across the seam, into `tail`.
3872 pos: f64,
3873 /// The last frame of the buffer before this one, one sample per channel.
3874 tail: Vec<f32>,
3875 /// Output frames per channel still to be emitted for this segment, or
3876 /// [`Resample::UNBOUNDED`] for a window with no end of its own -- what
3877 /// [`AudioSession::open_at`] asks for, where the source running out is the
3878 /// end and there is no shortfall to pad.
3879 owed: u64,
3880}
3881
3882impl Resample {
3883 /// "As many as the source has": a segment ending at `f64::INFINITY` owes the
3884 /// timeline nothing it did not decode.
3885 const UNBOUNDED: u64 = u64::MAX;
3886
3887 fn new(step: f64, owed: u64) -> Self {
3888 Self {
3889 step,
3890 pos: 0.,
3891 tail: Vec::new(),
3892 owed,
3893 }
3894 }
3895
3896 /// Rewrites `buf` in place as the frames this rate reads out of it. Never
3897 /// more than is owed, so the segment cannot overrun the room the timeline
3898 /// gave it.
3899 fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
3900 let frames = buf.len() / channels;
3901 if frames == 0 || channels == 0 {
3902 return;
3903 }
3904 let mut out: Vec<f32> = Vec::with_capacity(buf.len());
3905 while self.owed > (out.len() / channels) as u64 {
3906 let left = self.pos.floor();
3907 let right = left as i64 + 1;
3908 if right > frames as i64 - 1 {
3909 break; // the frame it would interpolate towards is not here yet
3910 }
3911 let frac = (self.pos - left) as f32;
3912 let (left, right) = (left as i64, right as usize);
3913 for c in 0..channels {
3914 // Before the buffer means the previous one's last frame; at the
3915 // very first buffer of a segment `pos` is 0, so this cannot be
3916 // asked for an empty tail.
3917 let a = match left < 0 {
3918 true => self.tail.get(c).copied().unwrap_or(0.),
3919 false => buf[left as usize * channels + c],
3920 };
3921 let b = buf[right * channels + c];
3922 out.push(a + (b - a) * frac);
3923 }
3924 self.pos += self.step;
3925 }
3926 self.tail.clear();
3927 self.tail.extend_from_slice(&buf[(frames - 1) * channels..]);
3928 self.pos -= frames as f64;
3929 if self.owed != Self::UNBOUNDED {
3930 self.owed -= (out.len() / channels) as u64;
3931 }
3932 *buf = out;
3933 }
3934
3935 /// The silence the segment still owes when its source ran out before the
3936 /// timeline did -- a rounding frame or two, or a clip whose file is shorter
3937 /// than the edit says. `false` means the consumer went away.
3938 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
3939 if self.owed == Self::UNBOUNDED {
3940 return true; // nothing was promised, so nothing is short
3941 }
3942 while self.owed > 0 {
3943 let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET));
3944 let chunk = AudioChunk {
3945 start_sample: *timeline,
3946 samples: vec![0.0; frames as usize * channels],
3947 };
3948 if tx.send(chunk).is_err() {
3949 return false;
3950 }
3951 *timeline += frames;
3952 self.owed -= frames;
3953 }
3954 true
3955 }
3956}
3957
3958/// One speeded-or-converted segment's whole rate chain: the resample that
3959/// turns the source's own rate into the timeline's, and -- only for a clip
3960/// whose [`Speed`](crate::project::Speed) is not real time -- the stretch
3961/// that changes its *time* without touching its pitch, after the resample
3962/// and before the equalizer sees a sample (the filter's bands are set in the
3963/// frequency a listener hears, and after a stretch that is still the
3964/// frequency the file was written at).
3965///
3966/// Which half owns the segment's promise depends on which halves there are:
3967/// a rate conversion alone is paced by the resample, as it always was, and a
3968/// speeded clip's resample runs unbounded (the ratio is all it is asked for)
3969/// while the stretch lands the timeline's frames exactly.
3970struct Rate {
3971 resample: Resample,
3972 stretch: Option<TimeStretch>,
3973}
3974
3975impl Rate {
3976 fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
3977 self.resample.process(buf, channels);
3978 if let Some(stretch) = self.stretch.as_mut() {
3979 stretch.process(buf, channels);
3980 }
3981 }
3982
3983 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
3984 match self.stretch.as_mut() {
3985 Some(stretch) => stretch.flush(channels, timeline, tx),
3986 None => self.resample.flush(channels, timeline, tx),
3987 }
3988 }
3989}
3990
3991struct Worker {
3992 /// Indexed by [`Segment::source`]; only the sources some segment names are
3993 /// `Some`, the rest were never opened.
3994 tracks: Vec<Option<Track>>,
3995 channels: usize,
3996 segments: Vec<Segment>,
3997 /// One per entry of `segments`, in the same order: the filter that segment's
3998 /// samples pass through on the way out, or `None` for one that plays flat.
3999 /// Beside the segments rather than inside them so the emit path can hold the
4000 /// window rules and the filter memory at once without splitting a borrow.
4001 eqs: Vec<Option<EqState>>,
4002 /// One per entry of `segments` again: that segment's rate chain, or
4003 /// `None` for one at real time on the timeline's own rate -- which is
4004 /// every segment of a project nobody has speeded or rate-mismatched, and
4005 /// the path that emits the decoder's own samples untouched.
4006 speeds: Vec<Option<Rate>>,
4007 /// One per entry of `segments` again: that segment's gain envelope, or
4008 /// `None` for one that plays flat -- [`emit`]'s last effect, run after
4009 /// the rate and the equalizer.
4010 fades: Vec<Option<crate::project::Fade>>,
4011 /// One per entry of `segments` again: the blocks a segment played backwards is
4012 /// decoded in ([`reverse_blocks`]), or `None` for one that plays forwards.
4013 reversed: Vec<Option<Vec<Segment>>>,
4014 /// `start_sample` of the first chunk.
4015 timeline: u64,
4016 tx: SyncSender<AudioChunk>,
4017}
4018
4019/// Sums one worker per lane into one stream (see
4020/// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline
4021/// position and synthesises its own gaps, so the lanes are sample-aligned by
4022/// construction and a mix is an add: no resampling, no positioning, no drift to
4023/// correct. What is emitted at each turn is the shortest block every still-live
4024/// lane can supply, which keeps a slow lane from being outrun and never buffers
4025/// more than the chunks already in flight.
4026///
4027/// A lane whose channel has closed has ended and simply stops being added --
4028/// that is what "shorter lane" means here. The mix ends when all of them have.
4029/// The accumulator is reused across turns; the one allocation per chunk is the
4030/// buffer the channel takes ownership of, and none of this is the RT path (the
4031/// device callback reads the ring the feeder has already filled).
4032/// The gains, ducks and limiter a mix starts from, carried as one value.
4033struct MixState {
4034 gains: Vec<f32>,
4035 ducks: Vec<Vec<Duck>>,
4036 limiter: Option<LimiterState>,
4037}
4038
4039fn mix(
4040 rxs: &[Receiver<AudioChunk>],
4041 channels: usize,
4042 state: MixState,
4043 rate: u32,
4044 controls: Option<&MixControls>,
4045 tx: &SyncSender<AudioChunk>,
4046) {
4047 let MixState { mut gains, mut ducks, mut limiter } = state;
4048 // The version of the mix these gains and this limiter came from; see the
4049 // reload at the head of the loop.
4050 let mut seen = 0;
4051 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
4052 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
4053 // Numbering follows lane 0, whose first chunk says where it starts.
4054 let mut base = 0;
4055 let mut emitted = 0;
4056 let mut out: Vec<f32> = Vec::new();
4057 // Per lane: the block after its gain and its duck, whether the lane had
4058 // samples in this block, and the key a duck reads. Kept between blocks so
4059 // the steady path allocates nothing beyond the chunk it sends.
4060 let mut scaled: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
4061 let mut filled: Vec<bool> = rxs.iter().map(|_| false).collect();
4062 // Per lane, per duck: the key that duck reads this block.
4063 let mut keys: Vec<Vec<Vec<f32>>> = rxs.iter().map(|_| Vec::new()).collect();
4064 // Per lane, one detector per duck, each with the key it reads: a lane ducked
4065 // under several keys is reduced by each of them in turn.
4066 let mut duckers: Vec<Vec<(usize, Ducker)>> = ducks
4067 .iter()
4068 .map(|lane| {
4069 lane.iter()
4070 .map(|d| (d.under, Ducker::new(d, rate)))
4071 .collect()
4072 })
4073 .collect();
4074 loop {
4075 // A mix moved while the stream plays, picked up between two blocks:
4076 // the levels change at a block boundary and nothing else changes at
4077 // all -- no flush, no re-open, no hole. The limiter is *retuned* rather
4078 // than rebuilt, so its delay line keeps running and the sample count
4079 // the master clock is made of does not move ([`LimiterState::retune`]).
4080 if let Some((next, next_ducks, params)) = controls.and_then(|c| c.changed(&mut seen)) {
4081 gains = next;
4082 gains.resize(rxs.len(), 1.0);
4083 ducks = next_ducks;
4084 ducks.resize(rxs.len(), Vec::new());
4085 // A duck that keeps its lane and its key keeps its detector and its
4086 // reduction; a new one starts at rest; one that was taken away is gone.
4087 for (slot, lane_ducks) in duckers.iter_mut().zip(&ducks) {
4088 let mut old = std::mem::take(slot);
4089 *slot = lane_ducks
4090 .iter()
4091 .map(|duck| match old.iter().position(|(under, _)| *under == duck.under) {
4092 Some(at) => {
4093 let (_, mut ducker) = old.swap_remove(at);
4094 ducker.retune(duck, rate);
4095 (duck.under, ducker)
4096 }
4097 None => (duck.under, Ducker::new(duck, rate)),
4098 })
4099 .collect();
4100 }
4101 match limiter.as_mut() {
4102 Some(state) => state.retune(&params),
4103 // First time it has ever been switched in on this stream: the
4104 // one that swallows nothing, for the count's sake.
4105 None if params.is_active() => {
4106 limiter = Some(LimiterState::engaged(&params, rate, channels));
4107 }
4108 None => {}
4109 }
4110 }
4111 for (i, rx) in rxs.iter().enumerate() {
4112 while live[i] && pending[i].is_empty() {
4113 match rx.recv() {
4114 Ok(chunk) => {
4115 if i == 0 && emitted == 0 {
4116 base = chunk.start_sample;
4117 }
4118 pending[i] = chunk.samples;
4119 }
4120 Err(_) => live[i] = false,
4121 }
4122 }
4123 }
4124 // The block every lane still playing can cover; `None` once they are all
4125 // done, which is the only way out of this loop besides a gone consumer.
4126 let Some(frames) = pending
4127 .iter()
4128 .filter(|p| !p.is_empty())
4129 .map(|p| p.len() / channels)
4130 .min()
4131 .filter(|&f| f > 0)
4132 else {
4133 // The mix has run out: the limiter still holds the stream's last frames, which go
4134 // out limited rather than being dropped (the export pads a shortfall with silence,
4135 // and that cut reads as an overshoot).
4136 if let Some(limiter) = limiter.as_mut() {
4137 let tail = limiter.drain();
4138 if !tail.is_empty() {
4139 let samples = tail.iter().map(|s| s.clamp(-1.0, 1.0)).collect();
4140 let _ = tx.send(AudioChunk { start_sample: base + emitted, samples });
4141 }
4142 }
4143 return;
4144 };
4145 let block = frames * channels;
4146 // Each lane's own volume, applied on its way into the sum: this is the
4147 // one place every lane's samples pass through, so a lane that is turned
4148 // down is turned down in an export exactly as it is in the room. Unity
4149 // is a multiply by 1.0, which f32 leaves alone.
4150 for (i, lane) in pending.iter_mut().enumerate() {
4151 filled[i] = !lane.is_empty();
4152 if !filled[i] {
4153 continue;
4154 }
4155 let gain = gains.get(i).copied().unwrap_or(1.0);
4156 let dst = &mut scaled[i];
4157 dst.clear();
4158 dst.extend(lane.drain(..block).map(|sample| sample * gain));
4159 }
4160 // Auto-ducking. A ducked lane is reduced by each of its keys' signals as
4161 // they stood after gain and before any duck, so no duck keys off another
4162 // duck's output: every key is read first, then the ducks are applied in
4163 // turn. A key that had no samples this block is silence, and lets its
4164 // duck go. A duck naming its own lane, or none, does nothing.
4165 for i in 0..rxs.len() {
4166 keys[i].resize_with(duckers[i].len(), Vec::new);
4167 for (j, (under, _)) in duckers[i].iter().enumerate() {
4168 let under = *under;
4169 if under == i || under >= rxs.len() {
4170 continue;
4171 }
4172 let key = &mut keys[i][j];
4173 key.clear();
4174 if filled[under] {
4175 key.extend_from_slice(&scaled[under]);
4176 } else {
4177 key.resize(block, 0.0);
4178 }
4179 }
4180 }
4181 for i in 0..rxs.len() {
4182 if !filled[i] {
4183 continue;
4184 }
4185 for (j, (under, ducker)) in duckers[i].iter_mut().enumerate() {
4186 if *under == i || *under >= rxs.len() {
4187 continue;
4188 }
4189 ducker.process(&keys[i][j], &mut scaled[i], channels);
4190 }
4191 }
4192 out.clear();
4193 out.resize(block, 0.0);
4194 for (i, lane) in scaled.iter().enumerate() {
4195 if !filled[i] {
4196 continue;
4197 }
4198 let mut peak = 0.0f32;
4199 for (sum, &level) in out.iter_mut().zip(lane) {
4200 peak = peak.max(level.abs());
4201 *sum += level;
4202 }
4203 // Read by the level meters ([`MixControls::take_lane_peaks`]); the
4204 // sum above is the same arithmetic it always was.
4205 if let Some(controls) = controls {
4206 controls.note_lane_peak(i, peak);
4207 }
4208 }
4209 // ...and the master limiter over the sum, before the clamp: what the
4210 // clamp used to catch by squaring it off is held under the ceiling
4211 // here instead ([`crate::limiter`]). Off, this is not even a branch
4212 // per sample.
4213 if let Some(limiter) = limiter.as_mut() {
4214 limiter.process(&mut out);
4215 }
4216 let frames = out.len() / channels;
4217 if frames == 0 {
4218 continue; // the limiter's delay line is still filling
4219 }
4220 let chunk = AudioChunk {
4221 start_sample: base + emitted,
4222 // Clamped, not wrapped: two lanes at full scale are what a mix has
4223 // to survive, and the device takes `[-1, 1]`.
4224 samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(),
4225 };
4226 if tx.send(chunk).is_err() {
4227 return; // caller moved on
4228 }
4229 emitted += frames as u64;
4230 }
4231}
4232
4233fn run(mut w: Worker) {
4234 let channels = w.channels;
4235 // Chunk numbering is continuous across every join, source ones included.
4236 let mut timeline = w.timeline;
4237 let segments = std::mem::take(&mut w.segments);
4238 let mut eqs = std::mem::take(&mut w.eqs);
4239 // A short list is "flat from here on" (`open_multi_streams_eq`), which this
4240 // pads out so the zip below still walks every segment.
4241 eqs.resize_with(segments.len(), || None);
4242 let mut speeds = std::mem::take(&mut w.speeds);
4243 // ...and a short rate list is "real time from here on", for the same reason.
4244 speeds.resize_with(segments.len(), || None);
4245 let mut fades = std::mem::take(&mut w.fades);
4246 // ...and a short fade list is "flat from here on", the same rule again.
4247 fades.resize_with(segments.len(), || None);
4248 let mut reversed = std::mem::take(&mut w.reversed);
4249 // ...and a short reversal list is "forwards from here on".
4250 reversed.resize_with(segments.len(), || None);
4251
4252 for ((((seg, eq), speed), fade), backwards) in segments
4253 .iter()
4254 .zip(eqs.iter_mut())
4255 .zip(speeds.iter_mut())
4256 .zip(fades.iter_mut())
4257 .zip(reversed.iter())
4258 {
4259 let Some(source) = seg.source else {
4260 // A gap: hand the device real silence rather than nothing at all,
4261 // in the same packet-sized chunks decoding produces, so `fed` and
4262 // the master clock keep counting straight through the hole.
4263 let mut left = seg.media_end;
4264 while left > 0 {
4265 let frames = left.min(u64::from(SAMPLES_PER_PACKET));
4266 let chunk = AudioChunk {
4267 start_sample: timeline,
4268 samples: vec![0.0; frames as usize * channels],
4269 };
4270 if w.tx.send(chunk).is_err() {
4271 return; // caller moved on
4272 }
4273 timeline += frames;
4274 left -= frames;
4275 }
4276 continue;
4277 };
4278 let Some(track) = w.tracks[source].as_mut() else {
4279 continue; // opener fills every named source; nothing to decode
4280 };
4281 let chain = Chain {
4282 eq: eq.as_mut(),
4283 speed: &mut *speed,
4284 fade: &mut *fade,
4285 channels,
4286 timeline: &mut timeline,
4287 tx: &w.tx,
4288 };
4289 let more = match backwards {
4290 Some(blocks) => run_backwards(track, blocks, chain),
4291 None => run_segment(track, seg, chain),
4292 };
4293 if !(more && settle(speed, channels, &mut timeline, &w.tx)) {
4294 return; // consumer went away
4295 }
4296 }
4297}
4298
4299/// One segment of one source, decoded forwards through `chain`. `false` means the
4300/// consumer went away, or the decoder could not be built and the rest of the mix
4301/// is not worth decoding.
4302fn run_segment(track: &mut Track, seg: &Segment, chain: Chain<'_>) -> bool {
4303 let Chain {
4304 mut eq,
4305 speed,
4306 fade,
4307 channels,
4308 timeline,
4309 tx,
4310 } = chain;
4311 let track = match track {
4312 Track::Sym(track) => return run_sym(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4313 Track::Ts(track) => return run_ts(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4314 Track::Truehd(track) => {
4315 return run_mkv_truehd(track, seg, Chain { eq, speed, fade, channels, timeline, tx });
4316 }
4317 Track::Ext(track) => return run_ext(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4318 Track::Mkv(track) => return run_mkv_ac3(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4319 Track::Ac3(track) => return run_ac3(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4320 Track::Aac(track) => track,
4321 };
4322 let mut interleaved = Vec::new();
4323 // An SBR track starts on a packet that carries its own header, which
4324 // may be ahead of the segment's pre-roll; its position is that packet's.
4325 let (start_id, mut pos) = if track.sbr {
4326 let id = sbr_start_packet(track, seg.start_id);
4327 let ts = packet_start_ts(&track.stts, id);
4328 (id, scale(ts, track.sample_rate, track.timescale).unwrap_or(0))
4329 } else {
4330 (seg.start_id, seg.start_pos)
4331 };
4332 let mut decoder = match aac_decoder(&track.params, track.source_channels()) {
4333 Ok(decoder) => decoder,
4334 Err(e) => {
4335 eprintln!("audio decoder init failed: {e}");
4336 return false;
4337 }
4338 };
4339
4340 for id in start_id..=track.sample_count {
4341 if pos >= seg.media_end {
4342 break; // segment done, on to the next one
4343 }
4344 let sample = match mp4track::sample(&mut track.reader, track.stream, id) {
4345 Ok(Some(sample)) => sample,
4346 Ok(None) => break,
4347 Err(e) => {
4348 eprintln!("audio demux error at sample {id}: {e}");
4349 break;
4350 }
4351 };
4352 let packet = Packet::new(
4353 track.track_id,
4354 units::Timestamp::new(sample.dts.unwrap_or(0)),
4355 units::Duration::new(u64::from(sample.duration.unwrap_or(0).max(0) as u32)),
4356 &sample.data[..],
4357 );
4358 if let Err(e) = decoder.decode(&packet, &mut interleaved) {
4359 eprintln!("audio decode error at sample {id}: {e}");
4360 break;
4361 }
4362 // decoder.decode already folded to track.channels(); widen the mono
4363 // case up to the timeline's own width before dividing by it below.
4364 widen(&mut interleaved, usize::from(track.channels()), channels);
4365 let next = pos + (interleaved.len() / channels) as u64;
4366 if !emit(
4367 &mut interleaved,
4368 seg,
4369 Chain {
4370 eq: eq.as_deref_mut(),
4371 speed: &mut *speed,
4372 fade: &mut *fade,
4373 channels,
4374 timeline: &mut *timeline,
4375 tx,
4376 },
4377 pos,
4378 next,
4379 ) {
4380 return false; // consumer went away
4381 }
4382 pos = next;
4383 }
4384 true
4385}
4386
4387/// How long one block of a reversed segment is, in seconds of the source: the most
4388/// that is ever held decoded at once, whatever the clip's length -- a stereo pair at
4389/// 48 kHz is 750 KB of it.
4390const REVERSE_BLOCK_SECS: u64 = 2;
4391
4392/// The blocks a reversed `seg` (the window `[media_target, media_end)` of `track`,
4393/// opened for the seconds from `start_secs`) is decoded in, in the order they are
4394/// *played*: the last stretch of the window first. Each is a segment of its own,
4395/// resolved against the packet table like any other, and trimmed to the exact
4396/// samples it owns so the blocks tile the window with nothing lost between.
4397fn reverse_blocks(track: &Track, source: usize, start_secs: f64, seg: &Segment) -> Vec<Segment> {
4398 let rate = u64::from(track.sample_rate().max(1));
4399 let step = REVERSE_BLOCK_SECS * rate;
4400 let mut blocks = Vec::new();
4401 let mut end = seg.media_end;
4402 while end > seg.media_target {
4403 let from = end.saturating_sub(step).max(seg.media_target);
4404 let (a, b) = (from - seg.media_target, end - seg.media_target);
4405 let mut block = track.segment(
4406 source,
4407 start_secs + a as f64 / rate as f64,
4408 start_secs + b as f64 / rate as f64,
4409 );
4410 // The seconds only find the packets; the samples are exact.
4411 block.media_target = from;
4412 block.media_end = end;
4413 blocks.push(block);
4414 end = from;
4415 }
4416 blocks
4417}
4418
4419/// A reversed segment: each block decoded forwards into memory, turned end for end
4420/// and handed to the rate, the equalizer and the fade as if it were the decoder's
4421/// own -- so a reversed clip is filtered, speeded and faded exactly as a forward one,
4422/// from the sound's last sample down. `false` as for [`run_segment`].
4423fn run_backwards(track: &mut Track, blocks: &[Segment], chain: Chain<'_>) -> bool {
4424 let Chain {
4425 eq,
4426 speed,
4427 fade,
4428 channels,
4429 timeline,
4430 tx,
4431 } = chain;
4432 // A block's chunks are collected here on the way out of the decoder: a block is
4433 // seconds of packets, never more than this many.
4434 let (hold, held) = sync_channel(1 << 14);
4435 let mut eq = eq;
4436 for block in blocks {
4437 let mut at = 0u64;
4438 let mut none = None;
4439 let mut flat = None;
4440 let ok = run_segment(
4441 track,
4442 block,
4443 Chain {
4444 eq: None,
4445 speed: &mut none,
4446 fade: &mut flat,
4447 channels,
4448 timeline: &mut at,
4449 tx: &hold,
4450 },
4451 );
4452 let mut samples: Vec<f32> = Vec::new();
4453 while let Ok(chunk) = held.try_recv() {
4454 samples.extend_from_slice(&chunk.samples);
4455 }
4456 // Frame order reversed, the channels of a frame left as they are.
4457 let frames = samples.len() / channels.max(1);
4458 for f in 0..frames / 2 {
4459 let (a, b) = (f * channels, (frames - 1 - f) * channels);
4460 for c in 0..channels {
4461 samples.swap(a + c, b + c);
4462 }
4463 }
4464 if !samples.is_empty()
4465 && !deliver(
4466 &mut samples,
4467 Chain {
4468 eq: eq.as_deref_mut(),
4469 speed: &mut *speed,
4470 fade: &mut *fade,
4471 channels,
4472 timeline: &mut *timeline,
4473 tx,
4474 },
4475 )
4476 {
4477 return false;
4478 }
4479 if !ok {
4480 return false;
4481 }
4482 }
4483 true
4484}
4485
4486/// Pays out whatever silence a speeded segment still owes the timeline (see
4487/// [`Resample::flush`]). Nothing at all at real time, where a segment owes the
4488/// timeline only the samples it decoded.
4489fn settle(
4490 speed: &mut Option<Rate>,
4491 channels: usize,
4492 timeline: &mut u64,
4493 tx: &SyncSender<AudioChunk>,
4494) -> bool {
4495 match speed {
4496 Some(speed) => speed.flush(channels, timeline, tx),
4497 None => true,
4498 }
4499}
4500
4501/// Trims one decoded buffer to the segment window and sends what survives.
4502/// `pos` is the media position of its first frame and `next` of the one after
4503/// it; both readers hand the same thing here, which is why the window rules
4504/// live in one place. `false` means the consumer went away.
4505///
4506/// Everything before the target is encoder priming and/or decoder pre-roll, not
4507/// audio the caller asked for: it is dropped, splitting the buffer that
4508/// straddles the target. The tail past the segment end goes too — on a short
4509/// segment that is this same buffer, trimmed at both ends.
4510///
4511/// The segment's equalizer runs here, on the trimmed buffer and nowhere else:
4512/// this is the one place both readers hand their samples over, so playback and
4513/// an audio export get the same filtered stream by construction rather than by
4514/// two call sites agreeing. Trimmed first, so the pre-roll a listener never
4515/// hears cannot ring the filter either. Nothing is allocated -- the device
4516/// callback is two hand-offs downstream of here in any case.
4517/// What one segment writes through: its equalizer, rate and fade, each carried
4518/// from one decoded buffer to the next, and the timeline and channel count the
4519/// samples land on. Passed whole so `emit` and the per-codec loops share one
4520/// shape instead of threading the same ten values through every call.
4521struct Chain<'a> {
4522 eq: Option<&'a mut EqState>,
4523 speed: &'a mut Option<Rate>,
4524 fade: &'a mut Option<crate::project::Fade>,
4525 channels: usize,
4526 timeline: &'a mut u64,
4527 tx: &'a SyncSender<AudioChunk>,
4528}
4529
4530fn emit(interleaved: &mut Vec<f32>, seg: &Segment, chain: Chain<'_>, pos: u64, next: u64) -> bool {
4531 let Chain {
4532 eq,
4533 speed,
4534 fade,
4535 channels,
4536 timeline,
4537 tx,
4538 } = chain;
4539 if next <= seg.media_target {
4540 return true;
4541 }
4542 let mut pos = pos;
4543 if pos < seg.media_target {
4544 interleaved.drain(..(seg.media_target - pos) as usize * channels);
4545 pos = seg.media_target;
4546 }
4547 if next > seg.media_end {
4548 interleaved.truncate((seg.media_end - pos) as usize * channels);
4549 }
4550 if interleaved.is_empty() {
4551 return true; // nothing left of it; the loop head ends the segment
4552 }
4553 deliver(
4554 interleaved,
4555 Chain {
4556 eq,
4557 speed,
4558 fade,
4559 channels,
4560 timeline,
4561 tx,
4562 },
4563 )
4564}
4565
4566/// Sends the samples of one decoded, window-trimmed buffer on their way: through the
4567/// rate, the equalizer and the fade, in that order, and out as the next chunk.
4568/// `false` means the consumer went away.
4569fn deliver(interleaved: &mut Vec<f32>, chain: Chain<'_>) -> bool {
4570 let Chain {
4571 eq,
4572 speed,
4573 fade,
4574 channels,
4575 timeline,
4576 tx,
4577 } = chain;
4578 // The rate first, the filter second: what the equalizer's bands are set in
4579 // is the frequency a listener hears, and after a resample that is not the
4580 // frequency the file was written at. A segment at real time has no
4581 // resampler at all and reaches the filter with the decoder's own samples.
4582 if let Some(speed) = speed {
4583 speed.process(interleaved, channels);
4584 if interleaved.is_empty() {
4585 return true; // this buffer resolved to no output frame of its own
4586 }
4587 }
4588 if let Some(eq) = eq {
4589 eq.process(interleaved);
4590 }
4591 // The fade last, on the same output-rate samples the mix will hear: its
4592 // frame counts are timeline frames ([`crate::project::Clip::fade_in`]),
4593 // which is what a resample has already turned these into. The state
4594 // walks forward with the segment across as many buffers as decoding
4595 // takes, exactly as the equalizer's does.
4596 if let Some(fade) = fade {
4597 fade.apply(interleaved, channels);
4598 fade.elapsed = fade
4599 .elapsed
4600 .saturating_add((interleaved.len() / channels) as u32);
4601 }
4602 let chunk = AudioChunk {
4603 start_sample: *timeline,
4604 samples: std::mem::take(interleaved),
4605 };
4606 *timeline += (chunk.samples.len() / channels) as u64;
4607 tx.send(chunk).is_ok()
4608}
4609
4610/// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids
4611/// come out of the same mp4 tables, the window rules are [`emit`]'s as always,
4612/// and what reaches the mixer is already the stereo downmix. `false` means the
4613/// consumer went away.
4614fn run_ac3(track: &mut Ac3Track, seg: &Segment, chain: Chain<'_>) -> bool {
4615 let Chain {
4616 mut eq,
4617 speed,
4618 fade,
4619 channels,
4620 timeline,
4621 tx,
4622 } = chain;
4623 let mut decoder = match ac3_decoder(track.requested) {
4624 Ok(decoder) => decoder,
4625 Err(e) => {
4626 eprintln!("audio decoder init failed: {e}");
4627 return true;
4628 }
4629 };
4630 let mut pos = seg.start_pos;
4631 for id in seg.start_id..=track.sample_count {
4632 if pos >= seg.media_end {
4633 return true; // segment done, on to the next one
4634 }
4635 let sample = match mp4track::sample(&mut track.reader, track.stream, id) {
4636 Ok(Some(sample)) => sample,
4637 Ok(None) => return true,
4638 Err(e) => {
4639 eprintln!("audio demux error at sample {id}: {e}");
4640 return true;
4641 }
4642 };
4643 let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.data) {
4644 Ok(Some(decoded)) => decoded,
4645 Ok(None) => continue, // the decoder wants another frame first
4646 Err(e) => {
4647 eprintln!("audio decode error at sample {id}: {e}");
4648 return true;
4649 }
4650 };
4651 // §7.8.2 has already folded anything wider than a pair; only a mono
4652 // track arrives here in its own width, and [`widen`]'s is the last word.
4653 widen(&mut interleaved, usize::from(track.channels), channels);
4654 let next = pos + samples;
4655 if !emit(
4656 &mut interleaved,
4657 seg,
4658 Chain {
4659 eq: eq.as_deref_mut(),
4660 speed: &mut *speed,
4661 fade: &mut *fade,
4662 channels,
4663 timeline: &mut *timeline,
4664 tx,
4665 },
4666 pos,
4667 next,
4668 ) {
4669 return false;
4670 }
4671 pos = next;
4672 }
4673 true
4674}
4675
4676/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks
4677/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the
4678/// stereo downmix are the same ones; only where a packet comes from differs.
4679/// `false` means the consumer went away.
4680fn run_mkv_ac3(track: &mut MkvAc3Track, seg: &Segment, chain: Chain<'_>) -> bool {
4681 let Chain {
4682 mut eq,
4683 speed,
4684 fade,
4685 channels,
4686 timeline,
4687 tx,
4688 } = chain;
4689 let mut decoder = match ac3_decoder(track.requested) {
4690 Ok(decoder) => decoder,
4691 Err(e) => {
4692 eprintln!("audio decoder init failed: {e}");
4693 return true;
4694 }
4695 };
4696 let mut pos = seg.start_pos;
4697 for id in seg.start_id as usize.. {
4698 if pos >= seg.media_end {
4699 return true; // segment done, on to the next one
4700 }
4701 let block = match track.mkv.frame(id) {
4702 Ok(Some(bytes)) => bytes,
4703 Ok(None) => return true, // end of the track
4704 Err(e) => {
4705 eprintln!("audio demux error at block {id}: {e}");
4706 return true;
4707 }
4708 };
4709 let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) {
4710 Ok(Some(decoded)) => decoded,
4711 Ok(None) => continue, // the decoder wants another frame first
4712 Err(e) => {
4713 eprintln!("audio decode error at block {id}: {e}");
4714 return true;
4715 }
4716 };
4717 // ...and widened here, as on the mp4 side.
4718 widen(&mut interleaved, usize::from(track.channels), channels);
4719 let next = pos + samples;
4720 if !emit(
4721 &mut interleaved,
4722 seg,
4723 Chain {
4724 eq: eq.as_deref_mut(),
4725 speed: &mut *speed,
4726 fade: &mut *fade,
4727 channels,
4728 timeline: &mut *timeline,
4729 tx,
4730 },
4731 pos,
4732 next,
4733 ) {
4734 return false;
4735 }
4736 pos = next;
4737 }
4738 true
4739}
4740
4741/// The Matroska TrueHD / MLP track: every block is one access unit, decoded by
4742/// `ec-truehd`, which is bit-exact against ffmpeg. The decoder hands back the
4743/// highest presentation the unit carries (7.1 where the stream has it, else 5.1,
4744/// else stereo), and [`downmix`] folds that to the pair the timeline carries, as
4745/// it does for every multichannel source. An Atmos track's 4th substream is
4746/// refused by `ec-truehd` by name, and so is the open.
4747struct MkvTruehdTrack {
4748 mkv: crate::demux::MkvAudio,
4749 sample_rate: u32,
4750 /// Samples per channel in every access unit. Constant across a stream, so a
4751 /// block's first sample is `id * au_samples` exactly, with no rounding from
4752 /// Matroska's millisecond timestamps.
4753 au_samples: u64,
4754 /// What the decoder emits: 2, 6 or 8 channels, before [`downmix`].
4755 source_channels: usize,
4756 /// What reaches the timeline: the source's width, or a pair for anything wider.
4757 channels: u16,
4758 total_samples: Option<u64>,
4759}
4760
4761/// Blocks scanned for the first decodable access unit when a track is opened. A
4762/// decoder emits nothing until it has seen a restart header, which a stream
4763/// carries every few access units.
4764const TRUEHD_PROBE_BLOCKS: usize = 256;
4765
4766/// Blocks decoded before a seek target so the decoder has seen its restart
4767/// header by the time the window starts (about 0.8 s at 48 kHz).
4768const TRUEHD_PRE_ROLL: u32 = 40;
4769
4770impl MkvTruehdTrack {
4771 /// `Ok(None)` when the file's first audio track is not TrueHD or MLP.
4772 fn open(path: &Path) -> crate::Result<Option<Self>> {
4773 Self::from_blocks(crate::demux::MkvAudio::open(path)?)
4774 }
4775
4776 /// [`open`](Self::open) on one named track ([`crate::demux::MkvAudioTrack::number`]).
4777 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
4778 Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?)
4779 }
4780
4781 fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> {
4782 let Some(mut mkv) = mkv else {
4783 return Ok(None);
4784 };
4785 if !matches!(mkv.codec, "truehd" | "mlp") {
4786 return Ok(None);
4787 }
4788 // Rate, layout and access-unit length all come out of the stream's own
4789 // major sync, as the decoder reads them: the first frame it can emit says
4790 // them. A first block the decoder cannot yet decode is not an error.
4791 let mut decoder = ec_truehd::TrueHdDecoder::new();
4792 let mut first = None;
4793 for id in 0..mkv.blocks().min(TRUEHD_PROBE_BLOCKS) {
4794 let Some(bytes) = mkv.frame(id)? else {
4795 break;
4796 };
4797 match decoder.decode_access_unit(&bytes) {
4798 Ok(Some(frame)) => {
4799 first = Some(frame);
4800 break;
4801 }
4802 Ok(None) | Err(ec_core::Error::NeedMore) => {}
4803 Err(e) => return Err(format!("TrueHD: {e}").into()),
4804 }
4805 }
4806 let frame = first.ok_or(
4807 "the TrueHD track of this Matroska file has no decodable access unit in its first blocks",
4808 )?;
4809 if frame.rate == 0 || frame.samples == 0 {
4810 return Err("the TrueHD track of this Matroska file states no sample rate".into());
4811 }
4812 let source_channels = frame.layout.channel_count();
4813 let au_samples = frame.samples as u64;
4814 Ok(Some(Self {
4815 sample_rate: frame.rate,
4816 au_samples,
4817 source_channels,
4818 channels: source_channels.min(2) as u16,
4819 total_samples: Some(mkv.blocks() as u64 * au_samples),
4820 mkv,
4821 }))
4822 }
4823
4824 /// `secs` on this source's timeline into media samples. No priming: a
4825 /// Matroska file carries no edit list and TrueHD no encoder delay.
4826 fn media(&self, secs: f64) -> u64 {
4827 (secs.max(0.0) * f64::from(self.sample_rate)).round() as u64
4828 }
4829
4830 /// One `[start, end)` window, resolved to blocks and media samples. The
4831 /// decoder is started [`TRUEHD_PRE_ROLL`] blocks early; what it decodes before
4832 /// the target is dropped by [`emit`].
4833 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
4834 let media_target = self.media(start_secs);
4835 let start_id = self.mkv.block_at(start_secs, TRUEHD_PRE_ROLL as usize);
4836 Segment {
4837 source: Some(source),
4838 start_id: start_id as u32,
4839 start_pos: start_id as u64 * self.au_samples,
4840 media_target,
4841 media_end: self.media(end_secs).max(media_target),
4842 }
4843 }
4844}
4845
4846/// One segment of a Matroska TrueHD / MLP track: [`run_mkv_ac3`]'s shape, with
4847/// the access unit's position computed from its block index rather than summed,
4848/// so a decoded unit that is not emitted (the decoder still warming up) cannot
4849/// shift every sample after it.
4850fn run_mkv_truehd(track: &mut MkvTruehdTrack, seg: &Segment, chain: Chain<'_>) -> bool {
4851 let Chain {
4852 mut eq,
4853 speed,
4854 fade,
4855 channels,
4856 timeline,
4857 tx,
4858 } = chain;
4859 let mut decoder = ec_truehd::TrueHdDecoder::new();
4860 for id in seg.start_id as usize.. {
4861 let pos = id as u64 * track.au_samples;
4862 if pos >= seg.media_end {
4863 return true; // segment done, on to the next one
4864 }
4865 let block = match track.mkv.frame(id) {
4866 Ok(Some(bytes)) => bytes,
4867 Ok(None) => return true, // end of the track
4868 Err(e) => {
4869 eprintln!("audio demux error at block {id}: {e}");
4870 return true;
4871 }
4872 };
4873 let frame = match decoder.decode_access_unit(&block) {
4874 Ok(Some(frame)) => frame,
4875 // No output yet (no restart header seen): nothing to emit for this unit.
4876 Ok(None) | Err(ec_core::Error::NeedMore) => continue,
4877 Err(e) => {
4878 eprintln!("audio decode error at block {id}: {e}");
4879 return true;
4880 }
4881 };
4882 let mut interleaved = truehd_f32(&frame);
4883 downmix(&mut interleaved, track.source_channels);
4884 widen(&mut interleaved, usize::from(track.channels), channels);
4885 let next = pos + frame.samples as u64;
4886 if !emit(
4887 &mut interleaved,
4888 seg,
4889 Chain {
4890 eq: eq.as_deref_mut(),
4891 speed,
4892 fade,
4893 channels,
4894 timeline,
4895 tx,
4896 },
4897 pos,
4898 next,
4899 ) {
4900 return false;
4901 }
4902 }
4903 true
4904}
4905
4906/// One segment of a DTS / ADPCM / A-law / mu-law / AMR track read by `ec-probe`
4907/// ([`crate::extaudio`]): the reader is seeked a pre-roll ahead of the window, a
4908/// fresh decoder runs from there, and each packet lands at the media position its
4909/// timestamp states (summed from the last one when it states none). `false` means
4910/// the consumer went away.
4911fn run_ext(track: &mut crate::extaudio::ExtFileTrack, seg: &Segment, chain: Chain<'_>) -> bool {
4912 let Chain {
4913 mut eq,
4914 speed,
4915 fade,
4916 channels,
4917 timeline,
4918 tx,
4919 } = chain;
4920 let mut decoder = match track.decoder() {
4921 Ok(decoder) => decoder,
4922 Err(e) => {
4923 eprintln!("audio decoder init failed: {e}");
4924 return true;
4925 }
4926 };
4927 let rate = f64::from(track.sample_rate.max(1));
4928 if let Err(e) = track.seek(seg.media_target as f64 / rate) {
4929 eprintln!("audio seek error: {e}");
4930 return true;
4931 }
4932 let mut next_pos = 0u64;
4933 loop {
4934 let (stated, block) = match track.next_packet() {
4935 Ok(Some(p)) => p,
4936 Ok(None) => return true, // end of the track
4937 Err(e) => {
4938 eprintln!("audio demux error: {e}");
4939 return true;
4940 }
4941 };
4942 let pos = stated.unwrap_or(next_pos);
4943 if pos >= seg.media_end {
4944 return true; // segment done, on to the next one
4945 }
4946 let (mut interleaved, source_channels) = match decoder.decode(&block) {
4947 Ok(Some(decoded)) => decoded,
4948 Ok(None) => {
4949 next_pos = pos;
4950 continue;
4951 }
4952 Err(e) => {
4953 eprintln!("audio decode error: {e}");
4954 return true;
4955 }
4956 };
4957 let frames = (interleaved.len() / source_channels.max(1)) as u64;
4958 downmix(&mut interleaved, source_channels);
4959 widen(&mut interleaved, usize::from(track.channels()), channels);
4960 let next = pos + frames;
4961 next_pos = next;
4962 if !emit(
4963 &mut interleaved,
4964 seg,
4965 Chain {
4966 eq: eq.as_deref_mut(),
4967 speed,
4968 fade,
4969 channels,
4970 timeline,
4971 tx,
4972 },
4973 pos,
4974 next,
4975 ) {
4976 return false;
4977 }
4978 }
4979}
4980
4981/// The decoder's S32 output as f32 in `[-1, 1)`, interleaved. Its samples carry
4982/// 24 significant bits (left-justified in 32), so both the widening to f32 and
4983/// the division by 2^31 are exact.
4984pub(crate) fn truehd_f32(frame: &ec_core::frame::AudioFrame) -> Vec<f32> {
4985 frame
4986 .data
4987 .first()
4988 .into_iter()
4989 .flat_map(|plane| plane.as_chunks::<4>().0.iter())
4990 .map(|s| i32::from_ne_bytes(*s) as f32 / 2_147_483_648.0)
4991 .collect()
4992}
4993
4994/// One segment of a standalone audio file: seek the reader to just before the
4995/// window, then decode forward until the window is filled.
4996///
4997/// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the
4998/// target is thrown away by [`emit`], which is what gives a codec with decoder
4999/// state — mp3's bit reservoir above all — something to warm up on, exactly as
5000/// the AAC path's two-packet pre-roll does. A reader that cannot seek at all
5001/// simply decodes from wherever it is; the window rules still hold, it is only
5002/// slower. `false` means the consumer went away.
5003/// One segment of a transport stream's sound: the track's own demuxer is sought a
5004/// pre-roll ahead of the window, a fresh decoder runs from there, and each packet lands at
5005/// the media position its timestamp states (the sound that starts after the picture leaves
5006/// silence in front of it; sound before the picture is trimmed away). `false` means the
5007/// consumer went away.
5008fn run_ts(track: &mut crate::demux::ts::TsAudio, seg: &Segment, chain: Chain<'_>) -> bool {
5009 let Chain {
5010 mut eq,
5011 speed,
5012 fade,
5013 channels,
5014 timeline,
5015 tx,
5016 } = chain;
5017 let rate = i128::from(track.sample_rate);
5018 let mut decoder = match track.decoder() {
5019 Ok(decoder) => decoder,
5020 Err(e) => {
5021 eprintln!("audio decoder init failed: {e}");
5022 return true;
5023 }
5024 };
5025 let target_secs = seg.media_target as f64 / track.sample_rate as f64;
5026 if let Err(e) = track.seek((target_secs - track.pre_roll_secs()).max(0.0)) {
5027 eprintln!("audio demux seek failed: {e}");
5028 return true;
5029 }
5030 let mut at: Option<i128> = None;
5031 let mut first = true;
5032 loop {
5033 let (stamp, bytes) = match track.next_packet() {
5034 Ok(Some(packet)) => packet,
5035 Ok(None) => return true, // end of the file, and of the segment
5036 Err(e) => {
5037 eprintln!("audio demux error: {e}");
5038 return true;
5039 }
5040 };
5041 // The count of samples decoded since the last stamp is the position, until a stamp
5042 // disagrees with it by more than a fiftieth of a second (a dropped packet, a splice).
5043 let pos = match at {
5044 Some(running) if (running - stamp).abs() <= rate / 50 => running,
5045 _ => stamp,
5046 };
5047 if pos >= seg.media_end as i128 {
5048 return true;
5049 }
5050 let decoded = match decoder.decode(&bytes) {
5051 Ok(Some(decoded)) => decoded,
5052 Ok(None) => continue,
5053 Err(e) => {
5054 eprintln!("audio decode error at sample {pos}: {e}");
5055 return true;
5056 }
5057 };
5058 let mut interleaved = decoded.samples;
5059 let width = decoded.channels.max(1);
5060 at = Some(pos + i128::from(decoded.frames));
5061 downmix(&mut interleaved, width);
5062 widen(&mut interleaved, width.min(2), channels);
5063 let frames = (interleaved.len() / channels) as i128;
5064 // A packet that starts before the clip does: the frames in front of 0 are dropped.
5065 let (mut pos, mut frames) = (pos, frames);
5066 if pos < 0 {
5067 let cut = ((-pos).min(frames)) as usize;
5068 interleaved.drain(..cut * channels);
5069 pos += cut as i128;
5070 frames -= cut as i128;
5071 }
5072 if frames <= 0 {
5073 continue;
5074 }
5075 // The first sound of the run begins after the window does: the gap is silence,
5076 // so the sound keeps its offset from the picture.
5077 if first {
5078 first = false;
5079 let target = seg.media_target as i128;
5080 if pos > target {
5081 let gap = (pos.min(seg.media_end as i128) - target) as usize;
5082 let mut silence = vec![0.0f32; gap * channels];
5083 if !emit(
5084 &mut silence,
5085 seg,
5086 Chain {
5087 eq: eq.as_deref_mut(),
5088 speed: &mut *speed,
5089 fade: &mut *fade,
5090 channels,
5091 timeline: &mut *timeline,
5092 tx,
5093 },
5094 target as u64,
5095 pos.min(seg.media_end as i128) as u64,
5096 ) {
5097 return false;
5098 }
5099 }
5100 }
5101 if !emit(
5102 &mut interleaved,
5103 seg,
5104 Chain {
5105 eq: eq.as_deref_mut(),
5106 speed: &mut *speed,
5107 fade: &mut *fade,
5108 channels,
5109 timeline: &mut *timeline,
5110 tx,
5111 },
5112 pos as u64,
5113 (pos + frames) as u64,
5114 ) {
5115 return false;
5116 }
5117 }
5118}
5119
5120fn run_sym(track: &mut SymTrack, seg: &Segment, chain: Chain<'_>) -> bool {
5121 let Chain {
5122 mut eq,
5123 speed,
5124 fade,
5125 channels,
5126 timeline,
5127 tx,
5128 } = chain;
5129 let mut decoder = match track.decoder() {
5130 Ok(decoder) => decoder,
5131 Err(e) => {
5132 eprintln!("audio decoder init failed: {e}");
5133 return true;
5134 }
5135 };
5136 track.seek_to(seg.media_target);
5137 let mut interleaved = Vec::new();
5138 // Media position of the next frame to decode: the landing for the first
5139 // packet, and the decoder's own count from there on. A packet's timestamp
5140 // cannot carry it, because the frames of one laced block all share the
5141 // block's -- accumulating is what both mp4 readers here already do.
5142 let mut at: Option<u64> = None;
5143 // The withheld tail (see `SymTrack::tail_hold`) and the position of its first frame.
5144 let mut held: Vec<f32> = Vec::new();
5145 let mut held_pos = 0u64;
5146 loop {
5147 let packet = match track.next_packet() {
5148 Ok(Some(packet)) => packet,
5149 Ok(None) => return true, // end of the file, and of the segment
5150 Err(e) => {
5151 eprintln!("audio demux error: {e}");
5152 return true;
5153 }
5154 };
5155 if packet.track_id != track.track_id {
5156 continue; // another track of the same container
5157 }
5158 // A Matroska Vorbis packet's own start is exact ([`SymTrack::exact_start`]);
5159 // the running count and the stamp only answer where there is no index.
5160 let pos = track.exact_start(packet.pts).or(at).unwrap_or_else(|| match track.params.codec {
5161 // A Vorbis run from the top starts at the top. Matroska stamps its
5162 // blocks a few milliseconds past the samples they hold (ffmpeg
5163 // starts the same file at 0), so the first block's stamp is not the
5164 // start of the run.
5165 CODEC_ID_VORBIS if seg.media_target == 0 => 0,
5166 _ => track.samples_at(packet.pts),
5167 });
5168 if pos >= seg.media_end {
5169 return true; // segment done, on to the next one
5170 }
5171 if let Err(e) = decoder.decode(&packet, &mut interleaved) {
5172 eprintln!("audio decode error at sample {pos}: {e}");
5173 return true;
5174 }
5175 // decoder.decode already folded to track.channels ([`SymDecoder::decode`],
5176 // [`downmix`]); widen the mono case up to the timeline's own width
5177 // before anything below divides by it.
5178 widen(&mut interleaved, usize::from(track.channels), channels);
5179 if interleaved.is_empty() {
5180 // A packet that answers nothing (a fresh decoder's first block
5181 // only primes the overlap) is not a position: the packet that
5182 // does answer carries its own timestamp, and counting on from this
5183 // one's is what put a seeked Vorbis file 1025 samples off its timeline.
5184 at = None;
5185 continue;
5186 }
5187 let next = pos + (interleaved.len() / channels) as u64;
5188 at = Some(next);
5189 // The last `tail_hold` frames of the track are not played: they wait
5190 // here, and whatever is still held when the file ends is dropped.
5191 let (pos, next) = if track.tail_hold > 0 {
5192 if held.is_empty() {
5193 held_pos = pos;
5194 }
5195 held.append(&mut interleaved);
5196 let keep = usize::try_from(track.tail_hold)
5197 .unwrap_or(usize::MAX)
5198 .saturating_mul(channels);
5199 let release = held.len().saturating_sub(keep);
5200 interleaved.extend(held.drain(..release));
5201 let released = (interleaved.len() / channels) as u64;
5202 let from = held_pos;
5203 held_pos += released;
5204 (from, from + released)
5205 } else {
5206 (pos, next)
5207 };
5208 // Reborrowed per packet: the filter memory has to carry across the
5209 // packet boundary, so this is one `EqState` for the whole segment.
5210 if !emit(
5211 &mut interleaved,
5212 seg,
5213 Chain {
5214 eq: eq.as_deref_mut(),
5215 speed: &mut *speed,
5216 fade: &mut *fade,
5217 channels,
5218 timeline: &mut *timeline,
5219 tx,
5220 },
5221 pos,
5222 next,
5223 ) {
5224 return false;
5225 }
5226 }
5227}
5228
5229#[cfg(test)]
5230mod tests {
5231 use super::{
5232 MixControls, PRE_ROLL, SAMPLES_PER_PACKET, downmix, packet_at, packet_run, packet_run_last,
5233 vorbis_to_film_order,
5234 };
5235 use crate::limiter::Limiter;
5236
5237 const C: f32 = std::f32::consts::FRAC_1_SQRT_2;
5238
5239 /// The fold, channel by channel and width by width: each side keeps its own
5240 /// front channel, takes the centre and its own surrounds at -3 dB, drops the
5241 /// LFE, and comes out unable to clip a full-scale source. The channel order
5242 /// is FL, FR, FC, LFE, BL, BR, SL, SR.
5243 #[test]
5244 fn a_surround_frame_folds_to_stereo_without_clipping() {
5245 // Per width: what each channel at full scale, alone, must land as
5246 // *before* the normalisation that width carries.
5247 let layouts: [(usize, &[(f32, f32)]); 6] = [
5248 (3, &[(1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]),
5249 (4, &[(1.0, 0.0), (0.0, 1.0), (C, 0.0), (0.0, C)]),
5250 (5, &[(1.0, 0.0), (0.0, 1.0), (C, C), (C, 0.0), (0.0, C)]),
5251 (
5252 6,
5253 &[
5254 (1.0, 0.0),
5255 (0.0, 1.0),
5256 (C, C),
5257 (0.0, 0.0),
5258 (C, 0.0),
5259 (0.0, C),
5260 ],
5261 ),
5262 (
5263 7,
5264 &[
5265 (1.0, 0.0),
5266 (0.0, 1.0),
5267 (C, C),
5268 (0.0, 0.0),
5269 (C, C),
5270 (C, 0.0),
5271 (0.0, C),
5272 ],
5273 ),
5274 (
5275 8,
5276 &[
5277 (1.0, 0.0),
5278 (0.0, 1.0),
5279 (C, C),
5280 (0.0, 0.0),
5281 (C, 0.0),
5282 (0.0, C),
5283 (C, 0.0),
5284 (0.0, C),
5285 ],
5286 ),
5287 ];
5288 for (from, want) in layouts {
5289 let (nl, nr) = want
5290 .iter()
5291 .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1));
5292 for (channel, &(left, right)) in want.iter().enumerate() {
5293 let mut frame = vec![0.0f32; from];
5294 frame[channel] = 1.0;
5295 downmix(&mut frame, from);
5296 assert_eq!(frame.len(), 2, "{from} ch: one frame is one stereo frame");
5297 assert!(
5298 (frame[0] - left / nl).abs() < 1e-6 && (frame[1] - right / nr).abs() < 1e-6,
5299 "{from} ch{channel}: {frame:?}, want {left}/{nl} {right}/{nr}"
5300 );
5301 }
5302 // Every channel at once is what a normalised fold exists for.
5303 let mut loud = vec![1.0f32; from * 2];
5304 downmix(&mut loud, from);
5305 assert_eq!(loud.len(), 4, "{from} ch: two frames out of two");
5306 assert!(
5307 loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),
5308 "{from} ch: full scale in, full scale out, never past it: {loud:?}"
5309 );
5310 }
5311 // Mono and stereo are handed over untouched.
5312 for from in [1, 2] {
5313 let mut flat = vec![0.5f32, -0.5];
5314 downmix(&mut flat, from);
5315 assert_eq!(flat, [0.5, -0.5], "{from} ch is not a fold");
5316 }
5317 }
5318
5319 /// The Vorbis order an Opus surround stream is stored in, into the film
5320 /// order the fold reads. Each channel is its own index, so a permutation
5321 /// that drifts is the value that comes out in the wrong slot.
5322 #[test]
5323 fn vorbis_order_becomes_film_order() {
5324 // (width, film slot -> the vorbis channel it must hold)
5325 for (from, want) in [
5326 (3usize, &[0, 2, 1][..]),
5327 (5, &[0, 2, 1, 3, 4]),
5328 (6, &[0, 2, 1, 5, 3, 4]),
5329 (7, &[0, 2, 1, 6, 5, 3, 4]),
5330 (8, &[0, 2, 1, 7, 5, 6, 3, 4]),
5331 ] {
5332 // Two frames, so a permutation that reads across the frame boundary
5333 // shows up as the wrong frame's value.
5334 let mut samples: Vec<f32> = (0..from * 2).map(|i| i as f32).collect();
5335 vorbis_to_film_order(&mut samples, from);
5336 let got: Vec<usize> = samples[..from].iter().map(|&s| s as usize).collect();
5337 assert_eq!(got, want, "{from} ch, first frame");
5338 let second: Vec<usize> = samples[from..].iter().map(|&s| s as usize - from).collect();
5339 assert_eq!(second, want, "{from} ch, second frame");
5340 }
5341 // 7.1's LFE is the last vorbis channel and the fourth film one.
5342 let mut lfe = vec![0.0f32; 8];
5343 lfe[7] = 1.0;
5344 vorbis_to_film_order(&mut lfe, 8);
5345 assert_eq!(
5346 lfe[3], 1.0,
5347 "the LFE lands where the fold drops it: {lfe:?}"
5348 );
5349 }
5350
5351 /// A real AAC track: one stts entry, N packets of 1024.
5352 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
5353 [(count, 1024)]
5354 }
5355
5356 #[test]
5357 fn packet_at_walks_back_by_the_pre_roll() {
5358 // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..).
5359 assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064));
5360 assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016));
5361 // Exactly on a packet boundary is the start of that packet, not the end
5362 // of the previous one.
5363 assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048));
5364 }
5365
5366 #[test]
5367 fn packet_at_clamps_both_ends() {
5368 // Head: no room for the walk-back, and packet ids are 1-based.
5369 assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0));
5370 assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0));
5371 // Past the end: the last packet, so the worker decodes ~nothing.
5372 assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776));
5373 // Degenerate boxes must not panic or wrap.
5374 assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0));
5375 assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0));
5376 }
5377
5378 #[test]
5379 fn packet_at_crosses_stts_entries() {
5380 // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240
5381 // with packet 11.
5382 let entries = [(10u32, 1024u32), (10, 512)];
5383 assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288));
5384 assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264));
5385 // The corner-cut clamp: on the first packet of the second entry the
5386 // walk-back stops there instead of stepping into the first entry.
5387 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
5388 }
5389
5390 /// xorshift64: adversarial segment lists do not deserve a dependency.
5391 fn rng(state: &mut u64) -> u64 {
5392 *state ^= *state << 13;
5393 *state ^= *state >> 7;
5394 *state ^= *state << 17;
5395 *state
5396 }
5397
5398 #[test]
5399 fn packet_run_keeps_cumulative_error_under_a_packet() {
5400 let packet = i64::from(SAMPLES_PER_PACKET);
5401 let mut state = 0x5eed_1234_9876_abcd;
5402 for rate in [44100i64, 48000] {
5403 for list in 0..100 {
5404 let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64);
5405 // 3..43 joins of anything from one video frame to four seconds.
5406 for join in 0..3 + rng(&mut state) % 40 {
5407 let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64;
5408 copied += i64::from(packet_run(&mut err, ideal, u32::MAX));
5409 asked += ideal;
5410 assert!(
5411 err.abs() < packet,
5412 "rate {rate} list {list} join {join}: err {err}"
5413 );
5414 }
5415 // The accumulator is the whole story: what it says is the drift.
5416 assert_eq!(copied * packet - asked, err);
5417 }
5418 }
5419 }
5420
5421 #[test]
5422 fn packet_run_rounds_against_the_running_debt() {
5423 // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples
5424 // owed, and the debt is repaid by a 44-packet second once it crosses a
5425 // half packet — never by letting each second round on its own.
5426 let mut err = 0;
5427 assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43);
5428 assert_eq!(err, -68);
5429 let mut seconds = 1;
5430 while packet_run(&mut err, 44100, u32::MAX) == 43 {
5431 seconds += 1;
5432 assert!(seconds < 20, "debt never repaid, err {err}");
5433 }
5434 assert_eq!(seconds, 7, "68 samples a second, half a packet is 512");
5435 assert!(err > 0, "the repaying second overshoots, err {err}");
5436 }
5437
5438 #[test]
5439 fn the_last_run_rounds_up_so_the_copy_reaches_its_picture() {
5440 // test_sync.mp4: 4.0 s at 44100 is 172.27 packets. Nearest copies 172 and
5441 // leaves 6 ms unwritten; the last run takes the 173rd, which runs 16 ms
5442 // past the picture -- under a frame.
5443 let ideal = 176_400;
5444 let mut err = 0;
5445 assert_eq!(packet_run(&mut err, ideal, u32::MAX), 172);
5446 let mut err = 0;
5447 assert_eq!(packet_run_last(&mut err, ideal, u32::MAX), 173);
5448 assert_eq!(err, 173 * 1024 - ideal);
5449 // A whole number of packets is not rounded up, and the track's end caps it.
5450 let mut err = 0;
5451 assert_eq!(packet_run_last(&mut err, 1024 * 10, u32::MAX), 10);
5452 assert_eq!(packet_run_last(&mut err, 1024 * 10, 4), 4);
5453 }
5454
5455 #[test]
5456 fn packet_run_forgives_a_debt_the_track_cannot_pay() {
5457 // Asking a second of a track with ten packets left: it delivers ten and
5458 // does not make the next segment copy the shortfall from elsewhere.
5459 let mut err = 0;
5460 assert_eq!(packet_run(&mut err, 44100, 10), 10);
5461 assert_eq!(err, 0);
5462 // Degenerate windows are empty, not negative.
5463 assert_eq!(packet_run(&mut err, 0, 10), 0);
5464 assert_eq!(packet_run(&mut err, i64::MAX, 7), 7);
5465 }
5466
5467 #[test]
5468 fn asc_round_trips_aac_lc_44100_stereo() {
5469 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
5470 let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8);
5471 let asc = [
5472 (profile << 3) | (freq_index >> 1),
5473 (freq_index << 7) | (chan_conf << 3),
5474 ];
5475 assert_eq!(asc, [0x12, 0x10]);
5476 }
5477
5478 /// The one claim worth making about a hand-written bitstream: our own
5479 /// decoder turns it into exactly one packet of exactly zero.
5480 #[test]
5481 fn a_silent_packet_decodes_to_a_packet_of_zero() {
5482 use super::silent_packet;
5483
5484 for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] {
5485 // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels.
5486 // `4 << 7` in a u8 is zero: freq_index 4 has no low bits to put in byte 1.
5487 let asc = [(2 << 3) | (4 >> 1), chan_conf << 3];
5488 let mut decoder = ec_aac::AacDecoder::with_config_bytes(&asc).expect("decoder");
5489 let bytes = silent_packet(chan_conf).expect("silence");
5490 let pcm = decoder.decode(&bytes, None).expect("decodes as AAC-LC");
5491 assert_eq!(pcm.channels as usize, channels);
5492 assert_eq!(pcm.samples.len(), SAMPLES_PER_PACKET as usize * channels);
5493 assert!(
5494 pcm.samples.iter().all(|&s| s == 0.0),
5495 "{chan_conf} ch is not silent"
5496 );
5497 }
5498 assert!(
5499 silent_packet(6).is_err(),
5500 "beyond stereo is refused, not faked"
5501 );
5502 }
5503
5504 #[test]
5505 fn lane_peaks_keep_the_highest_level_until_read() {
5506 let controls = MixControls::new(vec![1.0, 1.0], Vec::new(), Limiter::default());
5507 controls.note_lane_peak(0, 0.25);
5508 controls.note_lane_peak(0, 0.5);
5509 controls.note_lane_peak(0, 0.125);
5510 controls.note_lane_peak(1, 0.75);
5511 controls.note_lane_peak(7, 1.0);
5512 assert_eq!(
5513 controls.take_lane_peaks(),
5514 vec![0.5, 0.75],
5515 "the highest level since the last read, per lane; a lane with no slot is ignored"
5516 );
5517 assert_eq!(
5518 controls.take_lane_peaks(),
5519 vec![0.0, 0.0],
5520 "a read starts the meters over"
5521 );
5522 }
5523
5524 /// A stereo clip on a mono timeline is no longer refused: the export folds
5525 /// its pair to the one channel the timeline carries ([`super::widen`]), the
5526 /// same as playback does. The file comes back mono, and the stereo clip's
5527 /// span is audible in it -- silent there would mean the fold dropped it.
5528 #[test]
5529 fn a_mono_clip_then_a_stereo_clip_exports_stereo() {
5530 use crate::export::{ExportSettings, Format};
5531 use crate::project::{Clip, LaneKind, Project, Source, Speed};
5532 use crate::scale::FitPolicy;
5533
5534 let assets = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets");
5535 let mono = assets.join("test_seek_chirp.mkv");
5536 let stereo = assets.join("test_av1_grain.mkv");
5537 let meta = crate::demux::Demuxer::open(&assets.join("test_av.mp4"))
5538 .expect("open test_av")
5539 .0;
5540 let clip = |start, source| Clip {
5541 speed_keys: Vec::new(),
5542 reversed: false,
5543 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5544 angle: Default::default(),
5545 fade_in: 0,
5546 fade_out: 0,
5547 transition_out: 0,
5548 transition_kind: Default::default(),
5549 visualizer: 0,
5550 viz_paint: 0,
5551 gain_db: 0.0,
5552 gain_keys: Vec::new(),
5553 pan: 0,
5554 transform_keys: Vec::new(),
5555 opacity_keys: Vec::new(),
5556 color_keys: Vec::new(),
5557 effects: Vec::new(),
5558 start,
5559 in_frame: 0,
5560 out_frame: 30,
5561 source,
5562 link: None,
5563 eq: None,
5564 color: None,
5565 fit: FitPolicy::default(),
5566 speed: Speed::NORMAL,
5567 transform: None,
5568 pitch: 0,
5569 };
5570 // One second of the mono source, then one second of the stereo one.
5571 let project = Project::from_parts(
5572 vec![Source::new(&mono, 0), Source::new(&stereo, 0)],
5573 vec![(LaneKind::Audio, vec![clip(0, 0), clip(30, 1)])],
5574 Vec::new(),
5575 Vec::new(),
5576 Vec::new(),
5577 )
5578 .expect("a mono clip with a stereo clip after it");
5579
5580 let out = crate::scratch::Scratch::file("ve_stereo_on_mono", "wav");
5581 let handle = crate::export::start(
5582 project,
5583 meta,
5584 &out,
5585 &ExportSettings {
5586 format: Format::Wav,
5587 ..Default::default()
5588 },
5589 None,
5590 );
5591 let started = std::time::Instant::now();
5592 while !handle.is_finished() {
5593 assert!(started.elapsed().as_secs() < 120, "export did not finish in 120s");
5594 std::thread::sleep(std::time::Duration::from_millis(10));
5595 }
5596 handle
5597 .result()
5598 .expect("a finished export has an outcome")
5599 .expect("a mono clip then a stereo clip exports");
5600
5601 let (audio, chunks) = crate::AudioSession::open(&out)
5602 .expect("reopen the export")
5603 .expect("the export has audio");
5604 let mut samples = Vec::new();
5605 for chunk in chunks {
5606 samples.extend(chunk.samples);
5607 }
5608 // The timeline is as wide as its widest clip: the mono clip is widened
5609 // into both channels, and the stereo one is kept rather than folded.
5610 assert_eq!(audio.channels, 2, "a stereo clip makes the timeline stereo");
5611 let rate = f64::from(audio.sample_rate);
5612 let rms = |from: f64, to: f64| {
5613 let at = |secs: f64| (secs * rate) as usize;
5614 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
5615 assert!(!window.is_empty(), "no samples in [{from}, {to})");
5616 (window.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() / window.len() as f64)
5617 .sqrt()
5618 };
5619 let mono_span = rms(0.05, 0.95);
5620 let stereo_span = rms(1.05, 1.95);
5621 println!("rms: mono clip {mono_span:.4} stereo clip {stereo_span:.4}");
5622 assert!(mono_span > 0.01, "the mono clip is audible");
5623 assert!(stereo_span > 0.01, "the stereo clip is audible on the stereo timeline");
5624 std::fs::remove_file(&out).ok();
5625 }
5626}
5627