Merge the stream audio mixer into the engine gaps branch

settings.rs: both sides added built-in keys; the list keeps the stream
audio sources and adds the cache, file transfer and privacy keys (20).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-29 01:00:34 +00:00
commit 60a5ff7a68
30 files changed
+5350 -208

No files matched your search

+95
View File
@@ -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<bool> {
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<Vec<(String, String)>> {
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::<JString>(value)?;
value.try_to_string(env)
})?;
Ok(parse_apps(&lines))
}
/// `label<TAB>package` 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<Option<String>> {
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<jboolean> {
thread_local! {
// One per capture thread, reused for every call.
static BUFFER: std::cell::RefCell<Vec<f32>> = 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(),
+92 -1
View File
@@ -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<oneshot::Sender<Result<()>>>,
audio: Option<FrameSender<AudioBuffer>>,
/// Mixer inputs of [`AudioProvider::start_input`] captures, by id.
inputs: HashMap<u64, SourceInput>,
/// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC`
/// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync.
origin_ns: Option<i64>,
@@ -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<u64> {
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<AudioApp> {
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).
+3
View File
@@ -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;
+217
View File
@@ -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<Vec<(u64, Box<dyn TapSink>)>>,
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<Instant> = 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<dyn TapSink>) -> 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<Mutex<Vec<f32>>>);
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]);
}
}
+51
View File
@@ -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<String, StreamAudio>,
stream_volumes: HashMap<String, f32>,
/// 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<f32>,
@@ -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<Mutex<Vec<f32>>>);
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);
+548 -100
View File
@@ -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<AudioSourceSpec> {
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<AudioSourceSpec> {
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<AudioApps, MediaError> {
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<String>,
}
/// 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<AudioSourceSpec>,
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<Vec<LayerSpec>>,
/// 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<Vec<AudioSourceSpec>>,
}
/// 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<Codec>,
pub layers: Vec<LayerStats>,
/// 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<AudioSourceStats>,
}
/// 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<Shared>,
screen: Option<Box<dyn ScreenCapture>>,
audio: Option<Box<dyn AudioCapture>>,
/// The video source (for [`AudioSourceKind::WindowAudio`]).
source: SourceId,
// Boxed: a `Streamer` is held inline by previews.
audio: Mutex<Option<Box<StreamAudio>>>,
threads: Vec<JoinHandle<()>>,
/// Encoder threads, by layer.
encoders: Mutex<Vec<(LayerId, JoinHandle<()>)>>,
backend: &'static str,
restore_token: Option<String>,
/// Why the audio did not start at all.
audio_error: Option<String>,
}
@@ -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<String> {
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<MixerHandle> {
lock(&self.audio).as_ref().map(|a| a.mixer.clone())
}
/// The audio sources now.
pub fn audio_sources(&self) -> Vec<AudioSourceSpec> {
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<Box<dyn ScreenCapture>, Me
})
}
type AudioStart = (Box<dyn AudioCapture>, FrameReceiver<AudioBuffer>, 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<ActiveSource>,
thread: Option<JoinHandle<()>>,
}
fn start_audio(source: &SourceId) -> Result<AudioStart, MediaError> {
let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?;
encoder.set_bitrate(OPUS_BITRATE)?;
let mut capture: Box<dyn AudioCapture> = 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<Feed>,
error: Option<String>,
}
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<dyn SourceCapture>),
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<Shared>,
video: &SourceId,
sources: Vec<AudioSourceSpec>,
) -> Result<Self, MediaError> {
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<AudioSourceSpec>) {
let mut old: Vec<Option<ActiveSource>> = 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<Feed, String> {
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<String> {
let errors: Vec<String> = 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<AudioSourceStats> {
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<f32>) {
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<AudioBuffer>, mut encoder: VoiceEncoder) {
// Interleaved stereo waiting for a whole Opus frame.
let mut pending: Vec<f32> = 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<Arc<[u8]>> = 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<AudioSourceKind> = 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<S> = 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<f32> = (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")]
+136 -1
View File
@@ -1141,8 +1141,91 @@ pub static PRIVACY_BLOCK_MODE: Key<BlockMode> = Key::new(
BlockMode::default,
);
/// 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<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pid: Option<u32>,
},
/// 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<Vec<_>>` is `fn(&Vec<_>)`
fn valid_audio_sources(sources: &Vec<AudioSourceSetting>) -> 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<Vec<AudioSourceSetting>> = 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; 19] {
pub fn builtin_keys() -> [&'static dyn Setting; 20] {
[
&CRASH_REPORTS,
&AUDIO,
@@ -1159,6 +1242,7 @@ pub fn builtin_keys() -> [&'static dyn Setting; 19] {
&CHAT_HISTORY_PAGE,
&CHAT_DEDUPE_TOLERANCE_MS,
&CHAT_RETENTION_DAYS,
&STREAM_AUDIO_SOURCES,
&CACHE_MAX_MB,
&CACHE_FETCH_IMAGES,
&FILES_PROGRESS_MS,
@@ -1281,6 +1365,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();
+5 -1
View File
@@ -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 {
+10
View File
@@ -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
+83
View File
@@ -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>`: n stereo sources at 48 kHz (copied through)
//! - `mix/44k1/<n>`: 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<SourceInput>,
/// 20 ms of input at the sources' rate.
block: Vec<f32>,
out: Vec<f32>,
}
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);
+61 -3
View File
@@ -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<AudioBuffer>) -> 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<u64> {
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<AudioApp> {
Vec::new()
}
}
/// A capture of [`AudioProvider::start_input`]; stops it when dropped.
struct ProviderCapture {
provider: Arc<dyn AudioProvider>,
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<dyn AudioProvider>,
filter: &PlaybackFilter,
source: &SourceHandle,
) -> Result<Box<dyn SourceCapture>> {
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<T> = Mutex<Option<Arc<T>>>;
@@ -174,7 +233,6 @@ mod tests {
use std::time::Duration;
use super::*;
use crate::Error;
/// Sends one frame per start, or refuses.
#[derive(Default)]
+3
View File
@@ -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;
@@ -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/<pid>/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<String>) -> Error {
Error::CaptureUnavailable { backend: BACKEND, reason: reason.into() }
}
fn lock<T>(m: &Mutex<T>) -> 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<std::result::Result<(), String>>,
},
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<pw::channel::Sender<Command>>,
apps: watch::Receiver<Vec<AudioApp>>,
alive: Arc<AtomicBool>,
next_id: AtomicU64,
thread: Option<JoinHandle<()>>,
}
static SHARED: Mutex<Option<Weak<LinkManager>>> = 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<Arc<Self>> {
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<Self> {
let (commands, rx) = pw::channel::channel::<Command>();
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<Vec<AudioApp>> {
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<Self>,
filter: &PlaybackFilter,
source: &SourceHandle,
) -> Result<Box<dyn SourceCapture>> {
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<LinkManager>,
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<String>,
rx: pw::channel::Receiver<Command>,
apps: watch::Sender<Vec<AudioApp>>,
alive: Arc<AtomicBool>,
init: std_mpsc::Sender<std::result::Result<(), String>>,
) {
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<n>` 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::<u32>().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<u32> {
props.get(key).and_then(|v| v.trim().parse().ok()).filter(|&p| p > 0)
}
fn text(props: &DictRef, key: &str) -> Option<String> {
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<u32>,
pid: Option<u32>,
binary: Option<String>,
name: Option<String>,
/// Its details arrived (or never will).
known: bool,
_proxy: Option<(pw::client::ClientListener, pw::client::Client)>,
}
struct Node {
node_name: String,
client: Option<u32>,
app_name: Option<String>,
pid: Option<u32>,
binary: Option<String>,
icon: Option<String>,
media: Option<String>,
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<String>,
}
/// One capture stream.
struct Capture {
id: u64,
filter: PlaybackFilter,
node_name: String,
/// Its node, once in the registry.
node: Option<u32>,
_listener: pw::stream::StreamListener<CaptureData>,
_stream: pw::stream::StreamRc,
}
/// What a capture stream's callbacks own.
struct CaptureData {
input: SourceInput,
channels: u16,
scratch: Vec<f32>,
}
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<u32>,
marker: String,
own_binary: Option<String>,
clients: HashMap<u32, Client>,
nodes: HashMap<u32, Node>,
ports: HashMap<u32, Port>,
captures: Vec<Capture>,
/// 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<HashMap<u32, Vec<u32>>>,
apps: watch::Sender<Vec<AudioApp>>,
weak: RcWeak<RefCell<Model>>,
}
impl Model {
fn new(
core: pw::core::CoreRc,
registry: pw::registry::RegistryRc,
apps: watch::Sender<Vec<AudioApp>>,
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<RefCell<Model>>, 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::<pw::client::Client, _>(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::<pw::node::Node, _>(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<u32> {
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<u32> {
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::<pw::link::Link>("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<AudioApp> = 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}");
}
}
+315
View File
@@ -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<Item = &'a str>) -> 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<u32>,
/// Executable (Linux, Windows) or package name (Android): what
/// [`AppMatch::Name`] matches besides `name`.
pub binary: Option<String>,
/// Icon name (freedesktop icon theme) or icon path, if the application
/// gave one.
pub icon: Option<String>,
/// What it plays, if it says (e.g. a track or tab title).
pub media: Option<String>,
/// 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<Box<dyn SourceCapture>> {
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<Vec<AudioApp>>,
_keep: Box<dyn Send + Sync>,
}
impl AudioApps {
pub fn new(rx: watch::Receiver<Vec<AudioApp>>, keep: Box<dyn Send + Sync>) -> Self {
Self { rx, _keep: keep }
}
/// The list now (marks it seen).
pub fn current(&mut self) -> Vec<AudioApp> {
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<Vec<AudioApp>> {
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<Vec<AudioApp>> {
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<AudioApps> {
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<u32> {
#[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/<pid>/stat`.
#[cfg(target_os = "linux")]
pub fn parent_pid(pid: u32) -> Option<u32> {
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<Worker>,
capture: Box<dyn AudioCapture>,
}
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<dyn AudioCapture>,
source: &SourceHandle,
) -> Result<Box<dyn SourceCapture>> {
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);
}
}
+306 -56
View File
@@ -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<FrameReceiver<AudioBuffer>> {
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<wasapi::AudioClient, String> {
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<Worker> {
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<wasapi::AudioClient, String> {
let format = wasapi::WaveFormat::new(
32,
32,
@@ -265,15 +301,23 @@ fn open_client() -> std::result::Result<wasapi::AudioClient, String> {
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<wasapi::AudioClient, String> {
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<AudioBuffer>,
stop: &std::sync::atomic::AtomicBool,
mode: Loopback,
stop: &AtomicBool,
init: &std::sync::mpsc::Sender<std::result::Result<(), String>>,
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<f32> = 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<u8> = 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<Worker> {
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<Box<dyn SourceCapture>> {
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<u32> = 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<String> {
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<Vec<AudioApp>, 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<AudioApp> = 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<AudioApps> {
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<u32> {
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()
}
+15
View File
@@ -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<u32> {
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,
+4
View File
@@ -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;
File diff suppressed because it is too large. Load diff
+122
View File
@@ -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<bool> = const { Cell::new(false) };
static COUNT: Cell<u64> = 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<f32> = (0..BLOCK * 2).map(|i| (i as f32 * 0.01).sin() * 0.3).collect();
let mono_block: Vec<f32> = (0..882).map(|i| (i as f32 * 0.02).sin() * 0.3).collect();
let six_block: Vec<f32> = (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<f32>| {
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));
}
+427
View File
@@ -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<PathBuf> {
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<String>, freq: f64, name: String, stop: Arc<AtomicBool>) {
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<u8> = 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<Child>,
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<Self> {
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<AtomicBool>,
last: Arc<std::sync::Mutex<Vec<f32>>>,
thread: Option<JoinHandle<()>>,
_capture: Box<dyn SourceCapture>,
}
impl Listener {
fn new(manager: &Arc<LinkManager>, 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<f64> {
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);
}
+18 -1
View File
@@ -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);
+6 -2
View File
@@ -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;
+6 -2
View File
@@ -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<AudioSourceSpec>,
pub restore_token: Option<String>,
}
@@ -324,7 +328,7 @@ impl Capture {
}
pub fn audio_error(&self) -> Option<String> {
self.streamer.audio_error().map(str::to_owned)
self.streamer.audio_error()
}
/// The portal's token for this choice, to keep.