| 1 | /* |
| 2 | * Copyright 2026 LiveKit, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #pragma once |
| 18 | |
| 19 | #include <optional> |
| 20 | #include <utility> |
| 21 | #include <variant> |
| 22 | |
| 23 | #include "api/environment/environment.h" |
| 24 | #include "api/scoped_refptr.h" |
| 25 | #include "api/sequence_checker.h" |
| 26 | #include "livekit/synthetic_audio_device.h" |
| 27 | #include "modules/audio_device/include/audio_device.h" |
| 28 | #include "modules/audio_device/include/audio_device_defines.h" |
| 29 | #include "rtc_base/thread.h" |
| 30 | #include "rtc_base/thread_annotations.h" |
| 31 | |
| 32 | namespace livekit_ffi { |
| 33 | |
| 34 | /// ADM Proxy that manages synthetic and platform audio modes. |
| 35 | /// |
| 36 | /// This proxy implements the AudioDeviceModule interface and switches between: |
| 37 | /// 1. **Synthetic mode**: Uses `SyntheticAudioDevice`, which pumps the WebRTC |
| 38 | /// audio pipeline without platform audio. Remote audio is delivered via FFI |
| 39 | /// callbacks to external audio systems (e.g., Unity AudioSource). |
| 40 | /// 2. **Platform mode**: Real audio I/O through the Platform ADM with microphone |
| 41 | /// capture and speaker playout. Used when PlatformAudio is active for VoIP |
| 42 | /// with AEC. |
| 43 | /// |
| 44 | /// ## Threading Model |
| 45 | /// |
| 46 | /// The proxy is worker-thread-affine. Every public method marshals once at the |
| 47 | /// boundary onto the WebRTC worker thread via `RunOnWorker` and runs inline |
| 48 | /// when the caller is already on the worker, which is the case for all calls |
| 49 | /// originating from WebRTC internals (AudioState, the voice engine). All |
| 50 | /// mutable state, including both sub ADMs, is owned by the worker thread, so |
| 51 | /// no locks are needed and mode transitions execute as plain sequential code. |
| 52 | /// |
| 53 | /// This also satisfies the platform ADM threading contract: platform |
| 54 | /// implementations bind a sequence checker to their construction thread and |
| 55 | /// expect every control call on it. The platform ADM is created lazily on |
| 56 | /// first acquire, inside the worker-marshaled acquire path, so it binds to |
| 57 | /// the worker thread just like an eagerly constructed one would. The proxy |
| 58 | /// itself must be constructed on the worker thread so the synthetic ADM |
| 59 | /// binds to it as well. |
| 60 | /// Destruction may happen on any thread, teardown hops to the worker. |
| 61 | /// |
| 62 | /// Note for future extensions: platform ADM observer callbacks must not call |
| 63 | /// synchronously back into AudioDeviceController, as that would block the |
| 64 | /// observer thread on the worker while the worker may be waiting on it. |
| 65 | /// |
| 66 | /// ## Mode Selection |
| 67 | /// |
| 68 | /// - **Playout**: Uses Platform ADM when `ref_count > 0 && playout_enabled`, |
| 69 | /// otherwise uses synthetic mode (internal audio pumping task). |
| 70 | /// - **Recording**: Uses Platform ADM when `ref_count > 0 && recording_enabled`, |
| 71 | /// otherwise recording is unavailable (synthetic mode has no microphone). |
| 72 | /// |
| 73 | /// ## Lifecycle Management |
| 74 | /// |
| 75 | /// Platform ADM is created lazily on the first `AcquirePlatformAdm()` call, |
| 76 | /// so apps that never use PlatformAudio never construct it. Once created it |
| 77 | /// stays alive until the proxy is destroyed (re-creation caused iOS KVO |
| 78 | /// races). Reference counting controls which mode is active: |
| 79 | /// - `AcquirePlatformAdm()`: Increments ref count |
| 80 | /// - `ReleasePlatformAdm()`: Decrements ref count |
| 81 | /// - When ref_count is 0, playout uses synthetic mode |
| 82 | /// |
| 83 | /// ## Audio Modes |
| 84 | /// |
| 85 | /// | Mode | Recording | Playout | Use Case | |
| 86 | /// |------|-----------|---------|----------| |
| 87 | /// | Synthetic | NativeAudioSource | Internal task + FFI | Unity audio, agents | |
| 88 | /// | Platform | Platform ADM mic | Platform ADM speakers | VoIP with AEC | |
| 89 | /// |
| 90 | class AdmProxy : public webrtc::AudioDeviceModule { |
| 91 | public: |
| 92 | /// Must be constructed on the worker thread. |
| 93 | explicit AdmProxy(const webrtc::Environment& env, |
| 94 | webrtc::Thread* worker_thread); |
| 95 | ~AdmProxy() override; |
| 96 | |
| 97 | // =========================================================================== |
| 98 | // Platform ADM Lifecycle Management |
| 99 | // =========================================================================== |
| 100 | |
| 101 | /// Acquires a reference to the Platform ADM. |
| 102 | /// |
| 103 | /// On first call, creates and initializes the Platform ADM. On subsequent |
| 104 | /// calls, just increments the reference count. |
| 105 | /// |
| 106 | /// @return true if Platform ADM is ready for use, false if initialization failed. |
| 107 | bool AcquirePlatformAdm(); |
| 108 | |
| 109 | /// Releases a reference to the Platform ADM. |
| 110 | /// |
| 111 | /// When the reference count reaches zero, the proxy returns to synthetic |
| 112 | /// mode. The Platform ADM instance stays alive until destruction. |
| 113 | void ReleasePlatformAdm(); |
| 114 | |
| 115 | /// Returns the current reference count for the Platform ADM. |
| 116 | int platform_adm_ref_count() const; |
| 117 | |
| 118 | /// Returns true if Platform ADM is currently active (ref_count > 0). |
| 119 | bool is_platform_adm_active() const; |
| 120 | |
| 121 | // =========================================================================== |
| 122 | // Recording/Playout Control |
| 123 | // =========================================================================== |
| 124 | |
| 125 | /// Control whether recording (microphone) is enabled. |
| 126 | /// |
| 127 | /// When disabled (default), InitRecording/StartRecording return success but |
| 128 | /// do nothing. This allows NativeAudioSource to work without interference. |
| 129 | /// |
| 130 | /// @note Only effective when Platform ADM is active. |
| 131 | void set_recording_enabled(bool enabled); |
| 132 | bool recording_enabled() const; |
| 133 | |
| 134 | /// Control whether playout goes through Platform ADM speakers. |
| 135 | /// |
| 136 | /// When disabled (default), playout uses synthetic mode - remote audio is |
| 137 | /// delivered via FFI callbacks to the application (e.g., Unity AudioSource). |
| 138 | /// |
| 139 | /// When enabled, remote audio plays through the platform speakers with AEC. |
| 140 | /// |
| 141 | /// @note Only effective when Platform ADM is active. |
| 142 | void set_playout_enabled(bool enabled); |
| 143 | bool playout_enabled() const; |
| 144 | |
| 145 | // =========================================================================== |
| 146 | // AudioDeviceModule Interface |
| 147 | // =========================================================================== |
| 148 | |
| 149 | int32_t ActiveAudioLayer(AudioLayer* audioLayer) const override; |
| 150 | int32_t RegisterAudioCallback(webrtc::AudioTransport* transport) override; |
| 151 | |
| 152 | int32_t Init() override; |
| 153 | int32_t Terminate() override; |
| 154 | bool Initialized() const override; |
| 155 | |
| 156 | int16_t PlayoutDevices() override; |
| 157 | int16_t RecordingDevices() override; |
| 158 | int32_t PlayoutDeviceName(uint16_t index, |
| 159 | char name[webrtc::kAdmMaxDeviceNameSize], |
| 160 | char guid[webrtc::kAdmMaxGuidSize]) override; |
| 161 | int32_t RecordingDeviceName(uint16_t index, |
| 162 | char name[webrtc::kAdmMaxDeviceNameSize], |
| 163 | char guid[webrtc::kAdmMaxGuidSize]) override; |
| 164 | |
| 165 | int32_t SetPlayoutDevice(uint16_t index) override; |
| 166 | int32_t SetPlayoutDevice(WindowsDeviceType device) override; |
| 167 | int32_t SetRecordingDevice(uint16_t index) override; |
| 168 | int32_t SetRecordingDevice(WindowsDeviceType device) override; |
| 169 | |
| 170 | int32_t PlayoutIsAvailable(bool* available) override; |
| 171 | int32_t InitPlayout() override; |
| 172 | bool PlayoutIsInitialized() const override; |
| 173 | int32_t RecordingIsAvailable(bool* available) override; |
| 174 | int32_t InitRecording() override; |
| 175 | bool RecordingIsInitialized() const override; |
| 176 | |
| 177 | int32_t StartPlayout() override; |
| 178 | int32_t StopPlayout() override; |
| 179 | bool Playing() const override; |
| 180 | int32_t StartRecording() override; |
| 181 | int32_t StopRecording() override; |
| 182 | bool Recording() const override; |
| 183 | |
| 184 | int32_t InitSpeaker() override; |
| 185 | bool SpeakerIsInitialized() const override; |
| 186 | int32_t InitMicrophone() override; |
| 187 | bool MicrophoneIsInitialized() const override; |
| 188 | |
| 189 | int32_t SpeakerVolumeIsAvailable(bool* available) override; |
| 190 | int32_t SetSpeakerVolume(uint32_t volume) override; |
| 191 | int32_t SpeakerVolume(uint32_t* volume) const override; |
| 192 | int32_t MaxSpeakerVolume(uint32_t* maxVolume) const override; |
| 193 | int32_t MinSpeakerVolume(uint32_t* minVolume) const override; |
| 194 | |
| 195 | int32_t MicrophoneVolumeIsAvailable(bool* available) override; |
| 196 | int32_t SetMicrophoneVolume(uint32_t volume) override; |
| 197 | int32_t MicrophoneVolume(uint32_t* volume) const override; |
| 198 | int32_t MaxMicrophoneVolume(uint32_t* maxVolume) const override; |
| 199 | int32_t MinMicrophoneVolume(uint32_t* minVolume) const override; |
| 200 | |
| 201 | int32_t SpeakerMuteIsAvailable(bool* available) override; |
| 202 | int32_t SetSpeakerMute(bool enable) override; |
| 203 | int32_t SpeakerMute(bool* enabled) const override; |
| 204 | |
| 205 | int32_t MicrophoneMuteIsAvailable(bool* available) override; |
| 206 | int32_t SetMicrophoneMute(bool enable) override; |
| 207 | int32_t MicrophoneMute(bool* enabled) const override; |
| 208 | |
| 209 | int32_t StereoPlayoutIsAvailable(bool* available) const override; |
| 210 | int32_t SetStereoPlayout(bool enable) override; |
| 211 | int32_t StereoPlayout(bool* enabled) const override; |
| 212 | int32_t StereoRecordingIsAvailable(bool* available) const override; |
| 213 | int32_t SetStereoRecording(bool enable) override; |
| 214 | int32_t StereoRecording(bool* enabled) const override; |
| 215 | |
| 216 | int32_t PlayoutDelay(uint16_t* delayMS) const override; |
| 217 | |
| 218 | bool BuiltInAECIsAvailable() const override; |
| 219 | bool BuiltInAGCIsAvailable() const override; |
| 220 | bool BuiltInNSIsAvailable() const override; |
| 221 | |
| 222 | int32_t EnableBuiltInAEC(bool enable) override; |
| 223 | int32_t EnableBuiltInAGC(bool enable) override; |
| 224 | int32_t EnableBuiltInNS(bool enable) override; |
| 225 | |
| 226 | #if defined(WEBRTC_IOS) |
| 227 | int GetPlayoutAudioParameters(webrtc::AudioParameters* params) const override; |
| 228 | int GetRecordAudioParameters(webrtc::AudioParameters* params) const override; |
| 229 | #endif |
| 230 | |
| 231 | int32_t SetObserver(webrtc::AudioDeviceObserver* observer) override; |
| 232 | |
| 233 | private: |
| 234 | // Runs fn on the worker thread, inline when already on it. |
| 235 | template <typename Fn> |
| 236 | auto RunOnWorker(Fn&& fn) const { |
| 237 | if (worker_thread_->IsCurrent()) { |
| 238 | return fn(); |
| 239 | } |
| 240 | return worker_thread_->BlockingCall(std::forward<Fn>(fn)); |
| 241 | } |
| 242 | |
| 243 | // Forwards a call to the platform ADM on the worker thread. |
| 244 | // Returns default_value when no platform ADM is available. |
| 245 | template <typename R, typename Fn> |
| 246 | R WithPlatformAdm(R default_value, Fn&& fn) const { |
| 247 | return RunOnWorker([&]() -> R { |
| 248 | RTC_DCHECK_RUN_ON(worker_thread_); |
| 249 | if (!platform_adm_) { |
| 250 | return default_value; |
| 251 | } |
| 252 | return fn(*platform_adm_); |
| 253 | }); |
| 254 | } |
| 255 | |
| 256 | // Returns true if platform mode is active for playout |
| 257 | // (ref_count > 0 && playout_enabled) |
| 258 | bool IsPlatformPlayoutActive() const RTC_RUN_ON(worker_thread_); |
| 259 | |
| 260 | // Returns the ADM to use for recording operations. |
| 261 | // Platform ADM when recording is enabled (ref_count > 0 && recording_enabled), |
| 262 | // nullptr otherwise (recording not available in synthetic mode). |
| 263 | webrtc::AudioDeviceModule* RecordingAdm() const RTC_RUN_ON(worker_thread_); |
| 264 | |
| 265 | // Switches playout between synthetic and platform mode based on current |
| 266 | // state. Called when ref_count or playout_enabled changes. |
| 267 | // If playout is active, stops the old mode and starts the new one. |
| 268 | void SwitchPlayoutMode() RTC_RUN_ON(worker_thread_); |
| 269 | |
| 270 | // Switches recording to the correct ADM based on current state. |
| 271 | // Called when ref_count or recording_enabled changes. |
| 272 | // If recording is active, stops the old ADM and starts the new one. |
| 273 | void SwitchRecordingAdm() RTC_RUN_ON(worker_thread_); |
| 274 | |
| 275 | // Lazily creates and initializes the Platform ADM on first acquire, then |
| 276 | // replays cached state (audio transport, device selection, channel config) |
| 277 | // onto it. Runs on the worker thread so the fresh ADM binds its sequence |
| 278 | // checker there. Returns true if the ADM is available after the call. |
| 279 | bool EnsurePlatformAdmCreated() RTC_RUN_ON(worker_thread_); |
| 280 | bool InitPlatformAdm() RTC_RUN_ON(worker_thread_); |
| 281 | |
| 282 | const webrtc::Environment env_; |
| 283 | webrtc::Thread* const worker_thread_; |
| 284 | |
| 285 | // All mutable state below is owned by the worker thread. |
| 286 | |
| 287 | // Synthetic ADM for synthetic mode - pumps the WebRTC audio pipeline without |
| 288 | // platform audio via SyntheticAudioDevice's internal task. |
| 289 | webrtc::scoped_refptr<SyntheticAudioDevice> synthetic_adm_ |
| 290 | RTC_GUARDED_BY(worker_thread_); |
| 291 | |
| 292 | // Platform ADM for real audio I/O (microphone capture, speaker playout with AEC) |
| 293 | webrtc::scoped_refptr<webrtc::AudioDeviceModule> platform_adm_ |
| 294 | RTC_GUARDED_BY(worker_thread_); |
| 295 | |
| 296 | // Reference count for Platform ADM users (PlatformAudio instances) |
| 297 | int platform_adm_ref_count_ RTC_GUARDED_BY(worker_thread_) = 0; |
| 298 | |
| 299 | // Audio transport callback (registered by WebRTC) |
| 300 | webrtc::AudioTransport* audio_transport_ RTC_GUARDED_BY(worker_thread_) = |
| 301 | nullptr; |
| 302 | |
| 303 | // State tracking |
| 304 | bool playing_ RTC_GUARDED_BY(worker_thread_) = false; |
| 305 | bool recording_ RTC_GUARDED_BY(worker_thread_) = false; |
| 306 | |
| 307 | // Control flags |
| 308 | // When false (default), recording operations are no-ops (NativeAudioSource mode) |
| 309 | bool recording_enabled_ RTC_GUARDED_BY(worker_thread_) = false; |
| 310 | // When false (default), playout uses synthetic mode (internal task pumps audio) |
| 311 | bool playout_enabled_ RTC_GUARDED_BY(worker_thread_) = false; |
| 312 | |
| 313 | // Device selection made before the Platform ADM exists (it is created |
| 314 | // lazily on first acquire), re-applied once it is created. Holds either a |
| 315 | // numeric index or a Windows default device type, matching the two |
| 316 | // SetPlayoutDevice/SetRecordingDevice overloads, so an explicit index 0 |
| 317 | // and a Windows default device type both survive the replay. |
| 318 | using DeviceSelection = std::variant<uint16_t, WindowsDeviceType>; |
| 319 | static WindowsDeviceType SystemDefaultFor(WindowsDeviceType requested); |
| 320 | std::optional<DeviceSelection> selected_playout_device_ |
| 321 | RTC_GUARDED_BY(worker_thread_); |
| 322 | std::optional<DeviceSelection> selected_recording_device_ |
| 323 | RTC_GUARDED_BY(worker_thread_); |
| 324 | |
| 325 | // Observer registered before the Platform ADM exists, stored for the same |
| 326 | // replay-on-creation reason as the device selection. |
| 327 | webrtc::AudioDeviceObserver* audio_observer_ RTC_GUARDED_BY(worker_thread_) = |
| 328 | nullptr; |
| 329 | |
| 330 | // Channel configuration requested by the voice engine at factory init, |
| 331 | // stored for the same replay-on-creation reason as the device indices. |
| 332 | std::optional<bool> selected_stereo_playout_ RTC_GUARDED_BY(worker_thread_); |
| 333 | std::optional<bool> selected_stereo_recording_ |
| 334 | RTC_GUARDED_BY(worker_thread_); |
| 335 | }; |
| 336 | |
| 337 | } // namespace livekit_ffi |