169 lines · 7.2 KB · KotlinRaw
package com.cottondb.callingimport android.content.Contextimport android.media.AudioDeviceInfoimport android.media.AudioManagerimport android.media.ToneGeneratorimport android.os.Buildimport android.os.Handlerimport android.os.Looperimport kotlinx.serialization.json.JsonElementimport okhttp3.OkHttpClientimport okhttp3.Requestimport okhttp3.Responseimport okhttp3.WebSocketimport okhttp3.WebSocketListenerimport java.util.concurrent.TimeUnit/** * The room's socket over OkHttp (iOS: WebSocketCallSocket.swift): the room credential as its Bearer, each text frame * to `received` and a close nobody asked for to `closed`, both on the main thread; frames handed before it opens go * once it does. A stale socket's frames never reach the engine (it checks its own generation too). */class RoomSocket(private val log: CallLog) : CallSocketPort { private val client = OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS).build() private val main = Handler(Looper.getMainLooper()) private var socket: WebSocket? = null private var open = false private val queued = mutableListOf<String>() override fun open(url: String, credential: String, received: (JsonElement) -> Unit, closed: () -> Unit) { close() val request = Request.Builder().url(url).header("Authorization", "Bearer $credential").build() lateinit var mine: WebSocket mine = client.newWebSocket(request, object : WebSocketListener() { override fun onOpen(webSocket: WebSocket, response: Response) = main.post { if (socket !== mine) return@post open = true queued.forEach { mine.send(it) } queued.clear() }.let {} override fun onMessage(webSocket: WebSocket, text: String) = main.post { if (socket === mine) CallCenter.frame(text)?.let(received) ?: log.i("calls socket: a frame that is no JSON") }.let {} override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { webSocket.close(1000, null) main.post { if (socket === mine) { socket = null; open = false; closed() } } } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = main.post { log.i("calls socket: $t") if (socket === mine) { socket = null; open = false; closed() } }.let {} }) socket = mine } override fun send(frame: JsonElement) { val text = frame.toString() val socket = socket if (socket != null && open) socket.send(text) else queued += text } override fun close() { socket?.close(1000, null) socket = null open = false queued.clear() }}/** * The audio route for a call (iOS: CallAudioSession): communication mode while a call holds it, the earpiece for a * voice call and the loudspeaker for a video call, as a phone does, and the loudspeaker toggled by the person. On * Android 12 and later a Bluetooth device or headphones are routes too ([routes], [choose]): a headset that connects * during a call is offered at once, and a Bluetooth one is chosen when the call starts with it connected. */class CallAudio(context: Context) : CallAudioPort { private val audio = context.getSystemService(AudioManager::class.java) private var changed: (() -> Unit)? = null private val devices = object : android.media.AudioDeviceCallback() { override fun onAudioDevicesAdded(addedDevices: Array<out AudioDeviceInfo>?) { changed?.invoke() } override fun onAudioDevicesRemoved(removedDevices: Array<out AudioDeviceInfo>?) { changed?.invoke() } } override fun watch(changed: () -> Unit) { this.changed = changed runCatching { audio.registerAudioDeviceCallback(devices, Handler(Looper.getMainLooper())) } } override fun routes(): List<AudioRoute> { if (Build.VERSION.SDK_INT < 31) return listOf(AudioRoute(EARPIECE, "phone"), AudioRoute(SPEAKER, "speaker")) return audio.availableCommunicationDevices.mapNotNull { routeOf(it) }.distinctBy { it.id } } override fun current(): String? = if (Build.VERSION.SDK_INT >= 31) audio.communicationDevice?.let { routeOf(it)?.id } else null override fun choose(id: String) { if (Build.VERSION.SDK_INT < 31) return setSpeaker(id == SPEAKER) audio.availableCommunicationDevices.firstOrNull { routeOf(it)?.id == id }?.let { audio.setCommunicationDevice(it) } } private fun routeOf(device: AudioDeviceInfo): AudioRoute? = when (device.type) { AudioDeviceInfo.TYPE_BUILTIN_EARPIECE -> AudioRoute(EARPIECE, "phone") AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> AudioRoute(SPEAKER, "speaker") AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_WIRED_HEADPHONES, AudioDeviceInfo.TYPE_USB_HEADSET -> AudioRoute("wired:${device.id}", "wired") AudioDeviceInfo.TYPE_BLUETOOTH_SCO, AudioDeviceInfo.TYPE_BLE_HEADSET -> AudioRoute("bt:${device.address.ifEmpty { device.id.toString() }}", "bluetooth", device.productName?.toString()) else -> null } private companion object { const val EARPIECE = "phone" const val SPEAKER = "speaker" } override fun configure(video: Boolean) { audio.mode = AudioManager.MODE_IN_COMMUNICATION // A Bluetooth headset already connected takes the call, as a phone call does; else the earpiece or, for video, the loudspeaker. val headset = routes().firstOrNull { it.kind == "bluetooth" } ?: routes().firstOrNull { it.kind == "wired" } if (headset != null && Build.VERSION.SDK_INT >= 31) choose(headset.id) else setSpeaker(video) } override fun stop() { setSpeaker(false) if (Build.VERSION.SDK_INT >= 31) audio.clearCommunicationDevice() audio.mode = AudioManager.MODE_NORMAL } override fun setSpeaker(on: Boolean) { if (Build.VERSION.SDK_INT >= 31) { val wanted = if (on) AudioDeviceInfo.TYPE_BUILTIN_SPEAKER else AudioDeviceInfo.TYPE_BUILTIN_EARPIECE audio.availableCommunicationDevices.firstOrNull { it.type == wanted }?.let { audio.setCommunicationDevice(it) } ?: if (!on) audio.clearCommunicationDevice() else Unit } else { @Suppress("DEPRECATION") audio.isSpeakerphoneOn = on } }}/** The ringback heard while the other phone rings: 440 and 480 Hz, two seconds on and four off (iOS: RingbackTone). */class Ringback : CallTonePort { private var tone: ToneGenerator? = null override fun play(tone: String) { stop() this.tone = runCatching { ToneGenerator(AudioManager.STREAM_VOICE_CALL, 80) }.getOrNull() this.tone?.startTone(ToneGenerator.TONE_CDMA_NETWORK_USA_RINGBACK) } override fun stop() { tone?.stopTone() tone?.release() tone = null }}/** The main looper's clock. */class MainClock : CallClockPort { private val main = Handler(Looper.getMainLooper()) private val token = Any() override fun after(milliseconds: Long, fire: () -> Unit) { main.postAtTime({ fire() }, token, android.os.SystemClock.uptimeMillis() + milliseconds.coerceAtLeast(0)) } override fun cancelAll() = main.removeCallbacksAndMessages(token)}