diff --git a/Cargo.lock b/Cargo.lock index 515ee26..fce5534 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9175,16 +9175,19 @@ dependencies = [ "openh264", "pipewire", "reqwest", + "rtrb", "rustix 1.1.5", "sha2 0.10.9", "str0m", "thiserror 2.0.21", "tokio", "tracing", + "tracing-subscriber", "wasapi", "wayland-client", "wayland-protocols", "wayland-protocols-wlr", + "windows 0.62.2", "windows-capture", "x11rb", "yuv", diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 3004993..6716b43 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -11,6 +11,17 @@ + + + + + + + + diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt index 145f25a..64a199a 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt @@ -2,6 +2,7 @@ package io.github.faumaray.voelin import android.Manifest import android.content.Context +import android.content.Intent import android.content.pm.PackageManager import android.os.Build @@ -62,6 +63,40 @@ object Bridge { ScreenCaptureService.stopAudio() } + /** + * Capture into mixer input `id` (Native.onAudioInput) what `packageName` + * plays, or with null everything but us. False without a running screen + * capture or for a package we cannot see. + */ + @JvmStatic + fun startAudioInput(id: Long, packageName: String?): Boolean = + ScreenCaptureService.startInput(app, id, packageName) + + @JvmStatic + fun stopAudioInput(id: Long) { + ScreenCaptureService.stopInput(id) + } + + /** Launchable apps other than us, as "labelpackage" lines sorted by label. */ + @JvmStatic + fun launchableApps(): String { + val pm = app.packageManager + val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) + val activities = if (Build.VERSION.SDK_INT >= 33) { + pm.queryIntentActivities(launcher, PackageManager.ResolveInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + pm.queryIntentActivities(launcher, 0) + } + val separators = Regex("[\t\n]") + return activities + .map { it.activityInfo.packageName to it.loadLabel(pm).toString() } + .filter { it.first != app.packageName } + .distinctBy { it.first } + .sortedBy { it.second.lowercase() } + .joinToString("\n") { (packageName, label) -> label.replace(separators, " ") + "\t" + packageName } + } + @JvmStatic fun secretGet(key: String): String? = SecretStore.get(app, key) diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt index 5f91cea..7aacd8e 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt @@ -35,6 +35,13 @@ object Native { @JvmStatic external fun onSystemAudio(samples: FloatArray, count: Int, channels: Int, timestampNs: Long): Boolean + /** + * `count` interleaved 48 kHz float samples for mixer input `id` + * (Bridge.startAudioInput). Returns false when it is no longer wanted. + */ + @JvmStatic + external fun onAudioInput(id: Long, samples: FloatArray, count: Int, channels: Int): Boolean + /** "Disconnect" in the voice notification. */ @JvmStatic external fun onDisconnectVoice() diff --git a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt index 485f654..0daf999 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt @@ -22,9 +22,11 @@ import android.os.Handler import android.os.HandlerThread import android.os.IBinder import android.os.Looper +import android.os.Process import android.util.Log import android.view.Display import android.view.Surface +import java.util.concurrent.ConcurrentHashMap import kotlin.concurrent.thread import kotlin.math.max import kotlin.math.roundToInt @@ -32,8 +34,9 @@ import kotlin.math.roundToInt /** * Screen sharing: holds the MediaProjection (a `mediaProjection` foreground * service, as Android requires), mirrors the display into an ImageReader and - * hands each RGBA frame to Native.onScreenFrame; optionally captures what the - * device plays (AudioPlaybackCapture) for Native.onSystemAudio. + * hands each RGBA frame to Native.onScreenFrame; optionally captures what + * other apps play (AudioPlaybackCapture: all but us, or one app) for + * Native.onSystemAudio and Native.onAudioInput. */ class ScreenCaptureService : Service() { private var projection: MediaProjection? = null @@ -41,9 +44,17 @@ class ScreenCaptureService : Service() { private var reader: ImageReader? = null private var worker: HandlerThread? = null - @Volatile - private var audioRunning = false - private var audioThread: Thread? = null + /** A running AudioPlaybackCapture recording. */ + private class AudioCapture { + @Volatile + var running = true + + @Volatile + var thread: Thread? = null + } + + /** Recordings by id: SYSTEM_AUDIO, or a mixer input of the Rust side. */ + private val captures = ConcurrentHashMap() private val main = Handler(Looper.getMainLooper()) @@ -148,18 +159,24 @@ class ScreenCaptureService : Service() { ) } - /** Capture media, game and unknown-usage playback as 48 kHz stereo float. */ - private fun startAudioCapture(): Boolean { + /** + * Capture media, game and unknown-usage playback as 48 kHz stereo float: + * of app `uid`, or with null of every app but us (our voices and watched + * streams). Several recordings may run at once. + */ + private fun startAudioCapture(id: Long, uid: Int?): Boolean { val projection = projection ?: return false - if (audioRunning) return true + if (captures[id]?.running == true) return true if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { return false } - val config = AudioPlaybackCaptureConfiguration.Builder(projection) + val builder = AudioPlaybackCaptureConfiguration.Builder(projection) .addMatchingUsage(AudioAttributes.USAGE_MEDIA) .addMatchingUsage(AudioAttributes.USAGE_GAME) .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN) - .build() + // Uid rules cannot mix matching and excluding; one of them. + if (uid != null) builder.addMatchingUid(uid) else builder.excludeUid(Process.myUid()) + val config = builder.build() val format = AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_FLOAT) .setSampleRate(SAMPLE_RATE) @@ -174,22 +191,30 @@ class ScreenCaptureService : Service() { .setBufferSizeInBytes(max(minimum, SAMPLE_RATE / 10 * 2 * 4)) .build() } catch (e: Exception) { - Log.w(TAG, "system audio capture unavailable", e) + Log.w(TAG, "playback capture unavailable", e) return false } - audioRunning = true + val capture = AudioCapture() + captures[id] = capture record.startRecording() - audioThread = thread(name = "voelin-system-audio") { + capture.thread = thread(name = "voelin-audio-$id") { // 10 ms of stereo. val buffer = FloatArray(SAMPLE_RATE / 100 * 2) try { - while (audioRunning) { + while (capture.running) { val read = record.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING) if (read < 0) break - if (read > 0 && !Native.onSystemAudio(buffer, read, 2, System.nanoTime())) break + if (read == 0) continue + val wanted = if (id == SYSTEM_AUDIO) { + Native.onSystemAudio(buffer, read, 2, System.nanoTime()) + } else { + Native.onAudioInput(id, buffer, read, 2) + } + if (!wanted) break } } finally { - audioRunning = false + capture.running = false + captures.remove(id, capture) record.stop() record.release() } @@ -197,15 +222,15 @@ class ScreenCaptureService : Service() { return true } - private fun stopAudioCapture() { - audioRunning = false - audioThread?.join(500) - audioThread = null + private fun stopAudioCapture(id: Long) { + val capture = captures.remove(id) ?: return + capture.running = false + capture.thread?.join(500) } override fun onDestroy() { if (instance === this) instance = null - stopAudioCapture() + captures.keys.toList().forEach { stopAudioCapture(it) } display?.release() display = null reader?.close() @@ -222,6 +247,9 @@ class ScreenCaptureService : Service() { private const val TAG = "ScreenCaptureService" private const val ID = 2 private const val SAMPLE_RATE = 48_000 + + /** The recording for Native.onSystemAudio (Rust input ids start at 1). */ + private const val SYSTEM_AUDIO = 0L private const val ACTION_STOP = "io.github.faumaray.voelin.STOP_SHARING" private const val EXTRA_RESULT = "result" private const val EXTRA_DATA = "data" @@ -247,11 +275,37 @@ class ScreenCaptureService : Service() { fun startAudio(): Boolean { val service = instance ?: return false - return service.startAudioCapture() + return service.startAudioCapture(SYSTEM_AUDIO, null) } fun stopAudio() { - instance?.stopAudioCapture() + instance?.stopAudioCapture(SYSTEM_AUDIO) + } + + /** Capture `packageName` (null: every app but us) into mixer input `id`. */ + fun startInput(context: Context, id: Long, packageName: String?): Boolean { + val service = instance ?: return false + val uid = if (packageName == null) { + null + } else { + try { + val pm = context.packageManager + if (Build.VERSION.SDK_INT >= 33) { + pm.getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(0)).uid + } else { + @Suppress("DEPRECATION") + pm.getApplicationInfo(packageName, 0).uid + } + } catch (e: PackageManager.NameNotFoundException) { + Log.w(TAG, "no package $packageName to capture") + return false + } + } + return service.startAudioCapture(id, uid) + } + + fun stopInput(id: Long) { + instance?.stopAudioCapture(id) } } } diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index 8b5d065..f7d442d 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -111,6 +111,71 @@ pub fn stop_system_audio() -> Result<()> { }) } +/// Capture playback into mixer input `id` (delivered to +/// `Native.onAudioInput`): of the app `package`, or everything but ours. +/// `false` without a running screen capture, or for a package that is not +/// installed (or not visible to us). +pub fn start_audio_input(id: u64, package: Option<&str>) -> Result { + with_bridge(|env, class| { + let package = match package { + Some(package) => JObject::from(env.new_string(package)?), + None => JObject::null(), + }; + env.call_static_method( + class, + jni_str!("startAudioInput"), + jni_sig!((id: jlong, package: java.lang.String) -> jboolean), + &[JValue::Long(id as jlong), JValue::Object(&package)], + )? + .z() + }) +} + +pub fn stop_audio_input(id: u64) -> Result<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("stopAudioInput"), + jni_sig!((id: jlong) -> void), + &[JValue::Long(id as jlong)], + )?; + Ok(()) + }) +} + +/// Launchable apps other than ours, as `(label, package)`, sorted by label. +pub fn launchable_apps() -> Result> { + let lines = with_bridge(|env, class| { + let value = env + .call_static_method( + class, + jni_str!("launchableApps"), + jni_sig!(() -> java.lang.String), + &[], + )? + .l()?; + if value.is_null() { + return Ok(String::new()); + } + let value = env.cast_local::(value)?; + value.try_to_string(env) + })?; + Ok(parse_apps(&lines)) +} + +/// `labelpackage` lines. +fn parse_apps(lines: &str) -> Vec<(String, String)> { + lines + .lines() + .filter_map(|line| { + let (label, package) = line.split_once('\t')?; + let package = package.trim(); + let label = if label.trim().is_empty() { package } else { label.trim() }; + (!package.is_empty()).then(|| (label.to_owned(), package.to_owned())) + }) + .collect() +} + pub fn secret_get(key: &str) -> Result> { with_bridge(|env, class| { let key = JObject::from(env.new_string(key)?); @@ -250,6 +315,36 @@ fn on_system_audio<'local>( Ok(crate::capture::on_audio(buffer, channels.clamp(1, 8) as u16, timestamp_ns)) } +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_audio_input(id: jlong, samples: jfloat[], count: jint, channels: jint) -> jboolean, +}; + +/// Interleaved 48 kHz float samples for mixer input `id` (see +/// [`start_audio_input`]). Returns `false` once the input is gone. +fn on_audio_input<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + samples: JFloatArray<'local>, + count: jint, + channels: jint, +) -> Result { + thread_local! { + // One per capture thread, reused for every call. + static BUFFER: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let id = id as u64; + if !crate::capture::wants_input(id) { + return Ok(false); + } + BUFFER.with_borrow_mut(|buffer| { + buffer.resize(count.max(0) as usize, 0.0); + samples.get_region(env, 0, buffer)?; + Ok(crate::capture::on_input(id, buffer, channels.clamp(1, 8) as u16)) + }) +} + const _: jni::NativeMethod = native_method! { java_type = "io.github.faumaray.voelin.Native", static extern fn on_disconnect_voice(), diff --git a/crates/voelin-android/src/capture.rs b/crates/voelin-android/src/capture.rs index 9a2a298..a52d8d7 100644 --- a/crates/voelin-android/src/capture.rs +++ b/crates/voelin-android/src/capture.rs @@ -5,15 +5,21 @@ //! asks the Kotlin side for the user's consent; on consent it runs //! `ScreenCaptureService` (a `mediaProjection` foreground service) whose //! `ImageReader` hands RGBA frames to [`on_frame`]. System audio -//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection. +//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection: +//! everything but our own uid, or one app's uid, each into a stream mixer +//! input ([`on_input`]); several captures may run at once. +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use tokio::sync::oneshot; use tracing::warn; use voelin_media::capture::external::{self, AudioProvider, ScreenProvider}; +use voelin_media::capture::playback::{AppMatch, AudioApp, PlaybackFilter}; use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use voelin_media::mix::SourceInput; use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; use crate::bridge; @@ -29,6 +35,8 @@ struct State { /// Answer for the pending `start`. pending: Option>>, audio: Option>, + /// Mixer inputs of [`AudioProvider::start_input`] captures, by id. + inputs: HashMap, /// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC` /// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync. origin_ns: Option, @@ -135,6 +143,89 @@ impl AudioProvider for PlaybackAudio { warn!("stopping system audio: {e}"); } } + + /// Everything but our uid, or the uid of one app's package. + fn start_input(&self, filter: &PlaybackFilter, input: SourceInput) -> Result { + let package = match filter { + PlaybackFilter::AllButSelf => None, + PlaybackFilter::App(app @ AppMatch::Name(name)) => Some( + self.apps() + .into_iter() + .find(|a| { + app.matches_name([a.name.as_str(), a.binary.as_deref().unwrap_or("")]) + }) + .and_then(|a| a.binary) + // Not launchable (a service, say): maybe the package itself. + .unwrap_or_else(|| name.trim().to_owned()), + ), + PlaybackFilter::App(AppMatch::Pid(_)) => { + return Err(Error::CaptureUnavailable { + backend: AUDIO, + reason: "Android captures apps by package, not by process".into(), + }); + } + }; + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + with_state(|s| s.inputs.insert(id, input)); + let started = bridge::start_audio_input(id, package.as_deref()); + if let Ok(true) = started { + return Ok(id); + } + with_state(|s| s.inputs.remove(&id)); + let reason = match (started, package) { + (Err(e), _) => e.to_string(), + (_, Some(package)) => format!( + "cannot capture {package}: not installed, or no running screen capture (and \ + the microphone permission)" + ), + (_, None) => "needs a running screen capture (and the microphone permission)".into(), + }; + Err(Error::CaptureUnavailable { backend: AUDIO, reason }) + } + + fn stop_input(&self, id: u64) { + with_state(|s| s.inputs.remove(&id)); + if let Err(e) = bridge::stop_audio_input(id) { + warn!("stopping audio capture {id}: {e}"); + } + } + + /// Android cannot tell which apps play: the launchable ones. + fn apps(&self) -> Vec { + match bridge::launchable_apps() { + Ok(apps) => apps + .into_iter() + .map(|(name, package)| AudioApp { + name, + binary: Some(package), + ..AudioApp::default() + }) + .collect(), + Err(e) => { + warn!("listing apps: {e}"); + Vec::new() + } + } + } +} + +pub fn wants_input(id: u64) -> bool { + with_state(|s| s.inputs.get(&id).is_some_and(|i| !i.is_closed())) +} + +/// Captured playback for mixer input `id`. Returns `false` once the input +/// is gone (the capture then stops). +pub fn on_input(id: u64, samples: &[f32], channels: u16) -> bool { + with_state(|s| { + let Some(input) = s.inputs.get_mut(&id) else { return false }; + input.push(samples, channels); + if input.is_closed() { + s.inputs.remove(&id); + return false; + } + true + }) } /// The user answered the consent dialog (or the service failed to start). diff --git a/crates/voelin-audio/src/lib.rs b/crates/voelin-audio/src/lib.rs index 80693e8..0494562 100644 --- a/crates/voelin-audio/src/lib.rs +++ b/crates/voelin-audio/src/lib.rs @@ -10,6 +10,8 @@ //! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the //! vendored `tsclientlib::audio::AudioHandler`) //! - [`settings`]: all user audio settings in one serde struct +//! - [`tap`]: the processed microphone for other consumers (the stream +//! mixer), free while nobody listens //! - `device` (feature `device`): capture and playback through cpal, device //! lists and loss detection @@ -20,6 +22,7 @@ pub mod pcm; pub mod process; pub mod resample; pub mod settings; +pub mod tap; pub mod vad; pub mod wav; diff --git a/crates/voelin-audio/src/tap.rs b/crates/voelin-audio/src/tap.rs new file mode 100644 index 0000000..53d0f54 --- /dev/null +++ b/crates/voelin-audio/src/tap.rs @@ -0,0 +1,217 @@ +//! Taps: the processed microphone for consumers besides the voice +//! connection, such as the audio mixer of our screen share. +//! +//! The voice pipeline publishes every processed chunk (48 kHz mono, after +//! echo cancellation, noise suppression and gain control) to +//! [`microphone()`]. Unused, that is one relaxed atomic load per chunk. +//! With consumers attached ([`Tap::attach`]) the publisher hands the chunk +//! to each [`TapSink`] on its own thread; it never waits: the consumer list +//! is taken with a try-lock that only contends with attaching and +//! detaching, and a chunk that meets such a change is skipped. +//! +//! Several pipelines can run at once (one per server, the microphone +//! test); the tap follows one of them at a time: the first that publishes, +//! until it has been silent for [`HANDOVER`], then whichever publishes next. + +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; +use std::time::{Duration, Instant}; + +/// A publisher silent this long loses the tap to another one. +pub const HANDOVER: Duration = Duration::from_millis(200); + +/// Receives tapped audio on the publisher's thread. Must not block. +pub trait TapSink: Send { + /// 48 kHz mono samples. + fn write(&mut self, samples: &[f32]); + + /// `frames` samples of silence (e.g. while the microphone is muted). + fn silence(&mut self, frames: usize); +} + +/// A publish point that any number of consumers can attach to. +pub struct Tap { + /// Attached sinks: the only thing publishers look at when unused. + active: AtomicUsize, + sinks: Mutex)>>, + next_sink: AtomicU64, + /// The publisher followed now (0: none) and when it last published + /// (milliseconds since `epoch`). + owner: AtomicU64, + owner_seen: AtomicU64, +} + +static MICROPHONE: Tap = Tap::new(); +static NEXT_PUBLISHER: AtomicU64 = AtomicU64::new(1); + +/// Processed microphone audio, 48 kHz mono. +pub fn microphone() -> &'static Tap { + &MICROPHONE +} + +/// An id for a publisher (one per voice pipeline). +pub fn publisher_id() -> u64 { + NEXT_PUBLISHER.fetch_add(1, Ordering::Relaxed) +} + +fn now_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 +} + +impl Default for Tap { + fn default() -> Self { + Self::new() + } +} + +impl Tap { + pub const fn new() -> Self { + Self { + active: AtomicUsize::new(0), + sinks: Mutex::new(Vec::new()), + next_sink: AtomicU64::new(1), + owner: AtomicU64::new(0), + owner_seen: AtomicU64::new(0), + } + } + + /// Whether anyone listens: publishers skip all work otherwise. + #[inline] + pub fn is_active(&self) -> bool { + self.active.load(Ordering::Relaxed) != 0 + } + + /// Attach a consumer until the returned guard is dropped. + pub fn attach(&self, sink: Box) -> TapGuard<'_> { + let id = self.next_sink.fetch_add(1, Ordering::Relaxed); + let mut sinks = self.sinks.lock().unwrap_or_else(PoisonError::into_inner); + sinks.push((id, sink)); + self.active.store(sinks.len(), Ordering::Relaxed); + TapGuard { tap: self, id } + } + + fn detach(&self, id: u64) { + let mut sinks = self.sinks.lock().unwrap_or_else(PoisonError::into_inner); + sinks.retain(|(i, _)| *i != id); + self.active.store(sinks.len(), Ordering::Relaxed); + } + + /// Whether `publisher` is the one followed now (taking over from one + /// that went silent). + fn follows(&self, publisher: u64) -> bool { + let now = now_ms(); + let owner = self.owner.load(Ordering::Acquire); + if owner != publisher { + let stale = now.saturating_sub(self.owner_seen.load(Ordering::Relaxed)) + >= HANDOVER.as_millis() as u64; + if owner != 0 && !stale { + return false; + } + if self + .owner + .compare_exchange(owner, publisher, Ordering::AcqRel, Ordering::Relaxed) + .is_err() + { + return false; + } + } + self.owner_seen.store(now, Ordering::Relaxed); + true + } + + /// Hand `samples` to every consumer (no-op without consumers, or when + /// another publisher is followed). + pub fn publish(&self, publisher: u64, samples: &[f32]) { + if !self.is_active() || samples.is_empty() || !self.follows(publisher) { + return; + } + if let Ok(mut sinks) = self.sinks.try_lock() { + for (_, sink) in sinks.iter_mut() { + sink.write(samples); + } + } + } + + /// Hand `frames` samples of silence to every consumer. + pub fn publish_silence(&self, publisher: u64, frames: usize) { + if !self.is_active() || frames == 0 || !self.follows(publisher) { + return; + } + if let Ok(mut sinks) = self.sinks.try_lock() { + for (_, sink) in sinks.iter_mut() { + sink.silence(frames); + } + } + } +} + +/// Detaches its consumer when dropped. +pub struct TapGuard<'a> { + tap: &'a Tap, + id: u64, +} + +impl Drop for TapGuard<'_> { + fn drop(&mut self) { + self.tap.detach(self.id); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + #[derive(Clone, Default)] + struct Collect(Arc>>); + + impl TapSink for Collect { + fn write(&mut self, samples: &[f32]) { + self.0.lock().unwrap().extend_from_slice(samples); + } + + fn silence(&mut self, frames: usize) { + self.0.lock().unwrap().extend(std::iter::repeat_n(0.0, frames)); + } + } + + #[test] + fn consumers_attach_and_detach() { + let tap = Tap::new(); + let (a, b) = (publisher_id(), publisher_id()); + assert!(!tap.is_active()); + tap.publish(a, &[1.0]); + let first = Collect::default(); + let guard = tap.attach(Box::new(first.clone())); + assert!(tap.is_active()); + tap.publish(a, &[0.5, 0.25]); + tap.publish_silence(a, 2); + // Another publisher is ignored while the first is live. + tap.publish(b, &[9.0]); + let second = Collect::default(); + let guard2 = tap.attach(Box::new(second.clone())); + tap.publish(a, &[0.125]); + drop(guard); + tap.publish(a, &[0.0625]); + assert_eq!(*first.0.lock().unwrap(), [0.5, 0.25, 0.0, 0.0, 0.125]); + assert_eq!(*second.0.lock().unwrap(), [0.125, 0.0625]); + drop(guard2); + assert!(!tap.is_active()); + } + + #[test] + fn a_silent_publisher_hands_over() { + let tap = Tap::new(); + let (a, b) = (publisher_id(), publisher_id()); + let sink = Collect::default(); + let _guard = tap.attach(Box::new(sink.clone())); + tap.publish(a, &[1.0]); + tap.publish(b, &[2.0]); + std::thread::sleep(HANDOVER + Duration::from_millis(20)); + tap.publish(b, &[3.0]); + tap.publish(a, &[4.0]); + assert_eq!(*sink.0.lock().unwrap(), [1.0, 3.0]); + } +} diff --git a/crates/voelin-core/src/audio.rs b/crates/voelin-core/src/audio.rs index 0bc55d2..5d4602f 100644 --- a/crates/voelin-core/src/audio.rs +++ b/crates/voelin-core/src/audio.rs @@ -20,6 +20,7 @@ use tsclientlib::ClientId; use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket}; use voelin_audio::pcm::{self, FRAME_SAMPLES}; use voelin_audio::settings::TransmitMode; +use voelin_audio::tap; use voelin_audio::vad::SILENCE_DB; use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder}; @@ -145,6 +146,10 @@ struct Pipeline { /// Watched streams whose audio plays through the mixer. streams: HashMap, stream_volumes: HashMap, + /// Where processed microphone audio is published (for our screen + /// share's microphone source), and our id as its publisher. + mic_tap: &'static tap::Tap, + tap_id: u64, /// Processed microphone audio, for tests. #[cfg(test)] tap: Vec, @@ -168,6 +173,8 @@ impl Pipeline { level_peak: None, streams: HashMap::new(), stream_volumes: HashMap::new(), + mic_tap: tap::microphone(), + tap_id: tap::publisher_id(), settings, #[cfg(test)] tap: Vec::new(), @@ -276,6 +283,15 @@ impl Pipeline { self.processor.capture(samples, &mut self.processed); #[cfg(test)] self.tap.extend_from_slice(&self.processed); + // Our screen share's microphone source; one atomic load when unused. + let mic = self.mic_tap; + if mic.is_active() { + if self.input_muted { + mic.publish_silence(self.tap_id, self.processed.len()); + } else { + mic.publish(self.tap_id, &self.processed); + } + } let mut frames = Vec::new(); self.framer.push(&self.processed, |f| frames.push(f.to_vec())); for frame in frames { @@ -576,6 +592,41 @@ mod tests { assert_eq!(capture(&mut p, &tone), (0, 0)); } + /// The processed microphone reaches tap consumers (silence while muted, + /// whatever the transmit mode), and nothing is done without one. + #[test] + fn processed_microphone_reaches_the_tap() { + use std::sync::{Arc, Mutex}; + + static TAP: tap::Tap = tap::Tap::new(); + struct Sink(Arc>>); + impl tap::TapSink for Sink { + fn write(&mut self, samples: &[f32]) { + self.0.lock().unwrap().extend_from_slice(samples); + } + fn silence(&mut self, frames: usize) { + self.0.lock().unwrap().extend(std::iter::repeat_n(0.0, frames)); + } + } + + let mut p = pipeline(TransmitMode::PushToTalk); + p.mic_tap = &TAP; + let tone = sine(440.0, 0.1, 0.3); + capture(&mut p, &tone); + let got = Arc::new(Mutex::new(Vec::new())); + let guard = TAP.attach(Box::new(Sink(got.clone()))); + // Not transmitting (push-to-talk released): still tapped. + assert_eq!(capture(&mut p, &tone), (0, 0)); + assert_eq!(*got.lock().unwrap(), tone); + p.handle(AudioIn::InputMuted(true)); + capture(&mut p, &tone); + let got_now = got.lock().unwrap().clone(); + assert_eq!(got_now.len(), 2 * tone.len()); + assert!(got_now[tone.len()..].iter().all(|s| *s == 0.0)); + drop(guard); + assert!(!TAP.is_active()); + } + #[test] fn voice_activation_with_pre_roll() { let mut p = pipeline(TransmitMode::VoiceActivation); diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3d338d1..ba9a446 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -1,17 +1,19 @@ //! Stream media (feature `media`): capture and encoding for our stream, //! decoding for the streams we watch. //! -//! - [`Streamer`] captures a screen or window (and optionally system audio), -//! encodes the video with the codec our offer carries ([`stream_codec`], -//! VP8 by default) in one or more simulcast layers ([`LayerSpec`]), and -//! the audio with Opus (48 kHz stereo, 20 ms). Capture, conversion and -//! each layer's encoder run on threads of their own, connected by -//! latest-wins handoffs. It hands the frames to a [`MediaSink`]: the -//! [`StreamSink`] of a live stream, or an [`EncodedSource`] for code that -//! drives `voelin_stream::Streams` itself. Keyframe requests of viewers -//! are honoured per layer, and each layer's encoder follows the bitrate -//! the sink allows. [`Streamer::reconfigure`] changes frame rate, -//! bitrate, codec and layers while streaming. +//! - [`Streamer`] captures a screen or window, encodes the video with the +//! codec our offer carries ([`stream_codec`], VP8 by default) in one or +//! more simulcast layers ([`LayerSpec`]), and mixes any number of audio +//! sources ([`AudioSourceSpec`]: desktop audio without Voelin's own +//! playback, single applications, the shared window's application, the +//! microphone) into Opus (48 kHz stereo, 20 ms). Capture, conversion, +//! each layer's encoder and the audio mixer run on threads of their own. +//! It hands the frames to a [`MediaSink`]: the [`StreamSink`] of a live +//! stream, or an [`EncodedSource`] for code that drives +//! `voelin_stream::Streams` itself. Keyframe requests of viewers are +//! honoured per layer, and each layer's encoder follows the bitrate the +//! sink allows. [`Streamer::reconfigure`] changes frame rate, bitrate, +//! codec, layers and audio sources while streaming. //! - [`VideoPipeline`] decodes the video of a watched stream on its own //! thread and hands every picture to a callback. After lost frames or //! decoder errors it skips to the next keyframe and asks for one. @@ -34,25 +36,29 @@ use std::thread::JoinHandle; use std::time::{Duration, Instant}; use tracing::{debug, warn}; +use voelin_audio::tap::{self, TapGuard, TapSink}; use voelin_audio::{VoiceCodec, VoiceEncoder}; pub use voelin_media; +use voelin_media::capture::playback::{self, PlaybackFilter, SourceCapture}; +pub use voelin_media::capture::playback::{AppMatch, AudioApp, AudioApps}; pub use voelin_media::capture::synthetic::Pattern; use voelin_media::capture::synthetic::{SineSource, SyntheticScreen}; use voelin_media::capture::{ - self, AudioCapture, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, - SourceId, + self, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, SourceId, }; use voelin_media::handoff::Handoff; -use voelin_media::scale::Pyramid; -use voelin_media::{ - AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, FrameRef, VideoEncoder, - VideoFrame, +use voelin_media::mix::{ + BlockClock, MIX_RATE, MixerConfig, MixerHandle, SourceHandle, SourceInput, StreamMixer, }; +pub use voelin_media::mix::{Level, SourceState}; +use voelin_media::scale::Pyramid; +use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame}; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, }; +use crate::settings::{AudioSourceKindSetting, AudioSourceSetting}; use crate::stream::StreamSink; use crate::{Command, Engine, SessionId}; @@ -233,6 +239,150 @@ impl std::str::FromStr for CaptureBackend { } } +/// What an audio source of our stream captures. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum AudioSourceKind { + /// Everything that plays except this process and its children (the + /// voices and streams we play): PipeWire links from every other + /// playback stream, WASAPI process loopback excluding our process tree, + /// Android playback capture excluding our uid. + DesktopWithoutSelf, + /// One application (see [`AppMatch`]; [`audio_apps`] lists them). + App(AppMatch), + /// The application that owns the shared window ([`SourceId::Window`]), + /// where the platform tells: X11 `_NET_WM_PID`, the owner of a Windows + /// `HWND`. The ScreenCast portal (Wayland) does not say whose window it + /// shares: pick the application from [`audio_apps`] instead. + WindowAudio, + /// Our microphone as the voice connection sends it (after noise + /// suppression and gain control), while a voice connection runs. + Microphone, + /// A quiet sine tone of this many Hz (tests, the test pattern). + Synthetic { hz: u32 }, +} + +impl AudioSourceKind { + /// A name for the mixer and the UI. + pub fn label(&self) -> String { + match self { + AudioSourceKind::DesktopWithoutSelf => "Desktop audio (without Voelin)".into(), + AudioSourceKind::App(app) => format!("App: {app}"), + AudioSourceKind::WindowAudio => "Audio of the shared window".into(), + AudioSourceKind::Microphone => "Microphone".into(), + AudioSourceKind::Synthetic { hz } => format!("Test tone {hz} Hz"), + } + } +} + +/// One audio source of a stream, with its gain and mute. Compared bit for +/// bit (`gain` by its bits), so it is `Eq`. +#[derive(Clone, Debug)] +pub struct AudioSourceSpec { + pub kind: AudioSourceKind, + /// Linear gain (1: unchanged), any value >= 0. + pub gain: f32, + pub muted: bool, +} + +impl PartialEq for AudioSourceSpec { + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + && self.gain.to_bits() == other.gain.to_bits() + && self.muted == other.muted + } +} + +impl Eq for AudioSourceSpec {} + +impl AudioSourceSpec { + /// At gain 1, not muted. + pub fn new(kind: AudioSourceKind) -> Self { + Self { kind, gain: 1.0, muted: false } + } +} + +impl From<&AudioSourceSetting> for AudioSourceSpec { + fn from(setting: &AudioSourceSetting) -> Self { + let kind = match &setting.kind { + AudioSourceKindSetting::Desktop => AudioSourceKind::DesktopWithoutSelf, + // A pid wins: it names one process exactly. + AudioSourceKindSetting::App { pid: Some(pid), .. } => { + AudioSourceKind::App(AppMatch::Pid(*pid)) + } + AudioSourceKindSetting::App { name, pid: None } => { + AudioSourceKind::App(AppMatch::Name(name.clone().unwrap_or_default())) + } + AudioSourceKindSetting::Window => AudioSourceKind::WindowAudio, + AudioSourceKindSetting::Microphone => AudioSourceKind::Microphone, + AudioSourceKindSetting::Synthetic { frequency } => { + AudioSourceKind::Synthetic { hz: *frequency } + } + }; + Self { kind, gain: setting.gain, muted: setting.muted } + } +} + +impl From<&AudioSourceSpec> for AudioSourceSetting { + fn from(spec: &AudioSourceSpec) -> Self { + let kind = match &spec.kind { + AudioSourceKind::DesktopWithoutSelf => AudioSourceKindSetting::Desktop, + AudioSourceKind::App(AppMatch::Pid(pid)) => { + AudioSourceKindSetting::App { name: None, pid: Some(*pid) } + } + AudioSourceKind::App(AppMatch::Name(name)) => { + AudioSourceKindSetting::App { name: Some(name.clone()), pid: None } + } + AudioSourceKind::WindowAudio => AudioSourceKindSetting::Window, + AudioSourceKind::Microphone => AudioSourceKindSetting::Microphone, + AudioSourceKind::Synthetic { hz } => { + AudioSourceKindSetting::Synthetic { frequency: *hz } + } + }; + Self { kind, gain: spec.gain, muted: spec.muted } + } +} + +/// The sources of `settings::STREAM_AUDIO_SOURCES` as [`AudioSourceSpec`]s +/// (for [`StreamerConfig::audio_sources`]; empty: no audio). +pub fn audio_source_specs(settings: &[AudioSourceSetting]) -> Vec { + settings.iter().map(AudioSourceSpec::from).collect() +} + +/// The audio of a stream when none is chosen: a tone with the test +/// pattern, else desktop audio without Voelin. +pub fn default_audio_sources(source: &SourceId) -> Vec { + let kind = match source { + SourceId::Synthetic => AudioSourceKind::Synthetic { hz: 440 }, + _ => AudioSourceKind::DesktopWithoutSelf, + }; + vec![AudioSourceSpec::new(kind)] +} + +/// Applications that play audio now (Android: launchable apps), updated +/// live, for a picker of [`AudioSourceKind::App`]. +pub fn audio_apps() -> Result { + Ok(playback::audio_apps()?) +} + +/// One audio source in [`StreamerStats`]. +#[derive(Clone, Debug, PartialEq)] +pub struct AudioSourceStats { + /// The mixer's id of the source. + pub id: u64, + pub spec: AudioSourceSpec, + pub name: String, + /// After its gain, before its mute. + pub level: Level, + pub state: SourceState, + /// How far behind its capture it is mixed. + pub latency: Duration, + /// Times its capture delivered too late (and the audio broke up). + pub underruns: u64, + /// Why it captures nothing (no PipeWire, the window's process unknown, + /// ...). + pub error: Option, +} + /// What and how to stream. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StreamerConfig { @@ -247,8 +397,12 @@ pub struct StreamerConfig { pub bitrate_kbps: u32, /// The codec of our offer, see [`stream_codec`]. pub codec: Codec, - /// Capture and send system audio (a sine tone with the test pattern). + /// Send audio: [`audio_sources`](Self::audio_sources) mixed. pub audio: bool, + /// Audio sources mixed into the stream (any number); empty: the + /// [`default_audio_sources`] (a tone with the test pattern, else desktop + /// audio without Voelin). [`Streamer::reconfigure`] changes them live. + pub audio_sources: Vec, pub cursor: bool, /// Size of the test pattern ([`SourceId::Synthetic`]). pub synthetic_size: (u32, u32), @@ -271,6 +425,7 @@ impl Default for StreamerConfig { bitrate_kbps: 4608, codec: Codec::Vp8, audio: true, + audio_sources: Vec::new(), cursor: true, synthetic_size: (1280, 720), synthetic_pattern: Pattern::Simple, @@ -305,6 +460,10 @@ pub struct StreamerConfigUpdate { /// Another set of layers (`Some(vec![])`: back to a single layer). Layers /// keep their encoder when their id stays; new ids get new encoders. pub layers: Option>, + /// Other audio sources. Sources whose kind stays keep their capture and + /// just take the new gain and mute; new kinds start capturing, removed + /// ones stop. `Some(vec![])` silences the audio (the track stays). + pub audio_sources: Option>, } /// One simulcast layer in [`StreamerStats`]. Rates are over the last second. @@ -358,6 +517,11 @@ pub struct StreamerStats { pub convert_threads: usize, pub codec: Option, pub layers: Vec, + /// Level of the stream's audio (after the limiter). + pub audio_level: Level, + /// The limiter's lowest gain in the last 20 ms (1: not limiting). + pub audio_limiter: f32, + pub audio_sources: Vec, } /// One simulcast layer while streaming: its encoder thread's inbox and @@ -563,15 +727,23 @@ fn new_encoder( /// buffers). Each layer's newest frame goes through a one-slot handoff to /// that layer's encoder thread; a frame an encoder was too busy for is /// replaced, not queued. +/// +/// Audio sources feed a [`StreamMixer`] from their capture threads; the +/// mixer runs every 20 ms on a thread of its own and its output is encoded +/// with Opus. pub struct Streamer { shared: Arc, screen: Option>, - audio: Option>, + /// The video source (for [`AudioSourceKind::WindowAudio`]). + source: SourceId, + // Boxed: a `Streamer` is held inline by previews. + audio: Mutex>>, threads: Vec>, /// Encoder threads, by layer. encoders: Mutex)>>, backend: &'static str, restore_token: Option, + /// Why the audio did not start at all. audio_error: Option, } @@ -587,7 +759,8 @@ impl Streamer { let mut streamer = Self { shared: shared.clone(), screen: None, - audio: None, + source: config.source.clone(), + audio: Mutex::new(None), threads: Vec::new(), encoders: Mutex::new(Vec::new()), backend: "", @@ -643,13 +816,13 @@ impl Streamer { streamer.screen = Some(screen); streamer.restore_token = restore_token; if config.audio { - match start_audio(&config.source) { - Ok((capture, buffers, encoder)) => { - streamer.audio = Some(capture); - streamer.threads.push(spawn("voelin-stream-audio", move || { - audio_loop(&shared, buffers, encoder) - })?); - } + let sources = if config.audio_sources.is_empty() { + default_audio_sources(&config.source) + } else { + config.audio_sources.clone() + }; + match StreamAudio::start(&shared, &config.source, sources) { + Ok(audio) => *lock(&streamer.audio) = Some(Box::new(audio)), Err(e) => { warn!("streaming without audio: {e}"); streamer.audio_error = Some(e.to_string()); @@ -674,11 +847,15 @@ impl Streamer { Ok(()) } - /// Change frame rate, bitrate, codec or layers while streaming, without - /// restarting the capture; applies from the next frame. A new codec - /// gets new encoders, which start with a keyframe; new layers get new - /// encoders; removed layers stop. Fails without changing anything if an - /// encoder cannot be created. + /// Change frame rate, bitrate, codec, layers or audio sources while + /// streaming, without restarting the capture; applies from the next + /// frame. A new codec gets new encoders, which start with a keyframe; + /// new layers get new encoders; removed layers stop. Fails without + /// changing anything if an encoder cannot be created. Audio sources + /// that cannot capture (e.g. an application that is not running by pid) + /// do not fail the update: their [`AudioSourceStats::error`] says why. + /// Audio sources on a streamer started without audio start the audio + /// track. pub fn reconfigure( &self, codecs: &Codecs, @@ -752,6 +929,17 @@ impl Streamer { for thread in finished { let _ = thread.join(); } + if let Some(sources) = update.audio_sources { + let mut audio = lock(&self.audio); + match audio.as_mut() { + Some(audio) => audio.apply(sources), + None if !sources.is_empty() => { + let started = StreamAudio::start(&self.shared, &self.source, sources)?; + *audio = Some(Box::new(started)); + } + None => {} + } + } debug!(?removed, codec_changed, "stream reconfigured"); Ok(()) } @@ -776,14 +964,28 @@ impl Streamer { self.restore_token.as_deref() } - /// Why system audio is not captured, if it was asked for. - pub fn audio_error(&self) -> Option<&str> { - self.audio_error.as_deref() + /// Why there is no audio, or which audio sources capture nothing and why. + pub fn audio_error(&self) -> Option { + self.audio_error.clone().or_else(|| lock(&self.audio).as_ref().and_then(|a| a.error())) } - /// Whether system audio is captured. + /// Whether the stream has audio (mixed from its audio sources). pub fn has_audio(&self) -> bool { - self.audio.is_some() + lock(&self.audio).is_some() + } + + /// The audio mixer, for lock-free level meters + /// ([`MixerHandle::level`], each source's `level`) and direct control. + pub fn audio_mixer(&self) -> Option { + lock(&self.audio).as_ref().map(|a| a.mixer.clone()) + } + + /// The audio sources now. + pub fn audio_sources(&self) -> Vec { + lock(&self.audio) + .as_ref() + .map(|a| a.active.iter().map(|s| s.spec.clone()).collect()) + .unwrap_or_default() } /// The ids of the layers being encoded. @@ -793,6 +995,7 @@ impl Streamer { pub fn stats(&self) -> StreamerStats { let shared = &self.shared; + let audio = lock(&self.audio); let size = shared.size.load(Ordering::Relaxed); let codec = lock(&shared.settings).as_ref().map(|s| s.codec); let rates = lock(&shared.rates); @@ -836,6 +1039,9 @@ impl Streamer { convert_threads: shared.convert_threads.load(Ordering::Relaxed), codec, layers, + audio_level: audio.as_ref().map(|a| a.mixer.level()).unwrap_or_default(), + audio_limiter: audio.as_ref().map_or(1.0, |a| a.mixer.limiter_gain()), + audio_sources: audio.as_ref().map(|a| a.stats()).unwrap_or_default(), } } @@ -846,7 +1052,8 @@ impl Streamer { if let Some(mut screen) = self.screen.take() { screen.stop(); } - if let Some(mut audio) = self.audio.take() { + let audio = lock(&self.audio).take(); + if let Some(audio) = audio { audio.stop(); } for layer in lock(&self.shared.layers).iter() { @@ -913,17 +1120,175 @@ fn screen_backend(backend: &CaptureBackend) -> Result, Me }) } -type AudioStart = (Box, FrameReceiver, VoiceEncoder); +/// The stream's audio: the mixer (running on its own thread) and the +/// captures feeding its sources. +struct StreamAudio { + mixer: MixerHandle, + /// The video source, for [`AudioSourceKind::WindowAudio`]. + video: SourceId, + active: Vec, + thread: Option>, +} -fn start_audio(source: &SourceId) -> Result { - let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?; - encoder.set_bitrate(OPUS_BITRATE)?; - let mut capture: Box = match source { - SourceId::Synthetic => Box::new(SineSource::new(440.0, 0.05)), - _ => capture::default_audio_capture()?, - }; - let buffers = capture.start()?; - Ok((capture, buffers, encoder)) +/// An audio source in the mixer and what feeds it. +struct ActiveSource { + spec: AudioSourceSpec, + handle: SourceHandle, + _feed: Option, + error: Option, +} + +impl Drop for ActiveSource { + fn drop(&mut self) { + // Its captures see the input close and stop. + self.handle.remove(); + } +} + +/// What feeds a source; stops when dropped. +enum Feed { + Capture(#[allow(dead_code)] Box), + Microphone(#[allow(dead_code)] TapGuard<'static>), +} + +/// Processed microphone audio (48 kHz mono) into a mixer input. +struct MicrophoneInput(SourceInput); + +impl TapSink for MicrophoneInput { + fn write(&mut self, samples: &[f32]) { + self.0.push(samples, 1); + } + + fn silence(&mut self, frames: usize) { + self.0.push_silence(frames); + } +} + +impl StreamAudio { + /// Start the mixer thread and `sources`. + fn start( + shared: &Arc, + video: &SourceId, + sources: Vec, + ) -> Result { + let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?; + encoder.set_bitrate(OPUS_BITRATE)?; + let mixer = + StreamMixer::new(MixerConfig { max_block: OPUS_FRAME, ..MixerConfig::default() }); + let handle = mixer.handle(); + let thread = spawn("voelin-stream-audio", { + let shared = shared.clone(); + move || audio_loop(&shared, mixer, encoder) + })?; + let mut audio = + Self { mixer: handle, video: video.clone(), active: Vec::new(), thread: Some(thread) }; + audio.apply(sources); + Ok(audio) + } + + /// Make the sources `specs`: kinds that stay keep their capture and + /// take the new gain and mute, new ones start, the rest stop. + fn apply(&mut self, specs: Vec) { + let mut old: Vec> = self.active.drain(..).map(Some).collect(); + let mut next = Vec::with_capacity(specs.len()); + for spec in specs { + let same = + old.iter().position(|o| o.as_ref().is_some_and(|a| a.spec.kind == spec.kind)); + match same.and_then(|i| old[i].take()) { + Some(mut source) => { + source.handle.set_gain(spec.gain); + source.handle.set_muted(spec.muted); + source.spec = spec; + next.push(source); + } + None => next.push(self.start_source(spec)), + } + } + drop(old); + self.active = next; + } + + fn start_source(&self, spec: AudioSourceSpec) -> ActiveSource { + let handle = self.mixer.add_source(spec.kind.label()); + handle.set_gain(spec.gain); + handle.set_muted(spec.muted); + let (feed, error) = match self.feed(&spec.kind, &handle) { + Ok(feed) => (Some(feed), None), + Err(e) => { + warn!("stream audio source {}: {e}", spec.kind.label()); + (None, Some(e)) + } + }; + ActiveSource { spec, handle, _feed: feed, error } + } + + fn feed(&self, kind: &AudioSourceKind, handle: &SourceHandle) -> Result { + let playback = |filter: PlaybackFilter| { + playback::start_playback(&filter, handle).map(Feed::Capture).map_err(|e| e.to_string()) + }; + match kind { + AudioSourceKind::DesktopWithoutSelf => playback(PlaybackFilter::AllButSelf), + AudioSourceKind::App(app) => playback(PlaybackFilter::App(app.clone())), + AudioSourceKind::WindowAudio => { + let SourceId::Window(window) = self.video else { + return Err("no window is shared; pick the application instead".into()); + }; + let pid = playback::window_pid(window).ok_or( + "the shared window's process is unknown here; pick the application instead", + )?; + playback(PlaybackFilter::App(AppMatch::Pid(pid))) + } + AudioSourceKind::Microphone => { + let input = MicrophoneInput(handle.input(MIX_RATE)); + Ok(Feed::Microphone(tap::microphone().attach(Box::new(input)))) + } + AudioSourceKind::Synthetic { hz } => { + let tone = SineSource::new(*hz as f32, 0.05); + playback::forward_audio(Box::new(tone), handle) + .map(Feed::Capture) + .map_err(|e| e.to_string()) + } + } + } + + /// The sources that capture nothing, and why. + fn error(&self) -> Option { + let errors: Vec = self + .active + .iter() + .filter_map(|s| s.error.as_ref().map(|e| format!("{}: {e}", s.spec.kind.label()))) + .collect(); + (!errors.is_empty()).then(|| errors.join("; ")) + } + + fn stats(&self) -> Vec { + self.active + .iter() + .map(|s| { + let stats = s.handle.stats(); + AudioSourceStats { + id: s.handle.id(), + spec: s.spec.clone(), + name: s.handle.name().to_owned(), + level: s.handle.level(), + state: stats.state, + latency: stats.latency, + underruns: stats.underruns, + error: s.error.clone(), + } + }) + .collect() + } + + /// Stop the captures and the mixer thread (the streamer's stop flag + /// must be set). + fn stop(mut self) { + self.active.clear(); + if let Some(thread) = self.thread.take() { + thread.thread().unpark(); + let _ = thread.join(); + } + } } /// A layer as the capture thread sees it. @@ -1251,66 +1616,37 @@ fn stats_loop(shared: &Shared) { } } -/// Interleaved stereo from any channel count (extra channels are dropped). -fn append_stereo(buffer: &AudioBuffer, out: &mut Vec) { - match buffer.channels { - 0 => {} - 1 => out.extend(buffer.samples.iter().flat_map(|s| [*s, *s])), - 2 => out.extend_from_slice(&buffer.samples), - n => { - for frame in buffer.samples.chunks_exact(usize::from(n)) { - out.extend_from_slice(&frame[..2]); - } - } - } -} - -fn audio_loop(shared: &Shared, mut buffers: FrameReceiver, mut encoder: VoiceEncoder) { - // Interleaved stereo waiting for a whole Opus frame. - let mut pending: Vec = Vec::new(); - // Opus frames since the capture started: the RTP time in 20 ms steps. - let mut frames: u64 = 0; +/// The mixer thread: every 20 ms (on the monotonic clock) one Opus frame +/// of the mix, encoded while a sink is attached. The RTP time is the +/// frame's number since the start, so it follows real time across +/// silences and stalls. +fn audio_loop(shared: &Shared, mut mixer: StreamMixer, mut encoder: VoiceEncoder) { + let mut clock = BlockClock::new(OPUS_FRAME); + let mut block = vec![0.0f32; OPUS_FRAME * 2]; while !shared.stopped() { - let Some(buffer) = buffers.recv_timeout(POLL) else { - if buffers.is_closed() { - debug!("system audio capture ended"); - break; - } + let now = Instant::now(); + let due = clock.due(now); + if due.is_empty() { + std::thread::park_timeout(clock.next().saturating_duration_since(now).min(POLL)); continue; - }; - // Follow the capture clock across gaps (nothing played, sink not - // attached yet), so audio stays in step with video. - let at = buffer.timestamp.as_micros() as u64 * 48 / 1000; - let position = frames * OPUS_FRAME as u64 + (pending.len() / 2) as u64; - if at > position + 10 * OPUS_FRAME as u64 { - pending.clear(); - frames = at / OPUS_FRAME as u64; } - let Some(sink) = shared.sink() else { continue }; - append_stereo(&buffer, &mut pending); - while pending.len() >= OPUS_FRAME * 2 { - let data: Option> = match encoder.encode_to_bytes(&pending[..OPUS_FRAME * 2]) - { - Ok(data) => Some(data.into()), + for frame in due { + // Mixed even without a sink, so the sources' buffers keep moving. + mixer.mix(&mut block); + let Some(sink) = shared.sink() else { continue }; + let data: Arc<[u8]> = match encoder.encode_to_bytes(&block) { + Ok(data) => data.into(), Err(e) => { warn!("audio encoding failed: {e}"); - None + continue; } }; - pending.drain(..OPUS_FRAME * 2); - if let Some(data) = data { - let time = MediaTime::new(frames * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); - if sink.send(EncodedFrame { - kind: MediaKind::Audio, - time, - data, - layer: 0, - keyframe: false, - }) { - shared.audio_frames.fetch_add(1, Ordering::Relaxed); - } + let time = MediaTime::new(frame * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); + let frame = + EncodedFrame { kind: MediaKind::Audio, time, data, layer: 0, keyframe: false }; + if sink.send(frame) { + shared.audio_frames.fetch_add(1, Ordering::Relaxed); } - frames += 1; } } } @@ -2049,6 +2385,118 @@ mod tests { assert_eq!(source.streamer().layer_ids(), [0, 7]); } + #[test] + fn audio_sources_from_settings() { + use crate::settings::{AudioSourceKindSetting as K, AudioSourceSetting as S}; + let settings = [ + S::new(K::Desktop), + S { gain: 0.5, ..S::new(K::App { name: Some("firefox".into()), pid: None }) }, + S { muted: true, ..S::new(K::App { name: None, pid: Some(42) }) }, + S::new(K::Window), + S::new(K::Microphone), + S::new(K::Synthetic { frequency: 1000 }), + ]; + let specs = audio_source_specs(&settings); + let kinds: Vec = specs.iter().map(|s| s.kind.clone()).collect(); + assert_eq!( + kinds, + [ + AudioSourceKind::DesktopWithoutSelf, + AudioSourceKind::App(AppMatch::Name("firefox".into())), + AudioSourceKind::App(AppMatch::Pid(42)), + AudioSourceKind::WindowAudio, + AudioSourceKind::Microphone, + AudioSourceKind::Synthetic { hz: 1000 }, + ] + ); + assert_eq!((specs[1].gain, specs[2].muted), (0.5, true)); + let back: Vec = specs.iter().map(S::from).collect(); + assert_eq!(back, settings); + assert_eq!( + default_audio_sources(&SourceId::Monitor(0)), + [AudioSourceSpec::new(AudioSourceKind::DesktopWithoutSelf)] + ); + } + + /// Audio sources mixed, then changed while streaming: gain, mute, one + /// removed, the microphone added; levels in the stats follow. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn audio_sources_change_live() { + let codecs = Codecs::new(); + let tone = |hz| AudioSourceSpec::new(AudioSourceKind::Synthetic { hz }); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (64, 48), + audio_sources: vec![tone(440), AudioSourceSpec { gain: 0.5, ..tone(1000) }], + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let stats = streamer.stats(); + if done(&stats) { + return stats; + } + assert!(Instant::now() < deadline, "{what}: {:#?}", stats.audio_sources); + std::thread::sleep(Duration::from_millis(20)); + } + }; + // The SineSource tone is 0.05; the second at half gain. + let near = |level: f32, want: f32| (level - want).abs() < want * 0.1; + let stats = wait("both tones", &|s| { + s.audio_sources.len() == 2 + && near(s.audio_sources[0].level.peak, 0.05) + && near(s.audio_sources[1].level.peak, 0.025) + }); + assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing)); + assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}"); + let first = stats.audio_sources[0].id; + + // Mute the first (kept: same id), drop the second, add the + // microphone and a window source (the pattern is no window). + let update = StreamerConfigUpdate { + audio_sources: Some(vec![ + AudioSourceSpec { muted: true, ..tone(440) }, + AudioSourceSpec::new(AudioSourceKind::Microphone), + AudioSourceSpec::new(AudioSourceKind::WindowAudio), + ]), + ..StreamerConfigUpdate::default() + }; + streamer.reconfigure(&codecs, update).unwrap(); + assert_eq!(streamer.audio_sources().len(), 3); + let publisher = tap::publisher_id(); + let speak = std::thread::spawn(move || { + // 20 ms of a 0.2 tone every 20 ms, for a second. + let chunk: Vec = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect(); + for _ in 0..50 { + tap::microphone().publish(publisher, &chunk); + std::thread::sleep(Duration::from_millis(20)); + } + }); + let stats = wait("microphone in, tone muted", &|s| { + s.audio_sources.len() == 3 + && s.audio_sources[1].level.peak > 0.15 + && s.audio_level.peak > 0.15 + }); + speak.join().unwrap(); + assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source"); + assert!(stats.audio_sources[0].spec.muted); + // Muted sources are still metered. + assert!(near(stats.audio_sources[0].level.peak, 0.05), "{stats:?}"); + let window = &stats.audio_sources[2]; + assert!(window.error.as_deref().is_some_and(|e| e.contains("no window")), "{window:?}"); + assert!(streamer.audio_error().is_some_and(|e| e.contains("shared window"))); + assert!(streamer.audio_mixer().is_some()); + + // All sources gone: silence, the track stays. + let update = StreamerConfigUpdate { audio_sources: Some(Vec::new()), ..Default::default() }; + streamer.reconfigure(&codecs, update).unwrap(); + wait("silence", &|s| s.audio_sources.is_empty() && s.audio_level.peak < 0.01); + assert!(streamer.has_audio()); + } + /// Audio of the test pattern: 20 ms Opus frames on a 48 kHz clock. #[cfg(feature = "media-desktop")] #[tokio::test(flavor = "multi_thread")] diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index f888c18..025d35e 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1096,8 +1096,91 @@ pub static CHAT_RETENTION_DAYS: Key = Key::new( || 0, ); +/// What an audio source of our stream captures, as stored; see +/// [`AudioSourceSetting`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum AudioSourceKindSetting { + /// Everything that plays except Voelin itself (voices, watched streams). + Desktop, + /// One application: by `name` (application name or executable; the + /// package on Android), found again when it restarts, or by `pid` + /// (valid while that process runs). + App { + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pid: Option, + }, + /// The application of the shared window, where the platform tells + /// (X11, Windows). + Window, + /// Our microphone after noise suppression and gain control. + Microphone, + /// A test tone. + Synthetic { + #[serde(default = "default_tone")] + frequency: u32, + }, +} + +fn default_tone() -> u32 { + 440 +} + +fn unity() -> f32 { + 1.0 +} + +/// One audio source mixed into our stream. The serde form: +/// `{"kind": "desktop"}`, `{"kind": "app", "name": "firefox", "gain": 0.5}`, +/// `{"kind": "microphone", "muted": true}`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AudioSourceSetting { + #[serde(flatten)] + pub kind: AudioSourceKindSetting, + /// Linear gain (1: unchanged), any value >= 0. + #[serde(default = "unity")] + pub gain: f32, + #[serde(default)] + pub muted: bool, +} + +impl AudioSourceSetting { + pub fn new(kind: AudioSourceKindSetting) -> Self { + Self { kind, gain: 1.0, muted: false } + } +} + +#[allow(clippy::ptr_arg)] // a validation of `Key>` is `fn(&Vec<_>)` +fn valid_audio_sources(sources: &Vec) -> Result<(), String> { + for (i, source) in sources.iter().enumerate() { + if !(source.gain.is_finite() && source.gain >= 0.0) { + return Err(format!("source {i}: gain must be a number >= 0")); + } + if let AudioSourceKindSetting::App { name, pid } = &source.kind + && name.as_deref().is_none_or(|n| n.trim().is_empty()) + && pid.is_none() + { + return Err(format!("source {i}: an app needs a name or a pid")); + } + } + Ok(()) +} + +/// Audio sources mixed into our stream (read when a stream starts; a +/// running stream follows through `media::Streamer::reconfigure`). Empty: +/// the stream has no audio. +pub static STREAM_AUDIO_SOURCES: Key> = Key::new( + "stream.audio_sources", + Kind::Json, + "Audio sources mixed into our stream (desktop, app, window, microphone).", + || vec![AudioSourceSetting::new(AudioSourceKindSetting::Desktop)], +) +.validated(valid_audio_sources); + /// The keys every [`Settings`] knows from the start. -pub fn builtin_keys() -> [&'static dyn Setting; 15] { +pub fn builtin_keys() -> [&'static dyn Setting; 16] { [ &CRASH_REPORTS, &AUDIO, @@ -1114,6 +1197,7 @@ pub fn builtin_keys() -> [&'static dyn Setting; 15] { &CHAT_HISTORY_PAGE, &CHAT_DEDUPE_TOLERANCE_MS, &CHAT_RETENTION_DAYS, + &STREAM_AUDIO_SOURCES, ] } @@ -1232,6 +1316,57 @@ mod tests { assert_eq!(s.get(&STREAM_BITRATE_KBPS), u32::MAX); } + #[test] + fn audio_sources() { + let s = Settings::in_memory(); + assert_eq!( + s.get(&STREAM_AUDIO_SOURCES), + [AudioSourceSetting::new(AudioSourceKindSetting::Desktop)] + ); + assert_eq!( + s.get_json("stream.audio_sources"), + Some(json!([{"kind": "desktop", "gain": 1.0, "muted": false}])) + ); + s.set_json( + "stream.audio_sources", + json!([ + {"kind": "desktop", "gain": 0.5}, + {"kind": "app", "name": "firefox"}, + {"kind": "app", "pid": 4242, "muted": true}, + {"kind": "window"}, + {"kind": "microphone", "gain": 2}, + {"kind": "synthetic"} + ]), + ) + .unwrap(); + let sources = s.get(&STREAM_AUDIO_SOURCES); + assert_eq!(sources.len(), 6); + assert_eq!(sources[0].gain, 0.5); + assert_eq!( + sources[1].kind, + AudioSourceKindSetting::App { name: Some("firefox".into()), pid: None } + ); + assert!(sources[2].muted); + assert_eq!( + sources[4], + AudioSourceSetting { + gain: 2.0, + ..AudioSourceSetting::new(AudioSourceKindSetting::Microphone) + } + ); + assert_eq!(sources[5].kind, AudioSourceKindSetting::Synthetic { frequency: 440 }); + let invalid = + |r: Result<(), SettingsError>| matches!(r, Err(SettingsError::Invalid { .. })); + assert!(invalid(s.set_json("stream.audio_sources", json!([{"kind": "app"}])))); + assert!(invalid( + s.set_json("stream.audio_sources", json!([{"kind": "desktop", "gain": -1}])) + )); + assert!(invalid(s.set_json("stream.audio_sources", json!([{"kind": "speakers"}])))); + // No sources: no audio. + s.set_json("stream.audio_sources", json!([])).unwrap(); + assert!(s.get(&STREAM_AUDIO_SOURCES).is_empty()); + } + #[test] fn layers_convert_to_specs() { let s = Settings::in_memory(); diff --git a/crates/voelin-core/tests/media_live.rs b/crates/voelin-core/tests/media_live.rs index a4519db..3226768 100644 --- a/crates/voelin-core/tests/media_live.rs +++ b/crates/voelin-core/tests/media_live.rs @@ -159,7 +159,11 @@ async fn ts6_test_pattern_decoded() { assert!(widths.iter().all(|w| (120..=136).contains(w)), "{widths:?}"); let stats = viewer.stats(); assert!(stats.error.is_none(), "{stats:?}"); - eprintln!("decoded {stats:?}, sent {:?}", streamer.stats()); + // The mixed test tone went out as 20 ms Opus frames all along. + let sent = streamer.stats(); + eprintln!("decoded {stats:?}, sent {sent:?}"); + assert!(sent.audio_frames >= 50, "{sent:?}"); + assert!(sent.audio_sources.iter().all(|s| s.error.is_none()), "{sent:?}"); engine.send(Command::StopStream { session: 1 }); wait_for(&mut events, "stream ended", |e| match e { diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 1dccab6..8cf0ede 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -36,6 +36,8 @@ dav1d = { version = "0.11.1", optional = true } libvpx-native-sys = { version = "5.0.17", optional = true } openh264 = { version = "0.9.8", default-features = false, features = ["libloading"], optional = true } reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true } +# Lock-free single-producer rings from capture threads to the stream mixer. +rtrb = "0.4.0" sha2 = { version = "0.10.9", optional = true } str0m = { version = "0.23.1", default-features = false, optional = true } thiserror = "2.0.21" @@ -58,15 +60,23 @@ ndk = { version = "0.9.0", default-features = false, features = ["media", "api-l [target.'cfg(windows)'.dependencies] wasapi = "0.24.0" +# Process names for the list of applications with audio sessions. +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Threading"] } windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +# Logs of integration tests (`RUST_LOG`). +tracing-subscriber = { version = "0.3", features = ["env-filter"] } tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] } [[bench]] name = "convert" harness = false +[[bench]] +name = "mix" +harness = false + [lints] workspace = true diff --git a/crates/voelin-media/benches/mix.rs b/crates/voelin-media/benches/mix.rs new file mode 100644 index 0000000..5328670 --- /dev/null +++ b/crates/voelin-media/benches/mix.rs @@ -0,0 +1,83 @@ +//! The stream mixer: `cargo bench -p voelin-media --bench mix`. +//! +//! One iteration pushes 20 ms into every source and mixes one 20 ms block +//! (960 frames), as the streamer does 50 times a second. +//! +//! - `mix/48k/`: n stereo sources at 48 kHz (copied through) +//! - `mix/44k1/`: n stereo sources at 44.1 kHz (cubic resampling) +//! - `mix/limited/8`: eight loud sources, the limiter working on every frame + +use std::hint::black_box; +use std::time::Duration; + +use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use voelin_media::mix::{MixerConfig, SourceInput, StreamMixer}; + +const BLOCK: usize = 960; + +/// A mixer with `sources` sources at `rate`, each fed a 20 ms stereo block +/// per iteration. +struct Setup { + mixer: StreamMixer, + inputs: Vec, + /// 20 ms of input at the sources' rate. + block: Vec, + out: Vec, +} + +impl Setup { + fn new(sources: usize, rate: u32, amplitude: f32) -> Self { + let mixer = StreamMixer::new(MixerConfig::default()); + let handle = mixer.handle(); + let inputs = (0..sources).map(|i| handle.add_source(format!("s{i}")).input(rate)).collect(); + let frames = rate as usize / 50; + let block = (0..frames) + .flat_map(|i| { + let s = amplitude * (i as f32 * 0.05).sin(); + [s, -s] + }) + .collect(); + let mut setup = Self { mixer, inputs, block, out: vec![0.0; BLOCK * 2] }; + // Every source past its latency and settled. + for _ in 0..100 { + setup.step(); + } + setup + } + + fn step(&mut self) { + for input in &mut self.inputs { + input.push(&self.block, 2); + } + self.mixer.mix(&mut self.out); + } +} + +fn mixing(c: &mut Criterion) { + let mut group = c.benchmark_group("mix"); + group.sample_size(50).measurement_time(Duration::from_secs(3)); + for (name, rate) in [("48k", 48_000), ("44k1", 44_100)] { + for sources in [1, 4, 16, 64] { + let mut setup = Setup::new(sources, rate, 0.5 / sources as f32); + group.throughput(Throughput::Elements((BLOCK * sources) as u64)); + group.bench_function(BenchmarkId::new(name, sources), |b| { + b.iter(|| { + setup.step(); + black_box(&setup.out); + }); + }); + } + } + let mut setup = Setup::new(8, 48_000, 0.6); + group.throughput(Throughput::Elements((BLOCK * 8) as u64)); + group.bench_function(BenchmarkId::new("limited", 8), |b| { + b.iter(|| { + setup.step(); + black_box(&setup.out); + }); + }); + group.finish(); +} + +criterion_group!(benches, mixing); +criterion_main!(benches); diff --git a/crates/voelin-media/src/capture/external.rs b/crates/voelin-media/src/capture/external.rs index be60731..2d72691 100644 --- a/crates/voelin-media/src/capture/external.rs +++ b/crates/voelin-media/src/capture/external.rs @@ -13,12 +13,14 @@ use std::sync::{Arc, Mutex, PoisonError}; -use crate::Result; +use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, forward_audio}; use crate::capture::{ AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, }; -use crate::frame::{AudioBuffer, VideoFrame}; +use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; +use crate::mix::{SourceHandle, SourceInput}; use crate::queue::{FrameReceiver, FrameSender, frame_channel}; +use crate::{Error, Result}; /// Platform code that captures the screen. pub trait ScreenProvider: Send + Sync { @@ -50,6 +52,63 @@ pub trait AudioProvider: Send + Sync { fn start(&self, buffers: FrameSender) -> Result<()>; fn stop(&self); + + /// Start capturing the playback `filter` selects straight into a mixer + /// input; several captures may run at once. Returns an id for + /// [`stop_input`](Self::stop_input). The default supports none (see + /// [`start_playback`] for the fallback). + fn start_input(&self, filter: &PlaybackFilter, input: SourceInput) -> Result { + let _ = (filter, input); + Err(Error::CaptureUnavailable { + backend: self.name(), + reason: "capturing single applications is not supported".into(), + }) + } + + fn stop_input(&self, id: u64) { + let _ = id; + } + + /// Applications whose playback can be captured (Android: the launchable + /// apps, since it cannot tell which play). + fn apps(&self) -> Vec { + Vec::new() + } +} + +/// A capture of [`AudioProvider::start_input`]; stops it when dropped. +struct ProviderCapture { + provider: Arc, + id: u64, +} + +impl SourceCapture for ProviderCapture { + fn backend(&self) -> &'static str { + self.provider.name() + } +} + +impl Drop for ProviderCapture { + fn drop(&mut self) { + self.provider.stop_input(self.id); + } +} + +/// Capture through `provider` into `source`: [`AudioProvider::start_input`], +/// or for everything but our own playback, providers without it run their +/// plain [`AudioProvider::start`] into the source. +pub fn start_playback( + provider: Arc, + filter: &PlaybackFilter, + source: &SourceHandle, +) -> Result> { + match provider.start_input(filter, source.input(AUDIO_SAMPLE_RATE)) { + Ok(id) => Ok(Box::new(ProviderCapture { provider, id })), + Err(_) if *filter == PlaybackFilter::AllButSelf => { + forward_audio(Box::new(ExternalAudioCapture::new(provider)), source) + } + Err(e) => Err(e), + } } type Slot = Mutex>>; @@ -174,7 +233,6 @@ mod tests { use std::time::Duration; use super::*; - use crate::Error; /// Sends one frame per start, or refuses. #[derive(Default)] diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 4bfaf85..f37ee4d 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -33,6 +33,9 @@ pub mod external; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod pipewire_audio; #[cfg(all(target_os = "linux", feature = "pipewire"))] +pub mod pipewire_links; +pub mod playback; +#[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod portal; #[cfg(all(target_os = "linux", feature = "pipewire"))] mod pw; diff --git a/crates/voelin-media/src/capture/pipewire_links.rs b/crates/voelin-media/src/capture/pipewire_links.rs new file mode 100644 index 0000000..bd1ecc8 --- /dev/null +++ b/crates/voelin-media/src/capture/pipewire_links.rs @@ -0,0 +1,992 @@ +//! Per-application audio capture on PipeWire, by linking playback streams +//! into capture streams of ours. +//! +//! A [`LinkManager`] keeps one PipeWire connection on a thread of its own +//! and watches the registry: clients (process ids and executables), nodes +//! of class `Stream/Output/Audio` (every application's playback stream, +//! with `application.name`, `media.name`, icon name and state) and their +//! ports. +//! +//! Each capture ([`LinkManager::capture`]) is a PipeWire capture stream +//! with `node.autoconnect = false` (the session manager does not link it), +//! 48 kHz stereo `f32` (`FL`, `FR`), whose process callback pushes into a +//! mixer input. The manager links, through the `link-factory`, the output +//! ports of every playback stream the capture's [`PlaybackFilter`] selects +//! to the capture's input ports (mono and centre channels into both, +//! surround channels to their side, LFE left out), and keeps the links in +//! step as streams come and go: a tab that starts playing is linked within +//! a round trip, a stream that ends takes its links with it, and a +//! restarted application is matched again by name. PipeWire sums all links +//! into an input port, so one capture stream carries any number of +//! applications. The links belong to our connection and vanish with it. +//! +//! This rather than one capture stream per application with +//! `target.object`: whether a capture may follow a playback stream is the +//! session manager's policy, which differs between WirePlumber versions, +//! while links we make ourselves need only a session manager that +//! configures stream ports (WirePlumber and media-session do, whether or +//! not a stream is linked). No extra sink or loopback module is needed, the +//! default sink and all volumes stay as they are, and our own voice +//! playback (cpal → ALSA → pipewire-alsa, a client in this process) never +//! reaches the stream. +//! +//! Our own process tree is recognised by process id: a node's +//! `application.process.id`, else its client's `application.process.id`, +//! else the client's `pipewire.sec.pid`, compared with our pid and walked up +//! the `/proc//stat` parent chain (and, without any pid, by our +//! executable's name). In a sandbox with a pid namespace of its own the +//! daemon sees other pids than we do, so the manager's own connection +//! carries a marker property: native clients with that connection's +//! `pipewire.sec.pid` are ours too. A playback stream is linked only once +//! its node and client details have arrived, so our playback is never +//! linked, not even briefly. The playing sides of loopbacks and filters +//! (`node.link-group`) are never linked: what they replay is captured at +//! the applications that played it. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::Path; +use std::rc::{Rc, Weak as RcWeak}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc as std_mpsc; +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::thread::JoinHandle; +use std::time::Duration; + +use pipewire as pw; +use pw::spa::param::audio::{AudioFormat, AudioInfoRaw}; +use pw::spa::pod::{Object, Value}; +use pw::spa::utils::SpaTypes; +use pw::spa::utils::dict::DictRef; +use pw::types::ObjectType; +use tokio::sync::watch; +use tracing::{debug, warn}; + +use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, parent_pid}; +use crate::capture::pw::{pod, serialize}; +use crate::frame::AUDIO_SAMPLE_RATE; +use crate::mix::{SourceHandle, SourceInput}; +use crate::{Error, Result}; + +const BACKEND: &str = "pipewire"; +/// Prefix of our capture nodes' names. +pub const NODE_PREFIX: &str = "voelin-stream-audio"; +/// Samples converted per push (a PipeWire quantum is at most 8192 frames). +const SCRATCH: usize = 8192 * 2; +const PLAYBACK_CLASS: &str = "Stream/Output/Audio"; +/// Client property that marks the manager's own connection, whose +/// `pipewire.sec.pid` is this process as the daemon sees it (the host pid, +/// also inside a sandbox with a pid namespace). +const MARKER: &str = "voelin.link-manager"; + +/// `EPIPE`, what PipeWire reports when the daemon goes away. +fn libc_epipe() -> i32 { + rustix::io::Errno::PIPE.raw_os_error() +} + +fn unavailable(reason: impl Into) -> Error { + Error::CaptureUnavailable { backend: BACKEND, reason: reason.into() } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +enum Command { + Add { + id: u64, + filter: PlaybackFilter, + name: String, + input: SourceInput, + reply: std_mpsc::Sender>, + }, + Remove(u64), + Quit, +} + +/// Registry watcher and link maker on its own PipeWire connection (see the +/// module docs). One per process is enough: [`LinkManager::shared`]. +pub struct LinkManager { + commands: Mutex>, + apps: watch::Receiver>, + alive: Arc, + next_id: AtomicU64, + thread: Option>, +} + +static SHARED: Mutex>> = Mutex::new(None); + +impl LinkManager { + /// The process's manager, connected to the user's PipeWire daemon; a new + /// one when none is alive (or the last one lost its connection). + pub fn shared() -> Result> { + let mut slot = lock(&SHARED); + if let Some(manager) = slot.as_ref().and_then(Weak::upgrade) + && manager.is_alive() + { + return Ok(manager); + } + let manager = Arc::new(Self::connect(None)?); + *slot = Some(Arc::downgrade(&manager)); + Ok(manager) + } + + /// A manager of its own, connected to the daemon listening on `socket` + /// (the path of its `pipewire-0` socket), or the user's daemon. + pub fn connect(socket: Option<&Path>) -> Result { + let (commands, rx) = pw::channel::channel::(); + let (apps_tx, apps) = watch::channel(Vec::new()); + let alive = Arc::new(AtomicBool::new(true)); + let (init_tx, init_rx) = std_mpsc::channel(); + let remote = socket.map(|s| s.to_string_lossy().into_owned()); + let flag = alive.clone(); + let thread = std::thread::Builder::new() + .name("voelin-pipewire-links".into()) + .spawn(move || run(remote, rx, apps_tx, flag, init_tx))?; + let mut manager = Self { + commands: Mutex::new(commands), + apps, + alive, + next_id: AtomicU64::new(1), + thread: Some(thread), + }; + match init_rx.recv() { + Ok(Ok(())) => Ok(manager), + Ok(Err(e)) => { + manager.stop(); + Err(unavailable(e)) + } + Err(_) => { + manager.stop(); + Err(unavailable("the PipeWire thread ended during setup")) + } + } + } + + /// Whether the connection is still up. + pub fn is_alive(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } + + /// Applications with playback streams (not ours), updated live. + pub fn apps(&self) -> watch::Receiver> { + self.apps.clone() + } + + /// Capture the playback `filter` selects into a new input of `source`, + /// until the returned capture is dropped. + pub fn capture( + self: &Arc, + filter: &PlaybackFilter, + source: &SourceHandle, + ) -> Result> { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let input = source.input(AUDIO_SAMPLE_RATE); + let (reply, answer) = std_mpsc::channel(); + let name = source.name().to_owned(); + self.send(Command::Add { id, filter: filter.clone(), name, input, reply })?; + match answer.recv_timeout(Duration::from_secs(5)) { + Ok(Ok(())) => Ok(Box::new(LinkCapture { manager: self.clone(), id })), + Ok(Err(e)) => Err(unavailable(e)), + Err(_) => Err(unavailable("the PipeWire thread did not answer")), + } + } + + fn send(&self, command: Command) -> Result<()> { + lock(&self.commands) + .send(command) + .map_err(|_| unavailable("the PipeWire connection is gone")) + } + + fn stop(&mut self) { + let _ = self.send(Command::Quit); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for LinkManager { + fn drop(&mut self) { + self.stop(); + } +} + +/// One capture of a [`LinkManager`]; removes its stream and links on drop. +struct LinkCapture { + manager: Arc, + id: u64, +} + +impl SourceCapture for LinkCapture { + fn backend(&self) -> &'static str { + BACKEND + } +} + +impl Drop for LinkCapture { + fn drop(&mut self) { + let _ = self.manager.send(Command::Remove(self.id)); + } +} + +/// The manager's thread: connect, watch, link, until told to quit or the +/// daemon goes away. +fn run( + remote: Option, + rx: pw::channel::Receiver, + apps: watch::Sender>, + alive: Arc, + init: std_mpsc::Sender>, +) { + pw::init(); + static MARKERS: AtomicU64 = AtomicU64::new(1); + let marker = format!("{}-{}", std::process::id(), MARKERS.fetch_add(1, Ordering::Relaxed)); + let setup = (|| { + let mainloop = + pw::main_loop::MainLoopRc::new(None).map_err(|e| format!("PipeWire main loop: {e}"))?; + let context = pw::context::ContextRc::new(&mainloop, None) + .map_err(|e| format!("PipeWire context: {e}"))?; + let mut props = pw::properties::PropertiesBox::new(); + if let Some(remote) = remote { + props.insert(*pw::keys::REMOTE_NAME, remote); + } + props.insert(MARKER, marker.to_string()); + let core = context + .connect_rc(Some(props)) + .map_err(|e| format!("cannot connect to PipeWire: {e}"))?; + let registry = core.get_registry_rc().map_err(|e| format!("PipeWire registry: {e}"))?; + Ok::<_, String>((mainloop, context, core, registry)) + })(); + let (mainloop, _context, core, registry) = match setup { + Ok(parts) => parts, + Err(e) => { + alive.store(false, Ordering::Relaxed); + let _ = init.send(Err(e)); + return; + } + }; + let model = Rc::new(RefCell::new(Model::new(core.clone(), registry.clone(), apps, marker))); + let _registry = registry + .add_listener_local() + .global({ + let model = Rc::downgrade(&model); + move |global| { + if let Some(model) = model.upgrade() { + Model::global(&model, global); + } + } + }) + .global_remove({ + let model = Rc::downgrade(&model); + move |id| { + if let Some(model) = model.upgrade() { + model.borrow_mut().remove(id); + } + } + }) + .register(); + let _core = core + .add_listener_local() + .error({ + let mainloop = mainloop.downgrade(); + let alive = alive.clone(); + move |id, _seq, res, message| { + // Other errors (a link refused, a stale id) are for one + // object; losing the socket ends everything. + if id != pw::core::PW_ID_CORE || res != -libc_epipe() { + debug!(id, res, "PipeWire error: {message}"); + } else { + warn!("PipeWire connection lost: {message}"); + alive.store(false, Ordering::Relaxed); + if let Some(mainloop) = mainloop.upgrade() { + mainloop.quit(); + } + } + } + }) + .register(); + let _commands = rx.attach(mainloop.loop_(), { + let model = Rc::downgrade(&model); + let mainloop = mainloop.downgrade(); + move |command| match command { + Command::Quit => { + if let Some(mainloop) = mainloop.upgrade() { + mainloop.quit(); + } + } + Command::Add { id, filter, name, input, reply } => { + let result = match model.upgrade() { + Some(model) => model.borrow_mut().add_capture(id, filter, &name, input), + None => Err("shutting down".into()), + }; + let _ = reply.send(result); + } + Command::Remove(id) => { + if let Some(model) = model.upgrade() { + model.borrow_mut().remove_capture(id); + } + } + } + }); + let _ = init.send(Ok(())); + mainloop.run(); + alive.store(false, Ordering::Relaxed); + // Links, streams and proxies go before the connection. + model.borrow_mut().clear(); +} + +/// Where a playback port goes in our stereo input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Side { + Left, + Right, + Both, + Skip, +} + +/// The side of a channel position (`audio.channel`): anything with an L is +/// left, a trailing R (or R before C, W, H) right, centres and mono both, +/// LFE nowhere; `AUX` by parity. +fn side(channel: Option<&str>) -> Side { + let Some(channel) = channel.map(str::trim) else { return Side::Both }; + let upper = channel.to_ascii_uppercase(); + let c = upper.as_str(); + if c.starts_with("LFE") { + return Side::Skip; + } + if matches!(c, "MONO" | "FC" | "RC" | "TC" | "TFC" | "TRC" | "BC" | "BLC" | "BRC" | "") { + return Side::Both; + } + if let Some(n) = c.strip_prefix("AUX").and_then(|n| n.parse::().ok()) { + return if n % 2 == 0 { Side::Left } else { Side::Right }; + } + if c.contains('L') { + return Side::Left; + } + let bytes = c.as_bytes(); + let last = bytes[bytes.len() - 1]; + let before = bytes.len().checked_sub(2).map(|i| bytes[i]); + if last == b'R' || (before == Some(b'R') && matches!(last, b'C' | b'W' | b'H')) { + return Side::Right; + } + Side::Both +} + +/// A process id from a property. +fn pid(props: &DictRef, key: &str) -> Option { + props.get(key).and_then(|v| v.trim().parse().ok()).filter(|&p| p > 0) +} + +fn text(props: &DictRef, key: &str) -> Option { + props.get(key).map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned) +} + +struct Client { + /// Kernel-checked pid of the connection (`pipewire.sec.pid`); for + /// pipewire-pulse streams that is pipewire-pulse, not the application. + sec_pid: Option, + pid: Option, + binary: Option, + name: Option, + /// Its details arrived (or never will). + known: bool, + _proxy: Option<(pw::client::ClientListener, pw::client::Client)>, +} + +struct Node { + node_name: String, + client: Option, + app_name: Option, + pid: Option, + binary: Option, + icon: Option, + media: Option, + running: bool, + /// The playing side of a loopback or filter (`node.link-group`): it + /// replays what applications played into a virtual sink, which is + /// captured at those applications already. + internal: bool, + /// Its info arrived (or never will). + known: bool, + _proxy: Option<(pw::node::NodeListener, pw::node::Node)>, +} + +struct Port { + node: u32, + output: bool, + monitor: bool, + channel: Option, +} + +/// One capture stream. +struct Capture { + id: u64, + filter: PlaybackFilter, + node_name: String, + /// Its node, once in the registry. + node: Option, + _listener: pw::stream::StreamListener, + _stream: pw::stream::StreamRc, +} + +/// What a capture stream's callbacks own. +struct CaptureData { + input: SourceInput, + channels: u16, + scratch: Vec, +} + +impl CaptureData { + fn process(&mut self, stream: &pw::stream::Stream) { + let Some(mut buffer) = stream.dequeue_buffer() else { return }; + let Some(data) = buffer.datas_mut().first_mut() else { return }; + let chunk = data.chunk(); + let (offset, size) = (chunk.offset() as usize, chunk.size() as usize); + let Some(bytes) = data.data() else { return }; + let Some(bytes) = bytes.get(offset..offset + size) else { return }; + let channels = usize::from(self.channels.max(1)); + let part = SCRATCH / channels * channels * 4; + for part in bytes.chunks(part) { + self.scratch.clear(); + self.scratch + .extend(part.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))); + self.input.push(&self.scratch, self.channels); + } + } +} + +/// The registry as far as it matters here, our captures and our links. +struct Model { + core: pw::core::CoreRc, + registry: pw::registry::RegistryRc, + own_pid: u32, + /// Our pid as the daemon sees it (see [`MARKER`]). + own_sec_pid: Option, + marker: String, + own_binary: Option, + clients: HashMap, + nodes: HashMap, + ports: HashMap, + captures: Vec, + /// Links we made, by (output port, input port). + links: HashMap<(u32, u32), pw::link::Link>, + /// Parent chains of process ids, cached until a client goes. + chains: RefCell>>, + apps: watch::Sender>, + weak: RcWeak>, +} + +impl Model { + fn new( + core: pw::core::CoreRc, + registry: pw::registry::RegistryRc, + apps: watch::Sender>, + marker: String, + ) -> Self { + let own_binary = std::env::current_exe() + .ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())); + Self { + core, + registry, + own_pid: std::process::id(), + own_sec_pid: None, + marker, + own_binary, + clients: HashMap::new(), + nodes: HashMap::new(), + ports: HashMap::new(), + captures: Vec::new(), + links: HashMap::new(), + chains: RefCell::new(HashMap::new()), + apps, + weak: RcWeak::new(), + } + } + + fn global(model: &Rc>, global: &pw::registry::GlobalObject<&DictRef>) { + let Some(props) = global.props else { return }; + let mut this = model.borrow_mut(); + if this.weak.upgrade().is_none() { + this.weak = Rc::downgrade(model); + } + let id = global.id; + match global.type_ { + ObjectType::Client => { + if props.get(MARKER) == Some(this.marker.as_str()) { + this.own_sec_pid = pid(props, "pipewire.sec.pid"); + } + let proxy = + this.registry.bind::(global).ok().map(|client| { + let model = Rc::downgrade(model); + let listener = client + .add_listener_local() + .info(move |info| { + if let Some(model) = model.upgrade() { + model.borrow_mut().client_info(id, info.props()); + } + }) + .register(); + (listener, client) + }); + let client = Client { + sec_pid: pid(props, "pipewire.sec.pid"), + pid: pid(props, "application.process.id"), + binary: text(props, "application.process.binary"), + name: text(props, "application.name"), + known: proxy.is_none(), + _proxy: proxy, + }; + this.clients.insert(id, client); + } + ObjectType::Node => { + let node_name = props.get("node.name").unwrap_or_default().to_owned(); + if node_name.starts_with(NODE_PREFIX) { + let mut ours = false; + for capture in this.captures.iter_mut().filter(|c| c.node_name == node_name) { + capture.node = Some(id); + ours = true; + } + if ours { + debug!(node = id, %node_name, "capture node ready"); + this.reconcile(); + } + return; + } + if props.get("media.class") != Some(PLAYBACK_CLASS) { + return; + } + let proxy = this.registry.bind::(global).ok().map(|node| { + let model = Rc::downgrade(model); + let listener = node + .add_listener_local() + .info(move |info| { + if let Some(model) = model.upgrade() { + let running = matches!(info.state(), pw::node::NodeState::Running); + model.borrow_mut().node_info(id, running, info.props()); + } + }) + .register(); + (listener, node) + }); + let node = Node { + node_name, + client: pid(props, "client.id"), + app_name: text(props, "application.name"), + pid: pid(props, "application.process.id"), + binary: text(props, "application.process.binary"), + icon: None, + media: text(props, "media.name"), + running: false, + internal: props.get("node.link-group").is_some(), + known: proxy.is_none(), + _proxy: proxy, + }; + this.nodes.insert(id, node); + this.changed(); + } + ObjectType::Port => { + let Some(node) = pid(props, "node.id") else { return }; + let port = Port { + node, + output: props.get("port.direction") == Some("out"), + monitor: props.get("port.monitor") == Some("true"), + channel: text(props, "audio.channel"), + }; + this.ports.insert(id, port); + let relevant = this.nodes.contains_key(&node) + || this.captures.iter().any(|c| c.node == Some(node)); + if relevant { + this.reconcile(); + } + } + _ => {} + } + } + + fn client_info(&mut self, id: u32, props: Option<&DictRef>) { + let Some(client) = self.clients.get_mut(&id) else { return }; + if let Some(props) = props { + client.pid = pid(props, "application.process.id").or(client.pid); + client.sec_pid = pid(props, "pipewire.sec.pid").or(client.sec_pid); + client.binary = text(props, "application.process.binary").or(client.binary.take()); + client.name = text(props, "application.name").or(client.name.take()); + } + client.known = true; + self.changed(); + } + + fn node_info(&mut self, id: u32, running: bool, props: Option<&DictRef>) { + let Some(node) = self.nodes.get_mut(&id) else { return }; + node.running = running; + if let Some(props) = props { + node.app_name = text(props, "application.name").or(node.app_name.take()); + node.pid = pid(props, "application.process.id").or(node.pid); + node.binary = text(props, "application.process.binary").or(node.binary.take()); + node.icon = text(props, "application.icon-name") + .or_else(|| text(props, "application.icon_name")) + .or_else(|| text(props, "media.icon-name")) + .or(node.icon.take()); + node.media = text(props, "media.name").or(node.media.take()); + node.client = pid(props, "client.id").or(node.client); + node.internal |= props.get("node.link-group").is_some(); + } + node.known = true; + self.changed(); + } + + fn remove(&mut self, id: u32) { + if self.clients.remove(&id).is_some() { + // Its process may be gone and its id reused. + self.chains.borrow_mut().clear(); + } + let node = self.nodes.remove(&id).is_some(); + let port = self.ports.remove(&id).is_some(); + let mut capture = false; + for c in self.captures.iter_mut().filter(|c| c.node == Some(id)) { + c.node = None; + capture = true; + } + if port { + self.links.retain(|(out, input), _| *out != id && *input != id); + } + if node || capture { + self.changed(); + } else if port { + self.reconcile(); + } + } + + fn add_capture( + &mut self, + id: u64, + filter: PlaybackFilter, + name: &str, + input: SourceInput, + ) -> std::result::Result<(), String> { + let node_name = format!("{NODE_PREFIX}-{}-{id}", self.own_pid); + let description = format!("Voelin stream audio: {}", name.replace('\0', "")); + let mut props = pw::properties::PropertiesBox::new(); + props.insert(*pw::keys::MEDIA_TYPE, "Audio"); + props.insert(*pw::keys::MEDIA_CATEGORY, "Capture"); + props.insert(*pw::keys::MEDIA_ROLE, "Music"); + props.insert(*pw::keys::NODE_NAME, node_name.as_str()); + props.insert(*pw::keys::NODE_DESCRIPTION, description); + props.insert("node.autoconnect", "false"); + let stream = pw::stream::StreamRc::new(self.core.clone(), &node_name, props) + .map_err(|e| format!("PipeWire stream: {e}"))?; + let data = CaptureData { input, channels: 2, scratch: Vec::with_capacity(SCRATCH) }; + let listener = stream + .add_local_listener_with_user_data(data) + .state_changed(|_, _, _, new| { + if let pw::stream::StreamState::Error(e) = &new { + warn!("application audio stream failed: {e}"); + } + }) + .param_changed(|_, data, id, param| { + let Some(param) = param else { return }; + if id != pw::spa::param::ParamType::Format.as_raw() { + return; + } + let mut info = AudioInfoRaw::new(); + if info.parse(param).is_ok() && info.channels() > 0 { + data.channels = info.channels().min(u32::from(u16::MAX)) as u16; + } + }) + .process(|stream, data| data.process(stream)) + .register() + .map_err(|e| format!("PipeWire listener: {e}"))?; + let mut info = AudioInfoRaw::new(); + info.set_format(AudioFormat::F32LE); + info.set_rate(AUDIO_SAMPLE_RATE); + info.set_channels(2); + let mut position = [0; pw::spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; + position[0] = pw::spa::sys::SPA_AUDIO_CHANNEL_FL; + position[1] = pw::spa::sys::SPA_AUDIO_CHANNEL_FR; + info.set_position(position); + let format = serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties: info.into(), + }))?; + stream + .connect( + pw::spa::utils::Direction::Input, + None, + pw::stream::StreamFlags::MAP_BUFFERS, + &mut [pod(&format)?], + ) + .map_err(|e| format!("cannot connect the application audio stream: {e}"))?; + debug!(id, ?filter, %node_name, "application audio capture"); + self.captures.push(Capture { + id, + filter, + node_name, + node: None, + _listener: listener, + _stream: stream, + }); + Ok(()) + } + + fn remove_capture(&mut self, id: u64) { + self.captures.retain(|c| c.id != id); + self.reconcile(); + } + + fn clear(&mut self) { + self.links.clear(); + self.captures.clear(); + self.nodes.clear(); + self.clients.clear(); + self.ports.clear(); + } + + /// The parent chain of `pid`, itself first. + fn chain(&self, pid: u32) -> Vec { + if let Some(chain) = self.chains.borrow().get(&pid) { + return chain.clone(); + } + let mut chain = vec![pid]; + let mut current = pid; + while chain.len() < 64 { + match parent_pid(current) { + Some(parent) if parent > 0 && parent != current => { + chain.push(parent); + current = parent; + } + _ => break, + } + } + self.chains.borrow_mut().insert(pid, chain.clone()); + chain + } + + /// The process of a node: its own `application.process.id`, else its + /// client's, else the client's socket credentials. + fn node_pid(&self, node: &Node) -> Option { + let client = node.client.and_then(|c| self.clients.get(&c)); + node.pid.or(client.and_then(|c| c.pid)).or(client.and_then(|c| c.sec_pid)) + } + + /// The node's and its client's details are in. + fn resolved(&self, node: &Node) -> bool { + node.known && node.client.and_then(|c| self.clients.get(&c)).is_none_or(|c| c.known) + } + + /// Played by this process or one of its children. + fn is_ours(&self, node: &Node) -> bool { + let client = node.client.and_then(|c| self.clients.get(&c)); + // A native client of ours, as the daemon saw its socket. + if node.pid.is_none() + && self.own_sec_pid.is_some() + && client.and_then(|c| c.sec_pid) == self.own_sec_pid + { + return true; + } + match self.node_pid(node) { + Some(pid) => self.chain(pid).contains(&self.own_pid), + None => { + let binary = node.binary.as_deref().or(client.and_then(|c| c.binary.as_deref())); + binary.is_some() && binary == self.own_binary.as_deref() + } + } + } + + fn matches(&self, filter: &PlaybackFilter, node: &Node) -> bool { + if node.internal || self.is_ours(node) { + return false; + } + match filter { + PlaybackFilter::AllButSelf => true, + PlaybackFilter::App(app @ crate::capture::playback::AppMatch::Name(_)) => { + let client = node.client.and_then(|c| self.clients.get(&c)); + let names = [ + node.app_name.as_deref(), + node.binary.as_deref(), + client.and_then(|c| c.name.as_deref()), + client.and_then(|c| c.binary.as_deref()), + Some(node.node_name.as_str()), + ]; + app.matches_name(names.into_iter().flatten()) + } + PlaybackFilter::App(crate::capture::playback::AppMatch::Pid(wanted)) => { + let client = node.client.and_then(|c| self.clients.get(&c)); + [node.pid, client.and_then(|c| c.pid), client.and_then(|c| c.sec_pid)] + .into_iter() + .flatten() + .any(|pid| self.chain(pid).contains(wanted)) + } + } + } + + /// Nodes or clients changed: links and the app list follow. + fn changed(&mut self) { + self.reconcile(); + self.publish(); + } + + /// Make the links match what every capture selects now. + fn reconcile(&mut self) { + let mut wanted: HashMap<(u32, u32), (u32, u32)> = HashMap::new(); + for capture in &self.captures { + let Some(ours) = capture.node else { continue }; + let mut inputs = (None, None); + for (&id, port) in &self.ports { + if port.node != ours || port.output || port.monitor { + continue; + } + match side(port.channel.as_deref()) { + Side::Left => inputs.0 = Some(id), + Side::Right => inputs.1 = Some(id), + _ => {} + } + } + if inputs == (None, None) { + // Not configured by the session manager yet. + continue; + } + for (&node_id, node) in &self.nodes { + if !self.resolved(node) || !self.matches(&capture.filter, node) { + continue; + } + let outputs: Vec<(u32, &Port)> = self + .ports + .iter() + .filter(|(_, p)| p.node == node_id && p.output && !p.monitor) + .map(|(&id, p)| (id, p)) + .collect(); + let single = outputs.len() == 1; + for (port_id, port) in outputs { + let side = if single { Side::Both } else { side(port.channel.as_deref()) }; + let targets = match side { + Side::Left => [inputs.0, None], + Side::Right => [inputs.1, None], + Side::Both => [inputs.0, inputs.1], + Side::Skip => [None, None], + }; + for input in targets.into_iter().flatten() { + wanted.insert((port_id, input), (node_id, ours)); + } + } + } + } + self.links.retain(|pair, _| wanted.contains_key(pair)); + for (pair, nodes) in wanted { + if self.links.contains_key(&pair) { + continue; + } + let mut props = pw::properties::PropertiesBox::new(); + props.insert("link.output.node", nodes.0.to_string()); + props.insert("link.output.port", pair.0.to_string()); + props.insert("link.input.node", nodes.1.to_string()); + props.insert("link.input.port", pair.1.to_string()); + props.insert("object.linger", "false"); + match self.core.create_object::("link-factory", &props) { + Ok(link) => { + debug!(output = pair.0, input = pair.1, "linked"); + self.links.insert(pair, link); + } + Err(e) => warn!("cannot link port {} to {}: {e}", pair.0, pair.1), + } + } + } + + /// Send the list of playing applications if it changed. + fn publish(&self) { + let mut apps: Vec = Vec::new(); + for node in self.nodes.values() { + if !self.resolved(node) || node.internal || self.is_ours(node) { + continue; + } + let client = node.client.and_then(|c| self.clients.get(&c)); + let pid = self.node_pid(node); + let binary = node.binary.clone().or_else(|| client.and_then(|c| c.binary.clone())); + let name = node + .app_name + .clone() + .or_else(|| client.and_then(|c| c.name.clone())) + .or_else(|| binary.clone()) + .unwrap_or_else(|| node.node_name.clone()); + let existing = apps.iter_mut().find(|a| match pid { + Some(pid) => a.pid == Some(pid), + None => a.pid.is_none() && a.name == name, + }); + match existing { + Some(app) => { + app.streams += 1; + app.playing |= node.running; + if app.media.is_none() || (node.running && !app.playing) { + app.media = node.media.clone(); + } + if app.icon.is_none() { + app.icon = node.icon.clone(); + } + } + None => apps.push(AudioApp { + name, + pid, + binary, + icon: node.icon.clone(), + media: node.media.clone(), + streams: 1, + playing: node.running, + }), + } + } + apps.sort_by(|a, b| { + a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.pid.cmp(&b.pid)) + }); + self.apps.send_if_modified(|current| { + if *current == apps { + false + } else { + *current = apps; + true + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_sides() { + for (channel, expected) in [ + ("FL", Side::Left), + ("FR", Side::Right), + ("MONO", Side::Both), + ("FC", Side::Both), + ("LFE", Side::Skip), + ("RL", Side::Left), + ("RR", Side::Right), + ("SL", Side::Left), + ("SR", Side::Right), + ("FLC", Side::Left), + ("FRC", Side::Right), + ("RC", Side::Both), + ("TFL", Side::Left), + ("TRR", Side::Right), + ("FRW", Side::Right), + ("AUX0", Side::Left), + ("AUX1", Side::Right), + ("UNK", Side::Both), + ] { + assert_eq!(side(Some(channel)), expected, "{channel}"); + } + assert_eq!(side(None), Side::Both); + } + + /// Without a daemon, connecting fails with a clear error instead of + /// hanging. Skipped where a daemon socket exists. + #[test] + fn unavailable_without_daemon() { + let err = LinkManager::connect(Some(Path::new("/nonexistent/voelin/pipewire-0"))) + .err() + .expect("no daemon there"); + assert!(matches!(err, Error::CaptureUnavailable { backend: "pipewire", .. }), "{err}"); + } +} diff --git a/crates/voelin-media/src/capture/playback.rs b/crates/voelin-media/src/capture/playback.rs new file mode 100644 index 0000000..32be577 --- /dev/null +++ b/crates/voelin-media/src/capture/playback.rs @@ -0,0 +1,315 @@ +//! What applications play, captured into stream mixer sources: all of it +//! except our own process tree (so viewers do not hear the TeamSpeak voices +//! we play), or chosen applications only; and the list of applications +//! that play, for a picker. +//! +//! | Platform | All but ours | One application | Playing apps | +//! |---|---|---|---| +//! | Linux (PipeWire) | links from every other playback stream into a capture stream of ours ([`super::pipewire_links`]) | links from that application's streams | playback streams in the registry | +//! | Windows | WASAPI process loopback excluding our process tree | process loopback including the application's process tree | audio sessions of the default device | +//! | Android | `AudioPlaybackCapture` excluding our uid | matching the application's uid | launchable apps (Android cannot tell which play) | +//! +//! [`start_playback`] starts one; the capture feeds the given +//! [`SourceHandle`] (through one or more inputs) until it is dropped. +//! [`forward_audio`] feeds any [`AudioCapture`] into a source instead. + +use std::time::Duration; + +use tokio::sync::watch; + +use crate::capture::{AudioCapture, Worker}; +use crate::mix::SourceHandle; +use crate::{Error, Result}; + +/// Which playback a capture takes. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum PlaybackFilter { + /// Everything that plays except this process and its children (our + /// voices and watched streams). + AllButSelf, + /// One application's playback. + App(AppMatch), +} + +/// How an application is recognised. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum AppMatch { + /// A process and its children (Linux, Windows): the process that owns a + /// window, or an entry of the playing-apps list. Ends with the process. + Pid(u32), + /// By name, ignoring case: the application name or executable (Linux, + /// Windows; `.exe` optional) or the package name (Android). A restarted + /// application is found again. + Name(String), +} + +impl AppMatch { + /// Whether one of `names` is this name. + pub fn matches_name<'a>(&self, names: impl IntoIterator) -> bool { + let AppMatch::Name(wanted) = self else { return false }; + let wanted = wanted.trim(); + let wanted = wanted.strip_suffix(".exe").unwrap_or(wanted).to_lowercase(); + names.into_iter().any(|name| { + let name = name.trim(); + let name = name.strip_suffix(".exe").unwrap_or(name); + !name.is_empty() && name.to_lowercase() == wanted + }) + } +} + +impl std::fmt::Display for AppMatch { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AppMatch::Pid(pid) => write!(f, "process {pid}"), + AppMatch::Name(name) => f.write_str(name), + } + } +} + +/// An application that plays audio (or could, on Android), for a picker. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AudioApp { + /// Name to show. + pub name: String, + /// Its process (Linux, Windows); pick with [`AppMatch::Pid`]. + pub pid: Option, + /// Executable (Linux, Windows) or package name (Android): what + /// [`AppMatch::Name`] matches besides `name`. + pub binary: Option, + /// Icon name (freedesktop icon theme) or icon path, if the application + /// gave one. + pub icon: Option, + /// What it plays, if it says (e.g. a track or tab title). + pub media: Option, + /// Its playback streams now. + pub streams: u32, + /// Audio is flowing now (not paused or idle). + pub playing: bool, +} + +/// A running capture that feeds a mixer source; stops when dropped. +pub trait SourceCapture: Send { + /// Short name for logs (`"pipewire"`, `"wasapi"`, ...). + fn backend(&self) -> &'static str; +} + +/// Capture the playback `filter` selects into `source`, on this platform. +pub fn start_playback( + filter: &PlaybackFilter, + source: &SourceHandle, +) -> Result> { + if let Some(provider) = super::external::audio_provider() { + return super::external::start_playback(provider, filter, source); + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + return super::pipewire_links::LinkManager::shared()?.capture(filter, source); + #[cfg(windows)] + return super::windows::start_playback(filter, source); + #[allow(unreachable_code)] + { + let _ = (filter, source); + Err(Error::CaptureUnavailable { + backend: "audio", + reason: "no application audio capture in this build".into(), + }) + } +} + +/// Applications that play audio now, updated live. Holds the backend's +/// connection (e.g. to PipeWire) while it lives. +pub struct AudioApps { + rx: watch::Receiver>, + _keep: Box, +} + +impl AudioApps { + pub fn new(rx: watch::Receiver>, keep: Box) -> Self { + Self { rx, _keep: keep } + } + + /// The list now (marks it seen). + pub fn current(&mut self) -> Vec { + self.rx.borrow_and_update().clone() + } + + /// Whether the list changed since [`current`](Self::current). + pub fn has_changed(&self) -> bool { + self.rx.has_changed().unwrap_or(false) + } + + /// Wait for a change; `None` once the backend is gone. + pub async fn changed(&mut self) -> Option> { + self.rx.changed().await.ok()?; + Some(self.current()) + } + + /// Wait for a change from a plain thread, up to `timeout`. + pub fn wait_changed(&mut self, timeout: Duration) -> Option> { + let deadline = std::time::Instant::now() + timeout; + while std::time::Instant::now() < deadline { + if self.has_changed() { + return Some(self.current()); + } + std::thread::sleep(Duration::from_millis(20)); + } + None + } +} + +/// The applications that play audio, on this platform. +pub fn audio_apps() -> Result { + if let Some(provider) = super::external::audio_provider() { + let (tx, rx) = watch::channel(provider.apps()); + return Ok(AudioApps::new(rx, Box::new(tx))); + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + { + let manager = super::pipewire_links::LinkManager::shared()?; + return Ok(AudioApps::new(manager.apps(), Box::new(manager))); + } + #[cfg(windows)] + return super::windows::audio_apps(); + #[allow(unreachable_code)] + Err(Error::CaptureUnavailable { + backend: "audio", + reason: "no application audio listing in this build".into(), + }) +} + +/// The process that owns a captured window, where the platform tells (X11 +/// `_NET_WM_PID`, the owner of a Windows `HWND`). The ScreenCast portal +/// does not say which application a window belongs to. +pub fn window_pid(window: u64) -> Option { + #[cfg(all(target_os = "linux", feature = "x11"))] + return super::x11::window_pid(None, window); + #[cfg(windows)] + return super::windows::window_pid(window); + #[allow(unreachable_code)] + { + let _ = window; + None + } +} + +/// Whether `pid` is `ancestor` or one of its descendants (Linux: the +/// parent chain in `/proc`; elsewhere only `pid == ancestor`). +pub fn descends_from(pid: u32, ancestor: u32) -> bool { + if pid == ancestor { + return true; + } + #[cfg(target_os = "linux")] + { + let mut current = pid; + // A bound on the chain, in case of a cycle while processes are reused. + for _ in 0..64 { + match parent_pid(current) { + Some(parent) if parent == ancestor => return true, + Some(parent) if parent > 1 && parent != current => current = parent, + _ => return false, + } + } + } + false +} + +/// The parent of `pid` from `/proc//stat`. +#[cfg(target_os = "linux")] +pub fn parent_pid(pid: u32) -> Option { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + // `pid (comm) state ppid ...`; the command may contain spaces and ')'. + let rest = &stat[stat.rfind(')')? + 1..]; + rest.split_whitespace().nth(1)?.parse().ok() +} + +/// Feeds an [`AudioCapture`] (48 kHz buffers) into a mixer source from a +/// thread of its own. +struct Forwarded { + backend: &'static str, + worker: Option, + capture: Box, +} + +impl SourceCapture for Forwarded { + fn backend(&self) -> &'static str { + self.backend + } +} + +impl Drop for Forwarded { + fn drop(&mut self) { + self.worker = None; + self.capture.stop(); + } +} + +/// Start `capture` and feed its buffers into `source` until the returned +/// capture is dropped, the source is removed, or the capture ends. +pub fn forward_audio( + mut capture: Box, + source: &SourceHandle, +) -> Result> { + let mut buffers = capture.start()?; + let mut input = source.input(crate::frame::AUDIO_SAMPLE_RATE); + let worker = Worker::spawn("voelin-audio-forward", move |stop| { + while !stop.load(std::sync::atomic::Ordering::Relaxed) && !input.is_closed() { + match buffers.recv_timeout(Duration::from_millis(100)) { + Some(buffer) => { + input.push(&buffer.samples, buffer.channels); + } + None if buffers.is_closed() => break, + None => {} + } + } + })?; + Ok(Box::new(Forwarded { backend: capture.backend(), worker: Some(worker), capture })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::capture::synthetic::SineSource; + use crate::mix::{MixerConfig, StreamMixer}; + + #[test] + fn names_match_loosely() { + let firefox = AppMatch::Name("Firefox".into()); + assert!(firefox.matches_name(["firefox"])); + assert!(firefox.matches_name(["", "FIREFOX.exe"])); + assert!(!firefox.matches_name(["firefox-bin"])); + assert!(AppMatch::Name("spotify.exe".into()).matches_name(["Spotify"])); + assert!(!AppMatch::Pid(1).matches_name(["1"])); + assert_eq!(AppMatch::Pid(7).to_string(), "process 7"); + } + + #[cfg(target_os = "linux")] + #[test] + fn process_tree() { + let me = std::process::id(); + assert!(descends_from(me, me)); + let parent = parent_pid(me).unwrap(); + assert!(descends_from(me, parent)); + assert!(!descends_from(parent, me)); + let mut child = std::process::Command::new("sleep").arg("5").spawn().unwrap(); + assert!(descends_from(child.id(), me)); + assert_eq!(parent_pid(child.id()), Some(me)); + child.kill().unwrap(); + child.wait().unwrap(); + assert!(!descends_from(u32::MAX - 1, me)); + } + + #[test] + fn forwarded_capture_feeds_the_mixer() { + let mut mixer = StreamMixer::new(MixerConfig::default()); + let source = mixer.handle().add_source("tone"); + let capture = forward_audio(Box::new(SineSource::new(1000.0, 0.5)), &source).unwrap(); + assert_eq!(capture.backend(), "synthetic"); + let mut out = vec![0.0; 1920]; + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while source.level().peak < 0.4 && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + mixer.mix(&mut out); + } + assert!(source.level().peak > 0.4, "{:?}", source.level()); + drop(capture); + } +} diff --git a/crates/voelin-media/src/capture/windows.rs b/crates/voelin-media/src/capture/windows.rs index 75fcc9f..2ce053a 100644 --- a/crates/voelin-media/src/capture/windows.rs +++ b/crates/voelin-media/src/capture/windows.rs @@ -4,15 +4,17 @@ //! System audio uses process loopback in exclude mode with our own process //! id, so our own playback (TeamSpeak voices) is not captured (Windows 10 //! 2004 or later). Older systems fall back to plain loopback of the default -//! output device, which includes our playback. +//! output device, which includes our playback. Single applications use +//! process loopback in include mode on their process tree, one capture per +//! process ([`start_playback`]); [`audio_apps`] lists the processes with +//! audio sessions on the playback devices. //! //! Type-checked on Linux (`--target x86_64-pc-windows-gnu`), not run yet. -use std::collections::VecDeque; -use std::sync::atomic::Ordering; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; -use tracing::warn; +use tracing::{debug, warn}; use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler}; use windows_capture::frame::Frame; use windows_capture::graphics_capture_api::InternalCaptureControl; @@ -23,12 +25,14 @@ use windows_capture::settings::{ }; use windows_capture::window::Window; +use crate::capture::playback::{AppMatch, AudioApp, AudioApps, PlaybackFilter, SourceCapture}; use crate::capture::{ AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, - SourceId, Worker, + SourceId, Ticker, Worker, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; -use crate::queue::{FrameReceiver, FrameSender, frame_channel}; +use crate::mix::SourceHandle; +use crate::queue::{FrameReceiver, frame_channel}; use crate::{Error, Result}; const BACKEND: &str = "wgc"; @@ -221,34 +225,20 @@ impl WasapiLoopback { impl AudioCapture for WasapiLoopback { fn backend(&self) -> &'static str { - "wasapi" + AUDIO_BACKEND } fn start(&mut self) -> Result> { self.stop(); let (tx, rx) = frame_channel(50); - let (init_tx, init_rx) = std::sync::mpsc::channel(); - self.worker = Some(Worker::spawn("voelin-wasapi-loopback", move |stop| { - if let Err(e) = loopback(&tx, &stop, &init_tx) { - // After a successful start the receiver just sees the end. - let _ = init_tx.send(Err(e.clone())); - warn!("system audio capture ended: {e}"); - } - })?); - match init_rx.recv() { - Ok(Ok(())) => Ok(rx), - Ok(Err(reason)) => { - self.stop(); - Err(Error::CaptureUnavailable { backend: "wasapi", reason }) - } - Err(_) => { - self.stop(); - Err(Error::CaptureUnavailable { - backend: "wasapi", - reason: "capture thread ended".into(), - }) - } - } + let started = Instant::now(); + let worker = + spawn_loopback("voelin-wasapi-loopback", Loopback::AllButSelf, move |samples| { + let samples = samples.to_vec(); + tx.send(AudioBuffer { samples, channels: 2, timestamp: started.elapsed() }) + })?; + self.worker = Some(worker); + Ok(rx) } fn stop(&mut self) { @@ -256,7 +246,53 @@ impl AudioCapture for WasapiLoopback { } } -fn open_client() -> std::result::Result { +const AUDIO_BACKEND: &str = "wasapi"; +/// Bytes of one 48 kHz stereo `f32` frame. +const FRAME_BYTES: usize = 2 * 4; + +/// Which processes a loopback capture hears. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Loopback { + /// Everything except our process tree (plain device loopback where + /// process loopback is missing, which includes our playback). + AllButSelf, + /// One process and its children. + Tree(u32), +} + +/// Start a loopback capture on a thread of its own that hands each packet +/// (48 kHz stereo) to `deliver` until it returns `false` or the worker is +/// dropped. Returns once the capture runs (or failed to start). +fn spawn_loopback( + name: &str, + mode: Loopback, + mut deliver: impl FnMut(&[f32]) -> bool + Send + 'static, +) -> Result { + let (init_tx, init_rx) = std::sync::mpsc::channel(); + let mut worker = Worker::spawn(name, move |stop| { + if let Err(e) = loopback(mode, &stop, &init_tx, &mut deliver) { + // After a successful start the consumer just sees the end. + let _ = init_tx.send(Err(e.clone())); + warn!("audio capture ({mode:?}) ended: {e}"); + } + })?; + match init_rx.recv() { + Ok(Ok(())) => Ok(worker), + Ok(Err(reason)) => { + worker.stop(); + Err(Error::CaptureUnavailable { backend: AUDIO_BACKEND, reason }) + } + Err(_) => { + worker.stop(); + Err(Error::CaptureUnavailable { + backend: AUDIO_BACKEND, + reason: "capture thread ended".into(), + }) + } + } +} + +fn open_client(mode: Loopback) -> std::result::Result { let format = wasapi::WaveFormat::new( 32, 32, @@ -265,15 +301,23 @@ fn open_client() -> std::result::Result { 2, None, ); - let mode = wasapi::StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 200_000 }; - // Everything but our own process tree. - match wasapi::AudioClient::new_application_loopback_client(std::process::id(), false) { - Ok(mut client) => { - match client.initialize_client(&format, &wasapi::Direction::Capture, &mode) { - Ok(()) => return Ok(client), - Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"), - } - } + let stream = + wasapi::StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 200_000 }; + let (pid, include) = match mode { + // Everything but our own process tree. + Loopback::AllButSelf => (std::process::id(), false), + Loopback::Tree(pid) => (pid, true), + }; + let opened = wasapi::AudioClient::new_application_loopback_client(pid, include).and_then( + |mut client| { + client.initialize_client(&format, &wasapi::Direction::Capture, &stream)?; + Ok(client) + }, + ); + match opened { + Ok(client) => return Ok(client), + // No fallback that would capture other applications too. + Err(e) if include => return Err(format!("process loopback of {pid}: {e}")), Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"), } let enumerator = wasapi::DeviceEnumerator::new().map_err(|e| e.to_string())?; @@ -282,42 +326,61 @@ fn open_client() -> std::result::Result { let mut client = device.get_iaudioclient().map_err(|e| e.to_string())?; // Capture on a render device is loopback. client - .initialize_client(&format, &wasapi::Direction::Capture, &mode) + .initialize_client(&format, &wasapi::Direction::Capture, &stream) .map_err(|e| e.to_string())?; Ok(client) } +/// The capture loop: packets as they come, converted into one reused +/// buffer (nothing allocated per packet). fn loopback( - tx: &FrameSender, - stop: &std::sync::atomic::AtomicBool, + mode: Loopback, + stop: &AtomicBool, init: &std::sync::mpsc::Sender>, + deliver: &mut dyn FnMut(&[f32]) -> bool, ) -> std::result::Result<(), String> { // COM for this thread; "already initialised" is fine. let _ = wasapi::initialize_mta(); - let client = open_client()?; + let client = open_client(mode)?; let event = client.set_get_eventhandle().map_err(|e| e.to_string())?; let capture = client.get_audiocaptureclient().map_err(|e| e.to_string())?; client.start_stream().map_err(|e| e.to_string())?; let _ = init.send(Ok(())); - const FRAME_BYTES: usize = 2 * 4; - let chunk = AUDIO_SAMPLE_RATE as usize / 100 * FRAME_BYTES; - let started = Instant::now(); - let mut queue = VecDeque::new(); + // A tenth of a second per packet; grown if a packet is larger. + let mut bytes = vec![0u8; AUDIO_SAMPLE_RATE as usize / 10 * FRAME_BYTES]; + let mut samples: Vec = Vec::with_capacity(bytes.len() / 4); while !stop.load(Ordering::Relaxed) { // No events arrive while nothing plays. if event.wait_for_event(100).is_err() { continue; } - capture.read_from_device_to_deque(&mut queue).map_err(|e| e.to_string())?; - while queue.len() >= chunk { - let bytes: Vec = queue.drain(..chunk).collect(); - let samples = bytes - .chunks_exact(4) - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); - let buffer = AudioBuffer { samples, channels: 2, timestamp: started.elapsed() }; - if !tx.send(buffer) { + loop { + let (frames, info) = match capture.read_from_device(&mut bytes) { + Ok(read) => read, + Err(wasapi::WasapiError::DataLengthTooShort { expected, .. }) => { + // That packet is lost; the next one fits. + bytes.resize(expected * FRAME_BYTES, 0); + samples.reserve(expected * 2); + continue; + } + Err(e) => return Err(e.to_string()), + }; + if frames == 0 { + break; + } + let len = frames as usize * FRAME_BYTES; + samples.clear(); + if info.flags.silent { + samples.resize(len / 4, 0.0); + } else { + samples.extend( + bytes[..len] + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])), + ); + } + if !deliver(&samples) { stop.store(true, Ordering::Relaxed); break; } @@ -325,3 +388,190 @@ fn loopback( } client.stop_stream().map_err(|e| e.to_string()) } + +/// Loopback captures feeding a mixer source. +struct LoopbackCapture { + _worker: Worker, +} + +impl SourceCapture for LoopbackCapture { + fn backend(&self) -> &'static str { + AUDIO_BACKEND + } +} + +fn capture_into(mode: Loopback, source: &SourceHandle) -> Result { + let mut input = source.input(AUDIO_SAMPLE_RATE); + spawn_loopback("voelin-wasapi-source", mode, move |samples| { + input.push(samples, 2); + !input.is_closed() + }) +} + +/// Capture the playback `filter` selects into `source`: process loopback +/// excluding our process tree, or including the chosen process tree (for a +/// name, one capture per matching process, matched again every two +/// seconds). +pub fn start_playback( + filter: &PlaybackFilter, + source: &SourceHandle, +) -> Result> { + let worker = match filter { + PlaybackFilter::AllButSelf => capture_into(Loopback::AllButSelf, source)?, + PlaybackFilter::App(AppMatch::Pid(pid)) => capture_into(Loopback::Tree(*pid), source)?, + PlaybackFilter::App(app) => { + let (app, source) = (app.clone(), source.clone()); + Worker::spawn("voelin-wasapi-apps", move |stop| follow_app(&app, &source, &stop))? + } + }; + Ok(Box::new(LoopbackCapture { _worker: worker })) +} + +/// Keep one include-mode capture per process whose audio sessions match +/// `app`, until stopped or the source is removed. +fn follow_app(app: &AppMatch, source: &SourceHandle, stop: &AtomicBool) { + let _ = wasapi::initialize_mta(); + // Per process: its capture, and the polls it was missing from. + let mut captures: Vec<(u32, Worker, u32)> = Vec::new(); + let mut ticker = Ticker::new(1); + loop { + let pids: Vec = match sessions() { + Ok(apps) => apps + .into_iter() + .filter(|a| app.matches_name([a.name.as_str(), a.binary.as_deref().unwrap_or("")])) + .filter_map(|a| a.pid) + .collect(), + Err(e) => { + debug!("listing audio sessions: {e}"); + Vec::new() + } + }; + for entry in &mut captures { + entry.2 = if pids.contains(&entry.0) { 0 } else { entry.2 + 1 }; + } + // Gone for two polls: the process ended or closed its sessions. + captures.retain(|(_, _, missing)| *missing < 2); + for pid in pids { + if captures.iter().any(|(p, ..)| *p == pid) { + continue; + } + match capture_into(Loopback::Tree(pid), source) { + Ok(worker) => captures.push((pid, worker, 0)), + Err(e) => warn!("capturing process {pid} ({app}): {e}"), + } + } + if source.is_removed() || !ticker.wait(stop) || !ticker.wait(stop) { + break; + } + } +} + +/// The executable file name of `pid`, if we may look. +fn process_name(pid: u32) -> Option { + use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, + QueryFullProcessImageNameW, + }; + let mut path = [0u16; 1024]; + let mut len = path.len() as u32; + // SAFETY: the handle is checked by `OpenProcess` and closed by `Owned`; + // the pointer and length describe `path`, which outlives the call. + #[allow(unsafe_code)] + unsafe { + let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; + let process = windows::core::Owned::new(process); + QueryFullProcessImageNameW( + *process, + PROCESS_NAME_WIN32, + windows::core::PWSTR(path.as_mut_ptr()), + &mut len, + ) + .ok()?; + } + let path = String::from_utf16_lossy(&path[..(len as usize).min(path.len())]); + path.rsplit(['\\', '/']).next().map(str::to_owned).filter(|n| !n.is_empty()) +} + +/// Audio sessions of every active playback device, one entry per process +/// (not ours). +fn sessions() -> std::result::Result, String> { + let own = std::process::id(); + let enumerator = wasapi::DeviceEnumerator::new().map_err(|e| e.to_string())?; + let devices = + enumerator.get_device_collection(&wasapi::Direction::Render).map_err(|e| e.to_string())?; + let mut apps: Vec = Vec::new(); + for device in &devices { + let Ok(device) = device else { continue }; + let Ok(manager) = device.get_iaudiosessionmanager() else { continue }; + let Ok(sessions) = manager.get_audiosessionenumerator() else { continue }; + for i in 0..sessions.get_count().unwrap_or(0) { + let Ok(session) = sessions.get_session(i) else { continue }; + // Process 0 is the system sounds session. + let Ok(pid) = session.get_process_id() else { continue }; + if pid == 0 || pid == own { + continue; + } + let state = session.get_state().ok(); + if matches!(state, Some(wasapi::SessionState::Expired)) { + continue; + } + let playing = matches!(state, Some(wasapi::SessionState::Active)); + if let Some(app) = apps.iter_mut().find(|a| a.pid == Some(pid)) { + app.streams += 1; + app.playing |= playing; + continue; + } + let binary = process_name(pid); + // Names like "@%SystemRoot%\..." are resource references. + let display = session + .get_display_name() + .ok() + .filter(|n| !n.trim().is_empty() && !n.starts_with('@')); + let stem = binary.as_deref().map(|b| b.strip_suffix(".exe").unwrap_or(b).to_owned()); + apps.push(AudioApp { + name: display.or(stem).unwrap_or_else(|| format!("Process {pid}")), + pid: Some(pid), + binary, + icon: session.get_icon_path().ok().filter(|p| !p.trim().is_empty()), + media: None, + streams: 1, + playing, + }); + } + } + apps.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.pid.cmp(&b.pid))); + Ok(apps) +} + +/// Applications with audio sessions, polled every two seconds. +pub fn audio_apps() -> Result { + let _ = wasapi::initialize_mta(); + let first = sessions() + .map_err(|reason| Error::CaptureUnavailable { backend: AUDIO_BACKEND, reason })?; + let (tx, rx) = tokio::sync::watch::channel(first); + let worker = Worker::spawn("voelin-wasapi-sessions", move |stop| { + let _ = wasapi::initialize_mta(); + let mut ticker = Ticker::new(1); + while ticker.wait(&stop) && ticker.wait(&stop) && !tx.is_closed() { + if let Ok(apps) = sessions() { + tx.send_if_modified(|current| { + let changed = *current != apps; + if changed { + *current = apps; + } + changed + }); + } + } + })?; + Ok(AudioApps::new(rx, Box::new(worker))) +} + +/// The process that owns window `hwnd`. +pub fn window_pid(hwnd: u64) -> Option { + let window = Window::from_raw_hwnd(hwnd as usize as *mut std::ffi::c_void); + if !window.is_valid() { + return None; + } + window.process_id().ok() +} diff --git a/crates/voelin-media/src/capture/x11.rs b/crates/voelin-media/src/capture/x11.rs index 8d10406..de06ea9 100644 --- a/crates/voelin-media/src/capture/x11.rs +++ b/crates/voelin-media/src/capture/x11.rs @@ -195,6 +195,21 @@ impl ScreenCapture for X11Capture { } } +/// The process that owns `window` (its `_NET_WM_PID`) on `display` (`None`: +/// `$DISPLAY`), for capturing the window's audio. Clients set it +/// voluntarily; it is the pid on the window's host. +pub fn window_pid(display: Option<&str>, window: u64) -> Option { + let (conn, _) = RustConnection::connect(display).ok()?; + let atom = conn.intern_atom(true, b"_NET_WM_PID").ok()?.reply().ok()?.atom; + if atom == u32::from(AtomEnum::NONE) { + return None; + } + let window = u32::try_from(window).ok()?; + let reply = + conn.get_property(false, window, atom, AtomEnum::CARDINAL, 0, 1).ok()?.reply().ok()?; + reply.value32()?.next().filter(|&pid| pid > 0) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Rect { x: i16, diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 538625b..f45a6f1 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -13,6 +13,9 @@ //! test source, X11 (feature `x11`), the Wayland ScreenCast portal and //! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture //! plus WASAPI loopback on Windows +//! - [`mix`]: the stream's audio mixer ([`mix::StreamMixer`]): any number +//! of sources at their own pace and rate into 48 kHz stereo, with gains, +//! mutes, a soft limiter and lock-free meters //! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on //! - the streaming path: [`workers`] (a fork-join pool that allocates //! nothing per job), [`pool`] (recycled I420 frames), [`handoff`] @@ -29,6 +32,7 @@ pub mod codec; pub mod convert; pub mod frame; pub mod handoff; +pub mod mix; pub mod pool; pub mod queue; pub mod scale; diff --git a/crates/voelin-media/src/mix.rs b/crates/voelin-media/src/mix.rs new file mode 100644 index 0000000..e908a69 --- /dev/null +++ b/crates/voelin-media/src/mix.rs @@ -0,0 +1,1609 @@ +//! The stream's audio mixer: any number of sources into one 48 kHz stereo +//! signal ([`StreamMixer`]). +//! +//! - A source ([`MixerHandle::add_source`]) has a name, a gain and a mute, +//! and any number of inputs ([`SourceHandle::input`]): lock-free +//! single-producer rings that a capture thread fills at its own pace, at +//! any sample rate and channel count. Channels are mapped to stereo as +//! they are pushed; the rate is converted while mixing. +//! - The mixer runs on the caller's clock, one block at a time +//! ([`StreamMixer::mix`], paced by [`BlockClock`]). Each input is held at +//! a small fixed latency ([`MixerConfig::latency`], more for an input that +//! delivers in larger bursts or keeps arriving late): it starts once that +//! much is buffered, and an input that runs dry (its capture stalled, +//! nothing plays, or it ended) fades out and waits to buffer again while +//! every other source goes on. Clock drift between a source and the mixer +//! is absorbed by resampling up to 0.5 % faster or slower while the +//! buffer is off target; the rest of the time a 48 kHz input is copied +//! through bit-exact. +//! - Rate conversion is cubic (Catmull-Rom) interpolation per input. +//! - The sum goes through a master gain and a soft limiter (a peak envelope +//! with 1 ms attack, gain reduction above the threshold, and a soft clip +//! of what the envelope is too slow for), so the output never exceeds +//! full scale; below the threshold it is untouched. +//! - Levels (peak falling back at 20 dB/s, RMS over about 300 ms) of each +//! source (after its gain, before its mute) and of the output are atomics: +//! [`SourceHandle::level`] and [`MixerHandle::level`] read them without +//! locking, from any thread. +//! - Buffers are allocated when a source or an input is created, sized from +//! the [`MixerConfig`]; mixing works in place in them and allocates +//! nothing per block. Sources, inputs, gains and mutes change while +//! mixing: control calls queue changes that the mixer picks up at its next +//! block (with a non-blocking try-lock that only contends with those +//! calls). + +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +use crate::frame::AUDIO_SAMPLE_RATE; + +/// Output rate of the mixer. +pub const MIX_RATE: u32 = AUDIO_SAMPLE_RATE; + +/// One stereo frame: left, right. +pub type Frame = [f32; 2]; + +const SILENCE: Frame = [0.0; 2]; +/// The most the drift correction speeds an input up or slows it down. +const MAX_CORRECTION: f64 = 0.005; +/// Buffer error (seconds) above which the drift correction starts ... +const DRIFT_ENGAGE: f64 = 0.010; +/// ... and below which it winds down again. +const DRIFT_RELEASE: f64 = 0.002; +/// The correction aims to remove the error within this many seconds. +const DRIFT_TIME: f64 = 4.0; +/// Time constant of an input's average buffer level (seconds). +const FILL_TIME: f64 = 1.0; +/// Time constant (seconds) in which an input's largest burst is forgotten. +const BURST_TIME: f64 = 15.0; +/// Headroom beyond the largest burst and a block (seconds). +const BURST_MARGIN: f64 = 0.005; +/// Frames faded in when an input starts, and out when it runs dry. +const FADE: usize = 32; +/// Latency added to an input that ran dry and came back within +/// [`HICCUP`]: it delivers too unevenly for its latency. +const UNDERRUN_STEP: f64 = 0.010; +const HICCUP: f64 = 0.25; +/// Peak meters fall back this fast (dB per second). +const PEAK_FALL: f32 = 20.0; +/// Time constant of the RMS meters (seconds). +const RMS_TIME: f32 = 0.3; +/// Attack of the limiter's envelope (seconds). +const LIMITER_ATTACK: f32 = 0.001; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// How the mixer is set up; buffers are sized from it. +#[derive(Clone, Debug, PartialEq)] +pub struct MixerConfig { + /// Largest block [`StreamMixer::mix`] handles at once, in frames + /// (longer calls are split). Default 960: 20 ms, one Opus frame. + pub max_block: usize, + /// How far behind its capture each input is mixed, to absorb uneven + /// delivery. Inputs that deliver in larger bursts get more. Default + /// 40 ms. + pub latency: Duration, + /// Ring size of each input: how far ahead of the mixer a capture can + /// get before audio is dropped. Default 500 ms. + pub buffer: Duration, + /// Soft-limiter threshold, linear (0 to 1]. Default -1 dBFS. + pub limiter_threshold: f32, + /// How fast the limiter lets go. Default 100 ms. + pub limiter_release: Duration, +} + +impl Default for MixerConfig { + fn default() -> Self { + Self { + max_block: 960, + latency: Duration::from_millis(40), + buffer: Duration::from_millis(500), + limiter_threshold: 0.891, + limiter_release: Duration::from_millis(100), + } + } +} + +/// An `f32` in an `AtomicU32` (relaxed: every value is complete on its own). +struct AtomicF32(AtomicU32); + +impl AtomicF32 { + fn new(value: f32) -> Self { + Self(AtomicU32::new(value.to_bits())) + } + + fn load(&self) -> f32 { + f32::from_bits(self.0.load(Ordering::Relaxed)) + } + + fn store(&self, value: f32) { + self.0.store(value.to_bits(), Ordering::Relaxed); + } +} + +/// A meter reading, linear (1.0 is full scale). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Level { + /// Highest sample, falling back at 20 dB/s. + pub peak: f32, + /// Root mean square over about 300 ms (both channels). + pub rms: f32, +} + +impl Level { + pub fn peak_db(&self) -> f32 { + to_db(self.peak) + } + + pub fn rms_db(&self) -> f32 { + to_db(self.rms) + } +} + +/// dBFS of a linear level; -120 for silence. +pub fn to_db(level: f32) -> f32 { + if level > 1e-6 { 20.0 * level.log10() } else { -120.0 } +} + +/// A level for readers on other threads. +struct Meter { + peak: AtomicF32, + rms: AtomicF32, +} + +impl Meter { + fn new() -> Self { + Self { peak: AtomicF32::new(0.0), rms: AtomicF32::new(0.0) } + } + + fn load(&self) -> Level { + Level { peak: self.peak.load(), rms: self.rms.load() } + } +} + +/// The mixer's side of a meter: fall-back and smoothing. +#[derive(Default)] +struct MeterState { + peak: f32, + mean_square: f32, +} + +/// Fall-back and smoothing factors for one block. +#[derive(Clone, Copy)] +struct Ballistics { + decay: f32, + alpha: f32, +} + +impl Ballistics { + fn new(frames: usize) -> Self { + let dt = frames as f32 / MIX_RATE as f32; + Self { decay: 10f32.powf(-PEAK_FALL / 20.0 * dt), alpha: 1.0 - (-dt / RMS_TIME).exp() } + } +} + +impl MeterState { + /// Take a block's peak and sum of squares (over `samples` samples). + fn update(&mut self, peak: f32, squares: f32, samples: usize, b: Ballistics, meter: &Meter) { + self.peak = peak.max(self.peak * b.decay); + let mean = if samples == 0 { 0.0 } else { squares / samples as f32 }; + self.mean_square += b.alpha * (mean - self.mean_square); + meter.peak.store(self.peak); + meter.rms.store(self.mean_square.max(0.0).sqrt()); + } +} + +/// What a source is doing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SourceState { + /// Nothing buffered to play: no input yet, nothing plays, or the + /// capture stalled. Silent until an input buffers its latency. + #[default] + Idle, + /// At least one input plays. + Playing, + /// Every input ended (their captures stopped). + Ended, +} + +impl SourceState { + fn from_u8(value: u8) -> Self { + match value { + 1 => Self::Playing, + 2 => Self::Ended, + _ => Self::Idle, + } + } +} + +/// Counters of a source ([`SourceHandle::stats`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SourceStats { + pub state: SourceState, + /// Inputs feeding it. + pub inputs: usize, + /// How far behind their captures its playing inputs are mixed (the + /// largest average buffer level). + pub latency: Duration, + /// Times an input ran dry while playing (and came back soon: delivery + /// hiccups, not pauses). + pub underruns: u64, + /// Frames dropped because an input's ring was full (the mixer was held + /// up or stopped). + pub overflows: u64, + /// Frames skipped to bring an input that got far ahead back to its + /// latency. + pub skipped: u64, +} + +/// Burst size of an input, written by its producer. +struct LaneShared { + max_push: AtomicUsize, +} + +struct SourceShared { + id: u64, + name: String, + gain: AtomicF32, + muted: AtomicBool, + removed: AtomicBool, + meter: Meter, + state: AtomicU8, + inputs: AtomicUsize, + latency_us: AtomicU64, + underruns: AtomicU64, + overflows: AtomicU64, + skipped: AtomicU64, + /// Inputs the mixer has not picked up yet. + new_lanes: Mutex>, + has_new_lanes: AtomicBool, +} + +struct MixerShared { + config: MixerConfig, + next_id: AtomicU64, + /// The sources, in the order they were added (for listing). + sources: Mutex>>, + /// Sources the mixer has not picked up yet. + new_sources: Mutex>, + has_new_sources: AtomicBool, + gain: AtomicF32, + meter: Meter, + /// The limiter's current gain (1: not limiting). + limiter: AtomicF32, + /// Frames mixed. + frames: AtomicU64, +} + +/// One input as the mixer sees it: the consuming end of its ring, the +/// resampler window and the latency / drift state. +struct Lane { + ring: rtrb::Consumer, + shared: Arc, + rate: u32, + capacity: usize, + /// Input frames per output frame, without drift correction. + step: f64, + /// Relative speed-up (positive) or slow-down of the drift correction. + correction: f64, + /// The correction is winding down (at 48 kHz: until the phase lines + /// up with a sample again, so the input is copied bit-exact after). + releasing: bool, + /// Frames read from the ring and not passed yet: `window[0]` is the + /// frame before the next output position, which is `pos` in [1, 2). + window: Vec, + pos: f64, + playing: bool, + /// Played before: running dry counts as an underrun. + started: bool, + /// Frames faded in since starting. + faded: usize, + /// Average buffer level before a block is read (input frames). + fill: f64, + /// The level the drift correction keeps: where the input settled in + /// its first second of playing. + setpoint: Option, + settle_sum: f64, + settle_blocks: u32, + /// Largest burst seen lately (input frames). + burst: f64, + /// Latency added after hiccups (input frames). + extra: usize, + /// Blocks since the input ran dry. + dry_blocks: u64, + ended: bool, +} + +impl Lane { + fn new(config: &MixerConfig, rate: u32) -> (Self, rtrb::Producer, Arc) { + let rate = rate.max(1); + let step = f64::from(rate) / f64::from(MIX_RATE); + let window = max_input(config.max_block, step) + 8; + let capacity = + ((config.buffer.as_secs_f64() * f64::from(rate)).ceil() as usize).max(4 * window); + let (producer, ring) = rtrb::RingBuffer::new(capacity); + let shared = Arc::new(LaneShared { max_push: AtomicUsize::new(0) }); + let lane = Self { + ring, + shared: shared.clone(), + rate, + capacity, + step, + correction: 0.0, + releasing: false, + window: Vec::with_capacity(window), + pos: 1.0, + playing: false, + started: false, + faded: 0, + fill: 0.0, + setpoint: None, + settle_sum: 0.0, + settle_blocks: 0, + burst: 0.0, + extra: 0, + dry_blocks: 0, + ended: false, + }; + (lane, producer, shared) + } + + /// Input frames needed for `n` output frames at most. + fn max_input(&self, n: usize) -> usize { + max_input(n, self.step) + } + + /// Frames to buffer before playing. + fn target(&self, n: usize, latency: f64) -> usize { + let rate = f64::from(self.rate); + let base = (latency * rate) as usize; + let burst = self.burst as usize + self.max_input(n) + (BURST_MARGIN * rate) as usize; + (base.max(burst) + self.extra).min(self.capacity * 3 / 4) + } + + fn start(&mut self, avail: usize) { + self.window.clear(); + self.window.push(SILENCE); + self.pos = 1.0; + self.correction = 0.0; + self.releasing = false; + self.faded = 0; + self.playing = true; + self.settle(avail); + // Back soon after running dry: a hiccup, not a pause. + let dry = self.dry_blocks as f64 * 0.02; + if self.started && dry < HICCUP { + self.extra += (UNDERRUN_STEP * f64::from(self.rate)) as usize; + } + self.started = true; + } + + /// Render `out.len()` frames into `out` (overwriting it). Returns + /// `false`, with `out` untouched, while the input is not playing. + fn render(&mut self, out: &mut [Frame], latency: f64, source: &SourceShared) -> bool { + let n = out.len(); + let recent = self.shared.max_push.swap(0, Ordering::Relaxed) as f64; + let dt = n as f64 / f64::from(MIX_RATE); + self.burst = recent.max(self.burst * (-dt / BURST_TIME).exp()); + let mut avail = self.ring.slots(); + let target = self.target(n, latency); + if !self.playing { + let abandoned = self.ring.is_abandoned(); + if avail >= target.max(1) || (abandoned && avail > 0) { + self.start(avail); + } else { + self.ended = abandoned; + self.dry_blocks += 1; + return false; + } + } + // Far ahead (the mixer was held up, or the source runs fast): skip + // back to the target. + if avail > 2 * target + self.max_input(n) { + let skip = avail - target; + if let Ok(chunk) = self.ring.read_chunk(skip) { + chunk.commit_all(); + } + source.skipped.fetch_add(skip as u64, Ordering::Relaxed); + avail = target; + self.settle(avail); + } + self.steer(n, avail); + + // Read what this block needs. + let step = self.step * (1.0 + self.correction); + let reach = if self.releasing { step.max(self.step) } else { step }; + let need = ((self.pos + (n - 1) as f64 * reach) as usize + 3).min(self.window.capacity()); + let take = need.saturating_sub(self.window.len()).min(avail); + if take > 0 + && let Ok(chunk) = self.ring.read_chunk(take) + { + let (a, b) = chunk.as_slices(); + self.window.extend_from_slice(a); + self.window.extend_from_slice(b); + chunk.commit_all(); + } + + let produced = self.interpolate(out); + out[produced..].fill(SILENCE); + // Fade in after starting. + for frame in out[..produced].iter_mut() { + if self.faded >= FADE { + break; + } + self.faded += 1; + let g = self.faded as f32 / (FADE + 1) as f32; + *frame = [frame[0] * g, frame[1] * g]; + } + if produced < n { + // Ran dry: fade out what there was and wait for the latency again. + let m = produced.min(FADE); + for (j, frame) in out[produced - m..produced].iter_mut().enumerate() { + let g = (m - j) as f32 / (m + 1) as f32; + *frame = [frame[0] * g, frame[1] * g]; + } + if !self.ring.is_abandoned() { + source.underruns.fetch_add(1, Ordering::Relaxed); + } + self.playing = false; + self.dry_blocks = 0; + } else { + // Keep one frame of history before the next position. + let drop = (self.pos as usize).saturating_sub(1).min(self.window.len()); + self.window.drain(..drop); + self.pos -= drop as f64; + } + true + } + + /// Measure the level to keep afresh. + fn settle(&mut self, avail: usize) { + self.fill = avail as f64; + self.setpoint = None; + self.settle_sum = 0.0; + self.settle_blocks = 0; + self.correction = 0.0; + self.releasing = false; + } + + /// Drift correction: keep the average buffer level at the setpoint. + /// Starting at a burst's peak or trough is no drift, so the setpoint is + /// the average of the first second rather than the start threshold. + fn steer(&mut self, n: usize, avail: usize) { + let Some(setpoint) = self.setpoint else { + self.settle_sum += avail as f64; + self.settle_blocks += 1; + self.fill = self.settle_sum / f64::from(self.settle_blocks); + if f64::from(self.settle_blocks) * n as f64 >= FILL_TIME * f64::from(MIX_RATE) { + self.setpoint = Some(self.fill); + } + return; + }; + let alpha = 1.0 - (-(n as f64) / (f64::from(MIX_RATE) * FILL_TIME)).exp(); + self.fill += alpha * (avail as f64 - self.fill); + let error = (self.fill - setpoint) / f64::from(self.rate); + let wanted = (error / DRIFT_TIME).clamp(-MAX_CORRECTION, MAX_CORRECTION); + if self.correction == 0.0 { + if error.abs() > DRIFT_ENGAGE { + self.correction = wanted; + self.releasing = false; + } + } else if error.abs() < DRIFT_RELEASE || error.signum() != self.correction.signum() { + self.releasing = true; + } else if !self.releasing { + self.correction = wanted; + } + } + + /// Interpolate from the window into `out`; returns the frames produced + /// (fewer when the window runs out) and advances `pos`. + fn interpolate(&mut self, out: &mut [Frame]) -> usize { + let base = self.step; + if self.releasing && base != 1.0 { + // Changing the step keeps the phase: nothing to line up. + self.correction = 0.0; + self.releasing = false; + } + let len = self.window.len(); + let mut step = base * (1.0 + self.correction); + let mut x = self.pos; + if step == 1.0 && x.fract() == 0.0 { + // 48 kHz in step: a plain copy. + let i = x as usize; + let count = out.len().min(len.saturating_sub(i + 2)); + out[..count].copy_from_slice(&self.window[i..i + count]); + self.pos = x + count as f64; + return count; + } + let snap = (step - base).abs(); + let w = &self.window; + for (k, frame) in out.iter_mut().enumerate() { + let i = x as usize; + if i + 2 >= len { + self.pos = x; + return k; + } + let mut t = x - i as f64; + if self.releasing && t < snap { + // In phase with the input again: stop correcting. + x = i as f64; + t = 0.0; + step = base; + self.correction = 0.0; + self.releasing = false; + } + let t = t as f32; + let (p0, p1, p2, p3) = (w[i - 1], w[i], w[i + 1], w[i + 2]); + *frame = [cubic(p0[0], p1[0], p2[0], p3[0], t), cubic(p0[1], p1[1], p2[1], p3[1], t)]; + x += step; + } + self.pos = x; + out.len() + } +} + +/// Input frames for `n` output frames at `step`, with drift correction and +/// the interpolator's reach. +fn max_input(n: usize, step: f64) -> usize { + (n as f64 * step * (1.0 + MAX_CORRECTION)).ceil() as usize + 4 +} + +/// Catmull-Rom interpolation between `p1` (t = 0, returned exactly) and +/// `p2` (t = 1). +#[inline] +fn cubic(p0: f32, p1: f32, p2: f32, p3: f32, t: f32) -> f32 { + let a = -0.5 * p0 + 1.5 * p1 - 1.5 * p2 + 0.5 * p3; + let b = p0 - 2.5 * p1 + 2.0 * p2 - 0.5 * p3; + let c = 0.5 * (p2 - p0); + ((a * t + b) * t + c) * t + p1 +} + +/// A source as the mixer sees it. +struct MixSource { + shared: Arc, + lanes: Vec, + /// Gain and mute (1 or 0) the last block ended with; the next block + /// ramps from these to the current settings. + gain: f32, + mute: f32, + had_lanes: bool, + meter: MeterState, +} + +/// Envelope-following soft limiter. +struct Limiter { + threshold: f32, + attack: f32, + release: f32, + envelope: f32, + /// Lowest gain of the last block, for [`MixerHandle::limiter_gain`]. + lowest: f32, +} + +impl Limiter { + fn new(config: &MixerConfig) -> Self { + let coeff = |seconds: f32| (-1.0 / (seconds.max(1e-4) * MIX_RATE as f32)).exp(); + Self { + threshold: config.limiter_threshold.clamp(0.01, 1.0), + attack: coeff(LIMITER_ATTACK), + release: coeff(config.limiter_release.as_secs_f32()), + envelope: 0.0, + lowest: 1.0, + } + } + + #[inline] + fn process(&mut self, frame: &mut Frame) { + let peak = frame[0].abs().max(frame[1].abs()); + let coeff = if peak > self.envelope { self.attack } else { self.release }; + self.envelope = peak + coeff * (self.envelope - peak); + if self.envelope > self.threshold { + let gain = self.threshold / self.envelope; + self.lowest = self.lowest.min(gain); + frame[0] *= gain; + frame[1] *= gain; + } + frame[0] = soft_clip(frame[0], self.threshold); + frame[1] = soft_clip(frame[1], self.threshold); + } +} + +/// Unchanged up to `threshold`, then bending smoothly towards 1.0. +#[inline] +fn soft_clip(x: f32, threshold: f32) -> f32 { + let a = x.abs(); + if a <= threshold { + return x; + } + let knee = 1.0 - threshold; + if knee <= 0.0 { + return x.signum(); + } + (threshold + knee * ((a - threshold) / knee).tanh()).copysign(x) +} + +/// Mixes the sources; lives on the thread that paces the audio. Control it +/// from anywhere through [`StreamMixer::handle`]. +pub struct StreamMixer { + shared: Arc, + sources: Vec, + lane_buf: Vec, + source_buf: Vec, + mix_buf: Vec, + limiter: Limiter, + gain: f32, + meter: MeterState, +} + +impl Default for StreamMixer { + fn default() -> Self { + Self::new(MixerConfig::default()) + } +} + +impl StreamMixer { + pub fn new(config: MixerConfig) -> Self { + let config = MixerConfig { max_block: config.max_block.max(1), ..config }; + let block = config.max_block; + let limiter = Limiter::new(&config); + let shared = Arc::new(MixerShared { + config, + next_id: AtomicU64::new(1), + sources: Mutex::new(Vec::new()), + new_sources: Mutex::new(Vec::new()), + has_new_sources: AtomicBool::new(false), + gain: AtomicF32::new(1.0), + meter: Meter::new(), + limiter: AtomicF32::new(1.0), + frames: AtomicU64::new(0), + }); + Self { + shared, + sources: Vec::with_capacity(16), + lane_buf: vec![SILENCE; block], + source_buf: vec![SILENCE; block], + mix_buf: vec![SILENCE; block], + limiter, + gain: 1.0, + meter: MeterState::default(), + } + } + + pub fn handle(&self) -> MixerHandle { + MixerHandle { shared: self.shared.clone() } + } + + pub fn config(&self) -> &MixerConfig { + &self.shared.config + } + + /// Mix `out.len() / 2` frames of interleaved stereo into `out` + /// (overwriting it), on the caller's clock. + pub fn mix(&mut self, out: &mut [f32]) { + let block = self.shared.config.max_block * 2; + let even = out.len() & !1; + let (frames, rest) = out.split_at_mut(even); + for chunk in frames.chunks_mut(block) { + self.mix_block(chunk); + } + rest.fill(0.0); + } + + /// Pick up new sources and inputs, drop removed sources. + fn adopt(&mut self) { + if self.shared.has_new_sources.load(Ordering::Acquire) + && let Ok(mut new) = self.shared.new_sources.try_lock() + { + self.shared.has_new_sources.store(false, Ordering::Relaxed); + for mut source in new.drain(..) { + source.gain = source.shared.gain.load(); + source.mute = if source.shared.muted.load(Ordering::Relaxed) { 0.0 } else { 1.0 }; + self.sources.push(source); + } + } + self.sources.retain(|s| !s.shared.removed.load(Ordering::Relaxed)); + for source in &mut self.sources { + if source.shared.has_new_lanes.load(Ordering::Acquire) + && let Ok(mut new) = source.shared.new_lanes.try_lock() + { + source.shared.has_new_lanes.store(false, Ordering::Relaxed); + source.lanes.append(&mut new); + } + } + } + + fn mix_block(&mut self, out: &mut [f32]) { + let n = out.len() / 2; + self.adopt(); + let latency = self.shared.config.latency.as_secs_f64(); + let ballistics = Ballistics::new(n); + let Self { sources, lane_buf, source_buf, mix_buf, .. } = self; + let mix = &mut mix_buf[..n]; + mix.fill(SILENCE); + for source in sources.iter_mut() { + let sum = &mut source_buf[..n]; + let lane_out = &mut lane_buf[..n]; + let shared = &*source.shared; + let mut any = false; + let mut latency_seconds = 0.0f64; + for lane in &mut source.lanes { + let into = if any { &mut *lane_out } else { &mut *sum }; + if lane.render(into, latency, shared) { + if any { + for (s, l) in sum.iter_mut().zip(lane_out.iter()) { + s[0] += l[0]; + s[1] += l[1]; + } + } + any = true; + } + if lane.playing { + latency_seconds = latency_seconds.max(lane.fill / f64::from(lane.rate)); + } + } + source.lanes.retain(|l| !l.ended); + if !source.lanes.is_empty() { + source.had_lanes = true; + } + let state = if any { + SourceState::Playing + } else if source.lanes.is_empty() && source.had_lanes { + SourceState::Ended + } else { + SourceState::Idle + }; + shared.state.store(state as u8, Ordering::Relaxed); + shared.inputs.store(source.lanes.len(), Ordering::Relaxed); + shared.latency_us.store((latency_seconds * 1e6) as u64, Ordering::Relaxed); + + let gain = shared.gain.load(); + let mute = if shared.muted.load(Ordering::Relaxed) { 0.0 } else { 1.0 }; + if !any { + source.meter.update(0.0, 0.0, 0, ballistics, &shared.meter); + source.gain = gain; + source.mute = mute; + continue; + } + let (peak, squares) = add_source(sum, mix, (source.gain, gain), (source.mute, mute)); + source.meter.update(peak, squares, 2 * n, ballistics, &shared.meter); + source.gain = gain; + source.mute = mute; + } + + // Master gain, limiter, meter, interleave. + let gain = self.shared.gain.load(); + let from = self.gain; + let ramp = (gain - from) / n as f32; + self.limiter.lowest = 1.0; + let (mut peak, mut squares) = (0.0f32, 0.0f32); + for (k, (frame, pair)) in mix.iter_mut().zip(out.chunks_exact_mut(2)).enumerate() { + let g = if ramp == 0.0 { gain } else { from + ramp * (k + 1) as f32 }; + if g != 1.0 { + frame[0] *= g; + frame[1] *= g; + } + self.limiter.process(frame); + peak = peak.max(frame[0].abs()).max(frame[1].abs()); + squares += frame[0] * frame[0] + frame[1] * frame[1]; + pair[0] = frame[0]; + pair[1] = frame[1]; + } + self.gain = gain; + self.meter.update(peak, squares, 2 * n, ballistics, &self.shared.meter); + self.shared.limiter.store(self.limiter.lowest); + self.shared.frames.fetch_add(n as u64, Ordering::Relaxed); + } +} + +/// Add `sum` into `mix` with gain and mute ramped from `.0` to `.1` over +/// the block; returns the peak and sum of squares after the gain (before +/// the mute). +fn add_source(sum: &[Frame], mix: &mut [Frame], gain: (f32, f32), mute: (f32, f32)) -> (f32, f32) { + let (mut peak, mut squares) = (0.0f32, 0.0f32); + let n = sum.len() as f32; + if gain.0 == gain.1 && mute.0 == mute.1 { + let (g, m) = (gain.1, mute.1); + for (s, o) in sum.iter().zip(mix.iter_mut()) { + let (l, r) = (s[0] * g, s[1] * g); + peak = peak.max(l.abs()).max(r.abs()); + squares += l * l + r * r; + o[0] += l * m; + o[1] += r * m; + } + } else { + let dg = (gain.1 - gain.0) / n; + let dm = (mute.1 - mute.0) / n; + for (k, (s, o)) in sum.iter().zip(mix.iter_mut()).enumerate() { + let t = (k + 1) as f32; + let (g, m) = (gain.0 + dg * t, mute.0 + dm * t); + let (l, r) = (s[0] * g, s[1] * g); + peak = peak.max(l.abs()).max(r.abs()); + squares += l * l + r * r; + o[0] += l * m; + o[1] += r * m; + } + } + (peak, squares) +} + +impl Drop for StreamMixer { + fn drop(&mut self) { + // Inputs see the end (`SourceInput::is_closed`). + for source in lock(&self.shared.sources).iter() { + source.removed.store(true, Ordering::Relaxed); + } + for source in lock(&self.shared.new_sources).iter() { + source.shared.removed.store(true, Ordering::Relaxed); + } + } +} + +/// Controls a [`StreamMixer`] from any thread. Cheap to clone. +#[derive(Clone)] +pub struct MixerHandle { + shared: Arc, +} + +impl MixerHandle { + /// A new source (gain 1, not muted) with no inputs yet; the mixer picks + /// it up at its next block. + pub fn add_source(&self, name: impl Into) -> SourceHandle { + let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed); + let shared = Arc::new(SourceShared { + id, + name: name.into(), + gain: AtomicF32::new(1.0), + muted: AtomicBool::new(false), + removed: AtomicBool::new(false), + meter: Meter::new(), + state: AtomicU8::new(SourceState::Idle as u8), + inputs: AtomicUsize::new(0), + latency_us: AtomicU64::new(0), + underruns: AtomicU64::new(0), + overflows: AtomicU64::new(0), + skipped: AtomicU64::new(0), + new_lanes: Mutex::new(Vec::new()), + has_new_lanes: AtomicBool::new(false), + }); + let source = MixSource { + shared: shared.clone(), + lanes: Vec::with_capacity(4), + gain: 1.0, + mute: 1.0, + had_lanes: false, + meter: MeterState::default(), + }; + lock(&self.shared.sources).push(shared.clone()); + lock(&self.shared.new_sources).push(source); + self.shared.has_new_sources.store(true, Ordering::Release); + SourceHandle { mixer: self.shared.clone(), shared } + } + + /// The sources, in the order they were added. + pub fn sources(&self) -> Vec { + lock(&self.shared.sources) + .iter() + .map(|s| SourceHandle { mixer: self.shared.clone(), shared: s.clone() }) + .collect() + } + + pub fn source(&self, id: u64) -> Option { + lock(&self.shared.sources) + .iter() + .find(|s| s.id == id) + .map(|s| SourceHandle { mixer: self.shared.clone(), shared: s.clone() }) + } + + /// Gain after the sum, before the limiter (linear; ramps over a block). + pub fn set_gain(&self, gain: f32) { + self.shared.gain.store(sanitize_gain(gain)); + } + + pub fn gain(&self) -> f32 { + self.shared.gain.load() + } + + /// Output level (after the limiter). Lock-free. + pub fn level(&self) -> Level { + self.shared.meter.load() + } + + /// The limiter's lowest gain in the last block: 1 when it did nothing, + /// 0.5 for 6 dB of reduction. Lock-free. + pub fn limiter_gain(&self) -> f32 { + self.shared.limiter.load() + } + + /// Frames mixed so far. + pub fn frames(&self) -> u64 { + self.shared.frames.load(Ordering::Relaxed) + } + + pub fn config(&self) -> &MixerConfig { + &self.shared.config + } +} + +fn sanitize_gain(gain: f32) -> f32 { + if gain.is_finite() { gain.max(0.0) } else { 1.0 } +} + +/// Controls one source of a [`StreamMixer`]. Cheap to clone; the source +/// stays until [`remove`](Self::remove)d. +#[derive(Clone)] +pub struct SourceHandle { + mixer: Arc, + shared: Arc, +} + +impl std::fmt::Debug for SourceHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SourceHandle") + .field("id", &self.shared.id) + .field("name", &self.shared.name) + .finish() + } +} + +impl SourceHandle { + pub fn id(&self) -> u64 { + self.shared.id + } + + pub fn name(&self) -> &str { + &self.shared.name + } + + /// Linear gain, any value >= 0 (1: unchanged); ramps over one block. + pub fn set_gain(&self, gain: f32) { + self.shared.gain.store(sanitize_gain(gain)); + } + + pub fn gain(&self) -> f32 { + self.shared.gain.load() + } + + /// Mute (ramped over one block). A muted source is still read and + /// metered. + pub fn set_muted(&self, muted: bool) { + self.shared.muted.store(muted, Ordering::Relaxed); + } + + pub fn muted(&self) -> bool { + self.shared.muted.load(Ordering::Relaxed) + } + + /// Level after the gain, before the mute. Lock-free. + pub fn level(&self) -> Level { + self.shared.meter.load() + } + + pub fn state(&self) -> SourceState { + SourceState::from_u8(self.shared.state.load(Ordering::Relaxed)) + } + + pub fn stats(&self) -> SourceStats { + let s = &self.shared; + SourceStats { + state: self.state(), + inputs: s.inputs.load(Ordering::Relaxed), + latency: Duration::from_micros(s.latency_us.load(Ordering::Relaxed)), + underruns: s.underruns.load(Ordering::Relaxed), + overflows: s.overflows.load(Ordering::Relaxed), + skipped: s.skipped.load(Ordering::Relaxed), + } + } + + /// A new input at `rate` Hz for a capture thread to push into. A source + /// can have any number; each ends when its [`SourceInput`] is dropped + /// and what it buffered has played. + pub fn input(&self, rate: u32) -> SourceInput { + let (lane, ring, lane_shared) = Lane::new(&self.mixer.config, rate); + lock(&self.shared.new_lanes).push(lane); + self.shared.has_new_lanes.store(true, Ordering::Release); + SourceInput { + ring, + lane: lane_shared, + source: self.shared.clone(), + rate: rate.max(1), + weights: Vec::new(), + } + } + + /// Take the source out of the mix (from the next block); its inputs see + /// [`SourceInput::is_closed`]. + pub fn remove(&self) { + self.shared.removed.store(true, Ordering::Relaxed); + lock(&self.mixer.sources).retain(|s| s.id != self.shared.id); + lock(&self.shared.new_lanes).clear(); + } + + pub fn is_removed(&self) -> bool { + self.shared.removed.load(Ordering::Relaxed) + } +} + +/// The producing end of a source's input, for one capture thread. Pushing +/// never blocks or allocates (except a new channel count's downmix +/// weights); frames that do not fit in the ring are dropped and counted. +pub struct SourceInput { + ring: rtrb::Producer, + lane: Arc, + source: Arc, + rate: u32, + /// Downmix weights for more than two channels: (left, right) per + /// channel. + weights: Vec, +} + +impl std::fmt::Debug for SourceInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SourceInput") + .field("source", &self.source.id) + .field("rate", &self.rate) + .finish() + } +} + +/// Non-finite samples become silence. +#[inline] +fn clean(x: f32) -> f32 { + if x.is_finite() { x } else { 0.0 } +} + +/// Stereo weights for `channels` > 2 in WAVE order (FL FR FC LFE BL BR +/// FLC FRC ...): front left and right as they are, centre into both at +/// -3 dB, LFE dropped, the rest alternately left and right at -3 dB. Four +/// channels are taken as quad (FL FR BL BR). +fn downmix_weights(channels: usize, weights: &mut Vec) { + const H: f32 = std::f32::consts::FRAC_1_SQRT_2; + weights.clear(); + weights.extend([[1.0, 0.0], [0.0, 1.0]]); + let mut rest = 2; + if channels == 3 || channels >= 5 { + weights.push([H, H]); + rest = 3; + } + if channels >= 6 { + weights.push([0.0, 0.0]); + rest = 4; + } + for i in rest..channels { + weights.push(if (i - rest) % 2 == 0 { [H, 0.0] } else { [0.0, H] }); + } +} + +impl SourceInput { + pub fn rate(&self) -> u32 { + self.rate + } + + /// The source it feeds. + pub fn source_id(&self) -> u64 { + self.source.id + } + + /// The source was removed or the mixer is gone: stop capturing. + pub fn is_closed(&self) -> bool { + self.source.removed.load(Ordering::Relaxed) || self.ring.is_abandoned() + } + + /// Frames that fit now. + pub fn free(&self) -> usize { + self.ring.slots() + } + + /// Push interleaved samples with `channels` channels (mono is played on + /// both sides, more than two are downmixed). Returns the frames taken. + pub fn push(&mut self, samples: &[f32], channels: u16) -> usize { + match channels { + 0 => 0, + 1 => self.push_frames(samples.iter().map(|&s| [clean(s), clean(s)])), + 2 => self.push_frames(samples.chunks_exact(2).map(|f| [clean(f[0]), clean(f[1])])), + n => { + let n = usize::from(n); + if self.weights.len() != n { + downmix_weights(n, &mut self.weights); + } + let weights = std::mem::take(&mut self.weights); + let taken = self.push_frames(samples.chunks_exact(n).map(|f| { + let mut out = SILENCE; + for (s, w) in f.iter().zip(&weights) { + let s = clean(*s); + out[0] += s * w[0]; + out[1] += s * w[1]; + } + out + })); + self.weights = weights; + taken + } + } + } + + /// Push stereo frames. Returns the frames taken (the rest did not fit + /// and is counted as overflow). + pub fn push_frames(&mut self, frames: I) -> usize + where + I: IntoIterator, + I::IntoIter: ExactSizeIterator, + { + let frames = frames.into_iter(); + let len = frames.len(); + if len == 0 { + return 0; + } + self.lane.max_push.fetch_max(len, Ordering::Relaxed); + let n = len.min(self.ring.slots()); + let taken = match self.ring.write_chunk_uninit(n) { + Ok(chunk) => chunk.fill_from_iter(frames), + Err(_) => 0, + }; + if taken < len { + self.source.overflows.fetch_add((len - taken) as u64, Ordering::Relaxed); + } + taken + } + + /// Push `frames` frames of silence (e.g. a muted microphone). + pub fn push_silence(&mut self, frames: usize) -> usize { + self.push_frames(std::iter::repeat_n(SILENCE, frames)) + } +} + +/// Paces mixing on the monotonic clock: which blocks of `frames` frames are +/// due. Block `k` is due `k * frames / 48000` s after the start, computed +/// exactly (no drift). +pub struct BlockClock { + start: Instant, + frames: u64, + blocks: u64, + /// After falling this many blocks behind (a suspended machine), skip + /// ahead instead of mixing a burst. + max_behind: u64, +} + +impl BlockClock { + pub fn new(frames: usize) -> Self { + Self::starting_at(Instant::now(), frames) + } + + pub fn starting_at(start: Instant, frames: usize) -> Self { + Self { start, frames: frames.max(1) as u64, blocks: 0, max_behind: 25 } + } + + fn at(&self, block: u64) -> Instant { + let nanos = + u128::from(block) * u128::from(self.frames) * 1_000_000_000 / u128::from(MIX_RATE); + self.start + Duration::from_nanos(nanos as u64) + } + + /// When the next block is due. + pub fn next(&self) -> Instant { + self.at(self.blocks) + } + + /// The numbers of the blocks due at `now` (empty: wait until + /// [`next`](Self::next)). A block's number is the audio's position in + /// blocks since the start (e.g. its RTP time is `number * frames`). + /// After a long stall only the newest block is due; the numbers jump + /// ahead with the time. + pub fn due(&mut self, now: Instant) -> std::ops::Range { + if now < self.next() { + return self.blocks..self.blocks; + } + let elapsed = now.duration_since(self.start).as_nanos(); + let reached = + (elapsed * u128::from(MIX_RATE) / (u128::from(self.frames) * 1_000_000_000)) as u64 + 1; + let from = if reached - self.blocks > self.max_behind { reached - 1 } else { self.blocks }; + self.blocks = reached; + from..reached + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BLOCK: usize = 960; + + fn config() -> MixerConfig { + MixerConfig { max_block: BLOCK, latency: Duration::from_millis(40), ..Default::default() } + } + + /// Interleaved stereo DC. + fn dc(frames: usize, left: f32, right: f32) -> Vec { + (0..frames).flat_map(|_| [left, right]).collect() + } + + fn sine(frames: usize, start: usize, rate: u32, freq: f64, amplitude: f32) -> Vec { + (start..start + frames) + .flat_map(|i| { + let s = amplitude + * (2.0 * std::f64::consts::PI * freq * i as f64 / f64::from(rate)).sin() as f32; + [s, s] + }) + .collect() + } + + /// Goertzel magnitude of `freq` in the left channel, normalised so a + /// full sine of amplitude `a` gives about `a / 2`. + fn tone(samples: &[f32], freq: f64) -> f64 { + let left: Vec = samples.chunks_exact(2).map(|f| f64::from(f[0])).collect(); + let k = 2.0 * (2.0 * std::f64::consts::PI * freq / f64::from(MIX_RATE)).cos(); + let (mut s1, mut s2) = (0.0, 0.0); + for x in &left { + let s0 = x + k * s1 - s2; + s2 = s1; + s1 = s0; + } + (s1 * s1 + s2 * s2 - k * s1 * s2).max(0.0).sqrt() / left.len() as f64 + } + + /// Run `blocks` blocks: before each, `feed` pushes for that block. + fn run(mixer: &mut StreamMixer, blocks: usize, mut feed: impl FnMut(usize)) -> Vec { + let mut out = Vec::new(); + let mut block = vec![0.0; BLOCK * 2]; + for b in 0..blocks { + feed(b); + mixer.mix(&mut block); + out.extend_from_slice(&block); + } + out + } + + #[test] + fn sums_after_the_latency() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let mut a = handle.add_source("a").input(MIX_RATE); + let mut b = handle.add_source("b").input(MIX_RATE); + let out = run(&mut mixer, 20, |_| { + a.push(&dc(BLOCK, 0.25, 0.125), 2); + b.push(&dc(BLOCK, 0.25, -0.5), 2); + }); + // Silent while buffering (40 ms plus a block of headroom) ... + assert!(out[..2 * BLOCK].iter().all(|&s| s == 0.0)); + // ... then exact sums (past the fade-in). + let tail = &out[out.len() - 4 * BLOCK..]; + for f in tail.chunks_exact(2) { + assert_eq!(f, [0.5, -0.375]); + } + for s in handle.sources() { + assert_eq!(s.state(), SourceState::Playing); + assert_eq!(s.stats().underruns, 0); + assert!(s.stats().latency >= Duration::from_millis(40), "{:?}", s.stats()); + } + } + + #[test] + fn gains_and_mute_ramp_and_meter() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let source = handle.add_source("a"); + source.set_gain(0.5); + let mut input = source.input(MIX_RATE); + let mut feed = |_| { + input.push(&dc(BLOCK, 0.8, 0.8), 2); + }; + let out = run(&mut mixer, 10, &mut feed); + assert_eq!(out[out.len() - 2], 0.4); + let level = source.level(); + // The RMS meter rises over about 300 ms towards 0.4. + assert!((level.peak - 0.4).abs() < 1e-6 && (0.2..=0.4).contains(&level.rms), "{level:?}"); + assert!((handle.level().peak - 0.4).abs() < 1e-6); + + // A gain change ramps over one block, then holds. + source.set_gain(1.0); + let out = run(&mut mixer, 2, &mut feed); + let first: Vec = out[..BLOCK * 2].iter().step_by(2).copied().collect(); + assert!(first.windows(2).all(|w| w[1] >= w[0]), "monotonic ramp"); + assert!((first[0] - 0.4).abs() < 0.01 && (first[BLOCK - 1] - 0.8).abs() < 1e-5); + assert!(out[BLOCK * 2..].iter().all(|&s| s == 0.8)); + + // Muted: silent output, the source meter still reads. + source.set_muted(true); + let out = run(&mut mixer, 3, &mut feed); + assert!(out[BLOCK * 2..].iter().all(|&s| s == 0.0)); + assert!(source.level().peak > 0.79); + assert!(source.muted()); + source.set_muted(false); + let out = run(&mut mixer, 2, &mut feed); + assert_eq!(out[out.len() - 1], 0.8); + } + + #[test] + fn master_gain_and_limiter() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let mut a = handle.add_source("a").input(MIX_RATE); + let mut b = handle.add_source("b").input(MIX_RATE); + // Below the threshold nothing changes. + let out = run(&mut mixer, 8, |b_| { + a.push(&sine(BLOCK, b_ * BLOCK, MIX_RATE, 440.0, 0.4), 2); + b.push(&sine(BLOCK, b_ * BLOCK, MIX_RATE, 440.0, 0.4), 2); + }); + assert!(out.iter().all(|s| s.abs() <= 0.8 + 1e-6)); + assert_eq!(handle.limiter_gain(), 1.0); + // 1.6 peak: limited below full scale, still loud and in tune. + let out = run(&mut mixer, 20, |b_| { + a.push(&sine(BLOCK, (b_ + 8) * BLOCK, MIX_RATE, 440.0, 0.8), 2); + b.push(&sine(BLOCK, (b_ + 8) * BLOCK, MIX_RATE, 440.0, 0.8), 2); + }); + let peak = out.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(peak <= 1.0, "{peak}"); + assert!(peak > 0.85, "{peak}"); + assert!(handle.limiter_gain() < 0.7, "{}", handle.limiter_gain()); + let tail = &out[out.len() - 8 * BLOCK..]; + assert!(tone(tail, 440.0) > 0.3, "{}", tone(tail, 440.0)); + // The master gain applies before the limiter. + handle.set_gain(0.25); + let out = run(&mut mixer, 6, |b_| { + a.push(&dc(BLOCK, 0.4, 0.4), 2); + b.push(&dc(BLOCK, 0.4, 0.4), 2); + let _ = b_; + }); + assert!((out[out.len() - 1] - 0.2).abs() < 1e-6, "{}", out[out.len() - 1]); + assert!(soft_clip(10.0, 0.891) <= 1.0 && soft_clip(-10.0, 0.891) >= -1.0); + assert_eq!(soft_clip(0.5, 0.891), 0.5); + } + + #[test] + fn resamples_and_maps_channels() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + // 44.1 kHz mono 1 kHz tone, 10 ms pushes. + let mut mono = handle.add_source("mono").input(44_100); + let mut n = 0; + let out = run(&mut mixer, 100, |_| { + for _ in 0..2 { + let block: Vec = (n..n + 441) + .map(|i| { + 0.5 * (2.0 * std::f64::consts::PI * 1000.0 * i as f64 / 44_100.0).sin() + as f32 + }) + .collect(); + n += 441; + mono.push(&block, 1); + } + }); + let tail = &out[out.len() - 50 * BLOCK * 2..]; + let at = tone(tail, 1000.0); + assert!(at > 0.2, "{at}"); + assert!(tone(tail, 1100.0) < at / 50.0); + // Both channels. + assert!(tail.chunks_exact(2).all(|f| f[0] == f[1])); + // Output keeps pace with input: nothing ran dry or piled up. + let stats = handle.sources()[0].stats(); + assert_eq!((stats.underruns, stats.skipped, stats.overflows), (0, 0, 0), "{stats:?}"); + + // 5.1 downmix: centre into both sides, LFE dropped. + let mut weights = Vec::new(); + downmix_weights(6, &mut weights); + assert_eq!(weights.len(), 6); + assert_eq!(weights[3], [0.0, 0.0]); + assert!(weights[2][0] > 0.7 && weights[2][1] > 0.7); + assert_eq!((weights[4][1], weights[5][0]), (0.0, 0.0)); + let mut mixer = StreamMixer::new(config()); + let mut six = mixer.handle().add_source("5.1").input(MIX_RATE); + let frame = [0.1, 0.2, 0.0, 1.0, 0.0, 0.0]; + let out = run(&mut mixer, 6, |_| { + let samples: Vec = frame.iter().copied().cycle().take(BLOCK * 6).collect(); + six.push(&samples, 6); + }); + assert_eq!(&out[out.len() - 2..], [0.1, 0.2]); + } + + #[test] + fn a_stalled_or_ended_source_does_not_hold_up_others() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let steady = handle.add_source("steady"); + let flaky = handle.add_source("flaky"); + let mut a = steady.input(MIX_RATE); + let mut b = flaky.input(MIX_RATE); + let mut feed = |block: usize, flaky_on: bool| { + a.push(&dc(BLOCK, 0.25, 0.25), 2); + if flaky_on { + b.push(&dc(BLOCK, 0.5, 0.5), 2); + } + let _ = block; + }; + let out = run(&mut mixer, 10, |b_| feed(b_, true)); + assert_eq!(out[out.len() - 1], 0.75); + // The flaky source stops: the steady one goes on alone. + let out = run(&mut mixer, 10, |b_| feed(b_, false)); + assert_eq!(out[out.len() - 1], 0.25); + assert_eq!(flaky.state(), SourceState::Idle); + assert_eq!(steady.state(), SourceState::Playing); + assert_eq!(steady.stats().underruns, 0); + // It comes back after buffering its latency. + let out = run(&mut mixer, 10, |b_| feed(b_, true)); + assert_eq!(out[out.len() - 1], 0.75); + assert_eq!(flaky.stats().underruns, 1); + // Its capture ends: what was buffered plays out, then it is ended. + drop(b); + let out = run(&mut mixer, 10, |_| { + a.push(&dc(BLOCK, 0.25, 0.25), 2); + }); + assert_eq!(out[out.len() - 1], 0.25); + assert_eq!(flaky.state(), SourceState::Ended); + assert_eq!(flaky.stats().inputs, 0); + assert_eq!(flaky.stats().underruns, 1, "an end is not an underrun"); + } + + #[test] + fn sources_come_and_go_while_mixing() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let a = handle.add_source("a"); + let mut ia = a.input(MIX_RATE); + let out = run(&mut mixer, 6, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + }); + assert_eq!(out[out.len() - 1], 0.1); + // Any number of sources, added live. + let many: Vec<(SourceHandle, SourceInput)> = (0..40) + .map(|i| { + let s = handle.add_source(format!("s{i}")); + s.set_gain(0.5); + let input = s.input(if i % 2 == 0 { MIX_RATE } else { 44_100 }); + (s, input) + }) + .collect(); + let mut many: Vec<_> = many; + let out = run(&mut mixer, 10, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + for (_, input) in many.iter_mut() { + let frames = if input.rate() == MIX_RATE { BLOCK } else { 882 }; + input.push(&dc(frames, 0.01, 0.01), 2); + } + }); + let expected = 0.1 + 40.0 * 0.005; + assert!((out[out.len() - 1] - expected).abs() < 1e-4, "{}", out[out.len() - 1]); + assert_eq!(handle.sources().len(), 41); + // Removed ones leave at the next block; their inputs see it. + for (s, _) in &many { + s.remove(); + } + assert!(many.iter().all(|(_, input)| input.is_closed())); + let out = run(&mut mixer, 2, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + }); + assert_eq!(out[out.len() - 1], 0.1); + assert_eq!(handle.sources().len(), 1); + // A second input on a live source adds to it. + let mut ib = a.input(MIX_RATE); + let out = run(&mut mixer, 8, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + ib.push(&dc(BLOCK, 0.2, 0.2), 2); + }); + assert!((out[out.len() - 1] - 0.3).abs() < 1e-6); + assert_eq!(a.stats().inputs, 2); + assert!(handle.source(a.id()).is_some()); + drop(mixer); + assert!(ia.is_closed()); + } + + #[test] + fn drift_is_absorbed() { + // A source whose clock runs 0.1 % fast and one 0.1 % slow, for five + // simulated minutes: no skips, no underruns, and the latency stays + // where it settled, give or take the correction band. + for ppm in [1000.0, -1000.0] { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let source = handle.add_source("drift"); + let mut input = source.input(MIX_RATE); + let per_block = BLOCK as f64 * (1.0 + ppm / 1e6); + let (mut owed, mut phase) = (0.0, 0usize); + let mut block = vec![0.0; BLOCK * 2]; + let mut settled = None; + let mut worst = 0.0f64; + for b in 0..15_000 { + owed += per_block; + let frames = owed as usize; + owed -= frames as f64; + input.push(&sine(frames, phase, MIX_RATE, 300.0, 0.3), 2); + phase += frames; + mixer.mix(&mut block); + let latency = source.stats().latency.as_secs_f64(); + if b == 200 { + settled = Some(latency); + } + if let Some(settled) = settled { + worst = worst.max((latency - settled).abs()); + } + } + let stats = source.stats(); + assert_eq!( + (stats.underruns, stats.skipped, stats.overflows), + (0, 0, 0), + "{ppm}: {stats:?}" + ); + // Uncorrected, 0.1 % is 300 ms after five minutes. + assert!(worst < 0.015, "{ppm}: latency moved by {worst} s"); + assert!(tone(&block, 300.0) > 0.1); + } + } + + #[test] + fn bursty_input_gets_more_latency() { + // 8192-frame bursts every 170 ms (a power-saving PipeWire quantum). + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let source = handle.add_source("bursty"); + let mut input = source.input(MIX_RATE); + let mut owed = 0usize; + let mut phase = 0; + let mut block = vec![0.0; BLOCK * 2]; + for _ in 0..500 { + owed += BLOCK; + if owed >= 8192 { + input.push(&sine(8192, phase, MIX_RATE, 500.0, 0.3), 2); + phase += 8192; + owed -= 8192; + } + mixer.mix(&mut block); + } + let stats = source.stats(); + assert!(stats.latency > Duration::from_millis(170), "{stats:?}"); + // At most the first burst ran short before the latency adapted. + assert!(stats.underruns <= 1, "{stats:?}"); + assert_eq!(source.state(), SourceState::Playing); + } + + #[test] + fn nan_and_short_calls() { + let mut mixer = StreamMixer::new(config()); + let mut input = mixer.handle().add_source("x").input(MIX_RATE); + let mut samples = dc(BLOCK * 4, 0.5, 0.5); + samples[10] = f32::NAN; + samples[11] = f32::INFINITY; + input.push(&samples, 2); + // Odd lengths and blocks longer than `max_block` are fine. + let mut out = vec![1.0; BLOCK * 3 + 1]; + mixer.mix(&mut out); + assert!(out.iter().all(|s| s.is_finite())); + assert_eq!(out[out.len() - 1], 0.0); + assert_eq!(input.push(&[], 2), 0); + assert_eq!(input.push(&[0.1], 0), 0); + } + + #[test] + fn cubic_is_exact_on_samples_and_lines() { + assert_eq!(cubic(0.3, -0.7, 0.2, 0.9, 0.0), -0.7); + // A straight line is reproduced. + let v = cubic(0.0, 1.0, 2.0, 3.0, 0.25); + assert!((v - 1.25).abs() < 1e-6, "{v}"); + } + + #[test] + fn block_clock_paces_and_skips_ahead() { + let start = Instant::now(); + let mut clock = BlockClock::starting_at(start, 960); + assert_eq!(clock.due(start), 0..1); + assert!(clock.due(start).is_empty()); + assert_eq!(clock.next(), start + Duration::from_millis(20)); + assert_eq!(clock.due(start + Duration::from_millis(59)), 1..3); + assert_eq!(clock.due(start + Duration::from_millis(60)), 3..4); + // Exact over a long run: 441 frames is 9.1875 ms. + let mut clock = BlockClock::starting_at(start, 441); + let mut total = 0; + for ms in 1..=10_000u64 { + let due = clock.due(start + Duration::from_millis(ms)); + total += due.end - due.start; + } + assert_eq!(total, 10_000 * 48 / 441 + 1); + // After a long stall only the newest block is due, numbered by the + // time. + let mut clock = BlockClock::starting_at(start, 960); + clock.due(start); + assert_eq!(clock.due(start + Duration::from_secs(10)), 500..501); + assert_eq!(clock.due(start + Duration::from_millis(10_020)), 501..502); + assert!(to_db(1.0).abs() < 1e-6 && to_db(0.0) == -120.0); + } +} diff --git a/crates/voelin-media/tests/mix_alloc.rs b/crates/voelin-media/tests/mix_alloc.rs new file mode 100644 index 0000000..2f6d314 --- /dev/null +++ b/crates/voelin-media/tests/mix_alloc.rs @@ -0,0 +1,122 @@ +//! The stream mixer allocates nothing per block: pushing into inputs and +//! mixing, with resampling, downmixing, drift correction, gain and mute +//! changes, stalls and restarts, counted with a global allocator that +//! counts only on the thread that asks. +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; + +use voelin_media::mix::{MixerConfig, StreamMixer}; + +thread_local! { + static COUNTING: Cell = const { Cell::new(false) }; + static COUNT: Cell = const { Cell::new(0) }; +} + +fn count() { + // `try_with`: never panics, also while the thread is torn down; const + // thread locals without destructors never allocate. + let _ = COUNTING.try_with(|on| { + if on.get() { + let _ = COUNT.try_with(|n| n.set(n.get() + 1)); + } + }); +} + +struct Counting; + +// SAFETY: every method forwards to `System` with the caller's arguments +// unchanged, so `System`'s guarantees hold; counting touches only +// thread-local cells and never allocates. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged (see above). + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: forwarded unchanged. + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static ALLOCATOR: Counting = Counting; + +/// Allocations `f` makes on this thread. +fn allocations(f: impl FnOnce()) -> u64 { + COUNT.with(|n| n.set(0)); + COUNTING.with(|on| on.set(true)); + f(); + COUNTING.with(|on| on.set(false)); + COUNT.with(Cell::get) +} + +#[test] +fn mixing_allocates_nothing_per_block() { + const BLOCK: usize = 960; + // The counter works. + assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1); + let mut mixer = StreamMixer::new(MixerConfig::default()); + let handle = mixer.handle(); + // 48 kHz stereo, 44.1 kHz mono, 6 channels, and one that stalls. + let stereo = handle.add_source("stereo"); + let mono = handle.add_source("mono"); + let surround = handle.add_source("5.1"); + let flaky = handle.add_source("flaky"); + let mut inputs = [stereo.input(48_000), mono.input(44_100), surround.input(48_000)]; + let mut flaky_input = flaky.input(48_000); + let stereo_block: Vec = (0..BLOCK * 2).map(|i| (i as f32 * 0.01).sin() * 0.3).collect(); + let mono_block: Vec = (0..882).map(|i| (i as f32 * 0.02).sin() * 0.3).collect(); + let six_block: Vec = (0..BLOCK * 6).map(|i| (i as f32 * 0.03).sin() * 0.3).collect(); + let mut out = vec![0.0f32; BLOCK * 2]; + // Slightly fast clock on one input so the drift correction runs. + let mut owed = 0.0f64; + let mut step = |block: usize, out: &mut Vec| { + inputs[0].push(&stereo_block, 2); + inputs[1].push(&mono_block, 1); + owed += BLOCK as f64 * 1.004; + let frames = owed as usize; + owed -= frames as f64; + inputs[2].push(&six_block[..frames.min(BLOCK) * 6], 6); + // On for a second, off for a second. + if (block / 50).is_multiple_of(2) { + flaky_input.push(&stereo_block, 2); + } + match block % 7 { + 0 => stereo.set_gain(0.5 + (block % 3) as f32 * 0.25), + 3 => mono.set_muted(block.is_multiple_of(2)), + 5 => handle.set_gain(0.9), + _ => {} + } + mixer.mix(out); + let _ = (stereo.level(), handle.level(), surround.state(), handle.limiter_gain()); + }; + // Warm up: sources adopted, inputs playing, latencies settled. + for block in 0..300 { + step(block, &mut out); + } + let count = allocations(|| { + for block in 300..1300 { + step(block, &mut out); + } + }); + assert_eq!(count, 0, "allocations in 1000 blocks"); + // The flaky source went idle and came back in the measured part. + assert!(flaky.stats().underruns > 0); + assert!(out.iter().any(|s| *s != 0.0)); +} diff --git a/crates/voelin-media/tests/pipewire_apps.rs b/crates/voelin-media/tests/pipewire_apps.rs new file mode 100644 index 0000000..da12d5a --- /dev/null +++ b/crates/voelin-media/tests/pipewire_apps.rs @@ -0,0 +1,427 @@ +//! Application audio capture against a private PipeWire and WirePlumber: +//! two child processes play tones (1000 Hz as `voelin-tone-a`, 1500 Hz as +//! `voelin-tone-b`) and this process plays 700 Hz, like our voice playback. +//! "Desktop audio without us" must hear both children and not us, a +//! capture of one application only that one, and a child started later +//! is picked up while capturing. +//! +//! Needs `pipewire`, `wireplumber` and `dbus-daemon` (Debian/Ubuntu: +//! `pipewire-bin wireplumber dbus-daemon`); skipped without them. The +//! daemons run in a temporary `XDG_RUNTIME_DIR` and never touch the +//! user's session. +#![cfg(all(target_os = "linux", feature = "pipewire"))] + +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use pipewire as pw; +use voelin_media::capture::pipewire_links::LinkManager; +use voelin_media::capture::playback::{AppMatch, PlaybackFilter, SourceCapture}; +use voelin_media::mix::{BlockClock, MixerConfig, StreamMixer}; + +/// Set in a child: play this frequency until killed. +const TONE_ENV: &str = "VOELIN_TEST_TONE"; +const OURS: f64 = 700.0; +const TONE_A: f64 = 1000.0; +const TONE_B: f64 = 1500.0; +const TONE_C: f64 = 2200.0; + +fn find(binary: &str) -> Option { + std::env::var_os("PATH")? + .to_str()? + .split(':') + .map(|dir| Path::new(dir).join(binary)) + .find(|p| p.is_file()) +} + +/// Play `freq` Hz (0.3, stereo, 48 kHz) as application `name` until `stop`. +fn play(remote: Option, freq: f64, name: String, stop: Arc) { + pw::init(); + let mainloop = pw::main_loop::MainLoopRc::new(None).unwrap(); + let context = pw::context::ContextRc::new(&mainloop, None).unwrap(); + let mut props = pw::properties::PropertiesBox::new(); + if let Some(remote) = remote { + props.insert(*pw::keys::REMOTE_NAME, remote); + } + props.insert(*pw::keys::APP_NAME, name.as_str()); + let core = context.connect_rc(Some(props)).unwrap(); + // End with the daemon. + let _errors = core + .add_listener_local() + .error({ + let mainloop = mainloop.downgrade(); + move |id, _, _, _| { + if id == pw::core::PW_ID_CORE + && let Some(mainloop) = mainloop.upgrade() + { + mainloop.quit(); + } + } + }) + .register(); + let mut props = pw::properties::PropertiesBox::new(); + props.insert(*pw::keys::MEDIA_TYPE, "Audio"); + props.insert(*pw::keys::MEDIA_CATEGORY, "Playback"); + props.insert(*pw::keys::MEDIA_ROLE, "Music"); + props.insert(*pw::keys::APP_NAME, name.as_str()); + props.insert(*pw::keys::NODE_NAME, name.as_str()); + let stream = pw::stream::StreamRc::new(core.clone(), &name, props).unwrap(); + let _listener = stream + .add_local_listener_with_user_data(0.0f64) + .process(move |stream, phase| { + let Some(mut buffer) = stream.dequeue_buffer() else { return }; + let data = &mut buffer.datas_mut()[0]; + let frames = match data.data() { + Some(bytes) => { + let frames = bytes.len() / 8; + for frame in bytes.chunks_exact_mut(8) { + *phase += std::f64::consts::TAU * freq / 48_000.0; + let s = (0.3 * phase.sin()) as f32; + frame[..4].copy_from_slice(&s.to_le_bytes()); + frame[4..].copy_from_slice(&s.to_le_bytes()); + } + frames + } + None => 0, + }; + let chunk = data.chunk_mut(); + *chunk.offset_mut() = 0; + *chunk.stride_mut() = 8; + *chunk.size_mut() = (frames * 8) as u32; + }) + .register() + .unwrap(); + let mut info = pw::spa::param::audio::AudioInfoRaw::new(); + info.set_format(pw::spa::param::audio::AudioFormat::F32LE); + info.set_rate(48_000); + info.set_channels(2); + let mut position = [0; pw::spa::param::audio::MAX_CHANNELS]; + position[0] = pw::spa::sys::SPA_AUDIO_CHANNEL_FL; + position[1] = pw::spa::sys::SPA_AUDIO_CHANNEL_FR; + info.set_position(position); + let format: Vec = pw::spa::pod::serialize::PodSerializer::serialize( + std::io::Cursor::new(Vec::new()), + &pw::spa::pod::Value::Object(pw::spa::pod::Object { + type_: pw::spa::sys::SPA_TYPE_OBJECT_Format, + id: pw::spa::sys::SPA_PARAM_EnumFormat, + properties: info.into(), + }), + ) + .unwrap() + .0 + .into_inner(); + stream + .connect( + pw::spa::utils::Direction::Output, + None, + pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS, + &mut [pw::spa::pod::Pod::from_bytes(&format).unwrap()], + ) + .unwrap(); + let timer = mainloop.loop_().add_timer({ + let mainloop = mainloop.downgrade(); + move |_| { + if stop.load(Ordering::Relaxed) + && let Some(mainloop) = mainloop.upgrade() + { + mainloop.quit(); + } + } + }); + timer + .update_timer(Some(Duration::from_millis(50)), Some(Duration::from_millis(50))) + .into_result() + .unwrap(); + mainloop.run(); +} + +/// The child side: `cargo test` runs this test in the child process, where +/// `VOELIN_TEST_TONE` says what to play. +#[test] +fn tone_child() { + let Ok(spec) = std::env::var(TONE_ENV) else { return }; + let (freq, name) = spec.split_once(':').unwrap(); + play(None, freq.parse().unwrap(), name.to_owned(), Arc::new(AtomicBool::new(false))); +} + +/// Processes killed on drop. +struct Daemons { + children: Vec, + dir: PathBuf, +} + +impl Drop for Daemons { + fn drop(&mut self) { + for child in self.children.iter_mut().rev() { + let _ = child.kill(); + let _ = child.wait(); + } + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +impl Daemons { + fn start() -> Option { + let (pipewire, wireplumber, dbus) = + (find("pipewire")?, find("wireplumber")?, find("dbus-daemon")?); + // Short: the socket path must fit in 108 bytes. + let dir = PathBuf::from(format!("/tmp/voelin-pw-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut daemons = Daemons { children: Vec::new(), dir: dir.clone() }; + let mut bus = Command::new(dbus) + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let mut address = String::new(); + BufReader::new(bus.stdout.take().unwrap()).read_line(&mut address).ok()?; + daemons.children.push(bus); + let env = |command: &mut Command| { + command + .env("XDG_RUNTIME_DIR", &dir) + .env("XDG_CONFIG_HOME", dir.join("config")) + .env("XDG_STATE_HOME", dir.join("state")) + .env("DBUS_SESSION_BUS_ADDRESS", address.trim()) + .env_remove("PIPEWIRE_REMOTE") + .stdout(Stdio::null()) + .stderr(Stdio::null()); + }; + // A sink, as every desktop has one (WirePlumber sets up the ports of + // playback streams once they have somewhere to go). + let conf = dir.join("config/pipewire/pipewire.conf.d"); + std::fs::create_dir_all(&conf).unwrap(); + std::fs::write( + conf.join("voelin-test-sink.conf"), + "context.objects = [ { factory = adapter args = { factory.name = support.null-audio-sink \ + node.name = voelin-test-sink media.class = Audio/Sink audio.position = [ FL FR ] } } ]\n", + ) + .unwrap(); + let mut command = Command::new(pipewire); + env(&mut command); + daemons.children.push(command.spawn().ok()?); + let socket = dir.join("pipewire-0"); + let deadline = Instant::now() + Duration::from_secs(5); + while !socket.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + let mut command = Command::new(wireplumber); + env(&mut command); + daemons.children.push(command.spawn().ok()?); + socket.exists().then_some(daemons) + } + + fn socket(&self) -> PathBuf { + self.dir.join("pipewire-0") + } + + /// Another process playing `freq` as `name`: this test binary, started + /// through a shell that exits right away, so the player is not our + /// descendant (our own process tree is excluded from desktop audio). + fn tone_player(&self, freq: f64, name: &str) -> Player { + let out = Command::new("sh") + .args(["-c", "\"$0\" --exact tone_child --test-threads=1 >/dev/null 2>&1 & echo $!"]) + .arg(std::env::current_exe().unwrap()) + .env(TONE_ENV, format!("{freq}:{name}")) + .env("XDG_RUNTIME_DIR", &self.dir) + .env_remove("PIPEWIRE_REMOTE") + .stderr(Stdio::null()) + .output() + .unwrap(); + let pid = String::from_utf8_lossy(&out.stdout).trim().parse().expect("player pid"); + Player { pid } + } +} + +/// A tone player process; killed on drop. +struct Player { + pid: u32, +} + +impl Player { + fn kill(&mut self) { + if self.pid != 0 { + let _ = Command::new("kill").arg(self.pid.to_string()).status(); + self.pid = 0; + } + } +} + +impl Drop for Player { + fn drop(&mut self) { + self.kill(); + } +} + +/// Print the graph (for a failing test), if the PipeWire tools are there. +fn dump(dir: &Path) { + for (tool, args) in [("pw-link", &["-l"][..]), ("pw-cli", &["ls"][..])] { + if let Some(tool) = find(tool) + && let Ok(out) = Command::new(tool).args(args).env("XDG_RUNTIME_DIR", dir).output() + { + eprintln!("{}", String::from_utf8_lossy(&out.stdout)); + } + } +} + +/// Goertzel magnitude of `freq` in the left channel (about amplitude / 2). +fn tone(samples: &[f32], freq: f64) -> f64 { + let k = 2.0 * (std::f64::consts::TAU * freq / 48_000.0).cos(); + let (mut s1, mut s2) = (0.0, 0.0); + let mut n = 0; + for frame in samples.chunks_exact(2) { + let s0 = f64::from(frame[0]) + k * s1 - s2; + s2 = s1; + s1 = s0; + n += 1; + } + (s1 * s1 + s2 * s2 - k * s1 * s2).max(0.0).sqrt() / f64::from(n.max(1)) +} + +/// A mixer with one capture, mixed in real time on a thread; keeps the last +/// second. +struct Listener { + stop: Arc, + last: Arc>>, + thread: Option>, + _capture: Box, +} + +impl Listener { + fn new(manager: &Arc, filter: PlaybackFilter) -> Self { + let mut mixer = StreamMixer::new(MixerConfig::default()); + let source = mixer.handle().add_source(format!("{filter:?}")); + let capture = manager.capture(&filter, &source).expect("capture"); + let stop = Arc::new(AtomicBool::new(false)); + let last = Arc::new(std::sync::Mutex::new(Vec::new())); + let thread = std::thread::spawn({ + let (stop, last) = (stop.clone(), last.clone()); + move || { + let mut clock = BlockClock::new(960); + let mut block = vec![0.0f32; 1920]; + while !stop.load(Ordering::Relaxed) { + for _ in clock.due(Instant::now()) { + mixer.mix(&mut block); + let mut last = last.lock().unwrap(); + last.extend_from_slice(&block); + let excess = last.len().saturating_sub(96_000); + last.drain(..excess); + } + std::thread::sleep(Duration::from_millis(5)); + } + } + }); + Self { stop, last, thread: Some(thread), _capture: capture } + } + + fn levels(&self, freqs: &[f64]) -> Vec { + let last = self.last.lock().unwrap(); + freqs.iter().map(|&f| tone(&last, f)).collect() + } + + /// Wait until `heard` are all above 0.05 and `silent` below 0.005. + fn expect(&self, heard: &[f64], silent: &[f64], what: &str) { + self.expect_in(heard, silent, what, None); + } + + fn expect_in(&self, heard: &[f64], silent: &[f64], what: &str, dir: Option<&Path>) { + let deadline = Instant::now() + Duration::from_secs(15); + loop { + let loud = self.levels(heard); + let quiet = self.levels(silent); + if loud.iter().all(|&l| l > 0.05) && quiet.iter().all(|&l| l < 0.005) { + return; + } + if Instant::now() >= deadline + && let Some(dir) = dir + { + dump(dir); + } + assert!( + Instant::now() < deadline, + "{what}: {heard:?} at {loud:?} (want > 0.05), {silent:?} at {quiet:?} (want < 0.005)" + ); + std::thread::sleep(Duration::from_millis(200)); + } + } +} + +impl Drop for Listener { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +#[test] +fn desktop_without_self_and_single_apps() { + if std::env::var_os(TONE_ENV).is_some() { + return; + } + let _ = tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .with_test_writer() + .try_init(); + let Some(daemons) = Daemons::start() else { + eprintln!("skipped: needs pipewire, wireplumber and dbus-daemon"); + return; + }; + let remote = daemons.socket().to_string_lossy().into_owned(); + // Our own playback, as the voice audio would be. + let stop_ours = Arc::new(AtomicBool::new(false)); + let ours = std::thread::spawn({ + let (remote, stop) = (remote.clone(), stop_ours.clone()); + move || play(Some(remote), OURS, "voelin-own-voices".into(), stop) + }); + let mut a = daemons.tone_player(TONE_A, "voelin-tone-a"); + let b = daemons.tone_player(TONE_B, "voelin-tone-b"); + + let manager = Arc::new(LinkManager::connect(Some(&daemons.socket())).expect("connect")); + let desktop = Listener::new(&manager, PlaybackFilter::AllButSelf); + let by_name = + Listener::new(&manager, PlaybackFilter::App(AppMatch::Name("VOELIN-TONE-A".into()))); + let by_pid = Listener::new(&manager, PlaybackFilter::App(AppMatch::Pid(b.pid))); + desktop.expect_in(&[TONE_A, TONE_B], &[OURS], "desktop without us", Some(&daemons.dir)); + by_name.expect(&[TONE_A], &[TONE_B, OURS], "app by name"); + by_pid.expect(&[TONE_B], &[TONE_A, OURS], "app by pid"); + + // The picker's list: both children with their pids, not us. + let mut apps = manager.apps(); + let list = apps.borrow_and_update().clone(); + let names: Vec<&str> = list.iter().map(|a| a.name.as_str()).collect(); + assert!(names.contains(&"voelin-tone-a") && names.contains(&"voelin-tone-b"), "{list:?}"); + assert!(!names.contains(&"voelin-own-voices"), "{list:?}"); + let entry = list.iter().find(|a| a.name == "voelin-tone-b").unwrap(); + assert_eq!(entry.pid, Some(b.pid)); + assert!(entry.streams >= 1); + + // A new application is picked up live; one that quits is dropped. + let c = daemons.tone_player(TONE_C, "voelin-tone-c"); + desktop.expect(&[TONE_A, TONE_B, TONE_C], &[OURS], "desktop after a new app"); + by_name.expect(&[TONE_A], &[TONE_C], "app by name after a new app"); + a.kill(); + desktop.expect(&[TONE_B, TONE_C], &[TONE_A, OURS], "desktop after an app quit"); + let deadline = Instant::now() + Duration::from_secs(10); + while apps.borrow_and_update().iter().any(|a| a.name == "voelin-tone-a") { + assert!(Instant::now() < deadline, "voelin-tone-a still listed"); + std::thread::sleep(Duration::from_millis(100)); + } + // Restarted, the application is matched by name again. + let a = daemons.tone_player(TONE_A, "voelin-tone-a"); + by_name.expect(&[TONE_A], &[TONE_B, TONE_C, OURS], "app by name after a restart"); + + drop((desktop, by_name, by_pid)); + drop((a, b, c)); + stop_ours.store(true, Ordering::Relaxed); + let _ = ours.join(); + drop(manager); + drop(daemons); +} diff --git a/crates/voelin-media/tests/x11_capture.rs b/crates/voelin-media/tests/x11_capture.rs index fd01de2..3ba9940 100644 --- a/crates/voelin-media/tests/x11_capture.rs +++ b/crates/voelin-media/tests/x11_capture.rs @@ -8,7 +8,7 @@ use std::time::Duration; -use voelin_media::capture::x11::X11Capture; +use voelin_media::capture::x11::{self, X11Capture}; use voelin_media::{ CaptureOptions, Codec, Codecs, EncoderConfig, FrameReceiver, ScreenCapture, SourceId, VideoFrame, convert, @@ -168,6 +168,23 @@ async fn x11_capture_end_to_end() { assert_eq!(window.id, SourceId::Window(scene.test_window.into())); assert_eq!((window.width, window.height), (u32::from(WW), u32::from(WH))); + // The window's process, for capturing its audio. + let window_id = u64::from(scene.test_window); + assert_eq!(x11::window_pid(Some(&display), window_id), None, "no _NET_WM_PID yet"); + let net_wm_pid = scene.conn.intern_atom(false, b"_NET_WM_PID").unwrap().reply().unwrap().atom; + scene + .conn + .change_property32( + PropMode::REPLACE, + scene.test_window, + net_wm_pid, + AtomEnum::CARDINAL, + &[std::process::id()], + ) + .unwrap(); + scene.conn.sync().unwrap(); + assert_eq!(x11::window_pid(Some(&display), window_id), Some(std::process::id())); + // Same pixels through MIT-SHM and through GetImage. check_monitor(&mut capture, &scene).await; let mut get_image = X11Capture::with_display(display.clone()).use_shm(false); diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index ffbc6cb..a2fd142 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -4,7 +4,8 @@ use slint::{ComponentHandle, Model}; use tracing::warn; -use voelin_core::settings::{STREAM_BITRATE_KBPS, STREAM_FPS}; +use voelin_core::media::audio_source_specs; +use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS}; use voelin_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState}; use voelin_core::{Command, Event, StreamState, WatchState}; @@ -397,10 +398,13 @@ impl App { audio: form.audio, auto_accept: form.auto_accept, }; + // No sources configured: no audio. + let audio_sources = audio_source_specs(&self.prefs.get(&STREAM_AUDIO_SOURCES)); let request = CaptureRequest { fps, bitrate_kbps: bitrate, - audio: form.audio, + audio: form.audio && !audio_sources.is_empty(), + audio_sources, restore_token: self.settings.portal_restore_token.clone(), }; self.settings.share = defaults; diff --git a/crates/voelin-ui/src/video.rs b/crates/voelin-ui/src/video.rs index 35632e1..2c85683 100644 --- a/crates/voelin-ui/src/video.rs +++ b/crates/voelin-ui/src/video.rs @@ -13,7 +13,8 @@ use tracing::warn; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert}; use voelin_core::media::{ - self, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, stream_codec, + self, AudioSourceSpec, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, + stream_codec, }; use voelin_core::stream::PeerConfig; use voelin_core::{Engine, StreamSink}; @@ -230,6 +231,7 @@ impl Video { bitrate_kbps: options.bitrate_kbps, codec, audio: options.audio, + audio_sources: options.audio_sources, restore_token: options.restore_token, ..StreamerConfig::default() }; @@ -300,6 +302,8 @@ pub(crate) struct CaptureRequest { pub fps: u32, pub bitrate_kbps: u32, pub audio: bool, + /// Mixed into the stream's audio (`stream.audio_sources`). + pub audio_sources: Vec, pub restore_token: Option, } @@ -324,7 +328,7 @@ impl Capture { } pub fn audio_error(&self) -> Option { - self.streamer.audio_error().map(str::to_owned) + self.streamer.audio_error() } /// The portal's token for this choice, to keep. diff --git a/docs/media.md b/docs/media.md index 683a4a6..3445db8 100644 --- a/docs/media.md +++ b/docs/media.md @@ -1,7 +1,8 @@ # Media: frames, codecs and capture (`voelin-media`) -`crates/voelin-media` turns screens and system audio into frames, encodes and -decodes video, and converts pixels for rendering. It does no networking: +`crates/voelin-media` turns screens and what applications play into frames, +mixes the stream's audio, encodes and decodes video, and converts pixels for +rendering. It does no networking: `voelin-stream` carries the encoded frames (`Peer::write(MediaKind::Video, MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received `MediaFrame`s go to `VideoDecoder::decode`. @@ -30,6 +31,8 @@ MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received | `FrameReceiver` | bounded queue that drops the oldest item; `recv().await`, `try_recv()`, `recv_timeout()` | | `capture::default_screen_capture()`, `default_audio_capture()` | the backend for this session | | `capture::synthetic::{SyntheticScreen, SineSource}` | test pattern (moving rectangle, frame counter) and sine tone | +| `mix::{StreamMixer, MixerHandle, SourceHandle, SourceInput, BlockClock}` | the stream's audio mixer: any number of sources, each with gain, mute, level meters and any number of inputs (see [Stream audio](#stream-audio)) | +| `capture::playback::{start_playback, audio_apps, window_pid}` | what applications play, captured into a mixer source (`PlaybackFilter::AllButSelf` or `App(AppMatch::Name / Pid)`); the applications that play, updated live (`AudioApps`) | ```rust let codecs = Codecs::new().with_openh264(OpenH264::find_in(&data_dir)?); // H.264 optional @@ -58,7 +61,7 @@ streamer: capture thread ── FrameSink: pace, convert + scale (Pyramid on all ├─ encoder thread, layer 0 ─┐ ├─ encoder thread, layer 1 ─┤ └─ ... ├─ MediaSink: StreamSink / EncodedSource - AudioCapture ─ 20 ms stereo Opus (128 kbit/s) ─┘ + audio sources ─ StreamMixer (thread, every 20 ms) ─ stereo Opus (128 kbit/s) ─┘ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder ─ picture callback ─ Latest stream audio ─ session audio thread (mixer, own volume) ─ speakers ``` @@ -66,10 +69,11 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder - `Streamer::start(&codecs, StreamerConfig)` starts capturing right away (the portal asks the user then), so a cancelled dialog never starts a stream; frames are converted and encoded only after `attach(sink)`, i.e. once the - stream is live. Audio follows the capture clock across gaps. With the test - pattern (`SourceId::Synthetic`, `synthetic_pattern`) the audio is a quiet - sine tone. The portal's restore token is available afterwards - (`restore_token()`) to store. + stream is live. The audio is mixed from `StreamerConfig::audio_sources` + (see [Stream audio](#stream-audio)); without any, it is desktop audio + without Voelin, or a quiet sine tone with the test pattern + (`SourceId::Synthetic`, `synthetic_pattern`). The portal's restore token + is available afterwards (`restore_token()`) to store. - Threads: the capture backend calls the streamer's `FrameSink` on its own thread with the frame still in its capture buffer. Frames over the frame-rate cap (`StreamerConfig::fps`, any value >= 1) are skipped before @@ -90,7 +94,7 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder `max_bitrate`), else its configured bitrate; libvpx changes it in place without a keyframe. - `Streamer::reconfigure(&codecs, StreamerConfigUpdate { fps, bitrate_kbps, - codec, layers })` applies from the next frame without restarting the + codec, layers, audio_sources })` applies from the next frame without restarting the capture: encoders are created first (an error changes nothing), layers keep their encoder when their id stays, new ids get threads, removed ones stop, a new codec swaps every encoder (first frame a keyframe), and the @@ -99,7 +103,9 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder - `stats()`: `StreamerStats` with capture fps, convert time and threads, dropped frames, codec, and per layer (`LayerStats`) size, frames, keyframes, dropped, fps, kbit/s, encode time, target bitrate, threads - and encoder speed. Counters are atomics; rates are computed once a + and encoder speed; the audio mix's level and limiter gain, and per audio + source (`AudioSourceStats`) level, state, latency, underruns and why it + captures nothing, if so. Counters are atomics; rates are computed once a second, and a one-line summary is logged every 5 s at debug level (`RUST_LOG=voelin_core::media=debug`). - `CaptureBackend`: `Auto` (the session default: portal on Wayland, X11, @@ -122,6 +128,70 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder jitter buffer and mixer under a made-up client id, with its own volume. Playback is mono like the rest of the audio path. +## Stream audio + +The audio of our stream is a mix of any number of sources +(`StreamerConfig::audio_sources`: `AudioSourceSpec { kind, gain, muted }`): + +| `AudioSourceKind` | Captures | +|---|---| +| `DesktopWithoutSelf` (default) | everything that plays except Voelin: viewers do not hear the voices or streams we play | +| `App(AppMatch::Name(..))` | one application by name, ignoring case: application name or executable (`.exe` optional), the package on Android; found again when it restarts | +| `App(AppMatch::Pid(..))` | one process and its children (Linux, Windows) | +| `WindowAudio` | the application of the shared window: X11 `_NET_WM_PID`, the owner of a Windows `HWND`. The ScreenCast portal does not say whose window it shares; on Wayland, pick the application | +| `Microphone` | our microphone as the voice connection sends it (after echo cancellation, noise suppression and gain control), through `voelin_audio::tap::microphone()`, while a voice connection runs | +| `Synthetic { hz }` | a quiet sine tone (tests, and the default with the test pattern) | + +- Mixer (`voelin_media::mix::StreamMixer`): each source has inputs, + lock-free single-producer rings that capture threads fill at their own + pace, rate and channel count. Each input is held at a small latency + (40 ms by default, more for an input that delivers in bursts or keeps + arriving late). An input that runs dry fades out and buffers again + while the others go on. Clock drift is absorbed by resampling up to + 0.5 % while a buffer is off target. The sum passes a master gain and a + soft limiter, so it never exceeds full scale. Levels (peak and RMS) of + every source and of the output are atomics. Nothing is allocated per + block (`tests/mix_alloc.rs`; `benches/mix.rs` measures it). +- The streamer's audio thread mixes one 20 ms block whenever + `BlockClock` says it is due (monotonic clock, exact, no drift) and + encodes it with Opus in music mode. The block's number is its RTP time, + so the audio follows real time across silences and stalls; after a + stall of more than 25 blocks it jumps ahead instead of sending a burst. + It also mixes before a sink is attached, so the inputs keep draining. +- `StreamerConfigUpdate::audio_sources` changes the sources live. + Sources whose kind stays keep their capture and take the new gain and + mute; `Some(vec![])` leaves a silent track. A source that cannot + capture (an application that is not running, no PipeWire, a window + whose process is unknown) does not fail the stream: its + `AudioSourceStats::error` and `Streamer::audio_error()` say why. + `Streamer::audio_mixer()` hands out the `MixerHandle` for meters. +- The settings key `stream.audio_sources` stores the sources as JSON, e.g. + `[{"kind": "desktop"}, {"kind": "app", "name": "firefox", "gain": 0.5}, + {"kind": "microphone", "muted": true}]`. Other kinds are `"window"` and + `"synthetic"` (`frequency`), and an app can be given by `"pid"`. The + default is desktop audio; `[]` shares without sound. The desktop app + reads it when sharing starts (`media::audio_source_specs`). + `media::audio_apps()` lists the applications for a picker. + +What applications play is captured by `capture::playback::start_playback`: + +| Platform | All but ours | One application | Application list | +|---|---|---|---| +| Linux (PipeWire) | `pipewire_links::LinkManager`: a capture stream of ours that the session manager leaves unlinked (`node.autoconnect = false`) gets links from the output ports of every other playback stream (`Stream/Output/Audio`); PipeWire sums them. Links follow streams as they come and go | links from that application's streams only | playback streams in the registry, one entry per application, live | +| Windows | WASAPI process loopback excluding our process tree (before Windows 10 2004: plain loopback of the default device, which includes our playback) | process loopback including the process tree; by name, one capture per matching process, matched again every 2 s | processes with audio sessions on any playback device, polled every 2 s | +| Android | `AudioPlaybackCapture` excluding our uid | matching the package's uid | launchable apps (Android cannot tell which play) | + +On Linux, our own streams are recognised by the process id of the node, of +its client, or of the client's socket (`pipewire.sec.pid`, compared with our +own connection's, which also works in a sandbox), walked up the `/proc` +parent chain. The playing sides of loopbacks and filters (`node.link-group`) +are skipped: what they replay is captured at its source. This needs no +session-manager policy and no extra sink, and leaves the user's routing and +volumes alone. On Android, a capture needs the running screen capture and +the microphone permission, and apps can opt out +(`allowAudioPlaybackCapture`, or usages other than media, game and unknown, +e.g. calls). + ## Codecs Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with @@ -205,14 +275,14 @@ found at ..."). ## Capture -| Platform | Screen | System audio | +| Platform | Screen | System audio (`AudioCapture`; streams use [Stream audio](#stream-audio)) | |---|---|---| | any | `SyntheticScreen` | `SineSource` | | Linux X11 (`x11`, default) | `X11Capture`: MIT-SHM 1.2 (memfd passed to the server) or GetImage; RandR 1.5 monitors; windows from `_NET_CLIENT_LIST` (root children without a WM); XFixes cursor blended in | | | Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream (LINEAR DMA-BUF or shared memory) | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) | | Linux wlroots (`wlroots`, default) | `WlrootsCapture`: `ext-image-copy-capture-v1`, else `wlr-screencopy-unstable-v1`, outputs only, shared memory | | | Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback | -| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture`, 48 kHz float) | +| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture` of every app but ours, 48 kHz float) | `default_screen_capture()` picks a registered external provider first (`capture::external::set_screen_provider`, which the Android app calls at @@ -251,12 +321,11 @@ Notes: - X11 reads through the shared-memory segment in place (cursor blended into it); the monitor or window geometry is looked up once a second rather than per frame. x11rb still allocates a small reply buffer per request. -- PipeWire system audio captures everything the default sink plays, including - our own playback (TeamSpeak voices): PipeWire has no "all but this process" - monitor. Excluding our nodes needs a private null sink with links from every - other application's output (via the registry); TODO. Until then, play voices - on another sink or accept that viewers hear them. Without a PipeWire daemon, - `start` returns `Error::CaptureUnavailable`. +- `PipeWireAudioCapture` (the plain `AudioCapture`) captures everything the + default sink plays, including our own playback. Streams do not use it: their + desktop audio links every other application's playback into a capture + stream of ours ([Stream audio](#stream-audio)). Without a PipeWire daemon, + both return `Error::CaptureUnavailable`. - Windows process loopback needs Windows 10 2004 or later. ## Performance and benchmarks @@ -369,6 +438,12 @@ run on Windows yet. | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | | Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `voelin-core` `stream::tests::test_pattern_through_stream_tasks` | tested | | Stream audio (RTP time → jitter buffer ids, volume, end) | `voelin-core` `audio::tests::stream_audio_with_volume`, stream task test | tested | +| Stream mixer (latency, fade on underrun, drift correction, rate conversion, limiter, levels, live source changes), `BlockClock` | `voelin-media` `mix::tests`, `tests/mix_alloc.rs` (no allocation per block) | tested | +| Application audio on PipeWire: desktop without our own stream, by name, by pid, a new player linked live, a quit one dropped, a restarted one matched again, the app list | `voelin-media/tests/pipewire_apps.rs` (private PipeWire, WirePlumber and D-Bus; tones told apart by frequency) | tested with PipeWire 1.0 and WirePlumber 0.4; skipped without them | +| Streamer audio sources (mix levels, gain, mute, live change, microphone tap, window source error, silence) | `voelin-core` `media::tests::audio_sources_change_live`, `audio_sources_from_settings`, `settings::tests::audio_sources` | tested | +| X11 `_NET_WM_PID` of the shared window | `tests/x11_capture.rs` under Xvfb | tested | +| WASAPI per-process loopback, audio sessions, `HWND` owner | – | type-checked for `x86_64-pc-windows-gnu` only | +| Android per-app and all-but-ours playback capture | `cargo ndk -t arm64-v8a clippy`, `gradlew compileDebugKotlin` | compiles only (no device or emulator here) | | The same through the TeamSpeak 6 server | `voelin-core/tests/media_live.rs` (`VOELIN_LIVE=1`), `voelinctl stream start --synthetic` / `watch --expect-frames` | tested against 6.0.0-beta13.1 | | X11 monitor capture → VP8 → server → decoder | `voelinctl stream start --source x11` under Xvfb | tested manually (debug build: about 8 fps at 1400×900) | | Desktop app watching and sharing | Xvfb, `VOELIN_AUTOWATCH` / `VOELIN_AUTOSHARE` against voelinctl, screenshots | tested manually | diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 6ecac7e..bf65c55 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -211,7 +211,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { let streamer = Streamer::start(&codecs, config).await.context("capture")?; println!("capturing with {} ({codec})", streamer.backend()); if let Some(e) = streamer.audio_error() { - println!("no system audio: {e}"); + println!("audio: {e}"); } let audio = streamer.has_audio(); (Source::Encoded(EncodedSource::new(streamer)), audio)