/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamvideo.reactnative.audio import android.app.Activity import android.content.Context import android.media.AudioDeviceCallback import android.media.AudioDeviceInfo import android.media.AudioManager import android.os.Build import android.util.Log import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.WritableMap import com.facebook.react.modules.core.DeviceEventManagerModule import com.streamvideo.reactnative.audio.utils.AudioDeviceEndpointUtils import com.streamvideo.reactnative.audio.utils.AudioFocusUtil import com.streamvideo.reactnative.audio.utils.AudioManagerUtil import com.streamvideo.reactnative.audio.utils.AudioManagerUtil.Companion.getAvailableAudioDevices import com.streamvideo.reactnative.audio.utils.CallAudioRole import com.streamvideo.reactnative.callmanager.ProximityManager import com.streamvideo.reactnative.callmanager.StreamInCallManagerModule import com.streamvideo.reactnative.model.AudioDeviceEndpoint import com.streamvideo.reactnative.model.AudioDeviceEndpoint.Companion.EndpointType import java.util.concurrent.ExecutorService import java.util.concurrent.Executors data class EndpointMaps( // earpiece, speaker, unknown, wired_headset val bluetoothEndpoints: HashMap, // all bt endpoints val nonBluetoothEndpoints: HashMap<@EndpointType Int, AudioDeviceEndpoint> ) class AudioDeviceManager( private val mReactContext: ReactApplicationContext ) : AutoCloseable, AudioDeviceCallback(), AudioManager.OnAudioFocusChangeListener { private val mEndpointMaps by lazy { val initialAudioDevices = getAvailableAudioDevices(mAudioManager) val initialEndpoints = AudioDeviceEndpointUtils.getEndpointsFromAudioDeviceInfo(initialAudioDevices) val bluetoothEndpoints = HashMap() val nonBluetoothEndpoints = HashMap<@EndpointType Int, AudioDeviceEndpoint>() for (device in initialEndpoints) { if (device.isBluetoothType()) { bluetoothEndpoints[device.deviceId.toString()] = device } else { nonBluetoothEndpoints[device.type] = device } } EndpointMaps(bluetoothEndpoints, nonBluetoothEndpoints) } private var cachedAvailableEndpointIdsSet = setOf() /** Returns the currently selected audio device. */ private var _selectedAudioDeviceEndpoint: AudioDeviceEndpoint? = null var selectedAudioDeviceEndpoint: AudioDeviceEndpoint? get() = _selectedAudioDeviceEndpoint set(value) { _selectedAudioDeviceEndpoint = value // send an event to the frontend everytime this endpoint changes sendAudioStatusEvent() if (callAudioRole == CallAudioRole.Communicator) { proximityManager.update() } } // Default audio device; speaker phone for video calls or earpiece for audio only phone calls @EndpointType var defaultAudioDevice = AudioDeviceEndpoint.TYPE_SPEAKER var enableStereo: Boolean = false private val mAudioManager = mReactContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager /** * Indicator that we have lost audio focus. */ private var audioFocusLost = false private var audioFocusUtil = AudioFocusUtil(mAudioManager, this) var callAudioRole: CallAudioRole = CallAudioRole.Communicator /** * When true, the call is managed by the Android Telecom stack (via callingx). * Telecom owns audio focus, audio mode and device routing, so we must NOT use * AudioManager.setCommunicationDevice / startBluetoothSco / audio-focus APIs here. * We keep owning proximity, keep-screen-on and mic/output mute. */ var telecomManagedMode: Boolean = false /** * Opt-out for the Android 11+ communication-mode keep-alive. Sticky developer preference — * intentionally NOT reset in [stop], unlike the per-call fields above. */ var disableCommunicationModeWorkaround: Boolean = false /** * True once [stop]/[close] have torn routing down, until the next [start]. * * [updateAudioDeviceState] is enqueued from off-thread sources (Bluetooth receivers, * audio-focus and device callbacks), so a task can still land after teardown. Re-routing * then would re-assert MODE_IN_COMMUNICATION via AudioManagerUtil, undoing the * MODE_NORMAL restore in [stop]. Audio-thread confined. */ private var routingStopped = false /** Keeps MODE_IN_COMMUNICATION owned for the whole Communicator call on Android 11+. */ private val communicationModeKeepAlive: CommunicationModeKeepAlive = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { SilentPlaybackKeepAlive(mReactContext) } else { NoCommunicationModeKeepAlive } val bluetoothManager = BluetoothManager(mReactContext, this) private val proximityManager by lazy { ProximityManager(mReactContext, this) } init { // Note that we will immediately receive a call to onDevicesAdded with the list of // devices which are currently connected. mAudioManager.registerAudioDeviceCallback(this, null) } private fun setup() { if (!telecomManagedMode) { if (callAudioRole == CallAudioRole.Communicator) { mAudioManager.mode = AudioManager.MODE_IN_COMMUNICATION } else { // Audio routing is handled automatically by the system in normal media mode // and bluetooth microphones may not work on some devices. mAudioManager.mode = AudioManager.MODE_NORMAL } } audioFocusUtil.setup(callAudioRole, mReactContext) } /** Runs inline; callers must already be on the audio thread (see [runInAudioThread]). */ fun start(activity: Activity) { routingStopped = false setup() selectedAudioDeviceEndpoint = null if (callAudioRole == CallAudioRole.Communicator) { // Audio routing is manually controlled by the SDK in communication media mode // and local microphone can be published activity.volumeControlStream = AudioManager.STREAM_VOICE_CALL if (!telecomManagedMode) { // Telecom owns routing/focus; only run our own routing when not Telecom-managed. bluetoothManager.start() mAudioManager.registerAudioDeviceCallback(this, null) updateAudioDeviceState() } proximityManager.start() } else { activity.volumeControlStream = AudioManager.USE_DEFAULT_STREAM_TYPE } if (!telecomManagedMode) { audioFocusUtil.requestFocus(callAudioRole, mReactContext) } // Started last, after focus/routing, so the silent track uses the correct route. if (callAudioRole == CallAudioRole.Communicator && !telecomManagedMode && !disableCommunicationModeWorkaround ) { communicationModeKeepAlive.start() } } /** Runs inline; callers must already be on the audio thread (see [runInAudioThread]). */ fun stop(activity: Activity?) { routingStopped = true communicationModeKeepAlive.stop() if (callAudioRole == CallAudioRole.Communicator) { if (!telecomManagedMode) { // Only tear down what we set up ourselves; Telecom owns its own teardown. if (Build.VERSION.SDK_INT >= 31) { mAudioManager.clearCommunicationDevice() } else { mAudioManager.setSpeakerphoneOn(false) } bluetoothManager.stop() // Restore the mode set in setup(); it was previously left at // MODE_IN_COMMUNICATION, holding the device in in-call routing. mAudioManager.mode = AudioManager.MODE_NORMAL } callAudioRole = CallAudioRole.Communicator enableStereo = false defaultAudioDevice = AudioDeviceEndpoint.TYPE_SPEAKER proximityManager.stop() } activity?.volumeControlStream = AudioManager.USE_DEFAULT_STREAM_TYPE if (!telecomManagedMode) { audioFocusUtil.abandonFocus() } telecomManagedMode = false } fun setMicrophoneMute(enable: Boolean) { if (enable != mAudioManager.isMicrophoneMute) { mAudioManager.isMicrophoneMute = enable } } private fun bluetoothEndpointByName(name: String?): AudioDeviceEndpoint? { if (name == null) return null return mEndpointMaps.bluetoothEndpoints.values.firstOrNull { it.name == name } } /** * Resolves the currently-active Bluetooth endpoint. */ private fun activeBluetoothEndpoint(): AudioDeviceEndpoint? { if (Build.VERSION.SDK_INT >= 31) { mAudioManager.communicationDevice?.id?.toString()?.let { id -> mEndpointMaps.bluetoothEndpoints[id]?.let { return it } } } return bluetoothEndpointByName(bluetoothManager.getDeviceName()) } /** Resolves a non-Bluetooth endpoint by its stable device id. */ private fun nonBluetoothEndpointById(deviceId: String): AudioDeviceEndpoint? { return mEndpointMaps.nonBluetoothEndpoints.values.firstOrNull { it.deviceId.toString() == deviceId } } fun setSpeakerphoneOn(enable: Boolean) { if (enable) { switchDeviceEndpointType(AudioDeviceEndpoint.TYPE_SPEAKER) } else { if (Build.VERSION.SDK_INT >= 31) { mAudioManager.clearCommunicationDevice() // sets the first device that is not speaker getCurrentDeviceEndpoints().firstOrNull { !it.isSpeakerType() }?.also { switchDeviceEndpointType(it.type) } } else { mAudioManager.setSpeakerphoneOn(false) } } } private fun switchDeviceEndpointType(@EndpointType deviceType: Int) { // Sole sink for routing changes, and AudioManagerUtil re-asserts MODE_IN_COMMUNICATION // here — so late work of any origin must not reach it after teardown. if (routingStopped) return val newDevice = AudioManagerUtil.switchDeviceEndpointType( deviceType, mEndpointMaps, mAudioManager, bluetoothManager ) this.selectedAudioDeviceEndpoint = newDevice } /** Runs inline; callers must already be on the audio thread (see [runInAudioThread]). */ fun switchDeviceById( deviceId: String ) { Log.d(TAG, "switchDeviceById: deviceId = $deviceId") // Guarded here too: the branch below sets the communication device directly rather // than going through switchDeviceEndpointType(). if (routingStopped) return val btDevice = mEndpointMaps.bluetoothEndpoints[deviceId] if (btDevice != null) { if (Build.VERSION.SDK_INT >= 31) { mAudioManager.setCommunicationDevice(btDevice.deviceInfo) bluetoothManager.updateDevice() this.selectedAudioDeviceEndpoint = btDevice } else { switchDeviceEndpointType( AudioDeviceEndpoint.TYPE_BLUETOOTH ) } } else { val endpoint = nonBluetoothEndpointById(deviceId) if (endpoint != null) { switchDeviceEndpointType(endpoint.type) } else { Log.e(TAG, "switchDeviceById: no endpoint found for id $deviceId") } } } override fun close() { // Unlike start()/stop(), this is called straight from the module, so it must be queued // to land after any start/stop already pending on the audio thread. runInAudioThread { routingStopped = true communicationModeKeepAlive.release() mAudioManager.unregisterAudioDeviceCallback(this) proximityManager.onDestroy() } } /** Short description of the keep-alive state, for the audio debug log. */ fun communicationModeKeepAliveState(): String = communicationModeKeepAlive.describeState() override fun onAudioDevicesAdded(addedDevices: Array?) { if (addedDevices != null) { runInAudioThread { endpointsAddedUpdate( AudioDeviceEndpointUtils.getEndpointsFromAudioDeviceInfo( addedDevices.toList() ) ) } } } override fun onAudioDevicesRemoved(removedDevices: Array?) { if (removedDevices != null) { runInAudioThread { endpointsRemovedUpdate( AudioDeviceEndpointUtils.getEndpointsFromAudioDeviceInfo( removedDevices.toList() ) ) } } } private fun endpointsAddedUpdate(addedCallEndpoints: List) { // START tracking an endpoint var addedDevicesCount = 0 for (maybeNewEndpoint in addedCallEndpoints) { addedDevicesCount += maybeAddCallEndpoint(maybeNewEndpoint) } if (addedDevicesCount > 0) { updateAudioDeviceState() } } private fun endpointsRemovedUpdate(removedCallEndpoints: List) { // STOP tracking an endpoint var removedDevicesCount = 0 for (maybeRemovedDevice in removedCallEndpoints) { removedDevicesCount += maybeRemoveCallEndpoint(maybeRemovedDevice) } if (removedDevicesCount > 0) { updateAudioDeviceState() } } private fun getCurrentDeviceEndpoints(): List { val endpoints = if (Build.VERSION.SDK_INT >= 31) { (mEndpointMaps.bluetoothEndpoints.values + mEndpointMaps.nonBluetoothEndpoints.values).sorted() } else { val btEndpoint = bluetoothEndpointByName(bluetoothManager.getDeviceName()) if (btEndpoint != null) { val list = mutableListOf(btEndpoint) list.addAll(mEndpointMaps.nonBluetoothEndpoints.values) list.sorted() } else { mEndpointMaps.nonBluetoothEndpoints.values.sorted() } } return maybeRemoveEarpieceIfWiredPresent(endpoints) } /** * When a wired headset is connected the built-in earpiece is not separately * routable — the wired plug physically occupies the receiver path */ private fun maybeRemoveEarpieceIfWiredPresent( endpoints: List ): List { if (endpoints.any { it.isWiredHeadsetType() }) { return endpoints.filterNot { it.type == AudioDeviceEndpoint.TYPE_EARPIECE } } return endpoints } private fun maybeAddCallEndpoint(endpoint: AudioDeviceEndpoint): Int { if (endpoint.isBluetoothType()) { val key = endpoint.deviceId.toString() if (!mEndpointMaps.bluetoothEndpoints.containsKey(key)) { mEndpointMaps.bluetoothEndpoints[key] = endpoint Log.d(TAG, "maybeAddCallEndpoint: bluetooth endpoint added: " + endpoint.name) return 1 } } else { if (!mEndpointMaps.nonBluetoothEndpoints.containsKey(endpoint.type)) { mEndpointMaps.nonBluetoothEndpoints[endpoint.type] = endpoint Log.d(TAG, "maybeAddCallEndpoint: non-bluetooth endpoint added: " + endpoint.name) return 1 } } return 0 } private fun maybeRemoveCallEndpoint(endpoint: AudioDeviceEndpoint): Int { // TODO:: determine if it is necessary to cleanup listeners here if (endpoint.isBluetoothType()) { val key = endpoint.deviceId.toString() if (mEndpointMaps.bluetoothEndpoints.containsKey(key)) { mEndpointMaps.bluetoothEndpoints.remove(key) Log.d(TAG, "maybeRemoveCallEndpoint: bluetooth endpoint removed: " + endpoint.name) return 1 } } else { if (mEndpointMaps.nonBluetoothEndpoints.containsKey(endpoint.type)) { mEndpointMaps.nonBluetoothEndpoints.remove(endpoint.type) Log.d( TAG, "maybeRemoveCallEndpoint: non-bluetooth endpoint removed: " + endpoint.name ) return 1 } } return 0 } fun muteAudioOutput() { mAudioManager.adjustStreamVolume( if (callAudioRole === CallAudioRole.Communicator) AudioManager.STREAM_VOICE_CALL else AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE // Optional: prevents sound/vibration on mute ) } fun unmuteAudioOutput() { mAudioManager.adjustStreamVolume( if (callAudioRole === CallAudioRole.Communicator) AudioManager.STREAM_VOICE_CALL else AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_SHOW_UI ) } /** * Updates the list of available audio devices and selects a new audio device based on priority. * * This function performs the following actions: * 1. Retrieves the current list of available audio device endpoints. * 2. Compares the current list with the cached list to detect changes. * 3. Updates the Bluetooth device state if necessary (especially for older Android platforms). * 4. Determines the new audio device based on the following priority: * - Wired Headset (WH) * - Bluetooth (BT) * - Default audio device (speaker or earpiece) * 5. If a user has manually selected an audio device, that selection takes precedence. * 6. Handles Bluetooth SCO (Synchronous Connection-Oriented) connection: * - If the new device is Bluetooth and a headset is available, it attempts to start SCO audio. * - If SCO connection fails, it reverts the Bluetooth selection and chooses an alternative device. * - If a previous selection was Bluetooth and the new selection is not, it stops SCO audio. * 7. Switches to the new audio device endpoint. * 8. If the selected device or the list of available devices has changed, it sends an audio status event. * * The entire operation is performed on a dedicated audio thread to avoid blocking the main thread. */ fun updateAudioDeviceState() { runInAudioThread { // Bail early: on API < 31 bluetoothState survives stop(), so a late pass could // still start SCO after the call ended. if (routingStopped) return@runInAudioThread if (telecomManagedMode) { // Telecom is the single source of truth for routing/endpoints in this mode. return@runInAudioThread } val audioDevices = getCurrentDeviceEndpoints() // Compare by stable device id, not name val audioDeviceIdsSet = audioDevices.map { it.deviceId.toString() }.toSet() val devicesChanged = if (cachedAvailableEndpointIdsSet.size != audioDevices.size) { true } else { cachedAvailableEndpointIdsSet != audioDeviceIdsSet } cachedAvailableEndpointIdsSet = audioDeviceIdsSet Log.d( TAG, ("updateAudioDeviceState() Device status: available=$audioDevices, selected=$selectedAudioDeviceEndpoint") ) if (devicesChanged) { // notify the frontend that the available devices changed this.sendAudioStatusEvent(); } // Double-check if any Bluetooth headset is connected once again (useful for older android platforms) // TODO: we can possibly remove this, to be tested on older platforms if (bluetoothManager.bluetoothState == BluetoothManager.State.HEADSET_AVAILABLE || bluetoothManager.bluetoothState == BluetoothManager.State.HEADSET_UNAVAILABLE) { bluetoothManager.updateDevice() } /** sets newAudioDevice initially to this order: WH -> BT -> default(speaker or earpiece) */ var newAudioDevice = defaultAudioDevice audioDevices.firstOrNull { it.isWiredHeadsetType() || it.isBluetoothType() }?.also { newAudioDevice = it.type } var deviceSwitched = false Log.d( TAG, ("Decided newAudioDevice: ${endpointTypeDebug(newAudioDevice)}") ) /** To be called when BT SCO connection fails * Will do the following: * 1 - revert user selection if needed * 2 - sets newAudioDevice to something other than BT * 3 - change the bt manager to device state from sco connection state * */ fun revertBTSelection() { val selectedAudioDeviceEndpoint = this.selectedAudioDeviceEndpoint // prev selection was not BT, but new was BT // new can now be WiredHeadset or default if there was no selection before if (selectedAudioDeviceEndpoint != null && selectedAudioDeviceEndpoint.type != AudioDeviceEndpoint.TYPE_UNKNOWN && selectedAudioDeviceEndpoint.type != AudioDeviceEndpoint.TYPE_BLUETOOTH) { newAudioDevice = selectedAudioDeviceEndpoint.type } else { newAudioDevice = defaultAudioDevice audioDevices.firstOrNull { it.isWiredHeadsetType() }?.also { newAudioDevice = it.type } } // change the bt manager to device state from sco connection state bluetoothManager.updateDevice() Log.d( TAG, ("revertBTSelection newAudioDevice: ${endpointTypeDebug(newAudioDevice)}") ) } var selectedAudioDeviceEndpoint = this.selectedAudioDeviceEndpoint if (selectedAudioDeviceEndpoint == null || newAudioDevice != selectedAudioDeviceEndpoint.type) { // --- stop bluetooth if prev selection was bluetooth if (selectedAudioDeviceEndpoint?.type == AudioDeviceEndpoint.TYPE_BLUETOOTH && (bluetoothManager.bluetoothState == BluetoothManager.State.SCO_CONNECTED || bluetoothManager.bluetoothState == BluetoothManager.State.SCO_CONNECTING)) { bluetoothManager.stopScoAudio() bluetoothManager.updateDevice() } // --- start bluetooth if new is BT and we have a headset if (newAudioDevice == AudioDeviceEndpoint.TYPE_BLUETOOTH && bluetoothManager.bluetoothState == BluetoothManager.State.HEADSET_AVAILABLE) { // Attempt to start Bluetooth SCO audio (takes a few second to start on older platforms). if (!bluetoothManager.startScoAudio()) { revertBTSelection() } // already selected BT device if (bluetoothManager.bluetoothState == BluetoothManager.State.SCO_CONNECTED) { selectedAudioDeviceEndpoint = activeBluetoothEndpoint() this.selectedAudioDeviceEndpoint = selectedAudioDeviceEndpoint deviceSwitched = true } else if ( // still connecting (happens on older Android platforms) bluetoothManager.bluetoothState == BluetoothManager.State.SCO_CONNECTING) { // on older Android platforms // it will call this update function again, once connected or disconnected // so we can skip executing further return@runInAudioThread } } /** This check is meant for older Android platforms * it would have called this device update function again on timer execution * after two cases * 1 - SCO_CONNECTED or * 2 - SCO_DISCONNECTING * Here we see if it was disconnected then we revert to non-bluetooth selection * */ if (newAudioDevice == AudioDeviceEndpoint.TYPE_BLUETOOTH && selectedAudioDeviceEndpoint?.type != AudioDeviceEndpoint.TYPE_BLUETOOTH && bluetoothManager.bluetoothState == BluetoothManager.State.SCO_DISCONNECTING) { revertBTSelection() } if (newAudioDevice != selectedAudioDeviceEndpoint?.type) { // BT sco would be already connected at this point, so no need to switch again if (newAudioDevice != AudioDeviceEndpoint.TYPE_BLUETOOTH) { switchDeviceEndpointType(newAudioDevice) } deviceSwitched = true } if (deviceSwitched || devicesChanged) { Log.d( TAG, ("New device status: " + "available=" + audioDevices + ", " + "selected=" + this.selectedAudioDeviceEndpoint) ) } Log.d( TAG, "--- updateAudioDeviceState done" ) } else { Log.d( TAG, "--- updateAudioDeviceState: no change" ) } } } override fun onAudioFocusChange(focusChange: Int) { when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { Log.d(TAG, "Audio focus gained") // Some other application potentially stole our audio focus // temporarily. Restore our mode. if (audioFocusLost) { // removing the currently selected device store, as its untrue selectedAudioDeviceEndpoint = null // removing the currently selected device store will make sure a device selection is made updateAudioDeviceState() } audioFocusLost = false } AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { Log.d(TAG, "Audio focus lost") audioFocusLost = true } } } fun audioStatusMap(): WritableMap { val endpoint = this.selectedAudioDeviceEndpoint val devices = Arguments.createArray() for (device in getCurrentDeviceEndpoints()) { val deviceMap = Arguments.createMap() deviceMap.putString("id", device.deviceId.toString()) deviceMap.putString("name", device.name) deviceMap.putString( "type", AudioDeviceEndpointUtils.endpointTypeToString(device.type) ) devices.pushMap(deviceMap) } val data = Arguments.createMap() data.putArray("devices", devices) data.putString("currentEndpointType", endpointTypeDebug(endpoint?.type)) if (endpoint != null) { data.putString("selectedDeviceId", endpoint.deviceId.toString()) } return data } private fun sendAudioStatusEvent() { if (telecomManagedMode) { // callingx emits endpoint changes in this mode; avoid duplicate/conflicting events. return } try { if (mReactContext.hasActiveReactInstance()) { val payload = audioStatusMap() Log.d(TAG, "sendAudioStatusEvent: $payload") mReactContext.getJSModule( DeviceEventManagerModule.RCTDeviceEventEmitter::class.java ).emit("onAudioDeviceChanged", payload) } else { Log.e(TAG, "sendEvent(): reactContext is null or not having CatalystInstance yet.") } } catch (e: RuntimeException) { Log.e( TAG, "sendEvent(): java.lang.RuntimeException: Trying to invoke JS before CatalystInstance has been set!", e ) } } companion object { private val TAG: String = StreamInCallManagerModule.TAG + ":" + AudioDeviceManager::class.java.simpleName.toString() /** * Executor service for running audio-related tasks on a dedicated single thread. * *

This executor ensures that all audio processing, recording, playback, * or other audio-related operations are executed sequentially and do not * interfere with the main UI thread or other background tasks. Using a * single-threaded executor for audio tasks helps prevent race conditions * and simplifies synchronization when dealing with audio resources. * *

Tasks submitted to this executor will be processed in the order they * are submitted. */ private val audioThreadExecutor: ExecutorService = Executors.newSingleThreadExecutor() fun runInAudioThread(runnable: Runnable) { audioThreadExecutor.execute(runnable) } /** * Converts an endpoint type to a human-readable string for debugging purposes. * * @param endpointType The endpoint type to convert. Can be null. * @return A string representation of the endpoint type, or "NULL" if the input is null. */ private fun endpointTypeDebug(@EndpointType endpointType: Int?): String { if (endpointType == null) { return "NULL" } return AudioDeviceEndpointUtils.endpointTypeToString(endpointType) } } }