//! Background audio decode worker: pulls a source's audio track and hands //! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own //! reader so the video demuxer stays single-owner. //! //! Three readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as //! it always has -- that path also yields the raw access units the export //! copies, which is the only reason it is kept separate -- and a standalone //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through //! symphonia's own format probe, as does the AAC track of a **Matroska** file: //! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to //! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same //! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo //! timeline. Everything downstream of [`Track`] sees the //! same samples either way; only the packet copy asks which reader it came from, //! because there is nothing to copy out of an mp3 that an mp4 can hold. //! //! One output, however many lanes: a timeline's audio lanes are decoded side by //! side and summed ([`AudioSession::open_mixed_streams`]), which is what both //! the device and an audio-only export are handed. One lane skips the mixer //! entirely and is the plain single-stream path it always was. //! //! Both readers are addressed as `(path, stream)`. An mp4 may carry several //! audio tracks and the caller picks one; a standalone audio file carries //! exactly one, so any stream above 0 there is an `Err` rather than a silent //! fallback to the only track it has. use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::sync::{Arc, Mutex}; use std::thread; use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet}; use symphonia_codec_aac::AacDecoder; use symphonia_core::codecs::audio::{ AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::{CODEC_ID_AAC, CODEC_ID_OPUS}, }; use symphonia_core::formats::probe::Hint; // `TrackType` is the name both readers give their track kinds; the mp4 one is // imported above and used far more often here, so symphonia's is the one aliased. use symphonia_core::formats::{ FormatOptions, FormatReader, SeekMode, SeekTo, TrackType as SymKind, }; use symphonia_core::io::MediaSourceStream; use symphonia_core::meta::MetadataOptions; use symphonia_core::packet::Packet; use symphonia_core::units; use symphonia_core::units::{Time, TimeBase}; use crate::eq::{EqParams, EqState}; use crate::stretch::TimeStretch; use crate::limiter::{Limiter, LimiterState}; /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) const DEFAULT_PRIMING: u64 = 1024; /// An edit list entry that only shifts the timeline, carrying no media. const EMPTY_EDIT: u64 = u32::MAX as u64; /// What the sound of a *Matroska* file is read with, named for a refusal: /// symphonia's registry as this project enables it (see the feature list in /// `Cargo.toml`) plus the two families no symphonia version carries and this /// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`]) /// and Opus through `ruopus` ([`SymDecoder::Opus`]). /// /// Written down per container because capability is not one set: an mp4 video's /// sound never reaches symphonia ([`Track::open`] answers before it), so it /// reads fewer codecs than a Matroska file does. Both strings were "AAC only" /// long after that stopped being true, which is how a user came to re-encode a /// film whose FLAC track already played; `capability_matrix` opens one file per /// codec named here. const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, Opus, PCM and Vorbis"; /// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video /// file's sound is read and where it stops. const MP4_DECODED: &str = "AAC-LC and AC-3/E-AC-3"; /// Packets decoded and thrown away ahead of a seek target: one for the MDCT /// overlap-add that reconstructs the target packet, one to warm the decoder. const PRE_ROLL: u32 = 2; /// Frames per channel one AAC-LC packet carries. Fixed by the codec. pub(crate) const SAMPLES_PER_PACKET: u32 = 1024; /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the /// 256-sample overlap-add the target frame is reconstructed with. const AC3_PRE_ROLL: u32 = 1; /// Frames per channel a seek into a standalone audio file lands ahead of the /// window, decoded and thrown away: enough to refill an mp3's bit reservoir /// (a frame is 1152 samples and the reservoir reaches back two of them) at any /// rate we accept. const SYM_PRE_ROLL: u64 = 8192; #[derive(Debug, Clone, Copy, PartialEq)] pub struct AudioMeta { pub sample_rate: u32, pub channels: u16, /// Frames per channel the container claims, priming subtracted. `None` when /// the header does not say. pub total_samples: Option, } /// One decoder output block, ready to hand to an output device. pub struct AudioChunk { /// Position of the first frame, in samples-per-channel counted from the /// first audible sample: priming is already dropped, so 0 is media time 0. pub start_sample: u64, /// Interleaved, `AudioMeta::channels` values per frame. pub samples: Vec, } /// What a writer needs to declare an AAC track that plays copied packets: the /// esds fields verbatim from the source, no re-derivation. #[derive(Debug, Clone, Copy, PartialEq)] pub struct AacTrackParams { pub freq_index: u8, pub chan_conf: u8, pub sample_rate: u32, } /// One raw AAC access unit exactly as it sits in the source `mdat` — no ADTS /// header, which is the form an `mp4a` sample table wants. pub struct AacPacket { pub bytes: Vec, /// Frames per channel it decodes to, for the writer's stts. pub samples: u32, } /// Everything an import check needs from a candidate file's audio track. Two /// files may share a timeline when their layouts agree (or both are `None`). /// /// Rate and layout, of which only the **layout** is held to the timeline's: one /// output device and one exported track carry one width, while a rate of its own /// is resampled at the decoder's door ([`Resample`]). An mp3 that agrees on the /// layout may join a timeline of mp4s even though nothing about it can be /// *copied* into an export -- that is a separate refusal, at export time, in /// [`AudioSession::copy_multi_segments`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct AudioProbe { pub sample_rate: u32, pub channels: u16, } /// One audio stream of a file as its header describes it. Every audio track is /// described, decodable or not: a picker shows the ones we refuse greyed out /// rather than pretending a BluRay remux has fewer streams than it has. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StreamInfo { /// Position among this file's audio tracks in file order — the `stream` /// [`AudioSession::open_multi_streams`] takes. pub index: usize, /// Container codec. /// /// corner-cut: mp4 0.14 parses `mp4a` sample entries and silently drops every /// other kind (`stsd.rs` `_ => {}`), keeping no fourcc, so an AC-3/DTS/PCM /// stream can only be `"unknown"` here — enough to grey a row out, not /// enough to name the codec. Upgrade path is reading the sample entry's /// fourcc out of the file ourselves. pub codec: String, /// `0` for a stream whose sample entry mp4 0.14 does not parse. pub channels: u16, /// `0` for a stream whose sample entry mp4 0.14 does not parse. pub sample_rate: u32, /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write. pub lang: Option, /// Whether opening this stream would decode -- a codec question only now /// that no width is refused. The grey-out rule, mirroring what `Track::open` /// answers one file at a time. pub decodable: bool, } /// The mix settings a *running* mixer reads: what each lane is turned by on its /// way into the sum and the ceiling the sum comes out through, both swappable /// while the stream plays. /// /// This is what keeps a fader off the reseek path. Everything else a timeline /// says lives inside a decode worker -- a segment's window, its curve, its rate /// -- and can only be changed by rebuilding it, which is a flush, a re-open and /// a hole in the sound. These two live at the sum, where nothing is decoded, so /// the mixer can pick them up between one block and the next: an arrow key held /// down on a fader moves the level and nothing else moves at all. /// /// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live) /// is what says whether a mixer is actually reading it -- a single lane at /// unity with the limiter off is not mixed at all /// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this /// dead has to reopen the stream to be heard. pub struct MixControls { /// Bumped by every change; the mixer reloads when the number it last saw /// is not this one, so an unchanged mix costs one relaxed load per block. version: AtomicU64, /// The lane amplitudes and the limiter, together: they are set together and /// a mixer that read half of one change and half of the next would be /// mixing a state nobody asked for. state: Mutex<(Vec, Limiter)>, /// A mixer thread has these; see the type docs. live: AtomicBool, /// The open these were handed to finished without a mixer: a silent /// timeline, or a source that would not open. Set by whoever ran that open /// ([`PlaybackSession::start_audio`] does it from the feeder), because /// [`Self::live`] alone cannot tell "no mixer will ever read this" from /// "the mixer is still being opened" -- and a caller that cannot tell those /// apart either rebuilds the sound under a cold open, once per fader nudge, /// or hands a mix to nobody and never notices. detached: AtomicBool, } impl MixControls { pub fn new(gains: Vec, limiter: Limiter) -> Arc { Arc::new(Self { version: AtomicU64::new(0), state: Mutex::new((gains, limiter)), live: AtomicBool::new(false), detached: AtomicBool::new(false), }) } /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock /// held for a `Vec` swap and an atomic. pub fn set(&self, gains: Vec, limiter: Limiter) { *self.state.lock().unwrap() = (gains, limiter); self.version.fetch_add(1, Ordering::Release); } /// Whether a mixer thread is reading this at all. pub fn is_live(&self) -> bool { self.live.load(Ordering::Acquire) } /// Says the open is over and left no mixer behind; see [`Self::detached`]. pub fn detach(&self) { self.detached.store(true, Ordering::Release); } /// Whether anything can still hear a [`set`](Self::set): a mixer reading /// these, or an open still on its way to being one. pub fn is_reachable(&self) -> bool { !self.detached.load(Ordering::Acquire) } /// The mix, if it has moved since `seen`. `None` -- the every-block case -- /// takes no lock. fn changed(&self, seen: &mut u64) -> Option<(Vec, Limiter)> { let now = self.version.load(Ordering::Acquire); if now == *seen { return None; } *seen = now; Some(self.state.lock().unwrap().clone()) } } pub struct AudioSession; impl AudioSession { /// Opens the audio track of `path`. `Ok(None)` means the file simply has no /// audio, which is a valid session; `Err` is a real failure. pub fn open( path: impl AsRef, ) -> crate::Result)>> { Self::open_at(path, 0.0) } /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on /// the audible timeline; `start_sample` stays absolute from audible zero, so /// the output is the tail of a full run. Past the end yields no chunks. pub fn open_at( path: impl AsRef, start_secs: f64, ) -> crate::Result)>> { Self::open_segments(path, &[(start_secs, f64::INFINITY)]) } /// Decodes `segs` — half-open `[start, end)` windows in *source* seconds — /// back to back as one continuous stream: the chunks carry no gap at a join, /// so pouring them into a ring is seamless. Each segment gets a fresh /// decoder and its own pre-roll, which makes a seeked segment perceptually /// but not bit-exactly equal to the same window of a full run (perceptual /// noise substitution reseeds; measured below 1e-3). /// /// `start_sample` counts from the *first* segment's own audible start, so a /// single segment reads as absolute media time (what [`open_at`](Self::open_at) /// promises) and a list reads as one timeline. Segment ends past the track /// are capped; an empty list is a valid session with no chunks. pub fn open_segments( path: impl AsRef, segs: &[(f64, f64)], ) -> crate::Result)>> { let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect(); Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs) } /// [`open_segments`](Self::open_segments) over several files: a segment names /// its source by index into `sources`, and a source join behaves exactly like /// a cut inside one file — `start_sample` stays continuous, the decoder is /// fresh either way. Each source contributes *its own* priming, packet table /// and length, which is the whole reason the resolution is per source. /// /// A segment naming **no** source is a *gap*: that many seconds of silence /// are synthesised into the stream as ordinary chunks. Real chunks, not a /// pause — the master clock counts what the device has been fed, so a hole /// that fed nothing would stall the whole timeline on it. /// /// A segment naming a source that has **no track** is the same silence: a /// clip of a silent file is a hole with a picture over it, and the timeline /// let it in on exactly that footing ([`crate::PlaybackSession::import`]). /// /// Only the sources some segment names are opened. `Ok(None)` when `sources` /// is empty or its first entry has no AAC track; a later source that /// disagrees on *layout* is an `Err` — import refuses those up front (one /// timeline, one output device), this is the backstop. A source at another /// sample rate is not one of those: it is resampled, per segment. pub fn open_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], ) -> crate::Result)>> { let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect(); Self::open_multi_streams(&sources, segs) } /// [`open_multi_segments`](Self::open_multi_segments) with each source /// naming *which* of its audio streams to decode — files carrying several /// (a remux with one track per language) are otherwise stuck on their first. /// The index counts audio tracks in file order, as /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not /// exist or does not decode is an `Err` here, never a panic. pub fn open_multi_streams( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], ) -> crate::Result)>> { Self::open_multi_streams_eq(sources, segs, &[]) } /// [`open_multi_streams`](Self::open_multi_streams) with an equalizer per /// segment: `eqs[i]` is what segment `i` plays through, `None` for one that /// plays flat. Filtering happens **per segment**, inside the worker, before /// anything is mixed -- two clips with different curves must not be blurred /// into one another, and a segment's filter memory starts clean and dies /// with it, which is also what makes a seek a reset for free. /// /// A parallel list, not a fourth tuple element: see /// [`crate::Project::audio_eqs_from`], which is what builds it. A list /// shorter than `segs` (the empty one every plain caller passes) means the /// rest play flat, so a mismatch cannot panic and cannot silently shift a /// curve onto the wrong clip. pub fn open_multi_streams_eq( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], eqs: &[Option], ) -> crate::Result)>> { Self::open_multi_streams_speed(sources, segs, eqs, &[]) } /// [`open_multi_streams_eq`](Self::open_multi_streams_eq) with a *rate* per /// segment as well: `speeds[i]` says how fast segment `i` is read and how /// much timeline it owes ([`crate::project::Stretch`]), `None` for one at /// real time. [`crate::Project::audio_speeds_from`] is what builds it, beside /// the very list the segments come from. /// /// Resampling happens **per segment**, inside the worker and before the mix, /// for the equalizer's reasons: two clips at two speeds must not be read /// into one another, and the interpolator's memory dies with the segment. A /// list shorter than `segs` (the empty one every plain caller passes) means /// the rest play at real time, so nothing here can shift a rate onto the /// wrong clip and a project with no speeds decodes exactly the samples it /// always did. pub fn open_multi_streams_speed( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], eqs: &[Option], speeds: &[Option], ) -> crate::Result)>> { Self::open_multi_streams_speed_at(sources, segs, eqs, speeds, None) } /// [`open_multi_streams_speed`] with the project's own rate, when one was /// picked ([`crate::edith::Document::sample_rate`]), overriding the source's /// derived one. The per-segment [`Rate`] chain below already conforms any /// segment whose own rate differs from `meta.sample_rate`, so naming a rate /// here costs nothing new -- it only changes which rate that chain conforms /// *to*. pub fn open_multi_streams_speed_at( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], eqs: &[Option], speeds: &[Option], sample_rate: Option, ) -> crate::Result)>> { // No fades on this path, so the fps a `Fade` would be rescaled by is // never read; any finite value does. Self::open_multi_streams_speed_at_fade(sources, segs, eqs, speeds, &[], 1.0, sample_rate) } /// [`open_multi_streams_speed_at`](Self::open_multi_streams_speed_at) with a /// fade envelope per segment: `fades[i]` is what segment `i` plays through /// ([`emit`]'s last effect, after the rate and the equalizer), built the /// same way `eqs` and `speeds` are -- one entry per `segs`, a short list /// meaning flat from there on. `fps` is the timeline rate each `Fade` was /// built at ([`crate::Project::audio_fades_from`]) -- this is the one /// place that rate meets the audio one ([`crate::project::Fade::scaled`]). pub fn open_multi_streams_speed_at_fade( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], eqs: &[Option], speeds: &[Option], fades: &[Option], fps: f64, sample_rate: Option, ) -> crate::Result)>> { // The first source that could have a track, which is not always index 0: // a still image has none, and one at the front of the list (a save // renumbers, a library removal moves indexes) would be opened as a // broken audio file and take the whole timeline's sound down with it. // The same rule `PlaybackSession` probes by (`audio_source_of`). let Some((at, (path, stream))) = sources .iter() .enumerate() .find(|(_, (path, _))| !crate::is_image(path)) else { return Ok(None); }; let Some(first) = Track::open(path, *stream)? else { return Ok(None); }; // The timeline's meta is that source's: policy makes every other source // match it, and the checks below hold them to that. let meta = AudioMeta { sample_rate: sample_rate.unwrap_or_else(|| first.sample_rate()), channels: first.channels(), total_samples: first.total_samples(), }; // Built here only so an undecodable stream is an `Err` from the opener // rather than a silently empty channel; the worker makes its own. first.check_decoder()?; let mut tracks: Vec> = sources.iter().map(|_| None).collect(); // ...and which of them turned out to have no track at all, so a silent // source is opened once like any other rather than once per segment // naming it. let mut silent: Vec = sources.iter().map(|_| false).collect(); tracks[at] = Some(first); for &(source, ..) in segs { let Some(source) = source else { continue; // a gap opens no file }; if silent.get(source) == Some(&true) { continue; } let slot = tracks .get_mut(source) .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; if slot.is_some() { continue; // already opened, and the checks below already ran } let (path, stream) = &sources[source]; // A source with no audio track at all is not a failure: its // segments are silence, exactly as a gap's are, and the slot stays // empty to say so. That is what a silent clip on an audio lane // means -- a picture over a hole. let Some(track) = Track::open(path, *stream)? else { silent[source] = true; continue; }; // The *rate* is no longer held to the timeline's: a source written at // another one is read through its segment's [`Resample`] below, the // very interpolator a speeded clip already goes through, so it plays // at the pitch it was recorded at over the seconds it was placed for. // The layout still is -- one output device carries one width, and // everything wider than a pair is already folded to one. A mono // source is the one exception (DEBT #46): [`widen`] duplicates it // into every channel below, the same as [`PlaybackSession`]'s own // gate ([`crate::playback::audio_matches_probed`]) now allows. if track.channels() != meta.channels && !(track.channels() == 1 && meta.channels > 1) { return Err(format!( "source {source} is {} ch, the timeline is {} ch", track.channels(), meta.channels ) .into()); } track.check_decoder()?; *slot = Some(track); } let segments: Vec = segs .iter() // A gap, and a source with no track to decode, are the same stretch // of nothing: as many frames of silence as the window is long. .map(|&(source, start_secs, end_secs)| { match source.and_then(|source| Some((source, tracks[source].as_ref()?))) { Some((source, track)) => track.segment(source, start_secs, end_secs), None => Segment::silence( ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, ), } }) .collect(); // Chunk numbering is continuous across every join, counted from the first // segment's audible start in its own source (see `open_segments`). let timeline = segments.first().map_or(0, |s| match s.source { Some(source) => { let track = tracks[source].as_ref().expect("opened above"); // ...in *timeline* frames, which is not the source's own count // when it was written at another rate. Integer, so the equal-rate // case -- every project before this -- is the number it always was. let at = s.media_target.saturating_sub(track.priming()); at.saturating_mul(u64::from(meta.sample_rate)) / u64::from(track.sample_rate().max(1)) } None => 0, }); // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so // this bound is ~0.75 s of lookahead — enough to ride out decode jitter // without making a pause take a second to bite. // One filter per segment, built here where the rate and the layout are // known and off the thread that will run it. An identity curve costs a // branch and nothing else ([`EqState::process`]), and a segment with no // curve at all is not even that. let eqs: Vec> = segments .iter() .enumerate() .map(|(i, _)| { eqs.get(i) .and_then(Option::as_ref) .map(|p| EqState::new(p, meta.sample_rate, meta.channels)) }) .collect(); // One rate chain per segment that needs one, built where the sample // rate is known: what the timeline owes it is seconds there and frames // here. // // Two things ask for one, and they are NOT the same thing: a source // written at a rate other than the timeline's is a *rate conversion* // -- reading the samples at the ratio of the two rates is what keeps // a 48 kHz file's pitch on a 44.1 kHz timeline, and is the resampler's // whole duty now. A clip whose own [`Speed`] is not real time is a // *time* change: the resample hands the stretch a pitch-true stream // and the stretch hands the timeline the clip's compressed or // stretched seconds with every period of the signal kept (the tape // effect this used to be -- one resample at the speed -- moved the // pitch with the rate). A segment with neither has no chain at all // and reaches the mixer with the decoder's own samples, byte for // byte, as it always did. let speeds: Vec> = segments .iter() .zip(segs) .enumerate() .map(|(i, (seg, &(_, start_secs, end_secs)))| { let rate = seg .source .and_then(|source| tracks[source].as_ref()) .map_or(meta.sample_rate, Track::sample_rate); let ratio = f64::from(rate) / f64::from(meta.sample_rate.max(1)); let stretch = speeds.get(i).and_then(Option::as_ref); if stretch.is_none() && rate == meta.sample_rate { return None; } let channels = usize::from(meta.channels); // A speeded clip states the timeline it owes; a plain one owes // the window it was placed for, and an open-ended window owes // whatever its source has ([`Resample::UNBOUNDED`]). let secs = stretch.map_or(end_secs - start_secs, |s| s.timeline_secs); let owed = match (secs * f64::from(meta.sample_rate)).round() { frames if frames.is_finite() && frames >= 0.0 => { (frames as u64).min(Resample::UNBOUNDED - 1) } frames if frames > 0.0 => Resample::UNBOUNDED, _ => 0, }; Some(match stretch { // A rate conversion alone: the resampler owns the // segment's promise, as it always has. None => Rate { resample: Resample::new(ratio, owed), stretch: None, }, // A speeded clip: the resample is only the rate // conversion -- unbounded, because the ratio is all it // is asked for -- and the stretch lands the timeline's // frames exactly. Some(s) => Rate { resample: Resample::new(ratio, Resample::UNBOUNDED), stretch: Some(TimeStretch::new(s.step, owed, channels)), }, }) }) .collect(); // One [`crate::project::Fade`] per segment, exactly the eq and speed // lists' rule: a short `fades` (the empty one every plain caller // passes) means the rest play flat, and it is cloned rather than // built here because [`Project::audio_fades_from`] already resolved // each clip's own frame count against where this segment lands -- // in timeline frames, though, which is `fps`-relative and not yet // the rate `Fade::apply` will count samples at; `.scaled` re-counts // it in frames of `meta.sample_rate` now that this is known. let fade_ratio = f64::from(meta.sample_rate) / fps; let fades: Vec> = segments .iter() .enumerate() .map(|(i, _)| fades.get(i).copied().flatten().map(|f| f.scaled(fade_ratio))) .collect(); let (tx, rx) = sync_channel(32); thread::Builder::new() .name("audio-decode".into()) .spawn(move || { run(Worker { tracks, channels: meta.channels as usize, segments, eqs, speeds, fades, timeline, tx, }) })?; Ok(Some((meta, rx))) } /// Every audio lane of a timeline, summed into one stream: `lanes` is one /// play list per lane, each in the shape /// [`open_multi_streams`](Self::open_multi_streams) takes, and what comes /// out is what the device hears -- the lanes decoded side by side and added /// sample for sample, clamped to `[-1, 1]` so a loud pair cannot wrap the /// output. /// /// **One lane is not mixed at all**: it is `open_multi_streams` verbatim, so /// a timeline with a single audio lane decodes exactly the samples it always /// did, down to the bit and down to the thread count. /// /// Lengths need not agree: a lane that has run out contributes silence to /// what is left, which is what a shorter lane means. Each lane keeps its own /// gap rule -- a hole in it is real silence from its own worker, not a /// skipped chunk -- so the sum feeds the master clock a sample per sample of /// timeline however the lanes are arranged. `start_sample` numbers from the /// first lane's own start (see [`AudioChunk`]). pub fn open_mixed_streams( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], ) -> crate::Result)>> { Self::open_mixed_streams_eq(sources, lanes, &[]) } /// [`open_mixed_streams`](Self::open_mixed_streams) with /// [`open_multi_streams_eq`](Self::open_multi_streams_eq)'s per-segment /// equalizers, one list per lane -- [`crate::Project::audio_eqs_from`] is /// what shapes them. /// /// Filtering is each lane's worker's own business and therefore happens /// **before** the sum: a clip's curve reaches that clip's samples and stops /// there, where filtering the mix would smear every lane's curve over /// everything playing at the same instant. A missing or short list plays /// flat, as it does one lane down. pub fn open_mixed_streams_eq( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], ) -> crate::Result)>> { Self::open_mixed_streams_speed(sources, lanes, eqs, &[]) } /// [`open_mixed_streams_eq`](Self::open_mixed_streams_eq) with /// [`open_multi_streams_speed`](Self::open_multi_streams_speed)'s per-segment /// rates, one list per lane -- [`crate::Project::audio_speeds_from`] is what /// shapes them, off the same walk the segments come from. /// /// A resample is each lane's worker's own business and happens **before** /// the sum, exactly as the filtering does: every lane still hands the mixer /// as many samples as the timeline says, so the lanes stay sample-aligned by /// construction and a mix is still an add. pub fn open_mixed_streams_speed( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], ) -> crate::Result)>> { Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default()) } /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two /// settings that belong to the *mix* rather than to a clip: what each lane /// is turned up or down by on its way into the sum (`gains[i]`, an /// amplitude, [`crate::Project::audio_gains`] builds it) and the master /// limiter the sum comes out through. /// /// Both live at the sum and nowhere else, which is what makes a lane volume /// a *lane* volume and a limiter a master one: a gain applied per segment /// would have to agree with itself across a lane's cuts, and a limiter /// applied per lane would pump each lane against the others. A short or /// empty gain list means the rest play as they are, exactly as a short eq /// list means flat. /// /// Flat settings take the same path the mixer always took, down to the bit: /// one lane at unity with the limiter off is still `open_multi_streams` /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or /// a limiter that is on, is what puts a single-lane timeline through the /// mixer -- a sum of one, which is where both settings live. pub fn open_mixed_streams_master( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], gains: &[f32], limiter: Limiter, ) -> crate::Result)>> { Self::open_mixed_streams_master_at(sources, lanes, eqs, speeds, gains, limiter, None) } /// [`open_mixed_streams_master`] with the project's own rate /// ([`crate::edith::Document::sample_rate`]) overriding the derived one, the /// same rate every lane's meta agrees on ([`open_mixed_streams_live`]'s /// invariant). pub fn open_mixed_streams_master_at( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], gains: &[f32], limiter: Limiter, sample_rate: Option, ) -> crate::Result)>> { // No fades on this path -- see `open_multi_streams_speed_at`'s same // placeholder. Self::open_mixed_streams_master_at_fade( sources, lanes, eqs, speeds, &[], 1.0, gains, limiter, sample_rate, ) } /// [`open_mixed_streams_master_at`](Self::open_mixed_streams_master_at) /// with a fade envelope per segment; see /// [`open_mixed_streams_live_fade`](Self::open_mixed_streams_live_fade). /// `fps` is [`open_multi_streams_speed_at_fade`](Self::open_multi_streams_speed_at_fade)'s. pub fn open_mixed_streams_master_at_fade( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], fades: &[Vec>], fps: f64, gains: &[f32], limiter: Limiter, sample_rate: Option, ) -> crate::Result)>> { Self::open_mixed_streams_live_fade( sources, lanes, eqs, speeds, fades, fps, gains, limiter, None, sample_rate, ) } /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the /// mix left *reachable*: `live` is the handle the mixer picks its gains and /// its limiter off between blocks, so a fader moved while the stream plays /// is heard without the stream being rebuilt ([`MixControls`]). /// /// `gains`/`limiter` still say what it starts as -- they are what decides /// whether there is a mixer at all -- and the handle is marked live only /// when there is one. An export passes `None`: nothing can move under it. pub fn open_mixed_streams_live( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], gains: &[f32], limiter: Limiter, live: Option<&Arc>, sample_rate: Option, ) -> crate::Result)>> { // No fades on this path -- see `open_multi_streams_speed_at`'s same // placeholder. Self::open_mixed_streams_live_fade( sources, lanes, eqs, speeds, &[], 1.0, gains, limiter, live, sample_rate, ) } /// [`open_mixed_streams_live`](Self::open_mixed_streams_live) with a fade /// envelope per segment as well: `fades[i]` is what segment `i` plays /// through -- [`crate::Project::audio_fades_from`] is what builds it, off /// the same walk the segments come from. A short or missing list means /// the rest play flat, the eq list's rule. `fps` is the timeline rate /// those fades were built at ([`crate::project::Fade::scaled`]). pub fn open_mixed_streams_live_fade( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], fades: &[Vec>], fps: f64, gains: &[f32], limiter: Limiter, live: Option<&Arc>, sample_rate: Option, ) -> crate::Result)>> { let [first, ..] = lanes else { return Ok(None); }; if !Self::is_mixed(lanes.len(), gains, limiter) { let flat = Vec::new(); let plain = Vec::new(); let flat_fade = Vec::new(); return Self::open_multi_streams_speed_at_fade( sources, first, eqs.first().unwrap_or(&flat), speeds.first().unwrap_or(&plain), fades.first().unwrap_or(&flat_fade), fps, sample_rate, ); } let mut meta = None; let mut rxs = Vec::with_capacity(lanes.len()); for (i, segs) in lanes.iter().enumerate() { // Every lane takes its meta from the same source, so the metas // agree by construction; `None` from any of them is a silent // timeline. let flat = Vec::new(); let flat_fade = Vec::new(); let plain = Vec::new(); let Some((lane_meta, rx)) = Self::open_multi_streams_speed_at_fade( sources, segs, eqs.get(i).unwrap_or(&flat), speeds.get(i).unwrap_or(&plain), fades.get(i).unwrap_or(&flat_fade), fps, sample_rate, )? else { return Ok(None); }; meta = Some(lane_meta); rxs.push(rx); } let meta = meta.expect("at least one lane opened above"); let (tx, rx) = sync_channel(32); let channels = usize::from(meta.channels); // One per lane, in the lanes' own order, padded with unity: a short // list is "as it is from here on", the eq list's rule. let mut gains = gains.to_vec(); gains.resize(lanes.len(), 1.0); // Built here, off the thread that will run it, where the rate is known. let state = limiter .is_active() .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); // Marked before the spawn rather than inside it: a caller asks this the // moment the open returns, and a flag set on the far thread would still // read dead. let live = live.map(|live| { live.live.store(true, Ordering::Release); live.clone() }); let rate = meta.sample_rate; thread::Builder::new() .name("audio-mix".into()) .spawn(move || mix(&rxs, channels, gains, state, rate, live.as_deref(), &tx))?; Ok(Some((meta, rx))) } /// Whether these settings put the timeline through the **mixer**: more than /// one lane to sum, a lane off unity, or a limiter over the sum. Anything /// else is the single-lane flat path, which is `open_multi_streams` /// verbatim and has no mixer thread to talk to. /// /// Public to the crate because [`crate::PlaybackSession`] has to know the /// answer *before* the open now that it happens on another thread, and the /// answer must not be spelled out twice: what it decides is whether a fader /// is handed to a running mixer or rebuilds the stream. pub(crate) fn is_mixed(lanes: usize, gains: &[f32], limiter: Limiter) -> bool { lanes > 1 || limiter.is_active() || gains.iter().any(|&g| g != 1.0) } /// Why [`open`](Self::open) came back silent for a file that *has* sound: /// `Some(reason)` when there is an audio track in a codec this does not /// decode (an Opus web rip, say). `None` when the file is simply silent /// -- nothing to tell the user there. Header only, and only worth calling /// once the open has already returned no audio. pub fn unsupported(path: impl AsRef) -> crate::Result> { // Matroska: what symphonia reads out of one ([`Track::open`]) plus the // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder // ([`MkvAc3Track`]) and the Opus its own decoder takes; everything else // -- DTS, and whatever else no decoder here has -- is named rather than // left playing silent with no reason given. A Matroska file with no // audio track at all returns `None` here like any other silent file. if crate::demux::is_matroska(path.as_ref()) { let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { return Ok(None); }; // An AC-3 track that came up silent all the same is one that could // not be read -- a laced block, an unreadable syncframe -- and the // reader's own words are the ones worth showing. return Ok(Some(match MkvAc3Track::open(path.as_ref()) { Ok(Some(_)) => return Ok(None), // ...and the same question asked of the other reader, because a // refusal is a claim: a track symphonia's side really opens and // builds a decoder for is not one to tell the user about. This // is what stopped naming `A_OPUS` the moment Opus decoded. Ok(None) | Err(_) if SymTrack::open(path.as_ref()) .ok() .flatten() .is_some_and(|t| t.decoder().is_ok()) => { return Ok(None); } Ok(None) => format!( "the {codec} track of this Matroska file cannot be decoded — {MKV_DECODED} are" ), Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), })); } let file = File::open(path.as_ref())?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; // File order, out of `moov.traks`: naming a codec off a `HashMap` walk // would tell the user about a different track from one run to the next // on a film with two ([`audio_track_ids`], and the same trap the video // pick had in `demux::Mp4Demuxer::open`). Ok(audio_track_ids(&reader) .first() .and_then(|id| reader.tracks().get(id)) .map(|t| match t.media_type() { Ok(media) => { format!("the {media} audio track cannot be decoded — {MP4_DECODED} are") } Err(_) => { format!("the audio track is in a codec we cannot decode — {MP4_DECODED} are") } })) } /// The audio parameters of `path`'s `stream`, for checking an import /// against the timeline's first source: header only, no decoder and no /// worker. `Ok(None)` means no audio track — a silent file, which import /// pairs only with other silent files. A *named* stream that is not there /// or does not decode is an `Err`, as everywhere else. pub fn probe(path: impl AsRef, stream: usize) -> crate::Result> { let Some(track) = Track::open(path.as_ref(), stream)? else { return Ok(None); }; Ok(Some(AudioProbe { sample_rate: track.sample_rate(), channels: track.channels(), })) } /// Every audio stream of `path`, in file order: an entry's `index` is the /// stream number [`open_multi_streams`](Self::open_multi_streams) takes. /// Header only, no decoder and no worker — and no filtering either, so a /// stream this engine cannot decode is listed with `decodable: false` /// instead of vanishing. /// /// An empty list means the file has no audio at all, which is a valid /// silent source. /// /// A standalone audio file ([`crate::is_audio`]) has exactly one stream by /// construction — one track, no picture beside it — so it is described from /// symphonia's own header rather than walked as an mp4, which an mp3 is not /// and an ALAC `.m4a` only half is. pub fn probe_streams(path: impl AsRef) -> crate::Result> { let path = path.as_ref(); // A Matroska file lists one row per `TrackEntry` of audio -- a // dual-audio remux has two, and the second one used to be invisible -- // numbered by [`mkv_stream_order`]: the track that already plays first, // then the rest in file order. A file whose header will not walk at all // is an `Err` here, as it is in [`Track::open`]: a listing that quietly // came back empty for a broken file is how a lane ends up silent with // nothing to go on. No audio track at all is an empty list, which is // the silent source it says it is. if crate::demux::is_matroska(path) { let tracks = crate::demux::matroska_audio_tracks(path)?; let mut streams = Vec::new(); for (index, entry) in mkv_stream_order(path, &tracks) .into_iter() .map(|at| &tracks[at]) .enumerate() { // The routing [`Track::open`] does, one row at a time, so a row // describes the track that would really open: AC-3 and E-AC-3 // through the Dolby decoder's own reader, everything else // through symphonia. The AC-3 row describes what the decoder // *emits*, which is the stereo the §7.8 downmix hands the // timeline, not the 5.1 the file carries -- exactly as the mp4 // AC-3 rows do. let ac3 = matches!(entry.codec.as_str(), "A_AC3" | "A_EAC3") .then(|| MkvAc3Track::open_track(path, entry.number).ok().flatten()) .flatten(); // A track symphonia cannot even describe is listed undecodable // by the name the container gives it, rather than taking the // whole listing down with it: the other language still plays. let sym = match &ac3 { Some(_) => None, None => SymTrack::open_track(path, entry.number).ok().flatten(), }; let channels = ac3.as_ref().map_or_else( || sym.as_ref().map_or(0, |t| t.channels), |t| t.channels, ); streams.push(StreamInfo { index, codec: mkv_codec_name(&entry.codec), channels, sample_rate: ac3.as_ref().map_or_else( || sym.as_ref().map_or(0, |t| t.sample_rate), |t| t.sample_rate, ), lang: (entry.language != "und" && !entry.language.is_empty()) .then(|| entry.language.clone()), // No width gate any more: `channels` is what reaches the // timeline, which [`downmix`] makes a pair out of whatever // the file carries. What greys a row out is a codec nothing // here decodes, and nothing else. decodable: ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok()), }); } return Ok(streams); } if crate::is_audio(path) { let track = SymTrack::open_required(path)?; return Ok(vec![StreamInfo { index: 0, codec: track.codec.into(), channels: track.channels, sample_rate: track.sample_rate, // Neither the mp3 nor the wav headers carry an ISO-639 tag the // way an mdhd does, and a lone track needs no telling apart. lang: None, decodable: track.decoder().is_ok(), }]); } let file = File::open(path)?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; Ok(audio_track_ids(&reader) .into_iter() .enumerate() .map(|(index, id)| { let track = &reader.tracks()[&id]; let aac = matches!(track.media_type(), Ok(MediaType::AAC)); // An AC-3 track describes itself through its own reader: mp4 // 0.14 parses no sample entry for it, so `channel_config` and // `sample_freq_index` have nothing to say. What is listed is // the *decoded* shape -- stereo, because that is what the §7.8 // downmix hands the timeline (see [`Ac3Track`]). let ac3 = (!aac) .then(|| Ac3Track::open(path, index).ok().flatten()) .flatten(); let lang = track.language(); StreamInfo { index, codec: match (aac, &ac3) { (true, _) => "aac", (_, Some(_)) => "ac-3", _ => "unknown", } .into(), channels: ac3 .as_ref() .map_or_else(|| track.channel_config().map_or(0, channel_count), |t| { t.channels }), sample_rate: ac3.as_ref().map_or_else( || track.sample_freq_index().map_or(0, |f| f.freq()), |t| t.sample_rate, ), lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()), // The profile still gates -- the writer rebuilds an // AudioSpecificConfig and calls it LC -- but the layout no // longer does: a 5.1 or 7.1 AAC track decodes through // `rusty_aac` and folds to the pair the timeline carries // ([`aac_decoder`]). decodable: ac3.is_some() || aac && matches!( track.audio_profile(), Ok(AudioObjectType::AacLowComplexity) ), } }) .collect()) } /// How long `path`'s audio plays, in seconds. `Ok(None)` for a silent file. /// /// A standalone audio file is a source with no frame count of its own, so /// this is what its length on the timeline is derived from. Taken from the /// header where there is one; a stream that does not say — a bare mp3 with /// no Xing header is the usual one — is *decoded* to find out, which is /// linear in its length (~0.5 ms per source second) and happens once, at /// import, rather than per repaint. /// /// Stream 0: this answers for a standalone audio file, whose only stream /// that is. A video source's length is its frame count, never this. pub fn duration_secs(path: impl AsRef) -> crate::Result> { let path = path.as_ref(); let Some(track) = Track::open(path, 0)? else { return Ok(None); }; let rate = f64::from(track.sample_rate().max(1)); if let Some(total) = track.total_samples() { return Ok(Some(total as f64 / rate)); } drop(track); let Some((meta, rx)) = Self::open(path)? else { return Ok(None); }; let channels = usize::from(meta.channels.max(1)); let last = rx.into_iter().fold(0, |_, chunk| { chunk.start_sample + (chunk.samples.len() / channels) as u64 }); Ok(Some(last as f64 / f64::from(meta.sample_rate.max(1)))) } /// The raw AAC packets covering `segs` — the same half-open source-second /// windows [`open_segments`](Self::open_segments) decodes — copied out /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go /// straight into an mp4 writer, which is how an export keeps its sound exact /// wherever the edit lets it (a lane carrying an equalizer cannot be copied /// and is re-encoded instead -- `export::encode_audio`). /// /// Cut points do not land on 1024-sample boundaries, so each segment is /// rounded to whole packets against an error carried across the joins (see /// [`packet_run`]): the copy stays within half a packet (~12 ms) of the /// asked-for length however many cuts there are, instead of drifting out of /// lip sync one rounding at a time. /// /// The run starts one packet before the first audible one, which a reader /// drops as encoder priming — for a segment list starting at 0.0 that is the /// source's own priming packet, so the copy is the whole track from sample 1. /// /// `Ok(None)` for a file with no AAC track, and for an empty segment list. /// /// corner-cut: the first packet after an *interior* join decodes without its /// MDCT overlap predecessor, so up to 23 ms there can alias. Upgrade path is /// re-encoding just the join packets, which needs an encoder we do not have. pub fn copy_segments( path: impl AsRef, segs: &[(f64, f64)], ) -> crate::Result)>> { let segs: Vec<_> = segs.iter().map(|&(s, e)| (Some(0), s, e)).collect(); Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs) } /// [`copy_segments`](Self::copy_segments) over several files, segments naming /// their source by index into `sources`. The rounding debt is carried across /// a source join exactly as across a cut inside one file, so the bound stays /// half a packet over the whole list however many files it spans, and the /// extra priming packet is still the very first segment's alone. /// /// Every source that *has* a track must declare the same /// [`AacTrackParams`]: the copy becomes one output track with one esds. /// Import refuses a mismatch up front; the check here is the backstop. /// /// A segment naming **no** source is a gap, and is copied as that many /// packets of [`silent_packet`] silence — the rounding debt carried through /// it like any other, so the hole occupies its exact duration and the audio /// after it stays in sync with the picture. A gap the track *opens* on gets /// one silent packet more, which is the priming a reader drops. A segment /// naming a *silent* source is written the same way: a clip whose file has /// no audio track is a hole with a picture over it, and the timeline it /// joined already said so ([`crate::PlaybackSession::import`]). pub fn copy_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], ) -> crate::Result)>> { let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect(); Self::copy_multi_streams(&sources, segs) } /// [`copy_multi_segments`](Self::copy_multi_segments) with each source /// naming *which* of its audio streams to copy — the same `(path, stream)` /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two /// take it in the same shape on purpose: an export that copied a different /// stream from the one the timeline played would be a file that sounds /// nothing like what was edited, and nothing would say so. pub fn copy_multi_streams( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], ) -> crate::Result)>> { // The output track is declared from the first source that has one -- // not simply the first one named, which may be a silent clip. Such a // clip defines no rate and no layout; it is written as silence below // and the track goes on being the audible sources' track. let mut tracks: Vec>> = sources.iter().map(|_| None).collect(); let mut first = None; for &(source, ..) in segs { let Some(source) = source else { continue }; if let Some(track) = source_at(&mut tracks, sources, source)? { first = Some(track.track_params()); break; } } let Some(params) = first else { return Ok(None); // no segments, or nothing but silence }; let sample_rate = params.sample_rate; let mut err = 0i64; let mut packets: Vec = Vec::new(); for &(source, start_secs, end_secs) in segs { // A gap, and a clip whose source carries no track, are the same hole // to write: silence for as long as the window is. let named = match source { Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)), None => None, }; let Some((source, track)) = named else { let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; let bytes = silent_packet(params.chan_conf)?; // A reader drops the first packet of an AAC track as the // encoder's priming. When the track opens on a hole, that has to // come out of one *extra* packet of silence: dropped out of the // hole itself it would shorten it, and everything after the hole // would play a packet early. It is not part of the run, so it // owes the rounding debt nothing. let priming = u32::from(packets.is_empty()); for _ in 0..packet_run(&mut err, ideal, u32::MAX) + priming { packets.push(AacPacket { bytes: bytes.clone(), samples: SAMPLES_PER_PACKET, }); } continue; }; if track.track_params() != params { return Err(format!( "source {source} audio is {:?}, the timeline's is {params:?}", track.track_params() ) .into()); } let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale); let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0); let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64; let available = track.sample_count.saturating_sub(start_id - 1); // The head packet is the priming of the first segment only: a reader // drops exactly one, so an interior join must not add another -- // and neither must a segment behind a leading gap, which already // paid the priming in silence. let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1); let ids = head .into_iter() .chain(start_id..start_id + packet_run(&mut err, ideal, available)); for id in ids { let Some(sample) = track.reader.read_sample(track.track_id, id)? else { let count = track.sample_count; return Err(format!("audio sample {id} of {count} is missing").into()); }; packets.push(AacPacket { bytes: sample.bytes.to_vec(), samples: SAMPLES_PER_PACKET, }); } } Ok(Some((params, packets))) } } /// One AAC-LC access unit of silence, for the gaps in an exported timeline — /// this is the *copy* path, which never encodes anything, so the only silence it /// can write is one spelled out by hand. (The re-encode path next door has a /// real encoder and needs none of this: its gaps are zero samples.) /// /// It is the shortest legal `raw_data_block` there is: one element carrying /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no /// spectral data at all and therefore 1024 samples of exact zero. Every field /// is zero except the element id and the terminating `ID_END`, so the whole /// thing is 4 bytes mono and 7 stereo. Verified against our own decoder in the /// unit tests, which is the only claim worth making about hand-written /// bitstream. /// /// corner-cut: mono and stereo only, because `chan_conf` beyond 2 needs more /// elements per block; the timeline refuses such a source at import today, so /// this `Err` is a backstop. Upgrade path is emitting `chan_conf` elements. fn silent_packet(chan_conf: u8) -> crate::Result> { match chan_conf { // ID_SCE(000) tag(0000) + 22 zero bits + ID_END(111), byte-aligned. 1 => Ok(vec![0x00, 0x00, 0x00, 0x07]), // ID_CPE(001) tag(0000) common_window(0) + 2 x 22 zero bits + ID_END. 2 => Ok(vec![0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E]), n => Err(format!("cannot write silence for a {n}-channel AAC track").into()), } } /// The source at `index`, on the stream it names, opened on first use -- and /// `None` for a source that has no track at all, which the caller writes as /// silence exactly as it writes a gap. The outer `Option` is "has it been /// opened", the inner one "was there anything in it", so a silent source is /// opened once like any other. Sources a segment list never names are never /// touched: a project's list only grows. fn source_at<'a>( tracks: &'a mut [Option>], sources: &[(PathBuf, usize)], index: usize, ) -> crate::Result> { let slot = tracks .get_mut(index) .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; if slot.is_none() { let (path, stream) = &sources[index]; *slot = Some(copy_track(path, *stream)?); } Ok(slot.as_mut().expect("just opened").as_mut()) } /// A source's track for the *copy* path, which needs raw AAC access units. /// /// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name /// and by format. That is no longer the end of the road: `export::copy_audio` /// takes it as the answer "not copyable" and decodes and re-encodes the timeline /// instead, so these words are a fallback's reason rather than a user's refusal. /// They are still worded for a person, because a caller with no encoder to fall /// back on shows them verbatim. /// /// `Ok(None)` for a file with no audio at all, which is a silent export. fn copy_track(path: &Path, stream: usize) -> crate::Result> { match Track::open(path, stream)? { None => Ok(None), Some(Track::Aac(track)) => Ok(Some(track)), // A Matroska source gets its own words: its packets *are* AAC, so // "export needs AAC audio today" would read as a contradiction. What // they are not is packets of an mp4 sample table, which is what the // copy walks. The export decodes such a source and encodes it again // rather than showing this, so a film's sound reaches an mp4 either way; // the words stay for a caller that copies and cannot re-encode. // // corner-cut: the ceiling is the copy path being written against the mp4 // reader, not anything about the bytes. Upgrade path is a // `copy_segments` that walks a Matroska track, which would make this a // copy again instead of a re-encode. Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!( "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \ a copy walks an mp4's own sample table. It is decoded and encoded again \ instead", path.file_name() .unwrap_or(path.as_os_str()) .to_string_lossy(), ) .into()), Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)), // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` // sample table can hold. The export decodes it and encodes AAC, exactly // as it does for every other source no copy reaches. Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), } } /// The one wording for "this source's audio cannot be *copied* into an mp4", /// shared by every format that cannot be. What the export does about it is /// decode and re-encode; this is the reason it had to. fn uncopyable(path: &Path, codec: &str) -> crate::Error { format!( "a packet copy needs AAC in an mp4; {} is {codec}", path.file_name() .unwrap_or(path.as_os_str()) .to_string_lossy(), ) .into() } /// One source's audio, however it is stored: the mp4 AAC track the export can /// copy, or a standalone file read through symphonia's probe. The opener and /// the worker speak to this, never to either reader directly. enum Track { Aac(AacTrack), Ac3(Ac3Track), /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an /// mp4's sample table. Mkv(MkvAc3Track), Sym(SymTrack), } impl Track { /// `Ok(None)` for a file with no audio, which is a valid silent source. /// /// The mp4 reader goes first and its verdict is final for anything that is /// not [`crate::is_audio`]: a video file's audio track is exactly what it /// always was, silent mp4s included (an mp4 whose only `soun` track is one /// we cannot decode has always been a silent source, not an error). Only a /// standalone audio file falls through to symphonia — which is also how an /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track. /// /// `stream` counts audio tracks in file order, as /// [`AudioSession::probe_streams`] hands them out. A standalone audio file /// has exactly one, so any `stream` above 0 there is a promise the file /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. fn open(path: &Path, stream: usize) -> crate::Result> { // A Matroska file goes to symphonia, whose `mkv` reader is the one thing // here that reads its packets -- neither mp4 reader can open the file at // all -- except for the two codecs symphonia has no decoder for at any // version and this project does: AC-3 and E-AC-3 are handed to the Dolby // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither // one can decode (Opus, DTS) leaves the source the silent one it always // was, which `AudioSession::unsupported` puts into words, rather than // failing the import of a file whose picture is fine. A track that will // not open at all is *not* in that group: see below. if crate::demux::is_matroska(path) { // The numbering `probe_streams` lists and a project saves, from the // one function that decides it ([`mkv_stream_order`]): the stream // index picks a `TrackEntry`, that entry's *track number* is what // both readers are then pointed at. Positions are never handed to a // reader -- symphonia's own order is its business -- because a // mapping that drifts plays the wrong language and saves it into // the project. let tracks = crate::demux::matroska_audio_tracks(path)?; if tracks.is_empty() { return Ok(None); } let order = mkv_stream_order(path, &tracks); let Some(entry) = order.get(stream).map(|at| &tracks[*at]) else { return Err(format!( "{}: audio stream {stream} of {} stream{}", path.display(), tracks.len(), if tracks.len() == 1 { "" } else { "s" } ) .into()); }; match MkvAc3Track::open_track(path, entry.number) { Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), Ok(None) => {} // Named on the way past rather than returned: symphonia gets the // same file next and may read the track perfectly well (a laced // block is [`MkvAc3Track`]'s limitation, not the file's), and // if it cannot either, *its* `Err` is the one that comes back. Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), } // Two things are silent here and no more: a file with no audio // track at all, and a track whose codec nothing in this project // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts // that into words). A track that will not *open* is an `Err`, the // same answer the mp4 arm gives: turned into silence it would play // and export as a hole with only an eprintln to say why, which is a // bug wearing a feature's clothes. let Some(track) = SymTrack::open_track(path, entry.number)? else { return Ok(None); }; if let Err(e) = track.decoder() { eprintln!("matroska audio: {}: {e}", path.display()); return Ok(None); } return Ok(Some(Self::Sym(track))); } let audio_file = crate::is_audio(path); // Ahead of the AAC reader, because that one answers "not AAC" for a // *named* stream with an `Err` and an AC-3 track is not an error any // more. `Ok(None)` here means "not an AC-3 track", so every other file // falls through to exactly the reader it always used. if !audio_file && let Some(track) = Ac3Track::open(path, stream)? { return Ok(Some(Self::Ac3(track))); } match AacTrack::open(path, stream) { Ok(Some(track)) => return Ok(Some(Self::Aac(track))), Ok(None) if !audio_file => return Ok(None), Err(e) if !audio_file => return Err(e), _ => {} } if stream > 0 { return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); } SymTrack::open_required(path).map(|track| Some(Self::Sym(track))) } fn sample_rate(&self) -> u32 { match self { Self::Aac(t) => t.sample_rate, Self::Ac3(t) => t.sample_rate, Self::Mkv(t) => t.sample_rate, Self::Sym(t) => t.sample_rate, } } /// What this track hands the timeline: mono, or stereo for everything else. /// Nothing is refused for its width any more -- a layout wider than a pair /// is folded to one at the decoder's door ([`downmix`]), because one output /// device is all there is, not because the file is unreadable. fn channels(&self) -> u16 { match self { Self::Aac(t) => t.channels(), // Already downmixed by the AC-3 decoder itself; `channels` is what // comes *out* of it, and the 2.1 passthrough it leaves at 3 (see // [`Ac3Track`]) is folded by [`decode_ac3`] like any other width. Self::Ac3(t) => t.channels.min(2), // Downmixed by the very same decoder, out of a Matroska file. Self::Mkv(t) => t.channels.min(2), Self::Sym(t) => t.channels, } } /// Frames per channel of *audible* audio, priming already subtracted. fn total_samples(&self) -> Option { match self { Self::Aac(t) => t.total_samples, Self::Ac3(t) => t.total_samples, Self::Mkv(t) => t.total_samples, Self::Sym(t) => t.total_samples, } } /// Encoder delay of this file. Sources are joined, priming is not shared. fn priming(&self) -> u64 { match self { Self::Aac(t) => t.priming, Self::Ac3(t) => t.priming, // Matroska writes no edit list and AC-3 has no encoder delay: // block 0 is sample 0. Self::Mkv(_) => 0, Self::Sym(t) => t.priming, } } /// One `[start, end)` window of this source's seconds, resolved to whatever /// its own reader needs to find it again. fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { match self { Self::Aac(t) => t.segment(source, start_secs, end_secs), Self::Ac3(t) => t.segment(source, start_secs, end_secs), Self::Mkv(t) => t.segment(source, start_secs, end_secs), Self::Sym(t) => { let media_target = t.media(start_secs); Segment { source: Some(source), start_id: 0, start_pos: 0, media_target, media_end: t.media(end_secs).max(media_target), } } } } /// Builds and throws away a decoder, so an undecodable stream is an `Err` /// from the opener rather than a silently empty channel. fn check_decoder(&self) -> crate::Result<()> { match self { Self::Aac(t) => { aac_decoder(&t.params, t.source_channels())?; } Self::Ac3(t) => { ac3_decoder("ac3", t.requested)?; } Self::Mkv(t) => { ac3_decoder(t.mkv.codec, t.requested)?; } Self::Sym(t) => { t.decoder()?; } } Ok(()) } } /// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read /// through symphonia's own probe and codec registry. No packet table and no /// sample ids: the reader is *seeked* per segment and the packets it then hands /// out carry their own timestamps. struct SymTrack { reader: Box, /// The file the reader reads, kept because a seek builds a *new* one /// ([`SymTrack::seek_to`]). path: PathBuf, track_id: u32, sample_rate: u32, /// What reaches the timeline: the file's own layout, or 2 for anything /// wider, which is folded down by [`SymDecoder`] exactly as the AC-3 /// reader's decoder folds its own. channels: u16, /// What the decoder emits, which is what the fold reads. source_channels: u16, /// Frames per channel of audible audio, `None` when the header does not say. total_samples: Option, /// Encoder delay, and **always zero here**: symphonia 0.6 drops the leading /// frames itself, so a reader that skipped `Track::delay` on top would skip /// them twice. Kept as a field because [`Track::priming`] asks every track /// for one and the AAC and AC-3 readers beside it do owe a real number. /// /// This used to carry `delay` and cost the double skip on the two formats /// that declare one: a `.mp3` lost its first 1105 samples (25 ms) and read /// 25 ms short, an `.ogg` its first 128. Measured 2026-08-11 against /// `test_tone.flac` -- lossless, and the only one of the three whose /// container declares no delay at all -- which the mp3 and the ogg of the /// same tone align with sample for sample once this is not subtracted. priming: u64, time_base: TimeBase, params: AudioCodecParameters, /// The format's short name, for the export refusal. `&'static` because it /// comes out of the codec registry, which outlives everything here. codec: &'static str, } impl SymTrack { /// `Ok(None)` for a container that opened and holds no audio track at all -- /// a silent source, which is a thing a file is allowed to be. Everything /// else that goes wrong here is an `Err`: a file that will not open, will /// not parse, or carries a track it cannot describe is *broken*, and the /// difference matters because silence is played and exported without a word /// while an `Err` is shown ([`Track::open`]). fn open(path: &Path) -> crate::Result> { Self::open_inner(path, None) } /// [`open`](Self::open) pointed at one **named** track: a Matroska /// `TrackNumber`, which symphonia keeps as the track's id /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second /// language of a dual-audio file reachable, and it is matched by number /// rather than by position so this reader and /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which /// track a stream index meant. `Ok(None)` for a number the reader does not /// carry. fn open_track(path: &Path, number: u64) -> crate::Result> { Self::open_inner(path, Some(number)) } fn open_inner(path: &Path, number: Option) -> crate::Result> { let reader = sym_reader(path)?; let track = match number { Some(number) => reader .tracks() .iter() .find(|t| u64::from(t.id) == number), None => reader.default_track(SymKind::Audio), }; let Some(track) = track else { return Ok(None); }; // `track.delay` is deliberately not read: see the `priming` field. let (track_id, num_frames) = (track.id, track.num_frames); let time_base = track .time_base .ok_or_else(|| format!("{} declares no time base", path.display()))?; let Some(symphonia_core::codecs::CodecParameters::Audio(params)) = track.codec_params.clone() else { return Err(format!("{} declares no audio codec", path.display()).into()); }; let sample_rate = params .sample_rate .ok_or_else(|| format!("{} declares no sample rate", path.display()))?; let channels = params .channels .as_ref() .map(|c| c.count() as u16) .ok_or_else(|| format!("{} declares no channel layout", path.display()))?; let codec = symphonia::default::get_codecs() .get_audio_decoder(params.codec) .map_or("an unsupported format", |d| d.codec.info.short_name); // The one codec here that *does* owe a priming number: Opus states its // encoder delay in the stream itself (`OpusHead`'s pre-skip, 312 samples // on a film remux) and neither reader drops it, because symphonia trims // for its own decoders and the Opus one is this crate's. Measured against // ffmpeg's decode of the same file: 312 samples late in *both* an mkv and // an ogg until this is subtracted, sample-exact after (correlation // 1.00000). It is priming exactly as an AAC track's is, and it is read // off the stream rather than the container for that reason. let priming = match params.codec { CODEC_ID_OPUS => opus_pre_skip(params.extra_data.as_deref().unwrap_or_default()), _ => 0, }; Ok(Some(Self { reader, path: path.to_path_buf(), track_id, sample_rate, // Anything wider than a pair arrives as a stereo source, whatever it // was stored as: 5.1, 7.1 and everything between are folded by // [`downmix`] at the decoder's door ([`SymDecoder`]). channels: channels.min(2), source_channels: channels, total_samples: num_frames.map(|n| n.saturating_sub(priming)), priming, time_base, params, codec, })) } /// [`open`](Self::open) where having no audio track is itself the error: /// what a standalone audio file is held to, since a song with no sound in /// it is a broken file and not a silent source. fn open_required(path: &Path) -> crate::Result { Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into()) } /// A fresh decoder: seeking mid-stream leaves state that belongs to the /// packets we skipped, exactly as on the AAC path. /// /// Which decoder is not the caller's business, and it is not always /// symphonia's: its AAC decoder refuses anything wider than stereo outright /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 and /// 7.1 tracks of a film, so those go to `rusty_aac` instead /// ([`aac_decoder`]), and it has no Opus decoder at all, so that one goes to /// `ruopus`. fn decoder(&self) -> crate::Result { let from = usize::from(self.source_channels); if self.params.codec == CODEC_ID_OPUS { let (streams, coupled, mapping) = opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?; // 48 kHz whatever the container says: that is the only rate Opus // decodes at, and the rate both readers declare for it. let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping); return Ok(SymDecoder::Opus(Box::new(decoder), from)); } if self.params.codec == CODEC_ID_AAC { return aac_decoder(&self.params, from); } Ok(SymDecoder::Sym( symphonia::default::get_codecs() .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?, from, )) } /// `secs` on this source's audible timeline into media samples (priming /// included, so it compares directly against a decoded position). fn media(&self, secs: f64) -> u64 { ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) } /// A packet timestamp in the track's time base, as a media position: the /// scale [`media`](Self::media) hands out, so a landing compares directly /// against a segment's target. /// /// The priming comes *off* it because a Matroska Opus track's blocks are /// timestamped for the audible stream while the decoder hands its samples /// back with the pre-skip still in front of them. Measured against ffmpeg's /// decode of the same second of a real 5.1 Opus remux: without this term a seeked /// Opus track came out 6.5 ms -- one pre-skip, 312 samples -- ahead of it, /// with it, on the same sample. fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 { let secs = self.time_base.calc_time_saturating(ts).as_secs_f64(); ((secs.max(0.0) * f64::from(self.sample_rate)) as u64).saturating_sub(self.priming) } /// Puts the reader **at or before** `media_target`, [`SYM_PRE_ROLL`] ahead /// of it where the container allows, so that everything the caller did not /// ask for is decoder warm-up that [`emit`] drops. /// /// At or before is the whole point, and it is not what one seek gives. A /// Matroska seek lands on the first frame whose timestamp is at or past the /// one asked for, and its cue table can put that a whole cluster further on /// still: measured on a real 5.1 Opus remux, asking for 599.83 s (600 s less the /// pre-roll) landed at 601.487 s and asking for 609.83 s at 613.407 s. /// Samples that far *behind* the reader can never be emitted, and the film /// played from there while the timeline said 600 s -- 1.5 s of sound /// against picture, which is the seek desync this exists to kill. So the /// landing is read back, and an overshoot is asked again from far enough /// before it to swallow the overshoot. /// /// Each attempt gets a **new reader**, because symphonia's mkv seek is /// reliable exactly once per reader: it neither clears the frames it has /// already queued (they come out ahead of the new position, carrying the /// old block's timestamp) nor recovers its element iterator, and a second /// seek measured on the same file landed the reader back at the first /// cluster, 0.094 s, whatever it was asked for. Opening again costs 2 ms on /// a 5 GB film, which is what a seek is allowed to cost. fn seek_to(&mut self, media_target: u64) { let rate = f64::from(self.sample_rate.max(1)); let mut back = SYM_PRE_ROLL; // Enough for any overshoot a cue table can hold: each attempt asks from // strictly further back than the last, and the seek to 0 is the floor. for _ in 0..8 { let from = media_target.saturating_sub(back); match sym_reader(&self.path) { Ok(reader) => self.reader = reader, // Whatever the file did, the reader in hand still reads: fall // back to seeking that one, exactly as before this loop existed. Err(e) => eprintln!("audio reopen failed: {e}"), } // Asking for the beginning is asking for nothing: a fresh reader is // already there, and *seeking* there is how the first 167 ms of a // real 5.1 Opus remux went missing -- the cue table's first point put the // reader past them and no window rule can reach back. if from == 0 { return; } let secs = from as f64 / rate; let Some(time) = Time::try_from_secs_f64(secs) else { return; }; let to = SeekTo::Time { time, track_id: Some(self.track_id), }; // A failed seek is not fatal: it leaves the reader where it was, and // the window rules still only emit what the segment asked for. let landed = match self.reader.seek(SeekMode::Accurate, to) { Ok(landed) => self.samples_at(landed.actual_ts), Err(e) => { eprintln!("audio seek to {secs:.3}s failed: {e}"); return; } }; if landed <= media_target { return; } back += (landed - media_target) + SYM_PRE_ROLL; } } } /// One symphonia reader over `path`, which is both how a track is opened and /// how it is seeked ([`SymTrack::seek_to`]). fn sym_reader(path: &Path) -> crate::Result> { let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); // The extension is a hint, not a decision: the probe reads the magic and // is free to disagree, which is what makes a mislabelled file work. let mut hint = Hint::new(); if let Some(ext) = path.extension().and_then(|e| e.to_str()) { hint.with_extension(ext); } Ok(symphonia::default::get_probe().probe( &hint, mss, FormatOptions::default(), MetadataOptions::default(), )?) } /// One packet in, interleaved f32 out — whichever library did the decoding, and /// already folded to the layout [`SymTrack::channels`] promised. The number /// beside each is the width the decoder itself emits, which is what /// [`downmix`] folds from; 1 and 2 fold to nothing. enum SymDecoder { Sym(Box, usize), /// Boxed because the decoder carries its own IMDCT tables and this enum is /// moved into the worker. Aac(Box, usize), /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of /// a packet, the channel mapping table and the routing between them are all /// its business -- and the same width. Opus(Box, usize), } impl SymDecoder { fn decode(&mut self, packet: &Packet, out: &mut Vec) -> crate::Result<()> { match self { Self::Sym(decoder, from) => { decoder.decode(packet)?.copy_to_vec_interleaved::(out); downmix(out, *from); } Self::Aac(decoder, from) => { let pcm = decoder .decode(&packet.data, None) .map_err(|e| format!("AAC decode failed: {e}"))?; *out = pcm.samples; downmix(out, *from); } Self::Opus(decoder, from) => { *out = decoder .decode_packet(&packet.data) .map_err(|e| format!("Opus decode failed: {e}"))?; // The encoder delay is not dropped here: it is this track's // priming ([`SymTrack::open_inner`]), which the window rules // subtract once for the whole segment rather than per packet. vorbis_to_film_order(out, *from); downmix(out, *from); } } Ok(()) } } /// The decoder an AAC track of `from` channels needs: symphonia's own refuses /// anything wider than stereo outright (`aac/mod.rs:93`, "aac: aac too /// complex"), which is exactly the 5.1 and 7.1 tracks of a film, so those go to /// `rusty_aac` instead -- the same routing [`SymTrack::decoder`] does for a /// Matroska file, asked once here so an mp4's multichannel track takes it too. fn aac_decoder(params: &AudioCodecParameters, from: usize) -> crate::Result { if from > 2 { let asc = params .extra_data .as_deref() .ok_or("a multichannel AAC track with no AudioSpecificConfig")?; let decoder = rusty_aac::AacDecoder::with_config_bytes(asc) .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?; return Ok(SymDecoder::Aac(Box::new(decoder), from)); } Ok(SymDecoder::Sym( Box::new(AacDecoder::try_new(params, &AudioDecoderOptions::default())?), from, )) } /// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of /// `OpusHead`, little-endian. Zero for a track whose header is missing or too /// short to hold one -- there is nothing to subtract that we can trust. fn opus_pre_skip(head: &[u8]) -> u64 { match head { [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', _, _, lo, hi, ..] => { u64::from(u16::from_le_bytes([*lo, *hi])) } _ => 0, } } /// The stream layout of an Opus track, off the file's own `OpusHead`: how many /// elementary streams one packet carries, how many of those are coupled /// (stereo), and which decoded channel each output channel comes from. Both /// readers hand the header over as `extra_data` verbatim -- an mkv's /// `CodecPrivate`, an ogg's identification packet. /// /// Mapping family 0 carries no table at all and is mono or stereo by definition; /// every other family writes one (RFC 7845 §5.1), and family 1 -- the Vorbis /// surround layout a 5.1 film track is written with -- is four streams of which /// two are coupled. /// /// Everything here is checked rather than trusted: `MultistreamDecoder::with_rate` /// *panics* on a layout that breaks the RFC's limits, and this header comes /// straight out of a file, so a truncated or hostile one has to come back as an /// `Err` and be refused like any other undecodable track. fn opus_layout(head: &[u8], channels: usize) -> crate::Result<(usize, usize, Vec)> { if !(1..=255).contains(&channels) { return Err(format!("an Opus track of {channels} channels").into()); } let table = match head { [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', rest @ ..] if rest.len() > 10 => { // Byte 18 of the header is the mapping family; the table, when there // is one, is the two counts and one byte per output channel after it. match rest[10] { 0 => None, _ => Some(rest.get(11..13 + channels).ok_or("a truncated OpusHead")?), } } // No header at all: the container declared the channel count and nothing // else, which only family 0 can honestly be. _ => None, }; let Some(table) = table else { if channels > 2 { return Err(format!("an Opus track of {channels} channels with no mapping").into()); } return Ok((1, channels - 1, (0..channels as u8).collect())); }; let (streams, coupled) = (usize::from(table[0]), usize::from(table[1])); let mapping = table[2..].to_vec(); let decoded = streams + coupled; if streams < 1 || coupled > streams || decoded > 255 { return Err(format!("an Opus track of {streams} streams, {coupled} coupled").into()); } if !mapping.iter().all(|&m| m == 255 || usize::from(m) < decoded) { return Err(format!("an Opus channel mapping outside its {decoded} streams").into()); } Ok((streams, coupled, mapping)) } /// Surround Opus is stored in Vorbis channel order (RFC 7845 §5.1.1.2) and /// [`downmix`] reads the film order every other decoder here hands back. This is /// that permutation, in place, per width: each entry says which *source* channel /// the output slot of that index reads. Mono, stereo and quad agree already, and /// a width the RFC does not lay out is left alone rather than shuffled by guess. fn vorbis_to_film_order(samples: &mut [f32], from: usize) { let order: &[usize] = match from { 3 => &[0, 2, 1], // FL FC FR 5 => &[0, 2, 1, 3, 4], // FL FC FR SL SR 6 => &[0, 2, 1, 5, 3, 4], // FL FC FR SL SR LFE 7 => &[0, 2, 1, 6, 5, 3, 4], // FL FC FR SL SR BC LFE 8 => &[0, 2, 1, 7, 5, 6, 3, 4], // FL FC FR SL SR BL BR LFE _ => return, }; let mut frame = [0.0f32; 8]; for chunk in samples.chunks_exact_mut(from) { frame[..from].copy_from_slice(chunk); for (out, &src) in chunk.iter_mut().zip(order) { *out = frame[src]; } } } /// What each channel of a `from`-wide film-order layout contributes to the left /// and the right of a stereo fold. ITU-R BS.775: a front channel keeps its own /// side, the centre and the back centre go to both at -3 dB, a surround joins /// its own side at -3 dB, and the LFE is dropped -- it carries no programme a /// stereo pair could put anywhere, and neither ffmpeg's default downmix nor any /// player's puts it there. /// /// The film order is FL, FR, FC, LFE, BL, BR, SL, SR, which is what symphonia's /// decoders and `rusty_aac` both hand back (the latter reorders AAC's own /// C, L, R, Ls, Rs, LFE element order into it: `decode.rs:779`) and what the AC-3 /// decoder's own passthrough uses. /// /// corner-cut: a width past 7.1 (22.2, ambisonics) keeps its front pair and drops /// the rest -- no table here places those, and inventing one silently would be /// worse than a fold that is merely narrow. Upgrade path is one more arm. fn fold_coeffs(from: usize) -> Vec<(f32, f32)> { const C: f32 = std::f32::consts::FRAC_1_SQRT_2; const L: (f32, f32) = (1.0, 0.0); const R: (f32, f32) = (0.0, 1.0); const M: (f32, f32) = (C, C); const SL: (f32, f32) = (C, 0.0); const SR: (f32, f32) = (0.0, C); const X: (f32, f32) = (0.0, 0.0); match from { 3 => vec![L, R, X], // L R LFE (the 2.1 passthrough) 4 => vec![L, R, SL, SR], // FL FR BL BR 5 => vec![L, R, M, SL, SR], // FL FR FC BL BR 6 => vec![L, R, M, X, SL, SR], // 5.1 7 => vec![L, R, M, X, M, SL, SR], // FL FR FC LFE BC SL SR 8 => vec![L, R, M, X, SL, SR, SL, SR], // 7.1 n => (0..n).map(|c| [L, R][usize::from(c > 0)]).collect(), } } /// Anything wider than a stereo pair down to one, in place -- `from` is the /// channel count the decoder actually emitted, and 1 or 2 is not touched at all. /// This is what makes a 5.1 or 7.1 film an ordinary stereo source on the /// timeline instead of an import refusal. /// /// Both outputs are divided by the sum of their own coefficients /// ([`fold_coeffs`]), so a source at full scale cannot come out clipped. /// /// corner-cut: that normalisation costs 7.7 dB at 5.1 (9.9 at 7.1) against what /// ffmpeg's `-ac 2` hands out, which does not normalise and can overload -- so a /// film plays quieter here than in a player beside it. It is the loudness the /// AC-3 5.1 path already has (measured within 1.3 dB), so the two agree; the /// upgrade path is a limiter on the output, at which point the coefficients can /// go back to 1.0. fn downmix(samples: &mut Vec, from: usize) { if from < 3 { return; } let coeffs = fold_coeffs(from); let (left, right) = coeffs .iter() .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1)); // Never a boost: a layout with nothing on one side stays where it is. let (left, right) = (1.0 / left.max(1.0), 1.0 / right.max(1.0)); for frame in 0..samples.len() / from { let (mut l, mut r) = (0.0, 0.0); for (c, &(cl, cr)) in coeffs.iter().enumerate() { let sample = samples[frame * from + c]; l += cl * sample; r += cr * sample; } samples[2 * frame] = l * left; samples[2 * frame + 1] = r * right; } samples.truncate(samples.len() / from * 2); } /// The inverse of [`downmix`]: a mono buffer duplicated into every channel of /// a wider timeline, in place. `from` is the width the decoder actually /// handed back (already folded to 1 or 2 by [`downmix`] at its own door) and /// `to` is the timeline's own width ([`mix`]'s `channels`); anything that is /// not exactly the mono-into-wider case is left untouched -- a source already /// at `to`, and a source wider than `to`, which stays [`downmix`]'s refusal /// (DEBT #46: only 1-ch -> N-ch became legal, not the reverse). fn widen(samples: &mut Vec, from: usize, to: usize) { if from != 1 || to <= 1 { return; } let mut out = Vec::with_capacity(samples.len() * to); for &s in samples.iter() { out.extend(std::iter::repeat_n(s, to)); } *samples = out; } /// One source's AC-3 track: the same mp4 sample tables the AAC track is read /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and /// one timeline layout is all there is. A 5.1 BluRay track therefore arrives /// here as an ordinary stereo source, and its rows in the picker say so. /// /// `channels` is what the decoder actually emitted for the first frame rather /// than an assumed 2: everything from mono to 5.1 downmixes to stereo, but a 2.1 /// stream is a passthrough the library leaves at 3, and that is refused by name /// in [`Track::channels`] instead of being mislabelled. struct Ac3Track { reader: Mp4Reader>, track_id: u32, sample_count: u32, sample_rate: u32, channels: u16, timescale: u32, priming: u64, total_samples: Option, stts: Vec<(u32, u32)>, /// What the decoder is asked to hand out, from this track's own layout: /// `Some(2)` for anything with more than one front channel, `None` — the /// library's passthrough — for a mono track. See [`ac3_decoder`]. requested: Option, } impl Ac3Track { /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it /// is anything else (including out of range) — the caller then goes on to /// the AAC reader, which owns those verdicts and their wording. /// /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without /// keeping the fourcc, so what the track *is* comes out of the `stsd` by /// hand ([`crate::demux::sample_entry`]); the rate and the channel count /// come out of the first syncframe, which is where AC-3 states them. fn open(path: &Path, stream: usize) -> crate::Result> { let file = File::open(path)?; let size = file.metadata()?.len(); let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?; let ids = audio_track_ids(&reader); let Some(&track_id) = ids.get(stream) else { return Ok(None); }; if !matches!(crate::demux::sample_entry(path, track_id), Ok((kind, _)) if &kind == b"ac-3") { return Ok(None); } let track = &reader.tracks()[&track_id]; let timescale = track.timescale(); let duration = track.trak.mdia.mdhd.duration; let edit = edit_media_time(track); let stts: Vec<(u32, u32)> = stts_pairs(track).collect(); let sample_count = reader.sample_count(track_id)?; let first = reader .read_sample(track_id, 1)? .ok_or("the AC-3 track has no samples")?; let sample_rate = oxideav_ac3::syncinfo::parse(&first.bytes) .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))? .sample_rate; let nfchans = oxideav_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default()) .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? .nfchans; let requested = (nfchans > 1).then_some(2); let mut decoder = ac3_decoder("ac3", requested)?; let channels = decode_ac3(&mut decoder, &first.bytes)? .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) .filter(|&c| c > 0) .ok_or("the first AC-3 syncframe decoded to nothing")?; // No encoder delay in AC-3; a remux that writes an edit list is still // honoured, exactly as the AAC track honours it. let priming = edit .and_then(|t| scale(t, sample_rate, timescale)) .unwrap_or(0); Ok(Some(Self { track_id, sample_count, sample_rate, channels, timescale, priming, total_samples: scale(duration, sample_rate, timescale) .map(|d| d.saturating_sub(priming)), stts, requested, reader, })) } /// `secs` on this source's audible timeline into media samples. fn media(&self, secs: f64) -> u64 { ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) } /// One `[start, end)` window, resolved to syncframes and media samples — /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll. fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { let media_target = self.media(start_secs); let target_ts = unscale(media_target, self.sample_rate, self.timescale); let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL); Segment { source: Some(source), start_id, start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), media_target, media_end: self.media(end_secs).max(media_target), } } } /// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same /// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of /// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux /// therefore arrives on the timeline as an ordinary stereo source, exactly as /// the mp4 path's does, and the mono passthrough quirk is the same one. /// /// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side /// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): /// one block is one packet, one packet is one syncframe, and a seek lands on /// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in /// front of it. struct MkvAc3Track { mkv: crate::demux::MkvAudio, sample_rate: u32, /// What comes *out* of the decoder, measured on the first frame — 2 for /// anything from stereo to 5.1, 1 for a mono track (see `requested`). channels: u16, total_samples: Option, /// What the decoder is asked to hand out, from this track's own layout: /// `Some(2)` for anything with more than one front channel, `None` for a /// mono track. The reason is [`ac3_decoder`]'s `corner-cut`, not this file's. requested: Option, } impl MkvAc3Track { /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 — /// that mkv is the silent source it has always been. An `Err` is a track /// that is one and could not be read, which /// [`AudioSession::unsupported`] quotes back to the user. fn open(path: &Path) -> crate::Result> { Self::from_blocks(crate::demux::MkvAudio::open(path)?) } /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]), /// which is how the AC-3 half of a dual-audio file is reached. /// /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number fn open_track(path: &Path, number: u64) -> crate::Result> { Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?) } fn from_blocks(mkv: Option) -> crate::Result> { let Some(mut mkv) = mkv else { return Ok(None); }; let first = mkv .frame(0)? .ok_or("the AC-3 track of this Matroska file has no blocks")?; // Rate and layout come out of the bit stream, which is where AC-3 // states them: Matroska's `Audio` element repeats them and muxers get // that wrong often enough that the frame is the better source. // `nfchans` excludes the LFE in both syntaxes, which is what the // downmix decision wants. let (sample_rate, nfchans) = if mkv.codec == "eac3" { // Annex E's BSI starts right after the 16-bit syncword. let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; (bsi.sample_rate, bsi.nfchans) } else { let sync = oxideav_ac3::syncinfo::parse(&first) .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; (sync.sample_rate, bsi.nfchans) }; let requested = (nfchans > 1).then_some(2); let mut decoder = ac3_decoder(mkv.codec, requested)?; let (pcm, samples) = decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; let channels = (pcm.len() as u64 / samples.max(1)) as u16; if channels == 0 { return Err("the first AC-3 syncframe decoded to nothing".into()); } // The track runs to the last block's timestamp plus that block's own // frame -- a container that indexes nothing states no duration either, // and every frame of a syncframe stream is the same length. let last = mkv.secs(mkv.blocks().saturating_sub(1)); Ok(Some(Self { total_samples: Some((last * f64::from(sample_rate)) as u64 + samples), sample_rate, channels, requested, mkv, })) } /// `secs` on this source's timeline into media samples. No priming: the /// container carries no edit list and AC-3 no encoder delay. fn media(&self, secs: f64) -> u64 { (secs.max(0.0) * f64::from(self.sample_rate)) as u64 } /// One `[start, end)` window, resolved to blocks and media samples — /// [`Ac3Track::segment`] against block timestamps instead of an `stts`. fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { let media_target = self.media(start_secs); let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize); Segment { source: Some(source), start_id: start_id as u32, start_pos: self.media(self.mkv.secs(start_id)), media_target, media_end: self.media(end_secs).max(media_target), } } } /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a /// 5.1 track at all. Fresh per segment for the same reason every other decoder /// here is: a seek leaves overlap-add state belonging to the frames we skipped. /// /// corner-cut: `Some(2)` on a **mono** (`acmod` 1/0) source decodes to digital /// silence in oxideav-ac3 0.0.10 — measured, 5.1 and stereo are correct — so a /// mono track asks for no downmix at all and stays the mono source it is. The /// upgrade path is `Some(2)` unconditionally once the library duplicates the /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. /// /// `codec` is the track's own id — `ac3` or `eac3`, which the library registers /// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct /// behind both dispatches per packet on `bsid` in any case, so what this picks /// is the capability set, not the syntax. fn ac3_decoder(codec: &str, channels: Option) -> crate::Result> { let mut registry = CodecRegistry::new(); oxideav_ac3::register_codecs(&mut registry); let mut params = CodecParameters::audio(CodecId::new(codec)); params.channels = channels; registry .first_decoder(¶ms) .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) } /// One syncframe in, one buffer of interleaved f32 out and the frames per /// channel it holds. `Ok(None)` when the decoder wants more input before it can /// hand a frame back, which is not an error. The library speaks S16 /// little-endian; `/32768` is the whole conversion, and it lands in the /// `[-1, 1)` every other reader here emits. /// /// The frame count comes back beside the samples because an E-AC-3 frame is not /// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 /// or 3 blocks instead of 6 -- and dividing by an assumed length would put the /// channel count and every media position after it out. fn decode_ac3( decoder: &mut Box, bytes: &[u8], ) -> crate::Result, u64)>> { let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); decoder .send_packet(&packet) .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; match decoder.receive_frame() { Ok(Frame::Audio(audio)) => Ok(Some(( audio.data[0] .chunks_exact(2) .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) .collect(), u64::from(audio.samples), ))), Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), Err(oxideav_core::Error::NeedMore) => Ok(None), Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), } } /// One source's AAC track, resolved once: the reader plus everything the header /// has to say about it. `stts` is copied out because every other field would /// otherwise keep a borrow alive on the reader the worker needs mutably — a real /// AAC track has one entry, so it is two `u32`s. struct AacTrack { reader: Mp4Reader>, track_id: u32, sample_count: u32, sample_rate: u32, timescale: u32, /// Encoder delay of *this* file. Sources are joined, priming is not shared. priming: u64, total_samples: Option, stts: Vec<(u32, u32)>, config: ChannelConfig, freq_index: u8, chan_conf: u8, /// A fresh decoder is built from these per segment: seeking mid-stream /// leaves MDCT and PNS state that belongs to the packets we skipped. params: AudioCodecParameters, } impl AacTrack { /// The `stream`-th audio track of `path`, counted in file order over *all* /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out. /// /// Stream 0 is best effort: `Ok(None)` when there is no AAC track there at /// all, which is a valid silent source (a file whose audio is AC-3 still has /// a picture worth editing) and, for a standalone audio file, the door /// through to symphonia ([`Track::open`]). A stream the caller *named* is a /// promise instead, so out of range or not AAC there is an `Err` rather than /// silence the caller did not ask for. fn open(path: &Path, stream: usize) -> crate::Result> { let file = File::open(path)?; let size = file.metadata()?.len(); let reader = Mp4Reader::read_header(BufReader::new(file), size)?; let ids = audio_track_ids(&reader); let Some(track) = ids.get(stream).map(|id| &reader.tracks()[id]) else { return match stream { 0 => Ok(None), n => Err(format!( "{}: audio stream {n} of {} streams", path.display(), ids.len() ) .into()), }; }; if !matches!(track.media_type(), Ok(MediaType::AAC)) { return match stream { 0 => Ok(None), n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()), }; } // Refuse early with a message instead of failing packet by packet — and // a copy carries no profile of its own: the writer rebuilds the // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a // non-LC source would be mislabelled rather than merely unplayable. match track.audio_profile()? { AudioObjectType::AacLowComplexity => {} other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), } let track_id = track.track_id(); let sample_rate = track.sample_freq_index()?.freq(); let timescale = track.timescale(); let priming = priming_samples(track, sample_rate); let (_, freq_index, chan_conf) = asc_fields(track)?; let mut params = AudioCodecParameters::new(); params .for_codec(CODEC_ID_AAC) .with_sample_rate(sample_rate) .with_extra_data(audio_specific_config(track)?); let this = Self { track_id, sample_count: reader.sample_count(track_id)?, sample_rate, timescale, priming, total_samples: scale(track.trak.mdia.mdhd.duration, sample_rate, timescale) .map(|d| d.saturating_sub(priming)), stts: stts_pairs(track).collect(), config: track.channel_config()?, freq_index, chan_conf, params, reader, }; Ok(Some(this)) } /// What reaches the timeline: mono, or the stereo everything wider is folded /// to by [`downmix`] at the decoder's door. fn channels(&self) -> u16 { match self.config { ChannelConfig::Mono => 1, _ => 2, } } /// What the decoder emits, which is what the fold reads. fn source_channels(&self) -> usize { usize::from(channel_count(self.config).max(1)) } fn track_params(&self) -> AacTrackParams { AacTrackParams { freq_index: self.freq_index, chan_conf: self.chan_conf, sample_rate: self.sample_rate, } } /// `secs` on this source's audible timeline into media samples (priming /// included, so it compares directly against a decoded position). /// `f64::INFINITY` saturates. fn media(&self, secs: f64) -> u64 { ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) } /// One `[start, end)` window of this source's seconds, resolved to its own /// packets and media samples. fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { let media_target = self.media(start_secs); let target_ts = unscale(media_target, self.sample_rate, self.timescale); // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous // packet to cancel aliasing, plus one more to warm the decoder up. Their // output is discarded below, so this only costs decode time. let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL); Segment { source: Some(source), start_id, start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), media_target, // An inverted segment is an empty one, never a backwards run. media_end: self.media(end_secs).max(media_target), } } } /// How many whole packets to copy for a window of `ideal` samples per channel, /// capped at the `available` packets left in the track. /// /// `err` is "samples copied so far minus samples asked for", carried across the /// segment joins: rounding to nearest *against the running debt* keeps the /// cumulative error inside half a packet forever, where independent per-segment /// rounding would random-walk away from sync (charter D1: < 1024 at every join). fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { let packet = i64::from(SAMPLES_PER_PACKET); // Never carry a debt the track cannot pay: a segment running past the end // would otherwise inflate every later one. (Also tames `f64::INFINITY`, // which saturates to `i64::MAX` on the cast above.) let ideal = ideal.min(i64::from(available) * packet); let want = (ideal - *err) as f64 / packet as f64; let n = (want.round().max(0.0) as i64).min(i64::from(available)) as u32; *err += i64::from(n) * packet - ideal; n } /// The order a Matroska file's audio streams are numbered in, as positions into /// `tracks` (which is file order): **stream 0 is the track this project has /// always opened**, and the rest follow in file order behind it. /// /// Not file order outright, and the difference is a saved project's sound. A /// remux flags the language it wants heard with `FlagDefault` on whichever /// track it likes -- mkvmerge writes it on the second one all the time -- and /// that flag is what every reader here used to pick with. Numbering by file /// position would have made stream 0 a *different* track on those files, so an /// `.edith` project saved before this would quietly start playing the other /// language. Nothing that already plays may change what it plays. /// /// The old pick is not re-derived here, it is *run*: the AC-3 arm asks /// [`MkvAc3Track`] the same question [`Track::open`] asked it (and only of the /// file's first audio track, which is as far as [`crate::demux::MkvAudio`] /// ever looked), and everything else asks symphonia for its default track, /// which is `FlagDefault` where a muxer set one and the first readable track /// where nobody did. fn mkv_stream_order(path: &Path, tracks: &[crate::demux::MkvAudioTrack]) -> Vec { // One track is its own order, and it is the common case: no second probe // for the file that cannot have a second answer. if tracks.len() < 2 { return (0..tracks.len()).collect(); } let head = match tracks.first() { Some(first) if matches!(first.codec.as_str(), "A_AC3" | "A_EAC3") && matches!(MkvAc3Track::open_track(path, first.number), Ok(Some(_))) => { 0 } // A file symphonia will not open at all keeps file order: the open // itself is where that failure is reported, not the numbering. _ => SymTrack::open(path) .ok() .flatten() .and_then(|track| { tracks .iter() .position(|entry| entry.number == u64::from(track.track_id)) }) .unwrap_or(0), }; std::iter::once(head) .chain((0..tracks.len()).filter(|i| *i != head)) .collect() } /// The name a Matroska audio row wears: the container's own codec id, cut down /// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`. /// /// The codec id rather than symphonia's short name, because the rows that most /// need naming are exactly the ones it has no decoder for: an Opus or DTS track /// is greyed out with the codec in the reason (`unusable` in the app reads this /// very string), where symphonia would call it "an unsupported format". fn mkv_codec_name(id: &str) -> String { match id { "A_AC3" => "ac-3".into(), "A_EAC3" => "e-ac-3".into(), "A_MPEG/L3" => "mp3".into(), _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(), } } /// This file's audio tracks in file order — the order a stream index counts in. /// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a /// `HashMap`: iterating that would make "stream 0" a different track from one /// run to the next on any file carrying more than one. fn audio_track_ids(reader: &Mp4Reader) -> Vec { reader .moov .traks .iter() .filter(|trak| { matches!( TrackType::try_from(&trak.mdia.hdlr.handler_type), Ok(TrackType::Audio) ) }) .map(|trak| trak.tkhd.track_id) .collect() } /// Channels in an AAC channel configuration. The config number *is* the channel /// count up to 5.1; 7.1 is the one that is not. fn channel_count(config: ChannelConfig) -> u16 { match config { ChannelConfig::SevenOne => 8, other => other as u16, } } /// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a /// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside /// the crate (same trap as `SttsEntry`, see [`packet_at`]). fn asc_fields(track: &Mp4Track) -> crate::Result<(u8, u8, u8)> { let esds = track .trak .mdia .minf .stbl .stsd .mp4a .as_ref() .and_then(|mp4a| mp4a.esds.as_ref()) .ok_or("AAC track has no esds descriptor")?; let cfg = &esds.es_desc.dec_config.dec_specific; Ok((cfg.profile, cfg.freq_index, cfg.chan_conf)) } /// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14 /// parses those out and drops the raw bytes, so this is the exact inverse of its /// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`). fn audio_specific_config(track: &Mp4Track) -> crate::Result> { let (profile, freq_index, chan_conf) = asc_fields(track)?; Ok(Box::new([ (profile << 3) | (freq_index >> 1), (freq_index << 7) | (chan_conf << 3), ])) } /// The stts entries as the `(sample_count, sample_delta)` pairs [`packet_at`] /// walks; the box's own entry type is `pub(crate)` in mp4 0.14. Shared with /// `demux`, which walks a video trak's table with the same two helpers. pub(crate) fn stts_pairs(track: &Mp4Track) -> impl Iterator + '_ { track .trak .mdia .minf .stbl .stts .entries .iter() .map(|e| (e.sample_count, e.sample_delta)) } /// Encoder delay in samples-per-channel: the edit list's first real entry says /// how far into the media the presentation starts. /// /// corner-cut: an explicit `media_time` of 0 is taken at face value (no trim). /// Muxers that write a zero edit list despite a primed stream would leak the /// priming; upgrade path is preferring the codec delay when it disagrees. fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { edit_media_time(track) .and_then(|t| scale(t, sample_rate, track.timescale())) .unwrap_or(DEFAULT_PRIMING) } /// `media_time` of the edit list's first real entry, in the track's own /// timescale: where the presentation starts inside the media. `None` when there /// is no edit list, or only empty entries -- those shift the timeline rather /// than trim the media, and neither track honours that shift (see /// [`priming_samples`]'s corner-cut). Shared with `demux`, which owes the video /// track the same trim. pub(crate) fn edit_media_time(track: &Mp4Track) -> Option { track .trak .edts .as_ref() .and_then(|edts| edts.elst.as_ref()) .and_then(|elst| { elst.entries .iter() .map(|e| e.media_time) .find(|&t| t != EMPTY_EDIT && t != u64::MAX) }) } /// `value` from the track timescale into samples-per-channel. `None` on a zero /// timescale, which would be a broken header. fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option { let timescale = u64::from(timescale); (timescale != 0).then(|| value * u64::from(sample_rate) / timescale) } /// Inverse of [`scale`]: samples-per-channel back into the track timescale. fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 { match sample_rate { 0 => 0, rate => samples * u64::from(timescale) / u64::from(rate), } } /// The 1-based packet holding media time `target_ts`, walked back by `pre_roll` /// packets, plus that packet's own start time. Inverse of the mp4 crate's /// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is /// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs. /// /// corner-cut: the walk-back is clamped to the start of the containing stts entry /// rather than crossing into the previous one, so a target within `pre_roll` /// packets of an entry boundary gets less pre-roll. AAC packets are uniformly /// 1024 frames (one entry per track), so this cannot fire here; upgrade path is /// carrying the previous entry's delta through the walk. pub(crate) fn packet_at( entries: impl IntoIterator, target_ts: u64, pre_roll: u32, ) -> (u32, u64) { let mut first_id = 1u32; let mut elapsed = 0u64; let mut last = (1u32, 0u64); for (count, delta) in entries { let span = u64::from(count) * u64::from(delta); let index = if target_ts < elapsed + span && delta != 0 { ((target_ts - elapsed) / u64::from(delta)) as u32 } else { // Past this entry: remember its last packet in case the target runs // past the end of the track entirely. last = ( first_id + count.saturating_sub(1), elapsed + span.saturating_sub(u64::from(delta)), ); first_id += count; elapsed += span; continue; }; let index = index - index.min(pre_roll); return ( first_id + index, elapsed + u64::from(index) * u64::from(delta), ); } last } /// One window of a source to decode, resolved to media samples and packets — /// or, with no source, a stretch of synthesised silence. struct Segment { /// Index into the worker's tracks; the media positions below are that /// source's, not the timeline's. `None` for a gap, where only the length /// (`media_end`) means anything. source: Option, /// First packet to feed the decoder, 1-based; includes the pre-roll. start_id: u32, /// Media position of `start_id`'s first frame, in samples-per-channel. start_pos: u64, /// Media position of the first frame to emit. Everything decoded before it /// is pre-roll, priming, or seek overshoot, and gets dropped. media_target: u64, /// One past the last frame to emit; `u64::MAX` for "to the end of track". media_end: u64, } impl Segment { /// `frames` per channel of silence — a gap in the audio lane. fn silence(frames: u64) -> Self { Self { source: None, start_id: 0, start_pos: 0, media_target: 0, media_end: frames, } } } /// One segment's rate conversion: the decoded samples read at the ratio of /// the source's own sample rate to the timeline's, which is a pure rate /// conversion -- the pitch is preserved because the frames are read at the /// ratio of the rates rather than dropped, and 48 kHz onto a 44.1 kHz /// timeline is one resampler, not two. Linear interpolation between the two /// frames a fractional position falls between -- one multiply-add per /// channel, which is nothing beside the decode that produced them, and for a /// 48:44.1 ratio its worst-case image lands ~40 dB down; the alternative is /// a windowed-sinc kernel and a new state machine for a conversion that is /// not the audible risk in this path. /// /// It lives across the whole segment: `pos` carries the fraction over a packet /// boundary and `tail` keeps the frame before the buffer, so the interpolation /// at the seam is the same one it would have been inside a buffer. A segment /// starts one clean and drops it at the end, which is what makes a seek a /// reset for free -- exactly as the equalizer's state does. /// /// Time is no longer this struct's business: a clip whose own /// [`Speed`](crate::project::Speed) is not real time is re-timed by the /// [`TimeStretch`] behind it in its [`Rate`] chain, which compresses or /// stretches the timeline while keeping every period of the signal its own /// length -- this hands it a pitch-true stream at the timeline's rate and /// that is the whole of the hand-off. /// /// `owed` is what the timeline gives the segment, in frames per channel: /// resampling resolves to whole samples and a clip's own window resolves to /// whole *source* frames, so the two miss each other by a sample or two per /// clip. Truncating and padding to what is owed keeps that from accumulating /// into audible drift over a timeline of rate-mismatched cuts -- the picture's /// clip boundaries are exact by construction, and this makes the sound's /// exact too. struct Resample { /// Source frames per output frame: the ratio of the two sample rates. step: f64, /// Where the next output frame reads, relative to the current buffer's /// first frame. Negative means it reads across the seam, into `tail`. pos: f64, /// The last frame of the buffer before this one, one sample per channel. tail: Vec, /// Output frames per channel still to be emitted for this segment, or /// [`Resample::UNBOUNDED`] for a window with no end of its own -- what /// [`AudioSession::open_at`] asks for, where the source running out is the /// end and there is no shortfall to pad. owed: u64, } impl Resample { /// "As many as the source has": a segment ending at `f64::INFINITY` owes the /// timeline nothing it did not decode. const UNBOUNDED: u64 = u64::MAX; fn new(step: f64, owed: u64) -> Self { Self { step, pos: 0., tail: Vec::new(), owed, } } /// Rewrites `buf` in place as the frames this rate reads out of it. Never /// more than is owed, so the segment cannot overrun the room the timeline /// gave it. fn process(&mut self, buf: &mut Vec, channels: usize) { let frames = buf.len() / channels; if frames == 0 || channels == 0 { return; } let mut out: Vec = Vec::with_capacity(buf.len()); while self.owed > (out.len() / channels) as u64 { let left = self.pos.floor(); let right = left as i64 + 1; if right > frames as i64 - 1 { break; // the frame it would interpolate towards is not here yet } let frac = (self.pos - left) as f32; let (left, right) = (left as i64, right as usize); for c in 0..channels { // Before the buffer means the previous one's last frame; at the // very first buffer of a segment `pos` is 0, so this cannot be // asked for an empty tail. let a = match left < 0 { true => self.tail.get(c).copied().unwrap_or(0.), false => buf[left as usize * channels + c], }; let b = buf[right * channels + c]; out.push(a + (b - a) * frac); } self.pos += self.step; } self.tail.clear(); self.tail.extend_from_slice(&buf[(frames - 1) * channels..]); self.pos -= frames as f64; if self.owed != Self::UNBOUNDED { self.owed -= (out.len() / channels) as u64; } *buf = out; } /// The silence the segment still owes when its source ran out before the /// timeline did -- a rounding frame or two, or a clip whose file is shorter /// than the edit says. `false` means the consumer went away. fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender) -> bool { if self.owed == Self::UNBOUNDED { return true; // nothing was promised, so nothing is short } while self.owed > 0 { let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET)); let chunk = AudioChunk { start_sample: *timeline, samples: vec![0.0; frames as usize * channels], }; if tx.send(chunk).is_err() { return false; } *timeline += frames; self.owed -= frames; } true } } /// One speeded-or-converted segment's whole rate chain: the resample that /// turns the source's own rate into the timeline's, and -- only for a clip /// whose [`Speed`](crate::project::Speed) is not real time -- the stretch /// that changes its *time* without touching its pitch, after the resample /// and before the equalizer sees a sample (the filter's bands are set in the /// frequency a listener hears, and after a stretch that is still the /// frequency the file was written at). /// /// Which half owns the segment's promise depends on which halves there are: /// a rate conversion alone is paced by the resample, as it always was, and a /// speeded clip's resample runs unbounded (the ratio is all it is asked for) /// while the stretch lands the timeline's frames exactly. struct Rate { resample: Resample, stretch: Option, } impl Rate { fn process(&mut self, buf: &mut Vec, channels: usize) { self.resample.process(buf, channels); if let Some(stretch) = self.stretch.as_mut() { stretch.process(buf, channels); } } fn flush( &mut self, channels: usize, timeline: &mut u64, tx: &SyncSender, ) -> bool { match self.stretch.as_mut() { Some(stretch) => stretch.flush(channels, timeline, tx), None => self.resample.flush(channels, timeline, tx), } } } struct Worker { /// Indexed by [`Segment::source`]; only the sources some segment names are /// `Some`, the rest were never opened. tracks: Vec>, channels: usize, segments: Vec, /// One per entry of `segments`, in the same order: the filter that segment's /// samples pass through on the way out, or `None` for one that plays flat. /// Beside the segments rather than inside them so the emit path can hold the /// window rules and the filter memory at once without splitting a borrow. eqs: Vec>, /// One per entry of `segments` again: that segment's rate chain, or /// `None` for one at real time on the timeline's own rate -- which is /// every segment of a project nobody has speeded or rate-mismatched, and /// the path that emits the decoder's own samples untouched. speeds: Vec>, /// One per entry of `segments` again: that segment's gain envelope, or /// `None` for one that plays flat -- [`emit`]'s last effect, run after /// the rate and the equalizer. fades: Vec>, /// `start_sample` of the first chunk. timeline: u64, tx: SyncSender, } /// Sums one worker per lane into one stream (see /// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline /// position and synthesises its own gaps, so the lanes are sample-aligned by /// construction and a mix is an add: no resampling, no positioning, no drift to /// correct. What is emitted at each turn is the shortest block every still-live /// lane can supply, which keeps a slow lane from being outrun and never buffers /// more than the chunks already in flight. /// /// A lane whose channel has closed has ended and simply stops being added -- /// that is what "shorter lane" means here. The mix ends when all of them have. /// The accumulator is reused across turns; the one allocation per chunk is the /// buffer the channel takes ownership of, and none of this is the RT path (the /// device callback reads the ring the feeder has already filled). fn mix( rxs: &[Receiver], channels: usize, mut gains: Vec, mut limiter: Option, rate: u32, controls: Option<&MixControls>, tx: &SyncSender, ) { // The version of the mix these gains and this limiter came from; see the // reload at the head of the loop. let mut seen = 0; let mut pending: Vec> = rxs.iter().map(|_| Vec::new()).collect(); let mut live: Vec = rxs.iter().map(|_| true).collect(); // Numbering follows lane 0, whose first chunk says where it starts. let mut base = 0; let mut emitted = 0; let mut out: Vec = Vec::new(); loop { // A mix moved while the stream plays, picked up between two blocks: // the levels change at a block boundary and nothing else changes at // all -- no flush, no re-open, no hole. The limiter is *retuned* rather // than rebuilt, so its delay line keeps running and the sample count // the master clock is made of does not move ([`LimiterState::retune`]). if let Some((next, params)) = controls.and_then(|c| c.changed(&mut seen)) { gains = next; gains.resize(rxs.len(), 1.0); match limiter.as_mut() { Some(state) => state.retune(¶ms), // First time it has ever been switched in on this stream: the // one that swallows nothing, for the count's sake. None if params.is_active() => { limiter = Some(LimiterState::engaged(¶ms, rate, channels)); } None => {} } } for (i, rx) in rxs.iter().enumerate() { while live[i] && pending[i].is_empty() { match rx.recv() { Ok(chunk) => { if i == 0 && emitted == 0 { base = chunk.start_sample; } pending[i] = chunk.samples; } Err(_) => live[i] = false, } } } // The block every lane still playing can cover; `None` once they are all // done, which is the only way out of this loop besides a gone consumer. let Some(frames) = pending .iter() .filter(|p| !p.is_empty()) .map(|p| p.len() / channels) .min() .filter(|&f| f > 0) else { return; }; let block = frames * channels; out.clear(); out.resize(block, 0.0); for (i, lane) in pending .iter_mut() .enumerate() .filter(|(_, p)| !p.is_empty()) { // The lane's own volume, applied on its way into the sum: this is // the one place every lane's samples pass through, so a lane that // is turned down is turned down in an export exactly as it is in // the room. Unity is a multiply by 1.0, which f32 leaves alone. let gain = gains.get(i).copied().unwrap_or(1.0); for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) { *sum += sample * gain; } } // ...and the master limiter over the sum, before the clamp: what the // clamp used to catch by squaring it off is held under the ceiling // here instead ([`crate::limiter`]). Off, this is not even a branch // per sample. if let Some(limiter) = limiter.as_mut() { limiter.process(&mut out); } let frames = out.len() / channels; if frames == 0 { continue; // the limiter's delay line is still filling } let chunk = AudioChunk { start_sample: base + emitted, // Clamped, not wrapped: two lanes at full scale are what a mix has // to survive, and the device takes `[-1, 1]`. samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(), }; if tx.send(chunk).is_err() { return; // caller moved on } emitted += frames as u64; } } fn run(mut w: Worker) { let mut interleaved = Vec::new(); let channels = w.channels; // Chunk numbering is continuous across every join, source ones included. let mut timeline = w.timeline; let segments = std::mem::take(&mut w.segments); let mut eqs = std::mem::take(&mut w.eqs); // A short list is "flat from here on" (`open_multi_streams_eq`), which this // pads out so the zip below still walks every segment. eqs.resize_with(segments.len(), || None); let mut speeds = std::mem::take(&mut w.speeds); // ...and a short rate list is "real time from here on", for the same reason. speeds.resize_with(segments.len(), || None); let mut fades = std::mem::take(&mut w.fades); // ...and a short fade list is "flat from here on", the same rule again. fades.resize_with(segments.len(), || None); for (((seg, eq), speed), fade) in segments .iter() .zip(eqs.iter_mut()) .zip(speeds.iter_mut()) .zip(fades.iter_mut()) { let Some(source) = seg.source else { // A gap: hand the device real silence rather than nothing at all, // in the same packet-sized chunks decoding produces, so `fed` and // the master clock keep counting straight through the hole. let mut left = seg.media_end; while left > 0 { let frames = left.min(u64::from(SAMPLES_PER_PACKET)); let chunk = AudioChunk { start_sample: timeline, samples: vec![0.0; frames as usize * channels], }; if w.tx.send(chunk).is_err() { return; // caller moved on } timeline += frames; left -= frames; } continue; }; let Some(track) = w.tracks[source].as_mut() else { continue; // opener fills every named source; nothing to decode }; let track = match track { Track::Sym(track) => { if !run_sym( track, seg, eq.as_mut(), speed, fade, channels, &mut timeline, &w.tx, ) || !settle(speed, channels, &mut timeline, &w.tx) { return; // consumer went away } continue; } Track::Mkv(track) => { if !run_mkv_ac3( track, seg, eq.as_mut(), speed, fade, channels, &mut timeline, &w.tx, ) || !settle(speed, channels, &mut timeline, &w.tx) { return; // consumer went away } continue; } Track::Ac3(track) => { if !run_ac3( track, seg, eq.as_mut(), speed, fade, channels, &mut timeline, &w.tx, ) || !settle(speed, channels, &mut timeline, &w.tx) { return; // consumer went away } continue; } Track::Aac(track) => track, }; let mut decoder = match aac_decoder(&track.params, track.source_channels()) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); return; } }; let mut pos = seg.start_pos; for id in seg.start_id..=track.sample_count { if pos >= seg.media_end { break; // segment done, on to the next one } let sample = match track.reader.read_sample(track.track_id, id) { Ok(Some(sample)) => sample, Ok(None) => break, Err(e) => { eprintln!("audio demux error at sample {id}: {e}"); break; } }; let packet = Packet::new( track.track_id, units::Timestamp::new(sample.start_time as i64), units::Duration::new(u64::from(sample.duration)), &sample.bytes[..], ); if let Err(e) = decoder.decode(&packet, &mut interleaved) { eprintln!("audio decode error at sample {id}: {e}"); break; } // decoder.decode already folded to track.channels(); widen the mono // case up to the timeline's own width before dividing by it below. widen(&mut interleaved, usize::from(track.channels()), channels); let next = pos + (interleaved.len() / channels) as u64; if !emit( &mut interleaved, channels, seg, eq.as_mut(), speed.as_mut(), fade.as_mut(), pos, next, &mut timeline, &w.tx, ) { return; // consumer went away } pos = next; } if !settle(speed, channels, &mut timeline, &w.tx) { return; // consumer went away } } } /// Pays out whatever silence a speeded segment still owes the timeline (see /// [`Resample::flush`]). Nothing at all at real time, where a segment owes the /// timeline only the samples it decoded. fn settle( speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, ) -> bool { match speed { Some(speed) => speed.flush(channels, timeline, tx), None => true, } } /// Trims one decoded buffer to the segment window and sends what survives. /// `pos` is the media position of its first frame and `next` of the one after /// it; both readers hand the same thing here, which is why the window rules /// live in one place. `false` means the consumer went away. /// /// Everything before the target is encoder priming and/or decoder pre-roll, not /// audio the caller asked for: it is dropped, splitting the buffer that /// straddles the target. The tail past the segment end goes too — on a short /// segment that is this same buffer, trimmed at both ends. /// /// The segment's equalizer runs here, on the trimmed buffer and nowhere else: /// this is the one place both readers hand their samples over, so playback and /// an audio export get the same filtered stream by construction rather than by /// two call sites agreeing. Trimmed first, so the pre-roll a listener never /// hears cannot ring the filter either. Nothing is allocated -- the device /// callback is two hand-offs downstream of here in any case. fn emit( interleaved: &mut Vec, channels: usize, seg: &Segment, eq: Option<&mut EqState>, speed: Option<&mut Rate>, fade: Option<&mut crate::project::Fade>, pos: u64, next: u64, timeline: &mut u64, tx: &SyncSender, ) -> bool { if next <= seg.media_target { return true; } let mut pos = pos; if pos < seg.media_target { interleaved.drain(..(seg.media_target - pos) as usize * channels); pos = seg.media_target; } if next > seg.media_end { interleaved.truncate((seg.media_end - pos) as usize * channels); } if interleaved.is_empty() { return true; // nothing left of it; the loop head ends the segment } // The rate first, the filter second: what the equalizer's bands are set in // is the frequency a listener hears, and after a resample that is not the // frequency the file was written at. A segment at real time has no // resampler at all and reaches the filter with the decoder's own samples. if let Some(speed) = speed { speed.process(interleaved, channels); if interleaved.is_empty() { return true; // this buffer resolved to no output frame of its own } } if let Some(eq) = eq { eq.process(interleaved); } // The fade last, on the same output-rate samples the mix will hear: its // frame counts are timeline frames ([`crate::project::Clip::fade_in`]), // which is what a resample has already turned these into. The state // walks forward with the segment across as many buffers as decoding // takes, exactly as the equalizer's does. if let Some(fade) = fade { fade.apply(interleaved, channels); fade.elapsed = fade.elapsed.saturating_add((interleaved.len() / channels) as u32); } let chunk = AudioChunk { start_sample: *timeline, samples: std::mem::take(interleaved), }; *timeline += (chunk.samples.len() / channels) as u64; tx.send(chunk).is_ok() } /// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids /// come out of the same mp4 tables, the window rules are [`emit`]'s as always, /// and what reaches the mixer is already the stereo downmix. `false` means the /// consumer went away. fn run_ac3( track: &mut Ac3Track, seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, ) -> bool { let mut decoder = match ac3_decoder("ac3", track.requested) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); return true; } }; let mut pos = seg.start_pos; for id in seg.start_id..=track.sample_count { if pos >= seg.media_end { return true; // segment done, on to the next one } let sample = match track.reader.read_sample(track.track_id, id) { Ok(Some(sample)) => sample, Ok(None) => return true, Err(e) => { eprintln!("audio demux error at sample {id}: {e}"); return true; } }; let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) { Ok(Some(decoded)) => decoded, Ok(None) => continue, // the decoder wants another frame first Err(e) => { eprintln!("audio decode error at sample {id}: {e}"); return true; } }; // The library's §7.8 downmix already handles everything but its own 2.1 // passthrough, which comes out at 3 and is folded here like any width. downmix(&mut interleaved, usize::from(track.channels)); widen(&mut interleaved, usize::from(track.channels), channels); let next = pos + samples; if !emit( &mut interleaved, channels, seg, eq.as_deref_mut(), speed.as_mut(), fade.as_mut(), pos, next, timeline, tx, ) { return false; } pos = next; } true } /// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks /// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the /// stereo downmix are the same ones; only where a packet comes from differs. /// `false` means the consumer went away. fn run_mkv_ac3( track: &mut MkvAc3Track, seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, ) -> bool { let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); return true; } }; let mut pos = seg.start_pos; for id in seg.start_id as usize.. { if pos >= seg.media_end { return true; // segment done, on to the next one } let block = match track.mkv.frame(id) { Ok(Some(bytes)) => bytes, Ok(None) => return true, // end of the track Err(e) => { eprintln!("audio demux error at block {id}: {e}"); return true; } }; let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) { Ok(Some(decoded)) => decoded, Ok(None) => continue, // the decoder wants another frame first Err(e) => { eprintln!("audio decode error at block {id}: {e}"); return true; } }; // ...and the 2.1 passthrough folded here, as on the mp4 side. downmix(&mut interleaved, usize::from(track.channels)); widen(&mut interleaved, usize::from(track.channels), channels); let next = pos + samples; if !emit( &mut interleaved, channels, seg, eq.as_deref_mut(), speed.as_mut(), fade.as_mut(), pos, next, timeline, tx, ) { return false; } pos = next; } true } /// One segment of a standalone audio file: seek the reader to just before the /// window, then decode forward until the window is filled. /// /// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the /// target is thrown away by [`emit`], which is what gives a codec with decoder /// state — mp3's bit reservoir above all — something to warm up on, exactly as /// the AAC path's two-packet pre-roll does. A reader that cannot seek at all /// simply decodes from wherever it is; the window rules still hold, it is only /// slower. `false` means the consumer went away. fn run_sym( track: &mut SymTrack, seg: &Segment, mut eq: Option<&mut EqState>, speed: &mut Option, fade: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, ) -> bool { let mut decoder = match track.decoder() { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); return true; } }; track.seek_to(seg.media_target); let mut interleaved = Vec::new(); // Media position of the next frame to decode: the landing for the first // packet, and the decoder's own count from there on. A packet's timestamp // cannot carry it, because the frames of one laced block all share the // block's -- accumulating is what both mp4 readers here already do. let mut at: Option = None; loop { let packet = match track.reader.next_packet() { Ok(Some(packet)) => packet, Ok(None) => return true, // end of the file, and of the segment Err(e) => { eprintln!("audio demux error: {e}"); return true; } }; if packet.track_id != track.track_id { continue; // another track of the same container } let pos = *at.get_or_insert_with(|| track.samples_at(packet.pts)); if pos >= seg.media_end { return true; // segment done, on to the next one } if let Err(e) = decoder.decode(&packet, &mut interleaved) { eprintln!("audio decode error at sample {pos}: {e}"); return true; } // decoder.decode already folded to track.channels ([`SymDecoder::decode`], // [`downmix`]); widen the mono case up to the timeline's own width // before anything below divides by it. widen(&mut interleaved, usize::from(track.channels), channels); let next = pos + (interleaved.len() / channels) as u64; at = Some(next); // Reborrowed per packet: the filter memory has to carry across the // packet boundary, so this is one `EqState` for the whole segment. if !emit( &mut interleaved, channels, seg, eq.as_deref_mut(), speed.as_mut(), fade.as_mut(), pos, next, timeline, tx, ) { return false; } } } #[cfg(test)] mod tests { use super::{PRE_ROLL, SAMPLES_PER_PACKET, downmix, packet_at, packet_run, vorbis_to_film_order}; const C: f32 = std::f32::consts::FRAC_1_SQRT_2; /// The fold, channel by channel and width by width: each side keeps its own /// front channel, takes the centre and its own surrounds at -3 dB, drops the /// LFE, and comes out unable to clip a full-scale source. The channel order /// is FL, FR, FC, LFE, BL, BR, SL, SR. #[test] fn a_surround_frame_folds_to_stereo_without_clipping() { // Per width: what each channel at full scale, alone, must land as // *before* the normalisation that width carries. let layouts: [(usize, &[(f32, f32)]); 6] = [ (3, &[(1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]), (4, &[(1.0, 0.0), (0.0, 1.0), (C, 0.0), (0.0, C)]), (5, &[(1.0, 0.0), (0.0, 1.0), (C, C), (C, 0.0), (0.0, C)]), ( 6, &[(1.0, 0.0), (0.0, 1.0), (C, C), (0.0, 0.0), (C, 0.0), (0.0, C)], ), ( 7, &[ (1.0, 0.0), (0.0, 1.0), (C, C), (0.0, 0.0), (C, C), (C, 0.0), (0.0, C), ], ), ( 8, &[ (1.0, 0.0), (0.0, 1.0), (C, C), (0.0, 0.0), (C, 0.0), (0.0, C), (C, 0.0), (0.0, C), ], ), ]; for (from, want) in layouts { let (nl, nr) = want .iter() .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1)); for (channel, &(left, right)) in want.iter().enumerate() { let mut frame = vec![0.0f32; from]; frame[channel] = 1.0; downmix(&mut frame, from); assert_eq!(frame.len(), 2, "{from} ch: one frame is one stereo frame"); assert!( (frame[0] - left / nl).abs() < 1e-6 && (frame[1] - right / nr).abs() < 1e-6, "{from} ch{channel}: {frame:?}, want {left}/{nl} {right}/{nr}" ); } // Every channel at once is what a normalised fold exists for. let mut loud = vec![1.0f32; from * 2]; downmix(&mut loud, from); assert_eq!(loud.len(), 4, "{from} ch: two frames out of two"); assert!( loud.iter().all(|s| (*s - 1.0).abs() < 1e-6), "{from} ch: full scale in, full scale out, never past it: {loud:?}" ); } // Mono and stereo are handed over untouched. for from in [1, 2] { let mut flat = vec![0.5f32, -0.5]; downmix(&mut flat, from); assert_eq!(flat, [0.5, -0.5], "{from} ch is not a fold"); } } /// The Vorbis order an Opus surround stream is stored in, into the film /// order the fold reads. Each channel is its own index, so a permutation /// that drifts is the value that comes out in the wrong slot. #[test] fn vorbis_order_becomes_film_order() { // (width, film slot -> the vorbis channel it must hold) for (from, want) in [ (3usize, &[0, 2, 1][..]), (5, &[0, 2, 1, 3, 4]), (6, &[0, 2, 1, 5, 3, 4]), (7, &[0, 2, 1, 6, 5, 3, 4]), (8, &[0, 2, 1, 7, 5, 6, 3, 4]), ] { // Two frames, so a permutation that reads across the frame boundary // shows up as the wrong frame's value. let mut samples: Vec = (0..from * 2).map(|i| i as f32).collect(); vorbis_to_film_order(&mut samples, from); let got: Vec = samples[..from].iter().map(|&s| s as usize).collect(); assert_eq!(got, want, "{from} ch, first frame"); let second: Vec = samples[from..].iter().map(|&s| s as usize - from).collect(); assert_eq!(second, want, "{from} ch, second frame"); } // 7.1's LFE is the last vorbis channel and the fourth film one. let mut lfe = vec![0.0f32; 8]; lfe[7] = 1.0; vorbis_to_film_order(&mut lfe, 8); assert_eq!(lfe[3], 1.0, "the LFE lands where the fold drops it: {lfe:?}"); } /// A real AAC track: one stts entry, N packets of 1024. fn aac(count: u32) -> impl IntoIterator { [(count, 1024)] } #[test] fn packet_at_walks_back_by_the_pre_roll() { // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..). assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064)); assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016)); // Exactly on a packet boundary is the start of that packet, not the end // of the previous one. assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048)); } #[test] fn packet_at_clamps_both_ends() { // Head: no room for the walk-back, and packet ids are 1-based. assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0)); assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0)); // Past the end: the last packet, so the worker decodes ~nothing. assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776)); // Degenerate boxes must not panic or wrap. assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0)); assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0)); } #[test] fn packet_at_crosses_stts_entries() { // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240 // with packet 11. let entries = [(10u32, 1024u32), (10, 512)]; assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288)); assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264)); // The corner-cut clamp: on the first packet of the second entry the // walk-back stops there instead of stepping into the first entry. assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240)); } /// xorshift64: adversarial segment lists do not deserve a dependency. fn rng(state: &mut u64) -> u64 { *state ^= *state << 13; *state ^= *state >> 7; *state ^= *state << 17; *state } #[test] fn packet_run_keeps_cumulative_error_under_a_packet() { let packet = i64::from(SAMPLES_PER_PACKET); let mut state = 0x5eed_1234_9876_abcd; for rate in [44100i64, 48000] { for list in 0..100 { let (mut err, mut asked, mut copied) = (0i64, 0i64, 0i64); // 3..43 joins of anything from one video frame to four seconds. for join in 0..3 + rng(&mut state) % 40 { let ideal = rate / 30 + (rng(&mut state) % (4 * rate as u64)) as i64; copied += i64::from(packet_run(&mut err, ideal, u32::MAX)); asked += ideal; assert!( err.abs() < packet, "rate {rate} list {list} join {join}: err {err}" ); } // The accumulator is the whole story: what it says is the drift. assert_eq!(copied * packet - asked, err); } } } #[test] fn packet_run_rounds_against_the_running_debt() { // One second at 44100 is 43.07 packets: copying 43 leaves 68 samples // owed, and the debt is repaid by a 44-packet second once it crosses a // half packet — never by letting each second round on its own. let mut err = 0; assert_eq!(packet_run(&mut err, 44100, u32::MAX), 43); assert_eq!(err, -68); let mut seconds = 1; while packet_run(&mut err, 44100, u32::MAX) == 43 { seconds += 1; assert!(seconds < 20, "debt never repaid, err {err}"); } assert_eq!(seconds, 7, "68 samples a second, half a packet is 512"); assert!(err > 0, "the repaying second overshoots, err {err}"); } #[test] fn packet_run_forgives_a_debt_the_track_cannot_pay() { // Asking a second of a track with ten packets left: it delivers ten and // does not make the next segment copy the shortfall from elsewhere. let mut err = 0; assert_eq!(packet_run(&mut err, 44100, 10), 10); assert_eq!(err, 0); // Degenerate windows are empty, not negative. assert_eq!(packet_run(&mut err, 0, 10), 0); assert_eq!(packet_run(&mut err, i64::MAX, 7), 7); } #[test] fn asc_round_trips_aac_lc_44100_stereo() { // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo). let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8); let asc = [ (profile << 3) | (freq_index >> 1), (freq_index << 7) | (chan_conf << 3), ]; assert_eq!(asc, [0x12, 0x10]); } /// The one claim worth making about a hand-written bitstream: our own /// decoder turns it into exactly one packet of exactly zero. #[test] fn a_silent_packet_decodes_to_a_packet_of_zero() { use super::{AacDecoder, AudioDecoder, AudioDecoderOptions, silent_packet}; use symphonia_core::codecs::audio::{AudioCodecParameters, well_known::CODEC_ID_AAC}; use symphonia_core::{packet::Packet, units}; for (chan_conf, channels) in [(1u8, 1usize), (2, 2)] { // AAC-LC (profile 2), 44100 (freq_index 4), `chan_conf` channels. let asc: Box<[u8]> = Box::new([(2 << 3) | (4 >> 1), (4 << 7) | (chan_conf << 3)]); let mut params = AudioCodecParameters::new(); params .for_codec(CODEC_ID_AAC) .with_sample_rate(44100) .with_extra_data(asc); let mut decoder = AacDecoder::try_new(¶ms, &AudioDecoderOptions::default()).expect("decoder"); let bytes = silent_packet(chan_conf).expect("silence"); let packet = Packet::new( 0, units::Timestamp::new(0), units::Duration::new(u64::from(SAMPLES_PER_PACKET)), &bytes[..], ); let buf = decoder.decode(&packet).expect("decodes as AAC-LC"); let mut out = Vec::new(); buf.copy_to_vec_interleaved::(&mut out); assert_eq!(out.len(), SAMPLES_PER_PACKET as usize * channels); assert!( out.iter().all(|&s| s == 0.0), "{chan_conf} ch is not silent" ); } assert!( silent_packet(6).is_err(), "beyond stereo is refused, not faked" ); } }