forge
Explore
Log in

Don't you dare go Hollow

Common audio files import and play

Browse files at this commit

fe53979b702e6c94b280f2c8288270b94309c952Ahmet Kaan GümüşParent: 771cd4a
  • feat
    • common audio files import and play
Show full message
✨ feat(engine): common audio files import and play

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.lockmodified+118 -0
@@ -1612,6 +1612,7 @@ dependencies = [
1612 "libloading",1612 "libloading",
1613 "mp4",1613 "mp4",
1614 "rusty_h264",1614 "rusty_h264",
1615+ "symphonia",
1615 "symphonia-codec-aac",1616 "symphonia-codec-aac",
1616 "symphonia-core",1617 "symphonia-core",
1617 ]1618 ]
@@ -1764,6 +1765,12 @@ dependencies = [
1764 "zune-inflate",1765 "zune-inflate",
1765 ]1766 ]
1766 1767
1768+[[package]]
1769+name = "extended"
1770+version = "0.1.0"
1771+source = "registry+https://github.com/rust-lang/crates.io-index"
1772+checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
1773+
1767 [[package]]1774 [[package]]
1768 name = "fastrand"1775 name = "fastrand"
1769 version = "1.9.0"1776 version = "1.9.0"
@@ -5485,6 +5492,49 @@ dependencies = [
5485 "zeno",5492 "zeno",
5486 ]5493 ]
5487 5494
5495+[[package]]
5496+name = "symphonia"
5497+version = "0.6.0"
5498+source = "registry+https://github.com/rust-lang/crates.io-index"
5499+checksum = "1758d6c853020a7244de03cc3e0185eaea3f58715122422dd3cc7452e6d4c16a"
5500+dependencies = [
5501+ "lazy_static",
5502+ "symphonia-bundle-flac",
5503+ "symphonia-bundle-mp3",
5504+ "symphonia-codec-aac",
5505+ "symphonia-codec-alac",
5506+ "symphonia-codec-pcm",
5507+ "symphonia-codec-vorbis",
5508+ "symphonia-core",
5509+ "symphonia-format-isomp4",
5510+ "symphonia-format-ogg",
5511+ "symphonia-format-riff",
5512+ "symphonia-metadata",
5513+]
5514+
5515+[[package]]
5516+name = "symphonia-bundle-flac"
5517+version = "0.6.0"
5518+source = "registry+https://github.com/rust-lang/crates.io-index"
5519+checksum = "ee69ad01236a67260b82fd1ff9790dd75ead29f2f46af145e63b7e72273e0e03"
5520+dependencies = [
5521+ "log",
5522+ "symphonia-common",
5523+ "symphonia-core",
5524+ "symphonia-metadata",
5525+]
5526+
5527+[[package]]
5528+name = "symphonia-bundle-mp3"
5529+version = "0.6.0"
5530+source = "registry+https://github.com/rust-lang/crates.io-index"
5531+checksum = "350f1f2f2e19ad4dd315db94304d1eb361b29af070681f94e51b8fdaad769546"
5532+dependencies = [
5533+ "lazy_static",
5534+ "log",
5535+ "symphonia-core",
5536+]
5537+
5488 [[package]]5538 [[package]]
5489 name = "symphonia-codec-aac"5539 name = "symphonia-codec-aac"
5490 version = "0.6.0"5540 version = "0.6.0"
@@ -5497,6 +5547,38 @@ dependencies = [
5497 "symphonia-core",5547 "symphonia-core",
5498 ]5548 ]
5499 5549
5550+[[package]]
5551+name = "symphonia-codec-alac"
5552+version = "0.6.0"
5553+source = "registry+https://github.com/rust-lang/crates.io-index"
5554+checksum = "3a149cbfc7fb5c405d123a273227d31de17138419552112bf1aa7b73e65827b8"
5555+dependencies = [
5556+ "log",
5557+ "symphonia-common",
5558+ "symphonia-core",
5559+]
5560+
5561+[[package]]
5562+name = "symphonia-codec-pcm"
5563+version = "0.6.0"
5564+source = "registry+https://github.com/rust-lang/crates.io-index"
5565+checksum = "50baee168f0e9dcf6ba7fc06e8b57eb62072a4490cc7cf13af77e72baae5d328"
5566+dependencies = [
5567+ "log",
5568+ "symphonia-core",
5569+]
5570+
5571+[[package]]
5572+name = "symphonia-codec-vorbis"
5573+version = "0.6.0"
5574+source = "registry+https://github.com/rust-lang/crates.io-index"
5575+checksum = "45b07b4423cd8e0fc472575909a5554b12c2f58e3c190b38c24f042e732fd8de"
5576+dependencies = [
5577+ "log",
5578+ "symphonia-common",
5579+ "symphonia-core",
5580+]
5581+
5500 [[package]]5582 [[package]]
5501 name = "symphonia-common"5583 name = "symphonia-common"
5502 version = "0.6.0"5584 version = "0.6.0"
@@ -5522,6 +5604,42 @@ dependencies = [
5522 "smallvec",5604 "smallvec",
5523 ]5605 ]
5524 5606
5607+[[package]]
5608+name = "symphonia-format-isomp4"
5609+version = "0.6.0"
5610+source = "registry+https://github.com/rust-lang/crates.io-index"
5611+checksum = "2d179a01305b3505940135a9f0180d6ef4b487912748fe97554756f120fbd05e"
5612+dependencies = [
5613+ "log",
5614+ "symphonia-common",
5615+ "symphonia-core",
5616+ "symphonia-metadata",
5617+]
5618+
5619+[[package]]
5620+name = "symphonia-format-ogg"
5621+version = "0.6.0"
5622+source = "registry+https://github.com/rust-lang/crates.io-index"
5623+checksum = "b05a67e02b1e4fca1a261ba4fe06910a9357489ad8c36aafdd2960e9c6559433"
5624+dependencies = [
5625+ "log",
5626+ "symphonia-common",
5627+ "symphonia-core",
5628+ "symphonia-metadata",
5629+]
5630+
5631+[[package]]
5632+name = "symphonia-format-riff"
5633+version = "0.6.0"
5634+source = "registry+https://github.com/rust-lang/crates.io-index"
5635+checksum = "17424452a777666d3eaf09a5c651029b15b6a333812fcc5b5474f2a3f0cff3f0"
5636+dependencies = [
5637+ "extended",
5638+ "log",
5639+ "symphonia-core",
5640+ "symphonia-metadata",
5641+]
5642+
5525 [[package]]5643 [[package]]
5526 name = "symphonia-metadata"5644 name = "symphonia-metadata"
5527 version = "0.6.0"5645 version = "0.6.0"
crates/app/src/main.rsmodified+39 -5
@@ -549,10 +549,29 @@ impl Player {
549 /// moves along rather than being painted over. Reseeks like every other549 /// moves along rather than being painted over. Reseeks like every other
550 /// edit, and drops the timeline's selection with it: the insert has just550 /// edit, and drops the timeline's selection with it: the insert has just
551 /// moved the indices it pointed at.551 /// moved the indices it pointed at.
552- fn insert_source(&mut self, source: usize, cx: &mut Context<Self>) {552+ fn insert_source(&mut self, source: usize, onto: Option<Lane>, cx: &mut Context<Self>) {
553 if self.exporting().is_some() {553 if self.exporting().is_some() {
554 return;554 return;
555 }555 }
556+ // A file with no picture belongs on the audio lane and nowhere else:
557+ // dropped on the video lane it is refused by name, and asked for by the
558+ // Add button (which names no lane) it goes to the audio one.
559+ let songs: bool = self
560+ .session
561+ .as_ref()
562+ .and_then(|session| session.sources().get(source))
563+ .is_some_and(|path| engine::is_audio(path));
564+ if songs && onto == Some(Lane::Video) {
565+ let name = self
566+ .session
567+ .as_ref()
568+ .map_or_else(String::new, |session| file_name(&session.sources()[source]));
569+ self.notice = Some(
570+ format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(),
571+ );
572+ cx.notify();
573+ return;
574+ }
556 let clip = self.session.as_ref().and_then(|session| {575 let clip = self.session.as_ref().and_then(|session| {
557 let frames = source_frames(lane_clips(session), source);576 let frames = source_frames(lane_clips(session), source);
558 // Zero means nothing on the timeline plays from that file any more577 // Zero means nothing on the timeline plays from that file any more
@@ -567,6 +586,12 @@ impl Player {
567 })586 })
568 });587 });
569 let added = match (&mut self.session, clip) {588 let added = match (&mut self.session, clip) {
589+ // One lane, no ripple: there is nothing on the video lane to move
590+ // along with it, and a song laid over the picture is what dropping
591+ // it at the playhead means.
592+ (Some(session), Some(clip)) if songs => {
593+ session.place_at(Lane::Audio, session.now(), clip)
594+ }
570 (Some(session), Some(clip)) => session.paste_at(session.now(), clip),595 (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
571 _ => false,596 _ => false,
572 };597 };
@@ -1218,6 +1243,13 @@ impl Player {
1218 .map_or(0, |session| source_frames(lane_clips(session), i));1243 .map_or(0, |session| source_frames(lane_clips(session), i));
1219 let name: SharedString = file_name(path).into();1244 let name: SharedString = file_name(path).into();
1220 let tip: SharedString = match meta {1245 let tip: SharedString = match meta {
1246+ // A file with no picture has no size and no frame rate to
1247+ // report, and only one lane it can go on: saying so is the
1248+ // difference between a hint and a lie.
1249+ _ if engine::is_audio(path) => format!(
1250+ "{} — audio only · drag onto the audio lane, or Add at playhead",
1251+ path.display()
1252+ ),
1221 Some(meta) => format!(1253 Some(meta) => format!(
1222 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",1254 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1223 path.display(),1255 path.display(),
@@ -1347,7 +1379,9 @@ impl Player {
1347 can_add(self.selected_asset, self.session.is_some(), exporting),1379 can_add(self.selected_asset, self.session.is_some(), exporting),
1348 cx.listener(|this, _: &ClickEvent, _, cx| {1380 cx.listener(|this, _: &ClickEvent, _, cx| {
1349 if let Some(source) = this.selected_asset {1381 if let Some(source) = this.selected_asset {
1350- this.insert_source(source, cx);1382+ // No lane: the button means "wherever this belongs",
1383+ // which for a file with no picture is the audio lane.
1384+ this.insert_source(source, None, cx);
1351 }1385 }
1352 }),1386 }),
1353 ))1387 ))
@@ -1944,9 +1978,9 @@ impl Player {
1944 // Add button makes, through the same call -- at the1978 // Add button makes, through the same call -- at the
1945 // playhead, not at the pointer: clips here are placed end1979 // playhead, not at the pointer: clips here are placed end
1946 // to end, so where along the bed it landed says nothing.1980 // to end, so where along the bed it landed says nothing.
1947- .on_drop(1981+ .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| {
1948- cx.listener(|this, drag: &AssetDrag, _, cx| this.insert_source(drag.0, cx)),1982+ this.insert_source(drag.0, Some(lane), cx)
1949- )1983+ }))
1950 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))1984 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
1951 .children(clips.iter().enumerate().map(|(i, clip)| {1985 .children(clips.iter().enumerate().map(|(i, clip)| {
1952 let (start, len) = (1986 let (start, len) = (
crates/engine/Cargo.tomlmodified+19 -0
@@ -10,3 +10,22 @@ mp4 = "0.14"
10 rusty_h264 = { version = "0.8", default-features = false }10 rusty_h264 = { version = "0.8", default-features = false }
11 symphonia-core = "0.6"11 symphonia-core = "0.6"
12 symphonia-codec-aac = "0.6"12 symphonia-codec-aac = "0.6"
13+# The umbrella crate for the standalone audio files: one dependency instead of
14+# seven, and its `default::get_probe`/`get_codecs` are the registries this would
15+# otherwise hand-build. Explicit feature list rather than the default one -- no
16+# mkv, no ape, no adpcm: what is listed here is exactly what `is_audio` admits.
17+# There is no opus/ac3/dts feature at any symphonia version, which is why those
18+# are refused rather than promised.
19+symphonia = { version = "0.6", default-features = false, features = [
20+ "aac",
21+ "alac",
22+ "flac",
23+ "id3v1",
24+ "id3v2",
25+ "isomp4",
26+ "mp3",
27+ "ogg",
28+ "pcm",
29+ "vorbis",
30+ "wav",
31+] }
crates/engine/src/audio.rsmodified+409 -45
@@ -1,6 +1,14 @@
1-//! Background audio decode worker: pulls the AAC track out of an MP4 and hands1+//! Background audio decode worker: pulls a source's audio track and hands
2 //! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own2 //! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own
3-//! `Mp4Reader` so the video demuxer stays single-owner.3+//! reader so the video demuxer stays single-owner.
4+//!
5+//! Two readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as
6+//! it always has -- that path also yields the raw access units the export
7+//! copies, which is the only reason it is kept separate -- and a standalone
8+//! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through
9+//! symphonia's own format probe. Everything downstream of [`Track`] sees the
10+//! same samples either way; only the packet copy asks which reader it came from,
11+//! because there is nothing to copy out of an mp3 that an mp4 can hold.
4 12
5 use std::fs::File;13 use std::fs::File;
6 use std::io::BufReader;14 use std::io::BufReader;
@@ -13,8 +21,13 @@ use symphonia_codec_aac::AacDecoder;
13 use symphonia_core::codecs::audio::{21 use symphonia_core::codecs::audio::{
14 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,22 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,
15 };23 };
24+use symphonia_core::formats::probe::Hint;
25+use symphonia_core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo, TrackType};
26+use symphonia_core::io::MediaSourceStream;
27+use symphonia_core::meta::MetadataOptions;
16 use symphonia_core::packet::Packet;28 use symphonia_core::packet::Packet;
17 use symphonia_core::units;29 use symphonia_core::units;
30+use symphonia_core::units::{Time, TimeBase};
18 31
19 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.32 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
20 /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)33 /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
@@ -30,6 +43,12 @@ const PRE_ROLL: u32 = 2;
30 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.43 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.
31 const SAMPLES_PER_PACKET: u32 = 1024;44 const SAMPLES_PER_PACKET: u32 = 1024;
32 45
46+/// Frames per channel a seek into a standalone audio file lands ahead of the
47+/// window, decoded and thrown away: enough to refill an mp3's bit reservoir
48+/// (a frame is 1152 samples and the reservoir reaches back two of them) at any
49+/// rate we accept.
50+const SYM_PRE_ROLL: u64 = 8192;
51+
33 #[derive(Debug, Clone, Copy, PartialEq)]52 #[derive(Debug, Clone, Copy, PartialEq)]
34 pub struct AudioMeta {53 pub struct AudioMeta {
35 pub sample_rate: u32,54 pub sample_rate: u32,
@@ -67,9 +86,14 @@ pub struct AacPacket {
67 86
68 /// Everything an import check needs from a candidate file's audio track. Two87 /// Everything an import check needs from a candidate file's audio track. Two
69 /// files may share a timeline only when their probes are equal (or both `None`).88 /// files may share a timeline only when their probes are equal (or both `None`).
89+///
90+/// Rate and layout only: those are what one output device and one exported track
91+/// can carry, and an mp3 that agrees on both may join a timeline of mp4s even
92+/// though nothing about it can be *copied* into an export -- that is a separate
93+/// refusal, at export time, in [`AudioSession::copy_multi_segments`].
70 #[derive(Debug, Clone, Copy, PartialEq)]94 #[derive(Debug, Clone, Copy, PartialEq)]
71 pub struct AudioProbe {95 pub struct AudioProbe {
72- pub params: AacTrackParams,96+ pub sample_rate: u32,
73 pub channels: u16,97 pub channels: u16,
74 }98 }
75 99
@@ -141,13 +165,13 @@ impl AudioSession {
141 // The timeline's meta is the first source's: policy makes every other165 // The timeline's meta is the first source's: policy makes every other
142 // source match it, and the checks below hold them to that.166 // source match it, and the checks below hold them to that.
143 let meta = AudioMeta {167 let meta = AudioMeta {
144- sample_rate: first.sample_rate,168+ sample_rate: first.sample_rate(),
145 channels: first.channels()?,169 channels: first.channels()?,
146- total_samples: first.total_samples,170+ total_samples: first.total_samples(),
147 };171 };
148 // Built here only so an undecodable stream is an `Err` from the opener172 // Built here only so an undecodable stream is an `Err` from the opener
149 // rather than a silently empty channel; the worker makes its own.173 // rather than a silently empty channel; the worker makes its own.
150- AacDecoder::try_new(&first.params, &AudioDecoderOptions::default())?;174+ first.check_decoder()?;
151 175
152 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();176 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
153 tracks[0] = Some(first);177 tracks[0] = Some(first);
@@ -163,17 +187,17 @@ impl AudioSession {
163 }187 }
164 let track = Track::open(&sources[source])?188 let track = Track::open(&sources[source])?
165 .ok_or_else(|| format!("source {source} has no audio track"))?;189 .ok_or_else(|| format!("source {source} has no audio track"))?;
166- if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) {190+ if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {
167 return Err(format!(191 return Err(format!(
168 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",192 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
169- track.sample_rate,193+ track.sample_rate(),
170 track.channels()?,194 track.channels()?,
171 meta.sample_rate,195 meta.sample_rate,
172 meta.channels196 meta.channels
173 )197 )
174 .into());198 .into());
175 }199 }
176- AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())?;200+ track.check_decoder()?;
177 *slot = Some(track);201 *slot = Some(track);
178 }202 }
179 203
@@ -194,7 +218,7 @@ impl AudioSession {
194 let timeline = segments.first().map_or(0, |s| match s.source {218 let timeline = segments.first().map_or(0, |s| match s.source {
195 Some(source) => s219 Some(source) => s
196 .media_target220 .media_target
197- .saturating_sub(tracks[source].as_ref().expect("opened above").priming),221+ .saturating_sub(tracks[source].as_ref().expect("opened above").priming()),
198 None => 0,222 None => 0,
199 });223 });
200 224
@@ -218,18 +242,46 @@ impl AudioSession {
218 242
219 /// The audio parameters of `path`, for checking an import against the243 /// The audio parameters of `path`, for checking an import against the
220 /// timeline's first source: header only, no decoder and no worker.244 /// timeline's first source: header only, no decoder and no worker.
221- /// `Ok(None)` means no AAC track — an audio-less file, which import pairs245+ /// `Ok(None)` means no audio track — a silent file, which import pairs
222- /// only with other audio-less files.246+ /// only with other silent files.
223 pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> {247 pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> {
224 let Some(track) = Track::open(path.as_ref())? else {248 let Some(track) = Track::open(path.as_ref())? else {
225 return Ok(None);249 return Ok(None);
226 };250 };
227 Ok(Some(AudioProbe {251 Ok(Some(AudioProbe {
228- params: track.track_params(),252+ sample_rate: track.sample_rate(),
229 channels: track.channels()?,253 channels: track.channels()?,
230 }))254 }))
231 }255 }
232 256
257+ /// How long `path`'s audio plays, in seconds. `Ok(None)` for a silent file.
258+ ///
259+ /// A standalone audio file is a source with no frame count of its own, so
260+ /// this is what its length on the timeline is derived from. Taken from the
261+ /// header where there is one; a stream that does not say — a bare mp3 with
262+ /// no Xing header is the usual one — is *decoded* to find out, which is
263+ /// linear in its length (~0.5 ms per source second) and happens once, at
264+ /// import, rather than per repaint.
265+ pub fn duration_secs(path: impl AsRef<Path>) -> crate::Result<Option<f64>> {
266+ let path = path.as_ref();
267+ let Some(track) = Track::open(path)? else {
268+ return Ok(None);
269+ };
270+ let rate = f64::from(track.sample_rate().max(1));
271+ if let Some(total) = track.total_samples() {
272+ return Ok(Some(total as f64 / rate));
273+ }
274+ drop(track);
275+ let Some((meta, rx)) = Self::open(path)? else {
276+ return Ok(None);
277+ };
278+ let channels = usize::from(meta.channels.max(1));
279+ let last = rx.into_iter().fold(0, |_, chunk| {
280+ chunk.start_sample + (chunk.samples.len() / channels) as u64
281+ });
282+ Ok(Some(last as f64 / f64::from(meta.sample_rate.max(1))))
283+ }
284+
233 /// The raw AAC packets covering `segs` — the same half-open source-second285 /// The raw AAC packets covering `segs` — the same half-open source-second
234 /// windows [`open_segments`](Self::open_segments) decodes — copied out286 /// windows [`open_segments`](Self::open_segments) decodes — copied out
235 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go287 /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go
@@ -284,11 +336,11 @@ impl AudioSession {
284 let path = sources336 let path = sources
285 .get(first)337 .get(first)
286 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;338 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
287- let Some(track) = Track::open(path)? else {339+ let Some(track) = copy_track(path)? else {
288 return Ok(None); // silent source, silent export340 return Ok(None); // silent source, silent export
289 };341 };
290 let params = track.track_params();342 let params = track.track_params();
291- let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();343+ let mut tracks: Vec<Option<AacTrack>> = sources.iter().map(|_| None).collect();
292 tracks[first] = Some(track);344 tracks[first] = Some(track);
293 345
294 let sample_rate = params.sample_rate;346 let sample_rate = params.sample_rate;
@@ -376,27 +428,239 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
376 /// The source at `index`, opened on first use. Sources a segment list never428 /// The source at `index`, opened on first use. Sources a segment list never
377 /// names are never touched: a project's list only grows.429 /// names are never touched: a project's list only grows.
378 fn source_at<'a>(430 fn source_at<'a>(
379- tracks: &'a mut [Option<Track>],431+ tracks: &'a mut [Option<AacTrack>],
380 sources: &[PathBuf],432 sources: &[PathBuf],
381 index: usize,433 index: usize,
382-) -> crate::Result<&'a mut Track> {434+) -> crate::Result<&'a mut AacTrack> {
383 let slot = tracks435 let slot = tracks
384 .get_mut(index)436 .get_mut(index)
385 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;437 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
386 if slot.is_none() {438 if slot.is_none() {
387 *slot = Some(439 *slot = Some(
388- Track::open(&sources[index])?440+ copy_track(&sources[index])?
389 .ok_or_else(|| format!("source {index} has no audio track"))?,441 .ok_or_else(|| format!("source {index} has no audio track"))?,
390 );442 );
391 }443 }
392 Ok(slot.as_mut().expect("just opened"))444 Ok(slot.as_mut().expect("just opened"))
393 }445 }
394 446
447+/// A source's track for the *copy* path, which needs raw AAC access units.
448+///
449+/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by
450+/// name and by format rather than exported silent or, worse, exported as noise:
451+/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]),
452+/// so a timeline carrying one of those simply cannot become an mp4 today. The
453+/// wording is what a front-end shows.
454+///
455+/// `Ok(None)` for a file with no audio at all, which is a silent export.
456+fn copy_track(path: &Path) -> crate::Result<Option<AacTrack>> {
457+ match Track::open(path)? {
458+ None => Ok(None),
459+ Some(Track::Aac(track)) => Ok(Some(track)),
460+ Some(Track::Sym(track)) => Err(format!(
461+ "export needs AAC audio today; {} is {}",
462+ path.file_name()
463+ .unwrap_or(path.as_os_str())
464+ .to_string_lossy(),
465+ track.codec
466+ )
467+ .into()),
468+ }
469+}
470+
471+/// One source's audio, however it is stored: the mp4 AAC track the export can
472+/// copy, or a standalone file read through symphonia's probe. The opener and
473+/// the worker speak to this, never to either reader directly.
474+enum Track {
475+ Aac(AacTrack),
476+ Sym(SymTrack),
477+}
478+
479+impl Track {
480+ /// `Ok(None)` for a file with no audio, which is a valid silent source.
481+ ///
482+ /// The mp4 reader goes first and its verdict is final for anything that is
483+ /// not [`crate::is_audio`]: a video file's audio track is exactly what it
484+ /// always was, silent mp4s included (an mp4 whose only `soun` track is one
485+ /// we cannot decode has always been a silent source, not an error). Only a
486+ /// standalone audio file falls through to symphonia — which is also how an
487+ /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track.
488+ fn open(path: &Path) -> crate::Result<Option<Self>> {
489+ let audio_file = crate::is_audio(path);
490+ match AacTrack::open(path) {
491+ Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
492+ Ok(None) if !audio_file => return Ok(None),
493+ Err(e) if !audio_file => return Err(e),
494+ _ => {}
495+ }
496+ SymTrack::open(path).map(|track| Some(Self::Sym(track)))
497+ }
498+
499+ fn sample_rate(&self) -> u32 {
500+ match self {
501+ Self::Aac(t) => t.sample_rate,
502+ Self::Sym(t) => t.sample_rate,
503+ }
504+ }
505+
506+ /// Mono or stereo; anything wider is refused here rather than one packet at
507+ /// a time, because one output device and one copied track is all there is.
508+ fn channels(&self) -> crate::Result<u16> {
509+ match self {
510+ Self::Aac(t) => t.channels(),
511+ Self::Sym(t) => match t.channels {
512+ 1 | 2 => Ok(t.channels),
513+ n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
514+ },
515+ }
516+ }
517+
518+ /// Frames per channel of *audible* audio, priming already subtracted.
519+ fn total_samples(&self) -> Option<u64> {
520+ match self {
521+ Self::Aac(t) => t.total_samples,
522+ Self::Sym(t) => t.total_samples,
523+ }
524+ }
525+
526+ /// Encoder delay of this file. Sources are joined, priming is not shared.
527+ fn priming(&self) -> u64 {
528+ match self {
529+ Self::Aac(t) => t.priming,
530+ Self::Sym(t) => t.priming,
531+ }
532+ }
533+
534+ /// One `[start, end)` window of this source's seconds, resolved to whatever
535+ /// its own reader needs to find it again.
536+ fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
537+ match self {
538+ Self::Aac(t) => t.segment(source, start_secs, end_secs),
539+ Self::Sym(t) => {
540+ let media_target = t.media(start_secs);
541+ Segment {
542+ source: Some(source),
543+ start_id: 0,
544+ start_pos: 0,
545+ media_target,
546+ media_end: t.media(end_secs).max(media_target),
547+ }
548+ }
549+ }
550+ }
551+
552+ /// Builds and throws away a decoder, so an undecodable stream is an `Err`
553+ /// from the opener rather than a silently empty channel.
554+ fn check_decoder(&self) -> crate::Result<()> {
555+ match self {
556+ Self::Aac(t) => {
557+ AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
558+ }
559+ Self::Sym(t) => {
560+ t.decoder()?;
561+ }
562+ }
563+ Ok(())
564+ }
565+}
566+
567+/// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read
568+/// through symphonia's own probe and codec registry. No packet table and no
569+/// sample ids: the reader is *seeked* per segment and the packets it then hands
570+/// out carry their own timestamps.
571+struct SymTrack {
572+ reader: Box<dyn FormatReader>,
573+ track_id: u32,
574+ sample_rate: u32,
575+ channels: u16,
576+ /// Frames per channel of audible audio, `None` when the header does not say.
577+ total_samples: Option<u64>,
578+ /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the
579+ /// container where it declares one (mp3's Xing/LAME tag, ALAC's edit list).
580+ priming: u64,
581+ time_base: TimeBase,
582+ params: AudioCodecParameters,
583+ /// The format's short name, for the export refusal. `&'static` because it
584+ /// comes out of the codec registry, which outlives everything here.
585+ codec: &'static str,
586+}
587+
588+impl SymTrack {
589+ fn open(path: &Path) -> crate::Result<Self> {
590+ let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
591+ // The extension is a hint, not a decision: the probe reads the magic and
592+ // is free to disagree, which is what makes a mislabelled file work.
593+ let mut hint = Hint::new();
594+ if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
595+ hint.with_extension(ext);
596+ }
597+ let reader = symphonia::default::get_probe().probe(
598+ &hint,
599+ mss,
600+ FormatOptions::default(),
601+ MetadataOptions::default(),
602+ )?;
603+ let track = reader
604+ .default_track(TrackType::Audio)
605+ .ok_or_else(|| format!("{} has no audio track", path.display()))?;
606+ let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay);
607+ let time_base = track
608+ .time_base
609+ .ok_or_else(|| format!("{} declares no time base", path.display()))?;
610+ let Some(symphonia_core::codecs::CodecParameters::Audio(params)) =
611+ track.codec_params.clone()
612+ else {
613+ return Err(format!("{} declares no audio codec", path.display()).into());
614+ };
615+ let sample_rate = params
616+ .sample_rate
617+ .ok_or_else(|| format!("{} declares no sample rate", path.display()))?;
618+ let channels = params
619+ .channels
620+ .as_ref()
621+ .map(|c| c.count() as u16)
622+ .ok_or_else(|| format!("{} declares no channel layout", path.display()))?;
623+ let codec = symphonia::default::get_codecs()
624+ .get_audio_decoder(params.codec)
625+ .map_or("an unsupported format", |d| d.codec.info.short_name);
626+ Ok(Self {
627+ reader,
628+ track_id,
629+ sample_rate,
630+ channels,
631+ total_samples: num_frames,
632+ priming: u64::from(delay.unwrap_or(0)),
633+ time_base,
634+ params,
635+ codec,
636+ })
637+ }
638+
639+ /// A fresh decoder: seeking mid-stream leaves state that belongs to the
640+ /// packets we skipped, exactly as on the AAC path.
641+ fn decoder(&self) -> crate::Result<Box<dyn AudioDecoder>> {
642+ Ok(symphonia::default::get_codecs()
643+ .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?)
644+ }
645+
646+ /// `secs` on this source's audible timeline into media samples (priming
647+ /// included, so it compares directly against a decoded position).
648+ fn media(&self, secs: f64) -> u64 {
649+ ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
650+ }
651+
652+ /// A packet timestamp in the track's time base, as samples per channel.
653+ fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {
654+ let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
655+ (secs.max(0.0) * f64::from(self.sample_rate)) as u64
656+ }
657+}
658+
395 /// One source's AAC track, resolved once: the reader plus everything the header659 /// One source's AAC track, resolved once: the reader plus everything the header
396 /// has to say about it. `stts` is copied out because every other field would660 /// has to say about it. `stts` is copied out because every other field would
397 /// otherwise keep a borrow alive on the reader the worker needs mutably — a real661 /// otherwise keep a borrow alive on the reader the worker needs mutably — a real
398 /// AAC track has one entry, so it is two `u32`s.662 /// AAC track has one entry, so it is two `u32`s.
399-struct Track {663+struct AacTrack {
400 reader: Mp4Reader<BufReader<File>>,664 reader: Mp4Reader<BufReader<File>>,
401 track_id: u32,665 track_id: u32,
402 sample_count: u32,666 sample_count: u32,
@@ -414,7 +678,7 @@ struct Track {
414 params: AudioCodecParameters,678 params: AudioCodecParameters,
415 }679 }
416 680
417-impl Track {681+impl AacTrack {
418 /// `Ok(None)` for a file with no AAC track, which is a valid silent source.682 /// `Ok(None)` for a file with no AAC track, which is a valid silent source.
419 fn open(path: &Path) -> crate::Result<Option<Self>> {683 fn open(path: &Path) -> crate::Result<Option<Self>> {
420 let file = File::open(path)?;684 let file = File::open(path)?;
@@ -723,6 +987,15 @@ fn run(mut w: Worker) {
723 let Some(track) = w.tracks[source].as_mut() else {987 let Some(track) = w.tracks[source].as_mut() else {
724 continue; // opener fills every named source; nothing to decode988 continue; // opener fills every named source; nothing to decode
725 };989 };
990+ let track = match track {
991+ Track::Sym(track) => {
992+ if !run_sym(track, seg, channels, &mut timeline, &w.tx) {
993+ return; // consumer went away
994+ }
995+ continue;
996+ }
997+ Track::Aac(track) => track,
998+ };
726 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())999 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())
727 {1000 {
728 Ok(decoder) => decoder,1001 Ok(decoder) => decoder,
@@ -760,35 +1033,126 @@ fn run(mut w: Worker) {
760 };1033 };
761 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);1034 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
762 let next = pos + (interleaved.len() / channels) as u64;1035 let next = pos + (interleaved.len() / channels) as u64;
763-1036+ if !emit(
764- // Everything before the target is encoder priming and/or decoder1037+ &mut interleaved,
765- // pre-roll, not audio the caller asked for: drop it, splitting the1038+ channels,
766- // packet that straddles the target.1039+ seg,
767- if next <= seg.media_target {1040+ pos,
768- pos = next;1041+ next,
769- continue;1042+ &mut timeline,
770- }1043+ &w.tx,
771- if pos < seg.media_target {1044+ ) {
772- interleaved.drain(..(seg.media_target - pos) as usize * channels);1045+ return; // consumer went away
773- pos = seg.media_target;
774- }
775- // And the tail past the segment end goes too — on a short segment
776- // that is this same buffer, trimmed at both ends.
777- if next > seg.media_end {
778- interleaved.truncate((seg.media_end - pos) as usize * channels);
779 }1046 }
780 pos = next;1047 pos = next;
781- if interleaved.is_empty() {1048+ }
782- continue; // nothing left of it; the loop head ends the segment1049+ }
1050+}
1051+
1052+/// Trims one decoded buffer to the segment window and sends what survives.
1053+/// `pos` is the media position of its first frame and `next` of the one after
1054+/// it; both readers hand the same thing here, which is why the window rules
1055+/// live in one place. `false` means the consumer went away.
1056+///
1057+/// Everything before the target is encoder priming and/or decoder pre-roll, not
1058+/// audio the caller asked for: it is dropped, splitting the buffer that
1059+/// straddles the target. The tail past the segment end goes too — on a short
1060+/// segment that is this same buffer, trimmed at both ends.
1061+fn emit(
1062+ interleaved: &mut Vec<f32>,
1063+ channels: usize,
1064+ seg: &Segment,
1065+ pos: u64,
1066+ next: u64,
1067+ timeline: &mut u64,
1068+ tx: &SyncSender<AudioChunk>,
1069+) -> bool {
1070+ if next <= seg.media_target {
1071+ return true;
1072+ }
1073+ let mut pos = pos;
1074+ if pos < seg.media_target {
1075+ interleaved.drain(..(seg.media_target - pos) as usize * channels);
1076+ pos = seg.media_target;
1077+ }
1078+ if next > seg.media_end {
1079+ interleaved.truncate((seg.media_end - pos) as usize * channels);
1080+ }
1081+ if interleaved.is_empty() {
1082+ return true; // nothing left of it; the loop head ends the segment
1083+ }
1084+ let chunk = AudioChunk {
1085+ start_sample: *timeline,
1086+ samples: std::mem::take(interleaved),
1087+ };
1088+ *timeline += (chunk.samples.len() / channels) as u64;
1089+ tx.send(chunk).is_ok()
1090+}
1091+
1092+/// One segment of a standalone audio file: seek the reader to just before the
1093+/// window, then decode forward until the window is filled.
1094+///
1095+/// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the
1096+/// target is thrown away by [`emit`], which is what gives a codec with decoder
1097+/// state — mp3's bit reservoir above all — something to warm up on, exactly as
1098+/// the AAC path's two-packet pre-roll does. A reader that cannot seek at all
1099+/// simply decodes from wherever it is; the window rules still hold, it is only
1100+/// slower. `false` means the consumer went away.
1101+fn run_sym(
1102+ track: &mut SymTrack,
1103+ seg: &Segment,
1104+ channels: usize,
1105+ timeline: &mut u64,
1106+ tx: &SyncSender<AudioChunk>,
1107+) -> bool {
1108+ let mut decoder = match track.decoder() {
1109+ Ok(decoder) => decoder,
1110+ Err(e) => {
1111+ eprintln!("audio decoder init failed: {e}");
1112+ return true;
1113+ }
1114+ };
1115+ let rate = f64::from(track.sample_rate.max(1));
1116+ let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate;
1117+ if let Some(time) = Time::try_from_secs_f64(from) {
1118+ let to = SeekTo::Time {
1119+ time,
1120+ track_id: Some(track.track_id),
1121+ };
1122+ // A failed seek is not fatal: it leaves the reader where it was, and
1123+ // the window rules below still only emit what the segment asked for.
1124+ if let Err(e) = track.reader.seek(SeekMode::Accurate, to) {
1125+ eprintln!("audio seek to {from:.3}s failed: {e}");
1126+ }
1127+ }
1128+ let mut interleaved = Vec::new();
1129+ loop {
1130+ let packet = match track.reader.next_packet() {
1131+ Ok(Some(packet)) => packet,
1132+ Ok(None) => return true, // end of the file, and of the segment
1133+ Err(e) => {
1134+ eprintln!("audio demux error: {e}");
1135+ return true;
783 }1136 }
784- let chunk = AudioChunk {1137+ };
785- start_sample: timeline,1138+ if packet.track_id != track.track_id {
786- samples: std::mem::take(&mut interleaved),1139+ continue; // another track of the same container
787- };1140+ }
788- timeline += (chunk.samples.len() / channels) as u64;1141+ let pos = track.samples_at(packet.pts);
789- if w.tx.send(chunk).is_err() {1142+ if pos >= seg.media_end {
790- return; // consumer went away1143+ return true; // segment done, on to the next one
1144+ }
1145+ let buf = match decoder.decode(&packet) {
1146+ Ok(buf) => buf,
1147+ Err(e) => {
1148+ eprintln!("audio decode error at sample {pos}: {e}");
1149+ return true;
791 }1150 }
1151+ };
1152+ buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
1153+ let next = pos + (interleaved.len() / channels) as u64;
1154+ if !emit(&mut interleaved, channels, seg, pos, next, timeline, tx) {
1155+ return false;
792 }1156 }
793 }1157 }
794 }1158 }
crates/engine/src/lib.rsmodified+45 -0
@@ -23,7 +23,52 @@ pub use mux::{AudioParams, Mp4Muxer, VideoParams};
23 pub use playback::PlaybackSession;23 pub use playback::PlaybackSession;
24 pub use project::{Clip, Project};24 pub use project::{Clip, Project};
25 25
26+/// Whether a path names a standalone audio file -- a source with no picture,
27+/// which belongs on the audio lane and nowhere else. Extension only, lowercased:
28+/// the decoder is what really decides, but a front-end has to know which lane a
29+/// dropped file may land on *before* anything is opened, and so does
30+/// [`PlaybackSession::import`](playback::PlaybackSession::import).
31+///
32+/// Exactly the containers the engine's audio path reads (`audio::AudioSession`):
33+/// no opus, ac3 or dts, for which no pure-Rust decoder exists -- those are
34+/// refused by the same door that refuses a `.txt`, which is the honest answer.
35+pub fn is_audio(path: &std::path::Path) -> bool {
36+ path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
37+ matches!(
38+ e.to_ascii_lowercase().as_str(),
39+ "mp3" | "wav" | "flac" | "ogg" | "oga" | "m4a" | "aac"
40+ )
41+ })
42+}
43+
26 /// Boxed error; the engine has few failure modes and every one of them is fatal44 /// Boxed error; the engine has few failure modes and every one of them is fatal
27 /// to the session, so a message is all a caller can act on.45 /// to the session, so a message is all a caller can act on.
28 pub type Error = Box<dyn std::error::Error + Send + Sync>;46 pub type Error = Box<dyn std::error::Error + Send + Sync>;
29 pub type Result<T> = std::result::Result<T, Error>;47 pub type Result<T> = std::result::Result<T, Error>;
48+
49+#[cfg(test)]
50+mod tests {
51+ use std::path::Path;
52+
53+ #[test]
54+ fn is_audio_admits_the_containers_the_decoder_reads() {
55+ for name in [
56+ "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac",
57+ ] {
58+ assert!(super::is_audio(Path::new(name)), "{name}");
59+ }
60+ // Video, projects, the formats with no pure-Rust decoder, and a file
61+ // with no extension at all: all of them go elsewhere.
62+ for name in [
63+ "clip.mp4",
64+ "take.MP4",
65+ "cut.edith",
66+ "x.opus",
67+ "y.ac3",
68+ "notes",
69+ "mp3",
70+ ] {
71+ assert!(!super::is_audio(Path::new(name)), "{name}");
72+ }
73+ }
74+}
crates/engine/src/playback.rsmodified+125 -13
@@ -120,6 +120,17 @@ impl PlaybackSession {
120 /// a file we cannot hear is still a file we can watch.120 /// a file we cannot hear is still a file we can watch.
121 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {121 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
122 let path = path.as_ref().to_path_buf();122 let path = path.as_ref().to_path_buf();
123+ // A timeline is scaffolded from source 0's picture -- its size, its
124+ // frame rate, its clock. A song has none of that, so it joins a
125+ // timeline (`import`) rather than starting one, and saying so beats
126+ // failing in the demuxer's words.
127+ if crate::is_audio(&path) {
128+ return Err(format!(
129+ "{} has no picture: open a video first, then import it onto the audio lane",
130+ path.display()
131+ )
132+ .into());
133+ }
123 // `open_worker` rather than `open` purely for the worker handle: the134 // `open_worker` rather than `open` purely for the worker handle: the
124 // field has to exist from the start for the first seek to use it.135 // field has to exist from the start for the first seek to use it.
125 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;136 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
@@ -181,12 +192,34 @@ impl PlaybackSession {
181 192
182 let mut counts = vec![meta.frame_count];193 let mut counts = vec![meta.frame_count];
183 for source in &doc.sources[1..] {194 for source in &doc.sources[1..] {
195+ // A source with no picture is checked on what it does have, and
196+ // its length is its playing time -- the same two answers `import`
197+ // gave it when it first joined the timeline.
198+ if crate::is_audio(source) {
199+ audio_matches(AudioSession::probe(source)?, &first_audio)
200+ .map_err(|e| format!("source {}: {e}", source.display()))?;
201+ counts.push(audio_frames(source, meta.frame_rate)?);
202+ continue;
203+ }
184 let (other, _) =204 let (other, _) =
185 Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?;205 Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?;
186 matches_timeline(source, &other, &meta, &first_audio)206 matches_timeline(source, &other, &meta, &first_audio)
187 .map_err(|e| format!("source {}: {e}", source.display()))?;207 .map_err(|e| format!("source {}: {e}", source.display()))?;
188 counts.push(other.frame_count);208 counts.push(other.frame_count);
189 }209 }
210+ // The video lane can only play files that have pictures. Hand-written
211+ // (or hand-edited) project files are the one door this can come in
212+ // through, so it is refused by name here rather than becoming a clip
213+ // that decodes to nothing.
214+ for clip in &doc.video {
215+ if crate::is_audio(&doc.sources[clip.source]) {
216+ return Err(format!(
217+ "{} has no picture: it can only play on the audio lane",
218+ doc.sources[clip.source].display()
219+ )
220+ .into());
221+ }
222+ }
190 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {223 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {
191 if clip.out_frame > counts[clip.source] {224 if clip.out_frame > counts[clip.source] {
192 return Err(format!(225 return Err(format!(
@@ -440,6 +473,16 @@ impl PlaybackSession {
440 self.edit(|p| p.paste(at, clip))473 self.edit(|p| p.paste(at, clip))
441 }474 }
442 475
476+ /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
477+ /// on and rippling nothing -- the one-lane insert a source with no picture
478+ /// makes, and the only way an audio-only file reaches the timeline. The
479+ /// placement belongs to no group (see [`Project::place`]). One undo step,
480+ /// and it reseeks like every other edit.
481+ pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
482+ let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
483+ self.edit(|p| p.place(lane, at, clip))
484+ }
485+
443 /// Removes the video clip at `idx` and everything under it, closing the gap486 /// Removes the video clip at `idx` and everything under it, closing the gap
444 /// on every lane. Unlike a split this *does* move every following frame, so487 /// on every lane. Unlike a split this *does* move every following frame, so
445 /// the session reseeks to wherever the playhead now points.488 /// the session reseeks to wherever the playhead now points.
@@ -463,6 +506,9 @@ impl PlaybackSession {
463 /// the property that disagrees, for a caller to show. Nothing is changed by506 /// the property that disagrees, for a caller to show. Nothing is changed by
464 /// a refusal.507 /// a refusal.
465 pub fn import(&mut self, path: &Path) -> crate::Result<()> {508 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
509+ if crate::is_audio(path) {
510+ return self.import_audio(path);
511+ }
466 let (meta, _) = Demuxer::open(path)?;512 let (meta, _) = Demuxer::open(path)?;
467 let first = AudioSession::probe(&self.project.sources()[0])?;513 let first = AudioSession::probe(&self.project.sources()[0])?;
468 matches_timeline(path, &meta, &self.meta, &first)?;514 matches_timeline(path, &meta, &self.meta, &first)?;
@@ -481,6 +527,43 @@ impl PlaybackSession {
481 Ok(())527 Ok(())
482 }528 }
483 529
530+ /// Appends a standalone audio file to the end of the timeline, on the
531+ /// **audio lane alone**: a song has no picture, so there is nothing to put
532+ /// on the video lane and the timeline shows black under it. Its length is
533+ /// its playing time rounded up to whole frames, which is the only frame
534+ /// count such a source has.
535+ ///
536+ /// Refused in the same words as any other import when its rate or layout
537+ /// disagrees with the timeline's -- one output device, one set of
538+ /// parameters -- and refused outright on a silent timeline, which has no
539+ /// device open at all. Nothing is changed by a refusal.
540+ fn import_audio(&mut self, path: &Path) -> crate::Result<()> {
541+ let first = AudioSession::probe(&self.project.sources()[0])?;
542+ audio_matches(AudioSession::probe(path)?, &first)?;
543+ let frames = audio_frames(path, self.meta.frame_rate)?;
544+
545+ let old_end = self.timeline_duration();
546+ let source = self.project.import(path);
547+ let at = self.project.timeline_frames();
548+ self.project.place(
549+ Lane::Audio,
550+ at,
551+ Clip {
552+ start: at,
553+ in_frame: 0,
554+ out_frame: frames,
555+ source,
556+ link: None,
557+ },
558+ );
559+ // Same reason as a video import: the running audio worker's segment
560+ // list stops at the old end, so without a reseek the appended clip
561+ // would play silent.
562+ let at = if self.eos { old_end } else { self.now() };
563+ self.seek(at);
564+ Ok(())
565+ }
566+
484 /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`567 /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`
485 /// clamps to the new duration and keeps playing playing, so a delete that568 /// clamps to the new duration and keeps playing playing, so a delete that
486 /// shortens the timeline past the playhead lands on the last frame.569 /// shortens the timeline past the playhead lands on the last frame.
@@ -731,21 +814,50 @@ fn matches_timeline(
731 )814 )
732 .into());815 .into());
733 }816 }
734- // Whole-probe equality: rate, layout and the esds fields, which the audio817+ audio_matches(AudioSession::probe(path)?, first)
735- // worker holds every source to anyway. Both silent is a match.818+}
736- let probe = AudioSession::probe(path)?;819+
737- if probe != *first {820+/// Whether a candidate's audio may join a timeline whose first source probes as
738- return Err(match (probe, first) {821+/// `first`: same rate, same layout, or both silent. One output device and one
739- (None, _) => "the file is silent, the timeline has audio".to_string(),822+/// exported track is all there is, and no resampler.
740- (_, None) => "the file has audio, the timeline is silent".to_string(),823+///
741- (Some(a), Some(b)) => format!(824+/// The format itself is deliberately *not* part of this: an mp3 that agrees on
742- "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",825+/// rate and layout plays alongside a timeline of mp4s perfectly well. What it
743- a.params.sample_rate, a.channels, b.params.sample_rate, b.channels826+/// cannot do is be copied into an export, which is a refusal of its own, at
744- ),827+/// export time (`AudioSession::copy_multi_segments`).
745- }828+fn audio_matches(
829+ probe: Option<crate::AudioProbe>,
830+ first: &Option<crate::AudioProbe>,
831+) -> crate::Result<()> {
832+ if probe == *first {
833+ return Ok(());
834+ }
835+ Err(match (probe, first) {
836+ (None, _) => "the file is silent, the timeline has audio".to_string(),
837+ (_, None) => "the file has audio, the timeline is silent".to_string(),
838+ (Some(a), Some(b)) => format!(
839+ "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
840+ a.sample_rate, a.channels, b.sample_rate, b.channels
841+ ),
842+ }
843+ .into())
844+}
845+
846+/// How many timeline frames a standalone audio file occupies: its playing time
847+/// rounded *up*, so the last partial frame is still covered rather than cut off,
848+/// and never zero (a clip is never empty).
849+fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
850+ let secs = AudioSession::duration_secs(path)?
851+ .ok_or_else(|| format!("{} has no audio track", path.display()))?;
852+ let frames = (secs * fps).ceil();
853+ if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
854+ return Err(format!(
855+ "{} is {secs} s long, which is not a timeline",
856+ path.display()
857+ )
746 .into());858 .into());
747 }859 }
748- Ok(())860+ Ok((frames as u32).max(1))
749 }861 }
750 862
751 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a863 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a
crates/engine/tests/audio_files.rsadded+247 -0
@@ -0,0 +1,247 @@
1+//! Standalone audio files as sources: every container we claim to read decodes
2+//! to the same tone, a song joins a timeline of video on the audio lane, and
3+//! the three things it cannot do -- start a timeline, play on the video lane,
4+//! be copied into an mp4 -- are refusals that say so.
5+//!
6+//! ```text
7+//! cargo test -p engine --release --test audio_files
8+//! ```
9+
10+use std::path::{Path, PathBuf};
11+
12+use engine::project::Lane;
13+use engine::{AudioSession, Clip, PlaybackSession};
14+
15+/// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz
16+/// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone
17+/// `test_av.mp4` carries, so a song and a video clip share one timeline.
18+const CONTAINERS: [&str; 6] = [
19+ "test_tone.mp3",
20+ "test_tone.wav",
21+ "test_tone.flac",
22+ "test_tone.ogg",
23+ "test_tone.m4a",
24+ "test_tone.aac",
25+];
26+
27+fn asset(name: &str) -> PathBuf {
28+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
29+ .join("../../assets")
30+ .join(name)
31+}
32+
33+/// The message of a call that had to be refused. Not `expect_err`: that wants
34+/// `Debug` on the success side, and neither a session nor a packet has it.
35+fn refusal<T>(result: engine::Result<T>) -> String {
36+ match result {
37+ Ok(_) => panic!("expected a refusal"),
38+ Err(e) => e.to_string(),
39+ }
40+}
41+
42+fn open(path: impl AsRef<Path>) -> PlaybackSession {
43+ let session = PlaybackSession::open(path).expect("open");
44+ session.set_gain(0.0);
45+ session
46+}
47+
48+/// Every frame the file decodes to, interleaved, plus the meta it declares.
49+fn decode(path: &Path) -> (u32, u16, Vec<f32>) {
50+ let (meta, rx) = AudioSession::open(path)
51+ .expect("open")
52+ .expect("the fixture has audio");
53+ let mut samples = Vec::new();
54+ for chunk in rx {
55+ samples.extend(chunk.samples);
56+ }
57+ (meta.sample_rate, meta.channels, samples)
58+}
59+
60+#[test]
61+fn every_container_decodes_the_same_three_second_tone() {
62+ for name in CONTAINERS {
63+ let (rate, channels, samples) = decode(&asset(name));
64+ assert_eq!((rate, channels), (44100, 2), "{name}");
65+ let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
66+ // Lossy formats pad: a codec frame is 1152 (mp3) or 1024 (aac) samples,
67+ // so a tenth of a second is generous and still catches a decoder that
68+ // stops early or doubles the stream.
69+ assert!(
70+ (secs - 3.0).abs() < 0.1,
71+ "{name}: {secs:.3} s of audio, want 3.0"
72+ );
73+ // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): full scale at t=0.25
74+ // of every second, silence at t=0.75. Sample it there rather than
75+ // trusting a length -- a channel-swapped or mis-scaled decode still has
76+ // the right number of samples.
77+ for second in 0..3 {
78+ let at = |t: f64| {
79+ let frame = ((f64::from(second) + t) * f64::from(rate)) as usize;
80+ let block = &samples[frame * usize::from(channels)..][..usize::from(channels) * 64];
81+ block.iter().fold(0.0f32, |peak, s| peak.max(s.abs()))
82+ };
83+ // Depth as a ratio, not an absolute: the fixture's sines sit around
84+ // an eighth of full scale and that is the encoder's business
85+ // (ledger:873), while a dip 20x below the peak is the pulse.
86+ let (loud, quiet) = (at(0.25), at(0.75));
87+ assert!(loud > 0.05, "{name} second {second}: peak only {loud}");
88+ assert!(
89+ quiet < 0.05 * loud,
90+ "{name} second {second}: dip {quiet} against peak {loud}"
91+ );
92+ }
93+ }
94+}
95+
96+/// The length a placement is built from, which is the only frame count a file
97+/// with no picture has.
98+#[test]
99+fn duration_comes_from_the_header_or_the_decode() {
100+ for name in CONTAINERS {
101+ let secs = AudioSession::duration_secs(asset(name))
102+ .expect("probe")
103+ .expect("the fixture has audio");
104+ assert!(
105+ (secs - 3.0).abs() < 0.1,
106+ "{name}: duration reads {secs:.3} s"
107+ );
108+ }
109+ assert_eq!(
110+ AudioSession::duration_secs(asset("test_baseline.mp4")).expect("probe"),
111+ None,
112+ "a silent video has no audio duration"
113+ );
114+}
115+
116+#[test]
117+fn a_song_joins_a_video_timeline_on_the_audio_lane() {
118+ let mut session = open(asset("test_av.mp4"));
119+ let before = session.timeline_duration();
120+ session
121+ .import(&asset("test_tone.mp3"))
122+ .expect("import the song");
123+
124+ // 3 s at 30 fps, appended: the audio lane runs 90 frames past the video.
125+ assert!(
126+ (session.timeline_duration() - (before + 3.0)).abs() < 0.05,
127+ "{} s of timeline, want {}",
128+ session.timeline_duration(),
129+ before + 3.0
130+ );
131+ assert_eq!(session.sources().len(), 2);
132+ // The video lane never hears about it: one clip, the one the file opened
133+ // with. The audio lane has two.
134+ assert_eq!(session.lane_clips(Lane::Video).len(), 1, "video lane");
135+ assert_eq!(session.lane_clips(Lane::Audio).len(), 2, "audio lane");
136+ let song = session.lane_clips(Lane::Audio)[1];
137+ assert_eq!((song.source, song.in_frame, song.len()), (1, 0, 90));
138+
139+ // And it plays: the segment list past the join names the song, so the
140+ // worker opens it rather than running silent.
141+ session.seek(before + 1.0);
142+ assert!(session.lane_spans_by_source(Lane::Audio).len() >= 2);
143+}
144+
145+#[test]
146+fn a_rate_the_device_cannot_mix_is_refused_at_the_door() {
147+ let mut session = open(asset("test_av.mp4"));
148+ assert_eq!(
149+ refusal(session.import(&asset("test_tone_48k.wav"))),
150+ "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"
151+ );
152+ // Refused means unchanged: no source, no clip, no length.
153+ assert_eq!(session.sources().len(), 1);
154+ assert_eq!(session.lane_clips(Lane::Audio).len(), 1);
155+}
156+
157+#[test]
158+fn a_song_cannot_be_a_timeline_of_its_own() {
159+ let e = refusal(PlaybackSession::open(asset("test_tone.mp3")));
160+ assert!(
161+ e.ends_with("has no picture: open a video first, then import it onto the audio lane"),
162+ "{e}"
163+ );
164+}
165+
166+/// The export copies AAC packets and has no encoder, so a timeline carrying an
167+/// mp3 cannot become an mp4 -- named, with its format, rather than exported
168+/// silent or exported wrong.
169+#[test]
170+fn an_export_refuses_audio_it_cannot_copy() {
171+ let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];
172+ let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
173+ assert_eq!(
174+ refusal(AudioSession::copy_multi_segments(&sources, &segs)),
175+ "export needs AAC audio today; test_tone.mp3 is mp3"
176+ );
177+ // A timeline of nothing but mp4 still exports, which is the invariant this
178+ // refusal must not have cost.
179+ assert!(
180+ AudioSession::copy_multi_segments(&sources[..1], &segs[..1])
181+ .expect("mp4 audio still copies")
182+ .is_some()
183+ );
184+}
185+
186+#[test]
187+fn a_song_survives_a_save_and_a_reload() {
188+ let dir = std::env::temp_dir().join(format!("ve_audio_files_{}", std::process::id()));
189+ let _ = std::fs::remove_dir_all(&dir);
190+ std::fs::create_dir_all(&dir).expect("scratch dir");
191+ let copy = |name: &str| {
192+ let to = dir.join(name);
193+ std::fs::copy(asset(name), &to).expect("copy the fixture");
194+ to
195+ };
196+
197+ let mut session = open(copy("test_av.mp4"));
198+ session.import(&copy("test_tone.flac")).expect("import");
199+ // And one placed at the playhead, the way a library row dropped on the
200+ // audio lane arrives -- so the reload has both doors to restore.
201+ let song = session.lane_clips(Lane::Audio)[1];
202+ assert!(session.place_at(
203+ Lane::Audio,
204+ 1.0,
205+ Clip {
206+ in_frame: 0,
207+ out_frame: 30,
208+ ..song
209+ }
210+ ));
211+ let before = (
212+ session.lane_spans_by_source(Lane::Audio),
213+ session.sources().to_vec(),
214+ session.timeline_duration(),
215+ );
216+
217+ let project = dir.join("song.edith");
218+ session.save_project(&project).expect("save");
219+ drop(session);
220+ let reloaded = PlaybackSession::open_project(&project).expect("reload");
221+ reloaded.set_gain(0.0);
222+ assert_eq!(
223+ (
224+ reloaded.lane_spans_by_source(Lane::Audio),
225+ reloaded.sources().to_vec(),
226+ reloaded.timeline_duration()
227+ ),
228+ before
229+ );
230+
231+ // The one thing only a hand-edited project can ask for: a file with no
232+ // picture on the video lane. Written by hand, because no door in the engine
233+ // will produce it.
234+ let broken = dir.join("broken.edith");
235+ std::fs::write(
236+ &broken,
237+ "edith 2\nplayhead 0\nsource test_av.mp4\nsource test_tone.flac\n\
238+ video 0 0 90 1 -\naudio 0 0 90 1 -\n",
239+ )
240+ .expect("write");
241+ let e = refusal(PlaybackSession::open_project(&broken));
242+ assert!(
243+ e.ends_with("has no picture: it can only play on the audio lane"),
244+ "{e}"
245+ );
246+ let _ = std::fs::remove_dir_all(&dir);
247+}
crates/engine/tests/audio_multi.rsmodified+1 -1
@@ -193,7 +193,7 @@ fn probe_reads_the_import_policy_fields() {
193 .expect("probe")193 .expect("probe")
194 .expect("test_av.mp4 has audio");194 .expect("test_av.mp4 has audio");
195 assert_eq!(av.channels, 2);195 assert_eq!(av.channels, 2);
196- assert_eq!(av.params.sample_rate, RATE as u32);196+ assert_eq!(av.sample_rate, RATE as u32);
197 assert_eq!(197 assert_eq!(
198 AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(),198 AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(),
199 av,199 av,
scripts/gen_fixtures.shmodified+27 -0
@@ -29,4 +29,31 @@ ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30:duration=4 \
29 # has something concrete to refuse.29 # has something concrete to refuse.
30 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \30 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \
31 -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp431 -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4
32+# Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the
33+# A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song
34+# can share a timeline with the video clips and the peaks tests can reuse the
35+# dip pattern. One per container we claim to read.
36+tone="[0:a][1:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]"
37+for fmt in mp3 wav flac ogg m4a aac; do
38+ case $fmt in
39+ mp3) codec=(-c:a libmp3lame -b:a 128k) ;;
40+ wav) codec=(-c:a pcm_s16le) ;;
41+ flac) codec=(-c:a flac) ;;
42+ ogg) codec=(-c:a libvorbis) ;;
43+ # ALAC in mp4, and raw AAC in ADTS -- the two the mp4/AAC packet-copy
44+ # path cannot claim: one is not AAC, the other is not in an mp4.
45+ m4a) codec=(-c:a alac) ;;
46+ aac) codec=(-c:a aac -b:a 128k -f adts) ;;
47+ esac
48+ ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \
49+ -f lavfi -i "sine=frequency=880:duration=3" \
50+ -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \
51+ "assets/test_tone.$fmt"
52+done
53+# The refusal fixture: same tone at 48k, which one output device cannot mix
54+# with a 44.1k timeline.
55+ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \
56+ -f lavfi -i "sine=frequency=880:duration=3" \
57+ -filter_complex "$tone" -map "[a]" -ar 48000 -c:a pcm_s16le \
58+ assets/test_tone_48k.wav
32 echo "fixtures written to assets/"59 echo "fixtures written to assets/"