@poolse/native 0.0.0-stage → 3.1.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.
- package/CHANGELOG.md +31 -0
- package/LICENSE +206 -0
- package/README.md +116 -2
- package/android/build.gradle +58 -0
- package/android/consumer-rules.pro +11 -0
- package/android/src/main/AndroidManifest.xml +46 -0
- package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
- package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
- package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
- package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
- package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
- package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
- package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
- package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
- package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
- package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
- package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
- package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
- package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
- package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
- package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
- package/app.plugin.js +5 -0
- package/dist/index.cjs +197 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +313 -0
- package/dist/index.d.ts +313 -0
- package/dist/index.js +161 -0
- package/dist/index.js.map +1 -0
- package/expo-module.config.json +11 -0
- package/ios/Core/CallCoreRuntime.swift +543 -0
- package/ios/Core/CallHttpClient.swift +213 -0
- package/ios/Core/CallMachine.swift +394 -0
- package/ios/Core/PORTS_READY.md +93 -0
- package/ios/Core/Ports.swift +238 -0
- package/ios/Core/SnapshotEncoding.swift +122 -0
- package/ios/Module/PoolseCallVideoView.swift +70 -0
- package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
- package/ios/Module/PoolseCallsModule.swift +150 -0
- package/ios/Platform/CallCore.swift +623 -0
- package/ios/Platform/CallKitController.swift +326 -0
- package/ios/Platform/CallPictureInPicture.swift +145 -0
- package/ios/Platform/LiveKitMediaPort.swift +798 -0
- package/ios/Platform/LiveKitVideoSurface.swift +68 -0
- package/ios/Platform/MessageNotifications.swift +163 -0
- package/ios/Platform/Ringback.swift +61 -0
- package/ios/Platform/VoipPush.swift +174 -0
- package/ios/PoolseCalls.podspec +68 -0
- package/package.json +52 -3
- package/plugin/index.js +42 -0
- package/plugin/package.json +1 -0
- package/plugin/withCallDelegate.js +35 -0
- package/plugin/withLockscreenCalls.js +84 -0
- package/plugin/withNativeCallMedia.js +19 -0
- package/plugin/withPictureInPicture.js +28 -0
- package/plugin/withRingback.js +86 -0
- package/src/expo-modules-core.d.ts +16 -0
- package/src/index.ts +564 -0
- package/src/react-shims.d.ts +22 -0
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
package dev.poolse.callcore.livekit
|
|
2
|
+
|
|
3
|
+
import android.Manifest
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.pm.PackageManager
|
|
6
|
+
import android.util.Log
|
|
7
|
+
import androidx.core.content.ContextCompat
|
|
8
|
+
import com.twilio.audioswitch.AudioDevice
|
|
9
|
+
import dev.poolse.callcore.CallSessionBundle
|
|
10
|
+
import dev.poolse.callcore.MediaPort
|
|
11
|
+
import dev.poolse.callcore.android.AudioOutput
|
|
12
|
+
import dev.poolse.callcore.android.CallVideoSource
|
|
13
|
+
import dev.poolse.callcore.android.CallVideoSurface
|
|
14
|
+
import dev.poolse.callcore.android.MediaEvents
|
|
15
|
+
import dev.poolse.callcore.android.MediaParticipant
|
|
16
|
+
import io.livekit.android.ConnectOptions
|
|
17
|
+
import io.livekit.android.LiveKit
|
|
18
|
+
import io.livekit.android.audio.AudioSwitchHandler
|
|
19
|
+
import io.livekit.android.events.DisconnectReason
|
|
20
|
+
import io.livekit.android.events.RoomEvent
|
|
21
|
+
import io.livekit.android.events.collect
|
|
22
|
+
import io.livekit.android.room.Room
|
|
23
|
+
import io.livekit.android.room.participant.ConnectionQuality
|
|
24
|
+
import io.livekit.android.room.participant.Participant
|
|
25
|
+
import io.livekit.android.room.track.CameraPosition
|
|
26
|
+
import io.livekit.android.room.track.LocalVideoTrack
|
|
27
|
+
import io.livekit.android.room.track.RemoteTrackPublication
|
|
28
|
+
import io.livekit.android.room.track.Track
|
|
29
|
+
import io.livekit.android.room.track.VideoTrack
|
|
30
|
+
import kotlinx.coroutines.CoroutineScope
|
|
31
|
+
import kotlinx.coroutines.Dispatchers
|
|
32
|
+
import kotlinx.coroutines.Job
|
|
33
|
+
import kotlinx.coroutines.SupervisorJob
|
|
34
|
+
import kotlinx.coroutines.cancel
|
|
35
|
+
import kotlinx.coroutines.delay
|
|
36
|
+
import kotlinx.coroutines.launch
|
|
37
|
+
import org.json.JSONObject
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The shipped [MediaPort], over LiveKit's native Android SDK. Wire it
|
|
41
|
+
* with [factory] in [dev.poolse.callcore.android.CallCoreConfig].
|
|
42
|
+
*
|
|
43
|
+
* This is the one adapter that depends on an external SFU SDK, so it
|
|
44
|
+
* lives in its own source set (`src/main/livekit`) kept off the core
|
|
45
|
+
* library's classpath. Lifecycle and signaling are not its concern — it
|
|
46
|
+
* joins a room with the server-minted token, publishes the mic (and
|
|
47
|
+
* camera for video), routes audio, and reports room transitions back
|
|
48
|
+
* through [MediaEvents]. The runtime decides everything else.
|
|
49
|
+
*
|
|
50
|
+
* Threading: every method is called on the main thread (the runtime's
|
|
51
|
+
* thread) and every coroutine runs on Main.immediate, so [room] is only
|
|
52
|
+
* ever touched on main. Coroutines still re-check that the room they
|
|
53
|
+
* captured is the current one — a join/leave may have replaced it
|
|
54
|
+
* while they were suspended.
|
|
55
|
+
*/
|
|
56
|
+
class LiveKitMediaPort(
|
|
57
|
+
private val context: Context,
|
|
58
|
+
private val events: MediaEvents,
|
|
59
|
+
) : MediaPort, CallVideoSource {
|
|
60
|
+
|
|
61
|
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
|
62
|
+
@Volatile private var room: Room? = null
|
|
63
|
+
private var eventJob: Job? = null
|
|
64
|
+
private var media: String = "audio"
|
|
65
|
+
// Speaker unless a headset is in: a video call, or a room (a drop-in
|
|
66
|
+
// room is held like a meeting, not to the ear).
|
|
67
|
+
private var loud = false
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The user's output choice for the CURRENT call: an output id
|
|
71
|
+
* (`speaker`, `earpiece`, `wired`, `bluetooth`) or [PRIVATE] — the
|
|
72
|
+
* best private route. null = automatic (see [resolve]).
|
|
73
|
+
*/
|
|
74
|
+
private var outputWanted: String? = null
|
|
75
|
+
|
|
76
|
+
/** The current room's last device list; a newcomer in it takes the call. */
|
|
77
|
+
private var knownDevices: List<AudioDevice>? = null
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The user's mute / camera choices for the CURRENT call. They survive
|
|
81
|
+
* a rejoin: /reconnect rebuilds the room, and blindly re-enabling the
|
|
82
|
+
* mic there went live while the UI still showed "muted". Reset only
|
|
83
|
+
* when the call ends ([leave]) or a different call joins.
|
|
84
|
+
*/
|
|
85
|
+
private var mutedWanted = false
|
|
86
|
+
private var cameraWanted: Boolean? = null
|
|
87
|
+
private var joinedCallId: String? = null
|
|
88
|
+
|
|
89
|
+
/** Our own link to the SFU, as last reported. */
|
|
90
|
+
private var localQuality = "unknown"
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Incoming video is switched off to keep the audio going (see
|
|
94
|
+
* [qualityChanged]). Survives a rejoin of the same call, like mute.
|
|
95
|
+
*/
|
|
96
|
+
private var videoPaused = false
|
|
97
|
+
private var pauseJob: Job? = null
|
|
98
|
+
private var resumeJob: Job? = null
|
|
99
|
+
/** Remote camera publications this port switched off, by sid. */
|
|
100
|
+
private val pausedSids = mutableSetOf<String>()
|
|
101
|
+
|
|
102
|
+
/** Live `<CallVideoView>` slots; rebound whenever what they show may have changed. */
|
|
103
|
+
private val surfaces = linkedSetOf<LiveKitVideoSurface>()
|
|
104
|
+
|
|
105
|
+
override fun join(bundle: CallSessionBundle) {
|
|
106
|
+
// Rejoin of the same call keeps the user's choices; so do choices
|
|
107
|
+
// made while this call was still connecting (joinedCallId null). A
|
|
108
|
+
// different call joining without a leave starts clean.
|
|
109
|
+
if (joinedCallId != null && bundle.callId != joinedCallId) resetWanted()
|
|
110
|
+
joinedCallId = bundle.callId
|
|
111
|
+
detach()
|
|
112
|
+
media = bundle.media
|
|
113
|
+
val wantsVideo = bundle.media == "video"
|
|
114
|
+
loud = wantsVideo || bundle.kind == "room"
|
|
115
|
+
val newRoom = LiveKit.create(appContext = context.applicationContext)
|
|
116
|
+
configureAudio(newRoom, loud)
|
|
117
|
+
// A 1:1/small call: never let the SFU pause a subscribed camera for
|
|
118
|
+
// "not visible" — a track whose view mounts late would stay black.
|
|
119
|
+
// (Renderers are still registered with visibility via addRenderer.)
|
|
120
|
+
newRoom.adaptiveStream = false
|
|
121
|
+
newRoom.dynacast = false
|
|
122
|
+
room = newRoom
|
|
123
|
+
refreshVideo() // surfaces re-initialise against the new room's EGL
|
|
124
|
+
eventJob = scope.launch { observe(newRoom) }
|
|
125
|
+
scope.launch {
|
|
126
|
+
val connected = runCatching {
|
|
127
|
+
newRoom.connect(bundle.livekitUrl, bundle.livekitToken, ConnectOptions(autoSubscribe = true))
|
|
128
|
+
}.onFailure {
|
|
129
|
+
Log.w(TAG, "connect failed", it)
|
|
130
|
+
if (room === newRoom) {
|
|
131
|
+
// Don't leave a half-open room (and its audio mode) behind.
|
|
132
|
+
eventJob?.cancel()
|
|
133
|
+
eventJob = null
|
|
134
|
+
room = null
|
|
135
|
+
refreshVideo()
|
|
136
|
+
teardown(newRoom)
|
|
137
|
+
events.onFailed()
|
|
138
|
+
}
|
|
139
|
+
}.isSuccess
|
|
140
|
+
if (!connected || room !== newRoom) return@launch
|
|
141
|
+
// Publishing failures must not fail the call: audio-only is a call.
|
|
142
|
+
runCatching { newRoom.localParticipant.setMicrophoneEnabled(!mutedWanted) }
|
|
143
|
+
.onFailure { Log.w(TAG, "microphone publish failed", it) }
|
|
144
|
+
if (cameraWanted ?: wantsVideo) enableCamera(newRoom, true)
|
|
145
|
+
reportLocalCamera(newRoom)
|
|
146
|
+
refreshVideo()
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private fun cameraGranted() =
|
|
151
|
+
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
|
|
152
|
+
PackageManager.PERMISSION_GRANTED
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Publish / unpublish the camera. Without the CAMERA grant a video
|
|
156
|
+
* call joins audio-only instead of failing; a later setCamera(true)
|
|
157
|
+
* after the user grants it publishes then.
|
|
158
|
+
*/
|
|
159
|
+
private suspend fun enableCamera(r: Room, on: Boolean) {
|
|
160
|
+
if (on && !cameraGranted()) {
|
|
161
|
+
Log.i(TAG, "CAMERA not granted: staying audio-only")
|
|
162
|
+
return
|
|
163
|
+
}
|
|
164
|
+
runCatching { r.localParticipant.setCameraEnabled(on) }
|
|
165
|
+
.onFailure { Log.w(TAG, "camera ${if (on) "publish" else "unpublish"} failed", it) }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The call is over for this device: drop the room AND the call's choices. */
|
|
169
|
+
override fun leave() {
|
|
170
|
+
detach()
|
|
171
|
+
resetWanted()
|
|
172
|
+
joinedCallId = null
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private fun resetWanted() {
|
|
176
|
+
mutedWanted = false
|
|
177
|
+
cameraWanted = null
|
|
178
|
+
outputWanted = null
|
|
179
|
+
pauseJob?.cancel()
|
|
180
|
+
resumeJob?.cancel()
|
|
181
|
+
pauseJob = null
|
|
182
|
+
resumeJob = null
|
|
183
|
+
videoPaused = false
|
|
184
|
+
localQuality = "unknown"
|
|
185
|
+
reportNetwork()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Drop the current room only (a rejoin replaces it). */
|
|
189
|
+
private fun detach() {
|
|
190
|
+
eventJob?.cancel()
|
|
191
|
+
eventJob = null
|
|
192
|
+
// Their timers belong to that room; the next one starts its own.
|
|
193
|
+
pauseJob?.cancel()
|
|
194
|
+
resumeJob?.cancel()
|
|
195
|
+
pauseJob = null
|
|
196
|
+
resumeJob = null
|
|
197
|
+
pausedSids.clear()
|
|
198
|
+
val r = room ?: return
|
|
199
|
+
room = null
|
|
200
|
+
// Unbind every view from this room's tracks BEFORE its EGL is released.
|
|
201
|
+
refreshVideo()
|
|
202
|
+
teardown(r)
|
|
203
|
+
events.onLocalCamera(false, null)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private fun teardown(r: Room) {
|
|
207
|
+
runCatching { r.disconnect() }
|
|
208
|
+
// disconnect() keeps the room's engine, capturer and audio handler
|
|
209
|
+
// alive for a later reconnect; this port never reuses a room, so
|
|
210
|
+
// release it or every call leaks a PeerConnectionFactory.
|
|
211
|
+
runCatching { r.release() }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
override fun setMuted(muted: Boolean) {
|
|
215
|
+
mutedWanted = muted
|
|
216
|
+
val r = room ?: return
|
|
217
|
+
scope.launch { runCatching { r.localParticipant.setMicrophoneEnabled(!muted) } }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
override fun setCamera(on: Boolean) {
|
|
221
|
+
cameraWanted = on
|
|
222
|
+
val r = room ?: return
|
|
223
|
+
scope.launch {
|
|
224
|
+
enableCamera(r, on)
|
|
225
|
+
if (room !== r) return@launch
|
|
226
|
+
reportLocalCamera(r)
|
|
227
|
+
refreshVideo()
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Front ↔ back on the published camera track. */
|
|
232
|
+
override fun switchCamera() {
|
|
233
|
+
val r = room ?: return
|
|
234
|
+
val track = localCameraTrack(r) ?: return
|
|
235
|
+
val next = if (track.options.position == CameraPosition.BACK) CameraPosition.FRONT else CameraPosition.BACK
|
|
236
|
+
runCatching { track.switchCamera(null, next) }.onFailure { Log.w(TAG, "switchCamera failed", it) }
|
|
237
|
+
// The capturer switches asynchronously and updates the options when
|
|
238
|
+
// done: report (and re-mirror the self view) once it has.
|
|
239
|
+
scope.launch {
|
|
240
|
+
delay(SWITCH_SETTLE_MS)
|
|
241
|
+
if (room !== r) return@launch
|
|
242
|
+
reportLocalCamera(r)
|
|
243
|
+
refreshVideo()
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ── video ───────────────────────────────────────────────────────────
|
|
248
|
+
|
|
249
|
+
override fun createVideoSurface(context: Context): CallVideoSurface =
|
|
250
|
+
LiveKitVideoSurface(context, this).also { surfaces += it }
|
|
251
|
+
|
|
252
|
+
internal fun unregister(surface: LiveKitVideoSurface) { surfaces -= surface }
|
|
253
|
+
|
|
254
|
+
internal fun currentRoom(): Room? = room
|
|
255
|
+
|
|
256
|
+
private fun refreshVideo() {
|
|
257
|
+
for (s in surfaces.toList()) s.rebind()
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
private fun localCameraTrack(r: Room): LocalVideoTrack? =
|
|
261
|
+
r.localParticipant.getTrackPublication(Track.Source.CAMERA)
|
|
262
|
+
?.takeIf { !it.muted }?.track as? LocalVideoTrack
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The camera track a view should show: the local one, or the remote
|
|
266
|
+
* participant's — only once it is published, SUBSCRIBED and unmuted.
|
|
267
|
+
*/
|
|
268
|
+
internal fun cameraTrack(participantId: String?, local: Boolean): VideoTrack? {
|
|
269
|
+
val r = room ?: return null
|
|
270
|
+
if (local) return localCameraTrack(r)
|
|
271
|
+
val p = r.remoteParticipants.values.firstOrNull { it.identity?.value == participantId } ?: return null
|
|
272
|
+
return remoteCamera(p)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private fun remoteCamera(p: Participant): VideoTrack? {
|
|
276
|
+
// Paused: no picture to draw — the avatar shows, with the reason.
|
|
277
|
+
if (videoPaused) return null
|
|
278
|
+
val pub = p.getTrackPublication(Track.Source.CAMERA) as? RemoteTrackPublication ?: return null
|
|
279
|
+
if (!pub.subscribed || pub.muted) return null
|
|
280
|
+
return pub.track as? VideoTrack
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** `front` | `back` of the published local camera, or null when none. */
|
|
284
|
+
internal fun cameraFacing(): String? {
|
|
285
|
+
val r = room ?: return null
|
|
286
|
+
return when (localCameraTrack(r)?.options?.position) {
|
|
287
|
+
CameraPosition.FRONT -> "front"
|
|
288
|
+
CameraPosition.BACK -> "back"
|
|
289
|
+
null -> null
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private fun reportLocalCamera(r: Room) {
|
|
294
|
+
if (room !== r) return
|
|
295
|
+
val on = localCameraTrack(r) != null
|
|
296
|
+
events.onLocalCamera(on, if (on) cameraFacing() else null)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
override fun setSpeaker(on: Boolean) {
|
|
300
|
+
outputWanted = if (on) SPEAKER else PRIVATE
|
|
301
|
+
val handler = room?.audioHandler as? AudioSwitchHandler ?: return
|
|
302
|
+
applyRoute(handler)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
override fun setAudioOutput(id: String) {
|
|
306
|
+
outputWanted = id
|
|
307
|
+
val handler = room?.audioHandler as? AudioSwitchHandler ?: return
|
|
308
|
+
applyRoute(handler)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ── audio routing ───────────────────────────────────────────────────
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Seed AudioSwitch's own order (it starts during connect, before any
|
|
315
|
+
* choice is applied): a connected headset or Bluetooth device first,
|
|
316
|
+
* then the earpiece for voice or the speaker for video.
|
|
317
|
+
*/
|
|
318
|
+
private fun configureAudio(r: Room, video: Boolean) {
|
|
319
|
+
val handler = r.audioHandler as? AudioSwitchHandler ?: return
|
|
320
|
+
knownDevices = null
|
|
321
|
+
handler.preferredDeviceList = if (video) {
|
|
322
|
+
listOf(
|
|
323
|
+
AudioDevice.BluetoothHeadset::class.java,
|
|
324
|
+
AudioDevice.WiredHeadset::class.java,
|
|
325
|
+
AudioDevice.Speakerphone::class.java,
|
|
326
|
+
AudioDevice.Earpiece::class.java,
|
|
327
|
+
)
|
|
328
|
+
} else {
|
|
329
|
+
listOf(
|
|
330
|
+
AudioDevice.BluetoothHeadset::class.java,
|
|
331
|
+
AudioDevice.WiredHeadset::class.java,
|
|
332
|
+
AudioDevice.Earpiece::class.java,
|
|
333
|
+
AudioDevice.Speakerphone::class.java,
|
|
334
|
+
)
|
|
335
|
+
}
|
|
336
|
+
handler.audioDeviceChangeListener = listener@{ devices, selected ->
|
|
337
|
+
if (room?.audioHandler !== handler) return@listener
|
|
338
|
+
// Putting on a headset or connecting Bluetooth mid-call moves the
|
|
339
|
+
// call to it, whatever was picked before — as the dialer does. The
|
|
340
|
+
// first list of a room is not "new": a choice made while
|
|
341
|
+
// connecting must survive it.
|
|
342
|
+
val known = knownDevices
|
|
343
|
+
if (known != null && devices.any { it.isExternal() && it !in known }) outputWanted = null
|
|
344
|
+
knownDevices = devices
|
|
345
|
+
val target = resolve(devices)
|
|
346
|
+
if (target != null && target != selected) handler.selectDevice(target)
|
|
347
|
+
report(handler, devices, handler.selectedAudioDevice ?: selected)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private fun applyRoute(handler: AudioSwitchHandler) {
|
|
352
|
+
val devices = handler.availableAudioDevices
|
|
353
|
+
resolve(devices)?.let { if (it != handler.selectedAudioDevice) handler.selectDevice(it) }
|
|
354
|
+
report(handler, devices, handler.selectedAudioDevice)
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Where the call should play. A chosen device while it is connected
|
|
359
|
+
* (it is forgotten once it goes); otherwise a connected headset or
|
|
360
|
+
* Bluetooth device, then the speaker for video or the earpiece for
|
|
361
|
+
* voice — never the speaker over earbuds the user put on.
|
|
362
|
+
*/
|
|
363
|
+
private fun resolve(devices: List<AudioDevice>): AudioDevice? {
|
|
364
|
+
val wanted = outputWanted
|
|
365
|
+
if (wanted != null && wanted != PRIVATE) {
|
|
366
|
+
devices.firstOrNull { idOf(it) == wanted }?.let { return it }
|
|
367
|
+
outputWanted = null
|
|
368
|
+
}
|
|
369
|
+
val external = devices.firstOrNull { it is AudioDevice.BluetoothHeadset }
|
|
370
|
+
?: devices.firstOrNull { it is AudioDevice.WiredHeadset }
|
|
371
|
+
val earpiece = devices.firstOrNull { it is AudioDevice.Earpiece }
|
|
372
|
+
val speaker = devices.firstOrNull { it is AudioDevice.Speakerphone }
|
|
373
|
+
return when {
|
|
374
|
+
external != null -> external
|
|
375
|
+
outputWanted == PRIVATE -> earpiece ?: speaker
|
|
376
|
+
loud -> speaker ?: earpiece
|
|
377
|
+
else -> earpiece ?: speaker
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
private fun report(handler: AudioSwitchHandler, devices: List<AudioDevice>, selected: AudioDevice?) {
|
|
382
|
+
if (room?.audioHandler !== handler) return
|
|
383
|
+
events.onAudioRoute(routeOf(selected))
|
|
384
|
+
events.onAudioOutputs(
|
|
385
|
+
devices.map { AudioOutput(id = idOf(it), kind = routeOf(it), name = nameOf(it)) },
|
|
386
|
+
selected?.let(::idOf),
|
|
387
|
+
)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private fun AudioDevice.isExternal() =
|
|
391
|
+
this is AudioDevice.BluetoothHeadset || this is AudioDevice.WiredHeadset
|
|
392
|
+
|
|
393
|
+
private fun idOf(d: AudioDevice): String = when (d) {
|
|
394
|
+
is AudioDevice.Speakerphone -> SPEAKER
|
|
395
|
+
is AudioDevice.Earpiece -> "earpiece"
|
|
396
|
+
is AudioDevice.WiredHeadset -> "wired"
|
|
397
|
+
// AudioSwitch carries one Bluetooth device: the active headset.
|
|
398
|
+
is AudioDevice.BluetoothHeadset -> "bluetooth"
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** The Bluetooth device's own name; plain defaults for the rest. */
|
|
402
|
+
private fun nameOf(d: AudioDevice): String = when (d) {
|
|
403
|
+
is AudioDevice.Speakerphone -> "Speaker"
|
|
404
|
+
is AudioDevice.Earpiece -> "Phone"
|
|
405
|
+
is AudioDevice.WiredHeadset -> "Headphones"
|
|
406
|
+
is AudioDevice.BluetoothHeadset -> d.name.ifBlank { "Bluetooth" }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private fun routeOf(d: AudioDevice?): String = when (d) {
|
|
410
|
+
is AudioDevice.Speakerphone -> "speaker"
|
|
411
|
+
is AudioDevice.BluetoothHeadset -> "bluetooth"
|
|
412
|
+
is AudioDevice.WiredHeadset -> "headset"
|
|
413
|
+
is AudioDevice.Earpiece -> "earpiece"
|
|
414
|
+
null -> if (loud) "speaker" else "earpiece"
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ── room events ─────────────────────────────────────────────────────
|
|
418
|
+
|
|
419
|
+
private suspend fun observe(room: Room) {
|
|
420
|
+
room.events.collect { event ->
|
|
421
|
+
if (this.room !== room) return@collect
|
|
422
|
+
when (event) {
|
|
423
|
+
is RoomEvent.Connected -> {
|
|
424
|
+
(room.audioHandler as? AudioSwitchHandler)?.let(::applyRoute)
|
|
425
|
+
events.onConnected()
|
|
426
|
+
// Somebody may already be in (a late join, or a callee who
|
|
427
|
+
// answered before our media came up): they will not "connect".
|
|
428
|
+
if (room.remoteParticipants.isNotEmpty()) events.onRemoteJoined()
|
|
429
|
+
emit(room)
|
|
430
|
+
refreshVideo()
|
|
431
|
+
}
|
|
432
|
+
// LiveKit is resuming the SAME session (ICE restart / signal
|
|
433
|
+
// resume). Only reflect it: tearing the room down here fought
|
|
434
|
+
// its own recovery and turned every network blip into a rejoin.
|
|
435
|
+
is RoomEvent.Reconnecting -> events.onReconnecting()
|
|
436
|
+
is RoomEvent.Reconnected -> events.onRecovered()
|
|
437
|
+
// LiveKit gave up (or the server removed us). Our own leave()
|
|
438
|
+
// never gets here — the collector is cancelled first.
|
|
439
|
+
is RoomEvent.Disconnected -> {
|
|
440
|
+
if (event.reason != DisconnectReason.CLIENT_INITIATED) events.onLost()
|
|
441
|
+
}
|
|
442
|
+
is RoomEvent.ParticipantConnected -> { events.onRemoteJoined(); emit(room); refreshVideo() }
|
|
443
|
+
// Anything that can make a camera appear, vanish or freeze:
|
|
444
|
+
// update the roster's cameraOn, the local camera state, and
|
|
445
|
+
// rebind every video view.
|
|
446
|
+
is RoomEvent.ParticipantDisconnected,
|
|
447
|
+
is RoomEvent.TrackSubscribed,
|
|
448
|
+
is RoomEvent.TrackUnsubscribed,
|
|
449
|
+
is RoomEvent.TrackMuted,
|
|
450
|
+
is RoomEvent.TrackUnmuted,
|
|
451
|
+
is RoomEvent.TrackPublished,
|
|
452
|
+
is RoomEvent.TrackUnpublished,
|
|
453
|
+
is RoomEvent.LocalTrackSubscribed -> {
|
|
454
|
+
if (videoPaused) applyVideoPause(room)
|
|
455
|
+
emit(room)
|
|
456
|
+
reportLocalCamera(room)
|
|
457
|
+
refreshVideo()
|
|
458
|
+
}
|
|
459
|
+
is RoomEvent.ConnectionQualityChanged -> {
|
|
460
|
+
qualityChanged(room)
|
|
461
|
+
emit(room)
|
|
462
|
+
}
|
|
463
|
+
is RoomEvent.ActiveSpeakersChanged,
|
|
464
|
+
is RoomEvent.ParticipantMetadataChanged,
|
|
465
|
+
is RoomEvent.ParticipantAttributesChanged -> emit(room)
|
|
466
|
+
else -> Unit
|
|
467
|
+
}
|
|
468
|
+
Unit
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** The REMOTE roster — the local participant is never included. */
|
|
473
|
+
private fun emit(room: Room) {
|
|
474
|
+
events.onParticipants(
|
|
475
|
+
room.remoteParticipants.values.map {
|
|
476
|
+
val identity = it.identity?.value ?: ""
|
|
477
|
+
MediaParticipant(
|
|
478
|
+
identity = identity,
|
|
479
|
+
speaking = it.isSpeaking,
|
|
480
|
+
muted = !it.isMicrophoneEnabled(),
|
|
481
|
+
// Video, not avatar, only when there is a frame to draw:
|
|
482
|
+
// published, subscribed and unmuted.
|
|
483
|
+
cameraOn = remoteCamera(it) != null,
|
|
484
|
+
connectionQuality = wire(it.connectionQuality),
|
|
485
|
+
externalId = externalIdOf(it) ?: identity,
|
|
486
|
+
)
|
|
487
|
+
},
|
|
488
|
+
)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** The host's own user id, if the server put it in attributes/metadata. */
|
|
492
|
+
// ── connection quality ──────────────────────────────────────────────
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Our link went weak or came back. Weak for a while on a call with
|
|
496
|
+
* video coming in: switch that video off so the audio keeps going —
|
|
497
|
+
* the way FaceTime falls back — and bring it back once the link has
|
|
498
|
+
* been good for a while. Brief dips change nothing.
|
|
499
|
+
*/
|
|
500
|
+
private fun qualityChanged(r: Room) {
|
|
501
|
+
if (room !== r) return
|
|
502
|
+
val q = wire(r.localParticipant.connectionQuality)
|
|
503
|
+
if (q == "poor" || q == "lost") {
|
|
504
|
+
resumeJob?.cancel()
|
|
505
|
+
resumeJob = null
|
|
506
|
+
if (!videoPaused && pauseJob == null && hasRemoteVideo(r)) {
|
|
507
|
+
pauseJob = scope.launch {
|
|
508
|
+
delay(PAUSE_VIDEO_AFTER_MS)
|
|
509
|
+
pauseJob = null
|
|
510
|
+
if (room === r) setVideoPaused(r, true)
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
} else if (q == "good") {
|
|
514
|
+
pauseJob?.cancel()
|
|
515
|
+
pauseJob = null
|
|
516
|
+
if (videoPaused && resumeJob == null) {
|
|
517
|
+
resumeJob = scope.launch {
|
|
518
|
+
delay(RESUME_VIDEO_AFTER_MS)
|
|
519
|
+
resumeJob = null
|
|
520
|
+
if (room === r) setVideoPaused(r, false)
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
if (q != localQuality) {
|
|
525
|
+
localQuality = q
|
|
526
|
+
reportNetwork()
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
private fun hasRemoteVideo(r: Room) =
|
|
531
|
+
r.remoteParticipants.values.any { it.getTrackPublication(Track.Source.CAMERA) != null }
|
|
532
|
+
|
|
533
|
+
private fun setVideoPaused(r: Room, paused: Boolean) {
|
|
534
|
+
Log.i(TAG, "incoming video ${if (paused) "paused" else "resumed"} quality=$localQuality")
|
|
535
|
+
videoPaused = paused
|
|
536
|
+
applyVideoPause(r)
|
|
537
|
+
refreshVideo()
|
|
538
|
+
emit(r)
|
|
539
|
+
reportNetwork()
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Every remote camera on or off to match [videoPaused] — including one
|
|
544
|
+
* published after the pause began. Each publication is switched once:
|
|
545
|
+
* this runs on every track event, and re-sending the setting each time
|
|
546
|
+
* would only feed more events.
|
|
547
|
+
*/
|
|
548
|
+
private fun applyVideoPause(r: Room) {
|
|
549
|
+
val pubs = r.remoteParticipants.values.mapNotNull {
|
|
550
|
+
it.getTrackPublication(Track.Source.CAMERA) as? RemoteTrackPublication
|
|
551
|
+
}
|
|
552
|
+
if (videoPaused) {
|
|
553
|
+
for (pub in pubs) if (pausedSids.add(pub.sid)) runCatching { pub.setEnabled(false) }
|
|
554
|
+
} else {
|
|
555
|
+
for (pub in pubs) if (pausedSids.remove(pub.sid)) runCatching { pub.setEnabled(true) }
|
|
556
|
+
pausedSids.clear()
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
private fun reportNetwork() = events.onNetwork(localQuality, videoPaused)
|
|
561
|
+
|
|
562
|
+
private fun externalIdOf(p: Participant): String? =
|
|
563
|
+
runCatching { p.attributes["external_id"] }.getOrNull()?.ifEmpty { null }
|
|
564
|
+
?: p.metadata?.let { m ->
|
|
565
|
+
runCatching { JSONObject(m).optString("external_id", "") }.getOrNull()?.ifEmpty { null }
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
fun dispose() {
|
|
569
|
+
leave()
|
|
570
|
+
for (s in surfaces.toList()) s.release()
|
|
571
|
+
scope.cancel()
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
companion object {
|
|
575
|
+
private const val TAG = "PoolseLiveKit"
|
|
576
|
+
private const val SWITCH_SETTLE_MS = 600L
|
|
577
|
+
private const val SPEAKER = "speaker"
|
|
578
|
+
private const val PRIVATE = "private"
|
|
579
|
+
|
|
580
|
+
/** Weak this long before incoming video is paused; good this long before it is back. */
|
|
581
|
+
private const val PAUSE_VIDEO_AFTER_MS = 6_000L
|
|
582
|
+
private const val RESUME_VIDEO_AFTER_MS = 10_000L
|
|
583
|
+
|
|
584
|
+
fun wire(q: ConnectionQuality): String = when (q) {
|
|
585
|
+
ConnectionQuality.EXCELLENT, ConnectionQuality.GOOD -> "good"
|
|
586
|
+
ConnectionQuality.POOR -> "poor"
|
|
587
|
+
ConnectionQuality.LOST -> "lost"
|
|
588
|
+
else -> "unknown"
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** Pass as `mediaFactory` in CallCoreConfig. */
|
|
592
|
+
val factory: (Context, MediaEvents) -> MediaPort = { ctx, ev -> LiveKitMediaPort(ctx, ev) }
|
|
593
|
+
}
|
|
594
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
package dev.poolse.callcore.livekit
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.util.Log
|
|
5
|
+
import android.view.View
|
|
6
|
+
import dev.poolse.callcore.android.CallVideoSurface
|
|
7
|
+
import io.livekit.android.renderer.TextureViewRenderer
|
|
8
|
+
import io.livekit.android.room.Room
|
|
9
|
+
import io.livekit.android.room.track.VideoTrack
|
|
10
|
+
import livekit.org.webrtc.RendererCommon
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A [CallVideoSurface] over LiveKit's [TextureViewRenderer]. TextureView,
|
|
14
|
+
* not SurfaceView: a local picture-in-picture overlapping a full-screen
|
|
15
|
+
* remote composes like any view, with no SurfaceView z-order fights.
|
|
16
|
+
*
|
|
17
|
+
* The renderer is initialised against the CURRENT room's EGL context
|
|
18
|
+
* ([Room.initVideoRenderer]); a rejoin builds a new room, so [rebind]
|
|
19
|
+
* re-initialises it. Tracks are attached with [VideoTrack.addRenderer]
|
|
20
|
+
* — for a remote track that registers the view's visibility with the
|
|
21
|
+
* SDK, so adaptive stream (if ever enabled) resumes the track as soon as
|
|
22
|
+
* the view is on screen instead of keeping it paused.
|
|
23
|
+
*
|
|
24
|
+
* Main thread only, like the port that owns it.
|
|
25
|
+
*/
|
|
26
|
+
internal class LiveKitVideoSurface(
|
|
27
|
+
context: Context,
|
|
28
|
+
private val port: LiveKitMediaPort,
|
|
29
|
+
) : CallVideoSurface {
|
|
30
|
+
|
|
31
|
+
private val renderer = TextureViewRenderer(context)
|
|
32
|
+
override val view: View get() = renderer
|
|
33
|
+
|
|
34
|
+
private var initRoom: Room? = null
|
|
35
|
+
private var track: VideoTrack? = null
|
|
36
|
+
private var released = false
|
|
37
|
+
|
|
38
|
+
private var participantId: String? = null
|
|
39
|
+
private var local = false
|
|
40
|
+
private var mirror: Boolean? = null
|
|
41
|
+
private var fit = "cover"
|
|
42
|
+
|
|
43
|
+
override fun configure(participantId: String?, local: Boolean, mirror: Boolean?, fit: String) {
|
|
44
|
+
this.participantId = participantId
|
|
45
|
+
this.local = local
|
|
46
|
+
this.mirror = mirror
|
|
47
|
+
this.fit = fit
|
|
48
|
+
rebind()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Re-resolve the track (and the room) this slot should show. */
|
|
52
|
+
fun rebind() {
|
|
53
|
+
if (released) return
|
|
54
|
+
val room = port.currentRoom()
|
|
55
|
+
if (room !== initRoom) {
|
|
56
|
+
// Detach from the old room's track BEFORE its EGL goes away.
|
|
57
|
+
detachTrack()
|
|
58
|
+
if (initRoom != null) runCatching { renderer.release() }
|
|
59
|
+
initRoom = null
|
|
60
|
+
if (room != null) {
|
|
61
|
+
runCatching { room.initVideoRenderer(renderer); initRoom = room }
|
|
62
|
+
.onFailure { Log.w(TAG, "initVideoRenderer failed", it) }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
val next = if (initRoom != null) port.cameraTrack(participantId, local) else null
|
|
67
|
+
if (next !== track) {
|
|
68
|
+
detachTrack()
|
|
69
|
+
if (next != null) {
|
|
70
|
+
runCatching { next.addRenderer(renderer); track = next }
|
|
71
|
+
.onFailure { Log.w(TAG, "addRenderer failed", it) }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// No camera: hide the renderer so its last frozen frame never shows;
|
|
75
|
+
// the UI draws the avatar from the snapshot's cameraOn.
|
|
76
|
+
renderer.visibility = if (track != null) View.VISIBLE else View.INVISIBLE
|
|
77
|
+
if (initRoom != null) {
|
|
78
|
+
runCatching {
|
|
79
|
+
renderer.setMirror(mirror ?: (local && port.cameraFacing() != "back"))
|
|
80
|
+
renderer.setScalingType(
|
|
81
|
+
if (fit == "contain") RendererCommon.ScalingType.SCALE_ASPECT_FIT
|
|
82
|
+
else RendererCommon.ScalingType.SCALE_ASPECT_FILL,
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private fun detachTrack() {
|
|
89
|
+
val t = track ?: return
|
|
90
|
+
track = null
|
|
91
|
+
runCatching { t.removeRenderer(renderer) }
|
|
92
|
+
runCatching { renderer.clearImage() }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
override fun release() {
|
|
96
|
+
if (released) return
|
|
97
|
+
released = true
|
|
98
|
+
detachTrack()
|
|
99
|
+
if (initRoom != null) runCatching { renderer.release() }
|
|
100
|
+
initRoom = null
|
|
101
|
+
port.unregister(this)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private companion object {
|
|
105
|
+
const val TAG = "PoolseCallVideo"
|
|
106
|
+
}
|
|
107
|
+
}
|