forge
Explore
Log in

Don't you dare go Hollow

Audio decode, PipeWire output plugin, playback clock

Browse files at this commit

229a56987fe85b84bacf64c74c9c32675bff3f4aAhmet Kaan GümüşParent: fc06b75
  • feat
    • audio decode, PipeWire output plugin, playback clock
Show full message
✨ feat(engine): audio decode, PipeWire output plugin, playback clock

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.lockmodified+195 -0
@@ -60,6 +60,22 @@ dependencies = [
60 "equator",60 "equator",
61 ]61 ]
62 62
63+[[package]]
64+name = "annotate-snippets"
65+version = "0.11.5"
66+source = "registry+https://github.com/rust-lang/crates.io-index"
67+checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4"
68+dependencies = [
69+ "anstyle",
70+ "unicode-width",
71+]
72+
73+[[package]]
74+name = "anstyle"
75+version = "1.0.14"
76+source = "registry+https://github.com/rust-lang/crates.io-index"
77+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
78+
63 [[package]]79 [[package]]
64 name = "anyhow"80 name = "anyhow"
65 version = "1.0.104"81 version = "1.0.104"
@@ -525,6 +541,25 @@ dependencies = [
525 "syn 2.0.119",541 "syn 2.0.119",
526 ]542 ]
527 543
544+[[package]]
545+name = "bindgen"
546+version = "0.72.1"
547+source = "registry+https://github.com/rust-lang/crates.io-index"
548+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
549+dependencies = [
550+ "annotate-snippets",
551+ "bitflags 2.13.1",
552+ "cexpr",
553+ "clang-sys",
554+ "itertools 0.13.0",
555+ "proc-macro2",
556+ "quote",
557+ "regex",
558+ "rustc-hash 2.1.3",
559+ "shlex 1.3.0",
560+ "syn 2.0.119",
561+]
562+
528 [[package]]563 [[package]]
529 name = "bit-set"564 name = "bit-set"
530 version = "0.8.0"565 version = "0.8.0"
@@ -814,6 +849,16 @@ dependencies = [
814 "nom 7.1.3",849 "nom 7.1.3",
815 ]850 ]
816 851
852+[[package]]
853+name = "cfg-expr"
854+version = "0.20.8"
855+source = "registry+https://github.com/rust-lang/crates.io-index"
856+checksum = "fb693542bcafa528e198be0ebd9d3632ca5b7c93dbe7237460e199910835997c"
857+dependencies = [
858+ "smallvec",
859+ "target-lexicon",
860+]
861+
817 [[package]]862 [[package]]
818 name = "cfg-if"863 name = "cfg-if"
819 version = "1.0.4"864 version = "1.0.4"
@@ -1020,6 +1065,12 @@ version = "0.4.0"
1020 source = "registry+https://github.com/rust-lang/crates.io-index"1065 source = "registry+https://github.com/rust-lang/crates.io-index"
1021 checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"1066 checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
1022 1067
1068+[[package]]
1069+name = "cookie-factory"
1070+version = "0.3.3"
1071+source = "registry+https://github.com/rust-lang/crates.io-index"
1072+checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2"
1073+
1023 [[package]]1074 [[package]]
1024 name = "core-foundation"1075 name = "core-foundation"
1025 version = "0.9.4"1076 version = "0.9.4"
@@ -1561,6 +1612,17 @@ dependencies = [
1561 "libloading",1612 "libloading",
1562 "mp4",1613 "mp4",
1563 "rusty_h264",1614 "rusty_h264",
1615+ "symphonia-codec-aac",
1616+ "symphonia-core",
1617+]
1618+
1619+[[package]]
1620+name = "engine-audio"
1621+version = "0.1.0"
1622+dependencies = [
1623+ "engine",
1624+ "libspa-sys",
1625+ "pipewire",
1564 ]1626 ]
1565 1627
1566 [[package]]1628 [[package]]
@@ -3067,6 +3129,33 @@ dependencies = [
3067 "libc",3129 "libc",
3068 ]3130 ]
3069 3131
3132+[[package]]
3133+name = "libspa"
3134+version = "0.10.0"
3135+source = "registry+https://github.com/rust-lang/crates.io-index"
3136+checksum = "2909f3be29d674e7f10604aff18d1bbe1bb03c4cd61c8a8ba19c0b1d162f7d4e"
3137+dependencies = [
3138+ "bitflags 2.13.1",
3139+ "cc",
3140+ "cookie-factory",
3141+ "libc",
3142+ "libspa-sys",
3143+ "nom 8.0.0",
3144+ "rustix 1.1.4",
3145+ "system-deps",
3146+]
3147+
3148+[[package]]
3149+name = "libspa-sys"
3150+version = "0.10.0"
3151+source = "registry+https://github.com/rust-lang/crates.io-index"
3152+checksum = "69ad52764fca54818486f3cf75afec844d1f1a1568c24dcee25d41b1ab007dda"
3153+dependencies = [
3154+ "bindgen 0.72.1",
3155+ "cc",
3156+ "system-deps",
3157+]
3158+
3070 [[package]]3159 [[package]]
3071 name = "linux-raw-sys"3160 name = "linux-raw-sys"
3072 version = "0.4.15"3161 version = "0.4.15"
@@ -3890,6 +3979,31 @@ dependencies = [
3890 "futures-io",3979 "futures-io",
3891 ]3980 ]
3892 3981
3982+[[package]]
3983+name = "pipewire"
3984+version = "0.10.0"
3985+source = "registry+https://github.com/rust-lang/crates.io-index"
3986+checksum = "8585aba8a52ad74ccc633b8e293c1dc4277976bd5d510b925533f34fd6685f38"
3987+dependencies = [
3988+ "bitflags 2.13.1",
3989+ "libc",
3990+ "libspa",
3991+ "libspa-sys",
3992+ "pipewire-sys",
3993+ "rustix 1.1.4",
3994+]
3995+
3996+[[package]]
3997+name = "pipewire-sys"
3998+version = "0.10.0"
3999+source = "registry+https://github.com/rust-lang/crates.io-index"
4000+checksum = "f2089f245b548723e60325773c27f586b7a2372c79ea941b246cd0d654706adc"
4001+dependencies = [
4002+ "bindgen 0.72.1",
4003+ "libspa-sys",
4004+ "system-deps",
4005+]
4006+
3893 [[package]]4007 [[package]]
3894 name = "pkg-config"4008 name = "pkg-config"
3895 version = "0.3.33"4009 version = "0.3.33"
@@ -4472,6 +4586,12 @@ dependencies = [
4472 "regex-syntax",4586 "regex-syntax",
4473 ]4587 ]
4474 4588
4589+[[package]]
4590+name = "regex-lite"
4591+version = "0.1.9"
4592+source = "registry+https://github.com/rust-lang/crates.io-index"
4593+checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
4594+
4475 [[package]]4595 [[package]]
4476 name = "regex-syntax"4596 name = "regex-syntax"
4477 version = "0.8.11"4597 version = "0.8.11"
@@ -5365,6 +5485,56 @@ dependencies = [
5365 "zeno",5485 "zeno",
5366 ]5486 ]
5367 5487
5488+[[package]]
5489+name = "symphonia-codec-aac"
5490+version = "0.6.0"
5491+source = "registry+https://github.com/rust-lang/crates.io-index"
5492+checksum = "f1979c515a76371b186aad2feff5f23e21cbec775bf95de08bf1e3af92a2ad76"
5493+dependencies = [
5494+ "lazy_static",
5495+ "log",
5496+ "symphonia-common",
5497+ "symphonia-core",
5498+]
5499+
5500+[[package]]
5501+name = "symphonia-common"
5502+version = "0.6.0"
5503+source = "registry+https://github.com/rust-lang/crates.io-index"
5504+checksum = "8257891ffa7f05e02b58f4761e2abf7e5278c8744fd59e981559e050f86eef55"
5505+dependencies = [
5506+ "log",
5507+ "symphonia-core",
5508+ "symphonia-metadata",
5509+]
5510+
5511+[[package]]
5512+name = "symphonia-core"
5513+version = "0.6.0"
5514+source = "registry+https://github.com/rust-lang/crates.io-index"
5515+checksum = "95ec293b5f288383b72a7bffcade6b2860b642cf66f28b3bd5967349a49938b1"
5516+dependencies = [
5517+ "bitflags 2.13.1",
5518+ "bytemuck",
5519+ "lazy_static",
5520+ "log",
5521+ "num-complex",
5522+ "smallvec",
5523+]
5524+
5525+[[package]]
5526+name = "symphonia-metadata"
5527+version = "0.6.0"
5528+source = "registry+https://github.com/rust-lang/crates.io-index"
5529+checksum = "a31acf5cd623398a6208e2225d18f4b20f761c55098a796a5247ad516a4a8681"
5530+dependencies = [
5531+ "lazy_static",
5532+ "log",
5533+ "regex-lite",
5534+ "smallvec",
5535+ "symphonia-core",
5536+]
5537+
5368 [[package]]5538 [[package]]
5369 name = "syn"5539 name = "syn"
5370 version = "1.0.109"5540 version = "1.0.109"
@@ -5462,6 +5632,19 @@ dependencies = [
5462 "libc",5632 "libc",
5463 ]5633 ]
5464 5634
5635+[[package]]
5636+name = "system-deps"
5637+version = "7.0.8"
5638+source = "registry+https://github.com/rust-lang/crates.io-index"
5639+checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"
5640+dependencies = [
5641+ "cfg-expr",
5642+ "heck 0.5.0",
5643+ "pkg-config",
5644+ "toml 1.1.4+spec-1.1.0",
5645+ "version-compare",
5646+]
5647+
5465 [[package]]5648 [[package]]
5466 name = "taffy"5649 name = "taffy"
5467 version = "0.9.0"5650 version = "0.9.0"
@@ -5492,6 +5675,12 @@ dependencies = [
5492 "objc",5675 "objc",
5493 ]5676 ]
5494 5677
5678+[[package]]
5679+name = "target-lexicon"
5680+version = "0.13.5"
5681+source = "registry+https://github.com/rust-lang/crates.io-index"
5682+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
5683+
5495 [[package]]5684 [[package]]
5496 name = "tempfile"5685 name = "tempfile"
5497 version = "3.27.0"5686 version = "3.27.0"
@@ -6085,6 +6274,12 @@ dependencies = [
6085 "sval_serde",6274 "sval_serde",
6086 ]6275 ]
6087 6276
6277+[[package]]
6278+name = "version-compare"
6279+version = "0.2.1"
6280+source = "registry+https://github.com/rust-lang/crates.io-index"
6281+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
6282+
6088 [[package]]6283 [[package]]
6089 name = "version_check"6284 name = "version_check"
6090 version = "0.9.5"6285 version = "0.9.5"
Cargo.tomlmodified+1 -1
@@ -1,6 +1,6 @@
1 [workspace]1 [workspace]
2 resolver = "3"2 resolver = "3"
3-members = ["crates/engine", "crates/engine-hw", "crates/app"]3+members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"]
4 # Vendored third-party (see [patch.crates-io]); not ours to build or test.4 # Vendored third-party (see [patch.crates-io]); not ours to build or test.
5 exclude = ["vendor/cros-libva", "vendor/cros-codecs"]5 exclude = ["vendor/cros-libva", "vendor/cros-codecs"]
6 6
crates/engine-audio/Cargo.tomladded+15 -0
@@ -0,0 +1,15 @@
1+[package]
2+name = "engine-audio"
3+version = "0.1.0"
4+edition = "2024"
5+
6+# PipeWire audio output plugin. Dynamically loaded at runtime (dlopen) so the
7+# main binary never gains a DT_NEEDED on libpipewire — PipeWire missing at
8+# runtime means the app runs muted, never that it fails to start.
9+[lib]
10+crate-type = ["cdylib"]
11+
12+[dependencies]
13+engine = { path = "../engine" }
14+pipewire = "0.10"
15+libspa-sys = "0.10"
crates/engine-audio/src/lib.rsadded+455 -0
@@ -0,0 +1,455 @@
1+//! PipeWire playback, shipped as a `dlopen`-able plugin so the main binary
2+//! never gets a DT_NEEDED on libpipewire. Every entry point is `extern "C"`,
3+//! catches unwinds and reports failure as a null pointer or a negative code:
4+//! the caller's contract is "any failure means the app runs muted".
5+//!
6+//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with
7+//! `panic = "abort"` would turn a PipeWire bug into a killed app; the upgrade
8+//! path is running the output in a child process instead of in-process.
9+
10+use std::ffi::c_void;
11+use std::panic::{AssertUnwindSafe, catch_unwind};
12+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering};
13+use std::sync::{Arc, OnceLock, mpsc};
14+use std::thread::JoinHandle;
15+use std::time::{Duration, Instant};
16+
17+use pipewire as pw;
18+use pw::{properties::properties, spa};
19+use spa::pod::Pod;
20+
21+/// How long the loop thread waits for the daemon to accept the stream before
22+/// the open counts as failed. Negotiation is a couple of graph cycles when it
23+/// works at all, so this only ever fires on a broken setup.
24+const READY_TIMEOUT: Duration = Duration::from_secs(1);
25+/// Belt and braces around the whole open: no PipeWire call on this path is
26+/// supposed to block, but `ao_open` must never hang the caller.
27+const OPEN_TIMEOUT: Duration = Duration::from_secs(2);
28+/// Loop iteration timeout on the audio thread; also the worst-case latency of
29+/// an `ao_set_active` taking effect.
30+const POLL: Duration = Duration::from_millis(10);
31+/// Frames we hand over per callback, and the latency we ask the graph for.
32+/// Left to itself PipeWire gives us a buffer the size of the sink's (measured:
33+/// 12288 frames, 256 ms) and calls us once per buffer, so the position clock --
34+/// which only moves in the callback -- would step 256 ms at a time and land
35+/// that coarseness straight in the A/V sync. 1024 frames is ~23 ms, comfortably
36+/// inside a video frame; measured granularity is then one graph quantum.
37+///
38+/// ponytail: a graph running a quantum longer than this would consume more per
39+/// cycle than we deliver and starve. The fix is the crate's `v0_3_49` feature,
40+/// whose `pw_buffer.requested` says exactly how many frames the graph wants --
41+/// a Cargo.toml change, so not this slice.
42+const QUANTUM: u32 = 1024;
43+
44+/// Lock-free SPSC ring of f32 samples (interleaved, one producer: `ao_write`,
45+/// one consumer: the RT process callback). Samples live in atomics rather than
46+/// behind a lock so the RT thread never waits on the decoder thread.
47+struct Ring {
48+ /// Power-of-two length, so the monotonic counters below can be masked and
49+ /// still index correctly across a `usize` wrap.
50+ slots: Box<[AtomicU32]>,
51+ write: AtomicUsize,
52+ read: AtomicUsize,
53+}
54+
55+impl Ring {
56+ fn new(capacity: usize) -> Self {
57+ let len = capacity.next_power_of_two();
58+ Self {
59+ slots: (0..len).map(|_| AtomicU32::new(0)).collect(),
60+ write: AtomicUsize::new(0),
61+ read: AtomicUsize::new(0),
62+ }
63+ }
64+
65+ /// Appends as much of `src` as fits, returning how many samples were taken.
66+ fn push(&self, src: &[f32]) -> usize {
67+ let write = self.write.load(Ordering::Relaxed);
68+ let used = write.wrapping_sub(self.read.load(Ordering::Acquire));
69+ let n = src.len().min(self.slots.len() - used);
70+ let mask = self.slots.len() - 1;
71+ for (i, sample) in src[..n].iter().enumerate() {
72+ self.slots[write.wrapping_add(i) & mask].store(sample.to_bits(), Ordering::Relaxed);
73+ }
74+ self.write.store(write.wrapping_add(n), Ordering::Release);
75+ n
76+ }
77+
78+ /// Pops up to `want` samples as little-endian f32 into `dst`, returning how
79+ /// many were available. `dst` must hold `want * 4` bytes.
80+ fn pop(&self, dst: &mut [u8], want: usize) -> usize {
81+ let read = self.read.load(Ordering::Relaxed);
82+ let avail = self.write.load(Ordering::Acquire).wrapping_sub(read);
83+ let n = want.min(avail);
84+ let mask = self.slots.len() - 1;
85+ for i in 0..n {
86+ let bits = self.slots[read.wrapping_add(i) & mask].load(Ordering::Relaxed);
87+ dst[i * 4..i * 4 + 4].copy_from_slice(&bits.to_le_bytes());
88+ }
89+ self.read.store(read.wrapping_add(n), Ordering::Release);
90+ n
91+ }
92+}
93+
94+/// Everything the RT thread and the caller's thread both touch.
95+struct Shared {
96+ ring: Ring,
97+ /// Samples per channel played at the device, -1 until the first callback.
98+ position: AtomicI64,
99+ /// Set once the daemon has accepted the stream.
100+ ready: AtomicBool,
101+ /// Stream died (daemon gone, node removed); every later write fails.
102+ dead: AtomicBool,
103+ underruns: AtomicU64,
104+}
105+
106+enum Ctl {
107+ Active(bool),
108+ Quit,
109+}
110+
111+fn pw_init() {
112+ // Refcounted inside libpipewire, but a plugin has no safe point to call
113+ // `pw::deinit`, so we init exactly once and never tear down.
114+ static INIT: OnceLock<()> = OnceLock::new();
115+ INIT.get_or_init(pw::init);
116+}
117+
118+/// Builds the stream, reports readiness through `ready`, then owns the PipeWire
119+/// loop until told to quit. Everything PipeWire lives in this one frame: the
120+/// smart pointers are `Rc`-flavoured and the borrow chain (listener -> stream ->
121+/// core -> context -> loop) is what enforces the destruction order.
122+fn run(
123+ rate: u32,
124+ channels: usize,
125+ shared: Arc<Shared>,
126+ ready: mpsc::Sender<()>,
127+ ctl: mpsc::Receiver<Ctl>,
128+) -> Result<(), pw::Error> {
129+ pw_init();
130+ let mainloop = pw::main_loop::MainLoopRc::new(None)?;
131+ let context = pw::context::ContextRc::new(&mainloop, None)?;
132+ // Fails synchronously when there is no daemon to talk to: the clean probe.
133+ let core = context.connect_rc(None)?;
134+
135+ let stream = pw::stream::StreamBox::new(
136+ &core,
137+ "video-editor",
138+ properties! {
139+ *pw::keys::MEDIA_TYPE => "Audio",
140+ *pw::keys::MEDIA_CATEGORY => "Playback",
141+ *pw::keys::MEDIA_ROLE => "Movie",
142+ *pw::keys::AUDIO_CHANNELS => channels.to_string(),
143+ // Asks the graph to schedule us at our own quantum, which is what
144+ // keeps the fill below from under-delivering on a lazy sink.
145+ *pw::keys::NODE_LATENCY => format!("{QUANTUM}/{rate}"),
146+ },
147+ )?;
148+
149+ let _listener = stream
150+ .add_local_listener_with_user_data(())
151+ .state_changed({
152+ let shared = shared.clone();
153+ move |_, (), _old, new| match new {
154+ pw::stream::StreamState::Paused | pw::stream::StreamState::Streaming => {
155+ shared.ready.store(true, Ordering::Relaxed)
156+ }
157+ pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected => {
158+ shared.dead.store(true, Ordering::Relaxed)
159+ }
160+ pw::stream::StreamState::Connecting => {}
161+ }
162+ })
163+ .process({
164+ let shared = shared.clone();
165+ let stride = 4 * channels;
166+ move |stream, ()| {
167+ let Some(mut buffer) = stream.dequeue_buffer() else {
168+ return;
169+ };
170+ let datas = buffer.datas_mut();
171+ let Some(data) = datas.first_mut() else {
172+ return;
173+ };
174+ let n_frames = match data.data() {
175+ Some(slice) => {
176+ // Only a quantum per callback, however big the buffer
177+ // is: everything we queue here is latency the clock,
178+ // the pause and a future seek all have to wait out.
179+ let frames = (slice.len() / stride).min(QUANTUM as usize);
180+ let want = frames * channels;
181+ let got = shared.ring.pop(slice, want);
182+ if got < want {
183+ // Underrun: silence rather than stale samples, and
184+ // the clock below keeps running -- the device plays
185+ // that silence, so it really is elapsed time.
186+ slice[got * 4..want * 4].fill(0);
187+ shared.underruns.fetch_add(1, Ordering::Relaxed);
188+ }
189+ frames
190+ }
191+ None => 0,
192+ };
193+ let chunk = data.chunk_mut();
194+ *chunk.offset_mut() = 0;
195+ *chunk.stride_mut() = stride as _;
196+ *chunk.size_mut() = (stride * n_frames) as _;
197+
198+ // The A/V master clock: what the device has actually played,
199+ // which is the stream position minus everything still in flight.
200+ if let Ok(time) = stream.time() {
201+ let ticks = time.ticks() as i64 - time.delay();
202+ let (num, denom) = (time.rate().num as i128, time.rate().denom as i128);
203+ // `ticks` counts in the stream's own rate; convert to ours.
204+ let played = if denom > 0 {
205+ (ticks as i128 * num * rate as i128 / denom) as i64
206+ } else {
207+ ticks
208+ };
209+ shared.position.store(played.max(0), Ordering::Relaxed);
210+ }
211+ }
212+ })
213+ .register()?;
214+
215+ let mut audio_info = spa::param::audio::AudioInfoRaw::new();
216+ audio_info.set_format(spa::param::audio::AudioFormat::F32LE);
217+ audio_info.set_rate(rate);
218+ audio_info.set_channels(channels as u32);
219+ let mut position = [0; spa::param::audio::MAX_CHANNELS];
220+ match channels {
221+ 1 => position[0] = libspa_sys::SPA_AUDIO_CHANNEL_MONO,
222+ 2 => {
223+ position[0] = libspa_sys::SPA_AUDIO_CHANNEL_FL;
224+ position[1] = libspa_sys::SPA_AUDIO_CHANNEL_FR;
225+ }
226+ // Anything else keeps UNKNOWN positions and lets the daemon map them.
227+ _ => {}
228+ }
229+ audio_info.set_position(position);
230+
231+ let values: Vec<u8> = pw::spa::pod::serialize::PodSerializer::serialize(
232+ std::io::Cursor::new(Vec::new()),
233+ &pw::spa::pod::Value::Object(pw::spa::pod::Object {
234+ type_: libspa_sys::SPA_TYPE_OBJECT_Format,
235+ id: libspa_sys::SPA_PARAM_EnumFormat,
236+ properties: audio_info.into(),
237+ }),
238+ )
239+ .map_err(|_| pw::Error::CreationFailed)?
240+ .0
241+ .into_inner();
242+ let mut params = [Pod::from_bytes(&values).ok_or(pw::Error::CreationFailed)?];
243+
244+ stream.connect(
245+ spa::utils::Direction::Output,
246+ None,
247+ pw::stream::StreamFlags::AUTOCONNECT
248+ | pw::stream::StreamFlags::MAP_BUFFERS
249+ | pw::stream::StreamFlags::RT_PROCESS,
250+ &mut params,
251+ )?;
252+
253+ // `connect` only starts negotiation, so a bad format or a daemon that
254+ // refuses us still shows up here rather than as silent nothing later.
255+ let deadline = Instant::now() + READY_TIMEOUT;
256+ while !shared.ready.load(Ordering::Relaxed) {
257+ if shared.dead.load(Ordering::Relaxed) || Instant::now() >= deadline {
258+ return Err(pw::Error::CreationFailed);
259+ }
260+ mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL));
261+ }
262+ let _ = ready.send(());
263+
264+ // Driving the loop by hand instead of `mainloop.run()` + a PipeWire channel:
265+ // loop callbacks must be `'static` and the stream borrows the core, so a
266+ // callback cannot touch the stream. Iterating lets us call `set_active` from
267+ // this very frame. With RT_PROCESS the audio callback runs on the RT thread
268+ // regardless, so this loop only handles negotiation and control.
269+ 'run: loop {
270+ mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL));
271+ loop {
272+ match ctl.try_recv() {
273+ Ok(Ctl::Active(active)) => {
274+ let _ = stream.set_active(active);
275+ }
276+ // Disconnected means the session was dropped without a Quit.
277+ Ok(Ctl::Quit) | Err(mpsc::TryRecvError::Disconnected) => break 'run,
278+ Err(mpsc::TryRecvError::Empty) => break,
279+ }
280+ }
281+ }
282+ let _ = stream.disconnect();
283+ Ok(())
284+}
285+
286+struct Session {
287+ shared: Arc<Shared>,
288+ ctl: mpsc::Sender<Ctl>,
289+ thread: Option<JoinHandle<()>>,
290+}
291+
292+impl Drop for Session {
293+ fn drop(&mut self) {
294+ let _ = self.ctl.send(Ctl::Quit);
295+ if let Some(thread) = self.thread.take() {
296+ let _ = thread.join();
297+ }
298+ let underruns = self.shared.underruns.load(Ordering::Relaxed);
299+ if underruns > 0 {
300+ eprintln!("engine_audio: {underruns} underruns");
301+ }
302+ }
303+}
304+
305+/// Opens a playback stream for `sample_rate` Hz, `channels` channels of
306+/// interleaved f32. Returns null on any failure at all: no libpipewire, no
307+/// daemon, an unusable format.
308+#[unsafe(no_mangle)]
309+pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
310+ catch_unwind(AssertUnwindSafe(|| {
311+ if !(8_000..=768_000).contains(&sample_rate)
312+ || channels == 0
313+ || channels as usize > spa::param::audio::MAX_CHANNELS
314+ {
315+ return std::ptr::null_mut();
316+ }
317+ pw_init();
318+
319+ let shared = Arc::new(Shared {
320+ // One second of audio: enough that a stalled decoder is audible as
321+ // an underrun rather than papered over by a huge buffer.
322+ ring: Ring::new(sample_rate as usize * channels as usize),
323+ position: AtomicI64::new(-1),
324+ ready: AtomicBool::new(false),
325+ dead: AtomicBool::new(false),
326+ underruns: AtomicU64::new(0),
327+ });
328+ let (ready_tx, ready_rx) = mpsc::channel();
329+ let (ctl_tx, ctl_rx) = mpsc::channel();
330+ let thread = std::thread::spawn({
331+ let shared = shared.clone();
332+ move || {
333+ if let Err(e) = run(sample_rate, channels as usize, shared, ready_tx, ctl_rx) {
334+ eprintln!("engine_audio: {e}");
335+ }
336+ }
337+ });
338+
339+ // A failed setup drops `ready_tx`, so this returns without waiting out
340+ // the timeout; the timeout only covers a PipeWire call that blocks
341+ // against its contract, and then we leave the thread to its own exit.
342+ match ready_rx.recv_timeout(OPEN_TIMEOUT) {
343+ Ok(()) => Box::into_raw(Box::new(Session {
344+ shared,
345+ ctl: ctl_tx,
346+ thread: Some(thread),
347+ })) as *mut c_void,
348+ Err(_) => {
349+ let _ = ctl_tx.send(Ctl::Quit);
350+ std::ptr::null_mut()
351+ }
352+ }
353+ }))
354+ .unwrap_or(std::ptr::null_mut())
355+}
356+
357+/// Queues up to `n` interleaved f32 samples, returning how many were accepted:
358+/// short counts mean the ring is full. Never blocks. -1 once the stream is dead.
359+///
360+/// # Safety
361+/// `session` must come from [`ao_open`] and `samples` must point at `n` f32s.
362+#[unsafe(no_mangle)]
363+pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: usize) -> isize {
364+ catch_unwind(AssertUnwindSafe(|| {
365+ if session.is_null() || samples.is_null() {
366+ return -1;
367+ }
368+ // SAFETY: caller-guaranteed live session and `n` readable samples.
369+ let session = unsafe { &*(session as *const Session) };
370+ if session.shared.dead.load(Ordering::Relaxed) {
371+ return -1;
372+ }
373+ let samples = unsafe { std::slice::from_raw_parts(samples, n) };
374+ session.shared.ring.push(samples) as isize
375+ }))
376+ .unwrap_or(-1)
377+}
378+
379+/// Samples per channel actually played at the device, or -1 while unknown.
380+///
381+/// # Safety
382+/// `session` must come from [`ao_open`].
383+#[unsafe(no_mangle)]
384+pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
385+ catch_unwind(AssertUnwindSafe(|| {
386+ if session.is_null() {
387+ return -1;
388+ }
389+ // SAFETY: caller-guaranteed live session.
390+ let session = unsafe { &*(session as *const Session) };
391+ session.shared.position.load(Ordering::Relaxed)
392+ }))
393+ .unwrap_or(-1)
394+}
395+
396+/// Pauses (0) or resumes (non-zero) playback. Paused freezes the position.
397+/// 0 on success, negative on failure.
398+///
399+/// # Safety
400+/// `session` must come from [`ao_open`].
401+#[unsafe(no_mangle)]
402+pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 {
403+ catch_unwind(AssertUnwindSafe(|| {
404+ if session.is_null() {
405+ return -1;
406+ }
407+ // SAFETY: caller-guaranteed live session.
408+ let session = unsafe { &*(session as *const Session) };
409+ match session.ctl.send(Ctl::Active(active != 0)) {
410+ Ok(()) => 0,
411+ Err(_) => -1,
412+ }
413+ }))
414+ .unwrap_or(-1)
415+}
416+
417+/// Stops playback and releases the session. Safe to call with null.
418+///
419+/// # Safety
420+/// `session` must come from [`ao_open`] and must not be used afterwards.
421+#[unsafe(no_mangle)]
422+pub unsafe extern "C" fn ao_close(session: *mut c_void) {
423+ let _ = catch_unwind(AssertUnwindSafe(|| {
424+ if !session.is_null() {
425+ // SAFETY: pointer came from `Box::into_raw` in `ao_open`.
426+ drop(unsafe { Box::from_raw(session as *mut Session) });
427+ }
428+ }));
429+}
430+
431+#[cfg(test)]
432+mod tests {
433+ use super::Ring;
434+
435+ #[test]
436+ fn ring_wraps_fills_and_starves() {
437+ let ring = Ring::new(4);
438+ let mut out = [0u8; 24];
439+
440+ // Short write, then read it back as little-endian f32.
441+ assert_eq!(ring.push(&[1.0, 2.0]), 2);
442+ assert_eq!(ring.pop(&mut out, 2), 2);
443+ assert_eq!(&out[..4], &1.0f32.to_le_bytes());
444+ assert_eq!(&out[4..8], &2.0f32.to_le_bytes());
445+
446+ // Full ring accepts only what fits, and the tail wraps the mask.
447+ assert_eq!(ring.push(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), 4);
448+ assert_eq!(ring.push(&[9.0]), 0);
449+ assert_eq!(ring.pop(&mut out, 6), 4);
450+ assert_eq!(&out[12..16], &4.0f32.to_le_bytes());
451+
452+ // Empty ring starves instead of replaying stale samples.
453+ assert_eq!(ring.pop(&mut out, 4), 0);
454+ }
455+}
crates/engine/Cargo.tomlmodified+2 -0
@@ -8,3 +8,5 @@ edition.workspace = true
8 libloading = "0.8"8 libloading = "0.8"
9 mp4 = "0.14"9 mp4 = "0.14"
10 rusty_h264 = { version = "0.8", default-features = false }10 rusty_h264 = { version = "0.8", default-features = false }
11+symphonia-core = "0.6"
12+symphonia-codec-aac = "0.6"
crates/engine/src/ao.rsadded+132 -0
@@ -0,0 +1,132 @@
1+//! Runtime-optional audio output plugin (`libengine_audio.so`).
2+//!
3+//! The plugin links libpipewire; this crate and the app binary must not, so the
4+//! only coupling is this C ABI plus a `dlopen`. Anything that goes wrong --
5+//! plugin missing, no PipeWire daemon, an unusable format -- leaves us with
6+//! `None` and the caller plays silently.
7+
8+use std::ffi::c_void;
9+use std::path::Path;
10+use std::sync::OnceLock;
11+
12+use libloading::Library;
13+
14+const LIB_NAME: &str = "libengine_audio.so";
15+
16+struct Plugin {
17+ open: unsafe extern "C" fn(u32, u32) -> *mut c_void,
18+ write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize,
19+ position: unsafe extern "C" fn(*mut c_void) -> i64,
20+ set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
21+ close: unsafe extern "C" fn(*mut c_void),
22+ // Never dropped (lives in a static), so the fn pointers above stay valid.
23+ _lib: Library,
24+}
25+
26+fn plugin() -> Option<&'static Plugin> {
27+ static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
28+ PLUGIN.get_or_init(load).as_ref()
29+}
30+
31+fn load() -> Option<Plugin> {
32+ // Next to the executable first (cargo puts both in target/<profile>), then
33+ // whatever the dynamic linker's search path turns up.
34+ let beside_exe = std::env::current_exe()
35+ .ok()
36+ .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)));
37+ let candidates = beside_exe
38+ .as_deref()
39+ .into_iter()
40+ .chain(std::iter::once(Path::new(LIB_NAME)));
41+
42+ for candidate in candidates {
43+ // SAFETY: loading a shared object runs its initialisers; we only ever
44+ // name our own plugin, and every symbol below is type-checked against
45+ // the signatures this crate shares with it.
46+ let lib = match unsafe { Library::new(candidate) } {
47+ Ok(lib) => lib,
48+ Err(_) => continue,
49+ };
50+ let plugin = unsafe {
51+ (|| {
52+ Some(Plugin {
53+ open: *lib.get(b"ao_open\0").ok()?,
54+ write: *lib.get(b"ao_write\0").ok()?,
55+ position: *lib.get(b"ao_position\0").ok()?,
56+ set_active: *lib.get(b"ao_set_active\0").ok()?,
57+ close: *lib.get(b"ao_close\0").ok()?,
58+ _lib: lib,
59+ })
60+ })()
61+ };
62+ if plugin.is_some() {
63+ return plugin;
64+ }
65+ }
66+ None
67+}
68+
69+/// An open playback stream. Dropping it stops playback and closes the session.
70+pub struct AoSession {
71+ plugin: &'static Plugin,
72+ handle: *mut c_void,
73+}
74+
75+impl AoSession {
76+ /// Connects a playback stream for interleaved f32 at `sample_rate`.
77+ /// `None` covers everything: no plugin, no daemon, unusable format.
78+ pub fn open(sample_rate: u32, channels: u32) -> Option<Self> {
79+ let plugin = plugin()?;
80+ // SAFETY: plain scalars in, a session pointer or null out.
81+ let handle = unsafe { (plugin.open)(sample_rate, channels) };
82+ if handle.is_null() {
83+ return None;
84+ }
85+ Some(Self { plugin, handle })
86+ }
87+
88+ /// Whether the plugin itself is loadable. Says nothing about the daemon --
89+ /// only [`AoSession::open`] answers that, and it is cheap enough to be the
90+ /// real probe.
91+ pub fn probe() -> bool {
92+ plugin().is_some()
93+ }
94+
95+ /// Queues interleaved samples, returning how many were accepted; a short
96+ /// count means the ring is full and the caller should come back later.
97+ /// `None` once the output has died (daemon gone).
98+ pub fn write(&mut self, samples: &[f32]) -> Option<usize> {
99+ // SAFETY: `handle` is live and `samples` is a valid slice for the call.
100+ match unsafe { (self.plugin.write)(self.handle, samples.as_ptr(), samples.len()) } {
101+ n if n < 0 => None,
102+ n => Some(n as usize),
103+ }
104+ }
105+
106+ /// Samples per channel actually played at the device -- the master clock.
107+ /// `None` until the stream has run its first cycle.
108+ pub fn position(&self) -> Option<i64> {
109+ // SAFETY: `handle` came from `ao_open` and is still open.
110+ match unsafe { (self.plugin.position)(self.handle) } {
111+ n if n < 0 => None,
112+ n => Some(n),
113+ }
114+ }
115+
116+ /// Pauses or resumes playback; while paused the position stays put.
117+ pub fn set_active(&self, active: bool) -> bool {
118+ // SAFETY: `handle` came from `ao_open` and is still open.
119+ unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 }
120+ }
121+}
122+
123+impl Drop for AoSession {
124+ fn drop(&mut self) {
125+ // SAFETY: `handle` came from `ao_open` and is closed exactly once.
126+ unsafe { (self.plugin.close)(self.handle) }
127+ }
128+}
129+
130+// The session is used from one thread at a time (the audio feeder) and never
131+// shared; the PipeWire state behind it is not `Sync`.
132+unsafe impl Send for AoSession {}
crates/engine/src/audio.rsadded+236 -0
@@ -0,0 +1,236 @@
1+//! Background audio decode worker: pulls the AAC track out of an MP4 and hands
2+//! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own
3+//! `Mp4Reader` so the video demuxer stays single-owner.
4+
5+use std::fs::File;
6+use std::io::BufReader;
7+use std::path::Path;
8+use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
9+use std::thread;
10+
11+use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track};
12+use symphonia_codec_aac::AacDecoder;
13+use symphonia_core::codecs::audio::{
14+ AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,
15+};
16+use symphonia_core::packet::Packet;
17+use symphonia_core::units;
18+
19+/// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
20+/// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
21+const DEFAULT_PRIMING: u64 = 1024;
22+
23+/// An edit list entry that only shifts the timeline, carrying no media.
24+const EMPTY_EDIT: u64 = u32::MAX as u64;
25+
26+#[derive(Debug, Clone, Copy, PartialEq)]
27+pub struct AudioMeta {
28+ pub sample_rate: u32,
29+ pub channels: u16,
30+ /// Frames per channel the container claims, priming subtracted. `None` when
31+ /// the header does not say.
32+ pub total_samples: Option<u64>,
33+}
34+
35+/// One decoder output block, ready to hand to an output device.
36+pub struct AudioChunk {
37+ /// Position of the first frame, in samples-per-channel counted from the
38+ /// first audible sample: priming is already dropped, so 0 is media time 0.
39+ pub start_sample: u64,
40+ /// Interleaved, `AudioMeta::channels` values per frame.
41+ pub samples: Vec<f32>,
42+}
43+
44+pub struct AudioSession;
45+
46+impl AudioSession {
47+ /// Opens the audio track of `path`. `Ok(None)` means the file simply has no
48+ /// audio, which is a valid session; `Err` is a real failure.
49+ pub fn open(
50+ path: impl AsRef<Path>,
51+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
52+ let file = File::open(path.as_ref())?;
53+ let size = file.metadata()?.len();
54+ let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
55+
56+ let Some(track) = reader
57+ .tracks()
58+ .values()
59+ .find(|t| matches!(t.media_type(), Ok(MediaType::AAC)))
60+ else {
61+ return Ok(None);
62+ };
63+
64+ // AacDecoder only does plain LC, mono/stereo; refuse early with a
65+ // message instead of letting it fail packet by packet.
66+ match track.audio_profile()? {
67+ AudioObjectType::AacLowComplexity => {}
68+ other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()),
69+ }
70+ let channels: u16 = match track.channel_config()? {
71+ ChannelConfig::Mono => 1,
72+ ChannelConfig::Stereo => 2,
73+ other => return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()),
74+ };
75+
76+ let track_id = track.track_id();
77+ let sample_rate = track.sample_freq_index()?.freq();
78+ let priming = priming_samples(track, sample_rate);
79+ let total_samples = scale(track.trak.mdia.mdhd.duration, sample_rate, track.timescale())
80+ .map(|d| d.saturating_sub(priming));
81+
82+ let mut params = AudioCodecParameters::new();
83+ params
84+ .for_codec(CODEC_ID_AAC)
85+ .with_sample_rate(sample_rate)
86+ .with_extra_data(audio_specific_config(track)?);
87+ let decoder = AacDecoder::try_new(&params, &AudioDecoderOptions::default())?;
88+
89+ let sample_count = reader.sample_count(track_id)?;
90+ let meta = AudioMeta {
91+ sample_rate,
92+ channels,
93+ total_samples,
94+ };
95+ // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so
96+ // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
97+ // without making a pause take a second to bite.
98+ let (tx, rx) = sync_channel(32);
99+ thread::Builder::new().name("audio-decode".into()).spawn(move || {
100+ run(Worker {
101+ reader,
102+ decoder,
103+ track_id,
104+ sample_count,
105+ channels: channels as usize,
106+ priming,
107+ tx,
108+ })
109+ })?;
110+ Ok(Some((meta, rx)))
111+ }
112+}
113+
114+/// The 2-byte AAC-LC AudioSpecificConfig, rebuilt from the esds fields; mp4 0.14
115+/// parses those out and drops the raw bytes, so this is the exact inverse of its
116+/// writer (`mp4box/mp4a.rs` `DecoderSpecificDescriptor::write_box`).
117+fn audio_specific_config(track: &Mp4Track) -> crate::Result<Box<[u8]>> {
118+ let esds = track
119+ .trak
120+ .mdia
121+ .minf
122+ .stbl
123+ .stsd
124+ .mp4a
125+ .as_ref()
126+ .and_then(|mp4a| mp4a.esds.as_ref())
127+ .ok_or("AAC track has no esds descriptor")?;
128+ let cfg = &esds.es_desc.dec_config.dec_specific;
129+ Ok(Box::new([
130+ (cfg.profile << 3) | (cfg.freq_index >> 1),
131+ (cfg.freq_index << 7) | (cfg.chan_conf << 3),
132+ ]))
133+}
134+
135+/// Encoder delay in samples-per-channel: the edit list's first real entry says
136+/// how far into the media the presentation starts.
137+///
138+/// ponytail: an explicit `media_time` of 0 is taken at face value (no trim).
139+/// Muxers that write a zero edit list despite a primed stream would leak the
140+/// priming; upgrade path is preferring the codec delay when it disagrees.
141+fn priming_samples(track: &Mp4Track, sample_rate: u32) -> u64 {
142+ track
143+ .trak
144+ .edts
145+ .as_ref()
146+ .and_then(|edts| edts.elst.as_ref())
147+ .and_then(|elst| {
148+ elst.entries
149+ .iter()
150+ .map(|e| e.media_time)
151+ .find(|&t| t != EMPTY_EDIT && t != u64::MAX)
152+ })
153+ .and_then(|t| scale(t, sample_rate, track.timescale()))
154+ .unwrap_or(DEFAULT_PRIMING)
155+}
156+
157+/// `value` from the track timescale into samples-per-channel. `None` on a zero
158+/// timescale, which would be a broken header.
159+fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
160+ let timescale = u64::from(timescale);
161+ (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
162+}
163+
164+struct Worker {
165+ reader: Mp4Reader<BufReader<File>>,
166+ decoder: AacDecoder,
167+ track_id: u32,
168+ sample_count: u32,
169+ channels: usize,
170+ priming: u64,
171+ tx: SyncSender<AudioChunk>,
172+}
173+
174+fn run(mut w: Worker) {
175+ let mut interleaved = Vec::new();
176+ let mut to_skip = w.priming;
177+ let mut emitted = 0u64;
178+
179+ for id in 1..=w.sample_count {
180+ let sample = match w.reader.read_sample(w.track_id, id) {
181+ Ok(Some(sample)) => sample,
182+ Ok(None) => break,
183+ Err(e) => {
184+ eprintln!("audio demux error at sample {id}: {e}");
185+ break;
186+ }
187+ };
188+ let packet = Packet::new(
189+ w.track_id,
190+ units::Timestamp::new(sample.start_time as i64),
191+ units::Duration::new(u64::from(sample.duration)),
192+ &sample.bytes[..],
193+ );
194+ let buf = match w.decoder.decode(&packet) {
195+ Ok(buf) => buf,
196+ Err(e) => {
197+ eprintln!("audio decode error at sample {id}: {e}");
198+ break;
199+ }
200+ };
201+ buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
202+
203+ // Priming frames are encoder ramp-up, not audio: drop them so the first
204+ // sample the caller sees is the first audible one.
205+ if to_skip > 0 {
206+ let drop = to_skip.min((interleaved.len() / w.channels) as u64);
207+ interleaved.drain(..drop as usize * w.channels);
208+ to_skip -= drop;
209+ if interleaved.is_empty() {
210+ continue;
211+ }
212+ }
213+ let chunk = AudioChunk {
214+ start_sample: emitted,
215+ samples: std::mem::take(&mut interleaved),
216+ };
217+ emitted += (chunk.samples.len() / w.channels) as u64;
218+ if w.tx.send(chunk).is_err() {
219+ break; // consumer went away
220+ }
221+ }
222+}
223+
224+#[cfg(test)]
225+mod tests {
226+ #[test]
227+ fn asc_round_trips_aac_lc_44100_stereo() {
228+ // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
229+ let (profile, freq_index, chan_conf) = (2u8, 4u8, 2u8);
230+ let asc = [
231+ (profile << 3) | (freq_index >> 1),
232+ (freq_index << 7) | (chan_conf << 3),
233+ ];
234+ assert_eq!(asc, [0x12, 0x10]);
235+ }
236+}
crates/engine/src/clock.rsadded+311 -0
@@ -0,0 +1,311 @@
1+//! Playback master clock: the one answer to "what time is it in this timeline?".
2+//!
3+//! Audio owns the clock whenever it plays -- the app polls the audio plugin and
4+//! feeds the sample position in with [`PlaybackClock::set_audio_position`]. With
5+//! no audio (muted, video-only, past audio EOF) the clock is anchored to an
6+//! [`Instant`] instead. Both modes are the same timeline, so switching mid-play
7+//! re-anchors at the current time and never jumps.
8+//!
9+//! Granularity contract: in audio mode `now()` steps at the audio quantum, not
10+//! smoothly. The reported position advances once per 256-1024 frame buffer
11+//! (5-23 ms at 48 kHz) while the app polls per rendered frame (~16 ms), so two
12+//! consecutive polls can return the same time and the next can jump by a whole
13+//! quantum. That is below the app's drift threshold, so it costs nothing today.
14+//! Smoothing (interpolating with the report's own timestamp) belongs on the
15+//! audio-plugin side where that timestamp exists, not here.
16+//!
17+//! Drift policy -- whether a late frame is dropped or an early one held -- is the
18+//! app's; this type only reports time.
19+
20+use std::time::Instant;
21+
22+/// What drives [`PlaybackClock::now`].
23+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
24+pub enum ClockSource {
25+ /// Externally reported audio sample position.
26+ Audio,
27+ /// Elapsed wall time since the last anchor.
28+ Wall,
29+}
30+
31+/// Monotonic-while-playing playback position, in seconds. `Send`, with no
32+/// threads or I/O of its own: every state change is an explicit call.
33+pub struct PlaybackClock {
34+ source: ClockSource,
35+ playing: bool,
36+ /// Timeline position of the current anchor. While paused this *is* `now()`.
37+ base: f64,
38+ /// Wall anchor; only meaningful while playing in [`ClockSource::Wall`].
39+ anchor: Instant,
40+ /// Audio position at the anchor, `None` until the first report after a
41+ /// re-anchor. Reports are relative to this, so a stream that restarts its
42+ /// sample counter after a seek re-syncs instead of jumping.
43+ audio_ref: Option<f64>,
44+ /// Last accepted report, to clamp a position that runs backwards.
45+ audio_last: f64,
46+}
47+
48+impl PlaybackClock {
49+ /// A paused clock at t=0.
50+ pub fn new(source: ClockSource) -> Self {
51+ Self {
52+ source,
53+ playing: false,
54+ base: 0.0,
55+ anchor: Instant::now(),
56+ audio_ref: None,
57+ audio_last: 0.0,
58+ }
59+ }
60+
61+ pub fn source(&self) -> ClockSource {
62+ self.source
63+ }
64+
65+ pub fn is_playing(&self) -> bool {
66+ self.playing
67+ }
68+
69+ /// Current timeline position in seconds. Frozen exactly while paused, never
70+ /// decreasing while playing.
71+ pub fn now(&self) -> f64 {
72+ if !self.playing {
73+ return self.base;
74+ }
75+ match self.source {
76+ ClockSource::Wall => self.base + self.anchor.elapsed().as_secs_f64(),
77+ ClockSource::Audio => match self.audio_ref {
78+ Some(r) => self.base + (self.audio_last - r),
79+ None => self.base,
80+ },
81+ }
82+ }
83+
84+ /// Resumes from wherever `now()` was frozen. No-op if already playing.
85+ pub fn play(&mut self) {
86+ if !self.playing {
87+ self.playing = true;
88+ self.reanchor(self.base);
89+ }
90+ }
91+
92+ pub fn pause(&mut self) {
93+ if self.playing {
94+ self.base = self.now();
95+ self.playing = false;
96+ }
97+ }
98+
99+ /// Repositions the timeline to `secs`, playing or paused.
100+ pub fn seek_to(&mut self, secs: f64) {
101+ self.reanchor(secs);
102+ }
103+
104+ /// Audio EOF: keeps the clock running off wall time from the current
105+ /// position, so `now()` is continuous across the switch.
106+ pub fn switch_to_wall(&mut self) {
107+ self.reanchor(self.now());
108+ self.source = ClockSource::Wall;
109+ }
110+
111+ /// Hands the clock back to audio from the current position. The next
112+ /// reported sample position becomes the new reference whatever its value.
113+ pub fn switch_to_audio(&mut self) {
114+ self.reanchor(self.now());
115+ self.source = ClockSource::Audio;
116+ }
117+
118+ /// The app's audio position poll. Ignored in wall mode, and ignored when it
119+ /// runs backwards (a device reset restarts the counter) so playback time
120+ /// never rewinds under the renderer; the app re-syncs with `seek_to` or
121+ /// `switch_to_wall`.
122+ pub fn set_audio_position(&mut self, samples_played: u64, sample_rate: u32) {
123+ if sample_rate == 0 {
124+ return;
125+ }
126+ let secs = samples_played as f64 / sample_rate as f64;
127+ match self.audio_ref {
128+ None => {
129+ self.audio_ref = Some(secs);
130+ self.audio_last = secs;
131+ }
132+ Some(_) if secs > self.audio_last => self.audio_last = secs,
133+ Some(_) => {}
134+ }
135+ }
136+
137+ /// Makes `base` the current position and drops both source references, so
138+ /// the next wall tick or audio report continues from there.
139+ fn reanchor(&mut self, secs: f64) {
140+ self.base = secs;
141+ self.anchor = Instant::now();
142+ self.audio_ref = None;
143+ self.audio_last = 0.0;
144+ }
145+}
146+
147+#[cfg(test)]
148+mod tests {
149+ use super::*;
150+ use std::thread::sleep;
151+ use std::time::Duration;
152+
153+ const RATE: u32 = 48_000;
154+
155+ /// The app moves the clock between threads/closures.
156+ fn _assert_send<T: Send>() {}
157+ const _: fn() = || _assert_send::<PlaybackClock>();
158+
159+ fn audio_playing() -> PlaybackClock {
160+ let mut c = PlaybackClock::new(ClockSource::Audio);
161+ c.play();
162+ c
163+ }
164+
165+ #[test]
166+ fn audio_follows_reports_exactly() {
167+ let mut c = audio_playing();
168+ assert_eq!(c.now(), 0.0);
169+ c.set_audio_position(0, RATE); // first report sets the reference
170+ assert_eq!(c.now(), 0.0);
171+ c.set_audio_position(48_000, RATE);
172+ assert_eq!(c.now(), 1.0);
173+ c.set_audio_position(72_000, RATE);
174+ assert_eq!(c.now(), 1.5);
175+ }
176+
177+ #[test]
178+ fn audio_reference_is_relative_not_absolute() {
179+ // A stream already 10 s in still starts this clock's timeline at 0.
180+ let mut c = audio_playing();
181+ c.set_audio_position(480_000, RATE);
182+ assert_eq!(c.now(), 0.0);
183+ c.set_audio_position(504_000, RATE);
184+ assert_eq!(c.now(), 0.5);
185+ }
186+
187+ #[test]
188+ fn audio_regression_clamps() {
189+ let mut c = audio_playing();
190+ c.set_audio_position(0, RATE);
191+ c.set_audio_position(96_000, RATE);
192+ assert_eq!(c.now(), 2.0);
193+ c.set_audio_position(24_000, RATE); // device reset
194+ assert_eq!(c.now(), 2.0, "clock must not rewind");
195+ c.set_audio_position(0, RATE);
196+ assert_eq!(c.now(), 2.0);
197+ c.set_audio_position(120_000, RATE); // recovered, forward again
198+ assert_eq!(c.now(), 2.5);
199+ }
200+
201+ #[test]
202+ fn zero_sample_rate_ignored() {
203+ let mut c = audio_playing();
204+ c.set_audio_position(1_000, 0);
205+ assert_eq!(c.now(), 0.0);
206+ }
207+
208+ #[test]
209+ fn pause_freezes_and_play_resumes() {
210+ let mut c = audio_playing();
211+ c.set_audio_position(0, RATE);
212+ c.set_audio_position(48_000, RATE);
213+ c.pause();
214+ assert!(!c.is_playing());
215+ assert_eq!(c.now(), 1.0);
216+ // Audio keeps running for a moment after a pause request; ignored.
217+ c.set_audio_position(60_000, RATE);
218+ assert_eq!(c.now(), 1.0);
219+ c.play();
220+ assert_eq!(c.now(), 1.0, "no time gained across the pause");
221+ c.set_audio_position(72_000, RATE); // stream restarted mid-buffer
222+ assert_eq!(c.now(), 1.0);
223+ c.set_audio_position(96_000, RATE);
224+ assert_eq!(c.now(), 1.5);
225+ }
226+
227+ #[test]
228+ fn wall_advances_with_real_time() {
229+ let mut c = PlaybackClock::new(ClockSource::Wall);
230+ c.play();
231+ sleep(Duration::from_millis(120));
232+ let t = c.now();
233+ assert!((0.05..0.60).contains(&t), "wall clock at {t}");
234+ c.pause();
235+ let frozen = c.now();
236+ sleep(Duration::from_millis(120));
237+ assert_eq!(c.now(), frozen, "paused wall clock must not move");
238+ c.play();
239+ assert!(c.now() - frozen < 0.05);
240+ sleep(Duration::from_millis(120));
241+ assert!(c.now() > frozen + 0.05);
242+ }
243+
244+ #[test]
245+ fn switch_to_wall_is_continuous() {
246+ let mut c = audio_playing();
247+ c.set_audio_position(0, RATE);
248+ c.set_audio_position(96_000, RATE);
249+ let x = c.now();
250+ c.switch_to_wall();
251+ assert_eq!(c.source(), ClockSource::Wall);
252+ assert!((c.now() - x).abs() < 0.01, "jumped from {x} to {}", c.now());
253+ sleep(Duration::from_millis(120));
254+ assert!(c.now() > x + 0.05, "wall clock did not take over");
255+ }
256+
257+ #[test]
258+ fn switch_to_audio_is_continuous() {
259+ let mut c = PlaybackClock::new(ClockSource::Wall);
260+ c.play();
261+ sleep(Duration::from_millis(50));
262+ let before = c.now();
263+ c.switch_to_audio();
264+ let x = c.now();
265+ assert!((x - before).abs() < 0.01, "jumped from {before} to {x}");
266+ assert_eq!(c.now(), x, "audio mode holds until the first report");
267+ c.set_audio_position(240_000, RATE);
268+ assert_eq!(c.now(), x);
269+ c.set_audio_position(264_000, RATE);
270+ assert_eq!(c.now(), x + 0.5);
271+ }
272+
273+ #[test]
274+ fn seek_while_paused() {
275+ let mut c = PlaybackClock::new(ClockSource::Wall);
276+ c.seek_to(12.0);
277+ assert_eq!(c.now(), 12.0);
278+ sleep(Duration::from_millis(50));
279+ assert_eq!(c.now(), 12.0, "seek must not start the clock");
280+ c.play();
281+ sleep(Duration::from_millis(120));
282+ let t = c.now();
283+ assert!((12.05..12.60).contains(&t), "resumed at {t}");
284+ }
285+
286+ #[test]
287+ fn seek_while_playing_audio() {
288+ let mut c = audio_playing();
289+ c.set_audio_position(0, RATE);
290+ c.set_audio_position(48_000, RATE);
291+ c.seek_to(30.0);
292+ assert_eq!(c.now(), 30.0);
293+ // The app restarts the stream, so the counter comes back from zero.
294+ c.set_audio_position(0, RATE);
295+ assert_eq!(c.now(), 30.0);
296+ c.set_audio_position(24_000, RATE);
297+ assert_eq!(c.now(), 30.5);
298+ assert!(c.is_playing());
299+ }
300+
301+ #[test]
302+ fn seek_while_playing_wall() {
303+ let mut c = PlaybackClock::new(ClockSource::Wall);
304+ c.play();
305+ sleep(Duration::from_millis(50));
306+ c.seek_to(5.0);
307+ assert!((c.now() - 5.0).abs() < 0.01);
308+ sleep(Duration::from_millis(120));
309+ assert!(c.now() > 5.05);
310+ }
311+}
crates/engine/src/lib.rsmodified+5 -0
@@ -1,10 +1,15 @@
1 //! Video engine: demux -> decode -> pixel convert. No UI dependencies.1 //! Video engine: demux -> decode -> pixel convert. No UI dependencies.
2 2
3+pub mod ao;
4+pub mod audio;
5+pub mod clock;
3 pub mod convert;6 pub mod convert;
4 pub mod decode;7 pub mod decode;
5 pub mod demux;8 pub mod demux;
6 pub mod hw;9 pub mod hw;
7 10
11+pub use audio::{AudioChunk, AudioMeta, AudioSession};
12+pub use clock::PlaybackClock;
8 pub use decode::{DecodeSession, Frame};13 pub use decode::{DecodeSession, Frame};
9 pub use demux::VideoMeta;14 pub use demux::VideoMeta;
10 15
crates/engine/tests/ao_output.rsadded+103 -0
@@ -0,0 +1,103 @@
1+//! Audio output checks. These need a built `libengine_audio.so` plus a running
2+//! PipeWire daemon, so they are `#[ignore]`d by default. Run them with:
3+//!
4+//! ```text
5+//! cargo build --workspace --release
6+//! cargo test -p engine --release --test ao_output -- --ignored --nocapture --test-threads=1
7+//! ```
8+//!
9+//! `no_daemon_opens_nothing` sets `PIPEWIRE_REMOTE` in-process, hence the
10+//! required `--test-threads=1`; it restores the environment before asserting.
11+
12+use std::f32::consts::TAU;
13+use std::time::{Duration, Instant};
14+
15+use engine::ao::AoSession;
16+
17+const RATE: u32 = 44100;
18+const CHANNELS: u32 = 2;
19+
20+/// Half a second of a quiet 440 Hz tone, interleaved stereo.
21+fn tone() -> Vec<f32> {
22+ let frames = RATE as usize / 2;
23+ let mut samples = Vec::with_capacity(frames * CHANNELS as usize);
24+ for i in 0..frames {
25+ let value = (i as f32 * TAU * 440.0 / RATE as f32).sin() * 0.2;
26+ samples.extend([value; CHANNELS as usize]);
27+ }
28+ samples
29+}
30+
31+/// Waits up to `limit` for the clock to report a played position past zero.
32+fn wait_for_playback(ao: &AoSession, limit: Duration) -> i64 {
33+ let start = Instant::now();
34+ loop {
35+ if let Some(position) = ao.position() {
36+ if position > 0 {
37+ return position;
38+ }
39+ }
40+ assert!(start.elapsed() < limit, "playback position never advanced");
41+ std::thread::sleep(Duration::from_millis(10));
42+ }
43+}
44+
45+#[test]
46+#[ignore = "needs libengine_audio.so and a PipeWire daemon"]
47+fn plays_and_tracks_position() {
48+ assert!(AoSession::probe(), "plugin not loadable");
49+ let mut ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available");
50+
51+ // The ring holds a second, so two halves go in whole -- enough real audio
52+ // to cover the measurement below without starving.
53+ let samples = tone();
54+ assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
55+ assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
56+
57+ // Over 400 ms the clock must run at the rate we asked for, not at the
58+ // device's: the plugin converts PipeWire's ticks out of the graph rate.
59+ let first = wait_for_playback(&ao, Duration::from_secs(2));
60+ std::thread::sleep(Duration::from_millis(400));
61+ let second = ao.position().expect("position went unknown");
62+ let advanced = second - first;
63+ let expected = RATE as i64 * 400 / 1000;
64+ eprintln!("clock advanced {advanced} samples in 400 ms (expected ~{expected})");
65+ assert!(
66+ (advanced - expected).abs() < expected / 10,
67+ "clock runs at the wrong rate: {advanced} samples in 400 ms"
68+ );
69+
70+ // Paused means the device plays nothing, so the master clock must not move.
71+ assert!(ao.set_active(false), "pause rejected");
72+ std::thread::sleep(Duration::from_millis(150));
73+ let paused = ao.position().expect("position went unknown");
74+ std::thread::sleep(Duration::from_millis(100));
75+ assert_eq!(
76+ ao.position(),
77+ Some(paused),
78+ "position moved while paused: {paused}"
79+ );
80+
81+ ao.write(&samples).expect("write after pause");
82+ assert!(ao.set_active(true), "resume rejected");
83+ std::thread::sleep(Duration::from_millis(200));
84+ let resumed = ao.position().expect("position went unknown");
85+ assert!(resumed > paused, "clock did not resume: {paused} -> {resumed}");
86+}
87+
88+/// No reachable daemon must fail the open cleanly and quickly, never hang.
89+#[test]
90+#[ignore = "needs libengine_audio.so and a PipeWire daemon"]
91+fn no_daemon_opens_nothing() {
92+ assert!(AoSession::probe(), "plugin not loadable");
93+ // SAFETY: the suite is documented to run with --test-threads=1.
94+ unsafe { std::env::set_var("PIPEWIRE_REMOTE", "/nonexistent") };
95+ let start = Instant::now();
96+ let session = AoSession::open(RATE, CHANNELS);
97+ let elapsed = start.elapsed();
98+ unsafe { std::env::remove_var("PIPEWIRE_REMOTE") };
99+
100+ assert!(session.is_none(), "opened a stream with no daemon");
101+ assert!(elapsed < Duration::from_secs(2), "open took {elapsed:?}");
102+ eprintln!("open with no daemon failed in {elapsed:?}");
103+}
crates/engine/tests/audio_decode.rsadded+102 -0
@@ -0,0 +1,102 @@
1+use std::path::PathBuf;
2+use std::time::Instant;
3+
4+use engine::audio::AudioSession;
5+
6+const RATE: u32 = 44100;
7+const SECONDS: u32 = 5;
8+/// One AAC-LC packet; the container's tail padding is not trimmed, so the
9+/// decoded length may run up to a frame past the nominal duration.
10+const FRAME: i64 = 1024;
11+
12+fn asset(name: &str) -> PathBuf {
13+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14+ .join("../../assets")
15+ .join(name)
16+}
17+
18+/// Sign changes ignoring exact zeros, so the 1 Hz volume pulse touching zero
19+/// does not register as a crossing.
20+fn zero_crossings(samples: &[f32]) -> usize {
21+ let mut crossings = 0;
22+ let mut last = 0f32;
23+ for &s in samples {
24+ if s == 0.0 {
25+ continue;
26+ }
27+ if last != 0.0 && (s > 0.0) != (last > 0.0) {
28+ crossings += 1;
29+ }
30+ last = s;
31+ }
32+ crossings
33+}
34+
35+#[test]
36+fn decodes_av_mp4_audio() {
37+ let start = Instant::now();
38+ let (meta, rx) = AudioSession::open(asset("test_av.mp4"))
39+ .expect("open")
40+ .expect("test_av.mp4 has an audio track");
41+ assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
42+
43+ let mut left = Vec::new();
44+ let mut right = Vec::new();
45+ let mut next_sample = 0u64;
46+ let mut chunks = 0usize;
47+ for chunk in rx {
48+ // d. no gaps, no overlaps.
49+ assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start");
50+ assert!(!chunk.samples.is_empty(), "empty chunk {chunks}");
51+ assert_eq!(chunk.samples.len() % 2, 0, "partial frame in chunk {chunks}");
52+ next_sample += (chunk.samples.len() / 2) as u64;
53+ left.extend(chunk.samples.iter().step_by(2));
54+ right.extend(chunk.samples[1..].iter().step_by(2));
55+ chunks += 1;
56+ }
57+ let elapsed = start.elapsed();
58+ let frames = left.len();
59+ assert!(frames > 0, "no audio decoded");
60+
61+ // b. ~5 s of audio, priming trimmed, at most a frame of tail padding over.
62+ let want = (RATE * SECONDS) as i64;
63+ let slack = frames as i64 - want;
64+ assert!(
65+ (0..=FRAME).contains(&slack),
66+ "{frames} frames per channel, want {want} (+0..={FRAME})"
67+ );
68+ assert_eq!(right.len(), frames, "channel lengths differ");
69+
70+ // c. channel identity: L is 440 Hz, R is 880 Hz. A swap or a bad interleave
71+ // shows up as the wrong crossing count.
72+ let secs = frames as f64 / RATE as f64;
73+ for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
74+ let want = 2.0 * hz * secs;
75+ let got = zero_crossings(samples) as f64;
76+ assert!(
77+ (got - want).abs() <= 0.05 * want,
78+ "{name}: {got} zero crossings, want {want} +/-5%"
79+ );
80+ }
81+
82+ // Priming trimmed: the sine starts at a rising zero crossing, and audio is
83+ // present immediately rather than after a silent or garbage run-in.
84+ assert!(left[0].abs() < 0.05, "first sample {} not near zero", left[0]);
85+ assert!(left[1] > 0.0, "first sine quarter is not rising");
86+ let head_peak = left[..FRAME as usize].iter().fold(0f32, |m, s| m.max(s.abs()));
87+ assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}");
88+
89+ eprintln!(
90+ "{frames} frames/ch in {chunks} chunks, {elapsed:?} ({:?}/packet)",
91+ elapsed / chunks as u32
92+ );
93+}
94+
95+#[test]
96+fn video_only_file_has_no_audio() {
97+ assert!(
98+ AudioSession::open(asset("test_baseline.mp4"))
99+ .expect("open")
100+ .is_none()
101+ );
102+}