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 e1e0b5a..bb05f02 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -640,10 +640,28 @@ 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, path: &Path, stream: usize, cx: &mut Context) { + fn insert_source( + &mut self, + path: &Path, + stream: 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 -- which is + // the engine's choice, in `place_stream_at`, not one made twice here. + if engine::is_audio(path) && onto == Some(Lane::Video) { + let name = file_name(path); + self.notice = Some( + format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(), + ); + cx.notify(); + return; + } let frames = self.session.as_ref().map_or(0, |session| { source_frames(lane_clips(session), session.sources(), path) }); @@ -1334,6 +1352,13 @@ impl Player { // A greyed row says why in full, where its length would be: // the list is the one place the file's own tracks are named. (Some(why), _) => format!("{} — {why}", row.path.display()), + // 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. + (None, _) if engine::is_audio(&row.path) => format!( + "{} — audio only · drag onto the audio lane, or Add at playhead", + row.path.display() + ), (None, Some(meta)) => format!( "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", row.path.display(), @@ -1486,7 +1511,9 @@ impl Player { ), cx.listener(|this, _: &ClickEvent, _, cx| { if let Some((path, stream)) = this.selected_asset.clone() { - this.insert_source(&path, stream, cx); + // No lane: the button means "wherever this belongs", + // which for a file with no picture is the audio lane. + this.insert_source(&path, stream, None, cx); } }), )) @@ -2311,8 +2338,8 @@ 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.clone(), drag.1, cx) + .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| { + this.insert_source(&drag.0.clone(), drag.1, Some(lane), cx) })) .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) .children(clips.iter().enumerate().map(|(i, clip)| { 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 a5df407..d3e44cc 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -1,6 +1,19 @@ -//! 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. +//! +//! 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; @@ -13,8 +26,17 @@ use symphonia_codec_aac::AacDecoder; use symphonia_core::codecs::audio::{ AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, }; +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}; /// 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 +52,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 +95,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, } @@ -183,13 +216,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); @@ -206,17 +239,17 @@ impl AudioSession { let (path, stream) = &sources[source]; let track = Track::open(path, *stream)? .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); } @@ -237,7 +270,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, }); @@ -282,15 +315,15 @@ impl AudioSession { /// 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 AAC track — an audio-less file, which import - /// pairs only with other audio-less files. A *named* stream that is not - /// there or does not decode is an `Err`, as everywhere else. + /// 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 { - params: track.track_params(), + sample_rate: track.sample_rate(), channels: track.channels()?, })) } @@ -303,8 +336,27 @@ impl AudioSession { /// /// 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 file = File::open(path.as_ref())?; + let path = path.as_ref(); + if crate::is_audio(path) { + let track = SymTrack::open(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: matches!(track.channels, 1 | 2) && 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) @@ -331,6 +383,37 @@ impl AudioSession { .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 @@ -399,11 +482,11 @@ impl AudioSession { let (path, stream) = sources .get(first) .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; - let Some(track) = Track::open(path, *stream)? else { + let Some(track) = copy_track(path, *stream)? 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; @@ -491,28 +574,248 @@ fn silent_packet(chan_conf: u8) -> crate::Result> { /// The source at `index`, on the stream it names, 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, usize)], 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() { let (path, stream) = &sources[index]; *slot = Some( - Track::open(path, *stream)? + copy_track(path, *stream)? .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, stream: usize) -> crate::Result> { + match Track::open(path, stream)? { + 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. + /// + /// `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> { + let audio_file = crate::is_audio(path); + 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(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(SymKind::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, @@ -530,15 +833,16 @@ struct Track { params: AudioCodecParameters, } -impl Track { +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 audio there at all - /// or the codec is one we do not decode, which is a valid silent source (a - /// file whose audio is AC-3 still has a picture worth editing). A stream the - /// caller *named* is a promise instead, so out of range or undecodable - /// there is an `Err` rather than silence the caller did not ask for. + /// 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(); @@ -896,6 +1200,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, @@ -933,35 +1246,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 3a9faa0..505df4e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,7 +26,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 c6a5196..afb3fd0 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -125,6 +125,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)?; @@ -189,12 +200,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.path) { + audio_matches(source, &first_audio) + .map_err(|e| format!("source {}: {e}", source.path.display()))?; + counts.push(audio_frames(&source.path, meta.frame_rate)?); + continue; + } let (other, _) = Demuxer::open(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; matches_timeline(source, &other, &meta, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.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].path) { + return Err(format!( + "{} has no picture: it can only play on the audio lane", + doc.sources[clip.source].path.display() + ) + .into()); + } + } for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() { if clip.out_frame > counts[clip.source] { return Err(format!( @@ -471,6 +504,11 @@ impl PlaybackSession { /// there is no resampler here, and no AAC encoder to write the join with. /// A front-end greys such a row out; this is the backstop that keeps a /// stale one from making the whole timeline silent. + /// + /// Which lane it lands on is decided here, from the file: one with a + /// picture is pasted across both lanes as a grouped take, one without + /// ([`crate::is_audio`]) is *placed* on the audio lane alone, overwriting + /// what it lands on and rippling nothing. A caller never has to ask. pub fn place_stream_at( &mut self, timeline_secs: f64, @@ -488,16 +526,22 @@ impl PlaybackSession { let first = self.first_audio()?; audio_matches(&wanted, &first)?; let source = self.project.import(path, stream); - Ok(self.paste_at( - timeline_secs, - Clip { - start: 0, - in_frame: 0, - out_frame: frames.max(1), - source, - link: None, - }, - )) + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: frames.max(1), + source, + link: None, + }; + // Which lane a source may land on is decided here and only here, so a + // front-end never has to make the same call twice: a file with no + // picture goes on the audio lane alone, overwriting and rippling + // nothing, because there is nothing on the video lane to move along + // with it. + Ok(match crate::is_audio(path) { + true => self.place_at(Lane::Audio, timeline_secs, clip), + false => self.paste_at(timeline_secs, clip), + }) } /// What the timeline's audio *is*: source 0's chosen stream, probed. Every @@ -507,6 +551,16 @@ impl PlaybackSession { AudioSession::probe(&first.path, first.audio_stream) } + /// 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. @@ -530,6 +584,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 = self.first_audio()?; // Stream 0: an import brings a file in on its first audio track, and @@ -551,6 +608,46 @@ 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 = self.first_audio()?; + // Stream 0, and there is no other: a standalone audio file carries one + // track (`AudioSession::probe_streams`), so nothing here has a stream + // to pick the way `place_stream_at` does for an mp4. + audio_matches(&Source::new(path, 0), &first)?; + let frames = audio_frames(path, self.meta.frame_rate)?; + + let old_end = self.timeline_duration(); + let source = self.project.import(path, 0); + 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. @@ -819,25 +916,51 @@ fn matches_timeline( audio_matches(source, 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 audio half of [`matches_timeline`], which a stream placed on its own /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it /// comes with is already on the timeline. +/// +/// 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_streams`). fn audio_matches(source: &Source, first: &Option) -> crate::Result<()> { - // Whole-probe equality: rate, layout and the esds fields, which the audio - // worker holds every source to anyway. Both silent is a match. + // Whole-probe equality: rate and layout, which the audio worker holds every + // source to anyway. Both silent is a match. let probe = AudioSession::probe(&source.path, source.audio_stream)?; - 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 - ), - } + 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/src/waveform.rs b/crates/engine/src/waveform.rs index e3d6eff..10b0129 100644 --- a/crates/engine/src/waveform.rs +++ b/crates/engine/src/waveform.rs @@ -116,6 +116,31 @@ mod tests { } } + /// A song's clip draws like any other: this goes through the same + /// `open_multi_streams` the timeline plays with, which reads a standalone + /// audio file on stream 0 as readily as an mp4's AAC track. + #[test] + fn a_standalone_audio_file_has_peaks_too() { + let peaks = peaks(asset("test_tone.mp3"), 0, BPS) + .expect("open") + .expect("test_tone.mp3 is audio"); + let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one + assert!( + peaks.len().abs_diff(want) <= 2, + "{} buckets, want {want} +/-2", + peaks.len() + ); + // The fixture carries the A/V one's 1 Hz envelope, so the middle second + // has a dip and a peak. As a ratio, and a looser one: the tone sits + // around an eighth of full scale and mp3 does not preserve a true zero. + let level = |&(lo, hi): &(f32, f32)| hi - lo; + let band = &peaks[BPS as usize..][..BPS as usize]; + let dip = band.iter().map(level).fold(f32::MAX, f32::min); + let loudest = band.iter().map(level).fold(0.0, f32::max); + assert!(loudest > 0.05, "peak level only {loudest}"); + assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}"); + } + #[test] fn video_only_source_has_no_peaks() { assert!( 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 43cb5c7..63fd59e 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"), 0) .unwrap() diff --git a/crates/engine/tests/audio_streams.rs b/crates/engine/tests/audio_streams.rs index d9a4dd6..f83bbc0 100644 --- a/crates/engine/tests/audio_streams.rs +++ b/crates/engine/tests/audio_streams.rs @@ -179,3 +179,49 @@ fn an_impossible_stream_is_refused_not_guessed() { ); assert!(AudioSession::open_multi_streams(&[(silent, 1)], &[(Some(0), 0.0, 1.0)]).is_err()); } + +/// Where the stream picker meets a file that has no picture to pick against: a +/// standalone audio file is one stream, so it lists as one and answers to 0 +/// alone. A picker that offered a second row here would be offering a track +/// that does not exist. +#[test] +fn a_standalone_audio_file_is_exactly_one_stream() { + for (name, codec) in [("test_tone.mp3", "mp3"), ("test_tone.flac", "flac")] { + let streams = AudioSession::probe_streams(asset(name)).expect("probes"); + assert_eq!( + streams, + vec![StreamInfo { + index: 0, + codec: codec.into(), + channels: 2, + sample_rate: 44100, + // No mdhd to carry an ISO-639 tag, and one track needs no + // telling apart. + lang: None, + decodable: true, + }], + "{name}" + ); + // Stream 0 opens; anything above it is refused rather than quietly + // served the only track there is. + assert!( + AudioSession::open_multi_streams(&[(asset(name), 0)], &[(Some(0), 0.0, 1.0)]) + .expect("stream 0 opens") + .is_some(), + "{name}" + ); + let err = AudioSession::open_multi_streams(&[(asset(name), 1)], &[(Some(0), 0.0, 1.0)]) + .expect_err("there is no stream 1"); + assert!( + err.to_string().contains("audio stream 1 of 1 stream"), + "unhelpful refusal for {name}: {err}" + ); + } + // The ALAC .m4a is the awkward one: it parses as an mp4 whose only audio + // track is not AAC, so the mp4 walk would call it "unknown" and undecodable + // where symphonia decodes it perfectly well. + let alac = AudioSession::probe_streams(asset("test_tone.m4a")).expect("probes"); + assert_eq!(alac.len(), 1); + assert!(alac[0].decodable, "ALAC decodes: {alac:?}"); + assert_eq!((alac[0].sample_rate, alac[0].channels), (44100, 2)); +} diff --git a/crates/engine/tests/hevc.rs b/crates/engine/tests/hevc.rs index db58b5a..a128ab6 100644 --- a/crates/engine/tests/hevc.rs +++ b/crates/engine/tests/hevc.rs @@ -45,7 +45,7 @@ fn the_demuxer_reports_an_hevc_track() { .expect("probe") .expect("the fixture has an AAC track"); assert_eq!( - (probe.params.sample_rate, probe.channels), + (probe.sample_rate, probe.channels), (44_100, 2), "audio is read the same whatever the picture is coded with" ); diff --git a/crates/engine/tests/vp9.rs b/crates/engine/tests/vp9.rs index 420bab2..6ef227c 100644 --- a/crates/engine/tests/vp9.rs +++ b/crates/engine/tests/vp9.rs @@ -44,7 +44,7 @@ fn the_demuxer_reports_a_vp9_track() { .expect("probe") .expect("the fixture has an AAC track"); assert_eq!( - (probe.params.sample_rate, probe.channels), + (probe.sample_rate, probe.channels), (44_100, 2), "audio is read the same whatever the picture is coded with" ); diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 8ea07c7..3e8a629 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -89,4 +89,31 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ # 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/"