Cotton code
446 lines · 20.5 KB · KotlinRaw
package com.cottondb.callingimport android.content.Contextimport android.os.Handlerimport android.os.Looperimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport org.webrtc.AudioTrackimport org.webrtc.Camera2Enumeratorimport org.webrtc.CameraVideoCapturerimport org.webrtc.DataChannelimport org.webrtc.DefaultVideoDecoderFactoryimport org.webrtc.DefaultVideoEncoderFactoryimport org.webrtc.EglBaseimport org.webrtc.IceCandidateimport org.webrtc.MediaConstraintsimport org.webrtc.MediaStreamimport org.webrtc.PeerConnectionimport org.webrtc.PeerConnectionFactoryimport org.webrtc.RtpReceiverimport org.webrtc.RtpTransceiverimport org.webrtc.SdpObserverimport org.webrtc.SessionDescriptionimport org.webrtc.SurfaceTextureHelperimport org.webrtc.VideoSourceimport org.webrtc.VideoTrack/** The call's video tracks, drawn by the in-call screen (iOS: CallVideo). */class CallVideo {    var local by mutableStateOf<VideoTrack?>(null)        internal set    var remote by mutableStateOf<VideoTrack?>(null)        internal set    /** A group call's video, by the room's member id: one tile each. */    val remotes = androidx.compose.runtime.mutableStateMapOf<String, VideoTrack>()}/** * WebRTC's peer, as Cotton Calling uses it one to one (iOS: WebRTCPeer.swift): unified plan, max bundle, the * microphone track and, on a video call, the front camera's 720p30 track; offers, answers, ICE restarts and * candidates handed back through [CallPeerEvents]. Every WebRTC callback comes back to the main thread before it * reaches the engine. A candidate that arrives before the remote description waits for it. */class WebRtcPeer(private val context: Context, private val log: CallLog) : CallPeerPort {    val video = CallVideo()    val egl: EglBase by lazy { EglBase.create() }    private val main = Handler(Looper.getMainLooper())    private val factory: PeerConnectionFactory by lazy {        PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(context.applicationContext).createInitializationOptions())        PeerConnectionFactory.builder()            // The microphone as WebRTC hears it, for Take notes (this phone's own track).            .setAudioDeviceModule(                org.webrtc.audio.JavaAudioDeviceModule.builder(context.applicationContext)                    .setSamplesReadyCallback { samples -> micHeard?.invoke(samples.data, samples.sampleRate, samples.channelCount) }                    .createAudioDeviceModule(),            )            .setVideoEncoderFactory(DefaultVideoEncoderFactory(egl.eglBaseContext, true, true))            .setVideoDecoderFactory(DefaultVideoDecoderFactory(egl.eglBaseContext))            .createPeerConnectionFactory()    }    private var connection: PeerConnection? = null    private var events: CallPeerEvents? = null    private var audioTrack: AudioTrack? = null    private var videoTrack: VideoTrack? = null    private var videoSource: VideoSource? = null    private var capturer: CameraVideoCapturer? = null    private var textures: SurfaceTextureHelper? = null    private var remoteSet = false    private val waiting = mutableListOf<IceCandidate>()    // ── a group call's SFU connection ──    /** The connection goes to the SFU: one transceiver per track, each person's kept apart by its mid. */    private var sfu = false    /** Whose each pulled transceiver is, by mid (the room says it with each offer). */    private val owners = mutableMapOf<String, String>()    /** Each person's own audio track, by member: one stream per person, as Take notes needs. */    val voices = mutableMapOf<String, AudioTrack>()    /** Take notes: this phone's microphone as WebRTC hears it (16-bit PCM, its rate, its channels), while set. */    @Volatile var micHeard: ((ByteArray, Int, Int) -> Unit)? = null    /** A call of two: the other person's voice (peer to peer, one remote track, whose member the room names). */    private var other: AudioTrack? = null    /** [member]'s voice as this phone decodes it, to hear apart (Take notes): theirs on the SFU, the one other on a call of two. */    fun voiceOf(member: String): AudioTrack? = voices[member] ?: other.takeIf { !sfu }    /** SFU ops wait their turn: a description is set only once the one before it is. */    private val queue = ArrayDeque<(() -> Unit) -> Unit>()    private var running = false    private var speakingNow = false    private var loud = 0    private var quiet = 0    override fun create(offerer: Boolean, iceServers: List<CallIceServer>, video: Boolean, events: CallPeerEvents) {        close()        this.events = events        if (!open(iceServers)) return        val made = connection ?: return        val audio = factory.createAudioTrack("audio", factory.createAudioSource(MediaConstraints()))        made.addTrack(audio, listOf("cotton"))        audioTrack = audio        if (video) {            val source = factory.createVideoSource(false)            val track = factory.createVideoTrack("video", source)            made.addTrack(track, listOf("cotton"))            videoSource = source            videoTrack = track            this.video.local = track        }        if (offerer) offer(restart = false)    }    /** The peer connection itself, over these servers; false (and the media failed) when WebRTC makes none. */    private fun open(iceServers: List<CallIceServer>): Boolean {        val servers = iceServers.filter { it.urls.isNotEmpty() }.map { server ->            PeerConnection.IceServer.builder(server.urls).apply {                server.username?.let { setUsername(it) }                server.credential?.let { setPassword(it) }            }.createIceServer()        }        val configuration = PeerConnection.RTCConfiguration(servers).apply {            sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN            bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE            rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE            continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY        }        val made = factory.createPeerConnection(configuration, observer)        if (made == null) {            log.i("calls peer: WebRTC made no peer connection")            events?.media(CallMediaState.Failed)            return false        }        connection = made        return true    }    // ── a group call through the SFU ──    override fun switchToSfu(iceServers: List<CallIceServer>, video: Boolean, events: CallPeerEvents) {        close()        this.events = events        sfu = true        if (!open(iceServers)) return        wantVideo = video        listen()    }    private var wantVideo = false    override fun pushTracks(audio: Boolean, video: Boolean): Unit = turn { done ->        val made = connection ?: return@turn done()        val send = RtpTransceiver.RtpTransceiverInit(RtpTransceiver.RtpTransceiverDirection.SEND_ONLY, listOf("cotton"))        val mic = factory.createAudioTrack("audio", factory.createAudioSource(MediaConstraints()))        mic.setEnabled(audio)        audioTrack = mic        val pushed = mutableListOf<Pair<RtpTransceiver, String>>()        made.addTransceiver(mic, send)?.let { pushed += it to "audio" }        if (wantVideo) {            val source = factory.createVideoSource(false)            val track = factory.createVideoTrack("video", source)            track.setEnabled(video)            videoSource = source            videoTrack = track            this.video.local = track            made.addTransceiver(track, send)?.let { pushed += it to "video" }        }        made.createOffer(object : Sdp() {            override fun onCreateSuccess(description: SessionDescription?) {                val sdp = description?.description ?: return main.post { done() }.let {}                main.post {                    made.setLocalDescription(object : Sdp() {                        override fun onSetSuccess() = main.post {                            if (connection === made) {                                val tracks = pushed.map { (t, kind) -> SfuTrack(t.mid, null, "$kind-${t.mid}", kind) }                                events?.sfu("push", sdp, tracks, null)                            }                            done()                        }.let {}                        override fun onSetFailure(error: String?) = main.post { log.i("calls sfu: own offer refused: $error"); done() }.let {}                    }, SessionDescription(SessionDescription.Type.OFFER, sdp))                }            }            override fun onCreateFailure(error: String?) = main.post { log.i("calls sfu: no offer: $error"); done() }.let {}        }, MediaConstraints())        if (video && wantVideo) startCamera()    }    override fun applySfu(op: String, sdp: String, tracks: List<SfuTrack>): Unit = turn { done ->        val made = connection ?: return@turn done()        val offer = op == "offer"        // The SFU's offer of others' tracks can come before its answer to this phone's own push: it waits its turn.        if (offer && made.signalingState() == PeerConnection.SignalingState.HAVE_LOCAL_OFFER) {            main.postDelayed({ applySfu(op, sdp, tracks) }, 150)            return@turn done()        }        tracks.forEach { t -> if (t.mid != null && t.member != null) owners[t.mid] = t.member }        made.setRemoteDescription(object : Sdp() {            override fun onSetSuccess() = main.post {                if (connection !== made) return@post done()                if (!offer) return@post done()                made.createAnswer(object : Sdp() {                    override fun onCreateSuccess(description: SessionDescription?) {                        val answer = description?.description ?: return main.post { done() }.let {}                        main.post {                            made.setLocalDescription(object : Sdp() {                                override fun onSetSuccess() = main.post {                                    if (connection === made) {                                        events?.sfu("renegotiate", answer, null, null)                                        claim(made)                                    }                                    done()                                }.let {}                                override fun onSetFailure(error: String?) = main.post { log.i("calls sfu: own answer refused: $error"); done() }.let {}                            }, SessionDescription(SessionDescription.Type.ANSWER, answer))                        }                    }                    override fun onCreateFailure(error: String?) = main.post { log.i("calls sfu: no answer: $error"); done() }.let {}                }, MediaConstraints())            }.let {}            override fun onSetFailure(error: String?) = main.post { log.i("calls sfu: the SFU's $op was refused: $error"); done() }.let {}        }, SessionDescription(if (offer) SessionDescription.Type.OFFER else SessionDescription.Type.ANSWER, sdp))    }    /** Every pulled transceiver's track, kept as its person's (their video for the tile, their voice apart). */    private fun claim(made: PeerConnection) {        for (t in made.transceivers) {            val mid = t.mid ?: continue            val member = owners[mid] ?: continue            when (val track = t.receiver.track()) {                is VideoTrack -> video.remotes[member] = track                is AudioTrack -> voices[member] = track                else -> {}            }        }    }    override fun closeTracks(member: String) {        video.remotes.remove(member)        voices.remove(member)        val mids = owners.filterValues { it == member }.keys.toList()        mids.forEach { owners.remove(it) }        if (mids.isNotEmpty()) events?.sfu("close", null, null, mids)    }    /** One SFU op at a time: [work] calls its `done` once its descriptions are set. */    private fun turn(work: (() -> Unit) -> Unit) {        queue.addLast(work)        if (!running) next()    }    private fun next() {        val work = queue.removeFirstOrNull() ?: run { running = false; return }        running = true        work { main.post { next() } }    }    /** This phone's own voice, from the microphone's level, said on a change (on after two loud looks, off after five quiet). */    private fun listen() {        val made = connection ?: return        main.postDelayed({            if (connection !== made || !sfu) return@postDelayed            made.getStats { report ->                val level = report.statsMap.values.firstOrNull { it.type == "media-source" && it.members["kind"] == "audio" }?.members?.get("audioLevel") as? Double ?: 0.0                main.post {                    if (connection !== made) return@post                    val on = audioTrack?.enabled() == true && level > SPEAKING_LEVEL                    if (on) { loud++; quiet = 0 } else { quiet++; loud = 0 }                    if (!speakingNow && loud >= 2) { speakingNow = true; events?.speaking(true) }                    if (speakingNow && quiet >= 5) { speakingNow = false; events?.speaking(false) }                    listen()                }            }        }, 200)    }    companion object {        /** The microphone's audio level (0..1) above which this phone is talking. */        const val SPEAKING_LEVEL = 0.03    }    override fun applyRemote(kind: CallSignalKind, sdp: String) {        val connection = connection ?: return        val type = if (kind == CallSignalKind.Answer) SessionDescription.Type.ANSWER else SessionDescription.Type.OFFER        connection.setRemoteDescription(object : Sdp() {            override fun onSetSuccess() = main.post {                if (this@WebRtcPeer.connection !== connection) return@post                remoteSet = true                waiting.forEach { connection.addIceCandidate(it) }                waiting.clear()                if (kind != CallSignalKind.Answer) answer()            }.let {}            override fun onSetFailure(error: String?) = log.i("calls peer: the remote description was refused: $error")        }, SessionDescription(type, sdp))    }    override fun addCandidate(candidate: String, mid: String?, mline: Int?) {        val ice = IceCandidate(mid ?: "", mline ?: 0, candidate)        if (!remoteSet) waiting += ice else connection?.addIceCandidate(ice)    }    override fun restartIce() {        // On the SFU the connection restarts itself by a fresh push of its offer (`sfu renegotiate`).        if (sfu) return restartSfu()        offer(restart = true)    }    /** The SFU keeps its side of the connection; this phone's ICE gathers on by itself (continual gathering). */    private fun restartSfu() = log.i("calls sfu: the connection dropped; ICE gathers again by itself")    override fun close() {        stopCamera()        connection?.dispose()        connection = null        audioTrack = null        videoTrack = null        videoSource?.dispose()        videoSource = null        textures?.dispose()        textures = null        video.local = null        video.remote = null        video.remotes.clear()        voices.clear()        other = null        owners.clear()        queue.clear()        running = false        sfu = false        speakingNow = false        loud = 0        quiet = 0        events = null        remoteSet = false        waiting.clear()    }    override fun setSending(audio: Boolean, video: Boolean) {        audioTrack?.setEnabled(audio)        videoTrack?.setEnabled(video)        if (video && capturer == null && videoTrack != null) startCamera()        if (!video) stopCamera()    }    override fun startCamera() {        val source = videoSource ?: return        if (capturer != null) return        val cameras = Camera2Enumerator(context)        val front = cameras.deviceNames.firstOrNull { cameras.isFrontFacing(it) } ?: cameras.deviceNames.firstOrNull() ?: return        val made = cameras.createCapturer(front, null) ?: return        val helper = SurfaceTextureHelper.create("cotton-camera", egl.eglBaseContext)        made.initialize(helper, context, source.capturerObserver)        runCatching { made.startCapture(1280, 720, 30) }.onFailure { log.i("calls peer: the camera did not start: $it") }        capturer = made        textures = helper    }    override fun flipCamera() {        capturer?.switchCamera(null)    }    override fun stopCamera() {        capturer?.let { runCatching { it.stopCapture() }; it.dispose() }        capturer = null    }    private fun offer(restart: Boolean) {        val connection = connection ?: return        val constraints = MediaConstraints().apply { if (restart) mandatory += MediaConstraints.KeyValuePair("IceRestart", "true") }        connection.createOffer(object : Sdp() {            override fun onCreateSuccess(description: SessionDescription?) {                val sdp = description?.description ?: return log.i("calls peer: no offer")                main.post { setLocal(connection, SessionDescription.Type.OFFER, sdp, if (restart) CallSignalKind.Restart else CallSignalKind.Offer) }            }            override fun onCreateFailure(error: String?) = log.i("calls peer: no offer: $error")        }, constraints)    }    private fun answer() {        val connection = connection ?: return        connection.createAnswer(object : Sdp() {            override fun onCreateSuccess(description: SessionDescription?) {                val sdp = description?.description ?: return log.i("calls peer: no answer")                main.post { setLocal(connection, SessionDescription.Type.ANSWER, sdp, CallSignalKind.Answer) }            }            override fun onCreateFailure(error: String?) = log.i("calls peer: no answer: $error")        }, MediaConstraints())    }    private fun setLocal(connection: PeerConnection, type: SessionDescription.Type, sdp: String, kind: CallSignalKind) {        if (this.connection !== connection) return        connection.setLocalDescription(object : Sdp() {            override fun onSetSuccess() = main.post { if (this@WebRtcPeer.connection === connection) events?.signal(kind, sdp, null, null, null) }.let {}            override fun onSetFailure(error: String?) = log.i("calls peer: the local description was refused: $error")        }, SessionDescription(type, sdp))    }    private val observer = object : PeerConnection.Observer {        override fun onIceConnectionChange(state: PeerConnection.IceConnectionState?) {            val media = when (state) {                PeerConnection.IceConnectionState.CONNECTED, PeerConnection.IceConnectionState.COMPLETED -> CallMediaState.Connected                PeerConnection.IceConnectionState.DISCONNECTED -> CallMediaState.Disconnected                PeerConnection.IceConnectionState.FAILED -> CallMediaState.Failed                else -> null            } ?: return            main.post { events?.media(media) }        }        override fun onIceCandidate(candidate: IceCandidate?) {            candidate ?: return            main.post { events?.signal(CallSignalKind.Ice, null, candidate.sdp, candidate.sdpMid, candidate.sdpMLineIndex) }        }        override fun onAddTrack(receiver: RtpReceiver?, streams: Array<out MediaStream>?) {            if (sfu) return            when (val track = receiver?.track()) {                is VideoTrack -> main.post { video.remote = track }                is AudioTrack -> main.post { other = track }                else -> {}            }        }        override fun onTrack(transceiver: RtpTransceiver?) {            if (!sfu) return            main.post { connection?.let { claim(it) } }        }        override fun onSignalingChange(state: PeerConnection.SignalingState?) {}        override fun onIceConnectionReceivingChange(receiving: Boolean) {}        override fun onIceGatheringChange(state: PeerConnection.IceGatheringState?) {}        override fun onIceCandidatesRemoved(candidates: Array<out IceCandidate>?) {}        override fun onAddStream(stream: MediaStream?) {}        override fun onRemoveStream(stream: MediaStream?) {}        override fun onDataChannel(channel: DataChannel?) {}        override fun onRenegotiationNeeded() {}    }    /** WebRTC's SDP callbacks, each one a no-op unless overridden. */    private open class Sdp : SdpObserver {        override fun onCreateSuccess(description: SessionDescription?) {}        override fun onSetSuccess() {}        override fun onCreateFailure(error: String?) {}        override fun onSetFailure(error: String?) {}    }}