From 229a56987fe85b84bacf64c74c9c32675bff3f4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 06:47:38 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20audio=20decode,=20P?= =?UTF-8?q?ipeWire=20output=20plugin,=20playback=20clock?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wave 1 of the audio slice — three independent modules, app wiring comes next: - audio.rs: AAC-LC via standalone symphonia AacDecoder over the existing mp4 demuxer; priming trim read from the container elst (verified against ffprobe); channel identity pinned by zero-crossing tests on the 440/880 Hz fixture - engine-audio: dlopen'd PipeWire cdylib (ao_* C ABI). App binary keeps zero libpipewire linkage; daemon absent fails open() in ~1ms. Fill capped at 1024 frames/callback: uncapped, PipeWire hands the sink-sized buffer and the position clock steps 256ms at a time. Stream time rate is 1/48000 regardless of stream rate — position is rescaled or the clock runs 8.8% fast on 44.1k content - clock.rs: PlaybackClock, audio-driven with wall fallback; audio positions relative to last re-anchor so restarted streams re-sync; paused == frozen exactly, all re-anchoring through one path --- Cargo.lock | 195 ++++++++++++ Cargo.toml | 2 +- crates/engine-audio/Cargo.toml | 15 + crates/engine-audio/src/lib.rs | 455 ++++++++++++++++++++++++++++ crates/engine/Cargo.toml | 2 + crates/engine/src/ao.rs | 132 ++++++++ crates/engine/src/audio.rs | 236 +++++++++++++++ crates/engine/src/clock.rs | 311 +++++++++++++++++++ crates/engine/src/lib.rs | 5 + crates/engine/tests/ao_output.rs | 103 +++++++ crates/engine/tests/audio_decode.rs | 102 +++++++ 11 files changed, 1557 insertions(+), 1 deletion(-) create mode 100644 crates/engine-audio/Cargo.toml create mode 100644 crates/engine-audio/src/lib.rs create mode 100644 crates/engine/src/ao.rs create mode 100644 crates/engine/src/audio.rs create mode 100644 crates/engine/src/clock.rs create mode 100644 crates/engine/tests/ao_output.rs create mode 100644 crates/engine/tests/audio_decode.rs diff --git a/Cargo.lock b/Cargo.lock index 50d8715..0616864 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,6 +60,22 @@ dependencies = [ "equator", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "anyhow" version = "1.0.104" @@ -525,6 +541,25 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.1", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -814,6 +849,16 @@ dependencies = [ "nom 7.1.3", ] +[[package]] +name = "cfg-expr" +version = "0.20.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb693542bcafa528e198be0ebd9d3632ca5b7c93dbe7237460e199910835997c" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -1020,6 +1065,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "core-foundation" version = "0.9.4" @@ -1561,6 +1612,17 @@ dependencies = [ "libloading", "mp4", "rusty_h264", + "symphonia-codec-aac", + "symphonia-core", +] + +[[package]] +name = "engine-audio" +version = "0.1.0" +dependencies = [ + "engine", + "libspa-sys", + "pipewire", ] [[package]] @@ -3067,6 +3129,33 @@ dependencies = [ "libc", ] +[[package]] +name = "libspa" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2909f3be29d674e7f10604aff18d1bbe1bb03c4cd61c8a8ba19c0b1d162f7d4e" +dependencies = [ + "bitflags 2.13.1", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.4", + "system-deps", +] + +[[package]] +name = "libspa-sys" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ad52764fca54818486f3cf75afec844d1f1a1568c24dcee25d41b1ab007dda" +dependencies = [ + "bindgen 0.72.1", + "cc", + "system-deps", +] + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -3890,6 +3979,31 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8585aba8a52ad74ccc633b8e293c1dc4277976bd5d510b925533f34fd6685f38" +dependencies = [ + "bitflags 2.13.1", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.4", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2089f245b548723e60325773c27f586b7a2372c79ea941b246cd0d654706adc" +dependencies = [ + "bindgen 0.72.1", + "libspa-sys", + "system-deps", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -4472,6 +4586,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -5365,6 +5485,56 @@ dependencies = [ "zeno", ] +[[package]] +name = "symphonia-codec-aac" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1979c515a76371b186aad2feff5f23e21cbec775bf95de08bf1e3af92a2ad76" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-common" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8257891ffa7f05e02b58f4761e2abf7e5278c8744fd59e981559e050f86eef55" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-core" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95ec293b5f288383b72a7bffcade6b2860b642cf66f28b3bd5967349a49938b1" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "lazy_static", + "log", + "num-complex", + "smallvec", +] + +[[package]] +name = "symphonia-metadata" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31acf5cd623398a6208e2225d18f4b20f761c55098a796a5247ad516a4a8681" +dependencies = [ + "lazy_static", + "log", + "regex-lite", + "smallvec", + "symphonia-core", +] + [[package]] name = "syn" version = "1.0.109" @@ -5462,6 +5632,19 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 1.1.4+spec-1.1.0", + "version-compare", +] + [[package]] name = "taffy" version = "0.9.0" @@ -5492,6 +5675,12 @@ dependencies = [ "objc", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.27.0" @@ -6085,6 +6274,12 @@ dependencies = [ "sval_serde", ] +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index e5cd5b2..920d015 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/engine", "crates/engine-hw", "crates/app"] +members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"] # Vendored third-party (see [patch.crates-io]); not ours to build or test. exclude = ["vendor/cros-libva", "vendor/cros-codecs"] diff --git a/crates/engine-audio/Cargo.toml b/crates/engine-audio/Cargo.toml new file mode 100644 index 0000000..315dc44 --- /dev/null +++ b/crates/engine-audio/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "engine-audio" +version = "0.1.0" +edition = "2024" + +# PipeWire audio output plugin. Dynamically loaded at runtime (dlopen) so the +# main binary never gains a DT_NEEDED on libpipewire — PipeWire missing at +# runtime means the app runs muted, never that it fails to start. +[lib] +crate-type = ["cdylib"] + +[dependencies] +engine = { path = "../engine" } +pipewire = "0.10" +libspa-sys = "0.10" diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs new file mode 100644 index 0000000..3d41c11 --- /dev/null +++ b/crates/engine-audio/src/lib.rs @@ -0,0 +1,455 @@ +//! PipeWire playback, shipped as a `dlopen`-able plugin so the main binary +//! never gets a DT_NEEDED on libpipewire. Every entry point is `extern "C"`, +//! catches unwinds and reports failure as a null pointer or a negative code: +//! the caller's contract is "any failure means the app runs muted". +//! +//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with +//! `panic = "abort"` would turn a PipeWire bug into a killed app; the upgrade +//! path is running the output in a child process instead of in-process. + +use std::ffi::c_void; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, OnceLock, mpsc}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use pipewire as pw; +use pw::{properties::properties, spa}; +use spa::pod::Pod; + +/// How long the loop thread waits for the daemon to accept the stream before +/// the open counts as failed. Negotiation is a couple of graph cycles when it +/// works at all, so this only ever fires on a broken setup. +const READY_TIMEOUT: Duration = Duration::from_secs(1); +/// Belt and braces around the whole open: no PipeWire call on this path is +/// supposed to block, but `ao_open` must never hang the caller. +const OPEN_TIMEOUT: Duration = Duration::from_secs(2); +/// Loop iteration timeout on the audio thread; also the worst-case latency of +/// an `ao_set_active` taking effect. +const POLL: Duration = Duration::from_millis(10); +/// Frames we hand over per callback, and the latency we ask the graph for. +/// Left to itself PipeWire gives us a buffer the size of the sink's (measured: +/// 12288 frames, 256 ms) and calls us once per buffer, so the position clock -- +/// which only moves in the callback -- would step 256 ms at a time and land +/// that coarseness straight in the A/V sync. 1024 frames is ~23 ms, comfortably +/// inside a video frame; measured granularity is then one graph quantum. +/// +/// ponytail: a graph running a quantum longer than this would consume more per +/// cycle than we deliver and starve. The fix is the crate's `v0_3_49` feature, +/// whose `pw_buffer.requested` says exactly how many frames the graph wants -- +/// a Cargo.toml change, so not this slice. +const QUANTUM: u32 = 1024; + +/// Lock-free SPSC ring of f32 samples (interleaved, one producer: `ao_write`, +/// one consumer: the RT process callback). Samples live in atomics rather than +/// behind a lock so the RT thread never waits on the decoder thread. +struct Ring { + /// Power-of-two length, so the monotonic counters below can be masked and + /// still index correctly across a `usize` wrap. + slots: Box<[AtomicU32]>, + write: AtomicUsize, + read: AtomicUsize, +} + +impl Ring { + fn new(capacity: usize) -> Self { + let len = capacity.next_power_of_two(); + Self { + slots: (0..len).map(|_| AtomicU32::new(0)).collect(), + write: AtomicUsize::new(0), + read: AtomicUsize::new(0), + } + } + + /// Appends as much of `src` as fits, returning how many samples were taken. + fn push(&self, src: &[f32]) -> usize { + let write = self.write.load(Ordering::Relaxed); + let used = write.wrapping_sub(self.read.load(Ordering::Acquire)); + let n = src.len().min(self.slots.len() - used); + let mask = self.slots.len() - 1; + for (i, sample) in src[..n].iter().enumerate() { + self.slots[write.wrapping_add(i) & mask].store(sample.to_bits(), Ordering::Relaxed); + } + self.write.store(write.wrapping_add(n), Ordering::Release); + n + } + + /// Pops up to `want` samples as little-endian f32 into `dst`, returning how + /// many were available. `dst` must hold `want * 4` bytes. + fn pop(&self, dst: &mut [u8], want: usize) -> usize { + let read = self.read.load(Ordering::Relaxed); + let avail = self.write.load(Ordering::Acquire).wrapping_sub(read); + let n = want.min(avail); + let mask = self.slots.len() - 1; + for i in 0..n { + let bits = self.slots[read.wrapping_add(i) & mask].load(Ordering::Relaxed); + dst[i * 4..i * 4 + 4].copy_from_slice(&bits.to_le_bytes()); + } + self.read.store(read.wrapping_add(n), Ordering::Release); + n + } +} + +/// Everything the RT thread and the caller's thread both touch. +struct Shared { + ring: Ring, + /// Samples per channel played at the device, -1 until the first callback. + position: AtomicI64, + /// Set once the daemon has accepted the stream. + ready: AtomicBool, + /// Stream died (daemon gone, node removed); every later write fails. + dead: AtomicBool, + underruns: AtomicU64, +} + +enum Ctl { + Active(bool), + Quit, +} + +fn pw_init() { + // Refcounted inside libpipewire, but a plugin has no safe point to call + // `pw::deinit`, so we init exactly once and never tear down. + static INIT: OnceLock<()> = OnceLock::new(); + INIT.get_or_init(pw::init); +} + +/// Builds the stream, reports readiness through `ready`, then owns the PipeWire +/// loop until told to quit. Everything PipeWire lives in this one frame: the +/// smart pointers are `Rc`-flavoured and the borrow chain (listener -> stream -> +/// core -> context -> loop) is what enforces the destruction order. +fn run( + rate: u32, + channels: usize, + shared: Arc, + ready: mpsc::Sender<()>, + ctl: mpsc::Receiver, +) -> Result<(), pw::Error> { + pw_init(); + let mainloop = pw::main_loop::MainLoopRc::new(None)?; + let context = pw::context::ContextRc::new(&mainloop, None)?; + // Fails synchronously when there is no daemon to talk to: the clean probe. + let core = context.connect_rc(None)?; + + let stream = pw::stream::StreamBox::new( + &core, + "video-editor", + properties! { + *pw::keys::MEDIA_TYPE => "Audio", + *pw::keys::MEDIA_CATEGORY => "Playback", + *pw::keys::MEDIA_ROLE => "Movie", + *pw::keys::AUDIO_CHANNELS => channels.to_string(), + // Asks the graph to schedule us at our own quantum, which is what + // keeps the fill below from under-delivering on a lazy sink. + *pw::keys::NODE_LATENCY => format!("{QUANTUM}/{rate}"), + }, + )?; + + let _listener = stream + .add_local_listener_with_user_data(()) + .state_changed({ + let shared = shared.clone(); + move |_, (), _old, new| match new { + pw::stream::StreamState::Paused | pw::stream::StreamState::Streaming => { + shared.ready.store(true, Ordering::Relaxed) + } + pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected => { + shared.dead.store(true, Ordering::Relaxed) + } + pw::stream::StreamState::Connecting => {} + } + }) + .process({ + let shared = shared.clone(); + let stride = 4 * channels; + move |stream, ()| { + let Some(mut buffer) = stream.dequeue_buffer() else { + return; + }; + let datas = buffer.datas_mut(); + let Some(data) = datas.first_mut() else { + return; + }; + let n_frames = match data.data() { + Some(slice) => { + // Only a quantum per callback, however big the buffer + // is: everything we queue here is latency the clock, + // the pause and a future seek all have to wait out. + let frames = (slice.len() / stride).min(QUANTUM as usize); + let want = frames * channels; + let got = shared.ring.pop(slice, want); + if got < want { + // Underrun: silence rather than stale samples, and + // the clock below keeps running -- the device plays + // that silence, so it really is elapsed time. + slice[got * 4..want * 4].fill(0); + shared.underruns.fetch_add(1, Ordering::Relaxed); + } + frames + } + None => 0, + }; + let chunk = data.chunk_mut(); + *chunk.offset_mut() = 0; + *chunk.stride_mut() = stride as _; + *chunk.size_mut() = (stride * n_frames) as _; + + // The A/V master clock: what the device has actually played, + // which is the stream position minus everything still in flight. + if let Ok(time) = stream.time() { + let ticks = time.ticks() as i64 - time.delay(); + let (num, denom) = (time.rate().num as i128, time.rate().denom as i128); + // `ticks` counts in the stream's own rate; convert to ours. + let played = if denom > 0 { + (ticks as i128 * num * rate as i128 / denom) as i64 + } else { + ticks + }; + shared.position.store(played.max(0), Ordering::Relaxed); + } + } + }) + .register()?; + + let mut audio_info = spa::param::audio::AudioInfoRaw::new(); + audio_info.set_format(spa::param::audio::AudioFormat::F32LE); + audio_info.set_rate(rate); + audio_info.set_channels(channels as u32); + let mut position = [0; spa::param::audio::MAX_CHANNELS]; + match channels { + 1 => position[0] = libspa_sys::SPA_AUDIO_CHANNEL_MONO, + 2 => { + position[0] = libspa_sys::SPA_AUDIO_CHANNEL_FL; + position[1] = libspa_sys::SPA_AUDIO_CHANNEL_FR; + } + // Anything else keeps UNKNOWN positions and lets the daemon map them. + _ => {} + } + audio_info.set_position(position); + + let values: Vec = pw::spa::pod::serialize::PodSerializer::serialize( + std::io::Cursor::new(Vec::new()), + &pw::spa::pod::Value::Object(pw::spa::pod::Object { + type_: libspa_sys::SPA_TYPE_OBJECT_Format, + id: libspa_sys::SPA_PARAM_EnumFormat, + properties: audio_info.into(), + }), + ) + .map_err(|_| pw::Error::CreationFailed)? + .0 + .into_inner(); + let mut params = [Pod::from_bytes(&values).ok_or(pw::Error::CreationFailed)?]; + + stream.connect( + spa::utils::Direction::Output, + None, + pw::stream::StreamFlags::AUTOCONNECT + | pw::stream::StreamFlags::MAP_BUFFERS + | pw::stream::StreamFlags::RT_PROCESS, + &mut params, + )?; + + // `connect` only starts negotiation, so a bad format or a daemon that + // refuses us still shows up here rather than as silent nothing later. + let deadline = Instant::now() + READY_TIMEOUT; + while !shared.ready.load(Ordering::Relaxed) { + if shared.dead.load(Ordering::Relaxed) || Instant::now() >= deadline { + return Err(pw::Error::CreationFailed); + } + mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL)); + } + let _ = ready.send(()); + + // Driving the loop by hand instead of `mainloop.run()` + a PipeWire channel: + // loop callbacks must be `'static` and the stream borrows the core, so a + // callback cannot touch the stream. Iterating lets us call `set_active` from + // this very frame. With RT_PROCESS the audio callback runs on the RT thread + // regardless, so this loop only handles negotiation and control. + 'run: loop { + mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL)); + loop { + match ctl.try_recv() { + Ok(Ctl::Active(active)) => { + let _ = stream.set_active(active); + } + // Disconnected means the session was dropped without a Quit. + Ok(Ctl::Quit) | Err(mpsc::TryRecvError::Disconnected) => break 'run, + Err(mpsc::TryRecvError::Empty) => break, + } + } + } + let _ = stream.disconnect(); + Ok(()) +} + +struct Session { + shared: Arc, + ctl: mpsc::Sender, + thread: Option>, +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.ctl.send(Ctl::Quit); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + let underruns = self.shared.underruns.load(Ordering::Relaxed); + if underruns > 0 { + eprintln!("engine_audio: {underruns} underruns"); + } + } +} + +/// Opens a playback stream for `sample_rate` Hz, `channels` channels of +/// interleaved f32. Returns null on any failure at all: no libpipewire, no +/// daemon, an unusable format. +#[unsafe(no_mangle)] +pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { + catch_unwind(AssertUnwindSafe(|| { + if !(8_000..=768_000).contains(&sample_rate) + || channels == 0 + || channels as usize > spa::param::audio::MAX_CHANNELS + { + return std::ptr::null_mut(); + } + pw_init(); + + let shared = Arc::new(Shared { + // One second of audio: enough that a stalled decoder is audible as + // an underrun rather than papered over by a huge buffer. + ring: Ring::new(sample_rate as usize * channels as usize), + position: AtomicI64::new(-1), + ready: AtomicBool::new(false), + dead: AtomicBool::new(false), + underruns: AtomicU64::new(0), + }); + let (ready_tx, ready_rx) = mpsc::channel(); + let (ctl_tx, ctl_rx) = mpsc::channel(); + let thread = std::thread::spawn({ + let shared = shared.clone(); + move || { + if let Err(e) = run(sample_rate, channels as usize, shared, ready_tx, ctl_rx) { + eprintln!("engine_audio: {e}"); + } + } + }); + + // A failed setup drops `ready_tx`, so this returns without waiting out + // the timeout; the timeout only covers a PipeWire call that blocks + // against its contract, and then we leave the thread to its own exit. + match ready_rx.recv_timeout(OPEN_TIMEOUT) { + Ok(()) => Box::into_raw(Box::new(Session { + shared, + ctl: ctl_tx, + thread: Some(thread), + })) as *mut c_void, + Err(_) => { + let _ = ctl_tx.send(Ctl::Quit); + std::ptr::null_mut() + } + } + })) + .unwrap_or(std::ptr::null_mut()) +} + +/// Queues up to `n` interleaved f32 samples, returning how many were accepted: +/// short counts mean the ring is full. Never blocks. -1 once the stream is dead. +/// +/// # Safety +/// `session` must come from [`ao_open`] and `samples` must point at `n` f32s. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: usize) -> isize { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || samples.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and `n` readable samples. + let session = unsafe { &*(session as *const Session) }; + if session.shared.dead.load(Ordering::Relaxed) { + return -1; + } + let samples = unsafe { std::slice::from_raw_parts(samples, n) }; + session.shared.ring.push(samples) as isize + })) + .unwrap_or(-1) +} + +/// Samples per channel actually played at the device, or -1 while unknown. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + session.shared.position.load(Ordering::Relaxed) + })) + .unwrap_or(-1) +} + +/// Pauses (0) or resumes (non-zero) playback. Paused freezes the position. +/// 0 on success, negative on failure. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + match session.ctl.send(Ctl::Active(active != 0)) { + Ok(()) => 0, + Err(_) => -1, + } + })) + .unwrap_or(-1) +} + +/// Stops playback and releases the session. Safe to call with null. +/// +/// # Safety +/// `session` must come from [`ao_open`] and must not be used afterwards. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_close(session: *mut c_void) { + let _ = catch_unwind(AssertUnwindSafe(|| { + if !session.is_null() { + // SAFETY: pointer came from `Box::into_raw` in `ao_open`. + drop(unsafe { Box::from_raw(session as *mut Session) }); + } + })); +} + +#[cfg(test)] +mod tests { + use super::Ring; + + #[test] + fn ring_wraps_fills_and_starves() { + let ring = Ring::new(4); + let mut out = [0u8; 24]; + + // Short write, then read it back as little-endian f32. + assert_eq!(ring.push(&[1.0, 2.0]), 2); + assert_eq!(ring.pop(&mut out, 2), 2); + assert_eq!(&out[..4], &1.0f32.to_le_bytes()); + assert_eq!(&out[4..8], &2.0f32.to_le_bytes()); + + // Full ring accepts only what fits, and the tail wraps the mask. + assert_eq!(ring.push(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), 4); + assert_eq!(ring.push(&[9.0]), 0); + assert_eq!(ring.pop(&mut out, 6), 4); + assert_eq!(&out[12..16], &4.0f32.to_le_bytes()); + + // Empty ring starves instead of replaying stale samples. + assert_eq!(ring.pop(&mut out, 4), 0); + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b11a936..0e037a7 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,3 +8,5 @@ edition.workspace = true libloading = "0.8" mp4 = "0.14" rusty_h264 = { version = "0.8", default-features = false } +symphonia-core = "0.6" +symphonia-codec-aac = "0.6" diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs new file mode 100644 index 0000000..024697f --- /dev/null +++ b/crates/engine/src/ao.rs @@ -0,0 +1,132 @@ +//! Runtime-optional audio output plugin (`libengine_audio.so`). +//! +//! The plugin links libpipewire; this crate and the app binary must not, so the +//! only coupling is this C ABI plus a `dlopen`. Anything that goes wrong -- +//! plugin missing, no PipeWire daemon, an unusable format -- leaves us with +//! `None` and the caller plays silently. + +use std::ffi::c_void; +use std::path::Path; +use std::sync::OnceLock; + +use libloading::Library; + +const LIB_NAME: &str = "libengine_audio.so"; + +struct Plugin { + open: unsafe extern "C" fn(u32, u32) -> *mut c_void, + write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize, + position: unsafe extern "C" fn(*mut c_void) -> i64, + set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, + close: unsafe extern "C" fn(*mut c_void), + // Never dropped (lives in a static), so the fn pointers above stay valid. + _lib: Library, +} + +fn plugin() -> Option<&'static Plugin> { + static PLUGIN: OnceLock> = OnceLock::new(); + PLUGIN.get_or_init(load).as_ref() +} + +fn load() -> Option { + // Next to the executable first (cargo puts both in target/), then + // whatever the dynamic linker's search path turns up. + let beside_exe = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME))); + let candidates = beside_exe + .as_deref() + .into_iter() + .chain(std::iter::once(Path::new(LIB_NAME))); + + for candidate in candidates { + // SAFETY: loading a shared object runs its initialisers; we only ever + // name our own plugin, and every symbol below is type-checked against + // the signatures this crate shares with it. + let lib = match unsafe { Library::new(candidate) } { + Ok(lib) => lib, + Err(_) => continue, + }; + let plugin = unsafe { + (|| { + Some(Plugin { + open: *lib.get(b"ao_open\0").ok()?, + write: *lib.get(b"ao_write\0").ok()?, + position: *lib.get(b"ao_position\0").ok()?, + set_active: *lib.get(b"ao_set_active\0").ok()?, + close: *lib.get(b"ao_close\0").ok()?, + _lib: lib, + }) + })() + }; + if plugin.is_some() { + return plugin; + } + } + None +} + +/// An open playback stream. Dropping it stops playback and closes the session. +pub struct AoSession { + plugin: &'static Plugin, + handle: *mut c_void, +} + +impl AoSession { + /// Connects a playback stream for interleaved f32 at `sample_rate`. + /// `None` covers everything: no plugin, no daemon, unusable format. + pub fn open(sample_rate: u32, channels: u32) -> Option { + let plugin = plugin()?; + // SAFETY: plain scalars in, a session pointer or null out. + let handle = unsafe { (plugin.open)(sample_rate, channels) }; + if handle.is_null() { + return None; + } + Some(Self { plugin, handle }) + } + + /// Whether the plugin itself is loadable. Says nothing about the daemon -- + /// only [`AoSession::open`] answers that, and it is cheap enough to be the + /// real probe. + pub fn probe() -> bool { + plugin().is_some() + } + + /// Queues interleaved samples, returning how many were accepted; a short + /// count means the ring is full and the caller should come back later. + /// `None` once the output has died (daemon gone). + pub fn write(&mut self, samples: &[f32]) -> Option { + // SAFETY: `handle` is live and `samples` is a valid slice for the call. + match unsafe { (self.plugin.write)(self.handle, samples.as_ptr(), samples.len()) } { + n if n < 0 => None, + n => Some(n as usize), + } + } + + /// Samples per channel actually played at the device -- the master clock. + /// `None` until the stream has run its first cycle. + pub fn position(&self) -> Option { + // SAFETY: `handle` came from `ao_open` and is still open. + match unsafe { (self.plugin.position)(self.handle) } { + n if n < 0 => None, + n => Some(n), + } + } + + /// Pauses or resumes playback; while paused the position stays put. + pub fn set_active(&self, active: bool) -> bool { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } + } +} + +impl Drop for AoSession { + fn drop(&mut self) { + // SAFETY: `handle` came from `ao_open` and is closed exactly once. + unsafe { (self.plugin.close)(self.handle) } + } +} + +// The session is used from one thread at a time (the audio feeder) and never +// shared; the PipeWire state behind it is not `Sync`. +unsafe impl Send for AoSession {} diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs new file mode 100644 index 0000000..a4f633e --- /dev/null +++ b/crates/engine/src/audio.rs @@ -0,0 +1,236 @@ +//! Background audio decode worker: pulls the AAC track out of an MP4 and hands +//! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own +//! `Mp4Reader` so the video demuxer stays single-owner. + +use std::fs::File; +use std::io::BufReader; +use std::path::Path; +use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; +use std::thread; + +use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track}; +use symphonia_codec_aac::AacDecoder; +use symphonia_core::codecs::audio::{ + AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, +}; +use symphonia_core::packet::Packet; +use symphonia_core::units; + +/// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. +/// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) +const DEFAULT_PRIMING: u64 = 1024; + +/// An edit list entry that only shifts the timeline, carrying no media. +const EMPTY_EDIT: u64 = u32::MAX as u64; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AudioMeta { + pub sample_rate: u32, + pub channels: u16, + /// Frames per channel the container claims, priming subtracted. `None` when + /// the header does not say. + pub total_samples: Option, +} + +/// One decoder output block, ready to hand to an output device. +pub struct AudioChunk { + /// Position of the first frame, in samples-per-channel counted from the + /// first audible sample: priming is already dropped, so 0 is media time 0. + pub start_sample: u64, + /// Interleaved, `AudioMeta::channels` values per frame. + pub samples: Vec, +} + +pub struct AudioSession; + +impl AudioSession { + /// Opens the audio track of `path`. `Ok(None)` means the file simply has no + /// audio, which is a valid session; `Err` is a real failure. + pub fn open( + path: impl AsRef, + ) -> crate::Result)>> { + let file = File::open(path.as_ref())?; + let size = file.metadata()?.len(); + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; + + let Some(track) = reader + .tracks() + .values() + .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) + else { + return Ok(None); + }; + + // AacDecoder only does plain LC, mono/stereo; refuse early with a + // message instead of letting it fail packet by packet. + match track.audio_profile()? { + AudioObjectType::AacLowComplexity => {} + other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), + } + let channels: u16 = match track.channel_config()? { + ChannelConfig::Mono => 1, + ChannelConfig::Stereo => 2, + other => return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()), + }; + + let track_id = track.track_id(); + let sample_rate = track.sample_freq_index()?.freq(); + let priming = priming_samples(track, sample_rate); + let total_samples = scale(track.trak.mdia.mdhd.duration, sample_rate, track.timescale()) + .map(|d| d.saturating_sub(priming)); + + let mut params = AudioCodecParameters::new(); + params + .for_codec(CODEC_ID_AAC) + .with_sample_rate(sample_rate) + .with_extra_data(audio_specific_config(track)?); + let decoder = AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())?; + + let sample_count = reader.sample_count(track_id)?; + let meta = AudioMeta { + sample_rate, + channels, + total_samples, + }; + // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so + // this bound is ~0.75 s of lookahead — enough to ride out decode jitter + // without making a pause take a second to bite. + let (tx, rx) = sync_channel(32); + thread::Builder::new().name("audio-decode".into()).spawn(move || { + run(Worker { + reader, + decoder, + track_id, + sample_count, + channels: channels as usize, + priming, + tx, + }) + })?; + Ok(Some((meta, rx))) + } +} + +/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14 +/// parses those out and drops the raw bytes, so this is the exact inverse of its +/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`). +fn audio_specific_config(track: &Mp4Track) -> crate::Result> { + let esds = track + .trak + .mdia + .minf + .stbl + .stsd + .mp4a + .as_ref() + .and_then(|mp4a| mp4a.esds.as_ref()) + .ok_or("AAC track has no esds descriptor")?; + let cfg = &esds.es_desc.dec_config.dec_specific; + Ok(Box::new([ + (cfg.profile << 3) | (cfg.freq_index >> 1), + (cfg.freq_index << 7) | (cfg.chan_conf << 3), + ])) +} + +/// Encoder delay in samples-per-channel: the edit list's first real entry says +/// how far into the media the presentation starts. +/// +/// ponytail: an explicit `media_time` of 0 is taken at face value (no trim). +/// Muxers that write a zero edit list despite a primed stream would leak the +/// priming; upgrade path is preferring the codec delay when it disagrees. +fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 { + track + .trak + .edts + .as_ref() + .and_then(|edts| edts.elst.as_ref()) + .and_then(|elst| { + elst.entries + .iter() + .map(|e| e.media_time) + .find(|&t| t != EMPTY_EDIT && t != u64::MAX) + }) + .and_then(|t| scale(t, sample_rate, track.timescale())) + .unwrap_or(DEFAULT_PRIMING) +} + +/// `value` from the track timescale into samples-per-channel. `None` on a zero +/// timescale, which would be a broken header. +fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option { + let timescale = u64::from(timescale); + (timescale != 0).then(|| value * u64::from(sample_rate) / timescale) +} + +struct Worker { + reader: Mp4Reader>, + decoder: AacDecoder, + track_id: u32, + sample_count: u32, + channels: usize, + priming: u64, + tx: SyncSender, +} + +fn run(mut w: Worker) { + let mut interleaved = Vec::new(); + let mut to_skip = w.priming; + let mut emitted = 0u64; + + for id in 1..=w.sample_count { + let sample = match w.reader.read_sample(w.track_id, id) { + Ok(Some(sample)) => sample, + Ok(None) => break, + Err(e) => { + eprintln!("audio demux error at sample {id}: {e}"); + break; + } + }; + let packet = Packet::new( + w.track_id, + units::Timestamp::new(sample.start_time as i64), + units::Duration::new(u64::from(sample.duration)), + &sample.bytes[..], + ); + let buf = match w.decoder.decode(&packet) { + Ok(buf) => buf, + Err(e) => { + eprintln!("audio decode error at sample {id}: {e}"); + break; + } + }; + buf.copy_to_vec_interleaved::(&mut interleaved); + + // Priming frames are encoder ramp-up, not audio: drop them so the first + // sample the caller sees is the first audible one. + if to_skip > 0 { + let drop = to_skip.min((interleaved.len() / w.channels) as u64); + interleaved.drain(..drop as usize * w.channels); + to_skip -= drop; + if interleaved.is_empty() { + continue; + } + } + let chunk = AudioChunk { + start_sample: emitted, + samples: std::mem::take(&mut interleaved), + }; + emitted += (chunk.samples.len() / w.channels) as u64; + if w.tx.send(chunk).is_err() { + break; // consumer went away + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn asc_round_trips_aac_lc_44100_stereo() { + // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo). + let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8); + let asc = [ + (profile << 3) | (freq_index >> 1), + (freq_index << 7) | (chan_conf << 3), + ]; + assert_eq!(asc, [0x12, 0x10]); + } +} diff --git a/crates/engine/src/clock.rs b/crates/engine/src/clock.rs new file mode 100644 index 0000000..d7ba5b3 --- /dev/null +++ b/crates/engine/src/clock.rs @@ -0,0 +1,311 @@ +//! Playback master clock: the one answer to "what time is it in this timeline?". +//! +//! Audio owns the clock whenever it plays -- the app polls the audio plugin and +//! feeds the sample position in with [`PlaybackClock::set_audio_position`]. With +//! no audio (muted, video-only, past audio EOF) the clock is anchored to an +//! [`Instant`] instead. Both modes are the same timeline, so switching mid-play +//! re-anchors at the current time and never jumps. +//! +//! Granularity contract: in audio mode `now()` steps at the audio quantum, not +//! smoothly. The reported position advances once per 256-1024 frame buffer +//! (5-23 ms at 48 kHz) while the app polls per rendered frame (~16 ms), so two +//! consecutive polls can return the same time and the next can jump by a whole +//! quantum. That is below the app's drift threshold, so it costs nothing today. +//! Smoothing (interpolating with the report's own timestamp) belongs on the +//! audio-plugin side where that timestamp exists, not here. +//! +//! Drift policy -- whether a late frame is dropped or an early one held -- is the +//! app's; this type only reports time. + +use std::time::Instant; + +/// What drives [`PlaybackClock::now`]. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ClockSource { + /// Externally reported audio sample position. + Audio, + /// Elapsed wall time since the last anchor. + Wall, +} + +/// Monotonic-while-playing playback position, in seconds. `Send`, with no +/// threads or I/O of its own: every state change is an explicit call. +pub struct PlaybackClock { + source: ClockSource, + playing: bool, + /// Timeline position of the current anchor. While paused this *is* `now()`. + base: f64, + /// Wall anchor; only meaningful while playing in [`ClockSource::Wall`]. + anchor: Instant, + /// Audio position at the anchor, `None` until the first report after a + /// re-anchor. Reports are relative to this, so a stream that restarts its + /// sample counter after a seek re-syncs instead of jumping. + audio_ref: Option, + /// Last accepted report, to clamp a position that runs backwards. + audio_last: f64, +} + +impl PlaybackClock { + /// A paused clock at t=0. + pub fn new(source: ClockSource) -> Self { + Self { + source, + playing: false, + base: 0.0, + anchor: Instant::now(), + audio_ref: None, + audio_last: 0.0, + } + } + + pub fn source(&self) -> ClockSource { + self.source + } + + pub fn is_playing(&self) -> bool { + self.playing + } + + /// Current timeline position in seconds. Frozen exactly while paused, never + /// decreasing while playing. + pub fn now(&self) -> f64 { + if !self.playing { + return self.base; + } + match self.source { + ClockSource::Wall => self.base + self.anchor.elapsed().as_secs_f64(), + ClockSource::Audio => match self.audio_ref { + Some(r) => self.base + (self.audio_last - r), + None => self.base, + }, + } + } + + /// Resumes from wherever `now()` was frozen. No-op if already playing. + pub fn play(&mut self) { + if !self.playing { + self.playing = true; + self.reanchor(self.base); + } + } + + pub fn pause(&mut self) { + if self.playing { + self.base = self.now(); + self.playing = false; + } + } + + /// Repositions the timeline to `secs`, playing or paused. + pub fn seek_to(&mut self, secs: f64) { + self.reanchor(secs); + } + + /// Audio EOF: keeps the clock running off wall time from the current + /// position, so `now()` is continuous across the switch. + pub fn switch_to_wall(&mut self) { + self.reanchor(self.now()); + self.source = ClockSource::Wall; + } + + /// Hands the clock back to audio from the current position. The next + /// reported sample position becomes the new reference whatever its value. + pub fn switch_to_audio(&mut self) { + self.reanchor(self.now()); + self.source = ClockSource::Audio; + } + + /// The app's audio position poll. Ignored in wall mode, and ignored when it + /// runs backwards (a device reset restarts the counter) so playback time + /// never rewinds under the renderer; the app re-syncs with `seek_to` or + /// `switch_to_wall`. + pub fn set_audio_position(&mut self, samples_played: u64, sample_rate: u32) { + if sample_rate == 0 { + return; + } + let secs = samples_played as f64 / sample_rate as f64; + match self.audio_ref { + None => { + self.audio_ref = Some(secs); + self.audio_last = secs; + } + Some(_) if secs > self.audio_last => self.audio_last = secs, + Some(_) => {} + } + } + + /// Makes `base` the current position and drops both source references, so + /// the next wall tick or audio report continues from there. + fn reanchor(&mut self, secs: f64) { + self.base = secs; + self.anchor = Instant::now(); + self.audio_ref = None; + self.audio_last = 0.0; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::thread::sleep; + use std::time::Duration; + + const RATE: u32 = 48_000; + + /// The app moves the clock between threads/closures. + fn _assert_send() {} + const _: fn() = || _assert_send::(); + + fn audio_playing() -> PlaybackClock { + let mut c = PlaybackClock::new(ClockSource::Audio); + c.play(); + c + } + + #[test] + fn audio_follows_reports_exactly() { + let mut c = audio_playing(); + assert_eq!(c.now(), 0.0); + c.set_audio_position(0, RATE); // first report sets the reference + assert_eq!(c.now(), 0.0); + c.set_audio_position(48_000, RATE); + assert_eq!(c.now(), 1.0); + c.set_audio_position(72_000, RATE); + assert_eq!(c.now(), 1.5); + } + + #[test] + fn audio_reference_is_relative_not_absolute() { + // A stream already 10 s in still starts this clock's timeline at 0. + let mut c = audio_playing(); + c.set_audio_position(480_000, RATE); + assert_eq!(c.now(), 0.0); + c.set_audio_position(504_000, RATE); + assert_eq!(c.now(), 0.5); + } + + #[test] + fn audio_regression_clamps() { + let mut c = audio_playing(); + c.set_audio_position(0, RATE); + c.set_audio_position(96_000, RATE); + assert_eq!(c.now(), 2.0); + c.set_audio_position(24_000, RATE); // device reset + assert_eq!(c.now(), 2.0, "clock must not rewind"); + c.set_audio_position(0, RATE); + assert_eq!(c.now(), 2.0); + c.set_audio_position(120_000, RATE); // recovered, forward again + assert_eq!(c.now(), 2.5); + } + + #[test] + fn zero_sample_rate_ignored() { + let mut c = audio_playing(); + c.set_audio_position(1_000, 0); + assert_eq!(c.now(), 0.0); + } + + #[test] + fn pause_freezes_and_play_resumes() { + let mut c = audio_playing(); + c.set_audio_position(0, RATE); + c.set_audio_position(48_000, RATE); + c.pause(); + assert!(!c.is_playing()); + assert_eq!(c.now(), 1.0); + // Audio keeps running for a moment after a pause request; ignored. + c.set_audio_position(60_000, RATE); + assert_eq!(c.now(), 1.0); + c.play(); + assert_eq!(c.now(), 1.0, "no time gained across the pause"); + c.set_audio_position(72_000, RATE); // stream restarted mid-buffer + assert_eq!(c.now(), 1.0); + c.set_audio_position(96_000, RATE); + assert_eq!(c.now(), 1.5); + } + + #[test] + fn wall_advances_with_real_time() { + let mut c = PlaybackClock::new(ClockSource::Wall); + c.play(); + sleep(Duration::from_millis(120)); + let t = c.now(); + assert!((0.05..0.60).contains(&t), "wall clock at {t}"); + c.pause(); + let frozen = c.now(); + sleep(Duration::from_millis(120)); + assert_eq!(c.now(), frozen, "paused wall clock must not move"); + c.play(); + assert!(c.now() - frozen < 0.05); + sleep(Duration::from_millis(120)); + assert!(c.now() > frozen + 0.05); + } + + #[test] + fn switch_to_wall_is_continuous() { + let mut c = audio_playing(); + c.set_audio_position(0, RATE); + c.set_audio_position(96_000, RATE); + let x = c.now(); + c.switch_to_wall(); + assert_eq!(c.source(), ClockSource::Wall); + assert!((c.now() - x).abs() < 0.01, "jumped from {x} to {}", c.now()); + sleep(Duration::from_millis(120)); + assert!(c.now() > x + 0.05, "wall clock did not take over"); + } + + #[test] + fn switch_to_audio_is_continuous() { + let mut c = PlaybackClock::new(ClockSource::Wall); + c.play(); + sleep(Duration::from_millis(50)); + let before = c.now(); + c.switch_to_audio(); + let x = c.now(); + assert!((x - before).abs() < 0.01, "jumped from {before} to {x}"); + assert_eq!(c.now(), x, "audio mode holds until the first report"); + c.set_audio_position(240_000, RATE); + assert_eq!(c.now(), x); + c.set_audio_position(264_000, RATE); + assert_eq!(c.now(), x + 0.5); + } + + #[test] + fn seek_while_paused() { + let mut c = PlaybackClock::new(ClockSource::Wall); + c.seek_to(12.0); + assert_eq!(c.now(), 12.0); + sleep(Duration::from_millis(50)); + assert_eq!(c.now(), 12.0, "seek must not start the clock"); + c.play(); + sleep(Duration::from_millis(120)); + let t = c.now(); + assert!((12.05..12.60).contains(&t), "resumed at {t}"); + } + + #[test] + fn seek_while_playing_audio() { + let mut c = audio_playing(); + c.set_audio_position(0, RATE); + c.set_audio_position(48_000, RATE); + c.seek_to(30.0); + assert_eq!(c.now(), 30.0); + // The app restarts the stream, so the counter comes back from zero. + c.set_audio_position(0, RATE); + assert_eq!(c.now(), 30.0); + c.set_audio_position(24_000, RATE); + assert_eq!(c.now(), 30.5); + assert!(c.is_playing()); + } + + #[test] + fn seek_while_playing_wall() { + let mut c = PlaybackClock::new(ClockSource::Wall); + c.play(); + sleep(Duration::from_millis(50)); + c.seek_to(5.0); + assert!((c.now() - 5.0).abs() < 0.01); + sleep(Duration::from_millis(120)); + assert!(c.now() > 5.05); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7469199..0f5e45f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,10 +1,15 @@ //! Video engine: demux -> decode -> pixel convert. No UI dependencies. +pub mod ao; +pub mod audio; +pub mod clock; pub mod convert; pub mod decode; pub mod demux; pub mod hw; +pub use audio::{AudioChunk, AudioMeta, AudioSession}; +pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; diff --git a/crates/engine/tests/ao_output.rs b/crates/engine/tests/ao_output.rs new file mode 100644 index 0000000..d8673b3 --- /dev/null +++ b/crates/engine/tests/ao_output.rs @@ -0,0 +1,103 @@ +//! Audio output checks. These need a built `libengine_audio.so` plus a running +//! PipeWire daemon, so they are `#[ignore]`d by default. Run them with: +//! +//! ```text +//! cargo build --workspace --release +//! cargo test -p engine --release --test ao_output -- --ignored --nocapture --test-threads=1 +//! ``` +//! +//! `no_daemon_opens_nothing` sets `PIPEWIRE_REMOTE` in-process, hence the +//! required `--test-threads=1`; it restores the environment before asserting. + +use std::f32::consts::TAU; +use std::time::{Duration, Instant}; + +use engine::ao::AoSession; + +const RATE: u32 = 44100; +const CHANNELS: u32 = 2; + +/// Half a second of a quiet 440 Hz tone, interleaved stereo. +fn tone() -> Vec { + let frames = RATE as usize / 2; + let mut samples = Vec::with_capacity(frames * CHANNELS as usize); + for i in 0..frames { + let value = (i as f32 * TAU * 440.0 / RATE as f32).sin() * 0.2; + samples.extend([value; CHANNELS as usize]); + } + samples +} + +/// Waits up to `limit` for the clock to report a played position past zero. +fn wait_for_playback(ao: &AoSession, limit: Duration) -> i64 { + let start = Instant::now(); + loop { + if let Some(position) = ao.position() { + if position > 0 { + return position; + } + } + assert!(start.elapsed() < limit, "playback position never advanced"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +#[ignore = "needs libengine_audio.so and a PipeWire daemon"] +fn plays_and_tracks_position() { + assert!(AoSession::probe(), "plugin not loadable"); + let mut ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available"); + + // The ring holds a second, so two halves go in whole -- enough real audio + // to cover the measurement below without starving. + let samples = tone(); + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + + // Over 400 ms the clock must run at the rate we asked for, not at the + // device's: the plugin converts PipeWire's ticks out of the graph rate. + let first = wait_for_playback(&ao, Duration::from_secs(2)); + std::thread::sleep(Duration::from_millis(400)); + let second = ao.position().expect("position went unknown"); + let advanced = second - first; + let expected = RATE as i64 * 400 / 1000; + eprintln!("clock advanced {advanced} samples in 400 ms (expected ~{expected})"); + assert!( + (advanced - expected).abs() < expected / 10, + "clock runs at the wrong rate: {advanced} samples in 400 ms" + ); + + // Paused means the device plays nothing, so the master clock must not move. + assert!(ao.set_active(false), "pause rejected"); + std::thread::sleep(Duration::from_millis(150)); + let paused = ao.position().expect("position went unknown"); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!( + ao.position(), + Some(paused), + "position moved while paused: {paused}" + ); + + ao.write(&samples).expect("write after pause"); + assert!(ao.set_active(true), "resume rejected"); + std::thread::sleep(Duration::from_millis(200)); + let resumed = ao.position().expect("position went unknown"); + assert!(resumed > paused, "clock did not resume: {paused} -> {resumed}"); +} + +/// No reachable daemon must fail the open cleanly and quickly, never hang. +#[test] +#[ignore = "needs libengine_audio.so and a PipeWire daemon"] +fn no_daemon_opens_nothing() { + assert!(AoSession::probe(), "plugin not loadable"); + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("PIPEWIRE_REMOTE", "/nonexistent") }; + let start = Instant::now(); + let session = AoSession::open(RATE, CHANNELS); + let elapsed = start.elapsed(); + unsafe { std::env::remove_var("PIPEWIRE_REMOTE") }; + + assert!(session.is_none(), "opened a stream with no daemon"); + assert!(elapsed < Duration::from_secs(2), "open took {elapsed:?}"); + eprintln!("open with no daemon failed in {elapsed:?}"); +} diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs new file mode 100644 index 0000000..bcdeae1 --- /dev/null +++ b/crates/engine/tests/audio_decode.rs @@ -0,0 +1,102 @@ +use std::path::PathBuf; +use std::time::Instant; + +use engine::audio::AudioSession; + +const RATE: u32 = 44100; +const SECONDS: u32 = 5; +/// One AAC-LC packet; the container's tail padding is not trimmed, so the +/// decoded length may run up to a frame past the nominal duration. +const FRAME: i64 = 1024; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Sign changes ignoring exact zeros, so the 1 Hz volume pulse touching zero +/// does not register as a crossing. +fn zero_crossings(samples: &[f32]) -> usize { + let mut crossings = 0; + let mut last = 0f32; + for &s in samples { + if s == 0.0 { + continue; + } + if last != 0.0 && (s > 0.0) != (last > 0.0) { + crossings += 1; + } + last = s; + } + crossings +} + +#[test] +fn decodes_av_mp4_audio() { + let start = Instant::now(); + let (meta, rx) = AudioSession::open(asset("test_av.mp4")) + .expect("open") + .expect("test_av.mp4 has an audio track"); + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2)); + + let mut left = Vec::new(); + let mut right = Vec::new(); + let mut next_sample = 0u64; + let mut chunks = 0usize; + for chunk in rx { + // d. no gaps, no overlaps. + assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start"); + assert!(!chunk.samples.is_empty(), "empty chunk {chunks}"); + assert_eq!(chunk.samples.len() % 2, 0, "partial frame in chunk {chunks}"); + next_sample += (chunk.samples.len() / 2) as u64; + left.extend(chunk.samples.iter().step_by(2)); + right.extend(chunk.samples[1..].iter().step_by(2)); + chunks += 1; + } + let elapsed = start.elapsed(); + let frames = left.len(); + assert!(frames > 0, "no audio decoded"); + + // b. ~5 s of audio, priming trimmed, at most a frame of tail padding over. + let want = (RATE * SECONDS) as i64; + let slack = frames as i64 - want; + assert!( + (0..=FRAME).contains(&slack), + "{frames} frames per channel, want {want} (+0..={FRAME})" + ); + assert_eq!(right.len(), frames, "channel lengths differ"); + + // c. channel identity: L is 440 Hz, R is 880 Hz. A swap or a bad interleave + // shows up as the wrong crossing count. + let secs = frames as f64 / RATE as f64; + for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] { + let want = 2.0 * hz * secs; + let got = zero_crossings(samples) as f64; + assert!( + (got - want).abs() <= 0.05 * want, + "{name}: {got} zero crossings, want {want} +/-5%" + ); + } + + // Priming trimmed: the sine starts at a rising zero crossing, and audio is + // present immediately rather than after a silent or garbage run-in. + assert!(left[0].abs() < 0.05, "first sample {} not near zero", left[0]); + assert!(left[1] > 0.0, "first sine quarter is not rising"); + let head_peak = left[..FRAME as usize].iter().fold(0f32, |m, s| m.max(s.abs())); + assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}"); + + eprintln!( + "{frames} frames/ch in {chunks} chunks, {elapsed:?} ({:?}/packet)", + elapsed / chunks as u32 + ); +} + +#[test] +fn video_only_file_has_no_audio() { + assert!( + AudioSession::open(asset("test_baseline.mp4")) + .expect("open") + .is_none() + ); +}