@cloudflare/realtimekit-react-native 0.0.0 → 0.0.1-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +83 -0
  3. package/RealtimeKitCore.podspec +19 -0
  4. package/android/build.gradle +58 -0
  5. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  6. package/android/gradle/wrapper/gradle-wrapper.properties +5 -0
  7. package/android/gradlew +185 -0
  8. package/android/gradlew.bat +89 -0
  9. package/android/src/main/AndroidManifest.xml +23 -0
  10. package/android/src/main/java/com/reactnativecore/BackgroundTimer/RNBackgroundTimer.java +97 -0
  11. package/android/src/main/java/com/reactnativecore/Constants.java +14 -0
  12. package/android/src/main/java/com/reactnativecore/CoreModule.java +49 -0
  13. package/android/src/main/java/com/reactnativecore/CorePackage.java +34 -0
  14. package/android/src/main/java/com/reactnativecore/DyteHelperModule.java +268 -0
  15. package/android/src/main/java/com/reactnativecore/DyteHolder.java +7 -0
  16. package/android/src/main/java/com/reactnativecore/ForegroundService.java +48 -0
  17. package/android/src/main/java/com/reactnativecore/NotificationHelper.java +127 -0
  18. package/android/src/main/java/com/reactnativecore/RNPermissionsModule.java +226 -0
  19. package/android/src/main/java/com/reactnativecore/incallmanager/AppRTCBluetoothManager.java +637 -0
  20. package/android/src/main/java/com/reactnativecore/incallmanager/AppRTCProximitySensor.java +133 -0
  21. package/android/src/main/java/com/reactnativecore/incallmanager/AppRTCUtils.java +41 -0
  22. package/android/src/main/java/com/reactnativecore/incallmanager/InCallManagerModule.java +1881 -0
  23. package/android/src/main/java/com/reactnativecore/incallmanager/InCallProximityManager.java +162 -0
  24. package/android/src/main/java/com/reactnativecore/incallmanager/InCallWakeLockUtils.java +116 -0
  25. package/android/src/main/java/com/reactnativecore/incallmanager/ThreadUtils.java +39 -0
  26. package/app.plugin.js +1 -0
  27. package/ios/BroadcastEventEmitter.h +11 -0
  28. package/ios/BroadcastEventEmitter.m +72 -0
  29. package/ios/Core.h +5 -0
  30. package/ios/Core.m +28 -0
  31. package/ios/Core.xcodeproj/project.pbxproj +287 -0
  32. package/ios/DyteRNBackgroundTimer.h +22 -0
  33. package/ios/DyteRNBackgroundTimer.m +90 -0
  34. package/ios/DyteRNPermissionHandlerNotifications.h +17 -0
  35. package/ios/DyteRNPermissionHandlerNotifications.m +127 -0
  36. package/ios/DyteRNPermissions.h +50 -0
  37. package/ios/DyteRNPermissions.m +275 -0
  38. package/ios/DyteScreensharePickerView.h +8 -0
  39. package/ios/DyteScreensharePickerView.m +27 -0
  40. package/ios/PrivacyInfo.xcprivacy +60 -0
  41. package/ios/RNInCallManager.h +16 -0
  42. package/ios/RNInCallManager.m +1354 -0
  43. package/ios/permissions/DyteRNPermissionHandlerBluetoothPeripheral.h +4 -0
  44. package/ios/permissions/DyteRNPermissionHandlerBluetoothPeripheral.m +87 -0
  45. package/ios/permissions/DyteRNPermissionHandlerCamera.h +5 -0
  46. package/ios/permissions/DyteRNPermissionHandlerCamera.m +38 -0
  47. package/ios/permissions/DyteRNPermissionHandlerMicrophone.h +5 -0
  48. package/ios/permissions/DyteRNPermissionHandlerMicrophone.m +34 -0
  49. package/ios/permissions/DyteRNPermissionHandlerPhotoLibrary.h +8 -0
  50. package/ios/permissions/DyteRNPermissionHandlerPhotoLibrary.m +70 -0
  51. package/ios/screenshare/DyteDarwinNotificationCenter.swift +21 -0
  52. package/ios/screenshare/DyteScreenshareAtomic.swift +29 -0
  53. package/ios/screenshare/DyteScreenshareHandler.swift +103 -0
  54. package/ios/screenshare/DyteScreenshareUploader.swift +139 -0
  55. package/ios/screenshare/DyteSocketConnection.swift +190 -0
  56. package/lib/BackgroundHandler.d.ts +20 -0
  57. package/lib/BackgroundHandler.js +87 -0
  58. package/lib/LocalMediaError.d.ts +4 -0
  59. package/lib/LocalMediaError.js +6 -0
  60. package/lib/LocalMediaHandler.d.ts +118 -0
  61. package/lib/LocalMediaHandler.js +853 -0
  62. package/lib/LocalMediaInterfaces.d.ts +76 -0
  63. package/lib/LocalMediaInterfaces.js +1 -0
  64. package/lib/LocalMediaUtils.d.ts +93 -0
  65. package/lib/LocalMediaUtils.js +276 -0
  66. package/lib/NativeAudioManager.d.ts +16 -0
  67. package/lib/NativeAudioManager.js +93 -0
  68. package/lib/PermissionHandler.d.ts +34 -0
  69. package/lib/PermissionHandler.js +179 -0
  70. package/lib/ReactContext.d.ts +42 -0
  71. package/lib/ReactContext.js +96 -0
  72. package/lib/ReactHooks.d.ts +11 -0
  73. package/lib/ReactHooks.js +73 -0
  74. package/lib/index.d.ts +10 -0
  75. package/lib/index.js +40 -0
  76. package/lib/utils/crypto.d.ts +17 -0
  77. package/lib/utils/crypto.js +82 -0
  78. package/package.json +51 -4
  79. package/plugin/build/withDyte.d.ts +25 -0
  80. package/plugin/build/withDyte.js +100 -0
  81. package/plugin/src/withDyte.ts +150 -0
  82. package/plugin/tsconfig.json +10 -0
  83. package/plugin/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,637 @@
1
+ /*
2
+ * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3
+ *
4
+ * Use of this source code is governed by a BSD-style license
5
+ * that can be found in the LICENSE file in the root of the source
6
+ * tree. An additional intellectual property rights grant can be found
7
+ * in the file PATENTS. All contributing project authors may
8
+ * be found in the AUTHORS file in the root of the source tree.
9
+ */
10
+ package com.reactnativecore.incallmanager;
11
+ import android.annotation.SuppressLint;
12
+ import android.bluetooth.BluetoothClass;
13
+ import android.bluetooth.BluetoothAdapter;
14
+ import android.bluetooth.BluetoothDevice;
15
+ import android.bluetooth.BluetoothHeadset;
16
+ import android.bluetooth.BluetoothProfile;
17
+ import android.content.BroadcastReceiver;
18
+ import android.content.Context;
19
+ import android.content.Intent;
20
+ import android.content.IntentFilter;
21
+ import android.content.pm.PackageManager;
22
+ import android.media.AudioDeviceCallback;
23
+ import android.media.AudioDeviceInfo;
24
+ import android.media.AudioManager;
25
+ import android.os.Build;
26
+ import android.os.Handler;
27
+ import android.os.Looper;
28
+ import android.os.Process;
29
+ import android.util.Log;
30
+ import androidx.annotation.Nullable;
31
+ import androidx.annotation.RequiresApi;
32
+
33
+ import java.util.List;
34
+ import java.util.Set;
35
+ import java.util.ArrayList;
36
+ import com.reactnativecore.incallmanager.AppRTCUtils;
37
+ import com.reactnativecore.incallmanager.ThreadUtils;
38
+ import com.reactnativecore.incallmanager.InCallManagerModule;
39
+ /**
40
+ * AppRTCProximitySensor manages functions related to Bluetoth devices in the
41
+ * AppRTC demo.
42
+ */
43
+ public class AppRTCBluetoothManager {
44
+ private static final String TAG = "reactnativecore:AppRTCBluetoothManager";
45
+ // Timeout interval for starting or stopping audio to a Bluetooth SCO device.
46
+ private static final int BLUETOOTH_SCO_TIMEOUT_MS = 6000;
47
+ // Maximum number of SCO connection attempts.
48
+ private static final int MAX_SCO_CONNECTION_ATTEMPTS = 10;
49
+ // Bluetooth connection state.
50
+ public enum State {
51
+ // Bluetooth is not available; no adapter or Bluetooth is off.
52
+ UNINITIALIZED,
53
+ // Bluetooth error happened when trying to start Bluetooth.
54
+ ERROR,
55
+ // Bluetooth proxy object for the Headset profile exists, but no connected headset devices,
56
+ // SCO is not started or disconnected.
57
+ HEADSET_UNAVAILABLE,
58
+ // Bluetooth proxy object for the Headset profile connected, connected Bluetooth headset
59
+ // present, but SCO is not started or disconnected.
60
+ HEADSET_AVAILABLE,
61
+ // Bluetooth audio SCO connection with remote device is closing.
62
+ SCO_DISCONNECTING,
63
+ // Bluetooth audio SCO connection with remote device is initiated.
64
+ SCO_CONNECTING,
65
+ // Bluetooth audio SCO connection with remote device is established.
66
+ SCO_CONNECTED
67
+ }
68
+ private final Context apprtcContext;
69
+ private final InCallManagerModule apprtcAudioManager;
70
+ @Nullable
71
+ private final AudioManager audioManager;
72
+ private final Handler handler;
73
+ int scoConnectionAttempts;
74
+ private State bluetoothState;
75
+ private final BluetoothProfile.ServiceListener bluetoothServiceListener;
76
+ @Nullable
77
+ private BluetoothAdapter bluetoothAdapter;
78
+ @Nullable
79
+ private BluetoothHeadset bluetoothHeadset;
80
+ @Nullable
81
+ private BluetoothDevice bluetoothDevice;
82
+
83
+ @Nullable
84
+ private AudioDeviceInfo bluetoothAudioDevice;
85
+
86
+ private AudioDeviceCallback bluetoothAudioDeviceCallback;
87
+ private final BroadcastReceiver bluetoothHeadsetReceiver;
88
+ // Runs when the Bluetooth timeout expires. We use that timeout after calling
89
+ // startScoAudio() or stopScoAudio() because we're not guaranteed to get a
90
+ // callback after those calls.
91
+ private final Runnable bluetoothTimeoutRunnable = new Runnable() {
92
+ @Override
93
+ public void run() {
94
+ bluetoothTimeout();
95
+ }
96
+ };
97
+ /**
98
+ * Implementation of an interface that notifies BluetoothProfile IPC clients when they have been
99
+ * connected to or disconnected from the service.
100
+ */
101
+ private class BluetoothServiceListener implements BluetoothProfile.ServiceListener {
102
+ @Override
103
+ // Called to notify the client when the proxy object has been connected to the service.
104
+ // Once we have the profile proxy object, we can use it to monitor the state of the
105
+ // connection and perform other operations that are relevant to the headset profile.
106
+ public void onServiceConnected(int profile, BluetoothProfile proxy) {
107
+ if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
108
+ return;
109
+ }
110
+ // Log.d(TAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
111
+ // Android only supports one connected Bluetooth Headset at a time.
112
+ bluetoothHeadset = (BluetoothHeadset) proxy;
113
+ // Log.d(TAG, "onServiceConnected done: BT state=" + bluetoothState);
114
+ updateAudioDeviceState();
115
+ }
116
+ @Override
117
+ /** Notifies the client when the proxy object has been disconnected from the service. */
118
+ public void onServiceDisconnected(int profile) {
119
+ if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
120
+ return;
121
+ }
122
+ // Log.d(TAG, "BluetoothServiceListener.onServiceDisconnected: BT state=" + bluetoothState);
123
+ stopScoAudio();
124
+ bluetoothHeadset = null;
125
+ bluetoothDevice = null;
126
+ bluetoothState = State.HEADSET_UNAVAILABLE;
127
+ updateAudioDeviceState();
128
+ // Log.d(TAG, "onServiceDisconnected done: BT state=" + bluetoothState);
129
+ }
130
+ }
131
+
132
+ @RequiresApi(api = Build.VERSION_CODES.S)
133
+ private class BluetoothAudioDeviceCallback extends AudioDeviceCallback {
134
+ @Override
135
+ public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
136
+ updateDeviceList();
137
+ }
138
+
139
+ public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
140
+ updateDeviceList();
141
+ }
142
+
143
+ private void updateDeviceList() {
144
+ final AudioDeviceInfo newBtDevice = getScoDevice();
145
+ boolean needChange = false;
146
+ if (bluetoothAudioDevice != null && newBtDevice == null) {
147
+ needChange = true;
148
+ } else if (bluetoothAudioDevice == null && newBtDevice != null) {
149
+ needChange = true;
150
+ } else if (bluetoothAudioDevice != null && bluetoothAudioDevice.getId() != newBtDevice.getId()) {
151
+ needChange = true;
152
+ }
153
+ if (needChange) {
154
+ updateAudioDeviceState();
155
+ }
156
+ }
157
+ }
158
+
159
+ // Intent broadcast receiver which handles changes in Bluetooth device availability.
160
+ // Detects headset changes and Bluetooth SCO state changes.
161
+ private class BluetoothHeadsetBroadcastReceiver extends BroadcastReceiver {
162
+ @Override
163
+ public void onReceive(Context context, Intent intent) {
164
+ if (bluetoothState == State.UNINITIALIZED) {
165
+ return;
166
+ }
167
+ final String action = intent.getAction();
168
+ // Log.i(TAG, "BLE Action: "+ action);
169
+ // Change in connection state of the Headset profile. Note that the
170
+ // change does not tell us anything about whether we're streaming
171
+ // audio to BT over SCO. Typically received when user turns on a BT
172
+ // headset while audio is active using another audio device.
173
+ if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
174
+ final int state =
175
+ intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED);
176
+ // Log.d(TAG, "BluetoothHeadsetBroadcastReceiver.onReceive: "
177
+ // + "a=ACTION_CONNECTION_STATE_CHANGED, "
178
+ // + "s=" + stateToString(state) + ", "
179
+ // + "sb=" + isInitialStickyBroadcast() + ", "
180
+ // + "BT state: " + bluetoothState);
181
+ if (state == BluetoothHeadset.STATE_CONNECTED) {
182
+ scoConnectionAttempts = 0;
183
+ updateAudioDeviceState();
184
+ } else if (state == BluetoothHeadset.STATE_CONNECTING) {
185
+ // No action needed.
186
+ } else if (state == BluetoothHeadset.STATE_DISCONNECTING) {
187
+ // No action needed.
188
+ } else if (state == BluetoothHeadset.STATE_DISCONNECTED) {
189
+ // Bluetooth is probably powered off during the call.
190
+ stopScoAudio();
191
+ updateAudioDeviceState();
192
+ }
193
+ // Change in the audio (SCO) connection state of the Headset profile.
194
+ // Typically received after call to startScoAudio() has finalized.
195
+ } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
196
+ final int state = intent.getIntExtra(
197
+ BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
198
+ updateAudioDeviceState();
199
+ // Log.d(TAG, "BluetoothHeadsetBroadcastReceiver.onReceive: "
200
+ // + "a=ACTION_AUDIO_STATE_CHANGED, "
201
+ // + "s=" + stateToString(state) + ", "
202
+ // + "sb=" + isInitialStickyBroadcast() + ", "
203
+ // + "BT state: " + bluetoothState);
204
+ if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
205
+ cancelTimer();
206
+ if (bluetoothState == State.SCO_CONNECTING) {
207
+ // Log.d(TAG, "+++ Bluetooth audio SCO is now connected");
208
+ bluetoothState = State.SCO_CONNECTED;
209
+ scoConnectionAttempts = 0;
210
+ updateAudioDeviceState();
211
+ } else {
212
+ Log.w(TAG, "Unexpected state BluetoothHeadset.STATE_AUDIO_CONNECTED");
213
+ }
214
+ } else if (state == BluetoothHeadset.STATE_AUDIO_CONNECTING) {
215
+ // Log.d(TAG, "+++ Bluetooth audio SCO is now connecting...");
216
+ } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
217
+ // Log.d(TAG, "+++ Bluetooth audio SCO is now disconnected");
218
+ if (isInitialStickyBroadcast()) {
219
+ // Log.d(TAG, "Ignore STATE_AUDIO_DISCONNECTED initial sticky broadcast.");
220
+ return;
221
+ }
222
+ updateAudioDeviceState();
223
+ }
224
+ }
225
+ // Log.d(TAG, "onReceive done: BT state=" + bluetoothState);
226
+ }
227
+ }
228
+ /** Construction. */
229
+ public static AppRTCBluetoothManager create(Context context, InCallManagerModule audioManager) {
230
+ // Log.d(TAG, "create" + AppRTCUtils.getThreadInfo());
231
+ return new AppRTCBluetoothManager(context, audioManager);
232
+ }
233
+ protected AppRTCBluetoothManager(Context context, InCallManagerModule audioManager) {
234
+ // Log.d(TAG, "ctor");
235
+ ThreadUtils.checkIsOnMainThread();
236
+ apprtcContext = context;
237
+ apprtcAudioManager = audioManager;
238
+ this.audioManager = getAudioManager(context);
239
+ bluetoothState = State.UNINITIALIZED;
240
+ bluetoothServiceListener = new BluetoothServiceListener();
241
+ bluetoothHeadsetReceiver = new BluetoothHeadsetBroadcastReceiver();
242
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
243
+ bluetoothAudioDeviceCallback = new BluetoothAudioDeviceCallback();
244
+ }
245
+ handler = new Handler(Looper.getMainLooper());
246
+ }
247
+ /** Returns the internal state. */
248
+ public State getState() {
249
+ ThreadUtils.checkIsOnMainThread();
250
+ return bluetoothState;
251
+ }
252
+ /**
253
+ * Activates components required to detect Bluetooth devices and to enable
254
+ * BT SCO (audio is routed via BT SCO) for the headset profile. The end
255
+ * state will be HEADSET_UNAVAILABLE but a state machine has started which
256
+ * will start a state change sequence where the final outcome depends on
257
+ * if/when the BT headset is enabled.
258
+ * Example of state change sequence when start() is called while BT device
259
+ * is connected and enabled:
260
+ * UNINITIALIZED --> HEADSET_UNAVAILABLE --> HEADSET_AVAILABLE -->
261
+ * SCO_CONNECTING --> SCO_CONNECTED <==> audio is now routed via BT SCO.
262
+ * Note that the AppRTCAudioManager is also involved in driving this state
263
+ * change.
264
+ */
265
+ @SuppressLint("MissingPermission")
266
+ public void start() {
267
+ ThreadUtils.checkIsOnMainThread();
268
+ // Log.d(TAG, "start");
269
+ String p = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? android.Manifest.permission.BLUETOOTH_CONNECT : android.Manifest.permission.BLUETOOTH;
270
+ if (!hasPermission(apprtcContext, p)) {
271
+ Log.w(TAG, "Process (pid=" + Process.myPid() + ") lacks BLUETOOTH permission");
272
+ return;
273
+ }
274
+ if (bluetoothState != State.UNINITIALIZED) {
275
+ Log.w(TAG, "Invalid BT state");
276
+ return;
277
+ }
278
+ bluetoothHeadset = null;
279
+ bluetoothDevice = null;
280
+ scoConnectionAttempts = 0;
281
+ // Get a handle to the default local Bluetooth adapter.
282
+ bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
283
+ if (bluetoothAdapter == null) {
284
+ Log.w(TAG, "Device does not support Bluetooth");
285
+ return;
286
+ }
287
+ // Ensure that the device supports use of BT SCO audio for off call use cases.
288
+ if (!audioManager.isBluetoothScoAvailableOffCall()) {
289
+ Log.e(TAG, "Bluetooth SCO audio is not available off call");
290
+ return;
291
+ }
292
+ // logBluetoothAdapterInfo(bluetoothAdapter);
293
+ // Establish a connection to the HEADSET profile (includes both Bluetooth Headset and
294
+ // Hands-Free) proxy object and install a listener.
295
+ if (!getBluetoothProfileProxy(
296
+ apprtcContext, bluetoothServiceListener, BluetoothProfile.HEADSET)) {
297
+ // Log.e(TAG, "BluetoothAdapter.getProfileProxy(HEADSET) failed");
298
+ return;
299
+ }
300
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
301
+ audioManager.registerAudioDeviceCallback(bluetoothAudioDeviceCallback, null);
302
+ } else {
303
+ // Register receivers for BluetoothHeadset change notifications.
304
+ IntentFilter bluetoothHeadsetFilter = new IntentFilter();
305
+ // Register receiver for change in connection state of the Headset profile.
306
+ bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
307
+ // Register receiver for change in audio connection state of the Headset profile.
308
+ bluetoothHeadsetFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
309
+ registerReceiver(bluetoothHeadsetReceiver, bluetoothHeadsetFilter);
310
+ // Log.d(TAG, "HEADSET profile state: "
311
+ // + stateToString(bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)));
312
+ }
313
+ // Log.d(TAG, "Bluetooth proxy for headset profile has started");
314
+ bluetoothState = State.HEADSET_UNAVAILABLE;
315
+ // Log.d(TAG, "start done: BT state=" + bluetoothState);
316
+ }
317
+ /** Stops and closes all components related to Bluetooth audio. */
318
+ public void stop() {
319
+ ThreadUtils.checkIsOnMainThread();
320
+ // Log.d(TAG, "stop: BT state=" + bluetoothState);
321
+ if (bluetoothAdapter == null) {
322
+ return;
323
+ }
324
+ // Stop BT SCO connection with remote device if needed.
325
+ stopScoAudio();
326
+ // Close down remaining BT resources.
327
+ if (bluetoothState == State.UNINITIALIZED) {
328
+ return;
329
+ }
330
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
331
+ audioManager.unregisterAudioDeviceCallback(bluetoothAudioDeviceCallback);
332
+ } else {
333
+ unregisterReceiver(bluetoothHeadsetReceiver);
334
+ cancelTimer();
335
+ }
336
+ if (bluetoothHeadset != null) {
337
+ bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);
338
+ bluetoothHeadset = null;
339
+ }
340
+ bluetoothAdapter = null;
341
+ bluetoothDevice = null;
342
+ bluetoothState = State.UNINITIALIZED;
343
+ // Log.d(TAG, "stop done: BT state=" + bluetoothState);
344
+ }
345
+ /**
346
+ * Starts Bluetooth SCO connection with remote device.
347
+ * Note that the phone application always has the priority on the usage of the SCO connection
348
+ * for telephony. If this method is called while the phone is in call it will be ignored.
349
+ * Similarly, if a call is received or sent while an application is using the SCO connection,
350
+ * the connection will be lost for the application and NOT returned automatically when the call
351
+ * ends. Also note that: up to and including API version JELLY_BEAN_MR1, this method initiates a
352
+ * virtual voice call to the Bluetooth headset. After API version JELLY_BEAN_MR2 only a raw SCO
353
+ * audio connection is established.
354
+ * TODO(henrika): should we add support for virtual voice call to BT headset also for JBMR2 and
355
+ * higher. It might be required to initiates a virtual voice call since many devices do not
356
+ * accept SCO audio without a "call".
357
+ */
358
+ public boolean startScoAudio() {
359
+ ThreadUtils.checkIsOnMainThread();
360
+ // Log.d(TAG, "startSco: BT state=" + bluetoothState + ", "
361
+ // + "attempts: " + scoConnectionAttempts + ", "
362
+ // + "SCO is on: " + isScoOn());
363
+ if (scoConnectionAttempts >= MAX_SCO_CONNECTION_ATTEMPTS) {
364
+ // Log.e(TAG, "BT SCO connection fails - no more attempts");
365
+ return false;
366
+ }
367
+ if (bluetoothState != State.HEADSET_AVAILABLE) {
368
+ // Log.e(TAG, "BT SCO connection fails - no headset available");
369
+ return false;
370
+ }
371
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
372
+ if (bluetoothAudioDevice != null) {
373
+ audioManager.setCommunicationDevice(bluetoothAudioDevice);
374
+ bluetoothState = State.SCO_CONNECTED;
375
+ // Log.d(TAG, "Set bluetooth audio device as communication device: "
376
+ // + "id=" + bluetoothAudioDevice.getId());
377
+ } else {
378
+ bluetoothState = State.SCO_DISCONNECTING;
379
+ // Log.d(TAG, "Cannot find any bluetooth SCO device to set as communication device");
380
+ }
381
+ updateAudioDeviceState();
382
+ } else {
383
+ // The SCO connection establishment can take several seconds, hence we cannot rely on the
384
+ // connection to be available when the method returns but instead register to receive the
385
+ // intent ACTION_SCO_AUDIO_STATE_UPDATED and wait for the state to be SCO_AUDIO_STATE_CONNECTED.
386
+ // Start BT SCO channel and wait for ACTION_AUDIO_STATE_CHANGED.
387
+ // Log.d(TAG, "Starting Bluetooth SCO and waits for ACTION_AUDIO_STATE_CHANGED...");
388
+ bluetoothState = State.SCO_CONNECTING;
389
+ startTimer();
390
+ audioManager.startBluetoothSco();
391
+ audioManager.setBluetoothScoOn(true);
392
+ scoConnectionAttempts++;
393
+ // Log.d(TAG, "startScoAudio done: BT state=" + bluetoothState + ", "
394
+ // + "SCO is on: " + isScoOn());
395
+ }
396
+ return true;
397
+ }
398
+ private List<BluetoothDevice> getFinalConnectedDevices() {
399
+ List<BluetoothDevice> connectedDevices = bluetoothHeadset.getConnectedDevices();
400
+ List<BluetoothDevice> finalDevices = new ArrayList<BluetoothDevice>();
401
+
402
+ for (BluetoothDevice device : connectedDevices) {
403
+ int majorClass = device.getBluetoothClass().getMajorDeviceClass();
404
+
405
+ if (majorClass == BluetoothClass.Device.Major.AUDIO_VIDEO) {
406
+ finalDevices.add(device);
407
+ }
408
+ }
409
+ return finalDevices;
410
+ }
411
+ /** Stops Bluetooth SCO connection with remote device. */
412
+ public void stopScoAudio() {
413
+ ThreadUtils.checkIsOnMainThread();
414
+ // Log.d(TAG, "stopScoAudio: BT state=" + bluetoothState + ", "
415
+ // + "SCO is on: " + isScoOn());
416
+ if (bluetoothState != State.SCO_CONNECTING && bluetoothState != State.SCO_CONNECTED) {
417
+ return;
418
+ }
419
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
420
+ audioManager.clearCommunicationDevice();
421
+ } else {
422
+ cancelTimer();
423
+ audioManager.stopBluetoothSco();
424
+ audioManager.setBluetoothScoOn(false);
425
+ }
426
+ bluetoothState = State.SCO_DISCONNECTING;
427
+ // Log.d(TAG, "stopScoAudio done: BT state=" + bluetoothState + ", "
428
+ // + "SCO is on: " + isScoOn());
429
+ }
430
+ /**
431
+ * Use the BluetoothHeadset proxy object (controls the Bluetooth Headset
432
+ * Service via IPC) to update the list of connected devices for the HEADSET
433
+ * profile. The internal state will change to HEADSET_UNAVAILABLE or to
434
+ * HEADSET_AVAILABLE and `bluetoothDevice` will be mapped to the connected
435
+ * device if available.
436
+ */
437
+ @SuppressLint("MissingPermission")
438
+ public void updateDevice() {
439
+ if (bluetoothState == State.UNINITIALIZED || bluetoothHeadset == null) {
440
+ return;
441
+ }
442
+ // Log.d(TAG, "updateDevice");
443
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
444
+ bluetoothAudioDevice = getScoDevice();
445
+ if (bluetoothAudioDevice != null) {
446
+ bluetoothState = State.HEADSET_AVAILABLE;
447
+ // Log.d(TAG, "Connected bluetooth headset: "
448
+ // + "name=" + bluetoothAudioDevice.getProductName());
449
+ } else {
450
+ bluetoothState = State.HEADSET_UNAVAILABLE;
451
+ }
452
+ } else {
453
+ // Get connected devices for the headset profile. Returns the set of
454
+ // devices which are in state STATE_CONNECTED. The BluetoothDevice class
455
+ // is just a thin wrapper for a Bluetooth hardware address.
456
+ List<BluetoothDevice> devices = getFinalConnectedDevices();
457
+ if (devices.isEmpty()) {
458
+ bluetoothDevice = null;
459
+ bluetoothState = State.HEADSET_UNAVAILABLE;
460
+ // Log.d(TAG, "No connected bluetooth headset");
461
+ } else {
462
+ // Always use first device in list. Android only supports one device.
463
+ bluetoothDevice = devices.get(0);
464
+ bluetoothState = State.HEADSET_AVAILABLE;
465
+ // Log.d(TAG, "Connected bluetooth headset: "
466
+ // + "name=" + bluetoothDevice.getName() + ", "
467
+ // + "state=" + stateToString(bluetoothHeadset.getConnectionState(bluetoothDevice))
468
+ // + ", SCO audio=" + bluetoothHeadset.isAudioConnected(bluetoothDevice));
469
+ }
470
+ }
471
+ // Log.d(TAG, "updateDevice done: BT state=" + bluetoothState);
472
+ }
473
+ /**
474
+ * Stubs for test mocks.
475
+ */
476
+ @Nullable
477
+ protected AudioManager getAudioManager(Context context) {
478
+ return (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
479
+ }
480
+ protected void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
481
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
482
+ apprtcContext.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED);
483
+ } else {
484
+ apprtcContext.registerReceiver(receiver, filter);
485
+ }
486
+ }
487
+ protected void unregisterReceiver(BroadcastReceiver receiver) {
488
+ if (receiver != null) {
489
+ try {
490
+ apprtcContext.unregisterReceiver(receiver);
491
+ } catch (final Exception exception) {
492
+ // The receiver was not registered.
493
+ // There is nothing to do in that case.
494
+ // Everything is fine.
495
+ }
496
+ }
497
+ }
498
+ protected boolean getBluetoothProfileProxy(
499
+ Context context, BluetoothProfile.ServiceListener listener, int profile) {
500
+ return bluetoothAdapter.getProfileProxy(context, listener, profile);
501
+ }
502
+ protected boolean hasPermission(Context context, String permission) {
503
+ return apprtcContext.checkPermission(permission, Process.myPid(), Process.myUid())
504
+ == PackageManager.PERMISSION_GRANTED;
505
+ }
506
+ /** Logs the state of the local Bluetooth adapter. */
507
+ @SuppressLint({"HardwareIds", "MissingPermission"})
508
+ protected void logBluetoothAdapterInfo(BluetoothAdapter localAdapter) {
509
+ Log.d(TAG, "BluetoothAdapter: "
510
+ + "enabled=" + localAdapter.isEnabled() + ", "
511
+ + "state=" + stateToString(localAdapter.getState()) + ", "
512
+ + "name=" + localAdapter.getName() + ", "
513
+ + "address=" + localAdapter.getAddress());
514
+ // Log the set of BluetoothDevice objects that are bonded (paired) to the local adapter.
515
+ Set<BluetoothDevice> pairedDevices = localAdapter.getBondedDevices();
516
+ if (!pairedDevices.isEmpty()) {
517
+ Log.d(TAG, "paired devices:");
518
+ for (BluetoothDevice device : pairedDevices) {
519
+ Log.d(TAG, " name=" + device.getName() + ", address=" + device.getAddress() + ", deviceClass=" + String.valueOf(device.getBluetoothClass().getDeviceClass()) + ", deviceMajorClass=" + String.valueOf(device.getBluetoothClass().getMajorDeviceClass()));
520
+ }
521
+ }
522
+ }
523
+ /** Ensures that the audio manager updates its list of available audio devices. */
524
+ private void updateAudioDeviceState() {
525
+ ThreadUtils.checkIsOnMainThread();
526
+ // Log.d(TAG, "updateAudioDeviceState");
527
+ updateDevice();
528
+ apprtcAudioManager.updateAudioDeviceState();
529
+ }
530
+ /** Starts timer which times out after BLUETOOTH_SCO_TIMEOUT_MS milliseconds. */
531
+ private void startTimer() {
532
+ ThreadUtils.checkIsOnMainThread();
533
+ // Log.d(TAG, "startTimer");
534
+ handler.postDelayed(bluetoothTimeoutRunnable, BLUETOOTH_SCO_TIMEOUT_MS);
535
+ }
536
+ /** Cancels any outstanding timer tasks. */
537
+ private void cancelTimer() {
538
+ ThreadUtils.checkIsOnMainThread();
539
+ // Log.d(TAG, "cancelTimer");
540
+ handler.removeCallbacks(bluetoothTimeoutRunnable);
541
+ }
542
+ /**
543
+ * Called when start of the BT SCO channel takes too long time. Usually
544
+ * happens when the BT device has been turned on during an ongoing call.
545
+ */
546
+ @SuppressLint("MissingPermission")
547
+ private void bluetoothTimeout() {
548
+ ThreadUtils.checkIsOnMainThread();
549
+ if (bluetoothState == State.UNINITIALIZED || bluetoothHeadset == null) {
550
+ return;
551
+ }
552
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
553
+ // Log.w(TAG, "Invalid state, the timeout should not be running on the version: " + Build.VERSION.SDK_INT);
554
+ } else {
555
+ // Log.d(TAG, "bluetoothTimeout: BT state=" + bluetoothState + ", "
556
+ // + "attempts: " + scoConnectionAttempts + ", "
557
+ // + "SCO is on: " + isScoOn());
558
+ if (bluetoothState != State.SCO_CONNECTING) {
559
+ return;
560
+ }
561
+ // Bluetooth SCO should be connecting; check the latest result.
562
+ boolean scoConnected = false;
563
+ List<BluetoothDevice> devices = getFinalConnectedDevices();
564
+ if (devices.size() > 0) {
565
+ bluetoothDevice = devices.get(0);
566
+ if (bluetoothHeadset.isAudioConnected(bluetoothDevice)) {
567
+ // Log.d(TAG, "SCO connected with " + bluetoothDevice.getName());
568
+ scoConnected = true;
569
+ } else {
570
+ // Log.d(TAG, "SCO is not connected with " + bluetoothDevice.getName());
571
+ }
572
+ }
573
+ if (scoConnected) {
574
+ // We thought BT had timed out, but it's actually on; updating state.
575
+ bluetoothState = State.SCO_CONNECTED;
576
+ scoConnectionAttempts = 0;
577
+ } else {
578
+ // Give up and "cancel" our request by calling stopBluetoothSco().
579
+ Log.w(TAG, "BT failed to connect after timeout");
580
+ stopScoAudio();
581
+ }
582
+ }
583
+ updateAudioDeviceState();
584
+ // Log.d(TAG, "bluetoothTimeout done: BT state=" + bluetoothState);
585
+ }
586
+ /** Checks whether audio uses Bluetooth SCO. */
587
+ private boolean isScoOn() {
588
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
589
+ AudioDeviceInfo communicationDevice = audioManager.getCommunicationDevice();
590
+ return communicationDevice != null && bluetoothAudioDevice != null && communicationDevice.getId() == bluetoothAudioDevice.getId();
591
+ } else {
592
+ return audioManager.isBluetoothScoOn();
593
+ }
594
+ }
595
+ /** Converts BluetoothAdapter states into local string representations. */
596
+ private String stateToString(int state) {
597
+ switch (state) {
598
+ case BluetoothAdapter.STATE_DISCONNECTED:
599
+ return "DISCONNECTED";
600
+ case BluetoothAdapter.STATE_CONNECTED:
601
+ return "CONNECTED";
602
+ case BluetoothAdapter.STATE_CONNECTING:
603
+ return "CONNECTING";
604
+ case BluetoothAdapter.STATE_DISCONNECTING:
605
+ return "DISCONNECTING";
606
+ case BluetoothAdapter.STATE_OFF:
607
+ return "OFF";
608
+ case BluetoothAdapter.STATE_ON:
609
+ return "ON";
610
+ case BluetoothAdapter.STATE_TURNING_OFF:
611
+ // Indicates the local Bluetooth adapter is turning off. Local clients should immediately
612
+ // attempt graceful disconnection of any remote links.
613
+ return "TURNING_OFF";
614
+ case BluetoothAdapter.STATE_TURNING_ON:
615
+ // Indicates the local Bluetooth adapter is turning on. However local clients should wait
616
+ // for STATE_ON before attempting to use the adapter.
617
+ return "TURNING_ON";
618
+ default:
619
+ return "INVALID";
620
+ }
621
+ }
622
+
623
+ @Nullable
624
+ @RequiresApi(api = Build.VERSION_CODES.S)
625
+ private AudioDeviceInfo getScoDevice() {
626
+ if (audioManager != null) {
627
+ List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
628
+ for (AudioDeviceInfo device : devices) {
629
+ if (device.getType() == AudioDeviceInfo.TYPE_BLE_HEADSET
630
+ || device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
631
+ return device;
632
+ }
633
+ }
634
+ }
635
+ return null;
636
+ }
637
+ }