@stream-io/video-react-native-sdk 1.41.0 → 1.42.0

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 (63) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/android/src/main/java/com/streamvideo/reactnative/audio/AudioDeviceManager.kt +79 -54
  3. package/android/src/main/java/com/streamvideo/reactnative/audio/utils/AudioManagerUtil.kt +6 -2
  4. package/android/src/main/java/com/streamvideo/reactnative/callmanager/StreamInCallManagerModule.kt +3 -3
  5. package/dist/commonjs/hooks/index.js +11 -0
  6. package/dist/commonjs/hooks/index.js.map +1 -1
  7. package/dist/commonjs/hooks/push/useCallingExpWithCallingStateEffect.js +73 -0
  8. package/dist/commonjs/hooks/push/useCallingExpWithCallingStateEffect.js.map +1 -1
  9. package/dist/commonjs/hooks/useAudioDeviceStatus.js +76 -0
  10. package/dist/commonjs/hooks/useAudioDeviceStatus.js.map +1 -0
  11. package/dist/commonjs/modules/call-manager/CallManager.js +94 -47
  12. package/dist/commonjs/modules/call-manager/CallManager.js.map +1 -1
  13. package/dist/commonjs/utils/internal/callingx/callingx.js +0 -7
  14. package/dist/commonjs/utils/internal/callingx/callingx.js.map +1 -1
  15. package/dist/commonjs/utils/push/setupCallingExpEvents.js +0 -2
  16. package/dist/commonjs/utils/push/setupCallingExpEvents.js.map +1 -1
  17. package/dist/commonjs/version.js +1 -1
  18. package/dist/module/hooks/index.js +1 -0
  19. package/dist/module/hooks/index.js.map +1 -1
  20. package/dist/module/hooks/push/useCallingExpWithCallingStateEffect.js +73 -0
  21. package/dist/module/hooks/push/useCallingExpWithCallingStateEffect.js.map +1 -1
  22. package/dist/module/hooks/useAudioDeviceStatus.js +71 -0
  23. package/dist/module/hooks/useAudioDeviceStatus.js.map +1 -0
  24. package/dist/module/modules/call-manager/CallManager.js +94 -47
  25. package/dist/module/modules/call-manager/CallManager.js.map +1 -1
  26. package/dist/module/utils/internal/callingx/callingx.js +0 -7
  27. package/dist/module/utils/internal/callingx/callingx.js.map +1 -1
  28. package/dist/module/utils/push/setupCallingExpEvents.js +0 -2
  29. package/dist/module/utils/push/setupCallingExpEvents.js.map +1 -1
  30. package/dist/module/version.js +1 -1
  31. package/dist/typescript/hooks/index.d.ts +1 -0
  32. package/dist/typescript/hooks/index.d.ts.map +1 -1
  33. package/dist/typescript/hooks/push/useCallingExpWithCallingStateEffect.d.ts.map +1 -1
  34. package/dist/typescript/hooks/useAudioDeviceStatus.d.ts +21 -0
  35. package/dist/typescript/hooks/useAudioDeviceStatus.d.ts.map +1 -0
  36. package/dist/typescript/modules/call-manager/CallManager.d.ts +25 -11
  37. package/dist/typescript/modules/call-manager/CallManager.d.ts.map +1 -1
  38. package/dist/typescript/modules/call-manager/types.d.ts +29 -3
  39. package/dist/typescript/modules/call-manager/types.d.ts.map +1 -1
  40. package/dist/typescript/utils/internal/callingx/callingx.d.ts.map +1 -1
  41. package/dist/typescript/utils/push/setupCallingExpEvents.d.ts.map +1 -1
  42. package/dist/typescript/version.d.ts +1 -1
  43. package/expo-config-plugin/dist/index.js +2 -0
  44. package/expo-config-plugin/dist/withAndroidMessagingService.js +287 -0
  45. package/ios/StreamInCallManager.m +7 -0
  46. package/ios/StreamInCallManager.swift +257 -14
  47. package/package.json +8 -8
  48. package/src/hooks/index.ts +1 -0
  49. package/src/hooks/push/useCallingExpWithCallingStateEffect.ts +95 -0
  50. package/src/hooks/useAudioDeviceStatus.ts +90 -0
  51. package/src/modules/call-manager/CallManager.ts +122 -64
  52. package/src/modules/call-manager/native-module.d.ts +14 -7
  53. package/src/modules/call-manager/types.ts +30 -3
  54. package/src/utils/internal/callingx/callingx.ts +0 -8
  55. package/src/utils/push/setupCallingExpEvents.ts +0 -2
  56. package/src/version.ts +1 -1
  57. package/dist/commonjs/utils/internal/callingx/audioSessionPromise.js +0 -68
  58. package/dist/commonjs/utils/internal/callingx/audioSessionPromise.js.map +0 -1
  59. package/dist/module/utils/internal/callingx/audioSessionPromise.js +0 -63
  60. package/dist/module/utils/internal/callingx/audioSessionPromise.js.map +0 -1
  61. package/dist/typescript/utils/internal/callingx/audioSessionPromise.d.ts +0 -16
  62. package/dist/typescript/utils/internal/callingx/audioSessionPromise.d.ts.map +0 -1
  63. package/src/utils/internal/callingx/audioSessionPromise.ts +0 -65
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FIREBASE_DEP_MARKER = exports.FIREBASE_BOM_FALLBACK_VERSION = exports.FIREBASE_MESSAGING_ARTIFACT = exports.STREAM_DEFAULT_SERVICE = exports.GENERATED_SERVICE_CLASS_NAME = exports.EXPO_NOTIFICATIONS_SERVICE = void 0;
37
+ exports.updateManifest = updateManifest;
38
+ exports.buildServiceSource = buildServiceSource;
39
+ exports.validateBaseClass = validateBaseClass;
40
+ exports.resolveBaseClass = resolveBaseClass;
41
+ exports.isExpoNotificationsInstalled = isExpoNotificationsInstalled;
42
+ exports.getGeneratedServiceFqcn = getGeneratedServiceFqcn;
43
+ exports.addFirebaseMessagingDependency = addFirebaseMessagingDependency;
44
+ exports.resolveFirebaseBomVersion = resolveFirebaseBomVersion;
45
+ const config_plugins_1 = require("@expo/config-plugins");
46
+ const fs = __importStar(require("fs"));
47
+ const path = __importStar(require("path"));
48
+ const GENERATED_SERVICE_CLASS_NAME = 'StreamVideoMessagingService';
49
+ exports.GENERATED_SERVICE_CLASS_NAME = GENERATED_SERVICE_CLASS_NAME;
50
+ const STREAM_DEFAULT_SERVICE = 'io.getstream.rn.callingx.StreamMessagingService';
51
+ exports.STREAM_DEFAULT_SERVICE = STREAM_DEFAULT_SERVICE;
52
+ /** React Native Firebase's own FCM service. */
53
+ const RN_FIREBASE_SERVICE = 'io.invertase.firebase.messaging.ReactNativeFirebaseMessagingService';
54
+ /** expo-notifications' FCM service — the default base auto-detected when installed. */
55
+ const EXPO_NOTIFICATIONS_SERVICE = 'expo.modules.notifications.service.ExpoFirebaseMessagingService';
56
+ exports.EXPO_NOTIFICATIONS_SERVICE = EXPO_NOTIFICATIONS_SERVICE;
57
+ const MESSAGING_EVENT_ACTION = 'com.google.firebase.MESSAGING_EVENT';
58
+ /**
59
+ * The generated service lives in the `:app` module, which only has
60
+ * firebase-messaging on its *runtime* classpath (via callingx / RNFB /
61
+ * expo-notifications `implementation` deps). We add it as `compileOnly` so the
62
+ * app can compile a `FirebaseMessagingService` subclass. The runtime artifact is
63
+ * still supplied by those modules, so this avoids a version conflict.
64
+ */
65
+ const FIREBASE_MESSAGING_ARTIFACT = 'com.google.firebase:firebase-messaging';
66
+ exports.FIREBASE_MESSAGING_ARTIFACT = FIREBASE_MESSAGING_ARTIFACT;
67
+ /**
68
+ * Fallback Firebase BOM version, used only when the live BOM cannot be resolved
69
+ * from @react-native-firebase/app. This is the BOM shipped by the minimum RNFB
70
+ * version we support: @stream-io/react-native-callingx declares a
71
+ * `@react-native-firebase/* >= 23.0.0` peer dependency, and RNFB `23.0.0` pins
72
+ * firebase-bom `34.0.0`. Keep in sync with that peer floor.
73
+ */
74
+ const FIREBASE_BOM_FALLBACK_VERSION = '34.0.0';
75
+ exports.FIREBASE_BOM_FALLBACK_VERSION = FIREBASE_BOM_FALLBACK_VERSION;
76
+ /** Stable comment used to detect (and avoid duplicating) our gradle injection. */
77
+ const FIREBASE_DEP_MARKER = '// Added by @stream-io/video-react-native-sdk for the generated FCM messaging service';
78
+ exports.FIREBASE_DEP_MARKER = FIREBASE_DEP_MARKER;
79
+ function getAndroidPackage(config) {
80
+ const modResults = config.modResults;
81
+ const pkg = config.android?.package ?? modResults?.manifest?.$?.package;
82
+ if (!pkg) {
83
+ throw new Error('[StreamVideo] Unable to resolve the Android package name required to generate ' +
84
+ 'the FCM messaging service. Set "android.package" in your app config.');
85
+ }
86
+ return pkg;
87
+ }
88
+ function getGeneratedServiceFqcn(androidPackage) {
89
+ return `${androidPackage}.${GENERATED_SERVICE_CLASS_NAME}`;
90
+ }
91
+ function validateBaseClass(baseClass) {
92
+ if (typeof baseClass !== 'string' || baseClass.trim().length === 0) {
93
+ throw new Error('[StreamVideo] "androidMessagingServiceBaseClass" must be a non-empty string.');
94
+ }
95
+ if (!baseClass.includes('.')) {
96
+ throw new Error(`[StreamVideo] "androidMessagingServiceBaseClass" must be a fully-qualified class name ` +
97
+ `including its package (e.g. "expo.modules.notifications.service.ExpoFirebaseMessagingService"), ` +
98
+ `received "${baseClass}".`);
99
+ }
100
+ }
101
+ function isExpoNotificationsInstalled(projectRoot) {
102
+ try {
103
+ require.resolve('expo-notifications/package.json', projectRoot ? { paths: [projectRoot] } : undefined);
104
+ return true;
105
+ }
106
+ catch {
107
+ return false;
108
+ }
109
+ }
110
+ function resolveBaseClass(value, projectRoot) {
111
+ if (value === null) {
112
+ return undefined;
113
+ }
114
+ if (typeof value === 'string') {
115
+ validateBaseClass(value);
116
+ return value;
117
+ }
118
+ return isExpoNotificationsInstalled(projectRoot)
119
+ ? EXPO_NOTIFICATIONS_SERVICE
120
+ : undefined;
121
+ }
122
+ /** Kotlin source for the generated messaging service. */
123
+ function buildServiceSource(androidPackage, baseClassFqcn) {
124
+ const simpleName = baseClassFqcn.split('.').pop();
125
+ const shouldForwardNewToken = baseClassFqcn !== RN_FIREBASE_SERVICE;
126
+ const onNewToken = shouldForwardNewToken
127
+ ? `
128
+ override fun onNewToken(token: String) {
129
+ super.onNewToken(token)
130
+ // Keep Stream's device registration working under a non-RNFirebase base.
131
+ StreamMessagingHelper.forwardNewToken(token)
132
+ }
133
+ `
134
+ : '';
135
+ return `package ${androidPackage}
136
+
137
+ import android.annotation.SuppressLint
138
+ import com.google.firebase.messaging.RemoteMessage
139
+ import io.getstream.rn.callingx.StreamMessagingHelper
140
+ import ${baseClassFqcn}
141
+
142
+ /**
143
+ * AUTO-GENERATED by the @stream-io/video-react-native-sdk Expo config plugin.
144
+ * Do not edit — this file is regenerated on every \`expo prebuild\`.
145
+ *
146
+ * Extends the app-declared FCM service (${baseClassFqcn}) and injects Stream
147
+ * Video incoming-call (\`call.ring\`) handling. Stream's default
148
+ * ${STREAM_DEFAULT_SERVICE} is removed from the merged manifest so this class is
149
+ * the single FirebaseMessagingService for the app.
150
+ */
151
+ @SuppressLint("MissingFirebaseInstanceTokenRefresh")
152
+ class ${GENERATED_SERVICE_CLASS_NAME} : ${simpleName}() {
153
+ override fun onMessageReceived(remoteMessage: RemoteMessage) {
154
+ if (StreamMessagingHelper.isStreamCallRing(remoteMessage)) {
155
+ StreamMessagingHelper.handleMessage(applicationContext, remoteMessage)
156
+ return
157
+ }
158
+ super.onMessageReceived(remoteMessage)
159
+ }
160
+ ${onNewToken}}
161
+ `;
162
+ }
163
+ function updateManifest(androidManifest, generatedFqcn, baseClassFqcn) {
164
+ const manifest = androidManifest.manifest;
165
+ if (!manifest ||
166
+ !Array.isArray(manifest.application) ||
167
+ !manifest.application[0]) {
168
+ throw new Error('[StreamVideo] Malformed AndroidManifest.xml: missing <application> element.');
169
+ }
170
+ manifest.$ = manifest.$ ?? {};
171
+ manifest.$['xmlns:tools'] =
172
+ manifest.$['xmlns:tools'] ?? 'http://schemas.android.com/tools';
173
+ // Services whose registration we strip so the generated service is the only
174
+ // MESSAGING_EVENT handler: Stream's default (from react-native-callingx) and
175
+ // the base class (its logic still runs — the generated service subclasses it).
176
+ const servicesToRemove = [
177
+ ...new Set([STREAM_DEFAULT_SERVICE, baseClassFqcn]),
178
+ ];
179
+ const application = manifest.application[0];
180
+ const existing = application.service ?? [];
181
+ // Drop our own previously-added entries so re-runs don't duplicate them.
182
+ const services = existing.filter((service) => {
183
+ const name = service?.$?.['android:name'];
184
+ return name !== generatedFqcn && !servicesToRemove.includes(name ?? '');
185
+ });
186
+ // The generated service becomes the single com.google.firebase.MESSAGING_EVENT handler.
187
+ services.push({
188
+ $: {
189
+ 'android:name': generatedFqcn,
190
+ 'android:exported': 'false',
191
+ },
192
+ 'intent-filter': [
193
+ {
194
+ action: [{ $: { 'android:name': MESSAGING_EVENT_ACTION } }],
195
+ },
196
+ ],
197
+ });
198
+ // Remove the competing services so they don't win FCM delivery. `tools:node`
199
+ // is not part of the strict typing but is valid manifest merger syntax.
200
+ for (const name of servicesToRemove) {
201
+ services.push({
202
+ $: {
203
+ 'android:name': name,
204
+ 'tools:node': 'remove',
205
+ },
206
+ });
207
+ }
208
+ application.service = services;
209
+ return androidManifest;
210
+ }
211
+ const withGeneratedMessagingServiceFile = (config, value) => {
212
+ return (0, config_plugins_1.withDangerousMod)(config, [
213
+ 'android',
214
+ (dangerousConfig) => {
215
+ const baseClassFqcn = resolveBaseClass(value, dangerousConfig.modRequest.projectRoot);
216
+ if (!baseClassFqcn) {
217
+ return dangerousConfig;
218
+ }
219
+ const androidPackage = getAndroidPackage(dangerousConfig);
220
+ const packagePath = androidPackage.replace(/\./g, path.sep);
221
+ const javaDir = path.join(dangerousConfig.modRequest.platformProjectRoot, 'app', 'src', 'main', 'java', packagePath);
222
+ fs.mkdirSync(javaDir, { recursive: true });
223
+ const destPath = path.join(javaDir, `${GENERATED_SERVICE_CLASS_NAME}.kt`);
224
+ fs.writeFileSync(destPath, buildServiceSource(androidPackage, baseClassFqcn), 'utf8');
225
+ return dangerousConfig;
226
+ },
227
+ ]);
228
+ };
229
+ const withMessagingServiceManifest = (config, value) => {
230
+ return (0, config_plugins_1.withAndroidManifest)(config, (androidConfig) => {
231
+ const baseClassFqcn = resolveBaseClass(value, androidConfig.modRequest.projectRoot);
232
+ if (!baseClassFqcn) {
233
+ return androidConfig;
234
+ }
235
+ const androidPackage = getAndroidPackage(androidConfig);
236
+ androidConfig.modResults = updateManifest(androidConfig.modResults, getGeneratedServiceFqcn(androidPackage), baseClassFqcn);
237
+ return androidConfig;
238
+ });
239
+ };
240
+ function resolveFirebaseBomVersion(projectRoot) {
241
+ try {
242
+ const pkgPath = require.resolve('@react-native-firebase/app/package.json', projectRoot ? { paths: [projectRoot] } : undefined);
243
+ const pkg = require(pkgPath);
244
+ const bom = pkg?.sdkVersions?.android?.firebase;
245
+ return typeof bom === 'string' && bom.length > 0 ? bom : undefined;
246
+ }
247
+ catch {
248
+ return undefined;
249
+ }
250
+ }
251
+ const DEPENDENCIES_BLOCK = /dependencies\s*\{/;
252
+ function addFirebaseMessagingDependency(contents, bomVersion) {
253
+ if (contents.includes(FIREBASE_DEP_MARKER)) {
254
+ return contents;
255
+ }
256
+ if (!DEPENDENCIES_BLOCK.test(contents)) {
257
+ throw new Error('[StreamVideo] Could not find a "dependencies { }" block in the app build.gradle ' +
258
+ 'to add the firebase-messaging compile dependency for the generated FCM service.');
259
+ }
260
+ const lines = ` ${FIREBASE_DEP_MARKER}\n` +
261
+ ` compileOnly(platform("com.google.firebase:firebase-bom:${bomVersion ?? FIREBASE_BOM_FALLBACK_VERSION}"))\n` +
262
+ ` compileOnly("${FIREBASE_MESSAGING_ARTIFACT}")`;
263
+ return contents.replace(DEPENDENCIES_BLOCK, (match) => `${match}\n${lines}`);
264
+ }
265
+ const withMessagingServiceGradle = (config, value) => {
266
+ return (0, config_plugins_1.withAppBuildGradle)(config, (gradleConfig) => {
267
+ const baseClassFqcn = resolveBaseClass(value, gradleConfig.modRequest.projectRoot);
268
+ if (!baseClassFqcn) {
269
+ return gradleConfig;
270
+ }
271
+ const bomVersion = resolveFirebaseBomVersion(gradleConfig.modRequest.projectRoot);
272
+ gradleConfig.modResults.contents = addFirebaseMessagingDependency(gradleConfig.modResults.contents, bomVersion);
273
+ return gradleConfig;
274
+ });
275
+ };
276
+ const withAndroidMessagingService = (config, props) => {
277
+ // The messaging-service override only matters for the ringing flow, skip it otherwise.
278
+ if (!props?.ringing) {
279
+ return config;
280
+ }
281
+ const value = props?.androidMessagingServiceBaseClass;
282
+ let updated = withGeneratedMessagingServiceFile(config, value);
283
+ updated = withMessagingServiceManifest(updated, value);
284
+ updated = withMessagingServiceGradle(updated, value);
285
+ return updated;
286
+ };
287
+ exports.default = withAndroidMessagingService;
@@ -17,6 +17,13 @@ RCT_EXTERN_METHOD(stop)
17
17
 
18
18
  RCT_EXTERN_METHOD(showAudioRoutePicker)
19
19
 
20
+ RCT_EXTERN_METHOD(getAudioDeviceStatus:(RCTPromiseResolveBlock)resolve
21
+ reject:(RCTPromiseRejectBlock)reject)
22
+
23
+ RCT_EXTERN_METHOD(chooseAudioDeviceEndpoint:(NSString *)id)
24
+
25
+ RCT_EXTERN_METHOD(reapplyAudioRoute)
26
+
20
27
  RCT_EXTERN_METHOD(setForceSpeakerphoneOn:(BOOL)enable)
21
28
 
22
29
  RCT_EXTERN_METHOD(setMicrophoneMute:(BOOL)enable)
@@ -17,6 +17,20 @@ enum DefaultAudioDevice {
17
17
  case earpiece
18
18
  }
19
19
 
20
+ /// An explicit output route chosen via the device picker.
21
+ ///
22
+ /// `nil` (no explicit pick) means the call uses the category-driven default
23
+ /// (`.defaultToSpeaker` when the default device is the speaker), which keeps the
24
+ /// default route headphone-aware. Once the user picks a device we drive the route
25
+ /// explicitly instead — `.defaultToSpeaker` is dropped so `overrideOutputAudioPort(.none)`
26
+ /// can reach the earpiece (with `.defaultToSpeaker` present it resolves to the speaker).
27
+ private enum OutputRouting {
28
+ case speaker
29
+ /// Built-in earpiece (the built-in mic uid), wired headset, or Bluetooth — all
30
+ /// reached via `overrideOutputAudioPort(.none)` + `setPreferredInput(port)`.
31
+ case input(uid: String)
32
+ }
33
+
20
34
  private enum Constants {
21
35
  /// Debounce interval for refreshing stereo playout state after audio route changes.
22
36
  ///
@@ -32,6 +46,14 @@ private enum Constants {
32
46
 
33
47
  private enum StreamInCallManagerEvents {
34
48
  static let audioInterruption = "StreamInCallManagerAudioInterruption"
49
+ static let audioDeviceChanged = "onAudioDeviceChanged"
50
+ }
51
+
52
+ /// Stable device-id scheme for the JS layer. The built-in speaker is synthetic; every
53
+ /// other device is keyed by its `AVAudioSessionPortDescription.uid` (the
54
+ /// built-in earpiece is the built-in mic input routed with `.none`).
55
+ private enum AudioDeviceId {
56
+ static let speaker = "speaker"
35
57
  }
36
58
 
37
59
  @objc(StreamInCallManager)
@@ -42,6 +64,9 @@ class StreamInCallManager: RCTEventEmitter {
42
64
  private var audioManagerActivated = false
43
65
  private var callAudioRole: CallAudioRole = .communicator
44
66
  private var defaultAudioDevice: DefaultAudioDevice = .speaker
67
+ /// The user's explicit output pick, or `nil` to use the category default.
68
+ /// Re-applied on every engine rebuild so the pick survives interruptions.
69
+ private var selectedOutput: OutputRouting?
45
70
  private var enableStereo: Bool = false
46
71
  private var previousVolume: Float = 0.75
47
72
 
@@ -101,7 +126,7 @@ class StreamInCallManager: RCTEventEmitter {
101
126
  }
102
127
 
103
128
  /// Builds the audio config for the current role/device and sets it as WebRTC's default.
104
- private func makeAudioConfiguration() -> RTCAudioSessionConfiguration {
129
+ private func makeAudioConfiguration(for routing: OutputRouting?) -> RTCAudioSessionConfiguration {
105
130
  let category: AVAudioSession.Category
106
131
  let mode: AVAudioSession.Mode
107
132
  let options: AVAudioSession.CategoryOptions
@@ -138,7 +163,14 @@ class StreamInCallManager: RCTEventEmitter {
138
163
  #endif
139
164
  category = .playAndRecord
140
165
  mode = .voiceChat
141
- options = defaultAudioDevice == .speaker ? [bluetoothOption, .defaultToSpeaker] : [bluetoothOption]
166
+
167
+ var mustSetDefaultToSpeaker = defaultAudioDevice == .speaker
168
+ if case .input(let uid) = routing, isBuiltInMicUid(uid) {
169
+ // the selected output is a built-in mic
170
+ // then we always can't use defaultToSpeaker
171
+ mustSetDefaultToSpeaker = false
172
+ }
173
+ options = mustSetDefaultToSpeaker ? [bluetoothOption, .defaultToSpeaker] : [bluetoothOption]
142
174
  }
143
175
 
144
176
  let rtcConfig = RTCAudioSessionConfiguration.webRTC()
@@ -162,16 +194,21 @@ class StreamInCallManager: RCTEventEmitter {
162
194
  func setup() {
163
195
  audioSessionQueue.async { [self] in
164
196
  let adm = getAudioDeviceModule()
197
+ selectedOutput = nil
198
+
199
+ // This path (no CallKit) owns audio-session activation itself, so the
200
+ // engine must be allowed to start. Restores availability in case a
201
+ // prior CallKit call had gated it off.
202
+ _ = adm.setEngineAvailability(.default)
165
203
 
166
204
  // Stereo is listener-only and applies live. Cleared by stop()'s reset().
167
205
  if callAudioRole == .listener && enableStereo {
168
206
  adm.setStereoPlayoutPreference(true)
169
207
  }
170
208
 
171
- let rtcConfig = makeAudioConfiguration()
209
+ let rtcConfig = makeAudioConfiguration(for: selectedOutput)
172
210
  log("Setup with category: \(rtcConfig.category), mode: \(rtcConfig.mode), options: \(rtcConfig.categoryOptions)")
173
211
 
174
- // Set category only — the sink owns setActive().
175
212
  let session = RTCAudioSession.sharedInstance()
176
213
  session.lockForConfiguration()
177
214
  defer { session.unlockForConfiguration() }
@@ -223,13 +260,16 @@ class StreamInCallManager: RCTEventEmitter {
223
260
  return
224
261
  }
225
262
 
226
- let rtcConfig = makeAudioConfiguration()
263
+ let rtcConfig = makeAudioConfiguration(for: selectedOutput)
227
264
  let session = RTCAudioSession.sharedInstance()
228
265
  session.lockForConfiguration()
229
266
  defer { session.unlockForConfiguration() }
230
267
  do {
231
- try session.setConfiguration(rtcConfig)
232
- try session.setActive(true)
268
+ try session.setConfiguration(rtcConfig, active: true)
269
+ // Re-apply the explicit pick (if any) so it survives the engine rebuild.
270
+ if let selectedOutput {
271
+ try applyOutputRouting(selectedOutput)
272
+ }
233
273
  log("engineWillEnable: applied category=\(rtcConfig.category) mode=\(rtcConfig.mode) activated=true")
234
274
  } catch {
235
275
  log("engineWillEnable error: \(String(describing: error))")
@@ -252,6 +292,21 @@ class StreamInCallManager: RCTEventEmitter {
252
292
  }
253
293
  }
254
294
 
295
+ private func clearOutputRouting() {
296
+ if Self.callingxOwnsSession() {
297
+ return
298
+ }
299
+ let session = RTCAudioSession.sharedInstance()
300
+ session.lockForConfiguration()
301
+ defer { session.unlockForConfiguration() }
302
+ do {
303
+ try session.overrideOutputAudioPort(.none)
304
+ try AVAudioSession.sharedInstance().setPreferredInput(nil)
305
+ } catch {
306
+ log("clearOutputRouting error: \(String(describing: error))")
307
+ }
308
+ }
309
+
255
310
  /// Runtime KVC lookup of `CallingxSessionOwnership.callingxOwnsSession`.
256
311
  /// `@stream-io/react-native-callingx` is an optional peer dep, so a direct
257
312
  /// Swift `import` is not safe
@@ -303,6 +358,7 @@ class StreamInCallManager: RCTEventEmitter {
303
358
  }
304
359
  let adm = getAudioDeviceModule()
305
360
  adm.reset()
361
+ clearOutputRouting()
306
362
  // Deactivate directly: the .didDisableAudioEngine sink is async and we cancel it below.
307
363
  applyConfigForEngineDisable()
308
364
  // Tear down the engine-observer subscription so a re-setup wires a fresh one.
@@ -313,6 +369,7 @@ class StreamInCallManager: RCTEventEmitter {
313
369
  stereoRefreshWorkItem = nil
314
370
  callAudioRole = .communicator
315
371
  defaultAudioDevice = .speaker
372
+ selectedOutput = nil
316
373
  enableStereo = false
317
374
  audioManagerActivated = false
318
375
  }
@@ -345,18 +402,21 @@ class StreamInCallManager: RCTEventEmitter {
345
402
 
346
403
  @objc(setForceSpeakerphoneOn:)
347
404
  func setForceSpeakerphoneOn(enable: Bool) {
348
- audioSessionQueue.async { [weak self] in
405
+ audioSessionQueue.async { [self] in
349
406
  let session = RTCAudioSession.sharedInstance()
350
407
  session.lockForConfiguration()
351
408
  defer {
352
409
  session.unlockForConfiguration()
353
410
  }
354
- let avAudioSession = AVAudioSession.sharedInstance()
355
411
  do {
356
- try avAudioSession.overrideOutputAudioPort(enable ? .speaker : .none)
357
- try avAudioSession.setActive(true)
412
+ if enable {
413
+ try applyOutputRouting(.speaker)
414
+ } else {
415
+ try session.overrideOutputAudioPort(.none)
416
+ try AVAudioSession.sharedInstance().setPreferredInput(nil)
417
+ }
358
418
  } catch {
359
- self?.log("Error setting speakerphone: \(error)")
419
+ self.log("Error setting speakerphone: \(error)")
360
420
  }
361
421
  }
362
422
  }
@@ -367,6 +427,174 @@ class StreamInCallManager: RCTEventEmitter {
367
427
  log("iOS does not support setMicrophoneMute()")
368
428
  }
369
429
 
430
+ // MARK: - Audio Device Picker
431
+
432
+ @objc(getAudioDeviceStatus:reject:)
433
+ func getAudioDeviceStatus(resolve: @escaping RCTPromiseResolveBlock,
434
+ reject: @escaping RCTPromiseRejectBlock) {
435
+ audioSessionQueue.async { [weak self] in
436
+ guard let self else {
437
+ resolve(["devices": [], "currentEndpointType": "Unknown"])
438
+ return
439
+ }
440
+ resolve(self.buildAudioDevicesState())
441
+ }
442
+ }
443
+
444
+ /// Switches the audio output to the device with the given id.
445
+ @objc(chooseAudioDeviceEndpoint:)
446
+ func chooseAudioDeviceEndpoint(id: String) {
447
+ audioSessionQueue.async { [self] in
448
+ guard callAudioRole == .communicator else {
449
+ log("chooseAudioDeviceEndpoint ignored: only supported in communicator role")
450
+ return
451
+ }
452
+
453
+ let routing: OutputRouting = id == AudioDeviceId.speaker ? .speaker : .input(uid: id)
454
+
455
+ let session = RTCAudioSession.sharedInstance()
456
+ session.lockForConfiguration()
457
+ defer { session.unlockForConfiguration() }
458
+ do {
459
+ // Reconfigure first so the live category matches the pick (e.g. the earpiece
460
+ // drops `.defaultToSpeaker`, otherwise overrideOutputAudioPort(.none) would
461
+ // resolve back to the speaker). Then drive the route.
462
+ try session.setConfiguration(makeAudioConfiguration(for: routing))
463
+ try applyOutputRouting(routing)
464
+ selectedOutput = routing
465
+ } catch {
466
+ // a failure leaves the previous route intact.
467
+ log("chooseAudioDeviceEndpoint error: \(String(describing: error))")
468
+ }
469
+ }
470
+ }
471
+
472
+ /// Re-applies the current output pick (`selectedOutput`) — category untouched, no setActive.
473
+ /// Called on interruption-end (via callingx's interruption event, forwarded from JS) to
474
+ /// restore a Bluetooth/wired route
475
+ @objc(reapplyAudioRoute)
476
+ func reapplyAudioRoute() {
477
+ audioSessionQueue.async { [self] in
478
+ guard callAudioRole == .communicator, let routing = selectedOutput else { return }
479
+ let session = RTCAudioSession.sharedInstance()
480
+ session.lockForConfiguration()
481
+ defer { session.unlockForConfiguration() }
482
+ do {
483
+ try applyOutputRouting(routing)
484
+ } catch {
485
+ log("reapplyAudioRoute error: \(String(describing: error))")
486
+ }
487
+ }
488
+ }
489
+
490
+ /// Whether `uid` is the built-in microphone (i.e. an earpiece pick, in our id scheme).
491
+ private func isBuiltInMicUid(_ uid: String) -> Bool {
492
+ AVAudioSession.sharedInstance().availableInputs?
493
+ .contains { $0.uid == uid && $0.portType == .builtInMic } ?? false
494
+ }
495
+
496
+ /// Drives the audio route. Throws if a session command fails, so callers can gate
497
+ /// committed state (e.g. `selectedOutput`) on the route actually being applied.
498
+ private func applyOutputRouting(_ routing: OutputRouting) throws {
499
+ let rtcSession = RTCAudioSession.sharedInstance()
500
+ let availableInputs = AVAudioSession.sharedInstance().availableInputs
501
+ switch routing {
502
+ case .speaker:
503
+ if let builtInMic = availableInputs?.first(where: { $0.portType == .builtInMic }) {
504
+ try rtcSession.setPreferredInput(builtInMic)
505
+ }
506
+ try rtcSession.overrideOutputAudioPort(.speaker)
507
+ case .input(let uid):
508
+ try rtcSession.overrideOutputAudioPort(.none)
509
+ if let port = availableInputs?.first(where: { $0.uid == uid }) {
510
+ try rtcSession.setPreferredInput(port)
511
+ } else {
512
+ log("applyOutputRouting: no input found for id \(uid)")
513
+ }
514
+ }
515
+ }
516
+
517
+ /// Canonical endpoint-type string shared with the JS layer.M ust match with the Android implementation.
518
+ private func endpointType(for portType: AVAudioSession.Port) -> String {
519
+ switch portType {
520
+ case .builtInSpeaker: return "Speaker"
521
+ case .builtInMic, .builtInReceiver: return "Earpiece"
522
+ case .headphones, .headsetMic: return "Wired Headset"
523
+ case .bluetoothA2DP, .bluetoothHFP, .bluetoothLE, .carAudio: return "Bluetooth Device"
524
+ default: return "Unknown"
525
+ }
526
+ }
527
+
528
+ private func hasExternalAudioDevice(_ session: AVAudioSession) -> Bool {
529
+ let external: Set<AVAudioSession.Port> = [
530
+ .headphones, .headsetMic, .bluetoothHFP, .bluetoothA2DP, .bluetoothLE, .carAudio,
531
+ ]
532
+ if session.availableInputs?.contains(where: { external.contains($0.portType) }) == true {
533
+ return true
534
+ }
535
+ return session.currentRoute.outputs.contains { external.contains($0.portType) }
536
+ }
537
+
538
+ private func buildAudioDevicesState() -> [String: Any] {
539
+ let session = AVAudioSession.sharedInstance()
540
+ let inputs = session.availableInputs ?? []
541
+ let hasExternal = hasExternalAudioDevice(session)
542
+
543
+ var devices: [[String: String]] = [
544
+ ["id": AudioDeviceId.speaker, "name": "Speaker", "type": "Speaker"]
545
+ ]
546
+ for port in inputs {
547
+ let isBuiltInMic = port.portType == .builtInMic
548
+ // Hide the earpiece when a wired/BT device is present — it can't be routed to
549
+ // while one is connected, so listing it would be a dead, duplicate option.
550
+ if isBuiltInMic && hasExternal { continue }
551
+ devices.append([
552
+ "id": port.uid,
553
+ "name": isBuiltInMic ? "Earpiece" : port.portName,
554
+ "type": endpointType(for: port.portType),
555
+ ])
556
+ }
557
+
558
+ let output = session.currentRoute.outputs.first
559
+ let currentEndpointType = output.map { endpointType(for: $0.portType) } ?? "Unknown"
560
+
561
+ // Output-only routes (e.g. wired headphones without a mic) never appear in
562
+ // availableInputs. Add the active output when no listed device already represents
563
+ // its endpoint type, so it stays visible and selectable in the picker.
564
+ if let output,
565
+ output.portType != .builtInSpeaker,
566
+ !devices.contains(where: { $0["type"] == currentEndpointType }) {
567
+ devices.append([
568
+ "id": output.uid,
569
+ "name": output.portName,
570
+ "type": currentEndpointType,
571
+ ])
572
+ }
573
+
574
+ let selectedDeviceId: String?
575
+ if output?.portType == .builtInSpeaker {
576
+ selectedDeviceId = AudioDeviceId.speaker
577
+ } else if let inputUid = session.currentRoute.inputs.first?.uid,
578
+ devices.contains(where: { $0["id"] == inputUid }) {
579
+ // The active input maps to a listed device (earpiece / wired / BT).
580
+ selectedDeviceId = inputUid
581
+ } else {
582
+ // Output is on a device whose active input differs from a listed one — e.g. BT is
583
+ // the output while the input stayed built-in mic. Match by the output's endpoint
584
+ // type so the picker highlights the actual output (not the earpiece).
585
+ selectedDeviceId = devices.first(where: { $0["type"] == currentEndpointType })?["id"]
586
+ }
587
+
588
+ var result: [String: Any] = [
589
+ "devices": devices,
590
+ "currentEndpointType": currentEndpointType,
591
+ ]
592
+ if let selectedDeviceId {
593
+ result["selectedDeviceId"] = selectedDeviceId
594
+ }
595
+ return result
596
+ }
597
+
370
598
  @objc
371
599
  func logAudioState() {
372
600
  log(getAudioStateLog())
@@ -580,7 +808,19 @@ class StreamInCallManager: RCTEventEmitter {
580
808
  }
581
809
 
582
810
  logAudioState()
583
-
811
+
812
+ // Notify JS of the updated device list / selection.
813
+ audioSessionQueue.async { [weak self] in
814
+ guard let self,
815
+ self.audioManagerActivated,
816
+ self.callAudioRole == .communicator,
817
+ !Self.callingxOwnsSession() else { return }
818
+ self.sendEvent(
819
+ withName: StreamInCallManagerEvents.audioDeviceChanged,
820
+ body: self.buildAudioDevicesState()
821
+ )
822
+ }
823
+
584
824
  // Route changes can arrive on arbitrary queues; ensure UI-safe work on main
585
825
  DispatchQueue.main.async { [weak self] in
586
826
  self?.updateProximityMonitoring()
@@ -616,7 +856,10 @@ class StreamInCallManager: RCTEventEmitter {
616
856
  // MARK: - RCTEventEmitter
617
857
 
618
858
  override func supportedEvents() -> [String]! {
619
- return [StreamInCallManagerEvents.audioInterruption]
859
+ return [
860
+ StreamInCallManagerEvents.audioInterruption,
861
+ StreamInCallManagerEvents.audioDeviceChanged,
862
+ ]
620
863
  }
621
864
 
622
865
  // MARK: - Helper Methods