voelin-android: playback captures into mixer inputs (Rust side)

PlaybackAudio implements AudioProvider::start_input / stop_input / apps:
each capture gets an id, its SourceInput is kept in the capture state,
and the Kotlin side is asked (Bridge.startAudioInput) to capture
everything but our uid or the uid of one app's package, delivering to
Native.onAudioInput(id, ...), which pushes into that input from a reused
per-thread buffer. An app picked by name is looked up among the
launchable apps (label or package) and falls back to the name as a
package. Picking by process fails on Android. apps() lists the
launchable apps (Bridge.launchableApps, "label<TAB>package" lines),
because Android cannot tell which apps play.

The Kotlin counterpart follows in the next commit.

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-28 19:20:19 +00:00
1 parent 06c0dcc851
commit cc3afd3dbc
2 files changed
+187 -1

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).