forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio.rs5638 lines, 248.4 KiBHistoryRawDownload
1//! Background audio decode worker: pulls a source's audio track and hands
2//! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own
3//! reader so the video demuxer stays single-owner.
4//!
5//! Three readers, one output. An mp4 goes through `mp4` 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 type Key = (PathBuf, usize, Option<std::time::SystemTime>, u64);
1539 static KNOWN: std::sync::Mutex<Option<std::collections::HashMap<Key, f64>>> = std::sync::Mutex::new(None);
1540 let meta = std::fs::metadata(path).ok();
1541 let key: Key = (path.to_path_buf(), stream, meta.as_ref().and_then(|m| m.modified().ok()), meta.map_or(0, |m| m.len()));
1542 if let Some(secs) = KNOWN.lock().ok().and_then(|k| k.as_ref()?.get(&key).copied()) {
1543 return Ok(Some(secs));
1544 }
1545 let Some((meta, rx)) = Self::open(path)? else {
1546 return Ok(None);
1547 };
1548 let channels = usize::from(meta.channels.max(1));
1549 let last = rx.into_iter().fold(0, |_, chunk| {
1550 chunk.start_sample + (chunk.samples.len() / channels) as u64
1551 });
1552 let secs = last as f64 / f64::from(meta.sample_rate.max(1));
1553 if let Ok(mut k) = KNOWN.lock() {
1554 k.get_or_insert_with(Default::default).insert(key, secs);
1555 }
1556 Ok(Some(secs))
1557 }
1558
1559 /// The raw AAC packets covering `segs` — the same half-open source-second
1560 /// windows [`open_segments`](Self::open_segments) decodes — copied out
1561 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
1562 /// straight into an mp4 writer, which is how an export keeps its sound exact
1563 /// wherever the edit lets it (a lane carrying an equalizer cannot be copied
1564 /// and is re-encoded instead -- `export::encode_audio`).
1565 ///
1566 /// Cut points do not land on 1024-sample boundaries, so each segment is
1567 /// rounded to whole packets against an error carried across the joins (see
1568 /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the
1569 /// asked-for length however many cuts there are, instead of drifting out of
1570 /// lip sync one rounding at a time.
1571 ///
1572 /// The run starts one packet before the first audible one, which a reader
1573 /// drops as encoder priming — for a segment list starting at 0.0 that is the
1574 /// source's own priming packet, so the copy is the whole track from sample 1.
1575 ///
1576 /// `Ok(None)` for a file with no AAC track, and for an empty segment list.
1577 ///
1578 /// corner-cut: the first packet after an *interior* join decodes without its
1579 /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is
1580 /// re-encoding just the join packets, which needs an encoder we do not have.
1581 pub fn copy_segments(
1582 path: impl AsRef<Path>,
1583 segs: &[(f64, f64)],
1584 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
1585 let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect();
1586 Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs)
1587 }
1588
1589 /// [`copy_segments`](Self::copy_segments) over several files, segments naming
1590 /// their source by index into `sources`. The rounding debt is carried across
1591 /// a source join exactly as across a cut inside one file, so the bound stays
1592 /// half a packet over the whole list however many files it spans, and the
1593 /// extra priming packet is still the very first segment's alone.
1594 ///
1595 /// Every source that *has* a track must declare the same
1596 /// [`AacTrackParams`]: the copy becomes one output track with one esds.
1597 /// Import refuses a mismatch up front; the check here is the backstop.
1598 ///
1599 /// A segment naming **no** source is a gap, and is copied as that many
1600 /// packets of [`silent_packet`] silence — the rounding debt carried through
1601 /// it like any other, so the hole occupies its exact duration and the audio
1602 /// after it stays in sync with the picture. A gap the track *opens* on gets
1603 /// one silent packet more, which is the priming a reader drops. A segment
1604 /// naming a *silent* source is written the same way: a clip whose file has
1605 /// no audio track is a hole with a picture over it, and the timeline it
1606 /// joined already said so ([`crate::PlaybackSession::import`]).
1607 pub fn copy_multi_segments(
1608 sources: &[PathBuf],
1609 segs: &[(Option<usize>, f64, f64)],
1610 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
1611 let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
1612 Self::copy_multi_streams(&sources, segs)
1613 }
1614
1615 /// [`copy_multi_segments`](Self::copy_multi_segments) with each source
1616 /// naming *which* of its audio streams to copy — the same `(path, stream)`
1617 /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two
1618 /// take it in the same shape on purpose: an export that copied a different
1619 /// stream from the one the timeline played would be a file that sounds
1620 /// nothing like what was edited, and nothing would say so.
1621 pub fn copy_multi_streams(
1622 sources: &[(PathBuf, usize)],
1623 segs: &[(Option<usize>, f64, f64)],
1624 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
1625 // The output track is declared from the first source that has one --
1626 // not simply the first one named, which may be a silent clip. Such a
1627 // clip defines no rate and no layout; it is written as silence below
1628 // and the track goes on being the audible sources' track.
1629 let mut tracks: Vec<Option<Option<AacTrack>>> = sources.iter().map(|_| None).collect();
1630 let mut first = None;
1631 for &(source, ..) in segs {
1632 let Some(source) = source else { continue };
1633 if let Some(track) = source_at(&mut tracks, sources, source)? {
1634 first = Some(track.track_params());
1635 break;
1636 }
1637 }
1638 let Some(params) = first else {
1639 return Ok(None); // no segments, or nothing but silence
1640 };
1641
1642 let sample_rate = params.sample_rate;
1643 let mut err = 0i64;
1644 let mut packets: Vec<AacPacket> = Vec::new();
1645 for (at, &(source, start_secs, end_secs)) in segs.iter().enumerate() {
1646 // The last segment is the only one no later join pays a rounding
1647 // debt in, so its run rounds up ([`packet_run_last`]).
1648 let last = at + 1 == segs.len();
1649 // A gap, and a clip whose source carries no track, are the same hole
1650 // to write: silence for as long as the window is.
1651 let named = match source {
1652 Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)),
1653 None => None,
1654 };
1655 let Some((source, track)) = named else {
1656 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
1657 let bytes = silent_packet(params.chan_conf)?;
1658 // A reader drops the first packet of an AAC track as the
1659 // encoder's priming. When the track opens on a hole, that has to
1660 // come out of one *extra* packet of silence: dropped out of the
1661 // hole itself it would shorten it, and everything after the hole
1662 // would play a packet early. It is not part of the run, so it
1663 // owes the rounding debt nothing.
1664 let priming = u32::from(packets.is_empty());
1665 let run = match last {
1666 true => packet_run_last(&mut err, ideal, u32::MAX),
1667 false => packet_run(&mut err, ideal, u32::MAX),
1668 };
1669 for _ in 0..run + priming {
1670 packets.push(AacPacket {
1671 bytes: bytes.clone(),
1672 samples: SAMPLES_PER_PACKET,
1673 });
1674 }
1675 continue;
1676 };
1677 if track.track_params() != params {
1678 return Err(format!(
1679 "source {source} audio is {:?}, the timeline's is {params:?}",
1680 track.track_params()
1681 )
1682 .into());
1683 }
1684 let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale);
1685 let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0);
1686 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64;
1687 let available = track.sample_count.saturating_sub(start_id - 1);
1688 // The head packet is the priming of the first segment only: a reader
1689 // drops exactly one, so an interior join must not add another --
1690 // and neither must a segment behind a leading gap, which already
1691 // paid the priming in silence.
1692 let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1);
1693 let run = match last {
1694 true => packet_run_last(&mut err, ideal, available),
1695 false => packet_run(&mut err, ideal, available),
1696 };
1697 let ids = head
1698 .into_iter()
1699 .chain(start_id..start_id + run);
1700 for id in ids {
1701 let Some(sample) = mp4track::sample(&mut track.reader, track.stream, id)? else {
1702 let count = track.sample_count;
1703 return Err(format!("audio sample {id} of {count} is missing").into());
1704 };
1705 packets.push(AacPacket {
1706 bytes: sample.data.to_vec(),
1707 samples: SAMPLES_PER_PACKET,
1708 });
1709 }
1710 }
1711 Ok(Some((params, packets)))
1712 }
1713}
1714
1715/// One AAC-LC access unit of silence, for the gaps in an exported timeline —
1716/// this is the *copy* path, which never encodes anything, so the only silence it
1717/// can write is one spelled out by hand. (The re-encode path next door has a
1718/// real encoder and needs none of this: its gaps are zero samples.)
1719///
1720/// It is the shortest legal `raw_data_block` there is: one element carrying
1721/// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no
1722/// spectral data at all and therefore 1024 samples of exact zero. Every field
1723/// is zero except the element id and the terminating `ID_END`, so the whole
1724/// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the
1725/// unit tests, which is the only claim worth making about hand-written
1726/// bitstream.
1727///
1728/// corner-cut: mono and stereo only, because `chan_conf` beyond 2 needs more
1729/// elements per block; the timeline refuses such a source at import today, so
1730/// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements.
1731fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
1732 match chan_conf {
1733 // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned.
1734 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]),
1735 // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END.
1736 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]),
1737 n => Err(format!("cannot write silence for a {n}-channel AAC track").into()),
1738 }
1739}
1740
1741/// The source at `index`, on the stream it names, opened on first use -- and
1742/// `None` for a source that has no track at all, which the caller writes as
1743/// silence exactly as it writes a gap. The outer `Option` is "has it been
1744/// opened", the inner one "was there anything in it", so a silent source is
1745/// opened once like any other. Sources a segment list never names are never
1746/// touched: a project's list only grows.
1747fn source_at<'a>(
1748 tracks: &'a mut [Option<Option<AacTrack>>],
1749 sources: &[(PathBuf, usize)],
1750 index: usize,
1751) -> crate::Result<Option<&'a mut AacTrack>> {
1752 let slot = tracks
1753 .get_mut(index)
1754 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
1755 if slot.is_none() {
1756 let (path, stream) = &sources[index];
1757 *slot = Some(copy_track(path, *stream)?);
1758 }
1759 Ok(slot.as_mut().expect("just opened").as_mut())
1760}
1761
1762/// A source's track for the *copy* path, which needs raw AAC access units.
1763///
1764/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name
1765/// and by format. That is no longer the end of the road: `export::copy_audio`
1766/// takes it as the answer "not copyable" and decodes and re-encodes the timeline
1767/// instead, so these words are a fallback's reason rather than a user's refusal.
1768/// They are still worded for a person, because a caller with no encoder to fall
1769/// back on shows them verbatim.
1770///
1771/// `Ok(None)` for a file with no audio at all, which is a silent export.
1772fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
1773 match Track::open(path, stream)? {
1774 None => Ok(None),
1775 // An HE-AAC track has packets of 2048 frames and a config the copy
1776 // cannot rebuild, so it is re-encoded like every other uncopyable source.
1777 Some(Track::Aac(track)) if track.sbr => Err(format!(
1778 "a packet copy needs AAC-LC in an mp4; {} is HE-AAC",
1779 path.file_name()
1780 .unwrap_or(path.as_os_str())
1781 .to_string_lossy(),
1782 )
1783 .into()),
1784 Some(Track::Aac(track)) => Ok(Some(track)),
1785 // A Matroska source gets its own words: its packets *are* AAC, so
1786 // "export needs AAC audio today" would read as a contradiction. What
1787 // they are not is packets of an mp4 sample table, which is what the
1788 // copy walks. The export decodes such a source and encodes it again
1789 // rather than showing this, so a film's sound reaches an mp4 either way;
1790 // the words stay for a caller that copies and cannot re-encode.
1791 //
1792 // corner-cut: the ceiling is the copy path being written against the mp4
1793 // reader, not anything about the bytes. Upgrade path is a
1794 // `copy_segments` that walks a Matroska track, which would make this a
1795 // copy again instead of a re-encode.
1796 Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!(
1797 "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \
1798 a copy walks an mp4's own sample table. It is decoded and encoded again \
1799 instead",
1800 path.file_name()
1801 .unwrap_or(path.as_os_str())
1802 .to_string_lossy(),
1803 )
1804 .into()),
1805 Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
1806 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
1807 // sample table can hold. The export decodes it and encodes AAC, exactly
1808 // as it does for every other source no copy reaches.
1809 Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")),
1810 // The same reason again: a TrueHD access unit is not an `mp4a` sample.
1811 Some(Track::Truehd(_)) => Err(uncopyable(path, "TrueHD")),
1812 Some(Track::Ext(_)) => Err(uncopyable(path, "DTS, ADPCM, A-law, mu-law or AMR")),
1813 // A transport stream's packets are not an mp4's sample table either.
1814 Some(Track::Ts(_)) => Err(uncopyable(path, "an MPEG system stream's sound")),
1815 }
1816}
1817
1818/// The one wording for "this source's audio cannot be *copied* into an mp4",
1819/// shared by every format that cannot be. What the export does about it is
1820/// decode and re-encode; this is the reason it had to.
1821fn uncopyable(path: &Path, codec: &str) -> crate::Error {
1822 format!(
1823 "a packet copy needs AAC in an mp4; {} is {codec}",
1824 path.file_name()
1825 .unwrap_or(path.as_os_str())
1826 .to_string_lossy(),
1827 )
1828 .into()
1829}
1830
1831/// One source's audio, however it is stored: the mp4 AAC track the export can
1832/// copy, or a standalone file read through symphonia's probe. The opener and
1833/// the worker speak to this, never to either reader directly.
1834enum Track {
1835 Aac(AacTrack),
1836 Ac3(Ac3Track),
1837 /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an
1838 /// mp4's sample table.
1839 Mkv(MkvAc3Track),
1840 /// Dolby TrueHD or MLP, out of a Matroska file's blocks, decoded by
1841 /// `ec-truehd`.
1842 Truehd(MkvTruehdTrack),
1843 /// DTS, ADPCM, A-law / mu-law and AMR out of a Matroska, mp4 / QuickTime /
1844 /// 3GP, WAVE or raw file, read by `ec-probe` ([`crate::extaudio`]).
1845 Ext(Box<crate::extaudio::ExtFileTrack>),
1846 Sym(SymTrack),
1847 /// One sound track of an MPEG transport stream, its own demuxer under it
1848 /// ([`crate::demux::ts`]): AAC in ADTS, AC-3, E-AC-3, MP3 and HDMV LPCM.
1849 Ts(Box<crate::demux::ts::TsAudio>),
1850}
1851
1852impl Track {
1853 /// `Ok(None)` for a file with no audio, which is a valid silent source.
1854 ///
1855 /// The mp4 reader goes first and its verdict is final for anything that is
1856 /// not [`crate::is_audio`]: a video file's audio track is exactly what it
1857 /// always was, silent mp4s included (an mp4 whose only `soun` track is one
1858 /// we cannot decode has always been a silent source, not an error). Only a
1859 /// standalone audio file falls through to symphonia — which is also how an
1860 /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track.
1861 ///
1862 /// `stream` counts audio tracks in file order, as
1863 /// [`AudioSession::probe_streams`] hands them out. A standalone audio file
1864 /// has exactly one, so any `stream` above 0 there is a promise the file
1865 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
1866 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1867 crate::demux::refuse_speex(path)?;
1868 crate::demux::refuse_asf(path)?;
1869 // A Matroska file goes to symphonia, whose `mkv` reader is the one thing
1870 // here that reads its packets -- neither mp4 reader can open the file at
1871 // all -- except for the two codecs symphonia has no decoder for at any
1872 // version and this project does: AC-3 and E-AC-3 are handed to the Dolby
1873 // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither
1874 // one can decode (Opus, DTS) leaves the source the silent one it always
1875 // was, which `AudioSession::unsupported` puts into words, rather than
1876 // failing the import of a file whose picture is fine. A track that will
1877 // not open at all is *not* in that group: see below.
1878 if crate::demux::is_matroska(path) {
1879 // The numbering `probe_streams` lists and a project saves, from the
1880 // one function that decides it ([`mkv_stream_order`]): the stream
1881 // index picks a `TrackEntry`, that entry's *track number* is what
1882 // both readers are then pointed at. Positions are never handed to a
1883 // reader -- symphonia's own order is its business -- because a
1884 // mapping that drifts plays the wrong language and saves it into
1885 // the project.
1886 let tracks = crate::demux::matroska_audio_tracks(path)?;
1887 if tracks.is_empty() {
1888 return Ok(None);
1889 }
1890 let order = mkv_stream_order(path, &tracks);
1891 let Some(entry) = order.get(stream).map(|at| &tracks[*at]) else {
1892 return Err(format!(
1893 "{}: audio stream {stream} of {} stream{}",
1894 path.display(),
1895 tracks.len(),
1896 if tracks.len() == 1 { "" } else { "s" }
1897 )
1898 .into());
1899 };
1900 // TrueHD and MLP go to their own decoder out of the same blocks. An
1901 // open failure is returned, not passed on: symphonia cannot read the
1902 // track either, and the silence it would give is the bug
1903 // [`MkvTruehdTrack`] exists to avoid -- an Atmos track's refusal is
1904 // the answer the user needs.
1905 if matches!(entry.codec.as_str(), "A_TRUEHD" | "A_MLP")
1906 && let Some(track) = MkvTruehdTrack::open_track(path, entry.number)?
1907 {
1908 return Ok(Some(Self::Truehd(track)));
1909 }
1910 match MkvAc3Track::open_track(path, entry.number) {
1911 Ok(Some(track)) => return Ok(Some(Self::Mkv(track))),
1912 Ok(None) => {}
1913 // Named on the way past rather than returned: symphonia gets the
1914 // same file next and may read the track perfectly well (a laced
1915 // block is [`MkvAc3Track`]'s limitation, not the file's), and
1916 // if it cannot either, *its* `Err` is the one that comes back.
1917 Err(e) => debug_once(format!("matroska audio: {}: {e}", path.display())),
1918 }
1919 // Two things are silent here and no more: a file with no audio
1920 // track at all, and a track whose codec nothing in this project
1921 // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts
1922 // that into words). A track that will not *open* is an `Err`, the
1923 // same answer the mp4 arm gives: turned into silence it would play
1924 // and export as a hole with only an eprintln to say why, which is a
1925 // bug wearing a feature's clothes.
1926 // DTS (and its DTS-HD core) through `ec-dts`, out of the same blocks. An
1927 // open failure is returned: an XLL-only lossless track is refused by name.
1928 if (crate::extaudio::is_mkv_dts(&entry.codec) || crate::extaudio::is_mkv_mpeg_layer(&entry.codec))
1929 && let Some(track) = crate::extaudio::ExtFileTrack::open_native(path, entry.number)?
1930 {
1931 return Ok(Some(Self::Ext(Box::new(track))));
1932 }
1933 // Speex has no reader in this build (symphonia cannot open it): silent, and
1934 // `AudioSession::unsupported` names it for the warning.
1935 if codec_display_name(&entry.codec) == "Speex" {
1936 return Ok(None);
1937 }
1938 let Some(track) = SymTrack::open_track(path, entry.number)? else {
1939 return Ok(None);
1940 };
1941 if let Err(e) = track.decoder() {
1942 debug_once(format!("matroska audio: {}: {e}", path.display()));
1943 return Ok(None);
1944 }
1945 return Ok(Some(Self::Sym(track)));
1946 }
1947 // A transport stream is read by its own demuxer, whatever the sound in it is.
1948 if crate::demux::is_mpeg_system(path) {
1949 return Ok(crate::demux::ts::TsAudio::open(path, stream)?.map(|t| Self::Ts(Box::new(t))));
1950 }
1951 let audio_file = crate::is_audio(path);
1952 // Ahead of the AAC reader, because that one answers "not AAC" for a
1953 // *named* stream with an `Err` and an AC-3 track is not an error any
1954 // more. `Ok(None)` here means "not an AC-3 track", so every other file
1955 // falls through to exactly the reader it always used.
1956 if !audio_file && let Some(track) = Ac3Track::open(path, stream)? {
1957 return Ok(Some(Self::Ac3(track)));
1958 }
1959 match AacTrack::open(path, stream) {
1960 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
1961 Ok(None) if !audio_file => {
1962 // Not AAC: DTS, ADPCM, A-law / mu-law or AMR in an mp4 / QuickTime / 3GP file.
1963 return Ok(crate::extaudio::ExtFileTrack::open(path, stream)?.map(|t| Self::Ext(Box::new(t))));
1964 }
1965 Err(e) if !audio_file => {
1966 return match crate::extaudio::ExtFileTrack::open(path, stream) {
1967 Ok(Some(t)) => Ok(Some(Self::Ext(Box::new(t)))),
1968 _ => Err(e),
1969 };
1970 }
1971 _ => {}
1972 }
1973 // A WAVE file that is not plain PCM (ADPCM, A-law, mu-law, DTS), a raw `.dts`
1974 // or `.amr`: `ec-probe`'s reader, ahead of symphonia's.
1975 if stream == 0
1976 && let Some(track) = crate::extaudio::ExtFileTrack::open(path, 0)?
1977 {
1978 return Ok(Some(Self::Ext(Box::new(track))));
1979 }
1980 if stream > 0 {
1981 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
1982 }
1983 SymTrack::open_required(path).map(|track| Some(Self::Sym(track)))
1984 }
1985
1986 fn sample_rate(&self) -> u32 {
1987 match self {
1988 Self::Aac(t) => t.sample_rate,
1989 Self::Ac3(t) => t.sample_rate,
1990 Self::Mkv(t) => t.sample_rate,
1991 Self::Truehd(t) => t.sample_rate,
1992 Self::Ext(t) => t.sample_rate,
1993 Self::Sym(t) => t.sample_rate,
1994 Self::Ts(t) => t.sample_rate,
1995 }
1996 }
1997
1998 /// What this track hands the timeline: mono, or stereo for everything else.
1999 /// Nothing is refused for its width any more -- a layout wider than a pair
2000 /// is folded to one at the decoder's door ([`downmix`]), because one output
2001 /// device is all there is, not because the file is unreadable.
2002 fn channels(&self) -> u16 {
2003 match self {
2004 Self::Aac(t) => t.channels(),
2005 // Downmixed to a pair by the AC-3 decoder itself (§7.8.2); a mono
2006 // track passes through as the one channel it is (see [`ac3_decoder`]),
2007 // so what `channels` measures is already the timeline width.
2008 Self::Ac3(t) => t.channels,
2009 // The same decoder, out of a Matroska file.
2010 Self::Mkv(t) => t.channels,
2011 // Folded to a pair by [`downmix`] in the worker; see [`MkvTruehdTrack`].
2012 Self::Truehd(t) => t.channels,
2013 Self::Ext(t) => t.channels(),
2014 Self::Sym(t) => t.channels,
2015 Self::Ts(t) => t.channels(),
2016 }
2017 }
2018
2019 /// Frames per channel of *audible* audio, priming already subtracted.
2020 fn total_samples(&self) -> Option<u64> {
2021 match self {
2022 Self::Aac(t) => t.total_samples,
2023 Self::Ac3(t) => t.total_samples,
2024 Self::Mkv(t) => t.total_samples,
2025 Self::Truehd(t) => t.total_samples,
2026 Self::Ext(t) => t.total_samples,
2027 Self::Sym(t) => t.total_samples,
2028 Self::Ts(t) => t.total_samples,
2029 }
2030 }
2031
2032 /// Encoder delay of this file. Sources are joined, priming is not shared.
2033 fn priming(&self) -> u64 {
2034 match self {
2035 Self::Aac(t) => t.priming,
2036 Self::Ac3(t) => t.priming,
2037 // Matroska writes no edit list and AC-3 has no encoder delay:
2038 // block 0 is sample 0.
2039 Self::Mkv(_) | Self::Truehd(_) | Self::Ts(_) => 0,
2040 Self::Ext(t) => t.priming,
2041 Self::Sym(t) => t.priming,
2042 }
2043 }
2044
2045 /// One `[start, end)` window of this source's seconds, resolved to whatever
2046 /// its own reader needs to find it again.
2047 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
2048 match self {
2049 Self::Aac(t) => t.segment(source, start_secs, end_secs),
2050 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
2051 Self::Mkv(t) => t.segment(source, start_secs, end_secs),
2052 Self::Truehd(t) => t.segment(source, start_secs, end_secs),
2053 Self::Ext(t) => {
2054 let rate = f64::from(t.sample_rate);
2055 let media_target = (start_secs.max(0.0) * rate).round() as u64 + t.priming;
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).saturating_add(t.priming)).max(media_target),
2062 }
2063 }
2064 Self::Ts(t) => {
2065 let rate = f64::from(t.sample_rate);
2066 let media_target = (start_secs.max(0.0) * rate).round() as u64;
2067 Segment {
2068 source: Some(source),
2069 start_id: 0,
2070 start_pos: 0,
2071 media_target,
2072 media_end: ((end_secs.max(0.0) * rate).round() as u64).max(media_target),
2073 }
2074 }
2075 Self::Sym(t) => {
2076 let media_target = t.media(start_secs);
2077 Segment {
2078 source: Some(source),
2079 start_id: 0,
2080 start_pos: 0,
2081 media_target,
2082 media_end: t.media(end_secs).max(media_target),
2083 }
2084 }
2085 }
2086 }
2087
2088 /// Builds and throws away a decoder, so an undecodable stream is an `Err`
2089 /// from the opener rather than a silently empty channel.
2090 fn check_decoder(&self) -> crate::Result<()> {
2091 match self {
2092 Self::Aac(t) => {
2093 aac_decoder(&t.params, t.source_channels())?;
2094 }
2095 Self::Ac3(t) => {
2096 ac3_decoder(t.requested)?;
2097 }
2098 Self::Mkv(t) => {
2099 ac3_decoder(t.requested)?;
2100 }
2101 // Its first access unit was decoded by the opener already.
2102 Self::Truehd(_) => {}
2103 Self::Ext(t) => {
2104 t.decoder()?;
2105 }
2106 Self::Ts(t) => {
2107 t.decoder()?;
2108 }
2109 Self::Sym(t) => {
2110 t.decoder()?;
2111 }
2112 }
2113 Ok(())
2114 }
2115}
2116
2117/// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read
2118/// through symphonia's own probe and codec registry. No packet table and no
2119/// sample ids: the reader is *seeked* per segment and the packets it then hands
2120/// out carry their own timestamps.
2121struct SymTrack {
2122 reader: Box<dyn FormatReader>,
2123 /// The file the reader reads, kept because a seek builds a *new* one
2124 /// ([`SymTrack::seek_to`]).
2125 path: PathBuf,
2126 track_id: u32,
2127 sample_rate: u32,
2128 /// What reaches the timeline: the file's own layout, or 2 for anything
2129 /// wider, which is folded down by [`SymDecoder`] exactly as the AC-3
2130 /// reader's decoder folds its own.
2131 channels: u16,
2132 /// What the decoder emits, which is what the fold reads.
2133 source_channels: u16,
2134 /// Frames per channel of audible audio, `None` when the header does not say.
2135 total_samples: Option<u64>,
2136 /// Frames withheld at the very end of the track and never played: the
2137 /// `DiscardPadding` of Vorbis in Matroska, whose blocks carry no granule to
2138 /// cut by. Zero for everything else (Ogg Vorbis is cut by its granules, per
2139 /// packet).
2140 tail_hold: u64,
2141 /// Every packet of a Matroska Vorbis track with its exact start in samples
2142 /// ([`VorbisStarts`]). Matroska stamps a block in whole milliseconds, up to
2143 /// half a millisecond (22 samples at 44.1 kHz) off the samples it holds, so
2144 /// a track with this index is read by it -- packet by packet, and sought by
2145 /// sample -- rather than through symphonia's stamp-based reader. `None` for
2146 /// everything else, which keeps its packets' own timestamps or granules.
2147 vorbis_starts: Option<VorbisStartsRef>,
2148 /// The file the indexed packets are read from.
2149 vorbis_file: Option<File>,
2150 /// The index of the next packet [`SymTrack::next_packet`] reads.
2151 vorbis_next: usize,
2152 /// Encoder delay, and **always zero here**: symphonia 0.6 drops the leading
2153 /// frames itself, so a reader that skipped `Track::delay` on top would skip
2154 /// them twice. Kept as a field because [`Track::priming`] asks every track
2155 /// for one and the AAC and AC-3 readers beside it do owe a real number.
2156 ///
2157 /// This used to carry `delay` and cost the double skip on the two formats
2158 /// that declare one: a `.mp3` lost its first 1105 samples (25 ms) and read
2159 /// 25 ms short, an `.ogg` its first 128. Measured 2026-08-11 against
2160 /// `test_tone.flac` -- lossless, and the only one of the three whose
2161 /// container declares no delay at all -- which the mp3 and the ogg of the
2162 /// same tone align with sample for sample once this is not subtracted.
2163 priming: u64,
2164 time_base: TimeBase,
2165 params: AudioCodecParameters,
2166 /// The format's short name, for the export refusal. `&'static` because it
2167 /// comes out of the codec registry, which outlives everything here.
2168 codec: &'static str,
2169}
2170
2171impl SymTrack {
2172 /// `Ok(None)` for a container that opened and holds no audio track at all --
2173 /// a silent source, which is a thing a file is allowed to be. Everything
2174 /// else that goes wrong here is an `Err`: a file that will not open, will
2175 /// not parse, or carries a track it cannot describe is *broken*, and the
2176 /// difference matters because silence is played and exported without a word
2177 /// while an `Err` is shown ([`Track::open`]).
2178 fn open(path: &Path) -> crate::Result<Option<Self>> {
2179 Self::open_inner(path, None)
2180 }
2181
2182 /// [`open`](Self::open) pointed at one **named** track: a Matroska
2183 /// `TrackNumber`, which symphonia keeps as the track's id
2184 /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second
2185 /// language of a dual-audio file reachable, and it is matched by number
2186 /// rather than by position so this reader and
2187 /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which
2188 /// track a stream index meant. `Ok(None)` for a number the reader does not
2189 /// carry.
2190 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
2191 Self::open_inner(path, Some(number))
2192 }
2193
2194 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
2195 let reader = sym_reader(path)?;
2196 let track = match number {
2197 Some(number) => reader.tracks().iter().find(|t| u64::from(t.id) == number),
2198 None => reader.default_track(SymKind::Audio),
2199 };
2200 let Some(track) = track else {
2201 return Ok(None);
2202 };
2203 // `track.delay` is deliberately not read: see the `priming` field.
2204 let (track_id, num_frames) = (track.id, track.num_frames);
2205 let time_base = track
2206 .time_base
2207 .ok_or_else(|| format!("{} declares no time base", path.display()))?;
2208 let Some(symphonia_core::codecs::CodecParameters::Audio(params)) =
2209 track.codec_params.clone()
2210 else {
2211 return Err(format!("{} declares no audio codec", path.display()).into());
2212 };
2213 // An AAC track's rate is the one `ec-aac` decodes at, which for HE-AAC
2214 // is the SBR extension rate (2x the core the container may state). An
2215 // ADTS stream carries no config to read that from, so its header's rate
2216 // is only the core's until the first frames are decoded (see below).
2217 let mut sample_rate = match (params.codec, params.extra_data.as_deref()) {
2218 (CODEC_ID_AAC, Some(asc)) => aac_output_rate(asc)?,
2219 _ => params.sample_rate,
2220 }
2221 .ok_or_else(|| format!("{} declares no sample rate", path.display()))?;
2222 let mut channels = params.channels.as_ref().map(|c| c.count() as u16);
2223 // A plain-LC config, or an ADTS stream with none, may still be HE-AAC by
2224 // implicit signalling: its rate only doubles once a frame has carried an
2225 // SBR payload, so the first frames are decoded to read the real rate.
2226 if params.codec == CODEC_ID_AAC
2227 && aac_may_be_implicit(params.extra_data.as_deref())?
2228 && let Some(primed) = sym_aac_prime(path, track_id, params.extra_data.as_deref())?
2229 {
2230 sample_rate = primed.sample_rate;
2231 channels = Some(primed.channels);
2232 }
2233 let channels = channels
2234 .ok_or_else(|| format!("{} declares no channel layout", path.display()))?;
2235 // Vorbis in Matroska states no length on the track and its blocks carry
2236 // no granule: the last block's padding is what its muxer says to drop
2237 // from the end ([`crate::demux::matroska_tail_padding_ns`]).
2238 let tail_hold = match params.codec {
2239 CODEC_ID_VORBIS => crate::demux::matroska_tail_padding_ns(path, u64::from(track_id))
2240 .map_or(0, |ns| (ns as f64 * f64::from(sample_rate) / 1e9).round() as u64),
2241 _ => 0,
2242 };
2243 let vorbis_starts = match params.codec {
2244 CODEC_ID_VORBIS if crate::demux::is_matroska(path) => {
2245 matroska_vorbis_starts(path, u64::from(track_id), &params)
2246 }
2247 _ => None,
2248 };
2249 let vorbis_file = match vorbis_starts {
2250 Some(_) => Some(File::open(path)?),
2251 None => None,
2252 };
2253 // AAC is decoded by `ec-aac`, which symphonia's registry does not list.
2254 let codec = match params.codec {
2255 CODEC_ID_AAC => "aac",
2256 _ => symphonia::default::get_codecs()
2257 .get_audio_decoder(params.codec)
2258 .map_or("an unsupported format", |d| d.codec.info.short_name),
2259 };
2260 // The one codec here that *does* owe a priming number: Opus states its
2261 // encoder delay in the stream itself (`OpusHead`'s pre-skip, 312 samples
2262 // on a film remux) and neither reader drops it, because symphonia trims
2263 // for its own decoders and the Opus one is this crate's. Measured against
2264 // ffmpeg's decode of the same file: 312 samples late in *both* an mkv and
2265 // an ogg until this is subtracted, sample-exact after (correlation
2266 // 1.00000). It is priming exactly as an AAC track's is, and it is read
2267 // off the stream rather than the container for that reason.
2268 let priming = match params.codec {
2269 CODEC_ID_OPUS => opus_pre_skip(params.extra_data.as_deref().unwrap_or_default()),
2270 _ => 0,
2271 };
2272 Ok(Some(Self {
2273 reader,
2274 path: path.to_path_buf(),
2275 track_id,
2276 sample_rate,
2277 // Anything wider than a pair arrives as a stereo source, whatever it
2278 // was stored as: 5.1, 7.1 and everything between are folded by
2279 // [`downmix`] at the decoder's door ([`SymDecoder`]).
2280 channels: channels.min(2),
2281 source_channels: channels,
2282 total_samples: num_frames.map(|n| n.saturating_sub(priming)),
2283 tail_hold,
2284 vorbis_starts,
2285 vorbis_file,
2286 vorbis_next: 0,
2287 priming,
2288 time_base,
2289 params,
2290 codec,
2291 }))
2292 }
2293
2294 /// [`open`](Self::open) where having no audio track is itself the error:
2295 /// what a standalone audio file is held to, since a song with no sound in
2296 /// it is a broken file and not a silent source.
2297 fn open_required(path: &Path) -> crate::Result<Self> {
2298 Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into())
2299 }
2300
2301 /// A fresh decoder: seeking mid-stream leaves state that belongs to the
2302 /// packets we skipped, exactly as on the AAC path.
2303 ///
2304 /// Which decoder is not the caller's business, and it is not always
2305 /// symphonia's: it has no AAC decoder in this build at all (its HE-AAC
2306 /// refusal, "aac: aac too complex", is why), so every AAC track goes to
2307 /// `ec-aac` instead ([`aac_decoder`]), and it has no Opus decoder either, so
2308 /// that one goes to `ec-opus` ([`SymDecoder::Opus`]).
2309 fn decoder(&self) -> crate::Result<SymDecoder> {
2310 let from = usize::from(self.source_channels);
2311 if self.params.codec == CODEC_ID_OPUS {
2312 let (streams, coupled, mapping) =
2313 opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?;
2314 // 48 kHz whatever the container says: that is the only rate Opus
2315 // decodes at, and the rate both readers declare for it.
2316 let decoder =
2317 ec_opus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping);
2318 return Ok(SymDecoder::Opus(Box::new(decoder), from));
2319 }
2320 if self.params.codec == CODEC_ID_AAC {
2321 return aac_decoder(&self.params, from);
2322 }
2323 if self.params.codec == CODEC_ID_VORBIS {
2324 return vorbis_decoder(&self.params);
2325 }
2326 Ok(SymDecoder::Sym(
2327 symphonia::default::get_codecs()
2328 .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,
2329 from,
2330 ))
2331 }
2332
2333 /// `secs` on this source's audible timeline into media samples (priming
2334 /// included, so it compares directly against a decoded position).
2335 fn media(&self, secs: f64) -> u64 {
2336 ((secs * f64::from(self.sample_rate)).round() as u64).saturating_add(self.priming)
2337 }
2338
2339 /// Where the packet stamped `ts` begins, exactly, for a track with an index
2340 /// ([`VorbisStarts`]). `None` where there is none, or `ts` is not one of its
2341 /// packets' stamps.
2342 fn exact_start(&self, ts: units::Timestamp) -> Option<u64> {
2343 let starts = self.vorbis_starts.as_deref()?;
2344 Some(starts.packets[starts.at(ts.get())?].start)
2345 }
2346
2347 /// The next packet of the track: from the index's file where the track has
2348 /// one, stamped with its own stamp, and from the reader otherwise.
2349 fn next_packet(&mut self) -> Result<Option<Packet>, String> {
2350 let (Some(starts), Some(file)) = (self.vorbis_starts.as_deref(), self.vorbis_file.as_mut())
2351 else {
2352 return self.reader.next_packet().map_err(|e| e.to_string());
2353 };
2354 let Some(block) = starts.packets.get(self.vorbis_next) else {
2355 return Ok(None);
2356 };
2357 self.vorbis_next += 1;
2358 crate::demux::check_extent(file, block.at, block.len).map_err(|e| e.to_string())?;
2359 let mut data = vec![0u8; block.len];
2360 file.seek(SeekFrom::Start(block.at))
2361 .and_then(|_| file.read_exact(&mut data))
2362 .map_err(|e| format!("reading a Vorbis block: {e}"))?;
2363 let stamp = units::Timestamp::new(block.stamp);
2364 Ok(Some(Packet::new(self.track_id, stamp, units::Duration::ZERO, data)))
2365 }
2366
2367 /// A packet timestamp in the track's time base, as a media position: the
2368 /// scale [`media`](Self::media) hands out, so a landing compares directly
2369 /// against a segment's target.
2370 ///
2371 /// The priming comes *off* it because a Matroska Opus track's blocks are
2372 /// timestamped for the audible stream while the decoder hands its samples
2373 /// back with the pre-skip still in front of them. Measured against ffmpeg's
2374 /// decode of the same second of a real 5.1 Opus remux: without this term a seeked
2375 /// Opus track came out 6.5 ms -- one pre-skip, 312 samples -- ahead of it,
2376 /// with it, on the same sample.
2377 fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {
2378 let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
2379 // Rounded, not truncated: a position is a whole sample, and the seconds
2380 // it was converted through sit a sample low when truncated (11840 came
2381 // back 11839), which the seek test's exact check caught.
2382 ((secs.max(0.0) * f64::from(self.sample_rate)).round() as u64).saturating_sub(self.priming)
2383 }
2384
2385 /// Puts the reader **at or before** `media_target`, [`SYM_PRE_ROLL`] ahead
2386 /// of it where the container allows, so that everything the caller did not
2387 /// ask for is decoder warm-up that [`emit`] drops.
2388 ///
2389 /// At or before is the whole point, and it is not what one seek gives. A
2390 /// Matroska seek lands on the first frame whose timestamp is at or past the
2391 /// one asked for, and its cue table can put that a whole cluster further on
2392 /// still: measured on a real 5.1 Opus remux, asking for 599.83 s (600 s less the
2393 /// pre-roll) landed at 601.487 s and asking for 609.83 s at 613.407 s.
2394 /// Samples that far *behind* the reader can never be emitted, and the film
2395 /// played from there while the timeline said 600 s -- 1.5 s of sound
2396 /// against picture, which is the seek desync this exists to kill. So the
2397 /// landing is read back, and an overshoot is asked again from far enough
2398 /// before it to swallow the overshoot.
2399 ///
2400 /// Each attempt gets a **new reader**, because symphonia's mkv seek is
2401 /// reliable exactly once per reader: it neither clears the frames it has
2402 /// already queued (they come out ahead of the new position, carrying the
2403 /// old block's timestamp) nor recovers its element iterator, and a second
2404 /// seek measured on the same file landed the reader back at the first
2405 /// cluster, 0.094 s, whatever it was asked for. Opening again costs 2 ms on
2406 /// a 5 GB film, which is what a seek is allowed to cost.
2407 fn seek_to(&mut self, media_target: u64) {
2408 // With an index the packet is found by its sample, not by a seek of the
2409 // container's: the decoder starts at the packet before the first one
2410 // whose start is at or before the target, since a fresh decoder answers
2411 // nothing for the packet it starts on and the next one is the first
2412 // that answers. Nothing is read here; [`SymTrack::next_packet`] reads it.
2413 if let Some(starts) = self.vorbis_starts.as_deref() {
2414 let at_or_before = starts
2415 .packets
2416 .partition_point(|p| p.start <= media_target);
2417 self.vorbis_next = at_or_before.saturating_sub(2);
2418 return;
2419 }
2420 let rate = f64::from(self.sample_rate.max(1));
2421 let mut back = SYM_PRE_ROLL;
2422 // Enough for any overshoot a cue table can hold: each attempt asks from
2423 // strictly further back than the last, and the seek to 0 is the floor.
2424 for _ in 0..8 {
2425 let from = media_target.saturating_sub(back);
2426 match sym_reader(&self.path) {
2427 Ok(reader) => self.reader = reader,
2428 // Whatever the file did, the reader in hand still reads: fall
2429 // back to seeking that one, exactly as before this loop existed.
2430 Err(e) => eprintln!("audio reopen failed: {e}"),
2431 }
2432 // Asking for the beginning is asking for nothing: a fresh reader is
2433 // already there, and *seeking* there is how the first 167 ms of a
2434 // real 5.1 Opus remux went missing -- the cue table's first point put the
2435 // reader past them and no window rule can reach back.
2436 if from == 0 {
2437 return;
2438 }
2439 let secs = from as f64 / rate;
2440 let Some(time) = Time::try_from_secs_f64(secs) else {
2441 return;
2442 };
2443 let to = SeekTo::Time {
2444 time,
2445 track_id: Some(self.track_id),
2446 };
2447 // A failed seek is not fatal: it leaves the reader where it was, and
2448 // the window rules still only emit what the segment asked for.
2449 let landed = match self.reader.seek(SeekMode::Accurate, to) {
2450 Ok(landed) => self.samples_at(landed.actual_ts),
2451 Err(e) => {
2452 eprintln!("audio seek to {secs:.3}s failed: {e}");
2453 return;
2454 }
2455 };
2456 if landed <= media_target {
2457 return;
2458 }
2459 back += (landed - media_target) + SYM_PRE_ROLL;
2460 }
2461 }
2462}
2463
2464/// One symphonia reader over `path`, which is both how a track is opened and
2465/// how it is seeked ([`SymTrack::seek_to`]).
2466///
2467/// A raw ADTS stream is read by [`crate::adts`] rather than probed: symphonia's
2468/// own ADTS reader lives behind the `aac` feature this project does not link,
2469/// and an ADTS sync word is the one thing it would have answered to anyway.
2470fn sym_reader(path: &Path) -> crate::Result<Box<dyn FormatReader>> {
2471 let mut head = [0u8; 2];
2472 if File::open(path)?.read(&mut head)? == 2 && ec_aac::is_adts(&head) {
2473 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
2474 return Ok(Box::new(crate::adts::AdtsReader::try_new(mss)?));
2475 }
2476 let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
2477 // The extension is a hint, not a decision: the probe reads the magic and
2478 // is free to disagree, which is what makes a mislabelled file work.
2479 let mut hint = Hint::new();
2480 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
2481 hint.with_extension(ext);
2482 }
2483 Ok(symphonia::default::get_probe().probe(
2484 &hint,
2485 mss,
2486 FormatOptions::default(),
2487 MetadataOptions::default(),
2488 )?)
2489}
2490
2491/// One packet in, interleaved f32 out — whichever library did the decoding, and
2492/// already folded to the layout [`SymTrack::channels`] promised. The number
2493/// beside each is the width the decoder itself emits, which is what
2494/// [`downmix`] folds from; 1 and 2 fold to nothing.
2495enum SymDecoder {
2496 Sym(Box<dyn AudioDecoder>, usize),
2497 /// Every AAC track, mono to 7.1 and LC or HE-AAC: `ec-aac` takes the config
2498 /// the track carries, or the first ADTS frame's when it carries none. Boxed
2499 /// because the decoder carries its own IMDCT and SBR tables and this enum is
2500 /// moved into the worker.
2501 Aac(Box<ec_aac::AacDecoder>, usize),
2502 /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of
2503 /// a packet, the channel mapping table and the routing between them are all
2504 /// its business -- and the same width.
2505 Opus(Box<ec_opus::MultistreamDecoder>, usize),
2506 /// Every Vorbis track, Ogg or Matroska, mono to 7.1: `ec-vorbis` decodes
2507 /// the blocks, in the stream's channel order, and the second field is the
2508 /// width. The third maps each of those channels to the family's order
2509 /// ([`ec_vorbis::channel_map`]).
2510 Vorbis(Box<ec_vorbis::VorbisDecoder>, usize, Vec<usize>),
2511}
2512
2513impl SymDecoder {
2514 fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {
2515 match self {
2516 Self::Sym(decoder, from) => {
2517 decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);
2518 downmix(out, *from);
2519 }
2520 Self::Aac(decoder, from) => {
2521 let pcm = decoder
2522 .decode(&packet.data, None)
2523 .map_err(|e| format!("AAC decode failed: {e}"))?;
2524 // `pcm.sample_rate` is what this block is at; the track was
2525 // opened at the same rate ([`aac_output_rate`]), so the timeline
2526 // and the samples agree. The frame count comes from the block
2527 // itself, not from a fixed packet size, because HE-AAC carries
2528 // twice the frames of its core.
2529 *out = pcm.samples;
2530 downmix(out, *from);
2531 }
2532 Self::Vorbis(decoder, from, to_ec) => {
2533 let blocks = decoder
2534 .decode_audio(&packet.data)
2535 .map_err(|e| format!("Vorbis decode failed: {e}"))?;
2536 let mut planes = vec![Vec::new(); blocks.len()];
2537 for (channel, plane) in blocks.into_iter().enumerate() {
2538 if let Some(&slot) = to_ec.get(channel) {
2539 planes[slot] = plane;
2540 }
2541 }
2542 interleave_planes(&planes, out);
2543 vorbis_packet_window(out, planes.len(), packet);
2544 downmix(out, *from);
2545 }
2546 Self::Opus(decoder, from) => {
2547 *out = decoder
2548 .decode_packet(&packet.data)
2549 .map_err(|e| format!("Opus decode failed: {e}"))?;
2550 // The encoder delay is not dropped here: it is this track's
2551 // priming ([`SymTrack::open_inner`]), which the window rules
2552 // subtract once for the whole segment rather than per packet.
2553 vorbis_to_film_order(out, *from);
2554 downmix(out, *from);
2555 }
2556 }
2557 Ok(())
2558 }
2559}
2560
2561/// The decoder for a Vorbis track: `ec-vorbis`, from the identification and
2562/// setup headers symphonia states in the track's extra data (the same layout
2563/// in Ogg and in Matroska).
2564fn vorbis_decoder(params: &AudioCodecParameters) -> crate::Result<SymDecoder> {
2565 let decoder = vorbis_headers(params)?;
2566 let channels = usize::from(decoder.identification().channels);
2567 let (_, to_ec) = ec_vorbis::channel_map(channels);
2568 Ok(SymDecoder::Vorbis(Box::new(decoder), channels, to_ec))
2569}
2570
2571/// `ec-vorbis` built from a Vorbis track's headers, without a decoding state.
2572fn vorbis_headers(params: &AudioCodecParameters) -> crate::Result<ec_vorbis::VorbisDecoder> {
2573 let extra = params
2574 .extra_data
2575 .as_deref()
2576 .ok_or("a Vorbis track carries no headers")?;
2577 // symphonia states the identification header (30 bytes, fixed by Vorbis I)
2578 // and then the setup header; `ec-vorbis` wants all three, so the comment
2579 // header is written here as an empty one.
2580 let (ident, setup) = extra
2581 .split_at_checked(VORBIS_IDENT_LEN)
2582 .ok_or("a Vorbis track's identification header is short")?;
2583 ec_vorbis::VorbisDecoder::new(&[ident, VORBIS_EMPTY_COMMENTS, setup])
2584 .map_err(|e| format!("Vorbis headers: {e}").into())
2585}
2586
2587/// The starts of a Matroska Vorbis track's packets, in samples from its first.
2588///
2589/// Packet `n` answers the quarter of block `n-1` plus the quarter of block `n`
2590/// samples (`ec-vorbis` `packet_blocksize`), and the first packet answers none,
2591/// so the count of every packet before it is its exact position. The timestamp
2592/// alone cannot give that, since it is rounded to milliseconds, so the blocks
2593/// are counted: one byte each (their mode), in the cached block list of
2594/// [`crate::demux::matroska_track_blocks`]. The walk costs one read per block, and
2595/// it is kept per file, so a seek pays it once.
2596type VorbisStartsRef = Arc<VorbisStarts>;
2597
2598/// The packets of one Matroska Vorbis track, in storage order.
2599struct VorbisStarts {
2600 packets: Vec<VorbisPacket>,
2601}
2602
2603struct VorbisPacket {
2604 /// The block's own timestamp in the file, in `TimestampScale` ticks.
2605 stamp: i64,
2606 /// Where the packet's samples begin, in the track's own count from its start.
2607 start: u64,
2608 /// Where the block's bytes are, and how many.
2609 at: u64,
2610 len: usize,
2611}
2612
2613impl VorbisStarts {
2614 /// The index of the packet stamped `stamp`.
2615 fn at(&self, stamp: i64) -> Option<usize> {
2616 self.packets.binary_search_by_key(&stamp, |p| p.stamp).ok()
2617 }
2618}
2619
2620type StartsKey = (PathBuf, u64, u64, Option<std::time::SystemTime>);
2621
2622/// The most files whose packet index is kept; a seek reuses one of them.
2623const VORBIS_STARTS_KEPT: usize = 8;
2624
2625static VORBIS_STARTS: Mutex<Vec<(StartsKey, VorbisStartsRef)>> = Mutex::new(Vec::new());
2626
2627fn matroska_vorbis_starts(
2628 path: &Path,
2629 number: u64,
2630 params: &AudioCodecParameters,
2631) -> Option<VorbisStartsRef> {
2632 let meta = std::fs::metadata(path).ok()?;
2633 let key: StartsKey = (path.to_path_buf(), number, meta.len(), meta.modified().ok());
2634 if let Ok(kept) = VORBIS_STARTS.lock()
2635 && let Some((_, hit)) = kept.iter().find(|(k, _)| *k == key)
2636 {
2637 return Some(Arc::clone(hit));
2638 }
2639 let starts = Arc::new(vorbis_starts_walk(path, number, params)?);
2640 if let Ok(mut kept) = VORBIS_STARTS.lock() {
2641 if kept.len() >= VORBIS_STARTS_KEPT {
2642 kept.remove(0);
2643 }
2644 kept.push((key, Arc::clone(&starts)));
2645 }
2646 Some(starts)
2647}
2648
2649fn vorbis_starts_walk(
2650 path: &Path,
2651 number: u64,
2652 params: &AudioCodecParameters,
2653) -> Option<VorbisStarts> {
2654 let blocks = crate::demux::matroska_track_blocks(path, number)?;
2655 // The search by stamp needs them in order, which Matroska requires of a track.
2656 if blocks.windows(2).any(|w| w[0].0 >= w[1].0) {
2657 return None;
2658 }
2659 let headers = vorbis_headers(params).ok()?;
2660 let mut file = File::open(path).ok()?;
2661 let mut packets = Vec::with_capacity(blocks.len());
2662 let (mut samples, mut previous) = (0u64, None::<usize>);
2663 for (stamp, at, len) in blocks {
2664 packets.push(VorbisPacket {
2665 stamp,
2666 start: samples,
2667 at,
2668 len,
2669 });
2670 // The mode is in a packet's first byte, so the first bytes are all that is read.
2671 let mut head = [0u8; 8];
2672 let n = len.min(head.len());
2673 file.seek(SeekFrom::Start(at)).ok()?;
2674 file.read_exact(&mut head[..n]).ok()?;
2675 let size = headers.packet_blocksize(&head[..n]).ok()?;
2676 if let Some(previous) = previous {
2677 samples += (previous / 4 + size / 4) as u64;
2678 }
2679 previous = Some(size);
2680 }
2681 Some(VorbisStarts { packets })
2682}
2683
2684/// The fixed length of a Vorbis identification header (Vorbis I, A.2).
2685const VORBIS_IDENT_LEN: usize = 30;
2686
2687/// A Vorbis comment header with an empty vendor string and no comments, framed:
2688/// what `ec-vorbis` needs where symphonia's extra data carries none.
2689const VORBIS_EMPTY_COMMENTS: &[u8] = b"\x03vorbis\x00\x00\x00\x00\x00\x00\x00\x00\x01";
2690
2691/// Interleaves per-channel planes, in the order they are given.
2692fn interleave_planes(planes: &[Vec<f32>], out: &mut Vec<f32>) {
2693 let frames = planes.first().map_or(0, Vec::len);
2694 out.clear();
2695 out.reserve(frames * planes.len());
2696 for frame in 0..frames {
2697 for plane in planes {
2698 out.push(plane.get(frame).copied().unwrap_or(0.0));
2699 }
2700 }
2701}
2702
2703/// Cuts one Vorbis packet's decoded block down to the samples symphonia says
2704/// the packet owns: `dur` after its trims, from `trim_start`. Symphonia takes
2705/// both from the page granules (the stream's last block overhangs its end and
2706/// the first block has nothing before it), so the cut is the container's own.
2707/// A packet stating no duration keeps all of its block.
2708fn vorbis_packet_window(out: &mut Vec<f32>, channels: usize, packet: &Packet) {
2709 let channels = channels.max(1);
2710 let frames = out.len() / channels;
2711 let start = usize::try_from(packet.trim_start.get())
2712 .unwrap_or(usize::MAX)
2713 .min(frames);
2714 let end = match packet.dur.get() {
2715 0 => frames,
2716 dur => usize::try_from(dur).unwrap_or(usize::MAX).saturating_add(start).min(frames),
2717 };
2718 out.truncate(end * channels);
2719 out.drain(..start * channels);
2720}
2721
2722/// Samples per channel of a full HE-AAC frame: the SBR output of a 1024-sample
2723/// core. A frame whose header is missing comes out as the core alone, half this.
2724const SBR_FULL_FRAME: usize = 2048;
2725
2726/// The packet an SBR track's decoder starts on: the nearest one at or before
2727/// `from` whose own frame decodes with its SBR header, so every frame after it
2728/// is reconstructed. Headers come back every few packets (every 10 in libfdk's
2729/// streams), not on each one; a fresh decoder on a headerless frame gives its
2730/// core alone, which is how a frame without its header is told apart. Packet 1
2731/// always carries one.
2732fn sbr_start_packet(track: &mut AacTrack, from: u32) -> u32 {
2733 let mut id = from.max(1);
2734 while id > 1 {
2735 if sbr_packet_has_header(track, id) {
2736 return id;
2737 }
2738 id -= 1;
2739 }
2740 1
2741}
2742
2743/// Whether packet `id`, decoded on its own by a fresh decoder, comes out as a
2744/// full SBR frame. A failed read or decode counts as no.
2745fn sbr_packet_has_header(track: &mut AacTrack, id: u32) -> bool {
2746 let Ok(Some(sample)) = mp4track::sample(&mut track.reader, track.stream, id) else {
2747 return false;
2748 };
2749 let Ok(mut decoder) = aac_decoder(&track.params, track.source_channels()) else {
2750 return false;
2751 };
2752 let packet = Packet::new(
2753 track.track_id,
2754 units::Timestamp::new(sample.dts.unwrap_or(0)),
2755 units::Duration::new(u64::from(sample.duration.unwrap_or(0).max(0) as u32)),
2756 &sample.data[..],
2757 );
2758 let mut out = Vec::new();
2759 if decoder.decode(&packet, &mut out).is_err() {
2760 return false;
2761 }
2762 out.len() >= SBR_FULL_FRAME * track.source_channels()
2763}
2764
2765/// Where packet `id` starts on the track's timeline, from its time-to-sample
2766/// entries (`(count, delta)` runs, as [`packet_at`] reads them).
2767fn packet_start_ts(stts: &[(u32, u32)], id: u32) -> u64 {
2768 let mut first = 1u32;
2769 let mut ts = 0u64;
2770 for &(count, delta) in stts {
2771 if id < first + count {
2772 return ts + u64::from(id - first) * u64::from(delta);
2773 }
2774 first += count;
2775 ts += u64::from(count) * u64::from(delta);
2776 }
2777 ts
2778}
2779
2780/// The decoder for an AAC track of `from` channels: `ec-aac`, whatever the
2781/// width and whether or not the stream is HE-AAC. symphonia's own refused SBR
2782/// outright ("aac: aac too complex", `aac/mod.rs:91-96`), so it is not asked.
2783///
2784/// The config is the track's AudioSpecificConfig when it has one (mp4 `esds`,
2785/// Matroska `CodecPrivate`), which is what arms SBR. An ADTS stream has none,
2786/// and `ec-aac` takes its parameters from the first frame it reads.
2787fn aac_decoder(params: &AudioCodecParameters, from: usize) -> crate::Result<SymDecoder> {
2788 let decoder = match params.extra_data.as_deref() {
2789 Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)
2790 .map_err(|e| format!("AAC decoder init failed: {e}"))?,
2791 None => ec_aac::AacDecoder::new(),
2792 };
2793 Ok(SymDecoder::Aac(Box::new(decoder), from))
2794}
2795
2796/// The rate an AudioSpecificConfig decodes at: the extension rate for HE-AAC
2797/// (SBR reconstructed), the core rate otherwise. `Err` for a config `ec-aac`
2798/// cannot parse, which is a track that will not decode either.
2799fn aac_output_rate(asc: &[u8]) -> crate::Result<Option<u32>> {
2800 let decoder = ec_aac::AacDecoder::with_config_bytes(asc)
2801 .map_err(|e| format!("AAC config does not parse: {e}"))?;
2802 Ok(decoder.output_sample_rate())
2803}
2804
2805/// How many access units the implicit-SBR probe decodes. An SBR payload shows
2806/// in the first frame that carries one, and every SBR frame carries one, so two
2807/// frames are enough and bound the cost of opening a track.
2808const AAC_PRIME_UNITS: usize = 2;
2809
2810/// Whether an AAC track's rate can still change under implicit SBR: no config
2811/// (ADTS), or a plain AAC-LC one. An explicit SBR config states its rate, and a
2812/// PS one states its stereo output and rate, so neither is decoded to find out.
2813fn aac_may_be_implicit(asc: Option<&[u8]>) -> crate::Result<bool> {
2814 let Some(asc) = asc else {
2815 return Ok(true);
2816 };
2817 let decoder = ec_aac::AacDecoder::with_config_bytes(asc)
2818 .map_err(|e| format!("AAC config does not parse: {e}"))?;
2819 Ok(decoder.sbr_support() == ec_aac::SbrSupport::NotSignalled)
2820}
2821
2822/// What an AAC track decodes at, as a throwaway decoder finds it after its first
2823/// access units.
2824struct AacPrimed {
2825 sample_rate: u32,
2826 channels: u16,
2827 /// Whether an implicit SBR payload switched the rate on.
2828 implicit: bool,
2829}
2830
2831/// Decodes up to [`AAC_PRIME_UNITS`] of `units` through a fresh decoder, built
2832/// from `asc` or else from the first ADTS header, and reads back the rate it
2833/// now decodes at. `None` when no unit decodes: the caller keeps the rate its
2834/// container states, and the decode error surfaces on playback as it always has.
2835fn aac_prime(asc: Option<&[u8]>, units: &[&[u8]]) -> crate::Result<Option<AacPrimed>> {
2836 let mut decoder = match asc {
2837 Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)
2838 .map_err(|e| format!("AAC config does not parse: {e}"))?,
2839 None => ec_aac::AacDecoder::new(),
2840 };
2841 let mut channels = None;
2842 for unit in units.iter().take(AAC_PRIME_UNITS) {
2843 let Ok(pcm) = decoder.decode(unit, None) else {
2844 break;
2845 };
2846 channels = Some(pcm.channels);
2847 if decoder.sbr_implicit() {
2848 break;
2849 }
2850 }
2851 let (Some(channels), Some(sample_rate)) = (channels, decoder.output_sample_rate()) else {
2852 return Ok(None);
2853 };
2854 Ok(Some(AacPrimed {
2855 sample_rate,
2856 channels,
2857 implicit: decoder.sbr_implicit(),
2858 }))
2859}
2860
2861/// The first `count` packets of track `track_id` (for Matroska, its `TrackNumber`),
2862/// read through a fresh reader. Empty where the file cannot be read or has none,
2863/// and then the caller keeps what the header states.
2864pub(crate) fn first_packets(path: &Path, track_id: u32, count: usize) -> Vec<Vec<u8>> {
2865 let Ok(mut reader) = sym_reader(path) else {
2866 return Vec::new();
2867 };
2868 let mut out = Vec::with_capacity(count);
2869 while out.len() < count {
2870 match reader.next_packet() {
2871 Ok(Some(packet)) if packet.track_id == track_id => out.push(packet.data.to_vec()),
2872 Ok(Some(_)) => {}
2873 _ => break,
2874 }
2875 }
2876 out
2877}
2878
2879/// [`aac_prime`] over the first packets of `track_id`, read through a fresh
2880/// reader on `path`. A raw ADTS frame carries its own header, so it is decoded
2881/// as it stands.
2882fn sym_aac_prime(
2883 path: &Path,
2884 track_id: u32,
2885 asc: Option<&[u8]>,
2886) -> crate::Result<Option<AacPrimed>> {
2887 let mut reader = sym_reader(path)?;
2888 let mut units: Vec<Box<[u8]>> = Vec::with_capacity(AAC_PRIME_UNITS);
2889 while units.len() < AAC_PRIME_UNITS {
2890 match reader.next_packet()? {
2891 Some(packet) if packet.track_id == track_id => units.push(packet.data),
2892 Some(_) => {}
2893 None => break,
2894 }
2895 }
2896 let refs: Vec<&[u8]> = units.iter().map(|u| &u[..]).collect();
2897 aac_prime(asc, &refs)
2898}
2899
2900/// [`aac_prime`] over the first samples of an mp4 track, read through a fresh
2901/// reader on `path`: the track's own reader is borrowed by the track it opens.
2902fn mp4_aac_prime(path: &Path, stream: u32, asc: &[u8]) -> crate::Result<Option<AacPrimed>> {
2903 let mut reader = mp4track::open(path)?;
2904 let mut units: Vec<Vec<u8>> = Vec::with_capacity(AAC_PRIME_UNITS);
2905 for id in 1..=AAC_PRIME_UNITS as u32 {
2906 match mp4track::sample(&mut reader, stream, id) {
2907 Ok(Some(sample)) => units.push(sample.data.to_vec()),
2908 _ => break,
2909 }
2910 }
2911 let refs: Vec<&[u8]> = units.iter().map(Vec::as_slice).collect();
2912 aac_prime(Some(asc), &refs)
2913}
2914
2915/// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of
2916/// `OpusHead`, little-endian. Zero for a track whose header is missing or too
2917/// short to hold one -- there is nothing to subtract that we can trust.
2918fn opus_pre_skip(head: &[u8]) -> u64 {
2919 match head {
2920 [
2921 b'O',
2922 b'p',
2923 b'u',
2924 b's',
2925 b'H',
2926 b'e',
2927 b'a',
2928 b'd',
2929 _,
2930 _,
2931 lo,
2932 hi,
2933 ..,
2934 ] => u64::from(u16::from_le_bytes([*lo, *hi])),
2935 _ => 0,
2936 }
2937}
2938
2939/// The stream layout of an Opus track, off the file's own `OpusHead`: how many
2940/// elementary streams one packet carries, how many of those are coupled
2941/// (stereo), and which decoded channel each output channel comes from. Both
2942/// readers hand the header over as `extra_data` verbatim -- an mkv's
2943/// `CodecPrivate`, an ogg's identification packet.
2944///
2945/// Mapping family 0 carries no table at all and is mono or stereo by definition;
2946/// every other family writes one (RFC 7845 §5.1), and family 1 -- the Vorbis
2947/// surround layout a 5.1 film track is written with -- is four streams of which
2948/// two are coupled.
2949///
2950/// Everything here is checked rather than trusted: `MultistreamDecoder::with_rate`
2951/// *panics* on a layout that breaks the RFC's limits, and this header comes
2952/// straight out of a file, so a truncated or hostile one has to come back as an
2953/// `Err` and be refused like any other undecodable track.
2954fn opus_layout(head: &[u8], channels: usize) -> crate::Result<(usize, usize, Vec<u8>)> {
2955 if !(1..=255).contains(&channels) {
2956 return Err(format!("an Opus track of {channels} channels").into());
2957 }
2958 let table = match head {
2959 [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', rest @ ..] if rest.len() > 10 => {
2960 // Byte 18 of the header is the mapping family; the table, when there
2961 // is one, is the two counts and one byte per output channel after it.
2962 match rest[10] {
2963 0 => None,
2964 _ => Some(rest.get(11..13 + channels).ok_or("a truncated OpusHead")?),
2965 }
2966 }
2967 // No header at all: the container declared the channel count and nothing
2968 // else, which only family 0 can honestly be.
2969 _ => None,
2970 };
2971 let Some(table) = table else {
2972 if channels > 2 {
2973 return Err(format!("an Opus track of {channels} channels with no mapping").into());
2974 }
2975 return Ok((1, channels - 1, (0..channels as u8).collect()));
2976 };
2977 let (streams, coupled) = (usize::from(table[0]), usize::from(table[1]));
2978 let mapping = table[2..].to_vec();
2979 let decoded = streams + coupled;
2980 if streams < 1 || coupled > streams || decoded > 255 {
2981 return Err(format!("an Opus track of {streams} streams, {coupled} coupled").into());
2982 }
2983 if !mapping
2984 .iter()
2985 .all(|&m| m == 255 || usize::from(m) < decoded)
2986 {
2987 return Err(format!("an Opus channel mapping outside its {decoded} streams").into());
2988 }
2989 Ok((streams, coupled, mapping))
2990}
2991
2992/// Surround Opus is stored in Vorbis channel order (RFC 7845 §5.1.1.2) and
2993/// [`downmix`] reads the film order every other decoder here hands back. This is
2994/// that permutation, in place, per width: each entry says which *source* channel
2995/// the output slot of that index reads. Mono, stereo and quad agree already, and
2996/// a width the RFC does not lay out is left alone rather than shuffled by guess.
2997fn vorbis_to_film_order(samples: &mut [f32], from: usize) {
2998 let order: &[usize] = match from {
2999 3 => &[0, 2, 1], // FL FC FR
3000 5 => &[0, 2, 1, 3, 4], // FL FC FR SL SR
3001 6 => &[0, 2, 1, 5, 3, 4], // FL FC FR SL SR LFE
3002 7 => &[0, 2, 1, 6, 5, 3, 4], // FL FC FR SL SR BC LFE
3003 8 => &[0, 2, 1, 7, 5, 6, 3, 4], // FL FC FR SL SR BL BR LFE
3004 _ => return,
3005 };
3006 let mut frame = [0.0f32; 8];
3007 for chunk in samples.chunks_exact_mut(from) {
3008 frame[..from].copy_from_slice(chunk);
3009 for (out, &src) in chunk.iter_mut().zip(order) {
3010 *out = frame[src];
3011 }
3012 }
3013}
3014
3015/// What each channel of a `from`-wide film-order layout contributes to the left
3016/// and the right of a stereo fold. ITU-R BS.775: a front channel keeps its own
3017/// side, the centre and the back centre go to both at -3 dB, a surround joins
3018/// its own side at -3 dB, and the LFE is dropped -- it carries no programme a
3019/// stereo pair could put anywhere, and neither ffmpeg's default downmix nor any
3020/// player's puts it there.
3021///
3022/// The film order is FL, FR, FC, LFE, BL, BR, SL, SR, which is what symphonia's
3023/// decoders and `ec-aac` both hand back (the latter reorders AAC's own
3024/// C, L, R, Ls, Rs, LFE element order into it: its `film_order`) and what the
3025/// AC-3 decoder's own passthrough uses.
3026///
3027/// corner-cut: a width past 7.1 (22.2, ambisonics) keeps its front pair and drops
3028/// the rest -- no table here places those, and inventing one silently would be
3029/// worse than a fold that is merely narrow. Upgrade path is one more arm.
3030fn fold_coeffs(from: usize) -> Vec<(f32, f32)> {
3031 const C: f32 = std::f32::consts::FRAC_1_SQRT_2;
3032 const L: (f32, f32) = (1.0, 0.0);
3033 const R: (f32, f32) = (0.0, 1.0);
3034 const M: (f32, f32) = (C, C);
3035 const SL: (f32, f32) = (C, 0.0);
3036 const SR: (f32, f32) = (0.0, C);
3037 const X: (f32, f32) = (0.0, 0.0);
3038 match from {
3039 3 => vec![L, R, X], // L R LFE (the 2.1 passthrough)
3040 4 => vec![L, R, SL, SR], // FL FR BL BR
3041 5 => vec![L, R, M, SL, SR], // FL FR FC BL BR
3042 6 => vec![L, R, M, X, SL, SR], // 5.1
3043 7 => vec![L, R, M, X, M, SL, SR], // FL FR FC LFE BC SL SR
3044 8 => vec![L, R, M, X, SL, SR, SL, SR], // 7.1
3045 n => (0..n).map(|c| [L, R][usize::from(c > 0)]).collect(),
3046 }
3047}
3048
3049/// Anything wider than a stereo pair down to one, in place -- `from` is the
3050/// channel count the decoder actually emitted, and 1 or 2 is not touched at all.
3051/// This is what makes a 5.1 or 7.1 film an ordinary stereo source on the
3052/// timeline instead of an import refusal.
3053///
3054/// Both outputs are divided by the sum of their own coefficients
3055/// ([`fold_coeffs`]), so a source at full scale cannot come out clipped.
3056///
3057/// corner-cut: that normalisation costs 7.7 dB at 5.1 (9.9 at 7.1) against what
3058/// ffmpeg's `-ac 2` hands out, which does not normalise and can overload -- so a
3059/// film plays quieter here than in a player beside it. It is the loudness the
3060/// AC-3 5.1 path already has (measured within 1.3 dB), so the two agree; the
3061/// upgrade path is a limiter on the output, at which point the coefficients can
3062/// go back to 1.0.
3063fn downmix(samples: &mut Vec<f32>, from: usize) {
3064 if from < 3 {
3065 return;
3066 }
3067 let coeffs = fold_coeffs(from);
3068 let (left, right) = coeffs
3069 .iter()
3070 .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1));
3071 // Never a boost: a layout with nothing on one side stays where it is.
3072 let (left, right) = (1.0 / left.max(1.0), 1.0 / right.max(1.0));
3073 for frame in 0..samples.len() / from {
3074 let (mut l, mut r) = (0.0, 0.0);
3075 for (c, &(cl, cr)) in coeffs.iter().enumerate() {
3076 let sample = samples[frame * from + c];
3077 l += cl * sample;
3078 r += cr * sample;
3079 }
3080 samples[2 * frame] = l * left;
3081 samples[2 * frame + 1] = r * right;
3082 }
3083 samples.truncate(samples.len() / from * 2);
3084}
3085
3086/// The inverse of [`downmix`]: a mono buffer duplicated into every channel of
3087/// a wider timeline, in place. `from` is the width the decoder actually
3088/// handed back (already folded to 1 or 2 by [`downmix`] at its own door) and
3089/// `to` is the timeline's own width ([`mix`]'s `channels`); anything that is
3090/// not exactly the mono-into-wider case is left untouched -- a source already
3091/// at `to`, and a source wider than `to` other than a stereo pair onto a mono
3092/// timeline. That one is the remix the other way: each frame's two channels
3093/// are averaged into the timeline's single one (half of each, so full scale
3094/// in is full scale out), the same fold ffmpeg's `-ac 1` makes. Without it a
3095/// stereo file joining a mono timeline would hand the mixer twice the samples
3096/// it expects and play at double speed.
3097fn widen(samples: &mut Vec<f32>, from: usize, to: usize) {
3098 if from == 2 && to == 1 {
3099 let mut out = Vec::with_capacity(samples.len() / 2);
3100 out.extend(
3101 samples
3102 .as_chunks::<2>()
3103 .0
3104 .iter()
3105 .map(|f| (f[0] + f[1]) * 0.5),
3106 );
3107 *samples = out;
3108 return;
3109 }
3110 if from != 1 || to <= 1 {
3111 return;
3112 }
3113 let mut out = Vec::with_capacity(samples.len() * to);
3114 for &s in samples.iter() {
3115 out.extend(std::iter::repeat_n(s, to));
3116 }
3117 *samples = out;
3118}
3119
3120/// One source's AC-3 track: the same mp4 sample tables the AAC track is read
3121/// from, decoded through `ec-ac3` and **downmixed to stereo by the decoder
3122/// itself** (ATSC A/52 §7.8.2, [`ec_ac3::Downmix::Stereo`]), because one output
3123/// device and one timeline layout is all there is. A 5.1 BluRay track therefore
3124/// arrives here as an ordinary stereo source, and its rows in the picker say so.
3125///
3126/// `channels` is what the decoder actually emitted for the first frame rather
3127/// than an assumed 2: everything from stereo to 5.1 downmixes to stereo and a
3128/// mono track passes through as the one channel it is (`acmod` carries the
3129/// programme in the centre; duplicating it is the timeline's business, see
3130/// [`widen`]). The §7.8.2 fold is position-aware — every `acmod` from 1/0 to
3131/// 3/2 puts its centre and surrounds where the matrix says — so no width is
3132/// refused or mislabelled.
3133struct Ac3Track {
3134 reader: mp4track::Reader,
3135 stream: u32,
3136 sample_count: u32,
3137 sample_rate: u32,
3138 channels: u16,
3139 timescale: u32,
3140 priming: u64,
3141 total_samples: Option<u64>,
3142 stts: Vec<(u32, u32)>,
3143 /// What the decoder is asked to hand out, from this track's own layout:
3144 /// [`ec_ac3::Downmix::Stereo`] for anything with more than one front
3145 /// channel, [`ec_ac3::Downmix::Native`] — the coded channels untouched —
3146 /// for a mono track. See [`ac3_decoder`].
3147 requested: Option<u16>,
3148}
3149
3150impl Ac3Track {
3151 /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it
3152 /// is anything else (including out of range) — the caller then goes on to
3153 /// the AAC reader, which owns those verdicts and their wording.
3154 ///
3155 /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without
3156 /// keeping the fourcc, so what the track *is* comes out of the `stsd` by
3157 /// hand ([`crate::demux::sample_entry`]); the rate and the channel count
3158 /// come out of the first syncframe, which is where AC-3 states them.
3159 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
3160 let mut reader = mp4track::open(path)?;
3161 let Some(&(track_id, stream_id)) = mp4track::audio_tracks(&reader).get(stream) else {
3162 return Ok(None);
3163 };
3164 let Some(stream_id) = stream_id else {
3165 return Ok(None);
3166 };
3167 if &mp4track::sample_entry(&reader, track_id) != b"ac-3" {
3168 return Ok(None);
3169 }
3170 let timescale = mp4track::timescale(&reader, stream_id);
3171 let duration = mp4track::duration(&reader, stream_id).unwrap_or(0);
3172 let edit = mp4track::media_time(&reader, track_id);
3173 let stts = mp4track::stts(&reader, stream_id);
3174 let sample_count = mp4track::sample_count(&reader, stream_id);
3175
3176 let first = mp4track::sample(&mut reader, stream_id, 1)?
3177 .ok_or("the AC-3 track has no samples")?;
3178 let sample_rate = ec_ac3::syncinfo::parse(&first.data)
3179 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?
3180 .sample_rate;
3181 let nfchans = ec_ac3::bsi::parse(first.data.get(5..).unwrap_or_default())
3182 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
3183 .nfchans;
3184 let requested = (nfchans > 1).then_some(2);
3185 let mut decoder = ac3_decoder(requested)?;
3186 let channels = decode_ac3(&mut decoder, &first.data)?
3187 .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16)
3188 .filter(|&c| c > 0)
3189 .ok_or("the first AC-3 syncframe decoded to nothing")?;
3190
3191 // No encoder delay in AC-3; a remux that writes an edit list is still
3192 // honoured, exactly as the AAC track honours it.
3193 let priming = edit
3194 .and_then(|t| scale(t, sample_rate, timescale))
3195 .unwrap_or(0);
3196 Ok(Some(Self {
3197 stream: stream_id,
3198 sample_count,
3199 sample_rate,
3200 channels,
3201 timescale,
3202 priming,
3203 total_samples: scale(duration, sample_rate, timescale)
3204 .map(|d| d.saturating_sub(priming)),
3205 stts,
3206 requested,
3207 reader,
3208 }))
3209 }
3210
3211 /// `secs` on this source's audible timeline into media samples.
3212 fn media(&self, secs: f64) -> u64 {
3213 ((secs * f64::from(self.sample_rate)).round() as u64).saturating_add(self.priming)
3214 }
3215
3216 /// One `[start, end)` window, resolved to syncframes and media samples —
3217 /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll.
3218 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
3219 let media_target = self.media(start_secs);
3220 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
3221 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL);
3222 Segment {
3223 source: Some(source),
3224 start_id,
3225 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
3226 media_target,
3227 media_end: self.media(end_secs).max(media_target),
3228 }
3229 }
3230}
3231
3232/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same
3233/// decoder and the very same §7.8.2 stereo downmix [`Ac3Track`] runs, fed out of
3234/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux
3235/// therefore arrives on the timeline as an ordinary stereo source, exactly as
3236/// the mp4 path's does, and mono passes through exactly the same way.
3237///
3238/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side
3239/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]):
3240/// one block is one packet, one packet is one syncframe, and a seek lands on
3241/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in
3242/// front of it.
3243struct MkvAc3Track {
3244 mkv: crate::demux::MkvAudio,
3245 sample_rate: u32,
3246 /// What comes *out* of the decoder, measured on the first frame — 2 for
3247 /// anything from stereo to 5.1, 1 for a mono track (see `requested`).
3248 channels: u16,
3249 total_samples: Option<u64>,
3250 /// What the decoder is asked to hand out, from this track's own layout:
3251 /// `Some(2)` for anything with more than one front channel, `None` for a
3252 /// mono track. See [`ac3_decoder`].
3253 requested: Option<u16>,
3254}
3255
3256impl MkvAc3Track {
3257 /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 —
3258 /// that mkv is the silent source it has always been. An `Err` is a track
3259 /// that is one and could not be read, which
3260 /// [`AudioSession::unsupported`] quotes back to the user.
3261 fn open(path: &Path) -> crate::Result<Option<Self>> {
3262 Self::from_blocks(crate::demux::MkvAudio::open(path)?)
3263 }
3264
3265 /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]),
3266 /// which is how the AC-3 half of a dual-audio file is reached.
3267 ///
3268 /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number
3269 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
3270 Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?)
3271 }
3272
3273 fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> {
3274 let Some(mut mkv) = mkv else {
3275 return Ok(None);
3276 };
3277 // A TrueHD or MLP track has blocks too, and its own decoder ([`MkvTruehdTrack`]).
3278 if !matches!(mkv.codec, "ac3" | "eac3") {
3279 return Ok(None);
3280 }
3281 let first = mkv
3282 .frame(0)?
3283 .ok_or("the AC-3 track of this Matroska file has no blocks")?;
3284 // Rate and layout come out of the bit stream, which is where AC-3
3285 // states them: Matroska's `Audio` element repeats them and muxers get
3286 // that wrong often enough that the frame is the better source.
3287 // `nfchans` excludes the LFE in both syntaxes, which is what the
3288 // downmix decision wants.
3289 let (sample_rate, nfchans) = if mkv.codec == "eac3" {
3290 // Annex E's BSI starts right after the 16-bit syncword.
3291 let bsi = ec_ac3::eac3::parse(first.get(2..).unwrap_or_default())
3292 .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?;
3293 (bsi.sample_rate, bsi.nfchans)
3294 } else {
3295 let sync = ec_ac3::syncinfo::parse(&first)
3296 .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?;
3297 let bsi = ec_ac3::bsi::parse(first.get(5..).unwrap_or_default())
3298 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?;
3299 (sync.sample_rate, bsi.nfchans)
3300 };
3301 let requested = (nfchans > 1).then_some(2);
3302 let mut decoder = ac3_decoder(requested)?;
3303 let (pcm, samples) = decode_ac3(&mut decoder, &first)?
3304 .ok_or("the first AC-3 syncframe decoded to nothing")?;
3305 let channels = (pcm.len() as u64 / samples.max(1)) as u16;
3306 if channels == 0 {
3307 return Err("the first AC-3 syncframe decoded to nothing".into());
3308 }
3309 // The track runs to the last block's timestamp plus that block's own
3310 // frame -- a container that indexes nothing states no duration either,
3311 // and every frame of a syncframe stream is the same length.
3312 let last = mkv.secs(mkv.blocks().saturating_sub(1));
3313 Ok(Some(Self {
3314 total_samples: Some((last * f64::from(sample_rate)) as u64 + samples),
3315 sample_rate,
3316 channels,
3317 requested,
3318 mkv,
3319 }))
3320 }
3321
3322 /// `secs` on this source's timeline into media samples. No priming: the
3323 /// container carries no edit list and AC-3 no encoder delay.
3324 fn media(&self, secs: f64) -> u64 {
3325 (secs.max(0.0) * f64::from(self.sample_rate)).round() as u64
3326 }
3327
3328 /// One `[start, end)` window, resolved to blocks and media samples —
3329 /// [`Ac3Track::segment`] against block timestamps instead of an `stts`.
3330 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
3331 let media_target = self.media(start_secs);
3332 let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize);
3333 Segment {
3334 source: Some(source),
3335 start_id: start_id as u32,
3336 start_pos: self.media(self.mkv.secs(start_id)),
3337 media_target,
3338 media_end: self.media(end_secs).max(media_target),
3339 }
3340 }
3341}
3342
3343/// A fresh AC-3 / E-AC-3 decoder. `requested` is the downmix ask: `Some(2)`
3344/// hands back the library's own A/52 §7.8.2 stereo fold — per-position
3345/// coefficients from the frame's own `acmod` and mix levels, LFE dropped,
3346/// normalised so a full-scale mix cannot clip — which is the whole reason the
3347/// timeline can carry a 5.1 track at all; `None` passes the coded channels
3348/// through, which is what a mono track asks for (`acmod` 1/0 carries the
3349/// programme in the centre, and duplicating it is the timeline's business, see
3350/// [`widen`]). Fresh per segment for the same reason every other decoder here
3351/// is: a seek leaves overlap-add state belonging to the frames we skipped.
3352///
3353/// The syntax is not an argument: one decoder reads AC-3 and E-AC-3 alike,
3354/// dispatching per packet on `bsid`.
3355fn ac3_decoder(requested: Option<u16>) -> crate::Result<ec_ac3::Ac3Decoder> {
3356 Ok(ec_ac3::Ac3Decoder::with_options(ec_ac3::Options {
3357 downmix: requested
3358 .map(|_| ec_ac3::Downmix::Stereo)
3359 .unwrap_or(ec_ac3::Downmix::Native),
3360 ..ec_ac3::Options::default()
3361 }))
3362}
3363
3364/// One syncframe in, one buffer of interleaved f32 out and the frames per
3365/// channel it holds. `Ok(None)` when the decoder wants more input before it can
3366/// hand a frame back, which is not an error. The library speaks interleaved
3367/// little-endian f32 — the same `[-1, 1)` every other reader here emits.
3368///
3369/// The frame count comes back beside the samples because an E-AC-3 frame is not
3370/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2
3371/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the
3372/// channel count and every media position after it out.
3373fn decode_ac3(
3374 decoder: &mut ec_ac3::Ac3Decoder,
3375 bytes: &[u8],
3376) -> crate::Result<Option<(Vec<f32>, u64)>> {
3377 match decoder.decode_frame(bytes) {
3378 Ok(frame) => Ok(Some((
3379 frame.data[0]
3380 .as_chunks::<4>()
3381 .0
3382 .iter()
3383 .map(|s| f32::from_le_bytes(*s))
3384 .collect(),
3385 frame.samples as u64,
3386 ))),
3387 Err(ec_ac3::Error::NeedMore) => Ok(None),
3388 Err(e) => Err(format!("AC-3 decode failed: {e}").into()),
3389 }
3390}
3391
3392/// One source's AAC track, resolved once: the reader plus everything the header
3393/// has to say about it. `stts` is copied out because every other field would
3394/// otherwise keep a borrow alive on the reader the worker needs mutably — a real
3395/// AAC track has one entry, so it is two `u32`s.
3396struct AacTrack {
3397 reader: mp4track::Reader,
3398 stream: u32,
3399 track_id: u32,
3400 sample_count: u32,
3401 sample_rate: u32,
3402 timescale: u32,
3403 /// Encoder delay of *this* file. Sources are joined, priming is not shared.
3404 priming: u64,
3405 total_samples: Option<u64>,
3406 stts: Vec<(u32, u32)>,
3407 /// Channels the decoder emits, from the config: 1 for mono.
3408 layout_channels: usize,
3409 freq_index: u8,
3410 chan_conf: u8,
3411 /// HE-AAC: the stream carries SBR, so [`sample_rate`](Self::sample_rate) is
3412 /// the extension rate and a packet holds twice the core's frames. Such a
3413 /// track decodes but cannot be packet-copied, because the copy writes an
3414 /// AAC-LC config back out from `freq_index`/`chan_conf`.
3415 sbr: bool,
3416 /// A fresh decoder is built from these per segment: seeking mid-stream
3417 /// leaves MDCT and PNS state that belongs to the packets we skipped.
3418 params: AudioCodecParameters,
3419}
3420
3421impl AacTrack {
3422 /// The `stream`-th audio track of `path`, counted in file order over *all*
3423 /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out.
3424 ///
3425 /// Stream 0 is best effort: `Ok(None)` when there is no AAC track there at
3426 /// all, which is a valid silent source (a file whose audio is AC-3 still has
3427 /// a picture worth editing) and, for a standalone audio file, the door
3428 /// through to symphonia ([`Track::open`]). A stream the caller *named* is a
3429 /// promise instead, so out of range or not AAC there is an `Err` rather than
3430 /// silence the caller did not ask for.
3431 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
3432 let reader = mp4track::open(path)?;
3433 let audio = mp4track::audio_tracks(&reader);
3434 let Some(&(track_id, codec_stream)) = audio.get(stream) else {
3435 return match stream {
3436 0 => Ok(None),
3437 n => Err(format!(
3438 "{}: audio stream {n} of {} streams",
3439 path.display(),
3440 audio.len()
3441 )
3442 .into()),
3443 };
3444 };
3445 let stream_id = match codec_stream {
3446 Some(s) if mp4track::codec(&reader, s) == Some(CodecId::Aac) => s,
3447 _ => {
3448 return match stream {
3449 0 => Ok(None),
3450 n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()),
3451 };
3452 }
3453 };
3454 // The config as the file states it, extension frequency and all: the
3455 // decoder needs the SBR part, which a bare rate and channel count do not
3456 // carry.
3457 let asc: Box<[u8]> = mp4track::extradata(&reader, stream_id)
3458 .ok_or_else(|| format!("{}: AAC track has no config", path.display()))?;
3459 // Refuse early with a message instead of failing packet by packet. LC,
3460 // HE-AAC v1 (SBR) and HE-AAC v2 (SBR with PS) all decode through `ec-aac`.
3461 let (mut sbr, ps) = match asc_fields(&asc)?.0 {
3462 AAC_LC => (false, false),
3463 AAC_SBR => (true, false),
3464 AAC_PS => (true, true),
3465 other => {
3466 return Err(format!(
3467 "unsupported AAC profile: audio object type {other} (only AAC-LC, HE-AAC v1 and v2)"
3468 )
3469 .into());
3470 }
3471 };
3472
3473 let mut layout_channels = mp4track::channels(&reader, stream_id);
3474 if layout_channels == 0 {
3475 return Err(format!("{}: AAC config declares no channels", path.display()).into());
3476 }
3477 // The rate `ec-aac` decodes at, which for HE-AAC is the extension rate:
3478 // the container's own rate is the core's, and a timeline counted in it
3479 // would run at half speed against the decoded samples.
3480 let mut sample_rate = aac_output_rate(&asc)?
3481 .ok_or_else(|| format!("{}: AAC config declares no sample rate", path.display()))?;
3482 // Plain LC may carry SBR by implicit signalling: the rate is the decoded
3483 // one, read off the first access units, as for an ADTS or mkv stream.
3484 if aac_may_be_implicit(Some(&asc[..]))?
3485 && let Some(primed) = mp4_aac_prime(path, stream_id, &asc)?
3486 {
3487 sample_rate = primed.sample_rate;
3488 sbr |= primed.implicit;
3489 // The decoder's own width: an implicit PS payload makes a mono core
3490 // stereo, and the container's channel count does not say so.
3491 layout_channels = usize::from(primed.channels);
3492 }
3493 // Explicit HE-AAC v2 is stereo whatever the core's channel count.
3494 if ps {
3495 layout_channels = 2;
3496 }
3497 let timescale = mp4track::timescale(&reader, stream_id);
3498 let priming = priming_samples(
3499 mp4track::media_time(&reader, track_id),
3500 sample_rate,
3501 timescale,
3502 );
3503 let (_, freq_index, chan_conf) = asc_fields(&asc)?;
3504 let duration = mp4track::duration(&reader, stream_id);
3505 let mut params = AudioCodecParameters::new();
3506 params
3507 .for_codec(CODEC_ID_AAC)
3508 .with_sample_rate(sample_rate)
3509 .with_extra_data(asc);
3510 let this = Self {
3511 sample_count: mp4track::sample_count(&reader, stream_id),
3512 stts: mp4track::stts(&reader, stream_id),
3513 total_samples: duration
3514 .and_then(|d| scale(d, sample_rate, timescale))
3515 .map(|d| d.saturating_sub(priming)),
3516 stream: stream_id,
3517 track_id,
3518 sample_rate,
3519 timescale,
3520 priming,
3521 layout_channels,
3522 freq_index,
3523 chan_conf,
3524 sbr,
3525 params,
3526 reader,
3527 };
3528 Ok(Some(this))
3529 }
3530
3531 /// What reaches the timeline: mono, or the stereo everything wider is folded
3532 /// to by [`downmix`] at the decoder's door.
3533 fn channels(&self) -> u16 {
3534 match self.source_channels() {
3535 1 => 1,
3536 _ => 2,
3537 }
3538 }
3539
3540 /// What the decoder emits, which is what the fold reads.
3541 fn source_channels(&self) -> usize {
3542 self.layout_channels.max(1)
3543 }
3544
3545 fn track_params(&self) -> AacTrackParams {
3546 AacTrackParams {
3547 freq_index: self.freq_index,
3548 chan_conf: self.chan_conf,
3549 sample_rate: self.sample_rate,
3550 }
3551 }
3552
3553 /// `secs` on this source's audible timeline into media samples (priming
3554 /// included, so it compares directly against a decoded position).
3555 /// `f64::INFINITY` saturates.
3556 fn media(&self, secs: f64) -> u64 {
3557 ((secs * f64::from(self.sample_rate)).round() as u64).saturating_add(self.priming)
3558 }
3559
3560 /// One `[start, end)` window of this source's seconds, resolved to its own
3561 /// packets and media samples.
3562 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
3563 let media_target = self.media(start_secs);
3564 let target_ts = unscale(media_target, self.sample_rate, self.timescale);
3565 // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
3566 // packet to cancel aliasing, plus one more to warm the decoder up. Their
3567 // output is discarded below, so this only costs decode time. An SBR track
3568 // is walked back further when it is decoded ([`sbr_start_packet`]).
3569 let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL);
3570 Segment {
3571 source: Some(source),
3572 start_id,
3573 start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
3574 media_target,
3575 // An inverted segment is an empty one, never a backwards run.
3576 media_end: self.media(end_secs).max(media_target),
3577 }
3578 }
3579}
3580
3581/// [`packet_run`] for the last segment of a copy. Rounded to nearest, the debt
3582/// that run leaves is never paid: `test_sync.mp4`'s 4.0 s is 172.27 packets, so
3583/// 172 were copied and the sound stopped 6 ms short of its picture. Nothing
3584/// follows the last segment to take the shortfall, so this rounds up instead --
3585/// at most one packet, under a frame, past the picture.
3586fn packet_run_last(err: &mut i64, ideal: i64, available: u32) -> u32 {
3587 let packet = i64::from(SAMPLES_PER_PACKET);
3588 let ideal = ideal.min(i64::from(available) * packet);
3589 let want = (ideal - *err) as f64 / packet as f64;
3590 let n = (want.ceil().max(0.0) as i64).min(i64::from(available)) as u32;
3591 *err += i64::from(n) * packet - ideal;
3592 n
3593}
3594
3595/// How many whole packets to copy for a window of `ideal` samples per channel,
3596/// capped at the `available` packets left in the track.
3597///
3598/// `err` is "samples copied so far minus samples asked for", carried across the
3599/// segment joins: rounding to nearest *against the running debt* keeps the
3600/// cumulative error inside half a packet forever, where independent per-segment
3601/// rounding would random-walk away from sync (charter D1: < 1024 at every join).
3602fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 {
3603 let packet = i64::from(SAMPLES_PER_PACKET);
3604 // Never carry a debt the track cannot pay: a segment running past the end
3605 // would otherwise inflate every later one. (Also tames `f64::INFINITY`,
3606 // which saturates to `i64::MAX` on the cast above.)
3607 let ideal = ideal.min(i64::from(available) * packet);
3608 let want = (ideal - *err) as f64 / packet as f64;
3609 let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32;
3610 *err += i64::from(n) * packet - ideal;
3611 n
3612}
3613
3614/// The order a Matroska file's audio streams are numbered in, as positions into
3615/// `tracks` (which is file order): **stream 0 is the track this project has
3616/// always opened**, and the rest follow in file order behind it.
3617///
3618/// Not file order outright, and the difference is a saved project's sound. A
3619/// remux flags the language it wants heard with `FlagDefault` on whichever
3620/// track it likes -- mkvmerge writes it on the second one all the time -- and
3621/// that flag is what every reader here used to pick with. Numbering by file
3622/// position would have made stream 0 a *different* track on those files, so an
3623/// `.edith` project saved before this would quietly start playing the other
3624/// language. Nothing that already plays may change what it plays.
3625///
3626/// The old pick is not re-derived here, it is *run*: the AC-3 arm asks
3627/// [`MkvAc3Track`] the same question [`Track::open`] asked it (and only of the
3628/// file's first audio track, which is as far as [`crate::demux::MkvAudio`]
3629/// ever looked), and everything else asks symphonia for its default track,
3630/// which is `FlagDefault` where a muxer set one and the first readable track
3631/// where nobody did.
3632pub(crate) fn mkv_stream_order(path: &Path, tracks: &[crate::demux::MkvAudioTrack]) -> Vec<usize> {
3633 // One track is its own order, and it is the common case: no second probe
3634 // for the file that cannot have a second answer.
3635 if tracks.len() < 2 {
3636 return (0..tracks.len()).collect();
3637 }
3638 let head = match tracks.first() {
3639 Some(first) if dolby_track_opens(path, first) => 0,
3640 // A file symphonia will not open at all keeps file order: the open
3641 // itself is where that failure is reported, not the numbering.
3642 _ => SymTrack::open(path)
3643 .ok()
3644 .flatten()
3645 .and_then(|track| {
3646 tracks
3647 .iter()
3648 .position(|entry| entry.number == u64::from(track.track_id))
3649 })
3650 .unwrap_or(0),
3651 };
3652 std::iter::once(head)
3653 .chain((0..tracks.len()).filter(|i| *i != head))
3654 .collect()
3655}
3656
3657/// Whether `entry` is an AC-3, E-AC-3, TrueHD or MLP track one of the Dolby
3658/// decoders reads straight out of the blocks, and that decoder opens. The
3659/// question [`mkv_stream_order`] asks of the file's first track.
3660fn dolby_track_opens(path: &Path, entry: &crate::demux::MkvAudioTrack) -> bool {
3661 match entry.codec.as_str() {
3662 "A_AC3" | "A_EAC3" => matches!(MkvAc3Track::open_track(path, entry.number), Ok(Some(_))),
3663 "A_TRUEHD" | "A_MLP" => {
3664 matches!(MkvTruehdTrack::open_track(path, entry.number), Ok(Some(_)))
3665 }
3666 id if crate::extaudio::is_mkv_dts(id) || crate::extaudio::is_mkv_mpeg_layer(id) => {
3667 matches!(crate::extaudio::ExtFileTrack::open_native(path, entry.number), Ok(Some(_)))
3668 }
3669 _ => false,
3670 }
3671}
3672
3673/// The name a Matroska audio row wears: the container's own codec id, cut down
3674/// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`.
3675///
3676/// The codec id rather than symphonia's short name, because the rows that most
3677/// need naming are exactly the ones it has no decoder for: an Opus or DTS track
3678/// is greyed out with the codec in the reason (`unusable` in the app reads this
3679/// very string), where symphonia would call it "an unsupported format".
3680fn mkv_codec_name(id: &str) -> String {
3681 match id {
3682 "A_AC3" => "ac-3".into(),
3683 "A_EAC3" => "e-ac-3".into(),
3684 "A_MPEG/L3" => "mp3".into(),
3685 "A_MPEG/L1" | "A_MPEG/L2" => codec_display_name(id).to_ascii_lowercase(),
3686 _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(),
3687 }
3688}
3689
3690/// The AAC `audioObjectType`s this reads: LC, HE-AAC v1 (LC with SBR) and
3691/// HE-AAC v2 (SBR with Parametric Stereo).
3692const AAC_LC: u8 = 2;
3693const AAC_SBR: u8 = 5;
3694const AAC_PS: u8 = 29;
3695
3696/// `(profile, freq_index, chan_conf)` out of an `AudioSpecificConfig` (ISO
3697/// 14496-3 §1.6.2.1): the first five bits are the object type, the next four
3698/// the sampling-frequency index, the next four the channel configuration.
3699fn asc_fields(asc: &[u8]) -> crate::Result<(u8, u8, u8)> {
3700 match asc {
3701 [a, b, ..] => Ok((a >> 3, ((a & 0x7) << 1) | (b >> 7), (b >> 3) & 0xf)),
3702 _ => Err("AudioSpecificConfig shorter than its fixed header".into()),
3703 }
3704}
3705
3706/// Encoder delay in samples-per-channel: the edit list's first real entry says
3707/// how far into the media the presentation starts.
3708///
3709/// corner-cut: an explicit `media_time` of 0 is taken at face value (no trim).
3710/// Muxers that write a zero edit list despite a primed stream would leak the
3711/// priming; upgrade path is preferring the codec delay when it disagrees.
3712fn priming_samples(media_time: Option<u64>, sample_rate: u32, timescale: u32) -> u64 {
3713 media_time
3714 .and_then(|t| scale(t, sample_rate, timescale))
3715 .unwrap_or(DEFAULT_PRIMING)
3716}
3717
3718/// `value` from the track timescale into samples-per-channel. `None` on a zero
3719/// timescale, which would be a broken header.
3720fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
3721 let timescale = u64::from(timescale);
3722 (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
3723}
3724
3725/// Inverse of [`scale`]: samples-per-channel back into the track timescale.
3726fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 {
3727 match sample_rate {
3728 0 => 0,
3729 rate => samples * u64::from(timescale) / u64::from(rate),
3730 }
3731}
3732
3733/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll`
3734/// packets, plus that packet's own start time. Inverse of the mp4 crate's
3735/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is
3736/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs.
3737///
3738/// corner-cut: the walk-back is clamped to the start of the containing stts entry
3739/// rather than crossing into the previous one, so a target within `pre_roll`
3740/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
3741/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
3742/// carrying the previous entry's delta through the walk.
3743pub(crate) fn packet_at(
3744 entries: impl IntoIterator<Item = (u32, u32)>,
3745 target_ts: u64,
3746 pre_roll: u32,
3747) -> (u32, u64) {
3748 let mut first_id = 1u32;
3749 let mut elapsed = 0u64;
3750 let mut last = (1u32, 0u64);
3751 for (count, delta) in entries {
3752 let span = u64::from(count) * u64::from(delta);
3753 let index = if target_ts < elapsed + span && delta != 0 {
3754 ((target_ts - elapsed) / u64::from(delta)) as u32
3755 } else {
3756 // Past this entry: remember its last packet in case the target runs
3757 // past the end of the track entirely.
3758 last = (
3759 first_id + count.saturating_sub(1),
3760 elapsed + span.saturating_sub(u64::from(delta)),
3761 );
3762 first_id += count;
3763 elapsed += span;
3764 continue;
3765 };
3766 let index = index - index.min(pre_roll);
3767 return (
3768 first_id + index,
3769 elapsed + u64::from(index) * u64::from(delta),
3770 );
3771 }
3772 last
3773}
3774
3775/// One window of a source to decode, resolved to media samples and packets —
3776/// or, with no source, a stretch of synthesised silence.
3777struct Segment {
3778 /// Index into the worker's tracks; the media positions below are that
3779 /// source's, not the timeline's. `None` for a gap, where only the length
3780 /// (`media_end`) means anything.
3781 source: Option<usize>,
3782 /// First packet to feed the decoder, 1-based; includes the pre-roll.
3783 start_id: u32,
3784 /// Media position of `start_id`'s first frame, in samples-per-channel.
3785 start_pos: u64,
3786 /// Media position of the first frame to emit. Everything decoded before it
3787 /// is pre-roll, priming, or seek overshoot, and gets dropped.
3788 media_target: u64,
3789 /// One past the last frame to emit; `u64::MAX` for "to the end of track".
3790 media_end: u64,
3791}
3792
3793impl Segment {
3794 /// `frames` per channel of silence — a gap in the audio lane.
3795 fn silence(frames: u64) -> Self {
3796 Self {
3797 source: None,
3798 start_id: 0,
3799 start_pos: 0,
3800 media_target: 0,
3801 media_end: frames,
3802 }
3803 }
3804}
3805
3806/// The sample of a mix at `rate` that `secs` of timeline (from the mix's start) ends on:
3807/// the one rounding [`owed_samples`] makes of its running total, so anything that
3808/// has to land on the mix's own samples (an export's warm-up) counts them the same way.
3809pub(crate) fn timeline_sample(secs: f64, rate: u32) -> u64 {
3810 (secs * f64::from(rate)).round() as u64
3811}
3812
3813/// What each segment of a mix owes the timeline in samples, `None` for an
3814/// open-ended window. The sample each segment ends on is the running total of
3815/// the seconds it owes, rounded once against the mix rate, and a segment owes
3816/// the difference of two such roundings. Rounding each segment's own length
3817/// instead drifts: one frame at 59.94 fps is 800.8 samples, so every cut would
3818/// gain or lose up to a fifth of a sample, and a few thousand short cuts add up
3819/// to tens of samples.
3820fn owed_samples(
3821 segs: &[(Option<usize>, f64, f64)],
3822 speeds: &[Option<crate::project::Stretch>],
3823 rate: u32,
3824) -> Vec<Option<u64>> {
3825 let mut total_secs = 0.0f64;
3826 let mut at = 0u64;
3827 segs.iter()
3828 .enumerate()
3829 .map(|(i, &(_, start_secs, end_secs))| {
3830 let secs = speeds
3831 .get(i)
3832 .copied()
3833 .flatten()
3834 .map_or(end_secs - start_secs, |s| s.timeline_secs);
3835 if !secs.is_finite() {
3836 return None;
3837 }
3838 total_secs += secs.max(0.0);
3839 let end = timeline_sample(total_secs, rate);
3840 let owed = end.saturating_sub(at);
3841 at = end;
3842 Some(owed)
3843 })
3844 .collect()
3845}
3846
3847/// One segment's rate conversion: the decoded samples read at the ratio of
3848/// the source's own sample rate to the timeline's, which is a pure rate
3849/// conversion -- the pitch is preserved because the frames are read at the
3850/// ratio of the rates rather than dropped, and 48 kHz onto a 44.1 kHz
3851/// timeline is one resampler, not two. Linear interpolation between the two
3852/// frames a fractional position falls between -- one multiply-add per
3853/// channel, which is nothing beside the decode that produced them, and for a
3854/// 48:44.1 ratio its worst-case image lands ~40 dB down; the alternative is
3855/// a windowed-sinc kernel and a new state machine for a conversion that is
3856/// not the audible risk in this path.
3857///
3858/// It lives across the whole segment: `pos` carries the fraction over a packet
3859/// boundary and `tail` keeps the frame before the buffer, so the interpolation
3860/// at the seam is the same one it would have been inside a buffer. A segment
3861/// starts one clean and drops it at the end, which is what makes a seek a
3862/// reset for free -- exactly as the equalizer's state does.
3863///
3864/// Time is no longer this struct's business: a clip whose own
3865/// [`Speed`](crate::project::Speed) is not real time is re-timed by the
3866/// [`TimeStretch`] behind it in its [`Rate`] chain, which compresses or
3867/// stretches the timeline while keeping every period of the signal its own
3868/// length -- this hands it a pitch-true stream at the timeline's rate and
3869/// that is the whole of the hand-off.
3870///
3871/// `owed` is what the timeline gives the segment, in frames per channel:
3872/// resampling resolves to whole samples and a clip's own window resolves to
3873/// whole *source* frames, so the two miss each other by a sample or two per
3874/// clip. Truncating and padding to what is owed keeps that from accumulating
3875/// into audible drift over a timeline of rate-mismatched cuts -- the picture's
3876/// clip boundaries are exact by construction, and this makes the sound's
3877/// exact too.
3878struct Resample {
3879 /// Source frames per output frame: the ratio of the two sample rates.
3880 step: f64,
3881 /// Where the next output frame reads, relative to the current buffer's
3882 /// first frame. Negative means it reads across the seam, into `tail`.
3883 pos: f64,
3884 /// The last frame of the buffer before this one, one sample per channel.
3885 tail: Vec<f32>,
3886 /// Output frames per channel still to be emitted for this segment, or
3887 /// [`Resample::UNBOUNDED`] for a window with no end of its own -- what
3888 /// [`AudioSession::open_at`] asks for, where the source running out is the
3889 /// end and there is no shortfall to pad.
3890 owed: u64,
3891}
3892
3893impl Resample {
3894 /// "As many as the source has": a segment ending at `f64::INFINITY` owes the
3895 /// timeline nothing it did not decode.
3896 const UNBOUNDED: u64 = u64::MAX;
3897
3898 fn new(step: f64, owed: u64) -> Self {
3899 Self {
3900 step,
3901 pos: 0.,
3902 tail: Vec::new(),
3903 owed,
3904 }
3905 }
3906
3907 /// Rewrites `buf` in place as the frames this rate reads out of it. Never
3908 /// more than is owed, so the segment cannot overrun the room the timeline
3909 /// gave it.
3910 fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
3911 let frames = buf.len() / channels;
3912 if frames == 0 || channels == 0 {
3913 return;
3914 }
3915 let mut out: Vec<f32> = Vec::with_capacity(buf.len());
3916 while self.owed > (out.len() / channels) as u64 {
3917 let left = self.pos.floor();
3918 let right = left as i64 + 1;
3919 if right > frames as i64 - 1 {
3920 break; // the frame it would interpolate towards is not here yet
3921 }
3922 let frac = (self.pos - left) as f32;
3923 let (left, right) = (left as i64, right as usize);
3924 for c in 0..channels {
3925 // Before the buffer means the previous one's last frame; at the
3926 // very first buffer of a segment `pos` is 0, so this cannot be
3927 // asked for an empty tail.
3928 let a = match left < 0 {
3929 true => self.tail.get(c).copied().unwrap_or(0.),
3930 false => buf[left as usize * channels + c],
3931 };
3932 let b = buf[right * channels + c];
3933 out.push(a + (b - a) * frac);
3934 }
3935 self.pos += self.step;
3936 }
3937 self.tail.clear();
3938 self.tail.extend_from_slice(&buf[(frames - 1) * channels..]);
3939 self.pos -= frames as f64;
3940 if self.owed != Self::UNBOUNDED {
3941 self.owed -= (out.len() / channels) as u64;
3942 }
3943 *buf = out;
3944 }
3945
3946 /// The silence the segment still owes when its source ran out before the
3947 /// timeline did -- a rounding frame or two, or a clip whose file is shorter
3948 /// than the edit says. `false` means the consumer went away.
3949 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
3950 if self.owed == Self::UNBOUNDED {
3951 return true; // nothing was promised, so nothing is short
3952 }
3953 while self.owed > 0 {
3954 let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET));
3955 let chunk = AudioChunk {
3956 start_sample: *timeline,
3957 samples: vec![0.0; frames as usize * channels],
3958 };
3959 if tx.send(chunk).is_err() {
3960 return false;
3961 }
3962 *timeline += frames;
3963 self.owed -= frames;
3964 }
3965 true
3966 }
3967}
3968
3969/// One speeded-or-converted segment's whole rate chain: the resample that
3970/// turns the source's own rate into the timeline's, and -- only for a clip
3971/// whose [`Speed`](crate::project::Speed) is not real time -- the stretch
3972/// that changes its *time* without touching its pitch, after the resample
3973/// and before the equalizer sees a sample (the filter's bands are set in the
3974/// frequency a listener hears, and after a stretch that is still the
3975/// frequency the file was written at).
3976///
3977/// Which half owns the segment's promise depends on which halves there are:
3978/// a rate conversion alone is paced by the resample, as it always was, and a
3979/// speeded clip's resample runs unbounded (the ratio is all it is asked for)
3980/// while the stretch lands the timeline's frames exactly.
3981struct Rate {
3982 resample: Resample,
3983 stretch: Option<TimeStretch>,
3984}
3985
3986impl Rate {
3987 fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
3988 self.resample.process(buf, channels);
3989 if let Some(stretch) = self.stretch.as_mut() {
3990 stretch.process(buf, channels);
3991 }
3992 }
3993
3994 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
3995 match self.stretch.as_mut() {
3996 Some(stretch) => stretch.flush(channels, timeline, tx),
3997 None => self.resample.flush(channels, timeline, tx),
3998 }
3999 }
4000}
4001
4002struct Worker {
4003 /// Indexed by [`Segment::source`]; only the sources some segment names are
4004 /// `Some`, the rest were never opened.
4005 tracks: Vec<Option<Track>>,
4006 channels: usize,
4007 segments: Vec<Segment>,
4008 /// One per entry of `segments`, in the same order: the filter that segment's
4009 /// samples pass through on the way out, or `None` for one that plays flat.
4010 /// Beside the segments rather than inside them so the emit path can hold the
4011 /// window rules and the filter memory at once without splitting a borrow.
4012 eqs: Vec<Option<EqState>>,
4013 /// One per entry of `segments` again: that segment's rate chain, or
4014 /// `None` for one at real time on the timeline's own rate -- which is
4015 /// every segment of a project nobody has speeded or rate-mismatched, and
4016 /// the path that emits the decoder's own samples untouched.
4017 speeds: Vec<Option<Rate>>,
4018 /// One per entry of `segments` again: that segment's gain envelope, or
4019 /// `None` for one that plays flat -- [`emit`]'s last effect, run after
4020 /// the rate and the equalizer.
4021 fades: Vec<Option<crate::project::Fade>>,
4022 /// One per entry of `segments` again: the blocks a segment played backwards is
4023 /// decoded in ([`reverse_blocks`]), or `None` for one that plays forwards.
4024 reversed: Vec<Option<Vec<Segment>>>,
4025 /// `start_sample` of the first chunk.
4026 timeline: u64,
4027 tx: SyncSender<AudioChunk>,
4028}
4029
4030/// Sums one worker per lane into one stream (see
4031/// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline
4032/// position and synthesises its own gaps, so the lanes are sample-aligned by
4033/// construction and a mix is an add: no resampling, no positioning, no drift to
4034/// correct. What is emitted at each turn is the shortest block every still-live
4035/// lane can supply, which keeps a slow lane from being outrun and never buffers
4036/// more than the chunks already in flight.
4037///
4038/// A lane whose channel has closed has ended and simply stops being added --
4039/// that is what "shorter lane" means here. The mix ends when all of them have.
4040/// The accumulator is reused across turns; the one allocation per chunk is the
4041/// buffer the channel takes ownership of, and none of this is the RT path (the
4042/// device callback reads the ring the feeder has already filled).
4043/// The gains, ducks and limiter a mix starts from, carried as one value.
4044struct MixState {
4045 gains: Vec<f32>,
4046 ducks: Vec<Vec<Duck>>,
4047 limiter: Option<LimiterState>,
4048}
4049
4050fn mix(
4051 rxs: &[Receiver<AudioChunk>],
4052 channels: usize,
4053 state: MixState,
4054 rate: u32,
4055 controls: Option<&MixControls>,
4056 tx: &SyncSender<AudioChunk>,
4057) {
4058 let MixState { mut gains, mut ducks, mut limiter } = state;
4059 // The version of the mix these gains and this limiter came from; see the
4060 // reload at the head of the loop.
4061 let mut seen = 0;
4062 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
4063 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
4064 // Numbering follows lane 0, whose first chunk says where it starts.
4065 let mut base = 0;
4066 let mut emitted = 0;
4067 let mut out: Vec<f32> = Vec::new();
4068 // Per lane: the block after its gain and its duck, whether the lane had
4069 // samples in this block, and the key a duck reads. Kept between blocks so
4070 // the steady path allocates nothing beyond the chunk it sends.
4071 let mut scaled: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
4072 let mut filled: Vec<bool> = rxs.iter().map(|_| false).collect();
4073 // Per lane, per duck: the key that duck reads this block.
4074 let mut keys: Vec<Vec<Vec<f32>>> = rxs.iter().map(|_| Vec::new()).collect();
4075 // Per lane, one detector per duck, each with the key it reads: a lane ducked
4076 // under several keys is reduced by each of them in turn.
4077 let mut duckers: Vec<Vec<(usize, Ducker)>> = ducks
4078 .iter()
4079 .map(|lane| {
4080 lane.iter()
4081 .map(|d| (d.under, Ducker::new(d, rate)))
4082 .collect()
4083 })
4084 .collect();
4085 loop {
4086 // A mix moved while the stream plays, picked up between two blocks:
4087 // the levels change at a block boundary and nothing else changes at
4088 // all -- no flush, no re-open, no hole. The limiter is *retuned* rather
4089 // than rebuilt, so its delay line keeps running and the sample count
4090 // the master clock is made of does not move ([`LimiterState::retune`]).
4091 if let Some((next, next_ducks, params)) = controls.and_then(|c| c.changed(&mut seen)) {
4092 gains = next;
4093 gains.resize(rxs.len(), 1.0);
4094 ducks = next_ducks;
4095 ducks.resize(rxs.len(), Vec::new());
4096 // A duck that keeps its lane and its key keeps its detector and its
4097 // reduction; a new one starts at rest; one that was taken away is gone.
4098 for (slot, lane_ducks) in duckers.iter_mut().zip(&ducks) {
4099 let mut old = std::mem::take(slot);
4100 *slot = lane_ducks
4101 .iter()
4102 .map(|duck| match old.iter().position(|(under, _)| *under == duck.under) {
4103 Some(at) => {
4104 let (_, mut ducker) = old.swap_remove(at);
4105 ducker.retune(duck, rate);
4106 (duck.under, ducker)
4107 }
4108 None => (duck.under, Ducker::new(duck, rate)),
4109 })
4110 .collect();
4111 }
4112 match limiter.as_mut() {
4113 Some(state) => state.retune(&params),
4114 // First time it has ever been switched in on this stream: the
4115 // one that swallows nothing, for the count's sake.
4116 None if params.is_active() => {
4117 limiter = Some(LimiterState::engaged(&params, rate, channels));
4118 }
4119 None => {}
4120 }
4121 }
4122 for (i, rx) in rxs.iter().enumerate() {
4123 while live[i] && pending[i].is_empty() {
4124 match rx.recv() {
4125 Ok(chunk) => {
4126 if i == 0 && emitted == 0 {
4127 base = chunk.start_sample;
4128 }
4129 pending[i] = chunk.samples;
4130 }
4131 Err(_) => live[i] = false,
4132 }
4133 }
4134 }
4135 // The block every lane still playing can cover; `None` once they are all
4136 // done, which is the only way out of this loop besides a gone consumer.
4137 let Some(frames) = pending
4138 .iter()
4139 .filter(|p| !p.is_empty())
4140 .map(|p| p.len() / channels)
4141 .min()
4142 .filter(|&f| f > 0)
4143 else {
4144 // The mix has run out: the limiter still holds the stream's last frames, which go
4145 // out limited rather than being dropped (the export pads a shortfall with silence,
4146 // and that cut reads as an overshoot).
4147 if let Some(limiter) = limiter.as_mut() {
4148 let tail = limiter.drain();
4149 if !tail.is_empty() {
4150 let samples = tail.iter().map(|s| s.clamp(-1.0, 1.0)).collect();
4151 let _ = tx.send(AudioChunk { start_sample: base + emitted, samples });
4152 }
4153 }
4154 return;
4155 };
4156 let block = frames * channels;
4157 // Each lane's own volume, applied on its way into the sum: this is the
4158 // one place every lane's samples pass through, so a lane that is turned
4159 // down is turned down in an export exactly as it is in the room. Unity
4160 // is a multiply by 1.0, which f32 leaves alone.
4161 for (i, lane) in pending.iter_mut().enumerate() {
4162 filled[i] = !lane.is_empty();
4163 if !filled[i] {
4164 continue;
4165 }
4166 let gain = gains.get(i).copied().unwrap_or(1.0);
4167 let dst = &mut scaled[i];
4168 dst.clear();
4169 dst.extend(lane.drain(..block).map(|sample| sample * gain));
4170 }
4171 // Auto-ducking. A ducked lane is reduced by each of its keys' signals as
4172 // they stood after gain and before any duck, so no duck keys off another
4173 // duck's output: every key is read first, then the ducks are applied in
4174 // turn. A key that had no samples this block is silence, and lets its
4175 // duck go. A duck naming its own lane, or none, does nothing.
4176 for i in 0..rxs.len() {
4177 keys[i].resize_with(duckers[i].len(), Vec::new);
4178 for (j, (under, _)) in duckers[i].iter().enumerate() {
4179 let under = *under;
4180 if under == i || under >= rxs.len() {
4181 continue;
4182 }
4183 let key = &mut keys[i][j];
4184 key.clear();
4185 if filled[under] {
4186 key.extend_from_slice(&scaled[under]);
4187 } else {
4188 key.resize(block, 0.0);
4189 }
4190 }
4191 }
4192 for i in 0..rxs.len() {
4193 if !filled[i] {
4194 continue;
4195 }
4196 for (j, (under, ducker)) in duckers[i].iter_mut().enumerate() {
4197 if *under == i || *under >= rxs.len() {
4198 continue;
4199 }
4200 ducker.process(&keys[i][j], &mut scaled[i], channels);
4201 }
4202 }
4203 out.clear();
4204 out.resize(block, 0.0);
4205 for (i, lane) in scaled.iter().enumerate() {
4206 if !filled[i] {
4207 continue;
4208 }
4209 let mut peak = 0.0f32;
4210 for (sum, &level) in out.iter_mut().zip(lane) {
4211 peak = peak.max(level.abs());
4212 *sum += level;
4213 }
4214 // Read by the level meters ([`MixControls::take_lane_peaks`]); the
4215 // sum above is the same arithmetic it always was.
4216 if let Some(controls) = controls {
4217 controls.note_lane_peak(i, peak);
4218 }
4219 }
4220 // ...and the master limiter over the sum, before the clamp: what the
4221 // clamp used to catch by squaring it off is held under the ceiling
4222 // here instead ([`crate::limiter`]). Off, this is not even a branch
4223 // per sample.
4224 if let Some(limiter) = limiter.as_mut() {
4225 limiter.process(&mut out);
4226 }
4227 let frames = out.len() / channels;
4228 if frames == 0 {
4229 continue; // the limiter's delay line is still filling
4230 }
4231 let chunk = AudioChunk {
4232 start_sample: base + emitted,
4233 // Clamped, not wrapped: two lanes at full scale are what a mix has
4234 // to survive, and the device takes `[-1, 1]`.
4235 samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(),
4236 };
4237 if tx.send(chunk).is_err() {
4238 return; // caller moved on
4239 }
4240 emitted += frames as u64;
4241 }
4242}
4243
4244fn run(mut w: Worker) {
4245 let channels = w.channels;
4246 // Chunk numbering is continuous across every join, source ones included.
4247 let mut timeline = w.timeline;
4248 let segments = std::mem::take(&mut w.segments);
4249 let mut eqs = std::mem::take(&mut w.eqs);
4250 // A short list is "flat from here on" (`open_multi_streams_eq`), which this
4251 // pads out so the zip below still walks every segment.
4252 eqs.resize_with(segments.len(), || None);
4253 let mut speeds = std::mem::take(&mut w.speeds);
4254 // ...and a short rate list is "real time from here on", for the same reason.
4255 speeds.resize_with(segments.len(), || None);
4256 let mut fades = std::mem::take(&mut w.fades);
4257 // ...and a short fade list is "flat from here on", the same rule again.
4258 fades.resize_with(segments.len(), || None);
4259 let mut reversed = std::mem::take(&mut w.reversed);
4260 // ...and a short reversal list is "forwards from here on".
4261 reversed.resize_with(segments.len(), || None);
4262
4263 for ((((seg, eq), speed), fade), backwards) in segments
4264 .iter()
4265 .zip(eqs.iter_mut())
4266 .zip(speeds.iter_mut())
4267 .zip(fades.iter_mut())
4268 .zip(reversed.iter())
4269 {
4270 let Some(source) = seg.source else {
4271 // A gap: hand the device real silence rather than nothing at all,
4272 // in the same packet-sized chunks decoding produces, so `fed` and
4273 // the master clock keep counting straight through the hole.
4274 let mut left = seg.media_end;
4275 while left > 0 {
4276 let frames = left.min(u64::from(SAMPLES_PER_PACKET));
4277 let chunk = AudioChunk {
4278 start_sample: timeline,
4279 samples: vec![0.0; frames as usize * channels],
4280 };
4281 if w.tx.send(chunk).is_err() {
4282 return; // caller moved on
4283 }
4284 timeline += frames;
4285 left -= frames;
4286 }
4287 continue;
4288 };
4289 let Some(track) = w.tracks[source].as_mut() else {
4290 continue; // opener fills every named source; nothing to decode
4291 };
4292 let chain = Chain {
4293 eq: eq.as_mut(),
4294 speed: &mut *speed,
4295 fade: &mut *fade,
4296 channels,
4297 timeline: &mut timeline,
4298 tx: &w.tx,
4299 };
4300 let more = match backwards {
4301 Some(blocks) => run_backwards(track, blocks, chain),
4302 None => run_segment(track, seg, chain),
4303 };
4304 if !(more && settle(speed, channels, &mut timeline, &w.tx)) {
4305 return; // consumer went away
4306 }
4307 }
4308}
4309
4310/// One segment of one source, decoded forwards through `chain`. `false` means the
4311/// consumer went away, or the decoder could not be built and the rest of the mix
4312/// is not worth decoding.
4313fn run_segment(track: &mut Track, seg: &Segment, chain: Chain<'_>) -> bool {
4314 let Chain {
4315 mut eq,
4316 speed,
4317 fade,
4318 channels,
4319 timeline,
4320 tx,
4321 } = chain;
4322 let track = match track {
4323 Track::Sym(track) => return run_sym(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4324 Track::Ts(track) => return run_ts(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4325 Track::Truehd(track) => {
4326 return run_mkv_truehd(track, seg, Chain { eq, speed, fade, channels, timeline, tx });
4327 }
4328 Track::Ext(track) => return run_ext(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4329 Track::Mkv(track) => return run_mkv_ac3(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4330 Track::Ac3(track) => return run_ac3(track, seg, Chain { eq, speed, fade, channels, timeline, tx }),
4331 Track::Aac(track) => track,
4332 };
4333 let mut interleaved = Vec::new();
4334 // An SBR track starts on a packet that carries its own header, which
4335 // may be ahead of the segment's pre-roll; its position is that packet's.
4336 let (start_id, mut pos) = if track.sbr {
4337 let id = sbr_start_packet(track, seg.start_id);
4338 let ts = packet_start_ts(&track.stts, id);
4339 (id, scale(ts, track.sample_rate, track.timescale).unwrap_or(0))
4340 } else {
4341 (seg.start_id, seg.start_pos)
4342 };
4343 let mut decoder = match aac_decoder(&track.params, track.source_channels()) {
4344 Ok(decoder) => decoder,
4345 Err(e) => {
4346 eprintln!("audio decoder init failed: {e}");
4347 return false;
4348 }
4349 };
4350
4351 for id in start_id..=track.sample_count {
4352 if pos >= seg.media_end {
4353 break; // segment done, on to the next one
4354 }
4355 let sample = match mp4track::sample(&mut track.reader, track.stream, id) {
4356 Ok(Some(sample)) => sample,
4357 Ok(None) => break,
4358 Err(e) => {
4359 eprintln!("audio demux error at sample {id}: {e}");
4360 break;
4361 }
4362 };
4363 let packet = Packet::new(
4364 track.track_id,
4365 units::Timestamp::new(sample.dts.unwrap_or(0)),
4366 units::Duration::new(u64::from(sample.duration.unwrap_or(0).max(0) as u32)),
4367 &sample.data[..],
4368 );
4369 if let Err(e) = decoder.decode(&packet, &mut interleaved) {
4370 eprintln!("audio decode error at sample {id}: {e}");
4371 break;
4372 }
4373 // decoder.decode already folded to track.channels(); widen the mono
4374 // case up to the timeline's own width before dividing by it below.
4375 widen(&mut interleaved, usize::from(track.channels()), channels);
4376 let next = pos + (interleaved.len() / channels) as u64;
4377 if !emit(
4378 &mut interleaved,
4379 seg,
4380 Chain {
4381 eq: eq.as_deref_mut(),
4382 speed: &mut *speed,
4383 fade: &mut *fade,
4384 channels,
4385 timeline: &mut *timeline,
4386 tx,
4387 },
4388 pos,
4389 next,
4390 ) {
4391 return false; // consumer went away
4392 }
4393 pos = next;
4394 }
4395 true
4396}
4397
4398/// How long one block of a reversed segment is, in seconds of the source: the most
4399/// that is ever held decoded at once, whatever the clip's length -- a stereo pair at
4400/// 48 kHz is 750 KB of it.
4401const REVERSE_BLOCK_SECS: u64 = 2;
4402
4403/// The blocks a reversed `seg` (the window `[media_target, media_end)` of `track`,
4404/// opened for the seconds from `start_secs`) is decoded in, in the order they are
4405/// *played*: the last stretch of the window first. Each is a segment of its own,
4406/// resolved against the packet table like any other, and trimmed to the exact
4407/// samples it owns so the blocks tile the window with nothing lost between.
4408fn reverse_blocks(track: &Track, source: usize, start_secs: f64, seg: &Segment) -> Vec<Segment> {
4409 let rate = u64::from(track.sample_rate().max(1));
4410 let step = REVERSE_BLOCK_SECS * rate;
4411 let mut blocks = Vec::new();
4412 let mut end = seg.media_end;
4413 while end > seg.media_target {
4414 let from = end.saturating_sub(step).max(seg.media_target);
4415 let (a, b) = (from - seg.media_target, end - seg.media_target);
4416 let mut block = track.segment(
4417 source,
4418 start_secs + a as f64 / rate as f64,
4419 start_secs + b as f64 / rate as f64,
4420 );
4421 // The seconds only find the packets; the samples are exact.
4422 block.media_target = from;
4423 block.media_end = end;
4424 blocks.push(block);
4425 end = from;
4426 }
4427 blocks
4428}
4429
4430/// A reversed segment: each block decoded forwards into memory, turned end for end
4431/// and handed to the rate, the equalizer and the fade as if it were the decoder's
4432/// own -- so a reversed clip is filtered, speeded and faded exactly as a forward one,
4433/// from the sound's last sample down. `false` as for [`run_segment`].
4434fn run_backwards(track: &mut Track, blocks: &[Segment], chain: Chain<'_>) -> bool {
4435 let Chain {
4436 eq,
4437 speed,
4438 fade,
4439 channels,
4440 timeline,
4441 tx,
4442 } = chain;
4443 // A block's chunks are collected here on the way out of the decoder: a block is
4444 // seconds of packets, never more than this many.
4445 let (hold, held) = sync_channel(1 << 14);
4446 let mut eq = eq;
4447 for block in blocks {
4448 let mut at = 0u64;
4449 let mut none = None;
4450 let mut flat = None;
4451 let ok = run_segment(
4452 track,
4453 block,
4454 Chain {
4455 eq: None,
4456 speed: &mut none,
4457 fade: &mut flat,
4458 channels,
4459 timeline: &mut at,
4460 tx: &hold,
4461 },
4462 );
4463 let mut samples: Vec<f32> = Vec::new();
4464 while let Ok(chunk) = held.try_recv() {
4465 samples.extend_from_slice(&chunk.samples);
4466 }
4467 // Frame order reversed, the channels of a frame left as they are.
4468 let frames = samples.len() / channels.max(1);
4469 for f in 0..frames / 2 {
4470 let (a, b) = (f * channels, (frames - 1 - f) * channels);
4471 for c in 0..channels {
4472 samples.swap(a + c, b + c);
4473 }
4474 }
4475 if !samples.is_empty()
4476 && !deliver(
4477 &mut samples,
4478 Chain {
4479 eq: eq.as_deref_mut(),
4480 speed: &mut *speed,
4481 fade: &mut *fade,
4482 channels,
4483 timeline: &mut *timeline,
4484 tx,
4485 },
4486 )
4487 {
4488 return false;
4489 }
4490 if !ok {
4491 return false;
4492 }
4493 }
4494 true
4495}
4496
4497/// Pays out whatever silence a speeded segment still owes the timeline (see
4498/// [`Resample::flush`]). Nothing at all at real time, where a segment owes the
4499/// timeline only the samples it decoded.
4500fn settle(
4501 speed: &mut Option<Rate>,
4502 channels: usize,
4503 timeline: &mut u64,
4504 tx: &SyncSender<AudioChunk>,
4505) -> bool {
4506 match speed {
4507 Some(speed) => speed.flush(channels, timeline, tx),
4508 None => true,
4509 }
4510}
4511
4512/// Trims one decoded buffer to the segment window and sends what survives.
4513/// `pos` is the media position of its first frame and `next` of the one after
4514/// it; both readers hand the same thing here, which is why the window rules
4515/// live in one place. `false` means the consumer went away.
4516///
4517/// Everything before the target is encoder priming and/or decoder pre-roll, not
4518/// audio the caller asked for: it is dropped, splitting the buffer that
4519/// straddles the target. The tail past the segment end goes too — on a short
4520/// segment that is this same buffer, trimmed at both ends.
4521///
4522/// The segment's equalizer runs here, on the trimmed buffer and nowhere else:
4523/// this is the one place both readers hand their samples over, so playback and
4524/// an audio export get the same filtered stream by construction rather than by
4525/// two call sites agreeing. Trimmed first, so the pre-roll a listener never
4526/// hears cannot ring the filter either. Nothing is allocated -- the device
4527/// callback is two hand-offs downstream of here in any case.
4528/// What one segment writes through: its equalizer, rate and fade, each carried
4529/// from one decoded buffer to the next, and the timeline and channel count the
4530/// samples land on. Passed whole so `emit` and the per-codec loops share one
4531/// shape instead of threading the same ten values through every call.
4532struct Chain<'a> {
4533 eq: Option<&'a mut EqState>,
4534 speed: &'a mut Option<Rate>,
4535 fade: &'a mut Option<crate::project::Fade>,
4536 channels: usize,
4537 timeline: &'a mut u64,
4538 tx: &'a SyncSender<AudioChunk>,
4539}
4540
4541fn emit(interleaved: &mut Vec<f32>, seg: &Segment, chain: Chain<'_>, pos: u64, next: u64) -> bool {
4542 let Chain {
4543 eq,
4544 speed,
4545 fade,
4546 channels,
4547 timeline,
4548 tx,
4549 } = chain;
4550 if next <= seg.media_target {
4551 return true;
4552 }
4553 let mut pos = pos;
4554 if pos < seg.media_target {
4555 interleaved.drain(..(seg.media_target - pos) as usize * channels);
4556 pos = seg.media_target;
4557 }
4558 if next > seg.media_end {
4559 interleaved.truncate((seg.media_end - pos) as usize * channels);
4560 }
4561 if interleaved.is_empty() {
4562 return true; // nothing left of it; the loop head ends the segment
4563 }
4564 deliver(
4565 interleaved,
4566 Chain {
4567 eq,
4568 speed,
4569 fade,
4570 channels,
4571 timeline,
4572 tx,
4573 },
4574 )
4575}
4576
4577/// Sends the samples of one decoded, window-trimmed buffer on their way: through the
4578/// rate, the equalizer and the fade, in that order, and out as the next chunk.
4579/// `false` means the consumer went away.
4580fn deliver(interleaved: &mut Vec<f32>, chain: Chain<'_>) -> bool {
4581 let Chain {
4582 eq,
4583 speed,
4584 fade,
4585 channels,
4586 timeline,
4587 tx,
4588 } = chain;
4589 // The rate first, the filter second: what the equalizer's bands are set in
4590 // is the frequency a listener hears, and after a resample that is not the
4591 // frequency the file was written at. A segment at real time has no
4592 // resampler at all and reaches the filter with the decoder's own samples.
4593 if let Some(speed) = speed {
4594 speed.process(interleaved, channels);
4595 if interleaved.is_empty() {
4596 return true; // this buffer resolved to no output frame of its own
4597 }
4598 }
4599 if let Some(eq) = eq {
4600 eq.process(interleaved);
4601 }
4602 // The fade last, on the same output-rate samples the mix will hear: its
4603 // frame counts are timeline frames ([`crate::project::Clip::fade_in`]),
4604 // which is what a resample has already turned these into. The state
4605 // walks forward with the segment across as many buffers as decoding
4606 // takes, exactly as the equalizer's does.
4607 if let Some(fade) = fade {
4608 fade.apply(interleaved, channels);
4609 fade.elapsed = fade
4610 .elapsed
4611 .saturating_add((interleaved.len() / channels) as u32);
4612 }
4613 let chunk = AudioChunk {
4614 start_sample: *timeline,
4615 samples: std::mem::take(interleaved),
4616 };
4617 *timeline += (chunk.samples.len() / channels) as u64;
4618 tx.send(chunk).is_ok()
4619}
4620
4621/// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids
4622/// come out of the same mp4 tables, the window rules are [`emit`]'s as always,
4623/// and what reaches the mixer is already the stereo downmix. `false` means the
4624/// consumer went away.
4625fn run_ac3(track: &mut Ac3Track, seg: &Segment, chain: Chain<'_>) -> bool {
4626 let Chain {
4627 mut eq,
4628 speed,
4629 fade,
4630 channels,
4631 timeline,
4632 tx,
4633 } = chain;
4634 let mut decoder = match ac3_decoder(track.requested) {
4635 Ok(decoder) => decoder,
4636 Err(e) => {
4637 eprintln!("audio decoder init failed: {e}");
4638 return true;
4639 }
4640 };
4641 let mut pos = seg.start_pos;
4642 for id in seg.start_id..=track.sample_count {
4643 if pos >= seg.media_end {
4644 return true; // segment done, on to the next one
4645 }
4646 let sample = match mp4track::sample(&mut track.reader, track.stream, id) {
4647 Ok(Some(sample)) => sample,
4648 Ok(None) => return true,
4649 Err(e) => {
4650 eprintln!("audio demux error at sample {id}: {e}");
4651 return true;
4652 }
4653 };
4654 let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.data) {
4655 Ok(Some(decoded)) => decoded,
4656 Ok(None) => continue, // the decoder wants another frame first
4657 Err(e) => {
4658 eprintln!("audio decode error at sample {id}: {e}");
4659 return true;
4660 }
4661 };
4662 // §7.8.2 has already folded anything wider than a pair; only a mono
4663 // track arrives here in its own width, and [`widen`]'s is the last word.
4664 widen(&mut interleaved, usize::from(track.channels), channels);
4665 let next = pos + samples;
4666 if !emit(
4667 &mut interleaved,
4668 seg,
4669 Chain {
4670 eq: eq.as_deref_mut(),
4671 speed: &mut *speed,
4672 fade: &mut *fade,
4673 channels,
4674 timeline: &mut *timeline,
4675 tx,
4676 },
4677 pos,
4678 next,
4679 ) {
4680 return false;
4681 }
4682 pos = next;
4683 }
4684 true
4685}
4686
4687/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks
4688/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the
4689/// stereo downmix are the same ones; only where a packet comes from differs.
4690/// `false` means the consumer went away.
4691fn run_mkv_ac3(track: &mut MkvAc3Track, seg: &Segment, chain: Chain<'_>) -> bool {
4692 let Chain {
4693 mut eq,
4694 speed,
4695 fade,
4696 channels,
4697 timeline,
4698 tx,
4699 } = chain;
4700 let mut decoder = match ac3_decoder(track.requested) {
4701 Ok(decoder) => decoder,
4702 Err(e) => {
4703 eprintln!("audio decoder init failed: {e}");
4704 return true;
4705 }
4706 };
4707 let mut pos = seg.start_pos;
4708 for id in seg.start_id as usize.. {
4709 if pos >= seg.media_end {
4710 return true; // segment done, on to the next one
4711 }
4712 let block = match track.mkv.frame(id) {
4713 Ok(Some(bytes)) => bytes,
4714 Ok(None) => return true, // end of the track
4715 Err(e) => {
4716 eprintln!("audio demux error at block {id}: {e}");
4717 return true;
4718 }
4719 };
4720 let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) {
4721 Ok(Some(decoded)) => decoded,
4722 Ok(None) => continue, // the decoder wants another frame first
4723 Err(e) => {
4724 eprintln!("audio decode error at block {id}: {e}");
4725 return true;
4726 }
4727 };
4728 // ...and widened here, as on the mp4 side.
4729 widen(&mut interleaved, usize::from(track.channels), channels);
4730 let next = pos + samples;
4731 if !emit(
4732 &mut interleaved,
4733 seg,
4734 Chain {
4735 eq: eq.as_deref_mut(),
4736 speed: &mut *speed,
4737 fade: &mut *fade,
4738 channels,
4739 timeline: &mut *timeline,
4740 tx,
4741 },
4742 pos,
4743 next,
4744 ) {
4745 return false;
4746 }
4747 pos = next;
4748 }
4749 true
4750}
4751
4752/// The Matroska TrueHD / MLP track: every block is one access unit, decoded by
4753/// `ec-truehd`, which is bit-exact against ffmpeg. The decoder hands back the
4754/// highest presentation the unit carries (7.1 where the stream has it, else 5.1,
4755/// else stereo), and [`downmix`] folds that to the pair the timeline carries, as
4756/// it does for every multichannel source. An Atmos track's 4th substream is
4757/// refused by `ec-truehd` by name, and so is the open.
4758struct MkvTruehdTrack {
4759 mkv: crate::demux::MkvAudio,
4760 sample_rate: u32,
4761 /// Samples per channel in every access unit. Constant across a stream, so a
4762 /// block's first sample is `id * au_samples` exactly, with no rounding from
4763 /// Matroska's millisecond timestamps.
4764 au_samples: u64,
4765 /// What the decoder emits: 2, 6 or 8 channels, before [`downmix`].
4766 source_channels: usize,
4767 /// What reaches the timeline: the source's width, or a pair for anything wider.
4768 channels: u16,
4769 total_samples: Option<u64>,
4770}
4771
4772/// Blocks scanned for the first decodable access unit when a track is opened. A
4773/// decoder emits nothing until it has seen a restart header, which a stream
4774/// carries every few access units.
4775const TRUEHD_PROBE_BLOCKS: usize = 256;
4776
4777/// Blocks decoded before a seek target so the decoder has seen its restart
4778/// header by the time the window starts (about 0.8 s at 48 kHz).
4779const TRUEHD_PRE_ROLL: u32 = 40;
4780
4781impl MkvTruehdTrack {
4782 /// `Ok(None)` when the file's first audio track is not TrueHD or MLP.
4783 fn open(path: &Path) -> crate::Result<Option<Self>> {
4784 Self::from_blocks(crate::demux::MkvAudio::open(path)?)
4785 }
4786
4787 /// [`open`](Self::open) on one named track ([`crate::demux::MkvAudioTrack::number`]).
4788 fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> {
4789 Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?)
4790 }
4791
4792 fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> {
4793 let Some(mut mkv) = mkv else {
4794 return Ok(None);
4795 };
4796 if !matches!(mkv.codec, "truehd" | "mlp") {
4797 return Ok(None);
4798 }
4799 // Rate, layout and access-unit length all come out of the stream's own
4800 // major sync, as the decoder reads them: the first frame it can emit says
4801 // them. A first block the decoder cannot yet decode is not an error.
4802 let mut decoder = ec_truehd::TrueHdDecoder::new();
4803 let mut first = None;
4804 for id in 0..mkv.blocks().min(TRUEHD_PROBE_BLOCKS) {
4805 let Some(bytes) = mkv.frame(id)? else {
4806 break;
4807 };
4808 match decoder.decode_access_unit(&bytes) {
4809 Ok(Some(frame)) => {
4810 first = Some(frame);
4811 break;
4812 }
4813 Ok(None) | Err(ec_core::Error::NeedMore) => {}
4814 Err(e) => return Err(format!("TrueHD: {e}").into()),
4815 }
4816 }
4817 let frame = first.ok_or(
4818 "the TrueHD track of this Matroska file has no decodable access unit in its first blocks",
4819 )?;
4820 if frame.rate == 0 || frame.samples == 0 {
4821 return Err("the TrueHD track of this Matroska file states no sample rate".into());
4822 }
4823 let source_channels = frame.layout.channel_count();
4824 let au_samples = frame.samples as u64;
4825 Ok(Some(Self {
4826 sample_rate: frame.rate,
4827 au_samples,
4828 source_channels,
4829 channels: source_channels.min(2) as u16,
4830 total_samples: Some(mkv.blocks() as u64 * au_samples),
4831 mkv,
4832 }))
4833 }
4834
4835 /// `secs` on this source's timeline into media samples. No priming: a
4836 /// Matroska file carries no edit list and TrueHD no encoder delay.
4837 fn media(&self, secs: f64) -> u64 {
4838 (secs.max(0.0) * f64::from(self.sample_rate)).round() as u64
4839 }
4840
4841 /// One `[start, end)` window, resolved to blocks and media samples. The
4842 /// decoder is started [`TRUEHD_PRE_ROLL`] blocks early; what it decodes before
4843 /// the target is dropped by [`emit`].
4844 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
4845 let media_target = self.media(start_secs);
4846 let start_id = self.mkv.block_at(start_secs, TRUEHD_PRE_ROLL as usize);
4847 Segment {
4848 source: Some(source),
4849 start_id: start_id as u32,
4850 start_pos: start_id as u64 * self.au_samples,
4851 media_target,
4852 media_end: self.media(end_secs).max(media_target),
4853 }
4854 }
4855}
4856
4857/// One segment of a Matroska TrueHD / MLP track: [`run_mkv_ac3`]'s shape, with
4858/// the access unit's position computed from its block index rather than summed,
4859/// so a decoded unit that is not emitted (the decoder still warming up) cannot
4860/// shift every sample after it.
4861fn run_mkv_truehd(track: &mut MkvTruehdTrack, seg: &Segment, chain: Chain<'_>) -> bool {
4862 let Chain {
4863 mut eq,
4864 speed,
4865 fade,
4866 channels,
4867 timeline,
4868 tx,
4869 } = chain;
4870 let mut decoder = ec_truehd::TrueHdDecoder::new();
4871 for id in seg.start_id as usize.. {
4872 let pos = id as u64 * track.au_samples;
4873 if pos >= seg.media_end {
4874 return true; // segment done, on to the next one
4875 }
4876 let block = match track.mkv.frame(id) {
4877 Ok(Some(bytes)) => bytes,
4878 Ok(None) => return true, // end of the track
4879 Err(e) => {
4880 eprintln!("audio demux error at block {id}: {e}");
4881 return true;
4882 }
4883 };
4884 let frame = match decoder.decode_access_unit(&block) {
4885 Ok(Some(frame)) => frame,
4886 // No output yet (no restart header seen): nothing to emit for this unit.
4887 Ok(None) | Err(ec_core::Error::NeedMore) => continue,
4888 Err(e) => {
4889 eprintln!("audio decode error at block {id}: {e}");
4890 return true;
4891 }
4892 };
4893 let mut interleaved = truehd_f32(&frame);
4894 downmix(&mut interleaved, track.source_channels);
4895 widen(&mut interleaved, usize::from(track.channels), channels);
4896 let next = pos + frame.samples as u64;
4897 if !emit(
4898 &mut interleaved,
4899 seg,
4900 Chain {
4901 eq: eq.as_deref_mut(),
4902 speed,
4903 fade,
4904 channels,
4905 timeline,
4906 tx,
4907 },
4908 pos,
4909 next,
4910 ) {
4911 return false;
4912 }
4913 }
4914 true
4915}
4916
4917/// One segment of a DTS / ADPCM / A-law / mu-law / AMR track read by `ec-probe`
4918/// ([`crate::extaudio`]): the reader is seeked a pre-roll ahead of the window, a
4919/// fresh decoder runs from there, and each packet lands at the media position its
4920/// timestamp states (summed from the last one when it states none). `false` means
4921/// the consumer went away.
4922fn run_ext(track: &mut crate::extaudio::ExtFileTrack, seg: &Segment, chain: Chain<'_>) -> bool {
4923 let Chain {
4924 mut eq,
4925 speed,
4926 fade,
4927 channels,
4928 timeline,
4929 tx,
4930 } = chain;
4931 let mut decoder = match track.decoder() {
4932 Ok(decoder) => decoder,
4933 Err(e) => {
4934 eprintln!("audio decoder init failed: {e}");
4935 return true;
4936 }
4937 };
4938 let rate = f64::from(track.sample_rate.max(1));
4939 if let Err(e) = track.seek(seg.media_target as f64 / rate) {
4940 eprintln!("audio seek error: {e}");
4941 return true;
4942 }
4943 let mut next_pos = 0u64;
4944 loop {
4945 let (stated, block) = match track.next_packet() {
4946 Ok(Some(p)) => p,
4947 Ok(None) => return true, // end of the track
4948 Err(e) => {
4949 eprintln!("audio demux error: {e}");
4950 return true;
4951 }
4952 };
4953 let pos = stated.unwrap_or(next_pos);
4954 if pos >= seg.media_end {
4955 return true; // segment done, on to the next one
4956 }
4957 let (mut interleaved, source_channels) = match decoder.decode(&block) {
4958 Ok(Some(decoded)) => decoded,
4959 Ok(None) => {
4960 next_pos = pos;
4961 continue;
4962 }
4963 Err(e) => {
4964 eprintln!("audio decode error: {e}");
4965 return true;
4966 }
4967 };
4968 let frames = (interleaved.len() / source_channels.max(1)) as u64;
4969 downmix(&mut interleaved, source_channels);
4970 widen(&mut interleaved, usize::from(track.channels()), channels);
4971 let next = pos + frames;
4972 next_pos = next;
4973 if !emit(
4974 &mut interleaved,
4975 seg,
4976 Chain {
4977 eq: eq.as_deref_mut(),
4978 speed,
4979 fade,
4980 channels,
4981 timeline,
4982 tx,
4983 },
4984 pos,
4985 next,
4986 ) {
4987 return false;
4988 }
4989 }
4990}
4991
4992/// The decoder's S32 output as f32 in `[-1, 1)`, interleaved. Its samples carry
4993/// 24 significant bits (left-justified in 32), so both the widening to f32 and
4994/// the division by 2^31 are exact.
4995pub(crate) fn truehd_f32(frame: &ec_core::frame::AudioFrame) -> Vec<f32> {
4996 frame
4997 .data
4998 .first()
4999 .into_iter()
5000 .flat_map(|plane| plane.as_chunks::<4>().0.iter())
5001 .map(|s| i32::from_ne_bytes(*s) as f32 / 2_147_483_648.0)
5002 .collect()
5003}
5004
5005/// One segment of a standalone audio file: seek the reader to just before the
5006/// window, then decode forward until the window is filled.
5007///
5008/// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the
5009/// target is thrown away by [`emit`], which is what gives a codec with decoder
5010/// state — mp3's bit reservoir above all — something to warm up on, exactly as
5011/// the AAC path's two-packet pre-roll does. A reader that cannot seek at all
5012/// simply decodes from wherever it is; the window rules still hold, it is only
5013/// slower. `false` means the consumer went away.
5014/// One segment of a transport stream's sound: the track's own demuxer is sought a
5015/// pre-roll ahead of the window, a fresh decoder runs from there, and each packet lands at
5016/// the media position its timestamp states (the sound that starts after the picture leaves
5017/// silence in front of it; sound before the picture is trimmed away). `false` means the
5018/// consumer went away.
5019fn run_ts(track: &mut crate::demux::ts::TsAudio, seg: &Segment, chain: Chain<'_>) -> bool {
5020 let Chain {
5021 mut eq,
5022 speed,
5023 fade,
5024 channels,
5025 timeline,
5026 tx,
5027 } = chain;
5028 let rate = i128::from(track.sample_rate);
5029 let mut decoder = match track.decoder() {
5030 Ok(decoder) => decoder,
5031 Err(e) => {
5032 eprintln!("audio decoder init failed: {e}");
5033 return true;
5034 }
5035 };
5036 let target_secs = seg.media_target as f64 / track.sample_rate as f64;
5037 if let Err(e) = track.seek((target_secs - track.pre_roll_secs()).max(0.0)) {
5038 eprintln!("audio demux seek failed: {e}");
5039 return true;
5040 }
5041 let mut at: Option<i128> = None;
5042 let mut first = true;
5043 loop {
5044 let (stamp, bytes) = match track.next_packet() {
5045 Ok(Some(packet)) => packet,
5046 Ok(None) => return true, // end of the file, and of the segment
5047 Err(e) => {
5048 eprintln!("audio demux error: {e}");
5049 return true;
5050 }
5051 };
5052 // The count of samples decoded since the last stamp is the position, until a stamp
5053 // disagrees with it by more than a fiftieth of a second (a dropped packet, a splice).
5054 let pos = match at {
5055 Some(running) if (running - stamp).abs() <= rate / 50 => running,
5056 _ => stamp,
5057 };
5058 if pos >= seg.media_end as i128 {
5059 return true;
5060 }
5061 let decoded = match decoder.decode(&bytes) {
5062 Ok(Some(decoded)) => decoded,
5063 Ok(None) => continue,
5064 Err(e) => {
5065 eprintln!("audio decode error at sample {pos}: {e}");
5066 return true;
5067 }
5068 };
5069 let mut interleaved = decoded.samples;
5070 let width = decoded.channels.max(1);
5071 at = Some(pos + i128::from(decoded.frames));
5072 downmix(&mut interleaved, width);
5073 widen(&mut interleaved, width.min(2), channels);
5074 let frames = (interleaved.len() / channels) as i128;
5075 // A packet that starts before the clip does: the frames in front of 0 are dropped.
5076 let (mut pos, mut frames) = (pos, frames);
5077 if pos < 0 {
5078 let cut = ((-pos).min(frames)) as usize;
5079 interleaved.drain(..cut * channels);
5080 pos += cut as i128;
5081 frames -= cut as i128;
5082 }
5083 if frames <= 0 {
5084 continue;
5085 }
5086 // The first sound of the run begins after the window does: the gap is silence,
5087 // so the sound keeps its offset from the picture.
5088 if first {
5089 first = false;
5090 let target = seg.media_target as i128;
5091 if pos > target {
5092 let gap = (pos.min(seg.media_end as i128) - target) as usize;
5093 let mut silence = vec![0.0f32; gap * channels];
5094 if !emit(
5095 &mut silence,
5096 seg,
5097 Chain {
5098 eq: eq.as_deref_mut(),
5099 speed: &mut *speed,
5100 fade: &mut *fade,
5101 channels,
5102 timeline: &mut *timeline,
5103 tx,
5104 },
5105 target as u64,
5106 pos.min(seg.media_end as i128) as u64,
5107 ) {
5108 return false;
5109 }
5110 }
5111 }
5112 if !emit(
5113 &mut interleaved,
5114 seg,
5115 Chain {
5116 eq: eq.as_deref_mut(),
5117 speed: &mut *speed,
5118 fade: &mut *fade,
5119 channels,
5120 timeline: &mut *timeline,
5121 tx,
5122 },
5123 pos as u64,
5124 (pos + frames) as u64,
5125 ) {
5126 return false;
5127 }
5128 }
5129}
5130
5131fn run_sym(track: &mut SymTrack, seg: &Segment, chain: Chain<'_>) -> bool {
5132 let Chain {
5133 mut eq,
5134 speed,
5135 fade,
5136 channels,
5137 timeline,
5138 tx,
5139 } = chain;
5140 let mut decoder = match track.decoder() {
5141 Ok(decoder) => decoder,
5142 Err(e) => {
5143 eprintln!("audio decoder init failed: {e}");
5144 return true;
5145 }
5146 };
5147 track.seek_to(seg.media_target);
5148 let mut interleaved = Vec::new();
5149 // Media position of the next frame to decode: the landing for the first
5150 // packet, and the decoder's own count from there on. A packet's timestamp
5151 // cannot carry it, because the frames of one laced block all share the
5152 // block's -- accumulating is what both mp4 readers here already do.
5153 let mut at: Option<u64> = None;
5154 // The withheld tail (see `SymTrack::tail_hold`) and the position of its first frame.
5155 let mut held: Vec<f32> = Vec::new();
5156 let mut held_pos = 0u64;
5157 loop {
5158 let packet = match track.next_packet() {
5159 Ok(Some(packet)) => packet,
5160 Ok(None) => return true, // end of the file, and of the segment
5161 Err(e) => {
5162 eprintln!("audio demux error: {e}");
5163 return true;
5164 }
5165 };
5166 if packet.track_id != track.track_id {
5167 continue; // another track of the same container
5168 }
5169 // A Matroska Vorbis packet's own start is exact ([`SymTrack::exact_start`]);
5170 // the running count and the stamp only answer where there is no index.
5171 let pos = track.exact_start(packet.pts).or(at).unwrap_or_else(|| match track.params.codec {
5172 // A Vorbis run from the top starts at the top. Matroska stamps its
5173 // blocks a few milliseconds past the samples they hold (ffmpeg
5174 // starts the same file at 0), so the first block's stamp is not the
5175 // start of the run.
5176 CODEC_ID_VORBIS if seg.media_target == 0 => 0,
5177 _ => track.samples_at(packet.pts),
5178 });
5179 if pos >= seg.media_end {
5180 return true; // segment done, on to the next one
5181 }
5182 if let Err(e) = decoder.decode(&packet, &mut interleaved) {
5183 eprintln!("audio decode error at sample {pos}: {e}");
5184 return true;
5185 }
5186 // decoder.decode already folded to track.channels ([`SymDecoder::decode`],
5187 // [`downmix`]); widen the mono case up to the timeline's own width
5188 // before anything below divides by it.
5189 widen(&mut interleaved, usize::from(track.channels), channels);
5190 if interleaved.is_empty() {
5191 // A packet that answers nothing (a fresh decoder's first block
5192 // only primes the overlap) is not a position: the packet that
5193 // does answer carries its own timestamp, and counting on from this
5194 // one's is what put a seeked Vorbis file 1025 samples off its timeline.
5195 at = None;
5196 continue;
5197 }
5198 let next = pos + (interleaved.len() / channels) as u64;
5199 at = Some(next);
5200 // The last `tail_hold` frames of the track are not played: they wait
5201 // here, and whatever is still held when the file ends is dropped.
5202 let (pos, next) = if track.tail_hold > 0 {
5203 if held.is_empty() {
5204 held_pos = pos;
5205 }
5206 held.append(&mut interleaved);
5207 let keep = usize::try_from(track.tail_hold)
5208 .unwrap_or(usize::MAX)
5209 .saturating_mul(channels);
5210 let release = held.len().saturating_sub(keep);
5211 interleaved.extend(held.drain(..release));
5212 let released = (interleaved.len() / channels) as u64;
5213 let from = held_pos;
5214 held_pos += released;
5215 (from, from + released)
5216 } else {
5217 (pos, next)
5218 };
5219 // Reborrowed per packet: the filter memory has to carry across the
5220 // packet boundary, so this is one `EqState` for the whole segment.
5221 if !emit(
5222 &mut interleaved,
5223 seg,
5224 Chain {
5225 eq: eq.as_deref_mut(),
5226 speed: &mut *speed,
5227 fade: &mut *fade,
5228 channels,
5229 timeline: &mut *timeline,
5230 tx,
5231 },
5232 pos,
5233 next,
5234 ) {
5235 return false;
5236 }
5237 }
5238}
5239
5240#[cfg(test)]
5241mod tests {
5242 use super::{
5243 MixControls, PRE_ROLL, SAMPLES_PER_PACKET, downmix, packet_at, packet_run, packet_run_last,
5244 vorbis_to_film_order,
5245 };
5246 use crate::limiter::Limiter;
5247
5248 const C: f32 = std::f32::consts::FRAC_1_SQRT_2;
5249
5250 /// The fold, channel by channel and width by width: each side keeps its own
5251 /// front channel, takes the centre and its own surrounds at -3 dB, drops the
5252 /// LFE, and comes out unable to clip a full-scale source. The channel order
5253 /// is FL, FR, FC, LFE, BL, BR, SL, SR.
5254 #[test]
5255 fn a_surround_frame_folds_to_stereo_without_clipping() {
5256 // Per width: what each channel at full scale, alone, must land as
5257 // *before* the normalisation that width carries.
5258 let layouts: [(usize, &[(f32, f32)]); 6] = [
5259 (3, &[(1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]),
5260 (4, &[(1.0, 0.0), (0.0, 1.0), (C, 0.0), (0.0, C)]),
5261 (5, &[(1.0, 0.0), (0.0, 1.0), (C, C), (C, 0.0), (0.0, C)]),
5262 (
5263 6,
5264 &[
5265 (1.0, 0.0),
5266 (0.0, 1.0),
5267 (C, C),
5268 (0.0, 0.0),
5269 (C, 0.0),
5270 (0.0, C),
5271 ],
5272 ),
5273 (
5274 7,
5275 &[
5276 (1.0, 0.0),
5277 (0.0, 1.0),
5278 (C, C),
5279 (0.0, 0.0),
5280 (C, C),
5281 (C, 0.0),
5282 (0.0, C),
5283 ],
5284 ),
5285 (
5286 8,
5287 &[
5288 (1.0, 0.0),
5289 (0.0, 1.0),
5290 (C, C),
5291 (0.0, 0.0),
5292 (C, 0.0),
5293 (0.0, C),
5294 (C, 0.0),
5295 (0.0, C),
5296 ],
5297 ),
5298 ];
5299 for (from, want) in layouts {
5300 let (nl, nr) = want
5301 .iter()
5302 .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1));
5303 for (channel, &(left, right)) in want.iter().enumerate() {
5304 let mut frame = vec![0.0f32; from];
5305 frame[channel] = 1.0;
5306 downmix(&mut frame, from);
5307 assert_eq!(frame.len(), 2, "{from} ch: one frame is one stereo frame");
5308 assert!(
5309 (frame[0] - left / nl).abs() < 1e-6 && (frame[1] - right / nr).abs() < 1e-6,
5310 "{from} ch{channel}: {frame:?}, want {left}/{nl} {right}/{nr}"
5311 );
5312 }
5313 // Every channel at once is what a normalised fold exists for.
5314 let mut loud = vec![1.0f32; from * 2];
5315 downmix(&mut loud, from);
5316 assert_eq!(loud.len(), 4, "{from} ch: two frames out of two");
5317 assert!(
5318 loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),
5319 "{from} ch: full scale in, full scale out, never past it: {loud:?}"
5320 );
5321 }
5322 // Mono and stereo are handed over untouched.
5323 for from in [1, 2] {
5324 let mut flat = vec![0.5f32, -0.5];
5325 downmix(&mut flat, from);
5326 assert_eq!(flat, [0.5, -0.5], "{from} ch is not a fold");
5327 }
5328 }
5329
5330 /// The Vorbis order an Opus surround stream is stored in, into the film
5331 /// order the fold reads. Each channel is its own index, so a permutation
5332 /// that drifts is the value that comes out in the wrong slot.
5333 #[test]
5334 fn vorbis_order_becomes_film_order() {
5335 // (width, film slot -> the vorbis channel it must hold)
5336 for (from, want) in [
5337 (3usize, &[0, 2, 1][..]),
5338 (5, &[0, 2, 1, 3, 4]),
5339 (6, &[0, 2, 1, 5, 3, 4]),
5340 (7, &[0, 2, 1, 6, 5, 3, 4]),
5341 (8, &[0, 2, 1, 7, 5, 6, 3, 4]),
5342 ] {
5343 // Two frames, so a permutation that reads across the frame boundary
5344 // shows up as the wrong frame's value.
5345 let mut samples: Vec<f32> = (0..from * 2).map(|i| i as f32).collect();
5346 vorbis_to_film_order(&mut samples, from);
5347 let got: Vec<usize> = samples[..from].iter().map(|&s| s as usize).collect();
5348 assert_eq!(got, want, "{from} ch, first frame");
5349 let second: Vec<usize> = samples[from..].iter().map(|&s| s as usize - from).collect();
5350 assert_eq!(second, want, "{from} ch, second frame");
5351 }
5352 // 7.1's LFE is the last vorbis channel and the fourth film one.
5353 let mut lfe = vec![0.0f32; 8];
5354 lfe[7] = 1.0;
5355 vorbis_to_film_order(&mut lfe, 8);
5356 assert_eq!(
5357 lfe[3], 1.0,
5358 "the LFE lands where the fold drops it: {lfe:?}"
5359 );
5360 }
5361
5362 /// A real AAC track: one stts entry, N packets of 1024.
5363 fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
5364 [(count, 1024)]
5365 }
5366
5367 #[test]
5368 fn packet_at_walks_back_by_the_pre_roll() {
5369 // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..).
5370 assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064));
5371 assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016));
5372 // Exactly on a packet boundary is the start of that packet, not the end
5373 // of the previous one.
5374 assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048));
5375 }
5376
5377 #[test]
5378 fn packet_at_clamps_both_ends() {
5379 // Head: no room for the walk-back, and packet ids are 1-based.
5380 assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0));
5381 assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0));
5382 // Past the end: the last packet, so the worker decodes ~nothing.
5383 assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776));
5384 // Degenerate boxes must not panic or wrap.
5385 assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0));
5386 assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0));
5387 }
5388
5389 #[test]
5390 fn packet_at_crosses_stts_entries() {
5391 // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240
5392 // with packet 11.
5393 let entries = [(10u32, 1024u32), (10, 512)];
5394 assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288));
5395 assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264));
5396 // The corner-cut clamp: on the first packet of the second entry the
5397 // walk-back stops there instead of stepping into the first entry.
5398 assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
5399 }
5400
5401 /// xorshift64: adversarial segment lists do not deserve a dependency.
5402 fn rng(state: &mut u64) -> u64 {
5403 *state ^= *state << 13;
5404 *state ^= *state >> 7;
5405 *state ^= *state << 17;
5406 *state
5407 }
5408
5409 #[test]
5410 fn packet_run_keeps_cumulative_error_under_a_packet() {
5411 let packet = i64::from(SAMPLES_PER_PACKET);
5412 let mut state = 0x5eed_1234_9876_abcd;
5413 for rate in [44100i64, 48000] {
5414 for list in 0..100 {
5415 let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64);
5416 // 3..43 joins of anything from one video frame to four seconds.
5417 for join in 0..3 + rng(&mut state) % 40 {
5418 let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64;
5419 copied += i64::from(packet_run(&mut err, ideal, u32::MAX));
5420 asked += ideal;
5421 assert!(
5422 err.abs() < packet,
5423 "rate {rate} list {list} join {join}: err {err}"
5424 );
5425 }
5426 // The accumulator is the whole story: what it says is the drift.
5427 assert_eq!(copied * packet - asked, err);
5428 }
5429 }
5430 }
5431
5432 #[test]
5433 fn packet_run_rounds_against_the_running_debt() {
5434 // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples
5435 // owed, and the debt is repaid by a 44-packet second once it crosses a
5436 // half packet — never by letting each second round on its own.
5437 let mut err = 0;
5438 assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43);
5439 assert_eq!(err, -68);
5440 let mut seconds = 1;
5441 while packet_run(&mut err, 44100, u32::MAX) == 43 {
5442 seconds += 1;
5443 assert!(seconds < 20, "debt never repaid, err {err}");
5444 }
5445 assert_eq!(seconds, 7, "68 samples a second, half a packet is 512");
5446 assert!(err > 0, "the repaying second overshoots, err {err}");
5447 }
5448
5449 #[test]
5450 fn the_last_run_rounds_up_so_the_copy_reaches_its_picture() {
5451 // test_sync.mp4: 4.0 s at 44100 is 172.27 packets. Nearest copies 172 and
5452 // leaves 6 ms unwritten; the last run takes the 173rd, which runs 16 ms
5453 // past the picture -- under a frame.
5454 let ideal = 176_400;
5455 let mut err = 0;
5456 assert_eq!(packet_run(&mut err, ideal, u32::MAX), 172);
5457 let mut err = 0;
5458 assert_eq!(packet_run_last(&mut err, ideal, u32::MAX), 173);
5459 assert_eq!(err, 173 * 1024 - ideal);
5460 // A whole number of packets is not rounded up, and the track's end caps it.
5461 let mut err = 0;
5462 assert_eq!(packet_run_last(&mut err, 1024 * 10, u32::MAX), 10);
5463 assert_eq!(packet_run_last(&mut err, 1024 * 10, 4), 4);
5464 }
5465
5466 #[test]
5467 fn packet_run_forgives_a_debt_the_track_cannot_pay() {
5468 // Asking a second of a track with ten packets left: it delivers ten and
5469 // does not make the next segment copy the shortfall from elsewhere.
5470 let mut err = 0;
5471 assert_eq!(packet_run(&mut err, 44100, 10), 10);
5472 assert_eq!(err, 0);
5473 // Degenerate windows are empty, not negative.
5474 assert_eq!(packet_run(&mut err, 0, 10), 0);
5475 assert_eq!(packet_run(&mut err, i64::MAX, 7), 7);
5476 }
5477
5478 #[test]
5479 fn asc_round_trips_aac_lc_44100_stereo() {
5480 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
5481 let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8);
5482 let asc = [
5483 (profile << 3) | (freq_index >> 1),
5484 (freq_index << 7) | (chan_conf << 3),
5485 ];
5486 assert_eq!(asc, [0x12, 0x10]);
5487 }
5488
5489 /// The one claim worth making about a hand-written bitstream: our own
5490 /// decoder turns it into exactly one packet of exactly zero.
5491 #[test]
5492 fn a_silent_packet_decodes_to_a_packet_of_zero() {
5493 use super::silent_packet;
5494
5495 for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] {
5496 // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels.
5497 // `4 << 7` in a u8 is zero: freq_index 4 has no low bits to put in byte 1.
5498 let asc = [(2 << 3) | (4 >> 1), chan_conf << 3];
5499 let mut decoder = ec_aac::AacDecoder::with_config_bytes(&asc).expect("decoder");
5500 let bytes = silent_packet(chan_conf).expect("silence");
5501 let pcm = decoder.decode(&bytes, None).expect("decodes as AAC-LC");
5502 assert_eq!(pcm.channels as usize, channels);
5503 assert_eq!(pcm.samples.len(), SAMPLES_PER_PACKET as usize * channels);
5504 assert!(
5505 pcm.samples.iter().all(|&s| s == 0.0),
5506 "{chan_conf} ch is not silent"
5507 );
5508 }
5509 assert!(
5510 silent_packet(6).is_err(),
5511 "beyond stereo is refused, not faked"
5512 );
5513 }
5514
5515 #[test]
5516 fn lane_peaks_keep_the_highest_level_until_read() {
5517 let controls = MixControls::new(vec![1.0, 1.0], Vec::new(), Limiter::default());
5518 controls.note_lane_peak(0, 0.25);
5519 controls.note_lane_peak(0, 0.5);
5520 controls.note_lane_peak(0, 0.125);
5521 controls.note_lane_peak(1, 0.75);
5522 controls.note_lane_peak(7, 1.0);
5523 assert_eq!(
5524 controls.take_lane_peaks(),
5525 vec![0.5, 0.75],
5526 "the highest level since the last read, per lane; a lane with no slot is ignored"
5527 );
5528 assert_eq!(
5529 controls.take_lane_peaks(),
5530 vec![0.0, 0.0],
5531 "a read starts the meters over"
5532 );
5533 }
5534
5535 /// A stereo clip on a mono timeline is no longer refused: the export folds
5536 /// its pair to the one channel the timeline carries ([`super::widen`]), the
5537 /// same as playback does. The file comes back mono, and the stereo clip's
5538 /// span is audible in it -- silent there would mean the fold dropped it.
5539 #[test]
5540 fn a_mono_clip_then_a_stereo_clip_exports_stereo() {
5541 use crate::export::{ExportSettings, Format};
5542 use crate::project::{Clip, LaneKind, Project, Source, Speed};
5543 use crate::scale::FitPolicy;
5544
5545 let assets = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets");
5546 let mono = assets.join("test_seek_chirp.mkv");
5547 let stereo = assets.join("test_av1_grain.mkv");
5548 let meta = crate::demux::Demuxer::open(&assets.join("test_av.mp4"))
5549 .expect("open test_av")
5550 .0;
5551 let clip = |start, source| Clip {
5552 speed_keys: Vec::new(),
5553 reversed: false,
5554 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5555 angle: Default::default(),
5556 fade_in: 0,
5557 fade_out: 0,
5558 transition_out: 0,
5559 transition_kind: Default::default(),
5560 visualizer: 0,
5561 viz_paint: 0,
5562 gain_db: 0.0,
5563 gain_keys: Vec::new(),
5564 pan: 0,
5565 transform_keys: Vec::new(),
5566 opacity_keys: Vec::new(),
5567 color_keys: Vec::new(),
5568 effects: Vec::new(),
5569 start,
5570 in_frame: 0,
5571 out_frame: 30,
5572 source,
5573 link: None,
5574 eq: None,
5575 color: None,
5576 fit: FitPolicy::default(),
5577 speed: Speed::NORMAL,
5578 transform: None,
5579 pitch: 0.0,
5580 };
5581 // One second of the mono source, then one second of the stereo one.
5582 let project = Project::from_parts(
5583 vec![Source::new(&mono, 0), Source::new(&stereo, 0)],
5584 vec![(LaneKind::Audio, vec![clip(0, 0), clip(30, 1)])],
5585 Vec::new(),
5586 Vec::new(),
5587 Vec::new(),
5588 )
5589 .expect("a mono clip with a stereo clip after it");
5590
5591 let out = crate::scratch::Scratch::file("ve_stereo_on_mono", "wav");
5592 let handle = crate::export::start(
5593 project,
5594 meta,
5595 &out,
5596 &ExportSettings {
5597 format: Format::Wav,
5598 ..Default::default()
5599 },
5600 None,
5601 );
5602 let started = std::time::Instant::now();
5603 while !handle.is_finished() {
5604 assert!(started.elapsed().as_secs() < 120, "export did not finish in 120s");
5605 std::thread::sleep(std::time::Duration::from_millis(10));
5606 }
5607 handle
5608 .result()
5609 .expect("a finished export has an outcome")
5610 .expect("a mono clip then a stereo clip exports");
5611
5612 let (audio, chunks) = crate::AudioSession::open(&out)
5613 .expect("reopen the export")
5614 .expect("the export has audio");
5615 let mut samples = Vec::new();
5616 for chunk in chunks {
5617 samples.extend(chunk.samples);
5618 }
5619 // The timeline is as wide as its widest clip: the mono clip is widened
5620 // into both channels, and the stereo one is kept rather than folded.
5621 assert_eq!(audio.channels, 2, "a stereo clip makes the timeline stereo");
5622 let rate = f64::from(audio.sample_rate);
5623 let rms = |from: f64, to: f64| {
5624 let at = |secs: f64| (secs * rate) as usize;
5625 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
5626 assert!(!window.is_empty(), "no samples in [{from}, {to})");
5627 (window.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() / window.len() as f64)
5628 .sqrt()
5629 };
5630 let mono_span = rms(0.05, 0.95);
5631 let stereo_span = rms(1.05, 1.95);
5632 println!("rms: mono clip {mono_span:.4} stereo clip {stereo_span:.4}");
5633 assert!(mono_span > 0.01, "the mono clip is audible");
5634 assert!(stereo_span > 0.01, "the stereo clip is audible on the stereo timeline");
5635 std::fs::remove_file(&out).ok();
5636 }
5637}
5638