From 677a3e7cb9d5a887fdb5fbd8d4817b9d7aa7b7f2 Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:55:21 -0400 Subject: [PATCH] feat(channel): mix independent Native commentary inputs --- .../android/app/src/main/AndroidManifest.xml | 3 +- .../tv/piik/android/AppRuntimeService.java | 7 +- .../java/tv/piik/android/CapturePlatform.java | 8 +- .../java/tv/piik/android/MainActivity.java | 24 +- .../tv/piik/android/MicrophonePlatform.java | 118 ++++ prototype/channel-native/Cargo.toml | 2 +- .../src/capture/android/audio.rs | 27 +- .../channel-native/src/capture/android/mod.rs | 20 +- .../src/capture/android/platform.rs | 34 +- prototype/channel-native/src/capture/audio.rs | 93 ++- .../channel-native/src/capture/linux/audio.rs | 52 +- .../channel-native/src/capture/linux/mod.rs | 2 +- .../channel-native/src/capture/macos/audio.rs | 22 +- .../src/capture/macos/audio/microphone.rs | 223 ++++++ .../channel-native/src/capture/macos/mod.rs | 2 +- prototype/channel-native/src/capture/mod.rs | 25 +- prototype/channel-native/src/media/local.rs | 467 +++--------- .../channel-native/src/media/local/audio.rs | 666 ++++++++++++++++++ prototype/channel-native/src/peer.rs | 143 ++-- .../channel-native/src/peer/bandwidth.rs | 4 +- prototype/channel-server/src/app.rs | 110 ++- src/client/channel/app-link.ts | 46 +- 22 files changed, 1601 insertions(+), 497 deletions(-) create mode 100644 mobile/android/app/src/main/java/tv/piik/android/MicrophonePlatform.java create mode 100644 prototype/channel-native/src/capture/macos/audio/microphone.rs create mode 100644 prototype/channel-native/src/media/local/audio.rs 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> { } fn run( - target: Target, - include_tree: bool, + input: Input, control: &AudioControl, frames: mpsc::Sender, ready: &mut Option>>, ) -> Result<()> { let _com = Com::start()?; - let process = process(&target)?; - let client = client(process.as_ref().map(|_| (target.pid, include_tree)))?; + let (process, client) = match input { + Input::System(target, include_tree) => { + let process = process(&target)?; + let client = client(process.as_ref().map(|_| (target.pid, include_tree)))?; + (process, client) + } + Input::Microphone(id) => { + let devices = DeviceEnumerator::new()?; + let device = if id.is_empty() { + devices.get_default_device(&Direction::Capture)? + } else { + devices.get_device(&id)? + }; + (None, initialize(device.get_iaudioclient()?)?) + } + }; let event = client.set_get_eventhandle()?; // wasapi 0.26's slice reader dereferences the buffer even when SILENT is set. // GetBuffer's flags and timestamp belong to the original buffer, so handle it here. diff --git a/prototype/channel-native/src/capture/linux/audio.rs b/prototype/channel-native/src/capture/linux/audio.rs index 1f8ea0ab2..6f618b834 100644 --- a/prototype/channel-native/src/capture/linux/audio.rs +++ b/prototype/channel-native/src/capture/linux/audio.rs @@ -1,6 +1,6 @@ //! System-output sound, independent of Portal selection and video failure. use super::{message_error, Clock, Pipeline}; -use crate::capture::{AudioCapabilities, AudioFrame, Target}; +use crate::capture::{AudioCapabilities, AudioFrame, MicrophoneDevice, Target}; use anyhow::{anyhow, ensure, Context as _, Result}; use futures_util::StreamExt; use gst::prelude::*; @@ -18,6 +18,39 @@ pub fn audio_capabilities() -> AudioCapabilities { } } +pub fn microphones() -> Result> { + gst::init()?; + let monitor = gst::DeviceMonitor::new(); + monitor + .add_filter( + Some("Audio/Source"), + Some(&gst::Caps::builder("audio/x-raw").build()), + ) + .context("audio device provider unavailable")?; + monitor.start()?; + let devices = monitor + .devices() + .iter() + .filter_map(|device| { + // The provider configures the element's public device property with + // the source name which pulsesrc itself accepts. No stream is started. + let source = device.create_element(None).ok()?; + if source.factory()?.name() != "pulsesrc" { + return None; + } + let id = source + .property::>("device") + .filter(|id| !id.is_empty())?; + Some(MicrophoneDevice { + id, + label: device.display_name().to_string(), + }) + }) + .collect(); + monitor.stop(); + Ok(devices) +} + #[derive(Clone)] pub struct AudioControl(watch::Sender); impl AudioControl { @@ -41,6 +74,12 @@ pub struct AudioCapture { } impl AudioCapture { pub fn start(_target: Target) -> Result { + Self::start_device(Some("@DEFAULT_MONITOR@".into())) + } + pub fn microphone(device_id: String) -> Result { + Self::start_device((!device_id.is_empty()).then_some(device_id)) + } + fn start_device(device_id: Option) -> Result { gst::init()?; let runtime = tokio::runtime::Handle::try_current()?; let control = AudioControl(watch::channel(false).0); @@ -52,7 +91,7 @@ impl AudioCapture { .name("piik-linux-audio".into()) .spawn(move || { let mut ready = Some(ready); - let result = runtime.block_on(run(&worker, frames, &mut ready)); + let result = runtime.block_on(run(device_id, &worker, frames, &mut ready)); if let Some(ready) = ready { let error = result .as_ref() @@ -216,6 +255,7 @@ mod tests { } async fn run( + device_id: Option, control: &AudioControl, frames: mpsc::Sender, ready: &mut Option>>, @@ -223,9 +263,11 @@ async fn run( let pipeline = Pipeline(gst::Pipeline::new()); let clock = Clock::new(); clock.pipeline(&pipeline.0); - let source = gst::ElementFactory::make("pulsesrc") - .property("device", "@DEFAULT_MONITOR@") - .build()?; + let mut source = gst::ElementFactory::make("pulsesrc"); + if let Some(device_id) = device_id { + source = source.property("device", device_id); + } + let source = source.build()?; let convert = gst::ElementFactory::make("audioconvert").build()?; let resample = gst::ElementFactory::make("audioresample").build()?; let caps = gst::Caps::builder("audio/x-raw") diff --git a/prototype/channel-native/src/capture/linux/mod.rs b/prototype/channel-native/src/capture/linux/mod.rs index 9702618c4..21bd8f782 100644 --- a/prototype/channel-native/src/capture/linux/mod.rs +++ b/prototype/channel-native/src/capture/linux/mod.rs @@ -6,7 +6,7 @@ mod frames; mod portal; mod source; -pub use audio::{audio_capabilities, AudioCapture, AudioControl}; +pub use audio::{audio_capabilities, microphones, AudioCapture, AudioControl}; pub use encoding::{Encoding, EncodingControl}; pub use frames::{Clock, Frames, RawFrame}; pub use source::{targets, Capture, Control}; diff --git a/prototype/channel-native/src/capture/macos/audio.rs b/prototype/channel-native/src/capture/macos/audio.rs index 7eb989046..c42d25beb 100644 --- a/prototype/channel-native/src/capture/macos/audio.rs +++ b/prototype/channel-native/src/capture/macos/audio.rs @@ -11,6 +11,9 @@ use std::{ }; use tokio::sync::{mpsc, oneshot, Notify}; +mod microphone; +pub use microphone::microphones; + pub fn audio_capabilities() -> AudioCapabilities { AudioCapabilities { process_audio: true, @@ -68,8 +71,18 @@ pub struct AudioCapture { completion: Option>>, thread: Option>, } +enum Input { + System(Target), + Microphone(String), +} impl AudioCapture { pub fn start(target: Target) -> Result { + Self::spawn(Input::System(target)) + } + pub fn microphone(device_id: String) -> Result { + Self::spawn(Input::Microphone(device_id)) + } + fn spawn(input: Input) -> Result { let runtime = tokio::runtime::Handle::try_current()?; let control = AudioControl(Arc::new(Shared::default())); let worker = control.clone(); @@ -82,7 +95,14 @@ impl AudioCapture { let mut ready = Some(ready); let mut result = Ok(()); objc::ar_pool(|| { - result = runtime.block_on(run(target, &worker, frames, &mut ready)); + result = runtime.block_on(async { + match input { + Input::System(target) => run(target, &worker, frames, &mut ready).await, + Input::Microphone(device) => { + microphone::run(device, &worker, frames, &mut ready).await + } + } + }); }); if let Some(ready) = ready { let error = result diff --git a/prototype/channel-native/src/capture/macos/audio/microphone.rs b/prototype/channel-native/src/capture/macos/audio/microphone.rs new file mode 100644 index 000000000..58b1ce011 --- /dev/null +++ b/prototype/channel-native/src/capture/macos/audio/microphone.rs @@ -0,0 +1,223 @@ +//! AVAudioEngine owns the selected input and AVAudioConverter owns resampling. +use super::{checked, AudioControl, AudioFrame, Clock, Pcm}; +use crate::capture::MicrophoneDevice; +use anyhow::{anyhow, ensure, Context as _, Result}; +use cidre::{arc, at, av, cf, cm, core_audio, define_obj_type, ns, objc}; +use std::time::Duration; +use tokio::sync::{mpsc, oneshot}; + +pub fn microphones() -> Result> { + checked(core_audio::System::devices())? + .into_iter() + .filter_map(|device| { + let inputs = device.input_stream_cfg().ok()?; + if !inputs + .buffers() + .iter() + .any(|input| input.number_channels > 0) + { + return None; + } + Some((|| { + Ok(MicrophoneDevice { + id: checked(device.uid())?.to_string(), + label: checked(device.name())?.to_string(), + }) + })()) + }) + .collect() +} + +// cidre exposes AUAudioUnit but not this public macOS input-device setter. +define_obj_type!(InputUnit(at::au::AudioUnit)); +impl InputUnit { + #[objc::msg_send(setDeviceID:error:)] + unsafe fn set_device<'a>(&mut self, id: u32, error: *mut Option<&'a ns::Error>) -> bool; +} +unsafe extern "C" { + static AVAudioEngineConfigurationChangeNotification: &'static ns::NotificationName; +} + +pub(super) async fn run( + device_id: String, + control: &AudioControl, + frames: mpsc::Sender, + ready: &mut Option>>, +) -> Result<()> { + let permitted = tokio::select! { + _ = control.stopped() => return Ok(()), + permitted = av::CaptureDevice::request_access_for_media_type(av::MediaType::audio()) => checked(permitted)?, + }; + ensure!(permitted, "microphone_authorization_cancelled"); + let device = if device_id.is_empty() { + checked(core_audio::System::default_input_device())? + } else { + checked(core_audio::Device::with_uid(&cf::String::from_str( + &device_id, + )))? + }; + ensure!(!device.is_unknown(), "selected microphone unavailable"); + let mut engine = av::AudioEngine::new(); + let mut input = engine.input_node(); + let mut unit = input.audio_unit(); + // InputUnit adds only a selector to this same retained AUAudioUnit object. + let unit = unsafe { &mut *(unit.as_mut() as *mut at::au::AudioUnit as *mut InputUnit) }; + checked(ns::if_false(|error| unsafe { + unit.set_device(device.0 .0, error) + }))?; + let format = input.output_format_for_bus(0); + ensure!( + format.sample_rate() > 0.0 && format.channel_count() > 0, + "microphone has no input format" + ); + let output = av::AudioFormat::standard_with_sample_rate_and_channels(48_000.0, 2) + .context("microphone output format")?; + let converter = + av::AudioConverter::with_formats(&format, &output).context("microphone converter")?; + let mut converted = Converted { + converter, + input: format.clone(), + output, + pcm: Pcm::default(), + clock: Clock::new(), + next_sample: None, + expected_sample: None, + frames, + }; + let callback = control.clone(); + checked( + input.install_tap_on_bus(0, 960, Some(&format), move |buffer, time| { + if callback.is_stopped() { + return; + } + if let Err(error) = converted.receive(buffer, time) { + callback.0.finish(Some(format!("{error:#}"))); + } + }), + )?; + let mut notifications = ns::NotificationCenter::default(); + let changed = control.clone(); + let observer = notifications.add_observer_guard( + unsafe { AVAudioEngineConfigurationChangeNotification }, + Some(engine.as_ref()), + None, + move |_| { + changed + .0 + .finish(Some("microphone hardware configuration changed".into())) + }, + ); + let result = async { + if control.is_stopped() { + return Ok(()); + } + checked(engine.start())?; + if let Some(ready) = ready.take() { + let _ = ready.send(Ok(())); + } + control.stopped().await; + Ok::<_, anyhow::Error>(()) + } + .await; + // The notification only signals this owner; never tear down inside Apple's callback. + drop(observer); + engine.stop(); + let removed = checked(input.remove_tap_on_bus(0)); + result?; + if let Some(error) = &control.0.state.lock().unwrap().error { + return Err(anyhow!(error.clone())); + } + removed +} + +struct Converted { + converter: arc::R, + input: arc::R, + output: arc::R, + pcm: Pcm, + clock: Clock, + next_sample: Option, + expected_sample: Option, + frames: mpsc::Sender, +} +impl Converted { + fn receive(&mut self, buffer: &av::AudioPcmBuf, time: &av::AudioTime) -> Result<()> { + ensure!( + time.is_host_time_valid() && time.is_sample_time_valid(), + "microphone capture timestamp missing" + ); + if self + .expected_sample + .is_some_and(|next| next != time.sample_time()) + { + self.converter = av::AudioConverter::with_formats(&self.input, &self.output) + .context("microphone converter")?; + self.pcm = Pcm::default(); + self.next_sample = None; + } + self.expected_sample = Some(time.sample_time() + i64::from(buffer.frame_len())); + let captured = self + .clock + .project(cm::Clock::make_host_time_from_sys_units(time.host_time()))?; + self.next_sample.get_or_insert(time.sample_time() as f64); + let capacity = + (f64::from(buffer.frame_len()) * 48_000.0 / self.input.sample_rate()).ceil() as u32 + 1; + let mut output = av::AudioPcmBuf::with_format(&self.output, capacity) + .context("microphone PCM buffer")?; + let retained = buffer.retained(); + let mut supplied = false; + let mut input = av::AudioConverterInputBlock::new2( + move |_, status: &mut av::AudioConverterInputStatus| { + if supplied { + *status = av::AudioConverterInputStatus::NoDataNow; + return None; + } + supplied = true; + *status = av::AudioConverterInputStatus::HaveData; + // The converter consumes this retained native buffer synchronously. + unsafe { arc::return_opt_rar::(Some(&retained)) } + }, + ); + loop { + let status = checked( + self.converter + .convert_to_buf_with_input_from_block(&mut output, &mut input), + )?; + let left = output + .data_f32_at(0) + .context("microphone Float32 left channel")?; + let right = output + .data_f32_at(1) + .context("microphone Float32 right channel")?; + // Project the converter's next sample through this capture buffer's + // hardware sample/host-time pair, including buffered resampler input. + let delta = + (self.next_sample.unwrap() - time.sample_time() as f64) / self.input.sample_rate(); + let offset = Duration::from_secs_f64(delta.abs()); + let start = if delta < 0.0 { + captured - offset + } else { + captured + offset + }; + for (index, (left, right)) in left.iter().zip(right).enumerate() { + let time = start + Duration::from_nanos(index as u64 * 1_000_000_000 / 48_000); + if let Some(frame) = self.pcm.push([*left, *right], time) { + match self.frames.try_send(frame) { + Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {} + Err(mpsc::error::TrySendError::Closed(_)) => { + return Err(anyhow!("audio consumer closed")) + } + } + } + } + self.next_sample = Some( + self.next_sample.unwrap() + + f64::from(output.frame_len()) * self.input.sample_rate() / 48_000.0, + ); + if status != av::audio::ConverterOutputStatus::HaveData { + break; + } + } + Ok(()) + } +} diff --git a/prototype/channel-native/src/capture/macos/mod.rs b/prototype/channel-native/src/capture/macos/mod.rs index 2b22859cc..e8e2cbe50 100644 --- a/prototype/channel-native/src/capture/macos/mod.rs +++ b/prototype/channel-native/src/capture/macos/mod.rs @@ -5,7 +5,7 @@ mod encoding; mod frames; mod source; -pub use audio::{audio_capabilities, AudioCapture, AudioControl}; +pub use audio::{audio_capabilities, microphones, AudioCapture, AudioControl}; pub(crate) use decoder::Decoder; pub use encoding::{Encoding, EncodingControl}; pub(crate) use frames::ImageCopy; diff --git a/prototype/channel-native/src/capture/mod.rs b/prototype/channel-native/src/capture/mod.rs index 7725dd521..33d7e8757 100644 --- a/prototype/channel-native/src/capture/mod.rs +++ b/prototype/channel-native/src/capture/mod.rs @@ -5,8 +5,8 @@ pub use preview::{preview, MAX_PREVIEW_BYTES}; mod android; #[cfg(all(feature = "capture", target_os = "android"))] pub use android::{ - audio_capabilities, targets, AudioCapture, AudioControl, Capture, Control, Encoding, - EncodingControl, + audio_capabilities, microphones, targets, AudioCapture, AudioControl, Capture, Control, + Encoding, EncodingControl, }; /// Foreground handoff supplied by the installed App, separate from capture consent. @@ -50,7 +50,7 @@ mod windows; #[cfg(all(feature = "capture", target_os = "windows"))] mod worker; #[cfg(all(feature = "capture", target_os = "windows"))] -pub use audio::{audio_capabilities, AudioCapture, AudioControl}; +pub use audio::{audio_capabilities, microphones, AudioCapture, AudioControl}; #[cfg(all(feature = "capture", target_os = "windows"))] pub(crate) use decoder::Decoder; #[cfg(all(feature = "capture", target_os = "windows"))] @@ -59,15 +59,15 @@ pub use frames::Control; pub(crate) use frames::Frames; #[cfg(all(feature = "capture", target_os = "linux"))] pub use linux::{ - audio_capabilities, targets, AudioCapture, AudioControl, Capture, Control, Encoding, - EncodingControl, + audio_capabilities, microphones, targets, AudioCapture, AudioControl, Capture, Control, + Encoding, EncodingControl, }; #[cfg(all(feature = "capture", target_os = "linux"))] pub(crate) use linux::{decoder, Frames}; #[cfg(all(feature = "capture", target_os = "macos"))] pub use macos::{ - audio_capabilities, targets, AudioCapture, AudioControl, Capture, Control, Encoding, - EncodingControl, + audio_capabilities, microphones, targets, AudioCapture, AudioControl, Capture, Control, + Encoding, EncodingControl, }; #[cfg(all(feature = "capture", target_os = "macos"))] pub(crate) use macos::{Decoder, Frames}; @@ -110,6 +110,17 @@ pub struct AudioCapabilities { pub system_audio: bool, } +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct MicrophoneDevice { + pub id: String, + pub label: String, +} + +#[cfg(not(feature = "capture"))] +pub fn microphones() -> anyhow::Result> { + anyhow::bail!("microphone_unavailable") +} + #[cfg(not(feature = "capture"))] pub fn audio_capabilities() -> AudioCapabilities { AudioCapabilities::default() diff --git a/prototype/channel-native/src/media/local.rs b/prototype/channel-native/src/media/local.rs index ea3d8e5b1..425cdcbcb 100644 --- a/prototype/channel-native/src/media/local.rs +++ b/prototype/channel-native/src/media/local.rs @@ -3,28 +3,26 @@ use super::{ clock::SourceTime, packetizer::Packetizer, video::Video, H264Sps, Relay, Source, SourceFeed, SourceOrigin, }; +#[cfg(target_os = "windows")] +use crate::capture::AudioCapture; use crate::media::MediaKind; use crate::media::RtpCodec; use crate::{ - capture::{ - AudioCapture, AudioControl as CaptureAudioControl, Capture, Control as VideoControl, - Settings, Target, - }, + capture::{Capture, Control as VideoControl, Settings, Target}, peer::{Event, InitialMedia, SourceReady}, }; use anyhow::{anyhow, Result}; use rtc_shared::time::SystemInstant; -use std::{ - sync::{Arc, Mutex}, - time::Instant, -}; +use std::{sync::Arc, time::Instant}; use tokio::{ sync::{mpsc, oneshot, watch, Notify}, task::JoinHandle, }; use uuid::Uuid; +mod audio; mod encodings; +pub(crate) use audio::AudioLeaseControl; pub(crate) use super::encodings::VideoDemand; @@ -34,49 +32,28 @@ pub(crate) struct Control { video: VideoControl, video_settings: watch::Sender, video_requests: mpsc::Sender, - audio: Arc>>, - audio_settings: watch::Sender, + audio: audio::Control, } struct VideoSettingsRequest { settings: Settings, result: oneshot::Sender>, } -#[derive(Clone)] -pub(crate) struct AudioLeaseControl { - capture: Option, - cancelled: watch::Sender, - settings: watch::Sender, -} -impl AudioLeaseControl { - pub fn set_audio_settings(&self, settings: crate::peer::SourceAudioSettings) { - self.settings.send_replace(settings); - } - pub fn stop(&self) { - self.cancelled.send_replace(true); - if let Some(capture) = &self.capture { - capture.stop(); - } - } - pub fn is_stopped(&self) -> bool { - *self.cancelled.borrow() - } -} -struct AudioLease { - control: AudioLeaseControl, - task: JoinHandle<()>, -} -impl AudioLease { - async fn close(&mut self) { - self.control.stop(); - if let Err(error) = (&mut self.task).await { - eprintln!("Native audio task failed: {error}"); - } - } -} impl Control { + pub fn microphone_state(&self) -> watch::Receiver { + self.audio.microphone.clone() + } + pub async fn configure_microphone( + &self, + settings: crate::peer::SourceMicrophoneSettings, + ) -> Result<()> { + anyhow::ensure!(!self.is_stopped(), "capture_unavailable"); + self.audio.configure_microphone(settings).await + } + pub async fn cancel_microphone(&self) -> Result<()> { + self.audio.cancel_microphone().await + } pub async fn configure_video(&self, settings: Settings) -> Result<()> { - settings.validate()?; anyhow::ensure!(!self.is_stopped(), "capture_unavailable"); let (result, applied) = oneshot::channel(); self.video_requests @@ -85,11 +62,11 @@ impl Control { applied.await.map_err(|_| anyhow!("capture_unavailable"))? } pub fn set_audio_settings(&self, settings: crate::peer::SourceAudioSettings) { - self.audio_settings.send_replace(settings); + self.audio.settings.send_replace(settings); } pub fn audio_bitrate(&self) -> u32 { - self.audio_settings.borrow().bitrate + self.audio.settings.borrow().bitrate } #[cfg(target_os = "linux")] pub(crate) async fn authorize( @@ -102,9 +79,7 @@ impl Control { pub fn stop(&self) { self.video.stop(); - if let Some(audio) = self.audio.lock().unwrap().as_ref() { - audio.stop(); - } + self.audio.stop(); } pub fn is_stopped(&self) -> bool { self.video.is_stopped() @@ -113,13 +88,11 @@ impl Control { pub(crate) struct Producer { pub video: Uuid, - pub audio: Option, pub control: Control, task: Option>>, demands: watch::Sender>, - audio_lease: Option, - epoch: Instant, - clock: SystemInstant, + audio_task: Option>, + system_audio: Option, } impl Producer { pub fn settings(&self) -> Settings { @@ -134,7 +107,7 @@ impl Producer { true }); } - pub fn start( + pub async fn start( publication_id: Uuid, target: Target, settings: Settings, @@ -157,80 +130,59 @@ impl Producer { let capture = Capture::start(target.clone(), settings.fps, audio)?; let encoding = capture.encode(settings)?; let video_control = capture.control(); - let (audio_settings, settings_rx) = - watch::channel(crate::peer::SourceAudioSettings::default()); - let (audio_ready, required_audio) = if exclude_audio.is_some() { - let (ready, started) = oneshot::channel(); - (Some(ready), Some(started)) - } else { - (None, None) - }; - let (audio_error, warning) = if audio { - let (error, warning) = oneshot::channel(); - (Some(error), Some(warning)) - } else { - (None, None) - }; - let audio = if let Some(error) = audio_error { + let (audio_control, audio_task) = audio::start( + publication_id, + now, + clock, + ready_sources.clone(), + events.clone(), + relay, + cancelled.clone(), + ); + let mut system_audio = None; + let mut required_audio = None; + let mut warning = None; + if audio { #[cfg(target_os = "windows")] - let input = AudioCapture::start_with_exclusion(target, exclude_audio); + let input = AudioCapture::start_with_exclusion(target, exclude_audio.clone()); #[cfg(not(target_os = "windows"))] let input = if exclude_audio.is_some() { Err(anyhow!("audio exclusion unavailable")) } else { capture.audio(target) }; - match input { - Ok(capture) => { - let id = Uuid::new_v4(); - let (retire, retired) = watch::channel(false); - let control = AudioLeaseControl { - capture: Some(capture.control()), - cancelled: retire, - settings: audio_settings.clone(), - }; - let task = tokio::spawn(audio_source( - capture, - id, - publication_id, - now, - clock, - ready_sources.clone(), - events.clone(), - relay.clone(), - video_control.clone(), - cancelled.clone(), - error, - retired, - audio_ready, - settings_rx, - )); - Some((id, AudioLease { control, task })) + let prepared = match input { + Ok(input) => audio_control.system(Some(input)).await, + Err(error) => Err(error), + }; + match prepared { + Ok((control, ready, failed)) => { + system_audio = Some(control); + warning = failed; + if exclude_audio.is_some() { + required_audio = Some(ready); + } } Err(failure) => { let error_text = format!("{failure:#}"); - if let Some(ready) = audio_ready { - let _ = ready.send(Err(anyhow!(error_text.clone()))); + let (error, failed) = oneshot::channel(); + let _ = error.send(error_text.clone()); + warning = Some(failed); + if exclude_audio.is_some() { + let (ready, started) = oneshot::channel(); + let _ = ready.send(Err(anyhow!(error_text))); + required_audio = Some(started); } - eprintln!("Native source audio failed: {error_text}"); - let _ = error.send(error_text); - None } } - } else { - None - }; - let audio_id = audio.as_ref().map(|(id, _)| *id); + } let (video_settings, _) = watch::channel(settings); let (video_requests, changes) = mpsc::channel(1); let control = Control { video: video_control, video_settings, video_requests, - audio_settings, - audio: Arc::new(Mutex::new( - audio.as_ref().map(|(_, lease)| lease.control.clone()), - )), + audio: audio_control, }; let video = Uuid::new_v4(); let (ready, started) = oneshot::channel(); @@ -254,13 +206,11 @@ impl Producer { Ok(( Self { video, - audio: audio_id, control, task: Some(task), demands, - audio_lease: audio.map(|(_, lease)| lease), - epoch: now, - clock, + audio_task: Some(audio_task), + system_audio, }, started, warning, @@ -268,24 +218,21 @@ impl Producer { )) } - pub async fn stop_audio(&mut self) { - if let Some(control) = self.control.audio.lock().unwrap().take() { + pub fn audio(&self) -> Option { + *self.control.audio.source.borrow() + } + + pub async fn stop_system_audio(&mut self) { + if let Some(control) = self.system_audio.take() { control.stop(); } - if let Some(audio) = self.audio_lease.as_mut() { - audio.close().await; - } - self.audio_lease = None; - self.audio = None; + let _ = self.control.audio.stop_system().await; } pub fn audio_is_stopped(&self) -> bool { - self.control - .audio - .lock() - .unwrap() + self.system_audio .as_ref() - .is_some_and(|audio| audio.is_stopped()) + .is_some_and(AudioLeaseControl::is_stopped) } pub async fn close(&mut self) -> Option { @@ -300,179 +247,31 @@ impl Producer { } else { None }; - self.stop_audio().await; + if let Some(task) = self.audio_task.take() { + let _ = task.await; + } error } #[cfg(target_os = "windows")] pub async fn prepare_audio( &mut self, - publication_id: Uuid, target: Target, enabled: bool, exclude: Option, - ready_sources: mpsc::Sender, - events: mpsc::Sender, - relay: Relay, - cancelled: watch::Receiver, ) -> Result<( AudioLeaseControl, oneshot::Receiver>, Option>, )> { - self.stop_audio().await; + self.stop_system_audio().await; anyhow::ensure!(!self.control.is_stopped(), "capture_unavailable"); - let (retire, retired) = watch::channel(false); - let (ready, started) = oneshot::channel(); - let (warning, failed) = oneshot::channel(); - let capture = if enabled { - Some(AudioCapture::start_with_exclusion(target, exclude)?) - } else { - None - }; - let control = AudioLeaseControl { - capture: capture.as_ref().map(|c| c.control()), - cancelled: retire, - settings: self.control.audio_settings.clone(), - }; - *self.control.audio.lock().unwrap() = Some(control.clone()); - if let Some(capture) = capture { - let id = Uuid::new_v4(); - self.audio = Some(id); - let task = tokio::spawn(audio_source( - capture, - id, - publication_id, - self.epoch, - self.clock, - ready_sources, - events, - relay, - self.control.video.clone(), - cancelled, - warning, - retired, - Some(ready), - self.control.audio_settings.subscribe(), - )); - self.audio_lease = Some(AudioLease { - control: control.clone(), - task, - }); - if self.control.is_stopped() { - self.stop_audio().await; - anyhow::bail!("capture_unavailable"); - } - Ok((control, started, Some(failed))) - } else { - if self.control.is_stopped() { - self.stop_audio().await; - anyhow::bail!("capture_unavailable"); - } - let _ = ready.send(Ok(())); - Ok((control, started, None)) - } - } -} - -async fn audio_source( - mut capture: AudioCapture, - id: Uuid, - publication_id: Uuid, - now: Instant, - clock: SystemInstant, - ready_sources: mpsc::Sender, - events: mpsc::Sender, - relay: Relay, - video: VideoControl, - mut cancelled: watch::Receiver, - warning: oneshot::Sender, - mut retired: watch::Receiver, - mut ready: Option>>, - mut settings: watch::Receiver, -) { - let result = { - let work = async { - capture.ready().await?; - let mut encoder = - rusty_opus::OpusEncoder::new(48_000, 2, rusty_opus::Application::Audio)?; - encoder.complexity = 10; - encoder.use_cbr = true; - let mut encoded = [0u8; 1500]; - let mut source = RtpSource::new( - id, - publication_id, - MediaKind::Audio, - crate::peer::codec(), - 111, - now, - clock, - )?; - if let Some(ready) = ready.take() { - let _ = ready.send(Ok(())); - } - let mut first = true; - loop { - let mut frame = tokio::select! { - frame = capture.recv() => match frame { - Some(frame) => frame?, - None => break, - }, - _ = cancelled.changed() => break, - }; - let length = encode_audio( - &mut encoder, - &mut frame.samples, - *settings.borrow_and_update(), - &mut encoded, - )?; - let packets = - source.packetize(encoded[..length].to_vec(), frame.presentation_time)?; - if first { - tokio::select! { - result = ready_sources.send(SourceReady { source: source.source.clone(), media: InitialMedia::Rtp(packets) }) => { result?; } - _ = cancelled.changed() => break, - } - first = false; - } else { - for packet in packets { - relay.write(id, packet); - } - } - } - Ok::<_, anyhow::Error>(()) - }; - tokio::pin!(work); - tokio::select! { - result = &mut work => result, - _ = retired.changed() => Ok(()), - } - }; - if let Some(ready) = ready.take() { - let error = result - .as_ref() - .err() - .map(|error| format!("{error:#}")) - .unwrap_or_else(|| "audio preparation cancelled".into()); - let _ = ready.send(Err(anyhow!(error))); - } - let joined = tokio::task::spawn_blocking(move || capture.stop()) - .await - .map_err(anyhow::Error::from) - .and_then(|result| result); - if !video.is_stopped() && !*cancelled.borrow() && !*retired.borrow() { - let error = result - .and(joined) - .err() - .map(|error| format!("{error:#}")) - .unwrap_or_else(|| "source audio ended".into()); - eprintln!("Native source audio failed: {error}"); - let _ = warning.send(error); - tokio::select! { - _ = events.send(Event::CaptureAudioEnded { publication_id, source: id }) => {}, - _ = cancelled.changed() => {}, - _ = retired.changed() => {}, - } + let capture = enabled + .then(|| AudioCapture::start_with_exclusion(target, exclude)) + .transpose()?; + let (control, ready, warning) = self.control.audio.system(capture).await?; + self.system_audio = Some(control.clone()); + Ok((control, ready, warning)) } } @@ -483,10 +282,8 @@ fn encode_audio( encoded: &mut [u8], ) -> Result { encoder.bitrate_bps = settings.bitrate as i32; - if settings.gain != 1.0 { - for sample in samples.iter_mut() { - *sample = (*sample * settings.gain).clamp(-1.0, 1.0); - } + for sample in samples.iter_mut() { + *sample = (*sample * settings.gain).clamp(-1.0, 1.0); } Ok(encoder.encode(samples, 960, encoded)?) } @@ -613,104 +410,6 @@ mod tests { Ok(()) } - #[cfg(target_os = "windows")] - #[tokio::test] - async fn audio_replacement_joins_its_lease_and_keeps_the_video_clock() -> Result<()> { - let frames = crate::capture::Frames::new(crate::capture::FrameTiming::Capture)?; - let video = Uuid::new_v4(); - let epoch = Instant::now(); - let clock = SystemInstant::now(epoch); - let (retire, mut retired) = watch::channel(false); - let previous = AudioLeaseControl { - capture: None, - cancelled: retire, - settings: watch::channel(crate::peer::SourceAudioSettings::default()).0, - }; - let (joined, finished) = oneshot::channel(); - let task = tokio::spawn(async move { - let _ = retired.changed().await; - let _ = joined.send(()); - }); - let settings = Settings { - width: 1280, - height: 720, - fps: 30, - bitrate: 2_000_000, - }; - let mut producer = Producer { - video, - audio: Some(Uuid::new_v4()), - epoch, - clock, - control: Control { - video: frames.control(), - video_settings: watch::channel(settings).0, - video_requests: mpsc::channel(1).0, - audio_settings: previous.settings.clone(), - audio: Arc::new(Mutex::new(Some(previous.clone()))), - }, - task: Some(tokio::spawn(async { None })), - demands: watch::channel(vec![]).0, - audio_lease: Some(AudioLease { - control: previous.clone(), - task, - }), - }; - let target = Target { - kind: crate::capture::TargetKind::Display, - source_id: "1".into(), - title: "Fixture display".into(), - pid: 0, - creation_time: None, - }; - let (sources, _) = mpsc::channel(1); - let (events, _) = mpsc::channel(1); - let relay = Relay::default(); - let cancel = watch::channel(false).1; - let (pending, ready, _) = producer - .prepare_audio( - Uuid::new_v4(), - target.clone(), - false, - None, - sources.clone(), - events.clone(), - relay.clone(), - cancel.clone(), - ) - .await?; - ready.await??; - finished.await?; - assert!(previous.is_stopped()); - assert!(!producer.control.is_stopped()); - assert_eq!( - (producer.video, producer.epoch, producer.clock), - (video, epoch, clock) - ); - // An exclusion activation rejection must leave this same video alive - // with the previous source audio retired, rather than restore that mix. - assert!(producer - .prepare_audio( - Uuid::new_v4(), - target.clone(), - true, - Some(target), - sources, - events, - relay, - cancel - ) - .await - .is_err()); - assert!(pending.is_stopped()); - assert!(producer.audio.is_none()); - assert!(!producer.control.is_stopped()); - producer.control.stop(); - producer.stop_audio().await; - producer.close().await; - Ok(()) - } - #[test] fn audio_packets_and_reports_keep_the_shared_capture_clock_across_pcm_gaps() -> Result<()> { let epoch = Instant::now(); diff --git a/prototype/channel-native/src/media/local/audio.rs b/prototype/channel-native/src/media/local/audio.rs new file mode 100644 index 000000000..f09b2bdc0 --- /dev/null +++ b/prototype/channel-native/src/media/local/audio.rs @@ -0,0 +1,666 @@ +//! The publication's two PCM inputs share one optional Opus source and capture clock. +use super::{encode_audio, RtpSource}; +use crate::{ + capture::{AudioCapture, AudioControl as CaptureControl, AudioFrame}, + media::{MediaKind, Relay}, + peer::{Event, InitialMedia, SourceAudioSettings, SourceMicrophoneSettings, SourceReady}, +}; +use anyhow::{anyhow, Result}; +use futures_util::future::BoxFuture; +use rtc_shared::time::SystemInstant; +use std::{ + collections::VecDeque, + time::{Duration, Instant}, +}; +use tokio::{ + sync::{mpsc, oneshot, watch}, + task::JoinHandle, +}; +use uuid::Uuid; + +#[derive(Clone)] +pub(super) struct Control { + requests: mpsc::Sender, + stopped: watch::Sender, + pub source: watch::Receiver>, + pub microphone: watch::Receiver, + pub settings: watch::Sender, +} +#[derive(Clone)] +pub(crate) struct AudioLeaseControl { + capture: Option, + cancelled: watch::Sender, + settings: watch::Sender, +} +impl AudioLeaseControl { + pub fn set_audio_settings(&self, settings: SourceAudioSettings) { + self.settings.send_replace(settings); + } + pub fn stop(&self) { + self.cancelled.send_replace(true); + if let Some(capture) = &self.capture { + capture.stop(); + } + } + pub fn is_stopped(&self) -> bool { + *self.cancelled.borrow() + } +} +struct Input { + capture: AudioCapture, + system: Option<(watch::Receiver, oneshot::Sender)>, +} +enum Request { + System(Option, oneshot::Sender>), + StopSystem(oneshot::Sender<()>), + Microphone(SourceMicrophoneSettings, oneshot::Sender>), + CancelMicrophone(oneshot::Sender<()>), +} +struct Preparing { + control: CaptureControl, + ready: BoxFuture<'static, (Input, Result<()>)>, + microphone: Option, + reply: oneshot::Sender>, +} +impl Preparing { + fn new( + mut input: Input, + microphone: Option, + reply: oneshot::Sender>, + ) -> Self { + Self { + control: input.capture.control(), + microphone, + reply, + ready: Box::pin(async move { + let result = input.capture.ready().await; + (input, result) + }), + } + } + async fn close(self) { + self.control.stop(); + let (input, _) = self.ready.await; + close(input).await; + let _ = self.reply.send(Err(anyhow!("capture_cancelled"))); + } +} +impl Control { + pub fn stop(&self) { + self.stopped.send_replace(true); + } + pub async fn stop_system(&self) -> Result<()> { + let (done, wait) = oneshot::channel(); + self.requests + .send(Request::StopSystem(done)) + .await + .map_err(|_| anyhow!("capture_unavailable"))?; + wait.await.map_err(|_| anyhow!("capture_unavailable")) + } + pub async fn system( + &self, + capture: Option, + ) -> Result<( + AudioLeaseControl, + oneshot::Receiver>, + Option>, + )> { + let (cancel, cancelled) = watch::channel(false); + let (warning, failed) = oneshot::channel(); + let (ready, wait) = oneshot::channel(); + let control = AudioLeaseControl { + capture: capture.as_ref().map(AudioCapture::control), + cancelled: cancel, + settings: self.settings.clone(), + }; + let present = capture.is_some(); + if let Err(error) = self + .requests + .send(Request::System( + capture.map(|capture| Input { + capture, + system: Some((cancelled, warning)), + }), + ready, + )) + .await + { + if let Request::System(Some(input), _) = error.0 { + close(input).await; + } + return Err(anyhow!("capture_unavailable")); + } + Ok((control, wait, present.then_some(failed))) + } + pub async fn configure_microphone(&self, settings: SourceMicrophoneSettings) -> Result<()> { + let (done, wait) = oneshot::channel(); + self.requests + .send(Request::Microphone(settings, done)) + .await + .map_err(|_| anyhow!("capture_unavailable"))?; + wait.await.map_err(|_| anyhow!("capture_unavailable"))? + } + pub async fn cancel_microphone(&self) -> Result<()> { + let (done, wait) = oneshot::channel(); + self.requests + .send(Request::CancelMicrophone(done)) + .await + .map_err(|_| anyhow!("capture_unavailable"))?; + wait.await.map_err(|_| anyhow!("capture_unavailable")) + } +} + +pub(super) fn start( + publication: Uuid, + epoch: Instant, + clock: SystemInstant, + ready_sources: mpsc::Sender, + events: mpsc::Sender, + relay: Relay, + cancelled: watch::Receiver, +) -> (Control, JoinHandle<()>) { + run( + publication, + epoch, + clock, + ready_sources, + events, + relay, + cancelled, + AudioCapture::microphone, + ) +} + +fn run( + publication: Uuid, + epoch: Instant, + clock: SystemInstant, + ready_sources: mpsc::Sender, + events: mpsc::Sender, + relay: Relay, + mut cancelled: watch::Receiver, + open_microphone: impl Fn(String) -> Result + Send + Sync + 'static, +) -> (Control, JoinHandle<()>) { + let (requests, mut received) = mpsc::channel(1); + let (stopped, mut stop) = watch::channel(false); + let (source, source_state) = watch::channel(None); + let (microphone, mic_state) = watch::channel(SourceMicrophoneSettings::default()); + let (settings, audio_settings) = watch::channel(SourceAudioSettings::default()); + let control = Control { + requests, + stopped, + source: source_state, + microphone: mic_state, + settings, + }; + let task = tokio::spawn(async move { + let mut system: Option = None; + let mut mic: Option = None; + let mut pending: Option = None; + let mut output: Option<(rusty_opus::OpusEncoder, RtpSource, bool)> = None; + let mut mix = Mix::default(); + let mut encoded = [0u8; 1500]; + let work: Result<()> = async { + 'work: loop { + tokio::select! { + biased; + _ = wait_stopped(&mut stop) => break, + _ = wait_stopped(&mut cancelled) => break, + request = received.recv() => match request { + None => break, + Some(Request::StopSystem(done)) => { + if pending.as_ref().is_some_and(|p| p.microphone.is_none()) { pending.take().unwrap().close().await; } + if let Some(input) = system.take() { close(input).await; } + mix.clear(0); + let _ = done.send(()); + } + Some(Request::CancelMicrophone(done)) => { + if pending.as_ref().is_some_and(|p| p.microphone.is_some()) { pending.take().unwrap().close().await; } + let _ = done.send(()); + } + Some(Request::System(input, reply)) => { + if pending.is_some() { let _ = reply.send(Err(anyhow!("capture_pending"))); if let Some(input) = input { close(input).await; } } + else if let Some(input) = input { pending = Some(Preparing::new(input, None, reply)); } + else { let _ = reply.send(Ok(())); } + } + Some(Request::Microphone(next, reply)) => { + if pending.is_some() { let _ = reply.send(Err(anyhow!("capture_pending"))); } + else if !next.enabled { + if let Some(input) = mic.take() { close(input).await; } + mix.clear(1); + microphone.send_replace(next); + let _ = reply.send(Ok(())); + } else if mic.is_some() && microphone.borrow().device_id == next.device_id { + microphone.send_replace(next); + let _ = reply.send(Ok(())); + } else { + match open_microphone(next.device_id.clone()) { + Ok(capture) => pending = Some(Preparing::new(Input { capture, system: None }, Some(next), reply)), + Err(error) => { let _ = reply.send(Err(error)); } + } + } + } + }, + (input, result) = async { pending.as_mut().unwrap().ready.as_mut().await }, if pending.is_some() => { + let prepared = pending.take().unwrap(); + if let Err(error) = result { + let text = format!("{error:#}"); + failed(input, &text).await; + let _ = prepared.reply.send(Err(error)); + } else if prepared.control.is_stopped() || (prepared.microphone.is_some() && prepared.reply.is_closed()) { + close(input).await; + } else if let Some(next) = prepared.microphone { + if let Some(old) = mic.replace(input) { close(old).await; } + mix.clear(1); + microphone.send_replace(next); + let _ = prepared.reply.send(Ok(())); + } else { + if let Some(old) = system.replace(input) { close(old).await; } + mix.clear(0); + let _ = prepared.reply.send(Ok(())); + } + }, + frame = async { system.as_mut().unwrap().capture.recv().await }, if system.is_some() => match frame { + Some(Ok(frame)) => mix.push(0, frame), + end => { failed(system.take().unwrap(), &ended(end)).await; mix.clear(0); } + }, + frame = async { mic.as_mut().unwrap().capture.recv().await }, if mic.is_some() => match frame { + Some(Ok(frame)) => mix.push(1, frame), + end => { + failed(mic.take().unwrap(), &ended(end)).await; + mix.clear(1); + microphone.send_modify(|state| state.enabled = false); + } + }, + } + if system.is_none() && mic.is_none() { + if let Some((_, old, _)) = output.take() { + tokio::select! { + result = events.send(Event::CaptureAudioEnded { publication_id: publication, source: old.source.id }) => { result?; } + _ = wait_stopped(&mut stop) => break 'work, + _ = wait_stopped(&mut cancelled) => break 'work, + } + source.send_replace(None); + } + mix = Mix::default(); + } + let mic_gain = microphone.borrow().volume; + while let Some(mut frame) = mix.pop(system.is_some() && mic.is_some(), mic_gain) { + if output.is_none() { + let mut encoder = rusty_opus::OpusEncoder::new(48_000, 2, rusty_opus::Application::Audio)?; + encoder.complexity = 10; + encoder.use_cbr = true; + let id = Uuid::new_v4(); + output = Some((encoder, RtpSource::new(id, publication, MediaKind::Audio, crate::peer::codec(), 111, epoch, clock)?, true)); + source.send_replace(Some(id)); + } + let (encoder, rtp, first) = output.as_mut().unwrap(); + let length = encode_audio(encoder, &mut frame.samples, *audio_settings.borrow(), &mut encoded)?; + let packets = rtp.packetize(encoded[..length].to_vec(), frame.presentation_time)?; + if *first { + tokio::select! { + result = ready_sources.send(SourceReady { source: rtp.source.clone(), media: InitialMedia::Rtp(packets) }) => { result?; } + _ = wait_stopped(&mut stop) => break 'work, + _ = wait_stopped(&mut cancelled) => break 'work, + } + *first = false; + } else { for packet in packets { relay.write(rtp.source.id, packet); } } + } + } + Ok(()) + }.await; + if let Some(pending) = pending { + pending.close().await; + } + if let Some(input) = system { + close(input).await; + } + if let Some(input) = mic { + close(input).await; + } + microphone.send_modify(|state| state.enabled = false); + if let Err(error) = work { + eprintln!("Native audio source failed: {error:#}"); + } + // The Driver removes a stopped producer's last source after joining it. + // Keep that identity until either its end event is queued or that join. + let last = *source.borrow(); + if let Some(id) = last.filter(|_| !*stop.borrow() && !*cancelled.borrow()) { + tokio::select! { + _ = events.send(Event::CaptureAudioEnded { publication_id: publication, source: id }) => { source.send_replace(None); }, + _ = wait_stopped(&mut cancelled) => {}, + _ = wait_stopped(&mut stop) => {}, + } + } + }); + (control, task) +} + +async fn wait_stopped(signal: &mut watch::Receiver) { + let _ = signal.wait_for(|v| *v).await; +} + +fn ended(end: Option>) -> String { + end.and_then(Result::err) + .map(|error| format!("{error:#}")) + .unwrap_or_else(|| "audio input ended".into()) +} +async fn close(input: Input) { + let _ = tokio::task::spawn_blocking(move || input.capture.stop()).await; +} +async fn failed(mut input: Input, error: &str) { + if let Some((cancel, warning)) = input.system.take() { + if !*cancel.borrow() { + let _ = warning.send(error.into()); + } + } + eprintln!("Native audio input ended: {error}"); + close(input).await; +} + +/// One PCM frame of lookahead aligns native capture timestamps. Queues remain +/// bounded by the same two-frame raw-input budget; no silence timer or drift loop. +#[derive(Default)] +struct Mix { + inputs: [VecDeque; 2], + next: Option, +} +impl Mix { + fn clear(&mut self, index: usize) { + self.inputs[index].clear(); + } + fn push(&mut self, index: usize, frame: AudioFrame) { + let frames = &mut self.inputs[index]; + if frames.len() == 2 { + frames.pop_front(); + } + frames.push_back(frame); + } + fn pop(&mut self, two: bool, gain: f32) -> Option { + let duration = Duration::from_millis(20); + if let Some(next) = self.next { + for queue in &mut self.inputs { + while queue + .front() + .is_some_and(|frame| frame.presentation_time + duration <= next) + { + queue.pop_front(); + } + } + } + let earliest = self + .inputs + .iter() + .filter_map(|q| q.front().map(|f| f.presentation_time)) + .min()?; + let start = self.next.map_or(earliest, |next| next.max(earliest)); + let end = start + duration; + let latest = self + .inputs + .iter() + .filter_map(|q| q.back().map(|f| f.presentation_time)) + .max()?; + if two && latest < end { + return None; + } + let mut samples = vec![0.0; 1920]; + for (index, queue) in self.inputs.iter_mut().enumerate() { + for frame in queue.iter() { + let offset = if frame.presentation_time >= start { + (frame.presentation_time.duration_since(start).as_secs_f64() * 48_000.0).round() + as i64 + } else { + -(start.duration_since(frame.presentation_time).as_secs_f64() * 48_000.0) + .round() as i64 + }; + for (at, pair) in frame.samples.chunks_exact(2).enumerate() { + let at = at as i64 + offset; + if (0..960).contains(&at) { + for channel in 0..2 { + samples[at as usize * 2 + channel] += + pair[channel] * if index == 1 { gain } else { 1.0 }; + } + } + } + } + while queue + .front() + .is_some_and(|frame| frame.presentation_time + duration <= end) + { + queue.pop_front(); + } + } + self.next = Some(end); + Some(AudioFrame { + samples, + presentation_time: start, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(at: Instant, values: [f32; 2]) -> AudioFrame { + AudioFrame { + samples: values.repeat(960), + presentation_time: at, + } + } + + #[test] + fn captured_pcm_alignment_preserves_stereo_gain_gaps_and_input_retirement() { + let at = Instant::now(); + let mut mix = Mix::default(); + mix.push(0, frame(at, [0.2, 0.4])); + mix.push(1, frame(at + Duration::from_millis(10), [0.6, 0.8])); + assert!(mix.pop(true, 0.5).is_none()); + mix.push(0, frame(at + Duration::from_millis(20), [0.2, 0.4])); + let first = mix.pop(true, 0.5).unwrap(); + assert_eq!(first.presentation_time, at); + assert_eq!(&first.samples[..2], &[0.2, 0.4]); + assert_eq!(&first.samples[960..962], &[0.5, 0.8]); + // Retire only the system sound: the microphone's remaining half frame + // retains its position on the same output clock. + mix.clear(0); + mix.push(1, frame(at + Duration::from_millis(30), [0.6, 0.8])); + let next = mix.pop(false, 0.5).unwrap(); + assert_eq!(next.presentation_time, at + Duration::from_millis(20)); + assert!(next.samples.chunks_exact(2).all(|pair| pair == [0.3, 0.4])); + mix.clear(1); + mix.push(1, frame(at + Duration::from_millis(100), [0.6, 0.8])); + let gap = mix.pop(false, 0.0).unwrap(); + assert_eq!(gap.presentation_time, at + Duration::from_millis(100)); + assert!(gap.samples.iter().all(|sample| *sample == 0.0)); + assert!(mix.pop(false, 1.0).is_none()); + mix.push(0, frame(at + Duration::from_millis(20), [0.2, 0.4])); + assert!(mix.pop(false, 1.0).is_none()); + } + + #[cfg(target_os = "windows")] + #[tokio::test] + async fn independent_inputs_retain_one_opus_source_and_join_on_cancel() -> Result<()> { + use std::sync::Mutex; + tokio::time::timeout(Duration::from_secs(3), async { + let epoch = Instant::now(); + let clock = SystemInstant::now(epoch); + let publication = Uuid::new_v4(); + let (sources, mut ready) = mpsc::channel(4); + let (events, mut ended) = mpsc::channel(4); + let relay = Relay::default(); + let (_cancel, cancelled) = watch::channel(false); + let (mic, mic_pcm, mic_joined) = AudioCapture::fixture(true)?; + let mic_control = mic.control(); + let (again, again_pcm, again_joined) = AudioCapture::fixture(true)?; + let again_control = again.control(); + let (cancelled_candidate, _cancelled_pcm, cancelled_joined) = + AudioCapture::fixture(false)?; + let (cancel_opening, cancel_opened) = oneshot::channel(); + let (candidate, _candidate_pcm, candidate_joined) = AudioCapture::fixture(false)?; + let (opening, opened) = oneshot::channel(); + let inputs = Mutex::new(VecDeque::from([ + ("mic", mic, None), + ("again", again, None), + ("cancelled", cancelled_candidate, Some(cancel_opening)), + ("pending", candidate, Some(opening)), + ])); + let (control, task) = run( + publication, + epoch, + clock, + sources, + events, + relay.clone(), + cancelled, + move |device| { + if device == "missing" { + anyhow::bail!("device unavailable"); + } + let (expected, input, opening) = inputs.lock().unwrap().pop_front().unwrap(); + assert_eq!(device, expected); + if let Some(opening) = opening { + let _ = opening.send(()); + } + Ok(input) + }, + ); + assert!(control.source.borrow().is_none()); + let (system, system_pcm, system_joined) = AudioCapture::fixture(true)?; + let (_, started, _) = control.system(Some(system)).await?; + started.await??; + system_pcm.send(frame(epoch, [0.1, 0.2])).await?; + let first = ready.recv().await.unwrap(); + let id = first.source.id; + let InitialMedia::Rtp(first_packets) = first.media else { + panic!("audio RTP"); + }; + let first_timestamp = first_packets[0].header.timestamp; + let (packets, mut received) = mpsc::channel(8); + relay.set(id, vec![packets]); + control + .configure_microphone(SourceMicrophoneSettings { + enabled: true, + device_id: "mic".into(), + volume: 0.5, + }) + .await?; + for millis in [20, 40] { + mic_pcm + .send(frame(epoch + Duration::from_millis(millis), [0.2, 0.4])) + .await?; + system_pcm + .send(frame(epoch + Duration::from_millis(millis), [0.1, 0.2])) + .await?; + } + let mixed = received.recv().await.unwrap(); + assert_eq!(mixed.header.timestamp.wrapping_sub(first_timestamp), 960); + assert_eq!(control.source.borrow().as_ref(), Some(&id)); + assert!(control + .configure_microphone(SourceMicrophoneSettings { + enabled: true, + device_id: "missing".into(), + volume: 1.0 + }) + .await + .is_err()); + assert_eq!(control.microphone.borrow().device_id, "mic"); + assert!(!mic_control.is_stopped()); + control.stop_system().await?; + system_joined.await?; + assert!(!mic_control.is_stopped()); + mic_pcm + .send(frame(epoch + Duration::from_millis(80), [0.2, 0.4])) + .await?; + loop { + let packet = received.recv().await.unwrap(); + if packet.header.timestamp.wrapping_sub(first_timestamp) == 3840 { + break; + } + } + assert_eq!(*control.source.borrow(), Some(id)); + assert!(ready.try_recv().is_err()); + control + .configure_microphone(SourceMicrophoneSettings { + enabled: true, + device_id: "mic".into(), + volume: 1.5, + }) + .await?; + assert_eq!(control.microphone.borrow().volume, 1.5); + control + .configure_microphone(SourceMicrophoneSettings { + enabled: false, + device_id: "mic".into(), + volume: 1.5, + }) + .await?; + mic_joined.await?; + let Event::CaptureAudioEnded { source, .. } = ended.recv().await.unwrap() else { + panic!("source retired"); + }; + assert_eq!(source, id); + let mut current = control.source.clone(); + current.wait_for(Option::is_none).await?; + assert!(!control.microphone.borrow().enabled); + control + .configure_microphone(SourceMicrophoneSettings { + enabled: true, + device_id: "again".into(), + volume: 1.0, + }) + .await?; + again_pcm + .send(frame(epoch + Duration::from_millis(200), [0.2, 0.4])) + .await?; + let resumed = ready.recv().await.unwrap(); + assert_ne!(resumed.source.id, id); + let changing = { + let control = control.clone(); + tokio::spawn(async move { + control + .configure_microphone(SourceMicrophoneSettings { + enabled: true, + device_id: "cancelled".into(), + volume: 1.0, + }) + .await + }) + }; + cancel_opened.await?; + control.cancel_microphone().await?; + cancelled_joined.await?; + assert_eq!( + changing.await?.unwrap_err().to_string(), + "capture_cancelled" + ); + assert!(!again_control.is_stopped()); + assert!(control.microphone.borrow().enabled); + assert_eq!(control.microphone.borrow().device_id, "again"); + assert_eq!(*control.source.borrow(), Some(resumed.source.id)); + let changing = { + let control = control.clone(); + tokio::spawn(async move { + control + .configure_microphone(SourceMicrophoneSettings { + enabled: true, + device_id: "pending".into(), + volume: 1.0, + }) + .await + }) + }; + opened.await?; + control.stop(); + task.await?; + again_joined.await?; + candidate_joined.await?; + assert!(changing.await?.is_err()); + assert_eq!(*control.source.borrow(), Some(resumed.source.id)); + assert!(!control.microphone.borrow().enabled); + assert!(ended.try_recv().is_err()); // whole-producer stop owns its source cleanup + Ok::<_, anyhow::Error>(()) + }) + .await? + } +} diff --git a/prototype/channel-native/src/peer.rs b/prototype/channel-native/src/peer.rs index 4ebd7c42d..193290136 100644 --- a/prototype/channel-native/src/peer.rs +++ b/prototype/channel-native/src/peer.rs @@ -61,6 +61,32 @@ impl SourceAudioSettings { } } +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceMicrophoneSettings { + pub enabled: bool, + pub device_id: String, + pub volume: f32, +} +impl Default for SourceMicrophoneSettings { + fn default() -> Self { + Self { + enabled: false, + device_id: String::new(), + volume: 1.0, + } + } +} +impl SourceMicrophoneSettings { + pub fn validate(&self) -> Result<()> { + anyhow::ensure!( + self.volume.is_finite() && (0.0..=2.0).contains(&self.volume), + "invalid_microphone_settings" + ); + Ok(()) + } +} + #[derive(Clone, Debug, Default, serde::Deserialize)] pub struct IceServer { pub urls: Vec, @@ -136,6 +162,46 @@ struct Capture { pending_audio: Option, } impl CaptureLease { + pub fn microphone_state(&self) -> Option> { + #[cfg(feature = "capture")] + if let Some(CaptureLeaseControl::Capture(control)) = &self.control { + return Some(control.microphone_state()); + } + None + } + pub fn configure_microphone( + &self, + settings: SourceMicrophoneSettings, + ) -> Result> + Send + 'static> { + settings.validate()?; + anyhow::ensure!(!self.is_stopped(), "capture_unavailable"); + #[cfg(feature = "capture")] + let control = match self.control.as_ref() { + Some(CaptureLeaseControl::Capture(control)) => control.clone(), + _ => anyhow::bail!("capture_unavailable"), + }; + Ok(async move { + #[cfg(feature = "capture")] + return control.configure_microphone(settings).await; + #[cfg(not(feature = "capture"))] + anyhow::bail!("capture_unavailable") + }) + } + pub fn cancel_microphone( + &self, + ) -> Result> + Send + 'static> { + #[cfg(feature = "capture")] + let control = match self.control.as_ref() { + Some(CaptureLeaseControl::Capture(control)) => control.clone(), + _ => anyhow::bail!("capture_unavailable"), + }; + Ok(async move { + #[cfg(feature = "capture")] + return control.cancel_microphone().await; + #[cfg(not(feature = "capture"))] + anyhow::bail!("capture_unavailable") + }) + } pub fn configure_video( &self, settings: crate::capture::Settings, @@ -1060,25 +1126,10 @@ impl Driver { }) .map(|(id, _)| *id) { - let old = self.captures[&video].producer.audio; - if let Some(old) = old { - self.sources.remove(&old); - self.relay.remove(old); - self.refresh_media(false).await?; - } let capture = self.captures.get_mut(&video).unwrap(); let (control, ready, audio_error) = capture .producer - .prepare_audio( - publication, - target, - audio, - exclude_audio, - self.ready_sources.clone(), - self.events.clone(), - self.relay.clone(), - self.cancel.clone(), - ) + .prepare_audio(target, audio, exclude_audio) .await?; let id = Uuid::new_v4(); capture.pending_audio = Some(id); @@ -1101,11 +1152,7 @@ impl Driver { .values_mut() .filter(|capture| capture.selected && capture.scope.publication_id == publication) { - if let Some(audio) = capture.producer.audio { - self.sources.remove(&audio); - self.relay.remove(audio); - } - capture.producer.stop_audio().await; + capture.producer.stop_system_audio().await; } self.refresh_media(false).await?; } @@ -1120,7 +1167,8 @@ impl Driver { self.relay.clone(), self.cancel.clone(), self.bandwidth_changed.clone(), - )?; + ) + .await?; let id = producer.video; let lease = CaptureLease { id, @@ -1204,7 +1252,7 @@ impl Driver { capture.producer.control.stop(); self.sources.remove(old); self.relay.remove(*old); - if let Some(audio) = capture.producer.audio { + if let Some(audio) = capture.producer.audio() { self.sources.remove(&audio); self.relay.remove(audio); } @@ -1246,7 +1294,7 @@ impl Driver { if capture.selected { self.inputs.end_source(publication); } - let audio = capture.producer.audio; + let audio = capture.producer.audio(); let error = capture.producer.close().await; self.captures.remove(&source_id); self.sources.remove(&source_id); @@ -1276,43 +1324,27 @@ impl Driver { #[cfg(feature = "capture")] async fn capture_audio_ended(&mut self, publication: Uuid, source: Uuid) -> Result<()> { - if let Some(capture) = self + for capture in self .captures .values_mut() - .find(|c| c.scope.publication_id == publication && c.producer.audio == Some(source)) + .filter(|c| c.scope.publication_id == publication) { - capture.producer.audio = None; capture.prepared.retain(|ready| ready.source.id != source); - self.sources.remove(&source); - self.relay.remove(source); - self.refresh_media(false).await?; } - Ok(()) + self.sources.remove(&source); + self.relay.remove(source); + self.refresh_media(false).await } #[cfg(feature = "capture")] async fn cancelled_audio(&mut self) { - let cancelled: Vec<_> = self + for capture in self .captures - .iter() - .filter(|(_, capture)| capture.producer.audio_is_stopped()) - .map(|(video, _)| *video) - .collect(); - let changed = !cancelled.is_empty(); - for video in cancelled { - let capture = self.captures.get_mut(&video).unwrap(); + .values_mut() + .filter(|capture| capture.producer.audio_is_stopped()) + { capture.pending_audio = None; - if let Some(audio) = capture.producer.audio { - capture.prepared.retain(|ready| ready.source.id != audio); - self.sources.remove(&audio); - self.relay.remove(audio); - } - capture.producer.stop_audio().await; - } - if changed { - if let Err(error) = self.refresh_media(false).await { - eprintln!("Native retired audio unavailable: {error}"); - } + capture.producer.stop_system_audio().await; } } @@ -2616,21 +2648,16 @@ impl Driver { #[cfg(feature = "capture")] if matches!(ready.source.origin, SourceOrigin::Local) { let Some(capture) = self.captures.values_mut().find(|c| { - c.producer.video == ready.source.id || c.producer.audio == Some(ready.source.id) + c.producer.video == ready.source.id || c.producer.audio() == Some(ready.source.id) }) else { return Ok(()); }; if capture.producer.control.is_stopped() { return Ok(()); } - if capture.producer.audio == Some(ready.source.id) - && capture.producer.audio_is_stopped() - { - return Ok(()); - } if !capture.selected || (capture.pending_audio.is_some() - && capture.producer.audio == Some(ready.source.id)) + && capture.producer.audio() == Some(ready.source.id)) { capture.prepared.push(ready); return Ok(()); @@ -2679,7 +2706,7 @@ impl Driver { let active = self.captures.values().any(|c| { c.selected && !c.producer.control.is_stopped() - && (c.producer.video == source.id || c.producer.audio == Some(source.id)) + && (c.producer.video == source.id || c.producer.audio() == Some(source.id)) }); #[cfg(not(feature = "capture"))] let active = false; diff --git a/prototype/channel-native/src/peer/bandwidth.rs b/prototype/channel-native/src/peer/bandwidth.rs index c44b26681..de7d7703a 100644 --- a/prototype/channel-native/src/peer/bandwidth.rs +++ b/prototype/channel-native/src/peer/bandwidth.rs @@ -148,7 +148,7 @@ impl Driver { capture.selected && !capture.producer.control.is_stopped() && (capture.producer.video == source.id - || capture.producer.audio == Some(source.id)) + || capture.producer.audio() == Some(source.id)) })?; let producer = &capture.producer; if producer.video == source.id { @@ -169,7 +169,7 @@ impl Driver { producer.settings().bitrate }, ) - } else if producer.audio == Some(source.id) { + } else if producer.audio() == Some(source.id) { Some(producer.control.audio_bitrate()) } else { None diff --git a/prototype/channel-server/src/app.rs b/prototype/channel-server/src/app.rs index 15f563c8e..8c57b43c5 100644 --- a/prototype/channel-server/src/app.rs +++ b/prototype/channel-server/src/app.rs @@ -30,7 +30,7 @@ use piik_channel_core::RoomState; use piik_channel_native::{ capture::{Settings, Target}, input::{Desktop, Mode, SourceView}, - peer::{CaptureLease, SourceAudioSettings}, + peer::{CaptureLease, SourceAudioSettings, SourceMicrophoneSettings}, session::{ self, CommitCapture, HostCommand, Hosting, OpenRoom, PauseCapture, PrepareCapture, TransferSource, @@ -632,6 +632,7 @@ enum Operation { policy: String, }, Targets, + Microphones, Preview { target: Target, }, @@ -659,6 +660,12 @@ enum Operation { capture_id: Uuid, settings: SourceAudioSettings, }, + CaptureMicrophone { + publication_id: Uuid, + capture_id: Uuid, + room_id: String, + settings: SourceMicrophoneSettings, + }, CaptureVideoSettings { publication_id: Uuid, capture_id: Uuid, @@ -750,6 +757,7 @@ async fn connection( > = FuturesUnordered::new(); let mut audio_errors = FuturesUnordered::new(); let mut input_states = FuturesUnordered::new(); + let mut microphone_states = FuturesUnordered::new(); let mut operations = FuturesUnordered::new(); let mut previews = FuturesUnordered::new(); let mut preview: Option<(String, Option>)> = None; @@ -784,6 +792,15 @@ async fn connection( } continue; } + Some((publication_id, producer_id, changed, state)) = microphone_states.next(), if !microphone_states.is_empty() => { + let state: Option = state; + if let Some(state) = state.filter(|_| captures.get(&publication_id).and_then(Capture::lease).is_some_and(|lease| lease.producer_id() == producer_id)) { + let event = json!({"type":"capture_microphone_state","publicationId":publication_id,"state":state}); + timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; + microphone_states.push(next_microphone_state(publication_id, producer_id, changed)); + } + continue; + } Some(response) = operations.next(), if !operations.is_empty() => { let response: Value = response; timeout(IO_TIMEOUT, writer.send(Message::Text(response.to_string().into()))).await??; @@ -803,6 +820,7 @@ async fn connection( let request: AbortHandle = request; let result: Result = result; let mut initial_input = None; + let mut initial_microphone = None; let result = if request.is_aborted() { // Stop already retired this request, including a completed // future that had not yet been observed by the processor. @@ -829,6 +847,10 @@ async fn connection( initial_input = Some(state.borrow().clone()); if !retained { input_states.push(next_input_state(publication_id, lease.producer_id(), state.clone())); } } + if let Some(state) = lease.microphone_state() { + initial_microphone = Some(state.borrow().clone()); + if !retained { microphone_states.push(next_microphone_state(publication_id, lease.producer_id(), state)); } + } capture.pending = None; capture.active = Some(lease); Ok(Value::Null) @@ -850,6 +872,10 @@ async fn connection( let event = json!({"type":"input_state","publicationId":publication_id,"state":state}); timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; } + if let Some(state) = initial_microphone { + let event = json!({"type":"capture_microphone_state","publicationId":publication_id,"state":state}); + timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; + } continue; } }; @@ -893,6 +919,17 @@ async fn connection( Some(_) => capture_targets().await, None => Err(anyhow!("hello_required")), }, + Operation::Microphones => match &host { + Some(_) => { + tokio::task::spawn_blocking(|| { + Ok(serde_json::to_value( + piik_channel_native::capture::microphones()?, + )?) + }) + .await? + } + None => Err(anyhow!("hello_required")), + }, Operation::Preview { target } => { if host.is_none() { Err(anyhow!("hello_required")) @@ -1016,10 +1053,24 @@ async fn connection( } } Operation::CancelCapture { publication_id } => { - if let Some(capture) = captures.get_mut(&publication_id) { - capture.pending = None; + let cancel = + captures.get_mut(&publication_id).and_then(|capture| { + capture.pending = None; + capture.lease().map(CaptureLease::cancel_microphone) + }); + match cancel { + Some(Ok(cancel)) => { + operations.push(async move { + match cancel.await { + Ok(()) => json!({"id":request.id,"result":null}), + Err(error) => json!({"id":request.id,"error":error.to_string()}), + } + }.boxed()); + continue; + } + Some(Err(error)) => Err(error), + None => Ok(Value::Null), } - Ok(Value::Null) } Operation::TransferSource { publication_id, @@ -1085,6 +1136,40 @@ async fn connection( Err(error) => Err(error), } } + Operation::CaptureMicrophone { + publication_id, + capture_id, + room_id, + settings, + } => { + let update = captures + .get(&publication_id) + .and_then(Capture::lease) + .filter(|lease| { + lease.id == capture_id && lease.scope.room_id == room_id + }) + .ok_or_else(|| anyhow!("capture_unavailable")) + .and_then(|lease| { + Ok(( + lease.configure_microphone(settings)?, + lease + .microphone_state() + .ok_or_else(|| anyhow!("capture_unavailable"))?, + )) + }); + match update { + Ok((update, state)) => { + operations.push(async move { + match update.await { + Ok(()) => json!({"id":request.id,"result":state.borrow().clone()}), + Err(error) => json!({"id":request.id,"error":error.to_string()}), + } + }.boxed()); + continue; + } + Err(error) => Err(error), + } + } Operation::CapturePaused { publication_id, capture_id, @@ -1222,6 +1307,23 @@ async fn next_input_state( .map(|_| changed.borrow_and_update().clone()); (publication, producer, changed, state) } +async fn next_microphone_state( + publication: Uuid, + producer: Uuid, + mut changed: watch::Receiver, +) -> ( + Uuid, + Uuid, + watch::Receiver, + Option, +) { + let state = changed + .changed() + .await + .ok() + .map(|_| changed.borrow_and_update().clone()); + (publication, producer, changed, state) +} async fn open(commands: &mpsc::Sender, policy: &str) -> Result { let policy: RoomState = serde_json::from_str(policy)?; let (result, opened) = oneshot::channel(); diff --git a/src/client/channel/app-link.ts b/src/client/channel/app-link.ts index 0b8da4afa..db3377225 100644 --- a/src/client/channel/app-link.ts +++ b/src/client/channel/app-link.ts @@ -6,6 +6,7 @@ import { remoteShortcutKeySchema, type RemoteControlMode } from "../remote-contr import type { QualityProfile } from "../media/quality"; import { activateNativePicker } from "../native/activation"; import { NativeRoomHosting } from "./hosting-api"; +import type { CaptureDevice } from "../media/capture-devices"; const identitySchema = z.object({ service: z.literal("piik-channel-app"), protocol: z.number().int().positive(), port: z.number().int().min(1).max(65535) }); const healthSchema = identitySchema.extend({ protocol: z.literal(1), token: z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/) }); @@ -19,6 +20,9 @@ export type PreparedNativeCapture = z.infer; const previewSchema = z.string().max(23 + 4 * Math.ceil(64 * 1024 / 3)) .regex(/^data:image\/jpeg;base64,[A-Za-z0-9+/]+={0,2}$/).nullable(); const captureAudioFailureSchema = z.object({ type: z.literal("capture_audio_failed"), publicationId: z.uuid() }).strict(); +const microphoneSchema = z.object({ enabled: z.boolean(), deviceId: z.string(), volume: z.number().min(0).max(2) }).strict(); +export type NativeSourceMicrophone = z.infer; +const microphoneStateSchema = z.object({ type: z.literal("capture_microphone_state"), publicationId: z.uuid(), state: microphoneSchema }).strict(); const inputControlStateSchema = remoteControlStateSchema.extend({ canSetStopShortcut: z.boolean(), stopShortcut: remoteShortcutKeySchema.nullable().optional(), // Omitted: fixed chord. Null: system-managed, unbound. Text: actual OS chord. @@ -62,6 +66,7 @@ export class ChannelApp { private timer: ReturnType; private authenticated = false; private captures = new Map(); + private microphones = new Map(); private prepared = new Set(); private activationURL?: string; private processAudioExclusion = false; @@ -74,7 +79,9 @@ export class ChannelApp { captureRequest(roomId: string): NativeCaptureRequest | undefined { if (!this.activationURL) return; for (const { command } of this.requests.values()) { - if (command.type === "prepare_capture" && command.roomId === roomId && command.publicationId && this.prepared.has(command.publicationId)) { + if (command.roomId === roomId && command.publicationId && + ((command.type === "prepare_capture" && this.prepared.has(command.publicationId)) || + (command.type === "capture_microphone" && this.captures.has(command.publicationId)))) { return { publicationId: command.publicationId, activationURL: this.activationURL }; } } @@ -82,7 +89,8 @@ export class ChannelApp { constructor(health: AppHealth, channelId: string, userId: string, credential: string, name: string, onClose: () => void, onAudioFailure: (publicationId: string) => void, - onInputState: (publicationId: string, state: ChannelRemoteControlState) => void = () => {}) { + onInputState: (publicationId: string, state: ChannelRemoteControlState) => void = () => {}, + private readonly onMicrophoneState: (publicationId: string) => void = () => {}) { this.roomHosting = new NativeRoomHosting(`http://127.0.0.1:${health.port}/rooms/${channelId}/${userId}`, { Authorization: `Bearer ${health.token}`, "X-Piik-Credential": credential }); const socket = this.socket = new WebSocket(`ws://127.0.0.1:${health.port}/rooms`, `piik-channel-rooms.${health.token}`); @@ -111,6 +119,14 @@ export class ChannelApp { if (this.captures.has(publicationId) || this.prepared.has(publicationId)) onAudioFailure(publicationId); return; } + if (reply.type === "capture_microphone_state") { + const { publicationId, state } = microphoneStateSchema.parse(reply); + if (this.captures.has(publicationId) || this.prepared.has(publicationId)) { + this.microphones.set(publicationId, state); + onMicrophoneState(publicationId); + } + return; + } const request = this.requests.get(reply.id); if (!request) return; this.requests.delete(reply.id); @@ -192,6 +208,26 @@ export class ChannelApp { if (this.captures.get(publicationId) !== captureId) throw new DOMException("Capture cancelled", "AbortError"); } + sourceMicrophone(publicationId: string): NativeSourceMicrophone | undefined { + return this.captures.has(publicationId) ? this.microphones.get(publicationId) : undefined; + } + + async sourceMicrophones(): Promise { + await this.ready; + return z.array(z.object({ id: z.string(), label: z.string() }).strict()).parse(await this.request({ type: "microphones" })); + } + + async setSourceMicrophone(publicationId: string, roomId: string, settings: NativeSourceMicrophone): Promise { + const captureId = this.captures.get(publicationId); + if (!captureId) throw new Error("capture_unavailable"); + const pending = this.request({ type: "capture_microphone", publicationId, captureId, roomId, settings }); + if (settings.enabled && !this.sourceMicrophone(publicationId)?.enabled) activateNativePicker(this.activationURL); + const applied = microphoneSchema.parse(await pending); + if (this.captures.get(publicationId) !== captureId) throw new DOMException("Capture cancelled", "AbortError"); + this.microphones.set(publicationId, applied); + this.onMicrophoneState(publicationId); + } + async setCapturePaused(publicationId: string, paused: boolean): Promise { const captureId = this.captures.get(publicationId); if (!captureId) throw new Error("capture_unavailable"); @@ -221,12 +257,15 @@ export class ChannelApp { } async cancelCapture(publicationId: string): Promise { - if (!this.prepared.delete(publicationId)) return; + const prepared = this.prepared.delete(publicationId); + const microphone = [...this.requests.values()].some(({ command }) => command.type === "capture_microphone" && command.publicationId === publicationId); + if (!prepared && !microphone) return; if (this.connected) await this.request({ type: "cancel_capture", publicationId }); } async stopCapture(publicationId: string): Promise { const active = this.captures.delete(publicationId); + this.microphones.delete(publicationId); const prepared = this.prepared.delete(publicationId); if (!active && !prepared) return; if (this.connected) await this.request({ type: "stop_capture", publicationId }); @@ -259,6 +298,7 @@ export class ChannelApp { close(): void { this.authenticated = false; this.captures.clear(); + this.microphones.clear(); this.prepared.clear(); clearTimeout(this.timer); this.socket.onclose = null;