diff --git a/crates/media/src/audio.rs b/crates/media/src/audio.rs index 9f4ab3275..43d8dac48 100644 --- a/crates/media/src/audio.rs +++ b/crates/media/src/audio.rs @@ -7,9 +7,9 @@ use std::io::Cursor; use symphonia::core::audio::SampleBuffer; -use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions}; +use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions}; use symphonia::core::errors::Error as SymError; -use symphonia::core::formats::FormatOptions; +use symphonia::core::formats::{FormatOptions, Track}; use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions}; use symphonia::core::meta::MetadataOptions; use symphonia::core::probe::Hint; @@ -172,6 +172,21 @@ fn contained(f: impl FnOnce() -> Result) -> Result { const MAX_DEMUX_ERRORS: u32 = 64; fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result { + decode_symphonia_capped(bytes, ext, MAX_PCM_SAMPLES) +} + +/// The track playback decodes, with its decoder: the first one a decoder can be made for (a +/// video's audio track follows its video track). The duration probe measures the same track. +fn playable_track(tracks: &[Track]) -> Option<(u32, Box)> { + let codecs = symphonia::default::get_codecs(); + tracks + .iter() + .filter(|t| t.codec_params.codec != CODEC_TYPE_NULL) + .find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d))) +} + +/// [`decode_symphonia`] stopping once `max_samples` samples have been decoded. +fn decode_symphonia_capped(bytes: &Bytes, ext: &str, max_samples: usize) -> Result { let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default()); let mut hint = Hint::new(); match ext { @@ -189,14 +204,7 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result { other => sym_err(other), })?; let mut format = probed.format; - let codecs = symphonia::default::get_codecs(); - // The first track we can decode (a video's audio track follows its video track). - let (track_id, mut decoder) = format - .tracks() - .iter() - .filter(|t| t.codec_params.codec != CODEC_TYPE_NULL) - .find_map(|t| codecs.make(&t.codec_params, &DecoderOptions::default()).ok().map(|d| (t.id, d))) - .ok_or(MediaError::Missing("audio track we can decode"))?; + let (track_id, mut decoder) = playable_track(format.tracks()).ok_or(MediaError::Missing("audio track we can decode"))?; let mut out: Vec = Vec::new(); let mut rate = 0; let mut channels = 0u16; @@ -245,7 +253,15 @@ fn decode_symphonia(bytes: &Bytes, ext: &str) -> Result { } if let Some(b) = buf.as_mut() { b.copy_interleaved_ref(decoded); - out.extend_from_slice(b.samples()); + // stop at the cap with whole frames, keeping what fits, like the Opus paths + let room = max_samples.saturating_sub(out.len()); + let s = b.samples(); + if s.len() > room { + let fit = room - room % (ch.max(1) as usize); + out.extend_from_slice(s.get(..fit).unwrap_or_default()); + break; + } + out.extend_from_slice(s); } } Err(SymError::DecodeError(e)) => log::debug!("audio decode: {e}"), @@ -280,6 +296,48 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32, Some((name, p.sample_rate.unwrap_or(0), p.channels.map(|c| c.count() as u16).unwrap_or(0), p.n_frames)) } +/// Length in milliseconds of the track playback decodes, summed from its packet durations: the +/// file is demuxed but not decoded. `None` when the demuxer reports no durations. +pub(crate) fn demux_duration_ms(bytes: &Bytes, ext: &str) -> Option { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default()); + let mut hint = Hint::new(); + if ext != "unknown" { + hint.with_extension(ext); + } + let opts = FormatOptions { enable_gapless: true, ..Default::default() }; + let mut format = symphonia::default::get_probe().format(&hint, mss, &opts, &MetadataOptions::default()).ok()?.format; + let (id, _) = playable_track(format.tracks())?; + let tb = format.tracks().iter().find(|t| t.id == id)?.codec_params.time_base?; + let mut ticks = 0u64; + let mut errors = 0u32; + loop { + match format.next_packet() { + Ok(p) => { + errors = 0; + if p.track_id() == id { + ticks = ticks.saturating_add(p.dur); + } + } + Err(SymError::DecodeError(_)) => { + errors += 1; + if errors > MAX_DEMUX_ERRORS { + break; + } + } + Err(_) => break, + } + } + if ticks == 0 { + return None; + } + let t = tb.calc_time(ticks); + Some(t.seconds.saturating_mul(1000).saturating_add((t.frac * 1000.0).round() as u64)) + })) + .ok() + .flatten() +} + /// Interleaved PCM resampled (linear) to `rate`. pub fn resample(pcm: &Pcm, rate: u32) -> Pcm { if pcm.rate == rate || pcm.rate == 0 || rate == 0 { @@ -316,6 +374,43 @@ mod tests { assert!((r.at(101, 0) - 0.505).abs() < 1e-3); } + /// A long decode stops at the sample cap and keeps what it has, like the Opus paths, so audio + /// past the cap still plays (up to the cap) instead of failing. + #[test] + fn decode_stops_at_the_sample_cap() { + let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default()); + let full = decode_symphonia_capped(&b, "aac", usize::MAX).unwrap(); + let capped = decode_symphonia_capped(&b, "aac", 1001).unwrap(); + assert!(full.samples.len() > 1001, "the fixture is longer than the cap"); + assert!(!capped.samples.is_empty() && capped.samples.len() <= 1001, "{}", capped.samples.len()); + assert_eq!(capped.samples.len() % capped.channels as usize, 0, "whole frames only"); + assert_eq!(capped.samples[..], full.samples[..capped.samples.len()], "the start is kept as decoded"); + } + + /// The duration is measured on the track playback decodes: the first one a decoder can be made + /// for, not the first one with any codec. + #[test] + fn duration_and_playback_pick_the_same_track() { + use symphonia::core::audio::Channels; + use symphonia::core::codecs::{CODEC_TYPE_AAC, CODEC_TYPE_OPUS, CodecParameters}; + let stereo = Channels::FRONT_LEFT | Channels::FRONT_RIGHT; + let mut opus = CodecParameters::new(); + opus.for_codec(CODEC_TYPE_OPUS).with_sample_rate(48_000).with_channels(stereo); + let mut aac = CodecParameters::new(); + aac.for_codec(CODEC_TYPE_AAC).with_sample_rate(44_100).with_channels(stereo); + let tracks = [Track::new(1, opus), Track::new(2, aac)]; + // the first track has a codec but no decoder in this build (Symphonia has no Opus decoder) + assert_ne!(tracks[0].codec_params.codec, CODEC_TYPE_NULL); + assert_eq!(playable_track(&tracks).map(|(id, _)| id), Some(2)); + } + + #[test] + fn demux_duration_matches_decoded_length() { + let b: Bytes = std::sync::Arc::new(std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tone.aac")).unwrap_or_default()); + let ms = demux_duration_ms(&b, "aac").unwrap_or(0) as i64; + assert!((ms - 500).abs() <= 60, "{ms} ms"); + } + #[test] fn wma_is_reported_unsupported() { let mut b = crate::ASF_HEADER.to_vec(); diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 5a7da2aee..03b7b4f64 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -1,5 +1,5 @@ //! Media probing: container, duration, audio and video stream parameters — without decoding -//! (except for audio files whose container doesn't state a length). +//! (audio files whose container doesn't state a length are demuxed, not decoded). use crate::video::{codec_name, mkv_codec_name}; use crate::{ASF_HEADER, Bytes, Container, MediaError, Result}; @@ -50,9 +50,10 @@ fn ms(secs: f64) -> u64 { pub fn probe(bytes: &Bytes) -> Result { let mut info = probe_headers(bytes)?; if info.duration_ms == 0 && info.audio.as_ref().is_some_and(|a| a.decodable) && info.video.is_none() { - // No length in the header (raw MP3 / ADTS without an index): decode to measure. - if let Ok(pcm) = crate::audio::decode(bytes) { - info.duration_ms = ms(pcm.duration()); + // No length in the header (raw MP3 / ADTS without an index): add up the packet + // lengths. This only demuxes, so a long file neither allocates its PCM nor stalls the caller. + if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) { + info.duration_ms = d; } } Ok(info)