diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml
index a2ff826af..f614336ad 100644
--- a/mobile/android/app/src/main/AndroidManifest.xml
+++ b/mobile/android/app/src/main/AndroidManifest.xml
@@ -5,6 +5,7 @@
+
@@ -14,7 +15,7 @@
-
+
diff --git a/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java b/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java
index 8c0a3140a..c115671b8 100644
--- a/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java
+++ b/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java
@@ -15,8 +15,8 @@ public final class AppRuntimeService extends Service {
NativeRuntime runtime;
CompletableFuture startup;
Throwable failure;
- final java.util.ArrayDeque captureRequests = new java.util.ArrayDeque<>();
- int projections;
+ final java.util.ArrayDeque captureRequests = new java.util.ArrayDeque<>();
+ int projections, microphones;
@Override
public void onCreate() {
@@ -48,7 +48,8 @@ public final class AppRuntimeService extends Service {
3,
notification(),
(Build.VERSION.SDK_INT >= 34 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE : 0)
- | (projections > 0 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION : 0));
+ | (projections > 0 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION : 0)
+ | (microphones > 0 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE : 0));
}
void refreshNotification() {
diff --git a/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java b/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java
index d23384ee7..45057cf93 100644
--- a/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java
+++ b/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java
@@ -12,7 +12,7 @@ import android.util.DisplayMetrics;
import android.view.*;
/** OS permission and callback facts for one Rust-owned Capture. No codec or media queue. */
-public final class CapturePlatform implements AutoCloseable {
+public final class CapturePlatform implements CaptureRequest {
private final Context context;
private final SurfaceTexture texture = new SurfaceTexture(false);
private final Surface surface = new Surface(texture);
@@ -49,11 +49,11 @@ public final class CapturePlatform implements AutoCloseable {
}
public SurfaceTexture texture() { return texture; }
public synchronized boolean isClosed() { return closed; }
- synchronized boolean needsAudioPermission() {
+ public synchronized boolean needsAudioPermission() {
return audioRequested && !audioDenied && context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED;
}
- synchronized void audioPermission(boolean granted) { audioDenied = !granted; notifyAll(); }
- synchronized void presented(MainActivity activity) { permissionActivity = new java.lang.ref.WeakReference<>(activity); }
+ public synchronized void audioPermission(boolean granted) { audioDenied = !granted; notifyAll(); }
+ public synchronized void presented(MainActivity activity) { permissionActivity = new java.lang.ref.WeakReference<>(activity); }
void grant(int result, Intent data) {
synchronized (this) { permissionActivity = null; }
if (result != Activity.RESULT_OK || data == null) { close(); return; }
diff --git a/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java b/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java
index 868389fa8..30d7b0743 100644
--- a/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java
+++ b/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java
@@ -6,13 +6,23 @@ import android.net.Uri;
import android.os.*;
import android.widget.*;
+// Both requests use the existing visible-App permission queue; each retains
+// its own capture resource and cancellation lifetime.
+interface CaptureRequest extends AutoCloseable {
+ boolean isClosed();
+ boolean needsAudioPermission();
+ void audioPermission(boolean granted);
+ void presented(MainActivity activity);
+ void close();
+}
+
public final class MainActivity extends Activity {
static MainActivity current;
boolean visible, notificationRequest;
static final int NOTIFICATIONS = 13;
static final int PROJECTION = 14, SOURCE_AUDIO = 15;
private static final class PendingCapture {
- CapturePlatform capture;
+ CaptureRequest capture;
boolean projectionRequest, audioRequest;
}
private PendingCapture pending;
@@ -140,7 +150,7 @@ public final class MainActivity extends Activity {
pending.capture = service.captureRequests.poll();
if (pending.capture != null) pending.capture.presented(this);
}
- CapturePlatform capture = pending.capture;
+ CaptureRequest capture = pending.capture;
if (capture == null) return;
if (capture.isClosed()) { captureClosed(capture); return; }
if (pending.projectionRequest || pending.audioRequest) return;
@@ -149,10 +159,16 @@ public final class MainActivity extends Activity {
requestPermissions(new String[] {android.Manifest.permission.RECORD_AUDIO}, SOURCE_AUDIO);
return;
}
+ if (capture instanceof MicrophonePlatform microphone) {
+ pending.capture = null;
+ microphone.grant();
+ finish();
+ return;
+ }
pending.projectionRequest = true;
startActivityForResult(getSystemService(android.media.projection.MediaProjectionManager.class).createScreenCaptureIntent(), PROJECTION);
}
- void captureClosed(CapturePlatform owner) {
+ void captureClosed(CaptureRequest owner) {
if (pending == null || pending.capture != owner) return;
if (pending.projectionRequest) finishActivity(PROJECTION);
pending.capture = null;
@@ -162,7 +178,7 @@ public final class MainActivity extends Activity {
super.onActivityResult(request, result, data);
if (request != PROJECTION || pending == null || !pending.projectionRequest) return;
pending.projectionRequest = false;
- CapturePlatform owner = pending.capture;
+ CapturePlatform owner = (CapturePlatform) pending.capture;
pending.capture = null;
if (owner != null) {
AppRuntimeService service = AppRuntimeService.instance;
diff --git a/mobile/android/app/src/main/java/tv/piik/android/MicrophonePlatform.java b/mobile/android/app/src/main/java/tv/piik/android/MicrophonePlatform.java
new file mode 100644
index 000000000..a5da4afec
--- /dev/null
+++ b/mobile/android/app/src/main/java/tv/piik/android/MicrophonePlatform.java
@@ -0,0 +1,118 @@
+package tv.piik.android;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.media.*;
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+/** One Rust audio worker owns this recorder, independently of MediaProjection. */
+public final class MicrophonePlatform implements CaptureRequest {
+ private final Context context;
+ private final String deviceId;
+ private boolean requested, approved, denied, closed, foreground;
+ private String error;
+ private AudioRecord record;
+ private AppRuntimeService service;
+ private java.lang.ref.WeakReference permissionActivity;
+
+ public MicrophonePlatform(Context context, String deviceId) {
+ this.context = context.getApplicationContext();
+ this.deviceId = deviceId;
+ }
+ public String devices() throws Exception {
+ JSONArray result = new JSONArray();
+ for (AudioDeviceInfo device : context.getSystemService(AudioManager.class).getDevices(AudioManager.GET_DEVICES_INPUTS)) {
+ result.put(new JSONObject().put("id", Integer.toString(device.getId()))
+ .put("label", device.getProductName().toString()));
+ }
+ return result.toString();
+ }
+ public synchronized boolean isClosed() { return closed; }
+ public synchronized boolean needsAudioPermission() {
+ return !denied && context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED;
+ }
+ public synchronized void audioPermission(boolean granted) { denied = !granted; notifyAll(); }
+ public synchronized void presented(MainActivity activity) { permissionActivity = new java.lang.ref.WeakReference<>(activity); }
+
+ // Only the existing visible media entry calls this, before it returns to Browser.
+ synchronized void grant() {
+ permissionActivity = null;
+ if (closed) return;
+ try {
+ if (denied || needsAudioPermission()) throw new IllegalStateException("microphone_authorization_cancelled");
+ if (service == null || AppRuntimeService.instance != service) throw new IllegalStateException("App runtime stopped");
+ service.microphones++;
+ foreground = true;
+ service.foreground();
+ approved = true;
+ } catch (RuntimeException failure) {
+ error = failure.toString();
+ close();
+ }
+ notifyAll();
+ }
+ public synchronized AudioRecord audio() throws InterruptedException {
+ if (!requested && !closed) {
+ requested = true;
+ AppRuntimeService.main.post(() -> {
+ synchronized (this) {
+ if (closed) return;
+ service = AppRuntimeService.instance;
+ if (service == null) { error = "App runtime stopped"; close(); return; }
+ service.captureRequests.add(this);
+ service.notifyActivity();
+ }
+ });
+ }
+ while (!closed && !approved) wait();
+ if (error != null) throw new IllegalStateException(error);
+ if (closed) throw new IllegalStateException("microphone stopped");
+ if (record != null) throw new IllegalStateException("microphone already opened");
+ AudioDeviceInfo selected = null;
+ for (AudioDeviceInfo device : context.getSystemService(AudioManager.class).getDevices(AudioManager.GET_DEVICES_INPUTS)) {
+ if (Integer.toString(device.getId()).equals(deviceId)) selected = device;
+ }
+ if (!deviceId.isEmpty() && selected == null) throw new IllegalArgumentException("The selected microphone is unavailable");
+ AudioFormat format = new AudioFormat.Builder().setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
+ .setSampleRate(48000).setChannelMask(AudioFormat.CHANNEL_IN_MONO).build();
+ int minimum = AudioRecord.getMinBufferSize(48000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_FLOAT);
+ record = new AudioRecord.Builder().setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
+ .setAudioFormat(format).setBufferSizeInBytes(Math.max(minimum, 960 * 4 * 2)).build();
+ if (selected != null && !record.setPreferredDevice(selected)) throw new IllegalStateException("The selected microphone cannot be used");
+ record.startRecording();
+ if (record.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) throw new IllegalStateException("The microphone did not start");
+ AudioDeviceInfo routed = record.getRoutedDevice();
+ if (selected != null && (routed == null || routed.getId() != selected.getId())) throw new IllegalStateException("The selected microphone is not routed");
+ return record;
+ }
+ public void stopAudio() { close(); }
+ public synchronized void releaseAudio() {
+ try { close(); }
+ finally {
+ AudioRecord released = record;
+ record = null;
+ if (released != null) released.release();
+ }
+ }
+ @Override public synchronized void close() {
+ if (closed) return;
+ closed = true;
+ notifyAll();
+ try {
+ if (record != null && record.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) record.stop();
+ } finally { AppRuntimeService.main.post(() -> {
+ if (service != null) {
+ service.captureRequests.remove(this);
+ if (foreground) {
+ service.microphones--; foreground = false;
+ if (AppRuntimeService.instance == service) service.foreground();
+ }
+ service = null;
+ }
+ MainActivity activity = permissionActivity == null ? null : permissionActivity.get();
+ permissionActivity = null;
+ if (activity != null) activity.captureClosed(this);
+ }); }
+ }
+}
diff --git a/prototype/channel-native/Cargo.toml b/prototype/channel-native/Cargo.toml
index 6aa8dc612..f513d6a44 100644
--- a/prototype/channel-native/Cargo.toml
+++ b/prototype/channel-native/Cargo.toml
@@ -59,7 +59,7 @@ rustls-platform-verifier = "=0.7.1"
rustix = { version = "1", features = ["fs"] }
[target.'cfg(target_os = "macos")'.dependencies]
-cidre = { version = "=0.29.0", optional = true, default-features = false, features = ["sc", "vt", "iio", "async", "io_surface", "macos_13_0"] }
+cidre = { version = "=0.29.0", optional = true, default-features = false, features = ["sc", "vt", "iio", "async", "io_surface", "av", "core_audio", "macos_13_0"] }
libc = "0.2"
objc2-core-foundation = { version = "=0.3.2", default-features = false, features = ["std", "CFArray", "CFDictionary", "CFNumber", "CFString", "CFCGTypes"] }
objc2-core-graphics = { version = "=0.3.2", default-features = false, features = ["std", "CGEvent", "CGEventTypes", "CGEventSource", "CGRemoteOperation", "CGDisplayConfiguration", "CGDirectDisplay", "CGWindow", "CGGeometry", "libc"] }
diff --git a/prototype/channel-native/src/capture/android/audio.rs b/prototype/channel-native/src/capture/android/audio.rs
index 4636683f1..c7a4e9a10 100644
--- a/prototype/channel-native/src/capture/android/audio.rs
+++ b/prototype/channel-native/src/capture/android/audio.rs
@@ -74,6 +74,9 @@ impl AudioCapture {
thread: Some(thread),
})
}
+ pub fn microphone(device_id: String) -> Result {
+ Self::start(Platform::microphone(device_id)?, Clock::new()?)
+ }
pub fn control(&self) -> AudioControl {
self.control.clone()
}
@@ -124,6 +127,15 @@ fn run(
&[],
)?
.l()?;
+ let channels = env
+ .call_method(
+ &record,
+ jni_str!("getChannelCount"),
+ jni_sig!(() -> int),
+ &[],
+ )?
+ .i()? as usize;
+ ensure!(matches!(channels, 1 | 2), "expected mono or stereo PCM");
let timestamp = env.new_object(
jni_str!("android/media/AudioTimestamp"),
jni_sig!(() -> void),
@@ -132,7 +144,7 @@ fn run(
if let Some(ready) = ready.take() {
let _ = ready.send(Ok(()));
}
- let mut samples = vec![0.0f32; 960 * 2];
+ let mut samples = vec![0.0f32; 960 * channels];
let mut filled = 0usize;
let mut position = 0i64;
while !control.is_stopped() {
@@ -161,11 +173,11 @@ fn run(
break;
}
ensure!(
- count > 0 && count % 8 == 0,
+ count > 0 && count as usize % (channels * 4) == 0,
"AudioRecord read failed: {count}"
);
filled += count as usize / 4;
- position += i64::from(count) / 8;
+ position += i64::from(count) / (channels * 4) as i64;
if filled < samples.len() {
continue;
}
@@ -187,7 +199,14 @@ fn run(
let first = nanos + (position - 960 - capture_position) * 1_000_000_000 / 48_000;
// Source timestamps advance even when the existing bounded PCM queue is full.
let _ = frames.try_send(AudioFrame {
- samples: samples.clone(),
+ samples: if channels == 1 {
+ samples
+ .iter()
+ .flat_map(|sample| [*sample, *sample])
+ .collect()
+ } else {
+ samples.clone()
+ },
presentation_time: clock.project(first),
});
}
diff --git a/prototype/channel-native/src/capture/android/mod.rs b/prototype/channel-native/src/capture/android/mod.rs
index bab646d07..e33e5d46d 100644
--- a/prototype/channel-native/src/capture/android/mod.rs
+++ b/prototype/channel-native/src/capture/android/mod.rs
@@ -6,10 +6,11 @@ mod graphics;
mod platform;
mod source;
-use crate::capture::{AudioCapabilities, Target, TargetKind};
+use crate::capture::{AudioCapabilities, MicrophoneDevice, Target, TargetKind};
use anyhow::Result;
pub use audio::{AudioCapture, AudioControl};
pub use encoding::{Encoding, EncodingControl};
+use jni::{jni_sig, jni_str, objects::JString};
pub use source::{Capture, Control};
pub fn targets() -> Result> {
@@ -31,3 +32,20 @@ pub fn audio_capabilities() -> AudioCapabilities {
pub(super) fn activation_url() -> Result {
platform::activation_url()
}
+
+pub fn microphones() -> Result> {
+ platform::Platform::microphone(String::new())?.with(|env, object| {
+ let list = env
+ .call_method(
+ object,
+ jni_str!("devices"),
+ jni_sig!(() -> java.lang.String),
+ &[],
+ )?
+ .l()?;
+ let list = JString::cast_local(env, list)?
+ .mutf8_chars(env)?
+ .to_string();
+ Ok(serde_json::from_str(&list)?)
+ })
+}
diff --git a/prototype/channel-native/src/capture/android/platform.rs b/prototype/channel-native/src/capture/android/platform.rs
index 99f9be37e..63f1b53ed 100644
--- a/prototype/channel-native/src/capture/android/platform.rs
+++ b/prototype/channel-native/src/capture/android/platform.rs
@@ -38,6 +38,12 @@ pub(super) struct Platform {
}
impl Platform {
pub fn new(audio: bool) -> Result {
+ Self::create(audio, None)
+ }
+ pub fn microphone(device_id: String) -> Result {
+ Self::create(false, Some(device_id))
+ }
+ fn create(audio: bool, microphone: Option) -> Result {
let context = ndk_context::android_context();
// Application global reference and VM are installed before app::serve starts.
let vm = Arc::new(unsafe { JavaVM::from_raw(context.vm().cast()) });
@@ -52,7 +58,14 @@ impl Platform {
&[],
)?
.l()?;
- let name = JString::from_str(env, "tv.piik.android.CapturePlatform")?;
+ let name = JString::from_str(
+ env,
+ if microphone.is_some() {
+ "tv.piik.android.MicrophonePlatform"
+ } else {
+ "tv.piik.android.CapturePlatform"
+ },
+ )?;
let class = env
.call_method(
&loader,
@@ -62,11 +75,20 @@ impl Platform {
)?
.l()?;
let class = jni::objects::JClass::cast_local(env, class)?;
- let instance = env.new_object(
- class,
- jni_sig!((android.content.Context, boolean) -> void),
- &[(&*app).into(), audio.into()],
- )?;
+ let instance = if let Some(device_id) = microphone {
+ let device = JString::from_str(env, device_id)?;
+ env.new_object(
+ class,
+ jni_sig!((android.content.Context, java.lang.String) -> void),
+ &[(&*app).into(), (&device).into()],
+ )?
+ } else {
+ env.new_object(
+ class,
+ jni_sig!((android.content.Context, boolean) -> void),
+ &[(&*app).into(), audio.into()],
+ )?
+ };
Ok(env.new_global_ref(instance)?)
})?;
Ok(Self {
diff --git a/prototype/channel-native/src/capture/audio.rs b/prototype/channel-native/src/capture/audio.rs
index ecb7f98ab..979693fd5 100644
--- a/prototype/channel-native/src/capture/audio.rs
+++ b/prototype/channel-native/src/capture/audio.rs
@@ -1,5 +1,5 @@
//! Event-driven WASAPI loopback. This worker owns PCM only, not its video's lifetime.
-use super::{AudioCapabilities, AudioFrame, CaptureClock, Target, TargetKind};
+use super::{AudioCapabilities, AudioFrame, CaptureClock, MicrophoneDevice, Target, TargetKind};
use anyhow::{anyhow, ensure, Context as _, Result};
use std::{
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
@@ -42,7 +42,48 @@ pub struct AudioCapture {
completion: Option>>,
thread: Option>,
}
+enum Input {
+ System(Target, bool),
+ Microphone(String),
+}
impl AudioCapture {
+ #[cfg(test)]
+ pub(crate) fn fixture(
+ ready_now: bool,
+ ) -> Result<(Self, mpsc::Sender, oneshot::Receiver<()>)> {
+ let event = unsafe { CreateEventW(None, true, false, None)? };
+ let control = AudioControl(Arc::new(unsafe { OwnedHandle::from_raw_handle(event.0) }));
+ let worker = control.clone();
+ let (frames, receiver) = mpsc::channel(2);
+ let (ready, started) = oneshot::channel();
+ let (complete, completion) = oneshot::channel();
+ let (joined, finished) = oneshot::channel();
+ let thread = thread::spawn(move || {
+ let mut ready = Some(ready);
+ if ready_now {
+ let _ = ready.take().unwrap().send(Ok(()));
+ }
+ unsafe {
+ WaitForSingleObject(worker.handle(), INFINITE);
+ }
+ if let Some(ready) = ready {
+ let _ = ready.send(Err(anyhow!("candidate cancelled")));
+ }
+ let _ = complete.send(Ok(()));
+ let _ = joined.send(());
+ });
+ Ok((
+ Self {
+ control,
+ ready: Some(started),
+ frames: receiver,
+ completion: Some(completion),
+ thread: Some(thread),
+ },
+ frames,
+ finished,
+ ))
+ }
pub fn start(target: Target) -> Result {
Self::start_with_exclusion(target, None)
}
@@ -56,6 +97,12 @@ impl AudioCapture {
);
let include_tree = exclude.is_none();
let target = exclude.unwrap_or(target);
+ Self::spawn(Input::System(target, include_tree))
+ }
+ pub fn microphone(device_id: String) -> Result {
+ Self::spawn(Input::Microphone(device_id))
+ }
+ fn spawn(input: Input) -> Result {
let event = unsafe { CreateEventW(None, true, false, None)? };
let control = AudioControl(Arc::new(unsafe { OwnedHandle::from_raw_handle(event.0) }));
let worker = control.clone();
@@ -67,7 +114,7 @@ impl AudioCapture {
.name("piik-audio".into())
.spawn(move || {
let mut ready = Some(ready);
- let result = run(target, include_tree, &worker, frames, &mut ready);
+ let result = run(input, &worker, frames, &mut ready);
if let Some(ready) = ready {
let error = result
.as_ref()
@@ -146,7 +193,7 @@ impl Drop for Com {
}
fn client(process: Option<(u32, bool)>) -> Result {
- let mut client = match process {
+ let client = match process {
Some((pid, include_tree)) => {
AudioClient::new_application_loopback_client(pid, include_tree)?
}
@@ -154,6 +201,10 @@ fn client(process: Option<(u32, bool)>) -> Result {
.get_default_device(&Direction::Render)?
.get_iaudioclient()?,
};
+ initialize(client)
+}
+
+fn initialize(mut client: AudioClient) -> Result {
client.initialize_client(
&WaveFormat::new(32, 32, &SampleType::Float, 48_000, 2, None),
&Direction::Capture,
@@ -165,6 +216,21 @@ fn client(process: Option<(u32, bool)>) -> Result {
Ok(client)
}
+pub fn microphones() -> Result> {
+ let _com = Com::start()?;
+ DeviceEnumerator::new()?
+ .get_device_collection(&Direction::Capture)?
+ .into_iter()
+ .map(|device| {
+ let device = device?;
+ Ok(MicrophoneDevice {
+ id: device.get_id()?,
+ label: device.get_friendlyname()?,
+ })
+ })
+ .collect()
+}
+
/// Probe the actual APIs without starting a stream or reading any audio.
/// The caller should run this blocking refresh away from its signaling actor.
pub fn audio_capabilities() -> AudioCapabilities {
@@ -228,15 +294,28 @@ fn process(target: &Target) -> Result