Every audio stream is listed, and any one of them opens
Browse files at this commitdff7d843f3d0fedec086d9c2e7e2b68304835ed5Parent: 771cd4a- feat
- every audio stream is listed, and any one of them opens
4 changed files +346 -16
- crates/engine/src/audio.rs +145 -15
- crates/engine/src/lib.rs +3 -1
- crates/engine/tests/audio_streams.rs +181 -0
- scripts/gen_fixtures.sh +17 -0
crates/engine/src/audio.rsmodified+145 -15
| @@ -8,7 +8,7 @@ use std::path::{Path, PathBuf}; | |||
| 8 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | 8 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 9 | use std::thread; | 9 | use std::thread; |
| 10 | 10 | ||
| 11 | -use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track}; | 11 | +use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; |
| 12 | use symphonia_codec_aac::AacDecoder; | 12 | use symphonia_codec_aac::AacDecoder; |
| 13 | use symphonia_core::codecs::audio::{ | 13 | use symphonia_core::codecs::audio::{ |
| 14 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, | 14 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, |
| @@ -73,6 +73,34 @@ pub struct AudioProbe { | |||
| 73 | pub channels: u16, | 73 | pub channels: u16, |
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | +/// One audio stream of a file as its header describes it. Every audio track is | ||
| 77 | +/// described, decodable or not: a picker shows the ones we refuse greyed out | ||
| 78 | +/// rather than pretending a BluRay remux has fewer streams than it has. | ||
| 79 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 80 | +pub struct StreamInfo { | ||
| 81 | + /// Position among this file's audio tracks in file order — the `stream` | ||
| 82 | + /// [`AudioSession::open_multi_streams`] takes. | ||
| 83 | + pub index: usize, | ||
| 84 | + /// Container codec. | ||
| 85 | + /// | ||
| 86 | + /// ponytail: mp4 0.14 parses `mp4a` sample entries and silently drops every | ||
| 87 | + /// other kind (`stsd.rs` `_ => {}`), keeping no fourcc, so an AC-3/DTS/PCM | ||
| 88 | + /// stream can only be `"unknown"` here — enough to grey a row out, not | ||
| 89 | + /// enough to name the codec. Upgrade path is reading the sample entry's | ||
| 90 | + /// fourcc out of the file ourselves. | ||
| 91 | + pub codec: String, | ||
| 92 | + /// `0` for a stream whose sample entry mp4 0.14 does not parse. | ||
| 93 | + pub channels: u16, | ||
| 94 | + /// `0` for a stream whose sample entry mp4 0.14 does not parse. | ||
| 95 | + pub sample_rate: u32, | ||
| 96 | + /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write. | ||
| 97 | + pub lang: Option<String>, | ||
| 98 | + /// Whether opening this stream would decode: AAC-LC, mono or stereo. The | ||
| 99 | + /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels` | ||
| 100 | + /// make one file at a time. | ||
| 101 | + pub decodable: bool, | ||
| 102 | +} | ||
| 103 | + | ||
| 76 | pub struct AudioSession; | 104 | pub struct AudioSession; |
| 77 | 105 | ||
| 78 | impl AudioSession { | 106 | impl AudioSession { |
| @@ -132,10 +160,24 @@ impl AudioSession { | |||
| 132 | sources: &[PathBuf], | 160 | sources: &[PathBuf], |
| 133 | segs: &[(Option<usize>, f64, f64)], | 161 | segs: &[(Option<usize>, f64, f64)], |
| 134 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 162 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 135 | - let Some(first) = sources.first() else { | 163 | + let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect(); |
| 164 | + Self::open_multi_streams(&sources, segs) | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + /// [`open_multi_segments`](Self::open_multi_segments) with each source | ||
| 168 | + /// naming *which* of its audio streams to decode — files carrying several | ||
| 169 | + /// (a remux with one track per language) are otherwise stuck on their first. | ||
| 170 | + /// The index counts audio tracks in file order, as | ||
| 171 | + /// [`probe_streams`](Self::probe_streams) lists them; a stream that does not | ||
| 172 | + /// exist or does not decode is an `Err` here, never a panic. | ||
| 173 | + pub fn open_multi_streams( | ||
| 174 | + sources: &[(PathBuf, usize)], | ||
| 175 | + segs: &[(Option<usize>, f64, f64)], | ||
| 176 | + ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | ||
| 177 | + let Some((path, stream)) = sources.first() else { | ||
| 136 | return Ok(None); | 178 | return Ok(None); |
| 137 | }; | 179 | }; |
| 138 | - let Some(first) = Track::open(first)? else { | 180 | + let Some(first) = Track::open(path, *stream)? else { |
| 139 | return Ok(None); | 181 | return Ok(None); |
| 140 | }; | 182 | }; |
| 141 | // The timeline's meta is the first source's: policy makes every other | 183 | // The timeline's meta is the first source's: policy makes every other |
| @@ -161,7 +203,8 @@ impl AudioSession { | |||
| 161 | if slot.is_some() { | 203 | if slot.is_some() { |
| 162 | continue; // already opened, and the checks below already ran | 204 | continue; // already opened, and the checks below already ran |
| 163 | } | 205 | } |
| 164 | - let track = Track::open(&sources[source])? | 206 | + let (path, stream) = &sources[source]; |
| 207 | + let track = Track::open(path, *stream)? | ||
| 165 | .ok_or_else(|| format!("source {source} has no audio track"))?; | 208 | .ok_or_else(|| format!("source {source} has no audio track"))?; |
| 166 | if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { | 209 | if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { |
| 167 | return Err(format!( | 210 | return Err(format!( |
| @@ -221,7 +264,7 @@ impl AudioSession { | |||
| 221 | /// `Ok(None)` means no AAC track — an audio-less file, which import pairs | 264 | /// `Ok(None)` means no AAC track — an audio-less file, which import pairs |
| 222 | /// only with other audio-less files. | 265 | /// only with other audio-less files. |
| 223 | pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> { | 266 | pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> { |
| 224 | - let Some(track) = Track::open(path.as_ref())? else { | 267 | + let Some(track) = Track::open(path.as_ref(), 0)? else { |
| 225 | return Ok(None); | 268 | return Ok(None); |
| 226 | }; | 269 | }; |
| 227 | Ok(Some(AudioProbe { | 270 | Ok(Some(AudioProbe { |
| @@ -230,6 +273,42 @@ impl AudioSession { | |||
| 230 | })) | 273 | })) |
| 231 | } | 274 | } |
| 232 | 275 | ||
| 276 | + /// Every audio stream of `path`, in file order: an entry's `index` is the | ||
| 277 | + /// stream number [`open_multi_streams`](Self::open_multi_streams) takes. | ||
| 278 | + /// Header only, no decoder and no worker — and no filtering either, so a | ||
| 279 | + /// stream this engine cannot decode is listed with `decodable: false` | ||
| 280 | + /// instead of vanishing. | ||
| 281 | + /// | ||
| 282 | + /// An empty list means the file has no audio at all, which is a valid | ||
| 283 | + /// silent source. | ||
| 284 | + pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { | ||
| 285 | + let file = File::open(path.as_ref())?; | ||
| 286 | + let size = file.metadata()?.len(); | ||
| 287 | + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; | ||
| 288 | + Ok(audio_track_ids(&reader) | ||
| 289 | + .into_iter() | ||
| 290 | + .enumerate() | ||
| 291 | + .map(|(index, id)| { | ||
| 292 | + let track = &reader.tracks()[&id]; | ||
| 293 | + let aac = matches!(track.media_type(), Ok(MediaType::AAC)); | ||
| 294 | + let lang = track.language(); | ||
| 295 | + StreamInfo { | ||
| 296 | + index, | ||
| 297 | + codec: if aac { "aac" } else { "unknown" }.into(), | ||
| 298 | + channels: track.channel_config().map_or(0, channel_count), | ||
| 299 | + sample_rate: track.sample_freq_index().map_or(0, |f| f.freq()), | ||
| 300 | + lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()), | ||
| 301 | + decodable: aac | ||
| 302 | + && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity)) | ||
| 303 | + && matches!( | ||
| 304 | + track.channel_config(), | ||
| 305 | + Ok(ChannelConfig::Mono | ChannelConfig::Stereo) | ||
| 306 | + ), | ||
| 307 | + } | ||
| 308 | + }) | ||
| 309 | + .collect()) | ||
| 310 | + } | ||
| 311 | + | ||
| 233 | /// The raw AAC packets covering `segs` — the same half-open source-second | 312 | /// The raw AAC packets covering `segs` — the same half-open source-second |
| 234 | /// windows [`open_segments`](Self::open_segments) decodes — copied out | 313 | /// windows [`open_segments`](Self::open_segments) decodes — copied out |
| 235 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go | 314 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go |
| @@ -284,7 +363,7 @@ impl AudioSession { | |||
| 284 | let path = sources | 363 | let path = sources |
| 285 | .get(first) | 364 | .get(first) |
| 286 | .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; | 365 | .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; |
| 287 | - let Some(track) = Track::open(path)? else { | 366 | + let Some(track) = Track::open(path, 0)? else { |
| 288 | return Ok(None); // silent source, silent export | 367 | return Ok(None); // silent source, silent export |
| 289 | }; | 368 | }; |
| 290 | let params = track.track_params(); | 369 | let params = track.track_params(); |
| @@ -375,6 +454,11 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> { | |||
| 375 | 454 | ||
| 376 | /// The source at `index`, opened on first use. Sources a segment list never | 455 | /// The source at `index`, opened on first use. Sources a segment list never |
| 377 | /// names are never touched: a project's list only grows. | 456 | /// names are never touched: a project's list only grows. |
| 457 | +/// | ||
| 458 | +/// ponytail: the copy path is still stream 0 of every source — an export of a | ||
| 459 | +/// timeline playing stream 1 would carry stream 0's audio. Upgrade path is the | ||
| 460 | +/// `(PathBuf, usize)` list [`AudioSession::open_multi_streams`] already takes, | ||
| 461 | +/// which is S4b's job once a stream can be picked at all. | ||
| 378 | fn source_at<'a>( | 462 | fn source_at<'a>( |
| 379 | tracks: &'a mut [Option<Track>], | 463 | tracks: &'a mut [Option<Track>], |
| 380 | sources: &[PathBuf], | 464 | sources: &[PathBuf], |
| @@ -385,7 +469,7 @@ fn source_at<'a>( | |||
| 385 | .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; | 469 | .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; |
| 386 | if slot.is_none() { | 470 | if slot.is_none() { |
| 387 | *slot = Some( | 471 | *slot = Some( |
| 388 | - Track::open(&sources[index])? | 472 | + Track::open(&sources[index], 0)? |
| 389 | .ok_or_else(|| format!("source {index} has no audio track"))?, | 473 | .ok_or_else(|| format!("source {index} has no audio track"))?, |
| 390 | ); | 474 | ); |
| 391 | } | 475 | } |
| @@ -415,19 +499,37 @@ struct Track { | |||
| 415 | } | 499 | } |
| 416 | 500 | ||
| 417 | impl Track { | 501 | impl Track { |
| 418 | - /// `Ok(None)` for a file with no AAC track, which is a valid silent source. | 502 | + /// The `stream`-th audio track of `path`, counted in file order over *all* |
| 419 | - fn open(path: &Path) -> crate::Result<Option<Self>> { | 503 | + /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out. |
| 504 | + /// | ||
| 505 | + /// Stream 0 is best effort: `Ok(None)` when there is no audio there at all | ||
| 506 | + /// or the codec is one we do not decode, which is a valid silent source (a | ||
| 507 | + /// file whose audio is AC-3 still has a picture worth editing). A stream the | ||
| 508 | + /// caller *named* is a promise instead, so out of range or undecodable | ||
| 509 | + /// there is an `Err` rather than silence the caller did not ask for. | ||
| 510 | + fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { | ||
| 420 | let file = File::open(path)?; | 511 | let file = File::open(path)?; |
| 421 | let size = file.metadata()?.len(); | 512 | let size = file.metadata()?.len(); |
| 422 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; | 513 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; |
| 423 | 514 | ||
| 424 | - let Some(track) = reader | 515 | + let ids = audio_track_ids(&reader); |
| 425 | - .tracks() | 516 | + let Some(track) = ids.get(stream).map(|id| &reader.tracks()[id]) else { |
| 426 | - .values() | 517 | + return match stream { |
| 427 | - .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) | 518 | + 0 => Ok(None), |
| 428 | - else { | 519 | + n => Err(format!( |
| 429 | - return Ok(None); | 520 | + "{}: audio stream {n} of {} streams", |
| 521 | + path.display(), | ||
| 522 | + ids.len() | ||
| 523 | + ) | ||
| 524 | + .into()), | ||
| 525 | + }; | ||
| 430 | }; | 526 | }; |
| 527 | + if !matches!(track.media_type(), Ok(MediaType::AAC)) { | ||
| 528 | + return match stream { | ||
| 529 | + 0 => Ok(None), | ||
| 530 | + n => Err(format!("{}: audio stream {n} is not AAC", path.display()).into()), | ||
| 531 | + }; | ||
| 532 | + } | ||
| 431 | // Refuse early with a message instead of failing packet by packet — and | 533 | // Refuse early with a message instead of failing packet by packet — and |
| 432 | // a copy carries no profile of its own: the writer rebuilds the | 534 | // a copy carries no profile of its own: the writer rebuilds the |
| 433 | // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a | 535 | // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a |
| @@ -529,6 +631,34 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { | |||
| 529 | n | 631 | n |
| 530 | } | 632 | } |
| 531 | 633 | ||
| 634 | +/// This file's audio tracks in file order — the order a stream index counts in. | ||
| 635 | +/// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a | ||
| 636 | +/// `HashMap`: iterating that would make "stream 0" a different track from one | ||
| 637 | +/// run to the next on any file carrying more than one. | ||
| 638 | +fn audio_track_ids<R>(reader: &Mp4Reader<R>) -> Vec<u32> { | ||
| 639 | + reader | ||
| 640 | + .moov | ||
| 641 | + .traks | ||
| 642 | + .iter() | ||
| 643 | + .filter(|trak| { | ||
| 644 | + matches!( | ||
| 645 | + TrackType::try_from(&trak.mdia.hdlr.handler_type), | ||
| 646 | + Ok(TrackType::Audio) | ||
| 647 | + ) | ||
| 648 | + }) | ||
| 649 | + .map(|trak| trak.tkhd.track_id) | ||
| 650 | + .collect() | ||
| 651 | +} | ||
| 652 | + | ||
| 653 | +/// Channels in an AAC channel configuration. The config number *is* the channel | ||
| 654 | +/// count up to 5.1; 7.1 is the one that is not. | ||
| 655 | +fn channel_count(config: ChannelConfig) -> u16 { | ||
| 656 | + match config { | ||
| 657 | + ChannelConfig::SevenOne => 8, | ||
| 658 | + other => other as u16, | ||
| 659 | + } | ||
| 660 | +} | ||
| 661 | + | ||
| 532 | /// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a | 662 | /// `(profile, freq_index, chan_conf)` out of the esds descriptor. Returned as a |
| 533 | /// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside | 663 | /// tuple because mp4 0.14's `DecoderSpecificDescriptor` is unnameable outside |
| 534 | /// the crate (same trap as `SttsEntry`, see [`packet_at`]). | 664 | /// the crate (same trap as `SttsEntry`, see [`packet_at`]). |
crates/engine/src/lib.rsmodified+3 -1
| @@ -14,7 +14,9 @@ pub mod playback; | |||
| 14 | pub mod project; | 14 | pub mod project; |
| 15 | pub mod waveform; | 15 | pub mod waveform; |
| 16 | 16 | ||
| 17 | -pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession}; | 17 | +pub use audio::{ |
| 18 | + AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo, | ||
| 19 | +}; | ||
| 18 | pub use clock::PlaybackClock; | 20 | pub use clock::PlaybackClock; |
| 19 | pub use decode::{DecodeSession, Frame}; | 21 | pub use decode::{DecodeSession, Frame}; |
| 20 | pub use demux::VideoMeta; | 22 | pub use demux::VideoMeta; |
crates/engine/tests/audio_streams.rsadded+181 -0
| @@ -0,0 +1,181 @@ | |||
| 1 | +//! Files carry more than one audio track — a remux has one per language — so | ||
| 2 | +//! the engine has to *list* them all and open the one it is asked for, instead | ||
| 3 | +//! of taking whichever AAC track it stumbles on first. | ||
| 4 | + | ||
| 5 | +use std::path::PathBuf; | ||
| 6 | + | ||
| 7 | +use engine::audio::{AudioSession, StreamInfo}; | ||
| 8 | + | ||
| 9 | +/// Three audio streams: 0 is AAC 44.1k stereo (440/880 Hz, und), 1 is AAC | ||
| 10 | +/// 22.05k mono (220 Hz, fra), 2 is AC-3, which we cannot decode. | ||
| 11 | +/// See `scripts/gen_fixtures.sh`. | ||
| 12 | +const MULTI: &str = "test_multiaudio.mp4"; | ||
| 13 | + | ||
| 14 | +fn asset(name: &str) -> PathBuf { | ||
| 15 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 16 | + .join("../../assets") | ||
| 17 | + .join(name) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// Everything the worker produced for one stream, flat. | ||
| 21 | +fn decode(name: &str, stream: usize) -> (engine::AudioMeta, Vec<f32>) { | ||
| 22 | + let sources = [(asset(name), stream)]; | ||
| 23 | + let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) | ||
| 24 | + .expect("opens") | ||
| 25 | + .expect("has audio"); | ||
| 26 | + let mut samples = Vec::new(); | ||
| 27 | + for chunk in rx { | ||
| 28 | + samples.extend_from_slice(&chunk.samples); | ||
| 29 | + } | ||
| 30 | + (meta, samples) | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// Sign changes, exact zeros ignored: at one tone per channel this is 2f per | ||
| 34 | +/// second per channel. | ||
| 35 | +fn zero_crossings(samples: &[f32]) -> usize { | ||
| 36 | + let (mut crossings, mut last) = (0, 0f32); | ||
| 37 | + for &s in samples { | ||
| 38 | + if s == 0.0 { | ||
| 39 | + continue; | ||
| 40 | + } | ||
| 41 | + if last != 0.0 && (s > 0.0) != (last > 0.0) { | ||
| 42 | + crossings += 1; | ||
| 43 | + } | ||
| 44 | + last = s; | ||
| 45 | + } | ||
| 46 | + crossings | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +#[test] | ||
| 50 | +fn probe_streams_lists_every_audio_track_in_file_order() { | ||
| 51 | + let streams = AudioSession::probe_streams(asset(MULTI)).expect("probes"); | ||
| 52 | + assert_eq!( | ||
| 53 | + streams, | ||
| 54 | + vec![ | ||
| 55 | + StreamInfo { | ||
| 56 | + index: 0, | ||
| 57 | + codec: "aac".into(), | ||
| 58 | + channels: 2, | ||
| 59 | + sample_rate: 44100, | ||
| 60 | + lang: None, // the `und` every muxer writes by default | ||
| 61 | + decodable: true, | ||
| 62 | + }, | ||
| 63 | + StreamInfo { | ||
| 64 | + index: 1, | ||
| 65 | + codec: "aac".into(), | ||
| 66 | + channels: 1, | ||
| 67 | + sample_rate: 22050, | ||
| 68 | + lang: Some("fra".into()), | ||
| 69 | + decodable: true, | ||
| 70 | + }, | ||
| 71 | + // The one we cannot play is listed all the same, so a picker can | ||
| 72 | + // grey it rather than pretend the file has two streams. mp4 0.14 | ||
| 73 | + // keeps no fourcc for a sample entry it does not parse, hence the | ||
| 74 | + // blanks — the row exists, which is the point. | ||
| 75 | + StreamInfo { | ||
| 76 | + index: 2, | ||
| 77 | + codec: "unknown".into(), | ||
| 78 | + channels: 0, | ||
| 79 | + sample_rate: 0, | ||
| 80 | + lang: None, | ||
| 81 | + decodable: false, | ||
| 82 | + }, | ||
| 83 | + ] | ||
| 84 | + ); | ||
| 85 | + // File order, run to run: `Mp4Reader::tracks` is a HashMap, so a careless | ||
| 86 | + // enumeration would shuffle these two. | ||
| 87 | + for _ in 0..8 { | ||
| 88 | + let again = AudioSession::probe_streams(asset(MULTI)).expect("probes"); | ||
| 89 | + assert_eq!(again, streams); | ||
| 90 | + } | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +#[test] | ||
| 94 | +fn probe_streams_on_one_track_and_on_none() { | ||
| 95 | + let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes"); | ||
| 96 | + assert_eq!(one.len(), 1, "test_av.mp4 has a single audio track"); | ||
| 97 | + assert_eq!( | ||
| 98 | + (one[0].index, one[0].sample_rate, one[0].channels), | ||
| 99 | + (0, 44100, 2) | ||
| 100 | + ); | ||
| 101 | + assert!(one[0].decodable); | ||
| 102 | + // No audio at all is an empty list, not an error: a silent source is valid. | ||
| 103 | + assert!( | ||
| 104 | + AudioSession::probe_streams(asset("test_baseline.mp4")) | ||
| 105 | + .expect("probes") | ||
| 106 | + .is_empty() | ||
| 107 | + ); | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +#[test] | ||
| 111 | +fn a_named_stream_decodes_that_stream_and_not_the_first() { | ||
| 112 | + let (meta, samples) = decode(MULTI, 1); | ||
| 113 | + assert_eq!((meta.sample_rate, meta.channels), (22050, 1)); | ||
| 114 | + // 220 Hz mono is 2 crossings a period. Measured over the middle half only: | ||
| 115 | + // the encoder's ramp-in and the container's tail padding are low-level | ||
| 116 | + // noise that crosses zero far more often than the tone does. | ||
| 117 | + let middle = &samples[samples.len() / 4..samples.len() * 3 / 4]; | ||
| 118 | + let expected = 2.0 * 220.0 * middle.len() as f64 / 22050.0; | ||
| 119 | + let crossings = zero_crossings(middle) as f64; | ||
| 120 | + assert!( | ||
| 121 | + (crossings - expected).abs() < 0.05 * expected, | ||
| 122 | + "stream 1 is {crossings} crossings, 220 Hz mono would be {expected}" | ||
| 123 | + ); | ||
| 124 | + assert!(samples.len() > 22050, "less than a second of stream 1"); | ||
| 125 | + | ||
| 126 | + // Stream 0 of the same file is the other one entirely. | ||
| 127 | + let (meta, _) = decode(MULTI, 0); | ||
| 128 | + assert_eq!((meta.sample_rate, meta.channels), (44100, 2)); | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +#[test] | ||
| 132 | +fn stream_0_stays_exactly_what_the_wrapper_gave() { | ||
| 133 | + // The default wrapper and stream 0 are the same track, sample for sample. | ||
| 134 | + let (wrapped, rx) = AudioSession::open(asset(MULTI)) | ||
| 135 | + .expect("opens") | ||
| 136 | + .expect("audio"); | ||
| 137 | + let mut plain = Vec::new(); | ||
| 138 | + for chunk in rx { | ||
| 139 | + plain.extend_from_slice(&chunk.samples); | ||
| 140 | + } | ||
| 141 | + let (meta, named) = decode(MULTI, 0); | ||
| 142 | + assert_eq!(wrapped, meta); | ||
| 143 | + assert_eq!(plain, named); | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +#[test] | ||
| 147 | +fn an_impossible_stream_is_refused_not_guessed() { | ||
| 148 | + let out_of_range = [(asset(MULTI), 3)]; | ||
| 149 | + let err = AudioSession::open_multi_streams(&out_of_range, &[(Some(0), 0.0, 1.0)]) | ||
| 150 | + .expect_err("stream 3 of 3 does not exist"); | ||
| 151 | + assert!( | ||
| 152 | + err.to_string().contains("audio stream 3 of 3"), | ||
| 153 | + "unhelpful refusal: {err}" | ||
| 154 | + ); | ||
| 155 | + // Stream 2 exists but is AC-3: refused with its own message, not decoded | ||
| 156 | + // into noise and not silently swapped for a stream that does decode. | ||
| 157 | + let ac3 = [(asset(MULTI), 2)]; | ||
| 158 | + let err = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)]) | ||
| 159 | + .expect_err("AC-3 does not decode here"); | ||
| 160 | + assert!( | ||
| 161 | + err.to_string().contains("audio stream 2 is not AAC"), | ||
| 162 | + "unhelpful refusal: {err}" | ||
| 163 | + ); | ||
| 164 | + // A source a *segment* names, opened lazily, refuses just the same. | ||
| 165 | + let sources = [(asset(MULTI), 0), (asset(MULTI), 9)]; | ||
| 166 | + assert!( | ||
| 167 | + AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]) | ||
| 168 | + .is_err(), | ||
| 169 | + "a second source's bad stream index has to refuse too" | ||
| 170 | + ); | ||
| 171 | + | ||
| 172 | + // Stream 0 of a file with no audio is still the silent source it always | ||
| 173 | + // was; a *named* stream of one is a promise the file cannot keep. | ||
| 174 | + let silent = asset("test_baseline.mp4"); | ||
| 175 | + assert!( | ||
| 176 | + AudioSession::open_multi_streams(&[(silent.clone(), 0)], &[(Some(0), 0.0, 1.0)]) | ||
| 177 | + .expect("no audio is not an error") | ||
| 178 | + .is_none() | ||
| 179 | + ); | ||
| 180 | + assert!(AudioSession::open_multi_streams(&[(silent, 1)], &[(Some(0), 0.0, 1.0)]).is_err()); | ||
| 181 | +} | ||
scripts/gen_fixtures.shmodified+17 -0
| @@ -25,6 +25,23 @@ ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30:duration=4 \ | |||
| 25 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 25 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 26 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 26 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 27 | -c:a aac -b:a 128k assets/test_av2.mp4 | 27 | -c:a aac -b:a 128k assets/test_av2.mp4 |
| 28 | +# Multi-audio fixture: one video and three audio streams, so stream selection | ||
| 29 | +# has something to select. Stream 0 is AAC 44.1k stereo (440 Hz left, 880 Hz | ||
| 30 | +# right), stream 1 is AAC 22.05k mono 220 Hz tagged French — different rate, | ||
| 31 | +# layout and content, so a test can tell which stream it was handed — and | ||
| 32 | +# stream 2 is AC-3, the codec we cannot decode and must still list. | ||
| 33 | +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ | ||
| 34 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 35 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 36 | + -f lavfi -i "sine=frequency=220:duration=2" \ | ||
| 37 | + -f lavfi -i "sine=frequency=330:duration=2" \ | ||
| 38 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a0]" \ | ||
| 39 | + -map 0:v -map "[a0]" -map 3:a -map 4:a \ | ||
| 40 | + -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 41 | + -c:a:0 aac -ar:a:0 44100 -ac:a:0 2 \ | ||
| 42 | + -c:a:1 aac -ar:a:1 22050 -ac:a:1 1 \ | ||
| 43 | + -c:a:2 ac3 -ar:a:2 44100 -ac:a:2 2 \ | ||
| 44 | + -metadata:s:a:1 language=fra assets/test_multiaudio.mp4 | ||
| 28 | # Mismatch fixture: different resolution and no audio track at all, so import | 45 | # Mismatch fixture: different resolution and no audio track at all, so import |
| 29 | # has something concrete to refuse. | 46 | # has something concrete to refuse. |
| 30 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ | 47 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |