From fe53979b702e6c94b280f2c8288270b94309c952 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 09:03:57 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20common=20audio=20fi?= =?UTF-8?q?les=20import=20and=20play?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mp3, wav, flac, ogg-vorbis, ALAC and ADTS join a timeline as sources with no picture: symphonia's own probe reads them, the audio lane holds them, and the video lane refuses them by name. The mp4/AAC path is untouched -- it is still the only one that yields packets an export can copy, so a timeline carrying anything else is refused at export with the file and its format named rather than exported silent. A source with no picture is as long as it plays, rounded up to whole frames; import, load and the library row all derive its length from that. --- Cargo.lock | 118 ++++++++ crates/app/src/main.rs | 44 ++- crates/engine/Cargo.toml | 19 ++ crates/engine/src/audio.rs | 454 ++++++++++++++++++++++++++--- crates/engine/src/lib.rs | 45 +++ crates/engine/src/playback.rs | 138 ++++++++- crates/engine/tests/audio_files.rs | 247 ++++++++++++++++ crates/engine/tests/audio_multi.rs | 2 +- scripts/gen_fixtures.sh | 27 ++ 9 files changed, 1030 insertions(+), 64 deletions(-) create mode 100644 crates/engine/tests/audio_files.rs diff --git a/Cargo.lock b/Cargo.lock index 405b392..113256c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1612,6 +1612,7 @@ dependencies = [ "libloading", "mp4", "rusty_h264", + "symphonia", "symphonia-codec-aac", "symphonia-core", ] @@ -1764,6 +1765,12 @@ dependencies = [ "zune-inflate", ] +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + [[package]] name = "fastrand" version = "1.9.0" @@ -5485,6 +5492,49 @@ dependencies = [ "zeno", ] +[[package]] +name = "symphonia" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1758d6c853020a7244de03cc3e0185eaea3f58715122422dd3cc7452e6d4c16a" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-alac", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-isomp4", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee69ad01236a67260b82fd1ff9790dd75ead29f2f46af145e63b7e72273e0e03" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "350f1f2f2e19ad4dd315db94304d1eb361b29af070681f94e51b8fdaad769546" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + [[package]] name = "symphonia-codec-aac" version = "0.6.0" @@ -5497,6 +5547,38 @@ dependencies = [ "symphonia-core", ] +[[package]] +name = "symphonia-codec-alac" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a149cbfc7fb5c405d123a273227d31de17138419552112bf1aa7b73e65827b8" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50baee168f0e9dcf6ba7fc06e8b57eb62072a4490cc7cf13af77e72baae5d328" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45b07b4423cd8e0fc472575909a5554b12c2f58e3c190b38c24f042e732fd8de" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", +] + [[package]] name = "symphonia-common" version = "0.6.0" @@ -5522,6 +5604,42 @@ dependencies = [ "smallvec", ] +[[package]] +name = "symphonia-format-isomp4" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d179a01305b3505940135a9f0180d6ef4b487912748fe97554756f120fbd05e" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05a67e02b1e4fca1a261ba4fe06910a9357489ad8c36aafdd2960e9c6559433" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17424452a777666d3eaf09a5c651029b15b6a333812fcc5b5474f2a3f0cff3f0" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "symphonia-metadata" version = "0.6.0" diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 9206398..7c49969 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -549,10 +549,29 @@ impl Player { /// moves along rather than being painted over. Reseeks like every other /// edit, and drops the timeline's selection with it: the insert has just /// moved the indices it pointed at. - fn insert_source(&mut self, source: usize, cx: &mut Context) { + fn insert_source(&mut self, source: usize, onto: Option, cx: &mut Context) { if self.exporting().is_some() { return; } + // A file with no picture belongs on the audio lane and nowhere else: + // dropped on the video lane it is refused by name, and asked for by the + // Add button (which names no lane) it goes to the audio one. + let songs: bool = self + .session + .as_ref() + .and_then(|session| session.sources().get(source)) + .is_some_and(|path| engine::is_audio(path)); + if songs && onto == Some(Lane::Video) { + let name = self + .session + .as_ref() + .map_or_else(String::new, |session| file_name(&session.sources()[source])); + self.notice = Some( + format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(), + ); + cx.notify(); + return; + } let clip = self.session.as_ref().and_then(|session| { let frames = source_frames(lane_clips(session), source); // Zero means nothing on the timeline plays from that file any more @@ -567,6 +586,12 @@ impl Player { }) }); let added = match (&mut self.session, clip) { + // One lane, no ripple: there is nothing on the video lane to move + // along with it, and a song laid over the picture is what dropping + // it at the playhead means. + (Some(session), Some(clip)) if songs => { + session.place_at(Lane::Audio, session.now(), clip) + } (Some(session), Some(clip)) => session.paste_at(session.now(), clip), _ => false, }; @@ -1218,6 +1243,13 @@ impl Player { .map_or(0, |session| source_frames(lane_clips(session), i)); let name: SharedString = file_name(path).into(); let tip: SharedString = match meta { + // A file with no picture has no size and no frame rate to + // report, and only one lane it can go on: saying so is the + // difference between a hint and a lie. + _ if engine::is_audio(path) => format!( + "{} — audio only · drag onto the audio lane, or Add at playhead", + path.display() + ), Some(meta) => format!( "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", path.display(), @@ -1347,7 +1379,9 @@ impl Player { can_add(self.selected_asset, self.session.is_some(), exporting), cx.listener(|this, _: &ClickEvent, _, cx| { if let Some(source) = this.selected_asset { - this.insert_source(source, cx); + // No lane: the button means "wherever this belongs", + // which for a file with no picture is the audio lane. + this.insert_source(source, None, cx); } }), )) @@ -1944,9 +1978,9 @@ impl Player { // Add button makes, through the same call -- at the // playhead, not at the pointer: clips here are placed end // to end, so where along the bed it landed says nothing. - .on_drop( - cx.listener(|this, drag: &AssetDrag, _, cx| this.insert_source(drag.0, cx)), - ) + .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| { + this.insert_source(drag.0, Some(lane), cx) + })) .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) .children(clips.iter().enumerate().map(|(i, clip)| { let (start, len) = ( diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0e037a7..220a17b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,3 +10,22 @@ mp4 = "0.14" rusty_h264 = { version = "0.8", default-features = false } symphonia-core = "0.6" symphonia-codec-aac = "0.6" +# The umbrella crate for the standalone audio files: one dependency instead of +# seven, and its `default::get_probe`/`get_codecs` are the registries this would +# otherwise hand-build. Explicit feature list rather than the default one -- no +# mkv, no ape, no adpcm: what is listed here is exactly what `is_audio` admits. +# There is no opus/ac3/dts feature at any symphonia version, which is why those +# are refused rather than promised. +symphonia = { version = "0.6", default-features = false, features = [ + "aac", + "alac", + "flac", + "id3v1", + "id3v2", + "isomp4", + "mp3", + "ogg", + "pcm", + "vorbis", + "wav", +] } diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 9ede29f..f75da57 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -1,6 +1,14 @@ -//! Background audio decode worker: pulls the AAC track out of an MP4 and hands +//! 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 -//! `Mp4Reader` so the video demuxer stays single-owner. +//! reader so the video demuxer stays single-owner. +//! +//! Two 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. 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. use std::fs::File; use std::io::BufReader; @@ -13,8 +21,13 @@ use symphonia_codec_aac::AacDecoder; use symphonia_core::codecs::audio::{ AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, }; +use symphonia_core::formats::probe::Hint; +use symphonia_core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo, TrackType}; +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}; /// 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.) @@ -30,6 +43,12 @@ const PRE_ROLL: u32 = 2; /// Frames per channel one AAC-LC packet carries. Fixed by the codec. const SAMPLES_PER_PACKET: u32 = 1024; +/// 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, @@ -67,9 +86,14 @@ pub struct AacPacket { /// Everything an import check needs from a candidate file's audio track. Two /// files may share a timeline only when their probes are equal (or both `None`). +/// +/// Rate and layout only: those are what one output device and one exported track +/// can carry, and an mp3 that agrees on both 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 params: AacTrackParams, + pub sample_rate: u32, pub channels: u16, } @@ -141,13 +165,13 @@ impl AudioSession { // The timeline's meta is the first source's: policy makes every other // source match it, and the checks below hold them to that. let meta = AudioMeta { - sample_rate: first.sample_rate, + sample_rate: first.sample_rate(), channels: first.channels()?, - total_samples: first.total_samples, + 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. - AacDecoder::try_new(&first.params, &AudioDecoderOptions::default())?; + first.check_decoder()?; let mut tracks: Vec> = sources.iter().map(|_| None).collect(); tracks[0] = Some(first); @@ -163,17 +187,17 @@ impl AudioSession { } let track = Track::open(&sources[source])? .ok_or_else(|| format!("source {source} has no audio track"))?; - if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { + if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) { return Err(format!( "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", - track.sample_rate, + track.sample_rate(), track.channels()?, meta.sample_rate, meta.channels ) .into()); } - AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())?; + track.check_decoder()?; *slot = Some(track); } @@ -194,7 +218,7 @@ impl AudioSession { let timeline = segments.first().map_or(0, |s| match s.source { Some(source) => s .media_target - .saturating_sub(tracks[source].as_ref().expect("opened above").priming), + .saturating_sub(tracks[source].as_ref().expect("opened above").priming()), None => 0, }); @@ -218,18 +242,46 @@ impl AudioSession { /// The audio parameters of `path`, for checking an import against the /// timeline's first source: header only, no decoder and no worker. - /// `Ok(None)` means no AAC track — an audio-less file, which import pairs - /// only with other audio-less files. + /// `Ok(None)` means no audio track — a silent file, which import pairs + /// only with other silent files. pub fn probe(path: impl AsRef) -> crate::Result> { let Some(track) = Track::open(path.as_ref())? else { return Ok(None); }; Ok(Some(AudioProbe { - params: track.track_params(), + sample_rate: track.sample_rate(), channels: track.channels()?, })) } + /// 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. + pub fn duration_secs(path: impl AsRef) -> crate::Result> { + let path = path.as_ref(); + let Some(track) = Track::open(path)? 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 @@ -284,11 +336,11 @@ impl AudioSession { let path = sources .get(first) .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; - let Some(track) = Track::open(path)? else { + let Some(track) = copy_track(path)? else { return Ok(None); // silent source, silent export }; let params = track.track_params(); - let mut tracks: Vec> = sources.iter().map(|_| None).collect(); + let mut tracks: Vec> = sources.iter().map(|_| None).collect(); tracks[first] = Some(track); let sample_rate = params.sample_rate; @@ -376,27 +428,239 @@ fn silent_packet(chan_conf: u8) -> crate::Result> { /// The source at `index`, opened on first use. Sources a segment list never /// names are never touched: a project's list only grows. fn source_at<'a>( - tracks: &'a mut [Option], + tracks: &'a mut [Option], sources: &[PathBuf], index: usize, -) -> crate::Result<&'a mut Track> { +) -> crate::Result<&'a mut AacTrack> { let slot = tracks .get_mut(index) .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; if slot.is_none() { *slot = Some( - Track::open(&sources[index])? + copy_track(&sources[index])? .ok_or_else(|| format!("source {index} has no audio track"))?, ); } Ok(slot.as_mut().expect("just opened")) } +/// A source's track for the *copy* path, which needs raw AAC access units. +/// +/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by +/// name and by format rather than exported silent or, worse, exported as noise: +/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]), +/// so a timeline carrying one of those simply cannot become an mp4 today. The +/// wording is what a front-end shows. +/// +/// `Ok(None)` for a file with no audio at all, which is a silent export. +fn copy_track(path: &Path) -> crate::Result> { + match Track::open(path)? { + None => Ok(None), + Some(Track::Aac(track)) => Ok(Some(track)), + Some(Track::Sym(track)) => Err(format!( + "export needs AAC audio today; {} is {}", + path.file_name() + .unwrap_or(path.as_os_str()) + .to_string_lossy(), + track.codec + ) + .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), + 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. + fn open(path: &Path) -> crate::Result> { + let audio_file = crate::is_audio(path); + match AacTrack::open(path) { + 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), + _ => {} + } + SymTrack::open(path).map(|track| Some(Self::Sym(track))) + } + + fn sample_rate(&self) -> u32 { + match self { + Self::Aac(t) => t.sample_rate, + Self::Sym(t) => t.sample_rate, + } + } + + /// Mono or stereo; anything wider is refused here rather than one packet at + /// a time, because one output device and one copied track is all there is. + fn channels(&self) -> crate::Result { + match self { + Self::Aac(t) => t.channels(), + Self::Sym(t) => match t.channels { + 1 | 2 => Ok(t.channels), + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), + }, + } + } + + /// Frames per channel of *audible* audio, priming already subtracted. + fn total_samples(&self) -> Option { + match self { + Self::Aac(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::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::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) => { + AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; + } + 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, + track_id: u32, + sample_rate: u32, + channels: u16, + /// Frames per channel of audible audio, `None` when the header does not say. + total_samples: Option, + /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the + /// container where it declares one (mp3's Xing/LAME tag, ALAC's edit list). + 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 { + fn open(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); + } + let reader = symphonia::default::get_probe().probe( + &hint, + mss, + FormatOptions::default(), + MetadataOptions::default(), + )?; + let track = reader + .default_track(TrackType::Audio) + .ok_or_else(|| format!("{} has no audio track", path.display()))?; + let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay); + 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); + Ok(Self { + reader, + track_id, + sample_rate, + channels, + total_samples: num_frames, + priming: u64::from(delay.unwrap_or(0)), + time_base, + params, + codec, + }) + } + + /// A fresh decoder: seeking mid-stream leaves state that belongs to the + /// packets we skipped, exactly as on the AAC path. + fn decoder(&self) -> crate::Result> { + Ok(symphonia::default::get_codecs() + .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?) + } + + /// `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 samples per channel. + 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 + } +} + /// 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 Track { +struct AacTrack { reader: Mp4Reader>, track_id: u32, sample_count: u32, @@ -414,7 +678,7 @@ struct Track { params: AudioCodecParameters, } -impl Track { +impl AacTrack { /// `Ok(None)` for a file with no AAC track, which is a valid silent source. fn open(path: &Path) -> crate::Result> { let file = File::open(path)?; @@ -723,6 +987,15 @@ fn run(mut w: Worker) { 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, channels, &mut timeline, &w.tx) { + return; // consumer went away + } + continue; + } + Track::Aac(track) => track, + }; let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) { Ok(decoder) => decoder, @@ -760,35 +1033,126 @@ fn run(mut w: Worker) { }; buf.copy_to_vec_interleaved::(&mut interleaved); let next = pos + (interleaved.len() / channels) as u64; - - // Everything before the target is encoder priming and/or decoder - // pre-roll, not audio the caller asked for: drop it, splitting the - // packet that straddles the target. - if next <= seg.media_target { - pos = next; - continue; - } - if pos < seg.media_target { - interleaved.drain(..(seg.media_target - pos) as usize * channels); - pos = seg.media_target; - } - // And the tail past the segment end goes too — on a short segment - // that is this same buffer, trimmed at both ends. - if next > seg.media_end { - interleaved.truncate((seg.media_end - pos) as usize * channels); + if !emit( + &mut interleaved, + channels, + seg, + pos, + next, + &mut timeline, + &w.tx, + ) { + return; // consumer went away } pos = next; - if interleaved.is_empty() { - continue; // nothing left of it; the loop head ends the segment + } + } +} + +/// 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. +fn emit( + interleaved: &mut Vec, + channels: usize, + seg: &Segment, + 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 + } + 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 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, + 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; + } + }; + let rate = f64::from(track.sample_rate.max(1)); + let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate; + if let Some(time) = Time::try_from_secs_f64(from) { + let to = SeekTo::Time { + time, + track_id: Some(track.track_id), + }; + // A failed seek is not fatal: it leaves the reader where it was, and + // the window rules below still only emit what the segment asked for. + if let Err(e) = track.reader.seek(SeekMode::Accurate, to) { + eprintln!("audio seek to {from:.3}s failed: {e}"); + } + } + let mut interleaved = Vec::new(); + 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; } - let chunk = AudioChunk { - start_sample: timeline, - samples: std::mem::take(&mut interleaved), - }; - timeline += (chunk.samples.len() / channels) as u64; - if w.tx.send(chunk).is_err() { - return; // consumer went away + }; + if packet.track_id != track.track_id { + continue; // another track of the same container + } + let pos = track.samples_at(packet.pts); + if pos >= seg.media_end { + return true; // segment done, on to the next one + } + let buf = match decoder.decode(&packet) { + Ok(buf) => buf, + Err(e) => { + eprintln!("audio decode error at sample {pos}: {e}"); + return true; } + }; + buf.copy_to_vec_interleaved::(&mut interleaved); + let next = pos + (interleaved.len() / channels) as u64; + if !emit(&mut interleaved, channels, seg, pos, next, timeline, tx) { + return false; } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aae94c3..6b34a3c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -23,7 +23,52 @@ pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; pub use project::{Clip, Project}; +/// Whether a path names a standalone audio file -- a source with no picture, +/// which belongs on the audio lane and nowhere else. Extension only, lowercased: +/// the decoder is what really decides, but a front-end has to know which lane a +/// dropped file may land on *before* anything is opened, and so does +/// [`PlaybackSession::import`](playback::PlaybackSession::import). +/// +/// Exactly the containers the engine's audio path reads (`audio::AudioSession`): +/// no opus, ac3 or dts, for which no pure-Rust decoder exists -- those are +/// refused by the same door that refuses a `.txt`, which is the honest answer. +pub fn is_audio(path: &std::path::Path) -> bool { + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e.to_ascii_lowercase().as_str(), + "mp3" | "wav" | "flac" | "ogg" | "oga" | "m4a" | "aac" + ) + }) +} + /// Boxed error; the engine has few failure modes and every one of them is fatal /// to the session, so a message is all a caller can act on. pub type Error = Box; pub type Result = std::result::Result; + +#[cfg(test)] +mod tests { + use std::path::Path; + + #[test] + fn is_audio_admits_the_containers_the_decoder_reads() { + for name in [ + "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", + ] { + assert!(super::is_audio(Path::new(name)), "{name}"); + } + // Video, projects, the formats with no pure-Rust decoder, and a file + // with no extension at all: all of them go elsewhere. + for name in [ + "clip.mp4", + "take.MP4", + "cut.edith", + "x.opus", + "y.ac3", + "notes", + "mp3", + ] { + assert!(!super::is_audio(Path::new(name)), "{name}"); + } + } +} diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 79cc2f3..749d448 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -120,6 +120,17 @@ impl PlaybackSession { /// a file we cannot hear is still a file we can watch. pub fn open(path: impl AsRef) -> crate::Result { let path = path.as_ref().to_path_buf(); + // A timeline is scaffolded from source 0's picture -- its size, its + // frame rate, its clock. A song has none of that, so it joins a + // timeline (`import`) rather than starting one, and saying so beats + // failing in the demuxer's words. + if crate::is_audio(&path) { + return Err(format!( + "{} has no picture: open a video first, then import it onto the audio lane", + path.display() + ) + .into()); + } // `open_worker` rather than `open` purely for the worker handle: the // field has to exist from the start for the first seek to use it. let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; @@ -181,12 +192,34 @@ impl PlaybackSession { let mut counts = vec![meta.frame_count]; for source in &doc.sources[1..] { + // A source with no picture is checked on what it does have, and + // its length is its playing time -- the same two answers `import` + // gave it when it first joined the timeline. + if crate::is_audio(source) { + audio_matches(AudioSession::probe(source)?, &first_audio) + .map_err(|e| format!("source {}: {e}", source.display()))?; + counts.push(audio_frames(source, meta.frame_rate)?); + continue; + } let (other, _) = Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?; matches_timeline(source, &other, &meta, &first_audio) .map_err(|e| format!("source {}: {e}", source.display()))?; counts.push(other.frame_count); } + // The video lane can only play files that have pictures. Hand-written + // (or hand-edited) project files are the one door this can come in + // through, so it is refused by name here rather than becoming a clip + // that decodes to nothing. + for clip in &doc.video { + if crate::is_audio(&doc.sources[clip.source]) { + return Err(format!( + "{} has no picture: it can only play on the audio lane", + doc.sources[clip.source].display() + ) + .into()); + } + } for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() { if clip.out_frame > counts[clip.source] { return Err(format!( @@ -440,6 +473,16 @@ impl PlaybackSession { self.edit(|p| p.paste(at, clip)) } + /// Places `clip` on `lane` alone at the playhead, overwriting what it lands + /// on and rippling nothing -- the one-lane insert a source with no picture + /// makes, and the only way an audio-only file reaches the timeline. The + /// placement belongs to no group (see [`Project::place`]). One undo step, + /// and it reseeks like every other edit. + pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { + let at = secs_to_frame(timeline_secs, self.meta.frame_rate); + self.edit(|p| p.place(lane, at, clip)) + } + /// Removes the video clip at `idx` and everything under it, closing the gap /// on every lane. Unlike a split this *does* move every following frame, so /// the session reseeks to wherever the playhead now points. @@ -463,6 +506,9 @@ impl PlaybackSession { /// the property that disagrees, for a caller to show. Nothing is changed by /// a refusal. pub fn import(&mut self, path: &Path) -> crate::Result<()> { + if crate::is_audio(path) { + return self.import_audio(path); + } let (meta, _) = Demuxer::open(path)?; let first = AudioSession::probe(&self.project.sources()[0])?; matches_timeline(path, &meta, &self.meta, &first)?; @@ -481,6 +527,43 @@ impl PlaybackSession { Ok(()) } + /// Appends a standalone audio file to the end of the timeline, on the + /// **audio lane alone**: a song has no picture, so there is nothing to put + /// on the video lane and the timeline shows black under it. Its length is + /// its playing time rounded up to whole frames, which is the only frame + /// count such a source has. + /// + /// Refused in the same words as any other import when its rate or layout + /// disagrees with the timeline's -- one output device, one set of + /// parameters -- and refused outright on a silent timeline, which has no + /// device open at all. Nothing is changed by a refusal. + fn import_audio(&mut self, path: &Path) -> crate::Result<()> { + let first = AudioSession::probe(&self.project.sources()[0])?; + audio_matches(AudioSession::probe(path)?, &first)?; + let frames = audio_frames(path, self.meta.frame_rate)?; + + let old_end = self.timeline_duration(); + let source = self.project.import(path); + let at = self.project.timeline_frames(); + self.project.place( + Lane::Audio, + at, + Clip { + start: at, + in_frame: 0, + out_frame: frames, + source, + link: None, + }, + ); + // Same reason as a video import: the running audio worker's segment + // list stops at the old end, so without a reseek the appended clip + // would play silent. + let at = if self.eos { old_end } else { self.now() }; + self.seek(at); + Ok(()) + } + /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` /// clamps to the new duration and keeps playing playing, so a delete that /// shortens the timeline past the playhead lands on the last frame. @@ -731,21 +814,50 @@ fn matches_timeline( ) .into()); } - // Whole-probe equality: rate, layout and the esds fields, which the audio - // worker holds every source to anyway. Both silent is a match. - let probe = AudioSession::probe(path)?; - if probe != *first { - return Err(match (probe, first) { - (None, _) => "the file is silent, the timeline has audio".to_string(), - (_, None) => "the file has audio, the timeline is silent".to_string(), - (Some(a), Some(b)) => format!( - "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", - a.params.sample_rate, a.channels, b.params.sample_rate, b.channels - ), - } + audio_matches(AudioSession::probe(path)?, first) +} + +/// Whether a candidate's audio may join a timeline whose first source probes as +/// `first`: same rate, same layout, or both silent. One output device and one +/// exported track is all there is, and no resampler. +/// +/// The format itself is deliberately *not* part of this: an mp3 that agrees on +/// rate and layout plays alongside a timeline of mp4s perfectly well. What it +/// cannot do is be copied into an export, which is a refusal of its own, at +/// export time (`AudioSession::copy_multi_segments`). +fn audio_matches( + probe: Option, + first: &Option, +) -> crate::Result<()> { + if probe == *first { + return Ok(()); + } + Err(match (probe, first) { + (None, _) => "the file is silent, the timeline has audio".to_string(), + (_, None) => "the file has audio, the timeline is silent".to_string(), + (Some(a), Some(b)) => format!( + "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", + a.sample_rate, a.channels, b.sample_rate, b.channels + ), + } + .into()) +} + +/// How many timeline frames a standalone audio file occupies: its playing time +/// rounded *up*, so the last partial frame is still covered rather than cut off, +/// and never zero (a clip is never empty). +fn audio_frames(path: &Path, fps: f64) -> crate::Result { + let secs = AudioSession::duration_secs(path)? + .ok_or_else(|| format!("{} has no audio track", path.display()))?; + let frames = (secs * fps).ceil(); + if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) { + return Err(format!( + "{} is {secs} s long, which is not a timeline", + path.display() + ) .into()); } - Ok(()) + Ok((frames as u32).max(1)) } /// `None` for a silent session -- no audio track, no plugin, no daemon, or a diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs new file mode 100644 index 0000000..8bda557 --- /dev/null +++ b/crates/engine/tests/audio_files.rs @@ -0,0 +1,247 @@ +//! Standalone audio files as sources: every container we claim to read decodes +//! to the same tone, a song joins a timeline of video on the audio lane, and +//! the three things it cannot do -- start a timeline, play on the video lane, +//! be copied into an mp4 -- are refusals that say so. +//! +//! ```text +//! cargo test -p engine --release --test audio_files +//! ``` + +use std::path::{Path, PathBuf}; + +use engine::project::Lane; +use engine::{AudioSession, Clip, PlaybackSession}; + +/// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz +/// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone +/// `test_av.mp4` carries, so a song and a video clip share one timeline. +const CONTAINERS: [&str; 6] = [ + "test_tone.mp3", + "test_tone.wav", + "test_tone.flac", + "test_tone.ogg", + "test_tone.m4a", + "test_tone.aac", +]; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The message of a call that had to be refused. Not `expect_err`: that wants +/// `Debug` on the success side, and neither a session nor a packet has it. +fn refusal(result: engine::Result) -> String { + match result { + Ok(_) => panic!("expected a refusal"), + Err(e) => e.to_string(), + } +} + +fn open(path: impl AsRef) -> PlaybackSession { + let session = PlaybackSession::open(path).expect("open"); + session.set_gain(0.0); + session +} + +/// Every frame the file decodes to, interleaved, plus the meta it declares. +fn decode(path: &Path) -> (u32, u16, Vec) { + let (meta, rx) = AudioSession::open(path) + .expect("open") + .expect("the fixture has audio"); + let mut samples = Vec::new(); + for chunk in rx { + samples.extend(chunk.samples); + } + (meta.sample_rate, meta.channels, samples) +} + +#[test] +fn every_container_decodes_the_same_three_second_tone() { + for name in CONTAINERS { + let (rate, channels, samples) = decode(&asset(name)); + assert_eq!((rate, channels), (44100, 2), "{name}"); + let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels); + // Lossy formats pad: a codec frame is 1152 (mp3) or 1024 (aac) samples, + // so a tenth of a second is generous and still catches a decoder that + // stops early or doubles the stream. + assert!( + (secs - 3.0).abs() < 0.1, + "{name}: {secs:.3} s of audio, want 3.0" + ); + // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): full scale at t=0.25 + // of every second, silence at t=0.75. Sample it there rather than + // trusting a length -- a channel-swapped or mis-scaled decode still has + // the right number of samples. + for second in 0..3 { + let at = |t: f64| { + let frame = ((f64::from(second) + t) * f64::from(rate)) as usize; + let block = &samples[frame * usize::from(channels)..][..usize::from(channels) * 64]; + block.iter().fold(0.0f32, |peak, s| peak.max(s.abs())) + }; + // Depth as a ratio, not an absolute: the fixture's sines sit around + // an eighth of full scale and that is the encoder's business + // (ledger:873), while a dip 20x below the peak is the pulse. + let (loud, quiet) = (at(0.25), at(0.75)); + assert!(loud > 0.05, "{name} second {second}: peak only {loud}"); + assert!( + quiet < 0.05 * loud, + "{name} second {second}: dip {quiet} against peak {loud}" + ); + } + } +} + +/// The length a placement is built from, which is the only frame count a file +/// with no picture has. +#[test] +fn duration_comes_from_the_header_or_the_decode() { + for name in CONTAINERS { + let secs = AudioSession::duration_secs(asset(name)) + .expect("probe") + .expect("the fixture has audio"); + assert!( + (secs - 3.0).abs() < 0.1, + "{name}: duration reads {secs:.3} s" + ); + } + assert_eq!( + AudioSession::duration_secs(asset("test_baseline.mp4")).expect("probe"), + None, + "a silent video has no audio duration" + ); +} + +#[test] +fn a_song_joins_a_video_timeline_on_the_audio_lane() { + let mut session = open(asset("test_av.mp4")); + let before = session.timeline_duration(); + session + .import(&asset("test_tone.mp3")) + .expect("import the song"); + + // 3 s at 30 fps, appended: the audio lane runs 90 frames past the video. + assert!( + (session.timeline_duration() - (before + 3.0)).abs() < 0.05, + "{} s of timeline, want {}", + session.timeline_duration(), + before + 3.0 + ); + assert_eq!(session.sources().len(), 2); + // The video lane never hears about it: one clip, the one the file opened + // with. The audio lane has two. + assert_eq!(session.lane_clips(Lane::Video).len(), 1, "video lane"); + assert_eq!(session.lane_clips(Lane::Audio).len(), 2, "audio lane"); + let song = session.lane_clips(Lane::Audio)[1]; + assert_eq!((song.source, song.in_frame, song.len()), (1, 0, 90)); + + // And it plays: the segment list past the join names the song, so the + // worker opens it rather than running silent. + session.seek(before + 1.0); + assert!(session.lane_spans_by_source(Lane::Audio).len() >= 2); +} + +#[test] +fn a_rate_the_device_cannot_mix_is_refused_at_the_door() { + let mut session = open(asset("test_av.mp4")); + assert_eq!( + refusal(session.import(&asset("test_tone_48k.wav"))), + "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" + ); + // Refused means unchanged: no source, no clip, no length. + assert_eq!(session.sources().len(), 1); + assert_eq!(session.lane_clips(Lane::Audio).len(), 1); +} + +#[test] +fn a_song_cannot_be_a_timeline_of_its_own() { + let e = refusal(PlaybackSession::open(asset("test_tone.mp3"))); + assert!( + e.ends_with("has no picture: open a video first, then import it onto the audio lane"), + "{e}" + ); +} + +/// The export copies AAC packets and has no encoder, so a timeline carrying an +/// mp3 cannot become an mp4 -- named, with its format, rather than exported +/// silent or exported wrong. +#[test] +fn an_export_refuses_audio_it_cannot_copy() { + let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")]; + let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; + assert_eq!( + refusal(AudioSession::copy_multi_segments(&sources, &segs)), + "export needs AAC audio today; test_tone.mp3 is mp3" + ); + // A timeline of nothing but mp4 still exports, which is the invariant this + // refusal must not have cost. + assert!( + AudioSession::copy_multi_segments(&sources[..1], &segs[..1]) + .expect("mp4 audio still copies") + .is_some() + ); +} + +#[test] +fn a_song_survives_a_save_and_a_reload() { + let dir = std::env::temp_dir().join(format!("ve_audio_files_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let copy = |name: &str| { + let to = dir.join(name); + std::fs::copy(asset(name), &to).expect("copy the fixture"); + to + }; + + let mut session = open(copy("test_av.mp4")); + session.import(©("test_tone.flac")).expect("import"); + // And one placed at the playhead, the way a library row dropped on the + // audio lane arrives -- so the reload has both doors to restore. + let song = session.lane_clips(Lane::Audio)[1]; + assert!(session.place_at( + Lane::Audio, + 1.0, + Clip { + in_frame: 0, + out_frame: 30, + ..song + } + )); + let before = ( + session.lane_spans_by_source(Lane::Audio), + session.sources().to_vec(), + session.timeline_duration(), + ); + + let project = dir.join("song.edith"); + session.save_project(&project).expect("save"); + drop(session); + let reloaded = PlaybackSession::open_project(&project).expect("reload"); + reloaded.set_gain(0.0); + assert_eq!( + ( + reloaded.lane_spans_by_source(Lane::Audio), + reloaded.sources().to_vec(), + reloaded.timeline_duration() + ), + before + ); + + // The one thing only a hand-edited project can ask for: a file with no + // picture on the video lane. Written by hand, because no door in the engine + // will produce it. + let broken = dir.join("broken.edith"); + std::fs::write( + &broken, + "edith 2\nplayhead 0\nsource test_av.mp4\nsource test_tone.flac\n\ + video 0 0 90 1 -\naudio 0 0 90 1 -\n", + ) + .expect("write"); + let e = refusal(PlaybackSession::open_project(&broken)); + assert!( + e.ends_with("has no picture: it can only play on the audio lane"), + "{e}" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/audio_multi.rs b/crates/engine/tests/audio_multi.rs index fa9221b..cca7f6d 100644 --- a/crates/engine/tests/audio_multi.rs +++ b/crates/engine/tests/audio_multi.rs @@ -193,7 +193,7 @@ fn probe_reads_the_import_policy_fields() { .expect("probe") .expect("test_av.mp4 has audio"); assert_eq!(av.channels, 2); - assert_eq!(av.params.sample_rate, RATE as u32); + assert_eq!(av.sample_rate, RATE as u32); assert_eq!( AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(), av, diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index c1255d3..3888941 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -29,4 +29,31 @@ ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30:duration=4 \ # has something concrete to refuse. ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 +# Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the +# A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song +# can share a timeline with the video clips and the peaks tests can reuse the +# dip pattern. One per container we claim to read. +tone="[0:a][1:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" +for fmt in mp3 wav flac ogg m4a aac; do + case $fmt in + mp3) codec=(-c:a libmp3lame -b:a 128k) ;; + wav) codec=(-c:a pcm_s16le) ;; + flac) codec=(-c:a flac) ;; + ogg) codec=(-c:a libvorbis) ;; + # ALAC in mp4, and raw AAC in ADTS -- the two the mp4/AAC packet-copy + # path cannot claim: one is not AAC, the other is not in an mp4. + m4a) codec=(-c:a alac) ;; + aac) codec=(-c:a aac -b:a 128k -f adts) ;; + esac + ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ + -f lavfi -i "sine=frequency=880:duration=3" \ + -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ + "assets/test_tone.$fmt" +done +# The refusal fixture: same tone at 48k, which one output device cannot mix +# with a 44.1k timeline. +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ + -f lavfi -i "sine=frequency=880:duration=3" \ + -filter_complex "$tone" -map "[a]" -ar 48000 -c:a pcm_s16le \ + assets/test_tone_48k.wav echo "fixtures written to assets/"