Merge branch 'worktree-agent-a0ff500121178a837'
Browse files at this commit13 changed files +1162 -81
- Cargo.lock +118 -0
- crates/app/src/main.rs +31 -4
- crates/engine/Cargo.toml +19 -0
- crates/engine/src/audio.rs +456 -52
- crates/engine/src/lib.rs +45 -0
- crates/engine/src/playback.rs +145 -22
- crates/engine/src/waveform.rs +25 -0
- crates/engine/tests/audio_files.rs +247 -0
- crates/engine/tests/audio_multi.rs +1 -1
- crates/engine/tests/audio_streams.rs +46 -0
- crates/engine/tests/hevc.rs +1 -1
- crates/engine/tests/vp9.rs +1 -1
- scripts/gen_fixtures.sh +27 -0
Cargo.lockmodified+118 -0
| @@ -1612,6 +1612,7 @@ dependencies = [ | ||
| 1612 | 1612 | "libloading", |
| 1613 | 1613 | "mp4", |
| 1614 | 1614 | "rusty_h264", |
| 1615 | + "symphonia", | |
| 1615 | 1616 | "symphonia-codec-aac", |
| 1616 | 1617 | "symphonia-core", |
| 1617 | 1618 | ] |
| @@ -1764,6 +1765,12 @@ dependencies = [ | ||
| 1764 | 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 | 1774 | [[package]] |
| 1768 | 1775 | name = "fastrand" |
| 1769 | 1776 | version = "1.9.0" |
| @@ -5485,6 +5492,49 @@ dependencies = [ | ||
| 5485 | 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 | 5538 | [[package]] |
| 5489 | 5539 | name = "symphonia-codec-aac" |
| 5490 | 5540 | version = "0.6.0" |
| @@ -5497,6 +5547,38 @@ dependencies = [ | ||
| 5497 | 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 | 5582 | [[package]] |
| 5501 | 5583 | name = "symphonia-common" |
| 5502 | 5584 | version = "0.6.0" |
| @@ -5522,6 +5604,42 @@ dependencies = [ | ||
| 5522 | 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 | 5643 | [[package]] |
| 5526 | 5644 | name = "symphonia-metadata" |
| 5527 | 5645 | version = "0.6.0" |
crates/app/src/main.rsmodified+31 -4
| @@ -640,10 +640,28 @@ impl Player { | ||
| 640 | 640 | /// moves along rather than being painted over. Reseeks like every other |
| 641 | 641 | /// edit, and drops the timeline's selection with it: the insert has just |
| 642 | 642 | /// moved the indices it pointed at. |
| 643 | - fn insert_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) { | |
| 643 | + fn insert_source( | |
| 644 | + &mut self, | |
| 645 | + path: &Path, | |
| 646 | + stream: usize, | |
| 647 | + onto: Option<Lane>, | |
| 648 | + cx: &mut Context<Self>, | |
| 649 | + ) { | |
| 644 | 650 | if self.exporting().is_some() { |
| 645 | 651 | return; |
| 646 | 652 | } |
| 653 | + // A file with no picture belongs on the audio lane and nowhere else: | |
| 654 | + // dropped on the video lane it is refused by name, and asked for by the | |
| 655 | + // Add button (which names no lane) it goes to the audio one -- which is | |
| 656 | + // the engine's choice, in `place_stream_at`, not one made twice here. | |
| 657 | + if engine::is_audio(path) && onto == Some(Lane::Video) { | |
| 658 | + let name = file_name(path); | |
| 659 | + self.notice = Some( | |
| 660 | + format!("NOT ON THE VIDEO LANE — {name} has no picture; drop it on A1").into(), | |
| 661 | + ); | |
| 662 | + cx.notify(); | |
| 663 | + return; | |
| 664 | + } | |
| 647 | 665 | let frames = self.session.as_ref().map_or(0, |session| { |
| 648 | 666 | source_frames(lane_clips(session), session.sources(), path) |
| 649 | 667 | }); |
| @@ -1334,6 +1352,13 @@ impl Player { | ||
| 1334 | 1352 | // A greyed row says why in full, where its length would be: |
| 1335 | 1353 | // the list is the one place the file's own tracks are named. |
| 1336 | 1354 | (Some(why), _) => format!("{} — {why}", row.path.display()), |
| 1355 | + // A file with no picture has no size and no frame rate to | |
| 1356 | + // report, and only one lane it can go on: saying so is the | |
| 1357 | + // difference between a hint and a lie. | |
| 1358 | + (None, _) if engine::is_audio(&row.path) => format!( | |
| 1359 | + "{} — audio only · drag onto the audio lane, or Add at playhead", | |
| 1360 | + row.path.display() | |
| 1361 | + ), | |
| 1337 | 1362 | (None, Some(meta)) => format!( |
| 1338 | 1363 | "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", |
| 1339 | 1364 | row.path.display(), |
| @@ -1486,7 +1511,9 @@ impl Player { | ||
| 1486 | 1511 | ), |
| 1487 | 1512 | cx.listener(|this, _: &ClickEvent, _, cx| { |
| 1488 | 1513 | if let Some((path, stream)) = this.selected_asset.clone() { |
| 1489 | - this.insert_source(&path, stream, cx); | |
| 1514 | + // No lane: the button means "wherever this belongs", | |
| 1515 | + // which for a file with no picture is the audio lane. | |
| 1516 | + this.insert_source(&path, stream, None, cx); | |
| 1490 | 1517 | } |
| 1491 | 1518 | }), |
| 1492 | 1519 | )) |
| @@ -2311,8 +2338,8 @@ impl Player { | ||
| 2311 | 2338 | // Add button makes, through the same call -- at the |
| 2312 | 2339 | // playhead, not at the pointer: clips here are placed end |
| 2313 | 2340 | // to end, so where along the bed it landed says nothing. |
| 2314 | - .on_drop(cx.listener(|this, drag: &AssetDrag, _, cx| { | |
| 2315 | - this.insert_source(&drag.0.clone(), drag.1, cx) | |
| 2341 | + .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| { | |
| 2342 | + this.insert_source(&drag.0.clone(), drag.1, Some(lane), cx) | |
| 2316 | 2343 | })) |
| 2317 | 2344 | .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM))) |
| 2318 | 2345 | .children(clips.iter().enumerate().map(|(i, clip)| { |
crates/engine/Cargo.tomlmodified+19 -0
| @@ -10,3 +10,22 @@ mp4 = "0.14" | ||
| 10 | 10 | rusty_h264 = { version = "0.8", default-features = false } |
| 11 | 11 | symphonia-core = "0.6" |
| 12 | 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+456 -52
| @@ -1,6 +1,19 @@ | ||
| 1 | -//! Background audio decode worker: pulls the AAC track out of an MP4 and hands | |
| 1 | +//! Background audio decode worker: pulls a source's audio track and hands | |
| 2 | 2 | //! 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. | |
| 12 | +//! | |
| 13 | +//! Both readers are addressed as `(path, stream)`. An mp4 may carry several | |
| 14 | +//! audio tracks and the caller picks one; a standalone audio file carries | |
| 15 | +//! exactly one, so any stream above 0 there is an `Err` rather than a silent | |
| 16 | +//! fallback to the only track it has. | |
| 4 | 17 | |
| 5 | 18 | use std::fs::File; |
| 6 | 19 | use std::io::BufReader; |
| @@ -13,8 +26,17 @@ use symphonia_codec_aac::AacDecoder; | ||
| 13 | 26 | use symphonia_core::codecs::audio::{ |
| 14 | 27 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, |
| 15 | 28 | }; |
| 29 | +use symphonia_core::formats::probe::Hint; | |
| 30 | +// `TrackType` is the name both readers give their track kinds; the mp4 one is | |
| 31 | +// imported above and used far more often here, so symphonia's is the one aliased. | |
| 32 | +use symphonia_core::formats::{ | |
| 33 | + FormatOptions, FormatReader, SeekMode, SeekTo, TrackType as SymKind, | |
| 34 | +}; | |
| 35 | +use symphonia_core::io::MediaSourceStream; | |
| 36 | +use symphonia_core::meta::MetadataOptions; | |
| 16 | 37 | use symphonia_core::packet::Packet; |
| 17 | 38 | use symphonia_core::units; |
| 39 | +use symphonia_core::units::{Time, TimeBase}; | |
| 18 | 40 | |
| 19 | 41 | /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. |
| 20 | 42 | /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) |
| @@ -30,6 +52,12 @@ const PRE_ROLL: u32 = 2; | ||
| 30 | 52 | /// Frames per channel one AAC-LC packet carries. Fixed by the codec. |
| 31 | 53 | const SAMPLES_PER_PACKET: u32 = 1024; |
| 32 | 54 | |
| 55 | +/// Frames per channel a seek into a standalone audio file lands ahead of the | |
| 56 | +/// window, decoded and thrown away: enough to refill an mp3's bit reservoir | |
| 57 | +/// (a frame is 1152 samples and the reservoir reaches back two of them) at any | |
| 58 | +/// rate we accept. | |
| 59 | +const SYM_PRE_ROLL: u64 = 8192; | |
| 60 | + | |
| 33 | 61 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 34 | 62 | pub struct AudioMeta { |
| 35 | 63 | pub sample_rate: u32, |
| @@ -67,9 +95,14 @@ pub struct AacPacket { | ||
| 67 | 95 | |
| 68 | 96 | /// Everything an import check needs from a candidate file's audio track. Two |
| 69 | 97 | /// files may share a timeline only when their probes are equal (or both `None`). |
| 98 | +/// | |
| 99 | +/// Rate and layout only: those are what one output device and one exported track | |
| 100 | +/// can carry, and an mp3 that agrees on both may join a timeline of mp4s even | |
| 101 | +/// though nothing about it can be *copied* into an export -- that is a separate | |
| 102 | +/// refusal, at export time, in [`AudioSession::copy_multi_segments`]. | |
| 70 | 103 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 71 | 104 | pub struct AudioProbe { |
| 72 | - pub params: AacTrackParams, | |
| 105 | + pub sample_rate: u32, | |
| 73 | 106 | pub channels: u16, |
| 74 | 107 | } |
| 75 | 108 | |
| @@ -183,13 +216,13 @@ impl AudioSession { | ||
| 183 | 216 | // The timeline's meta is the first source's: policy makes every other |
| 184 | 217 | // source match it, and the checks below hold them to that. |
| 185 | 218 | let meta = AudioMeta { |
| 186 | - sample_rate: first.sample_rate, | |
| 219 | + sample_rate: first.sample_rate(), | |
| 187 | 220 | channels: first.channels()?, |
| 188 | - total_samples: first.total_samples, | |
| 221 | + total_samples: first.total_samples(), | |
| 189 | 222 | }; |
| 190 | 223 | // Built here only so an undecodable stream is an `Err` from the opener |
| 191 | 224 | // rather than a silently empty channel; the worker makes its own. |
| 192 | - AacDecoder::try_new(&first.params, &AudioDecoderOptions::default())?; | |
| 225 | + first.check_decoder()?; | |
| 193 | 226 | |
| 194 | 227 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); |
| 195 | 228 | tracks[0] = Some(first); |
| @@ -206,17 +239,17 @@ impl AudioSession { | ||
| 206 | 239 | let (path, stream) = &sources[source]; |
| 207 | 240 | let track = Track::open(path, *stream)? |
| 208 | 241 | .ok_or_else(|| format!("source {source} has no audio track"))?; |
| 209 | - if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { | |
| 242 | + if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) { | |
| 210 | 243 | return Err(format!( |
| 211 | 244 | "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", |
| 212 | - track.sample_rate, | |
| 245 | + track.sample_rate(), | |
| 213 | 246 | track.channels()?, |
| 214 | 247 | meta.sample_rate, |
| 215 | 248 | meta.channels |
| 216 | 249 | ) |
| 217 | 250 | .into()); |
| 218 | 251 | } |
| 219 | - AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())?; | |
| 252 | + track.check_decoder()?; | |
| 220 | 253 | *slot = Some(track); |
| 221 | 254 | } |
| 222 | 255 | |
| @@ -237,7 +270,7 @@ impl AudioSession { | ||
| 237 | 270 | let timeline = segments.first().map_or(0, |s| match s.source { |
| 238 | 271 | Some(source) => s |
| 239 | 272 | .media_target |
| 240 | - .saturating_sub(tracks[source].as_ref().expect("opened above").priming), | |
| 273 | + .saturating_sub(tracks[source].as_ref().expect("opened above").priming()), | |
| 241 | 274 | None => 0, |
| 242 | 275 | }); |
| 243 | 276 | |
| @@ -282,15 +315,15 @@ impl AudioSession { | ||
| 282 | 315 | |
| 283 | 316 | /// The audio parameters of `path`'s `stream`, for checking an import |
| 284 | 317 | /// against the timeline's first source: header only, no decoder and no |
| 285 | - /// worker. `Ok(None)` means no AAC track — an audio-less file, which import | |
| 286 | - /// pairs only with other audio-less files. A *named* stream that is not | |
| 287 | - /// there or does not decode is an `Err`, as everywhere else. | |
| 318 | + /// worker. `Ok(None)` means no audio track — a silent file, which import | |
| 319 | + /// pairs only with other silent files. A *named* stream that is not there | |
| 320 | + /// or does not decode is an `Err`, as everywhere else. | |
| 288 | 321 | pub fn probe(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<AudioProbe>> { |
| 289 | 322 | let Some(track) = Track::open(path.as_ref(), stream)? else { |
| 290 | 323 | return Ok(None); |
| 291 | 324 | }; |
| 292 | 325 | Ok(Some(AudioProbe { |
| 293 | - params: track.track_params(), | |
| 326 | + sample_rate: track.sample_rate(), | |
| 294 | 327 | channels: track.channels()?, |
| 295 | 328 | })) |
| 296 | 329 | } |
| @@ -303,8 +336,27 @@ impl AudioSession { | ||
| 303 | 336 | /// |
| 304 | 337 | /// An empty list means the file has no audio at all, which is a valid |
| 305 | 338 | /// silent source. |
| 339 | + /// | |
| 340 | + /// A standalone audio file ([`crate::is_audio`]) has exactly one stream by | |
| 341 | + /// construction — one track, no picture beside it — so it is described from | |
| 342 | + /// symphonia's own header rather than walked as an mp4, which an mp3 is not | |
| 343 | + /// and an ALAC `.m4a` only half is. | |
| 306 | 344 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { |
| 307 | - let file = File::open(path.as_ref())?; | |
| 345 | + let path = path.as_ref(); | |
| 346 | + if crate::is_audio(path) { | |
| 347 | + let track = SymTrack::open(path)?; | |
| 348 | + return Ok(vec![StreamInfo { | |
| 349 | + index: 0, | |
| 350 | + codec: track.codec.into(), | |
| 351 | + channels: track.channels, | |
| 352 | + sample_rate: track.sample_rate, | |
| 353 | + // Neither the mp3 nor the wav headers carry an ISO-639 tag the | |
| 354 | + // way an mdhd does, and a lone track needs no telling apart. | |
| 355 | + lang: None, | |
| 356 | + decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(), | |
| 357 | + }]); | |
| 358 | + } | |
| 359 | + let file = File::open(path)?; | |
| 308 | 360 | let size = file.metadata()?.len(); |
| 309 | 361 | let reader = Mp4Reader::read_header(BufReader::new(file), size)?; |
| 310 | 362 | Ok(audio_track_ids(&reader) |
| @@ -331,6 +383,37 @@ impl AudioSession { | ||
| 331 | 383 | .collect()) |
| 332 | 384 | } |
| 333 | 385 | |
| 386 | + /// How long `path`'s audio plays, in seconds. `Ok(None)` for a silent file. | |
| 387 | + /// | |
| 388 | + /// A standalone audio file is a source with no frame count of its own, so | |
| 389 | + /// this is what its length on the timeline is derived from. Taken from the | |
| 390 | + /// header where there is one; a stream that does not say — a bare mp3 with | |
| 391 | + /// no Xing header is the usual one — is *decoded* to find out, which is | |
| 392 | + /// linear in its length (~0.5 ms per source second) and happens once, at | |
| 393 | + /// import, rather than per repaint. | |
| 394 | + /// | |
| 395 | + /// Stream 0: this answers for a standalone audio file, whose only stream | |
| 396 | + /// that is. A video source's length is its frame count, never this. | |
| 397 | + pub fn duration_secs(path: impl AsRef<Path>) -> crate::Result<Option<f64>> { | |
| 398 | + let path = path.as_ref(); | |
| 399 | + let Some(track) = Track::open(path, 0)? else { | |
| 400 | + return Ok(None); | |
| 401 | + }; | |
| 402 | + let rate = f64::from(track.sample_rate().max(1)); | |
| 403 | + if let Some(total) = track.total_samples() { | |
| 404 | + return Ok(Some(total as f64 / rate)); | |
| 405 | + } | |
| 406 | + drop(track); | |
| 407 | + let Some((meta, rx)) = Self::open(path)? else { | |
| 408 | + return Ok(None); | |
| 409 | + }; | |
| 410 | + let channels = usize::from(meta.channels.max(1)); | |
| 411 | + let last = rx.into_iter().fold(0, |_, chunk| { | |
| 412 | + chunk.start_sample + (chunk.samples.len() / channels) as u64 | |
| 413 | + }); | |
| 414 | + Ok(Some(last as f64 / f64::from(meta.sample_rate.max(1)))) | |
| 415 | + } | |
| 416 | + | |
| 334 | 417 | /// The raw AAC packets covering `segs` — the same half-open source-second |
| 335 | 418 | /// windows [`open_segments`](Self::open_segments) decodes — copied out |
| 336 | 419 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go |
| @@ -399,11 +482,11 @@ impl AudioSession { | ||
| 399 | 482 | let (path, stream) = sources |
| 400 | 483 | .get(first) |
| 401 | 484 | .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; |
| 402 | - let Some(track) = Track::open(path, *stream)? else { | |
| 485 | + let Some(track) = copy_track(path, *stream)? else { | |
| 403 | 486 | return Ok(None); // silent source, silent export |
| 404 | 487 | }; |
| 405 | 488 | let params = track.track_params(); |
| 406 | - let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); | |
| 489 | + let mut tracks: Vec<Option<AacTrack>> = sources.iter().map(|_| None).collect(); | |
| 407 | 490 | tracks[first] = Some(track); |
| 408 | 491 | |
| 409 | 492 | let sample_rate = params.sample_rate; |
| @@ -491,28 +574,248 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> { | ||
| 491 | 574 | /// The source at `index`, on the stream it names, opened on first use. Sources |
| 492 | 575 | /// a segment list never names are never touched: a project's list only grows. |
| 493 | 576 | fn source_at<'a>( |
| 494 | - tracks: &'a mut [Option<Track>], | |
| 577 | + tracks: &'a mut [Option<AacTrack>], | |
| 495 | 578 | sources: &[(PathBuf, usize)], |
| 496 | 579 | index: usize, |
| 497 | -) -> crate::Result<&'a mut Track> { | |
| 580 | +) -> crate::Result<&'a mut AacTrack> { | |
| 498 | 581 | let slot = tracks |
| 499 | 582 | .get_mut(index) |
| 500 | 583 | .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; |
| 501 | 584 | if slot.is_none() { |
| 502 | 585 | let (path, stream) = &sources[index]; |
| 503 | 586 | *slot = Some( |
| 504 | - Track::open(path, *stream)? | |
| 587 | + copy_track(path, *stream)? | |
| 505 | 588 | .ok_or_else(|| format!("source {index} has no audio track"))?, |
| 506 | 589 | ); |
| 507 | 590 | } |
| 508 | 591 | Ok(slot.as_mut().expect("just opened")) |
| 509 | 592 | } |
| 510 | 593 | |
| 594 | +/// A source's track for the *copy* path, which needs raw AAC access units. | |
| 595 | +/// | |
| 596 | +/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by | |
| 597 | +/// name and by format rather than exported silent or, worse, exported as noise: | |
| 598 | +/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]), | |
| 599 | +/// so a timeline carrying one of those simply cannot become an mp4 today. The | |
| 600 | +/// wording is what a front-end shows. | |
| 601 | +/// | |
| 602 | +/// `Ok(None)` for a file with no audio at all, which is a silent export. | |
| 603 | +fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> { | |
| 604 | + match Track::open(path, stream)? { | |
| 605 | + None => Ok(None), | |
| 606 | + Some(Track::Aac(track)) => Ok(Some(track)), | |
| 607 | + Some(Track::Sym(track)) => Err(format!( | |
| 608 | + "export needs AAC audio today; {} is {}", | |
| 609 | + path.file_name() | |
| 610 | + .unwrap_or(path.as_os_str()) | |
| 611 | + .to_string_lossy(), | |
| 612 | + track.codec | |
| 613 | + ) | |
| 614 | + .into()), | |
| 615 | + } | |
| 616 | +} | |
| 617 | + | |
| 618 | +/// One source's audio, however it is stored: the mp4 AAC track the export can | |
| 619 | +/// copy, or a standalone file read through symphonia's probe. The opener and | |
| 620 | +/// the worker speak to this, never to either reader directly. | |
| 621 | +enum Track { | |
| 622 | + Aac(AacTrack), | |
| 623 | + Sym(SymTrack), | |
| 624 | +} | |
| 625 | + | |
| 626 | +impl Track { | |
| 627 | + /// `Ok(None)` for a file with no audio, which is a valid silent source. | |
| 628 | + /// | |
| 629 | + /// The mp4 reader goes first and its verdict is final for anything that is | |
| 630 | + /// not [`crate::is_audio`]: a video file's audio track is exactly what it | |
| 631 | + /// always was, silent mp4s included (an mp4 whose only `soun` track is one | |
| 632 | + /// we cannot decode has always been a silent source, not an error). Only a | |
| 633 | + /// standalone audio file falls through to symphonia — which is also how an | |
| 634 | + /// ALAC `.m4a` is reached, since it parses as an mp4 with no AAC track. | |
| 635 | + /// | |
| 636 | + /// `stream` counts audio tracks in file order, as | |
| 637 | + /// [`AudioSession::probe_streams`] hands them out. A standalone audio file | |
| 638 | + /// has exactly one, so any `stream` above 0 there is a promise the file | |
| 639 | + /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. | |
| 640 | + fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { | |
| 641 | + let audio_file = crate::is_audio(path); | |
| 642 | + match AacTrack::open(path, stream) { | |
| 643 | + Ok(Some(track)) => return Ok(Some(Self::Aac(track))), | |
| 644 | + Ok(None) if !audio_file => return Ok(None), | |
| 645 | + Err(e) if !audio_file => return Err(e), | |
| 646 | + _ => {} | |
| 647 | + } | |
| 648 | + if stream > 0 { | |
| 649 | + return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); | |
| 650 | + } | |
| 651 | + SymTrack::open(path).map(|track| Some(Self::Sym(track))) | |
| 652 | + } | |
| 653 | + | |
| 654 | + fn sample_rate(&self) -> u32 { | |
| 655 | + match self { | |
| 656 | + Self::Aac(t) => t.sample_rate, | |
| 657 | + Self::Sym(t) => t.sample_rate, | |
| 658 | + } | |
| 659 | + } | |
| 660 | + | |
| 661 | + /// Mono or stereo; anything wider is refused here rather than one packet at | |
| 662 | + /// a time, because one output device and one copied track is all there is. | |
| 663 | + fn channels(&self) -> crate::Result<u16> { | |
| 664 | + match self { | |
| 665 | + Self::Aac(t) => t.channels(), | |
| 666 | + Self::Sym(t) => match t.channels { | |
| 667 | + 1 | 2 => Ok(t.channels), | |
| 668 | + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | |
| 669 | + }, | |
| 670 | + } | |
| 671 | + } | |
| 672 | + | |
| 673 | + /// Frames per channel of *audible* audio, priming already subtracted. | |
| 674 | + fn total_samples(&self) -> Option<u64> { | |
| 675 | + match self { | |
| 676 | + Self::Aac(t) => t.total_samples, | |
| 677 | + Self::Sym(t) => t.total_samples, | |
| 678 | + } | |
| 679 | + } | |
| 680 | + | |
| 681 | + /// Encoder delay of this file. Sources are joined, priming is not shared. | |
| 682 | + fn priming(&self) -> u64 { | |
| 683 | + match self { | |
| 684 | + Self::Aac(t) => t.priming, | |
| 685 | + Self::Sym(t) => t.priming, | |
| 686 | + } | |
| 687 | + } | |
| 688 | + | |
| 689 | + /// One `[start, end)` window of this source's seconds, resolved to whatever | |
| 690 | + /// its own reader needs to find it again. | |
| 691 | + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { | |
| 692 | + match self { | |
| 693 | + Self::Aac(t) => t.segment(source, start_secs, end_secs), | |
| 694 | + Self::Sym(t) => { | |
| 695 | + let media_target = t.media(start_secs); | |
| 696 | + Segment { | |
| 697 | + source: Some(source), | |
| 698 | + start_id: 0, | |
| 699 | + start_pos: 0, | |
| 700 | + media_target, | |
| 701 | + media_end: t.media(end_secs).max(media_target), | |
| 702 | + } | |
| 703 | + } | |
| 704 | + } | |
| 705 | + } | |
| 706 | + | |
| 707 | + /// Builds and throws away a decoder, so an undecodable stream is an `Err` | |
| 708 | + /// from the opener rather than a silently empty channel. | |
| 709 | + fn check_decoder(&self) -> crate::Result<()> { | |
| 710 | + match self { | |
| 711 | + Self::Aac(t) => { | |
| 712 | + AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; | |
| 713 | + } | |
| 714 | + Self::Sym(t) => { | |
| 715 | + t.decoder()?; | |
| 716 | + } | |
| 717 | + } | |
| 718 | + Ok(()) | |
| 719 | + } | |
| 720 | +} | |
| 721 | + | |
| 722 | +/// A standalone audio file — mp3, wav, flac, vorbis in ogg, ALAC, ADTS — read | |
| 723 | +/// through symphonia's own probe and codec registry. No packet table and no | |
| 724 | +/// sample ids: the reader is *seeked* per segment and the packets it then hands | |
| 725 | +/// out carry their own timestamps. | |
| 726 | +struct SymTrack { | |
| 727 | + reader: Box<dyn FormatReader>, | |
| 728 | + track_id: u32, | |
| 729 | + sample_rate: u32, | |
| 730 | + channels: u16, | |
| 731 | + /// Frames per channel of audible audio, `None` when the header does not say. | |
| 732 | + total_samples: Option<u64>, | |
| 733 | + /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the | |
| 734 | + /// container where it declares one (mp3's Xing/LAME tag, ALAC's edit list). | |
| 735 | + priming: u64, | |
| 736 | + time_base: TimeBase, | |
| 737 | + params: AudioCodecParameters, | |
| 738 | + /// The format's short name, for the export refusal. `&'static` because it | |
| 739 | + /// comes out of the codec registry, which outlives everything here. | |
| 740 | + codec: &'static str, | |
| 741 | +} | |
| 742 | + | |
| 743 | +impl SymTrack { | |
| 744 | + fn open(path: &Path) -> crate::Result<Self> { | |
| 745 | + let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); | |
| 746 | + // The extension is a hint, not a decision: the probe reads the magic and | |
| 747 | + // is free to disagree, which is what makes a mislabelled file work. | |
| 748 | + let mut hint = Hint::new(); | |
| 749 | + if let Some(ext) = path.extension().and_then(|e| e.to_str()) { | |
| 750 | + hint.with_extension(ext); | |
| 751 | + } | |
| 752 | + let reader = symphonia::default::get_probe().probe( | |
| 753 | + &hint, | |
| 754 | + mss, | |
| 755 | + FormatOptions::default(), | |
| 756 | + MetadataOptions::default(), | |
| 757 | + )?; | |
| 758 | + let track = reader | |
| 759 | + .default_track(SymKind::Audio) | |
| 760 | + .ok_or_else(|| format!("{} has no audio track", path.display()))?; | |
| 761 | + let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay); | |
| 762 | + let time_base = track | |
| 763 | + .time_base | |
| 764 | + .ok_or_else(|| format!("{} declares no time base", path.display()))?; | |
| 765 | + let Some(symphonia_core::codecs::CodecParameters::Audio(params)) = | |
| 766 | + track.codec_params.clone() | |
| 767 | + else { | |
| 768 | + return Err(format!("{} declares no audio codec", path.display()).into()); | |
| 769 | + }; | |
| 770 | + let sample_rate = params | |
| 771 | + .sample_rate | |
| 772 | + .ok_or_else(|| format!("{} declares no sample rate", path.display()))?; | |
| 773 | + let channels = params | |
| 774 | + .channels | |
| 775 | + .as_ref() | |
| 776 | + .map(|c| c.count() as u16) | |
| 777 | + .ok_or_else(|| format!("{} declares no channel layout", path.display()))?; | |
| 778 | + let codec = symphonia::default::get_codecs() | |
| 779 | + .get_audio_decoder(params.codec) | |
| 780 | + .map_or("an unsupported format", |d| d.codec.info.short_name); | |
| 781 | + Ok(Self { | |
| 782 | + reader, | |
| 783 | + track_id, | |
| 784 | + sample_rate, | |
| 785 | + channels, | |
| 786 | + total_samples: num_frames, | |
| 787 | + priming: u64::from(delay.unwrap_or(0)), | |
| 788 | + time_base, | |
| 789 | + params, | |
| 790 | + codec, | |
| 791 | + }) | |
| 792 | + } | |
| 793 | + | |
| 794 | + /// A fresh decoder: seeking mid-stream leaves state that belongs to the | |
| 795 | + /// packets we skipped, exactly as on the AAC path. | |
| 796 | + fn decoder(&self) -> crate::Result<Box<dyn AudioDecoder>> { | |
| 797 | + Ok(symphonia::default::get_codecs() | |
| 798 | + .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?) | |
| 799 | + } | |
| 800 | + | |
| 801 | + /// `secs` on this source's audible timeline into media samples (priming | |
| 802 | + /// included, so it compares directly against a decoded position). | |
| 803 | + fn media(&self, secs: f64) -> u64 { | |
| 804 | + ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) | |
| 805 | + } | |
| 806 | + | |
| 807 | + /// A packet timestamp in the track's time base, as samples per channel. | |
| 808 | + fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 { | |
| 809 | + let secs = self.time_base.calc_time_saturating(ts).as_secs_f64(); | |
| 810 | + (secs.max(0.0) * f64::from(self.sample_rate)) as u64 | |
| 811 | + } | |
| 812 | +} | |
| 813 | + | |
| 511 | 814 | /// One source's AAC track, resolved once: the reader plus everything the header |
| 512 | 815 | /// has to say about it. `stts` is copied out because every other field would |
| 513 | 816 | /// otherwise keep a borrow alive on the reader the worker needs mutably — a real |
| 514 | 817 | /// AAC track has one entry, so it is two `u32`s. |
| 515 | -struct Track { | |
| 818 | +struct AacTrack { | |
| 516 | 819 | reader: Mp4Reader<BufReader<File>>, |
| 517 | 820 | track_id: u32, |
| 518 | 821 | sample_count: u32, |
| @@ -530,15 +833,16 @@ struct Track { | ||
| 530 | 833 | params: AudioCodecParameters, |
| 531 | 834 | } |
| 532 | 835 | |
| 533 | -impl Track { | |
| 836 | +impl AacTrack { | |
| 534 | 837 | /// The `stream`-th audio track of `path`, counted in file order over *all* |
| 535 | 838 | /// audio tracks — the numbering [`AudioSession::probe_streams`] hands out. |
| 536 | 839 | /// |
| 537 | - /// Stream 0 is best effort: `Ok(None)` when there is no audio there at all | |
| 538 | - /// or the codec is one we do not decode, which is a valid silent source (a | |
| 539 | - /// file whose audio is AC-3 still has a picture worth editing). A stream the | |
| 540 | - /// caller *named* is a promise instead, so out of range or undecodable | |
| 541 | - /// there is an `Err` rather than silence the caller did not ask for. | |
| 840 | + /// Stream 0 is best effort: `Ok(None)` when there is no AAC track there at | |
| 841 | + /// all, which is a valid silent source (a file whose audio is AC-3 still has | |
| 842 | + /// a picture worth editing) and, for a standalone audio file, the door | |
| 843 | + /// through to symphonia ([`Track::open`]). A stream the caller *named* is a | |
| 844 | + /// promise instead, so out of range or not AAC there is an `Err` rather than | |
| 845 | + /// silence the caller did not ask for. | |
| 542 | 846 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { |
| 543 | 847 | let file = File::open(path)?; |
| 544 | 848 | let size = file.metadata()?.len(); |
| @@ -896,6 +1200,15 @@ fn run(mut w: Worker) { | ||
| 896 | 1200 | let Some(track) = w.tracks[source].as_mut() else { |
| 897 | 1201 | continue; // opener fills every named source; nothing to decode |
| 898 | 1202 | }; |
| 1203 | + let track = match track { | |
| 1204 | + Track::Sym(track) => { | |
| 1205 | + if !run_sym(track, seg, channels, &mut timeline, &w.tx) { | |
| 1206 | + return; // consumer went away | |
| 1207 | + } | |
| 1208 | + continue; | |
| 1209 | + } | |
| 1210 | + Track::Aac(track) => track, | |
| 1211 | + }; | |
| 899 | 1212 | let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) |
| 900 | 1213 | { |
| 901 | 1214 | Ok(decoder) => decoder, |
| @@ -933,35 +1246,126 @@ fn run(mut w: Worker) { | ||
| 933 | 1246 | }; |
| 934 | 1247 | buf.copy_to_vec_interleaved::<f32>(&mut interleaved); |
| 935 | 1248 | let next = pos + (interleaved.len() / channels) as u64; |
| 936 | - | |
| 937 | - // Everything before the target is encoder priming and/or decoder | |
| 938 | - // pre-roll, not audio the caller asked for: drop it, splitting the | |
| 939 | - // packet that straddles the target. | |
| 940 | - if next <= seg.media_target { | |
| 941 | - pos = next; | |
| 942 | - continue; | |
| 943 | - } | |
| 944 | - if pos < seg.media_target { | |
| 945 | - interleaved.drain(..(seg.media_target - pos) as usize * channels); | |
| 946 | - pos = seg.media_target; | |
| 947 | - } | |
| 948 | - // And the tail past the segment end goes too — on a short segment | |
| 949 | - // that is this same buffer, trimmed at both ends. | |
| 950 | - if next > seg.media_end { | |
| 951 | - interleaved.truncate((seg.media_end - pos) as usize * channels); | |
| 1249 | + if !emit( | |
| 1250 | + &mut interleaved, | |
| 1251 | + channels, | |
| 1252 | + seg, | |
| 1253 | + pos, | |
| 1254 | + next, | |
| 1255 | + &mut timeline, | |
| 1256 | + &w.tx, | |
| 1257 | + ) { | |
| 1258 | + return; // consumer went away | |
| 952 | 1259 | } |
| 953 | 1260 | pos = next; |
| 954 | - if interleaved.is_empty() { | |
| 955 | - continue; // nothing left of it; the loop head ends the segment | |
| 1261 | + } | |
| 1262 | + } | |
| 1263 | +} | |
| 1264 | + | |
| 1265 | +/// Trims one decoded buffer to the segment window and sends what survives. | |
| 1266 | +/// `pos` is the media position of its first frame and `next` of the one after | |
| 1267 | +/// it; both readers hand the same thing here, which is why the window rules | |
| 1268 | +/// live in one place. `false` means the consumer went away. | |
| 1269 | +/// | |
| 1270 | +/// Everything before the target is encoder priming and/or decoder pre-roll, not | |
| 1271 | +/// audio the caller asked for: it is dropped, splitting the buffer that | |
| 1272 | +/// straddles the target. The tail past the segment end goes too — on a short | |
| 1273 | +/// segment that is this same buffer, trimmed at both ends. | |
| 1274 | +fn emit( | |
| 1275 | + interleaved: &mut Vec<f32>, | |
| 1276 | + channels: usize, | |
| 1277 | + seg: &Segment, | |
| 1278 | + pos: u64, | |
| 1279 | + next: u64, | |
| 1280 | + timeline: &mut u64, | |
| 1281 | + tx: &SyncSender<AudioChunk>, | |
| 1282 | +) -> bool { | |
| 1283 | + if next <= seg.media_target { | |
| 1284 | + return true; | |
| 1285 | + } | |
| 1286 | + let mut pos = pos; | |
| 1287 | + if pos < seg.media_target { | |
| 1288 | + interleaved.drain(..(seg.media_target - pos) as usize * channels); | |
| 1289 | + pos = seg.media_target; | |
| 1290 | + } | |
| 1291 | + if next > seg.media_end { | |
| 1292 | + interleaved.truncate((seg.media_end - pos) as usize * channels); | |
| 1293 | + } | |
| 1294 | + if interleaved.is_empty() { | |
| 1295 | + return true; // nothing left of it; the loop head ends the segment | |
| 1296 | + } | |
| 1297 | + let chunk = AudioChunk { | |
| 1298 | + start_sample: *timeline, | |
| 1299 | + samples: std::mem::take(interleaved), | |
| 1300 | + }; | |
| 1301 | + *timeline += (chunk.samples.len() / channels) as u64; | |
| 1302 | + tx.send(chunk).is_ok() | |
| 1303 | +} | |
| 1304 | + | |
| 1305 | +/// One segment of a standalone audio file: seek the reader to just before the | |
| 1306 | +/// window, then decode forward until the window is filled. | |
| 1307 | +/// | |
| 1308 | +/// The seek goes [`SYM_PRE_ROLL`] ahead of the target and everything before the | |
| 1309 | +/// target is thrown away by [`emit`], which is what gives a codec with decoder | |
| 1310 | +/// state — mp3's bit reservoir above all — something to warm up on, exactly as | |
| 1311 | +/// the AAC path's two-packet pre-roll does. A reader that cannot seek at all | |
| 1312 | +/// simply decodes from wherever it is; the window rules still hold, it is only | |
| 1313 | +/// slower. `false` means the consumer went away. | |
| 1314 | +fn run_sym( | |
| 1315 | + track: &mut SymTrack, | |
| 1316 | + seg: &Segment, | |
| 1317 | + channels: usize, | |
| 1318 | + timeline: &mut u64, | |
| 1319 | + tx: &SyncSender<AudioChunk>, | |
| 1320 | +) -> bool { | |
| 1321 | + let mut decoder = match track.decoder() { | |
| 1322 | + Ok(decoder) => decoder, | |
| 1323 | + Err(e) => { | |
| 1324 | + eprintln!("audio decoder init failed: {e}"); | |
| 1325 | + return true; | |
| 1326 | + } | |
| 1327 | + }; | |
| 1328 | + let rate = f64::from(track.sample_rate.max(1)); | |
| 1329 | + let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate; | |
| 1330 | + if let Some(time) = Time::try_from_secs_f64(from) { | |
| 1331 | + let to = SeekTo::Time { | |
| 1332 | + time, | |
| 1333 | + track_id: Some(track.track_id), | |
| 1334 | + }; | |
| 1335 | + // A failed seek is not fatal: it leaves the reader where it was, and | |
| 1336 | + // the window rules below still only emit what the segment asked for. | |
| 1337 | + if let Err(e) = track.reader.seek(SeekMode::Accurate, to) { | |
| 1338 | + eprintln!("audio seek to {from:.3}s failed: {e}"); | |
| 1339 | + } | |
| 1340 | + } | |
| 1341 | + let mut interleaved = Vec::new(); | |
| 1342 | + loop { | |
| 1343 | + let packet = match track.reader.next_packet() { | |
| 1344 | + Ok(Some(packet)) => packet, | |
| 1345 | + Ok(None) => return true, // end of the file, and of the segment | |
| 1346 | + Err(e) => { | |
| 1347 | + eprintln!("audio demux error: {e}"); | |
| 1348 | + return true; | |
| 956 | 1349 | } |
| 957 | - let chunk = AudioChunk { | |
| 958 | - start_sample: timeline, | |
| 959 | - samples: std::mem::take(&mut interleaved), | |
| 960 | - }; | |
| 961 | - timeline += (chunk.samples.len() / channels) as u64; | |
| 962 | - if w.tx.send(chunk).is_err() { | |
| 963 | - return; // consumer went away | |
| 1350 | + }; | |
| 1351 | + if packet.track_id != track.track_id { | |
| 1352 | + continue; // another track of the same container | |
| 1353 | + } | |
| 1354 | + let pos = track.samples_at(packet.pts); | |
| 1355 | + if pos >= seg.media_end { | |
| 1356 | + return true; // segment done, on to the next one | |
| 1357 | + } | |
| 1358 | + let buf = match decoder.decode(&packet) { | |
| 1359 | + Ok(buf) => buf, | |
| 1360 | + Err(e) => { | |
| 1361 | + eprintln!("audio decode error at sample {pos}: {e}"); | |
| 1362 | + return true; | |
| 964 | 1363 | } |
| 1364 | + }; | |
| 1365 | + buf.copy_to_vec_interleaved::<f32>(&mut interleaved); | |
| 1366 | + let next = pos + (interleaved.len() / channels) as u64; | |
| 1367 | + if !emit(&mut interleaved, channels, seg, pos, next, timeline, tx) { | |
| 1368 | + return false; | |
| 965 | 1369 | } |
| 966 | 1370 | } |
| 967 | 1371 | } |
crates/engine/src/lib.rsmodified+45 -0
| @@ -26,7 +26,52 @@ pub use mux::{AudioParams, Mp4Muxer, VideoParams}; | ||
| 26 | 26 | pub use playback::PlaybackSession; |
| 27 | 27 | pub use project::{Clip, Project}; |
| 28 | 28 | |
| 29 | +/// Whether a path names a standalone audio file -- a source with no picture, | |
| 30 | +/// which belongs on the audio lane and nowhere else. Extension only, lowercased: | |
| 31 | +/// the decoder is what really decides, but a front-end has to know which lane a | |
| 32 | +/// dropped file may land on *before* anything is opened, and so does | |
| 33 | +/// [`PlaybackSession::import`](playback::PlaybackSession::import). | |
| 34 | +/// | |
| 35 | +/// Exactly the containers the engine's audio path reads (`audio::AudioSession`): | |
| 36 | +/// no opus, ac3 or dts, for which no pure-Rust decoder exists -- those are | |
| 37 | +/// refused by the same door that refuses a `.txt`, which is the honest answer. | |
| 38 | +pub fn is_audio(path: &std::path::Path) -> bool { | |
| 39 | + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { | |
| 40 | + matches!( | |
| 41 | + e.to_ascii_lowercase().as_str(), | |
| 42 | + "mp3" | "wav" | "flac" | "ogg" | "oga" | "m4a" | "aac" | |
| 43 | + ) | |
| 44 | + }) | |
| 45 | +} | |
| 46 | + | |
| 29 | 47 | /// Boxed error; the engine has few failure modes and every one of them is fatal |
| 30 | 48 | /// to the session, so a message is all a caller can act on. |
| 31 | 49 | pub type Error = Box<dyn std::error::Error + Send + Sync>; |
| 32 | 50 | pub type Result<T> = std::result::Result<T, Error>; |
| 51 | + | |
| 52 | +#[cfg(test)] | |
| 53 | +mod tests { | |
| 54 | + use std::path::Path; | |
| 55 | + | |
| 56 | + #[test] | |
| 57 | + fn is_audio_admits_the_containers_the_decoder_reads() { | |
| 58 | + for name in [ | |
| 59 | + "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", | |
| 60 | + ] { | |
| 61 | + assert!(super::is_audio(Path::new(name)), "{name}"); | |
| 62 | + } | |
| 63 | + // Video, projects, the formats with no pure-Rust decoder, and a file | |
| 64 | + // with no extension at all: all of them go elsewhere. | |
| 65 | + for name in [ | |
| 66 | + "clip.mp4", | |
| 67 | + "take.MP4", | |
| 68 | + "cut.edith", | |
| 69 | + "x.opus", | |
| 70 | + "y.ac3", | |
| 71 | + "notes", | |
| 72 | + "mp3", | |
| 73 | + ] { | |
| 74 | + assert!(!super::is_audio(Path::new(name)), "{name}"); | |
| 75 | + } | |
| 76 | + } | |
| 77 | +} |
crates/engine/src/playback.rsmodified+145 -22
| @@ -125,6 +125,17 @@ impl PlaybackSession { | ||
| 125 | 125 | /// a file we cannot hear is still a file we can watch. |
| 126 | 126 | pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> { |
| 127 | 127 | let path = path.as_ref().to_path_buf(); |
| 128 | + // A timeline is scaffolded from source 0's picture -- its size, its | |
| 129 | + // frame rate, its clock. A song has none of that, so it joins a | |
| 130 | + // timeline (`import`) rather than starting one, and saying so beats | |
| 131 | + // failing in the demuxer's words. | |
| 132 | + if crate::is_audio(&path) { | |
| 133 | + return Err(format!( | |
| 134 | + "{} has no picture: open a video first, then import it onto the audio lane", | |
| 135 | + path.display() | |
| 136 | + ) | |
| 137 | + .into()); | |
| 138 | + } | |
| 128 | 139 | // `open_worker` rather than `open` purely for the worker handle: the |
| 129 | 140 | // field has to exist from the start for the first seek to use it. |
| 130 | 141 | let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; |
| @@ -189,12 +200,34 @@ impl PlaybackSession { | ||
| 189 | 200 | |
| 190 | 201 | let mut counts = vec![meta.frame_count]; |
| 191 | 202 | for source in &doc.sources[1..] { |
| 203 | + // A source with no picture is checked on what it does have, and | |
| 204 | + // its length is its playing time -- the same two answers `import` | |
| 205 | + // gave it when it first joined the timeline. | |
| 206 | + if crate::is_audio(&source.path) { | |
| 207 | + audio_matches(source, &first_audio) | |
| 208 | + .map_err(|e| format!("source {}: {e}", source.path.display()))?; | |
| 209 | + counts.push(audio_frames(&source.path, meta.frame_rate)?); | |
| 210 | + continue; | |
| 211 | + } | |
| 192 | 212 | let (other, _) = Demuxer::open(&source.path) |
| 193 | 213 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 194 | 214 | matches_timeline(source, &other, &meta, &first_audio) |
| 195 | 215 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 196 | 216 | counts.push(other.frame_count); |
| 197 | 217 | } |
| 218 | + // The video lane can only play files that have pictures. Hand-written | |
| 219 | + // (or hand-edited) project files are the one door this can come in | |
| 220 | + // through, so it is refused by name here rather than becoming a clip | |
| 221 | + // that decodes to nothing. | |
| 222 | + for clip in &doc.video { | |
| 223 | + if crate::is_audio(&doc.sources[clip.source].path) { | |
| 224 | + return Err(format!( | |
| 225 | + "{} has no picture: it can only play on the audio lane", | |
| 226 | + doc.sources[clip.source].path.display() | |
| 227 | + ) | |
| 228 | + .into()); | |
| 229 | + } | |
| 230 | + } | |
| 198 | 231 | for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() { |
| 199 | 232 | if clip.out_frame > counts[clip.source] { |
| 200 | 233 | return Err(format!( |
| @@ -471,6 +504,11 @@ impl PlaybackSession { | ||
| 471 | 504 | /// there is no resampler here, and no AAC encoder to write the join with. |
| 472 | 505 | /// A front-end greys such a row out; this is the backstop that keeps a |
| 473 | 506 | /// stale one from making the whole timeline silent. |
| 507 | + /// | |
| 508 | + /// Which lane it lands on is decided here, from the file: one with a | |
| 509 | + /// picture is pasted across both lanes as a grouped take, one without | |
| 510 | + /// ([`crate::is_audio`]) is *placed* on the audio lane alone, overwriting | |
| 511 | + /// what it lands on and rippling nothing. A caller never has to ask. | |
| 474 | 512 | pub fn place_stream_at( |
| 475 | 513 | &mut self, |
| 476 | 514 | timeline_secs: f64, |
| @@ -488,16 +526,22 @@ impl PlaybackSession { | ||
| 488 | 526 | let first = self.first_audio()?; |
| 489 | 527 | audio_matches(&wanted, &first)?; |
| 490 | 528 | let source = self.project.import(path, stream); |
| 491 | - Ok(self.paste_at( | |
| 492 | - timeline_secs, | |
| 493 | - Clip { | |
| 494 | - start: 0, | |
| 495 | - in_frame: 0, | |
| 496 | - out_frame: frames.max(1), | |
| 497 | - source, | |
| 498 | - link: None, | |
| 499 | - }, | |
| 500 | - )) | |
| 529 | + let clip = Clip { | |
| 530 | + start: 0, | |
| 531 | + in_frame: 0, | |
| 532 | + out_frame: frames.max(1), | |
| 533 | + source, | |
| 534 | + link: None, | |
| 535 | + }; | |
| 536 | + // Which lane a source may land on is decided here and only here, so a | |
| 537 | + // front-end never has to make the same call twice: a file with no | |
| 538 | + // picture goes on the audio lane alone, overwriting and rippling | |
| 539 | + // nothing, because there is nothing on the video lane to move along | |
| 540 | + // with it. | |
| 541 | + Ok(match crate::is_audio(path) { | |
| 542 | + true => self.place_at(Lane::Audio, timeline_secs, clip), | |
| 543 | + false => self.paste_at(timeline_secs, clip), | |
| 544 | + }) | |
| 501 | 545 | } |
| 502 | 546 | |
| 503 | 547 | /// What the timeline's audio *is*: source 0's chosen stream, probed. Every |
| @@ -507,6 +551,16 @@ impl PlaybackSession { | ||
| 507 | 551 | AudioSession::probe(&first.path, first.audio_stream) |
| 508 | 552 | } |
| 509 | 553 | |
| 554 | + /// Places `clip` on `lane` alone at the playhead, overwriting what it lands | |
| 555 | + /// on and rippling nothing -- the one-lane insert a source with no picture | |
| 556 | + /// makes, and the only way an audio-only file reaches the timeline. The | |
| 557 | + /// placement belongs to no group (see [`Project::place`]). One undo step, | |
| 558 | + /// and it reseeks like every other edit. | |
| 559 | + pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { | |
| 560 | + let at = secs_to_frame(timeline_secs, self.meta.frame_rate); | |
| 561 | + self.edit(|p| p.place(lane, at, clip)) | |
| 562 | + } | |
| 563 | + | |
| 510 | 564 | /// Removes the video clip at `idx` and everything under it, closing the gap |
| 511 | 565 | /// on every lane. Unlike a split this *does* move every following frame, so |
| 512 | 566 | /// the session reseeks to wherever the playhead now points. |
| @@ -530,6 +584,9 @@ impl PlaybackSession { | ||
| 530 | 584 | /// the property that disagrees, for a caller to show. Nothing is changed by |
| 531 | 585 | /// a refusal. |
| 532 | 586 | pub fn import(&mut self, path: &Path) -> crate::Result<()> { |
| 587 | + if crate::is_audio(path) { | |
| 588 | + return self.import_audio(path); | |
| 589 | + } | |
| 533 | 590 | let (meta, _) = Demuxer::open(path)?; |
| 534 | 591 | let first = self.first_audio()?; |
| 535 | 592 | // Stream 0: an import brings a file in on its first audio track, and |
| @@ -551,6 +608,46 @@ impl PlaybackSession { | ||
| 551 | 608 | Ok(()) |
| 552 | 609 | } |
| 553 | 610 | |
| 611 | + /// Appends a standalone audio file to the end of the timeline, on the | |
| 612 | + /// **audio lane alone**: a song has no picture, so there is nothing to put | |
| 613 | + /// on the video lane and the timeline shows black under it. Its length is | |
| 614 | + /// its playing time rounded up to whole frames, which is the only frame | |
| 615 | + /// count such a source has. | |
| 616 | + /// | |
| 617 | + /// Refused in the same words as any other import when its rate or layout | |
| 618 | + /// disagrees with the timeline's -- one output device, one set of | |
| 619 | + /// parameters -- and refused outright on a silent timeline, which has no | |
| 620 | + /// device open at all. Nothing is changed by a refusal. | |
| 621 | + fn import_audio(&mut self, path: &Path) -> crate::Result<()> { | |
| 622 | + let first = self.first_audio()?; | |
| 623 | + // Stream 0, and there is no other: a standalone audio file carries one | |
| 624 | + // track (`AudioSession::probe_streams`), so nothing here has a stream | |
| 625 | + // to pick the way `place_stream_at` does for an mp4. | |
| 626 | + audio_matches(&Source::new(path, 0), &first)?; | |
| 627 | + let frames = audio_frames(path, self.meta.frame_rate)?; | |
| 628 | + | |
| 629 | + let old_end = self.timeline_duration(); | |
| 630 | + let source = self.project.import(path, 0); | |
| 631 | + let at = self.project.timeline_frames(); | |
| 632 | + self.project.place( | |
| 633 | + Lane::Audio, | |
| 634 | + at, | |
| 635 | + Clip { | |
| 636 | + start: at, | |
| 637 | + in_frame: 0, | |
| 638 | + out_frame: frames, | |
| 639 | + source, | |
| 640 | + link: None, | |
| 641 | + }, | |
| 642 | + ); | |
| 643 | + // Same reason as a video import: the running audio worker's segment | |
| 644 | + // list stops at the old end, so without a reseek the appended clip | |
| 645 | + // would play silent. | |
| 646 | + let at = if self.eos { old_end } else { self.now() }; | |
| 647 | + self.seek(at); | |
| 648 | + Ok(()) | |
| 649 | + } | |
| 650 | + | |
| 554 | 651 | /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` |
| 555 | 652 | /// clamps to the new duration and keeps playing playing, so a delete that |
| 556 | 653 | /// shortens the timeline past the playhead lands on the last frame. |
| @@ -819,25 +916,51 @@ fn matches_timeline( | ||
| 819 | 916 | audio_matches(source, first) |
| 820 | 917 | } |
| 821 | 918 | |
| 919 | +/// Whether a candidate's audio may join a timeline whose first source probes as | |
| 920 | +/// `first`: same rate, same layout, or both silent. One output device and one | |
| 921 | +/// exported track is all there is, and no resampler. | |
| 922 | +/// | |
| 822 | 923 | /// The audio half of [`matches_timeline`], which a stream placed on its own |
| 823 | 924 | /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it |
| 824 | 925 | /// comes with is already on the timeline. |
| 926 | +/// | |
| 927 | +/// The format itself is deliberately *not* part of this: an mp3 that agrees on | |
| 928 | +/// rate and layout plays alongside a timeline of mp4s perfectly well. What it | |
| 929 | +/// cannot do is be copied into an export, which is a refusal of its own, at | |
| 930 | +/// export time (`AudioSession::copy_multi_streams`). | |
| 825 | 931 | fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> { |
| 826 | - // Whole-probe equality: rate, layout and the esds fields, which the audio | |
| 827 | - // worker holds every source to anyway. Both silent is a match. | |
| 932 | + // Whole-probe equality: rate and layout, which the audio worker holds every | |
| 933 | + // source to anyway. Both silent is a match. | |
| 828 | 934 | let probe = AudioSession::probe(&source.path, source.audio_stream)?; |
| 829 | - if probe != *first { | |
| 830 | - return Err(match (probe, first) { | |
| 831 | - (None, _) => "the file is silent, the timeline has audio".to_string(), | |
| 832 | - (_, None) => "the file has audio, the timeline is silent".to_string(), | |
| 833 | - (Some(a), Some(b)) => format!( | |
| 834 | - "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", | |
| 835 | - a.params.sample_rate, a.channels, b.params.sample_rate, b.channels | |
| 836 | - ), | |
| 837 | - } | |
| 935 | + if probe == *first { | |
| 936 | + return Ok(()); | |
| 937 | + } | |
| 938 | + Err(match (probe, first) { | |
| 939 | + (None, _) => "the file is silent, the timeline has audio".to_string(), | |
| 940 | + (_, None) => "the file has audio, the timeline is silent".to_string(), | |
| 941 | + (Some(a), Some(b)) => format!( | |
| 942 | + "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", | |
| 943 | + a.sample_rate, a.channels, b.sample_rate, b.channels | |
| 944 | + ), | |
| 945 | + } | |
| 946 | + .into()) | |
| 947 | +} | |
| 948 | + | |
| 949 | +/// How many timeline frames a standalone audio file occupies: its playing time | |
| 950 | +/// rounded *up*, so the last partial frame is still covered rather than cut off, | |
| 951 | +/// and never zero (a clip is never empty). | |
| 952 | +fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> { | |
| 953 | + let secs = AudioSession::duration_secs(path)? | |
| 954 | + .ok_or_else(|| format!("{} has no audio track", path.display()))?; | |
| 955 | + let frames = (secs * fps).ceil(); | |
| 956 | + if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) { | |
| 957 | + return Err(format!( | |
| 958 | + "{} is {secs} s long, which is not a timeline", | |
| 959 | + path.display() | |
| 960 | + ) | |
| 838 | 961 | .into()); |
| 839 | 962 | } |
| 840 | - Ok(()) | |
| 963 | + Ok((frames as u32).max(1)) | |
| 841 | 964 | } |
| 842 | 965 | |
| 843 | 966 | /// `None` for a silent session -- no audio track, no plugin, no daemon, or a |
crates/engine/src/waveform.rsmodified+25 -0
| @@ -116,6 +116,31 @@ mod tests { | ||
| 116 | 116 | } |
| 117 | 117 | } |
| 118 | 118 | |
| 119 | + /// A song's clip draws like any other: this goes through the same | |
| 120 | + /// `open_multi_streams` the timeline plays with, which reads a standalone | |
| 121 | + /// audio file on stream 0 as readily as an mp4's AAC track. | |
| 122 | + #[test] | |
| 123 | + fn a_standalone_audio_file_has_peaks_too() { | |
| 124 | + let peaks = peaks(asset("test_tone.mp3"), 0, BPS) | |
| 125 | + .expect("open") | |
| 126 | + .expect("test_tone.mp3 is audio"); | |
| 127 | + let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one | |
| 128 | + assert!( | |
| 129 | + peaks.len().abs_diff(want) <= 2, | |
| 130 | + "{} buckets, want {want} +/-2", | |
| 131 | + peaks.len() | |
| 132 | + ); | |
| 133 | + // The fixture carries the A/V one's 1 Hz envelope, so the middle second | |
| 134 | + // has a dip and a peak. As a ratio, and a looser one: the tone sits | |
| 135 | + // around an eighth of full scale and mp3 does not preserve a true zero. | |
| 136 | + let level = |&(lo, hi): &(f32, f32)| hi - lo; | |
| 137 | + let band = &peaks[BPS as usize..][..BPS as usize]; | |
| 138 | + let dip = band.iter().map(level).fold(f32::MAX, f32::min); | |
| 139 | + let loudest = band.iter().map(level).fold(0.0, f32::max); | |
| 140 | + assert!(loudest > 0.05, "peak level only {loudest}"); | |
| 141 | + assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}"); | |
| 142 | + } | |
| 143 | + | |
| 119 | 144 | #[test] |
| 120 | 145 | fn video_only_source_has_no_peaks() { |
| 121 | 146 | assert!( |
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(©("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 | 193 | .expect("probe") |
| 194 | 194 | .expect("test_av.mp4 has audio"); |
| 195 | 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 | 197 | assert_eq!( |
| 198 | 198 | AudioSession::probe(asset("test_av2.mp4"), 0) |
| 199 | 199 | .unwrap() |
crates/engine/tests/audio_streams.rsmodified+46 -0
| @@ -179,3 +179,49 @@ fn an_impossible_stream_is_refused_not_guessed() { | ||
| 179 | 179 | ); |
| 180 | 180 | assert!(AudioSession::open_multi_streams(&[(silent, 1)], &[(Some(0), 0.0, 1.0)]).is_err()); |
| 181 | 181 | } |
| 182 | + | |
| 183 | +/// Where the stream picker meets a file that has no picture to pick against: a | |
| 184 | +/// standalone audio file is one stream, so it lists as one and answers to 0 | |
| 185 | +/// alone. A picker that offered a second row here would be offering a track | |
| 186 | +/// that does not exist. | |
| 187 | +#[test] | |
| 188 | +fn a_standalone_audio_file_is_exactly_one_stream() { | |
| 189 | + for (name, codec) in [("test_tone.mp3", "mp3"), ("test_tone.flac", "flac")] { | |
| 190 | + let streams = AudioSession::probe_streams(asset(name)).expect("probes"); | |
| 191 | + assert_eq!( | |
| 192 | + streams, | |
| 193 | + vec![StreamInfo { | |
| 194 | + index: 0, | |
| 195 | + codec: codec.into(), | |
| 196 | + channels: 2, | |
| 197 | + sample_rate: 44100, | |
| 198 | + // No mdhd to carry an ISO-639 tag, and one track needs no | |
| 199 | + // telling apart. | |
| 200 | + lang: None, | |
| 201 | + decodable: true, | |
| 202 | + }], | |
| 203 | + "{name}" | |
| 204 | + ); | |
| 205 | + // Stream 0 opens; anything above it is refused rather than quietly | |
| 206 | + // served the only track there is. | |
| 207 | + assert!( | |
| 208 | + AudioSession::open_multi_streams(&[(asset(name), 0)], &[(Some(0), 0.0, 1.0)]) | |
| 209 | + .expect("stream 0 opens") | |
| 210 | + .is_some(), | |
| 211 | + "{name}" | |
| 212 | + ); | |
| 213 | + let err = AudioSession::open_multi_streams(&[(asset(name), 1)], &[(Some(0), 0.0, 1.0)]) | |
| 214 | + .expect_err("there is no stream 1"); | |
| 215 | + assert!( | |
| 216 | + err.to_string().contains("audio stream 1 of 1 stream"), | |
| 217 | + "unhelpful refusal for {name}: {err}" | |
| 218 | + ); | |
| 219 | + } | |
| 220 | + // The ALAC .m4a is the awkward one: it parses as an mp4 whose only audio | |
| 221 | + // track is not AAC, so the mp4 walk would call it "unknown" and undecodable | |
| 222 | + // where symphonia decodes it perfectly well. | |
| 223 | + let alac = AudioSession::probe_streams(asset("test_tone.m4a")).expect("probes"); | |
| 224 | + assert_eq!(alac.len(), 1); | |
| 225 | + assert!(alac[0].decodable, "ALAC decodes: {alac:?}"); | |
| 226 | + assert_eq!((alac[0].sample_rate, alac[0].channels), (44100, 2)); | |
| 227 | +} |
crates/engine/tests/hevc.rsmodified+1 -1
| @@ -45,7 +45,7 @@ fn the_demuxer_reports_an_hevc_track() { | ||
| 45 | 45 | .expect("probe") |
| 46 | 46 | .expect("the fixture has an AAC track"); |
| 47 | 47 | assert_eq!( |
| 48 | - (probe.params.sample_rate, probe.channels), | |
| 48 | + (probe.sample_rate, probe.channels), | |
| 49 | 49 | (44_100, 2), |
| 50 | 50 | "audio is read the same whatever the picture is coded with" |
| 51 | 51 | ); |
crates/engine/tests/vp9.rsmodified+1 -1
| @@ -44,7 +44,7 @@ fn the_demuxer_reports_a_vp9_track() { | ||
| 44 | 44 | .expect("probe") |
| 45 | 45 | .expect("the fixture has an AAC track"); |
| 46 | 46 | assert_eq!( |
| 47 | - (probe.params.sample_rate, probe.channels), | |
| 47 | + (probe.sample_rate, probe.channels), | |
| 48 | 48 | (44_100, 2), |
| 49 | 49 | "audio is read the same whatever the picture is coded with" |
| 50 | 50 | ); |
scripts/gen_fixtures.shmodified+27 -0
| @@ -89,4 +89,31 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 89 | 89 | # has something concrete to refuse. |
| 90 | 90 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |
| 91 | 91 | -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 |
| 92 | +# Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the | |
| 93 | +# A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song | |
| 94 | +# can share a timeline with the video clips and the peaks tests can reuse the | |
| 95 | +# dip pattern. One per container we claim to read. | |
| 96 | +tone="[0:a][1:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" | |
| 97 | +for fmt in mp3 wav flac ogg m4a aac; do | |
| 98 | + case $fmt in | |
| 99 | + mp3) codec=(-c:a libmp3lame -b:a 128k) ;; | |
| 100 | + wav) codec=(-c:a pcm_s16le) ;; | |
| 101 | + flac) codec=(-c:a flac) ;; | |
| 102 | + ogg) codec=(-c:a libvorbis) ;; | |
| 103 | + # ALAC in mp4, and raw AAC in ADTS -- the two the mp4/AAC packet-copy | |
| 104 | + # path cannot claim: one is not AAC, the other is not in an mp4. | |
| 105 | + m4a) codec=(-c:a alac) ;; | |
| 106 | + aac) codec=(-c:a aac -b:a 128k -f adts) ;; | |
| 107 | + esac | |
| 108 | + ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ | |
| 109 | + -f lavfi -i "sine=frequency=880:duration=3" \ | |
| 110 | + -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ | |
| 111 | + "assets/test_tone.$fmt" | |
| 112 | +done | |
| 113 | +# The refusal fixture: same tone at 48k, which one output device cannot mix | |
| 114 | +# with a 44.1k timeline. | |
| 115 | +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ | |
| 116 | + -f lavfi -i "sine=frequency=880:duration=3" \ | |
| 117 | + -filter_complex "$tone" -map "[a]" -ar 48000 -c:a pcm_s16le \ | |
| 118 | + assets/test_tone_48k.wav | |
| 92 | 119 | echo "fixtures written to assets/" |