diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index 8b5d065..f7d442d 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -111,6 +111,71 @@ pub fn stop_system_audio() -> Result<()> { }) } +/// Capture playback into mixer input `id` (delivered to +/// `Native.onAudioInput`): of the app `package`, or everything but ours. +/// `false` without a running screen capture, or for a package that is not +/// installed (or not visible to us). +pub fn start_audio_input(id: u64, package: Option<&str>) -> Result { + with_bridge(|env, class| { + let package = match package { + Some(package) => JObject::from(env.new_string(package)?), + None => JObject::null(), + }; + env.call_static_method( + class, + jni_str!("startAudioInput"), + jni_sig!((id: jlong, package: java.lang.String) -> jboolean), + &[JValue::Long(id as jlong), JValue::Object(&package)], + )? + .z() + }) +} + +pub fn stop_audio_input(id: u64) -> Result<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("stopAudioInput"), + jni_sig!((id: jlong) -> void), + &[JValue::Long(id as jlong)], + )?; + Ok(()) + }) +} + +/// Launchable apps other than ours, as `(label, package)`, sorted by label. +pub fn launchable_apps() -> Result> { + let lines = with_bridge(|env, class| { + let value = env + .call_static_method( + class, + jni_str!("launchableApps"), + jni_sig!(() -> java.lang.String), + &[], + )? + .l()?; + if value.is_null() { + return Ok(String::new()); + } + let value = env.cast_local::(value)?; + value.try_to_string(env) + })?; + Ok(parse_apps(&lines)) +} + +/// `labelpackage` lines. +fn parse_apps(lines: &str) -> Vec<(String, String)> { + lines + .lines() + .filter_map(|line| { + let (label, package) = line.split_once('\t')?; + let package = package.trim(); + let label = if label.trim().is_empty() { package } else { label.trim() }; + (!package.is_empty()).then(|| (label.to_owned(), package.to_owned())) + }) + .collect() +} + pub fn secret_get(key: &str) -> Result> { with_bridge(|env, class| { let key = JObject::from(env.new_string(key)?); @@ -250,6 +315,36 @@ fn on_system_audio<'local>( Ok(crate::capture::on_audio(buffer, channels.clamp(1, 8) as u16, timestamp_ns)) } +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_audio_input(id: jlong, samples: jfloat[], count: jint, channels: jint) -> jboolean, +}; + +/// Interleaved 48 kHz float samples for mixer input `id` (see +/// [`start_audio_input`]). Returns `false` once the input is gone. +fn on_audio_input<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + samples: JFloatArray<'local>, + count: jint, + channels: jint, +) -> Result { + thread_local! { + // One per capture thread, reused for every call. + static BUFFER: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let id = id as u64; + if !crate::capture::wants_input(id) { + return Ok(false); + } + BUFFER.with_borrow_mut(|buffer| { + buffer.resize(count.max(0) as usize, 0.0); + samples.get_region(env, 0, buffer)?; + Ok(crate::capture::on_input(id, buffer, channels.clamp(1, 8) as u16)) + }) +} + const _: jni::NativeMethod = native_method! { java_type = "io.github.faumaray.voelin.Native", static extern fn on_disconnect_voice(), diff --git a/crates/voelin-android/src/capture.rs b/crates/voelin-android/src/capture.rs index 9a2a298..a52d8d7 100644 --- a/crates/voelin-android/src/capture.rs +++ b/crates/voelin-android/src/capture.rs @@ -5,15 +5,21 @@ //! asks the Kotlin side for the user's consent; on consent it runs //! `ScreenCaptureService` (a `mediaProjection` foreground service) whose //! `ImageReader` hands RGBA frames to [`on_frame`]. System audio -//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection. +//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection: +//! everything but our own uid, or one app's uid, each into a stream mixer +//! input ([`on_input`]); several captures may run at once. +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use tokio::sync::oneshot; use tracing::warn; use voelin_media::capture::external::{self, AudioProvider, ScreenProvider}; +use voelin_media::capture::playback::{AppMatch, AudioApp, PlaybackFilter}; use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use voelin_media::mix::SourceInput; use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; use crate::bridge; @@ -29,6 +35,8 @@ struct State { /// Answer for the pending `start`. pending: Option>>, audio: Option>, + /// Mixer inputs of [`AudioProvider::start_input`] captures, by id. + inputs: HashMap, /// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC` /// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync. origin_ns: Option, @@ -135,6 +143,89 @@ impl AudioProvider for PlaybackAudio { warn!("stopping system audio: {e}"); } } + + /// Everything but our uid, or the uid of one app's package. + fn start_input(&self, filter: &PlaybackFilter, input: SourceInput) -> Result { + let package = match filter { + PlaybackFilter::AllButSelf => None, + PlaybackFilter::App(app @ AppMatch::Name(name)) => Some( + self.apps() + .into_iter() + .find(|a| { + app.matches_name([a.name.as_str(), a.binary.as_deref().unwrap_or("")]) + }) + .and_then(|a| a.binary) + // Not launchable (a service, say): maybe the package itself. + .unwrap_or_else(|| name.trim().to_owned()), + ), + PlaybackFilter::App(AppMatch::Pid(_)) => { + return Err(Error::CaptureUnavailable { + backend: AUDIO, + reason: "Android captures apps by package, not by process".into(), + }); + } + }; + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + with_state(|s| s.inputs.insert(id, input)); + let started = bridge::start_audio_input(id, package.as_deref()); + if let Ok(true) = started { + return Ok(id); + } + with_state(|s| s.inputs.remove(&id)); + let reason = match (started, package) { + (Err(e), _) => e.to_string(), + (_, Some(package)) => format!( + "cannot capture {package}: not installed, or no running screen capture (and \ + the microphone permission)" + ), + (_, None) => "needs a running screen capture (and the microphone permission)".into(), + }; + Err(Error::CaptureUnavailable { backend: AUDIO, reason }) + } + + fn stop_input(&self, id: u64) { + with_state(|s| s.inputs.remove(&id)); + if let Err(e) = bridge::stop_audio_input(id) { + warn!("stopping audio capture {id}: {e}"); + } + } + + /// Android cannot tell which apps play: the launchable ones. + fn apps(&self) -> Vec { + match bridge::launchable_apps() { + Ok(apps) => apps + .into_iter() + .map(|(name, package)| AudioApp { + name, + binary: Some(package), + ..AudioApp::default() + }) + .collect(), + Err(e) => { + warn!("listing apps: {e}"); + Vec::new() + } + } + } +} + +pub fn wants_input(id: u64) -> bool { + with_state(|s| s.inputs.get(&id).is_some_and(|i| !i.is_closed())) +} + +/// Captured playback for mixer input `id`. Returns `false` once the input +/// is gone (the capture then stops). +pub fn on_input(id: u64, samples: &[f32], channels: u16) -> bool { + with_state(|s| { + let Some(input) = s.inputs.get_mut(&id) else { return false }; + input.push(samples, channels); + if input.is_closed() { + s.inputs.remove(&id); + return false; + } + true + }) } /// The user answered the consent dialog (or the service failed to start).